@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/index.js CHANGED
@@ -22397,7 +22397,88 @@ var AcpConfigurationValueUnavailableError = class extends AcpExecutionError {
22397
22397
  }
22398
22398
  };
22399
22399
 
22400
- // src/acp/process-session.ts
22400
+ // src/acp/active-executions.ts
22401
+ var unreachable = (state) => {
22402
+ throw new AcpExecutionError("Unexpected execution state", { cause: state });
22403
+ };
22404
+ var ActiveExecutions = class {
22405
+ #entries = /* @__PURE__ */ new Map();
22406
+ command = (id) => {
22407
+ const state = this.#entries.get(id);
22408
+ switch (state?.kind) {
22409
+ case "running":
22410
+ case "cancelling":
22411
+ return state.commandId;
22412
+ case "cancelled-before-start":
22413
+ case void 0:
22414
+ return void 0;
22415
+ default:
22416
+ return unreachable(state);
22417
+ }
22418
+ };
22419
+ cancellation = (id) => {
22420
+ const state = this.#entries.get(id);
22421
+ switch (state?.kind) {
22422
+ case "cancelling":
22423
+ case "cancelled-before-start":
22424
+ return state.completion;
22425
+ case "running":
22426
+ case void 0:
22427
+ return void 0;
22428
+ default:
22429
+ return unreachable(state);
22430
+ }
22431
+ };
22432
+ isBusy = (id) => this.#entries.has(id);
22433
+ begin = (id, commandId) => {
22434
+ const state = this.#entries.get(id);
22435
+ switch (state?.kind) {
22436
+ case "running":
22437
+ case "cancelling":
22438
+ throw new AcpExecutionError(
22439
+ "Another prompt is already running in this conversation",
22440
+ {},
22441
+ "session_busy"
22442
+ );
22443
+ case "cancelled-before-start":
22444
+ case void 0:
22445
+ break;
22446
+ default:
22447
+ unreachable(state);
22448
+ }
22449
+ this.#entries.set(
22450
+ id,
22451
+ state?.kind === "cancelled-before-start" ? { kind: "cancelling", commandId, completion: state.completion } : { kind: "running", commandId }
22452
+ );
22453
+ };
22454
+ cancel = (id, stop) => {
22455
+ const state = this.#entries.get(id);
22456
+ switch (state?.kind) {
22457
+ case "cancelling":
22458
+ case "cancelled-before-start":
22459
+ return state.completion;
22460
+ case "running":
22461
+ case void 0:
22462
+ break;
22463
+ default:
22464
+ return unreachable(state);
22465
+ }
22466
+ const completion = Promise.withResolvers();
22467
+ this.#entries.set(
22468
+ id,
22469
+ state?.kind === "running" ? { kind: "cancelling", commandId: state.commandId, completion: completion.promise } : { kind: "cancelled-before-start", completion: completion.promise }
22470
+ );
22471
+ void (async () => await stop())().then(completion.resolve, completion.reject);
22472
+ return completion.promise;
22473
+ };
22474
+ finish = (id, commandId) => {
22475
+ if (this.command(id) === commandId) {
22476
+ this.#entries.delete(id);
22477
+ }
22478
+ };
22479
+ };
22480
+
22481
+ // src/acp/agent-session.ts
22401
22482
  import {
22402
22483
  methods as methods3,
22403
22484
  PROTOCOL_VERSION
@@ -22700,73 +22781,11 @@ async function replaceImageMarkers(text2, replace) {
22700
22781
  return `${rewritten}${text2.slice(cursor)}`;
22701
22782
  }
22702
22783
 
22703
- // src/acp/activity.ts
22784
+ // src/acp/activity-content.ts
22704
22785
  var TRUNCATION_MARKER = "\n\u2026 output truncated by Mobius";
22705
- var AcpActivityNarration = class {
22706
- activityId;
22707
- activityType;
22708
- sequence;
22709
- text;
22710
- constructor(activityId, activityType, sequence, text2) {
22711
- this.activityId = activityId;
22712
- this.activityType = activityType;
22713
- this.sequence = sequence;
22714
- this.text = text2;
22715
- }
22716
- };
22717
22786
  function isRecord3(value) {
22718
22787
  return typeof value === "object" && value !== null && !Array.isArray(value);
22719
22788
  }
22720
- var AcpActivity = class _AcpActivity {
22721
- activityId;
22722
- activityType;
22723
- input;
22724
- locations;
22725
- name;
22726
- output;
22727
- sequence;
22728
- status;
22729
- title;
22730
- toolKind;
22731
- content;
22732
- detail;
22733
- constructor(activityId, activityType, input2, locations, name, output2, sequence, status, title2, toolKind, content = [], detail = captureActivityDetail(content, input2, output2)) {
22734
- this.activityId = activityId;
22735
- this.activityType = activityType;
22736
- this.input = input2;
22737
- this.locations = locations;
22738
- this.name = name;
22739
- this.output = output2;
22740
- this.sequence = sequence;
22741
- this.status = status;
22742
- this.title = title2;
22743
- this.toolKind = toolKind;
22744
- this.content = content;
22745
- this.detail = detail;
22746
- }
22747
- complete = () => (this.activityType === "progress" || this.activityType === "reasoning") && (this.status === "pending" || this.status === "running") ? new _AcpActivity(
22748
- this.activityId,
22749
- this.activityType,
22750
- this.input,
22751
- this.locations,
22752
- this.name,
22753
- this.output,
22754
- this.sequence,
22755
- "completed",
22756
- this.title,
22757
- this.toolKind,
22758
- this.content,
22759
- this.detail
22760
- ) : this;
22761
- };
22762
- var ActivityIdentity = class {
22763
- id;
22764
- sequence;
22765
- constructor(id, sequence) {
22766
- this.id = id;
22767
- this.sequence = sequence;
22768
- }
22769
- };
22770
22789
  function truncate(value, maximumLength) {
22771
22790
  if (value.length <= maximumLength) {
22772
22791
  return value;
@@ -23043,441 +23062,174 @@ function contentPhase(content) {
23043
23062
  function isProgressMessage(content) {
23044
23063
  return contentPhase(content) === "commentary";
23045
23064
  }
23046
- var AcpActivityTracker = class {
23047
- #activities = /* @__PURE__ */ new Map();
23048
- #identities = /* @__PURE__ */ new Map();
23049
- #narrations = /* @__PURE__ */ new Map();
23050
- #onActivity;
23051
- #onNarration;
23052
- #prepareContent;
23053
- #activeNarrativeKey = "";
23054
- #nextSequence = 0;
23055
- constructor(onActivity, onNarration, prepareContent = (content) => Promise.resolve(content)) {
23056
- this.#onActivity = onActivity;
23057
- this.#onNarration = onNarration;
23058
- this.#prepareContent = prepareContent;
23059
- }
23060
- recordNarrative = async (activityType, messageId, text2) => {
23061
- const key = `${activityType}:${messageId}`;
23062
- if (this.#activeNarrativeKey !== key) {
23063
- await this.finishNarrative();
23065
+
23066
+ // src/acp/agent-connection.ts
23067
+ import { spawn as spawn2 } from "node:child_process";
23068
+ import { ndJsonStream, RequestError } from "@agentclientprotocol/sdk";
23069
+
23070
+ // src/acp/in-process/acp-endpoint.ts
23071
+ function acpEndpointTerminationError(termination) {
23072
+ switch (termination.kind) {
23073
+ case "failed":
23074
+ return termination.error;
23075
+ case "closed":
23076
+ return new AcpExecutionError("The ACP endpoint is closed", {}, "acp_endpoint_closed");
23077
+ default: {
23078
+ const unreachable2 = termination;
23079
+ return unreachable2;
23064
23080
  }
23065
- const identity2 = this.#identity(key);
23066
- const previous = this.#narrations.get(key);
23067
- const previousOutput = previous?.output ?? "";
23068
- const remaining = Math.max(0, AGENT_ACTIVITY_DETAIL_LIMIT - previousOutput.length);
23069
- this.#narrations.set(key, {
23070
- activityId: identity2.id,
23071
- activityType,
23072
- output: `${previousOutput}${text2.slice(0, remaining)}`,
23073
- originalBytes: (previous?.originalBytes ?? 0) + new TextEncoder().encode(text2).byteLength,
23074
- sequence: identity2.sequence,
23075
- truncated: (previous?.truncated ?? false) || text2.length > remaining
23076
- });
23077
- if (previous === void 0) {
23078
- await this.#record(key, this.#narrativeSnapshot(identity2, activityType, "", "running"));
23081
+ }
23082
+ }
23083
+
23084
+ // src/acp/value-utils.ts
23085
+ function truncate2(value, maximumLength) {
23086
+ return value.length <= maximumLength ? value : `${value.slice(0, Math.max(0, maximumLength - 1))}\u2026`;
23087
+ }
23088
+ function isRecord4(value) {
23089
+ return typeof value === "object" && value !== null && !Array.isArray(value);
23090
+ }
23091
+ function readString2(value, fallback = "") {
23092
+ return typeof value === "string" ? value : fallback;
23093
+ }
23094
+
23095
+ // src/acp/agent-connection.ts
23096
+ function readableWebStream(input2) {
23097
+ let streamOpen = true;
23098
+ return new ReadableStream({
23099
+ start(controller) {
23100
+ input2.on("data", (chunk) => {
23101
+ if (!streamOpen) {
23102
+ return;
23103
+ }
23104
+ if (chunk instanceof Uint8Array) {
23105
+ controller.enqueue(new Uint8Array(chunk));
23106
+ return;
23107
+ }
23108
+ streamOpen = false;
23109
+ controller.error(new Error("ACP process produced a non-binary chunk"));
23110
+ });
23111
+ input2.once("end", () => {
23112
+ if (!streamOpen) {
23113
+ return;
23114
+ }
23115
+ streamOpen = false;
23116
+ controller.close();
23117
+ });
23118
+ input2.once("error", (error62) => {
23119
+ if (!streamOpen) {
23120
+ return;
23121
+ }
23122
+ streamOpen = false;
23123
+ controller.error(error62);
23124
+ });
23125
+ },
23126
+ cancel() {
23127
+ streamOpen = false;
23079
23128
  }
23080
- this.#activeNarrativeKey = key;
23081
- if (text2.length > 0) {
23082
- await this.#onNarration(new AcpActivityNarration(identity2.id, activityType, identity2.sequence, text2));
23129
+ });
23130
+ }
23131
+ function createWritableAcpStream(output2) {
23132
+ let outputFailure;
23133
+ const pendingWriteFailures = /* @__PURE__ */ new Set();
23134
+ const fail = (error62) => {
23135
+ outputFailure = error62;
23136
+ for (const reject of pendingWriteFailures) {
23137
+ reject(error62);
23083
23138
  }
23139
+ pendingWriteFailures.clear();
23084
23140
  };
23085
- #narrativeSnapshot = (identity2, activityType, output2, status) => new AcpActivity(
23086
- identity2.id,
23087
- activityType,
23088
- "",
23089
- [],
23090
- "",
23091
- truncate(output2, AGENT_ACTIVITY_DETAIL_LIMIT),
23092
- identity2.sequence,
23093
- status,
23094
- activityType === "reasoning" ? "Reasoning" : "Progress update",
23095
- activityType === "reasoning" ? "think" : ""
23096
- );
23097
- recordPlan = async (plan) => {
23098
- await this.finishNarrative();
23099
- await this.#recordPlanEntries("plan:default", plan.entries);
23100
- };
23101
- recordPlanUpdate = async (update) => {
23102
- await this.finishNarrative();
23103
- const plan = update.plan;
23104
- const key = `plan:${plan.planId}`;
23105
- if (plan.type === "items") {
23106
- await this.#recordPlanEntries(key, plan.entries);
23107
- return;
23141
+ output2.on("error", fail);
23142
+ output2.once("close", () => {
23143
+ if (outputFailure === void 0) {
23144
+ fail(new Error("ACP process input closed"));
23108
23145
  }
23109
- const identity2 = this.#identity(key);
23110
- const output2 = plan.type === "markdown" ? plan.content : `Plan file: ${plan.uri}`;
23111
- await this.#record(
23112
- key,
23113
- new AcpActivity(
23114
- identity2.id,
23115
- "plan",
23116
- "",
23117
- [],
23118
- "",
23119
- truncate(output2, AGENT_ACTIVITY_DETAIL_LIMIT),
23120
- identity2.sequence,
23121
- "running",
23122
- "Plan",
23123
- ""
23124
- )
23125
- );
23126
- };
23127
- removePlan = async (update) => {
23128
- await this.finishNarrative();
23129
- const key = `plan:${update.planId}`;
23130
- const previous = this.#activities.get(key);
23131
- if (previous !== void 0) {
23132
- await this.#record(
23133
- key,
23134
- new AcpActivity(
23135
- previous.activityId,
23136
- previous.activityType,
23137
- previous.input,
23138
- previous.locations,
23139
- previous.name,
23140
- previous.output,
23141
- previous.sequence,
23142
- "completed",
23143
- previous.title,
23144
- previous.toolKind,
23145
- previous.content,
23146
- previous.detail
23147
- )
23148
- );
23146
+ });
23147
+ return new WritableStream({
23148
+ write(chunk) {
23149
+ if (outputFailure !== void 0) {
23150
+ return Promise.reject(outputFailure);
23151
+ }
23152
+ return new Promise((resolve9, reject) => {
23153
+ pendingWriteFailures.add(reject);
23154
+ output2.write(chunk, (error62) => {
23155
+ pendingWriteFailures.delete(reject);
23156
+ if (error62) {
23157
+ outputFailure = error62;
23158
+ reject(error62);
23159
+ return;
23160
+ }
23161
+ if (outputFailure !== void 0) {
23162
+ reject(outputFailure);
23163
+ return;
23164
+ }
23165
+ resolve9();
23166
+ });
23167
+ });
23149
23168
  }
23150
- };
23151
- recordToolCall = async (update) => {
23152
- await this.finishNarrative();
23153
- const key = `tool:${update.toolCallId}`;
23154
- const identity2 = this.#identity(key);
23155
- const output2 = update.rawOutput === void 0 ? readContentOutput(update.content) : formatUnknown(update.rawOutput);
23156
- const detailInput = update.rawInput === void 0 ? "" : formatUnknownDetail(update.rawInput);
23157
- const detailOutput = update.rawOutput === void 0 ? readContentOutputDetail(update.content) : formatUnknownDetail(update.rawOutput);
23158
- const detailContent = await normalizeToolContent(
23159
- toolContent(update.content, update.rawOutput),
23160
- this.#prepareContent
23161
- );
23162
- await this.#record(
23163
- key,
23164
- new AcpActivity(
23165
- identity2.id,
23166
- "tool",
23167
- update.rawInput === void 0 ? "" : formatUnknown(update.rawInput),
23168
- normalizeLocations(update.locations ?? []),
23169
- truncate(update.name ?? "", 128),
23170
- output2,
23171
- identity2.sequence,
23172
- normalizeToolStatus(update.status ?? "pending", "pending"),
23173
- normalizeTitle(update.title, "Tool call"),
23174
- update.kind ?? "other",
23175
- detailContent.slice(0, 100).map(summarizeDisplayContent),
23176
- captureActivityDetail(detailContent, detailInput, detailOutput)
23177
- )
23178
- );
23179
- };
23180
- recordToolCallUpdate = async (update) => {
23181
- await this.finishNarrative();
23182
- const key = `tool:${update.toolCallId}`;
23183
- const previous = this.#activities.get(key);
23184
- const identity2 = this.#identity(key);
23185
- const previousDetail = recordedDetail(previous);
23186
- const output2 = update.rawOutput !== void 0 ? formatUnknown(update.rawOutput) : update.content !== void 0 && update.content !== null ? readContentOutput(update.content) : previous?.output ?? "";
23187
- const nextContent = toolContent(update.content, update.rawOutput);
23188
- const content = nextContent.length === 0 ? previous?.content ?? [] : await normalizeToolContent(nextContent, this.#prepareContent);
23189
- const detailInput = update.rawInput === void 0 ? previousDetail?.input ?? previous?.input ?? "" : formatUnknownDetail(update.rawInput);
23190
- const detailOutput = update.rawOutput !== void 0 ? formatUnknownDetail(update.rawOutput) : update.content !== void 0 && update.content !== null ? readContentOutputDetail(update.content) : previousDetail?.output ?? previous?.output ?? "";
23191
- const detailContent = nextContent.length === 0 ? previousDetail?.content ?? previous?.content ?? [] : content;
23192
- await this.#record(
23193
- key,
23194
- new AcpActivity(
23195
- identity2.id,
23196
- "tool",
23197
- update.rawInput === void 0 ? previous?.input ?? "" : formatUnknown(update.rawInput),
23198
- update.locations === void 0 || update.locations === null ? previous?.locations ?? [] : normalizeLocations(update.locations),
23199
- update.name === void 0 || update.name === null ? previous?.name ?? "" : truncate(update.name, 128),
23200
- output2,
23201
- identity2.sequence,
23202
- update.status === void 0 || update.status === null ? previous?.status ?? "pending" : normalizeToolStatus(update.status, previous?.status ?? "pending"),
23203
- update.title === void 0 || update.title === null ? previous?.title ?? "Tool call" : normalizeTitle(update.title, "Tool call"),
23204
- update.kind === void 0 || update.kind === null ? previous?.toolKind ?? "other" : update.kind,
23205
- content.slice(0, 100).map(summarizeDisplayContent),
23206
- captureActivityDetail(detailContent, detailInput, detailOutput)
23207
- )
23208
- );
23209
- };
23210
- finishNarrative = async () => {
23211
- const key = this.#activeNarrativeKey;
23212
- if (key.length === 0) {
23169
+ });
23170
+ }
23171
+ var AgentConnection = class {
23172
+ connection;
23173
+ termination;
23174
+ #process;
23175
+ constructor(agent, cwd, client2) {
23176
+ if (agent.kind === "in-process-acp") {
23177
+ const inProcess = agent.createEndpoint({
23178
+ command: agent.command,
23179
+ cwd,
23180
+ environment: agent.environment
23181
+ });
23182
+ this.#process = { kind: "in-process", endpoint: inProcess };
23183
+ this.termination = inProcess.terminated;
23184
+ this.connection = createAcpClient(client2).connect(inProcess.app());
23213
23185
  return;
23214
23186
  }
23215
- this.#activeNarrativeKey = "";
23216
- await this.#completeNarrative(key);
23217
- };
23218
- finish = async () => {
23219
- await this.finishNarrative();
23220
- for (const key of this.#narrations.keys()) {
23221
- await this.#completeNarrative(key);
23187
+ const child = spawn2(agent.adapterPath, [...agent.arguments], {
23188
+ cwd,
23189
+ detached: process.platform !== "win32",
23190
+ env: { ...process.env, ...agent.environment },
23191
+ shell: false,
23192
+ stdio: ["pipe", "pipe", "pipe"]
23193
+ });
23194
+ this.#process = { kind: "child", child };
23195
+ const stdin = child.stdin;
23196
+ const stdout = child.stdout;
23197
+ const stderr = child.stderr;
23198
+ if (stdin === null || stdout === null || stderr === null) {
23199
+ child.kill("SIGKILL");
23200
+ throw new AcpExecutionError("ACP process streams are unavailable");
23222
23201
  }
23223
- const entries = [...this.#activities.entries()].sort((left, right) => left[1].sequence - right[1].sequence);
23224
- for (const [key, activity2] of entries) {
23225
- const completed = activity2.complete();
23226
- if (completed !== activity2) {
23227
- await this.#record(key, completed);
23202
+ stderr.setEncoding("utf8");
23203
+ stderr.on("data", (chunk) => {
23204
+ process.stderr.write(`[${agent.id}-acp] ${chunk}`);
23205
+ });
23206
+ this.termination = new Promise((resolve9) => {
23207
+ child.once("error", (cause) => {
23208
+ resolve9({ kind: "failed", error: new AcpExecutionError("The ACP process could not run", { cause }) });
23209
+ });
23210
+ child.once("exit", (code, signal) => {
23211
+ resolve9({
23212
+ kind: "failed",
23213
+ error: new AcpExecutionError("The ACP process stopped", { cause: { code, signal } })
23214
+ });
23215
+ });
23216
+ });
23217
+ const stream = ndJsonStream(createWritableAcpStream(stdin), readableWebStream(stdout));
23218
+ this.connection = createAcpClient(client2).connect(stream);
23219
+ }
23220
+ get inProcessAgent() {
23221
+ return this.#process.kind === "in-process" ? this.#process.endpoint : null;
23222
+ }
23223
+ captureProcessTree = async () => this.#process.kind === "child" ? await captureProcessTree(this.#process.child) : [];
23224
+ closeProcess = async (capturedProcesses = []) => {
23225
+ try {
23226
+ if (this.#process.kind === "in-process") {
23227
+ await this.#process.endpoint.close();
23228
+ return;
23228
23229
  }
23229
- }
23230
- };
23231
- // Materialize a streamed narration as one completed snapshot activity. The
23232
- // incremental events carried the text; this final event gives consumers the
23233
- // whole narration with its terminal status, as a single bounded item.
23234
- #completeNarrative = async (key) => {
23235
- const narration = this.#narrations.get(key);
23236
- if (narration === void 0) {
23237
- return;
23238
- }
23239
- this.#narrations.delete(key);
23240
- const previous = this.#activities.get(key);
23241
- const detail = narration.truncated ? {
23242
- capturedBytes: encodedByteLength({ content: [], input: "", output: narration.output }),
23243
- kind: "truncated",
23244
- originalBytes: narration.originalBytes
23245
- } : captureActivityDetail([], "", narration.output);
23246
- await this.#record(
23247
- key,
23248
- new AcpActivity(
23249
- narration.activityId,
23250
- narration.activityType,
23251
- "",
23252
- [],
23253
- "",
23254
- truncate(narration.output, AGENT_ACTIVITY_DETAIL_LIMIT),
23255
- narration.sequence,
23256
- "completed",
23257
- narration.activityType === "reasoning" ? "Reasoning" : "Progress update",
23258
- narration.activityType === "reasoning" ? "think" : "",
23259
- previous?.content ?? [],
23260
- detail
23261
- )
23262
- );
23263
- };
23264
- #identity = (key) => {
23265
- const existing = this.#identities.get(key);
23266
- if (existing !== void 0) {
23267
- return existing;
23268
- }
23269
- const identity2 = new ActivityIdentity(`activity-${crypto.randomUUID()}`, this.#nextSequence);
23270
- this.#nextSequence += 1;
23271
- this.#identities.set(key, identity2);
23272
- return identity2;
23273
- };
23274
- #record = async (key, activity2) => {
23275
- this.#activities.set(key, activity2);
23276
- await this.#onActivity(activity2);
23277
- };
23278
- #recordPlanEntries = async (key, entries) => {
23279
- const identity2 = this.#identity(key);
23280
- await this.#record(
23281
- key,
23282
- new AcpActivity(
23283
- identity2.id,
23284
- "plan",
23285
- "",
23286
- [],
23287
- "",
23288
- formatPlanEntries(entries),
23289
- identity2.sequence,
23290
- planStatus(entries),
23291
- "Plan",
23292
- ""
23293
- )
23294
- );
23295
- };
23296
- };
23297
-
23298
- // src/acp/native-session.ts
23299
- var path = external_exports.string().min(1).max(2048).refine((value) => !value.includes("\0"));
23300
- var title = external_exports.string().transform((value) => value.slice(0, 500));
23301
- var nativeSessionIdSchema = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/);
23302
- var nativeSessionInfoSchema = external_exports.object({
23303
- sessionId: nativeSessionIdSchema,
23304
- cwd: path,
23305
- additionalDirectories: external_exports.array(path).max(16).default([]).readonly(),
23306
- title: title.nullish(),
23307
- updatedAt: external_exports.iso.datetime({ offset: true }).nullish()
23308
- }).readonly();
23309
- var nativeSessionPageSchema = external_exports.object({
23310
- sessions: external_exports.array(nativeSessionInfoSchema).max(500).readonly(),
23311
- nextCursor: external_exports.string().min(1).max(4096).nullish()
23312
- }).readonly();
23313
-
23314
- // src/acp/process-endpoint.ts
23315
- import { spawn as spawn2 } from "node:child_process";
23316
- import { ndJsonStream, RequestError } from "@agentclientprotocol/sdk";
23317
-
23318
- // src/acp/in-process/acp-endpoint.ts
23319
- function acpEndpointTerminationError(termination) {
23320
- switch (termination.kind) {
23321
- case "failed":
23322
- return termination.error;
23323
- case "closed":
23324
- return new AcpExecutionError("The ACP endpoint is closed", {}, "acp_endpoint_closed");
23325
- default: {
23326
- const unreachable2 = termination;
23327
- return unreachable2;
23328
- }
23329
- }
23330
- }
23331
-
23332
- // src/acp/value-utils.ts
23333
- function truncate2(value, maximumLength) {
23334
- return value.length <= maximumLength ? value : `${value.slice(0, Math.max(0, maximumLength - 1))}\u2026`;
23335
- }
23336
- function isRecord4(value) {
23337
- return typeof value === "object" && value !== null && !Array.isArray(value);
23338
- }
23339
- function readString2(value, fallback = "") {
23340
- return typeof value === "string" ? value : fallback;
23341
- }
23342
-
23343
- // src/acp/process-endpoint.ts
23344
- function readableWebStream(input2) {
23345
- let streamOpen = true;
23346
- return new ReadableStream({
23347
- start(controller) {
23348
- input2.on("data", (chunk) => {
23349
- if (!streamOpen) {
23350
- return;
23351
- }
23352
- if (chunk instanceof Uint8Array) {
23353
- controller.enqueue(new Uint8Array(chunk));
23354
- return;
23355
- }
23356
- streamOpen = false;
23357
- controller.error(new Error("ACP process produced a non-binary chunk"));
23358
- });
23359
- input2.once("end", () => {
23360
- if (!streamOpen) {
23361
- return;
23362
- }
23363
- streamOpen = false;
23364
- controller.close();
23365
- });
23366
- input2.once("error", (error62) => {
23367
- if (!streamOpen) {
23368
- return;
23369
- }
23370
- streamOpen = false;
23371
- controller.error(error62);
23372
- });
23373
- },
23374
- cancel() {
23375
- streamOpen = false;
23376
- }
23377
- });
23378
- }
23379
- function createWritableAcpStream(output2) {
23380
- let outputFailure;
23381
- const pendingWriteFailures = /* @__PURE__ */ new Set();
23382
- const fail = (error62) => {
23383
- outputFailure = error62;
23384
- for (const reject of pendingWriteFailures) {
23385
- reject(error62);
23386
- }
23387
- pendingWriteFailures.clear();
23388
- };
23389
- output2.on("error", fail);
23390
- output2.once("close", () => {
23391
- if (outputFailure === void 0) {
23392
- fail(new Error("ACP process input closed"));
23393
- }
23394
- });
23395
- return new WritableStream({
23396
- write(chunk) {
23397
- if (outputFailure !== void 0) {
23398
- return Promise.reject(outputFailure);
23399
- }
23400
- return new Promise((resolve9, reject) => {
23401
- pendingWriteFailures.add(reject);
23402
- output2.write(chunk, (error62) => {
23403
- pendingWriteFailures.delete(reject);
23404
- if (error62) {
23405
- outputFailure = error62;
23406
- reject(error62);
23407
- return;
23408
- }
23409
- if (outputFailure !== void 0) {
23410
- reject(outputFailure);
23411
- return;
23412
- }
23413
- resolve9();
23414
- });
23415
- });
23416
- }
23417
- });
23418
- }
23419
- var AcpEndpoint = class {
23420
- connection;
23421
- termination;
23422
- #process;
23423
- constructor(agent, cwd, client2) {
23424
- if (agent.kind === "in-process-acp") {
23425
- const inProcess = agent.createEndpoint({
23426
- command: agent.command,
23427
- cwd,
23428
- environment: agent.environment
23429
- });
23430
- this.#process = { kind: "in-process", endpoint: inProcess };
23431
- this.termination = inProcess.terminated;
23432
- this.connection = createAcpClient(client2).connect(inProcess.app());
23433
- return;
23434
- }
23435
- const child = spawn2(agent.adapterPath, [...agent.arguments], {
23436
- cwd,
23437
- detached: process.platform !== "win32",
23438
- env: { ...process.env, ...agent.environment },
23439
- shell: false,
23440
- stdio: ["pipe", "pipe", "pipe"]
23441
- });
23442
- this.#process = { kind: "child", child };
23443
- const stdin = child.stdin;
23444
- const stdout = child.stdout;
23445
- const stderr = child.stderr;
23446
- if (stdin === null || stdout === null || stderr === null) {
23447
- child.kill("SIGKILL");
23448
- throw new AcpExecutionError("ACP process streams are unavailable");
23449
- }
23450
- stderr.setEncoding("utf8");
23451
- stderr.on("data", (chunk) => {
23452
- process.stderr.write(`[${agent.id}-acp] ${chunk}`);
23453
- });
23454
- this.termination = new Promise((resolve9) => {
23455
- child.once("error", (cause) => {
23456
- resolve9({ kind: "failed", error: new AcpExecutionError("The ACP process could not run", { cause }) });
23457
- });
23458
- child.once("exit", (code, signal) => {
23459
- resolve9({
23460
- kind: "failed",
23461
- error: new AcpExecutionError("The ACP process stopped", { cause: { code, signal } })
23462
- });
23463
- });
23464
- });
23465
- const stream = ndJsonStream(createWritableAcpStream(stdin), readableWebStream(stdout));
23466
- this.connection = createAcpClient(client2).connect(stream);
23467
- }
23468
- get inProcessAgent() {
23469
- return this.#process.kind === "in-process" ? this.#process.endpoint : null;
23470
- }
23471
- captureProcessTree = async () => this.#process.kind === "child" ? await captureProcessTree(this.#process.child) : [];
23472
- closeProcess = async (capturedProcesses = []) => {
23473
- try {
23474
- if (this.#process.kind === "in-process") {
23475
- await this.#process.endpoint.close();
23476
- return;
23477
- }
23478
- await stopProcessTree(this.#process.child, capturedProcesses);
23479
- } finally {
23480
- this.connection.close();
23230
+ await stopProcessTree(this.#process.child, capturedProcesses);
23231
+ } finally {
23232
+ this.connection.close();
23481
23233
  }
23482
23234
  };
23483
23235
  race = async (operation, exitMessage, signal) => {
@@ -23523,6 +23275,86 @@ var AcpEndpoint = class {
23523
23275
  };
23524
23276
  };
23525
23277
 
23278
+ // src/acp/native-session.ts
23279
+ var path = external_exports.string().min(1).max(2048).refine((value) => !value.includes("\0"));
23280
+ var title = external_exports.string().transform((value) => value.slice(0, 500));
23281
+ var nativeSessionIdSchema = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/);
23282
+ var nativeSessionInfoSchema = external_exports.object({
23283
+ sessionId: nativeSessionIdSchema,
23284
+ cwd: path,
23285
+ additionalDirectories: external_exports.array(path).max(16).default([]).readonly(),
23286
+ title: title.nullish(),
23287
+ updatedAt: external_exports.iso.datetime({ offset: true }).nullish()
23288
+ }).readonly();
23289
+ var nativeSessionPageSchema = external_exports.object({
23290
+ sessions: external_exports.array(nativeSessionInfoSchema).max(500).readonly(),
23291
+ nextCursor: external_exports.string().min(1).max(4096).nullish()
23292
+ }).readonly();
23293
+
23294
+ // src/acp/agent-update-stream.ts
23295
+ var MAX_PENDING_UPDATES = 100;
23296
+ var MAX_PENDING_BYTES = 1024 * 1024;
23297
+ var AgentUpdateStream = class {
23298
+ #selection = { kind: "awaiting-session", notifications: [], bytes: 0 };
23299
+ #tail = Promise.resolve();
23300
+ #consume;
23301
+ constructor(consume) {
23302
+ this.#consume = consume;
23303
+ }
23304
+ sessionId = () => this.#selection.kind === "selected" ? this.#selection.sessionId : "";
23305
+ drained = () => this.#tail;
23306
+ #enqueue = (notification) => {
23307
+ this.#tail = this.#tail.then(async () => await this.#consume(notification));
23308
+ return this.#tail;
23309
+ };
23310
+ receive = (notification) => {
23311
+ const selection = this.#selection;
23312
+ switch (selection.kind) {
23313
+ case "selected":
23314
+ return this.#enqueue(notification);
23315
+ case "awaiting-session": {
23316
+ const bytes = selection.bytes + Buffer.byteLength(JSON.stringify(notification));
23317
+ if (selection.notifications.length >= MAX_PENDING_UPDATES || bytes > MAX_PENDING_BYTES) {
23318
+ return Promise.reject(
23319
+ new AcpExecutionError(
23320
+ "ACP agent sent too many updates before creating its session",
23321
+ {},
23322
+ "agent_update_limit"
23323
+ )
23324
+ );
23325
+ }
23326
+ this.#selection = {
23327
+ kind: "awaiting-session",
23328
+ notifications: [...selection.notifications, notification],
23329
+ bytes
23330
+ };
23331
+ return Promise.resolve();
23332
+ }
23333
+ }
23334
+ };
23335
+ select = (sessionId) => {
23336
+ const selected = nativeSessionIdSchema.parse(sessionId);
23337
+ const selection = this.#selection;
23338
+ switch (selection.kind) {
23339
+ case "selected":
23340
+ if (selection.sessionId !== selected) {
23341
+ throw new AcpExecutionError(
23342
+ "ACP agent attempted to replace the selected session",
23343
+ {},
23344
+ "invalid_agent_session"
23345
+ );
23346
+ }
23347
+ return;
23348
+ case "awaiting-session":
23349
+ this.#selection = { kind: "selected", sessionId: selected };
23350
+ for (const notification of selection.notifications) {
23351
+ void this.#enqueue(notification);
23352
+ }
23353
+ return;
23354
+ }
23355
+ };
23356
+ };
23357
+
23526
23358
  // src/acp/session-config/session-config-protocol.ts
23527
23359
  import { methods as methods2 } from "@agentclientprotocol/sdk";
23528
23360
  var MAXIMUM_CONFIG_OPTIONS = 100;
@@ -23712,58 +23544,373 @@ var StandardSessionConfigProtocol = class {
23712
23544
  "ACP agent exited while changing session configuration",
23713
23545
  change.signal
23714
23546
  );
23715
- if (!isRecord5(response) || !Array.isArray(response["configOptions"])) {
23716
- throw new SessionConfigProtocolError("The Agent returned an invalid session configuration response");
23547
+ if (!isRecord5(response) || !Array.isArray(response["configOptions"])) {
23548
+ throw new SessionConfigProtocolError("The Agent returned an invalid session configuration response");
23549
+ }
23550
+ return replaceStandardConfigOptions(current, response["configOptions"]);
23551
+ };
23552
+ normalizeLifecycle = (response) => normalizeStandardLifecycle(response);
23553
+ normalizeUpdate = (current, value) => replaceStandardConfigOptions(current, value);
23554
+ };
23555
+ var standardSessionConfigProtocol = new StandardSessionConfigProtocol();
23556
+
23557
+ // src/acp/session-config/session-config-registry.ts
23558
+ function sessionConfigProtocolForAgent(_agentId) {
23559
+ return standardSessionConfigProtocol;
23560
+ }
23561
+
23562
+ // src/acp/session-contracts.ts
23563
+ var NullAcpSessionObserver = class {
23564
+ onCommands = () => Promise.resolve();
23565
+ onConfig = () => Promise.resolve();
23566
+ onContent = () => Promise.resolve();
23567
+ onElicitation = () => Promise.resolve();
23568
+ onElicitationResolved = () => Promise.resolve();
23569
+ onInfo = () => Promise.resolve();
23570
+ onPermission = () => Promise.resolve();
23571
+ onPermissionResolved = () => Promise.resolve();
23572
+ onUsage = () => Promise.resolve();
23573
+ };
23574
+ var AcpPreparedSession = class {
23575
+ agentName;
23576
+ agentVersion;
23577
+ capabilities;
23578
+ commands;
23579
+ configOptions;
23580
+ restored;
23581
+ constructor(agentName, agentVersion, capabilities, commands, configOptions, restored) {
23582
+ this.agentName = agentName;
23583
+ this.agentVersion = agentVersion;
23584
+ this.capabilities = capabilities;
23585
+ this.commands = commands;
23586
+ this.configOptions = configOptions;
23587
+ this.restored = restored;
23588
+ }
23589
+ };
23590
+ var AcpAgentSettingsSnapshot = class {
23591
+ agentName;
23592
+ agentVersion;
23593
+ configOptions;
23594
+ constructor(agentName, agentVersion, configOptions) {
23595
+ this.agentName = agentName;
23596
+ this.agentVersion = agentVersion;
23597
+ this.configOptions = configOptions;
23598
+ }
23599
+ };
23600
+
23601
+ // src/acp/activity.ts
23602
+ var AcpActivityNarration = class {
23603
+ activityId;
23604
+ activityType;
23605
+ sequence;
23606
+ text;
23607
+ constructor(activityId, activityType, sequence, text2) {
23608
+ this.activityId = activityId;
23609
+ this.activityType = activityType;
23610
+ this.sequence = sequence;
23611
+ this.text = text2;
23612
+ }
23613
+ };
23614
+ var AcpActivity = class _AcpActivity {
23615
+ activityId;
23616
+ activityType;
23617
+ input;
23618
+ locations;
23619
+ name;
23620
+ output;
23621
+ sequence;
23622
+ status;
23623
+ title;
23624
+ toolKind;
23625
+ content;
23626
+ detail;
23627
+ constructor(activityId, activityType, input2, locations, name, output2, sequence, status, title2, toolKind, content = [], detail = captureActivityDetail(content, input2, output2)) {
23628
+ this.activityId = activityId;
23629
+ this.activityType = activityType;
23630
+ this.input = input2;
23631
+ this.locations = locations;
23632
+ this.name = name;
23633
+ this.output = output2;
23634
+ this.sequence = sequence;
23635
+ this.status = status;
23636
+ this.title = title2;
23637
+ this.toolKind = toolKind;
23638
+ this.content = content;
23639
+ this.detail = detail;
23640
+ }
23641
+ complete = () => (this.activityType === "progress" || this.activityType === "reasoning") && (this.status === "pending" || this.status === "running") ? new _AcpActivity(
23642
+ this.activityId,
23643
+ this.activityType,
23644
+ this.input,
23645
+ this.locations,
23646
+ this.name,
23647
+ this.output,
23648
+ this.sequence,
23649
+ "completed",
23650
+ this.title,
23651
+ this.toolKind,
23652
+ this.content,
23653
+ this.detail
23654
+ ) : this;
23655
+ };
23656
+ var ActivityIdentity = class {
23657
+ id;
23658
+ sequence;
23659
+ constructor(id, sequence) {
23660
+ this.id = id;
23661
+ this.sequence = sequence;
23662
+ }
23663
+ };
23664
+ var AcpActivityTracker = class {
23665
+ #activities = /* @__PURE__ */ new Map();
23666
+ #identities = /* @__PURE__ */ new Map();
23667
+ #narrations = /* @__PURE__ */ new Map();
23668
+ #onActivity;
23669
+ #onNarration;
23670
+ #prepareContent;
23671
+ #activeNarrativeKey = "";
23672
+ #nextSequence = 0;
23673
+ constructor(onActivity, onNarration, prepareContent = (content) => Promise.resolve(content)) {
23674
+ this.#onActivity = onActivity;
23675
+ this.#onNarration = onNarration;
23676
+ this.#prepareContent = prepareContent;
23677
+ }
23678
+ recordNarrative = async (activityType, messageId, text2) => {
23679
+ const key = `${activityType}:${messageId}`;
23680
+ if (this.#activeNarrativeKey !== key) {
23681
+ await this.finishNarrative();
23682
+ }
23683
+ const identity2 = this.#identity(key);
23684
+ const previous = this.#narrations.get(key);
23685
+ const previousOutput = previous?.output ?? "";
23686
+ const remaining = Math.max(0, AGENT_ACTIVITY_DETAIL_LIMIT - previousOutput.length);
23687
+ this.#narrations.set(key, {
23688
+ activityId: identity2.id,
23689
+ activityType,
23690
+ output: `${previousOutput}${text2.slice(0, remaining)}`,
23691
+ originalBytes: (previous?.originalBytes ?? 0) + new TextEncoder().encode(text2).byteLength,
23692
+ sequence: identity2.sequence,
23693
+ truncated: (previous?.truncated ?? false) || text2.length > remaining
23694
+ });
23695
+ if (previous === void 0) {
23696
+ await this.#record(key, this.#narrativeSnapshot(identity2, activityType, "", "running"));
23697
+ }
23698
+ this.#activeNarrativeKey = key;
23699
+ if (text2.length > 0) {
23700
+ await this.#onNarration(new AcpActivityNarration(identity2.id, activityType, identity2.sequence, text2));
23701
+ }
23702
+ };
23703
+ #narrativeSnapshot = (identity2, activityType, output2, status) => new AcpActivity(
23704
+ identity2.id,
23705
+ activityType,
23706
+ "",
23707
+ [],
23708
+ "",
23709
+ truncate(output2, AGENT_ACTIVITY_DETAIL_LIMIT),
23710
+ identity2.sequence,
23711
+ status,
23712
+ activityType === "reasoning" ? "Reasoning" : "Progress update",
23713
+ activityType === "reasoning" ? "think" : ""
23714
+ );
23715
+ recordPlan = async (plan) => {
23716
+ await this.finishNarrative();
23717
+ await this.#recordPlanEntries("plan:default", plan.entries);
23718
+ };
23719
+ recordPlanUpdate = async (update) => {
23720
+ await this.finishNarrative();
23721
+ const plan = update.plan;
23722
+ const key = `plan:${plan.planId}`;
23723
+ if (plan.type === "items") {
23724
+ await this.#recordPlanEntries(key, plan.entries);
23725
+ return;
23726
+ }
23727
+ const identity2 = this.#identity(key);
23728
+ const output2 = plan.type === "markdown" ? plan.content : `Plan file: ${plan.uri}`;
23729
+ await this.#record(
23730
+ key,
23731
+ new AcpActivity(
23732
+ identity2.id,
23733
+ "plan",
23734
+ "",
23735
+ [],
23736
+ "",
23737
+ truncate(output2, AGENT_ACTIVITY_DETAIL_LIMIT),
23738
+ identity2.sequence,
23739
+ "running",
23740
+ "Plan",
23741
+ ""
23742
+ )
23743
+ );
23744
+ };
23745
+ removePlan = async (update) => {
23746
+ await this.finishNarrative();
23747
+ const key = `plan:${update.planId}`;
23748
+ const previous = this.#activities.get(key);
23749
+ if (previous !== void 0) {
23750
+ await this.#record(
23751
+ key,
23752
+ new AcpActivity(
23753
+ previous.activityId,
23754
+ previous.activityType,
23755
+ previous.input,
23756
+ previous.locations,
23757
+ previous.name,
23758
+ previous.output,
23759
+ previous.sequence,
23760
+ "completed",
23761
+ previous.title,
23762
+ previous.toolKind,
23763
+ previous.content,
23764
+ previous.detail
23765
+ )
23766
+ );
23767
+ }
23768
+ };
23769
+ recordToolCall = async (update) => {
23770
+ await this.finishNarrative();
23771
+ const key = `tool:${update.toolCallId}`;
23772
+ const identity2 = this.#identity(key);
23773
+ const output2 = update.rawOutput === void 0 ? readContentOutput(update.content) : formatUnknown(update.rawOutput);
23774
+ const detailInput = update.rawInput === void 0 ? "" : formatUnknownDetail(update.rawInput);
23775
+ const detailOutput = update.rawOutput === void 0 ? readContentOutputDetail(update.content) : formatUnknownDetail(update.rawOutput);
23776
+ const detailContent = await normalizeToolContent(
23777
+ toolContent(update.content, update.rawOutput),
23778
+ this.#prepareContent
23779
+ );
23780
+ await this.#record(
23781
+ key,
23782
+ new AcpActivity(
23783
+ identity2.id,
23784
+ "tool",
23785
+ update.rawInput === void 0 ? "" : formatUnknown(update.rawInput),
23786
+ normalizeLocations(update.locations ?? []),
23787
+ truncate(update.name ?? "", 128),
23788
+ output2,
23789
+ identity2.sequence,
23790
+ normalizeToolStatus(update.status ?? "pending", "pending"),
23791
+ normalizeTitle(update.title, "Tool call"),
23792
+ update.kind ?? "other",
23793
+ detailContent.slice(0, 100).map(summarizeDisplayContent),
23794
+ captureActivityDetail(detailContent, detailInput, detailOutput)
23795
+ )
23796
+ );
23797
+ };
23798
+ recordToolCallUpdate = async (update) => {
23799
+ await this.finishNarrative();
23800
+ const key = `tool:${update.toolCallId}`;
23801
+ const previous = this.#activities.get(key);
23802
+ const identity2 = this.#identity(key);
23803
+ const previousDetail = recordedDetail(previous);
23804
+ const output2 = update.rawOutput !== void 0 ? formatUnknown(update.rawOutput) : update.content !== void 0 && update.content !== null ? readContentOutput(update.content) : previous?.output ?? "";
23805
+ const nextContent = toolContent(update.content, update.rawOutput);
23806
+ const content = nextContent.length === 0 ? previous?.content ?? [] : await normalizeToolContent(nextContent, this.#prepareContent);
23807
+ const detailInput = update.rawInput === void 0 ? previousDetail?.input ?? previous?.input ?? "" : formatUnknownDetail(update.rawInput);
23808
+ const detailOutput = update.rawOutput !== void 0 ? formatUnknownDetail(update.rawOutput) : update.content !== void 0 && update.content !== null ? readContentOutputDetail(update.content) : previousDetail?.output ?? previous?.output ?? "";
23809
+ const detailContent = nextContent.length === 0 ? previousDetail?.content ?? previous?.content ?? [] : content;
23810
+ await this.#record(
23811
+ key,
23812
+ new AcpActivity(
23813
+ identity2.id,
23814
+ "tool",
23815
+ update.rawInput === void 0 ? previous?.input ?? "" : formatUnknown(update.rawInput),
23816
+ update.locations === void 0 || update.locations === null ? previous?.locations ?? [] : normalizeLocations(update.locations),
23817
+ update.name === void 0 || update.name === null ? previous?.name ?? "" : truncate(update.name, 128),
23818
+ output2,
23819
+ identity2.sequence,
23820
+ update.status === void 0 || update.status === null ? previous?.status ?? "pending" : normalizeToolStatus(update.status, previous?.status ?? "pending"),
23821
+ update.title === void 0 || update.title === null ? previous?.title ?? "Tool call" : normalizeTitle(update.title, "Tool call"),
23822
+ update.kind === void 0 || update.kind === null ? previous?.toolKind ?? "other" : update.kind,
23823
+ content.slice(0, 100).map(summarizeDisplayContent),
23824
+ captureActivityDetail(detailContent, detailInput, detailOutput)
23825
+ )
23826
+ );
23827
+ };
23828
+ finishNarrative = async () => {
23829
+ const key = this.#activeNarrativeKey;
23830
+ if (key.length === 0) {
23831
+ return;
23832
+ }
23833
+ this.#activeNarrativeKey = "";
23834
+ await this.#completeNarrative(key);
23835
+ };
23836
+ finish = async () => {
23837
+ await this.finishNarrative();
23838
+ for (const key of this.#narrations.keys()) {
23839
+ await this.#completeNarrative(key);
23840
+ }
23841
+ const entries = [...this.#activities.entries()].sort((left, right) => left[1].sequence - right[1].sequence);
23842
+ for (const [key, activity2] of entries) {
23843
+ const completed = activity2.complete();
23844
+ if (completed !== activity2) {
23845
+ await this.#record(key, completed);
23846
+ }
23847
+ }
23848
+ };
23849
+ // Materialize a streamed narration as one completed snapshot activity. The
23850
+ // incremental events carried the text; this final event gives consumers the
23851
+ // whole narration with its terminal status, as a single bounded item.
23852
+ #completeNarrative = async (key) => {
23853
+ const narration = this.#narrations.get(key);
23854
+ if (narration === void 0) {
23855
+ return;
23856
+ }
23857
+ this.#narrations.delete(key);
23858
+ const previous = this.#activities.get(key);
23859
+ const detail = narration.truncated ? {
23860
+ capturedBytes: encodedByteLength({ content: [], input: "", output: narration.output }),
23861
+ kind: "truncated",
23862
+ originalBytes: narration.originalBytes
23863
+ } : captureActivityDetail([], "", narration.output);
23864
+ await this.#record(
23865
+ key,
23866
+ new AcpActivity(
23867
+ narration.activityId,
23868
+ narration.activityType,
23869
+ "",
23870
+ [],
23871
+ "",
23872
+ truncate(narration.output, AGENT_ACTIVITY_DETAIL_LIMIT),
23873
+ narration.sequence,
23874
+ "completed",
23875
+ narration.activityType === "reasoning" ? "Reasoning" : "Progress update",
23876
+ narration.activityType === "reasoning" ? "think" : "",
23877
+ previous?.content ?? [],
23878
+ detail
23879
+ )
23880
+ );
23881
+ };
23882
+ #identity = (key) => {
23883
+ const existing = this.#identities.get(key);
23884
+ if (existing !== void 0) {
23885
+ return existing;
23717
23886
  }
23718
- return replaceStandardConfigOptions(current, response["configOptions"]);
23887
+ const identity2 = new ActivityIdentity(`activity-${crypto.randomUUID()}`, this.#nextSequence);
23888
+ this.#nextSequence += 1;
23889
+ this.#identities.set(key, identity2);
23890
+ return identity2;
23891
+ };
23892
+ #record = async (key, activity2) => {
23893
+ this.#activities.set(key, activity2);
23894
+ await this.#onActivity(activity2);
23895
+ };
23896
+ #recordPlanEntries = async (key, entries) => {
23897
+ const identity2 = this.#identity(key);
23898
+ await this.#record(
23899
+ key,
23900
+ new AcpActivity(
23901
+ identity2.id,
23902
+ "plan",
23903
+ "",
23904
+ [],
23905
+ "",
23906
+ formatPlanEntries(entries),
23907
+ identity2.sequence,
23908
+ planStatus(entries),
23909
+ "Plan",
23910
+ ""
23911
+ )
23912
+ );
23719
23913
  };
23720
- normalizeLifecycle = (response) => normalizeStandardLifecycle(response);
23721
- normalizeUpdate = (current, value) => replaceStandardConfigOptions(current, value);
23722
- };
23723
- var standardSessionConfigProtocol = new StandardSessionConfigProtocol();
23724
-
23725
- // src/acp/session-config/session-config-registry.ts
23726
- function sessionConfigProtocolForAgent(_agentId) {
23727
- return standardSessionConfigProtocol;
23728
- }
23729
-
23730
- // src/acp/session-contracts.ts
23731
- var NullAcpSessionObserver = class {
23732
- onCommands = () => Promise.resolve();
23733
- onConfig = () => Promise.resolve();
23734
- onContent = () => Promise.resolve();
23735
- onElicitation = () => Promise.resolve();
23736
- onElicitationResolved = () => Promise.resolve();
23737
- onInfo = () => Promise.resolve();
23738
- onPermission = () => Promise.resolve();
23739
- onPermissionResolved = () => Promise.resolve();
23740
- onUsage = () => Promise.resolve();
23741
- };
23742
- var AcpPreparedSession = class {
23743
- agentName;
23744
- agentVersion;
23745
- capabilities;
23746
- commands;
23747
- configOptions;
23748
- restored;
23749
- constructor(agentName, agentVersion, capabilities, commands, configOptions, restored) {
23750
- this.agentName = agentName;
23751
- this.agentVersion = agentVersion;
23752
- this.capabilities = capabilities;
23753
- this.commands = commands;
23754
- this.configOptions = configOptions;
23755
- this.restored = restored;
23756
- }
23757
- };
23758
- var AcpAgentSettingsSnapshot = class {
23759
- agentName;
23760
- agentVersion;
23761
- configOptions;
23762
- constructor(agentName, agentVersion, configOptions) {
23763
- this.agentName = agentName;
23764
- this.agentVersion = agentVersion;
23765
- this.configOptions = configOptions;
23766
- }
23767
23914
  };
23768
23915
 
23769
23916
  // src/acp/session-history.ts
@@ -30141,10 +30288,8 @@ var SqliteAcpSessionStore = class {
30141
30288
  };
30142
30289
  };
30143
30290
 
30144
- // src/acp/process-session.ts
30291
+ // src/acp/agent-session.ts
30145
30292
  var PROCESS_STOP_TIMEOUT_MILLISECONDS = 1e3;
30146
- var MAX_PRE_SESSION_UPDATES = 100;
30147
- var MAX_PRE_SESSION_UPDATE_BYTES = 1024 * 1024;
30148
30293
  var RetryableAcpInitializationError = class extends AcpExecutionError {
30149
30294
  constructor(cause) {
30150
30295
  super("ACP agent initialization failed", { cause });
@@ -30159,8 +30304,8 @@ function recordsEqual(left, right) {
30159
30304
  const rightEntries = Object.entries(right);
30160
30305
  return leftEntries.length === rightEntries.length && leftEntries.every(([name, value]) => right[name] === value);
30161
30306
  }
30162
- var AcpProcessSession = class _AcpProcessSession {
30163
- #endpoint;
30307
+ var AgentSession = class _AgentSession {
30308
+ #connection;
30164
30309
  #interactions;
30165
30310
  #additionalDirectories;
30166
30311
  #agentId;
@@ -30168,12 +30313,11 @@ var AcpProcessSession = class _AcpProcessSession {
30168
30313
  #environment;
30169
30314
  #getObserver;
30170
30315
  #mobiusSessionId;
30171
- #preSessionUpdates = [];
30316
+ #updates;
30172
30317
  #metrics;
30173
30318
  #sessionConfigProtocol;
30174
30319
  #store;
30175
30320
  #verifiedAgentVersion;
30176
- #preSessionUpdateBytes = 0;
30177
30321
  #agentName = "";
30178
30322
  #agentVersion = "";
30179
30323
  #bufferedAgentText = [];
@@ -30181,7 +30325,6 @@ var AcpProcessSession = class _AcpProcessSession {
30181
30325
  #commands = [];
30182
30326
  #configRevision = 0;
30183
30327
  #configOptions = [];
30184
- #nativeSessionId = "";
30185
30328
  #prompted = false;
30186
30329
  #nativePrompt = null;
30187
30330
  #replay = {
@@ -30191,10 +30334,11 @@ var AcpProcessSession = class _AcpProcessSession {
30191
30334
  #sessionTitle = null;
30192
30335
  #sessionUpdatedAt = "";
30193
30336
  #turn = new IdleAcpTurn();
30194
- #updateTail = Promise.resolve();
30195
30337
  constructor(agent, cwd, additionalDirectories, mobiusSessionId, getObserver, store, metrics) {
30338
+ this.#updates = new AgentUpdateStream((notification) => this.#processUpdate(notification));
30196
30339
  this.#additionalDirectories = [...additionalDirectories];
30197
30340
  this.#agentId = agent.id;
30341
+ this.#commands = [];
30198
30342
  this.#cwd = cwd;
30199
30343
  this.#environment = agent.environment;
30200
30344
  this.#getObserver = getObserver;
@@ -30209,7 +30353,7 @@ var AcpProcessSession = class _AcpProcessSession {
30209
30353
  assertNativeSession: (sessionId) => this.assertNativeSession(sessionId),
30210
30354
  observer: getObserver
30211
30355
  });
30212
- this.#endpoint = new AcpEndpoint(agent, cwd, this);
30356
+ this.#connection = new AgentConnection(agent, cwd, this);
30213
30357
  }
30214
30358
  static async #start(options, getObserver, store, initialize, metrics) {
30215
30359
  for (let attempt = 1; attempt <= 2; attempt += 1) {
@@ -30232,7 +30376,7 @@ var AcpProcessSession = class _AcpProcessSession {
30232
30376
  }
30233
30377
  const runtime = metrics.measureSync(
30234
30378
  "process-spawn",
30235
- () => new _AcpProcessSession(
30379
+ () => new _AgentSession(
30236
30380
  options.agent,
30237
30381
  options.cwd,
30238
30382
  options.additionalDirectories,
@@ -30262,14 +30406,14 @@ var AcpProcessSession = class _AcpProcessSession {
30262
30406
  }
30263
30407
  throw new AcpExecutionError("ACP agent initialization failed");
30264
30408
  }
30265
- static start = async (options, getObserver, store, metrics = unmeasuredOperationMetrics) => await _AcpProcessSession.#start(
30409
+ static start = async (options, getObserver, store, metrics = unmeasuredOperationMetrics) => await _AgentSession.#start(
30266
30410
  options,
30267
30411
  getObserver,
30268
30412
  store,
30269
30413
  async (runtime) => await runtime.initialize(options.signal, options.origin),
30270
30414
  metrics
30271
30415
  );
30272
- static startNativeSessionBrowser = async (options, getObserver, store) => await _AcpProcessSession.#start(
30416
+ static startNativeSessionBrowser = async (options, getObserver, store) => await _AgentSession.#start(
30273
30417
  options,
30274
30418
  getObserver,
30275
30419
  store,
@@ -30302,20 +30446,20 @@ var AcpProcessSession = class _AcpProcessSession {
30302
30446
  this.#replay = { kind: "capture", history };
30303
30447
  try {
30304
30448
  await this.race(
30305
- this.#endpoint.connection.agent.request(
30449
+ this.#connection.connection.agent.request(
30306
30450
  methods3.agent.session.load,
30307
30451
  {
30308
30452
  additionalDirectories: [...this.#additionalDirectories],
30309
30453
  cwd: this.#cwd,
30310
30454
  mcpServers: [],
30311
- sessionId: this.#nativeSessionId
30455
+ sessionId: this.#updates.sessionId()
30312
30456
  },
30313
30457
  { cancellationSignal: signal }
30314
30458
  ),
30315
30459
  "ACP agent exited while loading history",
30316
30460
  signal
30317
30461
  );
30318
- await this.#updateTail;
30462
+ await this.#updates.drained();
30319
30463
  signal.throwIfAborted();
30320
30464
  return await embedLocalHistoryImages(await history.snapshot(), signal);
30321
30465
  } finally {
@@ -30411,9 +30555,9 @@ var AcpProcessSession = class _AcpProcessSession {
30411
30555
  await this.#metrics.measure("agent-initialize", async () => await this.#initializeAgentOperation(signal));
30412
30556
  }
30413
30557
  async #initializeAgentOperation(signal) {
30414
- if (this.#endpoint.inProcessAgent !== null) {
30558
+ if (this.#connection.inProcessAgent !== null) {
30415
30559
  await this.race(
30416
- this.#endpoint.inProcessAgent.initialize(signal),
30560
+ this.#connection.inProcessAgent.initialize(signal),
30417
30561
  "The Codex app-server exited during initialization",
30418
30562
  signal
30419
30563
  ).catch((cause) => {
@@ -30422,7 +30566,7 @@ var AcpProcessSession = class _AcpProcessSession {
30422
30566
  });
30423
30567
  }
30424
30568
  const initialized = await this.race(
30425
- this.#endpoint.connection.agent.request(
30569
+ this.#connection.connection.agent.request(
30426
30570
  methods3.agent.initialize,
30427
30571
  {
30428
30572
  clientCapabilities: {
@@ -30501,7 +30645,7 @@ var AcpProcessSession = class _AcpProcessSession {
30501
30645
  const forked = await this.#metrics.measure(
30502
30646
  "session-fork",
30503
30647
  async () => await this.race(
30504
- this.#endpoint.connection.agent.request(
30648
+ this.#connection.connection.agent.request(
30505
30649
  methods3.agent.session.fork,
30506
30650
  {
30507
30651
  sessionId: nativeSessionIdSchema.parse(origin.nativeSessionId),
@@ -30516,7 +30660,7 @@ var AcpProcessSession = class _AcpProcessSession {
30516
30660
  )
30517
30661
  );
30518
30662
  this.selectNativeSession(forked.sessionId);
30519
- if (this.#nativeSessionId === origin.nativeSessionId || this.#store.findNative(this.#agentId, this.#nativeSessionId).length > 0) {
30663
+ if (this.#updates.sessionId() === origin.nativeSessionId || this.#store.findNative(this.#agentId, this.#updates.sessionId()).length > 0) {
30520
30664
  throw new AcpExecutionError(
30521
30665
  "The Agent did not create an independent fork",
30522
30666
  {},
@@ -30535,13 +30679,13 @@ var AcpProcessSession = class _AcpProcessSession {
30535
30679
  lifecycleResponse = await this.#metrics.measure(
30536
30680
  "session-resume",
30537
30681
  async () => await this.race(
30538
- this.#endpoint.connection.agent.request(
30682
+ this.#connection.connection.agent.request(
30539
30683
  methods3.agent.session.resume,
30540
30684
  {
30541
30685
  additionalDirectories: [...this.#additionalDirectories],
30542
30686
  cwd: this.#cwd,
30543
30687
  mcpServers: [],
30544
- sessionId: this.#nativeSessionId
30688
+ sessionId: this.#updates.sessionId()
30545
30689
  },
30546
30690
  { cancellationSignal: signal }
30547
30691
  ),
@@ -30555,13 +30699,13 @@ var AcpProcessSession = class _AcpProcessSession {
30555
30699
  lifecycleResponse = await this.#metrics.measure(
30556
30700
  "session-load",
30557
30701
  async () => await this.race(
30558
- this.#endpoint.connection.agent.request(
30702
+ this.#connection.connection.agent.request(
30559
30703
  methods3.agent.session.load,
30560
30704
  {
30561
30705
  additionalDirectories: [...this.#additionalDirectories],
30562
30706
  cwd: this.#cwd,
30563
30707
  mcpServers: [],
30564
- sessionId: this.#nativeSessionId
30708
+ sessionId: this.#updates.sessionId()
30565
30709
  },
30566
30710
  { cancellationSignal: signal }
30567
30711
  ),
@@ -30570,7 +30714,7 @@ var AcpProcessSession = class _AcpProcessSession {
30570
30714
  )
30571
30715
  );
30572
30716
  } finally {
30573
- await this.#updateTail;
30717
+ await this.#updates.drained();
30574
30718
  this.#replay = { kind: "idle" };
30575
30719
  }
30576
30720
  } else {
@@ -30594,7 +30738,7 @@ var AcpProcessSession = class _AcpProcessSession {
30594
30738
  const created = await this.#metrics.measure(
30595
30739
  "session-new",
30596
30740
  async () => await this.race(
30597
- this.#endpoint.connection.agent.request(
30741
+ this.#connection.connection.agent.request(
30598
30742
  methods3.agent.session.new,
30599
30743
  {
30600
30744
  additionalDirectories: [...this.#additionalDirectories],
@@ -30611,13 +30755,13 @@ var AcpProcessSession = class _AcpProcessSession {
30611
30755
  lifecycleResponse = created;
30612
30756
  }
30613
30757
  this.#configOptions = this.#sessionConfigProtocol.normalizeLifecycle(lifecycleResponse);
30614
- await this.#updateTail;
30758
+ await this.#updates.drained();
30615
30759
  signal.throwIfAborted();
30616
30760
  this.#store.write(
30617
30761
  new AcpStoredSession(
30618
30762
  this.#mobiusSessionId,
30619
30763
  this.#agentId,
30620
- this.#nativeSessionId,
30764
+ this.#updates.sessionId(),
30621
30765
  this.#cwd,
30622
30766
  this.#additionalDirectories,
30623
30767
  this.#prompted,
@@ -30634,7 +30778,7 @@ var AcpProcessSession = class _AcpProcessSession {
30634
30778
  );
30635
30779
  }
30636
30780
  const response = await this.race(
30637
- this.#endpoint.connection.agent.request(methods3.agent.session.list, cursor === null ? {} : { cursor }, {
30781
+ this.#connection.connection.agent.request(methods3.agent.session.list, cursor === null ? {} : { cursor }, {
30638
30782
  cancellationSignal: signal
30639
30783
  }),
30640
30784
  "ACP agent exited while listing sessions",
@@ -30659,7 +30803,7 @@ var AcpProcessSession = class _AcpProcessSession {
30659
30803
  );
30660
30804
  }
30661
30805
  await this.race(
30662
- this.#endpoint.connection.agent.request(
30806
+ this.#connection.connection.agent.request(
30663
30807
  methods3.agent.session.delete,
30664
30808
  { sessionId: nativeSessionIdSchema.parse(nativeSessionId) },
30665
30809
  { cancellationSignal: signal }
@@ -30668,9 +30812,9 @@ var AcpProcessSession = class _AcpProcessSession {
30668
30812
  signal
30669
30813
  );
30670
30814
  };
30671
- nativeSessionId = () => this.#nativeSessionId;
30815
+ nativeSessionId = () => this.#updates.sessionId();
30672
30816
  adoptNativeSessionId = (sessionId) => {
30673
- if (this.#prompted || this.#nativeSessionId !== sessionId) {
30817
+ if (this.#prompted || this.#updates.sessionId() !== sessionId) {
30674
30818
  throw new AcpExecutionError("The new native Session cannot be adopted", {}, "session_identity_mismatch");
30675
30819
  }
30676
30820
  const previousSessionId = this.#mobiusSessionId;
@@ -30718,10 +30862,10 @@ var AcpProcessSession = class _AcpProcessSession {
30718
30862
  const configured = await this.#sessionConfigProtocol.configure(
30719
30863
  this.#configOptions,
30720
30864
  options,
30721
- this.#nativeSessionId,
30865
+ this.#updates.sessionId(),
30722
30866
  {
30723
30867
  request: async (method, params, failureMessage, signal) => await this.race(
30724
- this.#endpoint.connection.agent.request(method, params, {
30868
+ this.#connection.connection.agent.request(method, params, {
30725
30869
  cancellationSignal: signal
30726
30870
  }),
30727
30871
  failureMessage,
@@ -30737,7 +30881,7 @@ var AcpProcessSession = class _AcpProcessSession {
30737
30881
  "invalid_session_configuration"
30738
30882
  );
30739
30883
  }
30740
- await this.#updateTail;
30884
+ await this.#updates.drained();
30741
30885
  if (this.#configRevision === configRevision) {
30742
30886
  this.#configOptions = configured;
30743
30887
  }
@@ -30802,7 +30946,7 @@ var AcpProcessSession = class _AcpProcessSession {
30802
30946
  };
30803
30947
  nativeHistoryTurn = () => {
30804
30948
  const prompt = this.#nativePrompt;
30805
- const nativeTurnId = this.#endpoint.inProcessAgent?.nativeTurnId?.() ?? null;
30949
+ const nativeTurnId = this.#connection.inProcessAgent?.nativeTurnId?.() ?? null;
30806
30950
  return prompt === null || nativeTurnId === null || nativeTurnId === prompt.previousTurnId ? null : { commandId: prompt.commandId, nativeTurnId };
30807
30951
  };
30808
30952
  prompt = async (options) => {
@@ -30817,7 +30961,7 @@ var AcpProcessSession = class _AcpProcessSession {
30817
30961
  new AcpStoredSession(
30818
30962
  this.#mobiusSessionId,
30819
30963
  this.#agentId,
30820
- this.#nativeSessionId,
30964
+ this.#updates.sessionId(),
30821
30965
  this.#cwd,
30822
30966
  this.#additionalDirectories,
30823
30967
  true,
@@ -30835,19 +30979,19 @@ var AcpProcessSession = class _AcpProcessSession {
30835
30979
  this.#turn = running;
30836
30980
  this.#nativePrompt = {
30837
30981
  commandId: options.commandId,
30838
- previousTurnId: this.#endpoint.inProcessAgent?.nativeTurnId?.() ?? null
30982
+ previousTurnId: this.#connection.inProcessAgent?.nativeTurnId?.() ?? null
30839
30983
  };
30840
30984
  try {
30841
30985
  const response = await this.race(
30842
- this.#endpoint.connection.agent.request(
30986
+ this.#connection.connection.agent.request(
30843
30987
  methods3.agent.session.prompt,
30844
- { prompt, sessionId: this.#nativeSessionId },
30988
+ { prompt, sessionId: this.#updates.sessionId() },
30845
30989
  { cancellationSignal: options.signal }
30846
30990
  ),
30847
30991
  "ACP agent exited during a prompt",
30848
30992
  options.signal
30849
30993
  );
30850
- await this.#updateTail;
30994
+ await this.#updates.drained();
30851
30995
  await this.flushAgentText();
30852
30996
  await running.activities.finish();
30853
30997
  let result;
@@ -30897,10 +31041,10 @@ var AcpProcessSession = class _AcpProcessSession {
30897
31041
  }
30898
31042
  const prompt = this.buildPrompt(options);
30899
31043
  const response = await this.race(
30900
- this.#endpoint.connection.agent.request("_session/steering", {
31044
+ this.#connection.connection.agent.request("_session/steering", {
30901
31045
  _meta: { steering: { idleBehavior: "promptRequired" } },
30902
31046
  prompt,
30903
- sessionId: this.#nativeSessionId
31047
+ sessionId: this.#updates.sessionId()
30904
31048
  }),
30905
31049
  "ACP agent exited during steering",
30906
31050
  options.signal
@@ -30933,12 +31077,12 @@ var AcpProcessSession = class _AcpProcessSession {
30933
31077
  );
30934
31078
  };
30935
31079
  cancel = async () => {
30936
- const capturedProcesses = await this.#endpoint.captureProcessTree();
31080
+ const capturedProcesses = await this.#connection.captureProcessTree();
30937
31081
  try {
30938
31082
  await this.#interactions.cancelPendingInteractions();
30939
31083
  if (this.#turn.running) {
30940
- await this.#endpoint.connection.agent.notify(methods3.agent.session.cancel, {
30941
- sessionId: this.#nativeSessionId
31084
+ await this.#connection.connection.agent.notify(methods3.agent.session.cancel, {
31085
+ sessionId: this.#updates.sessionId()
30942
31086
  });
30943
31087
  }
30944
31088
  } finally {
@@ -30950,45 +31094,9 @@ var AcpProcessSession = class _AcpProcessSession {
30950
31094
  onPermission = (request, signal) => this.#interactions.onPermission(request, signal);
30951
31095
  onElicitation = (request, signal) => this.#interactions.onElicitation(request, signal);
30952
31096
  onElicitationComplete = (notification) => this.#interactions.onElicitationComplete(notification);
30953
- onUpdate = (notification) => {
30954
- if (this.#nativeSessionId.length === 0) {
30955
- const notificationBytes = Buffer.byteLength(JSON.stringify(notification));
30956
- if (this.#preSessionUpdates.length >= MAX_PRE_SESSION_UPDATES || this.#preSessionUpdateBytes + notificationBytes > MAX_PRE_SESSION_UPDATE_BYTES) {
30957
- return Promise.reject(
30958
- new AcpExecutionError(
30959
- "ACP agent sent too many updates before creating its session",
30960
- {},
30961
- "agent_update_limit"
30962
- )
30963
- );
30964
- }
30965
- this.#preSessionUpdates.push(notification);
30966
- this.#preSessionUpdateBytes += notificationBytes;
30967
- return Promise.resolve();
30968
- }
30969
- return this.enqueueUpdate(notification);
30970
- };
30971
- enqueueUpdate = (notification) => {
30972
- this.#updateTail = this.#updateTail.then(async () => await this.processUpdate(notification));
30973
- return this.#updateTail;
30974
- };
30975
- selectNativeSession = (sessionId) => {
30976
- const selected = nativeSessionIdSchema.parse(sessionId);
30977
- if (this.#nativeSessionId.length > 0 && this.#nativeSessionId !== selected) {
30978
- throw new AcpExecutionError(
30979
- "ACP agent attempted to replace the selected session",
30980
- {},
30981
- "invalid_agent_session"
30982
- );
30983
- }
30984
- this.#nativeSessionId = selected;
30985
- const pending = this.#preSessionUpdates.splice(0);
30986
- this.#preSessionUpdateBytes = 0;
30987
- for (const notification of pending) {
30988
- void this.enqueueUpdate(notification);
30989
- }
30990
- };
30991
- processUpdate = async (notification) => {
31097
+ onUpdate = (notification) => this.#updates.receive(notification);
31098
+ selectNativeSession = (sessionId) => this.#updates.select(sessionId);
31099
+ #processUpdate = async (notification) => {
30992
31100
  this.assertNativeSession(notification.sessionId);
30993
31101
  const update = notification.update;
30994
31102
  if (this.#replay.kind === "capture") {
@@ -31058,7 +31166,7 @@ var AcpProcessSession = class _AcpProcessSession {
31058
31166
  })).filter((command) => command.name.length > 0);
31059
31167
  this.#commands = commands;
31060
31168
  await this.#getObserver().onCommands({
31061
- commands,
31169
+ commands: this.#commands,
31062
31170
  kind: SESSION_COMMANDS_UPDATED_KIND,
31063
31171
  sessionId: this.#mobiusSessionId
31064
31172
  });
@@ -31088,12 +31196,12 @@ var AcpProcessSession = class _AcpProcessSession {
31088
31196
  if (Object.hasOwn(update, "updatedAt")) {
31089
31197
  this.#sessionUpdatedAt = truncate2(update.updatedAt ?? "", 128);
31090
31198
  }
31091
- if (this.#nativeSessionId.length > 0) {
31199
+ if (this.#updates.sessionId().length > 0) {
31092
31200
  this.#store.write(
31093
31201
  new AcpStoredSession(
31094
31202
  this.#mobiusSessionId,
31095
31203
  this.#agentId,
31096
- this.#nativeSessionId,
31204
+ this.#updates.sessionId(),
31097
31205
  this.#cwd,
31098
31206
  this.#additionalDirectories,
31099
31207
  this.#prompted,
@@ -31125,11 +31233,11 @@ var AcpProcessSession = class _AcpProcessSession {
31125
31233
  close = async () => {
31126
31234
  try {
31127
31235
  await this.#interactions.cancelPendingInteractions();
31128
- if (this.#capabilities.closeSession && this.#nativeSessionId.length > 0) {
31236
+ if (this.#capabilities.closeSession && this.#updates.sessionId().length > 0) {
31129
31237
  try {
31130
- await this.#endpoint.connection.agent.request(
31238
+ await this.#connection.connection.agent.request(
31131
31239
  methods3.agent.session.close,
31132
- { sessionId: this.#nativeSessionId },
31240
+ { sessionId: this.#updates.sessionId() },
31133
31241
  {
31134
31242
  cancellationSignal: AbortSignal.timeout(PROCESS_STOP_TIMEOUT_MILLISECONDS)
31135
31243
  }
@@ -31141,10 +31249,10 @@ var AcpProcessSession = class _AcpProcessSession {
31141
31249
  await this.closeProcess();
31142
31250
  }
31143
31251
  };
31144
- closeProcess = (capturedProcesses = []) => this.#endpoint.closeProcess(capturedProcesses);
31145
- race = (operation, exitMessage, signal) => this.#endpoint.race(operation, exitMessage, signal);
31252
+ closeProcess = (capturedProcesses = []) => this.#connection.closeProcess(capturedProcesses);
31253
+ race = (operation, exitMessage, signal) => this.#connection.race(operation, exitMessage, signal);
31146
31254
  assertNativeSession = (sessionId) => {
31147
- if (sessionId !== this.#nativeSessionId) {
31255
+ if (sessionId !== this.#updates.sessionId()) {
31148
31256
  throw new AcpExecutionError("ACP agent referenced an unknown session", {}, "invalid_agent_session");
31149
31257
  }
31150
31258
  };
@@ -31158,8 +31266,8 @@ var AcpProcessSession = class _AcpProcessSession {
31158
31266
  };
31159
31267
  };
31160
31268
 
31161
- // src/acp/retained-sessions.ts
31162
- var RetainedSessions = class {
31269
+ // src/acp/retained-agent-processes.ts
31270
+ var RetainedAgentProcesses = class {
31163
31271
  #entries = /* @__PURE__ */ new Map();
31164
31272
  #events;
31165
31273
  constructor(events) {
@@ -31262,18 +31370,21 @@ var RetainedSessions = class {
31262
31370
  };
31263
31371
  };
31264
31372
 
31265
- // src/acp/native-session-browsers.ts
31266
- var NativeSessionBrowsers = class {
31267
- #sessions;
31373
+ // src/acp/agent-query-processes.ts
31374
+ var AgentQueryProcesses = class {
31375
+ #processesByQuery;
31268
31376
  #processes;
31269
31377
  #observer = new NullAcpSessionObserver();
31270
31378
  #store = new MemoryAcpSessionStore();
31271
31379
  constructor(processes) {
31272
31380
  this.#processes = processes;
31273
- this.#sessions = new RetainedSessions({ touch: processes.touch, changed: processes.notifyChanged });
31381
+ this.#processesByQuery = new RetainedAgentProcesses({
31382
+ touch: processes.touch,
31383
+ changed: processes.notifyChanged
31384
+ });
31274
31385
  }
31275
31386
  retire = async (sessionId, runtime) => {
31276
- const retained = this.#sessions.detach(sessionId, runtime);
31387
+ const retained = this.#processesByQuery.detach(sessionId, runtime);
31277
31388
  if (retained) {
31278
31389
  this.#store.remove(sessionId);
31279
31390
  }
@@ -31282,40 +31393,40 @@ var NativeSessionBrowsers = class {
31282
31393
  async #startRetained(options) {
31283
31394
  const runtime = await this.#processes.startRetained(
31284
31395
  options.signal,
31285
- () => AcpProcessSession.startNativeSessionBrowser(options, () => this.#observer, this.#store),
31396
+ () => AgentSession.startNativeSessionBrowser(options, () => this.#observer, this.#store),
31286
31397
  {
31287
- isBusy: () => this.#sessions.isBusy(options.sessionId),
31398
+ isBusy: () => this.#processesByQuery.isBusy(options.sessionId),
31288
31399
  retire: (runtime2) => this.retire(options.sessionId, runtime2)
31289
31400
  }
31290
31401
  );
31291
- this.#sessions.retain(options.sessionId, runtime);
31402
+ this.#processesByQuery.retain(options.sessionId, runtime);
31292
31403
  return runtime;
31293
31404
  }
31294
31405
  async #startPreparation(options) {
31295
- return await this.#sessions.prepare(options.sessionId, async () => {
31406
+ return await this.#processesByQuery.prepare(options.sessionId, async () => {
31296
31407
  return await this.#startRetained(options);
31297
31408
  });
31298
31409
  }
31299
31410
  async #replacePreparation(existing, options) {
31300
- return await this.#sessions.prepare(options.sessionId, async () => {
31411
+ return await this.#processesByQuery.prepare(options.sessionId, async () => {
31301
31412
  await this.retire(options.sessionId, existing);
31302
31413
  return await this.#startRetained(options);
31303
31414
  });
31304
31415
  }
31305
31416
  prepare = async (options) => {
31306
- const pending = this.#sessions.pending(options.sessionId);
31417
+ const pending = this.#processesByQuery.pending(options.sessionId);
31307
31418
  if (pending !== void 0) {
31308
31419
  const runtime2 = await pending;
31309
31420
  if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
31310
- this.#sessions.touch(options.sessionId, runtime2);
31421
+ this.#processesByQuery.touch(options.sessionId, runtime2);
31311
31422
  return runtime2.prepared();
31312
31423
  }
31313
31424
  return await this.prepare(options);
31314
31425
  }
31315
- const existing = this.#sessions.get(options.sessionId);
31426
+ const existing = this.#processesByQuery.get(options.sessionId);
31316
31427
  if (existing !== void 0) {
31317
31428
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
31318
- this.#sessions.touch(options.sessionId, existing);
31429
+ this.#processesByQuery.touch(options.sessionId, existing);
31319
31430
  return existing.prepared();
31320
31431
  }
31321
31432
  if (!existing.canRebind()) {
@@ -31332,7 +31443,7 @@ var NativeSessionBrowsers = class {
31332
31443
  return runtime.prepared();
31333
31444
  };
31334
31445
  async #ensure(options) {
31335
- const existing = this.#sessions.get(options.sessionId);
31446
+ const existing = this.#processesByQuery.get(options.sessionId);
31336
31447
  if (existing !== void 0) {
31337
31448
  if (!existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
31338
31449
  throw new AcpExecutionError(
@@ -31341,21 +31452,21 @@ var NativeSessionBrowsers = class {
31341
31452
  "session_identity_mismatch"
31342
31453
  );
31343
31454
  }
31344
- this.#sessions.touch(options.sessionId, existing);
31455
+ this.#processesByQuery.touch(options.sessionId, existing);
31345
31456
  return existing;
31346
31457
  }
31347
31458
  await this.prepare(options);
31348
- const started = this.#sessions.get(options.sessionId);
31459
+ const started = this.#processesByQuery.get(options.sessionId);
31349
31460
  if (started === void 0) {
31350
31461
  throw new AcpExecutionError("ACP native session browser did not start");
31351
31462
  }
31352
31463
  return started;
31353
31464
  }
31354
- use = async (options, operation) => await this.#sessions.use(options.sessionId, async () => await operation(await this.#ensure(options)));
31465
+ use = async (options, operation) => await this.#processesByQuery.use(options.sessionId, async () => await operation(await this.#ensure(options)));
31355
31466
  preview = async (options, nativeSessionId) => {
31356
31467
  return await this.#processes.runTransient(
31357
31468
  options.signal,
31358
- async () => await AcpProcessSession.startNativeSessionBrowser(
31469
+ async () => await AgentSession.startNativeSessionBrowser(
31359
31470
  options,
31360
31471
  () => this.#observer,
31361
31472
  new MemoryAcpSessionStore()
@@ -31368,88 +31479,9 @@ var NativeSessionBrowsers = class {
31368
31479
  );
31369
31480
  };
31370
31481
  close = async () => {
31371
- await Promise.all(this.#sessions.entries().map(async ([id, runtime]) => await this.retire(id, runtime)));
31372
- };
31373
- };
31374
-
31375
- // src/acp/session-executions.ts
31376
- var unreachable = (state) => {
31377
- throw new AcpExecutionError("Unexpected execution state", { cause: state });
31378
- };
31379
- var SessionExecutions = class {
31380
- #entries = /* @__PURE__ */ new Map();
31381
- command = (id) => {
31382
- const state = this.#entries.get(id);
31383
- switch (state?.kind) {
31384
- case "running":
31385
- case "cancelling":
31386
- return state.commandId;
31387
- case "cancelled-before-start":
31388
- case void 0:
31389
- return void 0;
31390
- default:
31391
- return unreachable(state);
31392
- }
31393
- };
31394
- cancellation = (id) => {
31395
- const state = this.#entries.get(id);
31396
- switch (state?.kind) {
31397
- case "cancelling":
31398
- case "cancelled-before-start":
31399
- return state.completion;
31400
- case "running":
31401
- case void 0:
31402
- return void 0;
31403
- default:
31404
- return unreachable(state);
31405
- }
31406
- };
31407
- isBusy = (id) => this.#entries.has(id);
31408
- begin = (id, commandId) => {
31409
- const state = this.#entries.get(id);
31410
- switch (state?.kind) {
31411
- case "running":
31412
- case "cancelling":
31413
- throw new AcpExecutionError(
31414
- "Another prompt is already running in this conversation",
31415
- {},
31416
- "session_busy"
31417
- );
31418
- case "cancelled-before-start":
31419
- case void 0:
31420
- break;
31421
- default:
31422
- unreachable(state);
31423
- }
31424
- this.#entries.set(
31425
- id,
31426
- state?.kind === "cancelled-before-start" ? { kind: "cancelling", commandId, completion: state.completion } : { kind: "running", commandId }
31427
- );
31428
- };
31429
- cancel = (id, stop) => {
31430
- const state = this.#entries.get(id);
31431
- switch (state?.kind) {
31432
- case "cancelling":
31433
- case "cancelled-before-start":
31434
- return state.completion;
31435
- case "running":
31436
- case void 0:
31437
- break;
31438
- default:
31439
- return unreachable(state);
31440
- }
31441
- const completion = Promise.withResolvers();
31442
- this.#entries.set(
31443
- id,
31444
- state?.kind === "running" ? { kind: "cancelling", commandId: state.commandId, completion: completion.promise } : { kind: "cancelled-before-start", completion: completion.promise }
31482
+ await Promise.all(
31483
+ this.#processesByQuery.entries().map(async ([id, runtime]) => await this.retire(id, runtime))
31445
31484
  );
31446
- void (async () => await stop())().then(completion.resolve, completion.reject);
31447
- return completion.promise;
31448
- };
31449
- finish = (id, commandId) => {
31450
- if (this.command(id) === commandId) {
31451
- this.#entries.delete(id);
31452
- }
31453
31485
  };
31454
31486
  };
31455
31487
 
@@ -31554,9 +31586,9 @@ async function waitForAcpProcessCapacity(completion, signal) {
31554
31586
  }
31555
31587
  }
31556
31588
 
31557
- // src/acp/process-pool.ts
31589
+ // src/acp/agent-process-pool.ts
31558
31590
  var MAX_ACP_PROCESSES = 10;
31559
- var AcpProcessPool = class {
31591
+ var AgentProcessPool = class {
31560
31592
  #slots = /* @__PURE__ */ new Map();
31561
31593
  #lock = new AcpProcessCapacityLock();
31562
31594
  #changed = Promise.withResolvers();
@@ -31660,13 +31692,16 @@ var AcpProcessPool = class {
31660
31692
  };
31661
31693
  };
31662
31694
 
31663
- // src/acp/session-manager.ts
31695
+ // src/acp/agent-runtime-manager.ts
31664
31696
  var SESSION_CONTROL_TIMEOUT_MILLISECONDS = 3e4;
31665
- var AcpSessionManager = class {
31666
- #processes = new AcpProcessPool();
31667
- #sessions = new RetainedSessions({ touch: this.#processes.touch, changed: this.#processes.notifyChanged });
31668
- #browsers = new NativeSessionBrowsers(this.#processes);
31669
- #executions = new SessionExecutions();
31697
+ var AgentRuntimeManager = class {
31698
+ #processes = new AgentProcessPool();
31699
+ #executionProcesses = new RetainedAgentProcesses({
31700
+ touch: this.#processes.touch,
31701
+ changed: this.#processes.notifyChanged
31702
+ });
31703
+ #queryProcesses = new AgentQueryProcesses(this.#processes);
31704
+ #executions = new ActiveExecutions();
31670
31705
  #agentSettingsObserver = new NullAcpSessionObserver();
31671
31706
  #nativeOperations = /* @__PURE__ */ new Set();
31672
31707
  #store;
@@ -31688,12 +31723,12 @@ var AcpSessionManager = class {
31688
31723
  }
31689
31724
  #retention(sessionId) {
31690
31725
  return {
31691
- isBusy: () => this.#executions.isBusy(sessionId) || this.#sessions.isBusy(sessionId) || this.#isNativeSessionOperationActive(sessionId),
31726
+ isBusy: () => this.#executions.isBusy(sessionId) || this.#executionProcesses.isBusy(sessionId) || this.#isNativeSessionOperationActive(sessionId),
31692
31727
  retire: (runtime) => this.#retireSessionProcess(sessionId, runtime, () => runtime.close())
31693
31728
  };
31694
31729
  }
31695
31730
  async #retireSessionProcess(sessionId, runtime, close) {
31696
- const retained = this.#sessions.detach(sessionId, runtime);
31731
+ const retained = this.#executionProcesses.detach(sessionId, runtime);
31697
31732
  try {
31698
31733
  await this.#processes.retire(runtime, close);
31699
31734
  } finally {
@@ -31707,14 +31742,14 @@ var AcpSessionManager = class {
31707
31742
  }
31708
31743
  async #startRetainedSessionProcess(options, start) {
31709
31744
  const runtime = await this.#processes.startRetained(options.signal, start, this.#retention(options.sessionId));
31710
- this.#sessions.retain(options.sessionId, runtime);
31745
+ this.#executionProcesses.retain(options.sessionId, runtime);
31711
31746
  return runtime;
31712
31747
  }
31713
31748
  async #startPreparation(options, metrics = unmeasuredOperationMetrics) {
31714
- return await this.#sessions.prepare(options.sessionId, async () => {
31749
+ return await this.#executionProcesses.prepare(options.sessionId, async () => {
31715
31750
  return await this.#startRetainedSessionProcess(
31716
31751
  options,
31717
- async () => await AcpProcessSession.start(
31752
+ async () => await AgentSession.start(
31718
31753
  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,
31719
31754
  () => this.#observer,
31720
31755
  this.#store,
@@ -31724,7 +31759,7 @@ var AcpSessionManager = class {
31724
31759
  });
31725
31760
  }
31726
31761
  async #replacePreparation(existing, options, metrics) {
31727
- return await this.#sessions.prepare(options.sessionId, async () => {
31762
+ return await this.#executionProcesses.prepare(options.sessionId, async () => {
31728
31763
  await this.#retireSessionProcess(
31729
31764
  options.sessionId,
31730
31765
  existing,
@@ -31733,17 +31768,17 @@ var AcpSessionManager = class {
31733
31768
  this.#store.remove(options.sessionId);
31734
31769
  return await this.#startRetainedSessionProcess(
31735
31770
  options,
31736
- async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
31771
+ async () => await AgentSession.start(options, () => this.#observer, this.#store, metrics)
31737
31772
  );
31738
31773
  });
31739
31774
  }
31740
31775
  async #replaceExecutionPreparation(existing, options) {
31741
31776
  const desiredConfigOptions = existing.prepared().configOptions;
31742
- return await this.#sessions.prepare(options.sessionId, async () => {
31777
+ return await this.#executionProcesses.prepare(options.sessionId, async () => {
31743
31778
  await this.#retireSessionProcess(options.sessionId, existing, async () => await existing.close());
31744
31779
  const runtime = await this.#startRetainedSessionProcess(
31745
31780
  options,
31746
- async () => await AcpProcessSession.start(options, () => this.#observer, this.#store)
31781
+ async () => await AgentSession.start(options, () => this.#observer, this.#store)
31747
31782
  );
31748
31783
  try {
31749
31784
  for (const desired of desiredConfigOptions) {
@@ -31794,19 +31829,19 @@ var AcpSessionManager = class {
31794
31829
  if (stored instanceof FoundAcpStoredSession && this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`)) {
31795
31830
  throw new AcpExecutionError("The native session is being managed", {}, "session_busy");
31796
31831
  }
31797
- const pending = this.#sessions.pending(options.sessionId);
31832
+ const pending = this.#executionProcesses.pending(options.sessionId);
31798
31833
  if (pending !== void 0) {
31799
31834
  const runtime2 = await metrics.measure("session-preparation-wait", async () => await pending);
31800
31835
  if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
31801
- this.#sessions.touch(options.sessionId, runtime2);
31836
+ this.#executionProcesses.touch(options.sessionId, runtime2);
31802
31837
  return runtime2.prepared();
31803
31838
  }
31804
31839
  return await this.prepareSession(options, metrics);
31805
31840
  }
31806
- const existing = this.#sessions.get(options.sessionId);
31841
+ const existing = this.#executionProcesses.get(options.sessionId);
31807
31842
  if (existing !== void 0) {
31808
31843
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
31809
- this.#sessions.touch(options.sessionId, existing);
31844
+ this.#executionProcesses.touch(options.sessionId, existing);
31810
31845
  return existing.prepared();
31811
31846
  }
31812
31847
  if (!existing.canRebind()) {
@@ -31829,7 +31864,7 @@ var AcpSessionManager = class {
31829
31864
  */
31830
31865
  inspectAgentSettings = async (options) => await this.#processes.runTransient(
31831
31866
  options.signal,
31832
- async () => await AcpProcessSession.start(
31867
+ async () => await AgentSession.start(
31833
31868
  {
31834
31869
  ...options,
31835
31870
  sessionId: `agent-settings-${crypto.randomUUID()}`
@@ -31860,10 +31895,10 @@ var AcpSessionManager = class {
31860
31895
  * Use inspectAgentSettings for Agent-scoped settings discovery.
31861
31896
  */
31862
31897
  inspectSession = async (options, metrics = unmeasuredOperationMetrics) => {
31863
- if (this.#sessions.pending(options.sessionId) !== void 0 || this.#sessions.get(options.sessionId) !== void 0) {
31898
+ if (this.#executionProcesses.pending(options.sessionId) !== void 0 || this.#executionProcesses.get(options.sessionId) !== void 0) {
31864
31899
  throw new AcpExecutionError("The configuration inspection session is already in use", {}, "session_busy");
31865
31900
  }
31866
- return await this.#sessions.use(options.sessionId, async () => {
31901
+ return await this.#executionProcesses.use(options.sessionId, async () => {
31867
31902
  const runtime = await this.#startPreparation(options, metrics);
31868
31903
  try {
31869
31904
  return runtime.prepared();
@@ -31877,12 +31912,12 @@ var AcpSessionManager = class {
31877
31912
  });
31878
31913
  };
31879
31914
  prepareExecutionSession = async (options) => {
31880
- const pending = this.#sessions.pending(options.sessionId);
31915
+ const pending = this.#executionProcesses.pending(options.sessionId);
31881
31916
  if (pending !== void 0) {
31882
31917
  await pending;
31883
31918
  return await this.prepareExecutionSession(options);
31884
31919
  }
31885
- const existing = this.#sessions.get(options.sessionId);
31920
+ const existing = this.#executionProcesses.get(options.sessionId);
31886
31921
  if (existing === void 0) {
31887
31922
  return (await this.#startPreparation(options)).prepared();
31888
31923
  }
@@ -31894,7 +31929,7 @@ var AcpSessionManager = class {
31894
31929
  );
31895
31930
  }
31896
31931
  if (existing.usesEnvironment(options.agent.environment)) {
31897
- this.#sessions.touch(options.sessionId, existing);
31932
+ this.#executionProcesses.touch(options.sessionId, existing);
31898
31933
  return existing.prepared();
31899
31934
  }
31900
31935
  if (existing.hasRunningTurn()) {
@@ -31906,21 +31941,21 @@ var AcpSessionManager = class {
31906
31941
  }
31907
31942
  return (await this.#replaceExecutionPreparation(existing, options)).prepared();
31908
31943
  };
31909
- prepareNativeSessionBrowser = (options) => this.#browsers.prepare(options);
31944
+ prepareNativeSessionBrowser = (options) => this.#queryProcesses.prepare(options);
31910
31945
  configureSession = async (options) => {
31911
- return await this.#sessions.use(options.sessionId, async () => {
31946
+ return await this.#executionProcesses.use(options.sessionId, async () => {
31912
31947
  const runtime = await this.ensureSession(options);
31913
31948
  return await runtime.configure(options);
31914
31949
  });
31915
31950
  };
31916
31951
  cancelPrompt = async (sessionId) => {
31917
31952
  await this.#executions.cancel(sessionId, async () => {
31918
- const runtime = this.#sessions.get(sessionId);
31953
+ const runtime = this.#executionProcesses.get(sessionId);
31919
31954
  if (runtime !== void 0) {
31920
31955
  try {
31921
31956
  await runtime.cancel();
31922
31957
  } finally {
31923
- if (this.#sessions.detach(sessionId, runtime)) {
31958
+ if (this.#executionProcesses.detach(sessionId, runtime)) {
31924
31959
  this.#processes.releaseClosed(runtime);
31925
31960
  }
31926
31961
  }
@@ -31931,14 +31966,14 @@ var AcpSessionManager = class {
31931
31966
  if (this.#executions.command(options.sessionId) !== options.targetCommandId) {
31932
31967
  throw new AcpExecutionError("The target turn is no longer active", {}, "steering_target_unavailable");
31933
31968
  }
31934
- const pending = this.#sessions.pending(options.sessionId);
31969
+ const pending = this.#executionProcesses.pending(options.sessionId);
31935
31970
  if (pending !== void 0) {
31936
31971
  await pending;
31937
31972
  }
31938
31973
  if (this.#executions.command(options.sessionId) !== options.targetCommandId) {
31939
31974
  throw new AcpExecutionError("The target turn is no longer active", {}, "steering_target_unavailable");
31940
31975
  }
31941
- const runtime = this.#sessions.get(options.sessionId);
31976
+ const runtime = this.#executionProcesses.get(options.sessionId);
31942
31977
  if (runtime === void 0 || !runtime.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
31943
31978
  throw new AcpExecutionError(
31944
31979
  "The target turn execution context is unavailable",
@@ -31996,7 +32031,7 @@ var AcpSessionManager = class {
31996
32031
  throw error62;
31997
32032
  }
31998
32033
  } catch (error62) {
31999
- const failedRuntime = this.#sessions.get(options.sessionId);
32034
+ const failedRuntime = this.#executionProcesses.get(options.sessionId);
32000
32035
  if (failedRuntime !== void 0) {
32001
32036
  await this.#retireSessionProcess(
32002
32037
  options.sessionId,
@@ -32018,32 +32053,32 @@ var AcpSessionManager = class {
32018
32053
  await this.#executions.cancellation(options.sessionId);
32019
32054
  } finally {
32020
32055
  this.#executions.finish(options.sessionId, options.commandId);
32021
- this.#sessions.touch(options.sessionId);
32056
+ this.#executionProcesses.touch(options.sessionId);
32022
32057
  this.#processes.notifyChanged();
32023
32058
  }
32024
32059
  }
32025
32060
  };
32026
32061
  respondPermission = async (options) => {
32027
- const runtime = this.#sessions.get(options.sessionId);
32062
+ const runtime = this.#executionProcesses.get(options.sessionId);
32028
32063
  if (runtime === void 0) {
32029
32064
  throw new AcpExecutionError("The permission request session is unavailable", {}, "session_not_found");
32030
32065
  }
32031
32066
  await runtime.respondPermission(options);
32032
32067
  };
32033
32068
  respondElicitation = async (options) => {
32034
- const runtime = this.#sessions.get(options.sessionId);
32069
+ const runtime = this.#executionProcesses.get(options.sessionId);
32035
32070
  if (runtime === void 0) {
32036
32071
  throw new AcpExecutionError("The elicitation request session is unavailable", {}, "session_not_found");
32037
32072
  }
32038
32073
  await runtime.respondElicitation(options);
32039
32074
  };
32040
32075
  close = async () => {
32041
- const sessions = [...this.#sessions.entries()];
32076
+ const sessions = [...this.#executionProcesses.entries()];
32042
32077
  await Promise.all([
32043
32078
  ...sessions.map(
32044
32079
  async ([sessionId, runtime]) => await this.#retireSessionProcess(sessionId, runtime, async () => await runtime.close())
32045
32080
  ),
32046
- this.#browsers.close()
32081
+ this.#queryProcesses.close()
32047
32082
  ]);
32048
32083
  };
32049
32084
  findSessions = (sessionIds) => sessionIds.flatMap((sessionId) => {
@@ -32051,17 +32086,17 @@ var AcpSessionManager = class {
32051
32086
  return stored instanceof FoundAcpStoredSession ? [stored.session] : [];
32052
32087
  });
32053
32088
  findLinkedSessions = (agentId, nativeSessionId) => this.#store.findNative(agentId, nativeSessionId);
32054
- hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
32089
+ hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#executionProcesses.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
32055
32090
  createNativeSession = async (options) => {
32056
32091
  const temporarySessionId = `new-${crypto.randomUUID()}`;
32057
32092
  const temporaryOptions = { ...options, sessionId: temporarySessionId };
32058
- return await this.#sessions.use(temporarySessionId, async () => {
32093
+ return await this.#executionProcesses.use(temporarySessionId, async () => {
32059
32094
  try {
32060
32095
  const runtime = await this.#startPreparation(temporaryOptions);
32061
32096
  let adopted = false;
32062
32097
  try {
32063
32098
  const nativeSessionId = runtime.nativeSessionId();
32064
- if (!isNativeChatSessionId(options.agent.id, nativeSessionId) || this.#sessions.get(nativeSessionId) !== void 0 || !(this.#store.read(nativeSessionId) instanceof MissingAcpStoredSession)) {
32099
+ if (!isNativeChatSessionId(options.agent.id, nativeSessionId) || this.#executionProcesses.get(nativeSessionId) !== void 0 || !(this.#store.read(nativeSessionId) instanceof MissingAcpStoredSession)) {
32065
32100
  throw new AcpExecutionError(
32066
32101
  "The Agent returned an invalid new Session ID",
32067
32102
  {},
@@ -32069,8 +32104,8 @@ var AcpSessionManager = class {
32069
32104
  );
32070
32105
  }
32071
32106
  runtime.adoptNativeSessionId(nativeSessionId);
32072
- this.#sessions.detach(temporarySessionId, runtime);
32073
- this.#sessions.retain(nativeSessionId, runtime);
32107
+ this.#executionProcesses.detach(temporarySessionId, runtime);
32108
+ this.#executionProcesses.retain(nativeSessionId, runtime);
32074
32109
  this.#processes.retain(runtime, this.#retention(nativeSessionId));
32075
32110
  adopted = true;
32076
32111
  return nativeSessionId;
@@ -32089,7 +32124,7 @@ var AcpSessionManager = class {
32089
32124
  });
32090
32125
  };
32091
32126
  ensureSession = async (options) => {
32092
- const existing = this.#sessions.get(options.sessionId);
32127
+ const existing = this.#executionProcesses.get(options.sessionId);
32093
32128
  if (existing !== void 0) {
32094
32129
  if (!existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
32095
32130
  throw new AcpExecutionError(
@@ -32098,18 +32133,18 @@ var AcpSessionManager = class {
32098
32133
  "session_identity_mismatch"
32099
32134
  );
32100
32135
  }
32101
- this.#sessions.touch(options.sessionId, existing);
32136
+ this.#executionProcesses.touch(options.sessionId, existing);
32102
32137
  return existing;
32103
32138
  }
32104
32139
  await this.prepareSession(options);
32105
- const started = this.#sessions.get(options.sessionId);
32140
+ const started = this.#executionProcesses.get(options.sessionId);
32106
32141
  if (started === void 0) {
32107
32142
  throw new AcpExecutionError("ACP session did not start");
32108
32143
  }
32109
32144
  return started;
32110
32145
  };
32111
32146
  listNativeSessions = async (options, cursor) => {
32112
- return await this.#browsers.use(
32147
+ return await this.#queryProcesses.use(
32113
32148
  options,
32114
32149
  async (runtime) => await runtime.listNativeSessions(cursor, options.signal)
32115
32150
  );
@@ -32118,7 +32153,7 @@ var AcpSessionManager = class {
32118
32153
  const key = `${options.agent.id}:${nativeSessionId}`;
32119
32154
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
32120
32155
  if (this.#nativeOperations.has(key) || linked.some(
32121
- (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#sessions.pending(entry.sessionId) !== void 0
32156
+ (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#executionProcesses.pending(entry.sessionId) !== void 0
32122
32157
  )) {
32123
32158
  throw new AcpExecutionError(
32124
32159
  "Wait for the native session's running operation to finish",
@@ -32128,13 +32163,13 @@ var AcpSessionManager = class {
32128
32163
  }
32129
32164
  this.#nativeOperations.add(key);
32130
32165
  try {
32131
- return await this.#browsers.preview(options, nativeSessionId);
32166
+ return await this.#queryProcesses.preview(options, nativeSessionId);
32132
32167
  } finally {
32133
32168
  this.#nativeOperations.delete(key);
32134
32169
  }
32135
32170
  };
32136
32171
  loadSessionHistory = async (options) => {
32137
- return await this.#sessions.use(options.sessionId, async () => {
32172
+ return await this.#executionProcesses.use(options.sessionId, async () => {
32138
32173
  const runtime = await this.ensureSession(options);
32139
32174
  const stored = this.#store.read(options.sessionId);
32140
32175
  if (stored instanceof FoundAcpStoredSession && this.#nativeHistoryReader !== null) {
@@ -32157,7 +32192,7 @@ var AcpSessionManager = class {
32157
32192
  }
32158
32193
  const linked = this.#store.findNative(options.agent.id, origin.nativeSessionId);
32159
32194
  if (linked.some(
32160
- (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#sessions.pending(entry.sessionId) !== void 0
32195
+ (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#executionProcesses.pending(entry.sessionId) !== void 0
32161
32196
  )) {
32162
32197
  throw new AcpExecutionError(
32163
32198
  "Wait for the native session's running operation to finish",
@@ -32167,7 +32202,7 @@ var AcpSessionManager = class {
32167
32202
  }
32168
32203
  const existing = linked[0];
32169
32204
  if (origin.kind === "import" && existing !== void 0) {
32170
- return await this.#sessions.use(existing.sessionId, async () => {
32205
+ return await this.#executionProcesses.use(existing.sessionId, async () => {
32171
32206
  const runtime = await this.ensureSession({
32172
32207
  ...options,
32173
32208
  sessionId: existing.sessionId
@@ -32191,10 +32226,10 @@ var AcpSessionManager = class {
32191
32226
  }
32192
32227
  });
32193
32228
  }
32194
- 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) {
32229
+ 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) {
32195
32230
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
32196
32231
  }
32197
- return await this.#sessions.use(options.sessionId, async () => {
32232
+ return await this.#executionProcesses.use(options.sessionId, async () => {
32198
32233
  this.#nativeOperations.add(key);
32199
32234
  try {
32200
32235
  const runtime = await this.#startPreparation({ ...options, origin });
@@ -32211,7 +32246,7 @@ var AcpSessionManager = class {
32211
32246
  }
32212
32247
  } catch (error62) {
32213
32248
  this.#store.remove(options.sessionId);
32214
- const runtime = this.#sessions.get(options.sessionId);
32249
+ const runtime = this.#executionProcesses.get(options.sessionId);
32215
32250
  if (runtime !== void 0) {
32216
32251
  await this.#retireSessionProcess(
32217
32252
  options.sessionId,
@@ -32226,11 +32261,11 @@ var AcpSessionManager = class {
32226
32261
  });
32227
32262
  };
32228
32263
  deleteNativeSession = async (options, nativeSessionId) => {
32229
- return await this.#browsers.use(options, async (runtime) => {
32264
+ return await this.#queryProcesses.use(options, async (runtime) => {
32230
32265
  const key = `${options.agent.id}:${nativeSessionId}`;
32231
32266
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
32232
32267
  if (this.#nativeOperations.has(key) || linked.some(
32233
- (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#sessions.pending(entry.sessionId) !== void 0
32268
+ (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#executionProcesses.pending(entry.sessionId) !== void 0
32234
32269
  )) {
32235
32270
  throw new AcpExecutionError(
32236
32271
  "Wait for the native session's running operation to finish",
@@ -32241,7 +32276,7 @@ var AcpSessionManager = class {
32241
32276
  this.#nativeOperations.add(key);
32242
32277
  try {
32243
32278
  for (const entry of linked) {
32244
- const active = this.#sessions.get(entry.sessionId);
32279
+ const active = this.#executionProcesses.get(entry.sessionId);
32245
32280
  if (active !== void 0 && active !== runtime) {
32246
32281
  await this.#retireSessionProcess(entry.sessionId, active, async () => await active.close());
32247
32282
  }
@@ -32250,7 +32285,7 @@ var AcpSessionManager = class {
32250
32285
  await runtime.deleteNativeSession(nativeSessionId, options.signal);
32251
32286
  const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
32252
32287
  if (runtime.nativeSessionId() === nativeSessionId) {
32253
- await this.#browsers.retire(options.sessionId, runtime);
32288
+ await this.#queryProcesses.retire(options.sessionId, runtime);
32254
32289
  }
32255
32290
  return deleted;
32256
32291
  } finally {
@@ -32263,9 +32298,9 @@ var AcpSessionManager = class {
32263
32298
 
32264
32299
  // src/acp/run-prompt.ts
32265
32300
  async function runAcpPrompt(options) {
32266
- const sessions = new AcpSessionManager();
32301
+ const agentRuntime = new AgentRuntimeManager();
32267
32302
  try {
32268
- return await sessions.runPrompt({
32303
+ return await agentRuntime.runPrompt({
32269
32304
  additionalDirectories: [],
32270
32305
  agent: new LocalAgentDefinition("test-agent", "Test agent", options.agentCommand, options.agentArguments),
32271
32306
  cwd: options.cwd,
@@ -32280,7 +32315,7 @@ async function runAcpPrompt(options) {
32280
32315
  signal: options.signal
32281
32316
  });
32282
32317
  } finally {
32283
- await sessions.close();
32318
+ await agentRuntime.close();
32284
32319
  }
32285
32320
  }
32286
32321
 
@@ -33486,6 +33521,7 @@ var COLLABORATION_MODE_SETTING_ID = "collaboration_mode";
33486
33521
  var MODEL_CATALOG_LIMIT = 1e3;
33487
33522
  var FAST_TIER = "fast";
33488
33523
  var SERVICE_TIER_FAST = "priority";
33524
+ var CODEX_COMMANDS = Object.freeze([{ description: "Compact the conversation context", name: "compact" }]);
33489
33525
  var WORKSPACE_WRITE_POLICY = Object.freeze({
33490
33526
  excludeSlashTmp: false,
33491
33527
  excludeTmpdirEnvVar: false,
@@ -33566,6 +33602,9 @@ function promptInput(prompt) {
33566
33602
  }
33567
33603
  return input2;
33568
33604
  }
33605
+ function isCompactPrompt(prompt) {
33606
+ return prompt.length === 1 && prompt[0]?.type === "text" && prompt[0].text.trim() === "/compact";
33607
+ }
33569
33608
  function steeringPromptInput(prompt) {
33570
33609
  const input2 = [];
33571
33610
  for (const block of prompt) {
@@ -33820,6 +33859,7 @@ var CodexAcpAgent = class {
33820
33859
  };
33821
33860
  this.#collaborationModeSelected = false;
33822
33861
  await this.#probeCollaborationMode(context.signal);
33862
+ await this.#emitAvailableCommands();
33823
33863
  return { configOptions: this.#configOptions(), sessionId: created.thread.id };
33824
33864
  }).onRequest(methods4.agent.session.setConfigOption, async (context) => {
33825
33865
  this.#applySelection(context.params.configId, context.params.value);
@@ -33838,6 +33878,7 @@ var CodexAcpAgent = class {
33838
33878
  this.#selectRestoredThread(resumed);
33839
33879
  await this.#probeCollaborationMode(context.signal);
33840
33880
  await this.#replayHistory(resumed.turns);
33881
+ await this.#emitAvailableCommands();
33841
33882
  return { configOptions: this.#configOptions() };
33842
33883
  }).onRequest(methods4.agent.session.fork, async (context) => {
33843
33884
  const forked = threadForkResponseSchema.parse(
@@ -33854,6 +33895,7 @@ var CodexAcpAgent = class {
33854
33895
  this.#selectRestoredThread(forked);
33855
33896
  await this.#probeCollaborationMode(context.signal);
33856
33897
  await this.#replayHistory(forked.turns);
33898
+ await this.#emitAvailableCommands();
33857
33899
  return { configOptions: this.#configOptions(), sessionId: forked.thread.id };
33858
33900
  }).onRequest(methods4.agent.session.resume, async (context) => {
33859
33901
  const resumed = threadResumeResponseSchema.parse(
@@ -33865,8 +33907,12 @@ var CodexAcpAgent = class {
33865
33907
  );
33866
33908
  this.#selectRestoredThread(resumed);
33867
33909
  await this.#probeCollaborationMode(context.signal);
33910
+ await this.#emitAvailableCommands();
33868
33911
  return { configOptions: this.#configOptions() };
33869
33912
  }).onRequest(methods4.agent.session.prompt, async (context) => {
33913
+ if (isCompactPrompt(context.params.prompt)) {
33914
+ return await this.#compact(context.signal);
33915
+ }
33870
33916
  return await this.#runTurn(promptInput(context.params.prompt), context.signal);
33871
33917
  }).onRequest(
33872
33918
  "_session/steering",
@@ -34146,6 +34192,12 @@ var CodexAcpAgent = class {
34146
34192
  update
34147
34193
  });
34148
34194
  };
34195
+ #emitAvailableCommands = async () => {
34196
+ await this.#emit({
34197
+ availableCommands: CODEX_COMMANDS.map((command) => ({ ...command })),
34198
+ sessionUpdate: "available_commands_update"
34199
+ });
34200
+ };
34149
34201
  /** Pushes the current settings so a mode change Codex applied reaches the Run settings panel. */
34150
34202
  #emitConfigOptionsUpdate = async () => {
34151
34203
  const connection = this.#connection;
@@ -34456,6 +34508,35 @@ var CodexAcpAgent = class {
34456
34508
  }
34457
34509
  }
34458
34510
  };
34511
+ #compact = async (signal) => {
34512
+ signal.throwIfAborted();
34513
+ if (this.#turn !== null) {
34514
+ throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
34515
+ }
34516
+ const completion = Promise.withResolvers();
34517
+ void completion.promise.catch(() => {
34518
+ });
34519
+ const aborted2 = () => {
34520
+ completion.reject(signal.reason);
34521
+ void this.close().catch((cause) => {
34522
+ console.error("The cancelled Codex endpoint could not release its process tree", cause);
34523
+ });
34524
+ };
34525
+ signal.addEventListener("abort", aborted2, { once: true });
34526
+ const turn = { completion, turn: { id: "" } };
34527
+ this.#streamedReasoningItemIds.clear();
34528
+ this.#turn = turn;
34529
+ try {
34530
+ await this.#appServer.request("thread/compact/start", { threadId: this.#nativeSessionId }, signal);
34531
+ return await completion.promise;
34532
+ } finally {
34533
+ signal.removeEventListener("abort", aborted2);
34534
+ if (this.#turn === turn) {
34535
+ this.#turn = null;
34536
+ this.#streamedReasoningItemIds.clear();
34537
+ }
34538
+ }
34539
+ };
34459
34540
  #steerTurn = async (params, signal) => {
34460
34541
  if (typeof params !== "object" || params === null) {
34461
34542
  throw new AcpExecutionError("Codex received an invalid steering request", {}, "invalid_request");
@@ -42529,7 +42610,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
42529
42610
  activeTurns.recordEvent(event);
42530
42611
  publisher.publish(sessionId, event);
42531
42612
  };
42532
- const sessions = new AcpSessionManager(
42613
+ const agentRuntime = new AgentRuntimeManager(
42533
42614
  new DaemonAcpObserver(recordSessionEvent),
42534
42615
  sessionStore,
42535
42616
  {
@@ -42551,20 +42632,28 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
42551
42632
  config2.relayUrl,
42552
42633
  new DaemonDiagnosticLog(stateDirectory)
42553
42634
  );
42554
- const nativeSessions = new NativeSessionService(config2, directories, sessions, audit, async (request, options2) => {
42555
- return await activeTurns.executionSnapshot(async (command) => {
42556
- if (command.sessionId !== request.targetSessionId || command.agentId !== request.agentId) {
42557
- return false;
42558
- }
42559
- const cwd = await directories.resolve(command.bindingId, command.directoryId, options2.signal);
42560
- const additionalDirectories = await directories.resolveMany(
42561
- command.bindingId,
42562
- command.additionalDirectoryIds,
42563
- options2.signal
42564
- );
42565
- return cwd === options2.cwd && additionalDirectories.length === options2.additionalDirectories.length && additionalDirectories.every((directory, index) => directory === options2.additionalDirectories[index]);
42566
- });
42567
- });
42635
+ const nativeSessions = new NativeSessionService(
42636
+ config2,
42637
+ directories,
42638
+ agentRuntime,
42639
+ audit,
42640
+ async (request, options2) => {
42641
+ return await activeTurns.executionSnapshot(async (command) => {
42642
+ if (command.sessionId !== request.targetSessionId || command.agentId !== request.agentId) {
42643
+ return false;
42644
+ }
42645
+ const cwd = await directories.resolve(command.bindingId, command.directoryId, options2.signal);
42646
+ const additionalDirectories = await directories.resolveMany(
42647
+ command.bindingId,
42648
+ command.additionalDirectoryIds,
42649
+ options2.signal
42650
+ );
42651
+ return cwd === options2.cwd && additionalDirectories.length === options2.additionalDirectories.length && additionalDirectories.every(
42652
+ (directory, index) => directory === options2.additionalDirectories[index]
42653
+ );
42654
+ });
42655
+ }
42656
+ );
42568
42657
  const installations = new AgentInstallationManager(
42569
42658
  specifications,
42570
42659
  installationExecutor,
@@ -42640,7 +42729,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
42640
42729
  config: config2,
42641
42730
  directories,
42642
42731
  audit,
42643
- sessions,
42732
+ sessions: agentRuntime,
42644
42733
  installations,
42645
42734
  installationObserver,
42646
42735
  nativeSessions,
@@ -42683,7 +42772,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
42683
42772
  await installations.close();
42684
42773
  } finally {
42685
42774
  try {
42686
- await sessions.close();
42775
+ await agentRuntime.close();
42687
42776
  } finally {
42688
42777
  try {
42689
42778
  sessionStore.close();