@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/cli.js CHANGED
@@ -3381,7 +3381,7 @@ var program = new Command();
3381
3381
  // package.json
3382
3382
  var package_default = {
3383
3383
  name: "@moxt-ai/mobius",
3384
- version: "0.0.111",
3384
+ version: "0.0.115",
3385
3385
  description: "Mobius CLI for pairing and running local AI agent services.",
3386
3386
  type: "module",
3387
3387
  bin: {
@@ -24607,6 +24607,7 @@ var turnSchema = external_exports.object({
24607
24607
  id: boundedText(256),
24608
24608
  status: turnStatusSchema
24609
24609
  });
24610
+ var turnSteerResponseSchema = external_exports.object({ turnId: boundedText(256) });
24610
24611
  var turnNotificationSchema = external_exports.object({
24611
24612
  thread: external_exports.object({ id: boundedText(256) }).nullish(),
24612
24613
  threadId: boundedText(256),
@@ -24991,7 +24992,10 @@ function presentToolItem(item) {
24991
24992
  kind: "execute",
24992
24993
  locations: [],
24993
24994
  rawInput: { command: item.command, cwd: item.cwd },
24994
- rawOutput: { exitCode: item.exitCode, output: truncate(output2, TOOL_OUTPUT_CHARACTER_LIMIT) },
24995
+ rawOutput: {
24996
+ ...item.exitCode == null ? {} : { exitCode: item.exitCode },
24997
+ output: truncate(output2, TOOL_OUTPUT_CHARACTER_LIMIT)
24998
+ },
24995
24999
  status: commandStatus(item.status),
24996
25000
  title: truncate(firstLine(item.command), TITLE_CHARACTER_LIMIT)
24997
25001
  };
@@ -25047,7 +25051,7 @@ function presentToolItem(item) {
25047
25051
  }
25048
25052
  return null;
25049
25053
  }
25050
- function toolCallUpdate(item) {
25054
+ function toolCallUpdate(item, lifecycle) {
25051
25055
  const presentation = presentToolItem(item);
25052
25056
  if (presentation === null) {
25053
25057
  return null;
@@ -25058,7 +25062,7 @@ function toolCallUpdate(item) {
25058
25062
  locations: [...presentation.locations],
25059
25063
  rawInput: presentation.rawInput,
25060
25064
  rawOutput: presentation.rawOutput,
25061
- status: presentation.status,
25065
+ status: lifecycle === "completed" && presentation.status === "in_progress" ? "completed" : presentation.status,
25062
25066
  title: presentation.title,
25063
25067
  toolCallId: item.id
25064
25068
  };
@@ -25167,6 +25171,54 @@ function promptInput(prompt) {
25167
25171
  }
25168
25172
  return input2;
25169
25173
  }
25174
+ function steeringPromptInput(prompt) {
25175
+ const input2 = [];
25176
+ for (const block of prompt) {
25177
+ if (typeof block !== "object" || block === null) {
25178
+ throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
25179
+ }
25180
+ const type = Reflect.get(block, "type");
25181
+ if (type === "text") {
25182
+ const text = Reflect.get(block, "text");
25183
+ if (typeof text !== "string") {
25184
+ throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
25185
+ }
25186
+ input2.push({ text, text_elements: [], type: "text" });
25187
+ continue;
25188
+ }
25189
+ if (type === "image") {
25190
+ const data = Reflect.get(block, "data");
25191
+ const mimeType = Reflect.get(block, "mimeType");
25192
+ if (typeof data !== "string" || typeof mimeType !== "string") {
25193
+ throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
25194
+ }
25195
+ input2.push({ type: "image", url: `data:${mimeType};base64,${data}` });
25196
+ continue;
25197
+ }
25198
+ if (type === "resource") {
25199
+ const resource = Reflect.get(block, "resource");
25200
+ if (typeof resource !== "object" || resource === null) {
25201
+ throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
25202
+ }
25203
+ const text = Reflect.get(resource, "text");
25204
+ if (text !== void 0 && typeof text !== "string") {
25205
+ throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
25206
+ }
25207
+ input2.push({ text: text ?? "", text_elements: [], type: "text" });
25208
+ continue;
25209
+ }
25210
+ if (type === "resource_link") {
25211
+ const uri = Reflect.get(block, "uri");
25212
+ if (typeof uri !== "string") {
25213
+ throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
25214
+ }
25215
+ input2.push({ text: `Resource: ${uri}`, text_elements: [], type: "text" });
25216
+ continue;
25217
+ }
25218
+ throw new AcpExecutionError("Codex received an unsupported steering prompt", {}, "invalid_request");
25219
+ }
25220
+ return input2;
25221
+ }
25170
25222
  function modelValues(models) {
25171
25223
  return models.map((model) => ({
25172
25224
  description: model.description ?? "",
@@ -25345,6 +25397,7 @@ var CodexAcpAgent = class {
25345
25397
  this.#app = createAgentApp({ name: "mobius-codex" }).onConnect((connection) => {
25346
25398
  this.#connection = connection;
25347
25399
  }).onRequest(methods.agent.initialize, async () => ({
25400
+ _meta: { steering: { supported: true } },
25348
25401
  agentCapabilities: {
25349
25402
  loadSession: true,
25350
25403
  promptCapabilities: { embeddedContext: true, image: true },
@@ -25418,7 +25471,11 @@ var CodexAcpAgent = class {
25418
25471
  return { configOptions: this.#configOptions() };
25419
25472
  }).onRequest(methods.agent.session.prompt, async (context) => {
25420
25473
  return await this.#runTurn(promptInput(context.params.prompt), context.signal);
25421
- }).onRequest(methods.agent.session.list, async (context) => {
25474
+ }).onRequest(
25475
+ "_session/steering",
25476
+ (params) => params,
25477
+ async (context) => await this.#steerTurn(context.params, context.signal)
25478
+ ).onRequest(methods.agent.session.list, async (context) => {
25422
25479
  const decoded = threadListResponseSchema.parse(
25423
25480
  await this.#appServer.request(
25424
25481
  "thread/list",
@@ -25585,7 +25642,7 @@ var CodexAcpAgent = class {
25585
25642
  });
25586
25643
  continue;
25587
25644
  }
25588
- const update = toolCallUpdate(item);
25645
+ const update = toolCallUpdate(item, "snapshot");
25589
25646
  if (update !== null) {
25590
25647
  await this.#emit({ ...update, sessionUpdate: "tool_call_update" });
25591
25648
  }
@@ -25782,7 +25839,7 @@ var CodexAcpAgent = class {
25782
25839
  });
25783
25840
  return;
25784
25841
  }
25785
- const update = toolCallUpdate(item);
25842
+ const update = toolCallUpdate(item, method === "item/completed" ? "completed" : "started");
25786
25843
  if (update !== null) {
25787
25844
  await this.#enqueue(async () => {
25788
25845
  await this.#emit({ ...update, sessionUpdate: "tool_call_update" });
@@ -25968,6 +26025,35 @@ var CodexAcpAgent = class {
25968
26025
  }
25969
26026
  }
25970
26027
  };
26028
+ #steerTurn = async (params, signal) => {
26029
+ if (typeof params !== "object" || params === null) {
26030
+ throw new AcpExecutionError("Codex received an invalid steering request", {}, "invalid_request");
26031
+ }
26032
+ const sessionId = Reflect.get(params, "sessionId");
26033
+ const prompt = Reflect.get(params, "prompt");
26034
+ if (typeof sessionId !== "string" || !Array.isArray(prompt)) {
26035
+ throw new AcpExecutionError("Codex received an invalid steering request", {}, "invalid_request");
26036
+ }
26037
+ const active = this.#turn;
26038
+ if (sessionId !== this.#nativeSessionId || active === null || active.turn.id.length === 0) {
26039
+ return { outcome: "promptRequired", reason: "noRunningTurn" };
26040
+ }
26041
+ const input2 = steeringPromptInput(prompt);
26042
+ if (input2.length === 0) {
26043
+ throw new AcpExecutionError("Codex received an empty steering request", {}, "invalid_request");
26044
+ }
26045
+ const response = turnSteerResponseSchema.parse(
26046
+ await this.#appServer.request(
26047
+ "turn/steer",
26048
+ { expectedTurnId: active.turn.id, input: input2, threadId: this.#nativeSessionId },
26049
+ AbortSignal.any([signal, AbortSignal.timeout(APPROVAL_TIMEOUT_MILLISECONDS)])
26050
+ )
26051
+ );
26052
+ if (response.turnId !== active.turn.id) {
26053
+ throw new AcpExecutionError("Codex steered an unexpected turn", {}, "steering_target_unavailable");
26054
+ }
26055
+ return { outcome: "injected" };
26056
+ };
25971
26057
  #interruptTurn = async () => {
25972
26058
  const turn = this.#turn;
25973
26059
  if (turn === null) {
@@ -28567,12 +28653,14 @@ var encodeAgentInstallCancelledEvent = (message) => encode3(message, agentInstal
28567
28653
 
28568
28654
  // ../protocol/src/messages.ts
28569
28655
  var SESSION_PROMPT_KIND = "session.prompt";
28656
+ var SESSION_PROMPT_DISPOSITION_KIND = "session.prompt.disposition";
28570
28657
  var RUNTIME_WORKSPACE_BINDING_ID = "workspace";
28571
28658
  var SESSION_CANCEL_KIND = "session.cancel";
28572
28659
  var RUNTIME_LIVENESS_READY_KIND = "runtime.liveness.ready";
28573
28660
  var RUNTIME_HEARTBEAT_KIND = "runtime.heartbeat";
28574
28661
  var RUNTIME_HEARTBEAT_ACK_KIND = "runtime.heartbeat.ack";
28575
28662
  var SESSION_STARTED_KIND = "session.started";
28663
+ var SESSION_QUEUED_KIND = "session.queued";
28576
28664
  var AGENT_MESSAGE_DELTA_KIND = "agent.message.delta";
28577
28665
  var AGENT_ACTIVITY_KIND = "agent.activity";
28578
28666
  var AGENT_ACTIVITY_NARRATION_KIND = "agent.activity.narration";
@@ -28856,6 +28944,30 @@ function decodeSessionCancelCommand(encoded) {
28856
28944
  sessionId: readIdentifier(value, "sessionId")
28857
28945
  };
28858
28946
  }
28947
+ function decodeSessionPromptDispositionCommand(encoded) {
28948
+ const value = parseJson2(encoded);
28949
+ assertExactKeys(value, ["commandId", "disposition", "kind", "sessionId"]);
28950
+ assertKind(value, SESSION_PROMPT_DISPOSITION_KIND);
28951
+ if (readPromptDisposition(value) !== SessionPromptDisposition.Steer) {
28952
+ throw new ProtocolMessageError("Only queued prompts can be steered");
28953
+ }
28954
+ return {
28955
+ commandId: readIdentifier(value, "commandId"),
28956
+ disposition: SessionPromptDisposition.Steer,
28957
+ kind: SESSION_PROMPT_DISPOSITION_KIND,
28958
+ sessionId: readIdentifier(value, "sessionId")
28959
+ };
28960
+ }
28961
+ function decodeSessionQueuedEvent(encoded) {
28962
+ const value = parseJson2(encoded);
28963
+ assertExactKeys(value, ["commandId", "kind", "sessionId"]);
28964
+ assertKind(value, SESSION_QUEUED_KIND);
28965
+ return {
28966
+ commandId: readIdentifier(value, "commandId"),
28967
+ kind: SESSION_QUEUED_KIND,
28968
+ sessionId: readIdentifier(value, "sessionId")
28969
+ };
28970
+ }
28859
28971
  function decodeRuntimeLivenessReadyEvent(encoded) {
28860
28972
  const value = parseJson2(encoded);
28861
28973
  assertExactKeys(value, ["kind"]);
@@ -28983,6 +29095,12 @@ function encodeSessionPromptCommand(message) {
28983
29095
  function encodeSessionCancelCommand(message) {
28984
29096
  return JSON.stringify(decodeSessionCancelCommand(JSON.stringify(message)));
28985
29097
  }
29098
+ function encodeSessionPromptDispositionCommand(message) {
29099
+ return JSON.stringify(decodeSessionPromptDispositionCommand(JSON.stringify(message)));
29100
+ }
29101
+ function encodeSessionQueuedEvent(message) {
29102
+ return JSON.stringify(decodeSessionQueuedEvent(JSON.stringify(message)));
29103
+ }
28986
29104
  function encodeRuntimeLivenessReadyEvent(message) {
28987
29105
  return JSON.stringify(decodeRuntimeLivenessReadyEvent(JSON.stringify(message)));
28988
29106
  }
@@ -29114,6 +29232,19 @@ var envelope = {
29114
29232
  requestId: identifierStringSchema,
29115
29233
  sessionId: identifierStringSchema
29116
29234
  };
29235
+ var activeTurnActivitySchema = external_exports.strictObject({
29236
+ activityId: external_exports.string().min(1).max(128),
29237
+ activityType: external_exports.string().min(1).max(128),
29238
+ content: external_exports.array(displayContentSchema).max(100).readonly(),
29239
+ input: external_exports.string().max(1e5),
29240
+ locations: external_exports.array(external_exports.string().min(1).max(2048)).max(100).readonly(),
29241
+ name: external_exports.string().max(128),
29242
+ output: external_exports.string().max(1e5),
29243
+ sequence: external_exports.number().int().nonnegative(),
29244
+ status: external_exports.string().min(1).max(64),
29245
+ title: external_exports.string().max(500),
29246
+ toolKind: external_exports.string().max(64)
29247
+ }).readonly();
29117
29248
  var identity = {
29118
29249
  ...envelope,
29119
29250
  kind: external_exports.literal(NATIVE_SESSION_REQUEST_KIND),
@@ -29189,7 +29320,9 @@ var nativeSessionResultSchema = external_exports.discriminatedUnion("action", [
29189
29320
  action: external_exports.literal("active-turn"),
29190
29321
  targetSessionId: identifierStringSchema,
29191
29322
  turn: external_exports.strictObject({
29323
+ activities: external_exports.array(activeTurnActivitySchema).max(100).readonly(),
29192
29324
  commandId: identifierStringSchema,
29325
+ content: external_exports.array(displayContentSchema).max(100).readonly(),
29193
29326
  prompt: external_exports.string().max(1e5),
29194
29327
  text: external_exports.string().max(ACTIVE_TURN_TEXT_LIMIT),
29195
29328
  truncated: external_exports.boolean(),
@@ -29493,6 +29626,11 @@ var serviceToDaemonSignatures = {
29493
29626
  encodeSessionPromptCommand,
29494
29627
  decodeSessionPromptCommand
29495
29628
  ),
29629
+ [SESSION_PROMPT_DISPOSITION_KIND]: defineMessageSignature(
29630
+ SESSION_PROMPT_DISPOSITION_KIND,
29631
+ encodeSessionPromptDispositionCommand,
29632
+ decodeSessionPromptDispositionCommand
29633
+ ),
29496
29634
  [WORKSPACE_LIST_KIND]: defineMessageSignature(
29497
29635
  WORKSPACE_LIST_KIND,
29498
29636
  encodeWorkspaceListCommand,
@@ -29563,6 +29701,11 @@ var daemonToServiceSignatures = {
29563
29701
  encodeSessionsQueriedEvent,
29564
29702
  decodeSessionsQueriedEvent
29565
29703
  ),
29704
+ [SESSION_QUEUED_KIND]: defineMessageSignature(
29705
+ SESSION_QUEUED_KIND,
29706
+ encodeSessionQueuedEvent,
29707
+ decodeSessionQueuedEvent
29708
+ ),
29566
29709
  [NATIVE_SESSION_RESULT_KIND]: defineMessageSignature(
29567
29710
  NATIVE_SESSION_RESULT_KIND,
29568
29711
  encodeNativeSessionResult,
@@ -35203,7 +35346,10 @@ function liveHistoryCoveredTurnRanges(history) {
35203
35346
  }
35204
35347
  return ranges;
35205
35348
  }
35206
- function paginateLiveSessionHistory(history, sessionId, cursor, limit) {
35349
+ function historyMessageCharacters(message) {
35350
+ return message.text.length + (message.role === "assistant" ? JSON.stringify(message.activities).length + JSON.stringify(message.content).length : 0);
35351
+ }
35352
+ function paginateAcpSessionHistory(history, sessionId, cursor, limit) {
35207
35353
  if (history.status === "unavailable") {
35208
35354
  if (cursor !== null) {
35209
35355
  throw new AcpExecutionError("Unavailable native Session history has no cursor", {}, "invalid_cursor");
@@ -35229,6 +35375,80 @@ function paginateLiveSessionHistory(history, sessionId, cursor, limit) {
35229
35375
  truncated: history.truncated
35230
35376
  };
35231
35377
  }
35378
+ function paginateLiveSessionHistory(history, activeTurn, sessionId, cursor, limit) {
35379
+ if (activeTurn === null || cursor !== null) {
35380
+ return paginateAcpSessionHistory(history, sessionId, cursor, limit);
35381
+ }
35382
+ const activeMessageOverhead = 4;
35383
+ const activeStructuredCharacters = JSON.stringify(activeTurn.activities).length + JSON.stringify(activeTurn.content).length;
35384
+ const maximumActiveTextLength = Math.max(
35385
+ 0,
35386
+ SESSION_HISTORY_CHARACTER_LIMIT - activeTurn.prompt.length - activeStructuredCharacters - activeMessageOverhead
35387
+ );
35388
+ const activeText = activeTurn.text.slice(-maximumActiveTextLength);
35389
+ const completeActiveMessages = [
35390
+ { role: "user", text: activeTurn.prompt },
35391
+ {
35392
+ activities: activeTurn.activities,
35393
+ content: activeTurn.content,
35394
+ role: "assistant",
35395
+ text: activeText
35396
+ }
35397
+ ];
35398
+ if (history.status === "unavailable") {
35399
+ return {
35400
+ coveredCommandIds: [],
35401
+ coveredMessageIds: [],
35402
+ messages: completeActiveMessages,
35403
+ nextCursor: null,
35404
+ status: "available",
35405
+ truncated: activeTurn.truncated || activeText.length !== activeTurn.text.length
35406
+ };
35407
+ }
35408
+ const latestNativeMessage = history.messages.at(-1);
35409
+ const activeMessages = latestNativeMessage?.role === "user" && latestNativeMessage.text === activeTurn.prompt ? completeActiveMessages.slice(1) : completeActiveMessages;
35410
+ let historicalMessageCount = 0;
35411
+ let remainingCharacters = SESSION_HISTORY_CHARACTER_LIMIT - activeText.length - activeMessageOverhead - activeStructuredCharacters - (activeMessages.length === completeActiveMessages.length ? activeTurn.prompt.length : 0);
35412
+ const historicalMessageLimit = Math.max(0, limit - activeMessages.length);
35413
+ for (let index = history.messages.length - 1; index >= 0 && historicalMessageCount < historicalMessageLimit; index -= 1) {
35414
+ const message = history.messages[index];
35415
+ if (message === void 0) {
35416
+ break;
35417
+ }
35418
+ const characters = historyMessageCharacters(message);
35419
+ if (characters > remainingCharacters) {
35420
+ break;
35421
+ }
35422
+ historicalMessageCount += 1;
35423
+ remainingCharacters -= characters;
35424
+ }
35425
+ const page = historicalMessageCount === 0 ? {
35426
+ coveredCommandIds: [],
35427
+ coveredMessageIds: [],
35428
+ messages: [],
35429
+ nextCursor: history.messages.length === 0 ? null : liveHistoryCursor(sessionId, history.messages.length),
35430
+ status: "available",
35431
+ truncated: history.truncated
35432
+ } : paginateAcpSessionHistory(history, sessionId, null, historicalMessageCount);
35433
+ return {
35434
+ ...page,
35435
+ messages: [...page.messages, ...activeMessages],
35436
+ truncated: page.truncated || activeTurn.truncated || activeText.length !== activeTurn.text.length
35437
+ };
35438
+ }
35439
+ function mergeLiveSessionHistory(history, activeTurn, sessionId) {
35440
+ const page = paginateLiveSessionHistory(history, activeTurn, sessionId, null, 1e3);
35441
+ if (page.status === "unavailable") {
35442
+ return { cause: page.cause, status: "unavailable" };
35443
+ }
35444
+ return {
35445
+ coveredCommandIds: page.coveredCommandIds,
35446
+ coveredMessageIds: page.coveredMessageIds,
35447
+ messages: page.messages,
35448
+ status: "available",
35449
+ truncated: page.truncated
35450
+ };
35451
+ }
35232
35452
 
35233
35453
  // src/prompt-artifact-resolver.ts
35234
35454
  import { createHash as createHash3 } from "node:crypto";
@@ -35860,7 +36080,7 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
35860
36080
  reportOperationFailure(socket, command.requestId, command.sessionId, error62, metrics.snapshot());
35861
36081
  }
35862
36082
  }
35863
- async function executeSessionLiveHistoryLoad(socket, command, config2, directories, audit, sessions, signal) {
36083
+ async function executeSessionLiveHistoryLoad(socket, command, config2, directories, audit, sessions, activeTurn, signal) {
35864
36084
  try {
35865
36085
  const resolved = await resolveSessionDirectories(
35866
36086
  directories,
@@ -35877,13 +36097,14 @@ async function executeSessionLiveHistoryLoad(socket, command, config2, directori
35877
36097
  signal
35878
36098
  });
35879
36099
  signal.throwIfAborted();
36100
+ const mergedHistory = mergeLiveSessionHistory(history, activeTurn(command.sessionId), command.sessionId);
35880
36101
  audit.record({
35881
36102
  commandId: command.requestId,
35882
36103
  event: "session_history_loaded",
35883
36104
  sessionId: command.sessionId
35884
36105
  });
35885
36106
  send(socket, {
35886
- history,
36107
+ history: mergedHistory,
35887
36108
  kind: "session.live-history.loaded",
35888
36109
  requestId: command.requestId,
35889
36110
  sessionId: command.sessionId
@@ -35909,7 +36130,7 @@ async function executeSessionLiveHistoryLoad(socket, command, config2, directori
35909
36130
  });
35910
36131
  }
35911
36132
  }
35912
- async function executeSessionLiveHistoryPageLoad(socket, command, config2, directories, audit, sessions, signal) {
36133
+ async function executeSessionLiveHistoryPageLoad(socket, command, config2, directories, audit, sessions, activeTurn, signal) {
35913
36134
  try {
35914
36135
  const resolved = await resolveSessionDirectories(
35915
36136
  directories,
@@ -35926,7 +36147,13 @@ async function executeSessionLiveHistoryPageLoad(socket, command, config2, direc
35926
36147
  signal
35927
36148
  });
35928
36149
  signal.throwIfAborted();
35929
- const page = paginateLiveSessionHistory(history, command.sessionId, command.cursor, command.limit);
36150
+ const page = paginateLiveSessionHistory(
36151
+ history,
36152
+ activeTurn(command.sessionId),
36153
+ command.sessionId,
36154
+ command.cursor,
36155
+ command.limit
36156
+ );
35930
36157
  audit.record({
35931
36158
  commandId: command.requestId,
35932
36159
  event: "session_history_loaded",
@@ -35999,14 +36226,11 @@ async function executeSessionConfigure(publisher, socket, command, config2, dire
35999
36226
  reportOperationFailure(socket, command.requestId, command.sessionId, error62);
36000
36227
  }
36001
36228
  }
36002
- async function executePrompt(operations, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, waitForSessionAvailability, timer, signal, recordLiveText, cancellationRequested) {
36003
- const activities = new CoalescingDaemonActivityPublisher(timer, (activity2) => {
36004
- publisher.publish(command.sessionId, daemonActivity(command, activity2));
36005
- });
36229
+ async function executePrompt(operations, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, acknowledgeQueued, waitForSessionAvailability, timer, signal, recordLiveEvent, cancellationRequested) {
36006
36230
  const narration = new CoalescingNarrationPublisher(
36007
36231
  timer,
36008
36232
  (increment) => {
36009
- publisher.publish(command.sessionId, {
36233
+ const event = {
36010
36234
  activityId: increment.activityId,
36011
36235
  activityType: increment.activityType,
36012
36236
  commandId: command.commandId,
@@ -36014,29 +36238,34 @@ async function executePrompt(operations, publisher, command, config2, directorie
36014
36238
  sequence: increment.sequence,
36015
36239
  sessionId: command.sessionId,
36016
36240
  text: increment.text
36017
- });
36241
+ };
36242
+ publisher.publish(command.sessionId, recordLiveEvent(event));
36018
36243
  },
36019
36244
  AGENT_ACTIVITY_COALESCING_MILLISECONDS,
36020
36245
  AGENT_TEXT_MAXIMUM_LENGTH
36021
36246
  );
36247
+ const activities = new CoalescingDaemonActivityPublisher(timer, (activity2) => {
36248
+ if (activity2.status !== "pending" && activity2.status !== "running") {
36249
+ narration.flush();
36250
+ }
36251
+ const event = daemonActivity(command, activity2);
36252
+ publisher.publish(command.sessionId, recordLiveEvent(event));
36253
+ });
36022
36254
  const text = new CoalescingTextPublisher(
36023
36255
  timer,
36024
36256
  (messageId, delta) => {
36025
- const stream = recordLiveText(delta);
36026
- publisher.publish(command.sessionId, {
36027
- commandId: command.commandId,
36028
- epoch: stream.epoch,
36029
- kind: AGENT_MESSAGE_DELTA_KIND,
36030
- messageId,
36031
- sequence: stream.sequence,
36032
- sessionId: command.sessionId,
36033
- text: delta
36034
- });
36257
+ publisher.publish(
36258
+ command.sessionId,
36259
+ recordLiveEvent({ kind: AGENT_MESSAGE_DELTA_KIND, messageId, text: delta })
36260
+ );
36035
36261
  },
36036
36262
  AGENT_TEXT_COALESCING_MILLISECONDS,
36037
36263
  AGENT_TEXT_MAXIMUM_LENGTH
36038
36264
  );
36039
36265
  try {
36266
+ if (command.disposition === SessionPromptDisposition.Queue) {
36267
+ acknowledgeQueued();
36268
+ }
36040
36269
  const resolved = await resolveSessionDirectories(
36041
36270
  directories,
36042
36271
  command.bindingId,
@@ -36046,10 +36275,10 @@ async function executePrompt(operations, publisher, command, config2, directorie
36046
36275
  );
36047
36276
  const agent = config2.catalog.find(command.agentId);
36048
36277
  const availability = await waitForSessionAvailability(signal);
36049
- if (availability === "busy") {
36278
+ if (availability.kind === "busy") {
36050
36279
  throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
36051
36280
  }
36052
- if (availability === "queue-target-unavailable") {
36281
+ if (availability.kind === "queue-target-unavailable") {
36053
36282
  throw new AcpExecutionError(
36054
36283
  "The queued prompt target is unavailable",
36055
36284
  {},
@@ -36067,7 +36296,7 @@ async function executePrompt(operations, publisher, command, config2, directorie
36067
36296
  sessionId: command.sessionId,
36068
36297
  signal
36069
36298
  });
36070
- if (command.disposition === SessionPromptDisposition.Steer) {
36299
+ if (availability.disposition === SessionPromptDisposition.Steer) {
36071
36300
  assertAppliedSessionConfiguration(prepared.configOptions, sessionConfigurations ?? []);
36072
36301
  } else {
36073
36302
  await applyCompleteSessionConfiguration(
@@ -36102,7 +36331,7 @@ async function executePrompt(operations, publisher, command, config2, directorie
36102
36331
  });
36103
36332
  const attachments = await resolvePromptArtifacts(config2, command, signal);
36104
36333
  let stopReason;
36105
- if (command.disposition === SessionPromptDisposition.Steer) {
36334
+ if (availability.disposition === SessionPromptDisposition.Steer) {
36106
36335
  await sessions.steerPrompt({
36107
36336
  additionalDirectories: resolved.additionalDirectories,
36108
36337
  agent: executionAgent,
@@ -36122,7 +36351,7 @@ async function executePrompt(operations, publisher, command, config2, directorie
36122
36351
  agent: executionAgent,
36123
36352
  commandId: command.commandId,
36124
36353
  cwd: resolved.cwd,
36125
- disposition: command.disposition,
36354
+ disposition: availability.disposition,
36126
36355
  images: attachments.images,
36127
36356
  onActivity: activities.record,
36128
36357
  onNarration: (increment) => {
@@ -37497,6 +37726,144 @@ var WorkspaceDirectoryService = class {
37497
37726
  };
37498
37727
  };
37499
37728
 
37729
+ // src/daemon-active-turn.ts
37730
+ import { randomUUID as randomUUID3 } from "node:crypto";
37731
+ var ActiveDaemonTurn = class {
37732
+ attemptId;
37733
+ command;
37734
+ #controller;
37735
+ #finished = Promise.withResolvers();
37736
+ #cancellationRequested = false;
37737
+ #dispatch;
37738
+ #text = "";
37739
+ #activities = /* @__PURE__ */ new Map();
37740
+ #content = /* @__PURE__ */ new Map();
37741
+ #truncated = false;
37742
+ #sequence = 0;
37743
+ #interaction = null;
37744
+ #epoch = decodeIdentifier(randomUUID3());
37745
+ constructor(command, attemptId) {
37746
+ this.attemptId = attemptId;
37747
+ this.command = command;
37748
+ this.#controller = new AbortController();
37749
+ this.#dispatch = command.disposition === SessionPromptDisposition.Queue ? { kind: "queued", promotion: Promise.withResolvers() } : { kind: "pending" };
37750
+ }
37751
+ abortDaemon = () => {
37752
+ this.#controller.abort();
37753
+ };
37754
+ finish = () => this.#finished.resolve();
37755
+ accept = () => {
37756
+ this.#dispatch = { kind: "accepted" };
37757
+ return { epoch: this.#epoch, sequence: 0 };
37758
+ };
37759
+ promoteQueuedPrompt = (command) => {
37760
+ if (command.commandId !== this.command.commandId || command.sessionId !== this.command.sessionId || this.#dispatch.kind !== "queued") {
37761
+ return false;
37762
+ }
37763
+ const promotion = this.#dispatch.promotion;
37764
+ this.#dispatch = { kind: "promoted" };
37765
+ promotion.resolve();
37766
+ return true;
37767
+ };
37768
+ queuePromotion = () => {
37769
+ if (this.#dispatch.kind === "queued") {
37770
+ return this.#dispatch.promotion.promise;
37771
+ }
37772
+ return this.#dispatch.kind === "promoted" ? Promise.resolve() : null;
37773
+ };
37774
+ effectiveDisposition = () => this.#dispatch.kind === "promoted" ? SessionPromptDisposition.Steer : this.command.disposition;
37775
+ recordEvent = (event) => {
37776
+ if (event.kind === AGENT_MESSAGE_DELTA_KIND) {
37777
+ this.#sequence += 1;
37778
+ this.#text += event.text;
37779
+ if (this.#text.length > ACTIVE_TURN_TEXT_LIMIT) {
37780
+ this.#text = this.#text.slice(-ACTIVE_TURN_TEXT_LIMIT);
37781
+ this.#truncated = true;
37782
+ }
37783
+ return {
37784
+ commandId: this.command.commandId,
37785
+ epoch: this.#epoch,
37786
+ kind: AGENT_MESSAGE_DELTA_KIND,
37787
+ messageId: event.messageId,
37788
+ sequence: this.#sequence,
37789
+ sessionId: this.command.sessionId,
37790
+ text: event.text
37791
+ };
37792
+ }
37793
+ if (event.sessionId !== this.command.sessionId || "commandId" in event && event.commandId !== this.command.commandId) {
37794
+ return event;
37795
+ }
37796
+ if (event.kind === AGENT_ACTIVITY_KIND) {
37797
+ this.#activities.set(event.activityId, {
37798
+ activityId: event.activityId,
37799
+ activityType: event.activityType,
37800
+ content: event.content,
37801
+ input: event.input,
37802
+ locations: event.locations,
37803
+ name: event.name,
37804
+ output: event.output,
37805
+ sequence: event.sequence,
37806
+ status: event.status,
37807
+ title: event.title,
37808
+ toolKind: event.toolKind
37809
+ });
37810
+ } else if (event.kind === AGENT_ACTIVITY_NARRATION_KIND) {
37811
+ const previous = this.#activities.get(event.activityId);
37812
+ this.#activities.set(event.activityId, {
37813
+ activityId: event.activityId,
37814
+ activityType: event.activityType,
37815
+ content: previous?.content ?? [],
37816
+ input: previous?.input ?? "",
37817
+ locations: previous?.locations ?? [],
37818
+ name: previous?.name ?? "",
37819
+ output: `${previous?.output ?? ""}${event.text}`,
37820
+ sequence: event.sequence,
37821
+ status: previous?.status ?? "running",
37822
+ title: previous?.title ?? "Thinking",
37823
+ toolKind: previous?.toolKind ?? ""
37824
+ });
37825
+ } else if (event.kind === AGENT_CONTENT_KIND) {
37826
+ this.#content.set(event.contentId, event.content);
37827
+ } else if (event.kind === SESSION_PERMISSION_REQUESTED_KIND || event.kind === SESSION_ELICITATION_REQUESTED_KIND) {
37828
+ this.#interaction = event;
37829
+ } else if ((event.kind === SESSION_PERMISSION_RESOLVED_KIND || event.kind === SESSION_ELICITATION_RESOLVED_KIND) && this.#interaction?.interactionId === event.interactionId) {
37830
+ this.#interaction = null;
37831
+ }
37832
+ return event;
37833
+ };
37834
+ snapshot = () => this.#dispatch.kind === "accepted" ? {
37835
+ activities: [...this.#activities.values()].sort((left, right) => left.sequence - right.sequence),
37836
+ commandId: decodeIdentifier(this.command.commandId),
37837
+ content: [...this.#content.values()],
37838
+ prompt: this.command.prompt,
37839
+ text: this.#text,
37840
+ truncated: this.#truncated,
37841
+ epoch: this.#epoch,
37842
+ interaction: this.#interaction,
37843
+ sequence: this.#sequence,
37844
+ state: "running"
37845
+ } : null;
37846
+ matches = (cancellation) => cancellation.commandId === this.command.commandId && cancellation.sessionId === this.command.sessionId;
37847
+ requestCancellation = () => {
37848
+ if (this.#cancellationRequested) {
37849
+ return "already-requested";
37850
+ }
37851
+ this.#cancellationRequested = true;
37852
+ if (this.#dispatch.kind !== "accepted") {
37853
+ this.#controller.abort(new Error("The queued Agent turn was cancelled"));
37854
+ return "pending";
37855
+ }
37856
+ return "running";
37857
+ };
37858
+ cancellationRequested = () => this.#cancellationRequested;
37859
+ get signal() {
37860
+ return this.#controller.signal;
37861
+ }
37862
+ get completion() {
37863
+ return this.#finished.promise;
37864
+ }
37865
+ };
37866
+
37500
37867
  // src/daemon-diagnostic-log.ts
37501
37868
  import { appendFileSync, mkdirSync, readFileSync as readFileSync2, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
37502
37869
  import { join as join17 } from "node:path";
@@ -37679,167 +38046,6 @@ var DaemonInstallationObserver = class {
37679
38046
  };
37680
38047
  };
37681
38048
 
37682
- // src/daemon-turn-reconciliation.ts
37683
- import { randomUUID as randomUUID3 } from "node:crypto";
37684
- import { fetch as fetch5 } from "undici";
37685
- var ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS = 2e4;
37686
- var ActiveDaemonTurn = class {
37687
- attemptId;
37688
- command;
37689
- #controller;
37690
- #finished = Promise.withResolvers();
37691
- #cancellationRequested = false;
37692
- #accepted = false;
37693
- #text = "";
37694
- #truncated = false;
37695
- #sequence = 0;
37696
- #interaction = null;
37697
- #epoch = decodeIdentifier(randomUUID3());
37698
- constructor(command, attemptId) {
37699
- this.attemptId = attemptId;
37700
- this.command = command;
37701
- this.#controller = new AbortController();
37702
- }
37703
- abortDaemon = () => {
37704
- this.#controller.abort();
37705
- };
37706
- finish = () => this.#finished.resolve();
37707
- accept = () => {
37708
- this.#accepted = true;
37709
- return { epoch: this.#epoch, sequence: 0 };
37710
- };
37711
- recordText = (delta) => {
37712
- this.#sequence += 1;
37713
- this.#text += delta;
37714
- if (this.#text.length > ACTIVE_TURN_TEXT_LIMIT) {
37715
- this.#text = this.#text.slice(-ACTIVE_TURN_TEXT_LIMIT);
37716
- this.#truncated = true;
37717
- }
37718
- return { epoch: this.#epoch, sequence: this.#sequence };
37719
- };
37720
- recordInteraction = (event) => {
37721
- if (event.sessionId !== this.command.sessionId) {
37722
- return;
37723
- }
37724
- if (event.kind === SESSION_PERMISSION_REQUESTED_KIND || event.kind === SESSION_ELICITATION_REQUESTED_KIND) {
37725
- if (event.commandId === this.command.commandId) {
37726
- this.#interaction = event;
37727
- }
37728
- } else if ((event.kind === SESSION_PERMISSION_RESOLVED_KIND || event.kind === SESSION_ELICITATION_RESOLVED_KIND) && this.#interaction?.interactionId === event.interactionId) {
37729
- this.#interaction = null;
37730
- }
37731
- };
37732
- snapshot = () => this.#accepted ? {
37733
- commandId: decodeIdentifier(this.command.commandId),
37734
- prompt: this.command.prompt,
37735
- text: this.#text,
37736
- truncated: this.#truncated,
37737
- epoch: this.#epoch,
37738
- interaction: this.#interaction,
37739
- sequence: this.#sequence,
37740
- state: "running"
37741
- } : null;
37742
- matches = (cancellation) => cancellation.commandId === this.command.commandId && cancellation.sessionId === this.command.sessionId;
37743
- requestCancellation = () => {
37744
- if (this.#cancellationRequested) {
37745
- return "already-requested";
37746
- }
37747
- this.#cancellationRequested = true;
37748
- if (!this.#accepted) {
37749
- this.#controller.abort(new Error("The queued Agent turn was cancelled"));
37750
- return "pending";
37751
- }
37752
- return "running";
37753
- };
37754
- cancellationRequested = () => this.#cancellationRequested;
37755
- get signal() {
37756
- return this.#controller.signal;
37757
- }
37758
- get completion() {
37759
- return this.#finished.promise;
37760
- }
37761
- };
37762
- var ActiveTurnReconciliationError = class extends Error {
37763
- code = "active_turn_reconciliation_failed";
37764
- diagnosticDetails;
37765
- relayErrorCode;
37766
- terminal;
37767
- constructor(message, options = {}) {
37768
- super(message, options);
37769
- this.name = "ActiveTurnReconciliationError";
37770
- this.relayErrorCode = options.relayErrorCode ?? null;
37771
- this.terminal = options.terminal ?? false;
37772
- this.diagnosticDetails = this.relayErrorCode === null ? {} : { relayErrorCode: this.relayErrorCode };
37773
- }
37774
- };
37775
- var TERMINAL_RECONCILIATION_RELAY_CODES = /* @__PURE__ */ new Set(["session_conflict"]);
37776
- async function relayErrorCode(response) {
37777
- try {
37778
- const body = JSON.parse(await response.text());
37779
- if (typeof body !== "object" || body === null) {
37780
- return null;
37781
- }
37782
- const error62 = Reflect.get(body, "error");
37783
- if (typeof error62 !== "object" || error62 === null) {
37784
- return null;
37785
- }
37786
- const code = Reflect.get(error62, "code");
37787
- return typeof code === "string" && code.length > 0 ? code : null;
37788
- } catch {
37789
- return null;
37790
- }
37791
- }
37792
- function activeTurnReconciliationEndpoint(config2, turn) {
37793
- const endpoint = relayHttpEndpoint(config2.relayUrl);
37794
- let channelPath = "";
37795
- if (endpoint.pathname.endsWith("/daemon")) {
37796
- channelPath = endpoint.pathname.slice(0, -"/daemon".length);
37797
- } else {
37798
- const runtimePath = "/v1/runtimes/connect";
37799
- if (!endpoint.pathname.endsWith(runtimePath)) {
37800
- throw new ActiveTurnReconciliationError("The Relay URL is invalid");
37801
- }
37802
- channelPath = `${endpoint.pathname.slice(0, -runtimePath.length)}/channels/${encodeURIComponent(config2.channelId)}`;
37803
- }
37804
- endpoint.pathname = `${channelPath}/sessions/${encodeURIComponent(turn.command.sessionId)}/attempts/${encodeURIComponent(turn.attemptId)}/reconciliation`;
37805
- return endpoint;
37806
- }
37807
- async function reconcileActiveTurn(config2, turn, signal) {
37808
- signal.throwIfAborted();
37809
- const timeoutSignal = AbortSignal.timeout(ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS);
37810
- const requestSignal = AbortSignal.any([signal, timeoutSignal]);
37811
- let response;
37812
- try {
37813
- response = await fetch5(activeTurnReconciliationEndpoint(config2, turn), {
37814
- body: JSON.stringify({ outcome: { kind: "running" } }),
37815
- dispatcher: environmentProxyDispatcher,
37816
- headers: { ...runtimeAuthorization(config2.relayUrl), "content-type": "application/json" },
37817
- method: "POST",
37818
- signal: requestSignal
37819
- });
37820
- } catch (error62) {
37821
- if (signal.aborted) {
37822
- signal.throwIfAborted();
37823
- }
37824
- throw new ActiveTurnReconciliationError(
37825
- timeoutSignal.aborted ? "The active Agent turn reconciliation timed out" : "The active Agent turn could not be reconciled",
37826
- { cause: error62 }
37827
- );
37828
- }
37829
- if (!response.ok) {
37830
- const errorCode = await relayErrorCode(response);
37831
- const terminal = errorCode !== null && TERMINAL_RECONCILIATION_RELAY_CODES.has(errorCode);
37832
- throw new ActiveTurnReconciliationError(
37833
- 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()}`,
37834
- { relayErrorCode: errorCode, terminal }
37835
- );
37836
- }
37837
- await response.body?.cancel();
37838
- }
37839
- async function reconcileActiveTurns(config2, turns, signal) {
37840
- await Promise.all(turns.map(async (turn) => await reconcileActiveTurn(config2, turn, signal)));
37841
- }
37842
-
37843
38049
  // src/native-sessions/codex-history.ts
37844
38050
  import { spawn as spawn5 } from "node:child_process";
37845
38051
  var responseSchema = external_exports.union([
@@ -39138,25 +39344,6 @@ var RelayConnectionDiagnostics = class {
39138
39344
  addFailureDetails(details, failure2);
39139
39345
  this.#record("relay_connection_failed", connectionEpoch.toString(), details, true);
39140
39346
  };
39141
- /**
39142
- * Records that the Runtime gave up on Agent turns the Relay already settled. This is not a connection
39143
- * failure, so it is recorded independently of the per-epoch failure deduplication.
39144
- */
39145
- reconciliationAbandoned = (connectionEpoch, relayErrorCode2, turnCount) => {
39146
- this.#record(
39147
- "relay_reconciliation_abandoned",
39148
- connectionEpoch.toString(),
39149
- {
39150
- connectionEpoch: connectionEpoch.toString(),
39151
- relayErrorCode: relayErrorCode2 ?? "unknown",
39152
- relayOrigin: this.#relayOrigin,
39153
- source: "reconciliation_abandoned",
39154
- turnCount: turnCount.toString(),
39155
- ...this.#route
39156
- },
39157
- true
39158
- );
39159
- };
39160
39347
  connectionOpened = (connectionEpoch) => {
39161
39348
  this.#record(
39162
39349
  "relay_connection_opened",
@@ -39384,7 +39571,6 @@ var systemDaemonTimer = new SystemDaemonTimer();
39384
39571
 
39385
39572
  // src/run-daemon.ts
39386
39573
  var RELAY_RECONNECT_DELAY_MILLISECONDS = 500;
39387
- var ACTIVE_TURN_RECONCILIATION_CLOSE_CODE = 4009;
39388
39574
  function closeRelaySocket(socket, code, reason) {
39389
39575
  try {
39390
39576
  socket.close(code, reason);
@@ -39453,7 +39639,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
39453
39639
  const relayUrl = new URL(config2.relayUrl);
39454
39640
  relayUrl.searchParams.set("liveness", "1");
39455
39641
  const socket = await connectRelay(relayUrl, signal);
39456
- const reconnectingTurns = [...activeTurns.values()];
39457
39642
  diagnostics.connectionOpened(connectionEpoch);
39458
39643
  const connectionController = new AbortController();
39459
39644
  const handleSettingsDiscovery = createAgentSettingsDiscoveryHandler({
@@ -39475,6 +39660,18 @@ async function runRelayConnection(config2, directories, audit, sessions, install
39475
39660
  timer,
39476
39661
  resolveEnvironment: resolveAgentCatalogEnvironment
39477
39662
  });
39663
+ const activeTurnSnapshot = (sessionId) => {
39664
+ for (const turn of activeTurns.values()) {
39665
+ if (turn.command.sessionId !== sessionId) {
39666
+ continue;
39667
+ }
39668
+ const snapshot = turn.snapshot();
39669
+ if (snapshot !== null) {
39670
+ return snapshot;
39671
+ }
39672
+ }
39673
+ return null;
39674
+ };
39478
39675
  const nativeRequestHandler = createNativeSessionRequestHandler({
39479
39676
  audit,
39480
39677
  diagnostics,
@@ -39549,24 +39746,34 @@ async function runRelayConnection(config2, directories, audit, sessions, install
39549
39746
  );
39550
39747
  });
39551
39748
  };
39552
- const waitForSessionAvailability = async (command, waitSignal) => {
39553
- if (command.disposition === SessionPromptDisposition.Steer) {
39554
- return "available";
39749
+ const waitForSessionAvailability = async (command, queuedTurn, waitSignal) => {
39750
+ if (queuedTurn.effectiveDisposition() === SessionPromptDisposition.Steer) {
39751
+ return { disposition: SessionPromptDisposition.Steer, kind: "available" };
39555
39752
  }
39556
39753
  for (; ; ) {
39557
39754
  const first = [...activeTurns.values()].find(
39558
39755
  (turn) => turn.command.sessionId === command.sessionId && turn.command.disposition !== SessionPromptDisposition.Steer
39559
39756
  );
39560
39757
  if (first === void 0 || first.command.commandId === command.commandId) {
39561
- return command.disposition !== SessionPromptDisposition.Queue || operations.isTerminalExecution(command.targetCommandId, command.sessionId) ? "available" : "queue-target-unavailable";
39758
+ return command.disposition !== SessionPromptDisposition.Queue || operations.isTerminalExecution(command.targetCommandId, command.sessionId) ? { disposition: queuedTurn.effectiveDisposition(), kind: "available" } : { kind: "queue-target-unavailable" };
39562
39759
  }
39563
39760
  if (command.disposition !== SessionPromptDisposition.Queue) {
39564
- return "busy";
39761
+ return { kind: "busy" };
39565
39762
  }
39566
39763
  if (first.command.commandId !== command.targetCommandId) {
39567
- return "queue-target-unavailable";
39764
+ return { kind: "queue-target-unavailable" };
39765
+ }
39766
+ const promotion = queuedTurn.queuePromotion();
39767
+ if (promotion === null) {
39768
+ throw new Error("The queued prompt cannot be promoted");
39769
+ }
39770
+ const decision = await Promise.race([
39771
+ waitForTurnCompletion(first, waitSignal).then(() => "target-completed"),
39772
+ promotion.then(() => "promoted")
39773
+ ]);
39774
+ if (decision === "promoted") {
39775
+ return { disposition: SessionPromptDisposition.Steer, kind: "available" };
39568
39776
  }
39569
- await waitForTurnCompletion(first, waitSignal);
39570
39777
  }
39571
39778
  };
39572
39779
  const connectionLiveness = new RelayConnectionLiveness(timer, {
@@ -39634,6 +39841,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
39634
39841
  directories,
39635
39842
  audit,
39636
39843
  sessions,
39844
+ activeTurnSnapshot,
39637
39845
  connectionController.signal
39638
39846
  );
39639
39847
  return;
@@ -39647,6 +39855,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
39647
39855
  directories,
39648
39856
  audit,
39649
39857
  sessions,
39858
+ activeTurnSnapshot,
39650
39859
  connectionController.signal
39651
39860
  );
39652
39861
  return;
@@ -39719,6 +39928,19 @@ async function runRelayConnection(config2, directories, audit, sessions, install
39719
39928
  });
39720
39929
  return;
39721
39930
  }
39931
+ if (kind === SESSION_PROMPT_DISPOSITION_KIND) {
39932
+ const disposition = message;
39933
+ const turn2 = activeTurns.get(disposition.commandId);
39934
+ if (turn2 === void 0 || !turn2.promoteQueuedPrompt(disposition)) {
39935
+ reportOperationFailure(
39936
+ socket,
39937
+ disposition.commandId,
39938
+ disposition.sessionId,
39939
+ new Error("The queued prompt is unavailable")
39940
+ );
39941
+ }
39942
+ return;
39943
+ }
39722
39944
  if (kind === WORKSPACE_LIST_KIND) {
39723
39945
  const command2 = message;
39724
39946
  void executeWorkspaceList(socket, command2, directories, audit, connectionController.signal);
@@ -39828,10 +40050,15 @@ async function runRelayConnection(config2, directories, audit, sessions, install
39828
40050
  sessions,
39829
40051
  receipt.attemptId,
39830
40052
  turn.accept,
39831
- (waitSignal) => waitForSessionAvailability(command, waitSignal),
40053
+ () => send(socket, {
40054
+ commandId: command.commandId,
40055
+ kind: SESSION_QUEUED_KIND,
40056
+ sessionId: command.sessionId
40057
+ }),
40058
+ (waitSignal) => waitForSessionAvailability(command, turn, waitSignal),
39832
40059
  timer,
39833
40060
  turn.signal,
39834
- turn.recordText,
40061
+ turn.recordEvent,
39835
40062
  turn.cancellationRequested
39836
40063
  ).catch((error62) => {
39837
40064
  console.error("Mobius daemon turn failed", error62);
@@ -39852,43 +40079,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
39852
40079
  socket.addEventListener("close", handleClose);
39853
40080
  socket.addEventListener("error", handleError);
39854
40081
  socket.addEventListener("message", handleMessage);
39855
- void reconcileActiveTurns(config2, reconnectingTurns, connectionController.signal).then(
39856
- () => {
39857
- if (finished) {
39858
- return;
39859
- }
39860
- publisher.connect(socket);
39861
- },
39862
- (error62) => {
39863
- if (finished) {
39864
- return;
39865
- }
39866
- console.error("Mobius daemon could not reconcile active Agent turns", error62);
39867
- if (error62 instanceof ActiveTurnReconciliationError && error62.terminal) {
39868
- diagnostics.reconciliationAbandoned(
39869
- connectionEpoch,
39870
- error62.relayErrorCode,
39871
- reconnectingTurns.length
39872
- );
39873
- console.error(
39874
- "Mobius daemon abandoned Agent turns the Relay already settled",
39875
- error62.relayErrorCode
39876
- );
39877
- for (const turn of reconnectingTurns) {
39878
- activeTurns.delete(turn.command.commandId);
39879
- turn.abortDaemon();
39880
- }
39881
- publisher.connect(socket);
39882
- return;
39883
- }
39884
- failAndClose(
39885
- new Error("Active Agent turn reconciliation failed", { cause: error62 }),
39886
- ACTIVE_TURN_RECONCILIATION_CLOSE_CODE,
39887
- "Active Agent turn reconciliation failed",
39888
- "reconciliation"
39889
- );
39890
- }
39891
- );
40082
+ publisher.connect(socket);
39892
40083
  if (signal.aborted) {
39893
40084
  stop();
39894
40085
  }
@@ -39920,7 +40111,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
39920
40111
  const activeTurns = /* @__PURE__ */ new Map();
39921
40112
  const recordSessionEvent = (sessionId, event) => {
39922
40113
  for (const turn of activeTurns.values()) {
39923
- turn.recordInteraction(event);
40114
+ turn.recordEvent(event);
39924
40115
  }
39925
40116
  publisher.publish(sessionId, event);
39926
40117
  };