@moxt-ai/mobius 0.0.126 → 0.0.128

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 (110) hide show
  1. package/dist/acp/{session-executions.d.ts → active-executions.d.ts} +2 -2
  2. package/dist/acp/active-executions.d.ts.map +1 -0
  3. package/dist/acp/{session-executions.js → active-executions.js} +2 -2
  4. package/dist/acp/active-executions.js.map +1 -0
  5. package/dist/acp/{process-endpoint.d.ts → agent-connection.d.ts} +2 -2
  6. package/dist/acp/{process-endpoint.d.ts.map → agent-connection.d.ts.map} +1 -1
  7. package/dist/acp/{process-endpoint.js → agent-connection.js} +2 -2
  8. package/dist/acp/{process-endpoint.js.map → agent-connection.js.map} +1 -1
  9. package/dist/acp/agent-process-pool.d.ts +17 -0
  10. package/dist/acp/agent-process-pool.d.ts.map +1 -0
  11. package/dist/acp/{process-pool.js → agent-process-pool.js} +2 -2
  12. package/dist/acp/agent-process-pool.js.map +1 -0
  13. package/dist/acp/agent-query-processes.d.ts +15 -0
  14. package/dist/acp/agent-query-processes.d.ts.map +1 -0
  15. package/dist/acp/agent-query-processes.js +97 -0
  16. package/dist/acp/agent-query-processes.js.map +1 -0
  17. package/dist/acp/{session-manager.d.ts → agent-runtime-manager.d.ts} +5 -5
  18. package/dist/acp/agent-runtime-manager.d.ts.map +1 -0
  19. package/dist/acp/{session-manager.js → agent-runtime-manager.js} +72 -149
  20. package/dist/acp/agent-runtime-manager.js.map +1 -0
  21. package/dist/acp/{process-session.d.ts → agent-session.d.ts} +4 -6
  22. package/dist/acp/agent-session.d.ts.map +1 -0
  23. package/dist/acp/{process-session.js → agent-session.js} +57 -86
  24. package/dist/acp/agent-session.js.map +1 -0
  25. package/dist/acp/agent-update-stream.d.ts +11 -0
  26. package/dist/acp/agent-update-stream.d.ts.map +1 -0
  27. package/dist/acp/agent-update-stream.js +56 -0
  28. package/dist/acp/agent-update-stream.js.map +1 -0
  29. package/dist/acp/codex/agent.d.ts.map +1 -1
  30. package/dist/acp/codex/agent.js +46 -0
  31. package/dist/acp/codex/agent.js.map +1 -1
  32. package/dist/acp/retained-agent-processes.d.ts +21 -0
  33. package/dist/acp/retained-agent-processes.d.ts.map +1 -0
  34. package/dist/acp/{retained-sessions.js → retained-agent-processes.js} +3 -3
  35. package/dist/acp/retained-agent-processes.js.map +1 -0
  36. package/dist/acp/run-prompt.d.ts +1 -1
  37. package/dist/acp/run-prompt.d.ts.map +1 -1
  38. package/dist/acp/run-prompt.js +4 -4
  39. package/dist/acp/run-prompt.js.map +1 -1
  40. package/dist/acp/session-config/apply-session-configuration.d.ts +2 -2
  41. package/dist/acp/session-config/apply-session-configuration.d.ts.map +1 -1
  42. package/dist/acp/session-config/apply-session-configuration.js +1 -1
  43. package/dist/acp/session-config/apply-session-configuration.js.map +1 -1
  44. package/dist/agent-catalog/discover-agent-settings.d.ts +2 -2
  45. package/dist/agent-catalog/discover-agent-settings.d.ts.map +1 -1
  46. package/dist/agent-catalog/discover-agent-settings.js +1 -1
  47. package/dist/agent-catalog/discover-agent-settings.js.map +1 -1
  48. package/dist/agent-catalog/handle-agent-catalog-refresh.js +1 -1
  49. package/dist/agent-catalog/handle-agent-catalog-refresh.js.map +1 -1
  50. package/dist/agent-catalog/handle-agent-settings-discovery.d.ts +2 -2
  51. package/dist/agent-catalog/handle-agent-settings-discovery.d.ts.map +1 -1
  52. package/dist/agent-catalog/handle-agent-settings-discovery.js +1 -1
  53. package/dist/agent-catalog/handle-agent-settings-discovery.js.map +1 -1
  54. package/dist/cli.js +463 -389
  55. package/dist/cli.js.map +4 -4
  56. package/dist/daemon-command-handler.d.ts +2 -2
  57. package/dist/daemon-command-handler.d.ts.map +1 -1
  58. package/dist/daemon-command-results.js +1 -1
  59. package/dist/daemon-command-results.js.map +1 -1
  60. package/dist/daemon-history-commands.d.ts +3 -3
  61. package/dist/daemon-history-commands.d.ts.map +1 -1
  62. package/dist/daemon-history-commands.js.map +1 -1
  63. package/dist/daemon-observers.d.ts +1 -1
  64. package/dist/daemon-observers.d.ts.map +1 -1
  65. package/dist/daemon-prompt-executor.d.ts +2 -2
  66. package/dist/daemon-prompt-executor.d.ts.map +1 -1
  67. package/dist/daemon-prompt-executor.js +1 -1
  68. package/dist/daemon-prompt-executor.js.map +1 -1
  69. package/dist/daemon-session-commands.d.ts +3 -3
  70. package/dist/daemon-session-commands.d.ts.map +1 -1
  71. package/dist/daemon-session-commands.js.map +1 -1
  72. package/dist/daemon-turn-registry.d.ts +13 -13
  73. package/dist/index.js +489 -415
  74. package/dist/index.js.map +4 -4
  75. package/dist/native-sessions/acp-history.d.ts +2 -2
  76. package/dist/native-sessions/acp-history.d.ts.map +1 -1
  77. package/dist/native-sessions/acp-history.js +1 -1
  78. package/dist/native-sessions/acp-history.js.map +1 -1
  79. package/dist/native-sessions/agent-adapter.d.ts +2 -2
  80. package/dist/native-sessions/agent-adapter.d.ts.map +1 -1
  81. package/dist/native-sessions/agent-adapter.js +1 -1
  82. package/dist/native-sessions/agent-adapter.js.map +1 -1
  83. package/dist/native-sessions/handle-native-requests.js +1 -1
  84. package/dist/native-sessions/handle-native-requests.js.map +1 -1
  85. package/dist/native-sessions/live-history-page.js +1 -1
  86. package/dist/native-sessions/live-history-page.js.map +1 -1
  87. package/dist/native-sessions/service.d.ts +2 -2
  88. package/dist/native-sessions/service.d.ts.map +1 -1
  89. package/dist/native-sessions/service.js +1 -1
  90. package/dist/native-sessions/service.js.map +1 -1
  91. package/dist/relay-connection/run-relay-connection.d.ts +2 -2
  92. package/dist/relay-connection/run-relay-connection.d.ts.map +1 -1
  93. package/dist/run-daemon.d.ts.map +1 -1
  94. package/dist/run-daemon.js +5 -5
  95. package/dist/run-daemon.js.map +1 -1
  96. package/dist/runtime.js +462 -388
  97. package/dist/runtime.js.map +4 -4
  98. package/package.json +1 -1
  99. package/dist/acp/process-pool.d.ts +0 -17
  100. package/dist/acp/process-pool.d.ts.map +0 -1
  101. package/dist/acp/process-pool.js.map +0 -1
  102. package/dist/acp/process-session.d.ts.map +0 -1
  103. package/dist/acp/process-session.js.map +0 -1
  104. package/dist/acp/retained-sessions.d.ts +0 -21
  105. package/dist/acp/retained-sessions.d.ts.map +0 -1
  106. package/dist/acp/retained-sessions.js.map +0 -1
  107. package/dist/acp/session-executions.d.ts.map +0 -1
  108. package/dist/acp/session-executions.js.map +0 -1
  109. package/dist/acp/session-manager.d.ts.map +0 -1
  110. package/dist/acp/session-manager.js.map +0 -1
package/dist/runtime.js CHANGED
@@ -23478,6 +23478,7 @@ var COLLABORATION_MODE_SETTING_ID = "collaboration_mode";
23478
23478
  var MODEL_CATALOG_LIMIT = 1e3;
23479
23479
  var FAST_TIER = "fast";
23480
23480
  var SERVICE_TIER_FAST = "priority";
23481
+ var CODEX_COMMANDS = Object.freeze([{ description: "Compact the conversation context", name: "compact" }]);
23481
23482
  var WORKSPACE_WRITE_POLICY = Object.freeze({
23482
23483
  excludeSlashTmp: false,
23483
23484
  excludeTmpdirEnvVar: false,
@@ -23558,6 +23559,9 @@ function promptInput(prompt) {
23558
23559
  }
23559
23560
  return input2;
23560
23561
  }
23562
+ function isCompactPrompt(prompt) {
23563
+ return prompt.length === 1 && prompt[0]?.type === "text" && prompt[0].text.trim() === "/compact";
23564
+ }
23561
23565
  function steeringPromptInput(prompt) {
23562
23566
  const input2 = [];
23563
23567
  for (const block of prompt) {
@@ -23812,6 +23816,7 @@ var CodexAcpAgent = class {
23812
23816
  };
23813
23817
  this.#collaborationModeSelected = false;
23814
23818
  await this.#probeCollaborationMode(context.signal);
23819
+ await this.#emitAvailableCommands();
23815
23820
  return { configOptions: this.#configOptions(), sessionId: created.thread.id };
23816
23821
  }).onRequest(methods.agent.session.setConfigOption, async (context) => {
23817
23822
  this.#applySelection(context.params.configId, context.params.value);
@@ -23830,6 +23835,7 @@ var CodexAcpAgent = class {
23830
23835
  this.#selectRestoredThread(resumed);
23831
23836
  await this.#probeCollaborationMode(context.signal);
23832
23837
  await this.#replayHistory(resumed.turns);
23838
+ await this.#emitAvailableCommands();
23833
23839
  return { configOptions: this.#configOptions() };
23834
23840
  }).onRequest(methods.agent.session.fork, async (context) => {
23835
23841
  const forked = threadForkResponseSchema.parse(
@@ -23846,6 +23852,7 @@ var CodexAcpAgent = class {
23846
23852
  this.#selectRestoredThread(forked);
23847
23853
  await this.#probeCollaborationMode(context.signal);
23848
23854
  await this.#replayHistory(forked.turns);
23855
+ await this.#emitAvailableCommands();
23849
23856
  return { configOptions: this.#configOptions(), sessionId: forked.thread.id };
23850
23857
  }).onRequest(methods.agent.session.resume, async (context) => {
23851
23858
  const resumed = threadResumeResponseSchema.parse(
@@ -23857,8 +23864,12 @@ var CodexAcpAgent = class {
23857
23864
  );
23858
23865
  this.#selectRestoredThread(resumed);
23859
23866
  await this.#probeCollaborationMode(context.signal);
23867
+ await this.#emitAvailableCommands();
23860
23868
  return { configOptions: this.#configOptions() };
23861
23869
  }).onRequest(methods.agent.session.prompt, async (context) => {
23870
+ if (isCompactPrompt(context.params.prompt)) {
23871
+ return await this.#compact(context.signal);
23872
+ }
23862
23873
  return await this.#runTurn(promptInput(context.params.prompt), context.signal);
23863
23874
  }).onRequest(
23864
23875
  "_session/steering",
@@ -24138,6 +24149,12 @@ var CodexAcpAgent = class {
24138
24149
  update
24139
24150
  });
24140
24151
  };
24152
+ #emitAvailableCommands = async () => {
24153
+ await this.#emit({
24154
+ availableCommands: CODEX_COMMANDS.map((command) => ({ ...command })),
24155
+ sessionUpdate: "available_commands_update"
24156
+ });
24157
+ };
24141
24158
  /** Pushes the current settings so a mode change Codex applied reaches the Run settings panel. */
24142
24159
  #emitConfigOptionsUpdate = async () => {
24143
24160
  const connection = this.#connection;
@@ -24448,6 +24465,35 @@ var CodexAcpAgent = class {
24448
24465
  }
24449
24466
  }
24450
24467
  };
24468
+ #compact = async (signal) => {
24469
+ signal.throwIfAborted();
24470
+ if (this.#turn !== null) {
24471
+ throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
24472
+ }
24473
+ const completion = Promise.withResolvers();
24474
+ void completion.promise.catch(() => {
24475
+ });
24476
+ const aborted2 = () => {
24477
+ completion.reject(signal.reason);
24478
+ void this.close().catch((cause) => {
24479
+ console.error("The cancelled Codex endpoint could not release its process tree", cause);
24480
+ });
24481
+ };
24482
+ signal.addEventListener("abort", aborted2, { once: true });
24483
+ const turn = { completion, turn: { id: "" } };
24484
+ this.#streamedReasoningItemIds.clear();
24485
+ this.#turn = turn;
24486
+ try {
24487
+ await this.#appServer.request("thread/compact/start", { threadId: this.#nativeSessionId }, signal);
24488
+ return await completion.promise;
24489
+ } finally {
24490
+ signal.removeEventListener("abort", aborted2);
24491
+ if (this.#turn === turn) {
24492
+ this.#turn = null;
24493
+ this.#streamedReasoningItemIds.clear();
24494
+ }
24495
+ }
24496
+ };
24451
24497
  #steerTurn = async (params, signal) => {
24452
24498
  if (typeof params !== "object" || params === null) {
24453
24499
  throw new AcpExecutionError("Codex received an invalid steering request", {}, "invalid_request");
@@ -26413,7 +26459,88 @@ import { createHash as createHash5, randomUUID as randomUUID6 } from "node:crypt
26413
26459
  import { join as join17 } from "node:path";
26414
26460
  import { styleText } from "node:util";
26415
26461
 
26416
- // src/acp/process-session.ts
26462
+ // src/acp/active-executions.ts
26463
+ var unreachable = (state) => {
26464
+ throw new AcpExecutionError("Unexpected execution state", { cause: state });
26465
+ };
26466
+ var ActiveExecutions = class {
26467
+ #entries = /* @__PURE__ */ new Map();
26468
+ command = (id) => {
26469
+ const state = this.#entries.get(id);
26470
+ switch (state?.kind) {
26471
+ case "running":
26472
+ case "cancelling":
26473
+ return state.commandId;
26474
+ case "cancelled-before-start":
26475
+ case void 0:
26476
+ return void 0;
26477
+ default:
26478
+ return unreachable(state);
26479
+ }
26480
+ };
26481
+ cancellation = (id) => {
26482
+ const state = this.#entries.get(id);
26483
+ switch (state?.kind) {
26484
+ case "cancelling":
26485
+ case "cancelled-before-start":
26486
+ return state.completion;
26487
+ case "running":
26488
+ case void 0:
26489
+ return void 0;
26490
+ default:
26491
+ return unreachable(state);
26492
+ }
26493
+ };
26494
+ isBusy = (id) => this.#entries.has(id);
26495
+ begin = (id, commandId) => {
26496
+ const state = this.#entries.get(id);
26497
+ switch (state?.kind) {
26498
+ case "running":
26499
+ case "cancelling":
26500
+ throw new AcpExecutionError(
26501
+ "Another prompt is already running in this conversation",
26502
+ {},
26503
+ "session_busy"
26504
+ );
26505
+ case "cancelled-before-start":
26506
+ case void 0:
26507
+ break;
26508
+ default:
26509
+ unreachable(state);
26510
+ }
26511
+ this.#entries.set(
26512
+ id,
26513
+ state?.kind === "cancelled-before-start" ? { kind: "cancelling", commandId, completion: state.completion } : { kind: "running", commandId }
26514
+ );
26515
+ };
26516
+ cancel = (id, stop) => {
26517
+ const state = this.#entries.get(id);
26518
+ switch (state?.kind) {
26519
+ case "cancelling":
26520
+ case "cancelled-before-start":
26521
+ return state.completion;
26522
+ case "running":
26523
+ case void 0:
26524
+ break;
26525
+ default:
26526
+ return unreachable(state);
26527
+ }
26528
+ const completion = Promise.withResolvers();
26529
+ this.#entries.set(
26530
+ id,
26531
+ state?.kind === "running" ? { kind: "cancelling", commandId: state.commandId, completion: completion.promise } : { kind: "cancelled-before-start", completion: completion.promise }
26532
+ );
26533
+ void (async () => await stop())().then(completion.resolve, completion.reject);
26534
+ return completion.promise;
26535
+ };
26536
+ finish = (id, commandId) => {
26537
+ if (this.command(id) === commandId) {
26538
+ this.#entries.delete(id);
26539
+ }
26540
+ };
26541
+ };
26542
+
26543
+ // src/acp/agent-session.ts
26417
26544
  import {
26418
26545
  methods as methods8,
26419
26546
  PROTOCOL_VERSION as PROTOCOL_VERSION3
@@ -27311,23 +27438,7 @@ var AcpActivityTracker = class {
27311
27438
  };
27312
27439
  };
27313
27440
 
27314
- // src/acp/native-session.ts
27315
- var path = external_exports.string().min(1).max(2048).refine((value) => !value.includes("\0"));
27316
- var title = external_exports.string().transform((value) => value.slice(0, 500));
27317
- var nativeSessionIdSchema = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/);
27318
- var nativeSessionInfoSchema = external_exports.object({
27319
- sessionId: nativeSessionIdSchema,
27320
- cwd: path,
27321
- additionalDirectories: external_exports.array(path).max(16).default([]).readonly(),
27322
- title: title.nullish(),
27323
- updatedAt: external_exports.iso.datetime({ offset: true }).nullish()
27324
- }).readonly();
27325
- var nativeSessionPageSchema = external_exports.object({
27326
- sessions: external_exports.array(nativeSessionInfoSchema).max(500).readonly(),
27327
- nextCursor: external_exports.string().min(1).max(4096).nullish()
27328
- }).readonly();
27329
-
27330
- // src/acp/process-endpoint.ts
27441
+ // src/acp/agent-connection.ts
27331
27442
  import { spawn as spawn4 } from "node:child_process";
27332
27443
  import { ndJsonStream as ndJsonStream2, RequestError as RequestError3 } from "@agentclientprotocol/sdk";
27333
27444
 
@@ -27342,7 +27453,7 @@ function readString2(value, fallback = "") {
27342
27453
  return typeof value === "string" ? value : fallback;
27343
27454
  }
27344
27455
 
27345
- // src/acp/process-endpoint.ts
27456
+ // src/acp/agent-connection.ts
27346
27457
  function readableWebStream(input2) {
27347
27458
  let streamOpen = true;
27348
27459
  return new ReadableStream({
@@ -27418,7 +27529,7 @@ function createWritableAcpStream(output2) {
27418
27529
  }
27419
27530
  });
27420
27531
  }
27421
- var AcpEndpoint = class {
27532
+ var AgentConnection = class {
27422
27533
  connection;
27423
27534
  termination;
27424
27535
  #process;
@@ -27525,6 +27636,86 @@ var AcpEndpoint = class {
27525
27636
  };
27526
27637
  };
27527
27638
 
27639
+ // src/acp/native-session.ts
27640
+ var path = external_exports.string().min(1).max(2048).refine((value) => !value.includes("\0"));
27641
+ var title = external_exports.string().transform((value) => value.slice(0, 500));
27642
+ var nativeSessionIdSchema = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/);
27643
+ var nativeSessionInfoSchema = external_exports.object({
27644
+ sessionId: nativeSessionIdSchema,
27645
+ cwd: path,
27646
+ additionalDirectories: external_exports.array(path).max(16).default([]).readonly(),
27647
+ title: title.nullish(),
27648
+ updatedAt: external_exports.iso.datetime({ offset: true }).nullish()
27649
+ }).readonly();
27650
+ var nativeSessionPageSchema = external_exports.object({
27651
+ sessions: external_exports.array(nativeSessionInfoSchema).max(500).readonly(),
27652
+ nextCursor: external_exports.string().min(1).max(4096).nullish()
27653
+ }).readonly();
27654
+
27655
+ // src/acp/agent-update-stream.ts
27656
+ var MAX_PENDING_UPDATES = 100;
27657
+ var MAX_PENDING_BYTES = 1024 * 1024;
27658
+ var AgentUpdateStream = class {
27659
+ #selection = { kind: "awaiting-session", notifications: [], bytes: 0 };
27660
+ #tail = Promise.resolve();
27661
+ #consume;
27662
+ constructor(consume) {
27663
+ this.#consume = consume;
27664
+ }
27665
+ sessionId = () => this.#selection.kind === "selected" ? this.#selection.sessionId : "";
27666
+ drained = () => this.#tail;
27667
+ #enqueue = (notification) => {
27668
+ this.#tail = this.#tail.then(async () => await this.#consume(notification));
27669
+ return this.#tail;
27670
+ };
27671
+ receive = (notification) => {
27672
+ const selection = this.#selection;
27673
+ switch (selection.kind) {
27674
+ case "selected":
27675
+ return this.#enqueue(notification);
27676
+ case "awaiting-session": {
27677
+ const bytes = selection.bytes + Buffer.byteLength(JSON.stringify(notification));
27678
+ if (selection.notifications.length >= MAX_PENDING_UPDATES || bytes > MAX_PENDING_BYTES) {
27679
+ return Promise.reject(
27680
+ new AcpExecutionError(
27681
+ "ACP agent sent too many updates before creating its session",
27682
+ {},
27683
+ "agent_update_limit"
27684
+ )
27685
+ );
27686
+ }
27687
+ this.#selection = {
27688
+ kind: "awaiting-session",
27689
+ notifications: [...selection.notifications, notification],
27690
+ bytes
27691
+ };
27692
+ return Promise.resolve();
27693
+ }
27694
+ }
27695
+ };
27696
+ select = (sessionId) => {
27697
+ const selected = nativeSessionIdSchema.parse(sessionId);
27698
+ const selection = this.#selection;
27699
+ switch (selection.kind) {
27700
+ case "selected":
27701
+ if (selection.sessionId !== selected) {
27702
+ throw new AcpExecutionError(
27703
+ "ACP agent attempted to replace the selected session",
27704
+ {},
27705
+ "invalid_agent_session"
27706
+ );
27707
+ }
27708
+ return;
27709
+ case "awaiting-session":
27710
+ this.#selection = { kind: "selected", sessionId: selected };
27711
+ for (const notification of selection.notifications) {
27712
+ void this.#enqueue(notification);
27713
+ }
27714
+ return;
27715
+ }
27716
+ };
27717
+ };
27718
+
27528
27719
  // src/acp/session-config/session-config-protocol.ts
27529
27720
  import { methods as methods7 } from "@agentclientprotocol/sdk";
27530
27721
  var MAXIMUM_CONFIG_OPTIONS = 100;
@@ -34143,10 +34334,8 @@ var SqliteAcpSessionStore = class {
34143
34334
  };
34144
34335
  };
34145
34336
 
34146
- // src/acp/process-session.ts
34337
+ // src/acp/agent-session.ts
34147
34338
  var PROCESS_STOP_TIMEOUT_MILLISECONDS = 1e3;
34148
- var MAX_PRE_SESSION_UPDATES = 100;
34149
- var MAX_PRE_SESSION_UPDATE_BYTES = 1024 * 1024;
34150
34339
  var RetryableAcpInitializationError = class extends AcpExecutionError {
34151
34340
  constructor(cause) {
34152
34341
  super("ACP agent initialization failed", { cause });
@@ -34161,8 +34350,8 @@ function recordsEqual(left, right) {
34161
34350
  const rightEntries = Object.entries(right);
34162
34351
  return leftEntries.length === rightEntries.length && leftEntries.every(([name, value]) => right[name] === value);
34163
34352
  }
34164
- var AcpProcessSession = class _AcpProcessSession {
34165
- #endpoint;
34353
+ var AgentSession = class _AgentSession {
34354
+ #connection;
34166
34355
  #interactions;
34167
34356
  #additionalDirectories;
34168
34357
  #agentId;
@@ -34170,12 +34359,11 @@ var AcpProcessSession = class _AcpProcessSession {
34170
34359
  #environment;
34171
34360
  #getObserver;
34172
34361
  #mobiusSessionId;
34173
- #preSessionUpdates = [];
34362
+ #updates;
34174
34363
  #metrics;
34175
34364
  #sessionConfigProtocol;
34176
34365
  #store;
34177
34366
  #verifiedAgentVersion;
34178
- #preSessionUpdateBytes = 0;
34179
34367
  #agentName = "";
34180
34368
  #agentVersion = "";
34181
34369
  #bufferedAgentText = [];
@@ -34183,7 +34371,6 @@ var AcpProcessSession = class _AcpProcessSession {
34183
34371
  #commands = [];
34184
34372
  #configRevision = 0;
34185
34373
  #configOptions = [];
34186
- #nativeSessionId = "";
34187
34374
  #prompted = false;
34188
34375
  #nativePrompt = null;
34189
34376
  #replay = {
@@ -34193,10 +34380,11 @@ var AcpProcessSession = class _AcpProcessSession {
34193
34380
  #sessionTitle = null;
34194
34381
  #sessionUpdatedAt = "";
34195
34382
  #turn = new IdleAcpTurn();
34196
- #updateTail = Promise.resolve();
34197
34383
  constructor(agent, cwd, additionalDirectories, mobiusSessionId, getObserver, store, metrics) {
34384
+ this.#updates = new AgentUpdateStream((notification) => this.#processUpdate(notification));
34198
34385
  this.#additionalDirectories = [...additionalDirectories];
34199
34386
  this.#agentId = agent.id;
34387
+ this.#commands = [];
34200
34388
  this.#cwd = cwd;
34201
34389
  this.#environment = agent.environment;
34202
34390
  this.#getObserver = getObserver;
@@ -34211,7 +34399,7 @@ var AcpProcessSession = class _AcpProcessSession {
34211
34399
  assertNativeSession: (sessionId) => this.assertNativeSession(sessionId),
34212
34400
  observer: getObserver
34213
34401
  });
34214
- this.#endpoint = new AcpEndpoint(agent, cwd, this);
34402
+ this.#connection = new AgentConnection(agent, cwd, this);
34215
34403
  }
34216
34404
  static async #start(options, getObserver, store, initialize, metrics) {
34217
34405
  for (let attempt = 1; attempt <= 2; attempt += 1) {
@@ -34234,7 +34422,7 @@ var AcpProcessSession = class _AcpProcessSession {
34234
34422
  }
34235
34423
  const runtime = metrics.measureSync(
34236
34424
  "process-spawn",
34237
- () => new _AcpProcessSession(
34425
+ () => new _AgentSession(
34238
34426
  options.agent,
34239
34427
  options.cwd,
34240
34428
  options.additionalDirectories,
@@ -34264,14 +34452,14 @@ var AcpProcessSession = class _AcpProcessSession {
34264
34452
  }
34265
34453
  throw new AcpExecutionError("ACP agent initialization failed");
34266
34454
  }
34267
- static start = async (options, getObserver, store, metrics = unmeasuredOperationMetrics) => await _AcpProcessSession.#start(
34455
+ static start = async (options, getObserver, store, metrics = unmeasuredOperationMetrics) => await _AgentSession.#start(
34268
34456
  options,
34269
34457
  getObserver,
34270
34458
  store,
34271
34459
  async (runtime) => await runtime.initialize(options.signal, options.origin),
34272
34460
  metrics
34273
34461
  );
34274
- static startNativeSessionBrowser = async (options, getObserver, store) => await _AcpProcessSession.#start(
34462
+ static startNativeSessionBrowser = async (options, getObserver, store) => await _AgentSession.#start(
34275
34463
  options,
34276
34464
  getObserver,
34277
34465
  store,
@@ -34304,20 +34492,20 @@ var AcpProcessSession = class _AcpProcessSession {
34304
34492
  this.#replay = { kind: "capture", history };
34305
34493
  try {
34306
34494
  await this.race(
34307
- this.#endpoint.connection.agent.request(
34495
+ this.#connection.connection.agent.request(
34308
34496
  methods8.agent.session.load,
34309
34497
  {
34310
34498
  additionalDirectories: [...this.#additionalDirectories],
34311
34499
  cwd: this.#cwd,
34312
34500
  mcpServers: [],
34313
- sessionId: this.#nativeSessionId
34501
+ sessionId: this.#updates.sessionId()
34314
34502
  },
34315
34503
  { cancellationSignal: signal }
34316
34504
  ),
34317
34505
  "ACP agent exited while loading history",
34318
34506
  signal
34319
34507
  );
34320
- await this.#updateTail;
34508
+ await this.#updates.drained();
34321
34509
  signal.throwIfAborted();
34322
34510
  return await embedLocalHistoryImages(await history.snapshot(), signal);
34323
34511
  } finally {
@@ -34413,9 +34601,9 @@ var AcpProcessSession = class _AcpProcessSession {
34413
34601
  await this.#metrics.measure("agent-initialize", async () => await this.#initializeAgentOperation(signal));
34414
34602
  }
34415
34603
  async #initializeAgentOperation(signal) {
34416
- if (this.#endpoint.inProcessAgent !== null) {
34604
+ if (this.#connection.inProcessAgent !== null) {
34417
34605
  await this.race(
34418
- this.#endpoint.inProcessAgent.initialize(signal),
34606
+ this.#connection.inProcessAgent.initialize(signal),
34419
34607
  "The Codex app-server exited during initialization",
34420
34608
  signal
34421
34609
  ).catch((cause) => {
@@ -34424,7 +34612,7 @@ var AcpProcessSession = class _AcpProcessSession {
34424
34612
  });
34425
34613
  }
34426
34614
  const initialized = await this.race(
34427
- this.#endpoint.connection.agent.request(
34615
+ this.#connection.connection.agent.request(
34428
34616
  methods8.agent.initialize,
34429
34617
  {
34430
34618
  clientCapabilities: {
@@ -34503,7 +34691,7 @@ var AcpProcessSession = class _AcpProcessSession {
34503
34691
  const forked = await this.#metrics.measure(
34504
34692
  "session-fork",
34505
34693
  async () => await this.race(
34506
- this.#endpoint.connection.agent.request(
34694
+ this.#connection.connection.agent.request(
34507
34695
  methods8.agent.session.fork,
34508
34696
  {
34509
34697
  sessionId: nativeSessionIdSchema.parse(origin.nativeSessionId),
@@ -34518,7 +34706,7 @@ var AcpProcessSession = class _AcpProcessSession {
34518
34706
  )
34519
34707
  );
34520
34708
  this.selectNativeSession(forked.sessionId);
34521
- if (this.#nativeSessionId === origin.nativeSessionId || this.#store.findNative(this.#agentId, this.#nativeSessionId).length > 0) {
34709
+ if (this.#updates.sessionId() === origin.nativeSessionId || this.#store.findNative(this.#agentId, this.#updates.sessionId()).length > 0) {
34522
34710
  throw new AcpExecutionError(
34523
34711
  "The Agent did not create an independent fork",
34524
34712
  {},
@@ -34537,13 +34725,13 @@ var AcpProcessSession = class _AcpProcessSession {
34537
34725
  lifecycleResponse = await this.#metrics.measure(
34538
34726
  "session-resume",
34539
34727
  async () => await this.race(
34540
- this.#endpoint.connection.agent.request(
34728
+ this.#connection.connection.agent.request(
34541
34729
  methods8.agent.session.resume,
34542
34730
  {
34543
34731
  additionalDirectories: [...this.#additionalDirectories],
34544
34732
  cwd: this.#cwd,
34545
34733
  mcpServers: [],
34546
- sessionId: this.#nativeSessionId
34734
+ sessionId: this.#updates.sessionId()
34547
34735
  },
34548
34736
  { cancellationSignal: signal }
34549
34737
  ),
@@ -34557,13 +34745,13 @@ var AcpProcessSession = class _AcpProcessSession {
34557
34745
  lifecycleResponse = await this.#metrics.measure(
34558
34746
  "session-load",
34559
34747
  async () => await this.race(
34560
- this.#endpoint.connection.agent.request(
34748
+ this.#connection.connection.agent.request(
34561
34749
  methods8.agent.session.load,
34562
34750
  {
34563
34751
  additionalDirectories: [...this.#additionalDirectories],
34564
34752
  cwd: this.#cwd,
34565
34753
  mcpServers: [],
34566
- sessionId: this.#nativeSessionId
34754
+ sessionId: this.#updates.sessionId()
34567
34755
  },
34568
34756
  { cancellationSignal: signal }
34569
34757
  ),
@@ -34572,7 +34760,7 @@ var AcpProcessSession = class _AcpProcessSession {
34572
34760
  )
34573
34761
  );
34574
34762
  } finally {
34575
- await this.#updateTail;
34763
+ await this.#updates.drained();
34576
34764
  this.#replay = { kind: "idle" };
34577
34765
  }
34578
34766
  } else {
@@ -34596,7 +34784,7 @@ var AcpProcessSession = class _AcpProcessSession {
34596
34784
  const created = await this.#metrics.measure(
34597
34785
  "session-new",
34598
34786
  async () => await this.race(
34599
- this.#endpoint.connection.agent.request(
34787
+ this.#connection.connection.agent.request(
34600
34788
  methods8.agent.session.new,
34601
34789
  {
34602
34790
  additionalDirectories: [...this.#additionalDirectories],
@@ -34613,13 +34801,13 @@ var AcpProcessSession = class _AcpProcessSession {
34613
34801
  lifecycleResponse = created;
34614
34802
  }
34615
34803
  this.#configOptions = this.#sessionConfigProtocol.normalizeLifecycle(lifecycleResponse);
34616
- await this.#updateTail;
34804
+ await this.#updates.drained();
34617
34805
  signal.throwIfAborted();
34618
34806
  this.#store.write(
34619
34807
  new AcpStoredSession(
34620
34808
  this.#mobiusSessionId,
34621
34809
  this.#agentId,
34622
- this.#nativeSessionId,
34810
+ this.#updates.sessionId(),
34623
34811
  this.#cwd,
34624
34812
  this.#additionalDirectories,
34625
34813
  this.#prompted,
@@ -34636,7 +34824,7 @@ var AcpProcessSession = class _AcpProcessSession {
34636
34824
  );
34637
34825
  }
34638
34826
  const response = await this.race(
34639
- this.#endpoint.connection.agent.request(methods8.agent.session.list, cursor === null ? {} : { cursor }, {
34827
+ this.#connection.connection.agent.request(methods8.agent.session.list, cursor === null ? {} : { cursor }, {
34640
34828
  cancellationSignal: signal
34641
34829
  }),
34642
34830
  "ACP agent exited while listing sessions",
@@ -34661,7 +34849,7 @@ var AcpProcessSession = class _AcpProcessSession {
34661
34849
  );
34662
34850
  }
34663
34851
  await this.race(
34664
- this.#endpoint.connection.agent.request(
34852
+ this.#connection.connection.agent.request(
34665
34853
  methods8.agent.session.delete,
34666
34854
  { sessionId: nativeSessionIdSchema.parse(nativeSessionId) },
34667
34855
  { cancellationSignal: signal }
@@ -34670,9 +34858,9 @@ var AcpProcessSession = class _AcpProcessSession {
34670
34858
  signal
34671
34859
  );
34672
34860
  };
34673
- nativeSessionId = () => this.#nativeSessionId;
34861
+ nativeSessionId = () => this.#updates.sessionId();
34674
34862
  adoptNativeSessionId = (sessionId) => {
34675
- if (this.#prompted || this.#nativeSessionId !== sessionId) {
34863
+ if (this.#prompted || this.#updates.sessionId() !== sessionId) {
34676
34864
  throw new AcpExecutionError("The new native Session cannot be adopted", {}, "session_identity_mismatch");
34677
34865
  }
34678
34866
  const previousSessionId = this.#mobiusSessionId;
@@ -34720,10 +34908,10 @@ var AcpProcessSession = class _AcpProcessSession {
34720
34908
  const configured = await this.#sessionConfigProtocol.configure(
34721
34909
  this.#configOptions,
34722
34910
  options,
34723
- this.#nativeSessionId,
34911
+ this.#updates.sessionId(),
34724
34912
  {
34725
34913
  request: async (method, params, failureMessage, signal) => await this.race(
34726
- this.#endpoint.connection.agent.request(method, params, {
34914
+ this.#connection.connection.agent.request(method, params, {
34727
34915
  cancellationSignal: signal
34728
34916
  }),
34729
34917
  failureMessage,
@@ -34739,7 +34927,7 @@ var AcpProcessSession = class _AcpProcessSession {
34739
34927
  "invalid_session_configuration"
34740
34928
  );
34741
34929
  }
34742
- await this.#updateTail;
34930
+ await this.#updates.drained();
34743
34931
  if (this.#configRevision === configRevision) {
34744
34932
  this.#configOptions = configured;
34745
34933
  }
@@ -34804,7 +34992,7 @@ var AcpProcessSession = class _AcpProcessSession {
34804
34992
  };
34805
34993
  nativeHistoryTurn = () => {
34806
34994
  const prompt = this.#nativePrompt;
34807
- const nativeTurnId = this.#endpoint.inProcessAgent?.nativeTurnId?.() ?? null;
34995
+ const nativeTurnId = this.#connection.inProcessAgent?.nativeTurnId?.() ?? null;
34808
34996
  return prompt === null || nativeTurnId === null || nativeTurnId === prompt.previousTurnId ? null : { commandId: prompt.commandId, nativeTurnId };
34809
34997
  };
34810
34998
  prompt = async (options) => {
@@ -34819,7 +35007,7 @@ var AcpProcessSession = class _AcpProcessSession {
34819
35007
  new AcpStoredSession(
34820
35008
  this.#mobiusSessionId,
34821
35009
  this.#agentId,
34822
- this.#nativeSessionId,
35010
+ this.#updates.sessionId(),
34823
35011
  this.#cwd,
34824
35012
  this.#additionalDirectories,
34825
35013
  true,
@@ -34837,19 +35025,19 @@ var AcpProcessSession = class _AcpProcessSession {
34837
35025
  this.#turn = running;
34838
35026
  this.#nativePrompt = {
34839
35027
  commandId: options.commandId,
34840
- previousTurnId: this.#endpoint.inProcessAgent?.nativeTurnId?.() ?? null
35028
+ previousTurnId: this.#connection.inProcessAgent?.nativeTurnId?.() ?? null
34841
35029
  };
34842
35030
  try {
34843
35031
  const response = await this.race(
34844
- this.#endpoint.connection.agent.request(
35032
+ this.#connection.connection.agent.request(
34845
35033
  methods8.agent.session.prompt,
34846
- { prompt, sessionId: this.#nativeSessionId },
35034
+ { prompt, sessionId: this.#updates.sessionId() },
34847
35035
  { cancellationSignal: options.signal }
34848
35036
  ),
34849
35037
  "ACP agent exited during a prompt",
34850
35038
  options.signal
34851
35039
  );
34852
- await this.#updateTail;
35040
+ await this.#updates.drained();
34853
35041
  await this.flushAgentText();
34854
35042
  await running.activities.finish();
34855
35043
  let result;
@@ -34899,10 +35087,10 @@ var AcpProcessSession = class _AcpProcessSession {
34899
35087
  }
34900
35088
  const prompt = this.buildPrompt(options);
34901
35089
  const response = await this.race(
34902
- this.#endpoint.connection.agent.request("_session/steering", {
35090
+ this.#connection.connection.agent.request("_session/steering", {
34903
35091
  _meta: { steering: { idleBehavior: "promptRequired" } },
34904
35092
  prompt,
34905
- sessionId: this.#nativeSessionId
35093
+ sessionId: this.#updates.sessionId()
34906
35094
  }),
34907
35095
  "ACP agent exited during steering",
34908
35096
  options.signal
@@ -34935,12 +35123,12 @@ var AcpProcessSession = class _AcpProcessSession {
34935
35123
  );
34936
35124
  };
34937
35125
  cancel = async () => {
34938
- const capturedProcesses = await this.#endpoint.captureProcessTree();
35126
+ const capturedProcesses = await this.#connection.captureProcessTree();
34939
35127
  try {
34940
35128
  await this.#interactions.cancelPendingInteractions();
34941
35129
  if (this.#turn.running) {
34942
- await this.#endpoint.connection.agent.notify(methods8.agent.session.cancel, {
34943
- sessionId: this.#nativeSessionId
35130
+ await this.#connection.connection.agent.notify(methods8.agent.session.cancel, {
35131
+ sessionId: this.#updates.sessionId()
34944
35132
  });
34945
35133
  }
34946
35134
  } finally {
@@ -34952,45 +35140,9 @@ var AcpProcessSession = class _AcpProcessSession {
34952
35140
  onPermission = (request, signal) => this.#interactions.onPermission(request, signal);
34953
35141
  onElicitation = (request, signal) => this.#interactions.onElicitation(request, signal);
34954
35142
  onElicitationComplete = (notification) => this.#interactions.onElicitationComplete(notification);
34955
- onUpdate = (notification) => {
34956
- if (this.#nativeSessionId.length === 0) {
34957
- const notificationBytes = Buffer.byteLength(JSON.stringify(notification));
34958
- if (this.#preSessionUpdates.length >= MAX_PRE_SESSION_UPDATES || this.#preSessionUpdateBytes + notificationBytes > MAX_PRE_SESSION_UPDATE_BYTES) {
34959
- return Promise.reject(
34960
- new AcpExecutionError(
34961
- "ACP agent sent too many updates before creating its session",
34962
- {},
34963
- "agent_update_limit"
34964
- )
34965
- );
34966
- }
34967
- this.#preSessionUpdates.push(notification);
34968
- this.#preSessionUpdateBytes += notificationBytes;
34969
- return Promise.resolve();
34970
- }
34971
- return this.enqueueUpdate(notification);
34972
- };
34973
- enqueueUpdate = (notification) => {
34974
- this.#updateTail = this.#updateTail.then(async () => await this.processUpdate(notification));
34975
- return this.#updateTail;
34976
- };
34977
- selectNativeSession = (sessionId) => {
34978
- const selected = nativeSessionIdSchema.parse(sessionId);
34979
- if (this.#nativeSessionId.length > 0 && this.#nativeSessionId !== selected) {
34980
- throw new AcpExecutionError(
34981
- "ACP agent attempted to replace the selected session",
34982
- {},
34983
- "invalid_agent_session"
34984
- );
34985
- }
34986
- this.#nativeSessionId = selected;
34987
- const pending = this.#preSessionUpdates.splice(0);
34988
- this.#preSessionUpdateBytes = 0;
34989
- for (const notification of pending) {
34990
- void this.enqueueUpdate(notification);
34991
- }
34992
- };
34993
- processUpdate = async (notification) => {
35143
+ onUpdate = (notification) => this.#updates.receive(notification);
35144
+ selectNativeSession = (sessionId) => this.#updates.select(sessionId);
35145
+ #processUpdate = async (notification) => {
34994
35146
  this.assertNativeSession(notification.sessionId);
34995
35147
  const update = notification.update;
34996
35148
  if (this.#replay.kind === "capture") {
@@ -35060,7 +35212,7 @@ var AcpProcessSession = class _AcpProcessSession {
35060
35212
  })).filter((command) => command.name.length > 0);
35061
35213
  this.#commands = commands;
35062
35214
  await this.#getObserver().onCommands({
35063
- commands,
35215
+ commands: this.#commands,
35064
35216
  kind: SESSION_COMMANDS_UPDATED_KIND,
35065
35217
  sessionId: this.#mobiusSessionId
35066
35218
  });
@@ -35090,12 +35242,12 @@ var AcpProcessSession = class _AcpProcessSession {
35090
35242
  if (Object.hasOwn(update, "updatedAt")) {
35091
35243
  this.#sessionUpdatedAt = truncate3(update.updatedAt ?? "", 128);
35092
35244
  }
35093
- if (this.#nativeSessionId.length > 0) {
35245
+ if (this.#updates.sessionId().length > 0) {
35094
35246
  this.#store.write(
35095
35247
  new AcpStoredSession(
35096
35248
  this.#mobiusSessionId,
35097
35249
  this.#agentId,
35098
- this.#nativeSessionId,
35250
+ this.#updates.sessionId(),
35099
35251
  this.#cwd,
35100
35252
  this.#additionalDirectories,
35101
35253
  this.#prompted,
@@ -35127,11 +35279,11 @@ var AcpProcessSession = class _AcpProcessSession {
35127
35279
  close = async () => {
35128
35280
  try {
35129
35281
  await this.#interactions.cancelPendingInteractions();
35130
- if (this.#capabilities.closeSession && this.#nativeSessionId.length > 0) {
35282
+ if (this.#capabilities.closeSession && this.#updates.sessionId().length > 0) {
35131
35283
  try {
35132
- await this.#endpoint.connection.agent.request(
35284
+ await this.#connection.connection.agent.request(
35133
35285
  methods8.agent.session.close,
35134
- { sessionId: this.#nativeSessionId },
35286
+ { sessionId: this.#updates.sessionId() },
35135
35287
  {
35136
35288
  cancellationSignal: AbortSignal.timeout(PROCESS_STOP_TIMEOUT_MILLISECONDS)
35137
35289
  }
@@ -35143,10 +35295,10 @@ var AcpProcessSession = class _AcpProcessSession {
35143
35295
  await this.closeProcess();
35144
35296
  }
35145
35297
  };
35146
- closeProcess = (capturedProcesses = []) => this.#endpoint.closeProcess(capturedProcesses);
35147
- race = (operation, exitMessage, signal) => this.#endpoint.race(operation, exitMessage, signal);
35298
+ closeProcess = (capturedProcesses = []) => this.#connection.closeProcess(capturedProcesses);
35299
+ race = (operation, exitMessage, signal) => this.#connection.race(operation, exitMessage, signal);
35148
35300
  assertNativeSession = (sessionId) => {
35149
- if (sessionId !== this.#nativeSessionId) {
35301
+ if (sessionId !== this.#updates.sessionId()) {
35150
35302
  throw new AcpExecutionError("ACP agent referenced an unknown session", {}, "invalid_agent_session");
35151
35303
  }
35152
35304
  };
@@ -35160,8 +35312,8 @@ var AcpProcessSession = class _AcpProcessSession {
35160
35312
  };
35161
35313
  };
35162
35314
 
35163
- // src/acp/retained-sessions.ts
35164
- var RetainedSessions = class {
35315
+ // src/acp/retained-agent-processes.ts
35316
+ var RetainedAgentProcesses = class {
35165
35317
  #entries = /* @__PURE__ */ new Map();
35166
35318
  #events;
35167
35319
  constructor(events) {
@@ -35264,84 +35416,118 @@ var RetainedSessions = class {
35264
35416
  };
35265
35417
  };
35266
35418
 
35267
- // src/acp/session-executions.ts
35268
- var unreachable = (state) => {
35269
- throw new AcpExecutionError("Unexpected execution state", { cause: state });
35270
- };
35271
- var SessionExecutions = class {
35272
- #entries = /* @__PURE__ */ new Map();
35273
- command = (id) => {
35274
- const state = this.#entries.get(id);
35275
- switch (state?.kind) {
35276
- case "running":
35277
- case "cancelling":
35278
- return state.commandId;
35279
- case "cancelled-before-start":
35280
- case void 0:
35281
- return void 0;
35282
- default:
35283
- return unreachable(state);
35419
+ // src/acp/agent-query-processes.ts
35420
+ var AgentQueryProcesses = class {
35421
+ #processesByQuery;
35422
+ #processes;
35423
+ #observer = new NullAcpSessionObserver();
35424
+ #store = new MemoryAcpSessionStore();
35425
+ constructor(processes) {
35426
+ this.#processes = processes;
35427
+ this.#processesByQuery = new RetainedAgentProcesses({
35428
+ touch: processes.touch,
35429
+ changed: processes.notifyChanged
35430
+ });
35431
+ }
35432
+ retire = async (sessionId, runtime) => {
35433
+ const retained = this.#processesByQuery.detach(sessionId, runtime);
35434
+ if (retained) {
35435
+ this.#store.remove(sessionId);
35284
35436
  }
35437
+ await this.#processes.retire(runtime, () => runtime.close());
35285
35438
  };
35286
- cancellation = (id) => {
35287
- const state = this.#entries.get(id);
35288
- switch (state?.kind) {
35289
- case "cancelling":
35290
- case "cancelled-before-start":
35291
- return state.completion;
35292
- case "running":
35293
- case void 0:
35294
- return void 0;
35295
- default:
35296
- return unreachable(state);
35439
+ async #startRetained(options) {
35440
+ const runtime = await this.#processes.startRetained(
35441
+ options.signal,
35442
+ () => AgentSession.startNativeSessionBrowser(options, () => this.#observer, this.#store),
35443
+ {
35444
+ isBusy: () => this.#processesByQuery.isBusy(options.sessionId),
35445
+ retire: (runtime2) => this.retire(options.sessionId, runtime2)
35446
+ }
35447
+ );
35448
+ this.#processesByQuery.retain(options.sessionId, runtime);
35449
+ return runtime;
35450
+ }
35451
+ async #startPreparation(options) {
35452
+ return await this.#processesByQuery.prepare(options.sessionId, async () => {
35453
+ return await this.#startRetained(options);
35454
+ });
35455
+ }
35456
+ async #replacePreparation(existing, options) {
35457
+ return await this.#processesByQuery.prepare(options.sessionId, async () => {
35458
+ await this.retire(options.sessionId, existing);
35459
+ return await this.#startRetained(options);
35460
+ });
35461
+ }
35462
+ prepare = async (options) => {
35463
+ const pending = this.#processesByQuery.pending(options.sessionId);
35464
+ if (pending !== void 0) {
35465
+ const runtime2 = await pending;
35466
+ if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35467
+ this.#processesByQuery.touch(options.sessionId, runtime2);
35468
+ return runtime2.prepared();
35469
+ }
35470
+ return await this.prepare(options);
35297
35471
  }
35298
- };
35299
- isBusy = (id) => this.#entries.has(id);
35300
- begin = (id, commandId) => {
35301
- const state = this.#entries.get(id);
35302
- switch (state?.kind) {
35303
- case "running":
35304
- case "cancelling":
35472
+ const existing = this.#processesByQuery.get(options.sessionId);
35473
+ if (existing !== void 0) {
35474
+ if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35475
+ this.#processesByQuery.touch(options.sessionId, existing);
35476
+ return existing.prepared();
35477
+ }
35478
+ if (!existing.canRebind()) {
35305
35479
  throw new AcpExecutionError(
35306
- "Another prompt is already running in this conversation",
35480
+ "The agent or workspace cannot change after a conversation has started",
35307
35481
  {},
35308
- "session_busy"
35482
+ "session_identity_mismatch"
35309
35483
  );
35310
- case "cancelled-before-start":
35311
- case void 0:
35312
- break;
35313
- default:
35314
- unreachable(state);
35484
+ }
35485
+ const runtime2 = await this.#replacePreparation(existing, options);
35486
+ return runtime2.prepared();
35315
35487
  }
35316
- this.#entries.set(
35317
- id,
35318
- state?.kind === "cancelled-before-start" ? { kind: "cancelling", commandId, completion: state.completion } : { kind: "running", commandId }
35319
- );
35488
+ const runtime = await this.#startPreparation(options);
35489
+ return runtime.prepared();
35320
35490
  };
35321
- cancel = (id, stop) => {
35322
- const state = this.#entries.get(id);
35323
- switch (state?.kind) {
35324
- case "cancelling":
35325
- case "cancelled-before-start":
35326
- return state.completion;
35327
- case "running":
35328
- case void 0:
35329
- break;
35330
- default:
35331
- return unreachable(state);
35491
+ async #ensure(options) {
35492
+ const existing = this.#processesByQuery.get(options.sessionId);
35493
+ if (existing !== void 0) {
35494
+ if (!existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35495
+ throw new AcpExecutionError(
35496
+ "The agent or workspace cannot change after a conversation has started",
35497
+ {},
35498
+ "session_identity_mismatch"
35499
+ );
35500
+ }
35501
+ this.#processesByQuery.touch(options.sessionId, existing);
35502
+ return existing;
35332
35503
  }
35333
- const completion = Promise.withResolvers();
35334
- this.#entries.set(
35335
- id,
35336
- state?.kind === "running" ? { kind: "cancelling", commandId: state.commandId, completion: completion.promise } : { kind: "cancelled-before-start", completion: completion.promise }
35504
+ await this.prepare(options);
35505
+ const started = this.#processesByQuery.get(options.sessionId);
35506
+ if (started === void 0) {
35507
+ throw new AcpExecutionError("ACP native session browser did not start");
35508
+ }
35509
+ return started;
35510
+ }
35511
+ use = async (options, operation) => await this.#processesByQuery.use(options.sessionId, async () => await operation(await this.#ensure(options)));
35512
+ preview = async (options, nativeSessionId) => {
35513
+ return await this.#processes.runTransient(
35514
+ options.signal,
35515
+ async () => await AgentSession.startNativeSessionBrowser(
35516
+ options,
35517
+ () => this.#observer,
35518
+ new MemoryAcpSessionStore()
35519
+ ),
35520
+ async (runtime) => {
35521
+ runtime.selectNativeSession(nativeSessionId);
35522
+ return await runtime.loadHistory(options.signal);
35523
+ },
35524
+ async (runtime) => await runtime.closeProcess()
35337
35525
  );
35338
- void (async () => await stop())().then(completion.resolve, completion.reject);
35339
- return completion.promise;
35340
35526
  };
35341
- finish = (id, commandId) => {
35342
- if (this.command(id) === commandId) {
35343
- this.#entries.delete(id);
35344
- }
35527
+ close = async () => {
35528
+ await Promise.all(
35529
+ this.#processesByQuery.entries().map(async ([id, runtime]) => await this.retire(id, runtime))
35530
+ );
35345
35531
  };
35346
35532
  };
35347
35533
 
@@ -35446,9 +35632,9 @@ async function waitForAcpProcessCapacity(completion, signal) {
35446
35632
  }
35447
35633
  }
35448
35634
 
35449
- // src/acp/process-pool.ts
35635
+ // src/acp/agent-process-pool.ts
35450
35636
  var MAX_ACP_PROCESSES = 10;
35451
- var AcpProcessPool = class {
35637
+ var AgentProcessPool = class {
35452
35638
  #slots = /* @__PURE__ */ new Map();
35453
35639
  #lock = new AcpProcessCapacityLock();
35454
35640
  #changed = Promise.withResolvers();
@@ -35552,20 +35738,18 @@ var AcpProcessPool = class {
35552
35738
  };
35553
35739
  };
35554
35740
 
35555
- // src/acp/session-manager.ts
35741
+ // src/acp/agent-runtime-manager.ts
35556
35742
  var SESSION_CONTROL_TIMEOUT_MILLISECONDS = 3e4;
35557
- var AcpSessionManager = class {
35558
- #processes = new AcpProcessPool();
35559
- #sessions = new RetainedSessions({ touch: this.#processes.touch, changed: this.#processes.notifyChanged });
35560
- #nativeBrowserSessions = new RetainedSessions({
35743
+ var AgentRuntimeManager = class {
35744
+ #processes = new AgentProcessPool();
35745
+ #executionProcesses = new RetainedAgentProcesses({
35561
35746
  touch: this.#processes.touch,
35562
35747
  changed: this.#processes.notifyChanged
35563
35748
  });
35564
- #executions = new SessionExecutions();
35749
+ #queryProcesses = new AgentQueryProcesses(this.#processes);
35750
+ #executions = new ActiveExecutions();
35565
35751
  #agentSettingsObserver = new NullAcpSessionObserver();
35566
35752
  #nativeOperations = /* @__PURE__ */ new Set();
35567
- #nativeBrowserObserver = new NullAcpSessionObserver();
35568
- #nativeBrowserStore = new MemoryAcpSessionStore();
35569
35753
  #store;
35570
35754
  #nativeHistoryReader;
35571
35755
  #sessionIdentity;
@@ -35583,20 +35767,14 @@ var AcpSessionManager = class {
35583
35767
  const stored = this.#store.read(sessionId);
35584
35768
  return stored instanceof FoundAcpStoredSession && this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`);
35585
35769
  }
35586
- #retention(sessionId, kind) {
35587
- if (kind === "execution") {
35588
- return {
35589
- isBusy: () => this.#executions.isBusy(sessionId) || this.#sessions.isBusy(sessionId) || this.#isNativeSessionOperationActive(sessionId),
35590
- retire: (runtime) => this.#retireSessionProcess(sessionId, runtime, () => runtime.close())
35591
- };
35592
- }
35770
+ #retention(sessionId) {
35593
35771
  return {
35594
- isBusy: () => this.#nativeBrowserSessions.isBusy(sessionId),
35595
- retire: (runtime) => this.#retireNativeBrowserProcess(sessionId, runtime, () => runtime.close())
35772
+ isBusy: () => this.#executions.isBusy(sessionId) || this.#executionProcesses.isBusy(sessionId) || this.#isNativeSessionOperationActive(sessionId),
35773
+ retire: (runtime) => this.#retireSessionProcess(sessionId, runtime, () => runtime.close())
35596
35774
  };
35597
35775
  }
35598
35776
  async #retireSessionProcess(sessionId, runtime, close) {
35599
- const retained = this.#sessions.detach(sessionId, runtime);
35777
+ const retained = this.#executionProcesses.detach(sessionId, runtime);
35600
35778
  try {
35601
35779
  await this.#processes.retire(runtime, close);
35602
35780
  } finally {
@@ -35608,61 +35786,16 @@ var AcpSessionManager = class {
35608
35786
  }
35609
35787
  }
35610
35788
  }
35611
- async #retireNativeBrowserProcess(sessionId, runtime, close) {
35612
- const retained = this.#nativeBrowserSessions.detach(sessionId, runtime);
35613
- if (retained) {
35614
- this.#nativeBrowserStore.remove(sessionId);
35615
- }
35616
- await this.#processes.retire(runtime, close);
35617
- }
35618
35789
  async #startRetainedSessionProcess(options, start) {
35619
- const runtime = await this.#processes.startRetained(
35620
- options.signal,
35621
- start,
35622
- this.#retention(options.sessionId, "execution")
35623
- );
35624
- this.#sessions.retain(options.sessionId, runtime);
35625
- return runtime;
35626
- }
35627
- async #startRetainedNativeBrowserProcess(options, start) {
35628
- const runtime = await this.#processes.startRetained(
35629
- options.signal,
35630
- start,
35631
- this.#retention(options.sessionId, "browser")
35632
- );
35633
- this.#nativeBrowserSessions.retain(options.sessionId, runtime);
35790
+ const runtime = await this.#processes.startRetained(options.signal, start, this.#retention(options.sessionId));
35791
+ this.#executionProcesses.retain(options.sessionId, runtime);
35634
35792
  return runtime;
35635
35793
  }
35636
- async #startNativeBrowserPreparation(options) {
35637
- return await this.#nativeBrowserSessions.prepare(options.sessionId, async () => {
35638
- return await this.#startRetainedNativeBrowserProcess(
35639
- options,
35640
- async () => await AcpProcessSession.startNativeSessionBrowser(
35641
- options,
35642
- () => this.#nativeBrowserObserver,
35643
- this.#nativeBrowserStore
35644
- )
35645
- );
35646
- });
35647
- }
35648
- async #replaceNativeBrowserPreparation(existing, options) {
35649
- return await this.#nativeBrowserSessions.prepare(options.sessionId, async () => {
35650
- await this.#retireNativeBrowserProcess(options.sessionId, existing, async () => await existing.close());
35651
- return await this.#startRetainedNativeBrowserProcess(
35652
- options,
35653
- async () => await AcpProcessSession.startNativeSessionBrowser(
35654
- options,
35655
- () => this.#nativeBrowserObserver,
35656
- this.#nativeBrowserStore
35657
- )
35658
- );
35659
- });
35660
- }
35661
35794
  async #startPreparation(options, metrics = unmeasuredOperationMetrics) {
35662
- return await this.#sessions.prepare(options.sessionId, async () => {
35795
+ return await this.#executionProcesses.prepare(options.sessionId, async () => {
35663
35796
  return await this.#startRetainedSessionProcess(
35664
35797
  options,
35665
- async () => await AcpProcessSession.start(
35798
+ async () => await AgentSession.start(
35666
35799
  options.origin === void 0 && this.#sessionIdentity === "native" && isNativeChatSessionId(options.agent.id, options.sessionId) && this.#store.read(options.sessionId) instanceof MissingAcpStoredSession ? { ...options, origin: { kind: "import", nativeSessionId: options.sessionId } } : options,
35667
35800
  () => this.#observer,
35668
35801
  this.#store,
@@ -35672,7 +35805,7 @@ var AcpSessionManager = class {
35672
35805
  });
35673
35806
  }
35674
35807
  async #replacePreparation(existing, options, metrics) {
35675
- return await this.#sessions.prepare(options.sessionId, async () => {
35808
+ return await this.#executionProcesses.prepare(options.sessionId, async () => {
35676
35809
  await this.#retireSessionProcess(
35677
35810
  options.sessionId,
35678
35811
  existing,
@@ -35681,17 +35814,17 @@ var AcpSessionManager = class {
35681
35814
  this.#store.remove(options.sessionId);
35682
35815
  return await this.#startRetainedSessionProcess(
35683
35816
  options,
35684
- async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
35817
+ async () => await AgentSession.start(options, () => this.#observer, this.#store, metrics)
35685
35818
  );
35686
35819
  });
35687
35820
  }
35688
35821
  async #replaceExecutionPreparation(existing, options) {
35689
35822
  const desiredConfigOptions = existing.prepared().configOptions;
35690
- return await this.#sessions.prepare(options.sessionId, async () => {
35823
+ return await this.#executionProcesses.prepare(options.sessionId, async () => {
35691
35824
  await this.#retireSessionProcess(options.sessionId, existing, async () => await existing.close());
35692
35825
  const runtime = await this.#startRetainedSessionProcess(
35693
35826
  options,
35694
- async () => await AcpProcessSession.start(options, () => this.#observer, this.#store)
35827
+ async () => await AgentSession.start(options, () => this.#observer, this.#store)
35695
35828
  );
35696
35829
  try {
35697
35830
  for (const desired of desiredConfigOptions) {
@@ -35742,19 +35875,19 @@ var AcpSessionManager = class {
35742
35875
  if (stored instanceof FoundAcpStoredSession && this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`)) {
35743
35876
  throw new AcpExecutionError("The native session is being managed", {}, "session_busy");
35744
35877
  }
35745
- const pending = this.#sessions.pending(options.sessionId);
35878
+ const pending = this.#executionProcesses.pending(options.sessionId);
35746
35879
  if (pending !== void 0) {
35747
35880
  const runtime2 = await metrics.measure("session-preparation-wait", async () => await pending);
35748
35881
  if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35749
- this.#sessions.touch(options.sessionId, runtime2);
35882
+ this.#executionProcesses.touch(options.sessionId, runtime2);
35750
35883
  return runtime2.prepared();
35751
35884
  }
35752
35885
  return await this.prepareSession(options, metrics);
35753
35886
  }
35754
- const existing = this.#sessions.get(options.sessionId);
35887
+ const existing = this.#executionProcesses.get(options.sessionId);
35755
35888
  if (existing !== void 0) {
35756
35889
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35757
- this.#sessions.touch(options.sessionId, existing);
35890
+ this.#executionProcesses.touch(options.sessionId, existing);
35758
35891
  return existing.prepared();
35759
35892
  }
35760
35893
  if (!existing.canRebind()) {
@@ -35777,7 +35910,7 @@ var AcpSessionManager = class {
35777
35910
  */
35778
35911
  inspectAgentSettings = async (options) => await this.#processes.runTransient(
35779
35912
  options.signal,
35780
- async () => await AcpProcessSession.start(
35913
+ async () => await AgentSession.start(
35781
35914
  {
35782
35915
  ...options,
35783
35916
  sessionId: `agent-settings-${crypto.randomUUID()}`
@@ -35808,10 +35941,10 @@ var AcpSessionManager = class {
35808
35941
  * Use inspectAgentSettings for Agent-scoped settings discovery.
35809
35942
  */
35810
35943
  inspectSession = async (options, metrics = unmeasuredOperationMetrics) => {
35811
- if (this.#sessions.pending(options.sessionId) !== void 0 || this.#sessions.get(options.sessionId) !== void 0) {
35944
+ if (this.#executionProcesses.pending(options.sessionId) !== void 0 || this.#executionProcesses.get(options.sessionId) !== void 0) {
35812
35945
  throw new AcpExecutionError("The configuration inspection session is already in use", {}, "session_busy");
35813
35946
  }
35814
- return await this.#sessions.use(options.sessionId, async () => {
35947
+ return await this.#executionProcesses.use(options.sessionId, async () => {
35815
35948
  const runtime = await this.#startPreparation(options, metrics);
35816
35949
  try {
35817
35950
  return runtime.prepared();
@@ -35825,12 +35958,12 @@ var AcpSessionManager = class {
35825
35958
  });
35826
35959
  };
35827
35960
  prepareExecutionSession = async (options) => {
35828
- const pending = this.#sessions.pending(options.sessionId);
35961
+ const pending = this.#executionProcesses.pending(options.sessionId);
35829
35962
  if (pending !== void 0) {
35830
35963
  await pending;
35831
35964
  return await this.prepareExecutionSession(options);
35832
35965
  }
35833
- const existing = this.#sessions.get(options.sessionId);
35966
+ const existing = this.#executionProcesses.get(options.sessionId);
35834
35967
  if (existing === void 0) {
35835
35968
  return (await this.#startPreparation(options)).prepared();
35836
35969
  }
@@ -35842,7 +35975,7 @@ var AcpSessionManager = class {
35842
35975
  );
35843
35976
  }
35844
35977
  if (existing.usesEnvironment(options.agent.environment)) {
35845
- this.#sessions.touch(options.sessionId, existing);
35978
+ this.#executionProcesses.touch(options.sessionId, existing);
35846
35979
  return existing.prepared();
35847
35980
  }
35848
35981
  if (existing.hasRunningTurn()) {
@@ -35854,49 +35987,21 @@ var AcpSessionManager = class {
35854
35987
  }
35855
35988
  return (await this.#replaceExecutionPreparation(existing, options)).prepared();
35856
35989
  };
35857
- prepareNativeSessionBrowser = async (options) => {
35858
- const pending = this.#nativeBrowserSessions.pending(options.sessionId);
35859
- if (pending !== void 0) {
35860
- const runtime2 = await pending;
35861
- if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35862
- this.#nativeBrowserSessions.touch(options.sessionId, runtime2);
35863
- return runtime2.prepared();
35864
- }
35865
- return await this.prepareNativeSessionBrowser(options);
35866
- }
35867
- const existing = this.#nativeBrowserSessions.get(options.sessionId);
35868
- if (existing !== void 0) {
35869
- if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35870
- this.#nativeBrowserSessions.touch(options.sessionId, existing);
35871
- return existing.prepared();
35872
- }
35873
- if (!existing.canRebind()) {
35874
- throw new AcpExecutionError(
35875
- "The agent or workspace cannot change after a conversation has started",
35876
- {},
35877
- "session_identity_mismatch"
35878
- );
35879
- }
35880
- const runtime2 = await this.#replaceNativeBrowserPreparation(existing, options);
35881
- return runtime2.prepared();
35882
- }
35883
- const runtime = await this.#startNativeBrowserPreparation(options);
35884
- return runtime.prepared();
35885
- };
35990
+ prepareNativeSessionBrowser = (options) => this.#queryProcesses.prepare(options);
35886
35991
  configureSession = async (options) => {
35887
- return await this.#sessions.use(options.sessionId, async () => {
35992
+ return await this.#executionProcesses.use(options.sessionId, async () => {
35888
35993
  const runtime = await this.ensureSession(options);
35889
35994
  return await runtime.configure(options);
35890
35995
  });
35891
35996
  };
35892
35997
  cancelPrompt = async (sessionId) => {
35893
35998
  await this.#executions.cancel(sessionId, async () => {
35894
- const runtime = this.#sessions.get(sessionId);
35999
+ const runtime = this.#executionProcesses.get(sessionId);
35895
36000
  if (runtime !== void 0) {
35896
36001
  try {
35897
36002
  await runtime.cancel();
35898
36003
  } finally {
35899
- if (this.#sessions.detach(sessionId, runtime)) {
36004
+ if (this.#executionProcesses.detach(sessionId, runtime)) {
35900
36005
  this.#processes.releaseClosed(runtime);
35901
36006
  }
35902
36007
  }
@@ -35907,14 +36012,14 @@ var AcpSessionManager = class {
35907
36012
  if (this.#executions.command(options.sessionId) !== options.targetCommandId) {
35908
36013
  throw new AcpExecutionError("The target turn is no longer active", {}, "steering_target_unavailable");
35909
36014
  }
35910
- const pending = this.#sessions.pending(options.sessionId);
36015
+ const pending = this.#executionProcesses.pending(options.sessionId);
35911
36016
  if (pending !== void 0) {
35912
36017
  await pending;
35913
36018
  }
35914
36019
  if (this.#executions.command(options.sessionId) !== options.targetCommandId) {
35915
36020
  throw new AcpExecutionError("The target turn is no longer active", {}, "steering_target_unavailable");
35916
36021
  }
35917
- const runtime = this.#sessions.get(options.sessionId);
36022
+ const runtime = this.#executionProcesses.get(options.sessionId);
35918
36023
  if (runtime === void 0 || !runtime.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35919
36024
  throw new AcpExecutionError(
35920
36025
  "The target turn execution context is unavailable",
@@ -35972,7 +36077,7 @@ var AcpSessionManager = class {
35972
36077
  throw error62;
35973
36078
  }
35974
36079
  } catch (error62) {
35975
- const failedRuntime = this.#sessions.get(options.sessionId);
36080
+ const failedRuntime = this.#executionProcesses.get(options.sessionId);
35976
36081
  if (failedRuntime !== void 0) {
35977
36082
  await this.#retireSessionProcess(
35978
36083
  options.sessionId,
@@ -35994,35 +36099,32 @@ var AcpSessionManager = class {
35994
36099
  await this.#executions.cancellation(options.sessionId);
35995
36100
  } finally {
35996
36101
  this.#executions.finish(options.sessionId, options.commandId);
35997
- this.#sessions.touch(options.sessionId);
36102
+ this.#executionProcesses.touch(options.sessionId);
35998
36103
  this.#processes.notifyChanged();
35999
36104
  }
36000
36105
  }
36001
36106
  };
36002
36107
  respondPermission = async (options) => {
36003
- const runtime = this.#sessions.get(options.sessionId);
36108
+ const runtime = this.#executionProcesses.get(options.sessionId);
36004
36109
  if (runtime === void 0) {
36005
36110
  throw new AcpExecutionError("The permission request session is unavailable", {}, "session_not_found");
36006
36111
  }
36007
36112
  await runtime.respondPermission(options);
36008
36113
  };
36009
36114
  respondElicitation = async (options) => {
36010
- const runtime = this.#sessions.get(options.sessionId);
36115
+ const runtime = this.#executionProcesses.get(options.sessionId);
36011
36116
  if (runtime === void 0) {
36012
36117
  throw new AcpExecutionError("The elicitation request session is unavailable", {}, "session_not_found");
36013
36118
  }
36014
36119
  await runtime.respondElicitation(options);
36015
36120
  };
36016
36121
  close = async () => {
36017
- const sessions = [...this.#sessions.entries()];
36018
- const nativeBrowserSessions = [...this.#nativeBrowserSessions.entries()];
36122
+ const sessions = [...this.#executionProcesses.entries()];
36019
36123
  await Promise.all([
36020
36124
  ...sessions.map(
36021
36125
  async ([sessionId, runtime]) => await this.#retireSessionProcess(sessionId, runtime, async () => await runtime.close())
36022
36126
  ),
36023
- ...nativeBrowserSessions.map(
36024
- async ([sessionId, runtime]) => await this.#retireNativeBrowserProcess(sessionId, runtime, async () => await runtime.close())
36025
- )
36127
+ this.#queryProcesses.close()
36026
36128
  ]);
36027
36129
  };
36028
36130
  findSessions = (sessionIds) => sessionIds.flatMap((sessionId) => {
@@ -36030,17 +36132,17 @@ var AcpSessionManager = class {
36030
36132
  return stored instanceof FoundAcpStoredSession ? [stored.session] : [];
36031
36133
  });
36032
36134
  findLinkedSessions = (agentId, nativeSessionId) => this.#store.findNative(agentId, nativeSessionId);
36033
- hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
36135
+ hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#executionProcesses.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
36034
36136
  createNativeSession = async (options) => {
36035
36137
  const temporarySessionId = `new-${crypto.randomUUID()}`;
36036
36138
  const temporaryOptions = { ...options, sessionId: temporarySessionId };
36037
- return await this.#sessions.use(temporarySessionId, async () => {
36139
+ return await this.#executionProcesses.use(temporarySessionId, async () => {
36038
36140
  try {
36039
36141
  const runtime = await this.#startPreparation(temporaryOptions);
36040
36142
  let adopted = false;
36041
36143
  try {
36042
36144
  const nativeSessionId = runtime.nativeSessionId();
36043
- if (!isNativeChatSessionId(options.agent.id, nativeSessionId) || this.#sessions.get(nativeSessionId) !== void 0 || !(this.#store.read(nativeSessionId) instanceof MissingAcpStoredSession)) {
36145
+ if (!isNativeChatSessionId(options.agent.id, nativeSessionId) || this.#executionProcesses.get(nativeSessionId) !== void 0 || !(this.#store.read(nativeSessionId) instanceof MissingAcpStoredSession)) {
36044
36146
  throw new AcpExecutionError(
36045
36147
  "The Agent returned an invalid new Session ID",
36046
36148
  {},
@@ -36048,9 +36150,9 @@ var AcpSessionManager = class {
36048
36150
  );
36049
36151
  }
36050
36152
  runtime.adoptNativeSessionId(nativeSessionId);
36051
- this.#sessions.detach(temporarySessionId, runtime);
36052
- this.#sessions.retain(nativeSessionId, runtime);
36053
- this.#processes.retain(runtime, this.#retention(nativeSessionId, "execution"));
36153
+ this.#executionProcesses.detach(temporarySessionId, runtime);
36154
+ this.#executionProcesses.retain(nativeSessionId, runtime);
36155
+ this.#processes.retain(runtime, this.#retention(nativeSessionId));
36054
36156
  adopted = true;
36055
36157
  return nativeSessionId;
36056
36158
  } finally {
@@ -36068,7 +36170,7 @@ var AcpSessionManager = class {
36068
36170
  });
36069
36171
  };
36070
36172
  ensureSession = async (options) => {
36071
- const existing = this.#sessions.get(options.sessionId);
36173
+ const existing = this.#executionProcesses.get(options.sessionId);
36072
36174
  if (existing !== void 0) {
36073
36175
  if (!existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
36074
36176
  throw new AcpExecutionError(
@@ -36077,46 +36179,27 @@ var AcpSessionManager = class {
36077
36179
  "session_identity_mismatch"
36078
36180
  );
36079
36181
  }
36080
- this.#sessions.touch(options.sessionId, existing);
36182
+ this.#executionProcesses.touch(options.sessionId, existing);
36081
36183
  return existing;
36082
36184
  }
36083
36185
  await this.prepareSession(options);
36084
- const started = this.#sessions.get(options.sessionId);
36186
+ const started = this.#executionProcesses.get(options.sessionId);
36085
36187
  if (started === void 0) {
36086
36188
  throw new AcpExecutionError("ACP session did not start");
36087
36189
  }
36088
36190
  return started;
36089
36191
  };
36090
- async #ensureNativeSessionBrowser(options) {
36091
- const existing = this.#nativeBrowserSessions.get(options.sessionId);
36092
- if (existing !== void 0) {
36093
- if (!existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
36094
- throw new AcpExecutionError(
36095
- "The agent or workspace cannot change after a conversation has started",
36096
- {},
36097
- "session_identity_mismatch"
36098
- );
36099
- }
36100
- this.#nativeBrowserSessions.touch(options.sessionId, existing);
36101
- return existing;
36102
- }
36103
- await this.prepareNativeSessionBrowser(options);
36104
- const started = this.#nativeBrowserSessions.get(options.sessionId);
36105
- if (started === void 0) {
36106
- throw new AcpExecutionError("ACP native session browser did not start");
36107
- }
36108
- return started;
36109
- }
36110
36192
  listNativeSessions = async (options, cursor) => {
36111
- return await this.#nativeBrowserSessions.use(options.sessionId, async () => {
36112
- return await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(cursor, options.signal);
36113
- });
36193
+ return await this.#queryProcesses.use(
36194
+ options,
36195
+ async (runtime) => await runtime.listNativeSessions(cursor, options.signal)
36196
+ );
36114
36197
  };
36115
36198
  previewNativeSession = async (options, nativeSessionId) => {
36116
36199
  const key = `${options.agent.id}:${nativeSessionId}`;
36117
36200
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
36118
36201
  if (this.#nativeOperations.has(key) || linked.some(
36119
- (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#sessions.pending(entry.sessionId) !== void 0
36202
+ (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#executionProcesses.pending(entry.sessionId) !== void 0
36120
36203
  )) {
36121
36204
  throw new AcpExecutionError(
36122
36205
  "Wait for the native session's running operation to finish",
@@ -36126,25 +36209,13 @@ var AcpSessionManager = class {
36126
36209
  }
36127
36210
  this.#nativeOperations.add(key);
36128
36211
  try {
36129
- return await this.#processes.runTransient(
36130
- options.signal,
36131
- async () => await AcpProcessSession.startNativeSessionBrowser(
36132
- options,
36133
- () => this.#nativeBrowserObserver,
36134
- new MemoryAcpSessionStore()
36135
- ),
36136
- async (runtime) => {
36137
- runtime.selectNativeSession(nativeSessionId);
36138
- return await runtime.loadHistory(options.signal);
36139
- },
36140
- async (runtime) => await runtime.closeProcess()
36141
- );
36212
+ return await this.#queryProcesses.preview(options, nativeSessionId);
36142
36213
  } finally {
36143
36214
  this.#nativeOperations.delete(key);
36144
36215
  }
36145
36216
  };
36146
36217
  loadSessionHistory = async (options) => {
36147
- return await this.#sessions.use(options.sessionId, async () => {
36218
+ return await this.#executionProcesses.use(options.sessionId, async () => {
36148
36219
  const runtime = await this.ensureSession(options);
36149
36220
  const stored = this.#store.read(options.sessionId);
36150
36221
  if (stored instanceof FoundAcpStoredSession && this.#nativeHistoryReader !== null) {
@@ -36167,7 +36238,7 @@ var AcpSessionManager = class {
36167
36238
  }
36168
36239
  const linked = this.#store.findNative(options.agent.id, origin.nativeSessionId);
36169
36240
  if (linked.some(
36170
- (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#sessions.pending(entry.sessionId) !== void 0
36241
+ (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#executionProcesses.pending(entry.sessionId) !== void 0
36171
36242
  )) {
36172
36243
  throw new AcpExecutionError(
36173
36244
  "Wait for the native session's running operation to finish",
@@ -36177,7 +36248,7 @@ var AcpSessionManager = class {
36177
36248
  }
36178
36249
  const existing = linked[0];
36179
36250
  if (origin.kind === "import" && existing !== void 0) {
36180
- return await this.#sessions.use(existing.sessionId, async () => {
36251
+ return await this.#executionProcesses.use(existing.sessionId, async () => {
36181
36252
  const runtime = await this.ensureSession({
36182
36253
  ...options,
36183
36254
  sessionId: existing.sessionId
@@ -36201,10 +36272,10 @@ var AcpSessionManager = class {
36201
36272
  }
36202
36273
  });
36203
36274
  }
36204
- if (this.#sessions.get(options.sessionId) !== void 0 || this.#sessions.pending(options.sessionId) !== void 0 || this.#store.read(options.sessionId) instanceof FoundAcpStoredSession || this.#store.read(options.sessionId) instanceof DeletedAcpStoredSession) {
36275
+ if (this.#executionProcesses.get(options.sessionId) !== void 0 || this.#executionProcesses.pending(options.sessionId) !== void 0 || this.#store.read(options.sessionId) instanceof FoundAcpStoredSession || this.#store.read(options.sessionId) instanceof DeletedAcpStoredSession) {
36205
36276
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
36206
36277
  }
36207
- return await this.#sessions.use(options.sessionId, async () => {
36278
+ return await this.#executionProcesses.use(options.sessionId, async () => {
36208
36279
  this.#nativeOperations.add(key);
36209
36280
  try {
36210
36281
  const runtime = await this.#startPreparation({ ...options, origin });
@@ -36221,7 +36292,7 @@ var AcpSessionManager = class {
36221
36292
  }
36222
36293
  } catch (error62) {
36223
36294
  this.#store.remove(options.sessionId);
36224
- const runtime = this.#sessions.get(options.sessionId);
36295
+ const runtime = this.#executionProcesses.get(options.sessionId);
36225
36296
  if (runtime !== void 0) {
36226
36297
  await this.#retireSessionProcess(
36227
36298
  options.sessionId,
@@ -36236,12 +36307,11 @@ var AcpSessionManager = class {
36236
36307
  });
36237
36308
  };
36238
36309
  deleteNativeSession = async (options, nativeSessionId) => {
36239
- return await this.#nativeBrowserSessions.use(options.sessionId, async () => {
36240
- const runtime = await this.#ensureNativeSessionBrowser(options);
36310
+ return await this.#queryProcesses.use(options, async (runtime) => {
36241
36311
  const key = `${options.agent.id}:${nativeSessionId}`;
36242
36312
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
36243
36313
  if (this.#nativeOperations.has(key) || linked.some(
36244
- (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#sessions.pending(entry.sessionId) !== void 0
36314
+ (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#executionProcesses.pending(entry.sessionId) !== void 0
36245
36315
  )) {
36246
36316
  throw new AcpExecutionError(
36247
36317
  "Wait for the native session's running operation to finish",
@@ -36252,7 +36322,7 @@ var AcpSessionManager = class {
36252
36322
  this.#nativeOperations.add(key);
36253
36323
  try {
36254
36324
  for (const entry of linked) {
36255
- const active = this.#sessions.get(entry.sessionId);
36325
+ const active = this.#executionProcesses.get(entry.sessionId);
36256
36326
  if (active !== void 0 && active !== runtime) {
36257
36327
  await this.#retireSessionProcess(entry.sessionId, active, async () => await active.close());
36258
36328
  }
@@ -36261,11 +36331,7 @@ var AcpSessionManager = class {
36261
36331
  await runtime.deleteNativeSession(nativeSessionId, options.signal);
36262
36332
  const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
36263
36333
  if (runtime.nativeSessionId() === nativeSessionId) {
36264
- await this.#retireNativeBrowserProcess(
36265
- options.sessionId,
36266
- runtime,
36267
- async () => await runtime.close()
36268
- );
36334
+ await this.#queryProcesses.retire(options.sessionId, runtime);
36269
36335
  }
36270
36336
  return deleted;
36271
36337
  } finally {
@@ -41686,7 +41752,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
41686
41752
  activeTurns.recordEvent(event);
41687
41753
  publisher.publish(sessionId, event);
41688
41754
  };
41689
- const sessions = new AcpSessionManager(
41755
+ const agentRuntime = new AgentRuntimeManager(
41690
41756
  new DaemonAcpObserver(recordSessionEvent),
41691
41757
  sessionStore,
41692
41758
  {
@@ -41708,20 +41774,28 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
41708
41774
  config2.relayUrl,
41709
41775
  new DaemonDiagnosticLog(stateDirectory)
41710
41776
  );
41711
- const nativeSessions = new NativeSessionService(config2, directories, sessions, audit, async (request, options2) => {
41712
- return await activeTurns.executionSnapshot(async (command) => {
41713
- if (command.sessionId !== request.targetSessionId || command.agentId !== request.agentId) {
41714
- return false;
41715
- }
41716
- const cwd = await directories.resolve(command.bindingId, command.directoryId, options2.signal);
41717
- const additionalDirectories = await directories.resolveMany(
41718
- command.bindingId,
41719
- command.additionalDirectoryIds,
41720
- options2.signal
41721
- );
41722
- return cwd === options2.cwd && additionalDirectories.length === options2.additionalDirectories.length && additionalDirectories.every((directory, index) => directory === options2.additionalDirectories[index]);
41723
- });
41724
- });
41777
+ const nativeSessions = new NativeSessionService(
41778
+ config2,
41779
+ directories,
41780
+ agentRuntime,
41781
+ audit,
41782
+ async (request, options2) => {
41783
+ return await activeTurns.executionSnapshot(async (command) => {
41784
+ if (command.sessionId !== request.targetSessionId || command.agentId !== request.agentId) {
41785
+ return false;
41786
+ }
41787
+ const cwd = await directories.resolve(command.bindingId, command.directoryId, options2.signal);
41788
+ const additionalDirectories = await directories.resolveMany(
41789
+ command.bindingId,
41790
+ command.additionalDirectoryIds,
41791
+ options2.signal
41792
+ );
41793
+ return cwd === options2.cwd && additionalDirectories.length === options2.additionalDirectories.length && additionalDirectories.every(
41794
+ (directory, index) => directory === options2.additionalDirectories[index]
41795
+ );
41796
+ });
41797
+ }
41798
+ );
41725
41799
  const installations = new AgentInstallationManager(
41726
41800
  specifications,
41727
41801
  installationExecutor,
@@ -41797,7 +41871,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
41797
41871
  config: config2,
41798
41872
  directories,
41799
41873
  audit,
41800
- sessions,
41874
+ sessions: agentRuntime,
41801
41875
  installations,
41802
41876
  installationObserver,
41803
41877
  nativeSessions,
@@ -41840,7 +41914,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
41840
41914
  await installations.close();
41841
41915
  } finally {
41842
41916
  try {
41843
- await sessions.close();
41917
+ await agentRuntime.close();
41844
41918
  } finally {
41845
41919
  try {
41846
41920
  sessionStore.close();