@uniqbit/mate-core 0.20.0 → 0.21.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-capability-plugins/companion-mentions/.claude-plugin/plugin.json +1 -1
- package/claude-capability-plugins/companion-mentions/hooks/register.ts +1 -1
- package/claude-plugin/hooks/hooks.json +10 -1
- package/claude-plugin/hooks/rtk-worktree-git.mjs +58 -0
- package/opencode-plugin/src/server.ts +9 -2
- package/package.json +2 -1
- package/src/cli/commands/artifact/delivery/environment.ts +28 -8
- package/src/cli/commands/artifact/delivery/link.ts +28 -9
- package/src/cli/commands/artifact/delivery/output.ts +7 -0
- package/src/cli/commands/companion/update.ts +2 -19
- package/src/cli/commands/factory/factory.ts +11 -1
- package/src/cli/commands/install.ts +47 -36
- package/src/cli/commands/launch/claude.ts +2 -0
- package/src/cli/commands/launch/shared.ts +33 -6
- package/src/cli/commands/plugin/install.ts +27 -11
- package/src/cli/commands/report/index.ts +180 -184
- package/src/cli/commands/report/markdown.ts +67 -72
- package/src/cli/commands/shared/companion-selection.ts +3 -1
- package/src/cli/commands/studio/access.ts +6 -14
- package/src/cli/commands/studio/areas.ts +112 -33
- package/src/cli/commands/studio/companion-add.ts +87 -0
- package/src/cli/commands/studio/companion-removal.ts +15 -8
- package/src/cli/commands/studio/factory-credential.ts +1 -15
- package/src/cli/commands/studio/factory-git-tokens.ts +40 -0
- package/src/cli/commands/studio/factory-relay.ts +18 -0
- package/src/cli/commands/studio/graph-model.ts +61 -0
- package/src/cli/commands/studio/graph.ts +336 -0
- package/src/cli/commands/studio/index.ts +4 -4
- package/src/cli/commands/studio/payload.ts +42 -15
- package/src/cli/commands/studio/repository-add.ts +116 -0
- package/src/cli/commands/studio/routes.ts +6 -0
- package/src/cli/commands/studio/selection.ts +12 -3
- package/src/cli/commands/studio/server.ts +127 -5
- package/src/cli/commands/studio/services.ts +40 -0
- package/src/cli/commands/studio/terminal.ts +45 -3
- package/src/cli/commands/studio/views/vault/markdown-tree.ts +84 -3
- package/src/cli/commands/studio/workset-session.ts +47 -14
- package/src/cli/commands/unwrap.ts +3 -0
- package/src/cli/commands/update.ts +2 -0
- package/src/cli/commands/vscode/release-vsix.json +4 -0
- package/src/cli/commands/vscode/setup.ts +71 -13
- package/src/cli/commands/vscode/vsix.ts +48 -7
- package/src/cli/commands/working/cleanup.ts +40 -8
- package/src/cli/commands/working/worktree.ts +176 -35
- package/src/cli/main.ts +17 -2
- package/src/cli/usage.ts +1 -1
- package/src/hooks/rtk-worktree-git.ts +48 -0
- package/src/hooks/validate-artifact-path.ts +38 -7
- package/src/lib/delivery/branch-template.ts +122 -0
- package/src/lib/delivery/branches.ts +21 -16
- package/src/lib/delivery/checkout.ts +102 -0
- package/src/lib/delivery/environment.ts +2 -0
- package/src/lib/delivery/merge-git.ts +13 -1
- package/src/lib/delivery/record-delivery.ts +83 -29
- package/src/lib/delivery/record.ts +15 -3
- package/src/lib/delivery/resolve-branch.ts +157 -110
- package/src/lib/factory/attach-client.ts +11 -1
- package/src/lib/factory/broker.ts +37 -40
- package/src/lib/factory/client.ts +22 -1
- package/src/lib/factory/clone-url.ts +39 -0
- package/src/lib/factory/command.ts +21 -5
- package/src/lib/factory/git-auth.ts +61 -0
- package/src/lib/factory/git-credential-store.ts +181 -0
- package/src/lib/factory/ids.ts +12 -2
- package/src/lib/factory/outcomes/actions.ts +20 -4
- package/src/lib/factory/outcomes/index.ts +77 -11
- package/src/lib/factory/outcomes/lifecycle.ts +9 -2
- package/src/lib/factory/outcomes/sessions.ts +23 -1
- package/src/lib/factory/prepare.ts +9 -3
- package/src/lib/factory/runner/scheduler.ts +96 -14
- package/src/lib/factory/runner/workflow.ts +5 -1
- package/src/lib/factory/runtime.ts +143 -43
- package/src/lib/orchestrator/companion-hub.ts +6 -1
- package/src/lib/orchestrator/engine-floor.ts +48 -0
- package/src/lib/orchestrator/launcher.ts +34 -1
- package/src/lib/orchestrator/projection-claude-commands.ts +2 -2
- package/src/lib/orchestrator/projection-claude-entry.ts +42 -21
- package/src/lib/orchestrator/projection-claude-links.ts +32 -8
- package/src/lib/orchestrator/projection-claude-skills.ts +2 -2
- package/src/lib/orchestrator/projection-entries.ts +22 -18
- package/src/lib/orchestrator/projection-opencode-copies.ts +65 -21
- package/src/lib/orchestrator/projection-runtime-documents.ts +66 -43
- package/src/lib/orchestrator/projection-types.ts +28 -1
- package/src/lib/orchestrator/refresh-working-claude-links.ts +3 -1
- package/src/lib/orchestrator/session-prepare.ts +6 -1
- package/src/lib/orchestrator/setup-compatibilities.ts +1 -1
- package/src/lib/orchestrator/types.ts +4 -0
- package/src/lib/orchestrator/umbrella-checkouts.ts +102 -0
- package/src/lib/orchestrator/working-repo-projection.ts +24 -4
- package/src/lib/orchestrator/wrap-pass.ts +1 -0
- package/src/lib/public-npm.ts +95 -50
- package/src/lib/session-state.ts +72 -2
- package/src/lib/update-checker.ts +7 -1
- package/src/lib/usage/aggregate.ts +202 -0
- package/src/lib/usage/cache.ts +87 -0
- package/src/lib/usage/claude-pricing.ts +71 -0
- package/src/lib/usage/claude.ts +189 -0
- package/src/lib/usage/collect.ts +56 -0
- package/src/lib/usage/opencode.ts +188 -0
- package/src/lib/usage/records.ts +80 -0
- package/src/lib/usage/rtk-database.ts +72 -0
- package/src/lib/usage/savings.ts +209 -0
- package/src/lib/usage/scope.ts +182 -0
- package/src/lib/usage/source.ts +102 -0
- package/src/lib/usage/types.ts +143 -0
- package/src/lib/usage/window.ts +37 -0
- package/src/lib/workset/factory-local.ts +157 -0
- package/src/lib/workset/record.ts +25 -11
- package/src/lib/workset/repositories.ts +118 -25
- package/src/lib/workset/worktree-include.ts +161 -0
- package/src/lib/workset/worktree-index.ts +6 -2
- package/src/lib/workset/worktree.ts +591 -101
- package/src/opencode/companion-hooks.ts +46 -8
- package/src/opencode/companion-policy.ts +18 -5
- package/src/opencode/enter-worktree.ts +254 -6
- package/src/opencode/session-register.ts +2 -2
- package/src/runtime/claude-bg-isolation.ts +138 -0
- package/src/runtime/companion-git.ts +10 -2
- package/src/runtime/companion-guidance.ts +17 -4
- package/src/runtime/current-branch.ts +16 -2
- package/src/runtime/entered-worktree.ts +24 -0
- package/src/runtime/git-tracked.ts +60 -0
- package/src/runtime/repo-destination.ts +72 -0
- package/src/runtime/repo-local.ts +25 -3
- package/src/runtime/rtk-git-guard.ts +66 -0
- package/src/runtime/runtime-document-manifest.ts +229 -19
- package/src/runtime/runtime-document-manifest.typecheck.ts +10 -0
- package/src/runtime/secret-guard.ts +9 -2
- package/src/runtime/secret-policy-weakening.ts +122 -0
- package/src/runtime/serving-claude-wrap.ts +15 -2
- package/src/runtime/umbrella-folder.ts +56 -0
- package/src/runtime/wrap-state.ts +5 -13
- package/src/studio.ts +37 -0
- package/src/templates/mate-skills/agents/mate-apply-change/SKILL.md +61 -6
- package/src/templates/mate-skills/agents/mate-explore-change/SKILL.md +8 -4
- package/src/templates/mate-skills/agents/mate-propose-change/SKILL.md +9 -5
- package/src/templates/mate-skills/agents/mate-publish-artifact/SKILL.md +5 -4
- package/src/templates/mate-skills/agents/mate-show-me/SKILL.md +10 -4
- package/src/templates/mate-skills/agents/mate-simplify-code/SKILL.md +5 -1
- package/src/templates/mate-skills/claude/mate-apply-change/SKILL.md +61 -6
- package/src/templates/mate-skills/claude/mate-explore-change/SKILL.md +8 -4
- package/src/templates/mate-skills/claude/mate-propose-change/SKILL.md +9 -5
- package/src/templates/mate-skills/claude/mate-publish-artifact/SKILL.md +5 -4
- package/src/templates/mate-skills/claude/mate-show-me/SKILL.md +10 -4
- package/src/templates/mate-skills/claude/mate-simplify-code/SKILL.md +5 -1
- package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +305 -42
- package/src/tools/setup/capabilities/rtk.ts +93 -1
- package/src/tools/setup/dynamic-plugins/audiences.ts +65 -21
- package/src/tools/setup/dynamic-plugins/frozen.ts +32 -13
- package/src/tools/setup/dynamic-plugins/hydrate.ts +4 -4
- package/src/tools/setup/dynamic-plugins/install.ts +24 -22
- package/src/tools/setup/dynamic-plugins/loader.ts +11 -7
- package/src/tools/setup/dynamic-plugins/paths.ts +30 -10
- package/src/tools/setup/dynamic-plugins/verify.ts +10 -7
- package/src/tools/setup/dynamic-plugins/workspaces.ts +153 -0
- package/src/tools/setup/mate.ts +3 -3
- package/src/tools/setup/plugins/gitignore.ts +15 -9
- package/src/tools/setup/providers/claude-plugin-hooks.ts +12 -0
- package/src/tools/setup/providers/claude.ts +25 -3
- package/src/tools/setup/utils.ts +4 -2
- package/src/tools/setup/working-repo-cleanup.ts +2 -2
- package/src/tools/setup.ts +25 -14
- package/studio-dist/client/assets/app-D9cw6szy.css +2 -0
- package/studio-dist/client/assets/artifacts-WD2ZXYrx.js +1 -0
- package/studio-dist/client/assets/button-Br0O1sXw.js +1 -0
- package/studio-dist/client/assets/combobox-DA7RAUUZ.js +1 -0
- package/studio-dist/client/assets/companion-view-CrabvxS8.js +1 -0
- package/studio-dist/client/assets/factory-DGS0E16C.js +6 -0
- package/studio-dist/client/assets/fields-6aXBpFhJ.js +1 -0
- package/studio-dist/client/assets/getting-started-Clde4w6P.js +1 -0
- package/studio-dist/client/assets/getting-started-D6kgWwWZ.js +1 -0
- package/studio-dist/client/assets/getting-started._topic-BiunccbT.js +1 -0
- package/studio-dist/client/assets/getting-started.index-DpiNoGw8.js +1 -0
- package/studio-dist/client/assets/graph-B_TCBVbu.js +2 -0
- package/studio-dist/client/assets/graph-canvas-Ba37Y5AE.js +3242 -0
- package/studio-dist/client/assets/guides-Du_RtJxP.js +1 -0
- package/studio-dist/client/assets/index-Df8L1LQa.js +40 -0
- package/studio-dist/client/assets/jsx-runtime-MZURdZre.js +1 -0
- package/studio-dist/client/assets/markdown-view-BOX6x0rL.js +1 -0
- package/studio-dist/client/assets/panel-dbmCx7Mx.js +1 -0
- package/studio-dist/client/assets/queries-RvHeXY12.js +1 -0
- package/studio-dist/client/assets/react-3QStrcDO.js +27 -0
- package/studio-dist/client/assets/report-url-XRL0x1SY.js +1 -0
- package/studio-dist/client/assets/reports-r3IK7Doz.js +1 -0
- package/studio-dist/client/assets/routes-C0A5LTFc.js +1 -0
- package/studio-dist/client/assets/select-CnaMd617.js +1 -0
- package/studio-dist/client/assets/skills-CzjzHpBT.js +1 -0
- package/studio-dist/client/assets/specs-B0ldF_6J.js +1 -0
- package/studio-dist/client/assets/specs-view-BnCLA0gW.js +1 -0
- package/studio-dist/client/assets/spinner-Dcm3fqK1.js +1 -0
- package/studio-dist/client/assets/steps-C0p2N1Pb.js +1 -0
- package/studio-dist/client/assets/store-Dw34catY.js +1 -0
- package/studio-dist/client/assets/studio-Cpz_HRHp.js +100 -0
- package/studio-dist/client/assets/studio-queries-ibmpFo6R.js +2 -0
- package/studio-dist/client/assets/usage-C2QJ_0IZ.js +55 -0
- package/studio-dist/client/assets/useAnchoredPopupScrollLock-Bj-FWb8z.js +1 -0
- package/studio-dist/client/assets/useMutation-aAr2uiay.js +1 -0
- package/studio-dist/client/assets/useSelector-AYcH7lB0.js +2 -0
- package/studio-dist/client/assets/vault-BGcxkSIY.js +1 -0
- package/studio-dist/client/assets/warnings-R1cE1rLf.js +1 -0
- package/studio-dist/client/assets/workflow-C2qTrMDH.js +1 -0
- package/studio-dist/server/assets/__23tanstack-start-server-fn-resolver-Bn896ZYj.js +122 -0
- package/studio-dist/server/assets/_tanstack-start-manifest_v.js +102 -35
- package/studio-dist/server/assets/{actions-Bvgj9eb8.js → actions-DYSv-9VV.js} +10 -4
- package/studio-dist/server/assets/artifacts-DnF9L3dZ.js +216 -0
- package/studio-dist/server/assets/{button-CIJqAhni.js → button-CgOIVdmD.js} +13 -1702
- package/studio-dist/server/assets/combobox-DV_s9W0s.js +483 -0
- package/studio-dist/server/assets/{companion-view-DISASvdJ.js → companion-view-BKVXD3TO.js} +3 -3
- package/studio-dist/server/assets/companions-C7fctnU9.js +31 -0
- package/studio-dist/server/assets/{createServerRpc-tK2lE9R2.js → createServerRpc-bFKFpGFG.js} +1 -1
- package/studio-dist/server/assets/{factory-DUTa0eDs.js → factory-C7Ybg0xG.js} +1256 -353
- package/studio-dist/server/assets/{factory-DGPmNGbo.js → factory-Df5uAHjb.js} +53 -6
- package/studio-dist/server/assets/fields-BbieQTD0.js +1190 -0
- package/studio-dist/server/assets/getting-started-B136TP57.js +4 -0
- package/studio-dist/server/assets/getting-started-CRxMWorQ.js +67 -0
- package/studio-dist/server/assets/getting-started._topic-DJKQAzYl.js +13 -0
- package/studio-dist/server/assets/getting-started.index-D84gec1t.js +13 -0
- package/studio-dist/server/assets/graph-CSje3029.js +801 -0
- package/studio-dist/server/assets/graph-DDZzXM1L.js +16 -0
- package/studio-dist/server/assets/graph-canvas-22bWB5-2.js +21066 -0
- package/studio-dist/server/assets/graph-wire-BdSUx0G5.js +58 -0
- package/studio-dist/server/assets/guides-D9dk1Frq.js +13 -0
- package/studio-dist/server/assets/guides-IE-19POz.js +5 -0
- package/studio-dist/server/assets/guides.server-vcYRY5wx.js +66 -0
- package/studio-dist/server/assets/jsx-runtime-Bt0s0YKS.js +451 -0
- package/studio-dist/server/assets/{markdown-view-Bn7xPdks.js → markdown-view-BR8dJ7aR.js} +28 -9
- package/studio-dist/server/assets/{panel-3Jmn4awF.js → panel-BR_t9iMM.js} +4 -4
- package/studio-dist/server/assets/queries-DWoTin-q.js +32 -0
- package/studio-dist/server/assets/react-CdqSUhaL.js +89 -0
- package/studio-dist/server/assets/redirect-BaZ_QyqF.js +39 -0
- package/studio-dist/server/assets/report-url-BUXPcE_8.js +9 -0
- package/studio-dist/server/assets/{reports-D6YMqhnO.js → reports-CQ9qQ1-n.js} +9 -10
- package/studio-dist/server/assets/{reports-C06RXVE2.js → reports-dYDEoBeq.js} +3 -3
- package/studio-dist/server/assets/{router-C8MGqlAY.js → router-DkRHNTpE.js} +787 -2862
- package/studio-dist/server/assets/{routes-BcFgvqf7.js → routes-B6GfOew4.js} +22 -171
- package/studio-dist/server/assets/{search-JAKurDNh.js → search-BJnWLfkG.js} +21 -2
- package/studio-dist/server/assets/select-Af7Wibii.js +1609 -0
- package/studio-dist/server/assets/{shell-DS3wUexh.js → shell-Hq-hXgnT.js} +6 -5
- package/studio-dist/server/assets/{skills-BEnOxiDl.js → skills-B7nEuVbx.js} +9 -8
- package/studio-dist/server/assets/{skills-CtrBAtX3.js → skills-B_YYL7q8.js} +3 -3
- package/studio-dist/server/assets/specs-BpLUFntA.js +51 -0
- package/studio-dist/server/assets/specs-view-0peMVd22.js +426 -0
- package/studio-dist/server/assets/spinner-CdwJW4VB.js +20 -0
- package/studio-dist/server/assets/{steps-Dq_CwY_s.js → steps-D56DApvK.js} +1 -1
- package/studio-dist/server/assets/store-Cs17okNG.js +280 -0
- package/studio-dist/server/assets/studio-CAcKp3bM.js +10340 -0
- package/studio-dist/server/assets/studio-queries-BtRGzDdh.js +1451 -0
- package/studio-dist/server/assets/usage-COdjd1gD.js +25570 -0
- package/studio-dist/server/assets/usage-f6pqE1tm.js +24 -0
- package/studio-dist/server/assets/useAnchoredPopupScrollLock-DlBKHRw7.js +756 -0
- package/studio-dist/server/assets/useMutation-DzTZGenE.js +690 -0
- package/studio-dist/server/assets/{__23tanstack-start-server-fn-resolver-M2GBs8s3.js → useSelector-DUmCUXAs.js} +4 -668
- package/studio-dist/server/assets/{vault-Fvxt2Tzl.js → vault-BDuIUq0F.js} +8 -5
- package/studio-dist/server/assets/{vault-BmWnryh3.js → vault-BVLp6zu3.js} +3 -3
- package/studio-dist/server/assets/{views-BgYa-za2.js → views-flRUr21z.js} +4 -4
- package/studio-dist/server/assets/{warnings-DzR6fyZh.js → warnings-CDy9pdgL.js} +3 -2
- package/studio-dist/server/assets/{delivery-path-C29fBynY.js → workflow-D9GKI2EV.js} +132 -106
- package/studio-dist/server/server.js +582 -8
- package/src/cli/commands/report/collector.ts +0 -288
- package/studio-dist/client/assets/app-CdPiFv59.css +0 -2
- package/studio-dist/client/assets/button-BIIHE0EQ.js +0 -3
- package/studio-dist/client/assets/companion-view-DM6YyXaR.js +0 -1
- package/studio-dist/client/assets/delivery-path-DELxj0Av.js +0 -1
- package/studio-dist/client/assets/factory-BZy0E8ty.js +0 -4
- package/studio-dist/client/assets/index-B3wkMzjA.js +0 -40
- package/studio-dist/client/assets/markdown-view-pQ2Qp_i5.js +0 -1
- package/studio-dist/client/assets/panel-CbajlC3p.js +0 -1
- package/studio-dist/client/assets/prepaint-CwSrpdFA.js +0 -27
- package/studio-dist/client/assets/react-CN2GSx7x.js +0 -1
- package/studio-dist/client/assets/reports-DllhYQ5_.js +0 -1
- package/studio-dist/client/assets/rolldown-runtime-WkwZ5CU-.js +0 -1
- package/studio-dist/client/assets/routes-COm-G3mK.js +0 -1
- package/studio-dist/client/assets/skills-DmWAy-jZ.js +0 -1
- package/studio-dist/client/assets/specs-BG3Wi3ln.js +0 -1
- package/studio-dist/client/assets/steps-DFsH3Neu.js +0 -1
- package/studio-dist/client/assets/vault-B2q1nBY5.js +0 -1
- package/studio-dist/client/assets/warnings-BSXIyuSQ.js +0 -1
- package/studio-dist/client/assets/workflow-DlsQD6Hc.js +0 -1
- package/studio-dist/server/assets/companions-BYbHWKOZ.js +0 -15
- package/studio-dist/server/assets/createServerFn-F5sAOF8V.js +0 -459
- package/studio-dist/server/assets/prepaint-DJfTQ_VH.js +0 -45
- package/studio-dist/server/assets/react-Ce6dj15C.js +0 -46
- package/studio-dist/server/assets/rolldown-runtime-DYf_mQCB.js +0 -34
- package/studio-dist/server/assets/specs-C8rv34-5.js +0 -211
- package/studio-dist/server/assets/studio-BeltxxKt.js +0 -216
- package/studio-dist/server/assets/workflow-liRYecHk.js +0 -73
package/src/lib/public-npm.ts
CHANGED
|
@@ -34,59 +34,94 @@ function packageNameFromSpec(packageSpec: string): string {
|
|
|
34
34
|
return separator === -1 ? packageSpec : packageSpec.slice(0, separator);
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
+
function packageScope(packageName: string): string | null {
|
|
38
|
+
return packageName.startsWith("@") ? packageName.slice(0, packageName.indexOf("/")) : null;
|
|
39
|
+
}
|
|
40
|
+
|
|
37
41
|
function getPublicNpmUserConfig(packageName: string, registry: string): string {
|
|
38
|
-
const scope =
|
|
42
|
+
const scope = packageScope(packageName);
|
|
39
43
|
return [`registry=${registry}`, ...(scope ? [`${scope}:registry=${registry}`] : []), ""].join(
|
|
40
44
|
"\n",
|
|
41
45
|
);
|
|
42
46
|
}
|
|
43
47
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
const tempDir = await publicNpmDeps.mkdtemp(path.join(os.tmpdir(), "mate-public-npm-"));
|
|
50
|
-
const userConfigPath = path.join(tempDir, ".npmrc");
|
|
48
|
+
/** CLI flags outrank project config and `npm_config_*` variables. */
|
|
49
|
+
function getRegistryFlags(packageName: string, registry: string): string[] {
|
|
50
|
+
const scope = packageScope(packageName);
|
|
51
|
+
return [`--registry=${registry}`, ...(scope ? [`--${scope}:registry=${registry}`] : [])];
|
|
52
|
+
}
|
|
51
53
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
"utf8",
|
|
56
|
-
);
|
|
54
|
+
const ISOLATED_DIR_PREFIX = "mate-public-npm-";
|
|
55
|
+
/** Makes the directory npm's `localPrefix`, so npm stops its upward project-config search there. */
|
|
56
|
+
const EMPTY_PACKAGE_JSON = "{}\n";
|
|
57
57
|
|
|
58
|
+
/**
|
|
59
|
+
* Runs `run` in a fresh temporary directory that holds only an empty `package.json`, so a
|
|
60
|
+
* package manager started there reads no project config from the caller's directory.
|
|
61
|
+
*/
|
|
62
|
+
async function withIsolatedPackageDir<T>(run: (dir: string) => Promise<T>): Promise<T> {
|
|
63
|
+
const dir = await publicNpmDeps.mkdtemp(path.join(os.tmpdir(), ISOLATED_DIR_PREFIX));
|
|
58
64
|
try {
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
NPM_CONFIG_USERCONFIG: userConfigPath,
|
|
62
|
-
});
|
|
65
|
+
await publicNpmDeps.writeFile(path.join(dir, "package.json"), EMPTY_PACKAGE_JSON, "utf8");
|
|
66
|
+
return await run(dir);
|
|
63
67
|
} finally {
|
|
64
|
-
await publicNpmDeps.rm(
|
|
68
|
+
await publicNpmDeps.rm(dir, { recursive: true, force: true });
|
|
65
69
|
}
|
|
66
70
|
}
|
|
67
71
|
|
|
72
|
+
function withIsolatedPackageDirSync<T>(run: (dir: string) => T): T {
|
|
73
|
+
const dir = publicNpmDeps.mkdtempSync(path.join(os.tmpdir(), ISOLATED_DIR_PREFIX));
|
|
74
|
+
try {
|
|
75
|
+
publicNpmDeps.writeFileSync(path.join(dir, "package.json"), EMPTY_PACKAGE_JSON, "utf8");
|
|
76
|
+
return run(dir);
|
|
77
|
+
} finally {
|
|
78
|
+
publicNpmDeps.rmSync(dir, { recursive: true, force: true });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
interface PublicNpmOptions {
|
|
83
|
+
cwd: string;
|
|
84
|
+
env: NodeJS.ProcessEnv;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Not named `.npmrc`, so npm does not also read the pin as the project config.
|
|
88
|
+
const USER_CONFIG_FILE = "user.npmrc";
|
|
89
|
+
|
|
90
|
+
function publicNpmOptions(dir: string): PublicNpmOptions {
|
|
91
|
+
return {
|
|
92
|
+
cwd: dir,
|
|
93
|
+
env: { ...process.env, NPM_CONFIG_USERCONFIG: path.join(dir, USER_CONFIG_FILE) },
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function withPublicNpmConfig<T>(
|
|
98
|
+
packageName: string,
|
|
99
|
+
registry: string,
|
|
100
|
+
run: (options: PublicNpmOptions) => Promise<T>,
|
|
101
|
+
): Promise<T> {
|
|
102
|
+
return withIsolatedPackageDir(async (dir) => {
|
|
103
|
+
await publicNpmDeps.writeFile(
|
|
104
|
+
path.join(dir, USER_CONFIG_FILE),
|
|
105
|
+
getPublicNpmUserConfig(packageName, registry),
|
|
106
|
+
"utf8",
|
|
107
|
+
);
|
|
108
|
+
return run(publicNpmOptions(dir));
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
68
112
|
function withPublicNpmConfigSync<T>(
|
|
69
113
|
packageName: string,
|
|
70
114
|
registry: string,
|
|
71
|
-
run: (
|
|
115
|
+
run: (options: PublicNpmOptions) => T,
|
|
72
116
|
): T {
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
);
|
|
81
|
-
|
|
82
|
-
try {
|
|
83
|
-
return run({
|
|
84
|
-
...process.env,
|
|
85
|
-
NPM_CONFIG_USERCONFIG: userConfigPath,
|
|
86
|
-
});
|
|
87
|
-
} finally {
|
|
88
|
-
publicNpmDeps.rmSync(tempDir, { recursive: true, force: true });
|
|
89
|
-
}
|
|
117
|
+
return withIsolatedPackageDirSync((dir) => {
|
|
118
|
+
publicNpmDeps.writeFileSync(
|
|
119
|
+
path.join(dir, USER_CONFIG_FILE),
|
|
120
|
+
getPublicNpmUserConfig(packageName, registry),
|
|
121
|
+
"utf8",
|
|
122
|
+
);
|
|
123
|
+
return run(publicNpmOptions(dir));
|
|
124
|
+
});
|
|
90
125
|
}
|
|
91
126
|
|
|
92
127
|
export async function fetchPublicPackageVersion(
|
|
@@ -94,38 +129,48 @@ export async function fetchPublicPackageVersion(
|
|
|
94
129
|
registry = PUBLIC_NPM_REGISTRY,
|
|
95
130
|
distTag = "latest",
|
|
96
131
|
): Promise<string> {
|
|
97
|
-
const { stdout } = await withPublicNpmConfig(packageName, registry, (
|
|
98
|
-
publicNpmDeps.execFile(
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
132
|
+
const { stdout } = await withPublicNpmConfig(packageName, registry, (options) =>
|
|
133
|
+
publicNpmDeps.execFile(
|
|
134
|
+
"npm",
|
|
135
|
+
["view", `${packageName}@${distTag}`, "version", ...getRegistryFlags(packageName, registry)],
|
|
136
|
+
{ timeout: 10_000, ...options },
|
|
137
|
+
),
|
|
102
138
|
);
|
|
103
139
|
|
|
104
140
|
return stdout.trim();
|
|
105
141
|
}
|
|
106
142
|
|
|
107
|
-
/** `npm pack` a package from
|
|
143
|
+
/** `npm pack` a package from `registry` into `destination`; returns the tarball path. */
|
|
108
144
|
export async function packPublicPackage(
|
|
109
145
|
packageSpec: string,
|
|
110
146
|
destination: string,
|
|
111
147
|
registry = PUBLIC_NPM_REGISTRY,
|
|
112
148
|
): Promise<string> {
|
|
113
|
-
const
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
149
|
+
const packageName = packageNameFromSpec(packageSpec);
|
|
150
|
+
const packDestination = path.resolve(destination);
|
|
151
|
+
const { stdout } = await withPublicNpmConfig(packageName, registry, (options) =>
|
|
152
|
+
publicNpmDeps.execFile(
|
|
153
|
+
"npm",
|
|
154
|
+
[
|
|
155
|
+
"pack",
|
|
156
|
+
packageSpec,
|
|
157
|
+
"--pack-destination",
|
|
158
|
+
packDestination,
|
|
159
|
+
...getRegistryFlags(packageName, registry),
|
|
160
|
+
],
|
|
161
|
+
{ timeout: 120_000, ...options },
|
|
162
|
+
),
|
|
118
163
|
);
|
|
119
164
|
const tarball = stdout.trim().split("\n").at(-1)?.trim();
|
|
120
165
|
if (!tarball) throw new Error(`npm pack ${packageSpec} printed no tarball name`);
|
|
121
|
-
return path.join(
|
|
166
|
+
return path.join(packDestination, tarball);
|
|
122
167
|
}
|
|
123
168
|
|
|
124
169
|
export function installPublicPackageSync(packageSpec: string, registry = PUBLIC_NPM_REGISTRY) {
|
|
125
|
-
return withPublicNpmConfigSync(packageNameFromSpec(packageSpec), registry, (
|
|
170
|
+
return withPublicNpmConfigSync(packageNameFromSpec(packageSpec), registry, (options) =>
|
|
126
171
|
publicNpmDeps.spawnSync("npm", ["install", "-g", packageSpec], {
|
|
127
172
|
stdio: "inherit",
|
|
128
|
-
|
|
173
|
+
...options,
|
|
129
174
|
}),
|
|
130
175
|
);
|
|
131
176
|
}
|
package/src/lib/session-state.ts
CHANGED
|
@@ -3,7 +3,13 @@ import fs from "node:fs/promises";
|
|
|
3
3
|
|
|
4
4
|
import { workingRepoGit } from "./delivery/branches";
|
|
5
5
|
import { mergeGit } from "./delivery/merge-git";
|
|
6
|
+
import { currentBranch } from "../runtime/current-branch";
|
|
6
7
|
import { processAlive } from "../runtime/opencode-server-record";
|
|
8
|
+
import {
|
|
9
|
+
umbrellaChildFolders,
|
|
10
|
+
umbrellaFolderOf,
|
|
11
|
+
umbrellaMirroredBy,
|
|
12
|
+
} from "../runtime/umbrella-folder";
|
|
7
13
|
import {
|
|
8
14
|
readSessionRegistry,
|
|
9
15
|
sessionRegistryPath,
|
|
@@ -48,8 +54,17 @@ export interface SessionStateDeps {
|
|
|
48
54
|
claudeAgents?: () => Promise<ClaudeAgent[] | null>;
|
|
49
55
|
isAlive?: (pid: number) => boolean;
|
|
50
56
|
directoryExists?: (dir: string) => Promise<boolean>;
|
|
51
|
-
/**
|
|
57
|
+
/**
|
|
58
|
+
* True when the branch's head is merged into the default branch of the checkout at `cwd`.
|
|
59
|
+
* Asked per child for a mirrored umbrella worktree.
|
|
60
|
+
*/
|
|
52
61
|
isMerged?: (cwd: string, branch: string) => Promise<boolean>;
|
|
62
|
+
/** True when the branch has no commits of its own in the checkout at `cwd`. Asked per unmerged child. */
|
|
63
|
+
isUntouched?: (cwd: string, branch: string) => Promise<boolean>;
|
|
64
|
+
/** The branch checked out at `cwd`; null when detached. Asked per mirrored worktree child. */
|
|
65
|
+
branchAt?: (cwd: string) => Promise<string | null>;
|
|
66
|
+
/** True when the checkout at `cwd` has the branch. Asked per detached mirrored worktree child. */
|
|
67
|
+
hasBranch?: (cwd: string, branch: string) => Promise<boolean>;
|
|
53
68
|
readFirstPrompt?: (transcript: string) => Promise<string | null>;
|
|
54
69
|
}
|
|
55
70
|
|
|
@@ -106,6 +121,56 @@ export async function branchMerged(cwd: string, branch: string): Promise<boolean
|
|
|
106
121
|
return (await git.patchMatch(tip, defaultBranch)) !== null;
|
|
107
122
|
}
|
|
108
123
|
|
|
124
|
+
async function branchExists(cwd: string, branch: string): Promise<boolean> {
|
|
125
|
+
return (await mergeGit(cwd).tip(branch)) !== null;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** True when the branch exists and its tip lies on the default branch's first-parent line. */
|
|
129
|
+
export async function branchUntouched(cwd: string, branch: string): Promise<boolean> {
|
|
130
|
+
const defaultBranch = await workingRepoGit(cwd).defaultBranch();
|
|
131
|
+
const git = mergeGit(cwd);
|
|
132
|
+
const tip = await git.tip(branch);
|
|
133
|
+
if (!tip) return false;
|
|
134
|
+
return (
|
|
135
|
+
(await git.isAncestor(tip, defaultBranch)) && (await git.onFirstParent(tip, defaultBranch))
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
type MergeCheck = (cwd: string, branch: string) => Promise<boolean>;
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* `isMerged` for a session's folder. A mirrored umbrella worktree holds one worktree per
|
|
143
|
+
* child, each checked on its own branch (the session's when detached; a detached child
|
|
144
|
+
* without it has no work of its own): merged once some child is and every other child's
|
|
145
|
+
* branch is untouched; a failing child check throws. An
|
|
146
|
+
* Umbrella Repository is no Git checkout, so it runs no check and is never merged.
|
|
147
|
+
*/
|
|
148
|
+
async function sessionBranchMerged(
|
|
149
|
+
cwd: string,
|
|
150
|
+
branch: string,
|
|
151
|
+
checks: {
|
|
152
|
+
isMerged: MergeCheck;
|
|
153
|
+
isUntouched: MergeCheck;
|
|
154
|
+
branchAt: (cwd: string) => Promise<string | null>;
|
|
155
|
+
hasBranch: MergeCheck;
|
|
156
|
+
},
|
|
157
|
+
): Promise<boolean> {
|
|
158
|
+
const umbrella = umbrellaFolderOf(cwd);
|
|
159
|
+
if (!umbrella) return checks.isMerged(cwd, branch);
|
|
160
|
+
if (!umbrellaMirroredBy(umbrella)) return false;
|
|
161
|
+
const states = await Promise.all(
|
|
162
|
+
umbrellaChildFolders(umbrella).map(async (child) => {
|
|
163
|
+
const own = await checks.branchAt(child);
|
|
164
|
+
// A branch gone from a checkout counts as merged; a detached child may never have had it.
|
|
165
|
+
if (own === null && !(await checks.hasBranch(child, branch))) return "untouched";
|
|
166
|
+
const checked = own ?? branch;
|
|
167
|
+
if (await checks.isMerged(child, checked)) return "merged";
|
|
168
|
+
return (await checks.isUntouched(child, checked)) ? "untouched" : "open";
|
|
169
|
+
}),
|
|
170
|
+
);
|
|
171
|
+
return states.includes("merged") && !states.includes("open");
|
|
172
|
+
}
|
|
173
|
+
|
|
109
174
|
/** Text of a user message line in a Claude transcript; null for anything else. */
|
|
110
175
|
function promptText(line: string): string | null {
|
|
111
176
|
let entry: unknown;
|
|
@@ -225,6 +290,9 @@ export async function listSessionsWithState(
|
|
|
225
290
|
isAlive: options.isAlive ?? processAlive,
|
|
226
291
|
directoryExists: options.directoryExists ?? exists,
|
|
227
292
|
isMerged: options.isMerged ?? branchMerged,
|
|
293
|
+
isUntouched: options.isUntouched ?? branchUntouched,
|
|
294
|
+
branchAt: options.branchAt ?? currentBranch,
|
|
295
|
+
hasBranch: options.hasBranch ?? branchExists,
|
|
228
296
|
};
|
|
229
297
|
const now = (options.now ?? (() => new Date()))();
|
|
230
298
|
const readPrompt = options.readFirstPrompt ?? readFirstPrompt;
|
|
@@ -234,7 +302,9 @@ export async function listSessionsWithState(
|
|
|
234
302
|
const mergeCache = new Map<string, Promise<boolean>>();
|
|
235
303
|
const merged = (cwd: string, branch: string) => {
|
|
236
304
|
const key = `${cwd}\0${branch}`;
|
|
237
|
-
if (!mergeCache.has(key))
|
|
305
|
+
if (!mergeCache.has(key)) {
|
|
306
|
+
mergeCache.set(key, sessionBranchMerged(cwd, branch, deps));
|
|
307
|
+
}
|
|
238
308
|
return mergeCache.get(key)!;
|
|
239
309
|
};
|
|
240
310
|
|
|
@@ -110,8 +110,14 @@ export function getUpdateChannel(version: string = getCurrentVersion()): UpdateC
|
|
|
110
110
|
return isCanaryVersion(version) ? "canary" : "latest";
|
|
111
111
|
}
|
|
112
112
|
|
|
113
|
+
/** A local test build counts as its release version, so `0.20.0` is not newer than `0.20.0-local.0`. */
|
|
113
114
|
export function isNewer(latest: string, current: string): boolean {
|
|
114
|
-
|
|
115
|
+
const currentVersion = semver.parse(current);
|
|
116
|
+
if (!semver.valid(latest) || !currentVersion) return false;
|
|
117
|
+
if (isLocalVersion(current)) {
|
|
118
|
+
const { major, minor, patch } = currentVersion;
|
|
119
|
+
return semver.gt(latest, `${major}.${minor}.${patch}`);
|
|
120
|
+
}
|
|
115
121
|
return semver.gt(latest, current);
|
|
116
122
|
}
|
|
117
123
|
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { normalizeUsageRecords, type UsageRecord } from "./records";
|
|
2
|
+
import type { UsageScope } from "./scope";
|
|
3
|
+
import type { UsageCollection } from "./source";
|
|
4
|
+
import {
|
|
5
|
+
unknownUsageMetrics,
|
|
6
|
+
type CompanionUsageSnapshot,
|
|
7
|
+
type UsageCost,
|
|
8
|
+
type UsageCoverage,
|
|
9
|
+
type UsageGroup,
|
|
10
|
+
type UsageMetrics,
|
|
11
|
+
type UsageSource,
|
|
12
|
+
type UsageWindow,
|
|
13
|
+
} from "./types";
|
|
14
|
+
import { usageDates } from "./window";
|
|
15
|
+
|
|
16
|
+
const successful = (source: UsageSource) => source.status === "ok" || source.status === "empty";
|
|
17
|
+
const sum = (values: (number | null | undefined)[], emptyKnown: boolean): number | null => {
|
|
18
|
+
const known = values.filter((value): value is number => typeof value === "number");
|
|
19
|
+
if (known.length) return known.reduce((a, b) => a + b, 0);
|
|
20
|
+
return emptyKnown ? 0 : null;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
function coverage(
|
|
24
|
+
sources: UsageSource[],
|
|
25
|
+
values: (number | null | undefined)[],
|
|
26
|
+
amount: number | null,
|
|
27
|
+
): UsageCoverage {
|
|
28
|
+
if (amount === null) return "unavailable";
|
|
29
|
+
const enabled = sources.filter((source) => source.status !== "disabled");
|
|
30
|
+
return enabled.every((source) => successful(source) && !source.partial) &&
|
|
31
|
+
values.every((value) => value !== null && value !== undefined)
|
|
32
|
+
? "complete"
|
|
33
|
+
: "partial";
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function costTotal(costs: (UsageCost | undefined)[], emptyKnown: boolean): UsageCost {
|
|
37
|
+
const known = costs.filter(
|
|
38
|
+
(cost): cost is UsageCost =>
|
|
39
|
+
cost?.amount !== null && cost?.amount !== undefined && cost.currency !== null,
|
|
40
|
+
);
|
|
41
|
+
const currencies = new Set(known.map((cost) => cost.currency));
|
|
42
|
+
if (currencies.size > 1) return { amount: null, currency: null, basis: "unknown" };
|
|
43
|
+
if (!known.length)
|
|
44
|
+
return {
|
|
45
|
+
amount: emptyKnown ? 0 : null,
|
|
46
|
+
currency: emptyKnown ? "USD" : null,
|
|
47
|
+
basis: emptyKnown ? "reported" : "unknown",
|
|
48
|
+
};
|
|
49
|
+
const bases = new Set(known.map((cost) => cost.basis));
|
|
50
|
+
return {
|
|
51
|
+
amount: known.reduce((total, cost) => total + cost.amount!, 0),
|
|
52
|
+
currency: known[0]!.currency,
|
|
53
|
+
basis: bases.size === 1 ? known[0]!.basis : "mixed",
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function usageMetrics(records: UsageRecord[], sources: UsageSource[]): UsageMetrics {
|
|
58
|
+
const metrics = unknownUsageMetrics();
|
|
59
|
+
const spending = records.filter((record) => record.tokens);
|
|
60
|
+
const savings = records.filter((record) => record.savings);
|
|
61
|
+
const providers = sources.filter(
|
|
62
|
+
(source) => source.name === "claude" || source.name === "opencode",
|
|
63
|
+
);
|
|
64
|
+
const savers = sources.filter((source) => source.name === "tokensave" || source.name === "rtk");
|
|
65
|
+
const usageKnown = providers.some(successful) && spending.length === 0;
|
|
66
|
+
const savingsKnown = savers.some(successful) && savings.length === 0;
|
|
67
|
+
const tokenSum = (token: keyof NonNullable<UsageRecord["tokens"]>) =>
|
|
68
|
+
sum(
|
|
69
|
+
spending.map((record) => record.tokens![token]),
|
|
70
|
+
usageKnown,
|
|
71
|
+
);
|
|
72
|
+
metrics.inputTokens = tokenSum("input");
|
|
73
|
+
metrics.outputTokens = tokenSum("output");
|
|
74
|
+
metrics.cacheReadTokens = tokenSum("cacheRead");
|
|
75
|
+
metrics.cacheWriteTokens = tokenSum("cacheWrite");
|
|
76
|
+
const tokenValues = spending.flatMap((record) => Object.values(record.tokens!));
|
|
77
|
+
metrics.totalTokens = sum(tokenValues, usageKnown);
|
|
78
|
+
metrics.cost = costTotal(
|
|
79
|
+
spending.map((record) => record.cost),
|
|
80
|
+
usageKnown,
|
|
81
|
+
);
|
|
82
|
+
metrics.savings.estimatedTokens = sum(
|
|
83
|
+
savings.map((record) => record.savings!.tokens),
|
|
84
|
+
savingsKnown,
|
|
85
|
+
);
|
|
86
|
+
metrics.savings.calls = sum(
|
|
87
|
+
savings.map((record) => record.savings!.calls),
|
|
88
|
+
savingsKnown,
|
|
89
|
+
);
|
|
90
|
+
metrics.savings.estimatedCost = costTotal(
|
|
91
|
+
savings.map((record) => record.savings!.cost),
|
|
92
|
+
false,
|
|
93
|
+
);
|
|
94
|
+
metrics.coverage = {
|
|
95
|
+
tokens: coverage(providers, tokenValues, metrics.totalTokens),
|
|
96
|
+
cost: coverage(
|
|
97
|
+
providers,
|
|
98
|
+
spending.map((record) => record.cost?.amount),
|
|
99
|
+
metrics.cost.amount,
|
|
100
|
+
),
|
|
101
|
+
savings: coverage(
|
|
102
|
+
savers,
|
|
103
|
+
savings.map((record) => record.savings!.tokens),
|
|
104
|
+
metrics.savings.estimatedTokens,
|
|
105
|
+
),
|
|
106
|
+
};
|
|
107
|
+
return metrics;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function append(group: Map<string, UsageRecord[]>, key: string, record: UsageRecord): void {
|
|
111
|
+
const entries = group.get(key);
|
|
112
|
+
if (entries) entries.push(record);
|
|
113
|
+
else group.set(key, [record]);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function usageGroup(
|
|
117
|
+
records: UsageRecord[],
|
|
118
|
+
sources: UsageSource[],
|
|
119
|
+
window: UsageWindow,
|
|
120
|
+
): UsageGroup {
|
|
121
|
+
const models = new Map<string, UsageRecord[]>();
|
|
122
|
+
const days = new Map<string, UsageRecord[]>();
|
|
123
|
+
for (const record of records) {
|
|
124
|
+
append(models, `${record.source}\0${record.model}`, record);
|
|
125
|
+
append(days, record.timestamp.slice(0, 10), record);
|
|
126
|
+
}
|
|
127
|
+
return {
|
|
128
|
+
metrics: usageMetrics(records, sources),
|
|
129
|
+
sources,
|
|
130
|
+
daily: usageDates(window).map((date) => ({
|
|
131
|
+
date,
|
|
132
|
+
metrics: usageMetrics(days.get(date) ?? [], sources),
|
|
133
|
+
})),
|
|
134
|
+
breakdowns: [...models.values()]
|
|
135
|
+
.map((entries) => ({
|
|
136
|
+
runtime: entries[0]!.source,
|
|
137
|
+
model: entries[0]!.model,
|
|
138
|
+
metrics: usageMetrics(
|
|
139
|
+
entries,
|
|
140
|
+
sources.filter((source) => source.name === entries[0]!.source),
|
|
141
|
+
),
|
|
142
|
+
}))
|
|
143
|
+
.toSorted((a, b) => a.runtime.localeCompare(b.runtime) || a.model.localeCompare(b.model)),
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function aggregateUsage(
|
|
148
|
+
scope: UsageScope,
|
|
149
|
+
window: UsageWindow,
|
|
150
|
+
collections: UsageCollection[],
|
|
151
|
+
collectedAt: string,
|
|
152
|
+
): CompanionUsageSnapshot {
|
|
153
|
+
const normalized = normalizeUsageRecords(
|
|
154
|
+
scope,
|
|
155
|
+
window,
|
|
156
|
+
collections.flatMap((collection) => collection.observations),
|
|
157
|
+
);
|
|
158
|
+
const { records, unattributed } = normalized;
|
|
159
|
+
const attributed = new Set(records.map((record) => `${record.source}\0${record.repositoryId}`));
|
|
160
|
+
const sources = collections
|
|
161
|
+
.flatMap((collection) => collection.sources)
|
|
162
|
+
.map((source): UsageSource => {
|
|
163
|
+
const empty =
|
|
164
|
+
source.status === "ok" && !attributed.has(`${source.name}\0${source.repositoryId}`);
|
|
165
|
+
const status = empty ? "empty" : source.status;
|
|
166
|
+
if (!unattributed.has(source.name)) return { ...source, status };
|
|
167
|
+
const note = "Some records lack reliable repository attribution.";
|
|
168
|
+
return {
|
|
169
|
+
...source,
|
|
170
|
+
status,
|
|
171
|
+
partial: true,
|
|
172
|
+
detail: source.detail ? `${note} ${source.detail}` : note,
|
|
173
|
+
};
|
|
174
|
+
});
|
|
175
|
+
const group = usageGroup(records, sources, window);
|
|
176
|
+
return {
|
|
177
|
+
kind: "companion-usage",
|
|
178
|
+
version: 1,
|
|
179
|
+
collectedAt,
|
|
180
|
+
window,
|
|
181
|
+
companion: { id: scope.companionId },
|
|
182
|
+
repositories: scope.repositories.map((repository) => ({
|
|
183
|
+
id: repository.id,
|
|
184
|
+
kind: repository.kind,
|
|
185
|
+
label: repository.label,
|
|
186
|
+
...usageGroup(
|
|
187
|
+
records.filter((record) => record.repositoryId === repository.id),
|
|
188
|
+
sources.filter((source) => source.repositoryId === repository.id),
|
|
189
|
+
window,
|
|
190
|
+
),
|
|
191
|
+
})),
|
|
192
|
+
totals: group.metrics,
|
|
193
|
+
daily: group.daily,
|
|
194
|
+
breakdowns: group.breakdowns,
|
|
195
|
+
sources,
|
|
196
|
+
warnings: sources.some(
|
|
197
|
+
(source) => (!successful(source) && source.status !== "disabled") || source.partial,
|
|
198
|
+
)
|
|
199
|
+
? ["Local-source coverage is incomplete; known values are not a complete bill."]
|
|
200
|
+
: [],
|
|
201
|
+
};
|
|
202
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { collectCompanionUsage } from "./collect";
|
|
2
|
+
import { resolveUsageScope, type UsageScope } from "./scope";
|
|
3
|
+
import {
|
|
4
|
+
UsageError,
|
|
5
|
+
type CompanionUsageSnapshot,
|
|
6
|
+
type UsageResponse,
|
|
7
|
+
type UsageWindow,
|
|
8
|
+
} from "./types";
|
|
9
|
+
import { usageWindow } from "./window";
|
|
10
|
+
|
|
11
|
+
export interface UsageRequest {
|
|
12
|
+
days: number;
|
|
13
|
+
refresh?: boolean;
|
|
14
|
+
}
|
|
15
|
+
export interface UsageCache {
|
|
16
|
+
read(companionPath: string, request: UsageRequest): Promise<UsageResponse>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Inserts as most recent and evicts the least recently used past the limit. */
|
|
20
|
+
function remember<T>(entries: Map<string, T>, key: string, value: T, limit: number): void {
|
|
21
|
+
entries.delete(key);
|
|
22
|
+
entries.set(key, value);
|
|
23
|
+
while (entries.size > limit) entries.delete(entries.keys().next().value!);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function createUsageCache(
|
|
27
|
+
deps: {
|
|
28
|
+
scope?: (path: string) => Promise<UsageScope>;
|
|
29
|
+
collect?: (scope: UsageScope, window: UsageWindow) => Promise<CompanionUsageSnapshot>;
|
|
30
|
+
now?: () => Date;
|
|
31
|
+
limit?: number;
|
|
32
|
+
} = {},
|
|
33
|
+
): UsageCache {
|
|
34
|
+
const held = new Map<string, CompanionUsageSnapshot>();
|
|
35
|
+
/** Last good snapshot per companion and window, whatever its scope; served when scope resolution fails. */
|
|
36
|
+
const latest = new Map<string, CompanionUsageSnapshot>();
|
|
37
|
+
const inFlight = new Map<string, Promise<UsageResponse>>();
|
|
38
|
+
const limit = Math.max(1, deps.limit ?? 32);
|
|
39
|
+
return {
|
|
40
|
+
async read(companionPath, request) {
|
|
41
|
+
const window = usageWindow(request.days, deps.now?.() ?? new Date());
|
|
42
|
+
const period = JSON.stringify([companionPath, window.start, window.endExclusive]);
|
|
43
|
+
let scope: UsageScope;
|
|
44
|
+
try {
|
|
45
|
+
scope = await (deps.scope ?? resolveUsageScope)(companionPath);
|
|
46
|
+
} catch {
|
|
47
|
+
return {
|
|
48
|
+
snapshot: latest.get(period) ?? null,
|
|
49
|
+
error: { code: "COMPANION_UNRESOLVED", message: "The selected companion is unavailable" },
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
const key = JSON.stringify([
|
|
53
|
+
companionPath,
|
|
54
|
+
window.start,
|
|
55
|
+
window.endExclusive,
|
|
56
|
+
scope.fingerprint,
|
|
57
|
+
]);
|
|
58
|
+
const cached = held.get(key);
|
|
59
|
+
if (cached && !request.refresh) {
|
|
60
|
+
remember(held, key, cached, limit);
|
|
61
|
+
return { snapshot: cached, error: null };
|
|
62
|
+
}
|
|
63
|
+
const pending = inFlight.get(key);
|
|
64
|
+
if (pending) return pending;
|
|
65
|
+
const collect = Promise.resolve().then(async (): Promise<UsageResponse> => {
|
|
66
|
+
try {
|
|
67
|
+
const snapshot = await (deps.collect ?? collectCompanionUsage)(scope, window);
|
|
68
|
+
remember(held, key, snapshot, limit);
|
|
69
|
+
remember(latest, period, snapshot, limit);
|
|
70
|
+
return { snapshot, error: null };
|
|
71
|
+
} catch (error) {
|
|
72
|
+
return {
|
|
73
|
+
snapshot: cached ?? null,
|
|
74
|
+
error: {
|
|
75
|
+
code: error instanceof UsageError ? error.code : "COLLECTION_FAILED",
|
|
76
|
+
message: "Usage refresh failed.",
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
} finally {
|
|
80
|
+
inFlight.delete(key);
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
inFlight.set(key, collect);
|
|
84
|
+
return collect;
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { nonnegative } from "./records";
|
|
2
|
+
import type { UsageCost } from "./types";
|
|
3
|
+
|
|
4
|
+
/** USD per million tokens: input, output, 5m write, 1h write, read. No runtime fetch. */
|
|
5
|
+
const rates: Record<string, readonly [number, number, number, number, number]> = {
|
|
6
|
+
"claude-haiku-4-5": [1, 5, 1.25, 2, 0.1],
|
|
7
|
+
"claude-haiku-4-5-20251001": [1, 5, 1.25, 2, 0.1],
|
|
8
|
+
"claude-sonnet-4-5": [3, 15, 3.75, 6, 0.3],
|
|
9
|
+
"claude-sonnet-4-5-20250929": [3, 15, 3.75, 6, 0.3],
|
|
10
|
+
"claude-sonnet-4-6": [3, 15, 3.75, 6, 0.3],
|
|
11
|
+
"claude-opus-4-5": [5, 25, 6.25, 10, 0.5],
|
|
12
|
+
"claude-opus-4-5-20251101": [5, 25, 6.25, 10, 0.5],
|
|
13
|
+
"claude-opus-4-6": [5, 25, 6.25, 10, 0.5],
|
|
14
|
+
"claude-opus-4-6-20260205": [5, 25, 6.25, 10, 0.5],
|
|
15
|
+
"claude-opus-4-7": [5, 25, 6.25, 10, 0.5],
|
|
16
|
+
"claude-opus-4-7-20260416": [5, 25, 6.25, 10, 0.5],
|
|
17
|
+
"claude-opus-4-8": [5, 25, 6.25, 10, 0.5],
|
|
18
|
+
"claude-opus-5": [5, 25, 6.25, 10, 0.5],
|
|
19
|
+
"claude-opus-5-5": [4, 20, 5, 8, 0.2],
|
|
20
|
+
"claude-sonnet-5": [2, 10, 2.5, 4, 0.2],
|
|
21
|
+
"claude-sonnet-5-5": [2, 10, 2.5, 4, 0.1],
|
|
22
|
+
"claude-haiku-5-5": [0.1, 0.5, 0.125, 0.2, 0.01],
|
|
23
|
+
"claude-fable-5": [10, 50, 12.5, 20, 1],
|
|
24
|
+
"claude-fable-5-1": [10, 50, 12.5, 20, 0.25],
|
|
25
|
+
"claude-mythos-5": [10, 50, 12.5, 20, 1],
|
|
26
|
+
"claude-mythos-5-1": [10, 50, 12.5, 20, 0.25],
|
|
27
|
+
"claude-mythos-preview": [10, 50, 12.5, 20, 1],
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export const CLAUDE_PRICING_DETAIL =
|
|
31
|
+
"API token costs: reported costs or model-specific LiteLLM API rates (2026-11-07).";
|
|
32
|
+
|
|
33
|
+
const rateFor = (model: string) => (Object.hasOwn(rates, model) ? rates[model] : undefined);
|
|
34
|
+
|
|
35
|
+
const optionalCount = (value: unknown) => (value === undefined ? 0 : nonnegative(value));
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* ccusage auto-mode formula, not its grouped CLI output. Snapshot:
|
|
39
|
+
* https://github.com/BerriAI/litellm/blob/268bc0345c53409342a6da56a96134034040aabe/model_prices_and_context_window.json
|
|
40
|
+
* Unknown models/counts never inherit a guessed rate. Stored cost takes precedence in the adapter.
|
|
41
|
+
*/
|
|
42
|
+
export function estimateClaudeCost(
|
|
43
|
+
model: string,
|
|
44
|
+
usage: Record<string, unknown>,
|
|
45
|
+
): UsageCost | undefined {
|
|
46
|
+
const rate = rateFor(model);
|
|
47
|
+
if (!rate) return;
|
|
48
|
+
const input = nonnegative(usage.input_tokens);
|
|
49
|
+
const output = nonnegative(usage.output_tokens);
|
|
50
|
+
const read = optionalCount(usage.cache_read_input_tokens);
|
|
51
|
+
const creation = usage.cache_creation;
|
|
52
|
+
if (
|
|
53
|
+
creation !== undefined &&
|
|
54
|
+
(!creation || typeof creation !== "object" || Array.isArray(creation))
|
|
55
|
+
)
|
|
56
|
+
return;
|
|
57
|
+
const breakdown = creation as Record<string, unknown> | undefined;
|
|
58
|
+
const hour = optionalCount(breakdown?.ephemeral_1h_input_tokens);
|
|
59
|
+
const total = optionalCount(usage.cache_creation_input_tokens);
|
|
60
|
+
const five = optionalCount(breakdown ? breakdown.ephemeral_5m_input_tokens : total);
|
|
61
|
+
if (input === null || output === null || read === null || hour === null || five === null) return;
|
|
62
|
+
if (
|
|
63
|
+
usage.cache_creation_input_tokens !== undefined &&
|
|
64
|
+
(total === null || (breakdown && total !== five + hour))
|
|
65
|
+
)
|
|
66
|
+
return;
|
|
67
|
+
const amount =
|
|
68
|
+
(input * rate[0] + output * rate[1] + five * rate[2] + hour * rate[3] + read * rate[4]) /
|
|
69
|
+
1_000_000;
|
|
70
|
+
return Number.isFinite(amount) ? { amount, currency: "USD", basis: "estimated" } : undefined;
|
|
71
|
+
}
|