@moxt-ai/mobius 0.0.169 → 0.0.172

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 (66) hide show
  1. package/dist/acp/agent-session.d.ts.map +1 -1
  2. package/dist/acp/agent-session.js +141 -42
  3. package/dist/acp/agent-session.js.map +1 -1
  4. package/dist/acp/codex/agent.d.ts.map +1 -1
  5. package/dist/acp/codex/agent.js +56 -31
  6. package/dist/acp/codex/agent.js.map +1 -1
  7. package/dist/acp/codex/items.d.ts +0 -9
  8. package/dist/acp/codex/items.d.ts.map +1 -1
  9. package/dist/acp/codex/items.js +0 -11
  10. package/dist/acp/codex/items.js.map +1 -1
  11. package/dist/acp/run-prompt.d.ts.map +1 -1
  12. package/dist/acp/run-prompt.js +7 -1
  13. package/dist/acp/run-prompt.js.map +1 -1
  14. package/dist/acp/session-contracts.d.ts +9 -4
  15. package/dist/acp/session-contracts.d.ts.map +1 -1
  16. package/dist/acp/session-contracts.js +1 -1
  17. package/dist/acp/session-contracts.js.map +1 -1
  18. package/dist/acp/session-history.d.ts +6 -3
  19. package/dist/acp/session-history.d.ts.map +1 -1
  20. package/dist/acp/session-history.js +41 -17
  21. package/dist/acp/session-history.js.map +1 -1
  22. package/dist/acp/session-interactions.d.ts +2 -0
  23. package/dist/acp/session-interactions.d.ts.map +1 -1
  24. package/dist/acp/session-interactions.js +36 -8
  25. package/dist/acp/session-interactions.js.map +1 -1
  26. package/dist/acp/session-store.d.ts +0 -13
  27. package/dist/acp/session-store.d.ts.map +1 -1
  28. package/dist/acp/session-store.js +3 -65
  29. package/dist/acp/session-store.js.map +1 -1
  30. package/dist/cli.js +350 -511
  31. package/dist/cli.js.map +4 -4
  32. package/dist/daemon-command-handler.d.ts.map +1 -1
  33. package/dist/daemon-command-handler.js +3 -8
  34. package/dist/daemon-command-handler.js.map +1 -1
  35. package/dist/daemon-history-commands.d.ts +3 -3
  36. package/dist/daemon-history-commands.d.ts.map +1 -1
  37. package/dist/daemon-history-commands.js +10 -66
  38. package/dist/daemon-history-commands.js.map +1 -1
  39. package/dist/daemon-observers.d.ts +3 -3
  40. package/dist/daemon-observers.d.ts.map +1 -1
  41. package/dist/daemon-observers.js +2 -18
  42. package/dist/daemon-observers.js.map +1 -1
  43. package/dist/daemon-prompt-executor.d.ts.map +1 -1
  44. package/dist/daemon-prompt-executor.js +3 -1
  45. package/dist/daemon-prompt-executor.js.map +1 -1
  46. package/dist/index.js +356 -511
  47. package/dist/index.js.map +4 -4
  48. package/dist/native-sessions/codex-history.js +3 -3
  49. package/dist/native-sessions/codex-history.js.map +1 -1
  50. package/dist/native-sessions/live-history-page.d.ts +0 -1
  51. package/dist/native-sessions/live-history-page.d.ts.map +1 -1
  52. package/dist/native-sessions/live-history-page.js +0 -14
  53. package/dist/native-sessions/live-history-page.js.map +1 -1
  54. package/dist/relay-connection/session-event-publisher.d.ts +1 -6
  55. package/dist/relay-connection/session-event-publisher.d.ts.map +1 -1
  56. package/dist/relay-connection/session-event-publisher.js +2 -7
  57. package/dist/relay-connection/session-event-publisher.js.map +1 -1
  58. package/dist/run-daemon.js +2 -2
  59. package/dist/run-daemon.js.map +1 -1
  60. package/dist/runtime.js +353 -514
  61. package/dist/runtime.js.map +4 -4
  62. package/dist/session-event-log-v2.d.ts +18 -9
  63. package/dist/session-event-log-v2.d.ts.map +1 -1
  64. package/dist/session-event-log-v2.js +39 -156
  65. package/dist/session-event-log-v2.js.map +1 -1
  66. package/package.json +1 -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.169",
3384
+ version: "0.0.172",
3385
3385
  description: "Mobius CLI for pairing and running local AI agent services.",
3386
3386
  type: "module",
3387
3387
  bin: {
@@ -25125,7 +25125,6 @@ var CodexAppServerClient = class {
25125
25125
  // src/acp/codex/items.ts
25126
25126
  var TOOL_OUTPUT_CHARACTER_LIMIT = 32768;
25127
25127
  var TITLE_CHARACTER_LIMIT = 500;
25128
- var CODEX_META_KEY = "codex";
25129
25128
  function truncate2(value, limit) {
25130
25129
  return value.length <= limit ? value : value.slice(0, limit);
25131
25130
  }
@@ -25264,12 +25263,6 @@ function reasoningText(item) {
25264
25263
  }
25265
25264
  return boundedParagraphs(item.summary.length > 0 ? item.summary : item.content, TOOL_OUTPUT_CHARACTER_LIMIT);
25266
25265
  }
25267
- function agentMessageMeta(phase) {
25268
- if (phase == null) {
25269
- return null;
25270
- }
25271
- return { [CODEX_META_KEY]: { phase } };
25272
- }
25273
25266
 
25274
25267
  // src/acp/codex/settings.ts
25275
25268
  var APPROVAL_TIMEOUT_MILLISECONDS = 36e5;
@@ -25714,8 +25707,8 @@ function promptInput(prompt) {
25714
25707
  function isCompactPrompt(prompt) {
25715
25708
  return prompt.length === 1 && prompt[0]?.type === "text" && prompt[0].text.trim() === "/compact";
25716
25709
  }
25717
- function steeringPromptInput(prompt) {
25718
- const input2 = [];
25710
+ function steeringPrompt(prompt) {
25711
+ const blocks = [];
25719
25712
  for (const block of prompt) {
25720
25713
  if (typeof block !== "object" || block === null) {
25721
25714
  throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
@@ -25726,7 +25719,7 @@ function steeringPromptInput(prompt) {
25726
25719
  if (typeof text2 !== "string") {
25727
25720
  throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
25728
25721
  }
25729
- input2.push({ text: text2, text_elements: [], type: "text" });
25722
+ blocks.push({ content: { text: text2, type: "text" }, input: { text: text2, text_elements: [], type: "text" } });
25730
25723
  continue;
25731
25724
  }
25732
25725
  if (type === "image") {
@@ -25735,7 +25728,10 @@ function steeringPromptInput(prompt) {
25735
25728
  if (typeof data !== "string" || typeof mimeType !== "string") {
25736
25729
  throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
25737
25730
  }
25738
- input2.push({ type: "image", url: `data:${mimeType};base64,${data}` });
25731
+ blocks.push({
25732
+ content: { data, mimeType, type: "image" },
25733
+ input: { type: "image", url: `data:${mimeType};base64,${data}` }
25734
+ });
25739
25735
  continue;
25740
25736
  }
25741
25737
  if (type === "resource") {
@@ -25743,24 +25739,40 @@ function steeringPromptInput(prompt) {
25743
25739
  if (typeof resource !== "object" || resource === null) {
25744
25740
  throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
25745
25741
  }
25742
+ const uri = Reflect.get(resource, "uri");
25746
25743
  const text2 = Reflect.get(resource, "text");
25747
- if (text2 !== void 0 && typeof text2 !== "string") {
25744
+ const blob2 = Reflect.get(resource, "blob");
25745
+ if (typeof uri !== "string" || typeof text2 !== "string" && typeof blob2 !== "string" || text2 !== void 0 && typeof text2 !== "string" || blob2 !== void 0 && typeof blob2 !== "string") {
25748
25746
  throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
25749
25747
  }
25750
- input2.push({ text: text2 ?? "", text_elements: [], type: "text" });
25748
+ blocks.push({
25749
+ content: typeof text2 === "string" ? { resource: { text: text2, uri }, type: "resource" } : { resource: { blob: blob2, uri }, type: "resource" },
25750
+ input: { text: text2 ?? "", text_elements: [], type: "text" }
25751
+ });
25751
25752
  continue;
25752
25753
  }
25753
25754
  if (type === "resource_link") {
25755
+ const name2 = Reflect.get(block, "name");
25754
25756
  const uri = Reflect.get(block, "uri");
25755
- if (typeof uri !== "string") {
25757
+ if (typeof name2 !== "string" || typeof uri !== "string") {
25756
25758
  throw new AcpExecutionError("Codex received an invalid steering prompt", {}, "invalid_request");
25757
25759
  }
25758
- input2.push({ text: `Resource: ${uri}`, text_elements: [], type: "text" });
25760
+ blocks.push({
25761
+ content: { name: name2, type: "resource_link", uri },
25762
+ input: { text: `Resource: ${uri}`, text_elements: [], type: "text" }
25763
+ });
25759
25764
  continue;
25760
25765
  }
25761
25766
  throw new AcpExecutionError("Codex received an unsupported steering prompt", {}, "invalid_request");
25762
25767
  }
25763
- return input2;
25768
+ return blocks;
25769
+ }
25770
+ function agentMessageUpdate(messageId, text2, phase) {
25771
+ return {
25772
+ content: { text: text2, type: "text" },
25773
+ messageId,
25774
+ sessionUpdate: phase === "commentary" ? "agent_thought_chunk" : "agent_message_chunk"
25775
+ };
25764
25776
  }
25765
25777
  function userInputSchema(questions) {
25766
25778
  const properties = {};
@@ -25900,6 +25912,14 @@ var CodexAcpAgent = class {
25900
25912
  if (isCompactPrompt(context.params.prompt)) {
25901
25913
  return await this.#compact(context.signal);
25902
25914
  }
25915
+ const messageId = crypto.randomUUID();
25916
+ for (const content of context.params.prompt) {
25917
+ await this.#emit({
25918
+ content,
25919
+ messageId,
25920
+ sessionUpdate: "user_message_chunk"
25921
+ });
25922
+ }
25903
25923
  return await this.#runTurn(promptInput(context.params.prompt), context.signal);
25904
25924
  }).onRequest(
25905
25925
  "_session/steering",
@@ -25987,12 +26007,7 @@ var CodexAcpAgent = class {
25987
26007
  continue;
25988
26008
  }
25989
26009
  if (item.type === "agentMessage") {
25990
- await this.#emit({
25991
- _meta: agentMessageMeta(item.phase),
25992
- content: { text: item.text, type: "text" },
25993
- messageId: item.id,
25994
- sessionUpdate: "agent_message_chunk"
25995
- });
26010
+ await this.#emit(agentMessageUpdate(item.id, item.text, item.phase));
25996
26011
  continue;
25997
26012
  }
25998
26013
  const update = toolCallUpdate(item, "snapshot");
@@ -26129,12 +26144,7 @@ var CodexAcpAgent = class {
26129
26144
  const phase = this.#agentMessages.get(decoded.data.itemId)?.phase;
26130
26145
  this.#agentMessages.set(decoded.data.itemId, { phase, kind: "streaming" });
26131
26146
  await this.#enqueue(async () => {
26132
- await this.#emit({
26133
- _meta: agentMessageMeta(phase),
26134
- content: { text: decoded.data.delta, type: "text" },
26135
- messageId: decoded.data.itemId,
26136
- sessionUpdate: "agent_message_chunk"
26137
- });
26147
+ await this.#emit(agentMessageUpdate(decoded.data.itemId, decoded.data.delta, phase));
26138
26148
  });
26139
26149
  }
26140
26150
  return;
@@ -26157,12 +26167,7 @@ var CodexAcpAgent = class {
26157
26167
  return;
26158
26168
  }
26159
26169
  await this.#enqueue(async () => {
26160
- await this.#emit({
26161
- _meta: agentMessageMeta(item.phase),
26162
- content: { text: item.text, type: "text" },
26163
- messageId: item.id,
26164
- sessionUpdate: "agent_message_chunk"
26165
- });
26170
+ await this.#emit(agentMessageUpdate(item.id, item.text, item.phase));
26166
26171
  });
26167
26172
  return;
26168
26173
  }
@@ -26396,14 +26401,22 @@ var CodexAcpAgent = class {
26396
26401
  if (sessionId !== this.#nativeSessionId || active === null || active.turn.id.length === 0) {
26397
26402
  return { outcome: "promptRequired", reason: "noRunningTurn" };
26398
26403
  }
26399
- const input2 = steeringPromptInput(prompt);
26400
- if (input2.length === 0) {
26404
+ const steering = steeringPrompt(prompt);
26405
+ if (steering.length === 0) {
26401
26406
  throw new AcpExecutionError("Codex received an empty steering request", {}, "invalid_request");
26402
26407
  }
26408
+ const messageId = crypto.randomUUID();
26409
+ for (const block of steering) {
26410
+ await this.#emit({ content: block.content, messageId, sessionUpdate: "user_message_chunk" });
26411
+ }
26403
26412
  const response = turnSteerResponseSchema.parse(
26404
26413
  await this.#appServer.request(
26405
26414
  "turn/steer",
26406
- { expectedTurnId: active.turn.id, input: input2, threadId: this.#nativeSessionId },
26415
+ {
26416
+ expectedTurnId: active.turn.id,
26417
+ input: steering.map((block) => block.input),
26418
+ threadId: this.#nativeSessionId
26419
+ },
26407
26420
  AbortSignal.any([signal, AbortSignal.timeout(APPROVAL_TIMEOUT_MILLISECONDS2)])
26408
26421
  )
26409
26422
  );
@@ -30108,10 +30121,7 @@ var lifecycleMetadataV2Schema = external_exports.discriminatedUnion("kind", [
30108
30121
  external_exports.object({ kind: external_exports.literal("session.queue.changed") }).readonly(),
30109
30122
  external_exports.object({ event: sessionPermissionRequestedEventSchema, kind: external_exports.literal("session.permission.requested") }).readonly(),
30110
30123
  external_exports.object({ event: sessionPermissionResolvedEventSchema, kind: external_exports.literal("session.permission.resolved") }).readonly(),
30111
- external_exports.object({
30112
- event: sessionElicitationRequestedEventSchema,
30113
- kind: external_exports.literal("session.elicitation.requested")
30114
- }).readonly(),
30124
+ external_exports.object({ event: sessionElicitationRequestedEventSchema, kind: external_exports.literal("session.elicitation.requested") }).readonly(),
30115
30125
  external_exports.object({ event: sessionElicitationResolvedEventSchema, kind: external_exports.literal("session.elicitation.resolved") }).readonly(),
30116
30126
  external_exports.object({
30117
30127
  ...lifecycleBase,
@@ -30213,6 +30223,7 @@ var mobiusSessionExportV2Schema = external_exports.object({
30213
30223
  }).readonly();
30214
30224
  var sessionEventEnvelopeV2Schema = external_exports.object({ event: sessionEventV2Schema, kind: external_exports.literal(SESSION_EVENT_V2_KIND) }).readonly();
30215
30225
  var sessionEventLogPageV2Schema = external_exports.object({
30226
+ daemonGenerationId: identifierStringSchema,
30216
30227
  events: external_exports.array(sessionEventV2Schema).max(MAX_EVENT_COUNT).readonly(),
30217
30228
  nextCursor: external_exports.string().min(1).max(512).nullable(),
30218
30229
  tailCursor: external_exports.string().max(512),
@@ -30220,17 +30231,13 @@ var sessionEventLogPageV2Schema = external_exports.object({
30220
30231
  version: external_exports.literal(2)
30221
30232
  }).readonly();
30222
30233
  var nativeEventPageRequestV2Schema = external_exports.object({ cursor: external_exports.string().min(1).max(512).nullable(), eventLimit: external_exports.number().int().min(1).max(1e4) }).readonly();
30223
- var executingPromptRequestEventLogV2Schema = external_exports.object({
30224
- attemptId: identifierStringSchema,
30234
+ var queuedPromptRequestEventLogV2Schema = external_exports.object({
30225
30235
  commandId: identifierStringSchema,
30226
- epoch: identifierStringSchema,
30227
- events: external_exports.array(sessionEventV2Schema).max(MAX_EVENT_COUNT).readonly(),
30228
- tailCursor: external_exports.string().max(512),
30229
- truncated: external_exports.boolean()
30236
+ content: external_exports.array(contentBlockV2Schema).min(1).max(100).readonly()
30230
30237
  }).readonly();
30231
30238
  var nativeSessionEventsV2Schema = external_exports.object({
30232
- executingPromptRequest: executingPromptRequestEventLogV2Schema.nullable(),
30233
- history: sessionEventLogPageV2Schema
30239
+ events: sessionEventLogPageV2Schema,
30240
+ queuedPromptRequests: external_exports.array(queuedPromptRequestEventLogV2Schema).max(MAX_COLLECTION_SIZE).readonly()
30234
30241
  }).readonly();
30235
30242
  function inputValue(value) {
30236
30243
  if (typeof value !== "string") {
@@ -30254,7 +30261,6 @@ function decode5(value, schema) {
30254
30261
  function encode4(value, schema) {
30255
30262
  return JSON.stringify(decode5(value, schema));
30256
30263
  }
30257
- var decodeSessionEventV2 = (value) => decode5(value, sessionEventV2Schema);
30258
30264
  var decodeSessionEventEnvelopeV2 = (value) => decode5(value, sessionEventEnvelopeV2Schema);
30259
30265
  var encodeSessionEventEnvelopeV2 = (value) => encode4(value, sessionEventEnvelopeV2Schema);
30260
30266
  var decodeAcpSessionUpdateV2 = (value) => decode5(value, acpSessionUpdateV2Schema);
@@ -30348,28 +30354,11 @@ function decodeRecordedSessionEvent(encoded) {
30348
30354
  var encodeRecordedSessionEvent = (event) => JSON.stringify(decodeRecordedSessionEvent(JSON.stringify(event)));
30349
30355
 
30350
30356
  // ../protocol/src/session-live-history.ts
30351
- var SESSION_LIVE_HISTORY_LOAD_KIND = "session.live-history.load";
30352
- var SESSION_LIVE_HISTORY_LOADED_KIND = "session.live-history.loaded";
30353
30357
  var SESSION_LIVE_HISTORY_PAGE_LOAD_KIND = "session.live-history.page.load";
30354
30358
  var SESSION_LIVE_HISTORY_PAGE_LOADED_KIND = "session.live-history.page.loaded";
30355
30359
  var SESSION_LIVE_HISTORY_V2_PAGE_LOAD_KIND = "session.live-history.v2.page.load";
30356
30360
  var SESSION_LIVE_HISTORY_V2_PAGE_LOADED_KIND = "session.live-history.v2.page.loaded";
30357
30361
  var directoryIdentifier = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,2047}$/);
30358
- var sessionLiveHistoryLoadSchema = external_exports.object({
30359
- additionalDirectoryIds: external_exports.array(directoryIdentifier).max(16).readonly(),
30360
- agentId: identifierStringSchema,
30361
- bindingId: identifierStringSchema,
30362
- directoryId: directoryIdentifier,
30363
- kind: external_exports.literal(SESSION_LIVE_HISTORY_LOAD_KIND),
30364
- requestId: identifierStringSchema,
30365
- sessionId: identifierStringSchema
30366
- }).readonly();
30367
- var sessionLiveHistoryLoadedSchema = external_exports.object({
30368
- history: sessionHistorySchema,
30369
- kind: external_exports.literal(SESSION_LIVE_HISTORY_LOADED_KIND),
30370
- requestId: identifierStringSchema,
30371
- sessionId: identifierStringSchema
30372
- }).readonly();
30373
30362
  var sessionLiveHistoryPageLoadSchema = external_exports.object({
30374
30363
  additionalDirectoryIds: external_exports.array(directoryIdentifier).max(16).readonly(),
30375
30364
  agentId: identifierStringSchema,
@@ -30412,10 +30401,6 @@ function decode7(schema, encoded) {
30412
30401
  throw new ProtocolMessageError("Invalid live Session history message", { cause });
30413
30402
  }
30414
30403
  }
30415
- var decodeSessionLiveHistoryLoad = (encoded) => decode7(sessionLiveHistoryLoadSchema, encoded);
30416
- var decodeSessionLiveHistoryLoaded = (encoded) => decode7(sessionLiveHistoryLoadedSchema, encoded);
30417
- var encodeSessionLiveHistoryLoad = (value) => JSON.stringify(sessionLiveHistoryLoadSchema.parse(value));
30418
- var encodeSessionLiveHistoryLoaded = (value) => JSON.stringify(sessionLiveHistoryLoadedSchema.parse(value));
30419
30404
  var decodeSessionLiveHistoryPageLoad = (encoded) => decode7(sessionLiveHistoryPageLoadSchema, encoded);
30420
30405
  var decodeSessionLiveHistoryPageLoaded = (encoded) => decode7(sessionLiveHistoryPageLoadedSchema, encoded);
30421
30406
  var encodeSessionLiveHistoryPageLoad = (value) => JSON.stringify(sessionLiveHistoryPageLoadSchema.parse(value));
@@ -30498,11 +30483,6 @@ var serviceToDaemonSignatures = {
30498
30483
  encodeSessionElicitationRespondCommand,
30499
30484
  decodeSessionElicitationRespondCommand
30500
30485
  ),
30501
- [SESSION_LIVE_HISTORY_LOAD_KIND]: defineMessageSignature(
30502
- SESSION_LIVE_HISTORY_LOAD_KIND,
30503
- encodeSessionLiveHistoryLoad,
30504
- decodeSessionLiveHistoryLoad
30505
- ),
30506
30486
  [SESSION_LIVE_HISTORY_PAGE_LOAD_KIND]: defineMessageSignature(
30507
30487
  SESSION_LIVE_HISTORY_PAGE_LOAD_KIND,
30508
30488
  encodeSessionLiveHistoryPageLoad,
@@ -30643,11 +30623,6 @@ var daemonToServiceSignatures = {
30643
30623
  encodeSessionOperationFailedEvent,
30644
30624
  decodeSessionOperationFailedEvent
30645
30625
  ),
30646
- [SESSION_LIVE_HISTORY_LOADED_KIND]: defineMessageSignature(
30647
- SESSION_LIVE_HISTORY_LOADED_KIND,
30648
- encodeSessionLiveHistoryLoaded,
30649
- decodeSessionLiveHistoryLoaded
30650
- ),
30651
30626
  [SESSION_LIVE_HISTORY_PAGE_LOADED_KIND]: defineMessageSignature(
30652
30627
  SESSION_LIVE_HISTORY_PAGE_LOADED_KIND,
30653
30628
  encodeSessionLiveHistoryPageLoaded,
@@ -31576,7 +31551,7 @@ var AuditStore = class {
31576
31551
  };
31577
31552
 
31578
31553
  // src/run-daemon.ts
31579
- import { createHash as createHash8, randomUUID as randomUUID8 } from "node:crypto";
31554
+ import { createHash as createHash8, randomUUID as randomUUID9 } from "node:crypto";
31580
31555
  import { join as join19 } from "node:path";
31581
31556
  import { styleText } from "node:util";
31582
31557
 
@@ -33125,7 +33100,7 @@ function sessionConfigProtocolForAgent(_agentId) {
33125
33100
 
33126
33101
  // src/acp/session-contracts.ts
33127
33102
  var NullAcpSessionObserver = class {
33128
- onAcpUpdate = (_sessionId, _update) => Promise.resolve();
33103
+ onSessionEventV2 = (_sessionId, _event, _position) => Promise.resolve();
33129
33104
  onCommands = () => Promise.resolve();
33130
33105
  onConfig = () => Promise.resolve();
33131
33106
  onContent = () => Promise.resolve();
@@ -33193,7 +33168,8 @@ function historyContentCharacters(messages) {
33193
33168
  var AcpHistoryReplay = class {
33194
33169
  #activities = /* @__PURE__ */ new Map();
33195
33170
  #messages = [];
33196
- #updates = [];
33171
+ #events = [];
33172
+ #records = [];
33197
33173
  #turnActivityIds = /* @__PURE__ */ new Set();
33198
33174
  #activityTracker = new AcpActivityTracker(
33199
33175
  async (activity2) => {
@@ -33215,8 +33191,10 @@ var AcpHistoryReplay = class {
33215
33191
  #firstMessageIndex = 0;
33216
33192
  #characters = 0;
33217
33193
  #truncated = false;
33218
- record = async (update, rawUpdate) => {
33219
- this.#updates.push(rawUpdate);
33194
+ record = async (update, rawUpdate, onRecorded = () => Promise.resolve()) => {
33195
+ this.#records.push({ kind: "acp", rawUpdate, update });
33196
+ this.#events.push({ payload: rawUpdate, type: "acp" });
33197
+ await onRecorded(this.#events.length);
33220
33198
  if (update.sessionUpdate === "agent_thought_chunk") {
33221
33199
  if (update.content.type === "text") {
33222
33200
  await this.#activityTracker.recordNarrative(
@@ -33225,30 +33203,30 @@ var AcpHistoryReplay = class {
33225
33203
  update.content.text
33226
33204
  );
33227
33205
  }
33228
- return;
33206
+ return this.#events.length;
33229
33207
  }
33230
33208
  if (update.sessionUpdate === "tool_call") {
33231
33209
  await this.#activityTracker.recordToolCall(update);
33232
- return;
33210
+ return this.#events.length;
33233
33211
  }
33234
33212
  if (update.sessionUpdate === "tool_call_update") {
33235
33213
  await this.#activityTracker.recordToolCallUpdate(update);
33236
- return;
33214
+ return this.#events.length;
33237
33215
  }
33238
33216
  if (update.sessionUpdate === "plan") {
33239
33217
  await this.#activityTracker.recordPlan(update);
33240
- return;
33218
+ return this.#events.length;
33241
33219
  }
33242
33220
  if (update.sessionUpdate === "plan_update") {
33243
33221
  await this.#activityTracker.recordPlanUpdate(update);
33244
- return;
33222
+ return this.#events.length;
33245
33223
  }
33246
33224
  if (update.sessionUpdate === "plan_removed") {
33247
33225
  await this.#activityTracker.removePlan(update);
33248
- return;
33226
+ return this.#events.length;
33249
33227
  }
33250
33228
  if (update.sessionUpdate !== "user_message_chunk" && update.sessionUpdate !== "agent_message_chunk") {
33251
- return;
33229
+ return this.#events.length;
33252
33230
  }
33253
33231
  if (update.sessionUpdate === "agent_message_chunk" && isProgressMessage(update)) {
33254
33232
  if (update.content.type === "text") {
@@ -33258,18 +33236,18 @@ var AcpHistoryReplay = class {
33258
33236
  update.content.text
33259
33237
  );
33260
33238
  }
33261
- return;
33239
+ return this.#events.length;
33262
33240
  }
33263
33241
  const role = update.sessionUpdate === "user_message_chunk" ? "user" : "assistant";
33264
33242
  const content = update.content;
33265
33243
  if (role === "assistant" && content.type !== "text") {
33266
33244
  await this.#activityTracker.finishNarrative();
33267
33245
  this.recordAssistantContent(update.messageId ?? null, normalizeContentBlock(content));
33268
- return;
33246
+ return this.#events.length;
33269
33247
  }
33270
33248
  const text2 = content.type === "text" ? content.text : content.type === "image" ? content.data.length > 0 ? `[@image](data:${content.mimeType};base64,${content.data})` : content.uri != null && content.uri.length > 0 ? `[@image](${content.uri})` : "[image attachment]" : `[${content.type} attachment]`;
33271
33249
  if (text2.length === 0) {
33272
- return;
33250
+ return this.#events.length;
33273
33251
  }
33274
33252
  const previous = this.#messages.at(-1);
33275
33253
  const id = update.messageId ?? null;
@@ -33296,10 +33274,30 @@ var AcpHistoryReplay = class {
33296
33274
  this.#characters += bounded2.length;
33297
33275
  this.#lastMessageId = id;
33298
33276
  this.trimMessages();
33277
+ return this.#events.length;
33278
+ };
33279
+ recordLifecycle = (event) => {
33280
+ if (event.type !== "lifecycle-metadata") {
33281
+ throw new Error("Lifecycle history only accepts lifecycle metadata");
33282
+ }
33283
+ this.#records.push({ event, kind: "lifecycle" });
33284
+ this.#events.push(event);
33285
+ return this.#events.length;
33286
+ };
33287
+ eventCount = () => this.#events.length;
33288
+ append = async (replay) => {
33289
+ for (const record2 of replay.#records) {
33290
+ if (record2.kind === "acp") {
33291
+ await this.record(record2.update, record2.rawUpdate);
33292
+ } else {
33293
+ this.recordLifecycle(record2.event);
33294
+ }
33295
+ }
33299
33296
  };
33300
- eventPage = (eventLimit, cursor) => {
33301
- const parsedCursor = cursor === null ? this.#updates.length : Number(cursor);
33302
- if (!Number.isSafeInteger(parsedCursor) || parsedCursor < 0 || parsedCursor > this.#updates.length) {
33297
+ eventPage = (eventLimit, cursor, appended = null) => {
33298
+ const events = appended === null ? this.#events : [...this.#events, ...appended.#events];
33299
+ const parsedCursor = cursor === null ? events.length : Number(cursor);
33300
+ if (!Number.isSafeInteger(parsedCursor) || parsedCursor < 0 || parsedCursor > events.length) {
33303
33301
  throw new Error("The native event cursor is invalid");
33304
33302
  }
33305
33303
  const endUpdate = parsedCursor;
@@ -33308,7 +33306,7 @@ var AcpHistoryReplay = class {
33308
33306
  nextCursor: startUpdate === 0 ? null : startUpdate.toString(),
33309
33307
  startPosition: startUpdate + 1,
33310
33308
  truncated: startUpdate > 0,
33311
- updates: this.#updates.slice(startUpdate, endUpdate)
33309
+ events: events.slice(startUpdate, endUpdate)
33312
33310
  };
33313
33311
  };
33314
33312
  snapshot = async () => {
@@ -33695,6 +33693,34 @@ var AcpSessionInteractions = class {
33695
33693
  constructor(context) {
33696
33694
  this.#context = context;
33697
33695
  }
33696
+ #notifyPermissionRequested = async (event) => {
33697
+ await this.#context.recordSessionEventV2({
33698
+ payload: { event, kind: "session.permission.requested" },
33699
+ type: "lifecycle-metadata"
33700
+ });
33701
+ await this.#context.observer().onPermission(event);
33702
+ };
33703
+ #notifyPermissionResolved = async (event) => {
33704
+ await this.#context.recordSessionEventV2({
33705
+ payload: { event, kind: "session.permission.resolved" },
33706
+ type: "lifecycle-metadata"
33707
+ });
33708
+ await this.#context.observer().onPermissionResolved(event);
33709
+ };
33710
+ #notifyElicitationRequested = async (event) => {
33711
+ await this.#context.recordSessionEventV2({
33712
+ payload: { event, kind: "session.elicitation.requested" },
33713
+ type: "lifecycle-metadata"
33714
+ });
33715
+ await this.#context.observer().onElicitation(event);
33716
+ };
33717
+ #notifyElicitationResolved = async (event) => {
33718
+ await this.#context.recordSessionEventV2({
33719
+ payload: { event, kind: "session.elicitation.resolved" },
33720
+ type: "lifecycle-metadata"
33721
+ });
33722
+ await this.#context.observer().onElicitationResolved(event);
33723
+ };
33698
33724
  respondPermission = async (options) => {
33699
33725
  const pending = this.#pendingPermissions.get(options.interactionId);
33700
33726
  if (pending === void 0) {
@@ -33720,7 +33746,7 @@ var AcpSessionInteractions = class {
33720
33746
  );
33721
33747
  }
33722
33748
  this.#pendingPermissions.delete(options.interactionId);
33723
- await this.#context.observer().onPermissionResolved({
33749
+ await this.#notifyPermissionResolved({
33724
33750
  interactionId: options.interactionId,
33725
33751
  kind: SESSION_PERMISSION_RESOLVED_KIND,
33726
33752
  optionId: options.outcome === "selected" ? options.optionId : "",
@@ -33760,7 +33786,7 @@ var AcpSessionInteractions = class {
33760
33786
  );
33761
33787
  }
33762
33788
  this.#pendingElicitations.delete(options.interactionId);
33763
- await this.#context.observer().onElicitationResolved({
33789
+ await this.#notifyElicitationResolved({
33764
33790
  action: options.action,
33765
33791
  interactionId: options.interactionId,
33766
33792
  kind: SESSION_ELICITATION_RESOLVED_KIND,
@@ -33789,7 +33815,7 @@ var AcpSessionInteractions = class {
33789
33815
  };
33790
33816
  signal.addEventListener("abort", abort, { once: true });
33791
33817
  try {
33792
- await this.#context.observer().onPermission({
33818
+ await this.#notifyPermissionRequested({
33793
33819
  commandId: this.#context.commandId(),
33794
33820
  interactionId,
33795
33821
  kind: SESSION_PERMISSION_REQUESTED_KIND,
@@ -33834,7 +33860,7 @@ var AcpSessionInteractions = class {
33834
33860
  };
33835
33861
  signal.addEventListener("abort", abort, { once: true });
33836
33862
  try {
33837
- await this.#context.observer().onElicitation({
33863
+ await this.#notifyElicitationRequested({
33838
33864
  accepted: false,
33839
33865
  commandId: this.#context.commandId(),
33840
33866
  elicitationId,
@@ -33858,7 +33884,7 @@ var AcpSessionInteractions = class {
33858
33884
  return;
33859
33885
  }
33860
33886
  this.#acceptedUrlElicitations.delete(notification.elicitationId);
33861
- await this.#context.observer().onElicitationResolved({
33887
+ await this.#notifyElicitationResolved({
33862
33888
  action: "complete",
33863
33889
  interactionId,
33864
33890
  kind: SESSION_ELICITATION_RESOLVED_KIND,
@@ -33871,7 +33897,7 @@ var AcpSessionInteractions = class {
33871
33897
  return;
33872
33898
  }
33873
33899
  this.#pendingPermissions.delete(interactionId);
33874
- await this.#context.observer().onPermissionResolved({
33900
+ await this.#notifyPermissionResolved({
33875
33901
  interactionId,
33876
33902
  kind: SESSION_PERMISSION_RESOLVED_KIND,
33877
33903
  optionId: "",
@@ -33885,7 +33911,7 @@ var AcpSessionInteractions = class {
33885
33911
  return;
33886
33912
  }
33887
33913
  this.#pendingElicitations.delete(interactionId);
33888
- await this.#context.observer().onElicitationResolved({
33914
+ await this.#notifyElicitationResolved({
33889
33915
  action: "cancel",
33890
33916
  interactionId,
33891
33917
  kind: SESSION_ELICITATION_RESOLVED_KIND,
@@ -33904,7 +33930,7 @@ var AcpSessionInteractions = class {
33904
33930
  await this.cancelElicitation(interactionId);
33905
33931
  }
33906
33932
  for (const interactionId of acceptedElicitationIds) {
33907
- await this.#context.observer().onElicitationResolved({
33933
+ await this.#notifyElicitationResolved({
33908
33934
  action: "cancel",
33909
33935
  interactionId,
33910
33936
  kind: SESSION_ELICITATION_RESOLVED_KIND,
@@ -38839,21 +38865,9 @@ var DeletedAcpStoredSession = class extends AcpStoredSessionLookup {
38839
38865
  var MemoryAcpSessionStore = class {
38840
38866
  #sessions = /* @__PURE__ */ new Map();
38841
38867
  #deleted = /* @__PURE__ */ new Set();
38842
- #eventsV2 = /* @__PURE__ */ new Map();
38843
- appendExecutingPromptEventV2 = (event) => {
38844
- const events = this.#eventsV2.get(event.sessionId);
38845
- if (events === void 0) {
38846
- throw new Error("The executing prompt event log has not started");
38847
- }
38848
- events.push(event);
38849
- };
38850
- clearExecutingPromptEventsV2 = (sessionId) => {
38851
- this.#eventsV2.delete(sessionId);
38852
- };
38853
38868
  close = () => {
38854
38869
  this.#sessions.clear();
38855
38870
  this.#deleted.clear();
38856
- this.#eventsV2.clear();
38857
38871
  };
38858
38872
  findNative = (agentId, nativeSessionId) => [...this.#sessions.values()].filter(
38859
38873
  (session) => session.agentId === agentId && session.nativeSessionId === nativeSessionId
@@ -38864,7 +38878,6 @@ var MemoryAcpSessionStore = class {
38864
38878
  for (const id of ids) {
38865
38879
  this.#sessions.delete(id);
38866
38880
  this.#deleted.add(id);
38867
- this.#eventsV2.delete(id);
38868
38881
  }
38869
38882
  return ids;
38870
38883
  };
@@ -38877,13 +38890,6 @@ var MemoryAcpSessionStore = class {
38877
38890
  };
38878
38891
  remove = (sessionId) => {
38879
38892
  this.#sessions.delete(sessionId);
38880
- this.#eventsV2.delete(sessionId);
38881
- };
38882
- readExecutingPromptEventsV2 = (sessionId) => [
38883
- ...this.#eventsV2.get(sessionId) ?? []
38884
- ];
38885
- startExecutingPromptEventsV2 = (sessionId, events) => {
38886
- this.#eventsV2.set(sessionId, [...events]);
38887
38893
  };
38888
38894
  write = (session) => {
38889
38895
  this.#sessions.set(session.sessionId, session);
@@ -38962,30 +38968,6 @@ var SqliteAcpSessionStore = class {
38962
38968
  close = () => {
38963
38969
  this.#sqliteDatabase.close();
38964
38970
  };
38965
- appendExecutingPromptEventV2 = (event) => {
38966
- this.#database.insert(sessionEventV2).values({
38967
- eventId: event.eventId,
38968
- eventJson: JSON.stringify(event),
38969
- position: Number(event.position),
38970
- sessionId: event.sessionId
38971
- }).run();
38972
- };
38973
- clearExecutingPromptEventsV2 = (sessionId) => {
38974
- this.#database.delete(sessionEventV2).where(eq(sessionEventV2.sessionId, sessionId)).run();
38975
- };
38976
- startExecutingPromptEventsV2 = (sessionId, events) => {
38977
- this.#transaction(() => {
38978
- this.#database.delete(sessionEventV2).where(eq(sessionEventV2.sessionId, sessionId)).run();
38979
- for (const event of events) {
38980
- this.#database.insert(sessionEventV2).values({
38981
- eventId: event.eventId,
38982
- eventJson: JSON.stringify(event),
38983
- position: Number(event.position),
38984
- sessionId: event.sessionId
38985
- }).run();
38986
- }
38987
- });
38988
- };
38989
38971
  findNative = (agentId, nativeSessionId) => this.#database.select().from(acpSession).where(and(eq(acpSession.agentId, agentId), eq(acpSession.nativeSessionId, nativeSessionId))).all().map(decodeStoredSession);
38990
38972
  list = () => this.#database.select().from(acpSession).orderBy(desc(acpSession.updatedAt)).all().map(decodeStoredSession);
38991
38973
  markDeleted = (agentId, nativeSessionId) => {
@@ -38994,7 +38976,6 @@ var SqliteAcpSessionStore = class {
38994
38976
  this.#database.delete(acpSession).where(and(eq(acpSession.agentId, agentId), eq(acpSession.nativeSessionId, nativeSessionId))).run();
38995
38977
  for (const id of ids) {
38996
38978
  this.#database.insert(deletedAcpSession).values({ sessionId: id }).onConflictDoNothing().run();
38997
- this.#database.delete(sessionEventV2).where(eq(sessionEventV2.sessionId, id)).run();
38998
38979
  }
38999
38980
  });
39000
38981
  return ids;
@@ -39008,12 +38989,8 @@ var SqliteAcpSessionStore = class {
39008
38989
  const row = this.#database.select().from(acpSession).where(eq(acpSession.sessionId, sessionId)).get();
39009
38990
  return row === void 0 ? new MissingAcpStoredSession() : new FoundAcpStoredSession(decodeStoredSession(row));
39010
38991
  };
39011
- readExecutingPromptEventsV2 = (sessionId) => this.#database.select({ eventJson: sessionEventV2.eventJson }).from(sessionEventV2).where(eq(sessionEventV2.sessionId, sessionId)).orderBy(asc(sessionEventV2.position)).all().map((row) => decodeSessionEventV2(row.eventJson));
39012
38992
  remove = (sessionId) => {
39013
- this.#transaction(() => {
39014
- this.#database.delete(acpSession).where(eq(acpSession.sessionId, sessionId)).run();
39015
- this.#database.delete(sessionEventV2).where(eq(sessionEventV2.sessionId, sessionId)).run();
39016
- });
38993
+ this.#database.delete(acpSession).where(eq(acpSession.sessionId, sessionId)).run();
39017
38994
  };
39018
38995
  write = (session) => {
39019
38996
  const value = {
@@ -39083,6 +39060,7 @@ var AgentSession = class _AgentSession {
39083
39060
  #sessionTitle = null;
39084
39061
  #sessionUpdatedAt = "";
39085
39062
  #turn = new IdleAcpTurn();
39063
+ #turnHistory = null;
39086
39064
  constructor(agent, cwd, additionalDirectories, mobiusSessionId, getObserver, store, metrics, contentExternalizer) {
39087
39065
  this.#updates = new AgentUpdateStream((notification) => this.#processUpdate(notification));
39088
39066
  this.#additionalDirectories = [...additionalDirectories];
@@ -39100,7 +39078,8 @@ var AgentSession = class _AgentSession {
39100
39078
  sessionId: () => this.#mobiusSessionId,
39101
39079
  commandId: () => this.#turn.commandId,
39102
39080
  assertNativeSession: (sessionId) => this.assertNativeSession(sessionId),
39103
- observer: getObserver
39081
+ observer: getObserver,
39082
+ recordSessionEventV2: this.#recordLifecycleEventV2
39104
39083
  });
39105
39084
  this.#connection = new AgentConnection(agent, cwd, this);
39106
39085
  this.#contentExternalizer = contentExternalizer;
@@ -39196,13 +39175,10 @@ var AgentSession = class _AgentSession {
39196
39175
  }
39197
39176
  };
39198
39177
  }
39199
- const loaded = await this.#loadSession(signal, "ACP agent exited while loading history");
39200
- return await embedLocalHistoryImages(await loaded.history.snapshot(), signal);
39178
+ const history = await this.#completedHistory(signal, "ACP agent exited while loading history");
39179
+ return await embedLocalHistoryImages(await history.snapshot(), signal);
39201
39180
  };
39202
39181
  loadHistoryEventsV2 = async (eventLimit, cursor, signal) => {
39203
- if (!this.#prompted && this.#nativeHistoryOwnership.kind === "fresh-session") {
39204
- return new AcpHistoryReplay().eventPage(eventLimit, cursor);
39205
- }
39206
39182
  if (!this.#capabilities.loadSession) {
39207
39183
  throw new AcpExecutionError(
39208
39184
  "This Agent restores context but does not provide message history.",
@@ -39210,9 +39186,20 @@ var AgentSession = class _AgentSession {
39210
39186
  "native_history_unsupported"
39211
39187
  );
39212
39188
  }
39213
- const loaded = await this.#loadSession(signal, "ACP agent exited while loading history");
39214
- return loaded.history.eventPage(eventLimit, cursor);
39189
+ const history = await this.#completedHistory(signal, "ACP agent exited while loading history");
39190
+ return history.eventPage(eventLimit, cursor, this.#turnHistory);
39215
39191
  };
39192
+ async #completedHistory(signal, exitMessage) {
39193
+ if (!this.#prompted && this.#nativeHistoryOwnership.kind === "fresh-session") {
39194
+ if (this.#sessionLoad.kind === "not-requested") {
39195
+ this.#sessionLoad = { history: new AcpHistoryReplay(), kind: "loaded", response: {} };
39196
+ }
39197
+ if (this.#sessionLoad.kind === "loaded") {
39198
+ return this.#sessionLoad.history;
39199
+ }
39200
+ }
39201
+ return (await this.#loadSession(signal, exitMessage)).history;
39202
+ }
39216
39203
  async #loadSession(signal, exitMessage) {
39217
39204
  if (this.#sessionLoad.kind === "loaded") {
39218
39205
  return this.#sessionLoad;
@@ -39696,19 +39683,7 @@ var AgentSession = class _AgentSession {
39696
39683
  if (this.#turn.running) {
39697
39684
  throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
39698
39685
  }
39699
- switch (this.#sessionLoad.kind) {
39700
- case "not-requested":
39701
- break;
39702
- case "loaded":
39703
- this.#sessionLoad = { kind: "not-requested" };
39704
- break;
39705
- case "capturing":
39706
- throw new AcpExecutionError("Session history is still loading", {}, "session_busy");
39707
- default: {
39708
- const unexpected = this.#sessionLoad;
39709
- throw new Error(`Unexpected Session load state: ${JSON.stringify(unexpected)}`);
39710
- }
39711
- }
39686
+ const completedHistory = this.#capabilities.loadSession ? await this.#completedHistory(options.signal, "ACP agent exited while loading history before a prompt") : null;
39712
39687
  const prompt = this.buildPrompt(options);
39713
39688
  if (this.#sessionTitle === null || this.#sessionTitle.length === 0) {
39714
39689
  this.#sessionTitle = truncate(options.prompt, 500);
@@ -39735,6 +39710,23 @@ var AgentSession = class _AgentSession {
39735
39710
  this.prepareAgentContent
39736
39711
  );
39737
39712
  this.#turn = running;
39713
+ this.#turnHistory = completedHistory === null ? null : new AcpHistoryReplay();
39714
+ const lifecycleV2 = options.lifecycleV2;
39715
+ if (lifecycleV2 !== void 0) {
39716
+ await this.#recordLifecycleEventV2({
39717
+ payload: { commandId: options.commandId, content: lifecycleV2.content, kind: "prompt.requested" },
39718
+ type: "lifecycle-metadata"
39719
+ });
39720
+ await this.#recordLifecycleEventV2({
39721
+ payload: {
39722
+ attemptId: lifecycleV2.attemptId,
39723
+ commandId: options.commandId,
39724
+ epoch: lifecycleV2.epoch,
39725
+ kind: "prompt.started"
39726
+ },
39727
+ type: "lifecycle-metadata"
39728
+ });
39729
+ }
39738
39730
  this.#nativePrompt = {
39739
39731
  commandId: options.commandId,
39740
39732
  previousTurnId: this.#connection.inProcessAgent?.nativeTurnId?.() ?? null
@@ -39789,16 +39781,37 @@ var AgentSession = class _AgentSession {
39789
39781
  this.#lastTerminalCommandId
39790
39782
  )
39791
39783
  );
39784
+ if (lifecycleV2 !== void 0) {
39785
+ await this.#recordLifecycleEventV2({
39786
+ payload: { commandId: options.commandId, kind: "prompt.completed", stopReason: result.stopReason },
39787
+ type: "lifecycle-metadata"
39788
+ });
39789
+ }
39792
39790
  return result;
39793
39791
  } catch (error62) {
39794
39792
  await running.activities.finish();
39793
+ const failure2 = error62 instanceof AcpExecutionError ? error62 : new AcpExecutionError("ACP agent execution failed", { cause: error62 });
39794
+ if (lifecycleV2 !== void 0) {
39795
+ await this.#recordLifecycleEventV2({
39796
+ payload: {
39797
+ attemptId: lifecycleV2.attemptId,
39798
+ code: failure2.code,
39799
+ commandId: options.commandId,
39800
+ kind: "prompt.failed",
39801
+ message: truncate(failure2.message, 500)
39802
+ },
39803
+ type: "lifecycle-metadata"
39804
+ });
39805
+ }
39795
39806
  if (error62 instanceof AcpExecutionError) {
39796
39807
  throw error62;
39797
39808
  }
39798
- throw new AcpExecutionError("ACP agent execution failed", {
39799
- cause: error62
39800
- });
39809
+ throw failure2;
39801
39810
  } finally {
39811
+ if (completedHistory !== null && this.#turnHistory !== null) {
39812
+ await completedHistory.append(this.#turnHistory);
39813
+ }
39814
+ this.#turnHistory = null;
39802
39815
  this.#turn = new IdleAcpTurn();
39803
39816
  }
39804
39817
  };
@@ -39814,41 +39827,80 @@ var AgentSession = class _AgentSession {
39814
39827
  throw new AcpExecutionError("The target turn is no longer active", {}, "steering_target_unavailable");
39815
39828
  }
39816
39829
  const prompt = this.buildPrompt(options);
39817
- const response = await this.race(
39818
- this.#connection.connection.agent.request("_session/steering", {
39819
- _meta: { steering: { idleBehavior: "promptRequired" } },
39820
- prompt,
39821
- sessionId: this.#updates.sessionId()
39822
- }),
39823
- "ACP agent exited during steering",
39824
- options.signal
39825
- );
39826
- if (!isRecord3(response)) {
39830
+ const lifecycleV2 = options.lifecycleV2;
39831
+ if (lifecycleV2 !== void 0) {
39832
+ await this.#recordLifecycleEventV2({
39833
+ payload: { commandId: options.commandId, content: lifecycleV2.content, kind: "prompt.requested" },
39834
+ type: "lifecycle-metadata"
39835
+ });
39836
+ await this.#recordLifecycleEventV2({
39837
+ payload: {
39838
+ attemptId: lifecycleV2.attemptId,
39839
+ commandId: options.commandId,
39840
+ epoch: lifecycleV2.epoch,
39841
+ kind: "prompt.started"
39842
+ },
39843
+ type: "lifecycle-metadata"
39844
+ });
39845
+ }
39846
+ try {
39847
+ const response = await this.race(
39848
+ this.#connection.connection.agent.request("_session/steering", {
39849
+ _meta: { steering: { idleBehavior: "promptRequired" } },
39850
+ prompt,
39851
+ sessionId: this.#updates.sessionId()
39852
+ }),
39853
+ "ACP agent exited during steering",
39854
+ options.signal
39855
+ );
39856
+ if (!isRecord3(response)) {
39857
+ throw new AcpExecutionError(
39858
+ "ACP agent returned an invalid steering response",
39859
+ {},
39860
+ "acp_invalid_steering_response"
39861
+ );
39862
+ }
39863
+ const outcome = response["outcome"];
39864
+ if (outcome === "injected" || outcome === "startedNewTurn") {
39865
+ if (lifecycleV2 !== void 0) {
39866
+ await this.#recordLifecycleEventV2({
39867
+ payload: { commandId: options.commandId, kind: "prompt.completed", stopReason: "steered" },
39868
+ type: "lifecycle-metadata"
39869
+ });
39870
+ }
39871
+ return outcome;
39872
+ }
39873
+ if (outcome === "promptRequired") {
39874
+ throw new AcpExecutionError(
39875
+ "The target turn finished before steering could be injected",
39876
+ {},
39877
+ "steering_target_unavailable"
39878
+ );
39879
+ }
39880
+ if (outcome === "failed") {
39881
+ throw new AcpExecutionError("The Agent could not inject steering", {}, "steering_failed");
39882
+ }
39827
39883
  throw new AcpExecutionError(
39828
39884
  "ACP agent returned an invalid steering response",
39829
39885
  {},
39830
39886
  "acp_invalid_steering_response"
39831
39887
  );
39888
+ } catch (error62) {
39889
+ const failure2 = error62 instanceof AcpExecutionError ? error62 : new AcpExecutionError("ACP agent execution failed", { cause: error62 });
39890
+ if (lifecycleV2 !== void 0) {
39891
+ await this.#recordLifecycleEventV2({
39892
+ payload: {
39893
+ attemptId: lifecycleV2.attemptId,
39894
+ code: failure2.code,
39895
+ commandId: options.commandId,
39896
+ kind: "prompt.failed",
39897
+ message: truncate(failure2.message, 500)
39898
+ },
39899
+ type: "lifecycle-metadata"
39900
+ });
39901
+ }
39902
+ throw failure2;
39832
39903
  }
39833
- const outcome = response["outcome"];
39834
- if (outcome === "injected" || outcome === "startedNewTurn") {
39835
- return outcome;
39836
- }
39837
- if (outcome === "promptRequired") {
39838
- throw new AcpExecutionError(
39839
- "The target turn finished before steering could be injected",
39840
- {},
39841
- "steering_target_unavailable"
39842
- );
39843
- }
39844
- if (outcome === "failed") {
39845
- throw new AcpExecutionError("The Agent could not inject steering", {}, "steering_failed");
39846
- }
39847
- throw new AcpExecutionError(
39848
- "ACP agent returned an invalid steering response",
39849
- {},
39850
- "acp_invalid_steering_response"
39851
- );
39852
39904
  };
39853
39905
  cancel = async () => {
39854
39906
  const capturedProcesses = await this.#connection.captureProcessTree();
@@ -39869,6 +39921,13 @@ var AgentSession = class _AgentSession {
39869
39921
  onElicitation = (request, signal) => this.#interactions.onElicitation(request, signal);
39870
39922
  onElicitationComplete = (notification) => this.#interactions.onElicitationComplete(notification);
39871
39923
  onUpdate = (notification) => this.#updates.receive(notification);
39924
+ #recordLifecycleEventV2 = async (event) => {
39925
+ if (event.type !== "lifecycle-metadata" || this.#sessionLoad.kind !== "loaded") {
39926
+ return;
39927
+ }
39928
+ const position = this.#turnHistory === null ? this.#sessionLoad.history.recordLifecycle(event) : this.#sessionLoad.history.eventCount() + this.#turnHistory.recordLifecycle(event);
39929
+ await this.#getObserver().onSessionEventV2?.(this.#mobiusSessionId, event, position);
39930
+ };
39872
39931
  selectNativeSession = (sessionId) => {
39873
39932
  this.#updates.select(sessionId);
39874
39933
  this.#nativeHistoryOwnership = { kind: "agent-owned" };
@@ -39885,9 +39944,20 @@ var AgentSession = class _AgentSession {
39885
39944
  if (this.#sessionLoad.kind === "capturing") {
39886
39945
  await this.#sessionLoad.history.record(update, rawUpdate);
39887
39946
  } else {
39888
- const onAcpUpdate = this.#getObserver().onAcpUpdate;
39889
- if (onAcpUpdate !== void 0) {
39890
- await onAcpUpdate(this.#mobiusSessionId, rawUpdate);
39947
+ const onSessionEventV2 = this.#getObserver().onSessionEventV2;
39948
+ if (this.#turnHistory !== null) {
39949
+ const completedEventCount = this.#sessionLoad.kind === "loaded" ? this.#sessionLoad.history.eventCount() : 0;
39950
+ await this.#turnHistory.record(update, rawUpdate, async (turnPosition) => {
39951
+ await onSessionEventV2?.(
39952
+ this.#mobiusSessionId,
39953
+ { payload: rawUpdate, type: "acp" },
39954
+ completedEventCount + turnPosition
39955
+ );
39956
+ });
39957
+ } else if (this.#sessionLoad.kind === "loaded") {
39958
+ await this.#sessionLoad.history.record(update, rawUpdate, async (position) => {
39959
+ await onSessionEventV2?.(this.#mobiusSessionId, { payload: rawUpdate, type: "acp" }, position);
39960
+ });
39891
39961
  }
39892
39962
  }
39893
39963
  if (this.#sessionLoad.kind === "capturing" && (update.sessionUpdate === "user_message_chunk" || update.sessionUpdate === "agent_message_chunk" || update.sessionUpdate === "agent_thought_chunk" || update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update" || update.sessionUpdate === "plan" || update.sessionUpdate === "plan_update" || update.sessionUpdate === "plan_removed")) {
@@ -42666,8 +42736,8 @@ var DaemonAcpObserver = class {
42666
42736
  this.#record = record2;
42667
42737
  this.#recordV2 = recordV2;
42668
42738
  }
42669
- onAcpUpdate = (sessionId, update) => {
42670
- this.#recordV2(sessionId, { payload: update, type: "acp" });
42739
+ onSessionEventV2 = (sessionId, event, position) => {
42740
+ this.#recordV2(sessionId, event, position);
42671
42741
  return Promise.resolve();
42672
42742
  };
42673
42743
  onCommands = (event) => {
@@ -42684,18 +42754,10 @@ var DaemonAcpObserver = class {
42684
42754
  };
42685
42755
  onElicitation = (event) => {
42686
42756
  this.#record(event.sessionId, event);
42687
- this.#recordV2(event.sessionId, {
42688
- payload: { event, kind: "session.elicitation.requested" },
42689
- type: "lifecycle-metadata"
42690
- });
42691
42757
  return Promise.resolve();
42692
42758
  };
42693
42759
  onElicitationResolved = (event) => {
42694
42760
  this.#record(event.sessionId, event);
42695
- this.#recordV2(event.sessionId, {
42696
- payload: { event, kind: "session.elicitation.resolved" },
42697
- type: "lifecycle-metadata"
42698
- });
42699
42761
  return Promise.resolve();
42700
42762
  };
42701
42763
  onInfo = (event) => {
@@ -42704,18 +42766,10 @@ var DaemonAcpObserver = class {
42704
42766
  };
42705
42767
  onPermission = (event) => {
42706
42768
  this.#record(event.sessionId, event);
42707
- this.#recordV2(event.sessionId, {
42708
- payload: { event, kind: "session.permission.requested" },
42709
- type: "lifecycle-metadata"
42710
- });
42711
42769
  return Promise.resolve();
42712
42770
  };
42713
42771
  onPermissionResolved = (event) => {
42714
42772
  this.#record(event.sessionId, event);
42715
- this.#recordV2(event.sessionId, {
42716
- payload: { event, kind: "session.permission.resolved" },
42717
- type: "lifecycle-metadata"
42718
- });
42719
42773
  return Promise.resolve();
42720
42774
  };
42721
42775
  onUsage = (event) => {
@@ -43550,14 +43604,14 @@ function decodeHistory(thread, value, options) {
43550
43604
  if (options.detail === "rich" && historyItem.text.length > 0) {
43551
43605
  append({
43552
43606
  activities: [
43553
- activity(historyItem.id ?? `progress-${sequence.toString()}`, "progress", sequence, {
43607
+ activity(historyItem.id ?? `reasoning-${sequence.toString()}`, "reasoning", sequence, {
43554
43608
  input: "",
43555
43609
  locations: [],
43556
43610
  name: "",
43557
43611
  output: historyItem.text,
43558
43612
  status: "completed",
43559
- title: "Progress",
43560
- toolKind: ""
43613
+ title: "Reasoning",
43614
+ toolKind: "think"
43561
43615
  })
43562
43616
  ],
43563
43617
  content: [],
@@ -45575,9 +45629,6 @@ async function streamLocalFile(command, send2, signal, workingDirectory, externa
45575
45629
  });
45576
45630
  }
45577
45631
 
45578
- // src/daemon-history-commands.ts
45579
- import { createHash as createHash7 } from "node:crypto";
45580
-
45581
45632
  // src/authorization/resolve-session-directories.ts
45582
45633
  import { basename as basename7 } from "node:path";
45583
45634
  var ResolvedSessionDirectories = class {
@@ -45845,72 +45896,8 @@ function paginateLiveSessionHistory(history, activeTurn, sessionId, encodedCurso
45845
45896
  }
45846
45897
  return paginateActiveTurn(historical, activeTurn, sessionId, cursor?.endIndex ?? activeTurn.messages.length, limit);
45847
45898
  }
45848
- function mergeLiveSessionHistory(history, activeTurn, sessionId) {
45849
- const page = paginateLiveSessionHistory(history, activeTurn, sessionId, null, 1e3);
45850
- if (page.status === "unavailable") {
45851
- return { cause: page.cause, status: "unavailable" };
45852
- }
45853
- return {
45854
- coveredCommandIds: page.coveredCommandIds,
45855
- ...page.streamPosition === void 0 ? {} : { streamPosition: page.streamPosition },
45856
- coveredMessageIds: page.coveredMessageIds,
45857
- messages: page.messages,
45858
- status: "available",
45859
- truncated: page.truncated || page.nextCursor !== null
45860
- };
45861
- }
45862
45899
 
45863
45900
  // src/daemon-history-commands.ts
45864
- async function executeSessionLiveHistoryLoad(socket, command, config2, directories, audit, sessions, activeTurn, signal) {
45865
- try {
45866
- const resolved = await resolveSessionDirectories(
45867
- directories,
45868
- config2.bindingId,
45869
- command.directoryId,
45870
- command.additionalDirectoryIds,
45871
- signal
45872
- );
45873
- const history = await sessions.loadSessionHistory({
45874
- additionalDirectories: resolved.additionalDirectories,
45875
- agent: config2.catalog.find(command.agentId),
45876
- cwd: resolved.cwd,
45877
- sessionId: command.sessionId,
45878
- signal
45879
- });
45880
- signal.throwIfAborted();
45881
- const mergedHistory = mergeLiveSessionHistory(history, activeTurn(command.sessionId), command.sessionId);
45882
- audit.record({
45883
- commandId: command.requestId,
45884
- event: "session_history_loaded",
45885
- sessionId: command.sessionId
45886
- });
45887
- send(socket, {
45888
- history: mergedHistory,
45889
- kind: "session.live-history.loaded",
45890
- requestId: command.requestId,
45891
- sessionId: command.sessionId
45892
- });
45893
- } catch (error62) {
45894
- if (signal.aborted) {
45895
- return;
45896
- }
45897
- audit.record({
45898
- commandId: command.requestId,
45899
- details: { code: operationErrorCode(error62) },
45900
- event: "session_history_unavailable",
45901
- sessionId: command.sessionId
45902
- });
45903
- send(socket, {
45904
- history: {
45905
- status: "unavailable",
45906
- cause: { code: operationErrorCode(error62), message: operationErrorMessage(error62) }
45907
- },
45908
- kind: "session.live-history.loaded",
45909
- requestId: command.requestId,
45910
- sessionId: command.sessionId
45911
- });
45912
- }
45913
- }
45914
45901
  async function executeSessionLiveHistoryPageLoad(socket, command, config2, directories, audit, sessions, activeTurn, signal) {
45915
45902
  try {
45916
45903
  const resolved = await resolveSessionDirectories(
@@ -45968,20 +45955,7 @@ async function executeSessionLiveHistoryPageLoad(socket, command, config2, direc
45968
45955
  });
45969
45956
  }
45970
45957
  }
45971
- function replayEvent(sessionId, position, update) {
45972
- const encoded = JSON.stringify(update);
45973
- const eventId = `native-${createHash7("sha256").update(sessionId).update(":").update(position.toString()).update(":").update(encoded).digest("hex")}`;
45974
- return {
45975
- eventId,
45976
- payload: update,
45977
- position: position.toString(),
45978
- provenance: { kind: "original" },
45979
- recordedAt: "1970-01-01T00:00:00.000Z",
45980
- sessionId,
45981
- type: "acp"
45982
- };
45983
- }
45984
- async function executeSessionLiveHistoryV2PageLoad(socket, command, config2, directories, audit, diagnostics, sessions, executingPromptRequest, signal) {
45958
+ async function executeSessionLiveHistoryV2PageLoad(socket, command, config2, directories, audit, diagnostics, sessions, eventLogV2, signal) {
45985
45959
  try {
45986
45960
  const resolved = await resolveSessionDirectories(
45987
45961
  directories,
@@ -45990,20 +45964,18 @@ async function executeSessionLiveHistoryV2PageLoad(socket, command, config2, dir
45990
45964
  command.additionalDirectoryIds,
45991
45965
  signal
45992
45966
  );
45993
- const replay = await sessions.loadSessionEventsV2(
45994
- {
45995
- additionalDirectories: resolved.additionalDirectories,
45996
- agent: config2.catalog.find(command.agentId),
45997
- cwd: resolved.cwd,
45998
- sessionId: command.sessionId,
45999
- signal
46000
- },
46001
- command.eventLimit,
46002
- command.cursor
46003
- );
45967
+ const loadOptions = {
45968
+ additionalDirectories: resolved.additionalDirectories,
45969
+ agent: config2.catalog.find(command.agentId),
45970
+ cwd: resolved.cwd,
45971
+ sessionId: command.sessionId,
45972
+ signal
45973
+ };
45974
+ const recovery = eventLogV2.promptRequestRecovery(command.sessionId);
45975
+ const replay = await sessions.loadSessionEventsV2(loadOptions, command.eventLimit, command.cursor);
46004
45976
  signal.throwIfAborted();
46005
- const events = replay.updates.map(
46006
- (update, index2) => replayEvent(command.sessionId, replay.startPosition + index2, update)
45977
+ const events = replay.events.map(
45978
+ (event, index2) => eventLogV2.event(command.sessionId, replay.startPosition + index2, event, "1970-01-01T00:00:00.000Z")
46007
45979
  );
46008
45980
  const tailCursor = events.at(-1)?.eventId ?? "";
46009
45981
  audit.record({
@@ -46013,14 +45985,15 @@ async function executeSessionLiveHistoryV2PageLoad(socket, command, config2, dir
46013
45985
  });
46014
45986
  send(socket, {
46015
45987
  events: {
46016
- executingPromptRequest: executingPromptRequest(command.sessionId),
46017
- history: {
45988
+ events: {
45989
+ daemonGenerationId: eventLogV2.daemonGenerationId,
46018
45990
  events,
46019
45991
  nextCursor: replay.nextCursor,
46020
45992
  tailCursor,
46021
45993
  truncated: replay.truncated,
46022
45994
  version: 2
46023
- }
45995
+ },
45996
+ queuedPromptRequests: recovery.queuedPromptRequests
46024
45997
  },
46025
45998
  kind: "session.live-history.v2.page.loaded",
46026
45999
  requestId: command.requestId,
@@ -46470,7 +46443,7 @@ async function executePrompt({
46470
46443
  }
46471
46444
  }
46472
46445
  const stream = activateAttempt();
46473
- eventLogV2.started(command.sessionId, command.commandId, attemptId, stream.epoch);
46446
+ const lifecycleV2 = eventLogV2.started(command.sessionId, command.commandId, attemptId, stream.epoch);
46474
46447
  if (!prepared.prompted) {
46475
46448
  const listing = await directories.list(config2.bindingId, command.directoryId, signal);
46476
46449
  publisher.publish(command.sessionId, {
@@ -46507,6 +46480,7 @@ async function executePrompt({
46507
46480
  commandId: command.commandId,
46508
46481
  cwd: resolved.cwd,
46509
46482
  images: attachments.images,
46483
+ lifecycleV2,
46510
46484
  prompt: command.prompt,
46511
46485
  resources: attachments.resources,
46512
46486
  sessionId: command.sessionId,
@@ -46522,6 +46496,7 @@ async function executePrompt({
46522
46496
  cwd: resolved.cwd,
46523
46497
  disposition: availability.disposition,
46524
46498
  images: attachments.images,
46499
+ lifecycleV2,
46525
46500
  onActivity: events.recordActivity,
46526
46501
  onNarration: events.recordNarration,
46527
46502
  onText: events.recordText,
@@ -46913,20 +46888,6 @@ function createDaemonCommandHandler({
46913
46888
  return {
46914
46889
  handle: (message) => {
46915
46890
  const kind = message.kind;
46916
- if (kind === SESSION_LIVE_HISTORY_LOAD_KIND) {
46917
- const command2 = message;
46918
- void executeSessionLiveHistoryLoad(
46919
- socket,
46920
- command2,
46921
- config2,
46922
- directories,
46923
- audit,
46924
- sessions,
46925
- activeTurnRecovery,
46926
- signal
46927
- );
46928
- return;
46929
- }
46930
46891
  if (kind === SESSION_LIVE_HISTORY_PAGE_LOAD_KIND) {
46931
46892
  const command2 = message;
46932
46893
  void executeSessionLiveHistoryPageLoad(
@@ -46950,7 +46911,7 @@ function createDaemonCommandHandler({
46950
46911
  audit,
46951
46912
  diagnostics,
46952
46913
  sessions,
46953
- eventLogV2.executingPromptRequest,
46914
+ eventLogV2,
46954
46915
  signal
46955
46916
  );
46956
46917
  return;
@@ -47623,10 +47584,6 @@ import { WebSocket as WebSocket9 } from "undici";
47623
47584
  var MAX_BUFFERED_BYTES = 32 * 1024 * 1024;
47624
47585
  var DaemonSessionEventPublisher = class {
47625
47586
  #socket = null;
47626
- #store;
47627
- constructor(store) {
47628
- this.#store = store;
47629
- }
47630
47587
  connect = (socket) => {
47631
47588
  this.#socket = socket;
47632
47589
  };
@@ -47678,7 +47635,6 @@ var DaemonSessionEventPublisher = class {
47678
47635
  }
47679
47636
  };
47680
47637
  publishV2 = (event) => {
47681
- this.#store.appendExecutingPromptEventV2(event);
47682
47638
  const socket = this.#socket;
47683
47639
  if (socket === null || socket.readyState !== WebSocket9.OPEN) {
47684
47640
  return;
@@ -47705,7 +47661,7 @@ var SystemDaemonTimer = class {
47705
47661
  var systemDaemonTimer = new SystemDaemonTimer();
47706
47662
 
47707
47663
  // src/session-event-log-v2.ts
47708
- var EXECUTING_PROMPT_EVENT_LIMIT = 1e4;
47664
+ import { createHash as createHash7, randomUUID as randomUUID8 } from "node:crypto";
47709
47665
  function promptContent(command) {
47710
47666
  const content = [];
47711
47667
  if (command.prompt.length > 0) {
@@ -47729,176 +47685,59 @@ function promptContent(command) {
47729
47685
  }
47730
47686
  return content;
47731
47687
  }
47688
+ function sessionEventV22(daemonGenerationId, sessionId, position, event, recordedAt) {
47689
+ const sessionPrefix = createHash7("sha256").update(sessionId).digest("hex").slice(0, 16);
47690
+ return {
47691
+ eventId: `event-${daemonGenerationId}-${sessionPrefix}-${position.toString().padStart(16, "0")}`,
47692
+ ...event,
47693
+ position: position.toString(),
47694
+ provenance: { kind: "original" },
47695
+ recordedAt,
47696
+ sessionId
47697
+ };
47698
+ }
47732
47699
  var DaemonSessionEventLogV2 = class {
47733
- #positions = /* @__PURE__ */ new Map();
47734
- #requests = /* @__PURE__ */ new Map();
47735
- #loadedRequestSessions = /* @__PURE__ */ new Set();
47700
+ daemonGenerationId = randomUUID8();
47736
47701
  #publisher;
47737
- #store;
47738
- constructor(publisher, store) {
47702
+ #queued = /* @__PURE__ */ new Map();
47703
+ constructor(publisher) {
47739
47704
  this.#publisher = publisher;
47740
- this.#store = store;
47741
47705
  }
47742
- #loadStoredEvents = (sessionId) => {
47743
- const stored = this.#store.readExecutingPromptEventsV2(sessionId);
47744
- const lastPosition = stored.at(-1)?.position;
47745
- if (lastPosition !== void 0) {
47746
- this.#positions.set(sessionId, Number(lastPosition));
47747
- }
47748
- return stored;
47749
- };
47750
- #loadRequests = (sessionId) => {
47751
- if (this.#loadedRequestSessions.has(sessionId)) {
47752
- return;
47753
- }
47754
- for (const event of this.#loadStoredEvents(sessionId)) {
47755
- if (event.type === "acp") {
47756
- continue;
47757
- }
47758
- const payload = event.payload;
47759
- if (payload.kind === "prompt.requested") {
47760
- this.#requests.set(payload.commandId, {
47761
- commandId: payload.commandId,
47762
- kind: "requested",
47763
- sessionId
47764
- });
47765
- continue;
47766
- }
47767
- if ("event" in payload) {
47768
- continue;
47769
- }
47770
- if (!("commandId" in payload)) {
47771
- continue;
47772
- }
47773
- const state = this.#requests.get(payload.commandId);
47774
- if (state === void 0) {
47775
- continue;
47776
- }
47777
- if (payload.kind === "prompt.started") {
47778
- this.#requests.set(payload.commandId, {
47779
- attemptId: payload.attemptId,
47780
- commandId: payload.commandId,
47781
- epoch: payload.epoch,
47782
- kind: "executing",
47783
- sessionId
47784
- });
47785
- } else if (payload.kind === "prompt.completed" || payload.kind === "prompt.failed" || payload.kind === "prompt.failed-before-start") {
47786
- this.#requests.delete(payload.commandId);
47787
- }
47788
- }
47789
- this.#loadedRequestSessions.add(sessionId);
47790
- };
47791
- #append = (sessionId, payload) => {
47792
- this.#loadRequests(sessionId);
47793
- const position = (this.#positions.get(sessionId) ?? 0) + 1;
47794
- const event = {
47795
- eventId: `event-${crypto.randomUUID()}`,
47796
- ...payload,
47797
- position: position.toString(),
47798
- provenance: { kind: "original" },
47799
- recordedAt: (/* @__PURE__ */ new Date()).toISOString(),
47800
- sessionId
47801
- };
47802
- this.#publisher.publishV2(event);
47803
- this.#positions.set(sessionId, position);
47804
- return event;
47805
- };
47806
47706
  requested = (command) => {
47807
- const content = promptContent(command);
47808
- this.#append(command.sessionId, {
47809
- payload: { commandId: command.commandId, content, kind: "prompt.requested" },
47810
- type: "lifecycle-metadata"
47811
- });
47812
- this.#requests.set(command.commandId, {
47707
+ this.#queued.set(command.commandId, {
47813
47708
  commandId: command.commandId,
47814
- kind: "requested",
47709
+ content: promptContent(command),
47815
47710
  sessionId: command.sessionId
47816
47711
  });
47817
47712
  };
47818
47713
  started = (sessionId, commandId, attemptId, epoch) => {
47819
- this.#loadRequests(sessionId);
47820
- const request = this.#requests.get(commandId);
47821
- if (request?.sessionId !== sessionId) {
47822
- return;
47714
+ const request = this.#queued.get(commandId);
47715
+ if (request?.sessionId === sessionId) {
47716
+ this.#queued.delete(commandId);
47717
+ return { attemptId, content: request.content, epoch };
47823
47718
  }
47824
- this.#append(sessionId, {
47825
- payload: { attemptId, commandId, epoch, kind: "prompt.started" },
47826
- type: "lifecycle-metadata"
47827
- });
47828
- this.#requests.set(commandId, {
47829
- attemptId,
47830
- commandId,
47831
- epoch,
47832
- kind: "executing",
47833
- sessionId
47834
- });
47719
+ throw new Error("The executing prompt was not registered in the V2 queue");
47835
47720
  };
47836
- record = (sessionId, payload) => {
47837
- this.#loadRequests(sessionId);
47838
- this.#append(sessionId, payload);
47721
+ record = (sessionId, event, position) => {
47722
+ this.#publisher.publishV2(this.event(sessionId, position, event, (/* @__PURE__ */ new Date()).toISOString()));
47839
47723
  };
47840
- #clearCompletedSession = (sessionId) => {
47841
- if (![...this.#requests.values()].some((request) => request.sessionId === sessionId)) {
47842
- this.#store.clearExecutingPromptEventsV2(sessionId);
47724
+ event = (sessionId, position, event, recordedAt) => sessionEventV22(this.daemonGenerationId, sessionId, position, event, recordedAt);
47725
+ queueChanged = (_sessionId) => void 0;
47726
+ completed = (sessionId, commandId, _stopReason) => {
47727
+ const request = this.#queued.get(commandId);
47728
+ if (request?.sessionId === sessionId) {
47729
+ this.#queued.delete(commandId);
47843
47730
  }
47844
47731
  };
47845
- queueChanged = (sessionId) => {
47846
- this.#append(sessionId, {
47847
- payload: { kind: "session.queue.changed" },
47848
- type: "lifecycle-metadata"
47849
- });
47850
- };
47851
- completed = (sessionId, commandId, stopReason) => {
47852
- this.#loadRequests(sessionId);
47853
- this.#append(sessionId, {
47854
- payload: { commandId, kind: "prompt.completed", stopReason },
47855
- type: "lifecycle-metadata"
47856
- });
47857
- this.#requests.delete(commandId);
47858
- this.#clearCompletedSession(sessionId);
47859
- };
47860
- failed = (sessionId, commandId, code, message) => {
47861
- this.#loadRequests(sessionId);
47862
- const request = this.#requests.get(commandId);
47863
- if (request?.kind === "executing" && request.commandId === commandId) {
47864
- this.#append(sessionId, {
47865
- payload: {
47866
- attemptId: request.attemptId,
47867
- code,
47868
- commandId,
47869
- kind: "prompt.failed",
47870
- message
47871
- },
47872
- type: "lifecycle-metadata"
47873
- });
47874
- } else {
47875
- this.#append(sessionId, {
47876
- payload: { code, commandId, kind: "prompt.failed-before-start", message },
47877
- type: "lifecycle-metadata"
47878
- });
47879
- }
47880
- this.#requests.delete(commandId);
47881
- this.#clearCompletedSession(sessionId);
47882
- };
47883
- executingPromptRequest = (sessionId) => {
47884
- this.#loadRequests(sessionId);
47885
- const request = [...this.#requests.values()].find(
47886
- (candidate) => candidate.sessionId === sessionId && candidate.kind === "executing"
47887
- );
47888
- if (request?.kind !== "executing") {
47889
- return null;
47732
+ failed = (sessionId, commandId, _code, _message) => {
47733
+ const request = this.#queued.get(commandId);
47734
+ if (request?.sessionId === sessionId) {
47735
+ this.#queued.delete(commandId);
47890
47736
  }
47891
- const requestEvents = this.#store.readExecutingPromptEventsV2(sessionId);
47892
- const events = requestEvents.slice(-EXECUTING_PROMPT_EVENT_LIMIT);
47893
- return {
47894
- attemptId: request.attemptId,
47895
- commandId: request.commandId,
47896
- epoch: request.epoch,
47897
- events,
47898
- tailCursor: events.at(-1)?.eventId ?? "",
47899
- truncated: events.length < requestEvents.length
47900
- };
47901
47737
  };
47738
+ promptRequestRecovery = (sessionId) => ({
47739
+ queuedPromptRequests: [...this.#queued.values()].filter((request) => request.sessionId === sessionId).map(({ commandId, content }) => ({ commandId, content }))
47740
+ });
47902
47741
  };
47903
47742
 
47904
47743
  // src/run-daemon.ts
@@ -47949,7 +47788,7 @@ async function installDetectedAgentIntegrations(config2, installations, signal)
47949
47788
  {
47950
47789
  agentId: agent.id,
47951
47790
  kind: AGENT_INSTALL_REQUEST_KIND,
47952
- requestId: `automatic-integration-${randomUUID8()}`
47791
+ requestId: `automatic-integration-${randomUUID9()}`
47953
47792
  },
47954
47793
  signal
47955
47794
  );
@@ -47972,8 +47811,8 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
47972
47811
  );
47973
47812
  await using externalContent = new LocalExternalContentStore(stateDirectory);
47974
47813
  const operations = new DaemonOperationState();
47975
- const publisher = new DaemonSessionEventPublisher(sessionStore);
47976
- const eventLogV2 = new DaemonSessionEventLogV2(publisher, sessionStore);
47814
+ const publisher = new DaemonSessionEventPublisher();
47815
+ const eventLogV2 = new DaemonSessionEventLogV2(publisher);
47977
47816
  const activeTurns = new DaemonTurnRegistry(operations);
47978
47817
  const recordSessionEvent = (sessionId, event) => {
47979
47818
  publisher.publish(sessionId, activeTurns.recordEvent(event));