@use-aistack/cli 0.23.0 → 0.23.2

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.23.0" : "0.0.0-dev";
20359
+ var CLI_VERSION = true ? "0.23.2" : "0.0.0-dev";
20360
20360
 
20361
20361
  // src/api.ts
20362
20362
  var BASE_URL = process.env.AISTACK_URL || "https://aistack.to";
@@ -22200,6 +22200,10 @@ function noteSyntheticTokens(agg, tsMs, tokens) {
22200
22200
  }
22201
22201
  function noteSessionStart(agg, sessionId, tsMs) {
22202
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]));
22203
22207
  const held = agg.sessionStarts.get(sessionId);
22204
22208
  if (held === void 0 || tsMs < held) {
22205
22209
  agg.sessionStarts.set(sessionId, tsMs);
@@ -22254,6 +22258,7 @@ function createAggregate() {
22254
22258
  seen: /* @__PURE__ */ new Map(),
22255
22259
  usageDays: /* @__PURE__ */ new Map(),
22256
22260
  sessionStarts: /* @__PURE__ */ new Map(),
22261
+ sessionDays: /* @__PURE__ */ new Map(),
22257
22262
  sessionAccounts: /* @__PURE__ */ new Map()
22258
22263
  };
22259
22264
  }
@@ -26233,6 +26238,66 @@ function reconcile(local, api) {
26233
26238
  return [...local.filter((c) => !grains.has(grain(c))), ...reported];
26234
26239
  }
26235
26240
 
26241
+ // src/harness/cursor/keychain.ts
26242
+ import { execFile } from "node:child_process";
26243
+ import { createDecipheriv, pbkdf2Sync } from "node:crypto";
26244
+ var ENCRYPTED_PREFIX = "cursor-safe-storage:v1:";
26245
+ var KEYCHAIN_SERVICE = "Cursor Safe Storage";
26246
+ var runSecurity = (args) => new Promise((resolve3) => {
26247
+ execFile(
26248
+ "/usr/bin/security",
26249
+ args,
26250
+ { timeout: 12e4, encoding: "utf8" },
26251
+ (error, stdout) => {
26252
+ const code2 = error?.code;
26253
+ resolve3({
26254
+ code: error ? typeof code2 === "number" ? code2 : -1 : 0,
26255
+ stdout: error ? "" : stdout
26256
+ });
26257
+ }
26258
+ );
26259
+ });
26260
+ function macKeychainReader(platform5 = process.platform, run = runSecurity) {
26261
+ let held;
26262
+ return () => {
26263
+ held ??= (async () => {
26264
+ if (platform5 !== "darwin") return { failure: "unsupported" };
26265
+ const { code: code2, stdout } = await run([
26266
+ "find-generic-password",
26267
+ "-w",
26268
+ "-s",
26269
+ KEYCHAIN_SERVICE
26270
+ ]);
26271
+ if (code2 === 44) return { failure: "missing" };
26272
+ const password = stdout.replace(/\r?\n$/, "");
26273
+ if (code2 !== 0 || !password) return { failure: "denied" };
26274
+ return { password };
26275
+ })();
26276
+ return held;
26277
+ };
26278
+ }
26279
+ var cursorKeychain = macKeychainReader();
26280
+ var KEY_TAG = "v10";
26281
+ var SALT = "saltysalt";
26282
+ var MAC_ITERATIONS = 1003;
26283
+ var IV = Buffer.alloc(16, " ");
26284
+ function decryptCursorToken(stored, password, iterations = MAC_ITERATIONS) {
26285
+ if (!stored.startsWith(ENCRYPTED_PREFIX)) return null;
26286
+ const sealed = Buffer.from(stored.slice(ENCRYPTED_PREFIX.length), "base64");
26287
+ if (sealed.subarray(0, 3).toString("latin1") !== KEY_TAG) return null;
26288
+ const body = sealed.subarray(3);
26289
+ if (body.length === 0 || body.length % 16 !== 0) return null;
26290
+ try {
26291
+ const key2 = pbkdf2Sync(password, SALT, iterations, 16, "sha1");
26292
+ const decipher = createDecipheriv("aes-128-cbc", key2, IV);
26293
+ return Buffer.concat([decipher.update(body), decipher.final()]).toString(
26294
+ "utf8"
26295
+ );
26296
+ } catch {
26297
+ return null;
26298
+ }
26299
+ }
26300
+
26236
26301
  // src/harness/cursor/local.ts
26237
26302
  import { existsSync as existsSync10 } from "node:fs";
26238
26303
  import { stat as stat7 } from "node:fs/promises";
@@ -27014,9 +27079,8 @@ function isPageByteLimit(error) {
27014
27079
  }
27015
27080
 
27016
27081
  // src/harness/cursor/account.ts
27017
- var ENCRYPTED_PREFIX = "cursor-safe-storage:";
27018
27082
  var digest = (value) => createHash7("sha256").update(value).digest("hex");
27019
- async function existingAccount(root) {
27083
+ async function storedToken(root) {
27020
27084
  let value;
27021
27085
  let db;
27022
27086
  try {
@@ -27029,11 +27093,47 @@ async function existingAccount(root) {
27029
27093
  } finally {
27030
27094
  db?.close();
27031
27095
  }
27032
- if (typeof value !== "string") return null;
27033
- const token = value.trim().replace(/^"|"$/g, "");
27096
+ return typeof value === "string" ? value.trim().replace(/^"|"$/g, "") : null;
27097
+ }
27098
+ var KEYCHAIN_NOTICE = [
27099
+ "Cursor keeps your sign-in encrypted in the macOS Keychain.",
27100
+ 'To read your exact Cursor usage, aistack asks macOS for the "Cursor Safe Storage" key.',
27101
+ "Choose Always Allow so the prompt does not come back on every sync.",
27102
+ "If you deny it, Cursor tokens are estimated from message text.",
27103
+ "The key and your sign-in stay in memory and go only to cursor.com."
27104
+ ].join("\n");
27105
+ async function keychainNotice(roots, platform5 = process.platform) {
27106
+ if (platform5 !== "darwin") return null;
27107
+ for (const root of roots)
27108
+ if ((await storedToken(root))?.startsWith(ENCRYPTED_PREFIX))
27109
+ return KEYCHAIN_NOTICE;
27110
+ return null;
27111
+ }
27112
+ async function existingAccount(root, options = {}) {
27113
+ const stored = await storedToken(root);
27114
+ if (stored === null) return null;
27115
+ let token = stored;
27034
27116
  if (token.startsWith(ENCRYPTED_PREFIX)) {
27035
27117
  trace("cursor account \xB7 sign-in is encrypted at rest", "warn");
27036
- return { problem: "encrypted" };
27118
+ const read3 = options.keychain ? await options.keychain() : void 0;
27119
+ if (!read3 || "failure" in read3 && read3.failure === "unsupported")
27120
+ return { problem: "encrypted" };
27121
+ if ("failure" in read3) {
27122
+ trace(`cursor account \xB7 keychain ${read3.failure}`, "warn");
27123
+ return {
27124
+ problem: read3.failure === "missing" ? "keychain-missing" : "keychain-denied"
27125
+ };
27126
+ }
27127
+ const opened = decryptCursorToken(token, read3.password);
27128
+ if (opened === null) {
27129
+ trace(
27130
+ "cursor account \xB7 keychain password did not open the sign-in",
27131
+ "warn"
27132
+ );
27133
+ return { problem: "undecryptable" };
27134
+ }
27135
+ trace("cursor account \xB7 opened the encrypted sign-in");
27136
+ token = opened.trim();
27037
27137
  }
27038
27138
  try {
27039
27139
  const claims = asObj(
@@ -27564,6 +27664,9 @@ function projectHistory(options) {
27564
27664
  var accountRefreshes = /* @__PURE__ */ new Map();
27565
27665
  var ACCOUNT_PROBLEMS = {
27566
27666
  encrypted: "Cursor keeps its sign-in encrypted in the system keychain",
27667
+ "keychain-denied": "Keychain access to Cursor Safe Storage was denied",
27668
+ "keychain-missing": "the Cursor Safe Storage item is missing from the Keychain",
27669
+ undecryptable: "the encrypted Cursor sign-in could not be decrypted",
27567
27670
  unreadable: "the stored Cursor sign-in could not be read"
27568
27671
  };
27569
27672
  async function readFolder(root, options, now, onProgress) {
@@ -27582,7 +27685,10 @@ async function readFolder(root, options, now, onProgress) {
27582
27685
  );
27583
27686
  complete = false;
27584
27687
  }
27585
- const lookup = ids.size ? await (options.accountImpl ?? existingAccount)(root) : null;
27688
+ const lookup = ids.size ? await (options.accountImpl ?? existingAccount)(
27689
+ root,
27690
+ options.keychain ? { keychain: options.keychainImpl ?? cursorKeychain } : {}
27691
+ ) : null;
27586
27692
  const account = lookup && "scope" in lookup ? lookup : null;
27587
27693
  const refreshKey = JSON.stringify([root, storeRoot(), file]);
27588
27694
  let refreshState = accountRefreshes.get(refreshKey);
@@ -31088,7 +31194,9 @@ function buildUsageDays(input) {
31088
31194
  (a, b) => countsTotalOf(b.tokens) - countsTotalOf(a.tokens) || a.model.localeCompare(b.model)
31089
31195
  );
31090
31196
  const directories2 = [...acc?.projectDirs ?? []];
31091
- const included = input.deferWorkspace ? directories2.filter((directory) => !input.deferWorkspace?.(directory)) : directories2;
31197
+ const included = input.deferWorkspace ? directories2.filter(
31198
+ (directory) => !input.deferWorkspace?.(directory, date)
31199
+ ) : directories2;
31092
31200
  out.set(date, {
31093
31201
  harness,
31094
31202
  sessions: sessionsByDay.get(date) ?? 0,
@@ -31210,6 +31318,28 @@ function buildMeasuredDays(input) {
31210
31318
  };
31211
31319
  });
31212
31320
  }
31321
+ function markDeletedEvidence(days, input) {
31322
+ const out = [];
31323
+ for (const day of days) {
31324
+ const carried = /* @__PURE__ */ new Set([
31325
+ ...(day.usage?.harnesses ?? []).map((h) => h.harness),
31326
+ ...(day.workflow?.harnesses ?? []).map((h) => h.harness)
31327
+ ]);
31328
+ const partial = [...input.ledgers].filter(
31329
+ ([harness, ledger]) => carried.has(harness) && !input.partialHarnesses.has(harness) && ledger.partialDates.has(day.date)
31330
+ ).map(([harness]) => harness).sort();
31331
+ const cleared = [...input.clearable].filter(
31332
+ ([harness, ledger]) => !carried.has(harness) && ledger.clearDates.has(day.date)
31333
+ ).map(([harness]) => harness).sort();
31334
+ if (!day.usage && !day.workflow && cleared.length === 0) continue;
31335
+ out.push({
31336
+ ...day,
31337
+ ...partial.length ? { partialHarnesses: partial } : {},
31338
+ ...cleared.length ? { clearedHarnesses: cleared } : {}
31339
+ });
31340
+ }
31341
+ return out;
31342
+ }
31213
31343
 
31214
31344
  // src/usage/diff.ts
31215
31345
  var MAX_DAY_WINDOW = 400;
@@ -31253,7 +31383,7 @@ function selectDaysToPublish(input) {
31253
31383
  }
31254
31384
 
31255
31385
  // src/workflow/git.ts
31256
- import { execFile, execFileSync as execFileSync2 } from "node:child_process";
31386
+ import { execFile as execFile2, execFileSync as execFileSync2 } from "node:child_process";
31257
31387
  import { existsSync as existsSync19 } from "node:fs";
31258
31388
  import path19 from "node:path";
31259
31389
  var TEST_FILE_RULE_VERSION = "test-files/v2";
@@ -31305,7 +31435,7 @@ var defaultRunner = (cwd, args, report) => {
31305
31435
  }
31306
31436
  };
31307
31437
  var defaultAsyncRunner = (cwd, args, report) => new Promise((resolve3) => {
31308
- execFile(
31438
+ execFile2(
31309
31439
  "git",
31310
31440
  [...args],
31311
31441
  {
@@ -31823,13 +31953,29 @@ function saveGrokDateHints(scope, hints, file = defaultFile) {
31823
31953
  mkdirSync9(path20.dirname(file), { recursive: true });
31824
31954
  writeFileSync9(file, JSON.stringify(cache, null, 2));
31825
31955
  }
31826
- function mapToHints(value, floor) {
31827
- return Object.fromEntries(
31828
- [...value].map(([id, dates]) => [
31829
- id,
31830
- [...dates].filter((d) => d >= floor).sort()
31831
- ])
31956
+
31957
+ // src/sync/sessionLedger.ts
31958
+ function readSessionLedger(previous, current, floor) {
31959
+ const partialDates = /* @__PURE__ */ new Set();
31960
+ const remembered = /* @__PURE__ */ new Set();
31961
+ const next = {};
31962
+ for (const [id, dates] of Object.entries(previous)) {
31963
+ const kept = dates.filter((date) => date >= floor);
31964
+ if (current.has(id)) {
31965
+ for (const date of kept) remembered.add(date);
31966
+ continue;
31967
+ }
31968
+ for (const date of kept) partialDates.add(date);
31969
+ if (kept.length) next[id] = kept;
31970
+ }
31971
+ for (const [id, dates] of current) {
31972
+ const kept = [...dates].filter((date) => date >= floor).sort();
31973
+ if (kept.length) next[id] = kept;
31974
+ }
31975
+ const clearDates = new Set(
31976
+ [...remembered].filter((date) => !partialDates.has(date))
31832
31977
  );
31978
+ return { partialDates, clearDates, next };
31833
31979
  }
31834
31980
 
31835
31981
  // src/sync/summary.ts
@@ -32318,6 +32464,7 @@ async function stageSync(deps) {
32318
32464
  const loadConfig = deps.loadConfigImpl ?? loadSyncConfig;
32319
32465
  const adapters = deps.adaptersImpl ?? (() => HARNESS_ADAPTERS);
32320
32466
  const windowDays = deps.windowDays ?? DEFAULT_WINDOW_DAYS;
32467
+ const keychain = deps.keychain === true ? { keychain: true } : {};
32321
32468
  const resolveProjectWorkspaceId = deps.getProjectWorkspaceIdImpl ?? getProjectWorkspaceId;
32322
32469
  const workspaceIds = /* @__PURE__ */ new Map();
32323
32470
  const projectWorkspaceId = (directory) => {
@@ -32488,10 +32635,11 @@ async function stageSync(deps) {
32488
32635
  `scan ${adapter.name} (recent and historical)`
32489
32636
  );
32490
32637
  [reading.recent, reading.history] = await adapter.scanWindows([
32491
- { sinceMs, publishWorkflow: false },
32638
+ { sinceMs, publishWorkflow: false, ...keychain },
32492
32639
  {
32493
32640
  sinceMs: daysSinceMs,
32494
32641
  publishWorkflow: config.publishWorkflow,
32642
+ ...keychain,
32495
32643
  onProgress: progress("recent usage and history")
32496
32644
  }
32497
32645
  ]);
@@ -32506,6 +32654,7 @@ async function stageSync(deps) {
32506
32654
  reading.recent = await adapter.scan({
32507
32655
  sinceMs,
32508
32656
  publishWorkflow: false,
32657
+ ...keychain,
32509
32658
  onProgress: progress("recent usage")
32510
32659
  });
32511
32660
  scanDone2(
@@ -32518,6 +32667,7 @@ async function stageSync(deps) {
32518
32667
  reading.history = await adapter.scan({
32519
32668
  sinceMs: daysSinceMs,
32520
32669
  publishWorkflow: config.publishWorkflow,
32670
+ ...keychain,
32521
32671
  onProgress: progress("history")
32522
32672
  });
32523
32673
  scanDone(
@@ -32544,8 +32694,15 @@ async function stageSync(deps) {
32544
32694
  `historical harnesses (${retentionDays} days): ${historical.map((a) => a.name).join(", ") || "none"}`
32545
32695
  );
32546
32696
  let dayScansComplete = true;
32697
+ const acknowledgements = [];
32547
32698
  const partialHarnesses = /* @__PURE__ */ new Set();
32548
- const sessionDatesByHarness = /* @__PURE__ */ new Map();
32699
+ const ledgers = /* @__PURE__ */ new Map();
32700
+ const ledgerFloor = utcDate2(daysSinceMs);
32701
+ const ledgerScope = (harness) => token && config.stack ? grokCacheScope(
32702
+ harness === "grok-build" ? deps.baseUrl : `${deps.baseUrl}\0${harness}`,
32703
+ config.stack.slug,
32704
+ token
32705
+ ) : null;
32549
32706
  for (const { adapter, recent } of readings) {
32550
32707
  if (!recent) continue;
32551
32708
  const { aggregate, stats } = recent;
@@ -32570,8 +32727,19 @@ async function stageSync(deps) {
32570
32727
  dayScansComplete = false;
32571
32728
  partialHarnesses.add(adapter.name);
32572
32729
  }
32573
- if (adapter.name === "grok-build" || adapter.name === "cursor")
32574
- sessionDatesByHarness.set(adapter.name, sessionDates ?? /* @__PURE__ */ new Map());
32730
+ const scope = ledgerScope(adapter.name);
32731
+ const ledger = scope ? readSessionLedger(
32732
+ loadGrokDateHints(scope, deps.sessionLedgerFile),
32733
+ sessionDates ?? aggregate.sessionDays,
32734
+ ledgerFloor
32735
+ ) : void 0;
32736
+ if (scope && ledger) {
32737
+ ledgers.set(adapter.name, ledger);
32738
+ acknowledgements.push(
32739
+ () => saveGrokDateHints(scope, ledger.next, deps.sessionLedgerFile)
32740
+ );
32741
+ }
32742
+ const wholeHarnessPartial = partialHarnesses.has(adapter.name);
32575
32743
  workflowScans.push({ aggregate: workflow2, local: workflowLocal });
32576
32744
  usageScans.push(
32577
32745
  buildUsageDays({
@@ -32582,8 +32750,11 @@ async function stageSync(deps) {
32582
32750
  accountId: harnessAccountId(adapter.name),
32583
32751
  // Old readings can hold a bare folder ID without root provenance.
32584
32752
  // A complete scan can replace it, while a partial union cannot tell
32585
- // whether the new root-scoped ID denotes that same workspace.
32586
- ...adapter.name === "claude-code" && partialHarnesses.has(adapter.name) ? { deferWorkspace: isClaudeWorkspaceFallback } : {}
32753
+ // whether the new root-scoped ID denotes that same workspace. A day
32754
+ // whose sessions were partly deleted is such a union too.
32755
+ ...adapter.name === "claude-code" ? {
32756
+ deferWorkspace: (directory, date) => (wholeHarnessPartial || (ledger?.partialDates.has(date) ?? false)) && isClaudeWorkspaceFallback(directory)
32757
+ } : {}
32587
32758
  })
32588
32759
  );
32589
32760
  }
@@ -32609,44 +32780,33 @@ async function stageSync(deps) {
32609
32780
  `git history \xB7 skipped (${config.publishWorkflow ? "no harness scanned" : "publishWorkflow off"})`
32610
32781
  );
32611
32782
  }
32612
- const correctionDates = /* @__PURE__ */ new Set();
32613
- let acknowledgePublish;
32614
- const acknowledgements = [];
32615
- for (const [harness, currentDates] of sessionDatesByHarness) {
32616
- if (!token || !config.stack) continue;
32617
- const scope = grokCacheScope(
32618
- harness === "grok-build" ? deps.baseUrl : `${deps.baseUrl}\0${harness}`,
32619
- config.stack.slug,
32620
- token
32621
- );
32622
- const floor = utcDate2(daysSinceMs);
32623
- const previous = loadGrokDateHints(scope);
32624
- const current = mapToHints(currentDates, floor);
32625
- for (const dates of Object.values(previous))
32626
- for (const date of dates) correctionDates.add(date);
32627
- for (const dates of Object.values(current))
32628
- for (const date of dates) correctionDates.add(date);
32629
- if (Object.keys(previous).some((id) => !(id in current))) {
32630
- dayScansComplete = false;
32631
- partialHarnesses.add(harness);
32632
- }
32633
- acknowledgements.push(() => saveGrokDateHints(scope, current));
32634
- }
32635
- if (acknowledgements.length && dayScansComplete)
32636
- acknowledgePublish = () => {
32637
- for (const acknowledge of acknowledgements) acknowledge();
32638
- };
32639
- const localDays = applyDayConsent(
32640
- buildMeasuredDays({
32641
- usage: mergeUsageDays(usageScans),
32642
- ...workflow ? { workflow: workflow.days } : {},
32643
- from: utcDate2(daysSinceMs),
32644
- to: utcDate2(now),
32645
- // A partial scan cannot prove that a formerly dated session disappeared.
32646
- includeDates: dayScansComplete ? correctionDates : /* @__PURE__ */ new Set()
32647
- }),
32648
- config
32783
+ const clearable = new Map(
32784
+ [...ledgers].filter(([harness]) => !partialHarnesses.has(harness))
32649
32785
  );
32786
+ const clearDates = new Set(
32787
+ [...clearable.values()].flatMap((ledger) => [...ledger.clearDates])
32788
+ );
32789
+ const acknowledgePublish = acknowledgements.length ? () => {
32790
+ for (const acknowledge of acknowledgements) acknowledge();
32791
+ } : void 0;
32792
+ const localDays = markDeletedEvidence(
32793
+ applyDayConsent(
32794
+ buildMeasuredDays({
32795
+ usage: mergeUsageDays(usageScans),
32796
+ ...workflow ? { workflow: workflow.days } : {},
32797
+ from: utcDate2(daysSinceMs),
32798
+ to: utcDate2(now),
32799
+ includeDates: clearDates
32800
+ }),
32801
+ config
32802
+ ),
32803
+ { ledgers, clearable, partialHarnesses }
32804
+ );
32805
+ const deletedDays = localDays.filter((day) => day.partialHarnesses).length;
32806
+ if (deletedDays)
32807
+ trace(
32808
+ `days \xB7 ${deletedDays} with deleted local sessions; the published reading is kept`
32809
+ );
32650
32810
  const days = selectDaysToPublish({
32651
32811
  local: localDays,
32652
32812
  manifest,
@@ -32863,6 +33023,7 @@ async function runAutoSync(deps) {
32863
33023
  failure2 = staged.blockedReason;
32864
33024
  } else {
32865
33025
  const res = await publish(staged.token, staged.bodyJson);
33026
+ staged.acknowledgePublish?.();
32866
33027
  url = res.url;
32867
33028
  }
32868
33029
  }
@@ -33177,6 +33338,8 @@ async function syncCommand(options = {}) {
33177
33338
  }
33178
33339
  const destinationToken = token;
33179
33340
  const destinationConfig = loaded;
33341
+ const notice = await discoverCursorRoots().then(({ homes }) => keychainNotice(homes)).catch(() => null);
33342
+ if (notice) p7.log.info(notice);
33180
33343
  p7.log.step("Scanning local history");
33181
33344
  const board = createBoard({
33182
33345
  write: (text) => process.stdout.write(text),
@@ -33188,7 +33351,8 @@ async function syncCommand(options = {}) {
33188
33351
  baseUrl: BASE_URL,
33189
33352
  getTokenImpl: () => destinationToken,
33190
33353
  loadConfigImpl: async () => destinationConfig,
33191
- onEvent: board.handle
33354
+ onEvent: board.handle,
33355
+ keychain: true
33192
33356
  });
33193
33357
  } catch (e) {
33194
33358
  traceError("sync scan", e);