@use-aistack/cli 0.16.7 → 0.16.8

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/index.js CHANGED
@@ -2586,11 +2586,11 @@ function isKeyValueStatement(sql) {
2586
2586
  function emit(context, operation, identity, adapter = "sqlite") {
2587
2587
  observeAdapterIo(context, { adapter, operation, ...identity });
2588
2588
  }
2589
- function openObservedDatabase(context, request2, open3) {
2589
+ function openObservedDatabase(context, request2, open4) {
2590
2590
  if (!context)
2591
- return open3();
2591
+ return open4();
2592
2592
  emit(context, "open", requestIdentity(request2));
2593
- return new ObservedDatabase(open3(), context, request2);
2593
+ return new ObservedDatabase(open4(), context, request2);
2594
2594
  }
2595
2595
  function observeDatabaseBackup(request2) {
2596
2596
  if (!request2.io)
@@ -4036,8 +4036,8 @@ var init_source_read_limits = __esm({
4036
4036
 
4037
4037
  // ../../node_modules/.pnpm/cursor-history@0.18.0_patch_hash=8c02b8ff8b7820637beb3f0d25856ca4f632932000105288ff64b66ffbbd8cf5/node_modules/cursor-history/dist/core/zip-stream.js
4038
4038
  import { createHash as createHash2 } from "node:crypto";
4039
- import { open, unlink } from "node:fs/promises";
4040
- import { Readable, Transform, Writable } from "node:stream";
4039
+ import { open as open2, unlink } from "node:fs/promises";
4040
+ import { Readable as Readable2, Transform, Writable } from "node:stream";
4041
4041
  import { pipeline } from "node:stream/promises";
4042
4042
  import { createInflateRaw } from "node:zlib";
4043
4043
  function zipEntryIoIdentity(name) {
@@ -4150,7 +4150,7 @@ function readHandleRange(handle, position, length, signal) {
4150
4150
  yield buffer.subarray(0, bytesRead);
4151
4151
  }
4152
4152
  }
4153
- return Readable.from(chunks(), { objectMode: false });
4153
+ return Readable2.from(chunks(), { objectMode: false });
4154
4154
  }
4155
4155
  function writeToHandle(handle) {
4156
4156
  let position = 0;
@@ -4540,7 +4540,7 @@ async function prepareZipFileInputs(inputs, options = {}) {
4540
4540
  for (const input of inputs) {
4541
4541
  throwIfAborted(options.signal);
4542
4542
  const normalized = validateWriteName(input.name, portableNames);
4543
- const handle = await open(input.sourcePath, "r");
4543
+ const handle = await open2(input.sourcePath, "r");
4544
4544
  try {
4545
4545
  const before = await handle.stat({ bigint: true });
4546
4546
  if (!before.isFile())
@@ -4701,7 +4701,7 @@ async function writeBoundedZipArchive(destinationPath, inputs, options = {}) {
4701
4701
  const limits = resolveSourceReadLimits(options.sourceReadLimits);
4702
4702
  throwIfAborted(options.signal);
4703
4703
  const plan = planWriteEntries(inputs, limits);
4704
- const destination = await open(destinationPath, "wx", 384);
4704
+ const destination = await open2(destinationPath, "wx", 384);
4705
4705
  try {
4706
4706
  await destination.chmod(384);
4707
4707
  let position = 0;
@@ -4723,7 +4723,7 @@ async function writeBoundedZipArchive(destinationPath, inputs, options = {}) {
4723
4723
  }
4724
4724
  if (!entry.sourcePath || !entry.checksum)
4725
4725
  throw formatError("Prepared ZIP input is incomplete.");
4726
- const source = await open(entry.sourcePath, "r");
4726
+ const source = await open2(entry.sourcePath, "r");
4727
4727
  try {
4728
4728
  const metadata = await source.stat({ bigint: true });
4729
4729
  if (!metadata.isFile() || metadata.size !== BigInt(entry.size)) {
@@ -4973,7 +4973,7 @@ var init_zip_stream = __esm({
4973
4973
  resourceClass: "backup-central-directory"
4974
4974
  });
4975
4975
  }
4976
- const handle = await open(path14, "r");
4976
+ const handle = await open2(path14, "r");
4977
4977
  try {
4978
4978
  if (options.io) {
4979
4979
  observeAdapterIo(options.io, {
@@ -5127,7 +5127,7 @@ var init_zip_stream = __esm({
5127
5127
  const entry = this.getEntry(name);
5128
5128
  if (!entry)
5129
5129
  throw formatError(`ZIP entry was not found: ${name}`);
5130
- const destination = await open(destinationPath, "r+");
5130
+ const destination = await open2(destinationPath, "r+");
5131
5131
  try {
5132
5132
  await destination.chmod(384);
5133
5133
  await destination.truncate(0);
@@ -5144,7 +5144,7 @@ var init_zip_stream = __esm({
5144
5144
  const entry = this.getEntry(name);
5145
5145
  if (!entry)
5146
5146
  throw formatError(`ZIP entry was not found: ${name}`);
5147
- const destination = await open(destinationPath, "r+");
5147
+ const destination = await open2(destinationPath, "r+");
5148
5148
  try {
5149
5149
  await destination.chmod(384);
5150
5150
  await destination.truncate(0);
@@ -18891,7 +18891,7 @@ function apiEquivalentCost(modelKey, t, atMs) {
18891
18891
  }
18892
18892
 
18893
18893
  // src/version.ts
18894
- var CLI_VERSION = true ? "0.16.7" : "0.0.0-dev";
18894
+ var CLI_VERSION = true ? "0.16.8" : "0.0.0-dev";
18895
18895
 
18896
18896
  // src/api.ts
18897
18897
  var BASE_URL = process.env.AISTACK_URL || "https://aistack.to";
@@ -24010,9 +24010,10 @@ function noteConfiguredMcpServers(agg, serverNames) {
24010
24010
 
24011
24011
  // src/harness/codex/scan.ts
24012
24012
  import { readFileSync as readFileSync6 } from "node:fs";
24013
- import { readdir as readdir3, realpath as realpath2, stat as stat3 } from "node:fs/promises";
24013
+ import { open, readdir as readdir3, realpath as realpath2, stat as stat3 } from "node:fs/promises";
24014
24014
  import { homedir as homedir7 } from "node:os";
24015
24015
  import path3 from "node:path";
24016
+ import { Readable } from "node:stream";
24016
24017
  import * as zlib from "node:zlib";
24017
24018
  import { parse as parseToml2 } from "smol-toml";
24018
24019
  function codexHome() {
@@ -24040,7 +24041,8 @@ async function* walkRollouts(dir) {
24040
24041
  else if (e.isFile() && isRolloutFile(e.name)) yield full;
24041
24042
  }
24042
24043
  }
24043
- var zstdDecompress = typeof zlib.zstdDecompressSync === "function" ? (buf) => zlib.zstdDecompressSync(buf) : null;
24044
+ var createZstdDecompress2 = typeof zlib.createZstdDecompress === "function" ? zlib.createZstdDecompress : null;
24045
+ var MAX_LINE_BYTES = 64 * 1024 * 1024;
24044
24046
  async function scan2(agg, opts = {}) {
24045
24047
  const stats = emptyScanStats();
24046
24048
  const visited = /* @__PURE__ */ new Set();
@@ -24077,7 +24079,7 @@ async function scan2(agg, opts = {}) {
24077
24079
  agg.files++;
24078
24080
  stats.filesRead++;
24079
24081
  if (opts.onProgress && agg.files % 20 === 0) opts.onProgress(agg.files);
24080
- const outcome = ingestWithRetry(agg, file, opts);
24082
+ const outcome = await ingestWithRetry(agg, file, opts);
24081
24083
  if (!outcome.ok) {
24082
24084
  stats.filesUnreadable++;
24083
24085
  stats.filesRead--;
@@ -24113,14 +24115,14 @@ function errorClass(e) {
24113
24115
  return e instanceof Error ? e.constructor.name : "unknown";
24114
24116
  }
24115
24117
  var readError = (reason) => Object.assign(new Error(reason), { code: reason });
24116
- function ingestWithRetry(agg, file, opts) {
24118
+ async function ingestWithRetry(agg, file, opts) {
24117
24119
  try {
24118
- return ingestFile2(agg, file, opts);
24120
+ return await ingestFile2(agg, file, opts);
24119
24121
  } catch (e) {
24120
24122
  traceError("codex rollout read", e);
24121
24123
  if (errorClass(e) === "ENOENT" && !file.endsWith(".zst")) {
24122
24124
  try {
24123
- return ingestFile2(agg, `${file}.zst`, opts);
24125
+ return await ingestFile2(agg, `${file}.zst`, opts);
24124
24126
  } catch (e2) {
24125
24127
  traceError("codex compressed rollout retry", e2);
24126
24128
  return { ok: false, reason: errorClass(e2) };
@@ -24129,56 +24131,125 @@ function ingestWithRetry(agg, file, opts) {
24129
24131
  return { ok: false, reason: errorClass(e) };
24130
24132
  }
24131
24133
  }
24132
- function ingestFile2(agg, file, opts) {
24133
- const readFile4 = opts.readFileImpl ?? readFileSync6;
24134
- const raw = readFile4(file);
24135
- let bytes = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
24136
- if (file.endsWith(".zst")) {
24137
- if (zstdDecompress === null) throw readError("zstd-unsupported");
24138
- try {
24139
- bytes = zstdDecompress(bytes);
24140
- } catch (error) {
24141
- traceError("codex zstd decompression", error);
24142
- throw readError("zstd-corrupt");
24143
- }
24134
+ async function ingestFile2(agg, file, opts) {
24135
+ const compressed = file.endsWith(".zst");
24136
+ if (compressed && !createZstdDecompress2) throw readError("zstd-unsupported");
24137
+ const handle = await open(file, "r");
24138
+ try {
24139
+ const { size } = await handle.stat();
24140
+ let nonEmptyLines = 0;
24141
+ let parseErrors = 0;
24142
+ async function* records(count2) {
24143
+ if (size === 0) return;
24144
+ async function* chunks() {
24145
+ for (let position = 0; position < size; ) {
24146
+ const buffer = Buffer.allocUnsafe(
24147
+ Math.min(opts.chunkBytes ?? 64 * 1024, size - position)
24148
+ );
24149
+ const { bytesRead } = await handle.read(
24150
+ buffer,
24151
+ 0,
24152
+ buffer.length,
24153
+ position
24154
+ );
24155
+ if (bytesRead === 0) throw readError("rollout-truncated");
24156
+ position += bytesRead;
24157
+ yield buffer.subarray(0, bytesRead);
24158
+ }
24159
+ }
24160
+ const source = opts.readStreamImpl ? opts.readStreamImpl(file, {
24161
+ start: 0,
24162
+ end: size - 1,
24163
+ highWaterMark: opts.chunkBytes ?? 64 * 1024
24164
+ }) : Readable.from(chunks(), { objectMode: false });
24165
+ let sourceError;
24166
+ const decoder = compressed ? createZstdDecompress2?.() : void 0;
24167
+ source.on("error", (error) => {
24168
+ sourceError = error;
24169
+ decoder?.destroy(error);
24170
+ });
24171
+ const stream = decoder ? source.pipe(decoder) : source;
24172
+ try {
24173
+ for await (const line of boundedLines(
24174
+ stream,
24175
+ opts.maxLineBytes ?? MAX_LINE_BYTES
24176
+ )) {
24177
+ if (line === "") continue;
24178
+ if (count2) nonEmptyLines++;
24179
+ let record;
24180
+ try {
24181
+ if (line === null) throw readError("record-too-large");
24182
+ record = JSON.parse(line);
24183
+ } catch (error) {
24184
+ if (count2) {
24185
+ if (parseErrors === 0)
24186
+ traceError("codex rollout JSON (first failure)", error, "warn");
24187
+ parseErrors++;
24188
+ }
24189
+ continue;
24190
+ }
24191
+ yield record;
24192
+ }
24193
+ } catch (error) {
24194
+ if (decoder && !sourceError) {
24195
+ traceError("codex zstd decompression", error);
24196
+ throw readError("zstd-corrupt");
24197
+ }
24198
+ throw sourceError ?? error;
24199
+ } finally {
24200
+ source.destroy();
24201
+ decoder?.destroy();
24202
+ }
24203
+ }
24204
+ const verdict = await classifyRollout(records(true));
24205
+ if (!verdict.genuine) return { ok: true, ...verdict };
24206
+ agg.lines += nonEmptyLines;
24207
+ agg.parseErrors += parseErrors;
24208
+ const state = createFileState();
24209
+ for await (const rec of records(false))
24210
+ ingestLine(agg, rec, state, opts.sinceMs);
24211
+ return { ok: true, genuine: true };
24212
+ } finally {
24213
+ await handle.close();
24144
24214
  }
24145
- let nonEmptyLines = 0;
24146
- let parseErrors = 0;
24147
- function* records() {
24148
- for (let start = 0; start < bytes.length; ) {
24215
+ }
24216
+ async function* boundedLines(stream, limit) {
24217
+ let parts = [];
24218
+ let length = 0;
24219
+ let oversized = false;
24220
+ for await (const chunk of stream) {
24221
+ const bytes = chunk;
24222
+ let start = 0;
24223
+ while (start < bytes.length) {
24149
24224
  const newline = bytes.indexOf(10, start);
24150
24225
  const end = newline < 0 ? bytes.length : newline;
24151
- const line = bytes.subarray(start, end).toString("utf8");
24152
- start = end + 1;
24153
- if (!line) continue;
24154
- nonEmptyLines++;
24155
- let record;
24156
- try {
24157
- record = JSON.parse(line);
24158
- } catch (error) {
24159
- if (parseErrors === 0)
24160
- traceError("codex rollout JSON (first failure)", error, "warn");
24161
- parseErrors++;
24162
- continue;
24226
+ const part = bytes.subarray(start, end);
24227
+ if (!oversized) {
24228
+ length += part.length;
24229
+ if (length > limit) {
24230
+ oversized = true;
24231
+ parts = [];
24232
+ } else parts.push(part);
24233
+ }
24234
+ if (newline >= 0) {
24235
+ yield oversized ? null : Buffer.concat(parts, length).toString("utf8");
24236
+ parts = [];
24237
+ length = 0;
24238
+ oversized = false;
24163
24239
  }
24164
- yield record;
24240
+ start = end + 1;
24165
24241
  }
24166
24242
  }
24167
- const verdict = classifyRollout(records());
24168
- if (!verdict.genuine) return { ok: true, ...verdict };
24169
- agg.lines += nonEmptyLines;
24170
- agg.parseErrors += parseErrors;
24171
- const state = createFileState();
24172
- for (const rec of records()) ingestLine(agg, rec, state, opts.sinceMs);
24173
- return { ok: true, genuine: true };
24243
+ if (oversized || length > 0)
24244
+ yield oversized ? null : Buffer.concat(parts, length).toString("utf8");
24174
24245
  }
24175
- function classifyRollout(records) {
24246
+ async function classifyRollout(records) {
24176
24247
  let originator = null;
24177
24248
  let sawTurnContext = false;
24178
24249
  let sawTokenCount = false;
24179
24250
  let genuine = true;
24180
24251
  let count2 = 0;
24181
- for (const raw of records) {
24252
+ for await (const raw of records) {
24182
24253
  const rec = asObj(raw);
24183
24254
  const type = rec ? asStr(rec.type) : null;
24184
24255
  const payload = rec ? asObj(rec.payload) : null;
@@ -24574,6 +24645,8 @@ async function readLocalOnce(root, before, onProgress, sourceReadLimits) {
24574
24645
  let unresolved = 0;
24575
24646
  let corrupted = 0;
24576
24647
  let ambiguous = 0;
24648
+ let stage = "reader setup";
24649
+ const signal = AbortSignal.timeout(12e4);
24577
24650
  try {
24578
24651
  const reader = await Promise.resolve().then(() => (init_lib(), lib_exports));
24579
24652
  const options = {
@@ -24583,7 +24656,7 @@ async function readLocalOnce(root, before, onProgress, sourceReadLimits) {
24583
24656
  traceError("cursor source diagnostic", diagnostic, "warn");
24584
24657
  out.complete = false;
24585
24658
  },
24586
- signal: AbortSignal.timeout(12e4)
24659
+ signal
24587
24660
  };
24588
24661
  context = reader.createSessionReadContext({ ...options, sourceReadLimits });
24589
24662
  const config = { ...options, readContext: context };
@@ -24592,6 +24665,7 @@ async function readLocalOnce(root, before, onProgress, sourceReadLimits) {
24592
24665
  const pageDone = traceTimer(
24593
24666
  offset === 0 ? "cursor session listing" : "cursor session page"
24594
24667
  );
24668
+ stage = "session listing";
24595
24669
  const page = await reader.listSessionSummaries({
24596
24670
  ...config,
24597
24671
  offset,
@@ -24605,6 +24679,7 @@ async function readLocalOnce(root, before, onProgress, sourceReadLimits) {
24605
24679
  out.complete = false;
24606
24680
  }
24607
24681
  try {
24682
+ stage = "session read";
24608
24683
  const session = await reader.getSession(summary.id, config);
24609
24684
  if (session.resolutionState !== "complete" || session.messages.some((m) => m.metadata?.corrupted)) {
24610
24685
  if (session.resolutionState !== "complete") unresolved++;
@@ -24612,6 +24687,7 @@ async function readLocalOnce(root, before, onProgress, sourceReadLimits) {
24612
24687
  corrupted++;
24613
24688
  out.complete = false;
24614
24689
  }
24690
+ stage = "token evidence";
24615
24691
  const tokens = await readTokenEvidence(root, session);
24616
24692
  out.sessions.push({ session, tokens });
24617
24693
  stats.filesRead++;
@@ -24619,7 +24695,7 @@ async function readLocalOnce(root, before, onProgress, sourceReadLimits) {
24619
24695
  } catch (error) {
24620
24696
  if (isPageByteLimit(error)) throw error;
24621
24697
  if (traceErrorCode(error) === "SESSION_AMBIGUOUS") ambiguous++;
24622
- else traceError("cursor session skipped", error, "warn");
24698
+ else traceError(`cursor ${stage}`, error, "warn");
24623
24699
  out.complete = false;
24624
24700
  stats.filesUnreadable++;
24625
24701
  } finally {
@@ -24638,7 +24714,9 @@ async function readLocalOnce(root, before, onProgress, sourceReadLimits) {
24638
24714
  offset += page.data.length;
24639
24715
  }
24640
24716
  } catch (error) {
24641
- traceError("cursor history", error);
24717
+ traceError(`cursor ${stage}`, error);
24718
+ if (signal.aborted)
24719
+ traceError("cursor read deadline", signal.reason, "warn");
24642
24720
  retrySmallPage = isPageByteLimit(error) && sourceReadLimits?.sqlitePageRows !== 1;
24643
24721
  stats.unreadableFiles.push({
24644
24722
  path: "history",
@@ -24764,6 +24842,23 @@ function apiContribution(value) {
24764
24842
  };
24765
24843
  }
24766
24844
  async function fetchWindow(account, from, to, fetchImpl = fetch) {
24845
+ const budget = { requests: 0, signal: AbortSignal.timeout(3e5) };
24846
+ async function read3(start, end) {
24847
+ try {
24848
+ return await fetchPages(account, start, end, fetchImpl, budget);
24849
+ } catch (error) {
24850
+ if (traceErrorCode(error) !== "CURSOR_PAGE_LIMIT" || end - start <= 1)
24851
+ throw error;
24852
+ const middle = start + Math.floor((end - start) / 2);
24853
+ trace("cursor account usage \xB7 splitting capped date window");
24854
+ const left = await read3(start, middle);
24855
+ const right = await read3(middle, end);
24856
+ return [...left, ...right];
24857
+ }
24858
+ }
24859
+ return read3(from, to);
24860
+ }
24861
+ async function fetchPages(account, from, to, fetchImpl, budget) {
24767
24862
  const out = [];
24768
24863
  const pages = /* @__PURE__ */ new Set();
24769
24864
  const eventIds = /* @__PURE__ */ new Set();
@@ -24771,12 +24866,17 @@ async function fetchWindow(account, from, to, fetchImpl = fetch) {
24771
24866
  let retrieved = 0;
24772
24867
  const pageSize = 100;
24773
24868
  for (let page = 1; page <= 100; page++) {
24869
+ budget.signal.throwIfAborted();
24870
+ if (++budget.requests > 1e3)
24871
+ throw Object.assign(new Error("Cursor request budget"), {
24872
+ code: "CURSOR_REQUEST_LIMIT"
24873
+ });
24774
24874
  const response = await fetchImpl(
24775
24875
  "https://cursor.com/api/dashboard/get-filtered-usage-events",
24776
24876
  {
24777
24877
  method: "POST",
24778
24878
  redirect: "error",
24779
- signal: AbortSignal.timeout(15e3),
24879
+ signal: AbortSignal.any([budget.signal, AbortSignal.timeout(15e3)]),
24780
24880
  headers: {
24781
24881
  "Content-Type": "application/json",
24782
24882
  Origin: "https://cursor.com",
@@ -24811,6 +24911,10 @@ async function fetchWindow(account, from, to, fetchImpl = fetch) {
24811
24911
  code: "CURSOR_PAGE_COUNT_CHANGED"
24812
24912
  });
24813
24913
  total = reported;
24914
+ if (total > 100 * pageSize)
24915
+ throw Object.assign(new Error("Cursor page limit"), {
24916
+ code: "CURSOR_PAGE_LIMIT"
24917
+ });
24814
24918
  }
24815
24919
  if (events.length) {
24816
24920
  const key2 = digest(JSON.stringify(events));
@@ -24901,26 +25005,36 @@ async function saveCache(file, value) {
24901
25005
  await writeFile(temporary, JSON.stringify(value), { mode: 384 });
24902
25006
  await rename(temporary, file);
24903
25007
  }
25008
+ var REFRESH_MS = 3e5;
24904
25009
  var WINDOW_MS = 30 * 864e5;
24905
25010
  async function refreshAccount(input) {
24906
25011
  const { cache, account, now, sessionIds } = input;
24907
- if (!account) return cache;
25012
+ if (!account || !sessionIds.size) return cache;
25013
+ const state = input.state;
25014
+ if (state && state.account !== account.scope) {
25015
+ state.account = account.scope;
25016
+ state.windows = {};
25017
+ state.failedAt = void 0;
25018
+ }
24908
25019
  const changed = cache.account !== account.scope;
24909
25020
  const next = {
24910
25021
  ...cache,
24911
25022
  account: account.scope,
24912
- windows: changed ? {} : { ...cache.windows }
25023
+ windows: { ...changed ? {} : cache.windows, ...state?.windows }
24913
25024
  };
25025
+ if (state?.failedAt !== void 0 && now - state.failedAt < REFRESH_MS)
25026
+ return next;
24914
25027
  for (let from = Math.floor(input.sinceMs / WINDOW_MS) * WINDOW_MS; from <= now; from += WINDOW_MS) {
24915
25028
  const to = Math.min(from + WINDOW_MS, now + 1);
24916
25029
  const key2 = String(from);
24917
25030
  const previous = next.windows[key2];
24918
- if (previous && now - previous.fetchedAt < 3e5) continue;
25031
+ if (previous && now - previous.fetchedAt < REFRESH_MS) continue;
24919
25032
  try {
24920
25033
  const events = (await fetchWindow(account, from, to, input.fetchImpl)).filter((e) => sessionIds.has(e.session));
24921
25034
  if (previous?.events.length && events.length === 0 && to <= now) continue;
24922
25035
  next.windows[key2] = { from, to, fetchedAt: now, events };
24923
25036
  } catch (error) {
25037
+ if (state) state.failedAt = now;
24924
25038
  traceError(
24925
25039
  "cursor account usage refresh (using local and previously cached usage)",
24926
25040
  error,
@@ -24929,6 +25043,7 @@ async function refreshAccount(input) {
24929
25043
  break;
24930
25044
  }
24931
25045
  }
25046
+ if (state) state.windows = next.windows;
24932
25047
  return next;
24933
25048
  }
24934
25049
  function cachedEvents(cache, sessionIds) {
@@ -25083,6 +25198,7 @@ function projectHistory(options) {
25083
25198
  }
25084
25199
 
25085
25200
  // src/harness/cursor/scan.ts
25201
+ var accountRefreshes = /* @__PURE__ */ new Map();
25086
25202
  async function scan3(options) {
25087
25203
  const root = options.root ?? dataPath();
25088
25204
  const now = options.now ?? Date.now();
@@ -25104,14 +25220,21 @@ async function scan3(options) {
25104
25220
  );
25105
25221
  complete = false;
25106
25222
  }
25107
- const account = await (options.accountImpl ?? existingAccount)(root);
25223
+ const account = ids.size ? await (options.accountImpl ?? existingAccount)(root) : null;
25224
+ const refreshKey = JSON.stringify([root, storeRoot(), file]);
25225
+ let refreshState = accountRefreshes.get(refreshKey);
25226
+ if (!refreshState) {
25227
+ refreshState = {};
25228
+ accountRefreshes.set(refreshKey, refreshState);
25229
+ }
25108
25230
  const cache = await refreshAccount({
25109
25231
  cache: loaded.value,
25110
25232
  account,
25111
25233
  sinceMs: options.sinceMs,
25112
25234
  now,
25113
25235
  sessionIds: ids,
25114
- fetchImpl: options.fetchImpl
25236
+ fetchImpl: options.fetchImpl,
25237
+ state: refreshState
25115
25238
  });
25116
25239
  const api = cachedEvents(cache, ids);
25117
25240
  const native = /* @__PURE__ */ new Set();
@@ -26150,7 +26273,7 @@ function errorClass2(e) {
26150
26273
  var readError2 = (reason) => Object.assign(new Error(reason), { code: reason });
26151
26274
  async function scan5(agg, opts = {}) {
26152
26275
  const stats = emptyScanStats();
26153
- const open3 = await loadSqlite();
26276
+ const open4 = await loadSqlite();
26154
26277
  const sinceMs = opts.sinceMs ?? 0;
26155
26278
  const state = createDbFoldState();
26156
26279
  readConfiguredMcpServers2(agg, state, opts.configFile);
@@ -26159,8 +26282,8 @@ async function scan5(agg, opts = {}) {
26159
26282
  stats.filesFound++;
26160
26283
  agg.files++;
26161
26284
  try {
26162
- if (open3 === null) throw readError2("sqlite-unsupported");
26163
- readDb(agg, state, open3, file, sinceMs);
26285
+ if (open4 === null) throw readError2("sqlite-unsupported");
26286
+ readDb(agg, state, open4, file, sinceMs);
26164
26287
  stats.filesRead++;
26165
26288
  } catch (e) {
26166
26289
  traceError("opencode database read", e);
@@ -26188,8 +26311,8 @@ function checkMigrationCeiling(db) {
26188
26311
  if (!Number.isFinite(prefix)) throw readError2("schema-unversioned");
26189
26312
  if (prefix > OPENCODE_MIGRATION_CEILING) throw readError2("schema-too-new");
26190
26313
  }
26191
- function readDb(agg, state, open3, file, sinceMs) {
26192
- const db = open3(file);
26314
+ function readDb(agg, state, open4, file, sinceMs) {
26315
+ const db = open4(file);
26193
26316
  try {
26194
26317
  checkMigrationCeiling(db);
26195
26318
  noteSessions(
@@ -26389,14 +26512,14 @@ function stripJsonc(text) {
26389
26512
  return out.replace(/,(\s*[}\]])/g, "$1");
26390
26513
  }
26391
26514
  async function detectOpencode(opts) {
26392
- const open3 = await loadSqlite();
26393
- if (open3 === null) return false;
26515
+ const open4 = await loadSqlite();
26516
+ if (open4 === null) return false;
26394
26517
  for (const root of opts.roots ?? opencodeDataDirs()) {
26395
26518
  for (const file of await dbFilesIn(root)) {
26396
26519
  if (!await exists4(file)) continue;
26397
26520
  let db = null;
26398
26521
  try {
26399
- db = open3(file);
26522
+ db = open4(file);
26400
26523
  checkMigrationCeiling(db);
26401
26524
  const probe = (table) => db?.prepare(
26402
26525
  `select 1 as hit from ${table} where time_created >= ? limit 1`
@@ -27112,7 +27235,7 @@ async function createCommand() {
27112
27235
  // src/commands/login.ts
27113
27236
  import { hostname } from "node:os";
27114
27237
  import * as p5 from "@clack/prompts";
27115
- import open2 from "open";
27238
+ import open3 from "open";
27116
27239
  function proposedMachineName(read3 = hostname) {
27117
27240
  try {
27118
27241
  const name = read3().trim().replace(/\.local$/i, "");
@@ -27154,7 +27277,7 @@ async function performLogin(options = {}) {
27154
27277
  p5.log.info(`${dim("CODE")} ${limeBold(session.userCode)}`);
27155
27278
  p5.log.info(`${dim("OPEN")} ${dim(session.authUrl)}`);
27156
27279
  try {
27157
- await open2(session.authUrl);
27280
+ await open3(session.authUrl);
27158
27281
  } catch {
27159
27282
  p5.log.warn(
27160
27283
  "Could not open browser automatically. Please visit the URL above."
@@ -28257,7 +28380,20 @@ function extractGitWorkflow(options) {
28257
28380
  let index = 0;
28258
28381
  for (const cwd of roots.values()) {
28259
28382
  const done = repositoryTimer(++index, roots.size);
28260
- const history = run(cwd, gitLogArgs());
28383
+ const metadata = run(cwd, gitMetadataArgs());
28384
+ const parts = [];
28385
+ let history = metadata === null ? null : "";
28386
+ if (metadata !== null) {
28387
+ for (const args of gitDiffBatches(metadata, options)) {
28388
+ const part = run(cwd, args);
28389
+ if (part === null) {
28390
+ history = null;
28391
+ break;
28392
+ }
28393
+ parts.push(part);
28394
+ }
28395
+ if (history !== null) history = parts.join("");
28396
+ }
28261
28397
  done(history);
28262
28398
  if (history) histories.push(history);
28263
28399
  }
@@ -28279,7 +28415,20 @@ async function extractGitWorkflowAsync(options) {
28279
28415
  const worker = async () => {
28280
28416
  for (let cwd = queue.shift(); cwd !== void 0; cwd = queue.shift()) {
28281
28417
  const done = repositoryTimer(++index, total);
28282
- const history = await run(cwd, gitLogArgs());
28418
+ const metadata = await run(cwd, gitMetadataArgs());
28419
+ const parts = [];
28420
+ let history = metadata === null ? null : "";
28421
+ if (metadata !== null) {
28422
+ for (const args of gitDiffBatches(metadata, options)) {
28423
+ const part = await run(cwd, args);
28424
+ if (part === null) {
28425
+ history = null;
28426
+ break;
28427
+ }
28428
+ parts.push(part);
28429
+ }
28430
+ if (history !== null) history = parts.join("");
28431
+ }
28283
28432
  done(history);
28284
28433
  if (history) histories.push(history);
28285
28434
  }
@@ -28319,17 +28468,39 @@ function countCommits(history) {
28319
28468
  }
28320
28469
  return count2;
28321
28470
  }
28322
- function gitLogArgs() {
28323
- return [
28471
+ var GIT_FORMAT = `--format=%x00${COMMIT_MARKER}%x00%H%x00%aI%x00`;
28472
+ var GIT_DIFF_BATCH_SIZE = 128;
28473
+ function gitMetadataArgs() {
28474
+ return ["log", "--all", "--no-merges", GIT_FORMAT, "--no-patch", "-z"];
28475
+ }
28476
+ function* gitDiffBatches(metadata, options) {
28477
+ const fields = metadata.split("\0");
28478
+ let hashes = [];
28479
+ const args = (batch) => [
28324
28480
  "-c",
28325
28481
  `core.bigFileThreshold=${BIG_FILE_THRESHOLD}`,
28326
28482
  "log",
28327
- "--all",
28483
+ "--no-walk=unsorted",
28328
28484
  "--no-merges",
28329
- `--format=%x00${COMMIT_MARKER}%x00%H%x00%aI%x00`,
28485
+ GIT_FORMAT,
28330
28486
  "--numstat",
28331
- "-z"
28487
+ "-z",
28488
+ ...batch,
28489
+ "--"
28332
28490
  ];
28491
+ for (let index = 0; index < fields.length; index++) {
28492
+ if (fields[index]?.replace(/^\n+/, "") !== COMMIT_MARKER) continue;
28493
+ const hash2 = fields[++index] ?? "";
28494
+ const authoredMs = Date.parse(fields[++index] ?? "");
28495
+ if (!/^[a-f0-9]+$/.test(hash2) || !Number.isFinite(authoredMs) || authoredMs < options.fromMs || authoredMs > options.toMs)
28496
+ continue;
28497
+ hashes.push(hash2);
28498
+ if (hashes.length === GIT_DIFF_BATCH_SIZE) {
28499
+ yield args(hashes);
28500
+ hashes = [];
28501
+ }
28502
+ }
28503
+ if (hashes.length) yield args(hashes);
28333
28504
  }
28334
28505
  function reduceGitHistories(histories, options) {
28335
28506
  const days = /* @__PURE__ */ new Map();