@moxt-ai/mobius 0.0.156 → 0.0.158

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 (37) hide show
  1. package/dist/acp/agent-session.d.ts.map +1 -1
  2. package/dist/acp/agent-session.js +23 -2
  3. package/dist/acp/agent-session.js.map +1 -1
  4. package/dist/acp/codex/agent.js +2 -2
  5. package/dist/acp/codex/agent.js.map +1 -1
  6. package/dist/acp/codex/app-server-protocol.d.ts +6 -6
  7. package/dist/acp/codex/app-server-protocol.d.ts.map +1 -1
  8. package/dist/acp/codex/app-server-protocol.js +5 -7
  9. package/dist/acp/codex/app-server-protocol.js.map +1 -1
  10. package/dist/acp/session-store.d.ts +12 -6
  11. package/dist/acp/session-store.d.ts.map +1 -1
  12. package/dist/acp/session-store.js +36 -5
  13. package/dist/acp/session-store.js.map +1 -1
  14. package/dist/cli.js +257 -115
  15. package/dist/cli.js.map +3 -3
  16. package/dist/daemon-command-handler.d.ts.map +1 -1
  17. package/dist/daemon-command-handler.js +5 -2
  18. package/dist/daemon-command-handler.js.map +1 -1
  19. package/dist/daemon-history-commands.d.ts +1 -1
  20. package/dist/daemon-history-commands.d.ts.map +1 -1
  21. package/dist/daemon-history-commands.js +3 -12
  22. package/dist/daemon-history-commands.js.map +1 -1
  23. package/dist/daemon-observers.d.ts +2 -2
  24. package/dist/daemon-observers.d.ts.map +1 -1
  25. package/dist/daemon-observers.js +17 -1
  26. package/dist/daemon-observers.js.map +1 -1
  27. package/dist/index.js +256 -114
  28. package/dist/index.js.map +3 -3
  29. package/dist/run-daemon.js +1 -1
  30. package/dist/run-daemon.js.map +1 -1
  31. package/dist/runtime.js +256 -114
  32. package/dist/runtime.js.map +3 -3
  33. package/dist/session-event-log-v2.d.ts +3 -3
  34. package/dist/session-event-log-v2.d.ts.map +1 -1
  35. package/dist/session-event-log-v2.js +103 -84
  36. package/dist/session-event-log-v2.js.map +1 -1
  37. package/package.json +1 -1
package/dist/runtime.js CHANGED
@@ -21489,8 +21489,15 @@ var acpSessionUpdateV2Schema = external_exports.discriminatedUnion("sessionUpdat
21489
21489
  }).readonly()
21490
21490
  ]);
21491
21491
  var lifecycleBase = { commandId: identifierStringSchema };
21492
- var sessionEventPayloadV2Schema = external_exports.discriminatedUnion("kind", [
21493
- external_exports.strictObject({ kind: external_exports.literal("acp.session.update"), update: acpSessionUpdateV2Schema }).readonly(),
21492
+ var lifecycleMetadataV2Schema = external_exports.discriminatedUnion("kind", [
21493
+ external_exports.strictObject({ kind: external_exports.literal("session.queue.changed") }).readonly(),
21494
+ external_exports.strictObject({ event: sessionPermissionRequestedEventSchema, kind: external_exports.literal("session.permission.requested") }).readonly(),
21495
+ external_exports.strictObject({ event: sessionPermissionResolvedEventSchema, kind: external_exports.literal("session.permission.resolved") }).readonly(),
21496
+ external_exports.strictObject({
21497
+ event: sessionElicitationRequestedEventSchema,
21498
+ kind: external_exports.literal("session.elicitation.requested")
21499
+ }).readonly(),
21500
+ external_exports.strictObject({ event: sessionElicitationResolvedEventSchema, kind: external_exports.literal("session.elicitation.resolved") }).readonly(),
21494
21501
  external_exports.strictObject({
21495
21502
  ...lifecycleBase,
21496
21503
  content: external_exports.array(contentBlockV2Schema).min(1).max(100).readonly(),
@@ -21512,6 +21519,10 @@ var sessionEventPayloadV2Schema = external_exports.discriminatedUnion("kind", [
21512
21519
  message: external_exports.string().min(1).max(500)
21513
21520
  }).readonly()
21514
21521
  ]);
21522
+ var sessionEventPayloadV2Schema = external_exports.discriminatedUnion("type", [
21523
+ external_exports.strictObject({ payload: acpSessionUpdateV2Schema, type: external_exports.literal("acp") }).readonly(),
21524
+ external_exports.strictObject({ payload: lifecycleMetadataV2Schema, type: external_exports.literal("lifecycle-metadata") }).readonly()
21525
+ ]);
21515
21526
  var positionSchema = external_exports.string().regex(/^(0|[1-9][0-9]*)$/);
21516
21527
  var provenanceSchema = external_exports.discriminatedUnion("kind", [
21517
21528
  external_exports.strictObject({ kind: external_exports.literal("original") }).readonly(),
@@ -21528,13 +21539,62 @@ var provenanceSchema = external_exports.discriminatedUnion("kind", [
21528
21539
  sourceSessionId: identifierStringSchema
21529
21540
  }).readonly()
21530
21541
  ]);
21531
- var sessionEventV2Schema = external_exports.strictObject({
21542
+ var sessionEventFieldsV2 = {
21532
21543
  eventId: identifierStringSchema,
21533
- payload: sessionEventPayloadV2Schema,
21534
21544
  position: positionSchema,
21535
21545
  provenance: provenanceSchema,
21536
21546
  recordedAt: external_exports.iso.datetime({ offset: true }),
21537
21547
  sessionId: identifierStringSchema
21548
+ };
21549
+ var sessionEventV2Schema = external_exports.discriminatedUnion("type", [
21550
+ external_exports.strictObject({ ...sessionEventFieldsV2, payload: acpSessionUpdateV2Schema, type: external_exports.literal("acp") }).readonly(),
21551
+ external_exports.strictObject({
21552
+ ...sessionEventFieldsV2,
21553
+ payload: lifecycleMetadataV2Schema,
21554
+ type: external_exports.literal("lifecycle-metadata")
21555
+ }).readonly()
21556
+ ]);
21557
+ var sessionExportV2Schema = external_exports.strictObject({
21558
+ binding: external_exports.strictObject({
21559
+ bindingId: identifierStringSchema,
21560
+ runtimeId: identifierStringSchema
21561
+ }).readonly(),
21562
+ events: external_exports.array(sessionEventV2Schema).max(MAX_EVENT_COUNT).readonly(),
21563
+ sessionId: identifierStringSchema,
21564
+ truncated: external_exports.boolean()
21565
+ }).readonly().superRefine((session, context) => {
21566
+ let previousPosition = 0n;
21567
+ const eventIds = /* @__PURE__ */ new Set();
21568
+ for (const [index2, event] of session.events.entries()) {
21569
+ if (event.sessionId !== session.sessionId) {
21570
+ context.addIssue({
21571
+ code: "custom",
21572
+ message: "Exported event belongs to a different Session",
21573
+ path: ["events", index2, "sessionId"]
21574
+ });
21575
+ }
21576
+ const position = BigInt(event.position);
21577
+ if (position <= previousPosition) {
21578
+ context.addIssue({
21579
+ code: "custom",
21580
+ message: "Exported events are not in increasing position order",
21581
+ path: ["events", index2, "position"]
21582
+ });
21583
+ }
21584
+ if (eventIds.has(event.eventId)) {
21585
+ context.addIssue({
21586
+ code: "custom",
21587
+ message: "Exported event identities are not unique",
21588
+ path: ["events", index2, "eventId"]
21589
+ });
21590
+ }
21591
+ previousPosition = position;
21592
+ eventIds.add(event.eventId);
21593
+ }
21594
+ });
21595
+ var mobiusSessionExportV2Schema = external_exports.strictObject({
21596
+ formatVersion: external_exports.literal("2"),
21597
+ session: sessionExportV2Schema
21538
21598
  }).readonly();
21539
21599
  var sessionEventEnvelopeV2Schema = external_exports.strictObject({ event: sessionEventV2Schema, kind: external_exports.literal(SESSION_EVENT_V2_KIND) }).readonly();
21540
21600
  var sessionEventLogPageV2Schema = external_exports.strictObject({
@@ -23616,16 +23676,15 @@ var threadStartResponseSchema = external_exports.object({
23616
23676
  serviceTier: boundedText(256).nullish(),
23617
23677
  thread: external_exports.object({ id: boundedText(256) })
23618
23678
  });
23679
+ var threadTurnSchema = external_exports.object({
23680
+ items: external_exports.array(external_exports.unknown()).max(1e5)
23681
+ });
23682
+ var threadTurnsSchema = external_exports.array(threadTurnSchema).max(1e5);
23619
23683
  var threadLifecycleResponseSchema = external_exports.object({
23620
23684
  model: boundedText(256).nullish(),
23621
23685
  reasoningEffort: boundedText(256).nullish(),
23622
23686
  serviceTier: boundedText(256).nullish(),
23623
- thread: external_exports.object({ id: boundedText(256) }),
23624
- turns: external_exports.array(
23625
- external_exports.object({
23626
- items: external_exports.array(external_exports.unknown()).max(1e5)
23627
- })
23628
- ).max(1e5).nullish()
23687
+ thread: external_exports.object({ id: boundedText(256), turns: threadTurnsSchema })
23629
23688
  });
23630
23689
  var threadResumeResponseSchema = threadLifecycleResponseSchema;
23631
23690
  var threadForkResponseSchema = threadLifecycleResponseSchema;
@@ -24640,7 +24699,7 @@ var CodexAcpAgent = class {
24640
24699
  this.#nativeSessionId = resumed.thread.id;
24641
24700
  this.#settings.selectRestoredThread(resumed);
24642
24701
  await this.#settings.probeCollaborationMode(this.#nativeSessionId, context.signal);
24643
- await this.#replayHistory(resumed.turns);
24702
+ await this.#replayHistory(resumed.thread.turns);
24644
24703
  await this.#emitAvailableCommands();
24645
24704
  return { configOptions: this.#settings.configOptions() };
24646
24705
  }).onRequest(methods.agent.session.fork, async (context) => {
@@ -24658,7 +24717,7 @@ var CodexAcpAgent = class {
24658
24717
  this.#nativeSessionId = forked.thread.id;
24659
24718
  this.#settings.selectRestoredThread(forked);
24660
24719
  await this.#settings.probeCollaborationMode(this.#nativeSessionId, context.signal);
24661
- await this.#replayHistory(forked.turns);
24720
+ await this.#replayHistory(forked.thread.turns);
24662
24721
  await this.#emitAvailableCommands();
24663
24722
  return { configOptions: this.#settings.configOptions(), sessionId: forked.thread.id };
24664
24723
  }).onRequest(methods.agent.session.resume, async (context) => {
@@ -35036,8 +35095,15 @@ var MemoryAcpSessionStore = class {
35036
35095
  #sessions = /* @__PURE__ */ new Map();
35037
35096
  #deleted = /* @__PURE__ */ new Set();
35038
35097
  #eventsV2 = /* @__PURE__ */ new Map();
35039
- appendEventV2 = (event) => {
35040
- this.#eventsV2.set(event.sessionId, [...this.#eventsV2.get(event.sessionId) ?? [], event]);
35098
+ appendExecutingPromptEventV2 = (event) => {
35099
+ const events = this.#eventsV2.get(event.sessionId);
35100
+ if (events === void 0) {
35101
+ throw new Error("The executing prompt event log has not started");
35102
+ }
35103
+ events.push(event);
35104
+ };
35105
+ clearExecutingPromptEventsV2 = (sessionId) => {
35106
+ this.#eventsV2.delete(sessionId);
35041
35107
  };
35042
35108
  close = () => {
35043
35109
  this.#sessions.clear();
@@ -35068,7 +35134,12 @@ var MemoryAcpSessionStore = class {
35068
35134
  this.#sessions.delete(sessionId);
35069
35135
  this.#eventsV2.delete(sessionId);
35070
35136
  };
35071
- readEventsV2 = (sessionId) => this.#eventsV2.get(sessionId) ?? [];
35137
+ readExecutingPromptEventsV2 = (sessionId) => [
35138
+ ...this.#eventsV2.get(sessionId) ?? []
35139
+ ];
35140
+ startExecutingPromptEventsV2 = (sessionId, events) => {
35141
+ this.#eventsV2.set(sessionId, [...events]);
35142
+ };
35072
35143
  write = (session) => {
35073
35144
  this.#sessions.set(session.sessionId, session);
35074
35145
  };
@@ -35136,7 +35207,7 @@ var SqliteAcpSessionStore = class {
35136
35207
  close = () => {
35137
35208
  this.#sqliteDatabase.close();
35138
35209
  };
35139
- appendEventV2 = (event) => {
35210
+ appendExecutingPromptEventV2 = (event) => {
35140
35211
  this.#database.insert(sessionEventV2).values({
35141
35212
  eventId: event.eventId,
35142
35213
  eventJson: JSON.stringify(event),
@@ -35144,6 +35215,22 @@ var SqliteAcpSessionStore = class {
35144
35215
  sessionId: event.sessionId
35145
35216
  }).run();
35146
35217
  };
35218
+ clearExecutingPromptEventsV2 = (sessionId) => {
35219
+ this.#database.delete(sessionEventV2).where(eq(sessionEventV2.sessionId, sessionId)).run();
35220
+ };
35221
+ startExecutingPromptEventsV2 = (sessionId, events) => {
35222
+ this.#database.transaction((transaction) => {
35223
+ transaction.delete(sessionEventV2).where(eq(sessionEventV2.sessionId, sessionId)).run();
35224
+ for (const event of events) {
35225
+ transaction.insert(sessionEventV2).values({
35226
+ eventId: event.eventId,
35227
+ eventJson: JSON.stringify(event),
35228
+ position: Number(event.position),
35229
+ sessionId: event.sessionId
35230
+ }).run();
35231
+ }
35232
+ });
35233
+ };
35147
35234
  findNative = (agentId, nativeSessionId) => this.#database.select().from(acpSession).where(and(eq(acpSession.agentId, agentId), eq(acpSession.nativeSessionId, nativeSessionId))).all().map(decodeStoredSession);
35148
35235
  list = () => this.#database.select().from(acpSession).orderBy(desc(acpSession.updatedAt)).all().map(decodeStoredSession);
35149
35236
  markDeleted = (agentId, nativeSessionId) => {
@@ -35166,7 +35253,7 @@ var SqliteAcpSessionStore = class {
35166
35253
  const row = this.#database.select().from(acpSession).where(eq(acpSession.sessionId, sessionId)).get();
35167
35254
  return row === void 0 ? new MissingAcpStoredSession() : new FoundAcpStoredSession(decodeStoredSession(row));
35168
35255
  };
35169
- readEventsV2 = (sessionId) => this.#database.select({ eventJson: sessionEventV2.eventJson }).from(sessionEventV2).where(eq(sessionEventV2.sessionId, sessionId)).orderBy(asc(sessionEventV2.position)).all().map((row) => decodeSessionEventV2(row.eventJson));
35256
+ 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));
35170
35257
  remove = (sessionId) => {
35171
35258
  this.#database.transaction((transaction) => {
35172
35259
  transaction.delete(acpSession).where(eq(acpSession.sessionId, sessionId)).run();
@@ -35232,6 +35319,7 @@ var AgentSession = class _AgentSession {
35232
35319
  #configRevision = 0;
35233
35320
  #configOptions = [];
35234
35321
  #lastTerminalCommandId = null;
35322
+ #nativeHistoryOwnership = { kind: "unbound" };
35235
35323
  #prompted = false;
35236
35324
  #nativePrompt = null;
35237
35325
  #sessionLoad = { kind: "not-requested" };
@@ -35352,6 +35440,9 @@ var AgentSession = class _AgentSession {
35352
35440
  return await embedLocalHistoryImages(await loaded.history.snapshot(), signal);
35353
35441
  };
35354
35442
  loadHistoryEventsV2 = async (eventLimit, cursor, signal) => {
35443
+ if (!this.#prompted && this.#nativeHistoryOwnership.kind === "fresh-session") {
35444
+ return new AcpHistoryReplay().eventPage(eventLimit, cursor);
35445
+ }
35355
35446
  if (!this.#capabilities.loadSession) {
35356
35447
  throw new AcpExecutionError(
35357
35448
  "This Agent restores context but does not provide message history.",
@@ -35641,6 +35732,7 @@ var AgentSession = class _AgentSession {
35641
35732
  )
35642
35733
  );
35643
35734
  this.selectNativeSession(created.sessionId);
35735
+ this.#nativeHistoryOwnership = { kind: "fresh-session" };
35644
35736
  lifecycleResponse = created;
35645
35737
  }
35646
35738
  this.#configOptions = this.#sessionConfigProtocol.normalizeLifecycle(lifecycleResponse);
@@ -35844,6 +35936,19 @@ var AgentSession = class _AgentSession {
35844
35936
  if (this.#turn.running) {
35845
35937
  throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
35846
35938
  }
35939
+ switch (this.#sessionLoad.kind) {
35940
+ case "not-requested":
35941
+ break;
35942
+ case "loaded":
35943
+ this.#sessionLoad = { kind: "not-requested" };
35944
+ break;
35945
+ case "capturing":
35946
+ throw new AcpExecutionError("Session history is still loading", {}, "session_busy");
35947
+ default: {
35948
+ const unexpected = this.#sessionLoad;
35949
+ throw new Error(`Unexpected Session load state: ${JSON.stringify(unexpected)}`);
35950
+ }
35951
+ }
35847
35952
  const prompt = this.buildPrompt(options);
35848
35953
  if (this.#sessionTitle === null || this.#sessionTitle.length === 0) {
35849
35954
  this.#sessionTitle = truncate(options.prompt, 500);
@@ -36004,12 +36109,15 @@ var AgentSession = class _AgentSession {
36004
36109
  onElicitation = (request, signal) => this.#interactions.onElicitation(request, signal);
36005
36110
  onElicitationComplete = (notification) => this.#interactions.onElicitationComplete(notification);
36006
36111
  onUpdate = (notification) => this.#updates.receive(notification);
36007
- selectNativeSession = (sessionId) => this.#updates.select(sessionId);
36112
+ selectNativeSession = (sessionId) => {
36113
+ this.#updates.select(sessionId);
36114
+ this.#nativeHistoryOwnership = { kind: "agent-owned" };
36115
+ };
36008
36116
  #processUpdate = async (notification) => {
36009
36117
  this.assertNativeSession(notification.sessionId);
36010
36118
  const update = notification.update;
36011
36119
  const rawUpdate = decodeAcpSessionUpdateV2(JSON.stringify(update));
36012
- if (this.#sessionLoad.kind !== "not-requested") {
36120
+ if (this.#sessionLoad.kind === "capturing") {
36013
36121
  await this.#sessionLoad.history.record(update, rawUpdate);
36014
36122
  } else {
36015
36123
  const onAcpUpdate = this.#getObserver().onAcpUpdate;
@@ -38360,7 +38468,7 @@ var DaemonAcpObserver = class {
38360
38468
  this.#recordV2 = recordV2;
38361
38469
  }
38362
38470
  onAcpUpdate = (sessionId, update) => {
38363
- this.#recordV2(sessionId, update);
38471
+ this.#recordV2(sessionId, { payload: update, type: "acp" });
38364
38472
  return Promise.resolve();
38365
38473
  };
38366
38474
  onCommands = (event) => {
@@ -38377,10 +38485,18 @@ var DaemonAcpObserver = class {
38377
38485
  };
38378
38486
  onElicitation = (event) => {
38379
38487
  this.#record(event.sessionId, event);
38488
+ this.#recordV2(event.sessionId, {
38489
+ payload: { event, kind: "session.elicitation.requested" },
38490
+ type: "lifecycle-metadata"
38491
+ });
38380
38492
  return Promise.resolve();
38381
38493
  };
38382
38494
  onElicitationResolved = (event) => {
38383
38495
  this.#record(event.sessionId, event);
38496
+ this.#recordV2(event.sessionId, {
38497
+ payload: { event, kind: "session.elicitation.resolved" },
38498
+ type: "lifecycle-metadata"
38499
+ });
38384
38500
  return Promise.resolve();
38385
38501
  };
38386
38502
  onInfo = (event) => {
@@ -38389,10 +38505,18 @@ var DaemonAcpObserver = class {
38389
38505
  };
38390
38506
  onPermission = (event) => {
38391
38507
  this.#record(event.sessionId, event);
38508
+ this.#recordV2(event.sessionId, {
38509
+ payload: { event, kind: "session.permission.requested" },
38510
+ type: "lifecycle-metadata"
38511
+ });
38392
38512
  return Promise.resolve();
38393
38513
  };
38394
38514
  onPermissionResolved = (event) => {
38395
38515
  this.#record(event.sessionId, event);
38516
+ this.#recordV2(event.sessionId, {
38517
+ payload: { event, kind: "session.permission.resolved" },
38518
+ type: "lifecycle-metadata"
38519
+ });
38396
38520
  return Promise.resolve();
38397
38521
  };
38398
38522
  onUsage = (event) => {
@@ -41633,25 +41757,16 @@ function replayEvent(sessionId, position, update) {
41633
41757
  const eventId = `native-${createHash5("sha256").update(sessionId).update(":").update(position.toString()).update(":").update(encoded).digest("hex")}`;
41634
41758
  return {
41635
41759
  eventId,
41636
- payload: { kind: "acp.session.update", update },
41760
+ payload: update,
41637
41761
  position: position.toString(),
41638
41762
  provenance: { kind: "original" },
41639
41763
  recordedAt: "1970-01-01T00:00:00.000Z",
41640
- sessionId
41764
+ sessionId,
41765
+ type: "acp"
41641
41766
  };
41642
41767
  }
41643
- async function executeSessionLiveHistoryV2PageLoad(socket, command, config2, directories, audit, sessions, localRecovery, executingPromptRequest, signal) {
41768
+ async function executeSessionLiveHistoryV2PageLoad(socket, command, config2, directories, audit, sessions, executingPromptRequest, signal) {
41644
41769
  try {
41645
- const local = localRecovery(command.sessionId, command.eventLimit, command.cursor);
41646
- if (local !== null) {
41647
- send(socket, {
41648
- events: local,
41649
- kind: "session.live-history.v2.page.loaded",
41650
- requestId: command.requestId,
41651
- sessionId: command.sessionId
41652
- });
41653
- return;
41654
- }
41655
41770
  const resolved = await resolveSessionDirectories(
41656
41771
  directories,
41657
41772
  config2.bindingId,
@@ -42535,7 +42650,10 @@ function createDaemonCommandHandler({
42535
42650
  timer,
42536
42651
  resolveEnvironment: resolveAgentCatalogEnvironment
42537
42652
  });
42538
- const queueChanged = (sessionId) => publisher.publish(sessionId, { kind: "session.queue.changed", sessionId });
42653
+ const queueChanged = (sessionId) => {
42654
+ publisher.publish(sessionId, { kind: "session.queue.changed", sessionId });
42655
+ eventLogV2.queueChanged(sessionId);
42656
+ };
42539
42657
  const activeTurnRecovery = (sessionId) => activeTurns.recovery((command) => command.sessionId === sessionId);
42540
42658
  const nativeRequestHandler = createNativeSessionRequestHandler({
42541
42659
  audit,
@@ -42585,7 +42703,6 @@ function createDaemonCommandHandler({
42585
42703
  directories,
42586
42704
  audit,
42587
42705
  sessions,
42588
- eventLogV2.recovery,
42589
42706
  eventLogV2.executingPromptRequest,
42590
42707
  signal
42591
42708
  );
@@ -43301,6 +43418,15 @@ var systemDaemonTimer = new SystemDaemonTimer();
43301
43418
 
43302
43419
  // src/session-event-log-v2.ts
43303
43420
  var EXECUTING_PROMPT_EVENT_LIMIT = 1e4;
43421
+ function eventArray(tail) {
43422
+ const reversed = [];
43423
+ let node2 = tail;
43424
+ while (node2 !== null) {
43425
+ reversed.push(node2.event);
43426
+ node2 = node2.previous;
43427
+ }
43428
+ return reversed.reverse();
43429
+ }
43304
43430
  function promptContent(command) {
43305
43431
  const content = [];
43306
43432
  if (command.prompt.length > 0) {
@@ -43324,27 +43450,8 @@ function promptContent(command) {
43324
43450
  }
43325
43451
  return content;
43326
43452
  }
43327
- function encodeLocalEventCursor(cursor) {
43328
- return Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url");
43329
- }
43330
- function decodeLocalEventCursor(sessionId, cursor) {
43331
- try {
43332
- const value = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
43333
- if (typeof value !== "object" || value === null || Array.isArray(value) || Object.keys(value).sort().join(",") !== "endEvent,sessionId" || Reflect.get(value, "sessionId") !== sessionId) {
43334
- throw new Error("Invalid V2 event cursor target");
43335
- }
43336
- const endEvent = Reflect.get(value, "endEvent");
43337
- if (typeof endEvent !== "number" || !Number.isSafeInteger(endEvent) || endEvent < 0) {
43338
- throw new Error("Invalid V2 event cursor boundary");
43339
- }
43340
- return { endEvent, sessionId };
43341
- } catch (cause) {
43342
- throw new AcpExecutionError("The native Session event cursor is invalid", { cause }, "invalid_cursor");
43343
- }
43344
- }
43345
43453
  var DaemonSessionEventLogV2 = class {
43346
43454
  #positions = /* @__PURE__ */ new Map();
43347
- #events = /* @__PURE__ */ new Map();
43348
43455
  #requests = /* @__PURE__ */ new Map();
43349
43456
  #loadedRequestSessions = /* @__PURE__ */ new Set();
43350
43457
  #publisher;
@@ -43353,13 +43460,8 @@ var DaemonSessionEventLogV2 = class {
43353
43460
  this.#publisher = publisher;
43354
43461
  this.#store = store;
43355
43462
  }
43356
- #eventsFor = (sessionId) => {
43357
- const cached2 = this.#events.get(sessionId);
43358
- if (cached2 !== void 0) {
43359
- return cached2;
43360
- }
43361
- const stored = this.#store.readEventsV2(sessionId);
43362
- this.#events.set(sessionId, stored);
43463
+ #loadStoredEvents = (sessionId) => {
43464
+ const stored = this.#store.readExecutingPromptEventsV2(sessionId);
43363
43465
  const lastPosition = stored.at(-1)?.position;
43364
43466
  if (lastPosition !== void 0) {
43365
43467
  this.#positions.set(sessionId, Number(lastPosition));
@@ -43370,25 +43472,37 @@ var DaemonSessionEventLogV2 = class {
43370
43472
  if (this.#loadedRequestSessions.has(sessionId)) {
43371
43473
  return;
43372
43474
  }
43373
- for (const event of this.#eventsFor(sessionId)) {
43475
+ for (const event of this.#loadStoredEvents(sessionId)) {
43476
+ if (event.type === "acp") {
43477
+ const executing = [...this.#requests.values()].find(
43478
+ (request) => request.sessionId === sessionId && request.kind === "executing"
43479
+ );
43480
+ if (executing !== void 0) {
43481
+ this.#requests.set(executing.commandId, {
43482
+ ...executing,
43483
+ eventTail: { event, previous: executing.eventTail }
43484
+ });
43485
+ }
43486
+ continue;
43487
+ }
43374
43488
  const payload = event.payload;
43375
43489
  if (payload.kind === "prompt.requested") {
43376
43490
  this.#requests.set(payload.commandId, {
43377
43491
  commandId: payload.commandId,
43378
- events: [event],
43492
+ eventTail: { event, previous: null },
43379
43493
  kind: "requested",
43380
43494
  sessionId
43381
43495
  });
43382
43496
  continue;
43383
43497
  }
43384
- if (payload.kind === "acp.session.update") {
43498
+ if ("event" in payload) {
43385
43499
  const executing = [...this.#requests.values()].find(
43386
43500
  (request) => request.sessionId === sessionId && request.kind === "executing"
43387
43501
  );
43388
43502
  if (executing !== void 0) {
43389
43503
  this.#requests.set(executing.commandId, {
43390
43504
  ...executing,
43391
- events: [...executing.events, event]
43505
+ eventTail: { event, previous: executing.eventTail }
43392
43506
  });
43393
43507
  }
43394
43508
  continue;
@@ -43400,13 +43514,12 @@ var DaemonSessionEventLogV2 = class {
43400
43514
  if (state === void 0) {
43401
43515
  continue;
43402
43516
  }
43403
- const events = [...state.events, event];
43404
43517
  if (payload.kind === "prompt.started") {
43405
43518
  this.#requests.set(payload.commandId, {
43406
43519
  attemptId: payload.attemptId,
43407
43520
  commandId: payload.commandId,
43408
43521
  epoch: payload.epoch,
43409
- events,
43522
+ eventTail: { event, previous: state.eventTail },
43410
43523
  kind: "executing",
43411
43524
  sessionId
43412
43525
  });
@@ -43417,31 +43530,41 @@ var DaemonSessionEventLogV2 = class {
43417
43530
  this.#loadedRequestSessions.add(sessionId);
43418
43531
  };
43419
43532
  #append = (sessionId, payload) => {
43420
- this.#eventsFor(sessionId);
43533
+ this.#loadRequests(sessionId);
43421
43534
  const position = (this.#positions.get(sessionId) ?? 0) + 1;
43422
43535
  const event = {
43423
43536
  eventId: `event-${crypto.randomUUID()}`,
43424
- payload,
43537
+ ...payload,
43425
43538
  position: position.toString(),
43426
43539
  provenance: { kind: "original" },
43427
43540
  recordedAt: (/* @__PURE__ */ new Date()).toISOString(),
43428
43541
  sessionId
43429
43542
  };
43430
- this.#store.appendEventV2(event);
43431
43543
  this.#positions.set(sessionId, position);
43432
- this.#events.set(sessionId, [...this.#eventsFor(sessionId), event]);
43433
43544
  this.#publisher.publishV2(event);
43434
43545
  return event;
43435
43546
  };
43436
43547
  requested = (command) => {
43548
+ const content = promptContent(command);
43437
43549
  const event = this.#append(command.sessionId, {
43438
- commandId: command.commandId,
43439
- content: promptContent(command),
43440
- kind: "prompt.requested"
43550
+ payload: { commandId: command.commandId, content, kind: "prompt.requested" },
43551
+ type: "lifecycle-metadata"
43441
43552
  });
43553
+ let eventTail = { event, previous: null };
43554
+ for (const block of content) {
43555
+ const userMessageEvent = this.#append(command.sessionId, {
43556
+ payload: {
43557
+ content: block,
43558
+ messageId: command.commandId,
43559
+ sessionUpdate: "user_message_chunk"
43560
+ },
43561
+ type: "acp"
43562
+ });
43563
+ eventTail = { event: userMessageEvent, previous: eventTail };
43564
+ }
43442
43565
  this.#requests.set(command.commandId, {
43443
43566
  commandId: command.commandId,
43444
- events: [event],
43567
+ eventTail,
43445
43568
  kind: "requested",
43446
43569
  sessionId: command.sessionId
43447
43570
  });
@@ -43452,39 +43575,85 @@ var DaemonSessionEventLogV2 = class {
43452
43575
  if (request?.sessionId !== sessionId) {
43453
43576
  return;
43454
43577
  }
43455
- const event = this.#append(sessionId, { attemptId, commandId, epoch, kind: "prompt.started" });
43578
+ const event = this.#append(sessionId, {
43579
+ payload: { attemptId, commandId, epoch, kind: "prompt.started" },
43580
+ type: "lifecycle-metadata"
43581
+ });
43456
43582
  this.#requests.set(commandId, {
43457
43583
  attemptId,
43458
43584
  commandId,
43459
43585
  epoch,
43460
- events: [...request.events, event],
43586
+ eventTail: { event, previous: request.eventTail },
43461
43587
  kind: "executing",
43462
43588
  sessionId
43463
43589
  });
43590
+ this.#store.startExecutingPromptEventsV2(sessionId, eventArray({ event, previous: request.eventTail }));
43464
43591
  };
43465
- acpUpdate = (sessionId, update) => {
43592
+ record = (sessionId, payload) => {
43466
43593
  this.#loadRequests(sessionId);
43467
- const event = this.#append(sessionId, { kind: "acp.session.update", update });
43594
+ const event = this.#append(sessionId, payload);
43595
+ this.#appendToExecutingRequest(sessionId, event);
43596
+ };
43597
+ #appendToExecutingRequest = (sessionId, event) => {
43468
43598
  const executing = [...this.#requests.values()].find(
43469
43599
  (request) => request.sessionId === sessionId && request.kind === "executing"
43470
43600
  );
43471
43601
  if (executing !== void 0) {
43472
- this.#requests.set(executing.commandId, { ...executing, events: [...executing.events, event] });
43602
+ this.#requests.set(executing.commandId, {
43603
+ ...executing,
43604
+ eventTail: { event, previous: executing.eventTail }
43605
+ });
43606
+ this.#store.appendExecutingPromptEventV2(event);
43473
43607
  }
43474
43608
  };
43609
+ queueChanged = (sessionId) => {
43610
+ const event = this.#append(sessionId, {
43611
+ payload: { kind: "session.queue.changed" },
43612
+ type: "lifecycle-metadata"
43613
+ });
43614
+ this.#appendToExecutingRequest(sessionId, event);
43615
+ };
43475
43616
  completed = (sessionId, commandId, stopReason) => {
43476
- this.#append(sessionId, { commandId, kind: "prompt.completed", stopReason });
43617
+ this.#loadRequests(sessionId);
43618
+ const request = this.#requests.get(commandId);
43619
+ const event = this.#append(sessionId, {
43620
+ payload: { commandId, kind: "prompt.completed", stopReason },
43621
+ type: "lifecycle-metadata"
43622
+ });
43477
43623
  this.#requests.delete(commandId);
43624
+ if (request?.kind === "executing" && request.sessionId === sessionId) {
43625
+ this.#store.clearExecutingPromptEventsV2(sessionId);
43626
+ } else {
43627
+ this.#appendToExecutingRequest(sessionId, event);
43628
+ }
43478
43629
  };
43479
43630
  failed = (sessionId, commandId, code, message) => {
43480
43631
  this.#loadRequests(sessionId);
43481
43632
  const request = this.#requests.get(commandId);
43633
+ let event;
43482
43634
  if (request?.kind === "executing" && request.commandId === commandId) {
43483
- this.#append(sessionId, { attemptId: request.attemptId, code, commandId, kind: "prompt.failed", message });
43635
+ event = this.#append(sessionId, {
43636
+ payload: {
43637
+ attemptId: request.attemptId,
43638
+ code,
43639
+ commandId,
43640
+ kind: "prompt.failed",
43641
+ message
43642
+ },
43643
+ type: "lifecycle-metadata"
43644
+ });
43484
43645
  } else {
43485
- this.#append(sessionId, { code, commandId, kind: "prompt.failed-before-start", message });
43646
+ event = this.#append(sessionId, {
43647
+ payload: { code, commandId, kind: "prompt.failed-before-start", message },
43648
+ type: "lifecycle-metadata"
43649
+ });
43486
43650
  }
43487
43651
  this.#requests.delete(commandId);
43652
+ if (request?.kind === "executing" && request.sessionId === sessionId) {
43653
+ this.#store.clearExecutingPromptEventsV2(sessionId);
43654
+ } else {
43655
+ this.#appendToExecutingRequest(sessionId, event);
43656
+ }
43488
43657
  };
43489
43658
  executingPromptRequest = (sessionId) => {
43490
43659
  this.#loadRequests(sessionId);
@@ -43494,42 +43663,15 @@ var DaemonSessionEventLogV2 = class {
43494
43663
  if (request?.kind !== "executing") {
43495
43664
  return null;
43496
43665
  }
43497
- const events = request.events.slice(-EXECUTING_PROMPT_EVENT_LIMIT);
43666
+ const requestEvents = eventArray(request.eventTail);
43667
+ const events = requestEvents.slice(-EXECUTING_PROMPT_EVENT_LIMIT);
43498
43668
  return {
43499
43669
  attemptId: request.attemptId,
43500
43670
  commandId: request.commandId,
43501
43671
  epoch: request.epoch,
43502
43672
  events,
43503
43673
  tailCursor: events.at(-1)?.eventId ?? "",
43504
- truncated: events.length < request.events.length
43505
- };
43506
- };
43507
- recovery = (sessionId, eventLimit, cursor) => {
43508
- const events = this.#eventsFor(sessionId);
43509
- if (events.length === 0) {
43510
- return null;
43511
- }
43512
- const executingPromptRequest = this.executingPromptRequest(sessionId);
43513
- const executingRequestState = [...this.#requests.values()].find(
43514
- (request) => request.sessionId === sessionId && request.kind === "executing"
43515
- );
43516
- const firstExecutingPosition = executingRequestState?.events[0]?.position;
43517
- const historyEvents = firstExecutingPosition === void 0 ? events : events.filter((event) => BigInt(event.position) < BigInt(firstExecutingPosition));
43518
- const endEvent = cursor === null ? historyEvents.length : decodeLocalEventCursor(sessionId, cursor).endEvent;
43519
- if (endEvent > historyEvents.length) {
43520
- throw new AcpExecutionError("The native Session event cursor is invalid", {}, "invalid_cursor");
43521
- }
43522
- const startEvent = Math.max(0, endEvent - eventLimit);
43523
- const pageEvents = historyEvents.slice(startEvent, endEvent);
43524
- return {
43525
- executingPromptRequest,
43526
- history: {
43527
- events: pageEvents,
43528
- nextCursor: startEvent === 0 ? null : encodeLocalEventCursor({ endEvent: startEvent, sessionId }),
43529
- tailCursor: pageEvents.at(-1)?.eventId ?? "",
43530
- truncated: startEvent > 0,
43531
- version: 2
43532
- }
43674
+ truncated: events.length < requestEvents.length
43533
43675
  };
43534
43676
  };
43535
43677
  };
@@ -43611,7 +43753,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
43611
43753
  publisher.publish(sessionId, activeTurns.recordEvent(event));
43612
43754
  };
43613
43755
  const agentRuntime = new AgentRuntimeManager(
43614
- new DaemonAcpObserver(recordSessionEvent, eventLogV2.acpUpdate),
43756
+ new DaemonAcpObserver(recordSessionEvent, eventLogV2.record),
43615
43757
  sessionStore,
43616
43758
  {
43617
43759
  read: async (options2, nativeSessionId, nativeTurn) => options2.agent.id === "codex" ? (await readCodexFullHistory(