gentle-pi 3.6.0 → 4.0.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/README.md +37 -6
- package/assets/agents/gentle-ai-explore.md +4 -4
- package/assets/agents/gentle-ai-verify.md +6 -4
- package/assets/agents/gentle-ai-worker.md +7 -9
- package/assets/orchestrator-delegation.md +40 -41
- package/assets/orchestrator-memory.md +1 -22
- package/assets/orchestrator-skills.md +1 -1
- package/assets/orchestrator.md +12 -24
- package/assets/support/strict-tdd-verify.md +4 -266
- package/assets/support/strict-tdd.md +8 -360
- package/bin/gentle-shell.mjs +254 -29
- package/docs/delegated-verification.md +26 -1
- package/docs/gentle-agents-activity.md +24 -0
- package/docs/gentle-shell.md +95 -30
- package/docs/native-authority-architecture.md +2 -2
- package/docs/prompt-history.md +280 -0
- package/docs/readme-reference.md +117 -235
- package/docs/telemetry.md +1 -1
- package/docs/yolo-mode.md +86 -0
- package/extensions/child-context.ts +26 -0
- package/extensions/child-safety.ts +23 -0
- package/extensions/gentle-agents.ts +509 -275
- package/extensions/gentle-ai.ts +781 -683
- package/extensions/gentle-shell.ts +1375 -88
- package/extensions/gentle-stats.ts +101 -0
- package/extensions/gentle-todo.ts +18 -7
- package/extensions/history/atomic-write.ts +38 -0
- package/extensions/history/hide-prompts.ts +183 -0
- package/extensions/history/index.ts +1419 -0
- package/extensions/history/load-shared-history.ts +39 -0
- package/extensions/history/selector-helpers.ts +538 -0
- package/extensions/history/session-scan.ts +233 -0
- package/extensions/history/store.ts +1119 -0
- package/extensions/nan-provider.ts +6 -0
- package/extensions/quiet-tools.ts +179 -87
- package/extensions/resume-hint.ts +60 -0
- package/extensions/skill-registry.ts +16 -12
- package/extensions/startup-banner.ts +60 -31
- package/lib/agent-assets.ts +604 -0
- package/lib/agent-profile-pin.ts +12 -0
- package/lib/agents-message-delivery.ts +181 -0
- package/lib/agents-protocol.ts +60 -0
- package/lib/agents-runner.ts +105 -98
- package/lib/agents-view.ts +26 -3
- package/lib/agents-widget.ts +16 -9
- package/lib/append-system-prompt.ts +21 -0
- package/lib/bounded-writer-admission.ts +147 -0
- package/lib/card-style-policy.ts +60 -0
- package/lib/child-context-files.ts +166 -0
- package/lib/codemode-renderer.ts +185 -0
- package/lib/command-palette-catalog.ts +3 -9
- package/lib/command-palette.ts +25 -14
- package/lib/destructive-command-guard.ts +144 -0
- package/lib/foreign-target-grants.ts +32 -0
- package/lib/gentle-ai-elapsed-store.ts +87 -0
- package/lib/gentle-ai-renderer.ts +196 -39
- package/lib/gentle-shell-launcher.ts +24 -13
- package/lib/gentle-shell-resume-hint.ts +176 -0
- package/lib/history-capture-policy.ts +95 -0
- package/lib/model-routing-authority.ts +5 -1
- package/lib/nan-provider.ts +227 -0
- package/lib/native-review-cli.ts +53 -108
- package/lib/odd-phase-inference.ts +231 -0
- package/lib/odd-phase.ts +141 -0
- package/lib/overlay-repaint.ts +26 -0
- package/lib/pi-tui-keys.ts +53 -0
- package/lib/review-candidate-view-owner.ts +67 -17
- package/lib/review-candidate-view.ts +112 -25
- package/lib/review-reminder-receipt.ts +48 -8
- package/lib/review-risk-assessment.ts +156 -11
- package/lib/review-sidebar-state.ts +223 -0
- package/lib/selection-engine.ts +515 -0
- package/lib/session-change-capture.ts +10 -1
- package/lib/session-messaging-grants.ts +135 -0
- package/lib/session-worktree-registry.ts +14 -2
- package/lib/shell-bar.ts +179 -24
- package/lib/shell-card.ts +287 -18
- package/lib/shell-changes-view.ts +2 -1
- package/lib/shell-prompt.ts +102 -6
- package/lib/shell-sidebar-layout.ts +78 -14
- package/lib/shell-sidebar.ts +15 -1
- package/lib/shell-todo.ts +23 -13
- package/lib/shell-usage-view.ts +9 -4
- package/lib/shell-usage.ts +66 -10
- package/lib/stats-collector.ts +381 -0
- package/lib/stats-view.ts +431 -0
- package/lib/theme-customization.ts +52 -0
- package/lib/vim-editor-adapter.ts +379 -0
- package/lib/vim-normal-engine.ts +154 -0
- package/lib/vim-operator-engine.ts +416 -0
- package/lib/vim-policy.ts +49 -0
- package/lib/vim-visual-engine.ts +107 -0
- package/lib/visual-customization-policy.ts +108 -0
- package/lib/visual-customize-view.ts +330 -0
- package/lib/visual-profiles.ts +228 -0
- package/lib/yolo-session-policy.ts +240 -0
- package/package.json +20 -8
- package/runtime/gentle-shell-launcher.mjs +23 -12
- package/runtime/gentle-shell-resume-hint.mjs +177 -0
- package/runtime/native-review-cli.mjs +53 -108
- package/runtime/review-risk-assessment.mjs +154 -9
- package/scripts/build-runtime-modules.mjs +1 -0
- package/scripts/gentle-ai-installer.mjs +14 -13
- package/scripts/mirror-odd-routing.mjs +2 -2
- package/scripts/run-test-suite.mjs +76 -0
- package/scripts/test-packed-runner.mjs +31 -14
- package/scripts/verify-package-files.mjs +11 -22
- package/skills/branch-pr/SKILL.md +24 -52
- package/skills/chained-pr/SKILL.md +31 -15
- package/skills/chained-pr/references/chaining-details.md +31 -20
- package/skills/gentle-ai/SKILL.md +9 -15
- package/skills/issue-creation/SKILL.md +8 -2
- package/skills/issue-creation/references/delegated-workflow-actions.md +19 -0
- package/skills/work-unit-commits/SKILL.md +4 -3
- package/tests/agent-profiles.test.ts +18 -0
- package/tests/agents-fake-child.ts +2 -2
- package/tests/agents-message-delivery.test.ts +106 -0
- package/tests/agents-protocol.test.ts +40 -0
- package/tests/agents-runner.test.ts +400 -89
- package/tests/agents-view-thread-identity.test.ts +169 -0
- package/tests/agents-view.test.ts +8 -2
- package/tests/agents-widget.test.ts +154 -15
- package/tests/append-system-prompt-route.test.ts +160 -0
- package/tests/append-system-prompt.test.ts +46 -0
- package/tests/artifact-language.test.ts +19 -213
- package/tests/ask-user-question.test.ts +44 -1
- package/tests/asset-installation-runtime.test.ts +5 -16
- package/tests/autonomous-guard.test.ts +69 -1
- package/tests/bounded-writer-admission.test.ts +95 -0
- package/tests/branch-pr-skill.test.ts +43 -0
- package/tests/card-style-policy.test.ts +55 -0
- package/tests/chained-pr-skill.test.ts +124 -0
- package/tests/child-context-files.test.ts +255 -0
- package/tests/child-safety.test.ts +82 -0
- package/tests/codemode-rendering.test.ts +491 -0
- package/tests/command-palette.test.ts +39 -3
- package/tests/delegated-key-learnings-contract.test.ts +0 -76
- package/tests/destructive-command-guard.test.ts +84 -0
- package/tests/devbinary/native-review-parity.devtest.ts +170 -2
- package/tests/devbinary/non-git-subagent-bootstrap.devtest.ts +193 -0
- package/tests/fixtures/stats/sessions/--work-alpha--/2026-09-28T10-00-00-000Z_aaa.jsonl +7 -0
- package/tests/fixtures/stats/sessions/--work-alpha--/2026-09-29T23-00-00-000Z_bbb.jsonl +3 -0
- package/tests/fixtures/stats/sessions/--work-alpha--/2026-09-30T08-00-00-000Z_ddd.jsonl +2 -0
- package/tests/fixtures/stats/sessions/--work-alpha--/2026-09-30T09-00-00-000Z_eee.jsonl +3 -0
- package/tests/fixtures/stats/sessions/--work-alpha--/run-1/session.jsonl +2 -0
- package/tests/fixtures/stats/sessions/--work-beta--/2026-09-01T12-00-00-000Z_ccc.jsonl +2 -0
- package/tests/fixtures/stats/user-pi/sessions/--work-alpha--/2026-09-28T10-00-00-000Z_aaa.jsonl +2 -0
- package/tests/fixtures/stats/user-pi/sessions/--work-alpha--/2026-09-29T23-00-00-000Z_bbb.jsonl +4 -0
- package/tests/fixtures/stats/user-pi/sessions/--work-gamma--/2026-09-20T09-00-00-000Z_fff.jsonl +3 -0
- package/tests/foreign-target-grants.test.ts +58 -0
- package/tests/generic-agent-tools.test.ts +54 -0
- package/tests/gentle-agents.test.ts +1411 -256
- package/tests/gentle-ai-binary.test.ts +3 -3
- package/tests/gentle-ai-elapsed-store.test.ts +68 -0
- package/tests/gentle-ai-installer.test.ts +68 -54
- package/tests/gentle-ai-renderer.test.ts +487 -8
- package/tests/gentle-ai.test.ts +288 -65
- package/tests/gentle-card-text.ts +2 -1
- package/tests/gentle-shell-bin.test.ts +651 -114
- package/tests/gentle-shell-launcher.test.ts +99 -52
- package/tests/gentle-shell-resume-hint.test.ts +270 -0
- package/tests/gentle-shell.test.ts +3839 -187
- package/tests/gentle-stats.test.ts +152 -0
- package/tests/gentle-theme.test.ts +4 -1
- package/tests/gentle-todo.test.ts +80 -8
- package/tests/history-atomic-write.test.ts +57 -0
- package/tests/history-capture-policy.test.ts +102 -0
- package/tests/history-command-registration.test.ts +164 -0
- package/tests/history-dedupe-entries.test.ts +123 -0
- package/tests/history-delete-backfill.test.ts +190 -0
- package/tests/history-delete-confirm.test.ts +460 -0
- package/tests/history-dispatch.test.ts +180 -0
- package/tests/history-drain-hidden.test.ts +110 -0
- package/tests/history-drain-order.test.ts +98 -0
- package/tests/history-expanded-globals.test.ts +62 -0
- package/tests/history-gc.test.ts +832 -0
- package/tests/history-header-layout.test.ts +265 -0
- package/tests/history-hide-prompts.test.ts +275 -0
- package/tests/history-lazy-windowing.test.ts +508 -0
- package/tests/history-legacy-migrate-v2.test.ts +297 -0
- package/tests/history-load-shared-history.test.ts +53 -0
- package/tests/history-max-results-cap.test.ts +76 -0
- package/tests/history-multi-reader.test.ts +203 -0
- package/tests/history-off-path.test.ts +170 -0
- package/tests/history-openflow-integration.test.ts +173 -0
- package/tests/history-overlay-margin.test.ts +326 -0
- package/tests/history-preview-layout.test.ts +93 -0
- package/tests/history-registry.test.ts +143 -0
- package/tests/history-scope-delete.test.ts +411 -0
- package/tests/history-search-caret-keys.test.ts +142 -0
- package/tests/history-seed-bootstrap.test.ts +170 -0
- package/tests/history-seed-regen.test.ts +129 -0
- package/tests/history-selector-windowing.test.ts +94 -0
- package/tests/history-session-scan-directory.test.ts +87 -0
- package/tests/history-session-scan-extract.test.ts +583 -0
- package/tests/history-session-writer.test.ts +351 -0
- package/tests/history-store-paths.test.ts +79 -0
- package/tests/history-tombstone-exact.test.ts +139 -0
- package/tests/history-wheel-mouse.test.ts +242 -0
- package/tests/inprocess-reviewer.test.ts +29 -19
- package/tests/issue-creation-skill.test.ts +61 -0
- package/tests/model-routing-authority.test.ts +16 -0
- package/tests/nan-provider.test.ts +471 -0
- package/tests/native-review-capability-contract.test.ts +13 -1
- package/tests/native-review-cli.test.ts +6 -120
- package/tests/native-review-parity-runtime.test.ts +100 -3
- package/tests/odd-integration.test.ts +67 -0
- package/tests/odd-phase-inference.test.ts +213 -0
- package/tests/odd-phase-loader.test.ts +253 -0
- package/tests/odd-phase.test.ts +307 -0
- package/tests/odd-routing-canonical-ratchet.test.ts +11 -6
- package/tests/odd-routing-contract.test.ts +86 -35
- package/tests/orchestrator-budget.test.ts +14 -39
- package/tests/orchestrator-rdd-ownership.test.ts +3 -3
- package/tests/overlay-repaint.test.ts +74 -0
- package/tests/package-manifest.test.ts +252 -115
- package/tests/packed-runner-owned-path.test.ts +46 -0
- package/tests/persona-single-channel.test.ts +6 -6
- package/tests/provider-defect-handoff.test.ts +3 -11
- package/tests/quiet-bash-runtime.test.ts +76 -0
- package/tests/quiet-tool-rendering.test.ts +409 -184
- package/tests/rdd-aware-verification-contract.test.ts +76 -1
- package/tests/rdd-status-line.test.ts +9 -4
- package/tests/resume-hint-extension.test.ts +122 -0
- package/tests/review-agent-end-preflight.test.ts +176 -12
- package/tests/review-candidate-owner-retry.test.ts +22 -1
- package/tests/review-candidate-view.test.ts +298 -0
- package/tests/review-contract-prompt.test.ts +108 -43
- package/tests/review-controller-lock-status.test.ts +0 -1
- package/tests/review-controller-native-routing.test.ts +611 -5
- package/tests/review-controller-workspace-root.test.ts +163 -4
- package/tests/review-host-relay-routing.test.ts +338 -2
- package/tests/review-integration-v2-forward.test.ts +200 -0
- package/tests/review-ledger-contract.test.ts +10 -34
- package/tests/review-reminder-receipt.test.ts +47 -1
- package/tests/review-risk-assessment.test.ts +498 -6
- package/tests/review-sidebar-state.test.ts +402 -0
- package/tests/run-test-suite.test.ts +124 -0
- package/tests/runtime-harness.mjs +145 -786
- package/tests/runtime-metrics-children.test.ts +16 -23
- package/tests/selection-engine.test.ts +421 -0
- package/tests/session-change-capture.test.ts +12 -1
- package/tests/session-messaging-grants.test.ts +255 -0
- package/tests/session-worktree-registry.test.ts +77 -0
- package/tests/shell-bar.test.ts +382 -1
- package/tests/shell-card.test.ts +353 -1
- package/tests/shell-changes-view.test.ts +52 -0
- package/tests/shell-prompt.test.ts +94 -2
- package/tests/shell-sidebar-layout.test.ts +325 -21
- package/tests/shell-sidebar-scroll-benchmark.test.ts +255 -0
- package/tests/shell-todo.test.ts +87 -1
- package/tests/shell-usage-view.test.ts +27 -0
- package/tests/shell-usage.test.ts +73 -0
- package/tests/skill-registry.test.ts +50 -1
- package/tests/startup-banner.test.ts +130 -2
- package/tests/stats-collector.test.ts +195 -0
- package/tests/stats-view.test.ts +202 -0
- package/tests/telemetry-trigger.test.ts +81 -20
- package/tests/theme-customization.test.ts +72 -0
- package/tests/vim-editor-adapter-host-resolution.test.ts +37 -0
- package/tests/vim-editor-adapter.test.ts +804 -0
- package/tests/vim-normal-engine.test.ts +101 -0
- package/tests/vim-operator-engine.test.ts +215 -0
- package/tests/vim-policy.test.ts +19 -0
- package/tests/vim-visual-engine.test.ts +52 -0
- package/tests/visual-customization-policy.test.ts +110 -0
- package/tests/visual-customize-view.test.ts +418 -0
- package/tests/visual-profiles.test.ts +87 -0
- package/tests/yolo-customize.test.ts +256 -0
- package/tests/yolo-mode-runtime.test.ts +161 -0
- package/tests/yolo-mode.test.ts +261 -0
- package/tests/yolo-session-policy.test.ts +59 -0
- package/themes/Gentle.json +2 -1
- package/themes/Gentleman-Cute.json +2 -1
- package/themes/Gentleman-Sexy.json +2 -1
- package/assets/agents/sdd-apply.md +0 -159
- package/assets/agents/sdd-archive.md +0 -228
- package/assets/agents/sdd-design.md +0 -49
- package/assets/agents/sdd-explore.md +0 -48
- package/assets/agents/sdd-init.md +0 -56
- package/assets/agents/sdd-onboard.md +0 -52
- package/assets/agents/sdd-proposal.md +0 -64
- package/assets/agents/sdd-remediate.md +0 -37
- package/assets/agents/sdd-research.md +0 -49
- package/assets/agents/sdd-spec.md +0 -192
- package/assets/agents/sdd-status.md +0 -54
- package/assets/agents/sdd-tasks.md +0 -108
- package/assets/agents/sdd-verify.md +0 -124
- package/assets/chains/sdd-full.chain.md +0 -83
- package/assets/chains/sdd-plan.chain.md +0 -56
- package/assets/chains/sdd-verify.chain.md +0 -43
- package/assets/sdd-orchestrator-workflow.md +0 -319
- package/assets/support/sdd-status-contract.md +0 -77
- package/docs/assets/diagrams/sdd-cycle.svg +0 -14
- package/extensions/sdd-init.ts +0 -816
- package/lib/openspec-deltas.ts +0 -156
- package/lib/sdd-preflight.ts +0 -1066
- package/lib/sdd-research-capabilities.ts +0 -94
- package/lib/sdd-status.ts +0 -26
- package/tests/fixtures/legacy/sdd-research-v2.5.0.md +0 -54
- package/tests/fixtures/native-review-cli/v2.1.3/bind-sdd.json +0 -25
- package/tests/fixtures/v0.10.7/assets/agents/sdd-apply.md +0 -132
- package/tests/openspec-deltas.test.ts +0 -209
- package/tests/sdd-agent-tools.test.ts +0 -156
- package/tests/sdd-archive-replay.test.ts +0 -82
- package/tests/sdd-classical-continuation.test.ts +0 -74
- package/tests/sdd-execution-routing-contract.test.ts +0 -44
- package/tests/sdd-managed-runtime-settlement.test.ts +0 -155
- package/tests/sdd-native-managed-uptake.test.ts +0 -243
- package/tests/sdd-no-attempts-contract.test.ts +0 -15
- package/tests/sdd-odd-integration.test.ts +0 -33
- package/tests/sdd-optional-research.test.ts +0 -124
- package/tests/sdd-planning-routing-contract.test.ts +0 -45
- package/tests/sdd-preflight-rpc-input.test.ts +0 -125
- package/tests/sdd-preflight.test.ts +0 -541
- package/tests/sdd-research-capabilities.test.ts +0 -114
- package/tests/sdd-research-live.test.ts +0 -241
- package/tests/sdd-selection-transport.test.ts +0 -653
- package/tests/sdd-status.test.ts +0 -9
- package/tests/sdd-task-truth.test.ts +0 -43
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
import { createReadStream, realpathSync } from "node:fs";
|
|
2
|
+
import { stat } from "node:fs/promises";
|
|
3
|
+
import { createInterface } from "node:readline";
|
|
4
|
+
import { listSessionFiles } from "../extensions/history/session-scan.ts";
|
|
5
|
+
import { SessionChanges } from "./session-changes.ts";
|
|
6
|
+
|
|
7
|
+
// /gentle:stats data: a read-only, failure-tolerant scan of Pi's top-level
|
|
8
|
+
// session files (nested subagent runs are excluded by listSessionFiles) across
|
|
9
|
+
// one or more homes, and pure aggregation over the parsed records. Nothing
|
|
10
|
+
// here persists anything.
|
|
11
|
+
// Day keys are local calendar dates ("YYYY-MM-DD"); key arithmetic runs in
|
|
12
|
+
// UTC so it never drifts across DST changes.
|
|
13
|
+
|
|
14
|
+
export const STATS_RANGE = {
|
|
15
|
+
ALL: "all",
|
|
16
|
+
WEEK: "7d",
|
|
17
|
+
MONTH: "30d",
|
|
18
|
+
} as const;
|
|
19
|
+
export type StatsRange = (typeof STATS_RANGE)[keyof typeof STATS_RANGE];
|
|
20
|
+
|
|
21
|
+
export const STATS_SCOPE = {
|
|
22
|
+
ALL: "all",
|
|
23
|
+
PROJECT: "project",
|
|
24
|
+
} as const;
|
|
25
|
+
export type StatsScope = (typeof STATS_SCOPE)[keyof typeof STATS_SCOPE];
|
|
26
|
+
|
|
27
|
+
const RANGE_DAYS: Record<StatsRange, number | undefined> = {
|
|
28
|
+
[STATS_RANGE.ALL]: undefined,
|
|
29
|
+
[STATS_RANGE.WEEK]: 7,
|
|
30
|
+
[STATS_RANGE.MONTH]: 30,
|
|
31
|
+
};
|
|
32
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
33
|
+
const COST_PRECISION = 1e9;
|
|
34
|
+
const UNKNOWN = "unknown";
|
|
35
|
+
|
|
36
|
+
export interface UsageRecord {
|
|
37
|
+
timestamp: number;
|
|
38
|
+
provider: string;
|
|
39
|
+
model: string;
|
|
40
|
+
input: number;
|
|
41
|
+
output: number;
|
|
42
|
+
cacheRead: number;
|
|
43
|
+
cacheWrite: number;
|
|
44
|
+
total: number;
|
|
45
|
+
cost: number;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface SessionRecord {
|
|
49
|
+
id: string;
|
|
50
|
+
cwd: string;
|
|
51
|
+
startedAt: number;
|
|
52
|
+
messages: UsageRecord[];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface TokenTotals {
|
|
56
|
+
input: number;
|
|
57
|
+
output: number;
|
|
58
|
+
cacheRead: number;
|
|
59
|
+
cacheWrite: number;
|
|
60
|
+
total: number;
|
|
61
|
+
cost: number;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface ModelStats {
|
|
65
|
+
model: string;
|
|
66
|
+
tokens: number;
|
|
67
|
+
cost: number;
|
|
68
|
+
messages: number;
|
|
69
|
+
share: number;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface StatsFilter {
|
|
73
|
+
range: StatsRange;
|
|
74
|
+
scope: StatsScope;
|
|
75
|
+
cwd?: string;
|
|
76
|
+
now: number;
|
|
77
|
+
dayKey?: (ms: number) => string;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface StatsSummary {
|
|
81
|
+
totals: TokenTotals;
|
|
82
|
+
models: ModelStats[];
|
|
83
|
+
days: Record<string, number>;
|
|
84
|
+
sessions: number;
|
|
85
|
+
activeDays: number;
|
|
86
|
+
daysInRange: number;
|
|
87
|
+
firstDay: string;
|
|
88
|
+
today: string;
|
|
89
|
+
mostActiveDay?: { day: string; tokens: number };
|
|
90
|
+
longestSession?: { id: string; durationMs: number };
|
|
91
|
+
longestStreak: number;
|
|
92
|
+
currentStreak: number;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface CurrentSessionStats {
|
|
96
|
+
totals: TokenTotals;
|
|
97
|
+
messages: number;
|
|
98
|
+
model?: string;
|
|
99
|
+
durationMs: number;
|
|
100
|
+
lines?: { added: number; removed: number };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function localDayKey(ms: number): string {
|
|
104
|
+
const date = new Date(ms);
|
|
105
|
+
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function dayUtc(key: string): number {
|
|
109
|
+
const [year, month, day] = key.split("-").map(Number);
|
|
110
|
+
return Date.UTC(year, month - 1, day);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function shiftDay(key: string, delta: number): string {
|
|
114
|
+
return new Date(dayUtc(key) + delta * DAY_MS).toISOString().slice(0, 10);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** 0 = Sunday … 6 = Saturday. */
|
|
118
|
+
export function weekdayOf(key: string): number {
|
|
119
|
+
return new Date(dayUtc(key)).getUTCDay();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function daysBetween(from: string, to: string): number {
|
|
123
|
+
return Math.round((dayUtc(to) - dayUtc(from)) / DAY_MS);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const emptyTotals = (): TokenTotals => ({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, cost: 0 });
|
|
127
|
+
const count = (value: unknown): number => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0);
|
|
128
|
+
const roundCost = (value: number): number => Math.round(value * COST_PRECISION) / COST_PRECISION;
|
|
129
|
+
const text = (value: unknown, fallback: string): string => (typeof value === "string" && value.length > 0 ? value : fallback);
|
|
130
|
+
|
|
131
|
+
function addUsage(totals: TokenTotals, record: UsageRecord): void {
|
|
132
|
+
totals.input += record.input;
|
|
133
|
+
totals.output += record.output;
|
|
134
|
+
totals.cacheRead += record.cacheRead;
|
|
135
|
+
totals.cacheWrite += record.cacheWrite;
|
|
136
|
+
totals.total += record.total;
|
|
137
|
+
totals.cost += record.cost;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
type RawEntry = { type?: unknown; timestamp?: unknown; message?: { role?: unknown; provider?: unknown; model?: unknown; usage?: unknown } };
|
|
141
|
+
|
|
142
|
+
/** One assistant usage record from a parsed entry, or undefined for anything else. */
|
|
143
|
+
export function usageRecord(entry: unknown): UsageRecord | undefined {
|
|
144
|
+
const raw = entry as RawEntry | null;
|
|
145
|
+
if (!raw || typeof raw !== "object" || raw.type !== "message" || raw.message?.role !== "assistant") return undefined;
|
|
146
|
+
const usage = raw.message.usage as Record<string, unknown> | undefined;
|
|
147
|
+
if (!usage || typeof usage !== "object") return undefined;
|
|
148
|
+
const timestamp = typeof raw.timestamp === "string" ? Date.parse(raw.timestamp) : NaN;
|
|
149
|
+
if (!Number.isFinite(timestamp)) return undefined;
|
|
150
|
+
const input = count(usage.input);
|
|
151
|
+
const output = count(usage.output);
|
|
152
|
+
const cacheRead = count(usage.cacheRead);
|
|
153
|
+
const cacheWrite = count(usage.cacheWrite);
|
|
154
|
+
const total = typeof usage.totalTokens === "number" && Number.isFinite(usage.totalTokens) && usage.totalTokens >= 0 ? usage.totalTokens : input + output + cacheRead + cacheWrite;
|
|
155
|
+
const cost = count((usage.cost as { total?: unknown } | undefined)?.total);
|
|
156
|
+
return { timestamp, provider: text(raw.message.provider, UNKNOWN), model: text(raw.message.model, UNKNOWN), input, output, cacheRead, cacheWrite, total, cost };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// Incremental so the loader can stream large files line by line. Only the
|
|
160
|
+
// header and assistant lines are parsed; everything else is skipped by a
|
|
161
|
+
// cheap substring check before JSON.parse.
|
|
162
|
+
class SessionParser {
|
|
163
|
+
private record: SessionRecord | undefined;
|
|
164
|
+
private sawFirst = false;
|
|
165
|
+
|
|
166
|
+
push(line: string): void {
|
|
167
|
+
if (!this.sawFirst) {
|
|
168
|
+
if (line.trim() === "") return;
|
|
169
|
+
this.sawFirst = true;
|
|
170
|
+
const header = parse(line) as { type?: unknown; id?: unknown; timestamp?: unknown; cwd?: unknown } | undefined;
|
|
171
|
+
if (header?.type !== "session") return;
|
|
172
|
+
const startedAt = typeof header.timestamp === "string" ? Date.parse(header.timestamp) : NaN;
|
|
173
|
+
this.record = { id: text(header.id, UNKNOWN), cwd: text(header.cwd, ""), startedAt, messages: [] };
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
if (!this.record || !line.includes("\"assistant\"")) return;
|
|
177
|
+
const usage = usageRecord(parse(line));
|
|
178
|
+
if (usage) this.record.messages.push(usage);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
result(): SessionRecord | undefined {
|
|
182
|
+
const record = this.record;
|
|
183
|
+
if (record && !Number.isFinite(record.startedAt)) record.startedAt = record.messages[0]?.timestamp ?? NaN;
|
|
184
|
+
return record;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function parse(line: string): unknown {
|
|
189
|
+
try {
|
|
190
|
+
return JSON.parse(line);
|
|
191
|
+
} catch {
|
|
192
|
+
return undefined;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export function parseSessionLines(lines: Iterable<string>): SessionRecord | undefined {
|
|
197
|
+
const parser = new SessionParser();
|
|
198
|
+
for (const line of lines) parser.push(line);
|
|
199
|
+
return parser.result();
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
async function readSessionFile(path: string): Promise<SessionRecord | undefined> {
|
|
203
|
+
const parser = new SessionParser();
|
|
204
|
+
const stream = createReadStream(path, { encoding: "utf8" });
|
|
205
|
+
const lines = createInterface({ input: stream, crlfDelay: Infinity });
|
|
206
|
+
try {
|
|
207
|
+
for await (const line of lines) parser.push(line);
|
|
208
|
+
} catch {
|
|
209
|
+
return undefined; // an unreadable file skips itself, never fatal
|
|
210
|
+
} finally {
|
|
211
|
+
lines.close();
|
|
212
|
+
stream.destroy();
|
|
213
|
+
}
|
|
214
|
+
return parser.result();
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export interface StatsLoader {
|
|
218
|
+
load(sessionsRoots: string | readonly string[]): Promise<SessionRecord[]>;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// Roots resolve through realpath so an alias (trailing slash, "..", a
|
|
222
|
+
// symlink) of a root already listed is read once; a missing root is skipped.
|
|
223
|
+
function sessionFiles(sessionsRoots: readonly string[]): string[] {
|
|
224
|
+
const roots = new Set<string>();
|
|
225
|
+
for (const root of sessionsRoots) {
|
|
226
|
+
try {
|
|
227
|
+
roots.add(realpathSync(root));
|
|
228
|
+
} catch {
|
|
229
|
+
// a missing or unreadable root contributes nothing
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
return [...new Set([...roots].flatMap(listSessionFiles))];
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const lastUsageAt = (record: SessionRecord): number => record.messages.reduce((latest, message) => Math.max(latest, message.timestamp), -Infinity);
|
|
236
|
+
|
|
237
|
+
// The same session can exist in two homes (a copied or migrated history).
|
|
238
|
+
// Only one copy counts: the one with more usage records, then the one whose
|
|
239
|
+
// last usage is newest; on a full tie the first file in path order stays.
|
|
240
|
+
function preferredCopy(kept: SessionRecord, other: SessionRecord): SessionRecord {
|
|
241
|
+
if (other.messages.length !== kept.messages.length) return other.messages.length > kept.messages.length ? other : kept;
|
|
242
|
+
return lastUsageAt(other) > lastUsageAt(kept) ? other : kept;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** A loader over one or more sessions roots that re-reads only files whose size or mtime changed since the last load. */
|
|
246
|
+
export function createStatsLoader(): StatsLoader {
|
|
247
|
+
const cache = new Map<string, { size: number; mtimeMs: number; record: SessionRecord | undefined }>();
|
|
248
|
+
return {
|
|
249
|
+
async load(sessionsRoots) {
|
|
250
|
+
const files = sessionFiles(typeof sessionsRoots === "string" ? [sessionsRoots] : sessionsRoots).sort();
|
|
251
|
+
const live = new Set(files);
|
|
252
|
+
for (const path of cache.keys()) if (!live.has(path)) cache.delete(path);
|
|
253
|
+
const byId = new Map<string, SessionRecord>();
|
|
254
|
+
const sessions: SessionRecord[] = [];
|
|
255
|
+
for (const path of files) {
|
|
256
|
+
let info;
|
|
257
|
+
try {
|
|
258
|
+
info = await stat(path);
|
|
259
|
+
} catch {
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
let cached = cache.get(path);
|
|
263
|
+
if (!cached || cached.size !== info.size || cached.mtimeMs !== info.mtimeMs) {
|
|
264
|
+
cached = { size: info.size, mtimeMs: info.mtimeMs, record: await readSessionFile(path) };
|
|
265
|
+
cache.set(path, cached);
|
|
266
|
+
}
|
|
267
|
+
const record = cached.record;
|
|
268
|
+
if (!record) continue;
|
|
269
|
+
// A header without an ID cannot be matched to another copy.
|
|
270
|
+
if (record.id === UNKNOWN) sessions.push(record);
|
|
271
|
+
else byId.set(record.id, byId.has(record.id) ? preferredCopy(byId.get(record.id)!, record) : record);
|
|
272
|
+
}
|
|
273
|
+
return [...byId.values(), ...sessions];
|
|
274
|
+
},
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
export function aggregateStats(sessions: readonly SessionRecord[], filter: StatsFilter): StatsSummary {
|
|
279
|
+
const dayKey = filter.dayKey ?? localDayKey;
|
|
280
|
+
const today = dayKey(filter.now);
|
|
281
|
+
const rangeDays = RANGE_DAYS[filter.range];
|
|
282
|
+
const startDay = rangeDays === undefined ? undefined : shiftDay(today, -(rangeDays - 1));
|
|
283
|
+
const totals = emptyTotals();
|
|
284
|
+
const models = new Map<string, Omit<ModelStats, "share">>();
|
|
285
|
+
const days: Record<string, number> = {};
|
|
286
|
+
let sessionCount = 0;
|
|
287
|
+
let longestSession: StatsSummary["longestSession"];
|
|
288
|
+
for (const session of sessions) {
|
|
289
|
+
if (filter.scope === STATS_SCOPE.PROJECT && session.cwd !== filter.cwd) continue;
|
|
290
|
+
let counted = false;
|
|
291
|
+
let lastAt = -Infinity;
|
|
292
|
+
for (const message of session.messages) {
|
|
293
|
+
const day = dayKey(message.timestamp);
|
|
294
|
+
if (startDay !== undefined && day < startDay) continue;
|
|
295
|
+
counted = true;
|
|
296
|
+
lastAt = Math.max(lastAt, message.timestamp);
|
|
297
|
+
addUsage(totals, message);
|
|
298
|
+
days[day] = (days[day] ?? 0) + message.total;
|
|
299
|
+
const model = models.get(message.model) ?? { model: message.model, tokens: 0, cost: 0, messages: 0 };
|
|
300
|
+
model.tokens += message.total;
|
|
301
|
+
model.cost += message.cost;
|
|
302
|
+
model.messages++;
|
|
303
|
+
models.set(message.model, model);
|
|
304
|
+
}
|
|
305
|
+
if (!counted) continue;
|
|
306
|
+
sessionCount++;
|
|
307
|
+
const durationMs = Number.isFinite(session.startedAt) ? Math.max(0, lastAt - session.startedAt) : 0;
|
|
308
|
+
if (!longestSession || durationMs > longestSession.durationMs) longestSession = { id: session.id, durationMs };
|
|
309
|
+
}
|
|
310
|
+
totals.cost = roundCost(totals.cost);
|
|
311
|
+
const active = Object.keys(days).sort();
|
|
312
|
+
const firstDay = startDay ?? active[0] ?? today;
|
|
313
|
+
let mostActiveDay: StatsSummary["mostActiveDay"];
|
|
314
|
+
for (const day of active) if (!mostActiveDay || days[day] > mostActiveDay.tokens) mostActiveDay = { day, tokens: days[day] };
|
|
315
|
+
return {
|
|
316
|
+
totals,
|
|
317
|
+
models: [...models.values()]
|
|
318
|
+
.map((model) => ({ ...model, cost: roundCost(model.cost), share: totals.total > 0 ? model.tokens / totals.total : 0 }))
|
|
319
|
+
.sort((a, b) => b.tokens - a.tokens || b.messages - a.messages || a.model.localeCompare(b.model)),
|
|
320
|
+
days,
|
|
321
|
+
sessions: sessionCount,
|
|
322
|
+
activeDays: active.length,
|
|
323
|
+
daysInRange: daysBetween(firstDay, today) + 1,
|
|
324
|
+
firstDay,
|
|
325
|
+
today,
|
|
326
|
+
mostActiveDay,
|
|
327
|
+
longestSession,
|
|
328
|
+
longestStreak: longestStreak(active),
|
|
329
|
+
currentStreak: currentStreak(days, today),
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function longestStreak(sortedDays: readonly string[]): number {
|
|
334
|
+
let best = 0;
|
|
335
|
+
let run = 0;
|
|
336
|
+
let previous: string | undefined;
|
|
337
|
+
for (const day of sortedDays) {
|
|
338
|
+
run = previous !== undefined && shiftDay(previous, 1) === day ? run + 1 : 1;
|
|
339
|
+
best = Math.max(best, run);
|
|
340
|
+
previous = day;
|
|
341
|
+
}
|
|
342
|
+
return best;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// A streak stays alive through an idle today: it counts back from today when
|
|
346
|
+
// today is active, otherwise from yesterday.
|
|
347
|
+
function currentStreak(days: Record<string, number>, today: string): number {
|
|
348
|
+
let day = days[today] !== undefined ? today : shiftDay(today, -1);
|
|
349
|
+
let streak = 0;
|
|
350
|
+
while (days[day] !== undefined) {
|
|
351
|
+
streak++;
|
|
352
|
+
day = shiftDay(day, -1);
|
|
353
|
+
}
|
|
354
|
+
return streak;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
type LiveEntry = { type?: string; customType?: string; data?: unknown; timestamp?: unknown; modelId?: unknown };
|
|
358
|
+
|
|
359
|
+
/** The live session from its in-memory entries: usage, wall time so far, and captured line changes. */
|
|
360
|
+
export function currentSessionStats(entries: readonly unknown[], options: { sessionId: string; now: number }): CurrentSessionStats {
|
|
361
|
+
const totals = emptyTotals();
|
|
362
|
+
let messages = 0;
|
|
363
|
+
let model: string | undefined;
|
|
364
|
+
let firstAt = Infinity;
|
|
365
|
+
for (const entry of entries as LiveEntry[]) {
|
|
366
|
+
const at = typeof entry?.timestamp === "string" ? Date.parse(entry.timestamp) : NaN;
|
|
367
|
+
if (Number.isFinite(at)) firstAt = Math.min(firstAt, at);
|
|
368
|
+
if (entry?.type === "model_change" && typeof entry.modelId === "string") model = entry.modelId;
|
|
369
|
+
const usage = usageRecord(entry);
|
|
370
|
+
if (!usage) continue;
|
|
371
|
+
addUsage(totals, usage);
|
|
372
|
+
messages++;
|
|
373
|
+
if (usage.model !== UNKNOWN) model = usage.model;
|
|
374
|
+
}
|
|
375
|
+
totals.cost = roundCost(totals.cost);
|
|
376
|
+
const worktrees = new SessionChanges(options.sessionId, entries as LiveEntry[]).worktrees;
|
|
377
|
+
const lines = worktrees.length === 0
|
|
378
|
+
? undefined
|
|
379
|
+
: worktrees.reduce((sum, tree) => ({ added: sum.added + tree.model.added, removed: sum.removed + tree.model.deleted }), { added: 0, removed: 0 });
|
|
380
|
+
return { totals, messages, model, durationMs: Number.isFinite(firstAt) ? Math.max(0, options.now - firstAt) : 0, lines };
|
|
381
|
+
}
|