@moxt-ai/mobius 0.0.122 → 0.0.125

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/acp/process-endpoint.d.ts +18 -0
  2. package/dist/acp/process-endpoint.d.ts.map +1 -0
  3. package/dist/acp/process-endpoint.js +191 -0
  4. package/dist/acp/process-endpoint.js.map +1 -0
  5. package/dist/acp/process-pool.d.ts +17 -0
  6. package/dist/acp/process-pool.d.ts.map +1 -0
  7. package/dist/acp/process-pool.js +107 -0
  8. package/dist/acp/process-pool.js.map +1 -0
  9. package/dist/acp/process-session.d.ts +5 -109
  10. package/dist/acp/process-session.d.ts.map +1 -1
  11. package/dist/acp/process-session.js +46 -444
  12. package/dist/acp/process-session.js.map +1 -1
  13. package/dist/acp/session-contracts.d.ts +104 -0
  14. package/dist/acp/session-contracts.d.ts.map +1 -0
  15. package/dist/acp/session-contracts.js +38 -0
  16. package/dist/acp/session-contracts.js.map +1 -0
  17. package/dist/acp/session-interactions.d.ts +22 -0
  18. package/dist/acp/session-interactions.d.ts.map +1 -0
  19. package/dist/acp/session-interactions.js +207 -0
  20. package/dist/acp/session-interactions.js.map +1 -0
  21. package/dist/acp/session-manager.d.ts +4 -2
  22. package/dist/acp/session-manager.d.ts.map +1 -1
  23. package/dist/acp/session-manager.js +53 -199
  24. package/dist/acp/session-manager.js.map +1 -1
  25. package/dist/cli.js +7210 -7209
  26. package/dist/cli.js.map +4 -4
  27. package/dist/daemon-active-turn.d.ts +2 -1
  28. package/dist/daemon-active-turn.d.ts.map +1 -1
  29. package/dist/daemon-active-turn.js +11 -8
  30. package/dist/daemon-active-turn.js.map +1 -1
  31. package/dist/daemon-command-handler.js +3 -4
  32. package/dist/daemon-command-handler.js.map +1 -1
  33. package/dist/daemon-prompt-executor.d.ts +1 -2
  34. package/dist/daemon-prompt-executor.d.ts.map +1 -1
  35. package/dist/daemon-prompt-executor.js +1 -4
  36. package/dist/daemon-prompt-executor.js.map +1 -1
  37. package/dist/daemon-turn-registry.d.ts +1 -1
  38. package/dist/daemon-turn-registry.d.ts.map +1 -1
  39. package/dist/daemon-turn-registry.js +22 -13
  40. package/dist/daemon-turn-registry.js.map +1 -1
  41. package/dist/index.js +7430 -7429
  42. package/dist/index.js.map +4 -4
  43. package/dist/runtime.js +7421 -7420
  44. package/dist/runtime.js.map +4 -4
  45. package/package.json +1 -1
@@ -1,64 +1,26 @@
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";
1
+ import { methods, PROTOCOL_VERSION, } from "@agentclientprotocol/sdk";
2
+ import { AGENT_CONTENT_KIND, decodeAgentPromptResponse, SESSION_COMMANDS_UPDATED_KIND, SESSION_CONFIG_UPDATED_KIND, SESSION_INFO_UPDATED_KIND, SESSION_USAGE_UPDATED_KIND, } from "@moxt-ai/mobius-protocol";
4
3
  import { readInlineRaster, readLocalRaster } from "../authorization/local-raster.js";
5
4
  import { readInlineVideo } from "../authorization/local-video.js";
6
5
  import { unmeasuredOperationMetrics } from "../infra/operation-metrics.js";
7
6
  import { embedLocalHistoryImages } from "../native-sessions/history-images.js";
8
- import { captureProcessTree, revalidateExecutable, stopProcessTree, } from "../process/executable.js";
7
+ import { revalidateExecutable } from "../process/executable.js";
9
8
  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";
9
+ import { imageDisplayContent, isProgressMessage, normalizeContentBlock } from "./activity.js";
14
10
  import { nativeSessionIdSchema, nativeSessionPageSchema, } from "./native-session.js";
11
+ import { AcpEndpoint } from "./process-endpoint.js";
15
12
  import { normalizeAcpCapabilities, unsupportedSessionCapabilities } from "./session-capabilities.js";
16
13
  import { SessionConfigProtocolError } from "./session-config/session-config-protocol.js";
17
14
  import { sessionConfigProtocolForAgent } from "./session-config/session-config-registry.js";
15
+ import { AcpPreparedSession, } from "./session-contracts.js";
18
16
  import { AcpHistoryReplay } from "./session-history.js";
19
- import { IdleAcpTurn, PendingElicitation, PendingPermission, RunningAcpTurn, } from "./session-state.js";
17
+ import { AcpSessionInteractions } from "./session-interactions.js";
18
+ import { IdleAcpTurn, RunningAcpTurn } from "./session-state.js";
20
19
  import { AcpStoredSession, DeletedAcpStoredSession, FoundAcpStoredSession, } from "./session-store.js";
21
- import { isRecord, readString, truncate } from "./value-utils.js";
20
+ import { isRecord, truncate } from "./value-utils.js";
22
21
  const PROCESS_STOP_TIMEOUT_MILLISECONDS = 1_000;
23
22
  const MAX_PRE_SESSION_UPDATES = 100;
24
23
  const MAX_PRE_SESSION_UPDATE_BYTES = 1024 * 1024;
25
- export class NullAcpSessionObserver {
26
- onCommands = () => Promise.resolve();
27
- onConfig = () => Promise.resolve();
28
- onContent = () => Promise.resolve();
29
- onElicitation = () => Promise.resolve();
30
- onElicitationResolved = () => Promise.resolve();
31
- onInfo = () => Promise.resolve();
32
- onPermission = () => Promise.resolve();
33
- onPermissionResolved = () => Promise.resolve();
34
- onUsage = () => Promise.resolve();
35
- }
36
- export class AcpPreparedSession {
37
- agentName;
38
- agentVersion;
39
- capabilities;
40
- commands;
41
- configOptions;
42
- restored;
43
- constructor(agentName, agentVersion, capabilities, commands, configOptions, restored) {
44
- this.agentName = agentName;
45
- this.agentVersion = agentVersion;
46
- this.capabilities = capabilities;
47
- this.commands = commands;
48
- this.configOptions = configOptions;
49
- this.restored = restored;
50
- }
51
- }
52
- export class AcpAgentSettingsSnapshot {
53
- agentName;
54
- agentVersion;
55
- configOptions;
56
- constructor(agentName, agentVersion, configOptions) {
57
- this.agentName = agentName;
58
- this.agentVersion = agentVersion;
59
- this.configOptions = configOptions;
60
- }
61
- }
62
24
  export { AcpConfigurationValueUnavailableError, AcpExecutionError } from "./acp-error.js";
63
25
  class RetryableAcpInitializationError extends AcpExecutionError {
64
26
  constructor(cause) {
@@ -66,81 +28,6 @@ class RetryableAcpInitializationError extends AcpExecutionError {
66
28
  this.name = "RetryableAcpInitializationError";
67
29
  }
68
30
  }
69
- function readableWebStream(input) {
70
- let streamOpen = true;
71
- return new ReadableStream({
72
- start(controller) {
73
- input.on("data", (chunk) => {
74
- if (!streamOpen) {
75
- return;
76
- }
77
- if (chunk instanceof Uint8Array) {
78
- controller.enqueue(new Uint8Array(chunk));
79
- return;
80
- }
81
- streamOpen = false;
82
- controller.error(new Error("ACP process produced a non-binary chunk"));
83
- });
84
- input.once("end", () => {
85
- if (!streamOpen) {
86
- return;
87
- }
88
- streamOpen = false;
89
- controller.close();
90
- });
91
- input.once("error", (error) => {
92
- if (!streamOpen) {
93
- return;
94
- }
95
- streamOpen = false;
96
- controller.error(error);
97
- });
98
- },
99
- cancel() {
100
- streamOpen = false;
101
- },
102
- });
103
- }
104
- export function createWritableAcpStream(output) {
105
- let outputFailure;
106
- const pendingWriteFailures = new Set();
107
- const fail = (error) => {
108
- outputFailure = error;
109
- for (const reject of pendingWriteFailures) {
110
- reject(error);
111
- }
112
- pendingWriteFailures.clear();
113
- };
114
- output.on("error", fail);
115
- output.once("close", () => {
116
- if (outputFailure === undefined) {
117
- fail(new Error("ACP process input closed"));
118
- }
119
- });
120
- return new WritableStream({
121
- write(chunk) {
122
- if (outputFailure !== undefined) {
123
- return Promise.reject(outputFailure);
124
- }
125
- return new Promise((resolve, reject) => {
126
- pendingWriteFailures.add(reject);
127
- output.write(chunk, (error) => {
128
- pendingWriteFailures.delete(reject);
129
- if (error) {
130
- outputFailure = error;
131
- reject(error);
132
- return;
133
- }
134
- if (outputFailure !== undefined) {
135
- reject(outputFailure);
136
- return;
137
- }
138
- resolve();
139
- });
140
- });
141
- },
142
- });
143
- }
144
31
  export function arraysEqual(left, right) {
145
32
  return left.length === right.length && left.every((value, index) => value === right[index]);
146
33
  }
@@ -150,21 +37,15 @@ export function recordsEqual(left, right) {
150
37
  return leftEntries.length === rightEntries.length && leftEntries.every(([name, value]) => right[name] === value);
151
38
  }
152
39
  export class AcpProcessSession {
40
+ #endpoint;
41
+ #interactions;
153
42
  #additionalDirectories;
154
- #acceptedUrlElicitations = new Map();
155
43
  #agentId;
156
- #connection;
157
44
  #cwd;
158
45
  #environment;
159
46
  #getObserver;
160
- #inProcessAgent;
161
47
  #mobiusSessionId;
162
- #pendingElicitations = new Map();
163
- #pendingPermissions = new Map();
164
48
  #preSessionUpdates = [];
165
- // Both topologies report a terminal outcome, even after a prompt's initial RPC is acknowledged.
166
- #termination;
167
- #runtimeChild;
168
49
  #metrics;
169
50
  #sessionConfigProtocol;
170
51
  #store;
@@ -199,53 +80,13 @@ export class AcpProcessSession {
199
80
  this.#sessionConfigProtocol = sessionConfigProtocolForAgent(agent.id);
200
81
  this.#store = store;
201
82
  this.#verifiedAgentVersion = agent.agentVersion;
202
- if (agent.kind === "in-process-acp") {
203
- // Mobius hosts the ACP Agent in-process and drives the vendor's own protocol, so there is
204
- // no adapter process to spawn or supervise here. The endpoint owns its own resources.
205
- const inProcess = agent.createEndpoint({
206
- command: agent.command,
207
- cwd,
208
- environment: agent.environment,
209
- });
210
- this.#inProcessAgent = inProcess;
211
- this.#runtimeChild = null;
212
- this.#termination = inProcess.terminated;
213
- this.#connection = createAcpClient(this).connect(inProcess.app());
214
- return;
215
- }
216
- this.#inProcessAgent = null;
217
- const child = spawn(agent.adapterPath, [...agent.arguments], {
218
- cwd,
219
- detached: process.platform !== "win32",
220
- env: { ...process.env, ...agent.environment },
221
- shell: false,
222
- stdio: ["pipe", "pipe", "pipe"],
223
- });
224
- this.#runtimeChild = child;
225
- const stdin = child.stdin;
226
- const stdout = child.stdout;
227
- const stderr = child.stderr;
228
- if (stdin === null || stdout === null || stderr === null) {
229
- child.kill("SIGKILL");
230
- throw new AcpExecutionError("ACP process streams are unavailable");
231
- }
232
- stderr.setEncoding("utf8");
233
- stderr.on("data", (chunk) => {
234
- process.stderr.write(`[${agent.id}-acp] ${chunk}`);
83
+ this.#interactions = new AcpSessionInteractions({
84
+ sessionId: () => this.#mobiusSessionId,
85
+ commandId: () => this.#turn.commandId,
86
+ assertNativeSession: (sessionId) => this.assertNativeSession(sessionId),
87
+ observer: getObserver,
235
88
  });
236
- this.#termination = new Promise((resolve) => {
237
- child.once("error", (cause) => {
238
- resolve({ kind: "failed", error: new AcpExecutionError("The ACP process could not run", { cause }) });
239
- });
240
- child.once("exit", (code, signal) => {
241
- resolve({
242
- kind: "failed",
243
- error: new AcpExecutionError("The ACP process stopped", { cause: { code, signal } }),
244
- });
245
- });
246
- });
247
- const stream = ndJsonStream(createWritableAcpStream(stdin), readableWebStream(stdout));
248
- this.#connection = createAcpClient(this).connect(stream);
89
+ this.#endpoint = new AcpEndpoint(agent, cwd, this);
249
90
  }
250
91
  static async #start(options, getObserver, store, initialize, metrics) {
251
92
  for (let attempt = 1; attempt <= 2; attempt += 1) {
@@ -305,7 +146,7 @@ export class AcpProcessSession {
305
146
  const history = new AcpHistoryReplay();
306
147
  this.#replay = { kind: "capture", history };
307
148
  try {
308
- await this.race(this.#connection.agent.request(methods.agent.session.load, {
149
+ await this.race(this.#endpoint.connection.agent.request(methods.agent.session.load, {
309
150
  additionalDirectories: [...this.#additionalDirectories],
310
151
  cwd: this.#cwd,
311
152
  mcpServers: [],
@@ -327,13 +168,10 @@ export class AcpProcessSession {
327
168
  bufferAgentText = async (text, messageId) => {
328
169
  const previous = this.#bufferedAgentText.at(-1);
329
170
  if (previous?.messageId === messageId) {
330
- this.#bufferedAgentText = [
331
- ...this.#bufferedAgentText.slice(0, -1),
332
- { chunks: [...previous.chunks, text], messageId },
333
- ];
171
+ previous.chunks.push(text);
334
172
  return;
335
173
  }
336
- this.#bufferedAgentText = [...this.#bufferedAgentText, { chunks: [text], messageId }];
174
+ this.#bufferedAgentText.push({ chunks: [text], messageId });
337
175
  };
338
176
  flushAgentText = async () => {
339
177
  const buffered = this.#bufferedAgentText;
@@ -411,15 +249,15 @@ export class AcpProcessSession {
411
249
  await this.#metrics.measure("agent-initialize", async () => await this.#initializeAgentOperation(signal));
412
250
  }
413
251
  async #initializeAgentOperation(signal) {
414
- if (this.#inProcessAgent !== null) {
252
+ if (this.#endpoint.inProcessAgent !== null) {
415
253
  // The ACP agent runs in this process, but it still owns an app-server child that must
416
254
  // start and complete its own handshake before the ACP conversation can begin.
417
- await this.race(this.#inProcessAgent.initialize(signal), "The Codex app-server exited during initialization", signal).catch((cause) => {
255
+ await this.race(this.#endpoint.inProcessAgent.initialize(signal), "The Codex app-server exited during initialization", signal).catch((cause) => {
418
256
  signal.throwIfAborted();
419
257
  throw new RetryableAcpInitializationError(cause);
420
258
  });
421
259
  }
422
- const initialized = await this.race(this.#connection.agent.request(methods.agent.initialize, {
260
+ const initialized = await this.race(this.#endpoint.connection.agent.request(methods.agent.initialize, {
423
261
  clientCapabilities: {
424
262
  elicitation: { form: {}, url: {} },
425
263
  plan: {},
@@ -458,7 +296,7 @@ export class AcpProcessSession {
458
296
  if (this.#additionalDirectories.length > 0 && !this.#capabilities.additionalDirectories) {
459
297
  throw new AcpExecutionError("This Agent cannot restore additional working directories", {}, "native_session_unsupported");
460
298
  }
461
- const forked = await this.#metrics.measure("session-fork", async () => await this.race(this.#connection.agent.request(methods.agent.session.fork, {
299
+ const forked = await this.#metrics.measure("session-fork", async () => await this.race(this.#endpoint.connection.agent.request(methods.agent.session.fork, {
462
300
  sessionId: nativeSessionIdSchema.parse(origin.nativeSessionId),
463
301
  cwd: this.#cwd,
464
302
  additionalDirectories: [...this.#additionalDirectories],
@@ -482,7 +320,7 @@ export class AcpProcessSession {
482
320
  this.#sessionTitle = stored.session.title;
483
321
  this.#restored = true;
484
322
  if (this.#capabilities.resumeSession) {
485
- lifecycleResponse = await this.#metrics.measure("session-resume", async () => await this.race(this.#connection.agent.request(methods.agent.session.resume, {
323
+ lifecycleResponse = await this.#metrics.measure("session-resume", async () => await this.race(this.#endpoint.connection.agent.request(methods.agent.session.resume, {
486
324
  additionalDirectories: [...this.#additionalDirectories],
487
325
  cwd: this.#cwd,
488
326
  mcpServers: [],
@@ -492,7 +330,7 @@ export class AcpProcessSession {
492
330
  else if (this.#capabilities.loadSession) {
493
331
  this.#replay = { kind: "discard" };
494
332
  try {
495
- lifecycleResponse = await this.#metrics.measure("session-load", async () => await this.race(this.#connection.agent.request(methods.agent.session.load, {
333
+ lifecycleResponse = await this.#metrics.measure("session-load", async () => await this.race(this.#endpoint.connection.agent.request(methods.agent.session.load, {
496
334
  additionalDirectories: [...this.#additionalDirectories],
497
335
  cwd: this.#cwd,
498
336
  mcpServers: [],
@@ -515,7 +353,7 @@ export class AcpProcessSession {
515
353
  }
516
354
  this.#store.remove(this.#mobiusSessionId);
517
355
  }
518
- const created = await this.#metrics.measure("session-new", async () => await this.race(this.#connection.agent.request(methods.agent.session.new, {
356
+ const created = await this.#metrics.measure("session-new", async () => await this.race(this.#endpoint.connection.agent.request(methods.agent.session.new, {
519
357
  additionalDirectories: [...this.#additionalDirectories],
520
358
  cwd: this.#cwd,
521
359
  mcpServers: [],
@@ -532,7 +370,7 @@ export class AcpProcessSession {
532
370
  if (!this.#capabilities.listSessions) {
533
371
  throw new AcpExecutionError("This Agent does not support native session listing", {}, "native_session_unsupported");
534
372
  }
535
- const response = await this.race(this.#connection.agent.request(methods.agent.session.list, cursor === null ? {} : { cursor }, {
373
+ const response = await this.race(this.#endpoint.connection.agent.request(methods.agent.session.list, cursor === null ? {} : { cursor }, {
536
374
  cancellationSignal: signal,
537
375
  }), "ACP agent exited while listing sessions", signal);
538
376
  const decoded = nativeSessionPageSchema.safeParse(response);
@@ -545,7 +383,7 @@ export class AcpProcessSession {
545
383
  if (!this.#capabilities.deleteSession || !this.#capabilities.listSessions) {
546
384
  throw new AcpExecutionError("This Agent does not support native session deletion", {}, "native_session_unsupported");
547
385
  }
548
- 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);
386
+ await this.race(this.#endpoint.connection.agent.request(methods.agent.session.delete, { sessionId: nativeSessionIdSchema.parse(nativeSessionId) }, { cancellationSignal: signal }), "ACP agent exited while deleting a session", signal);
549
387
  };
550
388
  nativeSessionId = () => this.#nativeSessionId;
551
389
  adoptNativeSessionId = (sessionId) => {
@@ -573,7 +411,7 @@ export class AcpProcessSession {
573
411
  const configRevision = this.#configRevision;
574
412
  try {
575
413
  const configured = await this.#sessionConfigProtocol.configure(this.#configOptions, options, this.#nativeSessionId, {
576
- request: async (method, params, failureMessage, signal) => await this.race(this.#connection.agent.request(method, params, {
414
+ request: async (method, params, failureMessage, signal) => await this.race(this.#endpoint.connection.agent.request(method, params, {
577
415
  cancellationSignal: signal,
578
416
  }), failureMessage, signal),
579
417
  });
@@ -644,7 +482,7 @@ export class AcpProcessSession {
644
482
  };
645
483
  nativeHistoryTurn = () => {
646
484
  const prompt = this.#nativePrompt;
647
- const nativeTurnId = this.#inProcessAgent?.nativeTurnId?.() ?? null;
485
+ const nativeTurnId = this.#endpoint.inProcessAgent?.nativeTurnId?.() ?? null;
648
486
  return prompt === null || nativeTurnId === null || nativeTurnId === prompt.previousTurnId
649
487
  ? null
650
488
  : { commandId: prompt.commandId, nativeTurnId };
@@ -663,10 +501,10 @@ export class AcpProcessSession {
663
501
  this.#turn = running;
664
502
  this.#nativePrompt = {
665
503
  commandId: options.commandId,
666
- previousTurnId: this.#inProcessAgent?.nativeTurnId?.() ?? null,
504
+ previousTurnId: this.#endpoint.inProcessAgent?.nativeTurnId?.() ?? null,
667
505
  };
668
506
  try {
669
- 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);
507
+ const response = await this.race(this.#endpoint.connection.agent.request(methods.agent.session.prompt, { prompt, sessionId: this.#nativeSessionId }, { cancellationSignal: options.signal }), "ACP agent exited during a prompt", options.signal);
670
508
  await this.#updateTail;
671
509
  await this.flushAgentText();
672
510
  await running.activities.finish();
@@ -711,7 +549,7 @@ export class AcpProcessSession {
711
549
  throw new AcpExecutionError("The target turn is no longer active", {}, "steering_target_unavailable");
712
550
  }
713
551
  const prompt = this.buildPrompt(options);
714
- const response = await this.race(this.#connection.agent.request("_session/steering", {
552
+ const response = await this.race(this.#endpoint.connection.agent.request("_session/steering", {
715
553
  _meta: { steering: { idleBehavior: "promptRequired" } },
716
554
  prompt,
717
555
  sessionId: this.#nativeSessionId,
@@ -732,11 +570,11 @@ export class AcpProcessSession {
732
570
  throw new AcpExecutionError("ACP agent returned an invalid steering response", {}, "acp_invalid_steering_response");
733
571
  };
734
572
  cancel = async () => {
735
- const capturedProcesses = this.#runtimeChild === null ? [] : await captureProcessTree(this.#runtimeChild);
573
+ const capturedProcesses = await this.#endpoint.captureProcessTree();
736
574
  try {
737
- await this.cancelPendingInteractions();
575
+ await this.#interactions.cancelPendingInteractions();
738
576
  if (this.#turn.running) {
739
- await this.#connection.agent.notify(methods.agent.session.cancel, {
577
+ await this.#endpoint.connection.agent.notify(methods.agent.session.cancel, {
740
578
  sessionId: this.#nativeSessionId,
741
579
  });
742
580
  }
@@ -745,151 +583,11 @@ export class AcpProcessSession {
745
583
  await this.closeProcess(capturedProcesses);
746
584
  }
747
585
  };
748
- respondPermission = async (options) => {
749
- const pending = this.#pendingPermissions.get(options.interactionId);
750
- if (pending === undefined) {
751
- throw new AcpExecutionError("The permission request is no longer active", {}, "permission_request_not_found");
752
- }
753
- if (options.outcome === "selected" && !pending.optionIds.has(options.optionId)) {
754
- throw new AcpExecutionError("The selected permission option is unavailable", {}, "invalid_permission_response");
755
- }
756
- const resolved = options.outcome === "selected" ? pending.select(options.optionId) : pending.cancel();
757
- if (!resolved) {
758
- throw new AcpExecutionError("The permission request was already resolved", {}, "permission_request_not_found");
759
- }
760
- this.#pendingPermissions.delete(options.interactionId);
761
- await this.#getObserver().onPermissionResolved({
762
- interactionId: options.interactionId,
763
- kind: SESSION_PERMISSION_RESOLVED_KIND,
764
- optionId: options.outcome === "selected" ? options.optionId : "",
765
- outcome: options.outcome,
766
- sessionId: this.#mobiusSessionId,
767
- });
768
- };
769
- respondElicitation = async (options) => {
770
- const pending = this.#pendingElicitations.get(options.interactionId);
771
- if (pending === undefined) {
772
- throw new AcpExecutionError("The elicitation request is no longer active", {}, "elicitation_request_not_found");
773
- }
774
- let resolved = false;
775
- if (options.action === "accept") {
776
- if (pending.elicitationId.length > 0) {
777
- resolved = pending.accept({});
778
- if (resolved) {
779
- this.#acceptedUrlElicitations.set(pending.elicitationId, pending.interactionId);
780
- }
781
- }
782
- else {
783
- resolved = pending.accept(validateElicitationContent(options.content, pending.requestedSchema));
784
- }
785
- }
786
- else if (options.action === "decline") {
787
- resolved = pending.decline();
788
- }
789
- else {
790
- resolved = pending.cancel();
791
- }
792
- if (!resolved) {
793
- throw new AcpExecutionError("The elicitation request was already resolved", {}, "elicitation_request_not_found");
794
- }
795
- this.#pendingElicitations.delete(options.interactionId);
796
- await this.#getObserver().onElicitationResolved({
797
- action: options.action,
798
- interactionId: options.interactionId,
799
- kind: SESSION_ELICITATION_RESOLVED_KIND,
800
- sessionId: this.#mobiusSessionId,
801
- });
802
- };
803
- onPermission = async (request, signal) => {
804
- this.assertNativeSession(request.sessionId);
805
- const interactionId = `permission-${crypto.randomUUID()}`;
806
- const options = request.options.slice(0, 20).map((option) => ({
807
- kind: option.kind,
808
- name: truncate(option.name, 255),
809
- optionId: truncate(option.optionId, 255),
810
- }));
811
- if (options.length === 0) {
812
- throw new AcpExecutionError("ACP permission request did not provide any choices", {}, "invalid_agent_permission_request");
813
- }
814
- const pending = new PendingPermission(interactionId, new Set(options.map((option) => option.optionId)));
815
- this.#pendingPermissions.set(interactionId, pending);
816
- const abort = () => {
817
- void this.cancelPermission(interactionId);
818
- };
819
- signal.addEventListener("abort", abort, { once: true });
820
- try {
821
- await this.#getObserver().onPermission({
822
- commandId: this.#turn.commandId,
823
- interactionId,
824
- kind: SESSION_PERMISSION_REQUESTED_KIND,
825
- options,
826
- sessionId: this.#mobiusSessionId,
827
- title: truncate(request.toolCall.title ?? "Permission required", 500),
828
- toolCallId: truncate(request.toolCall.toolCallId, 255),
829
- toolKind: truncate(request.toolCall.kind ?? "other", 64),
830
- });
831
- return await pending.completion.promise;
832
- }
833
- finally {
834
- signal.removeEventListener("abort", abort);
835
- this.#pendingPermissions.delete(interactionId);
836
- }
837
- };
838
- onElicitation = async (request, signal) => {
839
- const sessionId = Reflect.get(request, "sessionId");
840
- if (typeof sessionId !== "string") {
841
- throw new AcpExecutionError("Mobius only accepts session-scoped ACP elicitations", {}, "unsupported_elicitation_scope");
842
- }
843
- this.assertNativeSession(sessionId);
844
- if (request.mode !== "form" && request.mode !== "url") {
845
- throw new AcpExecutionError("The ACP agent requested an unsupported elicitation mode", {}, "unsupported_elicitation_mode");
846
- }
847
- const interactionId = `elicitation-${crypto.randomUUID()}`;
848
- const schemaValue = Reflect.get(request, "requestedSchema");
849
- const requestedSchema = request.mode === "form" ? schemaValue : {};
850
- const elicitationIdValue = Reflect.get(request, "elicitationId");
851
- const elicitationId = request.mode === "url" && typeof elicitationIdValue === "string" ? truncate(elicitationIdValue, 255) : "";
852
- const pending = new PendingElicitation(interactionId, elicitationId, requestedSchema);
853
- this.#pendingElicitations.set(interactionId, pending);
854
- const abort = () => {
855
- void this.cancelElicitation(interactionId);
856
- };
857
- signal.addEventListener("abort", abort, { once: true });
858
- try {
859
- await this.#getObserver().onElicitation({
860
- accepted: false,
861
- commandId: this.#turn.commandId,
862
- elicitationId,
863
- fields: normalizeElicitationFields(requestedSchema),
864
- interactionId,
865
- kind: SESSION_ELICITATION_REQUESTED_KIND,
866
- message: truncate(request.message, 2_000),
867
- mode: request.mode,
868
- sessionId: this.#mobiusSessionId,
869
- url: request.mode === "url" && typeof Reflect.get(request, "url") === "string"
870
- ? truncate(readString(Reflect.get(request, "url")), 4_096)
871
- : "",
872
- });
873
- return await pending.completion.promise;
874
- }
875
- finally {
876
- signal.removeEventListener("abort", abort);
877
- this.#pendingElicitations.delete(interactionId);
878
- }
879
- };
880
- onElicitationComplete = async (notification) => {
881
- const interactionId = this.#acceptedUrlElicitations.get(notification.elicitationId);
882
- if (interactionId === undefined) {
883
- return;
884
- }
885
- this.#acceptedUrlElicitations.delete(notification.elicitationId);
886
- await this.#getObserver().onElicitationResolved({
887
- action: "complete",
888
- interactionId,
889
- kind: SESSION_ELICITATION_RESOLVED_KIND,
890
- sessionId: this.#mobiusSessionId,
891
- });
892
- };
586
+ respondPermission = (options) => this.#interactions.respondPermission(options);
587
+ respondElicitation = (options) => this.#interactions.respondElicitation(options);
588
+ onPermission = (request, signal) => this.#interactions.onPermission(request, signal);
589
+ onElicitation = (request, signal) => this.#interactions.onElicitation(request, signal);
590
+ onElicitationComplete = (notification) => this.#interactions.onElicitationComplete(notification);
893
591
  onUpdate = (notification) => {
894
592
  if (this.#nativeSessionId.length === 0) {
895
593
  const notificationBytes = Buffer.byteLength(JSON.stringify(notification));
@@ -1042,10 +740,10 @@ export class AcpProcessSession {
1042
740
  };
1043
741
  close = async () => {
1044
742
  try {
1045
- await this.cancelPendingInteractions();
743
+ await this.#interactions.cancelPendingInteractions();
1046
744
  if (this.#capabilities.closeSession && this.#nativeSessionId.length > 0) {
1047
745
  try {
1048
- await this.#connection.agent.request(methods.agent.session.close, { sessionId: this.#nativeSessionId }, {
746
+ await this.#endpoint.connection.agent.request(methods.agent.session.close, { sessionId: this.#nativeSessionId }, {
1049
747
  cancellationSignal: AbortSignal.timeout(PROCESS_STOP_TIMEOUT_MILLISECONDS),
1050
748
  });
1051
749
  }
@@ -1058,57 +756,8 @@ export class AcpProcessSession {
1058
756
  await this.closeProcess();
1059
757
  }
1060
758
  };
1061
- closeProcess = async (capturedProcesses = []) => {
1062
- try {
1063
- if (this.#runtimeChild === null) {
1064
- // The in-process agent owns its app-server child and its process tree.
1065
- await this.#inProcessAgent?.close();
1066
- return;
1067
- }
1068
- await stopProcessTree(this.#runtimeChild, capturedProcesses);
1069
- }
1070
- finally {
1071
- this.#connection.close();
1072
- }
1073
- };
1074
- race = async (operation, exitMessage, signal) => {
1075
- signal.throwIfAborted();
1076
- let removeAbortListener = () => { };
1077
- const aborted = new Promise((_resolve, reject) => {
1078
- const rejectAbort = () => {
1079
- reject(signal.reason ?? new Error("ACP request was cancelled"));
1080
- };
1081
- signal.addEventListener("abort", rejectAbort, { once: true });
1082
- removeAbortListener = () => {
1083
- signal.removeEventListener("abort", rejectAbort);
1084
- };
1085
- });
1086
- try {
1087
- try {
1088
- return await Promise.race([
1089
- operation,
1090
- this.#termination.then((termination) => {
1091
- const cause = acpEndpointTerminationError(termination);
1092
- throw new AcpExecutionError(exitMessage, { cause }, cause.code);
1093
- }),
1094
- aborted,
1095
- ]);
1096
- }
1097
- catch (error) {
1098
- signal.throwIfAborted();
1099
- if (error instanceof RequestError && error.code === -32_000) {
1100
- throw new AcpExecutionError("Agent authentication is required", { cause: error }, "authentication_required");
1101
- }
1102
- if (error instanceof RequestError) {
1103
- throw new AcpExecutionError(truncate(error.message, 500), { cause: error }, "acp_agent_error");
1104
- }
1105
- throw error;
1106
- }
1107
- }
1108
- finally {
1109
- removeAbortListener();
1110
- }
1111
- };
759
+ closeProcess = (capturedProcesses = []) => this.#endpoint.closeProcess(capturedProcesses);
760
+ race = (operation, exitMessage, signal) => this.#endpoint.race(operation, exitMessage, signal);
1112
761
  assertNativeSession = (sessionId) => {
1113
762
  if (sessionId !== this.#nativeSessionId) {
1114
763
  throw new AcpExecutionError("ACP agent referenced an unknown session", {}, "invalid_agent_session");
@@ -1122,52 +771,5 @@ export class AcpProcessSession {
1122
771
  sessionId: this.#mobiusSessionId,
1123
772
  });
1124
773
  };
1125
- cancelPermission = async (interactionId) => {
1126
- const pending = this.#pendingPermissions.get(interactionId);
1127
- if (pending === undefined || !pending.cancel()) {
1128
- return;
1129
- }
1130
- this.#pendingPermissions.delete(interactionId);
1131
- await this.#getObserver().onPermissionResolved({
1132
- interactionId,
1133
- kind: SESSION_PERMISSION_RESOLVED_KIND,
1134
- optionId: "",
1135
- outcome: "cancelled",
1136
- sessionId: this.#mobiusSessionId,
1137
- });
1138
- };
1139
- cancelElicitation = async (interactionId) => {
1140
- const pending = this.#pendingElicitations.get(interactionId);
1141
- if (pending === undefined || !pending.cancel()) {
1142
- return;
1143
- }
1144
- this.#pendingElicitations.delete(interactionId);
1145
- await this.#getObserver().onElicitationResolved({
1146
- action: "cancel",
1147
- interactionId,
1148
- kind: SESSION_ELICITATION_RESOLVED_KIND,
1149
- sessionId: this.#mobiusSessionId,
1150
- });
1151
- };
1152
- cancelPendingInteractions = async () => {
1153
- const permissionIds = [...this.#pendingPermissions.keys()];
1154
- const elicitationIds = [...this.#pendingElicitations.keys()];
1155
- const acceptedElicitationIds = [...this.#acceptedUrlElicitations.values()];
1156
- this.#acceptedUrlElicitations.clear();
1157
- for (const interactionId of permissionIds) {
1158
- await this.cancelPermission(interactionId);
1159
- }
1160
- for (const interactionId of elicitationIds) {
1161
- await this.cancelElicitation(interactionId);
1162
- }
1163
- for (const interactionId of acceptedElicitationIds) {
1164
- await this.#getObserver().onElicitationResolved({
1165
- action: "cancel",
1166
- interactionId,
1167
- kind: SESSION_ELICITATION_RESOLVED_KIND,
1168
- sessionId: this.#mobiusSessionId,
1169
- });
1170
- }
1171
- };
1172
774
  }
1173
775
  //# sourceMappingURL=process-session.js.map