@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/runtime.js CHANGED
@@ -20986,6 +20986,19 @@ var envelope = {
20986
20986
  requestId: identifierStringSchema,
20987
20987
  sessionId: identifierStringSchema
20988
20988
  };
20989
+ var activeTurnActivitySchema = external_exports.strictObject({
20990
+ activityId: external_exports.string().min(1).max(128),
20991
+ activityType: external_exports.string().min(1).max(128),
20992
+ content: external_exports.array(displayContentSchema).max(100).readonly(),
20993
+ input: external_exports.string().max(1e5),
20994
+ locations: external_exports.array(external_exports.string().min(1).max(2048)).max(100).readonly(),
20995
+ name: external_exports.string().max(128),
20996
+ output: external_exports.string().max(1e5),
20997
+ sequence: external_exports.number().int().nonnegative(),
20998
+ status: external_exports.string().min(1).max(64),
20999
+ title: external_exports.string().max(500),
21000
+ toolKind: external_exports.string().max(64)
21001
+ }).readonly();
20989
21002
  var identity = {
20990
21003
  ...envelope,
20991
21004
  kind: external_exports.literal(NATIVE_SESSION_REQUEST_KIND),
@@ -21061,7 +21074,9 @@ var nativeSessionResultSchema = external_exports.discriminatedUnion("action", [
21061
21074
  action: external_exports.literal("active-turn"),
21062
21075
  targetSessionId: identifierStringSchema,
21063
21076
  turn: external_exports.strictObject({
21077
+ activities: external_exports.array(activeTurnActivitySchema).max(100).readonly(),
21064
21078
  commandId: identifierStringSchema,
21079
+ content: external_exports.array(displayContentSchema).max(100).readonly(),
21065
21080
  prompt: external_exports.string().max(1e5),
21066
21081
  text: external_exports.string().max(ACTIVE_TURN_TEXT_LIMIT),
21067
21082
  truncated: external_exports.boolean(),
@@ -23291,6 +23306,18 @@ var CODEX_META_KEY = "codex";
23291
23306
  function truncate(value, limit) {
23292
23307
  return value.length <= limit ? value : value.slice(0, limit);
23293
23308
  }
23309
+ function boundedParagraphs(values, limit) {
23310
+ let text = "";
23311
+ for (const value of values) {
23312
+ const separator = text.length === 0 ? "" : "\n\n";
23313
+ const remaining = limit - text.length;
23314
+ if (remaining <= separator.length) {
23315
+ break;
23316
+ }
23317
+ text += `${separator}${value.slice(0, remaining - separator.length)}`;
23318
+ }
23319
+ return text;
23320
+ }
23294
23321
  function textContent(text) {
23295
23322
  const block = { text: truncate(text, TOOL_OUTPUT_CHARACTER_LIMIT), type: "text" };
23296
23323
  return { content: block, type: "content" };
@@ -23408,6 +23435,12 @@ function decodeThreadItem(value) {
23408
23435
  const decoded = threadItemSchema.safeParse(value);
23409
23436
  return decoded.success ? decoded.data : null;
23410
23437
  }
23438
+ function reasoningText(item) {
23439
+ if (item.type !== "reasoning") {
23440
+ return null;
23441
+ }
23442
+ return boundedParagraphs(item.summary.length > 0 ? item.summary : item.content, TOOL_OUTPUT_CHARACTER_LIMIT);
23443
+ }
23411
23444
  function agentMessageMeta(phase) {
23412
23445
  if (phase == null) {
23413
23446
  return null;
@@ -24176,6 +24209,19 @@ var CodexAcpAgent = class {
24176
24209
  });
24177
24210
  return;
24178
24211
  }
24212
+ const reasoning = reasoningText(item);
24213
+ if (reasoning !== null) {
24214
+ if (method === "item/completed" && reasoning.length > 0) {
24215
+ await this.#enqueue(async () => {
24216
+ await this.#emit({
24217
+ content: { text: reasoning, type: "text" },
24218
+ messageId: item.id,
24219
+ sessionUpdate: "agent_thought_chunk"
24220
+ });
24221
+ });
24222
+ }
24223
+ return;
24224
+ }
24179
24225
  const update = toolCallUpdate(item, method === "item/completed" ? "completed" : "started");
24180
24226
  if (update !== null) {
24181
24227
  await this.#enqueue(async () => {
@@ -31015,7 +31061,10 @@ function liveHistoryCoveredTurnRanges(history) {
31015
31061
  }
31016
31062
  return ranges;
31017
31063
  }
31018
- function paginateLiveSessionHistory(history, sessionId, cursor, limit) {
31064
+ function historyMessageCharacters(message) {
31065
+ return message.text.length + (message.role === "assistant" ? JSON.stringify(message.activities).length + JSON.stringify(message.content).length : 0);
31066
+ }
31067
+ function paginateAcpSessionHistory(history, sessionId, cursor, limit) {
31019
31068
  if (history.status === "unavailable") {
31020
31069
  if (cursor !== null) {
31021
31070
  throw new AcpExecutionError("Unavailable native Session history has no cursor", {}, "invalid_cursor");
@@ -31041,6 +31090,80 @@ function paginateLiveSessionHistory(history, sessionId, cursor, limit) {
31041
31090
  truncated: history.truncated
31042
31091
  };
31043
31092
  }
31093
+ function paginateLiveSessionHistory(history, activeTurn, sessionId, cursor, limit) {
31094
+ if (activeTurn === null || cursor !== null) {
31095
+ return paginateAcpSessionHistory(history, sessionId, cursor, limit);
31096
+ }
31097
+ const activeMessageOverhead = 4;
31098
+ const activeStructuredCharacters = JSON.stringify(activeTurn.activities).length + JSON.stringify(activeTurn.content).length;
31099
+ const maximumActiveTextLength = Math.max(
31100
+ 0,
31101
+ SESSION_HISTORY_CHARACTER_LIMIT - activeTurn.prompt.length - activeStructuredCharacters - activeMessageOverhead
31102
+ );
31103
+ const activeText = activeTurn.text.slice(-maximumActiveTextLength);
31104
+ const completeActiveMessages = [
31105
+ { role: "user", text: activeTurn.prompt },
31106
+ {
31107
+ activities: activeTurn.activities,
31108
+ content: activeTurn.content,
31109
+ role: "assistant",
31110
+ text: activeText
31111
+ }
31112
+ ];
31113
+ if (history.status === "unavailable") {
31114
+ return {
31115
+ coveredCommandIds: [],
31116
+ coveredMessageIds: [],
31117
+ messages: completeActiveMessages,
31118
+ nextCursor: null,
31119
+ status: "available",
31120
+ truncated: activeTurn.truncated || activeText.length !== activeTurn.text.length
31121
+ };
31122
+ }
31123
+ const latestNativeMessage = history.messages.at(-1);
31124
+ const activeMessages = latestNativeMessage?.role === "user" && latestNativeMessage.text === activeTurn.prompt ? completeActiveMessages.slice(1) : completeActiveMessages;
31125
+ let historicalMessageCount = 0;
31126
+ let remainingCharacters = SESSION_HISTORY_CHARACTER_LIMIT - activeText.length - activeMessageOverhead - activeStructuredCharacters - (activeMessages.length === completeActiveMessages.length ? activeTurn.prompt.length : 0);
31127
+ const historicalMessageLimit = Math.max(0, limit - activeMessages.length);
31128
+ for (let index = history.messages.length - 1; index >= 0 && historicalMessageCount < historicalMessageLimit; index -= 1) {
31129
+ const message = history.messages[index];
31130
+ if (message === void 0) {
31131
+ break;
31132
+ }
31133
+ const characters = historyMessageCharacters(message);
31134
+ if (characters > remainingCharacters) {
31135
+ break;
31136
+ }
31137
+ historicalMessageCount += 1;
31138
+ remainingCharacters -= characters;
31139
+ }
31140
+ const page = historicalMessageCount === 0 ? {
31141
+ coveredCommandIds: [],
31142
+ coveredMessageIds: [],
31143
+ messages: [],
31144
+ nextCursor: history.messages.length === 0 ? null : liveHistoryCursor(sessionId, history.messages.length),
31145
+ status: "available",
31146
+ truncated: history.truncated
31147
+ } : paginateAcpSessionHistory(history, sessionId, null, historicalMessageCount);
31148
+ return {
31149
+ ...page,
31150
+ messages: [...page.messages, ...activeMessages],
31151
+ truncated: page.truncated || activeTurn.truncated || activeText.length !== activeTurn.text.length
31152
+ };
31153
+ }
31154
+ function mergeLiveSessionHistory(history, activeTurn, sessionId) {
31155
+ const page = paginateLiveSessionHistory(history, activeTurn, sessionId, null, 1e3);
31156
+ if (page.status === "unavailable") {
31157
+ return { cause: page.cause, status: "unavailable" };
31158
+ }
31159
+ return {
31160
+ coveredCommandIds: page.coveredCommandIds,
31161
+ coveredMessageIds: page.coveredMessageIds,
31162
+ messages: page.messages,
31163
+ status: "available",
31164
+ truncated: page.truncated
31165
+ };
31166
+ }
31044
31167
 
31045
31168
  // src/prompt-artifact-resolver.ts
31046
31169
  import { createHash as createHash2 } from "node:crypto";
@@ -31672,7 +31795,7 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
31672
31795
  reportOperationFailure(socket, command.requestId, command.sessionId, error62, metrics.snapshot());
31673
31796
  }
31674
31797
  }
31675
- async function executeSessionLiveHistoryLoad(socket, command, config2, directories, audit, sessions, signal) {
31798
+ async function executeSessionLiveHistoryLoad(socket, command, config2, directories, audit, sessions, activeTurn, signal) {
31676
31799
  try {
31677
31800
  const resolved = await resolveSessionDirectories(
31678
31801
  directories,
@@ -31689,13 +31812,14 @@ async function executeSessionLiveHistoryLoad(socket, command, config2, directori
31689
31812
  signal
31690
31813
  });
31691
31814
  signal.throwIfAborted();
31815
+ const mergedHistory = mergeLiveSessionHistory(history, activeTurn(command.sessionId), command.sessionId);
31692
31816
  audit.record({
31693
31817
  commandId: command.requestId,
31694
31818
  event: "session_history_loaded",
31695
31819
  sessionId: command.sessionId
31696
31820
  });
31697
31821
  send(socket, {
31698
- history,
31822
+ history: mergedHistory,
31699
31823
  kind: "session.live-history.loaded",
31700
31824
  requestId: command.requestId,
31701
31825
  sessionId: command.sessionId
@@ -31721,7 +31845,7 @@ async function executeSessionLiveHistoryLoad(socket, command, config2, directori
31721
31845
  });
31722
31846
  }
31723
31847
  }
31724
- async function executeSessionLiveHistoryPageLoad(socket, command, config2, directories, audit, sessions, signal) {
31848
+ async function executeSessionLiveHistoryPageLoad(socket, command, config2, directories, audit, sessions, activeTurn, signal) {
31725
31849
  try {
31726
31850
  const resolved = await resolveSessionDirectories(
31727
31851
  directories,
@@ -31738,7 +31862,13 @@ async function executeSessionLiveHistoryPageLoad(socket, command, config2, direc
31738
31862
  signal
31739
31863
  });
31740
31864
  signal.throwIfAborted();
31741
- const page = paginateLiveSessionHistory(history, command.sessionId, command.cursor, command.limit);
31865
+ const page = paginateLiveSessionHistory(
31866
+ history,
31867
+ activeTurn(command.sessionId),
31868
+ command.sessionId,
31869
+ command.cursor,
31870
+ command.limit
31871
+ );
31742
31872
  audit.record({
31743
31873
  commandId: command.requestId,
31744
31874
  event: "session_history_loaded",
@@ -31811,14 +31941,11 @@ async function executeSessionConfigure(publisher, socket, command, config2, dire
31811
31941
  reportOperationFailure(socket, command.requestId, command.sessionId, error62);
31812
31942
  }
31813
31943
  }
31814
- async function executePrompt(operations, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, acknowledgeQueued, waitForSessionAvailability, timer, signal, recordLiveText, cancellationRequested) {
31815
- const activities = new CoalescingDaemonActivityPublisher(timer, (activity2) => {
31816
- publisher.publish(command.sessionId, daemonActivity(command, activity2));
31817
- });
31944
+ async function executePrompt(operations, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, acknowledgeQueued, waitForSessionAvailability, timer, signal, recordLiveEvent, cancellationRequested) {
31818
31945
  const narration = new CoalescingNarrationPublisher(
31819
31946
  timer,
31820
31947
  (increment) => {
31821
- publisher.publish(command.sessionId, {
31948
+ const event = {
31822
31949
  activityId: increment.activityId,
31823
31950
  activityType: increment.activityType,
31824
31951
  commandId: command.commandId,
@@ -31826,24 +31953,26 @@ async function executePrompt(operations, publisher, command, config2, directorie
31826
31953
  sequence: increment.sequence,
31827
31954
  sessionId: command.sessionId,
31828
31955
  text: increment.text
31829
- });
31956
+ };
31957
+ publisher.publish(command.sessionId, recordLiveEvent(event));
31830
31958
  },
31831
31959
  AGENT_ACTIVITY_COALESCING_MILLISECONDS,
31832
31960
  AGENT_TEXT_MAXIMUM_LENGTH
31833
31961
  );
31962
+ const activities = new CoalescingDaemonActivityPublisher(timer, (activity2) => {
31963
+ if (activity2.status !== "pending" && activity2.status !== "running") {
31964
+ narration.flush();
31965
+ }
31966
+ const event = daemonActivity(command, activity2);
31967
+ publisher.publish(command.sessionId, recordLiveEvent(event));
31968
+ });
31834
31969
  const text = new CoalescingTextPublisher(
31835
31970
  timer,
31836
31971
  (messageId, delta) => {
31837
- const stream = recordLiveText(delta);
31838
- publisher.publish(command.sessionId, {
31839
- commandId: command.commandId,
31840
- epoch: stream.epoch,
31841
- kind: AGENT_MESSAGE_DELTA_KIND,
31842
- messageId,
31843
- sequence: stream.sequence,
31844
- sessionId: command.sessionId,
31845
- text: delta
31846
- });
31972
+ publisher.publish(
31973
+ command.sessionId,
31974
+ recordLiveEvent({ kind: AGENT_MESSAGE_DELTA_KIND, messageId, text: delta })
31975
+ );
31847
31976
  },
31848
31977
  AGENT_TEXT_COALESCING_MILLISECONDS,
31849
31978
  AGENT_TEXT_MAXIMUM_LENGTH
@@ -33312,6 +33441,144 @@ var WorkspaceDirectoryService = class {
33312
33441
  };
33313
33442
  };
33314
33443
 
33444
+ // src/daemon-active-turn.ts
33445
+ import { randomUUID as randomUUID2 } from "node:crypto";
33446
+ var ActiveDaemonTurn = class {
33447
+ attemptId;
33448
+ command;
33449
+ #controller;
33450
+ #finished = Promise.withResolvers();
33451
+ #cancellationRequested = false;
33452
+ #dispatch;
33453
+ #text = "";
33454
+ #activities = /* @__PURE__ */ new Map();
33455
+ #content = /* @__PURE__ */ new Map();
33456
+ #truncated = false;
33457
+ #sequence = 0;
33458
+ #interaction = null;
33459
+ #epoch = decodeIdentifier(randomUUID2());
33460
+ constructor(command, attemptId) {
33461
+ this.attemptId = attemptId;
33462
+ this.command = command;
33463
+ this.#controller = new AbortController();
33464
+ this.#dispatch = command.disposition === SessionPromptDisposition.Queue ? { kind: "queued", promotion: Promise.withResolvers() } : { kind: "pending" };
33465
+ }
33466
+ abortDaemon = () => {
33467
+ this.#controller.abort();
33468
+ };
33469
+ finish = () => this.#finished.resolve();
33470
+ accept = () => {
33471
+ this.#dispatch = { kind: "accepted" };
33472
+ return { epoch: this.#epoch, sequence: 0 };
33473
+ };
33474
+ promoteQueuedPrompt = (command) => {
33475
+ if (command.commandId !== this.command.commandId || command.sessionId !== this.command.sessionId || this.#dispatch.kind !== "queued") {
33476
+ return false;
33477
+ }
33478
+ const promotion = this.#dispatch.promotion;
33479
+ this.#dispatch = { kind: "promoted" };
33480
+ promotion.resolve();
33481
+ return true;
33482
+ };
33483
+ queuePromotion = () => {
33484
+ if (this.#dispatch.kind === "queued") {
33485
+ return this.#dispatch.promotion.promise;
33486
+ }
33487
+ return this.#dispatch.kind === "promoted" ? Promise.resolve() : null;
33488
+ };
33489
+ effectiveDisposition = () => this.#dispatch.kind === "promoted" ? SessionPromptDisposition.Steer : this.command.disposition;
33490
+ recordEvent = (event) => {
33491
+ if (event.kind === AGENT_MESSAGE_DELTA_KIND) {
33492
+ this.#sequence += 1;
33493
+ this.#text += event.text;
33494
+ if (this.#text.length > ACTIVE_TURN_TEXT_LIMIT) {
33495
+ this.#text = this.#text.slice(-ACTIVE_TURN_TEXT_LIMIT);
33496
+ this.#truncated = true;
33497
+ }
33498
+ return {
33499
+ commandId: this.command.commandId,
33500
+ epoch: this.#epoch,
33501
+ kind: AGENT_MESSAGE_DELTA_KIND,
33502
+ messageId: event.messageId,
33503
+ sequence: this.#sequence,
33504
+ sessionId: this.command.sessionId,
33505
+ text: event.text
33506
+ };
33507
+ }
33508
+ if (event.sessionId !== this.command.sessionId || "commandId" in event && event.commandId !== this.command.commandId) {
33509
+ return event;
33510
+ }
33511
+ if (event.kind === AGENT_ACTIVITY_KIND) {
33512
+ this.#activities.set(event.activityId, {
33513
+ activityId: event.activityId,
33514
+ activityType: event.activityType,
33515
+ content: event.content,
33516
+ input: event.input,
33517
+ locations: event.locations,
33518
+ name: event.name,
33519
+ output: event.output,
33520
+ sequence: event.sequence,
33521
+ status: event.status,
33522
+ title: event.title,
33523
+ toolKind: event.toolKind
33524
+ });
33525
+ } else if (event.kind === AGENT_ACTIVITY_NARRATION_KIND) {
33526
+ const previous = this.#activities.get(event.activityId);
33527
+ this.#activities.set(event.activityId, {
33528
+ activityId: event.activityId,
33529
+ activityType: event.activityType,
33530
+ content: previous?.content ?? [],
33531
+ input: previous?.input ?? "",
33532
+ locations: previous?.locations ?? [],
33533
+ name: previous?.name ?? "",
33534
+ output: `${previous?.output ?? ""}${event.text}`,
33535
+ sequence: event.sequence,
33536
+ status: previous?.status ?? "running",
33537
+ title: previous?.title ?? "Thinking",
33538
+ toolKind: previous?.toolKind ?? ""
33539
+ });
33540
+ } else if (event.kind === AGENT_CONTENT_KIND) {
33541
+ this.#content.set(event.contentId, event.content);
33542
+ } else if (event.kind === SESSION_PERMISSION_REQUESTED_KIND || event.kind === SESSION_ELICITATION_REQUESTED_KIND) {
33543
+ this.#interaction = event;
33544
+ } else if ((event.kind === SESSION_PERMISSION_RESOLVED_KIND || event.kind === SESSION_ELICITATION_RESOLVED_KIND) && this.#interaction?.interactionId === event.interactionId) {
33545
+ this.#interaction = null;
33546
+ }
33547
+ return event;
33548
+ };
33549
+ snapshot = () => this.#dispatch.kind === "accepted" ? {
33550
+ activities: [...this.#activities.values()].sort((left, right) => left.sequence - right.sequence),
33551
+ commandId: decodeIdentifier(this.command.commandId),
33552
+ content: [...this.#content.values()],
33553
+ prompt: this.command.prompt,
33554
+ text: this.#text,
33555
+ truncated: this.#truncated,
33556
+ epoch: this.#epoch,
33557
+ interaction: this.#interaction,
33558
+ sequence: this.#sequence,
33559
+ state: "running"
33560
+ } : null;
33561
+ matches = (cancellation) => cancellation.commandId === this.command.commandId && cancellation.sessionId === this.command.sessionId;
33562
+ requestCancellation = () => {
33563
+ if (this.#cancellationRequested) {
33564
+ return "already-requested";
33565
+ }
33566
+ this.#cancellationRequested = true;
33567
+ if (this.#dispatch.kind !== "accepted") {
33568
+ this.#controller.abort(new Error("The queued Agent turn was cancelled"));
33569
+ return "pending";
33570
+ }
33571
+ return "running";
33572
+ };
33573
+ cancellationRequested = () => this.#cancellationRequested;
33574
+ get signal() {
33575
+ return this.#controller.signal;
33576
+ }
33577
+ get completion() {
33578
+ return this.#finished.promise;
33579
+ }
33580
+ };
33581
+
33315
33582
  // src/daemon-diagnostic-log.ts
33316
33583
  import { appendFileSync, mkdirSync, readFileSync as readFileSync2, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
33317
33584
  import { join as join16 } from "node:path";
@@ -33494,184 +33761,6 @@ var DaemonInstallationObserver = class {
33494
33761
  };
33495
33762
  };
33496
33763
 
33497
- // src/daemon-turn-reconciliation.ts
33498
- import { randomUUID as randomUUID2 } from "node:crypto";
33499
- import { fetch as fetch4 } from "undici";
33500
- var ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS = 2e4;
33501
- var ActiveDaemonTurn = class {
33502
- attemptId;
33503
- command;
33504
- #controller;
33505
- #finished = Promise.withResolvers();
33506
- #cancellationRequested = false;
33507
- #dispatch;
33508
- #text = "";
33509
- #truncated = false;
33510
- #sequence = 0;
33511
- #interaction = null;
33512
- #epoch = decodeIdentifier(randomUUID2());
33513
- constructor(command, attemptId) {
33514
- this.attemptId = attemptId;
33515
- this.command = command;
33516
- this.#controller = new AbortController();
33517
- this.#dispatch = command.disposition === SessionPromptDisposition.Queue ? { kind: "queued", promotion: Promise.withResolvers() } : { kind: "pending" };
33518
- }
33519
- abortDaemon = () => {
33520
- this.#controller.abort();
33521
- };
33522
- finish = () => this.#finished.resolve();
33523
- accept = () => {
33524
- this.#dispatch = { kind: "accepted" };
33525
- return { epoch: this.#epoch, sequence: 0 };
33526
- };
33527
- promoteQueuedPrompt = (command) => {
33528
- if (command.commandId !== this.command.commandId || command.sessionId !== this.command.sessionId || this.#dispatch.kind !== "queued") {
33529
- return false;
33530
- }
33531
- const promotion = this.#dispatch.promotion;
33532
- this.#dispatch = { kind: "promoted" };
33533
- promotion.resolve();
33534
- return true;
33535
- };
33536
- queuePromotion = () => {
33537
- if (this.#dispatch.kind === "queued") {
33538
- return this.#dispatch.promotion.promise;
33539
- }
33540
- return this.#dispatch.kind === "promoted" ? Promise.resolve() : null;
33541
- };
33542
- effectiveDisposition = () => this.#dispatch.kind === "promoted" ? SessionPromptDisposition.Steer : this.command.disposition;
33543
- recordText = (delta) => {
33544
- this.#sequence += 1;
33545
- this.#text += delta;
33546
- if (this.#text.length > ACTIVE_TURN_TEXT_LIMIT) {
33547
- this.#text = this.#text.slice(-ACTIVE_TURN_TEXT_LIMIT);
33548
- this.#truncated = true;
33549
- }
33550
- return { epoch: this.#epoch, sequence: this.#sequence };
33551
- };
33552
- recordInteraction = (event) => {
33553
- if (event.sessionId !== this.command.sessionId) {
33554
- return;
33555
- }
33556
- if (event.kind === SESSION_PERMISSION_REQUESTED_KIND || event.kind === SESSION_ELICITATION_REQUESTED_KIND) {
33557
- if (event.commandId === this.command.commandId) {
33558
- this.#interaction = event;
33559
- }
33560
- } else if ((event.kind === SESSION_PERMISSION_RESOLVED_KIND || event.kind === SESSION_ELICITATION_RESOLVED_KIND) && this.#interaction?.interactionId === event.interactionId) {
33561
- this.#interaction = null;
33562
- }
33563
- };
33564
- snapshot = () => this.#dispatch.kind === "accepted" ? {
33565
- commandId: decodeIdentifier(this.command.commandId),
33566
- prompt: this.command.prompt,
33567
- text: this.#text,
33568
- truncated: this.#truncated,
33569
- epoch: this.#epoch,
33570
- interaction: this.#interaction,
33571
- sequence: this.#sequence,
33572
- state: "running"
33573
- } : null;
33574
- matches = (cancellation) => cancellation.commandId === this.command.commandId && cancellation.sessionId === this.command.sessionId;
33575
- requestCancellation = () => {
33576
- if (this.#cancellationRequested) {
33577
- return "already-requested";
33578
- }
33579
- this.#cancellationRequested = true;
33580
- if (this.#dispatch.kind !== "accepted") {
33581
- this.#controller.abort(new Error("The queued Agent turn was cancelled"));
33582
- return "pending";
33583
- }
33584
- return "running";
33585
- };
33586
- cancellationRequested = () => this.#cancellationRequested;
33587
- get signal() {
33588
- return this.#controller.signal;
33589
- }
33590
- get completion() {
33591
- return this.#finished.promise;
33592
- }
33593
- };
33594
- var ActiveTurnReconciliationError = class extends Error {
33595
- code = "active_turn_reconciliation_failed";
33596
- diagnosticDetails;
33597
- relayErrorCode;
33598
- terminal;
33599
- constructor(message, options = {}) {
33600
- super(message, options);
33601
- this.name = "ActiveTurnReconciliationError";
33602
- this.relayErrorCode = options.relayErrorCode ?? null;
33603
- this.terminal = options.terminal ?? false;
33604
- this.diagnosticDetails = this.relayErrorCode === null ? {} : { relayErrorCode: this.relayErrorCode };
33605
- }
33606
- };
33607
- var TERMINAL_RECONCILIATION_RELAY_CODES = /* @__PURE__ */ new Set(["session_conflict"]);
33608
- async function relayErrorCode(response) {
33609
- try {
33610
- const body = JSON.parse(await response.text());
33611
- if (typeof body !== "object" || body === null) {
33612
- return null;
33613
- }
33614
- const error62 = Reflect.get(body, "error");
33615
- if (typeof error62 !== "object" || error62 === null) {
33616
- return null;
33617
- }
33618
- const code = Reflect.get(error62, "code");
33619
- return typeof code === "string" && code.length > 0 ? code : null;
33620
- } catch {
33621
- return null;
33622
- }
33623
- }
33624
- function activeTurnReconciliationEndpoint(config2, turn) {
33625
- const endpoint = relayHttpEndpoint(config2.relayUrl);
33626
- let channelPath = "";
33627
- if (endpoint.pathname.endsWith("/daemon")) {
33628
- channelPath = endpoint.pathname.slice(0, -"/daemon".length);
33629
- } else {
33630
- const runtimePath = "/v1/runtimes/connect";
33631
- if (!endpoint.pathname.endsWith(runtimePath)) {
33632
- throw new ActiveTurnReconciliationError("The Relay URL is invalid");
33633
- }
33634
- channelPath = `${endpoint.pathname.slice(0, -runtimePath.length)}/channels/${encodeURIComponent(config2.channelId)}`;
33635
- }
33636
- endpoint.pathname = `${channelPath}/sessions/${encodeURIComponent(turn.command.sessionId)}/attempts/${encodeURIComponent(turn.attemptId)}/reconciliation`;
33637
- return endpoint;
33638
- }
33639
- async function reconcileActiveTurn(config2, turn, signal) {
33640
- signal.throwIfAborted();
33641
- const timeoutSignal = AbortSignal.timeout(ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS);
33642
- const requestSignal = AbortSignal.any([signal, timeoutSignal]);
33643
- let response;
33644
- try {
33645
- response = await fetch4(activeTurnReconciliationEndpoint(config2, turn), {
33646
- body: JSON.stringify({ outcome: { kind: "running" } }),
33647
- dispatcher: environmentProxyDispatcher,
33648
- headers: { ...runtimeAuthorization(config2.relayUrl), "content-type": "application/json" },
33649
- method: "POST",
33650
- signal: requestSignal
33651
- });
33652
- } catch (error62) {
33653
- if (signal.aborted) {
33654
- signal.throwIfAborted();
33655
- }
33656
- throw new ActiveTurnReconciliationError(
33657
- timeoutSignal.aborted ? "The active Agent turn reconciliation timed out" : "The active Agent turn could not be reconciled",
33658
- { cause: error62 }
33659
- );
33660
- }
33661
- if (!response.ok) {
33662
- const errorCode = await relayErrorCode(response);
33663
- const terminal = errorCode !== null && TERMINAL_RECONCILIATION_RELAY_CODES.has(errorCode);
33664
- throw new ActiveTurnReconciliationError(
33665
- 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()}`,
33666
- { relayErrorCode: errorCode, terminal }
33667
- );
33668
- }
33669
- await response.body?.cancel();
33670
- }
33671
- async function reconcileActiveTurns(config2, turns, signal) {
33672
- await Promise.all(turns.map(async (turn) => await reconcileActiveTurn(config2, turn, signal)));
33673
- }
33674
-
33675
33764
  // src/native-sessions/codex-history.ts
33676
33765
  import { spawn as spawn5 } from "node:child_process";
33677
33766
  var responseSchema = external_exports.union([
@@ -34970,25 +35059,6 @@ var RelayConnectionDiagnostics = class {
34970
35059
  addFailureDetails(details, failure2);
34971
35060
  this.#record("relay_connection_failed", connectionEpoch.toString(), details, true);
34972
35061
  };
34973
- /**
34974
- * Records that the Runtime gave up on Agent turns the Relay already settled. This is not a connection
34975
- * failure, so it is recorded independently of the per-epoch failure deduplication.
34976
- */
34977
- reconciliationAbandoned = (connectionEpoch, relayErrorCode2, turnCount) => {
34978
- this.#record(
34979
- "relay_reconciliation_abandoned",
34980
- connectionEpoch.toString(),
34981
- {
34982
- connectionEpoch: connectionEpoch.toString(),
34983
- relayErrorCode: relayErrorCode2 ?? "unknown",
34984
- relayOrigin: this.#relayOrigin,
34985
- source: "reconciliation_abandoned",
34986
- turnCount: turnCount.toString(),
34987
- ...this.#route
34988
- },
34989
- true
34990
- );
34991
- };
34992
35062
  connectionOpened = (connectionEpoch) => {
34993
35063
  this.#record(
34994
35064
  "relay_connection_opened",
@@ -35216,7 +35286,6 @@ var systemDaemonTimer = new SystemDaemonTimer();
35216
35286
 
35217
35287
  // src/run-daemon.ts
35218
35288
  var RELAY_RECONNECT_DELAY_MILLISECONDS = 500;
35219
- var ACTIVE_TURN_RECONCILIATION_CLOSE_CODE = 4009;
35220
35289
  function closeRelaySocket(socket, code, reason) {
35221
35290
  try {
35222
35291
  socket.close(code, reason);
@@ -35285,7 +35354,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
35285
35354
  const relayUrl = new URL(config2.relayUrl);
35286
35355
  relayUrl.searchParams.set("liveness", "1");
35287
35356
  const socket = await connectRelay(relayUrl, signal);
35288
- const reconnectingTurns = [...activeTurns.values()];
35289
35357
  diagnostics.connectionOpened(connectionEpoch);
35290
35358
  const connectionController = new AbortController();
35291
35359
  const handleSettingsDiscovery = createAgentSettingsDiscoveryHandler({
@@ -35307,6 +35375,18 @@ async function runRelayConnection(config2, directories, audit, sessions, install
35307
35375
  timer,
35308
35376
  resolveEnvironment: resolveAgentCatalogEnvironment
35309
35377
  });
35378
+ const activeTurnSnapshot = (sessionId) => {
35379
+ for (const turn of activeTurns.values()) {
35380
+ if (turn.command.sessionId !== sessionId) {
35381
+ continue;
35382
+ }
35383
+ const snapshot = turn.snapshot();
35384
+ if (snapshot !== null) {
35385
+ return snapshot;
35386
+ }
35387
+ }
35388
+ return null;
35389
+ };
35310
35390
  const nativeRequestHandler = createNativeSessionRequestHandler({
35311
35391
  audit,
35312
35392
  diagnostics,
@@ -35476,6 +35556,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
35476
35556
  directories,
35477
35557
  audit,
35478
35558
  sessions,
35559
+ activeTurnSnapshot,
35479
35560
  connectionController.signal
35480
35561
  );
35481
35562
  return;
@@ -35489,6 +35570,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
35489
35570
  directories,
35490
35571
  audit,
35491
35572
  sessions,
35573
+ activeTurnSnapshot,
35492
35574
  connectionController.signal
35493
35575
  );
35494
35576
  return;
@@ -35691,7 +35773,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
35691
35773
  (waitSignal) => waitForSessionAvailability(command, turn, waitSignal),
35692
35774
  timer,
35693
35775
  turn.signal,
35694
- turn.recordText,
35776
+ turn.recordEvent,
35695
35777
  turn.cancellationRequested
35696
35778
  ).catch((error62) => {
35697
35779
  console.error("Mobius daemon turn failed", error62);
@@ -35712,43 +35794,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
35712
35794
  socket.addEventListener("close", handleClose);
35713
35795
  socket.addEventListener("error", handleError);
35714
35796
  socket.addEventListener("message", handleMessage);
35715
- void reconcileActiveTurns(config2, reconnectingTurns, connectionController.signal).then(
35716
- () => {
35717
- if (finished) {
35718
- return;
35719
- }
35720
- publisher.connect(socket);
35721
- },
35722
- (error62) => {
35723
- if (finished) {
35724
- return;
35725
- }
35726
- console.error("Mobius daemon could not reconcile active Agent turns", error62);
35727
- if (error62 instanceof ActiveTurnReconciliationError && error62.terminal) {
35728
- diagnostics.reconciliationAbandoned(
35729
- connectionEpoch,
35730
- error62.relayErrorCode,
35731
- reconnectingTurns.length
35732
- );
35733
- console.error(
35734
- "Mobius daemon abandoned Agent turns the Relay already settled",
35735
- error62.relayErrorCode
35736
- );
35737
- for (const turn of reconnectingTurns) {
35738
- activeTurns.delete(turn.command.commandId);
35739
- turn.abortDaemon();
35740
- }
35741
- publisher.connect(socket);
35742
- return;
35743
- }
35744
- failAndClose(
35745
- new Error("Active Agent turn reconciliation failed", { cause: error62 }),
35746
- ACTIVE_TURN_RECONCILIATION_CLOSE_CODE,
35747
- "Active Agent turn reconciliation failed",
35748
- "reconciliation"
35749
- );
35750
- }
35751
- );
35797
+ publisher.connect(socket);
35752
35798
  if (signal.aborted) {
35753
35799
  stop();
35754
35800
  }
@@ -35780,7 +35826,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
35780
35826
  const activeTurns = /* @__PURE__ */ new Map();
35781
35827
  const recordSessionEvent = (sessionId, event) => {
35782
35828
  for (const turn of activeTurns.values()) {
35783
- turn.recordInteraction(event);
35829
+ turn.recordEvent(event);
35784
35830
  }
35785
35831
  publisher.publish(sessionId, event);
35786
35832
  };
@@ -35948,7 +35994,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
35948
35994
  import { mkdir as mkdir5, realpath as realpath9, stat as stat8 } from "node:fs/promises";
35949
35995
  import { hostname as hostname3 } from "node:os";
35950
35996
  import { basename as basename6, resolve as resolve6 } from "node:path";
35951
- import { fetch as fetch5 } from "undici";
35997
+ import { fetch as fetch4 } from "undici";
35952
35998
 
35953
35999
  // src/storage/runtime-installation-store.ts
35954
36000
  import { createHash as createHash5, randomUUID as randomUUID7 } from "node:crypto";
@@ -36583,7 +36629,7 @@ async function claimPairing(options, defaultWorkspace, localAgents, installableA
36583
36629
  const endpoint = options.pairingId.length > 0 ? mobiusApiUrl(options.relayOrigin, `/v1/runtime-pairings/${encodeURIComponent(options.pairingId)}/redeem`) : mobiusApiUrl(options.relayOrigin, "/pairings/claim");
36584
36630
  let response;
36585
36631
  try {
36586
- response = await fetch5(endpoint, {
36632
+ response = await fetch4(endpoint, {
36587
36633
  body: JSON.stringify({
36588
36634
  agents,
36589
36635
  installableAgents,