@moxt-ai/mobius 0.0.448 → 0.0.450

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-X6VDMZHE.js → chunk-6OVAZS3U.js} +295 -54
  2. package/dist/{chunk-X6VDMZHE.js.map → chunk-6OVAZS3U.js.map} +3 -3
  3. package/dist/{chunk-4PY4RNTC.js → chunk-Q7WARI45.js} +2 -2
  4. package/dist/{chunk-4PY4RNTC.js.map → chunk-Q7WARI45.js.map} +1 -1
  5. package/dist/{cli-B5KWLA5R.js → cli-OACSLIRY.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 +1 -1
  27. package/dist/engine/session/turn/session-execution.d.ts.map +1 -1
  28. package/dist/engine/session/turn/session-execution.js +7 -2
  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 +4 -2
  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-B5KWLA5R.js.map → cli-OACSLIRY.js.map} +0 -0
@@ -3,7 +3,7 @@ import {
3
3
  __export,
4
4
  __using,
5
5
  package_default
6
- } from "./chunk-4PY4RNTC.js";
6
+ } from "./chunk-Q7WARI45.js";
7
7
 
8
8
  // src/engine/runtime/relay/runtime-revocation.ts
9
9
  var runtimeRevocationCloseCode = 1008;
@@ -63894,9 +63894,44 @@ async function readFullHistory(transcript, sessionId, signal) {
63894
63894
  }
63895
63895
 
63896
63896
  // src/engine/acp/harness/claude/upstream/dist/environment-session-revision.js
63897
+ var LOCAL_COMMAND_TAGS = [
63898
+ "local-command-caveat",
63899
+ "command-name",
63900
+ "command-message",
63901
+ "command-args",
63902
+ "local-command-stdout",
63903
+ "local-command-stderr"
63904
+ ];
63905
+ function isLocalCommandRecord(message) {
63906
+ const payload = message.message;
63907
+ if (message.type !== "user" || typeof payload !== "object" || payload === null || !("content" in payload) || typeof payload.content !== "string") {
63908
+ return false;
63909
+ }
63910
+ const text2 = payload.content;
63911
+ let position = 0;
63912
+ let tags = 0;
63913
+ for (; ; ) {
63914
+ while (position < text2.length && /\s/u.test(text2.charAt(position))) {
63915
+ position += 1;
63916
+ }
63917
+ if (position === text2.length) {
63918
+ return tags > 0;
63919
+ }
63920
+ const tag = LOCAL_COMMAND_TAGS.find((name2) => text2.startsWith(`<${name2}>`, position));
63921
+ if (tag === void 0) {
63922
+ return false;
63923
+ }
63924
+ const end = text2.indexOf(`</${tag}>`, position + tag.length + 2);
63925
+ if (end === -1) {
63926
+ return false;
63927
+ }
63928
+ position = end + tag.length + 3;
63929
+ tags += 1;
63930
+ }
63931
+ }
63897
63932
  async function getEnvironmentSessionRevision(environment, sessionId, ownMessageIds, signal) {
63898
63933
  const messages = await getEnvironmentSessionMessages(environment, sessionId, signal);
63899
- return messages.findLast((message) => !ownMessageIds.has(message.uuid) && !isTaskNotificationOrigin(message.nativeOrigin))?.uuid ?? "";
63934
+ return messages.findLast((message) => !ownMessageIds.has(message.uuid) && !isTaskNotificationOrigin(message.nativeOrigin) && !isLocalCommandRecord(message))?.uuid ?? "";
63900
63935
  }
63901
63936
 
63902
63937
  // src/engine/acp/harness/claude/upstream/dist/session-config-ids.js
@@ -67843,7 +67878,7 @@ var ClaudeAcpAgent = class {
67843
67878
  };
67844
67879
  const noPromptInFlight = () => !(session.activeTurn && !session.activeTurn.settled) && firstUnsettledQueuedTurn() === void 0 && (session.pendingOrphanResults ?? 0) === 0 && (session.orphanCommands?.size ?? 0) === 0;
67845
67880
  const startAgentTurn = async () => {
67846
- if (session.agentTurn !== void 0 || !noPromptInFlight()) {
67881
+ if (session.agentTurn !== void 0 || session.agentCycleAbandoned === true || !noPromptInFlight()) {
67847
67882
  return;
67848
67883
  }
67849
67884
  await publishBackgroundTasks();
@@ -67865,6 +67900,9 @@ var ClaudeAcpAgent = class {
67865
67900
  return;
67866
67901
  }
67867
67902
  session.agentTurn = void 0;
67903
+ if (agentTurn.backstopArmed === true) {
67904
+ disarmForceCancel(session);
67905
+ }
67868
67906
  await publishBackgroundTasks();
67869
67907
  const ended = {
67870
67908
  stage: "ended",
@@ -67875,6 +67913,45 @@ var ClaudeAcpAgent = class {
67875
67913
  update: { sessionUpdate: "session_info_update", _meta: { [AGENT_TURN_META2]: ended } }
67876
67914
  });
67877
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
+ };
67878
67955
  const turnAwaitingSubagents = (turn) => {
67879
67956
  if (!turn.spawnedTaskIds?.size) {
67880
67957
  return false;
@@ -68007,10 +68084,15 @@ var ClaudeAcpAgent = class {
68007
68084
  this.trackResultOwedBySettledTurn(session, session.activeTurn);
68008
68085
  }
68009
68086
  settleActive(turnOutcome(session, "cancelled"));
68087
+ if (session.agentTurn?.cancelled === true && this.sessions[params.sessionId]) {
68088
+ session.agentCycleAbandoned = true;
68089
+ await endAgentTurn();
68090
+ }
68010
68091
  session.emittedAssistantText = false;
68011
68092
  if (!this.sessions[params.sessionId]) {
68012
68093
  void nextMessage.catch(() => {
68013
68094
  });
68095
+ await abandonAgentWork("The Agent session was closed");
68014
68096
  return;
68015
68097
  }
68016
68098
  cancelController = new AbortController();
@@ -68029,6 +68111,7 @@ var ClaudeAcpAgent = class {
68029
68111
  }
68030
68112
  }
68031
68113
  session.turnQueue = [];
68114
+ await abandonAgentWork("The Claude Agent process ended");
68032
68115
  this.closeQueryStream(session);
68033
68116
  return;
68034
68117
  }
@@ -68216,6 +68299,7 @@ var ClaudeAcpAgent = class {
68216
68299
  if (noPromptInFlight()) {
68217
68300
  await endAgentTurn();
68218
68301
  }
68302
+ session.agentCycleAbandoned = false;
68219
68303
  }
68220
68304
  break;
68221
68305
  }
@@ -68371,7 +68455,14 @@ var ClaudeAcpAgent = class {
68371
68455
  backgroundTasks.add(message.task_id);
68372
68456
  reportBackgroundActivity();
68373
68457
  }
68374
- 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") {
68375
68466
  session.liveBackgroundTasks.delete(message.task_id);
68376
68467
  if (backgroundTasks.delete(message.task_id)) {
68377
68468
  awaitingBackgroundResults.add(message.task_id);
@@ -68983,11 +69074,13 @@ ${message.api_refusal_explanation}` : "";
68983
69074
  if (processDied) {
68984
69075
  this.logger.error(`Session ${params.sessionId}: Claude Agent process died: ${message}`);
68985
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");
68986
69078
  this.closeQueryStream(session);
68987
69079
  delete this.sessions[params.sessionId];
68988
69080
  } else {
68989
69081
  this.logger.error(`Session ${params.sessionId}: query stream error: ${message}`);
68990
69082
  failAllTurns(error62);
69083
+ await abandonAgentWork("The Claude Agent stopped responding to the session");
68991
69084
  this.closeQueryStream(session);
68992
69085
  }
68993
69086
  }
@@ -69039,7 +69132,13 @@ ${message.api_refusal_explanation}` : "";
69039
69132
  this.trackOrphanCommand(session, turn.promptUuid, "started");
69040
69133
  }
69041
69134
  }
69135
+ /** A client's cancel also stops the background work its turn left running, so nothing wakes the model later. */
69042
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) {
69043
69142
  for (const submission of this.pendingSubmissions.get(params.sessionId) ?? []) {
69044
69143
  submission.abort();
69045
69144
  }
@@ -69057,6 +69156,9 @@ ${message.api_refusal_explanation}` : "";
69057
69156
  if (session.queryClosed) {
69058
69157
  return;
69059
69158
  }
69159
+ if (stopBackgroundWork) {
69160
+ void session.stopBackgroundWork?.();
69161
+ }
69060
69162
  if (isSteering(session.activeTurn)) {
69061
69163
  for (const uuid3 of session.activeTurn.steeredEchoes) {
69062
69164
  this.trackOrphanCommand(session, uuid3, "pending");
@@ -69110,7 +69212,10 @@ ${message.api_refusal_explanation}` : "";
69110
69212
  if (isSteering(session.activeTurn) && session.activeTurn.steeredSettle !== void 0) {
69111
69213
  session.idleBoundary = { kind: "accounted", turn: session.activeTurn ?? null };
69112
69214
  }
69113
- 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) {
69114
69219
  const cancelController = session.cancelController;
69115
69220
  session.forceCancelTimer = setTimeout(() => {
69116
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.`);
@@ -69171,7 +69276,7 @@ ${message.api_refusal_explanation}` : "";
69171
69276
  if (!session) {
69172
69277
  return;
69173
69278
  }
69174
- await this.cancel({ sessionId });
69279
+ await this.interrupt({ sessionId }, false);
69175
69280
  disarmForceCancel(session);
69176
69281
  session.cancelController?.abort();
69177
69282
  this.closeQueryStream(session);
@@ -80923,7 +81028,8 @@ var agentTurnReportSchema = external_exports.discriminatedUnion("stage", [
80923
81028
  reason: external_exports.enum(["background-task", "other"]).catch("other"),
80924
81029
  taskIds: external_exports.array(harnessText).max(1e3).readonly()
80925
81030
  }).readonly(),
80926
- 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()
80927
81033
  ]);
80928
81034
  function harnessReports(update) {
80929
81035
  if (update.sessionUpdate !== "session_info_update") {
@@ -90493,6 +90599,7 @@ async function restoreSession(session, signal, recovery) {
90493
90599
 
90494
90600
  // src/engine/session/live/agent-session.ts
90495
90601
  var SESSION_CONTROL_COMMAND_ID = "session-control";
90602
+ var BACKGROUND_HOLD_LIMIT_MILLISECONDS = 24 * 60 * 60 * 1e3;
90496
90603
  var AgentSession = class _AgentSession {
90497
90604
  // The restore surface: AgentSessionRestore members expose private state to
90498
90605
  // session-restore.ts only. The class keeps the fields private.
@@ -90523,10 +90630,13 @@ var AgentSession = class _AgentSession {
90523
90630
  hasBackgroundActivity = () => this.#backgroundActivity !== "none";
90524
90631
  #backgroundActivity = "none";
90525
90632
  /**
90526
- * The Turn the Agent is running on its own, with no prompt from any client. It has a command of the Runtime's
90527
- * 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.
90528
90636
  */
90529
90637
  #agentTurn = null;
90638
+ #held = null;
90639
+ #timer;
90530
90640
  /** The last command a client's prompt started; the Agent's own work continues it unless its work says otherwise. */
90531
90641
  #lastClientCommandId = void 0;
90532
90642
  /** The client command each piece of outstanding background work belongs to, fixed when it is first reported. */
@@ -90573,9 +90683,10 @@ var AgentSession = class _AgentSession {
90573
90683
  #restored = false;
90574
90684
  #sessionTitle = null;
90575
90685
  #sessionUpdatedAt = "";
90576
- 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) {
90577
90687
  this.#agentCommand = () => agentCommand(this.#mobiusSessionId);
90578
90688
  this.#promptSuggestions = promptSuggestions;
90689
+ this.#timer = timer;
90579
90690
  this.#additionalDirectories = [...additionalDirectories];
90580
90691
  this.#adapter = adapter;
90581
90692
  this.#agentId = agent2.id;
@@ -90643,7 +90754,7 @@ var AgentSession = class _AgentSession {
90643
90754
  }
90644
90755
  };
90645
90756
  }
90646
- static async #start(options, getObserver, agentCommand, store, initialize, metrics, adapter, promptSuggestions) {
90757
+ static async #start(options, getObserver, agentCommand, store, initialize, metrics, adapter, promptSuggestions, timer) {
90647
90758
  for (let attempt = 1; attempt <= 2; attempt += 1) {
90648
90759
  await metrics.measure(
90649
90760
  "executable-validation",
@@ -90662,7 +90773,8 @@ var AgentSession = class _AgentSession {
90662
90773
  metrics,
90663
90774
  adapter,
90664
90775
  options.externalizeSessionUpdate,
90665
- promptSuggestions
90776
+ promptSuggestions,
90777
+ timer
90666
90778
  )
90667
90779
  );
90668
90780
  try {
@@ -90685,7 +90797,7 @@ var AgentSession = class _AgentSession {
90685
90797
  }
90686
90798
  throw new AcpExecutionError("ACP agent initialization failed");
90687
90799
  }
90688
- 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(
90689
90801
  options,
90690
90802
  getObserver,
90691
90803
  agentCommand,
@@ -90696,7 +90808,8 @@ var AgentSession = class _AgentSession {
90696
90808
  },
90697
90809
  metrics,
90698
90810
  adapter,
90699
- promptSuggestions
90811
+ promptSuggestions,
90812
+ timer
90700
90813
  );
90701
90814
  belongsTo = (agentId, cwd, additionalDirectories) => this.#agentId === agentId && this.#cwd === cwd && arraysEqual(this.#additionalDirectories, additionalDirectories);
90702
90815
  usesEnvironment = (environment) => recordsEqual(this.#environment, environment);
@@ -91023,6 +91136,7 @@ var AgentSession = class _AgentSession {
91023
91136
  this.writeStoredSession((/* @__PURE__ */ new Date()).toISOString());
91024
91137
  const lifecycle = options.lifecycle;
91025
91138
  if (lifecycle !== void 0) {
91139
+ await this.#releaseHeld();
91026
91140
  await this.recordLifecycleEvent({
91027
91141
  payload: {
91028
91142
  commandId: options.commandId,
@@ -91064,15 +91178,15 @@ var AgentSession = class _AgentSession {
91064
91178
  this.writeStoredSession((/* @__PURE__ */ new Date()).toISOString());
91065
91179
  if (lifecycle !== void 0) {
91066
91180
  const messageId = result._meta?.messageId;
91067
- await this.recordLifecycleEvent({
91068
- payload: {
91069
- commandId: options.commandId,
91070
- kind: "prompt.completed",
91071
- ...messageId === void 0 ? {} : { messageId },
91072
- stopReason: result.stopReason
91073
- },
91074
- type: "lifecycle-metadata"
91075
- });
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
+ }
91076
91190
  }
91077
91191
  return result;
91078
91192
  } catch (error62) {
@@ -91282,41 +91396,117 @@ var AgentSession = class _AgentSession {
91282
91396
  await this.closeProcess();
91283
91397
  return;
91284
91398
  }
91285
- 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
+ }
91286
91404
  };
91287
91405
  closeProcess = async () => {
91288
91406
  if (this.#nativeIdentity.kind === "bound") {
91289
91407
  await this.#adapter.releaseSession({ ...this.#target(), signal: AbortSignal.timeout(3e4) });
91290
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
+ };
91291
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) => {
91292
91423
  const agentTurn = this.#agentTurn;
91293
- 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) {
91294
91471
  this.#agentTurn = null;
91295
- await this.recordLifecycleEvent({
91296
- payload: {
91297
- attemptId: agentTurn.attemptId,
91298
- code: "agent_process_closed",
91299
- commandId: agentTurn.commandId,
91300
- kind: "prompt.failed",
91301
- message: "The Agent process ended before the work it started on its own finished"
91302
- },
91303
- type: "lifecycle-metadata"
91304
- });
91305
- this.#getObserver().onAgentTurn?.(this.#mobiusSessionId, null);
91306
91472
  }
91307
- 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
+ }
91308
91490
  };
91309
91491
  /**
91310
- * Cancels the Turn the Agent started on its own when `commandId` names it; returns whether it did. Its end is
91311
- * 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.
91312
91495
  */
91313
91496
  cancelAgentTurn = async (commandId, signal) => {
91314
- if (this.#agentTurn?.commandId !== commandId) {
91497
+ const held = this.#held?.commandId === commandId ? this.#held : null;
91498
+ if (held === null && this.#agentTurn?.commandId !== commandId) {
91315
91499
  return false;
91316
91500
  }
91501
+ if (held !== null) {
91502
+ held.cancelled = true;
91503
+ }
91317
91504
  await this.#interactions.cancelPendingInteractions();
91318
91505
  signal.throwIfAborted();
91319
91506
  await this.#adapter.cancel({ ...this.#target(), signal });
91507
+ if (held !== null && this.#agentTurn === null) {
91508
+ await this.#releaseHeld();
91509
+ }
91320
91510
  return true;
91321
91511
  };
91322
91512
  #recordAgentTurn = async (report) => {
@@ -91325,11 +91515,26 @@ var AgentSession = class _AgentSession {
91325
91515
  if (this.#agentTurn !== null) {
91326
91516
  return;
91327
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
+ }
91328
91528
  const continues = report.taskIds.flatMap((taskId) => {
91329
91529
  const commandId = this.#backgroundTaskCommands.get(taskId);
91330
91530
  return commandId === void 0 ? [] : [commandId];
91331
91531
  })[0] ?? this.#lastClientCommandId;
91332
- const agentTurn = { attemptId: randomUUID14(), commandId: `agent-${randomUUID14()}`, continues };
91532
+ const agentTurn = {
91533
+ attemptId: randomUUID14(),
91534
+ commandId: `agent-${randomUUID14()}`,
91535
+ continues,
91536
+ held: false
91537
+ };
91333
91538
  this.#agentTurn = agentTurn;
91334
91539
  await this.recordLifecycleEvent({
91335
91540
  payload: {
@@ -91354,6 +91559,16 @@ var AgentSession = class _AgentSession {
91354
91559
  return;
91355
91560
  }
91356
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
+ }
91357
91572
  await this.recordLifecycleEvent({
91358
91573
  payload: {
91359
91574
  commandId: agentTurn.commandId,
@@ -91365,6 +91580,10 @@ var AgentSession = class _AgentSession {
91365
91580
  this.#getObserver().onAgentTurn?.(this.#mobiusSessionId, null);
91366
91581
  return;
91367
91582
  }
91583
+ case "failed": {
91584
+ await this.#failAgentTurn("agent_turn_failed", report.message);
91585
+ return;
91586
+ }
91368
91587
  default: {
91369
91588
  const unreachable2 = report;
91370
91589
  throw new AcpExecutionError("Unexpected Agent Turn report", { cause: unreachable2 });
@@ -91405,6 +91624,7 @@ var AgentSession = class _AgentSession {
91405
91624
  payload: { kind: "session.background.changed", tasks },
91406
91625
  type: "lifecycle-metadata"
91407
91626
  });
91627
+ await this.#releaseHeldIfDone();
91408
91628
  };
91409
91629
  agentSettingsModelEffort = () => this.#modelEffort;
91410
91630
  #sessionParams = (signal) => ({
@@ -91625,6 +91845,7 @@ var SessionManager2 = class {
91625
91845
  } else {
91626
91846
  this.#agentTurns.set(sessionId, commandId);
91627
91847
  }
91848
+ this.#processes.notifyChanged();
91628
91849
  this.#onSessionStatusChanged({
91629
91850
  kind: "session.status.changed",
91630
91851
  sessionId,
@@ -91712,7 +91933,8 @@ var SessionManager2 = class {
91712
91933
  metrics,
91713
91934
  options.adapter,
91714
91935
  capabilities,
91715
- this.promptSuggestions
91936
+ this.promptSuggestions,
91937
+ this.#timer
91716
91938
  )
91717
91939
  );
91718
91940
  });
@@ -91736,7 +91958,8 @@ var SessionManager2 = class {
91736
91958
  metrics,
91737
91959
  options.adapter,
91738
91960
  capabilities,
91739
- this.promptSuggestions
91961
+ this.promptSuggestions,
91962
+ this.#timer
91740
91963
  )
91741
91964
  );
91742
91965
  });
@@ -91757,7 +91980,8 @@ var SessionManager2 = class {
91757
91980
  unmeasuredOperationMetrics,
91758
91981
  options.adapter,
91759
91982
  capabilities,
91760
- this.promptSuggestions
91983
+ this.promptSuggestions,
91984
+ this.#timer
91761
91985
  )
91762
91986
  );
91763
91987
  try {
@@ -91814,7 +92038,8 @@ var SessionManager2 = class {
91814
92038
  unmeasuredOperationMetrics,
91815
92039
  options.adapter,
91816
92040
  capabilities,
91817
- this.promptSuggestions
92041
+ this.promptSuggestions,
92042
+ this.#timer
91818
92043
  )
91819
92044
  );
91820
92045
  });
@@ -92511,9 +92736,12 @@ var PromptLifecycle = class {
92511
92736
  #queued = /* @__PURE__ */ new Map();
92512
92737
  #recordActiveTurn;
92513
92738
  #executions;
92739
+ /** Whether the Agent holds the command open for background work, so its Agent session records how it ends. */
92740
+ #heldByAgent;
92514
92741
  #recordLifecycle;
92515
92742
  #append;
92516
- constructor(sink, recordLifecycle, append, recordActiveTurn, executions) {
92743
+ constructor(sink, recordLifecycle, append, recordActiveTurn, executions, heldByAgent = () => false) {
92744
+ this.#heldByAgent = heldByAgent;
92517
92745
  this.#recordLifecycle = recordLifecycle;
92518
92746
  this.#append = append;
92519
92747
  this.#recordActiveTurn = recordActiveTurn;
@@ -92628,7 +92856,7 @@ var PromptLifecycle = class {
92628
92856
  };
92629
92857
  completed = async (sessionId, commandId, stopReason) => {
92630
92858
  const request = this.#queued.get(commandId);
92631
- if (request?.sessionId !== sessionId || this.#executions.isTerminalExecution(commandId, sessionId)) {
92859
+ if (request?.sessionId !== sessionId || this.#executions.isTerminalExecution(commandId, sessionId) || this.#heldByAgent(sessionId, commandId)) {
92632
92860
  return;
92633
92861
  }
92634
92862
  const recorded = await this.#recordLifecycle(sessionId, {
@@ -93383,9 +93611,11 @@ var SessionExecutionState = class {
93383
93611
  #sessionId;
93384
93612
  #turnsByCommandId = /* @__PURE__ */ new Map();
93385
93613
  #operations;
93386
- constructor(sessionId, operations) {
93614
+ #heldByAgent;
93615
+ constructor(sessionId, operations, heldByAgent = () => false) {
93387
93616
  this.#sessionId = sessionId;
93388
93617
  this.#operations = operations;
93618
+ this.#heldByAgent = heldByAgent;
93389
93619
  }
93390
93620
  isEmpty = () => this.#turnsByCommandId.size === 0;
93391
93621
  start = (command, attemptId) => {
@@ -93435,7 +93665,7 @@ var SessionExecutionState = class {
93435
93665
  );
93436
93666
  if (command.disposition === SessionPromptDisposition.Queue) {
93437
93667
  const target = head();
93438
- if ((target === turn || target?.command.commandId !== command.targetCommandId) && !this.#operations.isTerminalExecution(command.targetCommandId, this.#sessionId)) {
93668
+ if ((target === turn || target?.command.commandId !== command.targetCommandId) && !this.#operations.isTerminalExecution(command.targetCommandId, this.#sessionId) && !this.#heldByAgent(command.targetCommandId)) {
93439
93669
  return { kind: "queue-target-unavailable" };
93440
93670
  }
93441
93671
  turn.enqueue();
@@ -93473,15 +93703,21 @@ var SessionTurns = class {
93473
93703
  #bySessionId = /* @__PURE__ */ new Map();
93474
93704
  #operations;
93475
93705
  #activity;
93476
- constructor(operations, activity = new RuntimeTurnActivity()) {
93706
+ #heldByAgent;
93707
+ constructor(operations, activity = new RuntimeTurnActivity(), heldByAgent = () => false) {
93477
93708
  this.#operations = operations;
93478
93709
  this.#activity = activity;
93710
+ this.#heldByAgent = heldByAgent;
93479
93711
  }
93480
93712
  acceptsPrompts = () => this.#activity.acceptsPrompts();
93481
93713
  session = (sessionId) => {
93482
93714
  let session = this.#bySessionId.get(sessionId);
93483
93715
  if (session === void 0) {
93484
- session = new SessionExecutionState(sessionId, this.#operations);
93716
+ session = new SessionExecutionState(
93717
+ sessionId,
93718
+ this.#operations,
93719
+ (commandId) => this.#heldByAgent(sessionId, commandId)
93720
+ );
93485
93721
  this.#bySessionId.set(sessionId, session);
93486
93722
  }
93487
93723
  return session;
@@ -93777,7 +94013,11 @@ function buildSessionLayer(options) {
93777
94013
  throw error62;
93778
94014
  }
93779
94015
  const sessionStore = new SqliteSessionStore(new AcpSessionTable(sessionDatabase), events);
93780
- const activeSessions = new SessionTurns(operations, options.turnActivity);
94016
+ const activeSessions = new SessionTurns(
94017
+ operations,
94018
+ options.turnActivity,
94019
+ (sessionId, commandId) => manager.isAgentTurn(sessionId, commandId)
94020
+ );
93781
94021
  const directories = new WorkspaceDirectoryService(bindingId, defaultWorkspace);
93782
94022
  const manager = new SessionManager2({
93783
94023
  observer: new SessionLayerObserver(
@@ -93811,7 +94051,8 @@ function buildSessionLayer(options) {
93811
94051
  },
93812
94052
  (sessionId, event, recordedAt) => events.append(sessionId, event, recordedAt),
93813
94053
  activeSessions.recordSessionEvent,
93814
- operations
94054
+ operations,
94055
+ (sessionId, commandId) => manager.isAgentTurn(sessionId, commandId)
93815
94056
  );
93816
94057
  const nativeSessions = new NativeSessionService(
93817
94058
  bindingId,
@@ -98076,4 +98317,4 @@ export {
98076
98317
  * MIT Licensed
98077
98318
  *)
98078
98319
  */
98079
- //# sourceMappingURL=chunk-X6VDMZHE.js.map
98320
+ //# sourceMappingURL=chunk-6OVAZS3U.js.map