@moxt-ai/mobius 0.0.93 → 0.0.96
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/dist/acp/activity.js +1 -1
- package/dist/acp/activity.js.map +1 -1
- package/dist/acp/codex/agent.d.ts.map +1 -1
- package/dist/acp/codex/agent.js +4 -8
- package/dist/acp/codex/agent.js.map +1 -1
- package/dist/acp/elicitation.d.ts +5 -0
- package/dist/acp/elicitation.d.ts.map +1 -0
- package/dist/acp/elicitation.js +186 -0
- package/dist/acp/elicitation.js.map +1 -0
- package/dist/acp/process-capacity.d.ts +12 -0
- package/dist/acp/process-capacity.d.ts.map +1 -0
- package/dist/acp/process-capacity.js +90 -0
- package/dist/acp/process-capacity.js.map +1 -0
- package/dist/acp/process-session.d.ts +166 -0
- package/dist/acp/process-session.d.ts.map +1 -0
- package/dist/acp/process-session.js +1300 -0
- package/dist/acp/process-session.js.map +1 -0
- package/dist/acp/session-config/apply-session-configuration.d.ts +9 -0
- package/dist/acp/session-config/apply-session-configuration.d.ts.map +1 -0
- package/dist/acp/session-config/apply-session-configuration.js +141 -0
- package/dist/acp/session-config/apply-session-configuration.js.map +1 -0
- package/dist/acp/session-manager.d.ts +8 -161
- package/dist/acp/session-manager.d.ts.map +1 -1
- package/dist/acp/session-manager.js +73 -1571
- package/dist/acp/session-manager.js.map +1 -1
- package/dist/acp/session-store.d.ts +3 -10
- package/dist/acp/session-store.d.ts.map +1 -1
- package/dist/acp/session-store.js +1 -131
- package/dist/acp/session-store.js.map +1 -1
- package/dist/acp/value-utils.d.ts +4 -0
- package/dist/acp/value-utils.d.ts.map +1 -0
- package/dist/acp/value-utils.js +10 -0
- package/dist/acp/value-utils.js.map +1 -0
- package/dist/agent-catalog/agent-settings-adapter.d.ts +5 -18
- package/dist/agent-catalog/agent-settings-adapter.d.ts.map +1 -1
- package/dist/agent-catalog/agent-settings-adapter.js +7 -161
- package/dist/agent-catalog/agent-settings-adapter.js.map +1 -1
- package/dist/agent-catalog/agent-settings-base.d.ts +26 -0
- package/dist/agent-catalog/agent-settings-base.d.ts.map +1 -0
- package/dist/agent-catalog/agent-settings-base.js +66 -0
- package/dist/agent-catalog/agent-settings-base.js.map +1 -0
- package/dist/agent-catalog/agents/codex-settings-adapter.d.ts +5 -0
- package/dist/agent-catalog/agents/codex-settings-adapter.d.ts.map +1 -0
- package/dist/agent-catalog/agents/codex-settings-adapter.js +6 -0
- package/dist/agent-catalog/agents/codex-settings-adapter.js.map +1 -0
- package/dist/agent-catalog/agents/deepseek-settings-adapter.d.ts +9 -0
- package/dist/agent-catalog/agents/deepseek-settings-adapter.d.ts.map +1 -0
- package/dist/agent-catalog/agents/deepseek-settings-adapter.js +26 -0
- package/dist/agent-catalog/agents/deepseek-settings-adapter.js.map +1 -0
- package/dist/agent-catalog/agents/opencode-settings-adapter.d.ts +9 -0
- package/dist/agent-catalog/agents/opencode-settings-adapter.d.ts.map +1 -0
- package/dist/agent-catalog/agents/opencode-settings-adapter.js +74 -0
- package/dist/agent-catalog/agents/opencode-settings-adapter.js.map +1 -0
- package/dist/agent-catalog/discover-agent-settings.d.ts +10 -0
- package/dist/agent-catalog/discover-agent-settings.d.ts.map +1 -0
- package/dist/agent-catalog/discover-agent-settings.js +252 -0
- package/dist/agent-catalog/discover-agent-settings.js.map +1 -0
- package/dist/audit/audit-store.d.ts +3 -4
- package/dist/audit/audit-store.d.ts.map +1 -1
- package/dist/audit/audit-store.js +10 -37
- package/dist/audit/audit-store.js.map +1 -1
- package/dist/cli.js +1699 -1624
- package/dist/cli.js.map +4 -4
- package/dist/config.d.ts +0 -2
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +2 -6
- package/dist/config.js.map +1 -1
- package/dist/daemon-manager.d.ts.map +1 -1
- package/dist/daemon-manager.js +13 -19
- package/dist/daemon-manager.js.map +1 -1
- package/dist/index.js +1696 -1622
- package/dist/index.js.map +4 -4
- package/dist/native-sessions/agent-adapter.d.ts +17 -0
- package/dist/native-sessions/agent-adapter.d.ts.map +1 -0
- package/dist/native-sessions/agent-adapter.js +22 -0
- package/dist/native-sessions/agent-adapter.js.map +1 -0
- package/dist/native-sessions/chat-agent.d.ts +3 -0
- package/dist/native-sessions/chat-agent.d.ts.map +1 -0
- package/dist/native-sessions/chat-agent.js +5 -0
- package/dist/native-sessions/chat-agent.js.map +1 -0
- package/dist/native-sessions/claude-adapter.d.ts +3 -0
- package/dist/native-sessions/claude-adapter.d.ts.map +1 -0
- package/dist/native-sessions/claude-adapter.js +7 -0
- package/dist/native-sessions/claude-adapter.js.map +1 -0
- package/dist/native-sessions/claude-history.d.ts +6 -0
- package/dist/native-sessions/claude-history.d.ts.map +1 -0
- package/dist/native-sessions/claude-history.js +27 -0
- package/dist/native-sessions/claude-history.js.map +1 -0
- package/dist/native-sessions/codex-adapter.d.ts +3 -0
- package/dist/native-sessions/codex-adapter.d.ts.map +1 -0
- package/dist/native-sessions/codex-adapter.js +21 -0
- package/dist/native-sessions/codex-adapter.js.map +1 -0
- package/dist/native-sessions/service.d.ts +0 -2
- package/dist/native-sessions/service.d.ts.map +1 -1
- package/dist/native-sessions/service.js +70 -32
- package/dist/native-sessions/service.js.map +1 -1
- package/dist/pairing/pair-local-machine.d.ts.map +1 -1
- package/dist/pairing/pair-local-machine.js +0 -1
- package/dist/pairing/pair-local-machine.js.map +1 -1
- package/dist/relay-connection/coalescing-narration-publisher.d.ts +1 -1
- package/dist/relay-connection/coalescing-narration-publisher.js +1 -1
- package/dist/relay-connection/coalescing-text-publisher.d.ts +1 -1
- package/dist/relay-connection/coalescing-text-publisher.js +1 -1
- package/dist/relay-connection/session-event-outbox.d.ts +4 -5
- package/dist/relay-connection/session-event-outbox.d.ts.map +1 -1
- package/dist/relay-connection/session-event-outbox.js +31 -21
- package/dist/relay-connection/session-event-outbox.js.map +1 -1
- package/dist/run-daemon.d.ts.map +1 -1
- package/dist/run-daemon.js +17 -406
- package/dist/run-daemon.js.map +1 -1
- package/dist/runtime.d.ts +0 -1
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +1633 -1557
- package/dist/runtime.js.map +4 -4
- package/dist/storage/runtime-installation-store.d.ts +0 -1
- package/dist/storage/runtime-installation-store.d.ts.map +1 -1
- package/dist/storage/runtime-installation-store.js +0 -1
- package/dist/storage/runtime-installation-store.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,1574 +1,13 @@
|
|
|
1
|
-
import { spawn } from "node:child_process";
|
|
2
|
-
import { methods, ndJsonStream, PROTOCOL_VERSION, RequestError, } from "@agentclientprotocol/sdk";
|
|
3
|
-
import { AGENT_CONTENT_KIND, decodeAgentPromptResponse, SESSION_COMMANDS_UPDATED_KIND, SESSION_CONFIG_UPDATED_KIND, SESSION_ELICITATION_REQUESTED_KIND, SESSION_ELICITATION_RESOLVED_KIND, SESSION_INFO_UPDATED_KIND, SESSION_PERMISSION_REQUESTED_KIND, SESSION_PERMISSION_RESOLVED_KIND, SESSION_USAGE_UPDATED_KIND, } from "@moxt-ai/mobius-protocol";
|
|
4
|
-
import { readInlineRaster, readLocalRaster } from "../authorization/local-raster.js";
|
|
5
|
-
import { readInlineVideo } from "../authorization/local-video.js";
|
|
6
1
|
import { unmeasuredOperationMetrics } from "../infra/operation-metrics.js";
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import { createAcpClient } from "./create-client.js";
|
|
12
|
-
import { acpEndpointTerminationError, } from "./in-process/acp-endpoint.js";
|
|
13
|
-
import { emitMarkdownChunksWithLocalImages } from "./markdown-images.js";
|
|
14
|
-
import { nativeSessionIdSchema, nativeSessionPageSchema, } from "./native-session.js";
|
|
15
|
-
import { normalizeAcpCapabilities, unsupportedSessionCapabilities } from "./session-capabilities.js";
|
|
16
|
-
import { SessionConfigProtocolError } from "./session-config/session-config-protocol.js";
|
|
17
|
-
import { sessionConfigProtocolForAgent } from "./session-config/session-config-registry.js";
|
|
18
|
-
import { AcpHistoryReplay } from "./session-history.js";
|
|
19
|
-
import { AcpStoredSession, DeletedAcpStoredSession, FoundAcpStoredSession, MemoryAcpSessionStore, } from "./session-store.js";
|
|
20
|
-
const PROCESS_STOP_TIMEOUT_MILLISECONDS = 1_000;
|
|
2
|
+
import { supportsNativeChat } from "../native-sessions/chat-agent.js";
|
|
3
|
+
import { AcpExecutionError } from "./acp-error.js";
|
|
4
|
+
import { AcpProcessCapacityLock, waitForAcpProcessCapacity } from "./process-capacity.js";
|
|
5
|
+
import { DeletedAcpStoredSession, FoundAcpStoredSession, MemoryAcpSessionStore, MissingAcpStoredSession, } from "./session-store.js";
|
|
21
6
|
const MAX_ACP_PROCESSES = 10;
|
|
22
|
-
const MAX_PRE_SESSION_UPDATES = 100;
|
|
23
|
-
const MAX_PRE_SESSION_UPDATE_BYTES = 1024 * 1024;
|
|
24
|
-
const SESSION_CONTROL_COMMAND_ID = "session-control";
|
|
25
7
|
const SESSION_CONTROL_TIMEOUT_MILLISECONDS = 30_000;
|
|
26
|
-
function nativeHistoryNotRetained() {
|
|
27
|
-
return {
|
|
28
|
-
cause: {
|
|
29
|
-
code: "native_history_not_retained",
|
|
30
|
-
message: "Native message history is not retained in the cloud for this Session.",
|
|
31
|
-
},
|
|
32
|
-
status: "unavailable",
|
|
33
|
-
};
|
|
34
|
-
}
|
|
35
|
-
export class NullAcpSessionObserver {
|
|
36
|
-
onCommands = () => Promise.resolve();
|
|
37
|
-
onConfig = () => Promise.resolve();
|
|
38
|
-
onContent = () => Promise.resolve();
|
|
39
|
-
onElicitation = () => Promise.resolve();
|
|
40
|
-
onElicitationResolved = () => Promise.resolve();
|
|
41
|
-
onInfo = () => Promise.resolve();
|
|
42
|
-
onPermission = () => Promise.resolve();
|
|
43
|
-
onPermissionResolved = () => Promise.resolve();
|
|
44
|
-
onUsage = () => Promise.resolve();
|
|
45
|
-
}
|
|
46
|
-
export class AcpPreparedSession {
|
|
47
|
-
agentName;
|
|
48
|
-
agentVersion;
|
|
49
|
-
capabilities;
|
|
50
|
-
commands;
|
|
51
|
-
configOptions;
|
|
52
|
-
restored;
|
|
53
|
-
constructor(agentName, agentVersion, capabilities, commands, configOptions, restored) {
|
|
54
|
-
this.agentName = agentName;
|
|
55
|
-
this.agentVersion = agentVersion;
|
|
56
|
-
this.capabilities = capabilities;
|
|
57
|
-
this.commands = commands;
|
|
58
|
-
this.configOptions = configOptions;
|
|
59
|
-
this.restored = restored;
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
export class AcpAgentSettingsSnapshot {
|
|
63
|
-
agentName;
|
|
64
|
-
agentVersion;
|
|
65
|
-
configOptions;
|
|
66
|
-
constructor(agentName, agentVersion, configOptions) {
|
|
67
|
-
this.agentName = agentName;
|
|
68
|
-
this.agentVersion = agentVersion;
|
|
69
|
-
this.configOptions = configOptions;
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
8
|
export { AcpConfigurationValueUnavailableError, AcpExecutionError } from "./acp-error.js";
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
super("ACP agent initialization failed", { cause });
|
|
76
|
-
this.name = "RetryableAcpInitializationError";
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
class AcpProcessCapacityLease {
|
|
80
|
-
#releaseCapacity;
|
|
81
|
-
#released = false;
|
|
82
|
-
constructor(releaseCapacity) {
|
|
83
|
-
this.#releaseCapacity = releaseCapacity;
|
|
84
|
-
}
|
|
85
|
-
release = () => {
|
|
86
|
-
if (this.#released) {
|
|
87
|
-
return;
|
|
88
|
-
}
|
|
89
|
-
this.#released = true;
|
|
90
|
-
this.#releaseCapacity();
|
|
91
|
-
};
|
|
92
|
-
}
|
|
93
|
-
class AcpProcessCapacityWaiter {
|
|
94
|
-
completion = Promise.withResolvers();
|
|
95
|
-
signal;
|
|
96
|
-
constructor(signal) {
|
|
97
|
-
this.signal = signal;
|
|
98
|
-
}
|
|
99
|
-
cancel = () => {
|
|
100
|
-
try {
|
|
101
|
-
this.signal.throwIfAborted();
|
|
102
|
-
}
|
|
103
|
-
catch (error) {
|
|
104
|
-
this.completion.reject(error);
|
|
105
|
-
}
|
|
106
|
-
};
|
|
107
|
-
}
|
|
108
|
-
class AcpProcessCapacityLock {
|
|
109
|
-
#locked = false;
|
|
110
|
-
#waiters = [];
|
|
111
|
-
acquire = async (signal) => {
|
|
112
|
-
signal.throwIfAborted();
|
|
113
|
-
if (!this.#locked) {
|
|
114
|
-
this.#locked = true;
|
|
115
|
-
return new AcpProcessCapacityLease(this.#release);
|
|
116
|
-
}
|
|
117
|
-
const waiter = new AcpProcessCapacityWaiter(signal);
|
|
118
|
-
this.#waiters.push(waiter);
|
|
119
|
-
signal.addEventListener("abort", waiter.cancel, { once: true });
|
|
120
|
-
if (signal.aborted) {
|
|
121
|
-
waiter.cancel();
|
|
122
|
-
}
|
|
123
|
-
try {
|
|
124
|
-
return await waiter.completion.promise;
|
|
125
|
-
}
|
|
126
|
-
finally {
|
|
127
|
-
signal.removeEventListener("abort", waiter.cancel);
|
|
128
|
-
const index = this.#waiters.indexOf(waiter);
|
|
129
|
-
if (index >= 0) {
|
|
130
|
-
this.#waiters.splice(index, 1);
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
};
|
|
134
|
-
#release = () => {
|
|
135
|
-
while (this.#waiters.length > 0) {
|
|
136
|
-
const waiter = this.#waiters.shift();
|
|
137
|
-
if (waiter === undefined || waiter.signal.aborted) {
|
|
138
|
-
continue;
|
|
139
|
-
}
|
|
140
|
-
waiter.completion.resolve(new AcpProcessCapacityLease(this.#release));
|
|
141
|
-
return;
|
|
142
|
-
}
|
|
143
|
-
this.#locked = false;
|
|
144
|
-
};
|
|
145
|
-
}
|
|
146
|
-
async function waitForAcpProcessCapacity(completion, signal) {
|
|
147
|
-
signal.throwIfAborted();
|
|
148
|
-
const cancelled = Promise.withResolvers();
|
|
149
|
-
const cancel = () => {
|
|
150
|
-
try {
|
|
151
|
-
signal.throwIfAborted();
|
|
152
|
-
}
|
|
153
|
-
catch (error) {
|
|
154
|
-
cancelled.reject(error);
|
|
155
|
-
}
|
|
156
|
-
};
|
|
157
|
-
signal.addEventListener("abort", cancel, { once: true });
|
|
158
|
-
if (signal.aborted) {
|
|
159
|
-
cancel();
|
|
160
|
-
}
|
|
161
|
-
try {
|
|
162
|
-
await Promise.race([completion, cancelled.promise]);
|
|
163
|
-
}
|
|
164
|
-
finally {
|
|
165
|
-
signal.removeEventListener("abort", cancel);
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
function readableWebStream(input) {
|
|
169
|
-
let streamOpen = true;
|
|
170
|
-
return new ReadableStream({
|
|
171
|
-
start(controller) {
|
|
172
|
-
input.on("data", (chunk) => {
|
|
173
|
-
if (!streamOpen) {
|
|
174
|
-
return;
|
|
175
|
-
}
|
|
176
|
-
if (chunk instanceof Uint8Array) {
|
|
177
|
-
controller.enqueue(new Uint8Array(chunk));
|
|
178
|
-
return;
|
|
179
|
-
}
|
|
180
|
-
streamOpen = false;
|
|
181
|
-
controller.error(new Error("ACP process produced a non-binary chunk"));
|
|
182
|
-
});
|
|
183
|
-
input.once("end", () => {
|
|
184
|
-
if (!streamOpen) {
|
|
185
|
-
return;
|
|
186
|
-
}
|
|
187
|
-
streamOpen = false;
|
|
188
|
-
controller.close();
|
|
189
|
-
});
|
|
190
|
-
input.once("error", (error) => {
|
|
191
|
-
if (!streamOpen) {
|
|
192
|
-
return;
|
|
193
|
-
}
|
|
194
|
-
streamOpen = false;
|
|
195
|
-
controller.error(error);
|
|
196
|
-
});
|
|
197
|
-
},
|
|
198
|
-
cancel() {
|
|
199
|
-
streamOpen = false;
|
|
200
|
-
},
|
|
201
|
-
});
|
|
202
|
-
}
|
|
203
|
-
export function createWritableAcpStream(output) {
|
|
204
|
-
let outputFailure;
|
|
205
|
-
const pendingWriteFailures = new Set();
|
|
206
|
-
const fail = (error) => {
|
|
207
|
-
outputFailure = error;
|
|
208
|
-
for (const reject of pendingWriteFailures) {
|
|
209
|
-
reject(error);
|
|
210
|
-
}
|
|
211
|
-
pendingWriteFailures.clear();
|
|
212
|
-
};
|
|
213
|
-
output.on("error", fail);
|
|
214
|
-
output.once("close", () => {
|
|
215
|
-
if (outputFailure === undefined) {
|
|
216
|
-
fail(new Error("ACP process input closed"));
|
|
217
|
-
}
|
|
218
|
-
});
|
|
219
|
-
return new WritableStream({
|
|
220
|
-
write(chunk) {
|
|
221
|
-
if (outputFailure !== undefined) {
|
|
222
|
-
return Promise.reject(outputFailure);
|
|
223
|
-
}
|
|
224
|
-
return new Promise((resolve, reject) => {
|
|
225
|
-
pendingWriteFailures.add(reject);
|
|
226
|
-
output.write(chunk, (error) => {
|
|
227
|
-
pendingWriteFailures.delete(reject);
|
|
228
|
-
if (error) {
|
|
229
|
-
outputFailure = error;
|
|
230
|
-
reject(error);
|
|
231
|
-
return;
|
|
232
|
-
}
|
|
233
|
-
if (outputFailure !== undefined) {
|
|
234
|
-
reject(outputFailure);
|
|
235
|
-
return;
|
|
236
|
-
}
|
|
237
|
-
resolve();
|
|
238
|
-
});
|
|
239
|
-
});
|
|
240
|
-
},
|
|
241
|
-
});
|
|
242
|
-
}
|
|
243
|
-
function truncate(value, maximumLength) {
|
|
244
|
-
return value.length <= maximumLength ? value : `${value.slice(0, Math.max(0, maximumLength - 1))}…`;
|
|
245
|
-
}
|
|
246
|
-
function isRecord(value) {
|
|
247
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
248
|
-
}
|
|
249
|
-
function readString(value, fallback = "") {
|
|
250
|
-
return typeof value === "string" ? value : fallback;
|
|
251
|
-
}
|
|
252
|
-
function arraysEqual(left, right) {
|
|
253
|
-
return left.length === right.length && left.every((value, index) => value === right[index]);
|
|
254
|
-
}
|
|
255
|
-
function recordsEqual(left, right) {
|
|
256
|
-
const leftEntries = Object.entries(left);
|
|
257
|
-
const rightEntries = Object.entries(right);
|
|
258
|
-
return leftEntries.length === rightEntries.length && leftEntries.every(([name, value]) => right[name] === value);
|
|
259
|
-
}
|
|
260
|
-
function elicitationFieldType(value) {
|
|
261
|
-
if (value === "boolean") {
|
|
262
|
-
return "boolean";
|
|
263
|
-
}
|
|
264
|
-
if (value === "integer") {
|
|
265
|
-
return "integer";
|
|
266
|
-
}
|
|
267
|
-
if (value === "number") {
|
|
268
|
-
return "number";
|
|
269
|
-
}
|
|
270
|
-
if (value === "array") {
|
|
271
|
-
return "multiselect";
|
|
272
|
-
}
|
|
273
|
-
return "string";
|
|
274
|
-
}
|
|
275
|
-
function normalizeElicitationOptions(schema) {
|
|
276
|
-
const normalized = [];
|
|
277
|
-
const oneOf = schema["oneOf"];
|
|
278
|
-
if (Array.isArray(oneOf)) {
|
|
279
|
-
for (const option of oneOf) {
|
|
280
|
-
if (isRecord(option) && typeof option["const"] === "string") {
|
|
281
|
-
normalized.push({
|
|
282
|
-
description: truncate(readString(option["description"]), 500),
|
|
283
|
-
label: truncate(readString(option["title"], option["const"]), 255),
|
|
284
|
-
value: truncate(option["const"], 500),
|
|
285
|
-
});
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
return normalized.slice(0, 200);
|
|
289
|
-
}
|
|
290
|
-
const enumValues = schema["enum"];
|
|
291
|
-
if (Array.isArray(enumValues)) {
|
|
292
|
-
for (const entry of enumValues) {
|
|
293
|
-
if (typeof entry === "string") {
|
|
294
|
-
normalized.push({ description: "", label: entry, value: entry });
|
|
295
|
-
}
|
|
296
|
-
}
|
|
297
|
-
return normalized.slice(0, 200);
|
|
298
|
-
}
|
|
299
|
-
const items = schema["items"];
|
|
300
|
-
if (!isRecord(items)) {
|
|
301
|
-
return normalized;
|
|
302
|
-
}
|
|
303
|
-
const anyOf = items["anyOf"];
|
|
304
|
-
if (Array.isArray(anyOf)) {
|
|
305
|
-
return normalizeElicitationOptions({ oneOf: anyOf });
|
|
306
|
-
}
|
|
307
|
-
return normalizeElicitationOptions({ enum: items["enum"] });
|
|
308
|
-
}
|
|
309
|
-
function numericString(value) {
|
|
310
|
-
return typeof value === "number" && Number.isFinite(value) ? value.toString() : "";
|
|
311
|
-
}
|
|
312
|
-
function normalizeElicitationFields(requestedSchema) {
|
|
313
|
-
if (!isRecord(requestedSchema) || !isRecord(requestedSchema["properties"])) {
|
|
314
|
-
return [];
|
|
315
|
-
}
|
|
316
|
-
const properties = requestedSchema["properties"];
|
|
317
|
-
const requiredValues = requestedSchema["required"];
|
|
318
|
-
const required = new Set(Array.isArray(requiredValues) ? requiredValues.filter((entry) => typeof entry === "string") : []);
|
|
319
|
-
const normalized = [];
|
|
320
|
-
for (const [name, property] of Object.entries(properties)) {
|
|
321
|
-
if (!isRecord(property)) {
|
|
322
|
-
continue;
|
|
323
|
-
}
|
|
324
|
-
const type = elicitationFieldType(property["type"]);
|
|
325
|
-
const options = normalizeElicitationOptions(property);
|
|
326
|
-
const normalizedType = type === "string" && options.length > 0 ? "select" : type;
|
|
327
|
-
const defaultValue = property["default"];
|
|
328
|
-
normalized.push({
|
|
329
|
-
defaultBooleanValue: typeof defaultValue === "boolean" ? defaultValue : false,
|
|
330
|
-
defaultNumberValue: typeof defaultValue === "number" && Number.isFinite(defaultValue) ? defaultValue : 0,
|
|
331
|
-
defaultStringValue: typeof defaultValue === "string"
|
|
332
|
-
? truncate(defaultValue, 10_000)
|
|
333
|
-
: Array.isArray(defaultValue)
|
|
334
|
-
? truncate(JSON.stringify(defaultValue), 10_000)
|
|
335
|
-
: "",
|
|
336
|
-
description: truncate(readString(property["description"]), 500),
|
|
337
|
-
format: truncate(readString(property["format"]), 64),
|
|
338
|
-
hasDefaultValue: defaultValue !== undefined && defaultValue !== null,
|
|
339
|
-
maximum: numericString(property["maximum"]),
|
|
340
|
-
maximumLength: numericString(property["maxLength"] ?? property["maxItems"]),
|
|
341
|
-
minimum: numericString(property["minimum"]),
|
|
342
|
-
minimumLength: numericString(property["minLength"] ?? property["minItems"]),
|
|
343
|
-
name: truncate(name, 128),
|
|
344
|
-
options,
|
|
345
|
-
pattern: truncate(readString(property["pattern"]), 500),
|
|
346
|
-
required: required.has(name),
|
|
347
|
-
title: truncate(readString(property["title"], name), 255),
|
|
348
|
-
type: normalizedType,
|
|
349
|
-
});
|
|
350
|
-
}
|
|
351
|
-
return normalized.slice(0, 100);
|
|
352
|
-
}
|
|
353
|
-
function validateStringValue(name, value, schema) {
|
|
354
|
-
const minimum = schema["minLength"];
|
|
355
|
-
const maximum = schema["maxLength"];
|
|
356
|
-
if (typeof minimum === "number" && value.length < minimum) {
|
|
357
|
-
throw new AcpExecutionError(`Elicitation field ${name} is shorter than allowed`, {}, "invalid_elicitation_response");
|
|
358
|
-
}
|
|
359
|
-
if (typeof maximum === "number" && value.length > maximum) {
|
|
360
|
-
throw new AcpExecutionError(`Elicitation field ${name} is longer than allowed`, {}, "invalid_elicitation_response");
|
|
361
|
-
}
|
|
362
|
-
const pattern = schema["pattern"];
|
|
363
|
-
if (typeof pattern === "string" && !new RegExp(pattern, "u").test(value)) {
|
|
364
|
-
throw new AcpExecutionError(`Elicitation field ${name} does not match the required format`, {}, "invalid_elicitation_response");
|
|
365
|
-
}
|
|
366
|
-
const allowed = normalizeElicitationOptions(schema);
|
|
367
|
-
if (allowed.length > 0 && !allowed.some((entry) => entry.value === value)) {
|
|
368
|
-
throw new AcpExecutionError(`Elicitation field ${name} is not an allowed value`, {}, "invalid_elicitation_response");
|
|
369
|
-
}
|
|
370
|
-
}
|
|
371
|
-
function validateNumericValue(name, value, schema, integer) {
|
|
372
|
-
if (!Number.isFinite(value) || (integer && !Number.isInteger(value))) {
|
|
373
|
-
throw new AcpExecutionError(`Elicitation field ${name} is not a valid number`, {}, "invalid_elicitation_response");
|
|
374
|
-
}
|
|
375
|
-
const minimum = schema["minimum"];
|
|
376
|
-
const maximum = schema["maximum"];
|
|
377
|
-
if ((typeof minimum === "number" && value < minimum) || (typeof maximum === "number" && value > maximum)) {
|
|
378
|
-
throw new AcpExecutionError(`Elicitation field ${name} is outside the allowed range`, {}, "invalid_elicitation_response");
|
|
379
|
-
}
|
|
380
|
-
}
|
|
381
|
-
function validateElicitationContent(encoded, requestedSchema) {
|
|
382
|
-
let decoded;
|
|
383
|
-
try {
|
|
384
|
-
decoded = JSON.parse(encoded);
|
|
385
|
-
}
|
|
386
|
-
catch (error) {
|
|
387
|
-
throw new AcpExecutionError("Elicitation response is not valid JSON", { cause: error }, "invalid_elicitation_response");
|
|
388
|
-
}
|
|
389
|
-
if (!isRecord(decoded) || !isRecord(requestedSchema) || !isRecord(requestedSchema["properties"])) {
|
|
390
|
-
throw new AcpExecutionError("Elicitation response does not match the requested form", {}, "invalid_elicitation_response");
|
|
391
|
-
}
|
|
392
|
-
const properties = requestedSchema["properties"];
|
|
393
|
-
const requiredValue = requestedSchema["required"];
|
|
394
|
-
const required = new Set(Array.isArray(requiredValue) ? requiredValue.filter((entry) => typeof entry === "string") : []);
|
|
395
|
-
for (const name of required) {
|
|
396
|
-
if (!(name in decoded)) {
|
|
397
|
-
throw new AcpExecutionError(`Elicitation field ${name} is required`, {}, "invalid_elicitation_response");
|
|
398
|
-
}
|
|
399
|
-
}
|
|
400
|
-
const validated = {};
|
|
401
|
-
for (const [name, value] of Object.entries(decoded)) {
|
|
402
|
-
const property = properties[name];
|
|
403
|
-
if (!isRecord(property)) {
|
|
404
|
-
throw new AcpExecutionError(`Elicitation field ${name} was not requested`, {}, "invalid_elicitation_response");
|
|
405
|
-
}
|
|
406
|
-
if (property["type"] === "string" && typeof value === "string") {
|
|
407
|
-
validateStringValue(name, value, property);
|
|
408
|
-
validated[name] = value;
|
|
409
|
-
continue;
|
|
410
|
-
}
|
|
411
|
-
if (property["type"] === "number" && typeof value === "number") {
|
|
412
|
-
validateNumericValue(name, value, property, false);
|
|
413
|
-
validated[name] = value;
|
|
414
|
-
continue;
|
|
415
|
-
}
|
|
416
|
-
if (property["type"] === "integer" && typeof value === "number") {
|
|
417
|
-
validateNumericValue(name, value, property, true);
|
|
418
|
-
validated[name] = value;
|
|
419
|
-
continue;
|
|
420
|
-
}
|
|
421
|
-
if (property["type"] === "boolean" && typeof value === "boolean") {
|
|
422
|
-
validated[name] = value;
|
|
423
|
-
continue;
|
|
424
|
-
}
|
|
425
|
-
if (property["type"] === "array" && Array.isArray(value) && value.every((entry) => typeof entry === "string")) {
|
|
426
|
-
const minimum = property["minItems"];
|
|
427
|
-
const maximum = property["maxItems"];
|
|
428
|
-
if ((typeof minimum === "number" && value.length < minimum) ||
|
|
429
|
-
(typeof maximum === "number" && value.length > maximum)) {
|
|
430
|
-
throw new AcpExecutionError(`Elicitation field ${name} has an invalid selection count`, {}, "invalid_elicitation_response");
|
|
431
|
-
}
|
|
432
|
-
const allowed = normalizeElicitationOptions(property);
|
|
433
|
-
if (allowed.length > 0 && value.some((entry) => !allowed.some((option) => option.value === entry))) {
|
|
434
|
-
throw new AcpExecutionError(`Elicitation field ${name} contains an invalid selection`, {}, "invalid_elicitation_response");
|
|
435
|
-
}
|
|
436
|
-
validated[name] = value;
|
|
437
|
-
continue;
|
|
438
|
-
}
|
|
439
|
-
throw new AcpExecutionError(`Elicitation field ${name} has the wrong type`, {}, "invalid_elicitation_response");
|
|
440
|
-
}
|
|
441
|
-
return validated;
|
|
442
|
-
}
|
|
443
|
-
class AcpTurnState {
|
|
444
|
-
}
|
|
445
|
-
class IdleAcpTurn extends AcpTurnState {
|
|
446
|
-
commandId = SESSION_CONTROL_COMMAND_ID;
|
|
447
|
-
running = false;
|
|
448
|
-
activities = new AcpActivityTracker(() => Promise.resolve(), () => Promise.resolve());
|
|
449
|
-
onText = () => Promise.resolve();
|
|
450
|
-
}
|
|
451
|
-
class RunningAcpTurn extends AcpTurnState {
|
|
452
|
-
commandId;
|
|
453
|
-
running = true;
|
|
454
|
-
activities;
|
|
455
|
-
onText;
|
|
456
|
-
constructor(commandId, onActivity, onNarration, onText, prepareContent) {
|
|
457
|
-
super();
|
|
458
|
-
this.commandId = commandId;
|
|
459
|
-
this.activities = new AcpActivityTracker(onActivity, onNarration ?? (() => Promise.resolve()), prepareContent);
|
|
460
|
-
this.onText = onText;
|
|
461
|
-
}
|
|
462
|
-
}
|
|
463
|
-
class PendingPermission {
|
|
464
|
-
completion = Promise.withResolvers();
|
|
465
|
-
interactionId;
|
|
466
|
-
optionIds;
|
|
467
|
-
#settled = false;
|
|
468
|
-
constructor(interactionId, optionIds) {
|
|
469
|
-
this.interactionId = interactionId;
|
|
470
|
-
this.optionIds = optionIds;
|
|
471
|
-
}
|
|
472
|
-
cancel = () => {
|
|
473
|
-
if (this.#settled) {
|
|
474
|
-
return false;
|
|
475
|
-
}
|
|
476
|
-
this.#settled = true;
|
|
477
|
-
this.completion.resolve({ outcome: { outcome: "cancelled" } });
|
|
478
|
-
return true;
|
|
479
|
-
};
|
|
480
|
-
select = (optionId) => {
|
|
481
|
-
if (this.#settled) {
|
|
482
|
-
return false;
|
|
483
|
-
}
|
|
484
|
-
this.#settled = true;
|
|
485
|
-
this.completion.resolve({
|
|
486
|
-
outcome: { optionId, outcome: "selected" },
|
|
487
|
-
});
|
|
488
|
-
return true;
|
|
489
|
-
};
|
|
490
|
-
}
|
|
491
|
-
class PendingElicitation {
|
|
492
|
-
completion = Promise.withResolvers();
|
|
493
|
-
elicitationId;
|
|
494
|
-
interactionId;
|
|
495
|
-
requestedSchema;
|
|
496
|
-
#settled = false;
|
|
497
|
-
constructor(interactionId, elicitationId, requestedSchema) {
|
|
498
|
-
this.elicitationId = elicitationId;
|
|
499
|
-
this.interactionId = interactionId;
|
|
500
|
-
this.requestedSchema = requestedSchema;
|
|
501
|
-
}
|
|
502
|
-
accept = (content) => {
|
|
503
|
-
if (this.#settled) {
|
|
504
|
-
return false;
|
|
505
|
-
}
|
|
506
|
-
this.#settled = true;
|
|
507
|
-
this.completion.resolve({ action: "accept", content });
|
|
508
|
-
return true;
|
|
509
|
-
};
|
|
510
|
-
cancel = () => {
|
|
511
|
-
if (this.#settled) {
|
|
512
|
-
return false;
|
|
513
|
-
}
|
|
514
|
-
this.#settled = true;
|
|
515
|
-
this.completion.resolve({ action: "cancel" });
|
|
516
|
-
return true;
|
|
517
|
-
};
|
|
518
|
-
decline = () => {
|
|
519
|
-
if (this.#settled) {
|
|
520
|
-
return false;
|
|
521
|
-
}
|
|
522
|
-
this.#settled = true;
|
|
523
|
-
this.completion.resolve({ action: "decline" });
|
|
524
|
-
return true;
|
|
525
|
-
};
|
|
526
|
-
}
|
|
527
|
-
class AcpProcessSession {
|
|
528
|
-
#additionalDirectories;
|
|
529
|
-
#acceptedUrlElicitations = new Map();
|
|
530
|
-
#agentId;
|
|
531
|
-
#connection;
|
|
532
|
-
#cwd;
|
|
533
|
-
#environment;
|
|
534
|
-
#getObserver;
|
|
535
|
-
#inProcessAgent;
|
|
536
|
-
#mobiusSessionId;
|
|
537
|
-
#pendingElicitations = new Map();
|
|
538
|
-
#pendingPermissions = new Map();
|
|
539
|
-
#preSessionUpdates = [];
|
|
540
|
-
// Both topologies report a terminal outcome, even after a prompt's initial RPC is acknowledged.
|
|
541
|
-
#termination;
|
|
542
|
-
#runtimeChild;
|
|
543
|
-
#metrics;
|
|
544
|
-
#sessionConfigProtocol;
|
|
545
|
-
#store;
|
|
546
|
-
#emittedToolImages = new Set();
|
|
547
|
-
#verifiedAgentVersion;
|
|
548
|
-
#preSessionUpdateBytes = 0;
|
|
549
|
-
#agentName = "";
|
|
550
|
-
#agentVersion = "";
|
|
551
|
-
#bufferedAgentText = [];
|
|
552
|
-
#capabilities = unsupportedSessionCapabilities();
|
|
553
|
-
#commands = [];
|
|
554
|
-
#configRevision = 0;
|
|
555
|
-
#configOptions = [];
|
|
556
|
-
#nativeSessionId = "";
|
|
557
|
-
#prompted = false;
|
|
558
|
-
#replay = {
|
|
559
|
-
kind: "idle",
|
|
560
|
-
};
|
|
561
|
-
#restored = false;
|
|
562
|
-
#sessionTitle = null;
|
|
563
|
-
#sessionUpdatedAt = "";
|
|
564
|
-
#turn = new IdleAcpTurn();
|
|
565
|
-
#updateTail = Promise.resolve();
|
|
566
|
-
constructor(agent, cwd, additionalDirectories, mobiusSessionId, getObserver, store, metrics) {
|
|
567
|
-
this.#additionalDirectories = [...additionalDirectories];
|
|
568
|
-
this.#agentId = agent.id;
|
|
569
|
-
this.#cwd = cwd;
|
|
570
|
-
this.#environment = agent.environment;
|
|
571
|
-
this.#getObserver = getObserver;
|
|
572
|
-
this.#mobiusSessionId = mobiusSessionId;
|
|
573
|
-
this.#metrics = metrics;
|
|
574
|
-
this.#sessionConfigProtocol = sessionConfigProtocolForAgent(agent.id);
|
|
575
|
-
this.#store = store;
|
|
576
|
-
this.#verifiedAgentVersion = agent.agentVersion;
|
|
577
|
-
if (agent.kind === "in-process-acp") {
|
|
578
|
-
// Mobius hosts the ACP Agent in-process and drives the vendor's own protocol, so there is
|
|
579
|
-
// no adapter process to spawn or supervise here. The endpoint owns its own resources.
|
|
580
|
-
const inProcess = agent.createEndpoint({
|
|
581
|
-
command: agent.command,
|
|
582
|
-
cwd,
|
|
583
|
-
environment: agent.environment,
|
|
584
|
-
});
|
|
585
|
-
this.#inProcessAgent = inProcess;
|
|
586
|
-
this.#runtimeChild = null;
|
|
587
|
-
this.#termination = inProcess.terminated;
|
|
588
|
-
this.#connection = createAcpClient(this).connect(inProcess.app());
|
|
589
|
-
return;
|
|
590
|
-
}
|
|
591
|
-
this.#inProcessAgent = null;
|
|
592
|
-
const child = spawn(agent.adapterPath, [...agent.arguments], {
|
|
593
|
-
cwd,
|
|
594
|
-
detached: process.platform !== "win32",
|
|
595
|
-
env: { ...process.env, ...agent.environment },
|
|
596
|
-
shell: false,
|
|
597
|
-
stdio: ["pipe", "pipe", "pipe"],
|
|
598
|
-
});
|
|
599
|
-
this.#runtimeChild = child;
|
|
600
|
-
const stdin = child.stdin;
|
|
601
|
-
const stdout = child.stdout;
|
|
602
|
-
const stderr = child.stderr;
|
|
603
|
-
if (stdin === null || stdout === null || stderr === null) {
|
|
604
|
-
child.kill("SIGKILL");
|
|
605
|
-
throw new AcpExecutionError("ACP process streams are unavailable");
|
|
606
|
-
}
|
|
607
|
-
stderr.setEncoding("utf8");
|
|
608
|
-
stderr.on("data", (chunk) => {
|
|
609
|
-
process.stderr.write(`[${agent.id}-acp] ${chunk}`);
|
|
610
|
-
});
|
|
611
|
-
this.#termination = new Promise((resolve) => {
|
|
612
|
-
child.once("error", (cause) => {
|
|
613
|
-
resolve({ kind: "failed", error: new AcpExecutionError("The ACP process could not run", { cause }) });
|
|
614
|
-
});
|
|
615
|
-
child.once("exit", (code, signal) => {
|
|
616
|
-
resolve({
|
|
617
|
-
kind: "failed",
|
|
618
|
-
error: new AcpExecutionError("The ACP process stopped", { cause: { code, signal } }),
|
|
619
|
-
});
|
|
620
|
-
});
|
|
621
|
-
});
|
|
622
|
-
const stream = ndJsonStream(createWritableAcpStream(stdin), readableWebStream(stdout));
|
|
623
|
-
this.#connection = createAcpClient(this).connect(stream);
|
|
624
|
-
}
|
|
625
|
-
static async #start(options, getObserver, store, initialize, metrics) {
|
|
626
|
-
for (let attempt = 1; attempt <= 2; attempt += 1) {
|
|
627
|
-
options.signal.throwIfAborted();
|
|
628
|
-
const unchanged = await metrics.measure("executable-validation", async () => await Promise.all([
|
|
629
|
-
// Only the adapter topology has an adapter executable to revalidate.
|
|
630
|
-
options.agent.kind === "acp-adapter-process"
|
|
631
|
-
? revalidateExecutable(options.agent.adapterIdentity)
|
|
632
|
-
: Promise.resolve(true),
|
|
633
|
-
revalidateExecutable(options.agent.agentIdentity),
|
|
634
|
-
]));
|
|
635
|
-
options.signal.throwIfAborted();
|
|
636
|
-
if (unchanged.some((result) => !result)) {
|
|
637
|
-
throw new AcpExecutionError("The local Agent runtime changed; restart Mobius before starting a new conversation", {}, "agent_runtime_changed");
|
|
638
|
-
}
|
|
639
|
-
const runtime = metrics.measureSync("process-spawn", () => new AcpProcessSession(options.agent, options.cwd, options.additionalDirectories, options.sessionId, getObserver, store, metrics));
|
|
640
|
-
try {
|
|
641
|
-
await initialize(runtime);
|
|
642
|
-
return runtime;
|
|
643
|
-
}
|
|
644
|
-
catch (error) {
|
|
645
|
-
await runtime.closeProcess();
|
|
646
|
-
options.signal.throwIfAborted();
|
|
647
|
-
if (error instanceof RetryableAcpInitializationError && attempt === 1) {
|
|
648
|
-
console.warn(`[${options.agent.id}-acp] ACP agent initialization failed; retrying once`);
|
|
649
|
-
continue;
|
|
650
|
-
}
|
|
651
|
-
if (error instanceof AcpExecutionError) {
|
|
652
|
-
throw error;
|
|
653
|
-
}
|
|
654
|
-
throw new AcpExecutionError("ACP agent initialization failed", {
|
|
655
|
-
cause: error,
|
|
656
|
-
});
|
|
657
|
-
}
|
|
658
|
-
}
|
|
659
|
-
throw new AcpExecutionError("ACP agent initialization failed");
|
|
660
|
-
}
|
|
661
|
-
static start = async (options, getObserver, store, metrics = unmeasuredOperationMetrics) => await AcpProcessSession.#start(options, getObserver, store, async (runtime) => await runtime.initialize(options.signal, options.origin), metrics);
|
|
662
|
-
static startNativeSessionBrowser = async (options, getObserver, store) => await AcpProcessSession.#start(options, getObserver, store, async (runtime) => await runtime.#initializeAgent(options.signal), unmeasuredOperationMetrics);
|
|
663
|
-
static startSessionForkAtTurn = async (options, sourceNativeSessionId, forkPoint, getObserver, store) => await AcpProcessSession.#start(options, getObserver, store, async (runtime) => await runtime.initialize(options.signal, { kind: "fork", nativeSessionId: sourceNativeSessionId }, forkPoint), unmeasuredOperationMetrics);
|
|
664
|
-
belongsTo = (agentId, cwd, additionalDirectories) => this.#agentId === agentId &&
|
|
665
|
-
this.#cwd === cwd &&
|
|
666
|
-
arraysEqual(this.#additionalDirectories, additionalDirectories);
|
|
667
|
-
usesEnvironment = (environment) => recordsEqual(this.#environment, environment);
|
|
668
|
-
canRebind = () => !this.#prompted && !this.#turn.running;
|
|
669
|
-
hasRunningTurn = () => this.#turn.running;
|
|
670
|
-
prepared = () => new AcpPreparedSession(this.#agentName, this.#agentVersion, this.#capabilities, this.#commands, this.#configOptions, this.#restored);
|
|
671
|
-
loadHistory = async (signal) => {
|
|
672
|
-
if (!this.#capabilities.loadSession) {
|
|
673
|
-
return {
|
|
674
|
-
status: "unavailable",
|
|
675
|
-
cause: {
|
|
676
|
-
code: "native_history_unsupported",
|
|
677
|
-
message: "This Agent restores context but does not provide message history.",
|
|
678
|
-
},
|
|
679
|
-
};
|
|
680
|
-
}
|
|
681
|
-
const history = new AcpHistoryReplay();
|
|
682
|
-
this.#replay = { kind: "capture", history };
|
|
683
|
-
try {
|
|
684
|
-
await this.race(this.#connection.agent.request(methods.agent.session.load, {
|
|
685
|
-
additionalDirectories: [...this.#additionalDirectories],
|
|
686
|
-
cwd: this.#cwd,
|
|
687
|
-
mcpServers: [],
|
|
688
|
-
sessionId: this.#nativeSessionId,
|
|
689
|
-
}, { cancellationSignal: signal }), "ACP agent exited while loading history", signal);
|
|
690
|
-
await this.#updateTail;
|
|
691
|
-
signal.throwIfAborted();
|
|
692
|
-
return await embedLocalHistoryImages(await history.snapshot(), signal);
|
|
693
|
-
}
|
|
694
|
-
finally {
|
|
695
|
-
this.#replay = { kind: "idle" };
|
|
696
|
-
}
|
|
697
|
-
};
|
|
698
|
-
emitAgentMessage = async (chunks, messageId) => {
|
|
699
|
-
const signal = AbortSignal.timeout(20_000);
|
|
700
|
-
await emitMarkdownChunksWithLocalImages({
|
|
701
|
-
chunks,
|
|
702
|
-
onImage: async (image) => await this.emitRaster(image, messageId, signal),
|
|
703
|
-
onText: async (content) => await this.#turn.onText(content, messageId),
|
|
704
|
-
signal,
|
|
705
|
-
});
|
|
706
|
-
};
|
|
707
|
-
bufferAgentText = async (text, messageId) => {
|
|
708
|
-
const previous = this.#bufferedAgentText.at(-1);
|
|
709
|
-
if (previous?.messageId === messageId) {
|
|
710
|
-
this.#bufferedAgentText = [
|
|
711
|
-
...this.#bufferedAgentText.slice(0, -1),
|
|
712
|
-
{ chunks: [...previous.chunks, text], messageId },
|
|
713
|
-
];
|
|
714
|
-
return;
|
|
715
|
-
}
|
|
716
|
-
this.#bufferedAgentText = [...this.#bufferedAgentText, { chunks: [text], messageId }];
|
|
717
|
-
};
|
|
718
|
-
flushAgentText = async () => {
|
|
719
|
-
const buffered = this.#bufferedAgentText;
|
|
720
|
-
this.#bufferedAgentText = [];
|
|
721
|
-
for (const message of buffered) {
|
|
722
|
-
await this.emitAgentMessage(message.chunks, message.messageId);
|
|
723
|
-
}
|
|
724
|
-
};
|
|
725
|
-
recordBufferedAgentTextAsProgress = async () => {
|
|
726
|
-
const buffered = this.#bufferedAgentText;
|
|
727
|
-
this.#bufferedAgentText = [];
|
|
728
|
-
for (const message of buffered) {
|
|
729
|
-
for (const chunk of message.chunks) {
|
|
730
|
-
await this.#turn.activities.recordNarrative("progress", message.messageId, chunk);
|
|
731
|
-
}
|
|
732
|
-
}
|
|
733
|
-
};
|
|
734
|
-
prepareAgentContent = async (content) => {
|
|
735
|
-
if (content.type === "image" && content.uri.length > 0) {
|
|
736
|
-
const signal = AbortSignal.timeout(20_000);
|
|
737
|
-
const raster = await readLocalRaster(content.uri, signal);
|
|
738
|
-
if (raster !== null) {
|
|
739
|
-
return await this.importRaster(raster, signal);
|
|
740
|
-
}
|
|
741
|
-
}
|
|
742
|
-
if (content.type === "image" && content.data.length > 0) {
|
|
743
|
-
const raster = readInlineRaster(content.data, content.name);
|
|
744
|
-
if (raster !== null) {
|
|
745
|
-
return await this.importRaster(raster, AbortSignal.timeout(20_000));
|
|
746
|
-
}
|
|
747
|
-
}
|
|
748
|
-
if (content.type === "video" && content.data.length > 0) {
|
|
749
|
-
const video = readInlineVideo(content.data, content.mimeType, content.name);
|
|
750
|
-
if (video === null) {
|
|
751
|
-
return { ...content, data: "" };
|
|
752
|
-
}
|
|
753
|
-
return this.importVideo(video);
|
|
754
|
-
}
|
|
755
|
-
return content;
|
|
756
|
-
};
|
|
757
|
-
emitAgentContent = async (content, messageId) => {
|
|
758
|
-
const prepared = await this.prepareAgentContent(content);
|
|
759
|
-
await this.#getObserver().onContent({
|
|
760
|
-
commandId: this.#turn.commandId,
|
|
761
|
-
content: prepared,
|
|
762
|
-
contentId: `content-${crypto.randomUUID()}`,
|
|
763
|
-
kind: AGENT_CONTENT_KIND,
|
|
764
|
-
messageId,
|
|
765
|
-
sessionId: this.#mobiusSessionId,
|
|
766
|
-
});
|
|
767
|
-
};
|
|
768
|
-
emitToolImages = async (update) => {
|
|
769
|
-
if (update.status !== "completed") {
|
|
770
|
-
return;
|
|
771
|
-
}
|
|
772
|
-
for (const [index, item] of (update.content ?? []).entries()) {
|
|
773
|
-
if (item.type !== "content" || item.content.type !== "image") {
|
|
774
|
-
continue;
|
|
775
|
-
}
|
|
776
|
-
const key = `${update.toolCallId}:${index.toString()}`;
|
|
777
|
-
if (this.#emittedToolImages.has(key)) {
|
|
778
|
-
continue;
|
|
779
|
-
}
|
|
780
|
-
this.#emittedToolImages.add(key);
|
|
781
|
-
await this.emitAgentContent(normalizeContentBlock(item.content), `tool-${key}`);
|
|
782
|
-
}
|
|
783
|
-
};
|
|
784
|
-
emitRaster = async (raster, messageId, signal) => {
|
|
785
|
-
const content = await this.importRaster(raster, signal);
|
|
786
|
-
await this.#getObserver().onContent({
|
|
787
|
-
commandId: this.#turn.commandId,
|
|
788
|
-
content,
|
|
789
|
-
contentId: `content-${crypto.randomUUID()}`,
|
|
790
|
-
kind: AGENT_CONTENT_KIND,
|
|
791
|
-
messageId,
|
|
792
|
-
sessionId: this.#mobiusSessionId,
|
|
793
|
-
});
|
|
794
|
-
};
|
|
795
|
-
importRaster = async (raster, _signal) => {
|
|
796
|
-
if (raster.sourceUri.length > 0) {
|
|
797
|
-
return {
|
|
798
|
-
...imageDisplayContent(raster.mimeType, raster.name, "", ""),
|
|
799
|
-
uri: raster.sourceUri,
|
|
800
|
-
};
|
|
801
|
-
}
|
|
802
|
-
return imageDisplayContent(raster.mimeType, raster.name, await raster.base64(), "");
|
|
803
|
-
};
|
|
804
|
-
importVideo = (video) => ({
|
|
805
|
-
artifactId: "",
|
|
806
|
-
data: video.base64(),
|
|
807
|
-
mimeType: video.mimeType,
|
|
808
|
-
name: video.name,
|
|
809
|
-
newText: "",
|
|
810
|
-
oldText: "",
|
|
811
|
-
path: "",
|
|
812
|
-
terminalId: "",
|
|
813
|
-
text: "",
|
|
814
|
-
type: "video",
|
|
815
|
-
uri: "",
|
|
816
|
-
});
|
|
817
|
-
async #initializeAgent(signal) {
|
|
818
|
-
await this.#metrics.measure("agent-initialize", async () => await this.#initializeAgentOperation(signal));
|
|
819
|
-
}
|
|
820
|
-
async #initializeAgentOperation(signal) {
|
|
821
|
-
if (this.#inProcessAgent !== null) {
|
|
822
|
-
// The ACP agent runs in this process, but it still owns an app-server child that must
|
|
823
|
-
// start and complete its own handshake before the ACP conversation can begin.
|
|
824
|
-
await this.race(this.#inProcessAgent.initialize(signal), "The Codex app-server exited during initialization", signal).catch((cause) => {
|
|
825
|
-
signal.throwIfAborted();
|
|
826
|
-
throw new RetryableAcpInitializationError(cause);
|
|
827
|
-
});
|
|
828
|
-
}
|
|
829
|
-
const initialized = await this.race(this.#connection.agent.request(methods.agent.initialize, {
|
|
830
|
-
clientCapabilities: {
|
|
831
|
-
elicitation: { form: {}, url: {} },
|
|
832
|
-
plan: {},
|
|
833
|
-
session: { configOptions: { boolean: {} } },
|
|
834
|
-
},
|
|
835
|
-
clientInfo: { name: "mobius", version: "0.0.3" },
|
|
836
|
-
protocolVersion: PROTOCOL_VERSION,
|
|
837
|
-
}, { cancellationSignal: signal }), "ACP agent exited during initialization", signal).catch((cause) => {
|
|
838
|
-
signal.throwIfAborted();
|
|
839
|
-
throw new RetryableAcpInitializationError(cause);
|
|
840
|
-
});
|
|
841
|
-
if (initialized.protocolVersion !== PROTOCOL_VERSION) {
|
|
842
|
-
throw new AcpExecutionError("ACP agent selected an unsupported protocol version", {}, "unsupported_acp_protocol");
|
|
843
|
-
}
|
|
844
|
-
this.#capabilities = normalizeAcpCapabilities(initialized);
|
|
845
|
-
this.#agentName = truncate(initialized.agentInfo?.title ?? initialized.agentInfo?.name ?? this.#agentId, 255);
|
|
846
|
-
this.#agentVersion = truncate(this.#verifiedAgentVersion.length > 0 ? this.#verifiedAgentVersion : (initialized.agentInfo?.version ?? ""), 128);
|
|
847
|
-
}
|
|
848
|
-
initialize = async (signal, origin, forkPoint) => {
|
|
849
|
-
await this.#initializeAgent(signal);
|
|
850
|
-
let stored = this.#metrics.measureSync("session-state-read", () => origin?.kind === "import"
|
|
851
|
-
? new FoundAcpStoredSession(new AcpStoredSession(this.#mobiusSessionId, this.#agentId, nativeSessionIdSchema.parse(origin.nativeSessionId), this.#cwd, this.#additionalDirectories, true))
|
|
852
|
-
: this.#store.read(this.#mobiusSessionId));
|
|
853
|
-
if (stored instanceof FoundAcpStoredSession && !stored.session.prompted) {
|
|
854
|
-
this.#store.remove(this.#mobiusSessionId);
|
|
855
|
-
stored = this.#metrics.measureSync("session-state-read", () => this.#store.read(this.#mobiusSessionId));
|
|
856
|
-
}
|
|
857
|
-
if (stored instanceof DeletedAcpStoredSession) {
|
|
858
|
-
throw new AcpExecutionError("The native Agent session was deleted. Start a new chat.", {}, "native_session_deleted");
|
|
859
|
-
}
|
|
860
|
-
let lifecycleResponse;
|
|
861
|
-
if (origin?.kind === "fork") {
|
|
862
|
-
if (!this.#capabilities.unstableForkSession) {
|
|
863
|
-
throw new AcpExecutionError("This Agent does not support session forking", {}, "native_session_unsupported");
|
|
864
|
-
}
|
|
865
|
-
if (this.#additionalDirectories.length > 0 && !this.#capabilities.additionalDirectories) {
|
|
866
|
-
throw new AcpExecutionError("This Agent cannot restore additional working directories", {}, "native_session_unsupported");
|
|
867
|
-
}
|
|
868
|
-
const forked = await this.#metrics.measure("session-fork", async () => await this.race(this.#connection.agent.request(methods.agent.session.fork, {
|
|
869
|
-
sessionId: nativeSessionIdSchema.parse(origin.nativeSessionId),
|
|
870
|
-
cwd: this.#cwd,
|
|
871
|
-
additionalDirectories: [...this.#additionalDirectories],
|
|
872
|
-
mcpServers: [],
|
|
873
|
-
...(forkPoint === undefined
|
|
874
|
-
? {}
|
|
875
|
-
: {
|
|
876
|
-
_meta: {
|
|
877
|
-
jetbrains: {
|
|
878
|
-
air: {
|
|
879
|
-
fork: {
|
|
880
|
-
version: 1,
|
|
881
|
-
messageFingerprint: forkPoint.messageFingerprint,
|
|
882
|
-
messageId: forkPoint.messageId,
|
|
883
|
-
messageOccurrence: forkPoint.messageOccurrence,
|
|
884
|
-
},
|
|
885
|
-
},
|
|
886
|
-
},
|
|
887
|
-
},
|
|
888
|
-
}),
|
|
889
|
-
}, { cancellationSignal: signal }), "ACP agent exited while forking a session", signal));
|
|
890
|
-
this.selectNativeSession(forked.sessionId);
|
|
891
|
-
if (this.#nativeSessionId === origin.nativeSessionId ||
|
|
892
|
-
this.#store.findNative(this.#agentId, this.#nativeSessionId).length > 0) {
|
|
893
|
-
throw new AcpExecutionError("The Agent did not create an independent fork", {}, "invalid_native_session_response");
|
|
894
|
-
}
|
|
895
|
-
this.#prompted = true;
|
|
896
|
-
this.#restored = true;
|
|
897
|
-
lifecycleResponse = forked;
|
|
898
|
-
}
|
|
899
|
-
else if (stored instanceof FoundAcpStoredSession &&
|
|
900
|
-
stored.session.agentId === this.#agentId &&
|
|
901
|
-
stored.session.cwd === this.#cwd &&
|
|
902
|
-
arraysEqual(stored.session.additionalDirectories, this.#additionalDirectories)) {
|
|
903
|
-
this.selectNativeSession(stored.session.nativeSessionId);
|
|
904
|
-
this.#prompted = stored.session.prompted;
|
|
905
|
-
this.#restored = true;
|
|
906
|
-
if (this.#capabilities.resumeSession) {
|
|
907
|
-
lifecycleResponse = await this.#metrics.measure("session-resume", async () => await this.race(this.#connection.agent.request(methods.agent.session.resume, {
|
|
908
|
-
additionalDirectories: [...this.#additionalDirectories],
|
|
909
|
-
cwd: this.#cwd,
|
|
910
|
-
mcpServers: [],
|
|
911
|
-
sessionId: this.#nativeSessionId,
|
|
912
|
-
}, { cancellationSignal: signal }), "ACP agent exited while resuming a session", signal));
|
|
913
|
-
}
|
|
914
|
-
else if (this.#capabilities.loadSession) {
|
|
915
|
-
this.#replay = { kind: "discard" };
|
|
916
|
-
try {
|
|
917
|
-
lifecycleResponse = await this.#metrics.measure("session-load", async () => await this.race(this.#connection.agent.request(methods.agent.session.load, {
|
|
918
|
-
additionalDirectories: [...this.#additionalDirectories],
|
|
919
|
-
cwd: this.#cwd,
|
|
920
|
-
mcpServers: [],
|
|
921
|
-
sessionId: this.#nativeSessionId,
|
|
922
|
-
}, { cancellationSignal: signal }), "ACP agent exited while loading a session", signal));
|
|
923
|
-
}
|
|
924
|
-
finally {
|
|
925
|
-
await this.#updateTail;
|
|
926
|
-
this.#replay = { kind: "idle" };
|
|
927
|
-
}
|
|
928
|
-
}
|
|
929
|
-
else {
|
|
930
|
-
throw new AcpExecutionError("The ACP agent cannot restore its persisted session", {}, "session_restore_unsupported");
|
|
931
|
-
}
|
|
932
|
-
}
|
|
933
|
-
else {
|
|
934
|
-
if (stored instanceof FoundAcpStoredSession) {
|
|
935
|
-
if (stored.session.prompted) {
|
|
936
|
-
throw new AcpExecutionError("The agent or workspace cannot change after a conversation has started", {}, "session_identity_mismatch");
|
|
937
|
-
}
|
|
938
|
-
this.#store.remove(this.#mobiusSessionId);
|
|
939
|
-
}
|
|
940
|
-
const created = await this.#metrics.measure("session-new", async () => await this.race(this.#connection.agent.request(methods.agent.session.new, {
|
|
941
|
-
additionalDirectories: [...this.#additionalDirectories],
|
|
942
|
-
cwd: this.#cwd,
|
|
943
|
-
mcpServers: [],
|
|
944
|
-
}, { cancellationSignal: signal }), "ACP agent exited while starting a session", signal));
|
|
945
|
-
this.selectNativeSession(created.sessionId);
|
|
946
|
-
lifecycleResponse = created;
|
|
947
|
-
}
|
|
948
|
-
this.#configOptions = this.#sessionConfigProtocol.normalizeLifecycle(lifecycleResponse);
|
|
949
|
-
await this.#updateTail;
|
|
950
|
-
signal.throwIfAborted();
|
|
951
|
-
if (this.#prompted) {
|
|
952
|
-
this.#store.write(new AcpStoredSession(this.#mobiusSessionId, this.#agentId, this.#nativeSessionId, this.#cwd, this.#additionalDirectories, true));
|
|
953
|
-
}
|
|
954
|
-
};
|
|
955
|
-
listNativeSessions = async (cursor, signal) => {
|
|
956
|
-
if (!this.#capabilities.listSessions) {
|
|
957
|
-
throw new AcpExecutionError("This Agent does not support native session listing", {}, "native_session_unsupported");
|
|
958
|
-
}
|
|
959
|
-
const response = await this.race(this.#connection.agent.request(methods.agent.session.list, cursor === null ? {} : { cursor }, {
|
|
960
|
-
cancellationSignal: signal,
|
|
961
|
-
}), "ACP agent exited while listing sessions", signal);
|
|
962
|
-
const decoded = nativeSessionPageSchema.safeParse(response);
|
|
963
|
-
if (!decoded.success) {
|
|
964
|
-
throw new AcpExecutionError("The Agent returned an invalid native session list", { cause: decoded.error }, "invalid_native_session_response");
|
|
965
|
-
}
|
|
966
|
-
return decoded.data;
|
|
967
|
-
};
|
|
968
|
-
deleteNativeSession = async (nativeSessionId, signal) => {
|
|
969
|
-
if (!this.#capabilities.deleteSession || !this.#capabilities.listSessions) {
|
|
970
|
-
throw new AcpExecutionError("This Agent does not support native session deletion", {}, "native_session_unsupported");
|
|
971
|
-
}
|
|
972
|
-
await this.race(this.#connection.agent.request(methods.agent.session.delete, { sessionId: nativeSessionIdSchema.parse(nativeSessionId) }, { cancellationSignal: signal }), "ACP agent exited while deleting a session", signal);
|
|
973
|
-
};
|
|
974
|
-
nativeSessionId = () => this.#nativeSessionId;
|
|
975
|
-
configure = async (options) => {
|
|
976
|
-
const existing = this.#configOptions.find((option) => option.id === options.configId);
|
|
977
|
-
if (existing === undefined || existing.type !== options.valueType) {
|
|
978
|
-
throw new AcpExecutionError("The requested ACP configuration option is unavailable", {}, "invalid_session_configuration");
|
|
979
|
-
}
|
|
980
|
-
if (existing.type === "select") {
|
|
981
|
-
if (existing.values.length < 2) {
|
|
982
|
-
throw new AcpExecutionError("The requested ACP configuration option is unavailable", {}, "invalid_session_configuration");
|
|
983
|
-
}
|
|
984
|
-
if (!existing.values.some((entry) => entry.value === options.value)) {
|
|
985
|
-
throw new AcpConfigurationValueUnavailableError(options.configId, options.value, existing.values.map((entry) => entry.value));
|
|
986
|
-
}
|
|
987
|
-
}
|
|
988
|
-
const configRevision = this.#configRevision;
|
|
989
|
-
try {
|
|
990
|
-
const configured = await this.#sessionConfigProtocol.configure(this.#configOptions, options, this.#nativeSessionId, {
|
|
991
|
-
request: async (method, params, failureMessage, signal) => await this.race(this.#connection.agent.request(method, params, {
|
|
992
|
-
cancellationSignal: signal,
|
|
993
|
-
}), failureMessage, signal),
|
|
994
|
-
});
|
|
995
|
-
const applied = configured.find((option) => option.id === options.configId);
|
|
996
|
-
if (applied === undefined ||
|
|
997
|
-
applied.type !== options.valueType ||
|
|
998
|
-
(applied.type === "boolean" && applied.booleanValue !== options.booleanValue) ||
|
|
999
|
-
(applied.type === "select" && applied.currentValue !== options.value)) {
|
|
1000
|
-
throw new AcpExecutionError("The Agent did not apply the requested session configuration", {}, "invalid_session_configuration");
|
|
1001
|
-
}
|
|
1002
|
-
await this.#updateTail;
|
|
1003
|
-
if (this.#configRevision === configRevision) {
|
|
1004
|
-
this.#configOptions = configured;
|
|
1005
|
-
}
|
|
1006
|
-
}
|
|
1007
|
-
catch (error) {
|
|
1008
|
-
if (error instanceof SessionConfigProtocolError) {
|
|
1009
|
-
throw new AcpExecutionError(error.message, { cause: error }, error.code);
|
|
1010
|
-
}
|
|
1011
|
-
throw error;
|
|
1012
|
-
}
|
|
1013
|
-
return this.#configOptions;
|
|
1014
|
-
};
|
|
1015
|
-
buildPrompt = (options) => {
|
|
1016
|
-
if (options.images.length > 0 && !this.#capabilities.imagePrompt) {
|
|
1017
|
-
throw new AcpExecutionError("The selected agent does not accept image prompts", {}, "unsupported_prompt_content");
|
|
1018
|
-
}
|
|
1019
|
-
if (options.resources.some((resource) => resource.type === "embedded") &&
|
|
1020
|
-
!this.#capabilities.embeddedContextPrompt) {
|
|
1021
|
-
throw new AcpExecutionError("The selected agent does not accept embedded context", {}, "unsupported_prompt_content");
|
|
1022
|
-
}
|
|
1023
|
-
const prompt = [];
|
|
1024
|
-
if (options.prompt.length > 0) {
|
|
1025
|
-
prompt.push({ text: options.prompt, type: "text" });
|
|
1026
|
-
}
|
|
1027
|
-
for (const image of options.images) {
|
|
1028
|
-
prompt.push({
|
|
1029
|
-
_meta: { mobius: { name: image.name } },
|
|
1030
|
-
data: image.data,
|
|
1031
|
-
mimeType: image.mimeType,
|
|
1032
|
-
type: "image",
|
|
1033
|
-
});
|
|
1034
|
-
}
|
|
1035
|
-
for (const resource of options.resources) {
|
|
1036
|
-
if (resource.type === "embedded") {
|
|
1037
|
-
prompt.push({
|
|
1038
|
-
resource: {
|
|
1039
|
-
mimeType: resource.mimeType,
|
|
1040
|
-
text: resource.text,
|
|
1041
|
-
uri: resource.uri,
|
|
1042
|
-
},
|
|
1043
|
-
type: "resource",
|
|
1044
|
-
});
|
|
1045
|
-
}
|
|
1046
|
-
else {
|
|
1047
|
-
prompt.push({
|
|
1048
|
-
mimeType: resource.mimeType,
|
|
1049
|
-
name: resource.name,
|
|
1050
|
-
type: "resource_link",
|
|
1051
|
-
uri: resource.uri,
|
|
1052
|
-
});
|
|
1053
|
-
}
|
|
1054
|
-
}
|
|
1055
|
-
if (prompt.length === 0) {
|
|
1056
|
-
throw new AcpExecutionError("A prompt must contain text or an attachment", {}, "empty_prompt");
|
|
1057
|
-
}
|
|
1058
|
-
return prompt;
|
|
1059
|
-
};
|
|
1060
|
-
prompt = async (options) => {
|
|
1061
|
-
if (this.#turn.running) {
|
|
1062
|
-
throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
|
|
1063
|
-
}
|
|
1064
|
-
const prompt = this.buildPrompt(options);
|
|
1065
|
-
this.#store.write(new AcpStoredSession(this.#mobiusSessionId, this.#agentId, this.#nativeSessionId, this.#cwd, this.#additionalDirectories, true));
|
|
1066
|
-
this.#prompted = true;
|
|
1067
|
-
const running = new RunningAcpTurn(options.commandId, options.onActivity, options.onNarration, options.onText, this.prepareAgentContent);
|
|
1068
|
-
this.#turn = running;
|
|
1069
|
-
try {
|
|
1070
|
-
const response = await this.race(this.#connection.agent.request(methods.agent.session.prompt, { prompt, sessionId: this.#nativeSessionId }, { cancellationSignal: options.signal }), "ACP agent exited during a prompt", options.signal);
|
|
1071
|
-
await this.#updateTail;
|
|
1072
|
-
await this.flushAgentText();
|
|
1073
|
-
await running.activities.finish();
|
|
1074
|
-
let result;
|
|
1075
|
-
try {
|
|
1076
|
-
result = decodeAgentPromptResponse(response);
|
|
1077
|
-
}
|
|
1078
|
-
catch (cause) {
|
|
1079
|
-
throw new AcpExecutionError("ACP agent returned an invalid prompt response", { cause }, "acp_invalid_prompt_response");
|
|
1080
|
-
}
|
|
1081
|
-
if (result.usage != null || result._meta?.quota !== undefined) {
|
|
1082
|
-
await this.#getObserver().onUsage({
|
|
1083
|
-
_meta: result._meta ?? null,
|
|
1084
|
-
commandId: options.commandId,
|
|
1085
|
-
kind: SESSION_USAGE_UPDATED_KIND,
|
|
1086
|
-
sessionId: this.#mobiusSessionId,
|
|
1087
|
-
source: "prompt",
|
|
1088
|
-
usage: result.usage ?? null,
|
|
1089
|
-
});
|
|
1090
|
-
}
|
|
1091
|
-
return result;
|
|
1092
|
-
}
|
|
1093
|
-
catch (error) {
|
|
1094
|
-
await running.activities.finish();
|
|
1095
|
-
if (error instanceof AcpExecutionError) {
|
|
1096
|
-
throw error;
|
|
1097
|
-
}
|
|
1098
|
-
throw new AcpExecutionError("ACP agent execution failed", {
|
|
1099
|
-
cause: error,
|
|
1100
|
-
});
|
|
1101
|
-
}
|
|
1102
|
-
finally {
|
|
1103
|
-
this.#bufferedAgentText = [];
|
|
1104
|
-
this.#turn = new IdleAcpTurn();
|
|
1105
|
-
}
|
|
1106
|
-
};
|
|
1107
|
-
steer = async (options) => {
|
|
1108
|
-
if (!this.#capabilities.steering) {
|
|
1109
|
-
throw new AcpExecutionError("The selected agent does not support mid-turn steering", {}, "steering_unsupported");
|
|
1110
|
-
}
|
|
1111
|
-
if (!this.#turn.running || this.#turn.commandId !== options.targetCommandId) {
|
|
1112
|
-
throw new AcpExecutionError("The target turn is no longer active", {}, "steering_target_unavailable");
|
|
1113
|
-
}
|
|
1114
|
-
const prompt = this.buildPrompt(options);
|
|
1115
|
-
const response = await this.race(this.#connection.agent.request("_session/steering", {
|
|
1116
|
-
_meta: { steering: { idleBehavior: "promptRequired" } },
|
|
1117
|
-
prompt,
|
|
1118
|
-
sessionId: this.#nativeSessionId,
|
|
1119
|
-
}), "ACP agent exited during steering", options.signal);
|
|
1120
|
-
if (!isRecord(response)) {
|
|
1121
|
-
throw new AcpExecutionError("ACP agent returned an invalid steering response", {}, "acp_invalid_steering_response");
|
|
1122
|
-
}
|
|
1123
|
-
const outcome = response["outcome"];
|
|
1124
|
-
if (outcome === "injected" || outcome === "startedNewTurn") {
|
|
1125
|
-
return outcome;
|
|
1126
|
-
}
|
|
1127
|
-
if (outcome === "promptRequired") {
|
|
1128
|
-
throw new AcpExecutionError("The target turn finished before steering could be injected", {}, "steering_target_unavailable");
|
|
1129
|
-
}
|
|
1130
|
-
if (outcome === "failed") {
|
|
1131
|
-
throw new AcpExecutionError("The Agent could not inject steering", {}, "steering_failed");
|
|
1132
|
-
}
|
|
1133
|
-
throw new AcpExecutionError("ACP agent returned an invalid steering response", {}, "acp_invalid_steering_response");
|
|
1134
|
-
};
|
|
1135
|
-
cancel = async () => {
|
|
1136
|
-
const capturedProcesses = this.#runtimeChild === null ? [] : await captureProcessTree(this.#runtimeChild);
|
|
1137
|
-
try {
|
|
1138
|
-
await this.cancelPendingInteractions();
|
|
1139
|
-
if (this.#turn.running) {
|
|
1140
|
-
await this.#connection.agent.notify(methods.agent.session.cancel, {
|
|
1141
|
-
sessionId: this.#nativeSessionId,
|
|
1142
|
-
});
|
|
1143
|
-
}
|
|
1144
|
-
}
|
|
1145
|
-
finally {
|
|
1146
|
-
await this.closeProcess(capturedProcesses);
|
|
1147
|
-
}
|
|
1148
|
-
};
|
|
1149
|
-
respondPermission = async (options) => {
|
|
1150
|
-
const pending = this.#pendingPermissions.get(options.interactionId);
|
|
1151
|
-
if (pending === undefined) {
|
|
1152
|
-
throw new AcpExecutionError("The permission request is no longer active", {}, "permission_request_not_found");
|
|
1153
|
-
}
|
|
1154
|
-
if (options.outcome === "selected" && !pending.optionIds.has(options.optionId)) {
|
|
1155
|
-
throw new AcpExecutionError("The selected permission option is unavailable", {}, "invalid_permission_response");
|
|
1156
|
-
}
|
|
1157
|
-
const resolved = options.outcome === "selected" ? pending.select(options.optionId) : pending.cancel();
|
|
1158
|
-
if (!resolved) {
|
|
1159
|
-
throw new AcpExecutionError("The permission request was already resolved", {}, "permission_request_not_found");
|
|
1160
|
-
}
|
|
1161
|
-
this.#pendingPermissions.delete(options.interactionId);
|
|
1162
|
-
await this.#getObserver().onPermissionResolved({
|
|
1163
|
-
interactionId: options.interactionId,
|
|
1164
|
-
kind: SESSION_PERMISSION_RESOLVED_KIND,
|
|
1165
|
-
optionId: options.outcome === "selected" ? options.optionId : "",
|
|
1166
|
-
outcome: options.outcome,
|
|
1167
|
-
sessionId: this.#mobiusSessionId,
|
|
1168
|
-
});
|
|
1169
|
-
};
|
|
1170
|
-
respondElicitation = async (options) => {
|
|
1171
|
-
const pending = this.#pendingElicitations.get(options.interactionId);
|
|
1172
|
-
if (pending === undefined) {
|
|
1173
|
-
throw new AcpExecutionError("The elicitation request is no longer active", {}, "elicitation_request_not_found");
|
|
1174
|
-
}
|
|
1175
|
-
let resolved = false;
|
|
1176
|
-
if (options.action === "accept") {
|
|
1177
|
-
if (pending.elicitationId.length > 0) {
|
|
1178
|
-
resolved = pending.accept({});
|
|
1179
|
-
if (resolved) {
|
|
1180
|
-
this.#acceptedUrlElicitations.set(pending.elicitationId, pending.interactionId);
|
|
1181
|
-
}
|
|
1182
|
-
}
|
|
1183
|
-
else {
|
|
1184
|
-
resolved = pending.accept(validateElicitationContent(options.content, pending.requestedSchema));
|
|
1185
|
-
}
|
|
1186
|
-
}
|
|
1187
|
-
else if (options.action === "decline") {
|
|
1188
|
-
resolved = pending.decline();
|
|
1189
|
-
}
|
|
1190
|
-
else {
|
|
1191
|
-
resolved = pending.cancel();
|
|
1192
|
-
}
|
|
1193
|
-
if (!resolved) {
|
|
1194
|
-
throw new AcpExecutionError("The elicitation request was already resolved", {}, "elicitation_request_not_found");
|
|
1195
|
-
}
|
|
1196
|
-
this.#pendingElicitations.delete(options.interactionId);
|
|
1197
|
-
await this.#getObserver().onElicitationResolved({
|
|
1198
|
-
action: options.action,
|
|
1199
|
-
interactionId: options.interactionId,
|
|
1200
|
-
kind: SESSION_ELICITATION_RESOLVED_KIND,
|
|
1201
|
-
sessionId: this.#mobiusSessionId,
|
|
1202
|
-
});
|
|
1203
|
-
};
|
|
1204
|
-
onPermission = async (request, signal) => {
|
|
1205
|
-
this.assertNativeSession(request.sessionId);
|
|
1206
|
-
const interactionId = `permission-${crypto.randomUUID()}`;
|
|
1207
|
-
const options = request.options.slice(0, 20).map((option) => ({
|
|
1208
|
-
kind: option.kind,
|
|
1209
|
-
name: truncate(option.name, 255),
|
|
1210
|
-
optionId: truncate(option.optionId, 255),
|
|
1211
|
-
}));
|
|
1212
|
-
if (options.length === 0) {
|
|
1213
|
-
throw new AcpExecutionError("ACP permission request did not provide any choices", {}, "invalid_agent_permission_request");
|
|
1214
|
-
}
|
|
1215
|
-
const pending = new PendingPermission(interactionId, new Set(options.map((option) => option.optionId)));
|
|
1216
|
-
this.#pendingPermissions.set(interactionId, pending);
|
|
1217
|
-
const abort = () => {
|
|
1218
|
-
void this.cancelPermission(interactionId);
|
|
1219
|
-
};
|
|
1220
|
-
signal.addEventListener("abort", abort, { once: true });
|
|
1221
|
-
try {
|
|
1222
|
-
await this.#getObserver().onPermission({
|
|
1223
|
-
commandId: this.#turn.commandId,
|
|
1224
|
-
interactionId,
|
|
1225
|
-
kind: SESSION_PERMISSION_REQUESTED_KIND,
|
|
1226
|
-
options,
|
|
1227
|
-
sessionId: this.#mobiusSessionId,
|
|
1228
|
-
title: truncate(request.toolCall.title ?? "Permission required", 500),
|
|
1229
|
-
toolCallId: truncate(request.toolCall.toolCallId, 255),
|
|
1230
|
-
toolKind: truncate(request.toolCall.kind ?? "other", 64),
|
|
1231
|
-
});
|
|
1232
|
-
return await pending.completion.promise;
|
|
1233
|
-
}
|
|
1234
|
-
finally {
|
|
1235
|
-
signal.removeEventListener("abort", abort);
|
|
1236
|
-
this.#pendingPermissions.delete(interactionId);
|
|
1237
|
-
}
|
|
1238
|
-
};
|
|
1239
|
-
onElicitation = async (request, signal) => {
|
|
1240
|
-
const sessionId = Reflect.get(request, "sessionId");
|
|
1241
|
-
if (typeof sessionId !== "string") {
|
|
1242
|
-
throw new AcpExecutionError("Mobius only accepts session-scoped ACP elicitations", {}, "unsupported_elicitation_scope");
|
|
1243
|
-
}
|
|
1244
|
-
this.assertNativeSession(sessionId);
|
|
1245
|
-
if (request.mode !== "form" && request.mode !== "url") {
|
|
1246
|
-
throw new AcpExecutionError("The ACP agent requested an unsupported elicitation mode", {}, "unsupported_elicitation_mode");
|
|
1247
|
-
}
|
|
1248
|
-
const interactionId = `elicitation-${crypto.randomUUID()}`;
|
|
1249
|
-
const schemaValue = Reflect.get(request, "requestedSchema");
|
|
1250
|
-
const requestedSchema = request.mode === "form" ? schemaValue : {};
|
|
1251
|
-
const elicitationIdValue = Reflect.get(request, "elicitationId");
|
|
1252
|
-
const elicitationId = request.mode === "url" && typeof elicitationIdValue === "string" ? truncate(elicitationIdValue, 255) : "";
|
|
1253
|
-
const pending = new PendingElicitation(interactionId, elicitationId, requestedSchema);
|
|
1254
|
-
this.#pendingElicitations.set(interactionId, pending);
|
|
1255
|
-
const abort = () => {
|
|
1256
|
-
void this.cancelElicitation(interactionId);
|
|
1257
|
-
};
|
|
1258
|
-
signal.addEventListener("abort", abort, { once: true });
|
|
1259
|
-
try {
|
|
1260
|
-
await this.#getObserver().onElicitation({
|
|
1261
|
-
accepted: false,
|
|
1262
|
-
commandId: this.#turn.commandId,
|
|
1263
|
-
elicitationId,
|
|
1264
|
-
fields: normalizeElicitationFields(requestedSchema),
|
|
1265
|
-
interactionId,
|
|
1266
|
-
kind: SESSION_ELICITATION_REQUESTED_KIND,
|
|
1267
|
-
message: truncate(request.message, 2_000),
|
|
1268
|
-
mode: request.mode,
|
|
1269
|
-
sessionId: this.#mobiusSessionId,
|
|
1270
|
-
url: request.mode === "url" && typeof Reflect.get(request, "url") === "string"
|
|
1271
|
-
? truncate(readString(Reflect.get(request, "url")), 4_096)
|
|
1272
|
-
: "",
|
|
1273
|
-
});
|
|
1274
|
-
return await pending.completion.promise;
|
|
1275
|
-
}
|
|
1276
|
-
finally {
|
|
1277
|
-
signal.removeEventListener("abort", abort);
|
|
1278
|
-
this.#pendingElicitations.delete(interactionId);
|
|
1279
|
-
}
|
|
1280
|
-
};
|
|
1281
|
-
onElicitationComplete = async (notification) => {
|
|
1282
|
-
const interactionId = this.#acceptedUrlElicitations.get(notification.elicitationId);
|
|
1283
|
-
if (interactionId === undefined) {
|
|
1284
|
-
return;
|
|
1285
|
-
}
|
|
1286
|
-
this.#acceptedUrlElicitations.delete(notification.elicitationId);
|
|
1287
|
-
await this.#getObserver().onElicitationResolved({
|
|
1288
|
-
action: "complete",
|
|
1289
|
-
interactionId,
|
|
1290
|
-
kind: SESSION_ELICITATION_RESOLVED_KIND,
|
|
1291
|
-
sessionId: this.#mobiusSessionId,
|
|
1292
|
-
});
|
|
1293
|
-
};
|
|
1294
|
-
onUpdate = (notification) => {
|
|
1295
|
-
if (this.#nativeSessionId.length === 0) {
|
|
1296
|
-
const notificationBytes = Buffer.byteLength(JSON.stringify(notification));
|
|
1297
|
-
if (this.#preSessionUpdates.length >= MAX_PRE_SESSION_UPDATES ||
|
|
1298
|
-
this.#preSessionUpdateBytes + notificationBytes > MAX_PRE_SESSION_UPDATE_BYTES) {
|
|
1299
|
-
return Promise.reject(new AcpExecutionError("ACP agent sent too many updates before creating its session", {}, "agent_update_limit"));
|
|
1300
|
-
}
|
|
1301
|
-
this.#preSessionUpdates.push(notification);
|
|
1302
|
-
this.#preSessionUpdateBytes += notificationBytes;
|
|
1303
|
-
return Promise.resolve();
|
|
1304
|
-
}
|
|
1305
|
-
return this.enqueueUpdate(notification);
|
|
1306
|
-
};
|
|
1307
|
-
enqueueUpdate = (notification) => {
|
|
1308
|
-
this.#updateTail = this.#updateTail.then(async () => await this.processUpdate(notification));
|
|
1309
|
-
return this.#updateTail;
|
|
1310
|
-
};
|
|
1311
|
-
selectNativeSession = (sessionId) => {
|
|
1312
|
-
const selected = nativeSessionIdSchema.parse(sessionId);
|
|
1313
|
-
if (this.#nativeSessionId.length > 0 && this.#nativeSessionId !== selected) {
|
|
1314
|
-
throw new AcpExecutionError("ACP agent attempted to replace the selected session", {}, "invalid_agent_session");
|
|
1315
|
-
}
|
|
1316
|
-
this.#nativeSessionId = selected;
|
|
1317
|
-
const pending = this.#preSessionUpdates.splice(0);
|
|
1318
|
-
this.#preSessionUpdateBytes = 0;
|
|
1319
|
-
for (const notification of pending) {
|
|
1320
|
-
void this.enqueueUpdate(notification);
|
|
1321
|
-
}
|
|
1322
|
-
};
|
|
1323
|
-
processUpdate = async (notification) => {
|
|
1324
|
-
this.assertNativeSession(notification.sessionId);
|
|
1325
|
-
const update = notification.update;
|
|
1326
|
-
if (this.#replay.kind === "capture") {
|
|
1327
|
-
await this.#replay.history.record(update);
|
|
1328
|
-
}
|
|
1329
|
-
if (this.#replay.kind !== "idle" &&
|
|
1330
|
-
(update.sessionUpdate === "user_message_chunk" ||
|
|
1331
|
-
update.sessionUpdate === "agent_message_chunk" ||
|
|
1332
|
-
update.sessionUpdate === "agent_thought_chunk" ||
|
|
1333
|
-
update.sessionUpdate === "tool_call" ||
|
|
1334
|
-
update.sessionUpdate === "tool_call_update" ||
|
|
1335
|
-
update.sessionUpdate === "plan" ||
|
|
1336
|
-
update.sessionUpdate === "plan_update" ||
|
|
1337
|
-
update.sessionUpdate === "plan_removed")) {
|
|
1338
|
-
return;
|
|
1339
|
-
}
|
|
1340
|
-
if (update.sessionUpdate === "agent_message_chunk") {
|
|
1341
|
-
if (update.content.type === "text") {
|
|
1342
|
-
if (isProgressMessage(update)) {
|
|
1343
|
-
await this.#turn.activities.recordNarrative("progress", update.messageId ?? "current", update.content.text);
|
|
1344
|
-
}
|
|
1345
|
-
else {
|
|
1346
|
-
await this.#turn.activities.finishNarrative();
|
|
1347
|
-
await this.bufferAgentText(update.content.text, truncate(update.messageId ?? "", 255));
|
|
1348
|
-
}
|
|
1349
|
-
}
|
|
1350
|
-
else {
|
|
1351
|
-
await this.#turn.activities.finishNarrative();
|
|
1352
|
-
await this.flushAgentText();
|
|
1353
|
-
await this.emitAgentContent(normalizeContentBlock(update.content), truncate(update.messageId ?? "", 255));
|
|
1354
|
-
}
|
|
1355
|
-
return;
|
|
1356
|
-
}
|
|
1357
|
-
if (update.sessionUpdate === "agent_thought_chunk") {
|
|
1358
|
-
if (update.content.type === "text") {
|
|
1359
|
-
await this.#turn.activities.recordNarrative("reasoning", update.messageId ?? "current", update.content.text);
|
|
1360
|
-
}
|
|
1361
|
-
return;
|
|
1362
|
-
}
|
|
1363
|
-
if (update.sessionUpdate === "tool_call") {
|
|
1364
|
-
await this.recordBufferedAgentTextAsProgress();
|
|
1365
|
-
await this.#turn.activities.recordToolCall(update);
|
|
1366
|
-
return;
|
|
1367
|
-
}
|
|
1368
|
-
if (update.sessionUpdate === "tool_call_update") {
|
|
1369
|
-
await this.#turn.activities.recordToolCallUpdate(update);
|
|
1370
|
-
await this.emitToolImages(update);
|
|
1371
|
-
return;
|
|
1372
|
-
}
|
|
1373
|
-
if (update.sessionUpdate === "plan") {
|
|
1374
|
-
await this.#turn.activities.recordPlan(update);
|
|
1375
|
-
return;
|
|
1376
|
-
}
|
|
1377
|
-
if (update.sessionUpdate === "plan_update") {
|
|
1378
|
-
await this.#turn.activities.recordPlanUpdate(update);
|
|
1379
|
-
return;
|
|
1380
|
-
}
|
|
1381
|
-
if (update.sessionUpdate === "plan_removed") {
|
|
1382
|
-
await this.#turn.activities.removePlan(update);
|
|
1383
|
-
return;
|
|
1384
|
-
}
|
|
1385
|
-
if (update.sessionUpdate === "available_commands_update") {
|
|
1386
|
-
const commands = update.availableCommands
|
|
1387
|
-
.slice(0, 500)
|
|
1388
|
-
.map((command) => ({
|
|
1389
|
-
description: truncate(command.description, 500),
|
|
1390
|
-
inputHint: truncate(command.input?.hint ?? "", 255),
|
|
1391
|
-
name: truncate(command.name, 128),
|
|
1392
|
-
}))
|
|
1393
|
-
.filter((command) => command.name.length > 0);
|
|
1394
|
-
this.#commands = commands;
|
|
1395
|
-
await this.#getObserver().onCommands({
|
|
1396
|
-
commands,
|
|
1397
|
-
kind: SESSION_COMMANDS_UPDATED_KIND,
|
|
1398
|
-
sessionId: this.#mobiusSessionId,
|
|
1399
|
-
});
|
|
1400
|
-
return;
|
|
1401
|
-
}
|
|
1402
|
-
if (update.sessionUpdate === "config_option_update") {
|
|
1403
|
-
this.#configOptions = this.#sessionConfigProtocol.normalizeUpdate(this.#configOptions, update.configOptions);
|
|
1404
|
-
this.#configRevision += 1;
|
|
1405
|
-
await this.emitConfigUpdate();
|
|
1406
|
-
return;
|
|
1407
|
-
}
|
|
1408
|
-
if (update.sessionUpdate === "current_mode_update") {
|
|
1409
|
-
this.#configOptions = this.#configOptions.map((option) => option.category === "mode" ? { ...option, currentValue: update.currentModeId } : option);
|
|
1410
|
-
this.#configRevision += 1;
|
|
1411
|
-
await this.emitConfigUpdate();
|
|
1412
|
-
return;
|
|
1413
|
-
}
|
|
1414
|
-
if (update.sessionUpdate === "session_info_update") {
|
|
1415
|
-
if (Object.hasOwn(update, "title")) {
|
|
1416
|
-
this.#sessionTitle = truncate(update.title ?? "", 500);
|
|
1417
|
-
}
|
|
1418
|
-
if (Object.hasOwn(update, "updatedAt")) {
|
|
1419
|
-
this.#sessionUpdatedAt = truncate(update.updatedAt ?? "", 128);
|
|
1420
|
-
}
|
|
1421
|
-
await this.#getObserver().onInfo({
|
|
1422
|
-
kind: SESSION_INFO_UPDATED_KIND,
|
|
1423
|
-
sessionId: this.#mobiusSessionId,
|
|
1424
|
-
title: this.#sessionTitle,
|
|
1425
|
-
updatedAt: this.#sessionUpdatedAt,
|
|
1426
|
-
});
|
|
1427
|
-
return;
|
|
1428
|
-
}
|
|
1429
|
-
if (update.sessionUpdate === "usage_update") {
|
|
1430
|
-
await this.#getObserver().onUsage({
|
|
1431
|
-
costAmount: update.cost?.amount ?? 0,
|
|
1432
|
-
costCurrency: truncate(update.cost?.currency ?? "", 16),
|
|
1433
|
-
hasCost: update.cost !== undefined && update.cost !== null,
|
|
1434
|
-
kind: SESSION_USAGE_UPDATED_KIND,
|
|
1435
|
-
sessionId: this.#mobiusSessionId,
|
|
1436
|
-
size: Math.max(0, Math.trunc(update.size)),
|
|
1437
|
-
source: "context",
|
|
1438
|
-
used: Math.max(0, Math.trunc(update.used)),
|
|
1439
|
-
});
|
|
1440
|
-
}
|
|
1441
|
-
};
|
|
1442
|
-
close = async () => {
|
|
1443
|
-
try {
|
|
1444
|
-
await this.cancelPendingInteractions();
|
|
1445
|
-
if (this.#capabilities.closeSession && this.#nativeSessionId.length > 0) {
|
|
1446
|
-
try {
|
|
1447
|
-
await this.#connection.agent.request(methods.agent.session.close, { sessionId: this.#nativeSessionId }, {
|
|
1448
|
-
cancellationSignal: AbortSignal.timeout(PROCESS_STOP_TIMEOUT_MILLISECONDS),
|
|
1449
|
-
});
|
|
1450
|
-
}
|
|
1451
|
-
catch {
|
|
1452
|
-
// Process teardown below remains authoritative.
|
|
1453
|
-
}
|
|
1454
|
-
}
|
|
1455
|
-
}
|
|
1456
|
-
finally {
|
|
1457
|
-
await this.closeProcess();
|
|
1458
|
-
}
|
|
1459
|
-
};
|
|
1460
|
-
closeProcess = async (capturedProcesses = []) => {
|
|
1461
|
-
try {
|
|
1462
|
-
if (this.#runtimeChild === null) {
|
|
1463
|
-
// The in-process agent owns its app-server child and its process tree.
|
|
1464
|
-
await this.#inProcessAgent?.close();
|
|
1465
|
-
return;
|
|
1466
|
-
}
|
|
1467
|
-
await stopProcessTree(this.#runtimeChild, capturedProcesses);
|
|
1468
|
-
}
|
|
1469
|
-
finally {
|
|
1470
|
-
this.#connection.close();
|
|
1471
|
-
}
|
|
1472
|
-
};
|
|
1473
|
-
race = async (operation, exitMessage, signal) => {
|
|
1474
|
-
signal.throwIfAborted();
|
|
1475
|
-
let removeAbortListener = () => { };
|
|
1476
|
-
const aborted = new Promise((_resolve, reject) => {
|
|
1477
|
-
const rejectAbort = () => {
|
|
1478
|
-
reject(signal.reason ?? new Error("ACP request was cancelled"));
|
|
1479
|
-
};
|
|
1480
|
-
signal.addEventListener("abort", rejectAbort, { once: true });
|
|
1481
|
-
removeAbortListener = () => {
|
|
1482
|
-
signal.removeEventListener("abort", rejectAbort);
|
|
1483
|
-
};
|
|
1484
|
-
});
|
|
1485
|
-
try {
|
|
1486
|
-
try {
|
|
1487
|
-
return await Promise.race([
|
|
1488
|
-
operation,
|
|
1489
|
-
this.#termination.then((termination) => {
|
|
1490
|
-
const cause = acpEndpointTerminationError(termination);
|
|
1491
|
-
throw new AcpExecutionError(exitMessage, { cause }, cause.code);
|
|
1492
|
-
}),
|
|
1493
|
-
aborted,
|
|
1494
|
-
]);
|
|
1495
|
-
}
|
|
1496
|
-
catch (error) {
|
|
1497
|
-
signal.throwIfAborted();
|
|
1498
|
-
if (error instanceof RequestError && error.code === -32_000) {
|
|
1499
|
-
throw new AcpExecutionError("Agent authentication is required", { cause: error }, "authentication_required");
|
|
1500
|
-
}
|
|
1501
|
-
if (error instanceof RequestError) {
|
|
1502
|
-
throw new AcpExecutionError(truncate(error.message, 500), { cause: error }, "acp_agent_error");
|
|
1503
|
-
}
|
|
1504
|
-
throw error;
|
|
1505
|
-
}
|
|
1506
|
-
}
|
|
1507
|
-
finally {
|
|
1508
|
-
removeAbortListener();
|
|
1509
|
-
}
|
|
1510
|
-
};
|
|
1511
|
-
assertNativeSession = (sessionId) => {
|
|
1512
|
-
if (sessionId !== this.#nativeSessionId) {
|
|
1513
|
-
throw new AcpExecutionError("ACP agent referenced an unknown session", {}, "invalid_agent_session");
|
|
1514
|
-
}
|
|
1515
|
-
};
|
|
1516
|
-
emitConfigUpdate = async () => {
|
|
1517
|
-
await this.#getObserver().onConfig({
|
|
1518
|
-
configOptions: this.#configOptions,
|
|
1519
|
-
kind: SESSION_CONFIG_UPDATED_KIND,
|
|
1520
|
-
requestId: `agent-update-${crypto.randomUUID()}`,
|
|
1521
|
-
sessionId: this.#mobiusSessionId,
|
|
1522
|
-
});
|
|
1523
|
-
};
|
|
1524
|
-
cancelPermission = async (interactionId) => {
|
|
1525
|
-
const pending = this.#pendingPermissions.get(interactionId);
|
|
1526
|
-
if (pending === undefined || !pending.cancel()) {
|
|
1527
|
-
return;
|
|
1528
|
-
}
|
|
1529
|
-
this.#pendingPermissions.delete(interactionId);
|
|
1530
|
-
await this.#getObserver().onPermissionResolved({
|
|
1531
|
-
interactionId,
|
|
1532
|
-
kind: SESSION_PERMISSION_RESOLVED_KIND,
|
|
1533
|
-
optionId: "",
|
|
1534
|
-
outcome: "cancelled",
|
|
1535
|
-
sessionId: this.#mobiusSessionId,
|
|
1536
|
-
});
|
|
1537
|
-
};
|
|
1538
|
-
cancelElicitation = async (interactionId) => {
|
|
1539
|
-
const pending = this.#pendingElicitations.get(interactionId);
|
|
1540
|
-
if (pending === undefined || !pending.cancel()) {
|
|
1541
|
-
return;
|
|
1542
|
-
}
|
|
1543
|
-
this.#pendingElicitations.delete(interactionId);
|
|
1544
|
-
await this.#getObserver().onElicitationResolved({
|
|
1545
|
-
action: "cancel",
|
|
1546
|
-
interactionId,
|
|
1547
|
-
kind: SESSION_ELICITATION_RESOLVED_KIND,
|
|
1548
|
-
sessionId: this.#mobiusSessionId,
|
|
1549
|
-
});
|
|
1550
|
-
};
|
|
1551
|
-
cancelPendingInteractions = async () => {
|
|
1552
|
-
const permissionIds = [...this.#pendingPermissions.keys()];
|
|
1553
|
-
const elicitationIds = [...this.#pendingElicitations.keys()];
|
|
1554
|
-
const acceptedElicitationIds = [...this.#acceptedUrlElicitations.values()];
|
|
1555
|
-
this.#acceptedUrlElicitations.clear();
|
|
1556
|
-
for (const interactionId of permissionIds) {
|
|
1557
|
-
await this.cancelPermission(interactionId);
|
|
1558
|
-
}
|
|
1559
|
-
for (const interactionId of elicitationIds) {
|
|
1560
|
-
await this.cancelElicitation(interactionId);
|
|
1561
|
-
}
|
|
1562
|
-
for (const interactionId of acceptedElicitationIds) {
|
|
1563
|
-
await this.#getObserver().onElicitationResolved({
|
|
1564
|
-
action: "cancel",
|
|
1565
|
-
interactionId,
|
|
1566
|
-
kind: SESSION_ELICITATION_RESOLVED_KIND,
|
|
1567
|
-
sessionId: this.#mobiusSessionId,
|
|
1568
|
-
});
|
|
1569
|
-
}
|
|
1570
|
-
};
|
|
1571
|
-
}
|
|
9
|
+
export { AcpAgentSettingsSnapshot, AcpPreparedSession, createWritableAcpStream, NullAcpSessionObserver, } from "./process-session.js";
|
|
10
|
+
import { AcpAgentSettingsSnapshot, AcpProcessSession, arraysEqual, NullAcpSessionObserver, nativeHistoryNotRetained, } from "./process-session.js";
|
|
1572
11
|
class AcpProcessEvictionCandidate {
|
|
1573
12
|
}
|
|
1574
13
|
class MissingAcpProcessEvictionCandidate extends AcpProcessEvictionCandidate {
|
|
@@ -1616,16 +55,17 @@ export class AcpSessionManager {
|
|
|
1616
55
|
#transientProcessCount = 0;
|
|
1617
56
|
#store;
|
|
1618
57
|
#nativeHistoryReader;
|
|
58
|
+
#sessionIdentity;
|
|
1619
59
|
#observer;
|
|
1620
|
-
constructor(observer = new NullAcpSessionObserver(), store = new MemoryAcpSessionStore(), nativeHistoryReader = null) {
|
|
60
|
+
constructor(observer = new NullAcpSessionObserver(), store = new MemoryAcpSessionStore(), nativeHistoryReader = null, sessionIdentity = "assigned") {
|
|
1621
61
|
this.#observer = observer;
|
|
1622
62
|
this.#store = store;
|
|
1623
63
|
this.#nativeHistoryReader = nativeHistoryReader;
|
|
64
|
+
this.#sessionIdentity = sessionIdentity;
|
|
1624
65
|
}
|
|
1625
66
|
setObserver = (observer) => {
|
|
1626
67
|
this.#observer = observer;
|
|
1627
68
|
};
|
|
1628
|
-
findLinkedSessions = (agentId, nativeSessionId) => this.#store.findNative(agentId, nativeSessionId);
|
|
1629
69
|
#notifyProcessCapacityChanged() {
|
|
1630
70
|
const changed = this.#processCapacityChanged;
|
|
1631
71
|
this.#processCapacityChanged = Promise.withResolvers();
|
|
@@ -1746,7 +186,14 @@ export class AcpSessionManager {
|
|
|
1746
186
|
if (retained) {
|
|
1747
187
|
this.#sessions.delete(sessionId);
|
|
1748
188
|
}
|
|
1749
|
-
|
|
189
|
+
try {
|
|
190
|
+
await this.#retireProcess(runtime, retained, close);
|
|
191
|
+
}
|
|
192
|
+
finally {
|
|
193
|
+
if (retained && this.#sessionIdentity === "native") {
|
|
194
|
+
this.#store.remove(sessionId);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
1750
197
|
}
|
|
1751
198
|
async #retireNativeBrowserProcess(sessionId, runtime, close) {
|
|
1752
199
|
const retained = this.#nativeBrowserSessions.get(sessionId) === runtime;
|
|
@@ -1871,7 +318,12 @@ export class AcpSessionManager {
|
|
|
1871
318
|
async #startPreparation(options, metrics = unmeasuredOperationMetrics) {
|
|
1872
319
|
const operation = (async () => {
|
|
1873
320
|
try {
|
|
1874
|
-
return await this.#startRetainedSessionProcess(options, async () => await AcpProcessSession.start(
|
|
321
|
+
return await this.#startRetainedSessionProcess(options, async () => await AcpProcessSession.start(this.#sessionIdentity === "native" &&
|
|
322
|
+
supportsNativeChat(options.agent.id) &&
|
|
323
|
+
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(options.sessionId) &&
|
|
324
|
+
this.#store.read(options.sessionId) instanceof MissingAcpStoredSession
|
|
325
|
+
? { ...options, origin: { kind: "import", nativeSessionId: options.sessionId } }
|
|
326
|
+
: options, () => this.#observer, this.#store, metrics));
|
|
1875
327
|
}
|
|
1876
328
|
finally {
|
|
1877
329
|
this.#preparing.delete(options.sessionId);
|
|
@@ -2247,6 +699,38 @@ export class AcpSessionManager {
|
|
|
2247
699
|
]);
|
|
2248
700
|
};
|
|
2249
701
|
hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
|
|
702
|
+
createNativeSession = async (options) => {
|
|
703
|
+
const temporarySessionId = `new-${crypto.randomUUID()}`;
|
|
704
|
+
const temporaryOptions = { ...options, sessionId: temporarySessionId };
|
|
705
|
+
this.#beginSessionUse(temporarySessionId);
|
|
706
|
+
try {
|
|
707
|
+
const runtime = await this.#startPreparation(temporaryOptions);
|
|
708
|
+
let adopted = false;
|
|
709
|
+
try {
|
|
710
|
+
const nativeSessionId = runtime.nativeSessionId();
|
|
711
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(nativeSessionId) ||
|
|
712
|
+
this.#sessions.has(nativeSessionId) ||
|
|
713
|
+
!(this.#store.read(nativeSessionId) instanceof MissingAcpStoredSession)) {
|
|
714
|
+
throw new AcpExecutionError("The Agent returned an invalid new Session ID", {}, "invalid_native_session_response");
|
|
715
|
+
}
|
|
716
|
+
runtime.adoptNativeSessionId(nativeSessionId);
|
|
717
|
+
this.#sessions.delete(temporarySessionId);
|
|
718
|
+
this.#sessions.set(nativeSessionId, runtime);
|
|
719
|
+
this.#retainedProcesses.set(runtime, new FoundAcpSessionProcessEvictionCandidate(nativeSessionId, runtime));
|
|
720
|
+
adopted = true;
|
|
721
|
+
return nativeSessionId;
|
|
722
|
+
}
|
|
723
|
+
finally {
|
|
724
|
+
if (!adopted) {
|
|
725
|
+
await this.#retireSessionProcess(temporarySessionId, runtime, async () => await runtime.closeProcess());
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
finally {
|
|
730
|
+
this.#store.remove(temporarySessionId);
|
|
731
|
+
this.#endSessionUse(temporarySessionId);
|
|
732
|
+
}
|
|
733
|
+
};
|
|
2250
734
|
ensureSession = async (options) => {
|
|
2251
735
|
const existing = this.#sessions.get(options.sessionId);
|
|
2252
736
|
if (existing !== undefined) {
|
|
@@ -2323,6 +807,24 @@ export class AcpSessionManager {
|
|
|
2323
807
|
this.#endSessionUse(options.sessionId);
|
|
2324
808
|
}
|
|
2325
809
|
};
|
|
810
|
+
loadLinkedSessionHistory = async (options) => {
|
|
811
|
+
options.signal.throwIfAborted();
|
|
812
|
+
const stored = this.#store.read(options.sessionId);
|
|
813
|
+
if (!(stored instanceof FoundAcpStoredSession) || !stored.session.prompted) {
|
|
814
|
+
return null;
|
|
815
|
+
}
|
|
816
|
+
const linked = stored.session;
|
|
817
|
+
if (linked.agentId !== options.agent.id ||
|
|
818
|
+
linked.cwd !== options.cwd ||
|
|
819
|
+
linked.additionalDirectories.length !== options.additionalDirectories.length ||
|
|
820
|
+
linked.additionalDirectories.some((directory, index) => directory !== options.additionalDirectories[index])) {
|
|
821
|
+
throw new AcpExecutionError("The session belongs to another Agent or workspace", {}, "session_identity_mismatch");
|
|
822
|
+
}
|
|
823
|
+
if (this.#nativeHistoryReader === null) {
|
|
824
|
+
return await this.loadSessionHistory(options);
|
|
825
|
+
}
|
|
826
|
+
return await this.#nativeHistoryReader.read(options, linked.nativeSessionId);
|
|
827
|
+
};
|
|
2326
828
|
openNativeSession = async (options, origin, loadHistory) => {
|
|
2327
829
|
const key = `${options.agent.id}:${origin.nativeSessionId}`;
|
|
2328
830
|
if (this.#nativeOperations.has(key)) {
|