@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/cli.js CHANGED
@@ -2340,11 +2340,11 @@ Expecting one of '${allowedValues.join("', '")}'`);
2340
2340
  };
2341
2341
  this._checkNumberOfArguments();
2342
2342
  const processedArgs = [];
2343
- this.registeredArguments.forEach((declaredArg, index) => {
2343
+ this.registeredArguments.forEach((declaredArg, index2) => {
2344
2344
  let value = declaredArg.defaultValue;
2345
2345
  if (declaredArg.variadic) {
2346
- if (index < this.args.length) {
2347
- value = this.args.slice(index);
2346
+ if (index2 < this.args.length) {
2347
+ value = this.args.slice(index2);
2348
2348
  if (declaredArg.parseArg) {
2349
2349
  value = value.reduce((processed, v) => {
2350
2350
  return myParseArg(declaredArg, v, processed);
@@ -2353,13 +2353,13 @@ Expecting one of '${allowedValues.join("', '")}'`);
2353
2353
  } else if (value === void 0) {
2354
2354
  value = [];
2355
2355
  }
2356
- } else if (index < this.args.length) {
2357
- value = this.args[index];
2356
+ } else if (index2 < this.args.length) {
2357
+ value = this.args[index2];
2358
2358
  if (declaredArg.parseArg) {
2359
2359
  value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2360
2360
  }
2361
2361
  }
2362
- processedArgs[index] = value;
2362
+ processedArgs[index2] = value;
2363
2363
  });
2364
2364
  this.processedArgs = processedArgs;
2365
2365
  }
@@ -2653,10 +2653,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
2653
2653
  }
2654
2654
  }
2655
2655
  if (/^--[^=]+=/.test(arg)) {
2656
- const index = arg.indexOf("=");
2657
- const option = this._findOption(arg.slice(0, index));
2656
+ const index2 = arg.indexOf("=");
2657
+ const option = this._findOption(arg.slice(0, index2));
2658
2658
  if (option && (option.required || option.optional)) {
2659
- this.emit(`option:${option.name()}`, arg.slice(index + 1));
2659
+ this.emit(`option:${option.name()}`, arg.slice(index2 + 1));
2660
2660
  continue;
2661
2661
  }
2662
2662
  }
@@ -3381,7 +3381,7 @@ var program = new Command();
3381
3381
  // package.json
3382
3382
  var package_default = {
3383
3383
  name: "@moxt-ai/mobius",
3384
- version: "0.0.175",
3384
+ version: "0.0.176",
3385
3385
  description: "Mobius CLI for pairing and running local AI agent services.",
3386
3386
  type: "module",
3387
3387
  bin: {
@@ -3435,6 +3435,7 @@ var package_default = {
3435
3435
  devDependencies: {
3436
3436
  "@moxt-ai/mobius-protocol": "workspace:*",
3437
3437
  "@types/node": "^24.13.5",
3438
+ "drizzle-kit": "1.0.0-rc.4",
3438
3439
  "drizzle-orm": "1.0.0-rc.4",
3439
3440
  esbuild: "0.28.2",
3440
3441
  "@moxt-ai/mobius-sdk": "workspace:*",
@@ -8320,11 +8321,11 @@ var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => {
8320
8321
  return payload;
8321
8322
  };
8322
8323
  });
8323
- function handleArrayResult(result, final, index) {
8324
+ function handleArrayResult(result, final, index2) {
8324
8325
  if (result.issues.length) {
8325
- final.issues.push(...prefixIssues(index, result.issues));
8326
+ final.issues.push(...prefixIssues(index2, result.issues));
8326
8327
  }
8327
- final.value[index] = result.value;
8328
+ final.value[index2] = result.value;
8328
8329
  }
8329
8330
  var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
8330
8331
  $ZodType.init(inst, def);
@@ -8935,14 +8936,14 @@ function mergeValues(a, b) {
8935
8936
  return { valid: false, mergeErrorPath: [] };
8936
8937
  }
8937
8938
  const newArray = [];
8938
- for (let index = 0; index < a.length; index++) {
8939
- const itemA = a[index];
8940
- const itemB = b[index];
8939
+ for (let index2 = 0; index2 < a.length; index2++) {
8940
+ const itemA = a[index2];
8941
+ const itemB = b[index2];
8941
8942
  const sharedValue = mergeValues(itemA, itemB);
8942
8943
  if (!sharedValue.valid) {
8943
8944
  return {
8944
8945
  valid: false,
8945
- mergeErrorPath: [index, ...sharedValue.mergeErrorPath]
8946
+ mergeErrorPath: [index2, ...sharedValue.mergeErrorPath]
8946
8947
  };
8947
8948
  }
8948
8949
  newArray.push(sharedValue.data);
@@ -9093,11 +9094,11 @@ function getTupleOptStart(items, key) {
9093
9094
  }
9094
9095
  return 0;
9095
9096
  }
9096
- function handleTupleResult(result, final, index) {
9097
+ function handleTupleResult(result, final, index2) {
9097
9098
  if (result.issues.length) {
9098
- final.issues.push(...prefixIssues(index, result.issues));
9099
+ final.issues.push(...prefixIssues(index2, result.issues));
9099
9100
  }
9100
- final.value[index] = result.value;
9101
+ final.value[index2] = result.value;
9101
9102
  }
9102
9103
  function handleTupleResults(itemResults, final, items, input2, optoutStart) {
9103
9104
  for (let i = 0; i < items.length; i++) {
@@ -23778,7 +23779,7 @@ function detectVersion(schema, defaultTarget) {
23778
23779
  return defaultTarget ?? "draft-2020-12";
23779
23780
  }
23780
23781
  function applyMinItems(items, minItems) {
23781
- return items.map((item, index) => index < minItems ? item : item.optional());
23782
+ return items.map((item, index2) => index2 < minItems ? item : item.optional());
23782
23783
  }
23783
23784
  function decodeJSONPointerSegment(segment) {
23784
23785
  return segment.replace(/~1/g, "/").replace(/~0/g, "~");
@@ -27852,9 +27853,9 @@ function comparePrerelease(left, right) {
27852
27853
  if (left.length === 0 || right.length === 0) {
27853
27854
  return left.length === right.length ? 0 : left.length === 0 ? 1 : -1;
27854
27855
  }
27855
- for (let index = 0; index < Math.max(left.length, right.length); index += 1) {
27856
- const leftPart = left[index];
27857
- const rightPart = right[index];
27856
+ for (let index2 = 0; index2 < Math.max(left.length, right.length); index2 += 1) {
27857
+ const leftPart = left[index2];
27858
+ const rightPart = right[index2];
27858
27859
  if (leftPart === void 0 || rightPart === void 0) {
27859
27860
  return leftPart === rightPart ? 0 : leftPart === void 0 ? -1 : 1;
27860
27861
  }
@@ -27879,8 +27880,8 @@ function compareAgentVersions(left, right) {
27879
27880
  if (parsedLeft === null || parsedRight === null) {
27880
27881
  return null;
27881
27882
  }
27882
- for (let index = 0; index < Math.max(parsedLeft.core.length, parsedRight.core.length); index += 1) {
27883
- const difference = (parsedLeft.core[index] ?? 0) - (parsedRight.core[index] ?? 0);
27883
+ for (let index2 = 0; index2 < Math.max(parsedLeft.core.length, parsedRight.core.length); index2 += 1) {
27884
+ const difference = (parsedLeft.core[index2] ?? 0) - (parsedRight.core[index2] ?? 0);
27884
27885
  if (difference !== 0) {
27885
27886
  return Math.sign(difference);
27886
27887
  }
@@ -28624,12 +28625,12 @@ var DEFAULT_AGENT_EXECUTION_CONFIGURATION = Object.freeze({
28624
28625
  });
28625
28626
  var sessionConfigurationSelectionsSchema = external_exports.array(sessionConfigurationSelectionSchema).max(100).superRefine((selections, context) => {
28626
28627
  const identifiers = /* @__PURE__ */ new Set();
28627
- for (const [index, selection] of selections.entries()) {
28628
+ for (const [index2, selection] of selections.entries()) {
28628
28629
  if (identifiers.has(selection.configId)) {
28629
28630
  context.addIssue({
28630
28631
  code: "custom",
28631
28632
  message: "Session configuration identifiers must be unique",
28632
- path: [index, "configId"]
28633
+ path: [index2, "configId"]
28633
28634
  });
28634
28635
  }
28635
28636
  identifiers.add(selection.configId);
@@ -30130,12 +30131,12 @@ var sessionExportV2Schema = external_exports.object({
30130
30131
  }).readonly().superRefine((session, context) => {
30131
30132
  let previousPosition = 0n;
30132
30133
  const eventIds = /* @__PURE__ */ new Set();
30133
- for (const [index, event] of session.events.entries()) {
30134
+ for (const [index2, event] of session.events.entries()) {
30134
30135
  if (event.sessionId !== session.sessionId) {
30135
30136
  context.addIssue({
30136
30137
  code: "custom",
30137
30138
  message: "Exported event belongs to a different Session",
30138
- path: ["events", index, "sessionId"]
30139
+ path: ["events", index2, "sessionId"]
30139
30140
  });
30140
30141
  }
30141
30142
  const position = BigInt(event.position);
@@ -30143,14 +30144,14 @@ var sessionExportV2Schema = external_exports.object({
30143
30144
  context.addIssue({
30144
30145
  code: "custom",
30145
30146
  message: "Exported events are not in increasing position order",
30146
- path: ["events", index, "position"]
30147
+ path: ["events", index2, "position"]
30147
30148
  });
30148
30149
  }
30149
30150
  if (eventIds.has(event.eventId)) {
30150
30151
  context.addIssue({
30151
30152
  code: "custom",
30152
30153
  message: "Exported event identities are not unique",
30153
- path: ["events", index, "eventId"]
30154
+ path: ["events", index2, "eventId"]
30154
30155
  });
30155
30156
  }
30156
30157
  previousPosition = position;
@@ -30201,6 +30202,7 @@ function decode5(value, schema) {
30201
30202
  function encode4(value, schema) {
30202
30203
  return JSON.stringify(decode5(value, schema));
30203
30204
  }
30205
+ var decodeSessionEventV2 = (value) => decode5(value, sessionEventV2Schema);
30204
30206
  var decodeSessionEventEnvelopeV2 = (value) => decode5(value, sessionEventEnvelopeV2Schema);
30205
30207
  var encodeSessionEventEnvelopeV2 = (value) => encode4(value, sessionEventEnvelopeV2Schema);
30206
30208
  var decodeAcpSessionUpdateV2 = (value) => decode5(value, acpSessionUpdateV2Schema);
@@ -30946,16 +30948,16 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
30946
30948
  };
30947
30949
  #readConnectionForChannel = async (channelId, signal) => {
30948
30950
  const normalizedChannelId = validateIdentifier(channelId, "invalid_channel_id");
30949
- const index = decodeChannelIndex(
30951
+ const index2 = decodeChannelIndex(
30950
30952
  await readJsonFile(this.channelIndexPath(normalizedChannelId), signal, "connection_not_found")
30951
30953
  );
30952
- if (index.applicationId !== this.applicationId || index.installationId !== this.installationId || index.channelId !== normalizedChannelId) {
30954
+ if (index2.applicationId !== this.applicationId || index2.installationId !== this.installationId || index2.channelId !== normalizedChannelId) {
30953
30955
  throw new RuntimeInstallationStoreError(
30954
30956
  "connection_owner_mismatch",
30955
30957
  "The saved Runtime connection belongs to another installation"
30956
30958
  );
30957
30959
  }
30958
- return await this.readConnection(index.connectionId, signal);
30960
+ return await this.readConnection(index2.connectionId, signal);
30959
30961
  };
30960
30962
  saveConnection = async (input2, signal) => {
30961
30963
  const stored = new VerifiedRuntimeConnection(
@@ -31150,16 +31152,16 @@ function hasExactKeys2(value, expectedKeys) {
31150
31152
  }
31151
31153
  function readSingleOption(arguments_, option) {
31152
31154
  const values = [];
31153
- for (let index = 0; index < arguments_.length; index += 1) {
31154
- if (arguments_[index] !== option) {
31155
+ for (let index2 = 0; index2 < arguments_.length; index2 += 1) {
31156
+ if (arguments_[index2] !== option) {
31155
31157
  continue;
31156
31158
  }
31157
- const value = arguments_[index + 1];
31159
+ const value = arguments_[index2 + 1];
31158
31160
  if (value === void 0 || value.startsWith("--")) {
31159
31161
  throw new PairingClientError("invalid_arguments", `${option} requires a value`);
31160
31162
  }
31161
31163
  values.push(value);
31162
- index += 1;
31164
+ index2 += 1;
31163
31165
  }
31164
31166
  if (values.length !== 1) {
31165
31167
  throw new PairingClientError("invalid_arguments", `${option} must be provided exactly once`);
@@ -31167,8 +31169,8 @@ function readSingleOption(arguments_, option) {
31167
31169
  return values[0] ?? "";
31168
31170
  }
31169
31171
  function assertKnownArguments(arguments_) {
31170
- for (let index = 0; index < arguments_.length; index += 2) {
31171
- const option = arguments_[index];
31172
+ for (let index2 = 0; index2 < arguments_.length; index2 += 2) {
31173
+ const option = arguments_[index2];
31172
31174
  if (option !== "--url" && option !== "--code" && option !== "--pairing" && option !== "--workspace") {
31173
31175
  throw new PairingClientError("invalid_arguments", `Unknown pairing option: ${option ?? "missing option"}`);
31174
31176
  }
@@ -31445,7 +31447,7 @@ var AuditStore = class {
31445
31447
  };
31446
31448
 
31447
31449
  // src/run-daemon.ts
31448
- import { createHash as createHash8, randomUUID as randomUUID9 } from "node:crypto";
31450
+ import { createHash as createHash8, randomUUID as randomUUID10 } from "node:crypto";
31449
31451
  import { join as join19 } from "node:path";
31450
31452
  import { styleText } from "node:util";
31451
31453
 
@@ -31568,7 +31570,7 @@ function startsWith(bytes, signature, offset = 0) {
31568
31570
  if (bytes.byteLength < offset + signature.byteLength) {
31569
31571
  return false;
31570
31572
  }
31571
- return signature.every((value, index) => bytes[offset + index] === value);
31573
+ return signature.every((value, index2) => bytes[offset + index2] === value);
31572
31574
  }
31573
31575
  function sniffRasterMime(bytes) {
31574
31576
  if (startsWith(bytes, PNG_SIGNATURE)) {
@@ -31696,7 +31698,7 @@ function startsWith2(bytes, signature, offset = 0) {
31696
31698
  if (bytes.byteLength < offset + signature.byteLength) {
31697
31699
  return false;
31698
31700
  }
31699
- return signature.every((value, index) => bytes[offset + index] === value);
31701
+ return signature.every((value, index2) => bytes[offset + index2] === value);
31700
31702
  }
31701
31703
  function sniffVideoMime(bytes) {
31702
31704
  if (startsWith2(bytes, MP4_FILE_TYPE, 4)) {
@@ -31825,10 +31827,10 @@ async function replaceImageMarkers(text2, replace) {
31825
31827
  let cursor = 0;
31826
31828
  let rewritten = "";
31827
31829
  for (const match of matches) {
31828
- const index = match.index ?? 0;
31829
- rewritten += text2.slice(cursor, index);
31830
+ const index2 = match.index ?? 0;
31831
+ rewritten += text2.slice(cursor, index2);
31830
31832
  rewritten += await replace(match[1] ?? "");
31831
- cursor = index + match[0].length;
31833
+ cursor = index2 + match[0].length;
31832
31834
  }
31833
31835
  return `${rewritten}${text2.slice(cursor)}`;
31834
31836
  }
@@ -33062,9 +33064,9 @@ function historyContentCharacters(messages) {
33062
33064
  var AcpHistoryReplay = class {
33063
33065
  #activities = /* @__PURE__ */ new Map();
33064
33066
  #messages = [];
33065
- #events = [];
33066
- #records = [];
33067
+ #events;
33067
33068
  #turnActivityIds = /* @__PURE__ */ new Set();
33069
+ #sessionId;
33068
33070
  #activityTracker = new AcpActivityTracker(
33069
33071
  async (activity2) => {
33070
33072
  this.#activities.set(activity2.activityId, activity2);
@@ -33085,10 +33087,16 @@ var AcpHistoryReplay = class {
33085
33087
  #firstMessageIndex = 0;
33086
33088
  #characters = 0;
33087
33089
  #truncated = false;
33090
+ constructor(events, sessionId) {
33091
+ this.#events = events;
33092
+ this.#sessionId = sessionId;
33093
+ }
33088
33094
  record = async (update, rawUpdate, onRecorded = () => Promise.resolve()) => {
33089
- this.#records.push({ kind: "acp", rawUpdate, update });
33090
- this.#events.push({ payload: rawUpdate, type: "acp" });
33091
- await onRecorded(this.#events.length);
33095
+ const position = this.#events.append(this.#sessionId, { payload: rawUpdate, type: "acp" });
33096
+ await onRecorded(position);
33097
+ return await this.#applyUpdate(update, position);
33098
+ };
33099
+ #applyUpdate = async (update, position) => {
33092
33100
  if (update.sessionUpdate === "agent_thought_chunk") {
33093
33101
  if (update.content.type === "text") {
33094
33102
  await this.#activityTracker.recordNarrative(
@@ -33097,30 +33105,30 @@ var AcpHistoryReplay = class {
33097
33105
  update.content.text
33098
33106
  );
33099
33107
  }
33100
- return this.#events.length;
33108
+ return position;
33101
33109
  }
33102
33110
  if (update.sessionUpdate === "tool_call") {
33103
33111
  await this.#activityTracker.recordToolCall(update);
33104
- return this.#events.length;
33112
+ return position;
33105
33113
  }
33106
33114
  if (update.sessionUpdate === "tool_call_update") {
33107
33115
  await this.#activityTracker.recordToolCallUpdate(update);
33108
- return this.#events.length;
33116
+ return position;
33109
33117
  }
33110
33118
  if (update.sessionUpdate === "plan") {
33111
33119
  await this.#activityTracker.recordPlan(update);
33112
- return this.#events.length;
33120
+ return position;
33113
33121
  }
33114
33122
  if (update.sessionUpdate === "plan_update") {
33115
33123
  await this.#activityTracker.recordPlanUpdate(update);
33116
- return this.#events.length;
33124
+ return position;
33117
33125
  }
33118
33126
  if (update.sessionUpdate === "plan_removed") {
33119
33127
  await this.#activityTracker.removePlan(update);
33120
- return this.#events.length;
33128
+ return position;
33121
33129
  }
33122
33130
  if (update.sessionUpdate !== "user_message_chunk" && update.sessionUpdate !== "agent_message_chunk") {
33123
- return this.#events.length;
33131
+ return position;
33124
33132
  }
33125
33133
  if (update.sessionUpdate === "agent_message_chunk" && isProgressMessage(update)) {
33126
33134
  if (update.content.type === "text") {
@@ -33130,18 +33138,18 @@ var AcpHistoryReplay = class {
33130
33138
  update.content.text
33131
33139
  );
33132
33140
  }
33133
- return this.#events.length;
33141
+ return position;
33134
33142
  }
33135
33143
  const role = update.sessionUpdate === "user_message_chunk" ? "user" : "assistant";
33136
33144
  const content = update.content;
33137
33145
  if (role === "assistant" && content.type !== "text") {
33138
33146
  await this.#activityTracker.finishNarrative();
33139
33147
  this.recordAssistantContent(update.messageId ?? null, normalizeContentBlock(content));
33140
- return this.#events.length;
33148
+ return position;
33141
33149
  }
33142
33150
  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]`;
33143
33151
  if (text2.length === 0) {
33144
- return this.#events.length;
33152
+ return position;
33145
33153
  }
33146
33154
  const previous = this.#messages.at(-1);
33147
33155
  const id = update.messageId ?? null;
@@ -33168,41 +33176,32 @@ var AcpHistoryReplay = class {
33168
33176
  this.#characters += bounded2.length;
33169
33177
  this.#lastMessageId = id;
33170
33178
  this.trimMessages();
33171
- return this.#events.length;
33179
+ return position;
33172
33180
  };
33173
33181
  recordLifecycle = (event) => {
33174
33182
  if (event.type !== "lifecycle-metadata") {
33175
33183
  throw new Error("Lifecycle history only accepts lifecycle metadata");
33176
33184
  }
33177
- this.#records.push({ event, kind: "lifecycle" });
33178
- this.#events.push(event);
33179
- return this.#events.length;
33185
+ return this.#events.append(this.#sessionId, event);
33180
33186
  };
33181
- eventCount = () => this.#events.length;
33182
33187
  append = async (replay) => {
33183
- for (const record2 of replay.#records) {
33184
- if (record2.kind === "acp") {
33185
- await this.record(record2.update, record2.rawUpdate);
33186
- } else {
33187
- this.recordLifecycle(record2.event);
33188
- }
33188
+ await replay.#activityTracker.finish();
33189
+ for (const [activityId, activity2] of replay.#activities) {
33190
+ this.#activities.set(activityId, activity2);
33189
33191
  }
33190
- };
33191
- eventPage = (eventLimit, cursor, appended = null) => {
33192
- const events = appended === null ? this.#events : [...this.#events, ...appended.#events];
33193
- const parsedCursor = cursor === null ? events.length : Number(cursor);
33194
- if (!Number.isSafeInteger(parsedCursor) || parsedCursor < 0 || parsedCursor > events.length) {
33195
- throw new Error("The native event cursor is invalid");
33192
+ for (const message of replay.#messages.slice(replay.#firstMessageIndex)) {
33193
+ this.#messages.push(message);
33194
+ this.#characters += message.text.length;
33196
33195
  }
33197
- const endUpdate = parsedCursor;
33198
- const startUpdate = Math.max(0, endUpdate - eventLimit);
33199
- return {
33200
- nextCursor: startUpdate === 0 ? null : startUpdate.toString(),
33201
- startPosition: startUpdate + 1,
33202
- truncated: startUpdate > 0,
33203
- events: events.slice(startUpdate, endUpdate)
33204
- };
33196
+ this.#turnActivityIds.clear();
33197
+ for (const activityId of replay.#turnActivityIds) {
33198
+ this.#turnActivityIds.add(activityId);
33199
+ }
33200
+ this.#lastMessageId = replay.#lastMessageId;
33201
+ this.#truncated ||= replay.#truncated;
33202
+ this.trimMessages();
33205
33203
  };
33204
+ eventPage = (eventLimit, cursor) => this.#events.page(this.#sessionId, eventLimit, cursor);
33206
33205
  snapshot = async () => {
33207
33206
  await this.#activityTracker.finish();
33208
33207
  const messages = this.#messages.slice(this.#firstMessageIndex).map((message) => {
@@ -33835,9 +33834,7 @@ var AcpSessionInteractions = class {
33835
33834
  };
33836
33835
 
33837
33836
  // src/acp/session-store.ts
33838
- import { chmodSync, mkdirSync } from "node:fs";
33839
- import { dirname as dirname4 } from "node:path";
33840
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
33837
+ import { randomUUID as randomUUID2 } from "node:crypto";
33841
33838
 
33842
33839
  // ../../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
33843
33840
  var entityKind = /* @__PURE__ */ Symbol.for("drizzle:entityKind");
@@ -34953,7 +34950,7 @@ function haveSameKeys(left, right) {
34953
34950
  const leftKeys = Object.keys(left);
34954
34951
  const rightKeys = Object.keys(right);
34955
34952
  if (leftKeys.length !== rightKeys.length) return false;
34956
- for (const [index, key] of leftKeys.entries()) if (key !== rightKeys[index]) return false;
34953
+ for (const [index2, key] of leftKeys.entries()) if (key !== rightKeys[index2]) return false;
34957
34954
  return true;
34958
34955
  }
34959
34956
  function mapUpdateSet(table, values) {
@@ -35706,195 +35703,6 @@ var NoopLogger = class {
35706
35703
  }
35707
35704
  };
35708
35705
 
35709
- // ../../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
35710
- var SQLiteCountBuilder = class SQLiteCountBuilder2 extends SQL {
35711
- static [entityKind] = "SQLiteCountBuilder";
35712
- dialect;
35713
- session;
35714
- static buildCount(source, filters, parens) {
35715
- const query = sql`select count(*) from ${source}${sql` where ${filters}`.if(filters)}`;
35716
- return parens ? sql`(${query})` : query;
35717
- }
35718
- constructor(countConfig) {
35719
- super(SQLiteCountBuilder2.buildCount(countConfig.source, countConfig.filters, true).queryChunks);
35720
- this.countConfig = countConfig;
35721
- this.dialect = countConfig.dialect;
35722
- this.session = countConfig.session;
35723
- this.mapWith((e) => {
35724
- if (typeof e === "number") return e;
35725
- return Number(e ?? 0);
35726
- });
35727
- }
35728
- executableSql;
35729
- build() {
35730
- if (!this.executableSql) {
35731
- const { source, filters } = this.countConfig;
35732
- this.executableSql = SQLiteCountBuilder2.buildCount(source, filters);
35733
- }
35734
- return this.dialect.sqlToQuery(this.executableSql);
35735
- }
35736
- };
35737
-
35738
- // ../../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
35739
- var SQLiteAsyncCountBuilder = class extends SQLiteCountBuilder {
35740
- static [entityKind] = "SQLiteAsyncCountBuilder";
35741
- constructor(countConfig) {
35742
- super(countConfig);
35743
- }
35744
- /** @internal */
35745
- executeRaw(placeholderValues) {
35746
- return this.session.prepareQuery(this.build(), "arrays", false, "all", (rows) => {
35747
- const v = rows[0]?.[0];
35748
- if (typeof v === "number") return v;
35749
- return v ? Number(v) : 0;
35750
- }).execute(placeholderValues);
35751
- }
35752
- async execute(placeholderValues) {
35753
- return await this.executeRaw(placeholderValues);
35754
- }
35755
- };
35756
- applyMixins(SQLiteAsyncCountBuilder, [QueryPromise]);
35757
- var SQLiteSyncCountBuilder = class extends SQLiteAsyncCountBuilder {
35758
- static [entityKind] = "SQLiteSyncCountBuilder";
35759
- sync(placeholderValues) {
35760
- return this.executeRaw(placeholderValues).sync();
35761
- }
35762
- };
35763
-
35764
- // ../../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
35765
- var RelationalQueryBuilder = class {
35766
- static [entityKind] = "SQLiteRelationalQueryBuilderV2";
35767
- constructor(mode, schema, table, tableConfig, dialect, session, forbidJsonb, builder = SQLiteRelationalQuery) {
35768
- this.mode = mode;
35769
- this.schema = schema;
35770
- this.table = table;
35771
- this.tableConfig = tableConfig;
35772
- this.dialect = dialect;
35773
- this.session = session;
35774
- this.forbidJsonb = forbidJsonb;
35775
- this.builder = builder;
35776
- }
35777
- findMany(config2) {
35778
- return new this.builder(this.mode, this.schema, this.table, this.tableConfig, this.dialect, this.session, config2 ?? true, "many", this.forbidJsonb);
35779
- }
35780
- findFirst(config2) {
35781
- return new this.builder(this.mode, this.schema, this.table, this.tableConfig, this.dialect, this.session, config2 ?? true, "first", this.forbidJsonb);
35782
- }
35783
- };
35784
- var SQLiteRelationalQuery = class {
35785
- static [entityKind] = "SQLiteRelationalQueryV2";
35786
- /** @internal */
35787
- mode;
35788
- /** @internal */
35789
- table;
35790
- /** @internal */
35791
- resultKind;
35792
- constructor(resultKind, schema, table, tableConfig, dialect, session, config2, mode, forbidJsonb) {
35793
- this.schema = schema;
35794
- this.tableConfig = tableConfig;
35795
- this.dialect = dialect;
35796
- this.session = session;
35797
- this.config = config2;
35798
- this.forbidJsonb = forbidJsonb;
35799
- this.resultKind = resultKind;
35800
- this.mode = mode;
35801
- this.table = table;
35802
- }
35803
- getSQL() {
35804
- return this._getQuery().sql;
35805
- }
35806
- _getQuery() {
35807
- const jsonb = this.forbidJsonb ? sql`json` : sql`jsonb`;
35808
- return this.dialect.buildRelationalQuery({
35809
- schema: this.schema,
35810
- table: this.table,
35811
- tableConfig: this.tableConfig,
35812
- queryConfig: this.config,
35813
- mode: this.mode,
35814
- jsonb
35815
- });
35816
- }
35817
- _toSQL() {
35818
- const query = this._getQuery();
35819
- return {
35820
- query,
35821
- builtQuery: this.dialect.sqlToQuery(query.sql)
35822
- };
35823
- }
35824
- toSQL() {
35825
- return this._toSQL().builtQuery;
35826
- }
35827
- };
35828
-
35829
- // ../../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
35830
- var SQLiteAsyncRelationalQuery = class extends SQLiteRelationalQuery {
35831
- static [entityKind] = "SQLiteAsyncRelationalQueryV2";
35832
- /** @internal */
35833
- _prepare(prepare = false) {
35834
- const { query, builtQuery } = this._toSQL();
35835
- const mapper = this.dialect.mapperGenerators.relationalRows({
35836
- isFirst: this.mode === "first",
35837
- parseJson: true,
35838
- parseJsonIfString: false,
35839
- rootJsonMappers: false,
35840
- selection: query.selection,
35841
- arrayModeRoot: true
35842
- });
35843
- return this.session.prepareQuery(builtQuery, "arrays", prepare, "all", mapper);
35844
- }
35845
- prepare() {
35846
- return this._prepare(true);
35847
- }
35848
- async execute(placeholderValues) {
35849
- return this._prepare().execute(placeholderValues);
35850
- }
35851
- };
35852
- var SQLiteSyncRelationalQuery = class extends SQLiteAsyncRelationalQuery {
35853
- static [entityKind] = "SQLiteSyncRelationalQueryV2";
35854
- sync(placeholderValues) {
35855
- return this._prepare().execute(placeholderValues).sync();
35856
- }
35857
- };
35858
- applyMixins(SQLiteAsyncRelationalQuery, [QueryPromise]);
35859
-
35860
- // ../../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
35861
- var SelectionProxyHandler = class SelectionProxyHandler2 {
35862
- static [entityKind] = "SelectionProxyHandler";
35863
- config;
35864
- constructor(config2) {
35865
- this.config = { ...config2 };
35866
- }
35867
- get(subquery, prop) {
35868
- if (prop === "_") return {
35869
- ...subquery["_"],
35870
- selectedFields: new Proxy(subquery._.selectedFields, this)
35871
- };
35872
- if (prop === ViewBaseConfig) return {
35873
- ...subquery[ViewBaseConfig],
35874
- selectedFields: new Proxy(subquery[ViewBaseConfig].selectedFields, this)
35875
- };
35876
- if (typeof prop === "symbol") return subquery[prop];
35877
- const value = (is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View) ? subquery[ViewBaseConfig].selectedFields : subquery)[prop];
35878
- if (is(value, SQL.Aliased)) {
35879
- if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) return value.sql;
35880
- const newValue = value.clone();
35881
- newValue.isSelectionField = true;
35882
- newValue.origin = this.config.alias;
35883
- return newValue;
35884
- }
35885
- if (is(value, SQL)) {
35886
- if (this.config.sqlBehavior === "sql") return value;
35887
- 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.`);
35888
- }
35889
- if (is(value, Column)) {
35890
- 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));
35891
- return value;
35892
- }
35893
- if (typeof value !== "object" || value === null) return value;
35894
- return new Proxy(value, new SelectionProxyHandler2(this.config));
35895
- }
35896
- };
35897
-
35898
35706
  // ../../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
35899
35707
  var ForeignKeyBuilder = class {
35900
35708
  static [entityKind] = "SQLiteForeignKeyBuilder";
@@ -36459,130 +36267,144 @@ function sqliteTableWithCasing(casing) {
36459
36267
  }
36460
36268
  var sqliteTable = sqliteTableWithCasing(void 0);
36461
36269
 
36462
- // ../../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
36463
- function extractUsedTable(table) {
36464
- if (is(table, SQLiteTable)) return [`${table[Table.Symbol.BaseName]}`];
36465
- if (is(table, Subquery)) return table._.usedTables ?? [];
36466
- if (is(table, SQL)) return table.usedTables ?? [];
36467
- return [];
36468
- }
36469
-
36470
- // ../../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
36471
- var SQLiteDeleteBase = class {
36472
- static [entityKind] = "SQLiteDelete";
36270
+ // ../../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
36271
+ var IndexBuilderOn = class {
36272
+ static [entityKind] = "SQLiteIndexBuilderOn";
36273
+ constructor(name2, unique) {
36274
+ this.name = name2;
36275
+ this.unique = unique;
36276
+ }
36277
+ on(...columns) {
36278
+ return new IndexBuilder(this.name, columns, this.unique);
36279
+ }
36280
+ };
36281
+ var IndexBuilder = class {
36282
+ static [entityKind] = "SQLiteIndexBuilder";
36473
36283
  /** @internal */
36474
36284
  config;
36475
- constructor(table, session, dialect, withList) {
36476
- this.table = table;
36477
- this.session = session;
36478
- this.dialect = dialect;
36285
+ constructor(name2, columns, unique) {
36479
36286
  this.config = {
36480
- table,
36481
- withList
36287
+ name: name2,
36288
+ columns,
36289
+ unique,
36290
+ where: void 0
36482
36291
  };
36483
36292
  }
36484
36293
  /**
36485
- * Adds a `where` clause to the query.
36486
- *
36487
- * Calling this method will delete only those rows that fulfill a specified condition.
36488
- *
36489
- * See docs: {@link https://orm.drizzle.team/docs/delete}
36490
- *
36491
- * @param where the `where` clause.
36492
- *
36493
- * @example
36494
- * You can use conditional operators and `sql function` to filter the rows to be deleted.
36495
- *
36496
- * ```ts
36497
- * // Delete all cars with green color
36498
- * db.delete(cars).where(eq(cars.color, 'green'));
36499
- * // or
36500
- * db.delete(cars).where(sql`${cars.color} = 'green'`)
36501
- * ```
36502
- *
36503
- * You can logically combine conditional operators with `and()` and `or()` operators:
36504
- *
36505
- * ```ts
36506
- * // Delete all BMW cars with a green color
36507
- * db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
36508
- *
36509
- * // Delete all cars with the green or blue color
36510
- * db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
36511
- * ```
36294
+ * Condition for partial index.
36512
36295
  */
36513
- where(where) {
36514
- this.config.where = where;
36296
+ where(condition) {
36297
+ this.config.where = condition;
36515
36298
  return this;
36516
36299
  }
36517
- orderBy(...columns) {
36518
- if (typeof columns[0] === "function") {
36519
- const orderBy = columns[0](new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({
36520
- sqlAliasedBehavior: "alias",
36521
- sqlBehavior: "sql"
36522
- })));
36523
- const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
36524
- this.config.orderBy = orderByArray;
36525
- } else {
36526
- const orderByArray = columns;
36527
- this.config.orderBy = orderByArray;
36528
- }
36529
- return this;
36530
- }
36531
- limit(limit) {
36532
- this.config.limit = limit;
36533
- return this;
36534
- }
36535
- returning(fields = this.table[SQLiteTable.Symbol.Columns]) {
36536
- this.config.returning = orderSelectedFields(fields);
36537
- return this;
36538
- }
36539
- getSQL() {
36540
- return this.dialect.buildDeleteQuery(this.config);
36541
- }
36542
- toSQL() {
36543
- return this.dialect.sqlToQuery(this.getSQL());
36300
+ /** @internal */
36301
+ build(table) {
36302
+ return new Index(this.config, table);
36544
36303
  }
36545
- $dynamic() {
36546
- return this;
36304
+ };
36305
+ var Index = class {
36306
+ static [entityKind] = "SQLiteIndex";
36307
+ config;
36308
+ isNameExplicit;
36309
+ constructor(config2, table) {
36310
+ this.config = {
36311
+ ...config2,
36312
+ table
36313
+ };
36314
+ this.isNameExplicit = !!config2.name;
36547
36315
  }
36548
36316
  };
36317
+ function index(name2) {
36318
+ return new IndexBuilderOn(name2, false);
36319
+ }
36549
36320
 
36550
- // ../../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
36551
- var SQLiteAsyncDeleteBase = class extends SQLiteDeleteBase {
36552
- static [entityKind] = "SQLiteAsyncDelete";
36321
+ // ../../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
36322
+ function primaryKey(...config2) {
36323
+ if (config2[0].columns) return new PrimaryKeyBuilder(config2[0].columns, config2[0].name);
36324
+ return new PrimaryKeyBuilder(config2);
36325
+ }
36326
+ var PrimaryKeyBuilder = class {
36327
+ static [entityKind] = "SQLitePrimaryKeyBuilder";
36553
36328
  /** @internal */
36554
- _prepare(prepare = false) {
36555
- 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, {
36556
- type: "delete",
36557
- tables: extractUsedTable(this.config.table)
36558
- });
36329
+ columns;
36330
+ /** @internal */
36331
+ name;
36332
+ constructor(columns, name2) {
36333
+ this.columns = columns;
36334
+ this.name = name2;
36559
36335
  }
36560
- prepare() {
36561
- return this._prepare(true);
36336
+ /** @internal */
36337
+ build(table) {
36338
+ return new PrimaryKey(table, this.columns, this.name);
36562
36339
  }
36563
- run = (placeholderValues) => {
36564
- return this._prepare().run(placeholderValues);
36565
- };
36566
- all = (placeholderValues) => {
36567
- return this._prepare().all(placeholderValues);
36568
- };
36569
- get = (placeholderValues) => {
36570
- return this._prepare().get(placeholderValues);
36571
- };
36572
- values = (placeholderValues) => {
36573
- return this._prepare().values(placeholderValues);
36574
- };
36575
- async execute(placeholderValues) {
36576
- return this._prepare().execute(placeholderValues);
36340
+ };
36341
+ var PrimaryKey = class {
36342
+ static [entityKind] = "SQLitePrimaryKey";
36343
+ columns;
36344
+ name;
36345
+ isNameExplicit;
36346
+ constructor(table, columns, name2) {
36347
+ this.table = table;
36348
+ this.columns = columns;
36349
+ this.name = name2;
36350
+ this.isNameExplicit = !!name2;
36351
+ }
36352
+ getName() {
36353
+ return this.name ?? `${this.table[SQLiteTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`;
36577
36354
  }
36578
36355
  };
36579
- applyMixins(SQLiteAsyncDeleteBase, [QueryPromise]);
36356
+
36357
+ // ../../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
36358
+ function extractUsedTable(table) {
36359
+ if (is(table, SQLiteTable)) return [`${table[Table.Symbol.BaseName]}`];
36360
+ if (is(table, Subquery)) return table._.usedTables ?? [];
36361
+ if (is(table, SQL)) return table.usedTables ?? [];
36362
+ return [];
36363
+ }
36580
36364
 
36581
36365
  // ../../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
36582
36366
  var SQLiteViewBase = class extends View {
36583
36367
  static [entityKind] = "SQLiteViewBase";
36584
36368
  };
36585
36369
 
36370
+ // ../../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
36371
+ var SelectionProxyHandler = class SelectionProxyHandler2 {
36372
+ static [entityKind] = "SelectionProxyHandler";
36373
+ config;
36374
+ constructor(config2) {
36375
+ this.config = { ...config2 };
36376
+ }
36377
+ get(subquery, prop) {
36378
+ if (prop === "_") return {
36379
+ ...subquery["_"],
36380
+ selectedFields: new Proxy(subquery._.selectedFields, this)
36381
+ };
36382
+ if (prop === ViewBaseConfig) return {
36383
+ ...subquery[ViewBaseConfig],
36384
+ selectedFields: new Proxy(subquery[ViewBaseConfig].selectedFields, this)
36385
+ };
36386
+ if (typeof prop === "symbol") return subquery[prop];
36387
+ const value = (is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View) ? subquery[ViewBaseConfig].selectedFields : subquery)[prop];
36388
+ if (is(value, SQL.Aliased)) {
36389
+ if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) return value.sql;
36390
+ const newValue = value.clone();
36391
+ newValue.isSelectionField = true;
36392
+ newValue.origin = this.config.alias;
36393
+ return newValue;
36394
+ }
36395
+ if (is(value, SQL)) {
36396
+ if (this.config.sqlBehavior === "sql") return value;
36397
+ 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.`);
36398
+ }
36399
+ if (is(value, Column)) {
36400
+ 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));
36401
+ return value;
36402
+ }
36403
+ if (typeof value !== "object" || value === null) return value;
36404
+ return new Proxy(value, new SelectionProxyHandler2(this.config));
36405
+ }
36406
+ };
36407
+
36586
36408
  // ../../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
36587
36409
  var TypedQueryBuilder = class {
36588
36410
  static [entityKind] = "TypedQueryBuilder";
@@ -37283,8 +37105,8 @@ var SQLiteDialect = class {
37283
37105
  buildJoins(joins) {
37284
37106
  if (!joins || joins.length === 0) return;
37285
37107
  const joinsArray = [];
37286
- if (joins) for (const [index, joinMeta] of joins.entries()) {
37287
- if (index === 0) joinsArray.push(sql` `);
37108
+ if (joins) for (const [index2, joinMeta] of joins.entries()) {
37109
+ if (index2 === 0) joinsArray.push(sql` `);
37288
37110
  const table = joinMeta.table;
37289
37111
  const onSql = joinMeta.on ? sql` on ${joinMeta.on}` : void 0;
37290
37112
  if (is(table, SQLiteTable)) {
@@ -37294,7 +37116,7 @@ var SQLiteDialect = class {
37294
37116
  const alias = tableName === origTableName ? void 0 : joinMeta.alias;
37295
37117
  joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`);
37296
37118
  } else joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join ${table}${onSql}`);
37297
- if (index < joins.length - 1) joinsArray.push(sql` `);
37119
+ if (index2 < joins.length - 1) joinsArray.push(sql` `);
37298
37120
  }
37299
37121
  return sql.join(joinsArray);
37300
37122
  }
@@ -37303,9 +37125,9 @@ var SQLiteDialect = class {
37303
37125
  }
37304
37126
  buildOrderBy(orderBy) {
37305
37127
  const orderByList = [];
37306
- if (orderBy) for (const [index, orderByValue] of orderBy.entries()) {
37128
+ if (orderBy) for (const [index2, orderByValue] of orderBy.entries()) {
37307
37129
  orderByList.push(orderByValue);
37308
- if (index < orderBy.length - 1) orderByList.push(sql`, `);
37130
+ if (index2 < orderBy.length - 1) orderByList.push(sql`, `);
37309
37131
  }
37310
37132
  return orderByList.length > 0 ? sql` order by ${sql.join(orderByList)}` : void 0;
37311
37133
  }
@@ -37333,9 +37155,9 @@ var SQLiteDialect = class {
37333
37155
  const whereSql = where ? sql` where ${where}` : void 0;
37334
37156
  const havingSql = having ? sql` having ${having}` : void 0;
37335
37157
  const groupByList = [];
37336
- if (groupBy) for (const [index, groupByValue] of groupBy.entries()) {
37158
+ if (groupBy) for (const [index2, groupByValue] of groupBy.entries()) {
37337
37159
  groupByList.push(groupByValue);
37338
- if (index < groupBy.length - 1) groupByList.push(sql`, `);
37160
+ if (index2 < groupBy.length - 1) groupByList.push(sql`, `);
37339
37161
  }
37340
37162
  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}`;
37341
37163
  if (setOperators.length > 0) return this.buildSetOperations(finalQuery, setOperators);
@@ -37624,6 +37446,268 @@ var QueryBuilder = class {
37624
37446
  }
37625
37447
  };
37626
37448
 
37449
+ // ../../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
37450
+ var SQLiteCountBuilder = class SQLiteCountBuilder2 extends SQL {
37451
+ static [entityKind] = "SQLiteCountBuilder";
37452
+ dialect;
37453
+ session;
37454
+ static buildCount(source, filters, parens) {
37455
+ const query = sql`select count(*) from ${source}${sql` where ${filters}`.if(filters)}`;
37456
+ return parens ? sql`(${query})` : query;
37457
+ }
37458
+ constructor(countConfig) {
37459
+ super(SQLiteCountBuilder2.buildCount(countConfig.source, countConfig.filters, true).queryChunks);
37460
+ this.countConfig = countConfig;
37461
+ this.dialect = countConfig.dialect;
37462
+ this.session = countConfig.session;
37463
+ this.mapWith((e) => {
37464
+ if (typeof e === "number") return e;
37465
+ return Number(e ?? 0);
37466
+ });
37467
+ }
37468
+ executableSql;
37469
+ build() {
37470
+ if (!this.executableSql) {
37471
+ const { source, filters } = this.countConfig;
37472
+ this.executableSql = SQLiteCountBuilder2.buildCount(source, filters);
37473
+ }
37474
+ return this.dialect.sqlToQuery(this.executableSql);
37475
+ }
37476
+ };
37477
+
37478
+ // ../../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
37479
+ var SQLiteAsyncCountBuilder = class extends SQLiteCountBuilder {
37480
+ static [entityKind] = "SQLiteAsyncCountBuilder";
37481
+ constructor(countConfig) {
37482
+ super(countConfig);
37483
+ }
37484
+ /** @internal */
37485
+ executeRaw(placeholderValues) {
37486
+ return this.session.prepareQuery(this.build(), "arrays", false, "all", (rows) => {
37487
+ const v = rows[0]?.[0];
37488
+ if (typeof v === "number") return v;
37489
+ return v ? Number(v) : 0;
37490
+ }).execute(placeholderValues);
37491
+ }
37492
+ async execute(placeholderValues) {
37493
+ return await this.executeRaw(placeholderValues);
37494
+ }
37495
+ };
37496
+ applyMixins(SQLiteAsyncCountBuilder, [QueryPromise]);
37497
+ var SQLiteSyncCountBuilder = class extends SQLiteAsyncCountBuilder {
37498
+ static [entityKind] = "SQLiteSyncCountBuilder";
37499
+ sync(placeholderValues) {
37500
+ return this.executeRaw(placeholderValues).sync();
37501
+ }
37502
+ };
37503
+
37504
+ // ../../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
37505
+ var RelationalQueryBuilder = class {
37506
+ static [entityKind] = "SQLiteRelationalQueryBuilderV2";
37507
+ constructor(mode, schema, table, tableConfig, dialect, session, forbidJsonb, builder = SQLiteRelationalQuery) {
37508
+ this.mode = mode;
37509
+ this.schema = schema;
37510
+ this.table = table;
37511
+ this.tableConfig = tableConfig;
37512
+ this.dialect = dialect;
37513
+ this.session = session;
37514
+ this.forbidJsonb = forbidJsonb;
37515
+ this.builder = builder;
37516
+ }
37517
+ findMany(config2) {
37518
+ return new this.builder(this.mode, this.schema, this.table, this.tableConfig, this.dialect, this.session, config2 ?? true, "many", this.forbidJsonb);
37519
+ }
37520
+ findFirst(config2) {
37521
+ return new this.builder(this.mode, this.schema, this.table, this.tableConfig, this.dialect, this.session, config2 ?? true, "first", this.forbidJsonb);
37522
+ }
37523
+ };
37524
+ var SQLiteRelationalQuery = class {
37525
+ static [entityKind] = "SQLiteRelationalQueryV2";
37526
+ /** @internal */
37527
+ mode;
37528
+ /** @internal */
37529
+ table;
37530
+ /** @internal */
37531
+ resultKind;
37532
+ constructor(resultKind, schema, table, tableConfig, dialect, session, config2, mode, forbidJsonb) {
37533
+ this.schema = schema;
37534
+ this.tableConfig = tableConfig;
37535
+ this.dialect = dialect;
37536
+ this.session = session;
37537
+ this.config = config2;
37538
+ this.forbidJsonb = forbidJsonb;
37539
+ this.resultKind = resultKind;
37540
+ this.mode = mode;
37541
+ this.table = table;
37542
+ }
37543
+ getSQL() {
37544
+ return this._getQuery().sql;
37545
+ }
37546
+ _getQuery() {
37547
+ const jsonb = this.forbidJsonb ? sql`json` : sql`jsonb`;
37548
+ return this.dialect.buildRelationalQuery({
37549
+ schema: this.schema,
37550
+ table: this.table,
37551
+ tableConfig: this.tableConfig,
37552
+ queryConfig: this.config,
37553
+ mode: this.mode,
37554
+ jsonb
37555
+ });
37556
+ }
37557
+ _toSQL() {
37558
+ const query = this._getQuery();
37559
+ return {
37560
+ query,
37561
+ builtQuery: this.dialect.sqlToQuery(query.sql)
37562
+ };
37563
+ }
37564
+ toSQL() {
37565
+ return this._toSQL().builtQuery;
37566
+ }
37567
+ };
37568
+
37569
+ // ../../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
37570
+ var SQLiteAsyncRelationalQuery = class extends SQLiteRelationalQuery {
37571
+ static [entityKind] = "SQLiteAsyncRelationalQueryV2";
37572
+ /** @internal */
37573
+ _prepare(prepare = false) {
37574
+ const { query, builtQuery } = this._toSQL();
37575
+ const mapper = this.dialect.mapperGenerators.relationalRows({
37576
+ isFirst: this.mode === "first",
37577
+ parseJson: true,
37578
+ parseJsonIfString: false,
37579
+ rootJsonMappers: false,
37580
+ selection: query.selection,
37581
+ arrayModeRoot: true
37582
+ });
37583
+ return this.session.prepareQuery(builtQuery, "arrays", prepare, "all", mapper);
37584
+ }
37585
+ prepare() {
37586
+ return this._prepare(true);
37587
+ }
37588
+ async execute(placeholderValues) {
37589
+ return this._prepare().execute(placeholderValues);
37590
+ }
37591
+ };
37592
+ var SQLiteSyncRelationalQuery = class extends SQLiteAsyncRelationalQuery {
37593
+ static [entityKind] = "SQLiteSyncRelationalQueryV2";
37594
+ sync(placeholderValues) {
37595
+ return this._prepare().execute(placeholderValues).sync();
37596
+ }
37597
+ };
37598
+ applyMixins(SQLiteAsyncRelationalQuery, [QueryPromise]);
37599
+
37600
+ // ../../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
37601
+ var SQLiteDeleteBase = class {
37602
+ static [entityKind] = "SQLiteDelete";
37603
+ /** @internal */
37604
+ config;
37605
+ constructor(table, session, dialect, withList) {
37606
+ this.table = table;
37607
+ this.session = session;
37608
+ this.dialect = dialect;
37609
+ this.config = {
37610
+ table,
37611
+ withList
37612
+ };
37613
+ }
37614
+ /**
37615
+ * Adds a `where` clause to the query.
37616
+ *
37617
+ * Calling this method will delete only those rows that fulfill a specified condition.
37618
+ *
37619
+ * See docs: {@link https://orm.drizzle.team/docs/delete}
37620
+ *
37621
+ * @param where the `where` clause.
37622
+ *
37623
+ * @example
37624
+ * You can use conditional operators and `sql function` to filter the rows to be deleted.
37625
+ *
37626
+ * ```ts
37627
+ * // Delete all cars with green color
37628
+ * db.delete(cars).where(eq(cars.color, 'green'));
37629
+ * // or
37630
+ * db.delete(cars).where(sql`${cars.color} = 'green'`)
37631
+ * ```
37632
+ *
37633
+ * You can logically combine conditional operators with `and()` and `or()` operators:
37634
+ *
37635
+ * ```ts
37636
+ * // Delete all BMW cars with a green color
37637
+ * db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
37638
+ *
37639
+ * // Delete all cars with the green or blue color
37640
+ * db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
37641
+ * ```
37642
+ */
37643
+ where(where) {
37644
+ this.config.where = where;
37645
+ return this;
37646
+ }
37647
+ orderBy(...columns) {
37648
+ if (typeof columns[0] === "function") {
37649
+ const orderBy = columns[0](new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({
37650
+ sqlAliasedBehavior: "alias",
37651
+ sqlBehavior: "sql"
37652
+ })));
37653
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
37654
+ this.config.orderBy = orderByArray;
37655
+ } else {
37656
+ const orderByArray = columns;
37657
+ this.config.orderBy = orderByArray;
37658
+ }
37659
+ return this;
37660
+ }
37661
+ limit(limit) {
37662
+ this.config.limit = limit;
37663
+ return this;
37664
+ }
37665
+ returning(fields = this.table[SQLiteTable.Symbol.Columns]) {
37666
+ this.config.returning = orderSelectedFields(fields);
37667
+ return this;
37668
+ }
37669
+ getSQL() {
37670
+ return this.dialect.buildDeleteQuery(this.config);
37671
+ }
37672
+ toSQL() {
37673
+ return this.dialect.sqlToQuery(this.getSQL());
37674
+ }
37675
+ $dynamic() {
37676
+ return this;
37677
+ }
37678
+ };
37679
+
37680
+ // ../../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
37681
+ var SQLiteAsyncDeleteBase = class extends SQLiteDeleteBase {
37682
+ static [entityKind] = "SQLiteAsyncDelete";
37683
+ /** @internal */
37684
+ _prepare(prepare = false) {
37685
+ 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, {
37686
+ type: "delete",
37687
+ tables: extractUsedTable(this.config.table)
37688
+ });
37689
+ }
37690
+ prepare() {
37691
+ return this._prepare(true);
37692
+ }
37693
+ run = (placeholderValues) => {
37694
+ return this._prepare().run(placeholderValues);
37695
+ };
37696
+ all = (placeholderValues) => {
37697
+ return this._prepare().all(placeholderValues);
37698
+ };
37699
+ get = (placeholderValues) => {
37700
+ return this._prepare().get(placeholderValues);
37701
+ };
37702
+ values = (placeholderValues) => {
37703
+ return this._prepare().values(placeholderValues);
37704
+ };
37705
+ async execute(placeholderValues) {
37706
+ return this._prepare().execute(placeholderValues);
37707
+ }
37708
+ };
37709
+ applyMixins(SQLiteAsyncDeleteBase, [QueryPromise]);
37710
+
37627
37711
  // ../../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
37628
37712
  var SQLiteInsertBuilder = class {
37629
37713
  static [entityKind] = "SQLiteInsertBuilder";
@@ -38511,133 +38595,6 @@ var SQLiteAsyncTransaction = class extends SQLiteAsyncDatabase {
38511
38595
  }
38512
38596
  };
38513
38597
 
38514
- // ../../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
38515
- var NodeSQLiteSession = class extends SQLiteAsyncSession {
38516
- static [entityKind] = "SQLJsSession";
38517
- logger;
38518
- constructor(client2, dialect, relations, options = {}) {
38519
- super(dialect, "sync");
38520
- this.client = client2;
38521
- this.relations = relations;
38522
- this.options = options;
38523
- this.logger = options.logger ?? new NoopLogger();
38524
- }
38525
- prepareQuery(query, mode, _prepare, executeMethod, mapper, queryMetadata) {
38526
- let stmt;
38527
- try {
38528
- stmt = this.client.prepare(query.sql);
38529
- } catch (e) {
38530
- throw new DrizzleQueryError(query.sql, query.params, e);
38531
- }
38532
- return new SQLiteAsyncPreparedQuery("sync", executeMethod, {
38533
- all: (params) => {
38534
- stmt.setReturnArrays(mode === "arrays");
38535
- const res = stmt.all(...params);
38536
- if (mode === "objects") return res.map((row) => ({ ...row }));
38537
- return res;
38538
- },
38539
- get: (params) => {
38540
- stmt.setReturnArrays(mode === "arrays");
38541
- const res = stmt.get(...params);
38542
- if (res && mode === "objects") return { ...res };
38543
- return res;
38544
- },
38545
- run: (params) => {
38546
- stmt.setReturnArrays(false);
38547
- return stmt.run(...params);
38548
- },
38549
- values: (params) => {
38550
- stmt.setReturnArrays(true);
38551
- return stmt.all(...params);
38552
- }
38553
- }, query, mapper, mode, this.logger, void 0, queryMetadata, void 0);
38554
- }
38555
- transaction(transaction, config2 = {}) {
38556
- const tx = new NodeSQLiteTransaction("sync", this.dialect, this, this.relations);
38557
- this.run(sql.raw(`begin${config2.behavior ? ` ${config2.behavior}` : ""}`));
38558
- try {
38559
- const result = transaction(tx);
38560
- this.run(sql`commit`);
38561
- return result;
38562
- } catch (err) {
38563
- this.run(sql`rollback`);
38564
- throw err;
38565
- }
38566
- }
38567
- };
38568
- var NodeSQLiteTransaction = class NodeSQLiteTransaction2 extends SQLiteAsyncTransaction {
38569
- static [entityKind] = "SQLJsTransaction";
38570
- transaction(transaction) {
38571
- const savepointName = `sp${this.nestedIndex + 1}`;
38572
- const tx = new NodeSQLiteTransaction2("sync", this.dialect, this.session, this._.relations, this.nestedIndex + 1);
38573
- tx.run(sql.raw(`savepoint ${savepointName}`));
38574
- try {
38575
- const result = transaction(tx);
38576
- tx.run(sql.raw(`release savepoint ${savepointName}`));
38577
- return result;
38578
- } catch (err) {
38579
- tx.run(sql.raw(`rollback to savepoint ${savepointName}`));
38580
- throw err;
38581
- }
38582
- }
38583
- };
38584
-
38585
- // ../../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
38586
- import { DatabaseSync } from "node:sqlite";
38587
- var NodeSQLiteDatabase = class extends SQLiteAsyncDatabase {
38588
- static [entityKind] = "NodeSQLiteDatabase";
38589
- };
38590
- function construct(client2, config2 = {}) {
38591
- const dialect = new SQLiteDialect({ useJitMappers: jitCompatCheck(config2.jit) });
38592
- let logger;
38593
- if (config2.logger === true) logger = new DefaultLogger();
38594
- else if (config2.logger !== false) logger = config2.logger;
38595
- const relations = config2.relations ?? {};
38596
- const db = new NodeSQLiteDatabase("sync", dialect, new NodeSQLiteSession(client2, dialect, relations, { logger }), relations);
38597
- db.$client = client2;
38598
- return db;
38599
- }
38600
- function drizzle(...params) {
38601
- if (params[0] === void 0 || typeof params[0] === "string") return construct(params[0] === void 0 ? new DatabaseSync(":memory:") : new DatabaseSync(params[0]), params[1]);
38602
- const { connection, client: client2, ...config2 } = params[0];
38603
- if (client2) return construct(client2, config2);
38604
- if (typeof connection === "object") {
38605
- const { path: path3, ...options } = connection;
38606
- return construct(new DatabaseSync(path3 ?? ":memory:", options), config2);
38607
- }
38608
- return construct(new DatabaseSync(connection ?? ":memory:"), config2);
38609
- }
38610
- (function(_drizzle) {
38611
- function mock(config2) {
38612
- return construct({}, config2);
38613
- }
38614
- _drizzle.mock = mock;
38615
- })(drizzle || (drizzle = {}));
38616
-
38617
- // src/generated/acp-session-store-migrations.ts
38618
- var acpSessionStoreMigrations = [
38619
- {
38620
- "name": "0000_slimy_captain_midlands.sql",
38621
- "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"
38622
- },
38623
- {
38624
- "name": "0001_regular_ultimates.sql",
38625
- "sql": "ALTER TABLE `acp_session` ADD `last_terminal_command_id` text;"
38626
- },
38627
- {
38628
- "name": "0002_equal_black_queen.sql",
38629
- "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`);"
38630
- },
38631
- {
38632
- "name": "0003_silky_ravenous.sql",
38633
- "sql": "DROP TABLE `session_event_v2`;"
38634
- },
38635
- {
38636
- "name": "0004_special_mathemanic.sql",
38637
- "sql": "DROP TABLE `deleted_acp_session`;--> statement-breakpoint\nALTER TABLE `acp_session` DROP COLUMN `last_terminal_command_id`;"
38638
- }
38639
- ];
38640
-
38641
38598
  // src/schema/acp-session-store/acp-session.ts
38642
38599
  var acpSession = sqliteTable("acp_session", {
38643
38600
  sessionId: text("session_id").primaryKey(),
@@ -38650,6 +38607,216 @@ var acpSession = sqliteTable("acp_session", {
38650
38607
  updatedAt: text("updated_at").notNull()
38651
38608
  });
38652
38609
 
38610
+ // src/schema/session-event-cache/session-event-v2.ts
38611
+ var sessionEventV2 = sqliteTable(
38612
+ "session_event_v2",
38613
+ {
38614
+ eventJson: text("event_json").notNull(),
38615
+ generationId: text("generation_id").notNull(),
38616
+ position: integer2("position").notNull(),
38617
+ sessionId: text("session_id").notNull()
38618
+ },
38619
+ (table) => [
38620
+ primaryKey({ columns: [table.generationId, table.sessionId, table.position] }),
38621
+ index("session_event_v2_generation_session_position_index").on(
38622
+ table.generationId,
38623
+ table.sessionId,
38624
+ table.position
38625
+ )
38626
+ ]
38627
+ );
38628
+
38629
+ // src/acp/session-event-store-v2.ts
38630
+ var HOT_EVENT_HIGH_WATER_MARK = 256;
38631
+ var HOT_EVENT_RETENTION = 128;
38632
+ function eventPage(eventCount, eventLimit, cursor, read) {
38633
+ const parsedCursor = cursor === null ? eventCount : Number(cursor);
38634
+ if (!Number.isSafeInteger(parsedCursor) || parsedCursor < 0 || parsedCursor > eventCount) {
38635
+ throw new Error("The native event cursor is invalid");
38636
+ }
38637
+ const endPosition = parsedCursor;
38638
+ const startPosition = Math.max(0, endPosition - eventLimit);
38639
+ return {
38640
+ events: read(startPosition + 1, endPosition),
38641
+ nextCursor: startPosition === 0 ? null : startPosition.toString(),
38642
+ startPosition: startPosition + 1,
38643
+ truncated: startPosition > 0
38644
+ };
38645
+ }
38646
+ var MemoryAcpSessionEventStoreV2 = class {
38647
+ generationId;
38648
+ #events = /* @__PURE__ */ new Map();
38649
+ constructor(generationId) {
38650
+ this.generationId = generationId;
38651
+ }
38652
+ append = (sessionId, event) => {
38653
+ const events = this.#events.get(sessionId) ?? [];
38654
+ events.push(event);
38655
+ this.#events.set(sessionId, events);
38656
+ return events.length;
38657
+ };
38658
+ close = () => this.#events.clear();
38659
+ page = (sessionId, eventLimit, cursor) => {
38660
+ const events = this.#events.get(sessionId) ?? [];
38661
+ return eventPage(
38662
+ events.length,
38663
+ eventLimit,
38664
+ cursor,
38665
+ (startPosition, endPosition) => events.slice(startPosition - 1, endPosition)
38666
+ );
38667
+ };
38668
+ remove = (sessionId) => {
38669
+ this.#events.delete(sessionId);
38670
+ };
38671
+ reset = this.remove;
38672
+ };
38673
+ var cachedEventRowSchema = external_exports.object({ eventJson: external_exports.string(), position: external_exports.number().int().positive() });
38674
+ function decodeCachedEvent(value) {
38675
+ const payload = external_exports.record(external_exports.string(), external_exports.unknown()).parse(value);
38676
+ const event = decodeSessionEventV2({
38677
+ ...payload,
38678
+ eventId: "cached-event",
38679
+ position: "1",
38680
+ provenance: { kind: "original" },
38681
+ recordedAt: "1970-01-01T00:00:00.000Z",
38682
+ sessionId: "cached-session"
38683
+ });
38684
+ return event.type === "acp" ? { payload: event.payload, type: event.type } : { payload: event.payload, type: event.type };
38685
+ }
38686
+ var CachedAcpSessionEventStoreV2 = class {
38687
+ generationId;
38688
+ #database;
38689
+ #ignoredPersistedSessions = /* @__PURE__ */ new Set();
38690
+ #localDatabase;
38691
+ #sessions = /* @__PURE__ */ new Map();
38692
+ #flushSchedule = { kind: "idle" };
38693
+ #isLocalDBAvailable = true;
38694
+ constructor(localDatabase, generationId) {
38695
+ this.generationId = generationId;
38696
+ this.#localDatabase = localDatabase;
38697
+ this.#database = localDatabase.orm;
38698
+ try {
38699
+ this.#localDatabase.transaction(() => this.#database.delete(sessionEventV2).run());
38700
+ } catch (error62) {
38701
+ this.#localDatabase.close();
38702
+ throw error62;
38703
+ }
38704
+ }
38705
+ append = (sessionId, event) => {
38706
+ if (this.#flushSchedule.kind === "closed") {
38707
+ throw new Error("The V2 Session event store is closed");
38708
+ }
38709
+ const session = this.#sessions.get(sessionId) ?? { hot: [], nextPosition: 1 };
38710
+ const position = session.nextPosition;
38711
+ session.hot.push({ event, position });
38712
+ session.nextPosition += 1;
38713
+ this.#sessions.set(sessionId, session);
38714
+ if (session.hot.length > HOT_EVENT_HIGH_WATER_MARK) {
38715
+ this.#scheduleFlush();
38716
+ }
38717
+ return position;
38718
+ };
38719
+ #scheduleFlush = () => {
38720
+ if (!this.#isLocalDBAvailable || this.#flushSchedule.kind !== "idle") {
38721
+ return;
38722
+ }
38723
+ const handle = setImmediate(() => {
38724
+ if (this.#flushSchedule.kind !== "scheduled" || this.#flushSchedule.handle !== handle) {
38725
+ return;
38726
+ }
38727
+ this.#flushSchedule = { kind: "idle" };
38728
+ this.#flush(false);
38729
+ });
38730
+ this.#flushSchedule = { handle, kind: "scheduled" };
38731
+ };
38732
+ #flush = (includeHotTail) => {
38733
+ if (!this.#isLocalDBAvailable || this.#flushSchedule.kind === "closed") {
38734
+ return;
38735
+ }
38736
+ const batches = [...this.#sessions.entries()].flatMap(([sessionId, session]) => {
38737
+ const count = includeHotTail ? session.hot.length : Math.max(0, session.hot.length - HOT_EVENT_RETENTION);
38738
+ return count === 0 ? [] : [{ count, events: session.hot.slice(0, count), sessionId }];
38739
+ });
38740
+ const values = batches.flatMap(
38741
+ (batch) => batch.events.map(({ event, position }) => ({
38742
+ eventJson: JSON.stringify(event),
38743
+ generationId: this.generationId,
38744
+ position,
38745
+ sessionId: batch.sessionId
38746
+ }))
38747
+ );
38748
+ if (values.length === 0) {
38749
+ return;
38750
+ }
38751
+ try {
38752
+ this.#localDatabase.transaction(() => {
38753
+ for (let offset = 0; offset < values.length; offset += 200) {
38754
+ this.#database.insert(sessionEventV2).values(values.slice(offset, offset + 200)).run();
38755
+ }
38756
+ });
38757
+ for (const batch of batches) {
38758
+ this.#sessions.get(batch.sessionId)?.hot.splice(0, batch.count);
38759
+ }
38760
+ } catch (cause) {
38761
+ this.#isLocalDBAvailable = false;
38762
+ console.warn("Mobius V2 Session event cache writes are unavailable; retaining events in memory", cause);
38763
+ }
38764
+ };
38765
+ page = (sessionId, eventLimit, cursor) => {
38766
+ const session = this.#sessions.get(sessionId);
38767
+ const eventCount = (session?.nextPosition ?? 1) - 1;
38768
+ return eventPage(eventCount, eventLimit, cursor, (startPosition, endPosition) => {
38769
+ const persisted = this.#ignoredPersistedSessions.has(sessionId) ? [] : this.#database.select({ eventJson: sessionEventV2.eventJson, position: sessionEventV2.position }).from(sessionEventV2).where(
38770
+ and(
38771
+ eq(sessionEventV2.generationId, this.generationId),
38772
+ eq(sessionEventV2.sessionId, sessionId),
38773
+ gte(sessionEventV2.position, startPosition),
38774
+ lte(sessionEventV2.position, endPosition)
38775
+ )
38776
+ ).orderBy(asc(sessionEventV2.position)).all().map((value) => {
38777
+ const row = cachedEventRowSchema.parse(value);
38778
+ return { event: decodeCachedEvent(JSON.parse(row.eventJson)), position: row.position };
38779
+ });
38780
+ const hot = (session?.hot ?? []).filter(
38781
+ ({ position }) => position >= startPosition && position <= endPosition
38782
+ );
38783
+ return [...persisted, ...hot].toSorted((left, right) => left.position - right.position).map(({ event }) => event);
38784
+ });
38785
+ };
38786
+ #deletePersisted = (sessionId) => {
38787
+ if (!this.#isLocalDBAvailable) {
38788
+ this.#ignoredPersistedSessions.add(sessionId);
38789
+ return;
38790
+ }
38791
+ try {
38792
+ this.#database.delete(sessionEventV2).where(and(eq(sessionEventV2.generationId, this.generationId), eq(sessionEventV2.sessionId, sessionId))).run();
38793
+ this.#ignoredPersistedSessions.delete(sessionId);
38794
+ } catch (cause) {
38795
+ this.#isLocalDBAvailable = false;
38796
+ this.#ignoredPersistedSessions.add(sessionId);
38797
+ console.warn("Mobius V2 Session event cache writes are unavailable; retaining events in memory", cause);
38798
+ }
38799
+ };
38800
+ remove = (sessionId) => {
38801
+ this.#deletePersisted(sessionId);
38802
+ this.#sessions.delete(sessionId);
38803
+ };
38804
+ reset = this.remove;
38805
+ close = () => {
38806
+ if (this.#flushSchedule.kind === "closed") {
38807
+ return;
38808
+ }
38809
+ if (this.#flushSchedule.kind === "scheduled") {
38810
+ clearImmediate(this.#flushSchedule.handle);
38811
+ }
38812
+ this.#flushSchedule = { kind: "idle" };
38813
+ this.#flush(true);
38814
+ this.#flushSchedule = { kind: "closed" };
38815
+ this.#localDatabase.close();
38816
+ this.#sessions.clear();
38817
+ };
38818
+ };
38819
+
38653
38820
  // src/acp/session-store.ts
38654
38821
  var AcpStoredSession = class {
38655
38822
  additionalDirectories;
@@ -38685,9 +38852,14 @@ var FoundAcpStoredSession = class extends AcpStoredSessionLookup {
38685
38852
  }
38686
38853
  };
38687
38854
  var MemoryAcpSessionStore = class {
38855
+ eventsV2;
38688
38856
  #sessions = /* @__PURE__ */ new Map();
38857
+ constructor(eventsV2 = new MemoryAcpSessionEventStoreV2(randomUUID2())) {
38858
+ this.eventsV2 = eventsV2;
38859
+ }
38689
38860
  close = () => {
38690
38861
  this.#sessions.clear();
38862
+ this.eventsV2.close();
38691
38863
  };
38692
38864
  findNative = (agentId, nativeSessionId) => [...this.#sessions.values()].filter(
38693
38865
  (session) => session.agentId === agentId && session.nativeSessionId === nativeSessionId
@@ -38699,6 +38871,7 @@ var MemoryAcpSessionStore = class {
38699
38871
  };
38700
38872
  remove = (sessionId) => {
38701
38873
  this.#sessions.delete(sessionId);
38874
+ this.eventsV2.remove(sessionId);
38702
38875
  };
38703
38876
  write = (session) => {
38704
38877
  this.#sessions.set(session.sessionId, session);
@@ -38730,39 +38903,20 @@ function decodeStoredSession(value) {
38730
38903
  );
38731
38904
  }
38732
38905
  var SqliteAcpSessionStore = class {
38906
+ eventsV2;
38733
38907
  #database;
38734
- #sqliteDatabase;
38735
- constructor(path3) {
38736
- mkdirSync(dirname4(path3), { mode: 448, recursive: true });
38737
- this.#sqliteDatabase = new DatabaseSync2(path3);
38738
- chmodSync(path3, 384);
38739
- this.#migrate();
38740
- this.#database = drizzle({ client: this.#sqliteDatabase });
38908
+ #localDatabase;
38909
+ constructor(localDatabase, eventsV2 = new MemoryAcpSessionEventStoreV2(randomUUID2())) {
38910
+ this.eventsV2 = eventsV2;
38911
+ this.#localDatabase = localDatabase;
38912
+ this.#database = localDatabase.orm;
38741
38913
  }
38742
- #migrate = () => {
38743
- const version2 = external_exports.object({ user_version: external_exports.number().int().nonnegative() }).parse(this.#sqliteDatabase.prepare("PRAGMA user_version").get()).user_version;
38744
- if (version2 > acpSessionStoreMigrations.length) {
38745
- this.#sqliteDatabase.close();
38746
- throw new Error("The ACP Session database was created by a newer Mobius version");
38747
- }
38748
- for (let index = version2; index < acpSessionStoreMigrations.length; index += 1) {
38749
- const migration = acpSessionStoreMigrations[index];
38750
- if (migration === void 0) {
38751
- throw new Error("The ACP Session migration is unavailable");
38752
- }
38753
- this.#sqliteDatabase.exec("BEGIN IMMEDIATE");
38754
- try {
38755
- this.#sqliteDatabase.exec(migration.sql);
38756
- this.#sqliteDatabase.exec(`PRAGMA user_version = ${index + 1}`);
38757
- this.#sqliteDatabase.exec("COMMIT");
38758
- } catch (error62) {
38759
- this.#sqliteDatabase.exec("ROLLBACK");
38760
- throw error62;
38761
- }
38762
- }
38763
- };
38764
38914
  close = () => {
38765
- this.#sqliteDatabase.close();
38915
+ try {
38916
+ this.#localDatabase.close();
38917
+ } finally {
38918
+ this.eventsV2.close();
38919
+ }
38766
38920
  };
38767
38921
  findNative = (agentId, nativeSessionId) => this.#database.select().from(acpSession).where(and(eq(acpSession.agentId, agentId), eq(acpSession.nativeSessionId, nativeSessionId))).all().map(decodeStoredSession);
38768
38922
  list = () => this.#database.select().from(acpSession).orderBy(desc(acpSession.updatedAt)).all().map(decodeStoredSession);
@@ -38772,6 +38926,7 @@ var SqliteAcpSessionStore = class {
38772
38926
  };
38773
38927
  remove = (sessionId) => {
38774
38928
  this.#database.delete(acpSession).where(eq(acpSession.sessionId, sessionId)).run();
38929
+ this.eventsV2.remove(sessionId);
38775
38930
  };
38776
38931
  write = (session) => {
38777
38932
  const value = {
@@ -38797,7 +38952,7 @@ var RetryableAcpInitializationError = class extends AcpExecutionError {
38797
38952
  }
38798
38953
  };
38799
38954
  function arraysEqual(left, right) {
38800
- return left.length === right.length && left.every((value, index) => value === right[index]);
38955
+ return left.length === right.length && left.every((value, index2) => value === right[index2]);
38801
38956
  }
38802
38957
  function recordsEqual(left, right) {
38803
38958
  const leftEntries = Object.entries(left);
@@ -38960,12 +39115,17 @@ var AgentSession = class _AgentSession {
38960
39115
  );
38961
39116
  }
38962
39117
  const history = await this.#completedHistory(signal, "ACP agent exited while loading history");
38963
- return history.eventPage(eventLimit, cursor, this.#turnHistory);
39118
+ return history.eventPage(eventLimit, cursor);
38964
39119
  };
38965
39120
  async #completedHistory(signal, exitMessage) {
38966
39121
  if (!this.#prompted && this.#nativeHistoryOwnership.kind === "fresh-session") {
38967
39122
  if (this.#sessionLoad.kind === "not-requested") {
38968
- this.#sessionLoad = { history: new AcpHistoryReplay(), kind: "loaded", response: {} };
39123
+ this.#store.eventsV2.reset(this.#mobiusSessionId);
39124
+ this.#sessionLoad = {
39125
+ history: new AcpHistoryReplay(this.#store.eventsV2, this.#mobiusSessionId),
39126
+ kind: "loaded",
39127
+ response: {}
39128
+ };
38969
39129
  }
38970
39130
  if (this.#sessionLoad.kind === "loaded") {
38971
39131
  return this.#sessionLoad.history;
@@ -38980,7 +39140,8 @@ var AgentSession = class _AgentSession {
38980
39140
  if (this.#sessionLoad.kind === "capturing") {
38981
39141
  return await waitForSharedOperation(this.#sessionLoad.completion, signal);
38982
39142
  }
38983
- const history = new AcpHistoryReplay();
39143
+ this.#store.eventsV2.reset(this.#mobiusSessionId);
39144
+ const history = new AcpHistoryReplay(this.#store.eventsV2, this.#mobiusSessionId);
38984
39145
  const completion = Promise.resolve().then(async () => {
38985
39146
  try {
38986
39147
  const response = await this.race(
@@ -39455,7 +39616,7 @@ var AgentSession = class _AgentSession {
39455
39616
  this.prepareAgentContent
39456
39617
  );
39457
39618
  this.#turn = running;
39458
- this.#turnHistory = completedHistory === null ? null : new AcpHistoryReplay();
39619
+ this.#turnHistory = completedHistory === null ? null : new AcpHistoryReplay(this.#store.eventsV2, this.#mobiusSessionId);
39459
39620
  const lifecycleV2 = options.lifecycleV2;
39460
39621
  if (lifecycleV2 !== void 0) {
39461
39622
  await this.#recordLifecycleEventV2({
@@ -39668,7 +39829,7 @@ var AgentSession = class _AgentSession {
39668
39829
  if (event.type !== "lifecycle-metadata" || this.#sessionLoad.kind !== "loaded") {
39669
39830
  return;
39670
39831
  }
39671
- const position = this.#turnHistory === null ? this.#sessionLoad.history.recordLifecycle(event) : this.#sessionLoad.history.eventCount() + this.#turnHistory.recordLifecycle(event);
39832
+ const position = this.#turnHistory === null ? this.#sessionLoad.history.recordLifecycle(event) : this.#turnHistory.recordLifecycle(event);
39672
39833
  await this.#getObserver().onSessionEventV2?.(this.#mobiusSessionId, event, position);
39673
39834
  };
39674
39835
  selectNativeSession = (sessionId) => {
@@ -39689,13 +39850,8 @@ var AgentSession = class _AgentSession {
39689
39850
  } else {
39690
39851
  const onSessionEventV2 = this.#getObserver().onSessionEventV2;
39691
39852
  if (this.#turnHistory !== null) {
39692
- const completedEventCount = this.#sessionLoad.kind === "loaded" ? this.#sessionLoad.history.eventCount() : 0;
39693
- await this.#turnHistory.record(update, rawUpdate, async (turnPosition) => {
39694
- await onSessionEventV2?.(
39695
- this.#mobiusSessionId,
39696
- { payload: rawUpdate, type: "acp" },
39697
- completedEventCount + turnPosition
39698
- );
39853
+ await this.#turnHistory.record(update, rawUpdate, async (position) => {
39854
+ await onSessionEventV2?.(this.#mobiusSessionId, { payload: rawUpdate, type: "acp" }, position);
39699
39855
  });
39700
39856
  } else if (this.#sessionLoad.kind === "loaded") {
39701
39857
  await this.#sessionLoad.history.record(update, rawUpdate, async (position) => {
@@ -40338,9 +40494,9 @@ var AcpContentExternalizer = class {
40338
40494
  };
40339
40495
 
40340
40496
  // src/external-content/local-external-content-store.ts
40341
- import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
40497
+ import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
40342
40498
  import { lstat, mkdir as mkdir6, readdir as readdir3, realpath as realpath8, rename as rename4, rm as rm3, stat as stat7, utimes, writeFile as writeFile4 } from "node:fs/promises";
40343
- import { dirname as dirname5, join as join16 } from "node:path";
40499
+ import { dirname as dirname4, join as join16 } from "node:path";
40344
40500
  var contentRequest = /^mobius-content:(image|audio|resource):([a-f0-9]{64})$/u;
40345
40501
  var CONTENT_LIFETIME_MILLISECONDS = 24 * 60 * 60 * 1e3;
40346
40502
  var metadataSchema2 = external_exports.strictObject({
@@ -40359,7 +40515,7 @@ var UnretainedExternalContentStore = class {
40359
40515
  };
40360
40516
  };
40361
40517
  async function atomicWrite(path3, bytes, signal) {
40362
- const temporary = `${path3}.${randomUUID2()}.tmp`;
40518
+ const temporary = `${path3}.${randomUUID3()}.tmp`;
40363
40519
  try {
40364
40520
  await writeFile4(temporary, bytes, { mode: 384, signal });
40365
40521
  signal.throwIfAborted();
@@ -40376,7 +40532,7 @@ var LocalExternalContentStore = class {
40376
40532
  #expirationTimer;
40377
40533
  #cleanup = Promise.resolve();
40378
40534
  constructor(stateDirectory) {
40379
- this.#root = join16(stateDirectory, "tmp", "session-content", randomUUID2());
40535
+ this.#root = join16(stateDirectory, "tmp", "session-content", randomUUID3());
40380
40536
  this.#expirationTimer = setInterval(() => {
40381
40537
  void this.#expire().catch(() => void 0);
40382
40538
  }, 6e4);
@@ -40387,11 +40543,11 @@ var LocalExternalContentStore = class {
40387
40543
  await mkdir6(this.#root, { mode: 448, recursive: true });
40388
40544
  const now = /* @__PURE__ */ new Date();
40389
40545
  await utimes(this.#root, now, now);
40390
- for (const directory of await readdir3(dirname5(this.#root), { withFileTypes: true })) {
40546
+ for (const directory of await readdir3(dirname4(this.#root), { withFileTypes: true })) {
40391
40547
  if (!directory.isDirectory() || !/^[a-f0-9-]{36}$/u.test(directory.name)) {
40392
40548
  continue;
40393
40549
  }
40394
- const path3 = join16(dirname5(this.#root), directory.name);
40550
+ const path3 = join16(dirname4(this.#root), directory.name);
40395
40551
  if (path3 === this.#root) {
40396
40552
  continue;
40397
40553
  }
@@ -40477,12 +40633,12 @@ var LocalExternalContentStore = class {
40477
40633
  }
40478
40634
  try {
40479
40635
  const [resolvedDirectory, resolvedPath, file2] = await Promise.all([
40480
- realpath8(dirname5(entry.path)),
40636
+ realpath8(dirname4(entry.path)),
40481
40637
  realpath8(entry.path),
40482
40638
  lstat(entry.path)
40483
40639
  ]);
40484
40640
  signal.throwIfAborted();
40485
- if (!file2.isFile() || file2.isSymbolicLink() || dirname5(resolvedPath) !== resolvedDirectory) {
40641
+ if (!file2.isFile() || file2.isSymbolicLink() || dirname4(resolvedPath) !== resolvedDirectory) {
40486
40642
  return null;
40487
40643
  }
40488
40644
  return { mediaType: entry.mediaType, name: entry.name, path: resolvedPath };
@@ -40559,9 +40715,9 @@ var AcpProcessCapacityLock = class {
40559
40715
  return await waiter.completion.promise;
40560
40716
  } finally {
40561
40717
  signal.removeEventListener("abort", waiter.cancel);
40562
- const index = this.#waiters.indexOf(waiter);
40563
- if (index >= 0) {
40564
- this.#waiters.splice(index, 1);
40718
+ const index2 = this.#waiters.indexOf(waiter);
40719
+ if (index2 >= 0) {
40720
+ this.#waiters.splice(index2, 1);
40565
40721
  }
40566
40722
  }
40567
40723
  };
@@ -41921,7 +42077,7 @@ var FixedInstallationExecutor = class {
41921
42077
  // src/authorization/workspace-directory.ts
41922
42078
  import { readdir as readdir4, realpath as realpath9, stat as stat8 } from "node:fs/promises";
41923
42079
  import { homedir as homedir2 } from "node:os";
41924
- import { basename as basename4, dirname as dirname6, isAbsolute as isAbsolute9, join as join17, normalize as normalize3, relative as relative4 } from "node:path";
42080
+ import { basename as basename4, dirname as dirname5, isAbsolute as isAbsolute9, join as join17, normalize as normalize3, relative as relative4 } from "node:path";
41925
42081
 
41926
42082
  // src/authorization/local-authorization-error.ts
41927
42083
  var LocalAuthorizationError = class extends Error {
@@ -42060,7 +42216,7 @@ var WorkspaceDirectoryService = class {
42060
42216
  }
42061
42217
  }
42062
42218
  entries.sort((a, b) => a.name.localeCompare(b.name));
42063
- const parent = dirname6(target);
42219
+ const parent = dirname5(target);
42064
42220
  return new WorkspaceDirectoryListing(
42065
42221
  id,
42066
42222
  this.label(target),
@@ -42085,7 +42241,7 @@ var WorkspaceDirectoryService = class {
42085
42241
  };
42086
42242
 
42087
42243
  // src/daemon-diagnostic-log.ts
42088
- import { appendFileSync, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
42244
+ import { appendFileSync, mkdirSync, readFileSync as readFileSync2, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
42089
42245
  import { join as join18 } from "node:path";
42090
42246
  var MAXIMUM_DAEMON_LOG_BYTES = 1 * 1024 * 1024;
42091
42247
  var DaemonDiagnosticLog = class {
@@ -42101,7 +42257,7 @@ var DaemonDiagnosticLog = class {
42101
42257
  const encoded = `${diagnostic.replace(/[\r\n]+/gu, " ").trim()}
42102
42258
  `;
42103
42259
  const encodedBytes = Buffer.byteLength(encoded);
42104
- mkdirSync2(this.#directory, { mode: 448, recursive: true });
42260
+ mkdirSync(this.#directory, { mode: 448, recursive: true });
42105
42261
  let existingBytes = 0;
42106
42262
  try {
42107
42263
  existingBytes = statSync3(this.#path).size;
@@ -42566,7 +42722,7 @@ var DaemonInstallationObserver = class {
42566
42722
  };
42567
42723
 
42568
42724
  // src/daemon-active-turn.ts
42569
- import { randomUUID as randomUUID3 } from "node:crypto";
42725
+ import { randomUUID as randomUUID4 } from "node:crypto";
42570
42726
  function activeMessageCharacters(message) {
42571
42727
  return message.text.length + (message.role === "assistant" ? JSON.stringify(message.activities).length + JSON.stringify(message.content).length : 0);
42572
42728
  }
@@ -42574,8 +42730,8 @@ var ACTIVE_TURN_TEXT_CHUNK_LIMIT = Math.floor(SESSION_HISTORY_CHARACTER_LIMIT /
42574
42730
  function boundedRecoveryMessages(messages) {
42575
42731
  const selected = [];
42576
42732
  let remainingCharacters = SESSION_HISTORY_CHARACTER_LIMIT;
42577
- for (let index = messages.length - 1; index >= 0 && selected.length < SESSION_HISTORY_MESSAGE_LIMIT; index -= 1) {
42578
- const message = messages[index];
42733
+ for (let index2 = messages.length - 1; index2 >= 0 && selected.length < SESSION_HISTORY_MESSAGE_LIMIT; index2 -= 1) {
42734
+ const message = messages[index2];
42579
42735
  if (message === void 0) {
42580
42736
  break;
42581
42737
  }
@@ -42600,7 +42756,7 @@ var ActiveDaemonTurn = class {
42600
42756
  #timeline;
42601
42757
  #sequence = 0;
42602
42758
  #interaction = null;
42603
- #epoch = decodeIdentifier(randomUUID3());
42759
+ #epoch = decodeIdentifier(randomUUID4());
42604
42760
  constructor(command, attemptId) {
42605
42761
  this.attemptId = attemptId;
42606
42762
  this.command = command;
@@ -42662,7 +42818,7 @@ var ActiveDaemonTurn = class {
42662
42818
  if (!this.#activities.has(event.activityId)) {
42663
42819
  this.#timeline = [
42664
42820
  ...this.#timeline,
42665
- { activityId: event.activityId, id: decodeIdentifier(randomUUID3()), kind: "activity" }
42821
+ { activityId: event.activityId, id: decodeIdentifier(randomUUID4()), kind: "activity" }
42666
42822
  ];
42667
42823
  }
42668
42824
  this.#activities.set(event.activityId, {
@@ -42683,7 +42839,7 @@ var ActiveDaemonTurn = class {
42683
42839
  if (previous === void 0) {
42684
42840
  this.#timeline = [
42685
42841
  ...this.#timeline,
42686
- { activityId: event.activityId, id: decodeIdentifier(randomUUID3()), kind: "activity" }
42842
+ { activityId: event.activityId, id: decodeIdentifier(randomUUID4()), kind: "activity" }
42687
42843
  ];
42688
42844
  }
42689
42845
  this.#activities.set(event.activityId, {
@@ -42708,7 +42864,7 @@ var ActiveDaemonTurn = class {
42708
42864
  ...this.#timeline,
42709
42865
  {
42710
42866
  content: /* @__PURE__ */ new Map([[event.contentId, event.content]]),
42711
- id: decodeIdentifier(randomUUID3()),
42867
+ id: decodeIdentifier(randomUUID4()),
42712
42868
  kind: "message",
42713
42869
  sourceMessageId: event.messageId,
42714
42870
  text: ""
@@ -42716,7 +42872,7 @@ var ActiveDaemonTurn = class {
42716
42872
  ];
42717
42873
  } else {
42718
42874
  this.#timeline = this.#timeline.map(
42719
- (entry, index) => index === target && entry.kind === "message" ? { ...entry, content: new Map([...entry.content, [event.contentId, event.content]]) } : entry
42875
+ (entry, index2) => index2 === target && entry.kind === "message" ? { ...entry, content: new Map([...entry.content, [event.contentId, event.content]]) } : entry
42720
42876
  );
42721
42877
  }
42722
42878
  } else if (event.kind === SESSION_PERMISSION_REQUESTED_KIND || event.kind === SESSION_ELICITATION_REQUESTED_KIND) {
@@ -42748,7 +42904,7 @@ var ActiveDaemonTurn = class {
42748
42904
  ...this.#timeline,
42749
42905
  {
42750
42906
  content: /* @__PURE__ */ new Map(),
42751
- id: decodeIdentifier(randomUUID3()),
42907
+ id: decodeIdentifier(randomUUID4()),
42752
42908
  kind: "message",
42753
42909
  sourceMessageId: messageId,
42754
42910
  text: remaining.slice(0, ACTIVE_TURN_TEXT_CHUNK_LIMIT)
@@ -43019,6 +43175,202 @@ var DaemonTurnRegistry = class {
43019
43175
  };
43020
43176
  };
43021
43177
 
43178
+ // src/generated/acp-session-store-migrations.ts
43179
+ var acpSessionStoreMigrations = [
43180
+ {
43181
+ "name": "0000_slimy_captain_midlands.sql",
43182
+ "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"
43183
+ },
43184
+ {
43185
+ "name": "0001_regular_ultimates.sql",
43186
+ "sql": "ALTER TABLE `acp_session` ADD `last_terminal_command_id` text;"
43187
+ },
43188
+ {
43189
+ "name": "0002_equal_black_queen.sql",
43190
+ "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`);"
43191
+ },
43192
+ {
43193
+ "name": "0003_silky_ravenous.sql",
43194
+ "sql": "DROP TABLE `session_event_v2`;"
43195
+ },
43196
+ {
43197
+ "name": "0004_special_mathemanic.sql",
43198
+ "sql": "DROP TABLE `deleted_acp_session`;--> statement-breakpoint\nALTER TABLE `acp_session` DROP COLUMN `last_terminal_command_id`;"
43199
+ }
43200
+ ];
43201
+
43202
+ // src/generated/session-event-cache-migrations.ts
43203
+ var sessionEventCacheMigrations = [
43204
+ {
43205
+ "name": "migration.sql",
43206
+ "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`);"
43207
+ }
43208
+ ];
43209
+
43210
+ // src/infra/local-sqlite-database.ts
43211
+ import { chmodSync, mkdirSync as mkdirSync2 } from "node:fs";
43212
+ import { dirname as dirname6 } from "node:path";
43213
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
43214
+
43215
+ // ../../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
43216
+ var NodeSQLiteSession = class extends SQLiteAsyncSession {
43217
+ static [entityKind] = "SQLJsSession";
43218
+ logger;
43219
+ constructor(client2, dialect, relations, options = {}) {
43220
+ super(dialect, "sync");
43221
+ this.client = client2;
43222
+ this.relations = relations;
43223
+ this.options = options;
43224
+ this.logger = options.logger ?? new NoopLogger();
43225
+ }
43226
+ prepareQuery(query, mode, _prepare, executeMethod, mapper, queryMetadata) {
43227
+ let stmt;
43228
+ try {
43229
+ stmt = this.client.prepare(query.sql);
43230
+ } catch (e) {
43231
+ throw new DrizzleQueryError(query.sql, query.params, e);
43232
+ }
43233
+ return new SQLiteAsyncPreparedQuery("sync", executeMethod, {
43234
+ all: (params) => {
43235
+ stmt.setReturnArrays(mode === "arrays");
43236
+ const res = stmt.all(...params);
43237
+ if (mode === "objects") return res.map((row) => ({ ...row }));
43238
+ return res;
43239
+ },
43240
+ get: (params) => {
43241
+ stmt.setReturnArrays(mode === "arrays");
43242
+ const res = stmt.get(...params);
43243
+ if (res && mode === "objects") return { ...res };
43244
+ return res;
43245
+ },
43246
+ run: (params) => {
43247
+ stmt.setReturnArrays(false);
43248
+ return stmt.run(...params);
43249
+ },
43250
+ values: (params) => {
43251
+ stmt.setReturnArrays(true);
43252
+ return stmt.all(...params);
43253
+ }
43254
+ }, query, mapper, mode, this.logger, void 0, queryMetadata, void 0);
43255
+ }
43256
+ transaction(transaction, config2 = {}) {
43257
+ const tx = new NodeSQLiteTransaction("sync", this.dialect, this, this.relations);
43258
+ this.run(sql.raw(`begin${config2.behavior ? ` ${config2.behavior}` : ""}`));
43259
+ try {
43260
+ const result = transaction(tx);
43261
+ this.run(sql`commit`);
43262
+ return result;
43263
+ } catch (err) {
43264
+ this.run(sql`rollback`);
43265
+ throw err;
43266
+ }
43267
+ }
43268
+ };
43269
+ var NodeSQLiteTransaction = class NodeSQLiteTransaction2 extends SQLiteAsyncTransaction {
43270
+ static [entityKind] = "SQLJsTransaction";
43271
+ transaction(transaction) {
43272
+ const savepointName = `sp${this.nestedIndex + 1}`;
43273
+ const tx = new NodeSQLiteTransaction2("sync", this.dialect, this.session, this._.relations, this.nestedIndex + 1);
43274
+ tx.run(sql.raw(`savepoint ${savepointName}`));
43275
+ try {
43276
+ const result = transaction(tx);
43277
+ tx.run(sql.raw(`release savepoint ${savepointName}`));
43278
+ return result;
43279
+ } catch (err) {
43280
+ tx.run(sql.raw(`rollback to savepoint ${savepointName}`));
43281
+ throw err;
43282
+ }
43283
+ }
43284
+ };
43285
+
43286
+ // ../../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
43287
+ import { DatabaseSync } from "node:sqlite";
43288
+ var NodeSQLiteDatabase = class extends SQLiteAsyncDatabase {
43289
+ static [entityKind] = "NodeSQLiteDatabase";
43290
+ };
43291
+ function construct(client2, config2 = {}) {
43292
+ const dialect = new SQLiteDialect({ useJitMappers: jitCompatCheck(config2.jit) });
43293
+ let logger;
43294
+ if (config2.logger === true) logger = new DefaultLogger();
43295
+ else if (config2.logger !== false) logger = config2.logger;
43296
+ const relations = config2.relations ?? {};
43297
+ const db = new NodeSQLiteDatabase("sync", dialect, new NodeSQLiteSession(client2, dialect, relations, { logger }), relations);
43298
+ db.$client = client2;
43299
+ return db;
43300
+ }
43301
+ function drizzle(...params) {
43302
+ if (params[0] === void 0 || typeof params[0] === "string") return construct(params[0] === void 0 ? new DatabaseSync(":memory:") : new DatabaseSync(params[0]), params[1]);
43303
+ const { connection, client: client2, ...config2 } = params[0];
43304
+ if (client2) return construct(client2, config2);
43305
+ if (typeof connection === "object") {
43306
+ const { path: path3, ...options } = connection;
43307
+ return construct(new DatabaseSync(path3 ?? ":memory:", options), config2);
43308
+ }
43309
+ return construct(new DatabaseSync(connection ?? ":memory:"), config2);
43310
+ }
43311
+ (function(_drizzle) {
43312
+ function mock(config2) {
43313
+ return construct({}, config2);
43314
+ }
43315
+ _drizzle.mock = mock;
43316
+ })(drizzle || (drizzle = {}));
43317
+
43318
+ // src/infra/local-sqlite-database.ts
43319
+ var LocalSqliteDatabase = class {
43320
+ orm;
43321
+ #sqlite;
43322
+ constructor(path3, label, migrations, pragmas = []) {
43323
+ mkdirSync2(dirname6(path3), { mode: 448, recursive: true });
43324
+ this.#sqlite = new DatabaseSync2(path3);
43325
+ chmodSync(path3, 384);
43326
+ try {
43327
+ for (const pragma of pragmas) {
43328
+ this.#sqlite.exec(pragma);
43329
+ }
43330
+ this.#migrate(label, migrations);
43331
+ this.orm = drizzle({ client: this.#sqlite });
43332
+ } catch (error62) {
43333
+ this.#sqlite.close();
43334
+ throw error62;
43335
+ }
43336
+ }
43337
+ #migrate = (label, migrations) => {
43338
+ const version2 = external_exports.object({ user_version: external_exports.number().int().nonnegative() }).parse(this.#sqlite.prepare("PRAGMA user_version").get()).user_version;
43339
+ if (version2 > migrations.length) {
43340
+ throw new Error(`The ${label} was created by a newer Mobius version`);
43341
+ }
43342
+ for (let index2 = version2; index2 < migrations.length; index2 += 1) {
43343
+ const migration = migrations[index2];
43344
+ if (migration === void 0) {
43345
+ throw new Error(`The ${label} migration is unavailable`);
43346
+ }
43347
+ this.transaction(() => {
43348
+ this.#sqlite.exec(migration.sql);
43349
+ this.#sqlite.exec(`PRAGMA user_version = ${index2 + 1}`);
43350
+ });
43351
+ }
43352
+ };
43353
+ transaction = (operation) => {
43354
+ this.#sqlite.exec("BEGIN IMMEDIATE");
43355
+ try {
43356
+ const result = operation();
43357
+ this.#sqlite.exec("COMMIT");
43358
+ return result;
43359
+ } catch (error62) {
43360
+ this.#sqlite.exec("ROLLBACK");
43361
+ throw error62;
43362
+ }
43363
+ };
43364
+ close = () => this.#sqlite.close();
43365
+ };
43366
+
43367
+ // src/local-databases.ts
43368
+ var openAcpSessionDatabase = (path3) => new LocalSqliteDatabase(path3, "ACP Session database", acpSessionStoreMigrations);
43369
+ var openSessionEventCacheV2Database = (path3) => new LocalSqliteDatabase(path3, "V2 Session event cache", sessionEventCacheMigrations, [
43370
+ "PRAGMA journal_mode = WAL",
43371
+ "PRAGMA synchronous = OFF"
43372
+ ]);
43373
+
43022
43374
  // src/native-sessions/codex-history.ts
43023
43375
  import { spawn as spawn5 } from "node:child_process";
43024
43376
  var responseSchema = external_exports.union([
@@ -43723,7 +44075,7 @@ var readCodexFullHistory = async (agent, cwd, nativeSessionId, signal, nativeTur
43723
44075
  });
43724
44076
 
43725
44077
  // src/native-sessions/service.ts
43726
- import { randomUUID as randomUUID4 } from "node:crypto";
44078
+ import { randomUUID as randomUUID5 } from "node:crypto";
43727
44079
  var NativeSessionService = class {
43728
44080
  #entries = /* @__PURE__ */ new Map();
43729
44081
  #cursors = /* @__PURE__ */ new Map();
@@ -43782,7 +44134,7 @@ var NativeSessionService = class {
43782
44134
  if (authorized === null) {
43783
44135
  return null;
43784
44136
  }
43785
- const entryId = decodeIdentifier(randomUUID4());
44137
+ const entryId = decodeIdentifier(randomUUID5());
43786
44138
  if (this.#entries.size >= 5e3) {
43787
44139
  this.#entries.clear();
43788
44140
  }
@@ -43838,7 +44190,7 @@ var NativeSessionService = class {
43838
44190
  "invalid_native_session_response"
43839
44191
  );
43840
44192
  }
43841
- nextCursor = decodeIdentifier(randomUUID4());
44193
+ nextCursor = decodeIdentifier(randomUUID5());
43842
44194
  if (this.#cursors.size >= 500) {
43843
44195
  this.#cursors.clear();
43844
44196
  }
@@ -44016,7 +44368,7 @@ var NativeSessionService = class {
44016
44368
  resolveTarget = async (command, options, selected) => {
44017
44369
  let cursor = null;
44018
44370
  const visited = /* @__PURE__ */ new Set();
44019
- for (let index = 0; index < 100; index += 1) {
44371
+ for (let index2 = 0; index2 < 100; index2 += 1) {
44020
44372
  const page = await this.#sessions.listNativeSessions(options, cursor);
44021
44373
  const info = page.sessions.find((entry) => entry.sessionId === selected.nativeSessionId);
44022
44374
  if (info !== void 0) {
@@ -44024,7 +44376,7 @@ var NativeSessionService = class {
44024
44376
  if (target === null) {
44025
44377
  throw new LocalAuthorizationError("The selected native session is not authorized");
44026
44378
  }
44027
- if (target.cwd !== selected.cwd || target.additionalDirectories.length !== selected.additionalDirectories.length || target.additionalDirectories.some((path3, index2) => path3 !== selected.additionalDirectories[index2])) {
44379
+ if (target.cwd !== selected.cwd || target.additionalDirectories.length !== selected.additionalDirectories.length || target.additionalDirectories.some((path3, index3) => path3 !== selected.additionalDirectories[index3])) {
44028
44380
  throw new AcpExecutionError(
44029
44381
  "This session's directory changed. Refresh the list before continuing.",
44030
44382
  {},
@@ -44063,7 +44415,7 @@ var NativeSessionService = class {
44063
44415
  };
44064
44416
 
44065
44417
  // src/relay-connection/daemon-operation-state.ts
44066
- import { createHash as createHash5, randomUUID as randomUUID5 } from "node:crypto";
44418
+ import { createHash as createHash5, randomUUID as randomUUID6 } from "node:crypto";
44067
44419
  var MAX_TERMINAL_RECEIPTS = 1024;
44068
44420
  function isTerminal(state) {
44069
44421
  return state === "succeeded" || state === "failed" || state === "cancelled";
@@ -44080,7 +44432,7 @@ var DaemonOperationState = class {
44080
44432
  }
44081
44433
  return { attemptId: existing.attemptId, commandId, kind: "duplicate", state: existing.state };
44082
44434
  }
44083
- const attemptId = randomUUID5();
44435
+ const attemptId = randomUUID6();
44084
44436
  this.#executions.set(commandId, { attemptId, commandHash, sessionId, state: "dispatching" });
44085
44437
  return { attemptId, commandId, kind: "accepted", state: "dispatching" };
44086
44438
  };
@@ -45044,7 +45396,7 @@ async function executeSessionLiveHistoryV2PageLoad(socket, command, config2, dir
45044
45396
  const replay = await sessions.loadSessionEventsV2(loadOptions, command.eventLimit, command.cursor);
45045
45397
  signal.throwIfAborted();
45046
45398
  const events = replay.events.map(
45047
- (event, index) => eventLogV2.event(command.sessionId, replay.startPosition + index, event, "1970-01-01T00:00:00.000Z")
45399
+ (event, index2) => eventLogV2.event(command.sessionId, replay.startPosition + index2, event, "1970-01-01T00:00:00.000Z")
45048
45400
  );
45049
45401
  const tailCursor = events.at(-1)?.eventId ?? "";
45050
45402
  audit.record({
@@ -45095,7 +45447,7 @@ async function executeSessionLiveHistoryV2PageLoad(socket, command, config2, dir
45095
45447
  }
45096
45448
 
45097
45449
  // src/acp/session-config/apply-session-configuration.ts
45098
- import { randomUUID as randomUUID6 } from "node:crypto";
45450
+ import { randomUUID as randomUUID7 } from "node:crypto";
45099
45451
  function invalidSessionConfiguration(message) {
45100
45452
  return new AcpExecutionError(message, {}, "invalid_session_configuration");
45101
45453
  }
@@ -45236,7 +45588,7 @@ async function applySessionConfigurationSelection(sessions, audit, options, sele
45236
45588
  booleanValue: selection.booleanValue,
45237
45589
  configId: selection.configId,
45238
45590
  cwd,
45239
- requestId: `cfg_${randomUUID6()}`,
45591
+ requestId: `cfg_${randomUUID7()}`,
45240
45592
  sessionId,
45241
45593
  signal,
45242
45594
  value: selection.value,
@@ -46306,7 +46658,7 @@ function connectRelay(url2, signal) {
46306
46658
  }
46307
46659
 
46308
46660
  // src/relay-connection/liveness.ts
46309
- import { randomUUID as randomUUID7 } from "node:crypto";
46661
+ import { randomUUID as randomUUID8 } from "node:crypto";
46310
46662
  var HEARTBEAT_ACK_TIMEOUT_MILLISECONDS = 1e4;
46311
46663
  var HEARTBEAT_INTERVAL_MILLISECONDS = 2e4;
46312
46664
  var RelayLivenessState = class {
@@ -46395,7 +46747,7 @@ var RelayConnectionLiveness = class {
46395
46747
  }
46396
46748
  throw new Error("Heartbeat was scheduled in an invalid state");
46397
46749
  }
46398
- const heartbeatId = randomUUID7();
46750
+ const heartbeatId = randomUUID8();
46399
46751
  this.#state = new AwaitingHeartbeatAckState(
46400
46752
  heartbeatId,
46401
46753
  this.#timer.schedule(this.#handleTimeout, HEARTBEAT_ACK_TIMEOUT_MILLISECONDS)
@@ -46687,7 +47039,7 @@ var SystemDaemonTimer = class {
46687
47039
  var systemDaemonTimer = new SystemDaemonTimer();
46688
47040
 
46689
47041
  // src/session-event-log-v2.ts
46690
- import { createHash as createHash7, randomUUID as randomUUID8 } from "node:crypto";
47042
+ import { createHash as createHash7, randomUUID as randomUUID9 } from "node:crypto";
46691
47043
  function promptContent(command) {
46692
47044
  const content = [];
46693
47045
  if (command.prompt.length > 0) {
@@ -46711,7 +47063,7 @@ function promptContent(command) {
46711
47063
  }
46712
47064
  return content;
46713
47065
  }
46714
- function sessionEventV2(daemonGenerationId, sessionId, position, event, recordedAt) {
47066
+ function sessionEventV22(daemonGenerationId, sessionId, position, event, recordedAt) {
46715
47067
  const sessionPrefix = createHash7("sha256").update(sessionId).digest("hex").slice(0, 16);
46716
47068
  return {
46717
47069
  eventId: `event-${daemonGenerationId}-${sessionPrefix}-${position.toString().padStart(16, "0")}`,
@@ -46723,11 +47075,12 @@ function sessionEventV2(daemonGenerationId, sessionId, position, event, recorded
46723
47075
  };
46724
47076
  }
46725
47077
  var DaemonSessionEventLogV2 = class {
46726
- daemonGenerationId = randomUUID8();
47078
+ daemonGenerationId;
46727
47079
  #publisher;
46728
47080
  #queued = /* @__PURE__ */ new Map();
46729
- constructor(publisher) {
47081
+ constructor(publisher, daemonGenerationId = randomUUID9()) {
46730
47082
  this.#publisher = publisher;
47083
+ this.daemonGenerationId = daemonGenerationId;
46731
47084
  }
46732
47085
  requested = (command) => {
46733
47086
  this.#queued.set(command.commandId, {
@@ -46747,7 +47100,7 @@ var DaemonSessionEventLogV2 = class {
46747
47100
  record = (sessionId, event, position) => {
46748
47101
  this.#publisher.publishV2(this.event(sessionId, position, event, (/* @__PURE__ */ new Date()).toISOString()));
46749
47102
  };
46750
- event = (sessionId, position, event, recordedAt) => sessionEventV2(this.daemonGenerationId, sessionId, position, event, recordedAt);
47103
+ event = (sessionId, position, event, recordedAt) => sessionEventV22(this.daemonGenerationId, sessionId, position, event, recordedAt);
46751
47104
  queueChanged = (_sessionId) => void 0;
46752
47105
  completed = (sessionId, commandId, _stopReason) => {
46753
47106
  const request = this.#queued.get(commandId);
@@ -46814,7 +47167,7 @@ async function installDetectedAgentIntegrations(config2, installations, signal)
46814
47167
  {
46815
47168
  agentId: agent.id,
46816
47169
  kind: AGENT_INSTALL_REQUEST_KIND,
46817
- requestId: `automatic-integration-${randomUUID9()}`
47170
+ requestId: `automatic-integration-${randomUUID10()}`
46818
47171
  },
46819
47172
  signal
46820
47173
  );
@@ -46832,13 +47185,24 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
46832
47185
  publishCatalog: async (installationSignal) => await publishAgentCatalog(config2, installationSignal),
46833
47186
  stateDirectory
46834
47187
  });
46835
- const sessionStore = new SqliteAcpSessionStore(
46836
- join19(stateDirectory, "sessions", `${createHash8("sha256").update(config2.channelId).digest("hex")}.sqlite`)
46837
- );
47188
+ const channelHash = createHash8("sha256").update(config2.channelId).digest("hex");
47189
+ const daemonGenerationId = randomUUID10();
47190
+ const sessionDatabase = openAcpSessionDatabase(join19(stateDirectory, "sessions", `${channelHash}.sqlite`));
47191
+ let eventsV2;
47192
+ try {
47193
+ eventsV2 = new CachedAcpSessionEventStoreV2(
47194
+ openSessionEventCacheV2Database(join19(stateDirectory, "sessions", `${channelHash}.events.sqlite`)),
47195
+ daemonGenerationId
47196
+ );
47197
+ } catch (error62) {
47198
+ sessionDatabase.close();
47199
+ throw error62;
47200
+ }
47201
+ const sessionStore = new SqliteAcpSessionStore(sessionDatabase, eventsV2);
46838
47202
  await using externalContent = new LocalExternalContentStore(stateDirectory);
46839
47203
  const operations = new DaemonOperationState();
46840
47204
  const publisher = new DaemonSessionEventPublisher();
46841
- const eventLogV2 = new DaemonSessionEventLogV2(publisher);
47205
+ const eventLogV2 = new DaemonSessionEventLogV2(publisher, daemonGenerationId);
46842
47206
  const activeTurns = new DaemonTurnRegistry(operations);
46843
47207
  const recordSessionEvent = (sessionId, event) => {
46844
47208
  publisher.publish(sessionId, activeTurns.recordEvent(event));
@@ -46884,7 +47248,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
46884
47248
  options2.signal
46885
47249
  );
46886
47250
  return cwd === options2.cwd && additionalDirectories.length === options2.additionalDirectories.length && additionalDirectories.every(
46887
- (directory, index) => directory === options2.additionalDirectories[index]
47251
+ (directory, index2) => directory === options2.additionalDirectories[index2]
46888
47252
  );
46889
47253
  });
46890
47254
  }
@@ -47349,12 +47713,12 @@ var RuntimeSupervisor = class {
47349
47713
  }
47350
47714
  };
47351
47715
  function pairingIdentifier(arguments_) {
47352
- const indexes = arguments_.flatMap((argument, index2) => argument === "--pairing" ? [index2] : []);
47716
+ const indexes = arguments_.flatMap((argument, index3) => argument === "--pairing" ? [index3] : []);
47353
47717
  if (indexes.length !== 1) {
47354
47718
  return null;
47355
47719
  }
47356
- const index = indexes[0];
47357
- return index === void 0 ? null : arguments_[index + 1] ?? null;
47720
+ const index2 = indexes[0];
47721
+ return index2 === void 0 ? null : arguments_[index2 + 1] ?? null;
47358
47722
  }
47359
47723
  async function waitForReady(active, signal) {
47360
47724
  if (active.status === "online") {
@@ -47649,9 +48013,9 @@ function formatPairTable(pairs) {
47649
48013
  const headers = ["connection_id", "app_id", "runtime_id", "workspace", "status"];
47650
48014
  const rows = pairs.map((pair) => [pair.connectionId, pair.appId, pair.runtimeId, pair.workspace, pair.status]);
47651
48015
  const widths = headers.map(
47652
- (header, index) => Math.max(header.length, ...rows.map((row) => row[index]?.length ?? 0))
48016
+ (header, index2) => Math.max(header.length, ...rows.map((row) => row[index2]?.length ?? 0))
47653
48017
  );
47654
- const line = (row) => `| ${row.map((value, index) => value.padEnd(widths[index] ?? value.length)).join(" | ")} |`;
48018
+ const line = (row) => `| ${row.map((value, index2) => value.padEnd(widths[index2] ?? value.length)).join(" | ")} |`;
47655
48019
  const divider = `|-${widths.map((width) => "-".repeat(width)).join("-|-")}-|`;
47656
48020
  return `${line(headers)}
47657
48021
  ${divider}