@moxt-ai/mobius 0.0.113 → 0.0.116

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/acp/codex/agent.d.ts.map +1 -1
  2. package/dist/acp/codex/agent.js +14 -1
  3. package/dist/acp/codex/agent.js.map +1 -1
  4. package/dist/acp/codex/items.d.ts +2 -0
  5. package/dist/acp/codex/items.d.ts.map +1 -1
  6. package/dist/acp/codex/items.js +19 -0
  7. package/dist/acp/codex/items.js.map +1 -1
  8. package/dist/cli.js +306 -260
  9. package/dist/cli.js.map +4 -4
  10. package/dist/daemon-active-turn.d.ts +33 -0
  11. package/dist/daemon-active-turn.d.ts.map +1 -0
  12. package/dist/daemon-active-turn.js +152 -0
  13. package/dist/daemon-active-turn.js.map +1 -0
  14. package/dist/daemon-session-commands.d.ts +14 -7
  15. package/dist/daemon-session-commands.d.ts.map +1 -1
  16. package/dist/daemon-session-commands.js +18 -21
  17. package/dist/daemon-session-commands.js.map +1 -1
  18. package/dist/index.js +305 -259
  19. package/dist/index.js.map +4 -4
  20. package/dist/native-sessions/live-history-page.d.ts +7 -2
  21. package/dist/native-sessions/live-history-page.d.ts.map +1 -1
  22. package/dist/native-sessions/live-history-page.js +87 -1
  23. package/dist/native-sessions/live-history-page.js.map +1 -1
  24. package/dist/relay-connection/diagnostics.d.ts +0 -5
  25. package/dist/relay-connection/diagnostics.d.ts.map +1 -1
  26. package/dist/relay-connection/diagnostics.js +0 -14
  27. package/dist/relay-connection/diagnostics.js.map +1 -1
  28. package/dist/run-daemon.d.ts.map +1 -1
  29. package/dist/run-daemon.js +18 -31
  30. package/dist/run-daemon.js.map +1 -1
  31. package/dist/runtime.js +307 -261
  32. package/dist/runtime.js.map +4 -4
  33. package/package.json +1 -1
  34. package/dist/daemon-turn-reconciliation.d.ts +0 -44
  35. package/dist/daemon-turn-reconciliation.d.ts.map +0 -1
  36. package/dist/daemon-turn-reconciliation.js +0 -195
  37. package/dist/daemon-turn-reconciliation.js.map +0 -1
package/dist/cli.js CHANGED
@@ -3381,7 +3381,7 @@ var program = new Command();
3381
3381
  // package.json
3382
3382
  var package_default = {
3383
3383
  name: "@moxt-ai/mobius",
3384
- version: "0.0.113",
3384
+ version: "0.0.116",
3385
3385
  description: "Mobius CLI for pairing and running local AI agent services.",
3386
3386
  type: "module",
3387
3387
  bin: {
@@ -24954,6 +24954,18 @@ var CODEX_META_KEY = "codex";
24954
24954
  function truncate(value, limit) {
24955
24955
  return value.length <= limit ? value : value.slice(0, limit);
24956
24956
  }
24957
+ function boundedParagraphs(values, limit) {
24958
+ let text = "";
24959
+ for (const value of values) {
24960
+ const separator = text.length === 0 ? "" : "\n\n";
24961
+ const remaining = limit - text.length;
24962
+ if (remaining <= separator.length) {
24963
+ break;
24964
+ }
24965
+ text += `${separator}${value.slice(0, remaining - separator.length)}`;
24966
+ }
24967
+ return text;
24968
+ }
24957
24969
  function textContent(text) {
24958
24970
  const block = { text: truncate(text, TOOL_OUTPUT_CHARACTER_LIMIT), type: "text" };
24959
24971
  return { content: block, type: "content" };
@@ -25071,6 +25083,12 @@ function decodeThreadItem(value) {
25071
25083
  const decoded = threadItemSchema.safeParse(value);
25072
25084
  return decoded.success ? decoded.data : null;
25073
25085
  }
25086
+ function reasoningText(item) {
25087
+ if (item.type !== "reasoning") {
25088
+ return null;
25089
+ }
25090
+ return boundedParagraphs(item.summary.length > 0 ? item.summary : item.content, TOOL_OUTPUT_CHARACTER_LIMIT);
25091
+ }
25074
25092
  function agentMessageMeta(phase) {
25075
25093
  if (phase == null) {
25076
25094
  return null;
@@ -25839,6 +25857,19 @@ var CodexAcpAgent = class {
25839
25857
  });
25840
25858
  return;
25841
25859
  }
25860
+ const reasoning = reasoningText(item);
25861
+ if (reasoning !== null) {
25862
+ if (method === "item/completed" && reasoning.length > 0) {
25863
+ await this.#enqueue(async () => {
25864
+ await this.#emit({
25865
+ content: { text: reasoning, type: "text" },
25866
+ messageId: item.id,
25867
+ sessionUpdate: "agent_thought_chunk"
25868
+ });
25869
+ });
25870
+ }
25871
+ return;
25872
+ }
25842
25873
  const update = toolCallUpdate(item, method === "item/completed" ? "completed" : "started");
25843
25874
  if (update !== null) {
25844
25875
  await this.#enqueue(async () => {
@@ -29232,6 +29263,19 @@ var envelope = {
29232
29263
  requestId: identifierStringSchema,
29233
29264
  sessionId: identifierStringSchema
29234
29265
  };
29266
+ var activeTurnActivitySchema = external_exports.strictObject({
29267
+ activityId: external_exports.string().min(1).max(128),
29268
+ activityType: external_exports.string().min(1).max(128),
29269
+ content: external_exports.array(displayContentSchema).max(100).readonly(),
29270
+ input: external_exports.string().max(1e5),
29271
+ locations: external_exports.array(external_exports.string().min(1).max(2048)).max(100).readonly(),
29272
+ name: external_exports.string().max(128),
29273
+ output: external_exports.string().max(1e5),
29274
+ sequence: external_exports.number().int().nonnegative(),
29275
+ status: external_exports.string().min(1).max(64),
29276
+ title: external_exports.string().max(500),
29277
+ toolKind: external_exports.string().max(64)
29278
+ }).readonly();
29235
29279
  var identity = {
29236
29280
  ...envelope,
29237
29281
  kind: external_exports.literal(NATIVE_SESSION_REQUEST_KIND),
@@ -29307,7 +29351,9 @@ var nativeSessionResultSchema = external_exports.discriminatedUnion("action", [
29307
29351
  action: external_exports.literal("active-turn"),
29308
29352
  targetSessionId: identifierStringSchema,
29309
29353
  turn: external_exports.strictObject({
29354
+ activities: external_exports.array(activeTurnActivitySchema).max(100).readonly(),
29310
29355
  commandId: identifierStringSchema,
29356
+ content: external_exports.array(displayContentSchema).max(100).readonly(),
29311
29357
  prompt: external_exports.string().max(1e5),
29312
29358
  text: external_exports.string().max(ACTIVE_TURN_TEXT_LIMIT),
29313
29359
  truncated: external_exports.boolean(),
@@ -35331,7 +35377,10 @@ function liveHistoryCoveredTurnRanges(history) {
35331
35377
  }
35332
35378
  return ranges;
35333
35379
  }
35334
- function paginateLiveSessionHistory(history, sessionId, cursor, limit) {
35380
+ function historyMessageCharacters(message) {
35381
+ return message.text.length + (message.role === "assistant" ? JSON.stringify(message.activities).length + JSON.stringify(message.content).length : 0);
35382
+ }
35383
+ function paginateAcpSessionHistory(history, sessionId, cursor, limit) {
35335
35384
  if (history.status === "unavailable") {
35336
35385
  if (cursor !== null) {
35337
35386
  throw new AcpExecutionError("Unavailable native Session history has no cursor", {}, "invalid_cursor");
@@ -35357,6 +35406,80 @@ function paginateLiveSessionHistory(history, sessionId, cursor, limit) {
35357
35406
  truncated: history.truncated
35358
35407
  };
35359
35408
  }
35409
+ function paginateLiveSessionHistory(history, activeTurn, sessionId, cursor, limit) {
35410
+ if (activeTurn === null || cursor !== null) {
35411
+ return paginateAcpSessionHistory(history, sessionId, cursor, limit);
35412
+ }
35413
+ const activeMessageOverhead = 4;
35414
+ const activeStructuredCharacters = JSON.stringify(activeTurn.activities).length + JSON.stringify(activeTurn.content).length;
35415
+ const maximumActiveTextLength = Math.max(
35416
+ 0,
35417
+ SESSION_HISTORY_CHARACTER_LIMIT - activeTurn.prompt.length - activeStructuredCharacters - activeMessageOverhead
35418
+ );
35419
+ const activeText = activeTurn.text.slice(-maximumActiveTextLength);
35420
+ const completeActiveMessages = [
35421
+ { role: "user", text: activeTurn.prompt },
35422
+ {
35423
+ activities: activeTurn.activities,
35424
+ content: activeTurn.content,
35425
+ role: "assistant",
35426
+ text: activeText
35427
+ }
35428
+ ];
35429
+ if (history.status === "unavailable") {
35430
+ return {
35431
+ coveredCommandIds: [],
35432
+ coveredMessageIds: [],
35433
+ messages: completeActiveMessages,
35434
+ nextCursor: null,
35435
+ status: "available",
35436
+ truncated: activeTurn.truncated || activeText.length !== activeTurn.text.length
35437
+ };
35438
+ }
35439
+ const latestNativeMessage = history.messages.at(-1);
35440
+ const activeMessages = latestNativeMessage?.role === "user" && latestNativeMessage.text === activeTurn.prompt ? completeActiveMessages.slice(1) : completeActiveMessages;
35441
+ let historicalMessageCount = 0;
35442
+ let remainingCharacters = SESSION_HISTORY_CHARACTER_LIMIT - activeText.length - activeMessageOverhead - activeStructuredCharacters - (activeMessages.length === completeActiveMessages.length ? activeTurn.prompt.length : 0);
35443
+ const historicalMessageLimit = Math.max(0, limit - activeMessages.length);
35444
+ for (let index = history.messages.length - 1; index >= 0 && historicalMessageCount < historicalMessageLimit; index -= 1) {
35445
+ const message = history.messages[index];
35446
+ if (message === void 0) {
35447
+ break;
35448
+ }
35449
+ const characters = historyMessageCharacters(message);
35450
+ if (characters > remainingCharacters) {
35451
+ break;
35452
+ }
35453
+ historicalMessageCount += 1;
35454
+ remainingCharacters -= characters;
35455
+ }
35456
+ const page = historicalMessageCount === 0 ? {
35457
+ coveredCommandIds: [],
35458
+ coveredMessageIds: [],
35459
+ messages: [],
35460
+ nextCursor: history.messages.length === 0 ? null : liveHistoryCursor(sessionId, history.messages.length),
35461
+ status: "available",
35462
+ truncated: history.truncated
35463
+ } : paginateAcpSessionHistory(history, sessionId, null, historicalMessageCount);
35464
+ return {
35465
+ ...page,
35466
+ messages: [...page.messages, ...activeMessages],
35467
+ truncated: page.truncated || activeTurn.truncated || activeText.length !== activeTurn.text.length
35468
+ };
35469
+ }
35470
+ function mergeLiveSessionHistory(history, activeTurn, sessionId) {
35471
+ const page = paginateLiveSessionHistory(history, activeTurn, sessionId, null, 1e3);
35472
+ if (page.status === "unavailable") {
35473
+ return { cause: page.cause, status: "unavailable" };
35474
+ }
35475
+ return {
35476
+ coveredCommandIds: page.coveredCommandIds,
35477
+ coveredMessageIds: page.coveredMessageIds,
35478
+ messages: page.messages,
35479
+ status: "available",
35480
+ truncated: page.truncated
35481
+ };
35482
+ }
35360
35483
 
35361
35484
  // src/prompt-artifact-resolver.ts
35362
35485
  import { createHash as createHash3 } from "node:crypto";
@@ -35988,7 +36111,7 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
35988
36111
  reportOperationFailure(socket, command.requestId, command.sessionId, error62, metrics.snapshot());
35989
36112
  }
35990
36113
  }
35991
- async function executeSessionLiveHistoryLoad(socket, command, config2, directories, audit, sessions, signal) {
36114
+ async function executeSessionLiveHistoryLoad(socket, command, config2, directories, audit, sessions, activeTurn, signal) {
35992
36115
  try {
35993
36116
  const resolved = await resolveSessionDirectories(
35994
36117
  directories,
@@ -36005,13 +36128,14 @@ async function executeSessionLiveHistoryLoad(socket, command, config2, directori
36005
36128
  signal
36006
36129
  });
36007
36130
  signal.throwIfAborted();
36131
+ const mergedHistory = mergeLiveSessionHistory(history, activeTurn(command.sessionId), command.sessionId);
36008
36132
  audit.record({
36009
36133
  commandId: command.requestId,
36010
36134
  event: "session_history_loaded",
36011
36135
  sessionId: command.sessionId
36012
36136
  });
36013
36137
  send(socket, {
36014
- history,
36138
+ history: mergedHistory,
36015
36139
  kind: "session.live-history.loaded",
36016
36140
  requestId: command.requestId,
36017
36141
  sessionId: command.sessionId
@@ -36037,7 +36161,7 @@ async function executeSessionLiveHistoryLoad(socket, command, config2, directori
36037
36161
  });
36038
36162
  }
36039
36163
  }
36040
- async function executeSessionLiveHistoryPageLoad(socket, command, config2, directories, audit, sessions, signal) {
36164
+ async function executeSessionLiveHistoryPageLoad(socket, command, config2, directories, audit, sessions, activeTurn, signal) {
36041
36165
  try {
36042
36166
  const resolved = await resolveSessionDirectories(
36043
36167
  directories,
@@ -36054,7 +36178,13 @@ async function executeSessionLiveHistoryPageLoad(socket, command, config2, direc
36054
36178
  signal
36055
36179
  });
36056
36180
  signal.throwIfAborted();
36057
- const page = paginateLiveSessionHistory(history, command.sessionId, command.cursor, command.limit);
36181
+ const page = paginateLiveSessionHistory(
36182
+ history,
36183
+ activeTurn(command.sessionId),
36184
+ command.sessionId,
36185
+ command.cursor,
36186
+ command.limit
36187
+ );
36058
36188
  audit.record({
36059
36189
  commandId: command.requestId,
36060
36190
  event: "session_history_loaded",
@@ -36127,14 +36257,11 @@ async function executeSessionConfigure(publisher, socket, command, config2, dire
36127
36257
  reportOperationFailure(socket, command.requestId, command.sessionId, error62);
36128
36258
  }
36129
36259
  }
36130
- async function executePrompt(operations, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, acknowledgeQueued, waitForSessionAvailability, timer, signal, recordLiveText, cancellationRequested) {
36131
- const activities = new CoalescingDaemonActivityPublisher(timer, (activity2) => {
36132
- publisher.publish(command.sessionId, daemonActivity(command, activity2));
36133
- });
36260
+ async function executePrompt(operations, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, acknowledgeQueued, waitForSessionAvailability, timer, signal, recordLiveEvent, cancellationRequested) {
36134
36261
  const narration = new CoalescingNarrationPublisher(
36135
36262
  timer,
36136
36263
  (increment) => {
36137
- publisher.publish(command.sessionId, {
36264
+ const event = {
36138
36265
  activityId: increment.activityId,
36139
36266
  activityType: increment.activityType,
36140
36267
  commandId: command.commandId,
@@ -36142,24 +36269,26 @@ async function executePrompt(operations, publisher, command, config2, directorie
36142
36269
  sequence: increment.sequence,
36143
36270
  sessionId: command.sessionId,
36144
36271
  text: increment.text
36145
- });
36272
+ };
36273
+ publisher.publish(command.sessionId, recordLiveEvent(event));
36146
36274
  },
36147
36275
  AGENT_ACTIVITY_COALESCING_MILLISECONDS,
36148
36276
  AGENT_TEXT_MAXIMUM_LENGTH
36149
36277
  );
36278
+ const activities = new CoalescingDaemonActivityPublisher(timer, (activity2) => {
36279
+ if (activity2.status !== "pending" && activity2.status !== "running") {
36280
+ narration.flush();
36281
+ }
36282
+ const event = daemonActivity(command, activity2);
36283
+ publisher.publish(command.sessionId, recordLiveEvent(event));
36284
+ });
36150
36285
  const text = new CoalescingTextPublisher(
36151
36286
  timer,
36152
36287
  (messageId, delta) => {
36153
- const stream = recordLiveText(delta);
36154
- publisher.publish(command.sessionId, {
36155
- commandId: command.commandId,
36156
- epoch: stream.epoch,
36157
- kind: AGENT_MESSAGE_DELTA_KIND,
36158
- messageId,
36159
- sequence: stream.sequence,
36160
- sessionId: command.sessionId,
36161
- text: delta
36162
- });
36288
+ publisher.publish(
36289
+ command.sessionId,
36290
+ recordLiveEvent({ kind: AGENT_MESSAGE_DELTA_KIND, messageId, text: delta })
36291
+ );
36163
36292
  },
36164
36293
  AGENT_TEXT_COALESCING_MILLISECONDS,
36165
36294
  AGENT_TEXT_MAXIMUM_LENGTH
@@ -37628,6 +37757,144 @@ var WorkspaceDirectoryService = class {
37628
37757
  };
37629
37758
  };
37630
37759
 
37760
+ // src/daemon-active-turn.ts
37761
+ import { randomUUID as randomUUID3 } from "node:crypto";
37762
+ var ActiveDaemonTurn = class {
37763
+ attemptId;
37764
+ command;
37765
+ #controller;
37766
+ #finished = Promise.withResolvers();
37767
+ #cancellationRequested = false;
37768
+ #dispatch;
37769
+ #text = "";
37770
+ #activities = /* @__PURE__ */ new Map();
37771
+ #content = /* @__PURE__ */ new Map();
37772
+ #truncated = false;
37773
+ #sequence = 0;
37774
+ #interaction = null;
37775
+ #epoch = decodeIdentifier(randomUUID3());
37776
+ constructor(command, attemptId) {
37777
+ this.attemptId = attemptId;
37778
+ this.command = command;
37779
+ this.#controller = new AbortController();
37780
+ this.#dispatch = command.disposition === SessionPromptDisposition.Queue ? { kind: "queued", promotion: Promise.withResolvers() } : { kind: "pending" };
37781
+ }
37782
+ abortDaemon = () => {
37783
+ this.#controller.abort();
37784
+ };
37785
+ finish = () => this.#finished.resolve();
37786
+ accept = () => {
37787
+ this.#dispatch = { kind: "accepted" };
37788
+ return { epoch: this.#epoch, sequence: 0 };
37789
+ };
37790
+ promoteQueuedPrompt = (command) => {
37791
+ if (command.commandId !== this.command.commandId || command.sessionId !== this.command.sessionId || this.#dispatch.kind !== "queued") {
37792
+ return false;
37793
+ }
37794
+ const promotion = this.#dispatch.promotion;
37795
+ this.#dispatch = { kind: "promoted" };
37796
+ promotion.resolve();
37797
+ return true;
37798
+ };
37799
+ queuePromotion = () => {
37800
+ if (this.#dispatch.kind === "queued") {
37801
+ return this.#dispatch.promotion.promise;
37802
+ }
37803
+ return this.#dispatch.kind === "promoted" ? Promise.resolve() : null;
37804
+ };
37805
+ effectiveDisposition = () => this.#dispatch.kind === "promoted" ? SessionPromptDisposition.Steer : this.command.disposition;
37806
+ recordEvent = (event) => {
37807
+ if (event.kind === AGENT_MESSAGE_DELTA_KIND) {
37808
+ this.#sequence += 1;
37809
+ this.#text += event.text;
37810
+ if (this.#text.length > ACTIVE_TURN_TEXT_LIMIT) {
37811
+ this.#text = this.#text.slice(-ACTIVE_TURN_TEXT_LIMIT);
37812
+ this.#truncated = true;
37813
+ }
37814
+ return {
37815
+ commandId: this.command.commandId,
37816
+ epoch: this.#epoch,
37817
+ kind: AGENT_MESSAGE_DELTA_KIND,
37818
+ messageId: event.messageId,
37819
+ sequence: this.#sequence,
37820
+ sessionId: this.command.sessionId,
37821
+ text: event.text
37822
+ };
37823
+ }
37824
+ if (event.sessionId !== this.command.sessionId || "commandId" in event && event.commandId !== this.command.commandId) {
37825
+ return event;
37826
+ }
37827
+ if (event.kind === AGENT_ACTIVITY_KIND) {
37828
+ this.#activities.set(event.activityId, {
37829
+ activityId: event.activityId,
37830
+ activityType: event.activityType,
37831
+ content: event.content,
37832
+ input: event.input,
37833
+ locations: event.locations,
37834
+ name: event.name,
37835
+ output: event.output,
37836
+ sequence: event.sequence,
37837
+ status: event.status,
37838
+ title: event.title,
37839
+ toolKind: event.toolKind
37840
+ });
37841
+ } else if (event.kind === AGENT_ACTIVITY_NARRATION_KIND) {
37842
+ const previous = this.#activities.get(event.activityId);
37843
+ this.#activities.set(event.activityId, {
37844
+ activityId: event.activityId,
37845
+ activityType: event.activityType,
37846
+ content: previous?.content ?? [],
37847
+ input: previous?.input ?? "",
37848
+ locations: previous?.locations ?? [],
37849
+ name: previous?.name ?? "",
37850
+ output: `${previous?.output ?? ""}${event.text}`,
37851
+ sequence: event.sequence,
37852
+ status: previous?.status ?? "running",
37853
+ title: previous?.title ?? "Thinking",
37854
+ toolKind: previous?.toolKind ?? ""
37855
+ });
37856
+ } else if (event.kind === AGENT_CONTENT_KIND) {
37857
+ this.#content.set(event.contentId, event.content);
37858
+ } else if (event.kind === SESSION_PERMISSION_REQUESTED_KIND || event.kind === SESSION_ELICITATION_REQUESTED_KIND) {
37859
+ this.#interaction = event;
37860
+ } else if ((event.kind === SESSION_PERMISSION_RESOLVED_KIND || event.kind === SESSION_ELICITATION_RESOLVED_KIND) && this.#interaction?.interactionId === event.interactionId) {
37861
+ this.#interaction = null;
37862
+ }
37863
+ return event;
37864
+ };
37865
+ snapshot = () => this.#dispatch.kind === "accepted" ? {
37866
+ activities: [...this.#activities.values()].sort((left, right) => left.sequence - right.sequence),
37867
+ commandId: decodeIdentifier(this.command.commandId),
37868
+ content: [...this.#content.values()],
37869
+ prompt: this.command.prompt,
37870
+ text: this.#text,
37871
+ truncated: this.#truncated,
37872
+ epoch: this.#epoch,
37873
+ interaction: this.#interaction,
37874
+ sequence: this.#sequence,
37875
+ state: "running"
37876
+ } : null;
37877
+ matches = (cancellation) => cancellation.commandId === this.command.commandId && cancellation.sessionId === this.command.sessionId;
37878
+ requestCancellation = () => {
37879
+ if (this.#cancellationRequested) {
37880
+ return "already-requested";
37881
+ }
37882
+ this.#cancellationRequested = true;
37883
+ if (this.#dispatch.kind !== "accepted") {
37884
+ this.#controller.abort(new Error("The queued Agent turn was cancelled"));
37885
+ return "pending";
37886
+ }
37887
+ return "running";
37888
+ };
37889
+ cancellationRequested = () => this.#cancellationRequested;
37890
+ get signal() {
37891
+ return this.#controller.signal;
37892
+ }
37893
+ get completion() {
37894
+ return this.#finished.promise;
37895
+ }
37896
+ };
37897
+
37631
37898
  // src/daemon-diagnostic-log.ts
37632
37899
  import { appendFileSync, mkdirSync, readFileSync as readFileSync2, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
37633
37900
  import { join as join17 } from "node:path";
@@ -37810,184 +38077,6 @@ var DaemonInstallationObserver = class {
37810
38077
  };
37811
38078
  };
37812
38079
 
37813
- // src/daemon-turn-reconciliation.ts
37814
- import { randomUUID as randomUUID3 } from "node:crypto";
37815
- import { fetch as fetch5 } from "undici";
37816
- var ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS = 2e4;
37817
- var ActiveDaemonTurn = class {
37818
- attemptId;
37819
- command;
37820
- #controller;
37821
- #finished = Promise.withResolvers();
37822
- #cancellationRequested = false;
37823
- #dispatch;
37824
- #text = "";
37825
- #truncated = false;
37826
- #sequence = 0;
37827
- #interaction = null;
37828
- #epoch = decodeIdentifier(randomUUID3());
37829
- constructor(command, attemptId) {
37830
- this.attemptId = attemptId;
37831
- this.command = command;
37832
- this.#controller = new AbortController();
37833
- this.#dispatch = command.disposition === SessionPromptDisposition.Queue ? { kind: "queued", promotion: Promise.withResolvers() } : { kind: "pending" };
37834
- }
37835
- abortDaemon = () => {
37836
- this.#controller.abort();
37837
- };
37838
- finish = () => this.#finished.resolve();
37839
- accept = () => {
37840
- this.#dispatch = { kind: "accepted" };
37841
- return { epoch: this.#epoch, sequence: 0 };
37842
- };
37843
- promoteQueuedPrompt = (command) => {
37844
- if (command.commandId !== this.command.commandId || command.sessionId !== this.command.sessionId || this.#dispatch.kind !== "queued") {
37845
- return false;
37846
- }
37847
- const promotion = this.#dispatch.promotion;
37848
- this.#dispatch = { kind: "promoted" };
37849
- promotion.resolve();
37850
- return true;
37851
- };
37852
- queuePromotion = () => {
37853
- if (this.#dispatch.kind === "queued") {
37854
- return this.#dispatch.promotion.promise;
37855
- }
37856
- return this.#dispatch.kind === "promoted" ? Promise.resolve() : null;
37857
- };
37858
- effectiveDisposition = () => this.#dispatch.kind === "promoted" ? SessionPromptDisposition.Steer : this.command.disposition;
37859
- recordText = (delta) => {
37860
- this.#sequence += 1;
37861
- this.#text += delta;
37862
- if (this.#text.length > ACTIVE_TURN_TEXT_LIMIT) {
37863
- this.#text = this.#text.slice(-ACTIVE_TURN_TEXT_LIMIT);
37864
- this.#truncated = true;
37865
- }
37866
- return { epoch: this.#epoch, sequence: this.#sequence };
37867
- };
37868
- recordInteraction = (event) => {
37869
- if (event.sessionId !== this.command.sessionId) {
37870
- return;
37871
- }
37872
- if (event.kind === SESSION_PERMISSION_REQUESTED_KIND || event.kind === SESSION_ELICITATION_REQUESTED_KIND) {
37873
- if (event.commandId === this.command.commandId) {
37874
- this.#interaction = event;
37875
- }
37876
- } else if ((event.kind === SESSION_PERMISSION_RESOLVED_KIND || event.kind === SESSION_ELICITATION_RESOLVED_KIND) && this.#interaction?.interactionId === event.interactionId) {
37877
- this.#interaction = null;
37878
- }
37879
- };
37880
- snapshot = () => this.#dispatch.kind === "accepted" ? {
37881
- commandId: decodeIdentifier(this.command.commandId),
37882
- prompt: this.command.prompt,
37883
- text: this.#text,
37884
- truncated: this.#truncated,
37885
- epoch: this.#epoch,
37886
- interaction: this.#interaction,
37887
- sequence: this.#sequence,
37888
- state: "running"
37889
- } : null;
37890
- matches = (cancellation) => cancellation.commandId === this.command.commandId && cancellation.sessionId === this.command.sessionId;
37891
- requestCancellation = () => {
37892
- if (this.#cancellationRequested) {
37893
- return "already-requested";
37894
- }
37895
- this.#cancellationRequested = true;
37896
- if (this.#dispatch.kind !== "accepted") {
37897
- this.#controller.abort(new Error("The queued Agent turn was cancelled"));
37898
- return "pending";
37899
- }
37900
- return "running";
37901
- };
37902
- cancellationRequested = () => this.#cancellationRequested;
37903
- get signal() {
37904
- return this.#controller.signal;
37905
- }
37906
- get completion() {
37907
- return this.#finished.promise;
37908
- }
37909
- };
37910
- var ActiveTurnReconciliationError = class extends Error {
37911
- code = "active_turn_reconciliation_failed";
37912
- diagnosticDetails;
37913
- relayErrorCode;
37914
- terminal;
37915
- constructor(message, options = {}) {
37916
- super(message, options);
37917
- this.name = "ActiveTurnReconciliationError";
37918
- this.relayErrorCode = options.relayErrorCode ?? null;
37919
- this.terminal = options.terminal ?? false;
37920
- this.diagnosticDetails = this.relayErrorCode === null ? {} : { relayErrorCode: this.relayErrorCode };
37921
- }
37922
- };
37923
- var TERMINAL_RECONCILIATION_RELAY_CODES = /* @__PURE__ */ new Set(["session_conflict"]);
37924
- async function relayErrorCode(response) {
37925
- try {
37926
- const body = JSON.parse(await response.text());
37927
- if (typeof body !== "object" || body === null) {
37928
- return null;
37929
- }
37930
- const error62 = Reflect.get(body, "error");
37931
- if (typeof error62 !== "object" || error62 === null) {
37932
- return null;
37933
- }
37934
- const code = Reflect.get(error62, "code");
37935
- return typeof code === "string" && code.length > 0 ? code : null;
37936
- } catch {
37937
- return null;
37938
- }
37939
- }
37940
- function activeTurnReconciliationEndpoint(config2, turn) {
37941
- const endpoint = relayHttpEndpoint(config2.relayUrl);
37942
- let channelPath = "";
37943
- if (endpoint.pathname.endsWith("/daemon")) {
37944
- channelPath = endpoint.pathname.slice(0, -"/daemon".length);
37945
- } else {
37946
- const runtimePath = "/v1/runtimes/connect";
37947
- if (!endpoint.pathname.endsWith(runtimePath)) {
37948
- throw new ActiveTurnReconciliationError("The Relay URL is invalid");
37949
- }
37950
- channelPath = `${endpoint.pathname.slice(0, -runtimePath.length)}/channels/${encodeURIComponent(config2.channelId)}`;
37951
- }
37952
- endpoint.pathname = `${channelPath}/sessions/${encodeURIComponent(turn.command.sessionId)}/attempts/${encodeURIComponent(turn.attemptId)}/reconciliation`;
37953
- return endpoint;
37954
- }
37955
- async function reconcileActiveTurn(config2, turn, signal) {
37956
- signal.throwIfAborted();
37957
- const timeoutSignal = AbortSignal.timeout(ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS);
37958
- const requestSignal = AbortSignal.any([signal, timeoutSignal]);
37959
- let response;
37960
- try {
37961
- response = await fetch5(activeTurnReconciliationEndpoint(config2, turn), {
37962
- body: JSON.stringify({ outcome: { kind: "running" } }),
37963
- dispatcher: environmentProxyDispatcher,
37964
- headers: { ...runtimeAuthorization(config2.relayUrl), "content-type": "application/json" },
37965
- method: "POST",
37966
- signal: requestSignal
37967
- });
37968
- } catch (error62) {
37969
- if (signal.aborted) {
37970
- signal.throwIfAborted();
37971
- }
37972
- throw new ActiveTurnReconciliationError(
37973
- timeoutSignal.aborted ? "The active Agent turn reconciliation timed out" : "The active Agent turn could not be reconciled",
37974
- { cause: error62 }
37975
- );
37976
- }
37977
- if (!response.ok) {
37978
- const errorCode = await relayErrorCode(response);
37979
- const terminal = errorCode !== null && TERMINAL_RECONCILIATION_RELAY_CODES.has(errorCode);
37980
- throw new ActiveTurnReconciliationError(
37981
- terminal ? `The Relay reported that the active Agent turn can no longer be reconciled (${errorCode})` : `The Relay rejected the active Agent turn reconciliation with status ${response.status.toString()}`,
37982
- { relayErrorCode: errorCode, terminal }
37983
- );
37984
- }
37985
- await response.body?.cancel();
37986
- }
37987
- async function reconcileActiveTurns(config2, turns, signal) {
37988
- await Promise.all(turns.map(async (turn) => await reconcileActiveTurn(config2, turn, signal)));
37989
- }
37990
-
37991
38080
  // src/native-sessions/codex-history.ts
37992
38081
  import { spawn as spawn5 } from "node:child_process";
37993
38082
  var responseSchema = external_exports.union([
@@ -39286,25 +39375,6 @@ var RelayConnectionDiagnostics = class {
39286
39375
  addFailureDetails(details, failure2);
39287
39376
  this.#record("relay_connection_failed", connectionEpoch.toString(), details, true);
39288
39377
  };
39289
- /**
39290
- * Records that the Runtime gave up on Agent turns the Relay already settled. This is not a connection
39291
- * failure, so it is recorded independently of the per-epoch failure deduplication.
39292
- */
39293
- reconciliationAbandoned = (connectionEpoch, relayErrorCode2, turnCount) => {
39294
- this.#record(
39295
- "relay_reconciliation_abandoned",
39296
- connectionEpoch.toString(),
39297
- {
39298
- connectionEpoch: connectionEpoch.toString(),
39299
- relayErrorCode: relayErrorCode2 ?? "unknown",
39300
- relayOrigin: this.#relayOrigin,
39301
- source: "reconciliation_abandoned",
39302
- turnCount: turnCount.toString(),
39303
- ...this.#route
39304
- },
39305
- true
39306
- );
39307
- };
39308
39378
  connectionOpened = (connectionEpoch) => {
39309
39379
  this.#record(
39310
39380
  "relay_connection_opened",
@@ -39532,7 +39602,6 @@ var systemDaemonTimer = new SystemDaemonTimer();
39532
39602
 
39533
39603
  // src/run-daemon.ts
39534
39604
  var RELAY_RECONNECT_DELAY_MILLISECONDS = 500;
39535
- var ACTIVE_TURN_RECONCILIATION_CLOSE_CODE = 4009;
39536
39605
  function closeRelaySocket(socket, code, reason) {
39537
39606
  try {
39538
39607
  socket.close(code, reason);
@@ -39601,7 +39670,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
39601
39670
  const relayUrl = new URL(config2.relayUrl);
39602
39671
  relayUrl.searchParams.set("liveness", "1");
39603
39672
  const socket = await connectRelay(relayUrl, signal);
39604
- const reconnectingTurns = [...activeTurns.values()];
39605
39673
  diagnostics.connectionOpened(connectionEpoch);
39606
39674
  const connectionController = new AbortController();
39607
39675
  const handleSettingsDiscovery = createAgentSettingsDiscoveryHandler({
@@ -39623,6 +39691,18 @@ async function runRelayConnection(config2, directories, audit, sessions, install
39623
39691
  timer,
39624
39692
  resolveEnvironment: resolveAgentCatalogEnvironment
39625
39693
  });
39694
+ const activeTurnSnapshot = (sessionId) => {
39695
+ for (const turn of activeTurns.values()) {
39696
+ if (turn.command.sessionId !== sessionId) {
39697
+ continue;
39698
+ }
39699
+ const snapshot = turn.snapshot();
39700
+ if (snapshot !== null) {
39701
+ return snapshot;
39702
+ }
39703
+ }
39704
+ return null;
39705
+ };
39626
39706
  const nativeRequestHandler = createNativeSessionRequestHandler({
39627
39707
  audit,
39628
39708
  diagnostics,
@@ -39792,6 +39872,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
39792
39872
  directories,
39793
39873
  audit,
39794
39874
  sessions,
39875
+ activeTurnSnapshot,
39795
39876
  connectionController.signal
39796
39877
  );
39797
39878
  return;
@@ -39805,6 +39886,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
39805
39886
  directories,
39806
39887
  audit,
39807
39888
  sessions,
39889
+ activeTurnSnapshot,
39808
39890
  connectionController.signal
39809
39891
  );
39810
39892
  return;
@@ -40007,7 +40089,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40007
40089
  (waitSignal) => waitForSessionAvailability(command, turn, waitSignal),
40008
40090
  timer,
40009
40091
  turn.signal,
40010
- turn.recordText,
40092
+ turn.recordEvent,
40011
40093
  turn.cancellationRequested
40012
40094
  ).catch((error62) => {
40013
40095
  console.error("Mobius daemon turn failed", error62);
@@ -40028,43 +40110,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40028
40110
  socket.addEventListener("close", handleClose);
40029
40111
  socket.addEventListener("error", handleError);
40030
40112
  socket.addEventListener("message", handleMessage);
40031
- void reconcileActiveTurns(config2, reconnectingTurns, connectionController.signal).then(
40032
- () => {
40033
- if (finished) {
40034
- return;
40035
- }
40036
- publisher.connect(socket);
40037
- },
40038
- (error62) => {
40039
- if (finished) {
40040
- return;
40041
- }
40042
- console.error("Mobius daemon could not reconcile active Agent turns", error62);
40043
- if (error62 instanceof ActiveTurnReconciliationError && error62.terminal) {
40044
- diagnostics.reconciliationAbandoned(
40045
- connectionEpoch,
40046
- error62.relayErrorCode,
40047
- reconnectingTurns.length
40048
- );
40049
- console.error(
40050
- "Mobius daemon abandoned Agent turns the Relay already settled",
40051
- error62.relayErrorCode
40052
- );
40053
- for (const turn of reconnectingTurns) {
40054
- activeTurns.delete(turn.command.commandId);
40055
- turn.abortDaemon();
40056
- }
40057
- publisher.connect(socket);
40058
- return;
40059
- }
40060
- failAndClose(
40061
- new Error("Active Agent turn reconciliation failed", { cause: error62 }),
40062
- ACTIVE_TURN_RECONCILIATION_CLOSE_CODE,
40063
- "Active Agent turn reconciliation failed",
40064
- "reconciliation"
40065
- );
40066
- }
40067
- );
40113
+ publisher.connect(socket);
40068
40114
  if (signal.aborted) {
40069
40115
  stop();
40070
40116
  }
@@ -40096,7 +40142,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
40096
40142
  const activeTurns = /* @__PURE__ */ new Map();
40097
40143
  const recordSessionEvent = (sessionId, event) => {
40098
40144
  for (const turn of activeTurns.values()) {
40099
- turn.recordInteraction(event);
40145
+ turn.recordEvent(event);
40100
40146
  }
40101
40147
  publisher.publish(sessionId, event);
40102
40148
  };