claude-code-session-manager 0.137.0 → 0.139.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.
Files changed (101) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +339 -82
  3. package/dist/assets/{AppSettings-l7NTc0yu.js → AppSettings-CUfWY9vN.js} +2 -2
  4. package/dist/assets/History-DDnqaLyw.js +2 -0
  5. package/dist/assets/HomeClaudeConfig-CGD2Onjv.js +3 -0
  6. package/dist/assets/{Panel-BuInRmA0.js → Panel-Csyd9HbD.js} +1 -1
  7. package/dist/assets/ProjectClaudeConfig-C-jlYpC_.js +26 -0
  8. package/dist/assets/{Scheduler-B7sn2mUw.js → Scheduler-NLs08fx7.js} +9 -9
  9. package/dist/assets/{SkillReferenceGraph-DwV0Ueyc.js → SkillReferenceGraph-DcscPXAG.js} +1 -1
  10. package/dist/assets/Skills-BpGRKOcY.js +67 -0
  11. package/dist/assets/{TiptapBody-Bl8hDhhS.js → TiptapBody-DSU3769X.js} +60 -54
  12. package/dist/assets/ViewTabs-C0PRZx4_.js +1 -0
  13. package/dist/assets/{VoiceButton-DJx-jY4r.js → VoiceButton-D2rMurNg.js} +1 -1
  14. package/dist/assets/{historyTotals-Cgjm5q24.js → historyTotals-TcIQs2sh.js} +1 -1
  15. package/dist/assets/{index-62tyjEQB.css → index-BCySPdtU.css} +1 -1
  16. package/dist/assets/index-C-d0DCre.js +3124 -0
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +471 -452
  20. package/package.json +13 -5
  21. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  22. package/plugins/session-manager-dev/skills/builder/SKILL.md +12 -4
  23. package/plugins/session-manager-dev/skills/builder/scripts/publish-preflight.cjs +255 -0
  24. package/plugins/session-manager-dev/skills/develop/SKILL.md +12 -5
  25. package/scripts/README.md +1 -0
  26. package/scripts/scheduler-mcp-server.cjs +161 -18
  27. package/src/main/build-info.json +4 -4
  28. package/src/main/chatRunner.cjs +53 -2
  29. package/src/main/exchanges.cjs +70 -5
  30. package/src/main/historyAggregator.cjs +84 -58
  31. package/src/main/historyDashboard.cjs +18 -13
  32. package/src/main/index.cjs +35 -9
  33. package/src/main/ipcSchemas.cjs +133 -5
  34. package/src/main/lib/claude/effectiveModelInfo.cjs +2 -2
  35. package/src/main/lib/claude/modelPricing.cjs +148 -0
  36. package/src/main/lib/demo-video-kit/checks.cjs +16 -0
  37. package/src/main/lib/epic/epicAdminRoutes.cjs +101 -0
  38. package/src/main/lib/epic/epicAttachments.cjs +143 -0
  39. package/src/main/lib/epic/epicJobReceipt.cjs +87 -0
  40. package/src/main/lib/epic/epicMint.cjs +4 -0
  41. package/src/main/lib/epic/epicOutsideRead.cjs +306 -0
  42. package/src/main/lib/epic/epicOutsideState.cjs +233 -0
  43. package/src/main/lib/epic/epicSettle.cjs +1 -1
  44. package/src/main/lib/epic/epicStateWatcher.cjs +157 -0
  45. package/src/main/lib/epic/externalRef.cjs +37 -0
  46. package/src/main/lib/epic/externalRefIndex.cjs +136 -0
  47. package/src/main/lib/epic/restorableSessions.cjs +151 -17
  48. package/src/main/lib/epic/transcriptUsage.cjs +197 -0
  49. package/src/main/lib/externalContract.cjs +111 -0
  50. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +121 -4
  51. package/src/main/lib/feedback-remote/crossProjectReply.cjs +83 -1
  52. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -6
  53. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +50 -8
  54. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +218 -4
  55. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +19 -3
  56. package/src/main/lib/feedback-remote/feedbackImages.cjs +171 -0
  57. package/src/main/lib/feedback-remote/localAdminHttp.cjs +11 -10
  58. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +287 -1
  59. package/src/main/lib/feedback-remote/needsYouAdminRoutes.cjs +133 -0
  60. package/src/main/lib/feedback-remote/needsYouIpc.cjs +50 -0
  61. package/src/main/lib/feedback-remote/needsYouStore.cjs +281 -0
  62. package/src/main/lib/feedback-remote/remoteFrameAssembler.cjs +113 -0
  63. package/src/main/lib/historyRollup.cjs +32 -5
  64. package/src/main/lib/mcpToolCatalog.cjs +111 -14
  65. package/src/main/lib/persona-macro/agentAdminRoutes.cjs +121 -0
  66. package/src/main/lib/persona-macro/macroLibrary.cjs +7 -0
  67. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  68. package/src/main/lib/process/bootStdioGuard.cjs +32 -0
  69. package/src/main/lib/process/stdioGuard.cjs +115 -0
  70. package/src/main/lib/promptSessionSchema.cjs +4 -0
  71. package/src/main/lib/remoteTranscriptTail.cjs +32 -1
  72. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -0
  73. package/src/main/lib/telemetry/auditEvents.cjs +176 -0
  74. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +45 -0
  75. package/src/main/loopEfficiencyHandlers.cjs +1 -1
  76. package/src/main/scheduler.cjs +29 -0
  77. package/src/main/templates/PRD_AUTHORING.md +1 -0
  78. package/src/main/transcripts.cjs +62 -7
  79. package/src/main/webRemote.cjs +122 -18
  80. package/src/preload/api.d.ts +98 -9
  81. package/src/preload/apiSurface.cjs +7 -0
  82. package/src/preload/apiSurface.json +415 -83
  83. package/src/preload/index.cjs +17 -3
  84. package/src/seed/agents/demo-video-builder.md +10 -7
  85. package/dist/assets/AgentLibrary-DV0DTZDC.js +0 -2
  86. package/dist/assets/Button-Cmfkgjfa.js +0 -1
  87. package/dist/assets/DocumentEditorPane-MTljV-Uw.js +0 -1
  88. package/dist/assets/Extensions-Cc1Q_8id.js +0 -2
  89. package/dist/assets/History-CFo-1DHo.js +0 -2
  90. package/dist/assets/Library-C_ibFiOx.js +0 -32
  91. package/dist/assets/ListDetail-ByULG209.js +0 -1
  92. package/dist/assets/ProjectClaudeConfig-yqqVtHY7.js +0 -25
  93. package/dist/assets/ProvenanceBadge-CJvnQReI.js +0 -1
  94. package/dist/assets/Settings-DRRSJksU.js +0 -2
  95. package/dist/assets/Skills-DVYHA9gV.js +0 -29
  96. package/dist/assets/SourceChip-DfJ5_5rV.js +0 -1
  97. package/dist/assets/SystemPrompt-f11wGllK.js +0 -1
  98. package/dist/assets/Toggle-DaxeFDFp.js +0 -1
  99. package/dist/assets/ViewTabs-DRtgFKRw.js +0 -1
  100. package/dist/assets/claude-settings-schema-COigsajx.js +0 -3
  101. package/dist/assets/index-iQ6pdyuS.js +0 -3116
@@ -44,8 +44,6 @@ const fs = require('node:fs');
44
44
  const os = require('node:os');
45
45
  const path = require('node:path');
46
46
  const { encodeCwd } = require('../util/encodeCwd.cjs');
47
- // Module object, not destructured: the memo test spies on readJsonOrSync.
48
- const atomicFs = require('../util/atomicFs.cjs');
49
47
  const { readActiveIndex } = require('./epicMint.cjs');
50
48
 
51
49
  /** A Claude Code session id: hex UUID 8-4-4-4-12, either case. */
@@ -93,7 +91,7 @@ const LATE_ROW_HINTS = ['"last-prompt"', '"custom-title"', '"summary"'];
93
91
  * budgets full, or at the 400-read cap.
94
92
  */
95
93
 
96
- /** @typedef {'invalid_id'|'not_found'|'cwd_mismatch'|'claimed'} RefusalCode */
94
+ /** @typedef {'invalid_id'|'not_found'|'cwd_mismatch'|'claimed'|'claim_check_unreadable'} RefusalCode */
97
95
  /** @typedef {{ ok: true, transcriptPath: string }} RestorableOk */
98
96
  /** @typedef {{ ok: false, code: RefusalCode, message: string }} RestorableRefusal */
99
97
 
@@ -118,9 +116,18 @@ const LATE_ROW_HINTS = ['"last-prompt"', '"custom-title"', '"summary"'];
118
116
 
119
117
  /**
120
118
  * One cwd's claimed-id memo. The sync and the async reader both read and write it.
119
+ * Completeness is not stored here: each scan returns its own (ClaimScan), so a
120
+ * concurrent scan of the same cwd overwriting this entry cannot change what
121
+ * another scan's caller acts on.
121
122
  * @typedef {{ indexKey: string, indexIds: string[], files: Map<string, ArchiveRec> }} ClaimedEntry
122
123
  */
123
124
 
125
+ /**
126
+ * One claim scan's result. `incomplete`: an archived Epic file could not be
127
+ * read even on retry during this scan, so `ids` may miss a claim.
128
+ * @typedef {{ ids: Set<string>, incomplete: boolean }} ClaimScan
129
+ */
130
+
124
131
  /** @type {Map<string, ClaimedEntry>} */
125
132
  const claimedCache = new Map();
126
133
 
@@ -275,15 +282,94 @@ function memoHit(prevFiles, name, key) {
275
282
  return hit && hit.key === key ? hit : null;
276
283
  }
277
284
 
285
+ /** A record key no stat key equals, so memoHit never serves it. */
286
+ const UNREAD_KEY = 'unread';
287
+
288
+ /**
289
+ * One read of an archived Epic file: `{ io: true }` when the read itself
290
+ * failed (EMFILE, EACCES, EIO…), else `{ doc }` with `doc` null for an empty
291
+ * file, invalid JSON or a non-object. A file gone since readdir (ENOENT) owns
292
+ * nothing, so it reads as `{ doc: null }`: atomicFs writes by tmp+rename, which
293
+ * never leaves the target missing. Not atomicFs.readJsonOr*: they return the
294
+ * fallback for both a parse error and an I/O error. Goes through the `fs`
295
+ * module object so tests can spy on readFileSync / promises.readFile.
296
+ * @typedef {{ io: true } | { io?: false, doc: object|null }} ArchiveRead
297
+ */
298
+
278
299
  /**
279
- * Second half: the record for an archived Epic file read at `key`. A missing,
280
- * empty or malformed file (`doc` null) owns nothing.
300
+ * @param {string} raw
301
+ * @returns {ArchiveRead}
302
+ */
303
+ function parseArchive(raw) {
304
+ if (raw.trim() === '') return { doc: null };
305
+ try {
306
+ const doc = JSON.parse(raw);
307
+ return { doc: doc && typeof doc === 'object' ? doc : null };
308
+ } catch {
309
+ return { doc: null };
310
+ }
311
+ }
312
+
313
+ /** @param {unknown} err */
314
+ function isGone(err) {
315
+ return !!err && typeof err === 'object' && /** @type {{ code?: unknown }} */ (err).code === 'ENOENT';
316
+ }
317
+
318
+ /**
319
+ * @param {string} file
320
+ * @returns {ArchiveRead}
321
+ */
322
+ function readArchiveSync(file) {
323
+ let raw;
324
+ try {
325
+ raw = fs.readFileSync(file, 'utf8');
326
+ } catch (err) {
327
+ return isGone(err) ? { doc: null } : { io: true };
328
+ }
329
+ return parseArchive(raw);
330
+ }
331
+
332
+ /**
333
+ * @param {string} file
334
+ * @returns {Promise<ArchiveRead>}
335
+ */
336
+ async function readArchiveAsync(file) {
337
+ let raw;
338
+ try {
339
+ raw = await fs.promises.readFile(file, 'utf8');
340
+ } catch (err) {
341
+ return isGone(err) ? { doc: null } : { io: true };
342
+ }
343
+ return parseArchive(raw);
344
+ }
345
+
346
+ /**
347
+ * Second half: the record for an archived Epic file read at `key`, from the
348
+ * result of reading it and (after an I/O failure) of reading it once more.
349
+ * Three cases:
350
+ * - parsed to an object: its session's claudeSessionId, memoised under `key`;
351
+ * - read fine but empty, invalid JSON or not an object: owns nothing, and
352
+ * that is memoised under `key` too, so an unchanged bad file is not re-read
353
+ * on every call (a rewrite changes the stat key and is read again);
354
+ * - the read failed twice (`io`): owns nothing for this call, gets UNREAD_KEY
355
+ * so the next call re-reads it, and `onUnreadable` marks the scan
356
+ * incomplete. Memoising it under the file's unchanged stat key would drop
357
+ * that Epic's claim until the file is next rewritten, and using the set
358
+ * without the claim would list or restore an Epic-owned session (breaks
359
+ * Epic:session = 1:1), so consumers fail closed on an incomplete scan.
281
360
  * @param {string} key
282
- * @param {unknown} doc
361
+ * @param {ArchiveRead} read
362
+ * @param {() => void} onUnreadable
283
363
  * @returns {ArchiveRec}
284
364
  */
285
- function archiveRec(key, doc) {
286
- return { key, sid: doc && typeof doc === 'object' ? sessionIdOf(/** @type {Row} */ (doc).session) : null };
365
+ function archiveRec(key, read, onUnreadable) {
366
+ if (read.io) {
367
+ onUnreadable();
368
+ return { key: UNREAD_KEY, sid: null };
369
+ }
370
+ const { doc } = read;
371
+ if (!doc) return { key, sid: null };
372
+ return { key, sid: sessionIdOf(/** @type {Row} */ (doc).session) };
287
373
  }
288
374
 
289
375
  /**
@@ -312,8 +398,18 @@ function commitClaimed(cwd, entry) {
312
398
  * @returns {Set<string>}
313
399
  */
314
400
  function claimedClaudeSessionIds(cwd, deps) {
401
+ return scanClaimedSync(cwd, deps).ids;
402
+ }
403
+
404
+ /**
405
+ * claimedClaudeSessionIds plus this scan's own completeness.
406
+ * @param {string} cwd
407
+ * @param {RestorableDeps} [deps]
408
+ * @returns {ClaimScan}
409
+ */
410
+ function scanClaimedSync(cwd, deps) {
315
411
  const dir = promptSessionsDirOf(cwd);
316
- if (!dir) return new Set();
412
+ if (!dir) return { ids: new Set(), incomplete: false };
317
413
  const d = deps || {};
318
414
  const prev = claimedCache.get(cwd);
319
415
  const indexKey = statKey(path.join(dir, ACTIVE_INDEX));
@@ -328,12 +424,21 @@ function claimedClaudeSessionIds(cwd, deps) {
328
424
  }
329
425
  /** @type {Map<string, ArchiveRec>} */
330
426
  const files = new Map();
427
+ let incomplete = false;
428
+ const markIncomplete = () => { incomplete = true; };
331
429
  for (const name of names) {
332
430
  const file = path.join(dir, name);
333
431
  const key = statKey(file);
334
- files.set(name, memoHit(prevFiles, name, key) || archiveRec(key, atomicFs.readJsonOrSync(file, null)));
432
+ const hit = memoHit(prevFiles, name, key);
433
+ if (hit) {
434
+ files.set(name, hit);
435
+ continue;
436
+ }
437
+ let read = readArchiveSync(file);
438
+ if (read.io) read = readArchiveSync(file); // one immediate retry
439
+ files.set(name, archiveRec(key, read, markIncomplete));
335
440
  }
336
- return commitClaimed(cwd, { indexKey, indexIds, files });
441
+ return { ids: commitClaimed(cwd, { indexKey, indexIds, files }), incomplete };
337
442
  }
338
443
 
339
444
  /**
@@ -348,8 +453,18 @@ function claimedClaudeSessionIds(cwd, deps) {
348
453
  * @returns {Promise<Set<string>>}
349
454
  */
350
455
  async function claimedClaudeSessionIdsAsync(cwd, deps) {
456
+ return (await scanClaimedAsync(cwd, deps)).ids;
457
+ }
458
+
459
+ /**
460
+ * claimedClaudeSessionIdsAsync plus this scan's own completeness.
461
+ * @param {string} cwd
462
+ * @param {RestorableDeps} [deps]
463
+ * @returns {Promise<ClaimScan>}
464
+ */
465
+ async function scanClaimedAsync(cwd, deps) {
351
466
  const dir = promptSessionsDirOf(cwd);
352
- if (!dir) return new Set();
467
+ if (!dir) return { ids: new Set(), incomplete: false };
353
468
  const d = deps || {};
354
469
  const prev = claimedCache.get(cwd);
355
470
  const indexKey = await statKeyAsync(path.join(dir, ACTIVE_INDEX));
@@ -364,16 +479,24 @@ async function claimedClaudeSessionIdsAsync(cwd, deps) {
364
479
  }
365
480
  /** @type {ArchiveRec[]} */
366
481
  const recs = new Array(names.length);
482
+ let incomplete = false;
483
+ const markIncomplete = () => { incomplete = true; };
367
484
  await forEachBounded(names.length, async (k) => {
368
485
  const file = path.join(dir, names[k]);
369
486
  const key = await statKeyAsync(file);
370
- // atomicFs.readJsonOr is fs.promises.readFile + JSON.parse; malformed → null.
371
- recs[k] = memoHit(prevFiles, names[k], key) || archiveRec(key, await atomicFs.readJsonOr(file, null));
487
+ const hit = memoHit(prevFiles, names[k], key);
488
+ if (hit) {
489
+ recs[k] = hit;
490
+ return;
491
+ }
492
+ let read = await readArchiveAsync(file);
493
+ if (read.io) read = await readArchiveAsync(file); // one immediate retry
494
+ recs[k] = archiveRec(key, read, markIncomplete);
372
495
  });
373
496
  /** @type {Map<string, ArchiveRec>} */
374
497
  const files = new Map();
375
498
  names.forEach((name, k) => files.set(name, recs[k])); // readdir order, as the sync reader
376
- return commitClaimed(cwd, { indexKey, indexIds, files });
499
+ return { ids: commitClaimed(cwd, { indexKey, indexIds, files }), incomplete };
377
500
  }
378
501
 
379
502
  /**
@@ -627,7 +750,13 @@ async function listRestorableSessions({ cwd, limit = DEFAULT_LIMIT, deps } = { c
627
750
  const candidates = await statCandidates(dir, names.filter(isTranscriptName));
628
751
  candidates.sort((a, b) => b.mtimeMs - a.mtimeMs || (a.sessionId < b.sessionId ? -1 : a.sessionId > b.sessionId ? 1 : 0));
629
752
 
630
- const claimed = lowerSet(await claimedClaudeSessionIdsAsync(projectCwd, d));
753
+ const scan = await scanClaimedAsync(projectCwd, d);
754
+ // An Epic file that could not be read may own any candidate: list nothing
755
+ // for this call rather than offer an Epic-owned session. The next call retries.
756
+ // Decided from this scan's own result, never the shared memo (a concurrent
757
+ // scan of this cwd may have overwritten it during the await).
758
+ if (scan.incomplete) return result;
759
+ const claimed = lowerSet(scan.ids);
631
760
  /** @type {Candidate[]} */
632
761
  const open = [];
633
762
  for (const c of candidates) {
@@ -827,7 +956,12 @@ function checkRestorableSessionSync(cwd, sessionId, deps) {
827
956
  ? `Session ${sessionId} in ${dir} records no cwd in its first 64 KiB, so it cannot be shown to belong to ${projectCwd}.`
828
957
  : `Session ${sessionId} in ${dir} was recorded in ${recordedCwd}, not ${projectCwd}.`);
829
958
  }
830
- if (lowerSet(claimedClaudeSessionIds(projectCwd, d)).has(sessionId.toLowerCase())) {
959
+ const scan = scanClaimedSync(projectCwd, d);
960
+ const claimed = lowerSet(scan.ids);
961
+ if (scan.incomplete) {
962
+ return refuse('claim_check_unreadable', `Cannot restore session ${sessionId} in ${dir} yet: the claim check could not read an Epic file in ${projectCwd}, so it cannot rule out that an Epic already owns this session. Try again.`);
963
+ }
964
+ if (claimed.has(sessionId.toLowerCase())) {
831
965
  return refuse('claimed', `Session ${sessionId} in ${dir} already belongs to an Epic in this project.`);
832
966
  }
833
967
  return { ok: true, transcriptPath };
@@ -0,0 +1,197 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * transcriptUsage.cjs — summarize one Claude Code transcript (JSONL) into
5
+ * per-call token totals, the largest single-call context, and an approximate
6
+ * breakdown of what filled it.
7
+ *
8
+ * Unlike historyAggregator's scanAggrLines (which sums every usage line),
9
+ * this counts each model call ONCE: Claude Code writes one line per content
10
+ * block, so several rows share a message.id and repeat its usage. Per id we
11
+ * keep the row with the largest output_tokens.
12
+ *
13
+ * Only main-chain (non-sidechain) rows count; '<synthetic>' model rows are
14
+ * ignored. Source sizes are approximated as characters / 4.
15
+ */
16
+
17
+ const fs = require('node:fs');
18
+ const readline = require('node:readline');
19
+
20
+ const CHARS_PER_TOKEN = 4;
21
+
22
+ function num(v) {
23
+ return typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : 0;
24
+ }
25
+
26
+ function textChars(content) {
27
+ if (typeof content === 'string') return content.length;
28
+ if (!Array.isArray(content)) return 0;
29
+ let n = 0;
30
+ for (const b of content) {
31
+ if (typeof b === 'string') n += b.length;
32
+ else if (b && typeof b === 'object' && typeof b.text === 'string') n += b.text.length;
33
+ }
34
+ return n;
35
+ }
36
+
37
+ function createAccumulator() {
38
+ /** message.id -> { model, usage } */
39
+ const callsById = new Map();
40
+ /** tool_use id -> tool name */
41
+ const toolNames = new Map();
42
+ /** [tool_use_id, chars] — resolved at finish so order does not matter */
43
+ const toolResults = [];
44
+ let userChars = 0;
45
+
46
+ function addRow(row) {
47
+ if (!row || typeof row !== 'object' || row.isSidechain === true) return;
48
+ const msg = row.message;
49
+ if (!msg || typeof msg !== 'object') return;
50
+
51
+ if (row.type === 'assistant') {
52
+ if (Array.isArray(msg.content)) {
53
+ for (const b of msg.content) {
54
+ if (b && b.type === 'tool_use' && typeof b.id === 'string' && typeof b.name === 'string') {
55
+ toolNames.set(b.id, b.name);
56
+ }
57
+ }
58
+ }
59
+ const usage = msg.usage;
60
+ if (!usage || typeof usage !== 'object') return;
61
+ if (typeof msg.model !== 'string' || msg.model === '<synthetic>') return;
62
+ const id = typeof msg.id === 'string' && msg.id ? msg.id : `__noid_${callsById.size}`;
63
+ const prev = callsById.get(id);
64
+ if (!prev || num(usage.output_tokens) > num(prev.usage.output_tokens)) {
65
+ callsById.set(id, { model: msg.model, usage });
66
+ }
67
+ return;
68
+ }
69
+
70
+ if (row.type === 'user') {
71
+ if (row.isMeta === true) return;
72
+ const c = msg.content;
73
+ if (typeof c === 'string') {
74
+ userChars += c.length;
75
+ return;
76
+ }
77
+ if (!Array.isArray(c)) return;
78
+ for (const b of c) {
79
+ if (!b || typeof b !== 'object') continue;
80
+ if (b.type === 'tool_result') {
81
+ toolResults.push([b.tool_use_id, textChars(b.content)]);
82
+ } else if (b.type === 'text' && typeof b.text === 'string') {
83
+ userChars += b.text.length;
84
+ }
85
+ }
86
+ }
87
+ }
88
+
89
+ function addLine(line) {
90
+ if (typeof line !== 'string' || !line.trim()) return;
91
+ let row;
92
+ try {
93
+ row = JSON.parse(line);
94
+ } catch {
95
+ return;
96
+ }
97
+ try {
98
+ addRow(row);
99
+ } catch {
100
+ /* defensive: never throw on a weird row */
101
+ }
102
+ }
103
+
104
+ function finish() {
105
+ let inputTokens = 0;
106
+ let cacheWriteTokens = 0;
107
+ let cacheReadTokens = 0;
108
+ let outputTokens = 0;
109
+ let largestContext = 0;
110
+ const models = {};
111
+ for (const { model, usage } of callsById.values()) {
112
+ const i = num(usage.input_tokens);
113
+ const cw = num(usage.cache_creation_input_tokens);
114
+ const cr = num(usage.cache_read_input_tokens);
115
+ inputTokens += i;
116
+ cacheWriteTokens += cw;
117
+ cacheReadTokens += cr;
118
+ outputTokens += num(usage.output_tokens);
119
+ if (i + cw + cr > largestContext) largestContext = i + cw + cr;
120
+ models[model] = (models[model] || 0) + 1;
121
+ }
122
+
123
+ const toolChars = new Map();
124
+ for (const [toolUseId, chars] of toolResults) {
125
+ const name = (typeof toolUseId === 'string' && toolNames.get(toolUseId)) || 'unknown';
126
+ const key = `tool:${name}`;
127
+ toolChars.set(key, (toolChars.get(key) || 0) + chars);
128
+ }
129
+
130
+ const bySource = [];
131
+ if (outputTokens > 0) bySource.push({ source: 'model_output', approxTokens: outputTokens });
132
+ for (const [source, chars] of toolChars) {
133
+ const approxTokens = Math.round(chars / CHARS_PER_TOKEN);
134
+ if (approxTokens > 0) bySource.push({ source, approxTokens });
135
+ }
136
+ const userTokens = Math.round(userChars / CHARS_PER_TOKEN);
137
+ if (userTokens > 0) bySource.push({ source: 'user_prompt', approxTokens: userTokens });
138
+ bySource.sort((a, b) => b.approxTokens - a.approxTokens || a.source.localeCompare(b.source));
139
+
140
+ return {
141
+ calls: callsById.size,
142
+ inputTokens,
143
+ cacheWriteTokens,
144
+ cacheReadTokens,
145
+ outputTokens,
146
+ largestContext,
147
+ models,
148
+ bySource,
149
+ };
150
+ }
151
+
152
+ return { addLine, finish };
153
+ }
154
+
155
+ /**
156
+ * @param {Iterable<string>} lines JSONL strings
157
+ */
158
+ function summarizeTranscriptUsage(lines) {
159
+ const acc = createAccumulator();
160
+ try {
161
+ if (lines && typeof lines[Symbol.iterator] === 'function') {
162
+ for (const line of lines) acc.addLine(line);
163
+ }
164
+ } catch {
165
+ /* a throwing iterator still yields what was read so far */
166
+ }
167
+ return acc.finish();
168
+ }
169
+
170
+ /**
171
+ * Stream a transcript file line by line.
172
+ * @param {string} filePath
173
+ * @returns {Promise<ReturnType<typeof summarizeTranscriptUsage> | null>}
174
+ */
175
+ async function summarizeTranscriptFile(filePath) {
176
+ try {
177
+ await fs.promises.access(filePath, fs.constants.R_OK);
178
+ } catch {
179
+ return null;
180
+ }
181
+ const acc = createAccumulator();
182
+ try {
183
+ const stream = fs.createReadStream(filePath, { encoding: 'utf8' });
184
+ const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
185
+ try {
186
+ for await (const line of rl) acc.addLine(line);
187
+ } finally {
188
+ rl.close();
189
+ stream.destroy();
190
+ }
191
+ } catch {
192
+ return null;
193
+ }
194
+ return acc.finish();
195
+ }
196
+
197
+ module.exports = { summarizeTranscriptUsage, summarizeTranscriptFile };
@@ -0,0 +1,111 @@
1
+ /**
2
+ * externalContract.cjs — sole owner of the outside-contract version number.
3
+ *
4
+ * RULE: a change that breaks an outside caller of an admin route, an MCP
5
+ * tool, an audit event or the admin-api.json shape increments
6
+ * CONTRACT_VERSION. Additive changes (a new route, a new optional field) do
7
+ * not.
8
+ *
9
+ * Why top-level lib/: the contract spans the admin HTTP transport, the MCP
10
+ * server, the audit log and the token file — no single domain subfolder owns
11
+ * it. Outside apps read the number (health route, unknown-route 404,
12
+ * admin-api.json) instead of probing for a missing route.
13
+ */
14
+
15
+ 'use strict';
16
+
17
+ const CONTRACT_VERSION = 1;
18
+
19
+ // Read once; null when package.json is unreadable.
20
+ let APP_VERSION = null;
21
+ try { APP_VERSION = require('../../../package.json').version || null; } catch { APP_VERSION = null; }
22
+
23
+ /** @returns {{ contractVersion: number, appVersion: string | null }} */
24
+ function contractInfo() {
25
+ return { contractVersion: CONTRACT_VERSION, appVersion: APP_VERSION };
26
+ }
27
+
28
+ /** Recursively freeze a plain object/array literal. */
29
+ function deepFreeze(v) {
30
+ if (v && typeof v === 'object') {
31
+ for (const k of Object.keys(v)) deepFreeze(v[k]);
32
+ Object.freeze(v);
33
+ }
34
+ return v;
35
+ }
36
+
37
+ /**
38
+ * The outside contract — what an outside app may depend on. Every list here
39
+ * is checked against the code by src/main/__tests__/externalContract.shape.test.cjs;
40
+ * changing one changes contractFingerprint(), which must then be recorded
41
+ * under a new CONTRACT_VERSION in CONTRACT_FINGERPRINTS.
42
+ */
43
+ const CONTRACT = deepFreeze({
44
+ routes: [
45
+ { method: 'GET', path: '/__admin/health' },
46
+ { method: 'POST', path: '/admin/feedback/open-session' },
47
+ { method: 'POST', path: '/admin/macros/run' },
48
+ { method: 'GET', path: '/admin/epics' },
49
+ { method: 'GET', path: '/admin/epic' },
50
+ { method: 'GET', path: '/admin/events' },
51
+ { method: 'GET', path: '/admin/agents' },
52
+ { method: 'POST', path: '/admin/needs-you' },
53
+ { method: 'POST', path: '/admin/needs-you/withdraw' },
54
+ { method: 'GET', path: '/admin/needs-you' },
55
+ ],
56
+ tools: {
57
+ feedback_open_session: { required: ['toCwd', 'fromCwd', 'title', 'motivation', 'acceptanceCriteria', 'body'] },
58
+ epic_list: { required: ['cwd'] },
59
+ epic_get: { required: ['cwd'], requiredOneOf: [['id', 'externalRef']] },
60
+ feedback_reply: { required: ['message', 'outcome'] },
61
+ agent_list: { required: [] },
62
+ },
63
+ epicStates: ['closed', 'awaiting_approval', 'needs_input', 'blocked', 'working', 'in_review', 'verified', 'open'],
64
+ epicRecordFields: [
65
+ 'epicId', 'cwd', 'title', 'goal', 'tag', 'agentType', 'status', 'state', 'blocked', 'prds',
66
+ 'verified', 'refuted', 'unvalidated', 'externalRef', 'source', 'createdAt', 'completedAt',
67
+ ],
68
+ receiptFields: ['jobs', 'chat'],
69
+ epicStateChangedFields: ['at', 'kind', 'cwd', 'epicId', 'from', 'to', 'blockedKind', 'externalRef'],
70
+ // Keys of an event-mode epic_cross_project_reply row (crossProjectReply.cjs replyAsEvent) as readEventsAfter returns it.
71
+ replyEventFields: [
72
+ 'at', 'kind', 'cwd', 'epicId', 'fromCwd', 'fromEpicId', 'outcome', 'delivery', 'mode', 'externalRef',
73
+ 'message', 'referencePaths',
74
+ ],
75
+ // Keys of one agent in GET /admin/agents?cwd=… (agentAdminRoutes.cjs publicAgent + resolved).
76
+ agentFields: [
77
+ 'name', 'title', 'description', 'model', 'effort', 'tags', 'tools', 'executorOnly', 'agentCli', 'agentCliModel',
78
+ 'seedVersion', 'path', 'resolved',
79
+ ],
80
+ // Keys of one stored Needs you item (feedback-remote/needsYouStore.cjs) as the store and GET /admin/needs-you return it.
81
+ needsYouItemFields: [
82
+ 'app', 'id', 'title', 'why', 'link', 'options', 'externalRef', 'status', 'answer', 'createdAt', 'updatedAt',
83
+ 'answeredAt',
84
+ ],
85
+ // Keys of a needs_you_answered row (feedback-remote/needsYouIpc.cjs) as readEventsAfter returns it; externalRef only when the item has one.
86
+ needsYouAnsweredFields: ['at', 'kind', 'app', 'id', 'answer', 'externalRef'],
87
+ eventKinds: ['epic_state_changed', 'job_transition', 'epic_cross_project_reply', 'needs_you_answered'],
88
+ adminApiFields: ['port', 'token', 'appVersion', 'contractVersion'],
89
+ });
90
+
91
+ /** JSON with object keys sorted at every level (arrays keep their order). */
92
+ function stableStringify(v) {
93
+ if (Array.isArray(v)) return `[${v.map(stableStringify).join(',')}]`;
94
+ if (v && typeof v === 'object') {
95
+ return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${stableStringify(v[k])}`).join(',')}}`;
96
+ }
97
+ return JSON.stringify(v);
98
+ }
99
+
100
+ /** @returns {string} sha256 hex of the manifest in stable key order. */
101
+ function contractFingerprint() {
102
+ return require('node:crypto').createHash('sha256').update(stableStringify(CONTRACT)).digest('hex');
103
+ }
104
+
105
+ /** Fingerprint recorded for each contract version. */
106
+ const CONTRACT_FINGERPRINTS = Object.freeze({
107
+ // v1 was unreleased when the manifest was completed (at/kind, epic_get requiredOneOf, then epic_cross_project_reply + feedback_reply + replyEventFields, then GET /admin/agents + agent_list + agentFields, then the Needs you routes + needsYouItemFields + needsYouAnsweredFields + needs_you_answered), so its fingerprint was replaced, not bumped.
108
+ 1: '6e8615100a963fd9691ab651948d21e04c8d54a5b07446e959371d17b834cddd',
109
+ });
110
+
111
+ module.exports = { CONTRACT_VERSION, contractInfo, CONTRACT, contractFingerprint, CONTRACT_FINGERPRINTS };