toolroll 0.9.133 → 0.9.135
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/CHANGELOG.md +66 -0
- package/dist/acp-agents.js +1 -1
- package/dist/acp-check-repo-schema.js +52 -0
- package/dist/acp-check.js +1 -1
- package/dist/acp-client.js +3 -3
- package/dist/acp-inspect.js +2 -1
- package/dist/acp-providers-schema.js +1 -1
- package/dist/agent-detect.js +1 -1
- package/dist/agent-fence.js +4 -4
- package/dist/agent-handoff.js +11 -0
- package/dist/agent-thread/acp-chat.js +1 -0
- package/dist/agent-thread/acp-turn.js +4 -0
- package/dist/agent-thread/chat-credential.js +1 -0
- package/dist/agent-thread/chat-home.js +1 -0
- package/dist/agent-thread/chat-spend.js +7 -0
- package/dist/agent-thread/chat-tools.js +1 -0
- package/dist/agent-thread/chat-turn.js +4 -0
- package/dist/agent-thread/custody.js +1 -1
- package/dist/agent-thread/direct-host.js +13 -8
- package/dist/agent-thread/fence.js +2 -2
- package/dist/agent-thread/gemini-chat.js +1 -0
- package/dist/agent-thread/git-workspace.js +3 -3
- package/dist/agent-thread/guards.js +1 -1
- package/dist/agent-thread/openrouter-chat.js +1 -0
- package/dist/agent-thread/providers.js +3 -3
- package/dist/agent-thread/ship.js +2 -2
- package/dist/agentconfig.js +1 -1
- package/dist/agents-live.js +2 -2
- package/dist/approval-decision.js +1 -0
- package/dist/approval-password.js +1 -1
- package/dist/approval-summary.js +1 -1
- package/dist/assignment.js +1 -1
- package/dist/attest.js +1 -1
- package/dist/batch-checks.js +2 -2
- package/dist/boot-identity.js +1 -1
- package/dist/bounded-spawn.js +2 -2
- package/dist/brief-fence.js +3 -1
- package/dist/browser/{chunk-agents-live-view.6fd2938ef96a85a4127cddb99dbc700b3201c58351d9f07dbcd8a2f7d7dfef22.js → chunk-agents-live-view.9f4367c89c6366769a567e729ac9181ccaa898bf3a168d3dc618f3cface887c7.js} +5 -5
- package/dist/browser/chunk-agents-live-view.9f4367c89c6366769a567e729ac9181ccaa898bf3a168d3dc618f3cface887c7.js.br +0 -0
- package/dist/browser/chunk-agents-live-view.9f4367c89c6366769a567e729ac9181ccaa898bf3a168d3dc618f3cface887c7.js.gz +0 -0
- package/dist/browser/chunk-bundle.ac5952c82c76e2efcdcf5a097c4fa235d6f1045dcc36d02ee921ff4be976a46a.js +2 -0
- package/dist/browser/chunk-bundle.ac5952c82c76e2efcdcf5a097c4fa235d6f1045dcc36d02ee921ff4be976a46a.js.br +0 -0
- package/dist/browser/chunk-bundle.ac5952c82c76e2efcdcf5a097c4fa235d6f1045dcc36d02ee921ff4be976a46a.js.gz +0 -0
- package/dist/browser/chunk-chat-parts.2a0b0b723508c5c48379f6a3d441f07a18c8b91ed64fd018962931c5ae43331e.js +4 -0
- package/dist/browser/chunk-chat-parts.2a0b0b723508c5c48379f6a3d441f07a18c8b91ed64fd018962931c5ae43331e.js.br +0 -0
- package/dist/browser/chunk-chat-parts.2a0b0b723508c5c48379f6a3d441f07a18c8b91ed64fd018962931c5ae43331e.js.gz +0 -0
- package/dist/browser/chunk-core.5490609e81c3a5f78da3e06b9795d71c287016ebc7fd02794b1122b474ebb07f.js +116 -0
- package/dist/browser/chunk-core.5490609e81c3a5f78da3e06b9795d71c287016ebc7fd02794b1122b474ebb07f.js.br +0 -0
- package/dist/browser/chunk-core.5490609e81c3a5f78da3e06b9795d71c287016ebc7fd02794b1122b474ebb07f.js.gz +0 -0
- package/dist/browser/{chunk-flow-view.71a0a3360292445ab70d67253bb9003163bbb7b1b03f14d1892cca83debd9b2c.js → chunk-flow-view.f5d74c7f072b739a7a0ed86ff35cafa7b8a041233372d1eeaab9eb941ddfc11e.js} +7 -7
- package/dist/browser/chunk-flow-view.f5d74c7f072b739a7a0ed86ff35cafa7b8a041233372d1eeaab9eb941ddfc11e.js.br +0 -0
- package/dist/browser/chunk-flow-view.f5d74c7f072b739a7a0ed86ff35cafa7b8a041233372d1eeaab9eb941ddfc11e.js.gz +0 -0
- package/dist/browser/chunk-flows-extra-view.01ebf93780b729363eda11ba21c764fe593bcd3e684aa833c9b86147f780fd41.js +4 -0
- package/dist/browser/chunk-flows-extra-view.01ebf93780b729363eda11ba21c764fe593bcd3e684aa833c9b86147f780fd41.js.br +0 -0
- package/dist/browser/chunk-flows-extra-view.01ebf93780b729363eda11ba21c764fe593bcd3e684aa833c9b86147f780fd41.js.gz +0 -0
- package/dist/browser/chunk-pages-bundle.e18059f0cb4fbb63e3698971d4c1830ad0945c3645235babc93010cd0b725c1d.js +6 -0
- package/dist/browser/chunk-pages-bundle.e18059f0cb4fbb63e3698971d4c1830ad0945c3645235babc93010cd0b725c1d.js.br +0 -0
- package/dist/browser/chunk-pages-bundle.e18059f0cb4fbb63e3698971d4c1830ad0945c3645235babc93010cd0b725c1d.js.gz +0 -0
- package/dist/browser/chunk-result-view.fc6a6494b316aa786807b7d17035c59defae1bfb0c03bf9c3795679b3a35dd77.js +2 -0
- package/dist/browser/chunk-result-view.fc6a6494b316aa786807b7d17035c59defae1bfb0c03bf9c3795679b3a35dd77.js.br +0 -0
- package/dist/browser/chunk-result-view.fc6a6494b316aa786807b7d17035c59defae1bfb0c03bf9c3795679b3a35dd77.js.gz +0 -0
- package/dist/browser/chunk-settings-view.6dd3a64ded7bd8c047650270918dfb455c9a514a5a40b84c7eb5f443f76fe66f.js +20 -0
- package/dist/browser/chunk-settings-view.6dd3a64ded7bd8c047650270918dfb455c9a514a5a40b84c7eb5f443f76fe66f.js.br +0 -0
- package/dist/browser/chunk-settings-view.6dd3a64ded7bd8c047650270918dfb455c9a514a5a40b84c7eb5f443f76fe66f.js.gz +0 -0
- package/dist/browser/chunk-shared.02c0b692de21a9bb80d1761aa887d8532431171945c02e663884c9f45b796753.js +3 -0
- package/dist/browser/chunk-shared.02c0b692de21a9bb80d1761aa887d8532431171945c02e663884c9f45b796753.js.br +0 -0
- package/dist/browser/chunk-shared.02c0b692de21a9bb80d1761aa887d8532431171945c02e663884c9f45b796753.js.gz +0 -0
- package/dist/browser/chunk-shared.0874336833f8101a63b169d8c2e55ca0f281e43e65d4bd6604555c791ea9dd87.js +2 -0
- package/dist/browser/chunk-shared.0874336833f8101a63b169d8c2e55ca0f281e43e65d4bd6604555c791ea9dd87.js.br +0 -0
- package/dist/browser/chunk-shared.0874336833f8101a63b169d8c2e55ca0f281e43e65d4bd6604555c791ea9dd87.js.gz +0 -0
- package/dist/browser/chunk-shared.2413dd78f32995fbca67f51ac8c21baf4727cd64f185ea739aa2a058e569b0ed.js +2 -0
- package/dist/browser/chunk-shared.2413dd78f32995fbca67f51ac8c21baf4727cd64f185ea739aa2a058e569b0ed.js.br +0 -0
- package/dist/browser/chunk-shared.2413dd78f32995fbca67f51ac8c21baf4727cd64f185ea739aa2a058e569b0ed.js.gz +0 -0
- package/dist/browser/chunk-shared.26bb0114998968cccb7bae5f6ffa8979ddecfafd8bc18bb6985760f6bcc030e6.js +5 -0
- package/dist/browser/chunk-shared.26bb0114998968cccb7bae5f6ffa8979ddecfafd8bc18bb6985760f6bcc030e6.js.br +0 -0
- package/dist/browser/chunk-shared.26bb0114998968cccb7bae5f6ffa8979ddecfafd8bc18bb6985760f6bcc030e6.js.gz +0 -0
- package/dist/browser/chunk-shared.6d0b8728b3e309886cfb6eaf596d3f20592939e521bb60bb090824f34da6b086.js +2 -0
- package/dist/browser/chunk-shared.6d0b8728b3e309886cfb6eaf596d3f20592939e521bb60bb090824f34da6b086.js.br +0 -0
- package/dist/browser/chunk-shared.6d0b8728b3e309886cfb6eaf596d3f20592939e521bb60bb090824f34da6b086.js.gz +0 -0
- package/dist/browser/chunk-shared.c3e5be1c5f441e94905a4bc2005d816d2a0b0e4108bae43e37ec274a911c6847.js +2 -0
- package/dist/browser/chunk-shared.c3e5be1c5f441e94905a4bc2005d816d2a0b0e4108bae43e37ec274a911c6847.js.br +0 -0
- package/dist/browser/chunk-shared.c3e5be1c5f441e94905a4bc2005d816d2a0b0e4108bae43e37ec274a911c6847.js.gz +0 -0
- package/dist/browser/chunk-shared.d1f25785c8c168cc75aa99c4be8ca56abfc5eafa3490f8817ff15e61cb901915.js +2 -0
- package/dist/browser/chunk-shared.d1f25785c8c168cc75aa99c4be8ca56abfc5eafa3490f8817ff15e61cb901915.js.br +0 -0
- package/dist/browser/chunk-shared.d1f25785c8c168cc75aa99c4be8ca56abfc5eafa3490f8817ff15e61cb901915.js.gz +0 -0
- package/dist/browser/chunk-shared.fd5f2699d3b0017797e5b5e1e1d92eb98818740ebf20a95364bbb7deea0c8242.js +4 -0
- package/dist/browser/chunk-shared.fd5f2699d3b0017797e5b5e1e1d92eb98818740ebf20a95364bbb7deea0c8242.js.br +0 -0
- package/dist/browser/chunk-shared.fd5f2699d3b0017797e5b5e1e1d92eb98818740ebf20a95364bbb7deea0c8242.js.gz +0 -0
- package/dist/browser/{chunk-sonner.da05d41088ec46a49ef6b86f4afa71fccd5462f1befa713ca930aa231e35349b.js → chunk-sonner.2472e1da55de10b11dc002c80a840966061e817c47793f5e216f1af6c6dbedff.js} +1 -1
- package/dist/browser/chunk-sonner.2472e1da55de10b11dc002c80a840966061e817c47793f5e216f1af6c6dbedff.js.br +0 -0
- package/dist/browser/chunk-sonner.2472e1da55de10b11dc002c80a840966061e817c47793f5e216f1af6c6dbedff.js.gz +0 -0
- package/dist/browser/chunk-task-view.bbeddc793a5e8a6d1f66b6cc5f0ce1da18414137e85c49ccd07be0e20f61ac12.js +2 -0
- package/dist/browser/chunk-task-view.bbeddc793a5e8a6d1f66b6cc5f0ce1da18414137e85c49ccd07be0e20f61ac12.js.br +0 -0
- package/dist/browser/chunk-task-view.bbeddc793a5e8a6d1f66b6cc5f0ce1da18414137e85c49ccd07be0e20f61ac12.js.gz +0 -0
- package/dist/browser/chunk-team-chat.c3255a5a1d94e39d559c07438c4690543602b1552b2c2bf57b8791d7f989141d.js +2 -0
- package/dist/browser/chunk-team-chat.c3255a5a1d94e39d559c07438c4690543602b1552b2c2bf57b8791d7f989141d.js.br +0 -0
- package/dist/browser/chunk-team-chat.c3255a5a1d94e39d559c07438c4690543602b1552b2c2bf57b8791d7f989141d.js.gz +0 -0
- package/dist/browser/manifest.json +204 -204
- package/dist/browser/{terminal.1ab49cbf9b9363f0f520b85e4125d40a302dffc10489e77b04ff1c620831eefe.js → terminal.18295f7cbf70d84b5564f3784b9630bec594fc558a7bf0303e34cde9b027eff9.js} +1 -1
- package/dist/browser/terminal.18295f7cbf70d84b5564f3784b9630bec594fc558a7bf0303e34cde9b027eff9.js.br +0 -0
- package/dist/browser/{terminal.1ab49cbf9b9363f0f520b85e4125d40a302dffc10489e77b04ff1c620831eefe.js.gz → terminal.18295f7cbf70d84b5564f3784b9630bec594fc558a7bf0303e34cde9b027eff9.js.gz} +0 -0
- package/dist/browser/workspace.3043c4a6df23ed1c0c8be3fb816fa9410a2ab99053eb54476f22a1735c03ca97.css +4 -0
- package/dist/browser/workspace.3043c4a6df23ed1c0c8be3fb816fa9410a2ab99053eb54476f22a1735c03ca97.css.br +0 -0
- package/dist/browser/workspace.3043c4a6df23ed1c0c8be3fb816fa9410a2ab99053eb54476f22a1735c03ca97.css.gz +0 -0
- package/dist/browser/{workspace.d6a38fe66b5ee0b74d8ea4b026148c285f664732511bc528c934309bbad1e5e4.js → workspace.aebb60d4e5ef4509a80cfaccf0af5f7246867ec7531a1734dd8e28c59594950e.js} +4 -4
- package/dist/browser/workspace.aebb60d4e5ef4509a80cfaccf0af5f7246867ec7531a1734dd8e28c59594950e.js.br +0 -0
- package/dist/browser/workspace.aebb60d4e5ef4509a80cfaccf0af5f7246867ec7531a1734dd8e28c59594950e.js.gz +0 -0
- package/dist/browser-open.js +1 -1
- package/dist/build-review.js +2 -2
- package/dist/builder-revision.js +4 -0
- package/dist/builder.js +31 -17
- package/dist/canvas-capture.js +2 -2
- package/dist/canvas-freshness.js +1 -1
- package/dist/central-recovery-stage.js +1 -1
- package/dist/chat-actions.js +11 -7
- package/dist/chat-channel.js +1 -1
- package/dist/chat-decide.js +8 -4
- package/dist/chat-review.js +1 -1
- package/dist/chat-terms.js +2 -2
- package/dist/check-levels.js +1 -1
- package/dist/cli-help.js +142 -13
- package/dist/cli.js +4 -3
- package/dist/companion/bonjour.js +1 -1
- package/dist/companion/daemon.js +1 -1
- package/dist/companion/passkey-gate.js +1 -1
- package/dist/companion/reads.js +1 -1
- package/dist/companion/store.js +1 -1
- package/dist/companion/webauthn.js +1 -1
- package/dist/companion/work.js +1 -1
- package/dist/container-state.js +2 -2
- package/dist/containment.js +2 -2
- package/dist/contracts/chat-actions.js +1 -1
- package/dist/contracts/console-api.js +1 -1
- package/dist/contracts/engine-api.js +1 -1
- package/dist/contracts/lead-tools.js +1 -1
- package/dist/contracts/project-memory.js +1 -1
- package/dist/contracts/provider.js +1 -1
- package/dist/controller-supervisor.js +2 -2
- package/dist/converse.js +1 -1
- package/dist/credential-broker.js +1 -1
- package/dist/decision.js +1 -1
- package/dist/demo.js +2 -2
- package/dist/dispatch.js +2 -2
- package/dist/dispose.js +1 -1
- package/dist/easy-start.js +2 -2
- package/dist/egress.js +1 -1
- package/dist/engine-chat.js +1 -1
- package/dist/engine-handoff.js +1 -1
- package/dist/engine-reads.js +3 -3
- package/dist/evals.js +2 -2
- package/dist/every-agent-schema.js +105 -0
- package/dist/evidence-pack.js +1 -1
- package/dist/evidence.js +1 -1
- package/dist/exec.js +5 -4
- package/dist/fallback.js +1 -1
- package/dist/fast-owner-schema.js +33 -0
- package/dist/fast-start.js +1 -1
- package/dist/flow-unattended.js +2 -2
- package/dist/git-identity.js +2 -2
- package/dist/github-import.js +1 -1
- package/dist/github-read.js +1 -1
- package/dist/handoff-relay.js +2 -0
- package/dist/install-mode.js +2 -3
- package/dist/invoke.js +9 -7
- package/dist/keys.js +1 -1
- package/dist/laptop-background.js +1 -1
- package/dist/lead-capabilities.js +1 -1
- package/dist/lead-cli.js +2 -2
- package/dist/lead-contract.js +1 -1
- package/dist/lead-debrief.js +7 -0
- package/dist/lead-doors.js +1 -1
- package/dist/lead-tools.js +5 -5
- package/dist/lead.js +2 -2
- package/dist/live-backup-change.js +2 -2
- package/dist/live-backup.js +2 -2
- package/dist/live-records.js +3 -3
- package/dist/live-terminal.js +4 -4
- package/dist/local-checks.js +1 -1
- package/dist/local-landing.js +22 -3
- package/dist/local-owner-acts.js +2 -2
- package/dist/local-owner.js +1 -1
- package/dist/machine-identity.js +1 -1
- package/dist/memory-pass.js +3 -3
- package/dist/model-catalog.js +8 -5
- package/dist/model-choices.js +3 -3
- package/dist/model-routing.js +1 -1
- package/dist/models-cli.js +2 -2
- package/dist/names.js +1 -1
- package/dist/needs-you.js +1 -1
- package/dist/onboard.js +1 -1
- package/dist/openrouter-key.js +2 -0
- package/dist/operate-commands.js +1 -1
- package/dist/operate-remote-arguments.js +1 -1
- package/dist/operate-remote.js +1 -1
- package/dist/operate.js +46 -19
- package/dist/orphan-sweep.js +1 -1
- package/dist/owner-mode.js +4 -0
- package/dist/panels.js +6 -0
- package/dist/peek-cli.js +2 -2
- package/dist/phase-routing.js +1 -1
- package/dist/pi-build.js +4 -0
- package/dist/pi-rpc.js +10 -0
- package/dist/pi-tools-extension.js +4 -0
- package/dist/plan-login.js +2 -2
- package/dist/plane-review.js +1 -1
- package/dist/planner-source.js +2 -2
- package/dist/planner.js +2 -2
- package/dist/plugin-bundle-source.js +1 -0
- package/dist/plugin-bundles-schema.js +43 -0
- package/dist/policy.js +1 -1
- package/dist/pre-run-phase.js +2 -0
- package/dist/presence-hold.js +1 -1
- package/dist/process-liveness.js +1 -1
- package/dist/process-tree.js +1 -1
- package/dist/project-knowledge.js +2 -2
- package/dist/project-learning.js +6 -5
- package/dist/project-memory.js +1 -1
- package/dist/project-skills.js +1 -1
- package/dist/project-tools.js +3 -3
- package/dist/prompt.js +1 -1
- package/dist/proposal.js +1 -1
- package/dist/protected-storage.js +2 -2
- package/dist/provider-auth.js +1 -1
- package/dist/provider-connection.js +2 -2
- package/dist/provider-home.js +1 -1
- package/dist/provider-limits.js +1 -1
- package/dist/provider.js +2 -2
- package/dist/public-access.js +1 -1
- package/dist/pull-request-flow.js +2 -2
- package/dist/read-executor.js +1 -1
- package/dist/release-adapters.js +2 -2
- package/dist/release-carry.js +3 -3
- package/dist/release-resume.js +2 -2
- package/dist/release-start.js +1 -0
- package/dist/reported-usage.js +1 -1
- package/dist/repository-context.js +1 -1
- package/dist/result-follow-ups.js +2 -2
- package/dist/result-projection.js +1 -1
- package/dist/review-switch.js +1 -1
- package/dist/route-change.js +25 -3
- package/dist/run-closeout.js +2 -2
- package/dist/runner.js +2 -2
- package/dist/sandbox-launch.js +2 -2
- package/dist/sandbox-runtime.js +1 -1
- package/dist/scope.js +1 -1
- package/dist/scout-browser.js +1 -1
- package/dist/scout.js +2 -2
- package/dist/serve.js +3 -3
- package/dist/server/chat-projection.js +1 -1
- package/dist/server/chat.js +3 -3
- package/dist/server/direct-chat.js +1 -1
- package/dist/server/engine-api.js +1 -1
- package/dist/server/handoff.js +1 -0
- package/dist/server/http.js +1 -1
- package/dist/server/live.js +1 -1
- package/dist/server/merge-ready-view.js +1 -1
- package/dist/server/one-time-secret.js +1 -1
- package/dist/server/panels.js +1 -0
- package/dist/server/people-tokens.js +1 -1
- package/dist/server/route-table.js +1 -1
- package/dist/server/runtime.js +1 -1
- package/dist/server/send-back-build.js +1 -1
- package/dist/server/settings-phone.js +1 -1
- package/dist/server/settings-section-table.js +1 -1
- package/dist/server/settings-sections.js +1 -1
- package/dist/server/settings.js +3 -2
- package/dist/server/task-overview.js +1 -0
- package/dist/server/task-view-data.js +3 -3
- package/dist/server/task-views.js +1 -1
- package/dist/server/tasks.js +6 -6
- package/dist/server/terminals.js +1 -1
- package/dist/settings-data.js +1 -1
- package/dist/settings-proofs.js +1 -1
- package/dist/setup-guide.js +1 -1
- package/dist/shared-deps.js +4 -4
- package/dist/sign-in-page.js +2 -2
- package/dist/skill-library.js +13 -22
- package/dist/skills-manifest.js +1 -1
- package/dist/spend-report.js +2 -1
- package/dist/spend.js +6 -4
- package/dist/ssr-workspace.js +89 -89
- package/dist/staged-runtimes.js +1 -1
- package/dist/status-probe.js +2 -2
- package/dist/stop-proof.js +2 -2
- package/dist/storage-sweep-child.js +2 -2
- package/dist/storage-sweep-process.js +1 -1
- package/dist/storage.js +2 -2
- package/dist/store-baseline.js +17 -79
- package/dist/store.js +24 -19
- package/dist/structured-json.js +1 -0
- package/dist/structured-output.js +1 -1
- package/dist/subscription-chat.js +16 -4
- package/dist/subscription-usage.js +3 -4
- package/dist/surface.js +1 -1
- package/dist/task-outcome-cli.js +5 -2
- package/dist/task-overview.js +1 -0
- package/dist/task-review-brief.js +1 -1
- package/dist/task-status.js +1 -1
- package/dist/teardown-git.js +4 -4
- package/dist/test-temp.js +1 -1
- package/dist/text-limits.js +1 -1
- package/dist/tool-broker.js +1 -1
- package/dist/toolroll-update.js +3 -3
- package/dist/trusted-path.js +1 -1
- package/dist/tui/darwin-arm64/toolroll-tui +0 -0
- package/dist/tui/darwin-x64/toolroll-tui +0 -0
- package/dist/tui/linux-arm64/toolroll-tui +0 -0
- package/dist/tui/linux-x64/toolroll-tui +0 -0
- package/dist/tui-contract.js +1 -1
- package/dist/tui-launch.js +2 -1
- package/dist/verification-evidence.js +1 -1
- package/dist/welcome-facts.js +1 -1
- package/dist/work-index.js +13 -5
- package/package.json +2 -1
- package/dist/browser/chunk-agents-live-view.6fd2938ef96a85a4127cddb99dbc700b3201c58351d9f07dbcd8a2f7d7dfef22.js.br +0 -0
- package/dist/browser/chunk-agents-live-view.6fd2938ef96a85a4127cddb99dbc700b3201c58351d9f07dbcd8a2f7d7dfef22.js.gz +0 -0
- package/dist/browser/chunk-bundle.77cfd5ccd851cf1fb8597d1d0eb12fc30913417f13b699d5b8ac61a4116274ef.js +0 -2
- package/dist/browser/chunk-bundle.77cfd5ccd851cf1fb8597d1d0eb12fc30913417f13b699d5b8ac61a4116274ef.js.br +0 -0
- package/dist/browser/chunk-bundle.77cfd5ccd851cf1fb8597d1d0eb12fc30913417f13b699d5b8ac61a4116274ef.js.gz +0 -0
- package/dist/browser/chunk-chat-parts.0e3997ddbeed8305b18353060e93f2a330d95ccb23b960f182dee211d205bb13.js +0 -4
- package/dist/browser/chunk-chat-parts.0e3997ddbeed8305b18353060e93f2a330d95ccb23b960f182dee211d205bb13.js.br +0 -0
- package/dist/browser/chunk-chat-parts.0e3997ddbeed8305b18353060e93f2a330d95ccb23b960f182dee211d205bb13.js.gz +0 -0
- package/dist/browser/chunk-core.23e919124df20f363902dc6e256d2408e103af285ebffbf0059fad7369c6ee8f.js +0 -116
- package/dist/browser/chunk-core.23e919124df20f363902dc6e256d2408e103af285ebffbf0059fad7369c6ee8f.js.br +0 -0
- package/dist/browser/chunk-core.23e919124df20f363902dc6e256d2408e103af285ebffbf0059fad7369c6ee8f.js.gz +0 -0
- package/dist/browser/chunk-flow-view.71a0a3360292445ab70d67253bb9003163bbb7b1b03f14d1892cca83debd9b2c.js.br +0 -0
- package/dist/browser/chunk-flow-view.71a0a3360292445ab70d67253bb9003163bbb7b1b03f14d1892cca83debd9b2c.js.gz +0 -0
- package/dist/browser/chunk-flows-extra-view.ebf20d864bea14592b61ce628afc066997e1f0a566abbfe6fc91f4db47245696.js +0 -4
- package/dist/browser/chunk-flows-extra-view.ebf20d864bea14592b61ce628afc066997e1f0a566abbfe6fc91f4db47245696.js.br +0 -0
- package/dist/browser/chunk-flows-extra-view.ebf20d864bea14592b61ce628afc066997e1f0a566abbfe6fc91f4db47245696.js.gz +0 -0
- package/dist/browser/chunk-pages-bundle.2fbb3d6de09f521a8ded75bd48b567d60bbfde351cae3492179714d76fc91ee5.js +0 -6
- package/dist/browser/chunk-pages-bundle.2fbb3d6de09f521a8ded75bd48b567d60bbfde351cae3492179714d76fc91ee5.js.br +0 -0
- package/dist/browser/chunk-pages-bundle.2fbb3d6de09f521a8ded75bd48b567d60bbfde351cae3492179714d76fc91ee5.js.gz +0 -0
- package/dist/browser/chunk-result-view.7527d4ed9c70c023b63821c87f8db00c374fddd8674f984cc7c03fae050e6ff0.js +0 -2
- package/dist/browser/chunk-result-view.7527d4ed9c70c023b63821c87f8db00c374fddd8674f984cc7c03fae050e6ff0.js.br +0 -0
- package/dist/browser/chunk-result-view.7527d4ed9c70c023b63821c87f8db00c374fddd8674f984cc7c03fae050e6ff0.js.gz +0 -0
- package/dist/browser/chunk-settings-view.129efb77f2d459e2254d17ab338dac474d14b86383fe024798dc61b9460d169c.js +0 -20
- package/dist/browser/chunk-settings-view.129efb77f2d459e2254d17ab338dac474d14b86383fe024798dc61b9460d169c.js.br +0 -0
- package/dist/browser/chunk-settings-view.129efb77f2d459e2254d17ab338dac474d14b86383fe024798dc61b9460d169c.js.gz +0 -0
- package/dist/browser/chunk-shared.01f5db9cab3e903447bac5a6484cbae518232a074542c5128a0ce8cac9fe5e7d.js +0 -3
- package/dist/browser/chunk-shared.01f5db9cab3e903447bac5a6484cbae518232a074542c5128a0ce8cac9fe5e7d.js.br +0 -0
- package/dist/browser/chunk-shared.01f5db9cab3e903447bac5a6484cbae518232a074542c5128a0ce8cac9fe5e7d.js.gz +0 -0
- package/dist/browser/chunk-shared.1cf4e4820f8c03a04d548d8b21b6169eda3354229b4feccdeb95534b3cc2ed09.js +0 -2
- package/dist/browser/chunk-shared.1cf4e4820f8c03a04d548d8b21b6169eda3354229b4feccdeb95534b3cc2ed09.js.br +0 -0
- package/dist/browser/chunk-shared.1cf4e4820f8c03a04d548d8b21b6169eda3354229b4feccdeb95534b3cc2ed09.js.gz +0 -0
- package/dist/browser/chunk-shared.408770b5e547bce6c67ad743638b8ef16381b092d71fc1a2b2b801cad9bd900f.js +0 -5
- package/dist/browser/chunk-shared.408770b5e547bce6c67ad743638b8ef16381b092d71fc1a2b2b801cad9bd900f.js.br +0 -0
- package/dist/browser/chunk-shared.408770b5e547bce6c67ad743638b8ef16381b092d71fc1a2b2b801cad9bd900f.js.gz +0 -0
- package/dist/browser/chunk-shared.47c9cc79ee85c5d6ebb9759b9d7f261ddd7aee78c7f70f2bc559d5b97444936d.js +0 -2
- package/dist/browser/chunk-shared.47c9cc79ee85c5d6ebb9759b9d7f261ddd7aee78c7f70f2bc559d5b97444936d.js.br +0 -0
- package/dist/browser/chunk-shared.47c9cc79ee85c5d6ebb9759b9d7f261ddd7aee78c7f70f2bc559d5b97444936d.js.gz +0 -0
- package/dist/browser/chunk-shared.60b718ab56ab520275f68f0378efa38941dc2d739c1284f842a19e6a25456e7d.js +0 -2
- package/dist/browser/chunk-shared.60b718ab56ab520275f68f0378efa38941dc2d739c1284f842a19e6a25456e7d.js.br +0 -0
- package/dist/browser/chunk-shared.60b718ab56ab520275f68f0378efa38941dc2d739c1284f842a19e6a25456e7d.js.gz +0 -0
- package/dist/browser/chunk-shared.9974523cbe568c3669da1b1a266aa7de741e2edcce3e4a943e73242c61324004.js +0 -2
- package/dist/browser/chunk-shared.9974523cbe568c3669da1b1a266aa7de741e2edcce3e4a943e73242c61324004.js.br +0 -0
- package/dist/browser/chunk-shared.9974523cbe568c3669da1b1a266aa7de741e2edcce3e4a943e73242c61324004.js.gz +0 -0
- package/dist/browser/chunk-shared.b536969256589ccff71a29b37eff95fccfd5a8f4fa4138ff503cb0e8fb10b4d0.js +0 -2
- package/dist/browser/chunk-shared.b536969256589ccff71a29b37eff95fccfd5a8f4fa4138ff503cb0e8fb10b4d0.js.br +0 -0
- package/dist/browser/chunk-shared.b536969256589ccff71a29b37eff95fccfd5a8f4fa4138ff503cb0e8fb10b4d0.js.gz +0 -0
- package/dist/browser/chunk-shared.cbc3fd4e985ceccf27c731d77030830edbf96dd0197424584ebb202eb6993ebd.js +0 -4
- package/dist/browser/chunk-shared.cbc3fd4e985ceccf27c731d77030830edbf96dd0197424584ebb202eb6993ebd.js.br +0 -0
- package/dist/browser/chunk-shared.cbc3fd4e985ceccf27c731d77030830edbf96dd0197424584ebb202eb6993ebd.js.gz +0 -0
- package/dist/browser/chunk-sonner.da05d41088ec46a49ef6b86f4afa71fccd5462f1befa713ca930aa231e35349b.js.br +0 -0
- package/dist/browser/chunk-sonner.da05d41088ec46a49ef6b86f4afa71fccd5462f1befa713ca930aa231e35349b.js.gz +0 -0
- package/dist/browser/chunk-task-view.9b9f418a71547aeea43a8acb26e8d48d486463b71b940eb72f3856038e27fa90.js +0 -2
- package/dist/browser/chunk-task-view.9b9f418a71547aeea43a8acb26e8d48d486463b71b940eb72f3856038e27fa90.js.br +0 -0
- package/dist/browser/chunk-task-view.9b9f418a71547aeea43a8acb26e8d48d486463b71b940eb72f3856038e27fa90.js.gz +0 -0
- package/dist/browser/chunk-team-chat.2be52f36796d5cd7ca8ea47a2aeb68c550625150ccc4186805bdecd87747138c.js +0 -2
- package/dist/browser/chunk-team-chat.2be52f36796d5cd7ca8ea47a2aeb68c550625150ccc4186805bdecd87747138c.js.br +0 -0
- package/dist/browser/chunk-team-chat.2be52f36796d5cd7ca8ea47a2aeb68c550625150ccc4186805bdecd87747138c.js.gz +0 -0
- package/dist/browser/terminal.1ab49cbf9b9363f0f520b85e4125d40a302dffc10489e77b04ff1c620831eefe.js.br +0 -0
- package/dist/browser/workspace.d6a38fe66b5ee0b74d8ea4b026148c285f664732511bc528c934309bbad1e5e4.js.br +0 -0
- package/dist/browser/workspace.d6a38fe66b5ee0b74d8ea4b026148c285f664732511bc528c934309bbad1e5e4.js.gz +0 -0
- package/dist/browser/workspace.d818fa094b8793160991ca784f4897c6d1862c02fbcbeebae637d8b855ab03d5.css +0 -4
- package/dist/browser/workspace.d818fa094b8793160991ca784f4897c6d1862c02fbcbeebae637d8b855ab03d5.css.br +0 -0
- package/dist/browser/workspace.d818fa094b8793160991ca784f4897c6d1862c02fbcbeebae637d8b855ab03d5.css.gz +0 -0
package/dist/skill-library.js
CHANGED
|
@@ -1,24 +1,15 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{unreachableWhy}from"./unreachable.js";import{scanForSecrets}from"./evidence.js";import{learningSha}from"./project-learning.js";import{PROJECT_SKILLS_GUIDANCE,PROJECT_SKILLS_READ,validateSkill}from"./project-skills.js";import{savedSkillPackageSchema}from"./contracts/project-skills.js";import{localSyncStatus,syncEnabledLocalTools}from"./skill-local-sync.js";export const LIBRARY_LIMITS=Object.freeze({maxSkills:200,maxBundleBytes:24*1024*1024,maxBundleFiles:2500,dailySweepMs:1440*60*1e3,maxFetchConcurrency:8});function packageBySha(store,sha){const row=store.handle.prepare("SELECT payload FROM skill_package WHERE sha=?").get(sha);if(!row||typeof row.payload!="string"||learningSha(row.payload)!==sha)throw Error("Saved library skill could not be verified.");const parsed=savedSkillPackageSchema.safeParse(JSON.parse(row.payload));if(!parsed.success)throw Error("Saved library skill could not be verified.");return{...parsed.data,sha}}function parseLibrarySelection(payload,sha){if(typeof payload!="string"||learningSha(payload)!==sha)throw Error("Saved skill library selection could not be verified.");const raw=JSON.parse(payload);if(raw===null||typeof raw!="object"||Array.isArray(raw))throw Error("Saved skill library selection could not be verified.");const out={};for(const[name,entry]of Object.entries(raw)){if(entry===null||typeof entry!="object"||Array.isArray(entry))throw Error("Saved skill library selection could not be verified.");const obj=entry;if(typeof obj.sha!="string"||typeof obj.enabled!="boolean")throw Error("Saved skill library selection could not be verified.");out[name]={sha:obj.sha,enabled:obj.enabled,...typeof obj.sourceId=="string"||obj.sourceId===null?{sourceId:obj.sourceId}:{}}}return out}export function currentLibrary(store){const row=store.handle.prepare("SELECT revision, payload, sha FROM skill_library_change ORDER BY revision DESC LIMIT 1").get();return row?{revision:Number(row.revision),selection:parseLibrarySelection(row.payload,row.sha)}:{revision:0,selection:{}}}export function projectSkillOptOuts(store,repo){const rows=store.handle.prepare("SELECT skill_name FROM skill_project_opt_out WHERE repo=? ORDER BY skill_name").all(repo);let all=!1;const names=new Set;for(const row of rows){const name=String(row.skill_name);name==="*"?all=!0:names.add(name)}return{all,names}}export function enabledLibrarySkills(store,repo){const{revision,selection}=currentLibrary(store),optOut=repo?projectSkillOptOuts(store,repo):{all:!1,names:new Set};if(optOut.all)return{revision,packages:[]};const packages=[];for(const[name,choice]of Object.entries(selection))!choice.enabled||optOut.names.has(name)||packages.push(packageBySha(store,choice.sha));return packages.sort((a,b)=>a.name.localeCompare(b.name)),{revision,packages}}export function mergeProjectAndLibrarySkills(store,repo,projectSelection){const{revision:libraryRevision,packages:globalPackages}=enabledLibrarySkills(store,repo),byName=new Map;for(const pkg of globalPackages)byName.set(pkg.name,pkg);for(const[name,choice]of Object.entries(projectSelection))choice.enabled?byName.set(name,packageBySha(store,choice.sha)):byName.delete(name);const packages=[...byName.values()].sort((a,b)=>a.name.localeCompare(b.name));return{libraryRevision,packages}}export function formatSkillsBrief(catalog,intro="Project skills supplied for this run. "){return catalog.length===0?"":`
|
|
1
|
+
import{bundleMetadata,resolvePluginSkillRoots,pluginSkillLocations,pluginSkillPathAllowed,fetchLocalSkillBundle,ignoredPluginPath,localPluginRoot,pluginManifestPath,readPluginMetadata,safeBundlePath}from"./plugin-bundle-source.js";import{createHash}from"node:crypto";import{unreachableWhy}from"./unreachable.js";import{scanForSecrets}from"./evidence.js";import{learningSha}from"./project-learning.js";import{PROJECT_SKILLS_GUIDANCE,PROJECT_SKILLS_READ,validateSkill}from"./project-skills.js";import{savedSkillPackageSchema}from"./contracts/project-skills.js";import{localSyncStatus,syncEnabledLocalTools}from"./skill-local-sync.js";export const LIBRARY_LIMITS=Object.freeze({maxSkills:200,maxBundleBytes:24*1024*1024,maxBundleFiles:2500,dailySweepMs:1440*60*1e3,maxFetchConcurrency:8});function packageBySha(store,sha){const row=store.handle.prepare("SELECT payload FROM skill_package WHERE sha=?").get(sha);if(!row||typeof row.payload!="string"||learningSha(row.payload)!==sha)throw Error("Saved library skill could not be verified.");const parsed=savedSkillPackageSchema.safeParse(JSON.parse(row.payload));if(!parsed.success)throw Error("Saved library skill could not be verified.");return{...parsed.data,sha}}function parseLibrarySelection(payload,sha){if(typeof payload!="string"||learningSha(payload)!==sha)throw Error("Saved skill library selection could not be verified.");const raw=JSON.parse(payload);if(raw===null||typeof raw!="object"||Array.isArray(raw))throw Error("Saved skill library selection could not be verified.");const out={};for(const[name,entry]of Object.entries(raw)){if(entry===null||typeof entry!="object"||Array.isArray(entry))throw Error("Saved skill library selection could not be verified.");const obj=entry;if(typeof obj.sha!="string"||typeof obj.enabled!="boolean")throw Error("Saved skill library selection could not be verified.");out[name]={sha:obj.sha,enabled:obj.enabled,...typeof obj.sourceId=="string"||obj.sourceId===null?{sourceId:obj.sourceId}:{}}}return out}export function currentLibrary(store){const row=store.handle.prepare("SELECT revision, payload, sha FROM skill_library_change ORDER BY revision DESC LIMIT 1").get();return row?{revision:Number(row.revision),selection:parseLibrarySelection(row.payload,row.sha)}:{revision:0,selection:{}}}export function projectSkillOptOuts(store,repo){const rows=store.handle.prepare("SELECT skill_name FROM skill_project_opt_out WHERE repo=? ORDER BY skill_name").all(repo);let all=!1;const names=new Set;for(const row of rows){const name=String(row.skill_name);name==="*"?all=!0:names.add(name)}return{all,names}}export function enabledLibrarySkills(store,repo){const{revision,selection}=currentLibrary(store),optOut=repo?projectSkillOptOuts(store,repo):{all:!1,names:new Set};if(optOut.all)return{revision,packages:[]};const packages=[];for(const[name,choice]of Object.entries(selection))!choice.enabled||optOut.names.has(name)||packages.push(packageBySha(store,choice.sha));return packages.sort((a,b)=>a.name.localeCompare(b.name)),{revision,packages}}export function mergeProjectAndLibrarySkills(store,repo,projectSelection){const{revision:libraryRevision,packages:globalPackages}=enabledLibrarySkills(store,repo),byName=new Map;for(const pkg of globalPackages)byName.set(pkg.name,pkg);for(const[name,choice]of Object.entries(projectSelection))choice.enabled?byName.set(name,packageBySha(store,choice.sha)):byName.delete(name);const packages=[...byName.values()].sort((a,b)=>a.name.localeCompare(b.name));return{libraryRevision,packages}}export function formatSkillsBrief(catalog,intro="Project skills supplied for this run. "){return catalog.length===0?"":`
|
|
2
2
|
${intro}${PROJECT_SKILLS_GUIDANCE}${PROJECT_SKILLS_READ}${JSON.stringify(catalog)}
|
|
3
|
-
`}function rowToBundle(row){let skillNames=[];try{const parsed=JSON.parse(String(row.skill_names_json??"[]"));Array.isArray(parsed)&&(skillNames=parsed.map(String))}catch{skillNames=[]}return{id:String(row.id),repoUrl:String(row.repo_url),owner:String(row.owner),repoName:String(row.repo_name),branch:String(row.branch),subpath:String(row.subpath??""),pinnedCommit:String(row.pinned_commit),previousCommit:typeof row.previous_commit=="string"?row.previous_commit:null,previousRevision:typeof row.previous_revision=="number"?row.previous_revision:null,skillNames,autoUpdate:Number(row.auto_update)===1,lastCheckedAt:typeof row.last_checked_at=="string"?row.last_checked_at:null,lastUpdatedAt:typeof row.last_updated_at=="string"?row.last_updated_at:null,heldCommit:typeof row.held_commit=="string"?row.held_commit:null,heldReason:typeof row.held_reason=="string"?row.held_reason:null,heldAt:typeof row.held_at=="string"?row.held_at:null,actor:String(row.actor),createdAt:String(row.created_at)}}export function listSkillBundles(store){return store.handle.prepare("SELECT * FROM skill_bundle ORDER BY id").all().map(row=>rowToBundle(row))}function writeLibraryRevision(store,selection,actor,source,now){const cur=currentLibrary(store);if(Object.values(selection).filter(c=>c.enabled).length>LIBRARY_LIMITS.maxSkills)throw Error(`Enable up to ${LIBRARY_LIMITS.maxSkills} skills in the global library.`);const payload=JSON.stringify(selection),nextRevision=cur.revision+1;return store.handle.prepare("INSERT INTO skill_library_change (revision, actor, at, payload, sha, source) VALUES (?,?,?,?,?,?)").run(nextRevision,actor,now.toISOString(),payload,learningSha(payload),source),nextRevision}function storeSkillPackage(store,pkg,actor,now){const payload=JSON.stringify(pkg),sha=learningSha(payload);return store.handle.prepare("INSERT OR IGNORE INTO skill_package VALUES (?,?)").run(sha,payload),store.handle.prepare("INSERT OR IGNORE INTO skill_owner VALUES (?,?,?)").run(sha,actor,now.toISOString()),{...pkg,sha}}export function skillLibraryView(store,options={}){const{revision,selection}=currentLibrary(store),skills=[...new Set(Object.values(selection).map(c=>c.sha))].map(sha=>packageBySha(store,sha)).sort((a,b)=>a.name.localeCompare(b.name)),bundles=listSkillBundles(store),localSync=localSyncStatus(store,options),history=store.handle.prepare("SELECT revision, actor, at, payload, sha, source FROM skill_library_change ORDER BY revision DESC LIMIT 20").all().map(row=>{const sel=parseLibrarySelection(row.payload,row.sha);return{revision:Number(row.revision),actor:String(row.actor),at:String(row.at),source:String(row.source),enabledCount:Object.values(sel).filter(c=>c.enabled).length}}),optOut=options.repo?projectSkillOptOuts(store,options.repo):null;return{revision,selection,skills,bundles,localSync,history,projectOptOut:optOut===null?null:{all:optOut.all,names:[...optOut.names].sort()}}}export function importLibrarySkill(store,args,now=new Date){if(!store.schemaCurrent())throw Error("Skill library needs the current database version.");const validated=validateSkill(args.files,args.source),result=store.transact(()=>{const saved=storeSkillPackage(store,validated,args.actor,now),next={...currentLibrary(store).selection,[saved.name]:{sha:saved.sha,enabled:args.enable!==!1,sourceId:null}},revision=writeLibraryRevision(store,next,args.actor,"manual",now);return{skill:saved,revision}}),enabled=enabledLibrarySkills(store).packages,localSync=syncEnabledLocalTools(store,{actor:args.actor,skills:enabled,libraryRevision:result.revision,...args.home===void 0?{}:{home:args.home},...args.env===void 0?{}:{env:args.env}},now);return{...result,localSync}}export function changeLibrarySkill(store,args,now=new Date){if(!store.schemaCurrent())throw Error("Skill library needs the current database version.");const nextRevision=store.transact(()=>{const cur=currentLibrary(store);if(cur.revision!==args.revision)throw Error("Skill library changed in another window. Reload and try again.");let next={...cur.selection};if(args.action==="restore"){if(!Number.isSafeInteger(args.restore)||(args.restore??0)<1)throw Error("Choose a valid library revision.");const row=store.handle.prepare("SELECT payload, sha FROM skill_library_change WHERE revision=?").get(args.restore);if(!row)throw Error("That library revision is unavailable.");next=parseLibrarySelection(row.payload,row.sha);for(const choice of Object.values(next))packageBySha(store,choice.sha);return writeLibraryRevision(store,next,args.actor,"rollback",now)}const name=args.name??(args.sha?packageBySha(store,args.sha).name:"");if(!name)throw Error("Choose a skill to update.");if(args.action==="remove")delete next[name];else{const sha=args.sha||next[name]?.sha;if(!sha)throw Error("Choose a saved skill version.");const pkg=packageBySha(store,sha);next[pkg.name]={sha:pkg.sha,enabled:args.action==="enable",sourceId:next[pkg.name]?.sourceId??null}}return writeLibraryRevision(store,next,args.actor,"manual",now)}),enabled=enabledLibrarySkills(store).packages,localSync=syncEnabledLocalTools(store,{actor:args.actor,skills:enabled,libraryRevision:nextRevision,...args.home===void 0?{}:{home:args.home},...args.env===void 0?{}:{env:args.env}},now);return{revision:nextRevision,localSync}}export function setProjectSkillOptOut(store,args,now=new Date){if(!store.schemaCurrent())throw Error("Skill library needs the current database version.");const skillName=args.skillName.trim();if(skillName!=="*"&&!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(skillName))throw Error("Choose a valid skill name or '*' for the whole library.");store.transact(()=>{args.optOut?store.handle.prepare(`INSERT INTO skill_project_opt_out (repo, skill_name, actor, at) VALUES (?,?,?,?)
|
|
4
|
-
ON CONFLICT(repo, skill_name) DO UPDATE SET actor=excluded.actor, at=excluded.at`).run(args.repo,skillName,args.actor,now.toISOString()):store.handle.prepare("DELETE FROM skill_project_opt_out WHERE repo=? AND skill_name=?").run(args.repo,skillName)})}export function parseGithubBundleUrl(rawUrl){let u;try{u=new URL(rawUrl.trim())}catch{throw Error("Enter a public github.com repository URL (for example https://github.com/owner/repo).")}if(u.protocol!=="https:"||u.hostname!=="github.com"||u.port||u.username||u.password||u.search||u.hash)throw Error("Use a public https://github.com repository URL with no query parameters or credentials.");const parts=u.pathname.replace(/\.git$/i,"").split("/").filter(Boolean);if(parts.length<2||parts.some(p=>!/^[a-zA-Z0-9_.-]+$/.test(p)||p==="."||p===".."))throw Error("Use https://github.com/owner/repo or https://github.com/owner/repo/tree/branch[/subfolder].");const[owner,repoName,kind,ref,...rest]=parts;if(kind!==void 0&&(kind!=="tree"||!ref))throw Error("Use https://github.com/owner/repo or https://github.com/owner/repo/tree/branch[/subfolder].");const subpath=rest.join("/"),id=subpath?`${owner}/${repoName}/${subpath}`:`${owner}/${repoName}`,repoUrl=subpath?`https://github.com/${owner}/${repoName}/tree/${ref}/${subpath}`:`https://github.com/${owner}/${repoName}`;return{id,repoUrl,owner,repoName,ref:ref??null,subpath}}async function githubJson(owner,repoName,path,fetcher,budget){let response;try{response=await fetcher(`https://api.github.com/repos/${owner}/${repoName}${path}`,{redirect:"error",signal:AbortSignal.timeout(2e4),headers:{Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"}})}catch(error){throw Error(`Couldn't reach GitHub: ${unreachableWhy(error,20)}.`)}if(!response.ok)throw Error(`GitHub returned ${response.status} for ${owner}/${repoName}${path.split("?")[0]}.`);const text=await response.text();if(budget.remaining-=Buffer.byteLength(text),budget.remaining<0)throw Error("GitHub bundle response exceeded the 24 MB size limit.");return JSON.parse(text)}export async function fetchGithubSkillBundle(url,fetcher=fetch,explicitCommit){const parsed=parseGithubBundleUrl(url),budget={remaining:LIBRARY_LIMITS.maxBundleBytes};let branch=parsed.ref??"";if(!branch){const repoInfo=await githubJson(parsed.owner,parsed.repoName,"",fetcher,budget);branch=typeof repoInfo.default_branch=="string"&&repoInfo.default_branch.trim()?repoInfo.default_branch.trim():"main"}let commit;if(explicitCommit!==void 0){if(!/^[0-9a-f]{40}$/.test(explicitCommit))throw Error("Pinned commit must be a 40-character SHA.");commit=explicitCommit}else{const commitObj=await githubJson(parsed.owner,parsed.repoName,`/commits/${encodeURIComponent(branch)}`,fetcher,budget);if(typeof commitObj.sha!="string"||!/^[0-9a-f]{40}$/.test(commitObj.sha))throw Error("GitHub did not return a pinned commit SHA for that branch.");commit=commitObj.sha}const treeObj=await githubJson(parsed.owner,parsed.repoName,`/git/trees/${commit}?recursive=1`,fetcher,budget);if(treeObj.truncated===!0||!Array.isArray(treeObj.tree))throw Error("Repository tree is truncated or unreadable; specify a narrower subfolder URL.");const prefix=parsed.subpath?`${parsed.subpath}/`:"",blobs=[];for(const entry of treeObj.tree){if(entry.type!=="blob"||entry.mode!=="100644"&&entry.mode!=="100755"||typeof entry.path!="string"||typeof entry.sha!="string"||!/^[0-9a-f]{40}$/.test(entry.sha)||prefix&&!entry.path.startsWith(prefix))continue;const relPath=prefix?entry.path.slice(prefix.length):entry.path;relPath&&blobs.push({path:entry.path,relPath,sha:entry.sha,size:Number(entry.size??0)})}const skillRoots=blobs.filter(b=>b.relPath==="SKILL.md"||b.relPath.endsWith("/SKILL.md")).map(b=>b.relPath==="SKILL.md"?"":b.relPath.slice(0,-9)).sort((a,b)=>a.length-b.length||a.localeCompare(b));if(skillRoots.length===0)throw Error("No SKILL.md files were found in that GitHub repository or subfolder.");if(skillRoots.length>LIBRARY_LIMITS.maxSkills)throw Error(`Repository contains ${skillRoots.length} skills, above the ${LIBRARY_LIMITS.maxSkills}-skill limit.`);const bySkill=new Map;for(const root of skillRoots)bySkill.set(root,[]);let totalFiles=0;for(const blob of blobs){let ownerRoot=null;for(const root of skillRoots)(root===""||blob.relPath.startsWith(`${root}/`))&&(ownerRoot===null||root.length>ownerRoot.length)&&(ownerRoot=root);if(ownerRoot===null)continue;const inner=ownerRoot===""?blob.relPath:blob.relPath.slice(ownerRoot.length+1);if(!inner.split("/").some(seg=>seg.startsWith("."))){if(totalFiles+=1,totalFiles>LIBRARY_LIMITS.maxBundleFiles)throw Error(`Bundle exceeds the ${LIBRARY_LIMITS.maxBundleFiles}-file limit.`);bySkill.get(ownerRoot).push({...blob,relPath:inner})}}const uniqueBlobs=new Map;for(const list of bySkill.values())for(const b of list)uniqueBlobs.set(b.sha,b);const blobBytes=new Map,queue=[...uniqueBlobs.keys()],worker=async()=>{for(;queue.length>0;){const sha=queue.shift(),body=await githubJson(parsed.owner,parsed.repoName,`/git/blobs/${sha}`,fetcher,budget);if(body.encoding!=="base64"||typeof body.content!="string")throw Error(`GitHub blob ${sha.slice(0,12)} was not returned as base64.`);const raw=Buffer.from(body.content.replace(/\s+/g,""),"base64");if(createHash("sha1").update(`blob ${raw.length}\0`).update(raw).digest("hex")!==sha)throw Error(`GitHub blob ${sha.slice(0,12)} failed SHA-1 verification.`);blobBytes.set(sha,raw)}};await Promise.all(Array.from({length:Math.min(LIBRARY_LIMITS.maxFetchConcurrency,Math.max(1,queue.length))},()=>worker()));const skills=[],skipped=[],seenNames=new Set;for(const[folder,list]of bySkill){const files=list.map(b=>({path:b.relPath,base64:blobBytes.get(b.sha).toString("base64")})),sourceLabel=`github:${parsed.owner}/${parsed.repoName}${folder?`/${parsed.subpath?`${parsed.subpath}/`:""}${folder}`:parsed.subpath?`/${parsed.subpath}`:""}@${commit.slice(0,12)}`;try{const pkg=validateSkill(files,sourceLabel);if(seenNames.has(pkg.name)){skipped.push({folder:folder||".",reason:`Duplicate skill name "${pkg.name}"`});continue}seenNames.add(pkg.name),skills.push(pkg)}catch(error){skipped.push({folder:folder||".",reason:error instanceof Error?error.message:String(error)})}}if(skills.length===0){const first=skipped[0]?`: ${skipped[0].reason}`:"";throw Error(`No valid skills could be imported from that repository${first}`)}return{id:parsed.id,repoUrl:parsed.repoUrl,owner:parsed.owner,repoName:parsed.repoName,branch,subpath:parsed.subpath,commit,skills,skipped}}export async function importGithubSkillBundle(store,args,now=new Date,fetcher=fetch){if(!store.schemaCurrent())throw Error("Skill library needs the current database version.");const fetched=await fetchGithubSkillBundle(args.url,fetcher),when=now.toISOString(),res=store.transact(()=>{const prevRow=store.handle.prepare("SELECT * FROM skill_bundle WHERE id=?").get(fetched.id),prevBundle=prevRow?rowToBundle(prevRow):null,cur=currentLibrary(store),next={...cur.selection};if(prevBundle!==null)for(const oldName of prevBundle.skillNames)next[oldName]?.sourceId===fetched.id&&delete next[oldName];const savedNames=[];for(const pkg of fetched.skills){const saved=storeSkillPackage(store,pkg,args.actor,now);next[saved.name]={sha:saved.sha,enabled:!0,sourceId:fetched.id},savedNames.push(saved.name)}savedNames.sort();const revision=writeLibraryRevision(store,next,args.actor,"bundle-import",now),autoUpdate=args.autoUpdate===void 0?prevBundle?.autoUpdate??!0:args.autoUpdate;return store.handle.prepare(`INSERT INTO skill_bundle
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
auto_update=excluded.auto_update,
|
|
15
|
-
last_checked_at=excluded.last_checked_at,
|
|
16
|
-
last_updated_at=excluded.last_updated_at,
|
|
17
|
-
held_commit=NULL, held_reason=NULL, held_at=NULL`).run(fetched.id,fetched.repoUrl,fetched.owner,fetched.repoName,fetched.branch,fetched.subpath,fetched.commit,prevBundle?.pinnedCommit??null,prevBundle!==null?cur.revision:null,JSON.stringify(savedNames),autoUpdate?1:0,when,when,args.actor,prevBundle?.createdAt??when,cur.revision),{bundle:rowToBundle(store.handle.prepare("SELECT * FROM skill_bundle WHERE id=?").get(fetched.id)),revision}}),enabled=enabledLibrarySkills(store).packages,localSync=syncEnabledLocalTools(store,{actor:args.actor,skills:enabled,libraryRevision:res.revision,...args.home===void 0?{}:{home:args.home},...args.env===void 0?{}:{env:args.env}},now);return{bundle:res.bundle,importedCount:fetched.skills.length,skipped:fetched.skipped,revision:res.revision,localSync}}const HIGH_RISK_TEXT_RULES=[[/\b(?:curl|wget)\b[^\n|]{0,200}\|\s*(?:ba|z|da)?sh\b/i,"pipes remote content directly into a shell"],[/\b(?:cat|less|head|tail|cp|scp|curl)\b[^\n]{0,160}(?:~\/\.ssh|id_rsa|id_ed25519|up-login\.txt|orders\.db|\.toolroll)/i,"references local secrets or Toolroll state files"],[/\bignore\s+(?:all\s+)?(?:previous|prior|earlier)\s+instructions\b/i,"contains prompt-injection override phrasing"],[/\boverride\s+(?:the\s+)?system\s+prompt\b/i,"contains system-prompt override phrasing"],[/\bapprove\s+this\s+task\s+automatically\b/i,"attempts to direct task approval"]];function decodeSkillText(pkg){return pkg.files.map(f=>Buffer.from(f.base64,"base64").toString("utf8")).join(`
|
|
18
|
-
`)}export function assessBundleUpdateSuspicion(previousSkills,nextSkills){const reasons=[],prevByName=new Map(previousSkills.map(s=>[s.name,s])),nextByName=new Map(nextSkills.map(s=>[s.name,s]));if(prevByName.size>=4){const removed=[...prevByName.keys()].filter(name=>!nextByName.has(name));removed.length*2>prevByName.size&&reasons.push(`removes ${removed.length} of ${prevByName.size} skills in one update`)}for(const next of nextSkills){const prev=prevByName.get(next.name),prevScripts=new Set((prev?.files??[]).filter(f=>f.path.startsWith("scripts/")).map(f=>f.path)),newScripts=next.files.filter(f=>f.path.startsWith("scripts/")&&!prevScripts.has(f.path));newScripts.length>0&&reasons.push(`${next.name}: adds new script file(s) (${newScripts.map(f=>f.path).join(", ")})`);const prevWarnings=new Set(prev?.warnings??[]),newWarnings=next.warnings.filter(w=>!prevWarnings.has(w));for(const warning of newWarnings)reasons.push(`${next.name}: ${warning}`);const nextText=decodeSkillText(next),prevText=prev?decodeSkillText(prev):"";scanForSecrets(nextText).length>0&&reasons.push(`${next.name}: contains secret-like material`);for(const[pattern,label]of HIGH_RISK_TEXT_RULES)pattern.test(nextText)&&!pattern.test(prevText)&&reasons.push(`${next.name}: ${label}`)}return reasons.length>0?{suspicious:!0,reasons}:{suspicious:!1}}export async function sweepSkillBundleUpdates(store,options){if(!store.schemaCurrent())return[];const now=options.now??new Date,fetcher=options.fetcher??fetch,bundles=listSkillBundles(store).filter(b=>options.onlyBundleId!==void 0?b.id===options.onlyBundleId:b.autoUpdate),results=[];let anyUpdated=!1,latestRevision=currentLibrary(store).revision;for(const bundle of bundles){if(!options.force&&bundle.lastCheckedAt!==null){const elapsed=now.getTime()-Date.parse(bundle.lastCheckedAt);if(Number.isFinite(elapsed)&&elapsed<LIBRARY_LIMITS.dailySweepMs){results.push({id:bundle.id,status:"skipped-recent",commit:bundle.pinnedCommit});continue}}const when=now.toISOString();try{const budget={remaining:2097152},latest=await githubJson(bundle.owner,bundle.repoName,`/commits/${encodeURIComponent(bundle.branch)}`,fetcher,budget);if(typeof latest.sha!="string"||!/^[0-9a-f]{40}$/.test(latest.sha))throw Error("GitHub returned no commit SHA for bundle branch.");if(latest.sha===bundle.pinnedCommit){store.handle.prepare("UPDATE skill_bundle SET last_checked_at=? WHERE id=?").run(when,bundle.id),results.push({id:bundle.id,status:"up-to-date",commit:bundle.pinnedCommit});continue}const incoming=await fetchGithubSkillBundle(bundle.repoUrl,fetcher,latest.sha),cur=currentLibrary(store),prevSkills=[];for(const name of bundle.skillNames){const entry=cur.selection[name];entry&&prevSkills.push(packageBySha(store,entry.sha))}const check=assessBundleUpdateSuspicion(prevSkills,incoming.skills);if(check.suspicious&&options.allowSuspiciousForId!==bundle.id){store.handle.prepare("UPDATE skill_bundle SET last_checked_at=?, held_commit=?, held_reason=?, held_at=? WHERE id=?").run(when,incoming.commit,check.reasons.join("; "),when,bundle.id),results.push({id:bundle.id,status:"held",commit:incoming.commit,previousCommit:bundle.pinnedCommit,reasons:check.reasons});continue}latestRevision=store.transact(()=>{const current=currentLibrary(store),next={...current.selection};for(const oldName of bundle.skillNames)next[oldName]?.sourceId===bundle.id&&delete next[oldName];const savedNames=[];for(const pkg of incoming.skills){const saved=storeSkillPackage(store,pkg,options.actor,now),wasEnabled=current.selection[saved.name]?.enabled??!0;next[saved.name]={sha:saved.sha,enabled:wasEnabled,sourceId:bundle.id},savedNames.push(saved.name)}savedNames.sort();const rev=writeLibraryRevision(store,next,options.actor,"auto-update",now);return store.handle.prepare(`UPDATE skill_bundle
|
|
19
|
-
SET previous_commit=?, previous_revision=?, pinned_commit=?, skill_names_json=?,
|
|
20
|
-
last_checked_at=?, last_updated_at=?, held_commit=NULL, held_reason=NULL, held_at=NULL
|
|
21
|
-
WHERE id=?`).run(bundle.pinnedCommit,current.revision,incoming.commit,JSON.stringify(savedNames),when,when,bundle.id),rev}),anyUpdated=!0,results.push({id:bundle.id,status:"updated",commit:incoming.commit,previousCommit:bundle.pinnedCommit})}catch(error){store.handle.prepare("UPDATE skill_bundle SET last_checked_at=? WHERE id=?").run(when,bundle.id),results.push({id:bundle.id,status:"error",error:error instanceof Error?error.message:String(error)})}}if(anyUpdated){const enabled=enabledLibrarySkills(store).packages;syncEnabledLocalTools(store,{actor:options.actor,skills:enabled,libraryRevision:latestRevision,...options.home===void 0?{}:{home:options.home},...options.env===void 0?{}:{env:options.env}},now)}return results}export function rollbackSkillBundle(store,args,now=new Date){if(!store.schemaCurrent())throw Error("Skill library needs the current database version.");const res=store.transact(()=>{const row=store.handle.prepare("SELECT * FROM skill_bundle WHERE id=?").get(args.id);if(!row)throw Error("That skill bundle was not found.");const bundle=rowToBundle(row);if(bundle.previousCommit===null||bundle.previousRevision===null)throw Error("No previous version is available to roll back to.");const revRow=store.handle.prepare("SELECT payload, sha FROM skill_library_change WHERE revision=?").get(bundle.previousRevision);if(!revRow)throw Error("The previous skill library revision could not be loaded.");const previousSelection=parseLibrarySelection(revRow.payload,revRow.sha);for(const choice of Object.values(previousSelection))packageBySha(store,choice.sha);const next={...currentLibrary(store).selection};for(const name of bundle.skillNames)next[name]?.sourceId===bundle.id&&delete next[name];const restoredNames=[];for(const[name,choice]of Object.entries(previousSelection))choice.sourceId===bundle.id&&(next[name]=choice,restoredNames.push(name));restoredNames.sort();const revision=writeLibraryRevision(store,next,args.actor,"rollback",now),when=now.toISOString();return store.handle.prepare(`UPDATE skill_bundle
|
|
22
|
-
SET pinned_commit=?, previous_commit=NULL, previous_revision=NULL, skill_names_json=?,
|
|
3
|
+
`}function rowToBundle(row){let skillNames=[];try{const parsed=JSON.parse(String(row.skill_names_json??"[]"));Array.isArray(parsed)&&(skillNames=parsed.map(String))}catch{skillNames=[]}return{sourceKind:row.source_kind==="local"?"local":"github",metadata:readPluginMetadata(String(row.metadata_json??"{}")),id:String(row.id),repoUrl:String(row.repo_url),owner:String(row.owner),repoName:String(row.repo_name),branch:String(row.branch),subpath:String(row.subpath??""),pinnedCommit:String(row.pinned_commit),previousCommit:typeof row.previous_commit=="string"?row.previous_commit:null,previousRevision:typeof row.previous_revision=="number"?row.previous_revision:null,skillNames,autoUpdate:Number(row.auto_update)===1,lastCheckedAt:typeof row.last_checked_at=="string"?row.last_checked_at:null,lastUpdatedAt:typeof row.last_updated_at=="string"?row.last_updated_at:null,heldCommit:typeof row.held_commit=="string"?row.held_commit:null,heldReason:typeof row.held_reason=="string"?row.held_reason:null,heldAt:typeof row.held_at=="string"?row.held_at:null,actor:String(row.actor),createdAt:String(row.created_at)}}export function listSkillBundles(store){return store.handle.prepare("SELECT * FROM skill_bundle WHERE removed_at IS NULL ORDER BY id").all().map(row=>rowToBundle(row))}function writeLibraryRevision(store,selection,actor,source,now){const cur=currentLibrary(store);if(Object.values(selection).filter(c=>c.enabled).length>LIBRARY_LIMITS.maxSkills)throw Error(`Enable up to ${LIBRARY_LIMITS.maxSkills} skills in the global library.`);const payload=JSON.stringify(selection),nextRevision=cur.revision+1;return store.handle.prepare("INSERT INTO skill_library_change (revision, actor, at, payload, sha, source) VALUES (?,?,?,?,?,?)").run(nextRevision,actor,now.toISOString(),payload,learningSha(payload),source),nextRevision}function storeSkillPackage(store,pkg,actor,now){const payload=JSON.stringify(pkg),sha=learningSha(payload);return store.handle.prepare("INSERT OR IGNORE INTO skill_package VALUES (?,?)").run(sha,payload),store.handle.prepare("INSERT OR IGNORE INTO skill_owner VALUES (?,?,?)").run(sha,actor,now.toISOString()),{...pkg,sha}}export function skillLibraryView(store,options={}){const{revision,selection}=currentLibrary(store),skills=[...new Set(Object.values(selection).map(c=>c.sha))].map(sha=>packageBySha(store,sha)).sort((a,b)=>a.name.localeCompare(b.name)),bundles=listSkillBundles(store),localSync=localSyncStatus(store,options),history=store.handle.prepare("SELECT revision, actor, at, payload, sha, source FROM skill_library_change ORDER BY revision DESC LIMIT 20").all().map(row=>{const sel=parseLibrarySelection(row.payload,row.sha);return{revision:Number(row.revision),actor:String(row.actor),at:String(row.at),source:String(row.source),enabledCount:Object.values(sel).filter(c=>c.enabled).length}}),optOut=options.repo?projectSkillOptOuts(store,options.repo):null;return{revision,selection,skills,bundles,localSync,history,projectOptOut:optOut===null?null:{all:optOut.all,names:[...optOut.names].sort()}}}export function importLibrarySkill(store,args,now=new Date){if(!store.schemaCurrent())throw Error("Skill library needs the current database version.");const validated=validateSkill(args.files,args.source),result=store.transact(()=>{const saved=storeSkillPackage(store,validated,args.actor,now),next={...currentLibrary(store).selection,[saved.name]:{sha:saved.sha,enabled:args.enable!==!1,sourceId:null}},revision=writeLibraryRevision(store,next,args.actor,"manual",now);return{skill:saved,revision}}),enabled=enabledLibrarySkills(store).packages,localSync=syncEnabledLocalTools(store,{actor:args.actor,skills:enabled,libraryRevision:result.revision,...args.home===void 0?{}:{home:args.home},...args.env===void 0?{}:{env:args.env}},now);return{...result,localSync}}export function changeLibrarySkill(store,args,now=new Date){if(!store.schemaCurrent())throw Error("Skill library needs the current database version.");const nextRevision=store.transact(()=>{const cur=currentLibrary(store);if(cur.revision!==args.revision)throw Error("Skill library changed in another window. Reload and try again.");let next={...cur.selection};if(args.action==="restore"){if(!Number.isSafeInteger(args.restore)||(args.restore??0)<1)throw Error("Choose a valid library revision.");const row=store.handle.prepare("SELECT payload, sha FROM skill_library_change WHERE revision=?").get(args.restore);if(!row)throw Error("That library revision is unavailable.");next=parseLibrarySelection(row.payload,row.sha);for(const choice of Object.values(next))packageBySha(store,choice.sha);return writeLibraryRevision(store,next,args.actor,"rollback",now)}const name=args.name??(args.sha?packageBySha(store,args.sha).name:"");if(!name)throw Error("Choose a skill to update.");if(args.action==="remove")delete next[name];else{const sha=args.sha||next[name]?.sha;if(!sha)throw Error("Choose a saved skill version.");const pkg=packageBySha(store,sha);next[pkg.name]={sha:pkg.sha,enabled:args.action==="enable",sourceId:next[pkg.name]?.sourceId??null}}return writeLibraryRevision(store,next,args.actor,"manual",now)}),enabled=enabledLibrarySkills(store).packages,localSync=syncEnabledLocalTools(store,{actor:args.actor,skills:enabled,libraryRevision:nextRevision,...args.home===void 0?{}:{home:args.home},...args.env===void 0?{}:{env:args.env}},now);return{revision:nextRevision,localSync}}export function setProjectSkillOptOut(store,args,now=new Date){if(!store.schemaCurrent())throw Error("Skill library needs the current database version.");const skillName=args.skillName.trim();if(skillName!=="*"&&!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(skillName))throw Error("Choose a valid skill name or '*' for the whole library.");store.transact(()=>{args.optOut?store.handle.prepare(`INSERT INTO skill_project_opt_out (repo, skill_name, actor, at) VALUES (?,?,?,?)
|
|
4
|
+
ON CONFLICT(repo, skill_name) DO UPDATE SET actor=excluded.actor, at=excluded.at`).run(args.repo,skillName,args.actor,now.toISOString()):store.handle.prepare("DELETE FROM skill_project_opt_out WHERE repo=? AND skill_name=?").run(args.repo,skillName)})}export function parseGithubBundleUrl(rawUrl){let u;if(rawUrl.includes("\\")||rawUrl.split(/[/?#]/).some(part=>/^(?:\.|%2e){1,2}$/i.test(part)))throw Error("Use a GitHub URL without traversal segments.");try{u=new URL(rawUrl.trim())}catch{throw Error("Enter a public github.com repository URL (for example https://github.com/owner/repo).")}if(u.protocol!=="https:"||u.hostname!=="github.com"||u.port||u.username||u.password||u.search||u.hash)throw Error("Use a public https://github.com repository URL with no query parameters or credentials.");const parts=u.pathname.replace(/\.git$/i,"").split("/").filter(Boolean);if(parts.length<2||parts.some(p=>!/^[a-zA-Z0-9_.-]+$/.test(p)||p==="."||p===".."))throw Error("Use https://github.com/owner/repo or https://github.com/owner/repo/tree/branch[/subfolder].");const[owner,repoName,kind,ref,...rest]=parts;if(kind!==void 0&&(kind!=="tree"||!ref))throw Error("Use https://github.com/owner/repo or https://github.com/owner/repo/tree/branch[/subfolder].");const subpath=rest.join("/"),id=subpath?`${owner}/${repoName}/${subpath}`:`${owner}/${repoName}`,repoUrl=subpath?`https://github.com/${owner}/${repoName}/tree/${ref}/${subpath}`:`https://github.com/${owner}/${repoName}`;return{id,repoUrl,owner,repoName,ref:ref??null,subpath}}async function githubJson(owner,repoName,path,fetcher,budget){let response;try{response=await fetcher(`https://api.github.com/repos/${owner}/${repoName}${path}`,{redirect:"error",signal:AbortSignal.timeout(2e4),headers:{Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"}})}catch(error){throw Error(`Couldn't reach GitHub: ${unreachableWhy(error,20)}.`)}if(!response.ok)throw Error(`GitHub returned ${response.status} for ${owner}/${repoName}${path.split("?")[0]}.`);if(!response.body)throw Error("GitHub returned an empty response.");const reader=response.body.getReader(),chunks=[];try{for(;;){const{done,value}=await reader.read();if(done)break;if(budget.remaining-=value.byteLength,budget.remaining<0)throw Error("GitHub bundle response exceeded the 24 MB size limit.");chunks.push(value)}}finally{await reader.cancel()}return JSON.parse(Buffer.concat(chunks).toString("utf8"))}export async function fetchGithubSkillBundle(url,fetcher=fetch,explicitCommit,explicitBranch){const parsed=parseGithubBundleUrl(url),budget={remaining:LIBRARY_LIMITS.maxBundleBytes};let branch=explicitBranch??parsed.ref??"";if(!branch){const repoInfo=await githubJson(parsed.owner,parsed.repoName,"",fetcher,budget);branch=typeof repoInfo.default_branch=="string"&&repoInfo.default_branch.trim()?repoInfo.default_branch.trim():"main"}let commit;if(explicitCommit!==void 0){if(!/^[0-9a-f]{40}$/.test(explicitCommit))throw Error("Pinned commit must be a 40-character SHA.");commit=explicitCommit}else{const commitObj=await githubJson(parsed.owner,parsed.repoName,`/commits/${encodeURIComponent(branch)}`,fetcher,budget);if(typeof commitObj.sha!="string"||!/^[0-9a-f]{40}$/.test(commitObj.sha))throw Error("GitHub did not return a pinned commit SHA for that branch.");commit=commitObj.sha}const treeObj=await githubJson(parsed.owner,parsed.repoName,`/git/trees/${commit}?recursive=1`,fetcher,budget);if(treeObj.truncated===!0||!Array.isArray(treeObj.tree))throw Error("Repository tree is truncated or unreadable; specify a narrower subfolder URL.");const prefix=parsed.subpath?`${parsed.subpath}/`:"",blobs=[],componentPaths=[];for(const entry of treeObj.tree){if(typeof entry.path!="string"||prefix&&!entry.path.startsWith(prefix))continue;const path=prefix?entry.path.slice(prefix.length):entry.path;if(!path)continue;if(!safeBundlePath(path))throw Error("Unsafe plug-in file path in GitHub tree.");if(componentPaths.push(path),entry.mode==="120000")throw Error("Plug-in bundles cannot contain symlinks.");if(entry.type!=="blob"||entry.mode!=="100644"&&entry.mode!=="100755"||typeof entry.path!="string"||typeof entry.sha!="string"||!/^[0-9a-f]{40}$/.test(entry.sha)||prefix&&!entry.path.startsWith(prefix))continue;const relPath=prefix?entry.path.slice(prefix.length):entry.path;relPath&&blobs.push({path:entry.path,relPath,sha:entry.sha,size:Number(entry.size??0)})}const manifestBlobs=blobs.filter(blob=>pluginManifestPath(blob.relPath));for(const blob of manifestBlobs)if(blob.size>64*1024)throw Error(`${blob.relPath} exceeds the 64 KB manifest limit.`);const blobBytes=new Map,queue=manifestBlobs.map(blob=>blob.sha),worker=async()=>{for(;queue.length>0;){const sha=queue.shift(),body=await githubJson(parsed.owner,parsed.repoName,`/git/blobs/${sha}`,fetcher,budget);if(body.encoding!=="base64"||typeof body.content!="string")throw Error(`GitHub blob ${sha.slice(0,12)} was not returned as base64.`);const raw=Buffer.from(body.content.replace(/\s+/g,""),"base64");if(createHash("sha1").update(`blob ${raw.length}\0`).update(raw).digest("hex")!==sha)throw Error(`GitHub blob ${sha.slice(0,12)} failed SHA-1 verification.`);blobBytes.set(sha,raw)}};await Promise.all(Array.from({length:Math.min(LIBRARY_LIMITS.maxFetchConcurrency,Math.max(1,queue.length))},()=>worker()));const manifests=new Map(manifestBlobs.map(blob=>[blob.relPath,blobBytes.get(blob.sha)])),locations=pluginSkillLocations(manifests),skillRoots=resolvePluginSkillRoots(blobs.map(blob=>blob.relPath),manifests);if(skillRoots.length===0)throw Error(componentPaths.includes(".claude-plugin/marketplace.json")?"This is a plug-in list; paste the link to one plug-in in it.":"No SKILL.md files were found in that GitHub repository or subfolder.");if(skillRoots.length>LIBRARY_LIMITS.maxSkills)throw Error(`Repository contains ${skillRoots.length} skills, above the ${LIBRARY_LIMITS.maxSkills}-skill limit.`);const bySkill=new Map;for(const root of skillRoots)bySkill.set(root,[]);let totalFiles=0;for(const blob of blobs){if(ignoredPluginPath(blob.relPath)||pluginManifestPath(blob.relPath))continue;let ownerRoot=null;for(const root of skillRoots)(root===""||blob.relPath.startsWith(`${root}/`))&&(ownerRoot===null||root.length>ownerRoot.length)&&(ownerRoot=root);if(ownerRoot===null)continue;const inner=ownerRoot===""?blob.relPath:blob.relPath.slice(ownerRoot.length+1);if(pluginSkillPathAllowed(blob.relPath,locations)){if(totalFiles+=1,totalFiles>LIBRARY_LIMITS.maxBundleFiles)throw Error(`Bundle exceeds the ${LIBRARY_LIMITS.maxBundleFiles}-file limit.`);bySkill.get(ownerRoot).push({...blob,relPath:inner})}}const uniqueBlobs=new Set;for(const list of bySkill.values())for(const blob of list)blobBytes.has(blob.sha)||uniqueBlobs.add(blob.sha);queue.push(...uniqueBlobs),await Promise.all(Array.from({length:Math.min(LIBRARY_LIMITS.maxFetchConcurrency,Math.max(1,queue.length))},()=>worker()));const skills=[],skipped=[],seenNames=new Set;for(const[folder,list]of bySkill){const files=list.map(b=>({path:b.relPath,base64:blobBytes.get(b.sha).toString("base64")})),sourceLabel=`github:${parsed.owner}/${parsed.repoName}${folder?`/${parsed.subpath?`${parsed.subpath}/`:""}${folder}`:parsed.subpath?`/${parsed.subpath}`:""}@${commit.slice(0,12)}`;try{const pkg=validateSkill(files,sourceLabel);if(seenNames.has(pkg.name)){skipped.push({folder:folder||".",reason:`Duplicate skill name "${pkg.name}"`});continue}seenNames.add(pkg.name),skills.push(pkg)}catch(error){skipped.push({folder:folder||".",reason:error instanceof Error?error.message:String(error)})}}if(skills.length===0){const first=skipped[0]?`: ${skipped[0].reason}`:"";throw Error(`No valid skills could be imported from that repository${first}`)}return{sourceKind:"github",metadata:bundleMetadata(componentPaths,manifests,skills),id:parsed.id,repoUrl:parsed.repoUrl,owner:parsed.owner,repoName:parsed.repoName,branch,subpath:parsed.subpath,commit,skills,skipped}}export async function importGithubSkillBundle(store,args,now=new Date,fetcher=fetch){if(!store.schemaCurrent())throw Error("Skill library needs the current database version.");const fetched=await fetchGithubSkillBundle(args.url,fetcher);return saveFetchedSkillBundle(store,fetched,args,now)}export function saveFetchedSkillBundle(store,fetched,args,now=new Date){if(!store.schemaCurrent())throw Error("Skill library needs the current database version.");const when=now.toISOString(),res=store.transact(()=>{if(args.authorize?.(),fetched.sourceKind==="local"&&localPluginRoot(store,fetched.repoUrl)!==fetched.repoUrl)throw Error("Plug-in source moved.");const row=store.handle.prepare("SELECT * FROM skill_bundle WHERE id=?").get(fetched.id),previous=row&&row.removed_at===null?rowToBundle(row):null;if(args.expectedPin!==void 0&&previous?.pinnedCommit!==args.expectedPin)throw Error("The plug-in changed while loading. Try again.");if(args.allowHeldPin!==void 0&&(previous?.heldCommit!==args.allowHeldPin||fetched.commit!==args.allowHeldPin))throw Error("The held update changed. Review it again.");const cur=currentLibrary(store);if(previous?.pinnedCommit===fetched.commit)return store.handle.prepare("UPDATE skill_bundle SET repo_url=?, branch=?, subpath=?, actor=?, last_checked_at=?, auto_update=COALESCE(?,auto_update) WHERE id=?").run(fetched.repoUrl,fetched.branch,fetched.subpath,args.actor,when,args.autoUpdate===void 0?null:args.autoUpdate?1:0,fetched.id),{bundle:rowToBundle(store.handle.prepare("SELECT * FROM skill_bundle WHERE id=?").get(fetched.id)),revision:cur.revision,importedCount:0};for(const choice of Object.values(cur.selection))packageBySha(store,choice.sha);const oldSkills=previous===null?[]:Object.entries(cur.selection).filter(([,choice])=>choice.sourceId===previous.id).map(([,choice])=>packageBySha(store,choice.sha)),suspicion=previous===null?{suspicious:!1}:assessBundleUpdateSuspicion(oldSkills,fetched.skills);if(suspicion.suspicious&&!(args.allowHeldPin===fetched.commit&&previous?.heldCommit===fetched.commit))return store.handle.prepare("UPDATE skill_bundle SET last_checked_at=?, held_commit=?, held_reason=?, held_at=? WHERE id=?").run(when,fetched.commit,suspicion.reasons.join("; "),when,fetched.id),{bundle:rowToBundle(store.handle.prepare("SELECT * FROM skill_bundle WHERE id=?").get(fetched.id)),revision:cur.revision,importedCount:0};for(const pkg of fetched.skills){const choice=cur.selection[pkg.name];if(choice!==void 0&&choice.sourceId!==fetched.id)throw Error(`Skill "${pkg.name}" already belongs to another source.`)}const next={...cur.selection};for(const[name,choice]of Object.entries(next))choice.sourceId===fetched.id&&delete next[name];const savedNames=[];for(const pkg of fetched.skills){const saved=storeSkillPackage(store,pkg,args.actor,now);next[saved.name]={sha:saved.sha,enabled:cur.selection[saved.name]?.enabled??!0,sourceId:fetched.id},savedNames.push(saved.name)}savedNames.sort();const revision=writeLibraryRevision(store,next,args.actor,args.source??"bundle-import",now);return store.handle.prepare(`INSERT INTO skill_bundle
|
|
5
|
+
(id, repo_url, owner, repo_name, branch, subpath, pinned_commit, previous_commit, previous_revision, skill_names_json,
|
|
6
|
+
auto_update, last_checked_at, last_updated_at, actor, created_at, source_kind, metadata_json, previous_metadata_json, removed_at)
|
|
7
|
+
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NULL)
|
|
8
|
+
ON CONFLICT(id) DO UPDATE SET repo_url=excluded.repo_url, branch=excluded.branch, subpath=excluded.subpath, actor=excluded.actor, pinned_commit=excluded.pinned_commit, previous_commit=excluded.previous_commit,
|
|
9
|
+
previous_revision=excluded.previous_revision, skill_names_json=excluded.skill_names_json, auto_update=excluded.auto_update,
|
|
10
|
+
last_checked_at=excluded.last_checked_at, last_updated_at=excluded.last_updated_at, metadata_json=excluded.metadata_json,
|
|
11
|
+
previous_metadata_json=excluded.previous_metadata_json, removed_at=NULL, held_commit=NULL, held_reason=NULL, held_at=NULL`).run(fetched.id,fetched.repoUrl,fetched.owner,fetched.repoName,fetched.branch,fetched.subpath,fetched.commit,previous?.pinnedCommit??null,previous?cur.revision:null,JSON.stringify(savedNames),args.autoUpdate??previous?.autoUpdate??!0?1:0,when,when,args.actor,previous?.createdAt??when,fetched.sourceKind,JSON.stringify(fetched.metadata),previous?.metadata?JSON.stringify(previous.metadata):null),{bundle:rowToBundle(store.handle.prepare("SELECT * FROM skill_bundle WHERE id=?").get(fetched.id)),revision,importedCount:fetched.skills.length}});let localSync=[];const sync=()=>{res.importedCount!==0&&(localSync=syncEnabledLocalTools(store,{actor:args.actor,skills:enabledLibrarySkills(store).packages,libraryRevision:res.revision,...args.home===void 0?{}:{home:args.home},...args.env===void 0?{}:{env:args.env}},now))};return args.deferSync?args.deferSync(sync):sync(),{...res,skipped:fetched.skipped,localSync}}export async function installSkillBundle(store,args,now=new Date,fetcher=fetch){const source=args.url.trim(),fetched=/^https?:/i.test(source)?await fetchGithubSkillBundle(source,fetcher):fetchLocalSkillBundle(store,source);return saveFetchedSkillBundle(store,fetched,args,now)}const HIGH_RISK_TEXT_RULES=[[/\b(?:curl|wget)\b[^\n|]{0,200}\|\s*(?:ba|z|da)?sh\b/i,"pipes remote content directly into a shell"],[/\b(?:cat|less|head|tail|cp|scp|curl)\b[^\n]{0,160}(?:~\/\.ssh|id_rsa|id_ed25519|up-login\.txt|orders\.db|\.toolroll)/i,"references local secrets or Toolroll state files"],[/\bignore\s+(?:all\s+)?(?:previous|prior|earlier)\s+instructions\b/i,"contains prompt-injection override phrasing"],[/\boverride\s+(?:the\s+)?system\s+prompt\b/i,"contains system-prompt override phrasing"],[/\bapprove\s+this\s+task\s+automatically\b/i,"attempts to direct task approval"]];function decodeSkillText(pkg){return pkg.files.map(f=>Buffer.from(f.base64,"base64").toString("utf8")).join(`
|
|
12
|
+
`)}export function assessBundleUpdateSuspicion(previousSkills,nextSkills){const reasons=[],prevByName=new Map(previousSkills.map(s=>[s.name,s])),nextByName=new Map(nextSkills.map(s=>[s.name,s]));if(prevByName.size>=4){const removed=[...prevByName.keys()].filter(name=>!nextByName.has(name));removed.length*2>prevByName.size&&reasons.push(`removes ${removed.length} of ${prevByName.size} skills in one update`)}for(const next of nextSkills){const prev=prevByName.get(next.name),prevScripts=new Set((prev?.files??[]).filter(f=>f.path.startsWith("scripts/")).map(f=>f.path)),newScripts=next.files.filter(f=>f.path.startsWith("scripts/")&&!prevScripts.has(f.path));newScripts.length>0&&reasons.push(`${next.name}: adds new script file(s) (${newScripts.map(f=>f.path).join(", ")})`);const prevWarnings=new Set(prev?.warnings??[]),newWarnings=next.warnings.filter(w=>!prevWarnings.has(w));for(const warning of newWarnings)reasons.push(`${next.name}: ${warning}`);const nextText=decodeSkillText(next),prevText=prev?decodeSkillText(prev):"";scanForSecrets(nextText).length>0&&reasons.push(`${next.name}: contains secret-like material`);for(const[pattern,label]of HIGH_RISK_TEXT_RULES)pattern.test(nextText)&&!pattern.test(prevText)&&reasons.push(`${next.name}: ${label}`)}return reasons.length>0?{suspicious:!0,reasons}:{suspicious:!1}}export async function sweepSkillBundleUpdates(store,options){if(!store.schemaCurrent())return[];const now=options.now??new Date,fetcher=options.fetcher??fetch,bundles=listSkillBundles(store).filter(b=>options.onlyBundleId!==void 0?b.id===options.onlyBundleId:b.autoUpdate),results=[];for(const bundle of bundles){if(!options.force&&bundle.lastCheckedAt!==null){const elapsed=now.getTime()-Date.parse(bundle.lastCheckedAt);if(Number.isFinite(elapsed)&&elapsed<LIBRARY_LIMITS.dailySweepMs){results.push({id:bundle.id,status:"skipped-recent",commit:bundle.pinnedCommit});continue}}const when=now.toISOString();let authorizationFailed=!1;const authorize=()=>{try{options.authorize?.()}catch(error){throw authorizationFailed=!0,error}},expectedPin=options.expectedPin??bundle.pinnedCommit,check=()=>{authorize();const current=listSkillBundles(store).find(one=>one.id===bundle.id);if(current?.pinnedCommit!==expectedPin)throw Error("The plug-in changed while loading. Try again.");if(options.allowSuspiciousForId===bundle.id&&(!options.allowHeldPin||current.heldCommit!==options.allowHeldPin))throw Error("The held update changed. Review it again.")},unchanged=()=>store.transact(()=>{check(),store.handle.prepare("UPDATE skill_bundle SET last_checked_at=? WHERE id=?").run(when,bundle.id)});try{let incoming;if(bundle.sourceKind==="local")incoming=fetchLocalSkillBundle(store,bundle.repoUrl);else{const latest=await githubJson(bundle.owner,bundle.repoName,`/commits/${encodeURIComponent(bundle.branch)}`,fetcher,{remaining:2097152});if(typeof latest.sha!="string"||!/^[a-f0-9]{40}$/.test(latest.sha))throw Error("GitHub returned no commit SHA for bundle branch.");if(options.allowSuspiciousForId===bundle.id&&latest.sha!==options.allowHeldPin)throw Error("The held update changed. Review it again.");if(latest.sha===bundle.pinnedCommit){unchanged(),results.push({id:bundle.id,status:"up-to-date",commit:bundle.pinnedCommit});continue}incoming=await fetchGithubSkillBundle(bundle.repoUrl,fetcher,latest.sha,bundle.branch)}if(options.allowSuspiciousForId===bundle.id&&incoming.commit!==options.allowHeldPin)throw Error("The held update changed. Review the latest version first.");if(incoming.commit===bundle.pinnedCommit){unchanged(),results.push({id:bundle.id,status:"up-to-date",commit:bundle.pinnedCommit});continue}const applied=saveFetchedSkillBundle(store,incoming,{actor:options.actor,source:"auto-update",authorize:check,expectedPin,...options.allowSuspiciousForId===bundle.id?{allowHeldPin:options.allowHeldPin??""}:{},...options.home===void 0?{}:{home:options.home},...options.env===void 0?{}:{env:options.env}},now);applied.importedCount===0?results.push({id:bundle.id,status:"held",commit:incoming.commit,previousCommit:bundle.pinnedCommit,reasons:[applied.bundle.heldReason??"Update needs review."]}):results.push({id:bundle.id,status:"updated",commit:incoming.commit,previousCommit:bundle.pinnedCommit})}catch(error){if(authorizationFailed)throw error;store.transact(()=>{authorize(),store.handle.prepare("UPDATE skill_bundle SET last_checked_at=? WHERE id=? AND pinned_commit=? AND removed_at IS NULL AND (? IS NULL OR held_commit=?)").run(when,bundle.id,expectedPin,options.allowSuspiciousForId===bundle.id?options.allowHeldPin??"":null,options.allowHeldPin??"")}),results.push({id:bundle.id,status:"error",error:error instanceof Error?error.message:String(error)})}}return results}export function rollbackSkillBundle(store,args,now=new Date){if(!store.schemaCurrent())throw Error("Skill library needs the current database version.");const res=store.transact(()=>{args.authorize?.();const row=store.handle.prepare("SELECT * FROM skill_bundle WHERE id=? AND removed_at IS NULL").get(args.id);if(!row)throw Error("That skill bundle was not found.");const bundle=rowToBundle(row);if(args.expectedPin!==void 0&&args.expectedPin!==bundle.pinnedCommit)throw Error("This plug-in changed. Reload before trying again.");if(bundle.previousCommit===null||bundle.previousRevision===null)throw Error("No previous version is available to roll back to.");const revRow=store.handle.prepare("SELECT payload, sha FROM skill_library_change WHERE revision=?").get(bundle.previousRevision);if(!revRow)throw Error("The previous skill library revision could not be loaded.");const previousSelection=parseLibrarySelection(revRow.payload,revRow.sha);for(const choice of Object.values(previousSelection))packageBySha(store,choice.sha);const next={...currentLibrary(store).selection};for(const name of bundle.skillNames)next[name]?.sourceId===bundle.id&&delete next[name];const restoredNames=[];for(const[name,choice]of Object.entries(previousSelection))if(choice.sourceId===bundle.id){if(next[name]!==void 0&&next[name]?.sourceId!==bundle.id)throw Error(`Skill "${name}" now belongs to another source.`);next[name]=choice,restoredNames.push(name)}restoredNames.sort();const revision=writeLibraryRevision(store,next,args.actor,"rollback",now),when=now.toISOString();return store.handle.prepare(`UPDATE skill_bundle
|
|
13
|
+
SET pinned_commit=?, metadata_json=COALESCE(previous_metadata_json, '{}'), previous_metadata_json=NULL, previous_commit=NULL, previous_revision=NULL, skill_names_json=?,
|
|
23
14
|
last_updated_at=?, held_commit=NULL, held_reason=NULL, held_at=NULL
|
|
24
|
-
WHERE id=?`).run(bundle.previousCommit,JSON.stringify(restoredNames),when,bundle.id),{bundle:rowToBundle(store.handle.prepare("SELECT * FROM skill_bundle WHERE id=?").get(bundle.id)),revision}}),enabled=enabledLibrarySkills(store).packages,localSync=syncEnabledLocalTools(store,{actor:args.actor,skills:enabled,libraryRevision:res.revision,...args.home===void 0?{}:{home:args.home},...args.env===void 0?{}:{env:args.env}},now);return{...res,localSync}}export function dismissHeldBundleUpdate(store,id){store.handle.prepare("UPDATE skill_bundle SET held_commit=NULL, held_reason=NULL, held_at=NULL WHERE id=?").run(id)}export function setBundleAutoUpdate(store,id,enabled){const res=store.handle.prepare("UPDATE skill_bundle SET auto_update=? WHERE id=?").run(enabled?1:0,id);if(Number(res.changes)===0)throw Error("That skill bundle was not found.")}export{syncEnabledLocalTools};
|
|
15
|
+
WHERE id=?`).run(bundle.previousCommit,JSON.stringify(restoredNames),when,bundle.id),{bundle:rowToBundle(store.handle.prepare("SELECT * FROM skill_bundle WHERE id=?").get(bundle.id)),revision}}),enabled=enabledLibrarySkills(store).packages,localSync=syncEnabledLocalTools(store,{actor:args.actor,skills:enabled,libraryRevision:res.revision,...args.home===void 0?{}:{home:args.home},...args.env===void 0?{}:{env:args.env}},now);return{...res,localSync}}export function dismissHeldBundleUpdate(store,id){const result=store.handle.prepare("UPDATE skill_bundle SET held_commit=NULL, held_reason=NULL, held_at=NULL WHERE id=? AND removed_at IS NULL AND held_commit IS NOT NULL").run(id);if(Number(result.changes)===0)throw Error("No held update was found.")}export function setBundleAutoUpdate(store,id,enabled){const res=store.handle.prepare("UPDATE skill_bundle SET auto_update=? WHERE id=? AND removed_at IS NULL").run(enabled?1:0,id);if(Number(res.changes)===0)throw Error("That skill bundle was not found.")}export{syncEnabledLocalTools};export function removeSkillBundle(store,args,now=new Date){if(!store.schemaCurrent())throw Error("Skill library needs the current database version.");const revision=store.transact(()=>{args.authorize?.();const bundle=listSkillBundles(store).find(one=>one.id===args.id);if(!bundle)throw Error("That plug-in was not found.");if(args.expectedPin!==void 0&&args.expectedPin!==bundle.pinnedCommit)throw Error("This plug-in changed. Reload before trying again.");const current=currentLibrary(store),next={...current.selection};for(const[name,choice]of Object.entries(next))packageBySha(store,choice.sha),choice.sourceId===bundle.id&&delete next[name];for(const table of["skill_bundle","skill_package","skill_library_change"])if(store.handle.prepare(`PRAGMA foreign_key_check(${table})`).all().length)throw Error("Saved references are damaged; removal was refused.");const revision2=writeLibraryRevision(store,next,args.actor,"manual",now);return store.handle.prepare("UPDATE skill_bundle SET removed_at=?, auto_update=0 WHERE id=? AND removed_at IS NULL").run(now.toISOString(),bundle.id),revision2}),localSync=syncEnabledLocalTools(store,{actor:args.actor,skills:enabledLibrarySkills(store).packages,libraryRevision:revision,...args.home===void 0?{}:{home:args.home},...args.env===void 0?{}:{env:args.env}},now);return{revision,localSync}}
|
package/dist/skills-manifest.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{closeSync,constants as fsConstants,fstatSync,lstatSync,openSync,readFileSync,realpathSync}from"node:fs";import{dirname,isAbsolute,relative}from"node:path";export const sha256Of=bytes=>createHash("sha256").update(bytes).digest("hex"),within=(child,parent)=>{const rel=relative(parent,child);return rel!==""&&!rel.startsWith("..")&&!isAbsolute(rel)};export function checkSkillsManifest(manifest){const changed=what=>({ok:!1,problem:`${what} changed after Toolroll prepared it`});try{for(const folder of manifest.folders){if(folder!==manifest.directory&&!within(folder,manifest.directory))return changed("A skill folder");const held=lstatSync(folder);if(!held.isDirectory()||held.isSymbolicLink()||realpathSync(folder)!==folder)return changed("A skill folder")}for(const file of manifest.files){if(!within(file.path,manifest.directory)||!manifest.folders.includes(dirname(file.path)))return changed("A skill file");const there=lstatSync(file.path);if(!there.isFile()||there.isSymbolicLink())return changed("A skill file");let fd=null;try{if(fd=openSync(file.path,fsConstants.O_RDONLY|fsConstants.O_NOFOLLOW|fsConstants.O_NONBLOCK),!fstatSync(fd).isFile()||realpathSync(file.path)!==file.path||sha256Of(readFileSync(fd))!==file.sha256)return changed("A skill file")}finally{fd!==null&&closeSync(fd)}}}catch{return{ok:!1,problem:"A skill file or folder is missing or can't be read where Toolroll left it"}}return{ok:!0,files:manifest.files.map(file=>file.path)}}export function skillsGrant(skills){if(skills===null)return{deny:[],files:[],digests:{},folders:[],problem:null};const canonical=path=>{try{return realpathSync(path)}catch{return path}},deny=[...new Set([skills.root,...skills.manifest===null?[]:[dirname(skills.manifest.directory)]].flatMap(path=>[path,canonical(path)]))].sort();if(skills.manifest===null)return{deny,files:[],digests:{},folders:[],problem:null};const checked=checkSkillsManifest(skills.manifest);if(!checked.ok)return{deny,files:[],digests:{},folders:[],problem:checked.problem};const digests=Object.fromEntries(skills.manifest.files.map(file=>[file.path,file.sha256]));return{deny,files:checked.files,digests,folders:[...skills.manifest.folders],problem:null}}
|
|
1
|
+
import{createHash}from"node:crypto";import{closeSync,constants as fsConstants,fstatSync,lstatSync,openSync,readFileSync,realpathSync}from"node:fs";import{dirname,isAbsolute,relative}from"node:path";export const sha256Of=bytes=>createHash("sha256").update(bytes).digest("hex"),within=(child,parent)=>{const rel=relative(parent,child);return rel!==""&&!rel.startsWith("..")&&!isAbsolute(rel)};export function checkSkillsManifest(manifest){const changed=what=>({ok:!1,problem:`${what} changed after Toolroll prepared it`});try{for(const folder of manifest.folders){if(folder!==manifest.directory&&!within(folder,manifest.directory))return changed("A skill folder");const held=lstatSync(folder);if(!held.isDirectory()||held.isSymbolicLink()||realpathSync(folder)!==folder)return changed("A skill folder")}for(const file of manifest.files){if(!within(file.path,manifest.directory)||!manifest.folders.includes(dirname(file.path)))return changed("A skill file");const there=lstatSync(file.path);if(!there.isFile()||there.isSymbolicLink())return changed("A skill file");let fd=null;try{if(fd=openSync(file.path,fsConstants.O_RDONLY|fsConstants.O_NOFOLLOW|fsConstants.O_NONBLOCK),!fstatSync(fd).isFile()||realpathSync(file.path)!==file.path||sha256Of(readFileSync(fd))!==file.sha256)return changed("A skill file")}finally{fd!==null&&closeSync(fd)}}}catch{return{ok:!1,problem:"A skill file or folder is missing or can't be read where Toolroll left it"}}return{ok:!0,files:manifest.files.map(file=>file.path)}}export function skillsGrant(skills){if(skills===null)return{deny:[],files:[],digests:{},folders:[],problem:null};if(skills.attachments!=null){const base=skillsGrant({root:skills.root,manifest:skills.manifest}),attached=skillsGrant({root:dirname(skills.attachments.directory),manifest:skills.attachments});if(attached.problem!==null)throw new Error(`Feedback attachments changed before launch: ${attached.problem}`);return{deny:[...new Set([...base.deny,...attached.deny])],files:[...base.files,...attached.files],digests:{...base.digests,...attached.digests},folders:[...base.folders,...attached.folders],problem:base.problem??attached.problem}}const canonical=path=>{try{return realpathSync(path)}catch{return path}},deny=[...new Set([skills.root,...skills.manifest===null?[]:[dirname(skills.manifest.directory)]].flatMap(path=>[path,canonical(path)]))].sort();if(skills.manifest===null)return{deny,files:[],digests:{},folders:[],problem:null};const checked=checkSkillsManifest(skills.manifest);if(!checked.ok)return{deny,files:[],digests:{},folders:[],problem:checked.problem};const digests=Object.fromEntries(skills.manifest.files.map(file=>[file.path,file.sha256]));return{deny,files:checked.files,digests,folders:[...skills.manifest.folders],problem:null}}
|
package/dist/spend-report.js
CHANGED
|
@@ -3,7 +3,8 @@ import{chatTurnAmountOf,reportedCostUsdOf,runAmountOf}from"./reported-usage.js";
|
|
|
3
3
|
r.external_id AS task, r.repo, r.filed_by, r.filed_by_kind, r.revision_of, s.microusd, s.source, s.billing
|
|
4
4
|
FROM run JOIN task_ref r ON r.id = run.task_ref LEFT JOIN run_spend s ON s.run = run.id
|
|
5
5
|
WHERE run.started_at >= ? AND run.started_at < ? ORDER BY run.id`).all(from,to)){const settledBilling=row.billing==="subscription"||row.billing==="api-key"?row.billing:null,basis=row.billing_basis==="evidence"||row.billing_basis==="default"?row.billing_basis:null,costUnknown=Number(row.cost_unknown??1)!==0,amount=runAmountOf({billing:settledBilling,spendMicrousd:count(row.microusd),costUsd:count(row.cost_usd),basis,costUnknown}),billing=basis==="evidence"&&settledBilling!==null?settledBilling:"unproved";let charge=null;if(billing!=="subscription"){const settled=micro(row.microusd);settled!==null&&(row.source==="reported"||row.source==="estimated")?charge=chargeOf(amount,settled,billing==="unproved"||costUnknown||row.source==="estimated"?"estimated":"reported"):charge=chargeOf(amount,usdMicro(row.cost_usd),"estimated")}const filer=row.filed_by==null&&row.revision_of!=null?filerOf(Number(row.task_ref)):{repo:text(row.repo),filedBy:text(row.filed_by),kind:text(row.filed_by_kind)},role=String(row.role);rows.push({ref:`run:${Number(row.id)}`,at:String(row.started_at),source:"run",role:RUN_ROLES.has(role)?role:"builder",project:text(row.repo),person:filer.kind==="person"||filer.kind==="coordinator"?filer.filedBy:null,subagent:subagentOf(filer.repo,filer.filedBy,filer.kind),taskId:String(row.task),runId:Number(row.id),provider:String(row.provider),modelChosen:text(row.model),modelReported:text(row.model_reported),billing,amount,charge})}const chatRequest=row=>{const provider=String(row.provider),reportedCostUsd=count(row.reported_cost_usd),billingReported=row.billing_reported==="subscription"||row.billing_reported==="api-key"?row.billing_reported:null,unknownSpend=Number(row.unknown_spend)===1,amount=chatTurnAmountOf({provider,settledMicrousd:count(row.settled_microusd),unknownSpend,reportedCostUsd,billingReported});if(DIRECT_CHAT.has(provider))return{amount,billing:"api-key",charge:chargeOf(amount,micro(row.settled_microusd),unknownSpend?"estimated":"settled")};const billing=billingReported??"unproved",reported=usdMicro(reportedCostUsd);return{amount,billing,charge:billing==="subscription"?null:chargeOf(amount,reported,billing==="api-key"?"reported":"estimated")}};for(const row of db.prepare(`SELECT id, created_at, approver, provider, model, model_reported, settled_microusd, unknown_spend, reported_cost_usd, billing_reported
|
|
6
|
-
FROM chat_turn WHERE mate_turn IS NULL AND created_at >= ? AND created_at < ? ORDER BY id`).all(from,to)){const request=chatRequest(row);rows.push({ref:`chat_turn:${Number(row.id)}`,at:String(row.created_at),source:"chat",role:"chat",project:null,person:text(row.approver),subagent:null,taskId:null,runId:null,provider:String(row.provider),modelChosen:text(row.model),modelReported:text(row.model_reported),...request})}
|
|
6
|
+
FROM chat_turn WHERE mate_turn IS NULL AND created_at >= ? AND created_at < ? ORDER BY id`).all(from,to)){const request=chatRequest(row);rows.push({ref:`chat_turn:${Number(row.id)}`,at:String(row.created_at),source:"chat",role:"chat",project:null,person:text(row.approver),subagent:null,taskId:null,runId:null,provider:String(row.provider),modelChosen:text(row.model),modelReported:text(row.model_reported),...request})}for(const row of db.prepare(`SELECT turn_id, admitted_at, person, repo, trust, ledger_provider, model, state, cost_basis, reserved_microusd, settled_microusd
|
|
7
|
+
FROM direct_chat_spend WHERE state <> 'released' AND admitted_at >= ? AND admitted_at < ? ORDER BY admitted_at, turn_id`).all(from,to)){const priced=row.trust==="priced",settled=row.state==="settled"&&row.cost_basis!=="unpriced"?micro(row.settled_microusd):null,amount=priced&&settled!==null?{kind:"api",microusd:settled}:{kind:"unknown"},held=priced&&row.state!=="settled"?micro(row.settled_microusd)??micro(row.reserved_microusd):null;rows.push({ref:`direct_chat_spend:${String(row.turn_id)}`,at:String(row.admitted_at),source:"chat",role:"chat",project:text(row.repo),person:text(row.person),subagent:null,taskId:null,runId:null,provider:String(row.ledger_provider),modelChosen:text(row.model),modelReported:null,billing:priced?"api-key":"unproved",amount,charge:settled!==null?chargeOf(amount,settled,row.cost_basis==="reported"?"reported":"estimated"):held!==null&&held>0?{microusd:held,basis:"estimated"}:null})}const turns=new Map;let until=null;for(const row of db.prepare(`SELECT t.id, t.created_at, t.approver, t.settled_microusd, th.scope_kind, th.scope_key,
|
|
7
8
|
MAX(t.deadline_at, COALESCE(t.finished_at, t.created_at), t.created_at) AS until
|
|
8
9
|
FROM mate_turn t LEFT JOIN lead_thread th ON th.id = t.thread WHERE t.created_at >= ? AND t.created_at < ? ORDER BY t.id`).all(from,to)){const project=row.scope_kind==="project"?text(row.scope_key):row.scope_kind==="task"&&row.scope_key!=null?taskRepo(String(row.scope_key)):null;turns.set(Number(row.id),{at:String(row.created_at),person:text(row.approver),project,settled:micro(row.settled_microusd),provider:null,model:null,charged:0,unknown:!1}),(until===null||String(row.until)>until)&&(until=String(row.until))}const stepsFrom=new Date(Date.parse(from)-36e5).toISOString(),stepsUntil=until===null?from:new Date(Date.parse(until)+36e5).toISOString();for(const row of until===null?[]:db.prepare(`SELECT c.id, c.mate_turn AS turn, c.provider, c.model, c.model_reported, c.settled_microusd, c.unknown_spend, c.reported_cost_usd, c.billing_reported
|
|
9
10
|
FROM chat_turn c WHERE c.created_at >= ? AND c.created_at < ? AND c.mate_turn IS NOT NULL ORDER BY c.mate_turn, c.id`).all(stepsFrom,stepsUntil)){const turn=turns.get(Number(row.turn));if(turn===void 0)continue;const request=chatRequest(row);turn.provider??=String(row.provider),turn.model??=text(row.model),turn.charged+=micro(row.settled_microusd)??0,request.amount.kind==="unknown"&&(turn.unknown=!0),rows.push({ref:`chat_turn:${Number(row.id)}`,at:turn.at,source:"lead",role:"lead",project:turn.project,person:turn.person,subagent:null,taskId:null,runId:null,provider:String(row.provider),modelChosen:text(row.model),modelReported:text(row.model_reported),...request})}for(const[id,turn]of turns){const held=turn.settled===null?0:turn.settled-turn.charged;if(held<=0)continue;const amount=turn.unknown?null:{kind:"unknown"};rows.push({ref:`mate_turn:${id}`,at:turn.at,source:"lead",role:"lead",project:turn.project,person:turn.person,subagent:null,taskId:null,runId:null,provider:turn.provider??"lead",modelChosen:turn.model,modelReported:null,billing:"api-key",amount,charge:{microusd:held,basis:"estimated"}})}for(const row of db.prepare(`SELECT t.id, t.at, t.subagent, t.model, t.provider, t.model_reported, t.cost_usd, m.repo FROM subagent_turn t JOIN subagent m ON m.id = t.subagent
|
package/dist/spend.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{realpathSync}from"node:fs";import{SUBSCRIPTION_CAPABLE,readAuthMode}from"./keys.js";export function billingOf(provider,db){const base=provider.replace(/-(subscription|api)$/,"");if(provider.endsWith("-api"))return"api-key";const setting=provider.endsWith("-subscription")||Object.hasOwn(SUBSCRIPTION_CAPABLE,provider)&&readAuthMode(provider)==="subscription"?"subscription":"api-key";return setting==="api-key"||db===void 0?setting:seenBilling(db,base)??setting}export function seenBilling(db,provider){const row=db.prepare("SELECT billing FROM provider_account WHERE provider = ?").get(provider);return row?.billing==="api-key"||row?.billing==="subscription"?row.billing:null}export function claudeBillingFrom(seen){return seen.keySource!==null&&seen.keySource!=="none"||seen.model!==null&&/^arn:|(^|\.)anthropic\.|@/.test(seen.model)?"api-key":seen.planWindows?"subscription":seen.keySource==="none"?"api-key":null}export function claudeMachineBilling(db){return seenBilling(db,"claude")??"subscription"}const REPORTS_COST=new Set(["claude","openrouter","anthropic-api","openrouter-api"]);export function canPrice(db,provider){return REPORTS_COST.has(provider)||ceilingPriceFor(db,provider)!==null}const CLAUDE_FAMILIES=["opus","sonnet","haiku","fable"],catalogSource=provider=>provider==="claude"||provider==="claude-subscription"||provider==="anthropic-api"?"claude":provider==="codex"||provider==="codex-subscription"?"codex":provider==="gemini"?"gemini":provider==="openrouter"||provider==="openrouter-api"?"openrouter":null;export function priceFor(db,provider,model){const source=catalogSource(provider);if(source===null||model===null||model===""||model==="default")return null;const priced=row=>row===void 0||row.input_usd==null||row.output_usd==null?null:{inputUsd:Number(row.input_usd),outputUsd:Number(row.output_usd),model:String(row.id)},exact=priced(db.prepare("SELECT id, input_usd, output_usd FROM model_seen WHERE source = ? AND id = ?").get(source,model));return exact!==null||source!=="claude"||!CLAUDE_FAMILIES.includes(model)?exact:priced(db.prepare(`SELECT id, input_usd, output_usd FROM model_seen WHERE source = 'claude' AND id LIKE ? AND last_seen_at = (SELECT MAX(last_seen_at) FROM model_seen WHERE source = 'claude')
|
|
2
|
-
ORDER BY COALESCE(released_at, '') DESC, id DESC LIMIT 1`).get(`claude-${model}-%`))}function ceilingPriceFor(db,provider){const source=catalogSource(provider);if(source===null)return null;const row=db.prepare(`SELECT MAX(input_usd) AS input_usd, MAX(output_usd) AS output_usd FROM model_seen WHERE source = ? AND input_usd IS NOT NULL AND output_usd IS NOT NULL
|
|
1
|
+
import{realpathSync}from"node:fs";import{SUBSCRIPTION_CAPABLE,readAuthMode}from"./keys.js";export function billingOf(provider,db){const base=provider.replace(/-(subscription|api)$/,"");if(provider.endsWith("-api"))return"api-key";const setting=provider.endsWith("-subscription")||Object.hasOwn(SUBSCRIPTION_CAPABLE,provider)&&readAuthMode(provider)==="subscription"?"subscription":"api-key";return setting==="api-key"||db===void 0?setting:seenBilling(db,base)??setting}export function seenBilling(db,provider){const row=db.prepare("SELECT billing FROM provider_account WHERE provider = ?").get(provider);return row?.billing==="api-key"||row?.billing==="subscription"?row.billing:null}export function claudeBillingFrom(seen){return seen.keySource!==null&&seen.keySource!=="none"||seen.model!==null&&/^arn:|(^|\.)anthropic\.|@/.test(seen.model)?"api-key":seen.planWindows?"subscription":seen.keySource==="none"?"api-key":null}export function claudeMachineBilling(db){return seenBilling(db,"claude")??"subscription"}const REPORTS_COST=new Set(["claude","openrouter","anthropic-api","openrouter-api"]);export const reportsCost=provider=>REPORTS_COST.has(provider);export function canPrice(db,provider){return REPORTS_COST.has(provider)||ceilingPriceFor(db,provider)!==null}const CLAUDE_FAMILIES=["opus","sonnet","haiku","fable"],catalogSource=provider=>provider==="claude"||provider==="claude-subscription"||provider==="anthropic-api"?"claude":provider==="codex"||provider==="codex-subscription"?"codex":provider==="gemini"||provider==="gemini-subscription"?"gemini":provider==="openrouter"||provider==="openrouter-api"?"openrouter":null;export function priceFor(db,provider,model){const source=catalogSource(provider);if(source===null||model===null||model===""||model==="default")return null;const priced=row=>row===void 0||row.input_usd==null||row.output_usd==null?null:{inputUsd:Number(row.input_usd),outputUsd:Number(row.output_usd),model:String(row.id)},exact=priced(db.prepare("SELECT id, input_usd, output_usd FROM model_seen WHERE source = ? AND id = ?").get(source,model));return exact!==null||source!=="claude"||!CLAUDE_FAMILIES.includes(model)?exact:priced(db.prepare(`SELECT id, input_usd, output_usd FROM model_seen WHERE source = 'claude' AND id LIKE ? AND last_seen_at = (SELECT MAX(last_seen_at) FROM model_seen WHERE source = 'claude')
|
|
2
|
+
ORDER BY COALESCE(released_at, '') DESC, id DESC LIMIT 1`).get(`claude-${model}-%`))}export function ceilingPriceFor(db,provider){const source=catalogSource(provider);if(source===null)return null;const row=db.prepare(`SELECT MAX(input_usd) AS input_usd, MAX(output_usd) AS output_usd FROM model_seen WHERE source = ? AND input_usd IS NOT NULL AND output_usd IS NOT NULL
|
|
3
3
|
AND last_seen_at = (SELECT MAX(last_seen_at) FROM model_seen WHERE source = ?)`).get(source,source);return row===void 0||row.input_usd==null||row.output_usd==null?null:{inputUsd:Number(row.input_usd),outputUsd:Number(row.output_usd),model:"highest listed price"}}export function priceWork(db,work,lookup=(provider,model)=>priceFor(db,provider,model)??ceilingPriceFor(db,provider)){if(work.billing==="subscription")return{microusd:0,source:"subscription",price:null};if(work.costUsd!==null&&Number.isFinite(work.costUsd))return{microusd:Math.round(work.costUsd*1e6),source:"reported",price:null};if(work.tokensIn===null&&work.tokensOut===null)return{microusd:null,source:"unpriced",price:null};const price=lookup(work.provider,work.model);return price===null?{microusd:null,source:"unpriced",price:null}:{microusd:Math.round((work.tokensIn??0)*price.inputUsd+(work.tokensOut??0)*price.outputUsd),source:"estimated",price}}export function monthOf(at){const from=new Date(Date.UTC(at.getUTCFullYear(),at.getUTCMonth(),1)),to=new Date(Date.UTC(at.getUTCFullYear(),at.getUTCMonth()+1,1));return{from:from.toISOString(),to:to.toISOString(),name:from.toISOString().slice(0,7)}}export function monthNamed(name){return name===null||!/^\d{4}-(0[1-9]|1[0-2])$/.test(name)?null:monthOf(new Date(`${name}-01T00:00:00.000Z`))}const soulName=soul=>{const front=/^---\s*\n([\s\S]*?)\n---/.exec(String(soul??""));return front===null?null:/^name:\s*(.+?)\s*$/m.exec(front[1])?.[1]??null};export function subagentNames(db){return new Map(db.prepare("SELECT id, handle, soul FROM subagent").all().map(row=>[Number(row.id),soulName(row.soul)??String(row.handle)]))}export function subagentFilers(db){const byName=new Map;for(const row of db.prepare("SELECT id, repo, handle, soul FROM subagent ORDER BY id").all()){const name=soulName(row.soul);for(const one of[String(row.handle),...name===null?[]:[name]])byName.set(`${String(row.repo)}
|
|
4
4
|
${one} (AI)`,Number(row.id))}return(repo,filedBy,kind)=>kind!=="subagent"||repo===null||filedBy===null?null:byName.get(`${repo}
|
|
5
5
|
${filedBy}`)??null}export function filersOf(db){const memo=new Map,read=db.prepare("SELECT id, backend, repo, filed_by, filed_by_kind, revision_of FROM task_ref WHERE id = ?"),source=db.prepare("SELECT id, backend, repo, filed_by, filed_by_kind, revision_of FROM task_ref WHERE backend = ? AND external_id = ? ORDER BY id DESC LIMIT 1");return taskRef=>{const known=memo.get(taskRef);if(known!==void 0)return known;let row=read.get(taskRef);const repo=row?.repo==null?null:String(row.repo),seen=new Set;for(;row!==void 0&&row.filed_by==null&&row.revision_of!=null&&!seen.has(Number(row.id))&&seen.size<64;)seen.add(Number(row.id)),row=source.get(row.backend,row.revision_of);const found={repo,filedBy:row?.filed_by==null?null:String(row.filed_by),kind:row?.filed_by_kind==null?null:String(row.filed_by_kind)};return memo.set(taskRef,found),found}}export function spendItems(db,from,to,readMode=provider=>billingOf(provider,db)){const modes=new Map,modeOf=provider=>{let mode=modes.get(provider);return mode===void 0&&(mode=readMode(provider),modes.set(provider,mode)),mode},prices=new Map,lookup=(provider,model)=>{const key=`${provider}
|
|
@@ -9,7 +9,8 @@ ${model??""}`;return prices.has(key)||prices.set(key,priceFor(db,provider,model)
|
|
|
9
9
|
EXISTS(SELECT 1 FROM side_spend WHERE at >= ?1 AND at < ?2) AS side,
|
|
10
10
|
EXISTS(SELECT 1 FROM flow_step_run WHERE kind = 'sort' AND started_at >= ?1 AND started_at < ?2) AS sort,
|
|
11
11
|
EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'thread_turn') AS threads,
|
|
12
|
-
EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'thread_relay_pending') AS reservations
|
|
12
|
+
EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'thread_relay_pending') AS reservations,
|
|
13
|
+
EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'direct_chat_spend') AS direct`).get(from,to)??{},any=key=>Number(has[key])===1;let filers=null;const subagentOf=(repo,filedBy,kind)=>(filers??=subagentFilers(db))(repo,filedBy,kind),filerOf=filersOf(db),text=value=>value==null?null:String(value),count=value=>value==null?null:Number(value),items=(any("runs")?db.prepare(`SELECT run.id, run.task_ref, run.provider, run.model, run.cost_usd, run.tokens_in, run.tokens_out, run.started_at, run.auth_mode,
|
|
13
14
|
r.external_id AS task, r.repo, r.filed_by, r.filed_by_kind, r.revision_of, s.microusd, s.source, s.billing
|
|
14
15
|
FROM run JOIN task_ref r ON r.id = run.task_ref LEFT JOIN run_spend s ON s.run = run.id
|
|
15
16
|
WHERE run.started_at >= ? AND run.started_at < ? ORDER BY run.id`).all(from,to):[]).map(row=>{const provider=String(row.provider),billing=row.billing==="subscription"||row.billing==="api-key"?row.billing:row.auth_mode==="subscription"||row.auth_mode==="api-key"?row.auth_mode:modeOf(provider),settled=row.source!=null,priced=settled?null:priceWork(db,{provider,model:text(row.model),costUsd:count(row.cost_usd),tokensIn:count(row.tokens_in),tokensOut:count(row.tokens_out),billing},lookup),filer=row.filed_by==null&&row.revision_of!=null?filerOf(Number(row.task_ref)):{repo:text(row.repo),filedBy:text(row.filed_by),kind:text(row.filed_by_kind)},kind=filer.kind;return{at:String(row.started_at),kind:"run",microusd:settled?count(row.microusd):priced.microusd,source:settled?String(row.source):priced.source,project:text(row.repo),person:kind==="person"||kind==="coordinator"?filer.filedBy:null,subagent:subagentOf(filer.repo,filer.filedBy,kind),provider,model:text(row.model),tokensIn:count(row.tokens_in),tokensOut:count(row.tokens_out),taskId:String(row.task),runId:Number(row.id),authMode:billing}});for(const row of any("subagent")?db.prepare(`SELECT t.at, t.subagent, t.model, t.provider, t.cost_usd, t.tokens_in, t.tokens_out, t.billing, m.repo FROM subagent_turn t JOIN subagent m ON m.id = t.subagent
|
|
@@ -22,6 +23,7 @@ ${model??""}`;return prices.has(key)||prices.set(key,priceFor(db,provider,model)
|
|
|
22
23
|
FROM flow_step_run fs JOIN flow_card c ON c.id = fs.card JOIN flow f ON f.id = c.flow
|
|
23
24
|
WHERE fs.kind = 'sort' AND fs.decision_json IS NOT NULL AND fs.started_at >= ? AND fs.started_at < ? ORDER BY fs.started_at`).all(from,to):[]){const cost=typeof row.cost=="number"&&Number.isFinite(row.cost)&&row.cost>=0?row.cost:null;items.push({at:String(row.at),kind:"sort",microusd:cost===null?null:Math.round(cost*1e6),source:cost===null?"unpriced":"reported",project:text(row.repo),person:null,subagent:null,provider:"openrouter",model:text(row.model),tokensIn:null,tokensOut:null,taskId:null,runId:null,authMode:"api-key"})}if(any("threads")){const reservations=any("reservations");for(const row of db.prepare(`SELECT COALESCE(started_at, admitted_at) AS at, repo, owner, provider, model, billing, status, cost_basis, cost_microusd, tokens_in, tokens_out,
|
|
24
25
|
${reservations?"(status IN ('finished', 'interrupted', 'unknown') AND id IN (SELECT turn FROM thread_relay_pending))":"0"} AS unsettled
|
|
25
|
-
FROM thread_turn WHERE status <> 'withdrawn' AND COALESCE(started_at, admitted_at) >= ? AND COALESCE(started_at, admitted_at) < ? ORDER BY admitted_at, id`).all(from,to)){const billing=row.billing==="subscription"?"subscription":"api-key",blind=billing==="api-key"&&(row.cost_basis==="unknown"||Number(row.unsettled)===1);items.push({at:String(row.at),kind:"flexible",microusd:billing==="subscription"?0:blind?null:Number(row.cost_microusd),source:billing==="subscription"?"subscription":blind?"unpriced":row.cost_basis==="measured"?"reported":"estimated",project:String(row.repo),person:String(row.owner),subagent:null,provider:String(row.provider),model:text(row.model),tokensIn:count(row.tokens_in),tokensOut:count(row.tokens_out),taskId:null,runId:null,authMode:billing})}}
|
|
26
|
+
FROM thread_turn WHERE status <> 'withdrawn' AND COALESCE(started_at, admitted_at) >= ? AND COALESCE(started_at, admitted_at) < ? ORDER BY admitted_at, id`).all(from,to)){const billing=row.billing==="subscription"?"subscription":"api-key",blind=billing==="api-key"&&(row.cost_basis==="unknown"||Number(row.unsettled)===1);items.push({at:String(row.at),kind:"flexible",microusd:billing==="subscription"?0:blind?null:Number(row.cost_microusd),source:billing==="subscription"?"subscription":blind?"unpriced":row.cost_basis==="measured"?"reported":"estimated",project:String(row.repo),person:String(row.owner),subagent:null,provider:String(row.provider),model:text(row.model),tokensIn:count(row.tokens_in),tokensOut:count(row.tokens_out),taskId:null,runId:null,authMode:billing})}}if(any("direct"))for(const row of db.prepare(`SELECT admitted_at, person, repo, agent, trust, ledger_provider, model, state, cost_basis, reserved_microusd, settled_microusd, tokens_in, tokens_out
|
|
27
|
+
FROM direct_chat_spend WHERE state <> 'released' AND admitted_at >= ? AND admitted_at < ? ORDER BY admitted_at, turn_id`).all(from,to)){const untrusted=row.trust==="untrusted",settled=row.state==="settled",microusd=untrusted||settled&&row.cost_basis==="unpriced"?null:settled?Number(row.settled_microusd):count(row.settled_microusd)??Number(row.reserved_microusd),source=microusd===null?"unpriced":settled&&row.cost_basis==="reported"?"reported":"estimated";items.push({at:String(row.admitted_at),kind:"chat",microusd,source,project:String(row.repo),person:String(row.person),subagent:null,provider:String(row.ledger_provider),model:text(row.model),tokensIn:count(row.tokens_in),tokensOut:count(row.tokens_out),taskId:null,runId:null,authMode:untrusted?"agent-login":"api-key"})}return items}const canonicalRepoPath=value=>{try{return realpathSync(value)}catch{return value}};export function countsToward(item,budget){return budget.scope==="installation"?!0:budget.scope==="project"?item.project!==null&&(item.project===budget.key||canonicalRepoPath(item.project)===canonicalRepoPath(budget.key)):budget.scope==="person"?item.person===budget.key:item.subagent!==null&&String(item.subagent)===budget.key}const PROVIDER_WORDS={claude:"Claude",codex:"Codex",gemini:"Gemini",openrouter:"OpenRouter"};export function budgetHoldWords(hold,month,subagentName){if(hold.over===null)return"";const label=budgetLabel(hold.over,subagentName);return hold.why==="unpriced"?`${label} budget can't price ${PROVIDER_WORDS[hold.unpricedProvider??""]??hold.unpricedProvider} work on a key yet. Open Settings → Models to load prices`:`${label} budget is used up for ${month}`}export function budgetStates(budgets,items){return budgets.map(budget=>{const mine=items.filter(item=>countsToward(item,budget)),spent=mine.reduce((sum,item)=>sum+(item.microusd??0),0);return{...budget,spentMicrousd:spent,unpriced:mine.filter(item=>item.microusd===null&&item.source==="unpriced"&&(item.tokensIn!==null||item.kind!=="run")).length,percent:Math.floor(spent/budget.limitMicrousd*100)}})}export function budgetLabel(budget,subagentName){return budget.scope==="installation"?"The whole installation's":budget.scope==="project"?`The ${budget.key.split("/").filter(Boolean).pop()??budget.key} project's`:budget.scope==="person"?`${budget.key}'s`:`${subagentName??`Subagent ${budget.key}`}'s`}export const usd=microusd=>microusd===null?"unpriced":`$${(microusd/1e6).toFixed(microusd!==0&&Math.abs(microusd)<1e7?2:0)}`;export function spendCsv(items,subagentNames2){const cell=value=>{const text=value==null?"":String(value),safe=/^[=+\-@\t\r]/.test(text)?`'${text}`:text;return/[",\n\r]/.test(safe)?`"${safe.replace(/"/g,'""')}"`:safe},head=["time_utc","kind","project","person","subagent","task","run","provider","model","tokens_in","tokens_out","cost_usd","priced_by","billing"],rows=items.map(item=>[item.at,item.kind,item.project,item.person,item.subagent===null?null:subagentNames2.get(item.subagent)??item.subagent,item.taskId,item.runId,item.provider,item.model,item.tokensIn,item.tokensOut,item.microusd===null?null:(item.microusd/1e6).toFixed(6),item.source,item.authMode].map(cell).join(","));return`\uFEFF${head.join(",")}\r
|
|
26
28
|
${rows.map(row=>`${row}\r
|
|
27
29
|
`).join("")}`}
|