@use-aistack/cli 0.22.1 → 0.23.1

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
@@ -20356,7 +20356,7 @@ var KNOWN_ROW_IDS = /* @__PURE__ */ new Set([
20356
20356
  ]);
20357
20357
 
20358
20358
  // src/version.ts
20359
- var CLI_VERSION = true ? "0.22.1" : "0.0.0-dev";
20359
+ var CLI_VERSION = true ? "0.23.1" : "0.0.0-dev";
20360
20360
 
20361
20361
  // src/api.ts
20362
20362
  var BASE_URL = process.env.AISTACK_URL || "https://aistack.to";
@@ -20842,6 +20842,37 @@ function getProjectWorkspaceId(directory, deps = {}) {
20842
20842
  writeProjects(data, file);
20843
20843
  return workspaceId;
20844
20844
  }
20845
+ var ACCOUNTS_FILE = join(CONFIG_DIR, "accounts.json");
20846
+ function readAccounts(file) {
20847
+ if (!existsSync(file)) return {};
20848
+ try {
20849
+ const raw = JSON.parse(readFileSync(file, "utf-8"));
20850
+ const data = {};
20851
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return data;
20852
+ for (const [harness, folders] of Object.entries(raw)) {
20853
+ if (!folders || typeof folders !== "object" || Array.isArray(folders))
20854
+ continue;
20855
+ data[harness] = {};
20856
+ for (const [key2, id] of Object.entries(folders))
20857
+ if (typeof id === "string" && PROJECT_WORKSPACE_ID_RE2.test(id))
20858
+ data[harness][key2] = id;
20859
+ }
20860
+ return data;
20861
+ } catch {
20862
+ return {};
20863
+ }
20864
+ }
20865
+ function getHarnessAccountId(harness, accountKey, deps = {}) {
20866
+ const file = deps.file ?? ACCOUNTS_FILE;
20867
+ const data = readAccounts(file);
20868
+ const held = data[harness]?.[accountKey];
20869
+ if (held) return held;
20870
+ const id = (deps.createId ?? (() => randomBytes(16).toString("base64url")))();
20871
+ data[harness] = { ...data[harness], [accountKey]: id };
20872
+ mkdirSync(dirname2(file), { recursive: true, mode: 448 });
20873
+ writeFileSync(file, JSON.stringify(data, null, 2), { mode: 384 });
20874
+ return id;
20875
+ }
20845
20876
  function getExcludedPaths(directory, file = PROJECTS_FILE) {
20846
20877
  return readProjects(file)[directory]?.excluded ?? [];
20847
20878
  }
@@ -22104,6 +22135,7 @@ var asName = (v) => {
22104
22135
  const s = asStr(v);
22105
22136
  return s === null ? null : cleanName(s);
22106
22137
  };
22138
+ var currentAccount = (agg) => agg.account ?? "";
22107
22139
  var utcDateOf = (ms) => new Date(ms).toISOString().slice(0, 10);
22108
22140
  function usageDayAcc(agg, tsMs) {
22109
22141
  const date = utcDateOf(tsMs);
@@ -22113,38 +22145,51 @@ function usageDayAcc(agg, tsMs) {
22113
22145
  models: /* @__PURE__ */ new Map(),
22114
22146
  subagentTokens: 0,
22115
22147
  syntheticTokens: 0,
22116
- projectDirs: /* @__PURE__ */ new Set()
22148
+ projectDirs: /* @__PURE__ */ new Set(),
22149
+ accounts: /* @__PURE__ */ new Map()
22117
22150
  };
22118
22151
  agg.usageDays.set(date, day);
22119
22152
  }
22120
22153
  return day;
22121
22154
  }
22155
+ var emptyCounts = () => ({
22156
+ input: 0,
22157
+ output: 0,
22158
+ cacheWrite5m: 0,
22159
+ cacheWrite1h: 0,
22160
+ cacheWriteUnsplit: 0,
22161
+ cacheRead: 0
22162
+ });
22163
+ function addCounts(into, c, sign) {
22164
+ into.input += sign * c.input;
22165
+ into.output += sign * c.output;
22166
+ into.cacheWrite5m += sign * c.cacheWrite5m;
22167
+ into.cacheWrite1h += sign * c.cacheWrite1h;
22168
+ into.cacheWriteUnsplit += sign * c.cacheWriteUnsplit;
22169
+ into.cacheRead += sign * c.cacheRead;
22170
+ }
22122
22171
  function noteUsageResponse(agg, response, sign = 1) {
22123
22172
  if (response.tsMs === null) return;
22124
22173
  const day = usageDayAcc(agg, response.tsMs);
22125
22174
  let m = day.models.get(response.modelKey);
22126
22175
  if (!m) {
22127
- m = {
22128
- counts: {
22129
- input: 0,
22130
- output: 0,
22131
- cacheWrite5m: 0,
22132
- cacheWrite1h: 0,
22133
- cacheWriteUnsplit: 0,
22134
- cacheRead: 0
22135
- },
22136
- costUSD: 0,
22137
- unpricedTokens: 0
22138
- };
22176
+ m = { counts: emptyCounts(), costUSD: 0, unpricedTokens: 0 };
22139
22177
  day.models.set(response.modelKey, m);
22140
22178
  }
22141
22179
  const c = response.counts;
22142
- m.counts.input += sign * c.input;
22143
- m.counts.output += sign * c.output;
22144
- m.counts.cacheWrite5m += sign * c.cacheWrite5m;
22145
- m.counts.cacheWrite1h += sign * c.cacheWrite1h;
22146
- m.counts.cacheWriteUnsplit += sign * c.cacheWriteUnsplit;
22147
- m.counts.cacheRead += sign * c.cacheRead;
22180
+ addCounts(m.counts, c, sign);
22181
+ const accountKey = response.account ?? currentAccount(agg);
22182
+ let account = day.accounts.get(accountKey);
22183
+ if (!account) {
22184
+ account = /* @__PURE__ */ new Map();
22185
+ day.accounts.set(accountKey, account);
22186
+ }
22187
+ let accountModel = account.get(response.modelKey);
22188
+ if (!accountModel) {
22189
+ accountModel = emptyCounts();
22190
+ account.set(response.modelKey, accountModel);
22191
+ }
22192
+ addCounts(accountModel, c, sign);
22148
22193
  if (response.costUSD === null) m.unpricedTokens += sign * countsTotal(c);
22149
22194
  else m.costUSD += sign * response.costUSD;
22150
22195
  if (response.sidechain) day.subagentTokens += sign * countsTotal(c);
@@ -22155,8 +22200,15 @@ function noteSyntheticTokens(agg, tsMs, tokens) {
22155
22200
  }
22156
22201
  function noteSessionStart(agg, sessionId, tsMs) {
22157
22202
  if (tsMs === null) return;
22203
+ const date = utcDateOf(tsMs);
22204
+ const days = agg.sessionDays.get(sessionId);
22205
+ if (days) days.add(date);
22206
+ else agg.sessionDays.set(sessionId, /* @__PURE__ */ new Set([date]));
22158
22207
  const held = agg.sessionStarts.get(sessionId);
22159
- if (held === void 0 || tsMs < held) agg.sessionStarts.set(sessionId, tsMs);
22208
+ if (held === void 0 || tsMs < held) {
22209
+ agg.sessionStarts.set(sessionId, tsMs);
22210
+ agg.sessionAccounts.set(sessionId, currentAccount(agg));
22211
+ }
22160
22212
  }
22161
22213
  function noteProjectDay(agg, directory, tsMs) {
22162
22214
  if (tsMs === null) return;
@@ -22205,7 +22257,9 @@ function createAggregate() {
22205
22257
  webFetchRequests: 0,
22206
22258
  seen: /* @__PURE__ */ new Map(),
22207
22259
  usageDays: /* @__PURE__ */ new Map(),
22208
- sessionStarts: /* @__PURE__ */ new Map()
22260
+ sessionStarts: /* @__PURE__ */ new Map(),
22261
+ sessionDays: /* @__PURE__ */ new Map(),
22262
+ sessionAccounts: /* @__PURE__ */ new Map()
22209
22263
  };
22210
22264
  }
22211
22265
  var bump = (m, k, n = 1) => m.set(k, (m.get(k) ?? 0) + n);
@@ -24727,7 +24781,13 @@ function ingestAssistant(agg, rec, tsMs) {
24727
24781
  }
24728
24782
  if (tsMs === null) agg.untimestampedResponses++;
24729
24783
  const sidechain = rec.isSidechain === true;
24730
- const contribution = buildContribution(usage, model, sidechain, tsMs);
24784
+ const contribution = buildContribution(
24785
+ usage,
24786
+ model,
24787
+ sidechain,
24788
+ tsMs,
24789
+ currentAccount(agg)
24790
+ );
24731
24791
  if (messageId === null) {
24732
24792
  agg.unkeyedResponses++;
24733
24793
  acceptContribution(agg, contribution);
@@ -24789,7 +24849,7 @@ function makeEntry(modelKey, counts2, tsMs) {
24789
24849
  costUSD: apiEquivalentCost(modelKey, counts2, tsMs)
24790
24850
  };
24791
24851
  }
24792
- function buildContribution(usage, model, sidechain, tsMs) {
24852
+ function buildContribution(usage, model, sidechain, tsMs, account) {
24793
24853
  const modelKey = modelKeyFor2(model, asStr(usage.speed));
24794
24854
  const entries = [makeEntry(modelKey, readCounts(usage), tsMs)];
24795
24855
  const mirrored = /* @__PURE__ */ new Map();
@@ -24827,7 +24887,8 @@ function buildContribution(usage, model, sidechain, tsMs) {
24827
24887
  webFetch: serverTools ? asNum(serverTools.web_fetch_requests) : 0,
24828
24888
  mirroredIterationTypes: [...mirrored],
24829
24889
  fallbackAttempts,
24830
- untypedMirrors
24890
+ untypedMirrors,
24891
+ account
24831
24892
  };
24832
24893
  }
24833
24894
  function applyContribution(agg, c, sign) {
@@ -24848,7 +24909,14 @@ function applyContribution(agg, c, sign) {
24848
24909
  else m.costUSD += sign * costUSD;
24849
24910
  noteUsageResponse(
24850
24911
  agg,
24851
- { tsMs: c.tsMs, modelKey, counts: counts2, costUSD, sidechain: c.sidechain },
24912
+ {
24913
+ tsMs: c.tsMs,
24914
+ modelKey,
24915
+ counts: counts2,
24916
+ costUSD,
24917
+ sidechain: c.sidechain,
24918
+ account: c.account
24919
+ },
24852
24920
  sign
24853
24921
  );
24854
24922
  });
@@ -25071,17 +25139,27 @@ async function discoverClaudeRoots() {
25071
25139
  }
25072
25140
  const roots = /* @__PURE__ */ new Set();
25073
25141
  const accounts = /* @__PURE__ */ new Set();
25142
+ const rootAccounts = /* @__PURE__ */ new Map();
25143
+ const groupRoots = /* @__PURE__ */ new Map();
25074
25144
  for (const profile of profiles) {
25075
25145
  try {
25076
25146
  const projects = await realpath3(path4.join(profile, "projects"));
25077
25147
  if (!(await stat4(projects)).isDirectory()) continue;
25078
25148
  roots.add(projects);
25079
- if (!groups.has(profile)) accounts.add(await realpath3(profile));
25149
+ if (groups.has(profile)) {
25150
+ if (!groupRoots.has(projects)) groupRoots.set(projects, profile);
25151
+ continue;
25152
+ }
25153
+ const account = await realpath3(profile);
25154
+ accounts.add(account);
25155
+ if (!rootAccounts.has(projects)) rootAccounts.set(projects, account);
25080
25156
  } catch (error) {
25081
25157
  failed(error);
25082
25158
  }
25083
25159
  }
25084
- return { roots: [...roots], profiles: [...accounts], complete };
25160
+ for (const [projects, group] of groupRoots)
25161
+ if (!rootAccounts.has(projects)) rootAccounts.set(projects, group);
25162
+ return { roots: [...roots], profiles: [...accounts], rootAccounts, complete };
25085
25163
  }
25086
25164
 
25087
25165
  // src/harness/claude/scan.ts
@@ -25119,6 +25197,7 @@ async function scan2(agg, opts = {}) {
25119
25197
  stats.sourceDiscoveryComplete = discovery.complete;
25120
25198
  for (const root of discovery.roots) {
25121
25199
  if (!await exists(root)) continue;
25200
+ agg.account = discovery.rootAccounts?.get(root) ?? root;
25122
25201
  for await (const file of walkJsonl(root)) {
25123
25202
  stats.filesFound++;
25124
25203
  let resolved;
@@ -25666,6 +25745,7 @@ async function scanWindows(windows, opts = {}) {
25666
25745
  });
25667
25746
  if (!eligible.length) continue;
25668
25747
  for (const { aggregate, stats, onProgress } of eligible) {
25748
+ aggregate.account = root;
25669
25749
  aggregate.files++;
25670
25750
  stats.filesRead++;
25671
25751
  if (aggregate.files % 20 === 0) onProgress?.(aggregate.files);
@@ -26939,31 +27019,41 @@ function isPageByteLimit(error) {
26939
27019
  }
26940
27020
 
26941
27021
  // src/harness/cursor/account.ts
27022
+ var ENCRYPTED_PREFIX = "cursor-safe-storage:";
26942
27023
  var digest = (value) => createHash7("sha256").update(value).digest("hex");
26943
27024
  async function existingAccount(root) {
27025
+ let value;
26944
27026
  let db;
26945
27027
  try {
26946
27028
  const { DatabaseSync } = await import("node:sqlite");
26947
27029
  db = new DatabaseSync(globalDb(root), { readOnly: true });
26948
- const row = db.prepare("SELECT value FROM ItemTable WHERE key = ?").get("cursorAuth/accessToken");
26949
- if (typeof row?.value !== "string") return null;
26950
- const token = row.value.trim().replace(/^"|"$/g, "");
27030
+ value = db.prepare("SELECT value FROM ItemTable WHERE key = ?").get("cursorAuth/accessToken")?.value;
27031
+ } catch (error) {
27032
+ traceError("cursor account lookup", error, "warn");
27033
+ return null;
27034
+ } finally {
27035
+ db?.close();
27036
+ }
27037
+ if (typeof value !== "string") return null;
27038
+ const token = value.trim().replace(/^"|"$/g, "");
27039
+ if (token.startsWith(ENCRYPTED_PREFIX)) {
27040
+ trace("cursor account \xB7 sign-in is encrypted at rest", "warn");
27041
+ return { problem: "encrypted" };
27042
+ }
27043
+ try {
26951
27044
  const claims = asObj(
26952
27045
  JSON.parse(
26953
27046
  Buffer.from(token.split(".")[1] ?? "", "base64url").toString("utf8")
26954
27047
  )
26955
27048
  );
26956
27049
  const subject = asStr(claims?.sub);
26957
- if (!subject || claims?.type === "api_key_token" || !/^[\w|:-]+$/.test(subject) || !/^[A-Za-z0-9_.-]+$/.test(token))
26958
- return null;
26959
- const user = subject.split("|").at(-1);
26960
- if (!user) return null;
27050
+ const user = subject?.split("|").at(-1);
27051
+ if (!subject || !user || claims?.type === "api_key_token" || !/^[\w|:-]+$/.test(subject) || !/^[A-Za-z0-9_.-]+$/.test(token))
27052
+ return { problem: "unreadable" };
26961
27053
  return { scope: digest(subject), cookie: `${user}%3A%3A${token}` };
26962
27054
  } catch (error) {
26963
- traceError("cursor account lookup", error, "warn");
26964
- return null;
26965
- } finally {
26966
- db?.close();
27055
+ traceError("cursor account token", error, "warn");
27056
+ return { problem: "unreadable" };
26967
27057
  }
26968
27058
  }
26969
27059
  function apiContribution(value) {
@@ -27173,6 +27263,17 @@ async function saveCache(file, value) {
27173
27263
  await writeFile3(temporary, JSON.stringify(value), { mode: 384 });
27174
27264
  await rename2(temporary, file);
27175
27265
  }
27266
+ function refreshFailure(error) {
27267
+ const status = error?.status;
27268
+ if (typeof status === "number")
27269
+ return `the usage request failed (HTTP ${status})`;
27270
+ const name = error?.name;
27271
+ if (name === "TimeoutError" || name === "AbortError")
27272
+ return "the usage request timed out";
27273
+ if (error instanceof TypeError)
27274
+ return "the usage request could not reach cursor.com";
27275
+ return "Cursor answered in a form this version cannot read";
27276
+ }
27176
27277
  var REFRESH_MS = 3e5;
27177
27278
  var WINDOW_MS = 30 * 864e5;
27178
27279
  async function refreshAccount(input) {
@@ -27183,6 +27284,7 @@ async function refreshAccount(input) {
27183
27284
  state.account = account.scope;
27184
27285
  state.windows = {};
27185
27286
  state.failedAt = void 0;
27287
+ state.failure = void 0;
27186
27288
  }
27187
27289
  const changed = cache.account !== account.scope;
27188
27290
  const next = {
@@ -27192,6 +27294,7 @@ async function refreshAccount(input) {
27192
27294
  };
27193
27295
  if (state?.failedAt !== void 0 && now - state.failedAt < REFRESH_MS)
27194
27296
  return next;
27297
+ if (state) state.failure = void 0;
27195
27298
  for (let from = Math.floor(input.sinceMs / WINDOW_MS) * WINDOW_MS; from <= now; from += WINDOW_MS) {
27196
27299
  const to = Math.min(from + WINDOW_MS, now + 1);
27197
27300
  const key2 = String(from);
@@ -27202,7 +27305,10 @@ async function refreshAccount(input) {
27202
27305
  if (previous?.events.length && events.length === 0 && to <= now) continue;
27203
27306
  next.windows[key2] = { from, to, fetchedAt: now, events };
27204
27307
  } catch (error) {
27205
- if (state) state.failedAt = now;
27308
+ if (state) {
27309
+ state.failedAt = now;
27310
+ state.failure = refreshFailure(error);
27311
+ }
27206
27312
  traceError(
27207
27313
  "cursor account usage refresh (using local and previously cached usage)",
27208
27314
  error,
@@ -27461,6 +27567,10 @@ function projectHistory(options) {
27461
27567
 
27462
27568
  // src/harness/cursor/scan.ts
27463
27569
  var accountRefreshes = /* @__PURE__ */ new Map();
27570
+ var ACCOUNT_PROBLEMS = {
27571
+ encrypted: "Cursor keeps its sign-in encrypted in the system keychain",
27572
+ unreadable: "the stored Cursor sign-in could not be read"
27573
+ };
27464
27574
  async function readFolder(root, options, now, onProgress) {
27465
27575
  const file = typeof options.cachePath === "function" ? options.cachePath(root) : options.cachePath ?? cacheFile(root, storeRoot());
27466
27576
  const local = await (options.readLocalImpl ?? readLocal)(root, onProgress);
@@ -27477,7 +27587,8 @@ async function readFolder(root, options, now, onProgress) {
27477
27587
  );
27478
27588
  complete = false;
27479
27589
  }
27480
- const account = ids.size ? await (options.accountImpl ?? existingAccount)(root) : null;
27590
+ const lookup = ids.size ? await (options.accountImpl ?? existingAccount)(root) : null;
27591
+ const account = lookup && "scope" in lookup ? lookup : null;
27481
27592
  const refreshKey = JSON.stringify([root, storeRoot(), file]);
27482
27593
  let refreshState = accountRefreshes.get(refreshKey);
27483
27594
  if (!refreshState) {
@@ -27493,6 +27604,20 @@ async function readFolder(root, options, now, onProgress) {
27493
27604
  fetchImpl: options.fetchImpl,
27494
27605
  state: refreshState
27495
27606
  });
27607
+ let accountMissing;
27608
+ if (lookup && "problem" in lookup)
27609
+ accountMissing = {
27610
+ reason: ACCOUNT_PROBLEMS[lookup.problem],
27611
+ retained: true
27612
+ };
27613
+ else if (account && refreshState.failure)
27614
+ accountMissing = { reason: refreshState.failure, retained: true };
27615
+ else if (ids.size && !account)
27616
+ accountMissing = {
27617
+ reason: "Cursor is not signed in on this machine",
27618
+ retained: false
27619
+ };
27620
+ if (accountMissing?.retained) complete = false;
27496
27621
  const api = cachedEvents(cache, ids);
27497
27622
  const contributions = local.sessions.flatMap(
27498
27623
  (s) => localContributions(s, api)
@@ -27523,7 +27648,8 @@ async function readFolder(root, options, now, onProgress) {
27523
27648
  api,
27524
27649
  contributions,
27525
27650
  previous: [...loaded.value.local, ...cachedEvents(loaded.value, ids)],
27526
- complete
27651
+ complete,
27652
+ ...accountMissing ? { accountMissing } : {}
27527
27653
  };
27528
27654
  }
27529
27655
  function dedupeNative(rows) {
@@ -27589,6 +27715,11 @@ async function scan4(options) {
27589
27715
  });
27590
27716
  }
27591
27717
  const owns = (index) => (row) => owner.get(row.session)?.folder === index;
27718
+ const folderRoots = roots;
27719
+ const accountOf = (session) => {
27720
+ const folder = owner.get(session)?.folder;
27721
+ return folder === void 0 ? "" : folderRoots[folder] ?? "";
27722
+ };
27592
27723
  const local = {
27593
27724
  sessions: folders.flatMap(
27594
27725
  (f, index) => f.local.sessions.filter(
@@ -27599,6 +27730,11 @@ async function scan4(options) {
27599
27730
  stats: emptyScanStats()
27600
27731
  };
27601
27732
  for (const folder of folders) addStats(local.stats, folder.local.stats);
27733
+ const missing = folders.flatMap(
27734
+ (f) => f.local.sessions.length ? [f.accountMissing] : []
27735
+ );
27736
+ const accountMissing = missing.find((m) => m?.retained) ?? (missing.length && missing.every(Boolean) ? missing[0] : void 0);
27737
+ if (accountMissing) local.stats.accountUsageMissing = accountMissing;
27602
27738
  if (!discoveryComplete) local.stats.sourceDiscoveryComplete = false;
27603
27739
  const api = folders.flatMap((f, index) => f.api.filter(owns(index)));
27604
27740
  const contributions = dedupeNative(
@@ -27637,6 +27773,7 @@ async function scan4(options) {
27637
27773
  }
27638
27774
  if (firstTime !== null) {
27639
27775
  aggregate.sessions.add(session.id);
27776
+ aggregate.account = accountOf(session.id);
27640
27777
  noteSessionStart(aggregate, session.id, firstTime);
27641
27778
  }
27642
27779
  }
@@ -27657,6 +27794,7 @@ async function scan4(options) {
27657
27794
  sessionDates.set(session, dates);
27658
27795
  if (tsMs < options.sinceMs || tsMs > now) continue;
27659
27796
  const model = normalizeModel(contribution.model);
27797
+ aggregate.account = accountOf(session);
27660
27798
  const counts2 = {
27661
27799
  input: buckets.input ?? 0,
27662
27800
  output: buckets.output ?? 0,
@@ -28393,7 +28531,7 @@ async function scanWindows2(windows, opts = {}) {
28393
28531
  const held = candidates.get(sessionId);
28394
28532
  const total = (values) => values.flatMap((value) => value.models).reduce((sum, model) => sum + countsTotal(model.counts), 0);
28395
28533
  if (!held || precedence > held.precedence || precedence === held.precedence && total(windowRows) > total(held.rows))
28396
- candidates.set(sessionId, { precedence, rows: windowRows });
28534
+ candidates.set(sessionId, { precedence, rows: windowRows, root });
28397
28535
  }
28398
28536
  onProgress?.(stats.filesFound);
28399
28537
  }
@@ -28429,7 +28567,8 @@ async function scanWindows2(windows, opts = {}) {
28429
28567
  }
28430
28568
  }
28431
28569
  for (const { aggregate, candidates, sessionDates } of targets) {
28432
- for (const { rows } of candidates.values()) {
28570
+ for (const { rows, root } of candidates.values()) {
28571
+ aggregate.account = root;
28433
28572
  for (const row of rows) {
28434
28573
  ingestContribution(aggregate, row);
28435
28574
  const dates = sessionDates.get(row.sessionId) ?? /* @__PURE__ */ new Set();
@@ -28710,29 +28849,31 @@ async function dbFilesIn(root) {
28710
28849
  async function storeFiles2(roots) {
28711
28850
  const dirs = roots ?? (await opencodeDataDirs()).homes;
28712
28851
  const candidates = [];
28713
- for (const root of dirs) candidates.push(...await dbFilesIn(root));
28852
+ for (const root of dirs)
28853
+ for (const file of await dbFilesIn(root))
28854
+ candidates.push({ file, account: root });
28714
28855
  const override = roots ? void 0 : process.env.OPENCODE_DB?.trim();
28715
- if (override)
28716
- candidates.push(
28717
- path15.resolve(
28718
- process.env.XDG_DATA_HOME?.trim() || path15.join(homedir18(), ".local", "share"),
28719
- "opencode",
28720
- override
28721
- )
28856
+ if (override) {
28857
+ const file = path15.resolve(
28858
+ process.env.XDG_DATA_HOME?.trim() || path15.join(homedir18(), ".local", "share"),
28859
+ "opencode",
28860
+ override
28722
28861
  );
28862
+ candidates.push({ file, account: file });
28863
+ }
28723
28864
  const files = [];
28724
28865
  const seen = /* @__PURE__ */ new Set();
28725
- for (const file of candidates) {
28726
- let key2 = file;
28866
+ for (const candidate of candidates) {
28867
+ let key2 = candidate.file;
28727
28868
  try {
28728
- key2 = await realpath5(file);
28869
+ key2 = await realpath5(candidate.file);
28729
28870
  } catch (error) {
28730
28871
  if (error?.code !== "ENOENT")
28731
28872
  traceError("opencode database path resolution", error, "warn");
28732
28873
  }
28733
28874
  if (seen.has(key2)) continue;
28734
28875
  seen.add(key2);
28735
- files.push(file);
28876
+ files.push(candidate);
28736
28877
  }
28737
28878
  return files;
28738
28879
  }
@@ -28759,9 +28900,10 @@ async function scan6(agg, opts = {}) {
28759
28900
  const sinceMs = opts.sinceMs ?? 0;
28760
28901
  const state = createDbFoldState();
28761
28902
  readConfiguredMcpServers2(agg, state, opts.configFile);
28762
- for (const file of await storeFiles2(opts.roots)) {
28903
+ for (const { file, account } of await storeFiles2(opts.roots)) {
28763
28904
  stats.filesFound++;
28764
28905
  agg.files++;
28906
+ agg.account = account;
28765
28907
  try {
28766
28908
  if (open4 === null) throw readError3("sqlite-unsupported");
28767
28909
  readDb(agg, state, open4, file, sinceMs);
@@ -29009,7 +29151,7 @@ function stripJsonc(text) {
29009
29151
  async function detectOpencode(opts) {
29010
29152
  const open4 = await loadSqlite2();
29011
29153
  if (open4 === null) return false;
29012
- for (const file of await storeFiles2(opts.roots)) {
29154
+ for (const { file } of await storeFiles2(opts.roots)) {
29013
29155
  if (!await exists4(file)) continue;
29014
29156
  let db = null;
29015
29157
  try {
@@ -29310,6 +29452,7 @@ async function scan7(agg, opts = {}) {
29310
29452
  stats.sourceDiscoveryComplete = discovery.complete;
29311
29453
  for (const root of discovery.homes) {
29312
29454
  if (!await exists5(root)) continue;
29455
+ agg.account = root;
29313
29456
  for await (const file of walkSessions(root)) {
29314
29457
  stats.filesFound++;
29315
29458
  let resolved;
@@ -30886,6 +31029,22 @@ function buildUsageDays(input) {
30886
31029
  const dates = [
30887
31030
  .../* @__PURE__ */ new Set([...agg.usageDays.keys(), ...sessionsByDay.keys()])
30888
31031
  ].sort();
31032
+ const sessionsByAccountDay = /* @__PURE__ */ new Map();
31033
+ for (const [session, startMs] of agg.sessionStarts) {
31034
+ const date = utcDateOf(startMs);
31035
+ const account = agg.sessionAccounts.get(session) ?? "";
31036
+ const byAccount = sessionsByAccountDay.get(date) ?? /* @__PURE__ */ new Map();
31037
+ byAccount.set(account, (byAccount.get(account) ?? 0) + 1);
31038
+ sessionsByAccountDay.set(date, byAccount);
31039
+ }
31040
+ const accountKeys = /* @__PURE__ */ new Set();
31041
+ for (const byAccount of sessionsByAccountDay.values())
31042
+ for (const key2 of byAccount.keys()) accountKeys.add(key2);
31043
+ for (const day of agg.usageDays.values())
31044
+ for (const [key2, models] of day.accounts)
31045
+ if ([...models.values()].some((c) => countsTotal(c) !== 0))
31046
+ accountKeys.add(key2);
31047
+ const accountId = input.accountId && accountKeys.size > 1 ? input.accountId : void 0;
30889
31048
  const out = /* @__PURE__ */ new Map();
30890
31049
  for (const date of dates) {
30891
31050
  const acc = agg.usageDays.get(date);
@@ -30934,7 +31093,9 @@ function buildUsageDays(input) {
30934
31093
  (a, b) => countsTotalOf(b.tokens) - countsTotalOf(a.tokens) || a.model.localeCompare(b.model)
30935
31094
  );
30936
31095
  const directories2 = [...acc?.projectDirs ?? []];
30937
- const included = input.deferWorkspace ? directories2.filter((directory) => !input.deferWorkspace?.(directory)) : directories2;
31096
+ const included = input.deferWorkspace ? directories2.filter(
31097
+ (directory) => !input.deferWorkspace?.(directory, date)
31098
+ ) : directories2;
30938
31099
  out.set(date, {
30939
31100
  harness,
30940
31101
  sessions: sessionsByDay.get(date) ?? 0,
@@ -30942,11 +31103,82 @@ function buildUsageDays(input) {
30942
31103
  ...included.length < directories2.length ? { workspaceEvidenceIncomplete: true } : {},
30943
31104
  models,
30944
31105
  subagentTokens: acc?.subagentTokens ?? 0,
30945
- excludedTokens: { unpriced, synthetic: acc?.syntheticTokens ?? 0 }
31106
+ excludedTokens: { unpriced, synthetic: acc?.syntheticTokens ?? 0 },
31107
+ ...accountId ? {
31108
+ accounts: accountsOfDay(
31109
+ acc,
31110
+ sessionsByAccountDay.get(date),
31111
+ accountId
31112
+ )
31113
+ } : {}
30946
31114
  });
30947
31115
  }
30948
31116
  return out;
30949
31117
  }
31118
+ function wireTokens(c) {
31119
+ const plain = {
31120
+ input: c.input,
31121
+ output: c.output,
31122
+ cacheWrite: c.cacheWrite5m + c.cacheWrite1h + c.cacheWriteUnsplit,
31123
+ cacheRead: c.cacheRead
31124
+ };
31125
+ return plain.cacheWrite > 0 ? {
31126
+ ...plain,
31127
+ cacheWriteTtl: {
31128
+ fiveMinute: c.cacheWrite5m,
31129
+ oneHour: c.cacheWrite1h,
31130
+ unsplit: c.cacheWriteUnsplit
31131
+ }
31132
+ } : plain;
31133
+ }
31134
+ function accountsOfDay(acc, sessions, accountId) {
31135
+ const keys = /* @__PURE__ */ new Set([
31136
+ ...acc?.accounts.keys() ?? [],
31137
+ ...sessions?.keys() ?? []
31138
+ ]);
31139
+ const out = [];
31140
+ for (const key2 of keys) {
31141
+ const groups = /* @__PURE__ */ new Map();
31142
+ const total = emptyCounts2();
31143
+ for (const [modelKey, counts2] of acc?.accounts.get(key2) ?? []) {
31144
+ const id = sanitizeModelId(baseModelId(modelKey));
31145
+ const g = groups.get(id) ?? emptyCounts2();
31146
+ addCounts2(g, counts2);
31147
+ groups.set(id, g);
31148
+ addCounts2(total, counts2);
31149
+ }
31150
+ const models = [...groups.entries()].map(([model, counts2]) => ({ model, tokens: wireTokens(counts2) })).filter((row) => countsTotalOf(row.tokens) > 0).sort(
31151
+ (a, b) => countsTotalOf(b.tokens) - countsTotalOf(a.tokens) || a.model.localeCompare(b.model)
31152
+ );
31153
+ const count2 = sessions?.get(key2) ?? 0;
31154
+ if (count2 === 0 && models.length === 0) continue;
31155
+ out.push({
31156
+ account: accountId(key2),
31157
+ sessions: count2,
31158
+ tokens: wireTokens(total),
31159
+ models
31160
+ });
31161
+ }
31162
+ return out.sort(
31163
+ (a, b) => a.account < b.account ? -1 : a.account > b.account ? 1 : 0
31164
+ );
31165
+ }
31166
+ var emptyCounts2 = () => ({
31167
+ input: 0,
31168
+ output: 0,
31169
+ cacheWrite5m: 0,
31170
+ cacheWrite1h: 0,
31171
+ cacheWriteUnsplit: 0,
31172
+ cacheRead: 0
31173
+ });
31174
+ function addCounts2(into, c) {
31175
+ into.input += c.input;
31176
+ into.output += c.output;
31177
+ into.cacheWrite5m += c.cacheWrite5m;
31178
+ into.cacheWrite1h += c.cacheWrite1h;
31179
+ into.cacheWriteUnsplit += c.cacheWriteUnsplit;
31180
+ into.cacheRead += c.cacheRead;
31181
+ }
30950
31182
  var countsTotalOf = (t) => t.input + t.output + t.cacheWrite + t.cacheRead;
30951
31183
  function mergeUsageDays(perHarness) {
30952
31184
  const out = /* @__PURE__ */ new Map();
@@ -30985,6 +31217,28 @@ function buildMeasuredDays(input) {
30985
31217
  };
30986
31218
  });
30987
31219
  }
31220
+ function markDeletedEvidence(days, input) {
31221
+ const out = [];
31222
+ for (const day of days) {
31223
+ const carried = /* @__PURE__ */ new Set([
31224
+ ...(day.usage?.harnesses ?? []).map((h) => h.harness),
31225
+ ...(day.workflow?.harnesses ?? []).map((h) => h.harness)
31226
+ ]);
31227
+ const partial = [...input.ledgers].filter(
31228
+ ([harness, ledger]) => carried.has(harness) && !input.partialHarnesses.has(harness) && ledger.partialDates.has(day.date)
31229
+ ).map(([harness]) => harness).sort();
31230
+ const cleared = [...input.clearable].filter(
31231
+ ([harness, ledger]) => !carried.has(harness) && ledger.clearDates.has(day.date)
31232
+ ).map(([harness]) => harness).sort();
31233
+ if (!day.usage && !day.workflow && cleared.length === 0) continue;
31234
+ out.push({
31235
+ ...day,
31236
+ ...partial.length ? { partialHarnesses: partial } : {},
31237
+ ...cleared.length ? { clearedHarnesses: cleared } : {}
31238
+ });
31239
+ }
31240
+ return out;
31241
+ }
30988
31242
 
30989
31243
  // src/usage/diff.ts
30990
31244
  var MAX_DAY_WINDOW = 400;
@@ -31598,13 +31852,29 @@ function saveGrokDateHints(scope, hints, file = defaultFile) {
31598
31852
  mkdirSync9(path20.dirname(file), { recursive: true });
31599
31853
  writeFileSync9(file, JSON.stringify(cache, null, 2));
31600
31854
  }
31601
- function mapToHints(value, floor) {
31602
- return Object.fromEntries(
31603
- [...value].map(([id, dates]) => [
31604
- id,
31605
- [...dates].filter((d) => d >= floor).sort()
31606
- ])
31855
+
31856
+ // src/sync/sessionLedger.ts
31857
+ function readSessionLedger(previous, current, floor) {
31858
+ const partialDates = /* @__PURE__ */ new Set();
31859
+ const remembered = /* @__PURE__ */ new Set();
31860
+ const next = {};
31861
+ for (const [id, dates] of Object.entries(previous)) {
31862
+ const kept = dates.filter((date) => date >= floor);
31863
+ if (current.has(id)) {
31864
+ for (const date of kept) remembered.add(date);
31865
+ continue;
31866
+ }
31867
+ for (const date of kept) partialDates.add(date);
31868
+ if (kept.length) next[id] = kept;
31869
+ }
31870
+ for (const [id, dates] of current) {
31871
+ const kept = [...dates].filter((date) => date >= floor).sort();
31872
+ if (kept.length) next[id] = kept;
31873
+ }
31874
+ const clearDates = new Set(
31875
+ [...remembered].filter((date) => !partialDates.has(date))
31607
31876
  );
31877
+ return { partialDates, clearDates, next };
31608
31878
  }
31609
31879
 
31610
31880
  // src/sync/summary.ts
@@ -31770,6 +32040,13 @@ var KEPT_PRIVATE_ROWS_SHOWN = 3;
31770
32040
  var UNREADABLE_FILES_SHOWN = 5;
31771
32041
  function scanNoteLines(stats, label) {
31772
32042
  const out = [];
32043
+ const missing = stats.accountUsageMissing;
32044
+ if (missing) {
32045
+ out.push(
32046
+ `account ${label} usage not read: ${missing.reason}`,
32047
+ ` Tokens are estimated from message text.${missing.retained ? " Days already on aistack are kept." : ""}`
32048
+ );
32049
+ }
31773
32050
  const shown = stats.unreadableFiles.slice(0, UNREADABLE_FILES_SHOWN);
31774
32051
  for (const f of shown) {
31775
32052
  out.push(` ${f.path} (${f.reason})`);
@@ -31810,6 +32087,8 @@ function payloadBlock(payload, width, ownWindow, stats) {
31810
32087
  out.push(`${label.toUpperCase()} ${payload.activity.sessions}`);
31811
32088
  if (payload.activity.totalTokens === 0) {
31812
32089
  out.push(`usage ${totals.slice(1).join(" \xB7 ")}`);
32090
+ if (stats)
32091
+ out.push(...scanNoteLines(stats, harnessLabel2(payload.harness.name)));
31813
32092
  return out;
31814
32093
  }
31815
32094
  out.push(
@@ -32093,6 +32372,16 @@ async function stageSync(deps) {
32093
32372
  workspaceIds.set(directory, id);
32094
32373
  return id;
32095
32374
  };
32375
+ const resolveAccountId = deps.getHarnessAccountIdImpl ?? getHarnessAccountId;
32376
+ const accountIds = /* @__PURE__ */ new Map();
32377
+ const harnessAccountId = (harness) => (accountKey) => {
32378
+ const cacheKey = `${harness}\0${accountKey}`;
32379
+ const held = accountIds.get(cacheKey);
32380
+ if (held !== void 0) return held;
32381
+ const id = resolveAccountId(harness, accountKey);
32382
+ accountIds.set(cacheKey, id);
32383
+ return id;
32384
+ };
32096
32385
  const fetchManifest = deps.fetchManifestImpl ?? fetchDayManifest;
32097
32386
  const fetchPrices = deps.fetchPricesImpl ?? fetchPriceTable;
32098
32387
  const emit2 = (event) => deps.onEvent?.(event);
@@ -32300,8 +32589,15 @@ async function stageSync(deps) {
32300
32589
  `historical harnesses (${retentionDays} days): ${historical.map((a) => a.name).join(", ") || "none"}`
32301
32590
  );
32302
32591
  let dayScansComplete = true;
32592
+ const acknowledgements = [];
32303
32593
  const partialHarnesses = /* @__PURE__ */ new Set();
32304
- const sessionDatesByHarness = /* @__PURE__ */ new Map();
32594
+ const ledgers = /* @__PURE__ */ new Map();
32595
+ const ledgerFloor = utcDate2(daysSinceMs);
32596
+ const ledgerScope = (harness) => token && config.stack ? grokCacheScope(
32597
+ harness === "grok-build" ? deps.baseUrl : `${deps.baseUrl}\0${harness}`,
32598
+ config.stack.slug,
32599
+ token
32600
+ ) : null;
32305
32601
  for (const { adapter, recent } of readings) {
32306
32602
  if (!recent) continue;
32307
32603
  const { aggregate, stats } = recent;
@@ -32326,8 +32622,19 @@ async function stageSync(deps) {
32326
32622
  dayScansComplete = false;
32327
32623
  partialHarnesses.add(adapter.name);
32328
32624
  }
32329
- if (adapter.name === "grok-build" || adapter.name === "cursor")
32330
- sessionDatesByHarness.set(adapter.name, sessionDates ?? /* @__PURE__ */ new Map());
32625
+ const scope = ledgerScope(adapter.name);
32626
+ const ledger = scope ? readSessionLedger(
32627
+ loadGrokDateHints(scope, deps.sessionLedgerFile),
32628
+ sessionDates ?? aggregate.sessionDays,
32629
+ ledgerFloor
32630
+ ) : void 0;
32631
+ if (scope && ledger) {
32632
+ ledgers.set(adapter.name, ledger);
32633
+ acknowledgements.push(
32634
+ () => saveGrokDateHints(scope, ledger.next, deps.sessionLedgerFile)
32635
+ );
32636
+ }
32637
+ const wholeHarnessPartial = partialHarnesses.has(adapter.name);
32331
32638
  workflowScans.push({ aggregate: workflow2, local: workflowLocal });
32332
32639
  usageScans.push(
32333
32640
  buildUsageDays({
@@ -32335,10 +32642,14 @@ async function stageSync(deps) {
32335
32642
  aggregate,
32336
32643
  publishCost: config.publishCost,
32337
32644
  projectWorkspaceId,
32645
+ accountId: harnessAccountId(adapter.name),
32338
32646
  // Old readings can hold a bare folder ID without root provenance.
32339
32647
  // A complete scan can replace it, while a partial union cannot tell
32340
- // whether the new root-scoped ID denotes that same workspace.
32341
- ...adapter.name === "claude-code" && partialHarnesses.has(adapter.name) ? { deferWorkspace: isClaudeWorkspaceFallback } : {}
32648
+ // whether the new root-scoped ID denotes that same workspace. A day
32649
+ // whose sessions were partly deleted is such a union too.
32650
+ ...adapter.name === "claude-code" ? {
32651
+ deferWorkspace: (directory, date) => (wholeHarnessPartial || (ledger?.partialDates.has(date) ?? false)) && isClaudeWorkspaceFallback(directory)
32652
+ } : {}
32342
32653
  })
32343
32654
  );
32344
32655
  }
@@ -32364,44 +32675,33 @@ async function stageSync(deps) {
32364
32675
  `git history \xB7 skipped (${config.publishWorkflow ? "no harness scanned" : "publishWorkflow off"})`
32365
32676
  );
32366
32677
  }
32367
- const correctionDates = /* @__PURE__ */ new Set();
32368
- let acknowledgePublish;
32369
- const acknowledgements = [];
32370
- for (const [harness, currentDates] of sessionDatesByHarness) {
32371
- if (!token || !config.stack) continue;
32372
- const scope = grokCacheScope(
32373
- harness === "grok-build" ? deps.baseUrl : `${deps.baseUrl}\0${harness}`,
32374
- config.stack.slug,
32375
- token
32376
- );
32377
- const floor = utcDate2(daysSinceMs);
32378
- const previous = loadGrokDateHints(scope);
32379
- const current = mapToHints(currentDates, floor);
32380
- for (const dates of Object.values(previous))
32381
- for (const date of dates) correctionDates.add(date);
32382
- for (const dates of Object.values(current))
32383
- for (const date of dates) correctionDates.add(date);
32384
- if (Object.keys(previous).some((id) => !(id in current))) {
32385
- dayScansComplete = false;
32386
- partialHarnesses.add(harness);
32387
- }
32388
- acknowledgements.push(() => saveGrokDateHints(scope, current));
32389
- }
32390
- if (acknowledgements.length && dayScansComplete)
32391
- acknowledgePublish = () => {
32392
- for (const acknowledge of acknowledgements) acknowledge();
32393
- };
32394
- const localDays = applyDayConsent(
32395
- buildMeasuredDays({
32396
- usage: mergeUsageDays(usageScans),
32397
- ...workflow ? { workflow: workflow.days } : {},
32398
- from: utcDate2(daysSinceMs),
32399
- to: utcDate2(now),
32400
- // A partial scan cannot prove that a formerly dated session disappeared.
32401
- includeDates: dayScansComplete ? correctionDates : /* @__PURE__ */ new Set()
32402
- }),
32403
- config
32678
+ const clearable = new Map(
32679
+ [...ledgers].filter(([harness]) => !partialHarnesses.has(harness))
32404
32680
  );
32681
+ const clearDates = new Set(
32682
+ [...clearable.values()].flatMap((ledger) => [...ledger.clearDates])
32683
+ );
32684
+ const acknowledgePublish = acknowledgements.length ? () => {
32685
+ for (const acknowledge of acknowledgements) acknowledge();
32686
+ } : void 0;
32687
+ const localDays = markDeletedEvidence(
32688
+ applyDayConsent(
32689
+ buildMeasuredDays({
32690
+ usage: mergeUsageDays(usageScans),
32691
+ ...workflow ? { workflow: workflow.days } : {},
32692
+ from: utcDate2(daysSinceMs),
32693
+ to: utcDate2(now),
32694
+ includeDates: clearDates
32695
+ }),
32696
+ config
32697
+ ),
32698
+ { ledgers, clearable, partialHarnesses }
32699
+ );
32700
+ const deletedDays = localDays.filter((day) => day.partialHarnesses).length;
32701
+ if (deletedDays)
32702
+ trace(
32703
+ `days \xB7 ${deletedDays} with deleted local sessions; the published reading is kept`
32704
+ );
32405
32705
  const days = selectDaysToPublish({
32406
32706
  local: localDays,
32407
32707
  manifest,
@@ -32618,6 +32918,7 @@ async function runAutoSync(deps) {
32618
32918
  failure2 = staged.blockedReason;
32619
32919
  } else {
32620
32920
  const res = await publish(staged.token, staged.bodyJson);
32921
+ staged.acknowledgePublish?.();
32621
32922
  url = res.url;
32622
32923
  }
32623
32924
  }