@moxt-ai/mobius 0.0.111 → 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.
Files changed (41) hide show
  1. package/dist/acp/codex/agent.d.ts.map +1 -1
  2. package/dist/acp/codex/agent.js +76 -3
  3. package/dist/acp/codex/agent.js.map +1 -1
  4. package/dist/acp/codex/app-server-protocol.d.ts +3 -0
  5. package/dist/acp/codex/app-server-protocol.d.ts.map +1 -1
  6. package/dist/acp/codex/app-server-protocol.js +1 -0
  7. package/dist/acp/codex/app-server-protocol.js.map +1 -1
  8. package/dist/acp/codex/items.d.ts +1 -1
  9. package/dist/acp/codex/items.d.ts.map +1 -1
  10. package/dist/acp/codex/items.js +6 -3
  11. package/dist/acp/codex/items.js.map +1 -1
  12. package/dist/cli.js +453 -262
  13. package/dist/cli.js.map +4 -4
  14. package/dist/daemon-active-turn.d.ts +33 -0
  15. package/dist/daemon-active-turn.d.ts.map +1 -0
  16. package/dist/daemon-active-turn.js +152 -0
  17. package/dist/daemon-active-turn.js.map +1 -0
  18. package/dist/daemon-session-commands.d.ts +21 -7
  19. package/dist/daemon-session-commands.d.ts.map +1 -1
  20. package/dist/daemon-session-commands.js +26 -26
  21. package/dist/daemon-session-commands.js.map +1 -1
  22. package/dist/index.js +452 -261
  23. package/dist/index.js.map +4 -4
  24. package/dist/native-sessions/live-history-page.d.ts +7 -2
  25. package/dist/native-sessions/live-history-page.d.ts.map +1 -1
  26. package/dist/native-sessions/live-history-page.js +87 -1
  27. package/dist/native-sessions/live-history-page.js.map +1 -1
  28. package/dist/relay-connection/diagnostics.d.ts +0 -5
  29. package/dist/relay-connection/diagnostics.d.ts.map +1 -1
  30. package/dist/relay-connection/diagnostics.js +0 -14
  31. package/dist/relay-connection/diagnostics.js.map +1 -1
  32. package/dist/run-daemon.d.ts.map +1 -1
  33. package/dist/run-daemon.js +49 -40
  34. package/dist/run-daemon.js.map +1 -1
  35. package/dist/runtime.js +454 -263
  36. package/dist/runtime.js.map +4 -4
  37. package/package.json +1 -1
  38. package/dist/daemon-turn-reconciliation.d.ts +0 -41
  39. package/dist/daemon-turn-reconciliation.d.ts.map +0 -1
  40. package/dist/daemon-turn-reconciliation.js +0 -173
  41. package/dist/daemon-turn-reconciliation.js.map +0 -1
package/dist/index.js CHANGED
@@ -20433,12 +20433,14 @@ var encodeAgentInstallCancelledEvent = (message) => encode3(message, agentInstal
20433
20433
 
20434
20434
  // ../protocol/src/messages.ts
20435
20435
  var SESSION_PROMPT_KIND = "session.prompt";
20436
+ var SESSION_PROMPT_DISPOSITION_KIND = "session.prompt.disposition";
20436
20437
  var RUNTIME_WORKSPACE_BINDING_ID = "workspace";
20437
20438
  var SESSION_CANCEL_KIND = "session.cancel";
20438
20439
  var RUNTIME_LIVENESS_READY_KIND = "runtime.liveness.ready";
20439
20440
  var RUNTIME_HEARTBEAT_KIND = "runtime.heartbeat";
20440
20441
  var RUNTIME_HEARTBEAT_ACK_KIND = "runtime.heartbeat.ack";
20441
20442
  var SESSION_STARTED_KIND = "session.started";
20443
+ var SESSION_QUEUED_KIND = "session.queued";
20442
20444
  var AGENT_MESSAGE_DELTA_KIND = "agent.message.delta";
20443
20445
  var AGENT_ACTIVITY_KIND = "agent.activity";
20444
20446
  var AGENT_ACTIVITY_NARRATION_KIND = "agent.activity.narration";
@@ -20722,6 +20724,30 @@ function decodeSessionCancelCommand(encoded) {
20722
20724
  sessionId: readIdentifier(value, "sessionId")
20723
20725
  };
20724
20726
  }
20727
+ function decodeSessionPromptDispositionCommand(encoded) {
20728
+ const value = parseJson2(encoded);
20729
+ assertExactKeys(value, ["commandId", "disposition", "kind", "sessionId"]);
20730
+ assertKind(value, SESSION_PROMPT_DISPOSITION_KIND);
20731
+ if (readPromptDisposition(value) !== SessionPromptDisposition.Steer) {
20732
+ throw new ProtocolMessageError("Only queued prompts can be steered");
20733
+ }
20734
+ return {
20735
+ commandId: readIdentifier(value, "commandId"),
20736
+ disposition: SessionPromptDisposition.Steer,
20737
+ kind: SESSION_PROMPT_DISPOSITION_KIND,
20738
+ sessionId: readIdentifier(value, "sessionId")
20739
+ };
20740
+ }
20741
+ function decodeSessionQueuedEvent(encoded) {
20742
+ const value = parseJson2(encoded);
20743
+ assertExactKeys(value, ["commandId", "kind", "sessionId"]);
20744
+ assertKind(value, SESSION_QUEUED_KIND);
20745
+ return {
20746
+ commandId: readIdentifier(value, "commandId"),
20747
+ kind: SESSION_QUEUED_KIND,
20748
+ sessionId: readIdentifier(value, "sessionId")
20749
+ };
20750
+ }
20725
20751
  function decodeRuntimeLivenessReadyEvent(encoded) {
20726
20752
  const value = parseJson2(encoded);
20727
20753
  assertExactKeys(value, ["kind"]);
@@ -20849,6 +20875,12 @@ function encodeSessionPromptCommand(message) {
20849
20875
  function encodeSessionCancelCommand(message) {
20850
20876
  return JSON.stringify(decodeSessionCancelCommand(JSON.stringify(message)));
20851
20877
  }
20878
+ function encodeSessionPromptDispositionCommand(message) {
20879
+ return JSON.stringify(decodeSessionPromptDispositionCommand(JSON.stringify(message)));
20880
+ }
20881
+ function encodeSessionQueuedEvent(message) {
20882
+ return JSON.stringify(decodeSessionQueuedEvent(JSON.stringify(message)));
20883
+ }
20852
20884
  function encodeRuntimeLivenessReadyEvent(message) {
20853
20885
  return JSON.stringify(decodeRuntimeLivenessReadyEvent(JSON.stringify(message)));
20854
20886
  }
@@ -20980,6 +21012,19 @@ var envelope = {
20980
21012
  requestId: identifierStringSchema,
20981
21013
  sessionId: identifierStringSchema
20982
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();
20983
21028
  var identity = {
20984
21029
  ...envelope,
20985
21030
  kind: external_exports.literal(NATIVE_SESSION_REQUEST_KIND),
@@ -21055,7 +21100,9 @@ var nativeSessionResultSchema = external_exports.discriminatedUnion("action", [
21055
21100
  action: external_exports.literal("active-turn"),
21056
21101
  targetSessionId: identifierStringSchema,
21057
21102
  turn: external_exports.strictObject({
21103
+ activities: external_exports.array(activeTurnActivitySchema).max(100).readonly(),
21058
21104
  commandId: identifierStringSchema,
21105
+ content: external_exports.array(displayContentSchema).max(100).readonly(),
21059
21106
  prompt: external_exports.string().max(1e5),
21060
21107
  text: external_exports.string().max(ACTIVE_TURN_TEXT_LIMIT),
21061
21108
  truncated: external_exports.boolean(),
@@ -21359,6 +21406,11 @@ var serviceToDaemonSignatures = {
21359
21406
  encodeSessionPromptCommand,
21360
21407
  decodeSessionPromptCommand
21361
21408
  ),
21409
+ [SESSION_PROMPT_DISPOSITION_KIND]: defineMessageSignature(
21410
+ SESSION_PROMPT_DISPOSITION_KIND,
21411
+ encodeSessionPromptDispositionCommand,
21412
+ decodeSessionPromptDispositionCommand
21413
+ ),
21362
21414
  [WORKSPACE_LIST_KIND]: defineMessageSignature(
21363
21415
  WORKSPACE_LIST_KIND,
21364
21416
  encodeWorkspaceListCommand,
@@ -21429,6 +21481,11 @@ var daemonToServiceSignatures = {
21429
21481
  encodeSessionsQueriedEvent,
21430
21482
  decodeSessionsQueriedEvent
21431
21483
  ),
21484
+ [SESSION_QUEUED_KIND]: defineMessageSignature(
21485
+ SESSION_QUEUED_KIND,
21486
+ encodeSessionQueuedEvent,
21487
+ decodeSessionQueuedEvent
21488
+ ),
21432
21489
  [NATIVE_SESSION_RESULT_KIND]: defineMessageSignature(
21433
21490
  NATIVE_SESSION_RESULT_KIND,
21434
21491
  encodeNativeSessionResult,
@@ -27291,6 +27348,7 @@ var turnSchema = external_exports.object({
27291
27348
  id: boundedText(256),
27292
27349
  status: turnStatusSchema
27293
27350
  });
27351
+ var turnSteerResponseSchema = external_exports.object({ turnId: boundedText(256) });
27294
27352
  var turnNotificationSchema = external_exports.object({
27295
27353
  thread: external_exports.object({ id: boundedText(256) }).nullish(),
27296
27354
  threadId: boundedText(256),
@@ -27675,7 +27733,10 @@ function presentToolItem(item) {
27675
27733
  kind: "execute",
27676
27734
  locations: [],
27677
27735
  rawInput: { command: item.command, cwd: item.cwd },
27678
- rawOutput: { exitCode: item.exitCode, output: truncate4(output2, TOOL_OUTPUT_CHARACTER_LIMIT) },
27736
+ rawOutput: {
27737
+ ...item.exitCode == null ? {} : { exitCode: item.exitCode },
27738
+ output: truncate4(output2, TOOL_OUTPUT_CHARACTER_LIMIT)
27739
+ },
27679
27740
  status: commandStatus(item.status),
27680
27741
  title: truncate4(firstLine(item.command), TITLE_CHARACTER_LIMIT)
27681
27742
  };
@@ -27731,7 +27792,7 @@ function presentToolItem(item) {
27731
27792
  }
27732
27793
  return null;
27733
27794
  }
27734
- function toolCallUpdate(item) {
27795
+ function toolCallUpdate(item, lifecycle) {
27735
27796
  const presentation = presentToolItem(item);
27736
27797
  if (presentation === null) {
27737
27798
  return null;
@@ -27742,7 +27803,7 @@ function toolCallUpdate(item) {
27742
27803
  locations: [...presentation.locations],
27743
27804
  rawInput: presentation.rawInput,
27744
27805
  rawOutput: presentation.rawOutput,
27745
- status: presentation.status,
27806
+ status: lifecycle === "completed" && presentation.status === "in_progress" ? "completed" : presentation.status,
27746
27807
  title: presentation.title,
27747
27808
  toolCallId: item.id
27748
27809
  };
@@ -27851,6 +27912,54 @@ function promptInput(prompt) {
27851
27912
  }
27852
27913
  return input2;
27853
27914
  }
27915
+ function steeringPromptInput(prompt) {
27916
+ const input2 = [];
27917
+ for (const block of prompt) {
27918
+ if (typeof block !== "object" || block === null) {
27919
+ throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
27920
+ }
27921
+ const type = Reflect.get(block, "type");
27922
+ if (type === "text") {
27923
+ const text = Reflect.get(block, "text");
27924
+ if (typeof text !== "string") {
27925
+ throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
27926
+ }
27927
+ input2.push({ text, text_elements: [], type: "text" });
27928
+ continue;
27929
+ }
27930
+ if (type === "image") {
27931
+ const data = Reflect.get(block, "data");
27932
+ const mimeType = Reflect.get(block, "mimeType");
27933
+ if (typeof data !== "string" || typeof mimeType !== "string") {
27934
+ throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
27935
+ }
27936
+ input2.push({ type: "image", url: `data:${mimeType};base64,${data}` });
27937
+ continue;
27938
+ }
27939
+ if (type === "resource") {
27940
+ const resource = Reflect.get(block, "resource");
27941
+ if (typeof resource !== "object" || resource === null) {
27942
+ throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
27943
+ }
27944
+ const text = Reflect.get(resource, "text");
27945
+ if (text !== void 0 && typeof text !== "string") {
27946
+ throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
27947
+ }
27948
+ input2.push({ text: text ?? "", text_elements: [], type: "text" });
27949
+ continue;
27950
+ }
27951
+ if (type === "resource_link") {
27952
+ const uri = Reflect.get(block, "uri");
27953
+ if (typeof uri !== "string") {
27954
+ throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
27955
+ }
27956
+ input2.push({ text: `Resource: ${uri}`, text_elements: [], type: "text" });
27957
+ continue;
27958
+ }
27959
+ throw new AcpExecutionError("Codex received an unsupported steering prompt", {}, "invalid_request");
27960
+ }
27961
+ return input2;
27962
+ }
27854
27963
  function modelValues(models) {
27855
27964
  return models.map((model) => ({
27856
27965
  description: model.description ?? "",
@@ -28029,6 +28138,7 @@ var CodexAcpAgent = class {
28029
28138
  this.#app = createAgentApp({ name: "mobius-codex" }).onConnect((connection) => {
28030
28139
  this.#connection = connection;
28031
28140
  }).onRequest(methods4.agent.initialize, async () => ({
28141
+ _meta: { steering: { supported: true } },
28032
28142
  agentCapabilities: {
28033
28143
  loadSession: true,
28034
28144
  promptCapabilities: { embeddedContext: true, image: true },
@@ -28102,7 +28212,11 @@ var CodexAcpAgent = class {
28102
28212
  return { configOptions: this.#configOptions() };
28103
28213
  }).onRequest(methods4.agent.session.prompt, async (context) => {
28104
28214
  return await this.#runTurn(promptInput(context.params.prompt), context.signal);
28105
- }).onRequest(methods4.agent.session.list, async (context) => {
28215
+ }).onRequest(
28216
+ "_session/steering",
28217
+ (params) => params,
28218
+ async (context) => await this.#steerTurn(context.params, context.signal)
28219
+ ).onRequest(methods4.agent.session.list, async (context) => {
28106
28220
  const decoded = threadListResponseSchema.parse(
28107
28221
  await this.#appServer.request(
28108
28222
  "thread/list",
@@ -28269,7 +28383,7 @@ var CodexAcpAgent = class {
28269
28383
  });
28270
28384
  continue;
28271
28385
  }
28272
- const update = toolCallUpdate(item);
28386
+ const update = toolCallUpdate(item, "snapshot");
28273
28387
  if (update !== null) {
28274
28388
  await this.#emit({ ...update, sessionUpdate: "tool_call_update" });
28275
28389
  }
@@ -28466,7 +28580,7 @@ var CodexAcpAgent = class {
28466
28580
  });
28467
28581
  return;
28468
28582
  }
28469
- const update = toolCallUpdate(item);
28583
+ const update = toolCallUpdate(item, method === "item/completed" ? "completed" : "started");
28470
28584
  if (update !== null) {
28471
28585
  await this.#enqueue(async () => {
28472
28586
  await this.#emit({ ...update, sessionUpdate: "tool_call_update" });
@@ -28652,6 +28766,35 @@ var CodexAcpAgent = class {
28652
28766
  }
28653
28767
  }
28654
28768
  };
28769
+ #steerTurn = async (params, signal) => {
28770
+ if (typeof params !== "object" || params === null) {
28771
+ throw new AcpExecutionError("Codex received an invalid steering request", {}, "invalid_request");
28772
+ }
28773
+ const sessionId = Reflect.get(params, "sessionId");
28774
+ const prompt = Reflect.get(params, "prompt");
28775
+ if (typeof sessionId !== "string" || !Array.isArray(prompt)) {
28776
+ throw new AcpExecutionError("Codex received an invalid steering request", {}, "invalid_request");
28777
+ }
28778
+ const active = this.#turn;
28779
+ if (sessionId !== this.#nativeSessionId || active === null || active.turn.id.length === 0) {
28780
+ return { outcome: "promptRequired", reason: "noRunningTurn" };
28781
+ }
28782
+ const input2 = steeringPromptInput(prompt);
28783
+ if (input2.length === 0) {
28784
+ throw new AcpExecutionError("Codex received an empty steering request", {}, "invalid_request");
28785
+ }
28786
+ const response = turnSteerResponseSchema.parse(
28787
+ await this.#appServer.request(
28788
+ "turn/steer",
28789
+ { expectedTurnId: active.turn.id, input: input2, threadId: this.#nativeSessionId },
28790
+ AbortSignal.any([signal, AbortSignal.timeout(APPROVAL_TIMEOUT_MILLISECONDS)])
28791
+ )
28792
+ );
28793
+ if (response.turnId !== active.turn.id) {
28794
+ throw new AcpExecutionError("Codex steered an unexpected turn", {}, "steering_target_unavailable");
28795
+ }
28796
+ return { outcome: "injected" };
28797
+ };
28655
28798
  #interruptTurn = async () => {
28656
28799
  const turn = this.#turn;
28657
28800
  if (turn === null) {
@@ -31765,7 +31908,10 @@ function liveHistoryCoveredTurnRanges(history) {
31765
31908
  }
31766
31909
  return ranges;
31767
31910
  }
31768
- 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) {
31769
31915
  if (history.status === "unavailable") {
31770
31916
  if (cursor !== null) {
31771
31917
  throw new AcpExecutionError("Unavailable native Session history has no cursor", {}, "invalid_cursor");
@@ -31791,6 +31937,80 @@ function paginateLiveSessionHistory(history, sessionId, cursor, limit) {
31791
31937
  truncated: history.truncated
31792
31938
  };
31793
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
+ }
31794
32014
 
31795
32015
  // src/prompt-artifact-resolver.ts
31796
32016
  import { createHash as createHash3 } from "node:crypto";
@@ -32422,7 +32642,7 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
32422
32642
  reportOperationFailure(socket, command.requestId, command.sessionId, error62, metrics.snapshot());
32423
32643
  }
32424
32644
  }
32425
- async function executeSessionLiveHistoryLoad(socket, command, config2, directories, audit, sessions, signal) {
32645
+ async function executeSessionLiveHistoryLoad(socket, command, config2, directories, audit, sessions, activeTurn, signal) {
32426
32646
  try {
32427
32647
  const resolved = await resolveSessionDirectories(
32428
32648
  directories,
@@ -32439,13 +32659,14 @@ async function executeSessionLiveHistoryLoad(socket, command, config2, directori
32439
32659
  signal
32440
32660
  });
32441
32661
  signal.throwIfAborted();
32662
+ const mergedHistory = mergeLiveSessionHistory(history, activeTurn(command.sessionId), command.sessionId);
32442
32663
  audit.record({
32443
32664
  commandId: command.requestId,
32444
32665
  event: "session_history_loaded",
32445
32666
  sessionId: command.sessionId
32446
32667
  });
32447
32668
  send(socket, {
32448
- history,
32669
+ history: mergedHistory,
32449
32670
  kind: "session.live-history.loaded",
32450
32671
  requestId: command.requestId,
32451
32672
  sessionId: command.sessionId
@@ -32471,7 +32692,7 @@ async function executeSessionLiveHistoryLoad(socket, command, config2, directori
32471
32692
  });
32472
32693
  }
32473
32694
  }
32474
- async function executeSessionLiveHistoryPageLoad(socket, command, config2, directories, audit, sessions, signal) {
32695
+ async function executeSessionLiveHistoryPageLoad(socket, command, config2, directories, audit, sessions, activeTurn, signal) {
32475
32696
  try {
32476
32697
  const resolved = await resolveSessionDirectories(
32477
32698
  directories,
@@ -32488,7 +32709,13 @@ async function executeSessionLiveHistoryPageLoad(socket, command, config2, direc
32488
32709
  signal
32489
32710
  });
32490
32711
  signal.throwIfAborted();
32491
- 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
+ );
32492
32719
  audit.record({
32493
32720
  commandId: command.requestId,
32494
32721
  event: "session_history_loaded",
@@ -32561,14 +32788,11 @@ async function executeSessionConfigure(publisher, socket, command, config2, dire
32561
32788
  reportOperationFailure(socket, command.requestId, command.sessionId, error62);
32562
32789
  }
32563
32790
  }
32564
- async function executePrompt(operations, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, waitForSessionAvailability, timer, signal, recordLiveText, cancellationRequested) {
32565
- const activities = new CoalescingDaemonActivityPublisher(timer, (activity2) => {
32566
- publisher.publish(command.sessionId, daemonActivity(command, activity2));
32567
- });
32791
+ async function executePrompt(operations, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, acknowledgeQueued, waitForSessionAvailability, timer, signal, recordLiveEvent, cancellationRequested) {
32568
32792
  const narration = new CoalescingNarrationPublisher(
32569
32793
  timer,
32570
32794
  (increment) => {
32571
- publisher.publish(command.sessionId, {
32795
+ const event = {
32572
32796
  activityId: increment.activityId,
32573
32797
  activityType: increment.activityType,
32574
32798
  commandId: command.commandId,
@@ -32576,29 +32800,34 @@ async function executePrompt(operations, publisher, command, config2, directorie
32576
32800
  sequence: increment.sequence,
32577
32801
  sessionId: command.sessionId,
32578
32802
  text: increment.text
32579
- });
32803
+ };
32804
+ publisher.publish(command.sessionId, recordLiveEvent(event));
32580
32805
  },
32581
32806
  AGENT_ACTIVITY_COALESCING_MILLISECONDS,
32582
32807
  AGENT_TEXT_MAXIMUM_LENGTH
32583
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
+ });
32584
32816
  const text = new CoalescingTextPublisher(
32585
32817
  timer,
32586
32818
  (messageId, delta) => {
32587
- const stream = recordLiveText(delta);
32588
- publisher.publish(command.sessionId, {
32589
- commandId: command.commandId,
32590
- epoch: stream.epoch,
32591
- kind: AGENT_MESSAGE_DELTA_KIND,
32592
- messageId,
32593
- sequence: stream.sequence,
32594
- sessionId: command.sessionId,
32595
- text: delta
32596
- });
32819
+ publisher.publish(
32820
+ command.sessionId,
32821
+ recordLiveEvent({ kind: AGENT_MESSAGE_DELTA_KIND, messageId, text: delta })
32822
+ );
32597
32823
  },
32598
32824
  AGENT_TEXT_COALESCING_MILLISECONDS,
32599
32825
  AGENT_TEXT_MAXIMUM_LENGTH
32600
32826
  );
32601
32827
  try {
32828
+ if (command.disposition === SessionPromptDisposition.Queue) {
32829
+ acknowledgeQueued();
32830
+ }
32602
32831
  const resolved = await resolveSessionDirectories(
32603
32832
  directories,
32604
32833
  command.bindingId,
@@ -32608,10 +32837,10 @@ async function executePrompt(operations, publisher, command, config2, directorie
32608
32837
  );
32609
32838
  const agent = config2.catalog.find(command.agentId);
32610
32839
  const availability = await waitForSessionAvailability(signal);
32611
- if (availability === "busy") {
32840
+ if (availability.kind === "busy") {
32612
32841
  throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
32613
32842
  }
32614
- if (availability === "queue-target-unavailable") {
32843
+ if (availability.kind === "queue-target-unavailable") {
32615
32844
  throw new AcpExecutionError(
32616
32845
  "The queued prompt target is unavailable",
32617
32846
  {},
@@ -32629,7 +32858,7 @@ async function executePrompt(operations, publisher, command, config2, directorie
32629
32858
  sessionId: command.sessionId,
32630
32859
  signal
32631
32860
  });
32632
- if (command.disposition === SessionPromptDisposition.Steer) {
32861
+ if (availability.disposition === SessionPromptDisposition.Steer) {
32633
32862
  assertAppliedSessionConfiguration(prepared.configOptions, sessionConfigurations ?? []);
32634
32863
  } else {
32635
32864
  await applyCompleteSessionConfiguration(
@@ -32664,7 +32893,7 @@ async function executePrompt(operations, publisher, command, config2, directorie
32664
32893
  });
32665
32894
  const attachments = await resolvePromptArtifacts(config2, command, signal);
32666
32895
  let stopReason;
32667
- if (command.disposition === SessionPromptDisposition.Steer) {
32896
+ if (availability.disposition === SessionPromptDisposition.Steer) {
32668
32897
  await sessions.steerPrompt({
32669
32898
  additionalDirectories: resolved.additionalDirectories,
32670
32899
  agent: executionAgent,
@@ -32684,7 +32913,7 @@ async function executePrompt(operations, publisher, command, config2, directorie
32684
32913
  agent: executionAgent,
32685
32914
  commandId: command.commandId,
32686
32915
  cwd: resolved.cwd,
32687
- disposition: command.disposition,
32916
+ disposition: availability.disposition,
32688
32917
  images: attachments.images,
32689
32918
  onActivity: activities.record,
32690
32919
  onNarration: (increment) => {
@@ -34059,6 +34288,144 @@ var WorkspaceDirectoryService = class {
34059
34288
  };
34060
34289
  };
34061
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
+
34062
34429
  // src/daemon-diagnostic-log.ts
34063
34430
  import { appendFileSync, mkdirSync, readFileSync as readFileSync2, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
34064
34431
  import { join as join17 } from "node:path";
@@ -34241,167 +34608,6 @@ var DaemonInstallationObserver = class {
34241
34608
  };
34242
34609
  };
34243
34610
 
34244
- // src/daemon-turn-reconciliation.ts
34245
- import { randomUUID as randomUUID3 } from "node:crypto";
34246
- import { fetch as fetch5 } from "undici";
34247
- var ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS = 2e4;
34248
- var ActiveDaemonTurn = class {
34249
- attemptId;
34250
- command;
34251
- #controller;
34252
- #finished = Promise.withResolvers();
34253
- #cancellationRequested = false;
34254
- #accepted = false;
34255
- #text = "";
34256
- #truncated = false;
34257
- #sequence = 0;
34258
- #interaction = null;
34259
- #epoch = decodeIdentifier(randomUUID3());
34260
- constructor(command, attemptId) {
34261
- this.attemptId = attemptId;
34262
- this.command = command;
34263
- this.#controller = new AbortController();
34264
- }
34265
- abortDaemon = () => {
34266
- this.#controller.abort();
34267
- };
34268
- finish = () => this.#finished.resolve();
34269
- accept = () => {
34270
- this.#accepted = true;
34271
- return { epoch: this.#epoch, sequence: 0 };
34272
- };
34273
- recordText = (delta) => {
34274
- this.#sequence += 1;
34275
- this.#text += delta;
34276
- if (this.#text.length > ACTIVE_TURN_TEXT_LIMIT) {
34277
- this.#text = this.#text.slice(-ACTIVE_TURN_TEXT_LIMIT);
34278
- this.#truncated = true;
34279
- }
34280
- return { epoch: this.#epoch, sequence: this.#sequence };
34281
- };
34282
- recordInteraction = (event) => {
34283
- if (event.sessionId !== this.command.sessionId) {
34284
- return;
34285
- }
34286
- if (event.kind === SESSION_PERMISSION_REQUESTED_KIND || event.kind === SESSION_ELICITATION_REQUESTED_KIND) {
34287
- if (event.commandId === this.command.commandId) {
34288
- this.#interaction = event;
34289
- }
34290
- } else if ((event.kind === SESSION_PERMISSION_RESOLVED_KIND || event.kind === SESSION_ELICITATION_RESOLVED_KIND) && this.#interaction?.interactionId === event.interactionId) {
34291
- this.#interaction = null;
34292
- }
34293
- };
34294
- snapshot = () => this.#accepted ? {
34295
- commandId: decodeIdentifier(this.command.commandId),
34296
- prompt: this.command.prompt,
34297
- text: this.#text,
34298
- truncated: this.#truncated,
34299
- epoch: this.#epoch,
34300
- interaction: this.#interaction,
34301
- sequence: this.#sequence,
34302
- state: "running"
34303
- } : null;
34304
- matches = (cancellation) => cancellation.commandId === this.command.commandId && cancellation.sessionId === this.command.sessionId;
34305
- requestCancellation = () => {
34306
- if (this.#cancellationRequested) {
34307
- return "already-requested";
34308
- }
34309
- this.#cancellationRequested = true;
34310
- if (!this.#accepted) {
34311
- this.#controller.abort(new Error("The queued Agent turn was cancelled"));
34312
- return "pending";
34313
- }
34314
- return "running";
34315
- };
34316
- cancellationRequested = () => this.#cancellationRequested;
34317
- get signal() {
34318
- return this.#controller.signal;
34319
- }
34320
- get completion() {
34321
- return this.#finished.promise;
34322
- }
34323
- };
34324
- var ActiveTurnReconciliationError = class extends Error {
34325
- code = "active_turn_reconciliation_failed";
34326
- diagnosticDetails;
34327
- relayErrorCode;
34328
- terminal;
34329
- constructor(message, options = {}) {
34330
- super(message, options);
34331
- this.name = "ActiveTurnReconciliationError";
34332
- this.relayErrorCode = options.relayErrorCode ?? null;
34333
- this.terminal = options.terminal ?? false;
34334
- this.diagnosticDetails = this.relayErrorCode === null ? {} : { relayErrorCode: this.relayErrorCode };
34335
- }
34336
- };
34337
- var TERMINAL_RECONCILIATION_RELAY_CODES = /* @__PURE__ */ new Set(["session_conflict"]);
34338
- async function relayErrorCode(response) {
34339
- try {
34340
- const body = JSON.parse(await response.text());
34341
- if (typeof body !== "object" || body === null) {
34342
- return null;
34343
- }
34344
- const error62 = Reflect.get(body, "error");
34345
- if (typeof error62 !== "object" || error62 === null) {
34346
- return null;
34347
- }
34348
- const code = Reflect.get(error62, "code");
34349
- return typeof code === "string" && code.length > 0 ? code : null;
34350
- } catch {
34351
- return null;
34352
- }
34353
- }
34354
- function activeTurnReconciliationEndpoint(config2, turn) {
34355
- const endpoint = relayHttpEndpoint(config2.relayUrl);
34356
- let channelPath = "";
34357
- if (endpoint.pathname.endsWith("/daemon")) {
34358
- channelPath = endpoint.pathname.slice(0, -"/daemon".length);
34359
- } else {
34360
- const runtimePath = "/v1/runtimes/connect";
34361
- if (!endpoint.pathname.endsWith(runtimePath)) {
34362
- throw new ActiveTurnReconciliationError("The Relay URL is invalid");
34363
- }
34364
- channelPath = `${endpoint.pathname.slice(0, -runtimePath.length)}/channels/${encodeURIComponent(config2.channelId)}`;
34365
- }
34366
- endpoint.pathname = `${channelPath}/sessions/${encodeURIComponent(turn.command.sessionId)}/attempts/${encodeURIComponent(turn.attemptId)}/reconciliation`;
34367
- return endpoint;
34368
- }
34369
- async function reconcileActiveTurn(config2, turn, signal) {
34370
- signal.throwIfAborted();
34371
- const timeoutSignal = AbortSignal.timeout(ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS);
34372
- const requestSignal = AbortSignal.any([signal, timeoutSignal]);
34373
- let response;
34374
- try {
34375
- response = await fetch5(activeTurnReconciliationEndpoint(config2, turn), {
34376
- body: JSON.stringify({ outcome: { kind: "running" } }),
34377
- dispatcher: environmentProxyDispatcher,
34378
- headers: { ...runtimeAuthorization(config2.relayUrl), "content-type": "application/json" },
34379
- method: "POST",
34380
- signal: requestSignal
34381
- });
34382
- } catch (error62) {
34383
- if (signal.aborted) {
34384
- signal.throwIfAborted();
34385
- }
34386
- throw new ActiveTurnReconciliationError(
34387
- timeoutSignal.aborted ? "The active Agent turn reconciliation timed out" : "The active Agent turn could not be reconciled",
34388
- { cause: error62 }
34389
- );
34390
- }
34391
- if (!response.ok) {
34392
- const errorCode = await relayErrorCode(response);
34393
- const terminal = errorCode !== null && TERMINAL_RECONCILIATION_RELAY_CODES.has(errorCode);
34394
- throw new ActiveTurnReconciliationError(
34395
- 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()}`,
34396
- { relayErrorCode: errorCode, terminal }
34397
- );
34398
- }
34399
- await response.body?.cancel();
34400
- }
34401
- async function reconcileActiveTurns(config2, turns, signal) {
34402
- await Promise.all(turns.map(async (turn) => await reconcileActiveTurn(config2, turn, signal)));
34403
- }
34404
-
34405
34611
  // src/native-sessions/codex-history.ts
34406
34612
  import { spawn as spawn5 } from "node:child_process";
34407
34613
  var responseSchema = external_exports.union([
@@ -35680,25 +35886,6 @@ var RelayConnectionDiagnostics = class {
35680
35886
  addFailureDetails(details, failure2);
35681
35887
  this.#record("relay_connection_failed", connectionEpoch.toString(), details, true);
35682
35888
  };
35683
- /**
35684
- * Records that the Runtime gave up on Agent turns the Relay already settled. This is not a connection
35685
- * failure, so it is recorded independently of the per-epoch failure deduplication.
35686
- */
35687
- reconciliationAbandoned = (connectionEpoch, relayErrorCode2, turnCount) => {
35688
- this.#record(
35689
- "relay_reconciliation_abandoned",
35690
- connectionEpoch.toString(),
35691
- {
35692
- connectionEpoch: connectionEpoch.toString(),
35693
- relayErrorCode: relayErrorCode2 ?? "unknown",
35694
- relayOrigin: this.#relayOrigin,
35695
- source: "reconciliation_abandoned",
35696
- turnCount: turnCount.toString(),
35697
- ...this.#route
35698
- },
35699
- true
35700
- );
35701
- };
35702
35889
  connectionOpened = (connectionEpoch) => {
35703
35890
  this.#record(
35704
35891
  "relay_connection_opened",
@@ -35926,7 +36113,6 @@ var systemDaemonTimer = new SystemDaemonTimer();
35926
36113
 
35927
36114
  // src/run-daemon.ts
35928
36115
  var RELAY_RECONNECT_DELAY_MILLISECONDS = 500;
35929
- var ACTIVE_TURN_RECONCILIATION_CLOSE_CODE = 4009;
35930
36116
  function closeRelaySocket(socket, code, reason) {
35931
36117
  try {
35932
36118
  socket.close(code, reason);
@@ -35995,7 +36181,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
35995
36181
  const relayUrl = new URL(config2.relayUrl);
35996
36182
  relayUrl.searchParams.set("liveness", "1");
35997
36183
  const socket = await connectRelay(relayUrl, signal);
35998
- const reconnectingTurns = [...activeTurns.values()];
35999
36184
  diagnostics.connectionOpened(connectionEpoch);
36000
36185
  const connectionController = new AbortController();
36001
36186
  const handleSettingsDiscovery = createAgentSettingsDiscoveryHandler({
@@ -36017,6 +36202,18 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36017
36202
  timer,
36018
36203
  resolveEnvironment: resolveAgentCatalogEnvironment
36019
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
+ };
36020
36217
  const nativeRequestHandler = createNativeSessionRequestHandler({
36021
36218
  audit,
36022
36219
  diagnostics,
@@ -36091,24 +36288,34 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36091
36288
  );
36092
36289
  });
36093
36290
  };
36094
- const waitForSessionAvailability = async (command, waitSignal) => {
36095
- if (command.disposition === SessionPromptDisposition.Steer) {
36096
- return "available";
36291
+ const waitForSessionAvailability = async (command, queuedTurn, waitSignal) => {
36292
+ if (queuedTurn.effectiveDisposition() === SessionPromptDisposition.Steer) {
36293
+ return { disposition: SessionPromptDisposition.Steer, kind: "available" };
36097
36294
  }
36098
36295
  for (; ; ) {
36099
36296
  const first = [...activeTurns.values()].find(
36100
36297
  (turn) => turn.command.sessionId === command.sessionId && turn.command.disposition !== SessionPromptDisposition.Steer
36101
36298
  );
36102
36299
  if (first === void 0 || first.command.commandId === command.commandId) {
36103
- return command.disposition !== SessionPromptDisposition.Queue || operations.isTerminalExecution(command.targetCommandId, command.sessionId) ? "available" : "queue-target-unavailable";
36300
+ return command.disposition !== SessionPromptDisposition.Queue || operations.isTerminalExecution(command.targetCommandId, command.sessionId) ? { disposition: queuedTurn.effectiveDisposition(), kind: "available" } : { kind: "queue-target-unavailable" };
36104
36301
  }
36105
36302
  if (command.disposition !== SessionPromptDisposition.Queue) {
36106
- return "busy";
36303
+ return { kind: "busy" };
36107
36304
  }
36108
36305
  if (first.command.commandId !== command.targetCommandId) {
36109
- return "queue-target-unavailable";
36306
+ return { kind: "queue-target-unavailable" };
36307
+ }
36308
+ const promotion = queuedTurn.queuePromotion();
36309
+ if (promotion === null) {
36310
+ throw new Error("The queued prompt cannot be promoted");
36311
+ }
36312
+ const decision = await Promise.race([
36313
+ waitForTurnCompletion(first, waitSignal).then(() => "target-completed"),
36314
+ promotion.then(() => "promoted")
36315
+ ]);
36316
+ if (decision === "promoted") {
36317
+ return { disposition: SessionPromptDisposition.Steer, kind: "available" };
36110
36318
  }
36111
- await waitForTurnCompletion(first, waitSignal);
36112
36319
  }
36113
36320
  };
36114
36321
  const connectionLiveness = new RelayConnectionLiveness(timer, {
@@ -36176,6 +36383,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36176
36383
  directories,
36177
36384
  audit,
36178
36385
  sessions,
36386
+ activeTurnSnapshot,
36179
36387
  connectionController.signal
36180
36388
  );
36181
36389
  return;
@@ -36189,6 +36397,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36189
36397
  directories,
36190
36398
  audit,
36191
36399
  sessions,
36400
+ activeTurnSnapshot,
36192
36401
  connectionController.signal
36193
36402
  );
36194
36403
  return;
@@ -36261,6 +36470,19 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36261
36470
  });
36262
36471
  return;
36263
36472
  }
36473
+ if (kind === SESSION_PROMPT_DISPOSITION_KIND) {
36474
+ const disposition = message;
36475
+ const turn2 = activeTurns.get(disposition.commandId);
36476
+ if (turn2 === void 0 || !turn2.promoteQueuedPrompt(disposition)) {
36477
+ reportOperationFailure(
36478
+ socket,
36479
+ disposition.commandId,
36480
+ disposition.sessionId,
36481
+ new Error("The queued prompt is unavailable")
36482
+ );
36483
+ }
36484
+ return;
36485
+ }
36264
36486
  if (kind === WORKSPACE_LIST_KIND) {
36265
36487
  const command2 = message;
36266
36488
  void executeWorkspaceList(socket, command2, directories, audit, connectionController.signal);
@@ -36370,10 +36592,15 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36370
36592
  sessions,
36371
36593
  receipt.attemptId,
36372
36594
  turn.accept,
36373
- (waitSignal) => waitForSessionAvailability(command, waitSignal),
36595
+ () => send(socket, {
36596
+ commandId: command.commandId,
36597
+ kind: SESSION_QUEUED_KIND,
36598
+ sessionId: command.sessionId
36599
+ }),
36600
+ (waitSignal) => waitForSessionAvailability(command, turn, waitSignal),
36374
36601
  timer,
36375
36602
  turn.signal,
36376
- turn.recordText,
36603
+ turn.recordEvent,
36377
36604
  turn.cancellationRequested
36378
36605
  ).catch((error62) => {
36379
36606
  console.error("Mobius daemon turn failed", error62);
@@ -36394,43 +36621,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36394
36621
  socket.addEventListener("close", handleClose);
36395
36622
  socket.addEventListener("error", handleError);
36396
36623
  socket.addEventListener("message", handleMessage);
36397
- void reconcileActiveTurns(config2, reconnectingTurns, connectionController.signal).then(
36398
- () => {
36399
- if (finished) {
36400
- return;
36401
- }
36402
- publisher.connect(socket);
36403
- },
36404
- (error62) => {
36405
- if (finished) {
36406
- return;
36407
- }
36408
- console.error("Mobius daemon could not reconcile active Agent turns", error62);
36409
- if (error62 instanceof ActiveTurnReconciliationError && error62.terminal) {
36410
- diagnostics.reconciliationAbandoned(
36411
- connectionEpoch,
36412
- error62.relayErrorCode,
36413
- reconnectingTurns.length
36414
- );
36415
- console.error(
36416
- "Mobius daemon abandoned Agent turns the Relay already settled",
36417
- error62.relayErrorCode
36418
- );
36419
- for (const turn of reconnectingTurns) {
36420
- activeTurns.delete(turn.command.commandId);
36421
- turn.abortDaemon();
36422
- }
36423
- publisher.connect(socket);
36424
- return;
36425
- }
36426
- failAndClose(
36427
- new Error("Active Agent turn reconciliation failed", { cause: error62 }),
36428
- ACTIVE_TURN_RECONCILIATION_CLOSE_CODE,
36429
- "Active Agent turn reconciliation failed",
36430
- "reconciliation"
36431
- );
36432
- }
36433
- );
36624
+ publisher.connect(socket);
36434
36625
  if (signal.aborted) {
36435
36626
  stop();
36436
36627
  }
@@ -36462,7 +36653,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
36462
36653
  const activeTurns = /* @__PURE__ */ new Map();
36463
36654
  const recordSessionEvent = (sessionId, event) => {
36464
36655
  for (const turn of activeTurns.values()) {
36465
- turn.recordInteraction(event);
36656
+ turn.recordEvent(event);
36466
36657
  }
36467
36658
  publisher.publish(sessionId, event);
36468
36659
  };