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