@use-aistack/cli 0.22.1 → 0.23.0

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.0" : "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);
@@ -22156,7 +22201,10 @@ function noteSyntheticTokens(agg, tsMs, tokens) {
22156
22201
  function noteSessionStart(agg, sessionId, tsMs) {
22157
22202
  if (tsMs === null) return;
22158
22203
  const held = agg.sessionStarts.get(sessionId);
22159
- if (held === void 0 || tsMs < held) agg.sessionStarts.set(sessionId, tsMs);
22204
+ if (held === void 0 || tsMs < held) {
22205
+ agg.sessionStarts.set(sessionId, tsMs);
22206
+ agg.sessionAccounts.set(sessionId, currentAccount(agg));
22207
+ }
22160
22208
  }
22161
22209
  function noteProjectDay(agg, directory, tsMs) {
22162
22210
  if (tsMs === null) return;
@@ -22205,7 +22253,8 @@ function createAggregate() {
22205
22253
  webFetchRequests: 0,
22206
22254
  seen: /* @__PURE__ */ new Map(),
22207
22255
  usageDays: /* @__PURE__ */ new Map(),
22208
- sessionStarts: /* @__PURE__ */ new Map()
22256
+ sessionStarts: /* @__PURE__ */ new Map(),
22257
+ sessionAccounts: /* @__PURE__ */ new Map()
22209
22258
  };
22210
22259
  }
22211
22260
  var bump = (m, k, n = 1) => m.set(k, (m.get(k) ?? 0) + n);
@@ -24727,7 +24776,13 @@ function ingestAssistant(agg, rec, tsMs) {
24727
24776
  }
24728
24777
  if (tsMs === null) agg.untimestampedResponses++;
24729
24778
  const sidechain = rec.isSidechain === true;
24730
- const contribution = buildContribution(usage, model, sidechain, tsMs);
24779
+ const contribution = buildContribution(
24780
+ usage,
24781
+ model,
24782
+ sidechain,
24783
+ tsMs,
24784
+ currentAccount(agg)
24785
+ );
24731
24786
  if (messageId === null) {
24732
24787
  agg.unkeyedResponses++;
24733
24788
  acceptContribution(agg, contribution);
@@ -24789,7 +24844,7 @@ function makeEntry(modelKey, counts2, tsMs) {
24789
24844
  costUSD: apiEquivalentCost(modelKey, counts2, tsMs)
24790
24845
  };
24791
24846
  }
24792
- function buildContribution(usage, model, sidechain, tsMs) {
24847
+ function buildContribution(usage, model, sidechain, tsMs, account) {
24793
24848
  const modelKey = modelKeyFor2(model, asStr(usage.speed));
24794
24849
  const entries = [makeEntry(modelKey, readCounts(usage), tsMs)];
24795
24850
  const mirrored = /* @__PURE__ */ new Map();
@@ -24827,7 +24882,8 @@ function buildContribution(usage, model, sidechain, tsMs) {
24827
24882
  webFetch: serverTools ? asNum(serverTools.web_fetch_requests) : 0,
24828
24883
  mirroredIterationTypes: [...mirrored],
24829
24884
  fallbackAttempts,
24830
- untypedMirrors
24885
+ untypedMirrors,
24886
+ account
24831
24887
  };
24832
24888
  }
24833
24889
  function applyContribution(agg, c, sign) {
@@ -24848,7 +24904,14 @@ function applyContribution(agg, c, sign) {
24848
24904
  else m.costUSD += sign * costUSD;
24849
24905
  noteUsageResponse(
24850
24906
  agg,
24851
- { tsMs: c.tsMs, modelKey, counts: counts2, costUSD, sidechain: c.sidechain },
24907
+ {
24908
+ tsMs: c.tsMs,
24909
+ modelKey,
24910
+ counts: counts2,
24911
+ costUSD,
24912
+ sidechain: c.sidechain,
24913
+ account: c.account
24914
+ },
24852
24915
  sign
24853
24916
  );
24854
24917
  });
@@ -25071,17 +25134,27 @@ async function discoverClaudeRoots() {
25071
25134
  }
25072
25135
  const roots = /* @__PURE__ */ new Set();
25073
25136
  const accounts = /* @__PURE__ */ new Set();
25137
+ const rootAccounts = /* @__PURE__ */ new Map();
25138
+ const groupRoots = /* @__PURE__ */ new Map();
25074
25139
  for (const profile of profiles) {
25075
25140
  try {
25076
25141
  const projects = await realpath3(path4.join(profile, "projects"));
25077
25142
  if (!(await stat4(projects)).isDirectory()) continue;
25078
25143
  roots.add(projects);
25079
- if (!groups.has(profile)) accounts.add(await realpath3(profile));
25144
+ if (groups.has(profile)) {
25145
+ if (!groupRoots.has(projects)) groupRoots.set(projects, profile);
25146
+ continue;
25147
+ }
25148
+ const account = await realpath3(profile);
25149
+ accounts.add(account);
25150
+ if (!rootAccounts.has(projects)) rootAccounts.set(projects, account);
25080
25151
  } catch (error) {
25081
25152
  failed(error);
25082
25153
  }
25083
25154
  }
25084
- return { roots: [...roots], profiles: [...accounts], complete };
25155
+ for (const [projects, group] of groupRoots)
25156
+ if (!rootAccounts.has(projects)) rootAccounts.set(projects, group);
25157
+ return { roots: [...roots], profiles: [...accounts], rootAccounts, complete };
25085
25158
  }
25086
25159
 
25087
25160
  // src/harness/claude/scan.ts
@@ -25119,6 +25192,7 @@ async function scan2(agg, opts = {}) {
25119
25192
  stats.sourceDiscoveryComplete = discovery.complete;
25120
25193
  for (const root of discovery.roots) {
25121
25194
  if (!await exists(root)) continue;
25195
+ agg.account = discovery.rootAccounts?.get(root) ?? root;
25122
25196
  for await (const file of walkJsonl(root)) {
25123
25197
  stats.filesFound++;
25124
25198
  let resolved;
@@ -25666,6 +25740,7 @@ async function scanWindows(windows, opts = {}) {
25666
25740
  });
25667
25741
  if (!eligible.length) continue;
25668
25742
  for (const { aggregate, stats, onProgress } of eligible) {
25743
+ aggregate.account = root;
25669
25744
  aggregate.files++;
25670
25745
  stats.filesRead++;
25671
25746
  if (aggregate.files % 20 === 0) onProgress?.(aggregate.files);
@@ -26939,31 +27014,41 @@ function isPageByteLimit(error) {
26939
27014
  }
26940
27015
 
26941
27016
  // src/harness/cursor/account.ts
27017
+ var ENCRYPTED_PREFIX = "cursor-safe-storage:";
26942
27018
  var digest = (value) => createHash7("sha256").update(value).digest("hex");
26943
27019
  async function existingAccount(root) {
27020
+ let value;
26944
27021
  let db;
26945
27022
  try {
26946
27023
  const { DatabaseSync } = await import("node:sqlite");
26947
27024
  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, "");
27025
+ value = db.prepare("SELECT value FROM ItemTable WHERE key = ?").get("cursorAuth/accessToken")?.value;
27026
+ } catch (error) {
27027
+ traceError("cursor account lookup", error, "warn");
27028
+ return null;
27029
+ } finally {
27030
+ db?.close();
27031
+ }
27032
+ if (typeof value !== "string") return null;
27033
+ const token = value.trim().replace(/^"|"$/g, "");
27034
+ if (token.startsWith(ENCRYPTED_PREFIX)) {
27035
+ trace("cursor account \xB7 sign-in is encrypted at rest", "warn");
27036
+ return { problem: "encrypted" };
27037
+ }
27038
+ try {
26951
27039
  const claims = asObj(
26952
27040
  JSON.parse(
26953
27041
  Buffer.from(token.split(".")[1] ?? "", "base64url").toString("utf8")
26954
27042
  )
26955
27043
  );
26956
27044
  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;
27045
+ const user = subject?.split("|").at(-1);
27046
+ if (!subject || !user || claims?.type === "api_key_token" || !/^[\w|:-]+$/.test(subject) || !/^[A-Za-z0-9_.-]+$/.test(token))
27047
+ return { problem: "unreadable" };
26961
27048
  return { scope: digest(subject), cookie: `${user}%3A%3A${token}` };
26962
27049
  } catch (error) {
26963
- traceError("cursor account lookup", error, "warn");
26964
- return null;
26965
- } finally {
26966
- db?.close();
27050
+ traceError("cursor account token", error, "warn");
27051
+ return { problem: "unreadable" };
26967
27052
  }
26968
27053
  }
26969
27054
  function apiContribution(value) {
@@ -27173,6 +27258,17 @@ async function saveCache(file, value) {
27173
27258
  await writeFile3(temporary, JSON.stringify(value), { mode: 384 });
27174
27259
  await rename2(temporary, file);
27175
27260
  }
27261
+ function refreshFailure(error) {
27262
+ const status = error?.status;
27263
+ if (typeof status === "number")
27264
+ return `the usage request failed (HTTP ${status})`;
27265
+ const name = error?.name;
27266
+ if (name === "TimeoutError" || name === "AbortError")
27267
+ return "the usage request timed out";
27268
+ if (error instanceof TypeError)
27269
+ return "the usage request could not reach cursor.com";
27270
+ return "Cursor answered in a form this version cannot read";
27271
+ }
27176
27272
  var REFRESH_MS = 3e5;
27177
27273
  var WINDOW_MS = 30 * 864e5;
27178
27274
  async function refreshAccount(input) {
@@ -27183,6 +27279,7 @@ async function refreshAccount(input) {
27183
27279
  state.account = account.scope;
27184
27280
  state.windows = {};
27185
27281
  state.failedAt = void 0;
27282
+ state.failure = void 0;
27186
27283
  }
27187
27284
  const changed = cache.account !== account.scope;
27188
27285
  const next = {
@@ -27192,6 +27289,7 @@ async function refreshAccount(input) {
27192
27289
  };
27193
27290
  if (state?.failedAt !== void 0 && now - state.failedAt < REFRESH_MS)
27194
27291
  return next;
27292
+ if (state) state.failure = void 0;
27195
27293
  for (let from = Math.floor(input.sinceMs / WINDOW_MS) * WINDOW_MS; from <= now; from += WINDOW_MS) {
27196
27294
  const to = Math.min(from + WINDOW_MS, now + 1);
27197
27295
  const key2 = String(from);
@@ -27202,7 +27300,10 @@ async function refreshAccount(input) {
27202
27300
  if (previous?.events.length && events.length === 0 && to <= now) continue;
27203
27301
  next.windows[key2] = { from, to, fetchedAt: now, events };
27204
27302
  } catch (error) {
27205
- if (state) state.failedAt = now;
27303
+ if (state) {
27304
+ state.failedAt = now;
27305
+ state.failure = refreshFailure(error);
27306
+ }
27206
27307
  traceError(
27207
27308
  "cursor account usage refresh (using local and previously cached usage)",
27208
27309
  error,
@@ -27461,6 +27562,10 @@ function projectHistory(options) {
27461
27562
 
27462
27563
  // src/harness/cursor/scan.ts
27463
27564
  var accountRefreshes = /* @__PURE__ */ new Map();
27565
+ var ACCOUNT_PROBLEMS = {
27566
+ encrypted: "Cursor keeps its sign-in encrypted in the system keychain",
27567
+ unreadable: "the stored Cursor sign-in could not be read"
27568
+ };
27464
27569
  async function readFolder(root, options, now, onProgress) {
27465
27570
  const file = typeof options.cachePath === "function" ? options.cachePath(root) : options.cachePath ?? cacheFile(root, storeRoot());
27466
27571
  const local = await (options.readLocalImpl ?? readLocal)(root, onProgress);
@@ -27477,7 +27582,8 @@ async function readFolder(root, options, now, onProgress) {
27477
27582
  );
27478
27583
  complete = false;
27479
27584
  }
27480
- const account = ids.size ? await (options.accountImpl ?? existingAccount)(root) : null;
27585
+ const lookup = ids.size ? await (options.accountImpl ?? existingAccount)(root) : null;
27586
+ const account = lookup && "scope" in lookup ? lookup : null;
27481
27587
  const refreshKey = JSON.stringify([root, storeRoot(), file]);
27482
27588
  let refreshState = accountRefreshes.get(refreshKey);
27483
27589
  if (!refreshState) {
@@ -27493,6 +27599,20 @@ async function readFolder(root, options, now, onProgress) {
27493
27599
  fetchImpl: options.fetchImpl,
27494
27600
  state: refreshState
27495
27601
  });
27602
+ let accountMissing;
27603
+ if (lookup && "problem" in lookup)
27604
+ accountMissing = {
27605
+ reason: ACCOUNT_PROBLEMS[lookup.problem],
27606
+ retained: true
27607
+ };
27608
+ else if (account && refreshState.failure)
27609
+ accountMissing = { reason: refreshState.failure, retained: true };
27610
+ else if (ids.size && !account)
27611
+ accountMissing = {
27612
+ reason: "Cursor is not signed in on this machine",
27613
+ retained: false
27614
+ };
27615
+ if (accountMissing?.retained) complete = false;
27496
27616
  const api = cachedEvents(cache, ids);
27497
27617
  const contributions = local.sessions.flatMap(
27498
27618
  (s) => localContributions(s, api)
@@ -27523,7 +27643,8 @@ async function readFolder(root, options, now, onProgress) {
27523
27643
  api,
27524
27644
  contributions,
27525
27645
  previous: [...loaded.value.local, ...cachedEvents(loaded.value, ids)],
27526
- complete
27646
+ complete,
27647
+ ...accountMissing ? { accountMissing } : {}
27527
27648
  };
27528
27649
  }
27529
27650
  function dedupeNative(rows) {
@@ -27589,6 +27710,11 @@ async function scan4(options) {
27589
27710
  });
27590
27711
  }
27591
27712
  const owns = (index) => (row) => owner.get(row.session)?.folder === index;
27713
+ const folderRoots = roots;
27714
+ const accountOf = (session) => {
27715
+ const folder = owner.get(session)?.folder;
27716
+ return folder === void 0 ? "" : folderRoots[folder] ?? "";
27717
+ };
27592
27718
  const local = {
27593
27719
  sessions: folders.flatMap(
27594
27720
  (f, index) => f.local.sessions.filter(
@@ -27599,6 +27725,11 @@ async function scan4(options) {
27599
27725
  stats: emptyScanStats()
27600
27726
  };
27601
27727
  for (const folder of folders) addStats(local.stats, folder.local.stats);
27728
+ const missing = folders.flatMap(
27729
+ (f) => f.local.sessions.length ? [f.accountMissing] : []
27730
+ );
27731
+ const accountMissing = missing.find((m) => m?.retained) ?? (missing.length && missing.every(Boolean) ? missing[0] : void 0);
27732
+ if (accountMissing) local.stats.accountUsageMissing = accountMissing;
27602
27733
  if (!discoveryComplete) local.stats.sourceDiscoveryComplete = false;
27603
27734
  const api = folders.flatMap((f, index) => f.api.filter(owns(index)));
27604
27735
  const contributions = dedupeNative(
@@ -27637,6 +27768,7 @@ async function scan4(options) {
27637
27768
  }
27638
27769
  if (firstTime !== null) {
27639
27770
  aggregate.sessions.add(session.id);
27771
+ aggregate.account = accountOf(session.id);
27640
27772
  noteSessionStart(aggregate, session.id, firstTime);
27641
27773
  }
27642
27774
  }
@@ -27657,6 +27789,7 @@ async function scan4(options) {
27657
27789
  sessionDates.set(session, dates);
27658
27790
  if (tsMs < options.sinceMs || tsMs > now) continue;
27659
27791
  const model = normalizeModel(contribution.model);
27792
+ aggregate.account = accountOf(session);
27660
27793
  const counts2 = {
27661
27794
  input: buckets.input ?? 0,
27662
27795
  output: buckets.output ?? 0,
@@ -28393,7 +28526,7 @@ async function scanWindows2(windows, opts = {}) {
28393
28526
  const held = candidates.get(sessionId);
28394
28527
  const total = (values) => values.flatMap((value) => value.models).reduce((sum, model) => sum + countsTotal(model.counts), 0);
28395
28528
  if (!held || precedence > held.precedence || precedence === held.precedence && total(windowRows) > total(held.rows))
28396
- candidates.set(sessionId, { precedence, rows: windowRows });
28529
+ candidates.set(sessionId, { precedence, rows: windowRows, root });
28397
28530
  }
28398
28531
  onProgress?.(stats.filesFound);
28399
28532
  }
@@ -28429,7 +28562,8 @@ async function scanWindows2(windows, opts = {}) {
28429
28562
  }
28430
28563
  }
28431
28564
  for (const { aggregate, candidates, sessionDates } of targets) {
28432
- for (const { rows } of candidates.values()) {
28565
+ for (const { rows, root } of candidates.values()) {
28566
+ aggregate.account = root;
28433
28567
  for (const row of rows) {
28434
28568
  ingestContribution(aggregate, row);
28435
28569
  const dates = sessionDates.get(row.sessionId) ?? /* @__PURE__ */ new Set();
@@ -28710,29 +28844,31 @@ async function dbFilesIn(root) {
28710
28844
  async function storeFiles2(roots) {
28711
28845
  const dirs = roots ?? (await opencodeDataDirs()).homes;
28712
28846
  const candidates = [];
28713
- for (const root of dirs) candidates.push(...await dbFilesIn(root));
28847
+ for (const root of dirs)
28848
+ for (const file of await dbFilesIn(root))
28849
+ candidates.push({ file, account: root });
28714
28850
  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
- )
28851
+ if (override) {
28852
+ const file = path15.resolve(
28853
+ process.env.XDG_DATA_HOME?.trim() || path15.join(homedir18(), ".local", "share"),
28854
+ "opencode",
28855
+ override
28722
28856
  );
28857
+ candidates.push({ file, account: file });
28858
+ }
28723
28859
  const files = [];
28724
28860
  const seen = /* @__PURE__ */ new Set();
28725
- for (const file of candidates) {
28726
- let key2 = file;
28861
+ for (const candidate of candidates) {
28862
+ let key2 = candidate.file;
28727
28863
  try {
28728
- key2 = await realpath5(file);
28864
+ key2 = await realpath5(candidate.file);
28729
28865
  } catch (error) {
28730
28866
  if (error?.code !== "ENOENT")
28731
28867
  traceError("opencode database path resolution", error, "warn");
28732
28868
  }
28733
28869
  if (seen.has(key2)) continue;
28734
28870
  seen.add(key2);
28735
- files.push(file);
28871
+ files.push(candidate);
28736
28872
  }
28737
28873
  return files;
28738
28874
  }
@@ -28759,9 +28895,10 @@ async function scan6(agg, opts = {}) {
28759
28895
  const sinceMs = opts.sinceMs ?? 0;
28760
28896
  const state = createDbFoldState();
28761
28897
  readConfiguredMcpServers2(agg, state, opts.configFile);
28762
- for (const file of await storeFiles2(opts.roots)) {
28898
+ for (const { file, account } of await storeFiles2(opts.roots)) {
28763
28899
  stats.filesFound++;
28764
28900
  agg.files++;
28901
+ agg.account = account;
28765
28902
  try {
28766
28903
  if (open4 === null) throw readError3("sqlite-unsupported");
28767
28904
  readDb(agg, state, open4, file, sinceMs);
@@ -29009,7 +29146,7 @@ function stripJsonc(text) {
29009
29146
  async function detectOpencode(opts) {
29010
29147
  const open4 = await loadSqlite2();
29011
29148
  if (open4 === null) return false;
29012
- for (const file of await storeFiles2(opts.roots)) {
29149
+ for (const { file } of await storeFiles2(opts.roots)) {
29013
29150
  if (!await exists4(file)) continue;
29014
29151
  let db = null;
29015
29152
  try {
@@ -29310,6 +29447,7 @@ async function scan7(agg, opts = {}) {
29310
29447
  stats.sourceDiscoveryComplete = discovery.complete;
29311
29448
  for (const root of discovery.homes) {
29312
29449
  if (!await exists5(root)) continue;
29450
+ agg.account = root;
29313
29451
  for await (const file of walkSessions(root)) {
29314
29452
  stats.filesFound++;
29315
29453
  let resolved;
@@ -30886,6 +31024,22 @@ function buildUsageDays(input) {
30886
31024
  const dates = [
30887
31025
  .../* @__PURE__ */ new Set([...agg.usageDays.keys(), ...sessionsByDay.keys()])
30888
31026
  ].sort();
31027
+ const sessionsByAccountDay = /* @__PURE__ */ new Map();
31028
+ for (const [session, startMs] of agg.sessionStarts) {
31029
+ const date = utcDateOf(startMs);
31030
+ const account = agg.sessionAccounts.get(session) ?? "";
31031
+ const byAccount = sessionsByAccountDay.get(date) ?? /* @__PURE__ */ new Map();
31032
+ byAccount.set(account, (byAccount.get(account) ?? 0) + 1);
31033
+ sessionsByAccountDay.set(date, byAccount);
31034
+ }
31035
+ const accountKeys = /* @__PURE__ */ new Set();
31036
+ for (const byAccount of sessionsByAccountDay.values())
31037
+ for (const key2 of byAccount.keys()) accountKeys.add(key2);
31038
+ for (const day of agg.usageDays.values())
31039
+ for (const [key2, models] of day.accounts)
31040
+ if ([...models.values()].some((c) => countsTotal(c) !== 0))
31041
+ accountKeys.add(key2);
31042
+ const accountId = input.accountId && accountKeys.size > 1 ? input.accountId : void 0;
30889
31043
  const out = /* @__PURE__ */ new Map();
30890
31044
  for (const date of dates) {
30891
31045
  const acc = agg.usageDays.get(date);
@@ -30942,11 +31096,82 @@ function buildUsageDays(input) {
30942
31096
  ...included.length < directories2.length ? { workspaceEvidenceIncomplete: true } : {},
30943
31097
  models,
30944
31098
  subagentTokens: acc?.subagentTokens ?? 0,
30945
- excludedTokens: { unpriced, synthetic: acc?.syntheticTokens ?? 0 }
31099
+ excludedTokens: { unpriced, synthetic: acc?.syntheticTokens ?? 0 },
31100
+ ...accountId ? {
31101
+ accounts: accountsOfDay(
31102
+ acc,
31103
+ sessionsByAccountDay.get(date),
31104
+ accountId
31105
+ )
31106
+ } : {}
30946
31107
  });
30947
31108
  }
30948
31109
  return out;
30949
31110
  }
31111
+ function wireTokens(c) {
31112
+ const plain = {
31113
+ input: c.input,
31114
+ output: c.output,
31115
+ cacheWrite: c.cacheWrite5m + c.cacheWrite1h + c.cacheWriteUnsplit,
31116
+ cacheRead: c.cacheRead
31117
+ };
31118
+ return plain.cacheWrite > 0 ? {
31119
+ ...plain,
31120
+ cacheWriteTtl: {
31121
+ fiveMinute: c.cacheWrite5m,
31122
+ oneHour: c.cacheWrite1h,
31123
+ unsplit: c.cacheWriteUnsplit
31124
+ }
31125
+ } : plain;
31126
+ }
31127
+ function accountsOfDay(acc, sessions, accountId) {
31128
+ const keys = /* @__PURE__ */ new Set([
31129
+ ...acc?.accounts.keys() ?? [],
31130
+ ...sessions?.keys() ?? []
31131
+ ]);
31132
+ const out = [];
31133
+ for (const key2 of keys) {
31134
+ const groups = /* @__PURE__ */ new Map();
31135
+ const total = emptyCounts2();
31136
+ for (const [modelKey, counts2] of acc?.accounts.get(key2) ?? []) {
31137
+ const id = sanitizeModelId(baseModelId(modelKey));
31138
+ const g = groups.get(id) ?? emptyCounts2();
31139
+ addCounts2(g, counts2);
31140
+ groups.set(id, g);
31141
+ addCounts2(total, counts2);
31142
+ }
31143
+ const models = [...groups.entries()].map(([model, counts2]) => ({ model, tokens: wireTokens(counts2) })).filter((row) => countsTotalOf(row.tokens) > 0).sort(
31144
+ (a, b) => countsTotalOf(b.tokens) - countsTotalOf(a.tokens) || a.model.localeCompare(b.model)
31145
+ );
31146
+ const count2 = sessions?.get(key2) ?? 0;
31147
+ if (count2 === 0 && models.length === 0) continue;
31148
+ out.push({
31149
+ account: accountId(key2),
31150
+ sessions: count2,
31151
+ tokens: wireTokens(total),
31152
+ models
31153
+ });
31154
+ }
31155
+ return out.sort(
31156
+ (a, b) => a.account < b.account ? -1 : a.account > b.account ? 1 : 0
31157
+ );
31158
+ }
31159
+ var emptyCounts2 = () => ({
31160
+ input: 0,
31161
+ output: 0,
31162
+ cacheWrite5m: 0,
31163
+ cacheWrite1h: 0,
31164
+ cacheWriteUnsplit: 0,
31165
+ cacheRead: 0
31166
+ });
31167
+ function addCounts2(into, c) {
31168
+ into.input += c.input;
31169
+ into.output += c.output;
31170
+ into.cacheWrite5m += c.cacheWrite5m;
31171
+ into.cacheWrite1h += c.cacheWrite1h;
31172
+ into.cacheWriteUnsplit += c.cacheWriteUnsplit;
31173
+ into.cacheRead += c.cacheRead;
31174
+ }
30950
31175
  var countsTotalOf = (t) => t.input + t.output + t.cacheWrite + t.cacheRead;
30951
31176
  function mergeUsageDays(perHarness) {
30952
31177
  const out = /* @__PURE__ */ new Map();
@@ -31770,6 +31995,13 @@ var KEPT_PRIVATE_ROWS_SHOWN = 3;
31770
31995
  var UNREADABLE_FILES_SHOWN = 5;
31771
31996
  function scanNoteLines(stats, label) {
31772
31997
  const out = [];
31998
+ const missing = stats.accountUsageMissing;
31999
+ if (missing) {
32000
+ out.push(
32001
+ `account ${label} usage not read: ${missing.reason}`,
32002
+ ` Tokens are estimated from message text.${missing.retained ? " Days already on aistack are kept." : ""}`
32003
+ );
32004
+ }
31773
32005
  const shown = stats.unreadableFiles.slice(0, UNREADABLE_FILES_SHOWN);
31774
32006
  for (const f of shown) {
31775
32007
  out.push(` ${f.path} (${f.reason})`);
@@ -31810,6 +32042,8 @@ function payloadBlock(payload, width, ownWindow, stats) {
31810
32042
  out.push(`${label.toUpperCase()} ${payload.activity.sessions}`);
31811
32043
  if (payload.activity.totalTokens === 0) {
31812
32044
  out.push(`usage ${totals.slice(1).join(" \xB7 ")}`);
32045
+ if (stats)
32046
+ out.push(...scanNoteLines(stats, harnessLabel2(payload.harness.name)));
31813
32047
  return out;
31814
32048
  }
31815
32049
  out.push(
@@ -32093,6 +32327,16 @@ async function stageSync(deps) {
32093
32327
  workspaceIds.set(directory, id);
32094
32328
  return id;
32095
32329
  };
32330
+ const resolveAccountId = deps.getHarnessAccountIdImpl ?? getHarnessAccountId;
32331
+ const accountIds = /* @__PURE__ */ new Map();
32332
+ const harnessAccountId = (harness) => (accountKey) => {
32333
+ const cacheKey = `${harness}\0${accountKey}`;
32334
+ const held = accountIds.get(cacheKey);
32335
+ if (held !== void 0) return held;
32336
+ const id = resolveAccountId(harness, accountKey);
32337
+ accountIds.set(cacheKey, id);
32338
+ return id;
32339
+ };
32096
32340
  const fetchManifest = deps.fetchManifestImpl ?? fetchDayManifest;
32097
32341
  const fetchPrices = deps.fetchPricesImpl ?? fetchPriceTable;
32098
32342
  const emit2 = (event) => deps.onEvent?.(event);
@@ -32335,6 +32579,7 @@ async function stageSync(deps) {
32335
32579
  aggregate,
32336
32580
  publishCost: config.publishCost,
32337
32581
  projectWorkspaceId,
32582
+ accountId: harnessAccountId(adapter.name),
32338
32583
  // Old readings can hold a bare folder ID without root provenance.
32339
32584
  // A complete scan can replace it, while a partial union cannot tell
32340
32585
  // whether the new root-scoped ID denotes that same workspace.