@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/runtime.js CHANGED
@@ -20407,12 +20407,14 @@ var encodeAgentInstallCancelledEvent = (message) => encode3(message, agentInstal
20407
20407
 
20408
20408
  // ../protocol/src/messages.ts
20409
20409
  var SESSION_PROMPT_KIND = "session.prompt";
20410
+ var SESSION_PROMPT_DISPOSITION_KIND = "session.prompt.disposition";
20410
20411
  var RUNTIME_WORKSPACE_BINDING_ID = "workspace";
20411
20412
  var SESSION_CANCEL_KIND = "session.cancel";
20412
20413
  var RUNTIME_LIVENESS_READY_KIND = "runtime.liveness.ready";
20413
20414
  var RUNTIME_HEARTBEAT_KIND = "runtime.heartbeat";
20414
20415
  var RUNTIME_HEARTBEAT_ACK_KIND = "runtime.heartbeat.ack";
20415
20416
  var SESSION_STARTED_KIND = "session.started";
20417
+ var SESSION_QUEUED_KIND = "session.queued";
20416
20418
  var AGENT_MESSAGE_DELTA_KIND = "agent.message.delta";
20417
20419
  var AGENT_ACTIVITY_KIND = "agent.activity";
20418
20420
  var AGENT_ACTIVITY_NARRATION_KIND = "agent.activity.narration";
@@ -20696,6 +20698,30 @@ function decodeSessionCancelCommand(encoded) {
20696
20698
  sessionId: readIdentifier(value, "sessionId")
20697
20699
  };
20698
20700
  }
20701
+ function decodeSessionPromptDispositionCommand(encoded) {
20702
+ const value = parseJson2(encoded);
20703
+ assertExactKeys(value, ["commandId", "disposition", "kind", "sessionId"]);
20704
+ assertKind(value, SESSION_PROMPT_DISPOSITION_KIND);
20705
+ if (readPromptDisposition(value) !== SessionPromptDisposition.Steer) {
20706
+ throw new ProtocolMessageError("Only queued prompts can be steered");
20707
+ }
20708
+ return {
20709
+ commandId: readIdentifier(value, "commandId"),
20710
+ disposition: SessionPromptDisposition.Steer,
20711
+ kind: SESSION_PROMPT_DISPOSITION_KIND,
20712
+ sessionId: readIdentifier(value, "sessionId")
20713
+ };
20714
+ }
20715
+ function decodeSessionQueuedEvent(encoded) {
20716
+ const value = parseJson2(encoded);
20717
+ assertExactKeys(value, ["commandId", "kind", "sessionId"]);
20718
+ assertKind(value, SESSION_QUEUED_KIND);
20719
+ return {
20720
+ commandId: readIdentifier(value, "commandId"),
20721
+ kind: SESSION_QUEUED_KIND,
20722
+ sessionId: readIdentifier(value, "sessionId")
20723
+ };
20724
+ }
20699
20725
  function decodeRuntimeLivenessReadyEvent(encoded) {
20700
20726
  const value = parseJson2(encoded);
20701
20727
  assertExactKeys(value, ["kind"]);
@@ -20823,6 +20849,12 @@ function encodeSessionPromptCommand(message) {
20823
20849
  function encodeSessionCancelCommand(message) {
20824
20850
  return JSON.stringify(decodeSessionCancelCommand(JSON.stringify(message)));
20825
20851
  }
20852
+ function encodeSessionPromptDispositionCommand(message) {
20853
+ return JSON.stringify(decodeSessionPromptDispositionCommand(JSON.stringify(message)));
20854
+ }
20855
+ function encodeSessionQueuedEvent(message) {
20856
+ return JSON.stringify(decodeSessionQueuedEvent(JSON.stringify(message)));
20857
+ }
20826
20858
  function encodeRuntimeLivenessReadyEvent(message) {
20827
20859
  return JSON.stringify(decodeRuntimeLivenessReadyEvent(JSON.stringify(message)));
20828
20860
  }
@@ -20954,6 +20986,19 @@ var envelope = {
20954
20986
  requestId: identifierStringSchema,
20955
20987
  sessionId: identifierStringSchema
20956
20988
  };
20989
+ var activeTurnActivitySchema = external_exports.strictObject({
20990
+ activityId: external_exports.string().min(1).max(128),
20991
+ activityType: external_exports.string().min(1).max(128),
20992
+ content: external_exports.array(displayContentSchema).max(100).readonly(),
20993
+ input: external_exports.string().max(1e5),
20994
+ locations: external_exports.array(external_exports.string().min(1).max(2048)).max(100).readonly(),
20995
+ name: external_exports.string().max(128),
20996
+ output: external_exports.string().max(1e5),
20997
+ sequence: external_exports.number().int().nonnegative(),
20998
+ status: external_exports.string().min(1).max(64),
20999
+ title: external_exports.string().max(500),
21000
+ toolKind: external_exports.string().max(64)
21001
+ }).readonly();
20957
21002
  var identity = {
20958
21003
  ...envelope,
20959
21004
  kind: external_exports.literal(NATIVE_SESSION_REQUEST_KIND),
@@ -21029,7 +21074,9 @@ var nativeSessionResultSchema = external_exports.discriminatedUnion("action", [
21029
21074
  action: external_exports.literal("active-turn"),
21030
21075
  targetSessionId: identifierStringSchema,
21031
21076
  turn: external_exports.strictObject({
21077
+ activities: external_exports.array(activeTurnActivitySchema).max(100).readonly(),
21032
21078
  commandId: identifierStringSchema,
21079
+ content: external_exports.array(displayContentSchema).max(100).readonly(),
21033
21080
  prompt: external_exports.string().max(1e5),
21034
21081
  text: external_exports.string().max(ACTIVE_TURN_TEXT_LIMIT),
21035
21082
  truncated: external_exports.boolean(),
@@ -21333,6 +21380,11 @@ var serviceToDaemonSignatures = {
21333
21380
  encodeSessionPromptCommand,
21334
21381
  decodeSessionPromptCommand
21335
21382
  ),
21383
+ [SESSION_PROMPT_DISPOSITION_KIND]: defineMessageSignature(
21384
+ SESSION_PROMPT_DISPOSITION_KIND,
21385
+ encodeSessionPromptDispositionCommand,
21386
+ decodeSessionPromptDispositionCommand
21387
+ ),
21336
21388
  [WORKSPACE_LIST_KIND]: defineMessageSignature(
21337
21389
  WORKSPACE_LIST_KIND,
21338
21390
  encodeWorkspaceListCommand,
@@ -21403,6 +21455,11 @@ var daemonToServiceSignatures = {
21403
21455
  encodeSessionsQueriedEvent,
21404
21456
  decodeSessionsQueriedEvent
21405
21457
  ),
21458
+ [SESSION_QUEUED_KIND]: defineMessageSignature(
21459
+ SESSION_QUEUED_KIND,
21460
+ encodeSessionQueuedEvent,
21461
+ decodeSessionQueuedEvent
21462
+ ),
21406
21463
  [NATIVE_SESSION_RESULT_KIND]: defineMessageSignature(
21407
21464
  NATIVE_SESSION_RESULT_KIND,
21408
21465
  encodeNativeSessionResult,
@@ -22902,6 +22959,7 @@ var turnSchema = external_exports.object({
22902
22959
  id: boundedText(256),
22903
22960
  status: turnStatusSchema
22904
22961
  });
22962
+ var turnSteerResponseSchema = external_exports.object({ turnId: boundedText(256) });
22905
22963
  var turnNotificationSchema = external_exports.object({
22906
22964
  thread: external_exports.object({ id: boundedText(256) }).nullish(),
22907
22965
  threadId: boundedText(256),
@@ -23286,7 +23344,10 @@ function presentToolItem(item) {
23286
23344
  kind: "execute",
23287
23345
  locations: [],
23288
23346
  rawInput: { command: item.command, cwd: item.cwd },
23289
- rawOutput: { exitCode: item.exitCode, output: truncate(output2, TOOL_OUTPUT_CHARACTER_LIMIT) },
23347
+ rawOutput: {
23348
+ ...item.exitCode == null ? {} : { exitCode: item.exitCode },
23349
+ output: truncate(output2, TOOL_OUTPUT_CHARACTER_LIMIT)
23350
+ },
23290
23351
  status: commandStatus(item.status),
23291
23352
  title: truncate(firstLine(item.command), TITLE_CHARACTER_LIMIT)
23292
23353
  };
@@ -23342,7 +23403,7 @@ function presentToolItem(item) {
23342
23403
  }
23343
23404
  return null;
23344
23405
  }
23345
- function toolCallUpdate(item) {
23406
+ function toolCallUpdate(item, lifecycle) {
23346
23407
  const presentation = presentToolItem(item);
23347
23408
  if (presentation === null) {
23348
23409
  return null;
@@ -23353,7 +23414,7 @@ function toolCallUpdate(item) {
23353
23414
  locations: [...presentation.locations],
23354
23415
  rawInput: presentation.rawInput,
23355
23416
  rawOutput: presentation.rawOutput,
23356
- status: presentation.status,
23417
+ status: lifecycle === "completed" && presentation.status === "in_progress" ? "completed" : presentation.status,
23357
23418
  title: presentation.title,
23358
23419
  toolCallId: item.id
23359
23420
  };
@@ -23462,6 +23523,54 @@ function promptInput(prompt) {
23462
23523
  }
23463
23524
  return input2;
23464
23525
  }
23526
+ function steeringPromptInput(prompt) {
23527
+ const input2 = [];
23528
+ for (const block of prompt) {
23529
+ if (typeof block !== "object" || block === null) {
23530
+ throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
23531
+ }
23532
+ const type = Reflect.get(block, "type");
23533
+ if (type === "text") {
23534
+ const text = Reflect.get(block, "text");
23535
+ if (typeof text !== "string") {
23536
+ throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
23537
+ }
23538
+ input2.push({ text, text_elements: [], type: "text" });
23539
+ continue;
23540
+ }
23541
+ if (type === "image") {
23542
+ const data = Reflect.get(block, "data");
23543
+ const mimeType = Reflect.get(block, "mimeType");
23544
+ if (typeof data !== "string" || typeof mimeType !== "string") {
23545
+ throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
23546
+ }
23547
+ input2.push({ type: "image", url: `data:${mimeType};base64,${data}` });
23548
+ continue;
23549
+ }
23550
+ if (type === "resource") {
23551
+ const resource = Reflect.get(block, "resource");
23552
+ if (typeof resource !== "object" || resource === null) {
23553
+ throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
23554
+ }
23555
+ const text = Reflect.get(resource, "text");
23556
+ if (text !== void 0 && typeof text !== "string") {
23557
+ throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
23558
+ }
23559
+ input2.push({ text: text ?? "", text_elements: [], type: "text" });
23560
+ continue;
23561
+ }
23562
+ if (type === "resource_link") {
23563
+ const uri = Reflect.get(block, "uri");
23564
+ if (typeof uri !== "string") {
23565
+ throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
23566
+ }
23567
+ input2.push({ text: `Resource: ${uri}`, text_elements: [], type: "text" });
23568
+ continue;
23569
+ }
23570
+ throw new AcpExecutionError("Codex received an unsupported steering prompt", {}, "invalid_request");
23571
+ }
23572
+ return input2;
23573
+ }
23465
23574
  function modelValues(models) {
23466
23575
  return models.map((model) => ({
23467
23576
  description: model.description ?? "",
@@ -23640,6 +23749,7 @@ var CodexAcpAgent = class {
23640
23749
  this.#app = createAgentApp({ name: "mobius-codex" }).onConnect((connection) => {
23641
23750
  this.#connection = connection;
23642
23751
  }).onRequest(methods.agent.initialize, async () => ({
23752
+ _meta: { steering: { supported: true } },
23643
23753
  agentCapabilities: {
23644
23754
  loadSession: true,
23645
23755
  promptCapabilities: { embeddedContext: true, image: true },
@@ -23713,7 +23823,11 @@ var CodexAcpAgent = class {
23713
23823
  return { configOptions: this.#configOptions() };
23714
23824
  }).onRequest(methods.agent.session.prompt, async (context) => {
23715
23825
  return await this.#runTurn(promptInput(context.params.prompt), context.signal);
23716
- }).onRequest(methods.agent.session.list, async (context) => {
23826
+ }).onRequest(
23827
+ "_session/steering",
23828
+ (params) => params,
23829
+ async (context) => await this.#steerTurn(context.params, context.signal)
23830
+ ).onRequest(methods.agent.session.list, async (context) => {
23717
23831
  const decoded = threadListResponseSchema.parse(
23718
23832
  await this.#appServer.request(
23719
23833
  "thread/list",
@@ -23880,7 +23994,7 @@ var CodexAcpAgent = class {
23880
23994
  });
23881
23995
  continue;
23882
23996
  }
23883
- const update = toolCallUpdate(item);
23997
+ const update = toolCallUpdate(item, "snapshot");
23884
23998
  if (update !== null) {
23885
23999
  await this.#emit({ ...update, sessionUpdate: "tool_call_update" });
23886
24000
  }
@@ -24077,7 +24191,7 @@ var CodexAcpAgent = class {
24077
24191
  });
24078
24192
  return;
24079
24193
  }
24080
- const update = toolCallUpdate(item);
24194
+ const update = toolCallUpdate(item, method === "item/completed" ? "completed" : "started");
24081
24195
  if (update !== null) {
24082
24196
  await this.#enqueue(async () => {
24083
24197
  await this.#emit({ ...update, sessionUpdate: "tool_call_update" });
@@ -24263,6 +24377,35 @@ var CodexAcpAgent = class {
24263
24377
  }
24264
24378
  }
24265
24379
  };
24380
+ #steerTurn = async (params, signal) => {
24381
+ if (typeof params !== "object" || params === null) {
24382
+ throw new AcpExecutionError("Codex received an invalid steering request", {}, "invalid_request");
24383
+ }
24384
+ const sessionId = Reflect.get(params, "sessionId");
24385
+ const prompt = Reflect.get(params, "prompt");
24386
+ if (typeof sessionId !== "string" || !Array.isArray(prompt)) {
24387
+ throw new AcpExecutionError("Codex received an invalid steering request", {}, "invalid_request");
24388
+ }
24389
+ const active = this.#turn;
24390
+ if (sessionId !== this.#nativeSessionId || active === null || active.turn.id.length === 0) {
24391
+ return { outcome: "promptRequired", reason: "noRunningTurn" };
24392
+ }
24393
+ const input2 = steeringPromptInput(prompt);
24394
+ if (input2.length === 0) {
24395
+ throw new AcpExecutionError("Codex received an empty steering request", {}, "invalid_request");
24396
+ }
24397
+ const response = turnSteerResponseSchema.parse(
24398
+ await this.#appServer.request(
24399
+ "turn/steer",
24400
+ { expectedTurnId: active.turn.id, input: input2, threadId: this.#nativeSessionId },
24401
+ AbortSignal.any([signal, AbortSignal.timeout(APPROVAL_TIMEOUT_MILLISECONDS)])
24402
+ )
24403
+ );
24404
+ if (response.turnId !== active.turn.id) {
24405
+ throw new AcpExecutionError("Codex steered an unexpected turn", {}, "steering_target_unavailable");
24406
+ }
24407
+ return { outcome: "injected" };
24408
+ };
24266
24409
  #interruptTurn = async () => {
24267
24410
  const turn = this.#turn;
24268
24411
  if (turn === null) {
@@ -30887,7 +31030,10 @@ function liveHistoryCoveredTurnRanges(history) {
30887
31030
  }
30888
31031
  return ranges;
30889
31032
  }
30890
- function paginateLiveSessionHistory(history, sessionId, cursor, limit) {
31033
+ function historyMessageCharacters(message) {
31034
+ return message.text.length + (message.role === "assistant" ? JSON.stringify(message.activities).length + JSON.stringify(message.content).length : 0);
31035
+ }
31036
+ function paginateAcpSessionHistory(history, sessionId, cursor, limit) {
30891
31037
  if (history.status === "unavailable") {
30892
31038
  if (cursor !== null) {
30893
31039
  throw new AcpExecutionError("Unavailable native Session history has no cursor", {}, "invalid_cursor");
@@ -30913,6 +31059,80 @@ function paginateLiveSessionHistory(history, sessionId, cursor, limit) {
30913
31059
  truncated: history.truncated
30914
31060
  };
30915
31061
  }
31062
+ function paginateLiveSessionHistory(history, activeTurn, sessionId, cursor, limit) {
31063
+ if (activeTurn === null || cursor !== null) {
31064
+ return paginateAcpSessionHistory(history, sessionId, cursor, limit);
31065
+ }
31066
+ const activeMessageOverhead = 4;
31067
+ const activeStructuredCharacters = JSON.stringify(activeTurn.activities).length + JSON.stringify(activeTurn.content).length;
31068
+ const maximumActiveTextLength = Math.max(
31069
+ 0,
31070
+ SESSION_HISTORY_CHARACTER_LIMIT - activeTurn.prompt.length - activeStructuredCharacters - activeMessageOverhead
31071
+ );
31072
+ const activeText = activeTurn.text.slice(-maximumActiveTextLength);
31073
+ const completeActiveMessages = [
31074
+ { role: "user", text: activeTurn.prompt },
31075
+ {
31076
+ activities: activeTurn.activities,
31077
+ content: activeTurn.content,
31078
+ role: "assistant",
31079
+ text: activeText
31080
+ }
31081
+ ];
31082
+ if (history.status === "unavailable") {
31083
+ return {
31084
+ coveredCommandIds: [],
31085
+ coveredMessageIds: [],
31086
+ messages: completeActiveMessages,
31087
+ nextCursor: null,
31088
+ status: "available",
31089
+ truncated: activeTurn.truncated || activeText.length !== activeTurn.text.length
31090
+ };
31091
+ }
31092
+ const latestNativeMessage = history.messages.at(-1);
31093
+ const activeMessages = latestNativeMessage?.role === "user" && latestNativeMessage.text === activeTurn.prompt ? completeActiveMessages.slice(1) : completeActiveMessages;
31094
+ let historicalMessageCount = 0;
31095
+ let remainingCharacters = SESSION_HISTORY_CHARACTER_LIMIT - activeText.length - activeMessageOverhead - activeStructuredCharacters - (activeMessages.length === completeActiveMessages.length ? activeTurn.prompt.length : 0);
31096
+ const historicalMessageLimit = Math.max(0, limit - activeMessages.length);
31097
+ for (let index = history.messages.length - 1; index >= 0 && historicalMessageCount < historicalMessageLimit; index -= 1) {
31098
+ const message = history.messages[index];
31099
+ if (message === void 0) {
31100
+ break;
31101
+ }
31102
+ const characters = historyMessageCharacters(message);
31103
+ if (characters > remainingCharacters) {
31104
+ break;
31105
+ }
31106
+ historicalMessageCount += 1;
31107
+ remainingCharacters -= characters;
31108
+ }
31109
+ const page = historicalMessageCount === 0 ? {
31110
+ coveredCommandIds: [],
31111
+ coveredMessageIds: [],
31112
+ messages: [],
31113
+ nextCursor: history.messages.length === 0 ? null : liveHistoryCursor(sessionId, history.messages.length),
31114
+ status: "available",
31115
+ truncated: history.truncated
31116
+ } : paginateAcpSessionHistory(history, sessionId, null, historicalMessageCount);
31117
+ return {
31118
+ ...page,
31119
+ messages: [...page.messages, ...activeMessages],
31120
+ truncated: page.truncated || activeTurn.truncated || activeText.length !== activeTurn.text.length
31121
+ };
31122
+ }
31123
+ function mergeLiveSessionHistory(history, activeTurn, sessionId) {
31124
+ const page = paginateLiveSessionHistory(history, activeTurn, sessionId, null, 1e3);
31125
+ if (page.status === "unavailable") {
31126
+ return { cause: page.cause, status: "unavailable" };
31127
+ }
31128
+ return {
31129
+ coveredCommandIds: page.coveredCommandIds,
31130
+ coveredMessageIds: page.coveredMessageIds,
31131
+ messages: page.messages,
31132
+ status: "available",
31133
+ truncated: page.truncated
31134
+ };
31135
+ }
30916
31136
 
30917
31137
  // src/prompt-artifact-resolver.ts
30918
31138
  import { createHash as createHash2 } from "node:crypto";
@@ -31544,7 +31764,7 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
31544
31764
  reportOperationFailure(socket, command.requestId, command.sessionId, error62, metrics.snapshot());
31545
31765
  }
31546
31766
  }
31547
- async function executeSessionLiveHistoryLoad(socket, command, config2, directories, audit, sessions, signal) {
31767
+ async function executeSessionLiveHistoryLoad(socket, command, config2, directories, audit, sessions, activeTurn, signal) {
31548
31768
  try {
31549
31769
  const resolved = await resolveSessionDirectories(
31550
31770
  directories,
@@ -31561,13 +31781,14 @@ async function executeSessionLiveHistoryLoad(socket, command, config2, directori
31561
31781
  signal
31562
31782
  });
31563
31783
  signal.throwIfAborted();
31784
+ const mergedHistory = mergeLiveSessionHistory(history, activeTurn(command.sessionId), command.sessionId);
31564
31785
  audit.record({
31565
31786
  commandId: command.requestId,
31566
31787
  event: "session_history_loaded",
31567
31788
  sessionId: command.sessionId
31568
31789
  });
31569
31790
  send(socket, {
31570
- history,
31791
+ history: mergedHistory,
31571
31792
  kind: "session.live-history.loaded",
31572
31793
  requestId: command.requestId,
31573
31794
  sessionId: command.sessionId
@@ -31593,7 +31814,7 @@ async function executeSessionLiveHistoryLoad(socket, command, config2, directori
31593
31814
  });
31594
31815
  }
31595
31816
  }
31596
- async function executeSessionLiveHistoryPageLoad(socket, command, config2, directories, audit, sessions, signal) {
31817
+ async function executeSessionLiveHistoryPageLoad(socket, command, config2, directories, audit, sessions, activeTurn, signal) {
31597
31818
  try {
31598
31819
  const resolved = await resolveSessionDirectories(
31599
31820
  directories,
@@ -31610,7 +31831,13 @@ async function executeSessionLiveHistoryPageLoad(socket, command, config2, direc
31610
31831
  signal
31611
31832
  });
31612
31833
  signal.throwIfAborted();
31613
- const page = paginateLiveSessionHistory(history, command.sessionId, command.cursor, command.limit);
31834
+ const page = paginateLiveSessionHistory(
31835
+ history,
31836
+ activeTurn(command.sessionId),
31837
+ command.sessionId,
31838
+ command.cursor,
31839
+ command.limit
31840
+ );
31614
31841
  audit.record({
31615
31842
  commandId: command.requestId,
31616
31843
  event: "session_history_loaded",
@@ -31683,14 +31910,11 @@ async function executeSessionConfigure(publisher, socket, command, config2, dire
31683
31910
  reportOperationFailure(socket, command.requestId, command.sessionId, error62);
31684
31911
  }
31685
31912
  }
31686
- async function executePrompt(operations, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, waitForSessionAvailability, timer, signal, recordLiveText, cancellationRequested) {
31687
- const activities = new CoalescingDaemonActivityPublisher(timer, (activity2) => {
31688
- publisher.publish(command.sessionId, daemonActivity(command, activity2));
31689
- });
31913
+ async function executePrompt(operations, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, acknowledgeQueued, waitForSessionAvailability, timer, signal, recordLiveEvent, cancellationRequested) {
31690
31914
  const narration = new CoalescingNarrationPublisher(
31691
31915
  timer,
31692
31916
  (increment) => {
31693
- publisher.publish(command.sessionId, {
31917
+ const event = {
31694
31918
  activityId: increment.activityId,
31695
31919
  activityType: increment.activityType,
31696
31920
  commandId: command.commandId,
@@ -31698,29 +31922,34 @@ async function executePrompt(operations, publisher, command, config2, directorie
31698
31922
  sequence: increment.sequence,
31699
31923
  sessionId: command.sessionId,
31700
31924
  text: increment.text
31701
- });
31925
+ };
31926
+ publisher.publish(command.sessionId, recordLiveEvent(event));
31702
31927
  },
31703
31928
  AGENT_ACTIVITY_COALESCING_MILLISECONDS,
31704
31929
  AGENT_TEXT_MAXIMUM_LENGTH
31705
31930
  );
31931
+ const activities = new CoalescingDaemonActivityPublisher(timer, (activity2) => {
31932
+ if (activity2.status !== "pending" && activity2.status !== "running") {
31933
+ narration.flush();
31934
+ }
31935
+ const event = daemonActivity(command, activity2);
31936
+ publisher.publish(command.sessionId, recordLiveEvent(event));
31937
+ });
31706
31938
  const text = new CoalescingTextPublisher(
31707
31939
  timer,
31708
31940
  (messageId, delta) => {
31709
- const stream = recordLiveText(delta);
31710
- publisher.publish(command.sessionId, {
31711
- commandId: command.commandId,
31712
- epoch: stream.epoch,
31713
- kind: AGENT_MESSAGE_DELTA_KIND,
31714
- messageId,
31715
- sequence: stream.sequence,
31716
- sessionId: command.sessionId,
31717
- text: delta
31718
- });
31941
+ publisher.publish(
31942
+ command.sessionId,
31943
+ recordLiveEvent({ kind: AGENT_MESSAGE_DELTA_KIND, messageId, text: delta })
31944
+ );
31719
31945
  },
31720
31946
  AGENT_TEXT_COALESCING_MILLISECONDS,
31721
31947
  AGENT_TEXT_MAXIMUM_LENGTH
31722
31948
  );
31723
31949
  try {
31950
+ if (command.disposition === SessionPromptDisposition.Queue) {
31951
+ acknowledgeQueued();
31952
+ }
31724
31953
  const resolved = await resolveSessionDirectories(
31725
31954
  directories,
31726
31955
  command.bindingId,
@@ -31730,10 +31959,10 @@ async function executePrompt(operations, publisher, command, config2, directorie
31730
31959
  );
31731
31960
  const agent = config2.catalog.find(command.agentId);
31732
31961
  const availability = await waitForSessionAvailability(signal);
31733
- if (availability === "busy") {
31962
+ if (availability.kind === "busy") {
31734
31963
  throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
31735
31964
  }
31736
- if (availability === "queue-target-unavailable") {
31965
+ if (availability.kind === "queue-target-unavailable") {
31737
31966
  throw new AcpExecutionError(
31738
31967
  "The queued prompt target is unavailable",
31739
31968
  {},
@@ -31751,7 +31980,7 @@ async function executePrompt(operations, publisher, command, config2, directorie
31751
31980
  sessionId: command.sessionId,
31752
31981
  signal
31753
31982
  });
31754
- if (command.disposition === SessionPromptDisposition.Steer) {
31983
+ if (availability.disposition === SessionPromptDisposition.Steer) {
31755
31984
  assertAppliedSessionConfiguration(prepared.configOptions, sessionConfigurations ?? []);
31756
31985
  } else {
31757
31986
  await applyCompleteSessionConfiguration(
@@ -31786,7 +32015,7 @@ async function executePrompt(operations, publisher, command, config2, directorie
31786
32015
  });
31787
32016
  const attachments = await resolvePromptArtifacts(config2, command, signal);
31788
32017
  let stopReason;
31789
- if (command.disposition === SessionPromptDisposition.Steer) {
32018
+ if (availability.disposition === SessionPromptDisposition.Steer) {
31790
32019
  await sessions.steerPrompt({
31791
32020
  additionalDirectories: resolved.additionalDirectories,
31792
32021
  agent: executionAgent,
@@ -31806,7 +32035,7 @@ async function executePrompt(operations, publisher, command, config2, directorie
31806
32035
  agent: executionAgent,
31807
32036
  commandId: command.commandId,
31808
32037
  cwd: resolved.cwd,
31809
- disposition: command.disposition,
32038
+ disposition: availability.disposition,
31810
32039
  images: attachments.images,
31811
32040
  onActivity: activities.record,
31812
32041
  onNarration: (increment) => {
@@ -33181,6 +33410,144 @@ var WorkspaceDirectoryService = class {
33181
33410
  };
33182
33411
  };
33183
33412
 
33413
+ // src/daemon-active-turn.ts
33414
+ import { randomUUID as randomUUID2 } from "node:crypto";
33415
+ var ActiveDaemonTurn = class {
33416
+ attemptId;
33417
+ command;
33418
+ #controller;
33419
+ #finished = Promise.withResolvers();
33420
+ #cancellationRequested = false;
33421
+ #dispatch;
33422
+ #text = "";
33423
+ #activities = /* @__PURE__ */ new Map();
33424
+ #content = /* @__PURE__ */ new Map();
33425
+ #truncated = false;
33426
+ #sequence = 0;
33427
+ #interaction = null;
33428
+ #epoch = decodeIdentifier(randomUUID2());
33429
+ constructor(command, attemptId) {
33430
+ this.attemptId = attemptId;
33431
+ this.command = command;
33432
+ this.#controller = new AbortController();
33433
+ this.#dispatch = command.disposition === SessionPromptDisposition.Queue ? { kind: "queued", promotion: Promise.withResolvers() } : { kind: "pending" };
33434
+ }
33435
+ abortDaemon = () => {
33436
+ this.#controller.abort();
33437
+ };
33438
+ finish = () => this.#finished.resolve();
33439
+ accept = () => {
33440
+ this.#dispatch = { kind: "accepted" };
33441
+ return { epoch: this.#epoch, sequence: 0 };
33442
+ };
33443
+ promoteQueuedPrompt = (command) => {
33444
+ if (command.commandId !== this.command.commandId || command.sessionId !== this.command.sessionId || this.#dispatch.kind !== "queued") {
33445
+ return false;
33446
+ }
33447
+ const promotion = this.#dispatch.promotion;
33448
+ this.#dispatch = { kind: "promoted" };
33449
+ promotion.resolve();
33450
+ return true;
33451
+ };
33452
+ queuePromotion = () => {
33453
+ if (this.#dispatch.kind === "queued") {
33454
+ return this.#dispatch.promotion.promise;
33455
+ }
33456
+ return this.#dispatch.kind === "promoted" ? Promise.resolve() : null;
33457
+ };
33458
+ effectiveDisposition = () => this.#dispatch.kind === "promoted" ? SessionPromptDisposition.Steer : this.command.disposition;
33459
+ recordEvent = (event) => {
33460
+ if (event.kind === AGENT_MESSAGE_DELTA_KIND) {
33461
+ this.#sequence += 1;
33462
+ this.#text += event.text;
33463
+ if (this.#text.length > ACTIVE_TURN_TEXT_LIMIT) {
33464
+ this.#text = this.#text.slice(-ACTIVE_TURN_TEXT_LIMIT);
33465
+ this.#truncated = true;
33466
+ }
33467
+ return {
33468
+ commandId: this.command.commandId,
33469
+ epoch: this.#epoch,
33470
+ kind: AGENT_MESSAGE_DELTA_KIND,
33471
+ messageId: event.messageId,
33472
+ sequence: this.#sequence,
33473
+ sessionId: this.command.sessionId,
33474
+ text: event.text
33475
+ };
33476
+ }
33477
+ if (event.sessionId !== this.command.sessionId || "commandId" in event && event.commandId !== this.command.commandId) {
33478
+ return event;
33479
+ }
33480
+ if (event.kind === AGENT_ACTIVITY_KIND) {
33481
+ this.#activities.set(event.activityId, {
33482
+ activityId: event.activityId,
33483
+ activityType: event.activityType,
33484
+ content: event.content,
33485
+ input: event.input,
33486
+ locations: event.locations,
33487
+ name: event.name,
33488
+ output: event.output,
33489
+ sequence: event.sequence,
33490
+ status: event.status,
33491
+ title: event.title,
33492
+ toolKind: event.toolKind
33493
+ });
33494
+ } else if (event.kind === AGENT_ACTIVITY_NARRATION_KIND) {
33495
+ const previous = this.#activities.get(event.activityId);
33496
+ this.#activities.set(event.activityId, {
33497
+ activityId: event.activityId,
33498
+ activityType: event.activityType,
33499
+ content: previous?.content ?? [],
33500
+ input: previous?.input ?? "",
33501
+ locations: previous?.locations ?? [],
33502
+ name: previous?.name ?? "",
33503
+ output: `${previous?.output ?? ""}${event.text}`,
33504
+ sequence: event.sequence,
33505
+ status: previous?.status ?? "running",
33506
+ title: previous?.title ?? "Thinking",
33507
+ toolKind: previous?.toolKind ?? ""
33508
+ });
33509
+ } else if (event.kind === AGENT_CONTENT_KIND) {
33510
+ this.#content.set(event.contentId, event.content);
33511
+ } else if (event.kind === SESSION_PERMISSION_REQUESTED_KIND || event.kind === SESSION_ELICITATION_REQUESTED_KIND) {
33512
+ this.#interaction = event;
33513
+ } else if ((event.kind === SESSION_PERMISSION_RESOLVED_KIND || event.kind === SESSION_ELICITATION_RESOLVED_KIND) && this.#interaction?.interactionId === event.interactionId) {
33514
+ this.#interaction = null;
33515
+ }
33516
+ return event;
33517
+ };
33518
+ snapshot = () => this.#dispatch.kind === "accepted" ? {
33519
+ activities: [...this.#activities.values()].sort((left, right) => left.sequence - right.sequence),
33520
+ commandId: decodeIdentifier(this.command.commandId),
33521
+ content: [...this.#content.values()],
33522
+ prompt: this.command.prompt,
33523
+ text: this.#text,
33524
+ truncated: this.#truncated,
33525
+ epoch: this.#epoch,
33526
+ interaction: this.#interaction,
33527
+ sequence: this.#sequence,
33528
+ state: "running"
33529
+ } : null;
33530
+ matches = (cancellation) => cancellation.commandId === this.command.commandId && cancellation.sessionId === this.command.sessionId;
33531
+ requestCancellation = () => {
33532
+ if (this.#cancellationRequested) {
33533
+ return "already-requested";
33534
+ }
33535
+ this.#cancellationRequested = true;
33536
+ if (this.#dispatch.kind !== "accepted") {
33537
+ this.#controller.abort(new Error("The queued Agent turn was cancelled"));
33538
+ return "pending";
33539
+ }
33540
+ return "running";
33541
+ };
33542
+ cancellationRequested = () => this.#cancellationRequested;
33543
+ get signal() {
33544
+ return this.#controller.signal;
33545
+ }
33546
+ get completion() {
33547
+ return this.#finished.promise;
33548
+ }
33549
+ };
33550
+
33184
33551
  // src/daemon-diagnostic-log.ts
33185
33552
  import { appendFileSync, mkdirSync, readFileSync as readFileSync2, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
33186
33553
  import { join as join16 } from "node:path";
@@ -33363,167 +33730,6 @@ var DaemonInstallationObserver = class {
33363
33730
  };
33364
33731
  };
33365
33732
 
33366
- // src/daemon-turn-reconciliation.ts
33367
- import { randomUUID as randomUUID2 } from "node:crypto";
33368
- import { fetch as fetch4 } from "undici";
33369
- var ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS = 2e4;
33370
- var ActiveDaemonTurn = class {
33371
- attemptId;
33372
- command;
33373
- #controller;
33374
- #finished = Promise.withResolvers();
33375
- #cancellationRequested = false;
33376
- #accepted = false;
33377
- #text = "";
33378
- #truncated = false;
33379
- #sequence = 0;
33380
- #interaction = null;
33381
- #epoch = decodeIdentifier(randomUUID2());
33382
- constructor(command, attemptId) {
33383
- this.attemptId = attemptId;
33384
- this.command = command;
33385
- this.#controller = new AbortController();
33386
- }
33387
- abortDaemon = () => {
33388
- this.#controller.abort();
33389
- };
33390
- finish = () => this.#finished.resolve();
33391
- accept = () => {
33392
- this.#accepted = true;
33393
- return { epoch: this.#epoch, sequence: 0 };
33394
- };
33395
- recordText = (delta) => {
33396
- this.#sequence += 1;
33397
- this.#text += delta;
33398
- if (this.#text.length > ACTIVE_TURN_TEXT_LIMIT) {
33399
- this.#text = this.#text.slice(-ACTIVE_TURN_TEXT_LIMIT);
33400
- this.#truncated = true;
33401
- }
33402
- return { epoch: this.#epoch, sequence: this.#sequence };
33403
- };
33404
- recordInteraction = (event) => {
33405
- if (event.sessionId !== this.command.sessionId) {
33406
- return;
33407
- }
33408
- if (event.kind === SESSION_PERMISSION_REQUESTED_KIND || event.kind === SESSION_ELICITATION_REQUESTED_KIND) {
33409
- if (event.commandId === this.command.commandId) {
33410
- this.#interaction = event;
33411
- }
33412
- } else if ((event.kind === SESSION_PERMISSION_RESOLVED_KIND || event.kind === SESSION_ELICITATION_RESOLVED_KIND) && this.#interaction?.interactionId === event.interactionId) {
33413
- this.#interaction = null;
33414
- }
33415
- };
33416
- snapshot = () => this.#accepted ? {
33417
- commandId: decodeIdentifier(this.command.commandId),
33418
- prompt: this.command.prompt,
33419
- text: this.#text,
33420
- truncated: this.#truncated,
33421
- epoch: this.#epoch,
33422
- interaction: this.#interaction,
33423
- sequence: this.#sequence,
33424
- state: "running"
33425
- } : null;
33426
- matches = (cancellation) => cancellation.commandId === this.command.commandId && cancellation.sessionId === this.command.sessionId;
33427
- requestCancellation = () => {
33428
- if (this.#cancellationRequested) {
33429
- return "already-requested";
33430
- }
33431
- this.#cancellationRequested = true;
33432
- if (!this.#accepted) {
33433
- this.#controller.abort(new Error("The queued Agent turn was cancelled"));
33434
- return "pending";
33435
- }
33436
- return "running";
33437
- };
33438
- cancellationRequested = () => this.#cancellationRequested;
33439
- get signal() {
33440
- return this.#controller.signal;
33441
- }
33442
- get completion() {
33443
- return this.#finished.promise;
33444
- }
33445
- };
33446
- var ActiveTurnReconciliationError = class extends Error {
33447
- code = "active_turn_reconciliation_failed";
33448
- diagnosticDetails;
33449
- relayErrorCode;
33450
- terminal;
33451
- constructor(message, options = {}) {
33452
- super(message, options);
33453
- this.name = "ActiveTurnReconciliationError";
33454
- this.relayErrorCode = options.relayErrorCode ?? null;
33455
- this.terminal = options.terminal ?? false;
33456
- this.diagnosticDetails = this.relayErrorCode === null ? {} : { relayErrorCode: this.relayErrorCode };
33457
- }
33458
- };
33459
- var TERMINAL_RECONCILIATION_RELAY_CODES = /* @__PURE__ */ new Set(["session_conflict"]);
33460
- async function relayErrorCode(response) {
33461
- try {
33462
- const body = JSON.parse(await response.text());
33463
- if (typeof body !== "object" || body === null) {
33464
- return null;
33465
- }
33466
- const error62 = Reflect.get(body, "error");
33467
- if (typeof error62 !== "object" || error62 === null) {
33468
- return null;
33469
- }
33470
- const code = Reflect.get(error62, "code");
33471
- return typeof code === "string" && code.length > 0 ? code : null;
33472
- } catch {
33473
- return null;
33474
- }
33475
- }
33476
- function activeTurnReconciliationEndpoint(config2, turn) {
33477
- const endpoint = relayHttpEndpoint(config2.relayUrl);
33478
- let channelPath = "";
33479
- if (endpoint.pathname.endsWith("/daemon")) {
33480
- channelPath = endpoint.pathname.slice(0, -"/daemon".length);
33481
- } else {
33482
- const runtimePath = "/v1/runtimes/connect";
33483
- if (!endpoint.pathname.endsWith(runtimePath)) {
33484
- throw new ActiveTurnReconciliationError("The Relay URL is invalid");
33485
- }
33486
- channelPath = `${endpoint.pathname.slice(0, -runtimePath.length)}/channels/${encodeURIComponent(config2.channelId)}`;
33487
- }
33488
- endpoint.pathname = `${channelPath}/sessions/${encodeURIComponent(turn.command.sessionId)}/attempts/${encodeURIComponent(turn.attemptId)}/reconciliation`;
33489
- return endpoint;
33490
- }
33491
- async function reconcileActiveTurn(config2, turn, signal) {
33492
- signal.throwIfAborted();
33493
- const timeoutSignal = AbortSignal.timeout(ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS);
33494
- const requestSignal = AbortSignal.any([signal, timeoutSignal]);
33495
- let response;
33496
- try {
33497
- response = await fetch4(activeTurnReconciliationEndpoint(config2, turn), {
33498
- body: JSON.stringify({ outcome: { kind: "running" } }),
33499
- dispatcher: environmentProxyDispatcher,
33500
- headers: { ...runtimeAuthorization(config2.relayUrl), "content-type": "application/json" },
33501
- method: "POST",
33502
- signal: requestSignal
33503
- });
33504
- } catch (error62) {
33505
- if (signal.aborted) {
33506
- signal.throwIfAborted();
33507
- }
33508
- throw new ActiveTurnReconciliationError(
33509
- timeoutSignal.aborted ? "The active Agent turn reconciliation timed out" : "The active Agent turn could not be reconciled",
33510
- { cause: error62 }
33511
- );
33512
- }
33513
- if (!response.ok) {
33514
- const errorCode = await relayErrorCode(response);
33515
- const terminal = errorCode !== null && TERMINAL_RECONCILIATION_RELAY_CODES.has(errorCode);
33516
- throw new ActiveTurnReconciliationError(
33517
- 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()}`,
33518
- { relayErrorCode: errorCode, terminal }
33519
- );
33520
- }
33521
- await response.body?.cancel();
33522
- }
33523
- async function reconcileActiveTurns(config2, turns, signal) {
33524
- await Promise.all(turns.map(async (turn) => await reconcileActiveTurn(config2, turn, signal)));
33525
- }
33526
-
33527
33733
  // src/native-sessions/codex-history.ts
33528
33734
  import { spawn as spawn5 } from "node:child_process";
33529
33735
  var responseSchema = external_exports.union([
@@ -34822,25 +35028,6 @@ var RelayConnectionDiagnostics = class {
34822
35028
  addFailureDetails(details, failure2);
34823
35029
  this.#record("relay_connection_failed", connectionEpoch.toString(), details, true);
34824
35030
  };
34825
- /**
34826
- * Records that the Runtime gave up on Agent turns the Relay already settled. This is not a connection
34827
- * failure, so it is recorded independently of the per-epoch failure deduplication.
34828
- */
34829
- reconciliationAbandoned = (connectionEpoch, relayErrorCode2, turnCount) => {
34830
- this.#record(
34831
- "relay_reconciliation_abandoned",
34832
- connectionEpoch.toString(),
34833
- {
34834
- connectionEpoch: connectionEpoch.toString(),
34835
- relayErrorCode: relayErrorCode2 ?? "unknown",
34836
- relayOrigin: this.#relayOrigin,
34837
- source: "reconciliation_abandoned",
34838
- turnCount: turnCount.toString(),
34839
- ...this.#route
34840
- },
34841
- true
34842
- );
34843
- };
34844
35031
  connectionOpened = (connectionEpoch) => {
34845
35032
  this.#record(
34846
35033
  "relay_connection_opened",
@@ -35068,7 +35255,6 @@ var systemDaemonTimer = new SystemDaemonTimer();
35068
35255
 
35069
35256
  // src/run-daemon.ts
35070
35257
  var RELAY_RECONNECT_DELAY_MILLISECONDS = 500;
35071
- var ACTIVE_TURN_RECONCILIATION_CLOSE_CODE = 4009;
35072
35258
  function closeRelaySocket(socket, code, reason) {
35073
35259
  try {
35074
35260
  socket.close(code, reason);
@@ -35137,7 +35323,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
35137
35323
  const relayUrl = new URL(config2.relayUrl);
35138
35324
  relayUrl.searchParams.set("liveness", "1");
35139
35325
  const socket = await connectRelay(relayUrl, signal);
35140
- const reconnectingTurns = [...activeTurns.values()];
35141
35326
  diagnostics.connectionOpened(connectionEpoch);
35142
35327
  const connectionController = new AbortController();
35143
35328
  const handleSettingsDiscovery = createAgentSettingsDiscoveryHandler({
@@ -35159,6 +35344,18 @@ async function runRelayConnection(config2, directories, audit, sessions, install
35159
35344
  timer,
35160
35345
  resolveEnvironment: resolveAgentCatalogEnvironment
35161
35346
  });
35347
+ const activeTurnSnapshot = (sessionId) => {
35348
+ for (const turn of activeTurns.values()) {
35349
+ if (turn.command.sessionId !== sessionId) {
35350
+ continue;
35351
+ }
35352
+ const snapshot = turn.snapshot();
35353
+ if (snapshot !== null) {
35354
+ return snapshot;
35355
+ }
35356
+ }
35357
+ return null;
35358
+ };
35162
35359
  const nativeRequestHandler = createNativeSessionRequestHandler({
35163
35360
  audit,
35164
35361
  diagnostics,
@@ -35233,24 +35430,34 @@ async function runRelayConnection(config2, directories, audit, sessions, install
35233
35430
  );
35234
35431
  });
35235
35432
  };
35236
- const waitForSessionAvailability = async (command, waitSignal) => {
35237
- if (command.disposition === SessionPromptDisposition.Steer) {
35238
- return "available";
35433
+ const waitForSessionAvailability = async (command, queuedTurn, waitSignal) => {
35434
+ if (queuedTurn.effectiveDisposition() === SessionPromptDisposition.Steer) {
35435
+ return { disposition: SessionPromptDisposition.Steer, kind: "available" };
35239
35436
  }
35240
35437
  for (; ; ) {
35241
35438
  const first = [...activeTurns.values()].find(
35242
35439
  (turn) => turn.command.sessionId === command.sessionId && turn.command.disposition !== SessionPromptDisposition.Steer
35243
35440
  );
35244
35441
  if (first === void 0 || first.command.commandId === command.commandId) {
35245
- return command.disposition !== SessionPromptDisposition.Queue || operations.isTerminalExecution(command.targetCommandId, command.sessionId) ? "available" : "queue-target-unavailable";
35442
+ return command.disposition !== SessionPromptDisposition.Queue || operations.isTerminalExecution(command.targetCommandId, command.sessionId) ? { disposition: queuedTurn.effectiveDisposition(), kind: "available" } : { kind: "queue-target-unavailable" };
35246
35443
  }
35247
35444
  if (command.disposition !== SessionPromptDisposition.Queue) {
35248
- return "busy";
35445
+ return { kind: "busy" };
35249
35446
  }
35250
35447
  if (first.command.commandId !== command.targetCommandId) {
35251
- return "queue-target-unavailable";
35448
+ return { kind: "queue-target-unavailable" };
35449
+ }
35450
+ const promotion = queuedTurn.queuePromotion();
35451
+ if (promotion === null) {
35452
+ throw new Error("The queued prompt cannot be promoted");
35453
+ }
35454
+ const decision = await Promise.race([
35455
+ waitForTurnCompletion(first, waitSignal).then(() => "target-completed"),
35456
+ promotion.then(() => "promoted")
35457
+ ]);
35458
+ if (decision === "promoted") {
35459
+ return { disposition: SessionPromptDisposition.Steer, kind: "available" };
35252
35460
  }
35253
- await waitForTurnCompletion(first, waitSignal);
35254
35461
  }
35255
35462
  };
35256
35463
  const connectionLiveness = new RelayConnectionLiveness(timer, {
@@ -35318,6 +35525,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
35318
35525
  directories,
35319
35526
  audit,
35320
35527
  sessions,
35528
+ activeTurnSnapshot,
35321
35529
  connectionController.signal
35322
35530
  );
35323
35531
  return;
@@ -35331,6 +35539,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
35331
35539
  directories,
35332
35540
  audit,
35333
35541
  sessions,
35542
+ activeTurnSnapshot,
35334
35543
  connectionController.signal
35335
35544
  );
35336
35545
  return;
@@ -35403,6 +35612,19 @@ async function runRelayConnection(config2, directories, audit, sessions, install
35403
35612
  });
35404
35613
  return;
35405
35614
  }
35615
+ if (kind === SESSION_PROMPT_DISPOSITION_KIND) {
35616
+ const disposition = message;
35617
+ const turn2 = activeTurns.get(disposition.commandId);
35618
+ if (turn2 === void 0 || !turn2.promoteQueuedPrompt(disposition)) {
35619
+ reportOperationFailure(
35620
+ socket,
35621
+ disposition.commandId,
35622
+ disposition.sessionId,
35623
+ new Error("The queued prompt is unavailable")
35624
+ );
35625
+ }
35626
+ return;
35627
+ }
35406
35628
  if (kind === WORKSPACE_LIST_KIND) {
35407
35629
  const command2 = message;
35408
35630
  void executeWorkspaceList(socket, command2, directories, audit, connectionController.signal);
@@ -35512,10 +35734,15 @@ async function runRelayConnection(config2, directories, audit, sessions, install
35512
35734
  sessions,
35513
35735
  receipt.attemptId,
35514
35736
  turn.accept,
35515
- (waitSignal) => waitForSessionAvailability(command, waitSignal),
35737
+ () => send(socket, {
35738
+ commandId: command.commandId,
35739
+ kind: SESSION_QUEUED_KIND,
35740
+ sessionId: command.sessionId
35741
+ }),
35742
+ (waitSignal) => waitForSessionAvailability(command, turn, waitSignal),
35516
35743
  timer,
35517
35744
  turn.signal,
35518
- turn.recordText,
35745
+ turn.recordEvent,
35519
35746
  turn.cancellationRequested
35520
35747
  ).catch((error62) => {
35521
35748
  console.error("Mobius daemon turn failed", error62);
@@ -35536,43 +35763,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
35536
35763
  socket.addEventListener("close", handleClose);
35537
35764
  socket.addEventListener("error", handleError);
35538
35765
  socket.addEventListener("message", handleMessage);
35539
- void reconcileActiveTurns(config2, reconnectingTurns, connectionController.signal).then(
35540
- () => {
35541
- if (finished) {
35542
- return;
35543
- }
35544
- publisher.connect(socket);
35545
- },
35546
- (error62) => {
35547
- if (finished) {
35548
- return;
35549
- }
35550
- console.error("Mobius daemon could not reconcile active Agent turns", error62);
35551
- if (error62 instanceof ActiveTurnReconciliationError && error62.terminal) {
35552
- diagnostics.reconciliationAbandoned(
35553
- connectionEpoch,
35554
- error62.relayErrorCode,
35555
- reconnectingTurns.length
35556
- );
35557
- console.error(
35558
- "Mobius daemon abandoned Agent turns the Relay already settled",
35559
- error62.relayErrorCode
35560
- );
35561
- for (const turn of reconnectingTurns) {
35562
- activeTurns.delete(turn.command.commandId);
35563
- turn.abortDaemon();
35564
- }
35565
- publisher.connect(socket);
35566
- return;
35567
- }
35568
- failAndClose(
35569
- new Error("Active Agent turn reconciliation failed", { cause: error62 }),
35570
- ACTIVE_TURN_RECONCILIATION_CLOSE_CODE,
35571
- "Active Agent turn reconciliation failed",
35572
- "reconciliation"
35573
- );
35574
- }
35575
- );
35766
+ publisher.connect(socket);
35576
35767
  if (signal.aborted) {
35577
35768
  stop();
35578
35769
  }
@@ -35604,7 +35795,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
35604
35795
  const activeTurns = /* @__PURE__ */ new Map();
35605
35796
  const recordSessionEvent = (sessionId, event) => {
35606
35797
  for (const turn of activeTurns.values()) {
35607
- turn.recordInteraction(event);
35798
+ turn.recordEvent(event);
35608
35799
  }
35609
35800
  publisher.publish(sessionId, event);
35610
35801
  };
@@ -35772,7 +35963,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
35772
35963
  import { mkdir as mkdir5, realpath as realpath9, stat as stat8 } from "node:fs/promises";
35773
35964
  import { hostname as hostname3 } from "node:os";
35774
35965
  import { basename as basename6, resolve as resolve6 } from "node:path";
35775
- import { fetch as fetch5 } from "undici";
35966
+ import { fetch as fetch4 } from "undici";
35776
35967
 
35777
35968
  // src/storage/runtime-installation-store.ts
35778
35969
  import { createHash as createHash5, randomUUID as randomUUID7 } from "node:crypto";
@@ -36407,7 +36598,7 @@ async function claimPairing(options, defaultWorkspace, localAgents, installableA
36407
36598
  const endpoint = options.pairingId.length > 0 ? mobiusApiUrl(options.relayOrigin, `/v1/runtime-pairings/${encodeURIComponent(options.pairingId)}/redeem`) : mobiusApiUrl(options.relayOrigin, "/pairings/claim");
36408
36599
  let response;
36409
36600
  try {
36410
- response = await fetch5(endpoint, {
36601
+ response = await fetch4(endpoint, {
36411
36602
  body: JSON.stringify({
36412
36603
  agents,
36413
36604
  installableAgents,