@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/index.js CHANGED
@@ -21012,6 +21012,19 @@ var envelope = {
21012
21012
  requestId: identifierStringSchema,
21013
21013
  sessionId: identifierStringSchema
21014
21014
  };
21015
+ var activeTurnActivitySchema = external_exports.strictObject({
21016
+ activityId: external_exports.string().min(1).max(128),
21017
+ activityType: external_exports.string().min(1).max(128),
21018
+ content: external_exports.array(displayContentSchema).max(100).readonly(),
21019
+ input: external_exports.string().max(1e5),
21020
+ locations: external_exports.array(external_exports.string().min(1).max(2048)).max(100).readonly(),
21021
+ name: external_exports.string().max(128),
21022
+ output: external_exports.string().max(1e5),
21023
+ sequence: external_exports.number().int().nonnegative(),
21024
+ status: external_exports.string().min(1).max(64),
21025
+ title: external_exports.string().max(500),
21026
+ toolKind: external_exports.string().max(64)
21027
+ }).readonly();
21015
21028
  var identity = {
21016
21029
  ...envelope,
21017
21030
  kind: external_exports.literal(NATIVE_SESSION_REQUEST_KIND),
@@ -21087,7 +21100,9 @@ var nativeSessionResultSchema = external_exports.discriminatedUnion("action", [
21087
21100
  action: external_exports.literal("active-turn"),
21088
21101
  targetSessionId: identifierStringSchema,
21089
21102
  turn: external_exports.strictObject({
21103
+ activities: external_exports.array(activeTurnActivitySchema).max(100).readonly(),
21090
21104
  commandId: identifierStringSchema,
21105
+ content: external_exports.array(displayContentSchema).max(100).readonly(),
21091
21106
  prompt: external_exports.string().max(1e5),
21092
21107
  text: external_exports.string().max(ACTIVE_TURN_TEXT_LIMIT),
21093
21108
  truncated: external_exports.boolean(),
@@ -27680,6 +27695,18 @@ var CODEX_META_KEY = "codex";
27680
27695
  function truncate4(value, limit) {
27681
27696
  return value.length <= limit ? value : value.slice(0, limit);
27682
27697
  }
27698
+ function boundedParagraphs(values, limit) {
27699
+ let text = "";
27700
+ for (const value of values) {
27701
+ const separator = text.length === 0 ? "" : "\n\n";
27702
+ const remaining = limit - text.length;
27703
+ if (remaining <= separator.length) {
27704
+ break;
27705
+ }
27706
+ text += `${separator}${value.slice(0, remaining - separator.length)}`;
27707
+ }
27708
+ return text;
27709
+ }
27683
27710
  function textContent(text) {
27684
27711
  const block = { text: truncate4(text, TOOL_OUTPUT_CHARACTER_LIMIT), type: "text" };
27685
27712
  return { content: block, type: "content" };
@@ -27797,6 +27824,12 @@ function decodeThreadItem(value) {
27797
27824
  const decoded = threadItemSchema.safeParse(value);
27798
27825
  return decoded.success ? decoded.data : null;
27799
27826
  }
27827
+ function reasoningText(item) {
27828
+ if (item.type !== "reasoning") {
27829
+ return null;
27830
+ }
27831
+ return boundedParagraphs(item.summary.length > 0 ? item.summary : item.content, TOOL_OUTPUT_CHARACTER_LIMIT);
27832
+ }
27800
27833
  function agentMessageMeta(phase) {
27801
27834
  if (phase == null) {
27802
27835
  return null;
@@ -28565,6 +28598,19 @@ var CodexAcpAgent = class {
28565
28598
  });
28566
28599
  return;
28567
28600
  }
28601
+ const reasoning = reasoningText(item);
28602
+ if (reasoning !== null) {
28603
+ if (method === "item/completed" && reasoning.length > 0) {
28604
+ await this.#enqueue(async () => {
28605
+ await this.#emit({
28606
+ content: { text: reasoning, type: "text" },
28607
+ messageId: item.id,
28608
+ sessionUpdate: "agent_thought_chunk"
28609
+ });
28610
+ });
28611
+ }
28612
+ return;
28613
+ }
28568
28614
  const update = toolCallUpdate(item, method === "item/completed" ? "completed" : "started");
28569
28615
  if (update !== null) {
28570
28616
  await this.#enqueue(async () => {
@@ -31893,7 +31939,10 @@ function liveHistoryCoveredTurnRanges(history) {
31893
31939
  }
31894
31940
  return ranges;
31895
31941
  }
31896
- function paginateLiveSessionHistory(history, sessionId, cursor, limit) {
31942
+ function historyMessageCharacters(message) {
31943
+ return message.text.length + (message.role === "assistant" ? JSON.stringify(message.activities).length + JSON.stringify(message.content).length : 0);
31944
+ }
31945
+ function paginateAcpSessionHistory(history, sessionId, cursor, limit) {
31897
31946
  if (history.status === "unavailable") {
31898
31947
  if (cursor !== null) {
31899
31948
  throw new AcpExecutionError("Unavailable native Session history has no cursor", {}, "invalid_cursor");
@@ -31919,6 +31968,80 @@ function paginateLiveSessionHistory(history, sessionId, cursor, limit) {
31919
31968
  truncated: history.truncated
31920
31969
  };
31921
31970
  }
31971
+ function paginateLiveSessionHistory(history, activeTurn, sessionId, cursor, limit) {
31972
+ if (activeTurn === null || cursor !== null) {
31973
+ return paginateAcpSessionHistory(history, sessionId, cursor, limit);
31974
+ }
31975
+ const activeMessageOverhead = 4;
31976
+ const activeStructuredCharacters = JSON.stringify(activeTurn.activities).length + JSON.stringify(activeTurn.content).length;
31977
+ const maximumActiveTextLength = Math.max(
31978
+ 0,
31979
+ SESSION_HISTORY_CHARACTER_LIMIT - activeTurn.prompt.length - activeStructuredCharacters - activeMessageOverhead
31980
+ );
31981
+ const activeText = activeTurn.text.slice(-maximumActiveTextLength);
31982
+ const completeActiveMessages = [
31983
+ { role: "user", text: activeTurn.prompt },
31984
+ {
31985
+ activities: activeTurn.activities,
31986
+ content: activeTurn.content,
31987
+ role: "assistant",
31988
+ text: activeText
31989
+ }
31990
+ ];
31991
+ if (history.status === "unavailable") {
31992
+ return {
31993
+ coveredCommandIds: [],
31994
+ coveredMessageIds: [],
31995
+ messages: completeActiveMessages,
31996
+ nextCursor: null,
31997
+ status: "available",
31998
+ truncated: activeTurn.truncated || activeText.length !== activeTurn.text.length
31999
+ };
32000
+ }
32001
+ const latestNativeMessage = history.messages.at(-1);
32002
+ const activeMessages = latestNativeMessage?.role === "user" && latestNativeMessage.text === activeTurn.prompt ? completeActiveMessages.slice(1) : completeActiveMessages;
32003
+ let historicalMessageCount = 0;
32004
+ let remainingCharacters = SESSION_HISTORY_CHARACTER_LIMIT - activeText.length - activeMessageOverhead - activeStructuredCharacters - (activeMessages.length === completeActiveMessages.length ? activeTurn.prompt.length : 0);
32005
+ const historicalMessageLimit = Math.max(0, limit - activeMessages.length);
32006
+ for (let index = history.messages.length - 1; index >= 0 && historicalMessageCount < historicalMessageLimit; index -= 1) {
32007
+ const message = history.messages[index];
32008
+ if (message === void 0) {
32009
+ break;
32010
+ }
32011
+ const characters = historyMessageCharacters(message);
32012
+ if (characters > remainingCharacters) {
32013
+ break;
32014
+ }
32015
+ historicalMessageCount += 1;
32016
+ remainingCharacters -= characters;
32017
+ }
32018
+ const page = historicalMessageCount === 0 ? {
32019
+ coveredCommandIds: [],
32020
+ coveredMessageIds: [],
32021
+ messages: [],
32022
+ nextCursor: history.messages.length === 0 ? null : liveHistoryCursor(sessionId, history.messages.length),
32023
+ status: "available",
32024
+ truncated: history.truncated
32025
+ } : paginateAcpSessionHistory(history, sessionId, null, historicalMessageCount);
32026
+ return {
32027
+ ...page,
32028
+ messages: [...page.messages, ...activeMessages],
32029
+ truncated: page.truncated || activeTurn.truncated || activeText.length !== activeTurn.text.length
32030
+ };
32031
+ }
32032
+ function mergeLiveSessionHistory(history, activeTurn, sessionId) {
32033
+ const page = paginateLiveSessionHistory(history, activeTurn, sessionId, null, 1e3);
32034
+ if (page.status === "unavailable") {
32035
+ return { cause: page.cause, status: "unavailable" };
32036
+ }
32037
+ return {
32038
+ coveredCommandIds: page.coveredCommandIds,
32039
+ coveredMessageIds: page.coveredMessageIds,
32040
+ messages: page.messages,
32041
+ status: "available",
32042
+ truncated: page.truncated
32043
+ };
32044
+ }
31922
32045
 
31923
32046
  // src/prompt-artifact-resolver.ts
31924
32047
  import { createHash as createHash3 } from "node:crypto";
@@ -32550,7 +32673,7 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
32550
32673
  reportOperationFailure(socket, command.requestId, command.sessionId, error62, metrics.snapshot());
32551
32674
  }
32552
32675
  }
32553
- async function executeSessionLiveHistoryLoad(socket, command, config2, directories, audit, sessions, signal) {
32676
+ async function executeSessionLiveHistoryLoad(socket, command, config2, directories, audit, sessions, activeTurn, signal) {
32554
32677
  try {
32555
32678
  const resolved = await resolveSessionDirectories(
32556
32679
  directories,
@@ -32567,13 +32690,14 @@ async function executeSessionLiveHistoryLoad(socket, command, config2, directori
32567
32690
  signal
32568
32691
  });
32569
32692
  signal.throwIfAborted();
32693
+ const mergedHistory = mergeLiveSessionHistory(history, activeTurn(command.sessionId), command.sessionId);
32570
32694
  audit.record({
32571
32695
  commandId: command.requestId,
32572
32696
  event: "session_history_loaded",
32573
32697
  sessionId: command.sessionId
32574
32698
  });
32575
32699
  send(socket, {
32576
- history,
32700
+ history: mergedHistory,
32577
32701
  kind: "session.live-history.loaded",
32578
32702
  requestId: command.requestId,
32579
32703
  sessionId: command.sessionId
@@ -32599,7 +32723,7 @@ async function executeSessionLiveHistoryLoad(socket, command, config2, directori
32599
32723
  });
32600
32724
  }
32601
32725
  }
32602
- async function executeSessionLiveHistoryPageLoad(socket, command, config2, directories, audit, sessions, signal) {
32726
+ async function executeSessionLiveHistoryPageLoad(socket, command, config2, directories, audit, sessions, activeTurn, signal) {
32603
32727
  try {
32604
32728
  const resolved = await resolveSessionDirectories(
32605
32729
  directories,
@@ -32616,7 +32740,13 @@ async function executeSessionLiveHistoryPageLoad(socket, command, config2, direc
32616
32740
  signal
32617
32741
  });
32618
32742
  signal.throwIfAborted();
32619
- const page = paginateLiveSessionHistory(history, command.sessionId, command.cursor, command.limit);
32743
+ const page = paginateLiveSessionHistory(
32744
+ history,
32745
+ activeTurn(command.sessionId),
32746
+ command.sessionId,
32747
+ command.cursor,
32748
+ command.limit
32749
+ );
32620
32750
  audit.record({
32621
32751
  commandId: command.requestId,
32622
32752
  event: "session_history_loaded",
@@ -32689,14 +32819,11 @@ async function executeSessionConfigure(publisher, socket, command, config2, dire
32689
32819
  reportOperationFailure(socket, command.requestId, command.sessionId, error62);
32690
32820
  }
32691
32821
  }
32692
- async function executePrompt(operations, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, acknowledgeQueued, waitForSessionAvailability, timer, signal, recordLiveText, cancellationRequested) {
32693
- const activities = new CoalescingDaemonActivityPublisher(timer, (activity2) => {
32694
- publisher.publish(command.sessionId, daemonActivity(command, activity2));
32695
- });
32822
+ async function executePrompt(operations, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, acknowledgeQueued, waitForSessionAvailability, timer, signal, recordLiveEvent, cancellationRequested) {
32696
32823
  const narration = new CoalescingNarrationPublisher(
32697
32824
  timer,
32698
32825
  (increment) => {
32699
- publisher.publish(command.sessionId, {
32826
+ const event = {
32700
32827
  activityId: increment.activityId,
32701
32828
  activityType: increment.activityType,
32702
32829
  commandId: command.commandId,
@@ -32704,24 +32831,26 @@ async function executePrompt(operations, publisher, command, config2, directorie
32704
32831
  sequence: increment.sequence,
32705
32832
  sessionId: command.sessionId,
32706
32833
  text: increment.text
32707
- });
32834
+ };
32835
+ publisher.publish(command.sessionId, recordLiveEvent(event));
32708
32836
  },
32709
32837
  AGENT_ACTIVITY_COALESCING_MILLISECONDS,
32710
32838
  AGENT_TEXT_MAXIMUM_LENGTH
32711
32839
  );
32840
+ const activities = new CoalescingDaemonActivityPublisher(timer, (activity2) => {
32841
+ if (activity2.status !== "pending" && activity2.status !== "running") {
32842
+ narration.flush();
32843
+ }
32844
+ const event = daemonActivity(command, activity2);
32845
+ publisher.publish(command.sessionId, recordLiveEvent(event));
32846
+ });
32712
32847
  const text = new CoalescingTextPublisher(
32713
32848
  timer,
32714
32849
  (messageId, delta) => {
32715
- const stream = recordLiveText(delta);
32716
- publisher.publish(command.sessionId, {
32717
- commandId: command.commandId,
32718
- epoch: stream.epoch,
32719
- kind: AGENT_MESSAGE_DELTA_KIND,
32720
- messageId,
32721
- sequence: stream.sequence,
32722
- sessionId: command.sessionId,
32723
- text: delta
32724
- });
32850
+ publisher.publish(
32851
+ command.sessionId,
32852
+ recordLiveEvent({ kind: AGENT_MESSAGE_DELTA_KIND, messageId, text: delta })
32853
+ );
32725
32854
  },
32726
32855
  AGENT_TEXT_COALESCING_MILLISECONDS,
32727
32856
  AGENT_TEXT_MAXIMUM_LENGTH
@@ -34190,6 +34319,144 @@ var WorkspaceDirectoryService = class {
34190
34319
  };
34191
34320
  };
34192
34321
 
34322
+ // src/daemon-active-turn.ts
34323
+ import { randomUUID as randomUUID3 } from "node:crypto";
34324
+ var ActiveDaemonTurn = class {
34325
+ attemptId;
34326
+ command;
34327
+ #controller;
34328
+ #finished = Promise.withResolvers();
34329
+ #cancellationRequested = false;
34330
+ #dispatch;
34331
+ #text = "";
34332
+ #activities = /* @__PURE__ */ new Map();
34333
+ #content = /* @__PURE__ */ new Map();
34334
+ #truncated = false;
34335
+ #sequence = 0;
34336
+ #interaction = null;
34337
+ #epoch = decodeIdentifier(randomUUID3());
34338
+ constructor(command, attemptId) {
34339
+ this.attemptId = attemptId;
34340
+ this.command = command;
34341
+ this.#controller = new AbortController();
34342
+ this.#dispatch = command.disposition === SessionPromptDisposition.Queue ? { kind: "queued", promotion: Promise.withResolvers() } : { kind: "pending" };
34343
+ }
34344
+ abortDaemon = () => {
34345
+ this.#controller.abort();
34346
+ };
34347
+ finish = () => this.#finished.resolve();
34348
+ accept = () => {
34349
+ this.#dispatch = { kind: "accepted" };
34350
+ return { epoch: this.#epoch, sequence: 0 };
34351
+ };
34352
+ promoteQueuedPrompt = (command) => {
34353
+ if (command.commandId !== this.command.commandId || command.sessionId !== this.command.sessionId || this.#dispatch.kind !== "queued") {
34354
+ return false;
34355
+ }
34356
+ const promotion = this.#dispatch.promotion;
34357
+ this.#dispatch = { kind: "promoted" };
34358
+ promotion.resolve();
34359
+ return true;
34360
+ };
34361
+ queuePromotion = () => {
34362
+ if (this.#dispatch.kind === "queued") {
34363
+ return this.#dispatch.promotion.promise;
34364
+ }
34365
+ return this.#dispatch.kind === "promoted" ? Promise.resolve() : null;
34366
+ };
34367
+ effectiveDisposition = () => this.#dispatch.kind === "promoted" ? SessionPromptDisposition.Steer : this.command.disposition;
34368
+ recordEvent = (event) => {
34369
+ if (event.kind === AGENT_MESSAGE_DELTA_KIND) {
34370
+ this.#sequence += 1;
34371
+ this.#text += event.text;
34372
+ if (this.#text.length > ACTIVE_TURN_TEXT_LIMIT) {
34373
+ this.#text = this.#text.slice(-ACTIVE_TURN_TEXT_LIMIT);
34374
+ this.#truncated = true;
34375
+ }
34376
+ return {
34377
+ commandId: this.command.commandId,
34378
+ epoch: this.#epoch,
34379
+ kind: AGENT_MESSAGE_DELTA_KIND,
34380
+ messageId: event.messageId,
34381
+ sequence: this.#sequence,
34382
+ sessionId: this.command.sessionId,
34383
+ text: event.text
34384
+ };
34385
+ }
34386
+ if (event.sessionId !== this.command.sessionId || "commandId" in event && event.commandId !== this.command.commandId) {
34387
+ return event;
34388
+ }
34389
+ if (event.kind === AGENT_ACTIVITY_KIND) {
34390
+ this.#activities.set(event.activityId, {
34391
+ activityId: event.activityId,
34392
+ activityType: event.activityType,
34393
+ content: event.content,
34394
+ input: event.input,
34395
+ locations: event.locations,
34396
+ name: event.name,
34397
+ output: event.output,
34398
+ sequence: event.sequence,
34399
+ status: event.status,
34400
+ title: event.title,
34401
+ toolKind: event.toolKind
34402
+ });
34403
+ } else if (event.kind === AGENT_ACTIVITY_NARRATION_KIND) {
34404
+ const previous = this.#activities.get(event.activityId);
34405
+ this.#activities.set(event.activityId, {
34406
+ activityId: event.activityId,
34407
+ activityType: event.activityType,
34408
+ content: previous?.content ?? [],
34409
+ input: previous?.input ?? "",
34410
+ locations: previous?.locations ?? [],
34411
+ name: previous?.name ?? "",
34412
+ output: `${previous?.output ?? ""}${event.text}`,
34413
+ sequence: event.sequence,
34414
+ status: previous?.status ?? "running",
34415
+ title: previous?.title ?? "Thinking",
34416
+ toolKind: previous?.toolKind ?? ""
34417
+ });
34418
+ } else if (event.kind === AGENT_CONTENT_KIND) {
34419
+ this.#content.set(event.contentId, event.content);
34420
+ } else if (event.kind === SESSION_PERMISSION_REQUESTED_KIND || event.kind === SESSION_ELICITATION_REQUESTED_KIND) {
34421
+ this.#interaction = event;
34422
+ } else if ((event.kind === SESSION_PERMISSION_RESOLVED_KIND || event.kind === SESSION_ELICITATION_RESOLVED_KIND) && this.#interaction?.interactionId === event.interactionId) {
34423
+ this.#interaction = null;
34424
+ }
34425
+ return event;
34426
+ };
34427
+ snapshot = () => this.#dispatch.kind === "accepted" ? {
34428
+ activities: [...this.#activities.values()].sort((left, right) => left.sequence - right.sequence),
34429
+ commandId: decodeIdentifier(this.command.commandId),
34430
+ content: [...this.#content.values()],
34431
+ prompt: this.command.prompt,
34432
+ text: this.#text,
34433
+ truncated: this.#truncated,
34434
+ epoch: this.#epoch,
34435
+ interaction: this.#interaction,
34436
+ sequence: this.#sequence,
34437
+ state: "running"
34438
+ } : null;
34439
+ matches = (cancellation) => cancellation.commandId === this.command.commandId && cancellation.sessionId === this.command.sessionId;
34440
+ requestCancellation = () => {
34441
+ if (this.#cancellationRequested) {
34442
+ return "already-requested";
34443
+ }
34444
+ this.#cancellationRequested = true;
34445
+ if (this.#dispatch.kind !== "accepted") {
34446
+ this.#controller.abort(new Error("The queued Agent turn was cancelled"));
34447
+ return "pending";
34448
+ }
34449
+ return "running";
34450
+ };
34451
+ cancellationRequested = () => this.#cancellationRequested;
34452
+ get signal() {
34453
+ return this.#controller.signal;
34454
+ }
34455
+ get completion() {
34456
+ return this.#finished.promise;
34457
+ }
34458
+ };
34459
+
34193
34460
  // src/daemon-diagnostic-log.ts
34194
34461
  import { appendFileSync, mkdirSync, readFileSync as readFileSync2, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
34195
34462
  import { join as join17 } from "node:path";
@@ -34372,184 +34639,6 @@ var DaemonInstallationObserver = class {
34372
34639
  };
34373
34640
  };
34374
34641
 
34375
- // src/daemon-turn-reconciliation.ts
34376
- import { randomUUID as randomUUID3 } from "node:crypto";
34377
- import { fetch as fetch5 } from "undici";
34378
- var ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS = 2e4;
34379
- var ActiveDaemonTurn = class {
34380
- attemptId;
34381
- command;
34382
- #controller;
34383
- #finished = Promise.withResolvers();
34384
- #cancellationRequested = false;
34385
- #dispatch;
34386
- #text = "";
34387
- #truncated = false;
34388
- #sequence = 0;
34389
- #interaction = null;
34390
- #epoch = decodeIdentifier(randomUUID3());
34391
- constructor(command, attemptId) {
34392
- this.attemptId = attemptId;
34393
- this.command = command;
34394
- this.#controller = new AbortController();
34395
- this.#dispatch = command.disposition === SessionPromptDisposition.Queue ? { kind: "queued", promotion: Promise.withResolvers() } : { kind: "pending" };
34396
- }
34397
- abortDaemon = () => {
34398
- this.#controller.abort();
34399
- };
34400
- finish = () => this.#finished.resolve();
34401
- accept = () => {
34402
- this.#dispatch = { kind: "accepted" };
34403
- return { epoch: this.#epoch, sequence: 0 };
34404
- };
34405
- promoteQueuedPrompt = (command) => {
34406
- if (command.commandId !== this.command.commandId || command.sessionId !== this.command.sessionId || this.#dispatch.kind !== "queued") {
34407
- return false;
34408
- }
34409
- const promotion = this.#dispatch.promotion;
34410
- this.#dispatch = { kind: "promoted" };
34411
- promotion.resolve();
34412
- return true;
34413
- };
34414
- queuePromotion = () => {
34415
- if (this.#dispatch.kind === "queued") {
34416
- return this.#dispatch.promotion.promise;
34417
- }
34418
- return this.#dispatch.kind === "promoted" ? Promise.resolve() : null;
34419
- };
34420
- effectiveDisposition = () => this.#dispatch.kind === "promoted" ? SessionPromptDisposition.Steer : this.command.disposition;
34421
- recordText = (delta) => {
34422
- this.#sequence += 1;
34423
- this.#text += delta;
34424
- if (this.#text.length > ACTIVE_TURN_TEXT_LIMIT) {
34425
- this.#text = this.#text.slice(-ACTIVE_TURN_TEXT_LIMIT);
34426
- this.#truncated = true;
34427
- }
34428
- return { epoch: this.#epoch, sequence: this.#sequence };
34429
- };
34430
- recordInteraction = (event) => {
34431
- if (event.sessionId !== this.command.sessionId) {
34432
- return;
34433
- }
34434
- if (event.kind === SESSION_PERMISSION_REQUESTED_KIND || event.kind === SESSION_ELICITATION_REQUESTED_KIND) {
34435
- if (event.commandId === this.command.commandId) {
34436
- this.#interaction = event;
34437
- }
34438
- } else if ((event.kind === SESSION_PERMISSION_RESOLVED_KIND || event.kind === SESSION_ELICITATION_RESOLVED_KIND) && this.#interaction?.interactionId === event.interactionId) {
34439
- this.#interaction = null;
34440
- }
34441
- };
34442
- snapshot = () => this.#dispatch.kind === "accepted" ? {
34443
- commandId: decodeIdentifier(this.command.commandId),
34444
- prompt: this.command.prompt,
34445
- text: this.#text,
34446
- truncated: this.#truncated,
34447
- epoch: this.#epoch,
34448
- interaction: this.#interaction,
34449
- sequence: this.#sequence,
34450
- state: "running"
34451
- } : null;
34452
- matches = (cancellation) => cancellation.commandId === this.command.commandId && cancellation.sessionId === this.command.sessionId;
34453
- requestCancellation = () => {
34454
- if (this.#cancellationRequested) {
34455
- return "already-requested";
34456
- }
34457
- this.#cancellationRequested = true;
34458
- if (this.#dispatch.kind !== "accepted") {
34459
- this.#controller.abort(new Error("The queued Agent turn was cancelled"));
34460
- return "pending";
34461
- }
34462
- return "running";
34463
- };
34464
- cancellationRequested = () => this.#cancellationRequested;
34465
- get signal() {
34466
- return this.#controller.signal;
34467
- }
34468
- get completion() {
34469
- return this.#finished.promise;
34470
- }
34471
- };
34472
- var ActiveTurnReconciliationError = class extends Error {
34473
- code = "active_turn_reconciliation_failed";
34474
- diagnosticDetails;
34475
- relayErrorCode;
34476
- terminal;
34477
- constructor(message, options = {}) {
34478
- super(message, options);
34479
- this.name = "ActiveTurnReconciliationError";
34480
- this.relayErrorCode = options.relayErrorCode ?? null;
34481
- this.terminal = options.terminal ?? false;
34482
- this.diagnosticDetails = this.relayErrorCode === null ? {} : { relayErrorCode: this.relayErrorCode };
34483
- }
34484
- };
34485
- var TERMINAL_RECONCILIATION_RELAY_CODES = /* @__PURE__ */ new Set(["session_conflict"]);
34486
- async function relayErrorCode(response) {
34487
- try {
34488
- const body = JSON.parse(await response.text());
34489
- if (typeof body !== "object" || body === null) {
34490
- return null;
34491
- }
34492
- const error62 = Reflect.get(body, "error");
34493
- if (typeof error62 !== "object" || error62 === null) {
34494
- return null;
34495
- }
34496
- const code = Reflect.get(error62, "code");
34497
- return typeof code === "string" && code.length > 0 ? code : null;
34498
- } catch {
34499
- return null;
34500
- }
34501
- }
34502
- function activeTurnReconciliationEndpoint(config2, turn) {
34503
- const endpoint = relayHttpEndpoint(config2.relayUrl);
34504
- let channelPath = "";
34505
- if (endpoint.pathname.endsWith("/daemon")) {
34506
- channelPath = endpoint.pathname.slice(0, -"/daemon".length);
34507
- } else {
34508
- const runtimePath = "/v1/runtimes/connect";
34509
- if (!endpoint.pathname.endsWith(runtimePath)) {
34510
- throw new ActiveTurnReconciliationError("The Relay URL is invalid");
34511
- }
34512
- channelPath = `${endpoint.pathname.slice(0, -runtimePath.length)}/channels/${encodeURIComponent(config2.channelId)}`;
34513
- }
34514
- endpoint.pathname = `${channelPath}/sessions/${encodeURIComponent(turn.command.sessionId)}/attempts/${encodeURIComponent(turn.attemptId)}/reconciliation`;
34515
- return endpoint;
34516
- }
34517
- async function reconcileActiveTurn(config2, turn, signal) {
34518
- signal.throwIfAborted();
34519
- const timeoutSignal = AbortSignal.timeout(ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS);
34520
- const requestSignal = AbortSignal.any([signal, timeoutSignal]);
34521
- let response;
34522
- try {
34523
- response = await fetch5(activeTurnReconciliationEndpoint(config2, turn), {
34524
- body: JSON.stringify({ outcome: { kind: "running" } }),
34525
- dispatcher: environmentProxyDispatcher,
34526
- headers: { ...runtimeAuthorization(config2.relayUrl), "content-type": "application/json" },
34527
- method: "POST",
34528
- signal: requestSignal
34529
- });
34530
- } catch (error62) {
34531
- if (signal.aborted) {
34532
- signal.throwIfAborted();
34533
- }
34534
- throw new ActiveTurnReconciliationError(
34535
- timeoutSignal.aborted ? "The active Agent turn reconciliation timed out" : "The active Agent turn could not be reconciled",
34536
- { cause: error62 }
34537
- );
34538
- }
34539
- if (!response.ok) {
34540
- const errorCode = await relayErrorCode(response);
34541
- const terminal = errorCode !== null && TERMINAL_RECONCILIATION_RELAY_CODES.has(errorCode);
34542
- throw new ActiveTurnReconciliationError(
34543
- 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()}`,
34544
- { relayErrorCode: errorCode, terminal }
34545
- );
34546
- }
34547
- await response.body?.cancel();
34548
- }
34549
- async function reconcileActiveTurns(config2, turns, signal) {
34550
- await Promise.all(turns.map(async (turn) => await reconcileActiveTurn(config2, turn, signal)));
34551
- }
34552
-
34553
34642
  // src/native-sessions/codex-history.ts
34554
34643
  import { spawn as spawn5 } from "node:child_process";
34555
34644
  var responseSchema = external_exports.union([
@@ -35828,25 +35917,6 @@ var RelayConnectionDiagnostics = class {
35828
35917
  addFailureDetails(details, failure2);
35829
35918
  this.#record("relay_connection_failed", connectionEpoch.toString(), details, true);
35830
35919
  };
35831
- /**
35832
- * Records that the Runtime gave up on Agent turns the Relay already settled. This is not a connection
35833
- * failure, so it is recorded independently of the per-epoch failure deduplication.
35834
- */
35835
- reconciliationAbandoned = (connectionEpoch, relayErrorCode2, turnCount) => {
35836
- this.#record(
35837
- "relay_reconciliation_abandoned",
35838
- connectionEpoch.toString(),
35839
- {
35840
- connectionEpoch: connectionEpoch.toString(),
35841
- relayErrorCode: relayErrorCode2 ?? "unknown",
35842
- relayOrigin: this.#relayOrigin,
35843
- source: "reconciliation_abandoned",
35844
- turnCount: turnCount.toString(),
35845
- ...this.#route
35846
- },
35847
- true
35848
- );
35849
- };
35850
35920
  connectionOpened = (connectionEpoch) => {
35851
35921
  this.#record(
35852
35922
  "relay_connection_opened",
@@ -36074,7 +36144,6 @@ var systemDaemonTimer = new SystemDaemonTimer();
36074
36144
 
36075
36145
  // src/run-daemon.ts
36076
36146
  var RELAY_RECONNECT_DELAY_MILLISECONDS = 500;
36077
- var ACTIVE_TURN_RECONCILIATION_CLOSE_CODE = 4009;
36078
36147
  function closeRelaySocket(socket, code, reason) {
36079
36148
  try {
36080
36149
  socket.close(code, reason);
@@ -36143,7 +36212,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36143
36212
  const relayUrl = new URL(config2.relayUrl);
36144
36213
  relayUrl.searchParams.set("liveness", "1");
36145
36214
  const socket = await connectRelay(relayUrl, signal);
36146
- const reconnectingTurns = [...activeTurns.values()];
36147
36215
  diagnostics.connectionOpened(connectionEpoch);
36148
36216
  const connectionController = new AbortController();
36149
36217
  const handleSettingsDiscovery = createAgentSettingsDiscoveryHandler({
@@ -36165,6 +36233,18 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36165
36233
  timer,
36166
36234
  resolveEnvironment: resolveAgentCatalogEnvironment
36167
36235
  });
36236
+ const activeTurnSnapshot = (sessionId) => {
36237
+ for (const turn of activeTurns.values()) {
36238
+ if (turn.command.sessionId !== sessionId) {
36239
+ continue;
36240
+ }
36241
+ const snapshot = turn.snapshot();
36242
+ if (snapshot !== null) {
36243
+ return snapshot;
36244
+ }
36245
+ }
36246
+ return null;
36247
+ };
36168
36248
  const nativeRequestHandler = createNativeSessionRequestHandler({
36169
36249
  audit,
36170
36250
  diagnostics,
@@ -36334,6 +36414,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36334
36414
  directories,
36335
36415
  audit,
36336
36416
  sessions,
36417
+ activeTurnSnapshot,
36337
36418
  connectionController.signal
36338
36419
  );
36339
36420
  return;
@@ -36347,6 +36428,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36347
36428
  directories,
36348
36429
  audit,
36349
36430
  sessions,
36431
+ activeTurnSnapshot,
36350
36432
  connectionController.signal
36351
36433
  );
36352
36434
  return;
@@ -36549,7 +36631,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36549
36631
  (waitSignal) => waitForSessionAvailability(command, turn, waitSignal),
36550
36632
  timer,
36551
36633
  turn.signal,
36552
- turn.recordText,
36634
+ turn.recordEvent,
36553
36635
  turn.cancellationRequested
36554
36636
  ).catch((error62) => {
36555
36637
  console.error("Mobius daemon turn failed", error62);
@@ -36570,43 +36652,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36570
36652
  socket.addEventListener("close", handleClose);
36571
36653
  socket.addEventListener("error", handleError);
36572
36654
  socket.addEventListener("message", handleMessage);
36573
- void reconcileActiveTurns(config2, reconnectingTurns, connectionController.signal).then(
36574
- () => {
36575
- if (finished) {
36576
- return;
36577
- }
36578
- publisher.connect(socket);
36579
- },
36580
- (error62) => {
36581
- if (finished) {
36582
- return;
36583
- }
36584
- console.error("Mobius daemon could not reconcile active Agent turns", error62);
36585
- if (error62 instanceof ActiveTurnReconciliationError && error62.terminal) {
36586
- diagnostics.reconciliationAbandoned(
36587
- connectionEpoch,
36588
- error62.relayErrorCode,
36589
- reconnectingTurns.length
36590
- );
36591
- console.error(
36592
- "Mobius daemon abandoned Agent turns the Relay already settled",
36593
- error62.relayErrorCode
36594
- );
36595
- for (const turn of reconnectingTurns) {
36596
- activeTurns.delete(turn.command.commandId);
36597
- turn.abortDaemon();
36598
- }
36599
- publisher.connect(socket);
36600
- return;
36601
- }
36602
- failAndClose(
36603
- new Error("Active Agent turn reconciliation failed", { cause: error62 }),
36604
- ACTIVE_TURN_RECONCILIATION_CLOSE_CODE,
36605
- "Active Agent turn reconciliation failed",
36606
- "reconciliation"
36607
- );
36608
- }
36609
- );
36655
+ publisher.connect(socket);
36610
36656
  if (signal.aborted) {
36611
36657
  stop();
36612
36658
  }
@@ -36638,7 +36684,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
36638
36684
  const activeTurns = /* @__PURE__ */ new Map();
36639
36685
  const recordSessionEvent = (sessionId, event) => {
36640
36686
  for (const turn of activeTurns.values()) {
36641
- turn.recordInteraction(event);
36687
+ turn.recordEvent(event);
36642
36688
  }
36643
36689
  publisher.publish(sessionId, event);
36644
36690
  };