@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/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(),
@@ -31893,7 +31908,10 @@ function liveHistoryCoveredTurnRanges(history) {
31893
31908
  }
31894
31909
  return ranges;
31895
31910
  }
31896
- function paginateLiveSessionHistory(history, sessionId, cursor, limit) {
31911
+ function historyMessageCharacters(message) {
31912
+ return message.text.length + (message.role === "assistant" ? JSON.stringify(message.activities).length + JSON.stringify(message.content).length : 0);
31913
+ }
31914
+ function paginateAcpSessionHistory(history, sessionId, cursor, limit) {
31897
31915
  if (history.status === "unavailable") {
31898
31916
  if (cursor !== null) {
31899
31917
  throw new AcpExecutionError("Unavailable native Session history has no cursor", {}, "invalid_cursor");
@@ -31919,6 +31937,80 @@ function paginateLiveSessionHistory(history, sessionId, cursor, limit) {
31919
31937
  truncated: history.truncated
31920
31938
  };
31921
31939
  }
31940
+ function paginateLiveSessionHistory(history, activeTurn, sessionId, cursor, limit) {
31941
+ if (activeTurn === null || cursor !== null) {
31942
+ return paginateAcpSessionHistory(history, sessionId, cursor, limit);
31943
+ }
31944
+ const activeMessageOverhead = 4;
31945
+ const activeStructuredCharacters = JSON.stringify(activeTurn.activities).length + JSON.stringify(activeTurn.content).length;
31946
+ const maximumActiveTextLength = Math.max(
31947
+ 0,
31948
+ SESSION_HISTORY_CHARACTER_LIMIT - activeTurn.prompt.length - activeStructuredCharacters - activeMessageOverhead
31949
+ );
31950
+ const activeText = activeTurn.text.slice(-maximumActiveTextLength);
31951
+ const completeActiveMessages = [
31952
+ { role: "user", text: activeTurn.prompt },
31953
+ {
31954
+ activities: activeTurn.activities,
31955
+ content: activeTurn.content,
31956
+ role: "assistant",
31957
+ text: activeText
31958
+ }
31959
+ ];
31960
+ if (history.status === "unavailable") {
31961
+ return {
31962
+ coveredCommandIds: [],
31963
+ coveredMessageIds: [],
31964
+ messages: completeActiveMessages,
31965
+ nextCursor: null,
31966
+ status: "available",
31967
+ truncated: activeTurn.truncated || activeText.length !== activeTurn.text.length
31968
+ };
31969
+ }
31970
+ const latestNativeMessage = history.messages.at(-1);
31971
+ const activeMessages = latestNativeMessage?.role === "user" && latestNativeMessage.text === activeTurn.prompt ? completeActiveMessages.slice(1) : completeActiveMessages;
31972
+ let historicalMessageCount = 0;
31973
+ let remainingCharacters = SESSION_HISTORY_CHARACTER_LIMIT - activeText.length - activeMessageOverhead - activeStructuredCharacters - (activeMessages.length === completeActiveMessages.length ? activeTurn.prompt.length : 0);
31974
+ const historicalMessageLimit = Math.max(0, limit - activeMessages.length);
31975
+ for (let index = history.messages.length - 1; index >= 0 && historicalMessageCount < historicalMessageLimit; index -= 1) {
31976
+ const message = history.messages[index];
31977
+ if (message === void 0) {
31978
+ break;
31979
+ }
31980
+ const characters = historyMessageCharacters(message);
31981
+ if (characters > remainingCharacters) {
31982
+ break;
31983
+ }
31984
+ historicalMessageCount += 1;
31985
+ remainingCharacters -= characters;
31986
+ }
31987
+ const page = historicalMessageCount === 0 ? {
31988
+ coveredCommandIds: [],
31989
+ coveredMessageIds: [],
31990
+ messages: [],
31991
+ nextCursor: history.messages.length === 0 ? null : liveHistoryCursor(sessionId, history.messages.length),
31992
+ status: "available",
31993
+ truncated: history.truncated
31994
+ } : paginateAcpSessionHistory(history, sessionId, null, historicalMessageCount);
31995
+ return {
31996
+ ...page,
31997
+ messages: [...page.messages, ...activeMessages],
31998
+ truncated: page.truncated || activeTurn.truncated || activeText.length !== activeTurn.text.length
31999
+ };
32000
+ }
32001
+ function mergeLiveSessionHistory(history, activeTurn, sessionId) {
32002
+ const page = paginateLiveSessionHistory(history, activeTurn, sessionId, null, 1e3);
32003
+ if (page.status === "unavailable") {
32004
+ return { cause: page.cause, status: "unavailable" };
32005
+ }
32006
+ return {
32007
+ coveredCommandIds: page.coveredCommandIds,
32008
+ coveredMessageIds: page.coveredMessageIds,
32009
+ messages: page.messages,
32010
+ status: "available",
32011
+ truncated: page.truncated
32012
+ };
32013
+ }
31922
32014
 
31923
32015
  // src/prompt-artifact-resolver.ts
31924
32016
  import { createHash as createHash3 } from "node:crypto";
@@ -32550,7 +32642,7 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
32550
32642
  reportOperationFailure(socket, command.requestId, command.sessionId, error62, metrics.snapshot());
32551
32643
  }
32552
32644
  }
32553
- async function executeSessionLiveHistoryLoad(socket, command, config2, directories, audit, sessions, signal) {
32645
+ async function executeSessionLiveHistoryLoad(socket, command, config2, directories, audit, sessions, activeTurn, signal) {
32554
32646
  try {
32555
32647
  const resolved = await resolveSessionDirectories(
32556
32648
  directories,
@@ -32567,13 +32659,14 @@ async function executeSessionLiveHistoryLoad(socket, command, config2, directori
32567
32659
  signal
32568
32660
  });
32569
32661
  signal.throwIfAborted();
32662
+ const mergedHistory = mergeLiveSessionHistory(history, activeTurn(command.sessionId), command.sessionId);
32570
32663
  audit.record({
32571
32664
  commandId: command.requestId,
32572
32665
  event: "session_history_loaded",
32573
32666
  sessionId: command.sessionId
32574
32667
  });
32575
32668
  send(socket, {
32576
- history,
32669
+ history: mergedHistory,
32577
32670
  kind: "session.live-history.loaded",
32578
32671
  requestId: command.requestId,
32579
32672
  sessionId: command.sessionId
@@ -32599,7 +32692,7 @@ async function executeSessionLiveHistoryLoad(socket, command, config2, directori
32599
32692
  });
32600
32693
  }
32601
32694
  }
32602
- async function executeSessionLiveHistoryPageLoad(socket, command, config2, directories, audit, sessions, signal) {
32695
+ async function executeSessionLiveHistoryPageLoad(socket, command, config2, directories, audit, sessions, activeTurn, signal) {
32603
32696
  try {
32604
32697
  const resolved = await resolveSessionDirectories(
32605
32698
  directories,
@@ -32616,7 +32709,13 @@ async function executeSessionLiveHistoryPageLoad(socket, command, config2, direc
32616
32709
  signal
32617
32710
  });
32618
32711
  signal.throwIfAborted();
32619
- const page = paginateLiveSessionHistory(history, command.sessionId, command.cursor, command.limit);
32712
+ const page = paginateLiveSessionHistory(
32713
+ history,
32714
+ activeTurn(command.sessionId),
32715
+ command.sessionId,
32716
+ command.cursor,
32717
+ command.limit
32718
+ );
32620
32719
  audit.record({
32621
32720
  commandId: command.requestId,
32622
32721
  event: "session_history_loaded",
@@ -32689,14 +32788,11 @@ async function executeSessionConfigure(publisher, socket, command, config2, dire
32689
32788
  reportOperationFailure(socket, command.requestId, command.sessionId, error62);
32690
32789
  }
32691
32790
  }
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
- });
32791
+ async function executePrompt(operations, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, acknowledgeQueued, waitForSessionAvailability, timer, signal, recordLiveEvent, cancellationRequested) {
32696
32792
  const narration = new CoalescingNarrationPublisher(
32697
32793
  timer,
32698
32794
  (increment) => {
32699
- publisher.publish(command.sessionId, {
32795
+ const event = {
32700
32796
  activityId: increment.activityId,
32701
32797
  activityType: increment.activityType,
32702
32798
  commandId: command.commandId,
@@ -32704,24 +32800,26 @@ async function executePrompt(operations, publisher, command, config2, directorie
32704
32800
  sequence: increment.sequence,
32705
32801
  sessionId: command.sessionId,
32706
32802
  text: increment.text
32707
- });
32803
+ };
32804
+ publisher.publish(command.sessionId, recordLiveEvent(event));
32708
32805
  },
32709
32806
  AGENT_ACTIVITY_COALESCING_MILLISECONDS,
32710
32807
  AGENT_TEXT_MAXIMUM_LENGTH
32711
32808
  );
32809
+ const activities = new CoalescingDaemonActivityPublisher(timer, (activity2) => {
32810
+ if (activity2.status !== "pending" && activity2.status !== "running") {
32811
+ narration.flush();
32812
+ }
32813
+ const event = daemonActivity(command, activity2);
32814
+ publisher.publish(command.sessionId, recordLiveEvent(event));
32815
+ });
32712
32816
  const text = new CoalescingTextPublisher(
32713
32817
  timer,
32714
32818
  (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
- });
32819
+ publisher.publish(
32820
+ command.sessionId,
32821
+ recordLiveEvent({ kind: AGENT_MESSAGE_DELTA_KIND, messageId, text: delta })
32822
+ );
32725
32823
  },
32726
32824
  AGENT_TEXT_COALESCING_MILLISECONDS,
32727
32825
  AGENT_TEXT_MAXIMUM_LENGTH
@@ -34190,6 +34288,144 @@ var WorkspaceDirectoryService = class {
34190
34288
  };
34191
34289
  };
34192
34290
 
34291
+ // src/daemon-active-turn.ts
34292
+ import { randomUUID as randomUUID3 } from "node:crypto";
34293
+ var ActiveDaemonTurn = class {
34294
+ attemptId;
34295
+ command;
34296
+ #controller;
34297
+ #finished = Promise.withResolvers();
34298
+ #cancellationRequested = false;
34299
+ #dispatch;
34300
+ #text = "";
34301
+ #activities = /* @__PURE__ */ new Map();
34302
+ #content = /* @__PURE__ */ new Map();
34303
+ #truncated = false;
34304
+ #sequence = 0;
34305
+ #interaction = null;
34306
+ #epoch = decodeIdentifier(randomUUID3());
34307
+ constructor(command, attemptId) {
34308
+ this.attemptId = attemptId;
34309
+ this.command = command;
34310
+ this.#controller = new AbortController();
34311
+ this.#dispatch = command.disposition === SessionPromptDisposition.Queue ? { kind: "queued", promotion: Promise.withResolvers() } : { kind: "pending" };
34312
+ }
34313
+ abortDaemon = () => {
34314
+ this.#controller.abort();
34315
+ };
34316
+ finish = () => this.#finished.resolve();
34317
+ accept = () => {
34318
+ this.#dispatch = { kind: "accepted" };
34319
+ return { epoch: this.#epoch, sequence: 0 };
34320
+ };
34321
+ promoteQueuedPrompt = (command) => {
34322
+ if (command.commandId !== this.command.commandId || command.sessionId !== this.command.sessionId || this.#dispatch.kind !== "queued") {
34323
+ return false;
34324
+ }
34325
+ const promotion = this.#dispatch.promotion;
34326
+ this.#dispatch = { kind: "promoted" };
34327
+ promotion.resolve();
34328
+ return true;
34329
+ };
34330
+ queuePromotion = () => {
34331
+ if (this.#dispatch.kind === "queued") {
34332
+ return this.#dispatch.promotion.promise;
34333
+ }
34334
+ return this.#dispatch.kind === "promoted" ? Promise.resolve() : null;
34335
+ };
34336
+ effectiveDisposition = () => this.#dispatch.kind === "promoted" ? SessionPromptDisposition.Steer : this.command.disposition;
34337
+ recordEvent = (event) => {
34338
+ if (event.kind === AGENT_MESSAGE_DELTA_KIND) {
34339
+ this.#sequence += 1;
34340
+ this.#text += event.text;
34341
+ if (this.#text.length > ACTIVE_TURN_TEXT_LIMIT) {
34342
+ this.#text = this.#text.slice(-ACTIVE_TURN_TEXT_LIMIT);
34343
+ this.#truncated = true;
34344
+ }
34345
+ return {
34346
+ commandId: this.command.commandId,
34347
+ epoch: this.#epoch,
34348
+ kind: AGENT_MESSAGE_DELTA_KIND,
34349
+ messageId: event.messageId,
34350
+ sequence: this.#sequence,
34351
+ sessionId: this.command.sessionId,
34352
+ text: event.text
34353
+ };
34354
+ }
34355
+ if (event.sessionId !== this.command.sessionId || "commandId" in event && event.commandId !== this.command.commandId) {
34356
+ return event;
34357
+ }
34358
+ if (event.kind === AGENT_ACTIVITY_KIND) {
34359
+ this.#activities.set(event.activityId, {
34360
+ activityId: event.activityId,
34361
+ activityType: event.activityType,
34362
+ content: event.content,
34363
+ input: event.input,
34364
+ locations: event.locations,
34365
+ name: event.name,
34366
+ output: event.output,
34367
+ sequence: event.sequence,
34368
+ status: event.status,
34369
+ title: event.title,
34370
+ toolKind: event.toolKind
34371
+ });
34372
+ } else if (event.kind === AGENT_ACTIVITY_NARRATION_KIND) {
34373
+ const previous = this.#activities.get(event.activityId);
34374
+ this.#activities.set(event.activityId, {
34375
+ activityId: event.activityId,
34376
+ activityType: event.activityType,
34377
+ content: previous?.content ?? [],
34378
+ input: previous?.input ?? "",
34379
+ locations: previous?.locations ?? [],
34380
+ name: previous?.name ?? "",
34381
+ output: `${previous?.output ?? ""}${event.text}`,
34382
+ sequence: event.sequence,
34383
+ status: previous?.status ?? "running",
34384
+ title: previous?.title ?? "Thinking",
34385
+ toolKind: previous?.toolKind ?? ""
34386
+ });
34387
+ } else if (event.kind === AGENT_CONTENT_KIND) {
34388
+ this.#content.set(event.contentId, event.content);
34389
+ } else if (event.kind === SESSION_PERMISSION_REQUESTED_KIND || event.kind === SESSION_ELICITATION_REQUESTED_KIND) {
34390
+ this.#interaction = event;
34391
+ } else if ((event.kind === SESSION_PERMISSION_RESOLVED_KIND || event.kind === SESSION_ELICITATION_RESOLVED_KIND) && this.#interaction?.interactionId === event.interactionId) {
34392
+ this.#interaction = null;
34393
+ }
34394
+ return event;
34395
+ };
34396
+ snapshot = () => this.#dispatch.kind === "accepted" ? {
34397
+ activities: [...this.#activities.values()].sort((left, right) => left.sequence - right.sequence),
34398
+ commandId: decodeIdentifier(this.command.commandId),
34399
+ content: [...this.#content.values()],
34400
+ prompt: this.command.prompt,
34401
+ text: this.#text,
34402
+ truncated: this.#truncated,
34403
+ epoch: this.#epoch,
34404
+ interaction: this.#interaction,
34405
+ sequence: this.#sequence,
34406
+ state: "running"
34407
+ } : null;
34408
+ matches = (cancellation) => cancellation.commandId === this.command.commandId && cancellation.sessionId === this.command.sessionId;
34409
+ requestCancellation = () => {
34410
+ if (this.#cancellationRequested) {
34411
+ return "already-requested";
34412
+ }
34413
+ this.#cancellationRequested = true;
34414
+ if (this.#dispatch.kind !== "accepted") {
34415
+ this.#controller.abort(new Error("The queued Agent turn was cancelled"));
34416
+ return "pending";
34417
+ }
34418
+ return "running";
34419
+ };
34420
+ cancellationRequested = () => this.#cancellationRequested;
34421
+ get signal() {
34422
+ return this.#controller.signal;
34423
+ }
34424
+ get completion() {
34425
+ return this.#finished.promise;
34426
+ }
34427
+ };
34428
+
34193
34429
  // src/daemon-diagnostic-log.ts
34194
34430
  import { appendFileSync, mkdirSync, readFileSync as readFileSync2, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
34195
34431
  import { join as join17 } from "node:path";
@@ -34372,184 +34608,6 @@ var DaemonInstallationObserver = class {
34372
34608
  };
34373
34609
  };
34374
34610
 
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
34611
  // src/native-sessions/codex-history.ts
34554
34612
  import { spawn as spawn5 } from "node:child_process";
34555
34613
  var responseSchema = external_exports.union([
@@ -35828,25 +35886,6 @@ var RelayConnectionDiagnostics = class {
35828
35886
  addFailureDetails(details, failure2);
35829
35887
  this.#record("relay_connection_failed", connectionEpoch.toString(), details, true);
35830
35888
  };
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
35889
  connectionOpened = (connectionEpoch) => {
35851
35890
  this.#record(
35852
35891
  "relay_connection_opened",
@@ -36074,7 +36113,6 @@ var systemDaemonTimer = new SystemDaemonTimer();
36074
36113
 
36075
36114
  // src/run-daemon.ts
36076
36115
  var RELAY_RECONNECT_DELAY_MILLISECONDS = 500;
36077
- var ACTIVE_TURN_RECONCILIATION_CLOSE_CODE = 4009;
36078
36116
  function closeRelaySocket(socket, code, reason) {
36079
36117
  try {
36080
36118
  socket.close(code, reason);
@@ -36143,7 +36181,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36143
36181
  const relayUrl = new URL(config2.relayUrl);
36144
36182
  relayUrl.searchParams.set("liveness", "1");
36145
36183
  const socket = await connectRelay(relayUrl, signal);
36146
- const reconnectingTurns = [...activeTurns.values()];
36147
36184
  diagnostics.connectionOpened(connectionEpoch);
36148
36185
  const connectionController = new AbortController();
36149
36186
  const handleSettingsDiscovery = createAgentSettingsDiscoveryHandler({
@@ -36165,6 +36202,18 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36165
36202
  timer,
36166
36203
  resolveEnvironment: resolveAgentCatalogEnvironment
36167
36204
  });
36205
+ const activeTurnSnapshot = (sessionId) => {
36206
+ for (const turn of activeTurns.values()) {
36207
+ if (turn.command.sessionId !== sessionId) {
36208
+ continue;
36209
+ }
36210
+ const snapshot = turn.snapshot();
36211
+ if (snapshot !== null) {
36212
+ return snapshot;
36213
+ }
36214
+ }
36215
+ return null;
36216
+ };
36168
36217
  const nativeRequestHandler = createNativeSessionRequestHandler({
36169
36218
  audit,
36170
36219
  diagnostics,
@@ -36334,6 +36383,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36334
36383
  directories,
36335
36384
  audit,
36336
36385
  sessions,
36386
+ activeTurnSnapshot,
36337
36387
  connectionController.signal
36338
36388
  );
36339
36389
  return;
@@ -36347,6 +36397,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36347
36397
  directories,
36348
36398
  audit,
36349
36399
  sessions,
36400
+ activeTurnSnapshot,
36350
36401
  connectionController.signal
36351
36402
  );
36352
36403
  return;
@@ -36549,7 +36600,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36549
36600
  (waitSignal) => waitForSessionAvailability(command, turn, waitSignal),
36550
36601
  timer,
36551
36602
  turn.signal,
36552
- turn.recordText,
36603
+ turn.recordEvent,
36553
36604
  turn.cancellationRequested
36554
36605
  ).catch((error62) => {
36555
36606
  console.error("Mobius daemon turn failed", error62);
@@ -36570,43 +36621,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36570
36621
  socket.addEventListener("close", handleClose);
36571
36622
  socket.addEventListener("error", handleError);
36572
36623
  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
- );
36624
+ publisher.connect(socket);
36610
36625
  if (signal.aborted) {
36611
36626
  stop();
36612
36627
  }
@@ -36638,7 +36653,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
36638
36653
  const activeTurns = /* @__PURE__ */ new Map();
36639
36654
  const recordSessionEvent = (sessionId, event) => {
36640
36655
  for (const turn of activeTurns.values()) {
36641
- turn.recordInteraction(event);
36656
+ turn.recordEvent(event);
36642
36657
  }
36643
36658
  publisher.publish(sessionId, event);
36644
36659
  };