@moxt-ai/mobius 0.0.358 → 0.0.360

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 (112) hide show
  1. package/dist/cli.js +943 -495
  2. package/dist/cli.js.map +4 -4
  3. package/dist/engine/acp/adapter/agent-initialization.d.ts +2 -2
  4. package/dist/engine/acp/adapter/agent-initialization.d.ts.map +1 -1
  5. package/dist/engine/acp/adapter/agent-initialization.js.map +1 -1
  6. package/dist/engine/acp/adapter/claude/adapter.d.ts +21 -4
  7. package/dist/engine/acp/adapter/claude/adapter.d.ts.map +1 -1
  8. package/dist/engine/acp/adapter/claude/adapter.js +52 -15
  9. package/dist/engine/acp/adapter/claude/adapter.js.map +1 -1
  10. package/dist/engine/acp/adapter/codex/adapter.d.ts +22 -5
  11. package/dist/engine/acp/adapter/codex/adapter.d.ts.map +1 -1
  12. package/dist/engine/acp/adapter/codex/adapter.js +70 -20
  13. package/dist/engine/acp/adapter/codex/adapter.js.map +1 -1
  14. package/dist/engine/acp/adapter/configuration-changes.d.ts +25 -0
  15. package/dist/engine/acp/adapter/configuration-changes.d.ts.map +1 -0
  16. package/dist/engine/acp/adapter/configuration-changes.js +47 -0
  17. package/dist/engine/acp/adapter/configuration-changes.js.map +1 -0
  18. package/dist/engine/acp/adapter/execution-connections.d.ts +26 -0
  19. package/dist/engine/acp/adapter/execution-connections.d.ts.map +1 -0
  20. package/dist/engine/acp/adapter/{live-sessions.js → execution-connections.js} +92 -24
  21. package/dist/engine/acp/adapter/execution-connections.js.map +1 -0
  22. package/dist/engine/acp/adapter/lifecycle-output.d.ts +10 -0
  23. package/dist/engine/acp/adapter/lifecycle-output.d.ts.map +1 -0
  24. package/dist/engine/acp/adapter/lifecycle-output.js +26 -0
  25. package/dist/engine/acp/adapter/lifecycle-output.js.map +1 -0
  26. package/dist/engine/acp/adapter/native-session-lookup.d.ts +2 -2
  27. package/dist/engine/acp/adapter/native-session-lookup.d.ts.map +1 -1
  28. package/dist/engine/acp/adapter/native-session-lookup.js +4 -4
  29. package/dist/engine/acp/adapter/native-session-lookup.js.map +1 -1
  30. package/dist/engine/acp/adapter/pi/adapter.d.ts +21 -4
  31. package/dist/engine/acp/adapter/pi/adapter.d.ts.map +1 -1
  32. package/dist/engine/acp/adapter/pi/adapter.js +52 -15
  33. package/dist/engine/acp/adapter/pi/adapter.js.map +1 -1
  34. package/dist/engine/acp/adapter/query-processes.d.ts +6 -5
  35. package/dist/engine/acp/adapter/query-processes.d.ts.map +1 -1
  36. package/dist/engine/acp/adapter/query-processes.js +36 -36
  37. package/dist/engine/acp/adapter/query-processes.js.map +1 -1
  38. package/dist/engine/acp/adapter/query-scope.d.ts +8 -0
  39. package/dist/engine/acp/adapter/query-scope.d.ts.map +1 -0
  40. package/dist/engine/acp/adapter/query-scope.js +16 -0
  41. package/dist/engine/acp/adapter/query-scope.js.map +1 -0
  42. package/dist/engine/acp/adapter/query-session.d.ts +3 -4
  43. package/dist/engine/acp/adapter/query-session.d.ts.map +1 -1
  44. package/dist/engine/acp/adapter/query-session.js +26 -31
  45. package/dist/engine/acp/adapter/query-session.js.map +1 -1
  46. package/dist/engine/acp/adapter/session-events.d.ts +34 -6
  47. package/dist/engine/acp/adapter/session-events.d.ts.map +1 -1
  48. package/dist/engine/acp/adapter/session-events.js +95 -3
  49. package/dist/engine/acp/adapter/session-events.js.map +1 -1
  50. package/dist/engine/acp/content/content-externalizer.d.ts +1 -0
  51. package/dist/engine/acp/content/content-externalizer.d.ts.map +1 -1
  52. package/dist/engine/acp/content/content-externalizer.js.map +1 -1
  53. package/dist/engine/acp/harness/codex/borrowed-agent.d.ts.map +1 -1
  54. package/dist/engine/acp/harness/codex/borrowed-agent.js +10 -3
  55. package/dist/engine/acp/harness/codex/borrowed-agent.js.map +1 -1
  56. package/dist/engine/acp/harness/codex/history.js +1 -1
  57. package/dist/engine/acp/harness/codex/history.js.map +1 -1
  58. package/dist/engine/acp/harness/codex/items.js +1 -1
  59. package/dist/engine/acp/harness/codex/owned-agent.d.ts.map +1 -1
  60. package/dist/engine/acp/harness/codex/owned-agent.js +3 -2
  61. package/dist/engine/acp/harness/codex/owned-agent.js.map +1 -1
  62. package/dist/engine/acp/native-history/preview-contract.d.ts +73 -16
  63. package/dist/engine/acp/native-history/preview-contract.d.ts.map +1 -1
  64. package/dist/engine/acp/protocol/session-config-protocol.d.ts +1 -0
  65. package/dist/engine/acp/protocol/session-config-protocol.d.ts.map +1 -1
  66. package/dist/engine/acp/protocol/session-config-protocol.js +1 -1
  67. package/dist/engine/acp/protocol/session-config-protocol.js.map +1 -1
  68. package/dist/engine/agent/runtime-agents.d.ts +4 -1
  69. package/dist/engine/agent/runtime-agents.d.ts.map +1 -1
  70. package/dist/engine/agent/runtime-agents.js +6 -4
  71. package/dist/engine/agent/runtime-agents.js.map +1 -1
  72. package/dist/engine/runtime/run.d.ts.map +1 -1
  73. package/dist/engine/runtime/run.js +6 -2
  74. package/dist/engine/runtime/run.js.map +1 -1
  75. package/dist/engine/session/api/session-api.d.ts +3 -0
  76. package/dist/engine/session/api/session-api.d.ts.map +1 -1
  77. package/dist/engine/session/api/session-api.js.map +1 -1
  78. package/dist/engine/session/live/agent-session-restore.d.ts +6 -16
  79. package/dist/engine/session/live/agent-session-restore.d.ts.map +1 -1
  80. package/dist/engine/session/live/agent-session.d.ts +7 -14
  81. package/dist/engine/session/live/agent-session.d.ts.map +1 -1
  82. package/dist/engine/session/live/agent-session.js +108 -87
  83. package/dist/engine/session/live/agent-session.js.map +1 -1
  84. package/dist/engine/session/live/session-restore.d.ts.map +1 -1
  85. package/dist/engine/session/live/session-restore.js +12 -35
  86. package/dist/engine/session/live/session-restore.js.map +1 -1
  87. package/dist/engine/session/manager/session-manager.d.ts.map +1 -1
  88. package/dist/engine/session/manager/session-manager.js +13 -5
  89. package/dist/engine/session/manager/session-manager.js.map +1 -1
  90. package/dist/engine/session/native/native-query.d.ts +5 -0
  91. package/dist/engine/session/native/native-query.d.ts.map +1 -0
  92. package/dist/engine/session/native/native-query.js +14 -0
  93. package/dist/engine/session/native/native-query.js.map +1 -0
  94. package/dist/engine/session/native/native-session-browser.d.ts.map +1 -1
  95. package/dist/engine/session/native/native-session-browser.js +27 -16
  96. package/dist/engine/session/native/native-session-browser.js.map +1 -1
  97. package/dist/engine/session/process/retained-agent-processes.d.ts +10 -10
  98. package/dist/engine/session/process/retained-agent-processes.d.ts.map +1 -1
  99. package/dist/engine/session/process/retained-agent-processes.js.map +1 -1
  100. package/dist/engine/session/prompt/execute-prompt.d.ts.map +1 -1
  101. package/dist/engine/session/prompt/execute-prompt.js +4 -1
  102. package/dist/engine/session/prompt/execute-prompt.js.map +1 -1
  103. package/dist/engine/util/branded-type.d.ts +4 -0
  104. package/dist/engine/util/branded-type.d.ts.map +1 -0
  105. package/dist/engine/util/branded-type.js +2 -0
  106. package/dist/engine/util/branded-type.js.map +1 -0
  107. package/dist/engine.js +882 -476
  108. package/dist/engine.js.map +4 -4
  109. package/package.json +2 -2
  110. package/dist/engine/acp/adapter/live-sessions.d.ts +0 -26
  111. package/dist/engine/acp/adapter/live-sessions.d.ts.map +0 -1
  112. package/dist/engine/acp/adapter/live-sessions.js.map +0 -1
package/dist/cli.js CHANGED
@@ -2086,7 +2086,7 @@ var init_package = __esm({
2086
2086
  "package.json"() {
2087
2087
  package_default = {
2088
2088
  name: "@moxt-ai/mobius",
2089
- version: "0.0.358",
2089
+ version: "0.0.360",
2090
2090
  description: "Mobius CLI for pairing and running local AI agent services.",
2091
2091
  type: "module",
2092
2092
  bin: {
@@ -75740,17 +75740,20 @@ var init_borrowed_agent = __esm({
75740
75740
  this.#seen.set(key, text2);
75741
75741
  continue;
75742
75742
  }
75743
+ if (item.type === "plan" && turn.status === "inProgress") {
75744
+ continue;
75745
+ }
75743
75746
  const previous = this.#seen.get(key);
75744
- const value = item.type === "agentMessage" ? item.text : reasoningText(item) ?? JSON.stringify(item);
75747
+ const value = item.type === "agentMessage" || item.type === "plan" ? item.text : reasoningText(item) ?? JSON.stringify(item);
75745
75748
  this.#seen.set(key, value);
75746
75749
  if (baseline || value === previous) {
75747
75750
  continue;
75748
75751
  }
75749
- if (item.type === "agentMessage" || reasoningText(item) !== null) {
75752
+ if (item.type === "agentMessage" || item.type === "plan" || reasoningText(item) !== null) {
75750
75753
  const text2 = previous !== void 0 && value.startsWith(previous) ? value.slice(previous.length) : value;
75751
75754
  if (text2.length > 0) {
75752
75755
  await this.#emit({
75753
- sessionUpdate: item.type === "agentMessage" ? "agent_message_chunk" : "agent_thought_chunk",
75756
+ sessionUpdate: item.type === "reasoning" ? "agent_thought_chunk" : "agent_message_chunk",
75754
75757
  messageId: item.id,
75755
75758
  content: { type: "text", text: text2 }
75756
75759
  });
@@ -76548,7 +76551,7 @@ var init_owned_agent = __esm({
76548
76551
  }
76549
76552
  return;
76550
76553
  }
76551
- if (item.type === "agentMessage") {
76554
+ if (item.type === "agentMessage" || item.type === "plan") {
76552
76555
  if (method === "item/started") {
76553
76556
  this.#agentMessages.set(item.id, "started");
76554
76557
  return;
@@ -76969,7 +76972,7 @@ async function replayCodexHistory(client2, threadId, emit, signal) {
76969
76972
  });
76970
76973
  }
76971
76974
  }
76972
- } else if (item.type === "agentMessage") {
76975
+ } else if (item.type === "agentMessage" || item.type === "plan") {
76973
76976
  await emit(agentMessageUpdate(item.id, item.text));
76974
76977
  } else if (item.type === "reasoning") {
76975
76978
  const text2 = reasoningText(item);
@@ -82884,6 +82887,29 @@ var init_run_cleanup = __esm({
82884
82887
  }
82885
82888
  });
82886
82889
 
82890
+ // src/engine/acp/protocol/native-session.ts
82891
+ var path7, title, nativeSessionIdSchema, nativeSessionInfoSchema, nativeSessionPageSchema;
82892
+ var init_native_session = __esm({
82893
+ "src/engine/acp/protocol/native-session.ts"() {
82894
+ "use strict";
82895
+ init_zod();
82896
+ path7 = external_exports.string().min(1).max(2048).refine((value) => !value.includes("\0"));
82897
+ title = external_exports.string().transform((value) => value.slice(0, 500));
82898
+ nativeSessionIdSchema = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/);
82899
+ nativeSessionInfoSchema = external_exports.object({
82900
+ sessionId: nativeSessionIdSchema,
82901
+ cwd: path7,
82902
+ additionalDirectories: external_exports.array(path7).max(16).default([]).readonly(),
82903
+ title: title.nullish(),
82904
+ updatedAt: external_exports.iso.datetime({ offset: true }).nullish()
82905
+ }).readonly();
82906
+ nativeSessionPageSchema = external_exports.object({
82907
+ sessions: external_exports.array(nativeSessionInfoSchema).max(500).readonly(),
82908
+ nextCursor: external_exports.string().min(1).max(4096).nullish()
82909
+ }).readonly();
82910
+ }
82911
+ });
82912
+
82887
82913
  // src/engine/acp/client/prompt-content.ts
82888
82914
  function validatePromptContent(options, capabilities) {
82889
82915
  if (options.images.length > 0 && !capabilities.imagePrompt) {
@@ -82946,29 +82972,6 @@ var init_prompt_content = __esm({
82946
82972
  }
82947
82973
  });
82948
82974
 
82949
- // src/engine/acp/protocol/native-session.ts
82950
- var path7, title, nativeSessionIdSchema, nativeSessionInfoSchema, nativeSessionPageSchema;
82951
- var init_native_session = __esm({
82952
- "src/engine/acp/protocol/native-session.ts"() {
82953
- "use strict";
82954
- init_zod();
82955
- path7 = external_exports.string().min(1).max(2048).refine((value) => !value.includes("\0"));
82956
- title = external_exports.string().transform((value) => value.slice(0, 500));
82957
- nativeSessionIdSchema = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/);
82958
- nativeSessionInfoSchema = external_exports.object({
82959
- sessionId: nativeSessionIdSchema,
82960
- cwd: path7,
82961
- additionalDirectories: external_exports.array(path7).max(16).default([]).readonly(),
82962
- title: title.nullish(),
82963
- updatedAt: external_exports.iso.datetime({ offset: true }).nullish()
82964
- }).readonly();
82965
- nativeSessionPageSchema = external_exports.object({
82966
- sessions: external_exports.array(nativeSessionInfoSchema).max(500).readonly(),
82967
- nextCursor: external_exports.string().min(1).max(4096).nullish()
82968
- }).readonly();
82969
- }
82970
- });
82971
-
82972
82975
  // src/engine/acp/protocol/session-config-protocol.ts
82973
82976
  import { methods as methods9 } from "@agentclientprotocol/sdk";
82974
82977
  function isRecord6(value) {
@@ -83292,6 +83295,117 @@ var init_agent_update_stream = __esm({
83292
83295
  }
83293
83296
  });
83294
83297
 
83298
+ // src/engine/acp/adapter/agent-initialization.ts
83299
+ import { methods as methods10, PROTOCOL_VERSION as PROTOCOL_VERSION3 } from "@agentclientprotocol/sdk";
83300
+ async function validateAgentRuntime(agent, signal) {
83301
+ signal.throwIfAborted();
83302
+ const unchanged = await Promise.all(agent.runtimeExecutables.map((identity2) => revalidateExecutable(identity2)));
83303
+ signal.throwIfAborted();
83304
+ if (unchanged.some((result) => !result)) {
83305
+ throw new AcpExecutionError(
83306
+ "The local Agent runtime changed; restart Mobius before starting a new conversation",
83307
+ {},
83308
+ "agent_runtime_changed"
83309
+ );
83310
+ }
83311
+ }
83312
+ async function initializeAgentConnection(connection, agentId, verifiedVersion, signal) {
83313
+ await connection.race(connection.initialize(signal), "The Agent runtime exited during initialization", signal).catch((cause) => {
83314
+ signal.throwIfAborted();
83315
+ throw new RetryableAcpInitializationError(cause);
83316
+ });
83317
+ const initialized = await connection.race(
83318
+ connection.connection.agent.request(
83319
+ methods10.agent.initialize,
83320
+ {
83321
+ clientCapabilities: {
83322
+ elicitation: { form: {}, url: {} },
83323
+ plan: {},
83324
+ session: { compaction: {}, configOptions: { boolean: {} } }
83325
+ },
83326
+ clientInfo: { name: "mobius", version: "0.0.3" },
83327
+ protocolVersion: PROTOCOL_VERSION3
83328
+ },
83329
+ { cancellationSignal: signal }
83330
+ ),
83331
+ "ACP agent exited during initialization",
83332
+ signal
83333
+ ).catch((cause) => {
83334
+ signal.throwIfAborted();
83335
+ throw new RetryableAcpInitializationError(cause);
83336
+ });
83337
+ if (initialized.protocolVersion !== PROTOCOL_VERSION3) {
83338
+ throw new AcpExecutionError(
83339
+ "ACP agent selected an unsupported protocol version",
83340
+ {},
83341
+ "unsupported_acp_protocol"
83342
+ );
83343
+ }
83344
+ return {
83345
+ capabilities: normalizeAcpCapabilities(initialized),
83346
+ agentName: truncate(initialized.agentInfo?.title ?? initialized.agentInfo?.name ?? agentId, 255),
83347
+ agentVersion: truncate(
83348
+ verifiedVersion.length > 0 ? verifiedVersion : initialized.agentInfo?.version ?? "",
83349
+ 128
83350
+ )
83351
+ };
83352
+ }
83353
+ var RetryableAcpInitializationError;
83354
+ var init_agent_initialization = __esm({
83355
+ "src/engine/acp/adapter/agent-initialization.ts"() {
83356
+ "use strict";
83357
+ init_executable();
83358
+ init_value_utils();
83359
+ init_acp_error();
83360
+ init_session_capabilities();
83361
+ RetryableAcpInitializationError = class extends AcpExecutionError {
83362
+ constructor(cause) {
83363
+ super("ACP agent initialization failed", { cause });
83364
+ this.name = "RetryableAcpInitializationError";
83365
+ }
83366
+ };
83367
+ }
83368
+ });
83369
+
83370
+ // src/engine/acp/adapter/configuration-changes.ts
83371
+ function recordConfigurationOptions(changes, options) {
83372
+ const modes = options.filter((option) => option.category === "mode");
83373
+ const selection = modes.length > 0 ? { kind: "unchanged" } : changes.kind === "mode" ? { kind: "selected", modeId: changes.modeId } : changes.kind === "replacement" ? changes.selection : { kind: "unchanged" };
83374
+ return {
83375
+ kind: "replacement",
83376
+ options,
83377
+ modes: modes.length > 0 ? modes : changes.kind === "replacement" ? changes.modes : [],
83378
+ selection
83379
+ };
83380
+ }
83381
+ function recordConfigurationMode(changes, modeId) {
83382
+ return changes.kind === "replacement" ? { ...changes, selection: { kind: "selected", modeId } } : { kind: "mode", modeId };
83383
+ }
83384
+ function applyConfigurationMode(options, modeId) {
83385
+ return options.map((option) => option.category === "mode" ? { ...option, currentValue: modeId } : option);
83386
+ }
83387
+ function applyConfigurationChanges(base, changes) {
83388
+ switch (changes.kind) {
83389
+ case "unchanged":
83390
+ return base;
83391
+ case "mode":
83392
+ return applyConfigurationMode(base, changes.modeId);
83393
+ case "replacement": {
83394
+ const options = changes.options.some((option) => option.category === "mode") ? changes.options : [
83395
+ ...changes.modes.length > 0 ? changes.modes : base.filter((option) => option.category === "mode"),
83396
+ ...changes.options
83397
+ ].slice(0, MAXIMUM_CONFIG_OPTIONS);
83398
+ return changes.selection.kind === "selected" ? applyConfigurationMode(options, changes.selection.modeId) : options;
83399
+ }
83400
+ }
83401
+ }
83402
+ var init_configuration_changes = __esm({
83403
+ "src/engine/acp/adapter/configuration-changes.ts"() {
83404
+ "use strict";
83405
+ init_session_config_protocol();
83406
+ }
83407
+ });
83408
+
83295
83409
  // src/engine/acp/adapter/session-events.ts
83296
83410
  import { setImmediate as yieldToRuntime2 } from "node:timers/promises";
83297
83411
  var AdapterSessionConnection, AcpSessionConnector;
@@ -83302,7 +83416,10 @@ var init_session_events = __esm({
83302
83416
  init_value_utils();
83303
83417
  init_acp_error();
83304
83418
  init_agent_update_stream();
83419
+ init_session_capabilities();
83305
83420
  init_session_config_protocol();
83421
+ init_agent_initialization();
83422
+ init_configuration_changes();
83306
83423
  AdapterSessionConnection = class {
83307
83424
  #connection;
83308
83425
  #onBackgroundActivity;
@@ -83311,19 +83428,24 @@ var init_session_events = __esm({
83311
83428
  #updates;
83312
83429
  #lifetime = new AbortController();
83313
83430
  #onClosed;
83431
+ #agent;
83432
+ #state = { kind: "uninitialized" };
83433
+ #initialization = {
83434
+ kind: "not-started"
83435
+ };
83314
83436
  events;
83315
83437
  constructor(options, externalizer, normalizeEvent, onClosed = () => void 0) {
83438
+ this.#agent = options.agent;
83316
83439
  this.#onClosed = onClosed;
83317
83440
  this.#onBackgroundActivity = options.onBackgroundActivity ?? (() => {
83318
83441
  });
83319
- const protocol = sessionConfigProtocolForAgent(options.agent.id);
83320
83442
  this.#updates = new AgentUpdateStream(async (notification) => {
83321
83443
  this.#lifetime.signal.throwIfAborted();
83322
83444
  if (notification.sessionId !== this.#updates.sessionId()) {
83323
83445
  throw new AcpExecutionError("ACP agent referenced an unknown session", {}, "invalid_agent_session");
83324
83446
  }
83325
83447
  const signal = AbortSignal.any([this.#lifetime.signal, AbortSignal.timeout(3e4)]);
83326
- const externalized = await externalizer.update(options.sessionId(), notification.update, signal);
83448
+ const externalized = options.externalizeUpdate === void 0 ? await externalizer.update(notification.sessionId, notification.update, signal) : await options.externalizeUpdate(notification.update, signal);
83327
83449
  signal.throwIfAborted();
83328
83450
  const update = externalized.agent;
83329
83451
  for (const eventUpdate of externalized.events) {
@@ -83349,13 +83471,15 @@ var init_session_events = __esm({
83349
83471
  };
83350
83472
  break;
83351
83473
  case "config_option_update":
83474
+ this.#applyConfigurationUpdate(update.configOptions);
83352
83475
  event = {
83353
83476
  kind: "configuration",
83354
83477
  payload,
83355
- configOptions: protocol.normalizeUpdate(options.configOptions(), update.configOptions)
83478
+ configOptions: this.snapshot().configOptions
83356
83479
  };
83357
83480
  break;
83358
83481
  case "current_mode_update":
83482
+ this.#applyModeUpdate(update.currentModeId);
83359
83483
  event = { kind: "mode", payload, modeId: update.currentModeId };
83360
83484
  break;
83361
83485
  case "session_info_update": {
@@ -83427,10 +83551,92 @@ var init_session_events = __esm({
83427
83551
  get termination() {
83428
83552
  return this.#connection.termination;
83429
83553
  }
83554
+ #ready = () => {
83555
+ const state = this.#state;
83556
+ if (state.kind !== "ready") {
83557
+ throw new AcpExecutionError(
83558
+ "The Agent session is not initialized or has closed",
83559
+ {},
83560
+ "invalid_agent_session"
83561
+ );
83562
+ }
83563
+ return state;
83564
+ };
83565
+ snapshot = () => this.#ready().snapshot;
83566
+ beginStateChange = () => {
83567
+ const state = this.#ready();
83568
+ if (state.operation.kind !== "idle") {
83569
+ throw new AcpExecutionError("Another session configuration operation is running", {}, "session_busy");
83570
+ }
83571
+ this.#state = { ...state, operation: { kind: "pending", changes: { kind: "unchanged" } } };
83572
+ };
83573
+ cancelStateChange = () => {
83574
+ if (this.#state.kind === "ready") {
83575
+ this.#state = { ...this.#state, operation: { kind: "idle" } };
83576
+ }
83577
+ };
83578
+ commitConfiguration = (options) => {
83579
+ const state = this.#ready();
83580
+ if (state.operation.kind !== "pending") {
83581
+ throw new AcpExecutionError("No session configuration operation is running", {}, "invalid_agent_session");
83582
+ }
83583
+ const configOptions = applyConfigurationChanges(options, state.operation.changes);
83584
+ this.#state = { ...state, snapshot: { ...state.snapshot, configOptions }, operation: { kind: "idle" } };
83585
+ return configOptions;
83586
+ };
83587
+ commitLifecycle = (response) => {
83588
+ const state = this.#ready();
83589
+ const capabilities = restrictAcpSessionCapabilities(state.snapshot.capabilities, response);
83590
+ this.commitConfiguration(sessionConfigProtocolForAgent(this.#agent.id).normalizeLifecycle(response));
83591
+ this.#state = { ...this.#ready(), snapshot: { capabilities, configOptions: this.snapshot().configOptions } };
83592
+ return this.snapshot();
83593
+ };
83594
+ #applyConfigurationUpdate = (value) => {
83595
+ const state = this.#ready();
83596
+ const protocol = sessionConfigProtocolForAgent(this.#agent.id);
83597
+ const configOptions = protocol.normalizeUpdate(state.snapshot.configOptions, value);
83598
+ const operation = state.operation.kind === "pending" ? {
83599
+ kind: "pending",
83600
+ changes: recordConfigurationOptions(state.operation.changes, protocol.normalizeUpdate([], value))
83601
+ } : state.operation;
83602
+ this.#state = { ...state, snapshot: { ...state.snapshot, configOptions }, operation };
83603
+ };
83604
+ #applyModeUpdate = (modeId) => {
83605
+ const state = this.#ready();
83606
+ const operation = state.operation.kind === "pending" ? { kind: "pending", changes: recordConfigurationMode(state.operation.changes, modeId) } : state.operation;
83607
+ this.#state = {
83608
+ ...state,
83609
+ snapshot: {
83610
+ ...state.snapshot,
83611
+ configOptions: applyConfigurationMode(state.snapshot.configOptions, modeId)
83612
+ },
83613
+ operation
83614
+ };
83615
+ };
83430
83616
  initialize = (signal) => this.#connection.initialize(signal);
83617
+ initializeAgent = (signal) => {
83618
+ if (this.#initialization.kind === "not-started") {
83619
+ this.#initialization = {
83620
+ kind: "started",
83621
+ result: initializeAgentConnection(this, this.#agent.id, this.#agent.agentVersion, signal).then(
83622
+ (agent) => {
83623
+ this.#lifetime.signal.throwIfAborted();
83624
+ this.#state = {
83625
+ kind: "ready",
83626
+ snapshot: { capabilities: agent.capabilities, configOptions: [] },
83627
+ operation: { kind: "idle" }
83628
+ };
83629
+ return agent;
83630
+ }
83631
+ )
83632
+ };
83633
+ }
83634
+ return this.#initialization.result;
83635
+ };
83431
83636
  agentSettingsModelEffort = () => this.#connection.agentSettingsModelEffort();
83432
83637
  race = (operation, exitMessage, signal) => this.#connection.race(operation, exitMessage, signal);
83433
83638
  closeProcess = async () => {
83639
+ this.#state = { kind: "closed" };
83434
83640
  this.#lifetime.abort(new DOMException("The adapter event subscription closed", "AbortError"));
83435
83641
  try {
83436
83642
  await this.#connection.closeProcess();
@@ -83478,12 +83684,12 @@ var init_session_events = __esm({
83478
83684
  }
83479
83685
  });
83480
83686
 
83481
- // src/engine/acp/adapter/live-sessions.ts
83687
+ // src/engine/acp/adapter/execution-connections.ts
83482
83688
  import { isAbsolute as isAbsolute14, resolve as resolve14 } from "node:path";
83483
- import { methods as methods10 } from "@agentclientprotocol/sdk";
83484
- var absolutePathSchema, targetSchema, AcpLiveSessions;
83485
- var init_live_sessions = __esm({
83486
- "src/engine/acp/adapter/live-sessions.ts"() {
83689
+ import { methods as methods11 } from "@agentclientprotocol/sdk";
83690
+ var absolutePathSchema, targetSchema, AcpExecutionConnections;
83691
+ var init_execution_connections = __esm({
83692
+ "src/engine/acp/adapter/execution-connections.ts"() {
83487
83693
  "use strict";
83488
83694
  init_protocol();
83489
83695
  init_zod();
@@ -83499,7 +83705,7 @@ var init_live_sessions = __esm({
83499
83705
  cwd: absolutePathSchema,
83500
83706
  additionalDirectories: external_exports.array(absolutePathSchema)
83501
83707
  });
83502
- AcpLiveSessions = class {
83708
+ AcpExecutionConnections = class {
83503
83709
  #sessions = /* @__PURE__ */ new Set();
83504
83710
  #externalizer;
83505
83711
  #normalizeEvent;
@@ -83507,16 +83713,72 @@ var init_live_sessions = __esm({
83507
83713
  this.#externalizer = externalizer;
83508
83714
  this.#normalizeEvent = normalizeEvent;
83509
83715
  }
83510
- connectSession = (scope) => {
83716
+ acquire = (params) => {
83717
+ params.signal.throwIfAborted();
83718
+ const existing = [...this.#sessions].find(
83719
+ ({ subscriber }) => subscriber.onSessionEvent === params.onSessionEvent
83720
+ );
83721
+ if (existing !== void 0) {
83722
+ if (existing.scope.agent !== params.scope.agent || existing.scope.cwd !== params.scope.cwd || !arraysEqual(existing.scope.additionalDirectories, params.scope.additionalDirectories)) {
83723
+ throw new AcpExecutionError(
83724
+ "The agent or workspace cannot change after a conversation has started",
83725
+ {},
83726
+ "session_identity_mismatch"
83727
+ );
83728
+ }
83729
+ return existing;
83730
+ }
83511
83731
  const connection = new AdapterSessionConnection(
83512
- scope,
83732
+ {
83733
+ agent: params.scope.agent,
83734
+ cwd: params.scope.cwd,
83735
+ ...params.scope.externalizeUpdate === void 0 ? {} : { externalizeUpdate: params.scope.externalizeUpdate },
83736
+ onEvent: (event) => params.onSessionEvent(connection.events.sessionId(), event),
83737
+ ...params.onBackgroundActivity === void 0 ? {} : { onBackgroundActivity: params.onBackgroundActivity },
83738
+ interactions: params.interactions
83739
+ },
83513
83740
  this.#externalizer,
83514
83741
  this.#normalizeEvent,
83515
83742
  () => this.#sessions.delete(session)
83516
83743
  );
83517
- const session = { connection, scope };
83744
+ const session = { connection, scope: params.scope, subscriber: params };
83518
83745
  this.#sessions.add(session);
83519
- return connection;
83746
+ return session;
83747
+ };
83748
+ /** Resource scope only: the concrete adapter supplies the protocol operation. */
83749
+ withConnection = async (params, operation) => {
83750
+ const signal = AbortSignal.any([params.signal, AbortSignal.timeout(6e4)]);
83751
+ signal.throwIfAborted();
83752
+ const session = this.acquire(params);
83753
+ const wasBound = session.connection.events.sessionId().length > 0;
83754
+ try {
83755
+ await session.connection.initializeAgent(signal);
83756
+ session.connection.beginStateChange();
83757
+ try {
83758
+ const result = await operation(session, signal);
83759
+ signal.throwIfAborted();
83760
+ return result;
83761
+ } catch (cause) {
83762
+ session.connection.cancelStateChange();
83763
+ throw cause;
83764
+ }
83765
+ } catch (cause) {
83766
+ if (!wasBound) {
83767
+ await session.connection.closeProcess();
83768
+ }
83769
+ throw cause;
83770
+ }
83771
+ };
83772
+ bind = (session, nativeSessionId) => {
83773
+ const existing = this.#find({
83774
+ nativeSessionId,
83775
+ cwd: session.scope.cwd,
83776
+ additionalDirectories: session.scope.additionalDirectories
83777
+ });
83778
+ if (existing !== void 0 && existing !== session) {
83779
+ throw new AcpExecutionError("Another writer is using this native session", {}, "session_busy");
83780
+ }
83781
+ session.connection.events.select(nativeSessionId);
83520
83782
  };
83521
83783
  #find = (target) => {
83522
83784
  const decoded = targetSchema.safeParse(target);
@@ -83545,12 +83807,12 @@ var init_live_sessions = __esm({
83545
83807
  }
83546
83808
  return session;
83547
83809
  };
83548
- cancel = async (target, signal) => {
83810
+ cancel = async ({ signal, ...target }) => {
83549
83811
  const bounded = AbortSignal.any([signal, AbortSignal.timeout(3e4)]);
83550
83812
  bounded.throwIfAborted();
83551
83813
  const { connection } = this.#resolve(target);
83552
83814
  await connection.race(
83553
- connection.connection.agent.notify(methods10.agent.session.cancel, {
83815
+ connection.connection.agent.notify(methods11.agent.session.cancel, {
83554
83816
  sessionId: connection.events.sessionId()
83555
83817
  }),
83556
83818
  "ACP agent exited while cancelling a prompt",
@@ -83558,19 +83820,19 @@ var init_live_sessions = __esm({
83558
83820
  );
83559
83821
  return "retained";
83560
83822
  };
83561
- closeSession = async (target, signal) => {
83823
+ closeSession = async ({ signal, ...target }) => {
83562
83824
  const session = this.#find(target);
83563
83825
  if (session === void 0) {
83564
83826
  signal.throwIfAborted();
83565
83827
  return;
83566
83828
  }
83567
- const { connection, scope } = session;
83829
+ const { connection } = session;
83568
83830
  try {
83569
83831
  signal.throwIfAborted();
83570
- if (scope.capabilities().closeSession) {
83832
+ if (connection.snapshot().capabilities.closeSession) {
83571
83833
  try {
83572
83834
  await connection.connection.agent.request(
83573
- methods10.agent.session.close,
83835
+ methods11.agent.session.close,
83574
83836
  { sessionId: connection.events.sessionId() },
83575
83837
  { cancellationSignal: AbortSignal.any([signal, AbortSignal.timeout(1e3)]) }
83576
83838
  );
@@ -83583,13 +83845,20 @@ var init_live_sessions = __esm({
83583
83845
  }
83584
83846
  signal.throwIfAborted();
83585
83847
  };
83586
- prompt = async (target, content, signal) => {
83848
+ releaseSession = async ({ signal, ...target }) => {
83849
+ const session = this.#find(target);
83850
+ if (session !== void 0) {
83851
+ await session.connection.closeProcess();
83852
+ }
83587
83853
  signal.throwIfAborted();
83588
- const { connection, scope } = this.#resolve(target);
83589
- const prompt = buildPromptContent(content, scope.capabilities());
83854
+ };
83855
+ prompt = async ({ content, signal, ...target }) => {
83856
+ signal.throwIfAborted();
83857
+ const { connection } = this.#resolve(target);
83858
+ const prompt = buildPromptContent(content, connection.snapshot().capabilities);
83590
83859
  const response = await connection.race(
83591
83860
  connection.connection.agent.request(
83592
- methods10.agent.session.prompt,
83861
+ methods11.agent.session.prompt,
83593
83862
  { prompt, sessionId: target.nativeSessionId },
83594
83863
  { cancellationSignal: signal }
83595
83864
  ),
@@ -83616,10 +83885,10 @@ var init_live_sessions = __esm({
83616
83885
  );
83617
83886
  }
83618
83887
  };
83619
- steer = async (target, content, signal) => {
83888
+ steer = async ({ content, signal, ...target }) => {
83620
83889
  signal.throwIfAborted();
83621
- const { connection, scope } = this.#resolve(target);
83622
- if (!scope.capabilities().steering) {
83890
+ const { connection } = this.#resolve(target);
83891
+ if (!connection.snapshot().capabilities.steering) {
83623
83892
  throw new AcpExecutionError(
83624
83893
  "The selected agent does not support mid-turn steering",
83625
83894
  {},
@@ -83631,7 +83900,7 @@ var init_live_sessions = __esm({
83631
83900
  "_session/steering",
83632
83901
  {
83633
83902
  _meta: { steering: { idleBehavior: "promptRequired" } },
83634
- prompt: buildPromptContent(content, scope.capabilities()),
83903
+ prompt: buildPromptContent(content, connection.snapshot().capabilities),
83635
83904
  sessionId: target.nativeSessionId
83636
83905
  },
83637
83906
  { cancellationSignal: signal }
@@ -83661,14 +83930,14 @@ var init_live_sessions = __esm({
83661
83930
  "acp_invalid_steering_response"
83662
83931
  );
83663
83932
  };
83664
- renameSession = async (target, title2, signal) => {
83933
+ renameSession = async ({ title: title2, signal, ...target }) => {
83665
83934
  signal.throwIfAborted();
83666
- const { connection, scope } = this.#resolve(target);
83935
+ const { connection } = this.#resolve(target);
83667
83936
  const normalized = truncate(title2, 500);
83668
83937
  if (normalized.length === 0) {
83669
83938
  throw new AcpExecutionError("The Session title cannot be empty", {}, "invalid_session_title");
83670
83939
  }
83671
- if (!scope.capabilities().renameSession) {
83940
+ if (!connection.snapshot().capabilities.renameSession) {
83672
83941
  return { nativeRenameApplied: false };
83673
83942
  }
83674
83943
  try {
@@ -83694,10 +83963,14 @@ var init_live_sessions = __esm({
83694
83963
  }
83695
83964
  return { nativeRenameApplied: true };
83696
83965
  };
83697
- configureSession = async (target, selection, signal) => {
83966
+ configureSession = async ({
83967
+ selection,
83968
+ signal,
83969
+ ...target
83970
+ }) => {
83698
83971
  signal.throwIfAborted();
83699
83972
  const { connection, scope } = this.#resolve(target);
83700
- const current = scope.configOptions();
83973
+ const current = connection.snapshot().configOptions;
83701
83974
  const existing = current.find((option) => option.id === selection.configId);
83702
83975
  if (existing === void 0 || existing.type !== selection.type || existing.type === "select" && existing.values.length < 2) {
83703
83976
  throw new AcpExecutionError(
@@ -83713,6 +83986,7 @@ var init_live_sessions = __esm({
83713
83986
  existing.values.map((entry) => entry.value)
83714
83987
  );
83715
83988
  }
83989
+ connection.beginStateChange();
83716
83990
  try {
83717
83991
  const configured = await sessionConfigProtocolForAgent(scope.agent.id).configure(
83718
83992
  current,
@@ -83740,8 +84014,9 @@ var init_live_sessions = __esm({
83740
84014
  );
83741
84015
  }
83742
84016
  await connection.events.drained();
83743
- return configured;
84017
+ return connection.commitConfiguration(configured);
83744
84018
  } catch (error62) {
84019
+ connection.cancelStateChange();
83745
84020
  if (error62 instanceof SessionConfigProtocolError) {
83746
84021
  throw new AcpExecutionError(error62.message, { cause: error62 }, error62.code);
83747
84022
  }
@@ -83762,8 +84037,48 @@ var init_live_sessions = __esm({
83762
84037
  }
83763
84038
  });
83764
84039
 
84040
+ // src/engine/acp/adapter/lifecycle-output.ts
84041
+ function sessionWorkspace(scope) {
84042
+ return { cwd: scope.cwd, additionalDirectories: [...scope.additionalDirectories], mcpServers: [] };
84043
+ }
84044
+ function createdNativeSessionId(response) {
84045
+ const decoded = external_exports.object({ sessionId: nativeSessionIdSchema }).safeParse(response);
84046
+ if (!decoded.success) {
84047
+ throw new AcpExecutionError(
84048
+ "The Agent returned an invalid native session",
84049
+ { cause: decoded.error },
84050
+ "invalid_native_session_response"
84051
+ );
84052
+ }
84053
+ return decoded.data.sessionId;
84054
+ }
84055
+ async function normalizeOpenedSession(session, nativeSessionId, response, signal) {
84056
+ await session.connection.race(
84057
+ session.connection.events.drained(),
84058
+ "ACP agent exited while opening a session",
84059
+ signal
84060
+ );
84061
+ signal.throwIfAborted();
84062
+ const initialized = await session.connection.initializeAgent(signal);
84063
+ return {
84064
+ nativeSessionId,
84065
+ agentName: initialized.agentName,
84066
+ agentVersion: initialized.agentVersion,
84067
+ agentSettingsModelEffort: session.connection.agentSettingsModelEffort(),
84068
+ ...session.connection.commitLifecycle(response)
84069
+ };
84070
+ }
84071
+ var init_lifecycle_output = __esm({
84072
+ "src/engine/acp/adapter/lifecycle-output.ts"() {
84073
+ "use strict";
84074
+ init_zod();
84075
+ init_acp_error();
84076
+ init_native_session();
84077
+ }
84078
+ });
84079
+
83765
84080
  // src/engine/acp/adapter/native-session-lookup.ts
83766
- async function findNativeSession(list, cwd, nativeSessionId, budget, signal) {
84081
+ async function findNativeSession(list, query, nativeSessionId, budget) {
83767
84082
  const decoded = lookupSchema.safeParse({ nativeSessionId, budget });
83768
84083
  if (!decoded.success) {
83769
84084
  throw new AcpExecutionError(
@@ -83777,9 +84092,9 @@ async function findNativeSession(list, cwd, nativeSessionId, budget, signal) {
83777
84092
  let inspected = 0;
83778
84093
  const visited = /* @__PURE__ */ new Set();
83779
84094
  for (let pageNumber = 0; pageNumber < limits.maximumPages; pageNumber += 1) {
83780
- signal.throwIfAborted();
83781
- const page = await list(cwd, cursor, signal);
83782
- signal.throwIfAborted();
84095
+ query.signal.throwIfAborted();
84096
+ const page = await list({ query, cursor });
84097
+ query.signal.throwIfAborted();
83783
84098
  inspected += page.sessions.length;
83784
84099
  const found = page.sessions.find((session) => session.sessionId === decoded.data.nativeSessionId);
83785
84100
  if (found !== void 0) {
@@ -84482,75 +84797,27 @@ var init_retained_agent_processes = __esm({
84482
84797
  }
84483
84798
  });
84484
84799
 
84485
- // src/engine/acp/adapter/agent-initialization.ts
84486
- import { methods as methods11, PROTOCOL_VERSION as PROTOCOL_VERSION3 } from "@agentclientprotocol/sdk";
84487
- async function validateAgentRuntime(agent, signal) {
84488
- signal.throwIfAborted();
84489
- const unchanged = await Promise.all(agent.runtimeExecutables.map((identity2) => revalidateExecutable(identity2)));
84490
- signal.throwIfAborted();
84491
- if (unchanged.some((result) => !result)) {
84492
- throw new AcpExecutionError(
84493
- "The local Agent runtime changed; restart Mobius before starting a new conversation",
84494
- {},
84495
- "agent_runtime_changed"
84496
- );
84497
- }
84800
+ // src/engine/acp/adapter/query-scope.ts
84801
+ function nativeSessionQueryKey(query) {
84802
+ return queryKeySchema.parse(
84803
+ JSON.stringify([
84804
+ query.agent.id,
84805
+ query.cwd,
84806
+ query.additionalDirectories,
84807
+ Object.entries(query.agent.environment).sort(([left], [right]) => left.localeCompare(right))
84808
+ ])
84809
+ );
84498
84810
  }
84499
- async function initializeAgentConnection(connection, agentId, verifiedVersion, signal) {
84500
- await connection.race(connection.initialize(signal), "The Agent runtime exited during initialization", signal).catch((cause) => {
84501
- signal.throwIfAborted();
84502
- throw new RetryableAcpInitializationError(cause);
84503
- });
84504
- const initialized = await connection.race(
84505
- connection.connection.agent.request(
84506
- methods11.agent.initialize,
84507
- {
84508
- clientCapabilities: {
84509
- elicitation: { form: {}, url: {} },
84510
- plan: {},
84511
- session: { compaction: {}, configOptions: { boolean: {} } }
84512
- },
84513
- clientInfo: { name: "mobius", version: "0.0.3" },
84514
- protocolVersion: PROTOCOL_VERSION3
84515
- },
84516
- { cancellationSignal: signal }
84517
- ),
84518
- "ACP agent exited during initialization",
84519
- signal
84520
- ).catch((cause) => {
84521
- signal.throwIfAborted();
84522
- throw new RetryableAcpInitializationError(cause);
84523
- });
84524
- if (initialized.protocolVersion !== PROTOCOL_VERSION3) {
84525
- throw new AcpExecutionError(
84526
- "ACP agent selected an unsupported protocol version",
84527
- {},
84528
- "unsupported_acp_protocol"
84529
- );
84530
- }
84531
- return {
84532
- capabilities: normalizeAcpCapabilities(initialized),
84533
- agentName: truncate(initialized.agentInfo?.title ?? initialized.agentInfo?.name ?? agentId, 255),
84534
- agentVersion: truncate(
84535
- verifiedVersion.length > 0 ? verifiedVersion : initialized.agentInfo?.version ?? "",
84536
- 128
84537
- )
84538
- };
84811
+ function nativeSessionPreviewKey(queryKey, nativeSessionId) {
84812
+ return previewKeySchema.parse(JSON.stringify([queryKey, nativeSessionId]));
84539
84813
  }
84540
- var RetryableAcpInitializationError;
84541
- var init_agent_initialization = __esm({
84542
- "src/engine/acp/adapter/agent-initialization.ts"() {
84814
+ var queryKeySchema, previewKeySchema;
84815
+ var init_query_scope = __esm({
84816
+ "src/engine/acp/adapter/query-scope.ts"() {
84543
84817
  "use strict";
84544
- init_executable();
84545
- init_value_utils();
84546
- init_acp_error();
84547
- init_session_capabilities();
84548
- RetryableAcpInitializationError = class extends AcpExecutionError {
84549
- constructor(cause) {
84550
- super("ACP agent initialization failed", { cause });
84551
- this.name = "RetryableAcpInitializationError";
84552
- }
84553
- };
84818
+ init_zod();
84819
+ queryKeySchema = external_exports.string().brand();
84820
+ previewKeySchema = external_exports.string().brand();
84554
84821
  }
84555
84822
  });
84556
84823
 
@@ -84562,48 +84829,35 @@ var init_query_session = __esm({
84562
84829
  "use strict";
84563
84830
  init_acp_error();
84564
84831
  init_native_session();
84565
- init_session_capabilities();
84566
84832
  init_agent_initialization();
84567
84833
  AcpQuerySession = class _AcpQuerySession {
84568
- #cwd;
84569
- #sessionId;
84834
+ #options;
84570
84835
  #events;
84571
84836
  #connection;
84572
84837
  #lifecycle = { kind: "open" };
84573
- #capabilities = unsupportedSessionCapabilities();
84574
- #configOptions = [];
84575
- constructor(agent, cwd, sessionId, events, connector) {
84576
- this.#cwd = cwd;
84577
- this.#sessionId = sessionId;
84838
+ #eventScope = crypto.randomUUID();
84839
+ constructor(options, events, connector) {
84840
+ this.#options = options;
84578
84841
  this.#events = events;
84579
84842
  this.#connection = connector.connectQuerySession({
84580
- agent,
84581
- cwd,
84582
- sessionId: () => sessionId,
84583
- configOptions: () => this.#configOptions,
84843
+ agent: options.agent,
84844
+ cwd: options.cwd,
84845
+ ...options.externalizeUpdate === void 0 ? {} : { externalizeUpdate: options.externalizeUpdate },
84584
84846
  onEvent: async (event) => {
84585
- this.#events.append(sessionId, { type: "acp", payload: event.payload });
84586
- if (event.kind === "configuration") {
84587
- this.#configOptions = event.configOptions;
84588
- }
84847
+ this.#events.append(this.#eventScope, { type: "acp", payload: event.payload });
84589
84848
  }
84590
84849
  });
84591
84850
  void this.#connection.termination.then(() => {
84592
84851
  this.#lifecycle = { kind: "terminated" };
84593
84852
  });
84594
84853
  }
84595
- static start = async (agent, cwd, sessionId, events, connector, signal) => {
84854
+ static start = async (options, events, connector) => {
84855
+ const { agent, signal } = options;
84596
84856
  for (let attempt = 1; attempt <= 2; attempt += 1) {
84597
84857
  await validateAgentRuntime(agent, signal);
84598
- const runtime = new _AcpQuerySession(agent, cwd, sessionId, events, connector);
84858
+ const runtime = new _AcpQuerySession(options, events, connector);
84599
84859
  try {
84600
- const initialized = await initializeAgentConnection(
84601
- runtime.#connection,
84602
- agent.id,
84603
- agent.agentVersion,
84604
- signal
84605
- );
84606
- runtime.#capabilities = initialized.capabilities;
84860
+ await runtime.#connection.initializeAgent(options.signal);
84607
84861
  return runtime;
84608
84862
  } catch (error62) {
84609
84863
  await runtime.closeProcess();
@@ -84620,7 +84874,7 @@ var init_query_session = __esm({
84620
84874
  }
84621
84875
  throw new AcpExecutionError("ACP agent initialization failed");
84622
84876
  };
84623
- capabilities = () => this.#capabilities;
84877
+ capabilities = () => this.#connection.snapshot().capabilities;
84624
84878
  hasTerminated = () => {
84625
84879
  switch (this.#lifecycle.kind) {
84626
84880
  case "open":
@@ -84634,7 +84888,7 @@ var init_query_session = __esm({
84634
84888
  }
84635
84889
  };
84636
84890
  listNativeSessions = async (cursor, signal) => {
84637
- if (!this.#capabilities.listSessions) {
84891
+ if (!this.capabilities().listSessions) {
84638
84892
  throw new AcpExecutionError(
84639
84893
  "This Agent does not support native session listing",
84640
84894
  {},
@@ -84658,22 +84912,24 @@ var init_query_session = __esm({
84658
84912
  }
84659
84913
  return decoded.data;
84660
84914
  };
84661
- previewEvents = async (nativeSessionId, eventLimit, additionalDirectories, signal) => {
84662
- if (!this.#capabilities.loadSession) {
84915
+ previewEvents = async (nativeSessionId, eventLimit, signal) => {
84916
+ if (!this.capabilities().loadSession) {
84663
84917
  throw new AcpExecutionError(
84664
84918
  "This Agent restores context but does not provide message history.",
84665
84919
  {},
84666
84920
  "native_history_unsupported"
84667
84921
  );
84668
84922
  }
84669
- this.#events.reset(this.#sessionId);
84923
+ this.#eventScope = nativeSessionId;
84924
+ this.#events.reset(nativeSessionId);
84670
84925
  this.#connection.events.select(nativeSessionId);
84671
- await this.#connection.race(
84926
+ this.#connection.beginStateChange();
84927
+ const response = await this.#connection.race(
84672
84928
  this.#connection.connection.agent.request(
84673
84929
  methods12.agent.session.load,
84674
84930
  {
84675
- additionalDirectories: [...additionalDirectories],
84676
- cwd: this.#cwd,
84931
+ additionalDirectories: [...this.#options.additionalDirectories],
84932
+ cwd: this.#options.cwd,
84677
84933
  mcpServers: [],
84678
84934
  sessionId: nativeSessionId
84679
84935
  },
@@ -84684,16 +84940,16 @@ var init_query_session = __esm({
84684
84940
  );
84685
84941
  await this.#connection.events.drained();
84686
84942
  signal.throwIfAborted();
84687
- return this.#events.page(this.#sessionId, eventLimit, null);
84943
+ this.#connection.commitLifecycle(response);
84944
+ return this.#events.page(nativeSessionId, eventLimit, null);
84688
84945
  };
84689
84946
  closeProcess = async () => await this.#connection.closeProcess();
84690
- discardEvents = () => this.#events.remove(this.#sessionId);
84947
+ discardEvents = () => this.#events.remove(this.#eventScope);
84691
84948
  };
84692
84949
  }
84693
84950
  });
84694
84951
 
84695
84952
  // src/engine/acp/adapter/query-processes.ts
84696
- import { randomUUID as randomUUID14 } from "node:crypto";
84697
84953
  var AgentQueryProcesses;
84698
84954
  var init_query_processes = __esm({
84699
84955
  "src/engine/acp/adapter/query-processes.ts"() {
@@ -84701,6 +84957,7 @@ var init_query_processes = __esm({
84701
84957
  init_session_event_store();
84702
84958
  init_operation_drain();
84703
84959
  init_retained_agent_processes();
84960
+ init_query_scope();
84704
84961
  init_query_session();
84705
84962
  AgentQueryProcesses = class {
84706
84963
  #eventPreviewsBySession = /* @__PURE__ */ new Map();
@@ -84717,45 +84974,46 @@ var init_query_processes = __esm({
84717
84974
  refreshAgent = (agent) => {
84718
84975
  this.#agent = agent;
84719
84976
  };
84720
- retire = async (readers, cwd, runtime) => {
84721
- readers.detach(cwd, runtime);
84977
+ retire = async (readers, key, runtime) => {
84978
+ readers.detach(key, runtime);
84722
84979
  try {
84723
84980
  await this.#processes.retire(runtime, () => runtime.closeProcess());
84724
84981
  } finally {
84725
84982
  runtime.discardEvents();
84726
84983
  }
84727
84984
  };
84728
- async #ensure(agent, readers, cwd, signal) {
84729
- signal.throwIfAborted();
84730
- const pending = readers.pending(cwd);
84985
+ async #ensure(readers, query) {
84986
+ query.signal.throwIfAborted();
84987
+ const key = nativeSessionQueryKey(query);
84988
+ const pending = readers.pending(key);
84731
84989
  if (pending !== void 0) {
84732
- return await waitForSharedOperation(pending, signal);
84990
+ return await waitForSharedOperation(pending, query.signal);
84733
84991
  }
84734
- const existing = readers.get(cwd);
84992
+ const existing = readers.get(key);
84735
84993
  if (existing !== void 0 && !existing.hasTerminated()) {
84736
- readers.touch(cwd, existing);
84994
+ readers.touch(key, existing);
84737
84995
  return existing;
84738
84996
  }
84739
- return await readers.prepare(cwd, async () => {
84997
+ return await readers.prepare(key, async () => {
84740
84998
  if (existing !== void 0) {
84741
- await this.retire(readers, cwd, existing);
84999
+ await this.retire(readers, key, existing);
84742
85000
  }
84743
- const readerId = randomUUID14();
84744
85001
  const runtime = await this.#processes.startRetained(
84745
- signal,
84746
- () => AcpQuerySession.start(agent, cwd, readerId, this.#store, this.#connector, signal),
85002
+ query.signal,
85003
+ () => AcpQuerySession.start(query, this.#store, this.#connector),
84747
85004
  {
84748
- isBusy: () => readers.isBusy(cwd),
84749
- retire: (runtime2) => this.retire(readers, cwd, runtime2),
84750
- retireIdle: (runtime2) => this.retire(readers, cwd, runtime2)
85005
+ isBusy: () => readers.isBusy(key),
85006
+ retire: (runtime2) => this.retire(readers, key, runtime2),
85007
+ retireIdle: (runtime2) => this.retire(readers, key, runtime2)
84751
85008
  }
84752
85009
  );
84753
- readers.retain(cwd, runtime);
85010
+ readers.retain(key, runtime);
84754
85011
  return runtime;
84755
85012
  });
84756
85013
  }
84757
- #use = async (cwd, signal, operation) => {
85014
+ #use = async (query, operation) => {
84758
85015
  const agent = this.#agent;
85016
+ const scoped = { ...query, agent };
84759
85017
  let readers = this.#processesByAgent.get(agent);
84760
85018
  if (readers === void 0) {
84761
85019
  readers = new RetainedAgentProcesses({
@@ -84765,35 +85023,38 @@ var init_query_processes = __esm({
84765
85023
  this.#processesByAgent.set(agent, readers);
84766
85024
  }
84767
85025
  const current = readers;
84768
- return await current.use(cwd, async () => await operation(await this.#ensure(agent, current, cwd, signal)));
85026
+ return await current.use(
85027
+ nativeSessionQueryKey(scoped),
85028
+ async () => await operation(await this.#ensure(current, scoped))
85029
+ );
84769
85030
  };
84770
- capabilities = async (cwd, signal) => await this.#use(cwd, signal, async (runtime) => runtime.capabilities());
84771
- listNativeSessions = async (cwd, cursor, signal) => await this.#use(cwd, signal, async (runtime) => await runtime.listNativeSessions(cursor, signal));
84772
- previewSessionEvents = async (cwd, additionalDirectories, request, signal) => {
84773
- signal.throwIfAborted();
84774
- const agent = this.#agent;
84775
- const { nativeSessionId, eventLimit, cursor, sessionId } = request;
85031
+ capabilities = async (query) => await this.#use(query, async (runtime) => runtime.capabilities());
85032
+ listNativeSessions = async (query, cursor) => await this.#use(query, async (runtime) => await runtime.listNativeSessions(cursor, query.signal));
85033
+ previewSessionEvents = async (query, request) => {
85034
+ query.signal.throwIfAborted();
85035
+ const scoped = { ...query, agent: this.#agent };
85036
+ const { nativeSessionId, eventLimit, cursor } = request;
85037
+ const key = nativeSessionPreviewKey(nativeSessionQueryKey(scoped), nativeSessionId);
84776
85038
  if (cursor !== null) {
84777
- const preview = this.#eventPreviewsBySession.get(sessionId);
85039
+ const preview = this.#eventPreviewsBySession.get(key);
84778
85040
  if (preview === void 0 || preview.nativeSessionId !== nativeSessionId) {
84779
85041
  throw new Error("The native event cursor is invalid");
84780
85042
  }
84781
- return preview.store.page(sessionId, eventLimit, cursor);
85043
+ return preview.store.page(nativeSessionId, eventLimit, cursor);
84782
85044
  }
84783
85045
  const store = new MemorySessionEventStore();
84784
- const previous = this.#eventPreviewsBySession.get(sessionId);
84785
- previous?.store.close();
84786
- this.#eventPreviewsBySession.set(sessionId, { nativeSessionId, store });
85046
+ this.#eventPreviewsBySession.get(key)?.store.close();
85047
+ this.#eventPreviewsBySession.set(key, { nativeSessionId, store });
84787
85048
  try {
84788
85049
  return await this.#processes.runTransient(
84789
- signal,
84790
- async () => await AcpQuerySession.start(agent, cwd, sessionId, store, this.#connector, signal),
84791
- async (runtime) => await runtime.previewEvents(nativeSessionId, eventLimit, additionalDirectories, signal),
84792
- async (runtime) => await runtime.closeProcess()
85050
+ query.signal,
85051
+ () => AcpQuerySession.start(scoped, store, this.#connector),
85052
+ (runtime) => runtime.previewEvents(nativeSessionId, eventLimit, query.signal),
85053
+ (runtime) => runtime.closeProcess()
84793
85054
  );
84794
85055
  } catch (error62) {
84795
- if (this.#eventPreviewsBySession.get(sessionId)?.store === store) {
84796
- this.#eventPreviewsBySession.delete(sessionId);
85056
+ if (this.#eventPreviewsBySession.get(key)?.store === store) {
85057
+ this.#eventPreviewsBySession.delete(key);
84797
85058
  }
84798
85059
  store.close();
84799
85060
  throw error62;
@@ -84802,7 +85063,7 @@ var init_query_processes = __esm({
84802
85063
  close = async () => {
84803
85064
  await Promise.all(
84804
85065
  [...this.#processesByAgent.values()].flatMap(
84805
- (readers) => readers.entries().map(async ([cwd, runtime]) => await this.retire(readers, cwd, runtime))
85066
+ (readers) => readers.entries().map(async ([key, runtime]) => await this.retire(readers, key, runtime))
84806
85067
  )
84807
85068
  );
84808
85069
  this.#processesByAgent.clear();
@@ -84817,39 +85078,104 @@ var init_query_processes = __esm({
84817
85078
  });
84818
85079
 
84819
85080
  // src/engine/acp/adapter/claude/adapter.ts
85081
+ import { methods as methods13 } from "@agentclientprotocol/sdk";
84820
85082
  var ClaudeAdapter;
84821
85083
  var init_adapter = __esm({
84822
85084
  "src/engine/acp/adapter/claude/adapter.ts"() {
84823
85085
  "use strict";
84824
85086
  init_run_cleanup();
84825
- init_live_sessions();
85087
+ init_native_session();
85088
+ init_execution_connections();
85089
+ init_lifecycle_output();
84826
85090
  init_native_session_lookup();
84827
85091
  init_query_processes();
84828
85092
  init_session_events();
84829
85093
  ClaudeAdapter = class {
84830
85094
  #queryProcesses;
84831
85095
  #connector;
84832
- #liveSessions;
85096
+ #executionConnections;
84833
85097
  constructor(agent, dependencies) {
84834
85098
  this.#connector = new AcpSessionConnector(dependencies.contentExternalizer);
84835
- this.#liveSessions = new AcpLiveSessions(dependencies.contentExternalizer);
85099
+ this.#executionConnections = new AcpExecutionConnections(dependencies.contentExternalizer);
84836
85100
  this.#queryProcesses = new AgentQueryProcesses(agent, dependencies.processes, this.#connector);
84837
85101
  }
84838
85102
  refreshAgent = (agent) => this.#queryProcesses.refreshAgent(agent);
84839
- getCapabilities = (cwd, signal) => this.#queryProcesses.capabilities(cwd, signal);
84840
- connectSession = (options) => this.#liveSessions.connectSession(options);
84841
- cancel = (...args) => this.#liveSessions.cancel(...args);
84842
- closeSession = (...args) => this.#liveSessions.closeSession(...args);
84843
- prompt = (...args) => this.#liveSessions.prompt(...args);
84844
- steer = (...args) => this.#liveSessions.steer(...args);
84845
- renameSession = (...args) => this.#liveSessions.renameSession(...args);
84846
- configureSession = (...args) => this.#liveSessions.configureSession(...args);
84847
- listSessions = (cwd, cursor, signal) => this.#queryProcesses.listNativeSessions(cwd, cursor, signal);
84848
- findSession = (cwd, nativeSessionId, budget, signal) => findNativeSession(this.listSessions, cwd, nativeSessionId, budget, signal);
84849
- readSessionHistory = (cwd, additionalDirectories, request, signal) => this.#queryProcesses.previewSessionEvents(cwd, additionalDirectories, request, signal);
85103
+ getCapabilities = async (query) => await this.#queryProcesses.capabilities(query);
85104
+ createSession = (params) => this.#executionConnections.withConnection(params, async (execution, signal) => {
85105
+ const { connection } = execution;
85106
+ const response = await connection.race(
85107
+ connection.connection.agent.request(methods13.agent.session.new, sessionWorkspace(params.scope), {
85108
+ cancellationSignal: signal
85109
+ }),
85110
+ "ACP agent exited while starting a session",
85111
+ signal
85112
+ );
85113
+ const nativeSessionId = createdNativeSessionId(response);
85114
+ this.#executionConnections.bind(execution, nativeSessionId);
85115
+ return normalizeOpenedSession(execution, nativeSessionId, response, signal);
85116
+ });
85117
+ forkSession = (params) => this.#executionConnections.withConnection(params, async (execution, signal) => {
85118
+ const { connection } = execution;
85119
+ const response = await connection.race(
85120
+ connection.connection.agent.request(
85121
+ methods13.agent.session.fork,
85122
+ {
85123
+ ...sessionWorkspace(params.scope),
85124
+ sessionId: nativeSessionIdSchema.parse(params.sourceNativeSessionId)
85125
+ },
85126
+ { cancellationSignal: signal }
85127
+ ),
85128
+ "ACP agent exited while forking a session",
85129
+ signal
85130
+ );
85131
+ const nativeSessionId = createdNativeSessionId(response);
85132
+ this.#executionConnections.bind(execution, nativeSessionId);
85133
+ return normalizeOpenedSession(execution, nativeSessionId, response, signal);
85134
+ });
85135
+ openSession = (params) => this.#executionConnections.withConnection(params, async (execution, signal) => {
85136
+ const { connection } = execution;
85137
+ const nativeSessionId = nativeSessionIdSchema.parse(params.nativeSessionId);
85138
+ this.#executionConnections.bind(execution, nativeSessionId);
85139
+ const response = await connection.race(
85140
+ connection.connection.agent.request(
85141
+ methods13.agent.session.resume,
85142
+ { ...sessionWorkspace(params.scope), sessionId: nativeSessionId },
85143
+ { cancellationSignal: signal }
85144
+ ),
85145
+ "ACP agent exited while resuming a session",
85146
+ signal
85147
+ );
85148
+ return normalizeOpenedSession(execution, nativeSessionId, response, signal);
85149
+ });
85150
+ openSessionWithReplay = (params) => this.#executionConnections.withConnection(params, async (execution, signal) => {
85151
+ const { connection } = execution;
85152
+ const nativeSessionId = nativeSessionIdSchema.parse(params.nativeSessionId);
85153
+ this.#executionConnections.bind(execution, nativeSessionId);
85154
+ const response = await connection.race(
85155
+ connection.connection.agent.request(
85156
+ methods13.agent.session.load,
85157
+ { ...sessionWorkspace(params.scope), sessionId: nativeSessionId },
85158
+ { cancellationSignal: signal }
85159
+ ),
85160
+ "ACP agent exited while loading a session",
85161
+ signal
85162
+ );
85163
+ await connection.race(connection.events.drained(), "ACP agent exited while loading a session", signal);
85164
+ return normalizeOpenedSession(execution, nativeSessionId, response, signal);
85165
+ });
85166
+ cancel = (...args) => this.#executionConnections.cancel(...args);
85167
+ closeSession = (...args) => this.#executionConnections.closeSession(...args);
85168
+ releaseSession = (params) => this.#executionConnections.releaseSession(params);
85169
+ prompt = (...args) => this.#executionConnections.prompt(...args);
85170
+ steer = (...args) => this.#executionConnections.steer(...args);
85171
+ renameSession = (...args) => this.#executionConnections.renameSession(...args);
85172
+ configureSession = (...args) => this.#executionConnections.configureSession(...args);
85173
+ listSessions = async ({ query, cursor }) => await this.#queryProcesses.listNativeSessions(query, cursor);
85174
+ findSession = ({ query, nativeSessionId, budget }) => findNativeSession(this.listSessions, query, nativeSessionId, budget);
85175
+ readSessionHistory = async ({ query, request }) => await this.#queryProcesses.previewSessionEvents(query, request);
84850
85176
  close = async () => await runCleanup(
84851
85177
  () => this.#queryProcesses.close(),
84852
- () => this.#liveSessions.close()
85178
+ () => this.#executionConnections.close()
84853
85179
  );
84854
85180
  };
84855
85181
  }
@@ -90765,6 +91091,7 @@ var init_tool_event = __esm({
90765
91091
 
90766
91092
  // src/engine/acp/adapter/codex/adapter.ts
90767
91093
  import { createHash as createHash5 } from "node:crypto";
91094
+ import { methods as methods14 } from "@agentclientprotocol/sdk";
90768
91095
  var CodexAdapter;
90769
91096
  var init_adapter2 = __esm({
90770
91097
  "src/engine/acp/adapter/codex/adapter.ts"() {
@@ -90776,7 +91103,8 @@ var init_adapter2 = __esm({
90776
91103
  init_app_server_client();
90777
91104
  init_history2();
90778
91105
  init_native_session();
90779
- init_live_sessions();
91106
+ init_execution_connections();
91107
+ init_lifecycle_output();
90780
91108
  init_native_session_lookup();
90781
91109
  init_preview_event_cache();
90782
91110
  init_query_processes();
@@ -90786,7 +91114,7 @@ var init_adapter2 = __esm({
90786
91114
  #agent;
90787
91115
  #queryProcesses;
90788
91116
  #connector;
90789
- #liveSessions;
91117
+ #executionConnections;
90790
91118
  #dependencies;
90791
91119
  #contentExternalizer;
90792
91120
  #previewCache = null;
@@ -90802,37 +91130,112 @@ var init_adapter2 = __esm({
90802
91130
  }
90803
91131
  };
90804
91132
  this.#connector = new AcpSessionConnector(this.#contentExternalizer, fitCodexToolEvent);
90805
- this.#liveSessions = new AcpLiveSessions(this.#contentExternalizer, fitCodexToolEvent);
91133
+ this.#executionConnections = new AcpExecutionConnections(this.#contentExternalizer, fitCodexToolEvent);
90806
91134
  this.#queryProcesses = new AgentQueryProcesses(agent, dependencies.processes, this.#connector);
90807
91135
  }
90808
91136
  refreshAgent = (agent) => {
90809
91137
  this.#agent = agent;
90810
91138
  this.#queryProcesses.refreshAgent(agent);
90811
91139
  };
90812
- getCapabilities = (cwd, signal) => this.#queryProcesses.capabilities(cwd, signal);
90813
- connectSession = (options) => this.#liveSessions.connectSession(options);
90814
- cancel = async (target, signal) => {
90815
- await this.#liveSessions.closeSession(target, signal);
91140
+ getCapabilities = async (query) => await this.#queryProcesses.capabilities(query);
91141
+ #executionParams = (params) => {
91142
+ const externalize = params.scope.externalizeUpdate;
91143
+ return externalize === void 0 ? params : {
91144
+ ...params,
91145
+ scope: {
91146
+ ...params.scope,
91147
+ externalizeUpdate: (update, signal) => externalize(prepareCodexToolUpdate(update), signal)
91148
+ }
91149
+ };
91150
+ };
91151
+ createSession = (params) => this.#executionConnections.withConnection(this.#executionParams(params), async (execution, signal) => {
91152
+ const { connection } = execution;
91153
+ const response = await connection.race(
91154
+ connection.connection.agent.request(methods14.agent.session.new, sessionWorkspace(params.scope), {
91155
+ cancellationSignal: signal
91156
+ }),
91157
+ "ACP agent exited while starting a session",
91158
+ signal
91159
+ );
91160
+ const nativeSessionId = createdNativeSessionId(response);
91161
+ this.#executionConnections.bind(execution, nativeSessionId);
91162
+ return normalizeOpenedSession(execution, nativeSessionId, response, signal);
91163
+ });
91164
+ forkSession = (params) => this.#executionConnections.withConnection(this.#executionParams(params), async (execution, signal) => {
91165
+ const { connection } = execution;
91166
+ const response = await connection.race(
91167
+ connection.connection.agent.request(
91168
+ methods14.agent.session.fork,
91169
+ {
91170
+ ...sessionWorkspace(params.scope),
91171
+ sessionId: nativeSessionIdSchema.parse(params.sourceNativeSessionId)
91172
+ },
91173
+ { cancellationSignal: signal }
91174
+ ),
91175
+ "ACP agent exited while forking a session",
91176
+ signal
91177
+ );
91178
+ const nativeSessionId = createdNativeSessionId(response);
91179
+ this.#executionConnections.bind(execution, nativeSessionId);
91180
+ return normalizeOpenedSession(execution, nativeSessionId, response, signal);
91181
+ });
91182
+ openSession = (params) => this.#executionConnections.withConnection(this.#executionParams(params), async (execution, signal) => {
91183
+ const { connection } = execution;
91184
+ const nativeSessionId = nativeSessionIdSchema.parse(params.nativeSessionId);
91185
+ this.#executionConnections.bind(execution, nativeSessionId);
91186
+ const response = await connection.race(
91187
+ connection.connection.agent.request(
91188
+ methods14.agent.session.resume,
91189
+ { ...sessionWorkspace(params.scope), sessionId: nativeSessionId },
91190
+ { cancellationSignal: signal }
91191
+ ),
91192
+ "ACP agent exited while resuming a session",
91193
+ signal
91194
+ );
91195
+ return normalizeOpenedSession(execution, nativeSessionId, response, signal);
91196
+ });
91197
+ openSessionWithReplay = (params) => this.#executionConnections.withConnection(this.#executionParams(params), async (execution, signal) => {
91198
+ const { connection } = execution;
91199
+ const nativeSessionId = nativeSessionIdSchema.parse(params.nativeSessionId);
91200
+ this.#executionConnections.bind(execution, nativeSessionId);
91201
+ const response = await connection.race(
91202
+ connection.connection.agent.request(
91203
+ methods14.agent.session.load,
91204
+ { ...sessionWorkspace(params.scope), sessionId: nativeSessionId },
91205
+ { cancellationSignal: signal }
91206
+ ),
91207
+ "ACP agent exited while loading a session",
91208
+ signal
91209
+ );
91210
+ await connection.race(connection.events.drained(), "ACP agent exited while loading a session", signal);
91211
+ return normalizeOpenedSession(execution, nativeSessionId, response, signal);
91212
+ });
91213
+ cancel = async (params) => {
91214
+ await this.#executionConnections.closeSession(params);
90816
91215
  return "closed";
90817
91216
  };
90818
- closeSession = (...args) => this.#liveSessions.closeSession(...args);
90819
- prompt = (...args) => this.#liveSessions.prompt(...args);
90820
- steer = (...args) => this.#liveSessions.steer(...args);
90821
- renameSession = (...args) => this.#liveSessions.renameSession(...args);
90822
- configureSession = (...args) => this.#liveSessions.configureSession(...args);
90823
- listSessions = (cwd, cursor, signal) => this.#queryProcesses.listNativeSessions(cwd, cursor, signal);
90824
- findSession = (cwd, nativeSessionId, budget, signal) => findNativeSession(this.listSessions, cwd, nativeSessionId, budget, signal);
91217
+ closeSession = (...args) => this.#executionConnections.closeSession(...args);
91218
+ releaseSession = (params) => this.#executionConnections.releaseSession(params);
91219
+ prompt = (...args) => this.#executionConnections.prompt(...args);
91220
+ steer = (...args) => this.#executionConnections.steer(...args);
91221
+ renameSession = (...args) => this.#executionConnections.renameSession(...args);
91222
+ configureSession = (...args) => this.#executionConnections.configureSession(...args);
91223
+ listSessions = async ({ query, cursor }) => await this.#queryProcesses.listNativeSessions(query, cursor);
91224
+ findSession = ({ query, nativeSessionId, budget }) => findNativeSession(this.listSessions, query, nativeSessionId, budget);
90825
91225
  close = async () => {
90826
91226
  await runCleanup(
90827
91227
  () => this.#queryProcesses.close(),
90828
- () => this.#liveSessions.close(),
91228
+ () => this.#executionConnections.close(),
90829
91229
  () => this.#previewCache?.close()
90830
91230
  );
90831
91231
  };
90832
- readSessionHistory = async (cwd, _additionalDirectories, request, cancellation) => {
90833
- const agent = this.#agent;
90834
- const signal = AbortSignal.any([cancellation, AbortSignal.timeout(6e4)]);
90835
- const { sessionId } = request;
91232
+ readSessionHistory = async ({
91233
+ query,
91234
+ request
91235
+ }) => {
91236
+ const { agent, cwd } = query;
91237
+ const signal = AbortSignal.any([query.signal, AbortSignal.timeout(6e4)]);
91238
+ const sessionId = request.nativeSessionId;
90836
91239
  signal.throwIfAborted();
90837
91240
  nativeSessionIdSchema.parse(request.nativeSessionId);
90838
91241
  if (agent.id !== "codex") {
@@ -90883,7 +91286,7 @@ var init_adapter2 = __esm({
90883
91286
  client2,
90884
91287
  request.nativeSessionId,
90885
91288
  async (update) => {
90886
- const externalized = await this.#contentExternalizer.update(sessionId, update, signal);
91289
+ const externalized = query.externalizeUpdate === void 0 ? await this.#contentExternalizer.update(sessionId, update, signal) : await query.externalizeUpdate(prepareCodexToolUpdate(update), signal);
90887
91290
  for (const event of externalized.events) {
90888
91291
  events.push({
90889
91292
  type: "acp",
@@ -90905,39 +91308,104 @@ var init_adapter2 = __esm({
90905
91308
  });
90906
91309
 
90907
91310
  // src/engine/acp/adapter/pi/adapter.ts
91311
+ import { methods as methods15 } from "@agentclientprotocol/sdk";
90908
91312
  var PiAdapter;
90909
91313
  var init_adapter3 = __esm({
90910
91314
  "src/engine/acp/adapter/pi/adapter.ts"() {
90911
91315
  "use strict";
90912
91316
  init_run_cleanup();
90913
- init_live_sessions();
91317
+ init_native_session();
91318
+ init_execution_connections();
91319
+ init_lifecycle_output();
90914
91320
  init_native_session_lookup();
90915
91321
  init_query_processes();
90916
91322
  init_session_events();
90917
91323
  PiAdapter = class {
90918
91324
  #queryProcesses;
90919
91325
  #connector;
90920
- #liveSessions;
91326
+ #executionConnections;
90921
91327
  constructor(agent, dependencies) {
90922
91328
  this.#connector = new AcpSessionConnector(dependencies.contentExternalizer);
90923
- this.#liveSessions = new AcpLiveSessions(dependencies.contentExternalizer);
91329
+ this.#executionConnections = new AcpExecutionConnections(dependencies.contentExternalizer);
90924
91330
  this.#queryProcesses = new AgentQueryProcesses(agent, dependencies.processes, this.#connector);
90925
91331
  }
90926
91332
  refreshAgent = (agent) => this.#queryProcesses.refreshAgent(agent);
90927
- getCapabilities = (cwd, signal) => this.#queryProcesses.capabilities(cwd, signal);
90928
- connectSession = (options) => this.#liveSessions.connectSession(options);
90929
- cancel = (...args) => this.#liveSessions.cancel(...args);
90930
- closeSession = (...args) => this.#liveSessions.closeSession(...args);
90931
- prompt = (...args) => this.#liveSessions.prompt(...args);
90932
- steer = (...args) => this.#liveSessions.steer(...args);
90933
- renameSession = (...args) => this.#liveSessions.renameSession(...args);
90934
- configureSession = (...args) => this.#liveSessions.configureSession(...args);
90935
- listSessions = (cwd, cursor, signal) => this.#queryProcesses.listNativeSessions(cwd, cursor, signal);
90936
- findSession = (cwd, nativeSessionId, budget, signal) => findNativeSession(this.listSessions, cwd, nativeSessionId, budget, signal);
90937
- readSessionHistory = (cwd, additionalDirectories, request, signal) => this.#queryProcesses.previewSessionEvents(cwd, additionalDirectories, request, signal);
91333
+ getCapabilities = async (query) => await this.#queryProcesses.capabilities(query);
91334
+ createSession = (params) => this.#executionConnections.withConnection(params, async (execution, signal) => {
91335
+ const { connection } = execution;
91336
+ const response = await connection.race(
91337
+ connection.connection.agent.request(methods15.agent.session.new, sessionWorkspace(params.scope), {
91338
+ cancellationSignal: signal
91339
+ }),
91340
+ "ACP agent exited while starting a session",
91341
+ signal
91342
+ );
91343
+ const nativeSessionId = createdNativeSessionId(response);
91344
+ this.#executionConnections.bind(execution, nativeSessionId);
91345
+ return normalizeOpenedSession(execution, nativeSessionId, response, signal);
91346
+ });
91347
+ forkSession = (params) => this.#executionConnections.withConnection(params, async (execution, signal) => {
91348
+ const { connection } = execution;
91349
+ const response = await connection.race(
91350
+ connection.connection.agent.request(
91351
+ methods15.agent.session.fork,
91352
+ {
91353
+ ...sessionWorkspace(params.scope),
91354
+ sessionId: nativeSessionIdSchema.parse(params.sourceNativeSessionId)
91355
+ },
91356
+ { cancellationSignal: signal }
91357
+ ),
91358
+ "ACP agent exited while forking a session",
91359
+ signal
91360
+ );
91361
+ const nativeSessionId = createdNativeSessionId(response);
91362
+ this.#executionConnections.bind(execution, nativeSessionId);
91363
+ return normalizeOpenedSession(execution, nativeSessionId, response, signal);
91364
+ });
91365
+ openSession = (params) => this.#executionConnections.withConnection(params, async (execution, signal) => {
91366
+ const { connection } = execution;
91367
+ const nativeSessionId = nativeSessionIdSchema.parse(params.nativeSessionId);
91368
+ this.#executionConnections.bind(execution, nativeSessionId);
91369
+ const response = await connection.race(
91370
+ connection.connection.agent.request(
91371
+ methods15.agent.session.resume,
91372
+ { ...sessionWorkspace(params.scope), sessionId: nativeSessionId },
91373
+ { cancellationSignal: signal }
91374
+ ),
91375
+ "ACP agent exited while resuming a session",
91376
+ signal
91377
+ );
91378
+ return normalizeOpenedSession(execution, nativeSessionId, response, signal);
91379
+ });
91380
+ openSessionWithReplay = (params) => this.#executionConnections.withConnection(params, async (execution, signal) => {
91381
+ const { connection } = execution;
91382
+ const nativeSessionId = nativeSessionIdSchema.parse(params.nativeSessionId);
91383
+ this.#executionConnections.bind(execution, nativeSessionId);
91384
+ const response = await connection.race(
91385
+ connection.connection.agent.request(
91386
+ methods15.agent.session.load,
91387
+ { ...sessionWorkspace(params.scope), sessionId: nativeSessionId },
91388
+ { cancellationSignal: signal }
91389
+ ),
91390
+ "ACP agent exited while loading a session",
91391
+ signal
91392
+ );
91393
+ await connection.race(connection.events.drained(), "ACP agent exited while loading a session", signal);
91394
+ return normalizeOpenedSession(execution, nativeSessionId, response, signal);
91395
+ });
91396
+ cancel = (...args) => this.#executionConnections.cancel(...args);
91397
+ closeSession = (...args) => this.#executionConnections.closeSession(...args);
91398
+ releaseSession = (params) => this.#executionConnections.releaseSession(params);
91399
+ prompt = (...args) => this.#executionConnections.prompt(...args);
91400
+ steer = (...args) => this.#executionConnections.steer(...args);
91401
+ renameSession = (...args) => this.#executionConnections.renameSession(...args);
91402
+ configureSession = (...args) => this.#executionConnections.configureSession(...args);
91403
+ listSessions = async ({ query, cursor }) => await this.#queryProcesses.listNativeSessions(query, cursor);
91404
+ findSession = ({ query, nativeSessionId, budget }) => findNativeSession(this.listSessions, query, nativeSessionId, budget);
91405
+ readSessionHistory = async ({ query, request }) => await this.#queryProcesses.previewSessionEvents(query, request);
90938
91406
  close = async () => await runCleanup(
90939
91407
  () => this.#queryProcesses.close(),
90940
- () => this.#liveSessions.close()
91408
+ () => this.#executionConnections.close()
90941
91409
  );
90942
91410
  };
90943
91411
  }
@@ -91255,10 +91723,12 @@ var init_content_externalizer = __esm({
91255
91723
 
91256
91724
  // src/engine/agent/runtime-agents.ts
91257
91725
  function createRuntimeAdapterRegistry(adapters, processes, externalize, linkedResources) {
91258
- return new AdapterRegistry(adapters, {
91259
- processes,
91260
- contentExternalizer: new AcpContentExternalizer(externalize, linkedResources)
91261
- });
91726
+ const contentExternalizer = new AcpContentExternalizer(externalize, linkedResources);
91727
+ const externalizeSessionUpdate = (sessionId, update, signal) => contentExternalizer.update(sessionId, update, signal);
91728
+ return {
91729
+ adapters: new AdapterRegistry(adapters, { processes, contentExternalizer }),
91730
+ externalizeSessionUpdate
91731
+ };
91262
91732
  }
91263
91733
  var RuntimeAgentDependencies;
91264
91734
  var init_runtime_agents = __esm({
@@ -93522,7 +93992,6 @@ var init_agent_turn = __esm({
93522
93992
  });
93523
93993
 
93524
93994
  // src/engine/session/live/session-restore.ts
93525
- import { methods as methods13 } from "@agentclientprotocol/sdk";
93526
93995
  function hasMethodNotFoundCode(cause) {
93527
93996
  const visited = /* @__PURE__ */ new Set();
93528
93997
  let current = cause;
@@ -93540,7 +94009,6 @@ async function restoreSession(session, signal, recovery, origin) {
93540
94009
  if (origin !== void 0) {
93541
94010
  session.setSessionTitle(origin.title);
93542
94011
  }
93543
- await session.initializeAgent(signal);
93544
94012
  let stored = session.metrics.measureSync(
93545
94013
  "session-state-read",
93546
94014
  () => origin?.kind === "import" ? new FoundStoredSession(
@@ -93560,7 +94028,7 @@ async function restoreSession(session, signal, recovery, origin) {
93560
94028
  stored = session.metrics.measureSync("session-state-read", () => session.store.read(session.sessionId));
93561
94029
  }
93562
94030
  const forkSource = origin?.kind === "fork" ? session.store.findNative(session.agentId, origin.nativeSessionId)[0] : void 0;
93563
- let lifecycleResponse2;
94031
+ let opened;
93564
94032
  if (origin?.kind === "fork") {
93565
94033
  if (!session.capabilities.unstableForkSession) {
93566
94034
  throw new AcpExecutionError(
@@ -93578,22 +94046,9 @@ async function restoreSession(session, signal, recovery, origin) {
93578
94046
  }
93579
94047
  const forked = await session.metrics.measure(
93580
94048
  "session-fork",
93581
- async () => await session.race(
93582
- session.agentRequest(
93583
- methods13.agent.session.fork,
93584
- {
93585
- sessionId: nativeSessionIdSchema.parse(origin.nativeSessionId),
93586
- cwd: session.cwd,
93587
- additionalDirectories: [...session.additionalDirectories],
93588
- mcpServers: []
93589
- },
93590
- { cancellationSignal: signal }
93591
- ),
93592
- "ACP agent exited while forking a session",
93593
- signal
93594
- )
94049
+ async () => await session.forkSession(origin.nativeSessionId, signal)
93595
94050
  );
93596
- session.selectNativeSession(forked.sessionId);
94051
+ session.selectNativeSession(forked.nativeSessionId);
93597
94052
  if (session.nativeSessionId() === origin.nativeSessionId || session.store.findNative(session.agentId, session.nativeSessionId()).length > 0) {
93598
94053
  throw new AcpExecutionError(
93599
94054
  "The Agent did not create an independent fork",
@@ -93606,7 +94061,7 @@ async function restoreSession(session, signal, recovery, origin) {
93606
94061
  if (recovery.kind === "execution-only") {
93607
94062
  session.startExecutionOnlyCapture();
93608
94063
  }
93609
- lifecycleResponse2 = forked;
94064
+ opened = forked;
93610
94065
  } else if (stored instanceof FoundStoredSession && stored.session.agentId === session.agentId && stored.session.cwd === session.cwd && arraysEqual(stored.session.additionalDirectories, session.additionalDirectories)) {
93611
94066
  session.selectNativeSession(stored.session.nativeSessionId);
93612
94067
  session.setPrompted(stored.session.prompted);
@@ -93620,29 +94075,13 @@ async function restoreSession(session, signal, recovery, origin) {
93620
94075
  "native_history_unsupported"
93621
94076
  );
93622
94077
  }
93623
- lifecycleResponse2 = await session.metrics.measure(
94078
+ opened = await session.metrics.measure(
93624
94079
  "session-load",
93625
- async () => (await session.loadSession(signal, "ACP agent exited while loading a session")).response
94080
+ async () => await session.openSessionWithReplay(signal)
93626
94081
  );
93627
94082
  } else if (recovery.kind === "execution-only") {
93628
94083
  try {
93629
- lifecycleResponse2 = await session.metrics.measure(
93630
- "session-resume",
93631
- async () => await session.race(
93632
- session.agentRequest(
93633
- methods13.agent.session.resume,
93634
- {
93635
- additionalDirectories: [...session.additionalDirectories],
93636
- cwd: session.cwd,
93637
- mcpServers: [],
93638
- sessionId: session.nativeSessionId()
93639
- },
93640
- { cancellationSignal: signal }
93641
- ),
93642
- "ACP agent exited while resuming a session",
93643
- signal
93644
- )
93645
- );
94084
+ opened = await session.metrics.measure("session-resume", async () => await session.openSession(signal));
93646
94085
  } catch (cause) {
93647
94086
  signal.throwIfAborted();
93648
94087
  if (cause instanceof AcpExecutionError && !hasMethodNotFoundCode(cause)) {
@@ -93656,27 +94095,11 @@ async function restoreSession(session, signal, recovery, origin) {
93656
94095
  }
93657
94096
  session.startExecutionOnlyCapture();
93658
94097
  } else if (session.capabilities.resumeSession) {
93659
- lifecycleResponse2 = await session.metrics.measure(
93660
- "session-resume",
93661
- async () => await session.race(
93662
- session.agentRequest(
93663
- methods13.agent.session.resume,
93664
- {
93665
- additionalDirectories: [...session.additionalDirectories],
93666
- cwd: session.cwd,
93667
- mcpServers: [],
93668
- sessionId: session.nativeSessionId()
93669
- },
93670
- { cancellationSignal: signal }
93671
- ),
93672
- "ACP agent exited while resuming a session",
93673
- signal
93674
- )
93675
- );
94098
+ opened = await session.metrics.measure("session-resume", async () => await session.openSession(signal));
93676
94099
  } else if (session.capabilities.loadSession) {
93677
- lifecycleResponse2 = await session.metrics.measure(
94100
+ opened = await session.metrics.measure(
93678
94101
  "session-load",
93679
- async () => (await session.loadSession(signal, "ACP agent exited while loading a session")).response
94102
+ async () => await session.openSessionWithReplay(signal)
93680
94103
  );
93681
94104
  } else {
93682
94105
  throw new AcpExecutionError(
@@ -93696,37 +94119,20 @@ async function restoreSession(session, signal, recovery, origin) {
93696
94119
  }
93697
94120
  session.store.remove(session.sessionId);
93698
94121
  }
93699
- const created = await session.metrics.measure(
93700
- "session-new",
93701
- async () => await session.race(
93702
- session.agentRequest(
93703
- methods13.agent.session.new,
93704
- {
93705
- additionalDirectories: [...session.additionalDirectories],
93706
- cwd: session.cwd,
93707
- mcpServers: []
93708
- },
93709
- { cancellationSignal: signal }
93710
- ),
93711
- "ACP agent exited while starting a session",
93712
- signal
93713
- )
93714
- );
93715
- session.selectNativeSession(created.sessionId);
94122
+ const created = await session.metrics.measure("session-new", async () => await session.createSession(signal));
94123
+ session.selectNativeSession(created.nativeSessionId);
93716
94124
  session.setNativeHistoryOwnership({ kind: "fresh-session" });
93717
94125
  if (recovery.kind === "execution-only") {
93718
94126
  session.startExecutionOnlyCapture();
93719
94127
  }
93720
- lifecycleResponse2 = created;
94128
+ opened = created;
93721
94129
  }
93722
- session.restrictSessionCapabilities(lifecycleResponse2);
93723
- session.setConfigOptions(session.sessionConfigProtocol.normalizeLifecycle(lifecycleResponse2));
94130
+ session.applySessionOpened(opened);
93724
94131
  if (forkSource !== void 0) {
93725
94132
  await session.restoreStoredConfigurations(forkSource, signal, "fork");
93726
94133
  } else if (stored instanceof FoundStoredSession && session.restored) {
93727
94134
  await session.restoreStoredConfigurations(stored.session, signal);
93728
94135
  }
93729
- await session.drained();
93730
94136
  signal.throwIfAborted();
93731
94137
  session.writeStoredSession(
93732
94138
  stored instanceof FoundStoredSession && session.restored ? stored.session.updatedAt : (/* @__PURE__ */ new Date()).toISOString()
@@ -93743,7 +94149,6 @@ var init_session_restore = __esm({
93743
94149
  });
93744
94150
 
93745
94151
  // src/engine/session/live/agent-session.ts
93746
- import { methods as methods14 } from "@agentclientprotocol/sdk";
93747
94152
  var AgentSession;
93748
94153
  var init_agent_session = __esm({
93749
94154
  "src/engine/session/live/agent-session.ts"() {
@@ -93754,7 +94159,6 @@ var init_agent_session = __esm({
93754
94159
  init_agent_initialization();
93755
94160
  init_prompt_content();
93756
94161
  init_session_capabilities();
93757
- init_session_config_protocol();
93758
94162
  init_serial_task_queue();
93759
94163
  init_value_utils();
93760
94164
  init_session_api();
@@ -93790,14 +94194,20 @@ var init_agent_session = __esm({
93790
94194
  get sessionId() {
93791
94195
  return this.#mobiusSessionId;
93792
94196
  }
93793
- get sessionConfigProtocol() {
93794
- return this.#sessionConfigProtocol;
93795
- }
93796
94197
  get store() {
93797
94198
  return this.#store;
93798
94199
  }
93799
- hasBackgroundActivity = () => this.#connection.hasBackgroundActivity();
93800
- #connection;
94200
+ hasBackgroundActivity = () => this.#backgroundActivity !== "none";
94201
+ #backgroundActivity = "none";
94202
+ #modelEffort = null;
94203
+ #scope;
94204
+ #subscriber;
94205
+ #nativeIdentity = {
94206
+ kind: "unbound"
94207
+ };
94208
+ get #nativeSessionId() {
94209
+ return this.#nativeIdentity.kind === "bound" ? this.#nativeIdentity.nativeSessionId : "";
94210
+ }
93801
94211
  #adapter;
93802
94212
  #additionalDirectories;
93803
94213
  #agentId;
@@ -93806,11 +94216,8 @@ var init_agent_session = __esm({
93806
94216
  #getObserver;
93807
94217
  #interactions;
93808
94218
  #mobiusSessionId;
93809
- #updates;
93810
94219
  #metrics;
93811
- #sessionConfigProtocol;
93812
94220
  #store;
93813
- #verifiedAgentVersion;
93814
94221
  #agentName = "";
93815
94222
  #agentVersion = "";
93816
94223
  #capabilities = unsupportedSessionCapabilities();
@@ -93826,7 +94233,7 @@ var init_agent_session = __esm({
93826
94233
  #sessionTitle = null;
93827
94234
  #sessionUpdatedAt = "";
93828
94235
  #turn = new IdleAgentTurn();
93829
- constructor(agent, cwd, additionalDirectories, mobiusSessionId, getObserver, store, metrics, adapter) {
94236
+ constructor(agent, cwd, additionalDirectories, mobiusSessionId, getObserver, store, metrics, adapter, externalize) {
93830
94237
  this.#additionalDirectories = [...additionalDirectories];
93831
94238
  this.#adapter = adapter;
93832
94239
  this.#agentId = agent.id;
@@ -93835,9 +94242,7 @@ var init_agent_session = __esm({
93835
94242
  this.#environment = agent.environment;
93836
94243
  this.#mobiusSessionId = mobiusSessionId;
93837
94244
  this.#metrics = metrics;
93838
- this.#sessionConfigProtocol = sessionConfigProtocolForAgent(agent.id);
93839
94245
  this.#store = store;
93840
- this.#verifiedAgentVersion = agent.agentVersion;
93841
94246
  this.#getObserver = getObserver;
93842
94247
  this.#interactions = new SessionInteractions({
93843
94248
  cwd: () => this.#cwd,
@@ -93848,25 +94253,31 @@ var init_agent_session = __esm({
93848
94253
  observer: getObserver,
93849
94254
  recordSessionEvent: this.recordLifecycleEvent
93850
94255
  });
93851
- const scope = {
94256
+ this.#scope = {
93852
94257
  agent,
93853
94258
  cwd,
93854
- sessionId: () => this.#mobiusSessionId,
93855
- configOptions: () => this.#configOptions,
93856
- onEvent: this.#processEvent
93857
- };
93858
- this.#connection = this.#adapter.connectSession({
93859
- ...scope,
93860
94259
  additionalDirectories: this.#additionalDirectories,
93861
- capabilities: () => this.#capabilities,
93862
- onBackgroundActivity: (activity) => this.#getObserver().onBackgroundActivity?.(this, activity),
94260
+ ...externalize === void 0 ? {} : { externalizeUpdate: (update, signal) => externalize(this.#mobiusSessionId, update, signal) }
94261
+ };
94262
+ this.#subscriber = {
94263
+ onSessionEvent: async (nativeSessionId, event) => {
94264
+ if (this.#nativeSessionId.length === 0) {
94265
+ this.selectNativeSession(nativeSessionId);
94266
+ } else {
94267
+ this.assertNativeSession(nativeSessionId);
94268
+ }
94269
+ await this.#processEvent(event);
94270
+ },
94271
+ onBackgroundActivity: (activity) => {
94272
+ this.#backgroundActivity = activity;
94273
+ this.#getObserver().onBackgroundActivity?.(this, activity);
94274
+ },
93863
94275
  interactions: {
93864
94276
  onPermission: this.#interactions.onPermission,
93865
94277
  onElicitation: this.#interactions.onElicitation,
93866
94278
  onElicitationComplete: this.#interactions.onElicitationComplete
93867
94279
  }
93868
- });
93869
- this.#updates = this.#connection.events;
94280
+ };
93870
94281
  }
93871
94282
  static async #start(options, getObserver, store, initialize, metrics, adapter) {
93872
94283
  for (let attempt = 1; attempt <= 2; attempt += 1) {
@@ -93884,7 +94295,8 @@ var init_agent_session = __esm({
93884
94295
  getObserver,
93885
94296
  store,
93886
94297
  metrics,
93887
- adapter
94298
+ adapter,
94299
+ options.externalizeSessionUpdate
93888
94300
  )
93889
94301
  );
93890
94302
  try {
@@ -93907,11 +94319,14 @@ var init_agent_session = __esm({
93907
94319
  }
93908
94320
  throw new AcpExecutionError("ACP agent initialization failed");
93909
94321
  }
93910
- static start = async (options, recovery, getObserver, store, metrics, adapter) => await _AgentSession.#start(
94322
+ static start = async (options, recovery, getObserver, store, metrics, adapter, capabilities = unsupportedSessionCapabilities()) => await _AgentSession.#start(
93911
94323
  options,
93912
94324
  getObserver,
93913
94325
  store,
93914
- async (runtime) => await runtime.initialize(options.signal, recovery, options.origin),
94326
+ async (runtime) => {
94327
+ runtime.#capabilities = capabilities;
94328
+ await runtime.initialize(options.signal, recovery, options.origin);
94329
+ },
93915
94330
  metrics,
93916
94331
  adapter
93917
94332
  );
@@ -93924,7 +94339,7 @@ var init_agent_session = __esm({
93924
94339
  new StoredSession(
93925
94340
  this.#mobiusSessionId,
93926
94341
  this.#agentId,
93927
- this.#updates.sessionId(),
94342
+ this.#nativeSessionId,
93928
94343
  this.#cwd,
93929
94344
  this.#additionalDirectories,
93930
94345
  this.#prompted,
@@ -93946,9 +94361,9 @@ var init_agent_session = __esm({
93946
94361
  if (normalized.length === 0) {
93947
94362
  throw new AcpExecutionError("The Session title cannot be empty", {}, "invalid_session_title");
93948
94363
  }
93949
- const nativeSessionId = this.#updates.sessionId();
94364
+ const nativeSessionId = this.#nativeSessionId;
93950
94365
  if (nativeSessionId.length > 0) {
93951
- await this.#adapter.renameSession(this.#target(), normalized, signal);
94366
+ await this.#adapter.renameSession({ ...this.#target(), title: normalized, signal });
93952
94367
  }
93953
94368
  const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
93954
94369
  await this.#processEvent({
@@ -93963,7 +94378,7 @@ var init_agent_session = __esm({
93963
94378
  };
93964
94379
  #captureSelectedConfigurationValues = () => {
93965
94380
  this.#sessionConfigurations.capture(this.#configOptions);
93966
- if (this.#updates.sessionId().length > 0) {
94381
+ if (this.#nativeSessionId.length > 0) {
93967
94382
  this.writeStoredSession((/* @__PURE__ */ new Date()).toISOString());
93968
94383
  }
93969
94384
  };
@@ -93993,8 +94408,12 @@ var init_agent_session = __esm({
93993
94408
  }
93994
94409
  }
93995
94410
  };
93996
- restrictSessionCapabilities = (response) => {
93997
- this.#capabilities = restrictAcpSessionCapabilities(this.#capabilities, response);
94411
+ applySessionOpened = (opened) => {
94412
+ this.#agentName = opened.agentName;
94413
+ this.#agentVersion = opened.agentVersion;
94414
+ this.#modelEffort = opened.agentSettingsModelEffort;
94415
+ this.#capabilities = opened.capabilities;
94416
+ this.setConfigOptions(opened.configOptions);
93998
94417
  };
93999
94418
  prepared = () => new PreparedSession(
94000
94419
  this.#agentName,
@@ -94014,7 +94433,7 @@ var init_agent_session = __esm({
94014
94433
  "native_history_unsupported"
94015
94434
  );
94016
94435
  }
94017
- await this.#completedHistory(signal, "ACP agent exited while loading history");
94436
+ await this.#completedHistory(signal);
94018
94437
  };
94019
94438
  /** Starts live event capture without asking the native Agent to replay its persisted history. */
94020
94439
  startExecutionOnlyCapture = () => {
@@ -94034,26 +94453,33 @@ var init_agent_session = __esm({
94034
94453
  "native_history_unsupported"
94035
94454
  );
94036
94455
  }
94037
- const history = await this.#completedHistory(signal, "ACP agent exited while loading history");
94456
+ const history = await this.#completedHistory(signal);
94038
94457
  return history.eventPage(eventLimit, cursor);
94039
94458
  };
94040
- async #completedHistory(signal, exitMessage) {
94459
+ async #completedHistory(signal) {
94041
94460
  if (!this.#prompted && this.#nativeHistoryOwnership.kind === "fresh-session") {
94042
94461
  if (this.#sessionLoad.kind === "not-requested") {
94043
94462
  this.#store.events.reset(this.#mobiusSessionId);
94044
94463
  this.#sessionLoad = {
94045
94464
  history: new HistoryReplayCapture(this.#store.events, this.#mobiusSessionId),
94046
94465
  kind: "loaded",
94047
- response: {}
94466
+ opened: {
94467
+ nativeSessionId: this.nativeSessionId(),
94468
+ capabilities: this.#capabilities,
94469
+ configOptions: [],
94470
+ agentName: this.#agentName,
94471
+ agentVersion: this.#agentVersion,
94472
+ agentSettingsModelEffort: this.#modelEffort
94473
+ }
94048
94474
  };
94049
94475
  }
94050
94476
  if (this.#sessionLoad.kind === "loaded") {
94051
94477
  return this.#sessionLoad.history;
94052
94478
  }
94053
94479
  }
94054
- return (await this.#loadSession(signal, exitMessage)).history;
94480
+ return (await this.#loadSession(signal)).history;
94055
94481
  }
94056
- async #loadSession(signal, exitMessage) {
94482
+ async #loadSession(signal) {
94057
94483
  if (this.#sessionLoad.kind === "loaded") {
94058
94484
  return this.#sessionLoad;
94059
94485
  }
@@ -94064,24 +94490,13 @@ var init_agent_session = __esm({
94064
94490
  const history = new HistoryReplayCapture(this.#store.events, this.#mobiusSessionId);
94065
94491
  const completion = Promise.resolve().then(async () => {
94066
94492
  try {
94067
- const response = await this.race(
94068
- this.#connection.connection.agent.request(
94069
- methods14.agent.session.load,
94070
- {
94071
- additionalDirectories: [...this.#additionalDirectories],
94072
- cwd: this.#cwd,
94073
- mcpServers: [],
94074
- sessionId: this.#updates.sessionId()
94075
- },
94076
- { cancellationSignal: signal }
94077
- ),
94078
- exitMessage,
94079
- signal
94080
- );
94081
- await this.#updates.drained();
94493
+ const opened = await this.#adapter.openSessionWithReplay({
94494
+ ...this.#sessionParams(signal),
94495
+ nativeSessionId: this.nativeSessionId()
94496
+ });
94082
94497
  signal.throwIfAborted();
94083
- this.restrictSessionCapabilities(response);
94084
- const loaded = { history, kind: "loaded", response };
94498
+ this.#capabilities = opened.capabilities;
94499
+ const loaded = { history, kind: "loaded", opened };
94085
94500
  this.#sessionLoad = loaded;
94086
94501
  return loaded;
94087
94502
  } catch (cause) {
@@ -94092,24 +94507,10 @@ var init_agent_session = __esm({
94092
94507
  this.#sessionLoad = { completion, history, kind: "capturing" };
94093
94508
  return await completion;
94094
94509
  }
94095
- async #initializeAgent(signal) {
94096
- await this.#metrics.measure("agent-initialize", async () => await this.#initializeAgentOperation(signal));
94097
- }
94098
- async #initializeAgentOperation(signal) {
94099
- const initialized = await initializeAgentConnection(
94100
- this.#connection,
94101
- this.#agentId,
94102
- this.#verifiedAgentVersion,
94103
- signal
94104
- );
94105
- this.#capabilities = initialized.capabilities;
94106
- this.#agentName = initialized.agentName;
94107
- this.#agentVersion = initialized.agentVersion;
94108
- }
94109
94510
  initialize = async (signal, recovery, origin) => await restoreSession(this, signal, recovery, origin);
94110
- nativeSessionId = () => this.#updates.sessionId();
94511
+ nativeSessionId = () => this.#nativeSessionId;
94111
94512
  adoptNativeSessionId = (sessionId) => {
94112
- if (this.#prompted || this.#updates.sessionId() !== sessionId) {
94513
+ if (this.#prompted || this.#nativeSessionId !== sessionId) {
94113
94514
  throw new AcpExecutionError("The new native Session cannot be adopted", {}, "session_identity_mismatch");
94114
94515
  }
94115
94516
  const previousSessionId = this.#mobiusSessionId;
@@ -94131,7 +94532,7 @@ var init_agent_session = __esm({
94131
94532
  };
94132
94533
  #applyConfiguration = async (selection, signal) => {
94133
94534
  const configRevision = this.#configRevision;
94134
- const configured = await this.#adapter.configureSession(this.#target(), selection, signal);
94535
+ const configured = await this.#adapter.configureSession({ ...this.#target(), selection, signal });
94135
94536
  if (this.#configRevision === configRevision) {
94136
94537
  this.#configOptions = configured;
94137
94538
  this.#configRevision = crypto.randomUUID();
@@ -94178,7 +94579,7 @@ var init_agent_session = __esm({
94178
94579
  await this.emitConfigUpdate();
94179
94580
  };
94180
94581
  #target = () => ({
94181
- nativeSessionId: this.#updates.sessionId(),
94582
+ nativeSessionId: this.#nativeSessionId,
94182
94583
  cwd: this.#cwd,
94183
94584
  additionalDirectories: this.#additionalDirectories
94184
94585
  });
@@ -94190,11 +94591,18 @@ var init_agent_session = __esm({
94190
94591
  this.#sessionLoad = {
94191
94592
  kind: "loaded",
94192
94593
  history: new HistoryReplayCapture(this.#store.events, this.#mobiusSessionId),
94193
- response: {}
94594
+ opened: {
94595
+ nativeSessionId: this.nativeSessionId(),
94596
+ capabilities: this.#capabilities,
94597
+ configOptions: [],
94598
+ agentName: this.#agentName,
94599
+ agentVersion: this.#agentVersion,
94600
+ agentSettingsModelEffort: this.#modelEffort
94601
+ }
94194
94602
  };
94195
94603
  }
94196
94604
  if (this.#capabilities.loadSession && this.#sessionLoad.kind !== "execution-only") {
94197
- await this.#completedHistory(options.signal, "ACP agent exited while loading history before a prompt");
94605
+ await this.#completedHistory(options.signal);
94198
94606
  }
94199
94607
  validatePromptContent(options, this.#capabilities);
94200
94608
  if (this.#sessionTitle === null || this.#sessionTitle.length === 0) {
@@ -94228,7 +94636,7 @@ var init_agent_session = __esm({
94228
94636
  });
94229
94637
  }
94230
94638
  try {
94231
- const result = await this.#adapter.prompt(this.#target(), options, options.signal);
94639
+ const result = await this.#adapter.prompt({ ...this.#target(), content: options, signal: options.signal });
94232
94640
  this.writeStoredSession((/* @__PURE__ */ new Date()).toISOString());
94233
94641
  if (lifecycle !== void 0) {
94234
94642
  await this.recordLifecycleEvent({
@@ -94299,7 +94707,7 @@ var init_agent_session = __esm({
94299
94707
  });
94300
94708
  }
94301
94709
  try {
94302
- const outcome = await this.#adapter.steer(this.#target(), options, options.signal);
94710
+ const outcome = await this.#adapter.steer({ ...this.#target(), content: options, signal: options.signal });
94303
94711
  if (lifecycle !== void 0) {
94304
94712
  await this.recordLifecycleEvent({
94305
94713
  payload: {
@@ -94333,7 +94741,7 @@ var init_agent_session = __esm({
94333
94741
  await this.#interactions.cancelPendingInteractions();
94334
94742
  signal.throwIfAborted();
94335
94743
  if (this.#turn.running) {
94336
- return await this.#adapter.cancel(this.#target(), signal);
94744
+ return await this.#adapter.cancel({ ...this.#target(), signal });
94337
94745
  }
94338
94746
  return "retained";
94339
94747
  };
@@ -94358,7 +94766,14 @@ var init_agent_session = __esm({
94358
94766
  await this.#getObserver().onSessionEvent?.(liveEvent2);
94359
94767
  };
94360
94768
  selectNativeSession = (sessionId) => {
94361
- this.#updates.select(sessionId);
94769
+ if (this.#nativeSessionId.length > 0 && this.#nativeSessionId !== sessionId) {
94770
+ throw new AcpExecutionError(
94771
+ "ACP agent attempted to replace the selected session",
94772
+ {},
94773
+ "invalid_agent_session"
94774
+ );
94775
+ }
94776
+ this.#nativeIdentity = { kind: "bound", nativeSessionId: sessionId };
94362
94777
  this.#nativeHistoryOwnership = { kind: "agent-owned" };
94363
94778
  };
94364
94779
  #processEvent = async (event) => {
@@ -94403,7 +94818,7 @@ var init_agent_session = __esm({
94403
94818
  break;
94404
94819
  }
94405
94820
  }
94406
- if (this.#updates.sessionId().length > 0) {
94821
+ if (this.#nativeSessionId.length > 0) {
94407
94822
  this.writeStoredSession((/* @__PURE__ */ new Date()).toISOString());
94408
94823
  }
94409
94824
  await this.#getObserver().onInfo({
@@ -94425,31 +94840,28 @@ var init_agent_session = __esm({
94425
94840
  await this.closeProcess();
94426
94841
  }
94427
94842
  }
94428
- if (this.#updates.sessionId().length === 0) {
94843
+ if (this.#nativeSessionId.length === 0) {
94429
94844
  await this.closeProcess();
94430
94845
  return;
94431
94846
  }
94432
- await this.#adapter.closeSession(this.#target(), AbortSignal.timeout(3e4));
94847
+ await this.#adapter.closeSession({ ...this.#target(), signal: AbortSignal.timeout(3e4) });
94433
94848
  };
94434
- closeProcess = () => this.#connection.closeProcess();
94435
- agentSettingsModelEffort = () => this.#connection.agentSettingsModelEffort();
94436
- race = (operation, exitMessage, signal) => this.#connection.race(operation, exitMessage, signal);
94437
- agentRequest(method, params, options) {
94438
- return this.#connection.connection.agent.request(
94439
- method,
94440
- params,
94441
- options
94442
- );
94443
- }
94444
- drained() {
94445
- return this.#updates.drained();
94446
- }
94447
- initializeAgent(signal) {
94448
- return this.#initializeAgent(signal);
94449
- }
94450
- async loadSession(signal, exitMessage) {
94451
- return await this.#loadSession(signal, exitMessage);
94452
- }
94849
+ closeProcess = async () => {
94850
+ if (this.#nativeIdentity.kind === "bound") {
94851
+ await this.#adapter.releaseSession({ ...this.#target(), signal: AbortSignal.timeout(3e4) });
94852
+ }
94853
+ this.#backgroundActivity = "none";
94854
+ };
94855
+ agentSettingsModelEffort = () => this.#modelEffort;
94856
+ #sessionParams = (signal) => ({
94857
+ ...this.#subscriber,
94858
+ scope: this.#scope,
94859
+ signal
94860
+ });
94861
+ createSession = (signal) => this.#adapter.createSession(this.#sessionParams(signal));
94862
+ forkSession = (sourceSessionId, signal) => this.#adapter.forkSession({ ...this.#sessionParams(signal), sourceNativeSessionId: sourceSessionId });
94863
+ openSession = (signal) => this.#adapter.openSession({ ...this.#sessionParams(signal), nativeSessionId: this.nativeSessionId() });
94864
+ openSessionWithReplay = async (signal) => (await this.#loadSession(signal)).opened;
94453
94865
  setConfigOptions(options) {
94454
94866
  this.#configOptions = options;
94455
94867
  this.#configRevision = crypto.randomUUID();
@@ -94467,7 +94879,7 @@ var init_agent_session = __esm({
94467
94879
  this.#sessionTitle = title2;
94468
94880
  }
94469
94881
  assertNativeSession = (sessionId) => {
94470
- if (sessionId !== this.#updates.sessionId()) {
94882
+ if (sessionId !== this.#nativeSessionId) {
94471
94883
  throw new AcpExecutionError("ACP agent referenced an unknown session", {}, "invalid_agent_session");
94472
94884
  }
94473
94885
  };
@@ -94498,6 +94910,23 @@ var init_native_chat_agent = __esm({
94498
94910
  }
94499
94911
  });
94500
94912
 
94913
+ // src/engine/session/native/native-query.ts
94914
+ function nativeSessionQuery(options) {
94915
+ const externalize = options.externalizeSessionUpdate;
94916
+ return {
94917
+ agent: options.agent,
94918
+ cwd: options.cwd,
94919
+ additionalDirectories: options.additionalDirectories,
94920
+ signal: options.signal,
94921
+ ...externalize === void 0 ? {} : { externalizeUpdate: (update, signal) => externalize(options.sessionId, update, signal) }
94922
+ };
94923
+ }
94924
+ var init_native_query = __esm({
94925
+ "src/engine/session/native/native-query.ts"() {
94926
+ "use strict";
94927
+ }
94928
+ });
94929
+
94501
94930
  // src/engine/session/turn/active-executions.ts
94502
94931
  var unreachable2, ActiveExecutions;
94503
94932
  var init_active_executions = __esm({
@@ -94593,9 +95022,11 @@ var init_session_manager = __esm({
94593
95022
  "use strict";
94594
95023
  init_protocol();
94595
95024
  init_acp_error();
95025
+ init_session_capabilities();
94596
95026
  init_operation_metrics();
94597
95027
  init_agent_session();
94598
95028
  init_native_chat_agent();
95029
+ init_native_query();
94599
95030
  init_retained_agent_processes();
94600
95031
  init_session_store2();
94601
95032
  init_active_executions();
@@ -94718,21 +95149,29 @@ var init_session_manager = __esm({
94718
95149
  if (retiring !== void 0) {
94719
95150
  await waitForSharedOperation(retiring, options.signal);
94720
95151
  }
94721
- const runtime = await this.#processes.startRetained(options.signal, start, this.#retention(options.sessionId));
95152
+ const stored = this.#store.read(options.sessionId);
95153
+ const capabilities = options.origin !== void 0 || stored instanceof FoundStoredSession && stored.session.prompted ? await options.adapter.getCapabilities(nativeSessionQuery(options)) : unsupportedSessionCapabilities();
95154
+ const runtime = await this.#processes.startRetained(
95155
+ options.signal,
95156
+ () => start(capabilities),
95157
+ this.#retention(options.sessionId)
95158
+ );
94722
95159
  this.#executionProcesses.retain(options.sessionId, runtime);
94723
95160
  return runtime;
94724
95161
  }
94725
95162
  async #startPreparation(options, recovery, metrics = unmeasuredOperationMetrics) {
94726
95163
  return await this.#executionProcesses.prepare(options.sessionId, async () => {
95164
+ const effectiveOptions = options.origin === void 0 && this.#sessionIdentity === "native" && isNativeChatSessionId(options.agent.id, options.sessionId) && this.#store.read(options.sessionId) instanceof MissingStoredSession ? { ...options, origin: { kind: "import", nativeSessionId: options.sessionId, title: "" } } : options;
94727
95165
  return await this.#startRetainedSessionProcess(
94728
- options,
94729
- async () => await AgentSession.start(
94730
- options.origin === void 0 && this.#sessionIdentity === "native" && isNativeChatSessionId(options.agent.id, options.sessionId) && this.#store.read(options.sessionId) instanceof MissingStoredSession ? { ...options, origin: { kind: "import", nativeSessionId: options.sessionId, title: "" } } : options,
95166
+ effectiveOptions,
95167
+ async (capabilities) => await AgentSession.start(
95168
+ effectiveOptions,
94731
95169
  recovery,
94732
95170
  () => this.#observer,
94733
95171
  this.#store,
94734
95172
  metrics,
94735
- options.adapter
95173
+ options.adapter,
95174
+ capabilities
94736
95175
  )
94737
95176
  );
94738
95177
  });
@@ -94747,13 +95186,14 @@ var init_session_manager = __esm({
94747
95186
  this.#store.remove(options.sessionId);
94748
95187
  return await this.#startRetainedSessionProcess(
94749
95188
  options,
94750
- async () => await AgentSession.start(
95189
+ async (capabilities) => await AgentSession.start(
94751
95190
  options,
94752
95191
  recovery,
94753
95192
  () => this.#observer,
94754
95193
  this.#store,
94755
95194
  metrics,
94756
- options.adapter
95195
+ options.adapter,
95196
+ capabilities
94757
95197
  )
94758
95198
  );
94759
95199
  });
@@ -94765,13 +95205,14 @@ var init_session_manager = __esm({
94765
95205
  await this.#retireSessionProcess(options.sessionId, existing, async () => await existing.close());
94766
95206
  const runtime = await this.#startRetainedSessionProcess(
94767
95207
  options,
94768
- async () => await AgentSession.start(
95208
+ async (capabilities) => await AgentSession.start(
94769
95209
  options,
94770
95210
  recovery,
94771
95211
  () => this.#observer,
94772
95212
  this.#store,
94773
95213
  unmeasuredOperationMetrics,
94774
- options.adapter
95214
+ options.adapter,
95215
+ capabilities
94775
95216
  )
94776
95217
  );
94777
95218
  try {
@@ -95399,7 +95840,7 @@ var init_local_authorization_error = __esm({
95399
95840
  });
95400
95841
 
95401
95842
  // src/engine/session/native/native-session-browser.ts
95402
- import { randomUUID as randomUUID15 } from "node:crypto";
95843
+ import { randomUUID as randomUUID14 } from "node:crypto";
95403
95844
  function nextForkTitle(sourceTitle, sessions) {
95404
95845
  let highest = 0;
95405
95846
  for (const session of sessions) {
@@ -95430,6 +95871,7 @@ var init_native_session_browser = __esm({
95430
95871
  init_native_session();
95431
95872
  init_operation_drain();
95432
95873
  init_local_authorization_error();
95874
+ init_native_query();
95433
95875
  MAXIMUM_SESSION_TITLE_LENGTH = 500;
95434
95876
  forkSuffixPattern = / \(Fork #([1-9][0-9]*)\)$/u;
95435
95877
  NativeSessionService = class {
@@ -95457,17 +95899,14 @@ var init_native_session_browser = __esm({
95457
95899
  (scoped) => this.#sessions.withNativeSessionOperation(
95458
95900
  scoped,
95459
95901
  nativeSessionId,
95460
- (target) => target.adapter.readSessionHistory(
95461
- target.cwd,
95462
- target.additionalDirectories,
95463
- {
95902
+ (target) => target.adapter.readSessionHistory({
95903
+ query: nativeSessionQuery(target),
95904
+ request: {
95464
95905
  nativeSessionId,
95465
95906
  eventLimit,
95466
- cursor,
95467
- sessionId: target.sessionId
95468
- },
95469
- target.signal
95470
- )
95907
+ cursor
95908
+ }
95909
+ })
95471
95910
  )
95472
95911
  );
95473
95912
  #execute = async (command, signal) => {
@@ -95498,7 +95937,7 @@ var init_native_session_browser = __esm({
95498
95937
  queuedCancellation: "before-start"
95499
95938
  };
95500
95939
  }
95501
- const capabilities = await options.adapter.getCapabilities(cwd, signal);
95940
+ const capabilities = await options.adapter.getCapabilities(nativeSessionQuery(options));
95502
95941
  if (!capabilities.listSessions) {
95503
95942
  throw new AcpExecutionError(
95504
95943
  "This Agent does not support native session listing",
@@ -95513,7 +95952,7 @@ var init_native_session_browser = __esm({
95513
95952
  if (authorized === null) {
95514
95953
  return null;
95515
95954
  }
95516
- const entryId = decodeIdentifier(randomUUID15());
95955
+ const entryId = decodeIdentifier(randomUUID14());
95517
95956
  if (this.#entries.size >= 5e3) {
95518
95957
  this.#entries.clear();
95519
95958
  }
@@ -95552,7 +95991,7 @@ var init_native_session_browser = __esm({
95552
95991
  }
95553
95992
  cursor = known.cursor;
95554
95993
  }
95555
- const page = await options.adapter.listSessions(cwd, cursor, signal);
95994
+ const page = await options.adapter.listSessions({ query: nativeSessionQuery(options), cursor });
95556
95995
  const entries = [];
95557
95996
  for (const info of page.sessions) {
95558
95997
  const entry = await register(info);
@@ -95569,7 +96008,7 @@ var init_native_session_browser = __esm({
95569
96008
  "invalid_native_session_response"
95570
96009
  );
95571
96010
  }
95572
- nextCursor = decodeIdentifier(randomUUID15());
96011
+ nextCursor = decodeIdentifier(randomUUID14());
95573
96012
  if (this.#cursors.size >= 500) {
95574
96013
  this.#cursors.clear();
95575
96014
  }
@@ -95587,15 +96026,14 @@ var init_native_session_browser = __esm({
95587
96026
  };
95588
96027
  }
95589
96028
  if (command.action === "find") {
95590
- const found = await options.adapter.findSession(
95591
- cwd,
95592
- command.nativeSessionId,
95593
- {
96029
+ const found = await options.adapter.findSession({
96030
+ query: nativeSessionQuery(options),
96031
+ nativeSessionId: command.nativeSessionId,
96032
+ budget: {
95594
96033
  maximumPages: 500,
95595
96034
  maximumEntries: 500
95596
- },
95597
- signal
95598
- );
96035
+ }
96036
+ });
95599
96037
  const entry = await register(found);
95600
96038
  if (entry !== null) {
95601
96039
  return { ...envelope2, action: "find", entry };
@@ -95733,15 +96171,14 @@ var init_native_session_browser = __esm({
95733
96171
  }
95734
96172
  };
95735
96173
  resolveTarget = async (command, options, selected) => {
95736
- const info = await options.adapter.findSession(
95737
- options.cwd,
95738
- selected.nativeSessionId,
95739
- {
96174
+ const info = await options.adapter.findSession({
96175
+ query: nativeSessionQuery(options),
96176
+ nativeSessionId: selected.nativeSessionId,
96177
+ budget: {
95740
96178
  maximumPages: 100,
95741
96179
  maximumEntries: null
95742
- },
95743
- options.signal
95744
- ).catch((cause) => {
96180
+ }
96181
+ }).catch((cause) => {
95745
96182
  options.signal.throwIfAborted();
95746
96183
  if (cause instanceof AcpExecutionError && cause.code === "native_session_not_found") {
95747
96184
  throw new AcpExecutionError(
@@ -96028,7 +96465,7 @@ var init_prompt_lifecycle = __esm({
96028
96465
  });
96029
96466
 
96030
96467
  // src/engine/session/turn/execution-receipts.ts
96031
- import { createHash as createHash7, randomUUID as randomUUID16 } from "node:crypto";
96468
+ import { createHash as createHash7, randomUUID as randomUUID15 } from "node:crypto";
96032
96469
  var MAX_TERMINAL_RECEIPTS, ExecutionReceipts;
96033
96470
  var init_execution_receipts = __esm({
96034
96471
  "src/engine/session/turn/execution-receipts.ts"() {
@@ -96175,7 +96612,7 @@ var init_execution_receipts = __esm({
96175
96612
  ).digest("hex");
96176
96613
  this.#save(commandId, {
96177
96614
  admissionOrder: this.#nextAdmissionOrder(),
96178
- attemptId: randomUUID16(),
96615
+ attemptId: randomUUID15(),
96179
96616
  commandHash,
96180
96617
  sessionId,
96181
96618
  started: false,
@@ -96257,7 +96694,7 @@ var init_execution_receipts = __esm({
96257
96694
  if (identity2 !== void 0) {
96258
96695
  return identity2.sessionId === sessionId && identity2.commandHash === commandHash ? { kind: "expired" } : { kind: "conflict" };
96259
96696
  }
96260
- const attemptId = randomUUID16();
96697
+ const attemptId = randomUUID15();
96261
96698
  this.#save(commandId, {
96262
96699
  admissionOrder: this.#nextAdmissionOrder(),
96263
96700
  attemptId,
@@ -96392,7 +96829,7 @@ var init_runtime_turn_activity = __esm({
96392
96829
  });
96393
96830
 
96394
96831
  // src/engine/session/turn/active-turn.ts
96395
- import { randomUUID as randomUUID17 } from "node:crypto";
96832
+ import { randomUUID as randomUUID16 } from "node:crypto";
96396
96833
  var ActiveRuntimeTurn;
96397
96834
  var init_active_turn = __esm({
96398
96835
  "src/engine/session/turn/active-turn.ts"() {
@@ -96407,7 +96844,7 @@ var init_active_turn = __esm({
96407
96844
  #dispatch;
96408
96845
  #sequence = 0;
96409
96846
  #interaction = null;
96410
- #epoch = decodeIdentifier(randomUUID17());
96847
+ #epoch = decodeIdentifier(randomUUID16());
96411
96848
  constructor(command, attemptId) {
96412
96849
  this.attemptId = attemptId;
96413
96850
  this.command = command;
@@ -97016,11 +97453,11 @@ var init_session_layer = __esm({
97016
97453
  });
97017
97454
 
97018
97455
  // src/engine/storage/files/scratch-directory.ts
97019
- import { randomUUID as randomUUID18 } from "node:crypto";
97456
+ import { randomUUID as randomUUID17 } from "node:crypto";
97020
97457
  import { lstat as lstat4, mkdir as mkdir5, readdir as readdir6, readFile as readFile7, realpath as realpath8, rename as rename4, rm as rm3, stat as stat8, utimes, writeFile as writeFile2 } from "node:fs/promises";
97021
97458
  import { dirname as dirname12, join as join30 } from "node:path";
97022
97459
  async function atomicWrite(path8, bytes, signal) {
97023
- const temporary = `${path8}.${randomUUID18()}.tmp`;
97460
+ const temporary = `${path8}.${randomUUID17()}.tmp`;
97024
97461
  try {
97025
97462
  await writeFile2(temporary, bytes, { mode: 384, signal });
97026
97463
  signal.throwIfAborted();
@@ -97036,7 +97473,7 @@ var init_scratch_directory = __esm({
97036
97473
  ScratchDirectory = class {
97037
97474
  #root;
97038
97475
  constructor(parent) {
97039
- this.#root = join30(parent, randomUUID18());
97476
+ this.#root = join30(parent, randomUUID17());
97040
97477
  }
97041
97478
  /** Refreshes this directory's lease and removes sibling directories whose lease is older than `leaseMilliseconds`. */
97042
97479
  refreshLease = async (leaseMilliseconds) => {
@@ -99228,7 +99665,7 @@ var init_native_sessions = __esm({
99228
99665
  });
99229
99666
 
99230
99667
  // src/engine/session/prompt/apply-session-configuration.ts
99231
- import { randomUUID as randomUUID19 } from "node:crypto";
99668
+ import { randomUUID as randomUUID18 } from "node:crypto";
99232
99669
  function invalidSessionConfiguration(message) {
99233
99670
  return new AcpExecutionError(message, {}, "invalid_session_configuration");
99234
99671
  }
@@ -99366,7 +99803,7 @@ async function applySessionConfigurationSelection(sessions, options, selection,
99366
99803
  booleanValue: selection.booleanValue,
99367
99804
  configId: selection.configId,
99368
99805
  cwd,
99369
- requestId: `cfg_${randomUUID19()}`,
99806
+ requestId: `cfg_${randomUUID18()}`,
99370
99807
  sessionId,
99371
99808
  signal,
99372
99809
  value: selection.value,
@@ -99439,7 +99876,11 @@ async function executePrompt({
99439
99876
  command.additionalDirectoryIds,
99440
99877
  signal
99441
99878
  );
99442
- const { agent, adapter } = await resolveAgent(command.agentId, signal, command.sessionId);
99879
+ const { agent, adapter, externalizeSessionUpdate } = await resolveAgent(
99880
+ command.agentId,
99881
+ signal,
99882
+ command.sessionId
99883
+ );
99443
99884
  const availability = await waitForSessionAvailability(signal);
99444
99885
  if (availability.kind === "busy") {
99445
99886
  throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
@@ -99457,6 +99898,7 @@ async function executePrompt({
99457
99898
  const recovery = command.historyPolicy === SessionHistoryPolicy.ExecutionOnly ? { kind: "execution-only" } : { kind: "interactive-only" };
99458
99899
  const preparation = {
99459
99900
  adapter,
99901
+ ...externalizeSessionUpdate === void 0 ? {} : { externalizeSessionUpdate },
99460
99902
  additionalDirectories: resolved.additionalDirectories,
99461
99903
  agent: executionAgent,
99462
99904
  cwd: resolved.cwd,
@@ -99511,6 +99953,7 @@ async function executePrompt({
99511
99953
  if (availability.disposition === SessionPromptDisposition.Steer) {
99512
99954
  await sessions.steerPrompt({
99513
99955
  adapter,
99956
+ ...externalizeSessionUpdate === void 0 ? {} : { externalizeSessionUpdate },
99514
99957
  additionalDirectories: resolved.additionalDirectories,
99515
99958
  agent: executionAgent,
99516
99959
  commandId: command.commandId,
@@ -99527,6 +99970,7 @@ async function executePrompt({
99527
99970
  } else {
99528
99971
  const result = await sessions.runPrompt({
99529
99972
  adapter,
99973
+ ...externalizeSessionUpdate === void 0 ? {} : { externalizeSessionUpdate },
99530
99974
  additionalDirectories: resolved.additionalDirectories,
99531
99975
  agent: executionAgent,
99532
99976
  commandId: command.commandId,
@@ -100940,7 +101384,7 @@ async function runRuntime(config2, parentSignal, timer = systemTimer, options =
100940
101384
  const publisher = new RuntimeSessionEventPublisher(timer);
100941
101385
  const externalContent = __using(_stack, new LocalExternalContentStore(stateDirectory), true);
100942
101386
  const processes = new AgentProcessPool(config2.localContext.maxAcpProcesses, timer);
100943
- const adapters = createRuntimeAdapterRegistry(
101387
+ const { adapters, externalizeSessionUpdate } = createRuntimeAdapterRegistry(
100944
101388
  config2.adapters,
100945
101389
  processes,
100946
101390
  (sessionId, content, contentSignal) => externalContent.put({ ...content, sessionId, signal: contentSignal }),
@@ -100950,7 +101394,11 @@ async function runRuntime(config2, parentSignal, timer = systemTimer, options =
100950
101394
  const catalogAgent = await resolveCatalogAgent(config2, agentId, resolveSignal);
100951
101395
  const environment = sessionId === void 0 ? void 0 : config2.sessionEnvironment?.({ sessionId, agentId });
100952
101396
  const agent = environment === void 0 ? catalogAgent : catalogAgent.withEnvironment({ ...catalogAgent.environment, ...environment });
100953
- return { agent, adapter: adapters.resolve(catalogAgent) };
101397
+ return {
101398
+ agent,
101399
+ adapter: adapters.resolve(catalogAgent),
101400
+ externalizeSessionUpdate
101401
+ };
100954
101402
  };
100955
101403
  const layer = buildSessionLayer({
100956
101404
  processes,
@@ -101335,7 +101783,7 @@ var init_engine = __esm({
101335
101783
  });
101336
101784
 
101337
101785
  // src/storage/daemon/version-data.ts
101338
- import { randomUUID as randomUUID20 } from "node:crypto";
101786
+ import { randomUUID as randomUUID19 } from "node:crypto";
101339
101787
  import { cp as cp2, lstat as lstat5, mkdtemp, readFile as readFile8, rename as rename5, rm as rm4, writeFile as writeFile3 } from "node:fs/promises";
101340
101788
  import { join as join33, relative as relative3, sep as sep5 } from "node:path";
101341
101789
  async function prepareVersionDataDirectory(root, version2, signal) {
@@ -101426,7 +101874,7 @@ async function discardVersionData(root, version2, signal) {
101426
101874
  return;
101427
101875
  }
101428
101876
  const versions = join33(root, STATE_ROOT_LAYOUT.versions);
101429
- const discarded = join33(versions, `.${version2}-discarded-${randomUUID20()}`);
101877
+ const discarded = join33(versions, `.${version2}-discarded-${randomUUID19()}`);
101430
101878
  try {
101431
101879
  await rename5(join33(versions, version2), discarded);
101432
101880
  } catch (cause) {
@@ -101440,7 +101888,7 @@ async function discardVersionData(root, version2, signal) {
101440
101888
  async function writeCurrentDataVersion(root, version2, signal) {
101441
101889
  await validateLocalPath(root, true, true, signal);
101442
101890
  await validateLocalPath(join33(root, STATE_ROOT_LAYOUT.versions, version2), true, true, signal);
101443
- const temporary = join33(root, `.current-data-${randomUUID20()}.txt`);
101891
+ const temporary = join33(root, `.current-data-${randomUUID19()}.txt`);
101444
101892
  try {
101445
101893
  await writeFile3(temporary, `versions/${version2}
101446
101894
  `, { mode: 384, flag: "wx", signal });
@@ -103044,7 +103492,7 @@ var init_quit = __esm({
103044
103492
  });
103045
103493
 
103046
103494
  // src/daemon/upgrades/upgrade.ts
103047
- import { randomUUID as randomUUID21 } from "node:crypto";
103495
+ import { randomUUID as randomUUID20 } from "node:crypto";
103048
103496
  import { setInterval as setInterval2, setTimeout as setTimeout4 } from "node:timers/promises";
103049
103497
  async function reportDaemonUpgradeAvailability(send2, signal) {
103050
103498
  if (!process.connected) {
@@ -103103,7 +103551,7 @@ async function requestDaemonReleaseUpgrade(stateDirectory, currentVersion, signa
103103
103551
  return await requestInstalledDaemonReleaseSwitch(stateDirectory, launch, signal);
103104
103552
  }
103105
103553
  async function requestInstalledDaemonReleaseSwitch(stateDirectory, launch, signal) {
103106
- const id = randomUUID21();
103554
+ const id = randomUUID20();
103107
103555
  const response = decodeKnownLifecycleResponse(
103108
103556
  await sendLocalRequest(stateDirectory, "manager", { kind: "switch", id, context: "npm", launch }, signal)
103109
103557
  );