@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/cli.js CHANGED
@@ -3381,7 +3381,7 @@ var program = new Command();
3381
3381
  // package.json
3382
3382
  var package_default = {
3383
3383
  name: "@moxt-ai/mobius",
3384
- version: "0.0.113",
3384
+ version: "0.0.115",
3385
3385
  description: "Mobius CLI for pairing and running local AI agent services.",
3386
3386
  type: "module",
3387
3387
  bin: {
@@ -29232,6 +29232,19 @@ var envelope = {
29232
29232
  requestId: identifierStringSchema,
29233
29233
  sessionId: identifierStringSchema
29234
29234
  };
29235
+ var activeTurnActivitySchema = external_exports.strictObject({
29236
+ activityId: external_exports.string().min(1).max(128),
29237
+ activityType: external_exports.string().min(1).max(128),
29238
+ content: external_exports.array(displayContentSchema).max(100).readonly(),
29239
+ input: external_exports.string().max(1e5),
29240
+ locations: external_exports.array(external_exports.string().min(1).max(2048)).max(100).readonly(),
29241
+ name: external_exports.string().max(128),
29242
+ output: external_exports.string().max(1e5),
29243
+ sequence: external_exports.number().int().nonnegative(),
29244
+ status: external_exports.string().min(1).max(64),
29245
+ title: external_exports.string().max(500),
29246
+ toolKind: external_exports.string().max(64)
29247
+ }).readonly();
29235
29248
  var identity = {
29236
29249
  ...envelope,
29237
29250
  kind: external_exports.literal(NATIVE_SESSION_REQUEST_KIND),
@@ -29307,7 +29320,9 @@ var nativeSessionResultSchema = external_exports.discriminatedUnion("action", [
29307
29320
  action: external_exports.literal("active-turn"),
29308
29321
  targetSessionId: identifierStringSchema,
29309
29322
  turn: external_exports.strictObject({
29323
+ activities: external_exports.array(activeTurnActivitySchema).max(100).readonly(),
29310
29324
  commandId: identifierStringSchema,
29325
+ content: external_exports.array(displayContentSchema).max(100).readonly(),
29311
29326
  prompt: external_exports.string().max(1e5),
29312
29327
  text: external_exports.string().max(ACTIVE_TURN_TEXT_LIMIT),
29313
29328
  truncated: external_exports.boolean(),
@@ -35331,7 +35346,10 @@ function liveHistoryCoveredTurnRanges(history) {
35331
35346
  }
35332
35347
  return ranges;
35333
35348
  }
35334
- function paginateLiveSessionHistory(history, sessionId, cursor, limit) {
35349
+ function historyMessageCharacters(message) {
35350
+ return message.text.length + (message.role === "assistant" ? JSON.stringify(message.activities).length + JSON.stringify(message.content).length : 0);
35351
+ }
35352
+ function paginateAcpSessionHistory(history, sessionId, cursor, limit) {
35335
35353
  if (history.status === "unavailable") {
35336
35354
  if (cursor !== null) {
35337
35355
  throw new AcpExecutionError("Unavailable native Session history has no cursor", {}, "invalid_cursor");
@@ -35357,6 +35375,80 @@ function paginateLiveSessionHistory(history, sessionId, cursor, limit) {
35357
35375
  truncated: history.truncated
35358
35376
  };
35359
35377
  }
35378
+ function paginateLiveSessionHistory(history, activeTurn, sessionId, cursor, limit) {
35379
+ if (activeTurn === null || cursor !== null) {
35380
+ return paginateAcpSessionHistory(history, sessionId, cursor, limit);
35381
+ }
35382
+ const activeMessageOverhead = 4;
35383
+ const activeStructuredCharacters = JSON.stringify(activeTurn.activities).length + JSON.stringify(activeTurn.content).length;
35384
+ const maximumActiveTextLength = Math.max(
35385
+ 0,
35386
+ SESSION_HISTORY_CHARACTER_LIMIT - activeTurn.prompt.length - activeStructuredCharacters - activeMessageOverhead
35387
+ );
35388
+ const activeText = activeTurn.text.slice(-maximumActiveTextLength);
35389
+ const completeActiveMessages = [
35390
+ { role: "user", text: activeTurn.prompt },
35391
+ {
35392
+ activities: activeTurn.activities,
35393
+ content: activeTurn.content,
35394
+ role: "assistant",
35395
+ text: activeText
35396
+ }
35397
+ ];
35398
+ if (history.status === "unavailable") {
35399
+ return {
35400
+ coveredCommandIds: [],
35401
+ coveredMessageIds: [],
35402
+ messages: completeActiveMessages,
35403
+ nextCursor: null,
35404
+ status: "available",
35405
+ truncated: activeTurn.truncated || activeText.length !== activeTurn.text.length
35406
+ };
35407
+ }
35408
+ const latestNativeMessage = history.messages.at(-1);
35409
+ const activeMessages = latestNativeMessage?.role === "user" && latestNativeMessage.text === activeTurn.prompt ? completeActiveMessages.slice(1) : completeActiveMessages;
35410
+ let historicalMessageCount = 0;
35411
+ let remainingCharacters = SESSION_HISTORY_CHARACTER_LIMIT - activeText.length - activeMessageOverhead - activeStructuredCharacters - (activeMessages.length === completeActiveMessages.length ? activeTurn.prompt.length : 0);
35412
+ const historicalMessageLimit = Math.max(0, limit - activeMessages.length);
35413
+ for (let index = history.messages.length - 1; index >= 0 && historicalMessageCount < historicalMessageLimit; index -= 1) {
35414
+ const message = history.messages[index];
35415
+ if (message === void 0) {
35416
+ break;
35417
+ }
35418
+ const characters = historyMessageCharacters(message);
35419
+ if (characters > remainingCharacters) {
35420
+ break;
35421
+ }
35422
+ historicalMessageCount += 1;
35423
+ remainingCharacters -= characters;
35424
+ }
35425
+ const page = historicalMessageCount === 0 ? {
35426
+ coveredCommandIds: [],
35427
+ coveredMessageIds: [],
35428
+ messages: [],
35429
+ nextCursor: history.messages.length === 0 ? null : liveHistoryCursor(sessionId, history.messages.length),
35430
+ status: "available",
35431
+ truncated: history.truncated
35432
+ } : paginateAcpSessionHistory(history, sessionId, null, historicalMessageCount);
35433
+ return {
35434
+ ...page,
35435
+ messages: [...page.messages, ...activeMessages],
35436
+ truncated: page.truncated || activeTurn.truncated || activeText.length !== activeTurn.text.length
35437
+ };
35438
+ }
35439
+ function mergeLiveSessionHistory(history, activeTurn, sessionId) {
35440
+ const page = paginateLiveSessionHistory(history, activeTurn, sessionId, null, 1e3);
35441
+ if (page.status === "unavailable") {
35442
+ return { cause: page.cause, status: "unavailable" };
35443
+ }
35444
+ return {
35445
+ coveredCommandIds: page.coveredCommandIds,
35446
+ coveredMessageIds: page.coveredMessageIds,
35447
+ messages: page.messages,
35448
+ status: "available",
35449
+ truncated: page.truncated
35450
+ };
35451
+ }
35360
35452
 
35361
35453
  // src/prompt-artifact-resolver.ts
35362
35454
  import { createHash as createHash3 } from "node:crypto";
@@ -35988,7 +36080,7 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
35988
36080
  reportOperationFailure(socket, command.requestId, command.sessionId, error62, metrics.snapshot());
35989
36081
  }
35990
36082
  }
35991
- async function executeSessionLiveHistoryLoad(socket, command, config2, directories, audit, sessions, signal) {
36083
+ async function executeSessionLiveHistoryLoad(socket, command, config2, directories, audit, sessions, activeTurn, signal) {
35992
36084
  try {
35993
36085
  const resolved = await resolveSessionDirectories(
35994
36086
  directories,
@@ -36005,13 +36097,14 @@ async function executeSessionLiveHistoryLoad(socket, command, config2, directori
36005
36097
  signal
36006
36098
  });
36007
36099
  signal.throwIfAborted();
36100
+ const mergedHistory = mergeLiveSessionHistory(history, activeTurn(command.sessionId), command.sessionId);
36008
36101
  audit.record({
36009
36102
  commandId: command.requestId,
36010
36103
  event: "session_history_loaded",
36011
36104
  sessionId: command.sessionId
36012
36105
  });
36013
36106
  send(socket, {
36014
- history,
36107
+ history: mergedHistory,
36015
36108
  kind: "session.live-history.loaded",
36016
36109
  requestId: command.requestId,
36017
36110
  sessionId: command.sessionId
@@ -36037,7 +36130,7 @@ async function executeSessionLiveHistoryLoad(socket, command, config2, directori
36037
36130
  });
36038
36131
  }
36039
36132
  }
36040
- async function executeSessionLiveHistoryPageLoad(socket, command, config2, directories, audit, sessions, signal) {
36133
+ async function executeSessionLiveHistoryPageLoad(socket, command, config2, directories, audit, sessions, activeTurn, signal) {
36041
36134
  try {
36042
36135
  const resolved = await resolveSessionDirectories(
36043
36136
  directories,
@@ -36054,7 +36147,13 @@ async function executeSessionLiveHistoryPageLoad(socket, command, config2, direc
36054
36147
  signal
36055
36148
  });
36056
36149
  signal.throwIfAborted();
36057
- const page = paginateLiveSessionHistory(history, command.sessionId, command.cursor, command.limit);
36150
+ const page = paginateLiveSessionHistory(
36151
+ history,
36152
+ activeTurn(command.sessionId),
36153
+ command.sessionId,
36154
+ command.cursor,
36155
+ command.limit
36156
+ );
36058
36157
  audit.record({
36059
36158
  commandId: command.requestId,
36060
36159
  event: "session_history_loaded",
@@ -36127,14 +36226,11 @@ async function executeSessionConfigure(publisher, socket, command, config2, dire
36127
36226
  reportOperationFailure(socket, command.requestId, command.sessionId, error62);
36128
36227
  }
36129
36228
  }
36130
- async function executePrompt(operations, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, acknowledgeQueued, waitForSessionAvailability, timer, signal, recordLiveText, cancellationRequested) {
36131
- const activities = new CoalescingDaemonActivityPublisher(timer, (activity2) => {
36132
- publisher.publish(command.sessionId, daemonActivity(command, activity2));
36133
- });
36229
+ async function executePrompt(operations, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, acknowledgeQueued, waitForSessionAvailability, timer, signal, recordLiveEvent, cancellationRequested) {
36134
36230
  const narration = new CoalescingNarrationPublisher(
36135
36231
  timer,
36136
36232
  (increment) => {
36137
- publisher.publish(command.sessionId, {
36233
+ const event = {
36138
36234
  activityId: increment.activityId,
36139
36235
  activityType: increment.activityType,
36140
36236
  commandId: command.commandId,
@@ -36142,24 +36238,26 @@ async function executePrompt(operations, publisher, command, config2, directorie
36142
36238
  sequence: increment.sequence,
36143
36239
  sessionId: command.sessionId,
36144
36240
  text: increment.text
36145
- });
36241
+ };
36242
+ publisher.publish(command.sessionId, recordLiveEvent(event));
36146
36243
  },
36147
36244
  AGENT_ACTIVITY_COALESCING_MILLISECONDS,
36148
36245
  AGENT_TEXT_MAXIMUM_LENGTH
36149
36246
  );
36247
+ const activities = new CoalescingDaemonActivityPublisher(timer, (activity2) => {
36248
+ if (activity2.status !== "pending" && activity2.status !== "running") {
36249
+ narration.flush();
36250
+ }
36251
+ const event = daemonActivity(command, activity2);
36252
+ publisher.publish(command.sessionId, recordLiveEvent(event));
36253
+ });
36150
36254
  const text = new CoalescingTextPublisher(
36151
36255
  timer,
36152
36256
  (messageId, delta) => {
36153
- const stream = recordLiveText(delta);
36154
- publisher.publish(command.sessionId, {
36155
- commandId: command.commandId,
36156
- epoch: stream.epoch,
36157
- kind: AGENT_MESSAGE_DELTA_KIND,
36158
- messageId,
36159
- sequence: stream.sequence,
36160
- sessionId: command.sessionId,
36161
- text: delta
36162
- });
36257
+ publisher.publish(
36258
+ command.sessionId,
36259
+ recordLiveEvent({ kind: AGENT_MESSAGE_DELTA_KIND, messageId, text: delta })
36260
+ );
36163
36261
  },
36164
36262
  AGENT_TEXT_COALESCING_MILLISECONDS,
36165
36263
  AGENT_TEXT_MAXIMUM_LENGTH
@@ -37628,6 +37726,144 @@ var WorkspaceDirectoryService = class {
37628
37726
  };
37629
37727
  };
37630
37728
 
37729
+ // src/daemon-active-turn.ts
37730
+ import { randomUUID as randomUUID3 } from "node:crypto";
37731
+ var ActiveDaemonTurn = class {
37732
+ attemptId;
37733
+ command;
37734
+ #controller;
37735
+ #finished = Promise.withResolvers();
37736
+ #cancellationRequested = false;
37737
+ #dispatch;
37738
+ #text = "";
37739
+ #activities = /* @__PURE__ */ new Map();
37740
+ #content = /* @__PURE__ */ new Map();
37741
+ #truncated = false;
37742
+ #sequence = 0;
37743
+ #interaction = null;
37744
+ #epoch = decodeIdentifier(randomUUID3());
37745
+ constructor(command, attemptId) {
37746
+ this.attemptId = attemptId;
37747
+ this.command = command;
37748
+ this.#controller = new AbortController();
37749
+ this.#dispatch = command.disposition === SessionPromptDisposition.Queue ? { kind: "queued", promotion: Promise.withResolvers() } : { kind: "pending" };
37750
+ }
37751
+ abortDaemon = () => {
37752
+ this.#controller.abort();
37753
+ };
37754
+ finish = () => this.#finished.resolve();
37755
+ accept = () => {
37756
+ this.#dispatch = { kind: "accepted" };
37757
+ return { epoch: this.#epoch, sequence: 0 };
37758
+ };
37759
+ promoteQueuedPrompt = (command) => {
37760
+ if (command.commandId !== this.command.commandId || command.sessionId !== this.command.sessionId || this.#dispatch.kind !== "queued") {
37761
+ return false;
37762
+ }
37763
+ const promotion = this.#dispatch.promotion;
37764
+ this.#dispatch = { kind: "promoted" };
37765
+ promotion.resolve();
37766
+ return true;
37767
+ };
37768
+ queuePromotion = () => {
37769
+ if (this.#dispatch.kind === "queued") {
37770
+ return this.#dispatch.promotion.promise;
37771
+ }
37772
+ return this.#dispatch.kind === "promoted" ? Promise.resolve() : null;
37773
+ };
37774
+ effectiveDisposition = () => this.#dispatch.kind === "promoted" ? SessionPromptDisposition.Steer : this.command.disposition;
37775
+ recordEvent = (event) => {
37776
+ if (event.kind === AGENT_MESSAGE_DELTA_KIND) {
37777
+ this.#sequence += 1;
37778
+ this.#text += event.text;
37779
+ if (this.#text.length > ACTIVE_TURN_TEXT_LIMIT) {
37780
+ this.#text = this.#text.slice(-ACTIVE_TURN_TEXT_LIMIT);
37781
+ this.#truncated = true;
37782
+ }
37783
+ return {
37784
+ commandId: this.command.commandId,
37785
+ epoch: this.#epoch,
37786
+ kind: AGENT_MESSAGE_DELTA_KIND,
37787
+ messageId: event.messageId,
37788
+ sequence: this.#sequence,
37789
+ sessionId: this.command.sessionId,
37790
+ text: event.text
37791
+ };
37792
+ }
37793
+ if (event.sessionId !== this.command.sessionId || "commandId" in event && event.commandId !== this.command.commandId) {
37794
+ return event;
37795
+ }
37796
+ if (event.kind === AGENT_ACTIVITY_KIND) {
37797
+ this.#activities.set(event.activityId, {
37798
+ activityId: event.activityId,
37799
+ activityType: event.activityType,
37800
+ content: event.content,
37801
+ input: event.input,
37802
+ locations: event.locations,
37803
+ name: event.name,
37804
+ output: event.output,
37805
+ sequence: event.sequence,
37806
+ status: event.status,
37807
+ title: event.title,
37808
+ toolKind: event.toolKind
37809
+ });
37810
+ } else if (event.kind === AGENT_ACTIVITY_NARRATION_KIND) {
37811
+ const previous = this.#activities.get(event.activityId);
37812
+ this.#activities.set(event.activityId, {
37813
+ activityId: event.activityId,
37814
+ activityType: event.activityType,
37815
+ content: previous?.content ?? [],
37816
+ input: previous?.input ?? "",
37817
+ locations: previous?.locations ?? [],
37818
+ name: previous?.name ?? "",
37819
+ output: `${previous?.output ?? ""}${event.text}`,
37820
+ sequence: event.sequence,
37821
+ status: previous?.status ?? "running",
37822
+ title: previous?.title ?? "Thinking",
37823
+ toolKind: previous?.toolKind ?? ""
37824
+ });
37825
+ } else if (event.kind === AGENT_CONTENT_KIND) {
37826
+ this.#content.set(event.contentId, event.content);
37827
+ } else if (event.kind === SESSION_PERMISSION_REQUESTED_KIND || event.kind === SESSION_ELICITATION_REQUESTED_KIND) {
37828
+ this.#interaction = event;
37829
+ } else if ((event.kind === SESSION_PERMISSION_RESOLVED_KIND || event.kind === SESSION_ELICITATION_RESOLVED_KIND) && this.#interaction?.interactionId === event.interactionId) {
37830
+ this.#interaction = null;
37831
+ }
37832
+ return event;
37833
+ };
37834
+ snapshot = () => this.#dispatch.kind === "accepted" ? {
37835
+ activities: [...this.#activities.values()].sort((left, right) => left.sequence - right.sequence),
37836
+ commandId: decodeIdentifier(this.command.commandId),
37837
+ content: [...this.#content.values()],
37838
+ prompt: this.command.prompt,
37839
+ text: this.#text,
37840
+ truncated: this.#truncated,
37841
+ epoch: this.#epoch,
37842
+ interaction: this.#interaction,
37843
+ sequence: this.#sequence,
37844
+ state: "running"
37845
+ } : null;
37846
+ matches = (cancellation) => cancellation.commandId === this.command.commandId && cancellation.sessionId === this.command.sessionId;
37847
+ requestCancellation = () => {
37848
+ if (this.#cancellationRequested) {
37849
+ return "already-requested";
37850
+ }
37851
+ this.#cancellationRequested = true;
37852
+ if (this.#dispatch.kind !== "accepted") {
37853
+ this.#controller.abort(new Error("The queued Agent turn was cancelled"));
37854
+ return "pending";
37855
+ }
37856
+ return "running";
37857
+ };
37858
+ cancellationRequested = () => this.#cancellationRequested;
37859
+ get signal() {
37860
+ return this.#controller.signal;
37861
+ }
37862
+ get completion() {
37863
+ return this.#finished.promise;
37864
+ }
37865
+ };
37866
+
37631
37867
  // src/daemon-diagnostic-log.ts
37632
37868
  import { appendFileSync, mkdirSync, readFileSync as readFileSync2, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
37633
37869
  import { join as join17 } from "node:path";
@@ -37810,184 +38046,6 @@ var DaemonInstallationObserver = class {
37810
38046
  };
37811
38047
  };
37812
38048
 
37813
- // src/daemon-turn-reconciliation.ts
37814
- import { randomUUID as randomUUID3 } from "node:crypto";
37815
- import { fetch as fetch5 } from "undici";
37816
- var ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS = 2e4;
37817
- var ActiveDaemonTurn = class {
37818
- attemptId;
37819
- command;
37820
- #controller;
37821
- #finished = Promise.withResolvers();
37822
- #cancellationRequested = false;
37823
- #dispatch;
37824
- #text = "";
37825
- #truncated = false;
37826
- #sequence = 0;
37827
- #interaction = null;
37828
- #epoch = decodeIdentifier(randomUUID3());
37829
- constructor(command, attemptId) {
37830
- this.attemptId = attemptId;
37831
- this.command = command;
37832
- this.#controller = new AbortController();
37833
- this.#dispatch = command.disposition === SessionPromptDisposition.Queue ? { kind: "queued", promotion: Promise.withResolvers() } : { kind: "pending" };
37834
- }
37835
- abortDaemon = () => {
37836
- this.#controller.abort();
37837
- };
37838
- finish = () => this.#finished.resolve();
37839
- accept = () => {
37840
- this.#dispatch = { kind: "accepted" };
37841
- return { epoch: this.#epoch, sequence: 0 };
37842
- };
37843
- promoteQueuedPrompt = (command) => {
37844
- if (command.commandId !== this.command.commandId || command.sessionId !== this.command.sessionId || this.#dispatch.kind !== "queued") {
37845
- return false;
37846
- }
37847
- const promotion = this.#dispatch.promotion;
37848
- this.#dispatch = { kind: "promoted" };
37849
- promotion.resolve();
37850
- return true;
37851
- };
37852
- queuePromotion = () => {
37853
- if (this.#dispatch.kind === "queued") {
37854
- return this.#dispatch.promotion.promise;
37855
- }
37856
- return this.#dispatch.kind === "promoted" ? Promise.resolve() : null;
37857
- };
37858
- effectiveDisposition = () => this.#dispatch.kind === "promoted" ? SessionPromptDisposition.Steer : this.command.disposition;
37859
- recordText = (delta) => {
37860
- this.#sequence += 1;
37861
- this.#text += delta;
37862
- if (this.#text.length > ACTIVE_TURN_TEXT_LIMIT) {
37863
- this.#text = this.#text.slice(-ACTIVE_TURN_TEXT_LIMIT);
37864
- this.#truncated = true;
37865
- }
37866
- return { epoch: this.#epoch, sequence: this.#sequence };
37867
- };
37868
- recordInteraction = (event) => {
37869
- if (event.sessionId !== this.command.sessionId) {
37870
- return;
37871
- }
37872
- if (event.kind === SESSION_PERMISSION_REQUESTED_KIND || event.kind === SESSION_ELICITATION_REQUESTED_KIND) {
37873
- if (event.commandId === this.command.commandId) {
37874
- this.#interaction = event;
37875
- }
37876
- } else if ((event.kind === SESSION_PERMISSION_RESOLVED_KIND || event.kind === SESSION_ELICITATION_RESOLVED_KIND) && this.#interaction?.interactionId === event.interactionId) {
37877
- this.#interaction = null;
37878
- }
37879
- };
37880
- snapshot = () => this.#dispatch.kind === "accepted" ? {
37881
- commandId: decodeIdentifier(this.command.commandId),
37882
- prompt: this.command.prompt,
37883
- text: this.#text,
37884
- truncated: this.#truncated,
37885
- epoch: this.#epoch,
37886
- interaction: this.#interaction,
37887
- sequence: this.#sequence,
37888
- state: "running"
37889
- } : null;
37890
- matches = (cancellation) => cancellation.commandId === this.command.commandId && cancellation.sessionId === this.command.sessionId;
37891
- requestCancellation = () => {
37892
- if (this.#cancellationRequested) {
37893
- return "already-requested";
37894
- }
37895
- this.#cancellationRequested = true;
37896
- if (this.#dispatch.kind !== "accepted") {
37897
- this.#controller.abort(new Error("The queued Agent turn was cancelled"));
37898
- return "pending";
37899
- }
37900
- return "running";
37901
- };
37902
- cancellationRequested = () => this.#cancellationRequested;
37903
- get signal() {
37904
- return this.#controller.signal;
37905
- }
37906
- get completion() {
37907
- return this.#finished.promise;
37908
- }
37909
- };
37910
- var ActiveTurnReconciliationError = class extends Error {
37911
- code = "active_turn_reconciliation_failed";
37912
- diagnosticDetails;
37913
- relayErrorCode;
37914
- terminal;
37915
- constructor(message, options = {}) {
37916
- super(message, options);
37917
- this.name = "ActiveTurnReconciliationError";
37918
- this.relayErrorCode = options.relayErrorCode ?? null;
37919
- this.terminal = options.terminal ?? false;
37920
- this.diagnosticDetails = this.relayErrorCode === null ? {} : { relayErrorCode: this.relayErrorCode };
37921
- }
37922
- };
37923
- var TERMINAL_RECONCILIATION_RELAY_CODES = /* @__PURE__ */ new Set(["session_conflict"]);
37924
- async function relayErrorCode(response) {
37925
- try {
37926
- const body = JSON.parse(await response.text());
37927
- if (typeof body !== "object" || body === null) {
37928
- return null;
37929
- }
37930
- const error62 = Reflect.get(body, "error");
37931
- if (typeof error62 !== "object" || error62 === null) {
37932
- return null;
37933
- }
37934
- const code = Reflect.get(error62, "code");
37935
- return typeof code === "string" && code.length > 0 ? code : null;
37936
- } catch {
37937
- return null;
37938
- }
37939
- }
37940
- function activeTurnReconciliationEndpoint(config2, turn) {
37941
- const endpoint = relayHttpEndpoint(config2.relayUrl);
37942
- let channelPath = "";
37943
- if (endpoint.pathname.endsWith("/daemon")) {
37944
- channelPath = endpoint.pathname.slice(0, -"/daemon".length);
37945
- } else {
37946
- const runtimePath = "/v1/runtimes/connect";
37947
- if (!endpoint.pathname.endsWith(runtimePath)) {
37948
- throw new ActiveTurnReconciliationError("The Relay URL is invalid");
37949
- }
37950
- channelPath = `${endpoint.pathname.slice(0, -runtimePath.length)}/channels/${encodeURIComponent(config2.channelId)}`;
37951
- }
37952
- endpoint.pathname = `${channelPath}/sessions/${encodeURIComponent(turn.command.sessionId)}/attempts/${encodeURIComponent(turn.attemptId)}/reconciliation`;
37953
- return endpoint;
37954
- }
37955
- async function reconcileActiveTurn(config2, turn, signal) {
37956
- signal.throwIfAborted();
37957
- const timeoutSignal = AbortSignal.timeout(ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS);
37958
- const requestSignal = AbortSignal.any([signal, timeoutSignal]);
37959
- let response;
37960
- try {
37961
- response = await fetch5(activeTurnReconciliationEndpoint(config2, turn), {
37962
- body: JSON.stringify({ outcome: { kind: "running" } }),
37963
- dispatcher: environmentProxyDispatcher,
37964
- headers: { ...runtimeAuthorization(config2.relayUrl), "content-type": "application/json" },
37965
- method: "POST",
37966
- signal: requestSignal
37967
- });
37968
- } catch (error62) {
37969
- if (signal.aborted) {
37970
- signal.throwIfAborted();
37971
- }
37972
- throw new ActiveTurnReconciliationError(
37973
- timeoutSignal.aborted ? "The active Agent turn reconciliation timed out" : "The active Agent turn could not be reconciled",
37974
- { cause: error62 }
37975
- );
37976
- }
37977
- if (!response.ok) {
37978
- const errorCode = await relayErrorCode(response);
37979
- const terminal = errorCode !== null && TERMINAL_RECONCILIATION_RELAY_CODES.has(errorCode);
37980
- throw new ActiveTurnReconciliationError(
37981
- terminal ? `The Relay reported that the active Agent turn can no longer be reconciled (${errorCode})` : `The Relay rejected the active Agent turn reconciliation with status ${response.status.toString()}`,
37982
- { relayErrorCode: errorCode, terminal }
37983
- );
37984
- }
37985
- await response.body?.cancel();
37986
- }
37987
- async function reconcileActiveTurns(config2, turns, signal) {
37988
- await Promise.all(turns.map(async (turn) => await reconcileActiveTurn(config2, turn, signal)));
37989
- }
37990
-
37991
38049
  // src/native-sessions/codex-history.ts
37992
38050
  import { spawn as spawn5 } from "node:child_process";
37993
38051
  var responseSchema = external_exports.union([
@@ -39286,25 +39344,6 @@ var RelayConnectionDiagnostics = class {
39286
39344
  addFailureDetails(details, failure2);
39287
39345
  this.#record("relay_connection_failed", connectionEpoch.toString(), details, true);
39288
39346
  };
39289
- /**
39290
- * Records that the Runtime gave up on Agent turns the Relay already settled. This is not a connection
39291
- * failure, so it is recorded independently of the per-epoch failure deduplication.
39292
- */
39293
- reconciliationAbandoned = (connectionEpoch, relayErrorCode2, turnCount) => {
39294
- this.#record(
39295
- "relay_reconciliation_abandoned",
39296
- connectionEpoch.toString(),
39297
- {
39298
- connectionEpoch: connectionEpoch.toString(),
39299
- relayErrorCode: relayErrorCode2 ?? "unknown",
39300
- relayOrigin: this.#relayOrigin,
39301
- source: "reconciliation_abandoned",
39302
- turnCount: turnCount.toString(),
39303
- ...this.#route
39304
- },
39305
- true
39306
- );
39307
- };
39308
39347
  connectionOpened = (connectionEpoch) => {
39309
39348
  this.#record(
39310
39349
  "relay_connection_opened",
@@ -39532,7 +39571,6 @@ var systemDaemonTimer = new SystemDaemonTimer();
39532
39571
 
39533
39572
  // src/run-daemon.ts
39534
39573
  var RELAY_RECONNECT_DELAY_MILLISECONDS = 500;
39535
- var ACTIVE_TURN_RECONCILIATION_CLOSE_CODE = 4009;
39536
39574
  function closeRelaySocket(socket, code, reason) {
39537
39575
  try {
39538
39576
  socket.close(code, reason);
@@ -39601,7 +39639,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
39601
39639
  const relayUrl = new URL(config2.relayUrl);
39602
39640
  relayUrl.searchParams.set("liveness", "1");
39603
39641
  const socket = await connectRelay(relayUrl, signal);
39604
- const reconnectingTurns = [...activeTurns.values()];
39605
39642
  diagnostics.connectionOpened(connectionEpoch);
39606
39643
  const connectionController = new AbortController();
39607
39644
  const handleSettingsDiscovery = createAgentSettingsDiscoveryHandler({
@@ -39623,6 +39660,18 @@ async function runRelayConnection(config2, directories, audit, sessions, install
39623
39660
  timer,
39624
39661
  resolveEnvironment: resolveAgentCatalogEnvironment
39625
39662
  });
39663
+ const activeTurnSnapshot = (sessionId) => {
39664
+ for (const turn of activeTurns.values()) {
39665
+ if (turn.command.sessionId !== sessionId) {
39666
+ continue;
39667
+ }
39668
+ const snapshot = turn.snapshot();
39669
+ if (snapshot !== null) {
39670
+ return snapshot;
39671
+ }
39672
+ }
39673
+ return null;
39674
+ };
39626
39675
  const nativeRequestHandler = createNativeSessionRequestHandler({
39627
39676
  audit,
39628
39677
  diagnostics,
@@ -39792,6 +39841,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
39792
39841
  directories,
39793
39842
  audit,
39794
39843
  sessions,
39844
+ activeTurnSnapshot,
39795
39845
  connectionController.signal
39796
39846
  );
39797
39847
  return;
@@ -39805,6 +39855,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
39805
39855
  directories,
39806
39856
  audit,
39807
39857
  sessions,
39858
+ activeTurnSnapshot,
39808
39859
  connectionController.signal
39809
39860
  );
39810
39861
  return;
@@ -40007,7 +40058,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40007
40058
  (waitSignal) => waitForSessionAvailability(command, turn, waitSignal),
40008
40059
  timer,
40009
40060
  turn.signal,
40010
- turn.recordText,
40061
+ turn.recordEvent,
40011
40062
  turn.cancellationRequested
40012
40063
  ).catch((error62) => {
40013
40064
  console.error("Mobius daemon turn failed", error62);
@@ -40028,43 +40079,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40028
40079
  socket.addEventListener("close", handleClose);
40029
40080
  socket.addEventListener("error", handleError);
40030
40081
  socket.addEventListener("message", handleMessage);
40031
- void reconcileActiveTurns(config2, reconnectingTurns, connectionController.signal).then(
40032
- () => {
40033
- if (finished) {
40034
- return;
40035
- }
40036
- publisher.connect(socket);
40037
- },
40038
- (error62) => {
40039
- if (finished) {
40040
- return;
40041
- }
40042
- console.error("Mobius daemon could not reconcile active Agent turns", error62);
40043
- if (error62 instanceof ActiveTurnReconciliationError && error62.terminal) {
40044
- diagnostics.reconciliationAbandoned(
40045
- connectionEpoch,
40046
- error62.relayErrorCode,
40047
- reconnectingTurns.length
40048
- );
40049
- console.error(
40050
- "Mobius daemon abandoned Agent turns the Relay already settled",
40051
- error62.relayErrorCode
40052
- );
40053
- for (const turn of reconnectingTurns) {
40054
- activeTurns.delete(turn.command.commandId);
40055
- turn.abortDaemon();
40056
- }
40057
- publisher.connect(socket);
40058
- return;
40059
- }
40060
- failAndClose(
40061
- new Error("Active Agent turn reconciliation failed", { cause: error62 }),
40062
- ACTIVE_TURN_RECONCILIATION_CLOSE_CODE,
40063
- "Active Agent turn reconciliation failed",
40064
- "reconciliation"
40065
- );
40066
- }
40067
- );
40082
+ publisher.connect(socket);
40068
40083
  if (signal.aborted) {
40069
40084
  stop();
40070
40085
  }
@@ -40096,7 +40111,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
40096
40111
  const activeTurns = /* @__PURE__ */ new Map();
40097
40112
  const recordSessionEvent = (sessionId, event) => {
40098
40113
  for (const turn of activeTurns.values()) {
40099
- turn.recordInteraction(event);
40114
+ turn.recordEvent(event);
40100
40115
  }
40101
40116
  publisher.publish(sessionId, event);
40102
40117
  };