@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/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.156",
3384
+ version: "0.0.158",
3385
3385
  description: "Mobius CLI for pairing and running local AI agent services.",
3386
3386
  type: "module",
3387
3387
  bin: {
@@ -24821,16 +24821,15 @@ var threadStartResponseSchema = external_exports.object({
24821
24821
  serviceTier: boundedText(256).nullish(),
24822
24822
  thread: external_exports.object({ id: boundedText(256) })
24823
24823
  });
24824
+ var threadTurnSchema = external_exports.object({
24825
+ items: external_exports.array(external_exports.unknown()).max(1e5)
24826
+ });
24827
+ var threadTurnsSchema = external_exports.array(threadTurnSchema).max(1e5);
24824
24828
  var threadLifecycleResponseSchema = external_exports.object({
24825
24829
  model: boundedText(256).nullish(),
24826
24830
  reasoningEffort: boundedText(256).nullish(),
24827
24831
  serviceTier: boundedText(256).nullish(),
24828
- thread: external_exports.object({ id: boundedText(256) }),
24829
- turns: external_exports.array(
24830
- external_exports.object({
24831
- items: external_exports.array(external_exports.unknown()).max(1e5)
24832
- })
24833
- ).max(1e5).nullish()
24832
+ thread: external_exports.object({ id: boundedText(256), turns: threadTurnsSchema })
24834
24833
  });
24835
24834
  var threadResumeResponseSchema = threadLifecycleResponseSchema;
24836
24835
  var threadForkResponseSchema = threadLifecycleResponseSchema;
@@ -25845,7 +25844,7 @@ var CodexAcpAgent = class {
25845
25844
  this.#nativeSessionId = resumed.thread.id;
25846
25845
  this.#settings.selectRestoredThread(resumed);
25847
25846
  await this.#settings.probeCollaborationMode(this.#nativeSessionId, context.signal);
25848
- await this.#replayHistory(resumed.turns);
25847
+ await this.#replayHistory(resumed.thread.turns);
25849
25848
  await this.#emitAvailableCommands();
25850
25849
  return { configOptions: this.#settings.configOptions() };
25851
25850
  }).onRequest(methods.agent.session.fork, async (context) => {
@@ -25863,7 +25862,7 @@ var CodexAcpAgent = class {
25863
25862
  this.#nativeSessionId = forked.thread.id;
25864
25863
  this.#settings.selectRestoredThread(forked);
25865
25864
  await this.#settings.probeCollaborationMode(this.#nativeSessionId, context.signal);
25866
- await this.#replayHistory(forked.turns);
25865
+ await this.#replayHistory(forked.thread.turns);
25867
25866
  await this.#emitAvailableCommands();
25868
25867
  return { configOptions: this.#settings.configOptions(), sessionId: forked.thread.id };
25869
25868
  }).onRequest(methods.agent.session.resume, async (context) => {
@@ -30086,8 +30085,15 @@ var acpSessionUpdateV2Schema = external_exports.discriminatedUnion("sessionUpdat
30086
30085
  }).readonly()
30087
30086
  ]);
30088
30087
  var lifecycleBase = { commandId: identifierStringSchema };
30089
- var sessionEventPayloadV2Schema = external_exports.discriminatedUnion("kind", [
30090
- external_exports.strictObject({ kind: external_exports.literal("acp.session.update"), update: acpSessionUpdateV2Schema }).readonly(),
30088
+ var lifecycleMetadataV2Schema = external_exports.discriminatedUnion("kind", [
30089
+ external_exports.strictObject({ kind: external_exports.literal("session.queue.changed") }).readonly(),
30090
+ external_exports.strictObject({ event: sessionPermissionRequestedEventSchema, kind: external_exports.literal("session.permission.requested") }).readonly(),
30091
+ external_exports.strictObject({ event: sessionPermissionResolvedEventSchema, kind: external_exports.literal("session.permission.resolved") }).readonly(),
30092
+ external_exports.strictObject({
30093
+ event: sessionElicitationRequestedEventSchema,
30094
+ kind: external_exports.literal("session.elicitation.requested")
30095
+ }).readonly(),
30096
+ external_exports.strictObject({ event: sessionElicitationResolvedEventSchema, kind: external_exports.literal("session.elicitation.resolved") }).readonly(),
30091
30097
  external_exports.strictObject({
30092
30098
  ...lifecycleBase,
30093
30099
  content: external_exports.array(contentBlockV2Schema).min(1).max(100).readonly(),
@@ -30109,6 +30115,10 @@ var sessionEventPayloadV2Schema = external_exports.discriminatedUnion("kind", [
30109
30115
  message: external_exports.string().min(1).max(500)
30110
30116
  }).readonly()
30111
30117
  ]);
30118
+ var sessionEventPayloadV2Schema = external_exports.discriminatedUnion("type", [
30119
+ external_exports.strictObject({ payload: acpSessionUpdateV2Schema, type: external_exports.literal("acp") }).readonly(),
30120
+ external_exports.strictObject({ payload: lifecycleMetadataV2Schema, type: external_exports.literal("lifecycle-metadata") }).readonly()
30121
+ ]);
30112
30122
  var positionSchema = external_exports.string().regex(/^(0|[1-9][0-9]*)$/);
30113
30123
  var provenanceSchema = external_exports.discriminatedUnion("kind", [
30114
30124
  external_exports.strictObject({ kind: external_exports.literal("original") }).readonly(),
@@ -30125,13 +30135,62 @@ var provenanceSchema = external_exports.discriminatedUnion("kind", [
30125
30135
  sourceSessionId: identifierStringSchema
30126
30136
  }).readonly()
30127
30137
  ]);
30128
- var sessionEventV2Schema = external_exports.strictObject({
30138
+ var sessionEventFieldsV2 = {
30129
30139
  eventId: identifierStringSchema,
30130
- payload: sessionEventPayloadV2Schema,
30131
30140
  position: positionSchema,
30132
30141
  provenance: provenanceSchema,
30133
30142
  recordedAt: external_exports.iso.datetime({ offset: true }),
30134
30143
  sessionId: identifierStringSchema
30144
+ };
30145
+ var sessionEventV2Schema = external_exports.discriminatedUnion("type", [
30146
+ external_exports.strictObject({ ...sessionEventFieldsV2, payload: acpSessionUpdateV2Schema, type: external_exports.literal("acp") }).readonly(),
30147
+ external_exports.strictObject({
30148
+ ...sessionEventFieldsV2,
30149
+ payload: lifecycleMetadataV2Schema,
30150
+ type: external_exports.literal("lifecycle-metadata")
30151
+ }).readonly()
30152
+ ]);
30153
+ var sessionExportV2Schema = external_exports.strictObject({
30154
+ binding: external_exports.strictObject({
30155
+ bindingId: identifierStringSchema,
30156
+ runtimeId: identifierStringSchema
30157
+ }).readonly(),
30158
+ events: external_exports.array(sessionEventV2Schema).max(MAX_EVENT_COUNT).readonly(),
30159
+ sessionId: identifierStringSchema,
30160
+ truncated: external_exports.boolean()
30161
+ }).readonly().superRefine((session, context) => {
30162
+ let previousPosition = 0n;
30163
+ const eventIds = /* @__PURE__ */ new Set();
30164
+ for (const [index2, event] of session.events.entries()) {
30165
+ if (event.sessionId !== session.sessionId) {
30166
+ context.addIssue({
30167
+ code: "custom",
30168
+ message: "Exported event belongs to a different Session",
30169
+ path: ["events", index2, "sessionId"]
30170
+ });
30171
+ }
30172
+ const position = BigInt(event.position);
30173
+ if (position <= previousPosition) {
30174
+ context.addIssue({
30175
+ code: "custom",
30176
+ message: "Exported events are not in increasing position order",
30177
+ path: ["events", index2, "position"]
30178
+ });
30179
+ }
30180
+ if (eventIds.has(event.eventId)) {
30181
+ context.addIssue({
30182
+ code: "custom",
30183
+ message: "Exported event identities are not unique",
30184
+ path: ["events", index2, "eventId"]
30185
+ });
30186
+ }
30187
+ previousPosition = position;
30188
+ eventIds.add(event.eventId);
30189
+ }
30190
+ });
30191
+ var mobiusSessionExportV2Schema = external_exports.strictObject({
30192
+ formatVersion: external_exports.literal("2"),
30193
+ session: sessionExportV2Schema
30135
30194
  }).readonly();
30136
30195
  var sessionEventEnvelopeV2Schema = external_exports.strictObject({ event: sessionEventV2Schema, kind: external_exports.literal(SESSION_EVENT_V2_KIND) }).readonly();
30137
30196
  var sessionEventLogPageV2Schema = external_exports.strictObject({
@@ -39397,8 +39456,15 @@ var MemoryAcpSessionStore = class {
39397
39456
  #sessions = /* @__PURE__ */ new Map();
39398
39457
  #deleted = /* @__PURE__ */ new Set();
39399
39458
  #eventsV2 = /* @__PURE__ */ new Map();
39400
- appendEventV2 = (event) => {
39401
- this.#eventsV2.set(event.sessionId, [...this.#eventsV2.get(event.sessionId) ?? [], event]);
39459
+ appendExecutingPromptEventV2 = (event) => {
39460
+ const events = this.#eventsV2.get(event.sessionId);
39461
+ if (events === void 0) {
39462
+ throw new Error("The executing prompt event log has not started");
39463
+ }
39464
+ events.push(event);
39465
+ };
39466
+ clearExecutingPromptEventsV2 = (sessionId) => {
39467
+ this.#eventsV2.delete(sessionId);
39402
39468
  };
39403
39469
  close = () => {
39404
39470
  this.#sessions.clear();
@@ -39429,7 +39495,12 @@ var MemoryAcpSessionStore = class {
39429
39495
  this.#sessions.delete(sessionId);
39430
39496
  this.#eventsV2.delete(sessionId);
39431
39497
  };
39432
- readEventsV2 = (sessionId) => this.#eventsV2.get(sessionId) ?? [];
39498
+ readExecutingPromptEventsV2 = (sessionId) => [
39499
+ ...this.#eventsV2.get(sessionId) ?? []
39500
+ ];
39501
+ startExecutingPromptEventsV2 = (sessionId, events) => {
39502
+ this.#eventsV2.set(sessionId, [...events]);
39503
+ };
39433
39504
  write = (session) => {
39434
39505
  this.#sessions.set(session.sessionId, session);
39435
39506
  };
@@ -39497,7 +39568,7 @@ var SqliteAcpSessionStore = class {
39497
39568
  close = () => {
39498
39569
  this.#sqliteDatabase.close();
39499
39570
  };
39500
- appendEventV2 = (event) => {
39571
+ appendExecutingPromptEventV2 = (event) => {
39501
39572
  this.#database.insert(sessionEventV2).values({
39502
39573
  eventId: event.eventId,
39503
39574
  eventJson: JSON.stringify(event),
@@ -39505,6 +39576,22 @@ var SqliteAcpSessionStore = class {
39505
39576
  sessionId: event.sessionId
39506
39577
  }).run();
39507
39578
  };
39579
+ clearExecutingPromptEventsV2 = (sessionId) => {
39580
+ this.#database.delete(sessionEventV2).where(eq(sessionEventV2.sessionId, sessionId)).run();
39581
+ };
39582
+ startExecutingPromptEventsV2 = (sessionId, events) => {
39583
+ this.#database.transaction((transaction) => {
39584
+ transaction.delete(sessionEventV2).where(eq(sessionEventV2.sessionId, sessionId)).run();
39585
+ for (const event of events) {
39586
+ transaction.insert(sessionEventV2).values({
39587
+ eventId: event.eventId,
39588
+ eventJson: JSON.stringify(event),
39589
+ position: Number(event.position),
39590
+ sessionId: event.sessionId
39591
+ }).run();
39592
+ }
39593
+ });
39594
+ };
39508
39595
  findNative = (agentId, nativeSessionId) => this.#database.select().from(acpSession).where(and(eq(acpSession.agentId, agentId), eq(acpSession.nativeSessionId, nativeSessionId))).all().map(decodeStoredSession);
39509
39596
  list = () => this.#database.select().from(acpSession).orderBy(desc(acpSession.updatedAt)).all().map(decodeStoredSession);
39510
39597
  markDeleted = (agentId, nativeSessionId) => {
@@ -39527,7 +39614,7 @@ var SqliteAcpSessionStore = class {
39527
39614
  const row = this.#database.select().from(acpSession).where(eq(acpSession.sessionId, sessionId)).get();
39528
39615
  return row === void 0 ? new MissingAcpStoredSession() : new FoundAcpStoredSession(decodeStoredSession(row));
39529
39616
  };
39530
- 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));
39617
+ 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));
39531
39618
  remove = (sessionId) => {
39532
39619
  this.#database.transaction((transaction) => {
39533
39620
  transaction.delete(acpSession).where(eq(acpSession.sessionId, sessionId)).run();
@@ -39593,6 +39680,7 @@ var AgentSession = class _AgentSession {
39593
39680
  #configRevision = 0;
39594
39681
  #configOptions = [];
39595
39682
  #lastTerminalCommandId = null;
39683
+ #nativeHistoryOwnership = { kind: "unbound" };
39596
39684
  #prompted = false;
39597
39685
  #nativePrompt = null;
39598
39686
  #sessionLoad = { kind: "not-requested" };
@@ -39713,6 +39801,9 @@ var AgentSession = class _AgentSession {
39713
39801
  return await embedLocalHistoryImages(await loaded.history.snapshot(), signal);
39714
39802
  };
39715
39803
  loadHistoryEventsV2 = async (eventLimit, cursor, signal) => {
39804
+ if (!this.#prompted && this.#nativeHistoryOwnership.kind === "fresh-session") {
39805
+ return new AcpHistoryReplay().eventPage(eventLimit, cursor);
39806
+ }
39716
39807
  if (!this.#capabilities.loadSession) {
39717
39808
  throw new AcpExecutionError(
39718
39809
  "This Agent restores context but does not provide message history.",
@@ -40002,6 +40093,7 @@ var AgentSession = class _AgentSession {
40002
40093
  )
40003
40094
  );
40004
40095
  this.selectNativeSession(created.sessionId);
40096
+ this.#nativeHistoryOwnership = { kind: "fresh-session" };
40005
40097
  lifecycleResponse = created;
40006
40098
  }
40007
40099
  this.#configOptions = this.#sessionConfigProtocol.normalizeLifecycle(lifecycleResponse);
@@ -40205,6 +40297,19 @@ var AgentSession = class _AgentSession {
40205
40297
  if (this.#turn.running) {
40206
40298
  throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
40207
40299
  }
40300
+ switch (this.#sessionLoad.kind) {
40301
+ case "not-requested":
40302
+ break;
40303
+ case "loaded":
40304
+ this.#sessionLoad = { kind: "not-requested" };
40305
+ break;
40306
+ case "capturing":
40307
+ throw new AcpExecutionError("Session history is still loading", {}, "session_busy");
40308
+ default: {
40309
+ const unexpected = this.#sessionLoad;
40310
+ throw new Error(`Unexpected Session load state: ${JSON.stringify(unexpected)}`);
40311
+ }
40312
+ }
40208
40313
  const prompt = this.buildPrompt(options);
40209
40314
  if (this.#sessionTitle === null || this.#sessionTitle.length === 0) {
40210
40315
  this.#sessionTitle = truncate(options.prompt, 500);
@@ -40365,12 +40470,15 @@ var AgentSession = class _AgentSession {
40365
40470
  onElicitation = (request, signal) => this.#interactions.onElicitation(request, signal);
40366
40471
  onElicitationComplete = (notification) => this.#interactions.onElicitationComplete(notification);
40367
40472
  onUpdate = (notification) => this.#updates.receive(notification);
40368
- selectNativeSession = (sessionId) => this.#updates.select(sessionId);
40473
+ selectNativeSession = (sessionId) => {
40474
+ this.#updates.select(sessionId);
40475
+ this.#nativeHistoryOwnership = { kind: "agent-owned" };
40476
+ };
40369
40477
  #processUpdate = async (notification) => {
40370
40478
  this.assertNativeSession(notification.sessionId);
40371
40479
  const update = notification.update;
40372
40480
  const rawUpdate = decodeAcpSessionUpdateV2(JSON.stringify(update));
40373
- if (this.#sessionLoad.kind !== "not-requested") {
40481
+ if (this.#sessionLoad.kind === "capturing") {
40374
40482
  await this.#sessionLoad.history.record(update, rawUpdate);
40375
40483
  } else {
40376
40484
  const onAcpUpdate = this.#getObserver().onAcpUpdate;
@@ -42721,7 +42829,7 @@ var DaemonAcpObserver = class {
42721
42829
  this.#recordV2 = recordV2;
42722
42830
  }
42723
42831
  onAcpUpdate = (sessionId, update) => {
42724
- this.#recordV2(sessionId, update);
42832
+ this.#recordV2(sessionId, { payload: update, type: "acp" });
42725
42833
  return Promise.resolve();
42726
42834
  };
42727
42835
  onCommands = (event) => {
@@ -42738,10 +42846,18 @@ var DaemonAcpObserver = class {
42738
42846
  };
42739
42847
  onElicitation = (event) => {
42740
42848
  this.#record(event.sessionId, event);
42849
+ this.#recordV2(event.sessionId, {
42850
+ payload: { event, kind: "session.elicitation.requested" },
42851
+ type: "lifecycle-metadata"
42852
+ });
42741
42853
  return Promise.resolve();
42742
42854
  };
42743
42855
  onElicitationResolved = (event) => {
42744
42856
  this.#record(event.sessionId, event);
42857
+ this.#recordV2(event.sessionId, {
42858
+ payload: { event, kind: "session.elicitation.resolved" },
42859
+ type: "lifecycle-metadata"
42860
+ });
42745
42861
  return Promise.resolve();
42746
42862
  };
42747
42863
  onInfo = (event) => {
@@ -42750,10 +42866,18 @@ var DaemonAcpObserver = class {
42750
42866
  };
42751
42867
  onPermission = (event) => {
42752
42868
  this.#record(event.sessionId, event);
42869
+ this.#recordV2(event.sessionId, {
42870
+ payload: { event, kind: "session.permission.requested" },
42871
+ type: "lifecycle-metadata"
42872
+ });
42753
42873
  return Promise.resolve();
42754
42874
  };
42755
42875
  onPermissionResolved = (event) => {
42756
42876
  this.#record(event.sessionId, event);
42877
+ this.#recordV2(event.sessionId, {
42878
+ payload: { event, kind: "session.permission.resolved" },
42879
+ type: "lifecycle-metadata"
42880
+ });
42757
42881
  return Promise.resolve();
42758
42882
  };
42759
42883
  onUsage = (event) => {
@@ -45994,25 +46118,16 @@ function replayEvent(sessionId, position, update) {
45994
46118
  const eventId = `native-${createHash6("sha256").update(sessionId).update(":").update(position.toString()).update(":").update(encoded).digest("hex")}`;
45995
46119
  return {
45996
46120
  eventId,
45997
- payload: { kind: "acp.session.update", update },
46121
+ payload: update,
45998
46122
  position: position.toString(),
45999
46123
  provenance: { kind: "original" },
46000
46124
  recordedAt: "1970-01-01T00:00:00.000Z",
46001
- sessionId
46125
+ sessionId,
46126
+ type: "acp"
46002
46127
  };
46003
46128
  }
46004
- async function executeSessionLiveHistoryV2PageLoad(socket, command, config2, directories, audit, sessions, localRecovery, executingPromptRequest, signal) {
46129
+ async function executeSessionLiveHistoryV2PageLoad(socket, command, config2, directories, audit, sessions, executingPromptRequest, signal) {
46005
46130
  try {
46006
- const local = localRecovery(command.sessionId, command.eventLimit, command.cursor);
46007
- if (local !== null) {
46008
- send(socket, {
46009
- events: local,
46010
- kind: "session.live-history.v2.page.loaded",
46011
- requestId: command.requestId,
46012
- sessionId: command.sessionId
46013
- });
46014
- return;
46015
- }
46016
46131
  const resolved = await resolveSessionDirectories(
46017
46132
  directories,
46018
46133
  config2.bindingId,
@@ -46896,7 +47011,10 @@ function createDaemonCommandHandler({
46896
47011
  timer,
46897
47012
  resolveEnvironment: resolveAgentCatalogEnvironment
46898
47013
  });
46899
- const queueChanged = (sessionId) => publisher.publish(sessionId, { kind: "session.queue.changed", sessionId });
47014
+ const queueChanged = (sessionId) => {
47015
+ publisher.publish(sessionId, { kind: "session.queue.changed", sessionId });
47016
+ eventLogV2.queueChanged(sessionId);
47017
+ };
46900
47018
  const activeTurnRecovery = (sessionId) => activeTurns.recovery((command) => command.sessionId === sessionId);
46901
47019
  const nativeRequestHandler = createNativeSessionRequestHandler({
46902
47020
  audit,
@@ -46946,7 +47064,6 @@ function createDaemonCommandHandler({
46946
47064
  directories,
46947
47065
  audit,
46948
47066
  sessions,
46949
- eventLogV2.recovery,
46950
47067
  eventLogV2.executingPromptRequest,
46951
47068
  signal
46952
47069
  );
@@ -47662,6 +47779,15 @@ var systemDaemonTimer = new SystemDaemonTimer();
47662
47779
 
47663
47780
  // src/session-event-log-v2.ts
47664
47781
  var EXECUTING_PROMPT_EVENT_LIMIT = 1e4;
47782
+ function eventArray(tail) {
47783
+ const reversed = [];
47784
+ let node2 = tail;
47785
+ while (node2 !== null) {
47786
+ reversed.push(node2.event);
47787
+ node2 = node2.previous;
47788
+ }
47789
+ return reversed.reverse();
47790
+ }
47665
47791
  function promptContent(command) {
47666
47792
  const content = [];
47667
47793
  if (command.prompt.length > 0) {
@@ -47685,27 +47811,8 @@ function promptContent(command) {
47685
47811
  }
47686
47812
  return content;
47687
47813
  }
47688
- function encodeLocalEventCursor(cursor) {
47689
- return Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url");
47690
- }
47691
- function decodeLocalEventCursor(sessionId, cursor) {
47692
- try {
47693
- const value = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
47694
- if (typeof value !== "object" || value === null || Array.isArray(value) || Object.keys(value).sort().join(",") !== "endEvent,sessionId" || Reflect.get(value, "sessionId") !== sessionId) {
47695
- throw new Error("Invalid V2 event cursor target");
47696
- }
47697
- const endEvent = Reflect.get(value, "endEvent");
47698
- if (typeof endEvent !== "number" || !Number.isSafeInteger(endEvent) || endEvent < 0) {
47699
- throw new Error("Invalid V2 event cursor boundary");
47700
- }
47701
- return { endEvent, sessionId };
47702
- } catch (cause) {
47703
- throw new AcpExecutionError("The native Session event cursor is invalid", { cause }, "invalid_cursor");
47704
- }
47705
- }
47706
47814
  var DaemonSessionEventLogV2 = class {
47707
47815
  #positions = /* @__PURE__ */ new Map();
47708
- #events = /* @__PURE__ */ new Map();
47709
47816
  #requests = /* @__PURE__ */ new Map();
47710
47817
  #loadedRequestSessions = /* @__PURE__ */ new Set();
47711
47818
  #publisher;
@@ -47714,13 +47821,8 @@ var DaemonSessionEventLogV2 = class {
47714
47821
  this.#publisher = publisher;
47715
47822
  this.#store = store;
47716
47823
  }
47717
- #eventsFor = (sessionId) => {
47718
- const cached2 = this.#events.get(sessionId);
47719
- if (cached2 !== void 0) {
47720
- return cached2;
47721
- }
47722
- const stored = this.#store.readEventsV2(sessionId);
47723
- this.#events.set(sessionId, stored);
47824
+ #loadStoredEvents = (sessionId) => {
47825
+ const stored = this.#store.readExecutingPromptEventsV2(sessionId);
47724
47826
  const lastPosition = stored.at(-1)?.position;
47725
47827
  if (lastPosition !== void 0) {
47726
47828
  this.#positions.set(sessionId, Number(lastPosition));
@@ -47731,25 +47833,37 @@ var DaemonSessionEventLogV2 = class {
47731
47833
  if (this.#loadedRequestSessions.has(sessionId)) {
47732
47834
  return;
47733
47835
  }
47734
- for (const event of this.#eventsFor(sessionId)) {
47836
+ for (const event of this.#loadStoredEvents(sessionId)) {
47837
+ if (event.type === "acp") {
47838
+ const executing = [...this.#requests.values()].find(
47839
+ (request) => request.sessionId === sessionId && request.kind === "executing"
47840
+ );
47841
+ if (executing !== void 0) {
47842
+ this.#requests.set(executing.commandId, {
47843
+ ...executing,
47844
+ eventTail: { event, previous: executing.eventTail }
47845
+ });
47846
+ }
47847
+ continue;
47848
+ }
47735
47849
  const payload = event.payload;
47736
47850
  if (payload.kind === "prompt.requested") {
47737
47851
  this.#requests.set(payload.commandId, {
47738
47852
  commandId: payload.commandId,
47739
- events: [event],
47853
+ eventTail: { event, previous: null },
47740
47854
  kind: "requested",
47741
47855
  sessionId
47742
47856
  });
47743
47857
  continue;
47744
47858
  }
47745
- if (payload.kind === "acp.session.update") {
47859
+ if ("event" in payload) {
47746
47860
  const executing = [...this.#requests.values()].find(
47747
47861
  (request) => request.sessionId === sessionId && request.kind === "executing"
47748
47862
  );
47749
47863
  if (executing !== void 0) {
47750
47864
  this.#requests.set(executing.commandId, {
47751
47865
  ...executing,
47752
- events: [...executing.events, event]
47866
+ eventTail: { event, previous: executing.eventTail }
47753
47867
  });
47754
47868
  }
47755
47869
  continue;
@@ -47761,13 +47875,12 @@ var DaemonSessionEventLogV2 = class {
47761
47875
  if (state === void 0) {
47762
47876
  continue;
47763
47877
  }
47764
- const events = [...state.events, event];
47765
47878
  if (payload.kind === "prompt.started") {
47766
47879
  this.#requests.set(payload.commandId, {
47767
47880
  attemptId: payload.attemptId,
47768
47881
  commandId: payload.commandId,
47769
47882
  epoch: payload.epoch,
47770
- events,
47883
+ eventTail: { event, previous: state.eventTail },
47771
47884
  kind: "executing",
47772
47885
  sessionId
47773
47886
  });
@@ -47778,31 +47891,41 @@ var DaemonSessionEventLogV2 = class {
47778
47891
  this.#loadedRequestSessions.add(sessionId);
47779
47892
  };
47780
47893
  #append = (sessionId, payload) => {
47781
- this.#eventsFor(sessionId);
47894
+ this.#loadRequests(sessionId);
47782
47895
  const position = (this.#positions.get(sessionId) ?? 0) + 1;
47783
47896
  const event = {
47784
47897
  eventId: `event-${crypto.randomUUID()}`,
47785
- payload,
47898
+ ...payload,
47786
47899
  position: position.toString(),
47787
47900
  provenance: { kind: "original" },
47788
47901
  recordedAt: (/* @__PURE__ */ new Date()).toISOString(),
47789
47902
  sessionId
47790
47903
  };
47791
- this.#store.appendEventV2(event);
47792
47904
  this.#positions.set(sessionId, position);
47793
- this.#events.set(sessionId, [...this.#eventsFor(sessionId), event]);
47794
47905
  this.#publisher.publishV2(event);
47795
47906
  return event;
47796
47907
  };
47797
47908
  requested = (command) => {
47909
+ const content = promptContent(command);
47798
47910
  const event = this.#append(command.sessionId, {
47799
- commandId: command.commandId,
47800
- content: promptContent(command),
47801
- kind: "prompt.requested"
47911
+ payload: { commandId: command.commandId, content, kind: "prompt.requested" },
47912
+ type: "lifecycle-metadata"
47802
47913
  });
47914
+ let eventTail = { event, previous: null };
47915
+ for (const block of content) {
47916
+ const userMessageEvent = this.#append(command.sessionId, {
47917
+ payload: {
47918
+ content: block,
47919
+ messageId: command.commandId,
47920
+ sessionUpdate: "user_message_chunk"
47921
+ },
47922
+ type: "acp"
47923
+ });
47924
+ eventTail = { event: userMessageEvent, previous: eventTail };
47925
+ }
47803
47926
  this.#requests.set(command.commandId, {
47804
47927
  commandId: command.commandId,
47805
- events: [event],
47928
+ eventTail,
47806
47929
  kind: "requested",
47807
47930
  sessionId: command.sessionId
47808
47931
  });
@@ -47813,39 +47936,85 @@ var DaemonSessionEventLogV2 = class {
47813
47936
  if (request?.sessionId !== sessionId) {
47814
47937
  return;
47815
47938
  }
47816
- const event = this.#append(sessionId, { attemptId, commandId, epoch, kind: "prompt.started" });
47939
+ const event = this.#append(sessionId, {
47940
+ payload: { attemptId, commandId, epoch, kind: "prompt.started" },
47941
+ type: "lifecycle-metadata"
47942
+ });
47817
47943
  this.#requests.set(commandId, {
47818
47944
  attemptId,
47819
47945
  commandId,
47820
47946
  epoch,
47821
- events: [...request.events, event],
47947
+ eventTail: { event, previous: request.eventTail },
47822
47948
  kind: "executing",
47823
47949
  sessionId
47824
47950
  });
47951
+ this.#store.startExecutingPromptEventsV2(sessionId, eventArray({ event, previous: request.eventTail }));
47825
47952
  };
47826
- acpUpdate = (sessionId, update) => {
47953
+ record = (sessionId, payload) => {
47827
47954
  this.#loadRequests(sessionId);
47828
- const event = this.#append(sessionId, { kind: "acp.session.update", update });
47955
+ const event = this.#append(sessionId, payload);
47956
+ this.#appendToExecutingRequest(sessionId, event);
47957
+ };
47958
+ #appendToExecutingRequest = (sessionId, event) => {
47829
47959
  const executing = [...this.#requests.values()].find(
47830
47960
  (request) => request.sessionId === sessionId && request.kind === "executing"
47831
47961
  );
47832
47962
  if (executing !== void 0) {
47833
- this.#requests.set(executing.commandId, { ...executing, events: [...executing.events, event] });
47963
+ this.#requests.set(executing.commandId, {
47964
+ ...executing,
47965
+ eventTail: { event, previous: executing.eventTail }
47966
+ });
47967
+ this.#store.appendExecutingPromptEventV2(event);
47834
47968
  }
47835
47969
  };
47970
+ queueChanged = (sessionId) => {
47971
+ const event = this.#append(sessionId, {
47972
+ payload: { kind: "session.queue.changed" },
47973
+ type: "lifecycle-metadata"
47974
+ });
47975
+ this.#appendToExecutingRequest(sessionId, event);
47976
+ };
47836
47977
  completed = (sessionId, commandId, stopReason) => {
47837
- this.#append(sessionId, { commandId, kind: "prompt.completed", stopReason });
47978
+ this.#loadRequests(sessionId);
47979
+ const request = this.#requests.get(commandId);
47980
+ const event = this.#append(sessionId, {
47981
+ payload: { commandId, kind: "prompt.completed", stopReason },
47982
+ type: "lifecycle-metadata"
47983
+ });
47838
47984
  this.#requests.delete(commandId);
47985
+ if (request?.kind === "executing" && request.sessionId === sessionId) {
47986
+ this.#store.clearExecutingPromptEventsV2(sessionId);
47987
+ } else {
47988
+ this.#appendToExecutingRequest(sessionId, event);
47989
+ }
47839
47990
  };
47840
47991
  failed = (sessionId, commandId, code, message) => {
47841
47992
  this.#loadRequests(sessionId);
47842
47993
  const request = this.#requests.get(commandId);
47994
+ let event;
47843
47995
  if (request?.kind === "executing" && request.commandId === commandId) {
47844
- this.#append(sessionId, { attemptId: request.attemptId, code, commandId, kind: "prompt.failed", message });
47996
+ event = this.#append(sessionId, {
47997
+ payload: {
47998
+ attemptId: request.attemptId,
47999
+ code,
48000
+ commandId,
48001
+ kind: "prompt.failed",
48002
+ message
48003
+ },
48004
+ type: "lifecycle-metadata"
48005
+ });
47845
48006
  } else {
47846
- this.#append(sessionId, { code, commandId, kind: "prompt.failed-before-start", message });
48007
+ event = this.#append(sessionId, {
48008
+ payload: { code, commandId, kind: "prompt.failed-before-start", message },
48009
+ type: "lifecycle-metadata"
48010
+ });
47847
48011
  }
47848
48012
  this.#requests.delete(commandId);
48013
+ if (request?.kind === "executing" && request.sessionId === sessionId) {
48014
+ this.#store.clearExecutingPromptEventsV2(sessionId);
48015
+ } else {
48016
+ this.#appendToExecutingRequest(sessionId, event);
48017
+ }
47849
48018
  };
47850
48019
  executingPromptRequest = (sessionId) => {
47851
48020
  this.#loadRequests(sessionId);
@@ -47855,42 +48024,15 @@ var DaemonSessionEventLogV2 = class {
47855
48024
  if (request?.kind !== "executing") {
47856
48025
  return null;
47857
48026
  }
47858
- const events = request.events.slice(-EXECUTING_PROMPT_EVENT_LIMIT);
48027
+ const requestEvents = eventArray(request.eventTail);
48028
+ const events = requestEvents.slice(-EXECUTING_PROMPT_EVENT_LIMIT);
47859
48029
  return {
47860
48030
  attemptId: request.attemptId,
47861
48031
  commandId: request.commandId,
47862
48032
  epoch: request.epoch,
47863
48033
  events,
47864
48034
  tailCursor: events.at(-1)?.eventId ?? "",
47865
- truncated: events.length < request.events.length
47866
- };
47867
- };
47868
- recovery = (sessionId, eventLimit, cursor) => {
47869
- const events = this.#eventsFor(sessionId);
47870
- if (events.length === 0) {
47871
- return null;
47872
- }
47873
- const executingPromptRequest = this.executingPromptRequest(sessionId);
47874
- const executingRequestState = [...this.#requests.values()].find(
47875
- (request) => request.sessionId === sessionId && request.kind === "executing"
47876
- );
47877
- const firstExecutingPosition = executingRequestState?.events[0]?.position;
47878
- const historyEvents = firstExecutingPosition === void 0 ? events : events.filter((event) => BigInt(event.position) < BigInt(firstExecutingPosition));
47879
- const endEvent = cursor === null ? historyEvents.length : decodeLocalEventCursor(sessionId, cursor).endEvent;
47880
- if (endEvent > historyEvents.length) {
47881
- throw new AcpExecutionError("The native Session event cursor is invalid", {}, "invalid_cursor");
47882
- }
47883
- const startEvent = Math.max(0, endEvent - eventLimit);
47884
- const pageEvents = historyEvents.slice(startEvent, endEvent);
47885
- return {
47886
- executingPromptRequest,
47887
- history: {
47888
- events: pageEvents,
47889
- nextCursor: startEvent === 0 ? null : encodeLocalEventCursor({ endEvent: startEvent, sessionId }),
47890
- tailCursor: pageEvents.at(-1)?.eventId ?? "",
47891
- truncated: startEvent > 0,
47892
- version: 2
47893
- }
48035
+ truncated: events.length < requestEvents.length
47894
48036
  };
47895
48037
  };
47896
48038
  };
@@ -47972,7 +48114,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
47972
48114
  publisher.publish(sessionId, activeTurns.recordEvent(event));
47973
48115
  };
47974
48116
  const agentRuntime = new AgentRuntimeManager(
47975
- new DaemonAcpObserver(recordSessionEvent, eventLogV2.acpUpdate),
48117
+ new DaemonAcpObserver(recordSessionEvent, eventLogV2.record),
47976
48118
  sessionStore,
47977
48119
  {
47978
48120
  read: async (options2, nativeSessionId, nativeTurn) => options2.agent.id === "codex" ? (await readCodexFullHistory(