@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/runtime.js CHANGED
@@ -23478,6 +23478,7 @@ var COLLABORATION_MODE_SETTING_ID = "collaboration_mode";
23478
23478
  var MODEL_CATALOG_LIMIT = 1e3;
23479
23479
  var FAST_TIER = "fast";
23480
23480
  var SERVICE_TIER_FAST = "priority";
23481
+ var CODEX_COMMANDS = Object.freeze([{ description: "Compact the conversation context", name: "compact" }]);
23481
23482
  var WORKSPACE_WRITE_POLICY = Object.freeze({
23482
23483
  excludeSlashTmp: false,
23483
23484
  excludeTmpdirEnvVar: false,
@@ -23558,6 +23559,9 @@ function promptInput(prompt) {
23558
23559
  }
23559
23560
  return input2;
23560
23561
  }
23562
+ function isCompactPrompt(prompt) {
23563
+ return prompt.length === 1 && prompt[0]?.type === "text" && prompt[0].text.trim() === "/compact";
23564
+ }
23561
23565
  function steeringPromptInput(prompt) {
23562
23566
  const input2 = [];
23563
23567
  for (const block of prompt) {
@@ -23812,6 +23816,7 @@ var CodexAcpAgent = class {
23812
23816
  };
23813
23817
  this.#collaborationModeSelected = false;
23814
23818
  await this.#probeCollaborationMode(context.signal);
23819
+ await this.#emitAvailableCommands();
23815
23820
  return { configOptions: this.#configOptions(), sessionId: created.thread.id };
23816
23821
  }).onRequest(methods.agent.session.setConfigOption, async (context) => {
23817
23822
  this.#applySelection(context.params.configId, context.params.value);
@@ -23830,6 +23835,7 @@ var CodexAcpAgent = class {
23830
23835
  this.#selectRestoredThread(resumed);
23831
23836
  await this.#probeCollaborationMode(context.signal);
23832
23837
  await this.#replayHistory(resumed.turns);
23838
+ await this.#emitAvailableCommands();
23833
23839
  return { configOptions: this.#configOptions() };
23834
23840
  }).onRequest(methods.agent.session.fork, async (context) => {
23835
23841
  const forked = threadForkResponseSchema.parse(
@@ -23846,6 +23852,7 @@ var CodexAcpAgent = class {
23846
23852
  this.#selectRestoredThread(forked);
23847
23853
  await this.#probeCollaborationMode(context.signal);
23848
23854
  await this.#replayHistory(forked.turns);
23855
+ await this.#emitAvailableCommands();
23849
23856
  return { configOptions: this.#configOptions(), sessionId: forked.thread.id };
23850
23857
  }).onRequest(methods.agent.session.resume, async (context) => {
23851
23858
  const resumed = threadResumeResponseSchema.parse(
@@ -23857,8 +23864,12 @@ var CodexAcpAgent = class {
23857
23864
  );
23858
23865
  this.#selectRestoredThread(resumed);
23859
23866
  await this.#probeCollaborationMode(context.signal);
23867
+ await this.#emitAvailableCommands();
23860
23868
  return { configOptions: this.#configOptions() };
23861
23869
  }).onRequest(methods.agent.session.prompt, async (context) => {
23870
+ if (isCompactPrompt(context.params.prompt)) {
23871
+ return await this.#compact(context.signal);
23872
+ }
23862
23873
  return await this.#runTurn(promptInput(context.params.prompt), context.signal);
23863
23874
  }).onRequest(
23864
23875
  "_session/steering",
@@ -24138,6 +24149,12 @@ var CodexAcpAgent = class {
24138
24149
  update
24139
24150
  });
24140
24151
  };
24152
+ #emitAvailableCommands = async () => {
24153
+ await this.#emit({
24154
+ availableCommands: CODEX_COMMANDS.map((command) => ({ ...command })),
24155
+ sessionUpdate: "available_commands_update"
24156
+ });
24157
+ };
24141
24158
  /** Pushes the current settings so a mode change Codex applied reaches the Run settings panel. */
24142
24159
  #emitConfigOptionsUpdate = async () => {
24143
24160
  const connection = this.#connection;
@@ -24448,6 +24465,35 @@ var CodexAcpAgent = class {
24448
24465
  }
24449
24466
  }
24450
24467
  };
24468
+ #compact = async (signal) => {
24469
+ signal.throwIfAborted();
24470
+ if (this.#turn !== null) {
24471
+ throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
24472
+ }
24473
+ const completion = Promise.withResolvers();
24474
+ void completion.promise.catch(() => {
24475
+ });
24476
+ const aborted2 = () => {
24477
+ completion.reject(signal.reason);
24478
+ void this.close().catch((cause) => {
24479
+ console.error("The cancelled Codex endpoint could not release its process tree", cause);
24480
+ });
24481
+ };
24482
+ signal.addEventListener("abort", aborted2, { once: true });
24483
+ const turn = { completion, turn: { id: "" } };
24484
+ this.#streamedReasoningItemIds.clear();
24485
+ this.#turn = turn;
24486
+ try {
24487
+ await this.#appServer.request("thread/compact/start", { threadId: this.#nativeSessionId }, signal);
24488
+ return await completion.promise;
24489
+ } finally {
24490
+ signal.removeEventListener("abort", aborted2);
24491
+ if (this.#turn === turn) {
24492
+ this.#turn = null;
24493
+ this.#streamedReasoningItemIds.clear();
24494
+ }
24495
+ }
24496
+ };
24451
24497
  #steerTurn = async (params, signal) => {
24452
24498
  if (typeof params !== "object" || params === null) {
24453
24499
  throw new AcpExecutionError("Codex received an invalid steering request", {}, "invalid_request");
@@ -26413,7 +26459,88 @@ import { createHash as createHash5, randomUUID as randomUUID6 } from "node:crypt
26413
26459
  import { join as join17 } from "node:path";
26414
26460
  import { styleText } from "node:util";
26415
26461
 
26416
- // src/acp/process-session.ts
26462
+ // src/acp/active-executions.ts
26463
+ var unreachable = (state) => {
26464
+ throw new AcpExecutionError("Unexpected execution state", { cause: state });
26465
+ };
26466
+ var ActiveExecutions = class {
26467
+ #entries = /* @__PURE__ */ new Map();
26468
+ command = (id) => {
26469
+ const state = this.#entries.get(id);
26470
+ switch (state?.kind) {
26471
+ case "running":
26472
+ case "cancelling":
26473
+ return state.commandId;
26474
+ case "cancelled-before-start":
26475
+ case void 0:
26476
+ return void 0;
26477
+ default:
26478
+ return unreachable(state);
26479
+ }
26480
+ };
26481
+ cancellation = (id) => {
26482
+ const state = this.#entries.get(id);
26483
+ switch (state?.kind) {
26484
+ case "cancelling":
26485
+ case "cancelled-before-start":
26486
+ return state.completion;
26487
+ case "running":
26488
+ case void 0:
26489
+ return void 0;
26490
+ default:
26491
+ return unreachable(state);
26492
+ }
26493
+ };
26494
+ isBusy = (id) => this.#entries.has(id);
26495
+ begin = (id, commandId) => {
26496
+ const state = this.#entries.get(id);
26497
+ switch (state?.kind) {
26498
+ case "running":
26499
+ case "cancelling":
26500
+ throw new AcpExecutionError(
26501
+ "Another prompt is already running in this conversation",
26502
+ {},
26503
+ "session_busy"
26504
+ );
26505
+ case "cancelled-before-start":
26506
+ case void 0:
26507
+ break;
26508
+ default:
26509
+ unreachable(state);
26510
+ }
26511
+ this.#entries.set(
26512
+ id,
26513
+ state?.kind === "cancelled-before-start" ? { kind: "cancelling", commandId, completion: state.completion } : { kind: "running", commandId }
26514
+ );
26515
+ };
26516
+ cancel = (id, stop) => {
26517
+ const state = this.#entries.get(id);
26518
+ switch (state?.kind) {
26519
+ case "cancelling":
26520
+ case "cancelled-before-start":
26521
+ return state.completion;
26522
+ case "running":
26523
+ case void 0:
26524
+ break;
26525
+ default:
26526
+ return unreachable(state);
26527
+ }
26528
+ const completion = Promise.withResolvers();
26529
+ this.#entries.set(
26530
+ id,
26531
+ state?.kind === "running" ? { kind: "cancelling", commandId: state.commandId, completion: completion.promise } : { kind: "cancelled-before-start", completion: completion.promise }
26532
+ );
26533
+ void (async () => await stop())().then(completion.resolve, completion.reject);
26534
+ return completion.promise;
26535
+ };
26536
+ finish = (id, commandId) => {
26537
+ if (this.command(id) === commandId) {
26538
+ this.#entries.delete(id);
26539
+ }
26540
+ };
26541
+ };
26542
+
26543
+ // src/acp/agent-session.ts
26417
26544
  import {
26418
26545
  methods as methods8,
26419
26546
  PROTOCOL_VERSION as PROTOCOL_VERSION3
@@ -26716,73 +26843,11 @@ async function replaceImageMarkers(text2, replace) {
26716
26843
  return `${rewritten}${text2.slice(cursor)}`;
26717
26844
  }
26718
26845
 
26719
- // src/acp/activity.ts
26846
+ // src/acp/activity-content.ts
26720
26847
  var TRUNCATION_MARKER = "\n\u2026 output truncated by Mobius";
26721
- var AcpActivityNarration = class {
26722
- activityId;
26723
- activityType;
26724
- sequence;
26725
- text;
26726
- constructor(activityId, activityType, sequence, text2) {
26727
- this.activityId = activityId;
26728
- this.activityType = activityType;
26729
- this.sequence = sequence;
26730
- this.text = text2;
26731
- }
26732
- };
26733
26848
  function isRecord5(value) {
26734
26849
  return typeof value === "object" && value !== null && !Array.isArray(value);
26735
26850
  }
26736
- var AcpActivity = class _AcpActivity {
26737
- activityId;
26738
- activityType;
26739
- input;
26740
- locations;
26741
- name;
26742
- output;
26743
- sequence;
26744
- status;
26745
- title;
26746
- toolKind;
26747
- content;
26748
- detail;
26749
- constructor(activityId, activityType, input2, locations, name, output2, sequence, status, title2, toolKind, content = [], detail = captureActivityDetail(content, input2, output2)) {
26750
- this.activityId = activityId;
26751
- this.activityType = activityType;
26752
- this.input = input2;
26753
- this.locations = locations;
26754
- this.name = name;
26755
- this.output = output2;
26756
- this.sequence = sequence;
26757
- this.status = status;
26758
- this.title = title2;
26759
- this.toolKind = toolKind;
26760
- this.content = content;
26761
- this.detail = detail;
26762
- }
26763
- complete = () => (this.activityType === "progress" || this.activityType === "reasoning") && (this.status === "pending" || this.status === "running") ? new _AcpActivity(
26764
- this.activityId,
26765
- this.activityType,
26766
- this.input,
26767
- this.locations,
26768
- this.name,
26769
- this.output,
26770
- this.sequence,
26771
- "completed",
26772
- this.title,
26773
- this.toolKind,
26774
- this.content,
26775
- this.detail
26776
- ) : this;
26777
- };
26778
- var ActivityIdentity = class {
26779
- id;
26780
- sequence;
26781
- constructor(id, sequence) {
26782
- this.id = id;
26783
- this.sequence = sequence;
26784
- }
26785
- };
26786
26851
  function truncate2(value, maximumLength) {
26787
26852
  if (value.length <= maximumLength) {
26788
26853
  return value;
@@ -27059,427 +27124,160 @@ function contentPhase(content) {
27059
27124
  function isProgressMessage(content) {
27060
27125
  return contentPhase(content) === "commentary";
27061
27126
  }
27062
- var AcpActivityTracker = class {
27063
- #activities = /* @__PURE__ */ new Map();
27064
- #identities = /* @__PURE__ */ new Map();
27065
- #narrations = /* @__PURE__ */ new Map();
27066
- #onActivity;
27067
- #onNarration;
27068
- #prepareContent;
27069
- #activeNarrativeKey = "";
27070
- #nextSequence = 0;
27071
- constructor(onActivity, onNarration, prepareContent = (content) => Promise.resolve(content)) {
27072
- this.#onActivity = onActivity;
27073
- this.#onNarration = onNarration;
27074
- this.#prepareContent = prepareContent;
27075
- }
27076
- recordNarrative = async (activityType, messageId, text2) => {
27077
- const key = `${activityType}:${messageId}`;
27078
- if (this.#activeNarrativeKey !== key) {
27079
- await this.finishNarrative();
27080
- }
27081
- const identity2 = this.#identity(key);
27082
- const previous = this.#narrations.get(key);
27083
- const previousOutput = previous?.output ?? "";
27084
- const remaining = Math.max(0, AGENT_ACTIVITY_DETAIL_LIMIT - previousOutput.length);
27085
- this.#narrations.set(key, {
27086
- activityId: identity2.id,
27087
- activityType,
27088
- output: `${previousOutput}${text2.slice(0, remaining)}`,
27089
- originalBytes: (previous?.originalBytes ?? 0) + new TextEncoder().encode(text2).byteLength,
27090
- sequence: identity2.sequence,
27091
- truncated: (previous?.truncated ?? false) || text2.length > remaining
27092
- });
27093
- if (previous === void 0) {
27094
- await this.#record(key, this.#narrativeSnapshot(identity2, activityType, "", "running"));
27127
+
27128
+ // src/acp/agent-connection.ts
27129
+ import { spawn as spawn4 } from "node:child_process";
27130
+ import { ndJsonStream as ndJsonStream2, RequestError as RequestError3 } from "@agentclientprotocol/sdk";
27131
+
27132
+ // src/acp/value-utils.ts
27133
+ function truncate3(value, maximumLength) {
27134
+ return value.length <= maximumLength ? value : `${value.slice(0, Math.max(0, maximumLength - 1))}\u2026`;
27135
+ }
27136
+ function isRecord6(value) {
27137
+ return typeof value === "object" && value !== null && !Array.isArray(value);
27138
+ }
27139
+ function readString2(value, fallback = "") {
27140
+ return typeof value === "string" ? value : fallback;
27141
+ }
27142
+
27143
+ // src/acp/agent-connection.ts
27144
+ function readableWebStream(input2) {
27145
+ let streamOpen = true;
27146
+ return new ReadableStream({
27147
+ start(controller) {
27148
+ input2.on("data", (chunk) => {
27149
+ if (!streamOpen) {
27150
+ return;
27151
+ }
27152
+ if (chunk instanceof Uint8Array) {
27153
+ controller.enqueue(new Uint8Array(chunk));
27154
+ return;
27155
+ }
27156
+ streamOpen = false;
27157
+ controller.error(new Error("ACP process produced a non-binary chunk"));
27158
+ });
27159
+ input2.once("end", () => {
27160
+ if (!streamOpen) {
27161
+ return;
27162
+ }
27163
+ streamOpen = false;
27164
+ controller.close();
27165
+ });
27166
+ input2.once("error", (error62) => {
27167
+ if (!streamOpen) {
27168
+ return;
27169
+ }
27170
+ streamOpen = false;
27171
+ controller.error(error62);
27172
+ });
27173
+ },
27174
+ cancel() {
27175
+ streamOpen = false;
27095
27176
  }
27096
- this.#activeNarrativeKey = key;
27097
- if (text2.length > 0) {
27098
- await this.#onNarration(new AcpActivityNarration(identity2.id, activityType, identity2.sequence, text2));
27177
+ });
27178
+ }
27179
+ function createWritableAcpStream(output2) {
27180
+ let outputFailure;
27181
+ const pendingWriteFailures = /* @__PURE__ */ new Set();
27182
+ const fail = (error62) => {
27183
+ outputFailure = error62;
27184
+ for (const reject of pendingWriteFailures) {
27185
+ reject(error62);
27099
27186
  }
27187
+ pendingWriteFailures.clear();
27100
27188
  };
27101
- #narrativeSnapshot = (identity2, activityType, output2, status) => new AcpActivity(
27102
- identity2.id,
27103
- activityType,
27104
- "",
27105
- [],
27106
- "",
27107
- truncate2(output2, AGENT_ACTIVITY_DETAIL_LIMIT),
27108
- identity2.sequence,
27109
- status,
27110
- activityType === "reasoning" ? "Reasoning" : "Progress update",
27111
- activityType === "reasoning" ? "think" : ""
27112
- );
27113
- recordPlan = async (plan) => {
27114
- await this.finishNarrative();
27115
- await this.#recordPlanEntries("plan:default", plan.entries);
27116
- };
27117
- recordPlanUpdate = async (update) => {
27118
- await this.finishNarrative();
27119
- const plan = update.plan;
27120
- const key = `plan:${plan.planId}`;
27121
- if (plan.type === "items") {
27122
- await this.#recordPlanEntries(key, plan.entries);
27123
- return;
27189
+ output2.on("error", fail);
27190
+ output2.once("close", () => {
27191
+ if (outputFailure === void 0) {
27192
+ fail(new Error("ACP process input closed"));
27124
27193
  }
27125
- const identity2 = this.#identity(key);
27126
- const output2 = plan.type === "markdown" ? plan.content : `Plan file: ${plan.uri}`;
27127
- await this.#record(
27128
- key,
27129
- new AcpActivity(
27130
- identity2.id,
27131
- "plan",
27132
- "",
27133
- [],
27134
- "",
27135
- truncate2(output2, AGENT_ACTIVITY_DETAIL_LIMIT),
27136
- identity2.sequence,
27137
- "running",
27138
- "Plan",
27139
- ""
27140
- )
27141
- );
27142
- };
27143
- removePlan = async (update) => {
27144
- await this.finishNarrative();
27145
- const key = `plan:${update.planId}`;
27146
- const previous = this.#activities.get(key);
27147
- if (previous !== void 0) {
27148
- await this.#record(
27149
- key,
27150
- new AcpActivity(
27151
- previous.activityId,
27152
- previous.activityType,
27153
- previous.input,
27154
- previous.locations,
27155
- previous.name,
27156
- previous.output,
27157
- previous.sequence,
27158
- "completed",
27159
- previous.title,
27160
- previous.toolKind,
27161
- previous.content,
27162
- previous.detail
27163
- )
27164
- );
27194
+ });
27195
+ return new WritableStream({
27196
+ write(chunk) {
27197
+ if (outputFailure !== void 0) {
27198
+ return Promise.reject(outputFailure);
27199
+ }
27200
+ return new Promise((resolve9, reject) => {
27201
+ pendingWriteFailures.add(reject);
27202
+ output2.write(chunk, (error62) => {
27203
+ pendingWriteFailures.delete(reject);
27204
+ if (error62) {
27205
+ outputFailure = error62;
27206
+ reject(error62);
27207
+ return;
27208
+ }
27209
+ if (outputFailure !== void 0) {
27210
+ reject(outputFailure);
27211
+ return;
27212
+ }
27213
+ resolve9();
27214
+ });
27215
+ });
27165
27216
  }
27166
- };
27167
- recordToolCall = async (update) => {
27168
- await this.finishNarrative();
27169
- const key = `tool:${update.toolCallId}`;
27170
- const identity2 = this.#identity(key);
27171
- const output2 = update.rawOutput === void 0 ? readContentOutput(update.content) : formatUnknown(update.rawOutput);
27172
- const detailInput = update.rawInput === void 0 ? "" : formatUnknownDetail(update.rawInput);
27173
- const detailOutput = update.rawOutput === void 0 ? readContentOutputDetail(update.content) : formatUnknownDetail(update.rawOutput);
27174
- const detailContent = await normalizeToolContent(
27175
- toolContent(update.content, update.rawOutput),
27176
- this.#prepareContent
27177
- );
27178
- await this.#record(
27179
- key,
27180
- new AcpActivity(
27181
- identity2.id,
27182
- "tool",
27183
- update.rawInput === void 0 ? "" : formatUnknown(update.rawInput),
27184
- normalizeLocations(update.locations ?? []),
27185
- truncate2(update.name ?? "", 128),
27186
- output2,
27187
- identity2.sequence,
27188
- normalizeToolStatus(update.status ?? "pending", "pending"),
27189
- normalizeTitle(update.title, "Tool call"),
27190
- update.kind ?? "other",
27191
- detailContent.slice(0, 100).map(summarizeDisplayContent),
27192
- captureActivityDetail(detailContent, detailInput, detailOutput)
27193
- )
27194
- );
27195
- };
27196
- recordToolCallUpdate = async (update) => {
27197
- await this.finishNarrative();
27198
- const key = `tool:${update.toolCallId}`;
27199
- const previous = this.#activities.get(key);
27200
- const identity2 = this.#identity(key);
27201
- const previousDetail = recordedDetail(previous);
27202
- const output2 = update.rawOutput !== void 0 ? formatUnknown(update.rawOutput) : update.content !== void 0 && update.content !== null ? readContentOutput(update.content) : previous?.output ?? "";
27203
- const nextContent = toolContent(update.content, update.rawOutput);
27204
- const content = nextContent.length === 0 ? previous?.content ?? [] : await normalizeToolContent(nextContent, this.#prepareContent);
27205
- const detailInput = update.rawInput === void 0 ? previousDetail?.input ?? previous?.input ?? "" : formatUnknownDetail(update.rawInput);
27206
- const detailOutput = update.rawOutput !== void 0 ? formatUnknownDetail(update.rawOutput) : update.content !== void 0 && update.content !== null ? readContentOutputDetail(update.content) : previousDetail?.output ?? previous?.output ?? "";
27207
- const detailContent = nextContent.length === 0 ? previousDetail?.content ?? previous?.content ?? [] : content;
27208
- await this.#record(
27209
- key,
27210
- new AcpActivity(
27211
- identity2.id,
27212
- "tool",
27213
- update.rawInput === void 0 ? previous?.input ?? "" : formatUnknown(update.rawInput),
27214
- update.locations === void 0 || update.locations === null ? previous?.locations ?? [] : normalizeLocations(update.locations),
27215
- update.name === void 0 || update.name === null ? previous?.name ?? "" : truncate2(update.name, 128),
27216
- output2,
27217
- identity2.sequence,
27218
- update.status === void 0 || update.status === null ? previous?.status ?? "pending" : normalizeToolStatus(update.status, previous?.status ?? "pending"),
27219
- update.title === void 0 || update.title === null ? previous?.title ?? "Tool call" : normalizeTitle(update.title, "Tool call"),
27220
- update.kind === void 0 || update.kind === null ? previous?.toolKind ?? "other" : update.kind,
27221
- content.slice(0, 100).map(summarizeDisplayContent),
27222
- captureActivityDetail(detailContent, detailInput, detailOutput)
27223
- )
27224
- );
27225
- };
27226
- finishNarrative = async () => {
27227
- const key = this.#activeNarrativeKey;
27228
- if (key.length === 0) {
27217
+ });
27218
+ }
27219
+ var AgentConnection = class {
27220
+ connection;
27221
+ termination;
27222
+ #process;
27223
+ constructor(agent, cwd, client2) {
27224
+ if (agent.kind === "in-process-acp") {
27225
+ const inProcess = agent.createEndpoint({
27226
+ command: agent.command,
27227
+ cwd,
27228
+ environment: agent.environment
27229
+ });
27230
+ this.#process = { kind: "in-process", endpoint: inProcess };
27231
+ this.termination = inProcess.terminated;
27232
+ this.connection = createAcpClient(client2).connect(inProcess.app());
27229
27233
  return;
27230
27234
  }
27231
- this.#activeNarrativeKey = "";
27232
- await this.#completeNarrative(key);
27233
- };
27234
- finish = async () => {
27235
- await this.finishNarrative();
27236
- for (const key of this.#narrations.keys()) {
27237
- await this.#completeNarrative(key);
27235
+ const child = spawn4(agent.adapterPath, [...agent.arguments], {
27236
+ cwd,
27237
+ detached: process.platform !== "win32",
27238
+ env: { ...process.env, ...agent.environment },
27239
+ shell: false,
27240
+ stdio: ["pipe", "pipe", "pipe"]
27241
+ });
27242
+ this.#process = { kind: "child", child };
27243
+ const stdin = child.stdin;
27244
+ const stdout = child.stdout;
27245
+ const stderr = child.stderr;
27246
+ if (stdin === null || stdout === null || stderr === null) {
27247
+ child.kill("SIGKILL");
27248
+ throw new AcpExecutionError("ACP process streams are unavailable");
27238
27249
  }
27239
- const entries = [...this.#activities.entries()].sort((left, right) => left[1].sequence - right[1].sequence);
27240
- for (const [key, activity2] of entries) {
27241
- const completed = activity2.complete();
27242
- if (completed !== activity2) {
27243
- await this.#record(key, completed);
27250
+ stderr.setEncoding("utf8");
27251
+ stderr.on("data", (chunk) => {
27252
+ process.stderr.write(`[${agent.id}-acp] ${chunk}`);
27253
+ });
27254
+ this.termination = new Promise((resolve9) => {
27255
+ child.once("error", (cause) => {
27256
+ resolve9({ kind: "failed", error: new AcpExecutionError("The ACP process could not run", { cause }) });
27257
+ });
27258
+ child.once("exit", (code, signal) => {
27259
+ resolve9({
27260
+ kind: "failed",
27261
+ error: new AcpExecutionError("The ACP process stopped", { cause: { code, signal } })
27262
+ });
27263
+ });
27264
+ });
27265
+ const stream = ndJsonStream2(createWritableAcpStream(stdin), readableWebStream(stdout));
27266
+ this.connection = createAcpClient(client2).connect(stream);
27267
+ }
27268
+ get inProcessAgent() {
27269
+ return this.#process.kind === "in-process" ? this.#process.endpoint : null;
27270
+ }
27271
+ captureProcessTree = async () => this.#process.kind === "child" ? await captureProcessTree(this.#process.child) : [];
27272
+ closeProcess = async (capturedProcesses = []) => {
27273
+ try {
27274
+ if (this.#process.kind === "in-process") {
27275
+ await this.#process.endpoint.close();
27276
+ return;
27244
27277
  }
27245
- }
27246
- };
27247
- // Materialize a streamed narration as one completed snapshot activity. The
27248
- // incremental events carried the text; this final event gives consumers the
27249
- // whole narration with its terminal status, as a single bounded item.
27250
- #completeNarrative = async (key) => {
27251
- const narration = this.#narrations.get(key);
27252
- if (narration === void 0) {
27253
- return;
27254
- }
27255
- this.#narrations.delete(key);
27256
- const previous = this.#activities.get(key);
27257
- const detail = narration.truncated ? {
27258
- capturedBytes: encodedByteLength({ content: [], input: "", output: narration.output }),
27259
- kind: "truncated",
27260
- originalBytes: narration.originalBytes
27261
- } : captureActivityDetail([], "", narration.output);
27262
- await this.#record(
27263
- key,
27264
- new AcpActivity(
27265
- narration.activityId,
27266
- narration.activityType,
27267
- "",
27268
- [],
27269
- "",
27270
- truncate2(narration.output, AGENT_ACTIVITY_DETAIL_LIMIT),
27271
- narration.sequence,
27272
- "completed",
27273
- narration.activityType === "reasoning" ? "Reasoning" : "Progress update",
27274
- narration.activityType === "reasoning" ? "think" : "",
27275
- previous?.content ?? [],
27276
- detail
27277
- )
27278
- );
27279
- };
27280
- #identity = (key) => {
27281
- const existing = this.#identities.get(key);
27282
- if (existing !== void 0) {
27283
- return existing;
27284
- }
27285
- const identity2 = new ActivityIdentity(`activity-${crypto.randomUUID()}`, this.#nextSequence);
27286
- this.#nextSequence += 1;
27287
- this.#identities.set(key, identity2);
27288
- return identity2;
27289
- };
27290
- #record = async (key, activity2) => {
27291
- this.#activities.set(key, activity2);
27292
- await this.#onActivity(activity2);
27293
- };
27294
- #recordPlanEntries = async (key, entries) => {
27295
- const identity2 = this.#identity(key);
27296
- await this.#record(
27297
- key,
27298
- new AcpActivity(
27299
- identity2.id,
27300
- "plan",
27301
- "",
27302
- [],
27303
- "",
27304
- formatPlanEntries(entries),
27305
- identity2.sequence,
27306
- planStatus(entries),
27307
- "Plan",
27308
- ""
27309
- )
27310
- );
27311
- };
27312
- };
27313
-
27314
- // src/acp/native-session.ts
27315
- var path = external_exports.string().min(1).max(2048).refine((value) => !value.includes("\0"));
27316
- var title = external_exports.string().transform((value) => value.slice(0, 500));
27317
- var nativeSessionIdSchema = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/);
27318
- var nativeSessionInfoSchema = external_exports.object({
27319
- sessionId: nativeSessionIdSchema,
27320
- cwd: path,
27321
- additionalDirectories: external_exports.array(path).max(16).default([]).readonly(),
27322
- title: title.nullish(),
27323
- updatedAt: external_exports.iso.datetime({ offset: true }).nullish()
27324
- }).readonly();
27325
- var nativeSessionPageSchema = external_exports.object({
27326
- sessions: external_exports.array(nativeSessionInfoSchema).max(500).readonly(),
27327
- nextCursor: external_exports.string().min(1).max(4096).nullish()
27328
- }).readonly();
27329
-
27330
- // src/acp/process-endpoint.ts
27331
- import { spawn as spawn4 } from "node:child_process";
27332
- import { ndJsonStream as ndJsonStream2, RequestError as RequestError3 } from "@agentclientprotocol/sdk";
27333
-
27334
- // src/acp/value-utils.ts
27335
- function truncate3(value, maximumLength) {
27336
- return value.length <= maximumLength ? value : `${value.slice(0, Math.max(0, maximumLength - 1))}\u2026`;
27337
- }
27338
- function isRecord6(value) {
27339
- return typeof value === "object" && value !== null && !Array.isArray(value);
27340
- }
27341
- function readString2(value, fallback = "") {
27342
- return typeof value === "string" ? value : fallback;
27343
- }
27344
-
27345
- // src/acp/process-endpoint.ts
27346
- function readableWebStream(input2) {
27347
- let streamOpen = true;
27348
- return new ReadableStream({
27349
- start(controller) {
27350
- input2.on("data", (chunk) => {
27351
- if (!streamOpen) {
27352
- return;
27353
- }
27354
- if (chunk instanceof Uint8Array) {
27355
- controller.enqueue(new Uint8Array(chunk));
27356
- return;
27357
- }
27358
- streamOpen = false;
27359
- controller.error(new Error("ACP process produced a non-binary chunk"));
27360
- });
27361
- input2.once("end", () => {
27362
- if (!streamOpen) {
27363
- return;
27364
- }
27365
- streamOpen = false;
27366
- controller.close();
27367
- });
27368
- input2.once("error", (error62) => {
27369
- if (!streamOpen) {
27370
- return;
27371
- }
27372
- streamOpen = false;
27373
- controller.error(error62);
27374
- });
27375
- },
27376
- cancel() {
27377
- streamOpen = false;
27378
- }
27379
- });
27380
- }
27381
- function createWritableAcpStream(output2) {
27382
- let outputFailure;
27383
- const pendingWriteFailures = /* @__PURE__ */ new Set();
27384
- const fail = (error62) => {
27385
- outputFailure = error62;
27386
- for (const reject of pendingWriteFailures) {
27387
- reject(error62);
27388
- }
27389
- pendingWriteFailures.clear();
27390
- };
27391
- output2.on("error", fail);
27392
- output2.once("close", () => {
27393
- if (outputFailure === void 0) {
27394
- fail(new Error("ACP process input closed"));
27395
- }
27396
- });
27397
- return new WritableStream({
27398
- write(chunk) {
27399
- if (outputFailure !== void 0) {
27400
- return Promise.reject(outputFailure);
27401
- }
27402
- return new Promise((resolve9, reject) => {
27403
- pendingWriteFailures.add(reject);
27404
- output2.write(chunk, (error62) => {
27405
- pendingWriteFailures.delete(reject);
27406
- if (error62) {
27407
- outputFailure = error62;
27408
- reject(error62);
27409
- return;
27410
- }
27411
- if (outputFailure !== void 0) {
27412
- reject(outputFailure);
27413
- return;
27414
- }
27415
- resolve9();
27416
- });
27417
- });
27418
- }
27419
- });
27420
- }
27421
- var AcpEndpoint = class {
27422
- connection;
27423
- termination;
27424
- #process;
27425
- constructor(agent, cwd, client2) {
27426
- if (agent.kind === "in-process-acp") {
27427
- const inProcess = agent.createEndpoint({
27428
- command: agent.command,
27429
- cwd,
27430
- environment: agent.environment
27431
- });
27432
- this.#process = { kind: "in-process", endpoint: inProcess };
27433
- this.termination = inProcess.terminated;
27434
- this.connection = createAcpClient(client2).connect(inProcess.app());
27435
- return;
27436
- }
27437
- const child = spawn4(agent.adapterPath, [...agent.arguments], {
27438
- cwd,
27439
- detached: process.platform !== "win32",
27440
- env: { ...process.env, ...agent.environment },
27441
- shell: false,
27442
- stdio: ["pipe", "pipe", "pipe"]
27443
- });
27444
- this.#process = { kind: "child", child };
27445
- const stdin = child.stdin;
27446
- const stdout = child.stdout;
27447
- const stderr = child.stderr;
27448
- if (stdin === null || stdout === null || stderr === null) {
27449
- child.kill("SIGKILL");
27450
- throw new AcpExecutionError("ACP process streams are unavailable");
27451
- }
27452
- stderr.setEncoding("utf8");
27453
- stderr.on("data", (chunk) => {
27454
- process.stderr.write(`[${agent.id}-acp] ${chunk}`);
27455
- });
27456
- this.termination = new Promise((resolve9) => {
27457
- child.once("error", (cause) => {
27458
- resolve9({ kind: "failed", error: new AcpExecutionError("The ACP process could not run", { cause }) });
27459
- });
27460
- child.once("exit", (code, signal) => {
27461
- resolve9({
27462
- kind: "failed",
27463
- error: new AcpExecutionError("The ACP process stopped", { cause: { code, signal } })
27464
- });
27465
- });
27466
- });
27467
- const stream = ndJsonStream2(createWritableAcpStream(stdin), readableWebStream(stdout));
27468
- this.connection = createAcpClient(client2).connect(stream);
27469
- }
27470
- get inProcessAgent() {
27471
- return this.#process.kind === "in-process" ? this.#process.endpoint : null;
27472
- }
27473
- captureProcessTree = async () => this.#process.kind === "child" ? await captureProcessTree(this.#process.child) : [];
27474
- closeProcess = async (capturedProcesses = []) => {
27475
- try {
27476
- if (this.#process.kind === "in-process") {
27477
- await this.#process.endpoint.close();
27478
- return;
27479
- }
27480
- await stopProcessTree(this.#process.child, capturedProcesses);
27481
- } finally {
27482
- this.connection.close();
27278
+ await stopProcessTree(this.#process.child, capturedProcesses);
27279
+ } finally {
27280
+ this.connection.close();
27483
27281
  }
27484
27282
  };
27485
27283
  race = async (operation, exitMessage, signal) => {
@@ -27525,6 +27323,86 @@ var AcpEndpoint = class {
27525
27323
  };
27526
27324
  };
27527
27325
 
27326
+ // src/acp/native-session.ts
27327
+ var path = external_exports.string().min(1).max(2048).refine((value) => !value.includes("\0"));
27328
+ var title = external_exports.string().transform((value) => value.slice(0, 500));
27329
+ var nativeSessionIdSchema = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/);
27330
+ var nativeSessionInfoSchema = external_exports.object({
27331
+ sessionId: nativeSessionIdSchema,
27332
+ cwd: path,
27333
+ additionalDirectories: external_exports.array(path).max(16).default([]).readonly(),
27334
+ title: title.nullish(),
27335
+ updatedAt: external_exports.iso.datetime({ offset: true }).nullish()
27336
+ }).readonly();
27337
+ var nativeSessionPageSchema = external_exports.object({
27338
+ sessions: external_exports.array(nativeSessionInfoSchema).max(500).readonly(),
27339
+ nextCursor: external_exports.string().min(1).max(4096).nullish()
27340
+ }).readonly();
27341
+
27342
+ // src/acp/agent-update-stream.ts
27343
+ var MAX_PENDING_UPDATES = 100;
27344
+ var MAX_PENDING_BYTES = 1024 * 1024;
27345
+ var AgentUpdateStream = class {
27346
+ #selection = { kind: "awaiting-session", notifications: [], bytes: 0 };
27347
+ #tail = Promise.resolve();
27348
+ #consume;
27349
+ constructor(consume) {
27350
+ this.#consume = consume;
27351
+ }
27352
+ sessionId = () => this.#selection.kind === "selected" ? this.#selection.sessionId : "";
27353
+ drained = () => this.#tail;
27354
+ #enqueue = (notification) => {
27355
+ this.#tail = this.#tail.then(async () => await this.#consume(notification));
27356
+ return this.#tail;
27357
+ };
27358
+ receive = (notification) => {
27359
+ const selection = this.#selection;
27360
+ switch (selection.kind) {
27361
+ case "selected":
27362
+ return this.#enqueue(notification);
27363
+ case "awaiting-session": {
27364
+ const bytes = selection.bytes + Buffer.byteLength(JSON.stringify(notification));
27365
+ if (selection.notifications.length >= MAX_PENDING_UPDATES || bytes > MAX_PENDING_BYTES) {
27366
+ return Promise.reject(
27367
+ new AcpExecutionError(
27368
+ "ACP agent sent too many updates before creating its session",
27369
+ {},
27370
+ "agent_update_limit"
27371
+ )
27372
+ );
27373
+ }
27374
+ this.#selection = {
27375
+ kind: "awaiting-session",
27376
+ notifications: [...selection.notifications, notification],
27377
+ bytes
27378
+ };
27379
+ return Promise.resolve();
27380
+ }
27381
+ }
27382
+ };
27383
+ select = (sessionId) => {
27384
+ const selected = nativeSessionIdSchema.parse(sessionId);
27385
+ const selection = this.#selection;
27386
+ switch (selection.kind) {
27387
+ case "selected":
27388
+ if (selection.sessionId !== selected) {
27389
+ throw new AcpExecutionError(
27390
+ "ACP agent attempted to replace the selected session",
27391
+ {},
27392
+ "invalid_agent_session"
27393
+ );
27394
+ }
27395
+ return;
27396
+ case "awaiting-session":
27397
+ this.#selection = { kind: "selected", sessionId: selected };
27398
+ for (const notification of selection.notifications) {
27399
+ void this.#enqueue(notification);
27400
+ }
27401
+ return;
27402
+ }
27403
+ };
27404
+ };
27405
+
27528
27406
  // src/acp/session-config/session-config-protocol.ts
27529
27407
  import { methods as methods7 } from "@agentclientprotocol/sdk";
27530
27408
  var MAXIMUM_CONFIG_OPTIONS = 100;
@@ -27689,83 +27567,398 @@ var StandardSessionConfigProtocol = class {
27689
27567
  if (existing === void 0) {
27690
27568
  return current;
27691
27569
  }
27692
- if (existing.type === "select" && existing.category === "mode") {
27693
- await transport.request(
27694
- methods7.agent.session.setMode,
27695
- { modeId: change.value, sessionId: nativeSessionId },
27696
- "ACP agent exited while setting the session mode",
27697
- change.signal
27698
- );
27699
- return updateCurrentValue(current, existing.id, change.value);
27570
+ if (existing.type === "select" && existing.category === "mode") {
27571
+ await transport.request(
27572
+ methods7.agent.session.setMode,
27573
+ { modeId: change.value, sessionId: nativeSessionId },
27574
+ "ACP agent exited while setting the session mode",
27575
+ change.signal
27576
+ );
27577
+ return updateCurrentValue(current, existing.id, change.value);
27578
+ }
27579
+ const params = existing.type === "boolean" ? {
27580
+ configId: existing.id,
27581
+ sessionId: nativeSessionId,
27582
+ type: "boolean",
27583
+ value: change.booleanValue
27584
+ } : {
27585
+ configId: existing.id,
27586
+ sessionId: nativeSessionId,
27587
+ value: change.value
27588
+ };
27589
+ const response = await transport.request(
27590
+ methods7.agent.session.setConfigOption,
27591
+ params,
27592
+ "ACP agent exited while changing session configuration",
27593
+ change.signal
27594
+ );
27595
+ if (!isRecord7(response) || !Array.isArray(response["configOptions"])) {
27596
+ throw new SessionConfigProtocolError("The Agent returned an invalid session configuration response");
27597
+ }
27598
+ return replaceStandardConfigOptions(current, response["configOptions"]);
27599
+ };
27600
+ normalizeLifecycle = (response) => normalizeStandardLifecycle(response);
27601
+ normalizeUpdate = (current, value) => replaceStandardConfigOptions(current, value);
27602
+ };
27603
+ var standardSessionConfigProtocol = new StandardSessionConfigProtocol();
27604
+
27605
+ // src/acp/session-config/session-config-registry.ts
27606
+ function sessionConfigProtocolForAgent(_agentId) {
27607
+ return standardSessionConfigProtocol;
27608
+ }
27609
+
27610
+ // src/acp/session-contracts.ts
27611
+ var NullAcpSessionObserver = class {
27612
+ onCommands = () => Promise.resolve();
27613
+ onConfig = () => Promise.resolve();
27614
+ onContent = () => Promise.resolve();
27615
+ onElicitation = () => Promise.resolve();
27616
+ onElicitationResolved = () => Promise.resolve();
27617
+ onInfo = () => Promise.resolve();
27618
+ onPermission = () => Promise.resolve();
27619
+ onPermissionResolved = () => Promise.resolve();
27620
+ onUsage = () => Promise.resolve();
27621
+ };
27622
+ var AcpPreparedSession = class {
27623
+ agentName;
27624
+ agentVersion;
27625
+ capabilities;
27626
+ commands;
27627
+ configOptions;
27628
+ restored;
27629
+ constructor(agentName, agentVersion, capabilities, commands, configOptions, restored) {
27630
+ this.agentName = agentName;
27631
+ this.agentVersion = agentVersion;
27632
+ this.capabilities = capabilities;
27633
+ this.commands = commands;
27634
+ this.configOptions = configOptions;
27635
+ this.restored = restored;
27636
+ }
27637
+ };
27638
+ var AcpAgentSettingsSnapshot = class {
27639
+ agentName;
27640
+ agentVersion;
27641
+ configOptions;
27642
+ constructor(agentName, agentVersion, configOptions) {
27643
+ this.agentName = agentName;
27644
+ this.agentVersion = agentVersion;
27645
+ this.configOptions = configOptions;
27646
+ }
27647
+ };
27648
+
27649
+ // src/acp/activity.ts
27650
+ var AcpActivityNarration = class {
27651
+ activityId;
27652
+ activityType;
27653
+ sequence;
27654
+ text;
27655
+ constructor(activityId, activityType, sequence, text2) {
27656
+ this.activityId = activityId;
27657
+ this.activityType = activityType;
27658
+ this.sequence = sequence;
27659
+ this.text = text2;
27660
+ }
27661
+ };
27662
+ var AcpActivity = class _AcpActivity {
27663
+ activityId;
27664
+ activityType;
27665
+ input;
27666
+ locations;
27667
+ name;
27668
+ output;
27669
+ sequence;
27670
+ status;
27671
+ title;
27672
+ toolKind;
27673
+ content;
27674
+ detail;
27675
+ constructor(activityId, activityType, input2, locations, name, output2, sequence, status, title2, toolKind, content = [], detail = captureActivityDetail(content, input2, output2)) {
27676
+ this.activityId = activityId;
27677
+ this.activityType = activityType;
27678
+ this.input = input2;
27679
+ this.locations = locations;
27680
+ this.name = name;
27681
+ this.output = output2;
27682
+ this.sequence = sequence;
27683
+ this.status = status;
27684
+ this.title = title2;
27685
+ this.toolKind = toolKind;
27686
+ this.content = content;
27687
+ this.detail = detail;
27688
+ }
27689
+ complete = () => (this.activityType === "progress" || this.activityType === "reasoning") && (this.status === "pending" || this.status === "running") ? new _AcpActivity(
27690
+ this.activityId,
27691
+ this.activityType,
27692
+ this.input,
27693
+ this.locations,
27694
+ this.name,
27695
+ this.output,
27696
+ this.sequence,
27697
+ "completed",
27698
+ this.title,
27699
+ this.toolKind,
27700
+ this.content,
27701
+ this.detail
27702
+ ) : this;
27703
+ };
27704
+ var ActivityIdentity = class {
27705
+ id;
27706
+ sequence;
27707
+ constructor(id, sequence) {
27708
+ this.id = id;
27709
+ this.sequence = sequence;
27710
+ }
27711
+ };
27712
+ var AcpActivityTracker = class {
27713
+ #activities = /* @__PURE__ */ new Map();
27714
+ #identities = /* @__PURE__ */ new Map();
27715
+ #narrations = /* @__PURE__ */ new Map();
27716
+ #onActivity;
27717
+ #onNarration;
27718
+ #prepareContent;
27719
+ #activeNarrativeKey = "";
27720
+ #nextSequence = 0;
27721
+ constructor(onActivity, onNarration, prepareContent = (content) => Promise.resolve(content)) {
27722
+ this.#onActivity = onActivity;
27723
+ this.#onNarration = onNarration;
27724
+ this.#prepareContent = prepareContent;
27725
+ }
27726
+ recordNarrative = async (activityType, messageId, text2) => {
27727
+ const key = `${activityType}:${messageId}`;
27728
+ if (this.#activeNarrativeKey !== key) {
27729
+ await this.finishNarrative();
27730
+ }
27731
+ const identity2 = this.#identity(key);
27732
+ const previous = this.#narrations.get(key);
27733
+ const previousOutput = previous?.output ?? "";
27734
+ const remaining = Math.max(0, AGENT_ACTIVITY_DETAIL_LIMIT - previousOutput.length);
27735
+ this.#narrations.set(key, {
27736
+ activityId: identity2.id,
27737
+ activityType,
27738
+ output: `${previousOutput}${text2.slice(0, remaining)}`,
27739
+ originalBytes: (previous?.originalBytes ?? 0) + new TextEncoder().encode(text2).byteLength,
27740
+ sequence: identity2.sequence,
27741
+ truncated: (previous?.truncated ?? false) || text2.length > remaining
27742
+ });
27743
+ if (previous === void 0) {
27744
+ await this.#record(key, this.#narrativeSnapshot(identity2, activityType, "", "running"));
27745
+ }
27746
+ this.#activeNarrativeKey = key;
27747
+ if (text2.length > 0) {
27748
+ await this.#onNarration(new AcpActivityNarration(identity2.id, activityType, identity2.sequence, text2));
27749
+ }
27750
+ };
27751
+ #narrativeSnapshot = (identity2, activityType, output2, status) => new AcpActivity(
27752
+ identity2.id,
27753
+ activityType,
27754
+ "",
27755
+ [],
27756
+ "",
27757
+ truncate2(output2, AGENT_ACTIVITY_DETAIL_LIMIT),
27758
+ identity2.sequence,
27759
+ status,
27760
+ activityType === "reasoning" ? "Reasoning" : "Progress update",
27761
+ activityType === "reasoning" ? "think" : ""
27762
+ );
27763
+ recordPlan = async (plan) => {
27764
+ await this.finishNarrative();
27765
+ await this.#recordPlanEntries("plan:default", plan.entries);
27766
+ };
27767
+ recordPlanUpdate = async (update) => {
27768
+ await this.finishNarrative();
27769
+ const plan = update.plan;
27770
+ const key = `plan:${plan.planId}`;
27771
+ if (plan.type === "items") {
27772
+ await this.#recordPlanEntries(key, plan.entries);
27773
+ return;
27774
+ }
27775
+ const identity2 = this.#identity(key);
27776
+ const output2 = plan.type === "markdown" ? plan.content : `Plan file: ${plan.uri}`;
27777
+ await this.#record(
27778
+ key,
27779
+ new AcpActivity(
27780
+ identity2.id,
27781
+ "plan",
27782
+ "",
27783
+ [],
27784
+ "",
27785
+ truncate2(output2, AGENT_ACTIVITY_DETAIL_LIMIT),
27786
+ identity2.sequence,
27787
+ "running",
27788
+ "Plan",
27789
+ ""
27790
+ )
27791
+ );
27792
+ };
27793
+ removePlan = async (update) => {
27794
+ await this.finishNarrative();
27795
+ const key = `plan:${update.planId}`;
27796
+ const previous = this.#activities.get(key);
27797
+ if (previous !== void 0) {
27798
+ await this.#record(
27799
+ key,
27800
+ new AcpActivity(
27801
+ previous.activityId,
27802
+ previous.activityType,
27803
+ previous.input,
27804
+ previous.locations,
27805
+ previous.name,
27806
+ previous.output,
27807
+ previous.sequence,
27808
+ "completed",
27809
+ previous.title,
27810
+ previous.toolKind,
27811
+ previous.content,
27812
+ previous.detail
27813
+ )
27814
+ );
27815
+ }
27816
+ };
27817
+ recordToolCall = async (update) => {
27818
+ await this.finishNarrative();
27819
+ const key = `tool:${update.toolCallId}`;
27820
+ const identity2 = this.#identity(key);
27821
+ const output2 = update.rawOutput === void 0 ? readContentOutput(update.content) : formatUnknown(update.rawOutput);
27822
+ const detailInput = update.rawInput === void 0 ? "" : formatUnknownDetail(update.rawInput);
27823
+ const detailOutput = update.rawOutput === void 0 ? readContentOutputDetail(update.content) : formatUnknownDetail(update.rawOutput);
27824
+ const detailContent = await normalizeToolContent(
27825
+ toolContent(update.content, update.rawOutput),
27826
+ this.#prepareContent
27827
+ );
27828
+ await this.#record(
27829
+ key,
27830
+ new AcpActivity(
27831
+ identity2.id,
27832
+ "tool",
27833
+ update.rawInput === void 0 ? "" : formatUnknown(update.rawInput),
27834
+ normalizeLocations(update.locations ?? []),
27835
+ truncate2(update.name ?? "", 128),
27836
+ output2,
27837
+ identity2.sequence,
27838
+ normalizeToolStatus(update.status ?? "pending", "pending"),
27839
+ normalizeTitle(update.title, "Tool call"),
27840
+ update.kind ?? "other",
27841
+ detailContent.slice(0, 100).map(summarizeDisplayContent),
27842
+ captureActivityDetail(detailContent, detailInput, detailOutput)
27843
+ )
27844
+ );
27845
+ };
27846
+ recordToolCallUpdate = async (update) => {
27847
+ await this.finishNarrative();
27848
+ const key = `tool:${update.toolCallId}`;
27849
+ const previous = this.#activities.get(key);
27850
+ const identity2 = this.#identity(key);
27851
+ const previousDetail = recordedDetail(previous);
27852
+ const output2 = update.rawOutput !== void 0 ? formatUnknown(update.rawOutput) : update.content !== void 0 && update.content !== null ? readContentOutput(update.content) : previous?.output ?? "";
27853
+ const nextContent = toolContent(update.content, update.rawOutput);
27854
+ const content = nextContent.length === 0 ? previous?.content ?? [] : await normalizeToolContent(nextContent, this.#prepareContent);
27855
+ const detailInput = update.rawInput === void 0 ? previousDetail?.input ?? previous?.input ?? "" : formatUnknownDetail(update.rawInput);
27856
+ const detailOutput = update.rawOutput !== void 0 ? formatUnknownDetail(update.rawOutput) : update.content !== void 0 && update.content !== null ? readContentOutputDetail(update.content) : previousDetail?.output ?? previous?.output ?? "";
27857
+ const detailContent = nextContent.length === 0 ? previousDetail?.content ?? previous?.content ?? [] : content;
27858
+ await this.#record(
27859
+ key,
27860
+ new AcpActivity(
27861
+ identity2.id,
27862
+ "tool",
27863
+ update.rawInput === void 0 ? previous?.input ?? "" : formatUnknown(update.rawInput),
27864
+ update.locations === void 0 || update.locations === null ? previous?.locations ?? [] : normalizeLocations(update.locations),
27865
+ update.name === void 0 || update.name === null ? previous?.name ?? "" : truncate2(update.name, 128),
27866
+ output2,
27867
+ identity2.sequence,
27868
+ update.status === void 0 || update.status === null ? previous?.status ?? "pending" : normalizeToolStatus(update.status, previous?.status ?? "pending"),
27869
+ update.title === void 0 || update.title === null ? previous?.title ?? "Tool call" : normalizeTitle(update.title, "Tool call"),
27870
+ update.kind === void 0 || update.kind === null ? previous?.toolKind ?? "other" : update.kind,
27871
+ content.slice(0, 100).map(summarizeDisplayContent),
27872
+ captureActivityDetail(detailContent, detailInput, detailOutput)
27873
+ )
27874
+ );
27875
+ };
27876
+ finishNarrative = async () => {
27877
+ const key = this.#activeNarrativeKey;
27878
+ if (key.length === 0) {
27879
+ return;
27880
+ }
27881
+ this.#activeNarrativeKey = "";
27882
+ await this.#completeNarrative(key);
27883
+ };
27884
+ finish = async () => {
27885
+ await this.finishNarrative();
27886
+ for (const key of this.#narrations.keys()) {
27887
+ await this.#completeNarrative(key);
27888
+ }
27889
+ const entries = [...this.#activities.entries()].sort((left, right) => left[1].sequence - right[1].sequence);
27890
+ for (const [key, activity2] of entries) {
27891
+ const completed = activity2.complete();
27892
+ if (completed !== activity2) {
27893
+ await this.#record(key, completed);
27894
+ }
27895
+ }
27896
+ };
27897
+ // Materialize a streamed narration as one completed snapshot activity. The
27898
+ // incremental events carried the text; this final event gives consumers the
27899
+ // whole narration with its terminal status, as a single bounded item.
27900
+ #completeNarrative = async (key) => {
27901
+ const narration = this.#narrations.get(key);
27902
+ if (narration === void 0) {
27903
+ return;
27700
27904
  }
27701
- const params = existing.type === "boolean" ? {
27702
- configId: existing.id,
27703
- sessionId: nativeSessionId,
27704
- type: "boolean",
27705
- value: change.booleanValue
27706
- } : {
27707
- configId: existing.id,
27708
- sessionId: nativeSessionId,
27709
- value: change.value
27710
- };
27711
- const response = await transport.request(
27712
- methods7.agent.session.setConfigOption,
27713
- params,
27714
- "ACP agent exited while changing session configuration",
27715
- change.signal
27905
+ this.#narrations.delete(key);
27906
+ const previous = this.#activities.get(key);
27907
+ const detail = narration.truncated ? {
27908
+ capturedBytes: encodedByteLength({ content: [], input: "", output: narration.output }),
27909
+ kind: "truncated",
27910
+ originalBytes: narration.originalBytes
27911
+ } : captureActivityDetail([], "", narration.output);
27912
+ await this.#record(
27913
+ key,
27914
+ new AcpActivity(
27915
+ narration.activityId,
27916
+ narration.activityType,
27917
+ "",
27918
+ [],
27919
+ "",
27920
+ truncate2(narration.output, AGENT_ACTIVITY_DETAIL_LIMIT),
27921
+ narration.sequence,
27922
+ "completed",
27923
+ narration.activityType === "reasoning" ? "Reasoning" : "Progress update",
27924
+ narration.activityType === "reasoning" ? "think" : "",
27925
+ previous?.content ?? [],
27926
+ detail
27927
+ )
27716
27928
  );
27717
- if (!isRecord7(response) || !Array.isArray(response["configOptions"])) {
27718
- throw new SessionConfigProtocolError("The Agent returned an invalid session configuration response");
27929
+ };
27930
+ #identity = (key) => {
27931
+ const existing = this.#identities.get(key);
27932
+ if (existing !== void 0) {
27933
+ return existing;
27719
27934
  }
27720
- return replaceStandardConfigOptions(current, response["configOptions"]);
27935
+ const identity2 = new ActivityIdentity(`activity-${crypto.randomUUID()}`, this.#nextSequence);
27936
+ this.#nextSequence += 1;
27937
+ this.#identities.set(key, identity2);
27938
+ return identity2;
27939
+ };
27940
+ #record = async (key, activity2) => {
27941
+ this.#activities.set(key, activity2);
27942
+ await this.#onActivity(activity2);
27943
+ };
27944
+ #recordPlanEntries = async (key, entries) => {
27945
+ const identity2 = this.#identity(key);
27946
+ await this.#record(
27947
+ key,
27948
+ new AcpActivity(
27949
+ identity2.id,
27950
+ "plan",
27951
+ "",
27952
+ [],
27953
+ "",
27954
+ formatPlanEntries(entries),
27955
+ identity2.sequence,
27956
+ planStatus(entries),
27957
+ "Plan",
27958
+ ""
27959
+ )
27960
+ );
27721
27961
  };
27722
- normalizeLifecycle = (response) => normalizeStandardLifecycle(response);
27723
- normalizeUpdate = (current, value) => replaceStandardConfigOptions(current, value);
27724
- };
27725
- var standardSessionConfigProtocol = new StandardSessionConfigProtocol();
27726
-
27727
- // src/acp/session-config/session-config-registry.ts
27728
- function sessionConfigProtocolForAgent(_agentId) {
27729
- return standardSessionConfigProtocol;
27730
- }
27731
-
27732
- // src/acp/session-contracts.ts
27733
- var NullAcpSessionObserver = class {
27734
- onCommands = () => Promise.resolve();
27735
- onConfig = () => Promise.resolve();
27736
- onContent = () => Promise.resolve();
27737
- onElicitation = () => Promise.resolve();
27738
- onElicitationResolved = () => Promise.resolve();
27739
- onInfo = () => Promise.resolve();
27740
- onPermission = () => Promise.resolve();
27741
- onPermissionResolved = () => Promise.resolve();
27742
- onUsage = () => Promise.resolve();
27743
- };
27744
- var AcpPreparedSession = class {
27745
- agentName;
27746
- agentVersion;
27747
- capabilities;
27748
- commands;
27749
- configOptions;
27750
- restored;
27751
- constructor(agentName, agentVersion, capabilities, commands, configOptions, restored) {
27752
- this.agentName = agentName;
27753
- this.agentVersion = agentVersion;
27754
- this.capabilities = capabilities;
27755
- this.commands = commands;
27756
- this.configOptions = configOptions;
27757
- this.restored = restored;
27758
- }
27759
- };
27760
- var AcpAgentSettingsSnapshot = class {
27761
- agentName;
27762
- agentVersion;
27763
- configOptions;
27764
- constructor(agentName, agentVersion, configOptions) {
27765
- this.agentName = agentName;
27766
- this.agentVersion = agentVersion;
27767
- this.configOptions = configOptions;
27768
- }
27769
27962
  };
27770
27963
 
27771
27964
  // src/acp/session-history.ts
@@ -34143,10 +34336,8 @@ var SqliteAcpSessionStore = class {
34143
34336
  };
34144
34337
  };
34145
34338
 
34146
- // src/acp/process-session.ts
34339
+ // src/acp/agent-session.ts
34147
34340
  var PROCESS_STOP_TIMEOUT_MILLISECONDS = 1e3;
34148
- var MAX_PRE_SESSION_UPDATES = 100;
34149
- var MAX_PRE_SESSION_UPDATE_BYTES = 1024 * 1024;
34150
34341
  var RetryableAcpInitializationError = class extends AcpExecutionError {
34151
34342
  constructor(cause) {
34152
34343
  super("ACP agent initialization failed", { cause });
@@ -34161,8 +34352,8 @@ function recordsEqual(left, right) {
34161
34352
  const rightEntries = Object.entries(right);
34162
34353
  return leftEntries.length === rightEntries.length && leftEntries.every(([name, value]) => right[name] === value);
34163
34354
  }
34164
- var AcpProcessSession = class _AcpProcessSession {
34165
- #endpoint;
34355
+ var AgentSession = class _AgentSession {
34356
+ #connection;
34166
34357
  #interactions;
34167
34358
  #additionalDirectories;
34168
34359
  #agentId;
@@ -34170,12 +34361,11 @@ var AcpProcessSession = class _AcpProcessSession {
34170
34361
  #environment;
34171
34362
  #getObserver;
34172
34363
  #mobiusSessionId;
34173
- #preSessionUpdates = [];
34364
+ #updates;
34174
34365
  #metrics;
34175
34366
  #sessionConfigProtocol;
34176
34367
  #store;
34177
34368
  #verifiedAgentVersion;
34178
- #preSessionUpdateBytes = 0;
34179
34369
  #agentName = "";
34180
34370
  #agentVersion = "";
34181
34371
  #bufferedAgentText = [];
@@ -34183,7 +34373,6 @@ var AcpProcessSession = class _AcpProcessSession {
34183
34373
  #commands = [];
34184
34374
  #configRevision = 0;
34185
34375
  #configOptions = [];
34186
- #nativeSessionId = "";
34187
34376
  #prompted = false;
34188
34377
  #nativePrompt = null;
34189
34378
  #replay = {
@@ -34193,10 +34382,11 @@ var AcpProcessSession = class _AcpProcessSession {
34193
34382
  #sessionTitle = null;
34194
34383
  #sessionUpdatedAt = "";
34195
34384
  #turn = new IdleAcpTurn();
34196
- #updateTail = Promise.resolve();
34197
34385
  constructor(agent, cwd, additionalDirectories, mobiusSessionId, getObserver, store, metrics) {
34386
+ this.#updates = new AgentUpdateStream((notification) => this.#processUpdate(notification));
34198
34387
  this.#additionalDirectories = [...additionalDirectories];
34199
34388
  this.#agentId = agent.id;
34389
+ this.#commands = [];
34200
34390
  this.#cwd = cwd;
34201
34391
  this.#environment = agent.environment;
34202
34392
  this.#getObserver = getObserver;
@@ -34211,7 +34401,7 @@ var AcpProcessSession = class _AcpProcessSession {
34211
34401
  assertNativeSession: (sessionId) => this.assertNativeSession(sessionId),
34212
34402
  observer: getObserver
34213
34403
  });
34214
- this.#endpoint = new AcpEndpoint(agent, cwd, this);
34404
+ this.#connection = new AgentConnection(agent, cwd, this);
34215
34405
  }
34216
34406
  static async #start(options, getObserver, store, initialize, metrics) {
34217
34407
  for (let attempt = 1; attempt <= 2; attempt += 1) {
@@ -34234,7 +34424,7 @@ var AcpProcessSession = class _AcpProcessSession {
34234
34424
  }
34235
34425
  const runtime = metrics.measureSync(
34236
34426
  "process-spawn",
34237
- () => new _AcpProcessSession(
34427
+ () => new _AgentSession(
34238
34428
  options.agent,
34239
34429
  options.cwd,
34240
34430
  options.additionalDirectories,
@@ -34264,14 +34454,14 @@ var AcpProcessSession = class _AcpProcessSession {
34264
34454
  }
34265
34455
  throw new AcpExecutionError("ACP agent initialization failed");
34266
34456
  }
34267
- static start = async (options, getObserver, store, metrics = unmeasuredOperationMetrics) => await _AcpProcessSession.#start(
34457
+ static start = async (options, getObserver, store, metrics = unmeasuredOperationMetrics) => await _AgentSession.#start(
34268
34458
  options,
34269
34459
  getObserver,
34270
34460
  store,
34271
34461
  async (runtime) => await runtime.initialize(options.signal, options.origin),
34272
34462
  metrics
34273
34463
  );
34274
- static startNativeSessionBrowser = async (options, getObserver, store) => await _AcpProcessSession.#start(
34464
+ static startNativeSessionBrowser = async (options, getObserver, store) => await _AgentSession.#start(
34275
34465
  options,
34276
34466
  getObserver,
34277
34467
  store,
@@ -34304,20 +34494,20 @@ var AcpProcessSession = class _AcpProcessSession {
34304
34494
  this.#replay = { kind: "capture", history };
34305
34495
  try {
34306
34496
  await this.race(
34307
- this.#endpoint.connection.agent.request(
34497
+ this.#connection.connection.agent.request(
34308
34498
  methods8.agent.session.load,
34309
34499
  {
34310
34500
  additionalDirectories: [...this.#additionalDirectories],
34311
34501
  cwd: this.#cwd,
34312
34502
  mcpServers: [],
34313
- sessionId: this.#nativeSessionId
34503
+ sessionId: this.#updates.sessionId()
34314
34504
  },
34315
34505
  { cancellationSignal: signal }
34316
34506
  ),
34317
34507
  "ACP agent exited while loading history",
34318
34508
  signal
34319
34509
  );
34320
- await this.#updateTail;
34510
+ await this.#updates.drained();
34321
34511
  signal.throwIfAborted();
34322
34512
  return await embedLocalHistoryImages(await history.snapshot(), signal);
34323
34513
  } finally {
@@ -34413,9 +34603,9 @@ var AcpProcessSession = class _AcpProcessSession {
34413
34603
  await this.#metrics.measure("agent-initialize", async () => await this.#initializeAgentOperation(signal));
34414
34604
  }
34415
34605
  async #initializeAgentOperation(signal) {
34416
- if (this.#endpoint.inProcessAgent !== null) {
34606
+ if (this.#connection.inProcessAgent !== null) {
34417
34607
  await this.race(
34418
- this.#endpoint.inProcessAgent.initialize(signal),
34608
+ this.#connection.inProcessAgent.initialize(signal),
34419
34609
  "The Codex app-server exited during initialization",
34420
34610
  signal
34421
34611
  ).catch((cause) => {
@@ -34424,7 +34614,7 @@ var AcpProcessSession = class _AcpProcessSession {
34424
34614
  });
34425
34615
  }
34426
34616
  const initialized = await this.race(
34427
- this.#endpoint.connection.agent.request(
34617
+ this.#connection.connection.agent.request(
34428
34618
  methods8.agent.initialize,
34429
34619
  {
34430
34620
  clientCapabilities: {
@@ -34503,7 +34693,7 @@ var AcpProcessSession = class _AcpProcessSession {
34503
34693
  const forked = await this.#metrics.measure(
34504
34694
  "session-fork",
34505
34695
  async () => await this.race(
34506
- this.#endpoint.connection.agent.request(
34696
+ this.#connection.connection.agent.request(
34507
34697
  methods8.agent.session.fork,
34508
34698
  {
34509
34699
  sessionId: nativeSessionIdSchema.parse(origin.nativeSessionId),
@@ -34518,7 +34708,7 @@ var AcpProcessSession = class _AcpProcessSession {
34518
34708
  )
34519
34709
  );
34520
34710
  this.selectNativeSession(forked.sessionId);
34521
- if (this.#nativeSessionId === origin.nativeSessionId || this.#store.findNative(this.#agentId, this.#nativeSessionId).length > 0) {
34711
+ if (this.#updates.sessionId() === origin.nativeSessionId || this.#store.findNative(this.#agentId, this.#updates.sessionId()).length > 0) {
34522
34712
  throw new AcpExecutionError(
34523
34713
  "The Agent did not create an independent fork",
34524
34714
  {},
@@ -34537,13 +34727,13 @@ var AcpProcessSession = class _AcpProcessSession {
34537
34727
  lifecycleResponse = await this.#metrics.measure(
34538
34728
  "session-resume",
34539
34729
  async () => await this.race(
34540
- this.#endpoint.connection.agent.request(
34730
+ this.#connection.connection.agent.request(
34541
34731
  methods8.agent.session.resume,
34542
34732
  {
34543
34733
  additionalDirectories: [...this.#additionalDirectories],
34544
34734
  cwd: this.#cwd,
34545
34735
  mcpServers: [],
34546
- sessionId: this.#nativeSessionId
34736
+ sessionId: this.#updates.sessionId()
34547
34737
  },
34548
34738
  { cancellationSignal: signal }
34549
34739
  ),
@@ -34557,13 +34747,13 @@ var AcpProcessSession = class _AcpProcessSession {
34557
34747
  lifecycleResponse = await this.#metrics.measure(
34558
34748
  "session-load",
34559
34749
  async () => await this.race(
34560
- this.#endpoint.connection.agent.request(
34750
+ this.#connection.connection.agent.request(
34561
34751
  methods8.agent.session.load,
34562
34752
  {
34563
34753
  additionalDirectories: [...this.#additionalDirectories],
34564
34754
  cwd: this.#cwd,
34565
34755
  mcpServers: [],
34566
- sessionId: this.#nativeSessionId
34756
+ sessionId: this.#updates.sessionId()
34567
34757
  },
34568
34758
  { cancellationSignal: signal }
34569
34759
  ),
@@ -34572,7 +34762,7 @@ var AcpProcessSession = class _AcpProcessSession {
34572
34762
  )
34573
34763
  );
34574
34764
  } finally {
34575
- await this.#updateTail;
34765
+ await this.#updates.drained();
34576
34766
  this.#replay = { kind: "idle" };
34577
34767
  }
34578
34768
  } else {
@@ -34596,7 +34786,7 @@ var AcpProcessSession = class _AcpProcessSession {
34596
34786
  const created = await this.#metrics.measure(
34597
34787
  "session-new",
34598
34788
  async () => await this.race(
34599
- this.#endpoint.connection.agent.request(
34789
+ this.#connection.connection.agent.request(
34600
34790
  methods8.agent.session.new,
34601
34791
  {
34602
34792
  additionalDirectories: [...this.#additionalDirectories],
@@ -34613,13 +34803,13 @@ var AcpProcessSession = class _AcpProcessSession {
34613
34803
  lifecycleResponse = created;
34614
34804
  }
34615
34805
  this.#configOptions = this.#sessionConfigProtocol.normalizeLifecycle(lifecycleResponse);
34616
- await this.#updateTail;
34806
+ await this.#updates.drained();
34617
34807
  signal.throwIfAborted();
34618
34808
  this.#store.write(
34619
34809
  new AcpStoredSession(
34620
34810
  this.#mobiusSessionId,
34621
34811
  this.#agentId,
34622
- this.#nativeSessionId,
34812
+ this.#updates.sessionId(),
34623
34813
  this.#cwd,
34624
34814
  this.#additionalDirectories,
34625
34815
  this.#prompted,
@@ -34636,7 +34826,7 @@ var AcpProcessSession = class _AcpProcessSession {
34636
34826
  );
34637
34827
  }
34638
34828
  const response = await this.race(
34639
- this.#endpoint.connection.agent.request(methods8.agent.session.list, cursor === null ? {} : { cursor }, {
34829
+ this.#connection.connection.agent.request(methods8.agent.session.list, cursor === null ? {} : { cursor }, {
34640
34830
  cancellationSignal: signal
34641
34831
  }),
34642
34832
  "ACP agent exited while listing sessions",
@@ -34661,7 +34851,7 @@ var AcpProcessSession = class _AcpProcessSession {
34661
34851
  );
34662
34852
  }
34663
34853
  await this.race(
34664
- this.#endpoint.connection.agent.request(
34854
+ this.#connection.connection.agent.request(
34665
34855
  methods8.agent.session.delete,
34666
34856
  { sessionId: nativeSessionIdSchema.parse(nativeSessionId) },
34667
34857
  { cancellationSignal: signal }
@@ -34670,9 +34860,9 @@ var AcpProcessSession = class _AcpProcessSession {
34670
34860
  signal
34671
34861
  );
34672
34862
  };
34673
- nativeSessionId = () => this.#nativeSessionId;
34863
+ nativeSessionId = () => this.#updates.sessionId();
34674
34864
  adoptNativeSessionId = (sessionId) => {
34675
- if (this.#prompted || this.#nativeSessionId !== sessionId) {
34865
+ if (this.#prompted || this.#updates.sessionId() !== sessionId) {
34676
34866
  throw new AcpExecutionError("The new native Session cannot be adopted", {}, "session_identity_mismatch");
34677
34867
  }
34678
34868
  const previousSessionId = this.#mobiusSessionId;
@@ -34720,10 +34910,10 @@ var AcpProcessSession = class _AcpProcessSession {
34720
34910
  const configured = await this.#sessionConfigProtocol.configure(
34721
34911
  this.#configOptions,
34722
34912
  options,
34723
- this.#nativeSessionId,
34913
+ this.#updates.sessionId(),
34724
34914
  {
34725
34915
  request: async (method, params, failureMessage, signal) => await this.race(
34726
- this.#endpoint.connection.agent.request(method, params, {
34916
+ this.#connection.connection.agent.request(method, params, {
34727
34917
  cancellationSignal: signal
34728
34918
  }),
34729
34919
  failureMessage,
@@ -34739,7 +34929,7 @@ var AcpProcessSession = class _AcpProcessSession {
34739
34929
  "invalid_session_configuration"
34740
34930
  );
34741
34931
  }
34742
- await this.#updateTail;
34932
+ await this.#updates.drained();
34743
34933
  if (this.#configRevision === configRevision) {
34744
34934
  this.#configOptions = configured;
34745
34935
  }
@@ -34804,7 +34994,7 @@ var AcpProcessSession = class _AcpProcessSession {
34804
34994
  };
34805
34995
  nativeHistoryTurn = () => {
34806
34996
  const prompt = this.#nativePrompt;
34807
- const nativeTurnId = this.#endpoint.inProcessAgent?.nativeTurnId?.() ?? null;
34997
+ const nativeTurnId = this.#connection.inProcessAgent?.nativeTurnId?.() ?? null;
34808
34998
  return prompt === null || nativeTurnId === null || nativeTurnId === prompt.previousTurnId ? null : { commandId: prompt.commandId, nativeTurnId };
34809
34999
  };
34810
35000
  prompt = async (options) => {
@@ -34819,7 +35009,7 @@ var AcpProcessSession = class _AcpProcessSession {
34819
35009
  new AcpStoredSession(
34820
35010
  this.#mobiusSessionId,
34821
35011
  this.#agentId,
34822
- this.#nativeSessionId,
35012
+ this.#updates.sessionId(),
34823
35013
  this.#cwd,
34824
35014
  this.#additionalDirectories,
34825
35015
  true,
@@ -34837,19 +35027,19 @@ var AcpProcessSession = class _AcpProcessSession {
34837
35027
  this.#turn = running;
34838
35028
  this.#nativePrompt = {
34839
35029
  commandId: options.commandId,
34840
- previousTurnId: this.#endpoint.inProcessAgent?.nativeTurnId?.() ?? null
35030
+ previousTurnId: this.#connection.inProcessAgent?.nativeTurnId?.() ?? null
34841
35031
  };
34842
35032
  try {
34843
35033
  const response = await this.race(
34844
- this.#endpoint.connection.agent.request(
35034
+ this.#connection.connection.agent.request(
34845
35035
  methods8.agent.session.prompt,
34846
- { prompt, sessionId: this.#nativeSessionId },
35036
+ { prompt, sessionId: this.#updates.sessionId() },
34847
35037
  { cancellationSignal: options.signal }
34848
35038
  ),
34849
35039
  "ACP agent exited during a prompt",
34850
35040
  options.signal
34851
35041
  );
34852
- await this.#updateTail;
35042
+ await this.#updates.drained();
34853
35043
  await this.flushAgentText();
34854
35044
  await running.activities.finish();
34855
35045
  let result;
@@ -34899,10 +35089,10 @@ var AcpProcessSession = class _AcpProcessSession {
34899
35089
  }
34900
35090
  const prompt = this.buildPrompt(options);
34901
35091
  const response = await this.race(
34902
- this.#endpoint.connection.agent.request("_session/steering", {
35092
+ this.#connection.connection.agent.request("_session/steering", {
34903
35093
  _meta: { steering: { idleBehavior: "promptRequired" } },
34904
35094
  prompt,
34905
- sessionId: this.#nativeSessionId
35095
+ sessionId: this.#updates.sessionId()
34906
35096
  }),
34907
35097
  "ACP agent exited during steering",
34908
35098
  options.signal
@@ -34935,12 +35125,12 @@ var AcpProcessSession = class _AcpProcessSession {
34935
35125
  );
34936
35126
  };
34937
35127
  cancel = async () => {
34938
- const capturedProcesses = await this.#endpoint.captureProcessTree();
35128
+ const capturedProcesses = await this.#connection.captureProcessTree();
34939
35129
  try {
34940
35130
  await this.#interactions.cancelPendingInteractions();
34941
35131
  if (this.#turn.running) {
34942
- await this.#endpoint.connection.agent.notify(methods8.agent.session.cancel, {
34943
- sessionId: this.#nativeSessionId
35132
+ await this.#connection.connection.agent.notify(methods8.agent.session.cancel, {
35133
+ sessionId: this.#updates.sessionId()
34944
35134
  });
34945
35135
  }
34946
35136
  } finally {
@@ -34952,45 +35142,9 @@ var AcpProcessSession = class _AcpProcessSession {
34952
35142
  onPermission = (request, signal) => this.#interactions.onPermission(request, signal);
34953
35143
  onElicitation = (request, signal) => this.#interactions.onElicitation(request, signal);
34954
35144
  onElicitationComplete = (notification) => this.#interactions.onElicitationComplete(notification);
34955
- onUpdate = (notification) => {
34956
- if (this.#nativeSessionId.length === 0) {
34957
- const notificationBytes = Buffer.byteLength(JSON.stringify(notification));
34958
- if (this.#preSessionUpdates.length >= MAX_PRE_SESSION_UPDATES || this.#preSessionUpdateBytes + notificationBytes > MAX_PRE_SESSION_UPDATE_BYTES) {
34959
- return Promise.reject(
34960
- new AcpExecutionError(
34961
- "ACP agent sent too many updates before creating its session",
34962
- {},
34963
- "agent_update_limit"
34964
- )
34965
- );
34966
- }
34967
- this.#preSessionUpdates.push(notification);
34968
- this.#preSessionUpdateBytes += notificationBytes;
34969
- return Promise.resolve();
34970
- }
34971
- return this.enqueueUpdate(notification);
34972
- };
34973
- enqueueUpdate = (notification) => {
34974
- this.#updateTail = this.#updateTail.then(async () => await this.processUpdate(notification));
34975
- return this.#updateTail;
34976
- };
34977
- selectNativeSession = (sessionId) => {
34978
- const selected = nativeSessionIdSchema.parse(sessionId);
34979
- if (this.#nativeSessionId.length > 0 && this.#nativeSessionId !== selected) {
34980
- throw new AcpExecutionError(
34981
- "ACP agent attempted to replace the selected session",
34982
- {},
34983
- "invalid_agent_session"
34984
- );
34985
- }
34986
- this.#nativeSessionId = selected;
34987
- const pending = this.#preSessionUpdates.splice(0);
34988
- this.#preSessionUpdateBytes = 0;
34989
- for (const notification of pending) {
34990
- void this.enqueueUpdate(notification);
34991
- }
34992
- };
34993
- processUpdate = async (notification) => {
35145
+ onUpdate = (notification) => this.#updates.receive(notification);
35146
+ selectNativeSession = (sessionId) => this.#updates.select(sessionId);
35147
+ #processUpdate = async (notification) => {
34994
35148
  this.assertNativeSession(notification.sessionId);
34995
35149
  const update = notification.update;
34996
35150
  if (this.#replay.kind === "capture") {
@@ -35060,7 +35214,7 @@ var AcpProcessSession = class _AcpProcessSession {
35060
35214
  })).filter((command) => command.name.length > 0);
35061
35215
  this.#commands = commands;
35062
35216
  await this.#getObserver().onCommands({
35063
- commands,
35217
+ commands: this.#commands,
35064
35218
  kind: SESSION_COMMANDS_UPDATED_KIND,
35065
35219
  sessionId: this.#mobiusSessionId
35066
35220
  });
@@ -35090,12 +35244,12 @@ var AcpProcessSession = class _AcpProcessSession {
35090
35244
  if (Object.hasOwn(update, "updatedAt")) {
35091
35245
  this.#sessionUpdatedAt = truncate3(update.updatedAt ?? "", 128);
35092
35246
  }
35093
- if (this.#nativeSessionId.length > 0) {
35247
+ if (this.#updates.sessionId().length > 0) {
35094
35248
  this.#store.write(
35095
35249
  new AcpStoredSession(
35096
35250
  this.#mobiusSessionId,
35097
35251
  this.#agentId,
35098
- this.#nativeSessionId,
35252
+ this.#updates.sessionId(),
35099
35253
  this.#cwd,
35100
35254
  this.#additionalDirectories,
35101
35255
  this.#prompted,
@@ -35127,11 +35281,11 @@ var AcpProcessSession = class _AcpProcessSession {
35127
35281
  close = async () => {
35128
35282
  try {
35129
35283
  await this.#interactions.cancelPendingInteractions();
35130
- if (this.#capabilities.closeSession && this.#nativeSessionId.length > 0) {
35284
+ if (this.#capabilities.closeSession && this.#updates.sessionId().length > 0) {
35131
35285
  try {
35132
- await this.#endpoint.connection.agent.request(
35286
+ await this.#connection.connection.agent.request(
35133
35287
  methods8.agent.session.close,
35134
- { sessionId: this.#nativeSessionId },
35288
+ { sessionId: this.#updates.sessionId() },
35135
35289
  {
35136
35290
  cancellationSignal: AbortSignal.timeout(PROCESS_STOP_TIMEOUT_MILLISECONDS)
35137
35291
  }
@@ -35143,10 +35297,10 @@ var AcpProcessSession = class _AcpProcessSession {
35143
35297
  await this.closeProcess();
35144
35298
  }
35145
35299
  };
35146
- closeProcess = (capturedProcesses = []) => this.#endpoint.closeProcess(capturedProcesses);
35147
- race = (operation, exitMessage, signal) => this.#endpoint.race(operation, exitMessage, signal);
35300
+ closeProcess = (capturedProcesses = []) => this.#connection.closeProcess(capturedProcesses);
35301
+ race = (operation, exitMessage, signal) => this.#connection.race(operation, exitMessage, signal);
35148
35302
  assertNativeSession = (sessionId) => {
35149
- if (sessionId !== this.#nativeSessionId) {
35303
+ if (sessionId !== this.#updates.sessionId()) {
35150
35304
  throw new AcpExecutionError("ACP agent referenced an unknown session", {}, "invalid_agent_session");
35151
35305
  }
35152
35306
  };
@@ -35160,8 +35314,8 @@ var AcpProcessSession = class _AcpProcessSession {
35160
35314
  };
35161
35315
  };
35162
35316
 
35163
- // src/acp/retained-sessions.ts
35164
- var RetainedSessions = class {
35317
+ // src/acp/retained-agent-processes.ts
35318
+ var RetainedAgentProcesses = class {
35165
35319
  #entries = /* @__PURE__ */ new Map();
35166
35320
  #events;
35167
35321
  constructor(events) {
@@ -35264,18 +35418,21 @@ var RetainedSessions = class {
35264
35418
  };
35265
35419
  };
35266
35420
 
35267
- // src/acp/native-session-browsers.ts
35268
- var NativeSessionBrowsers = class {
35269
- #sessions;
35421
+ // src/acp/agent-query-processes.ts
35422
+ var AgentQueryProcesses = class {
35423
+ #processesByQuery;
35270
35424
  #processes;
35271
35425
  #observer = new NullAcpSessionObserver();
35272
35426
  #store = new MemoryAcpSessionStore();
35273
35427
  constructor(processes) {
35274
35428
  this.#processes = processes;
35275
- this.#sessions = new RetainedSessions({ touch: processes.touch, changed: processes.notifyChanged });
35429
+ this.#processesByQuery = new RetainedAgentProcesses({
35430
+ touch: processes.touch,
35431
+ changed: processes.notifyChanged
35432
+ });
35276
35433
  }
35277
35434
  retire = async (sessionId, runtime) => {
35278
- const retained = this.#sessions.detach(sessionId, runtime);
35435
+ const retained = this.#processesByQuery.detach(sessionId, runtime);
35279
35436
  if (retained) {
35280
35437
  this.#store.remove(sessionId);
35281
35438
  }
@@ -35284,40 +35441,40 @@ var NativeSessionBrowsers = class {
35284
35441
  async #startRetained(options) {
35285
35442
  const runtime = await this.#processes.startRetained(
35286
35443
  options.signal,
35287
- () => AcpProcessSession.startNativeSessionBrowser(options, () => this.#observer, this.#store),
35444
+ () => AgentSession.startNativeSessionBrowser(options, () => this.#observer, this.#store),
35288
35445
  {
35289
- isBusy: () => this.#sessions.isBusy(options.sessionId),
35446
+ isBusy: () => this.#processesByQuery.isBusy(options.sessionId),
35290
35447
  retire: (runtime2) => this.retire(options.sessionId, runtime2)
35291
35448
  }
35292
35449
  );
35293
- this.#sessions.retain(options.sessionId, runtime);
35450
+ this.#processesByQuery.retain(options.sessionId, runtime);
35294
35451
  return runtime;
35295
35452
  }
35296
35453
  async #startPreparation(options) {
35297
- return await this.#sessions.prepare(options.sessionId, async () => {
35454
+ return await this.#processesByQuery.prepare(options.sessionId, async () => {
35298
35455
  return await this.#startRetained(options);
35299
35456
  });
35300
35457
  }
35301
35458
  async #replacePreparation(existing, options) {
35302
- return await this.#sessions.prepare(options.sessionId, async () => {
35459
+ return await this.#processesByQuery.prepare(options.sessionId, async () => {
35303
35460
  await this.retire(options.sessionId, existing);
35304
35461
  return await this.#startRetained(options);
35305
35462
  });
35306
35463
  }
35307
35464
  prepare = async (options) => {
35308
- const pending = this.#sessions.pending(options.sessionId);
35465
+ const pending = this.#processesByQuery.pending(options.sessionId);
35309
35466
  if (pending !== void 0) {
35310
35467
  const runtime2 = await pending;
35311
35468
  if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35312
- this.#sessions.touch(options.sessionId, runtime2);
35469
+ this.#processesByQuery.touch(options.sessionId, runtime2);
35313
35470
  return runtime2.prepared();
35314
35471
  }
35315
35472
  return await this.prepare(options);
35316
35473
  }
35317
- const existing = this.#sessions.get(options.sessionId);
35474
+ const existing = this.#processesByQuery.get(options.sessionId);
35318
35475
  if (existing !== void 0) {
35319
35476
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35320
- this.#sessions.touch(options.sessionId, existing);
35477
+ this.#processesByQuery.touch(options.sessionId, existing);
35321
35478
  return existing.prepared();
35322
35479
  }
35323
35480
  if (!existing.canRebind()) {
@@ -35334,7 +35491,7 @@ var NativeSessionBrowsers = class {
35334
35491
  return runtime.prepared();
35335
35492
  };
35336
35493
  async #ensure(options) {
35337
- const existing = this.#sessions.get(options.sessionId);
35494
+ const existing = this.#processesByQuery.get(options.sessionId);
35338
35495
  if (existing !== void 0) {
35339
35496
  if (!existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35340
35497
  throw new AcpExecutionError(
@@ -35343,21 +35500,21 @@ var NativeSessionBrowsers = class {
35343
35500
  "session_identity_mismatch"
35344
35501
  );
35345
35502
  }
35346
- this.#sessions.touch(options.sessionId, existing);
35503
+ this.#processesByQuery.touch(options.sessionId, existing);
35347
35504
  return existing;
35348
35505
  }
35349
35506
  await this.prepare(options);
35350
- const started = this.#sessions.get(options.sessionId);
35507
+ const started = this.#processesByQuery.get(options.sessionId);
35351
35508
  if (started === void 0) {
35352
35509
  throw new AcpExecutionError("ACP native session browser did not start");
35353
35510
  }
35354
35511
  return started;
35355
35512
  }
35356
- use = async (options, operation) => await this.#sessions.use(options.sessionId, async () => await operation(await this.#ensure(options)));
35513
+ use = async (options, operation) => await this.#processesByQuery.use(options.sessionId, async () => await operation(await this.#ensure(options)));
35357
35514
  preview = async (options, nativeSessionId) => {
35358
35515
  return await this.#processes.runTransient(
35359
35516
  options.signal,
35360
- async () => await AcpProcessSession.startNativeSessionBrowser(
35517
+ async () => await AgentSession.startNativeSessionBrowser(
35361
35518
  options,
35362
35519
  () => this.#observer,
35363
35520
  new MemoryAcpSessionStore()
@@ -35370,88 +35527,9 @@ var NativeSessionBrowsers = class {
35370
35527
  );
35371
35528
  };
35372
35529
  close = async () => {
35373
- await Promise.all(this.#sessions.entries().map(async ([id, runtime]) => await this.retire(id, runtime)));
35374
- };
35375
- };
35376
-
35377
- // src/acp/session-executions.ts
35378
- var unreachable = (state) => {
35379
- throw new AcpExecutionError("Unexpected execution state", { cause: state });
35380
- };
35381
- var SessionExecutions = class {
35382
- #entries = /* @__PURE__ */ new Map();
35383
- command = (id) => {
35384
- const state = this.#entries.get(id);
35385
- switch (state?.kind) {
35386
- case "running":
35387
- case "cancelling":
35388
- return state.commandId;
35389
- case "cancelled-before-start":
35390
- case void 0:
35391
- return void 0;
35392
- default:
35393
- return unreachable(state);
35394
- }
35395
- };
35396
- cancellation = (id) => {
35397
- const state = this.#entries.get(id);
35398
- switch (state?.kind) {
35399
- case "cancelling":
35400
- case "cancelled-before-start":
35401
- return state.completion;
35402
- case "running":
35403
- case void 0:
35404
- return void 0;
35405
- default:
35406
- return unreachable(state);
35407
- }
35408
- };
35409
- isBusy = (id) => this.#entries.has(id);
35410
- begin = (id, commandId) => {
35411
- const state = this.#entries.get(id);
35412
- switch (state?.kind) {
35413
- case "running":
35414
- case "cancelling":
35415
- throw new AcpExecutionError(
35416
- "Another prompt is already running in this conversation",
35417
- {},
35418
- "session_busy"
35419
- );
35420
- case "cancelled-before-start":
35421
- case void 0:
35422
- break;
35423
- default:
35424
- unreachable(state);
35425
- }
35426
- this.#entries.set(
35427
- id,
35428
- state?.kind === "cancelled-before-start" ? { kind: "cancelling", commandId, completion: state.completion } : { kind: "running", commandId }
35429
- );
35430
- };
35431
- cancel = (id, stop) => {
35432
- const state = this.#entries.get(id);
35433
- switch (state?.kind) {
35434
- case "cancelling":
35435
- case "cancelled-before-start":
35436
- return state.completion;
35437
- case "running":
35438
- case void 0:
35439
- break;
35440
- default:
35441
- return unreachable(state);
35442
- }
35443
- const completion = Promise.withResolvers();
35444
- this.#entries.set(
35445
- id,
35446
- state?.kind === "running" ? { kind: "cancelling", commandId: state.commandId, completion: completion.promise } : { kind: "cancelled-before-start", completion: completion.promise }
35530
+ await Promise.all(
35531
+ this.#processesByQuery.entries().map(async ([id, runtime]) => await this.retire(id, runtime))
35447
35532
  );
35448
- void (async () => await stop())().then(completion.resolve, completion.reject);
35449
- return completion.promise;
35450
- };
35451
- finish = (id, commandId) => {
35452
- if (this.command(id) === commandId) {
35453
- this.#entries.delete(id);
35454
- }
35455
35533
  };
35456
35534
  };
35457
35535
 
@@ -35556,9 +35634,9 @@ async function waitForAcpProcessCapacity(completion, signal) {
35556
35634
  }
35557
35635
  }
35558
35636
 
35559
- // src/acp/process-pool.ts
35637
+ // src/acp/agent-process-pool.ts
35560
35638
  var MAX_ACP_PROCESSES = 10;
35561
- var AcpProcessPool = class {
35639
+ var AgentProcessPool = class {
35562
35640
  #slots = /* @__PURE__ */ new Map();
35563
35641
  #lock = new AcpProcessCapacityLock();
35564
35642
  #changed = Promise.withResolvers();
@@ -35662,13 +35740,16 @@ var AcpProcessPool = class {
35662
35740
  };
35663
35741
  };
35664
35742
 
35665
- // src/acp/session-manager.ts
35743
+ // src/acp/agent-runtime-manager.ts
35666
35744
  var SESSION_CONTROL_TIMEOUT_MILLISECONDS = 3e4;
35667
- var AcpSessionManager = class {
35668
- #processes = new AcpProcessPool();
35669
- #sessions = new RetainedSessions({ touch: this.#processes.touch, changed: this.#processes.notifyChanged });
35670
- #browsers = new NativeSessionBrowsers(this.#processes);
35671
- #executions = new SessionExecutions();
35745
+ var AgentRuntimeManager = class {
35746
+ #processes = new AgentProcessPool();
35747
+ #executionProcesses = new RetainedAgentProcesses({
35748
+ touch: this.#processes.touch,
35749
+ changed: this.#processes.notifyChanged
35750
+ });
35751
+ #queryProcesses = new AgentQueryProcesses(this.#processes);
35752
+ #executions = new ActiveExecutions();
35672
35753
  #agentSettingsObserver = new NullAcpSessionObserver();
35673
35754
  #nativeOperations = /* @__PURE__ */ new Set();
35674
35755
  #store;
@@ -35690,12 +35771,12 @@ var AcpSessionManager = class {
35690
35771
  }
35691
35772
  #retention(sessionId) {
35692
35773
  return {
35693
- isBusy: () => this.#executions.isBusy(sessionId) || this.#sessions.isBusy(sessionId) || this.#isNativeSessionOperationActive(sessionId),
35774
+ isBusy: () => this.#executions.isBusy(sessionId) || this.#executionProcesses.isBusy(sessionId) || this.#isNativeSessionOperationActive(sessionId),
35694
35775
  retire: (runtime) => this.#retireSessionProcess(sessionId, runtime, () => runtime.close())
35695
35776
  };
35696
35777
  }
35697
35778
  async #retireSessionProcess(sessionId, runtime, close) {
35698
- const retained = this.#sessions.detach(sessionId, runtime);
35779
+ const retained = this.#executionProcesses.detach(sessionId, runtime);
35699
35780
  try {
35700
35781
  await this.#processes.retire(runtime, close);
35701
35782
  } finally {
@@ -35709,14 +35790,14 @@ var AcpSessionManager = class {
35709
35790
  }
35710
35791
  async #startRetainedSessionProcess(options, start) {
35711
35792
  const runtime = await this.#processes.startRetained(options.signal, start, this.#retention(options.sessionId));
35712
- this.#sessions.retain(options.sessionId, runtime);
35793
+ this.#executionProcesses.retain(options.sessionId, runtime);
35713
35794
  return runtime;
35714
35795
  }
35715
35796
  async #startPreparation(options, metrics = unmeasuredOperationMetrics) {
35716
- return await this.#sessions.prepare(options.sessionId, async () => {
35797
+ return await this.#executionProcesses.prepare(options.sessionId, async () => {
35717
35798
  return await this.#startRetainedSessionProcess(
35718
35799
  options,
35719
- async () => await AcpProcessSession.start(
35800
+ async () => await AgentSession.start(
35720
35801
  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,
35721
35802
  () => this.#observer,
35722
35803
  this.#store,
@@ -35726,7 +35807,7 @@ var AcpSessionManager = class {
35726
35807
  });
35727
35808
  }
35728
35809
  async #replacePreparation(existing, options, metrics) {
35729
- return await this.#sessions.prepare(options.sessionId, async () => {
35810
+ return await this.#executionProcesses.prepare(options.sessionId, async () => {
35730
35811
  await this.#retireSessionProcess(
35731
35812
  options.sessionId,
35732
35813
  existing,
@@ -35735,17 +35816,17 @@ var AcpSessionManager = class {
35735
35816
  this.#store.remove(options.sessionId);
35736
35817
  return await this.#startRetainedSessionProcess(
35737
35818
  options,
35738
- async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
35819
+ async () => await AgentSession.start(options, () => this.#observer, this.#store, metrics)
35739
35820
  );
35740
35821
  });
35741
35822
  }
35742
35823
  async #replaceExecutionPreparation(existing, options) {
35743
35824
  const desiredConfigOptions = existing.prepared().configOptions;
35744
- return await this.#sessions.prepare(options.sessionId, async () => {
35825
+ return await this.#executionProcesses.prepare(options.sessionId, async () => {
35745
35826
  await this.#retireSessionProcess(options.sessionId, existing, async () => await existing.close());
35746
35827
  const runtime = await this.#startRetainedSessionProcess(
35747
35828
  options,
35748
- async () => await AcpProcessSession.start(options, () => this.#observer, this.#store)
35829
+ async () => await AgentSession.start(options, () => this.#observer, this.#store)
35749
35830
  );
35750
35831
  try {
35751
35832
  for (const desired of desiredConfigOptions) {
@@ -35796,19 +35877,19 @@ var AcpSessionManager = class {
35796
35877
  if (stored instanceof FoundAcpStoredSession && this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`)) {
35797
35878
  throw new AcpExecutionError("The native session is being managed", {}, "session_busy");
35798
35879
  }
35799
- const pending = this.#sessions.pending(options.sessionId);
35880
+ const pending = this.#executionProcesses.pending(options.sessionId);
35800
35881
  if (pending !== void 0) {
35801
35882
  const runtime2 = await metrics.measure("session-preparation-wait", async () => await pending);
35802
35883
  if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35803
- this.#sessions.touch(options.sessionId, runtime2);
35884
+ this.#executionProcesses.touch(options.sessionId, runtime2);
35804
35885
  return runtime2.prepared();
35805
35886
  }
35806
35887
  return await this.prepareSession(options, metrics);
35807
35888
  }
35808
- const existing = this.#sessions.get(options.sessionId);
35889
+ const existing = this.#executionProcesses.get(options.sessionId);
35809
35890
  if (existing !== void 0) {
35810
35891
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35811
- this.#sessions.touch(options.sessionId, existing);
35892
+ this.#executionProcesses.touch(options.sessionId, existing);
35812
35893
  return existing.prepared();
35813
35894
  }
35814
35895
  if (!existing.canRebind()) {
@@ -35831,7 +35912,7 @@ var AcpSessionManager = class {
35831
35912
  */
35832
35913
  inspectAgentSettings = async (options) => await this.#processes.runTransient(
35833
35914
  options.signal,
35834
- async () => await AcpProcessSession.start(
35915
+ async () => await AgentSession.start(
35835
35916
  {
35836
35917
  ...options,
35837
35918
  sessionId: `agent-settings-${crypto.randomUUID()}`
@@ -35862,10 +35943,10 @@ var AcpSessionManager = class {
35862
35943
  * Use inspectAgentSettings for Agent-scoped settings discovery.
35863
35944
  */
35864
35945
  inspectSession = async (options, metrics = unmeasuredOperationMetrics) => {
35865
- if (this.#sessions.pending(options.sessionId) !== void 0 || this.#sessions.get(options.sessionId) !== void 0) {
35946
+ if (this.#executionProcesses.pending(options.sessionId) !== void 0 || this.#executionProcesses.get(options.sessionId) !== void 0) {
35866
35947
  throw new AcpExecutionError("The configuration inspection session is already in use", {}, "session_busy");
35867
35948
  }
35868
- return await this.#sessions.use(options.sessionId, async () => {
35949
+ return await this.#executionProcesses.use(options.sessionId, async () => {
35869
35950
  const runtime = await this.#startPreparation(options, metrics);
35870
35951
  try {
35871
35952
  return runtime.prepared();
@@ -35879,12 +35960,12 @@ var AcpSessionManager = class {
35879
35960
  });
35880
35961
  };
35881
35962
  prepareExecutionSession = async (options) => {
35882
- const pending = this.#sessions.pending(options.sessionId);
35963
+ const pending = this.#executionProcesses.pending(options.sessionId);
35883
35964
  if (pending !== void 0) {
35884
35965
  await pending;
35885
35966
  return await this.prepareExecutionSession(options);
35886
35967
  }
35887
- const existing = this.#sessions.get(options.sessionId);
35968
+ const existing = this.#executionProcesses.get(options.sessionId);
35888
35969
  if (existing === void 0) {
35889
35970
  return (await this.#startPreparation(options)).prepared();
35890
35971
  }
@@ -35896,7 +35977,7 @@ var AcpSessionManager = class {
35896
35977
  );
35897
35978
  }
35898
35979
  if (existing.usesEnvironment(options.agent.environment)) {
35899
- this.#sessions.touch(options.sessionId, existing);
35980
+ this.#executionProcesses.touch(options.sessionId, existing);
35900
35981
  return existing.prepared();
35901
35982
  }
35902
35983
  if (existing.hasRunningTurn()) {
@@ -35908,21 +35989,21 @@ var AcpSessionManager = class {
35908
35989
  }
35909
35990
  return (await this.#replaceExecutionPreparation(existing, options)).prepared();
35910
35991
  };
35911
- prepareNativeSessionBrowser = (options) => this.#browsers.prepare(options);
35992
+ prepareNativeSessionBrowser = (options) => this.#queryProcesses.prepare(options);
35912
35993
  configureSession = async (options) => {
35913
- return await this.#sessions.use(options.sessionId, async () => {
35994
+ return await this.#executionProcesses.use(options.sessionId, async () => {
35914
35995
  const runtime = await this.ensureSession(options);
35915
35996
  return await runtime.configure(options);
35916
35997
  });
35917
35998
  };
35918
35999
  cancelPrompt = async (sessionId) => {
35919
36000
  await this.#executions.cancel(sessionId, async () => {
35920
- const runtime = this.#sessions.get(sessionId);
36001
+ const runtime = this.#executionProcesses.get(sessionId);
35921
36002
  if (runtime !== void 0) {
35922
36003
  try {
35923
36004
  await runtime.cancel();
35924
36005
  } finally {
35925
- if (this.#sessions.detach(sessionId, runtime)) {
36006
+ if (this.#executionProcesses.detach(sessionId, runtime)) {
35926
36007
  this.#processes.releaseClosed(runtime);
35927
36008
  }
35928
36009
  }
@@ -35933,14 +36014,14 @@ var AcpSessionManager = class {
35933
36014
  if (this.#executions.command(options.sessionId) !== options.targetCommandId) {
35934
36015
  throw new AcpExecutionError("The target turn is no longer active", {}, "steering_target_unavailable");
35935
36016
  }
35936
- const pending = this.#sessions.pending(options.sessionId);
36017
+ const pending = this.#executionProcesses.pending(options.sessionId);
35937
36018
  if (pending !== void 0) {
35938
36019
  await pending;
35939
36020
  }
35940
36021
  if (this.#executions.command(options.sessionId) !== options.targetCommandId) {
35941
36022
  throw new AcpExecutionError("The target turn is no longer active", {}, "steering_target_unavailable");
35942
36023
  }
35943
- const runtime = this.#sessions.get(options.sessionId);
36024
+ const runtime = this.#executionProcesses.get(options.sessionId);
35944
36025
  if (runtime === void 0 || !runtime.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35945
36026
  throw new AcpExecutionError(
35946
36027
  "The target turn execution context is unavailable",
@@ -35998,7 +36079,7 @@ var AcpSessionManager = class {
35998
36079
  throw error62;
35999
36080
  }
36000
36081
  } catch (error62) {
36001
- const failedRuntime = this.#sessions.get(options.sessionId);
36082
+ const failedRuntime = this.#executionProcesses.get(options.sessionId);
36002
36083
  if (failedRuntime !== void 0) {
36003
36084
  await this.#retireSessionProcess(
36004
36085
  options.sessionId,
@@ -36020,32 +36101,32 @@ var AcpSessionManager = class {
36020
36101
  await this.#executions.cancellation(options.sessionId);
36021
36102
  } finally {
36022
36103
  this.#executions.finish(options.sessionId, options.commandId);
36023
- this.#sessions.touch(options.sessionId);
36104
+ this.#executionProcesses.touch(options.sessionId);
36024
36105
  this.#processes.notifyChanged();
36025
36106
  }
36026
36107
  }
36027
36108
  };
36028
36109
  respondPermission = async (options) => {
36029
- const runtime = this.#sessions.get(options.sessionId);
36110
+ const runtime = this.#executionProcesses.get(options.sessionId);
36030
36111
  if (runtime === void 0) {
36031
36112
  throw new AcpExecutionError("The permission request session is unavailable", {}, "session_not_found");
36032
36113
  }
36033
36114
  await runtime.respondPermission(options);
36034
36115
  };
36035
36116
  respondElicitation = async (options) => {
36036
- const runtime = this.#sessions.get(options.sessionId);
36117
+ const runtime = this.#executionProcesses.get(options.sessionId);
36037
36118
  if (runtime === void 0) {
36038
36119
  throw new AcpExecutionError("The elicitation request session is unavailable", {}, "session_not_found");
36039
36120
  }
36040
36121
  await runtime.respondElicitation(options);
36041
36122
  };
36042
36123
  close = async () => {
36043
- const sessions = [...this.#sessions.entries()];
36124
+ const sessions = [...this.#executionProcesses.entries()];
36044
36125
  await Promise.all([
36045
36126
  ...sessions.map(
36046
36127
  async ([sessionId, runtime]) => await this.#retireSessionProcess(sessionId, runtime, async () => await runtime.close())
36047
36128
  ),
36048
- this.#browsers.close()
36129
+ this.#queryProcesses.close()
36049
36130
  ]);
36050
36131
  };
36051
36132
  findSessions = (sessionIds) => sessionIds.flatMap((sessionId) => {
@@ -36053,17 +36134,17 @@ var AcpSessionManager = class {
36053
36134
  return stored instanceof FoundAcpStoredSession ? [stored.session] : [];
36054
36135
  });
36055
36136
  findLinkedSessions = (agentId, nativeSessionId) => this.#store.findNative(agentId, nativeSessionId);
36056
- hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
36137
+ hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#executionProcesses.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
36057
36138
  createNativeSession = async (options) => {
36058
36139
  const temporarySessionId = `new-${crypto.randomUUID()}`;
36059
36140
  const temporaryOptions = { ...options, sessionId: temporarySessionId };
36060
- return await this.#sessions.use(temporarySessionId, async () => {
36141
+ return await this.#executionProcesses.use(temporarySessionId, async () => {
36061
36142
  try {
36062
36143
  const runtime = await this.#startPreparation(temporaryOptions);
36063
36144
  let adopted = false;
36064
36145
  try {
36065
36146
  const nativeSessionId = runtime.nativeSessionId();
36066
- if (!isNativeChatSessionId(options.agent.id, nativeSessionId) || this.#sessions.get(nativeSessionId) !== void 0 || !(this.#store.read(nativeSessionId) instanceof MissingAcpStoredSession)) {
36147
+ if (!isNativeChatSessionId(options.agent.id, nativeSessionId) || this.#executionProcesses.get(nativeSessionId) !== void 0 || !(this.#store.read(nativeSessionId) instanceof MissingAcpStoredSession)) {
36067
36148
  throw new AcpExecutionError(
36068
36149
  "The Agent returned an invalid new Session ID",
36069
36150
  {},
@@ -36071,8 +36152,8 @@ var AcpSessionManager = class {
36071
36152
  );
36072
36153
  }
36073
36154
  runtime.adoptNativeSessionId(nativeSessionId);
36074
- this.#sessions.detach(temporarySessionId, runtime);
36075
- this.#sessions.retain(nativeSessionId, runtime);
36155
+ this.#executionProcesses.detach(temporarySessionId, runtime);
36156
+ this.#executionProcesses.retain(nativeSessionId, runtime);
36076
36157
  this.#processes.retain(runtime, this.#retention(nativeSessionId));
36077
36158
  adopted = true;
36078
36159
  return nativeSessionId;
@@ -36091,7 +36172,7 @@ var AcpSessionManager = class {
36091
36172
  });
36092
36173
  };
36093
36174
  ensureSession = async (options) => {
36094
- const existing = this.#sessions.get(options.sessionId);
36175
+ const existing = this.#executionProcesses.get(options.sessionId);
36095
36176
  if (existing !== void 0) {
36096
36177
  if (!existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
36097
36178
  throw new AcpExecutionError(
@@ -36100,18 +36181,18 @@ var AcpSessionManager = class {
36100
36181
  "session_identity_mismatch"
36101
36182
  );
36102
36183
  }
36103
- this.#sessions.touch(options.sessionId, existing);
36184
+ this.#executionProcesses.touch(options.sessionId, existing);
36104
36185
  return existing;
36105
36186
  }
36106
36187
  await this.prepareSession(options);
36107
- const started = this.#sessions.get(options.sessionId);
36188
+ const started = this.#executionProcesses.get(options.sessionId);
36108
36189
  if (started === void 0) {
36109
36190
  throw new AcpExecutionError("ACP session did not start");
36110
36191
  }
36111
36192
  return started;
36112
36193
  };
36113
36194
  listNativeSessions = async (options, cursor) => {
36114
- return await this.#browsers.use(
36195
+ return await this.#queryProcesses.use(
36115
36196
  options,
36116
36197
  async (runtime) => await runtime.listNativeSessions(cursor, options.signal)
36117
36198
  );
@@ -36120,7 +36201,7 @@ var AcpSessionManager = class {
36120
36201
  const key = `${options.agent.id}:${nativeSessionId}`;
36121
36202
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
36122
36203
  if (this.#nativeOperations.has(key) || linked.some(
36123
- (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#sessions.pending(entry.sessionId) !== void 0
36204
+ (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#executionProcesses.pending(entry.sessionId) !== void 0
36124
36205
  )) {
36125
36206
  throw new AcpExecutionError(
36126
36207
  "Wait for the native session's running operation to finish",
@@ -36130,13 +36211,13 @@ var AcpSessionManager = class {
36130
36211
  }
36131
36212
  this.#nativeOperations.add(key);
36132
36213
  try {
36133
- return await this.#browsers.preview(options, nativeSessionId);
36214
+ return await this.#queryProcesses.preview(options, nativeSessionId);
36134
36215
  } finally {
36135
36216
  this.#nativeOperations.delete(key);
36136
36217
  }
36137
36218
  };
36138
36219
  loadSessionHistory = async (options) => {
36139
- return await this.#sessions.use(options.sessionId, async () => {
36220
+ return await this.#executionProcesses.use(options.sessionId, async () => {
36140
36221
  const runtime = await this.ensureSession(options);
36141
36222
  const stored = this.#store.read(options.sessionId);
36142
36223
  if (stored instanceof FoundAcpStoredSession && this.#nativeHistoryReader !== null) {
@@ -36159,7 +36240,7 @@ var AcpSessionManager = class {
36159
36240
  }
36160
36241
  const linked = this.#store.findNative(options.agent.id, origin.nativeSessionId);
36161
36242
  if (linked.some(
36162
- (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#sessions.pending(entry.sessionId) !== void 0
36243
+ (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#executionProcesses.pending(entry.sessionId) !== void 0
36163
36244
  )) {
36164
36245
  throw new AcpExecutionError(
36165
36246
  "Wait for the native session's running operation to finish",
@@ -36169,7 +36250,7 @@ var AcpSessionManager = class {
36169
36250
  }
36170
36251
  const existing = linked[0];
36171
36252
  if (origin.kind === "import" && existing !== void 0) {
36172
- return await this.#sessions.use(existing.sessionId, async () => {
36253
+ return await this.#executionProcesses.use(existing.sessionId, async () => {
36173
36254
  const runtime = await this.ensureSession({
36174
36255
  ...options,
36175
36256
  sessionId: existing.sessionId
@@ -36193,10 +36274,10 @@ var AcpSessionManager = class {
36193
36274
  }
36194
36275
  });
36195
36276
  }
36196
- 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) {
36277
+ 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) {
36197
36278
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
36198
36279
  }
36199
- return await this.#sessions.use(options.sessionId, async () => {
36280
+ return await this.#executionProcesses.use(options.sessionId, async () => {
36200
36281
  this.#nativeOperations.add(key);
36201
36282
  try {
36202
36283
  const runtime = await this.#startPreparation({ ...options, origin });
@@ -36213,7 +36294,7 @@ var AcpSessionManager = class {
36213
36294
  }
36214
36295
  } catch (error62) {
36215
36296
  this.#store.remove(options.sessionId);
36216
- const runtime = this.#sessions.get(options.sessionId);
36297
+ const runtime = this.#executionProcesses.get(options.sessionId);
36217
36298
  if (runtime !== void 0) {
36218
36299
  await this.#retireSessionProcess(
36219
36300
  options.sessionId,
@@ -36228,11 +36309,11 @@ var AcpSessionManager = class {
36228
36309
  });
36229
36310
  };
36230
36311
  deleteNativeSession = async (options, nativeSessionId) => {
36231
- return await this.#browsers.use(options, async (runtime) => {
36312
+ return await this.#queryProcesses.use(options, async (runtime) => {
36232
36313
  const key = `${options.agent.id}:${nativeSessionId}`;
36233
36314
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
36234
36315
  if (this.#nativeOperations.has(key) || linked.some(
36235
- (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#sessions.pending(entry.sessionId) !== void 0
36316
+ (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#executionProcesses.pending(entry.sessionId) !== void 0
36236
36317
  )) {
36237
36318
  throw new AcpExecutionError(
36238
36319
  "Wait for the native session's running operation to finish",
@@ -36243,7 +36324,7 @@ var AcpSessionManager = class {
36243
36324
  this.#nativeOperations.add(key);
36244
36325
  try {
36245
36326
  for (const entry of linked) {
36246
- const active = this.#sessions.get(entry.sessionId);
36327
+ const active = this.#executionProcesses.get(entry.sessionId);
36247
36328
  if (active !== void 0 && active !== runtime) {
36248
36329
  await this.#retireSessionProcess(entry.sessionId, active, async () => await active.close());
36249
36330
  }
@@ -36252,7 +36333,7 @@ var AcpSessionManager = class {
36252
36333
  await runtime.deleteNativeSession(nativeSessionId, options.signal);
36253
36334
  const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
36254
36335
  if (runtime.nativeSessionId() === nativeSessionId) {
36255
- await this.#browsers.retire(options.sessionId, runtime);
36336
+ await this.#queryProcesses.retire(options.sessionId, runtime);
36256
36337
  }
36257
36338
  return deleted;
36258
36339
  } finally {
@@ -41673,7 +41754,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
41673
41754
  activeTurns.recordEvent(event);
41674
41755
  publisher.publish(sessionId, event);
41675
41756
  };
41676
- const sessions = new AcpSessionManager(
41757
+ const agentRuntime = new AgentRuntimeManager(
41677
41758
  new DaemonAcpObserver(recordSessionEvent),
41678
41759
  sessionStore,
41679
41760
  {
@@ -41695,20 +41776,28 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
41695
41776
  config2.relayUrl,
41696
41777
  new DaemonDiagnosticLog(stateDirectory)
41697
41778
  );
41698
- const nativeSessions = new NativeSessionService(config2, directories, sessions, audit, async (request, options2) => {
41699
- return await activeTurns.executionSnapshot(async (command) => {
41700
- if (command.sessionId !== request.targetSessionId || command.agentId !== request.agentId) {
41701
- return false;
41702
- }
41703
- const cwd = await directories.resolve(command.bindingId, command.directoryId, options2.signal);
41704
- const additionalDirectories = await directories.resolveMany(
41705
- command.bindingId,
41706
- command.additionalDirectoryIds,
41707
- options2.signal
41708
- );
41709
- return cwd === options2.cwd && additionalDirectories.length === options2.additionalDirectories.length && additionalDirectories.every((directory, index) => directory === options2.additionalDirectories[index]);
41710
- });
41711
- });
41779
+ const nativeSessions = new NativeSessionService(
41780
+ config2,
41781
+ directories,
41782
+ agentRuntime,
41783
+ audit,
41784
+ async (request, options2) => {
41785
+ return await activeTurns.executionSnapshot(async (command) => {
41786
+ if (command.sessionId !== request.targetSessionId || command.agentId !== request.agentId) {
41787
+ return false;
41788
+ }
41789
+ const cwd = await directories.resolve(command.bindingId, command.directoryId, options2.signal);
41790
+ const additionalDirectories = await directories.resolveMany(
41791
+ command.bindingId,
41792
+ command.additionalDirectoryIds,
41793
+ options2.signal
41794
+ );
41795
+ return cwd === options2.cwd && additionalDirectories.length === options2.additionalDirectories.length && additionalDirectories.every(
41796
+ (directory, index) => directory === options2.additionalDirectories[index]
41797
+ );
41798
+ });
41799
+ }
41800
+ );
41712
41801
  const installations = new AgentInstallationManager(
41713
41802
  specifications,
41714
41803
  installationExecutor,
@@ -41784,7 +41873,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
41784
41873
  config: config2,
41785
41874
  directories,
41786
41875
  audit,
41787
- sessions,
41876
+ sessions: agentRuntime,
41788
41877
  installations,
41789
41878
  installationObserver,
41790
41879
  nativeSessions,
@@ -41827,7 +41916,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
41827
41916
  await installations.close();
41828
41917
  } finally {
41829
41918
  try {
41830
- await sessions.close();
41919
+ await agentRuntime.close();
41831
41920
  } finally {
41832
41921
  try {
41833
41922
  sessionStore.close();