@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/index.js CHANGED
@@ -20409,6 +20409,7 @@ var RUNTIME_DELIVERY_COMMITTED_KIND = "runtime.delivery.committed";
20409
20409
  var SESSION_STARTED_KIND = "session.started";
20410
20410
  var AGENT_MESSAGE_DELTA_KIND = "agent.message.delta";
20411
20411
  var AGENT_ACTIVITY_KIND = "agent.activity";
20412
+ var AGENT_ACTIVITY_NARRATION_KIND = "agent.activity.narration";
20412
20413
  var AGENT_ACTIVITY_DETAIL_LIMIT = 5e5;
20413
20414
  var AGENT_ACTIVITY_RECORDED_FIELD_LIMIT = 4e6;
20414
20415
  var AGENT_ACTIVITY_RECORDED_DETAIL_LIMIT = 6e6;
@@ -20430,6 +20431,7 @@ var MAX_PROMPT_ATTACHMENT_LENGTH = 6e6;
20430
20431
  var MAX_EVENT_TEXT_LENGTH = 1e5;
20431
20432
  var MAX_RUNTIME_DELIVERY_PAYLOAD_LENGTH = 8 * 1024 * 1024;
20432
20433
  var ACTIVITY_TYPES = /* @__PURE__ */ new Set(["plan", "progress", "reasoning", "tool"]);
20434
+ var NARRATION_ACTIVITY_TYPES = /* @__PURE__ */ new Set(["progress", "reasoning"]);
20433
20435
  var ACTIVITY_STATUSES = /* @__PURE__ */ new Set(["pending", "running", "completed", "failed"]);
20434
20436
  var TOOL_KINDS = /* @__PURE__ */ new Set([
20435
20437
  "",
@@ -20853,6 +20855,20 @@ function encodeRuntimeDeliveryReceived(message) {
20853
20855
  function encodeRuntimeDeliveryCommitted(message) {
20854
20856
  return JSON.stringify(decodeRuntimeDeliveryCommitted(JSON.stringify(message)));
20855
20857
  }
20858
+ function decodeAgentActivityNarrationEvent(encoded) {
20859
+ const value = parseJson2(encoded);
20860
+ assertExactKeys(value, ["activityId", "activityType", "commandId", "kind", "sequence", "sessionId", "text"]);
20861
+ assertKind(value, AGENT_ACTIVITY_NARRATION_KIND);
20862
+ return {
20863
+ activityId: readIdentifier(value, "activityId"),
20864
+ activityType: readAllowedString(value, "activityType", NARRATION_ACTIVITY_TYPES),
20865
+ commandId: readIdentifier(value, "commandId"),
20866
+ kind: AGENT_ACTIVITY_NARRATION_KIND,
20867
+ sequence: readSequence(value, "sequence"),
20868
+ sessionId: readIdentifier(value, "sessionId"),
20869
+ text: readText(value, "text", MAX_EVENT_TEXT_LENGTH)
20870
+ };
20871
+ }
20856
20872
 
20857
20873
  // ../protocol/src/session-history.ts
20858
20874
  var SESSION_HISTORY_CHARACTER_LIMIT = 256e3;
@@ -21201,6 +21217,8 @@ function decodeRecordedSessionEvent(encoded) {
21201
21217
  switch (kind) {
21202
21218
  case AGENT_ACTIVITY_KIND:
21203
21219
  return decodeAgentActivityEvent(encoded);
21220
+ case AGENT_ACTIVITY_NARRATION_KIND:
21221
+ return decodeAgentActivityNarrationEvent(encoded);
21204
21222
  case AGENT_CONTENT_KIND:
21205
21223
  return decodeAgentContentEvent(encoded);
21206
21224
  case AGENT_MESSAGE_DELTA_KIND:
@@ -22669,6 +22687,18 @@ var AcpConfigurationValueUnavailableError = class extends AcpExecutionError {
22669
22687
 
22670
22688
  // src/acp/activity.ts
22671
22689
  var TRUNCATION_MARKER = "\n\u2026 output truncated by Mobius";
22690
+ var AcpActivityNarration = class {
22691
+ activityId;
22692
+ activityType;
22693
+ sequence;
22694
+ text;
22695
+ constructor(activityId, activityType, sequence, text3) {
22696
+ this.activityId = activityId;
22697
+ this.activityType = activityType;
22698
+ this.sequence = sequence;
22699
+ this.text = text3;
22700
+ }
22701
+ };
22672
22702
  function isRecord3(value) {
22673
22703
  return typeof value === "object" && value !== null && !Array.isArray(value);
22674
22704
  }
@@ -23001,12 +23031,15 @@ function isProgressMessage(content3) {
23001
23031
  var AcpActivityTracker = class {
23002
23032
  #activities = /* @__PURE__ */ new Map();
23003
23033
  #identities = /* @__PURE__ */ new Map();
23034
+ #narrations = /* @__PURE__ */ new Map();
23004
23035
  #onActivity;
23036
+ #onNarration;
23005
23037
  #prepareContent;
23006
23038
  #activeNarrativeKey = "";
23007
23039
  #nextSequence = 0;
23008
- constructor(onActivity, prepareContent = (content3) => Promise.resolve(content3)) {
23040
+ constructor(onActivity, onNarration, prepareContent = (content3) => Promise.resolve(content3)) {
23009
23041
  this.#onActivity = onActivity;
23042
+ this.#onNarration = onNarration;
23010
23043
  this.#prepareContent = prepareContent;
23011
23044
  }
23012
23045
  recordNarrative = async (activityType, messageId, text3) => {
@@ -23014,26 +23047,34 @@ var AcpActivityTracker = class {
23014
23047
  if (this.#activeNarrativeKey !== key) {
23015
23048
  await this.finishNarrative();
23016
23049
  }
23017
- const previous2 = this.#activities.get(key);
23018
23050
  const identity2 = this.#identity(key);
23019
- const fullOutput = `${recordedDetail(previous2)?.output ?? previous2?.output ?? ""}${text3}`;
23020
- const activity2 = new AcpActivity(
23021
- identity2.id,
23051
+ const previous2 = this.#narrations.get(key);
23052
+ this.#narrations.set(key, {
23053
+ activityId: identity2.id,
23022
23054
  activityType,
23023
- "",
23024
- [],
23025
- "",
23026
- truncate(fullOutput, AGENT_ACTIVITY_DETAIL_LIMIT),
23027
- identity2.sequence,
23028
- "running",
23029
- activityType === "reasoning" ? "Reasoning" : "Progress update",
23030
- activityType === "reasoning" ? "think" : "",
23031
- [],
23032
- captureActivityDetail([], "", fullOutput)
23033
- );
23034
- await this.#record(key, activity2);
23055
+ output: `${previous2?.output ?? ""}${text3}`,
23056
+ sequence: identity2.sequence
23057
+ });
23058
+ if (previous2 === void 0) {
23059
+ await this.#record(key, this.#narrativeSnapshot(identity2, activityType, "", "running"));
23060
+ }
23035
23061
  this.#activeNarrativeKey = key;
23062
+ if (text3.length > 0) {
23063
+ await this.#onNarration(new AcpActivityNarration(identity2.id, activityType, identity2.sequence, text3));
23064
+ }
23036
23065
  };
23066
+ #narrativeSnapshot = (identity2, activityType, output2, status) => new AcpActivity(
23067
+ identity2.id,
23068
+ activityType,
23069
+ "",
23070
+ [],
23071
+ "",
23072
+ truncate(output2, AGENT_ACTIVITY_DETAIL_LIMIT),
23073
+ identity2.sequence,
23074
+ status,
23075
+ activityType === "reasoning" ? "Reasoning" : "Progress update",
23076
+ activityType === "reasoning" ? "think" : ""
23077
+ );
23037
23078
  recordPlan = async (plan) => {
23038
23079
  await this.finishNarrative();
23039
23080
  await this.#recordPlanEntries("plan:default", plan.entries);
@@ -23153,17 +23194,13 @@ var AcpActivityTracker = class {
23153
23194
  return;
23154
23195
  }
23155
23196
  this.#activeNarrativeKey = "";
23156
- const activity2 = this.#activities.get(key);
23157
- if (activity2 === void 0) {
23158
- return;
23159
- }
23160
- const completed = activity2.complete();
23161
- if (completed !== activity2) {
23162
- await this.#record(key, completed);
23163
- }
23197
+ await this.#completeNarrative(key);
23164
23198
  };
23165
23199
  finish = async () => {
23166
23200
  await this.finishNarrative();
23201
+ for (const key of this.#narrations.keys()) {
23202
+ await this.#completeNarrative(key);
23203
+ }
23167
23204
  const entries = [...this.#activities.entries()].sort((left, right) => left[1].sequence - right[1].sequence);
23168
23205
  for (const [key, activity2] of entries) {
23169
23206
  const completed = activity2.complete();
@@ -23172,6 +23209,34 @@ var AcpActivityTracker = class {
23172
23209
  }
23173
23210
  }
23174
23211
  };
23212
+ // Materialize a streamed narration as one completed snapshot activity. The
23213
+ // incremental events carried the text; this final event gives consumers the
23214
+ // whole narration with its terminal status, as a single bounded item.
23215
+ #completeNarrative = async (key) => {
23216
+ const narration = this.#narrations.get(key);
23217
+ if (narration === void 0) {
23218
+ return;
23219
+ }
23220
+ this.#narrations.delete(key);
23221
+ const previous2 = this.#activities.get(key);
23222
+ await this.#record(
23223
+ key,
23224
+ new AcpActivity(
23225
+ narration.activityId,
23226
+ narration.activityType,
23227
+ "",
23228
+ [],
23229
+ "",
23230
+ truncate(narration.output, AGENT_ACTIVITY_DETAIL_LIMIT),
23231
+ narration.sequence,
23232
+ "completed",
23233
+ narration.activityType === "reasoning" ? "Reasoning" : "Progress update",
23234
+ narration.activityType === "reasoning" ? "think" : "",
23235
+ previous2?.content ?? [],
23236
+ captureActivityDetail([], "", narration.output)
23237
+ )
23238
+ );
23239
+ };
23175
23240
  #identity = (key) => {
23176
23241
  const existing = this.#identities.get(key);
23177
23242
  if (existing !== void 0) {
@@ -30815,17 +30880,22 @@ var AcpHistoryReplay = class {
30815
30880
  #activities = /* @__PURE__ */ new Map();
30816
30881
  #messages = [];
30817
30882
  #turnActivityIds = /* @__PURE__ */ new Set();
30818
- #activityTracker = new AcpActivityTracker(async (activity2) => {
30819
- this.#activities.set(activity2.activityId, activity2);
30820
- this.#turnActivityIds.add(activity2.activityId);
30821
- const latest = this.#messages.at(-1);
30822
- if (latest?.role === "assistant") {
30823
- this.#messages[this.#messages.length - 1] = {
30824
- ...latest,
30825
- activityIds: [...this.#turnActivityIds]
30826
- };
30827
- }
30828
- });
30883
+ #activityTracker = new AcpActivityTracker(
30884
+ async (activity2) => {
30885
+ this.#activities.set(activity2.activityId, activity2);
30886
+ this.#turnActivityIds.add(activity2.activityId);
30887
+ const latest = this.#messages.at(-1);
30888
+ if (latest?.role === "assistant") {
30889
+ this.#messages[this.#messages.length - 1] = {
30890
+ ...latest,
30891
+ activityIds: [...this.#turnActivityIds]
30892
+ };
30893
+ }
30894
+ },
30895
+ // History replay folds each narration into its snapshot activity, so no
30896
+ // separate incremental event is produced here.
30897
+ () => Promise.resolve()
30898
+ );
30829
30899
  #lastMessageId = null;
30830
30900
  #characters = 0;
30831
30901
  #truncated = false;
@@ -31644,7 +31714,10 @@ var AcpTurnState = class {
31644
31714
  var IdleAcpTurn = class extends AcpTurnState {
31645
31715
  commandId = SESSION_CONTROL_COMMAND_ID;
31646
31716
  running = false;
31647
- activities = new AcpActivityTracker(() => Promise.resolve());
31717
+ activities = new AcpActivityTracker(
31718
+ () => Promise.resolve(),
31719
+ () => Promise.resolve()
31720
+ );
31648
31721
  onText = () => Promise.resolve();
31649
31722
  };
31650
31723
  var RunningAcpTurn = class extends AcpTurnState {
@@ -31652,10 +31725,10 @@ var RunningAcpTurn = class extends AcpTurnState {
31652
31725
  running = true;
31653
31726
  activities;
31654
31727
  onText;
31655
- constructor(commandId, onActivity, onText, prepareContent) {
31728
+ constructor(commandId, onActivity, onNarration, onText, prepareContent) {
31656
31729
  super();
31657
31730
  this.commandId = commandId;
31658
- this.activities = new AcpActivityTracker(onActivity, prepareContent);
31731
+ this.activities = new AcpActivityTracker(onActivity, onNarration ?? (() => Promise.resolve()), prepareContent);
31659
31732
  this.onText = onText;
31660
31733
  }
31661
31734
  };
@@ -32460,6 +32533,7 @@ var AcpProcessSession = class _AcpProcessSession {
32460
32533
  const running = new RunningAcpTurn(
32461
32534
  options.commandId,
32462
32535
  options.onActivity,
32536
+ options.onNarration,
32463
32537
  options.onText,
32464
32538
  this.prepareAgentContent
32465
32539
  );
@@ -34065,6 +34139,7 @@ async function runAcpPrompt(options) {
34065
34139
  commandId: crypto.randomUUID(),
34066
34140
  images: [],
34067
34141
  onActivity: options.onActivity,
34142
+ ...options.onNarration === void 0 ? {} : { onNarration: options.onNarration },
34068
34143
  onText: options.onText,
34069
34144
  prompt: options.prompt,
34070
34145
  resources: [],
@@ -34852,6 +34927,11 @@ var threadStartResponseSchema = external_exports.object({
34852
34927
  serviceTier: boundedText(256).nullish(),
34853
34928
  thread: external_exports.object({ id: boundedText(256) })
34854
34929
  });
34930
+ var threadResumeResponseSchema = external_exports.object({
34931
+ model: boundedText(256).nullish(),
34932
+ reasoningEffort: boundedText(256).nullish(),
34933
+ thread: external_exports.object({ id: boundedText(256) }).nullish()
34934
+ });
34855
34935
  var reasoningEffortOptionSchema = external_exports.object({
34856
34936
  description: boundedText(4096).nullish(),
34857
34937
  reasoningEffort: boundedText(256)
@@ -34869,6 +34949,19 @@ var modelListResponseSchema = external_exports.object({
34869
34949
  data: external_exports.array(modelSchema).max(1e3),
34870
34950
  nextCursor: boundedText(1024).nullish()
34871
34951
  });
34952
+ var threadSchema = external_exports.object({
34953
+ createdAt: external_exports.number().nullish(),
34954
+ cwd: boundedText(4096).nullish(),
34955
+ id: boundedText(256),
34956
+ name: boundedText(4096).nullish(),
34957
+ preview: boundedText(4096).nullish(),
34958
+ updatedAt: external_exports.number().nullish()
34959
+ });
34960
+ var threadListResponseSchema = external_exports.object({
34961
+ data: external_exports.array(threadSchema).max(1e4),
34962
+ nextCursor: boundedText(1024).nullish()
34963
+ });
34964
+ var turnSteerResponseSchema = external_exports.object({ turnId: boundedText(256) });
34872
34965
 
34873
34966
  // src/acp/codex/app-server-client.ts
34874
34967
  var INITIALIZE_TIMEOUT_MILLISECONDS = 3e4;
@@ -35208,6 +35301,7 @@ function agentMessageMeta(phase) {
35208
35301
  var APPROVAL_REASON_CHARACTER_LIMIT = 500;
35209
35302
  var APPROVAL_TIMEOUT_MILLISECONDS = 36e5;
35210
35303
  var CODEX_AGENT_VERSION = "0.154.0";
35304
+ var STEERING_METHOD = "_session/steering";
35211
35305
  var MODEL_SETTING_ID = "model";
35212
35306
  var REASONING_EFFORT_SETTING_ID = "reasoning_effort";
35213
35307
  var MODE_SETTING_ID = "mode";
@@ -35258,6 +35352,26 @@ function initialMode(environment) {
35258
35352
  function capitalize(value) {
35259
35353
  return value.length === 0 ? value : value.charAt(0).toUpperCase() + value.slice(1);
35260
35354
  }
35355
+ function threadTitle(thread) {
35356
+ const named = thread.name?.trim() ?? "";
35357
+ if (named.length > 0) {
35358
+ return named;
35359
+ }
35360
+ return thread.preview?.trim() ?? "";
35361
+ }
35362
+ function isoTimestamp(seconds) {
35363
+ if (seconds == null || !Number.isFinite(seconds)) {
35364
+ return null;
35365
+ }
35366
+ return new Date(seconds * 1e3).toISOString();
35367
+ }
35368
+ function steeringParams(params) {
35369
+ const prompt = typeof params === "object" && params !== null ? Reflect.get(params, "prompt") : void 0;
35370
+ if (!Array.isArray(prompt)) {
35371
+ throw new AcpExecutionError("The steering prompt is invalid", {}, "steering_failed");
35372
+ }
35373
+ return { prompt };
35374
+ }
35261
35375
  var APPROVAL_OPTIONS = Object.freeze([
35262
35376
  { kind: "allow_once", name: "Allow once", optionId: "accept" },
35263
35377
  { kind: "allow_always", name: "Allow for this session", optionId: "acceptForSession" },
@@ -35431,10 +35545,12 @@ var CodexAcpAgent = class {
35431
35545
  agentCapabilities: {
35432
35546
  loadSession: false,
35433
35547
  promptCapabilities: { embeddedContext: true, image: true },
35434
- sessionCapabilities: { close: {} }
35548
+ sessionCapabilities: { close: {}, delete: {}, list: {}, resume: {} }
35435
35549
  },
35436
35550
  agentInfo: { name: "Codex", version: CODEX_AGENT_VERSION },
35437
35551
  authMethods: [],
35552
+ // Mobius reads this to decide whether mid-turn steering can be attempted at all.
35553
+ _meta: { steering: { supported: true } },
35438
35554
  protocolVersion: PROTOCOL_VERSION2
35439
35555
  })).onRequest(methods4.agent.session.new, async (context) => {
35440
35556
  const created = threadStartResponseSchema.parse(
@@ -35451,6 +35567,54 @@ var CodexAcpAgent = class {
35451
35567
  model: created.model ?? ""
35452
35568
  };
35453
35569
  return { configOptions: this.#configOptions(), sessionId: created.thread.id };
35570
+ }).onRequest(methods4.agent.session.resume, async (context) => {
35571
+ const resumed = threadResumeResponseSchema.parse(
35572
+ await this.#appServer.request(
35573
+ "thread/resume",
35574
+ { cwd: context.params.cwd, threadId: context.params.sessionId },
35575
+ AbortSignal.any([context.signal, AbortSignal.timeout(APPROVAL_TIMEOUT_MILLISECONDS)])
35576
+ )
35577
+ );
35578
+ if (resumed.thread == null) {
35579
+ throw new AcpExecutionError(
35580
+ "Codex no longer has the native session this conversation belongs to",
35581
+ {},
35582
+ "session_restore_unsupported"
35583
+ );
35584
+ }
35585
+ this.#nativeSessionId = resumed.thread.id;
35586
+ this.#selection = {
35587
+ ...this.#selection,
35588
+ effort: resumed.reasoningEffort ?? this.#selection.effort,
35589
+ model: resumed.model ?? this.#selection.model
35590
+ };
35591
+ return { configOptions: this.#configOptions() };
35592
+ }).onRequest(methods4.agent.session.list, async (context) => {
35593
+ const listed = threadListResponseSchema.parse(
35594
+ await this.#appServer.request(
35595
+ "thread/list",
35596
+ context.params.cursor === void 0 || context.params.cursor === null ? {} : { cursor: context.params.cursor },
35597
+ AbortSignal.any([context.signal, AbortSignal.timeout(APPROVAL_TIMEOUT_MILLISECONDS)])
35598
+ )
35599
+ );
35600
+ return {
35601
+ nextCursor: listed.nextCursor ?? null,
35602
+ sessions: listed.data.map((thread) => ({
35603
+ // The thread id is a UUID, which satisfies the native session id contract.
35604
+ additionalDirectories: [],
35605
+ cwd: thread.cwd ?? "",
35606
+ sessionId: thread.id,
35607
+ title: threadTitle(thread),
35608
+ updatedAt: isoTimestamp(thread.updatedAt)
35609
+ }))
35610
+ };
35611
+ }).onRequest(methods4.agent.session.delete, async (context) => {
35612
+ await this.#appServer.request(
35613
+ "thread/archive",
35614
+ { threadId: context.params.sessionId },
35615
+ AbortSignal.any([context.signal, AbortSignal.timeout(APPROVAL_TIMEOUT_MILLISECONDS)])
35616
+ );
35617
+ return {};
35454
35618
  }).onRequest(methods4.agent.session.setConfigOption, async (context) => {
35455
35619
  this.#applySelection(context.params.configId, context.params.value);
35456
35620
  return { configOptions: this.#configOptions() };
@@ -35459,6 +35623,30 @@ var CodexAcpAgent = class {
35459
35623
  return {};
35460
35624
  }).onRequest(methods4.agent.session.prompt, async (context) => {
35461
35625
  return await this.#runTurn(promptInput(context.params.prompt), context.signal);
35626
+ }).onRequest(STEERING_METHOD, steeringParams, async (context) => {
35627
+ const turn = this.#turn;
35628
+ if (turn === null || turn.turn.id.length === 0) {
35629
+ return { outcome: "promptRequired" };
35630
+ }
35631
+ try {
35632
+ const steered = turnSteerResponseSchema.parse(
35633
+ await this.#appServer.request(
35634
+ "turn/steer",
35635
+ {
35636
+ expectedTurnId: turn.turn.id,
35637
+ input: promptInput(context.params.prompt),
35638
+ threadId: this.#nativeSessionId
35639
+ },
35640
+ AbortSignal.any([context.signal, AbortSignal.timeout(APPROVAL_TIMEOUT_MILLISECONDS)])
35641
+ )
35642
+ );
35643
+ return { outcome: steered.turnId === turn.turn.id ? "injected" : "startedNewTurn" };
35644
+ } catch (error62) {
35645
+ if (error62 instanceof CodexAppServerError) {
35646
+ return { outcome: "promptRequired" };
35647
+ }
35648
+ throw error62;
35649
+ }
35462
35650
  }).onRequest(methods4.agent.session.close, async () => {
35463
35651
  await this.#interruptTurn();
35464
35652
  }).onNotification(methods4.agent.session.cancel, async () => {
@@ -39437,7 +39625,7 @@ var responseSchema = external_exports.union([
39437
39625
  external_exports.object({ id: external_exports.number(), result: external_exports.unknown() }),
39438
39626
  external_exports.object({ method: external_exports.string() })
39439
39627
  ]);
39440
- var threadSchema = external_exports.object({
39628
+ var threadSchema2 = external_exports.object({
39441
39629
  thread: external_exports.object({
39442
39630
  id: nativeSessionIdSchema,
39443
39631
  cwd: external_exports.string().min(1).max(2048).refine((path2) => !path2.includes("\0"))
@@ -39741,7 +39929,7 @@ async function readCodexHistoryWithOptions(agent, cwd, nativeSessionId, signal,
39741
39929
  });
39742
39930
  break;
39743
39931
  case "metadata": {
39744
- const { thread } = threadSchema.parse(message.result);
39932
+ const { thread } = threadSchema2.parse(message.result);
39745
39933
  state = { kind: "turns", requestId: 3, thread };
39746
39934
  send2({
39747
39935
  id: state.requestId,
@@ -40451,6 +40639,59 @@ async function resolvePromptArtifacts(config2, command, signal) {
40451
40639
  return new ResolvedPromptArtifacts(images, resources);
40452
40640
  }
40453
40641
 
40642
+ // src/relay-connection/coalescing-narration-publisher.ts
40643
+ var CoalescingNarrationPublisher = class {
40644
+ #coalescingMilliseconds;
40645
+ #maximumTextLength;
40646
+ #publish;
40647
+ #timer;
40648
+ #pending = /* @__PURE__ */ new Map();
40649
+ #scheduled = null;
40650
+ constructor(timer, publish, coalescingMilliseconds, maximumTextLength) {
40651
+ this.#publish = publish;
40652
+ this.#timer = timer;
40653
+ this.#coalescingMilliseconds = coalescingMilliseconds;
40654
+ this.#maximumTextLength = maximumTextLength;
40655
+ }
40656
+ /** Emit every buffered increment now, cancelling the pending flush. */
40657
+ flush = () => {
40658
+ this.#scheduled?.cancel();
40659
+ this.#scheduled = null;
40660
+ const increments = [...this.#pending.entries()].map(
40661
+ ([activityId, pending]) => ({
40662
+ activityId,
40663
+ activityType: pending.activityType,
40664
+ sequence: pending.sequence,
40665
+ text: pending.text
40666
+ })
40667
+ );
40668
+ this.#pending.clear();
40669
+ for (const increment of increments) {
40670
+ this.#publish(increment);
40671
+ }
40672
+ };
40673
+ /**
40674
+ * Buffer an increment, emitting the buffered text when it would exceed the
40675
+ * protocol's per-event text limit so no event is rejected by the codec.
40676
+ */
40677
+ record = (increment) => {
40678
+ if (increment.text.length === 0) {
40679
+ return;
40680
+ }
40681
+ const previous2 = this.#pending.get(increment.activityId);
40682
+ if (previous2 !== void 0 && previous2.text.length + increment.text.length > this.#maximumTextLength) {
40683
+ this.flush();
40684
+ }
40685
+ const current = this.#pending.get(increment.activityId);
40686
+ this.#pending.set(increment.activityId, {
40687
+ activityType: increment.activityType,
40688
+ sequence: increment.sequence,
40689
+ text: `${current?.text ?? ""}${increment.text}`
40690
+ });
40691
+ this.#scheduled ??= this.#timer.schedule(this.flush, this.#coalescingMilliseconds);
40692
+ };
40693
+ };
40694
+
40454
40695
  // src/relay-connection/coalescing-text-publisher.ts
40455
40696
  var CoalescingTextPublisher = class {
40456
40697
  #coalescingMilliseconds;
@@ -41168,6 +41409,19 @@ var SessionEventOutbox = class {
41168
41409
  return this.#enqueueBounded(sessionId, payload, attemptId ?? "", this.#limits.standardEventBytes);
41169
41410
  };
41170
41411
  enqueueCritical = (sessionId, payload, attemptId = "") => this.#enqueueBounded(sessionId, payload, attemptId, this.#limits.criticalEventBytes);
41412
+ /**
41413
+ * Bytes still available to standard Session events. The daemon uses this to shed
41414
+ * superseded streaming events instead of filling the durable outbox, so a long Turn
41415
+ * behind a slow Relay cannot make the next enqueue throw.
41416
+ */
41417
+ standardCapacityRemaining = () => {
41418
+ const state = this.#database.prepare(
41419
+ `SELECT total_bytes
41420
+ FROM relay_session_event_outbox_state
41421
+ WHERE singleton = 1`
41422
+ ).get();
41423
+ return this.#limits.standardEventBytes - rowNumber(state, "total_bytes");
41424
+ };
41171
41425
  claimRuntimeDelivery = (delivery) => {
41172
41426
  const payloadBytes = new TextEncoder().encode(delivery.payload).byteLength;
41173
41427
  this.#database.exec("BEGIN IMMEDIATE");
@@ -41776,6 +42030,12 @@ var ConnectedDaemonSessionEventState = class extends DaemonSessionEventConnectio
41776
42030
  var SESSION_EVENT_REPLAY_WINDOW = 16;
41777
42031
  var SESSION_EVENT_SOURCE_REPLAY_WINDOW = 4;
41778
42032
  var SESSION_EVENT_REPLAY_BYTE_LIMIT = 32 * 1024 * 1024;
42033
+ function reservesSessionEventCapacity(event) {
42034
+ if (event.kind === SESSION_COMPLETED_KIND || event.kind === SESSION_FAILED_KIND) {
42035
+ return true;
42036
+ }
42037
+ return event.kind === AGENT_ACTIVITY_KIND && (event.activityType === "progress" || event.activityType === "reasoning") && (event.status === "completed" || event.status === "failed");
42038
+ }
41779
42039
  var InFlightSessionEvent = class {
41780
42040
  byteLength;
41781
42041
  sourceKey;
@@ -41791,6 +42051,7 @@ var DaemonSessionEventPublisher = class {
41791
42051
  #outbox;
41792
42052
  #inFlightEvents = /* @__PURE__ */ new Map();
41793
42053
  #pausedSources = /* @__PURE__ */ new Map();
42054
+ #shedEventKinds = /* @__PURE__ */ new Set();
41794
42055
  #timer;
41795
42056
  #inFlightBytes = 0;
41796
42057
  #connection = new DisconnectedDaemonSessionEventState();
@@ -41812,17 +42073,64 @@ var DaemonSessionEventPublisher = class {
41812
42073
  };
41813
42074
  recordAttempt = (sessionId, event, attemptId) => {
41814
42075
  const encoded = encodeRecordedSessionEvent(event);
41815
- if (event.kind === SESSION_COMPLETED_KIND || event.kind === SESSION_FAILED_KIND) {
41816
- this.#outbox.enqueueCritical(sessionId, encoded, attemptId);
42076
+ if (reservesSessionEventCapacity(event)) {
42077
+ this.#enqueueReserved(sessionId, encoded, attemptId, event.kind);
41817
42078
  } else {
41818
- this.#outbox.enqueue(sessionId, encoded, attemptId);
42079
+ this.#enqueueStandard(sessionId, encoded, attemptId, event.kind);
41819
42080
  }
41820
42081
  this.#publishNextBatch();
41821
42082
  };
41822
42083
  recordRuntime = (sessionId, event) => {
41823
- this.#outbox.enqueue(sessionId, encodeRecordedSessionEvent(event));
42084
+ this.#enqueueStandard(sessionId, encodeRecordedSessionEvent(event), "", event.kind);
41824
42085
  this.#publishNextBatch();
41825
42086
  };
42087
+ /**
42088
+ * Enqueue a standard event, shedding it instead of ending the daemon when the
42089
+ * durable outbox is full.
42090
+ *
42091
+ * A capacity error used to escape the coalescing timer that publishes activities,
42092
+ * so the process exited and every restart died on the same retained backlog. A full
42093
+ * outbox is a recoverable runtime condition, not a fatal one: narration increments are
42094
+ * superseded by the completed snapshot, so they are shed first, and any other streaming
42095
+ * event is shed only at the wall rather than terminating the daemon.
42096
+ */
42097
+ #enqueueStandard = (sessionId, encoded, attemptId, kind) => {
42098
+ if (kind === AGENT_ACTIVITY_NARRATION_KIND && this.#outbox.standardCapacityRemaining() <= 0) {
42099
+ this.#reportShedEvent(kind);
42100
+ return;
42101
+ }
42102
+ try {
42103
+ this.#outbox.enqueue(sessionId, encoded, attemptId);
42104
+ } catch (error62) {
42105
+ if (!(error62 instanceof SessionEventOutboxCapacityError)) {
42106
+ throw error62;
42107
+ }
42108
+ this.#reportShedEvent(kind);
42109
+ }
42110
+ };
42111
+ /**
42112
+ * Enqueue on the reserved budget, degrading to a reported drop instead of raising.
42113
+ * Streaming events are shed before this budget is reached, so a Turn's terminal
42114
+ * events and the completed snapshot that carries its narration still land; a drop
42115
+ * here is the last resort for a backlog no acknowledgement can drain.
42116
+ */
42117
+ #enqueueReserved = (sessionId, encoded, attemptId, kind) => {
42118
+ try {
42119
+ this.#outbox.enqueueCritical(sessionId, encoded, attemptId);
42120
+ } catch (error62) {
42121
+ if (!(error62 instanceof SessionEventOutboxCapacityError)) {
42122
+ throw error62;
42123
+ }
42124
+ this.#reportShedEvent(kind);
42125
+ }
42126
+ };
42127
+ #reportShedEvent = (kind) => {
42128
+ if (this.#shedEventKinds.has(kind)) {
42129
+ return;
42130
+ }
42131
+ this.#shedEventKinds.add(kind);
42132
+ console.warn(`Mobius daemon is dropping durable "${kind}" events because the Session event outbox is full`);
42133
+ };
41826
42134
  acknowledge = (acknowledgement) => {
41827
42135
  if (!this.#outbox.acknowledge(acknowledgement)) {
41828
42136
  return;
@@ -42549,6 +42857,26 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
42549
42857
  const activities = new CoalescingDaemonActivityPublisher(timer, (activity2) => {
42550
42858
  publisher.recordAttempt(command.sessionId, daemonActivity(command, activity2), attemptId);
42551
42859
  });
42860
+ const narration = new CoalescingNarrationPublisher(
42861
+ timer,
42862
+ (increment) => {
42863
+ publisher.recordAttempt(
42864
+ command.sessionId,
42865
+ {
42866
+ activityId: increment.activityId,
42867
+ activityType: increment.activityType,
42868
+ commandId: command.commandId,
42869
+ kind: AGENT_ACTIVITY_NARRATION_KIND,
42870
+ sequence: increment.sequence,
42871
+ sessionId: command.sessionId,
42872
+ text: increment.text
42873
+ },
42874
+ attemptId
42875
+ );
42876
+ },
42877
+ AGENT_ACTIVITY_COALESCING_MILLISECONDS,
42878
+ AGENT_TEXT_MAXIMUM_LENGTH
42879
+ );
42552
42880
  const text3 = new CoalescingTextPublisher(
42553
42881
  timer,
42554
42882
  (messageId, delta) => {
@@ -42653,6 +42981,10 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
42653
42981
  disposition: command.disposition,
42654
42982
  images: attachments.images,
42655
42983
  onActivity: activities.record,
42984
+ onNarration: (increment) => {
42985
+ narration.record(increment);
42986
+ return Promise.resolve();
42987
+ },
42656
42988
  onText: (delta, messageId) => {
42657
42989
  text3.record(messageId, delta);
42658
42990
  return Promise.resolve();
@@ -42666,6 +42998,7 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
42666
42998
  stopReason = result.stopReason;
42667
42999
  }
42668
43000
  text3.flush();
43001
+ narration.flush();
42669
43002
  activities.flush();
42670
43003
  publisher.recordAttempt(
42671
43004
  command.sessionId,
@@ -42685,6 +43018,7 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
42685
43018
  });
42686
43019
  } catch (error62) {
42687
43020
  text3.flush();
43021
+ narration.flush();
42688
43022
  activities.flush();
42689
43023
  audit.record({
42690
43024
  commandId: command.commandId,