@hasna/mementos 0.14.87 → 0.14.88

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.
package/dist/cli/index.js CHANGED
@@ -1011,7 +1011,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
1011
1011
  this._exitCallback = (err) => {
1012
1012
  if (err.code !== "commander.executeSubCommandAsync") {
1013
1013
  throw err;
1014
- } else {}
1014
+ }
1015
1015
  };
1016
1016
  }
1017
1017
  return this;
@@ -2200,11 +2200,119 @@ var init_retired_storage_mode = __esm(() => {
2200
2200
  ];
2201
2201
  });
2202
2202
 
2203
- // src/storage.ts
2204
- import { Database } from "bun:sqlite";
2205
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
2203
+ // ../../node_modules/.bun/@hasna+paths@0.1.0/node_modules/@hasna/paths/dist/index.js
2206
2204
  import { homedir } from "os";
2207
2205
  import { join } from "path";
2206
+ function assertApp(app) {
2207
+ if (typeof app !== "string" || app.length === 0) {
2208
+ throw new TypeError("paths: app must be a non-empty string");
2209
+ }
2210
+ if (!APP_SLUG_RE.test(app)) {
2211
+ throw new TypeError(`paths: invalid app slug "${app}" \u2014 expected lowercase kebab-case ([a-z0-9]+(-[a-z0-9]+)*)`);
2212
+ }
2213
+ }
2214
+ function envOf(options) {
2215
+ return options.env ?? process.env;
2216
+ }
2217
+ function envValue(options, kind) {
2218
+ const value = envOf(options)[KIND_ENV[kind]];
2219
+ return typeof value === "string" && value.length > 0 ? value : undefined;
2220
+ }
2221
+ function isMacOS(platform) {
2222
+ return platform === "darwin";
2223
+ }
2224
+ function baseDir(kind, options) {
2225
+ const override = envValue(options, kind);
2226
+ if (override)
2227
+ return override;
2228
+ const home = options.home ?? homedir();
2229
+ const platform = options.platform ?? process.platform;
2230
+ if (isMacOS(platform)) {
2231
+ switch (kind) {
2232
+ case "config":
2233
+ case "data":
2234
+ return join(home, "Library", "Application Support", "Hasna");
2235
+ case "cache":
2236
+ return join(home, "Library", "Caches", "Hasna");
2237
+ case "state":
2238
+ return join(home, "Library", "Logs", "Hasna");
2239
+ }
2240
+ }
2241
+ switch (kind) {
2242
+ case "config":
2243
+ return join(home, ".config", "hasna");
2244
+ case "data":
2245
+ return join(home, ".local", "share", "hasna");
2246
+ case "state":
2247
+ return join(home, ".local", "state", "hasna");
2248
+ case "cache":
2249
+ return join(home, ".cache", "hasna");
2250
+ }
2251
+ }
2252
+ function resolvePath(kind, options) {
2253
+ assertApp(options.app);
2254
+ const appSegment = options.internal === true ? join("internal", options.app) : options.app;
2255
+ return join(baseDir(kind, options), appSegment);
2256
+ }
2257
+ function dataDir(options) {
2258
+ return resolvePath("data", options);
2259
+ }
2260
+ var KIND_ENV, APP_SLUG_RE;
2261
+ var init_dist = __esm(() => {
2262
+ KIND_ENV = {
2263
+ config: "HASNA_CONFIG_HOME",
2264
+ data: "HASNA_DATA_HOME",
2265
+ state: "HASNA_STATE_HOME",
2266
+ cache: "HASNA_CACHE_HOME"
2267
+ };
2268
+ APP_SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
2269
+ });
2270
+
2271
+ // src/lib/paths.ts
2272
+ import { existsSync } from "fs";
2273
+ import { homedir as homedir2 } from "os";
2274
+ import { join as join2, resolve } from "path";
2275
+ function effectiveHome() {
2276
+ return process.env["HOME"] || process.env["USERPROFILE"] || homedir2() || "/tmp";
2277
+ }
2278
+ function legacyDataRoot() {
2279
+ return join2(effectiveHome(), ".hasna", "mementos");
2280
+ }
2281
+ function resolverDataRoot() {
2282
+ return dataDir({
2283
+ app: "mementos",
2284
+ home: process.env["HOME"] || process.env["USERPROFILE"] || undefined
2285
+ });
2286
+ }
2287
+ function adoptResolverDataRoot(resolved, env = process.env) {
2288
+ const dataOverride = env.HASNA_DATA_HOME;
2289
+ if (typeof dataOverride === "string" && dataOverride.trim().length > 0)
2290
+ return true;
2291
+ return existsSync(join2(resolved, "mementos.db"));
2292
+ }
2293
+ function exactDataRoot() {
2294
+ for (const key of ["HASNA_MEMENTOS_HOME", "MEMENTOS_HOME"]) {
2295
+ const dir = process.env[key]?.trim();
2296
+ if (dir)
2297
+ return resolve(dir);
2298
+ }
2299
+ return;
2300
+ }
2301
+ function getDataRoot() {
2302
+ const exact = exactDataRoot();
2303
+ if (exact)
2304
+ return exact;
2305
+ const resolved = resolverDataRoot();
2306
+ return adoptResolverDataRoot(resolved) ? resolve(resolved) : resolve(legacyDataRoot());
2307
+ }
2308
+ var init_paths = __esm(() => {
2309
+ init_dist();
2310
+ });
2311
+
2312
+ // src/storage.ts
2313
+ import { Database } from "bun:sqlite";
2314
+ import { existsSync as existsSync2, mkdirSync, readFileSync, writeFileSync } from "fs";
2315
+ import { join as join3 } from "path";
2208
2316
  import { fileURLToPath } from "url";
2209
2317
  import { Worker } from "worker_threads";
2210
2318
  import pg from "pg";
@@ -2454,7 +2562,7 @@ function readEnv(name) {
2454
2562
  return value ? value : null;
2455
2563
  }
2456
2564
  function readConfigFile() {
2457
- if (!existsSync(STORAGE_CONFIG_PATH)) {
2565
+ if (!existsSync2(STORAGE_CONFIG_PATH)) {
2458
2566
  return {};
2459
2567
  }
2460
2568
  try {
@@ -2463,6 +2571,9 @@ function readConfigFile() {
2463
2571
  return {};
2464
2572
  }
2465
2573
  }
2574
+ function getConfigPath() {
2575
+ return STORAGE_CONFIG_PATH;
2576
+ }
2466
2577
  function getStorageDatabaseEnv() {
2467
2578
  for (const env of DATABASE_ENV_NAMES) {
2468
2579
  if (readEnv(env.name))
@@ -2699,11 +2810,7 @@ function getStorageStatus() {
2699
2810
  function getConfiguredConnectionString() {
2700
2811
  return getStorageDatabaseUrl() ?? undefined;
2701
2812
  }
2702
- function getStorageConnectionString(dbName = "mementos") {
2703
- assertNoLegacyStorageMode2();
2704
- if (!isServerContext()) {
2705
- throw new Error("Refusing to construct an RDS Postgres DSN outside the mementos-serve server. " + "The raw database DSN is NEVER distributed to client machines. " + "Clients must use the HTTP API: set HASNA_MEMENTOS_API_URL and " + "HASNA_MEMENTOS_API_KEY (and unset HASNA_MEMENTOS_DATABASE_URL).");
2706
- }
2813
+ function resolveConfiguredConnectionString(dbName) {
2707
2814
  const envConnectionString = getConfiguredConnectionString();
2708
2815
  if (envConnectionString) {
2709
2816
  const validation = validatePostgresConnectionString(envConnectionString);
@@ -2722,7 +2829,7 @@ function getStorageConnectionString(dbName = "mementos") {
2722
2829
  missing.push("storage.rds.username");
2723
2830
  }
2724
2831
  if (missing.length > 0) {
2725
- throw new Error(`Remote storage database is not configured. Missing ${missing.join(", ")}. Set HASNA_MEMENTOS_DATABASE_URL or configure ~/.hasna/mementos/storage/config.json.`);
2832
+ throw new Error(`Remote storage database is not configured. Missing ${missing.join(", ")}. Set HASNA_MEMENTOS_DATABASE_URL or configure ${STORAGE_CONFIG_PATH}.`);
2726
2833
  }
2727
2834
  const password = process.env[password_env];
2728
2835
  if (!password) {
@@ -2731,6 +2838,17 @@ function getStorageConnectionString(dbName = "mementos") {
2731
2838
  const sslParam = ssl ? "?sslmode=require" : "";
2732
2839
  return `postgres://${username}:${encodeURIComponent(password)}@${host}:${port}/${dbName}${sslParam}`;
2733
2840
  }
2841
+ function getStorageConnectionString(dbName = "mementos") {
2842
+ assertNoLegacyStorageMode2();
2843
+ if (!isServerContext()) {
2844
+ throw new Error("Refusing to construct an RDS Postgres DSN outside the mementos-serve server. " + "The raw database DSN is NEVER distributed to client machines. " + "Clients must use the HTTP API: set HASNA_MEMENTOS_API_URL and " + "HASNA_MEMENTOS_API_KEY (and unset HASNA_MEMENTOS_DATABASE_URL).");
2845
+ }
2846
+ return resolveConfiguredConnectionString(dbName);
2847
+ }
2848
+ function getStorageConnectionStringForOperator(dbName = "mementos") {
2849
+ assertNoLegacyStorageMode2();
2850
+ return resolveConfiguredConnectionString(dbName);
2851
+ }
2734
2852
  function isSyncExcludedTable(table) {
2735
2853
  return SYNC_EXCLUDED_TABLE_PATTERNS.some((pattern) => pattern.test(table));
2736
2854
  }
@@ -2889,6 +3007,7 @@ CREATE TABLE IF NOT EXISTS _sync_meta (
2889
3007
  var init_storage = __esm(() => {
2890
3008
  init_backend();
2891
3009
  init_retired_storage_mode();
3010
+ init_paths();
2892
3011
  PgSyncPool = class PgSyncPool {
2893
3012
  worker;
2894
3013
  status;
@@ -2906,12 +3025,12 @@ var init_storage = __esm(() => {
2906
3025
  const ext = import.meta.url.endsWith(".ts") ? ".ts" : ".js";
2907
3026
  const here = fileURLToPath(new URL(".", import.meta.url));
2908
3027
  const candidates = [
2909
- join(here, `pg-sync-worker${ext}`),
2910
- join(here, "..", `pg-sync-worker${ext}`),
2911
- join(here, "..", "..", `pg-sync-worker${ext}`)
3028
+ join3(here, `pg-sync-worker${ext}`),
3029
+ join3(here, "..", `pg-sync-worker${ext}`),
3030
+ join3(here, "..", "..", `pg-sync-worker${ext}`)
2912
3031
  ];
2913
3032
  for (const candidate of candidates) {
2914
- if (existsSync(candidate))
3033
+ if (existsSync2(candidate))
2915
3034
  return candidate;
2916
3035
  }
2917
3036
  return candidates[0];
@@ -2998,7 +3117,7 @@ var init_storage = __esm(() => {
2998
3117
  MEMENTOS_STORAGE_FALLBACK_ENV = {
2999
3118
  databaseUrl: "MEMENTOS_DATABASE_URL"
3000
3119
  };
3001
- LOCAL_DATA_DIR = join(homedir(), ".hasna", "mementos");
3120
+ LOCAL_DATA_DIR = getDataRoot();
3002
3121
  DEFAULT_STORAGE_CONFIG = {
3003
3122
  rds: {
3004
3123
  host: "",
@@ -3013,8 +3132,8 @@ var init_storage = __esm(() => {
3013
3132
  schedule_minutes: 0
3014
3133
  }
3015
3134
  };
3016
- STORAGE_CONFIG_DIR = join(LOCAL_DATA_DIR, "storage");
3017
- STORAGE_CONFIG_PATH = join(STORAGE_CONFIG_DIR, "config.json");
3135
+ STORAGE_CONFIG_DIR = join3(LOCAL_DATA_DIR, "storage");
3136
+ STORAGE_CONFIG_PATH = join3(STORAGE_CONFIG_DIR, "config.json");
3018
3137
  DATABASE_ENV_NAMES = [
3019
3138
  { name: MEMENTOS_STORAGE_ENV.databaseUrl, deprecated: false },
3020
3139
  { name: MEMENTOS_STORAGE_FALLBACK_ENV.databaseUrl, deprecated: false }
@@ -3039,7 +3158,7 @@ var init_storage = __esm(() => {
3039
3158
 
3040
3159
  // src/db/api-mode.ts
3041
3160
  import { tmpdir } from "os";
3042
- import { join as join2 } from "path";
3161
+ import { join as join4 } from "path";
3043
3162
  import { writeFileSync as writeFileSync2, unlinkSync } from "fs";
3044
3163
  import { randomUUID } from "crypto";
3045
3164
  function firstEnv2(keys) {
@@ -3164,7 +3283,7 @@ x-api-key: ${cfg.apiKey}
3164
3283
  ];
3165
3284
  let bodyFile;
3166
3285
  if (hasBody) {
3167
- bodyFile = join2(tmpdir(), `mem-req-${process.pid}-${randomUUID()}.json`);
3286
+ bodyFile = join4(tmpdir(), `mem-req-${process.pid}-${randomUUID()}.json`);
3168
3287
  writeFileSync2(bodyFile, JSON.stringify(body), { mode: 384 });
3169
3288
  args.push("--data-binary", `@${bodyFile}`);
3170
3289
  }
@@ -4650,18 +4769,18 @@ __export(exports_database, {
4650
4769
  escapeLikePrefix: () => escapeLikePrefix,
4651
4770
  closeDatabase: () => closeDatabase
4652
4771
  });
4653
- import { existsSync as existsSync2, mkdirSync as mkdirSync2, cpSync } from "fs";
4654
- import { dirname, join as join3, resolve } from "path";
4772
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, cpSync } from "fs";
4773
+ import { dirname, join as join5, resolve as resolve2 } from "path";
4655
4774
  function isInMemoryDb(path) {
4656
4775
  return path === ":memory:" || path.startsWith("file::memory:");
4657
4776
  }
4658
4777
  function findNearestMementosDb(startDir) {
4659
- let dir = resolve(startDir);
4778
+ let dir = resolve2(startDir);
4660
4779
  const home = process.env["HOME"] || process.env["USERPROFILE"] || "~";
4661
- const legacyHomeDb = resolve(home, ".mementos", "mementos.db");
4780
+ const legacyHomeDb = resolve2(home, ".mementos", "mementos.db");
4662
4781
  while (true) {
4663
- const candidate = join3(dir, ".mementos", "mementos.db");
4664
- if (existsSync2(candidate) && resolve(candidate) !== legacyHomeDb)
4782
+ const candidate = join5(dir, ".mementos", "mementos.db");
4783
+ if (existsSync3(candidate) && resolve2(candidate) !== legacyHomeDb)
4665
4784
  return candidate;
4666
4785
  const parent = dirname(dir);
4667
4786
  if (parent === dir)
@@ -4671,9 +4790,9 @@ function findNearestMementosDb(startDir) {
4671
4790
  return null;
4672
4791
  }
4673
4792
  function findGitRoot(startDir) {
4674
- let dir = resolve(startDir);
4793
+ let dir = resolve2(startDir);
4675
4794
  while (true) {
4676
- if (existsSync2(join3(dir, ".git")))
4795
+ if (existsSync3(join5(dir, ".git")))
4677
4796
  return dir;
4678
4797
  const parent = dirname(dir);
4679
4798
  if (parent === dir)
@@ -4684,10 +4803,10 @@ function findGitRoot(startDir) {
4684
4803
  }
4685
4804
  function migrateGlobalDir() {
4686
4805
  const home = process.env["HOME"] || process.env["USERPROFILE"] || "~";
4687
- const newDir = join3(home, ".hasna", "mementos");
4688
- const oldDir = join3(home, ".mementos");
4689
- if (!existsSync2(newDir) && existsSync2(oldDir)) {
4690
- mkdirSync2(join3(home, ".hasna"), { recursive: true });
4806
+ const newDir = getDataRoot();
4807
+ const oldDir = join5(home, ".mementos");
4808
+ if (!existsSync3(newDir) && existsSync3(oldDir)) {
4809
+ mkdirSync2(dirname(newDir), { recursive: true });
4691
4810
  cpSync(oldDir, newDir, { recursive: true });
4692
4811
  }
4693
4812
  }
@@ -4704,18 +4823,17 @@ function getDbPath() {
4704
4823
  if (process.env["MEMENTOS_DB_SCOPE"] === "project") {
4705
4824
  const gitRoot = findGitRoot(cwd);
4706
4825
  if (gitRoot) {
4707
- return join3(gitRoot, ".mementos", "mementos.db");
4826
+ return join5(gitRoot, ".mementos", "mementos.db");
4708
4827
  }
4709
4828
  }
4710
4829
  migrateGlobalDir();
4711
- const home = process.env["HOME"] || process.env["USERPROFILE"] || "~";
4712
- return join3(home, ".hasna", "mementos", "mementos.db");
4830
+ return join5(getDataRoot(), "mementos.db");
4713
4831
  }
4714
4832
  function ensureDir(filePath) {
4715
4833
  if (isInMemoryDb(filePath))
4716
4834
  return;
4717
- const dir = dirname(resolve(filePath));
4718
- if (!existsSync2(dir)) {
4835
+ const dir = dirname(resolve2(filePath));
4836
+ if (!existsSync3(dir)) {
4719
4837
  mkdirSync2(dir, { recursive: true });
4720
4838
  }
4721
4839
  }
@@ -4853,6 +4971,7 @@ var init_database = __esm(() => {
4853
4971
  init_storage();
4854
4972
  init_api_mode();
4855
4973
  init_migrations();
4974
+ init_paths();
4856
4975
  ALLOWED_TABLES = new Set([
4857
4976
  "memories",
4858
4977
  "agents",
@@ -5445,12 +5564,22 @@ function createMemory(input, dedupeMode = "merge", db) {
5445
5564
  const effectiveMode = dedupeMode === "overwrite" ? "merge" : dedupeMode === "version-fork" ? "create" : dedupeMode;
5446
5565
  if (effectiveMode === "error") {
5447
5566
  const existing = d.query(`SELECT id, agent_id, updated_at FROM memories
5448
- WHERE key = ? AND scope = ? AND COALESCE(project_id, '') = ? AND status = 'active'
5567
+ WHERE key = ? AND scope = ? AND COALESCE(project_id, '') = ?
5449
5568
  LIMIT 1`).get(input.key, input.scope || "private", input.project_id || "");
5450
5569
  if (existing) {
5451
5570
  throw new MemoryConflictError(input.key, existing);
5452
5571
  }
5453
5572
  }
5573
+ if (effectiveMode === "create") {
5574
+ const existing = d.query(`SELECT id, agent_id, updated_at FROM memories
5575
+ WHERE key = ? AND scope = ?
5576
+ AND COALESCE(agent_id, '') = ?
5577
+ AND COALESCE(project_id, '') = ?
5578
+ AND COALESCE(session_id, '') = ?`).get(input.key, input.scope || "private", input.agent_id || "", input.project_id || "", input.session_id || "");
5579
+ if (existing) {
5580
+ throw new MemoryConflictError(input.key, existing);
5581
+ }
5582
+ }
5454
5583
  if (effectiveMode === "merge") {
5455
5584
  const existing = d.query(`SELECT id, version FROM memories
5456
5585
  WHERE key = ? AND scope = ?
@@ -6102,6 +6231,17 @@ function updateMemory(id, input, db) {
6102
6231
  if (existing.version !== input.version) {
6103
6232
  throw new VersionConflictError(id, input.version, existing.version);
6104
6233
  }
6234
+ if (input.scope !== undefined && input.scope !== existing.scope) {
6235
+ const conflict = d.query(`SELECT id, agent_id, updated_at FROM memories
6236
+ WHERE key = ? AND scope = ?
6237
+ AND COALESCE(agent_id, '') = ?
6238
+ AND COALESCE(project_id, '') = ?
6239
+ AND COALESCE(session_id, '') = ?
6240
+ AND id != ?`).get(existing.key, input.scope, existing.agent_id || "", existing.project_id || "", existing.session_id || "", memoryId);
6241
+ if (conflict) {
6242
+ throw new MemoryConflictError(existing.key, conflict);
6243
+ }
6244
+ }
6105
6245
  const sets = ["version = version + 1", "updated_at = ?"];
6106
6246
  const params = [now()];
6107
6247
  if (input.value !== undefined) {
@@ -6360,16 +6500,16 @@ var init_memories = __esm(() => {
6360
6500
  });
6361
6501
 
6362
6502
  // src/db/agents.ts
6363
- import { homedir as homedir3 } from "os";
6364
- import { join as join5 } from "path";
6365
- import { existsSync as existsSync4, readFileSync as readFileSync2 } from "fs";
6503
+ import { homedir as homedir4 } from "os";
6504
+ import { join as join7 } from "path";
6505
+ import { existsSync as existsSync5, readFileSync as readFileSync2 } from "fs";
6366
6506
  function resolveWritingAgentName() {
6367
6507
  const envName = process.env["MEMENTOS_AGENT"]?.trim();
6368
6508
  if (envName)
6369
6509
  return envName;
6370
6510
  try {
6371
- const path = join5(homedir3(), ".hasna", "conversations", "agent-id");
6372
- if (existsSync4(path)) {
6511
+ const path = join7(homedir4(), ".hasna", "conversations", "agent-id");
6512
+ if (existsSync5(path)) {
6373
6513
  const fileAgent = readFileSync2(path, "utf8").trim();
6374
6514
  if (fileAgent)
6375
6515
  return fileAgent;
@@ -6580,13 +6720,13 @@ var init_agents = __esm(() => {
6580
6720
 
6581
6721
  // src/lib/package-version.ts
6582
6722
  import { readFileSync as readFileSync3 } from "fs";
6583
- import { dirname as dirname2, join as join6 } from "path";
6723
+ import { dirname as dirname2, join as join8 } from "path";
6584
6724
  import { fileURLToPath as fileURLToPath2 } from "url";
6585
6725
  function getMementosPackageVersion() {
6586
6726
  const here = dirname2(fileURLToPath2(import.meta.url));
6587
6727
  for (const candidate of [
6588
- join6(here, "..", "..", "package.json"),
6589
- join6(here, "..", "package.json")
6728
+ join8(here, "..", "..", "package.json"),
6729
+ join8(here, "..", "package.json")
6590
6730
  ]) {
6591
6731
  try {
6592
6732
  const parsed = JSON.parse(readFileSync3(candidate, "utf8"));
@@ -7572,7 +7712,7 @@ __export(exports_helpers, {
7572
7712
  getPackageVersion: () => getPackageVersion,
7573
7713
  getOutputFormat: () => getOutputFormat,
7574
7714
  getNestedValue: () => getNestedValue,
7575
- getConfigPath: () => getConfigPath,
7715
+ getConfigPath: () => getConfigPath2,
7576
7716
  formatWatchLine: () => formatWatchLine,
7577
7717
  formatMemoryLine: () => formatMemoryLine,
7578
7718
  formatMemoryDetail: () => formatMemoryDetail,
@@ -7593,11 +7733,11 @@ __export(exports_helpers, {
7593
7733
  });
7594
7734
  import chalk from "chalk";
7595
7735
  import { readFileSync as readFileSync4 } from "fs";
7596
- import { dirname as dirname3, join as join7, resolve as resolve2 } from "path";
7736
+ import { dirname as dirname3, join as join9, resolve as resolve3 } from "path";
7597
7737
  import { fileURLToPath as fileURLToPath3 } from "url";
7598
7738
  function getPackageVersion() {
7599
7739
  try {
7600
- const pkgPath = join7(dirname3(fileURLToPath3(import.meta.url)), "..", "..", "package.json");
7740
+ const pkgPath = join9(dirname3(fileURLToPath3(import.meta.url)), "..", "..", "package.json");
7601
7741
  const pkg = JSON.parse(readFileSync4(pkgPath, "utf-8"));
7602
7742
  return pkg.version || "0.0.0";
7603
7743
  } catch {
@@ -7877,7 +8017,7 @@ function resolveKeyOrId(keyOrId, opts, globalOpts) {
7877
8017
  const projectPath = opts.project || globalOpts.project;
7878
8018
  let projectId;
7879
8019
  if (projectPath) {
7880
- const project = getProject(resolve2(projectPath));
8020
+ const project = getProject(resolve3(projectPath));
7881
8021
  if (project)
7882
8022
  projectId = project.id;
7883
8023
  }
@@ -8156,14 +8296,13 @@ function validateConfigKeyValue(key, value, DEFAULT_CONFIG) {
8156
8296
  }
8157
8297
  return null;
8158
8298
  }
8159
- function getConfigPath() {
8160
- const { homedir: homedir4 } = __require("os");
8161
- return join7(homedir4(), ".hasna", "mementos", "config.json");
8299
+ function getConfigPath2() {
8300
+ return join9(getDataRoot(), "config.json");
8162
8301
  }
8163
8302
  function readFileConfig() {
8164
- const { existsSync: existsSync5 } = __require("fs");
8165
- const configPath = getConfigPath();
8166
- if (!existsSync5(configPath))
8303
+ const { existsSync: existsSync6 } = __require("fs");
8304
+ const configPath = getConfigPath2();
8305
+ if (!existsSync6(configPath))
8167
8306
  return {};
8168
8307
  try {
8169
8308
  const data = JSON.parse(readFileSync4(configPath, "utf-8"));
@@ -8177,10 +8316,10 @@ function readFileConfig() {
8177
8316
  }
8178
8317
  }
8179
8318
  function writeFileConfig(data) {
8180
- const { existsSync: existsSync5, writeFileSync: writeFileSync3, mkdirSync: mkdirSync3 } = __require("fs");
8181
- const configPath = getConfigPath();
8319
+ const { existsSync: existsSync6, writeFileSync: writeFileSync3, mkdirSync: mkdirSync3 } = __require("fs");
8320
+ const configPath = getConfigPath2();
8182
8321
  const dir = dirname3(configPath);
8183
- if (!existsSync5(dir))
8322
+ if (!existsSync6(dir))
8184
8323
  mkdirSync3(dir, { recursive: true });
8185
8324
  writeFileSync3(configPath, JSON.stringify(data, null, 2) + `
8186
8325
  `, "utf-8");
@@ -8193,6 +8332,7 @@ var init_helpers = __esm(() => {
8193
8332
  init_agents();
8194
8333
  init_projects();
8195
8334
  init_entities();
8335
+ init_paths();
8196
8336
  scopeColor = {
8197
8337
  global: chalk.cyan,
8198
8338
  shared: chalk.yellow,
@@ -8811,7 +8951,9 @@ function scoreResults(rows, queryLower, graphBoostedIds) {
8811
8951
  scored.sort((a, b) => {
8812
8952
  if (b.score !== a.score)
8813
8953
  return b.score - a.score;
8814
- return b.memory.importance - a.memory.importance;
8954
+ if (b.memory.importance !== a.memory.importance)
8955
+ return b.memory.importance - a.memory.importance;
8956
+ return a.memory.id.localeCompare(b.memory.id);
8815
8957
  });
8816
8958
  return scored;
8817
8959
  }
@@ -12908,13 +13050,13 @@ __export(exports_session_registry, {
12908
13050
  closeRegistry: () => closeRegistry,
12909
13051
  cleanStaleSessions: () => cleanStaleSessions
12910
13052
  });
12911
- import { existsSync as existsSync9, mkdirSync as mkdirSync5 } from "fs";
12912
- import { dirname as dirname6, join as join10 } from "path";
13053
+ import { existsSync as existsSync10, mkdirSync as mkdirSync5 } from "fs";
13054
+ import { dirname as dirname6, join as join15 } from "path";
12913
13055
  function getDb() {
12914
13056
  if (_db2)
12915
13057
  return _db2;
12916
13058
  const dir = dirname6(DB_PATH);
12917
- if (!existsSync9(dir))
13059
+ if (!existsSync10(dir))
12918
13060
  mkdirSync5(dir, { recursive: true });
12919
13061
  _db2 = new SqliteAdapter(DB_PATH);
12920
13062
  _db2.run("PRAGMA journal_mode = WAL");
@@ -13089,7 +13231,7 @@ function closeRegistry() {
13089
13231
  var DB_PATH, _db2 = null;
13090
13232
  var init_session_registry = __esm(() => {
13091
13233
  init_storage();
13092
- DB_PATH = join10(process.env["HOME"] || process.env["USERPROFILE"] || "~", ".open-sessions-registry.db");
13234
+ DB_PATH = join15(process.env["HOME"] || process.env["USERPROFILE"] || "~", ".open-sessions-registry.db");
13093
13235
  });
13094
13236
 
13095
13237
  // src/db/pg-migrations.ts
@@ -13884,7 +14026,7 @@ function getPgMigrationDiagnostics(connectionString) {
13884
14026
  const issues = [];
13885
14027
  if (!resolvedConnectionString) {
13886
14028
  try {
13887
- resolvedConnectionString = getStorageConnectionString("mementos");
14029
+ resolvedConnectionString = getStorageConnectionStringForOperator("mementos");
13888
14030
  } catch (error) {
13889
14031
  issues.push(error instanceof Error ? error.message : String(error));
13890
14032
  }
@@ -17949,7 +18091,7 @@ var init_zod = __esm(() => {
17949
18091
  init_external();
17950
18092
  });
17951
18093
 
17952
- // ../../node_modules/.bun/@ai-sdk+provider@3.0.14/node_modules/@ai-sdk/provider/dist/index.mjs
18094
+ // ../../node_modules/.bun/@ai-sdk+provider@3.0.15/node_modules/@ai-sdk/provider/dist/index.mjs
17953
18095
  function getErrorMessage(error) {
17954
18096
  if (error == null) {
17955
18097
  return "unknown error";
@@ -17981,7 +18123,7 @@ function isJSONObject(value) {
17981
18123
  return value != null && typeof value === "object" && Object.entries(value).every(([key, val]) => typeof key === "string" && (val === undefined || isJSONValue(val)));
17982
18124
  }
17983
18125
  var marker = "vercel.ai.error", symbol, _a, _b, AISDKError, name = "AI_APICallError", marker2, symbol2, _a2, _b2, APICallError, name2 = "AI_EmptyResponseBodyError", marker3, symbol3, _a3, _b3, EmptyResponseBodyError, name3 = "AI_InvalidArgumentError", marker4, symbol4, _a4, _b4, InvalidArgumentError2, name4 = "AI_InvalidPromptError", marker5, symbol5, _a5, _b5, InvalidPromptError, name5 = "AI_InvalidResponseDataError", marker6, symbol6, _a6, _b6, InvalidResponseDataError, name6 = "AI_JSONParseError", marker7, symbol7, _a7, _b7, JSONParseError, name7 = "AI_LoadAPIKeyError", marker8, symbol8, _a8, _b8, LoadAPIKeyError, name8 = "AI_LoadSettingError", marker9, symbol9, _a9, _b9, LoadSettingError, name9 = "AI_NoContentGeneratedError", marker10, symbol10, _a10, _b10, NoContentGeneratedError, name10 = "AI_NoSuchModelError", marker11, symbol11, _a11, _b11, NoSuchModelError, name11 = "AI_TooManyEmbeddingValuesForCallError", marker12, symbol12, _a12, _b12, TooManyEmbeddingValuesForCallError, name12 = "AI_TypeValidationError", marker13, symbol13, _a13, _b13, TypeValidationError, name13 = "AI_UnsupportedFunctionalityError", marker14, symbol14, _a14, _b14, UnsupportedFunctionalityError;
17984
- var init_dist = __esm(() => {
18126
+ var init_dist2 = __esm(() => {
17985
18127
  symbol = Symbol.for(marker);
17986
18128
  AISDKError = class _AISDKError extends (_b = Error, _a = symbol, _b) {
17987
18129
  constructor({
@@ -27565,7 +27707,7 @@ class JSONSchemaGenerator {
27565
27707
  if (val === undefined) {
27566
27708
  if (this.unrepresentable === "throw") {
27567
27709
  throw new Error("Literal `undefined` cannot be represented in JSON Schema");
27568
- } else {}
27710
+ }
27569
27711
  } else if (typeof val === "bigint") {
27570
27712
  if (this.unrepresentable === "throw") {
27571
27713
  throw new Error("BigInt literals cannot be represented in JSON Schema");
@@ -29614,7 +29756,7 @@ var init_v3 = __esm(() => {
29614
29756
  init_external();
29615
29757
  });
29616
29758
 
29617
- // ../../node_modules/.bun/eventsource-parser@3.1.0/node_modules/eventsource-parser/dist/index.js
29759
+ // ../../node_modules/.bun/eventsource-parser@3.1.1/node_modules/eventsource-parser/dist/index.js
29618
29760
  function noop(_arg) {}
29619
29761
  function createParser(config2) {
29620
29762
  if (typeof config2 == "function")
@@ -29701,7 +29843,7 @@ ${value2}`, dataLines++;
29701
29843
  }
29702
29844
  if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
29703
29845
  const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
29704
- id = value2.includes("\x00") ? undefined : value2;
29846
+ value2.includes("\x00") || (id = value2);
29705
29847
  return;
29706
29848
  }
29707
29849
  if (firstCharCode === 58) {
@@ -29729,7 +29871,7 @@ ${value2}`, dataLines++;
29729
29871
  ${value}`, dataLines++;
29730
29872
  break;
29731
29873
  case "id":
29732
- id = value.includes("\x00") ? undefined : value;
29874
+ value.includes("\x00") || (id = value);
29733
29875
  break;
29734
29876
  case "retry":
29735
29877
  /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(new ParseError(`Invalid \`retry\` value: "${value}"`, {
@@ -29766,7 +29908,7 @@ function isEventPrefix(chunk, i, firstCharCode) {
29766
29908
  return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;
29767
29909
  }
29768
29910
  var ParseError, LF = 10, CR = 13, SPACE = 32;
29769
- var init_dist2 = __esm(() => {
29911
+ var init_dist3 = __esm(() => {
29770
29912
  ParseError = class ParseError extends Error {
29771
29913
  constructor(message, options) {
29772
29914
  super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
@@ -29774,10 +29916,10 @@ var init_dist2 = __esm(() => {
29774
29916
  };
29775
29917
  });
29776
29918
 
29777
- // ../../node_modules/.bun/eventsource-parser@3.1.0/node_modules/eventsource-parser/dist/stream.js
29919
+ // ../../node_modules/.bun/eventsource-parser@3.1.1/node_modules/eventsource-parser/dist/stream.js
29778
29920
  var EventSourceParserStream;
29779
29921
  var init_stream = __esm(() => {
29780
- init_dist2();
29922
+ init_dist3();
29781
29923
  EventSourceParserStream = class EventSourceParserStream extends TransformStream {
29782
29924
  constructor({ onError, onRetry, onComment, maxBufferSize } = {}) {
29783
29925
  let parser;
@@ -29803,7 +29945,7 @@ var init_stream = __esm(() => {
29803
29945
  };
29804
29946
  });
29805
29947
 
29806
- // ../../node_modules/.bun/@ai-sdk+provider-utils@4.0.42+27912429049419a2/node_modules/@ai-sdk/provider-utils/dist/index.mjs
29948
+ // ../../node_modules/.bun/@ai-sdk+provider-utils@4.0.46+27912429049419a2/node_modules/@ai-sdk/provider-utils/dist/index.mjs
29807
29949
  function combineHeaders(...headers) {
29808
29950
  return headers.reduce((combinedHeaders, currentHeaders) => ({
29809
29951
  ...combinedHeaders,
@@ -30144,11 +30286,10 @@ async function loadNodeModule(id) {
30144
30286
  var _a22;
30145
30287
  const processWithBuiltins = globalThis.process;
30146
30288
  const builtinModule = (_a22 = processWithBuiltins == null ? undefined : processWithBuiltins.getBuiltinModule) == null ? undefined : _a22.call(processWithBuiltins, id);
30147
- return builtinModule == null ? await importNodeModule(id) : builtinModule;
30148
- }
30149
- function importNodeModule(id) {
30150
- dynamicImport != null || (dynamicImport = Function("specifier", "return import(specifier)"));
30151
- return dynamicImport(id);
30289
+ if (builtinModule == null) {
30290
+ throw new Error(`Node.js built-in module ${id} is unavailable`);
30291
+ }
30292
+ return builtinModule;
30152
30293
  }
30153
30294
  function getCurrentModulePath() {
30154
30295
  const originalPrepareStackTrace = Error.prepareStackTrace;
@@ -30247,7 +30388,7 @@ async function readResponseWithSizeLimit({
30247
30388
  } finally {
30248
30389
  try {
30249
30390
  await reader.cancel();
30250
- } finally {
30391
+ } catch (e) {} finally {
30251
30392
  reader.releaseLock();
30252
30393
  }
30253
30394
  }
@@ -31512,7 +31653,7 @@ function createProviderToolFactoryWithOutputSchema({
31512
31653
  supportsDeferredResults
31513
31654
  });
31514
31655
  }
31515
- async function resolve20(value) {
31656
+ async function resolve21(value) {
31516
31657
  if (typeof value === "function") {
31517
31658
  value = value();
31518
31659
  }
@@ -31647,7 +31788,7 @@ var DelayedPromise = class {
31647
31788
  isPending() {
31648
31789
  return this.status.type === "pending";
31649
31790
  }
31650
- }, btoa, atob2, name14 = "AI_DownloadError", marker15, symbol17, _a15, _b15, DownloadError, safeNodeFetchPromise, initialGlobalFetch, initialGlobalFetchIsNodeDefault, dynamicImport, MAX_DOWNLOAD_REDIRECTS = 10, DEFAULT_MAX_DOWNLOAD_SIZE, createIdGenerator = ({
31791
+ }, btoa, atob2, name14 = "AI_DownloadError", marker15, symbol17, _a15, _b15, DownloadError, safeNodeFetchPromise, initialGlobalFetch, initialGlobalFetchIsNodeDefault, MAX_DOWNLOAD_REDIRECTS = 10, DEFAULT_MAX_DOWNLOAD_SIZE, createIdGenerator = ({
31651
31792
  prefix,
31652
31793
  size = 16,
31653
31794
  alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
@@ -31671,7 +31812,7 @@ var DelayedPromise = class {
31671
31812
  });
31672
31813
  }
31673
31814
  return () => `${prefix}${separator}${generator()}`;
31674
- }, generateId2, FETCH_FAILED_ERROR_MESSAGES, BUN_ERROR_CODES, VERSION = "4.0.42", getOriginalFetch = () => globalThis.fetch, getFromApi = async ({
31815
+ }, generateId2, FETCH_FAILED_ERROR_MESSAGES, BUN_ERROR_CODES, VERSION = "4.0.46", getOriginalFetch = () => globalThis.fetch, getFromApi = async ({
31675
31816
  url: url2,
31676
31817
  headers = {},
31677
31818
  successfulResponseHandler,
@@ -32191,23 +32332,23 @@ var DelayedPromise = class {
32191
32332
  });
32192
32333
  }
32193
32334
  };
32194
- var init_dist3 = __esm(() => {
32195
- init_dist();
32196
- init_dist();
32197
- init_dist();
32198
- init_dist();
32199
- init_dist();
32200
- init_dist();
32201
- init_dist();
32202
- init_dist();
32335
+ var init_dist4 = __esm(() => {
32336
+ init_dist2();
32337
+ init_dist2();
32338
+ init_dist2();
32339
+ init_dist2();
32340
+ init_dist2();
32341
+ init_dist2();
32342
+ init_dist2();
32343
+ init_dist2();
32203
32344
  init_v4();
32204
32345
  init_v3();
32205
32346
  init_v3();
32206
32347
  init_v3();
32207
32348
  init_stream();
32208
- init_dist();
32209
- init_dist();
32210
- init_dist();
32349
+ init_dist2();
32350
+ init_dist2();
32351
+ init_dist2();
32211
32352
  ({ btoa, atob: atob2 } = globalThis);
32212
32353
  marker15 = `vercel.ai.error.${name14}`;
32213
32354
  symbol17 = Symbol.for(marker15);
@@ -32300,7 +32441,7 @@ var init_dist3 = __esm(() => {
32300
32441
  textDecoder = new TextDecoder;
32301
32442
  });
32302
32443
 
32303
- // ../../node_modules/.bun/@ai-sdk+anthropic@3.0.107+27912429049419a2/node_modules/@ai-sdk/anthropic/dist/index.mjs
32444
+ // ../../node_modules/.bun/@ai-sdk+anthropic@3.0.111+27912429049419a2/node_modules/@ai-sdk/anthropic/dist/index.mjs
32304
32445
  var exports_dist = {};
32305
32446
  __export(exports_dist, {
32306
32447
  forwardAnthropicContainerIdFromLastStep: () => forwardAnthropicContainerIdFromLastStep,
@@ -32758,7 +32899,7 @@ async function convertToAnthropicMessagesPrompt({
32758
32899
  cacheControlValidator,
32759
32900
  toolNameMapping
32760
32901
  }) {
32761
- var _a16, _b16, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v;
32902
+ var _a16, _b16, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u;
32762
32903
  const betas = /* @__PURE__ */ new Set;
32763
32904
  const blocks = groupIntoBlocks(prompt);
32764
32905
  const validator = cacheControlValidator || new CacheControlValidator;
@@ -33146,6 +33287,7 @@ async function convertToAnthropicMessagesPrompt({
33146
33287
  break;
33147
33288
  }
33148
33289
  case "tool-call": {
33290
+ const caller = getAnthropicCaller(part.providerOptions);
33149
33291
  if (part.providerExecuted) {
33150
33292
  const providerToolName = toolNameMapping.toProviderToolName(part.toolName);
33151
33293
  const isMcpToolUse = ((_l = (_k = part.providerOptions) == null ? undefined : _k.anthropic) == null ? undefined : _l.type) === "mcp-tool-use";
@@ -33174,6 +33316,7 @@ async function convertToAnthropicMessagesPrompt({
33174
33316
  id: part.toolCallId,
33175
33317
  name: subtoolName,
33176
33318
  input,
33319
+ ...caller && { caller },
33177
33320
  cache_control: cacheControl
33178
33321
  });
33179
33322
  } else if (providerToolName === "code_execution" && part.input != null && typeof part.input === "object" && "type" in part.input && part.input.type === "programmatic-tool-call") {
@@ -33183,6 +33326,7 @@ async function convertToAnthropicMessagesPrompt({
33183
33326
  id: part.toolCallId,
33184
33327
  name: "code_execution",
33185
33328
  input: inputWithoutType,
33329
+ ...caller && { caller },
33186
33330
  cache_control: cacheControl
33187
33331
  });
33188
33332
  } else {
@@ -33192,6 +33336,7 @@ async function convertToAnthropicMessagesPrompt({
33192
33336
  id: part.toolCallId,
33193
33337
  name: providerToolName,
33194
33338
  input: part.input,
33339
+ ...caller && { caller },
33195
33340
  cache_control: cacheControl
33196
33341
  });
33197
33342
  } else if (providerToolName === "tool_search_tool_regex" || providerToolName === "tool_search_tool_bm25") {
@@ -33200,6 +33345,7 @@ async function convertToAnthropicMessagesPrompt({
33200
33345
  id: part.toolCallId,
33201
33346
  name: providerToolName,
33202
33347
  input: part.input,
33348
+ ...caller && { caller },
33203
33349
  cache_control: cacheControl
33204
33350
  });
33205
33351
  } else if (providerToolName === "advisor") {
@@ -33208,6 +33354,7 @@ async function convertToAnthropicMessagesPrompt({
33208
33354
  id: part.toolCallId,
33209
33355
  name: "advisor",
33210
33356
  input: {},
33357
+ ...caller && { caller },
33211
33358
  cache_control: cacheControl
33212
33359
  });
33213
33360
  } else {
@@ -33219,11 +33366,6 @@ async function convertToAnthropicMessagesPrompt({
33219
33366
  }
33220
33367
  break;
33221
33368
  }
33222
- const callerOptions = (_o = part.providerOptions) == null ? undefined : _o.anthropic;
33223
- const caller = (callerOptions == null ? undefined : callerOptions.caller) ? (callerOptions.caller.type === "code_execution_20250825" || callerOptions.caller.type === "code_execution_20260120") && callerOptions.caller.toolId ? {
33224
- type: callerOptions.caller.type,
33225
- tool_id: callerOptions.caller.toolId
33226
- } : callerOptions.caller.type === "direct" ? { type: "direct" } : undefined : undefined;
33227
33369
  anthropicContent.push({
33228
33370
  type: "tool_use",
33229
33371
  id: part.toolCallId,
@@ -33236,6 +33378,7 @@ async function convertToAnthropicMessagesPrompt({
33236
33378
  }
33237
33379
  case "tool-result": {
33238
33380
  const providerToolName = toolNameMapping.toProviderToolName(part.toolName);
33381
+ const caller = getAnthropicCaller(part.providerOptions);
33239
33382
  if (mcpToolUseIds.has(part.toolCallId)) {
33240
33383
  const output = part.output;
33241
33384
  if (output.type !== "json" && output.type !== "error-json") {
@@ -33269,7 +33412,7 @@ async function convertToAnthropicMessagesPrompt({
33269
33412
  tool_use_id: part.toolCallId,
33270
33413
  content: {
33271
33414
  type: "code_execution_tool_result_error",
33272
- error_code: (_p = errorInfo.errorCode) != null ? _p : "unknown"
33415
+ error_code: (_o = errorInfo.errorCode) != null ? _o : "unknown"
33273
33416
  },
33274
33417
  cache_control: cacheControl
33275
33418
  });
@@ -33280,7 +33423,7 @@ async function convertToAnthropicMessagesPrompt({
33280
33423
  cache_control: cacheControl,
33281
33424
  content: {
33282
33425
  type: "bash_code_execution_tool_result_error",
33283
- error_code: (_q = errorInfo.errorCode) != null ? _q : "unknown"
33426
+ error_code: (_p = errorInfo.errorCode) != null ? _p : "unknown"
33284
33427
  }
33285
33428
  });
33286
33429
  }
@@ -33313,7 +33456,7 @@ async function convertToAnthropicMessagesPrompt({
33313
33456
  stdout: codeExecutionOutput.stdout,
33314
33457
  stderr: codeExecutionOutput.stderr,
33315
33458
  return_code: codeExecutionOutput.return_code,
33316
- content: (_r = codeExecutionOutput.content) != null ? _r : []
33459
+ content: (_q = codeExecutionOutput.content) != null ? _q : []
33317
33460
  },
33318
33461
  cache_control: cacheControl
33319
33462
  });
@@ -33331,7 +33474,7 @@ async function convertToAnthropicMessagesPrompt({
33331
33474
  encrypted_stdout: codeExecutionOutput.encrypted_stdout,
33332
33475
  stderr: codeExecutionOutput.stderr,
33333
33476
  return_code: codeExecutionOutput.return_code,
33334
- content: (_s = codeExecutionOutput.content) != null ? _s : []
33477
+ content: (_r = codeExecutionOutput.content) != null ? _r : []
33335
33478
  },
33336
33479
  cache_control: cacheControl
33337
33480
  });
@@ -33350,7 +33493,7 @@ async function convertToAnthropicMessagesPrompt({
33350
33493
  stdout: codeExecutionOutput.stdout,
33351
33494
  stderr: codeExecutionOutput.stderr,
33352
33495
  return_code: codeExecutionOutput.return_code,
33353
- content: (_t = codeExecutionOutput.content) != null ? _t : []
33496
+ content: (_s = codeExecutionOutput.content) != null ? _s : []
33354
33497
  },
33355
33498
  cache_control: cacheControl
33356
33499
  });
@@ -33386,8 +33529,9 @@ async function convertToAnthropicMessagesPrompt({
33386
33529
  tool_use_id: part.toolCallId,
33387
33530
  content: {
33388
33531
  type: "web_fetch_tool_result_error",
33389
- error_code: (_u = (await extractErrorValue(output.value)).errorCode) != null ? _u : "unavailable"
33532
+ error_code: (_t = (await extractErrorValue(output.value)).errorCode) != null ? _t : "unavailable"
33390
33533
  },
33534
+ ...caller && { caller },
33391
33535
  cache_control: cacheControl
33392
33536
  });
33393
33537
  break;
@@ -33421,6 +33565,7 @@ async function convertToAnthropicMessagesPrompt({
33421
33565
  }
33422
33566
  }
33423
33567
  },
33568
+ ...caller && { caller },
33424
33569
  cache_control: cacheControl
33425
33570
  });
33426
33571
  break;
@@ -33433,8 +33578,9 @@ async function convertToAnthropicMessagesPrompt({
33433
33578
  tool_use_id: part.toolCallId,
33434
33579
  content: {
33435
33580
  type: "web_search_tool_result_error",
33436
- error_code: (_v = (await extractErrorValue(output.value)).errorCode) != null ? _v : "unavailable"
33581
+ error_code: (_u = (await extractErrorValue(output.value)).errorCode) != null ? _u : "unavailable"
33437
33582
  },
33583
+ ...caller && { caller },
33438
33584
  cache_control: cacheControl
33439
33585
  });
33440
33586
  break;
@@ -33460,6 +33606,7 @@ async function convertToAnthropicMessagesPrompt({
33460
33606
  encrypted_content: result.encryptedContent,
33461
33607
  type: result.type
33462
33608
  })),
33609
+ ...caller && { caller },
33463
33610
  cache_control: cacheControl
33464
33611
  });
33465
33612
  break;
@@ -33628,6 +33775,17 @@ function moveToolUseBlocksToEnd(content) {
33628
33775
  flushSegment();
33629
33776
  return result;
33630
33777
  }
33778
+ function getAnthropicCaller(providerOptions) {
33779
+ var _a16;
33780
+ const caller = (_a16 = providerOptions == null ? undefined : providerOptions.anthropic) == null ? undefined : _a16.caller;
33781
+ if (((caller == null ? undefined : caller.type) === "code_execution_20250825" || (caller == null ? undefined : caller.type) === "code_execution_20260120") && caller.toolId) {
33782
+ return {
33783
+ type: caller.type,
33784
+ tool_id: caller.toolId
33785
+ };
33786
+ }
33787
+ return (caller == null ? undefined : caller.type) === "direct" ? { type: "direct" } : undefined;
33788
+ }
33631
33789
  function mapAnthropicStopReason({
33632
33790
  finishReason,
33633
33791
  isJsonResponseFromTool
@@ -33804,6 +33962,16 @@ function createCitationSource(citation, citationDocuments, generateId3) {
33804
33962
  }
33805
33963
  };
33806
33964
  }
33965
+ function getAnthropicCallerInfo(caller) {
33966
+ return caller == null ? undefined : {
33967
+ type: caller.type,
33968
+ toolId: "tool_id" in caller ? caller.tool_id : undefined
33969
+ };
33970
+ }
33971
+ function getAnthropicCallerMetadata(caller) {
33972
+ const callerInfo = getAnthropicCallerInfo(caller);
33973
+ return callerInfo == null ? {} : { providerMetadata: { anthropic: { caller: callerInfo } } };
33974
+ }
33807
33975
  function getModelCapabilities(modelId) {
33808
33976
  if (modelId.includes("claude-opus-5")) {
33809
33977
  return {
@@ -34032,7 +34200,7 @@ function forwardAnthropicContainerIdFromLastStep({
34032
34200
  }
34033
34201
  return;
34034
34202
  }
34035
- var VERSION2 = "3.0.107", anthropicErrorDataSchema, anthropicFailedResponseHandler, anthropicStopDetailsSchema, anthropicMessagesResponseSchema, anthropicMessagesChunkSchema, anthropicReasoningMetadataSchema, anthropicFilePartProviderOptions, anthropicSystemMessageProviderOptions, anthropicLanguageModelOptions, MAX_CACHE_BREAKPOINTS = 4, CacheControlValidator = class {
34203
+ var VERSION2 = "3.0.111", anthropicErrorDataSchema, anthropicFailedResponseHandler, anthropicStopDetailsSchema, anthropicToolCallCallerSchema, anthropicMessagesResponseSchema, anthropicMessagesChunkSchema, anthropicReasoningMetadataSchema, anthropicFilePartProviderOptions, anthropicSystemMessageProviderOptions, anthropicLanguageModelOptions, MAX_CACHE_BREAKPOINTS = 4, CacheControlValidator = class {
34036
34204
  constructor() {
34037
34205
  this.breakpointCount = 0;
34038
34206
  this.warnings = [];
@@ -34540,11 +34708,11 @@ var VERSION2 = "3.0.107", anthropicErrorDataSchema, anthropicFailedResponseHandl
34540
34708
  betas,
34541
34709
  headers
34542
34710
  }) {
34543
- return combineHeaders(await resolve20(this.config.headers), headers, betas.size > 0 ? { "anthropic-beta": Array.from(betas).join(",") } : {});
34711
+ return combineHeaders(await resolve21(this.config.headers), headers, betas.size > 0 ? { "anthropic-beta": Array.from(betas).join(",") } : {});
34544
34712
  }
34545
34713
  async getBetasFromHeaders(requestHeaders) {
34546
34714
  var _a16, _b16;
34547
- const configHeaders = await resolve20(this.config.headers);
34715
+ const configHeaders = await resolve21(this.config.headers);
34548
34716
  const configBetaHeader = (_a16 = configHeaders["anthropic-beta"]) != null ? _a16 : "";
34549
34717
  const requestBetaHeader = (_b16 = requestHeaders == null ? undefined : requestHeaders["anthropic-beta"]) != null ? _b16 : "";
34550
34718
  return new Set([
@@ -34691,23 +34859,12 @@ var VERSION2 = "3.0.107", anthropicErrorDataSchema, anthropicFailedResponseHandl
34691
34859
  text: JSON.stringify(part.input)
34692
34860
  });
34693
34861
  } else {
34694
- const caller = part.caller;
34695
- const callerInfo = caller ? {
34696
- type: caller.type,
34697
- toolId: "tool_id" in caller ? caller.tool_id : undefined
34698
- } : undefined;
34699
34862
  content.push({
34700
34863
  type: "tool-call",
34701
34864
  toolCallId: part.id,
34702
34865
  toolName: part.name,
34703
34866
  input: JSON.stringify(part.input),
34704
- ...callerInfo && {
34705
- providerMetadata: {
34706
- anthropic: {
34707
- caller: callerInfo
34708
- }
34709
- }
34710
- }
34867
+ ...getAnthropicCallerMetadata(part.caller)
34711
34868
  });
34712
34869
  }
34713
34870
  break;
@@ -34721,7 +34878,8 @@ var VERSION2 = "3.0.107", anthropicErrorDataSchema, anthropicFailedResponseHandl
34721
34878
  toolName: toolNameMapping.toCustomToolName("code_execution"),
34722
34879
  input: JSON.stringify({ type: part.name, ...part.input }),
34723
34880
  providerExecuted: true,
34724
- ...markCodeExecutionDynamic && providerToolName === "code_execution" ? { dynamic: true } : {}
34881
+ ...markCodeExecutionDynamic && providerToolName === "code_execution" ? { dynamic: true } : {},
34882
+ ...getAnthropicCallerMetadata(part.caller)
34725
34883
  });
34726
34884
  } else if (part.name === "web_search" || part.name === "code_execution" || part.name === "web_fetch") {
34727
34885
  const inputToSerialize = part.name === "code_execution" && part.input != null && typeof part.input === "object" && "code" in part.input && !("type" in part.input) ? { type: "programmatic-tool-call", ...part.input } : part.input;
@@ -34731,7 +34889,8 @@ var VERSION2 = "3.0.107", anthropicErrorDataSchema, anthropicFailedResponseHandl
34731
34889
  toolName: toolNameMapping.toCustomToolName(part.name),
34732
34890
  input: JSON.stringify(inputToSerialize),
34733
34891
  providerExecuted: true,
34734
- ...markCodeExecutionDynamic && part.name === "code_execution" ? { dynamic: true } : {}
34892
+ ...markCodeExecutionDynamic && part.name === "code_execution" ? { dynamic: true } : {},
34893
+ ...getAnthropicCallerMetadata(part.caller)
34735
34894
  });
34736
34895
  } else if (part.name === "tool_search_tool_regex" || part.name === "tool_search_tool_bm25") {
34737
34896
  serverToolCalls[part.id] = part.name;
@@ -34740,7 +34899,8 @@ var VERSION2 = "3.0.107", anthropicErrorDataSchema, anthropicFailedResponseHandl
34740
34899
  toolCallId: part.id,
34741
34900
  toolName: toolNameMapping.toCustomToolName(part.name),
34742
34901
  input: JSON.stringify(part.input),
34743
- providerExecuted: true
34902
+ providerExecuted: true,
34903
+ ...getAnthropicCallerMetadata(part.caller)
34744
34904
  });
34745
34905
  } else if (part.name === "advisor") {
34746
34906
  content.push({
@@ -34748,7 +34908,8 @@ var VERSION2 = "3.0.107", anthropicErrorDataSchema, anthropicFailedResponseHandl
34748
34908
  toolCallId: part.id,
34749
34909
  toolName: toolNameMapping.toCustomToolName("advisor"),
34750
34910
  input: JSON.stringify(part.input),
34751
- providerExecuted: true
34911
+ providerExecuted: true,
34912
+ ...getAnthropicCallerMetadata(part.caller)
34752
34913
  });
34753
34914
  }
34754
34915
  break;
@@ -34807,7 +34968,8 @@ var VERSION2 = "3.0.107", anthropicErrorDataSchema, anthropicFailedResponseHandl
34807
34968
  data: part.content.content.source.data
34808
34969
  }
34809
34970
  }
34810
- }
34971
+ },
34972
+ ...getAnthropicCallerMetadata(part.caller)
34811
34973
  });
34812
34974
  } else if (part.content.type === "web_fetch_tool_result_error") {
34813
34975
  content.push({
@@ -34818,7 +34980,8 @@ var VERSION2 = "3.0.107", anthropicErrorDataSchema, anthropicFailedResponseHandl
34818
34980
  result: {
34819
34981
  type: "web_fetch_tool_result_error",
34820
34982
  errorCode: part.content.error_code
34821
- }
34983
+ },
34984
+ ...getAnthropicCallerMetadata(part.caller)
34822
34985
  });
34823
34986
  }
34824
34987
  break;
@@ -34838,7 +35001,8 @@ var VERSION2 = "3.0.107", anthropicErrorDataSchema, anthropicFailedResponseHandl
34838
35001
  encryptedContent: result.encrypted_content,
34839
35002
  type: result.type
34840
35003
  };
34841
- })
35004
+ }),
35005
+ ...getAnthropicCallerMetadata(part.caller)
34842
35006
  });
34843
35007
  for (const result of part.content) {
34844
35008
  content.push({
@@ -34863,7 +35027,8 @@ var VERSION2 = "3.0.107", anthropicErrorDataSchema, anthropicFailedResponseHandl
34863
35027
  result: {
34864
35028
  type: "web_search_tool_result_error",
34865
35029
  errorCode: part.content.error_code
34866
- }
35030
+ },
35031
+ ...getAnthropicCallerMetadata(part.caller)
34867
35032
  });
34868
35033
  }
34869
35034
  break;
@@ -35204,11 +35369,7 @@ var VERSION2 = "3.0.107", anthropicErrorDataSchema, anthropicFailedResponseHandl
35204
35369
  id: String(value.index)
35205
35370
  });
35206
35371
  } else {
35207
- const caller = part.caller;
35208
- const callerInfo = caller ? {
35209
- type: caller.type,
35210
- toolId: "tool_id" in caller ? caller.tool_id : undefined
35211
- } : undefined;
35372
+ const callerInfo = getAnthropicCallerInfo(part.caller);
35212
35373
  const hasNonEmptyInput = part.input && Object.keys(part.input).length > 0;
35213
35374
  const initialInput = hasNonEmptyInput ? JSON.stringify(part.input) : "";
35214
35375
  contentBlocks[value.index] = {
@@ -35228,6 +35389,7 @@ var VERSION2 = "3.0.107", anthropicErrorDataSchema, anthropicFailedResponseHandl
35228
35389
  return;
35229
35390
  }
35230
35391
  case "server_tool_use": {
35392
+ const callerInfo = getAnthropicCallerInfo(part.caller);
35231
35393
  if ([
35232
35394
  "web_fetch",
35233
35395
  "web_search",
@@ -35248,7 +35410,8 @@ var VERSION2 = "3.0.107", anthropicErrorDataSchema, anthropicFailedResponseHandl
35248
35410
  ...markCodeExecutionDynamic && providerToolName === "code_execution" ? { dynamic: true } : {},
35249
35411
  firstDelta: finalInput.length === 0,
35250
35412
  providerToolName,
35251
- providerToolInputType
35413
+ providerToolInputType,
35414
+ ...callerInfo && { caller: callerInfo }
35252
35415
  };
35253
35416
  controller.enqueue({
35254
35417
  type: "tool-input-start",
@@ -35267,7 +35430,8 @@ var VERSION2 = "3.0.107", anthropicErrorDataSchema, anthropicFailedResponseHandl
35267
35430
  input: "",
35268
35431
  providerExecuted: true,
35269
35432
  firstDelta: true,
35270
- providerToolName: part.name
35433
+ providerToolName: part.name,
35434
+ ...callerInfo && { caller: callerInfo }
35271
35435
  };
35272
35436
  controller.enqueue({
35273
35437
  type: "tool-input-start",
@@ -35284,7 +35448,8 @@ var VERSION2 = "3.0.107", anthropicErrorDataSchema, anthropicFailedResponseHandl
35284
35448
  input: "{}",
35285
35449
  providerExecuted: true,
35286
35450
  firstDelta: true,
35287
- providerToolName: part.name
35451
+ providerToolName: part.name,
35452
+ ...callerInfo && { caller: callerInfo }
35288
35453
  };
35289
35454
  controller.enqueue({
35290
35455
  type: "tool-input-start",
@@ -35319,7 +35484,8 @@ var VERSION2 = "3.0.107", anthropicErrorDataSchema, anthropicFailedResponseHandl
35319
35484
  data: part.content.content.source.data
35320
35485
  }
35321
35486
  }
35322
- }
35487
+ },
35488
+ ...getAnthropicCallerMetadata(part.caller)
35323
35489
  });
35324
35490
  } else if (part.content.type === "web_fetch_tool_result_error") {
35325
35491
  controller.enqueue({
@@ -35330,7 +35496,8 @@ var VERSION2 = "3.0.107", anthropicErrorDataSchema, anthropicFailedResponseHandl
35330
35496
  result: {
35331
35497
  type: "web_fetch_tool_result_error",
35332
35498
  errorCode: part.content.error_code
35333
- }
35499
+ },
35500
+ ...getAnthropicCallerMetadata(part.caller)
35334
35501
  });
35335
35502
  }
35336
35503
  return;
@@ -35350,7 +35517,8 @@ var VERSION2 = "3.0.107", anthropicErrorDataSchema, anthropicFailedResponseHandl
35350
35517
  encryptedContent: result.encrypted_content,
35351
35518
  type: result.type
35352
35519
  };
35353
- })
35520
+ }),
35521
+ ...getAnthropicCallerMetadata(part.caller)
35354
35522
  });
35355
35523
  for (const result of part.content) {
35356
35524
  controller.enqueue({
@@ -35375,7 +35543,8 @@ var VERSION2 = "3.0.107", anthropicErrorDataSchema, anthropicFailedResponseHandl
35375
35543
  result: {
35376
35544
  type: "web_search_tool_result_error",
35377
35545
  errorCode: part.content.error_code
35378
- }
35546
+ },
35547
+ ...getAnthropicCallerMetadata(part.caller)
35379
35548
  });
35380
35549
  }
35381
35550
  return;
@@ -35753,11 +35922,7 @@ var VERSION2 = "3.0.107", anthropicErrorDataSchema, anthropicFailedResponseHandl
35753
35922
  for (let contentIndex = 0;contentIndex < value.message.content.length; contentIndex++) {
35754
35923
  const part = value.message.content[contentIndex];
35755
35924
  if (part.type === "tool_use") {
35756
- const caller = part.caller;
35757
- const callerInfo = caller ? {
35758
- type: caller.type,
35759
- toolId: "tool_id" in caller ? caller.tool_id : undefined
35760
- } : undefined;
35925
+ const callerInfo = getAnthropicCallerInfo(part.caller);
35761
35926
  controller.enqueue({
35762
35927
  type: "tool-input-start",
35763
35928
  id: part.id,
@@ -35917,59 +36082,59 @@ var VERSION2 = "3.0.107", anthropicErrorDataSchema, anthropicFailedResponseHandl
35917
36082
  }, bash_20241022InputSchema, bash_20241022, bash_20250124InputSchema, bash_20250124, computer_20241022InputSchema, computer_20241022, computer_20250124InputSchema, computer_20250124, computer_20251124InputSchema, computer_20251124, memory_20250818InputSchema, memory_20250818, textEditor_20241022InputSchema, textEditor_20241022, textEditor_20250124InputSchema, textEditor_20250124, textEditor_20250429InputSchema, textEditor_20250429, toolSearchBm25_20251119OutputSchema, toolSearchBm25_20251119InputSchema, factory11, toolSearchBm25_20251119 = (args = {}) => {
35918
36083
  return factory11(args);
35919
36084
  }, anthropicTools, ANTHROPIC_API_URL = "https://api.anthropic.com", ANTHROPIC_API_VERSIONED_URL, anthropic;
35920
- var init_dist4 = __esm(() => {
35921
- init_dist();
35922
- init_dist3();
35923
- init_dist();
35924
- init_dist3();
35925
- init_dist3();
36085
+ var init_dist5 = __esm(() => {
36086
+ init_dist2();
36087
+ init_dist4();
36088
+ init_dist2();
36089
+ init_dist4();
36090
+ init_dist4();
35926
36091
  init_v4();
35927
- init_dist3();
36092
+ init_dist4();
35928
36093
  init_v4();
35929
36094
  init_v4();
35930
- init_dist();
35931
- init_dist3();
36095
+ init_dist2();
36096
+ init_dist4();
35932
36097
  init_v4();
35933
- init_dist3();
36098
+ init_dist4();
35934
36099
  init_v4();
35935
- init_dist3();
36100
+ init_dist4();
35936
36101
  init_v4();
35937
- init_dist3();
36102
+ init_dist4();
35938
36103
  init_v4();
35939
- init_dist3();
36104
+ init_dist4();
35940
36105
  init_v4();
35941
- init_dist3();
36106
+ init_dist4();
35942
36107
  init_v4();
35943
- init_dist3();
35944
- init_dist();
35945
- init_dist3();
35946
- init_dist3();
36108
+ init_dist4();
36109
+ init_dist2();
36110
+ init_dist4();
36111
+ init_dist4();
35947
36112
  init_v4();
35948
- init_dist3();
36113
+ init_dist4();
35949
36114
  init_v4();
35950
- init_dist3();
36115
+ init_dist4();
35951
36116
  init_v4();
35952
- init_dist3();
36117
+ init_dist4();
35953
36118
  init_v4();
35954
- init_dist3();
36119
+ init_dist4();
35955
36120
  init_v4();
35956
- init_dist3();
36121
+ init_dist4();
35957
36122
  init_v4();
35958
- init_dist3();
36123
+ init_dist4();
35959
36124
  init_v4();
35960
- init_dist3();
36125
+ init_dist4();
35961
36126
  init_v4();
35962
- init_dist3();
36127
+ init_dist4();
35963
36128
  init_v4();
35964
- init_dist3();
36129
+ init_dist4();
35965
36130
  init_v4();
35966
- init_dist3();
36131
+ init_dist4();
35967
36132
  init_v4();
35968
- init_dist3();
36133
+ init_dist4();
35969
36134
  init_v4();
35970
- init_dist3();
36135
+ init_dist4();
35971
36136
  init_v4();
35972
- init_dist3();
36137
+ init_dist4();
35973
36138
  init_v4();
35974
36139
  anthropicErrorDataSchema = lazySchema(() => zodSchema(exports_external2.object({
35975
36140
  type: exports_external2.literal("error"),
@@ -35988,6 +36153,19 @@ var init_dist4 = __esm(() => {
35988
36153
  explanation: exports_external2.string().nullish(),
35989
36154
  recommended_model: exports_external2.string().nullish()
35990
36155
  });
36156
+ anthropicToolCallCallerSchema = exports_external2.union([
36157
+ exports_external2.object({
36158
+ type: exports_external2.literal("code_execution_20250825"),
36159
+ tool_id: exports_external2.string()
36160
+ }),
36161
+ exports_external2.object({
36162
+ type: exports_external2.literal("code_execution_20260120"),
36163
+ tool_id: exports_external2.string()
36164
+ }),
36165
+ exports_external2.object({
36166
+ type: exports_external2.literal("direct")
36167
+ })
36168
+ ]);
35991
36169
  anthropicMessagesResponseSchema = lazySchema(() => zodSchema(exports_external2.object({
35992
36170
  type: exports_external2.literal("message"),
35993
36171
  id: exports_external2.string().nullish(),
@@ -36040,34 +36218,14 @@ var init_dist4 = __esm(() => {
36040
36218
  id: exports_external2.string(),
36041
36219
  name: exports_external2.string(),
36042
36220
  input: exports_external2.unknown(),
36043
- caller: exports_external2.union([
36044
- exports_external2.object({
36045
- type: exports_external2.literal("code_execution_20250825"),
36046
- tool_id: exports_external2.string()
36047
- }),
36048
- exports_external2.object({
36049
- type: exports_external2.literal("code_execution_20260120"),
36050
- tool_id: exports_external2.string()
36051
- }),
36052
- exports_external2.object({
36053
- type: exports_external2.literal("direct")
36054
- })
36055
- ]).optional()
36221
+ caller: anthropicToolCallCallerSchema.optional()
36056
36222
  }),
36057
36223
  exports_external2.object({
36058
36224
  type: exports_external2.literal("server_tool_use"),
36059
36225
  id: exports_external2.string(),
36060
36226
  name: exports_external2.string(),
36061
36227
  input: exports_external2.record(exports_external2.string(), exports_external2.unknown()).nullish(),
36062
- caller: exports_external2.union([
36063
- exports_external2.object({
36064
- type: exports_external2.literal("code_execution_20260120"),
36065
- tool_id: exports_external2.string()
36066
- }),
36067
- exports_external2.object({
36068
- type: exports_external2.literal("direct")
36069
- })
36070
- ]).optional()
36228
+ caller: anthropicToolCallCallerSchema.optional()
36071
36229
  }),
36072
36230
  exports_external2.object({
36073
36231
  type: exports_external2.literal("mcp_tool_use"),
@@ -36088,6 +36246,7 @@ var init_dist4 = __esm(() => {
36088
36246
  exports_external2.object({
36089
36247
  type: exports_external2.literal("web_fetch_tool_result"),
36090
36248
  tool_use_id: exports_external2.string(),
36249
+ caller: anthropicToolCallCallerSchema.optional(),
36091
36250
  content: exports_external2.union([
36092
36251
  exports_external2.object({
36093
36252
  type: exports_external2.literal("web_fetch_result"),
@@ -36120,6 +36279,7 @@ var init_dist4 = __esm(() => {
36120
36279
  exports_external2.object({
36121
36280
  type: exports_external2.literal("web_search_tool_result"),
36122
36281
  tool_use_id: exports_external2.string(),
36282
+ caller: anthropicToolCallCallerSchema.optional(),
36123
36283
  content: exports_external2.union([
36124
36284
  exports_external2.array(exports_external2.object({
36125
36285
  type: exports_external2.literal("web_search_result"),
@@ -36323,19 +36483,7 @@ var init_dist4 = __esm(() => {
36323
36483
  id: exports_external2.string(),
36324
36484
  name: exports_external2.string(),
36325
36485
  input: exports_external2.unknown(),
36326
- caller: exports_external2.union([
36327
- exports_external2.object({
36328
- type: exports_external2.literal("code_execution_20250825"),
36329
- tool_id: exports_external2.string()
36330
- }),
36331
- exports_external2.object({
36332
- type: exports_external2.literal("code_execution_20260120"),
36333
- tool_id: exports_external2.string()
36334
- }),
36335
- exports_external2.object({
36336
- type: exports_external2.literal("direct")
36337
- })
36338
- ]).optional()
36486
+ caller: anthropicToolCallCallerSchema.optional()
36339
36487
  })
36340
36488
  ])).nullish(),
36341
36489
  stop_reason: exports_external2.string().nullish(),
@@ -36362,19 +36510,7 @@ var init_dist4 = __esm(() => {
36362
36510
  id: exports_external2.string(),
36363
36511
  name: exports_external2.string(),
36364
36512
  input: exports_external2.record(exports_external2.string(), exports_external2.unknown()).optional(),
36365
- caller: exports_external2.union([
36366
- exports_external2.object({
36367
- type: exports_external2.literal("code_execution_20250825"),
36368
- tool_id: exports_external2.string()
36369
- }),
36370
- exports_external2.object({
36371
- type: exports_external2.literal("code_execution_20260120"),
36372
- tool_id: exports_external2.string()
36373
- }),
36374
- exports_external2.object({
36375
- type: exports_external2.literal("direct")
36376
- })
36377
- ]).optional()
36513
+ caller: anthropicToolCallCallerSchema.optional()
36378
36514
  }),
36379
36515
  exports_external2.object({
36380
36516
  type: exports_external2.literal("redacted_thinking"),
@@ -36389,15 +36525,7 @@ var init_dist4 = __esm(() => {
36389
36525
  id: exports_external2.string(),
36390
36526
  name: exports_external2.string(),
36391
36527
  input: exports_external2.record(exports_external2.string(), exports_external2.unknown()).nullish(),
36392
- caller: exports_external2.union([
36393
- exports_external2.object({
36394
- type: exports_external2.literal("code_execution_20260120"),
36395
- tool_id: exports_external2.string()
36396
- }),
36397
- exports_external2.object({
36398
- type: exports_external2.literal("direct")
36399
- })
36400
- ]).optional()
36528
+ caller: anthropicToolCallCallerSchema.optional()
36401
36529
  }),
36402
36530
  exports_external2.object({
36403
36531
  type: exports_external2.literal("mcp_tool_use"),
@@ -36418,6 +36546,7 @@ var init_dist4 = __esm(() => {
36418
36546
  exports_external2.object({
36419
36547
  type: exports_external2.literal("web_fetch_tool_result"),
36420
36548
  tool_use_id: exports_external2.string(),
36549
+ caller: anthropicToolCallCallerSchema.optional(),
36421
36550
  content: exports_external2.union([
36422
36551
  exports_external2.object({
36423
36552
  type: exports_external2.literal("web_fetch_result"),
@@ -36450,6 +36579,7 @@ var init_dist4 = __esm(() => {
36450
36579
  exports_external2.object({
36451
36580
  type: exports_external2.literal("web_search_tool_result"),
36452
36581
  tool_use_id: exports_external2.string(),
36582
+ caller: anthropicToolCallCallerSchema.optional(),
36453
36583
  content: exports_external2.union([
36454
36584
  exports_external2.array(exports_external2.object({
36455
36585
  type: exports_external2.literal("web_search_result"),
@@ -37489,7 +37619,7 @@ var init_dist4 = __esm(() => {
37489
37619
  anthropic = createAnthropic();
37490
37620
  });
37491
37621
 
37492
- // ../../node_modules/.bun/@ai-sdk+openai@3.0.91+27912429049419a2/node_modules/@ai-sdk/openai/dist/index.mjs
37622
+ // ../../node_modules/.bun/@ai-sdk+openai@3.0.97+27912429049419a2/node_modules/@ai-sdk/openai/dist/index.mjs
37493
37623
  var exports_dist2 = {};
37494
37624
  __export(exports_dist2, {
37495
37625
  openai: () => openai,
@@ -38426,12 +38556,14 @@ async function convertToOpenAIResponsesInput({
38426
38556
  if (store && id != null) {
38427
38557
  input.push({ type: "item_reference", id });
38428
38558
  }
38429
- break;
38559
+ if (store || !hasShellTool || resolvedToolName !== "shell") {
38560
+ break;
38561
+ }
38430
38562
  }
38431
- if (hasPreviousResponseId && store && id != null) {
38563
+ const isProviderDefinedToolCall = hasLocalShellTool && resolvedToolName === "local_shell" || hasShellTool && resolvedToolName === "shell" || hasApplyPatchTool && resolvedToolName === "apply_patch" || ((_m = customProviderToolNames == null ? undefined : customProviderToolNames.has(resolvedToolName)) != null ? _m : false);
38564
+ if (hasPreviousResponseId && store && id != null && isProviderDefinedToolCall) {
38432
38565
  break;
38433
38566
  }
38434
- const isProviderDefinedToolCall = hasLocalShellTool && resolvedToolName === "local_shell" || hasShellTool && resolvedToolName === "shell" || hasApplyPatchTool && resolvedToolName === "apply_patch" || ((_m = customProviderToolNames == null ? undefined : customProviderToolNames.has(resolvedToolName)) != null ? _m : false);
38435
38567
  if (store && id != null && isProviderDefinedToolCall) {
38436
38568
  input.push({ type: "item_reference", id });
38437
38569
  break;
@@ -38652,7 +38784,7 @@ async function convertToOpenAIResponsesInput({
38652
38784
  continue;
38653
38785
  }
38654
38786
  processedApprovalIds.add(approvalResponse.approvalId);
38655
- if (store) {
38787
+ if (store && !hasConversation && !hasPreviousResponseId) {
38656
38788
  input.push({
38657
38789
  type: "item_reference",
38658
38790
  id: approvalResponse.approvalId
@@ -39616,7 +39748,7 @@ var openaiErrorDataSchema, openaiFailedResponseHandler, openaiChatResponseSchema
39616
39748
  });
39617
39749
  baseArgs.service_tier = undefined;
39618
39750
  }
39619
- if (openaiOptions.serviceTier === "priority" && !modelCapabilities.supportsPriorityProcessing) {
39751
+ if ((openaiOptions.serviceTier === "priority" || openaiOptions.serviceTier === "fast") && !modelCapabilities.supportsPriorityProcessing) {
39620
39752
  warnings.push({
39621
39753
  type: "unsupported",
39622
39754
  feature: "serviceTier",
@@ -40626,7 +40758,7 @@ var openaiErrorDataSchema, openaiFailedResponseHandler, openaiChatResponseSchema
40626
40758
  });
40627
40759
  delete baseArgs.service_tier;
40628
40760
  }
40629
- if ((openaiOptions == null ? undefined : openaiOptions.serviceTier) === "priority" && !modelCapabilities.supportsPriorityProcessing) {
40761
+ if (((openaiOptions == null ? undefined : openaiOptions.serviceTier) === "priority" || (openaiOptions == null ? undefined : openaiOptions.serviceTier) === "fast") && !modelCapabilities.supportsPriorityProcessing) {
40630
40762
  warnings.push({
40631
40763
  type: "unsupported",
40632
40764
  feature: "serviceTier",
@@ -42206,78 +42338,78 @@ var openaiErrorDataSchema, openaiFailedResponseHandler, openaiChatResponseSchema
42206
42338
  }
42207
42339
  };
42208
42340
  }
42209
- }, VERSION3 = "3.0.91", openai;
42210
- var init_dist5 = __esm(() => {
42211
- init_dist3();
42212
- init_dist();
42213
- init_dist3();
42341
+ }, VERSION3 = "3.0.97", openai;
42342
+ var init_dist6 = __esm(() => {
42343
+ init_dist4();
42344
+ init_dist2();
42345
+ init_dist4();
42214
42346
  init_v4();
42215
- init_dist3();
42216
- init_dist();
42217
- init_dist();
42218
- init_dist3();
42219
- init_dist3();
42347
+ init_dist4();
42348
+ init_dist2();
42349
+ init_dist2();
42350
+ init_dist4();
42351
+ init_dist4();
42220
42352
  init_v4();
42221
- init_dist3();
42353
+ init_dist4();
42222
42354
  init_v4();
42223
- init_dist();
42224
- init_dist3();
42225
- init_dist();
42355
+ init_dist2();
42356
+ init_dist4();
42357
+ init_dist2();
42226
42358
  init_v4();
42227
- init_dist3();
42228
- init_dist3();
42359
+ init_dist4();
42360
+ init_dist4();
42229
42361
  init_v4();
42230
- init_dist();
42231
- init_dist3();
42232
- init_dist3();
42362
+ init_dist2();
42363
+ init_dist4();
42364
+ init_dist4();
42233
42365
  init_v4();
42234
- init_dist3();
42366
+ init_dist4();
42235
42367
  init_v4();
42236
- init_dist3();
42237
- init_dist3();
42368
+ init_dist4();
42369
+ init_dist4();
42238
42370
  init_v4();
42239
- init_dist3();
42371
+ init_dist4();
42240
42372
  init_v4();
42241
- init_dist3();
42373
+ init_dist4();
42242
42374
  init_v4();
42243
- init_dist3();
42375
+ init_dist4();
42244
42376
  init_v4();
42245
- init_dist3();
42377
+ init_dist4();
42246
42378
  init_v4();
42247
- init_dist3();
42379
+ init_dist4();
42248
42380
  init_v4();
42249
- init_dist3();
42381
+ init_dist4();
42250
42382
  init_v4();
42251
- init_dist3();
42383
+ init_dist4();
42252
42384
  init_v4();
42253
- init_dist3();
42385
+ init_dist4();
42254
42386
  init_v4();
42255
- init_dist3();
42387
+ init_dist4();
42256
42388
  init_v4();
42257
- init_dist3();
42389
+ init_dist4();
42258
42390
  init_v4();
42259
- init_dist3();
42391
+ init_dist4();
42260
42392
  init_v4();
42261
- init_dist3();
42393
+ init_dist4();
42262
42394
  init_v4();
42263
- init_dist();
42264
- init_dist3();
42265
- init_dist();
42266
- init_dist3();
42395
+ init_dist2();
42396
+ init_dist4();
42397
+ init_dist2();
42398
+ init_dist4();
42267
42399
  init_v4();
42268
- init_dist3();
42400
+ init_dist4();
42269
42401
  init_v4();
42270
- init_dist3();
42402
+ init_dist4();
42271
42403
  init_v4();
42272
- init_dist();
42273
- init_dist3();
42274
- init_dist3();
42275
- init_dist3();
42404
+ init_dist2();
42405
+ init_dist4();
42406
+ init_dist4();
42407
+ init_dist4();
42276
42408
  init_v4();
42277
- init_dist3();
42278
- init_dist3();
42409
+ init_dist4();
42410
+ init_dist4();
42279
42411
  init_v4();
42280
- init_dist3();
42412
+ init_dist4();
42281
42413
  init_v4();
42282
42414
  openaiErrorDataSchema = exports_external2.object({
42283
42415
  error: exports_external2.object({
@@ -42413,7 +42545,7 @@ var init_dist5 = __esm(() => {
42413
42545
  store: exports_external2.boolean().optional(),
42414
42546
  metadata: exports_external2.record(exports_external2.string().max(64), exports_external2.string().max(512)).optional(),
42415
42547
  prediction: exports_external2.record(exports_external2.string(), exports_external2.any()).optional(),
42416
- serviceTier: exports_external2.enum(["auto", "flex", "priority", "default"]).optional(),
42548
+ serviceTier: exports_external2.enum(["auto", "flex", "priority", "fast", "default"]).optional(),
42417
42549
  strictJsonSchema: exports_external2.boolean().optional(),
42418
42550
  textVerbosity: exports_external2.enum(["low", "medium", "high"]).optional(),
42419
42551
  promptCacheKey: exports_external2.string().optional(),
@@ -43825,7 +43957,7 @@ var init_dist5 = __esm(() => {
43825
43957
  reasoningContext: exports_external2.enum(["auto", "current_turn", "all_turns"]).optional(),
43826
43958
  reasoningSummary: exports_external2.string().nullish(),
43827
43959
  safetyIdentifier: exports_external2.string().nullish(),
43828
- serviceTier: exports_external2.enum(["auto", "flex", "priority", "default"]).nullish(),
43960
+ serviceTier: exports_external2.enum(["auto", "flex", "priority", "fast", "default"]).nullish(),
43829
43961
  store: exports_external2.boolean().nullish(),
43830
43962
  passThroughUnsupportedFiles: exports_external2.boolean().optional(),
43831
43963
  strictJsonSchema: exports_external2.boolean().nullish(),
@@ -43934,7 +44066,7 @@ var init_dist5 = __esm(() => {
43934
44066
  openai = createOpenAI();
43935
44067
  });
43936
44068
 
43937
- // ../../node_modules/.bun/@ai-sdk+openai-compatible@2.0.64+27912429049419a2/node_modules/@ai-sdk/openai-compatible/dist/index.mjs
44069
+ // ../../node_modules/.bun/@ai-sdk+openai-compatible@2.0.69+27912429049419a2/node_modules/@ai-sdk/openai-compatible/dist/index.mjs
43938
44070
  var exports_dist3 = {};
43939
44071
  __export(exports_dist3, {
43940
44072
  createOpenAICompatible: () => createOpenAICompatible,
@@ -43985,7 +44117,7 @@ function convertOpenAICompatibleChatUsage(usage) {
43985
44117
  },
43986
44118
  outputTokens: {
43987
44119
  total: completionTokens,
43988
- text: completionTokens - reasoningTokens,
44120
+ text: Math.max(0, completionTokens - reasoningTokens),
43989
44121
  reasoning: reasoningTokens
43990
44122
  },
43991
44123
  raw: usage
@@ -45359,27 +45491,27 @@ var openaiCompatibleErrorDataSchema, defaultOpenAICompatibleErrorStructure, open
45359
45491
  }
45360
45492
  };
45361
45493
  }
45362
- }, openaiCompatibleImageResponseSchema, VERSION4 = "2.0.64";
45363
- var init_dist6 = __esm(() => {
45364
- init_dist();
45365
- init_dist3();
45494
+ }, openaiCompatibleImageResponseSchema, VERSION4 = "2.0.69";
45495
+ var init_dist7 = __esm(() => {
45496
+ init_dist2();
45497
+ init_dist4();
45366
45498
  init_v4();
45367
45499
  init_v4();
45368
- init_dist();
45369
- init_dist3();
45500
+ init_dist2();
45501
+ init_dist4();
45370
45502
  init_v4();
45371
- init_dist();
45372
- init_dist3();
45503
+ init_dist2();
45504
+ init_dist4();
45373
45505
  init_v4();
45374
- init_dist();
45506
+ init_dist2();
45375
45507
  init_v4();
45376
- init_dist();
45377
- init_dist3();
45508
+ init_dist2();
45509
+ init_dist4();
45378
45510
  init_v4();
45379
45511
  init_v4();
45380
- init_dist3();
45512
+ init_dist4();
45381
45513
  init_v4();
45382
- init_dist3();
45514
+ init_dist4();
45383
45515
  openaiCompatibleErrorDataSchema = exports_external2.object({
45384
45516
  error: exports_external2.object({
45385
45517
  message: exports_external2.string(),
@@ -45402,10 +45534,10 @@ var init_dist6 = __esm(() => {
45402
45534
  prompt_tokens: exports_external2.number().nullish(),
45403
45535
  completion_tokens: exports_external2.number().nullish(),
45404
45536
  total_tokens: exports_external2.number().nullish(),
45405
- prompt_tokens_details: exports_external2.object({
45537
+ prompt_tokens_details: exports_external2.looseObject({
45406
45538
  cached_tokens: exports_external2.number().nullish()
45407
45539
  }).nullish(),
45408
- completion_tokens_details: exports_external2.object({
45540
+ completion_tokens_details: exports_external2.looseObject({
45409
45541
  reasoning_tokens: exports_external2.number().nullish(),
45410
45542
  accepted_prediction_tokens: exports_external2.number().nullish(),
45411
45543
  rejected_prediction_tokens: exports_external2.number().nullish()
@@ -45472,7 +45604,7 @@ var init_dist6 = __esm(() => {
45472
45604
  suffix: exports_external2.string().optional(),
45473
45605
  user: exports_external2.string().optional()
45474
45606
  });
45475
- usageSchema = exports_external2.object({
45607
+ usageSchema = exports_external2.looseObject({
45476
45608
  prompt_tokens: exports_external2.number(),
45477
45609
  completion_tokens: exports_external2.number(),
45478
45610
  total_tokens: exports_external2.number()
@@ -45601,19 +45733,19 @@ var require_token_io = __commonJS((exports, module) => {
45601
45733
  getUserDataDir: () => getUserDataDir
45602
45734
  });
45603
45735
  module.exports = __toCommonJS2(token_io_exports);
45604
- var import_path2 = __toESM2(__require("path"));
45736
+ var import_path3 = __toESM2(__require("path"));
45605
45737
  var import_fs2 = __toESM2(__require("fs"));
45606
- var import_os3 = __toESM2(__require("os"));
45738
+ var import_os4 = __toESM2(__require("os"));
45607
45739
  var import_token_error = require_token_error();
45608
45740
  function findRootDir() {
45609
45741
  try {
45610
45742
  let dir = process.cwd();
45611
- while (dir !== import_path2.default.dirname(dir)) {
45612
- const pkgPath = import_path2.default.join(dir, ".vercel");
45743
+ while (dir !== import_path3.default.dirname(dir)) {
45744
+ const pkgPath = import_path3.default.join(dir, ".vercel");
45613
45745
  if (import_fs2.default.existsSync(pkgPath)) {
45614
45746
  return dir;
45615
45747
  }
45616
- dir = import_path2.default.dirname(dir);
45748
+ dir = import_path3.default.dirname(dir);
45617
45749
  }
45618
45750
  } catch (e) {
45619
45751
  throw new import_token_error.VercelOidcTokenError("Token refresh only supported in node server environments");
@@ -45624,11 +45756,11 @@ var require_token_io = __commonJS((exports, module) => {
45624
45756
  if (process.env.XDG_DATA_HOME) {
45625
45757
  return process.env.XDG_DATA_HOME;
45626
45758
  }
45627
- switch (import_os3.default.platform()) {
45759
+ switch (import_os4.default.platform()) {
45628
45760
  case "darwin":
45629
- return import_path2.default.join(import_os3.default.homedir(), "Library/Application Support");
45761
+ return import_path3.default.join(import_os4.default.homedir(), "Library/Application Support");
45630
45762
  case "linux":
45631
- return import_path2.default.join(import_os3.default.homedir(), ".local/share");
45763
+ return import_path3.default.join(import_os4.default.homedir(), ".local/share");
45632
45764
  case "win32":
45633
45765
  if (process.env.LOCALAPPDATA) {
45634
45766
  return process.env.LOCALAPPDATA;
@@ -45673,11 +45805,11 @@ var require_auth_config = __commonJS((exports, module) => {
45673
45805
  var path = __toESM2(__require("path"));
45674
45806
  var import_token_util = require_token_util();
45675
45807
  function getAuthConfigPath() {
45676
- const dataDir = (0, import_token_util.getVercelDataDir)();
45677
- if (!dataDir) {
45808
+ const dataDir2 = (0, import_token_util.getVercelDataDir)();
45809
+ if (!dataDir2) {
45678
45810
  throw new Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);
45679
45811
  }
45680
- return path.join(dataDir, "auth.json");
45812
+ return path.join(dataDir2, "auth.json");
45681
45813
  }
45682
45814
  function readAuthConfig() {
45683
45815
  try {
@@ -45738,10 +45870,10 @@ var require_oauth = __commonJS((exports, module) => {
45738
45870
  refreshTokenRequest: () => refreshTokenRequest
45739
45871
  });
45740
45872
  module.exports = __toCommonJS2(oauth_exports);
45741
- var import_os3 = __require("os");
45873
+ var import_os4 = __require("os");
45742
45874
  var VERCEL_ISSUER = "https://vercel.com";
45743
45875
  var VERCEL_CLI_CLIENT_ID = "cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp";
45744
- var userAgent = `@vercel/oidc node-${process.version} ${(0, import_os3.platform)()} (${(0, import_os3.arch)()}) ${(0, import_os3.hostname)()}`;
45876
+ var userAgent = `@vercel/oidc node-${process.version} ${(0, import_os4.platform)()} (${(0, import_os4.arch)()}) ${(0, import_os4.hostname)()}`;
45745
45877
  var _tokenEndpoint = null;
45746
45878
  async function getTokenEndpoint() {
45747
45879
  if (_tokenEndpoint) {
@@ -45884,11 +46016,11 @@ var require_token_util = __commonJS((exports, module) => {
45884
46016
  var import_auth_errors = require_auth_errors();
45885
46017
  function getVercelDataDir() {
45886
46018
  const vercelFolder = "com.vercel.cli";
45887
- const dataDir = (0, import_token_io.getUserDataDir)();
45888
- if (!dataDir) {
46019
+ const dataDir2 = (0, import_token_io.getUserDataDir)();
46020
+ if (!dataDir2) {
45889
46021
  return null;
45890
46022
  }
45891
- return path.join(dataDir, vercelFolder);
46023
+ return path.join(dataDir2, vercelFolder);
45892
46024
  }
45893
46025
  async function getVercelToken2(options) {
45894
46026
  const authConfig = (0, import_auth_config.readAuthConfig)();
@@ -46163,7 +46295,7 @@ var require_dist = __commonJS((exports, module) => {
46163
46295
  var import_token_util = require_token_util();
46164
46296
  });
46165
46297
 
46166
- // ../../node_modules/.bun/@ai-sdk+gateway@3.0.166+27912429049419a2/node_modules/@ai-sdk/gateway/dist/index.mjs
46298
+ // ../../node_modules/.bun/@ai-sdk+gateway@3.0.175+27912429049419a2/node_modules/@ai-sdk/gateway/dist/index.mjs
46167
46299
  async function createGatewayErrorFromResponse({
46168
46300
  response,
46169
46301
  statusCode,
@@ -46570,11 +46702,14 @@ var import_oidc, import_oidc2, marker17 = "vercel.ai.gateway.error", symbol18, _
46570
46702
  try {
46571
46703
  const { value } = await getFromApi({
46572
46704
  url: `${this.config.baseURL}/config`,
46573
- headers: await resolve20(this.config.headers()),
46705
+ headers: await resolve21(this.config.headers()),
46574
46706
  successfulResponseHandler: createJsonResponseHandler(gatewayAvailableModelsResponseSchema),
46575
46707
  failedResponseHandler: createJsonErrorResponseHandler({
46576
46708
  errorSchema: exports_external2.any(),
46577
- errorToMessage: (data) => data
46709
+ errorToMessage: (data) => {
46710
+ var _a112;
46711
+ return (_a112 = getErrorMessage2(data)) != null ? _a112 : "unknown error";
46712
+ }
46578
46713
  }),
46579
46714
  fetch: this.config.fetch
46580
46715
  });
@@ -46588,11 +46723,14 @@ var import_oidc, import_oidc2, marker17 = "vercel.ai.gateway.error", symbol18, _
46588
46723
  const baseUrl = new URL(this.config.baseURL);
46589
46724
  const { value } = await getFromApi({
46590
46725
  url: `${baseUrl.origin}/v1/credits`,
46591
- headers: await resolve20(this.config.headers()),
46726
+ headers: await resolve21(this.config.headers()),
46592
46727
  successfulResponseHandler: createJsonResponseHandler(gatewayCreditsResponseSchema),
46593
46728
  failedResponseHandler: createJsonErrorResponseHandler({
46594
46729
  errorSchema: exports_external2.any(),
46595
- errorToMessage: (data) => data
46730
+ errorToMessage: (data) => {
46731
+ var _a112;
46732
+ return (_a112 = getErrorMessage2(data)) != null ? _a112 : "unknown error";
46733
+ }
46596
46734
  }),
46597
46735
  fetch: this.config.fetch
46598
46736
  });
@@ -46634,11 +46772,14 @@ var import_oidc, import_oidc2, marker17 = "vercel.ai.gateway.error", symbol18, _
46634
46772
  }
46635
46773
  const { value } = await getFromApi({
46636
46774
  url: `${baseUrl.origin}/v1/report?${searchParams.toString()}`,
46637
- headers: await resolve20(this.config.headers()),
46775
+ headers: await resolve21(this.config.headers()),
46638
46776
  successfulResponseHandler: createJsonResponseHandler(gatewaySpendReportResponseSchema),
46639
46777
  failedResponseHandler: createJsonErrorResponseHandler({
46640
46778
  errorSchema: exports_external2.any(),
46641
- errorToMessage: (data) => data
46779
+ errorToMessage: (data) => {
46780
+ var _a112;
46781
+ return (_a112 = getErrorMessage2(data)) != null ? _a112 : "unknown error";
46782
+ }
46642
46783
  }),
46643
46784
  fetch: this.config.fetch
46644
46785
  });
@@ -46656,11 +46797,14 @@ var import_oidc, import_oidc2, marker17 = "vercel.ai.gateway.error", symbol18, _
46656
46797
  const baseUrl = new URL(this.config.baseURL);
46657
46798
  const { value } = await getFromApi({
46658
46799
  url: `${baseUrl.origin}/v1/generation?id=${encodeURIComponent(params.id)}`,
46659
- headers: await resolve20(this.config.headers()),
46800
+ headers: await resolve21(this.config.headers()),
46660
46801
  successfulResponseHandler: createJsonResponseHandler(gatewayGenerationInfoResponseSchema),
46661
46802
  failedResponseHandler: createJsonErrorResponseHandler({
46662
46803
  errorSchema: exports_external2.any(),
46663
- errorToMessage: (data) => data
46804
+ errorToMessage: (data) => {
46805
+ var _a112;
46806
+ return (_a112 = getErrorMessage2(data)) != null ? _a112 : "unknown error";
46807
+ }
46664
46808
  }),
46665
46809
  fetch: this.config.fetch
46666
46810
  });
@@ -46689,7 +46833,7 @@ var import_oidc, import_oidc2, marker17 = "vercel.ai.gateway.error", symbol18, _
46689
46833
  async doGenerate(options) {
46690
46834
  const { args, warnings } = await this.getArgs(options);
46691
46835
  const { abortSignal } = options;
46692
- const resolvedHeaders = await resolve20(this.config.headers());
46836
+ const resolvedHeaders = await resolve21(this.config.headers());
46693
46837
  try {
46694
46838
  const {
46695
46839
  responseHeaders,
@@ -46697,12 +46841,15 @@ var import_oidc, import_oidc2, marker17 = "vercel.ai.gateway.error", symbol18, _
46697
46841
  rawValue: rawResponse
46698
46842
  } = await postJsonToApi({
46699
46843
  url: this.getUrl(),
46700
- headers: combineHeaders(resolvedHeaders, options.headers, this.getModelConfigHeaders(this.modelId, false), await resolve20(this.config.o11yHeaders)),
46844
+ headers: combineHeaders(resolvedHeaders, options.headers, this.getModelConfigHeaders(this.modelId, false), await resolve21(this.config.o11yHeaders)),
46701
46845
  body: args,
46702
46846
  successfulResponseHandler: createJsonResponseHandler(exports_external2.any()),
46703
46847
  failedResponseHandler: createJsonErrorResponseHandler({
46704
46848
  errorSchema: exports_external2.any(),
46705
- errorToMessage: (data) => data
46849
+ errorToMessage: (data) => {
46850
+ var _a112;
46851
+ return (_a112 = getErrorMessage2(data)) != null ? _a112 : "unknown error";
46852
+ }
46706
46853
  }),
46707
46854
  ...abortSignal && { abortSignal },
46708
46855
  fetch: this.config.fetch
@@ -46720,16 +46867,19 @@ var import_oidc, import_oidc2, marker17 = "vercel.ai.gateway.error", symbol18, _
46720
46867
  async doStream(options) {
46721
46868
  const { args, warnings } = await this.getArgs(options);
46722
46869
  const { abortSignal } = options;
46723
- const resolvedHeaders = await resolve20(this.config.headers());
46870
+ const resolvedHeaders = await resolve21(this.config.headers());
46724
46871
  try {
46725
46872
  const { value: response, responseHeaders } = await postJsonToApi({
46726
46873
  url: this.getUrl(),
46727
- headers: combineHeaders(resolvedHeaders, options.headers, this.getModelConfigHeaders(this.modelId, true), await resolve20(this.config.o11yHeaders)),
46874
+ headers: combineHeaders(resolvedHeaders, options.headers, this.getModelConfigHeaders(this.modelId, true), await resolve21(this.config.o11yHeaders)),
46728
46875
  body: args,
46729
46876
  successfulResponseHandler: createEventSourceResponseHandler(exports_external2.any()),
46730
46877
  failedResponseHandler: createJsonErrorResponseHandler({
46731
46878
  errorSchema: exports_external2.any(),
46732
- errorToMessage: (data) => data
46879
+ errorToMessage: (data) => {
46880
+ var _a112;
46881
+ return (_a112 = getErrorMessage2(data)) != null ? _a112 : "unknown error";
46882
+ }
46733
46883
  }),
46734
46884
  ...abortSignal && { abortSignal },
46735
46885
  fetch: this.config.fetch
@@ -46809,7 +46959,7 @@ var import_oidc, import_oidc2, marker17 = "vercel.ai.gateway.error", symbol18, _
46809
46959
  providerOptions
46810
46960
  }) {
46811
46961
  var _a112, _b112;
46812
- const resolvedHeaders = await resolve20(this.config.headers());
46962
+ const resolvedHeaders = await resolve21(this.config.headers());
46813
46963
  try {
46814
46964
  const {
46815
46965
  responseHeaders,
@@ -46817,7 +46967,7 @@ var import_oidc, import_oidc2, marker17 = "vercel.ai.gateway.error", symbol18, _
46817
46967
  rawValue
46818
46968
  } = await postJsonToApi({
46819
46969
  url: this.getUrl(),
46820
- headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve20(this.config.o11yHeaders)),
46970
+ headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve21(this.config.o11yHeaders)),
46821
46971
  body: {
46822
46972
  values,
46823
46973
  ...providerOptions ? { providerOptions } : {}
@@ -46825,7 +46975,10 @@ var import_oidc, import_oidc2, marker17 = "vercel.ai.gateway.error", symbol18, _
46825
46975
  successfulResponseHandler: createJsonResponseHandler(gatewayEmbeddingResponseSchema),
46826
46976
  failedResponseHandler: createJsonErrorResponseHandler({
46827
46977
  errorSchema: exports_external2.any(),
46828
- errorToMessage: (data) => data
46978
+ errorToMessage: (data) => {
46979
+ var _a122;
46980
+ return (_a122 = getErrorMessage2(data)) != null ? _a122 : "unknown error";
46981
+ }
46829
46982
  }),
46830
46983
  ...abortSignal && { abortSignal },
46831
46984
  fetch: this.config.fetch
@@ -46873,7 +47026,7 @@ var import_oidc, import_oidc2, marker17 = "vercel.ai.gateway.error", symbol18, _
46873
47026
  abortSignal
46874
47027
  }) {
46875
47028
  var _a112, _b112, _c;
46876
- const resolvedHeaders = await resolve20(this.config.headers());
47029
+ const resolvedHeaders = await resolve21(this.config.headers());
46877
47030
  try {
46878
47031
  const {
46879
47032
  responseHeaders,
@@ -46881,7 +47034,7 @@ var import_oidc, import_oidc2, marker17 = "vercel.ai.gateway.error", symbol18, _
46881
47034
  rawValue
46882
47035
  } = await postJsonToApi({
46883
47036
  url: this.getUrl(),
46884
- headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve20(this.config.o11yHeaders)),
47037
+ headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve21(this.config.o11yHeaders)),
46885
47038
  body: {
46886
47039
  prompt,
46887
47040
  n,
@@ -46897,7 +47050,10 @@ var import_oidc, import_oidc2, marker17 = "vercel.ai.gateway.error", symbol18, _
46897
47050
  successfulResponseHandler: createJsonResponseHandler(gatewayImageResponseSchema),
46898
47051
  failedResponseHandler: createJsonErrorResponseHandler({
46899
47052
  errorSchema: exports_external2.any(),
46900
- errorToMessage: (data) => data
47053
+ errorToMessage: (data) => {
47054
+ var _a122;
47055
+ return (_a122 = getErrorMessage2(data)) != null ? _a122 : "unknown error";
47056
+ }
46901
47057
  }),
46902
47058
  ...abortSignal && { abortSignal },
46903
47059
  fetch: this.config.fetch
@@ -46958,11 +47114,11 @@ var import_oidc, import_oidc2, marker17 = "vercel.ai.gateway.error", symbol18, _
46958
47114
  headers,
46959
47115
  abortSignal
46960
47116
  }) {
46961
- const resolvedHeaders = await resolve20(this.config.headers());
47117
+ const resolvedHeaders = await resolve21(this.config.headers());
46962
47118
  try {
46963
47119
  const { responseHeaders, value: responseBody } = await postJsonToApi({
46964
47120
  url: this.getUrl(),
46965
- headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve20(this.config.o11yHeaders), { accept: "text/event-stream" }),
47121
+ headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve21(this.config.o11yHeaders), { accept: "text/event-stream" }),
46966
47122
  body: {
46967
47123
  prompt,
46968
47124
  n,
@@ -47050,7 +47206,10 @@ var import_oidc, import_oidc2, marker17 = "vercel.ai.gateway.error", symbol18, _
47050
47206
  },
47051
47207
  failedResponseHandler: createJsonErrorResponseHandler({
47052
47208
  errorSchema: exports_external2.any(),
47053
- errorToMessage: (data) => data
47209
+ errorToMessage: (data) => {
47210
+ var _a112;
47211
+ return (_a112 = getErrorMessage2(data)) != null ? _a112 : "unknown error";
47212
+ }
47054
47213
  }),
47055
47214
  ...abortSignal && { abortSignal },
47056
47215
  fetch: this.config.fetch
@@ -47096,7 +47255,7 @@ var import_oidc, import_oidc2, marker17 = "vercel.ai.gateway.error", symbol18, _
47096
47255
  providerOptions
47097
47256
  }) {
47098
47257
  var _a112;
47099
- const resolvedHeaders = await resolve20(this.config.headers());
47258
+ const resolvedHeaders = await resolve21(this.config.headers());
47100
47259
  try {
47101
47260
  const {
47102
47261
  responseHeaders,
@@ -47104,7 +47263,7 @@ var import_oidc, import_oidc2, marker17 = "vercel.ai.gateway.error", symbol18, _
47104
47263
  rawValue
47105
47264
  } = await postJsonToApi({
47106
47265
  url: this.getUrl(),
47107
- headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve20(this.config.o11yHeaders)),
47266
+ headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve21(this.config.o11yHeaders)),
47108
47267
  body: {
47109
47268
  documents,
47110
47269
  query,
@@ -47114,7 +47273,10 @@ var import_oidc, import_oidc2, marker17 = "vercel.ai.gateway.error", symbol18, _
47114
47273
  successfulResponseHandler: createJsonResponseHandler(gatewayRerankingResponseSchema),
47115
47274
  failedResponseHandler: createJsonErrorResponseHandler({
47116
47275
  errorSchema: exports_external2.any(),
47117
- errorToMessage: (data) => data
47276
+ errorToMessage: (data) => {
47277
+ var _a122;
47278
+ return (_a122 = getErrorMessage2(data)) != null ? _a122 : "unknown error";
47279
+ }
47118
47280
  }),
47119
47281
  ...abortSignal && { abortSignal },
47120
47282
  fetch: this.config.fetch
@@ -47158,7 +47320,7 @@ var import_oidc, import_oidc2, marker17 = "vercel.ai.gateway.error", symbol18, _
47158
47320
  headers,
47159
47321
  abortSignal
47160
47322
  }) {
47161
- const resolvedHeaders = await resolve20(this.config.headers());
47323
+ const resolvedHeaders = await resolve21(this.config.headers());
47162
47324
  try {
47163
47325
  const {
47164
47326
  responseHeaders,
@@ -47166,7 +47328,7 @@ var import_oidc, import_oidc2, marker17 = "vercel.ai.gateway.error", symbol18, _
47166
47328
  rawValue
47167
47329
  } = await postJsonToApi({
47168
47330
  url: this.getUrl(),
47169
- headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve20(this.config.o11yHeaders)),
47331
+ headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve21(this.config.o11yHeaders)),
47170
47332
  body: {
47171
47333
  text,
47172
47334
  ...voice && { voice },
@@ -47179,7 +47341,10 @@ var import_oidc, import_oidc2, marker17 = "vercel.ai.gateway.error", symbol18, _
47179
47341
  successfulResponseHandler: createJsonResponseHandler(gatewaySpeechResponseSchema),
47180
47342
  failedResponseHandler: createJsonErrorResponseHandler({
47181
47343
  errorSchema: exports_external2.any(),
47182
- errorToMessage: (data) => data
47344
+ errorToMessage: (data) => {
47345
+ var _a112;
47346
+ return (_a112 = getErrorMessage2(data)) != null ? _a112 : "unknown error";
47347
+ }
47183
47348
  }),
47184
47349
  ...abortSignal && { abortSignal },
47185
47350
  fetch: this.config.fetch
@@ -47225,7 +47390,7 @@ var import_oidc, import_oidc2, marker17 = "vercel.ai.gateway.error", symbol18, _
47225
47390
  abortSignal
47226
47391
  }) {
47227
47392
  var _a112, _b112, _c;
47228
- const resolvedHeaders = await resolve20(this.config.headers());
47393
+ const resolvedHeaders = await resolve21(this.config.headers());
47229
47394
  try {
47230
47395
  const {
47231
47396
  responseHeaders,
@@ -47233,7 +47398,7 @@ var import_oidc, import_oidc2, marker17 = "vercel.ai.gateway.error", symbol18, _
47233
47398
  rawValue
47234
47399
  } = await postJsonToApi({
47235
47400
  url: this.getUrl(),
47236
- headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve20(this.config.o11yHeaders)),
47401
+ headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve21(this.config.o11yHeaders)),
47237
47402
  body: {
47238
47403
  audio: audio instanceof Uint8Array ? convertUint8ArrayToBase64(audio) : audio,
47239
47404
  mediaType,
@@ -47242,7 +47407,10 @@ var import_oidc, import_oidc2, marker17 = "vercel.ai.gateway.error", symbol18, _
47242
47407
  successfulResponseHandler: createJsonResponseHandler(gatewayTranscriptionResponseSchema),
47243
47408
  failedResponseHandler: createJsonErrorResponseHandler({
47244
47409
  errorSchema: exports_external2.any(),
47245
- errorToMessage: (data) => data
47410
+ errorToMessage: (data) => {
47411
+ var _a122;
47412
+ return (_a122 = getErrorMessage2(data)) != null ? _a122 : "unknown error";
47413
+ }
47246
47414
  }),
47247
47415
  ...abortSignal && { abortSignal },
47248
47416
  fetch: this.config.fetch
@@ -47274,45 +47442,45 @@ var import_oidc, import_oidc2, marker17 = "vercel.ai.gateway.error", symbol18, _
47274
47442
  "ai-model-id": this.modelId
47275
47443
  };
47276
47444
  }
47277
- }, providerMetadataEntrySchema4, gatewayTranscriptionWarningSchema, gatewayTranscriptionResponseSchema, exaSearchInputSchema, exaSearchOutputSchema, exaSearchToolFactory, exaSearch = (config2 = {}) => exaSearchToolFactory(config2), parallelSearchInputSchema, parallelSearchOutputSchema, parallelSearchToolFactory, parallelSearch = (config2 = {}) => parallelSearchToolFactory(config2), perplexitySearchInputSchema, perplexitySearchOutputSchema, perplexitySearchToolFactory, perplexitySearch = (config2 = {}) => perplexitySearchToolFactory(config2), gatewayTools, VERSION5 = "3.0.166", AI_GATEWAY_PROTOCOL_VERSION = "0.0.1", gateway;
47278
- var init_dist7 = __esm(() => {
47279
- init_dist3();
47280
- init_dist();
47445
+ }, providerMetadataEntrySchema4, gatewayTranscriptionWarningSchema, gatewayTranscriptionResponseSchema, exaSearchInputSchema, exaSearchOutputSchema, exaSearchToolFactory, exaSearch = (config2 = {}) => exaSearchToolFactory(config2), parallelSearchInputSchema, parallelSearchOutputSchema, parallelSearchToolFactory, parallelSearch = (config2 = {}) => parallelSearchToolFactory(config2), perplexitySearchInputSchema, perplexitySearchOutputSchema, perplexitySearchToolFactory, perplexitySearch = (config2 = {}) => perplexitySearchToolFactory(config2), gatewayTools, VERSION5 = "3.0.175", AI_GATEWAY_PROTOCOL_VERSION = "0.0.1", gateway;
47446
+ var init_dist8 = __esm(() => {
47447
+ init_dist4();
47448
+ init_dist2();
47281
47449
  init_v4();
47282
47450
  init_v4();
47283
- init_dist3();
47451
+ init_dist4();
47284
47452
  init_v4();
47285
- init_dist3();
47286
- init_dist3();
47287
- init_dist3();
47453
+ init_dist4();
47454
+ init_dist4();
47455
+ init_dist4();
47288
47456
  init_v4();
47289
- init_dist3();
47290
- init_dist3();
47457
+ init_dist4();
47458
+ init_dist4();
47291
47459
  init_v4();
47292
- init_dist3();
47460
+ init_dist4();
47293
47461
  init_v4();
47294
- init_dist3();
47462
+ init_dist4();
47295
47463
  init_v4();
47296
- init_dist3();
47464
+ init_dist4();
47297
47465
  init_v4();
47298
- init_dist3();
47466
+ init_dist4();
47299
47467
  init_v4();
47300
- init_dist3();
47468
+ init_dist4();
47301
47469
  init_v4();
47302
- init_dist();
47303
- init_dist3();
47470
+ init_dist2();
47471
+ init_dist4();
47304
47472
  init_v4();
47305
- init_dist3();
47473
+ init_dist4();
47306
47474
  init_v4();
47307
- init_dist3();
47475
+ init_dist4();
47308
47476
  init_v4();
47309
- init_dist3();
47477
+ init_dist4();
47310
47478
  init_v4();
47311
- init_dist3();
47479
+ init_dist4();
47312
47480
  init_zod();
47313
- init_dist3();
47481
+ init_dist4();
47314
47482
  init_zod();
47315
- init_dist3();
47483
+ init_dist4();
47316
47484
  init_zod();
47317
47485
  import_oidc = __toESM(require_dist(), 1);
47318
47486
  import_oidc2 = __toESM(require_dist(), 1);
@@ -49215,7 +49383,7 @@ var require_tracestate_impl = __commonJS((exports) => {
49215
49383
  const value = listMember.slice(i + 1, part.length);
49216
49384
  if ((0, tracestate_validators_1.validateKey)(key) && (0, tracestate_validators_1.validateValue)(value)) {
49217
49385
  agg.set(key, value);
49218
- } else {}
49386
+ }
49219
49387
  }
49220
49388
  return agg;
49221
49389
  }, new Map);
@@ -49590,7 +49758,7 @@ var require_src = __commonJS((exports) => {
49590
49758
  };
49591
49759
  });
49592
49760
 
49593
- // ../../node_modules/.bun/ai@6.0.246+27912429049419a2/node_modules/ai/dist/index.mjs
49761
+ // ../../node_modules/.bun/ai@6.0.257+27912429049419a2/node_modules/ai/dist/index.mjs
49594
49762
  var exports_dist4 = {};
49595
49763
  __export(exports_dist4, {
49596
49764
  zodSchema: () => zodSchema,
@@ -50875,7 +51043,8 @@ async function recordSpan({
50875
51043
  tracer,
50876
51044
  attributes,
50877
51045
  fn,
50878
- endWhenDone = true
51046
+ endWhenDone = true,
51047
+ endOnError = endWhenDone
50879
51048
  }) {
50880
51049
  return tracer.startActiveSpan(name222, { attributes: await attributes }, async (span) => {
50881
51050
  const ctx = import_api3.context.active();
@@ -50889,7 +51058,9 @@ async function recordSpan({
50889
51058
  try {
50890
51059
  recordErrorOnSpan(span, error40);
50891
51060
  } finally {
50892
- span.end();
51061
+ if (endOnError) {
51062
+ span.end();
51063
+ }
50893
51064
  }
50894
51065
  throw error40;
50895
51066
  }
@@ -53359,6 +53530,7 @@ function processUIMessageStream({
53359
53530
  case "reasoning-start": {
53360
53531
  const reasoningPart = {
53361
53532
  type: "reasoning",
53533
+ id: chunk.id,
53362
53534
  text: "",
53363
53535
  providerMetadata: chunk.providerMetadata,
53364
53536
  state: "streaming"
@@ -53655,7 +53827,7 @@ function processUIMessageStream({
53655
53827
  }
53656
53828
  await updateMessageMetadata(chunk.messageMetadata);
53657
53829
  if (chunk.messageId != null || chunk.messageMetadata != null) {
53658
- write();
53830
+ write({ updateStatus: false });
53659
53831
  }
53660
53832
  break;
53661
53833
  }
@@ -53878,9 +54050,18 @@ function createAsyncIterableStream(source) {
53878
54050
  }
53879
54051
  async function consumeStream({
53880
54052
  stream,
53881
- onError
54053
+ onError,
54054
+ abortSignal
53882
54055
  }) {
53883
54056
  const reader = stream.getReader();
54057
+ const cancelOnAbort = () => {
54058
+ reader.cancel().catch(() => {});
54059
+ };
54060
+ if (abortSignal == null ? undefined : abortSignal.aborted) {
54061
+ cancelOnAbort();
54062
+ } else {
54063
+ abortSignal == null || abortSignal.addEventListener("abort", cancelOnAbort, { once: true });
54064
+ }
53884
54065
  try {
53885
54066
  while (true) {
53886
54067
  const { done } = await reader.read();
@@ -53890,6 +54071,7 @@ async function consumeStream({
53890
54071
  } catch (error40) {
53891
54072
  onError == null || onError(error40);
53892
54073
  } finally {
54074
+ abortSignal == null || abortSignal.removeEventListener("abort", cancelOnAbort);
53893
54075
  reader.releaseLock();
53894
54076
  }
53895
54077
  }
@@ -54490,6 +54672,27 @@ function createUIMessageStream({
54490
54672
  onError
54491
54673
  });
54492
54674
  }
54675
+ function createUIMessageSnapshot(message) {
54676
+ const textByPartIndex = /* @__PURE__ */ new Map;
54677
+ const messageWithoutText = {
54678
+ ...message,
54679
+ parts: message.parts.map((part, index) => {
54680
+ if (part.type === "text" || part.type === "reasoning") {
54681
+ textByPartIndex.set(index, part.text);
54682
+ return { ...part, text: "" };
54683
+ }
54684
+ return part;
54685
+ })
54686
+ };
54687
+ const snapshot2 = structuredClone(messageWithoutText);
54688
+ for (const [index, text2] of textByPartIndex) {
54689
+ const part = snapshot2.parts[index];
54690
+ if (part.type === "text" || part.type === "reasoning") {
54691
+ part.text = text2;
54692
+ }
54693
+ }
54694
+ return snapshot2;
54695
+ }
54493
54696
  function readUIMessageStream({
54494
54697
  message,
54495
54698
  stream,
@@ -54522,7 +54725,7 @@ function readUIMessageStream({
54522
54725
  return job({
54523
54726
  state,
54524
54727
  write: () => {
54525
- controller == null || controller.enqueue(structuredClone(state.message));
54728
+ controller == null || controller.enqueue(createUIMessageSnapshot(state.message));
54526
54729
  }
54527
54730
  });
54528
54731
  },
@@ -57405,7 +57608,7 @@ var import_api2, import_api3, __defProp2, __export2 = (target, all) => {
57405
57608
  }, imageMediaTypeSignatures, audioMediaTypeSignatures, videoMediaTypeSignatures, DEFAULT_SNIFF_BYTES = 18, MAX_SIGNATURE_BYTES = 12, MAX_ID3_TAG_BYTES, ID3_SCAN_BYTES, stripID3 = (bytes) => {
57406
57609
  const id3Size = (bytes[6] & 127) << 21 | (bytes[7] & 127) << 14 | (bytes[8] & 127) << 7 | bytes[9] & 127;
57407
57610
  return bytes.subarray(id3Size + 10);
57408
- }, VERSION6 = "6.0.246", download = async ({
57611
+ }, VERSION6 = "6.0.257", download = async ({
57409
57612
  url: url2,
57410
57613
  maxBytes,
57411
57614
  abortSignal
@@ -57500,7 +57703,7 @@ var import_api2, import_api3, __defProp2, __export2 = (target, all) => {
57500
57703
  const schema = asSchema(inputSchema);
57501
57704
  return {
57502
57705
  name: "object",
57503
- responseFormat: resolve20(schema.jsonSchema).then((jsonSchema2) => ({
57706
+ responseFormat: resolve21(schema.jsonSchema).then((jsonSchema2) => ({
57504
57707
  type: "json",
57505
57708
  schema: jsonSchema2,
57506
57709
  ...name222 != null && { name: name222 },
@@ -57561,7 +57764,7 @@ var import_api2, import_api3, __defProp2, __export2 = (target, all) => {
57561
57764
  const elementSchema = asSchema(inputElementSchema);
57562
57765
  return {
57563
57766
  name: "array",
57564
- responseFormat: resolve20(elementSchema.jsonSchema).then((jsonSchema2) => {
57767
+ responseFormat: resolve21(elementSchema.jsonSchema).then((jsonSchema2) => {
57565
57768
  const { $schema, ...itemSchema } = jsonSchema2;
57566
57769
  return {
57567
57770
  type: "json",
@@ -58604,6 +58807,7 @@ var import_api2, import_api3, __defProp2, __export2 = (target, all) => {
58604
58807
  }),
58605
58808
  tracer,
58606
58809
  endWhenDone: false,
58810
+ endOnError: true,
58607
58811
  fn: async (doStreamSpan2) => ({
58608
58812
  startTimestampMs: now22(),
58609
58813
  doStreamSpan: doStreamSpan2,
@@ -59523,10 +59727,11 @@ var import_api2, import_api3, __defProp2, __export2 = (target, all) => {
59523
59727
  onStepFinish,
59524
59728
  ...options
59525
59729
  }) {
59730
+ const preparedCall = await this.prepareCall(options);
59526
59731
  return generateText({
59527
- ...await this.prepareCall(options),
59732
+ ...preparedCall,
59528
59733
  abortSignal,
59529
- timeout,
59734
+ timeout: timeout != null ? timeout : preparedCall.timeout,
59530
59735
  onStepFinish: this.mergeOnStepFinishCallbacks(onStepFinish)
59531
59736
  });
59532
59737
  }
@@ -59537,10 +59742,11 @@ var import_api2, import_api3, __defProp2, __export2 = (target, all) => {
59537
59742
  onStepFinish,
59538
59743
  ...options
59539
59744
  }) {
59745
+ const preparedCall = await this.prepareCall(options);
59540
59746
  return streamText({
59541
- ...await this.prepareCall(options),
59747
+ ...preparedCall,
59542
59748
  abortSignal,
59543
- timeout,
59749
+ timeout: timeout != null ? timeout : preparedCall.timeout,
59544
59750
  experimental_transform,
59545
59751
  onStepFinish: this.mergeOnStepFinishCallbacks(onStepFinish)
59546
59752
  });
@@ -59897,6 +60103,7 @@ var import_api2, import_api3, __defProp2, __export2 = (target, all) => {
59897
60103
  }),
59898
60104
  tracer,
59899
60105
  endWhenDone: false,
60106
+ endOnError: true,
59900
60107
  fn: async (rootSpan) => {
59901
60108
  const standardizedPrompt = await standardizePrompt({
59902
60109
  system,
@@ -59966,6 +60173,7 @@ var import_api2, import_api3, __defProp2, __export2 = (target, all) => {
59966
60173
  }),
59967
60174
  tracer,
59968
60175
  endWhenDone: false,
60176
+ endOnError: true,
59969
60177
  fn: async (doStreamSpan2) => ({
59970
60178
  startTimestampMs: now22(),
59971
60179
  doStreamSpan: doStreamSpan2,
@@ -60552,9 +60760,9 @@ var import_api2, import_api3, __defProp2, __export2 = (target, all) => {
60552
60760
  ...options
60553
60761
  }) {
60554
60762
  var _a222, _b16, _c, _d, _e;
60555
- const resolvedBody = await resolve20(this.body);
60556
- const resolvedHeaders = await resolve20(this.headers);
60557
- const resolvedCredentials = await resolve20(this.credentials);
60763
+ const resolvedBody = await resolve21(this.body);
60764
+ const resolvedHeaders = await resolve21(this.headers);
60765
+ const resolvedCredentials = await resolve21(this.credentials);
60558
60766
  const baseHeaders = {
60559
60767
  ...normalizeHeaders(resolvedHeaders),
60560
60768
  ...normalizeHeaders(options.headers)
@@ -60602,9 +60810,9 @@ var import_api2, import_api3, __defProp2, __export2 = (target, all) => {
60602
60810
  }
60603
60811
  async reconnectToStream(options) {
60604
60812
  var _a222, _b16, _c, _d, _e;
60605
- const resolvedBody = await resolve20(this.body);
60606
- const resolvedHeaders = await resolve20(this.headers);
60607
- const resolvedCredentials = await resolve20(this.credentials);
60813
+ const resolvedBody = await resolve21(this.body);
60814
+ const resolvedHeaders = await resolve21(this.headers);
60815
+ const resolvedCredentials = await resolve21(this.credentials);
60608
60816
  const baseHeaders = {
60609
60817
  ...normalizeHeaders(resolvedHeaders),
60610
60818
  ...normalizeHeaders(options.headers)
@@ -60624,7 +60832,8 @@ var import_api2, import_api3, __defProp2, __export2 = (target, all) => {
60624
60832
  const response = await fetch2(api2, {
60625
60833
  method: "GET",
60626
60834
  headers,
60627
- credentials
60835
+ credentials,
60836
+ signal: options.abortSignal
60628
60837
  });
60629
60838
  if (response.status === 204) {
60630
60839
  return null;
@@ -60652,6 +60861,7 @@ var import_api2, import_api3, __defProp2, __export2 = (target, all) => {
60652
60861
  sendAutomaticallyWhen
60653
60862
  }) {
60654
60863
  this.activeResponse = undefined;
60864
+ this.activeResumeRequest = undefined;
60655
60865
  this.jobExecutor = new SerialJobExecutor;
60656
60866
  this.sendMessage = async (message, options) => {
60657
60867
  var _a222, _b16, _c, _d;
@@ -60793,12 +61003,9 @@ var import_api2, import_api3, __defProp2, __export2 = (target, all) => {
60793
61003
  });
60794
61004
  this.addToolResult = this.addToolOutput;
60795
61005
  this.stop = async () => {
60796
- var _a222;
60797
- if (this.status !== "streaming" && this.status !== "submitted")
60798
- return;
60799
- if ((_a222 = this.activeResponse) == null ? undefined : _a222.abortController) {
60800
- this.activeResponse.abortController.abort();
60801
- }
61006
+ var _a222, _b16;
61007
+ (_a222 = this.activeResumeRequest) == null || _a222.abortController.abort();
61008
+ (_b16 = this.activeResponse) == null || _b16.abortController.abort();
60802
61009
  };
60803
61010
  this.id = id;
60804
61011
  this.transport = transport;
@@ -60854,25 +61061,59 @@ var import_api2, import_api3, __defProp2, __export2 = (target, all) => {
60854
61061
  body,
60855
61062
  messageId
60856
61063
  }) {
60857
- var _a222, _b16;
61064
+ var _a222, _b16, _c;
61065
+ const abortController = new AbortController;
61066
+ const activeResumeRequest = trigger === "resume-stream" ? { abortController } : undefined;
61067
+ if (activeResumeRequest) {
61068
+ (_a222 = this.activeResumeRequest) == null || _a222.abortController.abort();
61069
+ this.activeResumeRequest = activeResumeRequest;
61070
+ }
61071
+ const isCurrentRequest = () => activeResumeRequest == null || this.activeResumeRequest === activeResumeRequest;
61072
+ const clearActiveResumeRequest = () => {
61073
+ if (this.activeResumeRequest === activeResumeRequest) {
61074
+ this.activeResumeRequest = undefined;
61075
+ }
61076
+ };
60858
61077
  let resumeStream;
60859
61078
  if (trigger === "resume-stream") {
60860
61079
  try {
60861
61080
  const reconnect = await this.transport.reconnectToStream({
60862
61081
  chatId: this.id,
61082
+ abortSignal: abortController.signal,
60863
61083
  metadata,
60864
61084
  headers,
60865
61085
  body
60866
61086
  });
61087
+ if (abortController.signal.aborted || !isCurrentRequest()) {
61088
+ await (reconnect == null ? undefined : reconnect.cancel().catch(() => {}));
61089
+ if (isCurrentRequest()) {
61090
+ this.setStatus({ status: "ready" });
61091
+ }
61092
+ clearActiveResumeRequest();
61093
+ return;
61094
+ }
60867
61095
  if (reconnect == null) {
61096
+ this.setStatus({ status: "ready" });
61097
+ clearActiveResumeRequest();
60868
61098
  return;
60869
61099
  }
60870
61100
  resumeStream = reconnect;
60871
61101
  } catch (err) {
61102
+ if (abortController.signal.aborted || err.name === "AbortError") {
61103
+ if (isCurrentRequest()) {
61104
+ this.setStatus({ status: "ready" });
61105
+ }
61106
+ clearActiveResumeRequest();
61107
+ return;
61108
+ }
61109
+ if (!isCurrentRequest()) {
61110
+ return;
61111
+ }
60872
61112
  if (this.onError && err instanceof Error) {
60873
61113
  this.onError(err);
60874
61114
  }
60875
61115
  this.setStatus({ status: "error", error: err });
61116
+ clearActiveResumeRequest();
60876
61117
  return;
60877
61118
  }
60878
61119
  }
@@ -60885,10 +61126,10 @@ var import_api2, import_api3, __defProp2, __export2 = (target, all) => {
60885
61126
  try {
60886
61127
  const response = {
60887
61128
  state: createStreamingUIMessageState({
60888
- lastMessage: trigger === "regenerate-message" ? undefined : this.state.snapshot(lastMessage),
61129
+ lastMessage: trigger === "resume-stream" || trigger === "regenerate-message" ? undefined : this.state.snapshot(lastMessage),
60889
61130
  messageId: this.generateId()
60890
61131
  }),
60891
- abortController: new AbortController
61132
+ abortController
60892
61133
  };
60893
61134
  activeResponse = response;
60894
61135
  response.abortController.signal.addEventListener("abort", () => {
@@ -60910,19 +61151,29 @@ var import_api2, import_api3, __defProp2, __export2 = (target, all) => {
60910
61151
  messageId
60911
61152
  });
60912
61153
  }
60913
- const runUpdateMessageJob = (job) => this.jobExecutor.run(() => job({
60914
- state: response.state,
60915
- write: () => {
60916
- var _a232;
60917
- this.setStatus({ status: "streaming" });
60918
- const replaceLastMessage = response.state.message.id === ((_a232 = this.lastMessage) == null ? undefined : _a232.id);
60919
- if (replaceLastMessage) {
60920
- this.state.replaceMessage(this.state.messages.length - 1, response.state.message);
60921
- } else {
60922
- this.state.pushMessage(response.state.message);
60923
- }
61154
+ const runUpdateMessageJob = (job) => this.jobExecutor.run(() => {
61155
+ if (response.abortController.signal.aborted) {
61156
+ return Promise.resolve();
60924
61157
  }
60925
- }));
61158
+ return job({
61159
+ state: response.state,
61160
+ write: ({ updateStatus = true } = {}) => {
61161
+ var _a232;
61162
+ if (response.abortController.signal.aborted) {
61163
+ return;
61164
+ }
61165
+ if (updateStatus) {
61166
+ this.setStatus({ status: "streaming" });
61167
+ }
61168
+ const replaceLastMessage = response.state.message.id === ((_a232 = this.lastMessage) == null ? undefined : _a232.id);
61169
+ if (replaceLastMessage) {
61170
+ this.state.replaceMessage(this.state.messages.length - 1, response.state.message);
61171
+ } else {
61172
+ this.state.pushMessage(response.state.message);
61173
+ }
61174
+ }
61175
+ });
61176
+ });
60926
61177
  await consumeStream({
60927
61178
  stream: processUIMessageStream({
60928
61179
  stream,
@@ -60935,15 +61186,29 @@ var import_api2, import_api3, __defProp2, __export2 = (target, all) => {
60935
61186
  throw error40;
60936
61187
  }
60937
61188
  }),
61189
+ abortSignal: response.abortController.signal,
60938
61190
  onError: (error40) => {
60939
61191
  throw error40;
60940
61192
  }
60941
61193
  });
60942
- this.setStatus({ status: "ready" });
61194
+ if (isAbort) {
61195
+ if (isCurrentRequest()) {
61196
+ this.setStatus({ status: "ready" });
61197
+ }
61198
+ return null;
61199
+ }
61200
+ if (isCurrentRequest()) {
61201
+ this.setStatus({ status: "ready" });
61202
+ }
60943
61203
  } catch (err) {
60944
61204
  if (isAbort || err.name === "AbortError") {
60945
61205
  isAbort = true;
60946
- this.setStatus({ status: "ready" });
61206
+ if (isCurrentRequest()) {
61207
+ this.setStatus({ status: "ready" });
61208
+ }
61209
+ return null;
61210
+ }
61211
+ if (!isCurrentRequest()) {
60947
61212
  return null;
60948
61213
  }
60949
61214
  isError = true;
@@ -60957,7 +61222,7 @@ var import_api2, import_api3, __defProp2, __export2 = (target, all) => {
60957
61222
  } finally {
60958
61223
  try {
60959
61224
  if (activeResponse) {
60960
- (_a222 = this.onFinish) == null || _a222.call(this, {
61225
+ (_b16 = this.onFinish) == null || _b16.call(this, {
60961
61226
  message: activeResponse.state.message,
60962
61227
  messages: this.state.messages,
60963
61228
  isAbort,
@@ -60966,17 +61231,17 @@ var import_api2, import_api3, __defProp2, __export2 = (target, all) => {
60966
61231
  finishReason: activeResponse.state.finishReason
60967
61232
  });
60968
61233
  }
60969
- } catch (err) {
60970
- console.error(err);
60971
- }
60972
- if (this.activeResponse === activeResponse) {
60973
- this.activeResponse = undefined;
61234
+ } finally {
61235
+ if (this.activeResponse === activeResponse) {
61236
+ this.activeResponse = undefined;
61237
+ }
61238
+ clearActiveResumeRequest();
60974
61239
  }
60975
61240
  }
60976
61241
  if (!isError && await this.shouldSendAutomatically()) {
60977
61242
  await this.makeRequest({
60978
61243
  trigger: "submit-message",
60979
- messageId: (_b16 = this.lastMessage) == null ? undefined : _b16.id,
61244
+ messageId: (_c = this.lastMessage) == null ? undefined : _c.id,
60980
61245
  metadata,
60981
61246
  headers,
60982
61247
  body
@@ -61015,96 +61280,96 @@ var import_api2, import_api3, __defProp2, __export2 = (target, all) => {
61015
61280
  return null;
61016
61281
  }
61017
61282
  }, TextStreamChatTransport;
61018
- var init_dist8 = __esm(() => {
61019
- init_dist7();
61020
- init_dist3();
61021
- init_dist3();
61022
- init_dist3();
61023
- init_dist();
61024
- init_dist();
61025
- init_dist();
61026
- init_dist();
61027
- init_dist();
61028
- init_dist();
61029
- init_dist();
61030
- init_dist();
61031
- init_dist();
61032
- init_dist();
61033
- init_dist();
61034
- init_dist();
61035
- init_dist();
61036
- init_dist();
61037
- init_dist();
61038
- init_dist();
61039
- init_dist();
61040
- init_dist();
61041
- init_dist();
61042
- init_dist();
61043
- init_dist();
61044
- init_dist3();
61045
- init_dist();
61046
- init_dist7();
61047
- init_dist3();
61048
- init_dist3();
61049
- init_dist3();
61050
- init_dist();
61051
- init_dist3();
61283
+ var init_dist9 = __esm(() => {
61284
+ init_dist8();
61285
+ init_dist4();
61286
+ init_dist4();
61287
+ init_dist4();
61288
+ init_dist2();
61289
+ init_dist2();
61290
+ init_dist2();
61291
+ init_dist2();
61292
+ init_dist2();
61293
+ init_dist2();
61294
+ init_dist2();
61295
+ init_dist2();
61296
+ init_dist2();
61297
+ init_dist2();
61298
+ init_dist2();
61299
+ init_dist2();
61300
+ init_dist2();
61301
+ init_dist2();
61302
+ init_dist2();
61303
+ init_dist2();
61304
+ init_dist2();
61305
+ init_dist2();
61306
+ init_dist2();
61307
+ init_dist2();
61308
+ init_dist2();
61309
+ init_dist4();
61310
+ init_dist2();
61311
+ init_dist8();
61312
+ init_dist4();
61313
+ init_dist4();
61314
+ init_dist4();
61315
+ init_dist2();
61316
+ init_dist4();
61052
61317
  init_v4();
61053
- init_dist();
61054
- init_dist3();
61055
- init_dist();
61056
- init_dist3();
61318
+ init_dist2();
61319
+ init_dist4();
61320
+ init_dist2();
61321
+ init_dist4();
61057
61322
  init_v4();
61058
61323
  init_v4();
61059
61324
  init_v4();
61060
61325
  init_v4();
61061
61326
  init_v4();
61062
- init_dist7();
61063
- init_dist();
61064
- init_dist();
61065
- init_dist7();
61066
- init_dist3();
61067
- init_dist3();
61068
- init_dist3();
61069
- init_dist3();
61070
- init_dist3();
61071
- init_dist();
61072
- init_dist3();
61073
- init_dist3();
61074
- init_dist3();
61075
- init_dist();
61076
- init_dist3();
61077
- init_dist3();
61327
+ init_dist8();
61328
+ init_dist2();
61329
+ init_dist2();
61330
+ init_dist8();
61331
+ init_dist4();
61332
+ init_dist4();
61333
+ init_dist4();
61334
+ init_dist4();
61335
+ init_dist4();
61336
+ init_dist2();
61337
+ init_dist4();
61338
+ init_dist4();
61339
+ init_dist4();
61340
+ init_dist2();
61341
+ init_dist4();
61342
+ init_dist4();
61078
61343
  init_v4();
61079
- init_dist3();
61080
- init_dist3();
61081
- init_dist3();
61082
- init_dist3();
61083
- init_dist();
61084
- init_dist3();
61344
+ init_dist4();
61345
+ init_dist4();
61346
+ init_dist4();
61347
+ init_dist4();
61348
+ init_dist2();
61349
+ init_dist4();
61085
61350
  init_v4();
61086
- init_dist3();
61087
- init_dist3();
61088
- init_dist3();
61089
- init_dist3();
61090
- init_dist();
61091
- init_dist3();
61092
- init_dist();
61093
- init_dist3();
61094
- init_dist3();
61095
- init_dist3();
61096
- init_dist3();
61097
- init_dist3();
61098
- init_dist();
61099
- init_dist3();
61100
- init_dist();
61101
- init_dist();
61102
- init_dist();
61103
- init_dist3();
61104
- init_dist3();
61105
- init_dist3();
61106
- init_dist3();
61107
- init_dist3();
61351
+ init_dist4();
61352
+ init_dist4();
61353
+ init_dist4();
61354
+ init_dist4();
61355
+ init_dist2();
61356
+ init_dist4();
61357
+ init_dist2();
61358
+ init_dist4();
61359
+ init_dist4();
61360
+ init_dist4();
61361
+ init_dist4();
61362
+ init_dist4();
61363
+ init_dist2();
61364
+ init_dist4();
61365
+ init_dist2();
61366
+ init_dist2();
61367
+ init_dist2();
61368
+ init_dist4();
61369
+ init_dist4();
61370
+ init_dist4();
61371
+ init_dist4();
61372
+ init_dist4();
61108
61373
  import_api2 = __toESM(require_src(), 1);
61109
61374
  import_api3 = __toESM(require_src(), 1);
61110
61375
  __defProp2 = Object.defineProperty;
@@ -62163,6 +62428,7 @@ var init_dist8 = __esm(() => {
62163
62428
  }),
62164
62429
  exports_external2.object({
62165
62430
  type: exports_external2.literal("reasoning"),
62431
+ id: exports_external2.string().optional(),
62166
62432
  text: exports_external2.string(),
62167
62433
  state: exports_external2.enum(["streaming", "done"]).optional(),
62168
62434
  providerMetadata: providerMetadataSchema.optional()
@@ -62571,7 +62837,7 @@ var {
62571
62837
  // src/cli/index.tsx
62572
62838
  init_database();
62573
62839
  import { readFileSync as readFileSync10 } from "fs";
62574
- import { dirname as dirname8, join as join14 } from "path";
62840
+ import { dirname as dirname8, join as join19 } from "path";
62575
62841
  import { fileURLToPath as fileURLToPath5 } from "url";
62576
62842
 
62577
62843
  // src/db/machines.ts
@@ -62683,9 +62949,9 @@ function resolveExitCode(err) {
62683
62949
 
62684
62950
  // ../../node_modules/.bun/@hasna+events@0.1.6/node_modules/@hasna/events/dist/commander.js
62685
62951
  import { chmod, mkdir, readFile, rename, writeFile } from "fs/promises";
62686
- import { existsSync as existsSync3 } from "fs";
62687
- import { homedir as homedir2 } from "os";
62688
- import { join as join4 } from "path";
62952
+ import { existsSync as existsSync4 } from "fs";
62953
+ import { homedir as homedir3 } from "os";
62954
+ import { join as join6 } from "path";
62689
62955
  import { createHmac, timingSafeEqual } from "crypto";
62690
62956
  import { randomUUID as randomUUID2 } from "crypto";
62691
62957
  import { spawn } from "child_process";
@@ -62734,7 +63000,7 @@ function channelMatchesEvent(channel, event) {
62734
63000
  var HASNA_EVENTS_DIR_ENV = "HASNA_EVENTS_DIR";
62735
63001
  var HASNA_EVENTS_HOME_ENV = "HASNA_EVENTS_HOME";
62736
63002
  function getEventsDataDir(override) {
62737
- return override || process.env[HASNA_EVENTS_DIR_ENV] || process.env[HASNA_EVENTS_HOME_ENV] || join4(homedir2(), ".hasna", "events");
63003
+ return override || process.env[HASNA_EVENTS_DIR_ENV] || process.env[HASNA_EVENTS_HOME_ENV] || join6(homedir3(), ".hasna", "events");
62738
63004
  }
62739
63005
 
62740
63006
  class JsonEventsStore {
@@ -62742,11 +63008,11 @@ class JsonEventsStore {
62742
63008
  channelsPath;
62743
63009
  eventsPath;
62744
63010
  deliveriesPath;
62745
- constructor(dataDir = getEventsDataDir()) {
62746
- this.dataDir = dataDir;
62747
- this.channelsPath = join4(dataDir, "channels.json");
62748
- this.eventsPath = join4(dataDir, "events.json");
62749
- this.deliveriesPath = join4(dataDir, "deliveries.json");
63011
+ constructor(dataDir2 = getEventsDataDir()) {
63012
+ this.dataDir = dataDir2;
63013
+ this.channelsPath = join6(dataDir2, "channels.json");
63014
+ this.eventsPath = join6(dataDir2, "events.json");
63015
+ this.deliveriesPath = join6(dataDir2, "deliveries.json");
62750
63016
  }
62751
63017
  async init() {
62752
63018
  await mkdir(this.dataDir, { recursive: true, mode: 448 });
@@ -62818,7 +63084,7 @@ class JsonEventsStore {
62818
63084
  };
62819
63085
  }
62820
63086
  async ensureArrayFile(path) {
62821
- if (!existsSync3(path)) {
63087
+ if (!existsSync4(path)) {
62822
63088
  await writeFile(path, `[]
62823
63089
  `, { encoding: "utf-8", mode: 384 });
62824
63090
  }
@@ -62935,7 +63201,7 @@ async function dispatchCommand(event, channel) {
62935
63201
  HASNA_EVENT_SCHEMA_VERSION: event.schemaVersion,
62936
63202
  HASNA_EVENT_JSON: eventJson
62937
63203
  };
62938
- return new Promise((resolve2) => {
63204
+ return new Promise((resolve3) => {
62939
63205
  const child = spawn(channel.command.command, channel.command.args ?? [], {
62940
63206
  cwd: channel.command.cwd,
62941
63207
  env,
@@ -62953,7 +63219,7 @@ async function dispatchCommand(event, channel) {
62953
63219
  });
62954
63220
  child.on("error", (error) => {
62955
63221
  clearTimeout(timeout);
62956
- resolve2({
63222
+ resolve3({
62957
63223
  attempt: 1,
62958
63224
  status: "failed",
62959
63225
  startedAt,
@@ -62966,7 +63232,7 @@ async function dispatchCommand(event, channel) {
62966
63232
  child.on("close", (code, signal) => {
62967
63233
  clearTimeout(timeout);
62968
63234
  const success = code === 0;
62969
- resolve2({
63235
+ resolve3({
62970
63236
  attempt: 1,
62971
63237
  status: success ? "success" : "failed",
62972
63238
  startedAt,
@@ -63373,7 +63639,7 @@ init_database();
63373
63639
  init_api_mode();
63374
63640
  init_memories();
63375
63641
  import chalk2 from "chalk";
63376
- import { resolve as resolve3 } from "path";
63642
+ import { resolve as resolve4 } from "path";
63377
63643
 
63378
63644
  // src/db/memory-project-link.ts
63379
63645
  init_storage();
@@ -64596,7 +64862,7 @@ function registerCrudCommands(program2) {
64596
64862
  session_id: globalOpts.session
64597
64863
  };
64598
64864
  if (globalOpts.project) {
64599
- const projectPath = resolve3(globalOpts.project);
64865
+ const projectPath = resolve4(globalOpts.project);
64600
64866
  const project = getProject(projectPath);
64601
64867
  if (!project) {
64602
64868
  throw new Error(`Unknown project "${projectPath}": no registered project matches that path.
@@ -64911,7 +65177,7 @@ init_helpers();
64911
65177
  init_projects();
64912
65178
  init_helpers();
64913
65179
  import chalk4 from "chalk";
64914
- import { resolve as resolve4 } from "path";
65180
+ import { resolve as resolve5 } from "path";
64915
65181
  function registerTailCommand(program2) {
64916
65182
  const handleError = makeHandleError(program2);
64917
65183
  program2.command("tail").description("Watch for new/updated memories in real-time (like tail -f)").option("--scope <scope>", "Scope filter: global, shared, private, working").option("-c, --category <cat>", "Category filter: preference, fact, knowledge, history, procedural, resource").option("--agent <name>", "Agent filter").option("--project <path>", "Project filter").option("--interval <ms>", "Poll interval in milliseconds (default: 2000)", parseInt).option("--notify", "Send macOS notifications for each change").action((opts) => {
@@ -64922,7 +65188,7 @@ function registerTailCommand(program2) {
64922
65188
  const projectPath = opts.project || globalOpts.project;
64923
65189
  let projectId;
64924
65190
  if (projectPath) {
64925
- const project = getProject(resolve4(projectPath));
65191
+ const project = getProject(resolve5(projectPath));
64926
65192
  if (project)
64927
65193
  projectId = project.id;
64928
65194
  }
@@ -65025,7 +65291,7 @@ init_projects();
65025
65291
  init_search();
65026
65292
  init_helpers();
65027
65293
  import chalk6 from "chalk";
65028
- import { resolve as resolve5 } from "path";
65294
+ import { resolve as resolve6 } from "path";
65029
65295
  function registerSearchCommand(program2) {
65030
65296
  const handleError = makeHandleError(program2);
65031
65297
  program2.command("search <query>").description("Full-text search across memories").option("--scope <scope>", "Scope filter").option("-c, --category <cat>", "Category filter").option("--tags <tags>", "Comma-separated tags filter").option("--project <path>", "Project filter (path or name)").option("--agent <name>", "Agent filter").option("--session <id>", "Session ID filter").option("--limit <n>", "Max results", parseInt).option("--offset <n>", "Offset for pagination", parseInt).option("--cursor <n>", "Cursor offset for the next page", parseInt).option("--format <fmt>", "Output format: compact (default), json, csv, yaml").option("--verbose", "Show match highlights and wider snippets").option("--history", "Show recent search queries instead of searching").option("--popular", "Show most popular search queries").action((query, opts) => {
@@ -65070,7 +65336,7 @@ function registerSearchCommand(program2) {
65070
65336
  const projectPath = opts.project || globalOpts.project;
65071
65337
  let projectId;
65072
65338
  if (projectPath) {
65073
- const project = getProject(resolve5(projectPath));
65339
+ const project = getProject(resolve6(projectPath));
65074
65340
  if (project)
65075
65341
  projectId = project.id;
65076
65342
  }
@@ -65336,7 +65602,7 @@ init_memories();
65336
65602
  init_search();
65337
65603
  init_helpers();
65338
65604
  import chalk11 from "chalk";
65339
- import { resolve as resolve6 } from "path";
65605
+ import { resolve as resolve7 } from "path";
65340
65606
 
65341
65607
  // src/cli/commands/memory-cmd-recall-exit.ts
65342
65608
  var RECALL_EXIT_NOT_FOUND = 1;
@@ -65352,7 +65618,7 @@ function registerRecallCommand(program2) {
65352
65618
  const projectPath = opts.project || globalOpts.project;
65353
65619
  let projectId;
65354
65620
  if (projectPath) {
65355
- const project = getProject(resolve6(projectPath));
65621
+ const project = getProject(resolve7(projectPath));
65356
65622
  if (project)
65357
65623
  projectId = project.id;
65358
65624
  }
@@ -65411,7 +65677,7 @@ init_memories();
65411
65677
  init_redact();
65412
65678
  init_helpers();
65413
65679
  import chalk12 from "chalk";
65414
- import { resolve as resolve7 } from "path";
65680
+ import { resolve as resolve8 } from "path";
65415
65681
  function registerListCommand(program2) {
65416
65682
  const handleError = makeHandleError(program2);
65417
65683
  program2.command("list").description("List memories with optional filters").option("--scope <scope>", "Scope filter").option("-c, --category <cat>", "Category filter").option("--tags <tags>", "Comma-separated tags filter").option("--importance-min <n>", "Minimum importance", parseInt).option("--pinned", "Show only pinned").option("--agent <name>", "Agent filter").option("--project <path>", "Project filter").option("--session <id>", "Session ID filter").option("--limit <n>", "Max results", parseInt).option("--offset <n>", "Offset for pagination", parseInt).option("--cursor <n>", "Cursor offset for the next page", parseInt).option("--status <status>", "Status filter: active, archived, expired").option("--format <fmt>", "Output format: compact (default), json, csv, yaml").option("--verbose", "Show wider memory snippets in human output").action((opts) => {
@@ -65426,7 +65692,7 @@ function registerListCommand(program2) {
65426
65692
  const projectPath = opts.project || globalOpts.project;
65427
65693
  let projectId;
65428
65694
  if (projectPath) {
65429
- const project = getProject(resolve7(projectPath));
65695
+ const project = getProject(resolve8(projectPath));
65430
65696
  if (!project) {
65431
65697
  throw new Error(`Project not found: ${projectPath}`);
65432
65698
  }
@@ -65740,7 +66006,7 @@ function registerStatsCommand(program2) {
65740
66006
 
65741
66007
  // src/cli/commands/info-report.ts
65742
66008
  import chalk14 from "chalk";
65743
- import { resolve as resolve8 } from "path";
66009
+ import { resolve as resolve9 } from "path";
65744
66010
  init_projects();
65745
66011
  function registerReportCommand(program2) {
65746
66012
  program2.command("report").description("Rich summary of memory activity and top memories").option("--days <n>", "Activity window in days (default: 7)", "7").option("--project <path>", "Filter by project path").option("--markdown", "Output as Markdown (for PRs, docs, etc.)").option("--json", "Output as JSON").action((opts) => {
@@ -65752,7 +66018,7 @@ function registerReportCommand(program2) {
65752
66018
  const projectPath = opts.project || globalOpts.project;
65753
66019
  let projectId;
65754
66020
  if (projectPath) {
65755
- const project = getProject(resolve8(projectPath));
66021
+ const project = getProject(resolve9(projectPath));
65756
66022
  if (project)
65757
66023
  projectId = project.id;
65758
66024
  }
@@ -65824,7 +66090,7 @@ mementos report \u2014 last ${days} days
65824
66090
 
65825
66091
  // src/cli/commands/info-stale.ts
65826
66092
  import chalk15 from "chalk";
65827
- import { resolve as resolve9 } from "path";
66093
+ import { resolve as resolve10 } from "path";
65828
66094
  init_projects();
65829
66095
  init_helpers();
65830
66096
  function registerStaleCommand(program2) {
@@ -65840,7 +66106,7 @@ function registerStaleCommand(program2) {
65840
66106
  const projectPath = opts.project || globalOpts.project;
65841
66107
  let projectId;
65842
66108
  if (projectPath) {
65843
- const project = getProject(resolve9(projectPath));
66109
+ const project = getProject(resolve10(projectPath));
65844
66110
  if (project)
65845
66111
  projectId = project.id;
65846
66112
  }
@@ -65961,7 +66227,7 @@ function registerHistoryCommand(program2) {
65961
66227
  init_projects();
65962
66228
  init_memories();
65963
66229
  import chalk17 from "chalk";
65964
- import { resolve as resolve10 } from "path";
66230
+ import { resolve as resolve11 } from "path";
65965
66231
 
65966
66232
  // src/lib/machine-visibility.ts
65967
66233
  function resolveVisibleMachineId(machineId, db) {
@@ -66005,7 +66271,7 @@ function registerContextCommand(program2) {
66005
66271
  const visibleMachineId = resolveVisibleMachineId(opts.machine);
66006
66272
  let projectId;
66007
66273
  if (projectPath) {
66008
- const project = getProject(resolve10(projectPath));
66274
+ const project = getProject(resolve11(projectPath));
66009
66275
  if (project)
66010
66276
  projectId = project.id;
66011
66277
  }
@@ -66119,7 +66385,7 @@ function registerInfoCommands(program2) {
66119
66385
  init_projects();
66120
66386
  init_memories();
66121
66387
  init_helpers();
66122
- import { resolve as resolve11 } from "path";
66388
+ import { resolve as resolve12 } from "path";
66123
66389
  function registerExportCommand(program2) {
66124
66390
  const handleError = makeHandleError(program2);
66125
66391
  program2.command("export").description("Export memories as JSON").option("--scope <scope>", "Scope filter").option("-c, --category <cat>", "Category filter").option("--agent <name>", "Agent filter").option("--project <path>", "Project filter").action((opts) => {
@@ -66129,7 +66395,7 @@ function registerExportCommand(program2) {
66129
66395
  const projectPath = opts.project || globalOpts.project;
66130
66396
  let projectId;
66131
66397
  if (projectPath) {
66132
- const project = getProject(resolve11(projectPath));
66398
+ const project = getProject(resolve12(projectPath));
66133
66399
  if (project)
66134
66400
  projectId = project.id;
66135
66401
  }
@@ -66151,7 +66417,7 @@ function registerExportCommand(program2) {
66151
66417
  init_memories();
66152
66418
  init_helpers();
66153
66419
  import chalk18 from "chalk";
66154
- import { resolve as resolve12 } from "path";
66420
+ import { resolve as resolve13 } from "path";
66155
66421
  import { readFileSync as readFileSync5 } from "fs";
66156
66422
  function registerImportCommand(program2) {
66157
66423
  const handleError = makeHandleError(program2);
@@ -66162,7 +66428,7 @@ function registerImportCommand(program2) {
66162
66428
  if (file === "-" || !file && !process.stdin.isTTY) {
66163
66429
  raw = await Bun.stdin.text();
66164
66430
  } else if (file) {
66165
- raw = readFileSync5(resolve12(file), "utf-8");
66431
+ raw = readFileSync5(resolve13(file), "utf-8");
66166
66432
  } else {
66167
66433
  console.error(chalk18.red("No input: provide a file path, use '-' for stdin, or pipe data."));
66168
66434
  process.exit(1);
@@ -66192,14 +66458,15 @@ function registerImportCommand(program2) {
66192
66458
  import chalk19 from "chalk";
66193
66459
 
66194
66460
  // src/lib/config.ts
66195
- import { existsSync as existsSync5, mkdirSync as mkdirSync3, readFileSync as readFileSync6, readdirSync, writeFileSync as writeFileSync3, unlinkSync as unlinkSync2, cpSync as cpSync2 } from "fs";
66196
- import { homedir as homedir4 } from "os";
66197
- import { basename, dirname as dirname4, join as join8, resolve as resolve13 } from "path";
66461
+ init_paths();
66462
+ import { existsSync as existsSync6, mkdirSync as mkdirSync3, readFileSync as readFileSync6, readdirSync, writeFileSync as writeFileSync3, unlinkSync as unlinkSync2, cpSync as cpSync2 } from "fs";
66463
+ import { homedir as homedir5 } from "os";
66464
+ import { basename, dirname as dirname4, join as join10, resolve as resolve14 } from "path";
66198
66465
  function isInMemoryDb2(path) {
66199
66466
  return path === ":memory:" || path.startsWith("file::memory:");
66200
66467
  }
66201
66468
  function homeDir() {
66202
- return process.env["HOME"] || process.env["USERPROFILE"] || homedir4();
66469
+ return process.env["HOME"] || process.env["USERPROFILE"] || homedir5();
66203
66470
  }
66204
66471
  var DEFAULT_CONFIG = {
66205
66472
  default_scope: "private",
@@ -66257,9 +66524,9 @@ function isValidCategory(value) {
66257
66524
  return VALID_CATEGORIES2.includes(value);
66258
66525
  }
66259
66526
  function loadConfig() {
66260
- const configPath = join8(homeDir(), ".hasna", "mementos", "config.json");
66527
+ const configPath = join10(getDataRoot(), "config.json");
66261
66528
  let fileConfig = {};
66262
- if (existsSync5(configPath)) {
66529
+ if (existsSync6(configPath)) {
66263
66530
  try {
66264
66531
  const raw = readFileSync6(configPath, "utf-8");
66265
66532
  fileConfig = JSON.parse(raw);
@@ -66285,10 +66552,10 @@ function loadConfig() {
66285
66552
  }
66286
66553
  function findFileWalkingUp(filename) {
66287
66554
  let dir = process.cwd();
66288
- const legacyHomeMementosDb = resolve13(homeDir(), ".mementos", "mementos.db");
66555
+ const legacyHomeMementosDb = resolve14(homeDir(), ".mementos", "mementos.db");
66289
66556
  while (true) {
66290
- const candidate = join8(dir, filename);
66291
- if (existsSync5(candidate) && resolve13(candidate) !== legacyHomeMementosDb) {
66557
+ const candidate = join10(dir, filename);
66558
+ if (existsSync6(candidate) && resolve14(candidate) !== legacyHomeMementosDb) {
66292
66559
  return candidate;
66293
66560
  }
66294
66561
  const parent = dirname4(dir);
@@ -66301,7 +66568,7 @@ function findFileWalkingUp(filename) {
66301
66568
  function findGitRoot2() {
66302
66569
  let dir = process.cwd();
66303
66570
  while (true) {
66304
- if (existsSync5(join8(dir, ".git"))) {
66571
+ if (existsSync6(join10(dir, ".git"))) {
66305
66572
  return dir;
66306
66573
  }
66307
66574
  const parent = dirname4(dir);
@@ -66312,14 +66579,14 @@ function findGitRoot2() {
66312
66579
  }
66313
66580
  }
66314
66581
  function profilesDir() {
66315
- return join8(homeDir(), ".hasna", "mementos", "profiles");
66582
+ return join10(getDataRoot(), "profiles");
66316
66583
  }
66317
66584
  function globalConfigPath() {
66318
- return join8(homeDir(), ".hasna", "mementos", "config.json");
66585
+ return join10(getDataRoot(), "config.json");
66319
66586
  }
66320
66587
  function readGlobalConfig() {
66321
66588
  const p = globalConfigPath();
66322
- if (!existsSync5(p))
66589
+ if (!existsSync6(p))
66323
66590
  return {};
66324
66591
  try {
66325
66592
  return JSON.parse(readFileSync6(p, "utf-8"));
@@ -66329,7 +66596,7 @@ function readGlobalConfig() {
66329
66596
  }
66330
66597
  function readGlobalConfigForWrite() {
66331
66598
  const p = globalConfigPath();
66332
- if (!existsSync5(p))
66599
+ if (!existsSync6(p))
66333
66600
  return {};
66334
66601
  try {
66335
66602
  const data = JSON.parse(readFileSync6(p, "utf-8"));
@@ -66365,13 +66632,13 @@ function setActiveProfile(name) {
66365
66632
  }
66366
66633
  function listProfiles() {
66367
66634
  const dir = profilesDir();
66368
- if (!existsSync5(dir))
66635
+ if (!existsSync6(dir))
66369
66636
  return [];
66370
66637
  return readdirSync(dir).filter((f) => f.endsWith(".db")).map((f) => basename(f, ".db")).sort();
66371
66638
  }
66372
66639
  function deleteProfile(name) {
66373
- const dbPath = join8(profilesDir(), `${name}.db`);
66374
- if (!existsSync5(dbPath))
66640
+ const dbPath = join10(profilesDir(), `${name}.db`);
66641
+ if (!existsSync6(dbPath))
66375
66642
  return false;
66376
66643
  unlinkSync2(dbPath);
66377
66644
  if (getActiveProfile() === name)
@@ -66380,10 +66647,10 @@ function deleteProfile(name) {
66380
66647
  }
66381
66648
  function getDbPath2() {
66382
66649
  const _home = homeDir();
66383
- const _newDir = join8(_home, ".hasna", "mementos");
66384
- const _oldDir = join8(_home, ".mementos");
66385
- if (!existsSync5(_newDir) && existsSync5(_oldDir)) {
66386
- mkdirSync3(join8(_home, ".hasna"), { recursive: true });
66650
+ const _newDir = getDataRoot();
66651
+ const _oldDir = join10(_home, ".mementos");
66652
+ if (!existsSync6(_newDir) && existsSync6(_oldDir)) {
66653
+ mkdirSync3(join10(_home, ".hasna"), { recursive: true });
66387
66654
  cpSync2(_oldDir, _newDir, { recursive: true });
66388
66655
  }
66389
66656
  const envDbPath = process.env["HASNA_MEMENTOS_DB_PATH"] ?? process.env["MEMENTOS_DB_PATH"];
@@ -66391,13 +66658,13 @@ function getDbPath2() {
66391
66658
  if (isInMemoryDb2(envDbPath)) {
66392
66659
  return envDbPath;
66393
66660
  }
66394
- const resolved = resolve13(envDbPath);
66661
+ const resolved = resolve14(envDbPath);
66395
66662
  ensureDir2(dirname4(resolved));
66396
66663
  return resolved;
66397
66664
  }
66398
66665
  const profile = getActiveProfile();
66399
66666
  if (profile) {
66400
- const profilePath = join8(profilesDir(), `${profile}.db`);
66667
+ const profilePath = join10(profilesDir(), `${profile}.db`);
66401
66668
  ensureDir2(dirname4(profilePath));
66402
66669
  return profilePath;
66403
66670
  }
@@ -66405,21 +66672,21 @@ function getDbPath2() {
66405
66672
  if (dbScope === "project") {
66406
66673
  const gitRoot = findGitRoot2();
66407
66674
  if (gitRoot) {
66408
- const dbPath = join8(gitRoot, ".mementos", "mementos.db");
66675
+ const dbPath = join10(gitRoot, ".mementos", "mementos.db");
66409
66676
  ensureDir2(dirname4(dbPath));
66410
66677
  return dbPath;
66411
66678
  }
66412
66679
  }
66413
- const found = findFileWalkingUp(join8(".mementos", "mementos.db"));
66680
+ const found = findFileWalkingUp(join10(".mementos", "mementos.db"));
66414
66681
  if (found) {
66415
66682
  return found;
66416
66683
  }
66417
- const fallback = join8(homeDir(), ".hasna", "mementos", "mementos.db");
66684
+ const fallback = join10(getDataRoot(), "mementos.db");
66418
66685
  ensureDir2(dirname4(fallback));
66419
66686
  return fallback;
66420
66687
  }
66421
66688
  function ensureDir2(dir) {
66422
- if (!existsSync5(dir)) {
66689
+ if (!existsSync6(dir)) {
66423
66690
  mkdirSync3(dir, { recursive: true });
66424
66691
  }
66425
66692
  }
@@ -66534,19 +66801,19 @@ function registerCleanCommand(program2) {
66534
66801
 
66535
66802
  // src/cli/commands/io-backup.ts
66536
66803
  init_database();
66804
+ init_paths();
66537
66805
  init_helpers();
66538
66806
  import chalk20 from "chalk";
66539
- import { resolve as resolve14, dirname as dirname5 } from "path";
66540
- import { existsSync as existsSync6, statSync, copyFileSync, mkdirSync as mkdirSync4, readdirSync as readdirSync2 } from "fs";
66807
+ import { join as join11, resolve as resolve15, dirname as dirname5 } from "path";
66808
+ import { existsSync as existsSync7, statSync, copyFileSync, mkdirSync as mkdirSync4, readdirSync as readdirSync2 } from "fs";
66541
66809
  function registerBackupCommand(program2) {
66542
66810
  const handleError = makeHandleError(program2);
66543
- program2.command("backup [path]").description("Backup the SQLite database to a file").option("--list", "List available backups in ~/.hasna/mementos/backups/").action((targetPath, opts) => {
66811
+ program2.command("backup [path]").description("Backup the SQLite database to a file").option("--list", "List available backups in the mementos backups dir").action((targetPath, opts) => {
66544
66812
  try {
66545
66813
  const globalOpts = program2.opts();
66546
- const home = process.env["HOME"] || process.env["USERPROFILE"] || "~";
66547
- const backupsDir = resolve14(home, ".hasna", "mementos", "backups");
66814
+ const backupsDir = join11(getDataRoot(), "backups");
66548
66815
  if (opts.list) {
66549
- if (!existsSync6(backupsDir)) {
66816
+ if (!existsSync7(backupsDir)) {
66550
66817
  if (globalOpts.json) {
66551
66818
  outputJson({ backups: [] });
66552
66819
  return;
@@ -66555,7 +66822,7 @@ function registerBackupCommand(program2) {
66555
66822
  return;
66556
66823
  }
66557
66824
  const files = readdirSync2(backupsDir).filter((f) => f.endsWith(".db")).map((f) => {
66558
- const filePath = resolve14(backupsDir, f);
66825
+ const filePath = resolve15(backupsDir, f);
66559
66826
  const st2 = statSync(filePath);
66560
66827
  return { name: f, path: filePath, size: st2.size, mtime: st2.mtime };
66561
66828
  }).sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
@@ -66588,23 +66855,23 @@ function registerBackupCommand(program2) {
66588
66855
  return;
66589
66856
  }
66590
66857
  const dbPath = getDbPath();
66591
- if (!existsSync6(dbPath)) {
66858
+ if (!existsSync7(dbPath)) {
66592
66859
  console.error(chalk20.red(`Database not found at ${dbPath}`));
66593
66860
  process.exit(1);
66594
66861
  }
66595
66862
  let dest;
66596
66863
  if (targetPath) {
66597
- dest = resolve14(targetPath);
66864
+ dest = resolve15(targetPath);
66598
66865
  } else {
66599
- if (!existsSync6(backupsDir)) {
66866
+ if (!existsSync7(backupsDir)) {
66600
66867
  mkdirSync4(backupsDir, { recursive: true });
66601
66868
  }
66602
66869
  const now3 = new Date;
66603
66870
  const ts = now3.toISOString().replace(/[-:T]/g, "").replace(/\..+/, "").slice(0, 15);
66604
- dest = resolve14(backupsDir, `mementos-${ts}.db`);
66871
+ dest = resolve15(backupsDir, `mementos-${ts}.db`);
66605
66872
  }
66606
66873
  const destDir = dirname5(dest);
66607
- if (!existsSync6(destDir)) {
66874
+ if (!existsSync7(destDir)) {
66608
66875
  mkdirSync4(destDir, { recursive: true });
66609
66876
  }
66610
66877
  copyFileSync(dbPath, dest);
@@ -66626,10 +66893,11 @@ function registerBackupCommand(program2) {
66626
66893
  init_database();
66627
66894
  init_api_mode();
66628
66895
  init_memories();
66896
+ init_paths();
66629
66897
  init_helpers();
66630
66898
  import chalk21 from "chalk";
66631
- import { resolve as resolve15 } from "path";
66632
- import { existsSync as existsSync7, statSync as statSync2, copyFileSync as copyFileSync2, readdirSync as readdirSync3 } from "fs";
66899
+ import { join as join12, resolve as resolve16 } from "path";
66900
+ import { existsSync as existsSync8, statSync as statSync2, copyFileSync as copyFileSync2, readdirSync as readdirSync3 } from "fs";
66633
66901
  function readMemoriesFromBackup(source) {
66634
66902
  const { Database: Database3 } = __require("bun:sqlite");
66635
66903
  const backupDb = new Database3(source, { readonly: true });
@@ -66642,19 +66910,18 @@ function readMemoriesFromBackup(source) {
66642
66910
  }
66643
66911
  function registerRestoreCommand(program2) {
66644
66912
  const handleError = makeHandleError(program2);
66645
- program2.command("restore [file]").description("Restore the database from a backup file").option("--latest", "Restore the most recent backup from ~/.hasna/mementos/backups/").option("--force", "Skip confirmation and perform the restore").action((filePath, opts) => {
66913
+ program2.command("restore [file]").description("Restore the database from a backup file").option("--latest", "Restore the most recent backup from the mementos backups dir").option("--force", "Skip confirmation and perform the restore").action((filePath, opts) => {
66646
66914
  try {
66647
66915
  const globalOpts = program2.opts();
66648
- const home = process.env["HOME"] || process.env["USERPROFILE"] || "~";
66649
- const backupsDir = resolve15(home, ".hasna", "mementos", "backups");
66916
+ const backupsDir = join12(getDataRoot(), "backups");
66650
66917
  let source;
66651
66918
  if (opts.latest) {
66652
- if (!existsSync7(backupsDir)) {
66919
+ if (!existsSync8(backupsDir)) {
66653
66920
  console.error(chalk21.red("No backups directory found."));
66654
66921
  process.exit(1);
66655
66922
  }
66656
66923
  const files = readdirSync3(backupsDir).filter((f) => f.endsWith(".db")).map((f) => {
66657
- const fp = resolve15(backupsDir, f);
66924
+ const fp = resolve16(backupsDir, f);
66658
66925
  const st = statSync2(fp);
66659
66926
  return { path: fp, mtime: st.mtime };
66660
66927
  }).sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
@@ -66664,12 +66931,12 @@ function registerRestoreCommand(program2) {
66664
66931
  }
66665
66932
  source = files[0].path;
66666
66933
  } else if (filePath) {
66667
- source = resolve15(filePath);
66934
+ source = resolve16(filePath);
66668
66935
  } else {
66669
66936
  console.error(chalk21.red("Provide a backup file path or use --latest"));
66670
66937
  process.exit(1);
66671
66938
  }
66672
- if (!existsSync7(source)) {
66939
+ if (!existsSync8(source)) {
66673
66940
  console.error(chalk21.red(`Backup file not found: ${source}`));
66674
66941
  process.exit(1);
66675
66942
  }
@@ -66744,7 +67011,7 @@ function registerRestoreCommand(program2) {
66744
67011
  }
66745
67012
  const dbPath = getDbPath();
66746
67013
  let currentCount = 0;
66747
- if (existsSync7(dbPath)) {
67014
+ if (existsSync8(dbPath)) {
66748
67015
  try {
66749
67016
  const db = getDatabase();
66750
67017
  const row = db.query("SELECT COUNT(*) as count FROM memories").get();
@@ -67026,7 +67293,7 @@ function registerAgentCommands(program2) {
67026
67293
  init_projects();
67027
67294
  init_memories();
67028
67295
  import chalk23 from "chalk";
67029
- import { resolve as resolve16 } from "path";
67296
+ import { resolve as resolve17 } from "path";
67030
67297
  init_helpers();
67031
67298
  function registerProjectCommands(program2) {
67032
67299
  const handleError = makeHandleError(program2);
@@ -67044,7 +67311,7 @@ function registerProjectCommands(program2) {
67044
67311
  console.error(chalk23.red("--name and --path are required when adding a project"));
67045
67312
  process.exit(1);
67046
67313
  }
67047
- const project = registerProject(name, resolve16(path), opts.description);
67314
+ const project = registerProject(name, resolve17(path), opts.description);
67048
67315
  if (globalOpts.json) {
67049
67316
  outputJson(project);
67050
67317
  } else {
@@ -67060,7 +67327,7 @@ function registerProjectCommands(program2) {
67060
67327
  if (opts.name !== undefined)
67061
67328
  updates.name = opts.name;
67062
67329
  if (opts.path !== undefined)
67063
- updates.path = resolve16(opts.path);
67330
+ updates.path = resolve17(opts.path);
67064
67331
  if (opts.description !== undefined) {
67065
67332
  updates.description = opts.description;
67066
67333
  }
@@ -67204,7 +67471,7 @@ function registerProjectCommands(program2) {
67204
67471
  const visibleMachineId = resolveVisibleMachineId(opts.machine);
67205
67472
  let projectId;
67206
67473
  if (projectPath) {
67207
- const project = getProject(resolve16(projectPath));
67474
+ const project = getProject(resolve17(projectPath));
67208
67475
  if (project)
67209
67476
  projectId = project.id;
67210
67477
  }
@@ -67557,7 +67824,7 @@ init_relations();
67557
67824
  init_entity_memories();
67558
67825
  init_helpers();
67559
67826
  import chalk24 from "chalk";
67560
- import { resolve as resolve17 } from "path";
67827
+ import { resolve as resolve18 } from "path";
67561
67828
  function registerEntityCommands(program2) {
67562
67829
  const handleError = makeHandleError(program2);
67563
67830
  const entityCmd = program2.command("entity").description("Knowledge graph entity commands");
@@ -67567,7 +67834,7 @@ function registerEntityCommands(program2) {
67567
67834
  const projectPath = opts.project || globalOpts.project;
67568
67835
  let projectId;
67569
67836
  if (projectPath) {
67570
- const project = getProject(resolve17(projectPath));
67837
+ const project = getProject(resolve18(projectPath));
67571
67838
  if (project)
67572
67839
  projectId = project.id;
67573
67840
  }
@@ -67640,7 +67907,7 @@ ${chalk24.bold(`Linked memories (${visibleMemories.length}${memories.length > vi
67640
67907
  const projectPath = opts.project || globalOpts.project;
67641
67908
  let projectId;
67642
67909
  if (projectPath) {
67643
- const project = getProject(resolve17(projectPath));
67910
+ const project = getProject(resolve18(projectPath));
67644
67911
  if (project)
67645
67912
  projectId = project.id;
67646
67913
  }
@@ -67998,11 +68265,11 @@ init_memories();
67998
68265
  init_agents();
67999
68266
  init_projects();
68000
68267
  import chalk27 from "chalk";
68001
- import { join as join9 } from "path";
68002
- import { homedir as homedir5 } from "os";
68268
+ import { join as join13 } from "path";
68269
+ import { homedir as homedir6 } from "os";
68003
68270
  import {
68004
68271
  readFileSync as readFileSync7,
68005
- existsSync as existsSync8,
68272
+ existsSync as existsSync9,
68006
68273
  accessSync,
68007
68274
  statSync as statSync3,
68008
68275
  constants as fsConstants
@@ -68016,10 +68283,10 @@ async function runCommandWithTimeout(args, timeoutMs) {
68016
68283
  let timedOut = false;
68017
68284
  const exitCode = await Promise.race([
68018
68285
  proc.exited,
68019
- new Promise((resolve18) => setTimeout(() => {
68286
+ new Promise((resolve19) => setTimeout(() => {
68020
68287
  timedOut = true;
68021
68288
  proc.kill();
68022
- resolve18(null);
68289
+ resolve19(null);
68023
68290
  }, timeoutMs))
68024
68291
  ]);
68025
68292
  const [stdout, stderr] = await Promise.all([stdoutPromise, stderrPromise]);
@@ -68037,7 +68304,7 @@ function registerDoctorCommand(program2) {
68037
68304
  checks.push({ name: "Version", status: "ok", detail: version });
68038
68305
  const dbPath = getDbPath();
68039
68306
  let db = null;
68040
- if (dbPath !== ":memory:" && existsSync8(dbPath)) {
68307
+ if (dbPath !== ":memory:" && existsSync9(dbPath)) {
68041
68308
  try {
68042
68309
  accessSync(dbPath, fsConstants.R_OK | fsConstants.W_OK);
68043
68310
  checks.push({ name: "Database file", status: "ok", detail: dbPath });
@@ -68056,7 +68323,7 @@ function registerDoctorCommand(program2) {
68056
68323
  checks.push({ name: "Database connection", status: "fail", detail: e instanceof Error ? e.message : String(e) });
68057
68324
  }
68058
68325
  try {
68059
- if (dbPath !== ":memory:" && existsSync8(dbPath)) {
68326
+ if (dbPath !== ":memory:" && existsSync9(dbPath)) {
68060
68327
  const stats = statSync3(dbPath);
68061
68328
  const sizeKb = (stats.size / 1024).toFixed(1);
68062
68329
  const sizeMb = (stats.size / (1024 * 1024)).toFixed(2);
@@ -68189,8 +68456,8 @@ function registerDoctorCommand(program2) {
68189
68456
  checks.push({ name: "MCP server", status: "warn", detail: "could not check (is claude CLI installed?)" });
68190
68457
  }
68191
68458
  try {
68192
- const settingsFilePath = join9(homedir5(), ".claude", "settings.json");
68193
- if (existsSync8(settingsFilePath)) {
68459
+ const settingsFilePath = join13(homedir6(), ".claude", "settings.json");
68460
+ if (existsSync9(settingsFilePath)) {
68194
68461
  const settings = JSON.parse(readFileSync7(settingsFilePath, "utf-8"));
68195
68462
  const hooksObj = settings["hooks"] || {};
68196
68463
  const stopHooks = hooksObj["Stop"] || [];
@@ -68207,11 +68474,11 @@ function registerDoctorCommand(program2) {
68207
68474
  checks.push({ name: "Stop hook", status: "warn", detail: "could not check stop hook" });
68208
68475
  }
68209
68476
  if (process.platform === "darwin") {
68210
- const plistFilePath = join9(homedir5(), "Library", "LaunchAgents", "com.hasna.mementos.plist");
68477
+ const plistFilePath = join13(homedir6(), "Library", "LaunchAgents", "com.hasna.mementos.plist");
68211
68478
  checks.push({
68212
68479
  name: "Auto-start",
68213
- status: existsSync8(plistFilePath) ? "ok" : "warn",
68214
- detail: existsSync8(plistFilePath) ? "configured (starts on login)" : "not configured \u2192 run: mementos init"
68480
+ status: existsSync9(plistFilePath) ? "ok" : "warn",
68481
+ detail: existsSync9(plistFilePath) ? "configured (starts on login)" : "not configured \u2192 run: mementos init"
68215
68482
  });
68216
68483
  } else {
68217
68484
  checks.push({ name: "Auto-start", status: "ok", detail: `n/a on ${process.platform}` });
@@ -68290,8 +68557,8 @@ async function runCloudDoctor(globalOpts, checks) {
68290
68557
  checks.push({ name: "MCP server", status: "warn", detail: "could not check (is claude CLI installed?)" });
68291
68558
  }
68292
68559
  try {
68293
- const settingsFilePath = join9(homedir5(), ".claude", "settings.json");
68294
- if (existsSync8(settingsFilePath)) {
68560
+ const settingsFilePath = join13(homedir6(), ".claude", "settings.json");
68561
+ if (existsSync9(settingsFilePath)) {
68295
68562
  const settings = JSON.parse(readFileSync7(settingsFilePath, "utf-8"));
68296
68563
  const hooksObj = settings["hooks"] || {};
68297
68564
  const stopHooks = hooksObj["Stop"] || [];
@@ -68308,11 +68575,11 @@ async function runCloudDoctor(globalOpts, checks) {
68308
68575
  checks.push({ name: "Stop hook", status: "warn", detail: "could not check stop hook" });
68309
68576
  }
68310
68577
  if (process.platform === "darwin") {
68311
- const plistFilePath = join9(homedir5(), "Library", "LaunchAgents", "com.hasna.mementos.plist");
68578
+ const plistFilePath = join13(homedir6(), "Library", "LaunchAgents", "com.hasna.mementos.plist");
68312
68579
  checks.push({
68313
68580
  name: "Auto-start",
68314
- status: existsSync8(plistFilePath) ? "ok" : "warn",
68315
- detail: existsSync8(plistFilePath) ? "configured (starts on login)" : "not configured \u2192 run: mementos init"
68581
+ status: existsSync9(plistFilePath) ? "ok" : "warn",
68582
+ detail: existsSync9(plistFilePath) ? "configured (starts on login)" : "not configured \u2192 run: mementos init"
68316
68583
  });
68317
68584
  } else {
68318
68585
  checks.push({ name: "Auto-start", status: "ok", detail: `n/a on ${process.platform}` });
@@ -68367,7 +68634,7 @@ function registerConfigCommand(program2) {
68367
68634
  return;
68368
68635
  }
68369
68636
  if (subcommand === "path") {
68370
- const p = getConfigPath();
68637
+ const p = getConfigPath2();
68371
68638
  if (useJson) {
68372
68639
  outputJson({ path: p });
68373
68640
  } else {
@@ -68436,7 +68703,7 @@ function registerConfigCommand(program2) {
68436
68703
  console.log(chalk28.green(`Reset ${key} to default (${JSON.stringify(defaultVal)})`));
68437
68704
  }
68438
68705
  } else {
68439
- const configPath = getConfigPath();
68706
+ const configPath = getConfigPath2();
68440
68707
  const { unlinkSync: unlinkSync3, existsSync: _existsSync } = __require("fs");
68441
68708
  if (_existsSync(configPath)) {
68442
68709
  unlinkSync3(configPath);
@@ -68460,6 +68727,8 @@ function registerConfigCommand(program2) {
68460
68727
 
68461
68728
  // src/cli/commands/system-profile.ts
68462
68729
  import chalk29 from "chalk";
68730
+ import { join as join14 } from "path";
68731
+ init_paths();
68463
68732
  init_helpers();
68464
68733
  function registerProfileCommand(program2) {
68465
68734
  const profileCmd = program2.command("profile").description("Manage named profile files and active-profile metadata");
@@ -68490,7 +68759,7 @@ function registerProfileCommand(program2) {
68490
68759
  if (active) {
68491
68760
  console.log(chalk29.green(`Active profile: ${active}`));
68492
68761
  if (!process.env["MEMENTOS_PROFILE"]) {
68493
- console.log(chalk29.dim("(persisted in ~/.hasna/mementos/config.json)"));
68762
+ console.log(chalk29.dim(`(persisted in ${join14(getDataRoot(), "config.json")})`));
68494
68763
  } else {
68495
68764
  console.log(chalk29.dim("(from MEMENTOS_PROFILE env var)"));
68496
68765
  }
@@ -68506,7 +68775,7 @@ function registerProfileCommand(program2) {
68506
68775
  }
68507
68776
  setActiveProfile(clean);
68508
68777
  console.log(chalk29.green(`\u2713 Active-profile metadata set: ${clean}`));
68509
- console.log(chalk29.dim(` Profile file: ~/.hasna/mementos/profiles/${clean}.db`));
68778
+ console.log(chalk29.dim(` Profile file: ${join14(getDataRoot(), "profiles", `${clean}.db`)}`));
68510
68779
  console.log(chalk29.dim(" Run `mementos storage mode` to verify the live runtime database."));
68511
68780
  });
68512
68781
  profileCmd.command("unset").description("Clear the active-profile metadata").action(() => {
@@ -68527,8 +68796,8 @@ function registerProfileCommand(program2) {
68527
68796
  process.exit(1);
68528
68797
  }
68529
68798
  process.stdout.write(chalk29.yellow(`Delete profile "${name}" and its DB? This cannot be undone. [y/N] `));
68530
- const answer = await new Promise((resolve18) => {
68531
- process.stdin.once("data", (d) => resolve18(d.toString().trim().toLowerCase()));
68799
+ const answer = await new Promise((resolve19) => {
68800
+ process.stdin.once("data", (d) => resolve19(d.toString().trim().toLowerCase()));
68532
68801
  });
68533
68802
  if (answer !== "y" && answer !== "yes") {
68534
68803
  console.log(chalk29.dim("Cancelled."));
@@ -69049,7 +69318,7 @@ function registerToolsCommand(program2) {
69049
69318
  // src/cli/commands/system-synthesized-profile.ts
69050
69319
  init_helpers();
69051
69320
  import chalk35 from "chalk";
69052
- import { resolve as resolve18 } from "path";
69321
+ import { resolve as resolve19 } from "path";
69053
69322
  function registerSynthesizedProfileCommand(program2) {
69054
69323
  const handleError = makeHandleError(program2);
69055
69324
  program2.command("synthesized-profile").description("Show or refresh the synthesized agent/project profile").option("--project-id <id>", "Project ID").option("--refresh", "Force refresh the profile (re-synthesize from memories)").action(async (opts) => {
@@ -69059,7 +69328,7 @@ function registerSynthesizedProfileCommand(program2) {
69059
69328
  let projectId = opts.projectId;
69060
69329
  if (!projectId && globalOpts.project) {
69061
69330
  const { getProject: getProject2 } = (init_projects(), __toCommonJS(exports_projects));
69062
- const project = getProject2(resolve18(globalOpts.project));
69331
+ const project = getProject2(resolve19(globalOpts.project));
69063
69332
  if (project)
69064
69333
  projectId = project.id;
69065
69334
  }
@@ -69244,7 +69513,7 @@ function registerMiscCommands(program2) {
69244
69513
  connStr = opts.connectionString;
69245
69514
  } else {
69246
69515
  try {
69247
- connStr = getStorageConnectionString("mementos");
69516
+ connStr = getStorageConnectionStringForOperator("mementos");
69248
69517
  } catch {
69249
69518
  const msg = "Remote storage database is not configured. Use --connection-string or set HASNA_MEMENTOS_DATABASE_URL.";
69250
69519
  if (useJson) {
@@ -69419,7 +69688,7 @@ args = []
69419
69688
  init_memories();
69420
69689
  init_helpers();
69421
69690
  import chalk39 from "chalk";
69422
- import { resolve as resolve19 } from "path";
69691
+ import { resolve as resolve20 } from "path";
69423
69692
  function registerWatchCommand(program2) {
69424
69693
  const handleError = makeHandleError(program2);
69425
69694
  program2.command("watch").description("Watch for new and changed memories in real-time").option("--scope <scope>", "Scope filter: global, shared, private, working").option("-c, --category <cat>", "Category filter: preference, fact, knowledge, history, procedural, resource").option("--agent <name>", "Agent filter").option("--project <path>", "Project filter").option("--interval <ms>", "Poll interval in milliseconds", parseInt).action((opts) => {
@@ -69430,7 +69699,7 @@ function registerWatchCommand(program2) {
69430
69699
  let projectId;
69431
69700
  if (projectPath) {
69432
69701
  const { getProject: getProject2 } = (init_projects(), __toCommonJS(exports_projects));
69433
- const project = getProject2(resolve19(projectPath));
69702
+ const project = getProject2(resolve20(projectPath));
69434
69703
  if (project)
69435
69704
  projectId = project.id;
69436
69705
  }
@@ -69986,7 +70255,7 @@ function resolveCurrentMachineId(local, requested) {
69986
70255
  function runStorageSync(direction, options = {}) {
69987
70256
  const backend = getStorageBackend();
69988
70257
  if (backend === "sqlite" && !options.remote) {
69989
- throw new Error("Remote storage is not configured. Set HASNA_MEMENTOS_DATABASE_URL or configure ~/.hasna/mementos/storage/config.json.");
70258
+ throw new Error(`Remote storage is not configured. Set HASNA_MEMENTOS_DATABASE_URL or configure ${getConfigPath()}.`);
69990
70259
  }
69991
70260
  return withManagedAdapters(options, (local, remote, currentMachineId) => {
69992
70261
  const tables = resolveTables(local, options.tables);
@@ -70250,7 +70519,7 @@ function installStorageSubcommands(storage, program2) {
70250
70519
  }
70251
70520
  return;
70252
70521
  }
70253
- const connectionString = opts.connectionString || getStorageConnectionString("mementos");
70522
+ const connectionString = opts.connectionString || getStorageConnectionStringForOperator("mementos");
70254
70523
  const result = await applyPgMigrations2(connectionString);
70255
70524
  if (useJson) {
70256
70525
  outputJson2(true, result);
@@ -70316,17 +70585,17 @@ import chalk41 from "chalk";
70316
70585
  import {
70317
70586
  readFileSync as readFileSync8,
70318
70587
  writeFileSync as writeFileSync4,
70319
- existsSync as existsSync10,
70588
+ existsSync as existsSync11,
70320
70589
  copyFileSync as copyFileSync3,
70321
70590
  mkdirSync as mkdirSync6
70322
70591
  } from "fs";
70323
- import { dirname as dirname7, join as join11 } from "path";
70324
- import { homedir as homedir6 } from "os";
70592
+ import { dirname as dirname7, join as join16 } from "path";
70593
+ import { homedir as homedir7 } from "os";
70325
70594
  import { fileURLToPath as fileURLToPath4 } from "url";
70326
70595
  function registerInitCommand(program2) {
70327
70596
  program2.command("init").description("One-command setup: register MCP, install stop hook, configure auto-start").action(async () => {
70328
70597
  const { platform: platform2 } = process;
70329
- const home = homedir6();
70598
+ const home = homedir7();
70330
70599
  const isMac = platform2 === "darwin";
70331
70600
  console.log("");
70332
70601
  console.log(chalk41.bold(" mementos \u2014 setting up your memory layer"));
@@ -70381,15 +70650,15 @@ function registerInitCommand(program2) {
70381
70650
  } else {
70382
70651
  console.log(chalk41.green(" \u2713 MCP server registered with Claude Code"));
70383
70652
  }
70384
- const hooksDir = join11(home, ".claude", "hooks");
70385
- const hookDest = join11(hooksDir, "mementos-stop-hook.ts");
70386
- const settingsPath = join11(home, ".claude", "settings.json");
70653
+ const hooksDir = join16(home, ".claude", "hooks");
70654
+ const hookDest = join16(hooksDir, "mementos-stop-hook.ts");
70655
+ const settingsPath = join16(home, ".claude", "settings.json");
70387
70656
  const hookCommand = `bun ${hookDest}`;
70388
70657
  let hookAlreadyInstalled = false;
70389
70658
  let hookError = null;
70390
70659
  try {
70391
70660
  let settings = {};
70392
- if (existsSync10(settingsPath)) {
70661
+ if (existsSync11(settingsPath)) {
70393
70662
  try {
70394
70663
  settings = JSON.parse(readFileSync8(settingsPath, "utf-8"));
70395
70664
  } catch {
@@ -70402,19 +70671,19 @@ function registerInitCommand(program2) {
70402
70671
  if (alreadyHasMementos) {
70403
70672
  hookAlreadyInstalled = true;
70404
70673
  } else {
70405
- if (!existsSync10(hooksDir)) {
70674
+ if (!existsSync11(hooksDir)) {
70406
70675
  mkdirSync6(hooksDir, { recursive: true });
70407
70676
  }
70408
- if (!existsSync10(hookDest)) {
70677
+ if (!existsSync11(hookDest)) {
70409
70678
  const packageDir = dirname7(dirname7(fileURLToPath4(import.meta.url)));
70410
70679
  const candidatePaths = [
70411
- join11(packageDir, "scripts", "hooks", "claude-stop-hook.ts"),
70412
- join11(packageDir, "..", "scripts", "hooks", "claude-stop-hook.ts"),
70413
- join11(home, ".bun", "install", "global", "node_modules", "@hasna", "mementos", "scripts", "hooks", "claude-stop-hook.ts")
70680
+ join16(packageDir, "scripts", "hooks", "claude-stop-hook.ts"),
70681
+ join16(packageDir, "..", "scripts", "hooks", "claude-stop-hook.ts"),
70682
+ join16(home, ".bun", "install", "global", "node_modules", "@hasna", "mementos", "scripts", "hooks", "claude-stop-hook.ts")
70414
70683
  ];
70415
70684
  let hookSourceFound = false;
70416
70685
  for (const src of candidatePaths) {
70417
- if (existsSync10(src)) {
70686
+ if (existsSync11(src)) {
70418
70687
  copyFileSync3(src, hookDest);
70419
70688
  hookSourceFound = true;
70420
70689
  break;
@@ -70480,7 +70749,7 @@ main().catch(() => {});
70480
70749
  if (!isMac) {
70481
70750
  console.log(chalk41.dim(` \xB7 Auto-start skipped (not macOS \u2014 platform: ${platform2})`));
70482
70751
  } else {
70483
- const plistPath = join11(home, "Library", "LaunchAgents", "com.hasna.mementos.plist");
70752
+ const plistPath = join16(home, "Library", "LaunchAgents", "com.hasna.mementos.plist");
70484
70753
  const plistContent = `<?xml version="1.0" encoding="UTF-8"?>
70485
70754
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
70486
70755
  <plist version="1.0">
@@ -70505,11 +70774,11 @@ main().catch(() => {});
70505
70774
  </plist>
70506
70775
  `;
70507
70776
  try {
70508
- if (existsSync10(plistPath)) {
70777
+ if (existsSync11(plistPath)) {
70509
70778
  autoStartAlreadyInstalled = true;
70510
70779
  } else {
70511
- const launchAgentsDir = join11(home, "Library", "LaunchAgents");
70512
- if (!existsSync10(launchAgentsDir)) {
70780
+ const launchAgentsDir = join16(home, "Library", "LaunchAgents");
70781
+ if (!existsSync11(launchAgentsDir)) {
70513
70782
  mkdirSync6(launchAgentsDir, { recursive: true });
70514
70783
  }
70515
70784
  writeFileSync4(plistPath, plistContent, "utf-8");
@@ -70525,7 +70794,7 @@ main().catch(() => {});
70525
70794
  console.log(chalk41.green(" \u2713 Auto-start configured (starts on login)"));
70526
70795
  }
70527
70796
  if (!autoStartAlreadyInstalled && !autoStartError) {
70528
- const plistPath2 = join11(home, "Library", "LaunchAgents", "com.hasna.mementos.plist");
70797
+ const plistPath2 = join16(home, "Library", "LaunchAgents", "com.hasna.mementos.plist");
70529
70798
  const loadResult = await run(["launchctl", "load", plistPath2]);
70530
70799
  if (!loadResult.ok) {
70531
70800
  console.log(chalk41.dim(` \xB7 launchctl load: ${loadResult.output || "already loaded"}`));
@@ -70560,7 +70829,7 @@ main().catch(() => {});
70560
70829
  init_agents();
70561
70830
  init_projects();
70562
70831
  import chalk42 from "chalk";
70563
- import { resolve as resolve21 } from "path";
70832
+ import { resolve as resolve22 } from "path";
70564
70833
 
70565
70834
  // src/lib/consolidation.ts
70566
70835
  init_database();
@@ -71403,7 +71672,7 @@ async function resolveAISDKModel(provider, model) {
71403
71672
  const key = process.env["ANTHROPIC_API_KEY"];
71404
71673
  if (!key)
71405
71674
  return null;
71406
- const mod = await Promise.resolve().then(() => (init_dist4(), exports_dist));
71675
+ const mod = await Promise.resolve().then(() => (init_dist5(), exports_dist));
71407
71676
  const anthropic2 = mod["anthropic"];
71408
71677
  return anthropic2 ? anthropic2(model) : null;
71409
71678
  }
@@ -71411,7 +71680,7 @@ async function resolveAISDKModel(provider, model) {
71411
71680
  const key = process.env["OPENAI_API_KEY"];
71412
71681
  if (!key)
71413
71682
  return null;
71414
- const mod = await Promise.resolve().then(() => (init_dist5(), exports_dist2));
71683
+ const mod = await Promise.resolve().then(() => (init_dist6(), exports_dist2));
71415
71684
  const openai2 = mod["openai"];
71416
71685
  return openai2 ? openai2(model) : null;
71417
71686
  }
@@ -71420,7 +71689,7 @@ async function resolveAISDKModel(provider, model) {
71420
71689
  if (!apiKey)
71421
71690
  return null;
71422
71691
  const baseURL = provider === "cerebras" ? "https://api.cerebras.ai/v1" : "https://api.x.ai/v1";
71423
- const mod = await Promise.resolve().then(() => (init_dist6(), exports_dist3));
71692
+ const mod = await Promise.resolve().then(() => (init_dist7(), exports_dist3));
71424
71693
  const createOpenAICompatible2 = mod["createOpenAICompatible"];
71425
71694
  if (!createOpenAICompatible2)
71426
71695
  return null;
@@ -71436,7 +71705,7 @@ function createAISDKReflectionCritic(options = {}) {
71436
71705
  if (!resolvedModel)
71437
71706
  return heuristicReflectionCritic(trajectory);
71438
71707
  try {
71439
- const ai = await Promise.resolve().then(() => (init_dist8(), exports_dist4));
71708
+ const ai = await Promise.resolve().then(() => (init_dist9(), exports_dist4));
71440
71709
  const generateObject2 = ai["generateObject"];
71441
71710
  if (!generateObject2)
71442
71711
  return heuristicReflectionCritic(trajectory);
@@ -71548,7 +71817,7 @@ function resolveAgentId(nameOrId) {
71548
71817
  function resolveProjectId(pathOrId) {
71549
71818
  if (!pathOrId)
71550
71819
  return;
71551
- return getProject(resolve21(pathOrId))?.id ?? getProject(pathOrId)?.id ?? pathOrId;
71820
+ return getProject(resolve22(pathOrId))?.id ?? getProject(pathOrId)?.id ?? pathOrId;
71552
71821
  }
71553
71822
  function registerConsolidationCommands(program2) {
71554
71823
  program2.command("consolidate").description("Consolidate memories: dedup, promote, summarize, and soft-delete stale low-value entries").option("--dry-run", "Plan actions without mutating memories").option("--scope <scope>", "Scope to consolidate: global, shared, private").option("--project <idOrPath>", "Project ID, name, or path").option("--agent <nameOrId>", "Agent name or ID").option("--duplicate-threshold <n>", "Near-duplicate similarity threshold 0-1", parseNumber2).option("--stale-days <n>", "Minimum age for decay/forget candidates", parseNumber2).option("--decay-threshold <n>", "Maximum decay score for soft-delete candidates", parseNumber2).option("--limit <n>", "Maximum memories to analyze", parseNumber2).option("--format <fmt>", "Output format: compact, json").action(async (opts) => {
@@ -71639,13 +71908,12 @@ function lessonTagForCli(kind) {
71639
71908
 
71640
71909
  // src/cli/brains.ts
71641
71910
  import {
71642
- existsSync as existsSync12,
71911
+ existsSync as existsSync13,
71643
71912
  mkdirSync as mkdirSync8,
71644
71913
  writeFileSync as writeFileSync6,
71645
71914
  readdirSync as readdirSync4
71646
71915
  } from "fs";
71647
- import { homedir as homedir8 } from "os";
71648
- import { join as join13 } from "path";
71916
+ import { join as join18 } from "path";
71649
71917
  import chalk43 from "chalk";
71650
71918
 
71651
71919
  // src/lib/gatherer.ts
@@ -71721,15 +71989,18 @@ var gatherTrainingData = async (options = {}) => {
71721
71989
  };
71722
71990
  };
71723
71991
 
71992
+ // src/cli/brains.ts
71993
+ init_paths();
71994
+
71724
71995
  // src/lib/model-config.ts
71725
- import { existsSync as existsSync11, mkdirSync as mkdirSync7, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "fs";
71726
- import { homedir as homedir7 } from "os";
71727
- import { join as join12 } from "path";
71996
+ init_paths();
71997
+ import { existsSync as existsSync12, mkdirSync as mkdirSync7, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "fs";
71998
+ import { join as join17 } from "path";
71728
71999
  var DEFAULT_MODEL = "gpt-4o-mini";
71729
- var CONFIG_DIR = join12(homedir7(), ".hasna", "mementos");
71730
- var CONFIG_PATH = join12(CONFIG_DIR, "config.json");
72000
+ var CONFIG_DIR = getDataRoot();
72001
+ var CONFIG_PATH = join17(CONFIG_DIR, "config.json");
71731
72002
  function readConfig() {
71732
- if (!existsSync11(CONFIG_PATH))
72003
+ if (!existsSync12(CONFIG_PATH))
71733
72004
  return {};
71734
72005
  try {
71735
72006
  const raw = readFileSync9(CONFIG_PATH, "utf-8");
@@ -71739,7 +72010,7 @@ function readConfig() {
71739
72010
  }
71740
72011
  }
71741
72012
  function writeConfig(config2) {
71742
- if (!existsSync11(CONFIG_DIR)) {
72013
+ if (!existsSync12(CONFIG_DIR)) {
71743
72014
  mkdirSync7(CONFIG_DIR, { recursive: true });
71744
72015
  }
71745
72016
  writeFileSync5(CONFIG_PATH, JSON.stringify(config2, null, 2) + `
@@ -71773,7 +72044,7 @@ function printInfo(msg) {
71773
72044
  function makeBrainsCommand() {
71774
72045
  const brains = new Command("brains");
71775
72046
  brains.description("Fine-tuned model training and management (via @hasna/brains)");
71776
- brains.command("gather").description("Gather training data from memories and write to JSONL").option("--limit <n>", "Maximum number of examples to gather", parseInt).option("--since <date>", "Only include memories created since this date (ISO 8601)").option("--output <dir>", "Output directory (default: ~/.hasna/mementos/training/)").option("--json", "Output result summary as JSON").action(async (opts) => {
72047
+ brains.command("gather").description("Gather training data from memories and write to JSONL").option("--limit <n>", "Maximum number of examples to gather", parseInt).option("--since <date>", "Only include memories created since this date (ISO 8601)").option("--output <dir>", "Output directory (default: the mementos training data dir)").option("--json", "Output result summary as JSON").action(async (opts) => {
71777
72048
  try {
71778
72049
  const since = opts.since ? new Date(opts.since) : undefined;
71779
72050
  if (since && isNaN(since.getTime())) {
@@ -71787,12 +72058,12 @@ function makeBrainsCommand() {
71787
72058
  limit: opts.limit,
71788
72059
  since
71789
72060
  });
71790
- const outputDir = opts.output ?? join13(homedir8(), ".hasna", "mementos", "training");
71791
- if (!existsSync12(outputDir)) {
72061
+ const outputDir = opts.output ?? join18(getDataRoot(), "training");
72062
+ if (!existsSync13(outputDir)) {
71792
72063
  mkdirSync8(outputDir, { recursive: true });
71793
72064
  }
71794
72065
  const timestamp2 = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
71795
- const outputPath = join13(outputDir, `mementos-training-${timestamp2}.jsonl`);
72066
+ const outputPath = join18(outputDir, `mementos-training-${timestamp2}.jsonl`);
71796
72067
  const jsonl = result.examples.map((ex) => JSON.stringify(ex)).join(`
71797
72068
  `);
71798
72069
  writeFileSync6(outputPath, jsonl + `
@@ -71816,8 +72087,8 @@ function makeBrainsCommand() {
71816
72087
  try {
71817
72088
  let datasetPath = opts.dataset;
71818
72089
  if (!datasetPath) {
71819
- const trainingDir = join13(homedir8(), ".hasna", "mementos", "training");
71820
- if (!existsSync12(trainingDir)) {
72090
+ const trainingDir = join18(getDataRoot(), "training");
72091
+ if (!existsSync13(trainingDir)) {
71821
72092
  printError("No training data found. Run `mementos brains gather` first.");
71822
72093
  process.exit(1);
71823
72094
  }
@@ -71827,9 +72098,9 @@ function makeBrainsCommand() {
71827
72098
  printError("No JSONL training files found. Run `mementos brains gather` first.");
71828
72099
  process.exit(1);
71829
72100
  }
71830
- datasetPath = join13(trainingDir, latestFile);
72101
+ datasetPath = join18(trainingDir, latestFile);
71831
72102
  }
71832
- if (!datasetPath || !existsSync12(datasetPath)) {
72103
+ if (!datasetPath || !existsSync13(datasetPath)) {
71833
72104
  printError(`Dataset file not found: ${datasetPath ?? "(unresolved)"}`);
71834
72105
  process.exit(1);
71835
72106
  }
@@ -71955,7 +72226,7 @@ function registerAllCommands(program2) {
71955
72226
  // src/cli/index.tsx
71956
72227
  function getPackageVersion2() {
71957
72228
  try {
71958
- const pkgPath = join14(dirname8(fileURLToPath5(import.meta.url)), "..", "..", "package.json");
72229
+ const pkgPath = join19(dirname8(fileURLToPath5(import.meta.url)), "..", "..", "package.json");
71959
72230
  const pkg = JSON.parse(readFileSync10(pkgPath, "utf-8"));
71960
72231
  return pkg.version || "0.0.0";
71961
72232
  } catch {