acpx 0.15.1 → 0.17.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 (47) hide show
  1. package/README.md +2 -0
  2. package/dist/agent-registry-DU6mhZBL.js +785 -0
  3. package/dist/agent-registry-DU6mhZBL.js.map +1 -0
  4. package/dist/agent-registry.d.ts +70 -0
  5. package/dist/agent-registry.d.ts.map +1 -0
  6. package/dist/agent-registry.js +2 -0
  7. package/dist/{cli-BHAT_D3V.js → cli-CiyfEC7L.js} +7 -14
  8. package/dist/cli-CiyfEC7L.js.map +1 -0
  9. package/dist/cli.d.ts +1 -1
  10. package/dist/cli.d.ts.map +1 -1
  11. package/dist/cli.js +160 -349
  12. package/dist/cli.js.map +1 -1
  13. package/dist/{client-Cvz6msGc.d.ts → client-C6NUFqr-.d.ts} +21 -13
  14. package/dist/client-C6NUFqr-.d.ts.map +1 -0
  15. package/dist/{flows-BOI1XkMp.js → flows-CTOdIk-m.js} +208 -279
  16. package/dist/flows-CTOdIk-m.js.map +1 -0
  17. package/dist/flows.d.ts +6 -17
  18. package/dist/flows.d.ts.map +1 -1
  19. package/dist/flows.js +1 -1
  20. package/dist/{flags-BHcZWTov.js → invocation-options-DbCcOAzM.js} +83 -58
  21. package/dist/invocation-options-DbCcOAzM.js.map +1 -0
  22. package/dist/ipc-D3akHMEq.js +3350 -0
  23. package/dist/ipc-D3akHMEq.js.map +1 -0
  24. package/dist/output-BPPjvJTI.js +980 -0
  25. package/dist/output-BPPjvJTI.js.map +1 -0
  26. package/dist/{live-checkpoint-sB7dFOYR.js → queue-owner-runtime--IbbndGz.js} +5359 -4574
  27. package/dist/queue-owner-runtime--IbbndGz.js.map +1 -0
  28. package/dist/runtime.d.ts +197 -27
  29. package/dist/runtime.d.ts.map +1 -1
  30. package/dist/runtime.js +864 -409
  31. package/dist/runtime.js.map +1 -1
  32. package/dist/{session-options-DyIGRNfu.d.ts → session-options-Dp6mzNSy.d.ts} +8 -6
  33. package/dist/session-options-Dp6mzNSy.d.ts.map +1 -0
  34. package/dist/session-watch--UX5dh00.js +76 -0
  35. package/dist/session-watch--UX5dh00.js.map +1 -0
  36. package/dist/watch-BbBxO-kb.js +32 -0
  37. package/dist/watch-BbBxO-kb.js.map +1 -0
  38. package/package.json +27 -25
  39. package/skills/acpx/SKILL.md +24 -19
  40. package/dist/cli-BHAT_D3V.js.map +0 -1
  41. package/dist/client-Cvz6msGc.d.ts.map +0 -1
  42. package/dist/flags-BHcZWTov.js.map +0 -1
  43. package/dist/flows-BOI1XkMp.js.map +0 -1
  44. package/dist/live-checkpoint-sB7dFOYR.js.map +0 -1
  45. package/dist/output-8-D6Gd4Z.js +0 -4714
  46. package/dist/output-8-D6Gd4Z.js.map +0 -1
  47. package/dist/session-options-DyIGRNfu.d.ts.map +0 -1
@@ -1,4714 +0,0 @@
1
- import { $ as formatPerfMetric, B as absolutePath, Bt as extractAcpError, C as sessionOptionsFromRecord, D as AcpClient, Dt as TimeoutError, Et as InterruptedError, F as runTimedExecFile, G as listSessions, H as findSession, Ht as toAcpErrorPayload, I as splitCommandLine, J as pruneSessions, K as listSessionsForAgent, Kt as OUTPUT_ERROR_CODES, Lt as formatErrorMessage, M as modelStateFromConfigOptions, Ot as withInterrupt, Rt as isRetryablePromptError, S as persistSessionOptions, T as applyLifecycleSnapshotToRecord, Tt as textPrompt, U as findSessionByDirectoryWalk, V as findGitRepositoryRoot, W as isoNow, X as writeSessionRecord, Y as resolveSessionRecord, _ as recordPromptSubmission, _t as isAcpJsonRpcMessage, a as applyConfigOptionSelection, at as setPerfGauge, b as advertisedModelState, c as applyRequestedModelIfAdvertised, d as setDesiredModeId, dt as defaultSessionEventLog, en as QueueConnectionError, et as getPerfMetricsSnapshot, f as syncAdvertisedModelState, ft as sessionBaseDir, g as recordClientOperation, gt as extractSessionUpdateNotification, h as createSessionConversation, ht as sessionEventSegmentPath, i as connectAndLoadSession, it as resetPerfMetrics, kt as withTimeout, l as currentModelIdFromSetModelResponse, lt as normalizeRuntimeSessionId, m as cloneSessionConversation, mt as sessionEventLockPath, n as runPromptTurn, nt as measurePerf, o as applyConfigOptionsToRecord, ot as startPerfTimer, p as cloneSessionAcpxState, pt as sessionEventActivePath, q as normalizeName, qt as OUTPUT_ERROR_ORIGINS, r as withConnectedSession, rt as recordPerfDuration, s as applyModelSelection, t as LiveSessionCheckpoint, tn as QueueProtocolError, tt as incrementPerfCounter, u as setCurrentModelId, v as recordSessionUpdate, vt as parseJsonRpcErrorMessage, w as applyConversation, wt as promptToDisplayText, x as mergeSessionOptions, xt as isPromptInput, y as trimConversationForRuntime, yt as parsePromptStopReason, zt as normalizeOutputError } from "./live-checkpoint-sB7dFOYR.js";
2
- import fs, { mkdtempSync, realpathSync, writeFileSync } from "node:fs";
3
- import path from "node:path";
4
- import fs$1 from "node:fs/promises";
5
- import os from "node:os";
6
- import { createHash, randomInt, randomUUID } from "node:crypto";
7
- import { spawn } from "node:child_process";
8
- import net from "node:net";
9
- //#region \0rolldown/runtime.js
10
- var __defProp = Object.defineProperty;
11
- var __exportAll = (all, no_symbols) => {
12
- let target = {};
13
- for (var name in all) __defProp(target, name, {
14
- get: all[name],
15
- enumerable: true
16
- });
17
- if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
18
- return target;
19
- };
20
- //#endregion
21
- //#region src/process-liveness.ts
22
- function isProcessAlive(pid) {
23
- if (!pid || !Number.isInteger(pid) || pid <= 0 || pid === process.pid) return false;
24
- try {
25
- process.kill(pid, 0);
26
- return true;
27
- } catch {
28
- return false;
29
- }
30
- }
31
- //#endregion
32
- //#region src/cli/session/contracts.ts
33
- const DEFAULT_QUEUE_OWNER_TTL_MS = 3e5;
34
- function normalizeQueueOwnerTtlMs(ttlMs) {
35
- if (ttlMs == null) return DEFAULT_QUEUE_OWNER_TTL_MS;
36
- if (!Number.isFinite(ttlMs) || ttlMs < 0) return DEFAULT_QUEUE_OWNER_TTL_MS;
37
- return Math.round(ttlMs);
38
- }
39
- //#endregion
40
- //#region src/cli/queue/paths.ts
41
- function shortHash(value, length) {
42
- return createHash("sha256").update(value).digest("hex").slice(0, length);
43
- }
44
- function queueKeyForSession(sessionId) {
45
- return shortHash(sessionId, 24);
46
- }
47
- function queueBaseDir(homeDir = os.homedir()) {
48
- return path.join(homeDir, ".acpx", "queues");
49
- }
50
- function queueSocketBaseDir(homeDir = os.homedir()) {
51
- if (process.platform === "win32") return;
52
- return path.join("/tmp", `acpx-${shortHash(homeDir, 10)}`);
53
- }
54
- function queueLockFilePath(sessionId, homeDir = os.homedir()) {
55
- return path.join(queueBaseDir(homeDir), `${queueKeyForSession(sessionId)}.lock`);
56
- }
57
- function queueSocketPath(sessionId, homeDir = os.homedir()) {
58
- const key = queueKeyForSession(sessionId);
59
- if (process.platform === "win32") return `\\\\.\\pipe\\acpx-${key}`;
60
- return path.join(queueSocketBaseDir(homeDir) ?? "/tmp", `${key}.sock`);
61
- }
62
- //#endregion
63
- //#region src/cli/queue/lease-store.ts
64
- const PROCESS_SIGTERM_GRACE_MS = 4e3;
65
- const PROCESS_SIGKILL_GRACE_MS = 1500;
66
- const PROCESS_POLL_MS = 50;
67
- const QUEUE_OWNER_STALE_HEARTBEAT_MS = 15e3;
68
- function parseQueueOwnerRecord(raw) {
69
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
70
- const record = raw;
71
- if (!hasValidQueueOwnerRecordFields(record)) return null;
72
- return {
73
- pid: record.pid,
74
- sessionId: record.sessionId,
75
- socketPath: record.socketPath,
76
- createdAt: record.createdAt,
77
- heartbeatAt: record.heartbeatAt,
78
- ownerGeneration: record.ownerGeneration,
79
- queueDepth: record.queueDepth,
80
- ...typeof record.mcpConfigPath === "string" ? { mcpConfigPath: record.mcpConfigPath } : {},
81
- ...typeof record.mcpConfigFingerprint === "string" ? { mcpConfigFingerprint: record.mcpConfigFingerprint } : {}
82
- };
83
- }
84
- function hasValidQueueOwnerRecordFields(record) {
85
- return isPositiveInteger(record.pid) && typeof record.sessionId === "string" && typeof record.socketPath === "string" && typeof record.createdAt === "string" && typeof record.heartbeatAt === "string" && isPositiveInteger(record.ownerGeneration) && isNonNegativeInteger(record.queueDepth);
86
- }
87
- function isPositiveInteger(value) {
88
- return Number.isInteger(value) && value > 0;
89
- }
90
- function isNonNegativeInteger(value) {
91
- return Number.isInteger(value) && value >= 0;
92
- }
93
- function createOwnerGeneration() {
94
- return randomInt(1, 2 ** 48);
95
- }
96
- function nowIso() {
97
- return (/* @__PURE__ */ new Date()).toISOString();
98
- }
99
- function isQueueOwnerHeartbeatStale(owner) {
100
- const heartbeatMs = Date.parse(owner.heartbeatAt);
101
- if (!Number.isFinite(heartbeatMs)) return true;
102
- return Date.now() - heartbeatMs > QUEUE_OWNER_STALE_HEARTBEAT_MS;
103
- }
104
- async function ensureQueueDir() {
105
- const baseDir = queueBaseDir();
106
- try {
107
- await fs$1.mkdir(baseDir, {
108
- recursive: true,
109
- mode: 448
110
- });
111
- await fs$1.chmod(baseDir, 448);
112
- } catch (error) {
113
- const message = error instanceof Error ? error.message : String(error);
114
- throw new Error(`Failed to prepare queue directory ${baseDir}: ${message}`, { cause: error });
115
- }
116
- const socketDir = queueSocketBaseDir();
117
- if (socketDir) try {
118
- await fs$1.mkdir(socketDir, {
119
- recursive: true,
120
- mode: 448
121
- });
122
- await fs$1.chmod(socketDir, 448);
123
- } catch (error) {
124
- const message = error instanceof Error ? error.message : String(error);
125
- throw new Error(`Failed to prepare queue socket directory ${socketDir}: ${message}`, { cause: error });
126
- }
127
- }
128
- async function removeSocketFile(socketPath) {
129
- if (process.platform === "win32") return;
130
- try {
131
- await fs$1.unlink(socketPath);
132
- } catch (error) {
133
- if (error.code !== "ENOENT") throw error;
134
- }
135
- }
136
- async function waitForProcessExit(pid, timeoutMs) {
137
- const deadline = Date.now() + Math.max(0, timeoutMs);
138
- while (Date.now() <= deadline) {
139
- if (!isProcessAlive(pid)) return true;
140
- await waitMs(PROCESS_POLL_MS);
141
- }
142
- return !isProcessAlive(pid);
143
- }
144
- async function cleanupStaleQueueOwner(sessionId, owner) {
145
- const lockPath = queueLockFilePath(sessionId);
146
- await removeSocketFile(owner?.socketPath ?? queueSocketPath(sessionId)).catch(() => {});
147
- await fs$1.unlink(lockPath).catch((error) => {
148
- if (error.code !== "ENOENT") throw error;
149
- });
150
- }
151
- async function retireStaleQueueOwner(sessionId, owner) {
152
- if (owner && isProcessAlive(owner.pid)) await terminateProcess(owner.pid);
153
- await cleanupStaleQueueOwner(sessionId, owner);
154
- }
155
- async function readQueueOwnerRecord(sessionId) {
156
- const lockPath = queueLockFilePath(sessionId);
157
- try {
158
- const payload = await fs$1.readFile(lockPath, "utf8");
159
- return parseQueueOwnerRecord(JSON.parse(payload)) ?? void 0;
160
- } catch {
161
- return;
162
- }
163
- }
164
- async function terminateProcess(pid) {
165
- if (!isProcessAlive(pid)) return false;
166
- try {
167
- process.kill(pid, "SIGTERM");
168
- } catch {
169
- return false;
170
- }
171
- if (await waitForProcessExit(pid, PROCESS_SIGTERM_GRACE_MS)) return true;
172
- try {
173
- process.kill(pid, "SIGKILL");
174
- } catch {
175
- return false;
176
- }
177
- await waitForProcessExit(pid, PROCESS_SIGKILL_GRACE_MS);
178
- return true;
179
- }
180
- async function ensureOwnerIsUsable(sessionId, owner) {
181
- const alive = isProcessAlive(owner.pid);
182
- const stale = isQueueOwnerHeartbeatStale(owner);
183
- if (alive && !stale) return true;
184
- await retireStaleQueueOwner(sessionId, owner);
185
- return false;
186
- }
187
- async function readQueueOwnerStatus(sessionId) {
188
- const owner = await readQueueOwnerRecord(sessionId);
189
- if (!owner) return;
190
- const alive = await ensureOwnerIsUsable(sessionId, owner);
191
- if (!alive) return;
192
- return {
193
- pid: owner.pid,
194
- socketPath: owner.socketPath,
195
- heartbeatAt: owner.heartbeatAt,
196
- ownerGeneration: owner.ownerGeneration,
197
- queueDepth: owner.queueDepth,
198
- alive,
199
- stale: isQueueOwnerHeartbeatStale(owner)
200
- };
201
- }
202
- async function tryAcquireQueueOwnerLease(sessionId, mcpConfigOrNowIsoFactory, nowIsoFactory = nowIso) {
203
- const { mcpConfigPath, clock } = resolveLeaseArguments(mcpConfigOrNowIsoFactory, nowIsoFactory);
204
- const mcpConfigMetadata = createMcpConfigMetadata(mcpConfigPath, readMcpConfigFingerprint(mcpConfigOrNowIsoFactory));
205
- await ensureQueueDir();
206
- const lockPath = queueLockFilePath(sessionId);
207
- const socketPath = queueSocketPath(sessionId);
208
- const createdAt = clock();
209
- const ownerGeneration = createOwnerGeneration();
210
- const payload = JSON.stringify({
211
- pid: process.pid,
212
- sessionId,
213
- socketPath,
214
- createdAt,
215
- heartbeatAt: createdAt,
216
- ownerGeneration,
217
- queueDepth: 0,
218
- ...mcpConfigMetadata
219
- }, null, 2);
220
- try {
221
- await fs$1.writeFile(lockPath, `${payload}\n`, {
222
- encoding: "utf8",
223
- flag: "wx"
224
- });
225
- await removeSocketFile(socketPath).catch(() => {});
226
- return {
227
- sessionId,
228
- lockPath,
229
- socketPath,
230
- createdAt,
231
- ownerGeneration,
232
- ...mcpConfigMetadata
233
- };
234
- } catch (error) {
235
- return await handleLeaseCollision(sessionId, error);
236
- }
237
- }
238
- function readMcpConfigFingerprint(mcpConfigOrNowIsoFactory) {
239
- return typeof mcpConfigOrNowIsoFactory === "object" ? mcpConfigOrNowIsoFactory?.fingerprint : void 0;
240
- }
241
- function createMcpConfigMetadata(mcpConfigPath, mcpConfigFingerprint) {
242
- return {
243
- ...mcpConfigPath ? { mcpConfigPath } : {},
244
- ...mcpConfigFingerprint ? { mcpConfigFingerprint } : {}
245
- };
246
- }
247
- async function handleLeaseCollision(sessionId, error) {
248
- if (error.code !== "EEXIST") throw error;
249
- const owner = await readQueueOwnerRecord(sessionId);
250
- if (!owner) {
251
- await cleanupStaleQueueOwner(sessionId, owner);
252
- return;
253
- }
254
- if (!isProcessAlive(owner.pid) || isQueueOwnerHeartbeatStale(owner)) await retireStaleQueueOwner(sessionId, owner);
255
- }
256
- function resolveLeaseArguments(mcpConfigOrNowIsoFactory, nowIsoFactory) {
257
- if (typeof mcpConfigOrNowIsoFactory === "string") return {
258
- mcpConfigPath: mcpConfigOrNowIsoFactory,
259
- clock: nowIsoFactory
260
- };
261
- if (typeof mcpConfigOrNowIsoFactory === "function") return {
262
- mcpConfigPath: void 0,
263
- clock: mcpConfigOrNowIsoFactory
264
- };
265
- if (mcpConfigOrNowIsoFactory) return {
266
- mcpConfigPath: mcpConfigOrNowIsoFactory.path,
267
- clock: nowIsoFactory
268
- };
269
- return {
270
- mcpConfigPath: void 0,
271
- clock: nowIsoFactory
272
- };
273
- }
274
- async function refreshQueueOwnerLease(lease, options, nowIsoFactory = nowIso) {
275
- const payload = JSON.stringify({
276
- pid: process.pid,
277
- sessionId: lease.sessionId,
278
- socketPath: lease.socketPath,
279
- createdAt: lease.createdAt,
280
- heartbeatAt: nowIsoFactory(),
281
- ownerGeneration: lease.ownerGeneration,
282
- queueDepth: Math.max(0, Math.round(options.queueDepth)),
283
- ...lease.mcpConfigPath ? { mcpConfigPath: lease.mcpConfigPath } : {},
284
- ...lease.mcpConfigFingerprint ? { mcpConfigFingerprint: lease.mcpConfigFingerprint } : {}
285
- }, null, 2);
286
- await fs$1.writeFile(lease.lockPath, `${payload}\n`, { encoding: "utf8" });
287
- }
288
- async function releaseQueueOwnerLease(lease) {
289
- await removeSocketFile(lease.socketPath).catch(() => {});
290
- await fs$1.unlink(lease.lockPath).catch((error) => {
291
- if (error.code !== "ENOENT") throw error;
292
- });
293
- }
294
- async function terminateQueueOwnerForSession(sessionId) {
295
- const owner = await readQueueOwnerRecord(sessionId);
296
- if (!owner) return;
297
- if (isProcessAlive(owner.pid)) await terminateProcess(owner.pid);
298
- await cleanupStaleQueueOwner(sessionId, owner);
299
- }
300
- async function waitMs(ms) {
301
- await new Promise((resolve) => {
302
- setTimeout(resolve, ms);
303
- });
304
- }
305
- //#endregion
306
- //#region src/cli/queue/ipc-transport.ts
307
- const QUEUE_CONNECT_ATTEMPTS = 40;
308
- const SOCKET_CONNECTION_TIMEOUT_MS = 5e3;
309
- function shouldRetryQueueConnect(error) {
310
- const code = error.code;
311
- return code === "ENOENT" || code === "ECONNREFUSED";
312
- }
313
- async function connectToSocket(socketPath, timeoutMs = SOCKET_CONNECTION_TIMEOUT_MS) {
314
- return await new Promise((resolve, reject) => {
315
- const socket = net.createConnection(socketPath);
316
- let settled = false;
317
- const timeout = setTimeout(() => {
318
- if (settled) return;
319
- settled = true;
320
- socket.destroy();
321
- reject(/* @__PURE__ */ new Error(`Connection to ${socketPath} timed out after ${timeoutMs}ms`));
322
- }, timeoutMs);
323
- const onConnect = () => {
324
- if (settled) return;
325
- settled = true;
326
- clearTimeout(timeout);
327
- socket.off("error", onError);
328
- resolve(socket);
329
- };
330
- const onError = (error) => {
331
- if (settled) return;
332
- settled = true;
333
- clearTimeout(timeout);
334
- socket.off("connect", onConnect);
335
- reject(error);
336
- };
337
- socket.once("connect", onConnect);
338
- socket.once("error", onError);
339
- });
340
- }
341
- async function connectToQueueOwner(owner, maxAttempts = QUEUE_CONNECT_ATTEMPTS) {
342
- let lastError;
343
- const attempts = Math.max(1, Math.trunc(maxAttempts));
344
- for (let attempt = 0; attempt < attempts; attempt += 1) try {
345
- return await measurePerf("queue.connect", async () => await connectToSocket(owner.socketPath));
346
- } catch (error) {
347
- lastError = error;
348
- if (!shouldRetryQueueConnect(error)) throw error;
349
- await waitMs(50);
350
- }
351
- if (lastError && !shouldRetryQueueConnect(lastError)) throw lastError;
352
- }
353
- //#endregion
354
- //#region src/cli/queue/ipc-health.ts
355
- async function probeQueueOwnerHealth(sessionId) {
356
- const ownerRecord = await readQueueOwnerRecord(sessionId);
357
- if (!ownerRecord) return {
358
- sessionId,
359
- hasLease: false,
360
- healthy: false,
361
- socketReachable: false,
362
- pidAlive: false
363
- };
364
- const owner = await readQueueOwnerStatus(sessionId);
365
- if (!owner) return {
366
- sessionId,
367
- hasLease: false,
368
- healthy: false,
369
- socketReachable: false,
370
- pidAlive: false
371
- };
372
- const pidAlive = owner.alive;
373
- let socketReachable = false;
374
- try {
375
- const socket = await connectToQueueOwner(ownerRecord, 2);
376
- if (socket) {
377
- socketReachable = true;
378
- if (!socket.destroyed) socket.end();
379
- }
380
- } catch {
381
- socketReachable = false;
382
- }
383
- return {
384
- sessionId,
385
- hasLease: true,
386
- healthy: socketReachable,
387
- socketReachable,
388
- pidAlive,
389
- pid: owner.pid,
390
- socketPath: owner.socketPath,
391
- ownerGeneration: owner.ownerGeneration,
392
- queueDepth: owner.queueDepth
393
- };
394
- }
395
- //#endregion
396
- //#region src/cli/queue/messages.ts
397
- function asRecord$2(value) {
398
- if (!value || typeof value !== "object" || Array.isArray(value)) return;
399
- return value;
400
- }
401
- function isPermissionMode(value) {
402
- return value === "approve-all" || value === "approve-reads" || value === "deny-all";
403
- }
404
- function isSessionResumePolicy(value) {
405
- return value === "allow-new" || value === "same-session-only";
406
- }
407
- function isNonInteractivePermissionPolicy(value) {
408
- return value === "deny" || value === "fail";
409
- }
410
- function isPermissionPolicy(value) {
411
- const record = asRecord$2(value);
412
- if (!record) return false;
413
- return hasValidPermissionRuleLists(record) && hasValidPermissionDefaultAction(record);
414
- }
415
- function hasValidPermissionRuleLists(record) {
416
- for (const key of [
417
- "autoApprove",
418
- "autoDeny",
419
- "escalate"
420
- ]) if (!isOptionalStringList(record[key])) return false;
421
- return true;
422
- }
423
- function isOptionalStringList(value) {
424
- return value == null || Array.isArray(value) && value.every((item) => typeof item === "string");
425
- }
426
- function hasValidPermissionDefaultAction(record) {
427
- return record.defaultAction == null || record.defaultAction === "approve" || record.defaultAction === "deny" || record.defaultAction === "escalate";
428
- }
429
- function isOutputErrorCode(value) {
430
- return typeof value === "string" && OUTPUT_ERROR_CODES.includes(value);
431
- }
432
- function isOutputErrorOrigin(value) {
433
- return typeof value === "string" && OUTPUT_ERROR_ORIGINS.includes(value);
434
- }
435
- function isPermissionEscalationEvent(value) {
436
- const event = asRecord$2(value);
437
- return !!event && hasRequiredPermissionEscalationFields(event) && hasOptionalStringFields(event, [
438
- "toolName",
439
- "toolKind",
440
- "matchedRule"
441
- ]);
442
- }
443
- function hasRequiredPermissionEscalationFields(event) {
444
- return event.type === "permission_escalation" && typeof event.sessionId === "string" && typeof event.toolCallId === "string" && typeof event.toolTitle === "string" && event.action === "escalate" && typeof event.message === "string" && typeof event.timestamp === "string";
445
- }
446
- function hasOptionalStringFields(record, keys) {
447
- return keys.every((key) => record[key] == null || typeof record[key] === "string");
448
- }
449
- function parseSessionOptions(value) {
450
- if (value == null) return;
451
- const record = asRecord$2(value);
452
- if (!record) return null;
453
- const sessionOptions = {};
454
- if (!assignSessionModel(sessionOptions, record.model)) return null;
455
- if (!assignSessionAllowedTools(sessionOptions, record.allowedTools)) return null;
456
- if (!assignSessionMaxTurns(sessionOptions, record.maxTurns)) return null;
457
- if (!assignSessionSystemPrompt(sessionOptions, record.systemPrompt)) return null;
458
- if (!assignSessionEnv(sessionOptions, record.env)) return null;
459
- return sessionOptions;
460
- }
461
- function assignSessionModel(options, value) {
462
- if (value == null) return true;
463
- if (typeof value !== "string" || value.trim().length === 0) return false;
464
- options.model = value;
465
- return true;
466
- }
467
- function assignSessionAllowedTools(options, value) {
468
- if (value == null) return true;
469
- if (!Array.isArray(value) || value.some((tool) => typeof tool !== "string")) return false;
470
- options.allowedTools = value;
471
- return true;
472
- }
473
- function assignSessionMaxTurns(options, value) {
474
- if (value == null) return true;
475
- if (typeof value !== "number" || !Number.isFinite(value)) return false;
476
- options.maxTurns = Math.max(1, Math.round(value));
477
- return true;
478
- }
479
- function assignSessionSystemPrompt(options, value) {
480
- if (value == null) return true;
481
- if (typeof value === "string") {
482
- options.systemPrompt = value;
483
- return true;
484
- }
485
- const systemPrompt = asRecord$2(value);
486
- if (!systemPrompt || typeof systemPrompt.append !== "string") return false;
487
- options.systemPrompt = { append: systemPrompt.append };
488
- return true;
489
- }
490
- function assignSessionEnv(options, value) {
491
- if (value == null) return true;
492
- const env = asRecord$2(value);
493
- if (!env) return false;
494
- const entries = Object.entries(env);
495
- if (entries.some(([, entryValue]) => typeof entryValue !== "string")) return false;
496
- options.env = Object.fromEntries(entries);
497
- return true;
498
- }
499
- function parseOwnerGeneration(value) {
500
- if (value == null) return;
501
- if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) return null;
502
- return value;
503
- }
504
- function parseNonNegativeInteger(value) {
505
- if (value == null) return;
506
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return null;
507
- return Math.round(value);
508
- }
509
- function parseQueueRequest(raw) {
510
- const request = asRecord$2(raw);
511
- if (!request || typeof request.type !== "string" || typeof request.requestId !== "string") return null;
512
- const ownerGeneration = parseOwnerGeneration(request.ownerGeneration);
513
- if (ownerGeneration === null) return null;
514
- return parseTypedQueueRequest(request, parseQueueRequestContext(request.requestId, ownerGeneration, request.timeoutMs));
515
- }
516
- function parseQueueRequestContext(requestId, ownerGeneration, timeoutRaw) {
517
- return {
518
- requestId,
519
- ownerGeneration,
520
- timeoutMs: parsePositiveTimeout(timeoutRaw)
521
- };
522
- }
523
- function parsePositiveTimeout(value) {
524
- if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return;
525
- return Math.round(value);
526
- }
527
- function parseTypedQueueRequest(request, context) {
528
- switch (request.type) {
529
- case "submit_prompt": return parseSubmitRequest(request, context);
530
- case "cancel_prompt": return {
531
- type: "cancel_prompt",
532
- requestId: context.requestId,
533
- ownerGeneration: context.ownerGeneration
534
- };
535
- case "close_session": return {
536
- type: "close_session",
537
- ...context
538
- };
539
- case "set_mode": return parseStringFieldRequest(request, context, "set_mode", "modeId");
540
- case "set_model": return parseStringFieldRequest(request, context, "set_model", "modelId");
541
- case "set_config_option": return parseSetConfigOptionRequest(request, context);
542
- default: return null;
543
- }
544
- }
545
- function parseSubmitRequest(request, context) {
546
- const parsed = parseSubmitRequestFields(request);
547
- if (!parsed) return null;
548
- return {
549
- type: "submit_prompt",
550
- requestId: context.requestId,
551
- ownerGeneration: context.ownerGeneration,
552
- message: parsed.message,
553
- prompt: parsed.prompt ?? textPrompt(parsed.message),
554
- permissionMode: parsed.permissionMode,
555
- ...parsed.resumePolicy !== void 0 ? { resumePolicy: parsed.resumePolicy } : {},
556
- nonInteractivePermissions: parsed.nonInteractivePermissions,
557
- ...parsed.permissionPolicy !== void 0 ? { permissionPolicy: parsed.permissionPolicy } : {},
558
- timeoutMs: context.timeoutMs,
559
- ...parsed.suppressSdkConsoleErrors !== void 0 ? { suppressSdkConsoleErrors: parsed.suppressSdkConsoleErrors } : {},
560
- ...parsed.promptRetries !== void 0 ? { promptRetries: parsed.promptRetries } : {},
561
- waitForCompletion: parsed.waitForCompletion,
562
- ...parsed.sessionOptions !== void 0 ? { sessionOptions: parsed.sessionOptions } : {}
563
- };
564
- }
565
- function parseSubmitRequestFields(request) {
566
- const parsed = {
567
- message: typeof request.message === "string" ? request.message : null,
568
- prompt: parseOptionalValue(request.prompt, isPromptInput),
569
- permissionMode: parseRequiredValue(request.permissionMode, isPermissionMode),
570
- resumePolicy: parseOptionalValue(request.resumePolicy, isSessionResumePolicy),
571
- nonInteractivePermissions: parseOptionalValue(request.nonInteractivePermissions, isNonInteractivePermissionPolicy),
572
- permissionPolicy: parseOptionalValue(request.permissionPolicy, isPermissionPolicy),
573
- suppressSdkConsoleErrors: parseOptionalBoolean(request.suppressSdkConsoleErrors),
574
- promptRetries: parseNonNegativeInteger(request.promptRetries),
575
- waitForCompletion: typeof request.waitForCompletion === "boolean" ? request.waitForCompletion : null,
576
- sessionOptions: parseSessionOptions(request.sessionOptions)
577
- };
578
- if (Object.values(parsed).some((value) => value === null)) return null;
579
- return parsed;
580
- }
581
- function parseOptionalValue(value, guard) {
582
- if (value == null) return;
583
- return guard(value) ? value : null;
584
- }
585
- function parseRequiredValue(value, guard) {
586
- return guard(value) ? value : null;
587
- }
588
- function parseOptionalBoolean(value) {
589
- if (value == null) return;
590
- return typeof value === "boolean" ? value : null;
591
- }
592
- function parseStringFieldRequest(request, context, type, field) {
593
- const value = parseNonEmptyString(request[field]);
594
- if (!value) return null;
595
- return {
596
- type,
597
- ...context,
598
- [field]: value
599
- };
600
- }
601
- function parseSetConfigOptionRequest(request, context) {
602
- const configId = parseNonEmptyString(request.configId);
603
- const value = parseNonEmptyString(request.value);
604
- if (!configId || !value) return null;
605
- return {
606
- type: "set_config_option",
607
- ...context,
608
- configId,
609
- value
610
- };
611
- }
612
- function parseNonEmptyString(value) {
613
- if (typeof value !== "string" || value.trim().length === 0) return null;
614
- return value;
615
- }
616
- function parseSessionSendResult(raw) {
617
- const result = asRecord$2(raw);
618
- if (!result || !hasValidSessionSendResultCore(result)) return null;
619
- const permissionStats = asRecord$2(result.permissionStats);
620
- const record = asRecord$2(result.record);
621
- if (!permissionStats || !record) return null;
622
- if (!hasValidPermissionStats(permissionStats)) return null;
623
- if (!hasValidSessionRecordShape(record)) return null;
624
- return result;
625
- }
626
- function hasValidSessionSendResultCore(result) {
627
- return typeof result.stopReason === "string" && typeof result.sessionId === "string" && typeof result.resumed === "boolean" && (result._meta === void 0 || result._meta === null || asRecord$2(result._meta) !== void 0);
628
- }
629
- function hasValidPermissionStats(permissionStats) {
630
- return [
631
- "requested",
632
- "approved",
633
- "denied",
634
- "cancelled"
635
- ].every((key) => typeof permissionStats[key] === "number");
636
- }
637
- function hasValidSessionRecordShape(record) {
638
- return hasStringFields(record, [
639
- "acpxRecordId",
640
- "acpSessionId",
641
- "agentCommand",
642
- "cwd",
643
- "createdAt",
644
- "lastUsedAt",
645
- "updated_at"
646
- ]) && Array.isArray(record.messages) && typeof record.lastSeq === "number" && Number.isInteger(record.lastSeq) && !!record.eventLog && typeof record.eventLog === "object";
647
- }
648
- function hasStringFields(record, keys) {
649
- return keys.every((key) => typeof record[key] === "string");
650
- }
651
- function parseQueueOwnerMessage(raw) {
652
- const message = asRecord$2(raw);
653
- if (!message || typeof message.type !== "string" || typeof message.requestId !== "string") return null;
654
- const ownerGeneration = parseOwnerGeneration(message.ownerGeneration);
655
- if (ownerGeneration === null) return null;
656
- return parseTypedQueueOwnerMessage(message, {
657
- requestId: message.requestId,
658
- ownerGeneration
659
- });
660
- }
661
- function parseTypedQueueOwnerMessage(message, context) {
662
- const parser = queueOwnerMessageParser(message.type);
663
- return parser ? parser(message, context) : null;
664
- }
665
- const QUEUE_OWNER_MESSAGE_PARSERS = {
666
- accepted: (_message, context) => ({
667
- type: "accepted",
668
- ...context
669
- }),
670
- event: parseEventOwnerMessage,
671
- permission_escalation: parsePermissionEscalationOwnerMessage,
672
- result: parseResultOwnerMessage,
673
- cancel_result: (message, context) => parseBooleanResultOwnerMessage(message, context, "cancel_result", "cancelled"),
674
- close_session_result: (message, context) => parseBooleanResultOwnerMessage(message, context, "close_session_result", "closed"),
675
- set_mode_result: (message, context) => parseStringResultOwnerMessage(message, context, "set_mode_result", "modeId"),
676
- set_model_result: parseSetModelOwnerMessage,
677
- set_config_option_result: parseSetConfigOptionOwnerMessage,
678
- error: parseErrorOwnerMessage
679
- };
680
- function queueOwnerMessageParser(type) {
681
- return Object.hasOwn(QUEUE_OWNER_MESSAGE_PARSERS, type) ? QUEUE_OWNER_MESSAGE_PARSERS[type] : void 0;
682
- }
683
- function parseEventOwnerMessage(message, context) {
684
- if (!isAcpJsonRpcMessage(message.message)) return null;
685
- return {
686
- type: "event",
687
- ...context,
688
- message: message.message
689
- };
690
- }
691
- function parsePermissionEscalationOwnerMessage(message, context) {
692
- if (!isPermissionEscalationEvent(message.event)) return null;
693
- return {
694
- type: "permission_escalation",
695
- ...context,
696
- event: message.event
697
- };
698
- }
699
- function parseResultOwnerMessage(message, context) {
700
- const result = parseSessionSendResult(message.result);
701
- if (!result) return null;
702
- return {
703
- type: "result",
704
- ...context,
705
- result
706
- };
707
- }
708
- function parseBooleanResultOwnerMessage(message, context, type, field) {
709
- if (typeof message[field] !== "boolean") return null;
710
- return {
711
- type,
712
- ...context,
713
- [field]: message[field]
714
- };
715
- }
716
- function parseStringResultOwnerMessage(message, context, type, field) {
717
- if (typeof message[field] !== "string") return null;
718
- return {
719
- type,
720
- ...context,
721
- [field]: message[field]
722
- };
723
- }
724
- function parseSetModelOwnerMessage(message, context) {
725
- if (typeof message.modelId !== "string") return null;
726
- const response = asRecord$2(message.response);
727
- if (message.response !== void 0 && (!response || !Array.isArray(response.configOptions))) return null;
728
- return {
729
- type: "set_model_result",
730
- ...context,
731
- modelId: message.modelId,
732
- ...response ? { response } : {}
733
- };
734
- }
735
- function parseSetConfigOptionOwnerMessage(message, context) {
736
- const response = asRecord$2(message.response);
737
- if (!response || !Array.isArray(response.configOptions)) return null;
738
- return {
739
- type: "set_config_option_result",
740
- ...context,
741
- response
742
- };
743
- }
744
- function parseErrorOwnerMessage(message, context) {
745
- if (!isValidOwnerErrorCore(message)) return null;
746
- const outputAlreadyEmitted = typeof message.outputAlreadyEmitted === "boolean" ? message.outputAlreadyEmitted : void 0;
747
- return {
748
- type: "error",
749
- ...context,
750
- code: message.code,
751
- detailCode: parseNonEmptyString(message.detailCode) ?? void 0,
752
- origin: message.origin,
753
- message: message.message,
754
- retryable: typeof message.retryable === "boolean" ? message.retryable : void 0,
755
- acp: toAcpErrorPayload(message.acp),
756
- ...outputAlreadyEmitted === void 0 ? {} : { outputAlreadyEmitted }
757
- };
758
- }
759
- function isValidOwnerErrorCore(message) {
760
- return typeof message.message === "string" && isOutputErrorCode(message.code) && isOutputErrorOrigin(message.origin);
761
- }
762
- //#endregion
763
- //#region src/cli/queue/request-limit.ts
764
- function queueRequestByteLimit(raw = process.env.ACPX_QUEUE_MAX_REQUEST_BYTES) {
765
- if (raw === void 0 || raw.trim() === "") return;
766
- const limit = Number(raw);
767
- if (!Number.isSafeInteger(limit) || limit < 0 || !/^\d+$/.test(raw.trim())) throw new Error("ACPX_QUEUE_MAX_REQUEST_BYTES must be a non-negative safe integer; zero is unlimited");
768
- return limit || void 0;
769
- }
770
- function queueRequestExceedsLimit(line, limit) {
771
- return limit !== void 0 && Buffer.byteLength(line, "utf8") > limit;
772
- }
773
- function assertQueueRequestSize(line) {
774
- const limit = queueRequestByteLimit();
775
- if (queueRequestExceedsLimit(line, limit)) throw new QueueProtocolError(`Queue request exceeded ACPX_QUEUE_MAX_REQUEST_BYTES (${limit} bytes); raise or unset the limit`, {
776
- detailCode: "QUEUE_REQUEST_TOO_LARGE",
777
- origin: "queue",
778
- retryable: false
779
- });
780
- }
781
- //#endregion
782
- //#region src/cli/queue/ipc-server.ts
783
- const QUEUE_SOCKET_DRAIN_TIMEOUT_MS = 1e3;
784
- function makeQueueOwnerError(requestId, message, detailCode, options = {}) {
785
- return {
786
- type: "error",
787
- requestId,
788
- ownerGeneration: void 0,
789
- code: "RUNTIME",
790
- detailCode,
791
- origin: "queue",
792
- retryable: options.retryable,
793
- message
794
- };
795
- }
796
- function makeQueueOwnerErrorFromUnknown(requestId, error, detailCode, options = {}) {
797
- const normalized = normalizeOutputError(error, {
798
- defaultCode: "RUNTIME",
799
- origin: "queue",
800
- detailCode,
801
- retryable: options.retryable
802
- });
803
- return {
804
- type: "error",
805
- requestId,
806
- code: normalized.code,
807
- detailCode: normalized.detailCode,
808
- origin: normalized.origin,
809
- message: normalized.message,
810
- retryable: normalized.retryable,
811
- acp: normalized.acp
812
- };
813
- }
814
- function writeQueueMessage(socket, message) {
815
- if (socket.destroyed || !socket.writable) return;
816
- socket.write(`${JSON.stringify(message)}\n`);
817
- }
818
- var SessionQueueOwner = class SessionQueueOwner {
819
- server;
820
- controlHandlers;
821
- ownerGeneration;
822
- maxQueueDepth;
823
- maxRequestBytes;
824
- onQueueDepthChanged;
825
- pending = [];
826
- waiters = [];
827
- sockets = /* @__PURE__ */ new Set();
828
- taskSockets = /* @__PURE__ */ new Set();
829
- drainingSockets = /* @__PURE__ */ new Set();
830
- closed = false;
831
- constructor(server, controlHandlers, lease, options) {
832
- this.server = server;
833
- this.controlHandlers = controlHandlers;
834
- this.ownerGeneration = lease.ownerGeneration;
835
- this.maxQueueDepth = Math.max(1, Math.round(options.maxQueueDepth));
836
- this.maxRequestBytes = queueRequestByteLimit(options.maxRequestBytes?.toString());
837
- this.onQueueDepthChanged = options.onQueueDepthChanged;
838
- }
839
- static async start(lease, controlHandlers, options = { maxQueueDepth: 16 }) {
840
- const ownerRef = { current: void 0 };
841
- const server = net.createServer((socket) => {
842
- ownerRef.current?.handleConnection(socket);
843
- });
844
- ownerRef.current = new SessionQueueOwner(server, controlHandlers, lease, options);
845
- await new Promise((resolve, reject) => {
846
- const onListening = () => {
847
- server.off("error", onError);
848
- resolve();
849
- };
850
- const onError = (error) => {
851
- server.off("listening", onListening);
852
- reject(error);
853
- };
854
- server.once("listening", onListening);
855
- server.once("error", onError);
856
- server.listen(lease.socketPath);
857
- });
858
- return ownerRef.current;
859
- }
860
- beginShutdown() {
861
- if (this.closed) return;
862
- this.closed = true;
863
- for (const waiter of this.waiters.splice(0)) waiter(void 0);
864
- for (const task of this.pending.splice(0)) {
865
- if (task.waitForCompletion) task.send(makeQueueOwnerError(task.requestId, "Queue owner shutting down before prompt execution", "QUEUE_OWNER_SHUTTING_DOWN", { retryable: true }));
866
- task.close();
867
- }
868
- for (const socket of this.sockets) if (!this.taskSockets.has(socket) && !this.drainingSockets.has(socket)) socket.destroy();
869
- this.emitQueueDepth();
870
- }
871
- async close() {
872
- this.beginShutdown();
873
- await new Promise((resolve) => {
874
- const forceCloseTimer = setTimeout(() => {
875
- for (const socket of this.sockets) socket.destroy();
876
- }, QUEUE_SOCKET_DRAIN_TIMEOUT_MS);
877
- forceCloseTimer.unref();
878
- this.server.close(() => {
879
- clearTimeout(forceCloseTimer);
880
- resolve();
881
- });
882
- });
883
- }
884
- async nextTask(timeoutMs) {
885
- if (this.pending.length > 0) {
886
- const task = this.pending.shift();
887
- this.emitQueueDepth();
888
- if (task) recordPerfDuration("queue.owner.wait_ms", Date.now() - task.enqueuedAt);
889
- return task;
890
- }
891
- if (this.closed) return;
892
- return await new Promise((resolve) => {
893
- const timer = timeoutMs != null && setTimeout(() => {
894
- const index = this.waiters.indexOf(waiter);
895
- if (index >= 0) this.waiters.splice(index, 1);
896
- resolve(void 0);
897
- }, Math.max(0, timeoutMs));
898
- const waiter = (task) => {
899
- if (timer) clearTimeout(timer);
900
- resolve(task);
901
- };
902
- this.waiters.push(waiter);
903
- });
904
- }
905
- queueDepth() {
906
- return this.pending.length;
907
- }
908
- emitQueueDepth() {
909
- this.onQueueDepthChanged?.(this.pending.length);
910
- }
911
- enqueue(task) {
912
- if (this.closed) {
913
- task.send(makeQueueOwnerError(task.requestId, "Queue owner is shutting down", "QUEUE_OWNER_SHUTTING_DOWN", { retryable: true }));
914
- task.close();
915
- return false;
916
- }
917
- const waiter = this.waiters.shift();
918
- if (waiter) {
919
- waiter(task);
920
- return true;
921
- }
922
- if (this.pending.length >= this.maxQueueDepth) {
923
- task.send({
924
- ...makeQueueOwnerError(task.requestId, `Queue owner is overloaded (${this.pending.length}/${this.maxQueueDepth} queued)`, "QUEUE_OWNER_OVERLOADED", { retryable: true }),
925
- ownerGeneration: this.ownerGeneration
926
- });
927
- task.close();
928
- return false;
929
- }
930
- this.pending.push(task);
931
- this.emitQueueDepth();
932
- return true;
933
- }
934
- handleControlRequest(options) {
935
- writeQueueMessage(options.socket, {
936
- type: "accepted",
937
- requestId: options.requestId,
938
- ownerGeneration: this.ownerGeneration
939
- });
940
- options.run().then((message) => {
941
- writeQueueMessage(options.socket, {
942
- ...message,
943
- ownerGeneration: this.ownerGeneration
944
- });
945
- }).catch((error) => {
946
- writeQueueMessage(options.socket, {
947
- ...makeQueueOwnerErrorFromUnknown(options.requestId, error, "QUEUE_CONTROL_REQUEST_FAILED"),
948
- ownerGeneration: this.ownerGeneration
949
- });
950
- }).finally(() => {
951
- this.endSocket(options.socket);
952
- });
953
- }
954
- endSocket(socket) {
955
- if (socket.destroyed || this.drainingSockets.has(socket)) return;
956
- this.taskSockets.delete(socket);
957
- this.drainingSockets.add(socket);
958
- socket.end(() => {
959
- this.drainingSockets.delete(socket);
960
- socket.destroy();
961
- });
962
- }
963
- failRequest(socket, requestId, message, detailCode) {
964
- writeQueueMessage(socket, {
965
- ...makeQueueOwnerError(requestId, message, detailCode, { retryable: false }),
966
- ownerGeneration: this.ownerGeneration
967
- });
968
- this.endSocket(socket);
969
- }
970
- parseRequestLine(socket, line) {
971
- let parsed;
972
- try {
973
- parsed = JSON.parse(line);
974
- } catch {
975
- this.failRequest(socket, "unknown", "Invalid queue request payload", "QUEUE_REQUEST_PAYLOAD_INVALID_JSON");
976
- return;
977
- }
978
- const request = parseQueueRequest(parsed);
979
- if (!request) this.failRequest(socket, "unknown", "Invalid queue request", "QUEUE_REQUEST_INVALID");
980
- return request ?? void 0;
981
- }
982
- rejectStaleOwnerGeneration(socket, request) {
983
- if (request.ownerGeneration === void 0 || this.ownerGeneration === void 0 || request.ownerGeneration === this.ownerGeneration) return false;
984
- this.failRequest(socket, request.requestId, "Queue request targeted a stale queue owner generation", "QUEUE_OWNER_GENERATION_MISMATCH");
985
- return true;
986
- }
987
- rejectClosedOwner(socket, request) {
988
- if (!this.closed) return false;
989
- writeQueueMessage(socket, {
990
- ...makeQueueOwnerError(request.requestId, "Queue owner is shutting down", "QUEUE_OWNER_CLOSED", { retryable: true }),
991
- ownerGeneration: this.ownerGeneration
992
- });
993
- this.endSocket(socket);
994
- return true;
995
- }
996
- handleControlQueueRequest(socket, request) {
997
- if (request.type === "cancel_prompt") {
998
- this.handleControlRequest({
999
- socket,
1000
- requestId: request.requestId,
1001
- run: async () => ({
1002
- type: "cancel_result",
1003
- requestId: request.requestId,
1004
- cancelled: await this.controlHandlers.cancelPrompt()
1005
- })
1006
- });
1007
- return true;
1008
- }
1009
- if (request.type === "close_session") {
1010
- this.handleControlRequest({
1011
- socket,
1012
- requestId: request.requestId,
1013
- run: async () => ({
1014
- type: "close_session_result",
1015
- requestId: request.requestId,
1016
- closed: await this.controlHandlers.closeSession(request.timeoutMs)
1017
- })
1018
- });
1019
- return true;
1020
- }
1021
- return this.handleSessionControlQueueRequest(socket, request);
1022
- }
1023
- handleSessionControlQueueRequest(socket, request) {
1024
- if (request.type === "set_mode") {
1025
- this.handleControlRequest({
1026
- socket,
1027
- requestId: request.requestId,
1028
- run: async () => {
1029
- await this.controlHandlers.setSessionMode(request.modeId, request.timeoutMs);
1030
- return {
1031
- type: "set_mode_result",
1032
- requestId: request.requestId,
1033
- modeId: request.modeId
1034
- };
1035
- }
1036
- });
1037
- return true;
1038
- }
1039
- if (request.type === "set_model") {
1040
- this.handleControlRequest({
1041
- socket,
1042
- requestId: request.requestId,
1043
- run: async () => {
1044
- const response = await this.controlHandlers.setSessionModel(request.modelId, request.timeoutMs);
1045
- return {
1046
- type: "set_model_result",
1047
- requestId: request.requestId,
1048
- modelId: request.modelId,
1049
- response
1050
- };
1051
- }
1052
- });
1053
- return true;
1054
- }
1055
- if (request.type === "set_config_option") {
1056
- this.handleControlRequest({
1057
- socket,
1058
- requestId: request.requestId,
1059
- run: async () => ({
1060
- type: "set_config_option_result",
1061
- requestId: request.requestId,
1062
- response: await this.controlHandlers.setSessionConfigOption(request.configId, request.value, request.timeoutMs)
1063
- })
1064
- });
1065
- return true;
1066
- }
1067
- return false;
1068
- }
1069
- enqueuePromptRequest(socket, request) {
1070
- this.taskSockets.add(socket);
1071
- const task = {
1072
- requestId: request.requestId,
1073
- message: request.message,
1074
- prompt: request.prompt ?? textPrompt(request.message),
1075
- permissionMode: request.permissionMode,
1076
- resumePolicy: request.resumePolicy,
1077
- nonInteractivePermissions: request.nonInteractivePermissions,
1078
- permissionPolicy: request.permissionPolicy,
1079
- timeoutMs: request.timeoutMs,
1080
- suppressSdkConsoleErrors: request.suppressSdkConsoleErrors,
1081
- promptRetries: request.promptRetries,
1082
- sessionOptions: request.sessionOptions,
1083
- waitForCompletion: request.waitForCompletion,
1084
- enqueuedAt: Date.now(),
1085
- send: (message) => {
1086
- writeQueueMessage(socket, {
1087
- ...message,
1088
- ownerGeneration: this.ownerGeneration
1089
- });
1090
- },
1091
- close: () => {
1092
- this.endSocket(socket);
1093
- }
1094
- };
1095
- if (!this.enqueue(task)) return;
1096
- writeQueueMessage(socket, {
1097
- type: "accepted",
1098
- requestId: request.requestId,
1099
- ownerGeneration: this.ownerGeneration
1100
- });
1101
- if (!request.waitForCompletion) task.close();
1102
- }
1103
- handleConnection(socket) {
1104
- this.sockets.add(socket);
1105
- socket.setEncoding("utf8");
1106
- socket.once("close", () => {
1107
- this.sockets.delete(socket);
1108
- this.taskSockets.delete(socket);
1109
- this.drainingSockets.delete(socket);
1110
- });
1111
- let buffer = "";
1112
- let handled = false;
1113
- const processLine = (line) => {
1114
- if (handled) return;
1115
- handled = true;
1116
- const request = this.parseRequestLine(socket, line);
1117
- if (!request || this.rejectClosedOwner(socket, request) || this.rejectStaleOwnerGeneration(socket, request)) return;
1118
- if (this.handleControlQueueRequest(socket, request)) return;
1119
- if (request.type !== "submit_prompt") {
1120
- this.failRequest(socket, request.requestId, "Invalid queue request", "QUEUE_REQUEST_INVALID");
1121
- return;
1122
- }
1123
- this.enqueuePromptRequest(socket, request);
1124
- };
1125
- socket.on("data", (chunk) => {
1126
- buffer += chunk;
1127
- let index = buffer.indexOf("\n");
1128
- while (index >= 0) {
1129
- const rawLine = buffer.slice(0, index);
1130
- if (this.rejectOversizedRequest(socket, rawLine)) return;
1131
- const line = rawLine.trim();
1132
- buffer = buffer.slice(index + 1);
1133
- if (line.length > 0) processLine(line);
1134
- index = buffer.indexOf("\n");
1135
- }
1136
- this.rejectOversizedRequest(socket, buffer);
1137
- });
1138
- socket.on("error", () => {});
1139
- }
1140
- rejectOversizedRequest(socket, line) {
1141
- if (!queueRequestExceedsLimit(line, this.maxRequestBytes)) return false;
1142
- socket.destroy();
1143
- return true;
1144
- }
1145
- };
1146
- //#endregion
1147
- //#region src/cli/queue/ipc.ts
1148
- const MAX_MESSAGE_BUFFER_SIZE = 10485760;
1149
- const STALE_OWNER_PROTOCOL_DETAIL_CODES = /* @__PURE__ */ new Set(["QUEUE_PROTOCOL_MALFORMED_MESSAGE", "QUEUE_PROTOCOL_UNEXPECTED_RESPONSE"]);
1150
- async function maybeRecoverStaleOwnerAfterProtocolMismatch(params) {
1151
- if (!(params.error instanceof QueueProtocolError)) return false;
1152
- const detailCode = params.error.detailCode;
1153
- if (!detailCode || !STALE_OWNER_PROTOCOL_DETAIL_CODES.has(detailCode)) return false;
1154
- await terminateQueueOwnerForSession(params.sessionId).catch(() => {});
1155
- incrementPerfCounter("queue.owner.stale_recovered");
1156
- if (params.verbose) process.stderr.write(`[acpx] dropped stale queue owner metadata after protocol mismatch for session ${params.sessionId} (${detailCode})\n`);
1157
- return true;
1158
- }
1159
- function assertOwnerGeneration(owner, message) {
1160
- if (owner.ownerGeneration !== void 0 && message.ownerGeneration !== void 0 && message.ownerGeneration !== owner.ownerGeneration) throw new QueueProtocolError("Queue owner returned mismatched generation", {
1161
- detailCode: "QUEUE_OWNER_GENERATION_MISMATCH",
1162
- origin: "queue",
1163
- retryable: true
1164
- });
1165
- return message;
1166
- }
1167
- function queueConnectionErrorFromOwner(message, outputAlreadyEmitted) {
1168
- return new QueueConnectionError(message.message, {
1169
- outputCode: message.code,
1170
- detailCode: message.detailCode,
1171
- origin: message.origin ?? "queue",
1172
- retryable: message.retryable,
1173
- acp: message.acp,
1174
- ...outputAlreadyEmitted ? { outputAlreadyEmitted: true } : {}
1175
- });
1176
- }
1177
- function makeMalformedQueueMessageError() {
1178
- return new QueueProtocolError("Queue owner sent malformed message", {
1179
- detailCode: "QUEUE_PROTOCOL_MALFORMED_MESSAGE",
1180
- origin: "queue",
1181
- retryable: true
1182
- });
1183
- }
1184
- function emitQueueOwnerError(formatter, policy, sessionId, message) {
1185
- formatter.setContext({ sessionId });
1186
- const queueErrorAlreadyEmitted = policy?.queueErrorAlreadyEmitted ?? true;
1187
- const shouldEmitInFormatter = message.outputAlreadyEmitted !== true || !queueErrorAlreadyEmitted;
1188
- if (shouldEmitInFormatter) {
1189
- formatter.onError({
1190
- code: message.code ?? "RUNTIME",
1191
- detailCode: message.detailCode,
1192
- origin: message.origin ?? "queue",
1193
- message: message.message,
1194
- retryable: message.retryable,
1195
- acp: message.acp
1196
- });
1197
- formatter.flush();
1198
- }
1199
- return queueConnectionErrorFromOwner(message, queueErrorAlreadyEmitted || shouldEmitInFormatter);
1200
- }
1201
- function parseQueueOwnerResponseLine(owner, requestId, line) {
1202
- let parsed;
1203
- try {
1204
- parsed = JSON.parse(line);
1205
- } catch {
1206
- throw new QueueProtocolError("Queue owner sent invalid JSON payload", {
1207
- detailCode: "QUEUE_PROTOCOL_INVALID_JSON",
1208
- origin: "queue",
1209
- retryable: true
1210
- });
1211
- }
1212
- const parsedMessage = parseQueueOwnerMessage(parsed);
1213
- if (!parsedMessage) throw makeMalformedQueueMessageError();
1214
- const message = assertOwnerGeneration(owner, parsedMessage);
1215
- if (message.requestId !== requestId) throw makeMalformedQueueMessageError();
1216
- return message;
1217
- }
1218
- async function runQueueOwnerRequest(options) {
1219
- const requestLine = JSON.stringify(options.request);
1220
- assertQueueRequestSize(requestLine);
1221
- const socket = await connectToQueueOwner(options.owner);
1222
- if (!socket) return;
1223
- socket.setEncoding("utf8");
1224
- return await new Promise((resolve, reject) => {
1225
- let settled = false;
1226
- let buffer = "";
1227
- const state = { acknowledged: false };
1228
- const finishResolve = (result) => {
1229
- if (settled) return;
1230
- settled = true;
1231
- socket.removeAllListeners();
1232
- if (!socket.destroyed) socket.end();
1233
- resolve(result);
1234
- };
1235
- const finishReject = (error) => {
1236
- if (settled) return;
1237
- settled = true;
1238
- socket.removeAllListeners();
1239
- if (!socket.destroyed) socket.destroy();
1240
- reject(error);
1241
- };
1242
- const controls = {
1243
- state,
1244
- resolve: finishResolve,
1245
- reject: finishReject
1246
- };
1247
- const processLine = (line) => {
1248
- let message;
1249
- try {
1250
- message = parseQueueOwnerResponseLine(options.owner, options.request.requestId, line);
1251
- } catch (error) {
1252
- finishReject(error);
1253
- return;
1254
- }
1255
- if (message.type === "accepted") {
1256
- state.acknowledged = true;
1257
- options.onAccepted?.(controls);
1258
- return;
1259
- }
1260
- options.onMessage(message, controls);
1261
- };
1262
- socket.on("data", (chunk) => {
1263
- buffer += chunk;
1264
- if (buffer.length > 10485760) {
1265
- socket.destroy();
1266
- finishReject(/* @__PURE__ */ new Error(`Message buffer exceeded ${MAX_MESSAGE_BUFFER_SIZE} bytes`));
1267
- return;
1268
- }
1269
- let index = buffer.indexOf("\n");
1270
- while (index >= 0) {
1271
- const line = buffer.slice(0, index).trim();
1272
- buffer = buffer.slice(index + 1);
1273
- if (line.length > 0) processLine(line);
1274
- index = buffer.indexOf("\n");
1275
- }
1276
- });
1277
- socket.once("error", (error) => {
1278
- finishReject(error);
1279
- });
1280
- socket.once("close", () => {
1281
- if (settled) return;
1282
- options.onClose(controls);
1283
- });
1284
- socket.write(`${requestLine}\n`);
1285
- });
1286
- }
1287
- function missingQueueAckError() {
1288
- return new QueueConnectionError("Queue owner did not acknowledge request", {
1289
- detailCode: "QUEUE_ACK_MISSING",
1290
- origin: "queue",
1291
- retryable: true
1292
- });
1293
- }
1294
- function unexpectedQueueResponseError() {
1295
- return new QueueProtocolError("Queue owner returned unexpected response", {
1296
- detailCode: "QUEUE_PROTOCOL_UNEXPECTED_RESPONSE",
1297
- origin: "queue",
1298
- retryable: true
1299
- });
1300
- }
1301
- function handleAcknowledgedSubmitMessage(message, controls, formatter) {
1302
- if (message.type === "event") {
1303
- formatter.onAcpMessage(message.message);
1304
- return;
1305
- }
1306
- if (message.type === "permission_escalation") {
1307
- formatter.onPermissionEscalation(message.event);
1308
- return;
1309
- }
1310
- if (message.type === "result") {
1311
- formatter.flush();
1312
- controls.resolve(message.result);
1313
- return;
1314
- }
1315
- controls.reject(unexpectedQueueResponseError());
1316
- }
1317
- function handleSubmitQueueOwnerMessage(message, controls, options) {
1318
- if (message.type === "error") {
1319
- controls.reject(emitQueueOwnerError(options.outputFormatter, options.errorEmissionPolicy, options.sessionId, message));
1320
- return;
1321
- }
1322
- if (!controls.state.acknowledged) {
1323
- controls.reject(missingQueueAckError());
1324
- return;
1325
- }
1326
- handleAcknowledgedSubmitMessage(message, controls, options.outputFormatter);
1327
- }
1328
- async function submitToQueueOwner(owner, options) {
1329
- const requestId = randomUUID();
1330
- const request = {
1331
- type: "submit_prompt",
1332
- requestId,
1333
- ownerGeneration: owner.ownerGeneration,
1334
- message: options.message,
1335
- prompt: options.prompt,
1336
- permissionMode: options.permissionMode,
1337
- resumePolicy: options.resumePolicy,
1338
- nonInteractivePermissions: options.nonInteractivePermissions,
1339
- permissionPolicy: options.permissionPolicy,
1340
- timeoutMs: options.timeoutMs,
1341
- suppressSdkConsoleErrors: options.suppressSdkConsoleErrors,
1342
- promptRetries: options.promptRetries ?? 0,
1343
- waitForCompletion: options.waitForCompletion,
1344
- sessionOptions: options.sessionOptions
1345
- };
1346
- options.outputFormatter.setContext({ sessionId: options.sessionId });
1347
- return await runQueueOwnerRequest({
1348
- owner,
1349
- request,
1350
- onAccepted: ({ resolve }) => {
1351
- options.onQueueAccepted?.();
1352
- options.outputFormatter.setContext({ sessionId: options.sessionId });
1353
- if (!options.waitForCompletion) resolve({
1354
- queued: true,
1355
- sessionId: options.sessionId,
1356
- requestId
1357
- });
1358
- },
1359
- onMessage: (message, controls) => {
1360
- handleSubmitQueueOwnerMessage(message, controls, options);
1361
- },
1362
- onClose: ({ state, resolve, reject }) => {
1363
- if (!state.acknowledged) {
1364
- reject(new QueueConnectionError("Queue owner disconnected before acknowledging request", {
1365
- detailCode: "QUEUE_DISCONNECTED_BEFORE_ACK",
1366
- origin: "queue",
1367
- retryable: true
1368
- }));
1369
- return;
1370
- }
1371
- if (!options.waitForCompletion) {
1372
- resolve({
1373
- queued: true,
1374
- sessionId: options.sessionId,
1375
- requestId
1376
- });
1377
- return;
1378
- }
1379
- reject(new QueueConnectionError("Queue owner disconnected before prompt completion", {
1380
- detailCode: "QUEUE_DISCONNECTED_BEFORE_COMPLETION",
1381
- origin: "queue",
1382
- retryable: true
1383
- }));
1384
- }
1385
- });
1386
- }
1387
- async function submitControlToQueueOwner(owner, request, isExpectedResponse) {
1388
- return await runQueueOwnerRequest({
1389
- owner,
1390
- request,
1391
- onMessage: (message, { state, resolve, reject }) => {
1392
- if (message.type === "error") {
1393
- reject(new QueueConnectionError(message.message, {
1394
- outputCode: message.code,
1395
- detailCode: message.detailCode,
1396
- origin: message.origin ?? "queue",
1397
- retryable: message.retryable,
1398
- acp: message.acp
1399
- }));
1400
- return;
1401
- }
1402
- if (!state.acknowledged) {
1403
- reject(new QueueConnectionError("Queue owner did not acknowledge request", {
1404
- detailCode: "QUEUE_ACK_MISSING",
1405
- origin: "queue",
1406
- retryable: true
1407
- }));
1408
- return;
1409
- }
1410
- if (!isExpectedResponse(message)) {
1411
- reject(new QueueProtocolError("Queue owner returned unexpected response", {
1412
- detailCode: "QUEUE_PROTOCOL_UNEXPECTED_RESPONSE",
1413
- origin: "queue",
1414
- retryable: true
1415
- }));
1416
- return;
1417
- }
1418
- resolve(message);
1419
- },
1420
- onClose: ({ state, reject }) => {
1421
- if (!state.acknowledged) {
1422
- reject(new QueueConnectionError("Queue owner disconnected before acknowledging request", {
1423
- detailCode: "QUEUE_DISCONNECTED_BEFORE_ACK",
1424
- origin: "queue",
1425
- retryable: true
1426
- }));
1427
- return;
1428
- }
1429
- reject(new QueueConnectionError("Queue owner disconnected before responding", {
1430
- detailCode: "QUEUE_DISCONNECTED_BEFORE_COMPLETION",
1431
- origin: "queue",
1432
- retryable: true
1433
- }));
1434
- }
1435
- });
1436
- }
1437
- async function submitCancelToQueueOwner(owner) {
1438
- const request = {
1439
- type: "cancel_prompt",
1440
- requestId: randomUUID(),
1441
- ownerGeneration: owner.ownerGeneration
1442
- };
1443
- const response = await submitControlToQueueOwner(owner, request, (message) => message.type === "cancel_result");
1444
- if (!response) return;
1445
- if (response.requestId !== request.requestId) throw new QueueProtocolError("Queue owner returned mismatched cancel response", {
1446
- detailCode: "QUEUE_PROTOCOL_MALFORMED_MESSAGE",
1447
- origin: "queue",
1448
- retryable: true
1449
- });
1450
- return response.cancelled;
1451
- }
1452
- async function submitSetModeToQueueOwner(owner, modeId, timeoutMs) {
1453
- const request = {
1454
- type: "set_mode",
1455
- requestId: randomUUID(),
1456
- ownerGeneration: owner.ownerGeneration,
1457
- modeId,
1458
- timeoutMs
1459
- };
1460
- const response = await submitControlToQueueOwner(owner, request, (message) => message.type === "set_mode_result");
1461
- if (!response) return;
1462
- if (response.requestId !== request.requestId) throw new QueueProtocolError("Queue owner returned mismatched set_mode response", {
1463
- detailCode: "QUEUE_PROTOCOL_MALFORMED_MESSAGE",
1464
- origin: "queue",
1465
- retryable: true
1466
- });
1467
- return true;
1468
- }
1469
- async function submitSetModelToQueueOwner(owner, modelId, timeoutMs) {
1470
- const request = {
1471
- type: "set_model",
1472
- requestId: randomUUID(),
1473
- ownerGeneration: owner.ownerGeneration,
1474
- modelId,
1475
- timeoutMs
1476
- };
1477
- const response = await submitControlToQueueOwner(owner, request, (message) => message.type === "set_model_result");
1478
- if (!response) return;
1479
- if (response.requestId !== request.requestId) throw new QueueProtocolError("Queue owner returned mismatched set_model response", {
1480
- detailCode: "QUEUE_PROTOCOL_MALFORMED_MESSAGE",
1481
- origin: "queue",
1482
- retryable: true
1483
- });
1484
- return response;
1485
- }
1486
- async function submitSetConfigOptionToQueueOwner(owner, configId, value, timeoutMs) {
1487
- const request = {
1488
- type: "set_config_option",
1489
- requestId: randomUUID(),
1490
- ownerGeneration: owner.ownerGeneration,
1491
- configId,
1492
- value,
1493
- timeoutMs
1494
- };
1495
- const response = await submitControlToQueueOwner(owner, request, (message) => message.type === "set_config_option_result");
1496
- if (!response) return;
1497
- if (response.requestId !== request.requestId) throw new QueueProtocolError("Queue owner returned mismatched set_config_option response", {
1498
- detailCode: "QUEUE_PROTOCOL_MALFORMED_MESSAGE",
1499
- origin: "queue",
1500
- retryable: true
1501
- });
1502
- return response.response;
1503
- }
1504
- async function submitCloseSessionToQueueOwner(owner, timeoutMs) {
1505
- const request = {
1506
- type: "close_session",
1507
- requestId: randomUUID(),
1508
- ownerGeneration: owner.ownerGeneration,
1509
- timeoutMs
1510
- };
1511
- const response = await submitControlToQueueOwner(owner, request, (message) => message.type === "close_session_result");
1512
- if (!response) return;
1513
- if (response.requestId !== request.requestId) throw new QueueProtocolError("Queue owner returned mismatched close_session response", {
1514
- detailCode: "QUEUE_PROTOCOL_MALFORMED_MESSAGE",
1515
- origin: "queue",
1516
- retryable: true
1517
- });
1518
- return response.closed;
1519
- }
1520
- function queueOwnerMcpConfigMatches(owner, options) {
1521
- return owner.mcpConfigPath === options.mcpConfigPath && owner.mcpConfigFingerprint === options.mcpConfigFingerprint;
1522
- }
1523
- function assertQueueOwnerMcpConfigMatches(owner, options) {
1524
- if (queueOwnerMcpConfigMatches(owner, options)) return;
1525
- throw new QueueConnectionError("Session queue owner uses a different MCP config; close the session before retrying", {
1526
- detailCode: "QUEUE_MCP_CONFIG_CONFLICT",
1527
- origin: "queue",
1528
- retryable: false
1529
- });
1530
- }
1531
- async function trySubmitToRunningOwner(options) {
1532
- const owner = await readQueueOwnerRecord(options.sessionId);
1533
- if (!owner) return;
1534
- if (!await ensureOwnerIsUsable(options.sessionId, owner)) return;
1535
- assertQueueOwnerMcpConfigMatches(owner, options);
1536
- let submitted;
1537
- try {
1538
- submitted = await submitToQueueOwner(owner, options);
1539
- } catch (error) {
1540
- if (await maybeRecoverStaleOwnerAfterProtocolMismatch({
1541
- sessionId: options.sessionId,
1542
- owner,
1543
- error,
1544
- verbose: options.verbose
1545
- })) return;
1546
- throw error;
1547
- }
1548
- if (submitted) {
1549
- if (options.verbose) process.stderr.write(`[acpx] queued prompt on active owner pid ${owner.pid} for session ${options.sessionId}\n`);
1550
- return submitted;
1551
- }
1552
- if (!(await probeQueueOwnerHealth(options.sessionId)).hasLease) return;
1553
- throw new QueueConnectionError("Session queue owner is running but not accepting queue requests", {
1554
- detailCode: "QUEUE_NOT_ACCEPTING_REQUESTS",
1555
- origin: "queue",
1556
- retryable: true
1557
- });
1558
- }
1559
- async function tryCloseSessionOnRunningOwner(options) {
1560
- const owner = await readQueueOwnerRecord(options.sessionId);
1561
- if (!owner) return;
1562
- const closed = await submitCloseSessionToQueueOwner(owner, options.timeoutMs);
1563
- if (closed !== void 0) {
1564
- if (options.verbose) process.stderr.write(`[acpx] requested session/close on active owner pid ${owner.pid} for session ${options.sessionId}\n`);
1565
- return closed;
1566
- }
1567
- if (!(await probeQueueOwnerHealth(options.sessionId)).hasLease) return;
1568
- throw new QueueConnectionError("Session queue owner is running but not accepting close_session requests", {
1569
- detailCode: "QUEUE_NOT_ACCEPTING_REQUESTS",
1570
- origin: "queue",
1571
- retryable: true
1572
- });
1573
- }
1574
- async function tryCancelOnRunningOwner(options) {
1575
- const owner = await readQueueOwnerRecord(options.sessionId);
1576
- if (!owner) return;
1577
- const cancelled = await submitCancelToQueueOwner(owner);
1578
- if (cancelled !== void 0) {
1579
- if (options.verbose) process.stderr.write(`[acpx] requested cancel on active owner pid ${owner.pid} for session ${options.sessionId}\n`);
1580
- return cancelled;
1581
- }
1582
- if (!(await probeQueueOwnerHealth(options.sessionId)).hasLease) return;
1583
- throw new QueueConnectionError("Session queue owner is running but not accepting cancel requests", {
1584
- detailCode: "QUEUE_NOT_ACCEPTING_REQUESTS",
1585
- origin: "queue",
1586
- retryable: true
1587
- });
1588
- }
1589
- async function trySetModeOnRunningOwner(sessionId, modeId, timeoutMs, verbose) {
1590
- const owner = await readQueueOwnerRecord(sessionId);
1591
- if (!owner) return;
1592
- if (await submitSetModeToQueueOwner(owner, modeId, timeoutMs)) {
1593
- if (verbose) process.stderr.write(`[acpx] requested session/set_mode on owner pid ${owner.pid} for session ${sessionId}\n`);
1594
- return true;
1595
- }
1596
- if (!(await probeQueueOwnerHealth(sessionId)).hasLease) return;
1597
- throw new QueueConnectionError("Session queue owner is running but not accepting set_mode requests", {
1598
- detailCode: "QUEUE_NOT_ACCEPTING_REQUESTS",
1599
- origin: "queue",
1600
- retryable: true
1601
- });
1602
- }
1603
- async function trySetModelOnRunningOwner(sessionId, modelId, timeoutMs, verbose) {
1604
- const owner = await readQueueOwnerRecord(sessionId);
1605
- if (!owner) return;
1606
- const submitted = await submitSetModelToQueueOwner(owner, modelId, timeoutMs);
1607
- if (submitted) {
1608
- if (verbose) process.stderr.write(`[acpx] requested a model config update on owner pid ${owner.pid} for session ${sessionId}\n`);
1609
- return submitted;
1610
- }
1611
- if (!(await probeQueueOwnerHealth(sessionId)).hasLease) return;
1612
- throw new QueueConnectionError("Session queue owner is running but not accepting set_model requests", {
1613
- detailCode: "QUEUE_NOT_ACCEPTING_REQUESTS",
1614
- origin: "queue",
1615
- retryable: true
1616
- });
1617
- }
1618
- async function trySetConfigOptionOnRunningOwner(sessionId, configId, value, timeoutMs, verbose) {
1619
- const owner = await readQueueOwnerRecord(sessionId);
1620
- if (!owner) return;
1621
- const response = await submitSetConfigOptionToQueueOwner(owner, configId, value, timeoutMs);
1622
- if (response) {
1623
- if (verbose) process.stderr.write(`[acpx] requested session/set_config_option on owner pid ${owner.pid} for session ${sessionId}\n`);
1624
- return response;
1625
- }
1626
- if (!(await probeQueueOwnerHealth(sessionId)).hasLease) return;
1627
- throw new QueueConnectionError("Session queue owner is running but not accepting set_config_option requests", {
1628
- detailCode: "QUEUE_NOT_ACCEPTING_REQUESTS",
1629
- origin: "queue",
1630
- retryable: true
1631
- });
1632
- }
1633
- //#endregion
1634
- //#region src/cli/session/prompt-runner.ts
1635
- function buildDirectConnectedSessionOptions(options, run) {
1636
- return {
1637
- sessionRecordId: options.sessionRecordId,
1638
- replacingConfigOption: options.replacingConfigOption,
1639
- loadRecord: resolveSessionRecord,
1640
- saveRecord: writeSessionRecord,
1641
- mcpServers: options.mcpServers,
1642
- nonInteractivePermissions: options.nonInteractivePermissions,
1643
- authCredentials: options.authCredentials,
1644
- authPolicy: options.authPolicy,
1645
- fs: options.fs,
1646
- terminal: options.terminal,
1647
- timeoutMs: options.timeoutMs,
1648
- verbose: options.verbose,
1649
- onClientAvailable: (controller) => {
1650
- options.onClientAvailable?.(controller);
1651
- },
1652
- onClientClosed: options.onClientClosed,
1653
- run
1654
- };
1655
- }
1656
- function toSessionMutationResult(result) {
1657
- return {
1658
- record: result.record,
1659
- resumed: result.resumed,
1660
- loadError: result.loadError
1661
- };
1662
- }
1663
- async function runSessionSetModeDirect(options) {
1664
- return toSessionMutationResult(await withConnectedSession(buildDirectConnectedSessionOptions(options, async ({ client, sessionId, record }) => {
1665
- await withTimeout(client.setSessionMode(sessionId, options.modeId), options.timeoutMs);
1666
- setDesiredModeId(record, options.modeId);
1667
- })));
1668
- }
1669
- async function runSessionSetModelDirect(options) {
1670
- const result = await withConnectedSession(buildDirectConnectedSessionOptions({
1671
- ...options,
1672
- replacingConfigOption: { key: "model" }
1673
- }, async ({ client, sessionId, record }) => {
1674
- const models = advertisedModelState(record.acpx);
1675
- const response = await withTimeout(client.setSessionModel(sessionId, options.modelId, models), options.timeoutMs);
1676
- record.acpx = applyModelSelection(record.acpx, options.modelId, response);
1677
- return response;
1678
- }));
1679
- return {
1680
- ...toSessionMutationResult(result),
1681
- response: result.value
1682
- };
1683
- }
1684
- async function runSessionSetConfigOptionDirect(options) {
1685
- const result = await withConnectedSession(buildDirectConnectedSessionOptions({
1686
- ...options,
1687
- replacingConfigOption: { key: options.configId }
1688
- }, async ({ client, sessionId, record }) => {
1689
- const response = await withTimeout(client.setSessionConfigOption(sessionId, options.configId, options.value), options.timeoutMs);
1690
- record.acpx = applyConfigOptionSelection(record.acpx, options.configId, options.value, response);
1691
- return response;
1692
- }));
1693
- return {
1694
- record: result.record,
1695
- response: result.value,
1696
- resumed: result.resumed,
1697
- loadError: result.loadError
1698
- };
1699
- }
1700
- //#endregion
1701
- //#region src/cli/session/session-control.ts
1702
- async function cancelSessionPrompt(options) {
1703
- const cancelled = await tryCancelOnRunningOwner(options);
1704
- return {
1705
- sessionId: options.sessionId,
1706
- cancelled: cancelled === true
1707
- };
1708
- }
1709
- async function setSessionMode(options) {
1710
- if (await trySetModeOnRunningOwner(options.sessionId, options.modeId, options.timeoutMs, options.verbose)) {
1711
- const record = await resolveSessionRecord(options.sessionId);
1712
- setDesiredModeId(record, options.modeId);
1713
- await writeSessionRecord(record);
1714
- return {
1715
- record,
1716
- resumed: false
1717
- };
1718
- }
1719
- return await runSessionSetModeDirect({
1720
- sessionRecordId: options.sessionId,
1721
- modeId: options.modeId,
1722
- mcpServers: options.mcpServers,
1723
- nonInteractivePermissions: options.nonInteractivePermissions,
1724
- authCredentials: options.authCredentials,
1725
- authPolicy: options.authPolicy,
1726
- fs: options.fs,
1727
- terminal: options.terminal,
1728
- timeoutMs: options.timeoutMs,
1729
- verbose: options.verbose
1730
- });
1731
- }
1732
- async function setSessionModel(options) {
1733
- const submittedToOwner = await trySetModelOnRunningOwner(options.sessionId, options.modelId, options.timeoutMs, options.verbose);
1734
- if (submittedToOwner) {
1735
- const record = await resolveSessionRecord(options.sessionId);
1736
- record.acpx = applyModelSelection(record.acpx, options.modelId, submittedToOwner.response);
1737
- await writeSessionRecord(record);
1738
- return {
1739
- record,
1740
- response: submittedToOwner.response,
1741
- resumed: false
1742
- };
1743
- }
1744
- return await runSessionSetModelDirect({
1745
- sessionRecordId: options.sessionId,
1746
- modelId: options.modelId,
1747
- mcpServers: options.mcpServers,
1748
- nonInteractivePermissions: options.nonInteractivePermissions,
1749
- authCredentials: options.authCredentials,
1750
- authPolicy: options.authPolicy,
1751
- fs: options.fs,
1752
- terminal: options.terminal,
1753
- timeoutMs: options.timeoutMs,
1754
- verbose: options.verbose
1755
- });
1756
- }
1757
- async function setSessionConfigOption(options) {
1758
- const ownerResponse = await trySetConfigOptionOnRunningOwner(options.sessionId, options.configId, options.value, options.timeoutMs, options.verbose);
1759
- if (ownerResponse) {
1760
- const record = await resolveSessionRecord(options.sessionId);
1761
- record.acpx = applyConfigOptionSelection(record.acpx, options.configId, options.value, ownerResponse);
1762
- await writeSessionRecord(record);
1763
- return {
1764
- record,
1765
- response: ownerResponse,
1766
- resumed: false
1767
- };
1768
- }
1769
- return await runSessionSetConfigOptionDirect({
1770
- sessionRecordId: options.sessionId,
1771
- configId: options.configId,
1772
- value: options.value,
1773
- mcpServers: options.mcpServers,
1774
- nonInteractivePermissions: options.nonInteractivePermissions,
1775
- authCredentials: options.authCredentials,
1776
- authPolicy: options.authPolicy,
1777
- fs: options.fs,
1778
- terminal: options.terminal,
1779
- timeoutMs: options.timeoutMs,
1780
- verbose: options.verbose
1781
- });
1782
- }
1783
- function firstAgentCommandToken(command) {
1784
- try {
1785
- return splitCommandLine(command).command || void 0;
1786
- } catch {
1787
- return;
1788
- }
1789
- }
1790
- async function isLikelyMatchingProcess(pid, agentCommand) {
1791
- const expectedToken = firstAgentCommandToken(agentCommand);
1792
- if (!expectedToken) return false;
1793
- const argv = await readProcessArgv(pid);
1794
- if (argv.length === 0) return false;
1795
- const executableBase = path.basename(argv[0]);
1796
- const expectedBase = path.basename(expectedToken);
1797
- return executableBase === expectedBase || argv.some((entry) => path.basename(entry) === expectedBase);
1798
- }
1799
- async function readProcessArgv(pid) {
1800
- const procArgv = await readProcCmdline(pid);
1801
- if (procArgv) return procArgv;
1802
- return splitCommandLineLike(process.platform === "win32" ? await readWindowsCommandLine(pid) : await readPosixCommandLine(pid));
1803
- }
1804
- async function readProcCmdline(pid) {
1805
- try {
1806
- return (await fs$1.readFile(`/proc/${pid}/cmdline`, "utf8")).split("\0").map((entry) => entry.trim()).filter((entry) => entry.length > 0);
1807
- } catch {
1808
- return;
1809
- }
1810
- }
1811
- async function readPosixCommandLine(pid) {
1812
- try {
1813
- return (await runTimedExecFile("ps", [
1814
- "-p",
1815
- String(pid),
1816
- "-o",
1817
- "command="
1818
- ])).trim() || void 0;
1819
- } catch {
1820
- return;
1821
- }
1822
- }
1823
- async function readWindowsCommandLine(pid) {
1824
- try {
1825
- return (await runTimedExecFile("powershell.exe", [
1826
- "-NoProfile",
1827
- "-NonInteractive",
1828
- "-Command",
1829
- `(Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}").CommandLine`
1830
- ], { windowsHide: true })).trim() || void 0;
1831
- } catch {
1832
- return;
1833
- }
1834
- }
1835
- function splitCommandLineLike(commandLine) {
1836
- if (!commandLine) return [];
1837
- try {
1838
- const parsed = splitCommandLine(commandLine);
1839
- return [parsed.command, ...parsed.args];
1840
- } catch {
1841
- return commandLine.split(/\s+/u).map((entry) => entry.trim()).filter((entry) => entry.length > 0);
1842
- }
1843
- }
1844
- const sessionControlTestInternals = {
1845
- firstAgentCommandToken,
1846
- splitCommandLineLike
1847
- };
1848
- async function closeSession(sessionId) {
1849
- const record = await resolveSessionRecord(sessionId);
1850
- await tryCloseSessionOnRunningOwner({ sessionId: record.acpxRecordId }).catch(() => {});
1851
- await terminateQueueOwnerForSession(record.acpxRecordId);
1852
- if (record.pid != null && isProcessAlive(record.pid) && await isLikelyMatchingProcess(record.pid, record.agentCommand)) await terminateProcess(record.pid);
1853
- record.pid = void 0;
1854
- record.closed = true;
1855
- record.closedAt = isoNow();
1856
- await writeSessionRecord(record);
1857
- return record;
1858
- }
1859
- //#endregion
1860
- //#region src/cli/session/session-management.ts
1861
- async function createSessionRecordWithClient(client, options) {
1862
- const cwd = absolutePath(options.cwd);
1863
- await withTimeout(client.start(), options.timeoutMs);
1864
- const createdState = options.resumeSessionId ? await resumeSessionRecordWithClient(client, options, cwd) : await createFreshSessionState(client, options, cwd);
1865
- const { sessionId, agentSessionId } = createdState;
1866
- const lifecycle = client.getAgentLifecycleSnapshot();
1867
- const now = isoNow();
1868
- const record = {
1869
- schema: "acpx.session.v1",
1870
- acpxRecordId: sessionId,
1871
- acpSessionId: sessionId,
1872
- agentSessionId,
1873
- agentCommand: options.agentCommand,
1874
- agentArgv: options.agentArgv,
1875
- cwd,
1876
- name: normalizeName(options.name),
1877
- createdAt: now,
1878
- lastUsedAt: now,
1879
- lastSeq: 0,
1880
- lastRequestId: void 0,
1881
- eventLog: defaultSessionEventLog(sessionId),
1882
- closed: false,
1883
- closedAt: void 0,
1884
- pid: lifecycle.running ? lifecycle.pid : void 0,
1885
- agentStartedAt: lifecycle.startedAt,
1886
- protocolVersion: client.initializeResult?.protocolVersion,
1887
- agentCapabilities: client.initializeResult?.agentCapabilities,
1888
- ...createSessionConversation(now),
1889
- acpx: {}
1890
- };
1891
- persistSessionOptions(record, options.sessionOptions);
1892
- applyCreatedSessionModelState(record, createdState, options.sessionOptions?.model);
1893
- await writeSessionRecord(record);
1894
- return record;
1895
- }
1896
- function applyCreatedSessionModelState(record, state, requestedModel) {
1897
- applyConfigOptionsToRecord(record, state.sessionResult);
1898
- applyConfigOptionsToRecord(record, state.requestedModelResponse);
1899
- syncAdvertisedModelState(record, state.requestedModelResponse ? modelStateFromConfigOptions(state.requestedModelResponse.configOptions) : state.sessionModels);
1900
- if (state.requestedModelApplied) setCurrentModelId(record, currentModelIdFromSetModelResponse(state.requestedModelResponse, requestedModel));
1901
- }
1902
- async function createFreshSessionState(client, options, cwd) {
1903
- const createdSession = await withTimeout(client.createSession(cwd), options.timeoutMs);
1904
- const modelApplication = await applyRequestedModelIfAdvertised({
1905
- client,
1906
- sessionId: createdSession.sessionId,
1907
- requestedModel: options.sessionOptions?.model,
1908
- models: createdSession.models,
1909
- agentCommand: options.agentCommand,
1910
- timeoutMs: options.timeoutMs,
1911
- onWarning: options.onModelWarning
1912
- });
1913
- return {
1914
- sessionId: createdSession.sessionId,
1915
- agentSessionId: normalizeRuntimeSessionId(createdSession.agentSessionId),
1916
- sessionResult: createdSession,
1917
- sessionModels: createdSession.models,
1918
- requestedModelApplied: modelApplication.applied,
1919
- requestedModelResponse: modelApplication.response
1920
- };
1921
- }
1922
- async function resumeSessionRecordWithClient(client, options, cwd) {
1923
- if (!options.resumeSessionId) throw new Error("resumeSessionId is required");
1924
- const resumeMethod = client.supportsResumeSession() ? "session/resume" : client.supportsLoadSession() ? "session/load" : void 0;
1925
- if (!resumeMethod) throw new Error(`Agent command "${options.agentCommand}" does not support session/resume or session/load; cannot resume session ${options.resumeSessionId}`);
1926
- try {
1927
- const resumedSession = await withTimeout(resumeMethod === "session/resume" ? client.resumeSession(options.resumeSessionId, cwd) : client.loadSession(options.resumeSessionId, cwd), options.timeoutMs);
1928
- const sessionModels = resumedSession.models;
1929
- const modelApplication = await applyRequestedModelIfAdvertised({
1930
- client,
1931
- sessionId: options.resumeSessionId,
1932
- requestedModel: options.sessionOptions?.model,
1933
- models: sessionModels,
1934
- agentCommand: options.agentCommand,
1935
- timeoutMs: options.timeoutMs,
1936
- onWarning: options.onModelWarning
1937
- });
1938
- return {
1939
- sessionId: options.resumeSessionId,
1940
- agentSessionId: normalizeRuntimeSessionId(resumedSession.agentSessionId),
1941
- sessionResult: resumedSession,
1942
- sessionModels,
1943
- requestedModelApplied: modelApplication.applied,
1944
- requestedModelResponse: modelApplication.response
1945
- };
1946
- } catch (error) {
1947
- throw new Error(`Failed to resume ACP session ${options.resumeSessionId}: ${formatErrorMessage(error)}`, { cause: error });
1948
- }
1949
- }
1950
- async function createSessionWithClient(options) {
1951
- const client = new AcpClient({
1952
- agentCommand: options.agentCommand,
1953
- agentArgv: options.agentArgv,
1954
- cwd: absolutePath(options.cwd),
1955
- mcpServers: options.mcpServers,
1956
- permissionMode: options.permissionMode,
1957
- nonInteractivePermissions: options.nonInteractivePermissions,
1958
- permissionPolicy: options.permissionPolicy,
1959
- authCredentials: options.authCredentials,
1960
- authPolicy: options.authPolicy,
1961
- fs: options.fs,
1962
- terminal: options.terminal,
1963
- verbose: options.verbose,
1964
- sessionOptions: options.sessionOptions
1965
- });
1966
- try {
1967
- return {
1968
- record: await withInterrupt(async () => await createSessionRecordWithClient(client, options), async () => {
1969
- await client.close();
1970
- }),
1971
- client
1972
- };
1973
- } catch (error) {
1974
- await client.close();
1975
- throw error;
1976
- }
1977
- }
1978
- async function createSession(options) {
1979
- const { record, client } = await createSessionWithClient(options);
1980
- try {
1981
- return record;
1982
- } finally {
1983
- await client.close();
1984
- applyLifecycleSnapshotToRecord(record, client.getAgentLifecycleSnapshot());
1985
- await writeSessionRecord(record);
1986
- }
1987
- }
1988
- async function listAgentSessions(options) {
1989
- const client = new AcpClient({
1990
- agentCommand: options.agentCommand,
1991
- agentArgv: options.agentArgv,
1992
- cwd: absolutePath(options.cwd),
1993
- mcpServers: options.mcpServers,
1994
- permissionMode: options.permissionMode,
1995
- nonInteractivePermissions: options.nonInteractivePermissions,
1996
- permissionPolicy: options.permissionPolicy,
1997
- authCredentials: options.authCredentials,
1998
- authPolicy: options.authPolicy,
1999
- fs: options.fs,
2000
- terminal: options.terminal,
2001
- verbose: options.verbose
2002
- });
2003
- try {
2004
- return await withInterrupt(async () => {
2005
- await withTimeout(client.start(), options.timeoutMs);
2006
- if (!client.supportsListSessions()) return;
2007
- const cwd = options.filterCwd ? absolutePath(options.filterCwd) : void 0;
2008
- const response = await withTimeout(client.listSessions({
2009
- ...cwd ? { cwd } : {},
2010
- ...options.cursor ? { cursor: options.cursor } : {}
2011
- }), options.timeoutMs);
2012
- return {
2013
- _meta: response._meta,
2014
- source: "agent",
2015
- sessions: response.sessions,
2016
- cursor: options.cursor,
2017
- cwd,
2018
- nextCursor: response.nextCursor
2019
- };
2020
- }, async () => {
2021
- await client.close();
2022
- });
2023
- } finally {
2024
- await client.close();
2025
- }
2026
- }
2027
- async function ensureSession(options) {
2028
- const cwd = absolutePath(options.cwd);
2029
- const gitRoot = findGitRepositoryRoot(cwd);
2030
- const walkBoundary = options.walkBoundary ?? gitRoot ?? cwd;
2031
- const existing = await findSessionByDirectoryWalk({
2032
- agentCommand: options.agentCommand,
2033
- cwd,
2034
- name: options.name,
2035
- boundary: walkBoundary
2036
- });
2037
- if (existing) {
2038
- const requestedModel = options.sessionOptions?.model;
2039
- if (requestedModel) return {
2040
- record: (await setSessionModel({
2041
- sessionId: existing.acpxRecordId,
2042
- modelId: requestedModel,
2043
- mcpServers: options.mcpServers,
2044
- nonInteractivePermissions: options.nonInteractivePermissions,
2045
- authCredentials: options.authCredentials,
2046
- authPolicy: options.authPolicy,
2047
- fs: options.fs,
2048
- terminal: options.terminal,
2049
- timeoutMs: options.timeoutMs,
2050
- verbose: options.verbose
2051
- })).record,
2052
- created: false
2053
- };
2054
- return {
2055
- record: existing,
2056
- created: false
2057
- };
2058
- }
2059
- return {
2060
- record: await createSession({
2061
- agentCommand: options.agentCommand,
2062
- agentArgv: options.agentArgv,
2063
- cwd,
2064
- name: options.name,
2065
- resumeSessionId: options.resumeSessionId,
2066
- mcpServers: options.mcpServers,
2067
- permissionMode: options.permissionMode,
2068
- nonInteractivePermissions: options.nonInteractivePermissions,
2069
- permissionPolicy: options.permissionPolicy,
2070
- authCredentials: options.authCredentials,
2071
- authPolicy: options.authPolicy,
2072
- fs: options.fs,
2073
- terminal: options.terminal,
2074
- timeoutMs: options.timeoutMs,
2075
- verbose: options.verbose,
2076
- sessionOptions: options.sessionOptions
2077
- }),
2078
- created: true
2079
- };
2080
- }
2081
- //#endregion
2082
- //#region src/perf-metrics-capture.ts
2083
- const PERF_METRICS_FILE_ENV = "ACPX_PERF_METRICS_FILE";
2084
- let installed = false;
2085
- let flushed = false;
2086
- let captureFilePath;
2087
- let captureRole = "cli";
2088
- let captureArgv = [];
2089
- let captureSequence = 0;
2090
- function shouldCapture() {
2091
- return typeof captureFilePath === "string" && captureFilePath.trim().length > 0;
2092
- }
2093
- function buildPayload(reason) {
2094
- return {
2095
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2096
- pid: process.pid,
2097
- ppid: process.ppid,
2098
- role: captureRole,
2099
- argv: captureArgv,
2100
- cwd: process.cwd(),
2101
- sequence: captureSequence,
2102
- reason,
2103
- metrics: getPerfMetricsSnapshot()
2104
- };
2105
- }
2106
- function payloadHasMetrics(payload) {
2107
- const metrics = payload.metrics;
2108
- return [
2109
- metrics.counters,
2110
- metrics.gauges,
2111
- metrics.timings
2112
- ].some((entries) => Object.keys(entries ?? {}).length > 0);
2113
- }
2114
- function appendPerfMetricsPayload(payload) {
2115
- fs.mkdirSync(path.dirname(captureFilePath), { recursive: true });
2116
- fs.appendFileSync(captureFilePath, `${JSON.stringify(payload)}\n`, "utf8");
2117
- captureSequence += 1;
2118
- }
2119
- function writePerfMetricsCapture(reason, resetAfterWrite) {
2120
- if (!shouldCapture()) return false;
2121
- const payload = buildPayload(reason);
2122
- if (!payloadHasMetrics(payload)) return false;
2123
- try {
2124
- appendPerfMetricsPayload(payload);
2125
- if (resetAfterWrite) resetPerfMetrics();
2126
- return true;
2127
- } catch {
2128
- return false;
2129
- }
2130
- }
2131
- function checkpointPerfMetricsCapture() {
2132
- flushed = false;
2133
- writePerfMetricsCapture("checkpoint", true);
2134
- }
2135
- function flushPerfMetricsCapture(reason = "exit") {
2136
- if (flushed || !shouldCapture()) return;
2137
- flushed = true;
2138
- writePerfMetricsCapture(reason, false);
2139
- }
2140
- function installPerfMetricsCapture(options = {}) {
2141
- captureFilePath = options.filePath ?? process.env[PERF_METRICS_FILE_ENV];
2142
- if (!shouldCapture()) return;
2143
- resetPerfMetrics();
2144
- captureRole = options.role ?? captureRole;
2145
- captureArgv = options.argv ?? [];
2146
- captureSequence = 0;
2147
- flushed = false;
2148
- if (installed) return;
2149
- installed = true;
2150
- process.once("exit", () => {
2151
- flushPerfMetricsCapture("exit");
2152
- });
2153
- for (const signal of ["SIGINT", "SIGTERM"]) {
2154
- const handler = () => {
2155
- flushPerfMetricsCapture("signal");
2156
- process.removeListener(signal, handler);
2157
- process.kill(process.pid, signal);
2158
- };
2159
- process.once(signal, handler);
2160
- }
2161
- }
2162
- //#endregion
2163
- //#region src/cli/queue/owner-turn-controller.ts
2164
- var QueueOwnerTurnController = class {
2165
- options;
2166
- state = "idle";
2167
- pendingCancel = false;
2168
- activeController;
2169
- constructor(options) {
2170
- this.options = options;
2171
- }
2172
- get lifecycleState() {
2173
- return this.state;
2174
- }
2175
- get hasPendingCancel() {
2176
- return this.pendingCancel;
2177
- }
2178
- beginTurn() {
2179
- this.state = "starting";
2180
- this.pendingCancel = false;
2181
- }
2182
- markPromptActive() {
2183
- if (this.state === "starting" || this.state === "active") this.state = "active";
2184
- }
2185
- endTurn() {
2186
- this.state = "idle";
2187
- this.pendingCancel = false;
2188
- }
2189
- beginClosing() {
2190
- this.state = "closing";
2191
- this.pendingCancel = false;
2192
- this.activeController = void 0;
2193
- }
2194
- setActiveController(controller) {
2195
- this.activeController = controller;
2196
- }
2197
- clearActiveController() {
2198
- this.activeController = void 0;
2199
- }
2200
- assertCanHandleControlRequest() {
2201
- if (this.state === "closing") throw new QueueConnectionError("Queue owner is closing", {
2202
- detailCode: "QUEUE_OWNER_SHUTTING_DOWN",
2203
- origin: "queue",
2204
- retryable: true
2205
- });
2206
- }
2207
- async requestCancel() {
2208
- const activeController = this.activeController;
2209
- if (activeController?.hasActivePrompt()) {
2210
- const cancelled = await activeController.requestCancelActivePrompt();
2211
- if (cancelled) this.pendingCancel = false;
2212
- return cancelled;
2213
- }
2214
- if (this.state === "starting" || this.state === "active") {
2215
- this.pendingCancel = true;
2216
- return true;
2217
- }
2218
- return false;
2219
- }
2220
- async applyPendingCancel() {
2221
- const activeController = this.activeController;
2222
- if (!this.pendingCancel || !activeController || !activeController.hasActivePrompt()) return false;
2223
- const cancelled = await activeController.requestCancelActivePrompt();
2224
- if (cancelled) this.pendingCancel = false;
2225
- return cancelled;
2226
- }
2227
- async setSessionMode(modeId, timeoutMs) {
2228
- this.assertCanHandleControlRequest();
2229
- const activeController = this.activeController;
2230
- if (activeController) {
2231
- await this.options.withTimeout(async () => await activeController.setSessionMode(modeId), timeoutMs);
2232
- return;
2233
- }
2234
- await this.options.setSessionModeFallback(modeId, timeoutMs);
2235
- }
2236
- async setSessionModel(modelId, timeoutMs) {
2237
- this.assertCanHandleControlRequest();
2238
- const activeController = this.activeController;
2239
- if (activeController) return await this.options.withTimeout(async () => await activeController.setSessionModel(modelId), timeoutMs);
2240
- return await this.options.setSessionModelFallback(modelId, timeoutMs);
2241
- }
2242
- async setSessionConfigOption(configId, value, timeoutMs) {
2243
- this.assertCanHandleControlRequest();
2244
- const activeController = this.activeController;
2245
- if (activeController) return await this.options.withTimeout(async () => await activeController.setSessionConfigOption(configId, value), timeoutMs);
2246
- return await this.options.setSessionConfigOptionFallback(configId, value, timeoutMs);
2247
- }
2248
- };
2249
- //#endregion
2250
- //#region src/cli/session/queue-owner-process.ts
2251
- const QUEUE_OWNER_PAYLOAD_FILE_ENV = "ACPX_QUEUE_OWNER_PAYLOAD_FILE";
2252
- const QUEUE_OWNER_PAYLOAD_ENV = "ACPX_QUEUE_OWNER_PAYLOAD";
2253
- function isNonEmptyStringArray(value) {
2254
- return Array.isArray(value) && value.length > 0 && value.every((entry) => typeof entry === "string" && entry.length > 0);
2255
- }
2256
- const NODE_TEST_FLAGS = /* @__PURE__ */ new Set([
2257
- "--experimental-test-coverage",
2258
- "--test",
2259
- "--test-name-pattern",
2260
- "--test-reporter",
2261
- "--test-reporter-destination"
2262
- ]);
2263
- const NODE_TEST_FLAGS_WITH_VALUE = /* @__PURE__ */ new Set([
2264
- "--test-name-pattern",
2265
- "--test-reporter",
2266
- "--test-reporter-destination"
2267
- ]);
2268
- const INSPECTOR_FLAGS_WITH_VALUE = /* @__PURE__ */ new Set([
2269
- "--inspect",
2270
- "--inspect-brk",
2271
- "--inspect-port",
2272
- "--inspect-publish-uid",
2273
- "--debug-port"
2274
- ]);
2275
- const INSPECTOR_FLAG_PREFIXES = [
2276
- "--inspect=",
2277
- "--inspect-brk=",
2278
- "--inspect-port=",
2279
- "--inspect-publish-uid=",
2280
- "--debug-port="
2281
- ];
2282
- function classifyExecArgv(value) {
2283
- if (value === void 0) return "drop";
2284
- if (NODE_TEST_FLAGS_WITH_VALUE.has(value) || INSPECTOR_FLAGS_WITH_VALUE.has(value)) return "drop-with-value";
2285
- return dropSingleExecArgv(value) ? "drop" : "keep";
2286
- }
2287
- function dropSingleExecArgv(value) {
2288
- return NODE_TEST_FLAGS.has(value) || value.startsWith("--test-") || INSPECTOR_FLAG_PREFIXES.some((prefix) => value.startsWith(prefix));
2289
- }
2290
- function sanitizeQueueOwnerExecArgv(execArgv = process.execArgv) {
2291
- const sanitized = [];
2292
- for (let index = 0; index < execArgv.length; index += 1) {
2293
- const value = execArgv[index] ?? "";
2294
- const decision = classifyExecArgv(value);
2295
- if (decision === "drop") continue;
2296
- if (decision === "drop-with-value") {
2297
- index += 1;
2298
- continue;
2299
- }
2300
- sanitized.push(value);
2301
- }
2302
- return sanitized;
2303
- }
2304
- function buildQueueOwnerArgOverride(entryPath, execArgv = process.execArgv) {
2305
- const sanitized = sanitizeQueueOwnerExecArgv(execArgv);
2306
- if (sanitized.length === 0) return null;
2307
- return JSON.stringify([
2308
- ...sanitized,
2309
- entryPath,
2310
- "__queue-owner"
2311
- ]);
2312
- }
2313
- function resolveQueueOwnerSpawnArgs(argv = process.argv) {
2314
- const override = process.env.ACPX_QUEUE_OWNER_ARGS;
2315
- if (override) {
2316
- const parsed = JSON.parse(override);
2317
- if (isNonEmptyStringArray(parsed)) return [...parsed];
2318
- throw new Error("acpx self-spawn failed: invalid ACPX_QUEUE_OWNER_ARGS");
2319
- }
2320
- const entry = argv[1];
2321
- if (!entry || entry.trim().length === 0) throw new Error("acpx self-spawn failed: missing CLI entry path");
2322
- return [realpathSync(entry), "__queue-owner"];
2323
- }
2324
- function queueOwnerRuntimeOptionsFromSend(options) {
2325
- return {
2326
- sessionId: options.sessionId,
2327
- mcpServers: options.mcpServers,
2328
- ...options.mcpConfigPath ? { mcpConfigPath: options.mcpConfigPath } : {},
2329
- ...options.mcpConfigFingerprint ? { mcpConfigFingerprint: options.mcpConfigFingerprint } : {},
2330
- permissionMode: options.permissionMode,
2331
- nonInteractivePermissions: options.nonInteractivePermissions,
2332
- authCredentials: options.authCredentials,
2333
- authPolicy: options.authPolicy,
2334
- fs: options.fs,
2335
- terminal: options.terminal,
2336
- suppressSdkConsoleErrors: options.suppressSdkConsoleErrors,
2337
- verbose: options.verbose,
2338
- ttlMs: options.ttlMs,
2339
- maxQueueDepth: options.maxQueueDepth,
2340
- promptRetries: options.promptRetries,
2341
- sessionOptions: options.sessionOptions
2342
- };
2343
- }
2344
- function writeQueueOwnerPayloadFile(payload) {
2345
- const dir = mkdtempSync(path.join(os.tmpdir(), "acpx-queue-owner-"));
2346
- const payloadPath = path.join(dir, "payload.json");
2347
- writeFileSync(payloadPath, payload, {
2348
- encoding: "utf8",
2349
- flag: "wx",
2350
- mode: 384
2351
- });
2352
- return payloadPath;
2353
- }
2354
- /** Max stderr bytes retained for cold-start diagnostics. */
2355
- const QUEUE_OWNER_STARTUP_STDERR_MAX_BYTES = 4e3;
2356
- function buildQueueOwnerSpawnOptions(payloadFilePath, opts) {
2357
- const env = {
2358
- ...process.env,
2359
- [QUEUE_OWNER_PAYLOAD_FILE_ENV]: payloadFilePath
2360
- };
2361
- delete env[QUEUE_OWNER_PAYLOAD_ENV];
2362
- return {
2363
- detached: true,
2364
- stdio: opts?.captureStderr === true ? [
2365
- "ignore",
2366
- "ignore",
2367
- "pipe"
2368
- ] : "ignore",
2369
- env,
2370
- windowsHide: true
2371
- };
2372
- }
2373
- function formatQueueOwnerStartupFailure(params) {
2374
- const parts = [`Session queue owner failed to start for session ${params.sessionId}`];
2375
- if (params.exit.spawnError) parts.push(`spawn error: ${params.exit.spawnError.message}`);
2376
- else if (params.exit.exited) {
2377
- const codePart = params.exit.code === null ? "null" : String(params.exit.code);
2378
- const signalPart = params.exit.signal ? `, signal ${params.exit.signal}` : "";
2379
- parts.push(`exited with code ${codePart}${signalPart} before binding its socket`);
2380
- }
2381
- const tail = params.logTail.trim();
2382
- if (tail.length > 0) parts.push(`stderr:\n${tail}`);
2383
- return parts.join(": ");
2384
- }
2385
- function spawnQueueOwnerProcess(options) {
2386
- const payloadPath = writeQueueOwnerPayloadFile(JSON.stringify(options));
2387
- let exited = false;
2388
- let code = null;
2389
- let signal = null;
2390
- let spawnError;
2391
- let capturing = true;
2392
- let stderrTail = Buffer.alloc(0);
2393
- const child = spawn(process.execPath, resolveQueueOwnerSpawnArgs(), buildQueueOwnerSpawnOptions(payloadPath, { captureStderr: true }));
2394
- const stopStartupCapture = () => {
2395
- if (!capturing) return;
2396
- capturing = false;
2397
- const stderr = child.stderr;
2398
- if (!stderr) return;
2399
- stderr.removeAllListeners("data");
2400
- stderr.on("data", () => {});
2401
- stderr.resume();
2402
- stderr.unref();
2403
- };
2404
- child.stderr?.on("data", (chunk) => {
2405
- if (!capturing) return;
2406
- const buf = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
2407
- const combined = Buffer.concat([stderrTail, buf]);
2408
- stderrTail = combined.length > 4e3 ? combined.subarray(combined.length - QUEUE_OWNER_STARTUP_STDERR_MAX_BYTES) : combined;
2409
- });
2410
- child.stderr?.on("error", () => {});
2411
- child.on("error", (error) => {
2412
- spawnError = error;
2413
- });
2414
- child.on("close", (exitCode, exitSignal) => {
2415
- exited = true;
2416
- code = exitCode;
2417
- signal = exitSignal;
2418
- stopStartupCapture();
2419
- });
2420
- child.unref();
2421
- return {
2422
- pid: child.pid,
2423
- getExitState: () => ({
2424
- exited,
2425
- code,
2426
- signal,
2427
- ...spawnError ? { spawnError } : {}
2428
- }),
2429
- readLogTail: (maxBytes = QUEUE_OWNER_STARTUP_STDERR_MAX_BYTES) => {
2430
- const start = Math.max(0, stderrTail.length - maxBytes);
2431
- return stderrTail.subarray(start).toString("utf8");
2432
- },
2433
- stopStartupCapture
2434
- };
2435
- }
2436
- //#endregion
2437
- //#region src/session/events.ts
2438
- const LOCK_RETRY_MS = 15;
2439
- const EVENT_LOCK_STALE_MS = 15e3;
2440
- async function ensureSessionDir() {
2441
- await fs$1.mkdir(sessionBaseDir(), { recursive: true });
2442
- }
2443
- async function pathExists(filePath) {
2444
- try {
2445
- await fs$1.access(filePath);
2446
- return true;
2447
- } catch {
2448
- return false;
2449
- }
2450
- }
2451
- async function statSize(filePath) {
2452
- try {
2453
- return (await fs$1.stat(filePath)).size;
2454
- } catch {
2455
- return 0;
2456
- }
2457
- }
2458
- async function countExistingSegments(sessionId, maxSegments) {
2459
- let count = 0;
2460
- for (let segment = 1; segment <= maxSegments; segment += 1) if (await pathExists(sessionEventSegmentPath(sessionId, segment))) count += 1;
2461
- if (await pathExists(sessionEventActivePath(sessionId))) count += 1;
2462
- return count;
2463
- }
2464
- async function resolveInitialSegmentCount(record, maxSegments) {
2465
- if (Number.isInteger(record.eventLog.segment_count) && record.eventLog.segment_count > 0) return record.eventLog.segment_count;
2466
- return await countExistingSegments(record.acpxRecordId, maxSegments) || 1;
2467
- }
2468
- async function rotateSegments(sessionId, maxSegments) {
2469
- const active = sessionEventActivePath(sessionId);
2470
- const overflow = sessionEventSegmentPath(sessionId, maxSegments);
2471
- await fs$1.unlink(overflow).catch((error) => {
2472
- if (error.code !== "ENOENT") throw error;
2473
- });
2474
- for (let segment = maxSegments - 1; segment >= 1; segment -= 1) {
2475
- const from = sessionEventSegmentPath(sessionId, segment);
2476
- const to = sessionEventSegmentPath(sessionId, segment + 1);
2477
- if (!await pathExists(from)) continue;
2478
- await fs$1.rename(from, to);
2479
- }
2480
- if (await pathExists(active)) await fs$1.rename(active, sessionEventSegmentPath(sessionId, 1));
2481
- }
2482
- function parseEventLockPayload(raw) {
2483
- try {
2484
- const parsed = JSON.parse(raw);
2485
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
2486
- const record = parsed;
2487
- return {
2488
- pid: typeof record.pid === "number" ? record.pid : void 0,
2489
- created_at: typeof record.created_at === "string" ? record.created_at : void 0
2490
- };
2491
- } catch {
2492
- return {};
2493
- }
2494
- }
2495
- async function removeStaleEventLock(lockPath) {
2496
- try {
2497
- const parsed = parseEventLockPayload(await fs$1.readFile(lockPath, "utf8"));
2498
- const createdAtMs = parsed.created_at ? Date.parse(parsed.created_at) : NaN;
2499
- const lockAgeMs = Number.isFinite(createdAtMs) ? Date.now() - createdAtMs : Number.POSITIVE_INFINITY;
2500
- if (isProcessAlive(parsed.pid) && lockAgeMs <= EVENT_LOCK_STALE_MS) return false;
2501
- await fs$1.unlink(lockPath);
2502
- incrementPerfCounter("session.events.stale_lock_recovered");
2503
- return true;
2504
- } catch (error) {
2505
- if (error.code === "ENOENT") return true;
2506
- return false;
2507
- }
2508
- }
2509
- async function acquireEventsLock(sessionId) {
2510
- await ensureSessionDir();
2511
- const lockPath = sessionEventLockPath(sessionId);
2512
- const payload = JSON.stringify({
2513
- pid: process.pid,
2514
- created_at: (/* @__PURE__ */ new Date()).toISOString()
2515
- }, null, 2);
2516
- for (;;) try {
2517
- await fs$1.writeFile(lockPath, `${payload}\n`, {
2518
- encoding: "utf8",
2519
- flag: "wx"
2520
- });
2521
- return { filePath: lockPath };
2522
- } catch (error) {
2523
- if (error.code !== "EEXIST") throw error;
2524
- if (await removeStaleEventLock(lockPath)) continue;
2525
- await new Promise((resolve) => {
2526
- setTimeout(resolve, LOCK_RETRY_MS);
2527
- });
2528
- }
2529
- }
2530
- async function releaseEventsLock(lock) {
2531
- await fs$1.unlink(lock.filePath).catch((error) => {
2532
- if (error.code !== "ENOENT") throw error;
2533
- });
2534
- }
2535
- var SessionEventWriter = class SessionEventWriter {
2536
- record;
2537
- lock;
2538
- maxSegmentBytes;
2539
- maxSegments;
2540
- activePath;
2541
- activeSizeBytes;
2542
- segmentCount;
2543
- closed = false;
2544
- constructor(record, lock, options, state) {
2545
- this.record = record;
2546
- this.lock = lock;
2547
- this.maxSegmentBytes = options.maxSegmentBytes;
2548
- this.maxSegments = options.maxSegments;
2549
- this.activePath = state.activePath;
2550
- this.activeSizeBytes = state.activeSizeBytes;
2551
- this.segmentCount = state.segmentCount;
2552
- }
2553
- static async open(record, options = {}) {
2554
- const lock = await acquireEventsLock(record.acpxRecordId);
2555
- const maxSegmentBytes = options.maxSegmentBytes ?? record.eventLog.max_segment_bytes ?? 67108864;
2556
- const maxSegments = options.maxSegments ?? record.eventLog.max_segments ?? 5;
2557
- const activePath = sessionEventActivePath(record.acpxRecordId);
2558
- const activeSizeBytes = await statSize(activePath);
2559
- const segmentCount = await resolveInitialSegmentCount(record, maxSegments);
2560
- return new SessionEventWriter(record, lock, {
2561
- maxSegmentBytes,
2562
- maxSegments
2563
- }, {
2564
- activePath,
2565
- activeSizeBytes,
2566
- segmentCount
2567
- });
2568
- }
2569
- getRecord() {
2570
- return this.record;
2571
- }
2572
- async appendMessage(message, options = {}) {
2573
- await this.appendMessages([message], options);
2574
- }
2575
- async appendMessages(messages, options = {}) {
2576
- if (this.closed) throw new Error("SessionEventWriter is closed");
2577
- if (messages.length === 0) return;
2578
- await ensureSessionDir();
2579
- await measurePerf("session.events.append_batch", async () => {
2580
- for (const message of messages) {
2581
- if (!isAcpJsonRpcMessage(message)) throw new Error("Attempted to persist invalid ACP JSON-RPC payload");
2582
- const line = `${JSON.stringify(message)}\n`;
2583
- const lineBytes = Buffer.byteLength(line);
2584
- if (this.activeSizeBytes > 0 && this.activeSizeBytes + lineBytes > this.maxSegmentBytes) {
2585
- await rotateSegments(this.record.acpxRecordId, this.maxSegments);
2586
- this.activePath = sessionEventActivePath(this.record.acpxRecordId);
2587
- this.activeSizeBytes = 0;
2588
- this.segmentCount = Math.min(this.segmentCount + 1, this.maxSegments);
2589
- incrementPerfCounter("session.events.rotate");
2590
- }
2591
- await fs$1.appendFile(this.activePath, line, "utf8");
2592
- this.activeSizeBytes += lineBytes;
2593
- this.record.lastSeq += 1;
2594
- if (Object.hasOwn(message, "id")) {
2595
- const id = message.id;
2596
- if (typeof id === "string" || typeof id === "number") this.record.lastRequestId = String(id);
2597
- }
2598
- const writeTs = (/* @__PURE__ */ new Date()).toISOString();
2599
- this.record.lastUsedAt = writeTs;
2600
- this.record.eventLog = {
2601
- active_path: this.activePath,
2602
- segment_count: this.segmentCount,
2603
- max_segment_bytes: this.maxSegmentBytes,
2604
- max_segments: this.maxSegments,
2605
- last_write_at: writeTs,
2606
- last_write_error: null
2607
- };
2608
- }
2609
- });
2610
- if (options.checkpoint === true) await writeSessionRecord(this.record);
2611
- }
2612
- async checkpoint() {
2613
- if (this.closed) throw new Error("SessionEventWriter is closed");
2614
- await writeSessionRecord(this.record);
2615
- }
2616
- async close(options = {}) {
2617
- if (this.closed) return;
2618
- try {
2619
- if (options.checkpoint !== false) await writeSessionRecord(this.record);
2620
- } finally {
2621
- this.closed = true;
2622
- await releaseEventsLock(this.lock);
2623
- }
2624
- }
2625
- };
2626
- //#endregion
2627
- //#region src/cli/session/runtime.ts
2628
- const INTERRUPT_CANCEL_WAIT_MS = 2500;
2629
- var QueueTaskOutputFormatter = class {
2630
- requestId;
2631
- send;
2632
- constructor(task) {
2633
- this.requestId = task.requestId;
2634
- this.send = task.send;
2635
- }
2636
- setContext(_context) {}
2637
- onAcpMessage(message) {
2638
- this.send({
2639
- type: "event",
2640
- requestId: this.requestId,
2641
- message
2642
- });
2643
- }
2644
- onError(params) {
2645
- this.send({
2646
- type: "error",
2647
- requestId: this.requestId,
2648
- code: params.code,
2649
- detailCode: params.detailCode,
2650
- origin: params.origin,
2651
- message: params.message,
2652
- retryable: params.retryable,
2653
- acp: params.acp
2654
- });
2655
- }
2656
- onPermissionEscalation(event) {
2657
- this.send({
2658
- type: "permission_escalation",
2659
- requestId: this.requestId,
2660
- event
2661
- });
2662
- }
2663
- flush() {}
2664
- };
2665
- const DISCARD_OUTPUT_FORMATTER = {
2666
- setContext() {},
2667
- onAcpMessage() {},
2668
- onError() {},
2669
- onPermissionEscalation() {},
2670
- flush() {}
2671
- };
2672
- function markOutputAlreadyEmitted(error, outputAlreadyEmitted) {
2673
- if (!outputAlreadyEmitted || !error || typeof error !== "object") return;
2674
- error.outputAlreadyEmitted = true;
2675
- }
2676
- async function runWithOptionalInterrupt(options) {
2677
- if (options.handleProcessInterrupts === false) return await options.run();
2678
- return await withInterrupt(options.run, options.handleInterrupt);
2679
- }
2680
- function attachAcpErrorPayload(error, acp) {
2681
- if (!acp || !error || typeof error !== "object") return;
2682
- error.acp = acp;
2683
- }
2684
- function rendersAcpErrors(policy) {
2685
- return policy?.queueErrorAlreadyEmitted ?? true;
2686
- }
2687
- function normalizedErrorText(value) {
2688
- return value.trim().toLowerCase();
2689
- }
2690
- function outboundAcpErrorMatches(error, acp) {
2691
- const errorText = normalizedErrorText(formatErrorMessage(error));
2692
- const details = acp.data?.details;
2693
- const candidateText = normalizedErrorText(typeof details === "string" && details.trim().length > 0 ? details : acp.message);
2694
- return errorText === candidateText || errorText.includes(candidateText);
2695
- }
2696
- var AcpErrorTracker = class {
2697
- latestInbound;
2698
- outbound = [];
2699
- reset() {
2700
- this.latestInbound = void 0;
2701
- this.outbound.length = 0;
2702
- }
2703
- observe(output, direction, message) {
2704
- output.onAcpMessage(message);
2705
- const acp = extractAcpError(message);
2706
- if (!acp) return;
2707
- if (direction === "inbound") {
2708
- this.latestInbound = acp;
2709
- return;
2710
- }
2711
- this.outbound.push(acp);
2712
- }
2713
- match(error) {
2714
- return this.latestInbound ?? this.outbound.findLast((acp) => outboundAcpErrorMatches(error, acp));
2715
- }
2716
- };
2717
- function toPromptResult(stopReason, sessionId, client, meta) {
2718
- return {
2719
- stopReason,
2720
- sessionId,
2721
- permissionStats: client.getPermissionStats(),
2722
- ...meta === void 0 ? {} : { _meta: meta }
2723
- };
2724
- }
2725
- function requestedModelId(value) {
2726
- return typeof value === "string" ? value.trim() : "";
2727
- }
2728
- function mergeConnectedModelState(state, connectedState) {
2729
- if (!connectedState) return state;
2730
- const nextState = cloneSessionAcpxState(state) ?? {};
2731
- mergeConnectedAdvertisedModelState(nextState, connectedState);
2732
- mergeConnectedModelPreferences(nextState, connectedState);
2733
- return nextState;
2734
- }
2735
- function mergeConnectedAdvertisedModelState(nextState, connectedState) {
2736
- if (connectedState.config_options !== void 0) nextState.config_options = structuredClone(connectedState.config_options);
2737
- else delete nextState.config_options;
2738
- if (connectedState.current_model_id !== void 0) nextState.current_model_id = connectedState.current_model_id;
2739
- else delete nextState.current_model_id;
2740
- if (connectedState.available_models) nextState.available_models = [...connectedState.available_models];
2741
- else delete nextState.available_models;
2742
- if (connectedState.model_control) nextState.model_control = connectedState.model_control;
2743
- else delete nextState.model_control;
2744
- }
2745
- function mergeConnectedModelPreferences(nextState, connectedState) {
2746
- if (connectedState.session_options) nextState.session_options = cloneSessionAcpxState(connectedState)?.session_options;
2747
- if (connectedState.desired_mode_id !== void 0) nextState.desired_mode_id = connectedState.desired_mode_id;
2748
- if (connectedState.desired_config_options) nextState.desired_config_options = { ...connectedState.desired_config_options };
2749
- else delete nextState.desired_config_options;
2750
- }
2751
- async function applyPromptModelIfAdvertised(params) {
2752
- const requestedModel = requestedModelId(params.requestedModel);
2753
- if (!requestedModel) return;
2754
- const result = await applyRequestedModelIfAdvertised({
2755
- client: params.client,
2756
- sessionId: params.sessionId,
2757
- requestedModel,
2758
- models: advertisedModelState(params.record.acpx),
2759
- agentCommand: params.record.agentCommand,
2760
- timeoutMs: params.timeoutMs,
2761
- onWarning: params.suppressWarnings ? void 0 : (message) => process.stderr.write(`[acpx] warning: ${message}\n`)
2762
- });
2763
- if (result.applied) params.record.acpx = applyModelSelection(params.record.acpx, requestedModel, result.response);
2764
- }
2765
- function jsonRpcIdKey$1(value) {
2766
- if (typeof value === "string") return `s:${value}`;
2767
- if (typeof value === "number" && Number.isFinite(value)) return `n:${value}`;
2768
- }
2769
- function extractJsonRpcRequestInfo(message) {
2770
- const candidate = message;
2771
- if (typeof candidate.method !== "string") return;
2772
- const idKey = jsonRpcIdKey$1(candidate.id);
2773
- if (!idKey) return;
2774
- return {
2775
- idKey,
2776
- method: candidate.method
2777
- };
2778
- }
2779
- function extractJsonRpcResponseInfo(message) {
2780
- const candidate = message;
2781
- const idKey = jsonRpcIdKey$1(candidate.id);
2782
- if (!idKey) return;
2783
- const hasError = Object.hasOwn(candidate, "error");
2784
- const hasResult = Object.hasOwn(candidate, "result");
2785
- if (!hasError && !hasResult) return;
2786
- return {
2787
- idKey,
2788
- hasError
2789
- };
2790
- }
2791
- const SESSION_RECONNECT_METHODS = /* @__PURE__ */ new Set(["session/load", "session/resume"]);
2792
- function filterRecoverableLoadFallbackOutput(messages) {
2793
- const requestMethodById = /* @__PURE__ */ new Map();
2794
- const failedLoadRequestIds = /* @__PURE__ */ new Set();
2795
- for (const message of messages) {
2796
- const request = extractJsonRpcRequestInfo(message);
2797
- if (request) {
2798
- requestMethodById.set(request.idKey, request.method);
2799
- continue;
2800
- }
2801
- const response = extractJsonRpcResponseInfo(message);
2802
- if (!response || !response.hasError) continue;
2803
- const requestMethod = requestMethodById.get(response.idKey);
2804
- if (requestMethod && SESSION_RECONNECT_METHODS.has(requestMethod)) failedLoadRequestIds.add(response.idKey);
2805
- }
2806
- if (failedLoadRequestIds.size === 0) return messages;
2807
- return messages.filter((message) => {
2808
- const request = extractJsonRpcRequestInfo(message);
2809
- if (request && SESSION_RECONNECT_METHODS.has(request.method) && failedLoadRequestIds.has(request.idKey)) return false;
2810
- const response = extractJsonRpcResponseInfo(message);
2811
- if (response && failedLoadRequestIds.has(response.idKey)) return false;
2812
- return true;
2813
- });
2814
- }
2815
- function filterBufferedConnectOutput(messages, loadError) {
2816
- if (loadError == null) return messages;
2817
- const filteredMessages = new Set(filterRecoverableLoadFallbackOutput(messages.map(({ message }) => message)));
2818
- return messages.filter(({ message }) => filteredMessages.has(message));
2819
- }
2820
- function emitPromptRetryNotice(params) {
2821
- if (params.suppressSdkConsoleErrors) return;
2822
- process.stderr.write(`[acpx] prompt failed (${formatErrorMessage(params.error)}), retrying in ${params.delayMs}ms (attempt ${params.attempt}/${params.maxRetries})\n`);
2823
- }
2824
- function emitConnectPerfMetric(startedAt, verbose) {
2825
- if (!verbose) return;
2826
- process.stderr.write(`[acpx] ${formatPerfMetric("prompt.connect_and_load", Date.now() - startedAt)}\n`);
2827
- }
2828
- function emitPromptPerfMetric(startedAt, verbose) {
2829
- if (!verbose) return;
2830
- process.stderr.write(`[acpx] ${formatPerfMetric("prompt.agent_turn", Date.now() - startedAt)}\n`);
2831
- }
2832
- function emitPromptHookError(error, verbose) {
2833
- if (!verbose) return;
2834
- process.stderr.write("[acpx] onPromptActive hook failed: " + formatErrorMessage(error) + "\n");
2835
- }
2836
- function emitPromptDisconnectNotice(snapshot, verbose) {
2837
- const lastExit = snapshot.lastExit;
2838
- if (!lastExit?.unexpectedDuringPrompt || !verbose) return;
2839
- process.stderr.write("[acpx] agent disconnected during prompt (" + lastExit.reason + ", exit=" + lastExit.exitCode + ", signal=" + (lastExit.signal ?? "none") + ")\n");
2840
- }
2841
- function shouldRetryRuntimePrompt(error, attempt, maxRetries, snapshot, hasSideEffects) {
2842
- if (!shouldRetryPromptAttempt(error, attempt, maxRetries, hasSideEffects)) return false;
2843
- return snapshot.lastExit?.unexpectedDuringPrompt !== true;
2844
- }
2845
- function shouldRetryPromptAttempt(error, attempt, maxRetries, hasSideEffects) {
2846
- return attempt < maxRetries && !hasSideEffects() && isRetryablePromptError(error);
2847
- }
2848
- async function waitBeforePromptRetry(error, attempt, maxRetries, suppressSdkConsoleErrors) {
2849
- const delayMs = Math.min(1e3 * 2 ** attempt, 1e4);
2850
- emitPromptRetryNotice({
2851
- error,
2852
- delayMs,
2853
- attempt: attempt + 1,
2854
- maxRetries,
2855
- suppressSdkConsoleErrors
2856
- });
2857
- await waitMs(delayMs);
2858
- }
2859
- function buildQueuedTaskRunOptions(sessionRecordId, task, options, outputFormatter) {
2860
- return {
2861
- sessionRecordId,
2862
- mcpServers: options.mcpServers,
2863
- prompt: task.prompt ?? textPrompt(task.message),
2864
- permissionMode: task.permissionMode,
2865
- resumePolicy: task.resumePolicy,
2866
- nonInteractivePermissions: task.nonInteractivePermissions ?? options.nonInteractivePermissions,
2867
- permissionPolicy: task.permissionPolicy,
2868
- authCredentials: options.authCredentials,
2869
- authPolicy: options.authPolicy,
2870
- outputFormatter,
2871
- errorEmissionPolicy: { queueErrorAlreadyEmitted: true },
2872
- timeoutMs: task.timeoutMs,
2873
- suppressSdkConsoleErrors: task.suppressSdkConsoleErrors ?? options.suppressSdkConsoleErrors,
2874
- verbose: options.verbose,
2875
- promptRetries: task.promptRetries ?? options.promptRetries ?? 0,
2876
- sessionOptions: mergeSessionOptions(task.sessionOptions, options.sessionOptions),
2877
- onClientAvailable: options.onClientAvailable,
2878
- onClientClosed: options.onClientClosed,
2879
- onPromptActive: options.onPromptActive,
2880
- handleProcessInterrupts: options.handleProcessInterrupts,
2881
- client: options.sharedClient
2882
- };
2883
- }
2884
- function sendQueuedTaskResult(task, result) {
2885
- if (!task.waitForCompletion) return;
2886
- task.send({
2887
- type: "result",
2888
- requestId: task.requestId,
2889
- result
2890
- });
2891
- }
2892
- function sendQueuedTaskError(task, error) {
2893
- if (!task.waitForCompletion) return;
2894
- const normalizedError = normalizeOutputError(error, {
2895
- origin: "runtime",
2896
- detailCode: "QUEUE_RUNTIME_PROMPT_FAILED"
2897
- });
2898
- const alreadyEmitted = error.outputAlreadyEmitted === true;
2899
- task.send({
2900
- type: "error",
2901
- requestId: task.requestId,
2902
- code: normalizedError.code,
2903
- detailCode: normalizedError.detailCode,
2904
- origin: normalizedError.origin,
2905
- message: normalizedError.message,
2906
- retryable: normalizedError.retryable,
2907
- acp: normalizedError.acp,
2908
- outputAlreadyEmitted: alreadyEmitted
2909
- });
2910
- }
2911
- async function runQueuedTask(sessionRecordId, task, options) {
2912
- const outputFormatter = task.waitForCompletion ? new QueueTaskOutputFormatter(task) : DISCARD_OUTPUT_FORMATTER;
2913
- try {
2914
- sendQueuedTaskResult(task, await runSessionPrompt(buildQueuedTaskRunOptions(sessionRecordId, task, options, outputFormatter)));
2915
- } catch (error) {
2916
- sendQueuedTaskError(task, error);
2917
- if (error instanceof InterruptedError) throw error;
2918
- } finally {
2919
- task.close();
2920
- }
2921
- }
2922
- async function runSessionPrompt(options) {
2923
- const stopTotalTimer = startPerfTimer("runtime.prompt.total");
2924
- const output = options.outputFormatter;
2925
- const shouldMarkAcpErrorsEmitted = rendersAcpErrors(options.errorEmissionPolicy);
2926
- const record = await measurePerf("session.resolve_prompt_record", async () => {
2927
- return await resolveSessionRecord(options.sessionRecordId);
2928
- });
2929
- const conversation = cloneSessionConversation(record);
2930
- let acpxState = cloneSessionAcpxState(record.acpx);
2931
- const promptStartedAt = isoNow();
2932
- const promptMessageId = recordPromptSubmission(conversation, options.prompt, promptStartedAt);
2933
- record.lastPromptAt = promptStartedAt;
2934
- record.lastUsedAt = promptStartedAt;
2935
- applyConversation(record, conversation);
2936
- record.acpx = acpxState;
2937
- await writeSessionRecord(record);
2938
- output.setContext({ sessionId: record.acpxRecordId });
2939
- const eventWriter = await measurePerf("session.events.open", async () => {
2940
- return await SessionEventWriter.open(record);
2941
- });
2942
- const pendingMessages = [];
2943
- const pendingConnectOutputMessages = [];
2944
- const sessionOptions = mergeSessionOptions(options.sessionOptions, sessionOptionsFromRecord(record));
2945
- let bufferingConnectOutput = true;
2946
- let promptTurnActive = false;
2947
- let promptTurnHadSideEffects = false;
2948
- const acpErrors = new AcpErrorTracker();
2949
- let eventWriterClosed = false;
2950
- const closeEventWriter = async (checkpoint) => {
2951
- if (eventWriterClosed) return;
2952
- eventWriterClosed = true;
2953
- await eventWriter.close({ checkpoint });
2954
- };
2955
- const flushPendingMessages = async (checkpoint = false) => {
2956
- if (pendingMessages.length === 0) return;
2957
- const batch = pendingMessages.splice(0);
2958
- await measurePerf("session.events.flush_pending", async () => {
2959
- await eventWriter.appendMessages(batch, { checkpoint });
2960
- });
2961
- };
2962
- const preserveClosedState = async () => {
2963
- const latest = await resolveSessionRecord(record.acpxRecordId).catch(() => void 0);
2964
- if (!latest?.closed) return;
2965
- record.closed = true;
2966
- record.closedAt = latest.closedAt ?? record.closedAt ?? isoNow();
2967
- record.pid = latest.pid;
2968
- if (latest.acpx) record.acpx = {
2969
- ...record.acpx,
2970
- ...latest.acpx
2971
- };
2972
- };
2973
- const liveCheckpoint = new LiveSessionCheckpoint({
2974
- save: async () => {
2975
- await flushPendingMessages(false);
2976
- record.lastUsedAt = isoNow();
2977
- applyConversation(record, conversation);
2978
- record.acpx = acpxState;
2979
- await preserveClosedState();
2980
- await eventWriter.checkpoint();
2981
- },
2982
- onError: (error) => {
2983
- if (options.verbose) process.stderr.write("[acpx] live session checkpoint failed: " + formatErrorMessage(error) + "\n");
2984
- }
2985
- });
2986
- let closeClientOnExit = options.client == null;
2987
- const client = options.client ?? new AcpClient({
2988
- agentCommand: record.agentCommand,
2989
- agentArgv: record.agentArgv,
2990
- cwd: absolutePath(record.cwd),
2991
- mcpServers: options.mcpServers,
2992
- permissionMode: options.permissionMode,
2993
- nonInteractivePermissions: options.nonInteractivePermissions,
2994
- permissionPolicy: options.permissionPolicy,
2995
- authCredentials: options.authCredentials,
2996
- authPolicy: options.authPolicy,
2997
- fs: options.fs,
2998
- terminal: options.terminal,
2999
- suppressSdkConsoleErrors: options.suppressSdkConsoleErrors,
3000
- verbose: options.verbose,
3001
- sessionOptions
3002
- });
3003
- client.updateRuntimeOptions({
3004
- permissionMode: options.permissionMode,
3005
- nonInteractivePermissions: options.nonInteractivePermissions,
3006
- permissionPolicy: options.permissionPolicy,
3007
- fs: options.fs,
3008
- terminal: options.terminal,
3009
- suppressSdkConsoleErrors: options.suppressSdkConsoleErrors,
3010
- verbose: options.verbose
3011
- });
3012
- client.setEventHandlers({
3013
- onAcpMessage: (direction, message) => {
3014
- pendingMessages.push(message);
3015
- options.onAcpMessage?.(direction, message);
3016
- },
3017
- onAcpOutputMessage: (direction, message) => {
3018
- if (bufferingConnectOutput) {
3019
- pendingConnectOutputMessages.push({
3020
- direction,
3021
- message
3022
- });
3023
- return;
3024
- }
3025
- acpErrors.observe(output, direction, message);
3026
- },
3027
- onSessionUpdate: (notification) => {
3028
- if (promptTurnActive) promptTurnHadSideEffects = true;
3029
- acpxState = recordSessionUpdate(conversation, acpxState, notification);
3030
- trimConversationForRuntime(conversation);
3031
- liveCheckpoint.request();
3032
- options.onSessionUpdate?.(notification);
3033
- },
3034
- onClientOperation: (operation) => {
3035
- if (promptTurnActive) promptTurnHadSideEffects = true;
3036
- acpxState = recordClientOperation(conversation, acpxState, operation);
3037
- trimConversationForRuntime(conversation);
3038
- liveCheckpoint.request();
3039
- options.onClientOperation?.(operation);
3040
- },
3041
- onPermissionEscalation: (event) => {
3042
- output.onPermissionEscalation(event);
3043
- options.onPermissionEscalation?.(event);
3044
- }
3045
- });
3046
- let activeSessionIdForControl = record.acpSessionId;
3047
- let notifiedClientAvailable = false;
3048
- const activeController = {
3049
- hasActivePrompt: () => client.hasActivePrompt(),
3050
- requestCancelActivePrompt: async () => await client.requestCancelActivePrompt(),
3051
- setSessionMode: async (modeId) => {
3052
- await client.setSessionMode(activeSessionIdForControl, modeId);
3053
- },
3054
- setSessionModel: async (modelId) => {
3055
- const models = advertisedModelState(acpxState);
3056
- const response = await client.setSessionModel(activeSessionIdForControl, modelId, models);
3057
- acpxState = applyModelSelection(acpxState, modelId, response);
3058
- return response;
3059
- },
3060
- setSessionConfigOption: async (configId, value) => {
3061
- const modelConfigId = advertisedModelState(acpxState)?.configId;
3062
- const response = await client.setSessionConfigOption(activeSessionIdForControl, configId, value);
3063
- acpxState = applyConfigOptionSelection(acpxState, configId, value, response, modelConfigId);
3064
- return response;
3065
- }
3066
- };
3067
- const flushConnectOutput = (loadError) => {
3068
- bufferingConnectOutput = false;
3069
- const outputMessages = filterBufferedConnectOutput(pendingConnectOutputMessages, loadError);
3070
- for (const { direction, message } of outputMessages) acpErrors.observe(output, direction, message);
3071
- pendingConnectOutputMessages.length = 0;
3072
- };
3073
- const connectForPrompt = async () => {
3074
- const connectStartedAt = Date.now();
3075
- try {
3076
- const connected = await measurePerf("runtime.connect_and_load", async () => {
3077
- return await connectAndLoadSession({
3078
- client,
3079
- record,
3080
- resumePolicy: options.resumePolicy,
3081
- replacingConfigOption: requestedModelId(options.sessionOptions?.model) ? { key: "model" } : void 0,
3082
- timeoutMs: options.timeoutMs,
3083
- verbose: options.verbose,
3084
- suppressWarnings: options.suppressSdkConsoleErrors,
3085
- activeController,
3086
- onClientAvailable: (controller) => {
3087
- options.onClientAvailable?.(controller);
3088
- notifiedClientAvailable = true;
3089
- },
3090
- onConnectedRecord: (connectedRecord) => {
3091
- connectedRecord.lastPromptAt = isoNow();
3092
- },
3093
- onSessionIdResolved: (sessionId) => {
3094
- activeSessionIdForControl = sessionId;
3095
- }
3096
- });
3097
- });
3098
- acpxState = mergeConnectedModelState(acpxState, record.acpx);
3099
- flushConnectOutput(connected.loadError);
3100
- emitConnectPerfMetric(connectStartedAt, options.verbose);
3101
- return connected;
3102
- } catch (error) {
3103
- closeClientOnExit = true;
3104
- flushConnectOutput();
3105
- throw error;
3106
- }
3107
- };
3108
- const buildPromptStartedHook = (attempt) => {
3109
- if (attempt !== 0 || !options.onPromptActive) return;
3110
- return async () => {
3111
- try {
3112
- await options.onPromptActive?.();
3113
- } catch (error) {
3114
- emitPromptHookError(error, options.verbose);
3115
- }
3116
- };
3117
- };
3118
- const runPromptAttempt = async (sessionId, attempt) => {
3119
- acpErrors.reset();
3120
- const promptStartedAt = Date.now();
3121
- const response = await measurePerf("runtime.prompt.agent_turn", async () => {
3122
- return await runPromptTurn({
3123
- client,
3124
- sessionId,
3125
- prompt: options.prompt,
3126
- timeoutMs: options.timeoutMs,
3127
- conversation,
3128
- promptMessageId,
3129
- onPromptStarted: buildPromptStartedHook(attempt)
3130
- });
3131
- });
3132
- emitPromptPerfMetric(promptStartedAt, options.verbose);
3133
- return response;
3134
- };
3135
- const handlePromptFailure = async (error, attempt) => {
3136
- const snapshot = client.getAgentLifecycleSnapshot();
3137
- if (shouldRetryRuntimePrompt(error, attempt, options.promptRetries ?? 0, snapshot, () => promptTurnHadSideEffects)) {
3138
- await waitBeforePromptRetry(error, attempt, options.promptRetries ?? 0, options.suppressSdkConsoleErrors);
3139
- return promptTurnHadSideEffects ? await failRuntimePrompt(error, snapshot) : "retry";
3140
- }
3141
- return await failRuntimePrompt(error, snapshot);
3142
- };
3143
- const failRuntimePrompt = async (error, snapshot) => {
3144
- promptTurnActive = false;
3145
- applyLifecycleSnapshotToRecord(record, snapshot);
3146
- emitPromptDisconnectNotice(snapshot, options.verbose);
3147
- const matchedAcpError = acpErrors.match(error);
3148
- const normalizedError = normalizeOutputError(error, {
3149
- origin: "runtime",
3150
- acp: matchedAcpError
3151
- });
3152
- await flushPendingMessages(false).catch(() => {});
3153
- output.flush();
3154
- record.lastUsedAt = isoNow();
3155
- applyConversation(record, conversation);
3156
- record.acpx = acpxState;
3157
- const propagated = error instanceof Error ? error : new Error(formatErrorMessage(error));
3158
- attachAcpErrorPayload(propagated, normalizedError.acp);
3159
- propagated.outputAlreadyEmitted = matchedAcpError !== void 0 && shouldMarkAcpErrorsEmitted;
3160
- propagated.normalizedOutputError = normalizedError;
3161
- throw propagated;
3162
- };
3163
- const runPromptWithRetries = async (sessionId) => {
3164
- promptTurnActive = true;
3165
- for (let attempt = 0;; attempt++) try {
3166
- return await runPromptAttempt(sessionId, attempt);
3167
- } catch (error) {
3168
- if (await handlePromptFailure(error, attempt) === "retry") continue;
3169
- }
3170
- };
3171
- const savePromptSuccess = async (response) => {
3172
- await flushPendingMessages(false);
3173
- output.flush();
3174
- const now = isoNow();
3175
- record.lastUsedAt = now;
3176
- record.closed = false;
3177
- record.closedAt = void 0;
3178
- record.protocolVersion = client.initializeResult?.protocolVersion;
3179
- record.agentCapabilities = client.initializeResult?.agentCapabilities;
3180
- applyConversation(record, conversation);
3181
- record.acpx = acpxState;
3182
- applyLifecycleSnapshotToRecord(record, client.getAgentLifecycleSnapshot());
3183
- stopTotalTimer();
3184
- return response;
3185
- };
3186
- const runPrompt = async () => {
3187
- const { sessionId: activeSessionId, resumed, loadError } = await connectForPrompt();
3188
- await applyPromptModelIfAdvertised({
3189
- client,
3190
- sessionId: activeSessionId,
3191
- requestedModel: options.sessionOptions?.model,
3192
- record,
3193
- timeoutMs: options.timeoutMs,
3194
- suppressWarnings: options.suppressSdkConsoleErrors
3195
- });
3196
- acpxState = cloneSessionAcpxState(record.acpx);
3197
- output.setContext({ sessionId: record.acpxRecordId });
3198
- await liveCheckpoint.checkpoint();
3199
- const response = await savePromptSuccess(await runPromptWithRetries(activeSessionId));
3200
- promptTurnActive = false;
3201
- return {
3202
- ...toPromptResult(response.stopReason, record.acpxRecordId, client, response._meta),
3203
- record,
3204
- resumed,
3205
- loadError
3206
- };
3207
- };
3208
- const handleInterrupt = async () => {
3209
- await client.cancelActivePrompt(INTERRUPT_CANCEL_WAIT_MS);
3210
- applyLifecycleSnapshotToRecord(record, client.getAgentLifecycleSnapshot());
3211
- record.lastUsedAt = isoNow();
3212
- applyConversation(record, conversation);
3213
- record.acpx = acpxState;
3214
- await flushPendingMessages(false).catch(() => {});
3215
- if (closeClientOnExit) await client.close();
3216
- };
3217
- try {
3218
- return await runWithOptionalInterrupt({
3219
- handleProcessInterrupts: options.handleProcessInterrupts,
3220
- run: runPrompt,
3221
- handleInterrupt
3222
- });
3223
- } catch (error) {
3224
- const matchedAcpError = acpErrors.match(error);
3225
- attachAcpErrorPayload(error, matchedAcpError);
3226
- markOutputAlreadyEmitted(error, matchedAcpError !== void 0 && shouldMarkAcpErrorsEmitted);
3227
- throw error;
3228
- } finally {
3229
- if (options.verbose) process.stderr.write(`[acpx] ${formatPerfMetric("prompt.total", stopTotalTimer())}\n`);
3230
- else stopTotalTimer();
3231
- if (notifiedClientAvailable) options.onClientClosed?.();
3232
- client.clearEventHandlers();
3233
- if (closeClientOnExit) await client.close();
3234
- applyLifecycleSnapshotToRecord(record, client.getAgentLifecycleSnapshot());
3235
- applyConversation(record, conversation);
3236
- record.acpx = acpxState;
3237
- await liveCheckpoint.flush().catch(() => {});
3238
- await flushPendingMessages(false).catch(() => {});
3239
- await preserveClosedState().catch(() => {});
3240
- await closeEventWriter(true).catch(() => {});
3241
- }
3242
- }
3243
- async function runOnce(options) {
3244
- const output = options.outputFormatter;
3245
- const shouldMarkAcpErrorsEmitted = rendersAcpErrors(options.errorEmissionPolicy);
3246
- let promptTurnActive = false;
3247
- let promptTurnHadSideEffects = false;
3248
- const acpErrors = new AcpErrorTracker();
3249
- const client = new AcpClient({
3250
- agentCommand: options.agentCommand,
3251
- agentArgv: options.agentArgv,
3252
- cwd: absolutePath(options.cwd),
3253
- mcpServers: options.mcpServers,
3254
- permissionMode: options.permissionMode,
3255
- nonInteractivePermissions: options.nonInteractivePermissions,
3256
- permissionPolicy: options.permissionPolicy,
3257
- authCredentials: options.authCredentials,
3258
- authPolicy: options.authPolicy,
3259
- fs: options.fs,
3260
- terminal: options.terminal,
3261
- suppressSdkConsoleErrors: options.suppressSdkConsoleErrors,
3262
- verbose: options.verbose,
3263
- onAcpMessage: options.onAcpMessage,
3264
- onAcpOutputMessage: (direction, message) => {
3265
- acpErrors.observe(output, direction, message);
3266
- },
3267
- onSessionUpdate: (notification) => {
3268
- if (promptTurnActive) promptTurnHadSideEffects = true;
3269
- options.onSessionUpdate?.(notification);
3270
- },
3271
- onClientOperation: (operation) => {
3272
- if (promptTurnActive) promptTurnHadSideEffects = true;
3273
- options.onClientOperation?.(operation);
3274
- },
3275
- onPermissionEscalation: (event) => {
3276
- output.onPermissionEscalation(event);
3277
- options.onPermissionEscalation?.(event);
3278
- },
3279
- sessionOptions: options.sessionOptions
3280
- });
3281
- const runExecPromptAttempt = async (sessionId) => {
3282
- acpErrors.reset();
3283
- return await measurePerf("runtime.exec.prompt", async () => {
3284
- return await withTimeout(client.prompt(sessionId, options.prompt), options.timeoutMs);
3285
- });
3286
- };
3287
- const runExecPromptWithRetries = async (sessionId) => {
3288
- const maxRetries = options.promptRetries ?? 0;
3289
- promptTurnActive = true;
3290
- for (let attempt = 0;; attempt++) try {
3291
- return await runExecPromptAttempt(sessionId);
3292
- } catch (error) {
3293
- if (shouldRetryPromptAttempt(error, attempt, maxRetries, () => promptTurnHadSideEffects)) {
3294
- await waitBeforePromptRetry(error, attempt, maxRetries, options.suppressSdkConsoleErrors);
3295
- if (!promptTurnHadSideEffects) continue;
3296
- }
3297
- promptTurnActive = false;
3298
- throw error;
3299
- }
3300
- };
3301
- try {
3302
- return await withInterrupt(async () => {
3303
- await measurePerf("runtime.exec.start", async () => {
3304
- await withTimeout(client.start(), options.timeoutMs);
3305
- });
3306
- const createdSession = await measurePerf("runtime.exec.create_session", async () => {
3307
- return await withTimeout(client.createSession(absolutePath(options.cwd)), options.timeoutMs);
3308
- });
3309
- const sessionId = createdSession.sessionId;
3310
- await applyRequestedModelIfAdvertised({
3311
- client,
3312
- sessionId,
3313
- requestedModel: options.sessionOptions?.model,
3314
- models: createdSession.models,
3315
- agentCommand: options.agentCommand,
3316
- timeoutMs: options.timeoutMs,
3317
- onWarning: options.suppressSdkConsoleErrors ? void 0 : (message) => process.stderr.write(`[acpx] warning: ${message}\n`)
3318
- });
3319
- for (const configOption of options.configOptions ?? []) await withTimeout(client.setSessionConfigOption(sessionId, configOption.configId, configOption.value), options.timeoutMs);
3320
- output.setContext({ sessionId });
3321
- const response = await runExecPromptWithRetries(sessionId);
3322
- promptTurnActive = false;
3323
- output.flush();
3324
- return toPromptResult(response.stopReason, sessionId, client, response._meta);
3325
- }, async () => {
3326
- await client.cancelActivePrompt(INTERRUPT_CANCEL_WAIT_MS);
3327
- await client.close();
3328
- });
3329
- } catch (error) {
3330
- const matchedAcpError = acpErrors.match(error);
3331
- attachAcpErrorPayload(error, matchedAcpError);
3332
- markOutputAlreadyEmitted(error, matchedAcpError !== void 0 && shouldMarkAcpErrorsEmitted);
3333
- throw error;
3334
- } finally {
3335
- await client.close();
3336
- }
3337
- }
3338
- async function sendSessionDirect(options) {
3339
- return await runSessionPrompt({
3340
- sessionRecordId: options.sessionId,
3341
- prompt: options.prompt,
3342
- mcpServers: options.mcpServers,
3343
- permissionMode: options.permissionMode,
3344
- resumePolicy: options.resumePolicy,
3345
- nonInteractivePermissions: options.nonInteractivePermissions,
3346
- permissionPolicy: options.permissionPolicy,
3347
- authCredentials: options.authCredentials,
3348
- authPolicy: options.authPolicy,
3349
- fs: options.fs,
3350
- terminal: options.terminal,
3351
- outputFormatter: options.outputFormatter,
3352
- errorEmissionPolicy: options.errorEmissionPolicy,
3353
- onAcpMessage: options.onAcpMessage,
3354
- onSessionUpdate: options.onSessionUpdate,
3355
- onClientOperation: options.onClientOperation,
3356
- onPermissionEscalation: options.onPermissionEscalation,
3357
- timeoutMs: options.timeoutMs,
3358
- suppressSdkConsoleErrors: options.suppressSdkConsoleErrors,
3359
- verbose: options.verbose,
3360
- client: options.client
3361
- });
3362
- }
3363
- //#endregion
3364
- //#region src/cli/session/queue-owner-runtime.ts
3365
- const QUEUE_OWNER_STARTUP_MAX_ATTEMPTS = 120;
3366
- const QUEUE_OWNER_HEARTBEAT_INTERVAL_MS = 5e3;
3367
- const QUEUE_OWNER_ACTIVE_TURN_CANCEL_GRACE_MS = 750;
3368
- async function submitToRunningOwner(options, waitForCompletion, extras) {
3369
- return await trySubmitToRunningOwner({
3370
- sessionId: options.sessionId,
3371
- message: promptToDisplayText(options.prompt),
3372
- prompt: options.prompt,
3373
- mcpConfigPath: options.mcpConfigPath,
3374
- mcpConfigFingerprint: options.mcpConfigFingerprint,
3375
- permissionMode: options.permissionMode,
3376
- nonInteractivePermissions: options.nonInteractivePermissions,
3377
- permissionPolicy: options.permissionPolicy,
3378
- outputFormatter: options.outputFormatter,
3379
- errorEmissionPolicy: options.errorEmissionPolicy,
3380
- timeoutMs: options.timeoutMs,
3381
- suppressSdkConsoleErrors: options.suppressSdkConsoleErrors,
3382
- promptRetries: options.promptRetries,
3383
- waitForCompletion,
3384
- verbose: options.verbose,
3385
- sessionOptions: options.sessionOptions,
3386
- onQueueAccepted: extras?.onQueueAccepted
3387
- });
3388
- }
3389
- function createQueueOwnerSharedClient(options, sessionRecord) {
3390
- return new AcpClient({
3391
- agentCommand: sessionRecord.agentCommand,
3392
- agentArgv: sessionRecord.agentArgv,
3393
- cwd: absolutePath(sessionRecord.cwd),
3394
- mcpServers: options.mcpServers,
3395
- permissionMode: options.permissionMode,
3396
- nonInteractivePermissions: options.nonInteractivePermissions,
3397
- authCredentials: options.authCredentials,
3398
- authPolicy: options.authPolicy,
3399
- fs: options.fs,
3400
- terminal: options.terminal,
3401
- suppressSdkConsoleErrors: options.suppressSdkConsoleErrors,
3402
- verbose: options.verbose,
3403
- sessionOptions: mergeSessionOptions(options.sessionOptions, sessionOptionsFromRecord(sessionRecord))
3404
- });
3405
- }
3406
- function createQueueOwnerTurnController(options) {
3407
- return new QueueOwnerTurnController({
3408
- withTimeout: async (run, timeoutMs) => await withTimeout(run(), timeoutMs),
3409
- setSessionModeFallback: async (modeId, timeoutMs) => {
3410
- await runSessionSetModeDirect({
3411
- sessionRecordId: options.sessionId,
3412
- modeId,
3413
- mcpServers: options.mcpServers,
3414
- nonInteractivePermissions: options.nonInteractivePermissions,
3415
- authCredentials: options.authCredentials,
3416
- authPolicy: options.authPolicy,
3417
- fs: options.fs,
3418
- terminal: options.terminal,
3419
- timeoutMs,
3420
- verbose: options.verbose
3421
- });
3422
- },
3423
- setSessionModelFallback: async (modelId, timeoutMs) => {
3424
- return (await runSessionSetModelDirect({
3425
- sessionRecordId: options.sessionId,
3426
- modelId,
3427
- mcpServers: options.mcpServers,
3428
- nonInteractivePermissions: options.nonInteractivePermissions,
3429
- authCredentials: options.authCredentials,
3430
- authPolicy: options.authPolicy,
3431
- fs: options.fs,
3432
- terminal: options.terminal,
3433
- timeoutMs,
3434
- verbose: options.verbose
3435
- })).response;
3436
- },
3437
- setSessionConfigOptionFallback: async (configId, value, timeoutMs) => {
3438
- return (await runSessionSetConfigOptionDirect({
3439
- sessionRecordId: options.sessionId,
3440
- configId,
3441
- value,
3442
- mcpServers: options.mcpServers,
3443
- nonInteractivePermissions: options.nonInteractivePermissions,
3444
- authCredentials: options.authCredentials,
3445
- authPolicy: options.authPolicy,
3446
- fs: options.fs,
3447
- terminal: options.terminal,
3448
- timeoutMs,
3449
- verbose: options.verbose
3450
- })).response;
3451
- }
3452
- });
3453
- }
3454
- function logDeferredCancelFailure(error, verbose) {
3455
- if (!verbose) return;
3456
- process.stderr.write(`[acpx] failed to apply deferred cancel: ${formatErrorMessage(error)}\n`);
3457
- }
3458
- function queueOwnerExitIsFatal(exit) {
3459
- return exit.exited && (exit.spawnError !== void 0 || exit.code !== 0 || exit.signal !== null);
3460
- }
3461
- function logQueueOwnerReady(params) {
3462
- if (!params.verbose) return;
3463
- process.stderr.write(`[acpx] queue owner ready for session ${params.sessionId} (ttlMs=${params.ttlMs}, maxQueueDepth=${params.maxQueueDepth})\n`);
3464
- }
3465
- async function closeQueueOwnerRuntime(params) {
3466
- if (params.heartbeatTimer) clearInterval(params.heartbeatTimer);
3467
- params.turnController.beginClosing();
3468
- await params.sharedClient.close().catch(() => {});
3469
- await params.owner?.close();
3470
- await writeQueueOwnerLifecycleSnapshot(params.sessionId, params.sharedClient);
3471
- await releaseQueueOwnerLease(params.lease);
3472
- if (params.verbose) process.stderr.write(`[acpx] queue owner stopped for session ${params.sessionId}\n`);
3473
- }
3474
- async function writeQueueOwnerLifecycleSnapshot(sessionId, sharedClient) {
3475
- try {
3476
- const record = await resolveSessionRecord(sessionId);
3477
- applyLifecycleSnapshotToRecord(record, sharedClient.getAgentLifecycleSnapshot());
3478
- await writeSessionRecord(record);
3479
- } catch {}
3480
- }
3481
- async function settlesWithin(promise, timeoutMs) {
3482
- let timer;
3483
- const timeout = new Promise((resolve) => {
3484
- timer = setTimeout(() => resolve(false), timeoutMs);
3485
- });
3486
- try {
3487
- return await Promise.race([promise.then(() => true, () => true), timeout]);
3488
- } finally {
3489
- if (timer) clearTimeout(timer);
3490
- }
3491
- }
3492
- function createQueueOwnerShutdownController(params) {
3493
- let requested = false;
3494
- let activeTurn;
3495
- let activeTurnShutdown;
3496
- let shutdownPromise;
3497
- const drainActiveTurn = async () => {
3498
- const turn = activeTurn;
3499
- if (!turn) return;
3500
- params.turnController.requestCancel().catch((error) => {
3501
- logDeferredCancelFailure(error, params.verbose);
3502
- });
3503
- if (!await settlesWithin(turn, QUEUE_OWNER_ACTIVE_TURN_CANCEL_GRACE_MS)) await params.sharedClient.close().catch(() => {});
3504
- await turn.catch(() => {});
3505
- };
3506
- const request = () => {
3507
- requested = true;
3508
- params.stopHeartbeat();
3509
- params.getOwner()?.beginShutdown();
3510
- activeTurnShutdown ??= drainActiveTurn();
3511
- };
3512
- return {
3513
- get requested() {
3514
- return requested;
3515
- },
3516
- request,
3517
- setActiveTurn: (turn) => {
3518
- activeTurn = turn;
3519
- },
3520
- clearActiveTurn: (turn) => {
3521
- if (activeTurn === turn) activeTurn = void 0;
3522
- },
3523
- shutdown: () => {
3524
- request();
3525
- shutdownPromise ??= (async () => {
3526
- await activeTurnShutdown;
3527
- await closeQueueOwnerRuntime({
3528
- lease: params.lease,
3529
- owner: params.getOwner(),
3530
- heartbeatTimer: void 0,
3531
- turnController: params.turnController,
3532
- sharedClient: params.sharedClient,
3533
- sessionId: params.sessionId,
3534
- verbose: params.verbose
3535
- });
3536
- })();
3537
- return shutdownPromise;
3538
- }
3539
- };
3540
- }
3541
- function applyRequestedShutdown(owner, shutdown) {
3542
- if (shutdown.requested) owner.beginShutdown();
3543
- }
3544
- function startQueueOwnerHeartbeat(params) {
3545
- if (!params.enabled) return;
3546
- return setInterval(() => {
3547
- refreshQueueOwnerLease(params.lease, { queueDepth: params.owner.queueDepth() }).catch(() => {});
3548
- }, QUEUE_OWNER_HEARTBEAT_INTERVAL_MS);
3549
- }
3550
- async function runSessionQueueOwner(options) {
3551
- const lease = await tryAcquireQueueOwnerLease(options.sessionId, {
3552
- path: options.mcpConfigPath,
3553
- fingerprint: options.mcpConfigFingerprint
3554
- });
3555
- if (!lease) return;
3556
- const sessionRecord = await resolveSessionRecord(options.sessionId);
3557
- let owner;
3558
- let heartbeatTimer;
3559
- const sharedClient = createQueueOwnerSharedClient(options, sessionRecord);
3560
- const ttlMs = normalizeQueueOwnerTtlMs(options.ttlMs);
3561
- const maxQueueDepth = Math.max(1, Math.round(options.maxQueueDepth ?? 16));
3562
- const taskPollTimeoutMs = ttlMs === 0 ? void 0 : ttlMs;
3563
- const initialTaskPollTimeoutMs = taskPollTimeoutMs == null ? void 0 : Math.max(taskPollTimeoutMs, 1e3);
3564
- const turnController = createQueueOwnerTurnController(options);
3565
- const applyPendingCancel = async () => {
3566
- return await turnController.applyPendingCancel();
3567
- };
3568
- const scheduleApplyPendingCancel = () => {
3569
- applyPendingCancel().catch((error) => {
3570
- logDeferredCancelFailure(error, options.verbose);
3571
- });
3572
- };
3573
- const setActiveController = (controller) => {
3574
- turnController.setActiveController(controller);
3575
- scheduleApplyPendingCancel();
3576
- };
3577
- const clearActiveController = () => {
3578
- turnController.clearActiveController();
3579
- };
3580
- const closeActiveBackendSession = async (timeoutMs) => {
3581
- const latestRecord = await resolveSessionRecord(options.sessionId);
3582
- if (!sharedClient.supportsCloseSession()) return false;
3583
- await withTimeout(sharedClient.closeSession(latestRecord.acpSessionId), timeoutMs);
3584
- return true;
3585
- };
3586
- const runPromptTurn = async (run) => {
3587
- turnController.beginTurn();
3588
- try {
3589
- return await run();
3590
- } finally {
3591
- turnController.endTurn();
3592
- }
3593
- };
3594
- const shutdown = createQueueOwnerShutdownController({
3595
- lease,
3596
- getOwner: () => owner,
3597
- stopHeartbeat: () => {
3598
- if (heartbeatTimer) {
3599
- clearInterval(heartbeatTimer);
3600
- heartbeatTimer = void 0;
3601
- }
3602
- },
3603
- turnController,
3604
- sharedClient,
3605
- sessionId: options.sessionId,
3606
- verbose: options.verbose
3607
- });
3608
- const onSignal = () => {
3609
- shutdown.request();
3610
- };
3611
- process.once("SIGINT", onSignal);
3612
- process.once("SIGTERM", onSignal);
3613
- process.once("SIGHUP", onSignal);
3614
- try {
3615
- owner = await SessionQueueOwner.start(lease, {
3616
- cancelPrompt: async () => {
3617
- if (!await turnController.requestCancel()) return false;
3618
- await applyPendingCancel();
3619
- return true;
3620
- },
3621
- closeSession: async (timeoutMs) => await closeActiveBackendSession(timeoutMs),
3622
- setSessionMode: async (modeId, timeoutMs) => {
3623
- await turnController.setSessionMode(modeId, timeoutMs);
3624
- },
3625
- setSessionModel: async (modelId, timeoutMs) => await turnController.setSessionModel(modelId, timeoutMs),
3626
- setSessionConfigOption: async (configId, value, timeoutMs) => {
3627
- return await turnController.setSessionConfigOption(configId, value, timeoutMs);
3628
- }
3629
- }, {
3630
- maxQueueDepth,
3631
- onQueueDepthChanged: (queueDepth) => {
3632
- setPerfGauge("queue.owner.depth", queueDepth);
3633
- refreshQueueOwnerLease(lease, { queueDepth }).catch(() => {});
3634
- }
3635
- });
3636
- applyRequestedShutdown(owner, shutdown);
3637
- logQueueOwnerReady({
3638
- sessionId: options.sessionId,
3639
- ttlMs,
3640
- maxQueueDepth,
3641
- verbose: options.verbose
3642
- });
3643
- await refreshQueueOwnerLease(lease, { queueDepth: owner.queueDepth() }).catch(() => {});
3644
- heartbeatTimer = startQueueOwnerHeartbeat({
3645
- enabled: !shutdown.requested,
3646
- lease,
3647
- owner
3648
- });
3649
- let isFirstTask = true;
3650
- while (true) {
3651
- const pollTimeoutMs = isFirstTask ? initialTaskPollTimeoutMs : taskPollTimeoutMs;
3652
- const task = await owner.nextTask(pollTimeoutMs);
3653
- if (!task) break;
3654
- isFirstTask = false;
3655
- const turnPromise = runPromptTurn(async () => {
3656
- try {
3657
- await runQueuedTask(options.sessionId, task, {
3658
- sharedClient,
3659
- verbose: options.verbose,
3660
- mcpServers: options.mcpServers,
3661
- nonInteractivePermissions: options.nonInteractivePermissions,
3662
- authCredentials: options.authCredentials,
3663
- authPolicy: options.authPolicy,
3664
- suppressSdkConsoleErrors: options.suppressSdkConsoleErrors,
3665
- promptRetries: task.promptRetries ?? 0,
3666
- sessionOptions: options.sessionOptions,
3667
- onClientAvailable: setActiveController,
3668
- onClientClosed: clearActiveController,
3669
- onPromptActive: async () => {
3670
- turnController.markPromptActive();
3671
- await applyPendingCancel();
3672
- },
3673
- handleProcessInterrupts: false
3674
- });
3675
- } finally {
3676
- checkpointPerfMetricsCapture();
3677
- }
3678
- });
3679
- shutdown.setActiveTurn(turnPromise);
3680
- try {
3681
- await turnPromise;
3682
- } finally {
3683
- shutdown.clearActiveTurn(turnPromise);
3684
- }
3685
- }
3686
- } finally {
3687
- process.off("SIGINT", onSignal);
3688
- process.off("SIGTERM", onSignal);
3689
- process.off("SIGHUP", onSignal);
3690
- await shutdown.shutdown();
3691
- }
3692
- }
3693
- async function sendSession(options) {
3694
- const waitForCompletion = options.waitForCompletion !== false;
3695
- const queuedToOwner = await submitToRunningOwner(options, waitForCompletion);
3696
- if (queuedToOwner) return queuedToOwner;
3697
- const owner = spawnQueueOwnerProcess(queueOwnerRuntimeOptionsFromSend(options));
3698
- const onQueueAccepted = () => {
3699
- owner.stopStartupCapture();
3700
- };
3701
- for (let attempt = 0; attempt < QUEUE_OWNER_STARTUP_MAX_ATTEMPTS; attempt += 1) {
3702
- const queued = await submitToRunningOwner(options, waitForCompletion, { onQueueAccepted });
3703
- if (queued) {
3704
- owner.stopStartupCapture();
3705
- return queued;
3706
- }
3707
- const exit = owner.getExitState();
3708
- if (queueOwnerExitIsFatal(exit)) {
3709
- const message = formatQueueOwnerStartupFailure({
3710
- sessionId: options.sessionId,
3711
- exit,
3712
- logTail: owner.readLogTail()
3713
- });
3714
- owner.stopStartupCapture();
3715
- throw new Error(message);
3716
- }
3717
- await waitMs(50);
3718
- }
3719
- const finalExit = owner.getExitState();
3720
- const message = formatQueueOwnerStartupFailure({
3721
- sessionId: options.sessionId,
3722
- exit: finalExit.exited ? finalExit : {
3723
- exited: false,
3724
- code: null,
3725
- signal: null
3726
- },
3727
- logTail: owner.readLogTail()
3728
- });
3729
- owner.stopStartupCapture();
3730
- throw new Error(message);
3731
- }
3732
- const queueOwnerRuntimeTestInternals = { queueOwnerExitIsFatal };
3733
- //#endregion
3734
- //#region src/session/session.ts
3735
- var session_exports = /* @__PURE__ */ __exportAll({
3736
- DEFAULT_HISTORY_LIMIT: () => 20,
3737
- DEFAULT_QUEUE_OWNER_TTL_MS: () => DEFAULT_QUEUE_OWNER_TTL_MS,
3738
- InterruptedError: () => InterruptedError,
3739
- TimeoutError: () => TimeoutError,
3740
- cancelSessionPrompt: () => cancelSessionPrompt,
3741
- closeSession: () => closeSession,
3742
- createSession: () => createSession,
3743
- createSessionWithClient: () => createSessionWithClient,
3744
- ensureSession: () => ensureSession,
3745
- findGitRepositoryRoot: () => findGitRepositoryRoot,
3746
- findSession: () => findSession,
3747
- findSessionByDirectoryWalk: () => findSessionByDirectoryWalk,
3748
- isProcessAlive: () => isProcessAlive,
3749
- listAgentSessions: () => listAgentSessions,
3750
- listSessions: () => listSessions,
3751
- listSessionsForAgent: () => listSessionsForAgent,
3752
- mergeConnectedModelState: () => mergeConnectedModelState,
3753
- normalizeQueueOwnerTtlMs: () => normalizeQueueOwnerTtlMs,
3754
- pruneSessions: () => pruneSessions,
3755
- queueOwnerRuntimeTestInternals: () => queueOwnerRuntimeTestInternals,
3756
- runOnce: () => runOnce,
3757
- runQueuedTask: () => runQueuedTask,
3758
- runSessionQueueOwner: () => runSessionQueueOwner,
3759
- sendSession: () => sendSession,
3760
- sendSessionDirect: () => sendSessionDirect,
3761
- sessionControlTestInternals: () => sessionControlTestInternals,
3762
- setSessionConfigOption: () => setSessionConfigOption,
3763
- setSessionMode: () => setSessionMode,
3764
- setSessionModel: () => setSessionModel
3765
- });
3766
- //#endregion
3767
- //#region src/acp/jsonrpc-error.ts
3768
- const OUTPUT_ERROR_JSONRPC_CODES = {
3769
- NO_SESSION: -32002,
3770
- TIMEOUT: -32070,
3771
- PERMISSION_DENIED: -32071,
3772
- PERMISSION_PROMPT_UNAVAILABLE: -32072,
3773
- RUNTIME: -32603,
3774
- USAGE: -32602
3775
- };
3776
- function hasValidAcpError(acp) {
3777
- return Boolean(acp && Number.isFinite(acp.code) && typeof acp.message === "string" && acp.message.trim().length > 0);
3778
- }
3779
- function buildFallbackData(params) {
3780
- const data = {
3781
- acpxCode: params.outputCode,
3782
- detailCode: params.detailCode,
3783
- origin: params.origin,
3784
- retryable: params.retryable,
3785
- timestamp: params.timestamp,
3786
- sessionId: params.sessionId
3787
- };
3788
- for (const [key, value] of Object.entries(data)) if (value === void 0) delete data[key];
3789
- return data;
3790
- }
3791
- function mergeAcpErrorData(acpData, fallbackData) {
3792
- if (Object.keys(fallbackData).length === 0) return acpData;
3793
- if (acpData === void 0) return fallbackData;
3794
- if (acpData && typeof acpData === "object" && !Array.isArray(acpData)) return {
3795
- ...fallbackData,
3796
- ...acpData
3797
- };
3798
- return acpData;
3799
- }
3800
- function buildErrorObject(params) {
3801
- const fallbackData = buildFallbackData(params);
3802
- if (hasValidAcpError(params.acp)) {
3803
- const data = mergeAcpErrorData(params.acp.data, fallbackData);
3804
- return {
3805
- code: params.acp.code,
3806
- message: params.acp.message,
3807
- ...data !== void 0 ? { data } : {}
3808
- };
3809
- }
3810
- const data = fallbackData;
3811
- return {
3812
- code: OUTPUT_ERROR_JSONRPC_CODES[params.outputCode] ?? -32603,
3813
- message: params.message,
3814
- ...Object.keys(data).length > 0 ? { data } : {}
3815
- };
3816
- }
3817
- function buildJsonRpcErrorResponse(params) {
3818
- return {
3819
- jsonrpc: "2.0",
3820
- id: params.id ?? null,
3821
- error: buildErrorObject(params)
3822
- };
3823
- }
3824
- //#endregion
3825
- //#region src/cli/output/read-suppression.ts
3826
- const SUPPRESSED_READ_OUTPUT = "[read output suppressed]";
3827
- function inferToolKindFromTitle(title) {
3828
- const normalized = title?.trim().toLowerCase();
3829
- if (!normalized) return;
3830
- const head = normalized.split(":", 1)[0]?.trim();
3831
- if (!head) return;
3832
- if ([
3833
- "read",
3834
- "cat",
3835
- "open",
3836
- "view"
3837
- ].some((needle) => head.includes(needle))) return "read";
3838
- }
3839
- function isReadLikeTool(tool) {
3840
- return tool.kind?.trim().toLowerCase() === "read" || inferToolKindFromTitle(tool.title) === "read";
3841
- }
3842
- //#endregion
3843
- //#region src/cli/output/json-formatter.ts
3844
- const DEFAULT_JSON_SESSION_ID = "unknown";
3845
- function asRecord$1(value) {
3846
- if (!value || typeof value !== "object" || Array.isArray(value)) return;
3847
- return value;
3848
- }
3849
- function jsonRpcIdKey(value) {
3850
- if (typeof value === "string") return `s:${value}`;
3851
- if (typeof value === "number" && Number.isFinite(value)) return `n:${value}`;
3852
- }
3853
- function sanitizeReadResult(result) {
3854
- const record = asRecord$1(result);
3855
- if (!record || typeof record.content !== "string") return result;
3856
- return {
3857
- ...record,
3858
- content: SUPPRESSED_READ_OUTPUT
3859
- };
3860
- }
3861
- function sanitizeToolContent(content) {
3862
- if (!Array.isArray(content)) return content;
3863
- return [{
3864
- type: "content",
3865
- content: {
3866
- type: "text",
3867
- text: SUPPRESSED_READ_OUTPUT
3868
- }
3869
- }];
3870
- }
3871
- function sanitizeToolMessage(message) {
3872
- const root = asRecord$1(message);
3873
- const params = asRecord$1(root?.params);
3874
- const update = asRecord$1(params?.update);
3875
- if (!root || !params || !update) return message;
3876
- return {
3877
- ...root,
3878
- params: {
3879
- ...params,
3880
- update: sanitizeToolUpdate(update)
3881
- }
3882
- };
3883
- }
3884
- function sanitizeToolUpdate(update) {
3885
- return {
3886
- ...update,
3887
- rawOutput: sanitizedRawOutput(update),
3888
- content: sanitizedContent(update)
3889
- };
3890
- }
3891
- function sanitizedRawOutput(update) {
3892
- if (Object.prototype.hasOwnProperty.call(update, "rawOutput") && update.rawOutput !== void 0) return { content: SUPPRESSED_READ_OUTPUT };
3893
- return update.rawOutput;
3894
- }
3895
- function sanitizedContent(update) {
3896
- if (Object.prototype.hasOwnProperty.call(update, "content") && update.content !== void 0) return sanitizeToolContent(update.content);
3897
- return update.content;
3898
- }
3899
- var JsonOutputFormatter = class {
3900
- stdout;
3901
- suppressReads;
3902
- sessionId;
3903
- requestMethodById = /* @__PURE__ */ new Map();
3904
- toolStateById = /* @__PURE__ */ new Map();
3905
- constructor(stdout, suppressReads, context) {
3906
- this.stdout = stdout;
3907
- this.suppressReads = suppressReads;
3908
- this.sessionId = context?.sessionId?.trim() || DEFAULT_JSON_SESSION_ID;
3909
- }
3910
- setContext(context) {
3911
- this.sessionId = context.sessionId?.trim() || this.sessionId || DEFAULT_JSON_SESSION_ID;
3912
- }
3913
- onAcpMessage(message) {
3914
- this.stdout.write(`${JSON.stringify(this.sanitizeMessage(message))}\n`);
3915
- }
3916
- sanitizeMessage(message) {
3917
- if (!this.suppressReads) return message;
3918
- const sanitizedResponse = this.sanitizeReadResponse(message);
3919
- if (sanitizedResponse !== message) return sanitizedResponse;
3920
- const sanitizedToolMessage = this.sanitizeReadToolMessage(message);
3921
- if (sanitizedToolMessage !== message) return sanitizedToolMessage;
3922
- this.trackRequestMethod(message);
3923
- return message;
3924
- }
3925
- trackRequestMethod(message) {
3926
- const candidate = message;
3927
- if (typeof candidate.method !== "string") return;
3928
- const idKey = jsonRpcIdKey(candidate.id);
3929
- if (!idKey) return;
3930
- this.requestMethodById.set(idKey, candidate.method);
3931
- }
3932
- sanitizeReadResponse(message) {
3933
- const candidate = message;
3934
- const idKey = jsonRpcIdKey(candidate.id);
3935
- if (!idKey) return message;
3936
- const hasResult = Object.hasOwn(candidate, "result");
3937
- const hasError = Object.hasOwn(candidate, "error");
3938
- if (!hasResult && !hasError) return message;
3939
- const method = this.requestMethodById.get(idKey);
3940
- this.requestMethodById.delete(idKey);
3941
- if (method !== "fs/read_text_file" || !hasResult) return message;
3942
- const root = asRecord$1(message);
3943
- if (!root) return message;
3944
- return {
3945
- ...root,
3946
- result: sanitizeReadResult(candidate.result)
3947
- };
3948
- }
3949
- sanitizeReadToolMessage(message) {
3950
- const update = this.readToolUpdate(message);
3951
- if (!update) return message;
3952
- const toolCallId = typeof update.toolCallId === "string" ? update.toolCallId : void 0;
3953
- if (!toolCallId) return message;
3954
- const current = this.mergeToolState(toolCallId, update);
3955
- this.toolStateById.set(toolCallId, current);
3956
- return isReadLikeTool(current) ? sanitizeToolMessage(message) : message;
3957
- }
3958
- readToolUpdate(message) {
3959
- const root = asRecord$1(message);
3960
- if (root?.method !== "session/update") return;
3961
- const params = asRecord$1(root.params);
3962
- const update = asRecord$1(params?.update);
3963
- if (!params || !update) return;
3964
- const sessionUpdate = update.sessionUpdate;
3965
- if (sessionUpdate !== "tool_call" && sessionUpdate !== "tool_call_update") return;
3966
- return update;
3967
- }
3968
- mergeToolState(toolCallId, update) {
3969
- const previous = this.toolStateById.get(toolCallId) ?? {};
3970
- return {
3971
- title: typeof update.title === "string" ? update.title : previous.title,
3972
- kind: typeof update.kind === "string" || update.kind === null ? update.kind : previous.kind
3973
- };
3974
- }
3975
- onError(params) {
3976
- this.stdout.write(`${JSON.stringify(buildJsonRpcErrorResponse({
3977
- outputCode: params.code,
3978
- detailCode: params.detailCode,
3979
- origin: params.origin,
3980
- message: params.message,
3981
- retryable: params.retryable,
3982
- timestamp: params.timestamp,
3983
- sessionId: this.sessionId,
3984
- acp: params.acp
3985
- }))}\n`);
3986
- }
3987
- onPermissionEscalation() {}
3988
- flush() {}
3989
- };
3990
- function createJsonOutputFormatter(stdout, suppressReads = false, context) {
3991
- return new JsonOutputFormatter(stdout, suppressReads, context);
3992
- }
3993
- //#endregion
3994
- //#region src/cli/output/output.ts
3995
- var output_exports = /* @__PURE__ */ __exportAll({
3996
- createOutputFormatter: () => createOutputFormatter,
3997
- getTextErrorRemediationHints: () => getTextErrorRemediationHints
3998
- });
3999
- const MAX_THOUGHT_CHARS = 900;
4000
- const MAX_INLINE_CHARS = 220;
4001
- const MAX_OUTPUT_CHARS = 2e3;
4002
- const MAX_OUTPUT_LINES = 28;
4003
- const MAX_LOCATION_ITEMS = 5;
4004
- const OUTPUT_PRIORITY_KEYS = [
4005
- "stdout",
4006
- "stderr",
4007
- "output",
4008
- "content",
4009
- "text",
4010
- "message",
4011
- "result",
4012
- "response",
4013
- "value"
4014
- ];
4015
- function asStatus(status) {
4016
- return status ?? "unknown";
4017
- }
4018
- function isFinalStatus(status) {
4019
- return status === "completed" || status === "failed";
4020
- }
4021
- function toStatusLabel(status) {
4022
- switch (status) {
4023
- case "in_progress": return "running";
4024
- case "pending": return "pending";
4025
- case "completed": return "completed";
4026
- case "failed": return "failed";
4027
- default: return "running";
4028
- }
4029
- }
4030
- function asRecord(value) {
4031
- if (!value || typeof value !== "object" || Array.isArray(value)) return;
4032
- return value;
4033
- }
4034
- function parseJsonRpcErrorSummary(message) {
4035
- const fallback = parseJsonRpcErrorMessage(message);
4036
- if (!fallback) return;
4037
- const details = asRecord(asRecord(message.error)?.data)?.details;
4038
- return typeof details === "string" && details.trim().length > 0 ? details.trim() : fallback;
4039
- }
4040
- function extractJsonRpcMethod(message) {
4041
- return Object.hasOwn(message, "method") ? message.method?.toString() : void 0;
4042
- }
4043
- function collapseWhitespace(value) {
4044
- return value.replace(/\s+/g, " ").trim();
4045
- }
4046
- function normalizeLineEndings(value) {
4047
- return value.replace(/\r\n?/g, "\n");
4048
- }
4049
- function truncate(value, maxChars) {
4050
- if (value.length <= maxChars) return value;
4051
- if (maxChars <= 3) return value.slice(0, maxChars);
4052
- return `${value.slice(0, maxChars - 3)}...`;
4053
- }
4054
- function toInline(value, maxChars = MAX_INLINE_CHARS) {
4055
- return truncate(collapseWhitespace(value), maxChars);
4056
- }
4057
- function indentBlock(value, prefix) {
4058
- return value.split("\n").map((line) => `${prefix}${line}`).join("\n");
4059
- }
4060
- function dedupeStrings(values) {
4061
- const seen = /* @__PURE__ */ new Set();
4062
- const result = [];
4063
- for (const value of values) {
4064
- if (seen.has(value)) continue;
4065
- seen.add(value);
4066
- result.push(value);
4067
- }
4068
- return result;
4069
- }
4070
- function safeJson(value, spacing) {
4071
- const seen = /* @__PURE__ */ new WeakSet();
4072
- try {
4073
- return JSON.stringify(value, (_key, entry) => {
4074
- if (typeof entry === "bigint") return `${entry}n`;
4075
- if (typeof entry === "function") return `[Function ${entry.name || "anonymous"}]`;
4076
- if (typeof entry === "symbol") return entry.toString();
4077
- if (entry && typeof entry === "object") {
4078
- if (seen.has(entry)) return "[Circular]";
4079
- seen.add(entry);
4080
- }
4081
- return entry;
4082
- }, spacing);
4083
- } catch {
4084
- return;
4085
- }
4086
- }
4087
- function readFirstString(source, keys) {
4088
- for (const key of keys) {
4089
- const value = source[key];
4090
- if (typeof value === "string" && value.trim()) return value.trim();
4091
- }
4092
- }
4093
- function readFirstFiniteNumber(source, keys) {
4094
- for (const key of keys) {
4095
- const value = source[key];
4096
- if (typeof value === "number" && Number.isFinite(value)) return value;
4097
- }
4098
- }
4099
- function formatMetadataNumber(value) {
4100
- return Number.isInteger(value) ? String(value) : String(Number(value.toFixed(8)));
4101
- }
4102
- function readFirstStringArray(source, keys) {
4103
- for (const key of keys) {
4104
- const value = source[key];
4105
- if (!Array.isArray(value)) continue;
4106
- const entries = value.map((entry) => typeof entry === "string" ? entry.trim() : "").filter((entry) => entry.length > 0);
4107
- if (entries.length > 0) return entries;
4108
- }
4109
- }
4110
- function formatDisjunction(values) {
4111
- if (values.length <= 1) return values[0] ?? "";
4112
- if (values.length === 2) return `${values[0]} or ${values[1]}`;
4113
- return `${values.slice(0, -1).join(", ")}, or ${values.at(-1)}`;
4114
- }
4115
- function parseAuthMethodIdsFromMessage(message) {
4116
- const methods = [];
4117
- const methodListMatch = message.match(/auth methods \[([^\]]+)\]/iu);
4118
- if (methodListMatch) methods.push(...methodListMatch[1].split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0));
4119
- const singleMethodMatch = message.match(/auth method ([\w.-]+)/iu);
4120
- if (singleMethodMatch) methods.push(singleMethodMatch[1]);
4121
- return dedupeStrings(methods);
4122
- }
4123
- function parseAuthMethodIdsFromAcpData(data) {
4124
- const record = asRecord(data);
4125
- if (!record) return [];
4126
- const methodIds = [];
4127
- if (typeof record.methodId === "string" && record.methodId.trim().length > 0) methodIds.push(record.methodId.trim());
4128
- if (Array.isArray(record.methods)) for (const entry of record.methods) {
4129
- const id = parseAuthMethodIdEntry(entry);
4130
- if (id) methodIds.push(id);
4131
- }
4132
- return dedupeStrings(methodIds);
4133
- }
4134
- function parseAuthMethodIdEntry(entry) {
4135
- if (typeof entry === "string" && entry.trim().length > 0) return entry.trim();
4136
- const id = asRecord(entry)?.id;
4137
- return typeof id === "string" && id.trim().length > 0 ? id.trim() : void 0;
4138
- }
4139
- function renderAuthRequiredHint(params) {
4140
- const methodIds = dedupeStrings([...parseAuthMethodIdsFromAcpData(params.acp?.data), ...parseAuthMethodIdsFromMessage(params.message)]);
4141
- if (methodIds.length === 0) return "hint: run `acpx config show` to locate the active config, then add the required credential under `auth` and retry.";
4142
- return `hint: run \`acpx config show\` to locate the active config, then add ${formatDisjunction(methodIds.map((methodId) => `\`auth.${methodId}\``))} and retry.`;
4143
- }
4144
- function getTextErrorRemediationHints(params) {
4145
- const lowerMessage = params.message.toLowerCase();
4146
- if (params.detailCode === "AUTH_REQUIRED") return [renderAuthRequiredHint(params)];
4147
- if (params.code === "TIMEOUT") return ["hint: increase `--timeout <seconds>` for long-running prompts, or check whether the agent/provider is stalled."];
4148
- if (params.code === "NO_SESSION") return noSessionHints(lowerMessage);
4149
- return matchingTextErrorRule(params, lowerMessage)?.hints ?? [];
4150
- }
4151
- const TEXT_ERROR_HINT_RULES = [
4152
- {
4153
- matches: (_params, lowerMessage) => isUnsupportedSessionLoadError(lowerMessage),
4154
- hints: ["hint: this adapter cannot resume saved ACP sessions; create a fresh one with `acpx <agent> sessions new` instead of reusing `--resume-session`."]
4155
- },
4156
- {
4157
- matches: (_params, lowerMessage) => isSessionLoadError(lowerMessage),
4158
- hints: ["hint: rerun with `--verbose` to capture the ACP load failure details.", "hint: if you do not need the old backend session, start a fresh one with `acpx <agent> sessions new` and retry."]
4159
- },
4160
- {
4161
- matches: (params, lowerMessage) => isRateLimitError(params.message, lowerMessage),
4162
- hints: ["hint: the provider appears rate-limited; retry later, switch model, or check provider quota/billing."]
4163
- },
4164
- {
4165
- matches: (_params, lowerMessage) => isModelLookupError(lowerMessage),
4166
- hints: ["hint: check the configured model name for this agent, then retry with `--model <model>` or `sessions set-model <model>`."]
4167
- },
4168
- {
4169
- matches: (_params, lowerMessage) => isSessionConfigMethodError(lowerMessage),
4170
- hints: ["hint: rerun with `--verbose` to capture the ACP method/error details before retrying."]
4171
- },
4172
- {
4173
- matches: isRuntimeAcpProtocolError,
4174
- hints: ["hint: rerun with `--verbose` to capture the underlying ACP error details."]
4175
- }
4176
- ];
4177
- function matchingTextErrorRule(params, lowerMessage) {
4178
- return TEXT_ERROR_HINT_RULES.find((rule) => rule.matches(params, lowerMessage));
4179
- }
4180
- function noSessionHints(lowerMessage) {
4181
- if (lowerMessage.includes("create one:")) return [];
4182
- return ["hint: the saved ACP session is missing or stale; start a fresh session with `acpx <agent> sessions new`, then retry."];
4183
- }
4184
- function isUnsupportedSessionLoadError(lowerMessage) {
4185
- return lowerMessage.includes("does not support session/resume") || lowerMessage.includes("does not support session/load");
4186
- }
4187
- function isSessionLoadError(lowerMessage) {
4188
- return lowerMessage.includes("failed to resume acp session") || lowerMessage.includes("session/resume") || lowerMessage.includes("session/load");
4189
- }
4190
- function isRateLimitError(message, lowerMessage) {
4191
- return /\b429\b/u.test(message) || ["rate limit", "quota exceeded"].some((text) => lowerMessage.includes(text));
4192
- }
4193
- function isModelLookupError(lowerMessage) {
4194
- return [
4195
- "model not found",
4196
- "unknown model",
4197
- "invalid model"
4198
- ].some((text) => lowerMessage.includes(text));
4199
- }
4200
- function isSessionConfigMethodError(lowerMessage) {
4201
- return [
4202
- "session/set_mode",
4203
- "session/set_model",
4204
- "session/set_config_option"
4205
- ].some((text) => lowerMessage.includes(text));
4206
- }
4207
- function isRuntimeAcpProtocolError(params, lowerMessage) {
4208
- return params.origin === "acp" && params.code === "RUNTIME" && (params.acp?.code === -32602 || params.acp?.code === -32603 || lowerMessage.includes("internal error"));
4209
- }
4210
- function summarizeToolInput(rawInput) {
4211
- if (rawInput == null) return;
4212
- if (isScalarToolInput(rawInput)) return toInline(String(rawInput));
4213
- const record = asRecord(rawInput);
4214
- if (record) return summarizeToolInputRecord(record) ?? summarizeToolInputJson(rawInput);
4215
- return summarizeToolInputJson(rawInput);
4216
- }
4217
- function isScalarToolInput(value) {
4218
- return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
4219
- }
4220
- function summarizeToolInputRecord(record) {
4221
- const command = readFirstString(record, [
4222
- "command",
4223
- "cmd",
4224
- "program"
4225
- ]);
4226
- const args = readFirstStringArray(record, ["args", "arguments"]);
4227
- if (command) return toInline([command, ...args ?? []].join(" "));
4228
- const location = readFirstString(record, [
4229
- "path",
4230
- "file",
4231
- "filePath",
4232
- "filepath",
4233
- "target",
4234
- "uri",
4235
- "url"
4236
- ]);
4237
- const query = readFirstString(record, [
4238
- "query",
4239
- "pattern",
4240
- "text",
4241
- "search"
4242
- ]);
4243
- return location || query ? toInline(location ?? query ?? "") : void 0;
4244
- }
4245
- function summarizeToolInputJson(rawInput) {
4246
- const json = safeJson(rawInput, 0);
4247
- return json ? toInline(json) : void 0;
4248
- }
4249
- function formatLocations(locations) {
4250
- if (!locations || locations.length === 0) return;
4251
- const unique = /* @__PURE__ */ new Set();
4252
- for (const location of locations) {
4253
- const formatted = formatLocation(location);
4254
- if (formatted) unique.add(formatted);
4255
- }
4256
- const items = [...unique];
4257
- if (items.length === 0) return;
4258
- const visible = items.slice(0, MAX_LOCATION_ITEMS);
4259
- const hidden = items.length - visible.length;
4260
- if (hidden <= 0) return visible.join(", ");
4261
- return `${visible.join(", ")}, +${hidden} more`;
4262
- }
4263
- function formatLocation(location) {
4264
- const path = location.path?.trim();
4265
- if (!path) return;
4266
- return `${path}${typeof location.line === "number" && Number.isFinite(location.line) ? `:${Math.max(1, Math.trunc(location.line))}` : ""}`;
4267
- }
4268
- function summarizeDiff(path, oldText, newText) {
4269
- const oldLines = oldText ? oldText.split("\n").length : 0;
4270
- const delta = newText.split("\n").length - oldLines;
4271
- if (delta === 0) return `diff ${path} (line count unchanged)`;
4272
- return `diff ${path} (${`${delta > 0 ? "+" : ""}${delta}`} lines)`;
4273
- }
4274
- function textFromContentBlock(content) {
4275
- switch (content.type) {
4276
- case "text": return content.text;
4277
- case "resource_link": return content.title ?? content.name ?? content.uri;
4278
- case "resource": return textFromResourceBlock(content);
4279
- case "image": return `[image] ${content.mimeType}`;
4280
- case "audio": return `[audio] ${content.mimeType}`;
4281
- default: return;
4282
- }
4283
- }
4284
- function textFromResourceBlock(content) {
4285
- if ("text" in content.resource && typeof content.resource.text === "string") return content.resource.text;
4286
- const uri = content.resource.uri;
4287
- const mimeType = content.resource.mimeType;
4288
- return `[resource] ${uri}${mimeType ? ` (${mimeType})` : ""}`;
4289
- }
4290
- function summarizeToolContent(content) {
4291
- if (!content || content.length === 0) return;
4292
- const fragments = [];
4293
- for (const entry of content) {
4294
- const fragment = summarizeToolContentEntry(entry);
4295
- if (fragment) fragments.push(fragment);
4296
- }
4297
- const unique = dedupeStrings(fragments.map((fragment) => fragment.trim()).filter((fragment) => fragment.length > 0));
4298
- if (unique.length === 0) return;
4299
- return unique.join("\n\n");
4300
- }
4301
- function summarizeToolContentEntry(entry) {
4302
- if (entry.type === "content") {
4303
- const text = textFromContentBlock(entry.content);
4304
- return text && text.trim() ? text.trimEnd() : void 0;
4305
- }
4306
- if (entry.type === "diff") return summarizeDiff(entry.path, entry.oldText, entry.newText);
4307
- if (entry.type === "terminal") return `[terminal] ${entry.terminalId}`;
4308
- }
4309
- function extractOutputText(value, depth = 0, seen = /* @__PURE__ */ new Set()) {
4310
- if (value == null) return;
4311
- const scalar = extractScalarOutputText(value);
4312
- if (scalar !== null) return scalar;
4313
- if (depth >= 4) return;
4314
- if (Array.isArray(value)) return extractOutputTextArray(value, depth, seen);
4315
- return extractOutputTextRecord(value, depth, seen);
4316
- }
4317
- function extractOutputTextRecord(value, depth, seen) {
4318
- const record = asRecord(value);
4319
- if (!record || seen.has(record)) return;
4320
- seen.add(record);
4321
- return extractPreferredOutputText(record, depth, seen) ?? extractJsonOutputText(record);
4322
- }
4323
- function extractScalarOutputText(value) {
4324
- if (typeof value === "string") {
4325
- const trimmed = value.trimEnd();
4326
- return trimmed.length > 0 ? trimmed : void 0;
4327
- }
4328
- if (typeof value === "number" || typeof value === "boolean") return String(value);
4329
- return null;
4330
- }
4331
- function extractOutputTextArray(value, depth, seen) {
4332
- const parts = value.map((entry) => extractOutputText(entry, depth + 1, seen)).filter((entry) => Boolean(entry));
4333
- return parts.length > 0 ? dedupeStrings(parts).join("\n") : void 0;
4334
- }
4335
- function extractPreferredOutputText(record, depth, seen) {
4336
- const uniquePreferred = dedupeStrings(OUTPUT_PRIORITY_KEYS.flatMap((key) => {
4337
- if (!(key in record)) return [];
4338
- const extracted = extractOutputText(record[key], depth + 1, seen);
4339
- return extracted ? [extracted] : [];
4340
- }));
4341
- return uniquePreferred.length > 0 ? uniquePreferred.join("\n") : void 0;
4342
- }
4343
- function extractJsonOutputText(record) {
4344
- const json = safeJson(record, 2);
4345
- return !json || json === "{}" ? void 0 : json;
4346
- }
4347
- function summarizeToolOutput(rawOutput, content) {
4348
- const fragments = dedupeStrings([extractOutputText(rawOutput), summarizeToolContent(content)].map((fragment) => fragment?.trim()).filter((fragment) => Boolean(fragment)));
4349
- if (fragments.length === 0) return;
4350
- return fragments.join("\n\n");
4351
- }
4352
- function renderToolOutput(state, suppressReads) {
4353
- if (suppressReads && isReadLikeTool(state)) return SUPPRESSED_READ_OUTPUT;
4354
- return summarizeToolOutput(state.rawOutput, state.content);
4355
- }
4356
- function limitOutputBlock(value) {
4357
- const normalized = value.replace(/\r\n/g, "\n").trim();
4358
- if (!normalized) return "";
4359
- const lines = normalized.split("\n");
4360
- const visible = lines.slice(0, MAX_OUTPUT_LINES);
4361
- let result = visible.join("\n");
4362
- if (lines.length > visible.length) {
4363
- const hidden = lines.length - visible.length;
4364
- result += `\n... (${hidden} more lines)`;
4365
- }
4366
- if (result.length > MAX_OUTPUT_CHARS) result = `${result.slice(0, 1997)}...`;
4367
- return result;
4368
- }
4369
- var TextOutputFormatter = class {
4370
- stdout;
4371
- useColor;
4372
- suppressReads;
4373
- toolStates = /* @__PURE__ */ new Map();
4374
- thoughtBuffer = "";
4375
- wroteAny = false;
4376
- atLineStart = true;
4377
- section = null;
4378
- constructor(stdout, suppressReads) {
4379
- this.stdout = stdout;
4380
- this.useColor = Boolean(stdout.isTTY);
4381
- this.suppressReads = suppressReads;
4382
- }
4383
- setContext(_context) {}
4384
- onAcpMessage(message) {
4385
- const notification = extractSessionUpdateNotification(message);
4386
- if (notification) {
4387
- this.renderSessionUpdate(notification);
4388
- return;
4389
- }
4390
- const method = extractJsonRpcMethod(message);
4391
- if (method && method !== "session/prompt" && method !== "session/cancel") {
4392
- this.onClientOperation({
4393
- method,
4394
- status: "running",
4395
- summary: method,
4396
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
4397
- });
4398
- return;
4399
- }
4400
- const stopReason = parsePromptStopReason(message);
4401
- if (stopReason) {
4402
- this.renderDone(stopReason);
4403
- return;
4404
- }
4405
- const errorMessage = parseJsonRpcErrorSummary(message);
4406
- if (errorMessage) this.onError({
4407
- code: "RUNTIME",
4408
- origin: "acp",
4409
- message: errorMessage
4410
- });
4411
- }
4412
- renderSessionUpdate(notification) {
4413
- const update = notification.update;
4414
- if (update.sessionUpdate !== "agent_thought_chunk") this.flushThoughtBuffer();
4415
- this.renderSessionUpdateBody(update);
4416
- }
4417
- renderSessionUpdateBody(update) {
4418
- switch (update.sessionUpdate) {
4419
- case "agent_message_chunk":
4420
- if (update.content.type === "text") this.writeAssistantChunk(update.content.text);
4421
- return;
4422
- case "agent_thought_chunk":
4423
- if (update.content.type === "text") this.thoughtBuffer += update.content.text;
4424
- return;
4425
- case "tool_call":
4426
- this.renderToolUpdate(update);
4427
- return;
4428
- case "tool_call_update":
4429
- this.renderToolUpdate(update);
4430
- return;
4431
- case "plan":
4432
- this.renderPlanUpdate(update.entries);
4433
- return;
4434
- default: return;
4435
- }
4436
- }
4437
- renderPlanUpdate(entries) {
4438
- this.beginSection("plan");
4439
- this.writeLine(this.bold("[plan]"));
4440
- for (const entry of entries) this.writeLine(` - [${entry.status}] ${entry.content}`);
4441
- }
4442
- renderDone(stopReason) {
4443
- this.flushThoughtBuffer();
4444
- this.beginSection("done");
4445
- this.writeLine(this.dim(`[done] ${stopReason}`));
4446
- }
4447
- onError(params) {
4448
- this.flushThoughtBuffer();
4449
- this.beginSection("done");
4450
- this.writeLine(this.formatAnsi(`[error] ${params.code}: ${params.message}`, "31"));
4451
- for (const hint of getTextErrorRemediationHints(params)) this.writeLine(this.dim(hint));
4452
- }
4453
- onClientOperation(operation) {
4454
- this.flushThoughtBuffer();
4455
- this.beginSection("client");
4456
- const normalizedStatus = operation.status === "completed" ? "completed" : operation.status === "failed" ? "failed" : "in_progress";
4457
- const statusText = this.colorStatus(operation.status, normalizedStatus);
4458
- this.writeLine(`${this.bold("[client]")} ${operation.summary} (${statusText})`);
4459
- if (operation.details && operation.details.trim().length > 0) {
4460
- this.writeLine(" details:");
4461
- this.writeLine(indentBlock(operation.details, " "));
4462
- }
4463
- }
4464
- onPermissionEscalation(event) {
4465
- this.flushThoughtBuffer();
4466
- this.beginSection("client");
4467
- this.writeLine(`${this.bold("[permission]")} ${event.message}`);
4468
- const details = [
4469
- `sessionId: ${event.sessionId}`,
4470
- `toolCallId: ${event.toolCallId}`,
4471
- event.toolName ? `toolName: ${event.toolName}` : void 0,
4472
- `toolTitle: ${event.toolTitle}`,
4473
- event.toolInput !== void 0 ? `toolInput: ${summarizeToolInput(event.toolInput) ?? "(structured input)"}` : void 0,
4474
- event.toolKind ? `toolKind: ${event.toolKind}` : void 0,
4475
- event.matchedRule ? `matchedRule: ${event.matchedRule}` : void 0
4476
- ].filter((line) => Boolean(line));
4477
- this.writeLine(indentBlock(details.join("\n"), " "));
4478
- }
4479
- flush() {
4480
- this.flushThoughtBuffer();
4481
- if (!this.atLineStart) this.write("\n");
4482
- }
4483
- write(chunk) {
4484
- if (!chunk) return;
4485
- this.stdout.write(chunk);
4486
- this.wroteAny = true;
4487
- this.atLineStart = chunk.endsWith("\n");
4488
- }
4489
- writeLine(line) {
4490
- this.write(`${line}\n`);
4491
- }
4492
- beginSection(next) {
4493
- if (!this.atLineStart) this.write("\n");
4494
- if (this.wroteAny) this.write("\n");
4495
- this.section = next;
4496
- }
4497
- writeAssistantChunk(text) {
4498
- if (!text) return;
4499
- this.section = "assistant";
4500
- this.write(text);
4501
- }
4502
- flushThoughtBuffer() {
4503
- const thought = truncate(normalizeLineEndings(this.thoughtBuffer).trim(), MAX_THOUGHT_CHARS);
4504
- this.thoughtBuffer = "";
4505
- if (!thought) return;
4506
- this.beginSection("thought");
4507
- const [firstLine, ...restLines] = thought.split("\n");
4508
- this.writeLine(this.dim(`[thinking] ${firstLine}`));
4509
- for (const line of restLines) this.writeLine(this.dim(` ${line}`));
4510
- }
4511
- renderToolUpdate(update) {
4512
- const state = this.getOrCreateToolState(update.toolCallId);
4513
- this.mergeToolState(state, update);
4514
- const status = asStatus(state.status);
4515
- if (isFinalStatus(status)) {
4516
- const signature = this.toolSignature(state);
4517
- if (signature !== state.finalSignature) {
4518
- state.finalSignature = signature;
4519
- this.renderFinalToolState(state, status);
4520
- }
4521
- return;
4522
- }
4523
- if (state.startedPrinted) return;
4524
- state.startedPrinted = true;
4525
- this.renderStartingToolState(state, status);
4526
- }
4527
- getOrCreateToolState(toolCallId) {
4528
- const existing = this.toolStates.get(toolCallId);
4529
- if (existing) return existing;
4530
- const created = {
4531
- id: toolCallId,
4532
- startedPrinted: false
4533
- };
4534
- this.toolStates.set(toolCallId, created);
4535
- return created;
4536
- }
4537
- mergeToolState(state, update) {
4538
- this.mergeToolTitle(state, update.title);
4539
- this.mergeToolPayloadState(state, update);
4540
- }
4541
- mergeToolTitle(state, title) {
4542
- if (typeof title === "string" && title.trim().length > 0) state.title = title;
4543
- }
4544
- mergeToolPayloadState(state, update) {
4545
- if (update.status !== void 0) state.status = update.status;
4546
- if (update.kind !== void 0) state.kind = update.kind;
4547
- if (update.locations !== void 0) state.locations = update.locations;
4548
- if (update.rawInput !== void 0) state.rawInput = update.rawInput;
4549
- if (update.rawOutput !== void 0) state.rawOutput = update.rawOutput;
4550
- if (update.content !== void 0) state.content = update.content;
4551
- }
4552
- toolSignature(state) {
4553
- const signaturePayload = {
4554
- title: state.title,
4555
- status: state.status,
4556
- kind: state.kind,
4557
- input: summarizeToolInput(state.rawInput),
4558
- files: formatLocations(state.locations),
4559
- output: renderToolOutput(state, this.suppressReads)
4560
- };
4561
- return safeJson(signaturePayload, 0) ?? JSON.stringify(signaturePayload);
4562
- }
4563
- renderStartingToolState(state, status) {
4564
- this.beginSection("tool");
4565
- const title = state.title ?? state.id;
4566
- const label = status === "pending" ? "pending" : "running";
4567
- const statusText = this.colorStatus(label, status);
4568
- this.writeLine(`${this.bold("[tool]")} ${title} (${statusText})`);
4569
- const input = summarizeToolInput(state.rawInput);
4570
- if (input) this.writeLine(` input: ${input}`);
4571
- const files = formatLocations(state.locations);
4572
- if (files) this.writeLine(` files: ${files}`);
4573
- }
4574
- renderFinalToolState(state, status) {
4575
- this.beginSection("tool");
4576
- const title = state.title ?? state.id;
4577
- const statusText = this.colorStatus(toStatusLabel(status), status);
4578
- this.writeLine(`${this.bold("[tool]")} ${title} (${statusText})`);
4579
- if (state.kind) this.writeLine(` kind: ${state.kind}`);
4580
- const input = summarizeToolInput(state.rawInput);
4581
- if (input) this.writeLine(` input: ${input}`);
4582
- const files = formatLocations(state.locations);
4583
- if (files) this.writeLine(` files: ${files}`);
4584
- const output = renderToolOutput(state, this.suppressReads);
4585
- if (output) {
4586
- this.writeLine(" output:");
4587
- this.writeLine(indentBlock(limitOutputBlock(output), " "));
4588
- }
4589
- }
4590
- formatAnsi(text, code) {
4591
- if (!this.useColor) return text;
4592
- return `\u001b[${code}m${text}\u001b[0m`;
4593
- }
4594
- bold(text) {
4595
- return this.formatAnsi(text, "1");
4596
- }
4597
- dim(text) {
4598
- return this.formatAnsi(text, "2");
4599
- }
4600
- colorStatus(text, status) {
4601
- if (!this.useColor) return text;
4602
- switch (status) {
4603
- case "completed": return this.formatAnsi(text, "32");
4604
- case "failed": return this.formatAnsi(text, "31");
4605
- default: return this.formatAnsi(text, "33");
4606
- }
4607
- }
4608
- };
4609
- var QuietOutputFormatter = class {
4610
- stdout;
4611
- stderr;
4612
- chunks = [];
4613
- flushed = false;
4614
- metadataFlushed = false;
4615
- constructor(stdout, stderr) {
4616
- this.stdout = stdout;
4617
- this.stderr = stderr;
4618
- }
4619
- setContext(_context) {}
4620
- onAcpMessage(message) {
4621
- const update = extractSessionUpdateNotification(message);
4622
- if (update?.update.sessionUpdate === "agent_message_chunk" && update.update.content.type === "text") {
4623
- this.chunks.push(update.update.content.text);
4624
- return;
4625
- }
4626
- if (parsePromptStopReason(message)) {
4627
- this.flushBufferedOutput();
4628
- this.flushMetadata(message);
4629
- }
4630
- }
4631
- onError(params) {
4632
- const qualifier = params.detailCode ? `${params.code} ${params.detailCode}` : params.code;
4633
- const message = preferredAcpErrorDetails(params.acp) ?? params.message;
4634
- this.stderr.write(`[acpx] error: ${qualifier} ${message.replace(/\r\n?|\n/g, " ")}\n`);
4635
- }
4636
- onPermissionEscalation(_event) {}
4637
- flush() {}
4638
- flushBufferedOutput() {
4639
- if (this.flushed) return;
4640
- this.flushed = true;
4641
- const text = this.chunks.join("");
4642
- this.stdout.write(text.endsWith("\n") ? text : `${text}\n`);
4643
- }
4644
- flushMetadata(message) {
4645
- if (this.metadataFlushed) return;
4646
- this.metadataFlushed = true;
4647
- const result = asRecord(message.result);
4648
- if (!result) return;
4649
- const usageLine = this.formatUsageLine(asRecord(result.usage));
4650
- if (usageLine) this.stderr.write(`${usageLine}\n`);
4651
- const costLine = this.formatCostLine(result.cost);
4652
- if (costLine) this.stderr.write(`${costLine}\n`);
4653
- }
4654
- formatUsageLine(usage) {
4655
- if (!usage) return;
4656
- const parts = [];
4657
- for (const [label, keys] of [
4658
- ["input", ["inputTokens", "input_tokens"]],
4659
- ["output", ["outputTokens", "output_tokens"]],
4660
- ["cache_read", [
4661
- "cachedReadTokens",
4662
- "cacheReadInputTokens",
4663
- "cache_read_input_tokens"
4664
- ]],
4665
- ["cache_write", [
4666
- "cachedWriteTokens",
4667
- "cacheCreationInputTokens",
4668
- "cache_creation_input_tokens"
4669
- ]],
4670
- ["total", ["totalTokens", "total_tokens"]]
4671
- ]) {
4672
- const value = readFirstFiniteNumber(usage, keys);
4673
- if (value !== void 0) parts.push(`${label}=${formatMetadataNumber(value)}`);
4674
- }
4675
- return parts.length > 0 ? `[acpx] tokens: ${parts.join(" ")}` : void 0;
4676
- }
4677
- formatCostLine(cost) {
4678
- const scalar = this.formatScalarCostLine(cost);
4679
- if (scalar) return scalar;
4680
- const record = asRecord(cost);
4681
- if (!record) return;
4682
- const amount = readFirstFiniteNumber(record, [
4683
- "amount",
4684
- "value",
4685
- "total"
4686
- ]);
4687
- if (amount === void 0) return;
4688
- const currency = typeof record.currency === "string" && record.currency.trim() ? ` ${record.currency.trim()}` : "";
4689
- return `[acpx] cost: ${formatMetadataNumber(amount)}${currency}`;
4690
- }
4691
- formatScalarCostLine(cost) {
4692
- if (typeof cost === "number" && Number.isFinite(cost)) return `[acpx] cost: ${formatMetadataNumber(cost)}`;
4693
- if (typeof cost === "string" && cost.trim()) return `[acpx] cost: ${cost.trim()}`;
4694
- }
4695
- };
4696
- function preferredAcpErrorDetails(acp) {
4697
- const details = asRecord(acp?.data)?.details;
4698
- return typeof details === "string" && details.trim().length > 0 ? details.trim() : void 0;
4699
- }
4700
- function createOutputFormatter(format, options = {}) {
4701
- const stdout = options.stdout ?? process.stdout;
4702
- const stderr = options.stderr ?? process.stderr;
4703
- const suppressReads = options.suppressReads === true;
4704
- switch (format) {
4705
- case "text": return new TextOutputFormatter(stdout, suppressReads);
4706
- case "json": return createJsonOutputFormatter(stdout, suppressReads, options.jsonContext);
4707
- case "quiet": return new QuietOutputFormatter(stdout, stderr);
4708
- default: throw new Error("Unsupported output format");
4709
- }
4710
- }
4711
- //#endregion
4712
- export { runSessionQueueOwner as a, buildQueueOwnerArgOverride as c, createSessionWithClient as d, cancelSessionPrompt as f, __exportAll as g, isProcessAlive as h, session_exports as i, flushPerfMetricsCapture as l, DEFAULT_QUEUE_OWNER_TTL_MS as m, getTextErrorRemediationHints as n, runOnce as o, probeQueueOwnerHealth as p, output_exports as r, sendSessionDirect as s, createOutputFormatter as t, installPerfMetricsCapture as u };
4713
-
4714
- //# sourceMappingURL=output-8-D6Gd4Z.js.map