@yuandc/aica 0.1.0

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 (49) hide show
  1. package/README.md +9 -0
  2. package/dist/acp/agent.js +54 -0
  3. package/dist/acp/client/acp-client.js +102 -0
  4. package/dist/acp/client/acp-content.js +13 -0
  5. package/dist/acp/client/acp-events.js +106 -0
  6. package/dist/acp/client/acp-process.js +34 -0
  7. package/dist/acp/client/acp-runtime-pool.js +248 -0
  8. package/dist/acp/client/context-usage.js +29 -0
  9. package/dist/acp/client/json-rpc.js +128 -0
  10. package/dist/acp/provider-types.js +1 -0
  11. package/dist/acp/providers/codex/codex-process.js +51 -0
  12. package/dist/acp/providers/codex/events.js +1473 -0
  13. package/dist/acp/providers/codex/permissions.js +49 -0
  14. package/dist/acp/providers/codex/provider.js +376 -0
  15. package/dist/acp/providers/codex-acp/adapter.js +947 -0
  16. package/dist/acp/providers/codex-acp/context-maintenance.js +148 -0
  17. package/dist/acp/providers/codex-acp/launch.js +35 -0
  18. package/dist/acp/providers/codex-acp/provider.js +486 -0
  19. package/dist/acp/providers/mimo/provider.js +448 -0
  20. package/dist/acp/providers/opencode/provider.js +489 -0
  21. package/dist/acp/providers/registry.js +23 -0
  22. package/dist/acp/standard-events.js +167 -0
  23. package/dist/commands/start.js +137 -0
  24. package/dist/commands/worker-auth.js +100 -0
  25. package/dist/commands/worker-project.js +57 -0
  26. package/dist/core/aca-config.js +74 -0
  27. package/dist/core/aca-server-client.js +57 -0
  28. package/dist/core/acp-event-coalescer.js +108 -0
  29. package/dist/core/acp-event-upload-filter.js +16 -0
  30. package/dist/core/acp-orphan-cleanup.js +91 -0
  31. package/dist/core/affected-files.js +268 -0
  32. package/dist/core/auth.js +36 -0
  33. package/dist/core/file-transfer-worker.js +169 -0
  34. package/dist/core/fs.js +28 -0
  35. package/dist/core/heartbeat.js +578 -0
  36. package/dist/core/job-permission-policy.js +42 -0
  37. package/dist/core/job-worker.js +749 -0
  38. package/dist/core/logger.js +42 -0
  39. package/dist/core/long-poll-worker.js +26 -0
  40. package/dist/core/machine-filesystem-worker.js +352 -0
  41. package/dist/core/paths.js +26 -0
  42. package/dist/core/process-identity.js +34 -0
  43. package/dist/core/process.js +33 -0
  44. package/dist/core/provider-health.js +54 -0
  45. package/dist/core/runtime-options.js +38 -0
  46. package/dist/core/worktree.js +95 -0
  47. package/dist/worker-cli.js +27 -0
  48. package/dist/worker-single-cli.js +17 -0
  49. package/package.json +35 -0
@@ -0,0 +1,148 @@
1
+ import fs from "node:fs";
2
+ const MB = 1024 * 1024;
3
+ export function readCodexContextMaintenancePolicy(env = process.env) {
4
+ return {
5
+ compactTokenThreshold: positiveInteger(env.ACA_CODEX_COMPACT_TOKEN_THRESHOLD, 120_000),
6
+ compactContextRatio: ratio(env.ACA_CODEX_COMPACT_CONTEXT_RATIO, 0.45),
7
+ rolloverTokenThreshold: positiveInteger(env.ACA_CODEX_ROLLOVER_TOKEN_THRESHOLD, 180_000),
8
+ rolloverContextRatio: ratio(env.ACA_CODEX_ROLLOVER_CONTEXT_RATIO, 0.60),
9
+ rolloutMaxBytes: positiveInteger(env.ACA_CODEX_ROLLOUT_MAX_BYTES, 50 * MB),
10
+ threadMaxTurns: positiveInteger(env.ACA_CODEX_THREAD_MAX_TURNS, 40),
11
+ compactTimeoutMs: positiveInteger(env.ACA_CODEX_COMPACT_TIMEOUT_MS, 10 * 60 * 1000),
12
+ slowEventThresholdMs: positiveInteger(env.ACA_CODEX_SLOW_EVENT_THRESHOLD_MS, 5 * 60 * 1000)
13
+ };
14
+ }
15
+ export function codexTokenUsageFromNotification(params, nowMs = Date.now()) {
16
+ const record = objectOrEmpty(params);
17
+ const tokenUsage = objectOrEmpty(record.tokenUsage);
18
+ const last = objectOrEmpty(tokenUsage.last);
19
+ const inputTokens = nonNegativeNumber(last.inputTokens);
20
+ const totalTokens = nonNegativeNumber(last.totalTokens);
21
+ const contextWindow = nonNegativeNumber(tokenUsage.modelContextWindow);
22
+ if (inputTokens === 0 && totalTokens === 0 && contextWindow === 0)
23
+ return null;
24
+ return {
25
+ inputTokens,
26
+ totalTokens,
27
+ contextWindow,
28
+ contextRatio: contextWindow > 0 ? inputTokens / contextWindow : 0,
29
+ observedAtMs: nowMs
30
+ };
31
+ }
32
+ export function decideCodexContextMaintenance(state, policy, input = {}) {
33
+ const compactReasons = [];
34
+ const rolloverReasons = [];
35
+ if (state.usage && state.usage.inputTokens >= policy.compactTokenThreshold)
36
+ compactReasons.push("token-threshold");
37
+ if (state.usage && state.usage.contextRatio >= policy.compactContextRatio)
38
+ compactReasons.push("context-ratio");
39
+ if (state.rolloutBytes >= policy.rolloutMaxBytes)
40
+ compactReasons.push("rollout-size");
41
+ if (state.turnCount >= policy.threadMaxTurns)
42
+ compactReasons.push("turn-count");
43
+ if (input.compactAttempted) {
44
+ if (input.compactFailed)
45
+ rolloverReasons.push("compact-failed");
46
+ if (state.usage && state.usage.inputTokens >= policy.rolloverTokenThreshold)
47
+ rolloverReasons.push("token-still-high");
48
+ if (state.usage && state.usage.contextRatio >= policy.rolloverContextRatio)
49
+ rolloverReasons.push("context-ratio-still-high");
50
+ if (state.rolloutBytes >= policy.rolloutMaxBytes)
51
+ rolloverReasons.push("rollout-size");
52
+ if (state.turnCount >= policy.threadMaxTurns)
53
+ rolloverReasons.push("turn-count");
54
+ }
55
+ return {
56
+ compact: compactReasons.length > 0,
57
+ rollover: rolloverReasons.length > 0,
58
+ reasons: [...new Set([...compactReasons, ...rolloverReasons])]
59
+ };
60
+ }
61
+ export function rolloutFileSize(filePath) {
62
+ if (!filePath)
63
+ return 0;
64
+ try {
65
+ const stat = fs.statSync(filePath);
66
+ return stat.isFile() ? stat.size : 0;
67
+ }
68
+ catch {
69
+ return 0;
70
+ }
71
+ }
72
+ export function buildCodexContinuityInstructions(input) {
73
+ const files = [...new Set(input.affectedFiles.map((item) => item.trim()).filter(Boolean))].slice(0, 30);
74
+ return [
75
+ "ACA automatically rotated a long Codex thread to keep future turns responsive.",
76
+ "Treat the following as continuity context, not as a new user request.",
77
+ "Repository files on disk are authoritative; inspect them before making further edits.",
78
+ "",
79
+ `Previous thread: ${input.previousThreadId}`,
80
+ `Working directory: ${input.cwd}`,
81
+ "",
82
+ "Latest user request:",
83
+ truncateText(input.userRequest, 3_000) || "(not available)",
84
+ "",
85
+ "Latest completed assistant result:",
86
+ truncateText(input.assistantResponse, 7_000) || "(not available)",
87
+ "",
88
+ "Recently affected files:",
89
+ files.length > 0 ? files.map((item) => `- ${item}`).join("\n") : "- (not recorded)"
90
+ ].join("\n");
91
+ }
92
+ export class CodexPromptPerformanceTracker {
93
+ startedAtMs;
94
+ firstEventAtMs = null;
95
+ lastEventAtMs = null;
96
+ eventCount = 0;
97
+ lastSlowReportAtMs = 0;
98
+ constructor(startedAtMs = Date.now()) {
99
+ this.startedAtMs = startedAtMs;
100
+ }
101
+ recordEvent(atMs = Date.now()) {
102
+ if (this.firstEventAtMs === null)
103
+ this.firstEventAtMs = atMs;
104
+ this.lastEventAtMs = atMs;
105
+ this.eventCount += 1;
106
+ }
107
+ shouldReportSlow(nowMs, thresholdMs) {
108
+ const lastActivityAt = this.lastEventAtMs ?? this.startedAtMs;
109
+ if (nowMs - lastActivityAt < thresholdMs)
110
+ return false;
111
+ if (this.lastSlowReportAtMs > 0 && nowMs - this.lastSlowReportAtMs < thresholdMs)
112
+ return false;
113
+ this.lastSlowReportAtMs = nowMs;
114
+ return true;
115
+ }
116
+ snapshot(nowMs = Date.now()) {
117
+ const lastActivityAt = this.lastEventAtMs ?? this.startedAtMs;
118
+ return {
119
+ startedAtMs: this.startedAtMs,
120
+ firstEventAtMs: this.firstEventAtMs,
121
+ lastEventAtMs: this.lastEventAtMs,
122
+ eventCount: this.eventCount,
123
+ firstEventLatencyMs: this.firstEventAtMs === null ? null : this.firstEventAtMs - this.startedAtMs,
124
+ silentForMs: Math.max(0, nowMs - lastActivityAt),
125
+ durationMs: Math.max(0, nowMs - this.startedAtMs)
126
+ };
127
+ }
128
+ }
129
+ function positiveInteger(value, fallback) {
130
+ const parsed = Number.parseInt(value ?? "", 10);
131
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
132
+ }
133
+ function ratio(value, fallback) {
134
+ const parsed = Number.parseFloat(value ?? "");
135
+ return Number.isFinite(parsed) && parsed > 0 && parsed <= 1 ? parsed : fallback;
136
+ }
137
+ function nonNegativeNumber(value) {
138
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : 0;
139
+ }
140
+ function truncateText(value, maxLength) {
141
+ const normalized = value.replace(/\r\n/g, "\n").trim();
142
+ if (normalized.length <= maxLength)
143
+ return normalized;
144
+ return `${normalized.slice(0, maxLength - 16).trimEnd()}\n...[truncated]`;
145
+ }
146
+ function objectOrEmpty(value) {
147
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
148
+ }
@@ -0,0 +1,35 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { createRequire } from "node:module";
4
+ import { fileURLToPath } from "node:url";
5
+ export function resolveCodexAcpLaunch() {
6
+ if (process.isSea || process.env.ACA_SINGLE_FILE_WORKER === "1") {
7
+ return {
8
+ command: process.execPath,
9
+ args: ["--internal-acp-adapter"]
10
+ };
11
+ }
12
+ const adapterTs = fileURLToPath(new URL("./adapter.ts", import.meta.url));
13
+ const adapterJs = fileURLToPath(new URL("./adapter.js", import.meta.url));
14
+ const distAdapterJs = adapterTs.replace(`${path.sep}src${path.sep}`, `${path.sep}dist${path.sep}`).replace(/\.ts$/, ".js");
15
+ if (fs.existsSync(distAdapterJs)) {
16
+ return {
17
+ command: process.execPath,
18
+ args: [distAdapterJs]
19
+ };
20
+ }
21
+ if (fs.existsSync(adapterJs)) {
22
+ return {
23
+ command: process.execPath,
24
+ args: [adapterJs]
25
+ };
26
+ }
27
+ const require = createRequire(import.meta.url);
28
+ return {
29
+ command: process.execPath,
30
+ args: ["--import", require.resolve("tsx"), adapterTs]
31
+ };
32
+ }
33
+ export function resolveCodexAcpDisplayCommand(launch) {
34
+ return `${path.basename(launch.command)} ${launch.args.join(" ")}`;
35
+ }
@@ -0,0 +1,486 @@
1
+ import fs from "node:fs";
2
+ import { promptBlocksToAcpContent } from "../../client/acp-content.js";
3
+ import { eventFromAcpSessionUpdate, statusFromAcpSessionUpdate } from "../../client/acp-events.js";
4
+ import { defaultAcpRuntimePool } from "../../client/acp-runtime-pool.js";
5
+ import { resolveCodexAcpLaunch } from "./launch.js";
6
+ import { CodexPromptPerformanceTracker, readCodexContextMaintenancePolicy } from "./context-maintenance.js";
7
+ export const codexAcpCapabilities = {
8
+ sessionResume: true,
9
+ imageInput: true,
10
+ fileAttachment: true,
11
+ filesystem: true,
12
+ terminal: true,
13
+ permissionRequest: true,
14
+ configOptions: true,
15
+ usage: true,
16
+ contextUsage: true,
17
+ contextCompaction: true,
18
+ plan: true,
19
+ diff: true
20
+ };
21
+ export class CodexAcpProvider {
22
+ id = "codex-acp";
23
+ name = "Codex ACP";
24
+ capabilities = codexAcpCapabilities;
25
+ async createSession(input) {
26
+ return new CodexAcpSession(input.cwd, input.providerSessionId ?? null, input.timeoutMs);
27
+ }
28
+ }
29
+ class CodexAcpSession {
30
+ cwd;
31
+ providerSessionId;
32
+ defaultTimeoutMs;
33
+ lease = null;
34
+ sessionResponse = null;
35
+ statusCallback = null;
36
+ updateCallback = null;
37
+ permissionCallback = null;
38
+ userInputCallback = null;
39
+ abortHandler = null;
40
+ statusTimeline = [];
41
+ updates = [];
42
+ content = "";
43
+ performanceTracker = null;
44
+ constructor(cwd, providerSessionId, defaultTimeoutMs = readCodexAcpPromptTimeoutMs()) {
45
+ this.cwd = cwd;
46
+ this.providerSessionId = providerSessionId;
47
+ this.defaultTimeoutMs = defaultTimeoutMs;
48
+ }
49
+ async sendPrompt(input) {
50
+ if (!fs.existsSync(input.cwd) || !fs.statSync(input.cwd).isDirectory()) {
51
+ throw new Error(`Project root does not exist or is not a directory: ${input.cwd}`);
52
+ }
53
+ const startedAt = Date.now();
54
+ this.statusCallback = input.onStatus ?? null;
55
+ this.updateCallback = input.onUpdate ?? null;
56
+ this.permissionCallback = input.onPermissionRequest ?? null;
57
+ this.userInputCallback = input.onUserInputRequest ?? null;
58
+ this.attachAbortSignal(input.signal);
59
+ this.content = "";
60
+ this.updates.length = 0;
61
+ this.statusTimeline.length = 0;
62
+ this.performanceTracker = new CodexPromptPerformanceTracker(startedAt);
63
+ let client = null;
64
+ let started = null;
65
+ let sessionId = this.providerSessionId;
66
+ let promptResponse;
67
+ let slowStatusTimer = null;
68
+ try {
69
+ this.emitStatus("initializing", "Codex ACP 启动中", "codex-acp");
70
+ const lease = await this.acquireRuntime(input.cwd);
71
+ this.lease = lease;
72
+ client = lease.client;
73
+ started = lease.started;
74
+ await this.initialize(lease);
75
+ sessionId = await this.establishSession(lease, input);
76
+ await this.applyConfig(client, sessionId, input);
77
+ this.emitStatus("thinking", "思考中");
78
+ slowStatusTimer = this.startSlowStatusTimer();
79
+ promptResponse = await this.promptWithAbort(client, {
80
+ sessionId,
81
+ prompt: promptBlocksToAcpContent(input.prompt, input.promptBlocks),
82
+ timeoutMs: input.timeoutMs ?? this.defaultTimeoutMs,
83
+ signal: input.signal
84
+ });
85
+ const nextSessionId = sessionIdFromPromptResponse(promptResponse);
86
+ if (nextSessionId && nextSessionId !== sessionId) {
87
+ sessionId = nextSessionId;
88
+ this.providerSessionId = nextSessionId;
89
+ lease.setProviderSession({ providerSessionId: nextSessionId, sessionResponse: this.sessionResponse });
90
+ }
91
+ }
92
+ finally {
93
+ if (slowStatusTimer)
94
+ clearInterval(slowStatusTimer);
95
+ if (this.abortHandler && input.signal) {
96
+ input.signal.removeEventListener("abort", this.abortHandler);
97
+ this.abortHandler = null;
98
+ }
99
+ this.releaseLease();
100
+ }
101
+ this.emitStatus("completed", "已完成");
102
+ return {
103
+ providerSessionId: sessionId,
104
+ cliType: "builtin",
105
+ agentType: "codex",
106
+ effectiveConfig: {
107
+ model: input.model ?? null,
108
+ mode: input.mode ?? null,
109
+ configOptionValues: input.configOptionValues ?? null,
110
+ command: started.command,
111
+ processPid: started.child.pid ?? null,
112
+ provider: "codex-acp",
113
+ protocol: "acp"
114
+ },
115
+ command: started.command,
116
+ args: started.args,
117
+ cwd: input.cwd,
118
+ exitCode: started.child.exitCode,
119
+ signal: started.child.signalCode,
120
+ durationMs: Date.now() - startedAt,
121
+ stdout: client.rpc.stdout,
122
+ stderr: client.rpc.stderr,
123
+ content: this.content.trim(),
124
+ updates: [...this.updates],
125
+ statusTimeline: [...this.statusTimeline],
126
+ performance: this.performanceTracker?.snapshot(),
127
+ contextUsage: contextUsageFromPromptResponse(promptResponse),
128
+ promptResponse
129
+ };
130
+ }
131
+ async compactContext(input) {
132
+ if (!fs.existsSync(input.cwd) || !fs.statSync(input.cwd).isDirectory()) {
133
+ throw new Error(`Project root does not exist or is not a directory: ${input.cwd}`);
134
+ }
135
+ const startedAt = Date.now();
136
+ this.statusCallback = input.onStatus ?? null;
137
+ this.updateCallback = input.onUpdate ?? null;
138
+ this.attachAbortSignal(input.signal);
139
+ let sessionId = this.providerSessionId;
140
+ let response;
141
+ try {
142
+ this.emitStatus("initializing", "Codex ACP 启动中", "codex-acp");
143
+ const lease = await this.acquireRuntime(input.cwd);
144
+ this.lease = lease;
145
+ await this.initialize(lease);
146
+ sessionId = await this.establishSession(lease, input);
147
+ await this.applyConfig(lease.client, sessionId, input);
148
+ response = await lease.client.compactSession({
149
+ sessionId,
150
+ allowRollover: input.allowRollover === true
151
+ }, input.timeoutMs ?? 10 * 60 * 1000);
152
+ const nextSessionId = sessionIdFromPromptResponse(response);
153
+ if (nextSessionId && nextSessionId !== sessionId) {
154
+ sessionId = nextSessionId;
155
+ this.providerSessionId = nextSessionId;
156
+ lease.setProviderSession({ providerSessionId: nextSessionId, sessionResponse: this.sessionResponse });
157
+ }
158
+ }
159
+ catch (error) {
160
+ if (this.lease && shouldDisposeRuntimeAfterCompactError(error, input.signal)) {
161
+ const lease = this.lease;
162
+ this.lease = null;
163
+ await lease.dispose().catch(() => void 0);
164
+ }
165
+ throw error;
166
+ }
167
+ finally {
168
+ if (this.abortHandler && input.signal) {
169
+ input.signal.removeEventListener("abort", this.abortHandler);
170
+ this.abortHandler = null;
171
+ }
172
+ this.releaseLease();
173
+ }
174
+ const record = objectOrNull(response) ?? {};
175
+ return {
176
+ providerSessionId: sessionId || this.providerSessionId || "",
177
+ contextUsage: contextUsageFromRecord(record.contextUsage),
178
+ maintenance: objectOrNull(record.maintenance) ?? {},
179
+ durationMs: Date.now() - startedAt
180
+ };
181
+ }
182
+ async cancel() {
183
+ if (this.providerSessionId)
184
+ this.lease?.client.cancel(this.providerSessionId);
185
+ }
186
+ async close() {
187
+ this.statusCallback = null;
188
+ this.updateCallback = null;
189
+ this.permissionCallback = null;
190
+ this.userInputCallback = null;
191
+ if (this.abortHandler)
192
+ this.abortHandler = null;
193
+ this.releaseLease();
194
+ }
195
+ async acquireRuntime(cwd) {
196
+ const launch = resolveCodexAcpLaunch();
197
+ return defaultAcpRuntimePool.acquire({
198
+ providerId: "codex-acp",
199
+ cwd,
200
+ providerSessionId: this.providerSessionId,
201
+ command: launch.command,
202
+ args: launch.args,
203
+ onSessionUpdate: (params) => this.handleSessionUpdate(params),
204
+ onClientRequest: async (method, params) => {
205
+ if (method === "session/request_permission")
206
+ return this.requestPermission(params);
207
+ if (method === "elicitation/create" || method === "session/request_user_input")
208
+ return this.requestUserInput(params);
209
+ throw new Error(`Unsupported Codex ACP client request: ${method}`);
210
+ }
211
+ });
212
+ }
213
+ async initialize(lease) {
214
+ if (lease.initialized)
215
+ return;
216
+ await lease.client.initialize(60_000);
217
+ lease.markInitialized();
218
+ }
219
+ async establishSession(lease, input) {
220
+ const client = lease.client;
221
+ const initialConfig = initialCodexConfig(input);
222
+ if (lease.providerSessionId && lease.sessionEstablished) {
223
+ this.providerSessionId = lease.providerSessionId;
224
+ this.sessionResponse = lease.sessionResponse;
225
+ return lease.providerSessionId;
226
+ }
227
+ if (this.providerSessionId) {
228
+ try {
229
+ this.emitStatus("resuming", "Codex ACP 会话恢复中", "session/load");
230
+ const loaded = await client.loadSession({ sessionId: this.providerSessionId, cwd: input.cwd, config: initialConfig }, 60_000);
231
+ this.sessionResponse = objectOrNull(loaded);
232
+ const sessionId = sessionIdFromResponse(loaded) || this.providerSessionId;
233
+ this.providerSessionId = sessionId;
234
+ lease.setProviderSession({ providerSessionId: sessionId, sessionResponse: this.sessionResponse });
235
+ return sessionId;
236
+ }
237
+ catch {
238
+ this.providerSessionId = null;
239
+ }
240
+ }
241
+ this.emitStatus("acp", "Codex ACP 会话创建中", "session/new");
242
+ const created = await client.newSession({ cwd: input.cwd, config: initialConfig }, 120_000);
243
+ this.sessionResponse = objectOrNull(created);
244
+ const sessionId = sessionIdFromResponse(created);
245
+ if (!sessionId)
246
+ throw new Error("Codex ACP session/new did not return sessionId");
247
+ this.providerSessionId = sessionId;
248
+ lease.setProviderSession({ providerSessionId: sessionId, sessionResponse: this.sessionResponse });
249
+ return sessionId;
250
+ }
251
+ async applyConfig(client, sessionId, input) {
252
+ if (input.model) {
253
+ await client.setSessionConfigOption({ sessionId, configId: "model", value: input.model }, 60_000).catch(() => void 0);
254
+ }
255
+ const approvalPolicy = approvalPolicyFromMode(input.mode);
256
+ if (approvalPolicy) {
257
+ await client.setSessionConfigOption({ sessionId, configId: "approvalPolicy", value: approvalPolicy }, 60_000).catch(() => void 0);
258
+ }
259
+ const mode = modeToCodexSandbox(input.mode);
260
+ if (mode) {
261
+ await client.setSessionConfigOption({ sessionId, configId: "sandbox", value: mode }, 60_000).catch(() => void 0);
262
+ }
263
+ for (const [configId, value] of Object.entries(input.configOptionValues ?? {})) {
264
+ if (["model", "mode", "sandbox", "approvalPolicy"].includes(configId))
265
+ continue;
266
+ await client.setSessionConfigOption({ sessionId, configId, value }, 60_000).catch(() => void 0);
267
+ }
268
+ }
269
+ handleSessionUpdate(params) {
270
+ this.performanceTracker?.recordEvent();
271
+ this.updates.push({ method: "session/update", params });
272
+ const event = eventFromAcpSessionUpdate(params);
273
+ if (event) {
274
+ if (event.type === "agent_message_chunk")
275
+ this.content += event.text ?? "";
276
+ this.updateCallback?.(event);
277
+ }
278
+ const status = statusFromAcpSessionUpdate(params);
279
+ if (status)
280
+ this.emitStatus(status.phase, status.label, status.detail, status.updateType);
281
+ }
282
+ startSlowStatusTimer() {
283
+ const thresholdMs = readCodexContextMaintenancePolicy().slowEventThresholdMs;
284
+ const timer = setInterval(() => {
285
+ const tracker = this.performanceTracker;
286
+ const now = Date.now();
287
+ if (!tracker?.shouldReportSlow(now, thresholdMs))
288
+ return;
289
+ const snapshot = tracker.snapshot(now);
290
+ const minutes = Math.max(1, Math.round(snapshot.silentForMs / 60_000));
291
+ this.emitStatus("thinking", "模型长时间处理中", `已 ${minutes} 分钟没有收到新的 ACP 事件`, "aca.performance.slow");
292
+ }, Math.min(30_000, Math.max(1_000, Math.floor(thresholdMs / 4))));
293
+ timer.unref();
294
+ return timer;
295
+ }
296
+ attachAbortSignal(signal) {
297
+ if (!signal)
298
+ return;
299
+ this.abortHandler = () => {
300
+ void this.cancel();
301
+ };
302
+ if (signal.aborted)
303
+ throw new Error("Codex ACP prompt cancelled");
304
+ signal.addEventListener("abort", this.abortHandler, { once: true });
305
+ }
306
+ async promptWithAbort(client, input) {
307
+ const promptPromise = client.prompt({ sessionId: input.sessionId, prompt: input.prompt }, input.timeoutMs);
308
+ if (!input.signal)
309
+ return promptPromise;
310
+ if (input.signal.aborted) {
311
+ await this.lease?.dispose().catch(() => void 0);
312
+ throw new Error("Codex ACP prompt cancelled");
313
+ }
314
+ let abortHandler = null;
315
+ const abortPromise = new Promise((_, reject) => {
316
+ abortHandler = () => {
317
+ client.cancel(input.sessionId);
318
+ void this.lease?.dispose().catch(() => void 0);
319
+ reject(new Error("Codex ACP prompt cancelled"));
320
+ };
321
+ input.signal?.addEventListener("abort", abortHandler, { once: true });
322
+ });
323
+ try {
324
+ return await Promise.race([promptPromise, abortPromise]);
325
+ }
326
+ finally {
327
+ if (abortHandler)
328
+ input.signal.removeEventListener("abort", abortHandler);
329
+ }
330
+ }
331
+ async requestPermission(params) {
332
+ if (!this.permissionCallback)
333
+ return { outcome: { outcome: "cancelled" } };
334
+ const record = params && typeof params === "object" && !Array.isArray(params) ? params : {};
335
+ const request = record.request && typeof record.request === "object" && !Array.isArray(record.request) ? record.request : record;
336
+ const rawOptions = Array.isArray(request.options) ? request.options : [];
337
+ const options = rawOptions.map((option, index) => {
338
+ const item = option && typeof option === "object" && !Array.isArray(option) ? option : {};
339
+ return {
340
+ optionId: String(item.optionId ?? item.id ?? index),
341
+ kind: String(item.kind ?? "choice"),
342
+ ...(typeof item.label === "string" ? { label: item.label } : {})
343
+ };
344
+ });
345
+ this.emitStatus("requestPermission", "等待授权", permissionRequestDetail(request), "session/request_permission");
346
+ return this.permissionCallback({
347
+ requestId: String(request.requestId ?? request.id ?? `codex-acp-permission-${Date.now()}`),
348
+ params,
349
+ options
350
+ });
351
+ }
352
+ async requestUserInput(params) {
353
+ if (!this.userInputCallback)
354
+ return { outcome: { outcome: "cancelled" } };
355
+ const record = params && typeof params === "object" && !Array.isArray(params) ? params : {};
356
+ const request = record.request && typeof record.request === "object" && !Array.isArray(record.request) ? record.request : record;
357
+ this.emitStatus("requestPermission", "等待输入", userInputRequestDetail(request), "elicitation/create");
358
+ return this.userInputCallback({
359
+ requestId: String(request.requestId ?? request.id ?? `codex-acp-input-${Date.now()}`),
360
+ prompt: String(request.prompt ?? request.message ?? request.question ?? ""),
361
+ params,
362
+ ...(typeof request.defaultValue === "string" ? { defaultValue: request.defaultValue } : {})
363
+ });
364
+ }
365
+ emitStatus(phase, label, detail, updateType) {
366
+ const status = {
367
+ phase,
368
+ label,
369
+ ...(detail ? { detail } : {}),
370
+ ...(updateType ? { updateType } : {}),
371
+ atMs: Date.now()
372
+ };
373
+ const last = this.statusTimeline[this.statusTimeline.length - 1];
374
+ if (last && last.phase === status.phase && last.label === status.label && last.detail === status.detail && last.updateType === status.updateType)
375
+ return;
376
+ this.statusTimeline.push(status);
377
+ this.statusCallback?.(status);
378
+ }
379
+ releaseLease() {
380
+ this.lease?.release();
381
+ this.lease = null;
382
+ }
383
+ }
384
+ function shouldDisposeRuntimeAfterCompactError(error, signal) {
385
+ if (signal?.aborted)
386
+ return true;
387
+ const message = error instanceof Error ? error.message : String(error || "");
388
+ return /compact.*timed out|request timed out.*compact|adapter closed|aborted|cancelled/i.test(message);
389
+ }
390
+ function sessionIdFromResponse(value) {
391
+ if (!value || typeof value !== "object" || Array.isArray(value))
392
+ return null;
393
+ const sessionId = value.sessionId;
394
+ return typeof sessionId === "string" && sessionId.trim() ? sessionId.trim() : null;
395
+ }
396
+ function objectOrNull(value) {
397
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
398
+ }
399
+ function modeToCodexSandbox(mode) {
400
+ const normalized = String(mode || "").trim();
401
+ if (!normalized)
402
+ return null;
403
+ if (normalized === "read-only")
404
+ return "read-only";
405
+ if (["agent-full-access", "full-access", "bypassPermissions", "danger-full-access"].includes(normalized))
406
+ return "danger-full-access";
407
+ return "workspace-write";
408
+ }
409
+ function approvalPolicyFromMode(mode) {
410
+ const normalized = String(mode || "").trim();
411
+ if (!normalized)
412
+ return null;
413
+ if (["agent-full-access", "full-access", "bypassPermissions", "danger-full-access"].includes(normalized))
414
+ return "never";
415
+ if (normalized === "acceptEdits" || normalized === "accept-edits")
416
+ return "on-failure";
417
+ return "on-request";
418
+ }
419
+ function initialCodexConfig(input) {
420
+ return {
421
+ ...(input.model ? { model: input.model } : {}),
422
+ ...(approvalPolicyFromMode(input.mode) ? { approvalPolicy: approvalPolicyFromMode(input.mode) } : {}),
423
+ ...(modeToCodexSandbox(input.mode) ? { sandbox: modeToCodexSandbox(input.mode) } : {}),
424
+ ...(input.configOptionValues ?? {})
425
+ };
426
+ }
427
+ function permissionRequestDetail(request) {
428
+ const params = request.params && typeof request.params === "object" && !Array.isArray(request.params) ? request.params : request;
429
+ for (const key of ["command", "cwd", "reason", "grantRoot", "method"]) {
430
+ const value = params[key];
431
+ if (typeof value === "string" && value.trim())
432
+ return textPreview(value);
433
+ }
434
+ return undefined;
435
+ }
436
+ function userInputRequestDetail(request) {
437
+ for (const key of ["prompt", "message", "question", "title"]) {
438
+ const value = request[key];
439
+ if (typeof value === "string" && value.trim())
440
+ return textPreview(value);
441
+ }
442
+ return undefined;
443
+ }
444
+ function textPreview(value) {
445
+ const normalized = value.replace(/\s+/g, " ").trim();
446
+ return normalized.length > 120 ? `${normalized.slice(0, 117)}...` : normalized;
447
+ }
448
+ function readCodexAcpPromptTimeoutMs() {
449
+ const parsed = Number.parseInt(process.env.ACA_CODEX_ACP_PROMPT_TIMEOUT_MS ?? process.env.ACA_ACP_PROMPT_TIMEOUT_MS ?? "", 10);
450
+ return Number.isInteger(parsed) && parsed >= 30_000 ? parsed : 6 * 60 * 60 * 1000;
451
+ }
452
+ function sessionIdFromPromptResponse(value) {
453
+ if (!value || typeof value !== "object" || Array.isArray(value))
454
+ return null;
455
+ const record = value;
456
+ return typeof record.sessionId === "string" && record.sessionId.trim() ? record.sessionId : null;
457
+ }
458
+ function contextUsageFromPromptResponse(value) {
459
+ const record = objectOrNull(value);
460
+ const meta = objectOrNull(record?._meta);
461
+ return contextUsageFromRecord(meta?.acaContextUsage);
462
+ }
463
+ function contextUsageFromRecord(value) {
464
+ const record = objectOrNull(value);
465
+ if (!record)
466
+ return null;
467
+ const contextWindow = finiteNumber(record.contextWindow);
468
+ const usedTokens = finiteNumber(record.usedTokens);
469
+ const inputTokens = finiteNumber(record.inputTokens);
470
+ const rawState = String(record.state || "unknown");
471
+ const state = ["active", "compacted", "new_thread"].includes(rawState)
472
+ ? rawState
473
+ : "unknown";
474
+ return {
475
+ usedTokens,
476
+ inputTokens,
477
+ contextWindow,
478
+ ratio: contextWindow > 0 ? Math.max(0, finiteNumber(record.ratio) || usedTokens / contextWindow) : 0,
479
+ observedAtMs: finiteNumber(record.observedAtMs) || Date.now(),
480
+ state,
481
+ maintenanceAction: typeof record.maintenanceAction === "string" ? record.maintenanceAction : null
482
+ };
483
+ }
484
+ function finiteNumber(value) {
485
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
486
+ }