@use-aistack/cli 0.16.4 → 0.16.6

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.
@@ -764,8 +764,8 @@ function detectPreferredStackSource(customDataPath) {
764
764
  return isWSL() ? "store" : "composer";
765
765
  }
766
766
  function getDefaultCursorDataPath(platform) {
767
- const p = platform ?? detectPlatform();
768
- switch (p) {
767
+ const p2 = platform ?? detectPlatform();
768
+ switch (p2) {
769
769
  case "windows":
770
770
  return join(process.env["APPDATA"] ?? join(homedir(), "AppData", "Roaming"), "Cursor", "User", "workspaceStorage");
771
771
  case "macos":
@@ -814,8 +814,8 @@ function normalizePath(filePath) {
814
814
  return normalized;
815
815
  }
816
816
  function pathsEqual(path1, path2) {
817
- const normalize = (p) => {
818
- let normalized = normalizePath(p).replace(/\\/g, "/");
817
+ const normalize = (p2) => {
818
+ let normalized = normalizePath(p2).replace(/\\/g, "/");
819
819
  if (/^\/[a-z]:\//i.test(normalized))
820
820
  normalized = normalized.slice(1);
821
821
  const wsl = normalized.match(/^\/mnt\/([a-z])(?:\/(.*))?$/i);
@@ -833,9 +833,9 @@ function pathsEqual(path1, path2) {
833
833
  function getStoreStackRoot(customDataPath) {
834
834
  return resolveStoreRoot(customDataPath);
835
835
  }
836
- function listSubdirs(p) {
836
+ function listSubdirs(p2) {
837
837
  try {
838
- return readdirSync(p, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
838
+ return readdirSync(p2, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
839
839
  } catch {
840
840
  return [];
841
841
  }
@@ -864,22 +864,22 @@ function hasStoreStructure(root) {
864
864
  }
865
865
  return false;
866
866
  }
867
- function isStoreRoot(p) {
868
- if (basename(p) === ".cursor")
867
+ function isStoreRoot(p2) {
868
+ if (basename(p2) === ".cursor")
869
869
  return true;
870
- const childCount = STORE_CHILDREN.filter((child) => existsSync(join(p, child))).length;
871
- return childCount >= 2 || hasStoreStructure(p);
870
+ const childCount = STORE_CHILDREN.filter((child) => existsSync(join(p2, child))).length;
871
+ return childCount >= 2 || hasStoreStructure(p2);
872
872
  }
873
- function isProvenStoreRoot(p) {
874
- return basename(p) === ".cursor" || hasStoreStructure(p);
873
+ function isProvenStoreRoot(p2) {
874
+ return basename(p2) === ".cursor" || hasStoreStructure(p2);
875
875
  }
876
- function findStoreRoot(p) {
877
- if (isStoreRoot(p))
878
- return p;
879
- if (STORE_CHILDREN.includes(basename(p))) {
880
- return dirname(p);
876
+ function findStoreRoot(p2) {
877
+ if (isStoreRoot(p2))
878
+ return p2;
879
+ if (STORE_CHILDREN.includes(basename(p2))) {
880
+ return dirname(p2);
881
881
  }
882
- let cur = p;
882
+ let cur = p2;
883
883
  for (let depth = 0; depth < 8 && cur; depth++) {
884
884
  if (basename(cur) === ".cursor")
885
885
  return cur;
@@ -982,10 +982,10 @@ function canonicalize(value, ancestors, arrayElement) {
982
982
  if (prototype !== Object.prototype && prototype !== null) {
983
983
  return unsupportedCanonicalValue(value);
984
984
  }
985
- const object = value;
985
+ const object2 = value;
986
986
  const members = [];
987
- for (const key2 of Object.keys(object).sort(compareCodePoints2)) {
988
- const member = object[key2];
987
+ for (const key2 of Object.keys(object2).sort(compareCodePoints2)) {
988
+ const member = object2[key2];
989
989
  if (member === void 0)
990
990
  continue;
991
991
  members.push(`${JSON.stringify(key2)}:${canonicalize(member, ancestors, false)}`);
@@ -3270,7 +3270,7 @@ var init_database = __esm({
3270
3270
  import { chmodSync, closeSync, constants, fchmodSync, fstatSync, fsyncSync, lstatSync, mkdtempSync, openSync, readFileSync as readFileSync2, readlinkSync, readdirSync as readdirSync2, realpathSync, rmdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";
3271
3271
  import { tmpdir } from "node:os";
3272
3272
  import { basename as basename2, isAbsolute, join as join2, relative, resolve, sep } from "node:path";
3273
- import { performance as performance2 } from "node:perf_hooks";
3273
+ import { performance } from "node:perf_hooks";
3274
3274
  function errnoCode(error) {
3275
3275
  return error instanceof Error && "code" in error ? String(error.code) : void 0;
3276
3276
  }
@@ -3720,7 +3720,7 @@ var init_private_temp = __esm({
3720
3720
  };
3721
3721
  IS_PERMISSION_AWARE_POSIX = process.platform !== "win32";
3722
3722
  CURRENT_UID = typeof process.getuid === "function" ? process.getuid() : void 0;
3723
- FALLBACK_CURRENT_PROCESS_TOKEN = `process:${process.pid}:${Math.trunc(performance2.timeOrigin * 1e3)}`;
3723
+ FALLBACK_CURRENT_PROCESS_TOKEN = `process:${process.pid}:${Math.trunc(performance.timeOrigin * 1e3)}`;
3724
3724
  activeWorkspaces = /* @__PURE__ */ new Set();
3725
3725
  installedSignalHandlers = /* @__PURE__ */ new Map();
3726
3726
  handlingSignal = false;
@@ -7983,9 +7983,9 @@ function readMessages(db, rootId, budget, failureOutcome, onDiagnostic, signal)
7983
7983
  };
7984
7984
  walk(rootId);
7985
7985
  const toolResults = { byId: /* @__PURE__ */ new Map(), usedIds: /* @__PURE__ */ new Set() };
7986
- for (const { object } of reachableLeaves) {
7986
+ for (const { object: object2 } of reachableLeaves) {
7987
7987
  throwIfAborted4(signal);
7988
- for (const [callId, stored] of extractToolResults(object)) {
7988
+ for (const [callId, stored] of extractToolResults(object2)) {
7989
7989
  toolResults.byId.set(callId, stored);
7990
7990
  }
7991
7991
  }
@@ -7993,8 +7993,8 @@ function readMessages(db, rootId, budget, failureOutcome, onDiagnostic, signal)
7993
7993
  let encounteredUnkeyedToolResult = false;
7994
7994
  for (let traversalOrdinal = 0; traversalOrdinal < reachableLeaves.length; traversalOrdinal++) {
7995
7995
  throwIfAborted4(signal);
7996
- const { hash, object } = reachableLeaves[traversalOrdinal];
7997
- const leaf = classifyLeaf(object, toolResults);
7996
+ const { hash, object: object2 } = reachableLeaves[traversalOrdinal];
7997
+ const leaf = classifyLeaf(object2, toolResults);
7998
7998
  rawContentBlockEvidence.push(...leaf.rawContentBlocks);
7999
7999
  if (leaf.kind === "message") {
8000
8000
  messages.push(leaf.message);
@@ -17695,8 +17695,8 @@ function splitOriginalSourceLines(content) {
17695
17695
  const lines = content.split("\n");
17696
17696
  return lines.map((line, index) => index < lines.length - 1 && line.endsWith("\r") ? line.slice(0, -1) : line);
17697
17697
  }
17698
- function hasOwn(object, key2) {
17699
- return object !== void 0 && Object.prototype.hasOwnProperty.call(object, key2);
17698
+ function hasOwn(object2, key2) {
17699
+ return object2 !== void 0 && Object.prototype.hasOwnProperty.call(object2, key2);
17700
17700
  }
17701
17701
  function unwrapPublicReadContext(value) {
17702
17702
  const issued = publicReadContexts.get(value);
@@ -18517,33 +18517,132 @@ var init_lib = __esm({
18517
18517
  // src/harness/cursor/worker.ts
18518
18518
  import { parentPort, workerData } from "node:worker_threads";
18519
18519
 
18520
+ // src/theme.ts
18521
+ import * as p from "@clack/prompts";
18522
+ var esc = (code) => `\x1B[${code}m`;
18523
+ var reset = esc("0");
18524
+ var LIME = "163;230;53";
18525
+ var YELLOW = "250;204;21";
18526
+ var RED = "248;113;113";
18527
+ var MUTED = "120;120;120";
18528
+ var lime = (s) => `${esc(`38;2;${LIME}`)}${s}${reset}`;
18529
+ var yellow = (s) => `${esc(`38;2;${YELLOW}`)}${s}${reset}`;
18530
+ var red = (s) => `${esc(`38;2;${RED}`)}${s}${reset}`;
18531
+ var dim = (s) => `${esc(`38;2;${MUTED}`)}${s}${reset}`;
18532
+ var bold = (s) => `${esc("1")}${s}${reset}`;
18533
+ var BAR = `${esc(`38;2;${MUTED}`)}\u2502${reset}`;
18534
+
18520
18535
  // src/trace.ts
18536
+ var levelLabels = {
18537
+ info: "INFO ",
18538
+ success: " OK ",
18539
+ warn: "WARN ",
18540
+ error: "ERROR"
18541
+ };
18542
+ var levelColors = { info: bold, success: lime, warn: yellow, error: red };
18521
18543
  var sink = null;
18522
18544
  var startedAtMs = 0;
18523
- var stderrSink = (line) => {
18524
- process.stderr.write(`${line}
18545
+ var clock = () => Date.now();
18546
+ var colored = false;
18547
+ var columns;
18548
+ var stderrSink = (line) => process.stderr.write(`${line}
18525
18549
  `);
18526
- };
18527
- function enableTrace(write = stderrSink, startedAt = Date.now()) {
18550
+ function enableTrace(write = stderrSink, startedAt = Date.now(), options = {}) {
18528
18551
  sink = write;
18552
+ columns = options.columns ?? (process.stderr.isTTY ? process.stderr.columns : void 0);
18553
+ clock = options.now ?? (() => Date.now());
18529
18554
  startedAtMs = startedAt;
18555
+ colored = options.color ?? (Boolean(process.stderr.isTTY) && process.env.NO_COLOR === void 0 && process.env.TERM !== "dumb");
18530
18556
  }
18531
- function elapsedLabel() {
18532
- const seconds = (Date.now() - startedAtMs) / 1e3;
18533
- return `+${seconds.toFixed(seconds < 10 ? 2 : 1)}s`;
18534
- }
18535
- function trace(message) {
18557
+ function trace(message, level = "info") {
18536
18558
  if (!sink) return;
18537
- sink(`[aistack ${elapsedLabel().padStart(7)}] ${message}`);
18559
+ const seconds = Math.max(0, (clock() - startedAtMs) / 1e3);
18560
+ const time = `+${seconds.toFixed(2)}s`.padStart(10);
18561
+ const prefix = `[aistack ${time}]`;
18562
+ const label = levelLabels[level];
18563
+ const width = columns ? Math.max(16, columns - prefix.length - 7) : void 0;
18564
+ const lines = message.split(/\r?\n/).flatMap((line) => {
18565
+ if (!width) return [line];
18566
+ const result = [];
18567
+ let rest = line;
18568
+ while (rest.length > width) {
18569
+ const space = rest.lastIndexOf(" ", width);
18570
+ const cut = space > 0 ? space : width;
18571
+ result.push(rest.slice(0, cut));
18572
+ rest = rest.slice(cut).trimStart();
18573
+ }
18574
+ return [...result, rest];
18575
+ });
18576
+ for (const [index, line] of lines.entries()) {
18577
+ const head = index === 0 ? `${prefix} ${label} ` : " ".repeat(prefix.length + 7);
18578
+ const styledHead = index === 0 && colored ? `${dim(prefix)} ${levelColors[level](label)} ` : head;
18579
+ sink(
18580
+ `${styledHead}${colored && (level === "error" || level === "warn") ? levelColors[level](line) : line}`
18581
+ );
18582
+ }
18538
18583
  }
18539
18584
  function traceTimer(label) {
18540
18585
  if (!sink) return () => {
18541
18586
  };
18542
- const started = performance.now();
18543
- return (note) => {
18544
- const ms = Math.round(performance.now() - started);
18545
- trace(`${label} \xB7 ${ms} ms${note ? ` \xB7 ${note}` : ""}`);
18546
- };
18587
+ const started = clock();
18588
+ return (note, level = "success") => trace(
18589
+ `${label} \xB7 ${Math.round(clock() - started)} ms${note ? ` \xB7 ${note}` : ""}`,
18590
+ level
18591
+ );
18592
+ }
18593
+ var knownNames = /* @__PURE__ */ new Set([
18594
+ "Error",
18595
+ "TypeError",
18596
+ "RangeError",
18597
+ "SyntaxError",
18598
+ "ReferenceError",
18599
+ "URIError",
18600
+ "EvalError",
18601
+ "AggregateError",
18602
+ "AbortError",
18603
+ "TimeoutError"
18604
+ ]);
18605
+ var object = (value) => value !== null && typeof value === "object" ? value : null;
18606
+ function traceErrorCode(error) {
18607
+ const value = object(error);
18608
+ const code = value?.code;
18609
+ if (typeof code === "string" && /^[A-Z][A-Z0-9_]{0,63}$/.test(code))
18610
+ return code;
18611
+ return typeof value?.name === "string" && knownNames.has(value.name) ? value.name : "unknown";
18612
+ }
18613
+ function traceError(operation, error, level = "error") {
18614
+ if (!sink) return;
18615
+ const seen = /* @__PURE__ */ new Set();
18616
+ function describe(value, depth = 0) {
18617
+ if (depth >= 4 || seen.has(value)) return "[cause omitted]";
18618
+ seen.add(value);
18619
+ const row = object(value);
18620
+ const code = traceErrorCode(value);
18621
+ const name = row?.name;
18622
+ const fields = typeof name === "string" && knownNames.has(name) && name !== code ? [name, code] : [code];
18623
+ const details = object(row?.details);
18624
+ if (code === "SOURCE_LIMIT_EXCEEDED" && details) {
18625
+ if (typeof details.bound === "string" && /^(sqlite|jsonl|zip)-[a-z-]{1,32}$/.test(details.bound))
18626
+ fields.push(details.bound);
18627
+ for (const key2 of ["limit", "observedAtLeast"]) {
18628
+ const n = details[key2];
18629
+ if (typeof n === "number" && Number.isSafeInteger(n) && n >= 0)
18630
+ fields.push(`${key2}=${n}`);
18631
+ }
18632
+ }
18633
+ for (const key2 of ["status", "statusCode", "errno", "errcode", "code"]) {
18634
+ const n = row?.[key2];
18635
+ if (typeof n === "number" && Number.isSafeInteger(n))
18636
+ fields.push(`${key2}=${n}`);
18637
+ }
18638
+ if (row?.cause !== void 0)
18639
+ fields.push(`cause: ${describe(row.cause, depth + 1)}`);
18640
+ if (value instanceof AggregateError)
18641
+ for (const child of value.errors.slice(0, 4))
18642
+ fields.push(`cause: ${describe(child, depth + 1)}`);
18643
+ return fields.join(" \xB7 ");
18644
+ }
18645
+ trace(`${operation} failed \xB7 ${describe(error)}`, level);
18547
18646
  }
18548
18647
 
18549
18648
  // src/harness/cursor/local.ts
@@ -18702,9 +18801,9 @@ var Pricer = class {
18702
18801
  */
18703
18802
  priceAt(modelKey, atMs) {
18704
18803
  if (atMs === null) return null;
18705
- for (const p of this.periodsFor(modelKey)) {
18706
- if ((p.from === null || atMs >= p.from) && (p.to === null || atMs < p.to)) {
18707
- return p;
18804
+ for (const p2 of this.periodsFor(modelKey)) {
18805
+ if ((p2.from === null || atMs >= p2.from) && (p2.to === null || atMs < p2.to)) {
18806
+ return p2;
18708
18807
  }
18709
18808
  }
18710
18809
  return null;
@@ -18712,7 +18811,7 @@ var Pricer = class {
18712
18811
  /** Every rate that applies anywhere inside `[fromMs, toMs]`. */
18713
18812
  periodsInWindow(modelKey, fromMs, toMs) {
18714
18813
  return this.periodsFor(modelKey).filter(
18715
- (p) => (p.from === null || p.from <= toMs) && (p.to === null || p.to > fromMs)
18814
+ (p2) => (p2.from === null || p2.from <= toMs) && (p2.to === null || p2.to > fromMs)
18716
18815
  );
18717
18816
  }
18718
18817
  /**
@@ -18841,15 +18940,15 @@ var PRICES = {
18841
18940
  function bundledPriceTable() {
18842
18941
  const rows = [];
18843
18942
  for (const [modelSlug, entry] of Object.entries(PRICES)) {
18844
- for (const p of entry.periods) {
18943
+ for (const p2 of entry.periods) {
18845
18944
  rows.push({
18846
18945
  modelSlug,
18847
- from: p.from ?? 0,
18848
- input: p.input,
18849
- output: p.output,
18850
- cacheRead: p.input * entry.cache.read,
18851
- cacheWrite5m: p.input * entry.cache.write5m,
18852
- cacheWrite1h: p.input * entry.cache.write1h,
18946
+ from: p2.from ?? 0,
18947
+ input: p2.input,
18948
+ output: p2.output,
18949
+ cacheRead: p2.input * entry.cache.read,
18950
+ cacheWrite5m: p2.input * entry.cache.write5m,
18951
+ cacheWrite1h: p2.input * entry.cache.write1h,
18853
18952
  source: entry.table,
18854
18953
  vendor: entry.vendor
18855
18954
  });
@@ -19016,7 +19115,8 @@ async function sourceStamp(root) {
19016
19115
  );
19017
19116
  return values.join("/");
19018
19117
  }
19019
- async function readLocalOnce(root, before, onProgress) {
19118
+ async function readLocalOnce(root, before, onProgress, sourceReadLimits) {
19119
+ before ??= await sourceStamp(root);
19020
19120
  const stats = emptyScanStats();
19021
19121
  const out = { sessions: [], complete: true, stats };
19022
19122
  if (!await hasLocalSource(root)) {
@@ -19026,17 +19126,19 @@ async function readLocalOnce(root, before, onProgress) {
19026
19126
  trace(`cursor \xB7 global database ${await globalDbSize(root)}`);
19027
19127
  const readDone = traceTimer("cursor history read");
19028
19128
  let context;
19129
+ let retrySmallPage = false;
19029
19130
  try {
19030
19131
  const reader = await Promise.resolve().then(() => (init_lib(), lib_exports));
19031
19132
  const options = {
19032
19133
  dataPath: root,
19033
19134
  sqliteDriver: "node:sqlite",
19034
- onDiagnostic: () => {
19135
+ onDiagnostic: (diagnostic) => {
19136
+ traceError("cursor source diagnostic", diagnostic, "warn");
19035
19137
  out.complete = false;
19036
19138
  },
19037
19139
  signal: AbortSignal.timeout(12e4)
19038
19140
  };
19039
- context = reader.createSessionReadContext(options);
19141
+ context = reader.createSessionReadContext({ ...options, sourceReadLimits });
19040
19142
  const config = { ...options, readContext: context };
19041
19143
  let offset = 0;
19042
19144
  while (true) {
@@ -19053,17 +19155,28 @@ async function readLocalOnce(root, before, onProgress) {
19053
19155
  for (const summary of page.data) {
19054
19156
  stats.filesFound++;
19055
19157
  if (summary.resolutionState === "ambiguous") {
19158
+ trace(
19159
+ "cursor session resolution incomplete \xB7 ambiguous source",
19160
+ "warn"
19161
+ );
19056
19162
  out.complete = false;
19057
19163
  }
19058
19164
  try {
19059
19165
  const session = await reader.getSession(summary.id, config);
19060
- if (session.resolutionState !== "complete" || session.messages.some((m) => m.metadata?.corrupted))
19166
+ if (session.resolutionState !== "complete" || session.messages.some((m) => m.metadata?.corrupted)) {
19167
+ trace(
19168
+ "cursor session incomplete \xB7 unresolved or corrupted messages",
19169
+ "warn"
19170
+ );
19061
19171
  out.complete = false;
19172
+ }
19062
19173
  const tokens = await readTokenEvidence(root, session);
19063
19174
  out.sessions.push({ session, tokens });
19064
19175
  stats.filesRead++;
19065
19176
  onProgress?.(stats.filesRead, page.pagination.total);
19066
- } catch {
19177
+ } catch (error) {
19178
+ if (isPageByteLimit(error)) throw error;
19179
+ traceError("cursor history", error);
19067
19180
  out.complete = false;
19068
19181
  stats.filesUnreadable++;
19069
19182
  } finally {
@@ -19072,24 +19185,52 @@ async function readLocalOnce(root, before, onProgress) {
19072
19185
  }
19073
19186
  if (!page.pagination.hasMore) break;
19074
19187
  if (page.data.length === 0 || offset >= 1e5) {
19188
+ trace(
19189
+ "cursor listing incomplete \xB7 empty page or pagination limit",
19190
+ "warn"
19191
+ );
19075
19192
  out.complete = false;
19076
19193
  break;
19077
19194
  }
19078
19195
  offset += page.data.length;
19079
19196
  }
19080
- } catch {
19197
+ } catch (error) {
19198
+ traceError("cursor history", error);
19199
+ retrySmallPage = isPageByteLimit(error) && sourceReadLimits?.sqlitePageRows !== 1;
19200
+ stats.unreadableFiles.push({
19201
+ path: "history",
19202
+ reason: traceErrorCode(error)
19203
+ });
19081
19204
  out.complete = false;
19082
19205
  stats.filesUnreadable++;
19083
19206
  } finally {
19084
19207
  try {
19085
19208
  await context?.dispose();
19086
- } catch {
19209
+ } catch (error) {
19210
+ traceError("cursor reader disposal", error);
19087
19211
  out.complete = false;
19088
19212
  }
19089
19213
  }
19090
- if (before !== await sourceStamp(root)) out.complete = false;
19214
+ if (retrySmallPage) {
19215
+ readDone(
19216
+ "page byte limit reached; retrying with one SQLite row per page",
19217
+ "warn"
19218
+ );
19219
+ return readLocalOnce(root, before, onProgress, {
19220
+ ...sourceReadLimits,
19221
+ sqlitePageRows: 1
19222
+ });
19223
+ }
19224
+ if (before !== await sourceStamp(root)) {
19225
+ trace(
19226
+ "cursor history incomplete \xB7 database changed during the read",
19227
+ "warn"
19228
+ );
19229
+ out.complete = false;
19230
+ }
19091
19231
  readDone(
19092
- `${stats.filesRead}/${stats.filesFound} sessions read, ${stats.filesUnreadable} unreadable${out.complete ? "" : ", incomplete"}`
19232
+ `${stats.filesRead}/${stats.filesFound} sessions read, ${stats.filesUnreadable} unreadable${out.complete ? "" : ", incomplete"}`,
19233
+ out.complete ? "success" : "warn"
19093
19234
  );
19094
19235
  return out;
19095
19236
  }
@@ -19101,6 +19242,10 @@ async function globalDbSize(root) {
19101
19242
  return "absent";
19102
19243
  }
19103
19244
  }
19245
+ function isPageByteLimit(error) {
19246
+ const details = asObj(asObj(error)?.details);
19247
+ return traceErrorCode(error) === "SOURCE_LIMIT_EXCEEDED" && details?.sourceKind === "sqlite" && details.bound === "sqlite-page-bytes";
19248
+ }
19104
19249
 
19105
19250
  // src/harness/cursor/worker.ts
19106
19251
  var port = parentPort;
@@ -19114,6 +19259,9 @@ readLocalOnce(
19114
19259
  (files, total) => post({ kind: "progress", files, ...total !== void 0 ? { total } : {} })
19115
19260
  ).then(
19116
19261
  (read) => post({ kind: "result", read }),
19117
- () => post({ kind: "error" })
19262
+ (error) => {
19263
+ traceError("cursor worker history", error);
19264
+ post({ kind: "error" });
19265
+ }
19118
19266
  );
19119
19267
  //# sourceMappingURL=cursor-worker.js.map