@moxt-ai/mobius 0.0.175 → 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 (49) hide show
  1. package/dist/acp/agent-session.d.ts.map +1 -1
  2. package/dist/acp/agent-session.js +14 -8
  3. package/dist/acp/agent-session.js.map +1 -1
  4. package/dist/acp/session-event-store-v2.d.ts +37 -0
  5. package/dist/acp/session-event-store-v2.d.ts.map +1 -0
  6. package/dist/acp/session-event-store-v2.js +199 -0
  7. package/dist/acp/session-event-store-v2.js.map +1 -0
  8. package/dist/acp/session-history.d.ts +3 -2
  9. package/dist/acp/session-history.d.ts.map +1 -1
  10. package/dist/acp/session-history.js +37 -41
  11. package/dist/acp/session-history.js.map +1 -1
  12. package/dist/acp/session-store.d.ts +7 -1
  13. package/dist/acp/session-store.d.ts.map +1 -1
  14. package/dist/acp/session-store.js +20 -37
  15. package/dist/acp/session-store.js.map +1 -1
  16. package/dist/cli.js +973 -609
  17. package/dist/cli.js.map +4 -4
  18. package/dist/generated/session-event-cache-migrations.d.ts +5 -0
  19. package/dist/generated/session-event-cache-migrations.d.ts.map +1 -0
  20. package/dist/generated/session-event-cache-migrations.js +9 -0
  21. package/dist/generated/session-event-cache-migrations.js.map +1 -0
  22. package/dist/index.js +967 -604
  23. package/dist/index.js.map +4 -4
  24. package/dist/infra/local-sqlite-database.d.ts +13 -0
  25. package/dist/infra/local-sqlite-database.d.ts.map +1 -0
  26. package/dist/infra/local-sqlite-database.js +57 -0
  27. package/dist/infra/local-sqlite-database.js.map +1 -0
  28. package/dist/local-databases.d.ts +4 -0
  29. package/dist/local-databases.d.ts.map +1 -0
  30. package/dist/local-databases.js +9 -0
  31. package/dist/local-databases.js.map +1 -0
  32. package/dist/run-daemon.d.ts.map +1 -1
  33. package/dist/run-daemon.js +15 -2
  34. package/dist/run-daemon.js.map +1 -1
  35. package/dist/runtime.js +955 -592
  36. package/dist/runtime.js.map +4 -4
  37. package/dist/schema/session-event-cache/index.d.ts +2 -0
  38. package/dist/schema/session-event-cache/index.d.ts.map +1 -0
  39. package/dist/schema/session-event-cache/index.js +2 -0
  40. package/dist/schema/session-event-cache/index.js.map +1 -0
  41. package/dist/schema/session-event-cache/session-event-v2.d.ts +72 -0
  42. package/dist/schema/session-event-cache/session-event-v2.d.ts.map +1 -0
  43. package/dist/schema/session-event-cache/session-event-v2.js +11 -0
  44. package/dist/schema/session-event-cache/session-event-v2.js.map +1 -0
  45. package/dist/session-event-log-v2.d.ts +2 -2
  46. package/dist/session-event-log-v2.d.ts.map +1 -1
  47. package/dist/session-event-log-v2.js +3 -2
  48. package/dist/session-event-log-v2.js.map +1 -1
  49. package/package.json +2 -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);
@@ -21529,12 +21529,12 @@ var sessionExportV2Schema = external_exports.object({
21529
21529
  }).readonly().superRefine((session, context) => {
21530
21530
  let previousPosition = 0n;
21531
21531
  const eventIds = /* @__PURE__ */ new Set();
21532
- for (const [index, event] of session.events.entries()) {
21532
+ for (const [index2, event] of session.events.entries()) {
21533
21533
  if (event.sessionId !== session.sessionId) {
21534
21534
  context.addIssue({
21535
21535
  code: "custom",
21536
21536
  message: "Exported event belongs to a different Session",
21537
- path: ["events", index, "sessionId"]
21537
+ path: ["events", index2, "sessionId"]
21538
21538
  });
21539
21539
  }
21540
21540
  const position = BigInt(event.position);
@@ -21542,14 +21542,14 @@ var sessionExportV2Schema = external_exports.object({
21542
21542
  context.addIssue({
21543
21543
  code: "custom",
21544
21544
  message: "Exported events are not in increasing position order",
21545
- path: ["events", index, "position"]
21545
+ path: ["events", index2, "position"]
21546
21546
  });
21547
21547
  }
21548
21548
  if (eventIds.has(event.eventId)) {
21549
21549
  context.addIssue({
21550
21550
  code: "custom",
21551
21551
  message: "Exported event identities are not unique",
21552
- path: ["events", index, "eventId"]
21552
+ path: ["events", index2, "eventId"]
21553
21553
  });
21554
21554
  }
21555
21555
  previousPosition = position;
@@ -21600,6 +21600,7 @@ function decode5(value, schema) {
21600
21600
  function encode4(value, schema) {
21601
21601
  return JSON.stringify(decode5(value, schema));
21602
21602
  }
21603
+ var decodeSessionEventV2 = (value) => decode5(value, sessionEventV2Schema);
21603
21604
  var decodeSessionEventEnvelopeV2 = (value) => decode5(value, sessionEventEnvelopeV2Schema);
21604
21605
  var encodeSessionEventEnvelopeV2 = (value) => encode4(value, sessionEventEnvelopeV2Schema);
21605
21606
  var decodeAcpSessionUpdateV2 = (value) => decode5(value, acpSessionUpdateV2Schema);
@@ -22915,7 +22916,7 @@ function startsWith(bytes, signature, offset = 0) {
22915
22916
  if (bytes.byteLength < offset + signature.byteLength) {
22916
22917
  return false;
22917
22918
  }
22918
- return signature.every((value, index) => bytes[offset + index] === value);
22919
+ return signature.every((value, index2) => bytes[offset + index2] === value);
22919
22920
  }
22920
22921
  function sniffRasterMime(bytes) {
22921
22922
  if (startsWith(bytes, PNG_SIGNATURE)) {
@@ -23043,7 +23044,7 @@ function startsWith2(bytes, signature, offset = 0) {
23043
23044
  if (bytes.byteLength < offset + signature.byteLength) {
23044
23045
  return false;
23045
23046
  }
23046
- return signature.every((value, index) => bytes[offset + index] === value);
23047
+ return signature.every((value, index2) => bytes[offset + index2] === value);
23047
23048
  }
23048
23049
  function sniffVideoMime(bytes) {
23049
23050
  if (startsWith2(bytes, MP4_FILE_TYPE, 4)) {
@@ -23172,10 +23173,10 @@ async function replaceImageMarkers(text2, replace) {
23172
23173
  let cursor = 0;
23173
23174
  let rewritten = "";
23174
23175
  for (const match of matches) {
23175
- const index = match.index ?? 0;
23176
- rewritten += text2.slice(cursor, index);
23176
+ const index2 = match.index ?? 0;
23177
+ rewritten += text2.slice(cursor, index2);
23177
23178
  rewritten += await replace(match[1] ?? "");
23178
- cursor = index + match[0].length;
23179
+ cursor = index2 + match[0].length;
23179
23180
  }
23180
23181
  return `${rewritten}${text2.slice(cursor)}`;
23181
23182
  }
@@ -24493,9 +24494,9 @@ function historyContentCharacters(messages) {
24493
24494
  var AcpHistoryReplay = class {
24494
24495
  #activities = /* @__PURE__ */ new Map();
24495
24496
  #messages = [];
24496
- #events = [];
24497
- #records = [];
24497
+ #events;
24498
24498
  #turnActivityIds = /* @__PURE__ */ new Set();
24499
+ #sessionId;
24499
24500
  #activityTracker = new AcpActivityTracker(
24500
24501
  async (activity2) => {
24501
24502
  this.#activities.set(activity2.activityId, activity2);
@@ -24516,10 +24517,16 @@ var AcpHistoryReplay = class {
24516
24517
  #firstMessageIndex = 0;
24517
24518
  #characters = 0;
24518
24519
  #truncated = false;
24520
+ constructor(events, sessionId) {
24521
+ this.#events = events;
24522
+ this.#sessionId = sessionId;
24523
+ }
24519
24524
  record = async (update, rawUpdate, onRecorded = () => Promise.resolve()) => {
24520
- this.#records.push({ kind: "acp", rawUpdate, update });
24521
- this.#events.push({ payload: rawUpdate, type: "acp" });
24522
- 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) => {
24523
24530
  if (update.sessionUpdate === "agent_thought_chunk") {
24524
24531
  if (update.content.type === "text") {
24525
24532
  await this.#activityTracker.recordNarrative(
@@ -24528,30 +24535,30 @@ var AcpHistoryReplay = class {
24528
24535
  update.content.text
24529
24536
  );
24530
24537
  }
24531
- return this.#events.length;
24538
+ return position;
24532
24539
  }
24533
24540
  if (update.sessionUpdate === "tool_call") {
24534
24541
  await this.#activityTracker.recordToolCall(update);
24535
- return this.#events.length;
24542
+ return position;
24536
24543
  }
24537
24544
  if (update.sessionUpdate === "tool_call_update") {
24538
24545
  await this.#activityTracker.recordToolCallUpdate(update);
24539
- return this.#events.length;
24546
+ return position;
24540
24547
  }
24541
24548
  if (update.sessionUpdate === "plan") {
24542
24549
  await this.#activityTracker.recordPlan(update);
24543
- return this.#events.length;
24550
+ return position;
24544
24551
  }
24545
24552
  if (update.sessionUpdate === "plan_update") {
24546
24553
  await this.#activityTracker.recordPlanUpdate(update);
24547
- return this.#events.length;
24554
+ return position;
24548
24555
  }
24549
24556
  if (update.sessionUpdate === "plan_removed") {
24550
24557
  await this.#activityTracker.removePlan(update);
24551
- return this.#events.length;
24558
+ return position;
24552
24559
  }
24553
24560
  if (update.sessionUpdate !== "user_message_chunk" && update.sessionUpdate !== "agent_message_chunk") {
24554
- return this.#events.length;
24561
+ return position;
24555
24562
  }
24556
24563
  if (update.sessionUpdate === "agent_message_chunk" && isProgressMessage(update)) {
24557
24564
  if (update.content.type === "text") {
@@ -24561,18 +24568,18 @@ var AcpHistoryReplay = class {
24561
24568
  update.content.text
24562
24569
  );
24563
24570
  }
24564
- return this.#events.length;
24571
+ return position;
24565
24572
  }
24566
24573
  const role = update.sessionUpdate === "user_message_chunk" ? "user" : "assistant";
24567
24574
  const content = update.content;
24568
24575
  if (role === "assistant" && content.type !== "text") {
24569
24576
  await this.#activityTracker.finishNarrative();
24570
24577
  this.recordAssistantContent(update.messageId ?? null, normalizeContentBlock(content));
24571
- return this.#events.length;
24578
+ return position;
24572
24579
  }
24573
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]`;
24574
24581
  if (text2.length === 0) {
24575
- return this.#events.length;
24582
+ return position;
24576
24583
  }
24577
24584
  const previous = this.#messages.at(-1);
24578
24585
  const id = update.messageId ?? null;
@@ -24599,41 +24606,32 @@ var AcpHistoryReplay = class {
24599
24606
  this.#characters += bounded2.length;
24600
24607
  this.#lastMessageId = id;
24601
24608
  this.trimMessages();
24602
- return this.#events.length;
24609
+ return position;
24603
24610
  };
24604
24611
  recordLifecycle = (event) => {
24605
24612
  if (event.type !== "lifecycle-metadata") {
24606
24613
  throw new Error("Lifecycle history only accepts lifecycle metadata");
24607
24614
  }
24608
- this.#records.push({ event, kind: "lifecycle" });
24609
- this.#events.push(event);
24610
- return this.#events.length;
24615
+ return this.#events.append(this.#sessionId, event);
24611
24616
  };
24612
- eventCount = () => this.#events.length;
24613
24617
  append = async (replay) => {
24614
- for (const record2 of replay.#records) {
24615
- if (record2.kind === "acp") {
24616
- await this.record(record2.update, record2.rawUpdate);
24617
- } else {
24618
- this.recordLifecycle(record2.event);
24619
- }
24618
+ await replay.#activityTracker.finish();
24619
+ for (const [activityId, activity2] of replay.#activities) {
24620
+ this.#activities.set(activityId, activity2);
24620
24621
  }
24621
- };
24622
- eventPage = (eventLimit, cursor, appended = null) => {
24623
- const events = appended === null ? this.#events : [...this.#events, ...appended.#events];
24624
- const parsedCursor = cursor === null ? events.length : Number(cursor);
24625
- if (!Number.isSafeInteger(parsedCursor) || parsedCursor < 0 || parsedCursor > events.length) {
24626
- 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;
24627
24625
  }
24628
- const endUpdate = parsedCursor;
24629
- const startUpdate = Math.max(0, endUpdate - eventLimit);
24630
- return {
24631
- nextCursor: startUpdate === 0 ? null : startUpdate.toString(),
24632
- startPosition: startUpdate + 1,
24633
- truncated: startUpdate > 0,
24634
- events: events.slice(startUpdate, endUpdate)
24635
- };
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();
24636
24633
  };
24634
+ eventPage = (eventLimit, cursor) => this.#events.page(this.#sessionId, eventLimit, cursor);
24637
24635
  snapshot = async () => {
24638
24636
  await this.#activityTracker.finish();
24639
24637
  const messages = this.#messages.slice(this.#firstMessageIndex).map((message) => {
@@ -25266,9 +25264,7 @@ var AcpSessionInteractions = class {
25266
25264
  };
25267
25265
 
25268
25266
  // src/acp/session-store.ts
25269
- import { chmodSync, mkdirSync } from "node:fs";
25270
- import { dirname } from "node:path";
25271
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
25267
+ import { randomUUID } from "node:crypto";
25272
25268
 
25273
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
25274
25270
  var entityKind = /* @__PURE__ */ Symbol.for("drizzle:entityKind");
@@ -26384,7 +26380,7 @@ function haveSameKeys(left, right) {
26384
26380
  const leftKeys = Object.keys(left);
26385
26381
  const rightKeys = Object.keys(right);
26386
26382
  if (leftKeys.length !== rightKeys.length) return false;
26387
- 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;
26388
26384
  return true;
26389
26385
  }
26390
26386
  function mapUpdateSet(table, values) {
@@ -27137,195 +27133,6 @@ var NoopLogger = class {
27137
27133
  }
27138
27134
  };
27139
27135
 
27140
- // ../../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
27141
- var SQLiteCountBuilder = class SQLiteCountBuilder2 extends SQL {
27142
- static [entityKind] = "SQLiteCountBuilder";
27143
- dialect;
27144
- session;
27145
- static buildCount(source, filters, parens) {
27146
- const query = sql`select count(*) from ${source}${sql` where ${filters}`.if(filters)}`;
27147
- return parens ? sql`(${query})` : query;
27148
- }
27149
- constructor(countConfig) {
27150
- super(SQLiteCountBuilder2.buildCount(countConfig.source, countConfig.filters, true).queryChunks);
27151
- this.countConfig = countConfig;
27152
- this.dialect = countConfig.dialect;
27153
- this.session = countConfig.session;
27154
- this.mapWith((e) => {
27155
- if (typeof e === "number") return e;
27156
- return Number(e ?? 0);
27157
- });
27158
- }
27159
- executableSql;
27160
- build() {
27161
- if (!this.executableSql) {
27162
- const { source, filters } = this.countConfig;
27163
- this.executableSql = SQLiteCountBuilder2.buildCount(source, filters);
27164
- }
27165
- return this.dialect.sqlToQuery(this.executableSql);
27166
- }
27167
- };
27168
-
27169
- // ../../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
27170
- var SQLiteAsyncCountBuilder = class extends SQLiteCountBuilder {
27171
- static [entityKind] = "SQLiteAsyncCountBuilder";
27172
- constructor(countConfig) {
27173
- super(countConfig);
27174
- }
27175
- /** @internal */
27176
- executeRaw(placeholderValues) {
27177
- return this.session.prepareQuery(this.build(), "arrays", false, "all", (rows) => {
27178
- const v = rows[0]?.[0];
27179
- if (typeof v === "number") return v;
27180
- return v ? Number(v) : 0;
27181
- }).execute(placeholderValues);
27182
- }
27183
- async execute(placeholderValues) {
27184
- return await this.executeRaw(placeholderValues);
27185
- }
27186
- };
27187
- applyMixins(SQLiteAsyncCountBuilder, [QueryPromise]);
27188
- var SQLiteSyncCountBuilder = class extends SQLiteAsyncCountBuilder {
27189
- static [entityKind] = "SQLiteSyncCountBuilder";
27190
- sync(placeholderValues) {
27191
- return this.executeRaw(placeholderValues).sync();
27192
- }
27193
- };
27194
-
27195
- // ../../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
27196
- var RelationalQueryBuilder = class {
27197
- static [entityKind] = "SQLiteRelationalQueryBuilderV2";
27198
- constructor(mode, schema, table, tableConfig, dialect, session, forbidJsonb, builder = SQLiteRelationalQuery) {
27199
- this.mode = mode;
27200
- this.schema = schema;
27201
- this.table = table;
27202
- this.tableConfig = tableConfig;
27203
- this.dialect = dialect;
27204
- this.session = session;
27205
- this.forbidJsonb = forbidJsonb;
27206
- this.builder = builder;
27207
- }
27208
- findMany(config2) {
27209
- return new this.builder(this.mode, this.schema, this.table, this.tableConfig, this.dialect, this.session, config2 ?? true, "many", this.forbidJsonb);
27210
- }
27211
- findFirst(config2) {
27212
- return new this.builder(this.mode, this.schema, this.table, this.tableConfig, this.dialect, this.session, config2 ?? true, "first", this.forbidJsonb);
27213
- }
27214
- };
27215
- var SQLiteRelationalQuery = class {
27216
- static [entityKind] = "SQLiteRelationalQueryV2";
27217
- /** @internal */
27218
- mode;
27219
- /** @internal */
27220
- table;
27221
- /** @internal */
27222
- resultKind;
27223
- constructor(resultKind, schema, table, tableConfig, dialect, session, config2, mode, forbidJsonb) {
27224
- this.schema = schema;
27225
- this.tableConfig = tableConfig;
27226
- this.dialect = dialect;
27227
- this.session = session;
27228
- this.config = config2;
27229
- this.forbidJsonb = forbidJsonb;
27230
- this.resultKind = resultKind;
27231
- this.mode = mode;
27232
- this.table = table;
27233
- }
27234
- getSQL() {
27235
- return this._getQuery().sql;
27236
- }
27237
- _getQuery() {
27238
- const jsonb = this.forbidJsonb ? sql`json` : sql`jsonb`;
27239
- return this.dialect.buildRelationalQuery({
27240
- schema: this.schema,
27241
- table: this.table,
27242
- tableConfig: this.tableConfig,
27243
- queryConfig: this.config,
27244
- mode: this.mode,
27245
- jsonb
27246
- });
27247
- }
27248
- _toSQL() {
27249
- const query = this._getQuery();
27250
- return {
27251
- query,
27252
- builtQuery: this.dialect.sqlToQuery(query.sql)
27253
- };
27254
- }
27255
- toSQL() {
27256
- return this._toSQL().builtQuery;
27257
- }
27258
- };
27259
-
27260
- // ../../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
27261
- var SQLiteAsyncRelationalQuery = class extends SQLiteRelationalQuery {
27262
- static [entityKind] = "SQLiteAsyncRelationalQueryV2";
27263
- /** @internal */
27264
- _prepare(prepare = false) {
27265
- const { query, builtQuery } = this._toSQL();
27266
- const mapper = this.dialect.mapperGenerators.relationalRows({
27267
- isFirst: this.mode === "first",
27268
- parseJson: true,
27269
- parseJsonIfString: false,
27270
- rootJsonMappers: false,
27271
- selection: query.selection,
27272
- arrayModeRoot: true
27273
- });
27274
- return this.session.prepareQuery(builtQuery, "arrays", prepare, "all", mapper);
27275
- }
27276
- prepare() {
27277
- return this._prepare(true);
27278
- }
27279
- async execute(placeholderValues) {
27280
- return this._prepare().execute(placeholderValues);
27281
- }
27282
- };
27283
- var SQLiteSyncRelationalQuery = class extends SQLiteAsyncRelationalQuery {
27284
- static [entityKind] = "SQLiteSyncRelationalQueryV2";
27285
- sync(placeholderValues) {
27286
- return this._prepare().execute(placeholderValues).sync();
27287
- }
27288
- };
27289
- applyMixins(SQLiteAsyncRelationalQuery, [QueryPromise]);
27290
-
27291
- // ../../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
27292
- var SelectionProxyHandler = class SelectionProxyHandler2 {
27293
- static [entityKind] = "SelectionProxyHandler";
27294
- config;
27295
- constructor(config2) {
27296
- this.config = { ...config2 };
27297
- }
27298
- get(subquery, prop) {
27299
- if (prop === "_") return {
27300
- ...subquery["_"],
27301
- selectedFields: new Proxy(subquery._.selectedFields, this)
27302
- };
27303
- if (prop === ViewBaseConfig) return {
27304
- ...subquery[ViewBaseConfig],
27305
- selectedFields: new Proxy(subquery[ViewBaseConfig].selectedFields, this)
27306
- };
27307
- if (typeof prop === "symbol") return subquery[prop];
27308
- const value = (is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View) ? subquery[ViewBaseConfig].selectedFields : subquery)[prop];
27309
- if (is(value, SQL.Aliased)) {
27310
- if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) return value.sql;
27311
- const newValue = value.clone();
27312
- newValue.isSelectionField = true;
27313
- newValue.origin = this.config.alias;
27314
- return newValue;
27315
- }
27316
- if (is(value, SQL)) {
27317
- if (this.config.sqlBehavior === "sql") return value;
27318
- 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.`);
27319
- }
27320
- if (is(value, Column)) {
27321
- 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));
27322
- return value;
27323
- }
27324
- if (typeof value !== "object" || value === null) return value;
27325
- return new Proxy(value, new SelectionProxyHandler2(this.config));
27326
- }
27327
- };
27328
-
27329
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
27330
27137
  var ForeignKeyBuilder = class {
27331
27138
  static [entityKind] = "SQLiteForeignKeyBuilder";
@@ -27890,130 +27697,144 @@ function sqliteTableWithCasing(casing) {
27890
27697
  }
27891
27698
  var sqliteTable = sqliteTableWithCasing(void 0);
27892
27699
 
27893
- // ../../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
27894
- function extractUsedTable(table) {
27895
- if (is(table, SQLiteTable)) return [`${table[Table.Symbol.BaseName]}`];
27896
- if (is(table, Subquery)) return table._.usedTables ?? [];
27897
- if (is(table, SQL)) return table.usedTables ?? [];
27898
- return [];
27899
- }
27900
-
27901
- // ../../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
27902
- var SQLiteDeleteBase = class {
27903
- 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";
27904
27713
  /** @internal */
27905
27714
  config;
27906
- constructor(table, session, dialect, withList) {
27907
- this.table = table;
27908
- this.session = session;
27909
- this.dialect = dialect;
27715
+ constructor(name2, columns, unique) {
27910
27716
  this.config = {
27911
- table,
27912
- withList
27717
+ name: name2,
27718
+ columns,
27719
+ unique,
27720
+ where: void 0
27913
27721
  };
27914
27722
  }
27915
27723
  /**
27916
- * Adds a `where` clause to the query.
27917
- *
27918
- * Calling this method will delete only those rows that fulfill a specified condition.
27919
- *
27920
- * See docs: {@link https://orm.drizzle.team/docs/delete}
27921
- *
27922
- * @param where the `where` clause.
27923
- *
27924
- * @example
27925
- * You can use conditional operators and `sql function` to filter the rows to be deleted.
27926
- *
27927
- * ```ts
27928
- * // Delete all cars with green color
27929
- * db.delete(cars).where(eq(cars.color, 'green'));
27930
- * // or
27931
- * db.delete(cars).where(sql`${cars.color} = 'green'`)
27932
- * ```
27933
- *
27934
- * You can logically combine conditional operators with `and()` and `or()` operators:
27935
- *
27936
- * ```ts
27937
- * // Delete all BMW cars with a green color
27938
- * db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
27939
- *
27940
- * // Delete all cars with the green or blue color
27941
- * db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
27942
- * ```
27724
+ * Condition for partial index.
27943
27725
  */
27944
- where(where) {
27945
- this.config.where = where;
27726
+ where(condition) {
27727
+ this.config.where = condition;
27946
27728
  return this;
27947
27729
  }
27948
- orderBy(...columns) {
27949
- if (typeof columns[0] === "function") {
27950
- const orderBy = columns[0](new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({
27951
- sqlAliasedBehavior: "alias",
27952
- sqlBehavior: "sql"
27953
- })));
27954
- const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
27955
- this.config.orderBy = orderByArray;
27956
- } else {
27957
- const orderByArray = columns;
27958
- this.config.orderBy = orderByArray;
27959
- }
27960
- return this;
27961
- }
27962
- limit(limit) {
27963
- this.config.limit = limit;
27964
- return this;
27965
- }
27966
- returning(fields = this.table[SQLiteTable.Symbol.Columns]) {
27967
- this.config.returning = orderSelectedFields(fields);
27968
- return this;
27969
- }
27970
- getSQL() {
27971
- return this.dialect.buildDeleteQuery(this.config);
27972
- }
27973
- toSQL() {
27974
- return this.dialect.sqlToQuery(this.getSQL());
27730
+ /** @internal */
27731
+ build(table) {
27732
+ return new Index(this.config, table);
27975
27733
  }
27976
- $dynamic() {
27977
- 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;
27978
27745
  }
27979
27746
  };
27747
+ function index(name2) {
27748
+ return new IndexBuilderOn(name2, false);
27749
+ }
27980
27750
 
27981
- // ../../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
27982
- var SQLiteAsyncDeleteBase = class extends SQLiteDeleteBase {
27983
- 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";
27984
27758
  /** @internal */
27985
- _prepare(prepare = false) {
27986
- 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, {
27987
- type: "delete",
27988
- tables: extractUsedTable(this.config.table)
27989
- });
27759
+ columns;
27760
+ /** @internal */
27761
+ name;
27762
+ constructor(columns, name2) {
27763
+ this.columns = columns;
27764
+ this.name = name2;
27990
27765
  }
27991
- prepare() {
27992
- return this._prepare(true);
27766
+ /** @internal */
27767
+ build(table) {
27768
+ return new PrimaryKey(table, this.columns, this.name);
27993
27769
  }
27994
- run = (placeholderValues) => {
27995
- return this._prepare().run(placeholderValues);
27996
- };
27997
- all = (placeholderValues) => {
27998
- return this._prepare().all(placeholderValues);
27999
- };
28000
- get = (placeholderValues) => {
28001
- return this._prepare().get(placeholderValues);
28002
- };
28003
- values = (placeholderValues) => {
28004
- return this._prepare().values(placeholderValues);
28005
- };
28006
- async execute(placeholderValues) {
28007
- 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`;
28008
27784
  }
28009
27785
  };
28010
- 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
+ }
28011
27794
 
28012
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
28013
27796
  var SQLiteViewBase = class extends View {
28014
27797
  static [entityKind] = "SQLiteViewBase";
28015
27798
  };
28016
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
+
28017
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
28018
27839
  var TypedQueryBuilder = class {
28019
27840
  static [entityKind] = "TypedQueryBuilder";
@@ -28714,8 +28535,8 @@ var SQLiteDialect = class {
28714
28535
  buildJoins(joins) {
28715
28536
  if (!joins || joins.length === 0) return;
28716
28537
  const joinsArray = [];
28717
- if (joins) for (const [index, joinMeta] of joins.entries()) {
28718
- if (index === 0) joinsArray.push(sql` `);
28538
+ if (joins) for (const [index2, joinMeta] of joins.entries()) {
28539
+ if (index2 === 0) joinsArray.push(sql` `);
28719
28540
  const table = joinMeta.table;
28720
28541
  const onSql = joinMeta.on ? sql` on ${joinMeta.on}` : void 0;
28721
28542
  if (is(table, SQLiteTable)) {
@@ -28725,7 +28546,7 @@ var SQLiteDialect = class {
28725
28546
  const alias = tableName === origTableName ? void 0 : joinMeta.alias;
28726
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}`);
28727
28548
  } else joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join ${table}${onSql}`);
28728
- if (index < joins.length - 1) joinsArray.push(sql` `);
28549
+ if (index2 < joins.length - 1) joinsArray.push(sql` `);
28729
28550
  }
28730
28551
  return sql.join(joinsArray);
28731
28552
  }
@@ -28734,9 +28555,9 @@ var SQLiteDialect = class {
28734
28555
  }
28735
28556
  buildOrderBy(orderBy) {
28736
28557
  const orderByList = [];
28737
- if (orderBy) for (const [index, orderByValue] of orderBy.entries()) {
28558
+ if (orderBy) for (const [index2, orderByValue] of orderBy.entries()) {
28738
28559
  orderByList.push(orderByValue);
28739
- if (index < orderBy.length - 1) orderByList.push(sql`, `);
28560
+ if (index2 < orderBy.length - 1) orderByList.push(sql`, `);
28740
28561
  }
28741
28562
  return orderByList.length > 0 ? sql` order by ${sql.join(orderByList)}` : void 0;
28742
28563
  }
@@ -28764,9 +28585,9 @@ var SQLiteDialect = class {
28764
28585
  const whereSql = where ? sql` where ${where}` : void 0;
28765
28586
  const havingSql = having ? sql` having ${having}` : void 0;
28766
28587
  const groupByList = [];
28767
- if (groupBy) for (const [index, groupByValue] of groupBy.entries()) {
28588
+ if (groupBy) for (const [index2, groupByValue] of groupBy.entries()) {
28768
28589
  groupByList.push(groupByValue);
28769
- if (index < groupBy.length - 1) groupByList.push(sql`, `);
28590
+ if (index2 < groupBy.length - 1) groupByList.push(sql`, `);
28770
28591
  }
28771
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}`;
28772
28593
  if (setOperators.length > 0) return this.buildSetOperations(finalQuery, setOperators);
@@ -29055,6 +28876,268 @@ var QueryBuilder = class {
29055
28876
  }
29056
28877
  };
29057
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
+
29058
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
29059
29142
  var SQLiteInsertBuilder = class {
29060
29143
  static [entityKind] = "SQLiteInsertBuilder";
@@ -29942,133 +30025,6 @@ var SQLiteAsyncTransaction = class extends SQLiteAsyncDatabase {
29942
30025
  }
29943
30026
  };
29944
30027
 
29945
- // ../../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
29946
- var NodeSQLiteSession = class extends SQLiteAsyncSession {
29947
- static [entityKind] = "SQLJsSession";
29948
- logger;
29949
- constructor(client2, dialect, relations, options = {}) {
29950
- super(dialect, "sync");
29951
- this.client = client2;
29952
- this.relations = relations;
29953
- this.options = options;
29954
- this.logger = options.logger ?? new NoopLogger();
29955
- }
29956
- prepareQuery(query, mode, _prepare, executeMethod, mapper, queryMetadata) {
29957
- let stmt;
29958
- try {
29959
- stmt = this.client.prepare(query.sql);
29960
- } catch (e) {
29961
- throw new DrizzleQueryError(query.sql, query.params, e);
29962
- }
29963
- return new SQLiteAsyncPreparedQuery("sync", executeMethod, {
29964
- all: (params) => {
29965
- stmt.setReturnArrays(mode === "arrays");
29966
- const res = stmt.all(...params);
29967
- if (mode === "objects") return res.map((row) => ({ ...row }));
29968
- return res;
29969
- },
29970
- get: (params) => {
29971
- stmt.setReturnArrays(mode === "arrays");
29972
- const res = stmt.get(...params);
29973
- if (res && mode === "objects") return { ...res };
29974
- return res;
29975
- },
29976
- run: (params) => {
29977
- stmt.setReturnArrays(false);
29978
- return stmt.run(...params);
29979
- },
29980
- values: (params) => {
29981
- stmt.setReturnArrays(true);
29982
- return stmt.all(...params);
29983
- }
29984
- }, query, mapper, mode, this.logger, void 0, queryMetadata, void 0);
29985
- }
29986
- transaction(transaction, config2 = {}) {
29987
- const tx = new NodeSQLiteTransaction("sync", this.dialect, this, this.relations);
29988
- this.run(sql.raw(`begin${config2.behavior ? ` ${config2.behavior}` : ""}`));
29989
- try {
29990
- const result = transaction(tx);
29991
- this.run(sql`commit`);
29992
- return result;
29993
- } catch (err) {
29994
- this.run(sql`rollback`);
29995
- throw err;
29996
- }
29997
- }
29998
- };
29999
- var NodeSQLiteTransaction = class NodeSQLiteTransaction2 extends SQLiteAsyncTransaction {
30000
- static [entityKind] = "SQLJsTransaction";
30001
- transaction(transaction) {
30002
- const savepointName = `sp${this.nestedIndex + 1}`;
30003
- const tx = new NodeSQLiteTransaction2("sync", this.dialect, this.session, this._.relations, this.nestedIndex + 1);
30004
- tx.run(sql.raw(`savepoint ${savepointName}`));
30005
- try {
30006
- const result = transaction(tx);
30007
- tx.run(sql.raw(`release savepoint ${savepointName}`));
30008
- return result;
30009
- } catch (err) {
30010
- tx.run(sql.raw(`rollback to savepoint ${savepointName}`));
30011
- throw err;
30012
- }
30013
- }
30014
- };
30015
-
30016
- // ../../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
30017
- import { DatabaseSync } from "node:sqlite";
30018
- var NodeSQLiteDatabase = class extends SQLiteAsyncDatabase {
30019
- static [entityKind] = "NodeSQLiteDatabase";
30020
- };
30021
- function construct(client2, config2 = {}) {
30022
- const dialect = new SQLiteDialect({ useJitMappers: jitCompatCheck(config2.jit) });
30023
- let logger;
30024
- if (config2.logger === true) logger = new DefaultLogger();
30025
- else if (config2.logger !== false) logger = config2.logger;
30026
- const relations = config2.relations ?? {};
30027
- const db = new NodeSQLiteDatabase("sync", dialect, new NodeSQLiteSession(client2, dialect, relations, { logger }), relations);
30028
- db.$client = client2;
30029
- return db;
30030
- }
30031
- function drizzle(...params) {
30032
- if (params[0] === void 0 || typeof params[0] === "string") return construct(params[0] === void 0 ? new DatabaseSync(":memory:") : new DatabaseSync(params[0]), params[1]);
30033
- const { connection, client: client2, ...config2 } = params[0];
30034
- if (client2) return construct(client2, config2);
30035
- if (typeof connection === "object") {
30036
- const { path: path2, ...options } = connection;
30037
- return construct(new DatabaseSync(path2 ?? ":memory:", options), config2);
30038
- }
30039
- return construct(new DatabaseSync(connection ?? ":memory:"), config2);
30040
- }
30041
- (function(_drizzle) {
30042
- function mock(config2) {
30043
- return construct({}, config2);
30044
- }
30045
- _drizzle.mock = mock;
30046
- })(drizzle || (drizzle = {}));
30047
-
30048
- // src/generated/acp-session-store-migrations.ts
30049
- var acpSessionStoreMigrations = [
30050
- {
30051
- "name": "0000_slimy_captain_midlands.sql",
30052
- "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"
30053
- },
30054
- {
30055
- "name": "0001_regular_ultimates.sql",
30056
- "sql": "ALTER TABLE `acp_session` ADD `last_terminal_command_id` text;"
30057
- },
30058
- {
30059
- "name": "0002_equal_black_queen.sql",
30060
- "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`);"
30061
- },
30062
- {
30063
- "name": "0003_silky_ravenous.sql",
30064
- "sql": "DROP TABLE `session_event_v2`;"
30065
- },
30066
- {
30067
- "name": "0004_special_mathemanic.sql",
30068
- "sql": "DROP TABLE `deleted_acp_session`;--> statement-breakpoint\nALTER TABLE `acp_session` DROP COLUMN `last_terminal_command_id`;"
30069
- }
30070
- ];
30071
-
30072
30028
  // src/schema/acp-session-store/acp-session.ts
30073
30029
  var acpSession = sqliteTable("acp_session", {
30074
30030
  sessionId: text("session_id").primaryKey(),
@@ -30081,6 +30037,216 @@ var acpSession = sqliteTable("acp_session", {
30081
30037
  updatedAt: text("updated_at").notNull()
30082
30038
  });
30083
30039
 
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
+ };
30249
+
30084
30250
  // src/acp/session-store.ts
30085
30251
  var AcpStoredSession = class {
30086
30252
  additionalDirectories;
@@ -30116,9 +30282,14 @@ var FoundAcpStoredSession = class extends AcpStoredSessionLookup {
30116
30282
  }
30117
30283
  };
30118
30284
  var MemoryAcpSessionStore = class {
30285
+ eventsV2;
30119
30286
  #sessions = /* @__PURE__ */ new Map();
30287
+ constructor(eventsV2 = new MemoryAcpSessionEventStoreV2(randomUUID())) {
30288
+ this.eventsV2 = eventsV2;
30289
+ }
30120
30290
  close = () => {
30121
30291
  this.#sessions.clear();
30292
+ this.eventsV2.close();
30122
30293
  };
30123
30294
  findNative = (agentId, nativeSessionId) => [...this.#sessions.values()].filter(
30124
30295
  (session) => session.agentId === agentId && session.nativeSessionId === nativeSessionId
@@ -30130,6 +30301,7 @@ var MemoryAcpSessionStore = class {
30130
30301
  };
30131
30302
  remove = (sessionId) => {
30132
30303
  this.#sessions.delete(sessionId);
30304
+ this.eventsV2.remove(sessionId);
30133
30305
  };
30134
30306
  write = (session) => {
30135
30307
  this.#sessions.set(session.sessionId, session);
@@ -30161,39 +30333,20 @@ function decodeStoredSession(value) {
30161
30333
  );
30162
30334
  }
30163
30335
  var SqliteAcpSessionStore = class {
30336
+ eventsV2;
30164
30337
  #database;
30165
- #sqliteDatabase;
30166
- constructor(path2) {
30167
- mkdirSync(dirname(path2), { mode: 448, recursive: true });
30168
- this.#sqliteDatabase = new DatabaseSync2(path2);
30169
- chmodSync(path2, 384);
30170
- this.#migrate();
30171
- 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;
30172
30343
  }
30173
- #migrate = () => {
30174
- const version2 = external_exports.object({ user_version: external_exports.number().int().nonnegative() }).parse(this.#sqliteDatabase.prepare("PRAGMA user_version").get()).user_version;
30175
- if (version2 > acpSessionStoreMigrations.length) {
30176
- this.#sqliteDatabase.close();
30177
- throw new Error("The ACP Session database was created by a newer Mobius version");
30178
- }
30179
- for (let index = version2; index < acpSessionStoreMigrations.length; index += 1) {
30180
- const migration = acpSessionStoreMigrations[index];
30181
- if (migration === void 0) {
30182
- throw new Error("The ACP Session migration is unavailable");
30183
- }
30184
- this.#sqliteDatabase.exec("BEGIN IMMEDIATE");
30185
- try {
30186
- this.#sqliteDatabase.exec(migration.sql);
30187
- this.#sqliteDatabase.exec(`PRAGMA user_version = ${index + 1}`);
30188
- this.#sqliteDatabase.exec("COMMIT");
30189
- } catch (error62) {
30190
- this.#sqliteDatabase.exec("ROLLBACK");
30191
- throw error62;
30192
- }
30193
- }
30194
- };
30195
30344
  close = () => {
30196
- this.#sqliteDatabase.close();
30345
+ try {
30346
+ this.#localDatabase.close();
30347
+ } finally {
30348
+ this.eventsV2.close();
30349
+ }
30197
30350
  };
30198
30351
  findNative = (agentId, nativeSessionId) => this.#database.select().from(acpSession).where(and(eq(acpSession.agentId, agentId), eq(acpSession.nativeSessionId, nativeSessionId))).all().map(decodeStoredSession);
30199
30352
  list = () => this.#database.select().from(acpSession).orderBy(desc(acpSession.updatedAt)).all().map(decodeStoredSession);
@@ -30203,6 +30356,7 @@ var SqliteAcpSessionStore = class {
30203
30356
  };
30204
30357
  remove = (sessionId) => {
30205
30358
  this.#database.delete(acpSession).where(eq(acpSession.sessionId, sessionId)).run();
30359
+ this.eventsV2.remove(sessionId);
30206
30360
  };
30207
30361
  write = (session) => {
30208
30362
  const value = {
@@ -30228,7 +30382,7 @@ var RetryableAcpInitializationError = class extends AcpExecutionError {
30228
30382
  }
30229
30383
  };
30230
30384
  function arraysEqual(left, right) {
30231
- 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]);
30232
30386
  }
30233
30387
  function recordsEqual(left, right) {
30234
30388
  const leftEntries = Object.entries(left);
@@ -30391,12 +30545,17 @@ var AgentSession = class _AgentSession {
30391
30545
  );
30392
30546
  }
30393
30547
  const history = await this.#completedHistory(signal, "ACP agent exited while loading history");
30394
- return history.eventPage(eventLimit, cursor, this.#turnHistory);
30548
+ return history.eventPage(eventLimit, cursor);
30395
30549
  };
30396
30550
  async #completedHistory(signal, exitMessage) {
30397
30551
  if (!this.#prompted && this.#nativeHistoryOwnership.kind === "fresh-session") {
30398
30552
  if (this.#sessionLoad.kind === "not-requested") {
30399
- 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
+ };
30400
30559
  }
30401
30560
  if (this.#sessionLoad.kind === "loaded") {
30402
30561
  return this.#sessionLoad.history;
@@ -30411,7 +30570,8 @@ var AgentSession = class _AgentSession {
30411
30570
  if (this.#sessionLoad.kind === "capturing") {
30412
30571
  return await waitForSharedOperation(this.#sessionLoad.completion, signal);
30413
30572
  }
30414
- const history = new AcpHistoryReplay();
30573
+ this.#store.eventsV2.reset(this.#mobiusSessionId);
30574
+ const history = new AcpHistoryReplay(this.#store.eventsV2, this.#mobiusSessionId);
30415
30575
  const completion = Promise.resolve().then(async () => {
30416
30576
  try {
30417
30577
  const response = await this.race(
@@ -30886,7 +31046,7 @@ var AgentSession = class _AgentSession {
30886
31046
  this.prepareAgentContent
30887
31047
  );
30888
31048
  this.#turn = running;
30889
- this.#turnHistory = completedHistory === null ? null : new AcpHistoryReplay();
31049
+ this.#turnHistory = completedHistory === null ? null : new AcpHistoryReplay(this.#store.eventsV2, this.#mobiusSessionId);
30890
31050
  const lifecycleV2 = options.lifecycleV2;
30891
31051
  if (lifecycleV2 !== void 0) {
30892
31052
  await this.#recordLifecycleEventV2({
@@ -31099,7 +31259,7 @@ var AgentSession = class _AgentSession {
31099
31259
  if (event.type !== "lifecycle-metadata" || this.#sessionLoad.kind !== "loaded") {
31100
31260
  return;
31101
31261
  }
31102
- 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);
31103
31263
  await this.#getObserver().onSessionEventV2?.(this.#mobiusSessionId, event, position);
31104
31264
  };
31105
31265
  selectNativeSession = (sessionId) => {
@@ -31120,13 +31280,8 @@ var AgentSession = class _AgentSession {
31120
31280
  } else {
31121
31281
  const onSessionEventV2 = this.#getObserver().onSessionEventV2;
31122
31282
  if (this.#turnHistory !== null) {
31123
- const completedEventCount = this.#sessionLoad.kind === "loaded" ? this.#sessionLoad.history.eventCount() : 0;
31124
- await this.#turnHistory.record(update, rawUpdate, async (turnPosition) => {
31125
- await onSessionEventV2?.(
31126
- this.#mobiusSessionId,
31127
- { payload: rawUpdate, type: "acp" },
31128
- completedEventCount + turnPosition
31129
- );
31283
+ await this.#turnHistory.record(update, rawUpdate, async (position) => {
31284
+ await onSessionEventV2?.(this.#mobiusSessionId, { payload: rawUpdate, type: "acp" }, position);
31130
31285
  });
31131
31286
  } else if (this.#sessionLoad.kind === "loaded") {
31132
31287
  await this.#sessionLoad.history.record(update, rawUpdate, async (position) => {
@@ -31769,9 +31924,9 @@ var AcpContentExternalizer = class {
31769
31924
  };
31770
31925
 
31771
31926
  // src/external-content/local-external-content-store.ts
31772
- import { createHash, randomUUID } from "node:crypto";
31927
+ import { createHash, randomUUID as randomUUID2 } from "node:crypto";
31773
31928
  import { lstat, mkdir, readdir as readdir2, realpath as realpath3, rename, rm, stat as stat3, utimes, writeFile } from "node:fs/promises";
31774
- import { dirname as dirname2, join as join4 } from "node:path";
31929
+ import { dirname, join as join4 } from "node:path";
31775
31930
  var contentRequest = /^mobius-content:(image|audio|resource):([a-f0-9]{64})$/u;
31776
31931
  var CONTENT_LIFETIME_MILLISECONDS = 24 * 60 * 60 * 1e3;
31777
31932
  var metadataSchema2 = external_exports.strictObject({
@@ -31790,7 +31945,7 @@ var UnretainedExternalContentStore = class {
31790
31945
  };
31791
31946
  };
31792
31947
  async function atomicWrite(path2, bytes, signal) {
31793
- const temporary = `${path2}.${randomUUID()}.tmp`;
31948
+ const temporary = `${path2}.${randomUUID2()}.tmp`;
31794
31949
  try {
31795
31950
  await writeFile(temporary, bytes, { mode: 384, signal });
31796
31951
  signal.throwIfAborted();
@@ -31807,7 +31962,7 @@ var LocalExternalContentStore = class {
31807
31962
  #expirationTimer;
31808
31963
  #cleanup = Promise.resolve();
31809
31964
  constructor(stateDirectory) {
31810
- this.#root = join4(stateDirectory, "tmp", "session-content", randomUUID());
31965
+ this.#root = join4(stateDirectory, "tmp", "session-content", randomUUID2());
31811
31966
  this.#expirationTimer = setInterval(() => {
31812
31967
  void this.#expire().catch(() => void 0);
31813
31968
  }, 6e4);
@@ -31818,11 +31973,11 @@ var LocalExternalContentStore = class {
31818
31973
  await mkdir(this.#root, { mode: 448, recursive: true });
31819
31974
  const now = /* @__PURE__ */ new Date();
31820
31975
  await utimes(this.#root, now, now);
31821
- for (const directory of await readdir2(dirname2(this.#root), { withFileTypes: true })) {
31976
+ for (const directory of await readdir2(dirname(this.#root), { withFileTypes: true })) {
31822
31977
  if (!directory.isDirectory() || !/^[a-f0-9-]{36}$/u.test(directory.name)) {
31823
31978
  continue;
31824
31979
  }
31825
- const path2 = join4(dirname2(this.#root), directory.name);
31980
+ const path2 = join4(dirname(this.#root), directory.name);
31826
31981
  if (path2 === this.#root) {
31827
31982
  continue;
31828
31983
  }
@@ -31908,12 +32063,12 @@ var LocalExternalContentStore = class {
31908
32063
  }
31909
32064
  try {
31910
32065
  const [resolvedDirectory, resolvedPath, file2] = await Promise.all([
31911
- realpath3(dirname2(entry.path)),
32066
+ realpath3(dirname(entry.path)),
31912
32067
  realpath3(entry.path),
31913
32068
  lstat(entry.path)
31914
32069
  ]);
31915
32070
  signal.throwIfAborted();
31916
- if (!file2.isFile() || file2.isSymbolicLink() || dirname2(resolvedPath) !== resolvedDirectory) {
32071
+ if (!file2.isFile() || file2.isSymbolicLink() || dirname(resolvedPath) !== resolvedDirectory) {
31917
32072
  return null;
31918
32073
  }
31919
32074
  return { mediaType: entry.mediaType, name: entry.name, path: resolvedPath };
@@ -31990,9 +32145,9 @@ var AcpProcessCapacityLock = class {
31990
32145
  return await waiter.completion.promise;
31991
32146
  } finally {
31992
32147
  signal.removeEventListener("abort", waiter.cancel);
31993
- const index = this.#waiters.indexOf(waiter);
31994
- if (index >= 0) {
31995
- this.#waiters.splice(index, 1);
32148
+ const index2 = this.#waiters.indexOf(waiter);
32149
+ if (index2 >= 0) {
32150
+ this.#waiters.splice(index2, 1);
31996
32151
  }
31997
32152
  }
31998
32153
  };
@@ -32979,7 +33134,7 @@ var LocalAgentInventory = class {
32979
33134
 
32980
33135
  // src/agent-installation/managed-npm-package.ts
32981
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";
32982
- 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";
32983
33138
  var INSTALL_TIMEOUT_MILLISECONDS = 5 * 60 * 1e3;
32984
33139
  var PACKAGE_METADATA_LIMIT_BYTES = 64 * 1024;
32985
33140
  var PACKAGE_LOCK_LIMIT_BYTES = 8 * 1024 * 1024;
@@ -33209,7 +33364,7 @@ var ManagedNpmPackageInstaller = class {
33209
33364
  throw error62;
33210
33365
  }
33211
33366
  }
33212
- const parent = dirname3(root);
33367
+ const parent = dirname2(root);
33213
33368
  await mkdir2(parent, { mode: 448, recursive: true });
33214
33369
  const staging = await mkdtemp(join5(parent, `.${definition.version}.staging-`));
33215
33370
  try {
@@ -33244,7 +33399,7 @@ var ManagedNpmPackageInstaller = class {
33244
33399
  NPM_CONFIG_IGNORE_SCRIPTS: "true",
33245
33400
  NPM_CONFIG_PACKAGE_LOCK: "true",
33246
33401
  NPM_CONFIG_REGISTRY: "https://registry.npmjs.org/",
33247
- PATH: `${dirname3(process.execPath)}${delimiter}/usr/bin${delimiter}/bin`
33402
+ PATH: `${dirname2(process.execPath)}${delimiter}/usr/bin${delimiter}/bin`
33248
33403
  };
33249
33404
  if (definition.includeOptionalDependencies) {
33250
33405
  installEnvironment["NPM_CONFIG_INCLUDE"] = "optional";
@@ -35729,7 +35884,7 @@ import { join as join11 } from "node:path";
35729
35884
  import { createHash as createHash2 } from "node:crypto";
35730
35885
  import { createReadStream } from "node:fs";
35731
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";
35732
- 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";
35733
35888
 
35734
35889
  // src/agent-installation/verified-download.ts
35735
35890
  import { fetch } from "undici";
@@ -36588,9 +36743,9 @@ function comparePrerelease(left, right) {
36588
36743
  if (left.length === 0 || right.length === 0) {
36589
36744
  return left.length === right.length ? 0 : left.length === 0 ? 1 : -1;
36590
36745
  }
36591
- for (let index = 0; index < Math.max(left.length, right.length); index += 1) {
36592
- const leftPart = left[index];
36593
- 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];
36594
36749
  if (leftPart === void 0 || rightPart === void 0) {
36595
36750
  return leftPart === rightPart ? 0 : leftPart === void 0 ? -1 : 1;
36596
36751
  }
@@ -36615,8 +36770,8 @@ function compareAgentVersions(left, right) {
36615
36770
  if (parsedLeft === null || parsedRight === null) {
36616
36771
  return null;
36617
36772
  }
36618
- for (let index = 0; index < Math.max(parsedLeft.core.length, parsedRight.core.length); index += 1) {
36619
- 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);
36620
36775
  if (difference !== 0) {
36621
36776
  return Math.sign(difference);
36622
36777
  }
@@ -37037,9 +37192,9 @@ async function discoverLocalAgentInventory(options) {
37037
37192
  }
37038
37193
 
37039
37194
  // src/storage/runtime-installation-store.ts
37040
- import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
37195
+ import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
37041
37196
  import { mkdir as mkdir5, open as open5, readdir as readdir3, rename as rename4, unlink, writeFile as writeFile4 } from "node:fs/promises";
37042
- 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";
37043
37198
  var APPLICATION_ID_PATTERN = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+){1,31}$/;
37044
37199
  var CONNECTION_ID_PATTERN = /^mcn_[a-f0-9]{32}$/;
37045
37200
  var INSTALLATION_ID_PATTERN = /^min_[a-f0-9]{32}$/;
@@ -37167,10 +37322,10 @@ function parseRelayOrigin(value) {
37167
37322
  return origin;
37168
37323
  }
37169
37324
  function connectionId() {
37170
- return `mcn_${randomUUID2().replaceAll("-", "")}`;
37325
+ return `mcn_${randomUUID3().replaceAll("-", "")}`;
37171
37326
  }
37172
37327
  function installationId() {
37173
- return `min_${randomUUID2().replaceAll("-", "")}`;
37328
+ return `min_${randomUUID3().replaceAll("-", "")}`;
37174
37329
  }
37175
37330
  function channelIndexFileName(channelId) {
37176
37331
  return `mci_${createHash3("sha256").update(channelId).digest("hex")}.json`;
@@ -37281,8 +37436,8 @@ async function readJsonFile(path2, signal, missingCode) {
37281
37436
  }
37282
37437
  async function writeJsonAtomically(path2, value, signal) {
37283
37438
  signal.throwIfAborted();
37284
- const directory = dirname5(path2);
37285
- const temporaryPath = join16(directory, `.${randomUUID2()}.tmp`);
37439
+ const directory = dirname4(path2);
37440
+ const temporaryPath = join16(directory, `.${randomUUID3()}.tmp`);
37286
37441
  try {
37287
37442
  await mkdir5(directory, { mode: 448, recursive: true });
37288
37443
  signal.throwIfAborted();
@@ -37359,16 +37514,16 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
37359
37514
  };
37360
37515
  #readConnectionForChannel = async (channelId, signal) => {
37361
37516
  const normalizedChannelId = validateIdentifier(channelId, "invalid_channel_id");
37362
- const index = decodeChannelIndex(
37517
+ const index2 = decodeChannelIndex(
37363
37518
  await readJsonFile(this.channelIndexPath(normalizedChannelId), signal, "connection_not_found")
37364
37519
  );
37365
- 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) {
37366
37521
  throw new RuntimeInstallationStoreError(
37367
37522
  "connection_owner_mismatch",
37368
37523
  "The saved Runtime connection belongs to another installation"
37369
37524
  );
37370
37525
  }
37371
- return await this.readConnection(index.connectionId, signal);
37526
+ return await this.readConnection(index2.connectionId, signal);
37372
37527
  };
37373
37528
  saveConnection = async (input2, signal) => {
37374
37529
  const stored = new VerifiedRuntimeConnection(
@@ -37563,16 +37718,16 @@ function hasExactKeys2(value, expectedKeys) {
37563
37718
  }
37564
37719
  function readSingleOption(arguments_, option) {
37565
37720
  const values = [];
37566
- for (let index = 0; index < arguments_.length; index += 1) {
37567
- if (arguments_[index] !== option) {
37721
+ for (let index2 = 0; index2 < arguments_.length; index2 += 1) {
37722
+ if (arguments_[index2] !== option) {
37568
37723
  continue;
37569
37724
  }
37570
- const value = arguments_[index + 1];
37725
+ const value = arguments_[index2 + 1];
37571
37726
  if (value === void 0 || value.startsWith("--")) {
37572
37727
  throw new PairingClientError("invalid_arguments", `${option} requires a value`);
37573
37728
  }
37574
37729
  values.push(value);
37575
- index += 1;
37730
+ index2 += 1;
37576
37731
  }
37577
37732
  if (values.length !== 1) {
37578
37733
  throw new PairingClientError("invalid_arguments", `${option} must be provided exactly once`);
@@ -37580,8 +37735,8 @@ function readSingleOption(arguments_, option) {
37580
37735
  return values[0] ?? "";
37581
37736
  }
37582
37737
  function assertKnownArguments(arguments_) {
37583
- for (let index = 0; index < arguments_.length; index += 2) {
37584
- const option = arguments_[index];
37738
+ for (let index2 = 0; index2 < arguments_.length; index2 += 2) {
37739
+ const option = arguments_[index2];
37585
37740
  if (option !== "--url" && option !== "--code" && option !== "--pairing" && option !== "--workspace") {
37586
37741
  throw new PairingClientError("invalid_arguments", `Unknown pairing option: ${option ?? "missing option"}`);
37587
37742
  }
@@ -37872,7 +38027,7 @@ function isRuntimeRelayRevocation(closeCode, closeReason) {
37872
38027
  }
37873
38028
 
37874
38029
  // src/run-daemon.ts
37875
- import { createHash as createHash8, randomUUID as randomUUID9 } from "node:crypto";
38030
+ import { createHash as createHash8, randomUUID as randomUUID10 } from "node:crypto";
37876
38031
  import { join as join19 } from "node:path";
37877
38032
  import { styleText } from "node:util";
37878
38033
 
@@ -38451,7 +38606,7 @@ var FixedInstallationExecutor = class {
38451
38606
  // src/authorization/workspace-directory.ts
38452
38607
  import { readdir as readdir4, realpath as realpath9, stat as stat8 } from "node:fs/promises";
38453
38608
  import { homedir as homedir2 } from "node:os";
38454
- 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";
38455
38610
  var WorkspaceDirectoryListing = class {
38456
38611
  directoryId;
38457
38612
  directoryLabel;
@@ -38579,7 +38734,7 @@ var WorkspaceDirectoryService = class {
38579
38734
  }
38580
38735
  }
38581
38736
  entries.sort((a, b) => a.name.localeCompare(b.name));
38582
- const parent = dirname6(target);
38737
+ const parent = dirname5(target);
38583
38738
  return new WorkspaceDirectoryListing(
38584
38739
  id,
38585
38740
  this.label(target),
@@ -38604,7 +38759,7 @@ var WorkspaceDirectoryService = class {
38604
38759
  };
38605
38760
 
38606
38761
  // src/daemon-diagnostic-log.ts
38607
- 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";
38608
38763
  import { join as join18 } from "node:path";
38609
38764
  var MAXIMUM_DAEMON_LOG_BYTES = 1 * 1024 * 1024;
38610
38765
  var DaemonDiagnosticLog = class {
@@ -38620,7 +38775,7 @@ var DaemonDiagnosticLog = class {
38620
38775
  const encoded = `${diagnostic.replace(/[\r\n]+/gu, " ").trim()}
38621
38776
  `;
38622
38777
  const encodedBytes = Buffer.byteLength(encoded);
38623
- mkdirSync2(this.#directory, { mode: 448, recursive: true });
38778
+ mkdirSync(this.#directory, { mode: 448, recursive: true });
38624
38779
  let existingBytes = 0;
38625
38780
  try {
38626
38781
  existingBytes = statSync3(this.#path).size;
@@ -39085,7 +39240,7 @@ var DaemonInstallationObserver = class {
39085
39240
  };
39086
39241
 
39087
39242
  // src/daemon-active-turn.ts
39088
- import { randomUUID as randomUUID3 } from "node:crypto";
39243
+ import { randomUUID as randomUUID4 } from "node:crypto";
39089
39244
  function activeMessageCharacters(message) {
39090
39245
  return message.text.length + (message.role === "assistant" ? JSON.stringify(message.activities).length + JSON.stringify(message.content).length : 0);
39091
39246
  }
@@ -39093,8 +39248,8 @@ var ACTIVE_TURN_TEXT_CHUNK_LIMIT = Math.floor(SESSION_HISTORY_CHARACTER_LIMIT /
39093
39248
  function boundedRecoveryMessages(messages) {
39094
39249
  const selected = [];
39095
39250
  let remainingCharacters = SESSION_HISTORY_CHARACTER_LIMIT;
39096
- for (let index = messages.length - 1; index >= 0 && selected.length < SESSION_HISTORY_MESSAGE_LIMIT; index -= 1) {
39097
- 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];
39098
39253
  if (message === void 0) {
39099
39254
  break;
39100
39255
  }
@@ -39119,7 +39274,7 @@ var ActiveDaemonTurn = class {
39119
39274
  #timeline;
39120
39275
  #sequence = 0;
39121
39276
  #interaction = null;
39122
- #epoch = decodeIdentifier(randomUUID3());
39277
+ #epoch = decodeIdentifier(randomUUID4());
39123
39278
  constructor(command, attemptId) {
39124
39279
  this.attemptId = attemptId;
39125
39280
  this.command = command;
@@ -39181,7 +39336,7 @@ var ActiveDaemonTurn = class {
39181
39336
  if (!this.#activities.has(event.activityId)) {
39182
39337
  this.#timeline = [
39183
39338
  ...this.#timeline,
39184
- { activityId: event.activityId, id: decodeIdentifier(randomUUID3()), kind: "activity" }
39339
+ { activityId: event.activityId, id: decodeIdentifier(randomUUID4()), kind: "activity" }
39185
39340
  ];
39186
39341
  }
39187
39342
  this.#activities.set(event.activityId, {
@@ -39202,7 +39357,7 @@ var ActiveDaemonTurn = class {
39202
39357
  if (previous === void 0) {
39203
39358
  this.#timeline = [
39204
39359
  ...this.#timeline,
39205
- { activityId: event.activityId, id: decodeIdentifier(randomUUID3()), kind: "activity" }
39360
+ { activityId: event.activityId, id: decodeIdentifier(randomUUID4()), kind: "activity" }
39206
39361
  ];
39207
39362
  }
39208
39363
  this.#activities.set(event.activityId, {
@@ -39227,7 +39382,7 @@ var ActiveDaemonTurn = class {
39227
39382
  ...this.#timeline,
39228
39383
  {
39229
39384
  content: /* @__PURE__ */ new Map([[event.contentId, event.content]]),
39230
- id: decodeIdentifier(randomUUID3()),
39385
+ id: decodeIdentifier(randomUUID4()),
39231
39386
  kind: "message",
39232
39387
  sourceMessageId: event.messageId,
39233
39388
  text: ""
@@ -39235,7 +39390,7 @@ var ActiveDaemonTurn = class {
39235
39390
  ];
39236
39391
  } else {
39237
39392
  this.#timeline = this.#timeline.map(
39238
- (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
39239
39394
  );
39240
39395
  }
39241
39396
  } else if (event.kind === SESSION_PERMISSION_REQUESTED_KIND || event.kind === SESSION_ELICITATION_REQUESTED_KIND) {
@@ -39267,7 +39422,7 @@ var ActiveDaemonTurn = class {
39267
39422
  ...this.#timeline,
39268
39423
  {
39269
39424
  content: /* @__PURE__ */ new Map(),
39270
- id: decodeIdentifier(randomUUID3()),
39425
+ id: decodeIdentifier(randomUUID4()),
39271
39426
  kind: "message",
39272
39427
  sourceMessageId: messageId,
39273
39428
  text: remaining.slice(0, ACTIVE_TURN_TEXT_CHUNK_LIMIT)
@@ -39538,6 +39693,202 @@ var DaemonTurnRegistry = class {
39538
39693
  };
39539
39694
  };
39540
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
+
39541
39892
  // src/native-sessions/codex-history.ts
39542
39893
  import { spawn as spawn5 } from "node:child_process";
39543
39894
  var responseSchema = external_exports.union([
@@ -40242,7 +40593,7 @@ var readCodexFullHistory = async (agent, cwd, nativeSessionId, signal, nativeTur
40242
40593
  });
40243
40594
 
40244
40595
  // src/native-sessions/service.ts
40245
- import { randomUUID as randomUUID4 } from "node:crypto";
40596
+ import { randomUUID as randomUUID5 } from "node:crypto";
40246
40597
  var NativeSessionService = class {
40247
40598
  #entries = /* @__PURE__ */ new Map();
40248
40599
  #cursors = /* @__PURE__ */ new Map();
@@ -40301,7 +40652,7 @@ var NativeSessionService = class {
40301
40652
  if (authorized === null) {
40302
40653
  return null;
40303
40654
  }
40304
- const entryId = decodeIdentifier(randomUUID4());
40655
+ const entryId = decodeIdentifier(randomUUID5());
40305
40656
  if (this.#entries.size >= 5e3) {
40306
40657
  this.#entries.clear();
40307
40658
  }
@@ -40357,7 +40708,7 @@ var NativeSessionService = class {
40357
40708
  "invalid_native_session_response"
40358
40709
  );
40359
40710
  }
40360
- nextCursor = decodeIdentifier(randomUUID4());
40711
+ nextCursor = decodeIdentifier(randomUUID5());
40361
40712
  if (this.#cursors.size >= 500) {
40362
40713
  this.#cursors.clear();
40363
40714
  }
@@ -40535,7 +40886,7 @@ var NativeSessionService = class {
40535
40886
  resolveTarget = async (command, options, selected) => {
40536
40887
  let cursor = null;
40537
40888
  const visited = /* @__PURE__ */ new Set();
40538
- for (let index = 0; index < 100; index += 1) {
40889
+ for (let index2 = 0; index2 < 100; index2 += 1) {
40539
40890
  const page = await this.#sessions.listNativeSessions(options, cursor);
40540
40891
  const info = page.sessions.find((entry) => entry.sessionId === selected.nativeSessionId);
40541
40892
  if (info !== void 0) {
@@ -40543,7 +40894,7 @@ var NativeSessionService = class {
40543
40894
  if (target === null) {
40544
40895
  throw new LocalAuthorizationError("The selected native session is not authorized");
40545
40896
  }
40546
- 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])) {
40547
40898
  throw new AcpExecutionError(
40548
40899
  "This session's directory changed. Refresh the list before continuing.",
40549
40900
  {},
@@ -40582,7 +40933,7 @@ var NativeSessionService = class {
40582
40933
  };
40583
40934
 
40584
40935
  // src/relay-connection/daemon-operation-state.ts
40585
- import { createHash as createHash5, randomUUID as randomUUID5 } from "node:crypto";
40936
+ import { createHash as createHash5, randomUUID as randomUUID6 } from "node:crypto";
40586
40937
  var MAX_TERMINAL_RECEIPTS = 1024;
40587
40938
  function isTerminal(state) {
40588
40939
  return state === "succeeded" || state === "failed" || state === "cancelled";
@@ -40599,7 +40950,7 @@ var DaemonOperationState = class {
40599
40950
  }
40600
40951
  return { attemptId: existing.attemptId, commandId, kind: "duplicate", state: existing.state };
40601
40952
  }
40602
- const attemptId = randomUUID5();
40953
+ const attemptId = randomUUID6();
40603
40954
  this.#executions.set(commandId, { attemptId, commandHash, sessionId, state: "dispatching" });
40604
40955
  return { attemptId, commandId, kind: "accepted", state: "dispatching" };
40605
40956
  };
@@ -41563,7 +41914,7 @@ async function executeSessionLiveHistoryV2PageLoad(socket, command, config2, dir
41563
41914
  const replay = await sessions.loadSessionEventsV2(loadOptions, command.eventLimit, command.cursor);
41564
41915
  signal.throwIfAborted();
41565
41916
  const events = replay.events.map(
41566
- (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")
41567
41918
  );
41568
41919
  const tailCursor = events.at(-1)?.eventId ?? "";
41569
41920
  audit.record({
@@ -41614,7 +41965,7 @@ async function executeSessionLiveHistoryV2PageLoad(socket, command, config2, dir
41614
41965
  }
41615
41966
 
41616
41967
  // src/acp/session-config/apply-session-configuration.ts
41617
- import { randomUUID as randomUUID6 } from "node:crypto";
41968
+ import { randomUUID as randomUUID7 } from "node:crypto";
41618
41969
  function invalidSessionConfiguration(message) {
41619
41970
  return new AcpExecutionError(message, {}, "invalid_session_configuration");
41620
41971
  }
@@ -41755,7 +42106,7 @@ async function applySessionConfigurationSelection(sessions, audit, options, sele
41755
42106
  booleanValue: selection.booleanValue,
41756
42107
  configId: selection.configId,
41757
42108
  cwd,
41758
- requestId: `cfg_${randomUUID6()}`,
42109
+ requestId: `cfg_${randomUUID7()}`,
41759
42110
  sessionId,
41760
42111
  signal,
41761
42112
  value: selection.value,
@@ -42805,7 +43156,7 @@ function connectRelay(url2, signal) {
42805
43156
  }
42806
43157
 
42807
43158
  // src/relay-connection/liveness.ts
42808
- import { randomUUID as randomUUID7 } from "node:crypto";
43159
+ import { randomUUID as randomUUID8 } from "node:crypto";
42809
43160
  var HEARTBEAT_ACK_TIMEOUT_MILLISECONDS = 1e4;
42810
43161
  var HEARTBEAT_INTERVAL_MILLISECONDS = 2e4;
42811
43162
  var RelayLivenessState = class {
@@ -42894,7 +43245,7 @@ var RelayConnectionLiveness = class {
42894
43245
  }
42895
43246
  throw new Error("Heartbeat was scheduled in an invalid state");
42896
43247
  }
42897
- const heartbeatId = randomUUID7();
43248
+ const heartbeatId = randomUUID8();
42898
43249
  this.#state = new AwaitingHeartbeatAckState(
42899
43250
  heartbeatId,
42900
43251
  this.#timer.schedule(this.#handleTimeout, HEARTBEAT_ACK_TIMEOUT_MILLISECONDS)
@@ -43186,7 +43537,7 @@ var SystemDaemonTimer = class {
43186
43537
  var systemDaemonTimer = new SystemDaemonTimer();
43187
43538
 
43188
43539
  // src/session-event-log-v2.ts
43189
- import { createHash as createHash7, randomUUID as randomUUID8 } from "node:crypto";
43540
+ import { createHash as createHash7, randomUUID as randomUUID9 } from "node:crypto";
43190
43541
  function promptContent(command) {
43191
43542
  const content = [];
43192
43543
  if (command.prompt.length > 0) {
@@ -43210,7 +43561,7 @@ function promptContent(command) {
43210
43561
  }
43211
43562
  return content;
43212
43563
  }
43213
- function sessionEventV2(daemonGenerationId, sessionId, position, event, recordedAt) {
43564
+ function sessionEventV22(daemonGenerationId, sessionId, position, event, recordedAt) {
43214
43565
  const sessionPrefix = createHash7("sha256").update(sessionId).digest("hex").slice(0, 16);
43215
43566
  return {
43216
43567
  eventId: `event-${daemonGenerationId}-${sessionPrefix}-${position.toString().padStart(16, "0")}`,
@@ -43222,11 +43573,12 @@ function sessionEventV2(daemonGenerationId, sessionId, position, event, recorded
43222
43573
  };
43223
43574
  }
43224
43575
  var DaemonSessionEventLogV2 = class {
43225
- daemonGenerationId = randomUUID8();
43576
+ daemonGenerationId;
43226
43577
  #publisher;
43227
43578
  #queued = /* @__PURE__ */ new Map();
43228
- constructor(publisher) {
43579
+ constructor(publisher, daemonGenerationId = randomUUID9()) {
43229
43580
  this.#publisher = publisher;
43581
+ this.daemonGenerationId = daemonGenerationId;
43230
43582
  }
43231
43583
  requested = (command) => {
43232
43584
  this.#queued.set(command.commandId, {
@@ -43246,7 +43598,7 @@ var DaemonSessionEventLogV2 = class {
43246
43598
  record = (sessionId, event, position) => {
43247
43599
  this.#publisher.publishV2(this.event(sessionId, position, event, (/* @__PURE__ */ new Date()).toISOString()));
43248
43600
  };
43249
- 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);
43250
43602
  queueChanged = (_sessionId) => void 0;
43251
43603
  completed = (sessionId, commandId, _stopReason) => {
43252
43604
  const request = this.#queued.get(commandId);
@@ -43313,7 +43665,7 @@ async function installDetectedAgentIntegrations(config2, installations, signal)
43313
43665
  {
43314
43666
  agentId: agent.id,
43315
43667
  kind: AGENT_INSTALL_REQUEST_KIND,
43316
- requestId: `automatic-integration-${randomUUID9()}`
43668
+ requestId: `automatic-integration-${randomUUID10()}`
43317
43669
  },
43318
43670
  signal
43319
43671
  );
@@ -43331,13 +43683,24 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
43331
43683
  publishCatalog: async (installationSignal) => await publishAgentCatalog(config2, installationSignal),
43332
43684
  stateDirectory
43333
43685
  });
43334
- const sessionStore = new SqliteAcpSessionStore(
43335
- join19(stateDirectory, "sessions", `${createHash8("sha256").update(config2.channelId).digest("hex")}.sqlite`)
43336
- );
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);
43337
43700
  await using externalContent = new LocalExternalContentStore(stateDirectory);
43338
43701
  const operations = new DaemonOperationState();
43339
43702
  const publisher = new DaemonSessionEventPublisher();
43340
- const eventLogV2 = new DaemonSessionEventLogV2(publisher);
43703
+ const eventLogV2 = new DaemonSessionEventLogV2(publisher, daemonGenerationId);
43341
43704
  const activeTurns = new DaemonTurnRegistry(operations);
43342
43705
  const recordSessionEvent = (sessionId, event) => {
43343
43706
  publisher.publish(sessionId, activeTurns.recordEvent(event));
@@ -43383,7 +43746,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
43383
43746
  options2.signal
43384
43747
  );
43385
43748
  return cwd === options2.cwd && additionalDirectories.length === options2.additionalDirectories.length && additionalDirectories.every(
43386
- (directory, index) => directory === options2.additionalDirectories[index]
43749
+ (directory, index2) => directory === options2.additionalDirectories[index2]
43387
43750
  );
43388
43751
  });
43389
43752
  }