@moxt-ai/mobius 0.0.174 → 0.0.176

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 (81) hide show
  1. package/dist/acp/agent-runtime-manager.d.ts +0 -1
  2. package/dist/acp/agent-runtime-manager.d.ts.map +1 -1
  3. package/dist/acp/agent-runtime-manager.js +2 -37
  4. package/dist/acp/agent-runtime-manager.js.map +1 -1
  5. package/dist/acp/agent-session.d.ts +0 -1
  6. package/dist/acp/agent-session.d.ts.map +1 -1
  7. package/dist/acp/agent-session.js +19 -25
  8. package/dist/acp/agent-session.js.map +1 -1
  9. package/dist/acp/session-event-store-v2.d.ts +37 -0
  10. package/dist/acp/session-event-store-v2.d.ts.map +1 -0
  11. package/dist/acp/session-event-store-v2.js +199 -0
  12. package/dist/acp/session-event-store-v2.js.map +1 -0
  13. package/dist/acp/session-history.d.ts +3 -2
  14. package/dist/acp/session-history.d.ts.map +1 -1
  15. package/dist/acp/session-history.js +37 -41
  16. package/dist/acp/session-history.js.map +1 -1
  17. package/dist/acp/session-store.d.ts +8 -9
  18. package/dist/acp/session-store.d.ts.map +1 -1
  19. package/dist/acp/session-store.js +27 -109
  20. package/dist/acp/session-store.js.map +1 -1
  21. package/dist/cli.js +985 -867
  22. package/dist/cli.js.map +4 -4
  23. package/dist/daemon-command-handler.d.ts.map +1 -1
  24. package/dist/daemon-command-handler.js +0 -1
  25. package/dist/daemon-command-handler.js.map +1 -1
  26. package/dist/daemon-turn-registry.d.ts +13 -13
  27. package/dist/generated/acp-session-store-migrations.d.ts +3 -0
  28. package/dist/generated/acp-session-store-migrations.d.ts.map +1 -1
  29. package/dist/generated/acp-session-store-migrations.js +5 -1
  30. package/dist/generated/acp-session-store-migrations.js.map +1 -1
  31. package/dist/generated/session-event-cache-migrations.d.ts +5 -0
  32. package/dist/generated/session-event-cache-migrations.d.ts.map +1 -0
  33. package/dist/generated/session-event-cache-migrations.js +9 -0
  34. package/dist/generated/session-event-cache-migrations.js.map +1 -0
  35. package/dist/index.js +979 -862
  36. package/dist/index.js.map +4 -4
  37. package/dist/infra/local-sqlite-database.d.ts +13 -0
  38. package/dist/infra/local-sqlite-database.d.ts.map +1 -0
  39. package/dist/infra/local-sqlite-database.js +57 -0
  40. package/dist/infra/local-sqlite-database.js.map +1 -0
  41. package/dist/local-databases.d.ts +4 -0
  42. package/dist/local-databases.d.ts.map +1 -0
  43. package/dist/local-databases.js +9 -0
  44. package/dist/local-databases.js.map +1 -0
  45. package/dist/native-sessions/handle-native-requests.d.ts +0 -2
  46. package/dist/native-sessions/handle-native-requests.d.ts.map +1 -1
  47. package/dist/native-sessions/handle-native-requests.js +1 -12
  48. package/dist/native-sessions/handle-native-requests.js.map +1 -1
  49. package/dist/native-sessions/service.d.ts.map +1 -1
  50. package/dist/native-sessions/service.js +0 -62
  51. package/dist/native-sessions/service.js.map +1 -1
  52. package/dist/run-daemon.d.ts.map +1 -1
  53. package/dist/run-daemon.js +15 -2
  54. package/dist/run-daemon.js.map +1 -1
  55. package/dist/runtime.js +969 -852
  56. package/dist/runtime.js.map +4 -4
  57. package/dist/schema/acp-session-store/acp-session.d.ts +0 -16
  58. package/dist/schema/acp-session-store/acp-session.d.ts.map +1 -1
  59. package/dist/schema/acp-session-store/acp-session.js +0 -1
  60. package/dist/schema/acp-session-store/acp-session.js.map +1 -1
  61. package/dist/schema/acp-session-store/index.d.ts +0 -1
  62. package/dist/schema/acp-session-store/index.d.ts.map +1 -1
  63. package/dist/schema/acp-session-store/index.js +0 -1
  64. package/dist/schema/acp-session-store/index.js.map +1 -1
  65. package/dist/schema/session-event-cache/index.d.ts +2 -0
  66. package/dist/schema/session-event-cache/index.d.ts.map +1 -0
  67. package/dist/schema/session-event-cache/index.js +2 -0
  68. package/dist/schema/session-event-cache/index.js.map +1 -0
  69. package/dist/schema/session-event-cache/session-event-v2.d.ts +72 -0
  70. package/dist/schema/session-event-cache/session-event-v2.d.ts.map +1 -0
  71. package/dist/schema/session-event-cache/session-event-v2.js +11 -0
  72. package/dist/schema/session-event-cache/session-event-v2.js.map +1 -0
  73. package/dist/session-event-log-v2.d.ts +2 -2
  74. package/dist/session-event-log-v2.d.ts.map +1 -1
  75. package/dist/session-event-log-v2.js +3 -2
  76. package/dist/session-event-log-v2.js.map +1 -1
  77. package/package.json +2 -1
  78. package/dist/schema/acp-session-store/deleted-acp-session.d.ts +0 -24
  79. package/dist/schema/acp-session-store/deleted-acp-session.d.ts.map +0 -1
  80. package/dist/schema/acp-session-store/deleted-acp-session.js +0 -5
  81. package/dist/schema/acp-session-store/deleted-acp-session.js.map +0 -1
package/dist/index.js CHANGED
@@ -3380,11 +3380,11 @@ var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => {
3380
3380
  return payload;
3381
3381
  };
3382
3382
  });
3383
- function handleArrayResult(result, final, index) {
3383
+ function handleArrayResult(result, final, index2) {
3384
3384
  if (result.issues.length) {
3385
- final.issues.push(...prefixIssues(index, result.issues));
3385
+ final.issues.push(...prefixIssues(index2, result.issues));
3386
3386
  }
3387
- final.value[index] = result.value;
3387
+ final.value[index2] = result.value;
3388
3388
  }
3389
3389
  var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
3390
3390
  $ZodType.init(inst, def);
@@ -3995,14 +3995,14 @@ function mergeValues(a, b) {
3995
3995
  return { valid: false, mergeErrorPath: [] };
3996
3996
  }
3997
3997
  const newArray = [];
3998
- for (let index = 0; index < a.length; index++) {
3999
- const itemA = a[index];
4000
- const itemB = b[index];
3998
+ for (let index2 = 0; index2 < a.length; index2++) {
3999
+ const itemA = a[index2];
4000
+ const itemB = b[index2];
4001
4001
  const sharedValue = mergeValues(itemA, itemB);
4002
4002
  if (!sharedValue.valid) {
4003
4003
  return {
4004
4004
  valid: false,
4005
- mergeErrorPath: [index, ...sharedValue.mergeErrorPath]
4005
+ mergeErrorPath: [index2, ...sharedValue.mergeErrorPath]
4006
4006
  };
4007
4007
  }
4008
4008
  newArray.push(sharedValue.data);
@@ -4153,11 +4153,11 @@ function getTupleOptStart(items, key) {
4153
4153
  }
4154
4154
  return 0;
4155
4155
  }
4156
- function handleTupleResult(result, final, index) {
4156
+ function handleTupleResult(result, final, index2) {
4157
4157
  if (result.issues.length) {
4158
- final.issues.push(...prefixIssues(index, result.issues));
4158
+ final.issues.push(...prefixIssues(index2, result.issues));
4159
4159
  }
4160
- final.value[index] = result.value;
4160
+ final.value[index2] = result.value;
4161
4161
  }
4162
4162
  function handleTupleResults(itemResults, final, items, input2, optoutStart) {
4163
4163
  for (let i = 0; i < items.length; i++) {
@@ -18838,7 +18838,7 @@ function detectVersion(schema, defaultTarget) {
18838
18838
  return defaultTarget ?? "draft-2020-12";
18839
18839
  }
18840
18840
  function applyMinItems(items, minItems) {
18841
- return items.map((item, index) => index < minItems ? item : item.optional());
18841
+ return items.map((item, index2) => index2 < minItems ? item : item.optional());
18842
18842
  }
18843
18843
  function decodeJSONPointerSegment(segment) {
18844
18844
  return segment.replace(/~1/g, "/").replace(/~0/g, "~");
@@ -20023,12 +20023,12 @@ var DEFAULT_AGENT_EXECUTION_CONFIGURATION = Object.freeze({
20023
20023
  });
20024
20024
  var sessionConfigurationSelectionsSchema = external_exports.array(sessionConfigurationSelectionSchema).max(100).superRefine((selections, context) => {
20025
20025
  const identifiers = /* @__PURE__ */ new Set();
20026
- for (const [index, selection] of selections.entries()) {
20026
+ for (const [index2, selection] of selections.entries()) {
20027
20027
  if (identifiers.has(selection.configId)) {
20028
20028
  context.addIssue({
20029
20029
  code: "custom",
20030
20030
  message: "Session configuration identifiers must be unique",
20031
- path: [index, "configId"]
20031
+ path: [index2, "configId"]
20032
20032
  });
20033
20033
  }
20034
20034
  identifiers.add(selection.configId);
@@ -21065,17 +21065,6 @@ var nativeSessionRequestSchema = external_exports.discriminatedUnion("action", [
21065
21065
  action: external_exports.enum(["import", "fork"]),
21066
21066
  entryId: identifierStringSchema,
21067
21067
  targetSessionId: identifierStringSchema
21068
- }).readonly(),
21069
- external_exports.object({
21070
- ...identity,
21071
- action: external_exports.literal("fork-recorded"),
21072
- targetSessionId: identifierStringSchema,
21073
- throughCommandId: identifierStringSchema
21074
- }).readonly(),
21075
- external_exports.object({
21076
- ...identity,
21077
- action: external_exports.literal("delete"),
21078
- entryId: identifierStringSchema
21079
21068
  }).readonly()
21080
21069
  ]);
21081
21070
  var nativeSessionCommandSchema = external_exports.discriminatedUnion("action", [
@@ -21091,17 +21080,6 @@ var nativeSessionCommandSchema = external_exports.discriminatedUnion("action", [
21091
21080
  action: external_exports.enum(["import", "fork"]),
21092
21081
  entryId: identifierStringSchema,
21093
21082
  targetSessionId: identifierStringSchema
21094
- }).readonly(),
21095
- external_exports.object({
21096
- ...identity,
21097
- action: external_exports.literal("fork-recorded"),
21098
- targetSessionId: identifierStringSchema,
21099
- throughCommandId: identifierStringSchema
21100
- }).readonly(),
21101
- external_exports.object({
21102
- ...identity,
21103
- action: external_exports.literal("delete"),
21104
- entryId: identifierStringSchema
21105
21083
  }).readonly()
21106
21084
  ]);
21107
21085
  var nativeSessionEntrySchema = external_exports.object({
@@ -21146,16 +21124,10 @@ var nativeSessionResultSchema = external_exports.discriminatedUnion("action", [
21146
21124
  }).readonly(),
21147
21125
  external_exports.object({
21148
21126
  ...resultEnvelope,
21149
- action: external_exports.enum(["import", "fork", "fork-recorded"]),
21127
+ action: external_exports.enum(["import", "fork"]),
21150
21128
  targetSessionId: identifierStringSchema,
21151
21129
  ready: sessionReadyEventSchema,
21152
21130
  title: external_exports.string().max(500)
21153
- }).readonly(),
21154
- external_exports.object({
21155
- ...resultEnvelope,
21156
- action: external_exports.literal("delete"),
21157
- entryId: identifierStringSchema,
21158
- deletedSessionIds: external_exports.array(identifierStringSchema).max(500).readonly()
21159
21131
  }).readonly()
21160
21132
  ]);
21161
21133
  var nativeSessionCancelSchema = external_exports.object({ ...envelope, kind: external_exports.literal(NATIVE_SESSION_CANCEL_KIND) }).readonly();
@@ -21557,12 +21529,12 @@ var sessionExportV2Schema = external_exports.object({
21557
21529
  }).readonly().superRefine((session, context) => {
21558
21530
  let previousPosition = 0n;
21559
21531
  const eventIds = /* @__PURE__ */ new Set();
21560
- for (const [index, event] of session.events.entries()) {
21532
+ for (const [index2, event] of session.events.entries()) {
21561
21533
  if (event.sessionId !== session.sessionId) {
21562
21534
  context.addIssue({
21563
21535
  code: "custom",
21564
21536
  message: "Exported event belongs to a different Session",
21565
- path: ["events", index, "sessionId"]
21537
+ path: ["events", index2, "sessionId"]
21566
21538
  });
21567
21539
  }
21568
21540
  const position = BigInt(event.position);
@@ -21570,14 +21542,14 @@ var sessionExportV2Schema = external_exports.object({
21570
21542
  context.addIssue({
21571
21543
  code: "custom",
21572
21544
  message: "Exported events are not in increasing position order",
21573
- path: ["events", index, "position"]
21545
+ path: ["events", index2, "position"]
21574
21546
  });
21575
21547
  }
21576
21548
  if (eventIds.has(event.eventId)) {
21577
21549
  context.addIssue({
21578
21550
  code: "custom",
21579
21551
  message: "Exported event identities are not unique",
21580
- path: ["events", index, "eventId"]
21552
+ path: ["events", index2, "eventId"]
21581
21553
  });
21582
21554
  }
21583
21555
  previousPosition = position;
@@ -21628,6 +21600,7 @@ function decode5(value, schema) {
21628
21600
  function encode4(value, schema) {
21629
21601
  return JSON.stringify(decode5(value, schema));
21630
21602
  }
21603
+ var decodeSessionEventV2 = (value) => decode5(value, sessionEventV2Schema);
21631
21604
  var decodeSessionEventEnvelopeV2 = (value) => decode5(value, sessionEventEnvelopeV2Schema);
21632
21605
  var encodeSessionEventEnvelopeV2 = (value) => encode4(value, sessionEventEnvelopeV2Schema);
21633
21606
  var decodeAcpSessionUpdateV2 = (value) => decode5(value, acpSessionUpdateV2Schema);
@@ -22943,7 +22916,7 @@ function startsWith(bytes, signature, offset = 0) {
22943
22916
  if (bytes.byteLength < offset + signature.byteLength) {
22944
22917
  return false;
22945
22918
  }
22946
- return signature.every((value, index) => bytes[offset + index] === value);
22919
+ return signature.every((value, index2) => bytes[offset + index2] === value);
22947
22920
  }
22948
22921
  function sniffRasterMime(bytes) {
22949
22922
  if (startsWith(bytes, PNG_SIGNATURE)) {
@@ -23071,7 +23044,7 @@ function startsWith2(bytes, signature, offset = 0) {
23071
23044
  if (bytes.byteLength < offset + signature.byteLength) {
23072
23045
  return false;
23073
23046
  }
23074
- return signature.every((value, index) => bytes[offset + index] === value);
23047
+ return signature.every((value, index2) => bytes[offset + index2] === value);
23075
23048
  }
23076
23049
  function sniffVideoMime(bytes) {
23077
23050
  if (startsWith2(bytes, MP4_FILE_TYPE, 4)) {
@@ -23200,10 +23173,10 @@ async function replaceImageMarkers(text2, replace) {
23200
23173
  let cursor = 0;
23201
23174
  let rewritten = "";
23202
23175
  for (const match of matches) {
23203
- const index = match.index ?? 0;
23204
- rewritten += text2.slice(cursor, index);
23176
+ const index2 = match.index ?? 0;
23177
+ rewritten += text2.slice(cursor, index2);
23205
23178
  rewritten += await replace(match[1] ?? "");
23206
- cursor = index + match[0].length;
23179
+ cursor = index2 + match[0].length;
23207
23180
  }
23208
23181
  return `${rewritten}${text2.slice(cursor)}`;
23209
23182
  }
@@ -24521,9 +24494,9 @@ function historyContentCharacters(messages) {
24521
24494
  var AcpHistoryReplay = class {
24522
24495
  #activities = /* @__PURE__ */ new Map();
24523
24496
  #messages = [];
24524
- #events = [];
24525
- #records = [];
24497
+ #events;
24526
24498
  #turnActivityIds = /* @__PURE__ */ new Set();
24499
+ #sessionId;
24527
24500
  #activityTracker = new AcpActivityTracker(
24528
24501
  async (activity2) => {
24529
24502
  this.#activities.set(activity2.activityId, activity2);
@@ -24544,10 +24517,16 @@ var AcpHistoryReplay = class {
24544
24517
  #firstMessageIndex = 0;
24545
24518
  #characters = 0;
24546
24519
  #truncated = false;
24520
+ constructor(events, sessionId) {
24521
+ this.#events = events;
24522
+ this.#sessionId = sessionId;
24523
+ }
24547
24524
  record = async (update, rawUpdate, onRecorded = () => Promise.resolve()) => {
24548
- this.#records.push({ kind: "acp", rawUpdate, update });
24549
- this.#events.push({ payload: rawUpdate, type: "acp" });
24550
- await onRecorded(this.#events.length);
24525
+ const position = this.#events.append(this.#sessionId, { payload: rawUpdate, type: "acp" });
24526
+ await onRecorded(position);
24527
+ return await this.#applyUpdate(update, position);
24528
+ };
24529
+ #applyUpdate = async (update, position) => {
24551
24530
  if (update.sessionUpdate === "agent_thought_chunk") {
24552
24531
  if (update.content.type === "text") {
24553
24532
  await this.#activityTracker.recordNarrative(
@@ -24556,30 +24535,30 @@ var AcpHistoryReplay = class {
24556
24535
  update.content.text
24557
24536
  );
24558
24537
  }
24559
- return this.#events.length;
24538
+ return position;
24560
24539
  }
24561
24540
  if (update.sessionUpdate === "tool_call") {
24562
24541
  await this.#activityTracker.recordToolCall(update);
24563
- return this.#events.length;
24542
+ return position;
24564
24543
  }
24565
24544
  if (update.sessionUpdate === "tool_call_update") {
24566
24545
  await this.#activityTracker.recordToolCallUpdate(update);
24567
- return this.#events.length;
24546
+ return position;
24568
24547
  }
24569
24548
  if (update.sessionUpdate === "plan") {
24570
24549
  await this.#activityTracker.recordPlan(update);
24571
- return this.#events.length;
24550
+ return position;
24572
24551
  }
24573
24552
  if (update.sessionUpdate === "plan_update") {
24574
24553
  await this.#activityTracker.recordPlanUpdate(update);
24575
- return this.#events.length;
24554
+ return position;
24576
24555
  }
24577
24556
  if (update.sessionUpdate === "plan_removed") {
24578
24557
  await this.#activityTracker.removePlan(update);
24579
- return this.#events.length;
24558
+ return position;
24580
24559
  }
24581
24560
  if (update.sessionUpdate !== "user_message_chunk" && update.sessionUpdate !== "agent_message_chunk") {
24582
- return this.#events.length;
24561
+ return position;
24583
24562
  }
24584
24563
  if (update.sessionUpdate === "agent_message_chunk" && isProgressMessage(update)) {
24585
24564
  if (update.content.type === "text") {
@@ -24589,18 +24568,18 @@ var AcpHistoryReplay = class {
24589
24568
  update.content.text
24590
24569
  );
24591
24570
  }
24592
- return this.#events.length;
24571
+ return position;
24593
24572
  }
24594
24573
  const role = update.sessionUpdate === "user_message_chunk" ? "user" : "assistant";
24595
24574
  const content = update.content;
24596
24575
  if (role === "assistant" && content.type !== "text") {
24597
24576
  await this.#activityTracker.finishNarrative();
24598
24577
  this.recordAssistantContent(update.messageId ?? null, normalizeContentBlock(content));
24599
- return this.#events.length;
24578
+ return position;
24600
24579
  }
24601
24580
  const text2 = content.type === "text" ? content.text : content.type === "image" ? content.data.length > 0 ? `[@image](data:${content.mimeType};base64,${content.data})` : content.uri != null && content.uri.length > 0 ? `[@image](${content.uri})` : "[image attachment]" : `[${content.type} attachment]`;
24602
24581
  if (text2.length === 0) {
24603
- return this.#events.length;
24582
+ return position;
24604
24583
  }
24605
24584
  const previous = this.#messages.at(-1);
24606
24585
  const id = update.messageId ?? null;
@@ -24627,41 +24606,32 @@ var AcpHistoryReplay = class {
24627
24606
  this.#characters += bounded2.length;
24628
24607
  this.#lastMessageId = id;
24629
24608
  this.trimMessages();
24630
- return this.#events.length;
24609
+ return position;
24631
24610
  };
24632
24611
  recordLifecycle = (event) => {
24633
24612
  if (event.type !== "lifecycle-metadata") {
24634
24613
  throw new Error("Lifecycle history only accepts lifecycle metadata");
24635
24614
  }
24636
- this.#records.push({ event, kind: "lifecycle" });
24637
- this.#events.push(event);
24638
- return this.#events.length;
24615
+ return this.#events.append(this.#sessionId, event);
24639
24616
  };
24640
- eventCount = () => this.#events.length;
24641
24617
  append = async (replay) => {
24642
- for (const record2 of replay.#records) {
24643
- if (record2.kind === "acp") {
24644
- await this.record(record2.update, record2.rawUpdate);
24645
- } else {
24646
- this.recordLifecycle(record2.event);
24647
- }
24618
+ await replay.#activityTracker.finish();
24619
+ for (const [activityId, activity2] of replay.#activities) {
24620
+ this.#activities.set(activityId, activity2);
24648
24621
  }
24649
- };
24650
- eventPage = (eventLimit, cursor, appended = null) => {
24651
- const events = appended === null ? this.#events : [...this.#events, ...appended.#events];
24652
- const parsedCursor = cursor === null ? events.length : Number(cursor);
24653
- if (!Number.isSafeInteger(parsedCursor) || parsedCursor < 0 || parsedCursor > events.length) {
24654
- throw new Error("The native event cursor is invalid");
24622
+ for (const message of replay.#messages.slice(replay.#firstMessageIndex)) {
24623
+ this.#messages.push(message);
24624
+ this.#characters += message.text.length;
24655
24625
  }
24656
- const endUpdate = parsedCursor;
24657
- const startUpdate = Math.max(0, endUpdate - eventLimit);
24658
- return {
24659
- nextCursor: startUpdate === 0 ? null : startUpdate.toString(),
24660
- startPosition: startUpdate + 1,
24661
- truncated: startUpdate > 0,
24662
- events: events.slice(startUpdate, endUpdate)
24663
- };
24626
+ this.#turnActivityIds.clear();
24627
+ for (const activityId of replay.#turnActivityIds) {
24628
+ this.#turnActivityIds.add(activityId);
24629
+ }
24630
+ this.#lastMessageId = replay.#lastMessageId;
24631
+ this.#truncated ||= replay.#truncated;
24632
+ this.trimMessages();
24664
24633
  };
24634
+ eventPage = (eventLimit, cursor) => this.#events.page(this.#sessionId, eventLimit, cursor);
24665
24635
  snapshot = async () => {
24666
24636
  await this.#activityTracker.finish();
24667
24637
  const messages = this.#messages.slice(this.#firstMessageIndex).map((message) => {
@@ -25294,9 +25264,7 @@ var AcpSessionInteractions = class {
25294
25264
  };
25295
25265
 
25296
25266
  // src/acp/session-store.ts
25297
- import { chmodSync, mkdirSync } from "node:fs";
25298
- import { dirname } from "node:path";
25299
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
25267
+ import { randomUUID } from "node:crypto";
25300
25268
 
25301
25269
  // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/entity.js
25302
25270
  var entityKind = /* @__PURE__ */ Symbol.for("drizzle:entityKind");
@@ -26412,7 +26380,7 @@ function haveSameKeys(left, right) {
26412
26380
  const leftKeys = Object.keys(left);
26413
26381
  const rightKeys = Object.keys(right);
26414
26382
  if (leftKeys.length !== rightKeys.length) return false;
26415
- for (const [index, key] of leftKeys.entries()) if (key !== rightKeys[index]) return false;
26383
+ for (const [index2, key] of leftKeys.entries()) if (key !== rightKeys[index2]) return false;
26416
26384
  return true;
26417
26385
  }
26418
26386
  function mapUpdateSet(table, values) {
@@ -27165,195 +27133,6 @@ var NoopLogger = class {
27165
27133
  }
27166
27134
  };
27167
27135
 
27168
- // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/sqlite-core/query-builders/count.js
27169
- var SQLiteCountBuilder = class SQLiteCountBuilder2 extends SQL {
27170
- static [entityKind] = "SQLiteCountBuilder";
27171
- dialect;
27172
- session;
27173
- static buildCount(source, filters, parens) {
27174
- const query = sql`select count(*) from ${source}${sql` where ${filters}`.if(filters)}`;
27175
- return parens ? sql`(${query})` : query;
27176
- }
27177
- constructor(countConfig) {
27178
- super(SQLiteCountBuilder2.buildCount(countConfig.source, countConfig.filters, true).queryChunks);
27179
- this.countConfig = countConfig;
27180
- this.dialect = countConfig.dialect;
27181
- this.session = countConfig.session;
27182
- this.mapWith((e) => {
27183
- if (typeof e === "number") return e;
27184
- return Number(e ?? 0);
27185
- });
27186
- }
27187
- executableSql;
27188
- build() {
27189
- if (!this.executableSql) {
27190
- const { source, filters } = this.countConfig;
27191
- this.executableSql = SQLiteCountBuilder2.buildCount(source, filters);
27192
- }
27193
- return this.dialect.sqlToQuery(this.executableSql);
27194
- }
27195
- };
27196
-
27197
- // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/sqlite-core/async/count.js
27198
- var SQLiteAsyncCountBuilder = class extends SQLiteCountBuilder {
27199
- static [entityKind] = "SQLiteAsyncCountBuilder";
27200
- constructor(countConfig) {
27201
- super(countConfig);
27202
- }
27203
- /** @internal */
27204
- executeRaw(placeholderValues) {
27205
- return this.session.prepareQuery(this.build(), "arrays", false, "all", (rows) => {
27206
- const v = rows[0]?.[0];
27207
- if (typeof v === "number") return v;
27208
- return v ? Number(v) : 0;
27209
- }).execute(placeholderValues);
27210
- }
27211
- async execute(placeholderValues) {
27212
- return await this.executeRaw(placeholderValues);
27213
- }
27214
- };
27215
- applyMixins(SQLiteAsyncCountBuilder, [QueryPromise]);
27216
- var SQLiteSyncCountBuilder = class extends SQLiteAsyncCountBuilder {
27217
- static [entityKind] = "SQLiteSyncCountBuilder";
27218
- sync(placeholderValues) {
27219
- return this.executeRaw(placeholderValues).sync();
27220
- }
27221
- };
27222
-
27223
- // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/sqlite-core/query-builders/query.js
27224
- var RelationalQueryBuilder = class {
27225
- static [entityKind] = "SQLiteRelationalQueryBuilderV2";
27226
- constructor(mode, schema, table, tableConfig, dialect, session, forbidJsonb, builder = SQLiteRelationalQuery) {
27227
- this.mode = mode;
27228
- this.schema = schema;
27229
- this.table = table;
27230
- this.tableConfig = tableConfig;
27231
- this.dialect = dialect;
27232
- this.session = session;
27233
- this.forbidJsonb = forbidJsonb;
27234
- this.builder = builder;
27235
- }
27236
- findMany(config2) {
27237
- return new this.builder(this.mode, this.schema, this.table, this.tableConfig, this.dialect, this.session, config2 ?? true, "many", this.forbidJsonb);
27238
- }
27239
- findFirst(config2) {
27240
- return new this.builder(this.mode, this.schema, this.table, this.tableConfig, this.dialect, this.session, config2 ?? true, "first", this.forbidJsonb);
27241
- }
27242
- };
27243
- var SQLiteRelationalQuery = class {
27244
- static [entityKind] = "SQLiteRelationalQueryV2";
27245
- /** @internal */
27246
- mode;
27247
- /** @internal */
27248
- table;
27249
- /** @internal */
27250
- resultKind;
27251
- constructor(resultKind, schema, table, tableConfig, dialect, session, config2, mode, forbidJsonb) {
27252
- this.schema = schema;
27253
- this.tableConfig = tableConfig;
27254
- this.dialect = dialect;
27255
- this.session = session;
27256
- this.config = config2;
27257
- this.forbidJsonb = forbidJsonb;
27258
- this.resultKind = resultKind;
27259
- this.mode = mode;
27260
- this.table = table;
27261
- }
27262
- getSQL() {
27263
- return this._getQuery().sql;
27264
- }
27265
- _getQuery() {
27266
- const jsonb = this.forbidJsonb ? sql`json` : sql`jsonb`;
27267
- return this.dialect.buildRelationalQuery({
27268
- schema: this.schema,
27269
- table: this.table,
27270
- tableConfig: this.tableConfig,
27271
- queryConfig: this.config,
27272
- mode: this.mode,
27273
- jsonb
27274
- });
27275
- }
27276
- _toSQL() {
27277
- const query = this._getQuery();
27278
- return {
27279
- query,
27280
- builtQuery: this.dialect.sqlToQuery(query.sql)
27281
- };
27282
- }
27283
- toSQL() {
27284
- return this._toSQL().builtQuery;
27285
- }
27286
- };
27287
-
27288
- // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/sqlite-core/async/query.js
27289
- var SQLiteAsyncRelationalQuery = class extends SQLiteRelationalQuery {
27290
- static [entityKind] = "SQLiteAsyncRelationalQueryV2";
27291
- /** @internal */
27292
- _prepare(prepare = false) {
27293
- const { query, builtQuery } = this._toSQL();
27294
- const mapper = this.dialect.mapperGenerators.relationalRows({
27295
- isFirst: this.mode === "first",
27296
- parseJson: true,
27297
- parseJsonIfString: false,
27298
- rootJsonMappers: false,
27299
- selection: query.selection,
27300
- arrayModeRoot: true
27301
- });
27302
- return this.session.prepareQuery(builtQuery, "arrays", prepare, "all", mapper);
27303
- }
27304
- prepare() {
27305
- return this._prepare(true);
27306
- }
27307
- async execute(placeholderValues) {
27308
- return this._prepare().execute(placeholderValues);
27309
- }
27310
- };
27311
- var SQLiteSyncRelationalQuery = class extends SQLiteAsyncRelationalQuery {
27312
- static [entityKind] = "SQLiteSyncRelationalQueryV2";
27313
- sync(placeholderValues) {
27314
- return this._prepare().execute(placeholderValues).sync();
27315
- }
27316
- };
27317
- applyMixins(SQLiteAsyncRelationalQuery, [QueryPromise]);
27318
-
27319
- // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/selection-proxy.js
27320
- var SelectionProxyHandler = class SelectionProxyHandler2 {
27321
- static [entityKind] = "SelectionProxyHandler";
27322
- config;
27323
- constructor(config2) {
27324
- this.config = { ...config2 };
27325
- }
27326
- get(subquery, prop) {
27327
- if (prop === "_") return {
27328
- ...subquery["_"],
27329
- selectedFields: new Proxy(subquery._.selectedFields, this)
27330
- };
27331
- if (prop === ViewBaseConfig) return {
27332
- ...subquery[ViewBaseConfig],
27333
- selectedFields: new Proxy(subquery[ViewBaseConfig].selectedFields, this)
27334
- };
27335
- if (typeof prop === "symbol") return subquery[prop];
27336
- const value = (is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View) ? subquery[ViewBaseConfig].selectedFields : subquery)[prop];
27337
- if (is(value, SQL.Aliased)) {
27338
- if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) return value.sql;
27339
- const newValue = value.clone();
27340
- newValue.isSelectionField = true;
27341
- newValue.origin = this.config.alias;
27342
- return newValue;
27343
- }
27344
- if (is(value, SQL)) {
27345
- if (this.config.sqlBehavior === "sql") return value;
27346
- throw new Error(`You tried to reference "${prop}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`);
27347
- }
27348
- if (is(value, Column)) {
27349
- if (this.config.alias) return new Proxy(value, new ColumnTableAliasProxyHandler(new Proxy(value.table, new TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false, true)), true));
27350
- return value;
27351
- }
27352
- if (typeof value !== "object" || value === null) return value;
27353
- return new Proxy(value, new SelectionProxyHandler2(this.config));
27354
- }
27355
- };
27356
-
27357
27136
  // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/sqlite-core/foreign-keys.js
27358
27137
  var ForeignKeyBuilder = class {
27359
27138
  static [entityKind] = "SQLiteForeignKeyBuilder";
@@ -27918,130 +27697,144 @@ function sqliteTableWithCasing(casing) {
27918
27697
  }
27919
27698
  var sqliteTable = sqliteTableWithCasing(void 0);
27920
27699
 
27921
- // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/sqlite-core/utils.js
27922
- function extractUsedTable(table) {
27923
- if (is(table, SQLiteTable)) return [`${table[Table.Symbol.BaseName]}`];
27924
- if (is(table, Subquery)) return table._.usedTables ?? [];
27925
- if (is(table, SQL)) return table.usedTables ?? [];
27926
- return [];
27927
- }
27928
-
27929
- // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/sqlite-core/query-builders/delete.js
27930
- var SQLiteDeleteBase = class {
27931
- static [entityKind] = "SQLiteDelete";
27700
+ // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/sqlite-core/indexes.js
27701
+ var IndexBuilderOn = class {
27702
+ static [entityKind] = "SQLiteIndexBuilderOn";
27703
+ constructor(name2, unique) {
27704
+ this.name = name2;
27705
+ this.unique = unique;
27706
+ }
27707
+ on(...columns) {
27708
+ return new IndexBuilder(this.name, columns, this.unique);
27709
+ }
27710
+ };
27711
+ var IndexBuilder = class {
27712
+ static [entityKind] = "SQLiteIndexBuilder";
27932
27713
  /** @internal */
27933
27714
  config;
27934
- constructor(table, session, dialect, withList) {
27935
- this.table = table;
27936
- this.session = session;
27937
- this.dialect = dialect;
27715
+ constructor(name2, columns, unique) {
27938
27716
  this.config = {
27939
- table,
27940
- withList
27717
+ name: name2,
27718
+ columns,
27719
+ unique,
27720
+ where: void 0
27941
27721
  };
27942
27722
  }
27943
27723
  /**
27944
- * Adds a `where` clause to the query.
27945
- *
27946
- * Calling this method will delete only those rows that fulfill a specified condition.
27947
- *
27948
- * See docs: {@link https://orm.drizzle.team/docs/delete}
27949
- *
27950
- * @param where the `where` clause.
27951
- *
27952
- * @example
27953
- * You can use conditional operators and `sql function` to filter the rows to be deleted.
27954
- *
27955
- * ```ts
27956
- * // Delete all cars with green color
27957
- * db.delete(cars).where(eq(cars.color, 'green'));
27958
- * // or
27959
- * db.delete(cars).where(sql`${cars.color} = 'green'`)
27960
- * ```
27961
- *
27962
- * You can logically combine conditional operators with `and()` and `or()` operators:
27963
- *
27964
- * ```ts
27965
- * // Delete all BMW cars with a green color
27966
- * db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
27967
- *
27968
- * // Delete all cars with the green or blue color
27969
- * db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
27970
- * ```
27724
+ * Condition for partial index.
27971
27725
  */
27972
- where(where) {
27973
- this.config.where = where;
27974
- return this;
27975
- }
27976
- orderBy(...columns) {
27977
- if (typeof columns[0] === "function") {
27978
- const orderBy = columns[0](new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({
27979
- sqlAliasedBehavior: "alias",
27980
- sqlBehavior: "sql"
27981
- })));
27982
- const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
27983
- this.config.orderBy = orderByArray;
27984
- } else {
27985
- const orderByArray = columns;
27986
- this.config.orderBy = orderByArray;
27987
- }
27988
- return this;
27989
- }
27990
- limit(limit) {
27991
- this.config.limit = limit;
27992
- return this;
27993
- }
27994
- returning(fields = this.table[SQLiteTable.Symbol.Columns]) {
27995
- this.config.returning = orderSelectedFields(fields);
27726
+ where(condition) {
27727
+ this.config.where = condition;
27996
27728
  return this;
27997
27729
  }
27998
- getSQL() {
27999
- return this.dialect.buildDeleteQuery(this.config);
28000
- }
28001
- toSQL() {
28002
- return this.dialect.sqlToQuery(this.getSQL());
27730
+ /** @internal */
27731
+ build(table) {
27732
+ return new Index(this.config, table);
28003
27733
  }
28004
- $dynamic() {
28005
- return this;
27734
+ };
27735
+ var Index = class {
27736
+ static [entityKind] = "SQLiteIndex";
27737
+ config;
27738
+ isNameExplicit;
27739
+ constructor(config2, table) {
27740
+ this.config = {
27741
+ ...config2,
27742
+ table
27743
+ };
27744
+ this.isNameExplicit = !!config2.name;
28006
27745
  }
28007
27746
  };
27747
+ function index(name2) {
27748
+ return new IndexBuilderOn(name2, false);
27749
+ }
28008
27750
 
28009
- // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/sqlite-core/async/delete.js
28010
- var SQLiteAsyncDeleteBase = class extends SQLiteDeleteBase {
28011
- static [entityKind] = "SQLiteAsyncDelete";
27751
+ // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/sqlite-core/primary-keys.js
27752
+ function primaryKey(...config2) {
27753
+ if (config2[0].columns) return new PrimaryKeyBuilder(config2[0].columns, config2[0].name);
27754
+ return new PrimaryKeyBuilder(config2);
27755
+ }
27756
+ var PrimaryKeyBuilder = class {
27757
+ static [entityKind] = "SQLitePrimaryKeyBuilder";
28012
27758
  /** @internal */
28013
- _prepare(prepare = false) {
28014
- return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), "arrays", prepare, this.config.returning ? "all" : "run", this.config.returning ? this.dialect.mapperGenerators.rows(this.config.returning, void 0) : void 0, {
28015
- type: "delete",
28016
- tables: extractUsedTable(this.config.table)
28017
- });
27759
+ columns;
27760
+ /** @internal */
27761
+ name;
27762
+ constructor(columns, name2) {
27763
+ this.columns = columns;
27764
+ this.name = name2;
28018
27765
  }
28019
- prepare() {
28020
- return this._prepare(true);
27766
+ /** @internal */
27767
+ build(table) {
27768
+ return new PrimaryKey(table, this.columns, this.name);
28021
27769
  }
28022
- run = (placeholderValues) => {
28023
- return this._prepare().run(placeholderValues);
28024
- };
28025
- all = (placeholderValues) => {
28026
- return this._prepare().all(placeholderValues);
28027
- };
28028
- get = (placeholderValues) => {
28029
- return this._prepare().get(placeholderValues);
28030
- };
28031
- values = (placeholderValues) => {
28032
- return this._prepare().values(placeholderValues);
28033
- };
28034
- async execute(placeholderValues) {
28035
- return this._prepare().execute(placeholderValues);
27770
+ };
27771
+ var PrimaryKey = class {
27772
+ static [entityKind] = "SQLitePrimaryKey";
27773
+ columns;
27774
+ name;
27775
+ isNameExplicit;
27776
+ constructor(table, columns, name2) {
27777
+ this.table = table;
27778
+ this.columns = columns;
27779
+ this.name = name2;
27780
+ this.isNameExplicit = !!name2;
27781
+ }
27782
+ getName() {
27783
+ return this.name ?? `${this.table[SQLiteTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`;
28036
27784
  }
28037
27785
  };
28038
- applyMixins(SQLiteAsyncDeleteBase, [QueryPromise]);
27786
+
27787
+ // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/sqlite-core/utils.js
27788
+ function extractUsedTable(table) {
27789
+ if (is(table, SQLiteTable)) return [`${table[Table.Symbol.BaseName]}`];
27790
+ if (is(table, Subquery)) return table._.usedTables ?? [];
27791
+ if (is(table, SQL)) return table.usedTables ?? [];
27792
+ return [];
27793
+ }
28039
27794
 
28040
27795
  // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/sqlite-core/view-base.js
28041
27796
  var SQLiteViewBase = class extends View {
28042
27797
  static [entityKind] = "SQLiteViewBase";
28043
27798
  };
28044
27799
 
27800
+ // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/selection-proxy.js
27801
+ var SelectionProxyHandler = class SelectionProxyHandler2 {
27802
+ static [entityKind] = "SelectionProxyHandler";
27803
+ config;
27804
+ constructor(config2) {
27805
+ this.config = { ...config2 };
27806
+ }
27807
+ get(subquery, prop) {
27808
+ if (prop === "_") return {
27809
+ ...subquery["_"],
27810
+ selectedFields: new Proxy(subquery._.selectedFields, this)
27811
+ };
27812
+ if (prop === ViewBaseConfig) return {
27813
+ ...subquery[ViewBaseConfig],
27814
+ selectedFields: new Proxy(subquery[ViewBaseConfig].selectedFields, this)
27815
+ };
27816
+ if (typeof prop === "symbol") return subquery[prop];
27817
+ const value = (is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View) ? subquery[ViewBaseConfig].selectedFields : subquery)[prop];
27818
+ if (is(value, SQL.Aliased)) {
27819
+ if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) return value.sql;
27820
+ const newValue = value.clone();
27821
+ newValue.isSelectionField = true;
27822
+ newValue.origin = this.config.alias;
27823
+ return newValue;
27824
+ }
27825
+ if (is(value, SQL)) {
27826
+ if (this.config.sqlBehavior === "sql") return value;
27827
+ throw new Error(`You tried to reference "${prop}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`);
27828
+ }
27829
+ if (is(value, Column)) {
27830
+ if (this.config.alias) return new Proxy(value, new ColumnTableAliasProxyHandler(new Proxy(value.table, new TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false, true)), true));
27831
+ return value;
27832
+ }
27833
+ if (typeof value !== "object" || value === null) return value;
27834
+ return new Proxy(value, new SelectionProxyHandler2(this.config));
27835
+ }
27836
+ };
27837
+
28045
27838
  // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/query-builders/query-builder.js
28046
27839
  var TypedQueryBuilder = class {
28047
27840
  static [entityKind] = "TypedQueryBuilder";
@@ -28742,8 +28535,8 @@ var SQLiteDialect = class {
28742
28535
  buildJoins(joins) {
28743
28536
  if (!joins || joins.length === 0) return;
28744
28537
  const joinsArray = [];
28745
- if (joins) for (const [index, joinMeta] of joins.entries()) {
28746
- if (index === 0) joinsArray.push(sql` `);
28538
+ if (joins) for (const [index2, joinMeta] of joins.entries()) {
28539
+ if (index2 === 0) joinsArray.push(sql` `);
28747
28540
  const table = joinMeta.table;
28748
28541
  const onSql = joinMeta.on ? sql` on ${joinMeta.on}` : void 0;
28749
28542
  if (is(table, SQLiteTable)) {
@@ -28753,7 +28546,7 @@ var SQLiteDialect = class {
28753
28546
  const alias = tableName === origTableName ? void 0 : joinMeta.alias;
28754
28547
  joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`);
28755
28548
  } else joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join ${table}${onSql}`);
28756
- if (index < joins.length - 1) joinsArray.push(sql` `);
28549
+ if (index2 < joins.length - 1) joinsArray.push(sql` `);
28757
28550
  }
28758
28551
  return sql.join(joinsArray);
28759
28552
  }
@@ -28762,9 +28555,9 @@ var SQLiteDialect = class {
28762
28555
  }
28763
28556
  buildOrderBy(orderBy) {
28764
28557
  const orderByList = [];
28765
- if (orderBy) for (const [index, orderByValue] of orderBy.entries()) {
28558
+ if (orderBy) for (const [index2, orderByValue] of orderBy.entries()) {
28766
28559
  orderByList.push(orderByValue);
28767
- if (index < orderBy.length - 1) orderByList.push(sql`, `);
28560
+ if (index2 < orderBy.length - 1) orderByList.push(sql`, `);
28768
28561
  }
28769
28562
  return orderByList.length > 0 ? sql` order by ${sql.join(orderByList)}` : void 0;
28770
28563
  }
@@ -28792,9 +28585,9 @@ var SQLiteDialect = class {
28792
28585
  const whereSql = where ? sql` where ${where}` : void 0;
28793
28586
  const havingSql = having ? sql` having ${having}` : void 0;
28794
28587
  const groupByList = [];
28795
- if (groupBy) for (const [index, groupByValue] of groupBy.entries()) {
28588
+ if (groupBy) for (const [index2, groupByValue] of groupBy.entries()) {
28796
28589
  groupByList.push(groupByValue);
28797
- if (index < groupBy.length - 1) groupByList.push(sql`, `);
28590
+ if (index2 < groupBy.length - 1) groupByList.push(sql`, `);
28798
28591
  }
28799
28592
  const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupByList.length > 0 ? sql` group by ${sql.join(groupByList)}` : void 0}${havingSql}${this.buildOrderBy(orderBy)}${this.buildLimit(limit)}${offset ? sql` offset ${offset}` : void 0}`;
28800
28593
  if (setOperators.length > 0) return this.buildSetOperations(finalQuery, setOperators);
@@ -29083,6 +28876,268 @@ var QueryBuilder = class {
29083
28876
  }
29084
28877
  };
29085
28878
 
28879
+ // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/sqlite-core/query-builders/count.js
28880
+ var SQLiteCountBuilder = class SQLiteCountBuilder2 extends SQL {
28881
+ static [entityKind] = "SQLiteCountBuilder";
28882
+ dialect;
28883
+ session;
28884
+ static buildCount(source, filters, parens) {
28885
+ const query = sql`select count(*) from ${source}${sql` where ${filters}`.if(filters)}`;
28886
+ return parens ? sql`(${query})` : query;
28887
+ }
28888
+ constructor(countConfig) {
28889
+ super(SQLiteCountBuilder2.buildCount(countConfig.source, countConfig.filters, true).queryChunks);
28890
+ this.countConfig = countConfig;
28891
+ this.dialect = countConfig.dialect;
28892
+ this.session = countConfig.session;
28893
+ this.mapWith((e) => {
28894
+ if (typeof e === "number") return e;
28895
+ return Number(e ?? 0);
28896
+ });
28897
+ }
28898
+ executableSql;
28899
+ build() {
28900
+ if (!this.executableSql) {
28901
+ const { source, filters } = this.countConfig;
28902
+ this.executableSql = SQLiteCountBuilder2.buildCount(source, filters);
28903
+ }
28904
+ return this.dialect.sqlToQuery(this.executableSql);
28905
+ }
28906
+ };
28907
+
28908
+ // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/sqlite-core/async/count.js
28909
+ var SQLiteAsyncCountBuilder = class extends SQLiteCountBuilder {
28910
+ static [entityKind] = "SQLiteAsyncCountBuilder";
28911
+ constructor(countConfig) {
28912
+ super(countConfig);
28913
+ }
28914
+ /** @internal */
28915
+ executeRaw(placeholderValues) {
28916
+ return this.session.prepareQuery(this.build(), "arrays", false, "all", (rows) => {
28917
+ const v = rows[0]?.[0];
28918
+ if (typeof v === "number") return v;
28919
+ return v ? Number(v) : 0;
28920
+ }).execute(placeholderValues);
28921
+ }
28922
+ async execute(placeholderValues) {
28923
+ return await this.executeRaw(placeholderValues);
28924
+ }
28925
+ };
28926
+ applyMixins(SQLiteAsyncCountBuilder, [QueryPromise]);
28927
+ var SQLiteSyncCountBuilder = class extends SQLiteAsyncCountBuilder {
28928
+ static [entityKind] = "SQLiteSyncCountBuilder";
28929
+ sync(placeholderValues) {
28930
+ return this.executeRaw(placeholderValues).sync();
28931
+ }
28932
+ };
28933
+
28934
+ // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/sqlite-core/query-builders/query.js
28935
+ var RelationalQueryBuilder = class {
28936
+ static [entityKind] = "SQLiteRelationalQueryBuilderV2";
28937
+ constructor(mode, schema, table, tableConfig, dialect, session, forbidJsonb, builder = SQLiteRelationalQuery) {
28938
+ this.mode = mode;
28939
+ this.schema = schema;
28940
+ this.table = table;
28941
+ this.tableConfig = tableConfig;
28942
+ this.dialect = dialect;
28943
+ this.session = session;
28944
+ this.forbidJsonb = forbidJsonb;
28945
+ this.builder = builder;
28946
+ }
28947
+ findMany(config2) {
28948
+ return new this.builder(this.mode, this.schema, this.table, this.tableConfig, this.dialect, this.session, config2 ?? true, "many", this.forbidJsonb);
28949
+ }
28950
+ findFirst(config2) {
28951
+ return new this.builder(this.mode, this.schema, this.table, this.tableConfig, this.dialect, this.session, config2 ?? true, "first", this.forbidJsonb);
28952
+ }
28953
+ };
28954
+ var SQLiteRelationalQuery = class {
28955
+ static [entityKind] = "SQLiteRelationalQueryV2";
28956
+ /** @internal */
28957
+ mode;
28958
+ /** @internal */
28959
+ table;
28960
+ /** @internal */
28961
+ resultKind;
28962
+ constructor(resultKind, schema, table, tableConfig, dialect, session, config2, mode, forbidJsonb) {
28963
+ this.schema = schema;
28964
+ this.tableConfig = tableConfig;
28965
+ this.dialect = dialect;
28966
+ this.session = session;
28967
+ this.config = config2;
28968
+ this.forbidJsonb = forbidJsonb;
28969
+ this.resultKind = resultKind;
28970
+ this.mode = mode;
28971
+ this.table = table;
28972
+ }
28973
+ getSQL() {
28974
+ return this._getQuery().sql;
28975
+ }
28976
+ _getQuery() {
28977
+ const jsonb = this.forbidJsonb ? sql`json` : sql`jsonb`;
28978
+ return this.dialect.buildRelationalQuery({
28979
+ schema: this.schema,
28980
+ table: this.table,
28981
+ tableConfig: this.tableConfig,
28982
+ queryConfig: this.config,
28983
+ mode: this.mode,
28984
+ jsonb
28985
+ });
28986
+ }
28987
+ _toSQL() {
28988
+ const query = this._getQuery();
28989
+ return {
28990
+ query,
28991
+ builtQuery: this.dialect.sqlToQuery(query.sql)
28992
+ };
28993
+ }
28994
+ toSQL() {
28995
+ return this._toSQL().builtQuery;
28996
+ }
28997
+ };
28998
+
28999
+ // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/sqlite-core/async/query.js
29000
+ var SQLiteAsyncRelationalQuery = class extends SQLiteRelationalQuery {
29001
+ static [entityKind] = "SQLiteAsyncRelationalQueryV2";
29002
+ /** @internal */
29003
+ _prepare(prepare = false) {
29004
+ const { query, builtQuery } = this._toSQL();
29005
+ const mapper = this.dialect.mapperGenerators.relationalRows({
29006
+ isFirst: this.mode === "first",
29007
+ parseJson: true,
29008
+ parseJsonIfString: false,
29009
+ rootJsonMappers: false,
29010
+ selection: query.selection,
29011
+ arrayModeRoot: true
29012
+ });
29013
+ return this.session.prepareQuery(builtQuery, "arrays", prepare, "all", mapper);
29014
+ }
29015
+ prepare() {
29016
+ return this._prepare(true);
29017
+ }
29018
+ async execute(placeholderValues) {
29019
+ return this._prepare().execute(placeholderValues);
29020
+ }
29021
+ };
29022
+ var SQLiteSyncRelationalQuery = class extends SQLiteAsyncRelationalQuery {
29023
+ static [entityKind] = "SQLiteSyncRelationalQueryV2";
29024
+ sync(placeholderValues) {
29025
+ return this._prepare().execute(placeholderValues).sync();
29026
+ }
29027
+ };
29028
+ applyMixins(SQLiteAsyncRelationalQuery, [QueryPromise]);
29029
+
29030
+ // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/sqlite-core/query-builders/delete.js
29031
+ var SQLiteDeleteBase = class {
29032
+ static [entityKind] = "SQLiteDelete";
29033
+ /** @internal */
29034
+ config;
29035
+ constructor(table, session, dialect, withList) {
29036
+ this.table = table;
29037
+ this.session = session;
29038
+ this.dialect = dialect;
29039
+ this.config = {
29040
+ table,
29041
+ withList
29042
+ };
29043
+ }
29044
+ /**
29045
+ * Adds a `where` clause to the query.
29046
+ *
29047
+ * Calling this method will delete only those rows that fulfill a specified condition.
29048
+ *
29049
+ * See docs: {@link https://orm.drizzle.team/docs/delete}
29050
+ *
29051
+ * @param where the `where` clause.
29052
+ *
29053
+ * @example
29054
+ * You can use conditional operators and `sql function` to filter the rows to be deleted.
29055
+ *
29056
+ * ```ts
29057
+ * // Delete all cars with green color
29058
+ * db.delete(cars).where(eq(cars.color, 'green'));
29059
+ * // or
29060
+ * db.delete(cars).where(sql`${cars.color} = 'green'`)
29061
+ * ```
29062
+ *
29063
+ * You can logically combine conditional operators with `and()` and `or()` operators:
29064
+ *
29065
+ * ```ts
29066
+ * // Delete all BMW cars with a green color
29067
+ * db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
29068
+ *
29069
+ * // Delete all cars with the green or blue color
29070
+ * db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
29071
+ * ```
29072
+ */
29073
+ where(where) {
29074
+ this.config.where = where;
29075
+ return this;
29076
+ }
29077
+ orderBy(...columns) {
29078
+ if (typeof columns[0] === "function") {
29079
+ const orderBy = columns[0](new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({
29080
+ sqlAliasedBehavior: "alias",
29081
+ sqlBehavior: "sql"
29082
+ })));
29083
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
29084
+ this.config.orderBy = orderByArray;
29085
+ } else {
29086
+ const orderByArray = columns;
29087
+ this.config.orderBy = orderByArray;
29088
+ }
29089
+ return this;
29090
+ }
29091
+ limit(limit) {
29092
+ this.config.limit = limit;
29093
+ return this;
29094
+ }
29095
+ returning(fields = this.table[SQLiteTable.Symbol.Columns]) {
29096
+ this.config.returning = orderSelectedFields(fields);
29097
+ return this;
29098
+ }
29099
+ getSQL() {
29100
+ return this.dialect.buildDeleteQuery(this.config);
29101
+ }
29102
+ toSQL() {
29103
+ return this.dialect.sqlToQuery(this.getSQL());
29104
+ }
29105
+ $dynamic() {
29106
+ return this;
29107
+ }
29108
+ };
29109
+
29110
+ // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/sqlite-core/async/delete.js
29111
+ var SQLiteAsyncDeleteBase = class extends SQLiteDeleteBase {
29112
+ static [entityKind] = "SQLiteAsyncDelete";
29113
+ /** @internal */
29114
+ _prepare(prepare = false) {
29115
+ return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), "arrays", prepare, this.config.returning ? "all" : "run", this.config.returning ? this.dialect.mapperGenerators.rows(this.config.returning, void 0) : void 0, {
29116
+ type: "delete",
29117
+ tables: extractUsedTable(this.config.table)
29118
+ });
29119
+ }
29120
+ prepare() {
29121
+ return this._prepare(true);
29122
+ }
29123
+ run = (placeholderValues) => {
29124
+ return this._prepare().run(placeholderValues);
29125
+ };
29126
+ all = (placeholderValues) => {
29127
+ return this._prepare().all(placeholderValues);
29128
+ };
29129
+ get = (placeholderValues) => {
29130
+ return this._prepare().get(placeholderValues);
29131
+ };
29132
+ values = (placeholderValues) => {
29133
+ return this._prepare().values(placeholderValues);
29134
+ };
29135
+ async execute(placeholderValues) {
29136
+ return this._prepare().execute(placeholderValues);
29137
+ }
29138
+ };
29139
+ applyMixins(SQLiteAsyncDeleteBase, [QueryPromise]);
29140
+
29086
29141
  // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/sqlite-core/query-builders/insert.js
29087
29142
  var SQLiteInsertBuilder = class {
29088
29143
  static [entityKind] = "SQLiteInsertBuilder";
@@ -29970,129 +30025,6 @@ var SQLiteAsyncTransaction = class extends SQLiteAsyncDatabase {
29970
30025
  }
29971
30026
  };
29972
30027
 
29973
- // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/node-sqlite/session.js
29974
- var NodeSQLiteSession = class extends SQLiteAsyncSession {
29975
- static [entityKind] = "SQLJsSession";
29976
- logger;
29977
- constructor(client2, dialect, relations, options = {}) {
29978
- super(dialect, "sync");
29979
- this.client = client2;
29980
- this.relations = relations;
29981
- this.options = options;
29982
- this.logger = options.logger ?? new NoopLogger();
29983
- }
29984
- prepareQuery(query, mode, _prepare, executeMethod, mapper, queryMetadata) {
29985
- let stmt;
29986
- try {
29987
- stmt = this.client.prepare(query.sql);
29988
- } catch (e) {
29989
- throw new DrizzleQueryError(query.sql, query.params, e);
29990
- }
29991
- return new SQLiteAsyncPreparedQuery("sync", executeMethod, {
29992
- all: (params) => {
29993
- stmt.setReturnArrays(mode === "arrays");
29994
- const res = stmt.all(...params);
29995
- if (mode === "objects") return res.map((row) => ({ ...row }));
29996
- return res;
29997
- },
29998
- get: (params) => {
29999
- stmt.setReturnArrays(mode === "arrays");
30000
- const res = stmt.get(...params);
30001
- if (res && mode === "objects") return { ...res };
30002
- return res;
30003
- },
30004
- run: (params) => {
30005
- stmt.setReturnArrays(false);
30006
- return stmt.run(...params);
30007
- },
30008
- values: (params) => {
30009
- stmt.setReturnArrays(true);
30010
- return stmt.all(...params);
30011
- }
30012
- }, query, mapper, mode, this.logger, void 0, queryMetadata, void 0);
30013
- }
30014
- transaction(transaction, config2 = {}) {
30015
- const tx = new NodeSQLiteTransaction("sync", this.dialect, this, this.relations);
30016
- this.run(sql.raw(`begin${config2.behavior ? ` ${config2.behavior}` : ""}`));
30017
- try {
30018
- const result = transaction(tx);
30019
- this.run(sql`commit`);
30020
- return result;
30021
- } catch (err) {
30022
- this.run(sql`rollback`);
30023
- throw err;
30024
- }
30025
- }
30026
- };
30027
- var NodeSQLiteTransaction = class NodeSQLiteTransaction2 extends SQLiteAsyncTransaction {
30028
- static [entityKind] = "SQLJsTransaction";
30029
- transaction(transaction) {
30030
- const savepointName = `sp${this.nestedIndex + 1}`;
30031
- const tx = new NodeSQLiteTransaction2("sync", this.dialect, this.session, this._.relations, this.nestedIndex + 1);
30032
- tx.run(sql.raw(`savepoint ${savepointName}`));
30033
- try {
30034
- const result = transaction(tx);
30035
- tx.run(sql.raw(`release savepoint ${savepointName}`));
30036
- return result;
30037
- } catch (err) {
30038
- tx.run(sql.raw(`rollback to savepoint ${savepointName}`));
30039
- throw err;
30040
- }
30041
- }
30042
- };
30043
-
30044
- // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/node-sqlite/driver.js
30045
- import { DatabaseSync } from "node:sqlite";
30046
- var NodeSQLiteDatabase = class extends SQLiteAsyncDatabase {
30047
- static [entityKind] = "NodeSQLiteDatabase";
30048
- };
30049
- function construct(client2, config2 = {}) {
30050
- const dialect = new SQLiteDialect({ useJitMappers: jitCompatCheck(config2.jit) });
30051
- let logger;
30052
- if (config2.logger === true) logger = new DefaultLogger();
30053
- else if (config2.logger !== false) logger = config2.logger;
30054
- const relations = config2.relations ?? {};
30055
- const db = new NodeSQLiteDatabase("sync", dialect, new NodeSQLiteSession(client2, dialect, relations, { logger }), relations);
30056
- db.$client = client2;
30057
- return db;
30058
- }
30059
- function drizzle(...params) {
30060
- if (params[0] === void 0 || typeof params[0] === "string") return construct(params[0] === void 0 ? new DatabaseSync(":memory:") : new DatabaseSync(params[0]), params[1]);
30061
- const { connection, client: client2, ...config2 } = params[0];
30062
- if (client2) return construct(client2, config2);
30063
- if (typeof connection === "object") {
30064
- const { path: path2, ...options } = connection;
30065
- return construct(new DatabaseSync(path2 ?? ":memory:", options), config2);
30066
- }
30067
- return construct(new DatabaseSync(connection ?? ":memory:"), config2);
30068
- }
30069
- (function(_drizzle) {
30070
- function mock(config2) {
30071
- return construct({}, config2);
30072
- }
30073
- _drizzle.mock = mock;
30074
- })(drizzle || (drizzle = {}));
30075
-
30076
- // src/generated/acp-session-store-migrations.ts
30077
- var acpSessionStoreMigrations = [
30078
- {
30079
- "name": "0000_slimy_captain_midlands.sql",
30080
- "sql": "CREATE TABLE `acp_session` (\n `session_id` text PRIMARY KEY NOT NULL,\n `agent_id` text NOT NULL,\n `native_session_id` text NOT NULL,\n `cwd` text NOT NULL,\n `additional_directories` text NOT NULL,\n `prompted` integer NOT NULL,\n `title` text NOT NULL,\n `updated_at` text NOT NULL\n);\n--> statement-breakpoint\nCREATE TABLE `deleted_acp_session` (\n `session_id` text PRIMARY KEY NOT NULL\n);\n"
30081
- },
30082
- {
30083
- "name": "0001_regular_ultimates.sql",
30084
- "sql": "ALTER TABLE `acp_session` ADD `last_terminal_command_id` text;"
30085
- },
30086
- {
30087
- "name": "0002_equal_black_queen.sql",
30088
- "sql": "CREATE TABLE `session_event_v2` (\n `event_id` text PRIMARY KEY NOT NULL,\n `event_json` text NOT NULL,\n `position` integer NOT NULL,\n `session_id` text NOT NULL\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX `session_event_v2_session_position_unique` ON `session_event_v2` (`session_id`,`position`);--> statement-breakpoint\nCREATE INDEX `session_event_v2_session_position_index` ON `session_event_v2` (`session_id`,`position`);"
30089
- },
30090
- {
30091
- "name": "0003_silky_ravenous.sql",
30092
- "sql": "DROP TABLE `session_event_v2`;"
30093
- }
30094
- ];
30095
-
30096
30028
  // src/schema/acp-session-store/acp-session.ts
30097
30029
  var acpSession = sqliteTable("acp_session", {
30098
30030
  sessionId: text("session_id").primaryKey(),
@@ -30100,33 +30032,235 @@ var acpSession = sqliteTable("acp_session", {
30100
30032
  nativeSessionId: text("native_session_id").notNull(),
30101
30033
  cwd: text("cwd").notNull(),
30102
30034
  additionalDirectories: text("additional_directories").notNull(),
30103
- lastTerminalCommandId: text("last_terminal_command_id"),
30104
30035
  prompted: integer2("prompted", { mode: "boolean" }).notNull(),
30105
30036
  title: text("title").notNull(),
30106
30037
  updatedAt: text("updated_at").notNull()
30107
30038
  });
30108
30039
 
30109
- // src/schema/acp-session-store/deleted-acp-session.ts
30110
- var deletedAcpSession = sqliteTable("deleted_acp_session", {
30111
- sessionId: text("session_id").primaryKey()
30112
- });
30040
+ // src/schema/session-event-cache/session-event-v2.ts
30041
+ var sessionEventV2 = sqliteTable(
30042
+ "session_event_v2",
30043
+ {
30044
+ eventJson: text("event_json").notNull(),
30045
+ generationId: text("generation_id").notNull(),
30046
+ position: integer2("position").notNull(),
30047
+ sessionId: text("session_id").notNull()
30048
+ },
30049
+ (table) => [
30050
+ primaryKey({ columns: [table.generationId, table.sessionId, table.position] }),
30051
+ index("session_event_v2_generation_session_position_index").on(
30052
+ table.generationId,
30053
+ table.sessionId,
30054
+ table.position
30055
+ )
30056
+ ]
30057
+ );
30058
+
30059
+ // src/acp/session-event-store-v2.ts
30060
+ var HOT_EVENT_HIGH_WATER_MARK = 256;
30061
+ var HOT_EVENT_RETENTION = 128;
30062
+ function eventPage(eventCount, eventLimit, cursor, read) {
30063
+ const parsedCursor = cursor === null ? eventCount : Number(cursor);
30064
+ if (!Number.isSafeInteger(parsedCursor) || parsedCursor < 0 || parsedCursor > eventCount) {
30065
+ throw new Error("The native event cursor is invalid");
30066
+ }
30067
+ const endPosition = parsedCursor;
30068
+ const startPosition = Math.max(0, endPosition - eventLimit);
30069
+ return {
30070
+ events: read(startPosition + 1, endPosition),
30071
+ nextCursor: startPosition === 0 ? null : startPosition.toString(),
30072
+ startPosition: startPosition + 1,
30073
+ truncated: startPosition > 0
30074
+ };
30075
+ }
30076
+ var MemoryAcpSessionEventStoreV2 = class {
30077
+ generationId;
30078
+ #events = /* @__PURE__ */ new Map();
30079
+ constructor(generationId) {
30080
+ this.generationId = generationId;
30081
+ }
30082
+ append = (sessionId, event) => {
30083
+ const events = this.#events.get(sessionId) ?? [];
30084
+ events.push(event);
30085
+ this.#events.set(sessionId, events);
30086
+ return events.length;
30087
+ };
30088
+ close = () => this.#events.clear();
30089
+ page = (sessionId, eventLimit, cursor) => {
30090
+ const events = this.#events.get(sessionId) ?? [];
30091
+ return eventPage(
30092
+ events.length,
30093
+ eventLimit,
30094
+ cursor,
30095
+ (startPosition, endPosition) => events.slice(startPosition - 1, endPosition)
30096
+ );
30097
+ };
30098
+ remove = (sessionId) => {
30099
+ this.#events.delete(sessionId);
30100
+ };
30101
+ reset = this.remove;
30102
+ };
30103
+ var cachedEventRowSchema = external_exports.object({ eventJson: external_exports.string(), position: external_exports.number().int().positive() });
30104
+ function decodeCachedEvent(value) {
30105
+ const payload = external_exports.record(external_exports.string(), external_exports.unknown()).parse(value);
30106
+ const event = decodeSessionEventV2({
30107
+ ...payload,
30108
+ eventId: "cached-event",
30109
+ position: "1",
30110
+ provenance: { kind: "original" },
30111
+ recordedAt: "1970-01-01T00:00:00.000Z",
30112
+ sessionId: "cached-session"
30113
+ });
30114
+ return event.type === "acp" ? { payload: event.payload, type: event.type } : { payload: event.payload, type: event.type };
30115
+ }
30116
+ var CachedAcpSessionEventStoreV2 = class {
30117
+ generationId;
30118
+ #database;
30119
+ #ignoredPersistedSessions = /* @__PURE__ */ new Set();
30120
+ #localDatabase;
30121
+ #sessions = /* @__PURE__ */ new Map();
30122
+ #flushSchedule = { kind: "idle" };
30123
+ #isLocalDBAvailable = true;
30124
+ constructor(localDatabase, generationId) {
30125
+ this.generationId = generationId;
30126
+ this.#localDatabase = localDatabase;
30127
+ this.#database = localDatabase.orm;
30128
+ try {
30129
+ this.#localDatabase.transaction(() => this.#database.delete(sessionEventV2).run());
30130
+ } catch (error62) {
30131
+ this.#localDatabase.close();
30132
+ throw error62;
30133
+ }
30134
+ }
30135
+ append = (sessionId, event) => {
30136
+ if (this.#flushSchedule.kind === "closed") {
30137
+ throw new Error("The V2 Session event store is closed");
30138
+ }
30139
+ const session = this.#sessions.get(sessionId) ?? { hot: [], nextPosition: 1 };
30140
+ const position = session.nextPosition;
30141
+ session.hot.push({ event, position });
30142
+ session.nextPosition += 1;
30143
+ this.#sessions.set(sessionId, session);
30144
+ if (session.hot.length > HOT_EVENT_HIGH_WATER_MARK) {
30145
+ this.#scheduleFlush();
30146
+ }
30147
+ return position;
30148
+ };
30149
+ #scheduleFlush = () => {
30150
+ if (!this.#isLocalDBAvailable || this.#flushSchedule.kind !== "idle") {
30151
+ return;
30152
+ }
30153
+ const handle = setImmediate(() => {
30154
+ if (this.#flushSchedule.kind !== "scheduled" || this.#flushSchedule.handle !== handle) {
30155
+ return;
30156
+ }
30157
+ this.#flushSchedule = { kind: "idle" };
30158
+ this.#flush(false);
30159
+ });
30160
+ this.#flushSchedule = { handle, kind: "scheduled" };
30161
+ };
30162
+ #flush = (includeHotTail) => {
30163
+ if (!this.#isLocalDBAvailable || this.#flushSchedule.kind === "closed") {
30164
+ return;
30165
+ }
30166
+ const batches = [...this.#sessions.entries()].flatMap(([sessionId, session]) => {
30167
+ const count = includeHotTail ? session.hot.length : Math.max(0, session.hot.length - HOT_EVENT_RETENTION);
30168
+ return count === 0 ? [] : [{ count, events: session.hot.slice(0, count), sessionId }];
30169
+ });
30170
+ const values = batches.flatMap(
30171
+ (batch) => batch.events.map(({ event, position }) => ({
30172
+ eventJson: JSON.stringify(event),
30173
+ generationId: this.generationId,
30174
+ position,
30175
+ sessionId: batch.sessionId
30176
+ }))
30177
+ );
30178
+ if (values.length === 0) {
30179
+ return;
30180
+ }
30181
+ try {
30182
+ this.#localDatabase.transaction(() => {
30183
+ for (let offset = 0; offset < values.length; offset += 200) {
30184
+ this.#database.insert(sessionEventV2).values(values.slice(offset, offset + 200)).run();
30185
+ }
30186
+ });
30187
+ for (const batch of batches) {
30188
+ this.#sessions.get(batch.sessionId)?.hot.splice(0, batch.count);
30189
+ }
30190
+ } catch (cause) {
30191
+ this.#isLocalDBAvailable = false;
30192
+ console.warn("Mobius V2 Session event cache writes are unavailable; retaining events in memory", cause);
30193
+ }
30194
+ };
30195
+ page = (sessionId, eventLimit, cursor) => {
30196
+ const session = this.#sessions.get(sessionId);
30197
+ const eventCount = (session?.nextPosition ?? 1) - 1;
30198
+ return eventPage(eventCount, eventLimit, cursor, (startPosition, endPosition) => {
30199
+ const persisted = this.#ignoredPersistedSessions.has(sessionId) ? [] : this.#database.select({ eventJson: sessionEventV2.eventJson, position: sessionEventV2.position }).from(sessionEventV2).where(
30200
+ and(
30201
+ eq(sessionEventV2.generationId, this.generationId),
30202
+ eq(sessionEventV2.sessionId, sessionId),
30203
+ gte(sessionEventV2.position, startPosition),
30204
+ lte(sessionEventV2.position, endPosition)
30205
+ )
30206
+ ).orderBy(asc(sessionEventV2.position)).all().map((value) => {
30207
+ const row = cachedEventRowSchema.parse(value);
30208
+ return { event: decodeCachedEvent(JSON.parse(row.eventJson)), position: row.position };
30209
+ });
30210
+ const hot = (session?.hot ?? []).filter(
30211
+ ({ position }) => position >= startPosition && position <= endPosition
30212
+ );
30213
+ return [...persisted, ...hot].toSorted((left, right) => left.position - right.position).map(({ event }) => event);
30214
+ });
30215
+ };
30216
+ #deletePersisted = (sessionId) => {
30217
+ if (!this.#isLocalDBAvailable) {
30218
+ this.#ignoredPersistedSessions.add(sessionId);
30219
+ return;
30220
+ }
30221
+ try {
30222
+ this.#database.delete(sessionEventV2).where(and(eq(sessionEventV2.generationId, this.generationId), eq(sessionEventV2.sessionId, sessionId))).run();
30223
+ this.#ignoredPersistedSessions.delete(sessionId);
30224
+ } catch (cause) {
30225
+ this.#isLocalDBAvailable = false;
30226
+ this.#ignoredPersistedSessions.add(sessionId);
30227
+ console.warn("Mobius V2 Session event cache writes are unavailable; retaining events in memory", cause);
30228
+ }
30229
+ };
30230
+ remove = (sessionId) => {
30231
+ this.#deletePersisted(sessionId);
30232
+ this.#sessions.delete(sessionId);
30233
+ };
30234
+ reset = this.remove;
30235
+ close = () => {
30236
+ if (this.#flushSchedule.kind === "closed") {
30237
+ return;
30238
+ }
30239
+ if (this.#flushSchedule.kind === "scheduled") {
30240
+ clearImmediate(this.#flushSchedule.handle);
30241
+ }
30242
+ this.#flushSchedule = { kind: "idle" };
30243
+ this.#flush(true);
30244
+ this.#flushSchedule = { kind: "closed" };
30245
+ this.#localDatabase.close();
30246
+ this.#sessions.clear();
30247
+ };
30248
+ };
30113
30249
 
30114
30250
  // src/acp/session-store.ts
30115
30251
  var AcpStoredSession = class {
30116
30252
  additionalDirectories;
30117
30253
  agentId;
30118
30254
  cwd;
30119
- lastTerminalCommandId;
30120
30255
  nativeSessionId;
30121
30256
  prompted;
30122
30257
  sessionId;
30123
30258
  title;
30124
30259
  updatedAt;
30125
- constructor(sessionId, agentId, nativeSessionId, cwd, additionalDirectories, prompted, title2, updatedAt = (/* @__PURE__ */ new Date()).toISOString(), lastTerminalCommandId = null) {
30260
+ constructor(sessionId, agentId, nativeSessionId, cwd, additionalDirectories, prompted, title2, updatedAt = (/* @__PURE__ */ new Date()).toISOString()) {
30126
30261
  this.additionalDirectories = [...additionalDirectories];
30127
30262
  this.agentId = agentId;
30128
30263
  this.cwd = cwd;
30129
- this.lastTerminalCommandId = lastTerminalCommandId;
30130
30264
  this.nativeSessionId = nativeSessionId;
30131
30265
  this.prompted = prompted;
30132
30266
  this.sessionId = sessionId;
@@ -30147,37 +30281,27 @@ var FoundAcpStoredSession = class extends AcpStoredSessionLookup {
30147
30281
  this.session = session;
30148
30282
  }
30149
30283
  };
30150
- var DeletedAcpStoredSession = class extends AcpStoredSessionLookup {
30151
- found = false;
30152
- };
30153
30284
  var MemoryAcpSessionStore = class {
30285
+ eventsV2;
30154
30286
  #sessions = /* @__PURE__ */ new Map();
30155
- #deleted = /* @__PURE__ */ new Set();
30287
+ constructor(eventsV2 = new MemoryAcpSessionEventStoreV2(randomUUID())) {
30288
+ this.eventsV2 = eventsV2;
30289
+ }
30156
30290
  close = () => {
30157
30291
  this.#sessions.clear();
30158
- this.#deleted.clear();
30292
+ this.eventsV2.close();
30159
30293
  };
30160
30294
  findNative = (agentId, nativeSessionId) => [...this.#sessions.values()].filter(
30161
30295
  (session) => session.agentId === agentId && session.nativeSessionId === nativeSessionId
30162
30296
  );
30163
30297
  list = () => [...this.#sessions.values()].toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt));
30164
- markDeleted = (agentId, nativeSessionId) => {
30165
- const ids = this.findNative(agentId, nativeSessionId).map((session) => session.sessionId);
30166
- for (const id of ids) {
30167
- this.#sessions.delete(id);
30168
- this.#deleted.add(id);
30169
- }
30170
- return ids;
30171
- };
30172
30298
  read = (sessionId) => {
30173
- if (this.#deleted.has(sessionId)) {
30174
- return new DeletedAcpStoredSession();
30175
- }
30176
30299
  const session = this.#sessions.get(sessionId);
30177
30300
  return session === void 0 ? new MissingAcpStoredSession() : new FoundAcpStoredSession(session);
30178
30301
  };
30179
30302
  remove = (sessionId) => {
30180
30303
  this.#sessions.delete(sessionId);
30304
+ this.eventsV2.remove(sessionId);
30181
30305
  };
30182
30306
  write = (session) => {
30183
30307
  this.#sessions.set(session.sessionId, session);
@@ -30187,14 +30311,12 @@ var storedSessionRowSchema = external_exports.object({
30187
30311
  additionalDirectories: external_exports.string(),
30188
30312
  agentId: external_exports.string(),
30189
30313
  cwd: external_exports.string(),
30190
- lastTerminalCommandId: external_exports.string().nullable(),
30191
30314
  nativeSessionId: external_exports.string(),
30192
30315
  prompted: external_exports.boolean(),
30193
30316
  sessionId: external_exports.string(),
30194
30317
  title: external_exports.string(),
30195
30318
  updatedAt: external_exports.string()
30196
30319
  });
30197
- var sessionIdRowSchema = external_exports.object({ sessionId: external_exports.string() });
30198
30320
  function decodeStoredSession(value) {
30199
30321
  const row = storedSessionRowSchema.parse(value);
30200
30322
  const decodedAdditionalDirectories = JSON.parse(row.additionalDirectories);
@@ -30207,98 +30329,47 @@ function decodeStoredSession(value) {
30207
30329
  additionalDirectories,
30208
30330
  row.prompted,
30209
30331
  row.title,
30210
- row.updatedAt,
30211
- row.lastTerminalCommandId
30332
+ row.updatedAt
30212
30333
  );
30213
30334
  }
30214
30335
  var SqliteAcpSessionStore = class {
30336
+ eventsV2;
30215
30337
  #database;
30216
- #sqliteDatabase;
30217
- constructor(path2) {
30218
- mkdirSync(dirname(path2), { mode: 448, recursive: true });
30219
- this.#sqliteDatabase = new DatabaseSync2(path2);
30220
- chmodSync(path2, 384);
30221
- this.#migrate();
30222
- this.#database = drizzle({ client: this.#sqliteDatabase });
30338
+ #localDatabase;
30339
+ constructor(localDatabase, eventsV2 = new MemoryAcpSessionEventStoreV2(randomUUID())) {
30340
+ this.eventsV2 = eventsV2;
30341
+ this.#localDatabase = localDatabase;
30342
+ this.#database = localDatabase.orm;
30223
30343
  }
30224
- #migrate = () => {
30225
- const version2 = external_exports.object({ user_version: external_exports.number().int().nonnegative() }).parse(this.#sqliteDatabase.prepare("PRAGMA user_version").get()).user_version;
30226
- if (version2 > acpSessionStoreMigrations.length) {
30227
- this.#sqliteDatabase.close();
30228
- throw new Error("The ACP Session database was created by a newer Mobius version");
30229
- }
30230
- for (let index = version2; index < acpSessionStoreMigrations.length; index += 1) {
30231
- const migration = acpSessionStoreMigrations[index];
30232
- if (migration === void 0) {
30233
- throw new Error("The ACP Session migration is unavailable");
30234
- }
30235
- this.#sqliteDatabase.exec("BEGIN IMMEDIATE");
30236
- try {
30237
- this.#sqliteDatabase.exec(migration.sql);
30238
- this.#sqliteDatabase.exec(`PRAGMA user_version = ${index + 1}`);
30239
- this.#sqliteDatabase.exec("COMMIT");
30240
- } catch (error62) {
30241
- this.#sqliteDatabase.exec("ROLLBACK");
30242
- throw error62;
30243
- }
30244
- }
30245
- };
30246
- #transaction = (operation) => {
30247
- this.#sqliteDatabase.exec("BEGIN IMMEDIATE");
30344
+ close = () => {
30248
30345
  try {
30249
- operation();
30250
- this.#sqliteDatabase.exec("COMMIT");
30251
- } catch (error62) {
30252
- this.#sqliteDatabase.exec("ROLLBACK");
30253
- throw error62;
30346
+ this.#localDatabase.close();
30347
+ } finally {
30348
+ this.eventsV2.close();
30254
30349
  }
30255
30350
  };
30256
- close = () => {
30257
- this.#sqliteDatabase.close();
30258
- };
30259
30351
  findNative = (agentId, nativeSessionId) => this.#database.select().from(acpSession).where(and(eq(acpSession.agentId, agentId), eq(acpSession.nativeSessionId, nativeSessionId))).all().map(decodeStoredSession);
30260
30352
  list = () => this.#database.select().from(acpSession).orderBy(desc(acpSession.updatedAt)).all().map(decodeStoredSession);
30261
- markDeleted = (agentId, nativeSessionId) => {
30262
- const ids = this.#database.select({ sessionId: acpSession.sessionId }).from(acpSession).where(and(eq(acpSession.agentId, agentId), eq(acpSession.nativeSessionId, nativeSessionId))).all().map((row) => sessionIdRowSchema.parse(row).sessionId);
30263
- this.#transaction(() => {
30264
- this.#database.delete(acpSession).where(and(eq(acpSession.agentId, agentId), eq(acpSession.nativeSessionId, nativeSessionId))).run();
30265
- for (const id of ids) {
30266
- this.#database.insert(deletedAcpSession).values({ sessionId: id }).onConflictDoNothing().run();
30267
- }
30268
- });
30269
- return ids;
30270
- };
30271
30353
  read = (sessionId) => {
30272
- const deleted = this.#database.select({ sessionId: deletedAcpSession.sessionId }).from(deletedAcpSession).where(eq(deletedAcpSession.sessionId, sessionId)).get();
30273
- if (deleted !== void 0) {
30274
- sessionIdRowSchema.parse(deleted);
30275
- return new DeletedAcpStoredSession();
30276
- }
30277
30354
  const row = this.#database.select().from(acpSession).where(eq(acpSession.sessionId, sessionId)).get();
30278
30355
  return row === void 0 ? new MissingAcpStoredSession() : new FoundAcpStoredSession(decodeStoredSession(row));
30279
30356
  };
30280
30357
  remove = (sessionId) => {
30281
30358
  this.#database.delete(acpSession).where(eq(acpSession.sessionId, sessionId)).run();
30359
+ this.eventsV2.remove(sessionId);
30282
30360
  };
30283
30361
  write = (session) => {
30284
30362
  const value = {
30285
30363
  additionalDirectories: JSON.stringify(session.additionalDirectories),
30286
30364
  agentId: session.agentId,
30287
30365
  cwd: session.cwd,
30288
- lastTerminalCommandId: session.lastTerminalCommandId,
30289
30366
  nativeSessionId: session.nativeSessionId,
30290
30367
  prompted: session.prompted,
30291
30368
  sessionId: session.sessionId,
30292
30369
  title: session.title,
30293
30370
  updatedAt: session.updatedAt
30294
30371
  };
30295
- this.#transaction(() => {
30296
- this.#database.delete(deletedAcpSession).where(eq(deletedAcpSession.sessionId, session.sessionId)).run();
30297
- this.#database.insert(acpSession).values(value).onConflictDoUpdate({
30298
- target: acpSession.sessionId,
30299
- set: value
30300
- }).run();
30301
- });
30372
+ this.#database.insert(acpSession).values(value).onConflictDoUpdate({ target: acpSession.sessionId, set: value }).run();
30302
30373
  };
30303
30374
  };
30304
30375
 
@@ -30311,7 +30382,7 @@ var RetryableAcpInitializationError = class extends AcpExecutionError {
30311
30382
  }
30312
30383
  };
30313
30384
  function arraysEqual(left, right) {
30314
- return left.length === right.length && left.every((value, index) => value === right[index]);
30385
+ return left.length === right.length && left.every((value, index2) => value === right[index2]);
30315
30386
  }
30316
30387
  function recordsEqual(left, right) {
30317
30388
  const leftEntries = Object.entries(left);
@@ -30339,7 +30410,6 @@ var AgentSession = class _AgentSession {
30339
30410
  #commands = [];
30340
30411
  #configRevision = 0;
30341
30412
  #configOptions = [];
30342
- #lastTerminalCommandId = null;
30343
30413
  #nativeHistoryOwnership = { kind: "unbound" };
30344
30414
  #prompted = false;
30345
30415
  #nativePrompt = null;
@@ -30475,12 +30545,17 @@ var AgentSession = class _AgentSession {
30475
30545
  );
30476
30546
  }
30477
30547
  const history = await this.#completedHistory(signal, "ACP agent exited while loading history");
30478
- return history.eventPage(eventLimit, cursor, this.#turnHistory);
30548
+ return history.eventPage(eventLimit, cursor);
30479
30549
  };
30480
30550
  async #completedHistory(signal, exitMessage) {
30481
30551
  if (!this.#prompted && this.#nativeHistoryOwnership.kind === "fresh-session") {
30482
30552
  if (this.#sessionLoad.kind === "not-requested") {
30483
- this.#sessionLoad = { history: new AcpHistoryReplay(), kind: "loaded", response: {} };
30553
+ this.#store.eventsV2.reset(this.#mobiusSessionId);
30554
+ this.#sessionLoad = {
30555
+ history: new AcpHistoryReplay(this.#store.eventsV2, this.#mobiusSessionId),
30556
+ kind: "loaded",
30557
+ response: {}
30558
+ };
30484
30559
  }
30485
30560
  if (this.#sessionLoad.kind === "loaded") {
30486
30561
  return this.#sessionLoad.history;
@@ -30495,7 +30570,8 @@ var AgentSession = class _AgentSession {
30495
30570
  if (this.#sessionLoad.kind === "capturing") {
30496
30571
  return await waitForSharedOperation(this.#sessionLoad.completion, signal);
30497
30572
  }
30498
- const history = new AcpHistoryReplay();
30573
+ this.#store.eventsV2.reset(this.#mobiusSessionId);
30574
+ const history = new AcpHistoryReplay(this.#store.eventsV2, this.#mobiusSessionId);
30499
30575
  const completion = Promise.resolve().then(async () => {
30500
30576
  try {
30501
30577
  const response = await this.race(
@@ -30652,13 +30728,6 @@ var AgentSession = class _AgentSession {
30652
30728
  this.#store.remove(this.#mobiusSessionId);
30653
30729
  stored = this.#metrics.measureSync("session-state-read", () => this.#store.read(this.#mobiusSessionId));
30654
30730
  }
30655
- if (stored instanceof DeletedAcpStoredSession) {
30656
- throw new AcpExecutionError(
30657
- "The native Agent session was deleted. Start a new chat.",
30658
- {},
30659
- "native_session_deleted"
30660
- );
30661
- }
30662
30731
  let lifecycleResponse;
30663
30732
  if (origin?.kind === "fork") {
30664
30733
  if (!this.#capabilities.unstableForkSession) {
@@ -30706,7 +30775,6 @@ var AgentSession = class _AgentSession {
30706
30775
  } else if (stored instanceof FoundAcpStoredSession && stored.session.agentId === this.#agentId && stored.session.cwd === this.#cwd && arraysEqual(stored.session.additionalDirectories, this.#additionalDirectories)) {
30707
30776
  this.selectNativeSession(stored.session.nativeSessionId);
30708
30777
  this.#prompted = stored.session.prompted;
30709
- this.#lastTerminalCommandId = stored.session.lastTerminalCommandId;
30710
30778
  this.#sessionTitle = stored.session.title;
30711
30779
  this.#restored = true;
30712
30780
  if (this.#capabilities.resumeSession) {
@@ -30782,8 +30850,7 @@ var AgentSession = class _AgentSession {
30782
30850
  this.#additionalDirectories,
30783
30851
  this.#prompted,
30784
30852
  this.#sessionTitle ?? "",
30785
- (/* @__PURE__ */ new Date()).toISOString(),
30786
- this.#lastTerminalCommandId
30853
+ (/* @__PURE__ */ new Date()).toISOString()
30787
30854
  )
30788
30855
  );
30789
30856
  };
@@ -30812,24 +30879,6 @@ var AgentSession = class _AgentSession {
30812
30879
  }
30813
30880
  return decoded.data;
30814
30881
  };
30815
- deleteNativeSession = async (nativeSessionId, signal) => {
30816
- if (!this.#capabilities.deleteSession || !this.#capabilities.listSessions) {
30817
- throw new AcpExecutionError(
30818
- "This Agent does not support native session deletion",
30819
- {},
30820
- "native_session_unsupported"
30821
- );
30822
- }
30823
- await this.race(
30824
- this.#connection.connection.agent.request(
30825
- methods3.agent.session.delete,
30826
- { sessionId: nativeSessionIdSchema.parse(nativeSessionId) },
30827
- { cancellationSignal: signal }
30828
- ),
30829
- "ACP agent exited while deleting a session",
30830
- signal
30831
- );
30832
- };
30833
30882
  nativeSessionId = () => this.#updates.sessionId();
30834
30883
  adoptNativeSessionId = (sessionId) => {
30835
30884
  if (this.#prompted || this.#updates.sessionId() !== sessionId) {
@@ -30985,8 +31034,7 @@ var AgentSession = class _AgentSession {
30985
31034
  this.#additionalDirectories,
30986
31035
  true,
30987
31036
  this.#sessionTitle,
30988
- (/* @__PURE__ */ new Date()).toISOString(),
30989
- this.#lastTerminalCommandId
31037
+ (/* @__PURE__ */ new Date()).toISOString()
30990
31038
  )
30991
31039
  );
30992
31040
  this.#prompted = true;
@@ -30998,7 +31046,7 @@ var AgentSession = class _AgentSession {
30998
31046
  this.prepareAgentContent
30999
31047
  );
31000
31048
  this.#turn = running;
31001
- this.#turnHistory = completedHistory === null ? null : new AcpHistoryReplay();
31049
+ this.#turnHistory = completedHistory === null ? null : new AcpHistoryReplay(this.#store.eventsV2, this.#mobiusSessionId);
31002
31050
  const lifecycleV2 = options.lifecycleV2;
31003
31051
  if (lifecycleV2 !== void 0) {
31004
31052
  await this.#recordLifecycleEventV2({
@@ -31055,7 +31103,6 @@ var AgentSession = class _AgentSession {
31055
31103
  usage: result.usage ?? null
31056
31104
  });
31057
31105
  }
31058
- this.#lastTerminalCommandId = options.commandId;
31059
31106
  this.#store.write(
31060
31107
  new AcpStoredSession(
31061
31108
  this.#mobiusSessionId,
@@ -31065,8 +31112,7 @@ var AgentSession = class _AgentSession {
31065
31112
  this.#additionalDirectories,
31066
31113
  true,
31067
31114
  this.#sessionTitle ?? "",
31068
- (/* @__PURE__ */ new Date()).toISOString(),
31069
- this.#lastTerminalCommandId
31115
+ (/* @__PURE__ */ new Date()).toISOString()
31070
31116
  )
31071
31117
  );
31072
31118
  if (lifecycleV2 !== void 0) {
@@ -31213,7 +31259,7 @@ var AgentSession = class _AgentSession {
31213
31259
  if (event.type !== "lifecycle-metadata" || this.#sessionLoad.kind !== "loaded") {
31214
31260
  return;
31215
31261
  }
31216
- const position = this.#turnHistory === null ? this.#sessionLoad.history.recordLifecycle(event) : this.#sessionLoad.history.eventCount() + this.#turnHistory.recordLifecycle(event);
31262
+ const position = this.#turnHistory === null ? this.#sessionLoad.history.recordLifecycle(event) : this.#turnHistory.recordLifecycle(event);
31217
31263
  await this.#getObserver().onSessionEventV2?.(this.#mobiusSessionId, event, position);
31218
31264
  };
31219
31265
  selectNativeSession = (sessionId) => {
@@ -31234,13 +31280,8 @@ var AgentSession = class _AgentSession {
31234
31280
  } else {
31235
31281
  const onSessionEventV2 = this.#getObserver().onSessionEventV2;
31236
31282
  if (this.#turnHistory !== null) {
31237
- const completedEventCount = this.#sessionLoad.kind === "loaded" ? this.#sessionLoad.history.eventCount() : 0;
31238
- await this.#turnHistory.record(update, rawUpdate, async (turnPosition) => {
31239
- await onSessionEventV2?.(
31240
- this.#mobiusSessionId,
31241
- { payload: rawUpdate, type: "acp" },
31242
- completedEventCount + turnPosition
31243
- );
31283
+ await this.#turnHistory.record(update, rawUpdate, async (position) => {
31284
+ await onSessionEventV2?.(this.#mobiusSessionId, { payload: rawUpdate, type: "acp" }, position);
31244
31285
  });
31245
31286
  } else if (this.#sessionLoad.kind === "loaded") {
31246
31287
  await this.#sessionLoad.history.record(update, rawUpdate, async (position) => {
@@ -31354,8 +31395,7 @@ var AgentSession = class _AgentSession {
31354
31395
  this.#additionalDirectories,
31355
31396
  this.#prompted,
31356
31397
  this.#sessionTitle ?? "",
31357
- (/* @__PURE__ */ new Date()).toISOString(),
31358
- this.#lastTerminalCommandId
31398
+ (/* @__PURE__ */ new Date()).toISOString()
31359
31399
  )
31360
31400
  );
31361
31401
  }
@@ -31884,9 +31924,9 @@ var AcpContentExternalizer = class {
31884
31924
  };
31885
31925
 
31886
31926
  // src/external-content/local-external-content-store.ts
31887
- import { createHash, randomUUID } from "node:crypto";
31927
+ import { createHash, randomUUID as randomUUID2 } from "node:crypto";
31888
31928
  import { lstat, mkdir, readdir as readdir2, realpath as realpath3, rename, rm, stat as stat3, utimes, writeFile } from "node:fs/promises";
31889
- import { dirname as dirname2, join as join4 } from "node:path";
31929
+ import { dirname, join as join4 } from "node:path";
31890
31930
  var contentRequest = /^mobius-content:(image|audio|resource):([a-f0-9]{64})$/u;
31891
31931
  var CONTENT_LIFETIME_MILLISECONDS = 24 * 60 * 60 * 1e3;
31892
31932
  var metadataSchema2 = external_exports.strictObject({
@@ -31905,7 +31945,7 @@ var UnretainedExternalContentStore = class {
31905
31945
  };
31906
31946
  };
31907
31947
  async function atomicWrite(path2, bytes, signal) {
31908
- const temporary = `${path2}.${randomUUID()}.tmp`;
31948
+ const temporary = `${path2}.${randomUUID2()}.tmp`;
31909
31949
  try {
31910
31950
  await writeFile(temporary, bytes, { mode: 384, signal });
31911
31951
  signal.throwIfAborted();
@@ -31922,7 +31962,7 @@ var LocalExternalContentStore = class {
31922
31962
  #expirationTimer;
31923
31963
  #cleanup = Promise.resolve();
31924
31964
  constructor(stateDirectory) {
31925
- this.#root = join4(stateDirectory, "tmp", "session-content", randomUUID());
31965
+ this.#root = join4(stateDirectory, "tmp", "session-content", randomUUID2());
31926
31966
  this.#expirationTimer = setInterval(() => {
31927
31967
  void this.#expire().catch(() => void 0);
31928
31968
  }, 6e4);
@@ -31933,11 +31973,11 @@ var LocalExternalContentStore = class {
31933
31973
  await mkdir(this.#root, { mode: 448, recursive: true });
31934
31974
  const now = /* @__PURE__ */ new Date();
31935
31975
  await utimes(this.#root, now, now);
31936
- for (const directory of await readdir2(dirname2(this.#root), { withFileTypes: true })) {
31976
+ for (const directory of await readdir2(dirname(this.#root), { withFileTypes: true })) {
31937
31977
  if (!directory.isDirectory() || !/^[a-f0-9-]{36}$/u.test(directory.name)) {
31938
31978
  continue;
31939
31979
  }
31940
- const path2 = join4(dirname2(this.#root), directory.name);
31980
+ const path2 = join4(dirname(this.#root), directory.name);
31941
31981
  if (path2 === this.#root) {
31942
31982
  continue;
31943
31983
  }
@@ -32023,12 +32063,12 @@ var LocalExternalContentStore = class {
32023
32063
  }
32024
32064
  try {
32025
32065
  const [resolvedDirectory, resolvedPath, file2] = await Promise.all([
32026
- realpath3(dirname2(entry.path)),
32066
+ realpath3(dirname(entry.path)),
32027
32067
  realpath3(entry.path),
32028
32068
  lstat(entry.path)
32029
32069
  ]);
32030
32070
  signal.throwIfAborted();
32031
- if (!file2.isFile() || file2.isSymbolicLink() || dirname2(resolvedPath) !== resolvedDirectory) {
32071
+ if (!file2.isFile() || file2.isSymbolicLink() || dirname(resolvedPath) !== resolvedDirectory) {
32032
32072
  return null;
32033
32073
  }
32034
32074
  return { mediaType: entry.mediaType, name: entry.name, path: resolvedPath };
@@ -32105,9 +32145,9 @@ var AcpProcessCapacityLock = class {
32105
32145
  return await waiter.completion.promise;
32106
32146
  } finally {
32107
32147
  signal.removeEventListener("abort", waiter.cancel);
32108
- const index = this.#waiters.indexOf(waiter);
32109
- if (index >= 0) {
32110
- this.#waiters.splice(index, 1);
32148
+ const index2 = this.#waiters.indexOf(waiter);
32149
+ if (index2 >= 0) {
32150
+ this.#waiters.splice(index2, 1);
32111
32151
  }
32112
32152
  }
32113
32153
  };
@@ -32396,13 +32436,6 @@ var AgentRuntimeManager = class {
32396
32436
  }
32397
32437
  prepareSession = async (options, metrics = unmeasuredOperationMetrics) => this.#operations.run(options, async (options2) => {
32398
32438
  const stored = metrics.measureSync("session-state-read", () => this.#store.read(options2.sessionId));
32399
- if (stored instanceof DeletedAcpStoredSession) {
32400
- throw new AcpExecutionError(
32401
- "The native Agent session was deleted. Start a new chat.",
32402
- {},
32403
- "native_session_deleted"
32404
- );
32405
- }
32406
32439
  if (stored instanceof FoundAcpStoredSession && this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`)) {
32407
32440
  throw new AcpExecutionError("The native session is being managed", {}, "session_busy");
32408
32441
  }
@@ -32851,7 +32884,7 @@ var AgentRuntimeManager = class {
32851
32884
  }
32852
32885
  });
32853
32886
  }
32854
- if (this.#executionProcesses.get(options2.sessionId) !== void 0 || this.#executionProcesses.pending(options2.sessionId) !== void 0 || this.#store.read(options2.sessionId) instanceof FoundAcpStoredSession || this.#store.read(options2.sessionId) instanceof DeletedAcpStoredSession) {
32887
+ if (this.#executionProcesses.get(options2.sessionId) !== void 0 || this.#executionProcesses.pending(options2.sessionId) !== void 0 || this.#store.read(options2.sessionId) instanceof FoundAcpStoredSession) {
32855
32888
  throw new AcpExecutionError(
32856
32889
  "The destination conversation already exists",
32857
32890
  {},
@@ -32897,40 +32930,6 @@ var AgentRuntimeManager = class {
32897
32930
  }
32898
32931
  });
32899
32932
  });
32900
- deleteNativeSession = async (options, nativeSessionId) => this.#operations.run(options, async (options2) => {
32901
- return await this.#queryProcesses.use(options2, async (runtime) => {
32902
- const key = `${options2.agent.id}:${nativeSessionId}`;
32903
- const linked = this.#store.findNative(options2.agent.id, nativeSessionId);
32904
- if (this.#nativeOperations.has(key) || linked.some(
32905
- (entry) => this.#executions.command(entry.sessionId) !== void 0 || this.#executionProcesses.pending(entry.sessionId) !== void 0
32906
- )) {
32907
- throw new AcpExecutionError(
32908
- "Wait for the native session's running operation to finish",
32909
- {},
32910
- "session_busy"
32911
- );
32912
- }
32913
- this.#nativeOperations.add(key);
32914
- try {
32915
- for (const entry of linked) {
32916
- const active = this.#executionProcesses.get(entry.sessionId);
32917
- if (active !== void 0 && active !== runtime) {
32918
- await this.#retireSessionProcess(entry.sessionId, active, async () => await active.close());
32919
- }
32920
- }
32921
- options2.signal.throwIfAborted();
32922
- await runtime.deleteNativeSession(nativeSessionId, options2.signal);
32923
- const deleted = this.#store.markDeleted(options2.agent.id, nativeSessionId);
32924
- if (runtime.nativeSessionId() === nativeSessionId) {
32925
- await this.#queryProcesses.retire(options2.sessionId, runtime);
32926
- }
32927
- return deleted;
32928
- } finally {
32929
- this.#nativeOperations.delete(key);
32930
- this.#processes.notifyChanged();
32931
- }
32932
- });
32933
- });
32934
32933
  };
32935
32934
 
32936
32935
  // src/acp/run-prompt.ts
@@ -33135,7 +33134,7 @@ var LocalAgentInventory = class {
33135
33134
 
33136
33135
  // src/agent-installation/managed-npm-package.ts
33137
33136
  import { mkdir as mkdir2, mkdtemp, open as open3, realpath as realpath4, rename as rename2, rm as rm2, stat as stat4 } from "node:fs/promises";
33138
- import { delimiter, dirname as dirname3, isAbsolute as isAbsolute2, join as join5, relative, sep } from "node:path";
33137
+ import { delimiter, dirname as dirname2, isAbsolute as isAbsolute2, join as join5, relative, sep } from "node:path";
33139
33138
  var INSTALL_TIMEOUT_MILLISECONDS = 5 * 60 * 1e3;
33140
33139
  var PACKAGE_METADATA_LIMIT_BYTES = 64 * 1024;
33141
33140
  var PACKAGE_LOCK_LIMIT_BYTES = 8 * 1024 * 1024;
@@ -33365,7 +33364,7 @@ var ManagedNpmPackageInstaller = class {
33365
33364
  throw error62;
33366
33365
  }
33367
33366
  }
33368
- const parent = dirname3(root);
33367
+ const parent = dirname2(root);
33369
33368
  await mkdir2(parent, { mode: 448, recursive: true });
33370
33369
  const staging = await mkdtemp(join5(parent, `.${definition.version}.staging-`));
33371
33370
  try {
@@ -33400,7 +33399,7 @@ var ManagedNpmPackageInstaller = class {
33400
33399
  NPM_CONFIG_IGNORE_SCRIPTS: "true",
33401
33400
  NPM_CONFIG_PACKAGE_LOCK: "true",
33402
33401
  NPM_CONFIG_REGISTRY: "https://registry.npmjs.org/",
33403
- PATH: `${dirname3(process.execPath)}${delimiter}/usr/bin${delimiter}/bin`
33402
+ PATH: `${dirname2(process.execPath)}${delimiter}/usr/bin${delimiter}/bin`
33404
33403
  };
33405
33404
  if (definition.includeOptionalDependencies) {
33406
33405
  installEnvironment["NPM_CONFIG_INCLUDE"] = "optional";
@@ -35885,7 +35884,7 @@ import { join as join11 } from "node:path";
35885
35884
  import { createHash as createHash2 } from "node:crypto";
35886
35885
  import { createReadStream } from "node:fs";
35887
35886
  import { chmod, copyFile, mkdir as mkdir4, mkdtemp as mkdtemp2, open as open4, realpath as realpath7, rename as rename3, rm as rm3, stat as stat6, writeFile as writeFile3 } from "node:fs/promises";
35888
- import { delimiter as delimiter2, dirname as dirname4, isAbsolute as isAbsolute6, join as join10, relative as relative3, sep as sep3 } from "node:path";
35887
+ import { delimiter as delimiter2, dirname as dirname3, isAbsolute as isAbsolute6, join as join10, relative as relative3, sep as sep3 } from "node:path";
35889
35888
 
35890
35889
  // src/agent-installation/verified-download.ts
35891
35890
  import { fetch } from "undici";
@@ -36744,9 +36743,9 @@ function comparePrerelease(left, right) {
36744
36743
  if (left.length === 0 || right.length === 0) {
36745
36744
  return left.length === right.length ? 0 : left.length === 0 ? 1 : -1;
36746
36745
  }
36747
- for (let index = 0; index < Math.max(left.length, right.length); index += 1) {
36748
- const leftPart = left[index];
36749
- const rightPart = right[index];
36746
+ for (let index2 = 0; index2 < Math.max(left.length, right.length); index2 += 1) {
36747
+ const leftPart = left[index2];
36748
+ const rightPart = right[index2];
36750
36749
  if (leftPart === void 0 || rightPart === void 0) {
36751
36750
  return leftPart === rightPart ? 0 : leftPart === void 0 ? -1 : 1;
36752
36751
  }
@@ -36771,8 +36770,8 @@ function compareAgentVersions(left, right) {
36771
36770
  if (parsedLeft === null || parsedRight === null) {
36772
36771
  return null;
36773
36772
  }
36774
- for (let index = 0; index < Math.max(parsedLeft.core.length, parsedRight.core.length); index += 1) {
36775
- const difference = (parsedLeft.core[index] ?? 0) - (parsedRight.core[index] ?? 0);
36773
+ for (let index2 = 0; index2 < Math.max(parsedLeft.core.length, parsedRight.core.length); index2 += 1) {
36774
+ const difference = (parsedLeft.core[index2] ?? 0) - (parsedRight.core[index2] ?? 0);
36776
36775
  if (difference !== 0) {
36777
36776
  return Math.sign(difference);
36778
36777
  }
@@ -37193,9 +37192,9 @@ async function discoverLocalAgentInventory(options) {
37193
37192
  }
37194
37193
 
37195
37194
  // src/storage/runtime-installation-store.ts
37196
- import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
37195
+ import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
37197
37196
  import { mkdir as mkdir5, open as open5, readdir as readdir3, rename as rename4, unlink, writeFile as writeFile4 } from "node:fs/promises";
37198
- import { dirname as dirname5, join as join16, resolve as resolve4 } from "node:path";
37197
+ import { dirname as dirname4, join as join16, resolve as resolve4 } from "node:path";
37199
37198
  var APPLICATION_ID_PATTERN = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+){1,31}$/;
37200
37199
  var CONNECTION_ID_PATTERN = /^mcn_[a-f0-9]{32}$/;
37201
37200
  var INSTALLATION_ID_PATTERN = /^min_[a-f0-9]{32}$/;
@@ -37323,10 +37322,10 @@ function parseRelayOrigin(value) {
37323
37322
  return origin;
37324
37323
  }
37325
37324
  function connectionId() {
37326
- return `mcn_${randomUUID2().replaceAll("-", "")}`;
37325
+ return `mcn_${randomUUID3().replaceAll("-", "")}`;
37327
37326
  }
37328
37327
  function installationId() {
37329
- return `min_${randomUUID2().replaceAll("-", "")}`;
37328
+ return `min_${randomUUID3().replaceAll("-", "")}`;
37330
37329
  }
37331
37330
  function channelIndexFileName(channelId) {
37332
37331
  return `mci_${createHash3("sha256").update(channelId).digest("hex")}.json`;
@@ -37437,8 +37436,8 @@ async function readJsonFile(path2, signal, missingCode) {
37437
37436
  }
37438
37437
  async function writeJsonAtomically(path2, value, signal) {
37439
37438
  signal.throwIfAborted();
37440
- const directory = dirname5(path2);
37441
- const temporaryPath = join16(directory, `.${randomUUID2()}.tmp`);
37439
+ const directory = dirname4(path2);
37440
+ const temporaryPath = join16(directory, `.${randomUUID3()}.tmp`);
37442
37441
  try {
37443
37442
  await mkdir5(directory, { mode: 448, recursive: true });
37444
37443
  signal.throwIfAborted();
@@ -37515,16 +37514,16 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
37515
37514
  };
37516
37515
  #readConnectionForChannel = async (channelId, signal) => {
37517
37516
  const normalizedChannelId = validateIdentifier(channelId, "invalid_channel_id");
37518
- const index = decodeChannelIndex(
37517
+ const index2 = decodeChannelIndex(
37519
37518
  await readJsonFile(this.channelIndexPath(normalizedChannelId), signal, "connection_not_found")
37520
37519
  );
37521
- if (index.applicationId !== this.applicationId || index.installationId !== this.installationId || index.channelId !== normalizedChannelId) {
37520
+ if (index2.applicationId !== this.applicationId || index2.installationId !== this.installationId || index2.channelId !== normalizedChannelId) {
37522
37521
  throw new RuntimeInstallationStoreError(
37523
37522
  "connection_owner_mismatch",
37524
37523
  "The saved Runtime connection belongs to another installation"
37525
37524
  );
37526
37525
  }
37527
- return await this.readConnection(index.connectionId, signal);
37526
+ return await this.readConnection(index2.connectionId, signal);
37528
37527
  };
37529
37528
  saveConnection = async (input2, signal) => {
37530
37529
  const stored = new VerifiedRuntimeConnection(
@@ -37719,16 +37718,16 @@ function hasExactKeys2(value, expectedKeys) {
37719
37718
  }
37720
37719
  function readSingleOption(arguments_, option) {
37721
37720
  const values = [];
37722
- for (let index = 0; index < arguments_.length; index += 1) {
37723
- if (arguments_[index] !== option) {
37721
+ for (let index2 = 0; index2 < arguments_.length; index2 += 1) {
37722
+ if (arguments_[index2] !== option) {
37724
37723
  continue;
37725
37724
  }
37726
- const value = arguments_[index + 1];
37725
+ const value = arguments_[index2 + 1];
37727
37726
  if (value === void 0 || value.startsWith("--")) {
37728
37727
  throw new PairingClientError("invalid_arguments", `${option} requires a value`);
37729
37728
  }
37730
37729
  values.push(value);
37731
- index += 1;
37730
+ index2 += 1;
37732
37731
  }
37733
37732
  if (values.length !== 1) {
37734
37733
  throw new PairingClientError("invalid_arguments", `${option} must be provided exactly once`);
@@ -37736,8 +37735,8 @@ function readSingleOption(arguments_, option) {
37736
37735
  return values[0] ?? "";
37737
37736
  }
37738
37737
  function assertKnownArguments(arguments_) {
37739
- for (let index = 0; index < arguments_.length; index += 2) {
37740
- const option = arguments_[index];
37738
+ for (let index2 = 0; index2 < arguments_.length; index2 += 2) {
37739
+ const option = arguments_[index2];
37741
37740
  if (option !== "--url" && option !== "--code" && option !== "--pairing" && option !== "--workspace") {
37742
37741
  throw new PairingClientError("invalid_arguments", `Unknown pairing option: ${option ?? "missing option"}`);
37743
37742
  }
@@ -38028,7 +38027,7 @@ function isRuntimeRelayRevocation(closeCode, closeReason) {
38028
38027
  }
38029
38028
 
38030
38029
  // src/run-daemon.ts
38031
- import { createHash as createHash8, randomUUID as randomUUID9 } from "node:crypto";
38030
+ import { createHash as createHash8, randomUUID as randomUUID10 } from "node:crypto";
38032
38031
  import { join as join19 } from "node:path";
38033
38032
  import { styleText } from "node:util";
38034
38033
 
@@ -38607,7 +38606,7 @@ var FixedInstallationExecutor = class {
38607
38606
  // src/authorization/workspace-directory.ts
38608
38607
  import { readdir as readdir4, realpath as realpath9, stat as stat8 } from "node:fs/promises";
38609
38608
  import { homedir as homedir2 } from "node:os";
38610
- import { basename as basename4, dirname as dirname6, isAbsolute as isAbsolute9, join as join17, normalize as normalize3, relative as relative4 } from "node:path";
38609
+ import { basename as basename4, dirname as dirname5, isAbsolute as isAbsolute9, join as join17, normalize as normalize3, relative as relative4 } from "node:path";
38611
38610
  var WorkspaceDirectoryListing = class {
38612
38611
  directoryId;
38613
38612
  directoryLabel;
@@ -38735,7 +38734,7 @@ var WorkspaceDirectoryService = class {
38735
38734
  }
38736
38735
  }
38737
38736
  entries.sort((a, b) => a.name.localeCompare(b.name));
38738
- const parent = dirname6(target);
38737
+ const parent = dirname5(target);
38739
38738
  return new WorkspaceDirectoryListing(
38740
38739
  id,
38741
38740
  this.label(target),
@@ -38760,7 +38759,7 @@ var WorkspaceDirectoryService = class {
38760
38759
  };
38761
38760
 
38762
38761
  // src/daemon-diagnostic-log.ts
38763
- import { appendFileSync, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
38762
+ import { appendFileSync, mkdirSync, readFileSync as readFileSync2, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
38764
38763
  import { join as join18 } from "node:path";
38765
38764
  var MAXIMUM_DAEMON_LOG_BYTES = 1 * 1024 * 1024;
38766
38765
  var DaemonDiagnosticLog = class {
@@ -38776,7 +38775,7 @@ var DaemonDiagnosticLog = class {
38776
38775
  const encoded = `${diagnostic.replace(/[\r\n]+/gu, " ").trim()}
38777
38776
  `;
38778
38777
  const encodedBytes = Buffer.byteLength(encoded);
38779
- mkdirSync2(this.#directory, { mode: 448, recursive: true });
38778
+ mkdirSync(this.#directory, { mode: 448, recursive: true });
38780
38779
  let existingBytes = 0;
38781
38780
  try {
38782
38781
  existingBytes = statSync3(this.#path).size;
@@ -39241,7 +39240,7 @@ var DaemonInstallationObserver = class {
39241
39240
  };
39242
39241
 
39243
39242
  // src/daemon-active-turn.ts
39244
- import { randomUUID as randomUUID3 } from "node:crypto";
39243
+ import { randomUUID as randomUUID4 } from "node:crypto";
39245
39244
  function activeMessageCharacters(message) {
39246
39245
  return message.text.length + (message.role === "assistant" ? JSON.stringify(message.activities).length + JSON.stringify(message.content).length : 0);
39247
39246
  }
@@ -39249,8 +39248,8 @@ var ACTIVE_TURN_TEXT_CHUNK_LIMIT = Math.floor(SESSION_HISTORY_CHARACTER_LIMIT /
39249
39248
  function boundedRecoveryMessages(messages) {
39250
39249
  const selected = [];
39251
39250
  let remainingCharacters = SESSION_HISTORY_CHARACTER_LIMIT;
39252
- for (let index = messages.length - 1; index >= 0 && selected.length < SESSION_HISTORY_MESSAGE_LIMIT; index -= 1) {
39253
- const message = messages[index];
39251
+ for (let index2 = messages.length - 1; index2 >= 0 && selected.length < SESSION_HISTORY_MESSAGE_LIMIT; index2 -= 1) {
39252
+ const message = messages[index2];
39254
39253
  if (message === void 0) {
39255
39254
  break;
39256
39255
  }
@@ -39275,7 +39274,7 @@ var ActiveDaemonTurn = class {
39275
39274
  #timeline;
39276
39275
  #sequence = 0;
39277
39276
  #interaction = null;
39278
- #epoch = decodeIdentifier(randomUUID3());
39277
+ #epoch = decodeIdentifier(randomUUID4());
39279
39278
  constructor(command, attemptId) {
39280
39279
  this.attemptId = attemptId;
39281
39280
  this.command = command;
@@ -39337,7 +39336,7 @@ var ActiveDaemonTurn = class {
39337
39336
  if (!this.#activities.has(event.activityId)) {
39338
39337
  this.#timeline = [
39339
39338
  ...this.#timeline,
39340
- { activityId: event.activityId, id: decodeIdentifier(randomUUID3()), kind: "activity" }
39339
+ { activityId: event.activityId, id: decodeIdentifier(randomUUID4()), kind: "activity" }
39341
39340
  ];
39342
39341
  }
39343
39342
  this.#activities.set(event.activityId, {
@@ -39358,7 +39357,7 @@ var ActiveDaemonTurn = class {
39358
39357
  if (previous === void 0) {
39359
39358
  this.#timeline = [
39360
39359
  ...this.#timeline,
39361
- { activityId: event.activityId, id: decodeIdentifier(randomUUID3()), kind: "activity" }
39360
+ { activityId: event.activityId, id: decodeIdentifier(randomUUID4()), kind: "activity" }
39362
39361
  ];
39363
39362
  }
39364
39363
  this.#activities.set(event.activityId, {
@@ -39383,7 +39382,7 @@ var ActiveDaemonTurn = class {
39383
39382
  ...this.#timeline,
39384
39383
  {
39385
39384
  content: /* @__PURE__ */ new Map([[event.contentId, event.content]]),
39386
- id: decodeIdentifier(randomUUID3()),
39385
+ id: decodeIdentifier(randomUUID4()),
39387
39386
  kind: "message",
39388
39387
  sourceMessageId: event.messageId,
39389
39388
  text: ""
@@ -39391,7 +39390,7 @@ var ActiveDaemonTurn = class {
39391
39390
  ];
39392
39391
  } else {
39393
39392
  this.#timeline = this.#timeline.map(
39394
- (entry, index) => index === target && entry.kind === "message" ? { ...entry, content: new Map([...entry.content, [event.contentId, event.content]]) } : entry
39393
+ (entry, index2) => index2 === target && entry.kind === "message" ? { ...entry, content: new Map([...entry.content, [event.contentId, event.content]]) } : entry
39395
39394
  );
39396
39395
  }
39397
39396
  } else if (event.kind === SESSION_PERMISSION_REQUESTED_KIND || event.kind === SESSION_ELICITATION_REQUESTED_KIND) {
@@ -39423,7 +39422,7 @@ var ActiveDaemonTurn = class {
39423
39422
  ...this.#timeline,
39424
39423
  {
39425
39424
  content: /* @__PURE__ */ new Map(),
39426
- id: decodeIdentifier(randomUUID3()),
39425
+ id: decodeIdentifier(randomUUID4()),
39427
39426
  kind: "message",
39428
39427
  sourceMessageId: messageId,
39429
39428
  text: remaining.slice(0, ACTIVE_TURN_TEXT_CHUNK_LIMIT)
@@ -39694,6 +39693,202 @@ var DaemonTurnRegistry = class {
39694
39693
  };
39695
39694
  };
39696
39695
 
39696
+ // src/generated/acp-session-store-migrations.ts
39697
+ var acpSessionStoreMigrations = [
39698
+ {
39699
+ "name": "0000_slimy_captain_midlands.sql",
39700
+ "sql": "CREATE TABLE `acp_session` (\n `session_id` text PRIMARY KEY NOT NULL,\n `agent_id` text NOT NULL,\n `native_session_id` text NOT NULL,\n `cwd` text NOT NULL,\n `additional_directories` text NOT NULL,\n `prompted` integer NOT NULL,\n `title` text NOT NULL,\n `updated_at` text NOT NULL\n);\n--> statement-breakpoint\nCREATE TABLE `deleted_acp_session` (\n `session_id` text PRIMARY KEY NOT NULL\n);\n"
39701
+ },
39702
+ {
39703
+ "name": "0001_regular_ultimates.sql",
39704
+ "sql": "ALTER TABLE `acp_session` ADD `last_terminal_command_id` text;"
39705
+ },
39706
+ {
39707
+ "name": "0002_equal_black_queen.sql",
39708
+ "sql": "CREATE TABLE `session_event_v2` (\n `event_id` text PRIMARY KEY NOT NULL,\n `event_json` text NOT NULL,\n `position` integer NOT NULL,\n `session_id` text NOT NULL\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX `session_event_v2_session_position_unique` ON `session_event_v2` (`session_id`,`position`);--> statement-breakpoint\nCREATE INDEX `session_event_v2_session_position_index` ON `session_event_v2` (`session_id`,`position`);"
39709
+ },
39710
+ {
39711
+ "name": "0003_silky_ravenous.sql",
39712
+ "sql": "DROP TABLE `session_event_v2`;"
39713
+ },
39714
+ {
39715
+ "name": "0004_special_mathemanic.sql",
39716
+ "sql": "DROP TABLE `deleted_acp_session`;--> statement-breakpoint\nALTER TABLE `acp_session` DROP COLUMN `last_terminal_command_id`;"
39717
+ }
39718
+ ];
39719
+
39720
+ // src/generated/session-event-cache-migrations.ts
39721
+ var sessionEventCacheMigrations = [
39722
+ {
39723
+ "name": "migration.sql",
39724
+ "sql": "CREATE TABLE `session_event_v2` (\n `event_json` text NOT NULL,\n `generation_id` text NOT NULL,\n `position` integer NOT NULL,\n `session_id` text NOT NULL,\n CONSTRAINT `session_event_v2_pk` PRIMARY KEY(`generation_id`, `session_id`, `position`)\n);\n--> statement-breakpoint\nCREATE INDEX `session_event_v2_generation_session_position_index` ON `session_event_v2` (`generation_id`,`session_id`,`position`);"
39725
+ }
39726
+ ];
39727
+
39728
+ // src/infra/local-sqlite-database.ts
39729
+ import { chmodSync, mkdirSync as mkdirSync2 } from "node:fs";
39730
+ import { dirname as dirname6 } from "node:path";
39731
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
39732
+
39733
+ // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/node-sqlite/session.js
39734
+ var NodeSQLiteSession = class extends SQLiteAsyncSession {
39735
+ static [entityKind] = "SQLJsSession";
39736
+ logger;
39737
+ constructor(client2, dialect, relations, options = {}) {
39738
+ super(dialect, "sync");
39739
+ this.client = client2;
39740
+ this.relations = relations;
39741
+ this.options = options;
39742
+ this.logger = options.logger ?? new NoopLogger();
39743
+ }
39744
+ prepareQuery(query, mode, _prepare, executeMethod, mapper, queryMetadata) {
39745
+ let stmt;
39746
+ try {
39747
+ stmt = this.client.prepare(query.sql);
39748
+ } catch (e) {
39749
+ throw new DrizzleQueryError(query.sql, query.params, e);
39750
+ }
39751
+ return new SQLiteAsyncPreparedQuery("sync", executeMethod, {
39752
+ all: (params) => {
39753
+ stmt.setReturnArrays(mode === "arrays");
39754
+ const res = stmt.all(...params);
39755
+ if (mode === "objects") return res.map((row) => ({ ...row }));
39756
+ return res;
39757
+ },
39758
+ get: (params) => {
39759
+ stmt.setReturnArrays(mode === "arrays");
39760
+ const res = stmt.get(...params);
39761
+ if (res && mode === "objects") return { ...res };
39762
+ return res;
39763
+ },
39764
+ run: (params) => {
39765
+ stmt.setReturnArrays(false);
39766
+ return stmt.run(...params);
39767
+ },
39768
+ values: (params) => {
39769
+ stmt.setReturnArrays(true);
39770
+ return stmt.all(...params);
39771
+ }
39772
+ }, query, mapper, mode, this.logger, void 0, queryMetadata, void 0);
39773
+ }
39774
+ transaction(transaction, config2 = {}) {
39775
+ const tx = new NodeSQLiteTransaction("sync", this.dialect, this, this.relations);
39776
+ this.run(sql.raw(`begin${config2.behavior ? ` ${config2.behavior}` : ""}`));
39777
+ try {
39778
+ const result = transaction(tx);
39779
+ this.run(sql`commit`);
39780
+ return result;
39781
+ } catch (err) {
39782
+ this.run(sql`rollback`);
39783
+ throw err;
39784
+ }
39785
+ }
39786
+ };
39787
+ var NodeSQLiteTransaction = class NodeSQLiteTransaction2 extends SQLiteAsyncTransaction {
39788
+ static [entityKind] = "SQLJsTransaction";
39789
+ transaction(transaction) {
39790
+ const savepointName = `sp${this.nestedIndex + 1}`;
39791
+ const tx = new NodeSQLiteTransaction2("sync", this.dialect, this.session, this._.relations, this.nestedIndex + 1);
39792
+ tx.run(sql.raw(`savepoint ${savepointName}`));
39793
+ try {
39794
+ const result = transaction(tx);
39795
+ tx.run(sql.raw(`release savepoint ${savepointName}`));
39796
+ return result;
39797
+ } catch (err) {
39798
+ tx.run(sql.raw(`rollback to savepoint ${savepointName}`));
39799
+ throw err;
39800
+ }
39801
+ }
39802
+ };
39803
+
39804
+ // ../../node_modules/.pnpm/drizzle-orm@1.0.0-rc.4_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6_f872c171b7e1945bb1fa42180063dab2/node_modules/drizzle-orm/node-sqlite/driver.js
39805
+ import { DatabaseSync } from "node:sqlite";
39806
+ var NodeSQLiteDatabase = class extends SQLiteAsyncDatabase {
39807
+ static [entityKind] = "NodeSQLiteDatabase";
39808
+ };
39809
+ function construct(client2, config2 = {}) {
39810
+ const dialect = new SQLiteDialect({ useJitMappers: jitCompatCheck(config2.jit) });
39811
+ let logger;
39812
+ if (config2.logger === true) logger = new DefaultLogger();
39813
+ else if (config2.logger !== false) logger = config2.logger;
39814
+ const relations = config2.relations ?? {};
39815
+ const db = new NodeSQLiteDatabase("sync", dialect, new NodeSQLiteSession(client2, dialect, relations, { logger }), relations);
39816
+ db.$client = client2;
39817
+ return db;
39818
+ }
39819
+ function drizzle(...params) {
39820
+ if (params[0] === void 0 || typeof params[0] === "string") return construct(params[0] === void 0 ? new DatabaseSync(":memory:") : new DatabaseSync(params[0]), params[1]);
39821
+ const { connection, client: client2, ...config2 } = params[0];
39822
+ if (client2) return construct(client2, config2);
39823
+ if (typeof connection === "object") {
39824
+ const { path: path2, ...options } = connection;
39825
+ return construct(new DatabaseSync(path2 ?? ":memory:", options), config2);
39826
+ }
39827
+ return construct(new DatabaseSync(connection ?? ":memory:"), config2);
39828
+ }
39829
+ (function(_drizzle) {
39830
+ function mock(config2) {
39831
+ return construct({}, config2);
39832
+ }
39833
+ _drizzle.mock = mock;
39834
+ })(drizzle || (drizzle = {}));
39835
+
39836
+ // src/infra/local-sqlite-database.ts
39837
+ var LocalSqliteDatabase = class {
39838
+ orm;
39839
+ #sqlite;
39840
+ constructor(path2, label, migrations, pragmas = []) {
39841
+ mkdirSync2(dirname6(path2), { mode: 448, recursive: true });
39842
+ this.#sqlite = new DatabaseSync2(path2);
39843
+ chmodSync(path2, 384);
39844
+ try {
39845
+ for (const pragma of pragmas) {
39846
+ this.#sqlite.exec(pragma);
39847
+ }
39848
+ this.#migrate(label, migrations);
39849
+ this.orm = drizzle({ client: this.#sqlite });
39850
+ } catch (error62) {
39851
+ this.#sqlite.close();
39852
+ throw error62;
39853
+ }
39854
+ }
39855
+ #migrate = (label, migrations) => {
39856
+ const version2 = external_exports.object({ user_version: external_exports.number().int().nonnegative() }).parse(this.#sqlite.prepare("PRAGMA user_version").get()).user_version;
39857
+ if (version2 > migrations.length) {
39858
+ throw new Error(`The ${label} was created by a newer Mobius version`);
39859
+ }
39860
+ for (let index2 = version2; index2 < migrations.length; index2 += 1) {
39861
+ const migration = migrations[index2];
39862
+ if (migration === void 0) {
39863
+ throw new Error(`The ${label} migration is unavailable`);
39864
+ }
39865
+ this.transaction(() => {
39866
+ this.#sqlite.exec(migration.sql);
39867
+ this.#sqlite.exec(`PRAGMA user_version = ${index2 + 1}`);
39868
+ });
39869
+ }
39870
+ };
39871
+ transaction = (operation) => {
39872
+ this.#sqlite.exec("BEGIN IMMEDIATE");
39873
+ try {
39874
+ const result = operation();
39875
+ this.#sqlite.exec("COMMIT");
39876
+ return result;
39877
+ } catch (error62) {
39878
+ this.#sqlite.exec("ROLLBACK");
39879
+ throw error62;
39880
+ }
39881
+ };
39882
+ close = () => this.#sqlite.close();
39883
+ };
39884
+
39885
+ // src/local-databases.ts
39886
+ var openAcpSessionDatabase = (path2) => new LocalSqliteDatabase(path2, "ACP Session database", acpSessionStoreMigrations);
39887
+ var openSessionEventCacheV2Database = (path2) => new LocalSqliteDatabase(path2, "V2 Session event cache", sessionEventCacheMigrations, [
39888
+ "PRAGMA journal_mode = WAL",
39889
+ "PRAGMA synchronous = OFF"
39890
+ ]);
39891
+
39697
39892
  // src/native-sessions/codex-history.ts
39698
39893
  import { spawn as spawn5 } from "node:child_process";
39699
39894
  var responseSchema = external_exports.union([
@@ -40398,8 +40593,7 @@ var readCodexFullHistory = async (agent, cwd, nativeSessionId, signal, nativeTur
40398
40593
  });
40399
40594
 
40400
40595
  // src/native-sessions/service.ts
40401
- import { randomUUID as randomUUID4 } from "node:crypto";
40402
- import { basename as basename5 } from "node:path";
40596
+ import { randomUUID as randomUUID5 } from "node:crypto";
40403
40597
  var NativeSessionService = class {
40404
40598
  #entries = /* @__PURE__ */ new Map();
40405
40599
  #cursors = /* @__PURE__ */ new Map();
@@ -40443,64 +40637,6 @@ var NativeSessionService = class {
40443
40637
  ...await this.#activeTurn(command, options)
40444
40638
  };
40445
40639
  }
40446
- if (command.action === "fork-recorded") {
40447
- const source = this.#sessions.findSessions([command.sessionId])[0];
40448
- if (source === void 0 || !source.prompted) {
40449
- throw new AcpExecutionError(
40450
- "The source conversation has no resumable native Agent session",
40451
- {},
40452
- "native_session_not_found"
40453
- );
40454
- }
40455
- if (source.agentId !== command.agentId || source.cwd !== cwd || source.additionalDirectories.length !== additionalDirectories.length || source.additionalDirectories.some((path2, index) => path2 !== additionalDirectories[index])) {
40456
- throw new AcpExecutionError(
40457
- "The source conversation execution target does not match the fork request",
40458
- {},
40459
- "native_session_target_changed"
40460
- );
40461
- }
40462
- if (source.lastTerminalCommandId !== command.throughCommandId) {
40463
- throw new AcpExecutionError(
40464
- "The selected Turn is no longer the source conversation head",
40465
- {},
40466
- "fork_point_stale"
40467
- );
40468
- }
40469
- const opened2 = await this.#sessions.openNativeSession(
40470
- { ...options, sessionId: command.targetSessionId },
40471
- { kind: "fork", nativeSessionId: source.nativeSessionId }
40472
- );
40473
- signal.throwIfAborted();
40474
- const directory = await this.#directories.list(this.#config.bindingId, command.directoryId, signal);
40475
- const ready2 = {
40476
- additionalDirectories: additionalDirectories.map((path2, index) => ({
40477
- directoryId: command.additionalDirectoryIds[index] ?? command.directoryId,
40478
- name: basename5(path2) || path2
40479
- })),
40480
- agentId: command.agentId,
40481
- agentName: opened2.prepared.agentName,
40482
- agentVersion: opened2.prepared.agentVersion,
40483
- capabilities: opened2.prepared.capabilities,
40484
- commands: opened2.prepared.commands,
40485
- configOptions: opened2.prepared.configOptions,
40486
- directoryId: command.directoryId,
40487
- directoryLabel: directory.directoryLabel,
40488
- kind: "session.ready",
40489
- requestId: command.requestId,
40490
- restored: true,
40491
- sessionId: opened2.sessionId
40492
- };
40493
- this.record(command, "native_recorded_session_forked");
40494
- return {
40495
- action: "fork-recorded",
40496
- kind: "native.session.result",
40497
- ready: ready2,
40498
- requestId: command.requestId,
40499
- sessionId: command.sessionId,
40500
- targetSessionId: command.targetSessionId,
40501
- title: source.title || "Untitled session"
40502
- };
40503
- }
40504
40640
  const prepared = await this.#sessions.prepareNativeSessionBrowser(options);
40505
40641
  if (!prepared.capabilities.listSessions) {
40506
40642
  throw new AcpExecutionError(
@@ -40516,7 +40652,7 @@ var NativeSessionService = class {
40516
40652
  if (authorized === null) {
40517
40653
  return null;
40518
40654
  }
40519
- const entryId = decodeIdentifier(randomUUID4());
40655
+ const entryId = decodeIdentifier(randomUUID5());
40520
40656
  if (this.#entries.size >= 5e3) {
40521
40657
  this.#entries.clear();
40522
40658
  }
@@ -40572,7 +40708,7 @@ var NativeSessionService = class {
40572
40708
  "invalid_native_session_response"
40573
40709
  );
40574
40710
  }
40575
- nextCursor = decodeIdentifier(randomUUID4());
40711
+ nextCursor = decodeIdentifier(randomUUID5());
40576
40712
  if (this.#cursors.size >= 500) {
40577
40713
  this.#cursors.clear();
40578
40714
  }
@@ -40635,25 +40771,6 @@ var NativeSessionService = class {
40635
40771
  );
40636
40772
  }
40637
40773
  const target = await this.resolveTarget(command, options, selected);
40638
- if (command.action === "delete") {
40639
- if (!prepared.capabilities.deleteSession) {
40640
- throw new AcpExecutionError(
40641
- "This Agent does not support native session deletion",
40642
- {},
40643
- "native_session_unsupported"
40644
- );
40645
- }
40646
- signal.throwIfAborted();
40647
- this.record(command, "native_session_delete_authorized");
40648
- const deletedSessionIds = await this.#sessions.deleteNativeSession(options, target.info.sessionId);
40649
- this.record(command, "native_session_deleted");
40650
- return {
40651
- ...envelope2,
40652
- action: "delete",
40653
- entryId: command.entryId,
40654
- deletedSessionIds: deletedSessionIds.map(decodeIdentifier)
40655
- };
40656
- }
40657
40774
  const action = command.action;
40658
40775
  if (action === "import" && !prepared.capabilities.loadSession && !prepared.capabilities.resumeSession) {
40659
40776
  throw new AcpExecutionError("This Agent cannot import native sessions", {}, "native_session_unsupported");
@@ -40769,7 +40886,7 @@ var NativeSessionService = class {
40769
40886
  resolveTarget = async (command, options, selected) => {
40770
40887
  let cursor = null;
40771
40888
  const visited = /* @__PURE__ */ new Set();
40772
- for (let index = 0; index < 100; index += 1) {
40889
+ for (let index2 = 0; index2 < 100; index2 += 1) {
40773
40890
  const page = await this.#sessions.listNativeSessions(options, cursor);
40774
40891
  const info = page.sessions.find((entry) => entry.sessionId === selected.nativeSessionId);
40775
40892
  if (info !== void 0) {
@@ -40777,7 +40894,7 @@ var NativeSessionService = class {
40777
40894
  if (target === null) {
40778
40895
  throw new LocalAuthorizationError("The selected native session is not authorized");
40779
40896
  }
40780
- if (target.cwd !== selected.cwd || target.additionalDirectories.length !== selected.additionalDirectories.length || target.additionalDirectories.some((path2, index2) => path2 !== selected.additionalDirectories[index2])) {
40897
+ if (target.cwd !== selected.cwd || target.additionalDirectories.length !== selected.additionalDirectories.length || target.additionalDirectories.some((path2, index3) => path2 !== selected.additionalDirectories[index3])) {
40781
40898
  throw new AcpExecutionError(
40782
40899
  "This session's directory changed. Refresh the list before continuing.",
40783
40900
  {},
@@ -40816,7 +40933,7 @@ var NativeSessionService = class {
40816
40933
  };
40817
40934
 
40818
40935
  // src/relay-connection/daemon-operation-state.ts
40819
- import { createHash as createHash5, randomUUID as randomUUID5 } from "node:crypto";
40936
+ import { createHash as createHash5, randomUUID as randomUUID6 } from "node:crypto";
40820
40937
  var MAX_TERMINAL_RECEIPTS = 1024;
40821
40938
  function isTerminal(state) {
40822
40939
  return state === "succeeded" || state === "failed" || state === "cancelled";
@@ -40833,7 +40950,7 @@ var DaemonOperationState = class {
40833
40950
  }
40834
40951
  return { attemptId: existing.attemptId, commandId, kind: "duplicate", state: existing.state };
40835
40952
  }
40836
- const attemptId = randomUUID5();
40953
+ const attemptId = randomUUID6();
40837
40954
  this.#executions.set(commandId, { attemptId, commandHash, sessionId, state: "dispatching" });
40838
40955
  return { attemptId, commandId, kind: "accepted", state: "dispatching" };
40839
40956
  };
@@ -41663,7 +41780,7 @@ function createAgentSettingsDiscoveryHandler(dependencies) {
41663
41780
  // src/artifacts/local-file-streamer.ts
41664
41781
  import { createReadStream as createReadStream2 } from "node:fs";
41665
41782
  import { realpath as realpath10, stat as stat9 } from "node:fs/promises";
41666
- import { basename as basename6, isAbsolute as isAbsolute10, normalize as normalize4, resolve as resolve7 } from "node:path";
41783
+ import { basename as basename5, isAbsolute as isAbsolute10, normalize as normalize4, resolve as resolve7 } from "node:path";
41667
41784
  import { fileURLToPath as fileURLToPath2 } from "node:url";
41668
41785
  var CHUNK_BYTES = 192 * 1024;
41669
41786
  function requestedPath(value) {
@@ -41715,7 +41832,7 @@ async function streamLocalFile(command, send2, signal, workingDirectory, externa
41715
41832
  kind: FILE_BEGIN_KIND,
41716
41833
  mediaType: external?.mediaType ?? raster?.mimeType ?? "application/octet-stream",
41717
41834
  modifiedAt: before.mtime.toISOString(),
41718
- name: external?.name ?? (basename6(target) || "file"),
41835
+ name: external?.name ?? (basename5(target) || "file"),
41719
41836
  requestId: command.requestId,
41720
41837
  sessionId: command.sessionId
41721
41838
  });
@@ -41745,7 +41862,7 @@ async function streamLocalFile(command, send2, signal, workingDirectory, externa
41745
41862
  }
41746
41863
 
41747
41864
  // src/authorization/resolve-session-directories.ts
41748
- import { basename as basename7 } from "node:path";
41865
+ import { basename as basename6 } from "node:path";
41749
41866
  var ResolvedSessionDirectories = class {
41750
41867
  additionalDirectories;
41751
41868
  additionalDirectoryEntries;
@@ -41770,7 +41887,7 @@ async function resolveSessionDirectories(directories, bindingId, directoryId2, a
41770
41887
  additionalDirectories.push(directory);
41771
41888
  additionalDirectoryEntries.push({
41772
41889
  directoryId: additionalDirectoryId,
41773
- name: basename7(directory)
41890
+ name: basename6(directory)
41774
41891
  });
41775
41892
  }
41776
41893
  return new ResolvedSessionDirectories(cwd, additionalDirectories, additionalDirectoryEntries);
@@ -41797,7 +41914,7 @@ async function executeSessionLiveHistoryV2PageLoad(socket, command, config2, dir
41797
41914
  const replay = await sessions.loadSessionEventsV2(loadOptions, command.eventLimit, command.cursor);
41798
41915
  signal.throwIfAborted();
41799
41916
  const events = replay.events.map(
41800
- (event, index) => eventLogV2.event(command.sessionId, replay.startPosition + index, event, "1970-01-01T00:00:00.000Z")
41917
+ (event, index2) => eventLogV2.event(command.sessionId, replay.startPosition + index2, event, "1970-01-01T00:00:00.000Z")
41801
41918
  );
41802
41919
  const tailCursor = events.at(-1)?.eventId ?? "";
41803
41920
  audit.record({
@@ -41848,7 +41965,7 @@ async function executeSessionLiveHistoryV2PageLoad(socket, command, config2, dir
41848
41965
  }
41849
41966
 
41850
41967
  // src/acp/session-config/apply-session-configuration.ts
41851
- import { randomUUID as randomUUID6 } from "node:crypto";
41968
+ import { randomUUID as randomUUID7 } from "node:crypto";
41852
41969
  function invalidSessionConfiguration(message) {
41853
41970
  return new AcpExecutionError(message, {}, "invalid_session_configuration");
41854
41971
  }
@@ -41989,7 +42106,7 @@ async function applySessionConfigurationSelection(sessions, audit, options, sele
41989
42106
  booleanValue: selection.booleanValue,
41990
42107
  configId: selection.configId,
41991
42108
  cwd,
41992
- requestId: `cfg_${randomUUID6()}`,
42109
+ requestId: `cfg_${randomUUID7()}`,
41993
42110
  sessionId,
41994
42111
  signal,
41995
42112
  value: selection.value,
@@ -42549,7 +42666,7 @@ async function executeSessionConfigure(publisher, socket, command, config2, dire
42549
42666
  // src/native-sessions/handle-native-requests.ts
42550
42667
  import { WebSocket as WebSocket4 } from "undici";
42551
42668
  function createNativeSessionRequestHandler(dependencies) {
42552
- const { audit, diagnostics, nativeSessions, publisher, signal, socket, timer } = dependencies;
42669
+ const { audit, diagnostics, nativeSessions, signal, socket, timer } = dependencies;
42553
42670
  const pending = /* @__PURE__ */ new Map();
42554
42671
  const cancel = (command) => {
42555
42672
  const request = pending.get(command.requestId);
@@ -42601,17 +42718,6 @@ function createNativeSessionRequestHandler(dependencies) {
42601
42718
  }
42602
42719
  operationSignal.throwIfAborted();
42603
42720
  const result = await nativeSessions.execute(command, operationSignal);
42604
- if (command.action === "fork-recorded" && result.action === "fork-recorded") {
42605
- publisher.publishBatch(result.ready.sessionId, [
42606
- result.ready,
42607
- {
42608
- kind: "session.forked",
42609
- sessionId: result.ready.sessionId,
42610
- sourceSessionId: command.sessionId,
42611
- throughCommandId: command.throughCommandId
42612
- }
42613
- ]);
42614
- }
42615
42721
  if (socket.readyState === WebSocket4.OPEN) {
42616
42722
  send(socket, result);
42617
42723
  }
@@ -42691,7 +42797,6 @@ function createDaemonCommandHandler({
42691
42797
  audit,
42692
42798
  diagnostics,
42693
42799
  nativeSessions,
42694
- publisher,
42695
42800
  signal,
42696
42801
  socket,
42697
42802
  timer
@@ -43051,7 +43156,7 @@ function connectRelay(url2, signal) {
43051
43156
  }
43052
43157
 
43053
43158
  // src/relay-connection/liveness.ts
43054
- import { randomUUID as randomUUID7 } from "node:crypto";
43159
+ import { randomUUID as randomUUID8 } from "node:crypto";
43055
43160
  var HEARTBEAT_ACK_TIMEOUT_MILLISECONDS = 1e4;
43056
43161
  var HEARTBEAT_INTERVAL_MILLISECONDS = 2e4;
43057
43162
  var RelayLivenessState = class {
@@ -43140,7 +43245,7 @@ var RelayConnectionLiveness = class {
43140
43245
  }
43141
43246
  throw new Error("Heartbeat was scheduled in an invalid state");
43142
43247
  }
43143
- const heartbeatId = randomUUID7();
43248
+ const heartbeatId = randomUUID8();
43144
43249
  this.#state = new AwaitingHeartbeatAckState(
43145
43250
  heartbeatId,
43146
43251
  this.#timer.schedule(this.#handleTimeout, HEARTBEAT_ACK_TIMEOUT_MILLISECONDS)
@@ -43432,7 +43537,7 @@ var SystemDaemonTimer = class {
43432
43537
  var systemDaemonTimer = new SystemDaemonTimer();
43433
43538
 
43434
43539
  // src/session-event-log-v2.ts
43435
- import { createHash as createHash7, randomUUID as randomUUID8 } from "node:crypto";
43540
+ import { createHash as createHash7, randomUUID as randomUUID9 } from "node:crypto";
43436
43541
  function promptContent(command) {
43437
43542
  const content = [];
43438
43543
  if (command.prompt.length > 0) {
@@ -43456,7 +43561,7 @@ function promptContent(command) {
43456
43561
  }
43457
43562
  return content;
43458
43563
  }
43459
- function sessionEventV2(daemonGenerationId, sessionId, position, event, recordedAt) {
43564
+ function sessionEventV22(daemonGenerationId, sessionId, position, event, recordedAt) {
43460
43565
  const sessionPrefix = createHash7("sha256").update(sessionId).digest("hex").slice(0, 16);
43461
43566
  return {
43462
43567
  eventId: `event-${daemonGenerationId}-${sessionPrefix}-${position.toString().padStart(16, "0")}`,
@@ -43468,11 +43573,12 @@ function sessionEventV2(daemonGenerationId, sessionId, position, event, recorded
43468
43573
  };
43469
43574
  }
43470
43575
  var DaemonSessionEventLogV2 = class {
43471
- daemonGenerationId = randomUUID8();
43576
+ daemonGenerationId;
43472
43577
  #publisher;
43473
43578
  #queued = /* @__PURE__ */ new Map();
43474
- constructor(publisher) {
43579
+ constructor(publisher, daemonGenerationId = randomUUID9()) {
43475
43580
  this.#publisher = publisher;
43581
+ this.daemonGenerationId = daemonGenerationId;
43476
43582
  }
43477
43583
  requested = (command) => {
43478
43584
  this.#queued.set(command.commandId, {
@@ -43492,7 +43598,7 @@ var DaemonSessionEventLogV2 = class {
43492
43598
  record = (sessionId, event, position) => {
43493
43599
  this.#publisher.publishV2(this.event(sessionId, position, event, (/* @__PURE__ */ new Date()).toISOString()));
43494
43600
  };
43495
- event = (sessionId, position, event, recordedAt) => sessionEventV2(this.daemonGenerationId, sessionId, position, event, recordedAt);
43601
+ event = (sessionId, position, event, recordedAt) => sessionEventV22(this.daemonGenerationId, sessionId, position, event, recordedAt);
43496
43602
  queueChanged = (_sessionId) => void 0;
43497
43603
  completed = (sessionId, commandId, _stopReason) => {
43498
43604
  const request = this.#queued.get(commandId);
@@ -43559,7 +43665,7 @@ async function installDetectedAgentIntegrations(config2, installations, signal)
43559
43665
  {
43560
43666
  agentId: agent.id,
43561
43667
  kind: AGENT_INSTALL_REQUEST_KIND,
43562
- requestId: `automatic-integration-${randomUUID9()}`
43668
+ requestId: `automatic-integration-${randomUUID10()}`
43563
43669
  },
43564
43670
  signal
43565
43671
  );
@@ -43577,13 +43683,24 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
43577
43683
  publishCatalog: async (installationSignal) => await publishAgentCatalog(config2, installationSignal),
43578
43684
  stateDirectory
43579
43685
  });
43580
- const sessionStore = new SqliteAcpSessionStore(
43581
- join19(stateDirectory, "sessions", `${createHash8("sha256").update(config2.channelId).digest("hex")}.sqlite`)
43582
- );
43686
+ const channelHash = createHash8("sha256").update(config2.channelId).digest("hex");
43687
+ const daemonGenerationId = randomUUID10();
43688
+ const sessionDatabase = openAcpSessionDatabase(join19(stateDirectory, "sessions", `${channelHash}.sqlite`));
43689
+ let eventsV2;
43690
+ try {
43691
+ eventsV2 = new CachedAcpSessionEventStoreV2(
43692
+ openSessionEventCacheV2Database(join19(stateDirectory, "sessions", `${channelHash}.events.sqlite`)),
43693
+ daemonGenerationId
43694
+ );
43695
+ } catch (error62) {
43696
+ sessionDatabase.close();
43697
+ throw error62;
43698
+ }
43699
+ const sessionStore = new SqliteAcpSessionStore(sessionDatabase, eventsV2);
43583
43700
  await using externalContent = new LocalExternalContentStore(stateDirectory);
43584
43701
  const operations = new DaemonOperationState();
43585
43702
  const publisher = new DaemonSessionEventPublisher();
43586
- const eventLogV2 = new DaemonSessionEventLogV2(publisher);
43703
+ const eventLogV2 = new DaemonSessionEventLogV2(publisher, daemonGenerationId);
43587
43704
  const activeTurns = new DaemonTurnRegistry(operations);
43588
43705
  const recordSessionEvent = (sessionId, event) => {
43589
43706
  publisher.publish(sessionId, activeTurns.recordEvent(event));
@@ -43629,7 +43746,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
43629
43746
  options2.signal
43630
43747
  );
43631
43748
  return cwd === options2.cwd && additionalDirectories.length === options2.additionalDirectories.length && additionalDirectories.every(
43632
- (directory, index) => directory === options2.additionalDirectories[index]
43749
+ (directory, index2) => directory === options2.additionalDirectories[index2]
43633
43750
  );
43634
43751
  });
43635
43752
  }