@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/cli.js CHANGED
@@ -3381,7 +3381,7 @@ var program = new Command();
3381
3381
  // package.json
3382
3382
  var package_default = {
3383
3383
  name: "@moxt-ai/mobius",
3384
- version: "0.0.126",
3384
+ version: "0.0.128",
3385
3385
  description: "Mobius CLI for pairing and running local AI agent services.",
3386
3386
  type: "module",
3387
3387
  bin: {
@@ -25118,6 +25118,7 @@ var COLLABORATION_MODE_SETTING_ID = "collaboration_mode";
25118
25118
  var MODEL_CATALOG_LIMIT = 1e3;
25119
25119
  var FAST_TIER = "fast";
25120
25120
  var SERVICE_TIER_FAST = "priority";
25121
+ var CODEX_COMMANDS = Object.freeze([{ description: "Compact the conversation context", name: "compact" }]);
25121
25122
  var WORKSPACE_WRITE_POLICY = Object.freeze({
25122
25123
  excludeSlashTmp: false,
25123
25124
  excludeTmpdirEnvVar: false,
@@ -25198,6 +25199,9 @@ function promptInput(prompt) {
25198
25199
  }
25199
25200
  return input2;
25200
25201
  }
25202
+ function isCompactPrompt(prompt) {
25203
+ return prompt.length === 1 && prompt[0]?.type === "text" && prompt[0].text.trim() === "/compact";
25204
+ }
25201
25205
  function steeringPromptInput(prompt) {
25202
25206
  const input2 = [];
25203
25207
  for (const block of prompt) {
@@ -25452,6 +25456,7 @@ var CodexAcpAgent = class {
25452
25456
  };
25453
25457
  this.#collaborationModeSelected = false;
25454
25458
  await this.#probeCollaborationMode(context.signal);
25459
+ await this.#emitAvailableCommands();
25455
25460
  return { configOptions: this.#configOptions(), sessionId: created.thread.id };
25456
25461
  }).onRequest(methods.agent.session.setConfigOption, async (context) => {
25457
25462
  this.#applySelection(context.params.configId, context.params.value);
@@ -25470,6 +25475,7 @@ var CodexAcpAgent = class {
25470
25475
  this.#selectRestoredThread(resumed);
25471
25476
  await this.#probeCollaborationMode(context.signal);
25472
25477
  await this.#replayHistory(resumed.turns);
25478
+ await this.#emitAvailableCommands();
25473
25479
  return { configOptions: this.#configOptions() };
25474
25480
  }).onRequest(methods.agent.session.fork, async (context) => {
25475
25481
  const forked = threadForkResponseSchema.parse(
@@ -25486,6 +25492,7 @@ var CodexAcpAgent = class {
25486
25492
  this.#selectRestoredThread(forked);
25487
25493
  await this.#probeCollaborationMode(context.signal);
25488
25494
  await this.#replayHistory(forked.turns);
25495
+ await this.#emitAvailableCommands();
25489
25496
  return { configOptions: this.#configOptions(), sessionId: forked.thread.id };
25490
25497
  }).onRequest(methods.agent.session.resume, async (context) => {
25491
25498
  const resumed = threadResumeResponseSchema.parse(
@@ -25497,8 +25504,12 @@ var CodexAcpAgent = class {
25497
25504
  );
25498
25505
  this.#selectRestoredThread(resumed);
25499
25506
  await this.#probeCollaborationMode(context.signal);
25507
+ await this.#emitAvailableCommands();
25500
25508
  return { configOptions: this.#configOptions() };
25501
25509
  }).onRequest(methods.agent.session.prompt, async (context) => {
25510
+ if (isCompactPrompt(context.params.prompt)) {
25511
+ return await this.#compact(context.signal);
25512
+ }
25502
25513
  return await this.#runTurn(promptInput(context.params.prompt), context.signal);
25503
25514
  }).onRequest(
25504
25515
  "_session/steering",
@@ -25778,6 +25789,12 @@ var CodexAcpAgent = class {
25778
25789
  update
25779
25790
  });
25780
25791
  };
25792
+ #emitAvailableCommands = async () => {
25793
+ await this.#emit({
25794
+ availableCommands: CODEX_COMMANDS.map((command) => ({ ...command })),
25795
+ sessionUpdate: "available_commands_update"
25796
+ });
25797
+ };
25781
25798
  /** Pushes the current settings so a mode change Codex applied reaches the Run settings panel. */
25782
25799
  #emitConfigOptionsUpdate = async () => {
25783
25800
  const connection = this.#connection;
@@ -26088,6 +26105,35 @@ var CodexAcpAgent = class {
26088
26105
  }
26089
26106
  }
26090
26107
  };
26108
+ #compact = async (signal) => {
26109
+ signal.throwIfAborted();
26110
+ if (this.#turn !== null) {
26111
+ throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
26112
+ }
26113
+ const completion = Promise.withResolvers();
26114
+ void completion.promise.catch(() => {
26115
+ });
26116
+ const aborted2 = () => {
26117
+ completion.reject(signal.reason);
26118
+ void this.close().catch((cause) => {
26119
+ console.error("The cancelled Codex endpoint could not release its process tree", cause);
26120
+ });
26121
+ };
26122
+ signal.addEventListener("abort", aborted2, { once: true });
26123
+ const turn = { completion, turn: { id: "" } };
26124
+ this.#streamedReasoningItemIds.clear();
26125
+ this.#turn = turn;
26126
+ try {
26127
+ await this.#appServer.request("thread/compact/start", { threadId: this.#nativeSessionId }, signal);
26128
+ return await completion.promise;
26129
+ } finally {
26130
+ signal.removeEventListener("abort", aborted2);
26131
+ if (this.#turn === turn) {
26132
+ this.#turn = null;
26133
+ this.#streamedReasoningItemIds.clear();
26134
+ }
26135
+ }
26136
+ };
26091
26137
  #steerTurn = async (params, signal) => {
26092
26138
  if (typeof params !== "object" || params === null) {
26093
26139
  throw new AcpExecutionError("Codex received an invalid steering request", {}, "invalid_request");
@@ -30732,7 +30778,88 @@ import { createHash as createHash6, randomUUID as randomUUID7 } from "node:crypt
30732
30778
  import { join as join18 } from "node:path";
30733
30779
  import { styleText } from "node:util";
30734
30780
 
30735
- // src/acp/process-session.ts
30781
+ // src/acp/active-executions.ts
30782
+ var unreachable = (state) => {
30783
+ throw new AcpExecutionError("Unexpected execution state", { cause: state });
30784
+ };
30785
+ var ActiveExecutions = class {
30786
+ #entries = /* @__PURE__ */ new Map();
30787
+ command = (id) => {
30788
+ const state = this.#entries.get(id);
30789
+ switch (state?.kind) {
30790
+ case "running":
30791
+ case "cancelling":
30792
+ return state.commandId;
30793
+ case "cancelled-before-start":
30794
+ case void 0:
30795
+ return void 0;
30796
+ default:
30797
+ return unreachable(state);
30798
+ }
30799
+ };
30800
+ cancellation = (id) => {
30801
+ const state = this.#entries.get(id);
30802
+ switch (state?.kind) {
30803
+ case "cancelling":
30804
+ case "cancelled-before-start":
30805
+ return state.completion;
30806
+ case "running":
30807
+ case void 0:
30808
+ return void 0;
30809
+ default:
30810
+ return unreachable(state);
30811
+ }
30812
+ };
30813
+ isBusy = (id) => this.#entries.has(id);
30814
+ begin = (id, commandId) => {
30815
+ const state = this.#entries.get(id);
30816
+ switch (state?.kind) {
30817
+ case "running":
30818
+ case "cancelling":
30819
+ throw new AcpExecutionError(
30820
+ "Another prompt is already running in this conversation",
30821
+ {},
30822
+ "session_busy"
30823
+ );
30824
+ case "cancelled-before-start":
30825
+ case void 0:
30826
+ break;
30827
+ default:
30828
+ unreachable(state);
30829
+ }
30830
+ this.#entries.set(
30831
+ id,
30832
+ state?.kind === "cancelled-before-start" ? { kind: "cancelling", commandId, completion: state.completion } : { kind: "running", commandId }
30833
+ );
30834
+ };
30835
+ cancel = (id, stop) => {
30836
+ const state = this.#entries.get(id);
30837
+ switch (state?.kind) {
30838
+ case "cancelling":
30839
+ case "cancelled-before-start":
30840
+ return state.completion;
30841
+ case "running":
30842
+ case void 0:
30843
+ break;
30844
+ default:
30845
+ return unreachable(state);
30846
+ }
30847
+ const completion = Promise.withResolvers();
30848
+ this.#entries.set(
30849
+ id,
30850
+ state?.kind === "running" ? { kind: "cancelling", commandId: state.commandId, completion: completion.promise } : { kind: "cancelled-before-start", completion: completion.promise }
30851
+ );
30852
+ void (async () => await stop())().then(completion.resolve, completion.reject);
30853
+ return completion.promise;
30854
+ };
30855
+ finish = (id, commandId) => {
30856
+ if (this.command(id) === commandId) {
30857
+ this.#entries.delete(id);
30858
+ }
30859
+ };
30860
+ };
30861
+
30862
+ // src/acp/agent-session.ts
30736
30863
  import {
30737
30864
  methods as methods8,
30738
30865
  PROTOCOL_VERSION as PROTOCOL_VERSION3
@@ -31630,23 +31757,7 @@ var AcpActivityTracker = class {
31630
31757
  };
31631
31758
  };
31632
31759
 
31633
- // src/acp/native-session.ts
31634
- var path2 = external_exports.string().min(1).max(2048).refine((value) => !value.includes("\0"));
31635
- var title = external_exports.string().transform((value) => value.slice(0, 500));
31636
- var nativeSessionIdSchema = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/);
31637
- var nativeSessionInfoSchema = external_exports.object({
31638
- sessionId: nativeSessionIdSchema,
31639
- cwd: path2,
31640
- additionalDirectories: external_exports.array(path2).max(16).default([]).readonly(),
31641
- title: title.nullish(),
31642
- updatedAt: external_exports.iso.datetime({ offset: true }).nullish()
31643
- }).readonly();
31644
- var nativeSessionPageSchema = external_exports.object({
31645
- sessions: external_exports.array(nativeSessionInfoSchema).max(500).readonly(),
31646
- nextCursor: external_exports.string().min(1).max(4096).nullish()
31647
- }).readonly();
31648
-
31649
- // src/acp/process-endpoint.ts
31760
+ // src/acp/agent-connection.ts
31650
31761
  import { spawn as spawn4 } from "node:child_process";
31651
31762
  import { ndJsonStream as ndJsonStream2, RequestError as RequestError3 } from "@agentclientprotocol/sdk";
31652
31763
 
@@ -31661,7 +31772,7 @@ function readString2(value, fallback = "") {
31661
31772
  return typeof value === "string" ? value : fallback;
31662
31773
  }
31663
31774
 
31664
- // src/acp/process-endpoint.ts
31775
+ // src/acp/agent-connection.ts
31665
31776
  function readableWebStream(input2) {
31666
31777
  let streamOpen = true;
31667
31778
  return new ReadableStream({
@@ -31737,7 +31848,7 @@ function createWritableAcpStream(output2) {
31737
31848
  }
31738
31849
  });
31739
31850
  }
31740
- var AcpEndpoint = class {
31851
+ var AgentConnection = class {
31741
31852
  connection;
31742
31853
  termination;
31743
31854
  #process;
@@ -31844,6 +31955,86 @@ var AcpEndpoint = class {
31844
31955
  };
31845
31956
  };
31846
31957
 
31958
+ // src/acp/native-session.ts
31959
+ var path2 = external_exports.string().min(1).max(2048).refine((value) => !value.includes("\0"));
31960
+ var title = external_exports.string().transform((value) => value.slice(0, 500));
31961
+ var nativeSessionIdSchema = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/);
31962
+ var nativeSessionInfoSchema = external_exports.object({
31963
+ sessionId: nativeSessionIdSchema,
31964
+ cwd: path2,
31965
+ additionalDirectories: external_exports.array(path2).max(16).default([]).readonly(),
31966
+ title: title.nullish(),
31967
+ updatedAt: external_exports.iso.datetime({ offset: true }).nullish()
31968
+ }).readonly();
31969
+ var nativeSessionPageSchema = external_exports.object({
31970
+ sessions: external_exports.array(nativeSessionInfoSchema).max(500).readonly(),
31971
+ nextCursor: external_exports.string().min(1).max(4096).nullish()
31972
+ }).readonly();
31973
+
31974
+ // src/acp/agent-update-stream.ts
31975
+ var MAX_PENDING_UPDATES = 100;
31976
+ var MAX_PENDING_BYTES = 1024 * 1024;
31977
+ var AgentUpdateStream = class {
31978
+ #selection = { kind: "awaiting-session", notifications: [], bytes: 0 };
31979
+ #tail = Promise.resolve();
31980
+ #consume;
31981
+ constructor(consume) {
31982
+ this.#consume = consume;
31983
+ }
31984
+ sessionId = () => this.#selection.kind === "selected" ? this.#selection.sessionId : "";
31985
+ drained = () => this.#tail;
31986
+ #enqueue = (notification) => {
31987
+ this.#tail = this.#tail.then(async () => await this.#consume(notification));
31988
+ return this.#tail;
31989
+ };
31990
+ receive = (notification) => {
31991
+ const selection = this.#selection;
31992
+ switch (selection.kind) {
31993
+ case "selected":
31994
+ return this.#enqueue(notification);
31995
+ case "awaiting-session": {
31996
+ const bytes = selection.bytes + Buffer.byteLength(JSON.stringify(notification));
31997
+ if (selection.notifications.length >= MAX_PENDING_UPDATES || bytes > MAX_PENDING_BYTES) {
31998
+ return Promise.reject(
31999
+ new AcpExecutionError(
32000
+ "ACP agent sent too many updates before creating its session",
32001
+ {},
32002
+ "agent_update_limit"
32003
+ )
32004
+ );
32005
+ }
32006
+ this.#selection = {
32007
+ kind: "awaiting-session",
32008
+ notifications: [...selection.notifications, notification],
32009
+ bytes
32010
+ };
32011
+ return Promise.resolve();
32012
+ }
32013
+ }
32014
+ };
32015
+ select = (sessionId) => {
32016
+ const selected = nativeSessionIdSchema.parse(sessionId);
32017
+ const selection = this.#selection;
32018
+ switch (selection.kind) {
32019
+ case "selected":
32020
+ if (selection.sessionId !== selected) {
32021
+ throw new AcpExecutionError(
32022
+ "ACP agent attempted to replace the selected session",
32023
+ {},
32024
+ "invalid_agent_session"
32025
+ );
32026
+ }
32027
+ return;
32028
+ case "awaiting-session":
32029
+ this.#selection = { kind: "selected", sessionId: selected };
32030
+ for (const notification of selection.notifications) {
32031
+ void this.#enqueue(notification);
32032
+ }
32033
+ return;
32034
+ }
32035
+ };
32036
+ };
32037
+
31847
32038
  // src/acp/session-config/session-config-protocol.ts
31848
32039
  import { methods as methods7 } from "@agentclientprotocol/sdk";
31849
32040
  var MAXIMUM_CONFIG_OPTIONS = 100;
@@ -38462,10 +38653,8 @@ var SqliteAcpSessionStore = class {
38462
38653
  };
38463
38654
  };
38464
38655
 
38465
- // src/acp/process-session.ts
38656
+ // src/acp/agent-session.ts
38466
38657
  var PROCESS_STOP_TIMEOUT_MILLISECONDS = 1e3;
38467
- var MAX_PRE_SESSION_UPDATES = 100;
38468
- var MAX_PRE_SESSION_UPDATE_BYTES = 1024 * 1024;
38469
38658
  var RetryableAcpInitializationError = class extends AcpExecutionError {
38470
38659
  constructor(cause) {
38471
38660
  super("ACP agent initialization failed", { cause });
@@ -38480,8 +38669,8 @@ function recordsEqual(left, right) {
38480
38669
  const rightEntries = Object.entries(right);
38481
38670
  return leftEntries.length === rightEntries.length && leftEntries.every(([name, value]) => right[name] === value);
38482
38671
  }
38483
- var AcpProcessSession = class _AcpProcessSession {
38484
- #endpoint;
38672
+ var AgentSession = class _AgentSession {
38673
+ #connection;
38485
38674
  #interactions;
38486
38675
  #additionalDirectories;
38487
38676
  #agentId;
@@ -38489,12 +38678,11 @@ var AcpProcessSession = class _AcpProcessSession {
38489
38678
  #environment;
38490
38679
  #getObserver;
38491
38680
  #mobiusSessionId;
38492
- #preSessionUpdates = [];
38681
+ #updates;
38493
38682
  #metrics;
38494
38683
  #sessionConfigProtocol;
38495
38684
  #store;
38496
38685
  #verifiedAgentVersion;
38497
- #preSessionUpdateBytes = 0;
38498
38686
  #agentName = "";
38499
38687
  #agentVersion = "";
38500
38688
  #bufferedAgentText = [];
@@ -38502,7 +38690,6 @@ var AcpProcessSession = class _AcpProcessSession {
38502
38690
  #commands = [];
38503
38691
  #configRevision = 0;
38504
38692
  #configOptions = [];
38505
- #nativeSessionId = "";
38506
38693
  #prompted = false;
38507
38694
  #nativePrompt = null;
38508
38695
  #replay = {
@@ -38512,10 +38699,11 @@ var AcpProcessSession = class _AcpProcessSession {
38512
38699
  #sessionTitle = null;
38513
38700
  #sessionUpdatedAt = "";
38514
38701
  #turn = new IdleAcpTurn();
38515
- #updateTail = Promise.resolve();
38516
38702
  constructor(agent, cwd, additionalDirectories, mobiusSessionId, getObserver, store, metrics) {
38703
+ this.#updates = new AgentUpdateStream((notification) => this.#processUpdate(notification));
38517
38704
  this.#additionalDirectories = [...additionalDirectories];
38518
38705
  this.#agentId = agent.id;
38706
+ this.#commands = [];
38519
38707
  this.#cwd = cwd;
38520
38708
  this.#environment = agent.environment;
38521
38709
  this.#getObserver = getObserver;
@@ -38530,7 +38718,7 @@ var AcpProcessSession = class _AcpProcessSession {
38530
38718
  assertNativeSession: (sessionId) => this.assertNativeSession(sessionId),
38531
38719
  observer: getObserver
38532
38720
  });
38533
- this.#endpoint = new AcpEndpoint(agent, cwd, this);
38721
+ this.#connection = new AgentConnection(agent, cwd, this);
38534
38722
  }
38535
38723
  static async #start(options, getObserver, store, initialize, metrics) {
38536
38724
  for (let attempt = 1; attempt <= 2; attempt += 1) {
@@ -38553,7 +38741,7 @@ var AcpProcessSession = class _AcpProcessSession {
38553
38741
  }
38554
38742
  const runtime = metrics.measureSync(
38555
38743
  "process-spawn",
38556
- () => new _AcpProcessSession(
38744
+ () => new _AgentSession(
38557
38745
  options.agent,
38558
38746
  options.cwd,
38559
38747
  options.additionalDirectories,
@@ -38583,14 +38771,14 @@ var AcpProcessSession = class _AcpProcessSession {
38583
38771
  }
38584
38772
  throw new AcpExecutionError("ACP agent initialization failed");
38585
38773
  }
38586
- static start = async (options, getObserver, store, metrics = unmeasuredOperationMetrics) => await _AcpProcessSession.#start(
38774
+ static start = async (options, getObserver, store, metrics = unmeasuredOperationMetrics) => await _AgentSession.#start(
38587
38775
  options,
38588
38776
  getObserver,
38589
38777
  store,
38590
38778
  async (runtime) => await runtime.initialize(options.signal, options.origin),
38591
38779
  metrics
38592
38780
  );
38593
- static startNativeSessionBrowser = async (options, getObserver, store) => await _AcpProcessSession.#start(
38781
+ static startNativeSessionBrowser = async (options, getObserver, store) => await _AgentSession.#start(
38594
38782
  options,
38595
38783
  getObserver,
38596
38784
  store,
@@ -38623,20 +38811,20 @@ var AcpProcessSession = class _AcpProcessSession {
38623
38811
  this.#replay = { kind: "capture", history };
38624
38812
  try {
38625
38813
  await this.race(
38626
- this.#endpoint.connection.agent.request(
38814
+ this.#connection.connection.agent.request(
38627
38815
  methods8.agent.session.load,
38628
38816
  {
38629
38817
  additionalDirectories: [...this.#additionalDirectories],
38630
38818
  cwd: this.#cwd,
38631
38819
  mcpServers: [],
38632
- sessionId: this.#nativeSessionId
38820
+ sessionId: this.#updates.sessionId()
38633
38821
  },
38634
38822
  { cancellationSignal: signal }
38635
38823
  ),
38636
38824
  "ACP agent exited while loading history",
38637
38825
  signal
38638
38826
  );
38639
- await this.#updateTail;
38827
+ await this.#updates.drained();
38640
38828
  signal.throwIfAborted();
38641
38829
  return await embedLocalHistoryImages(await history.snapshot(), signal);
38642
38830
  } finally {
@@ -38732,9 +38920,9 @@ var AcpProcessSession = class _AcpProcessSession {
38732
38920
  await this.#metrics.measure("agent-initialize", async () => await this.#initializeAgentOperation(signal));
38733
38921
  }
38734
38922
  async #initializeAgentOperation(signal) {
38735
- if (this.#endpoint.inProcessAgent !== null) {
38923
+ if (this.#connection.inProcessAgent !== null) {
38736
38924
  await this.race(
38737
- this.#endpoint.inProcessAgent.initialize(signal),
38925
+ this.#connection.inProcessAgent.initialize(signal),
38738
38926
  "The Codex app-server exited during initialization",
38739
38927
  signal
38740
38928
  ).catch((cause) => {
@@ -38743,7 +38931,7 @@ var AcpProcessSession = class _AcpProcessSession {
38743
38931
  });
38744
38932
  }
38745
38933
  const initialized = await this.race(
38746
- this.#endpoint.connection.agent.request(
38934
+ this.#connection.connection.agent.request(
38747
38935
  methods8.agent.initialize,
38748
38936
  {
38749
38937
  clientCapabilities: {
@@ -38822,7 +39010,7 @@ var AcpProcessSession = class _AcpProcessSession {
38822
39010
  const forked = await this.#metrics.measure(
38823
39011
  "session-fork",
38824
39012
  async () => await this.race(
38825
- this.#endpoint.connection.agent.request(
39013
+ this.#connection.connection.agent.request(
38826
39014
  methods8.agent.session.fork,
38827
39015
  {
38828
39016
  sessionId: nativeSessionIdSchema.parse(origin.nativeSessionId),
@@ -38837,7 +39025,7 @@ var AcpProcessSession = class _AcpProcessSession {
38837
39025
  )
38838
39026
  );
38839
39027
  this.selectNativeSession(forked.sessionId);
38840
- if (this.#nativeSessionId === origin.nativeSessionId || this.#store.findNative(this.#agentId, this.#nativeSessionId).length > 0) {
39028
+ if (this.#updates.sessionId() === origin.nativeSessionId || this.#store.findNative(this.#agentId, this.#updates.sessionId()).length > 0) {
38841
39029
  throw new AcpExecutionError(
38842
39030
  "The Agent did not create an independent fork",
38843
39031
  {},
@@ -38856,13 +39044,13 @@ var AcpProcessSession = class _AcpProcessSession {
38856
39044
  lifecycleResponse = await this.#metrics.measure(
38857
39045
  "session-resume",
38858
39046
  async () => await this.race(
38859
- this.#endpoint.connection.agent.request(
39047
+ this.#connection.connection.agent.request(
38860
39048
  methods8.agent.session.resume,
38861
39049
  {
38862
39050
  additionalDirectories: [...this.#additionalDirectories],
38863
39051
  cwd: this.#cwd,
38864
39052
  mcpServers: [],
38865
- sessionId: this.#nativeSessionId
39053
+ sessionId: this.#updates.sessionId()
38866
39054
  },
38867
39055
  { cancellationSignal: signal }
38868
39056
  ),
@@ -38876,13 +39064,13 @@ var AcpProcessSession = class _AcpProcessSession {
38876
39064
  lifecycleResponse = await this.#metrics.measure(
38877
39065
  "session-load",
38878
39066
  async () => await this.race(
38879
- this.#endpoint.connection.agent.request(
39067
+ this.#connection.connection.agent.request(
38880
39068
  methods8.agent.session.load,
38881
39069
  {
38882
39070
  additionalDirectories: [...this.#additionalDirectories],
38883
39071
  cwd: this.#cwd,
38884
39072
  mcpServers: [],
38885
- sessionId: this.#nativeSessionId
39073
+ sessionId: this.#updates.sessionId()
38886
39074
  },
38887
39075
  { cancellationSignal: signal }
38888
39076
  ),
@@ -38891,7 +39079,7 @@ var AcpProcessSession = class _AcpProcessSession {
38891
39079
  )
38892
39080
  );
38893
39081
  } finally {
38894
- await this.#updateTail;
39082
+ await this.#updates.drained();
38895
39083
  this.#replay = { kind: "idle" };
38896
39084
  }
38897
39085
  } else {
@@ -38915,7 +39103,7 @@ var AcpProcessSession = class _AcpProcessSession {
38915
39103
  const created = await this.#metrics.measure(
38916
39104
  "session-new",
38917
39105
  async () => await this.race(
38918
- this.#endpoint.connection.agent.request(
39106
+ this.#connection.connection.agent.request(
38919
39107
  methods8.agent.session.new,
38920
39108
  {
38921
39109
  additionalDirectories: [...this.#additionalDirectories],
@@ -38932,13 +39120,13 @@ var AcpProcessSession = class _AcpProcessSession {
38932
39120
  lifecycleResponse = created;
38933
39121
  }
38934
39122
  this.#configOptions = this.#sessionConfigProtocol.normalizeLifecycle(lifecycleResponse);
38935
- await this.#updateTail;
39123
+ await this.#updates.drained();
38936
39124
  signal.throwIfAborted();
38937
39125
  this.#store.write(
38938
39126
  new AcpStoredSession(
38939
39127
  this.#mobiusSessionId,
38940
39128
  this.#agentId,
38941
- this.#nativeSessionId,
39129
+ this.#updates.sessionId(),
38942
39130
  this.#cwd,
38943
39131
  this.#additionalDirectories,
38944
39132
  this.#prompted,
@@ -38955,7 +39143,7 @@ var AcpProcessSession = class _AcpProcessSession {
38955
39143
  );
38956
39144
  }
38957
39145
  const response = await this.race(
38958
- this.#endpoint.connection.agent.request(methods8.agent.session.list, cursor === null ? {} : { cursor }, {
39146
+ this.#connection.connection.agent.request(methods8.agent.session.list, cursor === null ? {} : { cursor }, {
38959
39147
  cancellationSignal: signal
38960
39148
  }),
38961
39149
  "ACP agent exited while listing sessions",
@@ -38980,7 +39168,7 @@ var AcpProcessSession = class _AcpProcessSession {
38980
39168
  );
38981
39169
  }
38982
39170
  await this.race(
38983
- this.#endpoint.connection.agent.request(
39171
+ this.#connection.connection.agent.request(
38984
39172
  methods8.agent.session.delete,
38985
39173
  { sessionId: nativeSessionIdSchema.parse(nativeSessionId) },
38986
39174
  { cancellationSignal: signal }
@@ -38989,9 +39177,9 @@ var AcpProcessSession = class _AcpProcessSession {
38989
39177
  signal
38990
39178
  );
38991
39179
  };
38992
- nativeSessionId = () => this.#nativeSessionId;
39180
+ nativeSessionId = () => this.#updates.sessionId();
38993
39181
  adoptNativeSessionId = (sessionId) => {
38994
- if (this.#prompted || this.#nativeSessionId !== sessionId) {
39182
+ if (this.#prompted || this.#updates.sessionId() !== sessionId) {
38995
39183
  throw new AcpExecutionError("The new native Session cannot be adopted", {}, "session_identity_mismatch");
38996
39184
  }
38997
39185
  const previousSessionId = this.#mobiusSessionId;
@@ -39039,10 +39227,10 @@ var AcpProcessSession = class _AcpProcessSession {
39039
39227
  const configured = await this.#sessionConfigProtocol.configure(
39040
39228
  this.#configOptions,
39041
39229
  options,
39042
- this.#nativeSessionId,
39230
+ this.#updates.sessionId(),
39043
39231
  {
39044
39232
  request: async (method, params, failureMessage, signal) => await this.race(
39045
- this.#endpoint.connection.agent.request(method, params, {
39233
+ this.#connection.connection.agent.request(method, params, {
39046
39234
  cancellationSignal: signal
39047
39235
  }),
39048
39236
  failureMessage,
@@ -39058,7 +39246,7 @@ var AcpProcessSession = class _AcpProcessSession {
39058
39246
  "invalid_session_configuration"
39059
39247
  );
39060
39248
  }
39061
- await this.#updateTail;
39249
+ await this.#updates.drained();
39062
39250
  if (this.#configRevision === configRevision) {
39063
39251
  this.#configOptions = configured;
39064
39252
  }
@@ -39123,7 +39311,7 @@ var AcpProcessSession = class _AcpProcessSession {
39123
39311
  };
39124
39312
  nativeHistoryTurn = () => {
39125
39313
  const prompt = this.#nativePrompt;
39126
- const nativeTurnId = this.#endpoint.inProcessAgent?.nativeTurnId?.() ?? null;
39314
+ const nativeTurnId = this.#connection.inProcessAgent?.nativeTurnId?.() ?? null;
39127
39315
  return prompt === null || nativeTurnId === null || nativeTurnId === prompt.previousTurnId ? null : { commandId: prompt.commandId, nativeTurnId };
39128
39316
  };
39129
39317
  prompt = async (options) => {
@@ -39138,7 +39326,7 @@ var AcpProcessSession = class _AcpProcessSession {
39138
39326
  new AcpStoredSession(
39139
39327
  this.#mobiusSessionId,
39140
39328
  this.#agentId,
39141
- this.#nativeSessionId,
39329
+ this.#updates.sessionId(),
39142
39330
  this.#cwd,
39143
39331
  this.#additionalDirectories,
39144
39332
  true,
@@ -39156,19 +39344,19 @@ var AcpProcessSession = class _AcpProcessSession {
39156
39344
  this.#turn = running;
39157
39345
  this.#nativePrompt = {
39158
39346
  commandId: options.commandId,
39159
- previousTurnId: this.#endpoint.inProcessAgent?.nativeTurnId?.() ?? null
39347
+ previousTurnId: this.#connection.inProcessAgent?.nativeTurnId?.() ?? null
39160
39348
  };
39161
39349
  try {
39162
39350
  const response = await this.race(
39163
- this.#endpoint.connection.agent.request(
39351
+ this.#connection.connection.agent.request(
39164
39352
  methods8.agent.session.prompt,
39165
- { prompt, sessionId: this.#nativeSessionId },
39353
+ { prompt, sessionId: this.#updates.sessionId() },
39166
39354
  { cancellationSignal: options.signal }
39167
39355
  ),
39168
39356
  "ACP agent exited during a prompt",
39169
39357
  options.signal
39170
39358
  );
39171
- await this.#updateTail;
39359
+ await this.#updates.drained();
39172
39360
  await this.flushAgentText();
39173
39361
  await running.activities.finish();
39174
39362
  let result;
@@ -39218,10 +39406,10 @@ var AcpProcessSession = class _AcpProcessSession {
39218
39406
  }
39219
39407
  const prompt = this.buildPrompt(options);
39220
39408
  const response = await this.race(
39221
- this.#endpoint.connection.agent.request("_session/steering", {
39409
+ this.#connection.connection.agent.request("_session/steering", {
39222
39410
  _meta: { steering: { idleBehavior: "promptRequired" } },
39223
39411
  prompt,
39224
- sessionId: this.#nativeSessionId
39412
+ sessionId: this.#updates.sessionId()
39225
39413
  }),
39226
39414
  "ACP agent exited during steering",
39227
39415
  options.signal
@@ -39254,12 +39442,12 @@ var AcpProcessSession = class _AcpProcessSession {
39254
39442
  );
39255
39443
  };
39256
39444
  cancel = async () => {
39257
- const capturedProcesses = await this.#endpoint.captureProcessTree();
39445
+ const capturedProcesses = await this.#connection.captureProcessTree();
39258
39446
  try {
39259
39447
  await this.#interactions.cancelPendingInteractions();
39260
39448
  if (this.#turn.running) {
39261
- await this.#endpoint.connection.agent.notify(methods8.agent.session.cancel, {
39262
- sessionId: this.#nativeSessionId
39449
+ await this.#connection.connection.agent.notify(methods8.agent.session.cancel, {
39450
+ sessionId: this.#updates.sessionId()
39263
39451
  });
39264
39452
  }
39265
39453
  } finally {
@@ -39271,45 +39459,9 @@ var AcpProcessSession = class _AcpProcessSession {
39271
39459
  onPermission = (request, signal) => this.#interactions.onPermission(request, signal);
39272
39460
  onElicitation = (request, signal) => this.#interactions.onElicitation(request, signal);
39273
39461
  onElicitationComplete = (notification) => this.#interactions.onElicitationComplete(notification);
39274
- onUpdate = (notification) => {
39275
- if (this.#nativeSessionId.length === 0) {
39276
- const notificationBytes = Buffer.byteLength(JSON.stringify(notification));
39277
- if (this.#preSessionUpdates.length >= MAX_PRE_SESSION_UPDATES || this.#preSessionUpdateBytes + notificationBytes > MAX_PRE_SESSION_UPDATE_BYTES) {
39278
- return Promise.reject(
39279
- new AcpExecutionError(
39280
- "ACP agent sent too many updates before creating its session",
39281
- {},
39282
- "agent_update_limit"
39283
- )
39284
- );
39285
- }
39286
- this.#preSessionUpdates.push(notification);
39287
- this.#preSessionUpdateBytes += notificationBytes;
39288
- return Promise.resolve();
39289
- }
39290
- return this.enqueueUpdate(notification);
39291
- };
39292
- enqueueUpdate = (notification) => {
39293
- this.#updateTail = this.#updateTail.then(async () => await this.processUpdate(notification));
39294
- return this.#updateTail;
39295
- };
39296
- selectNativeSession = (sessionId) => {
39297
- const selected = nativeSessionIdSchema.parse(sessionId);
39298
- if (this.#nativeSessionId.length > 0 && this.#nativeSessionId !== selected) {
39299
- throw new AcpExecutionError(
39300
- "ACP agent attempted to replace the selected session",
39301
- {},
39302
- "invalid_agent_session"
39303
- );
39304
- }
39305
- this.#nativeSessionId = selected;
39306
- const pending = this.#preSessionUpdates.splice(0);
39307
- this.#preSessionUpdateBytes = 0;
39308
- for (const notification of pending) {
39309
- void this.enqueueUpdate(notification);
39310
- }
39311
- };
39312
- processUpdate = async (notification) => {
39462
+ onUpdate = (notification) => this.#updates.receive(notification);
39463
+ selectNativeSession = (sessionId) => this.#updates.select(sessionId);
39464
+ #processUpdate = async (notification) => {
39313
39465
  this.assertNativeSession(notification.sessionId);
39314
39466
  const update = notification.update;
39315
39467
  if (this.#replay.kind === "capture") {
@@ -39379,7 +39531,7 @@ var AcpProcessSession = class _AcpProcessSession {
39379
39531
  })).filter((command) => command.name.length > 0);
39380
39532
  this.#commands = commands;
39381
39533
  await this.#getObserver().onCommands({
39382
- commands,
39534
+ commands: this.#commands,
39383
39535
  kind: SESSION_COMMANDS_UPDATED_KIND,
39384
39536
  sessionId: this.#mobiusSessionId
39385
39537
  });
@@ -39409,12 +39561,12 @@ var AcpProcessSession = class _AcpProcessSession {
39409
39561
  if (Object.hasOwn(update, "updatedAt")) {
39410
39562
  this.#sessionUpdatedAt = truncate3(update.updatedAt ?? "", 128);
39411
39563
  }
39412
- if (this.#nativeSessionId.length > 0) {
39564
+ if (this.#updates.sessionId().length > 0) {
39413
39565
  this.#store.write(
39414
39566
  new AcpStoredSession(
39415
39567
  this.#mobiusSessionId,
39416
39568
  this.#agentId,
39417
- this.#nativeSessionId,
39569
+ this.#updates.sessionId(),
39418
39570
  this.#cwd,
39419
39571
  this.#additionalDirectories,
39420
39572
  this.#prompted,
@@ -39446,11 +39598,11 @@ var AcpProcessSession = class _AcpProcessSession {
39446
39598
  close = async () => {
39447
39599
  try {
39448
39600
  await this.#interactions.cancelPendingInteractions();
39449
- if (this.#capabilities.closeSession && this.#nativeSessionId.length > 0) {
39601
+ if (this.#capabilities.closeSession && this.#updates.sessionId().length > 0) {
39450
39602
  try {
39451
- await this.#endpoint.connection.agent.request(
39603
+ await this.#connection.connection.agent.request(
39452
39604
  methods8.agent.session.close,
39453
- { sessionId: this.#nativeSessionId },
39605
+ { sessionId: this.#updates.sessionId() },
39454
39606
  {
39455
39607
  cancellationSignal: AbortSignal.timeout(PROCESS_STOP_TIMEOUT_MILLISECONDS)
39456
39608
  }
@@ -39462,10 +39614,10 @@ var AcpProcessSession = class _AcpProcessSession {
39462
39614
  await this.closeProcess();
39463
39615
  }
39464
39616
  };
39465
- closeProcess = (capturedProcesses = []) => this.#endpoint.closeProcess(capturedProcesses);
39466
- race = (operation, exitMessage, signal) => this.#endpoint.race(operation, exitMessage, signal);
39617
+ closeProcess = (capturedProcesses = []) => this.#connection.closeProcess(capturedProcesses);
39618
+ race = (operation, exitMessage, signal) => this.#connection.race(operation, exitMessage, signal);
39467
39619
  assertNativeSession = (sessionId) => {
39468
- if (sessionId !== this.#nativeSessionId) {
39620
+ if (sessionId !== this.#updates.sessionId()) {
39469
39621
  throw new AcpExecutionError("ACP agent referenced an unknown session", {}, "invalid_agent_session");
39470
39622
  }
39471
39623
  };
@@ -39479,8 +39631,8 @@ var AcpProcessSession = class _AcpProcessSession {
39479
39631
  };
39480
39632
  };
39481
39633
 
39482
- // src/acp/retained-sessions.ts
39483
- var RetainedSessions = class {
39634
+ // src/acp/retained-agent-processes.ts
39635
+ var RetainedAgentProcesses = class {
39484
39636
  #entries = /* @__PURE__ */ new Map();
39485
39637
  #events;
39486
39638
  constructor(events) {
@@ -39583,84 +39735,118 @@ var RetainedSessions = class {
39583
39735
  };
39584
39736
  };
39585
39737
 
39586
- // src/acp/session-executions.ts
39587
- var unreachable = (state) => {
39588
- throw new AcpExecutionError("Unexpected execution state", { cause: state });
39589
- };
39590
- var SessionExecutions = class {
39591
- #entries = /* @__PURE__ */ new Map();
39592
- command = (id) => {
39593
- const state = this.#entries.get(id);
39594
- switch (state?.kind) {
39595
- case "running":
39596
- case "cancelling":
39597
- return state.commandId;
39598
- case "cancelled-before-start":
39599
- case void 0:
39600
- return void 0;
39601
- default:
39602
- return unreachable(state);
39738
+ // src/acp/agent-query-processes.ts
39739
+ var AgentQueryProcesses = class {
39740
+ #processesByQuery;
39741
+ #processes;
39742
+ #observer = new NullAcpSessionObserver();
39743
+ #store = new MemoryAcpSessionStore();
39744
+ constructor(processes) {
39745
+ this.#processes = processes;
39746
+ this.#processesByQuery = new RetainedAgentProcesses({
39747
+ touch: processes.touch,
39748
+ changed: processes.notifyChanged
39749
+ });
39750
+ }
39751
+ retire = async (sessionId, runtime) => {
39752
+ const retained = this.#processesByQuery.detach(sessionId, runtime);
39753
+ if (retained) {
39754
+ this.#store.remove(sessionId);
39603
39755
  }
39756
+ await this.#processes.retire(runtime, () => runtime.close());
39604
39757
  };
39605
- cancellation = (id) => {
39606
- const state = this.#entries.get(id);
39607
- switch (state?.kind) {
39608
- case "cancelling":
39609
- case "cancelled-before-start":
39610
- return state.completion;
39611
- case "running":
39612
- case void 0:
39613
- return void 0;
39614
- default:
39615
- return unreachable(state);
39758
+ async #startRetained(options) {
39759
+ const runtime = await this.#processes.startRetained(
39760
+ options.signal,
39761
+ () => AgentSession.startNativeSessionBrowser(options, () => this.#observer, this.#store),
39762
+ {
39763
+ isBusy: () => this.#processesByQuery.isBusy(options.sessionId),
39764
+ retire: (runtime2) => this.retire(options.sessionId, runtime2)
39765
+ }
39766
+ );
39767
+ this.#processesByQuery.retain(options.sessionId, runtime);
39768
+ return runtime;
39769
+ }
39770
+ async #startPreparation(options) {
39771
+ return await this.#processesByQuery.prepare(options.sessionId, async () => {
39772
+ return await this.#startRetained(options);
39773
+ });
39774
+ }
39775
+ async #replacePreparation(existing, options) {
39776
+ return await this.#processesByQuery.prepare(options.sessionId, async () => {
39777
+ await this.retire(options.sessionId, existing);
39778
+ return await this.#startRetained(options);
39779
+ });
39780
+ }
39781
+ prepare = async (options) => {
39782
+ const pending = this.#processesByQuery.pending(options.sessionId);
39783
+ if (pending !== void 0) {
39784
+ const runtime2 = await pending;
39785
+ if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
39786
+ this.#processesByQuery.touch(options.sessionId, runtime2);
39787
+ return runtime2.prepared();
39788
+ }
39789
+ return await this.prepare(options);
39616
39790
  }
39617
- };
39618
- isBusy = (id) => this.#entries.has(id);
39619
- begin = (id, commandId) => {
39620
- const state = this.#entries.get(id);
39621
- switch (state?.kind) {
39622
- case "running":
39623
- case "cancelling":
39791
+ const existing = this.#processesByQuery.get(options.sessionId);
39792
+ if (existing !== void 0) {
39793
+ if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
39794
+ this.#processesByQuery.touch(options.sessionId, existing);
39795
+ return existing.prepared();
39796
+ }
39797
+ if (!existing.canRebind()) {
39624
39798
  throw new AcpExecutionError(
39625
- "Another prompt is already running in this conversation",
39799
+ "The agent or workspace cannot change after a conversation has started",
39626
39800
  {},
39627
- "session_busy"
39801
+ "session_identity_mismatch"
39628
39802
  );
39629
- case "cancelled-before-start":
39630
- case void 0:
39631
- break;
39632
- default:
39633
- unreachable(state);
39803
+ }
39804
+ const runtime2 = await this.#replacePreparation(existing, options);
39805
+ return runtime2.prepared();
39634
39806
  }
39635
- this.#entries.set(
39636
- id,
39637
- state?.kind === "cancelled-before-start" ? { kind: "cancelling", commandId, completion: state.completion } : { kind: "running", commandId }
39638
- );
39807
+ const runtime = await this.#startPreparation(options);
39808
+ return runtime.prepared();
39639
39809
  };
39640
- cancel = (id, stop) => {
39641
- const state = this.#entries.get(id);
39642
- switch (state?.kind) {
39643
- case "cancelling":
39644
- case "cancelled-before-start":
39645
- return state.completion;
39646
- case "running":
39647
- case void 0:
39648
- break;
39649
- default:
39650
- return unreachable(state);
39810
+ async #ensure(options) {
39811
+ const existing = this.#processesByQuery.get(options.sessionId);
39812
+ if (existing !== void 0) {
39813
+ if (!existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
39814
+ throw new AcpExecutionError(
39815
+ "The agent or workspace cannot change after a conversation has started",
39816
+ {},
39817
+ "session_identity_mismatch"
39818
+ );
39819
+ }
39820
+ this.#processesByQuery.touch(options.sessionId, existing);
39821
+ return existing;
39651
39822
  }
39652
- const completion = Promise.withResolvers();
39653
- this.#entries.set(
39654
- id,
39655
- state?.kind === "running" ? { kind: "cancelling", commandId: state.commandId, completion: completion.promise } : { kind: "cancelled-before-start", completion: completion.promise }
39823
+ await this.prepare(options);
39824
+ const started = this.#processesByQuery.get(options.sessionId);
39825
+ if (started === void 0) {
39826
+ throw new AcpExecutionError("ACP native session browser did not start");
39827
+ }
39828
+ return started;
39829
+ }
39830
+ use = async (options, operation) => await this.#processesByQuery.use(options.sessionId, async () => await operation(await this.#ensure(options)));
39831
+ preview = async (options, nativeSessionId) => {
39832
+ return await this.#processes.runTransient(
39833
+ options.signal,
39834
+ async () => await AgentSession.startNativeSessionBrowser(
39835
+ options,
39836
+ () => this.#observer,
39837
+ new MemoryAcpSessionStore()
39838
+ ),
39839
+ async (runtime) => {
39840
+ runtime.selectNativeSession(nativeSessionId);
39841
+ return await runtime.loadHistory(options.signal);
39842
+ },
39843
+ async (runtime) => await runtime.closeProcess()
39656
39844
  );
39657
- void (async () => await stop())().then(completion.resolve, completion.reject);
39658
- return completion.promise;
39659
39845
  };
39660
- finish = (id, commandId) => {
39661
- if (this.command(id) === commandId) {
39662
- this.#entries.delete(id);
39663
- }
39846
+ close = async () => {
39847
+ await Promise.all(
39848
+ this.#processesByQuery.entries().map(async ([id, runtime]) => await this.retire(id, runtime))
39849
+ );
39664
39850
  };
39665
39851
  };
39666
39852
 
@@ -39765,9 +39951,9 @@ async function waitForAcpProcessCapacity(completion, signal) {
39765
39951
  }
39766
39952
  }
39767
39953
 
39768
- // src/acp/process-pool.ts
39954
+ // src/acp/agent-process-pool.ts
39769
39955
  var MAX_ACP_PROCESSES = 10;
39770
- var AcpProcessPool = class {
39956
+ var AgentProcessPool = class {
39771
39957
  #slots = /* @__PURE__ */ new Map();
39772
39958
  #lock = new AcpProcessCapacityLock();
39773
39959
  #changed = Promise.withResolvers();
@@ -39871,20 +40057,18 @@ var AcpProcessPool = class {
39871
40057
  };
39872
40058
  };
39873
40059
 
39874
- // src/acp/session-manager.ts
40060
+ // src/acp/agent-runtime-manager.ts
39875
40061
  var SESSION_CONTROL_TIMEOUT_MILLISECONDS = 3e4;
39876
- var AcpSessionManager = class {
39877
- #processes = new AcpProcessPool();
39878
- #sessions = new RetainedSessions({ touch: this.#processes.touch, changed: this.#processes.notifyChanged });
39879
- #nativeBrowserSessions = new RetainedSessions({
40062
+ var AgentRuntimeManager = class {
40063
+ #processes = new AgentProcessPool();
40064
+ #executionProcesses = new RetainedAgentProcesses({
39880
40065
  touch: this.#processes.touch,
39881
40066
  changed: this.#processes.notifyChanged
39882
40067
  });
39883
- #executions = new SessionExecutions();
40068
+ #queryProcesses = new AgentQueryProcesses(this.#processes);
40069
+ #executions = new ActiveExecutions();
39884
40070
  #agentSettingsObserver = new NullAcpSessionObserver();
39885
40071
  #nativeOperations = /* @__PURE__ */ new Set();
39886
- #nativeBrowserObserver = new NullAcpSessionObserver();
39887
- #nativeBrowserStore = new MemoryAcpSessionStore();
39888
40072
  #store;
39889
40073
  #nativeHistoryReader;
39890
40074
  #sessionIdentity;
@@ -39902,20 +40086,14 @@ var AcpSessionManager = class {
39902
40086
  const stored = this.#store.read(sessionId);
39903
40087
  return stored instanceof FoundAcpStoredSession && this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`);
39904
40088
  }
39905
- #retention(sessionId, kind) {
39906
- if (kind === "execution") {
39907
- return {
39908
- isBusy: () => this.#executions.isBusy(sessionId) || this.#sessions.isBusy(sessionId) || this.#isNativeSessionOperationActive(sessionId),
39909
- retire: (runtime) => this.#retireSessionProcess(sessionId, runtime, () => runtime.close())
39910
- };
39911
- }
40089
+ #retention(sessionId) {
39912
40090
  return {
39913
- isBusy: () => this.#nativeBrowserSessions.isBusy(sessionId),
39914
- retire: (runtime) => this.#retireNativeBrowserProcess(sessionId, runtime, () => runtime.close())
40091
+ isBusy: () => this.#executions.isBusy(sessionId) || this.#executionProcesses.isBusy(sessionId) || this.#isNativeSessionOperationActive(sessionId),
40092
+ retire: (runtime) => this.#retireSessionProcess(sessionId, runtime, () => runtime.close())
39915
40093
  };
39916
40094
  }
39917
40095
  async #retireSessionProcess(sessionId, runtime, close) {
39918
- const retained = this.#sessions.detach(sessionId, runtime);
40096
+ const retained = this.#executionProcesses.detach(sessionId, runtime);
39919
40097
  try {
39920
40098
  await this.#processes.retire(runtime, close);
39921
40099
  } finally {
@@ -39927,61 +40105,16 @@ var AcpSessionManager = class {
39927
40105
  }
39928
40106
  }
39929
40107
  }
39930
- async #retireNativeBrowserProcess(sessionId, runtime, close) {
39931
- const retained = this.#nativeBrowserSessions.detach(sessionId, runtime);
39932
- if (retained) {
39933
- this.#nativeBrowserStore.remove(sessionId);
39934
- }
39935
- await this.#processes.retire(runtime, close);
39936
- }
39937
40108
  async #startRetainedSessionProcess(options, start) {
39938
- const runtime = await this.#processes.startRetained(
39939
- options.signal,
39940
- start,
39941
- this.#retention(options.sessionId, "execution")
39942
- );
39943
- this.#sessions.retain(options.sessionId, runtime);
39944
- return runtime;
39945
- }
39946
- async #startRetainedNativeBrowserProcess(options, start) {
39947
- const runtime = await this.#processes.startRetained(
39948
- options.signal,
39949
- start,
39950
- this.#retention(options.sessionId, "browser")
39951
- );
39952
- this.#nativeBrowserSessions.retain(options.sessionId, runtime);
40109
+ const runtime = await this.#processes.startRetained(options.signal, start, this.#retention(options.sessionId));
40110
+ this.#executionProcesses.retain(options.sessionId, runtime);
39953
40111
  return runtime;
39954
40112
  }
39955
- async #startNativeBrowserPreparation(options) {
39956
- return await this.#nativeBrowserSessions.prepare(options.sessionId, async () => {
39957
- return await this.#startRetainedNativeBrowserProcess(
39958
- options,
39959
- async () => await AcpProcessSession.startNativeSessionBrowser(
39960
- options,
39961
- () => this.#nativeBrowserObserver,
39962
- this.#nativeBrowserStore
39963
- )
39964
- );
39965
- });
39966
- }
39967
- async #replaceNativeBrowserPreparation(existing, options) {
39968
- return await this.#nativeBrowserSessions.prepare(options.sessionId, async () => {
39969
- await this.#retireNativeBrowserProcess(options.sessionId, existing, async () => await existing.close());
39970
- return await this.#startRetainedNativeBrowserProcess(
39971
- options,
39972
- async () => await AcpProcessSession.startNativeSessionBrowser(
39973
- options,
39974
- () => this.#nativeBrowserObserver,
39975
- this.#nativeBrowserStore
39976
- )
39977
- );
39978
- });
39979
- }
39980
40113
  async #startPreparation(options, metrics = unmeasuredOperationMetrics) {
39981
- return await this.#sessions.prepare(options.sessionId, async () => {
40114
+ return await this.#executionProcesses.prepare(options.sessionId, async () => {
39982
40115
  return await this.#startRetainedSessionProcess(
39983
40116
  options,
39984
- async () => await AcpProcessSession.start(
40117
+ async () => await AgentSession.start(
39985
40118
  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,
39986
40119
  () => this.#observer,
39987
40120
  this.#store,
@@ -39991,7 +40124,7 @@ var AcpSessionManager = class {
39991
40124
  });
39992
40125
  }
39993
40126
  async #replacePreparation(existing, options, metrics) {
39994
- return await this.#sessions.prepare(options.sessionId, async () => {
40127
+ return await this.#executionProcesses.prepare(options.sessionId, async () => {
39995
40128
  await this.#retireSessionProcess(
39996
40129
  options.sessionId,
39997
40130
  existing,
@@ -40000,17 +40133,17 @@ var AcpSessionManager = class {
40000
40133
  this.#store.remove(options.sessionId);
40001
40134
  return await this.#startRetainedSessionProcess(
40002
40135
  options,
40003
- async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
40136
+ async () => await AgentSession.start(options, () => this.#observer, this.#store, metrics)
40004
40137
  );
40005
40138
  });
40006
40139
  }
40007
40140
  async #replaceExecutionPreparation(existing, options) {
40008
40141
  const desiredConfigOptions = existing.prepared().configOptions;
40009
- return await this.#sessions.prepare(options.sessionId, async () => {
40142
+ return await this.#executionProcesses.prepare(options.sessionId, async () => {
40010
40143
  await this.#retireSessionProcess(options.sessionId, existing, async () => await existing.close());
40011
40144
  const runtime = await this.#startRetainedSessionProcess(
40012
40145
  options,
40013
- async () => await AcpProcessSession.start(options, () => this.#observer, this.#store)
40146
+ async () => await AgentSession.start(options, () => this.#observer, this.#store)
40014
40147
  );
40015
40148
  try {
40016
40149
  for (const desired of desiredConfigOptions) {
@@ -40061,19 +40194,19 @@ var AcpSessionManager = class {
40061
40194
  if (stored instanceof FoundAcpStoredSession && this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`)) {
40062
40195
  throw new AcpExecutionError("The native session is being managed", {}, "session_busy");
40063
40196
  }
40064
- const pending = this.#sessions.pending(options.sessionId);
40197
+ const pending = this.#executionProcesses.pending(options.sessionId);
40065
40198
  if (pending !== void 0) {
40066
40199
  const runtime2 = await metrics.measure("session-preparation-wait", async () => await pending);
40067
40200
  if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
40068
- this.#sessions.touch(options.sessionId, runtime2);
40201
+ this.#executionProcesses.touch(options.sessionId, runtime2);
40069
40202
  return runtime2.prepared();
40070
40203
  }
40071
40204
  return await this.prepareSession(options, metrics);
40072
40205
  }
40073
- const existing = this.#sessions.get(options.sessionId);
40206
+ const existing = this.#executionProcesses.get(options.sessionId);
40074
40207
  if (existing !== void 0) {
40075
40208
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
40076
- this.#sessions.touch(options.sessionId, existing);
40209
+ this.#executionProcesses.touch(options.sessionId, existing);
40077
40210
  return existing.prepared();
40078
40211
  }
40079
40212
  if (!existing.canRebind()) {
@@ -40096,7 +40229,7 @@ var AcpSessionManager = class {
40096
40229
  */
40097
40230
  inspectAgentSettings = async (options) => await this.#processes.runTransient(
40098
40231
  options.signal,
40099
- async () => await AcpProcessSession.start(
40232
+ async () => await AgentSession.start(
40100
40233
  {
40101
40234
  ...options,
40102
40235
  sessionId: `agent-settings-${crypto.randomUUID()}`
@@ -40127,10 +40260,10 @@ var AcpSessionManager = class {
40127
40260
  * Use inspectAgentSettings for Agent-scoped settings discovery.
40128
40261
  */
40129
40262
  inspectSession = async (options, metrics = unmeasuredOperationMetrics) => {
40130
- if (this.#sessions.pending(options.sessionId) !== void 0 || this.#sessions.get(options.sessionId) !== void 0) {
40263
+ if (this.#executionProcesses.pending(options.sessionId) !== void 0 || this.#executionProcesses.get(options.sessionId) !== void 0) {
40131
40264
  throw new AcpExecutionError("The configuration inspection session is already in use", {}, "session_busy");
40132
40265
  }
40133
- return await this.#sessions.use(options.sessionId, async () => {
40266
+ return await this.#executionProcesses.use(options.sessionId, async () => {
40134
40267
  const runtime = await this.#startPreparation(options, metrics);
40135
40268
  try {
40136
40269
  return runtime.prepared();
@@ -40144,12 +40277,12 @@ var AcpSessionManager = class {
40144
40277
  });
40145
40278
  };
40146
40279
  prepareExecutionSession = async (options) => {
40147
- const pending = this.#sessions.pending(options.sessionId);
40280
+ const pending = this.#executionProcesses.pending(options.sessionId);
40148
40281
  if (pending !== void 0) {
40149
40282
  await pending;
40150
40283
  return await this.prepareExecutionSession(options);
40151
40284
  }
40152
- const existing = this.#sessions.get(options.sessionId);
40285
+ const existing = this.#executionProcesses.get(options.sessionId);
40153
40286
  if (existing === void 0) {
40154
40287
  return (await this.#startPreparation(options)).prepared();
40155
40288
  }
@@ -40161,7 +40294,7 @@ var AcpSessionManager = class {
40161
40294
  );
40162
40295
  }
40163
40296
  if (existing.usesEnvironment(options.agent.environment)) {
40164
- this.#sessions.touch(options.sessionId, existing);
40297
+ this.#executionProcesses.touch(options.sessionId, existing);
40165
40298
  return existing.prepared();
40166
40299
  }
40167
40300
  if (existing.hasRunningTurn()) {
@@ -40173,49 +40306,21 @@ var AcpSessionManager = class {
40173
40306
  }
40174
40307
  return (await this.#replaceExecutionPreparation(existing, options)).prepared();
40175
40308
  };
40176
- prepareNativeSessionBrowser = async (options) => {
40177
- const pending = this.#nativeBrowserSessions.pending(options.sessionId);
40178
- if (pending !== void 0) {
40179
- const runtime2 = await pending;
40180
- if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
40181
- this.#nativeBrowserSessions.touch(options.sessionId, runtime2);
40182
- return runtime2.prepared();
40183
- }
40184
- return await this.prepareNativeSessionBrowser(options);
40185
- }
40186
- const existing = this.#nativeBrowserSessions.get(options.sessionId);
40187
- if (existing !== void 0) {
40188
- if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
40189
- this.#nativeBrowserSessions.touch(options.sessionId, existing);
40190
- return existing.prepared();
40191
- }
40192
- if (!existing.canRebind()) {
40193
- throw new AcpExecutionError(
40194
- "The agent or workspace cannot change after a conversation has started",
40195
- {},
40196
- "session_identity_mismatch"
40197
- );
40198
- }
40199
- const runtime2 = await this.#replaceNativeBrowserPreparation(existing, options);
40200
- return runtime2.prepared();
40201
- }
40202
- const runtime = await this.#startNativeBrowserPreparation(options);
40203
- return runtime.prepared();
40204
- };
40309
+ prepareNativeSessionBrowser = (options) => this.#queryProcesses.prepare(options);
40205
40310
  configureSession = async (options) => {
40206
- return await this.#sessions.use(options.sessionId, async () => {
40311
+ return await this.#executionProcesses.use(options.sessionId, async () => {
40207
40312
  const runtime = await this.ensureSession(options);
40208
40313
  return await runtime.configure(options);
40209
40314
  });
40210
40315
  };
40211
40316
  cancelPrompt = async (sessionId) => {
40212
40317
  await this.#executions.cancel(sessionId, async () => {
40213
- const runtime = this.#sessions.get(sessionId);
40318
+ const runtime = this.#executionProcesses.get(sessionId);
40214
40319
  if (runtime !== void 0) {
40215
40320
  try {
40216
40321
  await runtime.cancel();
40217
40322
  } finally {
40218
- if (this.#sessions.detach(sessionId, runtime)) {
40323
+ if (this.#executionProcesses.detach(sessionId, runtime)) {
40219
40324
  this.#processes.releaseClosed(runtime);
40220
40325
  }
40221
40326
  }
@@ -40226,14 +40331,14 @@ var AcpSessionManager = class {
40226
40331
  if (this.#executions.command(options.sessionId) !== options.targetCommandId) {
40227
40332
  throw new AcpExecutionError("The target turn is no longer active", {}, "steering_target_unavailable");
40228
40333
  }
40229
- const pending = this.#sessions.pending(options.sessionId);
40334
+ const pending = this.#executionProcesses.pending(options.sessionId);
40230
40335
  if (pending !== void 0) {
40231
40336
  await pending;
40232
40337
  }
40233
40338
  if (this.#executions.command(options.sessionId) !== options.targetCommandId) {
40234
40339
  throw new AcpExecutionError("The target turn is no longer active", {}, "steering_target_unavailable");
40235
40340
  }
40236
- const runtime = this.#sessions.get(options.sessionId);
40341
+ const runtime = this.#executionProcesses.get(options.sessionId);
40237
40342
  if (runtime === void 0 || !runtime.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
40238
40343
  throw new AcpExecutionError(
40239
40344
  "The target turn execution context is unavailable",
@@ -40291,7 +40396,7 @@ var AcpSessionManager = class {
40291
40396
  throw error62;
40292
40397
  }
40293
40398
  } catch (error62) {
40294
- const failedRuntime = this.#sessions.get(options.sessionId);
40399
+ const failedRuntime = this.#executionProcesses.get(options.sessionId);
40295
40400
  if (failedRuntime !== void 0) {
40296
40401
  await this.#retireSessionProcess(
40297
40402
  options.sessionId,
@@ -40313,35 +40418,32 @@ var AcpSessionManager = class {
40313
40418
  await this.#executions.cancellation(options.sessionId);
40314
40419
  } finally {
40315
40420
  this.#executions.finish(options.sessionId, options.commandId);
40316
- this.#sessions.touch(options.sessionId);
40421
+ this.#executionProcesses.touch(options.sessionId);
40317
40422
  this.#processes.notifyChanged();
40318
40423
  }
40319
40424
  }
40320
40425
  };
40321
40426
  respondPermission = async (options) => {
40322
- const runtime = this.#sessions.get(options.sessionId);
40427
+ const runtime = this.#executionProcesses.get(options.sessionId);
40323
40428
  if (runtime === void 0) {
40324
40429
  throw new AcpExecutionError("The permission request session is unavailable", {}, "session_not_found");
40325
40430
  }
40326
40431
  await runtime.respondPermission(options);
40327
40432
  };
40328
40433
  respondElicitation = async (options) => {
40329
- const runtime = this.#sessions.get(options.sessionId);
40434
+ const runtime = this.#executionProcesses.get(options.sessionId);
40330
40435
  if (runtime === void 0) {
40331
40436
  throw new AcpExecutionError("The elicitation request session is unavailable", {}, "session_not_found");
40332
40437
  }
40333
40438
  await runtime.respondElicitation(options);
40334
40439
  };
40335
40440
  close = async () => {
40336
- const sessions = [...this.#sessions.entries()];
40337
- const nativeBrowserSessions = [...this.#nativeBrowserSessions.entries()];
40441
+ const sessions = [...this.#executionProcesses.entries()];
40338
40442
  await Promise.all([
40339
40443
  ...sessions.map(
40340
40444
  async ([sessionId, runtime]) => await this.#retireSessionProcess(sessionId, runtime, async () => await runtime.close())
40341
40445
  ),
40342
- ...nativeBrowserSessions.map(
40343
- async ([sessionId, runtime]) => await this.#retireNativeBrowserProcess(sessionId, runtime, async () => await runtime.close())
40344
- )
40446
+ this.#queryProcesses.close()
40345
40447
  ]);
40346
40448
  };
40347
40449
  findSessions = (sessionIds) => sessionIds.flatMap((sessionId) => {
@@ -40349,17 +40451,17 @@ var AcpSessionManager = class {
40349
40451
  return stored instanceof FoundAcpStoredSession ? [stored.session] : [];
40350
40452
  });
40351
40453
  findLinkedSessions = (agentId, nativeSessionId) => this.#store.findNative(agentId, nativeSessionId);
40352
- hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
40454
+ hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#executionProcesses.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
40353
40455
  createNativeSession = async (options) => {
40354
40456
  const temporarySessionId = `new-${crypto.randomUUID()}`;
40355
40457
  const temporaryOptions = { ...options, sessionId: temporarySessionId };
40356
- return await this.#sessions.use(temporarySessionId, async () => {
40458
+ return await this.#executionProcesses.use(temporarySessionId, async () => {
40357
40459
  try {
40358
40460
  const runtime = await this.#startPreparation(temporaryOptions);
40359
40461
  let adopted = false;
40360
40462
  try {
40361
40463
  const nativeSessionId = runtime.nativeSessionId();
40362
- if (!isNativeChatSessionId(options.agent.id, nativeSessionId) || this.#sessions.get(nativeSessionId) !== void 0 || !(this.#store.read(nativeSessionId) instanceof MissingAcpStoredSession)) {
40464
+ if (!isNativeChatSessionId(options.agent.id, nativeSessionId) || this.#executionProcesses.get(nativeSessionId) !== void 0 || !(this.#store.read(nativeSessionId) instanceof MissingAcpStoredSession)) {
40363
40465
  throw new AcpExecutionError(
40364
40466
  "The Agent returned an invalid new Session ID",
40365
40467
  {},
@@ -40367,9 +40469,9 @@ var AcpSessionManager = class {
40367
40469
  );
40368
40470
  }
40369
40471
  runtime.adoptNativeSessionId(nativeSessionId);
40370
- this.#sessions.detach(temporarySessionId, runtime);
40371
- this.#sessions.retain(nativeSessionId, runtime);
40372
- this.#processes.retain(runtime, this.#retention(nativeSessionId, "execution"));
40472
+ this.#executionProcesses.detach(temporarySessionId, runtime);
40473
+ this.#executionProcesses.retain(nativeSessionId, runtime);
40474
+ this.#processes.retain(runtime, this.#retention(nativeSessionId));
40373
40475
  adopted = true;
40374
40476
  return nativeSessionId;
40375
40477
  } finally {
@@ -40387,7 +40489,7 @@ var AcpSessionManager = class {
40387
40489
  });
40388
40490
  };
40389
40491
  ensureSession = async (options) => {
40390
- const existing = this.#sessions.get(options.sessionId);
40492
+ const existing = this.#executionProcesses.get(options.sessionId);
40391
40493
  if (existing !== void 0) {
40392
40494
  if (!existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
40393
40495
  throw new AcpExecutionError(
@@ -40396,46 +40498,27 @@ var AcpSessionManager = class {
40396
40498
  "session_identity_mismatch"
40397
40499
  );
40398
40500
  }
40399
- this.#sessions.touch(options.sessionId, existing);
40501
+ this.#executionProcesses.touch(options.sessionId, existing);
40400
40502
  return existing;
40401
40503
  }
40402
40504
  await this.prepareSession(options);
40403
- const started = this.#sessions.get(options.sessionId);
40505
+ const started = this.#executionProcesses.get(options.sessionId);
40404
40506
  if (started === void 0) {
40405
40507
  throw new AcpExecutionError("ACP session did not start");
40406
40508
  }
40407
40509
  return started;
40408
40510
  };
40409
- async #ensureNativeSessionBrowser(options) {
40410
- const existing = this.#nativeBrowserSessions.get(options.sessionId);
40411
- if (existing !== void 0) {
40412
- if (!existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
40413
- throw new AcpExecutionError(
40414
- "The agent or workspace cannot change after a conversation has started",
40415
- {},
40416
- "session_identity_mismatch"
40417
- );
40418
- }
40419
- this.#nativeBrowserSessions.touch(options.sessionId, existing);
40420
- return existing;
40421
- }
40422
- await this.prepareNativeSessionBrowser(options);
40423
- const started = this.#nativeBrowserSessions.get(options.sessionId);
40424
- if (started === void 0) {
40425
- throw new AcpExecutionError("ACP native session browser did not start");
40426
- }
40427
- return started;
40428
- }
40429
40511
  listNativeSessions = async (options, cursor) => {
40430
- return await this.#nativeBrowserSessions.use(options.sessionId, async () => {
40431
- return await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(cursor, options.signal);
40432
- });
40512
+ return await this.#queryProcesses.use(
40513
+ options,
40514
+ async (runtime) => await runtime.listNativeSessions(cursor, options.signal)
40515
+ );
40433
40516
  };
40434
40517
  previewNativeSession = async (options, nativeSessionId) => {
40435
40518
  const key = `${options.agent.id}:${nativeSessionId}`;
40436
40519
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
40437
40520
  if (this.#nativeOperations.has(key) || linked.some(
40438
- (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#sessions.pending(entry.sessionId) !== void 0
40521
+ (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#executionProcesses.pending(entry.sessionId) !== void 0
40439
40522
  )) {
40440
40523
  throw new AcpExecutionError(
40441
40524
  "Wait for the native session's running operation to finish",
@@ -40445,25 +40528,13 @@ var AcpSessionManager = class {
40445
40528
  }
40446
40529
  this.#nativeOperations.add(key);
40447
40530
  try {
40448
- return await this.#processes.runTransient(
40449
- options.signal,
40450
- async () => await AcpProcessSession.startNativeSessionBrowser(
40451
- options,
40452
- () => this.#nativeBrowserObserver,
40453
- new MemoryAcpSessionStore()
40454
- ),
40455
- async (runtime) => {
40456
- runtime.selectNativeSession(nativeSessionId);
40457
- return await runtime.loadHistory(options.signal);
40458
- },
40459
- async (runtime) => await runtime.closeProcess()
40460
- );
40531
+ return await this.#queryProcesses.preview(options, nativeSessionId);
40461
40532
  } finally {
40462
40533
  this.#nativeOperations.delete(key);
40463
40534
  }
40464
40535
  };
40465
40536
  loadSessionHistory = async (options) => {
40466
- return await this.#sessions.use(options.sessionId, async () => {
40537
+ return await this.#executionProcesses.use(options.sessionId, async () => {
40467
40538
  const runtime = await this.ensureSession(options);
40468
40539
  const stored = this.#store.read(options.sessionId);
40469
40540
  if (stored instanceof FoundAcpStoredSession && this.#nativeHistoryReader !== null) {
@@ -40486,7 +40557,7 @@ var AcpSessionManager = class {
40486
40557
  }
40487
40558
  const linked = this.#store.findNative(options.agent.id, origin.nativeSessionId);
40488
40559
  if (linked.some(
40489
- (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#sessions.pending(entry.sessionId) !== void 0
40560
+ (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#executionProcesses.pending(entry.sessionId) !== void 0
40490
40561
  )) {
40491
40562
  throw new AcpExecutionError(
40492
40563
  "Wait for the native session's running operation to finish",
@@ -40496,7 +40567,7 @@ var AcpSessionManager = class {
40496
40567
  }
40497
40568
  const existing = linked[0];
40498
40569
  if (origin.kind === "import" && existing !== void 0) {
40499
- return await this.#sessions.use(existing.sessionId, async () => {
40570
+ return await this.#executionProcesses.use(existing.sessionId, async () => {
40500
40571
  const runtime = await this.ensureSession({
40501
40572
  ...options,
40502
40573
  sessionId: existing.sessionId
@@ -40520,10 +40591,10 @@ var AcpSessionManager = class {
40520
40591
  }
40521
40592
  });
40522
40593
  }
40523
- 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) {
40594
+ 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) {
40524
40595
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
40525
40596
  }
40526
- return await this.#sessions.use(options.sessionId, async () => {
40597
+ return await this.#executionProcesses.use(options.sessionId, async () => {
40527
40598
  this.#nativeOperations.add(key);
40528
40599
  try {
40529
40600
  const runtime = await this.#startPreparation({ ...options, origin });
@@ -40540,7 +40611,7 @@ var AcpSessionManager = class {
40540
40611
  }
40541
40612
  } catch (error62) {
40542
40613
  this.#store.remove(options.sessionId);
40543
- const runtime = this.#sessions.get(options.sessionId);
40614
+ const runtime = this.#executionProcesses.get(options.sessionId);
40544
40615
  if (runtime !== void 0) {
40545
40616
  await this.#retireSessionProcess(
40546
40617
  options.sessionId,
@@ -40555,12 +40626,11 @@ var AcpSessionManager = class {
40555
40626
  });
40556
40627
  };
40557
40628
  deleteNativeSession = async (options, nativeSessionId) => {
40558
- return await this.#nativeBrowserSessions.use(options.sessionId, async () => {
40559
- const runtime = await this.#ensureNativeSessionBrowser(options);
40629
+ return await this.#queryProcesses.use(options, async (runtime) => {
40560
40630
  const key = `${options.agent.id}:${nativeSessionId}`;
40561
40631
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
40562
40632
  if (this.#nativeOperations.has(key) || linked.some(
40563
- (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#sessions.pending(entry.sessionId) !== void 0
40633
+ (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#executionProcesses.pending(entry.sessionId) !== void 0
40564
40634
  )) {
40565
40635
  throw new AcpExecutionError(
40566
40636
  "Wait for the native session's running operation to finish",
@@ -40571,7 +40641,7 @@ var AcpSessionManager = class {
40571
40641
  this.#nativeOperations.add(key);
40572
40642
  try {
40573
40643
  for (const entry of linked) {
40574
- const active = this.#sessions.get(entry.sessionId);
40644
+ const active = this.#executionProcesses.get(entry.sessionId);
40575
40645
  if (active !== void 0 && active !== runtime) {
40576
40646
  await this.#retireSessionProcess(entry.sessionId, active, async () => await active.close());
40577
40647
  }
@@ -40580,11 +40650,7 @@ var AcpSessionManager = class {
40580
40650
  await runtime.deleteNativeSession(nativeSessionId, options.signal);
40581
40651
  const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
40582
40652
  if (runtime.nativeSessionId() === nativeSessionId) {
40583
- await this.#retireNativeBrowserProcess(
40584
- options.sessionId,
40585
- runtime,
40586
- async () => await runtime.close()
40587
- );
40653
+ await this.#queryProcesses.retire(options.sessionId, runtime);
40588
40654
  }
40589
40655
  return deleted;
40590
40656
  } finally {
@@ -46005,7 +46071,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
46005
46071
  activeTurns.recordEvent(event);
46006
46072
  publisher.publish(sessionId, event);
46007
46073
  };
46008
- const sessions = new AcpSessionManager(
46074
+ const agentRuntime = new AgentRuntimeManager(
46009
46075
  new DaemonAcpObserver(recordSessionEvent),
46010
46076
  sessionStore,
46011
46077
  {
@@ -46027,20 +46093,28 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
46027
46093
  config2.relayUrl,
46028
46094
  new DaemonDiagnosticLog(stateDirectory)
46029
46095
  );
46030
- const nativeSessions = new NativeSessionService(config2, directories, sessions, audit, async (request, options2) => {
46031
- return await activeTurns.executionSnapshot(async (command) => {
46032
- if (command.sessionId !== request.targetSessionId || command.agentId !== request.agentId) {
46033
- return false;
46034
- }
46035
- const cwd = await directories.resolve(command.bindingId, command.directoryId, options2.signal);
46036
- const additionalDirectories = await directories.resolveMany(
46037
- command.bindingId,
46038
- command.additionalDirectoryIds,
46039
- options2.signal
46040
- );
46041
- return cwd === options2.cwd && additionalDirectories.length === options2.additionalDirectories.length && additionalDirectories.every((directory, index) => directory === options2.additionalDirectories[index]);
46042
- });
46043
- });
46096
+ const nativeSessions = new NativeSessionService(
46097
+ config2,
46098
+ directories,
46099
+ agentRuntime,
46100
+ audit,
46101
+ async (request, options2) => {
46102
+ return await activeTurns.executionSnapshot(async (command) => {
46103
+ if (command.sessionId !== request.targetSessionId || command.agentId !== request.agentId) {
46104
+ return false;
46105
+ }
46106
+ const cwd = await directories.resolve(command.bindingId, command.directoryId, options2.signal);
46107
+ const additionalDirectories = await directories.resolveMany(
46108
+ command.bindingId,
46109
+ command.additionalDirectoryIds,
46110
+ options2.signal
46111
+ );
46112
+ return cwd === options2.cwd && additionalDirectories.length === options2.additionalDirectories.length && additionalDirectories.every(
46113
+ (directory, index) => directory === options2.additionalDirectories[index]
46114
+ );
46115
+ });
46116
+ }
46117
+ );
46044
46118
  const installations = new AgentInstallationManager(
46045
46119
  specifications,
46046
46120
  installationExecutor,
@@ -46116,7 +46190,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
46116
46190
  config: config2,
46117
46191
  directories,
46118
46192
  audit,
46119
- sessions,
46193
+ sessions: agentRuntime,
46120
46194
  installations,
46121
46195
  installationObserver,
46122
46196
  nativeSessions,
@@ -46159,7 +46233,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
46159
46233
  await installations.close();
46160
46234
  } finally {
46161
46235
  try {
46162
- await sessions.close();
46236
+ await agentRuntime.close();
46163
46237
  } finally {
46164
46238
  try {
46165
46239
  sessionStore.close();