claude-code-session-manager 0.138.0 → 0.140.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/.claude-plugin/marketplace.json +1 -1
- package/README.md +352 -79
- package/dist/assets/AppSettings-CMFEM68R.js +2 -0
- package/dist/assets/History--JwsFnbn.js +2 -0
- package/dist/assets/HomeClaudeConfig-ijEXs--3.js +3 -0
- package/dist/assets/{Panel-CeDiyuNn.js → Panel-CALyU0pe.js} +1 -1
- package/dist/assets/ProjectClaudeConfig-sdlA-fUb.js +26 -0
- package/dist/assets/Scheduler-YT3j8SUa.js +16 -0
- package/dist/assets/{SkillReferenceGraph-CFMK8NJh.js → SkillReferenceGraph-CxAuwhNN.js} +1 -1
- package/dist/assets/Skills-DtRzghn5.js +67 -0
- package/dist/assets/{TiptapBody-D1kTj-tn.js → TiptapBody-DApeu7x8.js} +60 -54
- package/dist/assets/ViewTabs-B7qLXRAH.js +1 -0
- package/dist/assets/{VoiceButton-CZeyPM31.js → VoiceButton-DtStfv1H.js} +1 -1
- package/dist/assets/{historyTotals-B00l64Jw.js → historyTotals-ydfnwepc.js} +1 -1
- package/dist/assets/index-CtxruO1L.js +3121 -0
- package/dist/assets/{index-62tyjEQB.css → index-DKXdXfka.css} +1 -1
- package/dist/index.html +2 -2
- package/dist-web/app.css +1 -1
- package/dist-web/app.js +467 -451
- package/package.json +17 -6
- package/plugins/AGENTS.md +60 -0
- package/plugins/CLAUDE.md +1 -60
- package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
- package/plugins/session-manager-dev/skills/builder/SKILL.md +12 -4
- package/plugins/session-manager-dev/skills/builder/scripts/publish-preflight.cjs +255 -0
- package/plugins/session-manager-dev/skills/develop/SKILL.md +36 -22
- package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +5 -4
- package/plugins/session-manager-dev/skills/maintaining-md-network/audit.md +4 -2
- package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +16 -12
- package/plugins/session-manager-dev/skills/maintaining-md-network/migrate-to-agents-md.md +15 -0
- package/plugins/session-manager-dev/skills/maintaining-md-network/placement.md +50 -2
- package/plugins/session-manager-dev/skills/maintaining-md-network/plan.md +10 -10
- package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +117 -112
- package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdDuplicates.cjs +182 -0
- package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdLinks.cjs +340 -0
- package/scripts/README.md +2 -0
- package/scripts/hooks/guard-tool-risk.cjs +91 -0
- package/scripts/hooks/lib/guard-tool-risk-policy.cjs +217 -0
- package/scripts/ops-sweep.cjs +53 -23
- package/scripts/scheduler-mcp-server.cjs +360 -35
- package/src/main/build-info.json +4 -4
- package/src/main/chatRunner.cjs +2 -2
- package/src/main/config.cjs +112 -8
- package/src/main/docEdit.cjs +6 -1
- package/src/main/exchanges.cjs +70 -5
- package/src/main/files.cjs +7 -27
- package/src/main/health.cjs +48 -15
- package/src/main/historyAggregator.cjs +172 -63
- package/src/main/historyDashboard.cjs +87 -17
- package/src/main/index.cjs +78 -4
- package/src/main/ipcSchemas.cjs +233 -20
- package/src/main/lib/AGENTS.md +54 -0
- package/src/main/lib/CLAUDE.md +1 -54
- package/src/main/lib/agent-cli/adapters/codex.cjs +5 -2
- package/src/main/lib/agent-cli/agentCliIpc.cjs +18 -2
- package/src/main/lib/agent-cli/agentCliSessionStore.cjs +1 -0
- package/src/main/lib/agent-cli/agentCliTurn.cjs +20 -2
- package/src/main/lib/agent-cli/geminiContextDefaults.cjs +94 -0
- package/src/main/lib/claude/effectiveModelInfo.cjs +92 -22
- package/src/main/lib/claude/jobSandboxPolicy.cjs +202 -0
- package/src/main/lib/claude/modelPricing.cjs +148 -0
- package/src/main/lib/claude/personaToolScope.cjs +12 -6
- package/src/main/lib/claude/rateLimitDetect.cjs +13 -2
- package/src/main/lib/claude/runClaudeP.cjs +6 -1
- package/src/main/lib/claude/toolRiskIpc.cjs +177 -0
- package/src/main/lib/claude/toolRiskMarks.cjs +373 -0
- package/src/main/lib/demo-video-kit/seedKit.cjs +27 -6
- package/src/main/lib/ephemeralCwd.cjs +37 -2
- package/src/main/lib/epic/delegationReadiness.cjs +42 -9
- package/src/main/lib/epic/epicAdminRoutes.cjs +121 -0
- package/src/main/lib/epic/epicJobReceipt.cjs +87 -0
- package/src/main/lib/epic/epicOutsideRead.cjs +423 -0
- package/src/main/lib/epic/epicOutsideState.cjs +233 -0
- package/src/main/lib/epic/epicSettle.cjs +1 -1
- package/src/main/lib/epic/epicStateWatcher.cjs +157 -0
- package/src/main/lib/epic/epicSweepValidator.cjs +7 -2
- package/src/main/lib/epic/epicValidationHook.cjs +24 -4
- package/src/main/lib/epic/externalRef.cjs +37 -0
- package/src/main/lib/epic/externalRefIndex.cjs +136 -0
- package/src/main/lib/epic/guardSpawnSettings.cjs +57 -1
- package/src/main/lib/epic/restorableSessions.cjs +151 -17
- package/src/main/lib/epic/transcriptUsage.cjs +197 -0
- package/src/main/lib/externalContract.cjs +137 -0
- package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +176 -5
- package/src/main/lib/feedback-remote/crossProjectReply.cjs +186 -9
- package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -6
- package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +50 -8
- package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +218 -4
- package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +19 -3
- package/src/main/lib/feedback-remote/feedbackImages.cjs +171 -0
- package/src/main/lib/feedback-remote/localAdminHttp.cjs +11 -10
- package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +167 -21
- package/src/main/lib/feedback-remote/needsYouAdminRoutes.cjs +133 -0
- package/src/main/lib/feedback-remote/needsYouIpc.cjs +50 -0
- package/src/main/lib/feedback-remote/needsYouStore.cjs +285 -0
- package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +98 -1
- package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +5 -0
- package/src/main/lib/git/branchSweep.cjs +209 -4
- package/src/main/lib/git/gitWorktree.cjs +41 -5
- package/src/main/lib/guardShims.cjs +1 -1
- package/src/main/lib/historyRollup.cjs +58 -5
- package/src/main/lib/insideHome.cjs +27 -1
- package/src/main/lib/mcpToolCatalog.cjs +232 -25
- package/src/main/lib/mdDocCensus.cjs +59 -78
- package/src/main/lib/mdDocRefs.cjs +71 -93
- package/src/main/lib/mdNetworkScan.cjs +245 -250
- package/src/main/lib/mdReviewRecord.cjs +22 -9
- package/src/main/lib/memoryMdNetwork.cjs +5 -12
- package/src/main/lib/opsOwnership.cjs +18 -2
- package/src/main/lib/opsRetentionSettings.cjs +28 -4
- package/src/main/lib/persona-macro/agentAdminRoutes.cjs +121 -0
- package/src/main/lib/persona-macro/macroJobDispatch.cjs +90 -20
- package/src/main/lib/persona-macro/macroJobIpc.cjs +144 -46
- package/src/main/lib/persona-macro/macroJobStatus.cjs +87 -9
- package/src/main/lib/persona-macro/macroLibrary.cjs +95 -5
- package/src/main/lib/persona-macro/personaImportHealth.cjs +78 -17
- package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +96 -0
- package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
- package/src/main/lib/prd/depSlugResolve.cjs +104 -4
- package/src/main/lib/prd/prdAdminRoutes.cjs +35 -2
- package/src/main/lib/prd/prdCreate.cjs +351 -23
- package/src/main/lib/prd/prdDisposition.cjs +11 -2
- package/src/main/lib/prd/prdFrontmatter.cjs +96 -3
- package/src/main/lib/process/loginItem.cjs +171 -0
- package/src/main/lib/process/loginItemPlan.cjs +193 -0
- package/src/main/lib/project-pages/playerBridge.cjs +4 -0
- package/src/main/lib/project-pages/videoReview.cjs +268 -0
- package/src/main/lib/project-pages/videoReviewIpc.cjs +229 -0
- package/src/main/lib/promptSessionSchema.cjs +4 -0
- package/src/main/lib/remoteTranscriptTail.cjs +32 -1
- package/src/main/lib/scheduler/cpuSample.cjs +131 -4
- package/src/main/lib/scheduler/fixPlanSlug.cjs +4 -3
- package/src/main/lib/scheduler/loadGate.cjs +24 -6
- package/src/main/lib/scheduler/planRecordHarvest.cjs +108 -0
- package/src/main/lib/scheduler/planRecordRetention.cjs +144 -0
- package/src/main/lib/scheduler/queueStore.cjs +7 -0
- package/src/main/lib/scheduler/rcaReport.cjs +21 -1
- package/src/main/lib/scheduler/reaperHelpers.cjs +35 -5
- package/src/main/lib/scheduler/runLogRetention.cjs +104 -3
- package/src/main/lib/scheduler/scheduleJobSchema.cjs +3 -0
- package/src/main/lib/scheduler/schedulerBatch.cjs +25 -48
- package/src/main/lib/scheduler/schedulerPaths.cjs +12 -0
- package/src/main/lib/scheduler/sessionSlots.cjs +176 -21
- package/src/main/lib/scheduler/validationQuality.cjs +282 -0
- package/src/main/lib/scheduler/validatorVerdictSchema.cjs +254 -0
- package/src/main/lib/tasks/taskAdminRoutes.cjs +641 -0
- package/src/main/lib/tasks/taskIpc.cjs +80 -0
- package/src/main/lib/tasks/taskLedger.cjs +502 -0
- package/src/main/lib/tasks/taskRun.cjs +313 -0
- package/src/main/lib/tasks/taskSwitch.cjs +120 -0
- package/src/main/lib/telemetry/auditEvents.cjs +176 -0
- package/src/main/lib/telemetry/eventsAdminRoutes.cjs +45 -0
- package/src/main/loginItemIpc.cjs +35 -0
- package/src/main/loopEfficiencyHandlers.cjs +11 -2
- package/src/main/projectPages.cjs +6 -15
- package/src/main/promptSessionEvents.cjs +9 -1
- package/src/main/queueOps.cjs +260 -3
- package/src/main/runVerify.cjs +53 -25
- package/src/main/scheduler/AGENTS.md +26 -0
- package/src/main/scheduler/CLAUDE.md +1 -26
- package/src/main/scheduler/budget.cjs +239 -9
- package/src/main/scheduler/cancelDependents.cjs +154 -0
- package/src/main/scheduler/prdParser.cjs +4 -1
- package/src/main/scheduler/starvation.cjs +20 -18
- package/src/main/scheduler.cjs +774 -64
- package/src/main/supervisor.cjs +5 -1
- package/src/main/templates/PRD_AUTHORING.md +7 -1
- package/src/main/transcripts.cjs +62 -7
- package/src/main/validationQualityHandlers.cjs +199 -0
- package/src/main/webRemote.cjs +132 -20
- package/src/preload/api.d.ts +434 -28
- package/src/preload/apiSurface.cjs +7 -0
- package/src/preload/apiSurface.json +485 -81
- package/src/preload/index.cjs +38 -5
- package/src/seed/agents/validator.md +19 -8
- package/dist/assets/AgentLibrary-C1d_D7uQ.js +0 -2
- package/dist/assets/AppSettings-CgDhqrsU.js +0 -2
- package/dist/assets/Button-Bk23rEnZ.js +0 -1
- package/dist/assets/DocumentEditorPane-BqY5Nq6W.js +0 -1
- package/dist/assets/Extensions-CXem-uwI.js +0 -2
- package/dist/assets/History-BwO3coo4.js +0 -2
- package/dist/assets/Library-BDV69fSe.js +0 -32
- package/dist/assets/ListDetail-CD-Fm6mh.js +0 -1
- package/dist/assets/ProjectClaudeConfig-NjdKdwe8.js +0 -25
- package/dist/assets/ProvenanceBadge-Bu8NmI_R.js +0 -1
- package/dist/assets/Scheduler-CkhTvG7C.js +0 -16
- package/dist/assets/Settings-COT34hBF.js +0 -2
- package/dist/assets/Skills-BgexoUkQ.js +0 -29
- package/dist/assets/SourceChip-BXjcdeb1.js +0 -1
- package/dist/assets/SystemPrompt-CeeH3EeW.js +0 -1
- package/dist/assets/Toggle-CENi19iK.js +0 -1
- package/dist/assets/ViewTabs-DDBb0x96.js +0 -1
- package/dist/assets/claude-settings-schema-COigsajx.js +0 -3
- package/dist/assets/index-CgCxpunJ.js +0 -3116
|
@@ -7,6 +7,7 @@ const os = require('node:os');
|
|
|
7
7
|
const { schemas } = require('./ipcSchemas.cjs');
|
|
8
8
|
const historyRollup = require('./lib/historyRollup.cjs');
|
|
9
9
|
const { sendIfAlive } = require('./lib/sendToRenderer.cjs');
|
|
10
|
+
const { costOfUsage } = require('./lib/claude/modelPricing.cjs');
|
|
10
11
|
|
|
11
12
|
const PROJECTS_DIR = path.join(os.homedir(), '.claude', 'projects');
|
|
12
13
|
const PARSE_BUDGET_MS = 2_000;
|
|
@@ -18,37 +19,6 @@ const MAX_FILE_BYTES = 20 * 1024 * 1024;
|
|
|
18
19
|
// range hit cache instead of self-evicting mid-scan and spuriously truncating.
|
|
19
20
|
const CACHE_MAX = 50_000;
|
|
20
21
|
|
|
21
|
-
// Dollars per million tokens (input / output / cache-read). Cache-read
|
|
22
|
-
// tokens are priced far below input because they're served from
|
|
23
|
-
// Anthropic's prompt cache, not re-processed — this is what makes the
|
|
24
|
-
// cache-savings figure in the dashboard real money, not a vanity stat.
|
|
25
|
-
// fable: Claude Fable 5.1 (claude-fable-5-1) — $10/$50 per MTok input/output,
|
|
26
|
-
// cache reads at $0.25/MTok (the `claude-api` skill's model reference and its
|
|
27
|
-
// Claude Fable 5.1 migration notes, both cached 2026-06-24).
|
|
28
|
-
const MODEL_PRICING = {
|
|
29
|
-
opus: { i: 15, o: 75, c: 1.5 },
|
|
30
|
-
sonnet: { i: 3, o: 15, c: 0.3 },
|
|
31
|
-
haiku: { i: 0.8, o: 4, c: 0.08 },
|
|
32
|
-
fable: { i: 10, o: 50, c: 0.25 },
|
|
33
|
-
};
|
|
34
|
-
const DEFAULT_PRICING_KEY = 'sonnet'; // fallback for unrecognized model ids
|
|
35
|
-
|
|
36
|
-
/**
|
|
37
|
-
* Resolve a raw model id (e.g. "claude-opus-4-8-20260115") to a pricing
|
|
38
|
-
* bucket key. Model ids aren't stable enough to match exactly, so this is a
|
|
39
|
-
* case-insensitive substring check. Unrecognized ids fall back to
|
|
40
|
-
* DEFAULT_PRICING_KEY and are flagged so callers can annotate them as
|
|
41
|
-
* estimated rather than exact.
|
|
42
|
-
*/
|
|
43
|
-
function resolvePricingKey(modelId) {
|
|
44
|
-
const id = String(modelId ?? '').toLowerCase();
|
|
45
|
-
if (id.includes('opus')) return { key: 'opus', estimated: false };
|
|
46
|
-
if (id.includes('sonnet')) return { key: 'sonnet', estimated: false };
|
|
47
|
-
if (id.includes('haiku')) return { key: 'haiku', estimated: false };
|
|
48
|
-
if (id.includes('fable')) return { key: 'fable', estimated: false };
|
|
49
|
-
return { key: DEFAULT_PRICING_KEY, estimated: true };
|
|
50
|
-
}
|
|
51
|
-
|
|
52
22
|
// ── LRU cache ─────────────────────────────────────────────────────────────────
|
|
53
23
|
// Shared implementation: lib/util/lruCache.cjs (re-exported below for existing callers).
|
|
54
24
|
const { LRUCache } = require('./lib/util/lruCache.cjs');
|
|
@@ -96,7 +66,10 @@ async function appendRollupAndNotify(entries) {
|
|
|
96
66
|
|
|
97
67
|
/**
|
|
98
68
|
* Cache for parseJSONL results.
|
|
99
|
-
* Entry shape: { mtimeMs: number, size: number, readOffset: number, inode: number,
|
|
69
|
+
* Entry shape: { mtimeMs: number, size: number, readOffset: number, inode: number,
|
|
70
|
+
* recentIds: Map<string, usage>, result: AggrResult }
|
|
71
|
+
* `recentIds` = the last 64 message ids with their counted usage, handed to
|
|
72
|
+
* the next tail parse so a message straddling two reads is counted once.
|
|
100
73
|
* `size` mirrors stat.size (used for exact-hit comparison).
|
|
101
74
|
* `readOffset` is the byte position of the end of the last complete line
|
|
102
75
|
* (≤ size) — the start position for the next tail-read so we never start
|
|
@@ -177,8 +150,17 @@ async function readSlice(filePath, from, to) {
|
|
|
177
150
|
|
|
178
151
|
// ── line scanners ─────────────────────────────────────────────────────────────
|
|
179
152
|
|
|
153
|
+
// cacheCreation1hTokens is the 1-hour part of cacheCreationTokens
|
|
154
|
+
// (usage.cache_creation.ephemeral_1h_input_tokens); it is priced differently
|
|
155
|
+
// from the 5-minute part, so it is kept alongside the sum.
|
|
156
|
+
const USAGE_FIELDS = ['inputTokens', 'outputTokens', 'cacheReadTokens', 'cacheCreationTokens', 'cacheCreation1hTokens'];
|
|
157
|
+
/** How many recent message ids the accumulator (and the cache entry) remembers. */
|
|
158
|
+
const RECENT_IDS_MAX = 64;
|
|
159
|
+
|
|
180
160
|
/**
|
|
181
161
|
* Scan JSONL lines into an aggregate accumulator (mutates acc).
|
|
162
|
+
* acc.recentIds (Map<message.id, counted usage>, created on demand, last
|
|
163
|
+
* RECENT_IDS_MAX ids) makes a repeated message.id count once.
|
|
182
164
|
* Returns { firstTs, lastTs } — firstTs is only captured when
|
|
183
165
|
* captureFirst=true (else null); lastTs is the most recent event timestamp
|
|
184
166
|
* seen in this batch of lines (file order, so simply "last one wins").
|
|
@@ -209,22 +191,48 @@ function scanAggrLines(lines, acc, captureFirst) {
|
|
|
209
191
|
const outT = usage.output_tokens ?? usage.outputTokens;
|
|
210
192
|
const cacheR = usage.cache_read_input_tokens ?? usage.cacheReadInputTokens;
|
|
211
193
|
const cacheC = usage.cache_creation_input_tokens ?? usage.cacheCreationInputTokens;
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
194
|
+
const cacheC1h = usage.cache_creation?.ephemeral_1h_input_tokens;
|
|
195
|
+
const vals = {
|
|
196
|
+
inputTokens: typeof inT === 'number' ? inT : 0,
|
|
197
|
+
outputTokens: typeof outT === 'number' ? outT : 0,
|
|
198
|
+
cacheReadTokens: typeof cacheR === 'number' ? cacheR : 0,
|
|
199
|
+
cacheCreationTokens: typeof cacheC === 'number' ? cacheC : 0,
|
|
200
|
+
cacheCreation1hTokens: typeof cacheC1h === 'number' ? cacheC1h : 0,
|
|
201
|
+
};
|
|
202
|
+
// A transcript writes one line per content block of a message and
|
|
203
|
+
// repeats the message's usage on each (same rule as
|
|
204
|
+
// lib/epic/transcriptUsage.cjs): per message.id, the counted value of
|
|
205
|
+
// each field is the largest seen, so a repeat adds only the increase.
|
|
206
|
+
const msgId = obj.message?.id;
|
|
207
|
+
let add = vals;
|
|
208
|
+
if (typeof msgId === 'string' && msgId) {
|
|
209
|
+
const recent = acc.recentIds ?? (acc.recentIds = new Map());
|
|
210
|
+
const prevVals = recent.get(msgId);
|
|
211
|
+
if (prevVals) {
|
|
212
|
+
add = {};
|
|
213
|
+
const next = {};
|
|
214
|
+
for (const k of USAGE_FIELDS) {
|
|
215
|
+
const prevK = prevVals[k] || 0;
|
|
216
|
+
add[k] = Math.max(0, vals[k] - prevK);
|
|
217
|
+
next[k] = Math.max(vals[k], prevK);
|
|
218
|
+
}
|
|
219
|
+
recent.delete(msgId);
|
|
220
|
+
recent.set(msgId, next);
|
|
221
|
+
} else {
|
|
222
|
+
recent.set(msgId, { ...vals });
|
|
223
|
+
while (recent.size > RECENT_IDS_MAX) recent.delete(recent.keys().next().value);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
for (const k of USAGE_FIELDS) acc[k] = (acc[k] || 0) + add[k];
|
|
216
227
|
|
|
217
228
|
// Only assistant usage lines carry model+usage together in practice;
|
|
218
229
|
// read defensively rather than assuming every usage line has a model.
|
|
219
230
|
const modelId = obj.message?.model;
|
|
220
231
|
if (typeof modelId === 'string' && modelId) {
|
|
221
232
|
const bucket = acc.byModel[modelId] ?? (acc.byModel[modelId] = {
|
|
222
|
-
inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheCreationTokens: 0,
|
|
233
|
+
inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheCreationTokens: 0, cacheCreation1hTokens: 0,
|
|
223
234
|
});
|
|
224
|
-
|
|
225
|
-
if (typeof outT === 'number') bucket.outputTokens += outT;
|
|
226
|
-
if (typeof cacheR === 'number') bucket.cacheReadTokens += cacheR;
|
|
227
|
-
if (typeof cacheC === 'number') bucket.cacheCreationTokens += cacheC;
|
|
235
|
+
for (const k of USAGE_FIELDS) bucket[k] = (bucket[k] || 0) + add[k];
|
|
228
236
|
}
|
|
229
237
|
}
|
|
230
238
|
|
|
@@ -281,6 +289,7 @@ async function parseJSONL(filePath, stat) {
|
|
|
281
289
|
outputTokens: 0,
|
|
282
290
|
cacheReadTokens: 0,
|
|
283
291
|
cacheCreationTokens: 0,
|
|
292
|
+
cacheCreation1hTokens: 0,
|
|
284
293
|
toolCallCount: 0,
|
|
285
294
|
toolBreakdown: {},
|
|
286
295
|
byModel: {},
|
|
@@ -318,6 +327,8 @@ async function parseJSONL(filePath, stat) {
|
|
|
318
327
|
const readFrom = cached.readOffset ?? cached.size;
|
|
319
328
|
const tail = await readSlice(filePath, readFrom, stat.size);
|
|
320
329
|
const delta = emptyAcc();
|
|
330
|
+
// Copy, so a failed tail parse leaves the cached memory untouched.
|
|
331
|
+
delta.recentIds = new Map(cached.recentIds ?? []);
|
|
321
332
|
const { lastTs: deltaLastTs } = scanAggrLines(tail.split('\n'), delta, false);
|
|
322
333
|
const prev = cached.result;
|
|
323
334
|
const merged = {
|
|
@@ -326,6 +337,7 @@ async function parseJSONL(filePath, stat) {
|
|
|
326
337
|
outputTokens: prev.outputTokens + delta.outputTokens,
|
|
327
338
|
cacheReadTokens: prev.cacheReadTokens + delta.cacheReadTokens,
|
|
328
339
|
cacheCreationTokens: prev.cacheCreationTokens + delta.cacheCreationTokens,
|
|
340
|
+
cacheCreation1hTokens: (prev.cacheCreation1hTokens || 0) + delta.cacheCreation1hTokens,
|
|
329
341
|
toolCallCount: prev.toolCallCount + delta.toolCallCount,
|
|
330
342
|
toolBreakdown: { ...prev.toolBreakdown },
|
|
331
343
|
byModel: {},
|
|
@@ -343,19 +355,20 @@ async function parseJSONL(filePath, stat) {
|
|
|
343
355
|
}
|
|
344
356
|
for (const [modelId, deltaBucket] of Object.entries(delta.byModel)) {
|
|
345
357
|
const b = merged.byModel[modelId] ?? (merged.byModel[modelId] = {
|
|
346
|
-
inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheCreationTokens: 0,
|
|
358
|
+
inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheCreationTokens: 0, cacheCreation1hTokens: 0,
|
|
347
359
|
});
|
|
348
360
|
b.inputTokens += deltaBucket.inputTokens;
|
|
349
361
|
b.outputTokens += deltaBucket.outputTokens;
|
|
350
362
|
b.cacheReadTokens += deltaBucket.cacheReadTokens;
|
|
351
363
|
b.cacheCreationTokens += deltaBucket.cacheCreationTokens;
|
|
364
|
+
b.cacheCreation1hTokens = (b.cacheCreation1hTokens || 0) + (deltaBucket.cacheCreation1hTokens || 0);
|
|
352
365
|
}
|
|
353
366
|
// readOffset advances to the last complete newline so the next tail
|
|
354
367
|
// always starts at a line boundary. size stays at stat.size so the
|
|
355
368
|
// exact-hit check works correctly on the next call.
|
|
356
369
|
const lastNl = tail.lastIndexOf('\n');
|
|
357
370
|
const readOffset = lastNl >= 0 ? readFrom + lastNl + 1 : readFrom;
|
|
358
|
-
aggrCache.set(filePath, { mtimeMs: stat.mtimeMs, size: stat.size, readOffset, inode: stat.ino, result: merged });
|
|
371
|
+
aggrCache.set(filePath, { mtimeMs: stat.mtimeMs, size: stat.size, readOffset, inode: stat.ino, recentIds: delta.recentIds, result: merged });
|
|
359
372
|
return { result: merged, cacheHit: false };
|
|
360
373
|
} catch {
|
|
361
374
|
// fall through to full parse
|
|
@@ -373,6 +386,9 @@ async function parseJSONL(filePath, stat) {
|
|
|
373
386
|
|
|
374
387
|
const acc = emptyAcc();
|
|
375
388
|
const { firstTs, lastTs } = scanAggrLines(text.split('\n'), acc, true);
|
|
389
|
+
// The id memory lives on the cache entry, not in the returned result.
|
|
390
|
+
const recentIds = acc.recentIds ?? new Map();
|
|
391
|
+
delete acc.recentIds;
|
|
376
392
|
acc.firstEventTs = firstTs;
|
|
377
393
|
acc.lastEventTs = lastTs;
|
|
378
394
|
|
|
@@ -386,7 +402,7 @@ async function parseJSONL(filePath, stat) {
|
|
|
386
402
|
|
|
387
403
|
const lastNlFull = text.lastIndexOf('\n');
|
|
388
404
|
const readOffsetFull = lastNlFull >= 0 ? lastNlFull + 1 : 0;
|
|
389
|
-
aggrCache.set(filePath, { mtimeMs: stat.mtimeMs, size: stat.size, readOffset: readOffsetFull, inode: stat.ino, result: acc });
|
|
405
|
+
aggrCache.set(filePath, { mtimeMs: stat.mtimeMs, size: stat.size, readOffset: readOffsetFull, inode: stat.ino, recentIds, result: acc });
|
|
390
406
|
return { result: acc, cacheHit: false };
|
|
391
407
|
}
|
|
392
408
|
|
|
@@ -405,6 +421,7 @@ function emptyBucket(sessionDate, encodedCwd) {
|
|
|
405
421
|
outputTokens: 0,
|
|
406
422
|
cacheReadTokens: 0,
|
|
407
423
|
cacheCreationTokens: 0,
|
|
424
|
+
cacheCreation1hTokens: 0,
|
|
408
425
|
toolCallCount: 0,
|
|
409
426
|
toolBreakdown: {},
|
|
410
427
|
byModel: {},
|
|
@@ -421,18 +438,20 @@ function foldParsedIntoBucket(b, parsed) {
|
|
|
421
438
|
b.outputTokens += parsed.outputTokens;
|
|
422
439
|
b.cacheReadTokens += parsed.cacheReadTokens;
|
|
423
440
|
b.cacheCreationTokens += parsed.cacheCreationTokens;
|
|
441
|
+
b.cacheCreation1hTokens = (b.cacheCreation1hTokens || 0) + (parsed.cacheCreation1hTokens || 0);
|
|
424
442
|
b.toolCallCount += parsed.toolCallCount;
|
|
425
443
|
for (const [tool, cnt] of Object.entries(parsed.toolBreakdown)) {
|
|
426
444
|
b.toolBreakdown[tool] = (b.toolBreakdown[tool] ?? 0) + cnt;
|
|
427
445
|
}
|
|
428
446
|
for (const [modelId, srcBucket] of Object.entries(parsed.byModel ?? {})) {
|
|
429
447
|
const dst = b.byModel[modelId] ?? (b.byModel[modelId] = {
|
|
430
|
-
inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheCreationTokens: 0,
|
|
448
|
+
inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheCreationTokens: 0, cacheCreation1hTokens: 0,
|
|
431
449
|
});
|
|
432
450
|
dst.inputTokens += srcBucket.inputTokens;
|
|
433
451
|
dst.outputTokens += srcBucket.outputTokens;
|
|
434
452
|
dst.cacheReadTokens += srcBucket.cacheReadTokens;
|
|
435
453
|
dst.cacheCreationTokens += srcBucket.cacheCreationTokens;
|
|
454
|
+
dst.cacheCreation1hTokens = (dst.cacheCreation1hTokens || 0) + (srcBucket.cacheCreation1hTokens || 0);
|
|
436
455
|
}
|
|
437
456
|
b.sessionCount++;
|
|
438
457
|
b.errorCount += parsed.errorCount;
|
|
@@ -467,6 +486,7 @@ function bucketToRollupLines(b) {
|
|
|
467
486
|
outputTokens: mb.outputTokens,
|
|
468
487
|
cacheReadTokens: mb.cacheReadTokens,
|
|
469
488
|
cacheCreationTokens: mb.cacheCreationTokens,
|
|
489
|
+
cacheCreation1hTokens: mb.cacheCreation1hTokens || 0,
|
|
470
490
|
toolCallCount: 0,
|
|
471
491
|
toolBreakdown: {},
|
|
472
492
|
errorCount: 0,
|
|
@@ -478,12 +498,13 @@ function bucketToRollupLines(b) {
|
|
|
478
498
|
return lines;
|
|
479
499
|
}
|
|
480
500
|
|
|
481
|
-
function finalizedMarkerLine(date) {
|
|
501
|
+
function finalizedMarkerLine(date, cycleStartedAt) {
|
|
482
502
|
return {
|
|
483
503
|
date,
|
|
484
504
|
projectDir: historyRollup.FINALIZED_PROJECT_ID,
|
|
485
505
|
modelId: historyRollup.FINALIZED_MODEL_ID,
|
|
486
506
|
finalizedAt: Date.now(),
|
|
507
|
+
cycleStartedAt,
|
|
487
508
|
v: historyRollup.ROLLUP_VERSION,
|
|
488
509
|
};
|
|
489
510
|
}
|
|
@@ -516,11 +537,21 @@ function rollupMapToRows(map, finalizedDates) {
|
|
|
516
537
|
} else {
|
|
517
538
|
const dst = row.byModel[bucket.modelId] ?? (row.byModel[bucket.modelId] = {
|
|
518
539
|
inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheCreationTokens: 0,
|
|
540
|
+
cacheCreation1hTokens: 0, cacheCreationUnknownTokens: 0,
|
|
519
541
|
});
|
|
520
542
|
dst.inputTokens += bucket.inputTokens || 0;
|
|
521
543
|
dst.outputTokens += bucket.outputTokens || 0;
|
|
522
544
|
dst.cacheReadTokens += bucket.cacheReadTokens || 0;
|
|
523
545
|
dst.cacheCreationTokens += bucket.cacheCreationTokens || 0;
|
|
546
|
+
// A line written before v4 has no 1-hour split: its cache writes count
|
|
547
|
+
// as unknown (costOfUsage prices them at the 1-hour rate, estimated).
|
|
548
|
+
// Both parts are plain sums, so several lines in one bucket stay right.
|
|
549
|
+
if (typeof bucket.cacheCreation1hTokens === 'number') {
|
|
550
|
+
dst.cacheCreation1hTokens += bucket.cacheCreation1hTokens;
|
|
551
|
+
row.cacheCreation1hTokens += bucket.cacheCreation1hTokens;
|
|
552
|
+
} else {
|
|
553
|
+
dst.cacheCreationUnknownTokens += bucket.cacheCreationTokens || 0;
|
|
554
|
+
}
|
|
524
555
|
row.inputTokens += bucket.inputTokens || 0;
|
|
525
556
|
row.outputTokens += bucket.outputTokens || 0;
|
|
526
557
|
row.cacheReadTokens += bucket.cacheReadTokens || 0;
|
|
@@ -577,6 +608,22 @@ async function finalizeClosedDays({ budgetMs, dryRun = false, cursorPath } = {})
|
|
|
577
608
|
}
|
|
578
609
|
}
|
|
579
610
|
|
|
611
|
+
// Skip threshold: local midnight of the day the last completed pass (at
|
|
612
|
+
// this ROLLUP_VERSION) started. That pass skipped only that day's content,
|
|
613
|
+
// so a folder with no transcript modified since that midnight holds nothing
|
|
614
|
+
// it did not already count. No such marker => no threshold => full pass.
|
|
615
|
+
let skipBeforeMs = null;
|
|
616
|
+
try {
|
|
617
|
+
const lastCycle = await historyRollup.readNewestFinalizedCycleStart();
|
|
618
|
+
if (lastCycle !== null) {
|
|
619
|
+
const midnight = new Date(lastCycle);
|
|
620
|
+
midnight.setHours(0, 0, 0, 0);
|
|
621
|
+
skipBeforeMs = midnight.getTime();
|
|
622
|
+
}
|
|
623
|
+
} catch {
|
|
624
|
+
skipBeforeMs = null;
|
|
625
|
+
}
|
|
626
|
+
|
|
580
627
|
let projectDirs;
|
|
581
628
|
try {
|
|
582
629
|
projectDirs = await fsp.readdir(PROJECTS_DIR, { withFileTypes: true });
|
|
@@ -592,6 +639,7 @@ async function finalizeClosedDays({ budgetMs, dryRun = false, cursorPath } = {})
|
|
|
592
639
|
const buckets = new Map();
|
|
593
640
|
let partial = false;
|
|
594
641
|
let walkedLast = lastDir;
|
|
642
|
+
const taskIds = await taskSessionIdSet();
|
|
595
643
|
|
|
596
644
|
for (const projEntry of projectDirs) {
|
|
597
645
|
if (deadline !== null && Date.now() >= deadline) {
|
|
@@ -605,13 +653,21 @@ async function finalizeClosedDays({ budgetMs, dryRun = false, cursorPath } = {})
|
|
|
605
653
|
let files;
|
|
606
654
|
try { files = await fsp.readdir(projectDir, { withFileTypes: true }); } catch { walkedLast = encodedCwd; continue; }
|
|
607
655
|
|
|
656
|
+
// Stat the whole folder first: a day's lines are whole-folder totals, so
|
|
657
|
+
// the folder is either skipped entirely or read entirely.
|
|
658
|
+
const stated = [];
|
|
608
659
|
for (const fileEntry of files) {
|
|
609
660
|
if (!fileEntry.name.endsWith('.jsonl')) continue;
|
|
661
|
+
if (isTaskTranscript(fileEntry.name, taskIds)) continue;
|
|
610
662
|
const filePath = path.join(projectDir, fileEntry.name);
|
|
663
|
+
try { stated.push({ filePath, stat: await fsp.stat(filePath) }); } catch { continue; }
|
|
664
|
+
}
|
|
665
|
+
if (skipBeforeMs !== null && !stated.some((f) => f.stat.mtimeMs >= skipBeforeMs)) {
|
|
666
|
+
walkedLast = encodedCwd;
|
|
667
|
+
continue;
|
|
668
|
+
}
|
|
611
669
|
|
|
612
|
-
|
|
613
|
-
try { stat = await fsp.stat(filePath); } catch { continue; }
|
|
614
|
-
|
|
670
|
+
for (const { filePath, stat } of stated) {
|
|
615
671
|
const { result: parsed } = await parseJSONL(filePath, stat);
|
|
616
672
|
if (parsed.skipped) continue;
|
|
617
673
|
|
|
@@ -633,7 +689,7 @@ async function finalizeClosedDays({ budgetMs, dryRun = false, cursorPath } = {})
|
|
|
633
689
|
// Only stamp dates as finalized (safe to trust with no live re-scan) once a
|
|
634
690
|
// full cycle has covered every project directory — possibly across calls.
|
|
635
691
|
if (!partial) {
|
|
636
|
-
for (const date of dates) entries.push(finalizedMarkerLine(date));
|
|
692
|
+
for (const date of dates) entries.push(finalizedMarkerLine(date, cycleStartedAt));
|
|
637
693
|
}
|
|
638
694
|
|
|
639
695
|
if (!dryRun) {
|
|
@@ -721,6 +777,7 @@ async function computeIntradayBuckets() {
|
|
|
721
777
|
}
|
|
722
778
|
|
|
723
779
|
const dirEntries = projectDirs.filter((e) => e.isDirectory());
|
|
780
|
+
const taskIds = await taskSessionIdSet();
|
|
724
781
|
|
|
725
782
|
// Directory count (thousands) is far smaller than file count (tens of
|
|
726
783
|
// thousands), so stat-ing every directory concurrently is cheap and tells
|
|
@@ -753,6 +810,7 @@ async function computeIntradayBuckets() {
|
|
|
753
810
|
intradayDirRegistry.set(d.encodedCwd, { mtimeMs: d.mtimeMs, fileNames });
|
|
754
811
|
}
|
|
755
812
|
for (const name of fileNames) {
|
|
813
|
+
if (isTaskTranscript(name, taskIds)) continue;
|
|
756
814
|
const filePath = path.join(d.dirPath, name);
|
|
757
815
|
if (intradayNotToday.has(filePath)) continue;
|
|
758
816
|
fileCandidates.push({ filePath, encodedCwd: d.encodedCwd });
|
|
@@ -822,6 +880,57 @@ async function refreshIntradayToday() {
|
|
|
822
880
|
return { date: today, projectsUpdated: buckets.size, strategy: INTRADAY_STRATEGY };
|
|
823
881
|
}
|
|
824
882
|
|
|
883
|
+
// ── persisted Task transcripts ────────────────────────────────────────────────
|
|
884
|
+
//
|
|
885
|
+
// A Task that persists its claude session (runtime.persistSession / resume)
|
|
886
|
+
// leaves a transcript under ~/.claude/projects/ AND an sm-task ledger row that
|
|
887
|
+
// historyDashboard joins in. Counting the transcript too would double it, so
|
|
888
|
+
// every rollup-feeding walk skips `<sessionId>.jsonl` for a persisted Task id.
|
|
889
|
+
// The ledger's start line is written before the process spawns, so a mid-run
|
|
890
|
+
// pass never meets a Task transcript whose id is not yet in this Set.
|
|
891
|
+
|
|
892
|
+
let taskReadersOverride = null;
|
|
893
|
+
|
|
894
|
+
/** Test-only: inject { listTaskProjects, listPersistedSessionIds }; null restores the real modules. */
|
|
895
|
+
function setTaskSessionReadersForTests(readers) {
|
|
896
|
+
taskReadersOverride = readers || null;
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
/**
|
|
900
|
+
* Set of persisted Task session ids across every project in
|
|
901
|
+
* taskSwitch.listTaskProjects(). Never throws: a failed project listing yields
|
|
902
|
+
* an empty Set, a failed ledger read skips that project only.
|
|
903
|
+
*/
|
|
904
|
+
async function taskSessionIdSet(deps = taskReadersOverride) {
|
|
905
|
+
const ids = new Set();
|
|
906
|
+
let listTaskProjects;
|
|
907
|
+
let listPersistedSessionIds;
|
|
908
|
+
try {
|
|
909
|
+
listTaskProjects = deps?.listTaskProjects ?? require('./lib/tasks/taskSwitch.cjs').listTaskProjects;
|
|
910
|
+
listPersistedSessionIds = deps?.listPersistedSessionIds ?? require('./lib/tasks/taskLedger.cjs').listPersistedSessionIds;
|
|
911
|
+
} catch {
|
|
912
|
+
return ids;
|
|
913
|
+
}
|
|
914
|
+
let projects;
|
|
915
|
+
try { projects = await listTaskProjects(); } catch { return ids; }
|
|
916
|
+
if (!Array.isArray(projects)) return ids;
|
|
917
|
+
for (const p of projects) {
|
|
918
|
+
const cwd = typeof p === 'string' ? p : p?.cwd;
|
|
919
|
+
if (typeof cwd !== 'string' || !cwd) continue;
|
|
920
|
+
try {
|
|
921
|
+
const got = await listPersistedSessionIds(cwd);
|
|
922
|
+
if (got) for (const id of got) if (typeof id === 'string' && id) ids.add(id);
|
|
923
|
+
} catch {
|
|
924
|
+
// Unreadable ledger: this project's ids are skipped; the pass goes on.
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
return ids;
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
function isTaskTranscript(fileName, taskIds) {
|
|
931
|
+
return taskIds.size > 0 && taskIds.has(fileName.replace(/\.jsonl$/, ''));
|
|
932
|
+
}
|
|
933
|
+
|
|
825
934
|
// ── aggregate ─────────────────────────────────────────────────────────────────
|
|
826
935
|
|
|
827
936
|
async function aggregate(req) {
|
|
@@ -865,6 +974,7 @@ async function aggregate(req) {
|
|
|
865
974
|
} catch {
|
|
866
975
|
return { rows: [], partial: false, truncated: false, scannedMs: Date.now() - t0, cacheSavingsUsd: 0, rollupDays: 0, liveDays: 0 };
|
|
867
976
|
}
|
|
977
|
+
const taskIds = await taskSessionIdSet();
|
|
868
978
|
|
|
869
979
|
outer:
|
|
870
980
|
for (const projEntry of projectDirs) {
|
|
@@ -881,6 +991,7 @@ async function aggregate(req) {
|
|
|
881
991
|
|
|
882
992
|
for (const fileEntry of files) {
|
|
883
993
|
if (!fileEntry.name.endsWith('.jsonl')) continue;
|
|
994
|
+
if (isTaskTranscript(fileEntry.name, taskIds)) continue;
|
|
884
995
|
const filePath = path.join(projectDir, fileEntry.name);
|
|
885
996
|
|
|
886
997
|
let stat;
|
|
@@ -946,17 +1057,13 @@ async function aggregate(req) {
|
|
|
946
1057
|
const byModel = {};
|
|
947
1058
|
let estimatedCostUsd = 0;
|
|
948
1059
|
for (const [modelId, bucket] of Object.entries(b.byModel)) {
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
estimatedCostUsd += costUsd;
|
|
957
|
-
// What those cache-read tokens would have cost at the full input rate,
|
|
958
|
-
// minus what they actually cost at the cache rate.
|
|
959
|
-
cacheSavingsUsd += bucket.cacheReadTokens * (pricing.i - pricing.c) / 1e6;
|
|
1060
|
+
// Priced by lib/claude/modelPricing.cjs: the exact model's current rate,
|
|
1061
|
+
// cache writes split 5-minute / 1-hour; estimated when the model id or
|
|
1062
|
+
// the write split is unknown.
|
|
1063
|
+
const cost = costOfUsage(modelId, bucket);
|
|
1064
|
+
byModel[modelId] = { ...bucket, costUsd: cost.costUsd, ...(cost.estimated ? { estimated: true } : {}) };
|
|
1065
|
+
estimatedCostUsd += cost.costUsd;
|
|
1066
|
+
cacheSavingsUsd += cost.cacheSavingsUsd;
|
|
960
1067
|
}
|
|
961
1068
|
return { ...b, byModel, estimatedCostUsd };
|
|
962
1069
|
});
|
|
@@ -1023,7 +1130,6 @@ const remote = { aggregate };
|
|
|
1023
1130
|
module.exports = {
|
|
1024
1131
|
registerHistoryAggregatorHandlers,
|
|
1025
1132
|
remote,
|
|
1026
|
-
MODEL_PRICING,
|
|
1027
1133
|
finalizeClosedDays,
|
|
1028
1134
|
decodeCwd,
|
|
1029
1135
|
refreshIntradayToday,
|
|
@@ -1032,12 +1138,15 @@ module.exports = {
|
|
|
1032
1138
|
// exported for tests
|
|
1033
1139
|
scanAggrLines,
|
|
1034
1140
|
parseJSONL,
|
|
1035
|
-
resolvePricingKey,
|
|
1036
1141
|
CACHE_MAX,
|
|
1037
1142
|
LRUCache,
|
|
1038
1143
|
computeActiveMinutes,
|
|
1144
|
+
bucketToRollupLines,
|
|
1145
|
+
rollupMapToRows,
|
|
1039
1146
|
mapWithConcurrency,
|
|
1040
1147
|
resetIntradayRegistryForTests,
|
|
1148
|
+
setTaskSessionReadersForTests,
|
|
1149
|
+
taskSessionIdSet,
|
|
1041
1150
|
INTRADAY_STAT_CONCURRENCY,
|
|
1042
1151
|
// exported for historyDashboard.cjs (pure, no I/O at require-time; reused
|
|
1043
1152
|
// rather than re-implemented so date-range math stays in one place)
|
|
@@ -5,27 +5,85 @@
|
|
|
5
5
|
* instantly regardless of transcript corpus size or retention/cleanup.
|
|
6
6
|
*
|
|
7
7
|
* Only imports historyRollup.cjs (the rollup reader) and pure helpers
|
|
8
|
-
* re-exported from historyAggregator.cjs (
|
|
8
|
+
* re-exported from historyAggregator.cjs (date math) plus lib/claude/modelPricing.cjs (cost) — never
|
|
9
9
|
* fs/promises, never PROJECTS_DIR. See historyDashboard.test.cjs's zero-scan
|
|
10
10
|
* guarantee test.
|
|
11
|
+
*
|
|
12
|
+
* The one non-rollup input is the Task ledger (lib/tasks/taskLedger.cjs
|
|
13
|
+
* readTaskUsageDays, for every project in lib/tasks/taskSwitch.cjs
|
|
14
|
+
* listTaskProjects, switch on or off). It is still no transcript scan and no
|
|
15
|
+
* PROJECTS_DIR: each project's own session-manager-operations/tasks/ day files.
|
|
16
|
+
* Its spend lands as rows keyed 'sm-task:<absolute cwd>' so the renderer fold
|
|
17
|
+
* puts it on that project's row. Nothing counts twice: Tasks run with
|
|
18
|
+
* --no-session-persistence and write no transcript, and historyAggregator.cjs
|
|
19
|
+
* skips the transcript of any Task that did persist (sibling PRD
|
|
20
|
+
* task-history-skip-task-transcripts), so no rollup line carries Task usage.
|
|
11
21
|
*/
|
|
12
22
|
|
|
13
23
|
'use strict';
|
|
14
24
|
|
|
15
25
|
const { ipcMain } = require('electron');
|
|
16
26
|
const historyRollup = require('./lib/historyRollup.cjs');
|
|
17
|
-
const {
|
|
18
|
-
|
|
19
|
-
resolvePricingKey,
|
|
20
|
-
localDate,
|
|
21
|
-
subtractDays,
|
|
22
|
-
} = require('./historyAggregator.cjs');
|
|
27
|
+
const { localDate, subtractDays } = require('./historyAggregator.cjs');
|
|
28
|
+
const { costOfUsage } = require('./lib/claude/modelPricing.cjs');
|
|
23
29
|
const { schemas } = require('./ipcSchemas.cjs');
|
|
24
30
|
|
|
25
31
|
// Read range start for rangeDays=0 ("all time"). Rollup dates are always
|
|
26
32
|
// after this, so it's an effective "no lower bound".
|
|
27
33
|
const EARLIEST_DATE = '1970-01-01';
|
|
28
34
|
|
|
35
|
+
/** Prefix of a Task project's row key in days[].byProject: 'sm-task:' + absolute cwd. */
|
|
36
|
+
const TASK_PROJECT_PREFIX = 'sm-task:';
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Default Task readers, required lazily so a dashboard that never reaches
|
|
40
|
+
* them (and the zero-scan test's module graph) stays as it was.
|
|
41
|
+
*/
|
|
42
|
+
function defaultTaskDeps() {
|
|
43
|
+
return {
|
|
44
|
+
listTaskProjects: () => require('./lib/tasks/taskSwitch.cjs').listTaskProjects(),
|
|
45
|
+
readTaskUsageDays: (cwd, range) => require('./lib/tasks/taskLedger.cjs').readTaskUsageDays(cwd, range),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Task ledger days → buckets shaped like rollup lines: per day, one totals
|
|
51
|
+
* bucket (promptCount = sessionCount = task count) and one bucket per model,
|
|
52
|
+
* so they go through the same fold + cost path as transcript rows.
|
|
53
|
+
*/
|
|
54
|
+
async function readTaskBuckets(from, to, deps) {
|
|
55
|
+
const listTaskProjects = deps.listTaskProjects ?? defaultTaskDeps().listTaskProjects;
|
|
56
|
+
const readTaskUsageDays = deps.readTaskUsageDays ?? defaultTaskDeps().readTaskUsageDays;
|
|
57
|
+
const buckets = [];
|
|
58
|
+
for (const { cwd } of listTaskProjects() || []) {
|
|
59
|
+
if (typeof cwd !== 'string' || !cwd) continue;
|
|
60
|
+
let days;
|
|
61
|
+
try {
|
|
62
|
+
days = await readTaskUsageDays(cwd, { sinceDate: from, untilDate: to });
|
|
63
|
+
} catch (err) {
|
|
64
|
+
console.warn(`[historyDashboard] Task ledger read failed for ${cwd}:`, err);
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
const projectDir = TASK_PROJECT_PREFIX + cwd;
|
|
68
|
+
for (const d of days || []) {
|
|
69
|
+
buckets.push({
|
|
70
|
+
date: d.date, projectDir, modelId: historyRollup.TOTALS_MODEL_ID,
|
|
71
|
+
promptCount: d.tasks || 0, sessionCount: d.tasks || 0,
|
|
72
|
+
});
|
|
73
|
+
for (const [modelId, m] of Object.entries(d.byModel || {})) {
|
|
74
|
+
buckets.push({
|
|
75
|
+
date: d.date, projectDir, modelId,
|
|
76
|
+
inputTokens: m.input_tokens || 0,
|
|
77
|
+
outputTokens: m.output_tokens || 0,
|
|
78
|
+
cacheReadTokens: m.cache_read_input_tokens || 0,
|
|
79
|
+
cacheCreationTokens: m.cache_creation_input_tokens || 0,
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return buckets;
|
|
85
|
+
}
|
|
86
|
+
|
|
29
87
|
function emptyProjectRow(date, projectDir) {
|
|
30
88
|
return {
|
|
31
89
|
date,
|
|
@@ -58,11 +116,21 @@ function foldBucketIntoRow(row, bucket) {
|
|
|
58
116
|
} else {
|
|
59
117
|
const dst = row.byModel[bucket.modelId] ?? (row.byModel[bucket.modelId] = {
|
|
60
118
|
inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheCreationTokens: 0,
|
|
119
|
+
cacheCreation1hTokens: 0, cacheCreationUnknownTokens: 0,
|
|
61
120
|
});
|
|
62
121
|
dst.inputTokens += bucket.inputTokens || 0;
|
|
63
122
|
dst.outputTokens += bucket.outputTokens || 0;
|
|
64
123
|
dst.cacheReadTokens += bucket.cacheReadTokens || 0;
|
|
65
124
|
dst.cacheCreationTokens += bucket.cacheCreationTokens || 0;
|
|
125
|
+
// A line written before rollup v4 has no 1-hour split: its cache writes
|
|
126
|
+
// count as unknown, which costOfUsage prices at the 1-hour rate and marks
|
|
127
|
+
// estimated. Both parts are plain sums, so a bucket mixing old and new
|
|
128
|
+
// lines (e.g. the previous-period row) stays right.
|
|
129
|
+
if (typeof bucket.cacheCreation1hTokens === 'number') {
|
|
130
|
+
dst.cacheCreation1hTokens += bucket.cacheCreation1hTokens;
|
|
131
|
+
} else {
|
|
132
|
+
dst.cacheCreationUnknownTokens += bucket.cacheCreationTokens || 0;
|
|
133
|
+
}
|
|
66
134
|
row.inputTokens += bucket.inputTokens || 0;
|
|
67
135
|
row.outputTokens += bucket.outputTokens || 0;
|
|
68
136
|
row.cacheReadTokens += bucket.cacheReadTokens || 0;
|
|
@@ -75,12 +143,7 @@ function computeRowCost(row) {
|
|
|
75
143
|
const byModel = {};
|
|
76
144
|
let estimatedCostUsd = 0;
|
|
77
145
|
for (const [modelId, bucket] of Object.entries(row.byModel)) {
|
|
78
|
-
const {
|
|
79
|
-
const pricing = MODEL_PRICING[key];
|
|
80
|
-
const costUsd =
|
|
81
|
-
(bucket.inputTokens + bucket.cacheCreationTokens) * pricing.i / 1e6 +
|
|
82
|
-
bucket.outputTokens * pricing.o / 1e6 +
|
|
83
|
-
bucket.cacheReadTokens * pricing.c / 1e6;
|
|
146
|
+
const { costUsd, estimated } = costOfUsage(modelId, bucket);
|
|
84
147
|
byModel[modelId] = { ...bucket, costUsd, ...(estimated ? { estimated: true } : {}) };
|
|
85
148
|
estimatedCostUsd += costUsd;
|
|
86
149
|
}
|
|
@@ -116,10 +179,11 @@ function addRowToTotals(totals, row) {
|
|
|
116
179
|
}
|
|
117
180
|
|
|
118
181
|
/**
|
|
119
|
-
* Answer the History dashboard's full request
|
|
120
|
-
* O(rollup lines in range) — no transcript file is
|
|
182
|
+
* Answer the History dashboard's full request from rollup lines plus the Task
|
|
183
|
+
* ledger. O(rollup lines + Task ledger lines in range) — no transcript file is
|
|
184
|
+
* ever opened. `deps` ({ listTaskProjects, readTaskUsageDays }) is for tests.
|
|
121
185
|
*/
|
|
122
|
-
async function computeDashboard(req) {
|
|
186
|
+
async function computeDashboard(req, deps = {}) {
|
|
123
187
|
const rangeDays = req?.rangeDays ?? 30;
|
|
124
188
|
const isAll = rangeDays === 0;
|
|
125
189
|
const today = localDate(new Date());
|
|
@@ -130,12 +194,13 @@ async function computeDashboard(req) {
|
|
|
130
194
|
const readFrom = isAll ? EARLIEST_DATE : prevFrom;
|
|
131
195
|
|
|
132
196
|
const map = await historyRollup.readRollup(readFrom, to);
|
|
197
|
+
const taskBuckets = await readTaskBuckets(readFrom, to, deps);
|
|
133
198
|
|
|
134
199
|
const daysMap = new Map(); // date -> Map(projectDir -> row)
|
|
135
200
|
const prevRow = emptyProjectRow('', '');
|
|
136
201
|
const finalizedDates = new Set();
|
|
137
202
|
|
|
138
|
-
for (const bucket of map.values()) {
|
|
203
|
+
for (const bucket of [...map.values(), ...taskBuckets]) {
|
|
139
204
|
if (bucket.projectDir === historyRollup.FINALIZED_PROJECT_ID && bucket.modelId === historyRollup.FINALIZED_MODEL_ID) {
|
|
140
205
|
if (bucket.finalizedAt) finalizedDates.add(bucket.date);
|
|
141
206
|
continue;
|
|
@@ -197,6 +262,9 @@ async function computeDashboard(req) {
|
|
|
197
262
|
addRowToTotals(prevTotals, computeRowCost(prevRow));
|
|
198
263
|
|
|
199
264
|
const provisionalDates = sortedDates.filter((d) => !finalizedDates.has(d));
|
|
265
|
+
// Days finalized under an older ROLLUP_VERSION that the finalize pass could
|
|
266
|
+
// not recount (transcripts gone) — their rows are still served as-is.
|
|
267
|
+
const legacyDates = historyRollup.legacyFinalizedDates(map).filter((d) => d >= from && d <= to);
|
|
200
268
|
|
|
201
269
|
return {
|
|
202
270
|
from,
|
|
@@ -209,6 +277,7 @@ async function computeDashboard(req) {
|
|
|
209
277
|
toolsByProject,
|
|
210
278
|
generatedAt: Date.now(),
|
|
211
279
|
provisionalDates,
|
|
280
|
+
legacyDates,
|
|
212
281
|
};
|
|
213
282
|
}
|
|
214
283
|
|
|
@@ -223,4 +292,5 @@ function registerHistoryDashboardHandlers() {
|
|
|
223
292
|
module.exports = {
|
|
224
293
|
registerHistoryDashboardHandlers,
|
|
225
294
|
computeDashboard,
|
|
295
|
+
TASK_PROJECT_PREFIX,
|
|
226
296
|
};
|