@moxt-ai/mobius 0.0.445 → 0.0.448

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 (37) hide show
  1. package/dist/{chunk-ERFISXVP.js → chunk-4PY4RNTC.js} +2 -2
  2. package/dist/{chunk-ERFISXVP.js.map → chunk-4PY4RNTC.js.map} +1 -1
  3. package/dist/{chunk-TMQPBQLB.js → chunk-X6VDMZHE.js} +403 -26
  4. package/dist/{chunk-TMQPBQLB.js.map → chunk-X6VDMZHE.js.map} +4 -4
  5. package/dist/{cli-Z2J7V3PA.js → cli-B5KWLA5R.js} +3 -3
  6. package/dist/cli.js +2 -2
  7. package/dist/engine/acp/adapter/execution-connections.d.ts.map +1 -1
  8. package/dist/engine/acp/adapter/execution-connections.js +2 -0
  9. package/dist/engine/acp/adapter/execution-connections.js.map +1 -1
  10. package/dist/engine/acp/adapter/session-events.d.ts +7 -1
  11. package/dist/engine/acp/adapter/session-events.d.ts.map +1 -1
  12. package/dist/engine/acp/adapter/session-events.js +65 -0
  13. package/dist/engine/acp/adapter/session-events.js.map +1 -1
  14. package/dist/engine/acp/agent/in-process-endpoint.d.ts +28 -0
  15. package/dist/engine/acp/agent/in-process-endpoint.d.ts.map +1 -1
  16. package/dist/engine/acp/agent/in-process-endpoint.js +7 -0
  17. package/dist/engine/acp/agent/in-process-endpoint.js.map +1 -1
  18. package/dist/engine/runtime/command/registry/interactions.d.ts.map +1 -1
  19. package/dist/engine/runtime/command/registry/interactions.js +7 -0
  20. package/dist/engine/runtime/command/registry/interactions.js.map +1 -1
  21. package/dist/engine/session/api/session-api.d.ts +2 -0
  22. package/dist/engine/session/api/session-api.d.ts.map +1 -1
  23. package/dist/engine/session/api/session-api.js.map +1 -1
  24. package/dist/engine/session/live/agent-session.d.ts +7 -0
  25. package/dist/engine/session/live/agent-session.d.ts.map +1 -1
  26. package/dist/engine/session/live/agent-session.js +143 -2
  27. package/dist/engine/session/live/agent-session.js.map +1 -1
  28. package/dist/engine/session/manager/session-manager.d.ts +2 -0
  29. package/dist/engine/session/manager/session-manager.d.ts.map +1 -1
  30. package/dist/engine/session/manager/session-manager.js +59 -8
  31. package/dist/engine/session/manager/session-manager.js.map +1 -1
  32. package/dist/engine/session/prompt/prompt-lifecycle.d.ts.map +1 -1
  33. package/dist/engine/session/prompt/prompt-lifecycle.js +5 -1
  34. package/dist/engine/session/prompt/prompt-lifecycle.js.map +1 -1
  35. package/dist/engine.js +2 -2
  36. package/package.json +2 -2
  37. /package/dist/{cli-Z2J7V3PA.js.map → cli-B5KWLA5R.js.map} +0 -0
@@ -3,7 +3,7 @@ import {
3
3
  __export,
4
4
  __using,
5
5
  package_default
6
- } from "./chunk-ERFISXVP.js";
6
+ } from "./chunk-4PY4RNTC.js";
7
7
 
8
8
  // src/engine/runtime/relay/runtime-revocation.ts
9
9
  var runtimeRevocationCloseCode = 1008;
@@ -20759,6 +20759,26 @@ var promptExecutionContextSchema = external_exports.object({
20759
20759
  directoryId: DIRECTORY_IDENTIFIER,
20760
20760
  additionalDirectoryIds: external_exports.array(DIRECTORY_IDENTIFIER).max(16).readonly()
20761
20761
  }).readonly();
20762
+ var promptInitiatorSchema = external_exports.object({
20763
+ kind: external_exports.literal("agent"),
20764
+ reason: external_exports.enum(["background-task", "other"]).catch("other"),
20765
+ // The command a client submitted whose background work led the Agent to start this one, followed through
20766
+ // earlier commands the Agent started itself. Absent when the Runtime cannot tell.
20767
+ continues: identifierStringSchema.optional().catch(void 0)
20768
+ }).readonly();
20769
+ var SESSION_BACKGROUND_TASK_MAX_COUNT = 100;
20770
+ var sessionBackgroundTaskSchema = external_exports.object({
20771
+ // Agent-owned identity.
20772
+ taskId: external_exports.string().min(1).max(2048),
20773
+ kind: external_exports.enum(["subagent", "shell", "other"]).catch("other"),
20774
+ state: external_exports.enum(["running", "awaiting-results"]).catch("running"),
20775
+ // The command a client submitted that this work belongs to, followed through commands the Agent started
20776
+ // itself. Absent when the Runtime cannot tell.
20777
+ commandId: identifierStringSchema.optional().catch(void 0),
20778
+ // The tool call that started the work, when the Agent reported one.
20779
+ toolCallId: external_exports.string().min(1).max(2048).optional().catch(void 0),
20780
+ description: external_exports.string().max(500).optional().catch(void 0)
20781
+ }).readonly();
20762
20782
  var promptCompletedSchema = external_exports.object({
20763
20783
  ...lifecycleBase,
20764
20784
  kind: external_exports.literal("prompt.completed"),
@@ -20778,6 +20798,13 @@ var lifecycleMetadataSchema = external_exports.discriminatedUnion("kind", [
20778
20798
  // `changedByCommandId` names the command whose admission to or departure from the queue changed it. Runtimes
20779
20799
  // before it existed omit it, so a reader must treat an unnamed change as possibly any command's.
20780
20800
  external_exports.object({ changedByCommandId: identifierStringSchema.optional(), kind: external_exports.literal("session.queue.changed") }).readonly(),
20801
+ // The Session's complete outstanding background work, replacing the last one recorded. An empty list means none
20802
+ // remains, including after the Agent process that ran it ended. A new Session generation starts with none.
20803
+ // Runtimes before it existed never record it.
20804
+ external_exports.object({
20805
+ kind: external_exports.literal("session.background.changed"),
20806
+ tasks: external_exports.array(sessionBackgroundTaskSchema).max(SESSION_BACKGROUND_TASK_MAX_COUNT).readonly()
20807
+ }).readonly(),
20781
20808
  external_exports.object({ event: sessionPermissionRequestedEventSchema, kind: external_exports.literal("session.permission.requested") }).readonly(),
20782
20809
  external_exports.object({ event: sessionPermissionResolvedEventSchema, kind: external_exports.literal("session.permission.resolved") }).readonly(),
20783
20810
  external_exports.object({ event: sessionElicitationRequestedEventSchema, kind: external_exports.literal("session.elicitation.requested") }).readonly(),
@@ -20790,7 +20817,14 @@ var lifecycleMetadataSchema = external_exports.discriminatedUnion("kind", [
20790
20817
  context: promptExecutionContextSchema.optional(),
20791
20818
  targetCommandId: identifierStringSchema.optional()
20792
20819
  }).readonly(),
20793
- external_exports.object({ ...lifecycleBase, attemptId: identifierStringSchema, epoch: identifierStringSchema, kind: external_exports.literal("prompt.started") }).readonly(),
20820
+ external_exports.object({
20821
+ ...lifecycleBase,
20822
+ attemptId: identifierStringSchema,
20823
+ epoch: identifierStringSchema,
20824
+ // An initiator a reader cannot decode leaves the command one a client submitted, as before it existed.
20825
+ initiator: promptInitiatorSchema.optional().catch(void 0),
20826
+ kind: external_exports.literal("prompt.started")
20827
+ }).readonly(),
20794
20828
  // The Runtime did not run this prompt itself: it handed it to the native session's owner, another client of the
20795
20829
  // Agent such as the Codex app, which runs queued input on its own terms. `queued`: the owner holds the prompt and
20796
20830
  // may keep holding it; Codex pauses its queue after an interrupted turn until its user continues. `started`: the
@@ -20816,6 +20850,7 @@ var isPromptTerminal = (payload) => {
20816
20850
  case "prompt.started":
20817
20851
  case "prompt.delegated":
20818
20852
  case "session.queue.changed":
20853
+ case "session.background.changed":
20819
20854
  case "session.permission.requested":
20820
20855
  case "session.permission.resolved":
20821
20856
  case "session.elicitation.requested":
@@ -26776,6 +26811,8 @@ function acpEndpointTerminationError(termination) {
26776
26811
  }
26777
26812
  }
26778
26813
  }
26814
+ var BACKGROUND_TASKS_META = "mobius.backgroundTasks";
26815
+ var AGENT_TURN_META = "mobius.agentTurn";
26779
26816
 
26780
26817
  // src/engine/acp/connection/agent-operation.ts
26781
26818
  var promptFailureIdentitySchema = external_exports.object({ messageId: external_exports.string().min(1).max(2048) });
@@ -67604,6 +67641,8 @@ var ClaudeAcpAgent = class {
67604
67641
  const backgroundTasks = /* @__PURE__ */ new Set();
67605
67642
  const awaitingBackgroundResults = /* @__PURE__ */ new Set();
67606
67643
  let processingBackgroundResults = /* @__PURE__ */ new Set();
67644
+ const backgroundTaskDetails = /* @__PURE__ */ new Map();
67645
+ let publishedBackgroundTasks = "[]";
67607
67646
  let hasBackgroundLevel = false;
67608
67647
  const reportBackgroundActivity = () => this.reportBackgroundActivity(session, backgroundTasks.size > 0 ? "running" : awaitingBackgroundResults.size > 0 ? "awaiting-results" : "none");
67609
67648
  let lastAssistantTotalUsage = null;
@@ -67772,6 +67811,70 @@ var ClaudeAcpAgent = class {
67772
67811
  };
67773
67812
  const findUnsettledTurn = (uuid3) => (session.turnQueue ?? []).find((t) => t.promptUuid === uuid3 && !t.settled);
67774
67813
  const firstUnsettledQueuedTurn = () => (session.turnQueue ?? []).find((t) => !t.settled);
67814
+ const publishBackgroundTasks = async () => {
67815
+ const report = (taskId, state) => {
67816
+ const details = backgroundTaskDetails.get(taskId);
67817
+ if (details?.ambient === true) {
67818
+ return [];
67819
+ }
67820
+ return [
67821
+ {
67822
+ taskId,
67823
+ kind: details?.kind ?? "other",
67824
+ state,
67825
+ ...details?.toolUseId === void 0 ? {} : { toolUseId: details.toolUseId },
67826
+ ...details?.description === void 0 ? {} : { description: details.description }
67827
+ }
67828
+ ];
67829
+ };
67830
+ const tasks = [
67831
+ ...[...backgroundTasks].flatMap((taskId) => report(taskId, "running")),
67832
+ ...[...awaitingBackgroundResults].filter((taskId) => !backgroundTasks.has(taskId)).flatMap((taskId) => report(taskId, "awaiting-results"))
67833
+ ];
67834
+ const encoded = JSON.stringify(tasks);
67835
+ if (encoded === publishedBackgroundTasks) {
67836
+ return;
67837
+ }
67838
+ publishedBackgroundTasks = encoded;
67839
+ await this.client.sessionUpdate({
67840
+ sessionId: params.sessionId,
67841
+ update: { sessionUpdate: "session_info_update", _meta: { [BACKGROUND_TASKS_META2]: tasks } }
67842
+ });
67843
+ };
67844
+ const noPromptInFlight = () => !(session.activeTurn && !session.activeTurn.settled) && firstUnsettledQueuedTurn() === void 0 && (session.pendingOrphanResults ?? 0) === 0 && (session.orphanCommands?.size ?? 0) === 0;
67845
+ const startAgentTurn = async () => {
67846
+ if (session.agentTurn !== void 0 || !noPromptInFlight()) {
67847
+ return;
67848
+ }
67849
+ await publishBackgroundTasks();
67850
+ session.agentTurn = { cancelled: false };
67851
+ const taskIds = [...awaitingBackgroundResults];
67852
+ const started = {
67853
+ stage: "started",
67854
+ reason: taskIds.length > 0 ? "background-task" : "other",
67855
+ taskIds
67856
+ };
67857
+ await this.client.sessionUpdate({
67858
+ sessionId: params.sessionId,
67859
+ update: { sessionUpdate: "session_info_update", _meta: { [AGENT_TURN_META2]: started } }
67860
+ });
67861
+ };
67862
+ const endAgentTurn = async () => {
67863
+ const agentTurn = session.agentTurn;
67864
+ if (agentTurn === void 0) {
67865
+ return;
67866
+ }
67867
+ session.agentTurn = void 0;
67868
+ await publishBackgroundTasks();
67869
+ const ended = {
67870
+ stage: "ended",
67871
+ stopReason: agentTurn.cancelled ? "cancelled" : "end_turn"
67872
+ };
67873
+ await this.client.sessionUpdate({
67874
+ sessionId: params.sessionId,
67875
+ update: { sessionUpdate: "session_info_update", _meta: { [AGENT_TURN_META2]: ended } }
67876
+ });
67877
+ };
67775
67878
  const turnAwaitingSubagents = (turn) => {
67776
67879
  if (!turn.spawnedTaskIds?.size) {
67777
67880
  return false;
@@ -67886,6 +67989,10 @@ var ClaudeAcpAgent = class {
67886
67989
  let pendingNext = null;
67887
67990
  try {
67888
67991
  while (true) {
67992
+ await publishBackgroundTasks();
67993
+ if (session.agentTurn !== void 0 && !noPromptInFlight()) {
67994
+ await endAgentTurn();
67995
+ }
67889
67996
  pendingNext ??= session.query.next().then((result) => ({ kind: "message", result }));
67890
67997
  const nextMessage = pendingNext;
67891
67998
  let onAbort;
@@ -67997,6 +68104,7 @@ var ClaudeAcpAgent = class {
67997
68104
  switch (message.subtype) {
67998
68105
  case "init":
67999
68106
  processingBackgroundResults = new Set(awaitingBackgroundResults);
68107
+ await startAgentTurn();
68000
68108
  if (message.capabilities?.includes("msg_lifecycle_v1")) {
68001
68109
  session.msgLifecycleV1 = true;
68002
68110
  }
@@ -68078,6 +68186,9 @@ var ClaudeAcpAgent = class {
68078
68186
  }
68079
68187
  case "session_state_changed": {
68080
68188
  session.lastSessionState = message.state;
68189
+ if (message.state === "running") {
68190
+ await startAgentTurn();
68191
+ }
68081
68192
  if (message.state === "idle") {
68082
68193
  disarmResultWatchdog();
68083
68194
  const boundary = session.idleBoundary;
@@ -68102,6 +68213,9 @@ var ClaudeAcpAgent = class {
68102
68213
  failActive(RequestError.internalError(errorKindData("no_result"), TURN_NO_RESULT_MESSAGE));
68103
68214
  }
68104
68215
  await session.titles.onTurnEnd(session);
68216
+ if (noPromptInFlight()) {
68217
+ await endAgentTurn();
68218
+ }
68105
68219
  }
68106
68220
  break;
68107
68221
  }
@@ -68219,6 +68333,12 @@ var ClaudeAcpAgent = class {
68219
68333
  parentToolUseId: message.tool_use_id,
68220
68334
  isSubagent: !!message.subagent_type
68221
68335
  });
68336
+ backgroundTaskDetails.set(message.task_id, {
68337
+ kind: message.subagent_type ? "subagent" : message.task_type === "local_bash" ? "shell" : "other",
68338
+ ambient: message.ambient === true || message.skip_transcript === true,
68339
+ ...message.tool_use_id === void 0 ? {} : { toolUseId: message.tool_use_id },
68340
+ ...message.description.length === 0 ? {} : { description: message.description }
68341
+ });
68222
68342
  if (message.subagent_type && session.activeTurn && !session.activeTurn.settled) {
68223
68343
  session.activeTurn.spawnedTaskIds ??= /* @__PURE__ */ new Set();
68224
68344
  session.activeTurn.spawnedTaskIds.add(message.task_id);
@@ -68239,6 +68359,7 @@ var ClaudeAcpAgent = class {
68239
68359
  if (message.skip_transcript) {
68240
68360
  backgroundTasks.delete(message.task_id);
68241
68361
  awaitingBackgroundResults.delete(message.task_id);
68362
+ backgroundTaskDetails.delete(message.task_id);
68242
68363
  } else if (backgroundTasks.delete(message.task_id)) {
68243
68364
  awaitingBackgroundResults.add(message.task_id);
68244
68365
  }
@@ -68526,6 +68647,9 @@ ${message.api_refusal_explanation}` : "";
68526
68647
  if (message.origin?.kind === "task-notification") {
68527
68648
  for (const id of processingBackgroundResults) {
68528
68649
  awaitingBackgroundResults.delete(id);
68650
+ if (!backgroundTasks.has(id)) {
68651
+ backgroundTaskDetails.delete(id);
68652
+ }
68529
68653
  }
68530
68654
  processingBackgroundResults.clear();
68531
68655
  reportBackgroundActivity();
@@ -68925,6 +69049,9 @@ ${message.api_refusal_explanation}` : "";
68925
69049
  return;
68926
69050
  }
68927
69051
  session.cancelled = true;
69052
+ if (session.agentTurn !== void 0) {
69053
+ session.agentTurn.cancelled = true;
69054
+ }
68928
69055
  session.pendingExitPlanModeInterruption = void 0;
68929
69056
  session.pendingExitPlanContextReset = void 0;
68930
69057
  if (session.queryClosed) {
@@ -71333,6 +71460,8 @@ async function runPromptWithCancellation(agent2, params, signal) {
71333
71460
  signal.removeEventListener("abort", onAbort);
71334
71461
  }
71335
71462
  }
71463
+ var BACKGROUND_TASKS_META2 = "mobius.backgroundTasks";
71464
+ var AGENT_TURN_META2 = "mobius.agentTurn";
71336
71465
  function createClaudeAcpApp(options = {}) {
71337
71466
  let agent2 = null;
71338
71467
  const app = agent({ name: "claude-code-acp" }).onConnect((connection) => {
@@ -80778,6 +80907,48 @@ function applyConfigurationChanges(base, changes) {
80778
80907
  }
80779
80908
 
80780
80909
  // src/engine/acp/adapter/session-events.ts
80910
+ var harnessText = external_exports.string().min(1).max(2048);
80911
+ var backgroundTaskReportsSchema = external_exports.array(
80912
+ external_exports.object({
80913
+ taskId: harnessText,
80914
+ kind: external_exports.enum(["subagent", "shell", "other"]).catch("other"),
80915
+ state: external_exports.enum(["running", "awaiting-results"]),
80916
+ toolUseId: harnessText.optional().catch(void 0),
80917
+ description: external_exports.string().optional().catch(void 0)
80918
+ }).readonly()
80919
+ ).max(1e3).readonly();
80920
+ var agentTurnReportSchema = external_exports.discriminatedUnion("stage", [
80921
+ external_exports.object({
80922
+ stage: external_exports.literal("started"),
80923
+ reason: external_exports.enum(["background-task", "other"]).catch("other"),
80924
+ taskIds: external_exports.array(harnessText).max(1e3).readonly()
80925
+ }).readonly(),
80926
+ external_exports.object({ stage: external_exports.literal("ended"), stopReason: external_exports.enum(["end_turn", "cancelled"]) }).readonly()
80927
+ ]);
80928
+ function harnessReports(update) {
80929
+ if (update.sessionUpdate !== "session_info_update") {
80930
+ return null;
80931
+ }
80932
+ const meta3 = update._meta;
80933
+ if (meta3 === void 0 || meta3 === null || !(AGENT_TURN_META in meta3) && !(BACKGROUND_TASKS_META in meta3)) {
80934
+ return null;
80935
+ }
80936
+ const decode6 = (key, schema) => {
80937
+ if (!(key in meta3)) {
80938
+ return null;
80939
+ }
80940
+ const decoded = schema.safeParse(meta3[key]);
80941
+ if (!decoded.success) {
80942
+ console.warn("[acp] Dropped a harness report that does not decode", { key });
80943
+ return null;
80944
+ }
80945
+ return decoded.data;
80946
+ };
80947
+ return {
80948
+ agentTurn: decode6(AGENT_TURN_META, agentTurnReportSchema),
80949
+ backgroundTasks: decode6(BACKGROUND_TASKS_META, backgroundTaskReportsSchema)
80950
+ };
80951
+ }
80781
80952
  function withMobiusFields(update, eventUpdate) {
80782
80953
  if (typeof eventUpdate !== "object" || eventUpdate === null) {
80783
80954
  return eventUpdate;
@@ -80820,6 +80991,16 @@ var AdapterSessionConnection = class {
80820
80991
  if (notification.sessionId !== this.#updates.sessionId()) {
80821
80992
  throw new AcpExecutionError("ACP agent referenced an unknown session", {}, "invalid_agent_session");
80822
80993
  }
80994
+ const reports = harnessReports(notification.update);
80995
+ if (reports !== null) {
80996
+ if (reports.backgroundTasks !== null) {
80997
+ await options.onBackgroundTasks?.(reports.backgroundTasks);
80998
+ }
80999
+ if (reports.agentTurn !== null) {
81000
+ await options.onAgentTurn?.(reports.agentTurn);
81001
+ }
81002
+ return;
81003
+ }
80823
81004
  const signal = AbortSignal.any([this.#lifetime.signal, AbortSignal.timeout(3e4)]);
80824
81005
  const externalized = options.externalizeUpdate === void 0 ? await externalizer.update(notification.sessionId, notification.update, signal) : await options.externalizeUpdate(notification.update, signal);
80825
81006
  signal.throwIfAborted();
@@ -81109,6 +81290,8 @@ var AcpExecutionConnections = class {
81109
81290
  ...params.onBackgroundActivity === void 0 ? {} : { onBackgroundActivity: params.onBackgroundActivity },
81110
81291
  ...params.onPromptDelegation === void 0 ? {} : { onPromptDelegation: params.onPromptDelegation },
81111
81292
  ...params.onPromptSuggestion === void 0 ? {} : { onPromptSuggestion: params.onPromptSuggestion },
81293
+ ...params.onAgentTurn === void 0 ? {} : { onAgentTurn: params.onAgentTurn },
81294
+ ...params.onBackgroundTasks === void 0 ? {} : { onBackgroundTasks: params.onBackgroundTasks },
81112
81295
  interactions: params.interactions
81113
81296
  },
81114
81297
  this.#externalizer,
@@ -89156,6 +89339,9 @@ var unmeasuredOperationMetrics = Object.freeze({
89156
89339
  snapshot: () => Object.freeze([])
89157
89340
  });
89158
89341
 
89342
+ // src/engine/session/live/agent-session.ts
89343
+ import { randomUUID as randomUUID14 } from "node:crypto";
89344
+
89159
89345
  // ../mobius-sdk/src/conversation-title.ts
89160
89346
  var CONVERSATION_TITLE_CHARACTER_LIMIT = 42;
89161
89347
  function conversationTitleFromText(text2) {
@@ -90336,6 +90522,19 @@ var AgentSession = class _AgentSession {
90336
90522
  }
90337
90523
  hasBackgroundActivity = () => this.#backgroundActivity !== "none";
90338
90524
  #backgroundActivity = "none";
90525
+ /**
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.
90528
+ */
90529
+ #agentTurn = null;
90530
+ /** The last command a client's prompt started; the Agent's own work continues it unless its work says otherwise. */
90531
+ #lastClientCommandId = void 0;
90532
+ /** The client command each piece of outstanding background work belongs to, fixed when it is first reported. */
90533
+ #backgroundTaskCommands = /* @__PURE__ */ new Map();
90534
+ /** The background work last recorded, so a report that changes nothing records nothing. */
90535
+ #recordedBackground = [];
90536
+ /** The command the Turn the Agent started on its own runs under, while it runs. */
90537
+ agentTurnCommand = () => this.#agentTurn?.commandId;
90339
90538
  /** The command whose prompt the Agent is running, which only the Agent can report as delegated. */
90340
90539
  #delegableCommandId = null;
90341
90540
  #modelEffort = null;
@@ -90391,7 +90590,7 @@ var AgentSession = class _AgentSession {
90391
90590
  cwd: () => this.#cwd,
90392
90591
  getToolCall: (toolCallId) => this.#store.events.getToolCall(this.#mobiusSessionId, toolCallId),
90393
90592
  sessionId: () => this.#mobiusSessionId,
90394
- commandId: () => this.#agentCommand() ?? SESSION_CONTROL_COMMAND_ID,
90593
+ commandId: () => this.#agentCommand() ?? this.#agentTurn?.commandId ?? SESSION_CONTROL_COMMAND_ID,
90395
90594
  assertNativeSession: this.assertNativeSession,
90396
90595
  observer: getObserver,
90397
90596
  recordSessionEvent: this.recordLifecycleEvent
@@ -90419,6 +90618,12 @@ var AgentSession = class _AgentSession {
90419
90618
  void this.#recordNativeHistoryRevision();
90420
90619
  }
90421
90620
  },
90621
+ onAgentTurn: async (report) => {
90622
+ await this.#recordAgentTurn(report);
90623
+ },
90624
+ onBackgroundTasks: async (tasks) => {
90625
+ await this.#recordBackgroundTasks(tasks);
90626
+ },
90422
90627
  onPromptDelegation: async (stage) => {
90423
90628
  const commandId = this.#delegableCommandId;
90424
90629
  if (commandId !== null) {
@@ -90840,6 +91045,9 @@ var AgentSession = class _AgentSession {
90840
91045
  });
90841
91046
  }
90842
91047
  this.#delegableCommandId = lifecycle === void 0 ? null : options.commandId;
91048
+ if (lifecycle !== void 0) {
91049
+ this.#lastClientCommandId = options.commandId;
91050
+ }
90843
91051
  try {
90844
91052
  const result = await this.#writeNativeHistory(async () => {
90845
91053
  try {
@@ -91081,6 +91289,122 @@ var AgentSession = class _AgentSession {
91081
91289
  await this.#adapter.releaseSession({ ...this.#target(), signal: AbortSignal.timeout(3e4) });
91082
91290
  }
91083
91291
  this.#backgroundActivity = "none";
91292
+ const agentTurn = this.#agentTurn;
91293
+ if (agentTurn !== null) {
91294
+ 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
+ }
91307
+ await this.#recordBackgroundTasks([]);
91308
+ };
91309
+ /**
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.
91312
+ */
91313
+ cancelAgentTurn = async (commandId, signal) => {
91314
+ if (this.#agentTurn?.commandId !== commandId) {
91315
+ return false;
91316
+ }
91317
+ await this.#interactions.cancelPendingInteractions();
91318
+ signal.throwIfAborted();
91319
+ await this.#adapter.cancel({ ...this.#target(), signal });
91320
+ return true;
91321
+ };
91322
+ #recordAgentTurn = async (report) => {
91323
+ switch (report.stage) {
91324
+ case "started": {
91325
+ if (this.#agentTurn !== null) {
91326
+ return;
91327
+ }
91328
+ const continues = report.taskIds.flatMap((taskId) => {
91329
+ const commandId = this.#backgroundTaskCommands.get(taskId);
91330
+ return commandId === void 0 ? [] : [commandId];
91331
+ })[0] ?? this.#lastClientCommandId;
91332
+ const agentTurn = { attemptId: randomUUID14(), commandId: `agent-${randomUUID14()}`, continues };
91333
+ this.#agentTurn = agentTurn;
91334
+ await this.recordLifecycleEvent({
91335
+ payload: {
91336
+ attemptId: agentTurn.attemptId,
91337
+ commandId: agentTurn.commandId,
91338
+ epoch: randomUUID14(),
91339
+ initiator: {
91340
+ kind: "agent",
91341
+ reason: report.reason,
91342
+ ...continues === void 0 ? {} : { continues }
91343
+ },
91344
+ kind: "prompt.started"
91345
+ },
91346
+ type: "lifecycle-metadata"
91347
+ });
91348
+ this.#getObserver().onAgentTurn?.(this.#mobiusSessionId, agentTurn.commandId);
91349
+ return;
91350
+ }
91351
+ case "ended": {
91352
+ const agentTurn = this.#agentTurn;
91353
+ if (agentTurn === null) {
91354
+ return;
91355
+ }
91356
+ this.#agentTurn = null;
91357
+ await this.recordLifecycleEvent({
91358
+ payload: {
91359
+ commandId: agentTurn.commandId,
91360
+ kind: "prompt.completed",
91361
+ stopReason: report.stopReason
91362
+ },
91363
+ type: "lifecycle-metadata"
91364
+ });
91365
+ this.#getObserver().onAgentTurn?.(this.#mobiusSessionId, null);
91366
+ return;
91367
+ }
91368
+ default: {
91369
+ const unreachable2 = report;
91370
+ throw new AcpExecutionError("Unexpected Agent Turn report", { cause: unreachable2 });
91371
+ }
91372
+ }
91373
+ };
91374
+ /**
91375
+ * Records the Session's outstanding background work when it changed. Each piece belongs to the client command that
91376
+ * was running, or that the Agent's own Turn continued, when it was first reported.
91377
+ */
91378
+ #recordBackgroundTasks = async (reports) => {
91379
+ const owner = this.#agentCommand() ?? this.#agentTurn?.continues ?? this.#lastClientCommandId;
91380
+ const current = new Set(reports.map((report) => report.taskId));
91381
+ for (const taskId of this.#backgroundTaskCommands.keys()) {
91382
+ if (!current.has(taskId)) {
91383
+ this.#backgroundTaskCommands.delete(taskId);
91384
+ }
91385
+ }
91386
+ const tasks = reports.slice(0, SESSION_BACKGROUND_TASK_MAX_COUNT).map((report) => {
91387
+ if (owner !== void 0 && !this.#backgroundTaskCommands.has(report.taskId)) {
91388
+ this.#backgroundTaskCommands.set(report.taskId, owner);
91389
+ }
91390
+ const commandId = this.#backgroundTaskCommands.get(report.taskId);
91391
+ return {
91392
+ kind: report.kind,
91393
+ state: report.state,
91394
+ taskId: report.taskId,
91395
+ ...commandId === void 0 ? {} : { commandId },
91396
+ ...report.toolUseId === void 0 ? {} : { toolCallId: report.toolUseId },
91397
+ ...report.description === void 0 ? {} : { description: truncate(report.description, 500) }
91398
+ };
91399
+ });
91400
+ if (JSON.stringify(tasks) === JSON.stringify(this.#recordedBackground)) {
91401
+ return;
91402
+ }
91403
+ this.#recordedBackground = tasks;
91404
+ await this.recordLifecycleEvent({
91405
+ payload: { kind: "session.background.changed", tasks },
91406
+ type: "lifecycle-metadata"
91407
+ });
91084
91408
  };
91085
91409
  agentSettingsModelEffort = () => this.#modelEffort;
91086
91410
  #sessionParams = (signal) => ({
@@ -91236,7 +91560,11 @@ var SessionManager2 = class {
91236
91560
  #store;
91237
91561
  #onSessionClosed;
91238
91562
  #timer;
91239
- #observer;
91563
+ /** What each Session's Agent process reports to: the runtime's observer, plus the Agent Turns this manager tracks. */
91564
+ #runtimeObserver;
91565
+ #onSessionStatusChanged;
91566
+ /** The command of the Turn each Session's Agent is running on its own; no client's prompt holds it. */
91567
+ #agentTurns = /* @__PURE__ */ new Map();
91240
91568
  /** Each Session's next-prompt suggestions. They outlive the Session's Agent process. */
91241
91569
  promptSuggestions;
91242
91570
  constructor({
@@ -91248,7 +91576,8 @@ var SessionManager2 = class {
91248
91576
  lastTurn = () => void 0,
91249
91577
  timer
91250
91578
  }) {
91251
- this.#observer = observer;
91579
+ this.#runtimeObserver = this.#observing(observer);
91580
+ this.#onSessionStatusChanged = onSessionStatusChanged;
91252
91581
  this.#processes = processes;
91253
91582
  this.#store = store;
91254
91583
  this.#lastTurn = lastTurn;
@@ -91271,11 +91600,42 @@ var SessionManager2 = class {
91271
91600
  return await runtime.recordControlEvent(event);
91272
91601
  };
91273
91602
  setObserver = (observer) => {
91274
- this.#observer = observer;
91603
+ this.#runtimeObserver = this.#observing(observer);
91275
91604
  };
91605
+ #observing(observer) {
91606
+ return {
91607
+ ...observer.onBackgroundActivity === void 0 ? {} : { onBackgroundActivity: observer.onBackgroundActivity },
91608
+ ...observer.onSessionEvent === void 0 ? {} : { onSessionEvent: observer.onSessionEvent },
91609
+ onAgentTurn: (sessionId, commandId) => {
91610
+ observer.onAgentTurn?.(sessionId, commandId);
91611
+ this.#agentTurnChanged(sessionId, commandId);
91612
+ },
91613
+ onCommands: observer.onCommands,
91614
+ onConfig: observer.onConfig,
91615
+ onElicitation: observer.onElicitation,
91616
+ onElicitationResolved: observer.onElicitationResolved,
91617
+ onInfo: observer.onInfo,
91618
+ onPermission: observer.onPermission,
91619
+ onPermissionResolved: observer.onPermissionResolved
91620
+ };
91621
+ }
91622
+ #agentTurnChanged(sessionId, commandId) {
91623
+ if (commandId === null) {
91624
+ this.#agentTurns.delete(sessionId);
91625
+ } else {
91626
+ this.#agentTurns.set(sessionId, commandId);
91627
+ }
91628
+ this.#onSessionStatusChanged({
91629
+ kind: "session.status.changed",
91630
+ sessionId,
91631
+ status: this.sessionStatus(sessionId)
91632
+ });
91633
+ }
91634
+ /** Whether `commandId` names the Turn the Session's Agent is running on its own. */
91635
+ isAgentTurn = (sessionId, commandId) => this.#agentTurns.get(sessionId) === commandId;
91276
91636
  #retention(sessionId) {
91277
91637
  return {
91278
- isBusy: () => this.#executionProcesses.get(sessionId)?.hasBackgroundActivity() === true || this.#executions.isBusy(sessionId) || this.#executionProcesses.isBusy(sessionId),
91638
+ isBusy: () => this.#executionProcesses.get(sessionId)?.hasBackgroundActivity() === true || this.#agentTurns.has(sessionId) || this.#executions.isBusy(sessionId) || this.#executionProcesses.isBusy(sessionId),
91279
91639
  retire: (runtime) => this.#retireSessionProcess(sessionId, runtime, () => runtime.close()),
91280
91640
  retireIdle: (runtime) => this.#stopSessionProcess(sessionId, runtime)
91281
91641
  };
@@ -91346,7 +91706,7 @@ var SessionManager2 = class {
91346
91706
  async (capabilities) => await AgentSession.start(
91347
91707
  options,
91348
91708
  recovery,
91349
- () => this.#observer,
91709
+ () => this.#runtimeObserver,
91350
91710
  this.#executions.agentCommand,
91351
91711
  this.#store,
91352
91712
  metrics,
@@ -91370,7 +91730,7 @@ var SessionManager2 = class {
91370
91730
  async (capabilities) => await AgentSession.start(
91371
91731
  options,
91372
91732
  recovery,
91373
- () => this.#observer,
91733
+ () => this.#runtimeObserver,
91374
91734
  this.#executions.agentCommand,
91375
91735
  this.#store,
91376
91736
  metrics,
@@ -91391,7 +91751,7 @@ var SessionManager2 = class {
91391
91751
  async (capabilities) => await AgentSession.start(
91392
91752
  options,
91393
91753
  recovery,
91394
- () => this.#observer,
91754
+ () => this.#runtimeObserver,
91395
91755
  this.#executions.agentCommand,
91396
91756
  this.#store,
91397
91757
  unmeasuredOperationMetrics,
@@ -91448,7 +91808,7 @@ var SessionManager2 = class {
91448
91808
  async (capabilities) => await AgentSession.start(
91449
91809
  options,
91450
91810
  recovery,
91451
- () => this.#observer,
91811
+ () => this.#runtimeObserver,
91452
91812
  this.#executions.agentCommand,
91453
91813
  this.#store,
91454
91814
  unmeasuredOperationMetrics,
@@ -91717,6 +92077,10 @@ var SessionManager2 = class {
91717
92077
  );
91718
92078
  /** Cancels the named command's Agent execution; a command that is not executing has nothing to stop. */
91719
92079
  cancelPrompt = async (sessionId, commandId, signal = AbortSignal.timeout(3e4)) => this.#operations.run({ signal }, async ({ signal: signal2 }) => {
92080
+ if (this.#agentTurns.get(sessionId) === commandId) {
92081
+ await this.#executionProcesses.get(sessionId)?.cancelAgentTurn(commandId, signal2);
92082
+ return;
92083
+ }
91720
92084
  await this.#executions.cancel(sessionId, commandId, async () => {
91721
92085
  const runtime = this.#executionProcesses.get(sessionId);
91722
92086
  if (runtime !== void 0) {
@@ -91912,11 +92276,18 @@ var SessionManager2 = class {
91912
92276
  return stored instanceof FoundStoredSession ? [stored.session] : [];
91913
92277
  });
91914
92278
  sessionStatus = (sessionId) => this.#reported(sessionId, this.#executions.status(sessionId));
91915
- /** An idle Session whose last started command failed says so, so a client that did not watch it still knows. */
92279
+ /**
92280
+ * A Session whose Agent runs a Turn of its own is working on that command while no client's prompt runs. An idle
92281
+ * Session whose last started command failed says so, so a client that did not watch it still knows.
92282
+ */
91916
92283
  #reported = (sessionId, status) => {
91917
92284
  if (status.kind !== "idle") {
91918
92285
  return status;
91919
92286
  }
92287
+ const agentTurn = this.#agentTurns.get(sessionId);
92288
+ if (agentTurn !== void 0) {
92289
+ return { commandId: agentTurn, kind: "working" };
92290
+ }
91920
92291
  const lastTurn = this.#lastTurn(sessionId);
91921
92292
  return lastTurn?.state === "failed" ? {
91922
92293
  ...status,
@@ -92181,7 +92552,7 @@ var PromptLifecycle = class {
92181
92552
  record = (recorded) => {
92182
92553
  this.#recordActiveTurn(recorded);
92183
92554
  const sessionId = recorded.sessionId;
92184
- if (recorded.type === "lifecycle-metadata" && isPromptTerminal(recorded.payload)) {
92555
+ if (recorded.type === "lifecycle-metadata" && isPromptTerminal(recorded.payload) && this.#queued.has(recorded.payload.commandId)) {
92185
92556
  this.#terminal.set(recorded.payload.commandId, recorded);
92186
92557
  const pending = this.#publications.get(sessionId) ?? [];
92187
92558
  pending.push(recorded);
@@ -92324,7 +92695,7 @@ async function settleAbandonedTurn(projection, operations, cancellation) {
92324
92695
  }
92325
92696
 
92326
92697
  // src/engine/session/turn/execution-receipts.ts
92327
- import { createHash as createHash7, randomUUID as randomUUID14 } from "node:crypto";
92698
+ import { createHash as createHash7, randomUUID as randomUUID15 } from "node:crypto";
92328
92699
  var MAX_TERMINAL_RECEIPTS = 1024;
92329
92700
  function executionStarted(state) {
92330
92701
  switch (state.kind) {
@@ -92626,7 +92997,7 @@ var ExecutionReceipts = class {
92626
92997
  ).digest("hex");
92627
92998
  this.#save(commandId, {
92628
92999
  admissionOrder: this.#nextAdmissionOrder(),
92629
- attemptId: randomUUID14(),
93000
+ attemptId: randomUUID15(),
92630
93001
  commandHash,
92631
93002
  sessionId,
92632
93003
  state: {
@@ -92738,7 +93109,7 @@ var ExecutionReceipts = class {
92738
93109
  default:
92739
93110
  return unexpectedStanding(standing);
92740
93111
  }
92741
- const attemptId = randomUUID14();
93112
+ const attemptId = randomUUID15();
92742
93113
  this.#save(commandId, {
92743
93114
  admissionOrder: this.#nextAdmissionOrder(),
92744
93115
  attemptId,
@@ -92851,11 +93222,11 @@ var RuntimeTurnActivity = class {
92851
93222
  };
92852
93223
 
92853
93224
  // src/engine/session/turn/active-turn.ts
92854
- import { randomUUID as randomUUID15 } from "node:crypto";
93225
+ import { randomUUID as randomUUID16 } from "node:crypto";
92855
93226
  var ActiveRuntimeTurn = class {
92856
93227
  attemptId;
92857
93228
  command;
92858
- epoch = decodeIdentifier(randomUUID15());
93229
+ epoch = decodeIdentifier(randomUUID16());
92859
93230
  #controller;
92860
93231
  #finished = Promise.withResolvers();
92861
93232
  #started;
@@ -93502,11 +93873,11 @@ import { extname as extname2, join as join29 } from "node:path";
93502
93873
  import { pathToFileURL as pathToFileURL3 } from "node:url";
93503
93874
 
93504
93875
  // src/engine/storage/files/scratch-directory.ts
93505
- import { randomUUID as randomUUID16 } from "node:crypto";
93876
+ import { randomUUID as randomUUID17 } from "node:crypto";
93506
93877
  import { lstat as lstat4, mkdir as mkdir5, readdir as readdir6, readFile as readFile7, realpath as realpath7, rename as rename4, rm as rm5, stat as stat6, utimes, writeFile as writeFile2 } from "node:fs/promises";
93507
93878
  import { dirname as dirname11, join as join28 } from "node:path";
93508
93879
  async function atomicWrite(path6, bytes, signal) {
93509
- const temporary = `${path6}.${randomUUID16()}.tmp`;
93880
+ const temporary = `${path6}.${randomUUID17()}.tmp`;
93510
93881
  try {
93511
93882
  await writeFile2(temporary, bytes, { mode: 384, signal });
93512
93883
  signal.throwIfAborted();
@@ -93518,7 +93889,7 @@ async function atomicWrite(path6, bytes, signal) {
93518
93889
  var ScratchDirectory = class {
93519
93890
  #root;
93520
93891
  constructor(parent) {
93521
- this.#root = join28(parent, randomUUID16());
93892
+ this.#root = join28(parent, randomUUID17());
93522
93893
  }
93523
93894
  /** Refreshes this directory's lease and removes sibling directories whose lease is older than `leaseMilliseconds`. */
93524
93895
  refreshLease = async (leaseMilliseconds) => {
@@ -94005,7 +94376,7 @@ var AgentProcessPool = class {
94005
94376
  };
94006
94377
 
94007
94378
  // src/engine/session/settings/agent-settings-cache.ts
94008
- import { createHash as createHash9, randomUUID as randomUUID17 } from "node:crypto";
94379
+ import { createHash as createHash9, randomUUID as randomUUID18 } from "node:crypto";
94009
94380
  import { join as join30 } from "node:path";
94010
94381
  var CACHE_FILE_LIMIT = 32 * 1024 * 1024;
94011
94382
  var CACHE_FORMAT = 1;
@@ -94078,7 +94449,7 @@ var AgentSettingsCache = class {
94078
94449
  return this.#generation;
94079
94450
  }
94080
94451
  invalidate = async (signal) => {
94081
- await writeInstallationFile(this.#generationPath, randomUUID17(), signal);
94452
+ await writeInstallationFile(this.#generationPath, randomUUID18(), signal);
94082
94453
  this.#generation += 1;
94083
94454
  };
94084
94455
  open = async (agent2, signal) => {
@@ -95299,6 +95670,12 @@ var sessionCancelCommand = {
95299
95670
  if (message.kind !== SESSION_CANCEL_KIND) {
95300
95671
  throw new Error("Command kind mismatch");
95301
95672
  }
95673
+ if (sessions.isAgentTurn(message.sessionId, message.commandId)) {
95674
+ void sessions.cancelPrompt(message.sessionId, message.commandId, signal).catch((error62) => {
95675
+ console.error("Mobius daemon could not cancel the Agent's own turn", error62);
95676
+ });
95677
+ return;
95678
+ }
95302
95679
  const turn = sessionTurns.get(message.commandId, message.sessionId);
95303
95680
  if (turn === void 0) {
95304
95681
  void settleAbandonedTurn(eventProjection, operations, message).catch((error62) => {
@@ -95588,7 +95965,7 @@ async function resolveSessionDirectories(directories, bindingId, directoryId, ad
95588
95965
  }
95589
95966
 
95590
95967
  // src/engine/session/prompt/apply-session-configuration.ts
95591
- import { randomUUID as randomUUID18 } from "node:crypto";
95968
+ import { randomUUID as randomUUID19 } from "node:crypto";
95592
95969
  function invalidSessionConfiguration(message) {
95593
95970
  return new AcpExecutionError(message, {}, "invalid_session_configuration");
95594
95971
  }
@@ -95713,7 +96090,7 @@ async function applySessionConfigurationSelection(sessions, options, selection,
95713
96090
  booleanValue: selection.booleanValue,
95714
96091
  configId: selection.configId,
95715
96092
  cwd,
95716
- requestId: `cfg_${randomUUID18()}`,
96093
+ requestId: `cfg_${randomUUID19()}`,
95717
96094
  sessionId,
95718
96095
  signal,
95719
96096
  value: selection.value,
@@ -97699,4 +98076,4 @@ export {
97699
98076
  * MIT Licensed
97700
98077
  *)
97701
98078
  */
97702
- //# sourceMappingURL=chunk-TMQPBQLB.js.map
98079
+ //# sourceMappingURL=chunk-X6VDMZHE.js.map