@moxt-ai/mobius 0.0.94 → 0.0.98
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.d.ts.map +1 -1
- package/dist/acp/activity.js +13 -2
- package/dist/acp/activity.js.map +1 -1
- package/dist/acp/codex/agent.d.ts.map +1 -1
- package/dist/acp/codex/agent.js +19 -4
- 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 +164 -0
- package/dist/acp/process-session.d.ts.map +1 -0
- package/dist/acp/process-session.js +1182 -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 +4 -159
- package/dist/acp/session-manager.d.ts.map +1 -1
- package/dist/acp/session-manager.js +11 -1581
- package/dist/acp/session-manager.js.map +1 -1
- package/dist/acp/session-state.d.ts +43 -0
- package/dist/acp/session-state.d.ts.map +1 -0
- package/dist/acp/session-state.js +87 -0
- package/dist/acp/session-state.js.map +1 -0
- 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/cli.js +8187 -15444
- package/dist/cli.js.map +4 -4
- package/dist/config.js +2 -2
- package/dist/config.js.map +1 -1
- package/dist/daemon-manager.d.ts +1 -1
- package/dist/daemon-manager.d.ts.map +1 -1
- package/dist/daemon-manager.js +1 -2
- package/dist/daemon-manager.js.map +1 -1
- package/dist/daemon-session-commands.d.ts +33 -0
- package/dist/daemon-session-commands.d.ts.map +1 -0
- package/dist/daemon-session-commands.js +522 -0
- package/dist/daemon-session-commands.js.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8598 -15855
- package/dist/index.js.map +4 -4
- package/dist/native-sessions/acp-history.d.ts +6 -0
- package/dist/native-sessions/acp-history.d.ts.map +1 -0
- package/dist/native-sessions/acp-history.js +27 -0
- package/dist/native-sessions/acp-history.js.map +1 -0
- 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 +26 -0
- package/dist/native-sessions/agent-adapter.js.map +1 -0
- package/dist/native-sessions/chat-agent.d.ts +4 -0
- package/dist/native-sessions/chat-agent.d.ts.map +1 -0
- package/dist/native-sessions/chat-agent.js +16 -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/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/live-history-page.d.ts +3 -0
- package/dist/native-sessions/live-history-page.d.ts.map +1 -0
- package/dist/native-sessions/live-history-page.js +81 -0
- package/dist/native-sessions/live-history-page.js.map +1 -0
- package/dist/native-sessions/opencode-adapter.d.ts +3 -0
- package/dist/native-sessions/opencode-adapter.d.ts.map +1 -0
- package/dist/native-sessions/opencode-adapter.js +7 -0
- package/dist/native-sessions/opencode-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 +25 -58
- package/dist/native-sessions/service.js.map +1 -1
- package/dist/pairing/pair-local-machine.js.map +1 -1
- package/dist/relay-connection/coalescing-activity-publisher.d.ts +10 -0
- package/dist/relay-connection/coalescing-activity-publisher.d.ts.map +1 -0
- package/dist/relay-connection/coalescing-activity-publisher.js +54 -0
- package/dist/relay-connection/coalescing-activity-publisher.js.map +1 -0
- package/dist/relay-connection/session-event-outbox.d.ts.map +1 -1
- package/dist/relay-connection/session-event-outbox.js +13 -48
- package/dist/relay-connection/session-event-outbox.js.map +1 -1
- package/dist/relay-connection/session-event-publisher.d.ts +17 -0
- package/dist/relay-connection/session-event-publisher.d.ts.map +1 -0
- package/dist/relay-connection/session-event-publisher.js +245 -0
- package/dist/relay-connection/session-event-publisher.js.map +1 -0
- package/dist/run-daemon.d.ts.map +1 -1
- package/dist/run-daemon.js +7 -1277
- package/dist/run-daemon.js.map +1 -1
- package/dist/runtime.d.ts +1 -1
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +8023 -15278
- package/dist/runtime.js.map +4 -4
- package/dist/storage/runtime-installation-store.d.ts +6 -14
- package/dist/storage/runtime-installation-store.d.ts.map +1 -1
- package/dist/storage/runtime-installation-store.js +16 -103
- package/dist/storage/runtime-installation-store.js.map +1 -1
- package/package.json +1 -4
- package/dist/acp/markdown-images.d.ts +0 -8
- package/dist/acp/markdown-images.d.ts.map +0 -1
- package/dist/acp/markdown-images.js +0 -55
- package/dist/acp/markdown-images.js.map +0 -1
|
@@ -0,0 +1,1182 @@
|
|
|
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
|
+
import { unmeasuredOperationMetrics } from "../infra/operation-metrics.js";
|
|
7
|
+
import { embedLocalHistoryImages } from "../native-sessions/history-images.js";
|
|
8
|
+
import { captureProcessTree, revalidateExecutable, stopProcessTree, } from "../process/executable.js";
|
|
9
|
+
import { AcpConfigurationValueUnavailableError, AcpExecutionError } from "./acp-error.js";
|
|
10
|
+
import { imageDisplayContent, isProgressMessage, normalizeContentBlock, } from "./activity.js";
|
|
11
|
+
import { createAcpClient } from "./create-client.js";
|
|
12
|
+
import { normalizeElicitationFields, validateElicitationContent } from "./elicitation.js";
|
|
13
|
+
import { acpEndpointTerminationError, } from "./in-process/acp-endpoint.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 { IdleAcpTurn, PendingElicitation, PendingPermission, RunningAcpTurn, } from "./session-state.js";
|
|
20
|
+
import { AcpStoredSession, DeletedAcpStoredSession, FoundAcpStoredSession, } from "./session-store.js";
|
|
21
|
+
import { isRecord, readString, truncate } from "./value-utils.js";
|
|
22
|
+
const PROCESS_STOP_TIMEOUT_MILLISECONDS = 1_000;
|
|
23
|
+
const MAX_PRE_SESSION_UPDATES = 100;
|
|
24
|
+
const MAX_PRE_SESSION_UPDATE_BYTES = 1024 * 1024;
|
|
25
|
+
export function nativeHistoryNotRetained() {
|
|
26
|
+
return {
|
|
27
|
+
cause: {
|
|
28
|
+
code: "native_history_not_retained",
|
|
29
|
+
message: "Native message history is not retained in the cloud for this Session.",
|
|
30
|
+
},
|
|
31
|
+
status: "unavailable",
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export class NullAcpSessionObserver {
|
|
35
|
+
onCommands = () => Promise.resolve();
|
|
36
|
+
onConfig = () => Promise.resolve();
|
|
37
|
+
onContent = () => Promise.resolve();
|
|
38
|
+
onElicitation = () => Promise.resolve();
|
|
39
|
+
onElicitationResolved = () => Promise.resolve();
|
|
40
|
+
onInfo = () => Promise.resolve();
|
|
41
|
+
onPermission = () => Promise.resolve();
|
|
42
|
+
onPermissionResolved = () => Promise.resolve();
|
|
43
|
+
onUsage = () => Promise.resolve();
|
|
44
|
+
}
|
|
45
|
+
export class AcpPreparedSession {
|
|
46
|
+
agentName;
|
|
47
|
+
agentVersion;
|
|
48
|
+
capabilities;
|
|
49
|
+
commands;
|
|
50
|
+
configOptions;
|
|
51
|
+
restored;
|
|
52
|
+
constructor(agentName, agentVersion, capabilities, commands, configOptions, restored) {
|
|
53
|
+
this.agentName = agentName;
|
|
54
|
+
this.agentVersion = agentVersion;
|
|
55
|
+
this.capabilities = capabilities;
|
|
56
|
+
this.commands = commands;
|
|
57
|
+
this.configOptions = configOptions;
|
|
58
|
+
this.restored = restored;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
export class AcpAgentSettingsSnapshot {
|
|
62
|
+
agentName;
|
|
63
|
+
agentVersion;
|
|
64
|
+
configOptions;
|
|
65
|
+
constructor(agentName, agentVersion, configOptions) {
|
|
66
|
+
this.agentName = agentName;
|
|
67
|
+
this.agentVersion = agentVersion;
|
|
68
|
+
this.configOptions = configOptions;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
export { AcpConfigurationValueUnavailableError, AcpExecutionError } from "./acp-error.js";
|
|
72
|
+
class RetryableAcpInitializationError extends AcpExecutionError {
|
|
73
|
+
constructor(cause) {
|
|
74
|
+
super("ACP agent initialization failed", { cause });
|
|
75
|
+
this.name = "RetryableAcpInitializationError";
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
function readableWebStream(input) {
|
|
79
|
+
let streamOpen = true;
|
|
80
|
+
return new ReadableStream({
|
|
81
|
+
start(controller) {
|
|
82
|
+
input.on("data", (chunk) => {
|
|
83
|
+
if (!streamOpen) {
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (chunk instanceof Uint8Array) {
|
|
87
|
+
controller.enqueue(new Uint8Array(chunk));
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
streamOpen = false;
|
|
91
|
+
controller.error(new Error("ACP process produced a non-binary chunk"));
|
|
92
|
+
});
|
|
93
|
+
input.once("end", () => {
|
|
94
|
+
if (!streamOpen) {
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
streamOpen = false;
|
|
98
|
+
controller.close();
|
|
99
|
+
});
|
|
100
|
+
input.once("error", (error) => {
|
|
101
|
+
if (!streamOpen) {
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
streamOpen = false;
|
|
105
|
+
controller.error(error);
|
|
106
|
+
});
|
|
107
|
+
},
|
|
108
|
+
cancel() {
|
|
109
|
+
streamOpen = false;
|
|
110
|
+
},
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
export function createWritableAcpStream(output) {
|
|
114
|
+
let outputFailure;
|
|
115
|
+
const pendingWriteFailures = new Set();
|
|
116
|
+
const fail = (error) => {
|
|
117
|
+
outputFailure = error;
|
|
118
|
+
for (const reject of pendingWriteFailures) {
|
|
119
|
+
reject(error);
|
|
120
|
+
}
|
|
121
|
+
pendingWriteFailures.clear();
|
|
122
|
+
};
|
|
123
|
+
output.on("error", fail);
|
|
124
|
+
output.once("close", () => {
|
|
125
|
+
if (outputFailure === undefined) {
|
|
126
|
+
fail(new Error("ACP process input closed"));
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
return new WritableStream({
|
|
130
|
+
write(chunk) {
|
|
131
|
+
if (outputFailure !== undefined) {
|
|
132
|
+
return Promise.reject(outputFailure);
|
|
133
|
+
}
|
|
134
|
+
return new Promise((resolve, reject) => {
|
|
135
|
+
pendingWriteFailures.add(reject);
|
|
136
|
+
output.write(chunk, (error) => {
|
|
137
|
+
pendingWriteFailures.delete(reject);
|
|
138
|
+
if (error) {
|
|
139
|
+
outputFailure = error;
|
|
140
|
+
reject(error);
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
if (outputFailure !== undefined) {
|
|
144
|
+
reject(outputFailure);
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
resolve();
|
|
148
|
+
});
|
|
149
|
+
});
|
|
150
|
+
},
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
export function arraysEqual(left, right) {
|
|
154
|
+
return left.length === right.length && left.every((value, index) => value === right[index]);
|
|
155
|
+
}
|
|
156
|
+
export function recordsEqual(left, right) {
|
|
157
|
+
const leftEntries = Object.entries(left);
|
|
158
|
+
const rightEntries = Object.entries(right);
|
|
159
|
+
return leftEntries.length === rightEntries.length && leftEntries.every(([name, value]) => right[name] === value);
|
|
160
|
+
}
|
|
161
|
+
export class AcpProcessSession {
|
|
162
|
+
#additionalDirectories;
|
|
163
|
+
#acceptedUrlElicitations = new Map();
|
|
164
|
+
#agentId;
|
|
165
|
+
#connection;
|
|
166
|
+
#cwd;
|
|
167
|
+
#environment;
|
|
168
|
+
#getObserver;
|
|
169
|
+
#inProcessAgent;
|
|
170
|
+
#mobiusSessionId;
|
|
171
|
+
#pendingElicitations = new Map();
|
|
172
|
+
#pendingPermissions = new Map();
|
|
173
|
+
#preSessionUpdates = [];
|
|
174
|
+
// Both topologies report a terminal outcome, even after a prompt's initial RPC is acknowledged.
|
|
175
|
+
#termination;
|
|
176
|
+
#runtimeChild;
|
|
177
|
+
#metrics;
|
|
178
|
+
#sessionConfigProtocol;
|
|
179
|
+
#store;
|
|
180
|
+
#verifiedAgentVersion;
|
|
181
|
+
#preSessionUpdateBytes = 0;
|
|
182
|
+
#agentName = "";
|
|
183
|
+
#agentVersion = "";
|
|
184
|
+
#bufferedAgentText = [];
|
|
185
|
+
#capabilities = unsupportedSessionCapabilities();
|
|
186
|
+
#commands = [];
|
|
187
|
+
#configRevision = 0;
|
|
188
|
+
#configOptions = [];
|
|
189
|
+
#nativeSessionId = "";
|
|
190
|
+
#prompted = false;
|
|
191
|
+
#replay = {
|
|
192
|
+
kind: "idle",
|
|
193
|
+
};
|
|
194
|
+
#restored = false;
|
|
195
|
+
#sessionTitle = null;
|
|
196
|
+
#sessionUpdatedAt = "";
|
|
197
|
+
#turn = new IdleAcpTurn();
|
|
198
|
+
#updateTail = Promise.resolve();
|
|
199
|
+
constructor(agent, cwd, additionalDirectories, mobiusSessionId, getObserver, store, metrics) {
|
|
200
|
+
this.#additionalDirectories = [...additionalDirectories];
|
|
201
|
+
this.#agentId = agent.id;
|
|
202
|
+
this.#cwd = cwd;
|
|
203
|
+
this.#environment = agent.environment;
|
|
204
|
+
this.#getObserver = getObserver;
|
|
205
|
+
this.#mobiusSessionId = mobiusSessionId;
|
|
206
|
+
this.#metrics = metrics;
|
|
207
|
+
this.#sessionConfigProtocol = sessionConfigProtocolForAgent(agent.id);
|
|
208
|
+
this.#store = store;
|
|
209
|
+
this.#verifiedAgentVersion = agent.agentVersion;
|
|
210
|
+
if (agent.kind === "in-process-acp") {
|
|
211
|
+
// Mobius hosts the ACP Agent in-process and drives the vendor's own protocol, so there is
|
|
212
|
+
// no adapter process to spawn or supervise here. The endpoint owns its own resources.
|
|
213
|
+
const inProcess = agent.createEndpoint({
|
|
214
|
+
command: agent.command,
|
|
215
|
+
cwd,
|
|
216
|
+
environment: agent.environment,
|
|
217
|
+
});
|
|
218
|
+
this.#inProcessAgent = inProcess;
|
|
219
|
+
this.#runtimeChild = null;
|
|
220
|
+
this.#termination = inProcess.terminated;
|
|
221
|
+
this.#connection = createAcpClient(this).connect(inProcess.app());
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
this.#inProcessAgent = null;
|
|
225
|
+
const child = spawn(agent.adapterPath, [...agent.arguments], {
|
|
226
|
+
cwd,
|
|
227
|
+
detached: process.platform !== "win32",
|
|
228
|
+
env: { ...process.env, ...agent.environment },
|
|
229
|
+
shell: false,
|
|
230
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
231
|
+
});
|
|
232
|
+
this.#runtimeChild = child;
|
|
233
|
+
const stdin = child.stdin;
|
|
234
|
+
const stdout = child.stdout;
|
|
235
|
+
const stderr = child.stderr;
|
|
236
|
+
if (stdin === null || stdout === null || stderr === null) {
|
|
237
|
+
child.kill("SIGKILL");
|
|
238
|
+
throw new AcpExecutionError("ACP process streams are unavailable");
|
|
239
|
+
}
|
|
240
|
+
stderr.setEncoding("utf8");
|
|
241
|
+
stderr.on("data", (chunk) => {
|
|
242
|
+
process.stderr.write(`[${agent.id}-acp] ${chunk}`);
|
|
243
|
+
});
|
|
244
|
+
this.#termination = new Promise((resolve) => {
|
|
245
|
+
child.once("error", (cause) => {
|
|
246
|
+
resolve({ kind: "failed", error: new AcpExecutionError("The ACP process could not run", { cause }) });
|
|
247
|
+
});
|
|
248
|
+
child.once("exit", (code, signal) => {
|
|
249
|
+
resolve({
|
|
250
|
+
kind: "failed",
|
|
251
|
+
error: new AcpExecutionError("The ACP process stopped", { cause: { code, signal } }),
|
|
252
|
+
});
|
|
253
|
+
});
|
|
254
|
+
});
|
|
255
|
+
const stream = ndJsonStream(createWritableAcpStream(stdin), readableWebStream(stdout));
|
|
256
|
+
this.#connection = createAcpClient(this).connect(stream);
|
|
257
|
+
}
|
|
258
|
+
static async #start(options, getObserver, store, initialize, metrics) {
|
|
259
|
+
for (let attempt = 1; attempt <= 2; attempt += 1) {
|
|
260
|
+
options.signal.throwIfAborted();
|
|
261
|
+
const unchanged = await metrics.measure("executable-validation", async () => await Promise.all([
|
|
262
|
+
// Only the adapter topology has an adapter executable to revalidate.
|
|
263
|
+
options.agent.kind === "acp-adapter-process"
|
|
264
|
+
? revalidateExecutable(options.agent.adapterIdentity)
|
|
265
|
+
: Promise.resolve(true),
|
|
266
|
+
revalidateExecutable(options.agent.agentIdentity),
|
|
267
|
+
]));
|
|
268
|
+
options.signal.throwIfAborted();
|
|
269
|
+
if (unchanged.some((result) => !result)) {
|
|
270
|
+
throw new AcpExecutionError("The local Agent runtime changed; restart Mobius before starting a new conversation", {}, "agent_runtime_changed");
|
|
271
|
+
}
|
|
272
|
+
const runtime = metrics.measureSync("process-spawn", () => new AcpProcessSession(options.agent, options.cwd, options.additionalDirectories, options.sessionId, getObserver, store, metrics));
|
|
273
|
+
try {
|
|
274
|
+
await initialize(runtime);
|
|
275
|
+
return runtime;
|
|
276
|
+
}
|
|
277
|
+
catch (error) {
|
|
278
|
+
await runtime.closeProcess();
|
|
279
|
+
options.signal.throwIfAborted();
|
|
280
|
+
if (error instanceof RetryableAcpInitializationError && attempt === 1) {
|
|
281
|
+
console.warn(`[${options.agent.id}-acp] ACP agent initialization failed; retrying once`);
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
if (error instanceof AcpExecutionError) {
|
|
285
|
+
throw error;
|
|
286
|
+
}
|
|
287
|
+
throw new AcpExecutionError("ACP agent initialization failed", {
|
|
288
|
+
cause: error,
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
throw new AcpExecutionError("ACP agent initialization failed");
|
|
293
|
+
}
|
|
294
|
+
static start = async (options, getObserver, store, metrics = unmeasuredOperationMetrics) => await AcpProcessSession.#start(options, getObserver, store, async (runtime) => await runtime.initialize(options.signal, options.origin), metrics);
|
|
295
|
+
static startNativeSessionBrowser = async (options, getObserver, store) => await AcpProcessSession.#start(options, getObserver, store, async (runtime) => await runtime.#initializeAgent(options.signal), unmeasuredOperationMetrics);
|
|
296
|
+
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);
|
|
297
|
+
belongsTo = (agentId, cwd, additionalDirectories) => this.#agentId === agentId &&
|
|
298
|
+
this.#cwd === cwd &&
|
|
299
|
+
arraysEqual(this.#additionalDirectories, additionalDirectories);
|
|
300
|
+
usesEnvironment = (environment) => recordsEqual(this.#environment, environment);
|
|
301
|
+
canRebind = () => !this.#prompted && !this.#turn.running;
|
|
302
|
+
hasRunningTurn = () => this.#turn.running;
|
|
303
|
+
prepared = () => new AcpPreparedSession(this.#agentName, this.#agentVersion, this.#capabilities, this.#commands, this.#configOptions, this.#restored);
|
|
304
|
+
loadHistory = async (signal) => {
|
|
305
|
+
if (!this.#capabilities.loadSession) {
|
|
306
|
+
return {
|
|
307
|
+
status: "unavailable",
|
|
308
|
+
cause: {
|
|
309
|
+
code: "native_history_unsupported",
|
|
310
|
+
message: "This Agent restores context but does not provide message history.",
|
|
311
|
+
},
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
const history = new AcpHistoryReplay();
|
|
315
|
+
this.#replay = { kind: "capture", history };
|
|
316
|
+
try {
|
|
317
|
+
await this.race(this.#connection.agent.request(methods.agent.session.load, {
|
|
318
|
+
additionalDirectories: [...this.#additionalDirectories],
|
|
319
|
+
cwd: this.#cwd,
|
|
320
|
+
mcpServers: [],
|
|
321
|
+
sessionId: this.#nativeSessionId,
|
|
322
|
+
}, { cancellationSignal: signal }), "ACP agent exited while loading history", signal);
|
|
323
|
+
await this.#updateTail;
|
|
324
|
+
signal.throwIfAborted();
|
|
325
|
+
return await embedLocalHistoryImages(await history.snapshot(), signal);
|
|
326
|
+
}
|
|
327
|
+
finally {
|
|
328
|
+
this.#replay = { kind: "idle" };
|
|
329
|
+
}
|
|
330
|
+
};
|
|
331
|
+
emitAgentMessage = async (chunks, messageId) => {
|
|
332
|
+
for (const chunk of chunks) {
|
|
333
|
+
await this.#turn.onText(chunk, messageId);
|
|
334
|
+
}
|
|
335
|
+
};
|
|
336
|
+
bufferAgentText = async (text, messageId) => {
|
|
337
|
+
const previous = this.#bufferedAgentText.at(-1);
|
|
338
|
+
if (previous?.messageId === messageId) {
|
|
339
|
+
this.#bufferedAgentText = [
|
|
340
|
+
...this.#bufferedAgentText.slice(0, -1),
|
|
341
|
+
{ chunks: [...previous.chunks, text], messageId },
|
|
342
|
+
];
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
this.#bufferedAgentText = [...this.#bufferedAgentText, { chunks: [text], messageId }];
|
|
346
|
+
};
|
|
347
|
+
flushAgentText = async () => {
|
|
348
|
+
const buffered = this.#bufferedAgentText;
|
|
349
|
+
this.#bufferedAgentText = [];
|
|
350
|
+
for (const message of buffered) {
|
|
351
|
+
await this.emitAgentMessage(message.chunks, message.messageId);
|
|
352
|
+
}
|
|
353
|
+
};
|
|
354
|
+
recordBufferedAgentTextAsProgress = async () => {
|
|
355
|
+
const buffered = this.#bufferedAgentText;
|
|
356
|
+
this.#bufferedAgentText = [];
|
|
357
|
+
for (const message of buffered) {
|
|
358
|
+
for (const chunk of message.chunks) {
|
|
359
|
+
await this.#turn.activities.recordNarrative("progress", message.messageId, chunk);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
};
|
|
363
|
+
prepareAgentContent = async (content) => {
|
|
364
|
+
if (content.type === "image" && content.uri.length > 0) {
|
|
365
|
+
const signal = AbortSignal.timeout(20_000);
|
|
366
|
+
const raster = await readLocalRaster(content.uri, signal);
|
|
367
|
+
if (raster !== null) {
|
|
368
|
+
return await this.importRaster(raster, signal);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
if (content.type === "image" && content.data.length > 0) {
|
|
372
|
+
const raster = readInlineRaster(content.data, content.name);
|
|
373
|
+
if (raster !== null) {
|
|
374
|
+
return await this.importRaster(raster, AbortSignal.timeout(20_000));
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
if (content.type === "video" && content.data.length > 0) {
|
|
378
|
+
const video = readInlineVideo(content.data, content.mimeType, content.name);
|
|
379
|
+
if (video === null) {
|
|
380
|
+
return { ...content, data: "" };
|
|
381
|
+
}
|
|
382
|
+
return this.importVideo(video);
|
|
383
|
+
}
|
|
384
|
+
return content;
|
|
385
|
+
};
|
|
386
|
+
emitAgentContent = async (content, messageId) => {
|
|
387
|
+
const prepared = await this.prepareAgentContent(content);
|
|
388
|
+
await this.#getObserver().onContent({
|
|
389
|
+
commandId: this.#turn.commandId,
|
|
390
|
+
content: prepared,
|
|
391
|
+
contentId: `content-${crypto.randomUUID()}`,
|
|
392
|
+
kind: AGENT_CONTENT_KIND,
|
|
393
|
+
messageId,
|
|
394
|
+
sessionId: this.#mobiusSessionId,
|
|
395
|
+
});
|
|
396
|
+
};
|
|
397
|
+
importRaster = async (raster, _signal) => {
|
|
398
|
+
if (raster.sourceUri.length > 0) {
|
|
399
|
+
return {
|
|
400
|
+
...imageDisplayContent(raster.mimeType, raster.name, "", ""),
|
|
401
|
+
uri: raster.sourceUri,
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
return imageDisplayContent(raster.mimeType, raster.name, await raster.base64(), "");
|
|
405
|
+
};
|
|
406
|
+
importVideo = (video) => ({
|
|
407
|
+
artifactId: "",
|
|
408
|
+
data: video.base64(),
|
|
409
|
+
mimeType: video.mimeType,
|
|
410
|
+
name: video.name,
|
|
411
|
+
newText: "",
|
|
412
|
+
oldText: "",
|
|
413
|
+
path: "",
|
|
414
|
+
terminalId: "",
|
|
415
|
+
text: "",
|
|
416
|
+
type: "video",
|
|
417
|
+
uri: "",
|
|
418
|
+
});
|
|
419
|
+
async #initializeAgent(signal) {
|
|
420
|
+
await this.#metrics.measure("agent-initialize", async () => await this.#initializeAgentOperation(signal));
|
|
421
|
+
}
|
|
422
|
+
async #initializeAgentOperation(signal) {
|
|
423
|
+
if (this.#inProcessAgent !== null) {
|
|
424
|
+
// The ACP agent runs in this process, but it still owns an app-server child that must
|
|
425
|
+
// start and complete its own handshake before the ACP conversation can begin.
|
|
426
|
+
await this.race(this.#inProcessAgent.initialize(signal), "The Codex app-server exited during initialization", signal).catch((cause) => {
|
|
427
|
+
signal.throwIfAborted();
|
|
428
|
+
throw new RetryableAcpInitializationError(cause);
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
const initialized = await this.race(this.#connection.agent.request(methods.agent.initialize, {
|
|
432
|
+
clientCapabilities: {
|
|
433
|
+
elicitation: { form: {}, url: {} },
|
|
434
|
+
plan: {},
|
|
435
|
+
session: { configOptions: { boolean: {} } },
|
|
436
|
+
},
|
|
437
|
+
clientInfo: { name: "mobius", version: "0.0.3" },
|
|
438
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
439
|
+
}, { cancellationSignal: signal }), "ACP agent exited during initialization", signal).catch((cause) => {
|
|
440
|
+
signal.throwIfAborted();
|
|
441
|
+
throw new RetryableAcpInitializationError(cause);
|
|
442
|
+
});
|
|
443
|
+
if (initialized.protocolVersion !== PROTOCOL_VERSION) {
|
|
444
|
+
throw new AcpExecutionError("ACP agent selected an unsupported protocol version", {}, "unsupported_acp_protocol");
|
|
445
|
+
}
|
|
446
|
+
this.#capabilities = normalizeAcpCapabilities(initialized);
|
|
447
|
+
this.#agentName = truncate(initialized.agentInfo?.title ?? initialized.agentInfo?.name ?? this.#agentId, 255);
|
|
448
|
+
this.#agentVersion = truncate(this.#verifiedAgentVersion.length > 0 ? this.#verifiedAgentVersion : (initialized.agentInfo?.version ?? ""), 128);
|
|
449
|
+
}
|
|
450
|
+
initialize = async (signal, origin, forkPoint) => {
|
|
451
|
+
await this.#initializeAgent(signal);
|
|
452
|
+
let stored = this.#metrics.measureSync("session-state-read", () => origin?.kind === "import"
|
|
453
|
+
? new FoundAcpStoredSession(new AcpStoredSession(this.#mobiusSessionId, this.#agentId, nativeSessionIdSchema.parse(origin.nativeSessionId), this.#cwd, this.#additionalDirectories, true))
|
|
454
|
+
: this.#store.read(this.#mobiusSessionId));
|
|
455
|
+
if (stored instanceof FoundAcpStoredSession && !stored.session.prompted) {
|
|
456
|
+
this.#store.remove(this.#mobiusSessionId);
|
|
457
|
+
stored = this.#metrics.measureSync("session-state-read", () => this.#store.read(this.#mobiusSessionId));
|
|
458
|
+
}
|
|
459
|
+
if (stored instanceof DeletedAcpStoredSession) {
|
|
460
|
+
throw new AcpExecutionError("The native Agent session was deleted. Start a new chat.", {}, "native_session_deleted");
|
|
461
|
+
}
|
|
462
|
+
let lifecycleResponse;
|
|
463
|
+
if (origin?.kind === "fork") {
|
|
464
|
+
if (!this.#capabilities.unstableForkSession) {
|
|
465
|
+
throw new AcpExecutionError("This Agent does not support session forking", {}, "native_session_unsupported");
|
|
466
|
+
}
|
|
467
|
+
if (this.#additionalDirectories.length > 0 && !this.#capabilities.additionalDirectories) {
|
|
468
|
+
throw new AcpExecutionError("This Agent cannot restore additional working directories", {}, "native_session_unsupported");
|
|
469
|
+
}
|
|
470
|
+
const forked = await this.#metrics.measure("session-fork", async () => await this.race(this.#connection.agent.request(methods.agent.session.fork, {
|
|
471
|
+
sessionId: nativeSessionIdSchema.parse(origin.nativeSessionId),
|
|
472
|
+
cwd: this.#cwd,
|
|
473
|
+
additionalDirectories: [...this.#additionalDirectories],
|
|
474
|
+
mcpServers: [],
|
|
475
|
+
...(forkPoint === undefined
|
|
476
|
+
? {}
|
|
477
|
+
: {
|
|
478
|
+
_meta: {
|
|
479
|
+
jetbrains: {
|
|
480
|
+
air: {
|
|
481
|
+
fork: {
|
|
482
|
+
version: 1,
|
|
483
|
+
messageFingerprint: forkPoint.messageFingerprint,
|
|
484
|
+
messageId: forkPoint.messageId,
|
|
485
|
+
messageOccurrence: forkPoint.messageOccurrence,
|
|
486
|
+
},
|
|
487
|
+
},
|
|
488
|
+
},
|
|
489
|
+
},
|
|
490
|
+
}),
|
|
491
|
+
}, { cancellationSignal: signal }), "ACP agent exited while forking a session", signal));
|
|
492
|
+
this.selectNativeSession(forked.sessionId);
|
|
493
|
+
if (this.#nativeSessionId === origin.nativeSessionId ||
|
|
494
|
+
this.#store.findNative(this.#agentId, this.#nativeSessionId).length > 0) {
|
|
495
|
+
throw new AcpExecutionError("The Agent did not create an independent fork", {}, "invalid_native_session_response");
|
|
496
|
+
}
|
|
497
|
+
this.#prompted = true;
|
|
498
|
+
this.#restored = true;
|
|
499
|
+
lifecycleResponse = forked;
|
|
500
|
+
}
|
|
501
|
+
else if (stored instanceof FoundAcpStoredSession &&
|
|
502
|
+
stored.session.agentId === this.#agentId &&
|
|
503
|
+
stored.session.cwd === this.#cwd &&
|
|
504
|
+
arraysEqual(stored.session.additionalDirectories, this.#additionalDirectories)) {
|
|
505
|
+
this.selectNativeSession(stored.session.nativeSessionId);
|
|
506
|
+
this.#prompted = stored.session.prompted;
|
|
507
|
+
this.#restored = true;
|
|
508
|
+
if (this.#capabilities.resumeSession) {
|
|
509
|
+
lifecycleResponse = await this.#metrics.measure("session-resume", async () => await this.race(this.#connection.agent.request(methods.agent.session.resume, {
|
|
510
|
+
additionalDirectories: [...this.#additionalDirectories],
|
|
511
|
+
cwd: this.#cwd,
|
|
512
|
+
mcpServers: [],
|
|
513
|
+
sessionId: this.#nativeSessionId,
|
|
514
|
+
}, { cancellationSignal: signal }), "ACP agent exited while resuming a session", signal));
|
|
515
|
+
}
|
|
516
|
+
else if (this.#capabilities.loadSession) {
|
|
517
|
+
this.#replay = { kind: "discard" };
|
|
518
|
+
try {
|
|
519
|
+
lifecycleResponse = await this.#metrics.measure("session-load", async () => await this.race(this.#connection.agent.request(methods.agent.session.load, {
|
|
520
|
+
additionalDirectories: [...this.#additionalDirectories],
|
|
521
|
+
cwd: this.#cwd,
|
|
522
|
+
mcpServers: [],
|
|
523
|
+
sessionId: this.#nativeSessionId,
|
|
524
|
+
}, { cancellationSignal: signal }), "ACP agent exited while loading a session", signal));
|
|
525
|
+
}
|
|
526
|
+
finally {
|
|
527
|
+
await this.#updateTail;
|
|
528
|
+
this.#replay = { kind: "idle" };
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
else {
|
|
532
|
+
throw new AcpExecutionError("The ACP agent cannot restore its persisted session", {}, "session_restore_unsupported");
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
else {
|
|
536
|
+
if (stored instanceof FoundAcpStoredSession) {
|
|
537
|
+
if (stored.session.prompted) {
|
|
538
|
+
throw new AcpExecutionError("The agent or workspace cannot change after a conversation has started", {}, "session_identity_mismatch");
|
|
539
|
+
}
|
|
540
|
+
this.#store.remove(this.#mobiusSessionId);
|
|
541
|
+
}
|
|
542
|
+
const created = await this.#metrics.measure("session-new", async () => await this.race(this.#connection.agent.request(methods.agent.session.new, {
|
|
543
|
+
additionalDirectories: [...this.#additionalDirectories],
|
|
544
|
+
cwd: this.#cwd,
|
|
545
|
+
mcpServers: [],
|
|
546
|
+
}, { cancellationSignal: signal }), "ACP agent exited while starting a session", signal));
|
|
547
|
+
this.selectNativeSession(created.sessionId);
|
|
548
|
+
lifecycleResponse = created;
|
|
549
|
+
}
|
|
550
|
+
this.#configOptions = this.#sessionConfigProtocol.normalizeLifecycle(lifecycleResponse);
|
|
551
|
+
await this.#updateTail;
|
|
552
|
+
signal.throwIfAborted();
|
|
553
|
+
if (this.#prompted) {
|
|
554
|
+
this.#store.write(new AcpStoredSession(this.#mobiusSessionId, this.#agentId, this.#nativeSessionId, this.#cwd, this.#additionalDirectories, true));
|
|
555
|
+
}
|
|
556
|
+
};
|
|
557
|
+
listNativeSessions = async (cursor, signal) => {
|
|
558
|
+
if (!this.#capabilities.listSessions) {
|
|
559
|
+
throw new AcpExecutionError("This Agent does not support native session listing", {}, "native_session_unsupported");
|
|
560
|
+
}
|
|
561
|
+
const response = await this.race(this.#connection.agent.request(methods.agent.session.list, cursor === null ? {} : { cursor }, {
|
|
562
|
+
cancellationSignal: signal,
|
|
563
|
+
}), "ACP agent exited while listing sessions", signal);
|
|
564
|
+
const decoded = nativeSessionPageSchema.safeParse(response);
|
|
565
|
+
if (!decoded.success) {
|
|
566
|
+
throw new AcpExecutionError("The Agent returned an invalid native session list", { cause: decoded.error }, "invalid_native_session_response");
|
|
567
|
+
}
|
|
568
|
+
return decoded.data;
|
|
569
|
+
};
|
|
570
|
+
deleteNativeSession = async (nativeSessionId, signal) => {
|
|
571
|
+
if (!this.#capabilities.deleteSession || !this.#capabilities.listSessions) {
|
|
572
|
+
throw new AcpExecutionError("This Agent does not support native session deletion", {}, "native_session_unsupported");
|
|
573
|
+
}
|
|
574
|
+
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);
|
|
575
|
+
};
|
|
576
|
+
nativeSessionId = () => this.#nativeSessionId;
|
|
577
|
+
adoptNativeSessionId = (sessionId) => {
|
|
578
|
+
if (this.#prompted || this.#nativeSessionId !== sessionId) {
|
|
579
|
+
throw new AcpExecutionError("The new native Session cannot be adopted", {}, "session_identity_mismatch");
|
|
580
|
+
}
|
|
581
|
+
const previousSessionId = this.#mobiusSessionId;
|
|
582
|
+
this.#store.write(new AcpStoredSession(sessionId, this.#agentId, sessionId, this.#cwd, this.#additionalDirectories, false));
|
|
583
|
+
this.#store.remove(previousSessionId);
|
|
584
|
+
this.#mobiusSessionId = sessionId;
|
|
585
|
+
};
|
|
586
|
+
configure = async (options) => {
|
|
587
|
+
const existing = this.#configOptions.find((option) => option.id === options.configId);
|
|
588
|
+
if (existing === undefined || existing.type !== options.valueType) {
|
|
589
|
+
throw new AcpExecutionError("The requested ACP configuration option is unavailable", {}, "invalid_session_configuration");
|
|
590
|
+
}
|
|
591
|
+
if (existing.type === "select") {
|
|
592
|
+
if (existing.values.length < 2) {
|
|
593
|
+
throw new AcpExecutionError("The requested ACP configuration option is unavailable", {}, "invalid_session_configuration");
|
|
594
|
+
}
|
|
595
|
+
if (!existing.values.some((entry) => entry.value === options.value)) {
|
|
596
|
+
throw new AcpConfigurationValueUnavailableError(options.configId, options.value, existing.values.map((entry) => entry.value));
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
const configRevision = this.#configRevision;
|
|
600
|
+
try {
|
|
601
|
+
const configured = await this.#sessionConfigProtocol.configure(this.#configOptions, options, this.#nativeSessionId, {
|
|
602
|
+
request: async (method, params, failureMessage, signal) => await this.race(this.#connection.agent.request(method, params, {
|
|
603
|
+
cancellationSignal: signal,
|
|
604
|
+
}), failureMessage, signal),
|
|
605
|
+
});
|
|
606
|
+
const applied = configured.find((option) => option.id === options.configId);
|
|
607
|
+
if (applied === undefined ||
|
|
608
|
+
applied.type !== options.valueType ||
|
|
609
|
+
(applied.type === "boolean" && applied.booleanValue !== options.booleanValue) ||
|
|
610
|
+
(applied.type === "select" && applied.currentValue !== options.value)) {
|
|
611
|
+
throw new AcpExecutionError("The Agent did not apply the requested session configuration", {}, "invalid_session_configuration");
|
|
612
|
+
}
|
|
613
|
+
await this.#updateTail;
|
|
614
|
+
if (this.#configRevision === configRevision) {
|
|
615
|
+
this.#configOptions = configured;
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
catch (error) {
|
|
619
|
+
if (error instanceof SessionConfigProtocolError) {
|
|
620
|
+
throw new AcpExecutionError(error.message, { cause: error }, error.code);
|
|
621
|
+
}
|
|
622
|
+
throw error;
|
|
623
|
+
}
|
|
624
|
+
return this.#configOptions;
|
|
625
|
+
};
|
|
626
|
+
buildPrompt = (options) => {
|
|
627
|
+
if (options.images.length > 0 && !this.#capabilities.imagePrompt) {
|
|
628
|
+
throw new AcpExecutionError("The selected agent does not accept image prompts", {}, "unsupported_prompt_content");
|
|
629
|
+
}
|
|
630
|
+
if (options.resources.some((resource) => resource.type === "embedded") &&
|
|
631
|
+
!this.#capabilities.embeddedContextPrompt) {
|
|
632
|
+
throw new AcpExecutionError("The selected agent does not accept embedded context", {}, "unsupported_prompt_content");
|
|
633
|
+
}
|
|
634
|
+
const prompt = [];
|
|
635
|
+
if (options.prompt.length > 0) {
|
|
636
|
+
prompt.push({ text: options.prompt, type: "text" });
|
|
637
|
+
}
|
|
638
|
+
for (const image of options.images) {
|
|
639
|
+
prompt.push({
|
|
640
|
+
_meta: { mobius: { name: image.name } },
|
|
641
|
+
data: image.data,
|
|
642
|
+
mimeType: image.mimeType,
|
|
643
|
+
type: "image",
|
|
644
|
+
});
|
|
645
|
+
}
|
|
646
|
+
for (const resource of options.resources) {
|
|
647
|
+
if (resource.type === "embedded") {
|
|
648
|
+
prompt.push({
|
|
649
|
+
resource: {
|
|
650
|
+
mimeType: resource.mimeType,
|
|
651
|
+
text: resource.text,
|
|
652
|
+
uri: resource.uri,
|
|
653
|
+
},
|
|
654
|
+
type: "resource",
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
else {
|
|
658
|
+
prompt.push({
|
|
659
|
+
mimeType: resource.mimeType,
|
|
660
|
+
name: resource.name,
|
|
661
|
+
type: "resource_link",
|
|
662
|
+
uri: resource.uri,
|
|
663
|
+
});
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
if (prompt.length === 0) {
|
|
667
|
+
throw new AcpExecutionError("A prompt must contain text or an attachment", {}, "empty_prompt");
|
|
668
|
+
}
|
|
669
|
+
return prompt;
|
|
670
|
+
};
|
|
671
|
+
prompt = async (options) => {
|
|
672
|
+
if (this.#turn.running) {
|
|
673
|
+
throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
|
|
674
|
+
}
|
|
675
|
+
const prompt = this.buildPrompt(options);
|
|
676
|
+
this.#store.write(new AcpStoredSession(this.#mobiusSessionId, this.#agentId, this.#nativeSessionId, this.#cwd, this.#additionalDirectories, true));
|
|
677
|
+
this.#prompted = true;
|
|
678
|
+
const running = new RunningAcpTurn(options.commandId, options.onActivity, options.onNarration, options.onText, this.prepareAgentContent);
|
|
679
|
+
this.#turn = running;
|
|
680
|
+
try {
|
|
681
|
+
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);
|
|
682
|
+
await this.#updateTail;
|
|
683
|
+
await this.flushAgentText();
|
|
684
|
+
await running.activities.finish();
|
|
685
|
+
let result;
|
|
686
|
+
try {
|
|
687
|
+
result = decodeAgentPromptResponse(response);
|
|
688
|
+
}
|
|
689
|
+
catch (cause) {
|
|
690
|
+
throw new AcpExecutionError("ACP agent returned an invalid prompt response", { cause }, "acp_invalid_prompt_response");
|
|
691
|
+
}
|
|
692
|
+
if (result.usage != null || result._meta?.quota !== undefined) {
|
|
693
|
+
await this.#getObserver().onUsage({
|
|
694
|
+
_meta: result._meta ?? null,
|
|
695
|
+
commandId: options.commandId,
|
|
696
|
+
kind: SESSION_USAGE_UPDATED_KIND,
|
|
697
|
+
sessionId: this.#mobiusSessionId,
|
|
698
|
+
source: "prompt",
|
|
699
|
+
usage: result.usage ?? null,
|
|
700
|
+
});
|
|
701
|
+
}
|
|
702
|
+
return result;
|
|
703
|
+
}
|
|
704
|
+
catch (error) {
|
|
705
|
+
await running.activities.finish();
|
|
706
|
+
if (error instanceof AcpExecutionError) {
|
|
707
|
+
throw error;
|
|
708
|
+
}
|
|
709
|
+
throw new AcpExecutionError("ACP agent execution failed", {
|
|
710
|
+
cause: error,
|
|
711
|
+
});
|
|
712
|
+
}
|
|
713
|
+
finally {
|
|
714
|
+
this.#bufferedAgentText = [];
|
|
715
|
+
this.#turn = new IdleAcpTurn();
|
|
716
|
+
}
|
|
717
|
+
};
|
|
718
|
+
steer = async (options) => {
|
|
719
|
+
if (!this.#capabilities.steering) {
|
|
720
|
+
throw new AcpExecutionError("The selected agent does not support mid-turn steering", {}, "steering_unsupported");
|
|
721
|
+
}
|
|
722
|
+
if (!this.#turn.running || this.#turn.commandId !== options.targetCommandId) {
|
|
723
|
+
throw new AcpExecutionError("The target turn is no longer active", {}, "steering_target_unavailable");
|
|
724
|
+
}
|
|
725
|
+
const prompt = this.buildPrompt(options);
|
|
726
|
+
const response = await this.race(this.#connection.agent.request("_session/steering", {
|
|
727
|
+
_meta: { steering: { idleBehavior: "promptRequired" } },
|
|
728
|
+
prompt,
|
|
729
|
+
sessionId: this.#nativeSessionId,
|
|
730
|
+
}), "ACP agent exited during steering", options.signal);
|
|
731
|
+
if (!isRecord(response)) {
|
|
732
|
+
throw new AcpExecutionError("ACP agent returned an invalid steering response", {}, "acp_invalid_steering_response");
|
|
733
|
+
}
|
|
734
|
+
const outcome = response["outcome"];
|
|
735
|
+
if (outcome === "injected" || outcome === "startedNewTurn") {
|
|
736
|
+
return outcome;
|
|
737
|
+
}
|
|
738
|
+
if (outcome === "promptRequired") {
|
|
739
|
+
throw new AcpExecutionError("The target turn finished before steering could be injected", {}, "steering_target_unavailable");
|
|
740
|
+
}
|
|
741
|
+
if (outcome === "failed") {
|
|
742
|
+
throw new AcpExecutionError("The Agent could not inject steering", {}, "steering_failed");
|
|
743
|
+
}
|
|
744
|
+
throw new AcpExecutionError("ACP agent returned an invalid steering response", {}, "acp_invalid_steering_response");
|
|
745
|
+
};
|
|
746
|
+
cancel = async () => {
|
|
747
|
+
const capturedProcesses = this.#runtimeChild === null ? [] : await captureProcessTree(this.#runtimeChild);
|
|
748
|
+
try {
|
|
749
|
+
await this.cancelPendingInteractions();
|
|
750
|
+
if (this.#turn.running) {
|
|
751
|
+
await this.#connection.agent.notify(methods.agent.session.cancel, {
|
|
752
|
+
sessionId: this.#nativeSessionId,
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
finally {
|
|
757
|
+
await this.closeProcess(capturedProcesses);
|
|
758
|
+
}
|
|
759
|
+
};
|
|
760
|
+
respondPermission = async (options) => {
|
|
761
|
+
const pending = this.#pendingPermissions.get(options.interactionId);
|
|
762
|
+
if (pending === undefined) {
|
|
763
|
+
throw new AcpExecutionError("The permission request is no longer active", {}, "permission_request_not_found");
|
|
764
|
+
}
|
|
765
|
+
if (options.outcome === "selected" && !pending.optionIds.has(options.optionId)) {
|
|
766
|
+
throw new AcpExecutionError("The selected permission option is unavailable", {}, "invalid_permission_response");
|
|
767
|
+
}
|
|
768
|
+
const resolved = options.outcome === "selected" ? pending.select(options.optionId) : pending.cancel();
|
|
769
|
+
if (!resolved) {
|
|
770
|
+
throw new AcpExecutionError("The permission request was already resolved", {}, "permission_request_not_found");
|
|
771
|
+
}
|
|
772
|
+
this.#pendingPermissions.delete(options.interactionId);
|
|
773
|
+
await this.#getObserver().onPermissionResolved({
|
|
774
|
+
interactionId: options.interactionId,
|
|
775
|
+
kind: SESSION_PERMISSION_RESOLVED_KIND,
|
|
776
|
+
optionId: options.outcome === "selected" ? options.optionId : "",
|
|
777
|
+
outcome: options.outcome,
|
|
778
|
+
sessionId: this.#mobiusSessionId,
|
|
779
|
+
});
|
|
780
|
+
};
|
|
781
|
+
respondElicitation = async (options) => {
|
|
782
|
+
const pending = this.#pendingElicitations.get(options.interactionId);
|
|
783
|
+
if (pending === undefined) {
|
|
784
|
+
throw new AcpExecutionError("The elicitation request is no longer active", {}, "elicitation_request_not_found");
|
|
785
|
+
}
|
|
786
|
+
let resolved = false;
|
|
787
|
+
if (options.action === "accept") {
|
|
788
|
+
if (pending.elicitationId.length > 0) {
|
|
789
|
+
resolved = pending.accept({});
|
|
790
|
+
if (resolved) {
|
|
791
|
+
this.#acceptedUrlElicitations.set(pending.elicitationId, pending.interactionId);
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
else {
|
|
795
|
+
resolved = pending.accept(validateElicitationContent(options.content, pending.requestedSchema));
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
else if (options.action === "decline") {
|
|
799
|
+
resolved = pending.decline();
|
|
800
|
+
}
|
|
801
|
+
else {
|
|
802
|
+
resolved = pending.cancel();
|
|
803
|
+
}
|
|
804
|
+
if (!resolved) {
|
|
805
|
+
throw new AcpExecutionError("The elicitation request was already resolved", {}, "elicitation_request_not_found");
|
|
806
|
+
}
|
|
807
|
+
this.#pendingElicitations.delete(options.interactionId);
|
|
808
|
+
await this.#getObserver().onElicitationResolved({
|
|
809
|
+
action: options.action,
|
|
810
|
+
interactionId: options.interactionId,
|
|
811
|
+
kind: SESSION_ELICITATION_RESOLVED_KIND,
|
|
812
|
+
sessionId: this.#mobiusSessionId,
|
|
813
|
+
});
|
|
814
|
+
};
|
|
815
|
+
onPermission = async (request, signal) => {
|
|
816
|
+
this.assertNativeSession(request.sessionId);
|
|
817
|
+
const interactionId = `permission-${crypto.randomUUID()}`;
|
|
818
|
+
const options = request.options.slice(0, 20).map((option) => ({
|
|
819
|
+
kind: option.kind,
|
|
820
|
+
name: truncate(option.name, 255),
|
|
821
|
+
optionId: truncate(option.optionId, 255),
|
|
822
|
+
}));
|
|
823
|
+
if (options.length === 0) {
|
|
824
|
+
throw new AcpExecutionError("ACP permission request did not provide any choices", {}, "invalid_agent_permission_request");
|
|
825
|
+
}
|
|
826
|
+
const pending = new PendingPermission(interactionId, new Set(options.map((option) => option.optionId)));
|
|
827
|
+
this.#pendingPermissions.set(interactionId, pending);
|
|
828
|
+
const abort = () => {
|
|
829
|
+
void this.cancelPermission(interactionId);
|
|
830
|
+
};
|
|
831
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
832
|
+
try {
|
|
833
|
+
await this.#getObserver().onPermission({
|
|
834
|
+
commandId: this.#turn.commandId,
|
|
835
|
+
interactionId,
|
|
836
|
+
kind: SESSION_PERMISSION_REQUESTED_KIND,
|
|
837
|
+
options,
|
|
838
|
+
sessionId: this.#mobiusSessionId,
|
|
839
|
+
title: truncate(request.toolCall.title ?? "Permission required", 500),
|
|
840
|
+
toolCallId: truncate(request.toolCall.toolCallId, 255),
|
|
841
|
+
toolKind: truncate(request.toolCall.kind ?? "other", 64),
|
|
842
|
+
});
|
|
843
|
+
return await pending.completion.promise;
|
|
844
|
+
}
|
|
845
|
+
finally {
|
|
846
|
+
signal.removeEventListener("abort", abort);
|
|
847
|
+
this.#pendingPermissions.delete(interactionId);
|
|
848
|
+
}
|
|
849
|
+
};
|
|
850
|
+
onElicitation = async (request, signal) => {
|
|
851
|
+
const sessionId = Reflect.get(request, "sessionId");
|
|
852
|
+
if (typeof sessionId !== "string") {
|
|
853
|
+
throw new AcpExecutionError("Mobius only accepts session-scoped ACP elicitations", {}, "unsupported_elicitation_scope");
|
|
854
|
+
}
|
|
855
|
+
this.assertNativeSession(sessionId);
|
|
856
|
+
if (request.mode !== "form" && request.mode !== "url") {
|
|
857
|
+
throw new AcpExecutionError("The ACP agent requested an unsupported elicitation mode", {}, "unsupported_elicitation_mode");
|
|
858
|
+
}
|
|
859
|
+
const interactionId = `elicitation-${crypto.randomUUID()}`;
|
|
860
|
+
const schemaValue = Reflect.get(request, "requestedSchema");
|
|
861
|
+
const requestedSchema = request.mode === "form" ? schemaValue : {};
|
|
862
|
+
const elicitationIdValue = Reflect.get(request, "elicitationId");
|
|
863
|
+
const elicitationId = request.mode === "url" && typeof elicitationIdValue === "string" ? truncate(elicitationIdValue, 255) : "";
|
|
864
|
+
const pending = new PendingElicitation(interactionId, elicitationId, requestedSchema);
|
|
865
|
+
this.#pendingElicitations.set(interactionId, pending);
|
|
866
|
+
const abort = () => {
|
|
867
|
+
void this.cancelElicitation(interactionId);
|
|
868
|
+
};
|
|
869
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
870
|
+
try {
|
|
871
|
+
await this.#getObserver().onElicitation({
|
|
872
|
+
accepted: false,
|
|
873
|
+
commandId: this.#turn.commandId,
|
|
874
|
+
elicitationId,
|
|
875
|
+
fields: normalizeElicitationFields(requestedSchema),
|
|
876
|
+
interactionId,
|
|
877
|
+
kind: SESSION_ELICITATION_REQUESTED_KIND,
|
|
878
|
+
message: truncate(request.message, 2_000),
|
|
879
|
+
mode: request.mode,
|
|
880
|
+
sessionId: this.#mobiusSessionId,
|
|
881
|
+
url: request.mode === "url" && typeof Reflect.get(request, "url") === "string"
|
|
882
|
+
? truncate(readString(Reflect.get(request, "url")), 4_096)
|
|
883
|
+
: "",
|
|
884
|
+
});
|
|
885
|
+
return await pending.completion.promise;
|
|
886
|
+
}
|
|
887
|
+
finally {
|
|
888
|
+
signal.removeEventListener("abort", abort);
|
|
889
|
+
this.#pendingElicitations.delete(interactionId);
|
|
890
|
+
}
|
|
891
|
+
};
|
|
892
|
+
onElicitationComplete = async (notification) => {
|
|
893
|
+
const interactionId = this.#acceptedUrlElicitations.get(notification.elicitationId);
|
|
894
|
+
if (interactionId === undefined) {
|
|
895
|
+
return;
|
|
896
|
+
}
|
|
897
|
+
this.#acceptedUrlElicitations.delete(notification.elicitationId);
|
|
898
|
+
await this.#getObserver().onElicitationResolved({
|
|
899
|
+
action: "complete",
|
|
900
|
+
interactionId,
|
|
901
|
+
kind: SESSION_ELICITATION_RESOLVED_KIND,
|
|
902
|
+
sessionId: this.#mobiusSessionId,
|
|
903
|
+
});
|
|
904
|
+
};
|
|
905
|
+
onUpdate = (notification) => {
|
|
906
|
+
if (this.#nativeSessionId.length === 0) {
|
|
907
|
+
const notificationBytes = Buffer.byteLength(JSON.stringify(notification));
|
|
908
|
+
if (this.#preSessionUpdates.length >= MAX_PRE_SESSION_UPDATES ||
|
|
909
|
+
this.#preSessionUpdateBytes + notificationBytes > MAX_PRE_SESSION_UPDATE_BYTES) {
|
|
910
|
+
return Promise.reject(new AcpExecutionError("ACP agent sent too many updates before creating its session", {}, "agent_update_limit"));
|
|
911
|
+
}
|
|
912
|
+
this.#preSessionUpdates.push(notification);
|
|
913
|
+
this.#preSessionUpdateBytes += notificationBytes;
|
|
914
|
+
return Promise.resolve();
|
|
915
|
+
}
|
|
916
|
+
return this.enqueueUpdate(notification);
|
|
917
|
+
};
|
|
918
|
+
enqueueUpdate = (notification) => {
|
|
919
|
+
this.#updateTail = this.#updateTail.then(async () => await this.processUpdate(notification));
|
|
920
|
+
return this.#updateTail;
|
|
921
|
+
};
|
|
922
|
+
selectNativeSession = (sessionId) => {
|
|
923
|
+
const selected = nativeSessionIdSchema.parse(sessionId);
|
|
924
|
+
if (this.#nativeSessionId.length > 0 && this.#nativeSessionId !== selected) {
|
|
925
|
+
throw new AcpExecutionError("ACP agent attempted to replace the selected session", {}, "invalid_agent_session");
|
|
926
|
+
}
|
|
927
|
+
this.#nativeSessionId = selected;
|
|
928
|
+
const pending = this.#preSessionUpdates.splice(0);
|
|
929
|
+
this.#preSessionUpdateBytes = 0;
|
|
930
|
+
for (const notification of pending) {
|
|
931
|
+
void this.enqueueUpdate(notification);
|
|
932
|
+
}
|
|
933
|
+
};
|
|
934
|
+
processUpdate = async (notification) => {
|
|
935
|
+
this.assertNativeSession(notification.sessionId);
|
|
936
|
+
const update = notification.update;
|
|
937
|
+
if (this.#replay.kind === "capture") {
|
|
938
|
+
await this.#replay.history.record(update);
|
|
939
|
+
}
|
|
940
|
+
if (this.#replay.kind !== "idle" &&
|
|
941
|
+
(update.sessionUpdate === "user_message_chunk" ||
|
|
942
|
+
update.sessionUpdate === "agent_message_chunk" ||
|
|
943
|
+
update.sessionUpdate === "agent_thought_chunk" ||
|
|
944
|
+
update.sessionUpdate === "tool_call" ||
|
|
945
|
+
update.sessionUpdate === "tool_call_update" ||
|
|
946
|
+
update.sessionUpdate === "plan" ||
|
|
947
|
+
update.sessionUpdate === "plan_update" ||
|
|
948
|
+
update.sessionUpdate === "plan_removed")) {
|
|
949
|
+
return;
|
|
950
|
+
}
|
|
951
|
+
if (update.sessionUpdate === "agent_message_chunk") {
|
|
952
|
+
if (update.content.type === "text") {
|
|
953
|
+
if (isProgressMessage(update)) {
|
|
954
|
+
await this.#turn.activities.recordNarrative("progress", update.messageId ?? "current", update.content.text);
|
|
955
|
+
}
|
|
956
|
+
else {
|
|
957
|
+
await this.#turn.activities.finishNarrative();
|
|
958
|
+
await this.bufferAgentText(update.content.text, truncate(update.messageId ?? "", 255));
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
else {
|
|
962
|
+
await this.#turn.activities.finishNarrative();
|
|
963
|
+
await this.flushAgentText();
|
|
964
|
+
await this.emitAgentContent(normalizeContentBlock(update.content), truncate(update.messageId ?? "", 255));
|
|
965
|
+
}
|
|
966
|
+
return;
|
|
967
|
+
}
|
|
968
|
+
if (update.sessionUpdate === "agent_thought_chunk") {
|
|
969
|
+
if (update.content.type === "text") {
|
|
970
|
+
await this.#turn.activities.recordNarrative("reasoning", update.messageId ?? "current", update.content.text);
|
|
971
|
+
}
|
|
972
|
+
return;
|
|
973
|
+
}
|
|
974
|
+
if (update.sessionUpdate === "tool_call") {
|
|
975
|
+
await this.recordBufferedAgentTextAsProgress();
|
|
976
|
+
await this.#turn.activities.recordToolCall(update);
|
|
977
|
+
return;
|
|
978
|
+
}
|
|
979
|
+
if (update.sessionUpdate === "tool_call_update") {
|
|
980
|
+
await this.#turn.activities.recordToolCallUpdate(update);
|
|
981
|
+
return;
|
|
982
|
+
}
|
|
983
|
+
if (update.sessionUpdate === "plan") {
|
|
984
|
+
await this.#turn.activities.recordPlan(update);
|
|
985
|
+
return;
|
|
986
|
+
}
|
|
987
|
+
if (update.sessionUpdate === "plan_update") {
|
|
988
|
+
await this.#turn.activities.recordPlanUpdate(update);
|
|
989
|
+
return;
|
|
990
|
+
}
|
|
991
|
+
if (update.sessionUpdate === "plan_removed") {
|
|
992
|
+
await this.#turn.activities.removePlan(update);
|
|
993
|
+
return;
|
|
994
|
+
}
|
|
995
|
+
if (update.sessionUpdate === "available_commands_update") {
|
|
996
|
+
const commands = update.availableCommands
|
|
997
|
+
.slice(0, 500)
|
|
998
|
+
.map((command) => ({
|
|
999
|
+
description: truncate(command.description, 500),
|
|
1000
|
+
inputHint: truncate(command.input?.hint ?? "", 255),
|
|
1001
|
+
name: truncate(command.name, 128),
|
|
1002
|
+
}))
|
|
1003
|
+
.filter((command) => command.name.length > 0);
|
|
1004
|
+
this.#commands = commands;
|
|
1005
|
+
await this.#getObserver().onCommands({
|
|
1006
|
+
commands,
|
|
1007
|
+
kind: SESSION_COMMANDS_UPDATED_KIND,
|
|
1008
|
+
sessionId: this.#mobiusSessionId,
|
|
1009
|
+
});
|
|
1010
|
+
return;
|
|
1011
|
+
}
|
|
1012
|
+
if (update.sessionUpdate === "config_option_update") {
|
|
1013
|
+
this.#configOptions = this.#sessionConfigProtocol.normalizeUpdate(this.#configOptions, update.configOptions);
|
|
1014
|
+
this.#configRevision += 1;
|
|
1015
|
+
await this.emitConfigUpdate();
|
|
1016
|
+
return;
|
|
1017
|
+
}
|
|
1018
|
+
if (update.sessionUpdate === "current_mode_update") {
|
|
1019
|
+
this.#configOptions = this.#configOptions.map((option) => option.category === "mode" ? { ...option, currentValue: update.currentModeId } : option);
|
|
1020
|
+
this.#configRevision += 1;
|
|
1021
|
+
await this.emitConfigUpdate();
|
|
1022
|
+
return;
|
|
1023
|
+
}
|
|
1024
|
+
if (update.sessionUpdate === "session_info_update") {
|
|
1025
|
+
if (Object.hasOwn(update, "title")) {
|
|
1026
|
+
this.#sessionTitle = truncate(update.title ?? "", 500);
|
|
1027
|
+
}
|
|
1028
|
+
if (Object.hasOwn(update, "updatedAt")) {
|
|
1029
|
+
this.#sessionUpdatedAt = truncate(update.updatedAt ?? "", 128);
|
|
1030
|
+
}
|
|
1031
|
+
await this.#getObserver().onInfo({
|
|
1032
|
+
kind: SESSION_INFO_UPDATED_KIND,
|
|
1033
|
+
sessionId: this.#mobiusSessionId,
|
|
1034
|
+
title: this.#sessionTitle,
|
|
1035
|
+
updatedAt: this.#sessionUpdatedAt,
|
|
1036
|
+
});
|
|
1037
|
+
return;
|
|
1038
|
+
}
|
|
1039
|
+
if (update.sessionUpdate === "usage_update") {
|
|
1040
|
+
await this.#getObserver().onUsage({
|
|
1041
|
+
costAmount: update.cost?.amount ?? 0,
|
|
1042
|
+
costCurrency: truncate(update.cost?.currency ?? "", 16),
|
|
1043
|
+
hasCost: update.cost !== undefined && update.cost !== null,
|
|
1044
|
+
kind: SESSION_USAGE_UPDATED_KIND,
|
|
1045
|
+
sessionId: this.#mobiusSessionId,
|
|
1046
|
+
size: Math.max(0, Math.trunc(update.size)),
|
|
1047
|
+
source: "context",
|
|
1048
|
+
used: Math.max(0, Math.trunc(update.used)),
|
|
1049
|
+
});
|
|
1050
|
+
}
|
|
1051
|
+
};
|
|
1052
|
+
close = async () => {
|
|
1053
|
+
try {
|
|
1054
|
+
await this.cancelPendingInteractions();
|
|
1055
|
+
if (this.#capabilities.closeSession && this.#nativeSessionId.length > 0) {
|
|
1056
|
+
try {
|
|
1057
|
+
await this.#connection.agent.request(methods.agent.session.close, { sessionId: this.#nativeSessionId }, {
|
|
1058
|
+
cancellationSignal: AbortSignal.timeout(PROCESS_STOP_TIMEOUT_MILLISECONDS),
|
|
1059
|
+
});
|
|
1060
|
+
}
|
|
1061
|
+
catch {
|
|
1062
|
+
// Process teardown below remains authoritative.
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
finally {
|
|
1067
|
+
await this.closeProcess();
|
|
1068
|
+
}
|
|
1069
|
+
};
|
|
1070
|
+
closeProcess = async (capturedProcesses = []) => {
|
|
1071
|
+
try {
|
|
1072
|
+
if (this.#runtimeChild === null) {
|
|
1073
|
+
// The in-process agent owns its app-server child and its process tree.
|
|
1074
|
+
await this.#inProcessAgent?.close();
|
|
1075
|
+
return;
|
|
1076
|
+
}
|
|
1077
|
+
await stopProcessTree(this.#runtimeChild, capturedProcesses);
|
|
1078
|
+
}
|
|
1079
|
+
finally {
|
|
1080
|
+
this.#connection.close();
|
|
1081
|
+
}
|
|
1082
|
+
};
|
|
1083
|
+
race = async (operation, exitMessage, signal) => {
|
|
1084
|
+
signal.throwIfAborted();
|
|
1085
|
+
let removeAbortListener = () => { };
|
|
1086
|
+
const aborted = new Promise((_resolve, reject) => {
|
|
1087
|
+
const rejectAbort = () => {
|
|
1088
|
+
reject(signal.reason ?? new Error("ACP request was cancelled"));
|
|
1089
|
+
};
|
|
1090
|
+
signal.addEventListener("abort", rejectAbort, { once: true });
|
|
1091
|
+
removeAbortListener = () => {
|
|
1092
|
+
signal.removeEventListener("abort", rejectAbort);
|
|
1093
|
+
};
|
|
1094
|
+
});
|
|
1095
|
+
try {
|
|
1096
|
+
try {
|
|
1097
|
+
return await Promise.race([
|
|
1098
|
+
operation,
|
|
1099
|
+
this.#termination.then((termination) => {
|
|
1100
|
+
const cause = acpEndpointTerminationError(termination);
|
|
1101
|
+
throw new AcpExecutionError(exitMessage, { cause }, cause.code);
|
|
1102
|
+
}),
|
|
1103
|
+
aborted,
|
|
1104
|
+
]);
|
|
1105
|
+
}
|
|
1106
|
+
catch (error) {
|
|
1107
|
+
signal.throwIfAborted();
|
|
1108
|
+
if (error instanceof RequestError && error.code === -32_000) {
|
|
1109
|
+
throw new AcpExecutionError("Agent authentication is required", { cause: error }, "authentication_required");
|
|
1110
|
+
}
|
|
1111
|
+
if (error instanceof RequestError) {
|
|
1112
|
+
throw new AcpExecutionError(truncate(error.message, 500), { cause: error }, "acp_agent_error");
|
|
1113
|
+
}
|
|
1114
|
+
throw error;
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
finally {
|
|
1118
|
+
removeAbortListener();
|
|
1119
|
+
}
|
|
1120
|
+
};
|
|
1121
|
+
assertNativeSession = (sessionId) => {
|
|
1122
|
+
if (sessionId !== this.#nativeSessionId) {
|
|
1123
|
+
throw new AcpExecutionError("ACP agent referenced an unknown session", {}, "invalid_agent_session");
|
|
1124
|
+
}
|
|
1125
|
+
};
|
|
1126
|
+
emitConfigUpdate = async () => {
|
|
1127
|
+
await this.#getObserver().onConfig({
|
|
1128
|
+
configOptions: this.#configOptions,
|
|
1129
|
+
kind: SESSION_CONFIG_UPDATED_KIND,
|
|
1130
|
+
requestId: `agent-update-${crypto.randomUUID()}`,
|
|
1131
|
+
sessionId: this.#mobiusSessionId,
|
|
1132
|
+
});
|
|
1133
|
+
};
|
|
1134
|
+
cancelPermission = async (interactionId) => {
|
|
1135
|
+
const pending = this.#pendingPermissions.get(interactionId);
|
|
1136
|
+
if (pending === undefined || !pending.cancel()) {
|
|
1137
|
+
return;
|
|
1138
|
+
}
|
|
1139
|
+
this.#pendingPermissions.delete(interactionId);
|
|
1140
|
+
await this.#getObserver().onPermissionResolved({
|
|
1141
|
+
interactionId,
|
|
1142
|
+
kind: SESSION_PERMISSION_RESOLVED_KIND,
|
|
1143
|
+
optionId: "",
|
|
1144
|
+
outcome: "cancelled",
|
|
1145
|
+
sessionId: this.#mobiusSessionId,
|
|
1146
|
+
});
|
|
1147
|
+
};
|
|
1148
|
+
cancelElicitation = async (interactionId) => {
|
|
1149
|
+
const pending = this.#pendingElicitations.get(interactionId);
|
|
1150
|
+
if (pending === undefined || !pending.cancel()) {
|
|
1151
|
+
return;
|
|
1152
|
+
}
|
|
1153
|
+
this.#pendingElicitations.delete(interactionId);
|
|
1154
|
+
await this.#getObserver().onElicitationResolved({
|
|
1155
|
+
action: "cancel",
|
|
1156
|
+
interactionId,
|
|
1157
|
+
kind: SESSION_ELICITATION_RESOLVED_KIND,
|
|
1158
|
+
sessionId: this.#mobiusSessionId,
|
|
1159
|
+
});
|
|
1160
|
+
};
|
|
1161
|
+
cancelPendingInteractions = async () => {
|
|
1162
|
+
const permissionIds = [...this.#pendingPermissions.keys()];
|
|
1163
|
+
const elicitationIds = [...this.#pendingElicitations.keys()];
|
|
1164
|
+
const acceptedElicitationIds = [...this.#acceptedUrlElicitations.values()];
|
|
1165
|
+
this.#acceptedUrlElicitations.clear();
|
|
1166
|
+
for (const interactionId of permissionIds) {
|
|
1167
|
+
await this.cancelPermission(interactionId);
|
|
1168
|
+
}
|
|
1169
|
+
for (const interactionId of elicitationIds) {
|
|
1170
|
+
await this.cancelElicitation(interactionId);
|
|
1171
|
+
}
|
|
1172
|
+
for (const interactionId of acceptedElicitationIds) {
|
|
1173
|
+
await this.#getObserver().onElicitationResolved({
|
|
1174
|
+
action: "cancel",
|
|
1175
|
+
interactionId,
|
|
1176
|
+
kind: SESSION_ELICITATION_RESOLVED_KIND,
|
|
1177
|
+
sessionId: this.#mobiusSessionId,
|
|
1178
|
+
});
|
|
1179
|
+
}
|
|
1180
|
+
};
|
|
1181
|
+
}
|
|
1182
|
+
//# sourceMappingURL=process-session.js.map
|