@use-aistack/cli 0.22.0 → 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.0" : "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
  });
@@ -24989,6 +25052,8 @@ function ingestTypedSkill(agg, rec, text) {
24989
25052
  import { readdir as readdir4, realpath as realpath3, stat as stat4 } from "node:fs/promises";
24990
25053
  import { homedir as homedir8 } from "node:os";
24991
25054
  import path4 from "node:path";
25055
+ var CLAUDE_HOMES_KEY = "claude";
25056
+ var CCS_HOMES_KEY = "ccs";
24992
25057
  async function discoverClaudeRoots() {
24993
25058
  const home = homedir8();
24994
25059
  const configHome = process.env.XDG_CONFIG_HOME || path4.join(home, ".config");
@@ -25010,41 +25075,86 @@ async function discoverClaudeRoots() {
25010
25075
  return [];
25011
25076
  }
25012
25077
  };
25013
- const configured = (process.env.CLAUDE_CONFIG_DIR ?? "").split(",").map((s) => s.trim()).filter(Boolean).map(
25014
- (dir) => path4.resolve(dir.startsWith("~/") ? path4.join(home, dir.slice(2)) : dir)
25015
- );
25016
- const profiles = /* @__PURE__ */ new Set([
25078
+ const ccsHome = process.env.CCS_HOME?.trim();
25079
+ const ccs = await discoverHomes({
25080
+ defaults: [path4.join(home, ".ccs")],
25081
+ configured: [process.env.CCS_DIR, ccsHome && path4.join(ccsHome, ".ccs")],
25082
+ remember: CCS_HOMES_KEY
25083
+ });
25084
+ if (!ccs.complete) complete = false;
25085
+ const contextGroups = /* @__PURE__ */ new Set();
25086
+ const managed = [];
25087
+ for (const dir of ccs.homes) {
25088
+ managed.push(...await children(path4.join(dir, "instances")));
25089
+ for (const group of await children(
25090
+ path4.join(dir, "shared", "context-groups")
25091
+ )) {
25092
+ contextGroups.add(group);
25093
+ managed.push(group);
25094
+ }
25095
+ }
25096
+ for (const account of await children(
25097
+ path4.join(home, ".cc-switch", "claude-accounts")
25098
+ ))
25099
+ managed.push(path4.join(account, "config"));
25100
+ for (const manager of [
25101
+ path4.join(home, ".claude-swap-backup"),
25102
+ path4.join(dataHome, "claude-swap")
25103
+ ]) {
25104
+ for (const collection of [manager, path4.join(manager, "sessions")])
25105
+ managed.push(...await children(collection));
25106
+ }
25107
+ const named = [
25017
25108
  path4.join(home, ".claude"),
25018
25109
  path4.join(configHome, "claude"),
25019
- ...configured,
25020
25110
  ...await children(home, ".claude"),
25021
- ...await children(configHome, "claude")
25022
- ]);
25111
+ ...await children(configHome, "claude"),
25112
+ ...managed
25113
+ ];
25114
+ const found = await discoverHomes({
25115
+ defaults: named,
25116
+ configured: (process.env.CLAUDE_CONFIG_DIR ?? "").split(","),
25117
+ remember: CLAUDE_HOMES_KEY
25118
+ });
25119
+ if (!found.complete) complete = false;
25120
+ const groups = /* @__PURE__ */ new Set();
25121
+ for (const group of contextGroups) {
25122
+ try {
25123
+ groups.add(await realpath3(group));
25124
+ } catch (error) {
25125
+ failed(error);
25126
+ }
25127
+ }
25128
+ const profiles = new Set(found.homes);
25023
25129
  for (const profile of [...profiles]) {
25024
25130
  for (const collection of ["profiles", "accounts"]) {
25025
25131
  for (const child of await children(path4.join(profile, collection)))
25026
25132
  profiles.add(child);
25027
25133
  }
25028
25134
  }
25029
- for (const manager of [
25030
- path4.join(home, ".claude-swap-backup"),
25031
- path4.join(dataHome, "claude-swap")
25032
- ]) {
25033
- for (const collection of [manager, path4.join(manager, "sessions")]) {
25034
- for (const child of await children(collection)) profiles.add(child);
25035
- }
25036
- }
25037
25135
  const roots = /* @__PURE__ */ new Set();
25136
+ const accounts = /* @__PURE__ */ new Set();
25137
+ const rootAccounts = /* @__PURE__ */ new Map();
25138
+ const groupRoots = /* @__PURE__ */ new Map();
25038
25139
  for (const profile of profiles) {
25039
- const projects = path4.join(profile, "projects");
25040
25140
  try {
25041
- if ((await stat4(projects)).isDirectory())
25042
- roots.add(await realpath3(projects));
25141
+ const projects = await realpath3(path4.join(profile, "projects"));
25142
+ if (!(await stat4(projects)).isDirectory()) continue;
25143
+ roots.add(projects);
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);
25043
25151
  } catch (error) {
25044
25152
  failed(error);
25045
25153
  }
25046
25154
  }
25047
- return { roots: [...roots], 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 };
25048
25158
  }
25049
25159
 
25050
25160
  // src/harness/claude/scan.ts
@@ -25082,6 +25192,7 @@ async function scan2(agg, opts = {}) {
25082
25192
  stats.sourceDiscoveryComplete = discovery.complete;
25083
25193
  for (const root of discovery.roots) {
25084
25194
  if (!await exists(root)) continue;
25195
+ agg.account = discovery.rootAccounts?.get(root) ?? root;
25085
25196
  for await (const file of walkJsonl(root)) {
25086
25197
  stats.filesFound++;
25087
25198
  let resolved;
@@ -25629,6 +25740,7 @@ async function scanWindows(windows, opts = {}) {
25629
25740
  });
25630
25741
  if (!eligible.length) continue;
25631
25742
  for (const { aggregate, stats, onProgress } of eligible) {
25743
+ aggregate.account = root;
25632
25744
  aggregate.files++;
25633
25745
  stats.filesRead++;
25634
25746
  if (aggregate.files % 20 === 0) onProgress?.(aggregate.files);
@@ -26902,31 +27014,41 @@ function isPageByteLimit(error) {
26902
27014
  }
26903
27015
 
26904
27016
  // src/harness/cursor/account.ts
27017
+ var ENCRYPTED_PREFIX = "cursor-safe-storage:";
26905
27018
  var digest = (value) => createHash7("sha256").update(value).digest("hex");
26906
27019
  async function existingAccount(root) {
27020
+ let value;
26907
27021
  let db;
26908
27022
  try {
26909
27023
  const { DatabaseSync } = await import("node:sqlite");
26910
27024
  db = new DatabaseSync(globalDb(root), { readOnly: true });
26911
- const row = db.prepare("SELECT value FROM ItemTable WHERE key = ?").get("cursorAuth/accessToken");
26912
- if (typeof row?.value !== "string") return null;
26913
- 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 {
26914
27039
  const claims = asObj(
26915
27040
  JSON.parse(
26916
27041
  Buffer.from(token.split(".")[1] ?? "", "base64url").toString("utf8")
26917
27042
  )
26918
27043
  );
26919
27044
  const subject = asStr(claims?.sub);
26920
- if (!subject || claims?.type === "api_key_token" || !/^[\w|:-]+$/.test(subject) || !/^[A-Za-z0-9_.-]+$/.test(token))
26921
- return null;
26922
- const user = subject.split("|").at(-1);
26923
- 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" };
26924
27048
  return { scope: digest(subject), cookie: `${user}%3A%3A${token}` };
26925
27049
  } catch (error) {
26926
- traceError("cursor account lookup", error, "warn");
26927
- return null;
26928
- } finally {
26929
- db?.close();
27050
+ traceError("cursor account token", error, "warn");
27051
+ return { problem: "unreadable" };
26930
27052
  }
26931
27053
  }
26932
27054
  function apiContribution(value) {
@@ -27136,6 +27258,17 @@ async function saveCache(file, value) {
27136
27258
  await writeFile3(temporary, JSON.stringify(value), { mode: 384 });
27137
27259
  await rename2(temporary, file);
27138
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
+ }
27139
27272
  var REFRESH_MS = 3e5;
27140
27273
  var WINDOW_MS = 30 * 864e5;
27141
27274
  async function refreshAccount(input) {
@@ -27146,6 +27279,7 @@ async function refreshAccount(input) {
27146
27279
  state.account = account.scope;
27147
27280
  state.windows = {};
27148
27281
  state.failedAt = void 0;
27282
+ state.failure = void 0;
27149
27283
  }
27150
27284
  const changed = cache.account !== account.scope;
27151
27285
  const next = {
@@ -27155,6 +27289,7 @@ async function refreshAccount(input) {
27155
27289
  };
27156
27290
  if (state?.failedAt !== void 0 && now - state.failedAt < REFRESH_MS)
27157
27291
  return next;
27292
+ if (state) state.failure = void 0;
27158
27293
  for (let from = Math.floor(input.sinceMs / WINDOW_MS) * WINDOW_MS; from <= now; from += WINDOW_MS) {
27159
27294
  const to = Math.min(from + WINDOW_MS, now + 1);
27160
27295
  const key2 = String(from);
@@ -27165,7 +27300,10 @@ async function refreshAccount(input) {
27165
27300
  if (previous?.events.length && events.length === 0 && to <= now) continue;
27166
27301
  next.windows[key2] = { from, to, fetchedAt: now, events };
27167
27302
  } catch (error) {
27168
- if (state) state.failedAt = now;
27303
+ if (state) {
27304
+ state.failedAt = now;
27305
+ state.failure = refreshFailure(error);
27306
+ }
27169
27307
  traceError(
27170
27308
  "cursor account usage refresh (using local and previously cached usage)",
27171
27309
  error,
@@ -27424,6 +27562,10 @@ function projectHistory(options) {
27424
27562
 
27425
27563
  // src/harness/cursor/scan.ts
27426
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
+ };
27427
27569
  async function readFolder(root, options, now, onProgress) {
27428
27570
  const file = typeof options.cachePath === "function" ? options.cachePath(root) : options.cachePath ?? cacheFile(root, storeRoot());
27429
27571
  const local = await (options.readLocalImpl ?? readLocal)(root, onProgress);
@@ -27440,7 +27582,8 @@ async function readFolder(root, options, now, onProgress) {
27440
27582
  );
27441
27583
  complete = false;
27442
27584
  }
27443
- 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;
27444
27587
  const refreshKey = JSON.stringify([root, storeRoot(), file]);
27445
27588
  let refreshState = accountRefreshes.get(refreshKey);
27446
27589
  if (!refreshState) {
@@ -27456,6 +27599,20 @@ async function readFolder(root, options, now, onProgress) {
27456
27599
  fetchImpl: options.fetchImpl,
27457
27600
  state: refreshState
27458
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;
27459
27616
  const api = cachedEvents(cache, ids);
27460
27617
  const contributions = local.sessions.flatMap(
27461
27618
  (s) => localContributions(s, api)
@@ -27486,7 +27643,8 @@ async function readFolder(root, options, now, onProgress) {
27486
27643
  api,
27487
27644
  contributions,
27488
27645
  previous: [...loaded.value.local, ...cachedEvents(loaded.value, ids)],
27489
- complete
27646
+ complete,
27647
+ ...accountMissing ? { accountMissing } : {}
27490
27648
  };
27491
27649
  }
27492
27650
  function dedupeNative(rows) {
@@ -27552,6 +27710,11 @@ async function scan4(options) {
27552
27710
  });
27553
27711
  }
27554
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
+ };
27555
27718
  const local = {
27556
27719
  sessions: folders.flatMap(
27557
27720
  (f, index) => f.local.sessions.filter(
@@ -27562,6 +27725,11 @@ async function scan4(options) {
27562
27725
  stats: emptyScanStats()
27563
27726
  };
27564
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;
27565
27733
  if (!discoveryComplete) local.stats.sourceDiscoveryComplete = false;
27566
27734
  const api = folders.flatMap((f, index) => f.api.filter(owns(index)));
27567
27735
  const contributions = dedupeNative(
@@ -27600,6 +27768,7 @@ async function scan4(options) {
27600
27768
  }
27601
27769
  if (firstTime !== null) {
27602
27770
  aggregate.sessions.add(session.id);
27771
+ aggregate.account = accountOf(session.id);
27603
27772
  noteSessionStart(aggregate, session.id, firstTime);
27604
27773
  }
27605
27774
  }
@@ -27620,6 +27789,7 @@ async function scan4(options) {
27620
27789
  sessionDates.set(session, dates);
27621
27790
  if (tsMs < options.sinceMs || tsMs > now) continue;
27622
27791
  const model = normalizeModel(contribution.model);
27792
+ aggregate.account = accountOf(session);
27623
27793
  const counts2 = {
27624
27794
  input: buckets.input ?? 0,
27625
27795
  output: buckets.output ?? 0,
@@ -28356,7 +28526,7 @@ async function scanWindows2(windows, opts = {}) {
28356
28526
  const held = candidates.get(sessionId);
28357
28527
  const total = (values) => values.flatMap((value) => value.models).reduce((sum, model) => sum + countsTotal(model.counts), 0);
28358
28528
  if (!held || precedence > held.precedence || precedence === held.precedence && total(windowRows) > total(held.rows))
28359
- candidates.set(sessionId, { precedence, rows: windowRows });
28529
+ candidates.set(sessionId, { precedence, rows: windowRows, root });
28360
28530
  }
28361
28531
  onProgress?.(stats.filesFound);
28362
28532
  }
@@ -28392,7 +28562,8 @@ async function scanWindows2(windows, opts = {}) {
28392
28562
  }
28393
28563
  }
28394
28564
  for (const { aggregate, candidates, sessionDates } of targets) {
28395
- for (const { rows } of candidates.values()) {
28565
+ for (const { rows, root } of candidates.values()) {
28566
+ aggregate.account = root;
28396
28567
  for (const row of rows) {
28397
28568
  ingestContribution(aggregate, row);
28398
28569
  const dates = sessionDates.get(row.sessionId) ?? /* @__PURE__ */ new Set();
@@ -28673,29 +28844,31 @@ async function dbFilesIn(root) {
28673
28844
  async function storeFiles2(roots) {
28674
28845
  const dirs = roots ?? (await opencodeDataDirs()).homes;
28675
28846
  const candidates = [];
28676
- 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 });
28677
28850
  const override = roots ? void 0 : process.env.OPENCODE_DB?.trim();
28678
- if (override)
28679
- candidates.push(
28680
- path15.resolve(
28681
- process.env.XDG_DATA_HOME?.trim() || path15.join(homedir18(), ".local", "share"),
28682
- "opencode",
28683
- override
28684
- )
28851
+ if (override) {
28852
+ const file = path15.resolve(
28853
+ process.env.XDG_DATA_HOME?.trim() || path15.join(homedir18(), ".local", "share"),
28854
+ "opencode",
28855
+ override
28685
28856
  );
28857
+ candidates.push({ file, account: file });
28858
+ }
28686
28859
  const files = [];
28687
28860
  const seen = /* @__PURE__ */ new Set();
28688
- for (const file of candidates) {
28689
- let key2 = file;
28861
+ for (const candidate of candidates) {
28862
+ let key2 = candidate.file;
28690
28863
  try {
28691
- key2 = await realpath5(file);
28864
+ key2 = await realpath5(candidate.file);
28692
28865
  } catch (error) {
28693
28866
  if (error?.code !== "ENOENT")
28694
28867
  traceError("opencode database path resolution", error, "warn");
28695
28868
  }
28696
28869
  if (seen.has(key2)) continue;
28697
28870
  seen.add(key2);
28698
- files.push(file);
28871
+ files.push(candidate);
28699
28872
  }
28700
28873
  return files;
28701
28874
  }
@@ -28722,9 +28895,10 @@ async function scan6(agg, opts = {}) {
28722
28895
  const sinceMs = opts.sinceMs ?? 0;
28723
28896
  const state = createDbFoldState();
28724
28897
  readConfiguredMcpServers2(agg, state, opts.configFile);
28725
- for (const file of await storeFiles2(opts.roots)) {
28898
+ for (const { file, account } of await storeFiles2(opts.roots)) {
28726
28899
  stats.filesFound++;
28727
28900
  agg.files++;
28901
+ agg.account = account;
28728
28902
  try {
28729
28903
  if (open4 === null) throw readError3("sqlite-unsupported");
28730
28904
  readDb(agg, state, open4, file, sinceMs);
@@ -28972,7 +29146,7 @@ function stripJsonc(text) {
28972
29146
  async function detectOpencode(opts) {
28973
29147
  const open4 = await loadSqlite2();
28974
29148
  if (open4 === null) return false;
28975
- for (const file of await storeFiles2(opts.roots)) {
29149
+ for (const { file } of await storeFiles2(opts.roots)) {
28976
29150
  if (!await exists4(file)) continue;
28977
29151
  let db = null;
28978
29152
  try {
@@ -29273,6 +29447,7 @@ async function scan7(agg, opts = {}) {
29273
29447
  stats.sourceDiscoveryComplete = discovery.complete;
29274
29448
  for (const root of discovery.homes) {
29275
29449
  if (!await exists5(root)) continue;
29450
+ agg.account = root;
29276
29451
  for await (const file of walkSessions(root)) {
29277
29452
  stats.filesFound++;
29278
29453
  let resolved;
@@ -29857,7 +30032,7 @@ import * as p7 from "@clack/prompts";
29857
30032
  // src/autosync/optin.ts
29858
30033
  import { existsSync as existsSync18 } from "node:fs";
29859
30034
  import { homedir as homedir27 } from "node:os";
29860
- import { dirname as dirname13, join as join20 } from "node:path";
30035
+ import { dirname as dirname12, join as join20 } from "node:path";
29861
30036
  import * as p6 from "@clack/prompts";
29862
30037
 
29863
30038
  // src/autosync/antigravityHook.ts
@@ -30369,7 +30544,7 @@ function grokAutoSyncHookInstalled(file = GROK_HOOK_FILE) {
30369
30544
  // src/autosync/homes.ts
30370
30545
  import { realpathSync as realpathSync4 } from "node:fs";
30371
30546
  import { homedir as homedir26 } from "node:os";
30372
- import { basename as basename5, dirname as dirname12, join as join19, relative as relative4, sep as sep3 } from "node:path";
30547
+ import { basename as basename5, join as join19, relative as relative4, sep as sep3 } from "node:path";
30373
30548
  var HOOK_HARNESSES = [
30374
30549
  "claude",
30375
30550
  "codex",
@@ -30400,8 +30575,8 @@ async function discoverHookHomes() {
30400
30575
  discoverGrokHomes()
30401
30576
  ]);
30402
30577
  return {
30403
- // A Claude Code profile is the folder that holds its `projects` folder.
30404
- claude: withDefault(join19(home, ".claude"), claude.roots.map(dirname12)),
30578
+ // Every Claude Code profile, remembered and CCS folders included.
30579
+ claude: withDefault(join19(home, ".claude"), claude.profiles),
30405
30580
  codex: withDefault(
30406
30581
  process.env.CODEX_HOME || join19(home, ".codex"),
30407
30582
  codex.homes
@@ -30733,7 +30908,7 @@ async function autoSyncStatus(deps = {}) {
30733
30908
  ]);
30734
30909
  }
30735
30910
  }
30736
- const cursorHome = dirname13(CURSOR_HOOK_FILE);
30911
+ const cursorHome = dirname12(CURSOR_HOOK_FILE);
30737
30912
  const cursorInstalled = (deps.cursorHookInstalledImpl ?? cursorAutoSyncHookInstalled)();
30738
30913
  if (cursorInstalled || existsSync18(cursorHome)) {
30739
30914
  rows.push([
@@ -30742,7 +30917,7 @@ async function autoSyncStatus(deps = {}) {
30742
30917
  cursorInstalled ? "hook installed" : "no hook"
30743
30918
  ]);
30744
30919
  }
30745
- const antigravityConfig = dirname13(antigravityHookFile());
30920
+ const antigravityConfig = dirname12(antigravityHookFile());
30746
30921
  const antigravityInstalled = (deps.antigravityHookInstalledImpl ?? antigravityAutoSyncHookInstalled)();
30747
30922
  if (antigravityInstalled || existsSync18(antigravityConfig)) {
30748
30923
  rows.push([
@@ -30832,7 +31007,7 @@ import {
30832
31007
  writeFileSync as writeFileSync11
30833
31008
  } from "node:fs";
30834
31009
  import { homedir as homedir29 } from "node:os";
30835
- import { dirname as dirname15, join as join21 } from "node:path";
31010
+ import { dirname as dirname14, join as join21 } from "node:path";
30836
31011
 
30837
31012
  // src/sync/stage.ts
30838
31013
  import { createHash as createHash11 } from "node:crypto";
@@ -30849,6 +31024,22 @@ function buildUsageDays(input) {
30849
31024
  const dates = [
30850
31025
  .../* @__PURE__ */ new Set([...agg.usageDays.keys(), ...sessionsByDay.keys()])
30851
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;
30852
31043
  const out = /* @__PURE__ */ new Map();
30853
31044
  for (const date of dates) {
30854
31045
  const acc = agg.usageDays.get(date);
@@ -30905,11 +31096,82 @@ function buildUsageDays(input) {
30905
31096
  ...included.length < directories2.length ? { workspaceEvidenceIncomplete: true } : {},
30906
31097
  models,
30907
31098
  subagentTokens: acc?.subagentTokens ?? 0,
30908
- 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
+ } : {}
30909
31107
  });
30910
31108
  }
30911
31109
  return out;
30912
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
+ }
30913
31175
  var countsTotalOf = (t) => t.input + t.output + t.cacheWrite + t.cacheRead;
30914
31176
  function mergeUsageDays(perHarness) {
30915
31177
  const out = /* @__PURE__ */ new Map();
@@ -31733,6 +31995,13 @@ var KEPT_PRIVATE_ROWS_SHOWN = 3;
31733
31995
  var UNREADABLE_FILES_SHOWN = 5;
31734
31996
  function scanNoteLines(stats, label) {
31735
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
+ }
31736
32005
  const shown = stats.unreadableFiles.slice(0, UNREADABLE_FILES_SHOWN);
31737
32006
  for (const f of shown) {
31738
32007
  out.push(` ${f.path} (${f.reason})`);
@@ -31773,6 +32042,8 @@ function payloadBlock(payload, width, ownWindow, stats) {
31773
32042
  out.push(`${label.toUpperCase()} ${payload.activity.sessions}`);
31774
32043
  if (payload.activity.totalTokens === 0) {
31775
32044
  out.push(`usage ${totals.slice(1).join(" \xB7 ")}`);
32045
+ if (stats)
32046
+ out.push(...scanNoteLines(stats, harnessLabel2(payload.harness.name)));
31776
32047
  return out;
31777
32048
  }
31778
32049
  out.push(
@@ -32056,6 +32327,16 @@ async function stageSync(deps) {
32056
32327
  workspaceIds.set(directory, id);
32057
32328
  return id;
32058
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
+ };
32059
32340
  const fetchManifest = deps.fetchManifestImpl ?? fetchDayManifest;
32060
32341
  const fetchPrices = deps.fetchPricesImpl ?? fetchPriceTable;
32061
32342
  const emit2 = (event) => deps.onEvent?.(event);
@@ -32298,6 +32579,7 @@ async function stageSync(deps) {
32298
32579
  aggregate,
32299
32580
  publishCost: config.publishCost,
32300
32581
  projectWorkspaceId,
32582
+ accountId: harnessAccountId(adapter.name),
32301
32583
  // Old readings can hold a bare folder ID without root provenance.
32302
32584
  // A complete scan can replace it, while a partial union cannot tell
32303
32585
  // whether the new root-scoped ID denotes that same workspace.
@@ -32452,7 +32734,7 @@ import {
32452
32734
  statSync as statSync7,
32453
32735
  writeFileSync as writeFileSync10
32454
32736
  } from "node:fs";
32455
- import { dirname as dirname14 } from "node:path";
32737
+ import { dirname as dirname13 } from "node:path";
32456
32738
  var MUTEX_WAIT_MS = 2e3;
32457
32739
  var MUTEX_STALE_MS = 3e4;
32458
32740
  var code = (error) => error?.code;
@@ -32491,7 +32773,7 @@ function isHeld(file, now, windowMs) {
32491
32773
  return Date.now() - statSync7(file).mtimeMs < windowMs;
32492
32774
  }
32493
32775
  function reserveAttempt(file, now, windowMs) {
32494
- mkdirSync10(dirname14(file), { recursive: true });
32776
+ mkdirSync10(dirname13(file), { recursive: true });
32495
32777
  const mutex = `${file}.lock`;
32496
32778
  if (!acquire(mutex)) return false;
32497
32779
  try {
@@ -32511,7 +32793,7 @@ var SYNC_LOG_MAX_LINES = 200;
32511
32793
  var FIX_COMMAND = "npx @use-aistack/cli@latest sync";
32512
32794
  var REVOKED_RESULT = "off - auto-sync is switched off for this stack";
32513
32795
  function appendLogLine(file, line) {
32514
- mkdirSync11(dirname15(file), { recursive: true });
32796
+ mkdirSync11(dirname14(file), { recursive: true });
32515
32797
  appendFileSync(file, `${line}
32516
32798
  `);
32517
32799
  const lines2 = readFileSync21(file, "utf-8").split("\n").filter(Boolean);