@moxt-ai/mobius 0.0.126 → 0.0.128

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/dist/acp/{session-executions.d.ts → active-executions.d.ts} +2 -2
  2. package/dist/acp/active-executions.d.ts.map +1 -0
  3. package/dist/acp/{session-executions.js → active-executions.js} +2 -2
  4. package/dist/acp/active-executions.js.map +1 -0
  5. package/dist/acp/{process-endpoint.d.ts → agent-connection.d.ts} +2 -2
  6. package/dist/acp/{process-endpoint.d.ts.map → agent-connection.d.ts.map} +1 -1
  7. package/dist/acp/{process-endpoint.js → agent-connection.js} +2 -2
  8. package/dist/acp/{process-endpoint.js.map → agent-connection.js.map} +1 -1
  9. package/dist/acp/agent-process-pool.d.ts +17 -0
  10. package/dist/acp/agent-process-pool.d.ts.map +1 -0
  11. package/dist/acp/{process-pool.js → agent-process-pool.js} +2 -2
  12. package/dist/acp/agent-process-pool.js.map +1 -0
  13. package/dist/acp/agent-query-processes.d.ts +15 -0
  14. package/dist/acp/agent-query-processes.d.ts.map +1 -0
  15. package/dist/acp/agent-query-processes.js +97 -0
  16. package/dist/acp/agent-query-processes.js.map +1 -0
  17. package/dist/acp/{session-manager.d.ts → agent-runtime-manager.d.ts} +5 -5
  18. package/dist/acp/agent-runtime-manager.d.ts.map +1 -0
  19. package/dist/acp/{session-manager.js → agent-runtime-manager.js} +72 -149
  20. package/dist/acp/agent-runtime-manager.js.map +1 -0
  21. package/dist/acp/{process-session.d.ts → agent-session.d.ts} +4 -6
  22. package/dist/acp/agent-session.d.ts.map +1 -0
  23. package/dist/acp/{process-session.js → agent-session.js} +57 -86
  24. package/dist/acp/agent-session.js.map +1 -0
  25. package/dist/acp/agent-update-stream.d.ts +11 -0
  26. package/dist/acp/agent-update-stream.d.ts.map +1 -0
  27. package/dist/acp/agent-update-stream.js +56 -0
  28. package/dist/acp/agent-update-stream.js.map +1 -0
  29. package/dist/acp/codex/agent.d.ts.map +1 -1
  30. package/dist/acp/codex/agent.js +46 -0
  31. package/dist/acp/codex/agent.js.map +1 -1
  32. package/dist/acp/retained-agent-processes.d.ts +21 -0
  33. package/dist/acp/retained-agent-processes.d.ts.map +1 -0
  34. package/dist/acp/{retained-sessions.js → retained-agent-processes.js} +3 -3
  35. package/dist/acp/retained-agent-processes.js.map +1 -0
  36. package/dist/acp/run-prompt.d.ts +1 -1
  37. package/dist/acp/run-prompt.d.ts.map +1 -1
  38. package/dist/acp/run-prompt.js +4 -4
  39. package/dist/acp/run-prompt.js.map +1 -1
  40. package/dist/acp/session-config/apply-session-configuration.d.ts +2 -2
  41. package/dist/acp/session-config/apply-session-configuration.d.ts.map +1 -1
  42. package/dist/acp/session-config/apply-session-configuration.js +1 -1
  43. package/dist/acp/session-config/apply-session-configuration.js.map +1 -1
  44. package/dist/agent-catalog/discover-agent-settings.d.ts +2 -2
  45. package/dist/agent-catalog/discover-agent-settings.d.ts.map +1 -1
  46. package/dist/agent-catalog/discover-agent-settings.js +1 -1
  47. package/dist/agent-catalog/discover-agent-settings.js.map +1 -1
  48. package/dist/agent-catalog/handle-agent-catalog-refresh.js +1 -1
  49. package/dist/agent-catalog/handle-agent-catalog-refresh.js.map +1 -1
  50. package/dist/agent-catalog/handle-agent-settings-discovery.d.ts +2 -2
  51. package/dist/agent-catalog/handle-agent-settings-discovery.d.ts.map +1 -1
  52. package/dist/agent-catalog/handle-agent-settings-discovery.js +1 -1
  53. package/dist/agent-catalog/handle-agent-settings-discovery.js.map +1 -1
  54. package/dist/cli.js +463 -389
  55. package/dist/cli.js.map +4 -4
  56. package/dist/daemon-command-handler.d.ts +2 -2
  57. package/dist/daemon-command-handler.d.ts.map +1 -1
  58. package/dist/daemon-command-results.js +1 -1
  59. package/dist/daemon-command-results.js.map +1 -1
  60. package/dist/daemon-history-commands.d.ts +3 -3
  61. package/dist/daemon-history-commands.d.ts.map +1 -1
  62. package/dist/daemon-history-commands.js.map +1 -1
  63. package/dist/daemon-observers.d.ts +1 -1
  64. package/dist/daemon-observers.d.ts.map +1 -1
  65. package/dist/daemon-prompt-executor.d.ts +2 -2
  66. package/dist/daemon-prompt-executor.d.ts.map +1 -1
  67. package/dist/daemon-prompt-executor.js +1 -1
  68. package/dist/daemon-prompt-executor.js.map +1 -1
  69. package/dist/daemon-session-commands.d.ts +3 -3
  70. package/dist/daemon-session-commands.d.ts.map +1 -1
  71. package/dist/daemon-session-commands.js.map +1 -1
  72. package/dist/daemon-turn-registry.d.ts +13 -13
  73. package/dist/index.js +489 -415
  74. package/dist/index.js.map +4 -4
  75. package/dist/native-sessions/acp-history.d.ts +2 -2
  76. package/dist/native-sessions/acp-history.d.ts.map +1 -1
  77. package/dist/native-sessions/acp-history.js +1 -1
  78. package/dist/native-sessions/acp-history.js.map +1 -1
  79. package/dist/native-sessions/agent-adapter.d.ts +2 -2
  80. package/dist/native-sessions/agent-adapter.d.ts.map +1 -1
  81. package/dist/native-sessions/agent-adapter.js +1 -1
  82. package/dist/native-sessions/agent-adapter.js.map +1 -1
  83. package/dist/native-sessions/handle-native-requests.js +1 -1
  84. package/dist/native-sessions/handle-native-requests.js.map +1 -1
  85. package/dist/native-sessions/live-history-page.js +1 -1
  86. package/dist/native-sessions/live-history-page.js.map +1 -1
  87. package/dist/native-sessions/service.d.ts +2 -2
  88. package/dist/native-sessions/service.d.ts.map +1 -1
  89. package/dist/native-sessions/service.js +1 -1
  90. package/dist/native-sessions/service.js.map +1 -1
  91. package/dist/relay-connection/run-relay-connection.d.ts +2 -2
  92. package/dist/relay-connection/run-relay-connection.d.ts.map +1 -1
  93. package/dist/run-daemon.d.ts.map +1 -1
  94. package/dist/run-daemon.js +5 -5
  95. package/dist/run-daemon.js.map +1 -1
  96. package/dist/runtime.js +462 -388
  97. package/dist/runtime.js.map +4 -4
  98. package/package.json +1 -1
  99. package/dist/acp/process-pool.d.ts +0 -17
  100. package/dist/acp/process-pool.d.ts.map +0 -1
  101. package/dist/acp/process-pool.js.map +0 -1
  102. package/dist/acp/process-session.d.ts.map +0 -1
  103. package/dist/acp/process-session.js.map +0 -1
  104. package/dist/acp/retained-sessions.d.ts +0 -21
  105. package/dist/acp/retained-sessions.d.ts.map +0 -1
  106. package/dist/acp/retained-sessions.js.map +0 -1
  107. package/dist/acp/session-executions.d.ts.map +0 -1
  108. package/dist/acp/session-executions.js.map +0 -1
  109. package/dist/acp/session-manager.d.ts.map +0 -1
  110. package/dist/acp/session-manager.js.map +0 -1
package/dist/index.js CHANGED
@@ -22373,7 +22373,112 @@ function loadDaemonConfig() {
22373
22373
  );
22374
22374
  }
22375
22375
 
22376
- // src/acp/process-session.ts
22376
+ // src/acp/acp-error.ts
22377
+ var AcpExecutionError = class extends Error {
22378
+ code;
22379
+ constructor(message, options = {}, code = "acp_execution_failed") {
22380
+ super(message, options);
22381
+ this.code = code;
22382
+ this.name = "AcpExecutionError";
22383
+ }
22384
+ };
22385
+ var AcpConfigurationValueUnavailableError = class extends AcpExecutionError {
22386
+ configId;
22387
+ offeredValueCount;
22388
+ offeredValues;
22389
+ requestedValue;
22390
+ constructor(configId, requestedValue, offeredValues) {
22391
+ super("The requested ACP configuration value is unavailable", {}, "invalid_session_configuration");
22392
+ this.name = "AcpConfigurationValueUnavailableError";
22393
+ this.configId = configId.slice(0, 128);
22394
+ this.requestedValue = requestedValue.slice(0, 128);
22395
+ this.offeredValueCount = offeredValues.length;
22396
+ this.offeredValues = Object.freeze(offeredValues.slice(0, 32).map((value) => value.slice(0, 128)));
22397
+ }
22398
+ };
22399
+
22400
+ // src/acp/active-executions.ts
22401
+ var unreachable = (state) => {
22402
+ throw new AcpExecutionError("Unexpected execution state", { cause: state });
22403
+ };
22404
+ var ActiveExecutions = class {
22405
+ #entries = /* @__PURE__ */ new Map();
22406
+ command = (id) => {
22407
+ const state = this.#entries.get(id);
22408
+ switch (state?.kind) {
22409
+ case "running":
22410
+ case "cancelling":
22411
+ return state.commandId;
22412
+ case "cancelled-before-start":
22413
+ case void 0:
22414
+ return void 0;
22415
+ default:
22416
+ return unreachable(state);
22417
+ }
22418
+ };
22419
+ cancellation = (id) => {
22420
+ const state = this.#entries.get(id);
22421
+ switch (state?.kind) {
22422
+ case "cancelling":
22423
+ case "cancelled-before-start":
22424
+ return state.completion;
22425
+ case "running":
22426
+ case void 0:
22427
+ return void 0;
22428
+ default:
22429
+ return unreachable(state);
22430
+ }
22431
+ };
22432
+ isBusy = (id) => this.#entries.has(id);
22433
+ begin = (id, commandId) => {
22434
+ const state = this.#entries.get(id);
22435
+ switch (state?.kind) {
22436
+ case "running":
22437
+ case "cancelling":
22438
+ throw new AcpExecutionError(
22439
+ "Another prompt is already running in this conversation",
22440
+ {},
22441
+ "session_busy"
22442
+ );
22443
+ case "cancelled-before-start":
22444
+ case void 0:
22445
+ break;
22446
+ default:
22447
+ unreachable(state);
22448
+ }
22449
+ this.#entries.set(
22450
+ id,
22451
+ state?.kind === "cancelled-before-start" ? { kind: "cancelling", commandId, completion: state.completion } : { kind: "running", commandId }
22452
+ );
22453
+ };
22454
+ cancel = (id, stop) => {
22455
+ const state = this.#entries.get(id);
22456
+ switch (state?.kind) {
22457
+ case "cancelling":
22458
+ case "cancelled-before-start":
22459
+ return state.completion;
22460
+ case "running":
22461
+ case void 0:
22462
+ break;
22463
+ default:
22464
+ return unreachable(state);
22465
+ }
22466
+ const completion = Promise.withResolvers();
22467
+ this.#entries.set(
22468
+ id,
22469
+ state?.kind === "running" ? { kind: "cancelling", commandId: state.commandId, completion: completion.promise } : { kind: "cancelled-before-start", completion: completion.promise }
22470
+ );
22471
+ void (async () => await stop())().then(completion.resolve, completion.reject);
22472
+ return completion.promise;
22473
+ };
22474
+ finish = (id, commandId) => {
22475
+ if (this.command(id) === commandId) {
22476
+ this.#entries.delete(id);
22477
+ }
22478
+ };
22479
+ };
22480
+
22481
+ // src/acp/agent-session.ts
22377
22482
  import {
22378
22483
  methods as methods3,
22379
22484
  PROTOCOL_VERSION
@@ -22676,30 +22781,6 @@ async function replaceImageMarkers(text2, replace) {
22676
22781
  return `${rewritten}${text2.slice(cursor)}`;
22677
22782
  }
22678
22783
 
22679
- // src/acp/acp-error.ts
22680
- var AcpExecutionError = class extends Error {
22681
- code;
22682
- constructor(message, options = {}, code = "acp_execution_failed") {
22683
- super(message, options);
22684
- this.code = code;
22685
- this.name = "AcpExecutionError";
22686
- }
22687
- };
22688
- var AcpConfigurationValueUnavailableError = class extends AcpExecutionError {
22689
- configId;
22690
- offeredValueCount;
22691
- offeredValues;
22692
- requestedValue;
22693
- constructor(configId, requestedValue, offeredValues) {
22694
- super("The requested ACP configuration value is unavailable", {}, "invalid_session_configuration");
22695
- this.name = "AcpConfigurationValueUnavailableError";
22696
- this.configId = configId.slice(0, 128);
22697
- this.requestedValue = requestedValue.slice(0, 128);
22698
- this.offeredValueCount = offeredValues.length;
22699
- this.offeredValues = Object.freeze(offeredValues.slice(0, 32).map((value) => value.slice(0, 128)));
22700
- }
22701
- };
22702
-
22703
22784
  // src/acp/activity.ts
22704
22785
  var TRUNCATION_MARKER = "\n\u2026 output truncated by Mobius";
22705
22786
  var AcpActivityNarration = class {
@@ -23295,23 +23376,7 @@ var AcpActivityTracker = class {
23295
23376
  };
23296
23377
  };
23297
23378
 
23298
- // src/acp/native-session.ts
23299
- var path = external_exports.string().min(1).max(2048).refine((value) => !value.includes("\0"));
23300
- var title = external_exports.string().transform((value) => value.slice(0, 500));
23301
- var nativeSessionIdSchema = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/);
23302
- var nativeSessionInfoSchema = external_exports.object({
23303
- sessionId: nativeSessionIdSchema,
23304
- cwd: path,
23305
- additionalDirectories: external_exports.array(path).max(16).default([]).readonly(),
23306
- title: title.nullish(),
23307
- updatedAt: external_exports.iso.datetime({ offset: true }).nullish()
23308
- }).readonly();
23309
- var nativeSessionPageSchema = external_exports.object({
23310
- sessions: external_exports.array(nativeSessionInfoSchema).max(500).readonly(),
23311
- nextCursor: external_exports.string().min(1).max(4096).nullish()
23312
- }).readonly();
23313
-
23314
- // src/acp/process-endpoint.ts
23379
+ // src/acp/agent-connection.ts
23315
23380
  import { spawn as spawn2 } from "node:child_process";
23316
23381
  import { ndJsonStream, RequestError } from "@agentclientprotocol/sdk";
23317
23382
 
@@ -23340,7 +23405,7 @@ function readString2(value, fallback = "") {
23340
23405
  return typeof value === "string" ? value : fallback;
23341
23406
  }
23342
23407
 
23343
- // src/acp/process-endpoint.ts
23408
+ // src/acp/agent-connection.ts
23344
23409
  function readableWebStream(input2) {
23345
23410
  let streamOpen = true;
23346
23411
  return new ReadableStream({
@@ -23416,7 +23481,7 @@ function createWritableAcpStream(output2) {
23416
23481
  }
23417
23482
  });
23418
23483
  }
23419
- var AcpEndpoint = class {
23484
+ var AgentConnection = class {
23420
23485
  connection;
23421
23486
  termination;
23422
23487
  #process;
@@ -23523,6 +23588,86 @@ var AcpEndpoint = class {
23523
23588
  };
23524
23589
  };
23525
23590
 
23591
+ // src/acp/native-session.ts
23592
+ var path = external_exports.string().min(1).max(2048).refine((value) => !value.includes("\0"));
23593
+ var title = external_exports.string().transform((value) => value.slice(0, 500));
23594
+ var nativeSessionIdSchema = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/);
23595
+ var nativeSessionInfoSchema = external_exports.object({
23596
+ sessionId: nativeSessionIdSchema,
23597
+ cwd: path,
23598
+ additionalDirectories: external_exports.array(path).max(16).default([]).readonly(),
23599
+ title: title.nullish(),
23600
+ updatedAt: external_exports.iso.datetime({ offset: true }).nullish()
23601
+ }).readonly();
23602
+ var nativeSessionPageSchema = external_exports.object({
23603
+ sessions: external_exports.array(nativeSessionInfoSchema).max(500).readonly(),
23604
+ nextCursor: external_exports.string().min(1).max(4096).nullish()
23605
+ }).readonly();
23606
+
23607
+ // src/acp/agent-update-stream.ts
23608
+ var MAX_PENDING_UPDATES = 100;
23609
+ var MAX_PENDING_BYTES = 1024 * 1024;
23610
+ var AgentUpdateStream = class {
23611
+ #selection = { kind: "awaiting-session", notifications: [], bytes: 0 };
23612
+ #tail = Promise.resolve();
23613
+ #consume;
23614
+ constructor(consume) {
23615
+ this.#consume = consume;
23616
+ }
23617
+ sessionId = () => this.#selection.kind === "selected" ? this.#selection.sessionId : "";
23618
+ drained = () => this.#tail;
23619
+ #enqueue = (notification) => {
23620
+ this.#tail = this.#tail.then(async () => await this.#consume(notification));
23621
+ return this.#tail;
23622
+ };
23623
+ receive = (notification) => {
23624
+ const selection = this.#selection;
23625
+ switch (selection.kind) {
23626
+ case "selected":
23627
+ return this.#enqueue(notification);
23628
+ case "awaiting-session": {
23629
+ const bytes = selection.bytes + Buffer.byteLength(JSON.stringify(notification));
23630
+ if (selection.notifications.length >= MAX_PENDING_UPDATES || bytes > MAX_PENDING_BYTES) {
23631
+ return Promise.reject(
23632
+ new AcpExecutionError(
23633
+ "ACP agent sent too many updates before creating its session",
23634
+ {},
23635
+ "agent_update_limit"
23636
+ )
23637
+ );
23638
+ }
23639
+ this.#selection = {
23640
+ kind: "awaiting-session",
23641
+ notifications: [...selection.notifications, notification],
23642
+ bytes
23643
+ };
23644
+ return Promise.resolve();
23645
+ }
23646
+ }
23647
+ };
23648
+ select = (sessionId) => {
23649
+ const selected = nativeSessionIdSchema.parse(sessionId);
23650
+ const selection = this.#selection;
23651
+ switch (selection.kind) {
23652
+ case "selected":
23653
+ if (selection.sessionId !== selected) {
23654
+ throw new AcpExecutionError(
23655
+ "ACP agent attempted to replace the selected session",
23656
+ {},
23657
+ "invalid_agent_session"
23658
+ );
23659
+ }
23660
+ return;
23661
+ case "awaiting-session":
23662
+ this.#selection = { kind: "selected", sessionId: selected };
23663
+ for (const notification of selection.notifications) {
23664
+ void this.#enqueue(notification);
23665
+ }
23666
+ return;
23667
+ }
23668
+ };
23669
+ };
23670
+
23526
23671
  // src/acp/session-config/session-config-protocol.ts
23527
23672
  import { methods as methods2 } from "@agentclientprotocol/sdk";
23528
23673
  var MAXIMUM_CONFIG_OPTIONS = 100;
@@ -30141,10 +30286,8 @@ var SqliteAcpSessionStore = class {
30141
30286
  };
30142
30287
  };
30143
30288
 
30144
- // src/acp/process-session.ts
30289
+ // src/acp/agent-session.ts
30145
30290
  var PROCESS_STOP_TIMEOUT_MILLISECONDS = 1e3;
30146
- var MAX_PRE_SESSION_UPDATES = 100;
30147
- var MAX_PRE_SESSION_UPDATE_BYTES = 1024 * 1024;
30148
30291
  var RetryableAcpInitializationError = class extends AcpExecutionError {
30149
30292
  constructor(cause) {
30150
30293
  super("ACP agent initialization failed", { cause });
@@ -30159,8 +30302,8 @@ function recordsEqual(left, right) {
30159
30302
  const rightEntries = Object.entries(right);
30160
30303
  return leftEntries.length === rightEntries.length && leftEntries.every(([name, value]) => right[name] === value);
30161
30304
  }
30162
- var AcpProcessSession = class _AcpProcessSession {
30163
- #endpoint;
30305
+ var AgentSession = class _AgentSession {
30306
+ #connection;
30164
30307
  #interactions;
30165
30308
  #additionalDirectories;
30166
30309
  #agentId;
@@ -30168,12 +30311,11 @@ var AcpProcessSession = class _AcpProcessSession {
30168
30311
  #environment;
30169
30312
  #getObserver;
30170
30313
  #mobiusSessionId;
30171
- #preSessionUpdates = [];
30314
+ #updates;
30172
30315
  #metrics;
30173
30316
  #sessionConfigProtocol;
30174
30317
  #store;
30175
30318
  #verifiedAgentVersion;
30176
- #preSessionUpdateBytes = 0;
30177
30319
  #agentName = "";
30178
30320
  #agentVersion = "";
30179
30321
  #bufferedAgentText = [];
@@ -30181,7 +30323,6 @@ var AcpProcessSession = class _AcpProcessSession {
30181
30323
  #commands = [];
30182
30324
  #configRevision = 0;
30183
30325
  #configOptions = [];
30184
- #nativeSessionId = "";
30185
30326
  #prompted = false;
30186
30327
  #nativePrompt = null;
30187
30328
  #replay = {
@@ -30191,10 +30332,11 @@ var AcpProcessSession = class _AcpProcessSession {
30191
30332
  #sessionTitle = null;
30192
30333
  #sessionUpdatedAt = "";
30193
30334
  #turn = new IdleAcpTurn();
30194
- #updateTail = Promise.resolve();
30195
30335
  constructor(agent, cwd, additionalDirectories, mobiusSessionId, getObserver, store, metrics) {
30336
+ this.#updates = new AgentUpdateStream((notification) => this.#processUpdate(notification));
30196
30337
  this.#additionalDirectories = [...additionalDirectories];
30197
30338
  this.#agentId = agent.id;
30339
+ this.#commands = [];
30198
30340
  this.#cwd = cwd;
30199
30341
  this.#environment = agent.environment;
30200
30342
  this.#getObserver = getObserver;
@@ -30209,7 +30351,7 @@ var AcpProcessSession = class _AcpProcessSession {
30209
30351
  assertNativeSession: (sessionId) => this.assertNativeSession(sessionId),
30210
30352
  observer: getObserver
30211
30353
  });
30212
- this.#endpoint = new AcpEndpoint(agent, cwd, this);
30354
+ this.#connection = new AgentConnection(agent, cwd, this);
30213
30355
  }
30214
30356
  static async #start(options, getObserver, store, initialize, metrics) {
30215
30357
  for (let attempt = 1; attempt <= 2; attempt += 1) {
@@ -30232,7 +30374,7 @@ var AcpProcessSession = class _AcpProcessSession {
30232
30374
  }
30233
30375
  const runtime = metrics.measureSync(
30234
30376
  "process-spawn",
30235
- () => new _AcpProcessSession(
30377
+ () => new _AgentSession(
30236
30378
  options.agent,
30237
30379
  options.cwd,
30238
30380
  options.additionalDirectories,
@@ -30262,14 +30404,14 @@ var AcpProcessSession = class _AcpProcessSession {
30262
30404
  }
30263
30405
  throw new AcpExecutionError("ACP agent initialization failed");
30264
30406
  }
30265
- static start = async (options, getObserver, store, metrics = unmeasuredOperationMetrics) => await _AcpProcessSession.#start(
30407
+ static start = async (options, getObserver, store, metrics = unmeasuredOperationMetrics) => await _AgentSession.#start(
30266
30408
  options,
30267
30409
  getObserver,
30268
30410
  store,
30269
30411
  async (runtime) => await runtime.initialize(options.signal, options.origin),
30270
30412
  metrics
30271
30413
  );
30272
- static startNativeSessionBrowser = async (options, getObserver, store) => await _AcpProcessSession.#start(
30414
+ static startNativeSessionBrowser = async (options, getObserver, store) => await _AgentSession.#start(
30273
30415
  options,
30274
30416
  getObserver,
30275
30417
  store,
@@ -30302,20 +30444,20 @@ var AcpProcessSession = class _AcpProcessSession {
30302
30444
  this.#replay = { kind: "capture", history };
30303
30445
  try {
30304
30446
  await this.race(
30305
- this.#endpoint.connection.agent.request(
30447
+ this.#connection.connection.agent.request(
30306
30448
  methods3.agent.session.load,
30307
30449
  {
30308
30450
  additionalDirectories: [...this.#additionalDirectories],
30309
30451
  cwd: this.#cwd,
30310
30452
  mcpServers: [],
30311
- sessionId: this.#nativeSessionId
30453
+ sessionId: this.#updates.sessionId()
30312
30454
  },
30313
30455
  { cancellationSignal: signal }
30314
30456
  ),
30315
30457
  "ACP agent exited while loading history",
30316
30458
  signal
30317
30459
  );
30318
- await this.#updateTail;
30460
+ await this.#updates.drained();
30319
30461
  signal.throwIfAborted();
30320
30462
  return await embedLocalHistoryImages(await history.snapshot(), signal);
30321
30463
  } finally {
@@ -30411,9 +30553,9 @@ var AcpProcessSession = class _AcpProcessSession {
30411
30553
  await this.#metrics.measure("agent-initialize", async () => await this.#initializeAgentOperation(signal));
30412
30554
  }
30413
30555
  async #initializeAgentOperation(signal) {
30414
- if (this.#endpoint.inProcessAgent !== null) {
30556
+ if (this.#connection.inProcessAgent !== null) {
30415
30557
  await this.race(
30416
- this.#endpoint.inProcessAgent.initialize(signal),
30558
+ this.#connection.inProcessAgent.initialize(signal),
30417
30559
  "The Codex app-server exited during initialization",
30418
30560
  signal
30419
30561
  ).catch((cause) => {
@@ -30422,7 +30564,7 @@ var AcpProcessSession = class _AcpProcessSession {
30422
30564
  });
30423
30565
  }
30424
30566
  const initialized = await this.race(
30425
- this.#endpoint.connection.agent.request(
30567
+ this.#connection.connection.agent.request(
30426
30568
  methods3.agent.initialize,
30427
30569
  {
30428
30570
  clientCapabilities: {
@@ -30501,7 +30643,7 @@ var AcpProcessSession = class _AcpProcessSession {
30501
30643
  const forked = await this.#metrics.measure(
30502
30644
  "session-fork",
30503
30645
  async () => await this.race(
30504
- this.#endpoint.connection.agent.request(
30646
+ this.#connection.connection.agent.request(
30505
30647
  methods3.agent.session.fork,
30506
30648
  {
30507
30649
  sessionId: nativeSessionIdSchema.parse(origin.nativeSessionId),
@@ -30516,7 +30658,7 @@ var AcpProcessSession = class _AcpProcessSession {
30516
30658
  )
30517
30659
  );
30518
30660
  this.selectNativeSession(forked.sessionId);
30519
- if (this.#nativeSessionId === origin.nativeSessionId || this.#store.findNative(this.#agentId, this.#nativeSessionId).length > 0) {
30661
+ if (this.#updates.sessionId() === origin.nativeSessionId || this.#store.findNative(this.#agentId, this.#updates.sessionId()).length > 0) {
30520
30662
  throw new AcpExecutionError(
30521
30663
  "The Agent did not create an independent fork",
30522
30664
  {},
@@ -30535,13 +30677,13 @@ var AcpProcessSession = class _AcpProcessSession {
30535
30677
  lifecycleResponse = await this.#metrics.measure(
30536
30678
  "session-resume",
30537
30679
  async () => await this.race(
30538
- this.#endpoint.connection.agent.request(
30680
+ this.#connection.connection.agent.request(
30539
30681
  methods3.agent.session.resume,
30540
30682
  {
30541
30683
  additionalDirectories: [...this.#additionalDirectories],
30542
30684
  cwd: this.#cwd,
30543
30685
  mcpServers: [],
30544
- sessionId: this.#nativeSessionId
30686
+ sessionId: this.#updates.sessionId()
30545
30687
  },
30546
30688
  { cancellationSignal: signal }
30547
30689
  ),
@@ -30555,13 +30697,13 @@ var AcpProcessSession = class _AcpProcessSession {
30555
30697
  lifecycleResponse = await this.#metrics.measure(
30556
30698
  "session-load",
30557
30699
  async () => await this.race(
30558
- this.#endpoint.connection.agent.request(
30700
+ this.#connection.connection.agent.request(
30559
30701
  methods3.agent.session.load,
30560
30702
  {
30561
30703
  additionalDirectories: [...this.#additionalDirectories],
30562
30704
  cwd: this.#cwd,
30563
30705
  mcpServers: [],
30564
- sessionId: this.#nativeSessionId
30706
+ sessionId: this.#updates.sessionId()
30565
30707
  },
30566
30708
  { cancellationSignal: signal }
30567
30709
  ),
@@ -30570,7 +30712,7 @@ var AcpProcessSession = class _AcpProcessSession {
30570
30712
  )
30571
30713
  );
30572
30714
  } finally {
30573
- await this.#updateTail;
30715
+ await this.#updates.drained();
30574
30716
  this.#replay = { kind: "idle" };
30575
30717
  }
30576
30718
  } else {
@@ -30594,7 +30736,7 @@ var AcpProcessSession = class _AcpProcessSession {
30594
30736
  const created = await this.#metrics.measure(
30595
30737
  "session-new",
30596
30738
  async () => await this.race(
30597
- this.#endpoint.connection.agent.request(
30739
+ this.#connection.connection.agent.request(
30598
30740
  methods3.agent.session.new,
30599
30741
  {
30600
30742
  additionalDirectories: [...this.#additionalDirectories],
@@ -30611,13 +30753,13 @@ var AcpProcessSession = class _AcpProcessSession {
30611
30753
  lifecycleResponse = created;
30612
30754
  }
30613
30755
  this.#configOptions = this.#sessionConfigProtocol.normalizeLifecycle(lifecycleResponse);
30614
- await this.#updateTail;
30756
+ await this.#updates.drained();
30615
30757
  signal.throwIfAborted();
30616
30758
  this.#store.write(
30617
30759
  new AcpStoredSession(
30618
30760
  this.#mobiusSessionId,
30619
30761
  this.#agentId,
30620
- this.#nativeSessionId,
30762
+ this.#updates.sessionId(),
30621
30763
  this.#cwd,
30622
30764
  this.#additionalDirectories,
30623
30765
  this.#prompted,
@@ -30634,7 +30776,7 @@ var AcpProcessSession = class _AcpProcessSession {
30634
30776
  );
30635
30777
  }
30636
30778
  const response = await this.race(
30637
- this.#endpoint.connection.agent.request(methods3.agent.session.list, cursor === null ? {} : { cursor }, {
30779
+ this.#connection.connection.agent.request(methods3.agent.session.list, cursor === null ? {} : { cursor }, {
30638
30780
  cancellationSignal: signal
30639
30781
  }),
30640
30782
  "ACP agent exited while listing sessions",
@@ -30659,7 +30801,7 @@ var AcpProcessSession = class _AcpProcessSession {
30659
30801
  );
30660
30802
  }
30661
30803
  await this.race(
30662
- this.#endpoint.connection.agent.request(
30804
+ this.#connection.connection.agent.request(
30663
30805
  methods3.agent.session.delete,
30664
30806
  { sessionId: nativeSessionIdSchema.parse(nativeSessionId) },
30665
30807
  { cancellationSignal: signal }
@@ -30668,9 +30810,9 @@ var AcpProcessSession = class _AcpProcessSession {
30668
30810
  signal
30669
30811
  );
30670
30812
  };
30671
- nativeSessionId = () => this.#nativeSessionId;
30813
+ nativeSessionId = () => this.#updates.sessionId();
30672
30814
  adoptNativeSessionId = (sessionId) => {
30673
- if (this.#prompted || this.#nativeSessionId !== sessionId) {
30815
+ if (this.#prompted || this.#updates.sessionId() !== sessionId) {
30674
30816
  throw new AcpExecutionError("The new native Session cannot be adopted", {}, "session_identity_mismatch");
30675
30817
  }
30676
30818
  const previousSessionId = this.#mobiusSessionId;
@@ -30718,10 +30860,10 @@ var AcpProcessSession = class _AcpProcessSession {
30718
30860
  const configured = await this.#sessionConfigProtocol.configure(
30719
30861
  this.#configOptions,
30720
30862
  options,
30721
- this.#nativeSessionId,
30863
+ this.#updates.sessionId(),
30722
30864
  {
30723
30865
  request: async (method, params, failureMessage, signal) => await this.race(
30724
- this.#endpoint.connection.agent.request(method, params, {
30866
+ this.#connection.connection.agent.request(method, params, {
30725
30867
  cancellationSignal: signal
30726
30868
  }),
30727
30869
  failureMessage,
@@ -30737,7 +30879,7 @@ var AcpProcessSession = class _AcpProcessSession {
30737
30879
  "invalid_session_configuration"
30738
30880
  );
30739
30881
  }
30740
- await this.#updateTail;
30882
+ await this.#updates.drained();
30741
30883
  if (this.#configRevision === configRevision) {
30742
30884
  this.#configOptions = configured;
30743
30885
  }
@@ -30802,7 +30944,7 @@ var AcpProcessSession = class _AcpProcessSession {
30802
30944
  };
30803
30945
  nativeHistoryTurn = () => {
30804
30946
  const prompt = this.#nativePrompt;
30805
- const nativeTurnId = this.#endpoint.inProcessAgent?.nativeTurnId?.() ?? null;
30947
+ const nativeTurnId = this.#connection.inProcessAgent?.nativeTurnId?.() ?? null;
30806
30948
  return prompt === null || nativeTurnId === null || nativeTurnId === prompt.previousTurnId ? null : { commandId: prompt.commandId, nativeTurnId };
30807
30949
  };
30808
30950
  prompt = async (options) => {
@@ -30817,7 +30959,7 @@ var AcpProcessSession = class _AcpProcessSession {
30817
30959
  new AcpStoredSession(
30818
30960
  this.#mobiusSessionId,
30819
30961
  this.#agentId,
30820
- this.#nativeSessionId,
30962
+ this.#updates.sessionId(),
30821
30963
  this.#cwd,
30822
30964
  this.#additionalDirectories,
30823
30965
  true,
@@ -30835,19 +30977,19 @@ var AcpProcessSession = class _AcpProcessSession {
30835
30977
  this.#turn = running;
30836
30978
  this.#nativePrompt = {
30837
30979
  commandId: options.commandId,
30838
- previousTurnId: this.#endpoint.inProcessAgent?.nativeTurnId?.() ?? null
30980
+ previousTurnId: this.#connection.inProcessAgent?.nativeTurnId?.() ?? null
30839
30981
  };
30840
30982
  try {
30841
30983
  const response = await this.race(
30842
- this.#endpoint.connection.agent.request(
30984
+ this.#connection.connection.agent.request(
30843
30985
  methods3.agent.session.prompt,
30844
- { prompt, sessionId: this.#nativeSessionId },
30986
+ { prompt, sessionId: this.#updates.sessionId() },
30845
30987
  { cancellationSignal: options.signal }
30846
30988
  ),
30847
30989
  "ACP agent exited during a prompt",
30848
30990
  options.signal
30849
30991
  );
30850
- await this.#updateTail;
30992
+ await this.#updates.drained();
30851
30993
  await this.flushAgentText();
30852
30994
  await running.activities.finish();
30853
30995
  let result;
@@ -30897,10 +31039,10 @@ var AcpProcessSession = class _AcpProcessSession {
30897
31039
  }
30898
31040
  const prompt = this.buildPrompt(options);
30899
31041
  const response = await this.race(
30900
- this.#endpoint.connection.agent.request("_session/steering", {
31042
+ this.#connection.connection.agent.request("_session/steering", {
30901
31043
  _meta: { steering: { idleBehavior: "promptRequired" } },
30902
31044
  prompt,
30903
- sessionId: this.#nativeSessionId
31045
+ sessionId: this.#updates.sessionId()
30904
31046
  }),
30905
31047
  "ACP agent exited during steering",
30906
31048
  options.signal
@@ -30933,12 +31075,12 @@ var AcpProcessSession = class _AcpProcessSession {
30933
31075
  );
30934
31076
  };
30935
31077
  cancel = async () => {
30936
- const capturedProcesses = await this.#endpoint.captureProcessTree();
31078
+ const capturedProcesses = await this.#connection.captureProcessTree();
30937
31079
  try {
30938
31080
  await this.#interactions.cancelPendingInteractions();
30939
31081
  if (this.#turn.running) {
30940
- await this.#endpoint.connection.agent.notify(methods3.agent.session.cancel, {
30941
- sessionId: this.#nativeSessionId
31082
+ await this.#connection.connection.agent.notify(methods3.agent.session.cancel, {
31083
+ sessionId: this.#updates.sessionId()
30942
31084
  });
30943
31085
  }
30944
31086
  } finally {
@@ -30950,45 +31092,9 @@ var AcpProcessSession = class _AcpProcessSession {
30950
31092
  onPermission = (request, signal) => this.#interactions.onPermission(request, signal);
30951
31093
  onElicitation = (request, signal) => this.#interactions.onElicitation(request, signal);
30952
31094
  onElicitationComplete = (notification) => this.#interactions.onElicitationComplete(notification);
30953
- onUpdate = (notification) => {
30954
- if (this.#nativeSessionId.length === 0) {
30955
- const notificationBytes = Buffer.byteLength(JSON.stringify(notification));
30956
- if (this.#preSessionUpdates.length >= MAX_PRE_SESSION_UPDATES || this.#preSessionUpdateBytes + notificationBytes > MAX_PRE_SESSION_UPDATE_BYTES) {
30957
- return Promise.reject(
30958
- new AcpExecutionError(
30959
- "ACP agent sent too many updates before creating its session",
30960
- {},
30961
- "agent_update_limit"
30962
- )
30963
- );
30964
- }
30965
- this.#preSessionUpdates.push(notification);
30966
- this.#preSessionUpdateBytes += notificationBytes;
30967
- return Promise.resolve();
30968
- }
30969
- return this.enqueueUpdate(notification);
30970
- };
30971
- enqueueUpdate = (notification) => {
30972
- this.#updateTail = this.#updateTail.then(async () => await this.processUpdate(notification));
30973
- return this.#updateTail;
30974
- };
30975
- selectNativeSession = (sessionId) => {
30976
- const selected = nativeSessionIdSchema.parse(sessionId);
30977
- if (this.#nativeSessionId.length > 0 && this.#nativeSessionId !== selected) {
30978
- throw new AcpExecutionError(
30979
- "ACP agent attempted to replace the selected session",
30980
- {},
30981
- "invalid_agent_session"
30982
- );
30983
- }
30984
- this.#nativeSessionId = selected;
30985
- const pending = this.#preSessionUpdates.splice(0);
30986
- this.#preSessionUpdateBytes = 0;
30987
- for (const notification of pending) {
30988
- void this.enqueueUpdate(notification);
30989
- }
30990
- };
30991
- processUpdate = async (notification) => {
31095
+ onUpdate = (notification) => this.#updates.receive(notification);
31096
+ selectNativeSession = (sessionId) => this.#updates.select(sessionId);
31097
+ #processUpdate = async (notification) => {
30992
31098
  this.assertNativeSession(notification.sessionId);
30993
31099
  const update = notification.update;
30994
31100
  if (this.#replay.kind === "capture") {
@@ -31058,7 +31164,7 @@ var AcpProcessSession = class _AcpProcessSession {
31058
31164
  })).filter((command) => command.name.length > 0);
31059
31165
  this.#commands = commands;
31060
31166
  await this.#getObserver().onCommands({
31061
- commands,
31167
+ commands: this.#commands,
31062
31168
  kind: SESSION_COMMANDS_UPDATED_KIND,
31063
31169
  sessionId: this.#mobiusSessionId
31064
31170
  });
@@ -31088,12 +31194,12 @@ var AcpProcessSession = class _AcpProcessSession {
31088
31194
  if (Object.hasOwn(update, "updatedAt")) {
31089
31195
  this.#sessionUpdatedAt = truncate2(update.updatedAt ?? "", 128);
31090
31196
  }
31091
- if (this.#nativeSessionId.length > 0) {
31197
+ if (this.#updates.sessionId().length > 0) {
31092
31198
  this.#store.write(
31093
31199
  new AcpStoredSession(
31094
31200
  this.#mobiusSessionId,
31095
31201
  this.#agentId,
31096
- this.#nativeSessionId,
31202
+ this.#updates.sessionId(),
31097
31203
  this.#cwd,
31098
31204
  this.#additionalDirectories,
31099
31205
  this.#prompted,
@@ -31125,11 +31231,11 @@ var AcpProcessSession = class _AcpProcessSession {
31125
31231
  close = async () => {
31126
31232
  try {
31127
31233
  await this.#interactions.cancelPendingInteractions();
31128
- if (this.#capabilities.closeSession && this.#nativeSessionId.length > 0) {
31234
+ if (this.#capabilities.closeSession && this.#updates.sessionId().length > 0) {
31129
31235
  try {
31130
- await this.#endpoint.connection.agent.request(
31236
+ await this.#connection.connection.agent.request(
31131
31237
  methods3.agent.session.close,
31132
- { sessionId: this.#nativeSessionId },
31238
+ { sessionId: this.#updates.sessionId() },
31133
31239
  {
31134
31240
  cancellationSignal: AbortSignal.timeout(PROCESS_STOP_TIMEOUT_MILLISECONDS)
31135
31241
  }
@@ -31141,10 +31247,10 @@ var AcpProcessSession = class _AcpProcessSession {
31141
31247
  await this.closeProcess();
31142
31248
  }
31143
31249
  };
31144
- closeProcess = (capturedProcesses = []) => this.#endpoint.closeProcess(capturedProcesses);
31145
- race = (operation, exitMessage, signal) => this.#endpoint.race(operation, exitMessage, signal);
31250
+ closeProcess = (capturedProcesses = []) => this.#connection.closeProcess(capturedProcesses);
31251
+ race = (operation, exitMessage, signal) => this.#connection.race(operation, exitMessage, signal);
31146
31252
  assertNativeSession = (sessionId) => {
31147
- if (sessionId !== this.#nativeSessionId) {
31253
+ if (sessionId !== this.#updates.sessionId()) {
31148
31254
  throw new AcpExecutionError("ACP agent referenced an unknown session", {}, "invalid_agent_session");
31149
31255
  }
31150
31256
  };
@@ -31158,8 +31264,8 @@ var AcpProcessSession = class _AcpProcessSession {
31158
31264
  };
31159
31265
  };
31160
31266
 
31161
- // src/acp/retained-sessions.ts
31162
- var RetainedSessions = class {
31267
+ // src/acp/retained-agent-processes.ts
31268
+ var RetainedAgentProcesses = class {
31163
31269
  #entries = /* @__PURE__ */ new Map();
31164
31270
  #events;
31165
31271
  constructor(events) {
@@ -31262,84 +31368,118 @@ var RetainedSessions = class {
31262
31368
  };
31263
31369
  };
31264
31370
 
31265
- // src/acp/session-executions.ts
31266
- var unreachable = (state) => {
31267
- throw new AcpExecutionError("Unexpected execution state", { cause: state });
31268
- };
31269
- var SessionExecutions = class {
31270
- #entries = /* @__PURE__ */ new Map();
31271
- command = (id) => {
31272
- const state = this.#entries.get(id);
31273
- switch (state?.kind) {
31274
- case "running":
31275
- case "cancelling":
31276
- return state.commandId;
31277
- case "cancelled-before-start":
31278
- case void 0:
31279
- return void 0;
31280
- default:
31281
- return unreachable(state);
31371
+ // src/acp/agent-query-processes.ts
31372
+ var AgentQueryProcesses = class {
31373
+ #processesByQuery;
31374
+ #processes;
31375
+ #observer = new NullAcpSessionObserver();
31376
+ #store = new MemoryAcpSessionStore();
31377
+ constructor(processes) {
31378
+ this.#processes = processes;
31379
+ this.#processesByQuery = new RetainedAgentProcesses({
31380
+ touch: processes.touch,
31381
+ changed: processes.notifyChanged
31382
+ });
31383
+ }
31384
+ retire = async (sessionId, runtime) => {
31385
+ const retained = this.#processesByQuery.detach(sessionId, runtime);
31386
+ if (retained) {
31387
+ this.#store.remove(sessionId);
31282
31388
  }
31389
+ await this.#processes.retire(runtime, () => runtime.close());
31283
31390
  };
31284
- cancellation = (id) => {
31285
- const state = this.#entries.get(id);
31286
- switch (state?.kind) {
31287
- case "cancelling":
31288
- case "cancelled-before-start":
31289
- return state.completion;
31290
- case "running":
31291
- case void 0:
31292
- return void 0;
31293
- default:
31294
- return unreachable(state);
31391
+ async #startRetained(options) {
31392
+ const runtime = await this.#processes.startRetained(
31393
+ options.signal,
31394
+ () => AgentSession.startNativeSessionBrowser(options, () => this.#observer, this.#store),
31395
+ {
31396
+ isBusy: () => this.#processesByQuery.isBusy(options.sessionId),
31397
+ retire: (runtime2) => this.retire(options.sessionId, runtime2)
31398
+ }
31399
+ );
31400
+ this.#processesByQuery.retain(options.sessionId, runtime);
31401
+ return runtime;
31402
+ }
31403
+ async #startPreparation(options) {
31404
+ return await this.#processesByQuery.prepare(options.sessionId, async () => {
31405
+ return await this.#startRetained(options);
31406
+ });
31407
+ }
31408
+ async #replacePreparation(existing, options) {
31409
+ return await this.#processesByQuery.prepare(options.sessionId, async () => {
31410
+ await this.retire(options.sessionId, existing);
31411
+ return await this.#startRetained(options);
31412
+ });
31413
+ }
31414
+ prepare = async (options) => {
31415
+ const pending = this.#processesByQuery.pending(options.sessionId);
31416
+ if (pending !== void 0) {
31417
+ const runtime2 = await pending;
31418
+ if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
31419
+ this.#processesByQuery.touch(options.sessionId, runtime2);
31420
+ return runtime2.prepared();
31421
+ }
31422
+ return await this.prepare(options);
31295
31423
  }
31296
- };
31297
- isBusy = (id) => this.#entries.has(id);
31298
- begin = (id, commandId) => {
31299
- const state = this.#entries.get(id);
31300
- switch (state?.kind) {
31301
- case "running":
31302
- case "cancelling":
31424
+ const existing = this.#processesByQuery.get(options.sessionId);
31425
+ if (existing !== void 0) {
31426
+ if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
31427
+ this.#processesByQuery.touch(options.sessionId, existing);
31428
+ return existing.prepared();
31429
+ }
31430
+ if (!existing.canRebind()) {
31303
31431
  throw new AcpExecutionError(
31304
- "Another prompt is already running in this conversation",
31432
+ "The agent or workspace cannot change after a conversation has started",
31305
31433
  {},
31306
- "session_busy"
31434
+ "session_identity_mismatch"
31307
31435
  );
31308
- case "cancelled-before-start":
31309
- case void 0:
31310
- break;
31311
- default:
31312
- unreachable(state);
31436
+ }
31437
+ const runtime2 = await this.#replacePreparation(existing, options);
31438
+ return runtime2.prepared();
31313
31439
  }
31314
- this.#entries.set(
31315
- id,
31316
- state?.kind === "cancelled-before-start" ? { kind: "cancelling", commandId, completion: state.completion } : { kind: "running", commandId }
31317
- );
31440
+ const runtime = await this.#startPreparation(options);
31441
+ return runtime.prepared();
31318
31442
  };
31319
- cancel = (id, stop) => {
31320
- const state = this.#entries.get(id);
31321
- switch (state?.kind) {
31322
- case "cancelling":
31323
- case "cancelled-before-start":
31324
- return state.completion;
31325
- case "running":
31326
- case void 0:
31327
- break;
31328
- default:
31329
- return unreachable(state);
31443
+ async #ensure(options) {
31444
+ const existing = this.#processesByQuery.get(options.sessionId);
31445
+ if (existing !== void 0) {
31446
+ if (!existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
31447
+ throw new AcpExecutionError(
31448
+ "The agent or workspace cannot change after a conversation has started",
31449
+ {},
31450
+ "session_identity_mismatch"
31451
+ );
31452
+ }
31453
+ this.#processesByQuery.touch(options.sessionId, existing);
31454
+ return existing;
31330
31455
  }
31331
- const completion = Promise.withResolvers();
31332
- this.#entries.set(
31333
- id,
31334
- state?.kind === "running" ? { kind: "cancelling", commandId: state.commandId, completion: completion.promise } : { kind: "cancelled-before-start", completion: completion.promise }
31456
+ await this.prepare(options);
31457
+ const started = this.#processesByQuery.get(options.sessionId);
31458
+ if (started === void 0) {
31459
+ throw new AcpExecutionError("ACP native session browser did not start");
31460
+ }
31461
+ return started;
31462
+ }
31463
+ use = async (options, operation) => await this.#processesByQuery.use(options.sessionId, async () => await operation(await this.#ensure(options)));
31464
+ preview = async (options, nativeSessionId) => {
31465
+ return await this.#processes.runTransient(
31466
+ options.signal,
31467
+ async () => await AgentSession.startNativeSessionBrowser(
31468
+ options,
31469
+ () => this.#observer,
31470
+ new MemoryAcpSessionStore()
31471
+ ),
31472
+ async (runtime) => {
31473
+ runtime.selectNativeSession(nativeSessionId);
31474
+ return await runtime.loadHistory(options.signal);
31475
+ },
31476
+ async (runtime) => await runtime.closeProcess()
31335
31477
  );
31336
- void (async () => await stop())().then(completion.resolve, completion.reject);
31337
- return completion.promise;
31338
31478
  };
31339
- finish = (id, commandId) => {
31340
- if (this.command(id) === commandId) {
31341
- this.#entries.delete(id);
31342
- }
31479
+ close = async () => {
31480
+ await Promise.all(
31481
+ this.#processesByQuery.entries().map(async ([id, runtime]) => await this.retire(id, runtime))
31482
+ );
31343
31483
  };
31344
31484
  };
31345
31485
 
@@ -31444,9 +31584,9 @@ async function waitForAcpProcessCapacity(completion, signal) {
31444
31584
  }
31445
31585
  }
31446
31586
 
31447
- // src/acp/process-pool.ts
31587
+ // src/acp/agent-process-pool.ts
31448
31588
  var MAX_ACP_PROCESSES = 10;
31449
- var AcpProcessPool = class {
31589
+ var AgentProcessPool = class {
31450
31590
  #slots = /* @__PURE__ */ new Map();
31451
31591
  #lock = new AcpProcessCapacityLock();
31452
31592
  #changed = Promise.withResolvers();
@@ -31550,20 +31690,18 @@ var AcpProcessPool = class {
31550
31690
  };
31551
31691
  };
31552
31692
 
31553
- // src/acp/session-manager.ts
31693
+ // src/acp/agent-runtime-manager.ts
31554
31694
  var SESSION_CONTROL_TIMEOUT_MILLISECONDS = 3e4;
31555
- var AcpSessionManager = class {
31556
- #processes = new AcpProcessPool();
31557
- #sessions = new RetainedSessions({ touch: this.#processes.touch, changed: this.#processes.notifyChanged });
31558
- #nativeBrowserSessions = new RetainedSessions({
31695
+ var AgentRuntimeManager = class {
31696
+ #processes = new AgentProcessPool();
31697
+ #executionProcesses = new RetainedAgentProcesses({
31559
31698
  touch: this.#processes.touch,
31560
31699
  changed: this.#processes.notifyChanged
31561
31700
  });
31562
- #executions = new SessionExecutions();
31701
+ #queryProcesses = new AgentQueryProcesses(this.#processes);
31702
+ #executions = new ActiveExecutions();
31563
31703
  #agentSettingsObserver = new NullAcpSessionObserver();
31564
31704
  #nativeOperations = /* @__PURE__ */ new Set();
31565
- #nativeBrowserObserver = new NullAcpSessionObserver();
31566
- #nativeBrowserStore = new MemoryAcpSessionStore();
31567
31705
  #store;
31568
31706
  #nativeHistoryReader;
31569
31707
  #sessionIdentity;
@@ -31581,20 +31719,14 @@ var AcpSessionManager = class {
31581
31719
  const stored = this.#store.read(sessionId);
31582
31720
  return stored instanceof FoundAcpStoredSession && this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`);
31583
31721
  }
31584
- #retention(sessionId, kind) {
31585
- if (kind === "execution") {
31586
- return {
31587
- isBusy: () => this.#executions.isBusy(sessionId) || this.#sessions.isBusy(sessionId) || this.#isNativeSessionOperationActive(sessionId),
31588
- retire: (runtime) => this.#retireSessionProcess(sessionId, runtime, () => runtime.close())
31589
- };
31590
- }
31722
+ #retention(sessionId) {
31591
31723
  return {
31592
- isBusy: () => this.#nativeBrowserSessions.isBusy(sessionId),
31593
- retire: (runtime) => this.#retireNativeBrowserProcess(sessionId, runtime, () => runtime.close())
31724
+ isBusy: () => this.#executions.isBusy(sessionId) || this.#executionProcesses.isBusy(sessionId) || this.#isNativeSessionOperationActive(sessionId),
31725
+ retire: (runtime) => this.#retireSessionProcess(sessionId, runtime, () => runtime.close())
31594
31726
  };
31595
31727
  }
31596
31728
  async #retireSessionProcess(sessionId, runtime, close) {
31597
- const retained = this.#sessions.detach(sessionId, runtime);
31729
+ const retained = this.#executionProcesses.detach(sessionId, runtime);
31598
31730
  try {
31599
31731
  await this.#processes.retire(runtime, close);
31600
31732
  } finally {
@@ -31606,61 +31738,16 @@ var AcpSessionManager = class {
31606
31738
  }
31607
31739
  }
31608
31740
  }
31609
- async #retireNativeBrowserProcess(sessionId, runtime, close) {
31610
- const retained = this.#nativeBrowserSessions.detach(sessionId, runtime);
31611
- if (retained) {
31612
- this.#nativeBrowserStore.remove(sessionId);
31613
- }
31614
- await this.#processes.retire(runtime, close);
31615
- }
31616
31741
  async #startRetainedSessionProcess(options, start) {
31617
- const runtime = await this.#processes.startRetained(
31618
- options.signal,
31619
- start,
31620
- this.#retention(options.sessionId, "execution")
31621
- );
31622
- this.#sessions.retain(options.sessionId, runtime);
31623
- return runtime;
31624
- }
31625
- async #startRetainedNativeBrowserProcess(options, start) {
31626
- const runtime = await this.#processes.startRetained(
31627
- options.signal,
31628
- start,
31629
- this.#retention(options.sessionId, "browser")
31630
- );
31631
- this.#nativeBrowserSessions.retain(options.sessionId, runtime);
31742
+ const runtime = await this.#processes.startRetained(options.signal, start, this.#retention(options.sessionId));
31743
+ this.#executionProcesses.retain(options.sessionId, runtime);
31632
31744
  return runtime;
31633
31745
  }
31634
- async #startNativeBrowserPreparation(options) {
31635
- return await this.#nativeBrowserSessions.prepare(options.sessionId, async () => {
31636
- return await this.#startRetainedNativeBrowserProcess(
31637
- options,
31638
- async () => await AcpProcessSession.startNativeSessionBrowser(
31639
- options,
31640
- () => this.#nativeBrowserObserver,
31641
- this.#nativeBrowserStore
31642
- )
31643
- );
31644
- });
31645
- }
31646
- async #replaceNativeBrowserPreparation(existing, options) {
31647
- return await this.#nativeBrowserSessions.prepare(options.sessionId, async () => {
31648
- await this.#retireNativeBrowserProcess(options.sessionId, existing, async () => await existing.close());
31649
- return await this.#startRetainedNativeBrowserProcess(
31650
- options,
31651
- async () => await AcpProcessSession.startNativeSessionBrowser(
31652
- options,
31653
- () => this.#nativeBrowserObserver,
31654
- this.#nativeBrowserStore
31655
- )
31656
- );
31657
- });
31658
- }
31659
31746
  async #startPreparation(options, metrics = unmeasuredOperationMetrics) {
31660
- return await this.#sessions.prepare(options.sessionId, async () => {
31747
+ return await this.#executionProcesses.prepare(options.sessionId, async () => {
31661
31748
  return await this.#startRetainedSessionProcess(
31662
31749
  options,
31663
- async () => await AcpProcessSession.start(
31750
+ async () => await AgentSession.start(
31664
31751
  options.origin === void 0 && this.#sessionIdentity === "native" && isNativeChatSessionId(options.agent.id, options.sessionId) && this.#store.read(options.sessionId) instanceof MissingAcpStoredSession ? { ...options, origin: { kind: "import", nativeSessionId: options.sessionId } } : options,
31665
31752
  () => this.#observer,
31666
31753
  this.#store,
@@ -31670,7 +31757,7 @@ var AcpSessionManager = class {
31670
31757
  });
31671
31758
  }
31672
31759
  async #replacePreparation(existing, options, metrics) {
31673
- return await this.#sessions.prepare(options.sessionId, async () => {
31760
+ return await this.#executionProcesses.prepare(options.sessionId, async () => {
31674
31761
  await this.#retireSessionProcess(
31675
31762
  options.sessionId,
31676
31763
  existing,
@@ -31679,17 +31766,17 @@ var AcpSessionManager = class {
31679
31766
  this.#store.remove(options.sessionId);
31680
31767
  return await this.#startRetainedSessionProcess(
31681
31768
  options,
31682
- async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
31769
+ async () => await AgentSession.start(options, () => this.#observer, this.#store, metrics)
31683
31770
  );
31684
31771
  });
31685
31772
  }
31686
31773
  async #replaceExecutionPreparation(existing, options) {
31687
31774
  const desiredConfigOptions = existing.prepared().configOptions;
31688
- return await this.#sessions.prepare(options.sessionId, async () => {
31775
+ return await this.#executionProcesses.prepare(options.sessionId, async () => {
31689
31776
  await this.#retireSessionProcess(options.sessionId, existing, async () => await existing.close());
31690
31777
  const runtime = await this.#startRetainedSessionProcess(
31691
31778
  options,
31692
- async () => await AcpProcessSession.start(options, () => this.#observer, this.#store)
31779
+ async () => await AgentSession.start(options, () => this.#observer, this.#store)
31693
31780
  );
31694
31781
  try {
31695
31782
  for (const desired of desiredConfigOptions) {
@@ -31740,19 +31827,19 @@ var AcpSessionManager = class {
31740
31827
  if (stored instanceof FoundAcpStoredSession && this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`)) {
31741
31828
  throw new AcpExecutionError("The native session is being managed", {}, "session_busy");
31742
31829
  }
31743
- const pending = this.#sessions.pending(options.sessionId);
31830
+ const pending = this.#executionProcesses.pending(options.sessionId);
31744
31831
  if (pending !== void 0) {
31745
31832
  const runtime2 = await metrics.measure("session-preparation-wait", async () => await pending);
31746
31833
  if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
31747
- this.#sessions.touch(options.sessionId, runtime2);
31834
+ this.#executionProcesses.touch(options.sessionId, runtime2);
31748
31835
  return runtime2.prepared();
31749
31836
  }
31750
31837
  return await this.prepareSession(options, metrics);
31751
31838
  }
31752
- const existing = this.#sessions.get(options.sessionId);
31839
+ const existing = this.#executionProcesses.get(options.sessionId);
31753
31840
  if (existing !== void 0) {
31754
31841
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
31755
- this.#sessions.touch(options.sessionId, existing);
31842
+ this.#executionProcesses.touch(options.sessionId, existing);
31756
31843
  return existing.prepared();
31757
31844
  }
31758
31845
  if (!existing.canRebind()) {
@@ -31775,7 +31862,7 @@ var AcpSessionManager = class {
31775
31862
  */
31776
31863
  inspectAgentSettings = async (options) => await this.#processes.runTransient(
31777
31864
  options.signal,
31778
- async () => await AcpProcessSession.start(
31865
+ async () => await AgentSession.start(
31779
31866
  {
31780
31867
  ...options,
31781
31868
  sessionId: `agent-settings-${crypto.randomUUID()}`
@@ -31806,10 +31893,10 @@ var AcpSessionManager = class {
31806
31893
  * Use inspectAgentSettings for Agent-scoped settings discovery.
31807
31894
  */
31808
31895
  inspectSession = async (options, metrics = unmeasuredOperationMetrics) => {
31809
- if (this.#sessions.pending(options.sessionId) !== void 0 || this.#sessions.get(options.sessionId) !== void 0) {
31896
+ if (this.#executionProcesses.pending(options.sessionId) !== void 0 || this.#executionProcesses.get(options.sessionId) !== void 0) {
31810
31897
  throw new AcpExecutionError("The configuration inspection session is already in use", {}, "session_busy");
31811
31898
  }
31812
- return await this.#sessions.use(options.sessionId, async () => {
31899
+ return await this.#executionProcesses.use(options.sessionId, async () => {
31813
31900
  const runtime = await this.#startPreparation(options, metrics);
31814
31901
  try {
31815
31902
  return runtime.prepared();
@@ -31823,12 +31910,12 @@ var AcpSessionManager = class {
31823
31910
  });
31824
31911
  };
31825
31912
  prepareExecutionSession = async (options) => {
31826
- const pending = this.#sessions.pending(options.sessionId);
31913
+ const pending = this.#executionProcesses.pending(options.sessionId);
31827
31914
  if (pending !== void 0) {
31828
31915
  await pending;
31829
31916
  return await this.prepareExecutionSession(options);
31830
31917
  }
31831
- const existing = this.#sessions.get(options.sessionId);
31918
+ const existing = this.#executionProcesses.get(options.sessionId);
31832
31919
  if (existing === void 0) {
31833
31920
  return (await this.#startPreparation(options)).prepared();
31834
31921
  }
@@ -31840,7 +31927,7 @@ var AcpSessionManager = class {
31840
31927
  );
31841
31928
  }
31842
31929
  if (existing.usesEnvironment(options.agent.environment)) {
31843
- this.#sessions.touch(options.sessionId, existing);
31930
+ this.#executionProcesses.touch(options.sessionId, existing);
31844
31931
  return existing.prepared();
31845
31932
  }
31846
31933
  if (existing.hasRunningTurn()) {
@@ -31852,49 +31939,21 @@ var AcpSessionManager = class {
31852
31939
  }
31853
31940
  return (await this.#replaceExecutionPreparation(existing, options)).prepared();
31854
31941
  };
31855
- prepareNativeSessionBrowser = async (options) => {
31856
- const pending = this.#nativeBrowserSessions.pending(options.sessionId);
31857
- if (pending !== void 0) {
31858
- const runtime2 = await pending;
31859
- if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
31860
- this.#nativeBrowserSessions.touch(options.sessionId, runtime2);
31861
- return runtime2.prepared();
31862
- }
31863
- return await this.prepareNativeSessionBrowser(options);
31864
- }
31865
- const existing = this.#nativeBrowserSessions.get(options.sessionId);
31866
- if (existing !== void 0) {
31867
- if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
31868
- this.#nativeBrowserSessions.touch(options.sessionId, existing);
31869
- return existing.prepared();
31870
- }
31871
- if (!existing.canRebind()) {
31872
- throw new AcpExecutionError(
31873
- "The agent or workspace cannot change after a conversation has started",
31874
- {},
31875
- "session_identity_mismatch"
31876
- );
31877
- }
31878
- const runtime2 = await this.#replaceNativeBrowserPreparation(existing, options);
31879
- return runtime2.prepared();
31880
- }
31881
- const runtime = await this.#startNativeBrowserPreparation(options);
31882
- return runtime.prepared();
31883
- };
31942
+ prepareNativeSessionBrowser = (options) => this.#queryProcesses.prepare(options);
31884
31943
  configureSession = async (options) => {
31885
- return await this.#sessions.use(options.sessionId, async () => {
31944
+ return await this.#executionProcesses.use(options.sessionId, async () => {
31886
31945
  const runtime = await this.ensureSession(options);
31887
31946
  return await runtime.configure(options);
31888
31947
  });
31889
31948
  };
31890
31949
  cancelPrompt = async (sessionId) => {
31891
31950
  await this.#executions.cancel(sessionId, async () => {
31892
- const runtime = this.#sessions.get(sessionId);
31951
+ const runtime = this.#executionProcesses.get(sessionId);
31893
31952
  if (runtime !== void 0) {
31894
31953
  try {
31895
31954
  await runtime.cancel();
31896
31955
  } finally {
31897
- if (this.#sessions.detach(sessionId, runtime)) {
31956
+ if (this.#executionProcesses.detach(sessionId, runtime)) {
31898
31957
  this.#processes.releaseClosed(runtime);
31899
31958
  }
31900
31959
  }
@@ -31905,14 +31964,14 @@ var AcpSessionManager = class {
31905
31964
  if (this.#executions.command(options.sessionId) !== options.targetCommandId) {
31906
31965
  throw new AcpExecutionError("The target turn is no longer active", {}, "steering_target_unavailable");
31907
31966
  }
31908
- const pending = this.#sessions.pending(options.sessionId);
31967
+ const pending = this.#executionProcesses.pending(options.sessionId);
31909
31968
  if (pending !== void 0) {
31910
31969
  await pending;
31911
31970
  }
31912
31971
  if (this.#executions.command(options.sessionId) !== options.targetCommandId) {
31913
31972
  throw new AcpExecutionError("The target turn is no longer active", {}, "steering_target_unavailable");
31914
31973
  }
31915
- const runtime = this.#sessions.get(options.sessionId);
31974
+ const runtime = this.#executionProcesses.get(options.sessionId);
31916
31975
  if (runtime === void 0 || !runtime.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
31917
31976
  throw new AcpExecutionError(
31918
31977
  "The target turn execution context is unavailable",
@@ -31970,7 +32029,7 @@ var AcpSessionManager = class {
31970
32029
  throw error62;
31971
32030
  }
31972
32031
  } catch (error62) {
31973
- const failedRuntime = this.#sessions.get(options.sessionId);
32032
+ const failedRuntime = this.#executionProcesses.get(options.sessionId);
31974
32033
  if (failedRuntime !== void 0) {
31975
32034
  await this.#retireSessionProcess(
31976
32035
  options.sessionId,
@@ -31992,35 +32051,32 @@ var AcpSessionManager = class {
31992
32051
  await this.#executions.cancellation(options.sessionId);
31993
32052
  } finally {
31994
32053
  this.#executions.finish(options.sessionId, options.commandId);
31995
- this.#sessions.touch(options.sessionId);
32054
+ this.#executionProcesses.touch(options.sessionId);
31996
32055
  this.#processes.notifyChanged();
31997
32056
  }
31998
32057
  }
31999
32058
  };
32000
32059
  respondPermission = async (options) => {
32001
- const runtime = this.#sessions.get(options.sessionId);
32060
+ const runtime = this.#executionProcesses.get(options.sessionId);
32002
32061
  if (runtime === void 0) {
32003
32062
  throw new AcpExecutionError("The permission request session is unavailable", {}, "session_not_found");
32004
32063
  }
32005
32064
  await runtime.respondPermission(options);
32006
32065
  };
32007
32066
  respondElicitation = async (options) => {
32008
- const runtime = this.#sessions.get(options.sessionId);
32067
+ const runtime = this.#executionProcesses.get(options.sessionId);
32009
32068
  if (runtime === void 0) {
32010
32069
  throw new AcpExecutionError("The elicitation request session is unavailable", {}, "session_not_found");
32011
32070
  }
32012
32071
  await runtime.respondElicitation(options);
32013
32072
  };
32014
32073
  close = async () => {
32015
- const sessions = [...this.#sessions.entries()];
32016
- const nativeBrowserSessions = [...this.#nativeBrowserSessions.entries()];
32074
+ const sessions = [...this.#executionProcesses.entries()];
32017
32075
  await Promise.all([
32018
32076
  ...sessions.map(
32019
32077
  async ([sessionId, runtime]) => await this.#retireSessionProcess(sessionId, runtime, async () => await runtime.close())
32020
32078
  ),
32021
- ...nativeBrowserSessions.map(
32022
- async ([sessionId, runtime]) => await this.#retireNativeBrowserProcess(sessionId, runtime, async () => await runtime.close())
32023
- )
32079
+ this.#queryProcesses.close()
32024
32080
  ]);
32025
32081
  };
32026
32082
  findSessions = (sessionIds) => sessionIds.flatMap((sessionId) => {
@@ -32028,17 +32084,17 @@ var AcpSessionManager = class {
32028
32084
  return stored instanceof FoundAcpStoredSession ? [stored.session] : [];
32029
32085
  });
32030
32086
  findLinkedSessions = (agentId, nativeSessionId) => this.#store.findNative(agentId, nativeSessionId);
32031
- hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
32087
+ hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#executionProcesses.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
32032
32088
  createNativeSession = async (options) => {
32033
32089
  const temporarySessionId = `new-${crypto.randomUUID()}`;
32034
32090
  const temporaryOptions = { ...options, sessionId: temporarySessionId };
32035
- return await this.#sessions.use(temporarySessionId, async () => {
32091
+ return await this.#executionProcesses.use(temporarySessionId, async () => {
32036
32092
  try {
32037
32093
  const runtime = await this.#startPreparation(temporaryOptions);
32038
32094
  let adopted = false;
32039
32095
  try {
32040
32096
  const nativeSessionId = runtime.nativeSessionId();
32041
- if (!isNativeChatSessionId(options.agent.id, nativeSessionId) || this.#sessions.get(nativeSessionId) !== void 0 || !(this.#store.read(nativeSessionId) instanceof MissingAcpStoredSession)) {
32097
+ if (!isNativeChatSessionId(options.agent.id, nativeSessionId) || this.#executionProcesses.get(nativeSessionId) !== void 0 || !(this.#store.read(nativeSessionId) instanceof MissingAcpStoredSession)) {
32042
32098
  throw new AcpExecutionError(
32043
32099
  "The Agent returned an invalid new Session ID",
32044
32100
  {},
@@ -32046,9 +32102,9 @@ var AcpSessionManager = class {
32046
32102
  );
32047
32103
  }
32048
32104
  runtime.adoptNativeSessionId(nativeSessionId);
32049
- this.#sessions.detach(temporarySessionId, runtime);
32050
- this.#sessions.retain(nativeSessionId, runtime);
32051
- this.#processes.retain(runtime, this.#retention(nativeSessionId, "execution"));
32105
+ this.#executionProcesses.detach(temporarySessionId, runtime);
32106
+ this.#executionProcesses.retain(nativeSessionId, runtime);
32107
+ this.#processes.retain(runtime, this.#retention(nativeSessionId));
32052
32108
  adopted = true;
32053
32109
  return nativeSessionId;
32054
32110
  } finally {
@@ -32066,7 +32122,7 @@ var AcpSessionManager = class {
32066
32122
  });
32067
32123
  };
32068
32124
  ensureSession = async (options) => {
32069
- const existing = this.#sessions.get(options.sessionId);
32125
+ const existing = this.#executionProcesses.get(options.sessionId);
32070
32126
  if (existing !== void 0) {
32071
32127
  if (!existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
32072
32128
  throw new AcpExecutionError(
@@ -32075,46 +32131,27 @@ var AcpSessionManager = class {
32075
32131
  "session_identity_mismatch"
32076
32132
  );
32077
32133
  }
32078
- this.#sessions.touch(options.sessionId, existing);
32134
+ this.#executionProcesses.touch(options.sessionId, existing);
32079
32135
  return existing;
32080
32136
  }
32081
32137
  await this.prepareSession(options);
32082
- const started = this.#sessions.get(options.sessionId);
32138
+ const started = this.#executionProcesses.get(options.sessionId);
32083
32139
  if (started === void 0) {
32084
32140
  throw new AcpExecutionError("ACP session did not start");
32085
32141
  }
32086
32142
  return started;
32087
32143
  };
32088
- async #ensureNativeSessionBrowser(options) {
32089
- const existing = this.#nativeBrowserSessions.get(options.sessionId);
32090
- if (existing !== void 0) {
32091
- if (!existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
32092
- throw new AcpExecutionError(
32093
- "The agent or workspace cannot change after a conversation has started",
32094
- {},
32095
- "session_identity_mismatch"
32096
- );
32097
- }
32098
- this.#nativeBrowserSessions.touch(options.sessionId, existing);
32099
- return existing;
32100
- }
32101
- await this.prepareNativeSessionBrowser(options);
32102
- const started = this.#nativeBrowserSessions.get(options.sessionId);
32103
- if (started === void 0) {
32104
- throw new AcpExecutionError("ACP native session browser did not start");
32105
- }
32106
- return started;
32107
- }
32108
32144
  listNativeSessions = async (options, cursor) => {
32109
- return await this.#nativeBrowserSessions.use(options.sessionId, async () => {
32110
- return await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(cursor, options.signal);
32111
- });
32145
+ return await this.#queryProcesses.use(
32146
+ options,
32147
+ async (runtime) => await runtime.listNativeSessions(cursor, options.signal)
32148
+ );
32112
32149
  };
32113
32150
  previewNativeSession = async (options, nativeSessionId) => {
32114
32151
  const key = `${options.agent.id}:${nativeSessionId}`;
32115
32152
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
32116
32153
  if (this.#nativeOperations.has(key) || linked.some(
32117
- (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#sessions.pending(entry.sessionId) !== void 0
32154
+ (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#executionProcesses.pending(entry.sessionId) !== void 0
32118
32155
  )) {
32119
32156
  throw new AcpExecutionError(
32120
32157
  "Wait for the native session's running operation to finish",
@@ -32124,25 +32161,13 @@ var AcpSessionManager = class {
32124
32161
  }
32125
32162
  this.#nativeOperations.add(key);
32126
32163
  try {
32127
- return await this.#processes.runTransient(
32128
- options.signal,
32129
- async () => await AcpProcessSession.startNativeSessionBrowser(
32130
- options,
32131
- () => this.#nativeBrowserObserver,
32132
- new MemoryAcpSessionStore()
32133
- ),
32134
- async (runtime) => {
32135
- runtime.selectNativeSession(nativeSessionId);
32136
- return await runtime.loadHistory(options.signal);
32137
- },
32138
- async (runtime) => await runtime.closeProcess()
32139
- );
32164
+ return await this.#queryProcesses.preview(options, nativeSessionId);
32140
32165
  } finally {
32141
32166
  this.#nativeOperations.delete(key);
32142
32167
  }
32143
32168
  };
32144
32169
  loadSessionHistory = async (options) => {
32145
- return await this.#sessions.use(options.sessionId, async () => {
32170
+ return await this.#executionProcesses.use(options.sessionId, async () => {
32146
32171
  const runtime = await this.ensureSession(options);
32147
32172
  const stored = this.#store.read(options.sessionId);
32148
32173
  if (stored instanceof FoundAcpStoredSession && this.#nativeHistoryReader !== null) {
@@ -32165,7 +32190,7 @@ var AcpSessionManager = class {
32165
32190
  }
32166
32191
  const linked = this.#store.findNative(options.agent.id, origin.nativeSessionId);
32167
32192
  if (linked.some(
32168
- (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#sessions.pending(entry.sessionId) !== void 0
32193
+ (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#executionProcesses.pending(entry.sessionId) !== void 0
32169
32194
  )) {
32170
32195
  throw new AcpExecutionError(
32171
32196
  "Wait for the native session's running operation to finish",
@@ -32175,7 +32200,7 @@ var AcpSessionManager = class {
32175
32200
  }
32176
32201
  const existing = linked[0];
32177
32202
  if (origin.kind === "import" && existing !== void 0) {
32178
- return await this.#sessions.use(existing.sessionId, async () => {
32203
+ return await this.#executionProcesses.use(existing.sessionId, async () => {
32179
32204
  const runtime = await this.ensureSession({
32180
32205
  ...options,
32181
32206
  sessionId: existing.sessionId
@@ -32199,10 +32224,10 @@ var AcpSessionManager = class {
32199
32224
  }
32200
32225
  });
32201
32226
  }
32202
- if (this.#sessions.get(options.sessionId) !== void 0 || this.#sessions.pending(options.sessionId) !== void 0 || this.#store.read(options.sessionId) instanceof FoundAcpStoredSession || this.#store.read(options.sessionId) instanceof DeletedAcpStoredSession) {
32227
+ if (this.#executionProcesses.get(options.sessionId) !== void 0 || this.#executionProcesses.pending(options.sessionId) !== void 0 || this.#store.read(options.sessionId) instanceof FoundAcpStoredSession || this.#store.read(options.sessionId) instanceof DeletedAcpStoredSession) {
32203
32228
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
32204
32229
  }
32205
- return await this.#sessions.use(options.sessionId, async () => {
32230
+ return await this.#executionProcesses.use(options.sessionId, async () => {
32206
32231
  this.#nativeOperations.add(key);
32207
32232
  try {
32208
32233
  const runtime = await this.#startPreparation({ ...options, origin });
@@ -32219,7 +32244,7 @@ var AcpSessionManager = class {
32219
32244
  }
32220
32245
  } catch (error62) {
32221
32246
  this.#store.remove(options.sessionId);
32222
- const runtime = this.#sessions.get(options.sessionId);
32247
+ const runtime = this.#executionProcesses.get(options.sessionId);
32223
32248
  if (runtime !== void 0) {
32224
32249
  await this.#retireSessionProcess(
32225
32250
  options.sessionId,
@@ -32234,12 +32259,11 @@ var AcpSessionManager = class {
32234
32259
  });
32235
32260
  };
32236
32261
  deleteNativeSession = async (options, nativeSessionId) => {
32237
- return await this.#nativeBrowserSessions.use(options.sessionId, async () => {
32238
- const runtime = await this.#ensureNativeSessionBrowser(options);
32262
+ return await this.#queryProcesses.use(options, async (runtime) => {
32239
32263
  const key = `${options.agent.id}:${nativeSessionId}`;
32240
32264
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
32241
32265
  if (this.#nativeOperations.has(key) || linked.some(
32242
- (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#sessions.pending(entry.sessionId) !== void 0
32266
+ (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#executionProcesses.pending(entry.sessionId) !== void 0
32243
32267
  )) {
32244
32268
  throw new AcpExecutionError(
32245
32269
  "Wait for the native session's running operation to finish",
@@ -32250,7 +32274,7 @@ var AcpSessionManager = class {
32250
32274
  this.#nativeOperations.add(key);
32251
32275
  try {
32252
32276
  for (const entry of linked) {
32253
- const active = this.#sessions.get(entry.sessionId);
32277
+ const active = this.#executionProcesses.get(entry.sessionId);
32254
32278
  if (active !== void 0 && active !== runtime) {
32255
32279
  await this.#retireSessionProcess(entry.sessionId, active, async () => await active.close());
32256
32280
  }
@@ -32259,11 +32283,7 @@ var AcpSessionManager = class {
32259
32283
  await runtime.deleteNativeSession(nativeSessionId, options.signal);
32260
32284
  const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
32261
32285
  if (runtime.nativeSessionId() === nativeSessionId) {
32262
- await this.#retireNativeBrowserProcess(
32263
- options.sessionId,
32264
- runtime,
32265
- async () => await runtime.close()
32266
- );
32286
+ await this.#queryProcesses.retire(options.sessionId, runtime);
32267
32287
  }
32268
32288
  return deleted;
32269
32289
  } finally {
@@ -32276,9 +32296,9 @@ var AcpSessionManager = class {
32276
32296
 
32277
32297
  // src/acp/run-prompt.ts
32278
32298
  async function runAcpPrompt(options) {
32279
- const sessions = new AcpSessionManager();
32299
+ const agentRuntime = new AgentRuntimeManager();
32280
32300
  try {
32281
- return await sessions.runPrompt({
32301
+ return await agentRuntime.runPrompt({
32282
32302
  additionalDirectories: [],
32283
32303
  agent: new LocalAgentDefinition("test-agent", "Test agent", options.agentCommand, options.agentArguments),
32284
32304
  cwd: options.cwd,
@@ -32293,7 +32313,7 @@ async function runAcpPrompt(options) {
32293
32313
  signal: options.signal
32294
32314
  });
32295
32315
  } finally {
32296
- await sessions.close();
32316
+ await agentRuntime.close();
32297
32317
  }
32298
32318
  }
32299
32319
 
@@ -33499,6 +33519,7 @@ var COLLABORATION_MODE_SETTING_ID = "collaboration_mode";
33499
33519
  var MODEL_CATALOG_LIMIT = 1e3;
33500
33520
  var FAST_TIER = "fast";
33501
33521
  var SERVICE_TIER_FAST = "priority";
33522
+ var CODEX_COMMANDS = Object.freeze([{ description: "Compact the conversation context", name: "compact" }]);
33502
33523
  var WORKSPACE_WRITE_POLICY = Object.freeze({
33503
33524
  excludeSlashTmp: false,
33504
33525
  excludeTmpdirEnvVar: false,
@@ -33579,6 +33600,9 @@ function promptInput(prompt) {
33579
33600
  }
33580
33601
  return input2;
33581
33602
  }
33603
+ function isCompactPrompt(prompt) {
33604
+ return prompt.length === 1 && prompt[0]?.type === "text" && prompt[0].text.trim() === "/compact";
33605
+ }
33582
33606
  function steeringPromptInput(prompt) {
33583
33607
  const input2 = [];
33584
33608
  for (const block of prompt) {
@@ -33833,6 +33857,7 @@ var CodexAcpAgent = class {
33833
33857
  };
33834
33858
  this.#collaborationModeSelected = false;
33835
33859
  await this.#probeCollaborationMode(context.signal);
33860
+ await this.#emitAvailableCommands();
33836
33861
  return { configOptions: this.#configOptions(), sessionId: created.thread.id };
33837
33862
  }).onRequest(methods4.agent.session.setConfigOption, async (context) => {
33838
33863
  this.#applySelection(context.params.configId, context.params.value);
@@ -33851,6 +33876,7 @@ var CodexAcpAgent = class {
33851
33876
  this.#selectRestoredThread(resumed);
33852
33877
  await this.#probeCollaborationMode(context.signal);
33853
33878
  await this.#replayHistory(resumed.turns);
33879
+ await this.#emitAvailableCommands();
33854
33880
  return { configOptions: this.#configOptions() };
33855
33881
  }).onRequest(methods4.agent.session.fork, async (context) => {
33856
33882
  const forked = threadForkResponseSchema.parse(
@@ -33867,6 +33893,7 @@ var CodexAcpAgent = class {
33867
33893
  this.#selectRestoredThread(forked);
33868
33894
  await this.#probeCollaborationMode(context.signal);
33869
33895
  await this.#replayHistory(forked.turns);
33896
+ await this.#emitAvailableCommands();
33870
33897
  return { configOptions: this.#configOptions(), sessionId: forked.thread.id };
33871
33898
  }).onRequest(methods4.agent.session.resume, async (context) => {
33872
33899
  const resumed = threadResumeResponseSchema.parse(
@@ -33878,8 +33905,12 @@ var CodexAcpAgent = class {
33878
33905
  );
33879
33906
  this.#selectRestoredThread(resumed);
33880
33907
  await this.#probeCollaborationMode(context.signal);
33908
+ await this.#emitAvailableCommands();
33881
33909
  return { configOptions: this.#configOptions() };
33882
33910
  }).onRequest(methods4.agent.session.prompt, async (context) => {
33911
+ if (isCompactPrompt(context.params.prompt)) {
33912
+ return await this.#compact(context.signal);
33913
+ }
33883
33914
  return await this.#runTurn(promptInput(context.params.prompt), context.signal);
33884
33915
  }).onRequest(
33885
33916
  "_session/steering",
@@ -34159,6 +34190,12 @@ var CodexAcpAgent = class {
34159
34190
  update
34160
34191
  });
34161
34192
  };
34193
+ #emitAvailableCommands = async () => {
34194
+ await this.#emit({
34195
+ availableCommands: CODEX_COMMANDS.map((command) => ({ ...command })),
34196
+ sessionUpdate: "available_commands_update"
34197
+ });
34198
+ };
34162
34199
  /** Pushes the current settings so a mode change Codex applied reaches the Run settings panel. */
34163
34200
  #emitConfigOptionsUpdate = async () => {
34164
34201
  const connection = this.#connection;
@@ -34469,6 +34506,35 @@ var CodexAcpAgent = class {
34469
34506
  }
34470
34507
  }
34471
34508
  };
34509
+ #compact = async (signal) => {
34510
+ signal.throwIfAborted();
34511
+ if (this.#turn !== null) {
34512
+ throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
34513
+ }
34514
+ const completion = Promise.withResolvers();
34515
+ void completion.promise.catch(() => {
34516
+ });
34517
+ const aborted2 = () => {
34518
+ completion.reject(signal.reason);
34519
+ void this.close().catch((cause) => {
34520
+ console.error("The cancelled Codex endpoint could not release its process tree", cause);
34521
+ });
34522
+ };
34523
+ signal.addEventListener("abort", aborted2, { once: true });
34524
+ const turn = { completion, turn: { id: "" } };
34525
+ this.#streamedReasoningItemIds.clear();
34526
+ this.#turn = turn;
34527
+ try {
34528
+ await this.#appServer.request("thread/compact/start", { threadId: this.#nativeSessionId }, signal);
34529
+ return await completion.promise;
34530
+ } finally {
34531
+ signal.removeEventListener("abort", aborted2);
34532
+ if (this.#turn === turn) {
34533
+ this.#turn = null;
34534
+ this.#streamedReasoningItemIds.clear();
34535
+ }
34536
+ }
34537
+ };
34472
34538
  #steerTurn = async (params, signal) => {
34473
34539
  if (typeof params !== "object" || params === null) {
34474
34540
  throw new AcpExecutionError("Codex received an invalid steering request", {}, "invalid_request");
@@ -42542,7 +42608,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
42542
42608
  activeTurns.recordEvent(event);
42543
42609
  publisher.publish(sessionId, event);
42544
42610
  };
42545
- const sessions = new AcpSessionManager(
42611
+ const agentRuntime = new AgentRuntimeManager(
42546
42612
  new DaemonAcpObserver(recordSessionEvent),
42547
42613
  sessionStore,
42548
42614
  {
@@ -42564,20 +42630,28 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
42564
42630
  config2.relayUrl,
42565
42631
  new DaemonDiagnosticLog(stateDirectory)
42566
42632
  );
42567
- const nativeSessions = new NativeSessionService(config2, directories, sessions, audit, async (request, options2) => {
42568
- return await activeTurns.executionSnapshot(async (command) => {
42569
- if (command.sessionId !== request.targetSessionId || command.agentId !== request.agentId) {
42570
- return false;
42571
- }
42572
- const cwd = await directories.resolve(command.bindingId, command.directoryId, options2.signal);
42573
- const additionalDirectories = await directories.resolveMany(
42574
- command.bindingId,
42575
- command.additionalDirectoryIds,
42576
- options2.signal
42577
- );
42578
- return cwd === options2.cwd && additionalDirectories.length === options2.additionalDirectories.length && additionalDirectories.every((directory, index) => directory === options2.additionalDirectories[index]);
42579
- });
42580
- });
42633
+ const nativeSessions = new NativeSessionService(
42634
+ config2,
42635
+ directories,
42636
+ agentRuntime,
42637
+ audit,
42638
+ async (request, options2) => {
42639
+ return await activeTurns.executionSnapshot(async (command) => {
42640
+ if (command.sessionId !== request.targetSessionId || command.agentId !== request.agentId) {
42641
+ return false;
42642
+ }
42643
+ const cwd = await directories.resolve(command.bindingId, command.directoryId, options2.signal);
42644
+ const additionalDirectories = await directories.resolveMany(
42645
+ command.bindingId,
42646
+ command.additionalDirectoryIds,
42647
+ options2.signal
42648
+ );
42649
+ return cwd === options2.cwd && additionalDirectories.length === options2.additionalDirectories.length && additionalDirectories.every(
42650
+ (directory, index) => directory === options2.additionalDirectories[index]
42651
+ );
42652
+ });
42653
+ }
42654
+ );
42581
42655
  const installations = new AgentInstallationManager(
42582
42656
  specifications,
42583
42657
  installationExecutor,
@@ -42653,7 +42727,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
42653
42727
  config: config2,
42654
42728
  directories,
42655
42729
  audit,
42656
- sessions,
42730
+ sessions: agentRuntime,
42657
42731
  installations,
42658
42732
  installationObserver,
42659
42733
  nativeSessions,
@@ -42696,7 +42770,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
42696
42770
  await installations.close();
42697
42771
  } finally {
42698
42772
  try {
42699
- await sessions.close();
42773
+ await agentRuntime.close();
42700
42774
  } finally {
42701
42775
  try {
42702
42776
  sessionStore.close();