@moxt-ai/mobius 0.0.449 → 0.0.451

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 (36) hide show
  1. package/dist/{chunk-LGPB3HHD.js → chunk-5QMXJEVI.js} +287 -57
  2. package/dist/{chunk-LGPB3HHD.js.map → chunk-5QMXJEVI.js.map} +2 -2
  3. package/dist/{chunk-INP7WEGL.js → chunk-XQBTUYWO.js} +2 -2
  4. package/dist/{chunk-INP7WEGL.js.map → chunk-XQBTUYWO.js.map} +1 -1
  5. package/dist/{cli-6H5E6DK2.js → cli-EWBWXBGR.js} +3 -3
  6. package/dist/cli.js +2 -2
  7. package/dist/engine/acp/adapter/session-events.d.ts.map +1 -1
  8. package/dist/engine/acp/adapter/session-events.js +1 -0
  9. package/dist/engine/acp/adapter/session-events.js.map +1 -1
  10. package/dist/engine/acp/agent/in-process-endpoint.d.ts +5 -0
  11. package/dist/engine/acp/agent/in-process-endpoint.d.ts.map +1 -1
  12. package/dist/engine/session/api/session-layer.d.ts.map +1 -1
  13. package/dist/engine/session/api/session-layer.js +2 -2
  14. package/dist/engine/session/api/session-layer.js.map +1 -1
  15. package/dist/engine/session/live/agent-session.d.ts +10 -3
  16. package/dist/engine/session/live/agent-session.d.ts.map +1 -1
  17. package/dist/engine/session/live/agent-session.js +162 -34
  18. package/dist/engine/session/live/agent-session.js.map +1 -1
  19. package/dist/engine/session/manager/session-manager.d.ts.map +1 -1
  20. package/dist/engine/session/manager/session-manager.js +6 -4
  21. package/dist/engine/session/manager/session-manager.js.map +1 -1
  22. package/dist/engine/session/prompt/prompt-lifecycle.d.ts +1 -1
  23. package/dist/engine/session/prompt/prompt-lifecycle.d.ts.map +1 -1
  24. package/dist/engine/session/prompt/prompt-lifecycle.js +7 -2
  25. package/dist/engine/session/prompt/prompt-lifecycle.js.map +1 -1
  26. package/dist/engine/session/turn/session-execution.d.ts +3 -1
  27. package/dist/engine/session/turn/session-execution.d.ts.map +1 -1
  28. package/dist/engine/session/turn/session-execution.js +28 -5
  29. package/dist/engine/session/turn/session-execution.js.map +1 -1
  30. package/dist/engine/session/turn/session-turns.d.ts +1 -1
  31. package/dist/engine/session/turn/session-turns.d.ts.map +1 -1
  32. package/dist/engine/session/turn/session-turns.js +15 -3
  33. package/dist/engine/session/turn/session-turns.js.map +1 -1
  34. package/dist/engine.js +2 -2
  35. package/package.json +1 -1
  36. /package/dist/{cli-6H5E6DK2.js.map → cli-EWBWXBGR.js.map} +0 -0
@@ -3,7 +3,7 @@ import {
3
3
  __export,
4
4
  __using,
5
5
  package_default
6
- } from "./chunk-INP7WEGL.js";
6
+ } from "./chunk-XQBTUYWO.js";
7
7
 
8
8
  // src/engine/runtime/relay/runtime-revocation.ts
9
9
  var runtimeRevocationCloseCode = 1008;
@@ -67878,7 +67878,7 @@ var ClaudeAcpAgent = class {
67878
67878
  };
67879
67879
  const noPromptInFlight = () => !(session.activeTurn && !session.activeTurn.settled) && firstUnsettledQueuedTurn() === void 0 && (session.pendingOrphanResults ?? 0) === 0 && (session.orphanCommands?.size ?? 0) === 0;
67880
67880
  const startAgentTurn = async () => {
67881
- if (session.agentTurn !== void 0 || !noPromptInFlight()) {
67881
+ if (session.agentTurn !== void 0 || session.agentCycleAbandoned === true || !noPromptInFlight()) {
67882
67882
  return;
67883
67883
  }
67884
67884
  await publishBackgroundTasks();
@@ -67900,6 +67900,9 @@ var ClaudeAcpAgent = class {
67900
67900
  return;
67901
67901
  }
67902
67902
  session.agentTurn = void 0;
67903
+ if (agentTurn.backstopArmed === true) {
67904
+ disarmForceCancel(session);
67905
+ }
67903
67906
  await publishBackgroundTasks();
67904
67907
  const ended = {
67905
67908
  stage: "ended",
@@ -67910,6 +67913,45 @@ var ClaudeAcpAgent = class {
67910
67913
  update: { sessionUpdate: "session_info_update", _meta: { [AGENT_TURN_META2]: ended } }
67911
67914
  });
67912
67915
  };
67916
+ const abandonAgentWork = async (message) => {
67917
+ const agentTurn = session.agentTurn;
67918
+ session.agentTurn = void 0;
67919
+ session.agentCycleAbandoned = false;
67920
+ backgroundTasks.clear();
67921
+ awaitingBackgroundResults.clear();
67922
+ processingBackgroundResults.clear();
67923
+ backgroundTaskDetails.clear();
67924
+ try {
67925
+ await publishBackgroundTasks();
67926
+ if (agentTurn === void 0) {
67927
+ return;
67928
+ }
67929
+ if (agentTurn.backstopArmed === true) {
67930
+ disarmForceCancel(session);
67931
+ }
67932
+ const report = agentTurn.cancelled ? { stage: "ended", stopReason: "cancelled" } : { stage: "failed", message };
67933
+ await this.client.sessionUpdate({
67934
+ sessionId: params.sessionId,
67935
+ update: { sessionUpdate: "session_info_update", _meta: { [AGENT_TURN_META2]: report } }
67936
+ });
67937
+ } catch (error62) {
67938
+ this.logger.error(`Session ${params.sessionId}: could not report the end of the Agent's own work: ${error62}`);
67939
+ }
67940
+ };
67941
+ session.stopBackgroundWork = async () => {
67942
+ const running = [...backgroundTasks].filter((taskId) => backgroundTaskDetails.get(taskId)?.ambient !== true);
67943
+ if (running.length === 0) {
67944
+ return;
67945
+ }
67946
+ session.agentCycleAbandoned = true;
67947
+ await Promise.all(running.map(async (taskId) => {
67948
+ try {
67949
+ await session.query.stopTask(taskId);
67950
+ } catch (error62) {
67951
+ this.logger.error(`Session ${params.sessionId}: could not stop background task ${taskId}: ${error62}`);
67952
+ }
67953
+ }));
67954
+ };
67913
67955
  const turnAwaitingSubagents = (turn) => {
67914
67956
  if (!turn.spawnedTaskIds?.size) {
67915
67957
  return false;
@@ -68042,10 +68084,15 @@ var ClaudeAcpAgent = class {
68042
68084
  this.trackResultOwedBySettledTurn(session, session.activeTurn);
68043
68085
  }
68044
68086
  settleActive(turnOutcome(session, "cancelled"));
68087
+ if (session.agentTurn?.cancelled === true && this.sessions[params.sessionId]) {
68088
+ session.agentCycleAbandoned = true;
68089
+ await endAgentTurn();
68090
+ }
68045
68091
  session.emittedAssistantText = false;
68046
68092
  if (!this.sessions[params.sessionId]) {
68047
68093
  void nextMessage.catch(() => {
68048
68094
  });
68095
+ await abandonAgentWork("The Agent session was closed");
68049
68096
  return;
68050
68097
  }
68051
68098
  cancelController = new AbortController();
@@ -68064,6 +68111,7 @@ var ClaudeAcpAgent = class {
68064
68111
  }
68065
68112
  }
68066
68113
  session.turnQueue = [];
68114
+ await abandonAgentWork("The Claude Agent process ended");
68067
68115
  this.closeQueryStream(session);
68068
68116
  return;
68069
68117
  }
@@ -68251,6 +68299,7 @@ var ClaudeAcpAgent = class {
68251
68299
  if (noPromptInFlight()) {
68252
68300
  await endAgentTurn();
68253
68301
  }
68302
+ session.agentCycleAbandoned = false;
68254
68303
  }
68255
68304
  break;
68256
68305
  }
@@ -68406,7 +68455,14 @@ var ClaudeAcpAgent = class {
68406
68455
  backgroundTasks.add(message.task_id);
68407
68456
  reportBackgroundActivity();
68408
68457
  }
68409
- if (message.patch.status === "completed" || message.patch.status === "failed" || message.patch.status === "killed") {
68458
+ if (message.patch.status === "killed") {
68459
+ session.liveBackgroundTasks.delete(message.task_id);
68460
+ backgroundTasks.delete(message.task_id);
68461
+ awaitingBackgroundResults.delete(message.task_id);
68462
+ processingBackgroundResults.delete(message.task_id);
68463
+ backgroundTaskDetails.delete(message.task_id);
68464
+ reportBackgroundActivity();
68465
+ } else if (message.patch.status === "completed" || message.patch.status === "failed") {
68410
68466
  session.liveBackgroundTasks.delete(message.task_id);
68411
68467
  if (backgroundTasks.delete(message.task_id)) {
68412
68468
  awaitingBackgroundResults.add(message.task_id);
@@ -69018,11 +69074,13 @@ ${message.api_refusal_explanation}` : "";
69018
69074
  if (processDied) {
69019
69075
  this.logger.error(`Session ${params.sessionId}: Claude Agent process died: ${message}`);
69020
69076
  failAllTurns(RequestError.internalError(void 0, "The Claude Agent process exited unexpectedly. Please start a new session."));
69077
+ await abandonAgentWork("The Claude Agent process exited unexpectedly");
69021
69078
  this.closeQueryStream(session);
69022
69079
  delete this.sessions[params.sessionId];
69023
69080
  } else {
69024
69081
  this.logger.error(`Session ${params.sessionId}: query stream error: ${message}`);
69025
69082
  failAllTurns(error62);
69083
+ await abandonAgentWork("The Claude Agent stopped responding to the session");
69026
69084
  this.closeQueryStream(session);
69027
69085
  }
69028
69086
  }
@@ -69074,7 +69132,13 @@ ${message.api_refusal_explanation}` : "";
69074
69132
  this.trackOrphanCommand(session, turn.promptUuid, "started");
69075
69133
  }
69076
69134
  }
69135
+ /** A client's cancel also stops the background work its turn left running, so nothing wakes the model later. */
69077
69136
  async cancel(params) {
69137
+ await this.interrupt(params, true);
69138
+ }
69139
+ /** Interrupts the session's in-flight work. Teardown passes `stopBackgroundWork: false`: closing a session is not
69140
+ * a member's Stop, so it leaves background tasks as they were, and a resumed session reports them interrupted. */
69141
+ async interrupt(params, stopBackgroundWork) {
69078
69142
  for (const submission of this.pendingSubmissions.get(params.sessionId) ?? []) {
69079
69143
  submission.abort();
69080
69144
  }
@@ -69092,6 +69156,9 @@ ${message.api_refusal_explanation}` : "";
69092
69156
  if (session.queryClosed) {
69093
69157
  return;
69094
69158
  }
69159
+ if (stopBackgroundWork) {
69160
+ void session.stopBackgroundWork?.();
69161
+ }
69095
69162
  if (isSteering(session.activeTurn)) {
69096
69163
  for (const uuid3 of session.activeTurn.steeredEchoes) {
69097
69164
  this.trackOrphanCommand(session, uuid3, "pending");
@@ -69145,7 +69212,10 @@ ${message.api_refusal_explanation}` : "";
69145
69212
  if (isSteering(session.activeTurn) && session.activeTurn.steeredSettle !== void 0) {
69146
69213
  session.idleBoundary = { kind: "accounted", turn: session.activeTurn ?? null };
69147
69214
  }
69148
- if (session.activeTurn && session.cancelController && !session.cancelController.signal.aborted && !session.forceCancelTimer) {
69215
+ if (session.agentTurn !== void 0 && !(session.activeTurn && !session.activeTurn.settled) && !session.forceCancelTimer) {
69216
+ session.agentTurn.backstopArmed = true;
69217
+ }
69218
+ if ((session.activeTurn || session.agentTurn?.backstopArmed === true) && session.cancelController && !session.cancelController.signal.aborted && !session.forceCancelTimer) {
69149
69219
  const cancelController = session.cancelController;
69150
69220
  session.forceCancelTimer = setTimeout(() => {
69151
69221
  this.logger.error(`Session ${params.sessionId}: cancel floor elapsed without the SDK yielding; forcing "cancelled". The underlying query may still be wedged \u2014 a new session may be required.`);
@@ -69206,7 +69276,7 @@ ${message.api_refusal_explanation}` : "";
69206
69276
  if (!session) {
69207
69277
  return;
69208
69278
  }
69209
- await this.cancel({ sessionId });
69279
+ await this.interrupt({ sessionId }, false);
69210
69280
  disarmForceCancel(session);
69211
69281
  session.cancelController?.abort();
69212
69282
  this.closeQueryStream(session);
@@ -80958,7 +81028,8 @@ var agentTurnReportSchema = external_exports.discriminatedUnion("stage", [
80958
81028
  reason: external_exports.enum(["background-task", "other"]).catch("other"),
80959
81029
  taskIds: external_exports.array(harnessText).max(1e3).readonly()
80960
81030
  }).readonly(),
80961
- external_exports.object({ stage: external_exports.literal("ended"), stopReason: external_exports.enum(["end_turn", "cancelled"]) }).readonly()
81031
+ external_exports.object({ stage: external_exports.literal("ended"), stopReason: external_exports.enum(["end_turn", "cancelled"]) }).readonly(),
81032
+ external_exports.object({ stage: external_exports.literal("failed"), message: harnessText }).readonly()
80962
81033
  ]);
80963
81034
  function harnessReports(update) {
80964
81035
  if (update.sessionUpdate !== "session_info_update") {
@@ -90528,6 +90599,7 @@ async function restoreSession(session, signal, recovery) {
90528
90599
 
90529
90600
  // src/engine/session/live/agent-session.ts
90530
90601
  var SESSION_CONTROL_COMMAND_ID = "session-control";
90602
+ var BACKGROUND_HOLD_LIMIT_MILLISECONDS = 24 * 60 * 60 * 1e3;
90531
90603
  var AgentSession = class _AgentSession {
90532
90604
  // The restore surface: AgentSessionRestore members expose private state to
90533
90605
  // session-restore.ts only. The class keeps the fields private.
@@ -90558,10 +90630,13 @@ var AgentSession = class _AgentSession {
90558
90630
  hasBackgroundActivity = () => this.#backgroundActivity !== "none";
90559
90631
  #backgroundActivity = "none";
90560
90632
  /**
90561
- * The Turn the Agent is running on its own, with no prompt from any client. It has a command of the Runtime's
90562
- * own, recorded with the same lifecycle events a client's prompt has.
90633
+ * The Turn the Agent is running on its own, with no prompt from any client. It continues the held command when one
90634
+ * is open (`held`); otherwise it has a command of the Runtime's own, recorded with the same lifecycle events a
90635
+ * client's prompt has.
90563
90636
  */
90564
90637
  #agentTurn = null;
90638
+ #held = null;
90639
+ #timer;
90565
90640
  /** The last command a client's prompt started; the Agent's own work continues it unless its work says otherwise. */
90566
90641
  #lastClientCommandId = void 0;
90567
90642
  /** The client command each piece of outstanding background work belongs to, fixed when it is first reported. */
@@ -90608,9 +90683,10 @@ var AgentSession = class _AgentSession {
90608
90683
  #restored = false;
90609
90684
  #sessionTitle = null;
90610
90685
  #sessionUpdatedAt = "";
90611
- constructor(agent2, cwd, additionalDirectories, mobiusSessionId, getObserver, agentCommand, store, metrics, adapter, externalize, promptSuggestions) {
90686
+ constructor(agent2, cwd, additionalDirectories, mobiusSessionId, getObserver, agentCommand, store, metrics, adapter, externalize, promptSuggestions, timer) {
90612
90687
  this.#agentCommand = () => agentCommand(this.#mobiusSessionId);
90613
90688
  this.#promptSuggestions = promptSuggestions;
90689
+ this.#timer = timer;
90614
90690
  this.#additionalDirectories = [...additionalDirectories];
90615
90691
  this.#adapter = adapter;
90616
90692
  this.#agentId = agent2.id;
@@ -90678,7 +90754,7 @@ var AgentSession = class _AgentSession {
90678
90754
  }
90679
90755
  };
90680
90756
  }
90681
- static async #start(options, getObserver, agentCommand, store, initialize, metrics, adapter, promptSuggestions) {
90757
+ static async #start(options, getObserver, agentCommand, store, initialize, metrics, adapter, promptSuggestions, timer) {
90682
90758
  for (let attempt = 1; attempt <= 2; attempt += 1) {
90683
90759
  await metrics.measure(
90684
90760
  "executable-validation",
@@ -90697,7 +90773,8 @@ var AgentSession = class _AgentSession {
90697
90773
  metrics,
90698
90774
  adapter,
90699
90775
  options.externalizeSessionUpdate,
90700
- promptSuggestions
90776
+ promptSuggestions,
90777
+ timer
90701
90778
  )
90702
90779
  );
90703
90780
  try {
@@ -90720,7 +90797,7 @@ var AgentSession = class _AgentSession {
90720
90797
  }
90721
90798
  throw new AcpExecutionError("ACP agent initialization failed");
90722
90799
  }
90723
- static start = async (options, recovery, getObserver, agentCommand, store, metrics, adapter, capabilities = unsupportedSessionCapabilities(), promptSuggestions = promptSuggestionsDisabled) => await _AgentSession.#start(
90800
+ static start = async (options, recovery, getObserver, agentCommand, store, metrics, adapter, capabilities = unsupportedSessionCapabilities(), promptSuggestions = promptSuggestionsDisabled, timer = systemTimer) => await _AgentSession.#start(
90724
90801
  options,
90725
90802
  getObserver,
90726
90803
  agentCommand,
@@ -90731,7 +90808,8 @@ var AgentSession = class _AgentSession {
90731
90808
  },
90732
90809
  metrics,
90733
90810
  adapter,
90734
- promptSuggestions
90811
+ promptSuggestions,
90812
+ timer
90735
90813
  );
90736
90814
  belongsTo = (agentId, cwd, additionalDirectories) => this.#agentId === agentId && this.#cwd === cwd && arraysEqual(this.#additionalDirectories, additionalDirectories);
90737
90815
  usesEnvironment = (environment) => recordsEqual(this.#environment, environment);
@@ -91058,6 +91136,7 @@ var AgentSession = class _AgentSession {
91058
91136
  this.writeStoredSession((/* @__PURE__ */ new Date()).toISOString());
91059
91137
  const lifecycle = options.lifecycle;
91060
91138
  if (lifecycle !== void 0) {
91139
+ await this.#releaseHeld();
91061
91140
  await this.recordLifecycleEvent({
91062
91141
  payload: {
91063
91142
  commandId: options.commandId,
@@ -91099,15 +91178,15 @@ var AgentSession = class _AgentSession {
91099
91178
  this.writeStoredSession((/* @__PURE__ */ new Date()).toISOString());
91100
91179
  if (lifecycle !== void 0) {
91101
91180
  const messageId = result._meta?.messageId;
91102
- await this.recordLifecycleEvent({
91103
- payload: {
91104
- commandId: options.commandId,
91105
- kind: "prompt.completed",
91106
- ...messageId === void 0 ? {} : { messageId },
91107
- stopReason: result.stopReason
91108
- },
91109
- type: "lifecycle-metadata"
91110
- });
91181
+ const completion = { ...messageId === void 0 ? {} : { messageId }, stopReason: result.stopReason };
91182
+ if (result.stopReason !== "cancelled" && this.#recordedBackground.length > 0) {
91183
+ this.#hold(options.commandId, lifecycle.attemptId, completion);
91184
+ } else {
91185
+ await this.recordLifecycleEvent({
91186
+ payload: { commandId: options.commandId, kind: "prompt.completed", ...completion },
91187
+ type: "lifecycle-metadata"
91188
+ });
91189
+ }
91111
91190
  }
91112
91191
  return result;
91113
91192
  } catch (error62) {
@@ -91317,41 +91396,117 @@ var AgentSession = class _AgentSession {
91317
91396
  await this.closeProcess();
91318
91397
  return;
91319
91398
  }
91320
- await this.#adapter.closeSession({ ...this.#target(), signal: AbortSignal.timeout(3e4) });
91399
+ try {
91400
+ await this.#adapter.closeSession({ ...this.#target(), signal: AbortSignal.timeout(3e4) });
91401
+ } finally {
91402
+ await this.#endAgentWork();
91403
+ }
91321
91404
  };
91322
91405
  closeProcess = async () => {
91323
91406
  if (this.#nativeIdentity.kind === "bound") {
91324
91407
  await this.#adapter.releaseSession({ ...this.#target(), signal: AbortSignal.timeout(3e4) });
91325
91408
  }
91409
+ await this.#endAgentWork();
91410
+ };
91411
+ /** Records that the Agent's process is gone, and with it the work it was doing on its own and its background work. */
91412
+ #endAgentWork = async () => {
91413
+ const failure2 = {
91414
+ code: "agent_process_closed",
91415
+ message: "The Agent process ended before the work it started on its own finished"
91416
+ };
91326
91417
  this.#backgroundActivity = "none";
91418
+ await this.#releaseHeld(this.#agentTurn?.held === true ? failure2 : void 0);
91419
+ await this.#failAgentTurn(failure2.code, failure2.message);
91420
+ await this.#recordBackgroundTasks([]);
91421
+ };
91422
+ #failAgentTurn = async (code, message) => {
91327
91423
  const agentTurn = this.#agentTurn;
91328
- if (agentTurn !== null) {
91424
+ if (agentTurn === null) {
91425
+ return;
91426
+ }
91427
+ this.#agentTurn = null;
91428
+ if (agentTurn.held) {
91429
+ await this.#releaseHeld({ code, message });
91430
+ return;
91431
+ }
91432
+ await this.recordLifecycleEvent({
91433
+ payload: {
91434
+ attemptId: agentTurn.attemptId,
91435
+ code,
91436
+ commandId: agentTurn.commandId,
91437
+ kind: "prompt.failed",
91438
+ message
91439
+ },
91440
+ type: "lifecycle-metadata"
91441
+ });
91442
+ this.#getObserver().onAgentTurn?.(this.#mobiusSessionId, null);
91443
+ };
91444
+ /** Keeps a command whose reply ended open for the background work still outstanding (see HeldCommand). */
91445
+ #hold = (commandId, attemptId, completion) => {
91446
+ this.#held = {
91447
+ attemptId,
91448
+ cancelled: false,
91449
+ commandId,
91450
+ completion,
91451
+ limit: this.#timer.schedule(() => {
91452
+ void this.#releaseHeld().catch((error62) => {
91453
+ console.error("Mobius daemon could not end a command held for background work", error62);
91454
+ });
91455
+ }, BACKGROUND_HOLD_LIMIT_MILLISECONDS)
91456
+ };
91457
+ this.#getObserver().onAgentTurn?.(this.#mobiusSessionId, commandId);
91458
+ };
91459
+ /**
91460
+ * Records the end of the held command, if one is open: how its reply ended, unless it was stopped or `failure`
91461
+ * says its continuation failed. The Agent's continuation of it, if one runs, belongs to nothing after this.
91462
+ */
91463
+ #releaseHeld = async (failure2) => {
91464
+ const held = this.#held;
91465
+ if (held === null) {
91466
+ return;
91467
+ }
91468
+ this.#held = null;
91469
+ held.limit.cancel();
91470
+ if (this.#agentTurn?.held === true) {
91329
91471
  this.#agentTurn = null;
91330
- await this.recordLifecycleEvent({
91331
- payload: {
91332
- attemptId: agentTurn.attemptId,
91333
- code: "agent_process_closed",
91334
- commandId: agentTurn.commandId,
91335
- kind: "prompt.failed",
91336
- message: "The Agent process ended before the work it started on its own finished"
91337
- },
91338
- type: "lifecycle-metadata"
91339
- });
91340
- this.#getObserver().onAgentTurn?.(this.#mobiusSessionId, null);
91341
91472
  }
91342
- await this.#recordBackgroundTasks([]);
91473
+ await this.recordLifecycleEvent({
91474
+ payload: failure2 !== void 0 ? {
91475
+ attemptId: held.attemptId,
91476
+ code: failure2.code,
91477
+ commandId: held.commandId,
91478
+ kind: "prompt.failed",
91479
+ message: truncate(failure2.message, 500)
91480
+ } : held.cancelled ? { commandId: held.commandId, kind: "prompt.completed", stopReason: "cancelled" } : { commandId: held.commandId, kind: "prompt.completed", ...held.completion },
91481
+ type: "lifecycle-metadata"
91482
+ });
91483
+ this.#getObserver().onAgentTurn?.(this.#mobiusSessionId, this.#agentTurn?.commandId ?? null);
91484
+ };
91485
+ /** Ends the held command once no background work is outstanding and no continuation of it is running. */
91486
+ #releaseHeldIfDone = async () => {
91487
+ if (this.#held !== null && this.#agentTurn === null && this.#recordedBackground.length === 0) {
91488
+ await this.#releaseHeld();
91489
+ }
91343
91490
  };
91344
91491
  /**
91345
- * Cancels the Turn the Agent started on its own when `commandId` names it; returns whether it did. Its end is
91346
- * recorded when the Agent reports it, as for any interrupted work.
91492
+ * Cancels the work the Agent does without a client's prompt running when `commandId` names it; returns whether it
91493
+ * did. That is a command held for background work, which also stops that work, or a Turn the Agent started on its
91494
+ * own. A continuation that is running records its end when the Agent reports it, as for any interrupted work.
91347
91495
  */
91348
91496
  cancelAgentTurn = async (commandId, signal) => {
91349
- if (this.#agentTurn?.commandId !== commandId) {
91497
+ const held = this.#held?.commandId === commandId ? this.#held : null;
91498
+ if (held === null && this.#agentTurn?.commandId !== commandId) {
91350
91499
  return false;
91351
91500
  }
91501
+ if (held !== null) {
91502
+ held.cancelled = true;
91503
+ }
91352
91504
  await this.#interactions.cancelPendingInteractions();
91353
91505
  signal.throwIfAborted();
91354
91506
  await this.#adapter.cancel({ ...this.#target(), signal });
91507
+ if (held !== null && this.#agentTurn === null) {
91508
+ await this.#releaseHeld();
91509
+ }
91355
91510
  return true;
91356
91511
  };
91357
91512
  #recordAgentTurn = async (report) => {
@@ -91360,11 +91515,26 @@ var AgentSession = class _AgentSession {
91360
91515
  if (this.#agentTurn !== null) {
91361
91516
  return;
91362
91517
  }
91518
+ const held = this.#held;
91519
+ if (held !== null) {
91520
+ this.#agentTurn = {
91521
+ attemptId: held.attemptId,
91522
+ commandId: held.commandId,
91523
+ continues: void 0,
91524
+ held: true
91525
+ };
91526
+ return;
91527
+ }
91363
91528
  const continues = report.taskIds.flatMap((taskId) => {
91364
91529
  const commandId = this.#backgroundTaskCommands.get(taskId);
91365
91530
  return commandId === void 0 ? [] : [commandId];
91366
91531
  })[0] ?? this.#lastClientCommandId;
91367
- const agentTurn = { attemptId: randomUUID14(), commandId: `agent-${randomUUID14()}`, continues };
91532
+ const agentTurn = {
91533
+ attemptId: randomUUID14(),
91534
+ commandId: `agent-${randomUUID14()}`,
91535
+ continues,
91536
+ held: false
91537
+ };
91368
91538
  this.#agentTurn = agentTurn;
91369
91539
  await this.recordLifecycleEvent({
91370
91540
  payload: {
@@ -91389,6 +91559,16 @@ var AgentSession = class _AgentSession {
91389
91559
  return;
91390
91560
  }
91391
91561
  this.#agentTurn = null;
91562
+ if (agentTurn.held) {
91563
+ const held = this.#held;
91564
+ if (held !== null && (held.cancelled || report.stopReason === "cancelled")) {
91565
+ held.cancelled = true;
91566
+ await this.#releaseHeld();
91567
+ return;
91568
+ }
91569
+ await this.#releaseHeldIfDone();
91570
+ return;
91571
+ }
91392
91572
  await this.recordLifecycleEvent({
91393
91573
  payload: {
91394
91574
  commandId: agentTurn.commandId,
@@ -91400,6 +91580,10 @@ var AgentSession = class _AgentSession {
91400
91580
  this.#getObserver().onAgentTurn?.(this.#mobiusSessionId, null);
91401
91581
  return;
91402
91582
  }
91583
+ case "failed": {
91584
+ await this.#failAgentTurn("agent_turn_failed", report.message);
91585
+ return;
91586
+ }
91403
91587
  default: {
91404
91588
  const unreachable2 = report;
91405
91589
  throw new AcpExecutionError("Unexpected Agent Turn report", { cause: unreachable2 });
@@ -91440,6 +91624,7 @@ var AgentSession = class _AgentSession {
91440
91624
  payload: { kind: "session.background.changed", tasks },
91441
91625
  type: "lifecycle-metadata"
91442
91626
  });
91627
+ await this.#releaseHeldIfDone();
91443
91628
  };
91444
91629
  agentSettingsModelEffort = () => this.#modelEffort;
91445
91630
  #sessionParams = (signal) => ({
@@ -91660,6 +91845,7 @@ var SessionManager2 = class {
91660
91845
  } else {
91661
91846
  this.#agentTurns.set(sessionId, commandId);
91662
91847
  }
91848
+ this.#processes.notifyChanged();
91663
91849
  this.#onSessionStatusChanged({
91664
91850
  kind: "session.status.changed",
91665
91851
  sessionId,
@@ -91747,7 +91933,8 @@ var SessionManager2 = class {
91747
91933
  metrics,
91748
91934
  options.adapter,
91749
91935
  capabilities,
91750
- this.promptSuggestions
91936
+ this.promptSuggestions,
91937
+ this.#timer
91751
91938
  )
91752
91939
  );
91753
91940
  });
@@ -91771,7 +91958,8 @@ var SessionManager2 = class {
91771
91958
  metrics,
91772
91959
  options.adapter,
91773
91960
  capabilities,
91774
- this.promptSuggestions
91961
+ this.promptSuggestions,
91962
+ this.#timer
91775
91963
  )
91776
91964
  );
91777
91965
  });
@@ -91792,7 +91980,8 @@ var SessionManager2 = class {
91792
91980
  unmeasuredOperationMetrics,
91793
91981
  options.adapter,
91794
91982
  capabilities,
91795
- this.promptSuggestions
91983
+ this.promptSuggestions,
91984
+ this.#timer
91796
91985
  )
91797
91986
  );
91798
91987
  try {
@@ -91849,7 +92038,8 @@ var SessionManager2 = class {
91849
92038
  unmeasuredOperationMetrics,
91850
92039
  options.adapter,
91851
92040
  capabilities,
91852
- this.promptSuggestions
92041
+ this.promptSuggestions,
92042
+ this.#timer
91853
92043
  )
91854
92044
  );
91855
92045
  });
@@ -92546,9 +92736,12 @@ var PromptLifecycle = class {
92546
92736
  #queued = /* @__PURE__ */ new Map();
92547
92737
  #recordActiveTurn;
92548
92738
  #executions;
92739
+ /** Whether the Agent holds the command open for background work, so its Agent session records how it ends. */
92740
+ #heldByAgent;
92549
92741
  #recordLifecycle;
92550
92742
  #append;
92551
- constructor(sink, recordLifecycle, append, recordActiveTurn, executions) {
92743
+ constructor(sink, recordLifecycle, append, recordActiveTurn, executions, heldByAgent = () => false) {
92744
+ this.#heldByAgent = heldByAgent;
92552
92745
  this.#recordLifecycle = recordLifecycle;
92553
92746
  this.#append = append;
92554
92747
  this.#recordActiveTurn = recordActiveTurn;
@@ -92663,7 +92856,7 @@ var PromptLifecycle = class {
92663
92856
  };
92664
92857
  completed = async (sessionId, commandId, stopReason) => {
92665
92858
  const request = this.#queued.get(commandId);
92666
- if (request?.sessionId !== sessionId || this.#executions.isTerminalExecution(commandId, sessionId)) {
92859
+ if (request?.sessionId !== sessionId || this.#executions.isTerminalExecution(commandId, sessionId) || this.#heldByAgent(sessionId, commandId)) {
92667
92860
  return;
92668
92861
  }
92669
92862
  const recorded = await this.#recordLifecycle(sessionId, {
@@ -93417,12 +93610,28 @@ var waitForTurnCompletion = (turn, waitSignal) => {
93417
93610
  var SessionExecutionState = class {
93418
93611
  #sessionId;
93419
93612
  #turnsByCommandId = /* @__PURE__ */ new Map();
93613
+ /**
93614
+ * Turns whose execution returned while the Agent holds their command open for background work it started. They no
93615
+ * longer take part in admission, but every client reading the Session's execution still sees them running.
93616
+ */
93617
+ #heldTurns = /* @__PURE__ */ new Map();
93420
93618
  #operations;
93421
- constructor(sessionId, operations) {
93619
+ #heldByAgent;
93620
+ constructor(sessionId, operations, heldByAgent = () => false) {
93422
93621
  this.#sessionId = sessionId;
93423
93622
  this.#operations = operations;
93623
+ this.#heldByAgent = heldByAgent;
93424
93624
  }
93425
- isEmpty = () => this.#turnsByCommandId.size === 0;
93625
+ isEmpty = () => this.#turnsByCommandId.size === 0 && this.heldTurns().length === 0;
93626
+ /** The held turns whose command the Agent still holds; a released hold leaves its turn behind for good. */
93627
+ heldTurns = () => {
93628
+ for (const commandId of this.#heldTurns.keys()) {
93629
+ if (!this.#heldByAgent(commandId)) {
93630
+ this.#heldTurns.delete(commandId);
93631
+ }
93632
+ }
93633
+ return [...this.#heldTurns.values()];
93634
+ };
93426
93635
  start = (command, attemptId) => {
93427
93636
  const turn = new ActiveRuntimeTurn(
93428
93637
  command,
@@ -93436,17 +93645,20 @@ var SessionExecutionState = class {
93436
93645
  get = (commandId) => this.#turnsByCommandId.get(commandId);
93437
93646
  finish = (turn) => {
93438
93647
  this.#turnsByCommandId.delete(turn.command.commandId);
93648
+ if (this.#heldByAgent(turn.command.commandId)) {
93649
+ this.#heldTurns.set(turn.command.commandId, turn);
93650
+ }
93439
93651
  turn.finish();
93440
93652
  };
93441
93653
  recordEvent = (event) => {
93442
93654
  if ("commandId" in event) {
93443
- const turn = this.#turnsByCommandId.get(event.commandId);
93655
+ const turn = this.#turnsByCommandId.get(event.commandId) ?? this.#heldTurns.get(event.commandId);
93444
93656
  if (turn !== void 0) {
93445
93657
  return turn.recordEvent(event);
93446
93658
  }
93447
93659
  }
93448
93660
  if (event.kind === SESSION_PERMISSION_RESOLVED_KIND || event.kind === SESSION_ELICITATION_RESOLVED_KIND) {
93449
- for (const turn of this.#turnsByCommandId.values()) {
93661
+ for (const turn of [...this.#turnsByCommandId.values(), ...this.#heldTurns.values()]) {
93450
93662
  if (turn.matchesInteraction(event.interactionId, this.#sessionId)) {
93451
93663
  return turn.recordEvent(event);
93452
93664
  }
@@ -93470,7 +93682,7 @@ var SessionExecutionState = class {
93470
93682
  );
93471
93683
  if (command.disposition === SessionPromptDisposition.Queue) {
93472
93684
  const target = head();
93473
- if ((target === turn || target?.command.commandId !== command.targetCommandId) && !this.#operations.isTerminalExecution(command.targetCommandId, this.#sessionId)) {
93685
+ if ((target === turn || target?.command.commandId !== command.targetCommandId) && !this.#operations.isTerminalExecution(command.targetCommandId, this.#sessionId) && !this.#heldByAgent(command.targetCommandId)) {
93474
93686
  return { kind: "queue-target-unavailable" };
93475
93687
  }
93476
93688
  turn.enqueue();
@@ -93508,15 +93720,21 @@ var SessionTurns = class {
93508
93720
  #bySessionId = /* @__PURE__ */ new Map();
93509
93721
  #operations;
93510
93722
  #activity;
93511
- constructor(operations, activity = new RuntimeTurnActivity()) {
93723
+ #heldByAgent;
93724
+ constructor(operations, activity = new RuntimeTurnActivity(), heldByAgent = () => false) {
93512
93725
  this.#operations = operations;
93513
93726
  this.#activity = activity;
93727
+ this.#heldByAgent = heldByAgent;
93514
93728
  }
93515
93729
  acceptsPrompts = () => this.#activity.acceptsPrompts();
93516
93730
  session = (sessionId) => {
93517
93731
  let session = this.#bySessionId.get(sessionId);
93518
93732
  if (session === void 0) {
93519
- session = new SessionExecutionState(sessionId, this.#operations);
93733
+ session = new SessionExecutionState(
93734
+ sessionId,
93735
+ this.#operations,
93736
+ (commandId) => this.#heldByAgent(sessionId, commandId)
93737
+ );
93520
93738
  this.#bySessionId.set(sessionId, session);
93521
93739
  }
93522
93740
  return session;
@@ -93549,7 +93767,14 @@ var SessionTurns = class {
93549
93767
  const current = matching.filter(
93550
93768
  (turn) => this.get(turn.command.commandId, turn.command.sessionId) === turn
93551
93769
  );
93552
- const turnSnapshot = current.map((turn) => turn.snapshot()).find((snapshot) => snapshot !== null);
93770
+ const held = [];
93771
+ for (const turn of session.heldTurns()) {
93772
+ if (await matches(turn.command)) {
93773
+ held.push(turn);
93774
+ }
93775
+ }
93776
+ const stillHeld = session.heldTurns();
93777
+ const turnSnapshot = [...current, ...held.filter((turn) => stillHeld.includes(turn))].map((turn) => turn.snapshot()).find((snapshot) => snapshot !== null);
93553
93778
  if (turnSnapshot === void 0 && current.length === 0) {
93554
93779
  continue;
93555
93780
  }
@@ -93812,7 +94037,11 @@ function buildSessionLayer(options) {
93812
94037
  throw error62;
93813
94038
  }
93814
94039
  const sessionStore = new SqliteSessionStore(new AcpSessionTable(sessionDatabase), events);
93815
- const activeSessions = new SessionTurns(operations, options.turnActivity);
94040
+ const activeSessions = new SessionTurns(
94041
+ operations,
94042
+ options.turnActivity,
94043
+ (sessionId, commandId) => manager.isAgentTurn(sessionId, commandId)
94044
+ );
93816
94045
  const directories = new WorkspaceDirectoryService(bindingId, defaultWorkspace);
93817
94046
  const manager = new SessionManager2({
93818
94047
  observer: new SessionLayerObserver(
@@ -93846,7 +94075,8 @@ function buildSessionLayer(options) {
93846
94075
  },
93847
94076
  (sessionId, event, recordedAt) => events.append(sessionId, event, recordedAt),
93848
94077
  activeSessions.recordSessionEvent,
93849
- operations
94078
+ operations,
94079
+ (sessionId, commandId) => manager.isAgentTurn(sessionId, commandId)
93850
94080
  );
93851
94081
  const nativeSessions = new NativeSessionService(
93852
94082
  bindingId,
@@ -98111,4 +98341,4 @@ export {
98111
98341
  * MIT Licensed
98112
98342
  *)
98113
98343
  */
98114
- //# sourceMappingURL=chunk-LGPB3HHD.js.map
98344
+ //# sourceMappingURL=chunk-5QMXJEVI.js.map