@moxt-ai/mobius 0.0.127 → 0.0.129

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 (123) 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/activity-content.d.ts +29 -0
  6. package/dist/acp/activity-content.d.ts.map +1 -0
  7. package/dist/acp/activity-content.js +301 -0
  8. package/dist/acp/activity-content.js.map +1 -0
  9. package/dist/acp/activity.d.ts +3 -9
  10. package/dist/acp/activity.d.ts.map +1 -1
  11. package/dist/acp/activity.js +2 -300
  12. package/dist/acp/activity.js.map +1 -1
  13. package/dist/acp/{process-endpoint.d.ts → agent-connection.d.ts} +2 -2
  14. package/dist/acp/{process-endpoint.d.ts.map → agent-connection.d.ts.map} +1 -1
  15. package/dist/acp/{process-endpoint.js → agent-connection.js} +2 -2
  16. package/dist/acp/{process-endpoint.js.map → agent-connection.js.map} +1 -1
  17. package/dist/acp/agent-process-pool.d.ts +17 -0
  18. package/dist/acp/agent-process-pool.d.ts.map +1 -0
  19. package/dist/acp/{process-pool.js → agent-process-pool.js} +2 -2
  20. package/dist/acp/agent-process-pool.js.map +1 -0
  21. package/dist/acp/{native-session-browsers.d.ts → agent-query-processes.d.ts} +7 -7
  22. package/dist/acp/agent-query-processes.d.ts.map +1 -0
  23. package/dist/acp/{native-session-browsers.js → agent-query-processes.js} +25 -22
  24. package/dist/acp/agent-query-processes.js.map +1 -0
  25. package/dist/acp/{session-manager.d.ts → agent-runtime-manager.d.ts} +5 -5
  26. package/dist/acp/agent-runtime-manager.d.ts.map +1 -0
  27. package/dist/acp/{session-manager.js → agent-runtime-manager.js} +69 -66
  28. package/dist/acp/agent-runtime-manager.js.map +1 -0
  29. package/dist/acp/{process-session.d.ts → agent-session.d.ts} +4 -6
  30. package/dist/acp/agent-session.d.ts.map +1 -0
  31. package/dist/acp/{process-session.js → agent-session.js} +58 -87
  32. package/dist/acp/agent-session.js.map +1 -0
  33. package/dist/acp/agent-update-stream.d.ts +11 -0
  34. package/dist/acp/agent-update-stream.d.ts.map +1 -0
  35. package/dist/acp/agent-update-stream.js +56 -0
  36. package/dist/acp/agent-update-stream.js.map +1 -0
  37. package/dist/acp/codex/agent.d.ts.map +1 -1
  38. package/dist/acp/codex/agent.js +46 -0
  39. package/dist/acp/codex/agent.js.map +1 -1
  40. package/dist/acp/retained-agent-processes.d.ts +21 -0
  41. package/dist/acp/retained-agent-processes.d.ts.map +1 -0
  42. package/dist/acp/{retained-sessions.js → retained-agent-processes.js} +3 -3
  43. package/dist/acp/retained-agent-processes.js.map +1 -0
  44. package/dist/acp/run-prompt.d.ts +1 -1
  45. package/dist/acp/run-prompt.d.ts.map +1 -1
  46. package/dist/acp/run-prompt.js +4 -4
  47. package/dist/acp/run-prompt.js.map +1 -1
  48. package/dist/acp/session-config/apply-session-configuration.d.ts +2 -2
  49. package/dist/acp/session-config/apply-session-configuration.d.ts.map +1 -1
  50. package/dist/acp/session-config/apply-session-configuration.js +1 -1
  51. package/dist/acp/session-config/apply-session-configuration.js.map +1 -1
  52. package/dist/acp/session-history.d.ts.map +1 -1
  53. package/dist/acp/session-history.js +2 -1
  54. package/dist/acp/session-history.js.map +1 -1
  55. package/dist/agent-catalog/discover-agent-settings.d.ts +2 -2
  56. package/dist/agent-catalog/discover-agent-settings.d.ts.map +1 -1
  57. package/dist/agent-catalog/discover-agent-settings.js +1 -1
  58. package/dist/agent-catalog/discover-agent-settings.js.map +1 -1
  59. package/dist/agent-catalog/handle-agent-catalog-refresh.js +1 -1
  60. package/dist/agent-catalog/handle-agent-catalog-refresh.js.map +1 -1
  61. package/dist/agent-catalog/handle-agent-settings-discovery.d.ts +2 -2
  62. package/dist/agent-catalog/handle-agent-settings-discovery.d.ts.map +1 -1
  63. package/dist/agent-catalog/handle-agent-settings-discovery.js +1 -1
  64. package/dist/agent-catalog/handle-agent-settings-discovery.js.map +1 -1
  65. package/dist/cli.js +698 -609
  66. package/dist/cli.js.map +4 -4
  67. package/dist/daemon-command-handler.d.ts +2 -2
  68. package/dist/daemon-command-handler.d.ts.map +1 -1
  69. package/dist/daemon-command-results.js +1 -1
  70. package/dist/daemon-command-results.js.map +1 -1
  71. package/dist/daemon-history-commands.d.ts +3 -3
  72. package/dist/daemon-history-commands.d.ts.map +1 -1
  73. package/dist/daemon-history-commands.js.map +1 -1
  74. package/dist/daemon-observers.d.ts +1 -1
  75. package/dist/daemon-observers.d.ts.map +1 -1
  76. package/dist/daemon-prompt-executor.d.ts +2 -2
  77. package/dist/daemon-prompt-executor.d.ts.map +1 -1
  78. package/dist/daemon-prompt-executor.js +1 -1
  79. package/dist/daemon-prompt-executor.js.map +1 -1
  80. package/dist/daemon-session-commands.d.ts +3 -3
  81. package/dist/daemon-session-commands.d.ts.map +1 -1
  82. package/dist/daemon-session-commands.js.map +1 -1
  83. package/dist/daemon-turn-registry.d.ts +13 -13
  84. package/dist/index.js +905 -816
  85. package/dist/index.js.map +4 -4
  86. package/dist/native-sessions/acp-history.d.ts +2 -2
  87. package/dist/native-sessions/acp-history.d.ts.map +1 -1
  88. package/dist/native-sessions/acp-history.js +1 -1
  89. package/dist/native-sessions/acp-history.js.map +1 -1
  90. package/dist/native-sessions/agent-adapter.d.ts +2 -2
  91. package/dist/native-sessions/agent-adapter.d.ts.map +1 -1
  92. package/dist/native-sessions/agent-adapter.js +1 -1
  93. package/dist/native-sessions/agent-adapter.js.map +1 -1
  94. package/dist/native-sessions/handle-native-requests.js +1 -1
  95. package/dist/native-sessions/handle-native-requests.js.map +1 -1
  96. package/dist/native-sessions/live-history-page.js +1 -1
  97. package/dist/native-sessions/live-history-page.js.map +1 -1
  98. package/dist/native-sessions/service.d.ts +2 -2
  99. package/dist/native-sessions/service.d.ts.map +1 -1
  100. package/dist/native-sessions/service.js +1 -1
  101. package/dist/native-sessions/service.js.map +1 -1
  102. package/dist/relay-connection/run-relay-connection.d.ts +2 -2
  103. package/dist/relay-connection/run-relay-connection.d.ts.map +1 -1
  104. package/dist/run-daemon.d.ts.map +1 -1
  105. package/dist/run-daemon.js +5 -5
  106. package/dist/run-daemon.js.map +1 -1
  107. package/dist/runtime.js +912 -823
  108. package/dist/runtime.js.map +4 -4
  109. package/package.json +1 -1
  110. package/dist/acp/native-session-browsers.d.ts.map +0 -1
  111. package/dist/acp/native-session-browsers.js.map +0 -1
  112. package/dist/acp/process-pool.d.ts +0 -17
  113. package/dist/acp/process-pool.d.ts.map +0 -1
  114. package/dist/acp/process-pool.js.map +0 -1
  115. package/dist/acp/process-session.d.ts.map +0 -1
  116. package/dist/acp/process-session.js.map +0 -1
  117. package/dist/acp/retained-sessions.d.ts +0 -21
  118. package/dist/acp/retained-sessions.d.ts.map +0 -1
  119. package/dist/acp/retained-sessions.js.map +0 -1
  120. package/dist/acp/session-executions.d.ts.map +0 -1
  121. package/dist/acp/session-executions.js.map +0 -1
  122. package/dist/acp/session-manager.d.ts.map +0 -1
  123. 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.127",
3384
+ version: "0.0.129",
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
@@ -31035,73 +31162,11 @@ async function replaceImageMarkers(text2, replace) {
31035
31162
  return `${rewritten}${text2.slice(cursor)}`;
31036
31163
  }
31037
31164
 
31038
- // src/acp/activity.ts
31165
+ // src/acp/activity-content.ts
31039
31166
  var TRUNCATION_MARKER = "\n\u2026 output truncated by Mobius";
31040
- var AcpActivityNarration = class {
31041
- activityId;
31042
- activityType;
31043
- sequence;
31044
- text;
31045
- constructor(activityId, activityType, sequence, text2) {
31046
- this.activityId = activityId;
31047
- this.activityType = activityType;
31048
- this.sequence = sequence;
31049
- this.text = text2;
31050
- }
31051
- };
31052
31167
  function isRecord7(value) {
31053
31168
  return typeof value === "object" && value !== null && !Array.isArray(value);
31054
31169
  }
31055
- var AcpActivity = class _AcpActivity {
31056
- activityId;
31057
- activityType;
31058
- input;
31059
- locations;
31060
- name;
31061
- output;
31062
- sequence;
31063
- status;
31064
- title;
31065
- toolKind;
31066
- content;
31067
- detail;
31068
- constructor(activityId, activityType, input2, locations, name, output2, sequence, status, title2, toolKind, content = [], detail = captureActivityDetail(content, input2, output2)) {
31069
- this.activityId = activityId;
31070
- this.activityType = activityType;
31071
- this.input = input2;
31072
- this.locations = locations;
31073
- this.name = name;
31074
- this.output = output2;
31075
- this.sequence = sequence;
31076
- this.status = status;
31077
- this.title = title2;
31078
- this.toolKind = toolKind;
31079
- this.content = content;
31080
- this.detail = detail;
31081
- }
31082
- complete = () => (this.activityType === "progress" || this.activityType === "reasoning") && (this.status === "pending" || this.status === "running") ? new _AcpActivity(
31083
- this.activityId,
31084
- this.activityType,
31085
- this.input,
31086
- this.locations,
31087
- this.name,
31088
- this.output,
31089
- this.sequence,
31090
- "completed",
31091
- this.title,
31092
- this.toolKind,
31093
- this.content,
31094
- this.detail
31095
- ) : this;
31096
- };
31097
- var ActivityIdentity = class {
31098
- id;
31099
- sequence;
31100
- constructor(id, sequence) {
31101
- this.id = id;
31102
- this.sequence = sequence;
31103
- }
31104
- };
31105
31170
  function truncate2(value, maximumLength) {
31106
31171
  if (value.length <= maximumLength) {
31107
31172
  return value;
@@ -31378,275 +31443,8 @@ function contentPhase(content) {
31378
31443
  function isProgressMessage(content) {
31379
31444
  return contentPhase(content) === "commentary";
31380
31445
  }
31381
- var AcpActivityTracker = class {
31382
- #activities = /* @__PURE__ */ new Map();
31383
- #identities = /* @__PURE__ */ new Map();
31384
- #narrations = /* @__PURE__ */ new Map();
31385
- #onActivity;
31386
- #onNarration;
31387
- #prepareContent;
31388
- #activeNarrativeKey = "";
31389
- #nextSequence = 0;
31390
- constructor(onActivity, onNarration, prepareContent = (content) => Promise.resolve(content)) {
31391
- this.#onActivity = onActivity;
31392
- this.#onNarration = onNarration;
31393
- this.#prepareContent = prepareContent;
31394
- }
31395
- recordNarrative = async (activityType, messageId, text2) => {
31396
- const key = `${activityType}:${messageId}`;
31397
- if (this.#activeNarrativeKey !== key) {
31398
- await this.finishNarrative();
31399
- }
31400
- const identity2 = this.#identity(key);
31401
- const previous = this.#narrations.get(key);
31402
- const previousOutput = previous?.output ?? "";
31403
- const remaining = Math.max(0, AGENT_ACTIVITY_DETAIL_LIMIT - previousOutput.length);
31404
- this.#narrations.set(key, {
31405
- activityId: identity2.id,
31406
- activityType,
31407
- output: `${previousOutput}${text2.slice(0, remaining)}`,
31408
- originalBytes: (previous?.originalBytes ?? 0) + new TextEncoder().encode(text2).byteLength,
31409
- sequence: identity2.sequence,
31410
- truncated: (previous?.truncated ?? false) || text2.length > remaining
31411
- });
31412
- if (previous === void 0) {
31413
- await this.#record(key, this.#narrativeSnapshot(identity2, activityType, "", "running"));
31414
- }
31415
- this.#activeNarrativeKey = key;
31416
- if (text2.length > 0) {
31417
- await this.#onNarration(new AcpActivityNarration(identity2.id, activityType, identity2.sequence, text2));
31418
- }
31419
- };
31420
- #narrativeSnapshot = (identity2, activityType, output2, status) => new AcpActivity(
31421
- identity2.id,
31422
- activityType,
31423
- "",
31424
- [],
31425
- "",
31426
- truncate2(output2, AGENT_ACTIVITY_DETAIL_LIMIT),
31427
- identity2.sequence,
31428
- status,
31429
- activityType === "reasoning" ? "Reasoning" : "Progress update",
31430
- activityType === "reasoning" ? "think" : ""
31431
- );
31432
- recordPlan = async (plan) => {
31433
- await this.finishNarrative();
31434
- await this.#recordPlanEntries("plan:default", plan.entries);
31435
- };
31436
- recordPlanUpdate = async (update) => {
31437
- await this.finishNarrative();
31438
- const plan = update.plan;
31439
- const key = `plan:${plan.planId}`;
31440
- if (plan.type === "items") {
31441
- await this.#recordPlanEntries(key, plan.entries);
31442
- return;
31443
- }
31444
- const identity2 = this.#identity(key);
31445
- const output2 = plan.type === "markdown" ? plan.content : `Plan file: ${plan.uri}`;
31446
- await this.#record(
31447
- key,
31448
- new AcpActivity(
31449
- identity2.id,
31450
- "plan",
31451
- "",
31452
- [],
31453
- "",
31454
- truncate2(output2, AGENT_ACTIVITY_DETAIL_LIMIT),
31455
- identity2.sequence,
31456
- "running",
31457
- "Plan",
31458
- ""
31459
- )
31460
- );
31461
- };
31462
- removePlan = async (update) => {
31463
- await this.finishNarrative();
31464
- const key = `plan:${update.planId}`;
31465
- const previous = this.#activities.get(key);
31466
- if (previous !== void 0) {
31467
- await this.#record(
31468
- key,
31469
- new AcpActivity(
31470
- previous.activityId,
31471
- previous.activityType,
31472
- previous.input,
31473
- previous.locations,
31474
- previous.name,
31475
- previous.output,
31476
- previous.sequence,
31477
- "completed",
31478
- previous.title,
31479
- previous.toolKind,
31480
- previous.content,
31481
- previous.detail
31482
- )
31483
- );
31484
- }
31485
- };
31486
- recordToolCall = async (update) => {
31487
- await this.finishNarrative();
31488
- const key = `tool:${update.toolCallId}`;
31489
- const identity2 = this.#identity(key);
31490
- const output2 = update.rawOutput === void 0 ? readContentOutput(update.content) : formatUnknown(update.rawOutput);
31491
- const detailInput = update.rawInput === void 0 ? "" : formatUnknownDetail(update.rawInput);
31492
- const detailOutput = update.rawOutput === void 0 ? readContentOutputDetail(update.content) : formatUnknownDetail(update.rawOutput);
31493
- const detailContent = await normalizeToolContent(
31494
- toolContent(update.content, update.rawOutput),
31495
- this.#prepareContent
31496
- );
31497
- await this.#record(
31498
- key,
31499
- new AcpActivity(
31500
- identity2.id,
31501
- "tool",
31502
- update.rawInput === void 0 ? "" : formatUnknown(update.rawInput),
31503
- normalizeLocations(update.locations ?? []),
31504
- truncate2(update.name ?? "", 128),
31505
- output2,
31506
- identity2.sequence,
31507
- normalizeToolStatus(update.status ?? "pending", "pending"),
31508
- normalizeTitle(update.title, "Tool call"),
31509
- update.kind ?? "other",
31510
- detailContent.slice(0, 100).map(summarizeDisplayContent),
31511
- captureActivityDetail(detailContent, detailInput, detailOutput)
31512
- )
31513
- );
31514
- };
31515
- recordToolCallUpdate = async (update) => {
31516
- await this.finishNarrative();
31517
- const key = `tool:${update.toolCallId}`;
31518
- const previous = this.#activities.get(key);
31519
- const identity2 = this.#identity(key);
31520
- const previousDetail = recordedDetail(previous);
31521
- const output2 = update.rawOutput !== void 0 ? formatUnknown(update.rawOutput) : update.content !== void 0 && update.content !== null ? readContentOutput(update.content) : previous?.output ?? "";
31522
- const nextContent = toolContent(update.content, update.rawOutput);
31523
- const content = nextContent.length === 0 ? previous?.content ?? [] : await normalizeToolContent(nextContent, this.#prepareContent);
31524
- const detailInput = update.rawInput === void 0 ? previousDetail?.input ?? previous?.input ?? "" : formatUnknownDetail(update.rawInput);
31525
- const detailOutput = update.rawOutput !== void 0 ? formatUnknownDetail(update.rawOutput) : update.content !== void 0 && update.content !== null ? readContentOutputDetail(update.content) : previousDetail?.output ?? previous?.output ?? "";
31526
- const detailContent = nextContent.length === 0 ? previousDetail?.content ?? previous?.content ?? [] : content;
31527
- await this.#record(
31528
- key,
31529
- new AcpActivity(
31530
- identity2.id,
31531
- "tool",
31532
- update.rawInput === void 0 ? previous?.input ?? "" : formatUnknown(update.rawInput),
31533
- update.locations === void 0 || update.locations === null ? previous?.locations ?? [] : normalizeLocations(update.locations),
31534
- update.name === void 0 || update.name === null ? previous?.name ?? "" : truncate2(update.name, 128),
31535
- output2,
31536
- identity2.sequence,
31537
- update.status === void 0 || update.status === null ? previous?.status ?? "pending" : normalizeToolStatus(update.status, previous?.status ?? "pending"),
31538
- update.title === void 0 || update.title === null ? previous?.title ?? "Tool call" : normalizeTitle(update.title, "Tool call"),
31539
- update.kind === void 0 || update.kind === null ? previous?.toolKind ?? "other" : update.kind,
31540
- content.slice(0, 100).map(summarizeDisplayContent),
31541
- captureActivityDetail(detailContent, detailInput, detailOutput)
31542
- )
31543
- );
31544
- };
31545
- finishNarrative = async () => {
31546
- const key = this.#activeNarrativeKey;
31547
- if (key.length === 0) {
31548
- return;
31549
- }
31550
- this.#activeNarrativeKey = "";
31551
- await this.#completeNarrative(key);
31552
- };
31553
- finish = async () => {
31554
- await this.finishNarrative();
31555
- for (const key of this.#narrations.keys()) {
31556
- await this.#completeNarrative(key);
31557
- }
31558
- const entries = [...this.#activities.entries()].sort((left, right) => left[1].sequence - right[1].sequence);
31559
- for (const [key, activity2] of entries) {
31560
- const completed = activity2.complete();
31561
- if (completed !== activity2) {
31562
- await this.#record(key, completed);
31563
- }
31564
- }
31565
- };
31566
- // Materialize a streamed narration as one completed snapshot activity. The
31567
- // incremental events carried the text; this final event gives consumers the
31568
- // whole narration with its terminal status, as a single bounded item.
31569
- #completeNarrative = async (key) => {
31570
- const narration = this.#narrations.get(key);
31571
- if (narration === void 0) {
31572
- return;
31573
- }
31574
- this.#narrations.delete(key);
31575
- const previous = this.#activities.get(key);
31576
- const detail = narration.truncated ? {
31577
- capturedBytes: encodedByteLength({ content: [], input: "", output: narration.output }),
31578
- kind: "truncated",
31579
- originalBytes: narration.originalBytes
31580
- } : captureActivityDetail([], "", narration.output);
31581
- await this.#record(
31582
- key,
31583
- new AcpActivity(
31584
- narration.activityId,
31585
- narration.activityType,
31586
- "",
31587
- [],
31588
- "",
31589
- truncate2(narration.output, AGENT_ACTIVITY_DETAIL_LIMIT),
31590
- narration.sequence,
31591
- "completed",
31592
- narration.activityType === "reasoning" ? "Reasoning" : "Progress update",
31593
- narration.activityType === "reasoning" ? "think" : "",
31594
- previous?.content ?? [],
31595
- detail
31596
- )
31597
- );
31598
- };
31599
- #identity = (key) => {
31600
- const existing = this.#identities.get(key);
31601
- if (existing !== void 0) {
31602
- return existing;
31603
- }
31604
- const identity2 = new ActivityIdentity(`activity-${crypto.randomUUID()}`, this.#nextSequence);
31605
- this.#nextSequence += 1;
31606
- this.#identities.set(key, identity2);
31607
- return identity2;
31608
- };
31609
- #record = async (key, activity2) => {
31610
- this.#activities.set(key, activity2);
31611
- await this.#onActivity(activity2);
31612
- };
31613
- #recordPlanEntries = async (key, entries) => {
31614
- const identity2 = this.#identity(key);
31615
- await this.#record(
31616
- key,
31617
- new AcpActivity(
31618
- identity2.id,
31619
- "plan",
31620
- "",
31621
- [],
31622
- "",
31623
- formatPlanEntries(entries),
31624
- identity2.sequence,
31625
- planStatus(entries),
31626
- "Plan",
31627
- ""
31628
- )
31629
- );
31630
- };
31631
- };
31632
-
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
31446
 
31649
- // src/acp/process-endpoint.ts
31447
+ // src/acp/agent-connection.ts
31650
31448
  import { spawn as spawn4 } from "node:child_process";
31651
31449
  import { ndJsonStream as ndJsonStream2, RequestError as RequestError3 } from "@agentclientprotocol/sdk";
31652
31450
 
@@ -31661,7 +31459,7 @@ function readString2(value, fallback = "") {
31661
31459
  return typeof value === "string" ? value : fallback;
31662
31460
  }
31663
31461
 
31664
- // src/acp/process-endpoint.ts
31462
+ // src/acp/agent-connection.ts
31665
31463
  function readableWebStream(input2) {
31666
31464
  let streamOpen = true;
31667
31465
  return new ReadableStream({
@@ -31737,7 +31535,7 @@ function createWritableAcpStream(output2) {
31737
31535
  }
31738
31536
  });
31739
31537
  }
31740
- var AcpEndpoint = class {
31538
+ var AgentConnection = class {
31741
31539
  connection;
31742
31540
  termination;
31743
31541
  #process;
@@ -31844,6 +31642,86 @@ var AcpEndpoint = class {
31844
31642
  };
31845
31643
  };
31846
31644
 
31645
+ // src/acp/native-session.ts
31646
+ var path2 = external_exports.string().min(1).max(2048).refine((value) => !value.includes("\0"));
31647
+ var title = external_exports.string().transform((value) => value.slice(0, 500));
31648
+ var nativeSessionIdSchema = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/);
31649
+ var nativeSessionInfoSchema = external_exports.object({
31650
+ sessionId: nativeSessionIdSchema,
31651
+ cwd: path2,
31652
+ additionalDirectories: external_exports.array(path2).max(16).default([]).readonly(),
31653
+ title: title.nullish(),
31654
+ updatedAt: external_exports.iso.datetime({ offset: true }).nullish()
31655
+ }).readonly();
31656
+ var nativeSessionPageSchema = external_exports.object({
31657
+ sessions: external_exports.array(nativeSessionInfoSchema).max(500).readonly(),
31658
+ nextCursor: external_exports.string().min(1).max(4096).nullish()
31659
+ }).readonly();
31660
+
31661
+ // src/acp/agent-update-stream.ts
31662
+ var MAX_PENDING_UPDATES = 100;
31663
+ var MAX_PENDING_BYTES = 1024 * 1024;
31664
+ var AgentUpdateStream = class {
31665
+ #selection = { kind: "awaiting-session", notifications: [], bytes: 0 };
31666
+ #tail = Promise.resolve();
31667
+ #consume;
31668
+ constructor(consume) {
31669
+ this.#consume = consume;
31670
+ }
31671
+ sessionId = () => this.#selection.kind === "selected" ? this.#selection.sessionId : "";
31672
+ drained = () => this.#tail;
31673
+ #enqueue = (notification) => {
31674
+ this.#tail = this.#tail.then(async () => await this.#consume(notification));
31675
+ return this.#tail;
31676
+ };
31677
+ receive = (notification) => {
31678
+ const selection = this.#selection;
31679
+ switch (selection.kind) {
31680
+ case "selected":
31681
+ return this.#enqueue(notification);
31682
+ case "awaiting-session": {
31683
+ const bytes = selection.bytes + Buffer.byteLength(JSON.stringify(notification));
31684
+ if (selection.notifications.length >= MAX_PENDING_UPDATES || bytes > MAX_PENDING_BYTES) {
31685
+ return Promise.reject(
31686
+ new AcpExecutionError(
31687
+ "ACP agent sent too many updates before creating its session",
31688
+ {},
31689
+ "agent_update_limit"
31690
+ )
31691
+ );
31692
+ }
31693
+ this.#selection = {
31694
+ kind: "awaiting-session",
31695
+ notifications: [...selection.notifications, notification],
31696
+ bytes
31697
+ };
31698
+ return Promise.resolve();
31699
+ }
31700
+ }
31701
+ };
31702
+ select = (sessionId) => {
31703
+ const selected = nativeSessionIdSchema.parse(sessionId);
31704
+ const selection = this.#selection;
31705
+ switch (selection.kind) {
31706
+ case "selected":
31707
+ if (selection.sessionId !== selected) {
31708
+ throw new AcpExecutionError(
31709
+ "ACP agent attempted to replace the selected session",
31710
+ {},
31711
+ "invalid_agent_session"
31712
+ );
31713
+ }
31714
+ return;
31715
+ case "awaiting-session":
31716
+ this.#selection = { kind: "selected", sessionId: selected };
31717
+ for (const notification of selection.notifications) {
31718
+ void this.#enqueue(notification);
31719
+ }
31720
+ return;
31721
+ }
31722
+ };
31723
+ };
31724
+
31847
31725
  // src/acp/session-config/session-config-protocol.ts
31848
31726
  import { methods as methods7 } from "@agentclientprotocol/sdk";
31849
31727
  var MAXIMUM_CONFIG_OPTIONS = 100;
@@ -32087,6 +31965,321 @@ var AcpAgentSettingsSnapshot = class {
32087
31965
  }
32088
31966
  };
32089
31967
 
31968
+ // src/acp/activity.ts
31969
+ var AcpActivityNarration = class {
31970
+ activityId;
31971
+ activityType;
31972
+ sequence;
31973
+ text;
31974
+ constructor(activityId, activityType, sequence, text2) {
31975
+ this.activityId = activityId;
31976
+ this.activityType = activityType;
31977
+ this.sequence = sequence;
31978
+ this.text = text2;
31979
+ }
31980
+ };
31981
+ var AcpActivity = class _AcpActivity {
31982
+ activityId;
31983
+ activityType;
31984
+ input;
31985
+ locations;
31986
+ name;
31987
+ output;
31988
+ sequence;
31989
+ status;
31990
+ title;
31991
+ toolKind;
31992
+ content;
31993
+ detail;
31994
+ constructor(activityId, activityType, input2, locations, name, output2, sequence, status, title2, toolKind, content = [], detail = captureActivityDetail(content, input2, output2)) {
31995
+ this.activityId = activityId;
31996
+ this.activityType = activityType;
31997
+ this.input = input2;
31998
+ this.locations = locations;
31999
+ this.name = name;
32000
+ this.output = output2;
32001
+ this.sequence = sequence;
32002
+ this.status = status;
32003
+ this.title = title2;
32004
+ this.toolKind = toolKind;
32005
+ this.content = content;
32006
+ this.detail = detail;
32007
+ }
32008
+ complete = () => (this.activityType === "progress" || this.activityType === "reasoning") && (this.status === "pending" || this.status === "running") ? new _AcpActivity(
32009
+ this.activityId,
32010
+ this.activityType,
32011
+ this.input,
32012
+ this.locations,
32013
+ this.name,
32014
+ this.output,
32015
+ this.sequence,
32016
+ "completed",
32017
+ this.title,
32018
+ this.toolKind,
32019
+ this.content,
32020
+ this.detail
32021
+ ) : this;
32022
+ };
32023
+ var ActivityIdentity = class {
32024
+ id;
32025
+ sequence;
32026
+ constructor(id, sequence) {
32027
+ this.id = id;
32028
+ this.sequence = sequence;
32029
+ }
32030
+ };
32031
+ var AcpActivityTracker = class {
32032
+ #activities = /* @__PURE__ */ new Map();
32033
+ #identities = /* @__PURE__ */ new Map();
32034
+ #narrations = /* @__PURE__ */ new Map();
32035
+ #onActivity;
32036
+ #onNarration;
32037
+ #prepareContent;
32038
+ #activeNarrativeKey = "";
32039
+ #nextSequence = 0;
32040
+ constructor(onActivity, onNarration, prepareContent = (content) => Promise.resolve(content)) {
32041
+ this.#onActivity = onActivity;
32042
+ this.#onNarration = onNarration;
32043
+ this.#prepareContent = prepareContent;
32044
+ }
32045
+ recordNarrative = async (activityType, messageId, text2) => {
32046
+ const key = `${activityType}:${messageId}`;
32047
+ if (this.#activeNarrativeKey !== key) {
32048
+ await this.finishNarrative();
32049
+ }
32050
+ const identity2 = this.#identity(key);
32051
+ const previous = this.#narrations.get(key);
32052
+ const previousOutput = previous?.output ?? "";
32053
+ const remaining = Math.max(0, AGENT_ACTIVITY_DETAIL_LIMIT - previousOutput.length);
32054
+ this.#narrations.set(key, {
32055
+ activityId: identity2.id,
32056
+ activityType,
32057
+ output: `${previousOutput}${text2.slice(0, remaining)}`,
32058
+ originalBytes: (previous?.originalBytes ?? 0) + new TextEncoder().encode(text2).byteLength,
32059
+ sequence: identity2.sequence,
32060
+ truncated: (previous?.truncated ?? false) || text2.length > remaining
32061
+ });
32062
+ if (previous === void 0) {
32063
+ await this.#record(key, this.#narrativeSnapshot(identity2, activityType, "", "running"));
32064
+ }
32065
+ this.#activeNarrativeKey = key;
32066
+ if (text2.length > 0) {
32067
+ await this.#onNarration(new AcpActivityNarration(identity2.id, activityType, identity2.sequence, text2));
32068
+ }
32069
+ };
32070
+ #narrativeSnapshot = (identity2, activityType, output2, status) => new AcpActivity(
32071
+ identity2.id,
32072
+ activityType,
32073
+ "",
32074
+ [],
32075
+ "",
32076
+ truncate2(output2, AGENT_ACTIVITY_DETAIL_LIMIT),
32077
+ identity2.sequence,
32078
+ status,
32079
+ activityType === "reasoning" ? "Reasoning" : "Progress update",
32080
+ activityType === "reasoning" ? "think" : ""
32081
+ );
32082
+ recordPlan = async (plan) => {
32083
+ await this.finishNarrative();
32084
+ await this.#recordPlanEntries("plan:default", plan.entries);
32085
+ };
32086
+ recordPlanUpdate = async (update) => {
32087
+ await this.finishNarrative();
32088
+ const plan = update.plan;
32089
+ const key = `plan:${plan.planId}`;
32090
+ if (plan.type === "items") {
32091
+ await this.#recordPlanEntries(key, plan.entries);
32092
+ return;
32093
+ }
32094
+ const identity2 = this.#identity(key);
32095
+ const output2 = plan.type === "markdown" ? plan.content : `Plan file: ${plan.uri}`;
32096
+ await this.#record(
32097
+ key,
32098
+ new AcpActivity(
32099
+ identity2.id,
32100
+ "plan",
32101
+ "",
32102
+ [],
32103
+ "",
32104
+ truncate2(output2, AGENT_ACTIVITY_DETAIL_LIMIT),
32105
+ identity2.sequence,
32106
+ "running",
32107
+ "Plan",
32108
+ ""
32109
+ )
32110
+ );
32111
+ };
32112
+ removePlan = async (update) => {
32113
+ await this.finishNarrative();
32114
+ const key = `plan:${update.planId}`;
32115
+ const previous = this.#activities.get(key);
32116
+ if (previous !== void 0) {
32117
+ await this.#record(
32118
+ key,
32119
+ new AcpActivity(
32120
+ previous.activityId,
32121
+ previous.activityType,
32122
+ previous.input,
32123
+ previous.locations,
32124
+ previous.name,
32125
+ previous.output,
32126
+ previous.sequence,
32127
+ "completed",
32128
+ previous.title,
32129
+ previous.toolKind,
32130
+ previous.content,
32131
+ previous.detail
32132
+ )
32133
+ );
32134
+ }
32135
+ };
32136
+ recordToolCall = async (update) => {
32137
+ await this.finishNarrative();
32138
+ const key = `tool:${update.toolCallId}`;
32139
+ const identity2 = this.#identity(key);
32140
+ const output2 = update.rawOutput === void 0 ? readContentOutput(update.content) : formatUnknown(update.rawOutput);
32141
+ const detailInput = update.rawInput === void 0 ? "" : formatUnknownDetail(update.rawInput);
32142
+ const detailOutput = update.rawOutput === void 0 ? readContentOutputDetail(update.content) : formatUnknownDetail(update.rawOutput);
32143
+ const detailContent = await normalizeToolContent(
32144
+ toolContent(update.content, update.rawOutput),
32145
+ this.#prepareContent
32146
+ );
32147
+ await this.#record(
32148
+ key,
32149
+ new AcpActivity(
32150
+ identity2.id,
32151
+ "tool",
32152
+ update.rawInput === void 0 ? "" : formatUnknown(update.rawInput),
32153
+ normalizeLocations(update.locations ?? []),
32154
+ truncate2(update.name ?? "", 128),
32155
+ output2,
32156
+ identity2.sequence,
32157
+ normalizeToolStatus(update.status ?? "pending", "pending"),
32158
+ normalizeTitle(update.title, "Tool call"),
32159
+ update.kind ?? "other",
32160
+ detailContent.slice(0, 100).map(summarizeDisplayContent),
32161
+ captureActivityDetail(detailContent, detailInput, detailOutput)
32162
+ )
32163
+ );
32164
+ };
32165
+ recordToolCallUpdate = async (update) => {
32166
+ await this.finishNarrative();
32167
+ const key = `tool:${update.toolCallId}`;
32168
+ const previous = this.#activities.get(key);
32169
+ const identity2 = this.#identity(key);
32170
+ const previousDetail = recordedDetail(previous);
32171
+ const output2 = update.rawOutput !== void 0 ? formatUnknown(update.rawOutput) : update.content !== void 0 && update.content !== null ? readContentOutput(update.content) : previous?.output ?? "";
32172
+ const nextContent = toolContent(update.content, update.rawOutput);
32173
+ const content = nextContent.length === 0 ? previous?.content ?? [] : await normalizeToolContent(nextContent, this.#prepareContent);
32174
+ const detailInput = update.rawInput === void 0 ? previousDetail?.input ?? previous?.input ?? "" : formatUnknownDetail(update.rawInput);
32175
+ const detailOutput = update.rawOutput !== void 0 ? formatUnknownDetail(update.rawOutput) : update.content !== void 0 && update.content !== null ? readContentOutputDetail(update.content) : previousDetail?.output ?? previous?.output ?? "";
32176
+ const detailContent = nextContent.length === 0 ? previousDetail?.content ?? previous?.content ?? [] : content;
32177
+ await this.#record(
32178
+ key,
32179
+ new AcpActivity(
32180
+ identity2.id,
32181
+ "tool",
32182
+ update.rawInput === void 0 ? previous?.input ?? "" : formatUnknown(update.rawInput),
32183
+ update.locations === void 0 || update.locations === null ? previous?.locations ?? [] : normalizeLocations(update.locations),
32184
+ update.name === void 0 || update.name === null ? previous?.name ?? "" : truncate2(update.name, 128),
32185
+ output2,
32186
+ identity2.sequence,
32187
+ update.status === void 0 || update.status === null ? previous?.status ?? "pending" : normalizeToolStatus(update.status, previous?.status ?? "pending"),
32188
+ update.title === void 0 || update.title === null ? previous?.title ?? "Tool call" : normalizeTitle(update.title, "Tool call"),
32189
+ update.kind === void 0 || update.kind === null ? previous?.toolKind ?? "other" : update.kind,
32190
+ content.slice(0, 100).map(summarizeDisplayContent),
32191
+ captureActivityDetail(detailContent, detailInput, detailOutput)
32192
+ )
32193
+ );
32194
+ };
32195
+ finishNarrative = async () => {
32196
+ const key = this.#activeNarrativeKey;
32197
+ if (key.length === 0) {
32198
+ return;
32199
+ }
32200
+ this.#activeNarrativeKey = "";
32201
+ await this.#completeNarrative(key);
32202
+ };
32203
+ finish = async () => {
32204
+ await this.finishNarrative();
32205
+ for (const key of this.#narrations.keys()) {
32206
+ await this.#completeNarrative(key);
32207
+ }
32208
+ const entries = [...this.#activities.entries()].sort((left, right) => left[1].sequence - right[1].sequence);
32209
+ for (const [key, activity2] of entries) {
32210
+ const completed = activity2.complete();
32211
+ if (completed !== activity2) {
32212
+ await this.#record(key, completed);
32213
+ }
32214
+ }
32215
+ };
32216
+ // Materialize a streamed narration as one completed snapshot activity. The
32217
+ // incremental events carried the text; this final event gives consumers the
32218
+ // whole narration with its terminal status, as a single bounded item.
32219
+ #completeNarrative = async (key) => {
32220
+ const narration = this.#narrations.get(key);
32221
+ if (narration === void 0) {
32222
+ return;
32223
+ }
32224
+ this.#narrations.delete(key);
32225
+ const previous = this.#activities.get(key);
32226
+ const detail = narration.truncated ? {
32227
+ capturedBytes: encodedByteLength({ content: [], input: "", output: narration.output }),
32228
+ kind: "truncated",
32229
+ originalBytes: narration.originalBytes
32230
+ } : captureActivityDetail([], "", narration.output);
32231
+ await this.#record(
32232
+ key,
32233
+ new AcpActivity(
32234
+ narration.activityId,
32235
+ narration.activityType,
32236
+ "",
32237
+ [],
32238
+ "",
32239
+ truncate2(narration.output, AGENT_ACTIVITY_DETAIL_LIMIT),
32240
+ narration.sequence,
32241
+ "completed",
32242
+ narration.activityType === "reasoning" ? "Reasoning" : "Progress update",
32243
+ narration.activityType === "reasoning" ? "think" : "",
32244
+ previous?.content ?? [],
32245
+ detail
32246
+ )
32247
+ );
32248
+ };
32249
+ #identity = (key) => {
32250
+ const existing = this.#identities.get(key);
32251
+ if (existing !== void 0) {
32252
+ return existing;
32253
+ }
32254
+ const identity2 = new ActivityIdentity(`activity-${crypto.randomUUID()}`, this.#nextSequence);
32255
+ this.#nextSequence += 1;
32256
+ this.#identities.set(key, identity2);
32257
+ return identity2;
32258
+ };
32259
+ #record = async (key, activity2) => {
32260
+ this.#activities.set(key, activity2);
32261
+ await this.#onActivity(activity2);
32262
+ };
32263
+ #recordPlanEntries = async (key, entries) => {
32264
+ const identity2 = this.#identity(key);
32265
+ await this.#record(
32266
+ key,
32267
+ new AcpActivity(
32268
+ identity2.id,
32269
+ "plan",
32270
+ "",
32271
+ [],
32272
+ "",
32273
+ formatPlanEntries(entries),
32274
+ identity2.sequence,
32275
+ planStatus(entries),
32276
+ "Plan",
32277
+ ""
32278
+ )
32279
+ );
32280
+ };
32281
+ };
32282
+
32090
32283
  // src/acp/session-history.ts
32091
32284
  var HISTORY_ACTIVITY_FIELD_LIMIT = 1e5;
32092
32285
  var HISTORY_ACTIVITY_LIMIT = 100;
@@ -38462,10 +38655,8 @@ var SqliteAcpSessionStore = class {
38462
38655
  };
38463
38656
  };
38464
38657
 
38465
- // src/acp/process-session.ts
38658
+ // src/acp/agent-session.ts
38466
38659
  var PROCESS_STOP_TIMEOUT_MILLISECONDS = 1e3;
38467
- var MAX_PRE_SESSION_UPDATES = 100;
38468
- var MAX_PRE_SESSION_UPDATE_BYTES = 1024 * 1024;
38469
38660
  var RetryableAcpInitializationError = class extends AcpExecutionError {
38470
38661
  constructor(cause) {
38471
38662
  super("ACP agent initialization failed", { cause });
@@ -38480,8 +38671,8 @@ function recordsEqual(left, right) {
38480
38671
  const rightEntries = Object.entries(right);
38481
38672
  return leftEntries.length === rightEntries.length && leftEntries.every(([name, value]) => right[name] === value);
38482
38673
  }
38483
- var AcpProcessSession = class _AcpProcessSession {
38484
- #endpoint;
38674
+ var AgentSession = class _AgentSession {
38675
+ #connection;
38485
38676
  #interactions;
38486
38677
  #additionalDirectories;
38487
38678
  #agentId;
@@ -38489,12 +38680,11 @@ var AcpProcessSession = class _AcpProcessSession {
38489
38680
  #environment;
38490
38681
  #getObserver;
38491
38682
  #mobiusSessionId;
38492
- #preSessionUpdates = [];
38683
+ #updates;
38493
38684
  #metrics;
38494
38685
  #sessionConfigProtocol;
38495
38686
  #store;
38496
38687
  #verifiedAgentVersion;
38497
- #preSessionUpdateBytes = 0;
38498
38688
  #agentName = "";
38499
38689
  #agentVersion = "";
38500
38690
  #bufferedAgentText = [];
@@ -38502,7 +38692,6 @@ var AcpProcessSession = class _AcpProcessSession {
38502
38692
  #commands = [];
38503
38693
  #configRevision = 0;
38504
38694
  #configOptions = [];
38505
- #nativeSessionId = "";
38506
38695
  #prompted = false;
38507
38696
  #nativePrompt = null;
38508
38697
  #replay = {
@@ -38512,10 +38701,11 @@ var AcpProcessSession = class _AcpProcessSession {
38512
38701
  #sessionTitle = null;
38513
38702
  #sessionUpdatedAt = "";
38514
38703
  #turn = new IdleAcpTurn();
38515
- #updateTail = Promise.resolve();
38516
38704
  constructor(agent, cwd, additionalDirectories, mobiusSessionId, getObserver, store, metrics) {
38705
+ this.#updates = new AgentUpdateStream((notification) => this.#processUpdate(notification));
38517
38706
  this.#additionalDirectories = [...additionalDirectories];
38518
38707
  this.#agentId = agent.id;
38708
+ this.#commands = [];
38519
38709
  this.#cwd = cwd;
38520
38710
  this.#environment = agent.environment;
38521
38711
  this.#getObserver = getObserver;
@@ -38530,7 +38720,7 @@ var AcpProcessSession = class _AcpProcessSession {
38530
38720
  assertNativeSession: (sessionId) => this.assertNativeSession(sessionId),
38531
38721
  observer: getObserver
38532
38722
  });
38533
- this.#endpoint = new AcpEndpoint(agent, cwd, this);
38723
+ this.#connection = new AgentConnection(agent, cwd, this);
38534
38724
  }
38535
38725
  static async #start(options, getObserver, store, initialize, metrics) {
38536
38726
  for (let attempt = 1; attempt <= 2; attempt += 1) {
@@ -38553,7 +38743,7 @@ var AcpProcessSession = class _AcpProcessSession {
38553
38743
  }
38554
38744
  const runtime = metrics.measureSync(
38555
38745
  "process-spawn",
38556
- () => new _AcpProcessSession(
38746
+ () => new _AgentSession(
38557
38747
  options.agent,
38558
38748
  options.cwd,
38559
38749
  options.additionalDirectories,
@@ -38583,14 +38773,14 @@ var AcpProcessSession = class _AcpProcessSession {
38583
38773
  }
38584
38774
  throw new AcpExecutionError("ACP agent initialization failed");
38585
38775
  }
38586
- static start = async (options, getObserver, store, metrics = unmeasuredOperationMetrics) => await _AcpProcessSession.#start(
38776
+ static start = async (options, getObserver, store, metrics = unmeasuredOperationMetrics) => await _AgentSession.#start(
38587
38777
  options,
38588
38778
  getObserver,
38589
38779
  store,
38590
38780
  async (runtime) => await runtime.initialize(options.signal, options.origin),
38591
38781
  metrics
38592
38782
  );
38593
- static startNativeSessionBrowser = async (options, getObserver, store) => await _AcpProcessSession.#start(
38783
+ static startNativeSessionBrowser = async (options, getObserver, store) => await _AgentSession.#start(
38594
38784
  options,
38595
38785
  getObserver,
38596
38786
  store,
@@ -38623,20 +38813,20 @@ var AcpProcessSession = class _AcpProcessSession {
38623
38813
  this.#replay = { kind: "capture", history };
38624
38814
  try {
38625
38815
  await this.race(
38626
- this.#endpoint.connection.agent.request(
38816
+ this.#connection.connection.agent.request(
38627
38817
  methods8.agent.session.load,
38628
38818
  {
38629
38819
  additionalDirectories: [...this.#additionalDirectories],
38630
38820
  cwd: this.#cwd,
38631
38821
  mcpServers: [],
38632
- sessionId: this.#nativeSessionId
38822
+ sessionId: this.#updates.sessionId()
38633
38823
  },
38634
38824
  { cancellationSignal: signal }
38635
38825
  ),
38636
38826
  "ACP agent exited while loading history",
38637
38827
  signal
38638
38828
  );
38639
- await this.#updateTail;
38829
+ await this.#updates.drained();
38640
38830
  signal.throwIfAborted();
38641
38831
  return await embedLocalHistoryImages(await history.snapshot(), signal);
38642
38832
  } finally {
@@ -38732,9 +38922,9 @@ var AcpProcessSession = class _AcpProcessSession {
38732
38922
  await this.#metrics.measure("agent-initialize", async () => await this.#initializeAgentOperation(signal));
38733
38923
  }
38734
38924
  async #initializeAgentOperation(signal) {
38735
- if (this.#endpoint.inProcessAgent !== null) {
38925
+ if (this.#connection.inProcessAgent !== null) {
38736
38926
  await this.race(
38737
- this.#endpoint.inProcessAgent.initialize(signal),
38927
+ this.#connection.inProcessAgent.initialize(signal),
38738
38928
  "The Codex app-server exited during initialization",
38739
38929
  signal
38740
38930
  ).catch((cause) => {
@@ -38743,7 +38933,7 @@ var AcpProcessSession = class _AcpProcessSession {
38743
38933
  });
38744
38934
  }
38745
38935
  const initialized = await this.race(
38746
- this.#endpoint.connection.agent.request(
38936
+ this.#connection.connection.agent.request(
38747
38937
  methods8.agent.initialize,
38748
38938
  {
38749
38939
  clientCapabilities: {
@@ -38822,7 +39012,7 @@ var AcpProcessSession = class _AcpProcessSession {
38822
39012
  const forked = await this.#metrics.measure(
38823
39013
  "session-fork",
38824
39014
  async () => await this.race(
38825
- this.#endpoint.connection.agent.request(
39015
+ this.#connection.connection.agent.request(
38826
39016
  methods8.agent.session.fork,
38827
39017
  {
38828
39018
  sessionId: nativeSessionIdSchema.parse(origin.nativeSessionId),
@@ -38837,7 +39027,7 @@ var AcpProcessSession = class _AcpProcessSession {
38837
39027
  )
38838
39028
  );
38839
39029
  this.selectNativeSession(forked.sessionId);
38840
- if (this.#nativeSessionId === origin.nativeSessionId || this.#store.findNative(this.#agentId, this.#nativeSessionId).length > 0) {
39030
+ if (this.#updates.sessionId() === origin.nativeSessionId || this.#store.findNative(this.#agentId, this.#updates.sessionId()).length > 0) {
38841
39031
  throw new AcpExecutionError(
38842
39032
  "The Agent did not create an independent fork",
38843
39033
  {},
@@ -38856,13 +39046,13 @@ var AcpProcessSession = class _AcpProcessSession {
38856
39046
  lifecycleResponse = await this.#metrics.measure(
38857
39047
  "session-resume",
38858
39048
  async () => await this.race(
38859
- this.#endpoint.connection.agent.request(
39049
+ this.#connection.connection.agent.request(
38860
39050
  methods8.agent.session.resume,
38861
39051
  {
38862
39052
  additionalDirectories: [...this.#additionalDirectories],
38863
39053
  cwd: this.#cwd,
38864
39054
  mcpServers: [],
38865
- sessionId: this.#nativeSessionId
39055
+ sessionId: this.#updates.sessionId()
38866
39056
  },
38867
39057
  { cancellationSignal: signal }
38868
39058
  ),
@@ -38876,13 +39066,13 @@ var AcpProcessSession = class _AcpProcessSession {
38876
39066
  lifecycleResponse = await this.#metrics.measure(
38877
39067
  "session-load",
38878
39068
  async () => await this.race(
38879
- this.#endpoint.connection.agent.request(
39069
+ this.#connection.connection.agent.request(
38880
39070
  methods8.agent.session.load,
38881
39071
  {
38882
39072
  additionalDirectories: [...this.#additionalDirectories],
38883
39073
  cwd: this.#cwd,
38884
39074
  mcpServers: [],
38885
- sessionId: this.#nativeSessionId
39075
+ sessionId: this.#updates.sessionId()
38886
39076
  },
38887
39077
  { cancellationSignal: signal }
38888
39078
  ),
@@ -38891,7 +39081,7 @@ var AcpProcessSession = class _AcpProcessSession {
38891
39081
  )
38892
39082
  );
38893
39083
  } finally {
38894
- await this.#updateTail;
39084
+ await this.#updates.drained();
38895
39085
  this.#replay = { kind: "idle" };
38896
39086
  }
38897
39087
  } else {
@@ -38915,7 +39105,7 @@ var AcpProcessSession = class _AcpProcessSession {
38915
39105
  const created = await this.#metrics.measure(
38916
39106
  "session-new",
38917
39107
  async () => await this.race(
38918
- this.#endpoint.connection.agent.request(
39108
+ this.#connection.connection.agent.request(
38919
39109
  methods8.agent.session.new,
38920
39110
  {
38921
39111
  additionalDirectories: [...this.#additionalDirectories],
@@ -38932,13 +39122,13 @@ var AcpProcessSession = class _AcpProcessSession {
38932
39122
  lifecycleResponse = created;
38933
39123
  }
38934
39124
  this.#configOptions = this.#sessionConfigProtocol.normalizeLifecycle(lifecycleResponse);
38935
- await this.#updateTail;
39125
+ await this.#updates.drained();
38936
39126
  signal.throwIfAborted();
38937
39127
  this.#store.write(
38938
39128
  new AcpStoredSession(
38939
39129
  this.#mobiusSessionId,
38940
39130
  this.#agentId,
38941
- this.#nativeSessionId,
39131
+ this.#updates.sessionId(),
38942
39132
  this.#cwd,
38943
39133
  this.#additionalDirectories,
38944
39134
  this.#prompted,
@@ -38955,7 +39145,7 @@ var AcpProcessSession = class _AcpProcessSession {
38955
39145
  );
38956
39146
  }
38957
39147
  const response = await this.race(
38958
- this.#endpoint.connection.agent.request(methods8.agent.session.list, cursor === null ? {} : { cursor }, {
39148
+ this.#connection.connection.agent.request(methods8.agent.session.list, cursor === null ? {} : { cursor }, {
38959
39149
  cancellationSignal: signal
38960
39150
  }),
38961
39151
  "ACP agent exited while listing sessions",
@@ -38980,7 +39170,7 @@ var AcpProcessSession = class _AcpProcessSession {
38980
39170
  );
38981
39171
  }
38982
39172
  await this.race(
38983
- this.#endpoint.connection.agent.request(
39173
+ this.#connection.connection.agent.request(
38984
39174
  methods8.agent.session.delete,
38985
39175
  { sessionId: nativeSessionIdSchema.parse(nativeSessionId) },
38986
39176
  { cancellationSignal: signal }
@@ -38989,9 +39179,9 @@ var AcpProcessSession = class _AcpProcessSession {
38989
39179
  signal
38990
39180
  );
38991
39181
  };
38992
- nativeSessionId = () => this.#nativeSessionId;
39182
+ nativeSessionId = () => this.#updates.sessionId();
38993
39183
  adoptNativeSessionId = (sessionId) => {
38994
- if (this.#prompted || this.#nativeSessionId !== sessionId) {
39184
+ if (this.#prompted || this.#updates.sessionId() !== sessionId) {
38995
39185
  throw new AcpExecutionError("The new native Session cannot be adopted", {}, "session_identity_mismatch");
38996
39186
  }
38997
39187
  const previousSessionId = this.#mobiusSessionId;
@@ -39039,10 +39229,10 @@ var AcpProcessSession = class _AcpProcessSession {
39039
39229
  const configured = await this.#sessionConfigProtocol.configure(
39040
39230
  this.#configOptions,
39041
39231
  options,
39042
- this.#nativeSessionId,
39232
+ this.#updates.sessionId(),
39043
39233
  {
39044
39234
  request: async (method, params, failureMessage, signal) => await this.race(
39045
- this.#endpoint.connection.agent.request(method, params, {
39235
+ this.#connection.connection.agent.request(method, params, {
39046
39236
  cancellationSignal: signal
39047
39237
  }),
39048
39238
  failureMessage,
@@ -39058,7 +39248,7 @@ var AcpProcessSession = class _AcpProcessSession {
39058
39248
  "invalid_session_configuration"
39059
39249
  );
39060
39250
  }
39061
- await this.#updateTail;
39251
+ await this.#updates.drained();
39062
39252
  if (this.#configRevision === configRevision) {
39063
39253
  this.#configOptions = configured;
39064
39254
  }
@@ -39123,7 +39313,7 @@ var AcpProcessSession = class _AcpProcessSession {
39123
39313
  };
39124
39314
  nativeHistoryTurn = () => {
39125
39315
  const prompt = this.#nativePrompt;
39126
- const nativeTurnId = this.#endpoint.inProcessAgent?.nativeTurnId?.() ?? null;
39316
+ const nativeTurnId = this.#connection.inProcessAgent?.nativeTurnId?.() ?? null;
39127
39317
  return prompt === null || nativeTurnId === null || nativeTurnId === prompt.previousTurnId ? null : { commandId: prompt.commandId, nativeTurnId };
39128
39318
  };
39129
39319
  prompt = async (options) => {
@@ -39138,7 +39328,7 @@ var AcpProcessSession = class _AcpProcessSession {
39138
39328
  new AcpStoredSession(
39139
39329
  this.#mobiusSessionId,
39140
39330
  this.#agentId,
39141
- this.#nativeSessionId,
39331
+ this.#updates.sessionId(),
39142
39332
  this.#cwd,
39143
39333
  this.#additionalDirectories,
39144
39334
  true,
@@ -39156,19 +39346,19 @@ var AcpProcessSession = class _AcpProcessSession {
39156
39346
  this.#turn = running;
39157
39347
  this.#nativePrompt = {
39158
39348
  commandId: options.commandId,
39159
- previousTurnId: this.#endpoint.inProcessAgent?.nativeTurnId?.() ?? null
39349
+ previousTurnId: this.#connection.inProcessAgent?.nativeTurnId?.() ?? null
39160
39350
  };
39161
39351
  try {
39162
39352
  const response = await this.race(
39163
- this.#endpoint.connection.agent.request(
39353
+ this.#connection.connection.agent.request(
39164
39354
  methods8.agent.session.prompt,
39165
- { prompt, sessionId: this.#nativeSessionId },
39355
+ { prompt, sessionId: this.#updates.sessionId() },
39166
39356
  { cancellationSignal: options.signal }
39167
39357
  ),
39168
39358
  "ACP agent exited during a prompt",
39169
39359
  options.signal
39170
39360
  );
39171
- await this.#updateTail;
39361
+ await this.#updates.drained();
39172
39362
  await this.flushAgentText();
39173
39363
  await running.activities.finish();
39174
39364
  let result;
@@ -39218,10 +39408,10 @@ var AcpProcessSession = class _AcpProcessSession {
39218
39408
  }
39219
39409
  const prompt = this.buildPrompt(options);
39220
39410
  const response = await this.race(
39221
- this.#endpoint.connection.agent.request("_session/steering", {
39411
+ this.#connection.connection.agent.request("_session/steering", {
39222
39412
  _meta: { steering: { idleBehavior: "promptRequired" } },
39223
39413
  prompt,
39224
- sessionId: this.#nativeSessionId
39414
+ sessionId: this.#updates.sessionId()
39225
39415
  }),
39226
39416
  "ACP agent exited during steering",
39227
39417
  options.signal
@@ -39254,12 +39444,12 @@ var AcpProcessSession = class _AcpProcessSession {
39254
39444
  );
39255
39445
  };
39256
39446
  cancel = async () => {
39257
- const capturedProcesses = await this.#endpoint.captureProcessTree();
39447
+ const capturedProcesses = await this.#connection.captureProcessTree();
39258
39448
  try {
39259
39449
  await this.#interactions.cancelPendingInteractions();
39260
39450
  if (this.#turn.running) {
39261
- await this.#endpoint.connection.agent.notify(methods8.agent.session.cancel, {
39262
- sessionId: this.#nativeSessionId
39451
+ await this.#connection.connection.agent.notify(methods8.agent.session.cancel, {
39452
+ sessionId: this.#updates.sessionId()
39263
39453
  });
39264
39454
  }
39265
39455
  } finally {
@@ -39271,45 +39461,9 @@ var AcpProcessSession = class _AcpProcessSession {
39271
39461
  onPermission = (request, signal) => this.#interactions.onPermission(request, signal);
39272
39462
  onElicitation = (request, signal) => this.#interactions.onElicitation(request, signal);
39273
39463
  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) => {
39464
+ onUpdate = (notification) => this.#updates.receive(notification);
39465
+ selectNativeSession = (sessionId) => this.#updates.select(sessionId);
39466
+ #processUpdate = async (notification) => {
39313
39467
  this.assertNativeSession(notification.sessionId);
39314
39468
  const update = notification.update;
39315
39469
  if (this.#replay.kind === "capture") {
@@ -39379,7 +39533,7 @@ var AcpProcessSession = class _AcpProcessSession {
39379
39533
  })).filter((command) => command.name.length > 0);
39380
39534
  this.#commands = commands;
39381
39535
  await this.#getObserver().onCommands({
39382
- commands,
39536
+ commands: this.#commands,
39383
39537
  kind: SESSION_COMMANDS_UPDATED_KIND,
39384
39538
  sessionId: this.#mobiusSessionId
39385
39539
  });
@@ -39409,12 +39563,12 @@ var AcpProcessSession = class _AcpProcessSession {
39409
39563
  if (Object.hasOwn(update, "updatedAt")) {
39410
39564
  this.#sessionUpdatedAt = truncate3(update.updatedAt ?? "", 128);
39411
39565
  }
39412
- if (this.#nativeSessionId.length > 0) {
39566
+ if (this.#updates.sessionId().length > 0) {
39413
39567
  this.#store.write(
39414
39568
  new AcpStoredSession(
39415
39569
  this.#mobiusSessionId,
39416
39570
  this.#agentId,
39417
- this.#nativeSessionId,
39571
+ this.#updates.sessionId(),
39418
39572
  this.#cwd,
39419
39573
  this.#additionalDirectories,
39420
39574
  this.#prompted,
@@ -39446,11 +39600,11 @@ var AcpProcessSession = class _AcpProcessSession {
39446
39600
  close = async () => {
39447
39601
  try {
39448
39602
  await this.#interactions.cancelPendingInteractions();
39449
- if (this.#capabilities.closeSession && this.#nativeSessionId.length > 0) {
39603
+ if (this.#capabilities.closeSession && this.#updates.sessionId().length > 0) {
39450
39604
  try {
39451
- await this.#endpoint.connection.agent.request(
39605
+ await this.#connection.connection.agent.request(
39452
39606
  methods8.agent.session.close,
39453
- { sessionId: this.#nativeSessionId },
39607
+ { sessionId: this.#updates.sessionId() },
39454
39608
  {
39455
39609
  cancellationSignal: AbortSignal.timeout(PROCESS_STOP_TIMEOUT_MILLISECONDS)
39456
39610
  }
@@ -39462,10 +39616,10 @@ var AcpProcessSession = class _AcpProcessSession {
39462
39616
  await this.closeProcess();
39463
39617
  }
39464
39618
  };
39465
- closeProcess = (capturedProcesses = []) => this.#endpoint.closeProcess(capturedProcesses);
39466
- race = (operation, exitMessage, signal) => this.#endpoint.race(operation, exitMessage, signal);
39619
+ closeProcess = (capturedProcesses = []) => this.#connection.closeProcess(capturedProcesses);
39620
+ race = (operation, exitMessage, signal) => this.#connection.race(operation, exitMessage, signal);
39467
39621
  assertNativeSession = (sessionId) => {
39468
- if (sessionId !== this.#nativeSessionId) {
39622
+ if (sessionId !== this.#updates.sessionId()) {
39469
39623
  throw new AcpExecutionError("ACP agent referenced an unknown session", {}, "invalid_agent_session");
39470
39624
  }
39471
39625
  };
@@ -39479,8 +39633,8 @@ var AcpProcessSession = class _AcpProcessSession {
39479
39633
  };
39480
39634
  };
39481
39635
 
39482
- // src/acp/retained-sessions.ts
39483
- var RetainedSessions = class {
39636
+ // src/acp/retained-agent-processes.ts
39637
+ var RetainedAgentProcesses = class {
39484
39638
  #entries = /* @__PURE__ */ new Map();
39485
39639
  #events;
39486
39640
  constructor(events) {
@@ -39583,18 +39737,21 @@ var RetainedSessions = class {
39583
39737
  };
39584
39738
  };
39585
39739
 
39586
- // src/acp/native-session-browsers.ts
39587
- var NativeSessionBrowsers = class {
39588
- #sessions;
39740
+ // src/acp/agent-query-processes.ts
39741
+ var AgentQueryProcesses = class {
39742
+ #processesByQuery;
39589
39743
  #processes;
39590
39744
  #observer = new NullAcpSessionObserver();
39591
39745
  #store = new MemoryAcpSessionStore();
39592
39746
  constructor(processes) {
39593
39747
  this.#processes = processes;
39594
- this.#sessions = new RetainedSessions({ touch: processes.touch, changed: processes.notifyChanged });
39748
+ this.#processesByQuery = new RetainedAgentProcesses({
39749
+ touch: processes.touch,
39750
+ changed: processes.notifyChanged
39751
+ });
39595
39752
  }
39596
39753
  retire = async (sessionId, runtime) => {
39597
- const retained = this.#sessions.detach(sessionId, runtime);
39754
+ const retained = this.#processesByQuery.detach(sessionId, runtime);
39598
39755
  if (retained) {
39599
39756
  this.#store.remove(sessionId);
39600
39757
  }
@@ -39603,40 +39760,40 @@ var NativeSessionBrowsers = class {
39603
39760
  async #startRetained(options) {
39604
39761
  const runtime = await this.#processes.startRetained(
39605
39762
  options.signal,
39606
- () => AcpProcessSession.startNativeSessionBrowser(options, () => this.#observer, this.#store),
39763
+ () => AgentSession.startNativeSessionBrowser(options, () => this.#observer, this.#store),
39607
39764
  {
39608
- isBusy: () => this.#sessions.isBusy(options.sessionId),
39765
+ isBusy: () => this.#processesByQuery.isBusy(options.sessionId),
39609
39766
  retire: (runtime2) => this.retire(options.sessionId, runtime2)
39610
39767
  }
39611
39768
  );
39612
- this.#sessions.retain(options.sessionId, runtime);
39769
+ this.#processesByQuery.retain(options.sessionId, runtime);
39613
39770
  return runtime;
39614
39771
  }
39615
39772
  async #startPreparation(options) {
39616
- return await this.#sessions.prepare(options.sessionId, async () => {
39773
+ return await this.#processesByQuery.prepare(options.sessionId, async () => {
39617
39774
  return await this.#startRetained(options);
39618
39775
  });
39619
39776
  }
39620
39777
  async #replacePreparation(existing, options) {
39621
- return await this.#sessions.prepare(options.sessionId, async () => {
39778
+ return await this.#processesByQuery.prepare(options.sessionId, async () => {
39622
39779
  await this.retire(options.sessionId, existing);
39623
39780
  return await this.#startRetained(options);
39624
39781
  });
39625
39782
  }
39626
39783
  prepare = async (options) => {
39627
- const pending = this.#sessions.pending(options.sessionId);
39784
+ const pending = this.#processesByQuery.pending(options.sessionId);
39628
39785
  if (pending !== void 0) {
39629
39786
  const runtime2 = await pending;
39630
39787
  if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
39631
- this.#sessions.touch(options.sessionId, runtime2);
39788
+ this.#processesByQuery.touch(options.sessionId, runtime2);
39632
39789
  return runtime2.prepared();
39633
39790
  }
39634
39791
  return await this.prepare(options);
39635
39792
  }
39636
- const existing = this.#sessions.get(options.sessionId);
39793
+ const existing = this.#processesByQuery.get(options.sessionId);
39637
39794
  if (existing !== void 0) {
39638
39795
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
39639
- this.#sessions.touch(options.sessionId, existing);
39796
+ this.#processesByQuery.touch(options.sessionId, existing);
39640
39797
  return existing.prepared();
39641
39798
  }
39642
39799
  if (!existing.canRebind()) {
@@ -39653,7 +39810,7 @@ var NativeSessionBrowsers = class {
39653
39810
  return runtime.prepared();
39654
39811
  };
39655
39812
  async #ensure(options) {
39656
- const existing = this.#sessions.get(options.sessionId);
39813
+ const existing = this.#processesByQuery.get(options.sessionId);
39657
39814
  if (existing !== void 0) {
39658
39815
  if (!existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
39659
39816
  throw new AcpExecutionError(
@@ -39662,21 +39819,21 @@ var NativeSessionBrowsers = class {
39662
39819
  "session_identity_mismatch"
39663
39820
  );
39664
39821
  }
39665
- this.#sessions.touch(options.sessionId, existing);
39822
+ this.#processesByQuery.touch(options.sessionId, existing);
39666
39823
  return existing;
39667
39824
  }
39668
39825
  await this.prepare(options);
39669
- const started = this.#sessions.get(options.sessionId);
39826
+ const started = this.#processesByQuery.get(options.sessionId);
39670
39827
  if (started === void 0) {
39671
39828
  throw new AcpExecutionError("ACP native session browser did not start");
39672
39829
  }
39673
39830
  return started;
39674
39831
  }
39675
- use = async (options, operation) => await this.#sessions.use(options.sessionId, async () => await operation(await this.#ensure(options)));
39832
+ use = async (options, operation) => await this.#processesByQuery.use(options.sessionId, async () => await operation(await this.#ensure(options)));
39676
39833
  preview = async (options, nativeSessionId) => {
39677
39834
  return await this.#processes.runTransient(
39678
39835
  options.signal,
39679
- async () => await AcpProcessSession.startNativeSessionBrowser(
39836
+ async () => await AgentSession.startNativeSessionBrowser(
39680
39837
  options,
39681
39838
  () => this.#observer,
39682
39839
  new MemoryAcpSessionStore()
@@ -39689,88 +39846,9 @@ var NativeSessionBrowsers = class {
39689
39846
  );
39690
39847
  };
39691
39848
  close = async () => {
39692
- await Promise.all(this.#sessions.entries().map(async ([id, runtime]) => await this.retire(id, runtime)));
39693
- };
39694
- };
39695
-
39696
- // src/acp/session-executions.ts
39697
- var unreachable = (state) => {
39698
- throw new AcpExecutionError("Unexpected execution state", { cause: state });
39699
- };
39700
- var SessionExecutions = class {
39701
- #entries = /* @__PURE__ */ new Map();
39702
- command = (id) => {
39703
- const state = this.#entries.get(id);
39704
- switch (state?.kind) {
39705
- case "running":
39706
- case "cancelling":
39707
- return state.commandId;
39708
- case "cancelled-before-start":
39709
- case void 0:
39710
- return void 0;
39711
- default:
39712
- return unreachable(state);
39713
- }
39714
- };
39715
- cancellation = (id) => {
39716
- const state = this.#entries.get(id);
39717
- switch (state?.kind) {
39718
- case "cancelling":
39719
- case "cancelled-before-start":
39720
- return state.completion;
39721
- case "running":
39722
- case void 0:
39723
- return void 0;
39724
- default:
39725
- return unreachable(state);
39726
- }
39727
- };
39728
- isBusy = (id) => this.#entries.has(id);
39729
- begin = (id, commandId) => {
39730
- const state = this.#entries.get(id);
39731
- switch (state?.kind) {
39732
- case "running":
39733
- case "cancelling":
39734
- throw new AcpExecutionError(
39735
- "Another prompt is already running in this conversation",
39736
- {},
39737
- "session_busy"
39738
- );
39739
- case "cancelled-before-start":
39740
- case void 0:
39741
- break;
39742
- default:
39743
- unreachable(state);
39744
- }
39745
- this.#entries.set(
39746
- id,
39747
- state?.kind === "cancelled-before-start" ? { kind: "cancelling", commandId, completion: state.completion } : { kind: "running", commandId }
39748
- );
39749
- };
39750
- cancel = (id, stop) => {
39751
- const state = this.#entries.get(id);
39752
- switch (state?.kind) {
39753
- case "cancelling":
39754
- case "cancelled-before-start":
39755
- return state.completion;
39756
- case "running":
39757
- case void 0:
39758
- break;
39759
- default:
39760
- return unreachable(state);
39761
- }
39762
- const completion = Promise.withResolvers();
39763
- this.#entries.set(
39764
- id,
39765
- state?.kind === "running" ? { kind: "cancelling", commandId: state.commandId, completion: completion.promise } : { kind: "cancelled-before-start", completion: completion.promise }
39849
+ await Promise.all(
39850
+ this.#processesByQuery.entries().map(async ([id, runtime]) => await this.retire(id, runtime))
39766
39851
  );
39767
- void (async () => await stop())().then(completion.resolve, completion.reject);
39768
- return completion.promise;
39769
- };
39770
- finish = (id, commandId) => {
39771
- if (this.command(id) === commandId) {
39772
- this.#entries.delete(id);
39773
- }
39774
39852
  };
39775
39853
  };
39776
39854
 
@@ -39875,9 +39953,9 @@ async function waitForAcpProcessCapacity(completion, signal) {
39875
39953
  }
39876
39954
  }
39877
39955
 
39878
- // src/acp/process-pool.ts
39956
+ // src/acp/agent-process-pool.ts
39879
39957
  var MAX_ACP_PROCESSES = 10;
39880
- var AcpProcessPool = class {
39958
+ var AgentProcessPool = class {
39881
39959
  #slots = /* @__PURE__ */ new Map();
39882
39960
  #lock = new AcpProcessCapacityLock();
39883
39961
  #changed = Promise.withResolvers();
@@ -39981,13 +40059,16 @@ var AcpProcessPool = class {
39981
40059
  };
39982
40060
  };
39983
40061
 
39984
- // src/acp/session-manager.ts
40062
+ // src/acp/agent-runtime-manager.ts
39985
40063
  var SESSION_CONTROL_TIMEOUT_MILLISECONDS = 3e4;
39986
- var AcpSessionManager = class {
39987
- #processes = new AcpProcessPool();
39988
- #sessions = new RetainedSessions({ touch: this.#processes.touch, changed: this.#processes.notifyChanged });
39989
- #browsers = new NativeSessionBrowsers(this.#processes);
39990
- #executions = new SessionExecutions();
40064
+ var AgentRuntimeManager = class {
40065
+ #processes = new AgentProcessPool();
40066
+ #executionProcesses = new RetainedAgentProcesses({
40067
+ touch: this.#processes.touch,
40068
+ changed: this.#processes.notifyChanged
40069
+ });
40070
+ #queryProcesses = new AgentQueryProcesses(this.#processes);
40071
+ #executions = new ActiveExecutions();
39991
40072
  #agentSettingsObserver = new NullAcpSessionObserver();
39992
40073
  #nativeOperations = /* @__PURE__ */ new Set();
39993
40074
  #store;
@@ -40009,12 +40090,12 @@ var AcpSessionManager = class {
40009
40090
  }
40010
40091
  #retention(sessionId) {
40011
40092
  return {
40012
- isBusy: () => this.#executions.isBusy(sessionId) || this.#sessions.isBusy(sessionId) || this.#isNativeSessionOperationActive(sessionId),
40093
+ isBusy: () => this.#executions.isBusy(sessionId) || this.#executionProcesses.isBusy(sessionId) || this.#isNativeSessionOperationActive(sessionId),
40013
40094
  retire: (runtime) => this.#retireSessionProcess(sessionId, runtime, () => runtime.close())
40014
40095
  };
40015
40096
  }
40016
40097
  async #retireSessionProcess(sessionId, runtime, close) {
40017
- const retained = this.#sessions.detach(sessionId, runtime);
40098
+ const retained = this.#executionProcesses.detach(sessionId, runtime);
40018
40099
  try {
40019
40100
  await this.#processes.retire(runtime, close);
40020
40101
  } finally {
@@ -40028,14 +40109,14 @@ var AcpSessionManager = class {
40028
40109
  }
40029
40110
  async #startRetainedSessionProcess(options, start) {
40030
40111
  const runtime = await this.#processes.startRetained(options.signal, start, this.#retention(options.sessionId));
40031
- this.#sessions.retain(options.sessionId, runtime);
40112
+ this.#executionProcesses.retain(options.sessionId, runtime);
40032
40113
  return runtime;
40033
40114
  }
40034
40115
  async #startPreparation(options, metrics = unmeasuredOperationMetrics) {
40035
- return await this.#sessions.prepare(options.sessionId, async () => {
40116
+ return await this.#executionProcesses.prepare(options.sessionId, async () => {
40036
40117
  return await this.#startRetainedSessionProcess(
40037
40118
  options,
40038
- async () => await AcpProcessSession.start(
40119
+ async () => await AgentSession.start(
40039
40120
  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,
40040
40121
  () => this.#observer,
40041
40122
  this.#store,
@@ -40045,7 +40126,7 @@ var AcpSessionManager = class {
40045
40126
  });
40046
40127
  }
40047
40128
  async #replacePreparation(existing, options, metrics) {
40048
- return await this.#sessions.prepare(options.sessionId, async () => {
40129
+ return await this.#executionProcesses.prepare(options.sessionId, async () => {
40049
40130
  await this.#retireSessionProcess(
40050
40131
  options.sessionId,
40051
40132
  existing,
@@ -40054,17 +40135,17 @@ var AcpSessionManager = class {
40054
40135
  this.#store.remove(options.sessionId);
40055
40136
  return await this.#startRetainedSessionProcess(
40056
40137
  options,
40057
- async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
40138
+ async () => await AgentSession.start(options, () => this.#observer, this.#store, metrics)
40058
40139
  );
40059
40140
  });
40060
40141
  }
40061
40142
  async #replaceExecutionPreparation(existing, options) {
40062
40143
  const desiredConfigOptions = existing.prepared().configOptions;
40063
- return await this.#sessions.prepare(options.sessionId, async () => {
40144
+ return await this.#executionProcesses.prepare(options.sessionId, async () => {
40064
40145
  await this.#retireSessionProcess(options.sessionId, existing, async () => await existing.close());
40065
40146
  const runtime = await this.#startRetainedSessionProcess(
40066
40147
  options,
40067
- async () => await AcpProcessSession.start(options, () => this.#observer, this.#store)
40148
+ async () => await AgentSession.start(options, () => this.#observer, this.#store)
40068
40149
  );
40069
40150
  try {
40070
40151
  for (const desired of desiredConfigOptions) {
@@ -40115,19 +40196,19 @@ var AcpSessionManager = class {
40115
40196
  if (stored instanceof FoundAcpStoredSession && this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`)) {
40116
40197
  throw new AcpExecutionError("The native session is being managed", {}, "session_busy");
40117
40198
  }
40118
- const pending = this.#sessions.pending(options.sessionId);
40199
+ const pending = this.#executionProcesses.pending(options.sessionId);
40119
40200
  if (pending !== void 0) {
40120
40201
  const runtime2 = await metrics.measure("session-preparation-wait", async () => await pending);
40121
40202
  if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
40122
- this.#sessions.touch(options.sessionId, runtime2);
40203
+ this.#executionProcesses.touch(options.sessionId, runtime2);
40123
40204
  return runtime2.prepared();
40124
40205
  }
40125
40206
  return await this.prepareSession(options, metrics);
40126
40207
  }
40127
- const existing = this.#sessions.get(options.sessionId);
40208
+ const existing = this.#executionProcesses.get(options.sessionId);
40128
40209
  if (existing !== void 0) {
40129
40210
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
40130
- this.#sessions.touch(options.sessionId, existing);
40211
+ this.#executionProcesses.touch(options.sessionId, existing);
40131
40212
  return existing.prepared();
40132
40213
  }
40133
40214
  if (!existing.canRebind()) {
@@ -40150,7 +40231,7 @@ var AcpSessionManager = class {
40150
40231
  */
40151
40232
  inspectAgentSettings = async (options) => await this.#processes.runTransient(
40152
40233
  options.signal,
40153
- async () => await AcpProcessSession.start(
40234
+ async () => await AgentSession.start(
40154
40235
  {
40155
40236
  ...options,
40156
40237
  sessionId: `agent-settings-${crypto.randomUUID()}`
@@ -40181,10 +40262,10 @@ var AcpSessionManager = class {
40181
40262
  * Use inspectAgentSettings for Agent-scoped settings discovery.
40182
40263
  */
40183
40264
  inspectSession = async (options, metrics = unmeasuredOperationMetrics) => {
40184
- if (this.#sessions.pending(options.sessionId) !== void 0 || this.#sessions.get(options.sessionId) !== void 0) {
40265
+ if (this.#executionProcesses.pending(options.sessionId) !== void 0 || this.#executionProcesses.get(options.sessionId) !== void 0) {
40185
40266
  throw new AcpExecutionError("The configuration inspection session is already in use", {}, "session_busy");
40186
40267
  }
40187
- return await this.#sessions.use(options.sessionId, async () => {
40268
+ return await this.#executionProcesses.use(options.sessionId, async () => {
40188
40269
  const runtime = await this.#startPreparation(options, metrics);
40189
40270
  try {
40190
40271
  return runtime.prepared();
@@ -40198,12 +40279,12 @@ var AcpSessionManager = class {
40198
40279
  });
40199
40280
  };
40200
40281
  prepareExecutionSession = async (options) => {
40201
- const pending = this.#sessions.pending(options.sessionId);
40282
+ const pending = this.#executionProcesses.pending(options.sessionId);
40202
40283
  if (pending !== void 0) {
40203
40284
  await pending;
40204
40285
  return await this.prepareExecutionSession(options);
40205
40286
  }
40206
- const existing = this.#sessions.get(options.sessionId);
40287
+ const existing = this.#executionProcesses.get(options.sessionId);
40207
40288
  if (existing === void 0) {
40208
40289
  return (await this.#startPreparation(options)).prepared();
40209
40290
  }
@@ -40215,7 +40296,7 @@ var AcpSessionManager = class {
40215
40296
  );
40216
40297
  }
40217
40298
  if (existing.usesEnvironment(options.agent.environment)) {
40218
- this.#sessions.touch(options.sessionId, existing);
40299
+ this.#executionProcesses.touch(options.sessionId, existing);
40219
40300
  return existing.prepared();
40220
40301
  }
40221
40302
  if (existing.hasRunningTurn()) {
@@ -40227,21 +40308,21 @@ var AcpSessionManager = class {
40227
40308
  }
40228
40309
  return (await this.#replaceExecutionPreparation(existing, options)).prepared();
40229
40310
  };
40230
- prepareNativeSessionBrowser = (options) => this.#browsers.prepare(options);
40311
+ prepareNativeSessionBrowser = (options) => this.#queryProcesses.prepare(options);
40231
40312
  configureSession = async (options) => {
40232
- return await this.#sessions.use(options.sessionId, async () => {
40313
+ return await this.#executionProcesses.use(options.sessionId, async () => {
40233
40314
  const runtime = await this.ensureSession(options);
40234
40315
  return await runtime.configure(options);
40235
40316
  });
40236
40317
  };
40237
40318
  cancelPrompt = async (sessionId) => {
40238
40319
  await this.#executions.cancel(sessionId, async () => {
40239
- const runtime = this.#sessions.get(sessionId);
40320
+ const runtime = this.#executionProcesses.get(sessionId);
40240
40321
  if (runtime !== void 0) {
40241
40322
  try {
40242
40323
  await runtime.cancel();
40243
40324
  } finally {
40244
- if (this.#sessions.detach(sessionId, runtime)) {
40325
+ if (this.#executionProcesses.detach(sessionId, runtime)) {
40245
40326
  this.#processes.releaseClosed(runtime);
40246
40327
  }
40247
40328
  }
@@ -40252,14 +40333,14 @@ var AcpSessionManager = class {
40252
40333
  if (this.#executions.command(options.sessionId) !== options.targetCommandId) {
40253
40334
  throw new AcpExecutionError("The target turn is no longer active", {}, "steering_target_unavailable");
40254
40335
  }
40255
- const pending = this.#sessions.pending(options.sessionId);
40336
+ const pending = this.#executionProcesses.pending(options.sessionId);
40256
40337
  if (pending !== void 0) {
40257
40338
  await pending;
40258
40339
  }
40259
40340
  if (this.#executions.command(options.sessionId) !== options.targetCommandId) {
40260
40341
  throw new AcpExecutionError("The target turn is no longer active", {}, "steering_target_unavailable");
40261
40342
  }
40262
- const runtime = this.#sessions.get(options.sessionId);
40343
+ const runtime = this.#executionProcesses.get(options.sessionId);
40263
40344
  if (runtime === void 0 || !runtime.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
40264
40345
  throw new AcpExecutionError(
40265
40346
  "The target turn execution context is unavailable",
@@ -40317,7 +40398,7 @@ var AcpSessionManager = class {
40317
40398
  throw error62;
40318
40399
  }
40319
40400
  } catch (error62) {
40320
- const failedRuntime = this.#sessions.get(options.sessionId);
40401
+ const failedRuntime = this.#executionProcesses.get(options.sessionId);
40321
40402
  if (failedRuntime !== void 0) {
40322
40403
  await this.#retireSessionProcess(
40323
40404
  options.sessionId,
@@ -40339,32 +40420,32 @@ var AcpSessionManager = class {
40339
40420
  await this.#executions.cancellation(options.sessionId);
40340
40421
  } finally {
40341
40422
  this.#executions.finish(options.sessionId, options.commandId);
40342
- this.#sessions.touch(options.sessionId);
40423
+ this.#executionProcesses.touch(options.sessionId);
40343
40424
  this.#processes.notifyChanged();
40344
40425
  }
40345
40426
  }
40346
40427
  };
40347
40428
  respondPermission = async (options) => {
40348
- const runtime = this.#sessions.get(options.sessionId);
40429
+ const runtime = this.#executionProcesses.get(options.sessionId);
40349
40430
  if (runtime === void 0) {
40350
40431
  throw new AcpExecutionError("The permission request session is unavailable", {}, "session_not_found");
40351
40432
  }
40352
40433
  await runtime.respondPermission(options);
40353
40434
  };
40354
40435
  respondElicitation = async (options) => {
40355
- const runtime = this.#sessions.get(options.sessionId);
40436
+ const runtime = this.#executionProcesses.get(options.sessionId);
40356
40437
  if (runtime === void 0) {
40357
40438
  throw new AcpExecutionError("The elicitation request session is unavailable", {}, "session_not_found");
40358
40439
  }
40359
40440
  await runtime.respondElicitation(options);
40360
40441
  };
40361
40442
  close = async () => {
40362
- const sessions = [...this.#sessions.entries()];
40443
+ const sessions = [...this.#executionProcesses.entries()];
40363
40444
  await Promise.all([
40364
40445
  ...sessions.map(
40365
40446
  async ([sessionId, runtime]) => await this.#retireSessionProcess(sessionId, runtime, async () => await runtime.close())
40366
40447
  ),
40367
- this.#browsers.close()
40448
+ this.#queryProcesses.close()
40368
40449
  ]);
40369
40450
  };
40370
40451
  findSessions = (sessionIds) => sessionIds.flatMap((sessionId) => {
@@ -40372,17 +40453,17 @@ var AcpSessionManager = class {
40372
40453
  return stored instanceof FoundAcpStoredSession ? [stored.session] : [];
40373
40454
  });
40374
40455
  findLinkedSessions = (agentId, nativeSessionId) => this.#store.findNative(agentId, nativeSessionId);
40375
- hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
40456
+ hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#executionProcesses.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
40376
40457
  createNativeSession = async (options) => {
40377
40458
  const temporarySessionId = `new-${crypto.randomUUID()}`;
40378
40459
  const temporaryOptions = { ...options, sessionId: temporarySessionId };
40379
- return await this.#sessions.use(temporarySessionId, async () => {
40460
+ return await this.#executionProcesses.use(temporarySessionId, async () => {
40380
40461
  try {
40381
40462
  const runtime = await this.#startPreparation(temporaryOptions);
40382
40463
  let adopted = false;
40383
40464
  try {
40384
40465
  const nativeSessionId = runtime.nativeSessionId();
40385
- if (!isNativeChatSessionId(options.agent.id, nativeSessionId) || this.#sessions.get(nativeSessionId) !== void 0 || !(this.#store.read(nativeSessionId) instanceof MissingAcpStoredSession)) {
40466
+ if (!isNativeChatSessionId(options.agent.id, nativeSessionId) || this.#executionProcesses.get(nativeSessionId) !== void 0 || !(this.#store.read(nativeSessionId) instanceof MissingAcpStoredSession)) {
40386
40467
  throw new AcpExecutionError(
40387
40468
  "The Agent returned an invalid new Session ID",
40388
40469
  {},
@@ -40390,8 +40471,8 @@ var AcpSessionManager = class {
40390
40471
  );
40391
40472
  }
40392
40473
  runtime.adoptNativeSessionId(nativeSessionId);
40393
- this.#sessions.detach(temporarySessionId, runtime);
40394
- this.#sessions.retain(nativeSessionId, runtime);
40474
+ this.#executionProcesses.detach(temporarySessionId, runtime);
40475
+ this.#executionProcesses.retain(nativeSessionId, runtime);
40395
40476
  this.#processes.retain(runtime, this.#retention(nativeSessionId));
40396
40477
  adopted = true;
40397
40478
  return nativeSessionId;
@@ -40410,7 +40491,7 @@ var AcpSessionManager = class {
40410
40491
  });
40411
40492
  };
40412
40493
  ensureSession = async (options) => {
40413
- const existing = this.#sessions.get(options.sessionId);
40494
+ const existing = this.#executionProcesses.get(options.sessionId);
40414
40495
  if (existing !== void 0) {
40415
40496
  if (!existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
40416
40497
  throw new AcpExecutionError(
@@ -40419,18 +40500,18 @@ var AcpSessionManager = class {
40419
40500
  "session_identity_mismatch"
40420
40501
  );
40421
40502
  }
40422
- this.#sessions.touch(options.sessionId, existing);
40503
+ this.#executionProcesses.touch(options.sessionId, existing);
40423
40504
  return existing;
40424
40505
  }
40425
40506
  await this.prepareSession(options);
40426
- const started = this.#sessions.get(options.sessionId);
40507
+ const started = this.#executionProcesses.get(options.sessionId);
40427
40508
  if (started === void 0) {
40428
40509
  throw new AcpExecutionError("ACP session did not start");
40429
40510
  }
40430
40511
  return started;
40431
40512
  };
40432
40513
  listNativeSessions = async (options, cursor) => {
40433
- return await this.#browsers.use(
40514
+ return await this.#queryProcesses.use(
40434
40515
  options,
40435
40516
  async (runtime) => await runtime.listNativeSessions(cursor, options.signal)
40436
40517
  );
@@ -40439,7 +40520,7 @@ var AcpSessionManager = class {
40439
40520
  const key = `${options.agent.id}:${nativeSessionId}`;
40440
40521
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
40441
40522
  if (this.#nativeOperations.has(key) || linked.some(
40442
- (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#sessions.pending(entry.sessionId) !== void 0
40523
+ (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#executionProcesses.pending(entry.sessionId) !== void 0
40443
40524
  )) {
40444
40525
  throw new AcpExecutionError(
40445
40526
  "Wait for the native session's running operation to finish",
@@ -40449,13 +40530,13 @@ var AcpSessionManager = class {
40449
40530
  }
40450
40531
  this.#nativeOperations.add(key);
40451
40532
  try {
40452
- return await this.#browsers.preview(options, nativeSessionId);
40533
+ return await this.#queryProcesses.preview(options, nativeSessionId);
40453
40534
  } finally {
40454
40535
  this.#nativeOperations.delete(key);
40455
40536
  }
40456
40537
  };
40457
40538
  loadSessionHistory = async (options) => {
40458
- return await this.#sessions.use(options.sessionId, async () => {
40539
+ return await this.#executionProcesses.use(options.sessionId, async () => {
40459
40540
  const runtime = await this.ensureSession(options);
40460
40541
  const stored = this.#store.read(options.sessionId);
40461
40542
  if (stored instanceof FoundAcpStoredSession && this.#nativeHistoryReader !== null) {
@@ -40478,7 +40559,7 @@ var AcpSessionManager = class {
40478
40559
  }
40479
40560
  const linked = this.#store.findNative(options.agent.id, origin.nativeSessionId);
40480
40561
  if (linked.some(
40481
- (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#sessions.pending(entry.sessionId) !== void 0
40562
+ (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#executionProcesses.pending(entry.sessionId) !== void 0
40482
40563
  )) {
40483
40564
  throw new AcpExecutionError(
40484
40565
  "Wait for the native session's running operation to finish",
@@ -40488,7 +40569,7 @@ var AcpSessionManager = class {
40488
40569
  }
40489
40570
  const existing = linked[0];
40490
40571
  if (origin.kind === "import" && existing !== void 0) {
40491
- return await this.#sessions.use(existing.sessionId, async () => {
40572
+ return await this.#executionProcesses.use(existing.sessionId, async () => {
40492
40573
  const runtime = await this.ensureSession({
40493
40574
  ...options,
40494
40575
  sessionId: existing.sessionId
@@ -40512,10 +40593,10 @@ var AcpSessionManager = class {
40512
40593
  }
40513
40594
  });
40514
40595
  }
40515
- 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) {
40596
+ 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) {
40516
40597
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
40517
40598
  }
40518
- return await this.#sessions.use(options.sessionId, async () => {
40599
+ return await this.#executionProcesses.use(options.sessionId, async () => {
40519
40600
  this.#nativeOperations.add(key);
40520
40601
  try {
40521
40602
  const runtime = await this.#startPreparation({ ...options, origin });
@@ -40532,7 +40613,7 @@ var AcpSessionManager = class {
40532
40613
  }
40533
40614
  } catch (error62) {
40534
40615
  this.#store.remove(options.sessionId);
40535
- const runtime = this.#sessions.get(options.sessionId);
40616
+ const runtime = this.#executionProcesses.get(options.sessionId);
40536
40617
  if (runtime !== void 0) {
40537
40618
  await this.#retireSessionProcess(
40538
40619
  options.sessionId,
@@ -40547,11 +40628,11 @@ var AcpSessionManager = class {
40547
40628
  });
40548
40629
  };
40549
40630
  deleteNativeSession = async (options, nativeSessionId) => {
40550
- return await this.#browsers.use(options, async (runtime) => {
40631
+ return await this.#queryProcesses.use(options, async (runtime) => {
40551
40632
  const key = `${options.agent.id}:${nativeSessionId}`;
40552
40633
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
40553
40634
  if (this.#nativeOperations.has(key) || linked.some(
40554
- (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#sessions.pending(entry.sessionId) !== void 0
40635
+ (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#executionProcesses.pending(entry.sessionId) !== void 0
40555
40636
  )) {
40556
40637
  throw new AcpExecutionError(
40557
40638
  "Wait for the native session's running operation to finish",
@@ -40562,7 +40643,7 @@ var AcpSessionManager = class {
40562
40643
  this.#nativeOperations.add(key);
40563
40644
  try {
40564
40645
  for (const entry of linked) {
40565
- const active = this.#sessions.get(entry.sessionId);
40646
+ const active = this.#executionProcesses.get(entry.sessionId);
40566
40647
  if (active !== void 0 && active !== runtime) {
40567
40648
  await this.#retireSessionProcess(entry.sessionId, active, async () => await active.close());
40568
40649
  }
@@ -40571,7 +40652,7 @@ var AcpSessionManager = class {
40571
40652
  await runtime.deleteNativeSession(nativeSessionId, options.signal);
40572
40653
  const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
40573
40654
  if (runtime.nativeSessionId() === nativeSessionId) {
40574
- await this.#browsers.retire(options.sessionId, runtime);
40655
+ await this.#queryProcesses.retire(options.sessionId, runtime);
40575
40656
  }
40576
40657
  return deleted;
40577
40658
  } finally {
@@ -45992,7 +46073,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
45992
46073
  activeTurns.recordEvent(event);
45993
46074
  publisher.publish(sessionId, event);
45994
46075
  };
45995
- const sessions = new AcpSessionManager(
46076
+ const agentRuntime = new AgentRuntimeManager(
45996
46077
  new DaemonAcpObserver(recordSessionEvent),
45997
46078
  sessionStore,
45998
46079
  {
@@ -46014,20 +46095,28 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
46014
46095
  config2.relayUrl,
46015
46096
  new DaemonDiagnosticLog(stateDirectory)
46016
46097
  );
46017
- const nativeSessions = new NativeSessionService(config2, directories, sessions, audit, async (request, options2) => {
46018
- return await activeTurns.executionSnapshot(async (command) => {
46019
- if (command.sessionId !== request.targetSessionId || command.agentId !== request.agentId) {
46020
- return false;
46021
- }
46022
- const cwd = await directories.resolve(command.bindingId, command.directoryId, options2.signal);
46023
- const additionalDirectories = await directories.resolveMany(
46024
- command.bindingId,
46025
- command.additionalDirectoryIds,
46026
- options2.signal
46027
- );
46028
- return cwd === options2.cwd && additionalDirectories.length === options2.additionalDirectories.length && additionalDirectories.every((directory, index) => directory === options2.additionalDirectories[index]);
46029
- });
46030
- });
46098
+ const nativeSessions = new NativeSessionService(
46099
+ config2,
46100
+ directories,
46101
+ agentRuntime,
46102
+ audit,
46103
+ async (request, options2) => {
46104
+ return await activeTurns.executionSnapshot(async (command) => {
46105
+ if (command.sessionId !== request.targetSessionId || command.agentId !== request.agentId) {
46106
+ return false;
46107
+ }
46108
+ const cwd = await directories.resolve(command.bindingId, command.directoryId, options2.signal);
46109
+ const additionalDirectories = await directories.resolveMany(
46110
+ command.bindingId,
46111
+ command.additionalDirectoryIds,
46112
+ options2.signal
46113
+ );
46114
+ return cwd === options2.cwd && additionalDirectories.length === options2.additionalDirectories.length && additionalDirectories.every(
46115
+ (directory, index) => directory === options2.additionalDirectories[index]
46116
+ );
46117
+ });
46118
+ }
46119
+ );
46031
46120
  const installations = new AgentInstallationManager(
46032
46121
  specifications,
46033
46122
  installationExecutor,
@@ -46103,7 +46192,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
46103
46192
  config: config2,
46104
46193
  directories,
46105
46194
  audit,
46106
- sessions,
46195
+ sessions: agentRuntime,
46107
46196
  installations,
46108
46197
  installationObserver,
46109
46198
  nativeSessions,
@@ -46146,7 +46235,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
46146
46235
  await installations.close();
46147
46236
  } finally {
46148
46237
  try {
46149
- await sessions.close();
46238
+ await agentRuntime.close();
46150
46239
  } finally {
46151
46240
  try {
46152
46241
  sessionStore.close();