@wacry/codeks-bridge 0.0.10 → 0.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -14,6 +14,8 @@ npm install -g @wacry/codeks-bridge
14
14
 
15
15
  把[示例配置](examples/config.json)复制到仓库外,填写端点与 API key 环境变量,保留需要的模型。`catalog` 选择受支持的模型,`upstream` 选择连接,`model` 是实际发给上游的部署名;窗口与参数可以覆盖目录默认值。
16
16
 
17
+ GPT 也可使用 ChatGPT 订阅:先运行 `codex login`(已有文件登录可直接复用),再给连接设置 `"auth": { "type": "chatgpt" }`。bridge 自动读取登录凭据和账号 ID、刷新 token,订阅端点可省略。见[订阅配置](docs/config.md#chatgpt-订阅)和[ChatGPT+Claude 示例](examples/chatgpt-claude.json)。
18
+
17
19
  ```sh
18
20
  codeks-bridge serve --config /absolute/path/bridge.json
19
21
  ```
@@ -28,7 +30,7 @@ codeks-bridge config-snippet --config /absolute/path/bridge.json
28
30
 
29
31
  ## 使用边界
30
32
 
31
- - 上游错误保留原始详情交给客户端;bridge 不自动换端点、重试或更换压缩方式。
33
+ - 普通模型错误保留原始详情交给客户端决定重试;ChatGPT 订阅 HTTP 401 最多进行一次鉴权恢复并重发。bridge 不自动换端点或更换压缩方式。
32
34
  - bridge 封装的 reasoning 默认只回放给原目标,原生压缩与 reasoning 的跨目标复用分别配置。无法识别的历史状态默认透传,也可配置[过滤或报错](docs/config.md#未识别的历史状态);实际兼容性由上游决定。
33
35
  - GPT 默认使用 `compaction.mode: "native"`:先做原生加密压缩,需要文字表示时再向原来源复述并缓存。其他模型默认使用标准文字压缩,也可通过 [`compaction.model`](docs/config.md#压缩模式与执行模型) 委托常用 GPT 执行原生压缩,直接复用已有模型配置;见 [GPT+Claude 双模型示例](examples/gpt-claude.json)。
34
36
  - 历史由 codeks 保存;按需复述的成功结果另存本地缓存。封装只是编码,文字 reasoning、摘要及复述配方可读。
package/dist/auth.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  import type { Api, UpstreamConfig } from "./types.ts";
2
- export declare function upstreamHeaders(config: UpstreamConfig, api: Api, signal: AbortSignal, clientHeaders?: Headers): Promise<Headers>;
2
+ export declare function upstreamHeaders(config: UpstreamConfig, api: Api, signal: AbortSignal, clientHeaders?: Headers, fetch?: typeof globalThis.fetch): Promise<Headers>;
package/dist/auth.js CHANGED
@@ -2,8 +2,9 @@ import { execFile } from "node:child_process";
2
2
  import { promisify } from "node:util";
3
3
  import { BridgeError } from "./errors.js";
4
4
  import { forwardRequestHeaders } from "./headers.js";
5
+ import { getChatgptCredentials } from "./chatgpt-auth.js";
5
6
  const execute = promisify(execFile);
6
- export async function upstreamHeaders(config, api, signal, clientHeaders) {
7
+ export async function upstreamHeaders(config, api, signal, clientHeaders, fetch = globalThis.fetch) {
7
8
  const headers = forwardRequestHeaders(clientHeaders, config.auth_header);
8
9
  for (const [name, value] of Object.entries(config.headers ?? {}))
9
10
  headers.set(name, value);
@@ -11,6 +12,12 @@ export async function upstreamHeaders(config, api, signal, clientHeaders) {
11
12
  headers.set("content-type", "application/json");
12
13
  if (api === "anthropic" && !headers.has("anthropic-version"))
13
14
  headers.set("anthropic-version", "2023-06-01");
15
+ if (config.auth?.type === "chatgpt") {
16
+ const credential = await getChatgptCredentials(config.auth, fetch);
17
+ headers.set("authorization", `Bearer ${credential.accessToken}`);
18
+ headers.set("chatgpt-account-id", credential.accountId);
19
+ return headers;
20
+ }
14
21
  let credential;
15
22
  if (config.api_key_env) {
16
23
  credential = process.env[config.api_key_env]?.trim();
@@ -0,0 +1,12 @@
1
+ export declare const CHATGPT_BASE_URL = "https://chatgpt.com/backend-api/codex";
2
+ export interface ChatgptAuthConfig {
3
+ type: "chatgpt";
4
+ codex_home?: string;
5
+ }
6
+ export interface ChatgptCredentials {
7
+ accessToken: string;
8
+ accountId: string;
9
+ }
10
+ export declare function getChatgptCredentials(auth: ChatgptAuthConfig, fetch?: typeof globalThis.fetch): Promise<ChatgptCredentials>;
11
+ /** Recover one rejected request, without refreshing credentials another caller already replaced. */
12
+ export declare function refreshChatgptCredentials(auth: ChatgptAuthConfig, rejected: ChatgptCredentials, fetch?: typeof globalThis.fetch): Promise<ChatgptCredentials>;
@@ -0,0 +1,195 @@
1
+ import { open, readFile, realpath, rename, unlink } from "node:fs/promises";
2
+ import { randomUUID } from "node:crypto";
3
+ import { homedir } from "node:os";
4
+ import { join, resolve } from "node:path";
5
+ import { BridgeError } from "./errors.js";
6
+ export const CHATGPT_BASE_URL = "https://chatgpt.com/backend-api/codex";
7
+ const DEFAULT_ISSUER = "https://auth.openai.com";
8
+ const DEFAULT_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
9
+ const LOGIN = 'Run codex -c \'cli_auth_credentials_store="file"\' login with the same CODEX_HOME.';
10
+ const locks = new Map();
11
+ const object = (value) => !!value && typeof value === "object" && !Array.isArray(value);
12
+ const text = (value) => typeof value === "string" && !!value.trim() && !/[\r\n]/.test(value);
13
+ const loginError = (message) => new BridgeError(`${message} ${LOGIN}`, "invalid_api_key", 401);
14
+ const changedLogin = () => loginError("ChatGPT login changed during authentication. Retry with the selected account.");
15
+ async function authPath(auth) {
16
+ const home = auth.codex_home ?? (process.env.CODEX_HOME?.trim() || join(homedir(), ".codex"));
17
+ // Preserve shared-file symlinks and serialize aliases of the same credential file.
18
+ try {
19
+ return await realpath(join(resolve(home), "auth.json"));
20
+ }
21
+ catch {
22
+ throw loginError("Cannot read ChatGPT file credentials from auth.json.");
23
+ }
24
+ }
25
+ async function readSnapshot(path) {
26
+ let document;
27
+ try {
28
+ document = JSON.parse(await readFile(path, "utf8"));
29
+ }
30
+ catch {
31
+ throw loginError("Cannot read ChatGPT file credentials from auth.json.");
32
+ }
33
+ const mode = document?.auth_mode ?? (document?.OPENAI_API_KEY != null || document?.personal_access_token != null ||
34
+ document?.bedrock_api_key != null || document?.bedrock_access_keys != null ? "other" : "chatgpt");
35
+ const tokens = document?.tokens;
36
+ if (!object(document) || mode !== "chatgpt" || !object(tokens) || !text(tokens.access_token) || !text(tokens.account_id)) {
37
+ throw loginError("auth.json must contain a ChatGPT login with an access token and selected account ID.");
38
+ }
39
+ return { document, tokens, credentials: { accessToken: tokens.access_token, accountId: tokens.account_id } };
40
+ }
41
+ /** JWT claims are scheduling hints; the saved account ID remains authoritative. */
42
+ function claims(token) {
43
+ if (typeof token !== "string")
44
+ return;
45
+ try {
46
+ const parts = token.split(".");
47
+ const payload = parts.length === 3 ? JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8")) : undefined;
48
+ return object(payload) ? payload : undefined;
49
+ }
50
+ catch {
51
+ return;
52
+ }
53
+ }
54
+ function refreshReason(snapshot) {
55
+ const exp = claims(snapshot.tokens.access_token)?.exp;
56
+ if (typeof exp === "number" && Number.isFinite(exp)) {
57
+ return exp * 1000 <= Date.now() + 5 * 60_000 ? "proactive_expiry" : undefined;
58
+ }
59
+ const refreshed = Date.parse(snapshot.document.last_refresh);
60
+ return Number.isFinite(refreshed) && refreshed < Date.now() - 8 * 86_400_000 ? "scheduled" : undefined;
61
+ }
62
+ async function locked(path, action) {
63
+ const previous = locks.get(path) ?? Promise.resolve();
64
+ let release;
65
+ const gate = new Promise(done => { release = done; });
66
+ const current = previous.then(() => gate);
67
+ locks.set(path, current);
68
+ await previous;
69
+ try {
70
+ return await action();
71
+ }
72
+ finally {
73
+ release();
74
+ if (locks.get(path) === current)
75
+ locks.delete(path);
76
+ }
77
+ }
78
+ function sameLogin(left, right) {
79
+ return left.credentials.accountId === right.credentials.accountId &&
80
+ left.tokens.login_owner_id === right.tokens.login_owner_id &&
81
+ claims(left.tokens.id_token)?.["https://api.openai.com/auth"]?.chatgpt_user_id ===
82
+ claims(right.tokens.id_token)?.["https://api.openai.com/auth"]?.chatgpt_user_id;
83
+ }
84
+ function authority(tokens) {
85
+ const provenance = tokens.oauth_provenance ?? { issuer: DEFAULT_ISSUER, client_id: DEFAULT_CLIENT_ID };
86
+ if (!object(provenance) || !text(provenance.issuer) || !text(provenance.client_id)) {
87
+ throw loginError("ChatGPT OAuth provenance is invalid.");
88
+ }
89
+ let issuer;
90
+ try {
91
+ issuer = new URL(provenance.issuer);
92
+ }
93
+ catch {
94
+ throw loginError("ChatGPT OAuth issuer is invalid.");
95
+ }
96
+ if (!["https:", "http:"].includes(issuer.protocol) || issuer.username || issuer.password || issuer.search || issuer.hash) {
97
+ throw loginError("ChatGPT OAuth issuer is invalid.");
98
+ }
99
+ return { issuer: provenance.issuer.replace(/\/+$/, ""), client_id: provenance.client_id };
100
+ }
101
+ async function save(path, document) {
102
+ const temporary = `${path}.bridge-${randomUUID()}.tmp`;
103
+ try {
104
+ const file = await open(temporary, "wx", 0o600);
105
+ try {
106
+ await file.writeFile(JSON.stringify(document, null, 2) + "\n");
107
+ await file.sync();
108
+ }
109
+ finally {
110
+ await file.close();
111
+ }
112
+ await rename(temporary, path);
113
+ }
114
+ catch {
115
+ throw new BridgeError("Cannot save refreshed ChatGPT credentials. Check auth.json directory permissions before retrying.", "invalid_prompt", 500);
116
+ }
117
+ finally {
118
+ await unlink(temporary).catch(() => { });
119
+ }
120
+ }
121
+ async function refresh(path, snapshot, reason, fetch) {
122
+ if (!text(snapshot.tokens.refresh_token))
123
+ throw loginError("ChatGPT credentials have no refresh token.");
124
+ const provenance = authority(snapshot.tokens);
125
+ let response;
126
+ try {
127
+ // Refresh tokens rotate. Finish and persist even if the inference request is canceled.
128
+ response = await fetch(`${provenance.issuer}/oauth/token`, {
129
+ method: "POST", headers: { "content-type": "application/json" }, redirect: "error",
130
+ signal: AbortSignal.timeout(30_000),
131
+ body: JSON.stringify({ grant_type: "refresh_token", client_id: provenance.client_id,
132
+ refresh_token: snapshot.tokens.refresh_token, refresh_reason: reason }),
133
+ });
134
+ }
135
+ catch {
136
+ throw new BridgeError("ChatGPT token refresh request failed.", "upstream_error", 502);
137
+ }
138
+ if (!response.ok) {
139
+ await response.body?.cancel().catch(() => { });
140
+ // OAuth error bodies can contain credentials; do not forward or capture them.
141
+ if (response.status === 400 || response.status === 401 || response.status === 403) {
142
+ throw loginError(`ChatGPT token refresh was rejected (HTTP ${response.status}).`);
143
+ }
144
+ throw new BridgeError(`ChatGPT token refresh failed (HTTP ${response.status}).`, "upstream_error", response.status);
145
+ }
146
+ let result;
147
+ try {
148
+ result = await response.json();
149
+ }
150
+ catch {
151
+ throw new BridgeError("ChatGPT token refresh returned invalid JSON.", "upstream_error", 502);
152
+ }
153
+ if (!object(result) || !text(result.access_token) || ["id_token", "refresh_token"].some(key => result[key] != null && !text(result[key])) || (result.id_token != null && !claims(result.id_token))) {
154
+ throw new BridgeError("ChatGPT token refresh returned invalid credentials.", "upstream_error", 502);
155
+ }
156
+ const current = await readSnapshot(path);
157
+ if (!sameLogin(snapshot, current))
158
+ throw changedLogin();
159
+ if (current.tokens.access_token !== snapshot.tokens.access_token || current.tokens.refresh_token !== snapshot.tokens.refresh_token ||
160
+ JSON.stringify(current.tokens.oauth_provenance) !== JSON.stringify(snapshot.tokens.oauth_provenance)) {
161
+ return current.credentials;
162
+ }
163
+ const tokens = { ...current.tokens, access_token: result.access_token,
164
+ oauth_provenance: current.tokens.oauth_provenance ?? provenance };
165
+ for (const key of ["id_token", "refresh_token"])
166
+ if (result[key] != null)
167
+ tokens[key] = result[key];
168
+ await save(path, { ...current.document, tokens, last_refresh: new Date().toISOString() });
169
+ return { accessToken: tokens.access_token, accountId: tokens.account_id };
170
+ }
171
+ export async function getChatgptCredentials(auth, fetch = globalThis.fetch) {
172
+ const path = await authPath(auth);
173
+ const initial = await readSnapshot(path);
174
+ if (!refreshReason(initial))
175
+ return initial.credentials;
176
+ return locked(path, async () => {
177
+ const current = await readSnapshot(path);
178
+ if (!sameLogin(initial, current))
179
+ throw changedLogin();
180
+ const reason = refreshReason(current);
181
+ return reason ? refresh(path, current, reason, fetch) : current.credentials;
182
+ });
183
+ }
184
+ /** Recover one rejected request, without refreshing credentials another caller already replaced. */
185
+ export async function refreshChatgptCredentials(auth, rejected, fetch = globalThis.fetch) {
186
+ const path = await authPath(auth);
187
+ return locked(path, async () => {
188
+ const current = await readSnapshot(path);
189
+ if (current.credentials.accountId !== rejected.accountId)
190
+ throw changedLogin();
191
+ if (current.credentials.accessToken !== rejected.accessToken)
192
+ return current.credentials;
193
+ return refresh(path, current, "unauthorized_recovery", fetch);
194
+ });
195
+ }
package/dist/config.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import type { BridgeConfig, ResolvedModel } from "./types.ts";
1
+ import type { BridgeConfig, ResolvedModel, UpstreamConfig } from "./types.ts";
2
+ export declare function upstreamBaseUrl(upstream: UpstreamConfig): string;
2
3
  export declare function validateConfig(value: unknown): BridgeConfig;
3
4
  export declare function loadConfig(path: string): Promise<BridgeConfig>;
4
5
  export declare function resolveModel(config: BridgeConfig, slug: string): ResolvedModel;
package/dist/config.js CHANGED
@@ -4,6 +4,7 @@ import { modelProfile } from "./profiles.js";
4
4
  import { getCatalogEntry } from "./model-catalog.js";
5
5
  import { BridgeError } from "./errors.js";
6
6
  import { validateAdapterConfig } from "./adapter-options.js";
7
+ import { CHATGPT_BASE_URL } from "./chatgpt-auth.js";
7
8
  function object(value) {
8
9
  return !!value && typeof value === "object" && !Array.isArray(value);
9
10
  }
@@ -12,9 +13,15 @@ function strings(value) {
12
13
  return Array.isArray(value) && value.every(v => typeof v === "string" && v.length > 0);
13
14
  }
14
15
  const hash = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
16
+ export function upstreamBaseUrl(upstream) {
17
+ const url = upstream.base_url ?? (upstream.auth?.type === "chatgpt" ? CHATGPT_BASE_URL : undefined);
18
+ if (!url)
19
+ fail("upstream base_url is required");
20
+ return url;
21
+ }
15
22
  /** Record provenance, never policy or credentials, in portable history. */
16
23
  function origin(config, model) {
17
- const connection = hash([model.upstream, config.upstreams[model.upstream].base_url.replace(/\/+$/, "")]);
24
+ const connection = hash([model.upstream, upstreamBaseUrl(config.upstreams[model.upstream]).replace(/\/+$/, "")]);
18
25
  const { adapter } = getCatalogEntry(model.catalog);
19
26
  return { connection, model: model.model, adapter, id: hash([connection, adapter, model.model]) };
20
27
  }
@@ -45,9 +52,19 @@ export function validateConfig(value) {
45
52
  for (const [name, up] of Object.entries(value.upstreams)) {
46
53
  if (!object(up))
47
54
  fail(`upstream ${name}: expected a connection object`);
55
+ if (up.auth !== undefined) {
56
+ if (!object(up.auth) || up.auth.type !== "chatgpt")
57
+ fail(`upstream ${name}: auth.type must be chatgpt`);
58
+ if (Object.keys(up.auth).some(key => !["type", "codex_home"].includes(key)))
59
+ fail(`upstream ${name}: unknown ChatGPT auth option`);
60
+ if (up.auth.codex_home !== undefined && (typeof up.auth.codex_home !== "string" || !up.auth.codex_home.trim()))
61
+ fail(`upstream ${name}: auth.codex_home must be a nonempty path`);
62
+ if ([up.api_key_env, up.api_key_command, up.auth_header].some(value => value !== undefined))
63
+ fail(`upstream ${name}: ChatGPT auth cannot be combined with api_key_env, api_key_command or auth_header`);
64
+ }
48
65
  let url;
49
66
  try {
50
- url = new URL(up.base_url);
67
+ url = new URL(upstreamBaseUrl(up));
51
68
  }
52
69
  catch {
53
70
  fail(`upstream ${name}: invalid base_url`);
@@ -1,5 +1,5 @@
1
1
  import { decodeCompaction, decodeReasoning } from "../carrier.js";
2
- import { resolveModel } from "../config.js";
2
+ import { resolveModel, upstreamBaseUrl } from "../config.js";
3
3
  import { replaysReasoning, restoresNativeCompaction } from "../history.js";
4
4
  /** Splits timed text into SSE events. An event takes the time of the part that completed it. */
5
5
  export function sseEvents(parts, finished = true) {
@@ -189,7 +189,7 @@ function routeView(inspector, route, responsesLite) {
189
189
  adapter: route.profile.id,
190
190
  api: route.profile.api,
191
191
  upstream: route.config.upstream,
192
- base_url: route.upstream.base_url,
192
+ base_url: upstreamBaseUrl(route.upstream),
193
193
  upstream_model: route.config.model,
194
194
  origin_id: route.origin.id,
195
195
  reasoning_format: route.profile.reasoning_format,
package/dist/types.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { ResponseWriter, Usage } from "./writer.ts";
2
+ import type { ChatgptAuthConfig } from "./chatgpt-auth.ts";
2
3
  export type Api = "responses" | "anthropic" | "chat";
3
4
  export type AdapterId = "gpt-responses" | "claude-messages" | "deepseek-chat";
4
5
  export type UnrecognizedStatePolicy = "passthrough" | "drop" | "error";
@@ -11,7 +12,9 @@ export interface AdapterConfig {
11
12
  "claude-messages"?: Partial<ClaudeMessagesOptions>;
12
13
  }
13
14
  export interface UpstreamConfig {
14
- base_url: string;
15
+ /** ChatGPT subscription auth supplies its native endpoint by default. */
16
+ base_url?: string;
17
+ auth?: ChatgptAuthConfig;
15
18
  api_key_env?: string;
16
19
  /** An argv array. The command writes a short-lived credential to stdout. */
17
20
  api_key_command?: string[];
@@ -115,7 +118,7 @@ export interface ResponsesRequest {
115
118
  [key: string]: any;
116
119
  }
117
120
  export interface BridgeServerOptions {
118
- /** Used by every upstream call, including compaction and handoffs. */
121
+ /** Used by all model calls and ChatGPT token refreshes. */
119
122
  fetch?: typeof globalThis.fetch;
120
123
  /** Runs once before routing. Return a replacement or change the request in place. */
121
124
  transformRequest?: (request: ResponsesRequest, context: {
@@ -1,3 +1,3 @@
1
1
  import type { ResolvedModel } from "./types.ts";
2
2
  /** base_url includes any API version prefix; path is appended, never resolved from /. */
3
- export declare function upstreamFetch(route: ResolvedModel, path: string, body: unknown, signal: AbortSignal, requestHeaders?: Headers, protocolHeaders?: Record<string, string | string[]>, fetch?: typeof globalThis.fetch): Promise<Response>;
3
+ export declare function upstreamFetch(route: ResolvedModel, path: string, body: unknown, signal: AbortSignal, requestHeaders?: Headers, protocolHeaders?: Record<string, string | string[]>, fetch?: typeof globalThis.fetch, recoverAuth?: boolean): Promise<Response>;
package/dist/upstream.js CHANGED
@@ -1,10 +1,14 @@
1
1
  import { upstreamHeaders } from "./auth.js";
2
2
  import { BridgeError, transportError, upstreamError, UpstreamHttpError } from "./errors.js";
3
3
  import { captureUpstream } from "./inspect/capture.js";
4
+ import { upstreamBaseUrl } from "./config.js";
5
+ import { refreshChatgptCredentials } from "./chatgpt-auth.js";
4
6
  /** base_url includes any API version prefix; path is appended, never resolved from /. */
5
- export async function upstreamFetch(route, path, body, signal, requestHeaders, protocolHeaders, fetch = globalThis.fetch) {
6
- const url = route.upstream.base_url.replace(/\/+$/, "") + "/" + path.replace(/^\/+/, "");
7
- const headers = await upstreamHeaders(route.upstream, route.profile.api, signal, requestHeaders);
7
+ export async function upstreamFetch(route, path, body, signal, requestHeaders, protocolHeaders, fetch = globalThis.fetch, recoverAuth = true) {
8
+ signal.throwIfAborted();
9
+ const url = upstreamBaseUrl(route.upstream).replace(/\/+$/, "") + "/" + path.replace(/^\/+/, "");
10
+ const headers = await upstreamHeaders(route.upstream, route.profile.api, signal, requestHeaders, fetch);
11
+ signal.throwIfAborted();
8
12
  for (const [name, value] of Object.entries(protocolHeaders ?? {})) {
9
13
  // A protocol may require additional comma-separated feature flags without
10
14
  // replacing the endpoint's configured flags. Scalar headers still replace.
@@ -82,6 +86,15 @@ export async function upstreamFetch(route, path, body, signal, requestHeaders, p
82
86
  const text = await response.text();
83
87
  if (combined.aborted)
84
88
  throw combined.reason;
89
+ if (response.status === 401 && recoverAuth && route.upstream.auth?.type === "chatgpt") {
90
+ // Authentication recovery only: no stream has been accepted, and model
91
+ // failures keep the client's existing retry policy.
92
+ await refreshChatgptCredentials(route.upstream.auth, {
93
+ accessToken: headers.get("authorization").slice("Bearer ".length),
94
+ accountId: headers.get("chatgpt-account-id"),
95
+ }, fetch);
96
+ return upstreamFetch(route, path, body, signal, requestHeaders, protocolHeaders, fetch, false);
97
+ }
85
98
  if (route.profile.api === "responses")
86
99
  throw new UpstreamHttpError(response.status, text, response.headers);
87
100
  let payload = text;
@@ -2,6 +2,20 @@
2
2
 
3
3
  模型选择 GPT 目录 key,例如 `catalog: "gpt-6.1-sol"`,条目指定 `gpt-responses` adapter,bridge 向连接的 `/responses` 发请求。`base_url` 包含版本前缀,例如 `https://api.openai.com/v1`。实际模型名可以是任意部署别名,转换不依赖名称前缀。
4
4
 
5
+ ## 订阅凭据与续期
6
+
7
+ 连接设置 `auth: { "type": "chatgpt" }` 时,默认使用 `https://chatgpt.com/backend-api/codex`;请求体、Lite、原生压缩与 handoff 继续使用同一个 Responses adapter。登录与目录选择见[订阅配置](config.md#chatgpt-订阅)。
8
+
9
+ 凭据处理以 Codex `rust-v0.164.0` 的 [AuthManager](https://github.com/openai/codex/blob/rust-v0.164.0/codex-rs/login/src/auth/manager.rs) 和 [TokenData](https://github.com/openai/codex/blob/rust-v0.164.0/codex-rs/login/src/token_data.rs) 为依据:每请求重新读取文件,token 与 `tokens.account_id` 来自同一快照。JWT 的 `exp` 只用于决定刷新时机:剩余不超过 5 分钟时刷新;没有可用 `exp` 时,参考 `last_refresh` 的 8 天周期。账号 ID 不从 access token 推断。
10
+
11
+ 刷新使用保存的 `oauth_provenance.issuer` 和 `client_id`,旧记录使用 Codex 默认 OAuth 来源。成功后保留原记录及未知字段,更新返回的 token 和 `last_refresh`,通过权限为 `0600` 的临时文件原子替换原文件。轮换后的 refresh token 必须成功写回,写入失败会报错。刷新错误不会把 OAuth 响应正文或凭据回传客户端。
12
+
13
+ 同一 bridge 进程按登录文件串行处理刷新,拿锁后重新读文件,其他请求已经更新 token 时直接复用。保存前核对登录记录,避免覆盖刷新期间发生的重新登录或账号切换。这不是与所有 codeks 或 bridge 进程共享的刷新锁;不要把进程内去重理解为跨进程互斥。
14
+
15
+ 模型请求收到 HTTP 401 时,bridge 允许一次鉴权恢复:先重新读取凭据,仍是被拒绝的 token 才刷新,再重发相同请求。此时下游 SSE 尚未开始;再次 401 原样交给 codeks,不循环刷新。其他 HTTP、流内或传输错误继续交给客户端处理。
16
+
17
+ OAuth 刷新发出后使用独立的 30 秒超时,即使原推理请求取消,也继续接收并保存轮换结果,避免丢失下一代 refresh token;取消的模型请求不会继续重发。OAuth 交换不进入 inspector 的请求正文捕获,模型的 401 与重发仍分别记录,鉴权 header 沿用现有脱敏。
18
+
5
19
  ## 请求与参数
6
20
 
7
21
  普通 Responses 参数、namespace 和 custom grammar 工具保留原始格式,包括未知扩展字段;请求及响应 header 按 [HTTP 边界](responses-stream.md#header-与转发边界) 默认透传。模型名替换为配置的实际名称,reasoning effort 使用 profile 默认值和配置映射。`max_output_tokens` 优先使用请求值,再使用模型默认值。
@@ -20,7 +34,7 @@ bridge 能识别的历史 reasoning 按允许来源选择,将 `responses.reaso
20
34
 
21
35
  `end_turn` 有显式值时遵从上游,否则有工具调用时返回 false。成功响应的 input/output usage 必须是有效计数,cache read/write、reasoning 分项有则记录;reasoning 不重复叠加到 input。无效 usage 作为错误返回,避免影响 codeks 压缩判断。`response.incomplete` 原样保留原因与可用 usage,由客户端处理继续生成、内容过滤或截断,不统一改成可重试错误。
22
36
 
23
- 上游成功响应头到达前,不建立下游 SSE。HTTP 失败保留原始 status、body 和诊断 header;流内错误保留完整 error 对象,不维护 GPT code 白名单。被允许的密文遭拒也直接返回,不自动过滤后重试。[错误结构](responses-stream.md)
37
+ 上游成功响应头到达前,不建立下游 SSE。除上述订阅 401 鉴权恢复外,HTTP 失败保留原始 status、body 和诊断 header;流内错误保留完整 error 对象,不维护 GPT code 白名单。被允许的密文遭拒也直接返回,不自动过滤后重试。[错误结构](responses-stream.md)
24
38
 
25
39
  ## 原生压缩
26
40
 
package/docs/config.md CHANGED
@@ -60,7 +60,8 @@
60
60
 
61
61
  | 字段 | 含义 |
62
62
  | --- | --- |
63
- | `base_url` | 包含版本前缀的 HTTP(S) URL;adapter 在其后追加请求路径 |
63
+ | `base_url` | 包含版本前缀的 HTTP(S) URL;adapter 在其后追加请求路径;ChatGPT 订阅鉴权可省略,使用订阅端点 |
64
+ | `auth` | `{"type":"chatgpt"}` 使用 codeks 的文件登录凭据;可选 `codex_home` 指定登录目录 |
64
65
  | `api_key_env` | API key 环境变量名称 |
65
66
  | `api_key_command` | 与 `api_key_env` 二选一;argv 数组,程序 stdout 返回当前凭据 |
66
67
  | `auth_header` | 覆盖鉴权 header 名;默认 GPT/DeepSeek 用 `authorization: Bearer …`,Claude 用 `x-api-key` |
@@ -72,6 +73,37 @@
72
73
 
73
74
  `api_key_command` 不经过 shell,每条上游请求执行一次,最多 30 秒,适合短期凭据。命令错误不会把 stdout/stderr 回传客户端。连接无需 key 的服务时可省略凭据设置。Claude 默认版本 header 为 `anthropic-version: 2023-06-01`。客户端 metadata 默认透传,鉴权使用上游配置;覆盖顺序及必要过滤见 [header 边界](responses-stream.md#header-与转发边界)。
74
75
 
76
+ ### ChatGPT 订阅
77
+
78
+ 先用 codeks 登录 ChatGPT,默认使用文件存储:
79
+
80
+ ```sh
81
+ codex login
82
+ ```
83
+
84
+ 远程或无浏览器的机器可使用 `login --device-auth`。已有有效的文件登录可以直接复用。bridge 读取 `auth.codex_home` 指定目录中的 `auth.json`;省略时依次使用 bridge 进程的 `CODEX_HOME`、`~/.codex`。自定义目录须与登录时的 `CODEX_HOME` 一致,例如:
85
+
86
+ ```json
87
+ {
88
+ "upstreams": {
89
+ "chatgpt": {
90
+ "auth": { "type": "chatgpt", "codex_home": "/absolute/path/to/codex-home" }
91
+ }
92
+ },
93
+ "models": {
94
+ "gpt": { "upstream": "chatgpt", "catalog": "gpt-6.1-sol", "model": "gpt-6.1-sol" }
95
+ }
96
+ }
97
+ ```
98
+
99
+ 使用默认登录目录时只需 `"auth": { "type": "chatgpt" }`。默认 `base_url` 为 `https://chatgpt.com/backend-api/codex`,显式值可覆盖。`auth` 与 `api_key_env`、`api_key_command`、`auth_header` 互斥;API key 连接继续使用原有配置。完整的[ChatGPT+Claude 示例](../examples/chatgpt-claude.json)可同时使用订阅和 Anthropic API key。
100
+
101
+ 无需复制 access token、refresh token 或账号 ID。每次请求从同一份登录记录读取 token 与所选账号,写入 `Authorization` 和 `ChatGPT-Account-ID`,覆盖同名客户端及静态 header。登录文件中的 `tokens.account_id` 是权威值,不能用 JWT 中的账号声明代替用户选择的 workspace。重新登录或切换账号后,后续请求会读取新记录;显式换账号也可能改变上游对已有历史密文的接受范围。
102
+
103
+ bridge 使用文件存储,不读取系统 keyring。如果曾将 `cli_auth_credentials_store` 改为 `keyring` 或 `auto`,可运行 `codex -c 'cli_auth_credentials_store="file"' login` 明确保存文件登录;默认配置不需要这个参数。缺少登录、凭据失效或刷新写回失败会明确报错。它不会从 API key 登录或其他存储中猜测一份备用凭据。
104
+
105
+ token 临近过期时自动续期并写回原文件;HTTP 401 可触发一次鉴权恢复,再重发尚未被接受的请求。普通模型错误的重试仍由 codeks 控制。具体刷新、并发与取消边界见 [GPT 订阅鉴权](backends-responses.md#订阅凭据与续期)。
106
+
75
107
  ## 模型
76
108
 
77
109
  | 字段 | 含义 |
package/docs/design.md CHANGED
@@ -46,6 +46,12 @@ Lite 仍调用 `/responses` 并返回 Responses SSE。完整工具 schema 位于
46
46
 
47
47
  底层 Chat 负责消息、工具、图片和 SSE;DeepSeek 方言只负责 thinking 参数、reasoning 字段和 usage。新增方言时复用稳定的协议部分,把差异留在对应 adapter。协议相同的模型版本可共用 adapter,参数差异先在新的目录条目中表达;真正改变载荷结构时再增加转换代码和格式版本。当前实现三类 adapter,不为尚未接入的模型维护空接口或版本矩阵。
48
48
 
49
+ ## 订阅鉴权复用文件登录
50
+
51
+ ChatGPT 订阅鉴权放在连接层,由 `auth.type: "chatgpt"` 显式启用。用户继续使用 `codex login`,bridge 复用其默认文件存储,在发送请求时从同一快照取得 token 与所选账号并处理续期。它不改模型目录、协议 adapter 或历史载荷,也不要求新增 codeks 补丁。API key 连接保留原来的环境变量和命令接口。
52
+
53
+ 选择文件存储,是为了保持零依赖及一致的跨平台行为。系统 keyring 有多套平台和后端实现,单独复制其中一套无法完整复用 codeks;现有 app-server `getAuthStatus` 已弃用,且不返回同一快照的账号 ID,依赖它还会引入额外进程和生命周期。明确的文件登录比这些隐含依赖更易维护。若以后需要完整支持其他存储,优先评估 codeks 提供稳定的原子凭据导出接口,再决定是否替换这层实现。[配置与刷新边界](backends-responses.md#订阅凭据与续期)
54
+
49
55
  ## 历史保存事实,配置决定恢复
50
56
 
51
57
  Reasoning 载荷记录来源、格式和原始数据;压缩载荷保存文字摘要及可选原生状态,或保存原生状态与按需复述配方。它们写入 Responses item 的 `encrypted_content`,由 codeks 原样持久化。bridge 不维护完整会话或响应 ID 索引;按需复述的成功结果及独立 usage 另存本地文件缓存,避免重复付费和服务重启后重复生成。
@@ -68,7 +74,7 @@ bridge 检查自身必须维持的不变量:配置引用存在、历史能转
68
74
 
69
75
  Claude 默认主动请求服务端对前缀失配 thinking 使用 `drop_block`,保留其余可接受的块。这是已配置的请求策略,不是在收到错误后重试或改写已存历史。它允许流式故障后的部分回答继续工作,但丢失 reasoning 仍可能影响质量或增加重新推理的开销,不能视作无损。检查器展示上游实际报告的丢弃位置和原因,区分 bridge 的来源过滤与服务端判断。协议与恢复时序见 [Claude Messages](backends-anthropic.md#失配策略与故障续接)。
70
76
 
71
- GPT 原生 HTTP 失败保留 status、body 和诊断 header,流内失败保留 error 对象。下游 HTTP 200 推迟到上游接受请求后,避免把 HTTP 失败变成 SSE 错误而改变 codeks 的重试判断;等待响应头期间没有 keepalive,是这一选择的明确代价。Claude/DeepSeek 只在协议转换边界映射错误分类。重试和退避由客户端控制,bridge 不叠加第二层重试。详见 [Responses 流](responses-stream.md)。
77
+ GPT 原生 HTTP 失败保留 status、body 和诊断 header,流内失败保留 error 对象。下游 HTTP 200 推迟到上游接受请求后,避免把 HTTP 失败变成 SSE 错误而改变 codeks 的重试判断;等待响应头期间没有 keepalive,是这一选择的明确代价。Claude/DeepSeek 只在协议转换边界映射错误分类。普通模型请求的重试和退避由客户端控制;ChatGPT 订阅仅在尚未开始下游 SSE 的 HTTP 401 上进行一次鉴权恢复,之后失败照常返回。详见 [Responses 流](responses-stream.md)。
72
78
 
73
79
  ## 压缩的生成和恢复分开
74
80
 
@@ -84,7 +90,7 @@ GPT 原生 HTTP 失败保留 status、body 和诊断 header,流内失败保留
84
90
 
85
91
  ## 调试捕获只观察
86
92
 
87
- [检查器](inspect.md)记录 bridge 真正收发的字节,不重新构造请求。入口请求在解析前保存原文;所有上游请求都经过 `upstreamFetch`,在这里保存实际发送的 JSON 和逐块到达的响应;写回 codeks 的内容在 `writeHead`/`write`/`end` 处记录。每条请求在 AsyncLocalStorage 中持有自己的记录,上游调用按用途附加 `main`、`summary`、`native` 或 `handoff` 标签,因此并发会话和子代理不会混在一起,后端代码不需要传递捕获参数。需要生成文字摘要时,`handoff` 先完成,再执行目标调用;命中摘要缓存时没有辅助上游调用。客户端响应只报告对应 main、summary 或 native 调用的 usage;handoff 用量留在缓存与独立上游记录,避免把辅助消耗当作客户端当前上下文。
93
+ [检查器](inspect.md)记录 bridge 真正收发的模型请求字节,不重新构造请求。入口请求在解析前保存原文;所有模型上游请求都经过 `upstreamFetch`,在这里保存实际发送的 JSON 和逐块到达的响应;写回 codeks 的内容在 `writeHead`/`write`/`end` 处记录。每条请求在 AsyncLocalStorage 中持有自己的记录,上游调用按用途附加 `main`、`summary`、`native` 或 `handoff` 标签,因此并发会话和子代理不会混在一起,后端代码不需要传递捕获参数。需要生成文字摘要时,`handoff` 先完成,再执行目标调用;命中摘要缓存时没有辅助上游调用。客户端响应只报告对应 main、summary 或 native 调用的 usage;handoff 用量留在缓存与独立上游记录,避免把辅助消耗当作客户端当前上下文。OAuth 刷新正文含凭据,不进入模型调用捕获;401 与其后的模型重发分别保留记录。
88
94
 
89
95
  服务端保存完整正文,折叠、截断和格式化都在页面完成,避免字段白名单遗漏协议新增内容。状态标注调用与 `prepareHistory` 相同的回放判断函数,显示的决定不会与实际转换分叉。页面是零依赖的静态文件,和运行时一样不引入第三方包。捕获关闭时不保存任何内容,每条请求只多一个 AsyncLocalStorage 作用域。
90
96
 
package/docs/embedding.md CHANGED
@@ -27,10 +27,12 @@ server.listen(8123, "127.0.0.1");
27
27
  | 选项 | 调用边界 |
28
28
  | --- | --- |
29
29
  | `transformRequest(request, { headers })` | 入口鉴权与 JSON 解析之后、模型路由和历史转换之前,主请求调用一次。可原位修改并返回 `void`,也可返回替换请求,支持 Promise。`headers` 是该请求的 HTTP headers。辅助压缩和按需复述不会再次调用它。 |
30
- | `fetch` | 与标准 `fetch` 签名相同,承接全部模型请求,包括压缩、委托压缩及按需复述。可接入宿主的代理、凭据和传输策略;须保留传入的取消信号并返回标准 `Response`。 |
30
+ | `fetch` | 与标准 `fetch` 签名相同,承接全部模型请求,包括压缩、委托压缩及按需复述,以及已启用的 ChatGPT OAuth 刷新。可接入宿主的代理、凭据和传输策略;须保留每次调用传入的取消信号并返回标准 `Response`。 |
31
31
  | `onResponseEvent(request, event)` | 同步观察主响应实际提交的标准 Responses 事件;`request` 是变换后的请求。缓冲后因失败丢弃的工具事件、辅助请求和 keepalive 不进入观察器。JSON 请求也产生同样的语义事件,其中每个已提交输出项有一次 `response.output_item.done`。 |
32
32
 
33
- 观察器应只读取参数,不修改请求或事件,也不返回 Promise。它在事件写出后同步执行;抛出的异常会进入现有请求错误处理,并停止该请求的后续观察,已经写出的事件无法撤回。如果交付终止错误时观察器自身抛错,bridge 关闭当前响应连接,不再尝试发送第二个错误;其他请求仍可继续。请求结束时取消仍在进行的上游调用,重试由客户端或宿主决定。原始上游帧及辅助调用的调试使用[检查器](inspect.md)。
33
+ 观察器应只读取参数,不修改请求或事件,也不返回 Promise。它在事件写出后同步执行;抛出的异常会进入现有请求错误处理,并停止该请求的后续观察,已经写出的事件无法撤回。如果交付终止错误时观察器自身抛错,bridge 关闭当前响应连接,不再尝试发送第二个错误;其他请求仍可继续。请求结束时取消仍在进行的模型调用,普通重试由客户端或宿主决定。原始上游帧及辅助调用的调试使用[检查器](inspect.md)。
34
+
35
+ 启用 ChatGPT 鉴权后,OAuth 刷新使用独立的 30 秒取消信号;宿主应保留这个信号,而非强行替换成原模型请求的信号。刷新正文含 refresh token,不应作为普通模型请求记录;bridge 的 inspector 不捕获它。模型 HTTP 401 最多在鉴权恢复后重发一次,尚未建立下游 SSE;取消的模型请求不会因刷新完成而恢复。详见[订阅凭据与续期](backends-responses.md#订阅凭据与续期)。
34
36
 
35
37
  宿主可通过 `AsyncLocalStorage` 在请求处理作用域中保存自己的关联信息,供 fetch 与观察器读取。bridge 不要求特定宿主元数据格式,也不管理宿主的重试。
36
38
 
@@ -67,9 +67,9 @@ HTTP 失败发生在建立下游流之前,响应体使用顶层 `error`,Retr
67
67
  | 无效输入、鉴权或权限错误 | `invalid_prompt` |
68
68
  | 断流、传输等其他失败 | `stream_error` 或 `upstream_error` |
69
69
 
70
- 原始错误体保留厂商 code/type 和其他诊断。这个转换表只适用于非 Responses 上游,不用于改写 GPT 原生错误。网络错误保留可用的原因链。缺少凭据、凭据命令失败、输出为空或多行均返回 HTTP 400 + `invalid_prompt`,保持原本的终止语义;命令的 stdout/stderr 不外传。
70
+ 原始错误体保留厂商 code/type 和其他诊断。这个转换表只适用于非 Responses 上游,不用于改写 GPT 原生错误。网络错误保留可用的原因链。API key 连接缺少凭据、凭据命令失败、输出为空或多行均返回 HTTP 400 + `invalid_prompt`,保持原本的终止语义;命令的 stdout/stderr 不外传。ChatGPT 文件登录缺失或失效返回 HTTP 401 + `invalid_api_key`,并提示重新登录。
71
71
 
72
- bridge 不重试、不替换端点,也不因错误移除 reasoning、关闭 thinking 或改用文字压缩。客户端决定重试预算和退避。下游取消会取消当前相关上游请求,包括正在进行的原生压缩或复述;尚未开始的后续步骤不会执行。
72
+ 普通模型错误的重试预算和退避由客户端决定;bridge 不替换端点,也不因错误移除 reasoning、关闭 thinking 或改用文字压缩。ChatGPT 订阅 HTTP 401 在下游 SSE 开始前最多进行一次鉴权恢复并重发,再次失败照常返回。下游取消会取消当前相关模型请求,包括正在进行的原生压缩或复述;尚未开始的后续步骤不会执行。已经发出的 OAuth 刷新使用独立的 30 秒超时完成并保存轮换凭据,避免取消推理时丢失新的 refresh token;它不会恢复已取消的模型请求。[鉴权边界](backends-responses.md#订阅凭据与续期)
73
73
 
74
74
  ## Usage
75
75
 
@@ -87,4 +87,4 @@ GPT 保留原始 usage,包括提供的 cache write 等分项;DeepSeek 使用
87
87
 
88
88
  按需复述的等待可能覆盖完整的辅助推理,客户端空闲超时应足以容纳该等待。
89
89
 
90
- 上游响应体空闲超时由 `upstreams.<id>.stream_idle_timeout_ms` 控制,默认 300 秒,也覆盖读取错误体。只有上游字节重置它,下游 keepalive 不延长它。等待响应头的时限由 `headers_timeout_ms` 控制,省略时沿用响应体空闲时限;收到响应头后重新开始响应体计时。任一字段设为 `null` 可禁用对应阶段的时限;两者均省略时保留原来的 300 秒行为。宿主已有传输重试或超时策略时,可据此分开配置,bridge 本身仍不重试。
90
+ 上游响应体空闲超时由 `upstreams.<id>.stream_idle_timeout_ms` 控制,默认 300 秒,也覆盖读取错误体。只有上游字节重置它,下游 keepalive 不延长它。等待响应头的时限由 `headers_timeout_ms` 控制,省略时沿用响应体空闲时限;收到响应头后重新开始响应体计时。任一字段设为 `null` 可禁用对应阶段的时限;两者均省略时保留原来的 300 秒行为。宿主已有传输重试或超时策略时,可据此分开配置;这些超时不会触发 bridge 自动重试,也不改变订阅 OAuth 刷新的独立时限。
@@ -0,0 +1,25 @@
1
+ {
2
+ "host": "127.0.0.1",
3
+ "port": 8787,
4
+ "upstreams": {
5
+ "chatgpt": {
6
+ "auth": { "type": "chatgpt" }
7
+ },
8
+ "anthropic": {
9
+ "base_url": "https://api.anthropic.com/v1",
10
+ "api_key_env": "ANTHROPIC_API_KEY"
11
+ }
12
+ },
13
+ "models": {
14
+ "gpt": {
15
+ "catalog": "gpt-6.1-sol",
16
+ "upstream": "chatgpt",
17
+ "model": "gpt-6.1-sol"
18
+ },
19
+ "claude": {
20
+ "catalog": "claude-sonnet-5-5",
21
+ "upstream": "anthropic",
22
+ "model": "claude-sonnet-5-5"
23
+ }
24
+ }
25
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wacry/codeks-bridge",
3
- "version": "0.0.10",
3
+ "version": "0.0.11",
4
4
  "description": "Configurable local Responses API bridge for codeks with GPT, Claude Messages, and DeepSeek Chat adapters.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "David Zhang",