@moxt-ai/mobius 0.0.113 → 0.0.115

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.
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(),
@@ -31015,7 +31030,10 @@ function liveHistoryCoveredTurnRanges(history) {
31015
31030
  }
31016
31031
  return ranges;
31017
31032
  }
31018
- function paginateLiveSessionHistory(history, sessionId, cursor, limit) {
31033
+ function historyMessageCharacters(message) {
31034
+ return message.text.length + (message.role === "assistant" ? JSON.stringify(message.activities).length + JSON.stringify(message.content).length : 0);
31035
+ }
31036
+ function paginateAcpSessionHistory(history, sessionId, cursor, limit) {
31019
31037
  if (history.status === "unavailable") {
31020
31038
  if (cursor !== null) {
31021
31039
  throw new AcpExecutionError("Unavailable native Session history has no cursor", {}, "invalid_cursor");
@@ -31041,6 +31059,80 @@ function paginateLiveSessionHistory(history, sessionId, cursor, limit) {
31041
31059
  truncated: history.truncated
31042
31060
  };
31043
31061
  }
31062
+ function paginateLiveSessionHistory(history, activeTurn, sessionId, cursor, limit) {
31063
+ if (activeTurn === null || cursor !== null) {
31064
+ return paginateAcpSessionHistory(history, sessionId, cursor, limit);
31065
+ }
31066
+ const activeMessageOverhead = 4;
31067
+ const activeStructuredCharacters = JSON.stringify(activeTurn.activities).length + JSON.stringify(activeTurn.content).length;
31068
+ const maximumActiveTextLength = Math.max(
31069
+ 0,
31070
+ SESSION_HISTORY_CHARACTER_LIMIT - activeTurn.prompt.length - activeStructuredCharacters - activeMessageOverhead
31071
+ );
31072
+ const activeText = activeTurn.text.slice(-maximumActiveTextLength);
31073
+ const completeActiveMessages = [
31074
+ { role: "user", text: activeTurn.prompt },
31075
+ {
31076
+ activities: activeTurn.activities,
31077
+ content: activeTurn.content,
31078
+ role: "assistant",
31079
+ text: activeText
31080
+ }
31081
+ ];
31082
+ if (history.status === "unavailable") {
31083
+ return {
31084
+ coveredCommandIds: [],
31085
+ coveredMessageIds: [],
31086
+ messages: completeActiveMessages,
31087
+ nextCursor: null,
31088
+ status: "available",
31089
+ truncated: activeTurn.truncated || activeText.length !== activeTurn.text.length
31090
+ };
31091
+ }
31092
+ const latestNativeMessage = history.messages.at(-1);
31093
+ const activeMessages = latestNativeMessage?.role === "user" && latestNativeMessage.text === activeTurn.prompt ? completeActiveMessages.slice(1) : completeActiveMessages;
31094
+ let historicalMessageCount = 0;
31095
+ let remainingCharacters = SESSION_HISTORY_CHARACTER_LIMIT - activeText.length - activeMessageOverhead - activeStructuredCharacters - (activeMessages.length === completeActiveMessages.length ? activeTurn.prompt.length : 0);
31096
+ const historicalMessageLimit = Math.max(0, limit - activeMessages.length);
31097
+ for (let index = history.messages.length - 1; index >= 0 && historicalMessageCount < historicalMessageLimit; index -= 1) {
31098
+ const message = history.messages[index];
31099
+ if (message === void 0) {
31100
+ break;
31101
+ }
31102
+ const characters = historyMessageCharacters(message);
31103
+ if (characters > remainingCharacters) {
31104
+ break;
31105
+ }
31106
+ historicalMessageCount += 1;
31107
+ remainingCharacters -= characters;
31108
+ }
31109
+ const page = historicalMessageCount === 0 ? {
31110
+ coveredCommandIds: [],
31111
+ coveredMessageIds: [],
31112
+ messages: [],
31113
+ nextCursor: history.messages.length === 0 ? null : liveHistoryCursor(sessionId, history.messages.length),
31114
+ status: "available",
31115
+ truncated: history.truncated
31116
+ } : paginateAcpSessionHistory(history, sessionId, null, historicalMessageCount);
31117
+ return {
31118
+ ...page,
31119
+ messages: [...page.messages, ...activeMessages],
31120
+ truncated: page.truncated || activeTurn.truncated || activeText.length !== activeTurn.text.length
31121
+ };
31122
+ }
31123
+ function mergeLiveSessionHistory(history, activeTurn, sessionId) {
31124
+ const page = paginateLiveSessionHistory(history, activeTurn, sessionId, null, 1e3);
31125
+ if (page.status === "unavailable") {
31126
+ return { cause: page.cause, status: "unavailable" };
31127
+ }
31128
+ return {
31129
+ coveredCommandIds: page.coveredCommandIds,
31130
+ coveredMessageIds: page.coveredMessageIds,
31131
+ messages: page.messages,
31132
+ status: "available",
31133
+ truncated: page.truncated
31134
+ };
31135
+ }
31044
31136
 
31045
31137
  // src/prompt-artifact-resolver.ts
31046
31138
  import { createHash as createHash2 } from "node:crypto";
@@ -31672,7 +31764,7 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
31672
31764
  reportOperationFailure(socket, command.requestId, command.sessionId, error62, metrics.snapshot());
31673
31765
  }
31674
31766
  }
31675
- async function executeSessionLiveHistoryLoad(socket, command, config2, directories, audit, sessions, signal) {
31767
+ async function executeSessionLiveHistoryLoad(socket, command, config2, directories, audit, sessions, activeTurn, signal) {
31676
31768
  try {
31677
31769
  const resolved = await resolveSessionDirectories(
31678
31770
  directories,
@@ -31689,13 +31781,14 @@ async function executeSessionLiveHistoryLoad(socket, command, config2, directori
31689
31781
  signal
31690
31782
  });
31691
31783
  signal.throwIfAborted();
31784
+ const mergedHistory = mergeLiveSessionHistory(history, activeTurn(command.sessionId), command.sessionId);
31692
31785
  audit.record({
31693
31786
  commandId: command.requestId,
31694
31787
  event: "session_history_loaded",
31695
31788
  sessionId: command.sessionId
31696
31789
  });
31697
31790
  send(socket, {
31698
- history,
31791
+ history: mergedHistory,
31699
31792
  kind: "session.live-history.loaded",
31700
31793
  requestId: command.requestId,
31701
31794
  sessionId: command.sessionId
@@ -31721,7 +31814,7 @@ async function executeSessionLiveHistoryLoad(socket, command, config2, directori
31721
31814
  });
31722
31815
  }
31723
31816
  }
31724
- async function executeSessionLiveHistoryPageLoad(socket, command, config2, directories, audit, sessions, signal) {
31817
+ async function executeSessionLiveHistoryPageLoad(socket, command, config2, directories, audit, sessions, activeTurn, signal) {
31725
31818
  try {
31726
31819
  const resolved = await resolveSessionDirectories(
31727
31820
  directories,
@@ -31738,7 +31831,13 @@ async function executeSessionLiveHistoryPageLoad(socket, command, config2, direc
31738
31831
  signal
31739
31832
  });
31740
31833
  signal.throwIfAborted();
31741
- const page = paginateLiveSessionHistory(history, command.sessionId, command.cursor, command.limit);
31834
+ const page = paginateLiveSessionHistory(
31835
+ history,
31836
+ activeTurn(command.sessionId),
31837
+ command.sessionId,
31838
+ command.cursor,
31839
+ command.limit
31840
+ );
31742
31841
  audit.record({
31743
31842
  commandId: command.requestId,
31744
31843
  event: "session_history_loaded",
@@ -31811,14 +31910,11 @@ async function executeSessionConfigure(publisher, socket, command, config2, dire
31811
31910
  reportOperationFailure(socket, command.requestId, command.sessionId, error62);
31812
31911
  }
31813
31912
  }
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
- });
31913
+ async function executePrompt(operations, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, acknowledgeQueued, waitForSessionAvailability, timer, signal, recordLiveEvent, cancellationRequested) {
31818
31914
  const narration = new CoalescingNarrationPublisher(
31819
31915
  timer,
31820
31916
  (increment) => {
31821
- publisher.publish(command.sessionId, {
31917
+ const event = {
31822
31918
  activityId: increment.activityId,
31823
31919
  activityType: increment.activityType,
31824
31920
  commandId: command.commandId,
@@ -31826,24 +31922,26 @@ async function executePrompt(operations, publisher, command, config2, directorie
31826
31922
  sequence: increment.sequence,
31827
31923
  sessionId: command.sessionId,
31828
31924
  text: increment.text
31829
- });
31925
+ };
31926
+ publisher.publish(command.sessionId, recordLiveEvent(event));
31830
31927
  },
31831
31928
  AGENT_ACTIVITY_COALESCING_MILLISECONDS,
31832
31929
  AGENT_TEXT_MAXIMUM_LENGTH
31833
31930
  );
31931
+ const activities = new CoalescingDaemonActivityPublisher(timer, (activity2) => {
31932
+ if (activity2.status !== "pending" && activity2.status !== "running") {
31933
+ narration.flush();
31934
+ }
31935
+ const event = daemonActivity(command, activity2);
31936
+ publisher.publish(command.sessionId, recordLiveEvent(event));
31937
+ });
31834
31938
  const text = new CoalescingTextPublisher(
31835
31939
  timer,
31836
31940
  (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
- });
31941
+ publisher.publish(
31942
+ command.sessionId,
31943
+ recordLiveEvent({ kind: AGENT_MESSAGE_DELTA_KIND, messageId, text: delta })
31944
+ );
31847
31945
  },
31848
31946
  AGENT_TEXT_COALESCING_MILLISECONDS,
31849
31947
  AGENT_TEXT_MAXIMUM_LENGTH
@@ -33312,6 +33410,144 @@ var WorkspaceDirectoryService = class {
33312
33410
  };
33313
33411
  };
33314
33412
 
33413
+ // src/daemon-active-turn.ts
33414
+ import { randomUUID as randomUUID2 } from "node:crypto";
33415
+ var ActiveDaemonTurn = class {
33416
+ attemptId;
33417
+ command;
33418
+ #controller;
33419
+ #finished = Promise.withResolvers();
33420
+ #cancellationRequested = false;
33421
+ #dispatch;
33422
+ #text = "";
33423
+ #activities = /* @__PURE__ */ new Map();
33424
+ #content = /* @__PURE__ */ new Map();
33425
+ #truncated = false;
33426
+ #sequence = 0;
33427
+ #interaction = null;
33428
+ #epoch = decodeIdentifier(randomUUID2());
33429
+ constructor(command, attemptId) {
33430
+ this.attemptId = attemptId;
33431
+ this.command = command;
33432
+ this.#controller = new AbortController();
33433
+ this.#dispatch = command.disposition === SessionPromptDisposition.Queue ? { kind: "queued", promotion: Promise.withResolvers() } : { kind: "pending" };
33434
+ }
33435
+ abortDaemon = () => {
33436
+ this.#controller.abort();
33437
+ };
33438
+ finish = () => this.#finished.resolve();
33439
+ accept = () => {
33440
+ this.#dispatch = { kind: "accepted" };
33441
+ return { epoch: this.#epoch, sequence: 0 };
33442
+ };
33443
+ promoteQueuedPrompt = (command) => {
33444
+ if (command.commandId !== this.command.commandId || command.sessionId !== this.command.sessionId || this.#dispatch.kind !== "queued") {
33445
+ return false;
33446
+ }
33447
+ const promotion = this.#dispatch.promotion;
33448
+ this.#dispatch = { kind: "promoted" };
33449
+ promotion.resolve();
33450
+ return true;
33451
+ };
33452
+ queuePromotion = () => {
33453
+ if (this.#dispatch.kind === "queued") {
33454
+ return this.#dispatch.promotion.promise;
33455
+ }
33456
+ return this.#dispatch.kind === "promoted" ? Promise.resolve() : null;
33457
+ };
33458
+ effectiveDisposition = () => this.#dispatch.kind === "promoted" ? SessionPromptDisposition.Steer : this.command.disposition;
33459
+ recordEvent = (event) => {
33460
+ if (event.kind === AGENT_MESSAGE_DELTA_KIND) {
33461
+ this.#sequence += 1;
33462
+ this.#text += event.text;
33463
+ if (this.#text.length > ACTIVE_TURN_TEXT_LIMIT) {
33464
+ this.#text = this.#text.slice(-ACTIVE_TURN_TEXT_LIMIT);
33465
+ this.#truncated = true;
33466
+ }
33467
+ return {
33468
+ commandId: this.command.commandId,
33469
+ epoch: this.#epoch,
33470
+ kind: AGENT_MESSAGE_DELTA_KIND,
33471
+ messageId: event.messageId,
33472
+ sequence: this.#sequence,
33473
+ sessionId: this.command.sessionId,
33474
+ text: event.text
33475
+ };
33476
+ }
33477
+ if (event.sessionId !== this.command.sessionId || "commandId" in event && event.commandId !== this.command.commandId) {
33478
+ return event;
33479
+ }
33480
+ if (event.kind === AGENT_ACTIVITY_KIND) {
33481
+ this.#activities.set(event.activityId, {
33482
+ activityId: event.activityId,
33483
+ activityType: event.activityType,
33484
+ content: event.content,
33485
+ input: event.input,
33486
+ locations: event.locations,
33487
+ name: event.name,
33488
+ output: event.output,
33489
+ sequence: event.sequence,
33490
+ status: event.status,
33491
+ title: event.title,
33492
+ toolKind: event.toolKind
33493
+ });
33494
+ } else if (event.kind === AGENT_ACTIVITY_NARRATION_KIND) {
33495
+ const previous = this.#activities.get(event.activityId);
33496
+ this.#activities.set(event.activityId, {
33497
+ activityId: event.activityId,
33498
+ activityType: event.activityType,
33499
+ content: previous?.content ?? [],
33500
+ input: previous?.input ?? "",
33501
+ locations: previous?.locations ?? [],
33502
+ name: previous?.name ?? "",
33503
+ output: `${previous?.output ?? ""}${event.text}`,
33504
+ sequence: event.sequence,
33505
+ status: previous?.status ?? "running",
33506
+ title: previous?.title ?? "Thinking",
33507
+ toolKind: previous?.toolKind ?? ""
33508
+ });
33509
+ } else if (event.kind === AGENT_CONTENT_KIND) {
33510
+ this.#content.set(event.contentId, event.content);
33511
+ } else if (event.kind === SESSION_PERMISSION_REQUESTED_KIND || event.kind === SESSION_ELICITATION_REQUESTED_KIND) {
33512
+ this.#interaction = event;
33513
+ } else if ((event.kind === SESSION_PERMISSION_RESOLVED_KIND || event.kind === SESSION_ELICITATION_RESOLVED_KIND) && this.#interaction?.interactionId === event.interactionId) {
33514
+ this.#interaction = null;
33515
+ }
33516
+ return event;
33517
+ };
33518
+ snapshot = () => this.#dispatch.kind === "accepted" ? {
33519
+ activities: [...this.#activities.values()].sort((left, right) => left.sequence - right.sequence),
33520
+ commandId: decodeIdentifier(this.command.commandId),
33521
+ content: [...this.#content.values()],
33522
+ prompt: this.command.prompt,
33523
+ text: this.#text,
33524
+ truncated: this.#truncated,
33525
+ epoch: this.#epoch,
33526
+ interaction: this.#interaction,
33527
+ sequence: this.#sequence,
33528
+ state: "running"
33529
+ } : null;
33530
+ matches = (cancellation) => cancellation.commandId === this.command.commandId && cancellation.sessionId === this.command.sessionId;
33531
+ requestCancellation = () => {
33532
+ if (this.#cancellationRequested) {
33533
+ return "already-requested";
33534
+ }
33535
+ this.#cancellationRequested = true;
33536
+ if (this.#dispatch.kind !== "accepted") {
33537
+ this.#controller.abort(new Error("The queued Agent turn was cancelled"));
33538
+ return "pending";
33539
+ }
33540
+ return "running";
33541
+ };
33542
+ cancellationRequested = () => this.#cancellationRequested;
33543
+ get signal() {
33544
+ return this.#controller.signal;
33545
+ }
33546
+ get completion() {
33547
+ return this.#finished.promise;
33548
+ }
33549
+ };
33550
+
33315
33551
  // src/daemon-diagnostic-log.ts
33316
33552
  import { appendFileSync, mkdirSync, readFileSync as readFileSync2, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
33317
33553
  import { join as join16 } from "node:path";
@@ -33494,184 +33730,6 @@ var DaemonInstallationObserver = class {
33494
33730
  };
33495
33731
  };
33496
33732
 
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
33733
  // src/native-sessions/codex-history.ts
33676
33734
  import { spawn as spawn5 } from "node:child_process";
33677
33735
  var responseSchema = external_exports.union([
@@ -34970,25 +35028,6 @@ var RelayConnectionDiagnostics = class {
34970
35028
  addFailureDetails(details, failure2);
34971
35029
  this.#record("relay_connection_failed", connectionEpoch.toString(), details, true);
34972
35030
  };
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
35031
  connectionOpened = (connectionEpoch) => {
34993
35032
  this.#record(
34994
35033
  "relay_connection_opened",
@@ -35216,7 +35255,6 @@ var systemDaemonTimer = new SystemDaemonTimer();
35216
35255
 
35217
35256
  // src/run-daemon.ts
35218
35257
  var RELAY_RECONNECT_DELAY_MILLISECONDS = 500;
35219
- var ACTIVE_TURN_RECONCILIATION_CLOSE_CODE = 4009;
35220
35258
  function closeRelaySocket(socket, code, reason) {
35221
35259
  try {
35222
35260
  socket.close(code, reason);
@@ -35285,7 +35323,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
35285
35323
  const relayUrl = new URL(config2.relayUrl);
35286
35324
  relayUrl.searchParams.set("liveness", "1");
35287
35325
  const socket = await connectRelay(relayUrl, signal);
35288
- const reconnectingTurns = [...activeTurns.values()];
35289
35326
  diagnostics.connectionOpened(connectionEpoch);
35290
35327
  const connectionController = new AbortController();
35291
35328
  const handleSettingsDiscovery = createAgentSettingsDiscoveryHandler({
@@ -35307,6 +35344,18 @@ async function runRelayConnection(config2, directories, audit, sessions, install
35307
35344
  timer,
35308
35345
  resolveEnvironment: resolveAgentCatalogEnvironment
35309
35346
  });
35347
+ const activeTurnSnapshot = (sessionId) => {
35348
+ for (const turn of activeTurns.values()) {
35349
+ if (turn.command.sessionId !== sessionId) {
35350
+ continue;
35351
+ }
35352
+ const snapshot = turn.snapshot();
35353
+ if (snapshot !== null) {
35354
+ return snapshot;
35355
+ }
35356
+ }
35357
+ return null;
35358
+ };
35310
35359
  const nativeRequestHandler = createNativeSessionRequestHandler({
35311
35360
  audit,
35312
35361
  diagnostics,
@@ -35476,6 +35525,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
35476
35525
  directories,
35477
35526
  audit,
35478
35527
  sessions,
35528
+ activeTurnSnapshot,
35479
35529
  connectionController.signal
35480
35530
  );
35481
35531
  return;
@@ -35489,6 +35539,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
35489
35539
  directories,
35490
35540
  audit,
35491
35541
  sessions,
35542
+ activeTurnSnapshot,
35492
35543
  connectionController.signal
35493
35544
  );
35494
35545
  return;
@@ -35691,7 +35742,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
35691
35742
  (waitSignal) => waitForSessionAvailability(command, turn, waitSignal),
35692
35743
  timer,
35693
35744
  turn.signal,
35694
- turn.recordText,
35745
+ turn.recordEvent,
35695
35746
  turn.cancellationRequested
35696
35747
  ).catch((error62) => {
35697
35748
  console.error("Mobius daemon turn failed", error62);
@@ -35712,43 +35763,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
35712
35763
  socket.addEventListener("close", handleClose);
35713
35764
  socket.addEventListener("error", handleError);
35714
35765
  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
- );
35766
+ publisher.connect(socket);
35752
35767
  if (signal.aborted) {
35753
35768
  stop();
35754
35769
  }
@@ -35780,7 +35795,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
35780
35795
  const activeTurns = /* @__PURE__ */ new Map();
35781
35796
  const recordSessionEvent = (sessionId, event) => {
35782
35797
  for (const turn of activeTurns.values()) {
35783
- turn.recordInteraction(event);
35798
+ turn.recordEvent(event);
35784
35799
  }
35785
35800
  publisher.publish(sessionId, event);
35786
35801
  };
@@ -35948,7 +35963,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
35948
35963
  import { mkdir as mkdir5, realpath as realpath9, stat as stat8 } from "node:fs/promises";
35949
35964
  import { hostname as hostname3 } from "node:os";
35950
35965
  import { basename as basename6, resolve as resolve6 } from "node:path";
35951
- import { fetch as fetch5 } from "undici";
35966
+ import { fetch as fetch4 } from "undici";
35952
35967
 
35953
35968
  // src/storage/runtime-installation-store.ts
35954
35969
  import { createHash as createHash5, randomUUID as randomUUID7 } from "node:crypto";
@@ -36583,7 +36598,7 @@ async function claimPairing(options, defaultWorkspace, localAgents, installableA
36583
36598
  const endpoint = options.pairingId.length > 0 ? mobiusApiUrl(options.relayOrigin, `/v1/runtime-pairings/${encodeURIComponent(options.pairingId)}/redeem`) : mobiusApiUrl(options.relayOrigin, "/pairings/claim");
36584
36599
  let response;
36585
36600
  try {
36586
- response = await fetch5(endpoint, {
36601
+ response = await fetch4(endpoint, {
36587
36602
  body: JSON.stringify({
36588
36603
  agents,
36589
36604
  installableAgents,