scope-agent-workbench 0.2.0 → 0.2.3

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.
Files changed (88) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/bridge/agent-email-relay.mjs +160 -160
  3. package/bridge/app-server-websocket-transport.mjs +219 -219
  4. package/bridge/archive/service.mjs +130 -130
  5. package/bridge/auth-profile-failover.mjs +58 -58
  6. package/bridge/auth-profile-manager.mjs +215 -215
  7. package/bridge/capacity-recovery.mjs +90 -90
  8. package/bridge/gpu-usage-history.mjs +322 -322
  9. package/bridge/local/history.mjs +20 -5
  10. package/bridge/plugins/aliyun-dlc/monitor.mjs +236 -236
  11. package/bridge/plugins/aliyun-dlc/probe.mjs +701 -701
  12. package/bridge/private-gateway.mjs +371 -371
  13. package/bridge/private-start.mjs +22 -22
  14. package/bridge/probes/app-server-handoff-probe.mjs +87 -87
  15. package/bridge/probes/app-server-writer-probe.mjs +69 -69
  16. package/bridge/probes/assistant-search-probe.mjs +321 -321
  17. package/bridge/probes/dialogue-probe.mjs +462 -462
  18. package/bridge/probes/history-probe.mjs +430 -345
  19. package/bridge/probes/new-session-preflight.mjs +14 -14
  20. package/bridge/probes/profile-cancel-probe.mjs +17 -17
  21. package/bridge/probes/profile-delete-probe.mjs +26 -26
  22. package/bridge/probes/profile-list-probe.mjs +114 -114
  23. package/bridge/probes/profile-write-probe.mjs +109 -109
  24. package/bridge/probes/raw-context-probe.mjs +51 -51
  25. package/bridge/probes/remote-probe.mjs +627 -626
  26. package/bridge/probes/submission-probe.mjs +2 -2
  27. package/bridge/probes/takeover-probe.mjs +326 -326
  28. package/bridge/probes/vscode-open-preflight.mjs +21 -21
  29. package/bridge/providers/claude-interactive.py +463 -341
  30. package/bridge/providers/cli-command.mjs +103 -103
  31. package/bridge/providers/conversations.mjs +231 -231
  32. package/bridge/providers/native-commands.py +38 -38
  33. package/bridge/providers/native-session-state.mjs +14 -14
  34. package/bridge/providers/native-session-state.py +96 -96
  35. package/bridge/providers/remote-job.py +130 -130
  36. package/bridge/remote-app-server-command.mjs +121 -121
  37. package/bridge/remote-directory-listing.mjs +148 -148
  38. package/bridge/rollout-summary.mjs +20 -2
  39. package/bridge/routes/dialogue.mjs +48 -3
  40. package/bridge/routes/models.mjs +312 -312
  41. package/bridge/server.mjs +3357 -3332
  42. package/bridge/session-attachments.mjs +150 -150
  43. package/bridge/session-catalog/agy-history.py +141 -2
  44. package/bridge/session-catalog/catalog.mjs +17 -0
  45. package/bridge/session-catalog/probe.py +1207 -331
  46. package/bridge/session-catalog/routes.mjs +6 -0
  47. package/bridge/start.mjs +205 -205
  48. package/bridge/state-persistence.mjs +9 -1
  49. package/bridge/tmux-session-control.mjs +29 -29
  50. package/bridge/vscode-opener.mjs +157 -157
  51. package/bridge/web-terminal.mjs +52 -52
  52. package/bridge/workbench/manager-context.mjs +51 -51
  53. package/bridge/workbench/service.mjs +301 -301
  54. package/dist/client/.vite/manifest.json +4 -4
  55. package/dist/client/assets/{index-Enu1x0PS.js → index-BMior55c.js} +2 -2
  56. package/dist/client/assets/{layout-segment-context-CmJzExWq.js → layout-segment-context-DjGudgXn.js} +1 -1
  57. package/dist/client/assets/page-CJqXlhDs.js +551 -0
  58. package/dist/client/assets/page-LYzRz6_S.css +1 -0
  59. package/dist/client/favicon.svg +6 -6
  60. package/dist/server/__vite_rsc_assets_manifest.js +8 -8
  61. package/dist/server/index.js +7 -7
  62. package/dist/server/ssr/__vite_rsc_assets_manifest.js +8 -8
  63. package/dist/server/ssr/assets/{page-CYYyCnKD.js → page-BB9Dri2u.js} +2416 -271
  64. package/dist/server/ssr/assets/page-LYzRz6_S.css +1 -0
  65. package/dist/server/ssr/index.js +1 -1
  66. package/dist/server/ssr/vinext-server.json +1 -1
  67. package/dist/server/vinext-server.json +1 -1
  68. package/dist/server/wrangler.json +1 -1
  69. package/lib/browser-snapshot-cache.js +53 -53
  70. package/lib/formula-preview.js +1 -1
  71. package/lib/incremental-snapshot.js +300 -300
  72. package/lib/markdown-math.js +151 -151
  73. package/lib/remote-links.js +95 -95
  74. package/lib/runtime-config.js +70 -70
  75. package/lib/session-filters.js +38 -38
  76. package/lib/ssh-config.js +26 -26
  77. package/lib/stable-order.js +39 -39
  78. package/lib/subagent-display-prefs.ts +130 -0
  79. package/package.json +1 -1
  80. package/scripts/agent-email-relay.mjs +104 -104
  81. package/scripts/email-notification-cli.mjs +28 -28
  82. package/scripts/enable-private-access.ps1 +109 -109
  83. package/scripts/fixtures/native-conversations.mjs +164 -6
  84. package/scripts/fixtures/workbench-conversations.mjs +475 -352
  85. package/scripts/preview-workbench.mjs +669 -669
  86. package/dist/client/assets/page-COBv6VWj.css +0 -1
  87. package/dist/client/assets/page-DVjU6VG_.js +0 -550
  88. package/dist/server/ssr/assets/page-COBv6VWj.css +0 -1
@@ -1,215 +1,215 @@
1
- import { randomUUID } from "node:crypto";
2
- import { JsonlAppServerConnection } from "./app-server-client.mjs";
3
-
4
- const PROFILE_NAME_PATTERN = /^[\p{L}\p{N}][\p{L}\p{N} ._-]{0,47}$/u;
5
-
6
- export function normalizeProfileName(value) {
7
- const name = String(value || "").trim().replace(/\s+/g, " ");
8
- if (!PROFILE_NAME_PATTERN.test(name)) {
9
- throw new Error("Profile 名称需为 1–48 个字母、数字、空格、点、下划线或短横线");
10
- }
11
- const slug = name
12
- .normalize("NFKD")
13
- .replace(/[^a-zA-Z0-9._-]+/g, "-")
14
- .replace(/^-+|-+$/g, "")
15
- .slice(0, 48);
16
- return { name, slug: slug || `profile-${randomUUID().slice(0, 8)}` };
17
- }
18
-
19
- export function publicAccount(accountResponse) {
20
- const account = accountResponse?.account;
21
- if (!account || typeof account !== "object") return null;
22
- if (account.type === "chatgpt") {
23
- return {
24
- type: "chatgpt",
25
- email: typeof account.email === "string" ? account.email.slice(0, 320) : "",
26
- planType:
27
- typeof account.planType === "string" ? account.planType.slice(0, 80) : "unknown",
28
- };
29
- }
30
- if (["apiKey", "amazonBedrock"].includes(account.type)) {
31
- return { type: account.type, email: "", planType: "" };
32
- }
33
- return null;
34
- }
35
-
36
- export class AuthProfileManager {
37
- constructor({
38
- spawnConnection,
39
- prepareProfile,
40
- finalizeProfile,
41
- cancelProfile,
42
- requestTimeoutMs = 45_000,
43
- now = () => Date.now(),
44
- }) {
45
- this.spawnConnection = spawnConnection;
46
- this.prepareProfile = prepareProfile;
47
- this.finalizeProfile = finalizeProfile;
48
- this.cancelProfile = cancelProfile;
49
- this.requestTimeoutMs = requestTimeoutMs;
50
- this.now = now;
51
- this.jobs = new Map();
52
- }
53
-
54
- async start({ host, executable = "codex", profileName }) {
55
- const profile = normalizeProfileName(profileName);
56
- const existing = Array.from(this.jobs.values()).find(
57
- (job) =>
58
- job.host === host &&
59
- job.profile.slug === profile.slug &&
60
- ["starting", "waiting"].includes(job.status),
61
- );
62
- if (existing) return this.publicJob(existing);
63
-
64
- await this.prepareProfile(host, profile);
65
- const job = {
66
- id: randomUUID(),
67
- host,
68
- profile,
69
- status: "starting",
70
- verificationUrl: "",
71
- userCode: "",
72
- loginId: "",
73
- error: null,
74
- account: null,
75
- startedAt: new Date(this.now()).toISOString(),
76
- completedAt: null,
77
- connection: null,
78
- };
79
- this.jobs.set(job.id, job);
80
-
81
- try {
82
- const child = this.spawnConnection({ host, executable, profile });
83
- const connection = new JsonlAppServerConnection({
84
- host: `${host}:${profile.slug}`,
85
- child,
86
- requestTimeoutMs: this.requestTimeoutMs,
87
- now: this.now,
88
- });
89
- job.connection = connection;
90
- connection.on("notification", (message) => {
91
- if (
92
- message.method === "account/login/completed" &&
93
- (!message.params?.loginId || message.params.loginId === job.loginId)
94
- ) {
95
- this.#complete(job, message.params).catch((error) =>
96
- this.#fail(job, error),
97
- );
98
- }
99
- });
100
- connection.on("close", (error) => {
101
- if (["starting", "waiting"].includes(job.status)) this.#fail(job, error);
102
- });
103
- await connection.start();
104
- const login = await connection.request("account/login/start", {
105
- type: "chatgptDeviceCode",
106
- });
107
- if (
108
- login?.type !== "chatgptDeviceCode" ||
109
- !login.loginId ||
110
- !login.userCode ||
111
- !login.verificationUrl
112
- ) {
113
- throw new Error("远端 Codex 未返回完整的 device auth 信息");
114
- }
115
- let verificationUrl;
116
- try {
117
- verificationUrl = new URL(String(login.verificationUrl));
118
- } catch {
119
- throw new Error("远端 Codex 返回的 device auth URL 无效");
120
- }
121
- if (verificationUrl.protocol !== "https:") {
122
- throw new Error("远端 Codex 返回了非 HTTPS 的 device auth URL");
123
- }
124
- job.loginId = String(login.loginId);
125
- job.userCode = String(login.userCode);
126
- job.verificationUrl = verificationUrl.toString();
127
- job.status = "waiting";
128
- return this.publicJob(job);
129
- } catch (error) {
130
- this.#fail(job, error);
131
- throw error;
132
- }
133
- }
134
-
135
- get(id) {
136
- const job = this.jobs.get(String(id || ""));
137
- return job ? this.publicJob(job) : null;
138
- }
139
-
140
- async cancel(id) {
141
- const job = this.jobs.get(String(id || ""));
142
- if (!job) throw new Error("找不到这条登录任务");
143
- if (["completed", "failed", "cancelled"].includes(job.status)) {
144
- return this.publicJob(job);
145
- }
146
- try {
147
- if (job.loginId && job.connection && !job.connection.closed) {
148
- await job.connection.request("account/login/cancel", {
149
- loginId: job.loginId,
150
- });
151
- }
152
- } finally {
153
- job.status = "cancelled";
154
- job.completedAt = new Date(this.now()).toISOString();
155
- job.connection?.close();
156
- job.connection = null;
157
- await this.cancelProfile?.(job.host, job.profile).catch(() => {});
158
- }
159
- return this.publicJob(job);
160
- }
161
-
162
- async cancelForProfile(host, slug) {
163
- const matches = Array.from(this.jobs.values()).filter(
164
- (job) =>
165
- job.host === host &&
166
- job.profile.slug === slug &&
167
- ["starting", "waiting"].includes(job.status),
168
- );
169
- for (const job of matches) await this.cancel(job.id);
170
- return matches.length;
171
- }
172
-
173
- publicJob(job) {
174
- return {
175
- id: job.id,
176
- host: job.host,
177
- profile: { ...job.profile },
178
- status: job.status,
179
- verificationUrl: job.verificationUrl,
180
- userCode: job.userCode,
181
- error: job.error,
182
- account: job.account,
183
- startedAt: job.startedAt,
184
- completedAt: job.completedAt,
185
- };
186
- }
187
-
188
- close() {
189
- for (const job of this.jobs.values()) job.connection?.close();
190
- }
191
-
192
- async #complete(job, result) {
193
- if (!result?.success) {
194
- throw new Error(result?.error || "Device auth 未完成");
195
- }
196
- const response = await job.connection.request("account/read", {
197
- refreshToken: false,
198
- });
199
- job.account = publicAccount(response);
200
- await this.finalizeProfile(job.host, job.profile, job.account);
201
- job.status = "completed";
202
- job.completedAt = new Date(this.now()).toISOString();
203
- job.connection.close();
204
- job.connection = null;
205
- }
206
-
207
- #fail(job, error) {
208
- if (["completed", "cancelled", "failed"].includes(job.status)) return;
209
- job.status = "failed";
210
- job.error = error instanceof Error ? error.message : String(error || "登录失败");
211
- job.completedAt = new Date(this.now()).toISOString();
212
- job.connection?.close();
213
- job.connection = null;
214
- }
215
- }
1
+ import { randomUUID } from "node:crypto";
2
+ import { JsonlAppServerConnection } from "./app-server-client.mjs";
3
+
4
+ const PROFILE_NAME_PATTERN = /^[\p{L}\p{N}][\p{L}\p{N} ._-]{0,47}$/u;
5
+
6
+ export function normalizeProfileName(value) {
7
+ const name = String(value || "").trim().replace(/\s+/g, " ");
8
+ if (!PROFILE_NAME_PATTERN.test(name)) {
9
+ throw new Error("Profile 名称需为 1–48 个字母、数字、空格、点、下划线或短横线");
10
+ }
11
+ const slug = name
12
+ .normalize("NFKD")
13
+ .replace(/[^a-zA-Z0-9._-]+/g, "-")
14
+ .replace(/^-+|-+$/g, "")
15
+ .slice(0, 48);
16
+ return { name, slug: slug || `profile-${randomUUID().slice(0, 8)}` };
17
+ }
18
+
19
+ export function publicAccount(accountResponse) {
20
+ const account = accountResponse?.account;
21
+ if (!account || typeof account !== "object") return null;
22
+ if (account.type === "chatgpt") {
23
+ return {
24
+ type: "chatgpt",
25
+ email: typeof account.email === "string" ? account.email.slice(0, 320) : "",
26
+ planType:
27
+ typeof account.planType === "string" ? account.planType.slice(0, 80) : "unknown",
28
+ };
29
+ }
30
+ if (["apiKey", "amazonBedrock"].includes(account.type)) {
31
+ return { type: account.type, email: "", planType: "" };
32
+ }
33
+ return null;
34
+ }
35
+
36
+ export class AuthProfileManager {
37
+ constructor({
38
+ spawnConnection,
39
+ prepareProfile,
40
+ finalizeProfile,
41
+ cancelProfile,
42
+ requestTimeoutMs = 45_000,
43
+ now = () => Date.now(),
44
+ }) {
45
+ this.spawnConnection = spawnConnection;
46
+ this.prepareProfile = prepareProfile;
47
+ this.finalizeProfile = finalizeProfile;
48
+ this.cancelProfile = cancelProfile;
49
+ this.requestTimeoutMs = requestTimeoutMs;
50
+ this.now = now;
51
+ this.jobs = new Map();
52
+ }
53
+
54
+ async start({ host, executable = "codex", profileName }) {
55
+ const profile = normalizeProfileName(profileName);
56
+ const existing = Array.from(this.jobs.values()).find(
57
+ (job) =>
58
+ job.host === host &&
59
+ job.profile.slug === profile.slug &&
60
+ ["starting", "waiting"].includes(job.status),
61
+ );
62
+ if (existing) return this.publicJob(existing);
63
+
64
+ await this.prepareProfile(host, profile);
65
+ const job = {
66
+ id: randomUUID(),
67
+ host,
68
+ profile,
69
+ status: "starting",
70
+ verificationUrl: "",
71
+ userCode: "",
72
+ loginId: "",
73
+ error: null,
74
+ account: null,
75
+ startedAt: new Date(this.now()).toISOString(),
76
+ completedAt: null,
77
+ connection: null,
78
+ };
79
+ this.jobs.set(job.id, job);
80
+
81
+ try {
82
+ const child = this.spawnConnection({ host, executable, profile });
83
+ const connection = new JsonlAppServerConnection({
84
+ host: `${host}:${profile.slug}`,
85
+ child,
86
+ requestTimeoutMs: this.requestTimeoutMs,
87
+ now: this.now,
88
+ });
89
+ job.connection = connection;
90
+ connection.on("notification", (message) => {
91
+ if (
92
+ message.method === "account/login/completed" &&
93
+ (!message.params?.loginId || message.params.loginId === job.loginId)
94
+ ) {
95
+ this.#complete(job, message.params).catch((error) =>
96
+ this.#fail(job, error),
97
+ );
98
+ }
99
+ });
100
+ connection.on("close", (error) => {
101
+ if (["starting", "waiting"].includes(job.status)) this.#fail(job, error);
102
+ });
103
+ await connection.start();
104
+ const login = await connection.request("account/login/start", {
105
+ type: "chatgptDeviceCode",
106
+ });
107
+ if (
108
+ login?.type !== "chatgptDeviceCode" ||
109
+ !login.loginId ||
110
+ !login.userCode ||
111
+ !login.verificationUrl
112
+ ) {
113
+ throw new Error("远端 Codex 未返回完整的 device auth 信息");
114
+ }
115
+ let verificationUrl;
116
+ try {
117
+ verificationUrl = new URL(String(login.verificationUrl));
118
+ } catch {
119
+ throw new Error("远端 Codex 返回的 device auth URL 无效");
120
+ }
121
+ if (verificationUrl.protocol !== "https:") {
122
+ throw new Error("远端 Codex 返回了非 HTTPS 的 device auth URL");
123
+ }
124
+ job.loginId = String(login.loginId);
125
+ job.userCode = String(login.userCode);
126
+ job.verificationUrl = verificationUrl.toString();
127
+ job.status = "waiting";
128
+ return this.publicJob(job);
129
+ } catch (error) {
130
+ this.#fail(job, error);
131
+ throw error;
132
+ }
133
+ }
134
+
135
+ get(id) {
136
+ const job = this.jobs.get(String(id || ""));
137
+ return job ? this.publicJob(job) : null;
138
+ }
139
+
140
+ async cancel(id) {
141
+ const job = this.jobs.get(String(id || ""));
142
+ if (!job) throw new Error("找不到这条登录任务");
143
+ if (["completed", "failed", "cancelled"].includes(job.status)) {
144
+ return this.publicJob(job);
145
+ }
146
+ try {
147
+ if (job.loginId && job.connection && !job.connection.closed) {
148
+ await job.connection.request("account/login/cancel", {
149
+ loginId: job.loginId,
150
+ });
151
+ }
152
+ } finally {
153
+ job.status = "cancelled";
154
+ job.completedAt = new Date(this.now()).toISOString();
155
+ job.connection?.close();
156
+ job.connection = null;
157
+ await this.cancelProfile?.(job.host, job.profile).catch(() => {});
158
+ }
159
+ return this.publicJob(job);
160
+ }
161
+
162
+ async cancelForProfile(host, slug) {
163
+ const matches = Array.from(this.jobs.values()).filter(
164
+ (job) =>
165
+ job.host === host &&
166
+ job.profile.slug === slug &&
167
+ ["starting", "waiting"].includes(job.status),
168
+ );
169
+ for (const job of matches) await this.cancel(job.id);
170
+ return matches.length;
171
+ }
172
+
173
+ publicJob(job) {
174
+ return {
175
+ id: job.id,
176
+ host: job.host,
177
+ profile: { ...job.profile },
178
+ status: job.status,
179
+ verificationUrl: job.verificationUrl,
180
+ userCode: job.userCode,
181
+ error: job.error,
182
+ account: job.account,
183
+ startedAt: job.startedAt,
184
+ completedAt: job.completedAt,
185
+ };
186
+ }
187
+
188
+ close() {
189
+ for (const job of this.jobs.values()) job.connection?.close();
190
+ }
191
+
192
+ async #complete(job, result) {
193
+ if (!result?.success) {
194
+ throw new Error(result?.error || "Device auth 未完成");
195
+ }
196
+ const response = await job.connection.request("account/read", {
197
+ refreshToken: false,
198
+ });
199
+ job.account = publicAccount(response);
200
+ await this.finalizeProfile(job.host, job.profile, job.account);
201
+ job.status = "completed";
202
+ job.completedAt = new Date(this.now()).toISOString();
203
+ job.connection.close();
204
+ job.connection = null;
205
+ }
206
+
207
+ #fail(job, error) {
208
+ if (["completed", "cancelled", "failed"].includes(job.status)) return;
209
+ job.status = "failed";
210
+ job.error = error instanceof Error ? error.message : String(error || "登录失败");
211
+ job.completedAt = new Date(this.now()).toISOString();
212
+ job.connection?.close();
213
+ job.connection = null;
214
+ }
215
+ }
@@ -1,90 +1,90 @@
1
- export const CAPACITY_CONTINUE_PROMPT = "继续";
2
-
3
- export const DEFAULT_CAPACITY_RETRY_DELAYS_MS = Object.freeze([
4
- 3_000,
5
- 10_000,
6
- 30_000,
7
- 60_000,
8
- 120_000,
9
- ]);
10
-
11
- const MODEL_CAPACITY_PATTERN = /selected model is(?: currently)? at capacity/i;
12
- // Codex occasionally accepts a turn and then receives an edge/backend error
13
- // from its own Responses endpoint. Limit retries to this exact endpoint and
14
- // retryable statuses; ordinary 404s from a user's command are never retried.
15
- const TRANSIENT_CODEX_BACKEND_PATTERN =
16
- /unexpected status\s+(?:404|408|429|500|502|503|504)\b[\s\S]{0,1000}chatgpt\.com\/backend-api\/codex\/responses/i;
17
-
18
- export function errorText(value, limit = 30_000) {
19
- const parts = [];
20
- const seen = new Set();
21
-
22
- function visit(candidate, depth) {
23
- if (parts.join("\n").length >= limit || depth > 6 || candidate == null) {
24
- return;
25
- }
26
- if (typeof candidate === "string") {
27
- if (candidate) parts.push(candidate);
28
- return;
29
- }
30
- if (["number", "boolean", "bigint"].includes(typeof candidate)) {
31
- parts.push(String(candidate));
32
- return;
33
- }
34
- if (typeof candidate !== "object" || seen.has(candidate)) return;
35
- seen.add(candidate);
36
- if (candidate instanceof Error) {
37
- visit(candidate.message, depth + 1);
38
- visit(candidate.cause, depth + 1);
39
- return;
40
- }
41
- if (Array.isArray(candidate)) {
42
- for (const item of candidate) visit(item, depth + 1);
43
- return;
44
- }
45
- const preferredKeys = [
46
- "message",
47
- "error",
48
- "additionalDetails",
49
- "codexErrorInfo",
50
- "details",
51
- "turn",
52
- "data",
53
- ];
54
- const keys = [
55
- ...preferredKeys.filter((key) => key in candidate),
56
- ...Object.keys(candidate).filter((key) => !preferredKeys.includes(key)),
57
- ];
58
- for (const key of keys) visit(candidate[key], depth + 1);
59
- }
60
-
61
- visit(value, 0);
62
- return parts.join("\n").slice(0, limit);
63
- }
64
-
65
- export function isModelCapacityError(value) {
66
- return MODEL_CAPACITY_PATTERN.test(errorText(value));
67
- }
68
-
69
- export function isTransientCodexBackendError(value) {
70
- return TRANSIENT_CODEX_BACKEND_PATTERN.test(errorText(value));
71
- }
72
-
73
- export function countModelCapacityWarnings(value) {
74
- return (String(value || "").match(
75
- /selected model is(?: currently)? at capacity/gi,
76
- ) || []).length;
77
- }
78
-
79
- export function hasUnansweredModelCapacityWarning(value) {
80
- const text = String(value || "");
81
- const matches = Array.from(
82
- text.matchAll(/selected model is(?: currently)? at capacity/gi),
83
- );
84
- const latest = matches.at(-1);
85
- if (!latest) return false;
86
- const tail = text.slice((latest.index || 0) + latest[0].length);
87
- // Codex TUI keeps submitted user prompts in scrollback as `› text`. If a
88
- // non-empty prompt follows the latest warning, that warning was handled.
89
- return !/(?:^|\n)\s*[›»>]\s+\S/m.test(tail);
90
- }
1
+ export const CAPACITY_CONTINUE_PROMPT = "继续";
2
+
3
+ export const DEFAULT_CAPACITY_RETRY_DELAYS_MS = Object.freeze([
4
+ 3_000,
5
+ 10_000,
6
+ 30_000,
7
+ 60_000,
8
+ 120_000,
9
+ ]);
10
+
11
+ const MODEL_CAPACITY_PATTERN = /selected model is(?: currently)? at capacity/i;
12
+ // Codex occasionally accepts a turn and then receives an edge/backend error
13
+ // from its own Responses endpoint. Limit retries to this exact endpoint and
14
+ // retryable statuses; ordinary 404s from a user's command are never retried.
15
+ const TRANSIENT_CODEX_BACKEND_PATTERN =
16
+ /unexpected status\s+(?:404|408|429|500|502|503|504)\b[\s\S]{0,1000}chatgpt\.com\/backend-api\/codex\/responses/i;
17
+
18
+ export function errorText(value, limit = 30_000) {
19
+ const parts = [];
20
+ const seen = new Set();
21
+
22
+ function visit(candidate, depth) {
23
+ if (parts.join("\n").length >= limit || depth > 6 || candidate == null) {
24
+ return;
25
+ }
26
+ if (typeof candidate === "string") {
27
+ if (candidate) parts.push(candidate);
28
+ return;
29
+ }
30
+ if (["number", "boolean", "bigint"].includes(typeof candidate)) {
31
+ parts.push(String(candidate));
32
+ return;
33
+ }
34
+ if (typeof candidate !== "object" || seen.has(candidate)) return;
35
+ seen.add(candidate);
36
+ if (candidate instanceof Error) {
37
+ visit(candidate.message, depth + 1);
38
+ visit(candidate.cause, depth + 1);
39
+ return;
40
+ }
41
+ if (Array.isArray(candidate)) {
42
+ for (const item of candidate) visit(item, depth + 1);
43
+ return;
44
+ }
45
+ const preferredKeys = [
46
+ "message",
47
+ "error",
48
+ "additionalDetails",
49
+ "codexErrorInfo",
50
+ "details",
51
+ "turn",
52
+ "data",
53
+ ];
54
+ const keys = [
55
+ ...preferredKeys.filter((key) => key in candidate),
56
+ ...Object.keys(candidate).filter((key) => !preferredKeys.includes(key)),
57
+ ];
58
+ for (const key of keys) visit(candidate[key], depth + 1);
59
+ }
60
+
61
+ visit(value, 0);
62
+ return parts.join("\n").slice(0, limit);
63
+ }
64
+
65
+ export function isModelCapacityError(value) {
66
+ return MODEL_CAPACITY_PATTERN.test(errorText(value));
67
+ }
68
+
69
+ export function isTransientCodexBackendError(value) {
70
+ return TRANSIENT_CODEX_BACKEND_PATTERN.test(errorText(value));
71
+ }
72
+
73
+ export function countModelCapacityWarnings(value) {
74
+ return (String(value || "").match(
75
+ /selected model is(?: currently)? at capacity/gi,
76
+ ) || []).length;
77
+ }
78
+
79
+ export function hasUnansweredModelCapacityWarning(value) {
80
+ const text = String(value || "");
81
+ const matches = Array.from(
82
+ text.matchAll(/selected model is(?: currently)? at capacity/gi),
83
+ );
84
+ const latest = matches.at(-1);
85
+ if (!latest) return false;
86
+ const tail = text.slice((latest.index || 0) + latest[0].length);
87
+ // Codex TUI keeps submitted user prompts in scrollback as `› text`. If a
88
+ // non-empty prompt follows the latest warning, that warning was handled.
89
+ return !/(?:^|\n)\s*[›»>]\s+\S/m.test(tail);
90
+ }