@moxt-ai/mobius 0.0.73 → 0.0.74

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 (40) hide show
  1. package/dist/acp/activity.d.ts +9 -1
  2. package/dist/acp/activity.d.ts.map +1 -1
  3. package/dist/acp/activity.js +51 -13
  4. package/dist/acp/activity.js.map +1 -1
  5. package/dist/acp/codex/agent.d.ts.map +1 -1
  6. package/dist/acp/codex/agent.js +103 -3
  7. package/dist/acp/codex/agent.js.map +1 -1
  8. package/dist/acp/codex/app-server-protocol.d.ts +34 -0
  9. package/dist/acp/codex/app-server-protocol.d.ts.map +1 -1
  10. package/dist/acp/codex/app-server-protocol.js +26 -0
  11. package/dist/acp/codex/app-server-protocol.js.map +1 -1
  12. package/dist/acp/run-prompt.d.ts +2 -1
  13. package/dist/acp/run-prompt.d.ts.map +1 -1
  14. package/dist/acp/run-prompt.js +1 -0
  15. package/dist/acp/run-prompt.js.map +1 -1
  16. package/dist/acp/session-history.d.ts.map +1 -1
  17. package/dist/acp/session-history.js +4 -1
  18. package/dist/acp/session-history.js.map +1 -1
  19. package/dist/acp/session-manager.d.ts +6 -1
  20. package/dist/acp/session-manager.d.ts.map +1 -1
  21. package/dist/acp/session-manager.js +4 -4
  22. package/dist/acp/session-manager.js.map +1 -1
  23. package/dist/cli.js +380 -47
  24. package/dist/cli.js.map +4 -4
  25. package/dist/index.js +380 -46
  26. package/dist/index.js.map +4 -4
  27. package/dist/relay-connection/coalescing-narration-publisher.d.ts +31 -0
  28. package/dist/relay-connection/coalescing-narration-publisher.d.ts.map +1 -0
  29. package/dist/relay-connection/coalescing-narration-publisher.js +61 -0
  30. package/dist/relay-connection/coalescing-narration-publisher.js.map +1 -0
  31. package/dist/relay-connection/session-event-outbox.d.ts +6 -0
  32. package/dist/relay-connection/session-event-outbox.d.ts.map +1 -1
  33. package/dist/relay-connection/session-event-outbox.js +13 -0
  34. package/dist/relay-connection/session-event-outbox.js.map +1 -1
  35. package/dist/run-daemon.d.ts.map +1 -1
  36. package/dist/run-daemon.js +88 -6
  37. package/dist/run-daemon.js.map +1 -1
  38. package/dist/runtime.js +379 -46
  39. package/dist/runtime.js.map +4 -4
  40. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -11,7 +11,7 @@ import { mkdir as mkdir6 } from "node:fs/promises";
11
11
  // package.json
12
12
  var package_default = {
13
13
  name: "@moxt-ai/mobius",
14
- version: "0.0.73",
14
+ version: "0.0.74",
15
15
  description: "Mobius CLI for pairing and running local AI agent services.",
16
16
  type: "module",
17
17
  bin: {
@@ -21276,6 +21276,11 @@ var threadStartResponseSchema = external_exports.object({
21276
21276
  serviceTier: boundedText(256).nullish(),
21277
21277
  thread: external_exports.object({ id: boundedText(256) })
21278
21278
  });
21279
+ var threadResumeResponseSchema = external_exports.object({
21280
+ model: boundedText(256).nullish(),
21281
+ reasoningEffort: boundedText(256).nullish(),
21282
+ thread: external_exports.object({ id: boundedText(256) }).nullish()
21283
+ });
21279
21284
  var reasoningEffortOptionSchema = external_exports.object({
21280
21285
  description: boundedText(4096).nullish(),
21281
21286
  reasoningEffort: boundedText(256)
@@ -21293,6 +21298,19 @@ var modelListResponseSchema = external_exports.object({
21293
21298
  data: external_exports.array(modelSchema).max(1e3),
21294
21299
  nextCursor: boundedText(1024).nullish()
21295
21300
  });
21301
+ var threadSchema = external_exports.object({
21302
+ createdAt: external_exports.number().nullish(),
21303
+ cwd: boundedText(4096).nullish(),
21304
+ id: boundedText(256),
21305
+ name: boundedText(4096).nullish(),
21306
+ preview: boundedText(4096).nullish(),
21307
+ updatedAt: external_exports.number().nullish()
21308
+ });
21309
+ var threadListResponseSchema = external_exports.object({
21310
+ data: external_exports.array(threadSchema).max(1e4),
21311
+ nextCursor: boundedText(1024).nullish()
21312
+ });
21313
+ var turnSteerResponseSchema = external_exports.object({ turnId: boundedText(256) });
21296
21314
 
21297
21315
  // src/acp/codex/app-server-client.ts
21298
21316
  var INITIALIZE_TIMEOUT_MILLISECONDS = 3e4;
@@ -21632,6 +21650,7 @@ function agentMessageMeta(phase) {
21632
21650
  var APPROVAL_REASON_CHARACTER_LIMIT = 500;
21633
21651
  var APPROVAL_TIMEOUT_MILLISECONDS = 36e5;
21634
21652
  var CODEX_AGENT_VERSION = "0.154.0";
21653
+ var STEERING_METHOD = "_session/steering";
21635
21654
  var MODEL_SETTING_ID = "model";
21636
21655
  var REASONING_EFFORT_SETTING_ID = "reasoning_effort";
21637
21656
  var MODE_SETTING_ID = "mode";
@@ -21682,6 +21701,26 @@ function initialMode(environment) {
21682
21701
  function capitalize(value) {
21683
21702
  return value.length === 0 ? value : value.charAt(0).toUpperCase() + value.slice(1);
21684
21703
  }
21704
+ function threadTitle(thread) {
21705
+ const named = thread.name?.trim() ?? "";
21706
+ if (named.length > 0) {
21707
+ return named;
21708
+ }
21709
+ return thread.preview?.trim() ?? "";
21710
+ }
21711
+ function isoTimestamp(seconds) {
21712
+ if (seconds == null || !Number.isFinite(seconds)) {
21713
+ return null;
21714
+ }
21715
+ return new Date(seconds * 1e3).toISOString();
21716
+ }
21717
+ function steeringParams(params) {
21718
+ const prompt = typeof params === "object" && params !== null ? Reflect.get(params, "prompt") : void 0;
21719
+ if (!Array.isArray(prompt)) {
21720
+ throw new AcpExecutionError("The steering prompt is invalid", {}, "steering_failed");
21721
+ }
21722
+ return { prompt };
21723
+ }
21685
21724
  var APPROVAL_OPTIONS = Object.freeze([
21686
21725
  { kind: "allow_once", name: "Allow once", optionId: "accept" },
21687
21726
  { kind: "allow_always", name: "Allow for this session", optionId: "acceptForSession" },
@@ -21855,10 +21894,12 @@ var CodexAcpAgent = class {
21855
21894
  agentCapabilities: {
21856
21895
  loadSession: false,
21857
21896
  promptCapabilities: { embeddedContext: true, image: true },
21858
- sessionCapabilities: { close: {} }
21897
+ sessionCapabilities: { close: {}, delete: {}, list: {}, resume: {} }
21859
21898
  },
21860
21899
  agentInfo: { name: "Codex", version: CODEX_AGENT_VERSION },
21861
21900
  authMethods: [],
21901
+ // Mobius reads this to decide whether mid-turn steering can be attempted at all.
21902
+ _meta: { steering: { supported: true } },
21862
21903
  protocolVersion: PROTOCOL_VERSION
21863
21904
  })).onRequest(methods.agent.session.new, async (context) => {
21864
21905
  const created = threadStartResponseSchema.parse(
@@ -21875,6 +21916,54 @@ var CodexAcpAgent = class {
21875
21916
  model: created.model ?? ""
21876
21917
  };
21877
21918
  return { configOptions: this.#configOptions(), sessionId: created.thread.id };
21919
+ }).onRequest(methods.agent.session.resume, async (context) => {
21920
+ const resumed = threadResumeResponseSchema.parse(
21921
+ await this.#appServer.request(
21922
+ "thread/resume",
21923
+ { cwd: context.params.cwd, threadId: context.params.sessionId },
21924
+ AbortSignal.any([context.signal, AbortSignal.timeout(APPROVAL_TIMEOUT_MILLISECONDS)])
21925
+ )
21926
+ );
21927
+ if (resumed.thread == null) {
21928
+ throw new AcpExecutionError(
21929
+ "Codex no longer has the native session this conversation belongs to",
21930
+ {},
21931
+ "session_restore_unsupported"
21932
+ );
21933
+ }
21934
+ this.#nativeSessionId = resumed.thread.id;
21935
+ this.#selection = {
21936
+ ...this.#selection,
21937
+ effort: resumed.reasoningEffort ?? this.#selection.effort,
21938
+ model: resumed.model ?? this.#selection.model
21939
+ };
21940
+ return { configOptions: this.#configOptions() };
21941
+ }).onRequest(methods.agent.session.list, async (context) => {
21942
+ const listed = threadListResponseSchema.parse(
21943
+ await this.#appServer.request(
21944
+ "thread/list",
21945
+ context.params.cursor === void 0 || context.params.cursor === null ? {} : { cursor: context.params.cursor },
21946
+ AbortSignal.any([context.signal, AbortSignal.timeout(APPROVAL_TIMEOUT_MILLISECONDS)])
21947
+ )
21948
+ );
21949
+ return {
21950
+ nextCursor: listed.nextCursor ?? null,
21951
+ sessions: listed.data.map((thread) => ({
21952
+ // The thread id is a UUID, which satisfies the native session id contract.
21953
+ additionalDirectories: [],
21954
+ cwd: thread.cwd ?? "",
21955
+ sessionId: thread.id,
21956
+ title: threadTitle(thread),
21957
+ updatedAt: isoTimestamp(thread.updatedAt)
21958
+ }))
21959
+ };
21960
+ }).onRequest(methods.agent.session.delete, async (context) => {
21961
+ await this.#appServer.request(
21962
+ "thread/archive",
21963
+ { threadId: context.params.sessionId },
21964
+ AbortSignal.any([context.signal, AbortSignal.timeout(APPROVAL_TIMEOUT_MILLISECONDS)])
21965
+ );
21966
+ return {};
21878
21967
  }).onRequest(methods.agent.session.setConfigOption, async (context) => {
21879
21968
  this.#applySelection(context.params.configId, context.params.value);
21880
21969
  return { configOptions: this.#configOptions() };
@@ -21883,6 +21972,30 @@ var CodexAcpAgent = class {
21883
21972
  return {};
21884
21973
  }).onRequest(methods.agent.session.prompt, async (context) => {
21885
21974
  return await this.#runTurn(promptInput(context.params.prompt), context.signal);
21975
+ }).onRequest(STEERING_METHOD, steeringParams, async (context) => {
21976
+ const turn = this.#turn;
21977
+ if (turn === null || turn.turn.id.length === 0) {
21978
+ return { outcome: "promptRequired" };
21979
+ }
21980
+ try {
21981
+ const steered = turnSteerResponseSchema.parse(
21982
+ await this.#appServer.request(
21983
+ "turn/steer",
21984
+ {
21985
+ expectedTurnId: turn.turn.id,
21986
+ input: promptInput(context.params.prompt),
21987
+ threadId: this.#nativeSessionId
21988
+ },
21989
+ AbortSignal.any([context.signal, AbortSignal.timeout(APPROVAL_TIMEOUT_MILLISECONDS)])
21990
+ )
21991
+ );
21992
+ return { outcome: steered.turnId === turn.turn.id ? "injected" : "startedNewTurn" };
21993
+ } catch (error62) {
21994
+ if (error62 instanceof CodexAppServerError) {
21995
+ return { outcome: "promptRequired" };
21996
+ }
21997
+ throw error62;
21998
+ }
21886
21999
  }).onRequest(methods.agent.session.close, async () => {
21887
22000
  await this.#interruptTurn();
21888
22001
  }).onNotification(methods.agent.session.cancel, async () => {
@@ -24647,6 +24760,7 @@ var RUNTIME_DELIVERY_COMMITTED_KIND = "runtime.delivery.committed";
24647
24760
  var SESSION_STARTED_KIND = "session.started";
24648
24761
  var AGENT_MESSAGE_DELTA_KIND = "agent.message.delta";
24649
24762
  var AGENT_ACTIVITY_KIND = "agent.activity";
24763
+ var AGENT_ACTIVITY_NARRATION_KIND = "agent.activity.narration";
24650
24764
  var AGENT_ACTIVITY_DETAIL_LIMIT = 5e5;
24651
24765
  var AGENT_ACTIVITY_RECORDED_FIELD_LIMIT = 4e6;
24652
24766
  var AGENT_ACTIVITY_RECORDED_DETAIL_LIMIT = 6e6;
@@ -24668,6 +24782,7 @@ var MAX_PROMPT_ATTACHMENT_LENGTH = 6e6;
24668
24782
  var MAX_EVENT_TEXT_LENGTH = 1e5;
24669
24783
  var MAX_RUNTIME_DELIVERY_PAYLOAD_LENGTH = 8 * 1024 * 1024;
24670
24784
  var ACTIVITY_TYPES = /* @__PURE__ */ new Set(["plan", "progress", "reasoning", "tool"]);
24785
+ var NARRATION_ACTIVITY_TYPES = /* @__PURE__ */ new Set(["progress", "reasoning"]);
24671
24786
  var ACTIVITY_STATUSES = /* @__PURE__ */ new Set(["pending", "running", "completed", "failed"]);
24672
24787
  var TOOL_KINDS = /* @__PURE__ */ new Set([
24673
24788
  "",
@@ -25091,6 +25206,20 @@ function encodeRuntimeDeliveryReceived(message) {
25091
25206
  function encodeRuntimeDeliveryCommitted(message) {
25092
25207
  return JSON.stringify(decodeRuntimeDeliveryCommitted(JSON.stringify(message)));
25093
25208
  }
25209
+ function decodeAgentActivityNarrationEvent(encoded) {
25210
+ const value = parseJson2(encoded);
25211
+ assertExactKeys(value, ["activityId", "activityType", "commandId", "kind", "sequence", "sessionId", "text"]);
25212
+ assertKind(value, AGENT_ACTIVITY_NARRATION_KIND);
25213
+ return {
25214
+ activityId: readIdentifier(value, "activityId"),
25215
+ activityType: readAllowedString(value, "activityType", NARRATION_ACTIVITY_TYPES),
25216
+ commandId: readIdentifier(value, "commandId"),
25217
+ kind: AGENT_ACTIVITY_NARRATION_KIND,
25218
+ sequence: readSequence(value, "sequence"),
25219
+ sessionId: readIdentifier(value, "sessionId"),
25220
+ text: readText(value, "text", MAX_EVENT_TEXT_LENGTH)
25221
+ };
25222
+ }
25094
25223
 
25095
25224
  // ../protocol/src/session-history.ts
25096
25225
  var SESSION_HISTORY_CHARACTER_LIMIT = 256e3;
@@ -25439,6 +25568,8 @@ function decodeRecordedSessionEvent(encoded) {
25439
25568
  switch (kind) {
25440
25569
  case AGENT_ACTIVITY_KIND:
25441
25570
  return decodeAgentActivityEvent(encoded);
25571
+ case AGENT_ACTIVITY_NARRATION_KIND:
25572
+ return decodeAgentActivityNarrationEvent(encoded);
25442
25573
  case AGENT_CONTENT_KIND:
25443
25574
  return decodeAgentContentEvent(encoded);
25444
25575
  case AGENT_MESSAGE_DELTA_KIND:
@@ -27039,6 +27170,18 @@ async function replaceImageMarkers(text3, replace) {
27039
27170
 
27040
27171
  // src/acp/activity.ts
27041
27172
  var TRUNCATION_MARKER = "\n\u2026 output truncated by Mobius";
27173
+ var AcpActivityNarration = class {
27174
+ activityId;
27175
+ activityType;
27176
+ sequence;
27177
+ text;
27178
+ constructor(activityId, activityType, sequence, text3) {
27179
+ this.activityId = activityId;
27180
+ this.activityType = activityType;
27181
+ this.sequence = sequence;
27182
+ this.text = text3;
27183
+ }
27184
+ };
27042
27185
  function isRecord7(value) {
27043
27186
  return typeof value === "object" && value !== null && !Array.isArray(value);
27044
27187
  }
@@ -27371,12 +27514,15 @@ function isProgressMessage(content3) {
27371
27514
  var AcpActivityTracker = class {
27372
27515
  #activities = /* @__PURE__ */ new Map();
27373
27516
  #identities = /* @__PURE__ */ new Map();
27517
+ #narrations = /* @__PURE__ */ new Map();
27374
27518
  #onActivity;
27519
+ #onNarration;
27375
27520
  #prepareContent;
27376
27521
  #activeNarrativeKey = "";
27377
27522
  #nextSequence = 0;
27378
- constructor(onActivity, prepareContent = (content3) => Promise.resolve(content3)) {
27523
+ constructor(onActivity, onNarration, prepareContent = (content3) => Promise.resolve(content3)) {
27379
27524
  this.#onActivity = onActivity;
27525
+ this.#onNarration = onNarration;
27380
27526
  this.#prepareContent = prepareContent;
27381
27527
  }
27382
27528
  recordNarrative = async (activityType, messageId, text3) => {
@@ -27384,26 +27530,34 @@ var AcpActivityTracker = class {
27384
27530
  if (this.#activeNarrativeKey !== key) {
27385
27531
  await this.finishNarrative();
27386
27532
  }
27387
- const previous2 = this.#activities.get(key);
27388
27533
  const identity2 = this.#identity(key);
27389
- const fullOutput = `${recordedDetail(previous2)?.output ?? previous2?.output ?? ""}${text3}`;
27390
- const activity2 = new AcpActivity(
27391
- identity2.id,
27534
+ const previous2 = this.#narrations.get(key);
27535
+ this.#narrations.set(key, {
27536
+ activityId: identity2.id,
27392
27537
  activityType,
27393
- "",
27394
- [],
27395
- "",
27396
- truncate2(fullOutput, AGENT_ACTIVITY_DETAIL_LIMIT),
27397
- identity2.sequence,
27398
- "running",
27399
- activityType === "reasoning" ? "Reasoning" : "Progress update",
27400
- activityType === "reasoning" ? "think" : "",
27401
- [],
27402
- captureActivityDetail([], "", fullOutput)
27403
- );
27404
- await this.#record(key, activity2);
27538
+ output: `${previous2?.output ?? ""}${text3}`,
27539
+ sequence: identity2.sequence
27540
+ });
27541
+ if (previous2 === void 0) {
27542
+ await this.#record(key, this.#narrativeSnapshot(identity2, activityType, "", "running"));
27543
+ }
27405
27544
  this.#activeNarrativeKey = key;
27545
+ if (text3.length > 0) {
27546
+ await this.#onNarration(new AcpActivityNarration(identity2.id, activityType, identity2.sequence, text3));
27547
+ }
27406
27548
  };
27549
+ #narrativeSnapshot = (identity2, activityType, output2, status) => new AcpActivity(
27550
+ identity2.id,
27551
+ activityType,
27552
+ "",
27553
+ [],
27554
+ "",
27555
+ truncate2(output2, AGENT_ACTIVITY_DETAIL_LIMIT),
27556
+ identity2.sequence,
27557
+ status,
27558
+ activityType === "reasoning" ? "Reasoning" : "Progress update",
27559
+ activityType === "reasoning" ? "think" : ""
27560
+ );
27407
27561
  recordPlan = async (plan) => {
27408
27562
  await this.finishNarrative();
27409
27563
  await this.#recordPlanEntries("plan:default", plan.entries);
@@ -27523,17 +27677,13 @@ var AcpActivityTracker = class {
27523
27677
  return;
27524
27678
  }
27525
27679
  this.#activeNarrativeKey = "";
27526
- const activity2 = this.#activities.get(key);
27527
- if (activity2 === void 0) {
27528
- return;
27529
- }
27530
- const completed = activity2.complete();
27531
- if (completed !== activity2) {
27532
- await this.#record(key, completed);
27533
- }
27680
+ await this.#completeNarrative(key);
27534
27681
  };
27535
27682
  finish = async () => {
27536
27683
  await this.finishNarrative();
27684
+ for (const key of this.#narrations.keys()) {
27685
+ await this.#completeNarrative(key);
27686
+ }
27537
27687
  const entries = [...this.#activities.entries()].sort((left, right) => left[1].sequence - right[1].sequence);
27538
27688
  for (const [key, activity2] of entries) {
27539
27689
  const completed = activity2.complete();
@@ -27542,6 +27692,34 @@ var AcpActivityTracker = class {
27542
27692
  }
27543
27693
  }
27544
27694
  };
27695
+ // Materialize a streamed narration as one completed snapshot activity. The
27696
+ // incremental events carried the text; this final event gives consumers the
27697
+ // whole narration with its terminal status, as a single bounded item.
27698
+ #completeNarrative = async (key) => {
27699
+ const narration = this.#narrations.get(key);
27700
+ if (narration === void 0) {
27701
+ return;
27702
+ }
27703
+ this.#narrations.delete(key);
27704
+ const previous2 = this.#activities.get(key);
27705
+ await this.#record(
27706
+ key,
27707
+ new AcpActivity(
27708
+ narration.activityId,
27709
+ narration.activityType,
27710
+ "",
27711
+ [],
27712
+ "",
27713
+ truncate2(narration.output, AGENT_ACTIVITY_DETAIL_LIMIT),
27714
+ narration.sequence,
27715
+ "completed",
27716
+ narration.activityType === "reasoning" ? "Reasoning" : "Progress update",
27717
+ narration.activityType === "reasoning" ? "think" : "",
27718
+ previous2?.content ?? [],
27719
+ captureActivityDetail([], "", narration.output)
27720
+ )
27721
+ );
27722
+ };
27545
27723
  #identity = (key) => {
27546
27724
  const existing = this.#identities.get(key);
27547
27725
  if (existing !== void 0) {
@@ -35185,17 +35363,22 @@ var AcpHistoryReplay = class {
35185
35363
  #activities = /* @__PURE__ */ new Map();
35186
35364
  #messages = [];
35187
35365
  #turnActivityIds = /* @__PURE__ */ new Set();
35188
- #activityTracker = new AcpActivityTracker(async (activity2) => {
35189
- this.#activities.set(activity2.activityId, activity2);
35190
- this.#turnActivityIds.add(activity2.activityId);
35191
- const latest = this.#messages.at(-1);
35192
- if (latest?.role === "assistant") {
35193
- this.#messages[this.#messages.length - 1] = {
35194
- ...latest,
35195
- activityIds: [...this.#turnActivityIds]
35196
- };
35197
- }
35198
- });
35366
+ #activityTracker = new AcpActivityTracker(
35367
+ async (activity2) => {
35368
+ this.#activities.set(activity2.activityId, activity2);
35369
+ this.#turnActivityIds.add(activity2.activityId);
35370
+ const latest = this.#messages.at(-1);
35371
+ if (latest?.role === "assistant") {
35372
+ this.#messages[this.#messages.length - 1] = {
35373
+ ...latest,
35374
+ activityIds: [...this.#turnActivityIds]
35375
+ };
35376
+ }
35377
+ },
35378
+ // History replay folds each narration into its snapshot activity, so no
35379
+ // separate incremental event is produced here.
35380
+ () => Promise.resolve()
35381
+ );
35199
35382
  #lastMessageId = null;
35200
35383
  #characters = 0;
35201
35384
  #truncated = false;
@@ -36014,7 +36197,10 @@ var AcpTurnState = class {
36014
36197
  var IdleAcpTurn = class extends AcpTurnState {
36015
36198
  commandId = SESSION_CONTROL_COMMAND_ID;
36016
36199
  running = false;
36017
- activities = new AcpActivityTracker(() => Promise.resolve());
36200
+ activities = new AcpActivityTracker(
36201
+ () => Promise.resolve(),
36202
+ () => Promise.resolve()
36203
+ );
36018
36204
  onText = () => Promise.resolve();
36019
36205
  };
36020
36206
  var RunningAcpTurn = class extends AcpTurnState {
@@ -36022,10 +36208,10 @@ var RunningAcpTurn = class extends AcpTurnState {
36022
36208
  running = true;
36023
36209
  activities;
36024
36210
  onText;
36025
- constructor(commandId, onActivity, onText, prepareContent) {
36211
+ constructor(commandId, onActivity, onNarration, onText, prepareContent) {
36026
36212
  super();
36027
36213
  this.commandId = commandId;
36028
- this.activities = new AcpActivityTracker(onActivity, prepareContent);
36214
+ this.activities = new AcpActivityTracker(onActivity, onNarration ?? (() => Promise.resolve()), prepareContent);
36029
36215
  this.onText = onText;
36030
36216
  }
36031
36217
  };
@@ -36830,6 +37016,7 @@ var AcpProcessSession = class _AcpProcessSession {
36830
37016
  const running = new RunningAcpTurn(
36831
37017
  options.commandId,
36832
37018
  options.onActivity,
37019
+ options.onNarration,
36833
37020
  options.onText,
36834
37021
  this.prepareAgentContent
36835
37022
  );
@@ -39498,7 +39685,7 @@ var responseSchema = external_exports.union([
39498
39685
  external_exports.object({ id: external_exports.number(), result: external_exports.unknown() }),
39499
39686
  external_exports.object({ method: external_exports.string() })
39500
39687
  ]);
39501
- var threadSchema = external_exports.object({
39688
+ var threadSchema2 = external_exports.object({
39502
39689
  thread: external_exports.object({
39503
39690
  id: nativeSessionIdSchema,
39504
39691
  cwd: external_exports.string().min(1).max(2048).refine((path2) => !path2.includes("\0"))
@@ -39802,7 +39989,7 @@ async function readCodexHistoryWithOptions(agent, cwd, nativeSessionId, signal,
39802
39989
  });
39803
39990
  break;
39804
39991
  case "metadata": {
39805
- const { thread } = threadSchema.parse(message.result);
39992
+ const { thread } = threadSchema2.parse(message.result);
39806
39993
  state = { kind: "turns", requestId: 3, thread };
39807
39994
  send2({
39808
39995
  id: state.requestId,
@@ -40512,6 +40699,59 @@ async function resolvePromptArtifacts(config2, command, signal) {
40512
40699
  return new ResolvedPromptArtifacts(images, resources);
40513
40700
  }
40514
40701
 
40702
+ // src/relay-connection/coalescing-narration-publisher.ts
40703
+ var CoalescingNarrationPublisher = class {
40704
+ #coalescingMilliseconds;
40705
+ #maximumTextLength;
40706
+ #publish;
40707
+ #timer;
40708
+ #pending = /* @__PURE__ */ new Map();
40709
+ #scheduled = null;
40710
+ constructor(timer, publish, coalescingMilliseconds, maximumTextLength) {
40711
+ this.#publish = publish;
40712
+ this.#timer = timer;
40713
+ this.#coalescingMilliseconds = coalescingMilliseconds;
40714
+ this.#maximumTextLength = maximumTextLength;
40715
+ }
40716
+ /** Emit every buffered increment now, cancelling the pending flush. */
40717
+ flush = () => {
40718
+ this.#scheduled?.cancel();
40719
+ this.#scheduled = null;
40720
+ const increments = [...this.#pending.entries()].map(
40721
+ ([activityId, pending]) => ({
40722
+ activityId,
40723
+ activityType: pending.activityType,
40724
+ sequence: pending.sequence,
40725
+ text: pending.text
40726
+ })
40727
+ );
40728
+ this.#pending.clear();
40729
+ for (const increment of increments) {
40730
+ this.#publish(increment);
40731
+ }
40732
+ };
40733
+ /**
40734
+ * Buffer an increment, emitting the buffered text when it would exceed the
40735
+ * protocol's per-event text limit so no event is rejected by the codec.
40736
+ */
40737
+ record = (increment) => {
40738
+ if (increment.text.length === 0) {
40739
+ return;
40740
+ }
40741
+ const previous2 = this.#pending.get(increment.activityId);
40742
+ if (previous2 !== void 0 && previous2.text.length + increment.text.length > this.#maximumTextLength) {
40743
+ this.flush();
40744
+ }
40745
+ const current = this.#pending.get(increment.activityId);
40746
+ this.#pending.set(increment.activityId, {
40747
+ activityType: increment.activityType,
40748
+ sequence: increment.sequence,
40749
+ text: `${current?.text ?? ""}${increment.text}`
40750
+ });
40751
+ this.#scheduled ??= this.#timer.schedule(this.flush, this.#coalescingMilliseconds);
40752
+ };
40753
+ };
40754
+
40515
40755
  // src/relay-connection/coalescing-text-publisher.ts
40516
40756
  var CoalescingTextPublisher = class {
40517
40757
  #coalescingMilliseconds;
@@ -41249,6 +41489,19 @@ var SessionEventOutbox = class {
41249
41489
  return this.#enqueueBounded(sessionId, payload, attemptId ?? "", this.#limits.standardEventBytes);
41250
41490
  };
41251
41491
  enqueueCritical = (sessionId, payload, attemptId = "") => this.#enqueueBounded(sessionId, payload, attemptId, this.#limits.criticalEventBytes);
41492
+ /**
41493
+ * Bytes still available to standard Session events. The daemon uses this to shed
41494
+ * superseded streaming events instead of filling the durable outbox, so a long Turn
41495
+ * behind a slow Relay cannot make the next enqueue throw.
41496
+ */
41497
+ standardCapacityRemaining = () => {
41498
+ const state = this.#database.prepare(
41499
+ `SELECT total_bytes
41500
+ FROM relay_session_event_outbox_state
41501
+ WHERE singleton = 1`
41502
+ ).get();
41503
+ return this.#limits.standardEventBytes - rowNumber(state, "total_bytes");
41504
+ };
41252
41505
  claimRuntimeDelivery = (delivery) => {
41253
41506
  const payloadBytes = new TextEncoder().encode(delivery.payload).byteLength;
41254
41507
  this.#database.exec("BEGIN IMMEDIATE");
@@ -41857,6 +42110,12 @@ var ConnectedDaemonSessionEventState = class extends DaemonSessionEventConnectio
41857
42110
  var SESSION_EVENT_REPLAY_WINDOW = 16;
41858
42111
  var SESSION_EVENT_SOURCE_REPLAY_WINDOW = 4;
41859
42112
  var SESSION_EVENT_REPLAY_BYTE_LIMIT = 32 * 1024 * 1024;
42113
+ function reservesSessionEventCapacity(event) {
42114
+ if (event.kind === SESSION_COMPLETED_KIND || event.kind === SESSION_FAILED_KIND) {
42115
+ return true;
42116
+ }
42117
+ return event.kind === AGENT_ACTIVITY_KIND && (event.activityType === "progress" || event.activityType === "reasoning") && (event.status === "completed" || event.status === "failed");
42118
+ }
41860
42119
  var InFlightSessionEvent = class {
41861
42120
  byteLength;
41862
42121
  sourceKey;
@@ -41872,6 +42131,7 @@ var DaemonSessionEventPublisher = class {
41872
42131
  #outbox;
41873
42132
  #inFlightEvents = /* @__PURE__ */ new Map();
41874
42133
  #pausedSources = /* @__PURE__ */ new Map();
42134
+ #shedEventKinds = /* @__PURE__ */ new Set();
41875
42135
  #timer;
41876
42136
  #inFlightBytes = 0;
41877
42137
  #connection = new DisconnectedDaemonSessionEventState();
@@ -41893,17 +42153,64 @@ var DaemonSessionEventPublisher = class {
41893
42153
  };
41894
42154
  recordAttempt = (sessionId, event, attemptId) => {
41895
42155
  const encoded = encodeRecordedSessionEvent(event);
41896
- if (event.kind === SESSION_COMPLETED_KIND || event.kind === SESSION_FAILED_KIND) {
41897
- this.#outbox.enqueueCritical(sessionId, encoded, attemptId);
42156
+ if (reservesSessionEventCapacity(event)) {
42157
+ this.#enqueueReserved(sessionId, encoded, attemptId, event.kind);
41898
42158
  } else {
41899
- this.#outbox.enqueue(sessionId, encoded, attemptId);
42159
+ this.#enqueueStandard(sessionId, encoded, attemptId, event.kind);
41900
42160
  }
41901
42161
  this.#publishNextBatch();
41902
42162
  };
41903
42163
  recordRuntime = (sessionId, event) => {
41904
- this.#outbox.enqueue(sessionId, encodeRecordedSessionEvent(event));
42164
+ this.#enqueueStandard(sessionId, encodeRecordedSessionEvent(event), "", event.kind);
41905
42165
  this.#publishNextBatch();
41906
42166
  };
42167
+ /**
42168
+ * Enqueue a standard event, shedding it instead of ending the daemon when the
42169
+ * durable outbox is full.
42170
+ *
42171
+ * A capacity error used to escape the coalescing timer that publishes activities,
42172
+ * so the process exited and every restart died on the same retained backlog. A full
42173
+ * outbox is a recoverable runtime condition, not a fatal one: narration increments are
42174
+ * superseded by the completed snapshot, so they are shed first, and any other streaming
42175
+ * event is shed only at the wall rather than terminating the daemon.
42176
+ */
42177
+ #enqueueStandard = (sessionId, encoded, attemptId, kind) => {
42178
+ if (kind === AGENT_ACTIVITY_NARRATION_KIND && this.#outbox.standardCapacityRemaining() <= 0) {
42179
+ this.#reportShedEvent(kind);
42180
+ return;
42181
+ }
42182
+ try {
42183
+ this.#outbox.enqueue(sessionId, encoded, attemptId);
42184
+ } catch (error62) {
42185
+ if (!(error62 instanceof SessionEventOutboxCapacityError)) {
42186
+ throw error62;
42187
+ }
42188
+ this.#reportShedEvent(kind);
42189
+ }
42190
+ };
42191
+ /**
42192
+ * Enqueue on the reserved budget, degrading to a reported drop instead of raising.
42193
+ * Streaming events are shed before this budget is reached, so a Turn's terminal
42194
+ * events and the completed snapshot that carries its narration still land; a drop
42195
+ * here is the last resort for a backlog no acknowledgement can drain.
42196
+ */
42197
+ #enqueueReserved = (sessionId, encoded, attemptId, kind) => {
42198
+ try {
42199
+ this.#outbox.enqueueCritical(sessionId, encoded, attemptId);
42200
+ } catch (error62) {
42201
+ if (!(error62 instanceof SessionEventOutboxCapacityError)) {
42202
+ throw error62;
42203
+ }
42204
+ this.#reportShedEvent(kind);
42205
+ }
42206
+ };
42207
+ #reportShedEvent = (kind) => {
42208
+ if (this.#shedEventKinds.has(kind)) {
42209
+ return;
42210
+ }
42211
+ this.#shedEventKinds.add(kind);
42212
+ console.warn(`Mobius daemon is dropping durable "${kind}" events because the Session event outbox is full`);
42213
+ };
41907
42214
  acknowledge = (acknowledgement) => {
41908
42215
  if (!this.#outbox.acknowledge(acknowledgement)) {
41909
42216
  return;
@@ -42630,6 +42937,26 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
42630
42937
  const activities = new CoalescingDaemonActivityPublisher(timer, (activity2) => {
42631
42938
  publisher.recordAttempt(command.sessionId, daemonActivity(command, activity2), attemptId);
42632
42939
  });
42940
+ const narration = new CoalescingNarrationPublisher(
42941
+ timer,
42942
+ (increment) => {
42943
+ publisher.recordAttempt(
42944
+ command.sessionId,
42945
+ {
42946
+ activityId: increment.activityId,
42947
+ activityType: increment.activityType,
42948
+ commandId: command.commandId,
42949
+ kind: AGENT_ACTIVITY_NARRATION_KIND,
42950
+ sequence: increment.sequence,
42951
+ sessionId: command.sessionId,
42952
+ text: increment.text
42953
+ },
42954
+ attemptId
42955
+ );
42956
+ },
42957
+ AGENT_ACTIVITY_COALESCING_MILLISECONDS,
42958
+ AGENT_TEXT_MAXIMUM_LENGTH
42959
+ );
42633
42960
  const text3 = new CoalescingTextPublisher(
42634
42961
  timer,
42635
42962
  (messageId, delta) => {
@@ -42734,6 +43061,10 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
42734
43061
  disposition: command.disposition,
42735
43062
  images: attachments.images,
42736
43063
  onActivity: activities.record,
43064
+ onNarration: (increment) => {
43065
+ narration.record(increment);
43066
+ return Promise.resolve();
43067
+ },
42737
43068
  onText: (delta, messageId) => {
42738
43069
  text3.record(messageId, delta);
42739
43070
  return Promise.resolve();
@@ -42747,6 +43078,7 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
42747
43078
  stopReason = result.stopReason;
42748
43079
  }
42749
43080
  text3.flush();
43081
+ narration.flush();
42750
43082
  activities.flush();
42751
43083
  publisher.recordAttempt(
42752
43084
  command.sessionId,
@@ -42766,6 +43098,7 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
42766
43098
  });
42767
43099
  } catch (error62) {
42768
43100
  text3.flush();
43101
+ narration.flush();
42769
43102
  activities.flush();
42770
43103
  audit.record({
42771
43104
  commandId: command.commandId,