-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
180 lines (164 loc) · 6.78 KB
/
Copy pathworker.js
File metadata and controls
180 lines (164 loc) · 6.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
/**
* CodingPlan API Proxy Worker
*
* Features:
* - OpenAI-compatible /v1/models and /v1/chat/completions
* - KV-backed token storage and JSON refresh-token flow
* - /health, /status, /usage, /claim and /refresh helpers
* - 429 retry with Retry-After support
*/
const UPSTREAM = "https://api.gitcode.com/api/v5";
const OAUTH_REFRESH = "https://acs.atomgit.com/oauth/refresh";
const UA = "atomcode/4.25.7";
const MODEL_MAP = {
"deepseek-v4-flash": "deepseek-ai/DeepSeek-V4-Flash",
"deepseek-v4": "deepseek-ai/DeepSeek-V4-Flash",
"deepseek-r1": "deepseek-ai/DeepSeek-R1",
"qwen-vl": "Qwen/Qwen3-VL-8B-Instruct",
"qwen3-vl": "Qwen/Qwen3-VL-8B-Instruct",
"qwen3-vl-8b": "Qwen/Qwen3-VL-8B-Instruct",
"glm-5": "GLM-5.2",
"GLM-5.2": "GLM-5.2",
};
const KV_TOKEN = "access_token";
const KV_REFRESH = "refresh_token";
const KV_EXPIRES = "expires_at";
const CORS = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "*",
};
function json(data, init = {}) {
return Response.json(data, { ...init, headers: { ...CORS, ...(init.headers || {}) } });
}
async function loadTokens(env) {
const envToken = env.CODINGPLAN_TOKEN || "";
const envRefresh = env.CODINGPLAN_REFRESH || "";
const envExpires = env.CODINGPLAN_EXPIRES_AT || "0";
if (!env.CODINGPLAN_KV) {
return { token: envToken, refresh: envRefresh, expires: envExpires };
}
const [token, refresh, expires] = await Promise.all([
env.CODINGPLAN_KV.get(KV_TOKEN),
env.CODINGPLAN_KV.get(KV_REFRESH),
env.CODINGPLAN_KV.get(KV_EXPIRES),
]);
return {
token: token || envToken,
refresh: refresh || envRefresh,
expires: expires || envExpires,
};
}
async function saveTokens(env, tokens) {
if (!env.CODINGPLAN_KV) return;
await Promise.all([
env.CODINGPLAN_KV.put(KV_TOKEN, tokens.token),
env.CODINGPLAN_KV.put(KV_REFRESH, tokens.refresh),
env.CODINGPLAN_KV.put(KV_EXPIRES, String(tokens.expires_at)),
]);
}
function needsRefresh(expiresAt) {
const value = parseInt(expiresAt || "0", 10);
return value > 0 && Date.now() > value - 24 * 3600 * 1000;
}
async function refreshTokens(env, force = false) {
const tokens = await loadTokens(env);
if (!tokens.refresh) return tokens;
if (!force && !needsRefresh(tokens.expires)) return tokens;
const resp = await fetch(OAUTH_REFRESH, {
method: "POST",
headers: { "User-Agent": UA, "Content-Type": "application/json" },
body: JSON.stringify({ refresh_token: tokens.refresh }),
});
if (!resp.ok) return tokens;
const data = await resp.json();
const fresh = {
token: data.access_token || tokens.token,
refresh: data.refresh_token || tokens.refresh,
expires_at: Date.now() + (data.expires_in || 604800) * 1000,
};
await saveTokens(env, fresh);
return { token: fresh.token, refresh: fresh.refresh, expires: String(fresh.expires_at) };
}
function summarizeStatus(status) {
const usage = status.current_usage || {};
const window = (status.rate_limit_windows || [])[0] || {};
const plan = status.codingplan_free || {};
return {
plan_name: plan.plan_name || status.plan_type,
plan_type: status.plan_type,
expires_at: status.expires_at || plan.expires_at,
window_hours: usage.window_hours || window.window_hours,
window_limit: usage.window_token_limit || window.call_limit,
used: usage.window_tokens_used || window.calls_used,
usage_percent: usage.usage_percent || window.usage_percent,
reset_at: usage.reset_at_display || window.reset_at_display,
quota_exhausted: status.window_quota_exhausted || window.quota_exhausted,
};
}
async function upstream(path, token, init = {}) {
return fetch(`${UPSTREAM}${path}`, {
...init,
headers: {
Authorization: `Bearer ${token}`,
"User-Agent": UA,
"Content-Type": "application/json",
...(init.headers || {}),
},
});
}
async function withRetry(fn, retries = 3) {
let last;
for (let attempt = 0; attempt <= retries; attempt++) {
last = await fn();
if (last.status !== 429 || attempt === retries) return last;
const retryAfter = parseFloat(last.headers.get("Retry-After") || "");
const waitMs = Number.isFinite(retryAfter) ? retryAfter * 1000 : Math.min(2 ** attempt * 1000, 8000);
await new Promise((resolve) => setTimeout(resolve, waitMs));
}
return last;
}
export default {
async fetch(request, env) {
const url = new URL(request.url);
if (request.method === "OPTIONS") return new Response(null, { headers: CORS });
const tokens = await refreshTokens(env);
const token = tokens.token;
if (url.pathname === "/" || url.pathname === "/health") {
return json({ status: "ok", service: "CodingPlan Worker Proxy", authenticated: Boolean(token), token_expires_at: tokens.expires || "0" });
}
if (url.pathname === "/v1/models") {
return json({ object: "list", data: Object.keys(MODEL_MAP).map((id) => ({ id, object: "model", created: 0, owned_by: "codingplan" })) });
}
if (url.pathname === "/status" || url.pathname === "/usage") {
if (!token) return json({ error: "no auth token" }, { status: 401 });
const resp = await upstream("/coding-plan/status", token);
const data = await resp.json();
return json({ summary: summarizeStatus(data), raw: data }, { status: resp.status });
}
if (url.pathname === "/refresh" && request.method === "POST") {
const fresh = await refreshTokens(env, true);
return json({ refreshed: Boolean(fresh.token), token_expires_at: fresh.expires || "0" });
}
if (url.pathname === "/claim" && request.method === "POST") {
if (!token) return json({ error: "no auth token" }, { status: 401 });
const body = await request.json().catch(() => ({}));
const plan = body.plan_type || body.plan || "Pro";
const resp = await upstream("/coding-plan/claim-v2", token, { method: "POST", body: JSON.stringify({ plan_type: plan }) });
return new Response(resp.body, { status: resp.status, headers: { ...CORS, "Content-Type": "application/json" } });
}
if (url.pathname === "/v1/chat/completions" && request.method === "POST") {
if (!token) return json({ error: "no auth token" }, { status: 401 });
const body = await request.json();
body.model = MODEL_MAP[body.model] || body.model;
const resp = await withRetry(() => upstream("/chat/completions", token, { method: "POST", body: JSON.stringify(body), headers: { Accept: body.stream ? "text/event-stream" : "application/json" } }));
const headers = new Headers(resp.headers);
Object.entries(CORS).forEach(([key, value]) => headers.set(key, value));
return new Response(resp.body, { status: resp.status, headers });
}
return json({ error: "not found" }, { status: 404 });
},
async scheduled(event, env) {
await refreshTokens(env, true);
},
};