@1agents/acp-service 0.3.0 → 0.4.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 +57 -33
- package/dist/bin/acp-service.js +2 -2
- package/dist/src/bridge.d.ts +2 -2
- package/dist/src/bridge.js +1 -1
- package/dist/src/catalog.js +20 -3
- package/dist/src/manifest.js +1 -1
- package/package.json +27 -8
- package/vendor/runtime/LICENSE +21 -0
- package/vendor/runtime/README.md +115 -0
- package/vendor/runtime/dist/agent-registry-CMg8LHKY.js +806 -0
- package/vendor/runtime/dist/agent-registry-CMg8LHKY.js.map +1 -0
- package/vendor/runtime/dist/agent-registry.d.ts +70 -0
- package/vendor/runtime/dist/agent-registry.d.ts.map +1 -0
- package/vendor/runtime/dist/agent-registry.js +2 -0
- package/vendor/runtime/dist/cli-DUHyAADv.js +182 -0
- package/vendor/runtime/dist/cli-DUHyAADv.js.map +1 -0
- package/vendor/runtime/dist/cli.d.ts +12 -0
- package/vendor/runtime/dist/cli.d.ts.map +1 -0
- package/vendor/runtime/dist/cli.js +2632 -0
- package/vendor/runtime/dist/cli.js.map +1 -0
- package/vendor/runtime/dist/client-DjkWknf7.d.ts +262 -0
- package/vendor/runtime/dist/client-DjkWknf7.d.ts.map +1 -0
- package/vendor/runtime/dist/docs-site/.nojekyll +0 -0
- package/vendor/runtime/dist/docs-site/CLI.html +832 -0
- package/vendor/runtime/dist/docs-site/CNAME +1 -0
- package/vendor/runtime/dist/docs-site/VISION.html +415 -0
- package/vendor/runtime/dist/docs-site/agents.html +391 -0
- package/vendor/runtime/dist/docs-site/compare.html +359 -0
- package/vendor/runtime/dist/docs-site/config.html +450 -0
- package/vendor/runtime/dist/docs-site/custom-agents.html +408 -0
- package/vendor/runtime/dist/docs-site/exit-codes.html +347 -0
- package/vendor/runtime/dist/docs-site/favicon.svg +21 -0
- package/vendor/runtime/dist/docs-site/flows.html +497 -0
- package/vendor/runtime/dist/docs-site/index.html +367 -0
- package/vendor/runtime/dist/docs-site/install.html +386 -0
- package/vendor/runtime/dist/docs-site/llms.txt +35 -0
- package/vendor/runtime/dist/docs-site/output-formats.html +403 -0
- package/vendor/runtime/dist/docs-site/permissions.html +413 -0
- package/vendor/runtime/dist/docs-site/prompting.html +460 -0
- package/vendor/runtime/dist/docs-site/proof-2026-07-18-grok-ext-methods/index.html +336 -0
- package/vendor/runtime/dist/docs-site/quickstart.html +382 -0
- package/vendor/runtime/dist/docs-site/runtime-environment.html +329 -0
- package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +335 -0
- package/vendor/runtime/dist/docs-site/session-control.html +406 -0
- package/vendor/runtime/dist/docs-site/session-watch.html +354 -0
- package/vendor/runtime/dist/docs-site/sessions.html +486 -0
- package/vendor/runtime/dist/docs-site/shared-sessions.html +377 -0
- package/vendor/runtime/dist/flows-CiJSCy4D.js +2474 -0
- package/vendor/runtime/dist/flows-CiJSCy4D.js.map +1 -0
- package/vendor/runtime/dist/flows.d.ts +334 -0
- package/vendor/runtime/dist/flows.d.ts.map +1 -0
- package/vendor/runtime/dist/flows.js +2 -0
- package/vendor/runtime/dist/invocation-options-BlIySxIw.js +345 -0
- package/vendor/runtime/dist/invocation-options-BlIySxIw.js.map +1 -0
- package/vendor/runtime/dist/ipc-BlljKR2b.js +5336 -0
- package/vendor/runtime/dist/ipc-BlljKR2b.js.map +1 -0
- package/vendor/runtime/dist/output-BzXQKArM.js +1012 -0
- package/vendor/runtime/dist/output-BzXQKArM.js.map +1 -0
- package/vendor/runtime/dist/queue-owner-runtime-DSFdsS_y.js +8867 -0
- package/vendor/runtime/dist/queue-owner-runtime-DSFdsS_y.js.map +1 -0
- package/vendor/runtime/dist/runtime.d.ts +1156 -0
- package/vendor/runtime/dist/runtime.d.ts.map +1 -0
- package/vendor/runtime/dist/runtime.js +3675 -0
- package/vendor/runtime/dist/runtime.js.map +1 -0
- package/vendor/runtime/dist/session-options-ORCchZGk.d.ts +426 -0
- package/vendor/runtime/dist/session-options-ORCchZGk.d.ts.map +1 -0
- package/vendor/runtime/dist/session-watch-BiBTBMz4.js +76 -0
- package/vendor/runtime/dist/session-watch-BiBTBMz4.js.map +1 -0
- package/vendor/runtime/dist/watch-iYiP-lOo.js +85 -0
- package/vendor/runtime/dist/watch-iYiP-lOo.js.map +1 -0
- package/vendor/runtime/package.json +46 -0
- package/vendor/runtime/skills/acpx/SKILL.md +688 -0
|
@@ -0,0 +1,3675 @@
|
|
|
1
|
+
import { A as findSession, B as assertPersistedKeyPolicy, C as textPrompt, Ct as normalizeOutputError, H as serializeSessionRecordForDisk, L as readSessionRecord, R as resolveSessionRecord, Tt as isAcpResourceNotFoundError, V as parseSessionRecord, gt as writePrivateJsonFile, t as tryCancelOnRunningOwner, ut as defaultSessionEventLog, wt as extractAcpError } from "./ipc-BlljKR2b.js";
|
|
2
|
+
import { a as createAgentRegistry, i as DEFAULT_AGENT_NAME, k as normalizeAgentCommandInput } from "./agent-registry-CMg8LHKY.js";
|
|
3
|
+
import { $ as isRequestedModelUnsupportedError, A as applyInitialModelSelection, B as reconcileAgentSessionId, C as setSessionModeOnOwner, D as connectAndLoadSession, E as withConnectedSession, F as persistSessionOptions, G as recordSessionUpdate, I as sessionOptionsFromRecord, J as advertisedModelState, K as trimConversationForRuntime, L as applyConversation, M as applyRequestedModelIfAdvertised, N as setDesiredModeId, O as applyConfigOptionSelection, P as normalizeSessionOptionShape, Q as RequestedModelUnsupportedError, R as applyLifecycleSnapshotToRecord, T as setSessionModelOnOwner, U as recordClientOperation, V as cloneSessionConversation, W as recordPromptSubmission, X as REQUESTED_MODEL_UNSUPPORTED_ERROR_CODE, Y as AcpClient, Z as REQUESTED_MODEL_UNSUPPORTED_REASONS, _ as cancelSessionPrompt, c as LiveSessionCheckpoint, dt as TimeoutError, et as resolveRequestedConfigOption, ft as assertControlAuthority, h as ensureSession, j as applyModelSelection, k as applyConfigOptionsToRecord, l as runPromptTurn, mt as withTimeout, q as cloneSessionAcpxState, r as sendSession, s as DISCARD_OUTPUT_FORMATTER, tt as resolveRequestedModelId, v as closeSession, x as setSessionConfigOptionOnOwner, z as createInitialSessionRecord } from "./queue-owner-runtime-DSFdsS_y.js";
|
|
4
|
+
import { t as watchSession } from "./watch-iYiP-lOo.js";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import fs from "node:fs/promises";
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
10
|
+
import { isDeepStrictEqual } from "node:util";
|
|
11
|
+
//#region src/runtime/public/errors.ts
|
|
12
|
+
var AcpRuntimeError = class extends Error {
|
|
13
|
+
code;
|
|
14
|
+
cause;
|
|
15
|
+
constructor(code, message, options) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.name = "AcpRuntimeError";
|
|
18
|
+
this.code = code;
|
|
19
|
+
this.cause = options?.cause;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
function isAcpRuntimeError(value) {
|
|
23
|
+
return value instanceof AcpRuntimeError;
|
|
24
|
+
}
|
|
25
|
+
//#endregion
|
|
26
|
+
//#region src/runtime/engine/controls.ts
|
|
27
|
+
function advertisedConfigOptionIds(record) {
|
|
28
|
+
const configOptions = record?.acpx?.config_options;
|
|
29
|
+
if (!configOptions) return;
|
|
30
|
+
return new Set(configOptions.map((option) => option.id).filter((id) => typeof id === "string" && id.trim().length > 0));
|
|
31
|
+
}
|
|
32
|
+
/** Caller-owned controls and the config option keys the session last advertised. */
|
|
33
|
+
function capabilitiesFromRecord(record) {
|
|
34
|
+
const advertisedIds = advertisedConfigOptionIds(record);
|
|
35
|
+
return {
|
|
36
|
+
controls: [
|
|
37
|
+
"session/set_mode",
|
|
38
|
+
"session/set_model",
|
|
39
|
+
"session/set_config_option",
|
|
40
|
+
"session/status"
|
|
41
|
+
],
|
|
42
|
+
...advertisedIds?.size ? { configOptionKeys: [...advertisedIds] } : {}
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
function resolveSupportedConfigOptionId(record, configId) {
|
|
46
|
+
const advertisedIds = advertisedConfigOptionIds(record);
|
|
47
|
+
if (!advertisedIds) return configId;
|
|
48
|
+
if (advertisedIds.has(configId)) return configId;
|
|
49
|
+
if (configId === "thinking" && advertisedIds.has("effort")) return "effort";
|
|
50
|
+
const supported = [...advertisedIds].toSorted();
|
|
51
|
+
const supportedText = supported.length > 0 ? supported.join(", ") : "none";
|
|
52
|
+
throw new AcpRuntimeError("ACP_BACKEND_UNSUPPORTED_CONTROL", `ACP session ${record.acpxRecordId} does not advertise config option '${configId}'. Supported config options: ${supportedText}.`);
|
|
53
|
+
}
|
|
54
|
+
//#endregion
|
|
55
|
+
//#region src/runtime/public/shared.ts
|
|
56
|
+
function isRecord(value) {
|
|
57
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
58
|
+
}
|
|
59
|
+
function asTrimmedString(value) {
|
|
60
|
+
return typeof value === "string" ? value.trim() : "";
|
|
61
|
+
}
|
|
62
|
+
function asString(value) {
|
|
63
|
+
return typeof value === "string" ? value : void 0;
|
|
64
|
+
}
|
|
65
|
+
function asOptionalString(value) {
|
|
66
|
+
return asTrimmedString(value) || void 0;
|
|
67
|
+
}
|
|
68
|
+
function deriveAgentFromSessionKey(sessionKey, fallbackAgent) {
|
|
69
|
+
const match = sessionKey.match(/^agent:([^:]+):/i);
|
|
70
|
+
return (match?.[1] ? asTrimmedString(match[1]) : "") || fallbackAgent;
|
|
71
|
+
}
|
|
72
|
+
//#endregion
|
|
73
|
+
//#region src/runtime/public/events.ts
|
|
74
|
+
const TOOL_OUTPUT_SUMMARY_MAX_CHARS = 500;
|
|
75
|
+
function safeParseJsonObject(line) {
|
|
76
|
+
try {
|
|
77
|
+
const parsed = JSON.parse(line);
|
|
78
|
+
return isRecord(parsed) ? parsed : null;
|
|
79
|
+
} catch {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function asOptionalFiniteNumber(value) {
|
|
84
|
+
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
85
|
+
}
|
|
86
|
+
function readMeta(source) {
|
|
87
|
+
return isRecord(source) ? { meta: source } : {};
|
|
88
|
+
}
|
|
89
|
+
function resolveStructuredPromptPayload(parsed) {
|
|
90
|
+
if (asTrimmedString(parsed.method) === "session/update") {
|
|
91
|
+
const params = parsed.params;
|
|
92
|
+
if (isRecord(params) && isRecord(params.update)) {
|
|
93
|
+
const update = params.update;
|
|
94
|
+
const tag = asOptionalString(update.sessionUpdate);
|
|
95
|
+
return {
|
|
96
|
+
type: tag ?? "",
|
|
97
|
+
payload: update,
|
|
98
|
+
...tag ? { tag } : {},
|
|
99
|
+
...readMeta(params._meta)
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const sessionUpdate = asOptionalString(parsed.sessionUpdate);
|
|
104
|
+
if (sessionUpdate) return {
|
|
105
|
+
type: sessionUpdate,
|
|
106
|
+
payload: parsed,
|
|
107
|
+
tag: sessionUpdate,
|
|
108
|
+
...readMeta(parsed._meta)
|
|
109
|
+
};
|
|
110
|
+
const type = asTrimmedString(parsed.type);
|
|
111
|
+
const tag = asOptionalString(parsed.tag);
|
|
112
|
+
return {
|
|
113
|
+
type,
|
|
114
|
+
payload: parsed,
|
|
115
|
+
...tag ? { tag } : {},
|
|
116
|
+
...readMeta(parsed._meta)
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
function resolveStatusTextForTag(params) {
|
|
120
|
+
const resolver = STATUS_TEXT_RESOLVERS[params.tag];
|
|
121
|
+
return resolver ? resolver(params.payload) : null;
|
|
122
|
+
}
|
|
123
|
+
const STATUS_TEXT_RESOLVERS = {
|
|
124
|
+
available_commands_update: availableCommandsStatusText,
|
|
125
|
+
current_mode_update: currentModeStatusText,
|
|
126
|
+
config_option_update: configOptionStatusText,
|
|
127
|
+
session_info_update: sessionInfoStatusText,
|
|
128
|
+
plan: planStatusText,
|
|
129
|
+
background_task: backgroundTaskStatusText
|
|
130
|
+
};
|
|
131
|
+
function availableCommandsStatusText(payload) {
|
|
132
|
+
const commands = Array.isArray(payload.availableCommands) ? payload.availableCommands : [];
|
|
133
|
+
return commands.length > 0 ? `available commands updated (${commands.length})` : "available commands updated";
|
|
134
|
+
}
|
|
135
|
+
function currentModeStatusText(payload) {
|
|
136
|
+
const mode = asTrimmedString(payload.currentModeId) || asTrimmedString(payload.modeId) || asTrimmedString(payload.mode);
|
|
137
|
+
return mode ? `mode updated: ${mode}` : "mode updated";
|
|
138
|
+
}
|
|
139
|
+
function configOptionStatusText(payload) {
|
|
140
|
+
const id = asTrimmedString(payload.id) || asTrimmedString(payload.configOptionId);
|
|
141
|
+
const value = asTrimmedString(payload.currentValue) || asTrimmedString(payload.value) || asTrimmedString(payload.optionValue);
|
|
142
|
+
if (id && value) return `config updated: ${id}=${value}`;
|
|
143
|
+
return id ? `config updated: ${id}` : "config updated";
|
|
144
|
+
}
|
|
145
|
+
function sessionInfoStatusText(payload) {
|
|
146
|
+
return asTrimmedString(payload.summary) || asTrimmedString(payload.message) || "session updated";
|
|
147
|
+
}
|
|
148
|
+
function planStatusText(payload) {
|
|
149
|
+
const content = asTrimmedString((Array.isArray(payload.entries) ? payload.entries : []).find((entry) => isRecord(entry))?.content);
|
|
150
|
+
return content ? `plan: ${content}` : null;
|
|
151
|
+
}
|
|
152
|
+
function backgroundTaskStatusText(payload) {
|
|
153
|
+
const tasks = Array.isArray(payload.tasks) ? payload.tasks.filter(isRecord) : [];
|
|
154
|
+
const running = tasks.filter((t) => t.status === "running").length;
|
|
155
|
+
const completed = tasks.filter((t) => t.status === "completed").length;
|
|
156
|
+
const failed = tasks.filter((t) => t.status === "failed" || t.status === "cancelled" || t.status === "killed").length;
|
|
157
|
+
const total = tasks.length;
|
|
158
|
+
if (total === 0) return null;
|
|
159
|
+
return `background tasks: ${completed}/${total} (${running} running, ${failed} failed)`;
|
|
160
|
+
}
|
|
161
|
+
function isPlanEntryStatus(value) {
|
|
162
|
+
return value === "pending" || value === "in_progress" || value === "completed";
|
|
163
|
+
}
|
|
164
|
+
function isPlanEntryPriority(value) {
|
|
165
|
+
return value === "high" || value === "medium" || value === "low";
|
|
166
|
+
}
|
|
167
|
+
function planUpdateEvent(payload) {
|
|
168
|
+
const raw = payload.entries;
|
|
169
|
+
const entries = normalizePlanEntries(raw);
|
|
170
|
+
if (Array.isArray(raw) && raw.length === 0) return {
|
|
171
|
+
type: "status",
|
|
172
|
+
text: "plan updated",
|
|
173
|
+
tag: "plan",
|
|
174
|
+
entries: []
|
|
175
|
+
};
|
|
176
|
+
const text = planStatusText(payload) ?? (entries.length > 0 ? `plan: ${entries[0]?.content}` : null);
|
|
177
|
+
if (!text) return null;
|
|
178
|
+
return {
|
|
179
|
+
type: "status",
|
|
180
|
+
text,
|
|
181
|
+
tag: "plan",
|
|
182
|
+
...entries.length > 0 ? { entries } : {}
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
function normalizePlanEntries(value) {
|
|
186
|
+
if (!Array.isArray(value)) return [];
|
|
187
|
+
const entries = [];
|
|
188
|
+
for (const entry of value) {
|
|
189
|
+
const normalized = normalizePlanEntry(entry);
|
|
190
|
+
if (normalized) entries.push(normalized);
|
|
191
|
+
}
|
|
192
|
+
return entries;
|
|
193
|
+
}
|
|
194
|
+
function normalizePlanEntry(value) {
|
|
195
|
+
if (!isRecord(value)) return;
|
|
196
|
+
const content = asTrimmedString(value.content);
|
|
197
|
+
const status = asTrimmedString(value.status);
|
|
198
|
+
if (!content || !isPlanEntryStatus(status)) return;
|
|
199
|
+
const priority = asTrimmedString(value.priority);
|
|
200
|
+
return {
|
|
201
|
+
content,
|
|
202
|
+
status,
|
|
203
|
+
...isPlanEntryPriority(priority) ? { priority } : {}
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Documented allowlist for text_delta.meta origin fields.
|
|
208
|
+
* Only these keys may be copied from ACP update `_meta`.
|
|
209
|
+
* Unknown keys (including secret-like producer-controlled names) are dropped.
|
|
210
|
+
*/
|
|
211
|
+
const ORIGIN_META_KEYS = [
|
|
212
|
+
"origin",
|
|
213
|
+
"kind",
|
|
214
|
+
"source"
|
|
215
|
+
];
|
|
216
|
+
/**
|
|
217
|
+
* Preserve a fail-closed subset of ACP update origin fields for text_delta
|
|
218
|
+
* consumers. Empty or unusable values are omitted rather than inferred.
|
|
219
|
+
*/
|
|
220
|
+
function extractTextDeltaOrigin(payload) {
|
|
221
|
+
const messageId = asOptionalString(payload.messageId);
|
|
222
|
+
const meta = sanitizeOriginMeta(payload._meta);
|
|
223
|
+
return {
|
|
224
|
+
...messageId ? { messageId } : {},
|
|
225
|
+
...meta ? { meta } : {}
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Copy only allowlisted string origin keys from wire `_meta`.
|
|
230
|
+
* Nested objects, arrays, non-strings, and unknown keys are dropped.
|
|
231
|
+
*/
|
|
232
|
+
function sanitizeOriginMeta(value) {
|
|
233
|
+
if (!isRecord(value)) return;
|
|
234
|
+
const out = {};
|
|
235
|
+
for (const key of ORIGIN_META_KEYS) {
|
|
236
|
+
const entry = value[key];
|
|
237
|
+
if (typeof entry !== "string") continue;
|
|
238
|
+
const trimmed = entry.trim();
|
|
239
|
+
if (!trimmed) continue;
|
|
240
|
+
out[key] = trimmed;
|
|
241
|
+
}
|
|
242
|
+
return Object.keys(out).length > 0 ? out : void 0;
|
|
243
|
+
}
|
|
244
|
+
function resolveTextChunk(params) {
|
|
245
|
+
const origin = extractTextDeltaOrigin(params.payload);
|
|
246
|
+
const contentRaw = params.payload.content;
|
|
247
|
+
if (isRecord(contentRaw)) {
|
|
248
|
+
const contentType = asTrimmedString(contentRaw.type);
|
|
249
|
+
if (contentType && contentType !== "text") return null;
|
|
250
|
+
const text = asString(contentRaw.text);
|
|
251
|
+
if (text && text.length > 0) return {
|
|
252
|
+
type: "text_delta",
|
|
253
|
+
text,
|
|
254
|
+
stream: params.stream,
|
|
255
|
+
tag: params.tag,
|
|
256
|
+
...readAgentTurnId(params.meta),
|
|
257
|
+
...origin
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
const text = asString(params.payload.text);
|
|
261
|
+
if (!text || text.length === 0) return null;
|
|
262
|
+
return {
|
|
263
|
+
type: "text_delta",
|
|
264
|
+
text,
|
|
265
|
+
stream: params.stream,
|
|
266
|
+
tag: params.tag,
|
|
267
|
+
...readAgentTurnId(params.meta),
|
|
268
|
+
...origin
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
function readAgentTurnId(meta) {
|
|
272
|
+
const promptId = asOptionalString(meta?.promptId);
|
|
273
|
+
return promptId && promptId.length > 0 ? { agentTurnId: promptId } : {};
|
|
274
|
+
}
|
|
275
|
+
function createTextDeltaEvent(params) {
|
|
276
|
+
if (params.content == null || params.content.length === 0) return null;
|
|
277
|
+
return {
|
|
278
|
+
type: "text_delta",
|
|
279
|
+
text: params.content,
|
|
280
|
+
stream: params.stream,
|
|
281
|
+
...params.tag ? { tag: params.tag } : {},
|
|
282
|
+
...readAgentTurnId(params.meta)
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
function readFirstString(record, keys) {
|
|
286
|
+
for (const key of keys) {
|
|
287
|
+
const value = asOptionalString(record[key]);
|
|
288
|
+
if (value) return value;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
function readFirstStringArray(record, keys) {
|
|
292
|
+
for (const key of keys) {
|
|
293
|
+
const value = record[key];
|
|
294
|
+
if (!Array.isArray(value)) continue;
|
|
295
|
+
const entries = value.map((entry) => asOptionalString(entry)).filter((entry) => entry !== void 0);
|
|
296
|
+
if (entries.length > 0) return entries;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
function summarizeToolInput(rawInput) {
|
|
300
|
+
if (rawInput == null) return;
|
|
301
|
+
if (typeof rawInput === "string" || typeof rawInput === "number" || typeof rawInput === "boolean") return String(rawInput);
|
|
302
|
+
if (!isRecord(rawInput)) return;
|
|
303
|
+
const command = readFirstString(rawInput, [
|
|
304
|
+
"command",
|
|
305
|
+
"cmd",
|
|
306
|
+
"program"
|
|
307
|
+
]);
|
|
308
|
+
const args = readFirstStringArray(rawInput, ["args", "arguments"]);
|
|
309
|
+
if (command) return [command, ...args ?? []].join(" ");
|
|
310
|
+
return readFirstString(rawInput, [
|
|
311
|
+
"path",
|
|
312
|
+
"file",
|
|
313
|
+
"filePath",
|
|
314
|
+
"filepath",
|
|
315
|
+
"target",
|
|
316
|
+
"uri",
|
|
317
|
+
"url",
|
|
318
|
+
"query",
|
|
319
|
+
"pattern",
|
|
320
|
+
"text",
|
|
321
|
+
"search"
|
|
322
|
+
]);
|
|
323
|
+
}
|
|
324
|
+
function truncateToolSummary(value) {
|
|
325
|
+
if (value.length <= TOOL_OUTPUT_SUMMARY_MAX_CHARS) return value;
|
|
326
|
+
return `${value.slice(0, 499)}…`;
|
|
327
|
+
}
|
|
328
|
+
function readToolContentText(value) {
|
|
329
|
+
const record = isRecord(value) ? value : void 0;
|
|
330
|
+
if (!record) return;
|
|
331
|
+
if (record.type === "content") return readToolContentText(record.content);
|
|
332
|
+
return toolContentTextReader(String(record.type))?.(record);
|
|
333
|
+
}
|
|
334
|
+
const TOOL_CONTENT_TEXT_READERS = {
|
|
335
|
+
text: (record) => asString(record.text),
|
|
336
|
+
audio: (record) => `[audio] ${asOptionalString(record.mimeType) || "audio"}`,
|
|
337
|
+
resource_link: (record) => asOptionalString(record.title) || asOptionalString(record.name) || asOptionalString(record.uri),
|
|
338
|
+
resource: (record) => {
|
|
339
|
+
const resource = isRecord(record.resource) ? record.resource : void 0;
|
|
340
|
+
return asString(resource?.text) || asOptionalString(resource?.uri);
|
|
341
|
+
},
|
|
342
|
+
diff: (record) => `diff ${asOptionalString(record.path) || "file"}`,
|
|
343
|
+
terminal: (record) => {
|
|
344
|
+
const terminalId = asOptionalString(record.terminalId) || asOptionalString(record.id);
|
|
345
|
+
return terminalId ? `[terminal] ${terminalId}` : "[terminal]";
|
|
346
|
+
}
|
|
347
|
+
};
|
|
348
|
+
function toolContentTextReader(type) {
|
|
349
|
+
return Object.hasOwn(TOOL_CONTENT_TEXT_READERS, type) ? TOOL_CONTENT_TEXT_READERS[type] : void 0;
|
|
350
|
+
}
|
|
351
|
+
function summarizeToolContent(content) {
|
|
352
|
+
if (!Array.isArray(content)) return;
|
|
353
|
+
const fragments = content.map((entry) => readToolContentText(entry)?.trim()).filter((entry) => Boolean(entry));
|
|
354
|
+
if (fragments.length === 0) return;
|
|
355
|
+
return truncateToolSummary([...new Set(fragments)].join("\n"));
|
|
356
|
+
}
|
|
357
|
+
function summarizeToolOutput(rawOutput) {
|
|
358
|
+
if (rawOutput == null) return;
|
|
359
|
+
if (isScalarToolOutput(rawOutput)) return truncateToolSummary(String(rawOutput));
|
|
360
|
+
const record = isRecord(rawOutput) ? rawOutput : void 0;
|
|
361
|
+
if (!record) return;
|
|
362
|
+
return truncateToolSummary(readFirstString(record, [
|
|
363
|
+
"text",
|
|
364
|
+
"message",
|
|
365
|
+
"error",
|
|
366
|
+
"stdout",
|
|
367
|
+
"stderr",
|
|
368
|
+
"content"
|
|
369
|
+
]) ?? "") || void 0;
|
|
370
|
+
}
|
|
371
|
+
function isScalarToolOutput(value) {
|
|
372
|
+
return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
|
|
373
|
+
}
|
|
374
|
+
function shouldForwardArray(value) {
|
|
375
|
+
return Array.isArray(value);
|
|
376
|
+
}
|
|
377
|
+
function readToolKind(value) {
|
|
378
|
+
const kind = asOptionalString(value);
|
|
379
|
+
return kind && TOOL_KINDS.has(kind) ? kind : void 0;
|
|
380
|
+
}
|
|
381
|
+
const TOOL_KINDS = /* @__PURE__ */ new Set([
|
|
382
|
+
"read",
|
|
383
|
+
"edit",
|
|
384
|
+
"delete",
|
|
385
|
+
"move",
|
|
386
|
+
"search",
|
|
387
|
+
"execute",
|
|
388
|
+
"fetch",
|
|
389
|
+
"think",
|
|
390
|
+
"switch_mode",
|
|
391
|
+
"other"
|
|
392
|
+
]);
|
|
393
|
+
function readClaudeCodeToolName(meta) {
|
|
394
|
+
if (!isRecord(meta)) return;
|
|
395
|
+
const claudeCode = meta.claudeCode;
|
|
396
|
+
if (!isRecord(claudeCode)) return;
|
|
397
|
+
const nameVal = claudeCode.toolName;
|
|
398
|
+
if (typeof nameVal !== "string") return;
|
|
399
|
+
const trimmed = nameVal.trim();
|
|
400
|
+
return trimmed.length > 0 ? trimmed : void 0;
|
|
401
|
+
}
|
|
402
|
+
function readClaudeCodeToolCallId(meta) {
|
|
403
|
+
if (!isRecord(meta)) return;
|
|
404
|
+
const claudeCode = meta.claudeCode;
|
|
405
|
+
if (!isRecord(claudeCode)) return;
|
|
406
|
+
const idVal = claudeCode.toolCallId;
|
|
407
|
+
if (typeof idVal !== "string") return;
|
|
408
|
+
const trimmed = idVal.trim();
|
|
409
|
+
return trimmed.length > 0 ? trimmed : void 0;
|
|
410
|
+
}
|
|
411
|
+
function selectToolCallDetailSummary(params) {
|
|
412
|
+
return params.tag === "tool_call_update" ? params.outputSummary ?? params.inputSummary : params.inputSummary ?? params.outputSummary;
|
|
413
|
+
}
|
|
414
|
+
function createToolCallEvent(params) {
|
|
415
|
+
const title = asTrimmedString(params.payload.title) || "tool call";
|
|
416
|
+
const status = asTrimmedString(params.payload.status);
|
|
417
|
+
const inputSummary = summarizeToolInput(params.payload.rawInput);
|
|
418
|
+
const outputSummary = summarizeToolContent(params.payload.content) ?? summarizeToolOutput(params.payload.rawOutput);
|
|
419
|
+
const toolCallId = asOptionalString(params.payload.toolCallId) ?? readClaudeCodeToolCallId(params.payload._meta);
|
|
420
|
+
const kind = readToolKind(params.payload.kind);
|
|
421
|
+
const summaryText = status ? `${title} (${status})` : title;
|
|
422
|
+
const detailSummary = selectToolCallDetailSummary({
|
|
423
|
+
tag: params.tag,
|
|
424
|
+
inputSummary,
|
|
425
|
+
outputSummary
|
|
426
|
+
});
|
|
427
|
+
const toolName = readClaudeCodeToolName(params.payload._meta);
|
|
428
|
+
const event = {
|
|
429
|
+
type: "tool_call",
|
|
430
|
+
text: detailSummary ? `${summaryText}: ${detailSummary}` : summaryText,
|
|
431
|
+
tag: params.tag,
|
|
432
|
+
title,
|
|
433
|
+
...readAgentTurnId(params.meta)
|
|
434
|
+
};
|
|
435
|
+
assignToolCallEventMetadata(event, params.payload, {
|
|
436
|
+
toolCallId,
|
|
437
|
+
status,
|
|
438
|
+
kind,
|
|
439
|
+
toolName
|
|
440
|
+
});
|
|
441
|
+
return event;
|
|
442
|
+
}
|
|
443
|
+
function assignToolCallEventMetadata(event, payload, values) {
|
|
444
|
+
if (event.type !== "tool_call") return;
|
|
445
|
+
if (typeof values.toolCallId === "string") event.toolCallId = values.toolCallId;
|
|
446
|
+
if (values.status) event.status = values.status;
|
|
447
|
+
if (values.kind) event.kind = values.kind;
|
|
448
|
+
if (values.toolName) event.toolName = values.toolName;
|
|
449
|
+
assignForwardedToolPayload(event, payload);
|
|
450
|
+
}
|
|
451
|
+
function assignForwardedToolPayload(event, payload) {
|
|
452
|
+
if (shouldForwardArray(payload.locations)) event.locations = payload.locations;
|
|
453
|
+
if (Object.prototype.hasOwnProperty.call(payload, "rawInput")) event.rawInput = payload.rawInput;
|
|
454
|
+
if (Object.prototype.hasOwnProperty.call(payload, "rawOutput")) event.rawOutput = payload.rawOutput;
|
|
455
|
+
if (shouldForwardArray(payload.content)) event.content = payload.content;
|
|
456
|
+
}
|
|
457
|
+
function parsePromptEventLine(line) {
|
|
458
|
+
const trimmed = line.trim();
|
|
459
|
+
if (!trimmed) return null;
|
|
460
|
+
const parsed = safeParseJsonObject(trimmed);
|
|
461
|
+
if (!parsed) return {
|
|
462
|
+
type: "status",
|
|
463
|
+
text: trimmed
|
|
464
|
+
};
|
|
465
|
+
const structured = resolveStructuredPromptPayload(parsed);
|
|
466
|
+
const type = structured.type;
|
|
467
|
+
const payload = structured.payload;
|
|
468
|
+
const tag = structured.tag;
|
|
469
|
+
const meta = structured.meta;
|
|
470
|
+
const parser = promptEventParser(type);
|
|
471
|
+
return parser ? parser(payload, tag, meta) : null;
|
|
472
|
+
}
|
|
473
|
+
const PROMPT_EVENT_PARSERS = {
|
|
474
|
+
text: (payload, tag, meta) => createTextDeltaEvent({
|
|
475
|
+
content: asString(payload.content),
|
|
476
|
+
stream: "output",
|
|
477
|
+
tag,
|
|
478
|
+
meta
|
|
479
|
+
}),
|
|
480
|
+
thought: (payload, tag, meta) => createTextDeltaEvent({
|
|
481
|
+
content: asString(payload.content),
|
|
482
|
+
stream: "thought",
|
|
483
|
+
tag,
|
|
484
|
+
meta
|
|
485
|
+
}),
|
|
486
|
+
tool_call: (payload, tag, meta) => createToolCallEvent({
|
|
487
|
+
payload,
|
|
488
|
+
tag: tag ?? "tool_call",
|
|
489
|
+
meta
|
|
490
|
+
}),
|
|
491
|
+
tool_call_update: (payload, tag, meta) => createToolCallEvent({
|
|
492
|
+
payload,
|
|
493
|
+
tag: tag ?? "tool_call_update",
|
|
494
|
+
meta
|
|
495
|
+
}),
|
|
496
|
+
agent_message_chunk: (payload, _tag, meta) => resolveTextChunk({
|
|
497
|
+
payload,
|
|
498
|
+
stream: "output",
|
|
499
|
+
tag: "agent_message_chunk",
|
|
500
|
+
meta
|
|
501
|
+
}),
|
|
502
|
+
agent_thought_chunk: (payload, _tag, meta) => resolveTextChunk({
|
|
503
|
+
payload,
|
|
504
|
+
stream: "thought",
|
|
505
|
+
tag: "agent_thought_chunk",
|
|
506
|
+
meta
|
|
507
|
+
}),
|
|
508
|
+
usage_update: usageUpdateEvent,
|
|
509
|
+
available_commands_update: availableCommandsUpdateEvent,
|
|
510
|
+
current_mode_update: currentModeUpdateEvent,
|
|
511
|
+
config_option_update: (payload) => statusUpdateEvent("config_option_update", payload),
|
|
512
|
+
session_info_update: (payload) => statusUpdateEvent("session_info_update", payload),
|
|
513
|
+
plan: planUpdateEvent,
|
|
514
|
+
background_task: backgroundTaskUpdateEvent,
|
|
515
|
+
client_operation: clientOperationEvent,
|
|
516
|
+
update: updateStatusEvent,
|
|
517
|
+
done: () => null,
|
|
518
|
+
error: () => null
|
|
519
|
+
};
|
|
520
|
+
function promptEventParser(type) {
|
|
521
|
+
return Object.hasOwn(PROMPT_EVENT_PARSERS, type) ? PROMPT_EVENT_PARSERS[type] : void 0;
|
|
522
|
+
}
|
|
523
|
+
function usageUpdateEvent(payload) {
|
|
524
|
+
const used = asOptionalFiniteNumber(payload.used);
|
|
525
|
+
const size = asOptionalFiniteNumber(payload.size);
|
|
526
|
+
const meta = isRecord(payload._meta) ? payload._meta : void 0;
|
|
527
|
+
return buildUsageUpdateEvent({
|
|
528
|
+
used,
|
|
529
|
+
size,
|
|
530
|
+
cost: normalizeUsageCost(payload.cost),
|
|
531
|
+
breakdown: normalizeUsageBreakdown(meta?.usage)
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
function buildUsageUpdateEvent(parts) {
|
|
535
|
+
const { used, size, cost, breakdown } = parts;
|
|
536
|
+
return {
|
|
537
|
+
type: "status",
|
|
538
|
+
text: used != null && size != null ? `usage updated: ${used}/${size}` : "usage updated",
|
|
539
|
+
tag: "usage_update",
|
|
540
|
+
...used != null ? { used } : {},
|
|
541
|
+
...size != null ? { size } : {},
|
|
542
|
+
...cost ? { cost } : {},
|
|
543
|
+
...breakdown ? { breakdown } : {}
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
function currentModeUpdateEvent(payload) {
|
|
547
|
+
const currentModeId = asTrimmedString(payload.currentModeId) || asTrimmedString(payload.modeId) || asTrimmedString(payload.mode);
|
|
548
|
+
if (!currentModeId) return statusUpdateEvent("current_mode_update", payload);
|
|
549
|
+
return {
|
|
550
|
+
type: "status",
|
|
551
|
+
text: `mode updated: ${currentModeId}`,
|
|
552
|
+
tag: "current_mode_update",
|
|
553
|
+
currentModeId
|
|
554
|
+
};
|
|
555
|
+
}
|
|
556
|
+
function backgroundTaskUpdateEvent(payload) {
|
|
557
|
+
const tasks = normalizeBackgroundTasks(payload.tasks);
|
|
558
|
+
if (!tasks) return statusUpdateEvent("background_task", payload);
|
|
559
|
+
return {
|
|
560
|
+
type: "background_task",
|
|
561
|
+
tasks
|
|
562
|
+
};
|
|
563
|
+
}
|
|
564
|
+
const BACKGROUND_TASK_STATUSES = /* @__PURE__ */ new Set([
|
|
565
|
+
"running",
|
|
566
|
+
"completed",
|
|
567
|
+
"failed",
|
|
568
|
+
"cancelled",
|
|
569
|
+
"killed"
|
|
570
|
+
]);
|
|
571
|
+
function normalizeBackgroundTaskStatus(value) {
|
|
572
|
+
const raw = asTrimmedString(value);
|
|
573
|
+
return BACKGROUND_TASK_STATUSES.has(raw) ? raw : "running";
|
|
574
|
+
}
|
|
575
|
+
function normalizeBackgroundTask(entry) {
|
|
576
|
+
if (!isRecord(entry)) return;
|
|
577
|
+
const id = asOptionalString(entry.id);
|
|
578
|
+
const command = asOptionalString(entry.command);
|
|
579
|
+
if (!id || !command) return;
|
|
580
|
+
const duration = asOptionalString(entry.duration);
|
|
581
|
+
const output = asOptionalString(entry.output);
|
|
582
|
+
const exitCode = typeof entry.exitCode === "number" ? entry.exitCode : void 0;
|
|
583
|
+
return {
|
|
584
|
+
id,
|
|
585
|
+
status: normalizeBackgroundTaskStatus(entry.status),
|
|
586
|
+
command,
|
|
587
|
+
...duration ? { duration } : {},
|
|
588
|
+
...exitCode !== void 0 ? { exitCode } : {},
|
|
589
|
+
...output ? { output } : {}
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
function normalizeBackgroundTasks(value) {
|
|
593
|
+
if (!Array.isArray(value)) return;
|
|
594
|
+
const tasks = [];
|
|
595
|
+
for (const entry of value) {
|
|
596
|
+
const normalized = normalizeBackgroundTask(entry);
|
|
597
|
+
if (normalized) tasks.push(normalized);
|
|
598
|
+
}
|
|
599
|
+
return tasks.length > 0 ? tasks : void 0;
|
|
600
|
+
}
|
|
601
|
+
function availableCommandsUpdateEvent(payload) {
|
|
602
|
+
const raw = Array.isArray(payload.availableCommands) ? payload.availableCommands : [];
|
|
603
|
+
const availableCommands = [];
|
|
604
|
+
for (const entry of raw) {
|
|
605
|
+
if (!isRecord(entry)) continue;
|
|
606
|
+
const name = asTrimmedString(entry.name);
|
|
607
|
+
if (!name) continue;
|
|
608
|
+
const description = asTrimmedString(entry.description);
|
|
609
|
+
availableCommands.push({
|
|
610
|
+
name,
|
|
611
|
+
...description ? { description } : {},
|
|
612
|
+
hasInput: entry.input != null
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
return {
|
|
616
|
+
type: "status",
|
|
617
|
+
text: availableCommands.length > 0 ? `available commands updated (${availableCommands.length})` : "available commands updated",
|
|
618
|
+
tag: "available_commands_update",
|
|
619
|
+
availableCommands
|
|
620
|
+
};
|
|
621
|
+
}
|
|
622
|
+
function normalizeUsageCost(value) {
|
|
623
|
+
if (!isRecord(value)) return;
|
|
624
|
+
const amount = asOptionalFiniteNumber(value.amount);
|
|
625
|
+
const currency = asTrimmedString(value.currency);
|
|
626
|
+
if (amount == null && !currency) return;
|
|
627
|
+
return {
|
|
628
|
+
...amount != null ? { amount } : {},
|
|
629
|
+
...currency ? { currency } : {}
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
const USAGE_BREAKDOWN_FIELDS = [
|
|
633
|
+
["inputTokens", ["inputTokens", "input_tokens"]],
|
|
634
|
+
["outputTokens", ["outputTokens", "output_tokens"]],
|
|
635
|
+
["cachedReadTokens", [
|
|
636
|
+
"cachedReadTokens",
|
|
637
|
+
"cacheReadInputTokens",
|
|
638
|
+
"cache_read_input_tokens"
|
|
639
|
+
]],
|
|
640
|
+
["cachedWriteTokens", [
|
|
641
|
+
"cachedWriteTokens",
|
|
642
|
+
"cacheCreationInputTokens",
|
|
643
|
+
"cache_creation_input_tokens"
|
|
644
|
+
]],
|
|
645
|
+
["thoughtTokens", ["thoughtTokens", "thought_tokens"]],
|
|
646
|
+
["totalTokens", ["totalTokens", "total_tokens"]]
|
|
647
|
+
];
|
|
648
|
+
function normalizeUsageBreakdown(value) {
|
|
649
|
+
if (!isRecord(value)) return;
|
|
650
|
+
const breakdown = {};
|
|
651
|
+
for (const [key, aliases] of USAGE_BREAKDOWN_FIELDS) {
|
|
652
|
+
const v = firstFiniteNumber(value, aliases);
|
|
653
|
+
if (v != null) breakdown[key] = v;
|
|
654
|
+
}
|
|
655
|
+
return Object.keys(breakdown).length > 0 ? breakdown : void 0;
|
|
656
|
+
}
|
|
657
|
+
function firstFiniteNumber(record, keys) {
|
|
658
|
+
for (const key of keys) {
|
|
659
|
+
const value = asOptionalFiniteNumber(record[key]);
|
|
660
|
+
if (value != null) return value;
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
function statusUpdateEvent(tag, payload) {
|
|
664
|
+
const text = resolveStatusTextForTag({
|
|
665
|
+
tag,
|
|
666
|
+
payload
|
|
667
|
+
});
|
|
668
|
+
if (!text) return null;
|
|
669
|
+
return {
|
|
670
|
+
type: "status",
|
|
671
|
+
text,
|
|
672
|
+
tag
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
function clientOperationEvent(payload, tag) {
|
|
676
|
+
const text = [
|
|
677
|
+
asTrimmedString(payload.method) || "operation",
|
|
678
|
+
asTrimmedString(payload.status),
|
|
679
|
+
asTrimmedString(payload.summary)
|
|
680
|
+
].filter(Boolean).join(" ");
|
|
681
|
+
return text ? {
|
|
682
|
+
type: "status",
|
|
683
|
+
text,
|
|
684
|
+
...tag ? { tag } : {}
|
|
685
|
+
} : null;
|
|
686
|
+
}
|
|
687
|
+
function updateStatusEvent(payload, tag) {
|
|
688
|
+
const update = asTrimmedString(payload.update);
|
|
689
|
+
return update ? {
|
|
690
|
+
type: "status",
|
|
691
|
+
text: update,
|
|
692
|
+
...tag ? { tag } : {}
|
|
693
|
+
} : null;
|
|
694
|
+
}
|
|
695
|
+
//#endregion
|
|
696
|
+
//#region src/runtime/public/probe.ts
|
|
697
|
+
/**
|
|
698
|
+
* Inspect session model metadata without a runtime store or prompt. The agent
|
|
699
|
+
* may create native session history; only its owned transport is closed.
|
|
700
|
+
*/
|
|
701
|
+
async function inspectAgentModels(options) {
|
|
702
|
+
options.signal?.throwIfAborted();
|
|
703
|
+
const timeoutMs = options.timeoutMs ?? 12e4;
|
|
704
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) throw new RangeError("Model inspection timeoutMs must be positive and at most 2147483647");
|
|
705
|
+
const deadline = new AbortController();
|
|
706
|
+
const signal = options.signal ? AbortSignal.any([options.signal, deadline.signal]) : deadline.signal;
|
|
707
|
+
const assertActive = () => signal.throwIfAborted();
|
|
708
|
+
const client = new AcpClient({
|
|
709
|
+
...normalizeAgentCommandInput(options.agentCommand),
|
|
710
|
+
cwd: options.cwd,
|
|
711
|
+
agentProcessEnv: options.agentProcessEnv,
|
|
712
|
+
permissionMode: "deny-all",
|
|
713
|
+
nonInteractivePermissions: "deny",
|
|
714
|
+
fs: false,
|
|
715
|
+
terminal: false,
|
|
716
|
+
processLifecycle: {
|
|
717
|
+
onBeforeSpawn: assertActive,
|
|
718
|
+
onSpawned: assertActive
|
|
719
|
+
}
|
|
720
|
+
});
|
|
721
|
+
const timer = setTimeout(() => deadline.abort(new TimeoutError(timeoutMs)), timeoutMs);
|
|
722
|
+
let onAbort;
|
|
723
|
+
const aborted = new Promise((_resolve, reject) => {
|
|
724
|
+
onAbort = () => reject(signal.reason);
|
|
725
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
726
|
+
});
|
|
727
|
+
const inspection = (async () => {
|
|
728
|
+
assertActive();
|
|
729
|
+
await client.start();
|
|
730
|
+
assertActive();
|
|
731
|
+
const { models } = await client.createSession();
|
|
732
|
+
assertActive();
|
|
733
|
+
return models ? {
|
|
734
|
+
currentModelId: models.currentModelId,
|
|
735
|
+
availableModelIds: models.availableModels.map((model) => model.modelId),
|
|
736
|
+
availableModels: models.availableModels
|
|
737
|
+
} : void 0;
|
|
738
|
+
})();
|
|
739
|
+
try {
|
|
740
|
+
return await Promise.race([inspection, aborted]);
|
|
741
|
+
} finally {
|
|
742
|
+
clearTimeout(timer);
|
|
743
|
+
signal.removeEventListener("abort", onAbort);
|
|
744
|
+
try {
|
|
745
|
+
if (signal.aborted) await client.close();
|
|
746
|
+
} finally {
|
|
747
|
+
await inspection.catch(() => {});
|
|
748
|
+
await client.close();
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
function isPrimitiveDetail(value) {
|
|
753
|
+
return value == null || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || typeof value === "symbol";
|
|
754
|
+
}
|
|
755
|
+
function formatFunctionDetail(value) {
|
|
756
|
+
return value.name ? `[Function ${value.name}]` : "[Function]";
|
|
757
|
+
}
|
|
758
|
+
function serializeRuntimeDetail(value) {
|
|
759
|
+
const seen = /* @__PURE__ */ new WeakSet();
|
|
760
|
+
return JSON.stringify(value, (_key, nested) => {
|
|
761
|
+
if (nested instanceof Error) return nested.message || nested.name;
|
|
762
|
+
if (nested && typeof nested === "object") {
|
|
763
|
+
if (seen.has(nested)) return "[Circular]";
|
|
764
|
+
seen.add(nested);
|
|
765
|
+
}
|
|
766
|
+
return nested;
|
|
767
|
+
}) ?? "undefined";
|
|
768
|
+
}
|
|
769
|
+
function formatRuntimeDetail(value) {
|
|
770
|
+
if (value instanceof Error) return value.message || value.name;
|
|
771
|
+
if (typeof value === "string") return value;
|
|
772
|
+
if (isPrimitiveDetail(value)) return String(value);
|
|
773
|
+
if (typeof value === "function") return formatFunctionDetail(value);
|
|
774
|
+
try {
|
|
775
|
+
return serializeRuntimeDetail(value);
|
|
776
|
+
} catch {
|
|
777
|
+
return "unserializable object";
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
function normalizeRuntimeDetails(details) {
|
|
781
|
+
return details?.map((detail) => formatRuntimeDetail(detail));
|
|
782
|
+
}
|
|
783
|
+
async function probeRuntime(options, deps = {}) {
|
|
784
|
+
const agentName = options.probeAgent?.trim() || "codex";
|
|
785
|
+
const agentCommand = normalizeAgentCommandInput(options.agentRegistry.resolve(agentName));
|
|
786
|
+
const client = createProbeClient(options, agentName, agentCommand, deps);
|
|
787
|
+
try {
|
|
788
|
+
await client.start();
|
|
789
|
+
return {
|
|
790
|
+
ok: true,
|
|
791
|
+
message: "embedded ACP runtime ready",
|
|
792
|
+
details: [
|
|
793
|
+
`agent=${agentName}`,
|
|
794
|
+
`command=${agentCommand.agentCommand}`,
|
|
795
|
+
`cwd=${options.cwd}`,
|
|
796
|
+
...client.initializeResult?.protocolVersion ? [`protocolVersion=${client.initializeResult.protocolVersion}`] : []
|
|
797
|
+
]
|
|
798
|
+
};
|
|
799
|
+
} catch (error) {
|
|
800
|
+
return {
|
|
801
|
+
ok: false,
|
|
802
|
+
message: "embedded ACP runtime probe failed",
|
|
803
|
+
details: [
|
|
804
|
+
`agent=${agentName}`,
|
|
805
|
+
`command=${agentCommand.agentCommand}`,
|
|
806
|
+
`cwd=${options.cwd}`,
|
|
807
|
+
formatRuntimeDetail(error)
|
|
808
|
+
]
|
|
809
|
+
};
|
|
810
|
+
} finally {
|
|
811
|
+
await client.close().catch(() => {});
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
function createProbeClient(options, agentName, agentCommand, deps) {
|
|
815
|
+
const clientOptions = {
|
|
816
|
+
...agentCommand,
|
|
817
|
+
cwd: options.cwd,
|
|
818
|
+
agentProcessEnv: options.agentProcessEnv,
|
|
819
|
+
mcpServers: typeof options.mcpServers === "function" ? [] : [...options.mcpServers ?? []],
|
|
820
|
+
permissionMode: options.permissionMode,
|
|
821
|
+
nonInteractivePermissions: options.nonInteractivePermissions,
|
|
822
|
+
permissionPolicy: options.permissionPolicy,
|
|
823
|
+
fs: false,
|
|
824
|
+
terminal: false,
|
|
825
|
+
processLifecycle: options.processLifecycle,
|
|
826
|
+
processLaunchScope: {
|
|
827
|
+
kind: "runtime-probe",
|
|
828
|
+
agent: agentName
|
|
829
|
+
},
|
|
830
|
+
verbose: options.verbose
|
|
831
|
+
};
|
|
832
|
+
return deps.clientFactory?.(clientOptions) ?? new AcpClient(clientOptions);
|
|
833
|
+
}
|
|
834
|
+
//#endregion
|
|
835
|
+
//#region src/runtime/engine/reuse-policy.ts
|
|
836
|
+
function shouldReuseExistingRecord(record, params) {
|
|
837
|
+
if (record.acpx?.reset_on_next_ensure === true) return false;
|
|
838
|
+
if (path.resolve(record.cwd) !== path.resolve(params.cwd)) return false;
|
|
839
|
+
if (record.agentCommand !== params.agentCommand) return false;
|
|
840
|
+
if (!sameArgv(record.agentArgv, params.agentArgv)) return false;
|
|
841
|
+
if (params.resumeSessionId && record.acpSessionId !== params.resumeSessionId) return false;
|
|
842
|
+
return true;
|
|
843
|
+
}
|
|
844
|
+
function sameArgv(left, right) {
|
|
845
|
+
const leftValues = left ?? [];
|
|
846
|
+
const rightValues = right ?? [];
|
|
847
|
+
return leftValues.length === rightValues.length && leftValues.every((value, index) => value === rightValues[index]);
|
|
848
|
+
}
|
|
849
|
+
//#endregion
|
|
850
|
+
//#region src/acp/config-option-support.ts
|
|
851
|
+
function asRecord$1(value) {
|
|
852
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return;
|
|
853
|
+
return value;
|
|
854
|
+
}
|
|
855
|
+
function isModeOption(option) {
|
|
856
|
+
return option.category === "mode" || option.id === "mode";
|
|
857
|
+
}
|
|
858
|
+
function parseChoice(value) {
|
|
859
|
+
const option = asRecord$1(value);
|
|
860
|
+
if (!option || typeof option.value !== "string" || typeof option.name !== "string") return;
|
|
861
|
+
const description = typeof option.description === "string" ? option.description : void 0;
|
|
862
|
+
return {
|
|
863
|
+
value: option.value,
|
|
864
|
+
name: option.name,
|
|
865
|
+
...description ? { description } : {}
|
|
866
|
+
};
|
|
867
|
+
}
|
|
868
|
+
function parseChoices(value) {
|
|
869
|
+
if (!Array.isArray(value)) return [];
|
|
870
|
+
const choices = [];
|
|
871
|
+
for (const entry of value) {
|
|
872
|
+
const direct = parseChoice(entry);
|
|
873
|
+
if (direct) {
|
|
874
|
+
choices.push(direct);
|
|
875
|
+
continue;
|
|
876
|
+
}
|
|
877
|
+
const group = asRecord$1(entry);
|
|
878
|
+
if (group && Array.isArray(group.options)) for (const nested of group.options) {
|
|
879
|
+
const choice = parseChoice(nested);
|
|
880
|
+
if (choice) choices.push(choice);
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
return choices;
|
|
884
|
+
}
|
|
885
|
+
function optionalString$1(value) {
|
|
886
|
+
return typeof value === "string" && value !== "" ? value : void 0;
|
|
887
|
+
}
|
|
888
|
+
function isNonModeSelect(option) {
|
|
889
|
+
return option.type === "select" && typeof option.id === "string" && !isModeOption(option);
|
|
890
|
+
}
|
|
891
|
+
function parseConfigOption(value) {
|
|
892
|
+
const option = asRecord$1(value);
|
|
893
|
+
if (!option || !isNonModeSelect(option)) return;
|
|
894
|
+
const choices = parseChoices(option.options);
|
|
895
|
+
if (choices.length === 0) return;
|
|
896
|
+
const id = option.id;
|
|
897
|
+
return {
|
|
898
|
+
id,
|
|
899
|
+
name: optionalString$1(option.name) ?? id,
|
|
900
|
+
...optionalString$1(option.category) ? { category: option.category } : {},
|
|
901
|
+
...optionalString$1(option.currentValue) ? { currentValue: option.currentValue } : {},
|
|
902
|
+
options: choices
|
|
903
|
+
};
|
|
904
|
+
}
|
|
905
|
+
/**
|
|
906
|
+
* Parse the non-mode select config options out of a session's config options.
|
|
907
|
+
* Returns undefined when the agent advertised none, so callers can distinguish
|
|
908
|
+
* "no options" from "empty options".
|
|
909
|
+
*/
|
|
910
|
+
function configOptionsFromConfigOptions(configOptions) {
|
|
911
|
+
if (!Array.isArray(configOptions)) return;
|
|
912
|
+
const options = [];
|
|
913
|
+
for (const entry of configOptions) {
|
|
914
|
+
const parsed = parseConfigOption(entry);
|
|
915
|
+
if (parsed) options.push(parsed);
|
|
916
|
+
}
|
|
917
|
+
return options.length > 0 ? options : void 0;
|
|
918
|
+
}
|
|
919
|
+
//#endregion
|
|
920
|
+
//#region src/acp/mode-support.ts
|
|
921
|
+
function asRecord(value) {
|
|
922
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return;
|
|
923
|
+
return value;
|
|
924
|
+
}
|
|
925
|
+
function isModeSelectOption(option) {
|
|
926
|
+
return option.type === "select" && (option.category === "mode" || option.id === "mode");
|
|
927
|
+
}
|
|
928
|
+
function parseAvailableMode(value) {
|
|
929
|
+
const option = asRecord(value);
|
|
930
|
+
if (!option || typeof option.value !== "string" || typeof option.name !== "string") return;
|
|
931
|
+
const description = typeof option.description === "string" ? option.description : void 0;
|
|
932
|
+
return {
|
|
933
|
+
id: option.value,
|
|
934
|
+
name: option.name,
|
|
935
|
+
...description ? { description } : {}
|
|
936
|
+
};
|
|
937
|
+
}
|
|
938
|
+
function parseModeOption(option) {
|
|
939
|
+
const rawModes = Array.isArray(option.options) ? option.options : [];
|
|
940
|
+
const availableModes = [];
|
|
941
|
+
for (const rawMode of rawModes) {
|
|
942
|
+
const mode = parseAvailableMode(rawMode);
|
|
943
|
+
if (mode) availableModes.push(mode);
|
|
944
|
+
}
|
|
945
|
+
const currentModeId = typeof option.currentValue === "string" && option.currentValue !== "" ? option.currentValue : void 0;
|
|
946
|
+
return {
|
|
947
|
+
...currentModeId ? { currentModeId } : {},
|
|
948
|
+
availableModes
|
|
949
|
+
};
|
|
950
|
+
}
|
|
951
|
+
/**
|
|
952
|
+
* Parse the mode select option out of a session's config options. Returns
|
|
953
|
+
* undefined when the agent never advertised one (mode-less agents), so
|
|
954
|
+
* callers can distinguish "no modes" from "empty modes".
|
|
955
|
+
*/
|
|
956
|
+
function modeStateFromConfigOptions(configOptions) {
|
|
957
|
+
if (!Array.isArray(configOptions)) return;
|
|
958
|
+
for (const entry of configOptions) {
|
|
959
|
+
const option = asRecord(entry);
|
|
960
|
+
if (option && isModeSelectOption(option)) return parseModeOption(option);
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
//#endregion
|
|
964
|
+
//#region src/runtime/engine/status.ts
|
|
965
|
+
function runtimeStatusFromRecord(record) {
|
|
966
|
+
return {
|
|
967
|
+
forkSupported: Boolean(record.agentCapabilities?.sessionCapabilities?.fork),
|
|
968
|
+
...record.lastRequestId ? { lastRequestId: record.lastRequestId } : {},
|
|
969
|
+
summary: statusSummary(record),
|
|
970
|
+
acpxRecordId: record.acpxRecordId,
|
|
971
|
+
backendSessionId: record.acpSessionId,
|
|
972
|
+
agentSessionId: record.agentSessionId,
|
|
973
|
+
...buildModelsField(record),
|
|
974
|
+
...buildModesField(record),
|
|
975
|
+
...buildConfigOptionsField(record),
|
|
976
|
+
...buildUsageField(record),
|
|
977
|
+
...buildAvailableCommandsField(record),
|
|
978
|
+
details: {
|
|
979
|
+
cwd: record.cwd,
|
|
980
|
+
lastUsedAt: record.lastUsedAt,
|
|
981
|
+
closed: record.closed === true,
|
|
982
|
+
...record.acpx?.config_options !== void 0 ? { configOptions: structuredClone(record.acpx.config_options) } : {}
|
|
983
|
+
}
|
|
984
|
+
};
|
|
985
|
+
}
|
|
986
|
+
function buildModesField(record) {
|
|
987
|
+
const modes = modeStateFromConfigOptions(record.acpx?.config_options);
|
|
988
|
+
if (!modes) return {};
|
|
989
|
+
const liveModeId = record.acpx?.current_mode_id;
|
|
990
|
+
return { modes: {
|
|
991
|
+
...modes,
|
|
992
|
+
...liveModeId ? { currentModeId: liveModeId } : {}
|
|
993
|
+
} };
|
|
994
|
+
}
|
|
995
|
+
function buildConfigOptionsField(record) {
|
|
996
|
+
const configOptions = configOptionsFromConfigOptions(record.acpx?.config_options);
|
|
997
|
+
return configOptions ? { configOptions } : {};
|
|
998
|
+
}
|
|
999
|
+
function statusSummary(record) {
|
|
1000
|
+
return [
|
|
1001
|
+
`session=${record.acpxRecordId}`,
|
|
1002
|
+
`backendSessionId=${record.acpSessionId}`,
|
|
1003
|
+
record.agentSessionId ? `agentSessionId=${record.agentSessionId}` : null,
|
|
1004
|
+
record.pid != null ? `pid=${record.pid}` : null,
|
|
1005
|
+
record.closed ? "closed" : "open"
|
|
1006
|
+
].filter(Boolean).join(" ");
|
|
1007
|
+
}
|
|
1008
|
+
function buildModelsField(record) {
|
|
1009
|
+
const { available_models: available = [], current_model_id: currentModelId } = record.acpx ?? {};
|
|
1010
|
+
if (available.length === 0 && currentModelId === void 0) return {};
|
|
1011
|
+
return { models: {
|
|
1012
|
+
...currentModelId !== void 0 ? { currentModelId } : {},
|
|
1013
|
+
availableModelIds: [...available],
|
|
1014
|
+
...buildModelNamesField(record.acpx)
|
|
1015
|
+
} };
|
|
1016
|
+
}
|
|
1017
|
+
function buildModelNamesField(state) {
|
|
1018
|
+
const models = advertisedModelState(state);
|
|
1019
|
+
return models && (models.configId || state?.available_model_names !== void 0) ? { availableModels: models.availableModels } : {};
|
|
1020
|
+
}
|
|
1021
|
+
function tokenUsageToBreakdown(usage) {
|
|
1022
|
+
if (!usage) return;
|
|
1023
|
+
const breakdown = {};
|
|
1024
|
+
assignUsageBreakdownField(breakdown, "inputTokens", usage.input_tokens);
|
|
1025
|
+
assignUsageBreakdownField(breakdown, "outputTokens", usage.output_tokens);
|
|
1026
|
+
assignUsageBreakdownField(breakdown, "cachedReadTokens", usage.cache_read_input_tokens);
|
|
1027
|
+
assignUsageBreakdownField(breakdown, "cachedWriteTokens", usage.cache_creation_input_tokens);
|
|
1028
|
+
assignUsageBreakdownField(breakdown, "thoughtTokens", usage.thought_tokens);
|
|
1029
|
+
assignUsageBreakdownField(breakdown, "totalTokens", usage.total_tokens);
|
|
1030
|
+
return Object.keys(breakdown).length > 0 ? breakdown : void 0;
|
|
1031
|
+
}
|
|
1032
|
+
function assignUsageBreakdownField(breakdown, key, value) {
|
|
1033
|
+
if (value !== void 0) breakdown[key] = value;
|
|
1034
|
+
}
|
|
1035
|
+
function buildUsageField(record) {
|
|
1036
|
+
const cumulative = tokenUsageToBreakdown(record.cumulative_token_usage);
|
|
1037
|
+
const perRequestEntries = Object.entries(record.request_token_usage ?? {}).map(([id, value]) => [id, tokenUsageToBreakdown(value)]).filter((entry) => entry[1] !== void 0);
|
|
1038
|
+
const perRequest = perRequestEntries.length > 0 ? Object.fromEntries(perRequestEntries) : void 0;
|
|
1039
|
+
const cost = record.cumulative_cost;
|
|
1040
|
+
const usage = {
|
|
1041
|
+
...cumulative ? { cumulative } : {},
|
|
1042
|
+
...cost ? { cost } : {},
|
|
1043
|
+
...perRequest ? { perRequest } : {}
|
|
1044
|
+
};
|
|
1045
|
+
return Object.keys(usage).length > 0 ? { usage } : {};
|
|
1046
|
+
}
|
|
1047
|
+
function buildAvailableCommandsField(record) {
|
|
1048
|
+
const commands = record.acpx?.available_commands;
|
|
1049
|
+
if (!commands || commands.length === 0) return {};
|
|
1050
|
+
const availableCommands = commands.map((command) => runtimeAvailableCommand(command)).filter((command) => command !== void 0);
|
|
1051
|
+
return availableCommands.length > 0 ? { availableCommands } : {};
|
|
1052
|
+
}
|
|
1053
|
+
function runtimeAvailableCommand(command) {
|
|
1054
|
+
if (typeof command === "string") {
|
|
1055
|
+
const name = command.trim();
|
|
1056
|
+
return name ? { name } : void 0;
|
|
1057
|
+
}
|
|
1058
|
+
const record = commandRecord(command);
|
|
1059
|
+
if (!record) return;
|
|
1060
|
+
const name = asOptionalString(record.name);
|
|
1061
|
+
if (!name) return;
|
|
1062
|
+
const runtimeCommand = { name };
|
|
1063
|
+
const description = asOptionalString(record.description);
|
|
1064
|
+
if (description) runtimeCommand.description = description;
|
|
1065
|
+
if (typeof record.has_input === "boolean") runtimeCommand.hasInput = record.has_input;
|
|
1066
|
+
return runtimeCommand;
|
|
1067
|
+
}
|
|
1068
|
+
function commandRecord(value) {
|
|
1069
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return;
|
|
1070
|
+
return value;
|
|
1071
|
+
}
|
|
1072
|
+
//#endregion
|
|
1073
|
+
//#region src/runtime/engine/turn.ts
|
|
1074
|
+
function createDeferred() {
|
|
1075
|
+
let resolve;
|
|
1076
|
+
let reject;
|
|
1077
|
+
return {
|
|
1078
|
+
promise: new Promise((res, rej) => {
|
|
1079
|
+
resolve = res;
|
|
1080
|
+
reject = rej;
|
|
1081
|
+
}),
|
|
1082
|
+
resolve,
|
|
1083
|
+
reject
|
|
1084
|
+
};
|
|
1085
|
+
}
|
|
1086
|
+
var AsyncEventQueue = class {
|
|
1087
|
+
items = [];
|
|
1088
|
+
waits = [];
|
|
1089
|
+
closed = false;
|
|
1090
|
+
push(item) {
|
|
1091
|
+
if (this.closed) return;
|
|
1092
|
+
const waiter = this.waits.shift();
|
|
1093
|
+
if (waiter) {
|
|
1094
|
+
waiter.resolve(item);
|
|
1095
|
+
return;
|
|
1096
|
+
}
|
|
1097
|
+
this.items.push(item);
|
|
1098
|
+
}
|
|
1099
|
+
close() {
|
|
1100
|
+
if (this.closed) return;
|
|
1101
|
+
this.closed = true;
|
|
1102
|
+
for (const waiter of this.waits.splice(0)) waiter.resolve(null);
|
|
1103
|
+
}
|
|
1104
|
+
clear() {
|
|
1105
|
+
this.items.length = 0;
|
|
1106
|
+
}
|
|
1107
|
+
async next() {
|
|
1108
|
+
if (this.items.length > 0) return this.items.shift() ?? null;
|
|
1109
|
+
if (this.closed) return null;
|
|
1110
|
+
const waiter = createDeferred();
|
|
1111
|
+
this.waits.push(waiter);
|
|
1112
|
+
return await waiter.promise;
|
|
1113
|
+
}
|
|
1114
|
+
async *iterate() {
|
|
1115
|
+
try {
|
|
1116
|
+
while (true) {
|
|
1117
|
+
const next = await this.next();
|
|
1118
|
+
if (!next) return;
|
|
1119
|
+
yield next;
|
|
1120
|
+
}
|
|
1121
|
+
} finally {
|
|
1122
|
+
this.close();
|
|
1123
|
+
this.clear();
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
};
|
|
1127
|
+
function toPromptInput(text, attachments) {
|
|
1128
|
+
if (!attachments || attachments.length === 0) return text;
|
|
1129
|
+
const blocks = [];
|
|
1130
|
+
if (text) blocks.push({
|
|
1131
|
+
type: "text",
|
|
1132
|
+
text
|
|
1133
|
+
});
|
|
1134
|
+
for (const attachment of attachments) {
|
|
1135
|
+
if (attachment.mediaType.startsWith("image/")) {
|
|
1136
|
+
blocks.push({
|
|
1137
|
+
type: "image",
|
|
1138
|
+
mimeType: attachment.mediaType,
|
|
1139
|
+
data: attachment.data
|
|
1140
|
+
});
|
|
1141
|
+
continue;
|
|
1142
|
+
}
|
|
1143
|
+
if (attachment.mediaType.startsWith("audio/")) {
|
|
1144
|
+
blocks.push({
|
|
1145
|
+
type: "audio",
|
|
1146
|
+
mimeType: attachment.mediaType,
|
|
1147
|
+
data: attachment.data
|
|
1148
|
+
});
|
|
1149
|
+
continue;
|
|
1150
|
+
}
|
|
1151
|
+
throw new AcpRuntimeError("ACP_TURN_FAILED", `Unsupported ACP runtime attachment media type: ${attachment.mediaType}`);
|
|
1152
|
+
}
|
|
1153
|
+
return blocks.length > 0 ? blocks : textPrompt(text);
|
|
1154
|
+
}
|
|
1155
|
+
function legacyTerminalEventFromTurnResult(result) {
|
|
1156
|
+
if (result.status === "failed") return {
|
|
1157
|
+
type: "error",
|
|
1158
|
+
message: result.error.message,
|
|
1159
|
+
...result.error.code ? { code: result.error.code } : {},
|
|
1160
|
+
...result.error.detailCode ? { detailCode: result.error.detailCode } : {},
|
|
1161
|
+
...result.error.retryable === void 0 ? {} : { retryable: result.error.retryable }
|
|
1162
|
+
};
|
|
1163
|
+
return {
|
|
1164
|
+
type: "done",
|
|
1165
|
+
...result.stopReason ? { stopReason: result.stopReason } : {},
|
|
1166
|
+
...result._meta === void 0 ? {} : { _meta: result._meta }
|
|
1167
|
+
};
|
|
1168
|
+
}
|
|
1169
|
+
//#endregion
|
|
1170
|
+
//#region src/runtime/engine/manager.ts
|
|
1171
|
+
async function settleAttempt(run) {
|
|
1172
|
+
try {
|
|
1173
|
+
return {
|
|
1174
|
+
ok: true,
|
|
1175
|
+
value: await run()
|
|
1176
|
+
};
|
|
1177
|
+
} catch (error) {
|
|
1178
|
+
return {
|
|
1179
|
+
ok: false,
|
|
1180
|
+
error
|
|
1181
|
+
};
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
function firstFailedAttempt(attempts) {
|
|
1185
|
+
return attempts.find((attempt) => !attempt.ok);
|
|
1186
|
+
}
|
|
1187
|
+
function isoNow() {
|
|
1188
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
1189
|
+
}
|
|
1190
|
+
function isUnsupportedSessionCloseError(error) {
|
|
1191
|
+
const acp = extractAcpError(error);
|
|
1192
|
+
if (!acp) return false;
|
|
1193
|
+
if (acp.code === -32601 || acp.code === -32602) return true;
|
|
1194
|
+
if (acp.code !== -32603 || !acp.data || typeof acp.data !== "object") return false;
|
|
1195
|
+
const details = acp.data.details;
|
|
1196
|
+
return typeof details === "string" && details.toLowerCase().includes("invalid params");
|
|
1197
|
+
}
|
|
1198
|
+
function createRecordId(sessionKey, mode) {
|
|
1199
|
+
if (mode === "persistent") return sessionKey;
|
|
1200
|
+
return `${sessionKey}:oneshot:${randomUUID()}`;
|
|
1201
|
+
}
|
|
1202
|
+
function resumePolicyForSessionMode(mode) {
|
|
1203
|
+
return mode === "persistent" ? "same-session-only" : "allow-new";
|
|
1204
|
+
}
|
|
1205
|
+
async function startRuntimeClient(client, agent, timeoutMs) {
|
|
1206
|
+
try {
|
|
1207
|
+
await withTimeout(client.start(), timeoutMs);
|
|
1208
|
+
} catch (error) {
|
|
1209
|
+
if (!(error instanceof TimeoutError)) throw error;
|
|
1210
|
+
throw new AcpRuntimeError("ACP_SESSION_INIT_FAILED", `ACP agent ${path.basename(agent.agentArgv?.[0] ?? agent.agentCommand.split(/\s+/)[0])} did not complete ACP initialization within ${timeoutMs}ms. Check that the configured command starts an ACP server.`, { cause: error });
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
async function createOrLoadRuntimeSession(client, resumeSessionId, cwd) {
|
|
1214
|
+
if (resumeSessionId) {
|
|
1215
|
+
if (client.supportsResumeSession()) {
|
|
1216
|
+
const resumed = await client.resumeSession(resumeSessionId, cwd);
|
|
1217
|
+
return {
|
|
1218
|
+
sessionId: resumeSessionId,
|
|
1219
|
+
agentSessionId: resumed.agentSessionId,
|
|
1220
|
+
sessionResult: resumed
|
|
1221
|
+
};
|
|
1222
|
+
}
|
|
1223
|
+
if (!client.supportsLoadSession()) throw new Error(`Agent does not support session/resume or session/load; cannot resume session ${resumeSessionId}`);
|
|
1224
|
+
const loaded = await client.loadSession(resumeSessionId, cwd);
|
|
1225
|
+
return {
|
|
1226
|
+
sessionId: resumeSessionId,
|
|
1227
|
+
agentSessionId: loaded.agentSessionId,
|
|
1228
|
+
sessionResult: loaded
|
|
1229
|
+
};
|
|
1230
|
+
}
|
|
1231
|
+
const created = await client.createSession(cwd);
|
|
1232
|
+
return {
|
|
1233
|
+
sessionId: created.sessionId,
|
|
1234
|
+
agentSessionId: created.agentSessionId,
|
|
1235
|
+
sessionResult: created
|
|
1236
|
+
};
|
|
1237
|
+
}
|
|
1238
|
+
var AcpRuntimeManager = class {
|
|
1239
|
+
options;
|
|
1240
|
+
deps;
|
|
1241
|
+
activeControllers = /* @__PURE__ */ new Map();
|
|
1242
|
+
controlSessionRecords = /* @__PURE__ */ new Map();
|
|
1243
|
+
retainedSessionOwners = /* @__PURE__ */ new Map();
|
|
1244
|
+
retiringSessionOwners = /* @__PURE__ */ new Set();
|
|
1245
|
+
pendingOneShotRecordIds = /* @__PURE__ */ new Map();
|
|
1246
|
+
ensureSessionLocks = /* @__PURE__ */ new Map();
|
|
1247
|
+
runtimeOperationLocks = /* @__PURE__ */ new Map();
|
|
1248
|
+
sessionTasks = /* @__PURE__ */ new Map();
|
|
1249
|
+
closingActiveRecords = /* @__PURE__ */ new Set();
|
|
1250
|
+
transientCredentials = /* @__PURE__ */ new Map();
|
|
1251
|
+
liveClients = /* @__PURE__ */ new Set();
|
|
1252
|
+
pendingTasks = /* @__PURE__ */ new Set();
|
|
1253
|
+
shuttingDown = false;
|
|
1254
|
+
shutdownTask;
|
|
1255
|
+
constructor(options, deps = {}) {
|
|
1256
|
+
this.options = options;
|
|
1257
|
+
this.deps = deps;
|
|
1258
|
+
}
|
|
1259
|
+
setTransientCredentials(recordId, credentials) {
|
|
1260
|
+
if (!credentials || Object.keys(credentials).length === 0) {
|
|
1261
|
+
this.transientCredentials.delete(recordId);
|
|
1262
|
+
return;
|
|
1263
|
+
}
|
|
1264
|
+
this.transientCredentials.set(recordId, { ...credentials });
|
|
1265
|
+
}
|
|
1266
|
+
createClient(options) {
|
|
1267
|
+
this.assertOpen();
|
|
1268
|
+
const clientOptions = {
|
|
1269
|
+
...options,
|
|
1270
|
+
agentProcessEnv: this.options.agentProcessEnv,
|
|
1271
|
+
processLifecycle: {
|
|
1272
|
+
...options.processLifecycle,
|
|
1273
|
+
onBeforeSpawn: async (launch) => {
|
|
1274
|
+
this.assertOpen();
|
|
1275
|
+
await options.processLifecycle?.onBeforeSpawn?.(launch);
|
|
1276
|
+
this.assertOpen();
|
|
1277
|
+
},
|
|
1278
|
+
onSpawned: async (process) => {
|
|
1279
|
+
this.assertOpen();
|
|
1280
|
+
await options.processLifecycle?.onSpawned?.(process);
|
|
1281
|
+
this.assertOpen();
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
};
|
|
1285
|
+
const client = this.deps.clientFactory?.(clientOptions) ?? new AcpClient(clientOptions);
|
|
1286
|
+
this.liveClients.add(client);
|
|
1287
|
+
return client;
|
|
1288
|
+
}
|
|
1289
|
+
async probe() {
|
|
1290
|
+
let client;
|
|
1291
|
+
try {
|
|
1292
|
+
return await probeRuntime(this.options, { clientFactory: (options) => client = this.createClient(options) });
|
|
1293
|
+
} finally {
|
|
1294
|
+
if (client) this.liveClients.delete(client);
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
assertOpen() {
|
|
1298
|
+
if (this.shuttingDown) throw new AcpRuntimeError("ACP_BACKEND_UNAVAILABLE", "ACP runtime is shut down.");
|
|
1299
|
+
}
|
|
1300
|
+
shutdown() {
|
|
1301
|
+
if (!this.shutdownTask) {
|
|
1302
|
+
this.shuttingDown = true;
|
|
1303
|
+
this.shutdownTask = this.shutdownOwnedClients();
|
|
1304
|
+
}
|
|
1305
|
+
return this.shutdownTask;
|
|
1306
|
+
}
|
|
1307
|
+
async shutdownOwnedClients() {
|
|
1308
|
+
const closed = await Promise.allSettled([...this.liveClients].map(async (client) => {
|
|
1309
|
+
client.requestCancelActivePrompt().catch(() => {});
|
|
1310
|
+
await this.closeClient(client);
|
|
1311
|
+
}));
|
|
1312
|
+
await Promise.allSettled([
|
|
1313
|
+
...this.ensureSessionLocks.values(),
|
|
1314
|
+
...this.runtimeOperationLocks.values(),
|
|
1315
|
+
...this.pendingTasks
|
|
1316
|
+
]);
|
|
1317
|
+
const owners = /* @__PURE__ */ new Set([...this.retainedSessionOwners.values(), ...this.retiringSessionOwners]);
|
|
1318
|
+
const stopped = await Promise.allSettled([...owners].map(async (owner) => {
|
|
1319
|
+
this.removeRetainedSessionOwner(owner);
|
|
1320
|
+
const retirement = owner.retirement;
|
|
1321
|
+
if (retirement) await retirement;
|
|
1322
|
+
else {
|
|
1323
|
+
const failure = await this.stopSessionOwner(owner);
|
|
1324
|
+
if (failure) throw failure.error;
|
|
1325
|
+
}
|
|
1326
|
+
this.retiringSessionOwners.delete(owner);
|
|
1327
|
+
}));
|
|
1328
|
+
const errors = [];
|
|
1329
|
+
for (const result of [...closed, ...stopped]) if (result.status === "rejected") errors.push(result.reason);
|
|
1330
|
+
if (errors.length) throw new AggregateError(errors, "ACP runtime shutdown failed.");
|
|
1331
|
+
}
|
|
1332
|
+
trackTask(task) {
|
|
1333
|
+
this.pendingTasks.add(task);
|
|
1334
|
+
const remove = () => {
|
|
1335
|
+
this.pendingTasks.delete(task);
|
|
1336
|
+
};
|
|
1337
|
+
task.then(remove, remove);
|
|
1338
|
+
return task;
|
|
1339
|
+
}
|
|
1340
|
+
queueSessionTask(recordId, run, cancel) {
|
|
1341
|
+
const tasks = this.sessionTasks.get(recordId) ?? /* @__PURE__ */ new Set();
|
|
1342
|
+
this.sessionTasks.set(recordId, tasks);
|
|
1343
|
+
const previous = [...tasks].at(-1)?.completion;
|
|
1344
|
+
const result = (async () => {
|
|
1345
|
+
await previous?.catch(() => {});
|
|
1346
|
+
return await run();
|
|
1347
|
+
})();
|
|
1348
|
+
const task = {
|
|
1349
|
+
completion: result.then(() => {}),
|
|
1350
|
+
cancel
|
|
1351
|
+
};
|
|
1352
|
+
task.completion.catch(() => {});
|
|
1353
|
+
tasks.add(task);
|
|
1354
|
+
const remove = () => {
|
|
1355
|
+
tasks.delete(task);
|
|
1356
|
+
if (tasks.size === 0) this.sessionTasks.delete(recordId);
|
|
1357
|
+
};
|
|
1358
|
+
result.then(remove, remove);
|
|
1359
|
+
return this.trackTask(result);
|
|
1360
|
+
}
|
|
1361
|
+
async cancelSessionTasks(recordId) {
|
|
1362
|
+
const tasks = [...this.sessionTasks.get(recordId) ?? []];
|
|
1363
|
+
await Promise.all(tasks.flatMap((task) => task.cancel ? [task.cancel()] : []));
|
|
1364
|
+
return tasks;
|
|
1365
|
+
}
|
|
1366
|
+
async closeClient(client) {
|
|
1367
|
+
await client.close();
|
|
1368
|
+
this.liveClients.delete(client);
|
|
1369
|
+
}
|
|
1370
|
+
createSessionOwner(input) {
|
|
1371
|
+
const owner = {
|
|
1372
|
+
...input,
|
|
1373
|
+
checkpoint: new LiveSessionCheckpoint({
|
|
1374
|
+
save: async () => this.saveSessionOwner(owner),
|
|
1375
|
+
onPersisted: () => {
|
|
1376
|
+
const notice = owner.pendingOutOfTurnNotice;
|
|
1377
|
+
owner.pendingOutOfTurnNotice = void 0;
|
|
1378
|
+
notice?.();
|
|
1379
|
+
}
|
|
1380
|
+
}),
|
|
1381
|
+
bufferSessionUpdates: false,
|
|
1382
|
+
pendingSessionUpdates: []
|
|
1383
|
+
};
|
|
1384
|
+
this.installActiveOwnerEventHandlers(owner);
|
|
1385
|
+
return owner;
|
|
1386
|
+
}
|
|
1387
|
+
installActiveOwnerEventHandlers(owner) {
|
|
1388
|
+
owner.client.setEventHandlers({
|
|
1389
|
+
onSessionUpdate: (notification) => this.routeOwnedSessionUpdate(owner, notification),
|
|
1390
|
+
onClientOperation: (operation) => this.routeOwnedClientOperation(owner, operation)
|
|
1391
|
+
});
|
|
1392
|
+
}
|
|
1393
|
+
installIdleOwnerEventHandlers(owner) {
|
|
1394
|
+
try {
|
|
1395
|
+
owner.client.clearEventHandlers();
|
|
1396
|
+
} catch {}
|
|
1397
|
+
owner.client.setEventHandlers({ onSessionUpdate: (notification) => this.routeOwnedSessionUpdate(owner, notification) });
|
|
1398
|
+
}
|
|
1399
|
+
async saveSessionOwner(owner) {
|
|
1400
|
+
if (!owner.recordId) return;
|
|
1401
|
+
const active = owner.activeTurn?.turn;
|
|
1402
|
+
const target = active ?? owner.projection;
|
|
1403
|
+
if (!target) return;
|
|
1404
|
+
const { record, conversation } = target;
|
|
1405
|
+
if (active?.connected) record.acpx = active.acpxState;
|
|
1406
|
+
record.lastUsedAt = isoNow();
|
|
1407
|
+
applyConversation(record, conversation);
|
|
1408
|
+
applyLifecycleSnapshotToRecord(record, owner.client.getAgentLifecycleSnapshot());
|
|
1409
|
+
await this.refreshClosedState(record);
|
|
1410
|
+
await this.options.sessionStore.save(record);
|
|
1411
|
+
}
|
|
1412
|
+
routeOwnedSessionUpdate(owner, notification) {
|
|
1413
|
+
const active = owner.activeTurn;
|
|
1414
|
+
if (active) {
|
|
1415
|
+
const { task, turn } = active;
|
|
1416
|
+
if (turn.connected) {
|
|
1417
|
+
turn.acpxState = recordSessionUpdate(turn.conversation, turn.acpxState, notification);
|
|
1418
|
+
owner.checkpoint.request();
|
|
1419
|
+
} else turn.record.acpx = recordSessionUpdate(turn.conversation, turn.record.acpx, notification);
|
|
1420
|
+
trimConversationForRuntime(turn.conversation);
|
|
1421
|
+
this.emitRuntimeTurnEvent(task, {
|
|
1422
|
+
jsonrpc: "2.0",
|
|
1423
|
+
method: "session/update",
|
|
1424
|
+
params: notification
|
|
1425
|
+
});
|
|
1426
|
+
return;
|
|
1427
|
+
}
|
|
1428
|
+
if (owner.bufferSessionUpdates) {
|
|
1429
|
+
owner.pendingSessionUpdates.push(notification);
|
|
1430
|
+
return;
|
|
1431
|
+
}
|
|
1432
|
+
const projection = owner.projection;
|
|
1433
|
+
if (!projection) {
|
|
1434
|
+
owner.pendingSessionUpdates.push(notification);
|
|
1435
|
+
return;
|
|
1436
|
+
}
|
|
1437
|
+
projection.record.acpx = recordSessionUpdate(projection.conversation, projection.record.acpx, notification);
|
|
1438
|
+
trimConversationForRuntime(projection.conversation);
|
|
1439
|
+
const updateTag = notification.update.sessionUpdate;
|
|
1440
|
+
owner.pendingOutOfTurnNotice = () => {
|
|
1441
|
+
this.options.onOutOfTurnSessionUpdate?.(owner.recordId ?? owner.sessionKey, updateTag, notification);
|
|
1442
|
+
};
|
|
1443
|
+
owner.checkpoint.request();
|
|
1444
|
+
}
|
|
1445
|
+
routeOwnedClientOperation(owner, operation) {
|
|
1446
|
+
const active = owner.activeTurn;
|
|
1447
|
+
if (!active) return;
|
|
1448
|
+
const { task, turn } = active;
|
|
1449
|
+
if (turn.connected) {
|
|
1450
|
+
turn.acpxState = recordClientOperation(turn.conversation, turn.acpxState, operation);
|
|
1451
|
+
owner.checkpoint.request();
|
|
1452
|
+
} else turn.record.acpx = recordClientOperation(turn.conversation, turn.record.acpx, operation);
|
|
1453
|
+
trimConversationForRuntime(turn.conversation);
|
|
1454
|
+
this.emitRuntimeTurnEvent(task, {
|
|
1455
|
+
type: "client_operation",
|
|
1456
|
+
...operation
|
|
1457
|
+
});
|
|
1458
|
+
}
|
|
1459
|
+
attachIdleProjection(owner, record, conversation = cloneSessionConversation(record), acpxState = record.acpx) {
|
|
1460
|
+
record.acpx = acpxState;
|
|
1461
|
+
owner.projection = {
|
|
1462
|
+
record,
|
|
1463
|
+
conversation
|
|
1464
|
+
};
|
|
1465
|
+
owner.activeTurn = void 0;
|
|
1466
|
+
this.drainPendingSessionUpdates(owner);
|
|
1467
|
+
}
|
|
1468
|
+
drainPendingSessionUpdates(owner) {
|
|
1469
|
+
for (const notification of owner.pendingSessionUpdates.splice(0)) this.routeOwnedSessionUpdate(owner, notification);
|
|
1470
|
+
}
|
|
1471
|
+
async flushSessionOwner(owner) {
|
|
1472
|
+
await owner.client.waitForSessionUpdatesIdle?.().catch(() => {});
|
|
1473
|
+
await owner.checkpoint.flush();
|
|
1474
|
+
}
|
|
1475
|
+
removeRetainedSessionOwner(owner) {
|
|
1476
|
+
if (owner.recordId && this.retainedSessionOwners.get(owner.recordId) === owner) this.retainedSessionOwners.delete(owner.recordId);
|
|
1477
|
+
if (owner.mode === "oneshot" && owner.recordId && this.pendingOneShotRecordIds.get(owner.sessionKey) === owner.recordId) this.pendingOneShotRecordIds.delete(owner.sessionKey);
|
|
1478
|
+
}
|
|
1479
|
+
async readRetainedSessionOwner(record, options) {
|
|
1480
|
+
const owner = this.retainedSessionOwners.get(record.acpxRecordId);
|
|
1481
|
+
if (!owner) return;
|
|
1482
|
+
await this.flushSessionOwner(owner);
|
|
1483
|
+
const projectedRecord = owner.projection?.record;
|
|
1484
|
+
if (projectedRecord && projectedRecord !== record) Object.assign(record, structuredClone(projectedRecord));
|
|
1485
|
+
if (!owner.client.hasReusableSession(record.acpSessionId)) {
|
|
1486
|
+
this.removeRetainedSessionOwner(owner);
|
|
1487
|
+
await this.stopSessionOwner(owner);
|
|
1488
|
+
return;
|
|
1489
|
+
}
|
|
1490
|
+
if (options.consume) this.removeRetainedSessionOwner(owner);
|
|
1491
|
+
return owner;
|
|
1492
|
+
}
|
|
1493
|
+
async closeRetainedSessionOwner(recordId) {
|
|
1494
|
+
const owner = this.retainedSessionOwners.get(recordId);
|
|
1495
|
+
if (!owner) return;
|
|
1496
|
+
this.removeRetainedSessionOwner(owner);
|
|
1497
|
+
await this.stopSessionOwner(owner);
|
|
1498
|
+
}
|
|
1499
|
+
async stopSessionOwner(owner) {
|
|
1500
|
+
const flushAttempt = await settleAttempt(async () => this.flushSessionOwner(owner));
|
|
1501
|
+
const closeAttempt = await settleAttempt(async () => this.closeClient(owner.client));
|
|
1502
|
+
if (!closeAttempt.ok) this.retiringSessionOwners.add(owner);
|
|
1503
|
+
return firstFailedAttempt([
|
|
1504
|
+
flushAttempt,
|
|
1505
|
+
closeAttempt,
|
|
1506
|
+
await settleAttempt(async () => owner.checkpoint.flush()),
|
|
1507
|
+
await settleAttempt(() => owner.client.clearEventHandlers())
|
|
1508
|
+
]);
|
|
1509
|
+
}
|
|
1510
|
+
async retrySessionCleanup(recordId) {
|
|
1511
|
+
for (const owner of this.retiringSessionOwners) if (owner.recordId === recordId) {
|
|
1512
|
+
owner.retirement ??= this.finalizeSessionConnection({
|
|
1513
|
+
client: owner.client,
|
|
1514
|
+
owner
|
|
1515
|
+
}).then(() => {
|
|
1516
|
+
this.retiringSessionOwners.delete(owner);
|
|
1517
|
+
}).finally(() => {
|
|
1518
|
+
owner.retirement = void 0;
|
|
1519
|
+
});
|
|
1520
|
+
await owner.retirement;
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
async refreshClosedState(record) {
|
|
1524
|
+
if (!this.closingActiveRecords.has(record.acpxRecordId)) return record.closed === true;
|
|
1525
|
+
const latest = await this.options.sessionStore.load(record.acpxRecordId).catch(() => void 0);
|
|
1526
|
+
record.closed = true;
|
|
1527
|
+
record.closedAt = latest?.closedAt ?? record.closedAt ?? isoNow();
|
|
1528
|
+
if (latest?.acpx?.reset_on_next_ensure === true) record.acpx = {
|
|
1529
|
+
...record.acpx,
|
|
1530
|
+
reset_on_next_ensure: true
|
|
1531
|
+
};
|
|
1532
|
+
return true;
|
|
1533
|
+
}
|
|
1534
|
+
async retainPersistentSessionOwnerAfterTurn(input) {
|
|
1535
|
+
const { record, owner } = input;
|
|
1536
|
+
if (!this.canRetainPersistentSessionOwner(owner, record)) return false;
|
|
1537
|
+
const previousOwner = this.retainedSessionOwners.get(record.acpxRecordId);
|
|
1538
|
+
this.retainedSessionOwners.set(record.acpxRecordId, owner);
|
|
1539
|
+
if (previousOwner && previousOwner !== owner) {
|
|
1540
|
+
this.removeRetainedSessionOwner(previousOwner);
|
|
1541
|
+
await this.stopSessionOwner(previousOwner);
|
|
1542
|
+
}
|
|
1543
|
+
this.installIdleOwnerEventHandlers(owner);
|
|
1544
|
+
return true;
|
|
1545
|
+
}
|
|
1546
|
+
canRetainPersistentSessionOwner(owner, record) {
|
|
1547
|
+
return !this.shuttingDown && owner.mode === "persistent" && !record.closed && !(owner.client.hasUnresolvedPrompt?.() ?? false) && owner.client.hasReusableSession(record.acpSessionId);
|
|
1548
|
+
}
|
|
1549
|
+
resolveMcpServers(session) {
|
|
1550
|
+
const servers = this.options.mcpServers;
|
|
1551
|
+
const { sessionKey, cwd, agentCommand, agentArgv } = session;
|
|
1552
|
+
return [...typeof servers === "function" ? servers({
|
|
1553
|
+
sessionKey,
|
|
1554
|
+
cwd,
|
|
1555
|
+
agentCommand,
|
|
1556
|
+
agentArgv: agentArgv ? [...agentArgv] : void 0
|
|
1557
|
+
}) : servers ?? []];
|
|
1558
|
+
}
|
|
1559
|
+
resolveSessionPermissions(session) {
|
|
1560
|
+
const { sessionKey, cwd, agentCommand, agentArgv } = session;
|
|
1561
|
+
const { permissionMode = this.options.permissionMode, nonInteractivePermissions = this.options.nonInteractivePermissions, permissionPolicy = this.options.permissionPolicy, onPermissionRequest = this.options.onPermissionRequest } = this.options.sessionPermissions?.({
|
|
1562
|
+
sessionKey,
|
|
1563
|
+
cwd,
|
|
1564
|
+
agentCommand,
|
|
1565
|
+
agentArgv: agentArgv ? [...agentArgv] : void 0
|
|
1566
|
+
}) ?? {};
|
|
1567
|
+
return {
|
|
1568
|
+
permissionMode,
|
|
1569
|
+
nonInteractivePermissions,
|
|
1570
|
+
permissionPolicy,
|
|
1571
|
+
onPermissionRequest
|
|
1572
|
+
};
|
|
1573
|
+
}
|
|
1574
|
+
resolveClientCapabilities() {
|
|
1575
|
+
return {
|
|
1576
|
+
fs: this.options.fs,
|
|
1577
|
+
terminal: this.options.terminal
|
|
1578
|
+
};
|
|
1579
|
+
}
|
|
1580
|
+
async withRuntimeControlSession(record, sessionMode, run, replayOptions, authority) {
|
|
1581
|
+
await this.retrySessionCleanup(record.acpxRecordId);
|
|
1582
|
+
assertControlAuthority(authority);
|
|
1583
|
+
const owner = await this.readRetainedSessionOwner(record, { consume: false });
|
|
1584
|
+
assertControlAuthority(authority);
|
|
1585
|
+
if (owner) {
|
|
1586
|
+
const ownedRecord = owner.projection?.record ?? record;
|
|
1587
|
+
try {
|
|
1588
|
+
const value = await run({
|
|
1589
|
+
client: owner.client,
|
|
1590
|
+
sessionId: ownedRecord.acpSessionId,
|
|
1591
|
+
record: ownedRecord
|
|
1592
|
+
});
|
|
1593
|
+
this.refreshOwnedRecordLifecycle(owner, ownedRecord);
|
|
1594
|
+
await owner.checkpoint.checkpoint();
|
|
1595
|
+
return value;
|
|
1596
|
+
} finally {
|
|
1597
|
+
await this.flushSessionOwner(owner);
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1600
|
+
let controlClient;
|
|
1601
|
+
let controlledRecord = record;
|
|
1602
|
+
const checkpoint = new LiveSessionCheckpoint({ save: async () => this.options.sessionStore.save(controlledRecord) });
|
|
1603
|
+
try {
|
|
1604
|
+
const result = await settleAttempt(async () => withConnectedSession({
|
|
1605
|
+
sessionRecordId: record.acpxRecordId,
|
|
1606
|
+
loadRecord: async (sessionRecordId) => {
|
|
1607
|
+
controlledRecord = await this.requireRecord(sessionRecordId);
|
|
1608
|
+
this.controlSessionRecords.set(sessionRecordId, {
|
|
1609
|
+
record: controlledRecord,
|
|
1610
|
+
checkpoint
|
|
1611
|
+
});
|
|
1612
|
+
return controlledRecord;
|
|
1613
|
+
},
|
|
1614
|
+
saveRecord: async () => checkpoint.checkpoint(),
|
|
1615
|
+
createClient: (options) => controlClient = this.createClient({
|
|
1616
|
+
...options,
|
|
1617
|
+
processLifecycle: this.options.processLifecycle,
|
|
1618
|
+
processLaunchScope: {
|
|
1619
|
+
kind: "runtime-session",
|
|
1620
|
+
sessionKey: record.name ?? record.acpxRecordId
|
|
1621
|
+
}
|
|
1622
|
+
}),
|
|
1623
|
+
mcpServers: this.resolveMcpServers({
|
|
1624
|
+
...record,
|
|
1625
|
+
sessionKey: record.name ?? record.acpxRecordId
|
|
1626
|
+
}),
|
|
1627
|
+
...this.resolveSessionPermissions({
|
|
1628
|
+
...record,
|
|
1629
|
+
sessionKey: record.name ?? record.acpxRecordId
|
|
1630
|
+
}),
|
|
1631
|
+
...this.resolveClientCapabilities(),
|
|
1632
|
+
elicitationModes: this.options.elicitationModes,
|
|
1633
|
+
verbose: this.options.verbose,
|
|
1634
|
+
timeoutMs: this.options.timeoutMs,
|
|
1635
|
+
resumePolicy: resumePolicyForSessionMode(sessionMode),
|
|
1636
|
+
replacingMode: replayOptions?.replacingMode,
|
|
1637
|
+
replacingConfigOption: replayOptions?.replacingConfigOption,
|
|
1638
|
+
authority,
|
|
1639
|
+
run,
|
|
1640
|
+
onAskUserQuestion: this.options.onAskUserQuestion,
|
|
1641
|
+
onExitPlanMode: this.options.onExitPlanMode,
|
|
1642
|
+
authCredentials: this.transientCredentials.get(record.acpxRecordId)
|
|
1643
|
+
}));
|
|
1644
|
+
this.controlSessionRecords.delete(record.acpxRecordId);
|
|
1645
|
+
const flushed = await settleAttempt(async () => checkpoint.flush());
|
|
1646
|
+
if (!result.ok) throw result.error;
|
|
1647
|
+
if (!flushed.ok) throw flushed.error;
|
|
1648
|
+
return result.value.value;
|
|
1649
|
+
} finally {
|
|
1650
|
+
this.controlSessionRecords.delete(record.acpxRecordId);
|
|
1651
|
+
if (controlClient) this.liveClients.delete(controlClient);
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
refreshOwnedRecordLifecycle(owner, record) {
|
|
1655
|
+
record.lastUsedAt = isoNow();
|
|
1656
|
+
record.closed = false;
|
|
1657
|
+
record.closedAt = void 0;
|
|
1658
|
+
record.protocolVersion = owner.client.initializeResult?.protocolVersion;
|
|
1659
|
+
record.agentCapabilities = owner.client.initializeResult?.agentCapabilities;
|
|
1660
|
+
applyLifecycleSnapshotToRecord(record, owner.client.getAgentLifecycleSnapshot());
|
|
1661
|
+
}
|
|
1662
|
+
async ensureSession(input) {
|
|
1663
|
+
return await this.withEnsureSessionLock(input, async () => this.ensureSessionWithOwnership(input));
|
|
1664
|
+
}
|
|
1665
|
+
async withEnsureSessionLock(input, run) {
|
|
1666
|
+
const key = `${input.mode}\0${input.sessionKey}`;
|
|
1667
|
+
return await this.withManagerLock(this.ensureSessionLocks, key, run);
|
|
1668
|
+
}
|
|
1669
|
+
async withManagerLock(locks, key, run, authority) {
|
|
1670
|
+
this.assertOpen();
|
|
1671
|
+
assertControlAuthority(authority);
|
|
1672
|
+
return await this.serializeManagerOperation(locks, key, async () => {
|
|
1673
|
+
this.assertOpen();
|
|
1674
|
+
assertControlAuthority(authority);
|
|
1675
|
+
return await run();
|
|
1676
|
+
});
|
|
1677
|
+
}
|
|
1678
|
+
async serializeManagerOperation(locks, key, run) {
|
|
1679
|
+
const previous = locks.get(key) ?? Promise.resolve();
|
|
1680
|
+
let release;
|
|
1681
|
+
const gate = new Promise((resolve) => {
|
|
1682
|
+
release = resolve;
|
|
1683
|
+
});
|
|
1684
|
+
const tail = previous.then(() => gate);
|
|
1685
|
+
locks.set(key, tail);
|
|
1686
|
+
await previous;
|
|
1687
|
+
try {
|
|
1688
|
+
return await run();
|
|
1689
|
+
} finally {
|
|
1690
|
+
release();
|
|
1691
|
+
if (locks.get(key) === tail) locks.delete(key);
|
|
1692
|
+
}
|
|
1693
|
+
}
|
|
1694
|
+
async ensureSessionWithOwnership(input) {
|
|
1695
|
+
const cwd = path.resolve(input.cwd?.trim() || this.options.cwd);
|
|
1696
|
+
const { agentCommand, agentArgv: defaultAgentArgv } = normalizeAgentCommandInput(this.options.agentRegistry.resolve(input.agent));
|
|
1697
|
+
const agent = {
|
|
1698
|
+
cwd,
|
|
1699
|
+
agentCommand,
|
|
1700
|
+
agentArgv: input.agentArgv ?? defaultAgentArgv
|
|
1701
|
+
};
|
|
1702
|
+
if (input.mode !== "persistent") return await this.acquireRuntimeSession(input, agent);
|
|
1703
|
+
const compatible = await this.reuseCompatiblePersistentSession(input, agent);
|
|
1704
|
+
if (compatible) return compatible;
|
|
1705
|
+
this.assertRuntimeSessionIdle(input.sessionKey);
|
|
1706
|
+
return await this.withManagerLock(this.runtimeOperationLocks, input.sessionKey, async () => this.acquireRuntimeSession(input, agent));
|
|
1707
|
+
}
|
|
1708
|
+
async reuseCompatiblePersistentSession(input, agent) {
|
|
1709
|
+
const controlled = this.controlSessionRecords.get(input.sessionKey);
|
|
1710
|
+
const record = controlled ? controlled.record : await this.findSession(input.sessionKey);
|
|
1711
|
+
if (!record || this.closingActiveRecords.has(input.sessionKey) || !shouldReuseExistingRecord(record, {
|
|
1712
|
+
...agent,
|
|
1713
|
+
resumeSessionId: input.resumeSessionId
|
|
1714
|
+
})) return;
|
|
1715
|
+
if (!record.closed) return record;
|
|
1716
|
+
if (!controlled || this.sessionTasks.has(input.sessionKey)) return;
|
|
1717
|
+
return await this.reuseRuntimeSession({ record }, controlled.checkpoint);
|
|
1718
|
+
}
|
|
1719
|
+
async acquireRuntimeSession(input, agent) {
|
|
1720
|
+
const existing = await this.loadExistingRuntimeSession(input);
|
|
1721
|
+
if (existing && this.canReuseRuntimeSession(input, agent, existing)) return await this.reuseRuntimeSession(existing);
|
|
1722
|
+
await this.closeConflictingPersistentSession(input, existing?.owner);
|
|
1723
|
+
return await this.createOwnedRuntimeSession(input, agent);
|
|
1724
|
+
}
|
|
1725
|
+
async loadExistingRuntimeSession(input) {
|
|
1726
|
+
const existingRecordId = input.mode === "persistent" ? input.sessionKey : this.pendingOneShotRecordIds.get(input.sessionKey);
|
|
1727
|
+
if (!existingRecordId) return;
|
|
1728
|
+
await this.retrySessionCleanup(existingRecordId);
|
|
1729
|
+
let record = await this.findSession(existingRecordId);
|
|
1730
|
+
if (!record) return;
|
|
1731
|
+
const owner = this.retainedSessionOwners.get(record.acpxRecordId);
|
|
1732
|
+
if (owner) {
|
|
1733
|
+
await this.flushSessionOwner(owner);
|
|
1734
|
+
record = owner.projection?.record ?? record;
|
|
1735
|
+
}
|
|
1736
|
+
return {
|
|
1737
|
+
record,
|
|
1738
|
+
owner
|
|
1739
|
+
};
|
|
1740
|
+
}
|
|
1741
|
+
async findSession(sessionKey) {
|
|
1742
|
+
return await this.options.sessionStore.load(sessionKey);
|
|
1743
|
+
}
|
|
1744
|
+
canReuseRuntimeSession(input, agent, existing) {
|
|
1745
|
+
if (!shouldReuseExistingRecord(existing.record, {
|
|
1746
|
+
cwd: agent.cwd,
|
|
1747
|
+
agentCommand: agent.agentCommand,
|
|
1748
|
+
agentArgv: agent.agentArgv,
|
|
1749
|
+
resumeSessionId: input.resumeSessionId
|
|
1750
|
+
})) return false;
|
|
1751
|
+
if (input.mode === "persistent") return true;
|
|
1752
|
+
return Boolean(existing.owner && !existing.record.closed && this.pendingOneShotRecordIds.get(input.sessionKey) === existing.record.acpxRecordId && this.retainedSessionOwners.get(existing.record.acpxRecordId) === existing.owner && isDeepStrictEqual(sessionOptionsFromRecord(existing.record), normalizeSessionOptionShape(input.sessionOptions)));
|
|
1753
|
+
}
|
|
1754
|
+
assertRuntimeSessionIdle(recordId) {
|
|
1755
|
+
if (this.sessionTasks.has(recordId) || this.runtimeOperationLocks.has(recordId)) throw new AcpRuntimeError("ACP_SESSION_INIT_FAILED", `Cannot ensure session ${recordId} with incompatible or closing state while its work is unfinished. Wait for existing work to finish or use a different session key.`);
|
|
1756
|
+
}
|
|
1757
|
+
async reuseRuntimeSession({ record, owner }, checkpoint = owner?.checkpoint) {
|
|
1758
|
+
if (!record.closed && !this.closingActiveRecords.has(record.acpxRecordId)) return record;
|
|
1759
|
+
record.closed = false;
|
|
1760
|
+
record.closedAt = void 0;
|
|
1761
|
+
this.closingActiveRecords.delete(record.acpxRecordId);
|
|
1762
|
+
if (checkpoint) await checkpoint.checkpoint();
|
|
1763
|
+
else await this.options.sessionStore.save(record);
|
|
1764
|
+
return record;
|
|
1765
|
+
}
|
|
1766
|
+
async closeConflictingPersistentSession(input, owner) {
|
|
1767
|
+
if (input.mode === "persistent" && owner?.recordId) {
|
|
1768
|
+
this.removeRetainedSessionOwner(owner);
|
|
1769
|
+
this.retiringSessionOwners.add(owner);
|
|
1770
|
+
await this.retrySessionCleanup(owner.recordId);
|
|
1771
|
+
}
|
|
1772
|
+
}
|
|
1773
|
+
async createOwnedRuntimeSession(input, agent) {
|
|
1774
|
+
const { cwd, agentCommand, agentArgv } = agent;
|
|
1775
|
+
const client = this.createClient({
|
|
1776
|
+
agentCommand,
|
|
1777
|
+
agentArgv,
|
|
1778
|
+
cwd,
|
|
1779
|
+
mcpServers: this.resolveMcpServers({
|
|
1780
|
+
...agent,
|
|
1781
|
+
sessionKey: input.sessionKey
|
|
1782
|
+
}),
|
|
1783
|
+
...this.resolveSessionPermissions({
|
|
1784
|
+
...agent,
|
|
1785
|
+
sessionKey: input.sessionKey
|
|
1786
|
+
}),
|
|
1787
|
+
...this.resolveClientCapabilities(),
|
|
1788
|
+
onAskUserQuestion: this.options.onAskUserQuestion,
|
|
1789
|
+
onExitPlanMode: this.options.onExitPlanMode,
|
|
1790
|
+
authCredentials: input.authCredentials,
|
|
1791
|
+
elicitationModes: this.options.elicitationModes,
|
|
1792
|
+
processLifecycle: this.options.processLifecycle,
|
|
1793
|
+
processLaunchScope: {
|
|
1794
|
+
kind: "runtime-session",
|
|
1795
|
+
sessionKey: input.sessionKey
|
|
1796
|
+
},
|
|
1797
|
+
verbose: this.options.verbose,
|
|
1798
|
+
sessionOptions: input.sessionOptions
|
|
1799
|
+
});
|
|
1800
|
+
const owner = this.createSessionOwner({
|
|
1801
|
+
client,
|
|
1802
|
+
sessionKey: input.sessionKey,
|
|
1803
|
+
mode: input.mode
|
|
1804
|
+
});
|
|
1805
|
+
let retained = false;
|
|
1806
|
+
try {
|
|
1807
|
+
await startRuntimeClient(client, agent, this.options.timeoutMs);
|
|
1808
|
+
this.assertOpen();
|
|
1809
|
+
const session = await createOrLoadRuntimeSession(client, input.resumeSessionId, cwd);
|
|
1810
|
+
const record = await this.prepareInitialRuntimeRecord({
|
|
1811
|
+
input,
|
|
1812
|
+
client,
|
|
1813
|
+
owner,
|
|
1814
|
+
agentCommand,
|
|
1815
|
+
agentArgv,
|
|
1816
|
+
cwd,
|
|
1817
|
+
session
|
|
1818
|
+
});
|
|
1819
|
+
this.setTransientCredentials(record.acpxRecordId, input.authCredentials);
|
|
1820
|
+
await this.retainInitializedSessionOwner(owner, record);
|
|
1821
|
+
retained = true;
|
|
1822
|
+
return record;
|
|
1823
|
+
} finally {
|
|
1824
|
+
if (!retained) {
|
|
1825
|
+
owner.recordId = void 0;
|
|
1826
|
+
client.clearEventHandlers();
|
|
1827
|
+
await this.closeClient(client);
|
|
1828
|
+
}
|
|
1829
|
+
}
|
|
1830
|
+
}
|
|
1831
|
+
async prepareInitialRuntimeRecord(params) {
|
|
1832
|
+
const { input, client, owner, agentCommand, agentArgv, cwd, session } = params;
|
|
1833
|
+
const record = createInitialSessionRecord({
|
|
1834
|
+
recordId: createRecordId(input.sessionKey, input.mode),
|
|
1835
|
+
name: input.sessionKey,
|
|
1836
|
+
sessionId: session.sessionId,
|
|
1837
|
+
agentCommand,
|
|
1838
|
+
agentArgv,
|
|
1839
|
+
cwd,
|
|
1840
|
+
agentSessionId: session.agentSessionId
|
|
1841
|
+
});
|
|
1842
|
+
this.closingActiveRecords.delete(record.acpxRecordId);
|
|
1843
|
+
record.protocolVersion = client.initializeResult?.protocolVersion;
|
|
1844
|
+
record.agentCapabilities = client.initializeResult?.agentCapabilities;
|
|
1845
|
+
this.attachIdleProjection(owner, record);
|
|
1846
|
+
applyConfigOptionsToRecord(record, session.sessionResult);
|
|
1847
|
+
const modelApplication = await applyRequestedModelIfAdvertised({
|
|
1848
|
+
client,
|
|
1849
|
+
sessionId: session.sessionId,
|
|
1850
|
+
requestedModel: input.sessionOptions?.model,
|
|
1851
|
+
models: session.sessionResult.models,
|
|
1852
|
+
agentCommand,
|
|
1853
|
+
timeoutMs: this.options.timeoutMs
|
|
1854
|
+
});
|
|
1855
|
+
applyInitialModelSelection(record, session.sessionResult.models, modelApplication);
|
|
1856
|
+
applyLifecycleSnapshotToRecord(record, client.getAgentLifecycleSnapshot());
|
|
1857
|
+
persistSessionOptions(record, input.sessionOptions);
|
|
1858
|
+
return record;
|
|
1859
|
+
}
|
|
1860
|
+
async retainInitializedSessionOwner(owner, record) {
|
|
1861
|
+
owner.recordId = record.acpxRecordId;
|
|
1862
|
+
await owner.checkpoint.checkpoint();
|
|
1863
|
+
this.assertOpen();
|
|
1864
|
+
const previousOwner = this.retainedSessionOwners.get(record.acpxRecordId);
|
|
1865
|
+
this.retainedSessionOwners.set(record.acpxRecordId, owner);
|
|
1866
|
+
if (owner.mode === "oneshot") this.pendingOneShotRecordIds.set(owner.sessionKey, record.acpxRecordId);
|
|
1867
|
+
if (previousOwner && previousOwner !== owner) {
|
|
1868
|
+
this.removeRetainedSessionOwner(previousOwner);
|
|
1869
|
+
await this.stopSessionOwner(previousOwner);
|
|
1870
|
+
}
|
|
1871
|
+
}
|
|
1872
|
+
startTurn(input) {
|
|
1873
|
+
this.assertOpen();
|
|
1874
|
+
let promptInput;
|
|
1875
|
+
try {
|
|
1876
|
+
promptInput = toPromptInput(input.text, input.attachments);
|
|
1877
|
+
} catch (error) {
|
|
1878
|
+
this.trackTask(this.closeRetainedOneShotHandle(input.handle).catch(() => {}));
|
|
1879
|
+
throw error;
|
|
1880
|
+
}
|
|
1881
|
+
const queue = new AsyncEventQueue();
|
|
1882
|
+
const result = createDeferred();
|
|
1883
|
+
const promptStarted = createDeferred();
|
|
1884
|
+
promptStarted.promise.catch(() => {});
|
|
1885
|
+
const sessionReady = createDeferred();
|
|
1886
|
+
sessionReady.promise.catch(() => {});
|
|
1887
|
+
let resultSettled = false;
|
|
1888
|
+
const state = {
|
|
1889
|
+
pendingCancel: false,
|
|
1890
|
+
turnActive: true,
|
|
1891
|
+
activeController: null
|
|
1892
|
+
};
|
|
1893
|
+
let streamClosed = false;
|
|
1894
|
+
const settleResult = (next) => {
|
|
1895
|
+
if (resultSettled) return;
|
|
1896
|
+
resultSettled = true;
|
|
1897
|
+
result.resolve(next);
|
|
1898
|
+
};
|
|
1899
|
+
const closeStream = () => {
|
|
1900
|
+
if (streamClosed) return;
|
|
1901
|
+
streamClosed = true;
|
|
1902
|
+
queue.clear();
|
|
1903
|
+
queue.close();
|
|
1904
|
+
};
|
|
1905
|
+
const requestCancel = async () => {
|
|
1906
|
+
if (state.activeController) return await state.activeController.requestCancelActivePrompt();
|
|
1907
|
+
if (!state.turnActive) return false;
|
|
1908
|
+
state.pendingCancel = true;
|
|
1909
|
+
return true;
|
|
1910
|
+
};
|
|
1911
|
+
const abortHandler = () => {
|
|
1912
|
+
requestCancel().catch(() => {});
|
|
1913
|
+
};
|
|
1914
|
+
if (input.signal && !input.signal.aborted) input.signal.addEventListener("abort", abortHandler, { once: true });
|
|
1915
|
+
this.queueSessionTask(input.handle.acpxRecordId ?? input.handle.sessionKey, async () => this.runRuntimeTurnTask({
|
|
1916
|
+
input,
|
|
1917
|
+
promptInput,
|
|
1918
|
+
queue,
|
|
1919
|
+
promptStarted,
|
|
1920
|
+
sessionReady,
|
|
1921
|
+
state,
|
|
1922
|
+
settleResult,
|
|
1923
|
+
abortHandler
|
|
1924
|
+
}), requestCancel);
|
|
1925
|
+
return {
|
|
1926
|
+
requestId: input.requestId,
|
|
1927
|
+
promptStarted: promptStarted.promise,
|
|
1928
|
+
events: queue.iterate(),
|
|
1929
|
+
result: result.promise,
|
|
1930
|
+
cancel: async () => {
|
|
1931
|
+
await requestCancel();
|
|
1932
|
+
},
|
|
1933
|
+
closeStream: async () => {
|
|
1934
|
+
closeStream();
|
|
1935
|
+
}
|
|
1936
|
+
};
|
|
1937
|
+
}
|
|
1938
|
+
async closeRetainedOneShotHandle(handle) {
|
|
1939
|
+
const recordId = handle.acpxRecordId ?? handle.sessionKey;
|
|
1940
|
+
await this.serializeManagerOperation(this.runtimeOperationLocks, recordId, async () => {
|
|
1941
|
+
if (this.retainedSessionOwners.get(recordId)?.mode === "oneshot") await this.closeRetainedSessionOwner(recordId);
|
|
1942
|
+
});
|
|
1943
|
+
}
|
|
1944
|
+
async runRuntimeTurnTask(task) {
|
|
1945
|
+
let turn;
|
|
1946
|
+
let terminalResult;
|
|
1947
|
+
try {
|
|
1948
|
+
if (this.cancelRuntimeTurnBeforePrompt(task)) {
|
|
1949
|
+
await this.closeRetainedOneShotHandle(task.input.handle);
|
|
1950
|
+
terminalResult = {
|
|
1951
|
+
status: "cancelled",
|
|
1952
|
+
stopReason: "cancelled"
|
|
1953
|
+
};
|
|
1954
|
+
} else {
|
|
1955
|
+
turn = await this.prepareRuntimeTurn(task);
|
|
1956
|
+
const { sessionId } = await this.connectRuntimeTurn(task, turn);
|
|
1957
|
+
this.assertOpen();
|
|
1958
|
+
await this.resolveRuntimeTurnReady(task, turn);
|
|
1959
|
+
if (this.cancelRuntimeTurnBeforePrompt(task)) terminalResult = {
|
|
1960
|
+
status: "cancelled",
|
|
1961
|
+
stopReason: "cancelled"
|
|
1962
|
+
};
|
|
1963
|
+
else {
|
|
1964
|
+
const response = await this.runRuntimePrompt(task, turn, sessionId);
|
|
1965
|
+
this.updateCompletedRuntimeTurn(turn);
|
|
1966
|
+
terminalResult = this.completedRuntimeTurnResult(task, turn, response, response.stopReason === "cancelled" ? "cancelled" : "completed");
|
|
1967
|
+
}
|
|
1968
|
+
}
|
|
1969
|
+
} catch (error) {
|
|
1970
|
+
terminalResult = await this.handleRuntimeTurnFailure(task, turn, error);
|
|
1971
|
+
}
|
|
1972
|
+
const finalization = await settleAttempt(async () => this.serializeManagerOperation(this.runtimeOperationLocks, task.input.handle.acpxRecordId ?? task.input.handle.sessionKey, async () => this.finalizeRuntimeTurn(task, turn)));
|
|
1973
|
+
if (!finalization.ok) {
|
|
1974
|
+
task.settleResult(this.finalizationFailureResult(task, finalization.error));
|
|
1975
|
+
throw finalization.error;
|
|
1976
|
+
}
|
|
1977
|
+
task.settleResult(terminalResult);
|
|
1978
|
+
}
|
|
1979
|
+
/**
|
|
1980
|
+
* Finalization itself failed (e.g. checkpoint ENOSPC); skip the terminal
|
|
1981
|
+
* turn-results snapshot because that save would fail too.
|
|
1982
|
+
*/
|
|
1983
|
+
finalizationFailureResult(task, error) {
|
|
1984
|
+
task.promptStarted.reject(error);
|
|
1985
|
+
task.sessionReady.reject(error);
|
|
1986
|
+
const normalized = normalizeOutputError(error, { origin: "runtime" });
|
|
1987
|
+
return {
|
|
1988
|
+
status: "failed",
|
|
1989
|
+
error: {
|
|
1990
|
+
message: normalized.message,
|
|
1991
|
+
...normalized.code ? { code: normalized.code } : {},
|
|
1992
|
+
...normalized.detailCode ? { detailCode: normalized.detailCode } : {},
|
|
1993
|
+
...normalized.retryable !== void 0 ? { retryable: normalized.retryable } : {}
|
|
1994
|
+
}
|
|
1995
|
+
};
|
|
1996
|
+
}
|
|
1997
|
+
completedRuntimeTurnResult(_task, _turn, response, status) {
|
|
1998
|
+
return {
|
|
1999
|
+
status,
|
|
2000
|
+
...response.stopReason ? { stopReason: response.stopReason } : {},
|
|
2001
|
+
...response._meta === void 0 ? {} : { _meta: response._meta }
|
|
2002
|
+
};
|
|
2003
|
+
}
|
|
2004
|
+
async runRuntimePrompt(task, turn, sessionId) {
|
|
2005
|
+
return await runPromptTurn({
|
|
2006
|
+
client: turn.client,
|
|
2007
|
+
sessionId,
|
|
2008
|
+
prompt: task.promptInput,
|
|
2009
|
+
timeoutMs: task.input.timeoutMs ?? this.options.timeoutMs,
|
|
2010
|
+
conversation: turn.conversation,
|
|
2011
|
+
promptMessageId: turn.promptMessageId,
|
|
2012
|
+
onPromptRequestWritten: () => task.promptStarted.resolve(),
|
|
2013
|
+
onElicitation: task.input.onElicitation,
|
|
2014
|
+
onPermissionRequest: task.input.onPermissionRequest,
|
|
2015
|
+
authority: task.input
|
|
2016
|
+
});
|
|
2017
|
+
}
|
|
2018
|
+
async prepareRuntimeTurn(task) {
|
|
2019
|
+
const recordId = task.input.handle.acpxRecordId ?? task.input.handle.sessionKey;
|
|
2020
|
+
return await this.withManagerLock(this.runtimeOperationLocks, recordId, async () => {
|
|
2021
|
+
await this.retrySessionCleanup(recordId);
|
|
2022
|
+
return await this.prepareRuntimeTurnWithOwnership(task);
|
|
2023
|
+
});
|
|
2024
|
+
}
|
|
2025
|
+
async prepareRuntimeTurnWithOwnership(task) {
|
|
2026
|
+
const { record, retainedOwner, conversation, acpxState, promptMessageId } = await this.prepareRuntimeTurnState(task);
|
|
2027
|
+
try {
|
|
2028
|
+
const client = retainedOwner?.client ?? this.createTurnClient(record);
|
|
2029
|
+
const owner = this.resolveRuntimeTurnOwner(task, record, client, retainedOwner);
|
|
2030
|
+
const turn = this.createRunningRuntimeTurn({
|
|
2031
|
+
record,
|
|
2032
|
+
conversation,
|
|
2033
|
+
acpxState,
|
|
2034
|
+
client,
|
|
2035
|
+
owner,
|
|
2036
|
+
connected: retainedOwner !== void 0,
|
|
2037
|
+
promptMessageId
|
|
2038
|
+
});
|
|
2039
|
+
this.activateRuntimeTurn(task, turn);
|
|
2040
|
+
return turn;
|
|
2041
|
+
} catch (error) {
|
|
2042
|
+
this.restoreBufferedSessionOwner(retainedOwner);
|
|
2043
|
+
throw error;
|
|
2044
|
+
}
|
|
2045
|
+
}
|
|
2046
|
+
async prepareRuntimeTurnState(task) {
|
|
2047
|
+
const { record, retainedOwner } = await this.acquireRuntimeTurnState(task);
|
|
2048
|
+
const conversation = cloneSessionConversation(record);
|
|
2049
|
+
const acpxState = cloneSessionAcpxState(record.acpx);
|
|
2050
|
+
try {
|
|
2051
|
+
const promptStartedAt = isoNow();
|
|
2052
|
+
const promptMessageId = recordPromptSubmission(conversation, task.promptInput, promptStartedAt, task.input.requestId);
|
|
2053
|
+
trimConversationForRuntime(conversation);
|
|
2054
|
+
const nextAcpxState = cloneSessionAcpxState(acpxState) ?? {};
|
|
2055
|
+
nextAcpxState.turn_results = {
|
|
2056
|
+
...nextAcpxState.turn_results,
|
|
2057
|
+
[task.input.requestId]: {
|
|
2058
|
+
status: "running",
|
|
2059
|
+
prompt_message_id: promptMessageId ?? task.input.requestId,
|
|
2060
|
+
started_at: promptStartedAt
|
|
2061
|
+
}
|
|
2062
|
+
};
|
|
2063
|
+
record.lastRequestId = task.input.requestId;
|
|
2064
|
+
record.lastPromptAt = promptStartedAt;
|
|
2065
|
+
record.lastUsedAt = promptStartedAt;
|
|
2066
|
+
record.acpx = nextAcpxState;
|
|
2067
|
+
applyConversation(record, conversation);
|
|
2068
|
+
await this.options.sessionStore.save(record);
|
|
2069
|
+
return {
|
|
2070
|
+
record,
|
|
2071
|
+
retainedOwner,
|
|
2072
|
+
conversation,
|
|
2073
|
+
acpxState: nextAcpxState,
|
|
2074
|
+
promptMessageId
|
|
2075
|
+
};
|
|
2076
|
+
} catch (error) {
|
|
2077
|
+
this.restoreBufferedSessionOwner(retainedOwner);
|
|
2078
|
+
throw error;
|
|
2079
|
+
}
|
|
2080
|
+
}
|
|
2081
|
+
async acquireRuntimeTurnState(task) {
|
|
2082
|
+
const recordId = task.input.handle.acpxRecordId ?? task.input.handle.sessionKey;
|
|
2083
|
+
let record = await this.requireRecord(recordId);
|
|
2084
|
+
const retainedOwner = await this.readRetainedSessionOwner(record, { consume: false });
|
|
2085
|
+
if (!retainedOwner) return { record };
|
|
2086
|
+
retainedOwner.bufferSessionUpdates = true;
|
|
2087
|
+
try {
|
|
2088
|
+
await retainedOwner.checkpoint.flush();
|
|
2089
|
+
const projection = retainedOwner.projection;
|
|
2090
|
+
if (projection) record = structuredClone(projection.record);
|
|
2091
|
+
return {
|
|
2092
|
+
record,
|
|
2093
|
+
retainedOwner
|
|
2094
|
+
};
|
|
2095
|
+
} catch (error) {
|
|
2096
|
+
this.restoreBufferedSessionOwner(retainedOwner);
|
|
2097
|
+
throw error;
|
|
2098
|
+
}
|
|
2099
|
+
}
|
|
2100
|
+
restoreBufferedSessionOwner(owner) {
|
|
2101
|
+
if (!owner) return;
|
|
2102
|
+
owner.bufferSessionUpdates = false;
|
|
2103
|
+
this.drainPendingSessionUpdates(owner);
|
|
2104
|
+
}
|
|
2105
|
+
resolveRuntimeTurnOwner(task, record, client, retainedOwner) {
|
|
2106
|
+
return retainedOwner ?? this.createSessionOwner({
|
|
2107
|
+
client,
|
|
2108
|
+
sessionKey: record.name ?? task.input.handle.sessionKey,
|
|
2109
|
+
mode: task.input.sessionMode
|
|
2110
|
+
});
|
|
2111
|
+
}
|
|
2112
|
+
createRunningRuntimeTurn(input) {
|
|
2113
|
+
const { record, conversation, acpxState, client, owner, connected, promptMessageId } = input;
|
|
2114
|
+
return {
|
|
2115
|
+
record,
|
|
2116
|
+
conversation,
|
|
2117
|
+
acpxState,
|
|
2118
|
+
client,
|
|
2119
|
+
owner,
|
|
2120
|
+
connected,
|
|
2121
|
+
promptMessageId,
|
|
2122
|
+
activeSessionId: record.acpSessionId
|
|
2123
|
+
};
|
|
2124
|
+
}
|
|
2125
|
+
activateRuntimeTurn(task, turn) {
|
|
2126
|
+
const { owner, record } = turn;
|
|
2127
|
+
this.removeRetainedSessionOwner(owner);
|
|
2128
|
+
owner.recordId = record.acpxRecordId;
|
|
2129
|
+
task.state.activeController = this.buildRuntimeTurnController(task, turn);
|
|
2130
|
+
this.activeControllers.set(record.acpxRecordId, task.state.activeController);
|
|
2131
|
+
owner.projection = void 0;
|
|
2132
|
+
owner.activeTurn = {
|
|
2133
|
+
task,
|
|
2134
|
+
turn
|
|
2135
|
+
};
|
|
2136
|
+
this.installActiveOwnerEventHandlers(owner);
|
|
2137
|
+
owner.bufferSessionUpdates = false;
|
|
2138
|
+
this.drainPendingSessionUpdates(owner);
|
|
2139
|
+
}
|
|
2140
|
+
createTurnClient(record) {
|
|
2141
|
+
return this.createClient({
|
|
2142
|
+
agentCommand: record.agentCommand,
|
|
2143
|
+
agentArgv: record.agentArgv,
|
|
2144
|
+
cwd: record.cwd,
|
|
2145
|
+
mcpServers: this.resolveMcpServers({
|
|
2146
|
+
...record,
|
|
2147
|
+
sessionKey: record.name ?? record.acpxRecordId
|
|
2148
|
+
}),
|
|
2149
|
+
...this.resolveSessionPermissions({
|
|
2150
|
+
...record,
|
|
2151
|
+
sessionKey: record.name ?? record.acpxRecordId
|
|
2152
|
+
}),
|
|
2153
|
+
...this.resolveClientCapabilities(),
|
|
2154
|
+
elicitationModes: this.options.elicitationModes,
|
|
2155
|
+
processLifecycle: this.options.processLifecycle,
|
|
2156
|
+
processLaunchScope: {
|
|
2157
|
+
kind: "runtime-session",
|
|
2158
|
+
sessionKey: record.name ?? record.acpxRecordId
|
|
2159
|
+
},
|
|
2160
|
+
verbose: this.options.verbose,
|
|
2161
|
+
sessionOptions: sessionOptionsFromRecord(record)
|
|
2162
|
+
});
|
|
2163
|
+
}
|
|
2164
|
+
buildRuntimeTurnController(task, turn) {
|
|
2165
|
+
return {
|
|
2166
|
+
hasActivePrompt: () => turn.client.hasActivePrompt(),
|
|
2167
|
+
requestCancelActivePrompt: async () => await this.requestRuntimeTurnCancel(task, turn),
|
|
2168
|
+
setSessionMode: async (modeId, authority) => {
|
|
2169
|
+
await this.waitForRuntimeControlSession(task, turn);
|
|
2170
|
+
await turn.client.setSessionMode(turn.activeSessionId, modeId, authority);
|
|
2171
|
+
const nextState = cloneSessionAcpxState(turn.acpxState) ?? {};
|
|
2172
|
+
nextState.desired_mode_id = modeId;
|
|
2173
|
+
turn.acpxState = nextState;
|
|
2174
|
+
await turn.owner.checkpoint.checkpoint();
|
|
2175
|
+
},
|
|
2176
|
+
setSessionModel: async (modelId, authority) => {
|
|
2177
|
+
await this.waitForRuntimeControlSession(task, turn);
|
|
2178
|
+
const models = advertisedModelState(turn.acpxState);
|
|
2179
|
+
const resolvedModelId = resolveRequestedModelId({
|
|
2180
|
+
requestedModel: modelId,
|
|
2181
|
+
models,
|
|
2182
|
+
agentCommand: turn.record.agentCommand
|
|
2183
|
+
});
|
|
2184
|
+
const response = await turn.client.setSessionModel(turn.activeSessionId, modelId, models, authority);
|
|
2185
|
+
turn.acpxState = applyModelSelection(turn.acpxState, modelId, response, resolvedModelId);
|
|
2186
|
+
await turn.owner.checkpoint.checkpoint();
|
|
2187
|
+
return response;
|
|
2188
|
+
},
|
|
2189
|
+
setSessionConfigOption: async (configId, value, authority) => {
|
|
2190
|
+
return (await task.state.activeController.setResolvedSessionConfigOption(configId, value, authority)).response;
|
|
2191
|
+
},
|
|
2192
|
+
setResolvedSessionConfigOption: async (configId, value, authority) => await this.setRuntimeResolvedSessionConfigOption(task, turn, configId, value, authority)
|
|
2193
|
+
};
|
|
2194
|
+
}
|
|
2195
|
+
async waitForRuntimeControlSession(task, turn) {
|
|
2196
|
+
if (turn.client.hasActivePrompt()) return;
|
|
2197
|
+
await task.sessionReady.promise;
|
|
2198
|
+
}
|
|
2199
|
+
async requestRuntimeTurnCancel(task, turn) {
|
|
2200
|
+
if (turn.client.hasActivePrompt()) return await turn.client.requestCancelActivePrompt();
|
|
2201
|
+
if (!task.state.turnActive) return false;
|
|
2202
|
+
task.state.pendingCancel = true;
|
|
2203
|
+
return true;
|
|
2204
|
+
}
|
|
2205
|
+
async setRuntimeResolvedSessionConfigOption(task, turn, configId, value, authority) {
|
|
2206
|
+
await this.waitForRuntimeControlSession(task, turn);
|
|
2207
|
+
const resolvedConfigId = resolveSupportedConfigOptionId({
|
|
2208
|
+
...turn.record,
|
|
2209
|
+
acpx: turn.acpxState ?? void 0
|
|
2210
|
+
}, configId);
|
|
2211
|
+
const models = advertisedModelState(turn.acpxState);
|
|
2212
|
+
const { modelConfigId, resolvedValue } = resolveRequestedConfigOption({
|
|
2213
|
+
configId: resolvedConfigId,
|
|
2214
|
+
value,
|
|
2215
|
+
models,
|
|
2216
|
+
agentCommand: turn.record.agentCommand
|
|
2217
|
+
});
|
|
2218
|
+
const response = await turn.client.setSessionConfigOption(turn.activeSessionId, resolvedConfigId, value, models, authority);
|
|
2219
|
+
turn.acpxState = applyConfigOptionSelection(turn.acpxState, resolvedConfigId, value, response, modelConfigId, resolvedValue);
|
|
2220
|
+
await turn.owner.checkpoint.checkpoint();
|
|
2221
|
+
return {
|
|
2222
|
+
configId: resolvedConfigId,
|
|
2223
|
+
response
|
|
2224
|
+
};
|
|
2225
|
+
}
|
|
2226
|
+
emitRuntimeTurnEvent(task, payload) {
|
|
2227
|
+
const parsed = parsePromptEventLine(JSON.stringify(payload));
|
|
2228
|
+
if (!parsed) return;
|
|
2229
|
+
task.queue.push(parsed);
|
|
2230
|
+
}
|
|
2231
|
+
async connectRuntimeTurn(task, turn) {
|
|
2232
|
+
if (turn.connected) return {
|
|
2233
|
+
sessionId: turn.record.acpSessionId,
|
|
2234
|
+
resumed: false,
|
|
2235
|
+
loadError: void 0
|
|
2236
|
+
};
|
|
2237
|
+
const loaded = await this.connectRuntimeTurnClient(task, turn);
|
|
2238
|
+
turn.acpxState = cloneSessionAcpxState(turn.record.acpx);
|
|
2239
|
+
turn.connected = true;
|
|
2240
|
+
return loaded;
|
|
2241
|
+
}
|
|
2242
|
+
async connectRuntimeTurnClient(task, turn) {
|
|
2243
|
+
return await connectAndLoadSession({
|
|
2244
|
+
client: turn.client,
|
|
2245
|
+
record: turn.record,
|
|
2246
|
+
resumePolicy: resumePolicyForSessionMode(task.input.sessionMode),
|
|
2247
|
+
timeoutMs: this.options.timeoutMs,
|
|
2248
|
+
activeController: task.state.activeController,
|
|
2249
|
+
onClientAvailable: () => this.publishRuntimeTurnController(task, turn),
|
|
2250
|
+
onConnectedRecord: (connectedRecord) => {
|
|
2251
|
+
connectedRecord.lastPromptAt = isoNow();
|
|
2252
|
+
},
|
|
2253
|
+
onSessionIdResolved: (sessionIdValue) => {
|
|
2254
|
+
turn.activeSessionId = sessionIdValue;
|
|
2255
|
+
}
|
|
2256
|
+
});
|
|
2257
|
+
}
|
|
2258
|
+
publishRuntimeTurnController(task, turn) {
|
|
2259
|
+
const controller = task.state.activeController;
|
|
2260
|
+
if (controller) this.activeControllers.set(turn.record.acpxRecordId, controller);
|
|
2261
|
+
}
|
|
2262
|
+
async resolveRuntimeTurnReady(task, turn) {
|
|
2263
|
+
task.sessionReady.resolve();
|
|
2264
|
+
turn.record.lastRequestId = task.input.requestId;
|
|
2265
|
+
turn.record.lastPromptAt = isoNow();
|
|
2266
|
+
turn.record.closed = false;
|
|
2267
|
+
turn.record.closedAt = void 0;
|
|
2268
|
+
turn.record.lastUsedAt = isoNow();
|
|
2269
|
+
await turn.owner.checkpoint.checkpoint();
|
|
2270
|
+
}
|
|
2271
|
+
cancelRuntimeTurnBeforePrompt(task) {
|
|
2272
|
+
if (!task.state.pendingCancel && !task.input.signal?.aborted) return false;
|
|
2273
|
+
task.state.pendingCancel = false;
|
|
2274
|
+
task.promptStarted.reject(/* @__PURE__ */ new Error("ACP turn cancelled before prompt submission."));
|
|
2275
|
+
return true;
|
|
2276
|
+
}
|
|
2277
|
+
updateCompletedRuntimeTurn(turn) {
|
|
2278
|
+
turn.record.acpSessionId = turn.activeSessionId;
|
|
2279
|
+
reconcileAgentSessionId(turn.record, turn.record.agentSessionId);
|
|
2280
|
+
turn.record.protocolVersion = turn.client.initializeResult?.protocolVersion;
|
|
2281
|
+
turn.record.agentCapabilities = turn.client.initializeResult?.agentCapabilities;
|
|
2282
|
+
}
|
|
2283
|
+
async handleRuntimeTurnFailure(task, turn, error) {
|
|
2284
|
+
if (!task.input.signal?.aborted || error !== task.input.signal.reason) return await this.failRuntimeTurn(task, turn, error);
|
|
2285
|
+
task.promptStarted.reject(error);
|
|
2286
|
+
task.sessionReady.reject(error);
|
|
2287
|
+
return {
|
|
2288
|
+
status: "cancelled",
|
|
2289
|
+
stopReason: "cancelled"
|
|
2290
|
+
};
|
|
2291
|
+
}
|
|
2292
|
+
async saveCompletedRuntimeTurn(turn) {
|
|
2293
|
+
turn.record.acpSessionId = turn.activeSessionId;
|
|
2294
|
+
reconcileAgentSessionId(turn.record, turn.record.agentSessionId);
|
|
2295
|
+
turn.record.protocolVersion = turn.client.initializeResult?.protocolVersion;
|
|
2296
|
+
turn.record.agentCapabilities = turn.client.initializeResult?.agentCapabilities;
|
|
2297
|
+
turn.record.acpx = turn.acpxState;
|
|
2298
|
+
applyConversation(turn.record, turn.conversation);
|
|
2299
|
+
applyLifecycleSnapshotToRecord(turn.record, turn.client.getAgentLifecycleSnapshot());
|
|
2300
|
+
await this.options.sessionStore.save(turn.record);
|
|
2301
|
+
}
|
|
2302
|
+
async saveTerminalRuntimeTurn(turn, status, stopReason, errorCode) {
|
|
2303
|
+
applyTerminalTurnSnapshot(turn, status, stopReason, errorCode, isoNow());
|
|
2304
|
+
await this.saveCompletedRuntimeTurn(turn);
|
|
2305
|
+
}
|
|
2306
|
+
async failRuntimeTurn(task, turn, error) {
|
|
2307
|
+
task.promptStarted.reject(error);
|
|
2308
|
+
task.sessionReady.reject(error);
|
|
2309
|
+
const normalized = normalizeOutputError(error, { origin: "runtime" });
|
|
2310
|
+
if (turn) await this.saveTerminalRuntimeTurn(turn, "failed", "runtime_error", normalized.code ?? normalized.detailCode).catch(() => {});
|
|
2311
|
+
return {
|
|
2312
|
+
status: "failed",
|
|
2313
|
+
error: {
|
|
2314
|
+
message: normalized.message,
|
|
2315
|
+
...normalized.code ? { code: normalized.code } : {},
|
|
2316
|
+
...normalized.detailCode ? { detailCode: normalized.detailCode } : {},
|
|
2317
|
+
...normalized.retryable !== void 0 ? { retryable: normalized.retryable } : {}
|
|
2318
|
+
}
|
|
2319
|
+
};
|
|
2320
|
+
}
|
|
2321
|
+
async finalizeRuntimeTurn(task, turn) {
|
|
2322
|
+
task.state.turnActive = false;
|
|
2323
|
+
const abortHandlerAttempt = await settleAttempt(() => task.input.signal?.removeEventListener("abort", task.abortHandler));
|
|
2324
|
+
const recordAttempt = await settleAttempt(async () => turn ? await this.finalizeRuntimeTurnRecord(turn) : false);
|
|
2325
|
+
let failure = firstFailedAttempt([abortHandlerAttempt, recordAttempt]);
|
|
2326
|
+
let pooled = recordAttempt.ok ? recordAttempt.value : false;
|
|
2327
|
+
if (failure) {
|
|
2328
|
+
this.discardRetainedRuntimeTurnOwner(turn);
|
|
2329
|
+
pooled = false;
|
|
2330
|
+
}
|
|
2331
|
+
const closeAttempt = await settleAttempt(async () => this.closeRuntimeTurnClient(turn, pooled));
|
|
2332
|
+
this.cleanupRuntimeTurn(task, turn);
|
|
2333
|
+
failure ??= firstFailedAttempt([closeAttempt]);
|
|
2334
|
+
if (failure) throw failure.error;
|
|
2335
|
+
}
|
|
2336
|
+
discardRetainedRuntimeTurnOwner(turn) {
|
|
2337
|
+
if (turn) {
|
|
2338
|
+
this.removeRetainedSessionOwner(turn.owner);
|
|
2339
|
+
this.attachFinalRuntimeProjection(turn);
|
|
2340
|
+
}
|
|
2341
|
+
}
|
|
2342
|
+
attachFinalRuntimeProjection(turn) {
|
|
2343
|
+
const current = turn.connected ? turn.acpxState : turn.record.acpx;
|
|
2344
|
+
const state = turn.record.acpx?.reset_on_next_ensure === true ? {
|
|
2345
|
+
...current,
|
|
2346
|
+
reset_on_next_ensure: true
|
|
2347
|
+
} : current;
|
|
2348
|
+
this.attachIdleProjection(turn.owner, turn.record, turn.conversation, state);
|
|
2349
|
+
}
|
|
2350
|
+
async closeRuntimeTurnClient(turn, pooled) {
|
|
2351
|
+
if (!turn || pooled) return;
|
|
2352
|
+
const failure = firstFailedAttempt([
|
|
2353
|
+
await settleAttempt(() => turn.client.clearEventHandlers()),
|
|
2354
|
+
await settleAttempt(async () => this.closeClient(turn.client)),
|
|
2355
|
+
await settleAttempt(async () => this.flushSessionOwner(turn.owner))
|
|
2356
|
+
]);
|
|
2357
|
+
if (failure) {
|
|
2358
|
+
this.retiringSessionOwners.add(turn.owner);
|
|
2359
|
+
throw failure.error;
|
|
2360
|
+
}
|
|
2361
|
+
}
|
|
2362
|
+
cleanupRuntimeTurn(task, turn) {
|
|
2363
|
+
if (turn) {
|
|
2364
|
+
this.activeControllers.delete(turn.record.acpxRecordId);
|
|
2365
|
+
this.closingActiveRecords.delete(turn.record.acpxRecordId);
|
|
2366
|
+
}
|
|
2367
|
+
task.queue.close();
|
|
2368
|
+
}
|
|
2369
|
+
async finalizeRuntimeTurnRecord(turn) {
|
|
2370
|
+
if (!turn.connected) turn.acpxState = cloneSessionAcpxState(turn.record.acpx);
|
|
2371
|
+
await turn.owner.checkpoint.checkpoint();
|
|
2372
|
+
this.attachFinalRuntimeProjection(turn);
|
|
2373
|
+
if (turn.record.closed || !turn.connected) return false;
|
|
2374
|
+
return await this.retainPersistentSessionOwnerAfterTurn({
|
|
2375
|
+
record: turn.record,
|
|
2376
|
+
owner: turn.owner
|
|
2377
|
+
});
|
|
2378
|
+
}
|
|
2379
|
+
async *runTurn(input) {
|
|
2380
|
+
const turn = this.startTurn(input);
|
|
2381
|
+
yield* turn.events;
|
|
2382
|
+
yield legacyTerminalEventFromTurnResult(await turn.result);
|
|
2383
|
+
}
|
|
2384
|
+
getStatus(handle) {
|
|
2385
|
+
this.assertOpen();
|
|
2386
|
+
return this.trackTask(this.readStatus(handle));
|
|
2387
|
+
}
|
|
2388
|
+
async readStatus(handle) {
|
|
2389
|
+
const recordId = handle.acpxRecordId ?? handle.sessionKey;
|
|
2390
|
+
const owner = this.retainedSessionOwners.get(recordId);
|
|
2391
|
+
if (owner) await this.flushSessionOwner(owner);
|
|
2392
|
+
return runtimeStatusFromRecord(await this.requireRecord(recordId));
|
|
2393
|
+
}
|
|
2394
|
+
async setMode(handle, mode, sessionMode = "persistent", authority) {
|
|
2395
|
+
const recordId = handle.acpxRecordId ?? handle.sessionKey;
|
|
2396
|
+
await this.withManagerLock(this.runtimeOperationLocks, recordId, async () => this.setModeWithOwnership(handle, mode, sessionMode, authority), authority);
|
|
2397
|
+
}
|
|
2398
|
+
async setModeWithOwnership(handle, mode, sessionMode, authority) {
|
|
2399
|
+
const record = await this.requireRecord(handle.acpxRecordId ?? handle.sessionKey);
|
|
2400
|
+
assertControlAuthority(authority);
|
|
2401
|
+
const controller = this.activeControllers.get(record.acpxRecordId);
|
|
2402
|
+
if (controller) {
|
|
2403
|
+
await controller.setSessionMode(mode, authority);
|
|
2404
|
+
return;
|
|
2405
|
+
}
|
|
2406
|
+
await this.withRuntimeControlSession(record, sessionMode, async ({ client, sessionId, record: connectedRecord }) => {
|
|
2407
|
+
await client.setSessionMode(sessionId, mode, authority);
|
|
2408
|
+
setDesiredModeId(connectedRecord, mode);
|
|
2409
|
+
}, { replacingMode: true }, authority);
|
|
2410
|
+
}
|
|
2411
|
+
async setModel(handle, model, sessionMode = "persistent", authority) {
|
|
2412
|
+
const recordId = handle.acpxRecordId ?? handle.sessionKey;
|
|
2413
|
+
await this.withManagerLock(this.runtimeOperationLocks, recordId, async () => this.setModelWithOwnership(handle, model, sessionMode, authority), authority);
|
|
2414
|
+
}
|
|
2415
|
+
async setModelWithOwnership(handle, model, sessionMode, authority) {
|
|
2416
|
+
const record = await this.requireRecord(handle.acpxRecordId ?? handle.sessionKey);
|
|
2417
|
+
assertControlAuthority(authority);
|
|
2418
|
+
const controller = this.activeControllers.get(record.acpxRecordId);
|
|
2419
|
+
if (controller) {
|
|
2420
|
+
await controller.setSessionModel(model, authority);
|
|
2421
|
+
return;
|
|
2422
|
+
}
|
|
2423
|
+
await this.withRuntimeControlSession(record, sessionMode, async ({ client, sessionId, record: connectedRecord }) => {
|
|
2424
|
+
const models = advertisedModelState(connectedRecord.acpx);
|
|
2425
|
+
const resolvedModelId = resolveRequestedModelId({
|
|
2426
|
+
requestedModel: model,
|
|
2427
|
+
models,
|
|
2428
|
+
agentCommand: connectedRecord.agentCommand
|
|
2429
|
+
});
|
|
2430
|
+
const response = await client.setSessionModel(sessionId, model, models, authority);
|
|
2431
|
+
connectedRecord.acpx = applyModelSelection(connectedRecord.acpx, model, response, resolvedModelId);
|
|
2432
|
+
}, { replacingConfigOption: { key: "model" } }, authority);
|
|
2433
|
+
}
|
|
2434
|
+
async setConfigOption(handle, key, value, sessionMode = "persistent", authority) {
|
|
2435
|
+
const recordId = handle.acpxRecordId ?? handle.sessionKey;
|
|
2436
|
+
return await this.withManagerLock(this.runtimeOperationLocks, recordId, async () => this.setConfigOptionWithOwnership(handle, key, value, sessionMode, authority), authority);
|
|
2437
|
+
}
|
|
2438
|
+
async setConfigOptionWithOwnership(handle, key, value, sessionMode, authority) {
|
|
2439
|
+
const record = await this.requireRecord(handle.acpxRecordId ?? handle.sessionKey);
|
|
2440
|
+
assertControlAuthority(authority);
|
|
2441
|
+
const controller = this.activeControllers.get(record.acpxRecordId);
|
|
2442
|
+
if (controller) {
|
|
2443
|
+
const { response } = await controller.setResolvedSessionConfigOption(key, value, authority);
|
|
2444
|
+
return response;
|
|
2445
|
+
}
|
|
2446
|
+
return await this.withRuntimeControlSession(record, sessionMode, async ({ client, sessionId, record: connectedRecord }) => {
|
|
2447
|
+
const configId = resolveSupportedConfigOptionId(connectedRecord, key);
|
|
2448
|
+
const models = advertisedModelState(connectedRecord.acpx);
|
|
2449
|
+
const { modelConfigId, resolvedValue } = resolveRequestedConfigOption({
|
|
2450
|
+
configId,
|
|
2451
|
+
value,
|
|
2452
|
+
models,
|
|
2453
|
+
agentCommand: connectedRecord.agentCommand
|
|
2454
|
+
});
|
|
2455
|
+
const response = await client.setSessionConfigOption(sessionId, configId, value, models, authority);
|
|
2456
|
+
connectedRecord.acpx = applyConfigOptionSelection(connectedRecord.acpx, configId, value, response, modelConfigId, resolvedValue);
|
|
2457
|
+
return response;
|
|
2458
|
+
}, { replacingConfigOption: {
|
|
2459
|
+
key,
|
|
2460
|
+
resolve: (connectedRecord) => resolveSupportedConfigOptionId(connectedRecord, key)
|
|
2461
|
+
} }, authority);
|
|
2462
|
+
}
|
|
2463
|
+
async logoutSession(input) {
|
|
2464
|
+
const record = await this.requireRecord(input.handle.acpxRecordId ?? input.handle.sessionKey);
|
|
2465
|
+
await this.withRuntimeControlSession(record, "persistent", async ({ client }) => {
|
|
2466
|
+
await client.logout();
|
|
2467
|
+
});
|
|
2468
|
+
}
|
|
2469
|
+
async authenticateSession(input) {
|
|
2470
|
+
const record = await this.requireRecord(input.handle.acpxRecordId ?? input.handle.sessionKey);
|
|
2471
|
+
await this.withRuntimeControlSession(record, "persistent", async ({ client }) => {
|
|
2472
|
+
await client.authenticate(input.methodId, input.credentials);
|
|
2473
|
+
});
|
|
2474
|
+
}
|
|
2475
|
+
async forkSession(input) {
|
|
2476
|
+
const record = await this.requireRecord(input.handle.acpxRecordId ?? input.handle.sessionKey);
|
|
2477
|
+
if (!record.agentCapabilities?.sessionCapabilities?.fork) throw new Error("capability_unsupported");
|
|
2478
|
+
const result = await this.withRuntimeControlSession(record, "persistent", async ({ client }) => {
|
|
2479
|
+
return await client.forkSession({
|
|
2480
|
+
sessionId: record.acpSessionId,
|
|
2481
|
+
cwd: input.cwd
|
|
2482
|
+
});
|
|
2483
|
+
});
|
|
2484
|
+
const newRecord = {
|
|
2485
|
+
...record,
|
|
2486
|
+
acpxRecordId: result.sessionId,
|
|
2487
|
+
acpSessionId: result.agentSessionId || result.sessionId,
|
|
2488
|
+
agentSessionId: result.agentSessionId,
|
|
2489
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2490
|
+
lastUsedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2491
|
+
updated_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2492
|
+
messages: [...record.messages],
|
|
2493
|
+
name: `${record.name || record.acpxRecordId} (Fork)`
|
|
2494
|
+
};
|
|
2495
|
+
await this.options.sessionStore.save(newRecord);
|
|
2496
|
+
return result;
|
|
2497
|
+
}
|
|
2498
|
+
async deleteSession(input) {
|
|
2499
|
+
const record = await this.requireRecord(input.handle.acpxRecordId ?? input.handle.sessionKey);
|
|
2500
|
+
if (!record.agentCapabilities?.sessionCapabilities?.delete) throw new Error("capability_unsupported");
|
|
2501
|
+
await this.withRuntimeControlSession(record, "persistent", async ({ client }) => {
|
|
2502
|
+
await client.deleteSession(record.acpSessionId);
|
|
2503
|
+
});
|
|
2504
|
+
record.closed = true;
|
|
2505
|
+
record.closedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
2506
|
+
await this.options.sessionStore.save(record);
|
|
2507
|
+
}
|
|
2508
|
+
async cancel(handle) {
|
|
2509
|
+
await this.activeControllers.get(handle.acpxRecordId ?? handle.sessionKey)?.requestCancelActivePrompt();
|
|
2510
|
+
}
|
|
2511
|
+
prepareFreshSession(handle) {
|
|
2512
|
+
this.assertOpen();
|
|
2513
|
+
const recordId = handle.acpxRecordId ?? handle.sessionKey;
|
|
2514
|
+
const cancelled = this.cancelSessionTasks(recordId);
|
|
2515
|
+
cancelled.catch(() => {});
|
|
2516
|
+
return this.queueSessionTask(recordId, async () => {
|
|
2517
|
+
const tasks = await cancelled;
|
|
2518
|
+
await Promise.all(tasks.map((task) => task.completion));
|
|
2519
|
+
return await this.withManagerLock(this.runtimeOperationLocks, recordId, async () => this.closeRuntimeSession(handle, "prepare-fresh"));
|
|
2520
|
+
});
|
|
2521
|
+
}
|
|
2522
|
+
close(handle, options = {}) {
|
|
2523
|
+
this.assertOpen();
|
|
2524
|
+
const recordId = handle.acpxRecordId ?? handle.sessionKey;
|
|
2525
|
+
return this.trackTask(this.withManagerLock(this.runtimeOperationLocks, recordId, async () => {
|
|
2526
|
+
return await this.closeRuntimeSession(handle, options.discardPersistentState === true ? "discard" : "release");
|
|
2527
|
+
}));
|
|
2528
|
+
}
|
|
2529
|
+
async closeRuntimeSession(handle, intent) {
|
|
2530
|
+
const recordId = handle.acpxRecordId ?? handle.sessionKey;
|
|
2531
|
+
await this.retrySessionCleanup(recordId);
|
|
2532
|
+
const record = await this.resolveRuntimeRecordForClose(recordId);
|
|
2533
|
+
this.markActiveRuntimeRecordClosing(record);
|
|
2534
|
+
if (intent !== "prepare-fresh") await this.cancelSessionTasks(recordId);
|
|
2535
|
+
await this.closeRuntimeRecordOwnership(record, intent);
|
|
2536
|
+
record.closed = true;
|
|
2537
|
+
record.closedAt = isoNow();
|
|
2538
|
+
await this.options.sessionStore.save(record);
|
|
2539
|
+
this.transientCredentials.delete(record.acpxRecordId);
|
|
2540
|
+
}
|
|
2541
|
+
async adoptSession(input) {
|
|
2542
|
+
const sourceRecordId = input.handle.acpxRecordId ?? input.handle.sessionKey;
|
|
2543
|
+
const targetRecordId = input.sessionKey.trim();
|
|
2544
|
+
const sourceRecord = await this.requireRecord(sourceRecordId);
|
|
2545
|
+
if (sourceRecordId === targetRecordId) return sourceRecord;
|
|
2546
|
+
const rebind = this.requireSessionStoreRebind();
|
|
2547
|
+
this.assertAdoptableSessionSource(sourceRecordId, targetRecordId);
|
|
2548
|
+
await this.assertAdoptionTargetAvailable(targetRecordId);
|
|
2549
|
+
const owner = this.retainedSessionOwners.get(sourceRecordId);
|
|
2550
|
+
if (owner) await this.flushSessionOwner(owner);
|
|
2551
|
+
try {
|
|
2552
|
+
await this.assertAdoptionTargetAvailable(targetRecordId);
|
|
2553
|
+
const now = isoNow();
|
|
2554
|
+
const adoptedRecord = {
|
|
2555
|
+
...sourceRecord,
|
|
2556
|
+
acpxRecordId: targetRecordId,
|
|
2557
|
+
name: targetRecordId,
|
|
2558
|
+
lastUsedAt: now,
|
|
2559
|
+
updated_at: now,
|
|
2560
|
+
eventLog: {
|
|
2561
|
+
...sourceRecord.eventLog,
|
|
2562
|
+
active_path: defaultSessionEventLog(targetRecordId).active_path
|
|
2563
|
+
}
|
|
2564
|
+
};
|
|
2565
|
+
await rebind(sourceRecordId, adoptedRecord);
|
|
2566
|
+
this.moveAdoptedManagerState(sourceRecordId, targetRecordId, owner);
|
|
2567
|
+
return adoptedRecord;
|
|
2568
|
+
} catch (error) {
|
|
2569
|
+
throw error instanceof AcpRuntimeError ? error : new AcpRuntimeError("ACP_SESSION_INIT_FAILED", `Failed to adopt ACP session ${sourceRecordId} as ${targetRecordId}.`, { cause: error });
|
|
2570
|
+
}
|
|
2571
|
+
}
|
|
2572
|
+
requireSessionStoreRebind() {
|
|
2573
|
+
if (!this.options.sessionStore.rebind) throw new AcpRuntimeError("ACP_SESSION_INIT_FAILED", "The configured ACP session store does not support session adoption.");
|
|
2574
|
+
return async (sourceSessionId, record) => {
|
|
2575
|
+
await this.options.sessionStore.rebind(sourceSessionId, record);
|
|
2576
|
+
};
|
|
2577
|
+
}
|
|
2578
|
+
assertAdoptableSessionSource(sourceRecordId, targetRecordId) {
|
|
2579
|
+
if (!targetRecordId) throw new AcpRuntimeError("ACP_SESSION_INIT_FAILED", "ACP session key is required.");
|
|
2580
|
+
if (sourceRecordId.includes(":oneshot:")) throw new AcpRuntimeError("ACP_SESSION_INIT_FAILED", `Cannot adopt one-shot ACP session ${sourceRecordId}.`);
|
|
2581
|
+
}
|
|
2582
|
+
async assertAdoptionTargetAvailable(targetRecordId) {
|
|
2583
|
+
const existing = await this.options.sessionStore.load(targetRecordId);
|
|
2584
|
+
if (existing && !existing.closed) throw new AcpRuntimeError("ACP_SESSION_INIT_FAILED", `ACP session already exists: ${targetRecordId}`);
|
|
2585
|
+
}
|
|
2586
|
+
moveAdoptedManagerState(sourceRecordId, targetRecordId, owner) {
|
|
2587
|
+
if (owner) {
|
|
2588
|
+
owner.sessionKey = targetRecordId;
|
|
2589
|
+
owner.recordId = targetRecordId;
|
|
2590
|
+
if (owner.projection) {
|
|
2591
|
+
owner.projection.record.acpxRecordId = targetRecordId;
|
|
2592
|
+
owner.projection.record.name = targetRecordId;
|
|
2593
|
+
}
|
|
2594
|
+
this.retainedSessionOwners.delete(sourceRecordId);
|
|
2595
|
+
this.retainedSessionOwners.set(targetRecordId, owner);
|
|
2596
|
+
}
|
|
2597
|
+
const creds = this.transientCredentials.get(sourceRecordId);
|
|
2598
|
+
if (creds) {
|
|
2599
|
+
this.transientCredentials.delete(sourceRecordId);
|
|
2600
|
+
this.transientCredentials.set(targetRecordId, creds);
|
|
2601
|
+
}
|
|
2602
|
+
}
|
|
2603
|
+
async resolveRuntimeRecordForClose(recordId) {
|
|
2604
|
+
const retainedOwner = this.retainedSessionOwners.get(recordId);
|
|
2605
|
+
if (retainedOwner) await this.flushSessionOwner(retainedOwner);
|
|
2606
|
+
return retainedOwner?.projection?.record ?? await this.requireRecord(recordId);
|
|
2607
|
+
}
|
|
2608
|
+
markActiveRuntimeRecordClosing(record) {
|
|
2609
|
+
if (this.activeControllers.has(record.acpxRecordId)) this.closingActiveRecords.add(record.acpxRecordId);
|
|
2610
|
+
}
|
|
2611
|
+
async closeRuntimeRecordOwnership(record, intent) {
|
|
2612
|
+
if (intent === "discard") await this.closeBackendSession(record);
|
|
2613
|
+
else if (intent === "prepare-fresh") {
|
|
2614
|
+
const owner = this.retainedSessionOwners.get(record.acpxRecordId);
|
|
2615
|
+
if (owner) {
|
|
2616
|
+
this.removeRetainedSessionOwner(owner);
|
|
2617
|
+
this.retiringSessionOwners.add(owner);
|
|
2618
|
+
}
|
|
2619
|
+
await this.retrySessionCleanup(record.acpxRecordId);
|
|
2620
|
+
} else await this.closeRetainedSessionOwner(record.acpxRecordId);
|
|
2621
|
+
if (intent !== "release") record.acpx = {
|
|
2622
|
+
...record.acpx,
|
|
2623
|
+
reset_on_next_ensure: true
|
|
2624
|
+
};
|
|
2625
|
+
}
|
|
2626
|
+
async closeBackendSession(record) {
|
|
2627
|
+
const connection = await this.acquireBackendCloseConnection(record);
|
|
2628
|
+
try {
|
|
2629
|
+
await this.requestBackendSessionClose(record, connection);
|
|
2630
|
+
} catch (error) {
|
|
2631
|
+
this.handleBackendSessionCloseError(record, error);
|
|
2632
|
+
} finally {
|
|
2633
|
+
await this.finalizeSessionConnection(connection);
|
|
2634
|
+
}
|
|
2635
|
+
}
|
|
2636
|
+
async finalizeSessionConnection(connection) {
|
|
2637
|
+
const failure = firstFailedAttempt([
|
|
2638
|
+
await settleAttempt(async () => {
|
|
2639
|
+
if (connection.owner) await this.flushSessionOwner(connection.owner);
|
|
2640
|
+
}),
|
|
2641
|
+
await settleAttempt(() => connection.owner?.client.clearEventHandlers()),
|
|
2642
|
+
await settleAttempt(async () => this.closeClient(connection.client)),
|
|
2643
|
+
await settleAttempt(async () => connection.owner?.checkpoint.flush())
|
|
2644
|
+
]);
|
|
2645
|
+
if (failure) throw failure.error;
|
|
2646
|
+
}
|
|
2647
|
+
async acquireBackendCloseConnection(record) {
|
|
2648
|
+
const owner = await this.readRetainedSessionOwner(record, { consume: true });
|
|
2649
|
+
if (owner) return {
|
|
2650
|
+
client: owner.client,
|
|
2651
|
+
owner
|
|
2652
|
+
};
|
|
2653
|
+
return { client: this.createTurnClient(record) };
|
|
2654
|
+
}
|
|
2655
|
+
async requestBackendSessionClose(record, connection) {
|
|
2656
|
+
if (!connection.owner) await withTimeout(connection.client.start(), this.options.timeoutMs);
|
|
2657
|
+
if (!connection.client.supportsCloseSession()) throw new AcpRuntimeError("ACP_BACKEND_UNSUPPORTED_CONTROL", `Agent does not support session/close for ${record.acpxRecordId}.`);
|
|
2658
|
+
await withTimeout(connection.client.closeSession(record.acpSessionId), this.options.timeoutMs);
|
|
2659
|
+
}
|
|
2660
|
+
handleBackendSessionCloseError(record, error) {
|
|
2661
|
+
if (isAcpResourceNotFoundError(error)) return;
|
|
2662
|
+
if (isUnsupportedSessionCloseError(error)) throw new AcpRuntimeError("ACP_BACKEND_UNSUPPORTED_CONTROL", `Agent does not support session/close for ${record.acpxRecordId}.`, { cause: error });
|
|
2663
|
+
throw error;
|
|
2664
|
+
}
|
|
2665
|
+
async requireRecord(sessionId) {
|
|
2666
|
+
const record = await this.options.sessionStore.load(sessionId);
|
|
2667
|
+
if (!record) throw new Error(`ACP session not found: ${sessionId}`);
|
|
2668
|
+
return record;
|
|
2669
|
+
}
|
|
2670
|
+
};
|
|
2671
|
+
function terminalPromptMessageId(turn, requestId) {
|
|
2672
|
+
return turn.promptMessageId ?? requestId;
|
|
2673
|
+
}
|
|
2674
|
+
function terminalStartedAt(turn, existing, completedAt) {
|
|
2675
|
+
return existing?.started_at ?? turn.record.lastPromptAt ?? completedAt;
|
|
2676
|
+
}
|
|
2677
|
+
function assignTerminalDetails(snapshot, stopReason, errorCode) {
|
|
2678
|
+
if (stopReason) snapshot.stop_reason = stopReason;
|
|
2679
|
+
if (errorCode) snapshot.error_code = errorCode;
|
|
2680
|
+
}
|
|
2681
|
+
function applyTerminalTurnSnapshot(turn, status, stopReason, errorCode, completedAt) {
|
|
2682
|
+
const requestId = turn.record.lastRequestId;
|
|
2683
|
+
if (!requestId) return;
|
|
2684
|
+
const nextState = cloneSessionAcpxState(turn.acpxState) ?? {};
|
|
2685
|
+
const existing = nextState.turn_results?.[requestId];
|
|
2686
|
+
const snapshot = {
|
|
2687
|
+
status,
|
|
2688
|
+
prompt_message_id: terminalPromptMessageId(turn, requestId),
|
|
2689
|
+
started_at: terminalStartedAt(turn, existing, completedAt),
|
|
2690
|
+
completed_at: completedAt
|
|
2691
|
+
};
|
|
2692
|
+
assignTerminalDetails(snapshot, stopReason, errorCode);
|
|
2693
|
+
nextState.turn_results = {
|
|
2694
|
+
...nextState.turn_results,
|
|
2695
|
+
[requestId]: snapshot
|
|
2696
|
+
};
|
|
2697
|
+
turn.acpxState = nextState;
|
|
2698
|
+
}
|
|
2699
|
+
//#endregion
|
|
2700
|
+
//#region src/runtime/public/file-session-store.ts
|
|
2701
|
+
function safeSessionId$1(sessionId) {
|
|
2702
|
+
return encodeURIComponent(sessionId);
|
|
2703
|
+
}
|
|
2704
|
+
var FileSessionStore = class {
|
|
2705
|
+
stateDir;
|
|
2706
|
+
constructor(stateDir) {
|
|
2707
|
+
this.stateDir = stateDir;
|
|
2708
|
+
}
|
|
2709
|
+
get sessionDir() {
|
|
2710
|
+
return path.join(this.stateDir, "sessions");
|
|
2711
|
+
}
|
|
2712
|
+
filePath(sessionId) {
|
|
2713
|
+
return path.join(this.sessionDir, `${safeSessionId$1(sessionId)}.json`);
|
|
2714
|
+
}
|
|
2715
|
+
async ensureDir() {
|
|
2716
|
+
await fs.mkdir(this.sessionDir, {
|
|
2717
|
+
recursive: true,
|
|
2718
|
+
mode: 448
|
|
2719
|
+
});
|
|
2720
|
+
}
|
|
2721
|
+
async load(sessionId) {
|
|
2722
|
+
await this.ensureDir();
|
|
2723
|
+
let payload;
|
|
2724
|
+
try {
|
|
2725
|
+
payload = await fs.readFile(this.filePath(sessionId), "utf8");
|
|
2726
|
+
} catch (error) {
|
|
2727
|
+
if (error.code === "ENOENT") return;
|
|
2728
|
+
throw error;
|
|
2729
|
+
}
|
|
2730
|
+
let parsed;
|
|
2731
|
+
try {
|
|
2732
|
+
parsed = JSON.parse(payload);
|
|
2733
|
+
} catch {
|
|
2734
|
+
return;
|
|
2735
|
+
}
|
|
2736
|
+
const record = parseSessionRecord(parsed);
|
|
2737
|
+
return record?.acpxRecordId === sessionId ? record : void 0;
|
|
2738
|
+
}
|
|
2739
|
+
async save(record) {
|
|
2740
|
+
const persisted = serializeSessionRecordForDisk(record);
|
|
2741
|
+
assertPersistedKeyPolicy(persisted);
|
|
2742
|
+
await writePrivateJsonFile(this.filePath(record.acpxRecordId), persisted);
|
|
2743
|
+
}
|
|
2744
|
+
async rebind(sourceSessionId, record) {
|
|
2745
|
+
await this.ensureDir();
|
|
2746
|
+
if (sourceSessionId === record.acpxRecordId) {
|
|
2747
|
+
await this.save(record);
|
|
2748
|
+
return;
|
|
2749
|
+
}
|
|
2750
|
+
const sourceFile = this.filePath(sourceSessionId);
|
|
2751
|
+
const targetFile = this.filePath(record.acpxRecordId);
|
|
2752
|
+
const persisted = serializeSessionRecordForDisk(record);
|
|
2753
|
+
assertPersistedKeyPolicy(persisted);
|
|
2754
|
+
const tempFile = `${targetFile}.${process.pid}.${Date.now()}.${randomUUID()}.tmp`;
|
|
2755
|
+
const payload = JSON.stringify(persisted, null, 2);
|
|
2756
|
+
await fs.writeFile(tempFile, `${payload}\n`, {
|
|
2757
|
+
encoding: "utf8",
|
|
2758
|
+
flag: "wx"
|
|
2759
|
+
});
|
|
2760
|
+
try {
|
|
2761
|
+
await fs.link(tempFile, targetFile);
|
|
2762
|
+
} catch (error) {
|
|
2763
|
+
if (error.code === "EEXIST") throw new Error(`ACP session already exists: ${record.acpxRecordId}`, { cause: error });
|
|
2764
|
+
throw error;
|
|
2765
|
+
} finally {
|
|
2766
|
+
await fs.unlink(tempFile).catch(() => {});
|
|
2767
|
+
}
|
|
2768
|
+
try {
|
|
2769
|
+
await fs.unlink(sourceFile);
|
|
2770
|
+
} catch (error) {
|
|
2771
|
+
await fs.unlink(targetFile).catch(() => {});
|
|
2772
|
+
throw error;
|
|
2773
|
+
}
|
|
2774
|
+
}
|
|
2775
|
+
};
|
|
2776
|
+
function createFileSessionStore(options) {
|
|
2777
|
+
return new FileSessionStore(path.resolve(options.stateDir));
|
|
2778
|
+
}
|
|
2779
|
+
//#endregion
|
|
2780
|
+
//#region src/runtime/public/handle-state.ts
|
|
2781
|
+
const ACPX_RUNTIME_HANDLE_PREFIX = "acpx:v2:";
|
|
2782
|
+
function encodeAcpxRuntimeHandleState(state) {
|
|
2783
|
+
const payload = Buffer.from(JSON.stringify(state), "utf8").toString("base64url");
|
|
2784
|
+
return `${ACPX_RUNTIME_HANDLE_PREFIX}${payload}`;
|
|
2785
|
+
}
|
|
2786
|
+
function decodeAcpxRuntimeHandleState(runtimeSessionName) {
|
|
2787
|
+
const trimmed = runtimeSessionName.trim();
|
|
2788
|
+
if (!trimmed.startsWith(ACPX_RUNTIME_HANDLE_PREFIX)) return null;
|
|
2789
|
+
try {
|
|
2790
|
+
const raw = Buffer.from(trimmed.slice(8), "base64url").toString("utf8");
|
|
2791
|
+
const parsed = JSON.parse(raw);
|
|
2792
|
+
const name = asOptionalString(parsed.name);
|
|
2793
|
+
const agent = asOptionalString(parsed.agent);
|
|
2794
|
+
const cwd = asOptionalString(parsed.cwd);
|
|
2795
|
+
const mode = asOptionalString(parsed.mode);
|
|
2796
|
+
if (!name || !agent || !cwd || mode !== "persistent" && mode !== "oneshot") return null;
|
|
2797
|
+
return {
|
|
2798
|
+
name,
|
|
2799
|
+
agent,
|
|
2800
|
+
cwd,
|
|
2801
|
+
mode,
|
|
2802
|
+
acpxRecordId: asOptionalString(parsed.acpxRecordId),
|
|
2803
|
+
backendSessionId: asOptionalString(parsed.backendSessionId),
|
|
2804
|
+
agentSessionId: asOptionalString(parsed.agentSessionId)
|
|
2805
|
+
};
|
|
2806
|
+
} catch {
|
|
2807
|
+
return null;
|
|
2808
|
+
}
|
|
2809
|
+
}
|
|
2810
|
+
function writeHandleState(handle, state) {
|
|
2811
|
+
handle.runtimeSessionName = encodeAcpxRuntimeHandleState(state);
|
|
2812
|
+
handle.cwd = state.cwd;
|
|
2813
|
+
handle.acpxRecordId = state.acpxRecordId;
|
|
2814
|
+
handle.backendSessionId = state.backendSessionId;
|
|
2815
|
+
handle.agentSessionId = state.agentSessionId;
|
|
2816
|
+
}
|
|
2817
|
+
//#endregion
|
|
2818
|
+
//#region src/runtime/public/turn-journal.ts
|
|
2819
|
+
const TERMINAL_STATUSES = /* @__PURE__ */ new Set([
|
|
2820
|
+
"completed",
|
|
2821
|
+
"failed",
|
|
2822
|
+
"cancelled"
|
|
2823
|
+
]);
|
|
2824
|
+
function isTerminal(status) {
|
|
2825
|
+
return TERMINAL_STATUSES.has(status);
|
|
2826
|
+
}
|
|
2827
|
+
function fingerprintPrompt(promptText) {
|
|
2828
|
+
return createHash("sha256").update(promptText).digest("hex");
|
|
2829
|
+
}
|
|
2830
|
+
function safeSessionId(sessionId) {
|
|
2831
|
+
return encodeURIComponent(sessionId);
|
|
2832
|
+
}
|
|
2833
|
+
function validTransition(previous, next) {
|
|
2834
|
+
if (!previous || previous === next) return true;
|
|
2835
|
+
if (previous === "queued") return next === "running" || isTerminal(next);
|
|
2836
|
+
if (previous === "running") return isTerminal(next);
|
|
2837
|
+
return false;
|
|
2838
|
+
}
|
|
2839
|
+
function optionalString(value) {
|
|
2840
|
+
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
2841
|
+
}
|
|
2842
|
+
const journalEventSchema = z.object({
|
|
2843
|
+
schema: z.literal("acpx.turn.v1"),
|
|
2844
|
+
sequence: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
|
|
2845
|
+
status: z.enum([
|
|
2846
|
+
"queued",
|
|
2847
|
+
"running",
|
|
2848
|
+
"completed",
|
|
2849
|
+
"failed",
|
|
2850
|
+
"cancelled"
|
|
2851
|
+
]),
|
|
2852
|
+
session_id: z.string(),
|
|
2853
|
+
turn_id: z.string(),
|
|
2854
|
+
client_request_id: z.string(),
|
|
2855
|
+
prompt_text: z.string(),
|
|
2856
|
+
request_fingerprint: z.string(),
|
|
2857
|
+
occurred_at: z.string(),
|
|
2858
|
+
created_at: z.string(),
|
|
2859
|
+
agent_type: z.unknown().optional().transform(optionalString),
|
|
2860
|
+
final_answer: z.unknown().optional().transform(optionalString),
|
|
2861
|
+
error_code: z.unknown().optional().transform(optionalString),
|
|
2862
|
+
error_text: z.unknown().optional().transform(optionalString),
|
|
2863
|
+
runtime_record_id: z.unknown().optional().transform(optionalString),
|
|
2864
|
+
runtime_request_id: z.unknown().optional().transform(optionalString),
|
|
2865
|
+
prompt_message_id: z.unknown().optional().transform(optionalString),
|
|
2866
|
+
stop_reason: z.unknown().optional().transform(optionalString),
|
|
2867
|
+
terminal_source: z.unknown().optional().transform(optionalString),
|
|
2868
|
+
started_at: z.unknown().optional().transform(optionalString),
|
|
2869
|
+
completed_at: z.unknown().optional().transform(optionalString)
|
|
2870
|
+
});
|
|
2871
|
+
function parseEvent(value) {
|
|
2872
|
+
return journalEventSchema.safeParse(value).data;
|
|
2873
|
+
}
|
|
2874
|
+
function retainedValue(value, previous, key) {
|
|
2875
|
+
return value ?? previous?.[key];
|
|
2876
|
+
}
|
|
2877
|
+
function applyEvent(state, event) {
|
|
2878
|
+
const previous = state.byTurnId.get(event.turn_id);
|
|
2879
|
+
const turn = {
|
|
2880
|
+
id: event.turn_id,
|
|
2881
|
+
turnId: event.turn_id,
|
|
2882
|
+
sessionId: event.session_id,
|
|
2883
|
+
clientRequestId: event.client_request_id,
|
|
2884
|
+
status: event.status,
|
|
2885
|
+
promptText: event.prompt_text,
|
|
2886
|
+
requestFingerprint: event.request_fingerprint,
|
|
2887
|
+
agentType: retainedValue(event.agent_type, previous, "agentType"),
|
|
2888
|
+
finalAnswer: retainedValue(event.final_answer, previous, "finalAnswer"),
|
|
2889
|
+
errorCode: event.error_code,
|
|
2890
|
+
errorText: event.error_text,
|
|
2891
|
+
runtimeRecordId: retainedValue(event.runtime_record_id, previous, "runtimeRecordId"),
|
|
2892
|
+
runtimeRequestId: retainedValue(event.runtime_request_id, previous, "runtimeRequestId"),
|
|
2893
|
+
promptMessageId: retainedValue(event.prompt_message_id, previous, "promptMessageId"),
|
|
2894
|
+
stopReason: retainedValue(event.stop_reason, previous, "stopReason"),
|
|
2895
|
+
terminalSource: retainedValue(event.terminal_source, previous, "terminalSource"),
|
|
2896
|
+
lastEventSeq: event.sequence,
|
|
2897
|
+
createdAt: event.created_at,
|
|
2898
|
+
updatedAt: event.occurred_at,
|
|
2899
|
+
startedAt: retainedValue(event.started_at, previous, "startedAt"),
|
|
2900
|
+
completedAt: retainedValue(event.completed_at, previous, "completedAt")
|
|
2901
|
+
};
|
|
2902
|
+
state.sequence = Math.max(state.sequence, event.sequence);
|
|
2903
|
+
state.byTurnId.set(turn.turnId, turn);
|
|
2904
|
+
state.byClientRequestId.set(turn.clientRequestId, turn);
|
|
2905
|
+
}
|
|
2906
|
+
function emptyState() {
|
|
2907
|
+
return {
|
|
2908
|
+
sequence: 0,
|
|
2909
|
+
byTurnId: /* @__PURE__ */ new Map(),
|
|
2910
|
+
byClientRequestId: /* @__PURE__ */ new Map()
|
|
2911
|
+
};
|
|
2912
|
+
}
|
|
2913
|
+
function sameMutation(turn, input) {
|
|
2914
|
+
return turn.status === input.status && [
|
|
2915
|
+
"finalAnswer",
|
|
2916
|
+
"errorCode",
|
|
2917
|
+
"errorText",
|
|
2918
|
+
"stopReason",
|
|
2919
|
+
"runtimeRequestId",
|
|
2920
|
+
"promptMessageId"
|
|
2921
|
+
].every((key) => input[key] === void 0 || turn[key] === input[key]);
|
|
2922
|
+
}
|
|
2923
|
+
function validateMutation(previous, input, fingerprint) {
|
|
2924
|
+
if (previous && previous.requestFingerprint && fingerprint && previous.requestFingerprint !== fingerprint) throw new Error(`Turn idempotency conflict for ${input.turnId}`);
|
|
2925
|
+
if (!validTransition(previous?.status, input.status)) throw new Error(`Invalid Turn transition ${previous?.status} -> ${input.status}`);
|
|
2926
|
+
}
|
|
2927
|
+
function mutationFingerprint(input, previous) {
|
|
2928
|
+
const promptText = input.promptText ?? "";
|
|
2929
|
+
return input.requestFingerprint || (previous?.promptText === promptText ? previous.requestFingerprint : void 0) || fingerprintPrompt(promptText);
|
|
2930
|
+
}
|
|
2931
|
+
function transitionTime(value, previous, key, transition, occurredAt) {
|
|
2932
|
+
return retainedValue(value, previous, key) ?? (transition ? occurredAt : void 0);
|
|
2933
|
+
}
|
|
2934
|
+
function mutationTimestamps(input, previous) {
|
|
2935
|
+
const occurredAt = input.occurredAt ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
2936
|
+
return {
|
|
2937
|
+
occurred_at: occurredAt,
|
|
2938
|
+
created_at: previous?.createdAt ?? occurredAt,
|
|
2939
|
+
started_at: transitionTime(input.startedAt, previous, "startedAt", input.status === "running", occurredAt),
|
|
2940
|
+
completed_at: transitionTime(input.completedAt, previous, "completedAt", isTerminal(input.status), occurredAt)
|
|
2941
|
+
};
|
|
2942
|
+
}
|
|
2943
|
+
function mutationEvent(input, previous, sequence, clientRequestId, requestFingerprint) {
|
|
2944
|
+
return {
|
|
2945
|
+
schema: "acpx.turn.v1",
|
|
2946
|
+
sequence,
|
|
2947
|
+
session_id: input.sessionId,
|
|
2948
|
+
turn_id: input.turnId,
|
|
2949
|
+
client_request_id: clientRequestId,
|
|
2950
|
+
status: input.status,
|
|
2951
|
+
prompt_text: previous?.promptText || (input.promptText ?? ""),
|
|
2952
|
+
request_fingerprint: previous?.requestFingerprint || requestFingerprint,
|
|
2953
|
+
agent_type: retainedValue(input.agentType, previous, "agentType"),
|
|
2954
|
+
final_answer: retainedValue(input.finalAnswer, previous, "finalAnswer"),
|
|
2955
|
+
error_code: input.errorCode,
|
|
2956
|
+
error_text: input.errorText,
|
|
2957
|
+
runtime_record_id: retainedValue(input.runtimeRecordId, previous, "runtimeRecordId"),
|
|
2958
|
+
runtime_request_id: retainedValue(input.runtimeRequestId, previous, "runtimeRequestId"),
|
|
2959
|
+
prompt_message_id: retainedValue(input.promptMessageId, previous, "promptMessageId"),
|
|
2960
|
+
stop_reason: retainedValue(input.stopReason, previous, "stopReason"),
|
|
2961
|
+
terminal_source: retainedValue(input.terminalSource, previous, "terminalSource"),
|
|
2962
|
+
...mutationTimestamps(input, previous)
|
|
2963
|
+
};
|
|
2964
|
+
}
|
|
2965
|
+
var AcpTurnJournal = class {
|
|
2966
|
+
stateDir;
|
|
2967
|
+
chains = /* @__PURE__ */ new Map();
|
|
2968
|
+
constructor(options) {
|
|
2969
|
+
this.stateDir = path.resolve(options.stateDir);
|
|
2970
|
+
}
|
|
2971
|
+
filePath(sessionId) {
|
|
2972
|
+
return path.join(this.stateDir, "sessions", `${safeSessionId(sessionId)}.turns.ndjson`);
|
|
2973
|
+
}
|
|
2974
|
+
async readState(sessionId) {
|
|
2975
|
+
const state = emptyState();
|
|
2976
|
+
let payload;
|
|
2977
|
+
try {
|
|
2978
|
+
payload = await fs.readFile(this.filePath(sessionId), "utf8");
|
|
2979
|
+
} catch (error) {
|
|
2980
|
+
if (error.code === "ENOENT") return state;
|
|
2981
|
+
throw error;
|
|
2982
|
+
}
|
|
2983
|
+
for (const line of payload.split("\n")) {
|
|
2984
|
+
if (!line.trim()) continue;
|
|
2985
|
+
try {
|
|
2986
|
+
const event = parseEvent(JSON.parse(line));
|
|
2987
|
+
if (event && event.session_id === sessionId) applyEvent(state, event);
|
|
2988
|
+
} catch {}
|
|
2989
|
+
}
|
|
2990
|
+
return state;
|
|
2991
|
+
}
|
|
2992
|
+
async withSessionLock(sessionId, operation) {
|
|
2993
|
+
const previous = this.chains.get(sessionId) ?? Promise.resolve();
|
|
2994
|
+
let release;
|
|
2995
|
+
const current = new Promise((resolve) => {
|
|
2996
|
+
release = resolve;
|
|
2997
|
+
});
|
|
2998
|
+
const queued = previous.catch(() => {}).then(() => current);
|
|
2999
|
+
this.chains.set(sessionId, queued);
|
|
3000
|
+
await previous.catch(() => {});
|
|
3001
|
+
try {
|
|
3002
|
+
return await operation();
|
|
3003
|
+
} finally {
|
|
3004
|
+
release?.();
|
|
3005
|
+
if (this.chains.get(sessionId) === queued) this.chains.delete(sessionId);
|
|
3006
|
+
}
|
|
3007
|
+
}
|
|
3008
|
+
async appendEvent(sessionId, event) {
|
|
3009
|
+
const journalPath = this.filePath(sessionId);
|
|
3010
|
+
await fs.mkdir(path.dirname(journalPath), { recursive: true });
|
|
3011
|
+
const file = await fs.open(journalPath, "a+");
|
|
3012
|
+
try {
|
|
3013
|
+
const stats = await file.stat();
|
|
3014
|
+
if (stats.size > 0) {
|
|
3015
|
+
const trailing = Buffer.alloc(1);
|
|
3016
|
+
await file.read(trailing, 0, 1, stats.size - 1);
|
|
3017
|
+
if (trailing[0] !== 10) await file.write("\n");
|
|
3018
|
+
}
|
|
3019
|
+
await file.write(`${JSON.stringify(event)}\n`);
|
|
3020
|
+
await file.sync();
|
|
3021
|
+
} finally {
|
|
3022
|
+
await file.close();
|
|
3023
|
+
}
|
|
3024
|
+
}
|
|
3025
|
+
async record(input) {
|
|
3026
|
+
return await this.withSessionLock(input.sessionId, async () => {
|
|
3027
|
+
const state = await this.readState(input.sessionId);
|
|
3028
|
+
const clientRequestId = input.clientRequestId || input.turnId;
|
|
3029
|
+
const byRequest = state.byClientRequestId.get(clientRequestId);
|
|
3030
|
+
const previous = state.byTurnId.get(input.turnId);
|
|
3031
|
+
const requestFingerprint = mutationFingerprint(input, previous);
|
|
3032
|
+
if (byRequest && byRequest.turnId !== input.turnId) {
|
|
3033
|
+
if (byRequest.requestFingerprint !== requestFingerprint) throw new Error(`Turn idempotency conflict for request ${clientRequestId}`);
|
|
3034
|
+
return {
|
|
3035
|
+
turn: byRequest,
|
|
3036
|
+
created: false,
|
|
3037
|
+
changed: false
|
|
3038
|
+
};
|
|
3039
|
+
}
|
|
3040
|
+
validateMutation(previous, input, requestFingerprint);
|
|
3041
|
+
if (previous && sameMutation(previous, input)) return {
|
|
3042
|
+
turn: previous,
|
|
3043
|
+
created: false,
|
|
3044
|
+
changed: false
|
|
3045
|
+
};
|
|
3046
|
+
const event = mutationEvent(input, previous, state.sequence + 1, clientRequestId, requestFingerprint);
|
|
3047
|
+
await this.appendEvent(input.sessionId, event);
|
|
3048
|
+
applyEvent(state, event);
|
|
3049
|
+
return {
|
|
3050
|
+
turn: state.byTurnId.get(input.turnId),
|
|
3051
|
+
created: previous === void 0,
|
|
3052
|
+
changed: true
|
|
3053
|
+
};
|
|
3054
|
+
});
|
|
3055
|
+
}
|
|
3056
|
+
async snapshot(sessionId) {
|
|
3057
|
+
return await this.withSessionLock(sessionId, async () => {
|
|
3058
|
+
const state = await this.readState(sessionId);
|
|
3059
|
+
const turns = [...state.byTurnId.values()].toSorted((left, right) => left.createdAt.localeCompare(right.createdAt) || left.lastEventSeq - right.lastEventSeq);
|
|
3060
|
+
return {
|
|
3061
|
+
sessionId,
|
|
3062
|
+
sequence: state.sequence,
|
|
3063
|
+
active: turns.find((turn) => turn.status === "running"),
|
|
3064
|
+
queued: turns.filter((turn) => turn.status === "queued"),
|
|
3065
|
+
turns
|
|
3066
|
+
};
|
|
3067
|
+
});
|
|
3068
|
+
}
|
|
3069
|
+
};
|
|
3070
|
+
function createTurnJournal(options) {
|
|
3071
|
+
return new AcpTurnJournal(options);
|
|
3072
|
+
}
|
|
3073
|
+
//#endregion
|
|
3074
|
+
//#region src/runtime/shared.ts
|
|
3075
|
+
const SHARED_BACKEND = "acpx-shared";
|
|
3076
|
+
function invalidOption(message) {
|
|
3077
|
+
throw new AcpRuntimeError("ACP_INVALID_RUNTIME_OPTION", message);
|
|
3078
|
+
}
|
|
3079
|
+
function sharedHandle(record) {
|
|
3080
|
+
return {
|
|
3081
|
+
backend: SHARED_BACKEND,
|
|
3082
|
+
sessionKey: record.name ?? "",
|
|
3083
|
+
runtimeSessionName: record.acpxRecordId,
|
|
3084
|
+
acpxRecordId: record.acpxRecordId,
|
|
3085
|
+
backendSessionId: record.acpSessionId,
|
|
3086
|
+
agentSessionId: record.agentSessionId,
|
|
3087
|
+
cwd: record.cwd
|
|
3088
|
+
};
|
|
3089
|
+
}
|
|
3090
|
+
function sharedRecordId(handle) {
|
|
3091
|
+
if (handle.backend !== SHARED_BACKEND || !handle.acpxRecordId) return invalidOption("A shared runtime requires a handle from a shared session.");
|
|
3092
|
+
return handle.acpxRecordId;
|
|
3093
|
+
}
|
|
3094
|
+
/**
|
|
3095
|
+
* Shared controls are owner-only. Falling back to a direct connection would
|
|
3096
|
+
* start a second adapter connection for a session another process owns, and
|
|
3097
|
+
* that path may create a fresh provider session when the saved one no longer
|
|
3098
|
+
* loads. Shared turns already refuse that trade; controls refuse it too.
|
|
3099
|
+
*/
|
|
3100
|
+
function requireOwnerDispatch(result, control) {
|
|
3101
|
+
if (result === void 0) throw new AcpRuntimeError("ACP_BACKEND_UNAVAILABLE", `No running owner holds this shared session, so ${control} was not sent. Submit a turn to start an owner, or apply the change with the equivalent acpx command, which connects directly instead of starting one.`);
|
|
3102
|
+
return result;
|
|
3103
|
+
}
|
|
3104
|
+
function turnFailure(error) {
|
|
3105
|
+
const normalized = normalizeOutputError(error, {
|
|
3106
|
+
defaultCode: "RUNTIME",
|
|
3107
|
+
origin: "queue"
|
|
3108
|
+
});
|
|
3109
|
+
if (normalized.detailCode === "QUEUE_REQUEST_CANCELLED") return {
|
|
3110
|
+
status: "cancelled",
|
|
3111
|
+
stopReason: "cancelled"
|
|
3112
|
+
};
|
|
3113
|
+
return {
|
|
3114
|
+
status: "failed",
|
|
3115
|
+
error: {
|
|
3116
|
+
message: normalized.message,
|
|
3117
|
+
code: normalized.code,
|
|
3118
|
+
detailCode: normalized.detailCode,
|
|
3119
|
+
retryable: normalized.retryable
|
|
3120
|
+
}
|
|
3121
|
+
};
|
|
3122
|
+
}
|
|
3123
|
+
/** A client of the CLI's local session owner. Shutdown detaches this client. */
|
|
3124
|
+
var SharedAcpRuntime = class {
|
|
3125
|
+
registry;
|
|
3126
|
+
options;
|
|
3127
|
+
disconnect = new AbortController();
|
|
3128
|
+
pending = /* @__PURE__ */ new Set();
|
|
3129
|
+
controlChains = /* @__PURE__ */ new Map();
|
|
3130
|
+
constructor(options) {
|
|
3131
|
+
for (const name of [
|
|
3132
|
+
"sessionStore",
|
|
3133
|
+
"agentProcessEnv",
|
|
3134
|
+
"mcpServers",
|
|
3135
|
+
"sessionPermissions",
|
|
3136
|
+
"processLifecycle",
|
|
3137
|
+
"onPermissionRequest",
|
|
3138
|
+
"elicitationModes",
|
|
3139
|
+
"fs",
|
|
3140
|
+
"terminal"
|
|
3141
|
+
]) if (Object.hasOwn(options, name)) invalidOption(`${name} belongs to the in-process runtime and is not supported by shared sessions.`);
|
|
3142
|
+
this.options = {
|
|
3143
|
+
...options,
|
|
3144
|
+
cwd: path.resolve(options.cwd),
|
|
3145
|
+
authCredentials: options.authCredentials ? { ...options.authCredentials } : void 0
|
|
3146
|
+
};
|
|
3147
|
+
this.registry = options.agentRegistry ?? createAgentRegistry();
|
|
3148
|
+
}
|
|
3149
|
+
assertOpen() {
|
|
3150
|
+
if (this.disconnect.signal.aborted) throw new AcpRuntimeError("ACP_BACKEND_UNAVAILABLE", "Shared ACP runtime is shut down.");
|
|
3151
|
+
}
|
|
3152
|
+
track(task) {
|
|
3153
|
+
this.pending.add(task);
|
|
3154
|
+
task.then(() => this.pending.delete(task), () => this.pending.delete(task));
|
|
3155
|
+
return task;
|
|
3156
|
+
}
|
|
3157
|
+
sessionOptions(input) {
|
|
3158
|
+
if (!input.agent.trim()) invalidOption("ACP agent id is required.");
|
|
3159
|
+
return {
|
|
3160
|
+
...normalizeAgentCommandInput(this.registry.resolve(input.agent)),
|
|
3161
|
+
cwd: path.resolve(input.cwd ?? this.options.cwd),
|
|
3162
|
+
name: input.sessionKey.trim() || void 0
|
|
3163
|
+
};
|
|
3164
|
+
}
|
|
3165
|
+
async findSession(input) {
|
|
3166
|
+
this.assertOpen();
|
|
3167
|
+
const record = await findSession(this.sessionOptions(input));
|
|
3168
|
+
return record ? sharedHandle(record) : void 0;
|
|
3169
|
+
}
|
|
3170
|
+
ensureSession(input) {
|
|
3171
|
+
this.assertOpen();
|
|
3172
|
+
if (input.mode !== "persistent") invalidOption("Shared sessions require persistent mode; use the in-process runtime for oneshot sessions.");
|
|
3173
|
+
const session = this.sessionOptions(input);
|
|
3174
|
+
return this.track(ensureSession({
|
|
3175
|
+
...this.options,
|
|
3176
|
+
...session,
|
|
3177
|
+
walkBoundary: session.cwd,
|
|
3178
|
+
sessionOptions: input.sessionOptions,
|
|
3179
|
+
resumeSessionId: input.resumeSessionId,
|
|
3180
|
+
handleProcessInterrupts: false,
|
|
3181
|
+
signal: this.disconnect.signal
|
|
3182
|
+
}).then(({ record }) => {
|
|
3183
|
+
this.assertOpen();
|
|
3184
|
+
return sharedHandle(record);
|
|
3185
|
+
}));
|
|
3186
|
+
}
|
|
3187
|
+
startTurn(input) {
|
|
3188
|
+
this.assertOpen();
|
|
3189
|
+
if (input.mode !== "prompt" || input.assertActive || input.onPermissionRequest || input.onElicitation) invalidOption("Shared turns support prompt mode and the client's static permission policy; in-process callbacks and steering are unsupported.");
|
|
3190
|
+
if (!input.requestId.trim()) invalidOption("A shared turn requires a requestId.");
|
|
3191
|
+
const sessionId = sharedRecordId(input.handle);
|
|
3192
|
+
const prompt = toPromptInput(input.text, input.attachments);
|
|
3193
|
+
const events = new AsyncEventQueue();
|
|
3194
|
+
const promptStarted = createDeferred();
|
|
3195
|
+
promptStarted.promise.catch(() => {});
|
|
3196
|
+
let accepted = false;
|
|
3197
|
+
let settled = false;
|
|
3198
|
+
let cancelRequested = input.signal?.aborted === true;
|
|
3199
|
+
let cancellation;
|
|
3200
|
+
const cancel = async () => {
|
|
3201
|
+
cancelRequested = true;
|
|
3202
|
+
if (!accepted || settled) return;
|
|
3203
|
+
cancellation ??= tryCancelOnRunningOwner({
|
|
3204
|
+
sessionId,
|
|
3205
|
+
targetRequestId: input.requestId
|
|
3206
|
+
}).then(() => {});
|
|
3207
|
+
await cancellation;
|
|
3208
|
+
};
|
|
3209
|
+
const onAbort = () => {
|
|
3210
|
+
cancel().catch(() => {});
|
|
3211
|
+
};
|
|
3212
|
+
input.signal?.addEventListener("abort", onAbort, { once: true });
|
|
3213
|
+
const run = async () => {
|
|
3214
|
+
if (cancelRequested) return {
|
|
3215
|
+
status: "cancelled",
|
|
3216
|
+
stopReason: "cancelled"
|
|
3217
|
+
};
|
|
3218
|
+
if ((await resolveSessionRecord(sessionId)).closed) throw new AcpRuntimeError("ACP_SESSION_INIT_FAILED", "Shared session is closed; ensure it again before submitting a turn.");
|
|
3219
|
+
if (cancelRequested) return {
|
|
3220
|
+
status: "cancelled",
|
|
3221
|
+
stopReason: "cancelled"
|
|
3222
|
+
};
|
|
3223
|
+
const result = await sendSession({
|
|
3224
|
+
...this.options,
|
|
3225
|
+
sessionId,
|
|
3226
|
+
requestId: input.requestId,
|
|
3227
|
+
prompt: typeof prompt === "string" ? textPrompt(prompt) : prompt,
|
|
3228
|
+
resumePolicy: "same-session-only",
|
|
3229
|
+
requireSharedRuntime: true,
|
|
3230
|
+
signal: this.disconnect.signal,
|
|
3231
|
+
timeoutMs: input.timeoutMs ?? this.options.timeoutMs,
|
|
3232
|
+
queueOwnerArgs: [fileURLToPath(new URL("../cli.js", import.meta.url)), "__queue-owner"],
|
|
3233
|
+
onQueueAccepted: () => {
|
|
3234
|
+
accepted = true;
|
|
3235
|
+
if (cancelRequested) cancel().catch(() => {});
|
|
3236
|
+
},
|
|
3237
|
+
onPromptStarted: () => promptStarted.resolve(),
|
|
3238
|
+
outputFormatter: {
|
|
3239
|
+
...DISCARD_OUTPUT_FORMATTER,
|
|
3240
|
+
onAcpMessage: (message) => {
|
|
3241
|
+
const event = parsePromptEventLine(JSON.stringify(message));
|
|
3242
|
+
if (event) events.push(event);
|
|
3243
|
+
}
|
|
3244
|
+
},
|
|
3245
|
+
errorEmissionPolicy: { queueErrorAlreadyEmitted: false },
|
|
3246
|
+
waitForCompletion: true
|
|
3247
|
+
});
|
|
3248
|
+
if ("queued" in result) throw new AcpRuntimeError("ACP_TURN_FAILED", "Shared turn ended without a completion result.");
|
|
3249
|
+
return {
|
|
3250
|
+
status: result.stopReason === "cancelled" ? "cancelled" : "completed",
|
|
3251
|
+
stopReason: result.stopReason,
|
|
3252
|
+
_meta: result._meta
|
|
3253
|
+
};
|
|
3254
|
+
};
|
|
3255
|
+
const result = this.track(run().catch(turnFailure).finally(() => {
|
|
3256
|
+
settled = true;
|
|
3257
|
+
promptStarted.reject(new AcpRuntimeError("ACP_TURN_FAILED", "Turn settled before its prompt was written."));
|
|
3258
|
+
input.signal?.removeEventListener("abort", onAbort);
|
|
3259
|
+
events.close();
|
|
3260
|
+
}));
|
|
3261
|
+
return {
|
|
3262
|
+
requestId: input.requestId,
|
|
3263
|
+
promptStarted: promptStarted.promise,
|
|
3264
|
+
events: events.iterate(),
|
|
3265
|
+
result,
|
|
3266
|
+
cancel,
|
|
3267
|
+
closeStream: async () => {
|
|
3268
|
+
events.clear();
|
|
3269
|
+
events.close();
|
|
3270
|
+
}
|
|
3271
|
+
};
|
|
3272
|
+
}
|
|
3273
|
+
async *runTurn(input) {
|
|
3274
|
+
const turn = this.startTurn(input);
|
|
3275
|
+
yield* turn.events;
|
|
3276
|
+
yield legacyTerminalEventFromTurnResult(await turn.result);
|
|
3277
|
+
}
|
|
3278
|
+
async getStatus(input) {
|
|
3279
|
+
this.assertOpen();
|
|
3280
|
+
return runtimeStatusFromRecord(await resolveSessionRecord(sharedRecordId(input.handle)));
|
|
3281
|
+
}
|
|
3282
|
+
async getCapabilities(input) {
|
|
3283
|
+
this.assertOpen();
|
|
3284
|
+
if (!input?.handle) return capabilitiesFromRecord(void 0);
|
|
3285
|
+
return capabilitiesFromRecord(await readSessionRecord(sharedRecordId(input.handle)));
|
|
3286
|
+
}
|
|
3287
|
+
/**
|
|
3288
|
+
* Preserves this client's control order, including caller-side persistence
|
|
3289
|
+
* when talking to older owners. Updated owners checkpoint accepted controls
|
|
3290
|
+
* themselves; serialization here cannot coordinate other legacy callers.
|
|
3291
|
+
*/
|
|
3292
|
+
chainControl(sessionId, run) {
|
|
3293
|
+
const result = (this.controlChains.get(sessionId) ?? Promise.resolve()).then(run, run);
|
|
3294
|
+
const chained = result.then(() => void 0, () => void 0);
|
|
3295
|
+
this.controlChains.set(sessionId, chained);
|
|
3296
|
+
chained.then(() => {
|
|
3297
|
+
if (this.controlChains.get(sessionId) === chained) this.controlChains.delete(sessionId);
|
|
3298
|
+
});
|
|
3299
|
+
return result;
|
|
3300
|
+
}
|
|
3301
|
+
/**
|
|
3302
|
+
* Checks this client's authority locally, then hands the control to the
|
|
3303
|
+
* running owner. The check gates this client's dispatch only; it cannot gate
|
|
3304
|
+
* controls other clients of the same owner send, and it cannot recall a
|
|
3305
|
+
* control the owner already accepted.
|
|
3306
|
+
*/
|
|
3307
|
+
async dispatchControl(input, control, send) {
|
|
3308
|
+
this.assertOpen();
|
|
3309
|
+
const sessionId = sharedRecordId(input.handle);
|
|
3310
|
+
const assertAuthority = () => {
|
|
3311
|
+
this.assertOpen();
|
|
3312
|
+
assertControlAuthority(input);
|
|
3313
|
+
};
|
|
3314
|
+
return await this.track(this.chainControl(sessionId, async () => {
|
|
3315
|
+
assertAuthority();
|
|
3316
|
+
return requireOwnerDispatch(await send(sessionId, assertAuthority), control);
|
|
3317
|
+
}));
|
|
3318
|
+
}
|
|
3319
|
+
async setMode(input) {
|
|
3320
|
+
await this.dispatchControl(input, "session/set_mode", async (sessionId, assertAuthority) => setSessionModeOnOwner({
|
|
3321
|
+
sessionId,
|
|
3322
|
+
modeId: input.mode,
|
|
3323
|
+
timeoutMs: this.options.timeoutMs,
|
|
3324
|
+
assertDispatch: assertAuthority
|
|
3325
|
+
}));
|
|
3326
|
+
}
|
|
3327
|
+
async setModel(input) {
|
|
3328
|
+
await this.dispatchControl(input, "session/set_model", async (sessionId, assertAuthority) => setSessionModelOnOwner({
|
|
3329
|
+
sessionId,
|
|
3330
|
+
modelId: input.model,
|
|
3331
|
+
timeoutMs: this.options.timeoutMs,
|
|
3332
|
+
assertDispatch: assertAuthority
|
|
3333
|
+
}));
|
|
3334
|
+
}
|
|
3335
|
+
async setConfigOption(input) {
|
|
3336
|
+
return (await this.dispatchControl(input, "session/set_config_option", async (sessionId, assertAuthority) => {
|
|
3337
|
+
const configId = resolveSupportedConfigOptionId(await resolveSessionRecord(sessionId), input.key);
|
|
3338
|
+
assertAuthority();
|
|
3339
|
+
return await setSessionConfigOptionOnOwner({
|
|
3340
|
+
sessionId,
|
|
3341
|
+
configId,
|
|
3342
|
+
value: input.value,
|
|
3343
|
+
timeoutMs: this.options.timeoutMs,
|
|
3344
|
+
assertDispatch: assertAuthority
|
|
3345
|
+
});
|
|
3346
|
+
})).response;
|
|
3347
|
+
}
|
|
3348
|
+
watchSession(input) {
|
|
3349
|
+
this.assertOpen();
|
|
3350
|
+
const signal = input.signal ? AbortSignal.any([input.signal, this.disconnect.signal]) : this.disconnect.signal;
|
|
3351
|
+
const recordId = sharedRecordId(input.handle);
|
|
3352
|
+
const record = readSessionRecord(recordId).then((value) => {
|
|
3353
|
+
if (!value || value.acpxRecordId !== recordId) throw new AcpRuntimeError("ACP_SESSION_INIT_FAILED", "Shared session record is unavailable.");
|
|
3354
|
+
return value;
|
|
3355
|
+
});
|
|
3356
|
+
record.catch(() => {});
|
|
3357
|
+
return watchSession({
|
|
3358
|
+
record,
|
|
3359
|
+
cursor: input.cursor,
|
|
3360
|
+
signal
|
|
3361
|
+
});
|
|
3362
|
+
}
|
|
3363
|
+
async cancel(input) {
|
|
3364
|
+
this.assertOpen();
|
|
3365
|
+
await this.track(cancelSessionPrompt({ sessionId: sharedRecordId(input.handle) }));
|
|
3366
|
+
}
|
|
3367
|
+
async close(input) {
|
|
3368
|
+
this.assertOpen();
|
|
3369
|
+
await this.track(closeSession(sharedRecordId(input.handle)));
|
|
3370
|
+
}
|
|
3371
|
+
async shutdown() {
|
|
3372
|
+
this.disconnect.abort(new AcpRuntimeError("ACP_BACKEND_UNAVAILABLE", "Shared client detached; submitted work may still be running."));
|
|
3373
|
+
await Promise.allSettled(this.pending);
|
|
3374
|
+
}
|
|
3375
|
+
};
|
|
3376
|
+
function createSharedAcpRuntime(options) {
|
|
3377
|
+
return new SharedAcpRuntime(options);
|
|
3378
|
+
}
|
|
3379
|
+
//#endregion
|
|
3380
|
+
//#region src/runtime.ts
|
|
3381
|
+
const ACPX_BACKEND_ID = "acpx";
|
|
3382
|
+
var AcpxRuntime = class {
|
|
3383
|
+
options;
|
|
3384
|
+
testOptions;
|
|
3385
|
+
healthy = false;
|
|
3386
|
+
shutdownTask;
|
|
3387
|
+
probeTasks = /* @__PURE__ */ new Set();
|
|
3388
|
+
manager = null;
|
|
3389
|
+
managerPromise = null;
|
|
3390
|
+
constructor(options, testOptions) {
|
|
3391
|
+
this.options = options;
|
|
3392
|
+
this.testOptions = testOptions;
|
|
3393
|
+
if (options.agentProcessEnv) this.options = {
|
|
3394
|
+
...options,
|
|
3395
|
+
agentProcessEnv: { ...options.agentProcessEnv }
|
|
3396
|
+
};
|
|
3397
|
+
}
|
|
3398
|
+
isHealthy() {
|
|
3399
|
+
return this.healthy;
|
|
3400
|
+
}
|
|
3401
|
+
async probeAvailability() {
|
|
3402
|
+
const report = await this.runProbe();
|
|
3403
|
+
this.healthy = report.ok;
|
|
3404
|
+
}
|
|
3405
|
+
async doctor() {
|
|
3406
|
+
const report = await this.runProbe();
|
|
3407
|
+
this.healthy = report.ok;
|
|
3408
|
+
return {
|
|
3409
|
+
ok: report.ok,
|
|
3410
|
+
code: report.ok ? void 0 : "ACP_BACKEND_UNAVAILABLE",
|
|
3411
|
+
message: report.message,
|
|
3412
|
+
details: normalizeRuntimeDetails(report.details)
|
|
3413
|
+
};
|
|
3414
|
+
}
|
|
3415
|
+
resolveSessionIdentity(input) {
|
|
3416
|
+
const sessionName = input.sessionKey.trim();
|
|
3417
|
+
if (!sessionName) throw new AcpRuntimeError("ACP_SESSION_INIT_FAILED", "ACP session key is required.");
|
|
3418
|
+
const agent = input.agent.trim();
|
|
3419
|
+
if (!agent) throw new AcpRuntimeError("ACP_SESSION_INIT_FAILED", "ACP agent id is required.");
|
|
3420
|
+
return {
|
|
3421
|
+
sessionName,
|
|
3422
|
+
agent
|
|
3423
|
+
};
|
|
3424
|
+
}
|
|
3425
|
+
async findSession(input) {
|
|
3426
|
+
const { sessionName, agent } = this.resolveSessionIdentity(input);
|
|
3427
|
+
const record = await (await this.getManager()).findSession(sessionName);
|
|
3428
|
+
return record ? this.createSessionHandle({
|
|
3429
|
+
sessionKey: input.sessionKey,
|
|
3430
|
+
agent,
|
|
3431
|
+
mode: "persistent"
|
|
3432
|
+
}, record) : void 0;
|
|
3433
|
+
}
|
|
3434
|
+
async ensureSession(input) {
|
|
3435
|
+
const { sessionName, agent } = this.resolveSessionIdentity(input);
|
|
3436
|
+
const record = await (await this.getManager()).ensureSession({
|
|
3437
|
+
sessionKey: sessionName,
|
|
3438
|
+
agent,
|
|
3439
|
+
mode: input.mode,
|
|
3440
|
+
cwd: input.cwd ?? this.options.cwd,
|
|
3441
|
+
resumeSessionId: input.resumeSessionId,
|
|
3442
|
+
sessionOptions: input.sessionOptions,
|
|
3443
|
+
agentArgv: input.agentArgv,
|
|
3444
|
+
authCredentials: input.authCredentials
|
|
3445
|
+
});
|
|
3446
|
+
return this.createSessionHandle({
|
|
3447
|
+
...input,
|
|
3448
|
+
agent
|
|
3449
|
+
}, record);
|
|
3450
|
+
}
|
|
3451
|
+
createSessionHandle(input, record) {
|
|
3452
|
+
const handle = {
|
|
3453
|
+
sessionKey: input.sessionKey,
|
|
3454
|
+
backend: ACPX_BACKEND_ID,
|
|
3455
|
+
runtimeSessionName: "",
|
|
3456
|
+
cwd: record.cwd,
|
|
3457
|
+
acpxRecordId: record.acpxRecordId,
|
|
3458
|
+
backendSessionId: record.acpSessionId,
|
|
3459
|
+
agentSessionId: record.agentSessionId
|
|
3460
|
+
};
|
|
3461
|
+
writeHandleState(handle, {
|
|
3462
|
+
name: input.sessionKey.trim(),
|
|
3463
|
+
agent: input.agent,
|
|
3464
|
+
cwd: record.cwd,
|
|
3465
|
+
mode: input.mode,
|
|
3466
|
+
acpxRecordId: record.acpxRecordId,
|
|
3467
|
+
backendSessionId: record.acpSessionId,
|
|
3468
|
+
agentSessionId: record.agentSessionId
|
|
3469
|
+
});
|
|
3470
|
+
return handle;
|
|
3471
|
+
}
|
|
3472
|
+
async adoptSession(input) {
|
|
3473
|
+
const sessionKey = input.sessionKey.trim();
|
|
3474
|
+
if (!sessionKey) throw new AcpRuntimeError("ACP_SESSION_INIT_FAILED", "ACP session key is required.");
|
|
3475
|
+
const state = this.resolveHandleState(input.handle);
|
|
3476
|
+
if (state.mode !== "persistent") throw new AcpRuntimeError("ACP_SESSION_INIT_FAILED", "Only persistent ACP sessions can be adopted.");
|
|
3477
|
+
const record = await (await this.getManager()).adoptSession({
|
|
3478
|
+
handle: {
|
|
3479
|
+
...input.handle,
|
|
3480
|
+
acpxRecordId: state.acpxRecordId ?? input.handle.acpxRecordId ?? input.handle.sessionKey
|
|
3481
|
+
},
|
|
3482
|
+
sessionKey
|
|
3483
|
+
});
|
|
3484
|
+
input.handle.sessionKey = sessionKey;
|
|
3485
|
+
writeHandleState(input.handle, {
|
|
3486
|
+
...state,
|
|
3487
|
+
name: sessionKey,
|
|
3488
|
+
cwd: record.cwd,
|
|
3489
|
+
acpxRecordId: record.acpxRecordId,
|
|
3490
|
+
backendSessionId: record.acpSessionId,
|
|
3491
|
+
agentSessionId: record.agentSessionId
|
|
3492
|
+
});
|
|
3493
|
+
return input.handle;
|
|
3494
|
+
}
|
|
3495
|
+
async logoutSession(input) {
|
|
3496
|
+
const { handle } = this.resolveManagerHandle(input.handle);
|
|
3497
|
+
await (await this.getManager()).logoutSession({ handle });
|
|
3498
|
+
}
|
|
3499
|
+
async authenticateSession(input) {
|
|
3500
|
+
const { handle } = this.resolveManagerHandle(input.handle);
|
|
3501
|
+
await (await this.getManager()).authenticateSession({
|
|
3502
|
+
...input,
|
|
3503
|
+
handle
|
|
3504
|
+
});
|
|
3505
|
+
}
|
|
3506
|
+
async forkSession(input) {
|
|
3507
|
+
const { handle } = this.resolveManagerHandle(input.handle);
|
|
3508
|
+
return await (await this.getManager()).forkSession({
|
|
3509
|
+
...input,
|
|
3510
|
+
handle
|
|
3511
|
+
});
|
|
3512
|
+
}
|
|
3513
|
+
async deleteSession(input) {
|
|
3514
|
+
const { handle } = this.resolveManagerHandle(input.handle);
|
|
3515
|
+
await (await this.getManager()).deleteSession({
|
|
3516
|
+
...input,
|
|
3517
|
+
handle
|
|
3518
|
+
});
|
|
3519
|
+
}
|
|
3520
|
+
startTurn(input) {
|
|
3521
|
+
const { handle, state } = this.resolveManagerHandle(input.handle);
|
|
3522
|
+
const turnPromise = this.getManager().then((manager) => manager.startTurn({
|
|
3523
|
+
handle,
|
|
3524
|
+
text: input.text,
|
|
3525
|
+
attachments: input.attachments,
|
|
3526
|
+
mode: input.mode,
|
|
3527
|
+
sessionMode: state.mode,
|
|
3528
|
+
requestId: input.requestId,
|
|
3529
|
+
timeoutMs: input.timeoutMs,
|
|
3530
|
+
signal: input.signal,
|
|
3531
|
+
assertActive: input.assertActive,
|
|
3532
|
+
onElicitation: input.onElicitation,
|
|
3533
|
+
onPermissionRequest: input.onPermissionRequest
|
|
3534
|
+
}));
|
|
3535
|
+
turnPromise.catch(() => {});
|
|
3536
|
+
return {
|
|
3537
|
+
requestId: input.requestId,
|
|
3538
|
+
get promptStarted() {
|
|
3539
|
+
return turnPromise.then((turn) => turn.promptStarted);
|
|
3540
|
+
},
|
|
3541
|
+
events: { async *[Symbol.asyncIterator]() {
|
|
3542
|
+
yield* (await turnPromise).events;
|
|
3543
|
+
} },
|
|
3544
|
+
get result() {
|
|
3545
|
+
return turnPromise.then((turn) => turn.result);
|
|
3546
|
+
},
|
|
3547
|
+
cancel(inputArgs) {
|
|
3548
|
+
return turnPromise.then((turn) => turn.cancel(inputArgs));
|
|
3549
|
+
},
|
|
3550
|
+
closeStream(inputArgs) {
|
|
3551
|
+
return turnPromise.then((turn) => turn.closeStream(inputArgs));
|
|
3552
|
+
}
|
|
3553
|
+
};
|
|
3554
|
+
}
|
|
3555
|
+
async *runTurn(input) {
|
|
3556
|
+
const { handle, state } = this.resolveManagerHandle(input.handle);
|
|
3557
|
+
yield* (await this.getManager()).runTurn({
|
|
3558
|
+
handle,
|
|
3559
|
+
text: input.text,
|
|
3560
|
+
attachments: input.attachments,
|
|
3561
|
+
mode: input.mode,
|
|
3562
|
+
sessionMode: state.mode,
|
|
3563
|
+
requestId: input.requestId,
|
|
3564
|
+
timeoutMs: input.timeoutMs,
|
|
3565
|
+
signal: input.signal,
|
|
3566
|
+
assertActive: input.assertActive,
|
|
3567
|
+
onElicitation: input.onElicitation,
|
|
3568
|
+
onPermissionRequest: input.onPermissionRequest
|
|
3569
|
+
});
|
|
3570
|
+
}
|
|
3571
|
+
async getCapabilities(input) {
|
|
3572
|
+
if (!input?.handle) return capabilitiesFromRecord(void 0);
|
|
3573
|
+
const { handle } = this.resolveManagerHandle(input.handle);
|
|
3574
|
+
return capabilitiesFromRecord(await this.options.sessionStore.load(handle.acpxRecordId ?? handle.sessionKey));
|
|
3575
|
+
}
|
|
3576
|
+
async getStatus(input) {
|
|
3577
|
+
const { handle } = this.resolveManagerHandle(input.handle);
|
|
3578
|
+
return await (await this.getManager()).getStatus(handle);
|
|
3579
|
+
}
|
|
3580
|
+
async setMode(input) {
|
|
3581
|
+
const { handle, state } = this.resolveManagerHandle(input.handle);
|
|
3582
|
+
await (await this.getManager()).setMode(handle, input.mode, state.mode, input);
|
|
3583
|
+
}
|
|
3584
|
+
async setModel(input) {
|
|
3585
|
+
const { handle, state } = this.resolveManagerHandle(input.handle);
|
|
3586
|
+
await (await this.getManager()).setModel(handle, input.model, state.mode, input);
|
|
3587
|
+
}
|
|
3588
|
+
async setConfigOption(input) {
|
|
3589
|
+
const { handle, state } = this.resolveManagerHandle(input.handle);
|
|
3590
|
+
return await (await this.getManager()).setConfigOption(handle, input.key, input.value, state.mode, input);
|
|
3591
|
+
}
|
|
3592
|
+
async cancel(input) {
|
|
3593
|
+
const { handle } = this.resolveManagerHandle(input.handle);
|
|
3594
|
+
await (await this.getManager()).cancel(handle);
|
|
3595
|
+
}
|
|
3596
|
+
async prepareFreshSession(input) {
|
|
3597
|
+
const { handle } = this.resolveManagerHandle(input.handle);
|
|
3598
|
+
await (await this.getManager()).prepareFreshSession(handle);
|
|
3599
|
+
}
|
|
3600
|
+
async close(input) {
|
|
3601
|
+
const { handle } = this.resolveManagerHandle(input.handle);
|
|
3602
|
+
await (await this.getManager()).close(handle, { discardPersistentState: input.discardPersistentState });
|
|
3603
|
+
}
|
|
3604
|
+
shutdown() {
|
|
3605
|
+
if (!this.shutdownTask) {
|
|
3606
|
+
this.healthy = false;
|
|
3607
|
+
const managerShutdown = this.managerPromise?.then((manager) => manager.shutdown());
|
|
3608
|
+
this.shutdownTask = Promise.allSettled([managerShutdown, ...this.probeTasks]).then(([manager]) => {
|
|
3609
|
+
if (manager.status === "rejected") throw manager.reason;
|
|
3610
|
+
});
|
|
3611
|
+
}
|
|
3612
|
+
return this.shutdownTask;
|
|
3613
|
+
}
|
|
3614
|
+
async getManager() {
|
|
3615
|
+
if (this.shutdownTask) throw new AcpRuntimeError("ACP_BACKEND_UNAVAILABLE", "ACP runtime is shut down.");
|
|
3616
|
+
if (this.manager) return this.manager;
|
|
3617
|
+
if (!this.managerPromise) this.managerPromise = Promise.resolve(this.testOptions?.managerFactory?.(this.options) ?? new AcpRuntimeManager(this.options)).then((manager) => {
|
|
3618
|
+
this.manager = manager;
|
|
3619
|
+
return manager;
|
|
3620
|
+
});
|
|
3621
|
+
return await this.managerPromise;
|
|
3622
|
+
}
|
|
3623
|
+
async runProbe() {
|
|
3624
|
+
if (this.shutdownTask) throw new AcpRuntimeError("ACP_BACKEND_UNAVAILABLE", "ACP runtime is shut down.");
|
|
3625
|
+
const probe = this.testOptions?.probeRunner?.(this.options) ?? this.getManager().then((manager) => manager.probe());
|
|
3626
|
+
this.probeTasks.add(probe);
|
|
3627
|
+
try {
|
|
3628
|
+
const report = await probe;
|
|
3629
|
+
if (this.shutdownTask) throw new AcpRuntimeError("ACP_BACKEND_UNAVAILABLE", "ACP runtime is shut down.");
|
|
3630
|
+
return report;
|
|
3631
|
+
} finally {
|
|
3632
|
+
this.probeTasks.delete(probe);
|
|
3633
|
+
}
|
|
3634
|
+
}
|
|
3635
|
+
resolveManagerHandle(handle) {
|
|
3636
|
+
const state = this.resolveHandleState(handle);
|
|
3637
|
+
return {
|
|
3638
|
+
handle: {
|
|
3639
|
+
...handle,
|
|
3640
|
+
acpxRecordId: state.acpxRecordId ?? handle.acpxRecordId ?? handle.sessionKey
|
|
3641
|
+
},
|
|
3642
|
+
state
|
|
3643
|
+
};
|
|
3644
|
+
}
|
|
3645
|
+
resolveHandleState(handle) {
|
|
3646
|
+
const decoded = decodeAcpxRuntimeHandleState(handle.runtimeSessionName);
|
|
3647
|
+
if (decoded) return {
|
|
3648
|
+
...decoded,
|
|
3649
|
+
acpxRecordId: decoded.acpxRecordId ?? handle.acpxRecordId,
|
|
3650
|
+
backendSessionId: decoded.backendSessionId ?? handle.backendSessionId,
|
|
3651
|
+
agentSessionId: decoded.agentSessionId ?? handle.agentSessionId
|
|
3652
|
+
};
|
|
3653
|
+
const runtimeSessionName = handle.runtimeSessionName.trim();
|
|
3654
|
+
if (!runtimeSessionName) throw new AcpRuntimeError("ACP_SESSION_INIT_FAILED", "Invalid embedded ACP runtime handle: runtimeSessionName is missing.");
|
|
3655
|
+
return {
|
|
3656
|
+
name: runtimeSessionName,
|
|
3657
|
+
agent: deriveAgentFromSessionKey(handle.sessionKey, DEFAULT_AGENT_NAME),
|
|
3658
|
+
cwd: handle.cwd ?? this.options.cwd,
|
|
3659
|
+
mode: "persistent",
|
|
3660
|
+
acpxRecordId: handle.acpxRecordId,
|
|
3661
|
+
backendSessionId: handle.backendSessionId,
|
|
3662
|
+
agentSessionId: handle.agentSessionId
|
|
3663
|
+
};
|
|
3664
|
+
}
|
|
3665
|
+
};
|
|
3666
|
+
function createAcpRuntime(options) {
|
|
3667
|
+
return new AcpxRuntime(options);
|
|
3668
|
+
}
|
|
3669
|
+
function createRuntimeStore(options) {
|
|
3670
|
+
return createFileSessionStore(options);
|
|
3671
|
+
}
|
|
3672
|
+
//#endregion
|
|
3673
|
+
export { ACPX_BACKEND_ID, AcpRuntimeError, AcpxRuntime, DEFAULT_AGENT_NAME, REQUESTED_MODEL_UNSUPPORTED_ERROR_CODE, REQUESTED_MODEL_UNSUPPORTED_REASONS, RequestedModelUnsupportedError, SharedAcpRuntime, createAcpRuntime, createAgentRegistry, createFileSessionStore, createRuntimeStore, createSharedAcpRuntime, createTurnJournal, decodeAcpxRuntimeHandleState, encodeAcpxRuntimeHandleState, inspectAgentModels, isAcpRuntimeError, isRequestedModelUnsupportedError };
|
|
3674
|
+
|
|
3675
|
+
//# sourceMappingURL=runtime.js.map
|