@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/index.js CHANGED
@@ -21515,8 +21515,15 @@ var acpSessionUpdateV2Schema = external_exports.discriminatedUnion("sessionUpdat
21515
21515
  }).readonly()
21516
21516
  ]);
21517
21517
  var lifecycleBase = { commandId: identifierStringSchema };
21518
- var sessionEventPayloadV2Schema = external_exports.discriminatedUnion("kind", [
21519
- external_exports.strictObject({ kind: external_exports.literal("acp.session.update"), update: acpSessionUpdateV2Schema }).readonly(),
21518
+ var lifecycleMetadataV2Schema = external_exports.discriminatedUnion("kind", [
21519
+ external_exports.strictObject({ kind: external_exports.literal("session.queue.changed") }).readonly(),
21520
+ external_exports.strictObject({ event: sessionPermissionRequestedEventSchema, kind: external_exports.literal("session.permission.requested") }).readonly(),
21521
+ external_exports.strictObject({ event: sessionPermissionResolvedEventSchema, kind: external_exports.literal("session.permission.resolved") }).readonly(),
21522
+ external_exports.strictObject({
21523
+ event: sessionElicitationRequestedEventSchema,
21524
+ kind: external_exports.literal("session.elicitation.requested")
21525
+ }).readonly(),
21526
+ external_exports.strictObject({ event: sessionElicitationResolvedEventSchema, kind: external_exports.literal("session.elicitation.resolved") }).readonly(),
21520
21527
  external_exports.strictObject({
21521
21528
  ...lifecycleBase,
21522
21529
  content: external_exports.array(contentBlockV2Schema).min(1).max(100).readonly(),
@@ -21538,6 +21545,10 @@ var sessionEventPayloadV2Schema = external_exports.discriminatedUnion("kind", [
21538
21545
  message: external_exports.string().min(1).max(500)
21539
21546
  }).readonly()
21540
21547
  ]);
21548
+ var sessionEventPayloadV2Schema = external_exports.discriminatedUnion("type", [
21549
+ external_exports.strictObject({ payload: acpSessionUpdateV2Schema, type: external_exports.literal("acp") }).readonly(),
21550
+ external_exports.strictObject({ payload: lifecycleMetadataV2Schema, type: external_exports.literal("lifecycle-metadata") }).readonly()
21551
+ ]);
21541
21552
  var positionSchema = external_exports.string().regex(/^(0|[1-9][0-9]*)$/);
21542
21553
  var provenanceSchema = external_exports.discriminatedUnion("kind", [
21543
21554
  external_exports.strictObject({ kind: external_exports.literal("original") }).readonly(),
@@ -21554,13 +21565,62 @@ var provenanceSchema = external_exports.discriminatedUnion("kind", [
21554
21565
  sourceSessionId: identifierStringSchema
21555
21566
  }).readonly()
21556
21567
  ]);
21557
- var sessionEventV2Schema = external_exports.strictObject({
21568
+ var sessionEventFieldsV2 = {
21558
21569
  eventId: identifierStringSchema,
21559
- payload: sessionEventPayloadV2Schema,
21560
21570
  position: positionSchema,
21561
21571
  provenance: provenanceSchema,
21562
21572
  recordedAt: external_exports.iso.datetime({ offset: true }),
21563
21573
  sessionId: identifierStringSchema
21574
+ };
21575
+ var sessionEventV2Schema = external_exports.discriminatedUnion("type", [
21576
+ external_exports.strictObject({ ...sessionEventFieldsV2, payload: acpSessionUpdateV2Schema, type: external_exports.literal("acp") }).readonly(),
21577
+ external_exports.strictObject({
21578
+ ...sessionEventFieldsV2,
21579
+ payload: lifecycleMetadataV2Schema,
21580
+ type: external_exports.literal("lifecycle-metadata")
21581
+ }).readonly()
21582
+ ]);
21583
+ var sessionExportV2Schema = external_exports.strictObject({
21584
+ binding: external_exports.strictObject({
21585
+ bindingId: identifierStringSchema,
21586
+ runtimeId: identifierStringSchema
21587
+ }).readonly(),
21588
+ events: external_exports.array(sessionEventV2Schema).max(MAX_EVENT_COUNT).readonly(),
21589
+ sessionId: identifierStringSchema,
21590
+ truncated: external_exports.boolean()
21591
+ }).readonly().superRefine((session, context) => {
21592
+ let previousPosition = 0n;
21593
+ const eventIds = /* @__PURE__ */ new Set();
21594
+ for (const [index2, event] of session.events.entries()) {
21595
+ if (event.sessionId !== session.sessionId) {
21596
+ context.addIssue({
21597
+ code: "custom",
21598
+ message: "Exported event belongs to a different Session",
21599
+ path: ["events", index2, "sessionId"]
21600
+ });
21601
+ }
21602
+ const position = BigInt(event.position);
21603
+ if (position <= previousPosition) {
21604
+ context.addIssue({
21605
+ code: "custom",
21606
+ message: "Exported events are not in increasing position order",
21607
+ path: ["events", index2, "position"]
21608
+ });
21609
+ }
21610
+ if (eventIds.has(event.eventId)) {
21611
+ context.addIssue({
21612
+ code: "custom",
21613
+ message: "Exported event identities are not unique",
21614
+ path: ["events", index2, "eventId"]
21615
+ });
21616
+ }
21617
+ previousPosition = position;
21618
+ eventIds.add(event.eventId);
21619
+ }
21620
+ });
21621
+ var mobiusSessionExportV2Schema = external_exports.strictObject({
21622
+ formatVersion: external_exports.literal("2"),
21623
+ session: sessionExportV2Schema
21564
21624
  }).readonly();
21565
21625
  var sessionEventEnvelopeV2Schema = external_exports.strictObject({ event: sessionEventV2Schema, kind: external_exports.literal(SESSION_EVENT_V2_KIND) }).readonly();
21566
21626
  var sessionEventLogPageV2Schema = external_exports.strictObject({
@@ -30858,8 +30918,15 @@ var MemoryAcpSessionStore = class {
30858
30918
  #sessions = /* @__PURE__ */ new Map();
30859
30919
  #deleted = /* @__PURE__ */ new Set();
30860
30920
  #eventsV2 = /* @__PURE__ */ new Map();
30861
- appendEventV2 = (event) => {
30862
- this.#eventsV2.set(event.sessionId, [...this.#eventsV2.get(event.sessionId) ?? [], event]);
30921
+ appendExecutingPromptEventV2 = (event) => {
30922
+ const events = this.#eventsV2.get(event.sessionId);
30923
+ if (events === void 0) {
30924
+ throw new Error("The executing prompt event log has not started");
30925
+ }
30926
+ events.push(event);
30927
+ };
30928
+ clearExecutingPromptEventsV2 = (sessionId) => {
30929
+ this.#eventsV2.delete(sessionId);
30863
30930
  };
30864
30931
  close = () => {
30865
30932
  this.#sessions.clear();
@@ -30890,7 +30957,12 @@ var MemoryAcpSessionStore = class {
30890
30957
  this.#sessions.delete(sessionId);
30891
30958
  this.#eventsV2.delete(sessionId);
30892
30959
  };
30893
- readEventsV2 = (sessionId) => this.#eventsV2.get(sessionId) ?? [];
30960
+ readExecutingPromptEventsV2 = (sessionId) => [
30961
+ ...this.#eventsV2.get(sessionId) ?? []
30962
+ ];
30963
+ startExecutingPromptEventsV2 = (sessionId, events) => {
30964
+ this.#eventsV2.set(sessionId, [...events]);
30965
+ };
30894
30966
  write = (session) => {
30895
30967
  this.#sessions.set(session.sessionId, session);
30896
30968
  };
@@ -30958,7 +31030,7 @@ var SqliteAcpSessionStore = class {
30958
31030
  close = () => {
30959
31031
  this.#sqliteDatabase.close();
30960
31032
  };
30961
- appendEventV2 = (event) => {
31033
+ appendExecutingPromptEventV2 = (event) => {
30962
31034
  this.#database.insert(sessionEventV2).values({
30963
31035
  eventId: event.eventId,
30964
31036
  eventJson: JSON.stringify(event),
@@ -30966,6 +31038,22 @@ var SqliteAcpSessionStore = class {
30966
31038
  sessionId: event.sessionId
30967
31039
  }).run();
30968
31040
  };
31041
+ clearExecutingPromptEventsV2 = (sessionId) => {
31042
+ this.#database.delete(sessionEventV2).where(eq(sessionEventV2.sessionId, sessionId)).run();
31043
+ };
31044
+ startExecutingPromptEventsV2 = (sessionId, events) => {
31045
+ this.#database.transaction((transaction) => {
31046
+ transaction.delete(sessionEventV2).where(eq(sessionEventV2.sessionId, sessionId)).run();
31047
+ for (const event of events) {
31048
+ transaction.insert(sessionEventV2).values({
31049
+ eventId: event.eventId,
31050
+ eventJson: JSON.stringify(event),
31051
+ position: Number(event.position),
31052
+ sessionId: event.sessionId
31053
+ }).run();
31054
+ }
31055
+ });
31056
+ };
30969
31057
  findNative = (agentId, nativeSessionId) => this.#database.select().from(acpSession).where(and(eq(acpSession.agentId, agentId), eq(acpSession.nativeSessionId, nativeSessionId))).all().map(decodeStoredSession);
30970
31058
  list = () => this.#database.select().from(acpSession).orderBy(desc(acpSession.updatedAt)).all().map(decodeStoredSession);
30971
31059
  markDeleted = (agentId, nativeSessionId) => {
@@ -30988,7 +31076,7 @@ var SqliteAcpSessionStore = class {
30988
31076
  const row = this.#database.select().from(acpSession).where(eq(acpSession.sessionId, sessionId)).get();
30989
31077
  return row === void 0 ? new MissingAcpStoredSession() : new FoundAcpStoredSession(decodeStoredSession(row));
30990
31078
  };
30991
- 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));
31079
+ 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));
30992
31080
  remove = (sessionId) => {
30993
31081
  this.#database.transaction((transaction) => {
30994
31082
  transaction.delete(acpSession).where(eq(acpSession.sessionId, sessionId)).run();
@@ -31054,6 +31142,7 @@ var AgentSession = class _AgentSession {
31054
31142
  #configRevision = 0;
31055
31143
  #configOptions = [];
31056
31144
  #lastTerminalCommandId = null;
31145
+ #nativeHistoryOwnership = { kind: "unbound" };
31057
31146
  #prompted = false;
31058
31147
  #nativePrompt = null;
31059
31148
  #sessionLoad = { kind: "not-requested" };
@@ -31174,6 +31263,9 @@ var AgentSession = class _AgentSession {
31174
31263
  return await embedLocalHistoryImages(await loaded.history.snapshot(), signal);
31175
31264
  };
31176
31265
  loadHistoryEventsV2 = async (eventLimit, cursor, signal) => {
31266
+ if (!this.#prompted && this.#nativeHistoryOwnership.kind === "fresh-session") {
31267
+ return new AcpHistoryReplay().eventPage(eventLimit, cursor);
31268
+ }
31177
31269
  if (!this.#capabilities.loadSession) {
31178
31270
  throw new AcpExecutionError(
31179
31271
  "This Agent restores context but does not provide message history.",
@@ -31463,6 +31555,7 @@ var AgentSession = class _AgentSession {
31463
31555
  )
31464
31556
  );
31465
31557
  this.selectNativeSession(created.sessionId);
31558
+ this.#nativeHistoryOwnership = { kind: "fresh-session" };
31466
31559
  lifecycleResponse = created;
31467
31560
  }
31468
31561
  this.#configOptions = this.#sessionConfigProtocol.normalizeLifecycle(lifecycleResponse);
@@ -31666,6 +31759,19 @@ var AgentSession = class _AgentSession {
31666
31759
  if (this.#turn.running) {
31667
31760
  throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
31668
31761
  }
31762
+ switch (this.#sessionLoad.kind) {
31763
+ case "not-requested":
31764
+ break;
31765
+ case "loaded":
31766
+ this.#sessionLoad = { kind: "not-requested" };
31767
+ break;
31768
+ case "capturing":
31769
+ throw new AcpExecutionError("Session history is still loading", {}, "session_busy");
31770
+ default: {
31771
+ const unexpected = this.#sessionLoad;
31772
+ throw new Error(`Unexpected Session load state: ${JSON.stringify(unexpected)}`);
31773
+ }
31774
+ }
31669
31775
  const prompt = this.buildPrompt(options);
31670
31776
  if (this.#sessionTitle === null || this.#sessionTitle.length === 0) {
31671
31777
  this.#sessionTitle = truncate2(options.prompt, 500);
@@ -31826,12 +31932,15 @@ var AgentSession = class _AgentSession {
31826
31932
  onElicitation = (request, signal) => this.#interactions.onElicitation(request, signal);
31827
31933
  onElicitationComplete = (notification) => this.#interactions.onElicitationComplete(notification);
31828
31934
  onUpdate = (notification) => this.#updates.receive(notification);
31829
- selectNativeSession = (sessionId) => this.#updates.select(sessionId);
31935
+ selectNativeSession = (sessionId) => {
31936
+ this.#updates.select(sessionId);
31937
+ this.#nativeHistoryOwnership = { kind: "agent-owned" };
31938
+ };
31830
31939
  #processUpdate = async (notification) => {
31831
31940
  this.assertNativeSession(notification.sessionId);
31832
31941
  const update = notification.update;
31833
31942
  const rawUpdate = decodeAcpSessionUpdateV2(JSON.stringify(update));
31834
- if (this.#sessionLoad.kind !== "not-requested") {
31943
+ if (this.#sessionLoad.kind === "capturing") {
31835
31944
  await this.#sessionLoad.history.record(update, rawUpdate);
31836
31945
  } else {
31837
31946
  const onAcpUpdate = this.#getObserver().onAcpUpdate;
@@ -33915,16 +34024,15 @@ var threadStartResponseSchema = external_exports.object({
33915
34024
  serviceTier: boundedText(256).nullish(),
33916
34025
  thread: external_exports.object({ id: boundedText(256) })
33917
34026
  });
34027
+ var threadTurnSchema = external_exports.object({
34028
+ items: external_exports.array(external_exports.unknown()).max(1e5)
34029
+ });
34030
+ var threadTurnsSchema = external_exports.array(threadTurnSchema).max(1e5);
33918
34031
  var threadLifecycleResponseSchema = external_exports.object({
33919
34032
  model: boundedText(256).nullish(),
33920
34033
  reasoningEffort: boundedText(256).nullish(),
33921
34034
  serviceTier: boundedText(256).nullish(),
33922
- thread: external_exports.object({ id: boundedText(256) }),
33923
- turns: external_exports.array(
33924
- external_exports.object({
33925
- items: external_exports.array(external_exports.unknown()).max(1e5)
33926
- })
33927
- ).max(1e5).nullish()
34035
+ thread: external_exports.object({ id: boundedText(256), turns: threadTurnsSchema })
33928
34036
  });
33929
34037
  var threadResumeResponseSchema = threadLifecycleResponseSchema;
33930
34038
  var threadForkResponseSchema = threadLifecycleResponseSchema;
@@ -34939,7 +35047,7 @@ var CodexAcpAgent = class {
34939
35047
  this.#nativeSessionId = resumed.thread.id;
34940
35048
  this.#settings.selectRestoredThread(resumed);
34941
35049
  await this.#settings.probeCollaborationMode(this.#nativeSessionId, context.signal);
34942
- await this.#replayHistory(resumed.turns);
35050
+ await this.#replayHistory(resumed.thread.turns);
34943
35051
  await this.#emitAvailableCommands();
34944
35052
  return { configOptions: this.#settings.configOptions() };
34945
35053
  }).onRequest(methods4.agent.session.fork, async (context) => {
@@ -34957,7 +35065,7 @@ var CodexAcpAgent = class {
34957
35065
  this.#nativeSessionId = forked.thread.id;
34958
35066
  this.#settings.selectRestoredThread(forked);
34959
35067
  await this.#settings.probeCollaborationMode(this.#nativeSessionId, context.signal);
34960
- await this.#replayHistory(forked.turns);
35068
+ await this.#replayHistory(forked.thread.turns);
34961
35069
  await this.#emitAvailableCommands();
34962
35070
  return { configOptions: this.#settings.configOptions(), sessionId: forked.thread.id };
34963
35071
  }).onRequest(methods4.agent.session.resume, async (context) => {
@@ -39238,7 +39346,7 @@ var DaemonAcpObserver = class {
39238
39346
  this.#recordV2 = recordV2;
39239
39347
  }
39240
39348
  onAcpUpdate = (sessionId, update) => {
39241
- this.#recordV2(sessionId, update);
39349
+ this.#recordV2(sessionId, { payload: update, type: "acp" });
39242
39350
  return Promise.resolve();
39243
39351
  };
39244
39352
  onCommands = (event) => {
@@ -39255,10 +39363,18 @@ var DaemonAcpObserver = class {
39255
39363
  };
39256
39364
  onElicitation = (event) => {
39257
39365
  this.#record(event.sessionId, event);
39366
+ this.#recordV2(event.sessionId, {
39367
+ payload: { event, kind: "session.elicitation.requested" },
39368
+ type: "lifecycle-metadata"
39369
+ });
39258
39370
  return Promise.resolve();
39259
39371
  };
39260
39372
  onElicitationResolved = (event) => {
39261
39373
  this.#record(event.sessionId, event);
39374
+ this.#recordV2(event.sessionId, {
39375
+ payload: { event, kind: "session.elicitation.resolved" },
39376
+ type: "lifecycle-metadata"
39377
+ });
39262
39378
  return Promise.resolve();
39263
39379
  };
39264
39380
  onInfo = (event) => {
@@ -39267,10 +39383,18 @@ var DaemonAcpObserver = class {
39267
39383
  };
39268
39384
  onPermission = (event) => {
39269
39385
  this.#record(event.sessionId, event);
39386
+ this.#recordV2(event.sessionId, {
39387
+ payload: { event, kind: "session.permission.requested" },
39388
+ type: "lifecycle-metadata"
39389
+ });
39270
39390
  return Promise.resolve();
39271
39391
  };
39272
39392
  onPermissionResolved = (event) => {
39273
39393
  this.#record(event.sessionId, event);
39394
+ this.#recordV2(event.sessionId, {
39395
+ payload: { event, kind: "session.permission.resolved" },
39396
+ type: "lifecycle-metadata"
39397
+ });
39274
39398
  return Promise.resolve();
39275
39399
  };
39276
39400
  onUsage = (event) => {
@@ -42511,25 +42635,16 @@ function replayEvent(sessionId, position, update) {
42511
42635
  const eventId = `native-${createHash6("sha256").update(sessionId).update(":").update(position.toString()).update(":").update(encoded).digest("hex")}`;
42512
42636
  return {
42513
42637
  eventId,
42514
- payload: { kind: "acp.session.update", update },
42638
+ payload: update,
42515
42639
  position: position.toString(),
42516
42640
  provenance: { kind: "original" },
42517
42641
  recordedAt: "1970-01-01T00:00:00.000Z",
42518
- sessionId
42642
+ sessionId,
42643
+ type: "acp"
42519
42644
  };
42520
42645
  }
42521
- async function executeSessionLiveHistoryV2PageLoad(socket, command, config2, directories, audit, sessions, localRecovery, executingPromptRequest, signal) {
42646
+ async function executeSessionLiveHistoryV2PageLoad(socket, command, config2, directories, audit, sessions, executingPromptRequest, signal) {
42522
42647
  try {
42523
- const local = localRecovery(command.sessionId, command.eventLimit, command.cursor);
42524
- if (local !== null) {
42525
- send(socket, {
42526
- events: local,
42527
- kind: "session.live-history.v2.page.loaded",
42528
- requestId: command.requestId,
42529
- sessionId: command.sessionId
42530
- });
42531
- return;
42532
- }
42533
42648
  const resolved = await resolveSessionDirectories(
42534
42649
  directories,
42535
42650
  config2.bindingId,
@@ -43413,7 +43528,10 @@ function createDaemonCommandHandler({
43413
43528
  timer,
43414
43529
  resolveEnvironment: resolveAgentCatalogEnvironment
43415
43530
  });
43416
- const queueChanged = (sessionId) => publisher.publish(sessionId, { kind: "session.queue.changed", sessionId });
43531
+ const queueChanged = (sessionId) => {
43532
+ publisher.publish(sessionId, { kind: "session.queue.changed", sessionId });
43533
+ eventLogV2.queueChanged(sessionId);
43534
+ };
43417
43535
  const activeTurnRecovery = (sessionId) => activeTurns.recovery((command) => command.sessionId === sessionId);
43418
43536
  const nativeRequestHandler = createNativeSessionRequestHandler({
43419
43537
  audit,
@@ -43463,7 +43581,6 @@ function createDaemonCommandHandler({
43463
43581
  directories,
43464
43582
  audit,
43465
43583
  sessions,
43466
- eventLogV2.recovery,
43467
43584
  eventLogV2.executingPromptRequest,
43468
43585
  signal
43469
43586
  );
@@ -44159,6 +44276,15 @@ var systemDaemonTimer = new SystemDaemonTimer();
44159
44276
 
44160
44277
  // src/session-event-log-v2.ts
44161
44278
  var EXECUTING_PROMPT_EVENT_LIMIT = 1e4;
44279
+ function eventArray(tail) {
44280
+ const reversed = [];
44281
+ let node2 = tail;
44282
+ while (node2 !== null) {
44283
+ reversed.push(node2.event);
44284
+ node2 = node2.previous;
44285
+ }
44286
+ return reversed.reverse();
44287
+ }
44162
44288
  function promptContent(command) {
44163
44289
  const content = [];
44164
44290
  if (command.prompt.length > 0) {
@@ -44182,27 +44308,8 @@ function promptContent(command) {
44182
44308
  }
44183
44309
  return content;
44184
44310
  }
44185
- function encodeLocalEventCursor(cursor) {
44186
- return Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url");
44187
- }
44188
- function decodeLocalEventCursor(sessionId, cursor) {
44189
- try {
44190
- const value = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
44191
- if (typeof value !== "object" || value === null || Array.isArray(value) || Object.keys(value).sort().join(",") !== "endEvent,sessionId" || Reflect.get(value, "sessionId") !== sessionId) {
44192
- throw new Error("Invalid V2 event cursor target");
44193
- }
44194
- const endEvent = Reflect.get(value, "endEvent");
44195
- if (typeof endEvent !== "number" || !Number.isSafeInteger(endEvent) || endEvent < 0) {
44196
- throw new Error("Invalid V2 event cursor boundary");
44197
- }
44198
- return { endEvent, sessionId };
44199
- } catch (cause) {
44200
- throw new AcpExecutionError("The native Session event cursor is invalid", { cause }, "invalid_cursor");
44201
- }
44202
- }
44203
44311
  var DaemonSessionEventLogV2 = class {
44204
44312
  #positions = /* @__PURE__ */ new Map();
44205
- #events = /* @__PURE__ */ new Map();
44206
44313
  #requests = /* @__PURE__ */ new Map();
44207
44314
  #loadedRequestSessions = /* @__PURE__ */ new Set();
44208
44315
  #publisher;
@@ -44211,13 +44318,8 @@ var DaemonSessionEventLogV2 = class {
44211
44318
  this.#publisher = publisher;
44212
44319
  this.#store = store;
44213
44320
  }
44214
- #eventsFor = (sessionId) => {
44215
- const cached2 = this.#events.get(sessionId);
44216
- if (cached2 !== void 0) {
44217
- return cached2;
44218
- }
44219
- const stored = this.#store.readEventsV2(sessionId);
44220
- this.#events.set(sessionId, stored);
44321
+ #loadStoredEvents = (sessionId) => {
44322
+ const stored = this.#store.readExecutingPromptEventsV2(sessionId);
44221
44323
  const lastPosition = stored.at(-1)?.position;
44222
44324
  if (lastPosition !== void 0) {
44223
44325
  this.#positions.set(sessionId, Number(lastPosition));
@@ -44228,25 +44330,37 @@ var DaemonSessionEventLogV2 = class {
44228
44330
  if (this.#loadedRequestSessions.has(sessionId)) {
44229
44331
  return;
44230
44332
  }
44231
- for (const event of this.#eventsFor(sessionId)) {
44333
+ for (const event of this.#loadStoredEvents(sessionId)) {
44334
+ if (event.type === "acp") {
44335
+ const executing = [...this.#requests.values()].find(
44336
+ (request) => request.sessionId === sessionId && request.kind === "executing"
44337
+ );
44338
+ if (executing !== void 0) {
44339
+ this.#requests.set(executing.commandId, {
44340
+ ...executing,
44341
+ eventTail: { event, previous: executing.eventTail }
44342
+ });
44343
+ }
44344
+ continue;
44345
+ }
44232
44346
  const payload = event.payload;
44233
44347
  if (payload.kind === "prompt.requested") {
44234
44348
  this.#requests.set(payload.commandId, {
44235
44349
  commandId: payload.commandId,
44236
- events: [event],
44350
+ eventTail: { event, previous: null },
44237
44351
  kind: "requested",
44238
44352
  sessionId
44239
44353
  });
44240
44354
  continue;
44241
44355
  }
44242
- if (payload.kind === "acp.session.update") {
44356
+ if ("event" in payload) {
44243
44357
  const executing = [...this.#requests.values()].find(
44244
44358
  (request) => request.sessionId === sessionId && request.kind === "executing"
44245
44359
  );
44246
44360
  if (executing !== void 0) {
44247
44361
  this.#requests.set(executing.commandId, {
44248
44362
  ...executing,
44249
- events: [...executing.events, event]
44363
+ eventTail: { event, previous: executing.eventTail }
44250
44364
  });
44251
44365
  }
44252
44366
  continue;
@@ -44258,13 +44372,12 @@ var DaemonSessionEventLogV2 = class {
44258
44372
  if (state === void 0) {
44259
44373
  continue;
44260
44374
  }
44261
- const events = [...state.events, event];
44262
44375
  if (payload.kind === "prompt.started") {
44263
44376
  this.#requests.set(payload.commandId, {
44264
44377
  attemptId: payload.attemptId,
44265
44378
  commandId: payload.commandId,
44266
44379
  epoch: payload.epoch,
44267
- events,
44380
+ eventTail: { event, previous: state.eventTail },
44268
44381
  kind: "executing",
44269
44382
  sessionId
44270
44383
  });
@@ -44275,31 +44388,41 @@ var DaemonSessionEventLogV2 = class {
44275
44388
  this.#loadedRequestSessions.add(sessionId);
44276
44389
  };
44277
44390
  #append = (sessionId, payload) => {
44278
- this.#eventsFor(sessionId);
44391
+ this.#loadRequests(sessionId);
44279
44392
  const position = (this.#positions.get(sessionId) ?? 0) + 1;
44280
44393
  const event = {
44281
44394
  eventId: `event-${crypto.randomUUID()}`,
44282
- payload,
44395
+ ...payload,
44283
44396
  position: position.toString(),
44284
44397
  provenance: { kind: "original" },
44285
44398
  recordedAt: (/* @__PURE__ */ new Date()).toISOString(),
44286
44399
  sessionId
44287
44400
  };
44288
- this.#store.appendEventV2(event);
44289
44401
  this.#positions.set(sessionId, position);
44290
- this.#events.set(sessionId, [...this.#eventsFor(sessionId), event]);
44291
44402
  this.#publisher.publishV2(event);
44292
44403
  return event;
44293
44404
  };
44294
44405
  requested = (command) => {
44406
+ const content = promptContent(command);
44295
44407
  const event = this.#append(command.sessionId, {
44296
- commandId: command.commandId,
44297
- content: promptContent(command),
44298
- kind: "prompt.requested"
44408
+ payload: { commandId: command.commandId, content, kind: "prompt.requested" },
44409
+ type: "lifecycle-metadata"
44299
44410
  });
44411
+ let eventTail = { event, previous: null };
44412
+ for (const block of content) {
44413
+ const userMessageEvent = this.#append(command.sessionId, {
44414
+ payload: {
44415
+ content: block,
44416
+ messageId: command.commandId,
44417
+ sessionUpdate: "user_message_chunk"
44418
+ },
44419
+ type: "acp"
44420
+ });
44421
+ eventTail = { event: userMessageEvent, previous: eventTail };
44422
+ }
44300
44423
  this.#requests.set(command.commandId, {
44301
44424
  commandId: command.commandId,
44302
- events: [event],
44425
+ eventTail,
44303
44426
  kind: "requested",
44304
44427
  sessionId: command.sessionId
44305
44428
  });
@@ -44310,39 +44433,85 @@ var DaemonSessionEventLogV2 = class {
44310
44433
  if (request?.sessionId !== sessionId) {
44311
44434
  return;
44312
44435
  }
44313
- const event = this.#append(sessionId, { attemptId, commandId, epoch, kind: "prompt.started" });
44436
+ const event = this.#append(sessionId, {
44437
+ payload: { attemptId, commandId, epoch, kind: "prompt.started" },
44438
+ type: "lifecycle-metadata"
44439
+ });
44314
44440
  this.#requests.set(commandId, {
44315
44441
  attemptId,
44316
44442
  commandId,
44317
44443
  epoch,
44318
- events: [...request.events, event],
44444
+ eventTail: { event, previous: request.eventTail },
44319
44445
  kind: "executing",
44320
44446
  sessionId
44321
44447
  });
44448
+ this.#store.startExecutingPromptEventsV2(sessionId, eventArray({ event, previous: request.eventTail }));
44322
44449
  };
44323
- acpUpdate = (sessionId, update) => {
44450
+ record = (sessionId, payload) => {
44324
44451
  this.#loadRequests(sessionId);
44325
- const event = this.#append(sessionId, { kind: "acp.session.update", update });
44452
+ const event = this.#append(sessionId, payload);
44453
+ this.#appendToExecutingRequest(sessionId, event);
44454
+ };
44455
+ #appendToExecutingRequest = (sessionId, event) => {
44326
44456
  const executing = [...this.#requests.values()].find(
44327
44457
  (request) => request.sessionId === sessionId && request.kind === "executing"
44328
44458
  );
44329
44459
  if (executing !== void 0) {
44330
- this.#requests.set(executing.commandId, { ...executing, events: [...executing.events, event] });
44460
+ this.#requests.set(executing.commandId, {
44461
+ ...executing,
44462
+ eventTail: { event, previous: executing.eventTail }
44463
+ });
44464
+ this.#store.appendExecutingPromptEventV2(event);
44331
44465
  }
44332
44466
  };
44467
+ queueChanged = (sessionId) => {
44468
+ const event = this.#append(sessionId, {
44469
+ payload: { kind: "session.queue.changed" },
44470
+ type: "lifecycle-metadata"
44471
+ });
44472
+ this.#appendToExecutingRequest(sessionId, event);
44473
+ };
44333
44474
  completed = (sessionId, commandId, stopReason) => {
44334
- this.#append(sessionId, { commandId, kind: "prompt.completed", stopReason });
44475
+ this.#loadRequests(sessionId);
44476
+ const request = this.#requests.get(commandId);
44477
+ const event = this.#append(sessionId, {
44478
+ payload: { commandId, kind: "prompt.completed", stopReason },
44479
+ type: "lifecycle-metadata"
44480
+ });
44335
44481
  this.#requests.delete(commandId);
44482
+ if (request?.kind === "executing" && request.sessionId === sessionId) {
44483
+ this.#store.clearExecutingPromptEventsV2(sessionId);
44484
+ } else {
44485
+ this.#appendToExecutingRequest(sessionId, event);
44486
+ }
44336
44487
  };
44337
44488
  failed = (sessionId, commandId, code, message) => {
44338
44489
  this.#loadRequests(sessionId);
44339
44490
  const request = this.#requests.get(commandId);
44491
+ let event;
44340
44492
  if (request?.kind === "executing" && request.commandId === commandId) {
44341
- this.#append(sessionId, { attemptId: request.attemptId, code, commandId, kind: "prompt.failed", message });
44493
+ event = this.#append(sessionId, {
44494
+ payload: {
44495
+ attemptId: request.attemptId,
44496
+ code,
44497
+ commandId,
44498
+ kind: "prompt.failed",
44499
+ message
44500
+ },
44501
+ type: "lifecycle-metadata"
44502
+ });
44342
44503
  } else {
44343
- this.#append(sessionId, { code, commandId, kind: "prompt.failed-before-start", message });
44504
+ event = this.#append(sessionId, {
44505
+ payload: { code, commandId, kind: "prompt.failed-before-start", message },
44506
+ type: "lifecycle-metadata"
44507
+ });
44344
44508
  }
44345
44509
  this.#requests.delete(commandId);
44510
+ if (request?.kind === "executing" && request.sessionId === sessionId) {
44511
+ this.#store.clearExecutingPromptEventsV2(sessionId);
44512
+ } else {
44513
+ this.#appendToExecutingRequest(sessionId, event);
44514
+ }
44346
44515
  };
44347
44516
  executingPromptRequest = (sessionId) => {
44348
44517
  this.#loadRequests(sessionId);
@@ -44352,42 +44521,15 @@ var DaemonSessionEventLogV2 = class {
44352
44521
  if (request?.kind !== "executing") {
44353
44522
  return null;
44354
44523
  }
44355
- const events = request.events.slice(-EXECUTING_PROMPT_EVENT_LIMIT);
44524
+ const requestEvents = eventArray(request.eventTail);
44525
+ const events = requestEvents.slice(-EXECUTING_PROMPT_EVENT_LIMIT);
44356
44526
  return {
44357
44527
  attemptId: request.attemptId,
44358
44528
  commandId: request.commandId,
44359
44529
  epoch: request.epoch,
44360
44530
  events,
44361
44531
  tailCursor: events.at(-1)?.eventId ?? "",
44362
- truncated: events.length < request.events.length
44363
- };
44364
- };
44365
- recovery = (sessionId, eventLimit, cursor) => {
44366
- const events = this.#eventsFor(sessionId);
44367
- if (events.length === 0) {
44368
- return null;
44369
- }
44370
- const executingPromptRequest = this.executingPromptRequest(sessionId);
44371
- const executingRequestState = [...this.#requests.values()].find(
44372
- (request) => request.sessionId === sessionId && request.kind === "executing"
44373
- );
44374
- const firstExecutingPosition = executingRequestState?.events[0]?.position;
44375
- const historyEvents = firstExecutingPosition === void 0 ? events : events.filter((event) => BigInt(event.position) < BigInt(firstExecutingPosition));
44376
- const endEvent = cursor === null ? historyEvents.length : decodeLocalEventCursor(sessionId, cursor).endEvent;
44377
- if (endEvent > historyEvents.length) {
44378
- throw new AcpExecutionError("The native Session event cursor is invalid", {}, "invalid_cursor");
44379
- }
44380
- const startEvent = Math.max(0, endEvent - eventLimit);
44381
- const pageEvents = historyEvents.slice(startEvent, endEvent);
44382
- return {
44383
- executingPromptRequest,
44384
- history: {
44385
- events: pageEvents,
44386
- nextCursor: startEvent === 0 ? null : encodeLocalEventCursor({ endEvent: startEvent, sessionId }),
44387
- tailCursor: pageEvents.at(-1)?.eventId ?? "",
44388
- truncated: startEvent > 0,
44389
- version: 2
44390
- }
44532
+ truncated: events.length < requestEvents.length
44391
44533
  };
44392
44534
  };
44393
44535
  };
@@ -44469,7 +44611,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
44469
44611
  publisher.publish(sessionId, activeTurns.recordEvent(event));
44470
44612
  };
44471
44613
  const agentRuntime = new AgentRuntimeManager(
44472
- new DaemonAcpObserver(recordSessionEvent, eventLogV2.acpUpdate),
44614
+ new DaemonAcpObserver(recordSessionEvent, eventLogV2.record),
44473
44615
  sessionStore,
44474
44616
  {
44475
44617
  read: async (options2, nativeSessionId, nativeTurn) => options2.agent.id === "codex" ? (await readCodexFullHistory(