toolroll 0.9.134 → 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 +37 -0
- 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/agent-detect.js +1 -1
- package/dist/agent-fence.js +4 -4
- package/dist/agent-thread/chat-turn.js +2 -2
- package/dist/agent-thread/direct-host.js +2 -2
- package/dist/agent-thread/fence.js +2 -2
- package/dist/agent-thread/git-workspace.js +2 -2
- package/dist/agent-thread/guards.js +1 -1
- package/dist/agent-thread/providers.js +1 -1
- package/dist/agent-thread/ship.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/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/browser/{chunk-agents-live-view.e97fbf607cb8075aad7a48664556d11ea41469785f82384b5171b76c524f71e2.js → chunk-agents-live-view.9f4367c89c6366769a567e729ac9181ccaa898bf3a168d3dc618f3cface887c7.js} +4 -4
- 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.64343d638685133eb96578bfb35bf560f329d0743ac5deda720ae27f5699c9d9.js → chunk-core.5490609e81c3a5f78da3e06b9795d71c287016ebc7fd02794b1122b474ebb07f.js} +12 -12
- 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.264e801af330461985aadcab42bc4ac4e036ba124394a7b5a100f2cd1edf89f0.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.85e1b9e0838ccc819e7b8368f80dd5240dda90f53ea2974a256a8fa4122ba2fb.js → chunk-shared.02c0b692de21a9bb80d1761aa887d8532431171945c02e663884c9f45b796753.js} +2 -2
- 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.26f6cbfdeb9bcd63231f23dbf96cacb39b78324aeed2503e86109efa89fa27db.js → chunk-shared.26bb0114998968cccb7bae5f6ffa8979ddecfafd8bc18bb6985760f6bcc030e6.js} +3 -3
- 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.5b47ca221b8b77b26ce8006f0569c981df2b905005cebe9fc54444d4906d436e.js → chunk-shared.fd5f2699d3b0017797e5b5e1e1d92eb98818740ebf20a95364bbb7deea0c8242.js} +3 -3
- 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.160372eb4f9455847ca83e8ff5d983c6b3010ef0dc2eaf541e2eaceaac3b994c.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 +194 -194
- 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.efd01c3aaf8e07c4a64194e2bfbd7aee4f7fa515f2acebdfdd90af1badba8ce7.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.js +21 -14
- 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 +3 -3
- package/dist/chat-decide.js +8 -4
- package/dist/cli-help.js +8 -7
- package/dist/cli.js +2 -2
- 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/controller-supervisor.js +2 -2
- package/dist/credential-broker.js +1 -1
- package/dist/demo.js +2 -2
- package/dist/easy-start.js +1 -1
- package/dist/egress.js +1 -1
- package/dist/engine-handoff.js +1 -1
- package/dist/engine-reads.js +1 -1
- package/dist/evals.js +2 -2
- package/dist/exec.js +4 -4
- package/dist/fast-owner-schema.js +33 -0
- package/dist/fast-start.js +1 -1
- package/dist/flow-unattended.js +2 -2
- package/dist/github-import.js +1 -1
- package/dist/github-read.js +1 -1
- package/dist/install-mode.js +2 -3
- package/dist/invoke.js +9 -7
- package/dist/laptop-background.js +1 -1
- package/dist/lead-capabilities.js +1 -1
- package/dist/live-backup-change.js +2 -2
- package/dist/live-backup.js +2 -2
- package/dist/live-terminal.js +3 -3
- package/dist/local-checks.js +1 -1
- package/dist/local-landing.js +22 -3
- package/dist/local-owner.js +1 -1
- package/dist/machine-identity.js +1 -1
- 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/onboard.js +1 -1
- package/dist/operate-remote-arguments.js +1 -1
- package/dist/operate.js +33 -16
- package/dist/orphan-sweep.js +1 -1
- package/dist/owner-mode.js +4 -0
- package/dist/peek-cli.js +2 -2
- package/dist/phase-routing.js +1 -1
- package/dist/pi-build.js +1 -1
- package/dist/plane-review.js +1 -1
- package/dist/planner-source.js +2 -2
- package/dist/planner.js +1 -1
- package/dist/pre-run-phase.js +1 -1
- package/dist/presence-hold.js +1 -1
- package/dist/process-liveness.js +1 -1
- package/dist/process-tree.js +1 -1
- package/dist/project-tools.js +2 -2
- package/dist/prompt.js +1 -1
- package/dist/proposal.js +1 -1
- package/dist/protected-storage.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/result-follow-ups.js +2 -2
- 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 +1 -1
- 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/serve.js +3 -3
- package/dist/server/chat.js +1 -1
- package/dist/server/direct-chat.js +1 -1
- package/dist/server/engine-api.js +1 -1
- package/dist/server/http.js +1 -1
- package/dist/server/one-time-secret.js +1 -1
- package/dist/server/route-table.js +1 -1
- package/dist/server/runtime.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 +2 -1
- package/dist/server/task-view-data.js +3 -3
- package/dist/server/task-views.js +1 -1
- package/dist/server/tasks.js +5 -5
- package/dist/server/terminals.js +1 -1
- package/dist/settings-data.js +1 -1
- package/dist/settings-proofs.js +1 -1
- package/dist/shared-deps.js +4 -4
- package/dist/sign-in-page.js +2 -2
- package/dist/ssr-workspace.js +88 -88
- 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 +5 -33
- package/dist/store.js +19 -14
- package/dist/subscription-usage.js +3 -3
- package/dist/surface.js +1 -1
- package/dist/test-temp.js +1 -1
- package/dist/tool-broker.js +1 -1
- package/dist/toolroll-update.js +3 -3
- 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-launch.js +1 -1
- package/dist/welcome-facts.js +1 -1
- package/package.json +1 -1
- package/dist/browser/chunk-agents-live-view.e97fbf607cb8075aad7a48664556d11ea41469785f82384b5171b76c524f71e2.js.br +0 -0
- package/dist/browser/chunk-agents-live-view.e97fbf607cb8075aad7a48664556d11ea41469785f82384b5171b76c524f71e2.js.gz +0 -0
- package/dist/browser/chunk-bundle.48f442a2868e9b77e9f54c5b77f1bba629ccd1615de8a2f62619b811783314f6.js +0 -2
- package/dist/browser/chunk-bundle.48f442a2868e9b77e9f54c5b77f1bba629ccd1615de8a2f62619b811783314f6.js.br +0 -0
- package/dist/browser/chunk-bundle.48f442a2868e9b77e9f54c5b77f1bba629ccd1615de8a2f62619b811783314f6.js.gz +0 -0
- package/dist/browser/chunk-chat-parts.1669e6985c5c0c11eea6792ea177ea4c9f7e7ebf27bd3b31742feb6a26d5b2a5.js +0 -4
- package/dist/browser/chunk-chat-parts.1669e6985c5c0c11eea6792ea177ea4c9f7e7ebf27bd3b31742feb6a26d5b2a5.js.br +0 -0
- package/dist/browser/chunk-chat-parts.1669e6985c5c0c11eea6792ea177ea4c9f7e7ebf27bd3b31742feb6a26d5b2a5.js.gz +0 -0
- package/dist/browser/chunk-core.64343d638685133eb96578bfb35bf560f329d0743ac5deda720ae27f5699c9d9.js.br +0 -0
- package/dist/browser/chunk-core.64343d638685133eb96578bfb35bf560f329d0743ac5deda720ae27f5699c9d9.js.gz +0 -0
- package/dist/browser/chunk-flow-view.264e801af330461985aadcab42bc4ac4e036ba124394a7b5a100f2cd1edf89f0.js.br +0 -0
- package/dist/browser/chunk-flow-view.264e801af330461985aadcab42bc4ac4e036ba124394a7b5a100f2cd1edf89f0.js.gz +0 -0
- package/dist/browser/chunk-flows-extra-view.6761503a97e1f17b474703ff5687a8682c54f9db1715e0a9762a979030a1b036.js +0 -4
- package/dist/browser/chunk-flows-extra-view.6761503a97e1f17b474703ff5687a8682c54f9db1715e0a9762a979030a1b036.js.br +0 -0
- package/dist/browser/chunk-flows-extra-view.6761503a97e1f17b474703ff5687a8682c54f9db1715e0a9762a979030a1b036.js.gz +0 -0
- package/dist/browser/chunk-pages-bundle.365da73d009e3ced30b55bca7107f548dc832f7a9f52926d3dcd68aa5596da11.js +0 -6
- package/dist/browser/chunk-pages-bundle.365da73d009e3ced30b55bca7107f548dc832f7a9f52926d3dcd68aa5596da11.js.br +0 -0
- package/dist/browser/chunk-pages-bundle.365da73d009e3ced30b55bca7107f548dc832f7a9f52926d3dcd68aa5596da11.js.gz +0 -0
- package/dist/browser/chunk-result-view.d4dc562a1a6a52a1497e25300d5f80c220952ceb5bb719ca32ef8dc1e74a4124.js +0 -2
- package/dist/browser/chunk-result-view.d4dc562a1a6a52a1497e25300d5f80c220952ceb5bb719ca32ef8dc1e74a4124.js.br +0 -0
- package/dist/browser/chunk-result-view.d4dc562a1a6a52a1497e25300d5f80c220952ceb5bb719ca32ef8dc1e74a4124.js.gz +0 -0
- package/dist/browser/chunk-settings-view.ff302e1c5faf5486c96e5fc96fa32492da4153e6e19997ce7b718adab21bf3b7.js +0 -20
- package/dist/browser/chunk-settings-view.ff302e1c5faf5486c96e5fc96fa32492da4153e6e19997ce7b718adab21bf3b7.js.br +0 -0
- package/dist/browser/chunk-settings-view.ff302e1c5faf5486c96e5fc96fa32492da4153e6e19997ce7b718adab21bf3b7.js.gz +0 -0
- package/dist/browser/chunk-shared.152678a803cfb6dee935162fbbbdb38d031d80f1d32ce48610f37bc1c8621e49.js +0 -2
- package/dist/browser/chunk-shared.152678a803cfb6dee935162fbbbdb38d031d80f1d32ce48610f37bc1c8621e49.js.br +0 -0
- package/dist/browser/chunk-shared.152678a803cfb6dee935162fbbbdb38d031d80f1d32ce48610f37bc1c8621e49.js.gz +0 -0
- package/dist/browser/chunk-shared.26f6cbfdeb9bcd63231f23dbf96cacb39b78324aeed2503e86109efa89fa27db.js.br +0 -0
- package/dist/browser/chunk-shared.26f6cbfdeb9bcd63231f23dbf96cacb39b78324aeed2503e86109efa89fa27db.js.gz +0 -0
- package/dist/browser/chunk-shared.4e21c6b33b9a525e63c360d20a1830f1a26c5021f5d218f2300f21ff840af27e.js +0 -2
- package/dist/browser/chunk-shared.4e21c6b33b9a525e63c360d20a1830f1a26c5021f5d218f2300f21ff840af27e.js.br +0 -0
- package/dist/browser/chunk-shared.4e21c6b33b9a525e63c360d20a1830f1a26c5021f5d218f2300f21ff840af27e.js.gz +0 -0
- package/dist/browser/chunk-shared.5b47ca221b8b77b26ce8006f0569c981df2b905005cebe9fc54444d4906d436e.js.br +0 -0
- package/dist/browser/chunk-shared.5b47ca221b8b77b26ce8006f0569c981df2b905005cebe9fc54444d4906d436e.js.gz +0 -0
- package/dist/browser/chunk-shared.85e1b9e0838ccc819e7b8368f80dd5240dda90f53ea2974a256a8fa4122ba2fb.js.br +0 -0
- package/dist/browser/chunk-shared.85e1b9e0838ccc819e7b8368f80dd5240dda90f53ea2974a256a8fa4122ba2fb.js.gz +0 -0
- package/dist/browser/chunk-shared.a326d625dea5cda744678a73b38c0cb2688721c9228e26d262279ecd5c2d7d11.js +0 -2
- package/dist/browser/chunk-shared.a326d625dea5cda744678a73b38c0cb2688721c9228e26d262279ecd5c2d7d11.js.br +0 -0
- package/dist/browser/chunk-shared.a326d625dea5cda744678a73b38c0cb2688721c9228e26d262279ecd5c2d7d11.js.gz +0 -0
- package/dist/browser/chunk-shared.e906e9c8c0859e000616dbc382f88597447f30205c92b7cb9a8e2351f3ef2722.js +0 -2
- package/dist/browser/chunk-shared.e906e9c8c0859e000616dbc382f88597447f30205c92b7cb9a8e2351f3ef2722.js.br +0 -0
- package/dist/browser/chunk-shared.e906e9c8c0859e000616dbc382f88597447f30205c92b7cb9a8e2351f3ef2722.js.gz +0 -0
- package/dist/browser/chunk-shared.f6354151d62439f2d78f5d17cf9bc44f35b4da37685beb77467d98dd9cc6f1e4.js +0 -2
- package/dist/browser/chunk-shared.f6354151d62439f2d78f5d17cf9bc44f35b4da37685beb77467d98dd9cc6f1e4.js.br +0 -0
- package/dist/browser/chunk-shared.f6354151d62439f2d78f5d17cf9bc44f35b4da37685beb77467d98dd9cc6f1e4.js.gz +0 -0
- package/dist/browser/chunk-sonner.160372eb4f9455847ca83e8ff5d983c6b3010ef0dc2eaf541e2eaceaac3b994c.js.br +0 -0
- package/dist/browser/chunk-sonner.160372eb4f9455847ca83e8ff5d983c6b3010ef0dc2eaf541e2eaceaac3b994c.js.gz +0 -0
- package/dist/browser/chunk-task-view.325b506afc26b25147b2e90cec5ad1392d50e6150a7fb33c81a996daa99bb05a.js +0 -2
- package/dist/browser/chunk-task-view.325b506afc26b25147b2e90cec5ad1392d50e6150a7fb33c81a996daa99bb05a.js.br +0 -0
- package/dist/browser/chunk-task-view.325b506afc26b25147b2e90cec5ad1392d50e6150a7fb33c81a996daa99bb05a.js.gz +0 -0
- package/dist/browser/chunk-team-chat.d560bcc5d819e63133d377b8a6f10f901356e680771f19d4fe1af044adfffb22.js +0 -2
- package/dist/browser/chunk-team-chat.d560bcc5d819e63133d377b8a6f10f901356e680771f19d4fe1af044adfffb22.js.br +0 -0
- package/dist/browser/chunk-team-chat.d560bcc5d819e63133d377b8a6f10f901356e680771f19d4fe1af044adfffb22.js.gz +0 -0
- package/dist/browser/workspace.ac1270b58f672fa920535348cc582f5fc68247b341d6fc8ec733b25336f2b9cc.css +0 -4
- package/dist/browser/workspace.ac1270b58f672fa920535348cc582f5fc68247b341d6fc8ec733b25336f2b9cc.css.br +0 -0
- package/dist/browser/workspace.ac1270b58f672fa920535348cc582f5fc68247b341d6fc8ec733b25336f2b9cc.css.gz +0 -0
- package/dist/browser/workspace.efd01c3aaf8e07c4a64194e2bfbd7aee4f7fa515f2acebdfdd90af1badba8ce7.js.br +0 -0
- package/dist/browser/workspace.efd01c3aaf8e07c4a64194e2bfbd7aee4f7fa515f2acebdfdd90af1badba8ce7.js.gz +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{z}from"zod";import{chatCardSchema}from"./chat-card.js";import{parseContract}from"./contract.js";import{PROVIDER_ID_VALUES}from"./provider.js";export const ENGINE_API_VERSION=1;const version=z.literal(ENGINE_API_VERSION),iso=z.string(),liveRecordSchema=z.union([z.object({k:z.literal("open"),at:iso,detail:z.enum(["base","commands"]),s:z.number().int().optional()}),z.object({k:z.literal("start"),at:iso,s:z.number().int().optional()}),z.object({k:z.literal("say"),at:iso,t:z.array(z.string()),s:z.number().int().optional()}),z.object({k:z.literal("you"),at:iso,t:z.array(z.string())}),z.object({k:z.literal("step"),at:iso,id:z.string(),kind:z.string(),target:z.string().optional(),once:z.literal(!0).optional(),s:z.number().int().optional()}),z.object({k:z.literal("done"),at:iso,id:z.string(),ok:z.boolean().nullable(),out:z.array(z.string()).optional(),s:z.number().int().optional()}),z.object({k:z.literal("cut"),at:iso,s:z.number().int().optional()}),z.object({k:z.literal("cap"),at:iso.optional(),s:z.number().int().optional()}),z.object({k:z.literal("child"),s:z.number().int(),at:iso.optional(),parent:z.string().nullable(),via:z.number().int().optional(),desc:z.string().optional()}),z.object({k:z.literal("end"),s:z.number().int(),at:iso.optional(),ok:z.boolean().nullable()}),z.object({k:z.literal("over")})]);export const liveSessionRefSchema=z.discriminatedUnion("kind",[z.object({kind:z.literal("run"),id:z.number().int().positive(),task:z.string().nullable()}),z.object({kind:z.literal("thread"),id:z.string().regex(/^[0-9a-f]{32}$/),task:z.null()})]);const hex32=z.string().regex(/^[0-9a-f]{32}$/),flexibleLevelSchema=z.enum(["supervised","auto","full"]),answerStateSchema=z.enum(["pending","decided","sending","sent","delivered","not-sent","uncertain","withdrawn"]),threadQuestionSchema=z.object({request:hex32,kind:z.enum(["permission","question"]),title:z.string(),detail:z.string().nullable(),tool:z.string().nullable(),complete:z.boolean(),digest:z.string().regex(/^[0-9a-f]{64}$/),state:answerStateSchema,answerable:z.boolean(),parts:z.array(z.object({id:z.string(),question:z.string(),options:z.array(z.string())}))});export const threadTerminalSchema=z.strictObject({available:z.boolean(),launch:hex32,generation:z.number().int().positive(),lifecycle:z.enum(["starting","live","stopping","exited","unresolved"]),viewing:z.enum(["detached","viewing"]),control:z.enum(["none","self","other"]),protocol:z.literal(1),cols:z.number().int().min(2).max(500),rows:z.number().int().min(2).max(500)}),threadFactsSchema=z.object({version:z.string().regex(/^[0-9a-f]{16}$/),title:z.string(),project:z.string().nullable(),level:flexibleLevelSchema.nullable(),agent:z.object({provider:z.string(),model:z.string()}).nullable(),turn:z.object({seq:z.number().int(),status:z.string(),costUsd:z.number().nullable(),costBasis:z.enum(["measured","estimated","unknown"]).nullable(),endWords:z.string().optional(),billing:z.enum(["subscription","api-key"]).optional()}).nullable(),questions:z.array(threadQuestionSchema),runtime:z.enum(["stream-json","interactive"]).optional(),terminal:threadTerminalSchema.optional(),ended:z.object({words:z.string(),stopPending:z.boolean()}).optional(),ship:z.object({seq:z.number().int(),state:z.string(),words:z.string()}).optional()}),liveSessionWindowSchema=z.object({version,session:liveSessionRefSchema,room:z.string(),live:z.boolean(),file:z.enum(["main","sub"]),window:z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),records:z.array(liveRecordSchema),cursor:z.string(),restarted:z.boolean(),earlier:z.boolean(),quarantined:z.number().int(),skipped:z.number().int(),more:z.boolean()}),z.object({ok:z.literal(!1),reason:z.enum(["missing","unavailable","off"])})]),thread:threadFactsSchema.optional()}),liveThreadsSchema=z.object({version,on:z.boolean().optional(),threads:z.array(z.object({id:hex32,title:z.string(),project:z.string().nullable(),level:flexibleLevelSchema.nullable(),live:z.boolean(),waiting:z.number().int(),costUsd:z.number().nullable(),turn:z.string().nullable(),ended:z.boolean(),stopPending:z.boolean(),ship:z.string().nullable(),turnSeq:z.number().int().nullable(),shipSeq:z.number().int().nullable()}))});const workAskSchema=z.enum(["release","approve","answer","flow","wrong","review","setup","other"]),needRowSchema=z.object({id:z.string(),title:z.string(),href:z.string(),project:z.string().nullable(),age:z.string(),at:iso.optional(),state:z.enum(["needs","running","queued","done"]),ask:workAskSchema.nullable(),group:z.enum(["decide","review","unblock"]).optional(),reason:z.string().nullable(),line:z.string().nullable(),action:z.object({label:z.string(),href:z.string()}).nullable(),question:z.object({id:z.number().int(),text:z.string(),recap:z.string(),options:z.array(z.object({id:z.string(),label:z.string(),consequence:z.string(),recommended:z.boolean()}))}).nullable()});export const waitingSchema=z.object({retryAt:iso.nullable(),lastFailure:z.string().nullable(),attempt:z.enum(["build","plan"])}),WORK_ROW_GROUPS=["decide","review","unblock","building","rest"],WORK_STATUS_TONES=["attention","problem","live","ready","done","muted","neutral"],WORK_WORD_TONES=["","needs","ask","live","done","failed"];const workRowSchema=z.object({id:z.string(),title:z.string(),href:z.string(),project:z.string().nullable(),age:z.string(),status:z.object({label:z.string(),tone:z.enum(WORK_STATUS_TONES),token:z.string()}),word:z.object({word:z.string(),tone:z.enum(WORK_WORD_TONES)}),ask:z.string().nullable(),chip:z.string().nullable(),group:z.enum(WORK_ROW_GROUPS),rank:z.number().int(),check:z.enum(["failed","stale","unreadable"]).optional(),landed:z.string().optional(),detail:z.string().nullable(),problem:z.string().nullable(),need:needRowSchema.nullable(),waiting:waitingSchema.nullable()});export const workRowsSchema=z.object({version,project:z.string().nullable(),projectName:z.string(),needsCount:z.number().int(),groups:z.array(z.object({key:z.string(),label:z.string(),count:z.number().int()})).nullable(),rows:z.array(workRowSchema),needs:z.array(z.object({key:z.enum(["decide","review","unblock"]),label:z.string(),count:z.number().int(),rows:z.array(needRowSchema)})),next:z.string().nullable(),room:z.literal("workspace"),spend:z.object({todayUsd:z.number(),planPercent:z.number().int().nullable()}).nullable(),limits:z.array(z.object({provider:z.string(),plan:z.string().nullable(),window:z.string(),usedPercent:z.number(),reached:z.boolean(),resetsAt:z.string().nullable(),observedAt:z.string()})).nullable()}),stepCardSchema=z.object({key:z.enum(["plan","approve","build","checks","review","ready"]),label:z.string(),state:z.enum(["done","current","stuck","skipped","todo"]),mark:z.enum(["done","needs","live","wait","stuck","skipped","todo"]),sentence:z.string(),at:iso.nullable(),needsYou:z.boolean(),inChain:z.boolean(),agent:z.object({provider:z.string(),model:z.string().nullable()}).nullable(),startedAt:iso.nullable(),latestStartedAt:iso.nullable(),finishedAt:iso.nullable(),costUsd:z.number().nullable(),runs:z.array(z.number().int()),terms:z.object({key:z.string(),revision:z.string().nullable(),rows:z.array(z.object({label:z.string(),words:z.string(),lines:z.array(z.string())})),warnings:z.array(z.string()),usualLabel:z.string(),usual:z.array(z.object({label:z.string(),words:z.string()}))}).optional()}),stepCardsSchema=z.object({version,task:z.object({id:z.string(),root:z.string(),title:z.string(),state:z.string(),project:z.string().nullable()}),chain:z.enum(["plan-first","just-code"]),headline:z.string().nullable(),liveRun:z.number().int().nullable(),latestRun:z.number().int().nullable(),familyBuilds:z.array(z.number().int()).optional(),models:z.array(z.object({phase:z.string(),provider:z.string(),model:z.string(),chosen:z.enum(["recommended","override","pinned"])})).nullable(),cards:z.array(stepCardSchema).nullable(),review:z.object({buildNow:z.boolean().optional(),run:z.number().int(),receipt:z.string().regex(/^[0-9a-f]{64}$/),source:z.string(),accept:z.object({owed:z.enum(["person-check","exception"]).nullable(),blockers:z.array(z.string()),needs:z.string().nullable()})}).nullable(),shell:z.object({run:z.number().int(),why:z.string().nullable()}).nullable(),failure:z.object({line:z.string(),failedInARow:z.number().int(),suggestion:z.string().nullable(),agentSaid:z.array(z.string()).max(8).nullable()}).nullable(),waiting:waitingSchema.extend({agentSaid:z.array(z.string()).max(8).nullable()}).nullable(),held:z.object({id:z.number().int(),reason:z.string(),lastFailure:z.string().nullable()}).nullable(),retry:z.object({run:z.number().int(),digest:z.string()}).nullable(),planStopped:z.object({incident:z.number().int(),kind:z.enum(["plan","question","stalled"]),line:z.string(),problems:z.array(z.string()).max(8).nullable(),agentSaid:z.array(z.string()).max(8).nullable(),again:z.object({source:z.string().regex(/^[0-9a-f]{64}$/)}).nullable()}).nullable(),plan:z.object({source:z.string().regex(/^[0-9a-f]{64}$/)}).nullable(),planQueued:z.boolean(),approval:z.object({by:z.string(),you:z.boolean(),automatic:z.boolean()}).nullable(),scopeDigest:z.string().nullable(),agentChoices:z.object({plan:z.array(z.object({provider:z.string(),model:z.string()})),build:z.array(z.object({provider:z.string(),model:z.string()}))}).nullable(),pendingAgentChange:z.object({phase:z.enum(["plan","build"]),provider:z.string(),model:z.string(),when:z.enum(["next-run","restart"]),by:z.string(),at:z.string(),problem:z.string().nullable()}).nullable(),landing:z.object({words:z.string(),reverted:z.boolean()}).nullable(),check:z.enum(["failed","stale","unreadable"]).optional(),runChecks:z.object({run:z.number().int(),level:z.enum(["quick","full"])}).optional(),behindMain:z.object({run:z.number().int(),receipt:z.string().regex(/^[0-9a-f]{64}$/),source:z.string(),main:z.string(),behind:z.number().int(),note:z.string()}).optional(),room:z.string()}),approvalCardSchema=z.object({version,task:z.string(),key:z.string().nullable(),digest:z.string().regex(/^[0-9a-f]{64}$/).nullable(),nonce:z.string().regex(/^[0-9a-f]{32}$/).nullable(),terms:z.array(z.object({label:z.string(),words:z.string()})),problem:z.string().nullable()});const diffProblemSchema=z.string().nullable();export const resultDiffSchema=z.object({version,task:z.string(),run:z.number().int().nullable(),totals:z.object({files:z.number().int(),additions:z.number().int(),deletions:z.number().int(),binary:z.number().int(),filesTruncated:z.boolean()}).nullable(),files:z.array(z.object({file:z.number().int(),path:z.string(),oldPath:z.string().nullable(),additions:z.number().int(),deletions:z.number().int(),binary:z.boolean(),hunks:z.number().int()})),patchTruncated:z.boolean(),problem:diffProblemSchema});const diffLineSchema=z.object({kind:z.enum(["context","addition","deletion","meta"]),text:z.string(),oldLine:z.number().int().nullable(),newLine:z.number().int().nullable()});export const resultDiffFileSchema=z.object({version,task:z.string(),run:z.number().int(),file:z.object({file:z.number().int(),path:z.string(),oldPath:z.string().nullable(),meta:z.array(z.string()),hunks:z.array(z.object({header:z.string(),lines:z.array(diffLineSchema)})),lineCount:z.number().int().nonnegative().nullable()}),linesTruncated:z.boolean()}),DIFF_CONTEXT_MAX=100,resultDiffContextSchema=z.object({version,task:z.string(),run:z.number().int(),file:z.number().int(),from:z.number().int(),lines:z.array(z.object({newLine:z.number().int(),text:z.string()})),lineCount:z.number().int().nullable(),problem:z.string().nullable()});const agentUseSchema=z.object({supported:z.boolean(),ready:z.boolean(),mark:z.string().nullable(),reason:z.string().nullable(),fix:z.string().nullable()});export const agentsReadSchema=z.object({version,checkedAt:iso.nullable(),agents:z.array(z.object({id:z.string(),name:z.string(),state:z.enum(["signed-in","signed-out","unknown","not-installed"]),how:z.string().nullable(),signIn:z.string().nullable(),ready:z.boolean(),next:z.string().nullable(),setup:z.object({install:z.string().nullable(),canInstall:z.boolean(),signIn:z.string().nullable(),canSignIn:z.boolean(),key:z.string().nullable(),check:z.string().nullable(),note:z.string().nullable(),registry:z.string().nullable(),registryUnsure:z.boolean()}),chat:agentUseSchema.optional(),build:agentUseSchema.extend({roles:z.array(z.string())}).optional()})),firstTask:z.object({id:z.string(),name:z.string()}).nullable(),lines:z.array(z.string())}),modelsReadSchema=z.object({version,canChange:z.boolean(),digest:z.string(),problem:z.string().nullable(),roles:z.array(z.object({key:z.enum(["plan","build","build-light","build-strong","review"]),label:z.string(),current:z.string(),words:z.string(),choices:z.array(z.object({provider:z.string(),label:z.string(),models:z.array(z.object({value:z.string(),label:z.string()}))}))})),defaultAgent:z.string().nullable(),presets:z.array(z.object({agent:z.string(),name:z.string(),words:z.string(),fields:z.record(z.string(),z.string())}))}),termStateSchema=z.object({available:z.boolean(),problem:z.string().nullable(),programs:z.array(z.enum(["claude","codex","antigravity","shell"])),projects:z.array(z.object({path:z.string(),name:z.string()})),sessions:z.array(z.object({id:z.string().regex(/^[0-9a-f]{32}$/),repo:z.string(),project:z.string(),program:z.enum(["claude","codex","antigravity","shell"]),branch:z.string(),startedAt:iso,endedAt:iso.nullable(),exit:z.object({code:z.number().int().nullable(),signal:z.number().int().nullable()}).nullable(),cleanup:z.enum(["clean","uncertain"]).nullable(),task:z.string().nullable(),run:z.number().int().nullable()}))}),termStartedSchema=z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),id:z.string().regex(/^[0-9a-f]{32}$/)}),z.object({ok:z.literal(!1),error:z.string()})]);const leadLinkSchema=z.object({label:z.string(),href:z.string(),task:z.string().nullable(),tab:z.enum(["live","steps","diff"]).nullable()}),leadCardPrimarySchema=z.discriminatedUnion("kind",[z.object({kind:z.literal("confirm"),label:z.string(),irreversible:z.boolean(),native:z.boolean()}),z.object({kind:z.literal("link"),label:z.string(),href:z.string(),task:z.string().nullable(),tab:z.enum(["live","steps","diff"]).nullable()})]);export const leadChatCardSchema=z.object({id:z.number().int(),kind:z.string(),label:z.string(),state:z.enum(["pending","confirmed","refused","dismissed","expired"]),data:z.boolean(),lines:z.array(z.string()),card:chatCardSchema.nullable(),said:z.string().nullable(),note:z.string().nullable(),primary:leadCardPrimarySchema.nullable(),dismissable:z.boolean(),links:z.array(leadLinkSchema)});const leadAskSchema=z.object({turn:z.number().int(),question:z.string(),options:z.array(z.string()),open:z.boolean(),stale:z.boolean()}),leadMessageSchema=z.object({id:z.number().int(),role:z.enum(["operator","assistant"]),text:z.string(),activity:z.string().nullable(),createdAt:iso,cards:z.array(leadChatCardSchema),ask:leadAskSchema.nullable()}),leadQueuedSchema=z.object({id:z.number().int(),text:z.string(),status:z.enum(["queued","starting","cancelled","failed","uncertain"]),detail:z.string().nullable()});export const leadChatSchema=z.object({version,room:z.string(),session:z.number().int().nullable(),leadName:z.string(),canSend:z.boolean(),problem:z.string().nullable(),project:z.string().nullable(),busy:z.boolean(),pendingProposals:z.number().int(),queued:z.array(leadQueuedSchema),messages:z.array(leadMessageSchema)});const automationTriggerSchema=z.object({id:z.number().int(),kind:z.string(),words:z.string(),state:z.enum(["active","paused"]),nextAt:iso.nullable(),lastAt:iso.nullable(),lastOutcome:z.string().max(200).nullable(),failures:z.number().int(),canPress:z.boolean(),canCheck:z.boolean(),label:z.string().nullable(),questions:z.array(z.string()).nullable(),resumeRunsNow:z.boolean()});export const automationsSchema=z.object({version,canAct:z.boolean(),automations:z.array(z.object({id:z.number().int(),name:z.string(),project:z.string().nullable(),group:z.enum(["needs","running","on","paused"]),starts:z.string(),nextAt:iso.nullable(),waiting:z.number().int(),inProgress:z.number().int(),trouble:z.string().nullable(),triggers:z.array(automationTriggerSchema)}))});const namedPathSchema=z.object({name:z.string(),path:z.string()});export const projectsSchema=z.object({version,canAdd:z.boolean(),projects:z.array(namedPathSchema),found:z.array(namedPathSchema).max(40)}),directChatProviderSchema=z.enum(PROVIDER_ID_VALUES),directChatPostureSchema=z.object({summary:z.string(),detail:z.string(),sandboxed:z.boolean()}),directChatToolSchema=z.object({id:z.string(),ordinal:z.number().int(),name:z.string(),detail:z.string(),status:z.enum(["running","done","error"]),updatedAt:iso}),directChatArtifactSchema=z.object({id:hex32,kind:z.enum(["output","attachment"]),filename:z.string(),mimeType:z.string(),byteSize:z.number().int(),url:z.string(),sourcePath:z.string().nullable(),createdAt:iso}),directChatShipSummarySchema=z.object({id:hex32,seq:z.number().int(),mode:z.enum(["ship","keep-branch"]),branch:z.string(),candidateSha:z.string(),state:z.enum(["kept","imported","armed","completed","merging","merged","cancelled","failed"]),taskId:z.string().nullable(),prUrl:z.string().nullable(),detail:z.string().nullable(),createdAt:iso,stateAt:iso}),directChatUsageSchema=z.object({inputTokens:z.number().int(),outputTokens:z.number().int(),cacheReadTokens:z.number().int(),cacheCreationTokens:z.number().int(),thinkingTokens:z.number().int(),contextTokens:z.number().int(),contextWindow:z.number().int().nullable(),costUsd:z.number().nullable()}),directChatModelOptionSchema=z.object({provider:directChatProviderSchema,id:z.string(),label:z.string(),efforts:z.array(z.string()),defaultEffort:z.string().nullable(),contextWindow:z.number().int().nullable()}),directChatTurnSchema=z.object({id:hex32,seq:z.number().int(),userPrompt:z.string(),switchedFromProvider:directChatProviderSchema.nullable(),status:z.enum(["running","completed","stopped","failed","interrupted"]),assistantText:z.string(),errorText:z.string().nullable(),createdAt:iso,finishedAt:iso.nullable(),usage:directChatUsageSchema.nullable(),tools:z.array(directChatToolSchema),artifacts:z.array(directChatArtifactSchema)}),directChatSummarySchema=z.object({id:hex32,title:z.string(),project:z.string(),branch:z.string(),provider:directChatProviderSchema,modelId:z.string(),effort:z.string().nullable(),providerLabel:z.string().optional(),pickerProvider:directChatProviderSchema.optional(),posture:directChatPostureSchema,running:z.boolean(),lastStatus:z.enum(["running","completed","stopped","failed","interrupted"]).nullable(),changedFilesCount:z.number().int(),mainDirtyFiles:z.array(z.string()),usage:directChatUsageSchema.nullable(),createdAt:iso,updatedAt:iso}),directChatsListSchema=z.object({version,available:z.boolean(),problem:z.string().nullable(),backgroundOn:z.boolean(),models:z.array(directChatModelOptionSchema),threads:z.array(directChatSummarySchema)}),directChatDetailSchema=z.object({version,room:z.string(),thread:directChatSummarySchema,turns:z.array(directChatTurnSchema),attachments:z.array(directChatArtifactSchema),ships:z.array(directChatShipSummarySchema),diff:z.object({changedFiles:z.array(z.string()),diffText:z.string(),dirty:z.boolean(),unread:z.literal(!0).optional()})}),directChatShipPreviewSchema=z.object({version,threadId:hex32,mode:z.enum(["ship","keep-branch"]),canAutoMerge:z.boolean(),autoMergeReason:z.string().nullable(),termsDigest:hex32,title:z.string(),goal:z.string(),baseSha:z.string(),branch:z.string(),changedFiles:z.array(z.string()),checkCommand:z.string().nullable(),githubRepo:z.string().nullable(),githubBase:z.string().nullable(),mergeSummary:z.string()}),directChatShippedSchema=z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),ship:directChatShipSummarySchema,said:z.string()}),z.object({ok:z.literal(!1),error:z.string(),code:z.string().optional()})]),directChatAttachedSchema=z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),artifact:directChatArtifactSchema,cloneRelativePath:z.string().nullable()}),z.object({ok:z.literal(!1),error:z.string()})]),directChatStartedSchema=z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),threadId:hex32,turnId:hex32,room:z.string()}),z.object({ok:z.literal(!1),error:z.string(),code:z.string().optional()})]),directChatMutatedSchema=z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),said:z.string()}),z.object({ok:z.literal(!1),error:z.string(),code:z.string().optional()})]),taskResultReportItemSchema=z.object({title:z.string(),why:z.string(),url:z.string(),image:z.string().nullable()}),taskResultReportFollowUpSchema=z.object({title:z.string(),goal:z.string()}),taskResultReportShotSchema=z.object({file:z.string(),caption:z.string(),url:z.string(),artifactUrl:z.string().nullable(),problem:z.string().nullable()}),taskResultReportSchema=z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),title:z.string(),summary:z.string(),document:z.string(),truncated:z.boolean(),items:z.array(taskResultReportItemSchema),followUps:z.array(taskResultReportFollowUpSchema),shots:z.array(taskResultReportShotSchema)}),z.object({ok:z.literal(!1),problem:z.string()})]),taskResultHandoffSchema=z.object({conclusion:z.string(),changes:z.array(z.string()),verification:z.array(z.string()),followUps:z.array(z.string()),decisions:z.array(z.string()),assumptions:z.array(z.string()),notDone:z.array(z.string()),risks:z.array(z.string())}),taskResultScreenshotSchema=z.object({caption:z.string(),path:z.string(),url:z.string()}),taskResultSchema=z.object({version,task:z.string(),deliverable:z.enum(["code","report"]),run:z.number().int().nullable(),role:z.string().nullable(),outcome:z.string().nullable(),verdict:z.string().nullable(),summary:z.string().nullable(),report:taskResultReportSchema.nullable(),handoff:taskResultHandoffSchema.nullable(),screenshots:z.array(taskResultScreenshotSchema)}),linkRedemptionSchema=z.object({version,account:z.string(),cookie:z.object({name:z.string(),value:z.string().regex(/^[0-9a-f]{64}$/)}),csrf:z.string().regex(/^[0-9a-f]{64}$/),key:z.string().regex(/^[0-9a-f]{64}$/),epoch:z.string(),passwordSet:z.boolean().optional()}),linkRedemptionRequestSchema=z.strictObject({code:z.string().regex(/^[A-Za-z0-9_-]{43}$/)}),ENGINE_REQUESTS={linkRedemption:{route:"POST /login/once",schema:linkRedemptionRequestSchema}},engineRefusalSchema=z.object({error:z.string()}),helloSchema=z.object({version,toolroll:z.string(),contract:z.string().regex(/^[0-9a-f]{64}$/),responses:z.array(z.string()),mode:z.enum(["solo","team"]),defaultChain:z.enum(["just-code","plan-first"])}),ENGINE_RESPONSES={liveSessionWindow:{route:"GET /agents/live/<kind>/<id>",schema:liveSessionWindowSchema},liveThreads:{route:"GET /agents/live/threads",schema:liveThreadsSchema},workRows:{route:"GET /work/rows",schema:workRowsSchema},stepCards:{route:"GET /t/<task>/steps",schema:stepCardsSchema},approvalCard:{route:"GET /t/<task>/approval",schema:approvalCardSchema},resultDiff:{route:"GET /t/<task>/diff",schema:resultDiffSchema},resultDiffFile:{route:"GET /t/<task>/diff?run=&file=",schema:resultDiffFileSchema},resultDiffContext:{route:"GET /t/<task>/diff?run=&file=&from=&count=",schema:resultDiffContextSchema},taskResult:{route:"GET /t/<task>/result",schema:taskResultSchema},linkRedemption:{route:"POST /login/once",schema:linkRedemptionSchema},refusal:{route:"every engine route's refusal",schema:engineRefusalSchema},hello:{route:"GET /engine/hello",schema:helloSchema},agents:{route:"GET /engine/agents",schema:agentsReadSchema},models:{route:"GET /engine/models",schema:modelsReadSchema},leadChat:{route:"GET /engine/chat",schema:leadChatSchema},automations:{route:"GET /engine/automations",schema:automationsSchema},projects:{route:"GET /engine/projects",schema:projectsSchema},termState:{route:"GET /term/state",schema:termStateSchema},termStarted:{route:"POST /term/start, /term/agent/sign-in, /term/agent/install",schema:termStartedSchema},directChatsList:{route:"GET /engine/direct-chats",schema:directChatsListSchema},directChatDetail:{route:"GET /engine/direct-chats/<id>",schema:directChatDetailSchema},directChatStarted:{route:"POST /engine/direct-chats, /engine/direct-chats/<id>/messages",schema:directChatStartedSchema},directChatMutated:{route:"POST /engine/direct-chats/<id>/{stop,model,delete,apply-main-edits,ship-cancel}",schema:directChatMutatedSchema},directChatShipPreview:{route:"POST /engine/direct-chats/<id>/ship-preview",schema:directChatShipPreviewSchema},directChatShipped:{route:"POST /engine/direct-chats/<id>/ship",schema:directChatShippedSchema},directChatAttached:{route:"POST /engine/direct-chats/<id>/attachments",schema:directChatAttachedSchema}};const toStderr=(route,issues)=>process.stderr.write(`engine api: ${route} disagrees with its contract: ${issues.slice(0,5).map(one=>`${one.path} ${one.kind}`).join("; ")}
|
|
1
|
+
import{createHash}from"node:crypto";import{z}from"zod";import{chatCardSchema}from"./chat-card.js";import{parseContract}from"./contract.js";import{PROVIDER_ID_VALUES}from"./provider.js";export const ENGINE_API_VERSION=1;const version=z.literal(ENGINE_API_VERSION),iso=z.string(),liveRecordSchema=z.union([z.object({k:z.literal("open"),at:iso,detail:z.enum(["base","commands"]),s:z.number().int().optional()}),z.object({k:z.literal("start"),at:iso,s:z.number().int().optional()}),z.object({k:z.literal("say"),at:iso,t:z.array(z.string()),s:z.number().int().optional()}),z.object({k:z.literal("you"),at:iso,t:z.array(z.string())}),z.object({k:z.literal("step"),at:iso,id:z.string(),kind:z.string(),target:z.string().optional(),once:z.literal(!0).optional(),s:z.number().int().optional()}),z.object({k:z.literal("done"),at:iso,id:z.string(),ok:z.boolean().nullable(),out:z.array(z.string()).optional(),s:z.number().int().optional()}),z.object({k:z.literal("cut"),at:iso,s:z.number().int().optional()}),z.object({k:z.literal("cap"),at:iso.optional(),s:z.number().int().optional()}),z.object({k:z.literal("child"),s:z.number().int(),at:iso.optional(),parent:z.string().nullable(),via:z.number().int().optional(),desc:z.string().optional()}),z.object({k:z.literal("end"),s:z.number().int(),at:iso.optional(),ok:z.boolean().nullable()}),z.object({k:z.literal("over")})]);export const liveSessionRefSchema=z.discriminatedUnion("kind",[z.object({kind:z.literal("run"),id:z.number().int().positive(),task:z.string().nullable()}),z.object({kind:z.literal("thread"),id:z.string().regex(/^[0-9a-f]{32}$/),task:z.null()})]);const hex32=z.string().regex(/^[0-9a-f]{32}$/),flexibleLevelSchema=z.enum(["supervised","auto","full"]),answerStateSchema=z.enum(["pending","decided","sending","sent","delivered","not-sent","uncertain","withdrawn"]),threadQuestionSchema=z.object({request:hex32,kind:z.enum(["permission","question"]),title:z.string(),detail:z.string().nullable(),tool:z.string().nullable(),complete:z.boolean(),digest:z.string().regex(/^[0-9a-f]{64}$/),state:answerStateSchema,answerable:z.boolean(),parts:z.array(z.object({id:z.string(),question:z.string(),options:z.array(z.string())}))});export const threadTerminalSchema=z.strictObject({available:z.boolean(),launch:hex32,generation:z.number().int().positive(),lifecycle:z.enum(["starting","live","stopping","exited","unresolved"]),viewing:z.enum(["detached","viewing"]),control:z.enum(["none","self","other"]),protocol:z.literal(1),cols:z.number().int().min(2).max(500),rows:z.number().int().min(2).max(500)}),threadFactsSchema=z.object({version:z.string().regex(/^[0-9a-f]{16}$/),title:z.string(),project:z.string().nullable(),level:flexibleLevelSchema.nullable(),agent:z.object({provider:z.string(),model:z.string()}).nullable(),turn:z.object({seq:z.number().int(),status:z.string(),costUsd:z.number().nullable(),costBasis:z.enum(["measured","estimated","unknown"]).nullable(),endWords:z.string().optional(),billing:z.enum(["subscription","api-key"]).optional()}).nullable(),questions:z.array(threadQuestionSchema),runtime:z.enum(["stream-json","interactive"]).optional(),terminal:threadTerminalSchema.optional(),ended:z.object({words:z.string(),stopPending:z.boolean()}).optional(),ship:z.object({seq:z.number().int(),state:z.string(),words:z.string()}).optional()}),liveSessionWindowSchema=z.object({version,session:liveSessionRefSchema,room:z.string(),live:z.boolean(),file:z.enum(["main","sub"]),window:z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),records:z.array(liveRecordSchema),cursor:z.string(),restarted:z.boolean(),earlier:z.boolean(),quarantined:z.number().int(),skipped:z.number().int(),more:z.boolean()}),z.object({ok:z.literal(!1),reason:z.enum(["missing","unavailable","off"])})]),thread:threadFactsSchema.optional()}),liveThreadsSchema=z.object({version,on:z.boolean().optional(),threads:z.array(z.object({id:hex32,title:z.string(),project:z.string().nullable(),level:flexibleLevelSchema.nullable(),live:z.boolean(),waiting:z.number().int(),costUsd:z.number().nullable(),turn:z.string().nullable(),ended:z.boolean(),stopPending:z.boolean(),ship:z.string().nullable(),turnSeq:z.number().int().nullable(),shipSeq:z.number().int().nullable()}))});const workAskSchema=z.enum(["release","approve","answer","flow","wrong","review","setup","other"]),needRowSchema=z.object({id:z.string(),title:z.string(),href:z.string(),project:z.string().nullable(),age:z.string(),at:iso.optional(),state:z.enum(["needs","running","queued","done"]),ask:workAskSchema.nullable(),group:z.enum(["decide","review","unblock"]).optional(),reason:z.string().nullable(),line:z.string().nullable(),action:z.object({label:z.string(),href:z.string()}).nullable(),question:z.object({id:z.number().int(),text:z.string(),recap:z.string(),options:z.array(z.object({id:z.string(),label:z.string(),consequence:z.string(),recommended:z.boolean()}))}).nullable()});export const waitingSchema=z.object({retryAt:iso.nullable(),lastFailure:z.string().nullable(),attempt:z.enum(["build","plan"])}),WORK_ROW_GROUPS=["decide","review","unblock","building","rest"],WORK_STATUS_TONES=["attention","problem","live","ready","done","muted","neutral"],WORK_WORD_TONES=["","needs","ask","live","done","failed"];const workRowSchema=z.object({id:z.string(),title:z.string(),href:z.string(),project:z.string().nullable(),age:z.string(),status:z.object({label:z.string(),tone:z.enum(WORK_STATUS_TONES),token:z.string()}),word:z.object({word:z.string(),tone:z.enum(WORK_WORD_TONES)}),ask:z.string().nullable(),chip:z.string().nullable(),group:z.enum(WORK_ROW_GROUPS),rank:z.number().int(),check:z.enum(["failed","stale","unreadable"]).optional(),landed:z.string().optional(),detail:z.string().nullable(),problem:z.string().nullable(),need:needRowSchema.nullable(),waiting:waitingSchema.nullable()});export const workRowsSchema=z.object({version,project:z.string().nullable(),projectName:z.string(),needsCount:z.number().int(),groups:z.array(z.object({key:z.string(),label:z.string(),count:z.number().int()})).nullable(),rows:z.array(workRowSchema),needs:z.array(z.object({key:z.enum(["decide","review","unblock"]),label:z.string(),count:z.number().int(),rows:z.array(needRowSchema)})),next:z.string().nullable(),room:z.literal("workspace"),spend:z.object({todayUsd:z.number(),planPercent:z.number().int().nullable()}).nullable(),limits:z.array(z.object({provider:z.string(),plan:z.string().nullable(),window:z.string(),usedPercent:z.number(),reached:z.boolean(),resetsAt:z.string().nullable(),observedAt:z.string()})).nullable()}),stepCardSchema=z.object({key:z.enum(["plan","approve","build","checks","review","ready"]),label:z.string(),state:z.enum(["done","current","stuck","skipped","todo"]),mark:z.enum(["done","needs","live","wait","stuck","skipped","todo"]),sentence:z.string(),at:iso.nullable(),needsYou:z.boolean(),inChain:z.boolean(),agent:z.object({provider:z.string(),model:z.string().nullable()}).nullable(),startedAt:iso.nullable(),latestStartedAt:iso.nullable(),finishedAt:iso.nullable(),costUsd:z.number().nullable(),runs:z.array(z.number().int()),terms:z.object({key:z.string(),revision:z.string().nullable(),rows:z.array(z.object({label:z.string(),words:z.string(),lines:z.array(z.string())})),warnings:z.array(z.string()),decision:z.object({question:z.string(),from:z.string().nullable(),summary:z.array(z.string().max(80)).max(3),planSteps:z.number().int().nonnegative().nullable(),planFiles:z.number().int().nonnegative().nullable(),agents:z.object({plan:z.string().nullable(),build:z.string().nullable(),review:z.string().nullable()}),estimateMinutes:z.number().int().nonnegative().nullable(),risk:z.object({reach:z.enum(["low","medium","high"]),undo:z.enum(["low","medium","high"]),proof:z.enum(["low","medium","high"]),secrets:z.enum(["low","medium","high"])}),unusual:z.array(z.string()),recommended:z.enum(["approve","replan"]),waiting:z.object({index:z.number().int().nonnegative(),total:z.number().int().nonnegative()})}).optional(),usualLabel:z.string(),usual:z.array(z.object({label:z.string(),words:z.string()}))}).optional()}),stepCardsSchema=z.object({version,task:z.object({id:z.string(),root:z.string(),title:z.string(),state:z.string(),project:z.string().nullable()}),chain:z.enum(["plan-first","just-code"]),headline:z.string().nullable(),liveRun:z.number().int().nullable(),latestRun:z.number().int().nullable(),familyBuilds:z.array(z.number().int()).optional(),models:z.array(z.object({phase:z.string(),provider:z.string(),model:z.string(),chosen:z.enum(["recommended","override","pinned"])})).nullable(),cards:z.array(stepCardSchema).nullable(),review:z.object({buildNow:z.boolean().optional(),run:z.number().int(),receipt:z.string().regex(/^[0-9a-f]{64}$/),source:z.string(),accept:z.object({owed:z.enum(["person-check","exception"]).nullable(),blockers:z.array(z.string()),needs:z.string().nullable()})}).nullable(),shell:z.object({run:z.number().int(),why:z.string().nullable()}).nullable(),failure:z.object({line:z.string(),failedInARow:z.number().int(),suggestion:z.string().nullable(),agentSaid:z.array(z.string()).max(8).nullable()}).nullable(),waiting:waitingSchema.extend({agentSaid:z.array(z.string()).max(8).nullable()}).nullable(),held:z.object({id:z.number().int(),reason:z.string(),lastFailure:z.string().nullable()}).nullable(),retry:z.object({run:z.number().int(),digest:z.string()}).nullable(),planStopped:z.object({incident:z.number().int(),kind:z.enum(["plan","question","stalled"]),line:z.string(),problems:z.array(z.string()).max(8).nullable(),agentSaid:z.array(z.string()).max(8).nullable(),again:z.object({source:z.string().regex(/^[0-9a-f]{64}$/)}).nullable()}).nullable(),plan:z.object({source:z.string().regex(/^[0-9a-f]{64}$/)}).nullable(),planQueued:z.boolean(),approval:z.object({by:z.string(),you:z.boolean(),automatic:z.boolean()}).nullable(),scopeDigest:z.string().nullable(),agentChoices:z.object({plan:z.array(z.object({provider:z.string(),model:z.string()})),build:z.array(z.object({provider:z.string(),model:z.string()}))}).nullable(),pendingAgentChange:z.object({phase:z.enum(["plan","build"]),provider:z.string(),model:z.string(),when:z.enum(["next-run","restart"]),by:z.string(),at:z.string(),problem:z.string().nullable()}).nullable(),landing:z.object({words:z.string(),reverted:z.boolean()}).nullable(),check:z.enum(["failed","stale","unreadable"]).optional(),runChecks:z.object({run:z.number().int(),level:z.enum(["quick","full"])}).optional(),behindMain:z.object({run:z.number().int(),receipt:z.string().regex(/^[0-9a-f]{64}$/),source:z.string(),main:z.string(),behind:z.number().int(),note:z.string()}).optional(),room:z.string()}),approvalCardSchema=z.object({version,task:z.string(),key:z.string().nullable(),digest:z.string().regex(/^[0-9a-f]{64}$/).nullable(),nonce:z.string().regex(/^[0-9a-f]{32}$/).nullable(),terms:z.array(z.object({label:z.string(),words:z.string()})),problem:z.string().nullable()});const diffProblemSchema=z.string().nullable();export const resultDiffSchema=z.object({version,task:z.string(),run:z.number().int().nullable(),totals:z.object({files:z.number().int(),additions:z.number().int(),deletions:z.number().int(),binary:z.number().int(),filesTruncated:z.boolean()}).nullable(),files:z.array(z.object({file:z.number().int(),path:z.string(),oldPath:z.string().nullable(),additions:z.number().int(),deletions:z.number().int(),binary:z.boolean(),hunks:z.number().int()})),patchTruncated:z.boolean(),problem:diffProblemSchema});const diffLineSchema=z.object({kind:z.enum(["context","addition","deletion","meta"]),text:z.string(),oldLine:z.number().int().nullable(),newLine:z.number().int().nullable()});export const resultDiffFileSchema=z.object({version,task:z.string(),run:z.number().int(),file:z.object({file:z.number().int(),path:z.string(),oldPath:z.string().nullable(),meta:z.array(z.string()),hunks:z.array(z.object({header:z.string(),lines:z.array(diffLineSchema)})),lineCount:z.number().int().nonnegative().nullable()}),linesTruncated:z.boolean()}),DIFF_CONTEXT_MAX=100,resultDiffContextSchema=z.object({version,task:z.string(),run:z.number().int(),file:z.number().int(),from:z.number().int(),lines:z.array(z.object({newLine:z.number().int(),text:z.string()})),lineCount:z.number().int().nullable(),problem:z.string().nullable()});const agentUseSchema=z.object({supported:z.boolean(),ready:z.boolean(),mark:z.string().nullable(),reason:z.string().nullable(),fix:z.string().nullable()});export const agentsReadSchema=z.object({version,checkedAt:iso.nullable(),agents:z.array(z.object({id:z.string(),name:z.string(),state:z.enum(["signed-in","signed-out","unknown","not-installed"]),how:z.string().nullable(),signIn:z.string().nullable(),ready:z.boolean(),next:z.string().nullable(),setup:z.object({install:z.string().nullable(),canInstall:z.boolean(),signIn:z.string().nullable(),canSignIn:z.boolean(),key:z.string().nullable(),check:z.string().nullable(),note:z.string().nullable(),registry:z.string().nullable(),registryUnsure:z.boolean()}),chat:agentUseSchema.optional(),build:agentUseSchema.extend({roles:z.array(z.string())}).optional()})),firstTask:z.object({id:z.string(),name:z.string()}).nullable(),lines:z.array(z.string())}),modelsReadSchema=z.object({version,canChange:z.boolean(),digest:z.string(),problem:z.string().nullable(),roles:z.array(z.object({key:z.enum(["plan","build","build-light","build-strong","review"]),label:z.string(),current:z.string(),words:z.string(),choices:z.array(z.object({provider:z.string(),label:z.string(),models:z.array(z.object({value:z.string(),label:z.string()}))}))})),defaultAgent:z.string().nullable(),presets:z.array(z.object({agent:z.string(),name:z.string(),words:z.string(),fields:z.record(z.string(),z.string())}))}),termStateSchema=z.object({available:z.boolean(),problem:z.string().nullable(),programs:z.array(z.enum(["claude","codex","antigravity","shell"])),projects:z.array(z.object({path:z.string(),name:z.string()})),sessions:z.array(z.object({id:z.string().regex(/^[0-9a-f]{32}$/),repo:z.string(),project:z.string(),program:z.enum(["claude","codex","antigravity","shell"]),branch:z.string(),startedAt:iso,endedAt:iso.nullable(),exit:z.object({code:z.number().int().nullable(),signal:z.number().int().nullable()}).nullable(),cleanup:z.enum(["clean","uncertain"]).nullable(),task:z.string().nullable(),run:z.number().int().nullable()}))}),termStartedSchema=z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),id:z.string().regex(/^[0-9a-f]{32}$/)}),z.object({ok:z.literal(!1),error:z.string()})]);const leadLinkSchema=z.object({label:z.string(),href:z.string(),task:z.string().nullable(),tab:z.enum(["live","steps","diff"]).nullable()}),leadCardPrimarySchema=z.discriminatedUnion("kind",[z.object({kind:z.literal("confirm"),label:z.string(),irreversible:z.boolean(),native:z.boolean()}),z.object({kind:z.literal("link"),label:z.string(),href:z.string(),task:z.string().nullable(),tab:z.enum(["live","steps","diff"]).nullable()})]);export const leadChatCardSchema=z.object({id:z.number().int(),kind:z.string(),label:z.string(),state:z.enum(["pending","confirmed","refused","dismissed","expired"]),data:z.boolean(),lines:z.array(z.string()),card:chatCardSchema.nullable(),said:z.string().nullable(),note:z.string().nullable(),primary:leadCardPrimarySchema.nullable(),dismissable:z.boolean(),links:z.array(leadLinkSchema)});const leadAskSchema=z.object({turn:z.number().int(),question:z.string(),options:z.array(z.string()),open:z.boolean(),stale:z.boolean()}),leadMessageSchema=z.object({id:z.number().int(),role:z.enum(["operator","assistant"]),text:z.string(),activity:z.string().nullable(),createdAt:iso,cards:z.array(leadChatCardSchema),ask:leadAskSchema.nullable()}),leadQueuedSchema=z.object({id:z.number().int(),text:z.string(),status:z.enum(["queued","starting","cancelled","failed","uncertain"]),detail:z.string().nullable()});export const leadChatSchema=z.object({version,room:z.string(),session:z.number().int().nullable(),leadName:z.string(),canSend:z.boolean(),problem:z.string().nullable(),project:z.string().nullable(),busy:z.boolean(),pendingProposals:z.number().int(),queued:z.array(leadQueuedSchema),messages:z.array(leadMessageSchema)});const automationTriggerSchema=z.object({id:z.number().int(),kind:z.string(),words:z.string(),state:z.enum(["active","paused"]),nextAt:iso.nullable(),lastAt:iso.nullable(),lastOutcome:z.string().max(200).nullable(),failures:z.number().int(),canPress:z.boolean(),canCheck:z.boolean(),label:z.string().nullable(),questions:z.array(z.string()).nullable(),resumeRunsNow:z.boolean()});export const automationsSchema=z.object({version,canAct:z.boolean(),automations:z.array(z.object({id:z.number().int(),name:z.string(),project:z.string().nullable(),group:z.enum(["needs","running","on","paused"]),starts:z.string(),nextAt:iso.nullable(),waiting:z.number().int(),inProgress:z.number().int(),trouble:z.string().nullable(),triggers:z.array(automationTriggerSchema)}))});const namedPathSchema=z.object({name:z.string(),path:z.string()});export const projectsSchema=z.object({version,canAdd:z.boolean(),projects:z.array(namedPathSchema),found:z.array(namedPathSchema).max(40)}),directChatProviderSchema=z.enum(PROVIDER_ID_VALUES),directChatPostureSchema=z.object({summary:z.string(),detail:z.string(),sandboxed:z.boolean()}),directChatToolSchema=z.object({id:z.string(),ordinal:z.number().int(),name:z.string(),detail:z.string(),status:z.enum(["running","done","error"]),updatedAt:iso}),directChatArtifactSchema=z.object({id:hex32,kind:z.enum(["output","attachment"]),filename:z.string(),mimeType:z.string(),byteSize:z.number().int(),url:z.string(),sourcePath:z.string().nullable(),createdAt:iso}),directChatShipSummarySchema=z.object({id:hex32,seq:z.number().int(),mode:z.enum(["ship","keep-branch"]),branch:z.string(),candidateSha:z.string(),state:z.enum(["kept","imported","armed","completed","merging","merged","cancelled","failed"]),taskId:z.string().nullable(),prUrl:z.string().nullable(),detail:z.string().nullable(),createdAt:iso,stateAt:iso}),directChatUsageSchema=z.object({inputTokens:z.number().int(),outputTokens:z.number().int(),cacheReadTokens:z.number().int(),cacheCreationTokens:z.number().int(),thinkingTokens:z.number().int(),contextTokens:z.number().int(),contextWindow:z.number().int().nullable(),costUsd:z.number().nullable()}),directChatModelOptionSchema=z.object({provider:directChatProviderSchema,id:z.string(),label:z.string(),efforts:z.array(z.string()),defaultEffort:z.string().nullable(),contextWindow:z.number().int().nullable()}),directChatTurnSchema=z.object({id:hex32,seq:z.number().int(),userPrompt:z.string(),switchedFromProvider:directChatProviderSchema.nullable(),status:z.enum(["running","completed","stopped","failed","interrupted"]),assistantText:z.string(),errorText:z.string().nullable(),createdAt:iso,finishedAt:iso.nullable(),usage:directChatUsageSchema.nullable(),tools:z.array(directChatToolSchema),artifacts:z.array(directChatArtifactSchema)}),directChatSummarySchema=z.object({id:hex32,title:z.string(),project:z.string(),branch:z.string(),provider:directChatProviderSchema,modelId:z.string(),effort:z.string().nullable(),providerLabel:z.string().optional(),pickerProvider:directChatProviderSchema.optional(),posture:directChatPostureSchema,running:z.boolean(),lastStatus:z.enum(["running","completed","stopped","failed","interrupted"]).nullable(),changedFilesCount:z.number().int(),mainDirtyFiles:z.array(z.string()),usage:directChatUsageSchema.nullable(),createdAt:iso,updatedAt:iso}),directChatsListSchema=z.object({version,available:z.boolean(),problem:z.string().nullable(),backgroundOn:z.boolean(),models:z.array(directChatModelOptionSchema),threads:z.array(directChatSummarySchema)}),directChatDetailSchema=z.object({version,room:z.string(),thread:directChatSummarySchema,turns:z.array(directChatTurnSchema),attachments:z.array(directChatArtifactSchema),ships:z.array(directChatShipSummarySchema),diff:z.object({changedFiles:z.array(z.string()),diffText:z.string(),dirty:z.boolean(),unread:z.literal(!0).optional()})}),directChatShipPreviewSchema=z.object({version,threadId:hex32,mode:z.enum(["ship","keep-branch"]),canAutoMerge:z.boolean(),autoMergeReason:z.string().nullable(),termsDigest:hex32,title:z.string(),goal:z.string(),baseSha:z.string(),branch:z.string(),changedFiles:z.array(z.string()),checkCommand:z.string().nullable(),githubRepo:z.string().nullable(),githubBase:z.string().nullable(),mergeSummary:z.string()}),directChatShippedSchema=z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),ship:directChatShipSummarySchema,said:z.string()}),z.object({ok:z.literal(!1),error:z.string(),code:z.string().optional()})]),directChatAttachedSchema=z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),artifact:directChatArtifactSchema,cloneRelativePath:z.string().nullable()}),z.object({ok:z.literal(!1),error:z.string()})]),directChatStartedSchema=z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),threadId:hex32,turnId:hex32,room:z.string()}),z.object({ok:z.literal(!1),error:z.string(),code:z.string().optional()})]),directChatMutatedSchema=z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),said:z.string()}),z.object({ok:z.literal(!1),error:z.string(),code:z.string().optional()})]),taskResultReportItemSchema=z.object({title:z.string(),why:z.string(),url:z.string(),image:z.string().nullable()}),taskResultReportFollowUpSchema=z.object({title:z.string(),goal:z.string()}),taskResultReportShotSchema=z.object({file:z.string(),caption:z.string(),url:z.string(),artifactUrl:z.string().nullable(),problem:z.string().nullable()}),taskResultReportSchema=z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),title:z.string(),summary:z.string(),document:z.string(),truncated:z.boolean(),items:z.array(taskResultReportItemSchema),followUps:z.array(taskResultReportFollowUpSchema),shots:z.array(taskResultReportShotSchema)}),z.object({ok:z.literal(!1),problem:z.string()})]),taskResultHandoffSchema=z.object({conclusion:z.string(),changes:z.array(z.string()),verification:z.array(z.string()),followUps:z.array(z.string()),decisions:z.array(z.string()),assumptions:z.array(z.string()),notDone:z.array(z.string()),risks:z.array(z.string())}),taskResultScreenshotSchema=z.object({caption:z.string(),path:z.string(),url:z.string()}),taskResultSchema=z.object({version,task:z.string(),deliverable:z.enum(["code","report"]),run:z.number().int().nullable(),role:z.string().nullable(),outcome:z.string().nullable(),verdict:z.string().nullable(),summary:z.string().nullable(),report:taskResultReportSchema.nullable(),handoff:taskResultHandoffSchema.nullable(),screenshots:z.array(taskResultScreenshotSchema)}),linkRedemptionSchema=z.object({version,account:z.string(),cookie:z.object({name:z.string(),value:z.string().regex(/^[0-9a-f]{64}$/)}),csrf:z.string().regex(/^[0-9a-f]{64}$/),key:z.string().regex(/^[0-9a-f]{64}$/),epoch:z.string(),passwordSet:z.boolean().optional()}),linkRedemptionRequestSchema=z.strictObject({code:z.string().regex(/^[A-Za-z0-9_-]{43}$/)}),ENGINE_REQUESTS={linkRedemption:{route:"POST /login/once",schema:linkRedemptionRequestSchema}},engineRefusalSchema=z.object({error:z.string()}),helloSchema=z.object({version,toolroll:z.string(),contract:z.string().regex(/^[0-9a-f]{64}$/),responses:z.array(z.string()),mode:z.enum(["solo","team"]),defaultChain:z.enum(["just-code","plan-first"])}),ENGINE_RESPONSES={liveSessionWindow:{route:"GET /agents/live/<kind>/<id>",schema:liveSessionWindowSchema},liveThreads:{route:"GET /agents/live/threads",schema:liveThreadsSchema},workRows:{route:"GET /work/rows",schema:workRowsSchema},stepCards:{route:"GET /t/<task>/steps",schema:stepCardsSchema},approvalCard:{route:"GET /t/<task>/approval",schema:approvalCardSchema},resultDiff:{route:"GET /t/<task>/diff",schema:resultDiffSchema},resultDiffFile:{route:"GET /t/<task>/diff?run=&file=",schema:resultDiffFileSchema},resultDiffContext:{route:"GET /t/<task>/diff?run=&file=&from=&count=",schema:resultDiffContextSchema},taskResult:{route:"GET /t/<task>/result",schema:taskResultSchema},linkRedemption:{route:"POST /login/once",schema:linkRedemptionSchema},refusal:{route:"every engine route's refusal",schema:engineRefusalSchema},hello:{route:"GET /engine/hello",schema:helloSchema},agents:{route:"GET /engine/agents",schema:agentsReadSchema},models:{route:"GET /engine/models",schema:modelsReadSchema},leadChat:{route:"GET /engine/chat",schema:leadChatSchema},automations:{route:"GET /engine/automations",schema:automationsSchema},projects:{route:"GET /engine/projects",schema:projectsSchema},termState:{route:"GET /term/state",schema:termStateSchema},termStarted:{route:"POST /term/start, /term/agent/sign-in, /term/agent/install",schema:termStartedSchema},directChatsList:{route:"GET /engine/direct-chats",schema:directChatsListSchema},directChatDetail:{route:"GET /engine/direct-chats/<id>",schema:directChatDetailSchema},directChatStarted:{route:"POST /engine/direct-chats, /engine/direct-chats/<id>/messages",schema:directChatStartedSchema},directChatMutated:{route:"POST /engine/direct-chats/<id>/{stop,model,delete,apply-main-edits,ship-cancel}",schema:directChatMutatedSchema},directChatShipPreview:{route:"POST /engine/direct-chats/<id>/ship-preview",schema:directChatShipPreviewSchema},directChatShipped:{route:"POST /engine/direct-chats/<id>/ship",schema:directChatShippedSchema},directChatAttached:{route:"POST /engine/direct-chats/<id>/attachments",schema:directChatAttachedSchema}};const toStderr=(route,issues)=>process.stderr.write(`engine api: ${route} disagrees with its contract: ${issues.slice(0,5).map(one=>`${one.path} ${one.kind}`).join("; ")}
|
|
2
2
|
`);export function checkEngineResponse(name,payload,report=toStderr){const{route,schema}=ENGINE_RESPONSES[name],parsed=parseContract(schema,payload);return parsed.ok||report(route,parsed.issues),payload}export function engineJsonSchemas(){const json=schema=>{const{$schema:_dialect,...rest}=z.toJSONSchema(schema,{target:"draft-2020-12",unrepresentable:"throw"});return rest};return{responses:Object.fromEntries(Object.entries(ENGINE_RESPONSES).map(([name,one])=>[name,json(one.schema)])),requests:Object.fromEntries(Object.entries(ENGINE_REQUESTS).map(([name,one])=>[name,json(one.schema)]))}}export function engineContractDigest(){return createHash("sha256").update(JSON.stringify({version:ENGINE_API_VERSION,...engineJsonSchemas()})).digest("hex")}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{spawn}from"node:child_process";import{performance}from"node:perf_hooks";import{stopProcessTree}from"./process-tree.js";export async function superviseController(args){const retryMs=args.retryMs??1e3,maxRetryMs=args.maxRetryMs??3e4,stableMs=args.stableMs??3e4,shutdownMs=args.shutdownMs??45e3;for(const value of[retryMs,maxRetryMs,stableMs,shutdownMs])if(!Number.isSafeInteger(value)||value<1||value>2147483647)throw new Error("Invalid controller supervision interval.");if(maxRetryMs<retryMs)throw new Error("Controller restart ceiling must cover its initial delay.");let generation=0,failures=0,child=null,escalation=null;const emit=state=>{try{args.onState?.(state)}catch{process.stderr.write(`Controller supervisor could not record its status.
|
|
2
|
-
`)}},stop=()=>{const owned=child;owned===null||owned.exitCode!==null||owned.signalCode!==null||(owned.kill("SIGTERM"),escalation===null&&(escalation=setTimeout(()=>{owned.exitCode===null&&owned.signalCode===null&&!stopProcessTree(owned)&&owned.kill("SIGKILL")},shutdownMs)))};args.signal.addEventListener("abort",stop);try{for(;!args.signal.aborted;){generation++;const started=performance.now();if(emit({phase:"starting",generation,controllerPid:null}),args.signal.aborted)break;const exited=await new Promise(done=>{const output=args.label===void 0?"inherit":"pipe",owned=spawn(args.file,[...args.argv],{...args.cwd===void 0?{}:{cwd:args.cwd}
|
|
1
|
+
import{spawn}from"node:child_process";import{performance}from"node:perf_hooks";import{withoutLeadTokenEnv}from"./names.js";import{stopProcessTree}from"./process-tree.js";export async function superviseController(args){const retryMs=args.retryMs??1e3,maxRetryMs=args.maxRetryMs??3e4,stableMs=args.stableMs??3e4,shutdownMs=args.shutdownMs??45e3;for(const value of[retryMs,maxRetryMs,stableMs,shutdownMs])if(!Number.isSafeInteger(value)||value<1||value>2147483647)throw new Error("Invalid controller supervision interval.");if(maxRetryMs<retryMs)throw new Error("Controller restart ceiling must cover its initial delay.");let generation=0,failures=0,child=null,escalation=null;const emit=state=>{try{args.onState?.(state)}catch{process.stderr.write(`Controller supervisor could not record its status.
|
|
2
|
+
`)}},stop=()=>{const owned=child;owned===null||owned.exitCode!==null||owned.signalCode!==null||(owned.kill("SIGTERM"),escalation===null&&(escalation=setTimeout(()=>{owned.exitCode===null&&owned.signalCode===null&&!stopProcessTree(owned)&&owned.kill("SIGKILL")},shutdownMs)))};args.signal.addEventListener("abort",stop);try{for(;!args.signal.aborted;){generation++;const started=performance.now();if(emit({phase:"starting",generation,controllerPid:null}),args.signal.aborted)break;const exited=await new Promise(done=>{const output=args.label===void 0?"inherit":"pipe",owned=spawn(args.file,[...args.argv],{...args.cwd===void 0?{}:{cwd:args.cwd},env:withoutLeadTokenEnv(args.env??process.env),stdio:args.ipc===!0?["ignore",output,output,"ipc"]:args.label===void 0?"inherit":["ignore","pipe","pipe"],windowsHide:!0});if(child=owned,args.label!==void 0)for(const stream of[owned.stdout,owned.stderr])labelLines(stream,args.label);try{args.onSpawn?.(owned,generation)}catch{process.stderr.write(`Controller supervisor could not attach to its controller.
|
|
3
3
|
`)}owned.once("spawn",()=>{emit({phase:"running",generation,controllerPid:owned.pid??null}),args.signal.aborted&&stop()}),owned.once("error",()=>{}),owned.once("close",(code,signal)=>done({code,signal})),args.signal.aborted&&stop()});if(child=null,escalation!==null&&(clearTimeout(escalation),escalation=null),args.signal.aborted)break;failures=performance.now()-started>=stableMs?0:Math.min(failures+1,20);const delay=Math.min(maxRetryMs,retryMs*2**Math.max(0,failures-1));emit({phase:"backoff",generation,controllerPid:null,exit:exited,retryMs:delay}),await new Promise(done=>{let timer;const finish=()=>{clearTimeout(timer),args.signal.removeEventListener("abort",finish),done()};timer=setTimeout(finish,delay),args.signal.addEventListener("abort",finish,{once:!0}),args.signal.aborted&&finish()})}}finally{args.signal.removeEventListener("abort",stop),escalation!==null&&clearTimeout(escalation),emit({phase:"stopped",generation,controllerPid:null})}}function labelLines(stream,label){if(stream===null)return;const prefix=label===""?"":`${label} `;let pending="";stream.setEncoding("utf8"),stream.on("data",chunk=>{const lines=(pending+chunk).split(`
|
|
4
4
|
`);pending=lines.pop()??"",pending.length>64*1024&&(lines.push(pending),pending="");for(const line of lines)process.stderr.write(`${prefix}${line}
|
|
5
5
|
`)}),stream.on("end",()=>{pending!==""&&process.stderr.write(`${prefix}${pending}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{execFile}from"node:child_process";import{statSync}from"node:fs";import{join}from"node:path";import{parse}from"tldts";const OP_TIMEOUT_MS=15e3,LIST_CACHE_TTL_MS=15e3,ITEM_ID=/^[A-Za-z0-9_-]{8,64}$/;function findOpCli(){const dirs=["/opt/homebrew/bin","/usr/local/bin","/usr/bin",...(process.env.PATH??"").split(":")];for(const d of dirs){if(!d)continue;const candidate=join(d,"op");try{if(statSync(candidate).isFile())return candidate}catch{}}return null}function normalizeDomain(raw){const trimmed=raw.trim().toLowerCase();if(!trimmed)return null;try{const host=(trimmed.includes("://")?new URL(trimmed):new URL(`https://${trimmed}`)).hostname.replace(/\.$/,"");return/^\[[0-9a-f:.]+\]$/.test(host)?host:!host||host.includes("..")||!/^[a-z0-9.-]+$/.test(host)?null:host}catch{return null}}function registrableDomain(host){const parsed=parse(host,{allowPrivateDomains:!0});return parsed.isIp!==!1||!(parsed.isIcann||parsed.isPrivate)||parsed.hostname!==host?null:parsed.domain}export function domainMatchesOrigin(currentOrigin,itemDomains){let url;try{url=new URL(currentOrigin)}catch{return!1}const host=url.hostname.replace(/\.$/,""),isLocal=host==="localhost"||host==="127.0.0.1"||host==="[::1]";if(url.protocol!=="https:"&&!(url.protocol==="http:"&&isLocal))return!1;const hostRoot=registrableDomain(host);return itemDomains.some(raw=>{const allowed=normalizeDomain(raw);if(allowed===null)return!1;const root=registrableDomain(allowed);return host===allowed||root!==null&&root===hostRoot})}function defaultExecOp(opBin){return(args,timeoutMs)=>new Promise((resolveRun,rejectRun)=>{execFile(opBin,[...args],{timeout:timeoutMs,maxBuffer:4*1024*1024},(err,stdout,stderr)=>{if(err){const msg=stderr?.trim()||err.message||"1Password CLI failed";rejectRun(new Error(msg));return}resolveRun(stdout)})})}export class CredentialBroker{opPath;execOpOverride;nowMs;cachedList=null;constructor(deps={}){this.opPath=deps.opPath??findOpCli,this.execOpOverride=deps.execOp,this.nowMs=deps.nowMs??Date.now}isAvailable(){return this.execOpOverride!==void 0||this.opPath()!==null}async runOp(args){if(this.execOpOverride)return this.execOpOverride(args,OP_TIMEOUT_MS);const bin=this.opPath();if(!bin)throw Object.assign(new Error("1Password CLI (op) isn't installed on your Mac."),{code:"unavailable"});return defaultExecOp(bin)(args,OP_TIMEOUT_MS)}async listAll(){const now=this.nowMs();if(this.cachedList&&now-this.cachedList.at<LIST_CACHE_TTL_MS)return this.cachedList.items;const rawText=await this.runOp(["item","list","--categories","Login","--format","json"]);let parsed;try{parsed=JSON.parse(rawText)}catch{throw new Error("Couldn't read 1Password login list.")}if(!Array.isArray(parsed))return[];const items=[];for(const entry of parsed){if(!entry||typeof entry!="object"||Array.isArray(entry))continue;const rec=entry,id=typeof rec.id=="string"?rec.id:"",title=typeof rec.title=="string"?rec.title:"";if(!ITEM_ID.test(id)||!title)continue;const vaultObj=rec.vault,vault=vaultObj&&typeof vaultObj=="object"&&typeof vaultObj.name=="string"?String(vaultObj.name):"Personal",domains=[];if(Array.isArray(rec.urls))for(const u of rec.urls){const href=u&&typeof u=="object"?u.href:null,d=typeof href=="string"?normalizeDomain(href):null;d&&!domains.includes(d)&&domains.push(d)}items.push({id,title:title.slice(0,120),vault:vault.slice(0,80),domains,hasOtp:!0})}return this.cachedList={at:now,items},items}async listMatching(currentOrigin){return this.isAvailable()?(await this.listAll()).filter(item=>domainMatchesOrigin(currentOrigin,item.domains)):[]}async fetchFieldForOrigin(itemId,currentOrigin,field){if(!ITEM_ID.test(itemId))throw Object.assign(new Error("Invalid 1Password item id."),{code:"invalid_params"});const item=(await this.listAll()).find(one=>one.id===itemId);if(!item)throw Object.assign(new Error("That 1Password login wasn't found."),{code:"not_found"});if(!domainMatchesOrigin(currentOrigin,item.domains))throw Object.assign(new Error(`Refused: "${item.title}" doesn't match the current page's origin (${currentOrigin}).`),{code:"origin_mismatch"});if(field==="otp"){const code=(await this.runOp(["item","get",itemId,"--otp"])).trim();if(!code)throw Object.assign(new Error("No one-time code is set up on that 1Password item."),{code:"not_found"});return code}const raw=await this.runOp(["item","get",itemId,"--fields",`type=${field==="password"?"concealed":"text"},purpose=${field.toUpperCase()}`,"--reveal","--format","json"]);let parsed;try{parsed=JSON.parse(raw)}catch{parsed=null}const extract=node=>{if(!node||typeof node!="object")return null;if(Array.isArray(node)){for(const item2 of node){const found=extract(item2);if(found)return found}return null}const rec=node;return typeof rec.value=="string"&&rec.value.length>0?rec.value:null},value=extract(parsed);if(value)return value;const fallback=(await this.runOp(["item","get",itemId,"--fields",`label=${field}`,"--reveal"])).trim();if(!fallback)throw Object.assign(new Error(`No ${field} stored on "${item.title}".`),{code:"not_found"});return fallback}}
|
|
1
|
+
import{execFile}from"node:child_process";import{statSync}from"node:fs";import{join}from"node:path";import{parse}from"tldts";import{withoutLeadTokenEnv}from"./names.js";const OP_TIMEOUT_MS=15e3,LIST_CACHE_TTL_MS=15e3,ITEM_ID=/^[A-Za-z0-9_-]{8,64}$/;function findOpCli(){const dirs=["/opt/homebrew/bin","/usr/local/bin","/usr/bin",...(process.env.PATH??"").split(":")];for(const d of dirs){if(!d)continue;const candidate=join(d,"op");try{if(statSync(candidate).isFile())return candidate}catch{}}return null}function normalizeDomain(raw){const trimmed=raw.trim().toLowerCase();if(!trimmed)return null;try{const host=(trimmed.includes("://")?new URL(trimmed):new URL(`https://${trimmed}`)).hostname.replace(/\.$/,"");return/^\[[0-9a-f:.]+\]$/.test(host)?host:!host||host.includes("..")||!/^[a-z0-9.-]+$/.test(host)?null:host}catch{return null}}function registrableDomain(host){const parsed=parse(host,{allowPrivateDomains:!0});return parsed.isIp!==!1||!(parsed.isIcann||parsed.isPrivate)||parsed.hostname!==host?null:parsed.domain}export function domainMatchesOrigin(currentOrigin,itemDomains){let url;try{url=new URL(currentOrigin)}catch{return!1}const host=url.hostname.replace(/\.$/,""),isLocal=host==="localhost"||host==="127.0.0.1"||host==="[::1]";if(url.protocol!=="https:"&&!(url.protocol==="http:"&&isLocal))return!1;const hostRoot=registrableDomain(host);return itemDomains.some(raw=>{const allowed=normalizeDomain(raw);if(allowed===null)return!1;const root=registrableDomain(allowed);return host===allowed||root!==null&&root===hostRoot})}function defaultExecOp(opBin){return(args,timeoutMs)=>new Promise((resolveRun,rejectRun)=>{execFile(opBin,[...args],{timeout:timeoutMs,maxBuffer:4*1024*1024,env:withoutLeadTokenEnv(process.env)},(err,stdout,stderr)=>{if(err){const msg=stderr?.trim()||err.message||"1Password CLI failed";rejectRun(new Error(msg));return}resolveRun(stdout)})})}export class CredentialBroker{opPath;execOpOverride;nowMs;cachedList=null;constructor(deps={}){this.opPath=deps.opPath??findOpCli,this.execOpOverride=deps.execOp,this.nowMs=deps.nowMs??Date.now}isAvailable(){return this.execOpOverride!==void 0||this.opPath()!==null}async runOp(args){if(this.execOpOverride)return this.execOpOverride(args,OP_TIMEOUT_MS);const bin=this.opPath();if(!bin)throw Object.assign(new Error("1Password CLI (op) isn't installed on your Mac."),{code:"unavailable"});return defaultExecOp(bin)(args,OP_TIMEOUT_MS)}async listAll(){const now=this.nowMs();if(this.cachedList&&now-this.cachedList.at<LIST_CACHE_TTL_MS)return this.cachedList.items;const rawText=await this.runOp(["item","list","--categories","Login","--format","json"]);let parsed;try{parsed=JSON.parse(rawText)}catch{throw new Error("Couldn't read 1Password login list.")}if(!Array.isArray(parsed))return[];const items=[];for(const entry of parsed){if(!entry||typeof entry!="object"||Array.isArray(entry))continue;const rec=entry,id=typeof rec.id=="string"?rec.id:"",title=typeof rec.title=="string"?rec.title:"";if(!ITEM_ID.test(id)||!title)continue;const vaultObj=rec.vault,vault=vaultObj&&typeof vaultObj=="object"&&typeof vaultObj.name=="string"?String(vaultObj.name):"Personal",domains=[];if(Array.isArray(rec.urls))for(const u of rec.urls){const href=u&&typeof u=="object"?u.href:null,d=typeof href=="string"?normalizeDomain(href):null;d&&!domains.includes(d)&&domains.push(d)}items.push({id,title:title.slice(0,120),vault:vault.slice(0,80),domains,hasOtp:!0})}return this.cachedList={at:now,items},items}async listMatching(currentOrigin){return this.isAvailable()?(await this.listAll()).filter(item=>domainMatchesOrigin(currentOrigin,item.domains)):[]}async fetchFieldForOrigin(itemId,currentOrigin,field){if(!ITEM_ID.test(itemId))throw Object.assign(new Error("Invalid 1Password item id."),{code:"invalid_params"});const item=(await this.listAll()).find(one=>one.id===itemId);if(!item)throw Object.assign(new Error("That 1Password login wasn't found."),{code:"not_found"});if(!domainMatchesOrigin(currentOrigin,item.domains))throw Object.assign(new Error(`Refused: "${item.title}" doesn't match the current page's origin (${currentOrigin}).`),{code:"origin_mismatch"});if(field==="otp"){const code=(await this.runOp(["item","get",itemId,"--otp"])).trim();if(!code)throw Object.assign(new Error("No one-time code is set up on that 1Password item."),{code:"not_found"});return code}const raw=await this.runOp(["item","get",itemId,"--fields",`type=${field==="password"?"concealed":"text"},purpose=${field.toUpperCase()}`,"--reveal","--format","json"]);let parsed;try{parsed=JSON.parse(raw)}catch{parsed=null}const extract=node=>{if(!node||typeof node!="object")return null;if(Array.isArray(node)){for(const item2 of node){const found=extract(item2);if(found)return found}return null}const rec=node;return typeof rec.value=="string"&&rec.value.length>0?rec.value:null},value=extract(parsed);if(value)return value;const fallback=(await this.runOp(["item","get",itemId,"--fields",`label=${field}`,"--reveal"])).trim();if(!fallback)throw Object.assign(new Error(`No ${field} stored on "${item.title}".`),{code:"not_found"});return fallback}}
|
package/dist/demo.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{execFileSync}from"node:child_process";import{mkdirSync,mkdtempSync,realpathSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{dirname,join}from"node:path";import{randomBytes}from"node:crypto";import{openStore}from"./store.js";import{addApprover,propose,approve}from"./scope.js";import{legOf,routeDigestOf}from"./phase-routing.js";import{acquire,release}from"./claim.js";import{register}from"./runner.js";import{createScheduledFlow}from"./flow-schedule.js";import{fileTaskProposal}from"./proposal.js";import{storeEvidence,budgetedStatJson,imageDimensions}from"./evidence.js";import{parseProof,adjudicate}from"./proof.js";import{sealVerificationReceipt}from"./verification-evidence.js";import{HANDOFF_VERSION,readHandoffArtifact}from"./contracts/handoff.js";import{parseExecutionPlanDocument,milestonesOf}from"./plan.js";import{maybeTriggerRepair}from"./dispose.js";import{deflateSync}from"node:zlib";import{FLOW_TEMPLATES}from"./flows.js";const DEMO_PROFILE={provider:"claude",model:"sonnet",permissionArgv:"auto",maxTurns:1e3,repairMaxTurns:4,timeoutSeconds:1200,timeoutKind:"idle",repairTimeoutSeconds:300,repairModel:"inherit"};function presentedRoute(store,taskRef,role,spend={provider:"claude",model:null}){const authority=store.routeAuthorityFor(taskRef,role)??store.routeAuthorityFor(taskRef,role,spend);if(authority===null||!authority.ok)throw new Error(`demo seed: ${authority===null?"no task":authority.problem}`);return{route:authority.stamp}}const DEMO_PATCH=`diff --git a/src/payout.ts b/src/payout.ts
|
|
1
|
+
import{execFileSync}from"node:child_process";import{mkdirSync,mkdtempSync,realpathSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{dirname,join}from"node:path";import{randomBytes}from"node:crypto";import{openStore}from"./store.js";import{addApprover,propose,approve}from"./scope.js";import{legOf,routeDigestOf}from"./phase-routing.js";import{acquire,release}from"./claim.js";import{register}from"./runner.js";import{createScheduledFlow}from"./flow-schedule.js";import{fileTaskProposal}from"./proposal.js";import{storeEvidence,budgetedStatJson,imageDimensions}from"./evidence.js";import{parseProof,adjudicate}from"./proof.js";import{withoutLeadTokenEnv}from"./names.js";import{sealVerificationReceipt}from"./verification-evidence.js";import{HANDOFF_VERSION,readHandoffArtifact}from"./contracts/handoff.js";import{parseExecutionPlanDocument,milestonesOf}from"./plan.js";import{maybeTriggerRepair}from"./dispose.js";import{deflateSync}from"node:zlib";import{FLOW_TEMPLATES}from"./flows.js";const DEMO_PROFILE={provider:"claude",model:"sonnet",permissionArgv:"auto",maxTurns:1e3,repairMaxTurns:4,timeoutSeconds:1200,timeoutKind:"idle",repairTimeoutSeconds:300,repairModel:"inherit"};function presentedRoute(store,taskRef,role,spend={provider:"claude",model:null}){const authority=store.routeAuthorityFor(taskRef,role)??store.routeAuthorityFor(taskRef,role,spend);if(authority===null||!authority.ok)throw new Error(`demo seed: ${authority===null?"no task":authority.problem}`);return{route:authority.stamp}}const DEMO_PATCH=`diff --git a/src/payout.ts b/src/payout.ts
|
|
2
2
|
index 3f1c2aa..9e07b41 100644
|
|
3
3
|
--- a/src/payout.ts
|
|
4
4
|
+++ b/src/payout.ts
|
|
@@ -72,7 +72,7 @@ ${b.check.stdout}
|
|
|
72
72
|
`),DEMO_BUILDING_PLAN_V1=["## Approach","Add a per-endpoint token-bucket limiter and enforce it before dispatch, reusing the existing webhook queue.","## Milestones","1. Add a per-endpoint token-bucket limiter.","2. Enforce the limiter before dispatch.","3. Add timeout budgets per endpoint.","4. Cover the limiter and budget interaction with load tests.","## Dependencies","- The existing webhook queue exposes a stable per-endpoint key.","## Risks","- A shared limiter could starve a burst-y but healthy endpoint; scope it per-endpoint from the start.","## Proof","- c1 — load-test one slow and one healthy endpoint together.",""].join(`
|
|
73
73
|
`),DEMO_BUILDING_PLAN_V2=["## Approach","Derive a stable per-endpoint key from the normalized webhook URL host, since the queue has none; add a per-endpoint token-bucket limiter keyed on it and enforce it before dispatch.","## Milestones","1. Derive a stable per-endpoint key from the normalized URL host.","2. Add a per-endpoint token-bucket limiter.","3. Enforce the limiter before dispatch.","4. Confirm the dispatch feature flag is enabled in every deploy target.","5. Add timeout budgets per endpoint.","6. Cover the limiter and budget interaction with load tests.","## Dependencies","- None found — the per-endpoint key is now derived, not assumed.","## Risks","- A shared limiter could starve a burst-y but healthy endpoint; scope it per-endpoint from the start.","## Proof","- c1 — load-test one slow and one healthy endpoint together.",""].join(`
|
|
74
74
|
`),DEMO_BUILDING_REVISION_REASON="The webhook queue has no stable per-endpoint key (src/webhooks/queue.ts) — the planned limiter needed one, so this revision derives it from the normalized URL host instead.",DEMO_BUILDING_REVISION_EVIDENCE="src/webhooks/queue.ts";function encodeDemoPng(width,height,rgb){const pixels=Buffer.alloc(width*height*3);for(let y=0;y<height;y++){const shade=Math.round(y/Math.max(1,height-1)*40);for(let x=0;x<width;x++)for(let c=0;c<3;c++)pixels[(y*width+x)*3+c]=Math.min(255,rgb[c]+shade)}return encodePngPixels(width,height,pixels)}function pngOf(width,height,raw){const crcTable=Array.from({length:256},(_,n)=>{let c=n;for(let k=0;k<8;k++)c=c&1?3988292384^c>>>1:c>>>1;return c>>>0}),crc32=buf=>{let c=4294967295;for(const byte of buf)c=crcTable[(c^byte)&255]^c>>>8;return(c^4294967295)>>>0},chunk=(type,data)=>{const len=Buffer.alloc(4);len.writeUInt32BE(data.length,0);const typed=Buffer.concat([Buffer.from(type,"ascii"),data]),crc=Buffer.alloc(4);return crc.writeUInt32BE(crc32(typed),0),Buffer.concat([len,typed,crc])},ihdr=Buffer.alloc(13);ihdr.writeUInt32BE(width,0),ihdr.writeUInt32BE(height,4),ihdr[8]=8,ihdr[9]=2;const idat=deflateSync(raw);return Buffer.concat([Buffer.from([137,80,78,71,13,10,26,10]),chunk("IHDR",ihdr),chunk("IDAT",idat),chunk("IEND",Buffer.alloc(0))])}const DEMO_SCREENSHOT_PNG=encodeDemoPng(640,400,[16,24,32]);export function seedDemo(store,repos,evidenceRoot,now){if(!store.isDemo())throw new Error("seedDemo refuses an unfenced database — stamp it demo first");const password=`demo-${randomBytes(9).toString("base64url")}`,added=addApprover(store,"demo",now,void 0,void 0,{},password);if(!added.ok)throw new Error(`demo approver: ${added.reason}`);const token=password,hoursAgo=hours=>new Date(now.getTime()-hours*36e5);store.setPhaseConfig("installation","build","claude","sonnet","demo",now),store.setPhaseConfig("installation","plan","claude","sonnet","demo",now),store.setPhaseConfig("installation","review","claude","sonnet","demo",now),store.setPhaseTierConfig("installation","build","strong","claude","opus","demo",now),store.setPhaseTierConfig("installation","review","strong","codex","gpt-5-codex","demo",now);const nightShift=register(store,{name:"night-shift-1",host:"demo",capacity:2,repos:[repos.api,repos.web],now:hoursAgo(30)});store.recordProviderReadiness("night-shift-1",[{provider:"claude",state:"unknown",reason:"installed (claude 2.1.0); no non-spending login check exists — a real run is the proof",probe:"version"},{provider:"codex",state:"ready",reason:"installed (codex 0.62.0); logged in as demo@standing-orders.dev",probe:"identity"},{provider:"openrouter",state:"unavailable",reason:"OPENROUTER_API_KEY is absent from this runner's environment",probe:"key"},{provider:"gemini",state:"unavailable",reason:"`gemini` is not installed on this runner's PATH",probe:"version"}],hoursAgo(.2));const genericAcceptance=[{id:"c1",statement:"The described change is made and verified.",how:null,evidence:["manual-review"]}],task=(id,title,repo,goal,acceptance=genericAcceptance)=>{const made=fileTaskProposal(store,{id,title,repo,...goal===void 0?{}:{goal,acceptance},filedVia:"demo"},hoursAgo(30));if(!made.ok)throw new Error(`seed task ${id}: ${made.reason}`);return made.id},run=(ref,role,leaseId,branch,worktree,at)=>store.startRun({taskRef:ref,leaseId,runner:"night-shift-1",...role==="planner"?{role}:{},branch,worktree,now:hoursAgo(at),...presentedRoute(store,ref,role)}),plannerDraft=(ref,taskId,leaseId,worktree,at,doneAt,plan)=>{const planner=run(ref,"planner",leaseId,`toolroll-plan/${taskId}`,worktree,at),artifact=storeEvidence(store,evidenceRoot,planner,"plan","plan.md",Buffer.from(plan,"utf8"),"planner handoff (verified tree) [demo: synthetic]",hoursAgo(doneAt));return store.finishRun(planner,{outcome:"built",reason:"plan-drafted",now:hoursAgo(doneAt)}),artifact},planned=task("rotate-log-format","Rotate the request-log format to JSON lines",repos.web,"Switch the request logger to JSON lines so the collector stops parsing free text. Keep the human console formatter for local dev. Migrate the two dashboards that grep the old format."),plannedRef=store.refFor("built-in",planned).id;store.editTaskRoute(plannedRef,{by:"demo",authenticate:()=>({ok:!0}),size:{size:"large",risky:!1}},hoursAgo(3.5)),store.editTaskRoute(plannedRef,{by:"demo",authenticate:()=>({ok:!0}),override:{phase:"review",provider:"claude",model:"opus"}},hoursAgo(3.2)),store.setPlanState(plannedRef,"drafted"),plannerDraft(plannedRef,planned,"demo-lease-plan",join(repos.web,".demo-worktree-plan"),3,2.8,DEMO_EXECUTION_PLAN);const asking=task("choose-retry-policy","Choose the webhook retry policy",repos.api,"Give outbound webhooks a bounded retry policy with dead-lettering.");approve(store,asking,"demo",hoursAgo(3),store.getScope(asking)?.digest??"",token);const askingRun=run(store.refFor("built-in",asking).id,"builder","demo-lease-ask",`toolroll/${asking}`,join(repos.api,".demo-worktree"),2);store.saveDecision({run:askingRun,urgency:"blocking",recap:"Retries currently hammer failing endpoints forever. The collector at partner X was down 40 minutes yesterday and we sent 8,400 attempts.",question:"How should webhook retries back off?",options:[{id:"exp",label:"Exponential, cap 1h, dead-letter after 24h",consequence:"Slowest to give up; partners see at most ~30 attempts/day.",reversible:!0},{id:"fixed",label:"Fixed 5-minute retries, dead-letter after 2h",consequence:"Faster surrender; brief outages on their side can drop events.",reversible:!0}],recommendation:"exp"},hoursAgo(1));const buildingGoal="Add per-endpoint concurrency caps and timeout budgets to webhook delivery.",building=task("harden-webhook-retries","Harden webhook delivery against slow consumers",repos.api,buildingGoal),proposedBuilding=propose(store,{profile:DEMO_PROFILE,taskId:building,goal:buildingGoal,outOfScope:"No changes to the public webhook payload shape.",touches:["src/webhooks/"],acceptance:[{id:"c1",statement:"Slow consumers cannot starve other endpoints' delivery.",how:"Load-test one slow and one healthy endpoint together.",evidence:["check"]}],now:hoursAgo(21)});approve(store,building,"demo",hoursAgo(20),proposedBuilding.digest,token);const buildingRef=store.refFor("built-in",building).id,buildingRev1Artifact=plannerDraft(buildingRef,building,"demo-lease-plan-2",join(repos.api,".demo-worktree-plan-2"),19,18.9,DEMO_BUILDING_PLAN_V1),buildingPriorRun=run(buildingRef,"builder","demo-lease-prior",`toolroll/${building}`,join(repos.api,".demo-worktree-1"),2),buildingRev2Artifact=storeEvidence(store,evidenceRoot,buildingPriorRun,"plan","revision.md",Buffer.from(DEMO_BUILDING_PLAN_V2,"utf8"),"builder-filed revision proposal [demo: synthetic]",hoursAgo(1.6)),buildingRev2Id=store.insertPlanRevision({taskRef:buildingRef,revision:2,artifact:buildingRev2Artifact,parentHash:store.getArtifact(buildingRev1Artifact)?.sha256??null,reason:DEMO_BUILDING_REVISION_REASON,evidenceLink:DEMO_BUILDING_REVISION_EVIDENCE,author:`builder:${buildingPriorRun}`,originRun:buildingPriorRun,kind:"builder-proposal",authorityKind:"plan-only",authorityDigest:"demo-authority-digest-unchanged",changedFields:[],status:"applied"},hoursAgo(1.6));store.setRunPlanRevision(buildingPriorRun,buildingRev2Id,"demo-authority-digest-unchanged"),store.finishRun(buildingPriorRun,{outcome:"refused",reason:"plan-revised",now:hoursAgo(1.6)});const liveClaim=acquire(store,buildingRef,"night-shift-1",{now:hoursAgo(.4),token:nightShift.token,ttlMs:4*36e5}),liveRun=run(buildingRef,"builder",liveClaim.ok?liveClaim.claim.leaseId:"demo-lease-live",`toolroll/${building}`,join(repos.api,".demo-worktree-2"),.4);store.setRunPlanRevision(liveRun,buildingRev2Id,"demo-authority-digest-unchanged");const buildingRev2Parsed=parseExecutionPlanDocument(DEMO_BUILDING_PLAN_V2);if(!buildingRev2Parsed.ok)throw new Error("demo building revision 2 plan is malformed");const milestoneStates=["completed","completed","current","blocked"];store.insertRunCheckpoint({run:liveRun,taskRef:buildingRef,planRevision:buildingRev2Id,snapshot:{revisionHash:store.getArtifact(buildingRev2Artifact)?.sha256??"",milestones:milestonesOf(buildingRev2Parsed.document).map((one,index)=>({id:one.id,state:milestoneStates[index]??"pending",note:index===3?"the flag is off in the staging deploy target — confirming before enforcing":null}))}},hoursAgo(.1)),store.setRunPhase(liveRun,"agent-running"),store.setTaskState(building,"running",hoursAgo(.4));const filed=(id,title,repo,scope,proposedAt,approvedAt)=>{const taskId=task(id,title,repo,scope.goal),proposed=propose(store,{profile:DEMO_PROFILE,taskId,...scope,now:hoursAgo(proposedAt)});return approve(store,taskId,"demo",hoursAgo(approvedAt),proposed.digest,token),{taskId,ref:store.refFor("built-in",taskId).id,digest:proposed.digest}},startBuild=(t,leaseId,runner,worktree,at,sealed=!1)=>{const run2=store.startRun({taskRef:t.ref,leaseId,runner,branch:`toolroll/${t.taskId}`,worktree,now:hoursAgo(at),...sealed?sealedRoute(store,t.taskId):presentedRoute(store,t.ref,"builder")});return store.stampRun(run2,{baseRevision:ZERO_TREE,scopeDigest:t.digest}),run2},times=(...hours)=>hours.map(hoursAgo),done=filed("fix-payout-rounding","Fix the payout rounding drift",repos.api,{goal:"Find and fix the half-cent drift in payout settlement; prove it with ledger-fixture tests.",outOfScope:"No ledger schema changes.",touches:["src/payout.ts","src/payout.test.ts"],acceptance:[{id:"c1",statement:"Ledger-fixture tests demonstrate the half-cent drift is gone.",how:null,evidence:["check","changed-path"]},{id:"c2",statement:"The human console formatter still renders payout dashboards.",how:null,evidence:["screenshot"]}]},27,26),doneCheck=store.setVerifyCommand({repo:store.refFor("built-in",done.taskId).repo??repos.api,command:DEMO_CHECK_COMMAND,timeoutMs:12e4,approvedBy:"demo"},hoursAgo(26)),doneRun=startBuild(done,"demo-lease-done","night-shift-2",join(repos.api,".demo-worktree-3"),9,!0);recordDemoBuild(store,evidenceRoot,doneRun,done.taskId,{head:DONE_HEAD,patch:DEMO_PATCH,files:[["src/payout.ts",4,1],["src/payout.test.ts",9,0]],handoff:built({conclusion:"Fixed the payout rounding drift: settle() now rounds at cent precision instead of accumulating half-cent errors. Added boundary tests against the ledger fixtures. All 214 tests pass.",changes:["Rounded settlement values at cent precision in src/payout.ts.","Added ledger-fixture coverage for half-cent boundaries."],verification:["All 214 tests pass, including the new rounding boundary cases."],decisions:["Rounded each line at cent precision in settle(), not when the total is displayed."],assumptions:["The ledger fixtures cover every currency payouts are made in."],risks:["Totals for settlements already paid at the old precision are not recalculated."]}),proof:proofOf([met("c1","Ledger-fixture tests demonstrate the half-cent drift is gone.","Added and ran boundary tests against the ledger fixtures.",[["check","npm test"],["changed-path","src/payout.ts"],["changed-path","src/payout.test.ts"]]),met("c2","The human console formatter still renders payout dashboards.","Ran the dashboard's own snapshot tests.",[["screenshot","evidence/payout-dashboard.png"]])],["src/payout.ts","src/payout.test.ts"],{checks:[{command:"npm test",exitCode:0,summary:"214 tests passed, including the new rounding boundary cases."}],screenshots:[{path:"evidence/payout-dashboard.png",caption:"Payout dashboard after the fix — totals match the ledger."}]}),at:times(8.5,8.4,8.4),facts:{handoff:!0},verified:!0,screenshot:{png:DEMO_SCREENSHOT_PNG,claimed:"evidence/payout-dashboard.png",file:"screenshot-demo.png"},check:{stdout:`214 tests passed.
|
|
75
|
-
`,command:doneCheck}}),store.addRunNote(doneRun,"demo","Reviewed the diff — the fixture numbers check out. Shipping.",hoursAgo(3));const failed=filed("retire-legacy-flag","Retire the legacy payout feature flag",repos.api,{goal:"Remove LEGACY_PAYOUT and every branch behind it.",acceptance:[{id:"c1",statement:"No reference to LEGACY_PAYOUT remains in the codebase.",how:null,evidence:["changed-path"]}]},16,15);recordDemoBuild(store,evidenceRoot,startBuild(failed,"demo-lease-failed","night-shift-2",join(repos.api,".demo-worktree-4"),6),failed.taskId,{head:"5a1f0c7e2b9d4e6f8a0b1c2d3e4f5a6b7c8d9e0f",patch:DEMO_FAILED_PATCH,files:[["src/payout.ts",1,5],["src/config.ts",0,2]],handoff:built({conclusion:"Removed LEGACY_PAYOUT from settlement and config. The admin override still reads it, so one reference remains.",changes:["Dropped the legacy settlement branch in src/payout.ts.","Removed the LEGACY_PAYOUT flag from src/config.ts."],verification:["Searched the codebase for LEGACY_PAYOUT after the change."]}),proof:proofOf([met("c1","No reference to LEGACY_PAYOUT remains in the codebase.","Removed the flag and the settlement branch behind it.",[["changed-path","src/payout.ts"],["changed-path","src/config.ts"]])],["src/payout.ts","src/config.ts"],{caveats:["c1: src/admin/overrides.ts still reads LEGACY_PAYOUT for the per-merchant override toggle, so one reference remains."]}),at:times(5.6,5.6,5.5),facts:{},failed:!0});const copy=filed("confirm-empty-state-copy","Confirm the new inbox empty-state copy reads well",repos.web,{goal:"Rewrite the inbox's empty-state copy so it explains why nothing is there yet.",acceptance:[{id:"c1",statement:"The new empty-state copy reads clearly.",how:"Open the inbox pane with zero items and read it.",evidence:["manual-review"]}]},10,9);recordDemoBuild(store,evidenceRoot,startBuild(copy,"demo-lease-copy","night-shift-1",join(repos.web,".demo-worktree-5"),4),copy.taskId,{head:"1c2d3e4f52aa01c9f3d7700e54bf8d69288fbe99",patch:DEMO_COPY_PATCH,files:[["src/inbox-copy.ts",3,1]],handoff:built({conclusion:"Rewrote the inbox's empty-state copy so it explains why the list is empty instead of just saying so.",changes:["Replaced the empty-state body copy in src/inbox-copy.ts."],verification:["Opened the inbox pane with zero items and read the new copy."],decisions:["Kept the copy to one sentence and a link to filters, with no illustration."],assumptions:["An empty inbox usually means a filter is on, not that there is no mail."],notDone:["The copy is English only; the other locales still show the old line."]}),proof:proofOf([met("c1","The new empty-state copy reads clearly.","Opened the inbox pane with zero items and read the new copy aloud.",[["manual-review","read the new copy in src/inbox-copy.ts"]])],["src/inbox-copy.ts"]),at:times(3.6,3.5,3.5),facts:{handoff:!0}});const reviewed=filed("guard-payout-limiter","Guard the payout limiter against concurrent settlement",repos.api,{goal:"Add a per-account concurrency guard so two settlements never race the same payout limiter.",outOfScope:"No changes to the limiter's public API.",touches:["src/payout-limiter.ts"],acceptance:[{id:"c1",statement:"Two concurrent settlements for the same account cannot both pass the limiter.",how:"Read the guard; an independent reviewer confirms it actually locks.",evidence:["manual-review"]},{id:"c2",statement:"The existing limiter tests still pass.",how:null,evidence:["check"]}]},6,5.8),reviewedRun=startBuild(reviewed,"demo-lease-reviewed","night-shift-1",join(repos.api,".demo-worktree-4"),5),reviewedArtifacts=recordDemoBuild(store,evidenceRoot,reviewedRun,reviewed.taskId,{head:"aa11bb22cc33dd44ee55ff6600112233445566aa",patch:DEMO_REPAIR_PATCH,files:[["src/payout-limiter.ts",1,0]],handoff:built({conclusion:"Added a TODO comment marking the per-account lock — ran out of turns before wiring the actual guard.",changes:["Marked the per-account lock in src/payout-limiter.ts."],verification:[]}),proof:proofOf([met("c1","Two concurrent settlements for the same account cannot both pass the limiter.","Added the lock.",[["manual-review","see src/payout-limiter.ts"]]),met("c2","The existing limiter tests still pass.","npm test",[["check","npm test"]])],["src/payout-limiter.ts"],{checks:[{command:"npm test",exitCode:0,summary:"214 tests passed."}]}),at:times(4.6,4.5,4.4),captureStatus:!0,verified:!0}),reviewAsked=store.requestReview(reviewedRun,"alex",hoursAgo(3.95));if(!reviewAsked.ok)throw new Error(`demo: the seeded review could not be requested (${reviewAsked.reason})`);const reviewerRun=store.startRun({taskRef:reviewed.ref,leaseId:"demo-lease-reviewer",runner:"night-shift-1",role:"reviewer",parentRun:reviewedRun,request:reviewAsked.id,provider:"codex",now:hoursAgo(3.9),...presentedRoute(store,reviewed.ref,"reviewer")}),reviewedProofSha=store.getArtifact(reviewedArtifacts.proof)?.sha256??null;store.stampProviderStart(reviewerRun,hoursAgo(3.9));const{folded}=store.ingestReview({reviewerRunId:reviewerRun,runId:reviewedRun,artifactId:reviewedArtifacts.diff,author:"reviewer:codex",comments:[{path:"src/payout-limiter.ts",line:1,note:"This is a TODO, not a lock — two concurrent calls both still read the same rate before either settles.",severity:"problem"}],judgements:[{id:"c1",judgement:"contradicts",note:"The diff adds a TODO comment, not an actual lock — two concurrent settlements still race the limiter."},{id:"c2",judgement:"upholds",note:"The stored check log supports that the existing limiter test suite still passes."}],bindings:{diffSha:store.getArtifact(reviewedArtifacts.diff)?.sha256??"",scopeDigest:reviewed.digest,headSha:store.getRun(reviewedRun)?.headRevision??store.getRun(reviewedRun)?.baseRevision??null,proof:reviewedProofSha===null?null:{artifactId:reviewedArtifacts.proof,sha256:reviewedProofSha},checkLog:null,screenshots:[]}},hoursAgo(3.9));if(folded===null)throw new Error("seed reviewed+repaired: the fold produced nothing");const repairTrigger=maybeTriggerRepair(store,repos.api,evidenceRoot,reviewedRun,folded.verdict,hoursAgo(3.9));if(repairTrigger.kind!=="drafted")throw new Error(`seed reviewed+repaired: expected a draft, got ${repairTrigger.kind}`);task("design-tokens","Extract the design tokens package",repos.web),task("ship-dark-mode","Ship dark mode",repos.web),store.addEdge("ship-dark-mode","design-tokens",{}),store.cancelTask("design-tokens",hoursAgo(10),"the token package was superseded");const held=task("migrate-billing","Migrate billing exports to the new vendor",repos.api);store.hold(store.refFor("built-in",held).id,"waiting on the vendor sandbox account",null,hoursAgo(12));const nightly=createScheduledFlow(store,{repo:realpathSync(repos.api),name:"Nightly dependency refresh",stem:"nightly-deps",schedule:"daily:03:30",by:"demo",terms:{goal:"Refresh the lockfile within existing ranges, run the suite, summarize anything notable.",outOfScope:"No major version bumps.",touches:[],requirements:[],budgetPerRunMicrousd:null,costCeilingUsd:null,acceptance:[{id:"c1",statement:"The full test suite passes against the refreshed lockfile.",how:null,evidence:["check"]}]}},hoursAgo(70));if(!nightly.ok)throw new Error(`seed scheduled flow: ${nightly.message}`);const pub=store.createPublicationIntent({run:doneRun,taskRef:done.ref,githubRepo:"acme/payments-api",remote:"origin",base:"main",head:`toolroll/${done.taskId}`,headSha:DONE_HEAD,bodyHash:"demo",draft:!1},hoursAgo(8.3));return store.markPublicationPushed(pub,hoursAgo(8.2)),store.markPublicationOpened(pub,47,"https://github.com/acme/payments-api/pull/47",hoursAgo(8.1)),store.recordPublicationCheckState(pub,"passing",hoursAgo(1.5)),seedDemoFlows(store,repos.web,now),{login:{name:"demo",password},repos:[repos.api,repos.web]}}export function makeDemoRepos(root){const make=(name,files)=>{const dir=join(root,name);mkdirSync(join(dir,"src"),{recursive:!0});for(const[file,content]of Object.entries(files))mkdirSync(dirname(join(dir,file)),{recursive:!0}),writeFileSync(join(dir,file),content);try{for(const args of[["init","-q","-b","main"],["add","-A"],["-c","user.email=demo@localhost","-c","user.name=demo","commit","-q","-m","seed"]])execFileSync("git",args,{cwd:dir,stdio:"ignore",timeout:3e4})}catch{}return dir};return{api:make("payments-api",{"package.json":JSON.stringify({name:"payments-api",private:!0},null,2),"src/payout.ts":`export function settle(cents: number, rate: number): number {
|
|
75
|
+
`,command:doneCheck}}),store.addRunNote(doneRun,"demo","Reviewed the diff — the fixture numbers check out. Shipping.",hoursAgo(3));const failed=filed("retire-legacy-flag","Retire the legacy payout feature flag",repos.api,{goal:"Remove LEGACY_PAYOUT and every branch behind it.",acceptance:[{id:"c1",statement:"No reference to LEGACY_PAYOUT remains in the codebase.",how:null,evidence:["changed-path"]}]},16,15);recordDemoBuild(store,evidenceRoot,startBuild(failed,"demo-lease-failed","night-shift-2",join(repos.api,".demo-worktree-4"),6),failed.taskId,{head:"5a1f0c7e2b9d4e6f8a0b1c2d3e4f5a6b7c8d9e0f",patch:DEMO_FAILED_PATCH,files:[["src/payout.ts",1,5],["src/config.ts",0,2]],handoff:built({conclusion:"Removed LEGACY_PAYOUT from settlement and config. The admin override still reads it, so one reference remains.",changes:["Dropped the legacy settlement branch in src/payout.ts.","Removed the LEGACY_PAYOUT flag from src/config.ts."],verification:["Searched the codebase for LEGACY_PAYOUT after the change."]}),proof:proofOf([met("c1","No reference to LEGACY_PAYOUT remains in the codebase.","Removed the flag and the settlement branch behind it.",[["changed-path","src/payout.ts"],["changed-path","src/config.ts"]])],["src/payout.ts","src/config.ts"],{caveats:["c1: src/admin/overrides.ts still reads LEGACY_PAYOUT for the per-merchant override toggle, so one reference remains."]}),at:times(5.6,5.6,5.5),facts:{},failed:!0});const copy=filed("confirm-empty-state-copy","Confirm the new inbox empty-state copy reads well",repos.web,{goal:"Rewrite the inbox's empty-state copy so it explains why nothing is there yet.",acceptance:[{id:"c1",statement:"The new empty-state copy reads clearly.",how:"Open the inbox pane with zero items and read it.",evidence:["manual-review"]}]},10,9);recordDemoBuild(store,evidenceRoot,startBuild(copy,"demo-lease-copy","night-shift-1",join(repos.web,".demo-worktree-5"),4),copy.taskId,{head:"1c2d3e4f52aa01c9f3d7700e54bf8d69288fbe99",patch:DEMO_COPY_PATCH,files:[["src/inbox-copy.ts",3,1]],handoff:built({conclusion:"Rewrote the inbox's empty-state copy so it explains why the list is empty instead of just saying so.",changes:["Replaced the empty-state body copy in src/inbox-copy.ts."],verification:["Opened the inbox pane with zero items and read the new copy."],decisions:["Kept the copy to one sentence and a link to filters, with no illustration."],assumptions:["An empty inbox usually means a filter is on, not that there is no mail."],notDone:["The copy is English only; the other locales still show the old line."]}),proof:proofOf([met("c1","The new empty-state copy reads clearly.","Opened the inbox pane with zero items and read the new copy aloud.",[["manual-review","read the new copy in src/inbox-copy.ts"]])],["src/inbox-copy.ts"]),at:times(3.6,3.5,3.5),facts:{handoff:!0}});const reviewed=filed("guard-payout-limiter","Guard the payout limiter against concurrent settlement",repos.api,{goal:"Add a per-account concurrency guard so two settlements never race the same payout limiter.",outOfScope:"No changes to the limiter's public API.",touches:["src/payout-limiter.ts"],acceptance:[{id:"c1",statement:"Two concurrent settlements for the same account cannot both pass the limiter.",how:"Read the guard; an independent reviewer confirms it actually locks.",evidence:["manual-review"]},{id:"c2",statement:"The existing limiter tests still pass.",how:null,evidence:["check"]}]},6,5.8),reviewedRun=startBuild(reviewed,"demo-lease-reviewed","night-shift-1",join(repos.api,".demo-worktree-4"),5),reviewedArtifacts=recordDemoBuild(store,evidenceRoot,reviewedRun,reviewed.taskId,{head:"aa11bb22cc33dd44ee55ff6600112233445566aa",patch:DEMO_REPAIR_PATCH,files:[["src/payout-limiter.ts",1,0]],handoff:built({conclusion:"Added a TODO comment marking the per-account lock — ran out of turns before wiring the actual guard.",changes:["Marked the per-account lock in src/payout-limiter.ts."],verification:[]}),proof:proofOf([met("c1","Two concurrent settlements for the same account cannot both pass the limiter.","Added the lock.",[["manual-review","see src/payout-limiter.ts"]]),met("c2","The existing limiter tests still pass.","npm test",[["check","npm test"]])],["src/payout-limiter.ts"],{checks:[{command:"npm test",exitCode:0,summary:"214 tests passed."}]}),at:times(4.6,4.5,4.4),captureStatus:!0,verified:!0}),reviewAsked=store.requestReview(reviewedRun,"alex",hoursAgo(3.95));if(!reviewAsked.ok)throw new Error(`demo: the seeded review could not be requested (${reviewAsked.reason})`);const reviewerRun=store.startRun({taskRef:reviewed.ref,leaseId:"demo-lease-reviewer",runner:"night-shift-1",role:"reviewer",parentRun:reviewedRun,request:reviewAsked.id,provider:"codex",now:hoursAgo(3.9),...presentedRoute(store,reviewed.ref,"reviewer")}),reviewedProofSha=store.getArtifact(reviewedArtifacts.proof)?.sha256??null;store.stampProviderStart(reviewerRun,hoursAgo(3.9));const{folded}=store.ingestReview({reviewerRunId:reviewerRun,runId:reviewedRun,artifactId:reviewedArtifacts.diff,author:"reviewer:codex",comments:[{path:"src/payout-limiter.ts",line:1,note:"This is a TODO, not a lock — two concurrent calls both still read the same rate before either settles.",severity:"problem"}],judgements:[{id:"c1",judgement:"contradicts",note:"The diff adds a TODO comment, not an actual lock — two concurrent settlements still race the limiter."},{id:"c2",judgement:"upholds",note:"The stored check log supports that the existing limiter test suite still passes."}],bindings:{diffSha:store.getArtifact(reviewedArtifacts.diff)?.sha256??"",scopeDigest:reviewed.digest,headSha:store.getRun(reviewedRun)?.headRevision??store.getRun(reviewedRun)?.baseRevision??null,proof:reviewedProofSha===null?null:{artifactId:reviewedArtifacts.proof,sha256:reviewedProofSha},checkLog:null,screenshots:[]}},hoursAgo(3.9));if(folded===null)throw new Error("seed reviewed+repaired: the fold produced nothing");const repairTrigger=maybeTriggerRepair(store,repos.api,evidenceRoot,reviewedRun,folded.verdict,hoursAgo(3.9));if(repairTrigger.kind!=="drafted")throw new Error(`seed reviewed+repaired: expected a draft, got ${repairTrigger.kind}`);task("design-tokens","Extract the design tokens package",repos.web),task("ship-dark-mode","Ship dark mode",repos.web),store.addEdge("ship-dark-mode","design-tokens",{}),store.cancelTask("design-tokens",hoursAgo(10),"the token package was superseded");const held=task("migrate-billing","Migrate billing exports to the new vendor",repos.api);store.hold(store.refFor("built-in",held).id,"waiting on the vendor sandbox account",null,hoursAgo(12));const nightly=createScheduledFlow(store,{repo:realpathSync(repos.api),name:"Nightly dependency refresh",stem:"nightly-deps",schedule:"daily:03:30",by:"demo",terms:{goal:"Refresh the lockfile within existing ranges, run the suite, summarize anything notable.",outOfScope:"No major version bumps.",touches:[],requirements:[],budgetPerRunMicrousd:null,costCeilingUsd:null,acceptance:[{id:"c1",statement:"The full test suite passes against the refreshed lockfile.",how:null,evidence:["check"]}]}},hoursAgo(70));if(!nightly.ok)throw new Error(`seed scheduled flow: ${nightly.message}`);const pub=store.createPublicationIntent({run:doneRun,taskRef:done.ref,githubRepo:"acme/payments-api",remote:"origin",base:"main",head:`toolroll/${done.taskId}`,headSha:DONE_HEAD,bodyHash:"demo",draft:!1},hoursAgo(8.3));return store.markPublicationPushed(pub,hoursAgo(8.2)),store.markPublicationOpened(pub,47,"https://github.com/acme/payments-api/pull/47",hoursAgo(8.1)),store.recordPublicationCheckState(pub,"passing",hoursAgo(1.5)),seedDemoFlows(store,repos.web,now),{login:{name:"demo",password},repos:[repos.api,repos.web]}}export function makeDemoRepos(root){const make=(name,files)=>{const dir=join(root,name);mkdirSync(join(dir,"src"),{recursive:!0});for(const[file,content]of Object.entries(files))mkdirSync(dirname(join(dir,file)),{recursive:!0}),writeFileSync(join(dir,file),content);try{for(const args of[["init","-q","-b","main"],["add","-A"],["-c","user.email=demo@localhost","-c","user.name=demo","commit","-q","-m","seed"]])execFileSync("git",args,{cwd:dir,stdio:"ignore",timeout:3e4,env:withoutLeadTokenEnv(process.env)})}catch{}return dir};return{api:make("payments-api",{"package.json":JSON.stringify({name:"payments-api",private:!0},null,2),"src/payout.ts":`export function settle(cents: number, rate: number): number {
|
|
76
76
|
return Math.round(cents * rate * 100) / 100;
|
|
77
77
|
}
|
|
78
78
|
`,...demoLeadFiles("payments-api")}),web:make("web-console",{"package.json":JSON.stringify({name:"web-console",private:!0},null,2),"src/app.ts":`export const app = () => 'hello';
|
package/dist/easy-start.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{spawn}from"node:child_process";import{existsSync,realpathSync}from"node:fs";import{dirname,resolve}from"node:path";import{instanceSocketTooLong,requestLocalLink}from"./console-instance.js";import{backgroundInstalled,backgroundOn,startInstalledService}from"./laptop-background.js";import{proveConsoleReadOnly}from"./quick-start.js";import{backgroundAsked,installationCreatedBy,localModeCandidate,localModeOf,openStore,openStoreReadOnly,recordBackgroundAsked}from"./store.js";import{underAgent}from"./prompt.js";import{savedLoginFile}from"./login-secrets.js";const PROVE_EVERY_MS=50;export{easyStartApplies,easyStartArgs}from"./easy-start-args.js";export const SIGN_IN_HANDOFF_MS=6e4;const EXIT={ok:0,failed:1,usage:2,refused:3};export const UP_STOPPED_LINE="Toolroll's background worker stopped. Run `toolroll --verbose` to see why.",START_OVER_POINTER="This Toolroll was set up with a password. To start over without one: https://github.com/ap9000/toolroll/blob/main/docs/guide/linux.md#start-over-without-a-password";export async function runEasyStart(mode,args,seams){const{write}=seams,port=args.port===void 0||args.port===null?null:Number(args.port);if(port!==null&&(!/^[0-9]{1,5}$/.test(args.port)||port<1||port>65535))return write("--port is a whole number from 1 to 65535."),EXIT.usage;const rootArgs=[...args.projectRoot===null?[]:["--project-root",args.projectRoot],...port===null?[]:["--port",String(port)],...args.verbose===!0?["--verbose"]:[]],elsewhere=proof2=>{port!==null&&proof2.ok&&proof2.port!==port&&write(`Toolroll is already set up on port ${proof2.port}, so it opens there.`)},sleep=seams.sleep??(ms=>new Promise(resolve2=>setTimeout(resolve2,ms))),first=await seams.prove();if(!first.ok&&first.state==="refused")return write(`Toolroll can't open: ${first.message}.`),EXIT.refused;const refusedTooDeep=()=>{if(first.ok||args.web&&!seams.serviceInstalled())return!1;const deep=seams.socketProblem();return deep===null?!1:(write(`Toolroll can't start: ${deep}.`),!0)},joinRepo=async()=>{if(mode!=="start")return EXIT.ok;const found=await seams.findRepo(seams.cwd);if(found===null)return EXIT.ok;let repo=found;try{repo=realpathSync(found)}catch{}return await seams.enrolled(repo)?EXIT.ok:seams.admit(repo)};let local=seams.localMode();if((local==="candidate"||local==="absent")&&!first.ok&&first.state==="none"){if(refusedTooDeep())return EXIT.refused;const sandbox=await seams.sandbox(),others=await(seams.prerequisites?.()??Promise.resolve({blockers:[],advisories:[]})),blockers=[];let passwordInstead=!1;if(sandbox.missing.length>0){const{missingSandboxToolsWords}=await import("./sandbox-runtime.js");blockers.push(missingSandboxToolsWords(sandbox.missing))}else if(sandbox.problem!==null){const{UNCONFINED_OPT_IN}=await import("./sandbox-runtime.js");blockers.push([`Agents can't run in a sandbox here: ${sandbox.problem}.`,...(sandbox.repair??[]).filter(line=>line!==UNCONFINED_OPT_IN)]),passwordInstead=others.blockers.length===0}if(blockers.push(...others.blockers),blockers.length>0){if(blockers.length===1){for(const line of blockers[0])write(line);sandbox.missing.length===0&&sandbox.problem!==null&&write("Then run toolroll again.")}else write("Toolroll can't start on this computer yet. Fix these, then run toolroll again:"),blockers.forEach((lines,index)=>lines.forEach((line,at)=>write(at===0?`${index+1}. ${line}`:` ${line}`)));passwordInstead&&write("To start now with a password instead, run `toolroll up`. Agents then run only once the sandbox works, or if an instance operator lets them run without OS confinement (`toolroll config unconfined-agents allow`).");for(const line of others.advisories)write(line);return EXIT.refused}await seams.initLocal()&&(local="on")}if(local==="candidate"&&(local="off"),local!=="off"&&refusedTooDeep())return EXIT.refused;if(local==="off"){if(seams.passwordByLaptopStart()&&write(START_OVER_POINTER),!first.ok)return seams.runUpForeground(rootArgs);const joined=await joinRepo();return joined!==EXIT.ok?joined:(elsewhere(first),write(`Toolroll is on ${first.url}`),await seams.openBrowser(first.url),EXIT.ok)}if(args.web&&!first.ok&&!seams.serviceInstalled())return seams.runUpForeground(["--laptop",...rootArgs]);let owned=null;const stoppedHere=new Set,exitCodes=new Map,stopOwned=child=>{stoppedHere.add(child),child.stop()},stoppedOnItsOwn=()=>{const child=owned;if(child===null||child.running()||stoppedHere.has(child))return null;const code=exitCodes.get(child);return typeof code=="number"&&code!==0?UP_STOPPED_LINE:null},upArgs=["--laptop","--no-open",...rootArgs],startOwned=async()=>{const child=seams.spawnUp(upArgs);owned=child,child.exited.then(code=>{exitCodes.set(child,code)});const deadline=Date.now()+(seams.startTimeoutMs??9e4);for(;;){const proof2=await seams.prove();if(proof2.ok)return proof2;if(!child.running()){const last=child.tail().filter(line=>line.trim()!=="").slice(-3).join(" — ");return{ok:!1,state:"refused",message:last===""?"it stopped while starting":last}}if(Date.now()>=deadline)return stopOwned(child),{ok:!1,state:"refused",message:"it didn't answer in time"};await sleep(PROVE_EVERY_MS)}};let proof=first;if(proof.ok){const joined=await joinRepo();if(joined!==EXIT.ok)return joined}else if(globalThis[Symbol.for("toolroll.starting-said")]!==!0&&write("Starting Toolroll…"),proof=seams.serviceInstalled()?await seams.startService():await startOwned(),!proof.ok)return write(`Toolroll didn't start: ${proof.message}.`),EXIT.failed;elsewhere(proof);const url=proof.url,ownedNow=()=>owned!==null&&owned.running()?owned:null,waitOwned=async()=>{const child=ownedNow();return child===null||(write("Ctrl-C stops it."),await child.exited),EXIT.ok};if(seams.localMode()!=="on"){const{problem,repair}=await seams.sandbox();if(problem!==null&&write(`Toolroll can't start without a password here: ${problem}.`),problem!==null)for(const line of repair??[])write(line);const saved=seams.savedLogin();return write(saved===null?`Toolroll is on ${url}. Sign in with your password.`:`Toolroll is on ${url}. Your password: run \`cat -- '${saved.replaceAll("'","'\\''")}'\``),await seams.openBrowser(url),waitOwned()}if(args.web){const opened=await seams.openSignedIn();if(!opened.ok){write(`Toolroll is on ${url}, but it couldn't sign you in: ${opened.message}.`),write(`Run \`toolroll\` to use it in this terminal.${opened.message.includes("toolroll password set")?"":" To use a browser, run `toolroll password set` and sign in with that password."}`);const child=ownedNow();return child!==null&&stopOwned(child),EXIT.refused}return write(`Toolroll is on ${url}`),ownedNow()===null?(write("Opening Toolroll in your browser…"),await opened.wait(SIGN_IN_HANDOFF_MS),EXIT.ok):waitOwned()}const handoff=async()=>{const child=ownedNow();child!==null&&stoppedHere.add(child);const result=await seams.backgroundOn(child===null?null:{controllerPid:child.pid,restart:async()=>{const again=await startOwned();if(!again.ok)throw Error(again.message)}});return result.ok&&(owned=null),result.message},session={owned:()=>ownedNow()!==null,stopped:stoppedOnItsOwn,openBuilderPassword:async(task,setup)=>{const page=`/t/${encodeURIComponent(task)}`,target=new URL(setup?"/password/set":`${page}#agents`,url);return setup&&target.searchParams.set("next",page),await seams.openBrowser(target.href)===!1?`Open ${target.href} in a browser, then Agents → Change agents and save the new builder.`:"In the browser, open Agents → Change agents and save the new builder."},openBrowser:async page=>{const{isTuiPage}=await import("./tui-contract.js");if(page!==void 0&&!isTuiPage(page))return"That browser page is unavailable.";if(page?.startsWith("/t/")===!0){if((await seams.openSignedIn(page)).ok)return"Opened in your browser.";const href=new URL(page,url).href;return await seams.openBrowser(href)===!1?`Open ${href} in a browser.`:"Opened Task in your browser."}if(page==="projects"||page==="lead-providers"){const href=new URL(page==="projects"?"/projects":"/settings/lead#lead-config",url).href;return await seams.openBrowser(href)===!1?`Open ${href} in a browser.`:`Opened ${page==="projects"?"Projects":"Lead settings"} in your browser.`}const opened=await seams.openSignedIn(page);return opened.ok?"Opened in your browser.":`The browser couldn't be opened: ${opened.message}.`},shouldAskBackground:()=>ownedNow()!==null&&!seams.serviceInstalled()&&!seams.backgroundAsked(),answerBackground:async yes=>(seams.recordBackgroundAnswer(yes),yes?handoff():"Okay. To change your mind later, run `toolroll background on`.")},exit=await seams.openTui(session),ended=owned;ended!==null&&!ended.running()&&await ended.exited;const died=stoppedOnItsOwn();if(died!==null){if(args.verbose===!0)for(const line of ended?.tail()??[])write(line);return write(died),EXIT.failed}if(ownedNow()!==null){if(exit==="keep"){const said=await handoff();if(write(said),ownedNow()===null)return write("Reopen with: toolroll"),EXIT.ok}const child=ownedNow();child!==null&&(write("Stopping Toolroll… (running work is saved)"),stopOwned(child),await child.exited,write("Toolroll stopped."))}return write("Reopen with: toolroll"),EXIT.ok}export function spawnOwnedUp(args,options){const entry=options.entry??process.argv[1];if(entry===void 0)throw Error("can't find Toolroll's own command to start it");const child=spawn(process.execPath,[...process.execArgv,entry,"up",...args,"--db",options.databaseFile],{cwd:options.cwd,stdio:["ignore","pipe","pipe","ipc"]}),lines=[],keep=chunk=>{for(const line of String(chunk).split(`
|
|
1
|
+
import{spawn}from"node:child_process";import{existsSync,realpathSync}from"node:fs";import{dirname,resolve}from"node:path";import{instanceSocketTooLong,requestLocalLink}from"./console-instance.js";import{backgroundInstalled,backgroundOn,startInstalledService}from"./laptop-background.js";import{proveConsoleReadOnly}from"./quick-start.js";import{backgroundAsked,installationCreatedBy,localModeCandidate,localModeOf,openStore,openStoreReadOnly,recordBackgroundAsked}from"./store.js";import{underAgent}from"./prompt.js";import{savedLoginFile}from"./login-secrets.js";import{withoutLeadTokenEnv}from"./names.js";const PROVE_EVERY_MS=50;export{easyStartApplies,easyStartArgs}from"./easy-start-args.js";export const SIGN_IN_HANDOFF_MS=6e4;const EXIT={ok:0,failed:1,usage:2,refused:3};export const UP_STOPPED_LINE="Toolroll's background worker stopped. Run `toolroll --verbose` to see why.",START_OVER_POINTER="This Toolroll was set up with a password. To start over without one: https://github.com/ap9000/toolroll/blob/main/docs/guide/linux.md#start-over-without-a-password";export async function runEasyStart(mode,args,seams){const{write}=seams,port=args.port===void 0||args.port===null?null:Number(args.port);if(port!==null&&(!/^[0-9]{1,5}$/.test(args.port)||port<1||port>65535))return write("--port is a whole number from 1 to 65535."),EXIT.usage;const rootArgs=[...args.projectRoot===null?[]:["--project-root",args.projectRoot],...port===null?[]:["--port",String(port)],...args.verbose===!0?["--verbose"]:[]],elsewhere=proof2=>{port!==null&&proof2.ok&&proof2.port!==port&&write(`Toolroll is already set up on port ${proof2.port}, so it opens there.`)},sleep=seams.sleep??(ms=>new Promise(resolve2=>setTimeout(resolve2,ms))),first=await seams.prove();if(!first.ok&&first.state==="refused")return write(`Toolroll can't open: ${first.message}.`),EXIT.refused;const refusedTooDeep=()=>{if(first.ok||args.web&&!seams.serviceInstalled())return!1;const deep=seams.socketProblem();return deep===null?!1:(write(`Toolroll can't start: ${deep}.`),!0)},joinRepo=async()=>{if(mode!=="start")return EXIT.ok;const found=await seams.findRepo(seams.cwd);if(found===null)return EXIT.ok;let repo=found;try{repo=realpathSync(found)}catch{}return await seams.enrolled(repo)?EXIT.ok:seams.admit(repo)};let local=seams.localMode();if((local==="candidate"||local==="absent")&&!first.ok&&first.state==="none"){if(refusedTooDeep())return EXIT.refused;const sandbox=await seams.sandbox(),others=await(seams.prerequisites?.()??Promise.resolve({blockers:[],advisories:[]})),blockers=[];let passwordInstead=!1;if(sandbox.missing.length>0){const{missingSandboxToolsWords}=await import("./sandbox-runtime.js");blockers.push(missingSandboxToolsWords(sandbox.missing))}else if(sandbox.problem!==null){const{UNCONFINED_OPT_IN}=await import("./sandbox-runtime.js");blockers.push([`Agents can't run in a sandbox here: ${sandbox.problem}.`,...(sandbox.repair??[]).filter(line=>line!==UNCONFINED_OPT_IN)]),passwordInstead=others.blockers.length===0}if(blockers.push(...others.blockers),blockers.length>0){if(blockers.length===1){for(const line of blockers[0])write(line);sandbox.missing.length===0&&sandbox.problem!==null&&write("Then run toolroll again.")}else write("Toolroll can't start on this computer yet. Fix these, then run toolroll again:"),blockers.forEach((lines,index)=>lines.forEach((line,at)=>write(at===0?`${index+1}. ${line}`:` ${line}`)));passwordInstead&&write("To start now with a password instead, run `toolroll up`. Agents then run only once the sandbox works, or if an instance operator lets them run without OS confinement (`toolroll config unconfined-agents allow`).");for(const line of others.advisories)write(line);return EXIT.refused}await seams.initLocal()&&(local="on")}if(local==="candidate"&&(local="off"),local!=="off"&&refusedTooDeep())return EXIT.refused;if(local==="off"){if(seams.passwordByLaptopStart()&&write(START_OVER_POINTER),!first.ok)return seams.runUpForeground(rootArgs);const joined=await joinRepo();return joined!==EXIT.ok?joined:(elsewhere(first),write(`Toolroll is on ${first.url}`),await seams.openBrowser(first.url),EXIT.ok)}if(args.web&&!first.ok&&!seams.serviceInstalled())return seams.runUpForeground(["--laptop",...rootArgs]);let owned=null;const stoppedHere=new Set,exitCodes=new Map,stopOwned=child=>{stoppedHere.add(child),child.stop()},stoppedOnItsOwn=()=>{const child=owned;if(child===null||child.running()||stoppedHere.has(child))return null;const code=exitCodes.get(child);return typeof code=="number"&&code!==0?UP_STOPPED_LINE:null},upArgs=["--laptop","--no-open",...rootArgs],startOwned=async()=>{const child=seams.spawnUp(upArgs);owned=child,child.exited.then(code=>{exitCodes.set(child,code)});const deadline=Date.now()+(seams.startTimeoutMs??9e4);for(;;){const proof2=await seams.prove();if(proof2.ok)return proof2;if(!child.running()){const last=child.tail().filter(line=>line.trim()!=="").slice(-3).join(" — ");return{ok:!1,state:"refused",message:last===""?"it stopped while starting":last}}if(Date.now()>=deadline)return stopOwned(child),{ok:!1,state:"refused",message:"it didn't answer in time"};await sleep(PROVE_EVERY_MS)}};let proof=first;if(proof.ok){const joined=await joinRepo();if(joined!==EXIT.ok)return joined}else if(globalThis[Symbol.for("toolroll.starting-said")]!==!0&&write("Starting Toolroll…"),proof=seams.serviceInstalled()?await seams.startService():await startOwned(),!proof.ok)return write(`Toolroll didn't start: ${proof.message}.`),EXIT.failed;elsewhere(proof);const url=proof.url,ownedNow=()=>owned!==null&&owned.running()?owned:null,waitOwned=async()=>{const child=ownedNow();return child===null||(write("Ctrl-C stops it."),await child.exited),EXIT.ok};if(seams.localMode()!=="on"){const{problem,repair}=await seams.sandbox();if(problem!==null&&write(`Toolroll can't start without a password here: ${problem}.`),problem!==null)for(const line of repair??[])write(line);const saved=seams.savedLogin();return write(saved===null?`Toolroll is on ${url}. Sign in with your password.`:`Toolroll is on ${url}. Your password: run \`cat -- '${saved.replaceAll("'","'\\''")}'\``),await seams.openBrowser(url),waitOwned()}if(args.web){const opened=await seams.openSignedIn();if(!opened.ok){write(`Toolroll is on ${url}, but it couldn't sign you in: ${opened.message}.`),write(`Run \`toolroll\` to use it in this terminal.${opened.message.includes("toolroll password set")?"":" To use a browser, run `toolroll password set` and sign in with that password."}`);const child=ownedNow();return child!==null&&stopOwned(child),EXIT.refused}return write(`Toolroll is on ${url}`),ownedNow()===null?(write("Opening Toolroll in your browser…"),await opened.wait(SIGN_IN_HANDOFF_MS),EXIT.ok):waitOwned()}const handoff=async()=>{const child=ownedNow();child!==null&&stoppedHere.add(child);const result=await seams.backgroundOn(child===null?null:{controllerPid:child.pid,restart:async()=>{const again=await startOwned();if(!again.ok)throw Error(again.message)}});return result.ok&&(owned=null),result.message},session={owned:()=>ownedNow()!==null,stopped:stoppedOnItsOwn,openBuilderPassword:async(task,setup)=>{const page=`/t/${encodeURIComponent(task)}`,target=new URL(setup?"/password/set":`${page}#agents`,url);return setup&&target.searchParams.set("next",page),await seams.openBrowser(target.href)===!1?`Open ${target.href} in a browser, then Agents → Change agents and save the new builder.`:"In the browser, open Agents → Change agents and save the new builder."},openBrowser:async page=>{const{isTuiPage}=await import("./tui-contract.js");if(page!==void 0&&!isTuiPage(page))return"That browser page is unavailable.";if(page?.startsWith("/t/")===!0){if((await seams.openSignedIn(page)).ok)return"Opened in your browser.";const href=new URL(page,url).href;return await seams.openBrowser(href)===!1?`Open ${href} in a browser.`:"Opened Task in your browser."}if(page==="projects"||page==="lead-providers"){const href=new URL(page==="projects"?"/projects":"/settings/lead#lead-config",url).href;return await seams.openBrowser(href)===!1?`Open ${href} in a browser.`:`Opened ${page==="projects"?"Projects":"Lead settings"} in your browser.`}const opened=await seams.openSignedIn(page);return opened.ok?"Opened in your browser.":`The browser couldn't be opened: ${opened.message}.`},shouldAskBackground:()=>ownedNow()!==null&&!seams.serviceInstalled()&&!seams.backgroundAsked(),answerBackground:async yes=>(seams.recordBackgroundAnswer(yes),yes?handoff():"Okay. To change your mind later, run `toolroll background on`.")},exit=await seams.openTui(session),ended=owned;ended!==null&&!ended.running()&&await ended.exited;const died=stoppedOnItsOwn();if(died!==null){if(args.verbose===!0)for(const line of ended?.tail()??[])write(line);return write(died),EXIT.failed}if(ownedNow()!==null){if(exit==="keep"){const said=await handoff();if(write(said),ownedNow()===null)return write("Reopen with: toolroll"),EXIT.ok}const child=ownedNow();child!==null&&(write("Stopping Toolroll… (running work is saved)"),stopOwned(child),await child.exited,write("Toolroll stopped."))}return write("Reopen with: toolroll"),EXIT.ok}export function spawnOwnedUp(args,options){const entry=options.entry??process.argv[1];if(entry===void 0)throw Error("can't find Toolroll's own command to start it");const child=spawn(process.execPath,[...process.execArgv,entry,"up",...args,"--db",options.databaseFile],{cwd:options.cwd,env:withoutLeadTokenEnv(process.env),stdio:["ignore","pipe","pipe","ipc"]}),lines=[],keep=chunk=>{for(const line of String(chunk).split(`
|
|
2
2
|
`))line!==""&&lines.push(line);lines.length>40&&lines.splice(0,lines.length-40)};child.stdout?.on("data",keep),child.stderr?.on("data",keep);let running=child.pid!==void 0;const exited=new Promise(resolve2=>{child.once("exit",code=>{running=!1,resolve2(code)}),child.once("error",error=>{running=!1,lines.push(error.message),resolve2(null)})});return{pid:child.pid??-1,exited,running:()=>running,stop:()=>{running&&child.kill("SIGTERM")},tail:()=>[...lines]}}export function defaultEasyStartSeams(options){const file=options.databaseFile,cwd=options.cwd??process.cwd();return{databaseFile:file,cwd,write:options.write,prove:()=>proveConsoleReadOnly(file,options.build),socketProblem:()=>instanceSocketTooLong(file),localMode:()=>localModeRead(file),initLocal:async()=>(await import("./operate.js")).easyStartInitLocalMode(file,{stdin:process.stdin.isTTY===!0,stdout:process.stdout.isTTY===!0,agent:underAgent(process.env),json:!1,remote:(await import("./local-owner.js")).localOwnerRequested()}),sandbox:async()=>{const{missingLinuxSandboxTools,sandboxAdviceLines,sandboxRuntimeDiagnosis}=await import("./sandbox-runtime.js"),missing=process.platform==="linux"?missingLinuxSandboxTools():[];if(missing.length>0)return{missing,problem:null};const diagnosis=sandboxRuntimeDiagnosis();return diagnosis.ok?{missing,problem:null}:{missing,problem:diagnosis.why,repair:sandboxAdviceLines(diagnosis)}},prerequisites:async()=>(await import("./preflight.js")).startPrerequisites(),passwordByLaptopStart:()=>{const store=openStoreReadOnly(file);if(store===null)return!1;try{return installationCreatedBy(store)==="laptop"&&localModeOf(store)===null}catch{return!1}finally{store.close()}},savedLogin:()=>{const saved=resolve(savedLoginFile(dirname(file)));return existsSync(saved)?saved:null},serviceInstalled:()=>backgroundInstalled(),startService:async()=>{const store=openStore(file);try{return await startInstalledService(store,file)}finally{store.close()}},spawnUp:args=>spawnOwnedUp(args,{cwd,databaseFile:file}),runUpForeground:async args=>(await import("./operate.js")).runOperate("up",[...args,"--db",file],options.write,options.operate??{}),openBrowser:async url=>(await import("./operate.js")).openBrowser(url),openSignedIn:page=>openLocalSignIn(file,options.build,page===void 0?{}:{page}),openTui:async session=>{const{chooseOrRebuildTuiBinary,runTuiBinary}=await import("./tui-launch.js"),{engineContractDigest}=await import("./contracts/engine-api.js"),choice=await chooseOrRebuildTuiBinary({env:process.env,screenReader:options.screenReader===!0,platform:process.platform,arch:process.arch,contract:engineContractDigest(),devBinary:options.tuiBinary??null,write:options.write});choice.notice!==void 0&&options.write(`${choice.notice}.`);let why=choice.ok?null:choice.why;for(let opened=0;choice.ok&&opened<5;opened++){const reader=openStoreReadOnly(file),link=reader===null?{ok:!1,message:"Toolroll's database can't be read"}:await requestLocalLink(file,reader,options.build).finally(()=>reader.close());if(!link.ok){if(opened>0)return options.write("Toolroll can't sign this screen in again here. Sign in with your password in the browser."),"leave";why=`the terminal workbench couldn't sign in (${link.message})`;break}const{checkoutTop}=await import("./teardown-git.js"),end=await runTuiBinary({binary:choice.binary,identity:choice.identity,link:link.url,session,project:checkoutTop(cwd),cwd});if(end==="ended"){const{askLineOrEof,reopenAfterSignOut}=await import("./tui-launch.js"),terminal=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;if(opened<4&&await reopenAfterSignOut({terminal,agent:underAgent(process.env),ask:askLineOrEof}))continue;return"leave"}if(end==="central-unavailable")return"leave";if(end==="changed")why="the terminal workbench changed after it was checked";else{if(end!=="classic")return end;why=null}break}return why!==null&&options.write(`Terminal workbench unavailable: ${why}.`),options.write("Run `toolroll --web` to open Toolroll in your browser."),"leave"},backgroundOn:async foreground=>{const store=openStore(file);try{const on=await backgroundOn(store,file,null,{terminal:!1,...foreground===null?{}:{foreground}});return on.ok?{ok:!0,message:`Toolroll now runs in the background at ${on.url}. It starts when you log in.`}:{ok:!1,message:`Toolroll couldn't move to the background: ${on.message}.${(on.rolledBack??[]).map(line=>` ${line}.`).join("")}`}}finally{store.close()}},backgroundAsked:()=>{const store=openStoreReadOnly(file);if(store===null)return!0;try{return backgroundAsked(store)!==null}finally{store.close()}},recordBackgroundAnswer:yes=>{const store=openStore(file);try{recordBackgroundAsked(store,yes?"yes":"no",new Date)}finally{store.close()}},findRepo:async dir=>{const{checkoutTop}=await import("./teardown-git.js");return checkoutTop(dir)},enrolled:async repo=>{const{loadRepos}=await import("./repos.js"),{registryBeside}=await import("./project-admission.js"),loaded=await loadRepos(registryBeside(file));return!("error"in loaded)&&loaded.repos.includes(repo)},admit:options.admit}}export function localModeRead(file){if(file!==":memory:"&&!existsSync(file))return"absent";const store=openStoreReadOnly(file);if(store===null)return"off";try{return localModeOf(store)?.enabled===!0?"on":localModeCandidate(store)?"candidate":"off"}catch{return"off"}finally{store.close()}}export async function openLocalSignIn(databaseFile,build,seams={}){const{ledgerSpent,NO_SAFE_OPENER,openSignInLink,platformOpener}=await import("./sign-in-page.js");if(platformOpener(seams.platform)===null)return{ok:!1,message:NO_SAFE_OPENER};const{instanceRunDir,prepareRunDir}=await import("./console-instance.js"),parent=instanceRunDir(databaseFile),problem=prepareRunDir(parent);if(problem!==null)return{ok:!1,message:problem};const store=openStoreReadOnly(databaseFile);if(store===null)return{ok:!1,message:"Toolroll's database can't be read"};let handed=!1;try{const spent=ledgerSpent(store,"local link",null),expiresAt=Date.now()+(seams.expiresMs??(await import("./server/session.js")).SIGN_IN_LINK_MS),asked=await(seams.request??(one=>requestLocalLink(databaseFile,one,build)))(store);if(!asked.ok)return asked;const{isTuiPage}=await import("./tui-contract.js"),link=seams.page!==void 0&&isTuiPage(seams.page)?{...asked,url:`${asked.url}?then=${seams.page}`}:asked;handed=!0;const opened=await openSignInLink(link.url,{parent,spent,expiresAt,onEnd:()=>store.close(),...seams.opener===void 0?{}:{opener:seams.opener},...seams.platform===void 0?{}:{platform:seams.platform},...seams.everyMs===void 0?{}:{everyMs:seams.everyMs}});return opened.opened?{ok:!0,wait:opened.wait}:{ok:!1,message:"the browser opener didn't start or failed"}}finally{handed||store.close()}}
|
package/dist/egress.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createServer,request as httpRequest}from"node:http";import{randomBytes,timingSafeEqual}from"node:crypto";import{isIP}from"node:net";import{domainToASCII}from"node:url";import{readdirSync}from"node:fs";import{basename,join}from"node:path";import{connectFirst,isPublicAddress}from"./scout-net.js";import{lookup as dnsLookup}from"node:dns/promises";import{folderAnswers}from"./folder-gate.js";export const NETWORK_POLICY_VERSION=1,PROJECT_NETWORK_DEFAULT={mode:"allowlist",hosts:[],loopback:"proxy-only"},MAX_NETWORK_HOSTS=200;const MAX_SNAPSHOT_HOSTS=MAX_NETWORK_HOSTS+100;export function normalizeHost(input){const trimmed=input.trim().toLowerCase().replace(/\.$/,""),wildcard=trimmed.startsWith("*."),bare=wildcard?trimmed.slice(2):trimmed;if(bare===""||bare.length>253||isIP(bare.replace(/^\[|\]$/g,""))!==0||/[\s/\\:@?#%[\]*,;]/.test(bare))return null;const ascii=domainToASCII(bare);if(ascii===""||ascii!==ascii.toLowerCase())return null;const labels=ascii.split(".");return labels.length<2||!labels.every(label=>/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label))||/^\d+$/.test(labels.at(-1))?null:wildcard?`*.${ascii}`:ascii}export function hostAllowed(host,hosts){const name=normalizeHost(host);return name===null||name.startsWith("*.")?!1:hosts.some(entry=>entry===name||entry.startsWith("*.")&&name.endsWith(entry.slice(1)))}export function untilClosed(signal,work){return signal.aborted?Promise.resolve(null):new Promise((resolve,reject)=>{const aborted=()=>resolve(null);signal.addEventListener("abort",aborted,{once:!0});let pending;try{pending=work()}catch(error){signal.removeEventListener("abort",aborted),reject(error);return}pending.then(value=>{signal.removeEventListener("abort",aborted),resolve(value)},error=>{signal.removeEventListener("abort",aborted),reject(error)})})}function anyHostByName(host){const name=normalizeHost(host);return name!==null&&!name.startsWith("*.")}export const PROVIDER_HOSTS={claude:["api.anthropic.com","console.anthropic.com","platform.claude.com"],codex:["api.openai.com","chatgpt.com","auth.openai.com"],openrouter:["openrouter.ai"],gemini:["generativelanguage.googleapis.com","cloudcode-pa.googleapis.com","oauth2.googleapis.com"],opencode:["opencode.ai","*.opencode.ai","models.dev"],cursor:["*.cursor.sh","*.cursor.com"],cline:["api.cline.bot"],qwen:["chat.qwen.ai","dashscope.aliyuncs.com","dashscope-intl.aliyuncs.com"],goose:[],antigravity:["daily-cloudcode-pa.googleapis.com","cloudcode-pa.googleapis.com","generativelanguage.googleapis.com","oauth2.googleapis.com","accounts.google.com"],grok:["api.x.ai"],copilot:["api.github.com","github.com","*.githubcopilot.com"],kiro:["kiro.dev","*.kiro.dev","*.kiro.aws.dev","*.signin.aws"],amp:["ampcode.com","*.ampcode.com"],droid:["factory.ai","*.factory.ai"]};const PI_PROVIDER_HOSTS={anthropic:["api.anthropic.com","console.anthropic.com","platform.claude.com"],openai:["api.openai.com"],"openai-codex":["chatgpt.com","auth.openai.com"],"github-copilot":["api.github.com","github.com","*.githubcopilot.com"],google:["generativelanguage.googleapis.com"],"google-gemini-cli":["cloudcode-pa.googleapis.com","oauth2.googleapis.com"],"google-antigravity":["daily-cloudcode-pa.googleapis.com","cloudcode-pa.googleapis.com","oauth2.googleapis.com"],openrouter:["openrouter.ai"],xai:["api.x.ai"]};function providerHostsOf(provider,model=null){if(provider!=="pi")return PROVIDER_HOSTS[provider]??[];const service=model===null?-1:model.indexOf("/");return service<=0?[]:PI_PROVIDER_HOSTS[model.slice(0,service)]??[]}export const REGISTRY_HOSTS={npm:["registry.npmjs.org","registry.yarnpkg.com","repo.yarnpkg.com","nodejs.org"],python:["pypi.org","files.pythonhosted.org"],rust:["crates.io","index.crates.io","static.crates.io"],go:["proxy.golang.org","sum.golang.org"],ruby:["rubygems.org","index.rubygems.org"],jvm:["repo.maven.apache.org","repo1.maven.org","plugins.gradle.org","services.gradle.org","downloads.gradle.org"]};const ECOSYSTEM_FILES={"package.json":"npm","package-lock.json":"npm","npm-shrinkwrap.json":"npm","yarn.lock":"npm","pnpm-lock.yaml":"npm","bun.lock":"npm","bun.lockb":"npm","pyproject.toml":"python","requirements.txt":"python",pipfile:"python","pipfile.lock":"python","poetry.lock":"python","uv.lock":"python","setup.py":"python","setup.cfg":"python","cargo.toml":"rust","cargo.lock":"rust","go.mod":"go","go.sum":"go",gemfile:"ruby","gemfile.lock":"ruby","pom.xml":"jvm","build.gradle":"jvm","build.gradle.kts":"jvm","settings.gradle":"jvm","settings.gradle.kts":"jvm"};export function ecosystemsOf(paths){const found=new Set;for(const path of paths){const name=basename(path).toLowerCase(),one=ECOSYSTEM_FILES[name]??(/^requirements[\w.-]*\.txt$/.test(name)?"python":void 0);one!==void 0&&found.add(one)}return[...found].sort()}const WALK_DEPTH=3,WALK_LIMIT=5e3,WALK_SKIP=new Set(["node_modules","vendor","target","dist","build","venv","__pycache__"]);export function repositoryEcosystems(repo){if(!folderAnswers(repo))return[];const paths=[],walk=(folder,depth)=>{let entries;try{entries=readdirSync(folder,{withFileTypes:!0})}catch{return}for(const entry of entries){if(paths.length>=WALK_LIMIT)return;entry.isFile()?paths.push(join(folder,entry.name)):entry.isDirectory()&&depth<WALK_DEPTH&&!entry.name.startsWith(".")&&!WALK_SKIP.has(entry.name)&&walk(join(folder,entry.name),depth+1)}};return walk(repo,0),ecosystemsOf(paths)}export function resolveNetwork(provider,project,ecosystems,model=null){if(project.mode==="open")return{version:NETWORK_POLICY_VERSION,mode:"open",hosts:[],loopback:project.loopback};const hosts=new Set([...providerHostsOf(provider,model),...ecosystems.flatMap(one=>REGISTRY_HOSTS[one]),...project.hosts]);return{version:NETWORK_POLICY_VERSION,mode:"allowlist",hosts:[...hosts].sort(),loopback:project.loopback}}export function providerOnlyNetwork(provider,model=null){return{version:NETWORK_POLICY_VERSION,mode:"allowlist",hosts:[...new Set(providerHostsOf(provider,model))].sort(),loopback:"proxy-only"}}const NEEDS_LOCAL_SERVICES={antigravity:"Gemini"};export function localServicesRefusal(provider,network,platform=process.platform){const name=NEEDS_LOCAL_SERVICES[provider];return name===void 0||platform!=="darwin"||network!==void 0&&(network.mode==="open"||network.loopback==="any")?null:`${name} needs to reach its own helper on this Mac, and this project doesn't let builds reach local services, so nothing was started. To use ${name} here, allow local services in the project's network settings, or choose another agent.`}export function legacyNetwork(provider,ecosystems){return{...resolveNetwork(provider,{mode:"allowlist",hosts:[],loopback:"proxy-only"},ecosystems)}}export function networkFromValue(value){if(value===null||typeof value!="object"||Array.isArray(value))return null;const v=value,keys=Object.keys(v);if(keys.length!==4||!["version","mode","hosts","loopback"].every(key=>keys.includes(key))||v.version!==NETWORK_POLICY_VERSION||v.mode!=="allowlist"&&v.mode!=="open"||v.loopback!=="any"&&v.loopback!=="proxy-only"||!Array.isArray(v.hosts)||v.hosts.length>MAX_SNAPSHOT_HOSTS)return null;const hosts=[];for(const one of v.hosts){if(typeof one!="string"||normalizeHost(one)!==one)return null;hosts.push(one)}return v.mode==="open"&&hosts.length>0||new Set(hosts).size!==hosts.length||hosts.some((one,index)=>index>0&&hosts[index-1]>=one)?null:{version:NETWORK_POLICY_VERSION,mode:v.mode,hosts,loopback:v.loopback}}export function projectNetworkFromValue(value){if(value===null||typeof value!="object"||Array.isArray(value))return null;const v=value;if(Object.keys(v).length!==3||v.mode!=="allowlist"&&v.mode!=="open"||v.loopback!=="any"&&v.loopback!=="proxy-only"||!Array.isArray(v.hosts)||v.hosts.length>MAX_NETWORK_HOSTS)return null;const hosts=v.hosts.map(one=>typeof one=="string"?normalizeHost(one):null);return hosts.some(one=>one===null)?null:{mode:v.mode,hosts:[...new Set(hosts)].sort(),loopback:v.loopback}}export function unaccountedHosts(network,provider){const full=Object.values(REGISTRY_HOSTS).filter(hosts=>hosts.every(one=>network.hosts.includes(one))),own=PROVIDER_HOSTS[provider]??[],known=new Set([...own.length>0&&own.every(one=>network.hosts.includes(one))?own:[],...full.flat()]);return network.hosts.filter(one=>!known.has(one))}export function codexCommandsOffline(profile,platform=process.platform){return profile.provider!=="codex"&&profile.provider!=="openrouter"||platform==="darwin"?!1:!(profile.sandboxMode==="danger-full-access"&&profile.network?.mode==="open")}export function networkWords(network,provider,options){const offlineSuffix=options?.commandsOffline!==!0?"":network?.mode==="open"?" (Codex commands run offline until Full access is on)":" (Codex commands run offline — set a worktree setup command for dependencies)";if(network===null)return`Network: approved before network rules (provider and package registries only)${offlineSuffix}`;if(network.mode==="open")return`Network: open — any host${network.loopback==="proxy-only"?"":", and every local service on this Mac"}${offlineSuffix}`;const full=Object.entries(REGISTRY_HOSTS).filter(([,hosts])=>hosts.every(one=>network.hosts.includes(one))),own=PROVIDER_HOSTS[provider]??[],named=own.length>0&&own.every(one=>network.hosts.includes(one)),known=new Set([...named?own:[],...full.flatMap(([,hosts])=>hosts)]),added=network.hosts.filter(one=>!known.has(one)),parts=[...named?["the agent's provider"]:[],...full.map(([name])=>REGISTRY_NAMES[name])];return`Network: ${parts.length===0&&added.length===0?"no hosts":[parts.join(", "),added.length===0?"":`${parts.length===0?"":"and "}${added.join(", ")}`].filter(Boolean).join(", ")}`+(network.loopback==="any"?"; and every local service on this Mac":"")+offlineSuffix}const REGISTRY_NAMES={npm:"npm",python:"PyPI",rust:"crates.io",go:"the Go proxy",ruby:"RubyGems",jvm:"Maven and Gradle"},HOST_LIMIT=50;export function runNetworkFromValue(value){if(value===null||typeof value!="object"||Array.isArray(value))return null;const v=value;if(v.mode!=="open"&&v.mode!=="allowlist"||v.phase!=="agent")return null;const count=n=>typeof n=="number"&&Number.isSafeInteger(n)&&n>=0,out={mode:v.mode,phase:"agent"};if(v.via===!0&&(out.via=!0),v.hosts!==void 0){if(!count(v.hosts))return null;out.hosts=v.hosts}if(v.loopback!==void 0){if(v.loopback!=="any"&&v.loopback!=="proxy-only")return null;out.loopback=v.loopback}if(v.counts!==void 0){const c=v.counts;if(c===null||typeof c!="object"||!count(c.connections)||!count(c.refused)||!count(c.otherHosts)||!Array.isArray(c.hosts)||c.hosts.length>HOST_LIMIT)return null;const hosts=[];for(const one of c.hosts){const h=one;if(h===null||typeof h!="object"||typeof h.host!="string"||h.host.length>300||!count(h.connections)||!count(h.refused))return null;hosts.push({host:h.host,connections:h.connections,refused:h.refused})}out.counts={connections:c.connections,refused:c.refused,hosts,otherHosts:c.otherHosts}}return out}export function proxyEnv(proxy,loopback){const local=loopback==="proxy-only"?"":"localhost,127.0.0.1,::1";return{HTTPS_PROXY:proxy.url,https_proxy:proxy.url,HTTP_PROXY:proxy.url,http_proxy:proxy.url,ALL_PROXY:proxy.url,all_proxy:proxy.url,NO_PROXY:local,no_proxy:local,NODE_USE_ENV_PROXY:"1"}}export async function startEgressProxy(options){const addressAllowed=options.addressAllowed??isPublicAddress,upstreamPort=options.upstreamPort??(port2=>port2),lookup=options.lookup??(async host=>(await dnsLookup(host,{all:!0,verbatim:!0})).map(one=>one.address)),connectUpstream=options.connect??((addresses,port2,signal)=>connectFirst(addresses,port2,void 0,signal)),closing=new AbortController,isClosed=()=>closing.signal.aborted,secret=randomBytes(24).toString("base64url"),expected=Buffer.from(secret),sockets=new Set,byHost=new Map;let connections=0,refused=0,otherHosts=0;const count=(host,allowed,why)=>{allowed?connections++:refused++;const key=normalizeHost(host)??"(not a host name)";let entry=byHost.get(key);if(entry===void 0&&byHost.size>=HOST_LIMIT){otherHosts++;return}entry===void 0&&(entry={connections:0,refused:0},byHost.set(key,entry)),allowed?entry.connections++:entry.refused++;try{options.decided?.(key,allowed,why)}catch{}},authorized=incoming=>{const header=String(incoming.headers["proxy-authorization"]??""),basic=/^Basic ([A-Za-z0-9+/=]+)$/.exec(header)?.[1];if(basic===void 0)return!1;const decoded=Buffer.from(basic,"base64").toString("utf8"),colon=decoded.indexOf(":"),given=Buffer.from(colon<0?"":decoded.slice(colon+1));return given.length===expected.length&&timingSafeEqual(given,expected)},admit=async(host,port2,wantPort)=>{if(port2!==wantPort)return{ok:!1,why:`port ${port2} is not allowed`};if(options.open===!0?!anyHostByName(host):!hostAllowed(host,options.hosts))return{ok:!1,why:"not an approved host"};let addresses;try{const found=await untilClosed(closing.signal,()=>lookup(normalizeHost(host)));if(found===null||isClosed())return{ok:!1,why:"the proxy closed"};addresses=found}catch{return{ok:!1,why:"the host does not resolve"}}return addresses.length===0?{ok:!1,why:"the host does not resolve"}:addresses.every(addressAllowed)?{ok:!0,addresses}:{ok:!1,why:"not a public internet address"}},server=createServer((incoming,outgoing)=>{(async()=>{if(!authorized(incoming)){outgoing.writeHead(407,{"proxy-authenticate":'Basic realm="toolroll"'}).end();return}let url;try{url=new URL(incoming.url??"")}catch{outgoing.writeHead(400).end();return}const hostHeader=String(incoming.headers.host??"").toLowerCase(),sameHost=hostHeader===url.host.toLowerCase()||hostHeader===url.hostname.toLowerCase()||url.port===""&&hostHeader===`${url.hostname.toLowerCase()}:80`;if(url.protocol!=="http:"||url.username!==""||url.password!==""||!sameHost){count(url.hostname,!1,"not a plain web request for its own host"),outgoing.writeHead(403,{"content-type":"text/plain"}).end("Toolroll: this build may reach only its approved hosts.");return}const reached=await admit(url.hostname,Number(url.port||80),80);if(isClosed()){incoming.socket.destroy();return}if(!reached.ok){count(url.hostname,!1,reached.why),outgoing.writeHead(403,{"content-type":"text/plain"}).end(`Toolroll: ${url.hostname} is not one of this build's approved hosts.`);return}const upstream=await connectUpstream(reached.addresses,upstreamPort(80),closing.signal);if(isClosed()){upstream?.destroy(),incoming.socket.destroy();return}if(upstream===null){outgoing.writeHead(502).end();return}count(url.hostname,!0,"approved"),sockets.add(upstream),upstream.on("close",()=>sockets.delete(upstream));const headers={...incoming.headers};delete headers["proxy-connection"],delete headers["proxy-authorization"];const forward=httpRequest({createConnection:()=>upstream,method:incoming.method,path:`${url.pathname}${url.search}`,headers,setHost:!1},answer=>{outgoing.writeHead(answer.statusCode??502,answer.headers),answer.pipe(outgoing)});forward.on("error",()=>{outgoing.headersSent||outgoing.writeHead(502),outgoing.end()}),incoming.pipe(forward)})()});server.on("connect",(incoming,client,head)=>{sockets.add(client),client.on("close",()=>sockets.delete(client)),client.on("error",()=>client.destroy()),(async()=>{if(!authorized(incoming)){client.end(`HTTP/1.1 407 Proxy Authentication Required\r
|
|
1
|
+
import{createServer,request as httpRequest}from"node:http";import{randomBytes,timingSafeEqual}from"node:crypto";import{isIP}from"node:net";import{domainToASCII}from"node:url";import{readdirSync}from"node:fs";import{basename,join}from"node:path";import{connectFirst,isPublicAddress}from"./scout-net.js";import{lookup as dnsLookup}from"node:dns/promises";import{folderAnswers}from"./folder-gate.js";export const NETWORK_POLICY_VERSION=1,PROJECT_NETWORK_DEFAULT={mode:"allowlist",hosts:[],loopback:"proxy-only"},FAST_PROJECT_NETWORK_DEFAULT={mode:"open",hosts:[],loopback:"any"},isOldDefaultProjectNetwork=network=>network.mode==="allowlist"&&network.hosts.length===0&&network.loopback==="proxy-only",MAX_NETWORK_HOSTS=200;const MAX_SNAPSHOT_HOSTS=MAX_NETWORK_HOSTS+100;export function normalizeHost(input){const trimmed=input.trim().toLowerCase().replace(/\.$/,""),wildcard=trimmed.startsWith("*."),bare=wildcard?trimmed.slice(2):trimmed;if(bare===""||bare.length>253||isIP(bare.replace(/^\[|\]$/g,""))!==0||/[\s/\\:@?#%[\]*,;]/.test(bare))return null;const ascii=domainToASCII(bare);if(ascii===""||ascii!==ascii.toLowerCase())return null;const labels=ascii.split(".");return labels.length<2||!labels.every(label=>/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label))||/^\d+$/.test(labels.at(-1))?null:wildcard?`*.${ascii}`:ascii}export function hostAllowed(host,hosts){const name=normalizeHost(host);return name===null||name.startsWith("*.")?!1:hosts.some(entry=>entry===name||entry.startsWith("*.")&&name.endsWith(entry.slice(1)))}export function untilClosed(signal,work){return signal.aborted?Promise.resolve(null):new Promise((resolve,reject)=>{const aborted=()=>resolve(null);signal.addEventListener("abort",aborted,{once:!0});let pending;try{pending=work()}catch(error){signal.removeEventListener("abort",aborted),reject(error);return}pending.then(value=>{signal.removeEventListener("abort",aborted),resolve(value)},error=>{signal.removeEventListener("abort",aborted),reject(error)})})}function anyHostByName(host){const name=normalizeHost(host);return name!==null&&!name.startsWith("*.")}export const PROVIDER_HOSTS={claude:["api.anthropic.com","console.anthropic.com","platform.claude.com"],codex:["api.openai.com","chatgpt.com","auth.openai.com"],openrouter:["openrouter.ai"],gemini:["generativelanguage.googleapis.com","cloudcode-pa.googleapis.com","oauth2.googleapis.com"],opencode:["opencode.ai","*.opencode.ai","models.dev"],cursor:["*.cursor.sh","*.cursor.com"],cline:["api.cline.bot"],qwen:["chat.qwen.ai","dashscope.aliyuncs.com","dashscope-intl.aliyuncs.com"],goose:[],antigravity:["daily-cloudcode-pa.googleapis.com","cloudcode-pa.googleapis.com","generativelanguage.googleapis.com","oauth2.googleapis.com","accounts.google.com"],grok:["api.x.ai"],copilot:["api.github.com","github.com","*.githubcopilot.com"],kiro:["kiro.dev","*.kiro.dev","*.kiro.aws.dev","*.signin.aws"],amp:["ampcode.com","*.ampcode.com"],droid:["factory.ai","*.factory.ai"]};const PI_PROVIDER_HOSTS={anthropic:["api.anthropic.com","console.anthropic.com","platform.claude.com"],openai:["api.openai.com"],"openai-codex":["chatgpt.com","auth.openai.com"],"github-copilot":["api.github.com","github.com","*.githubcopilot.com"],google:["generativelanguage.googleapis.com"],"google-gemini-cli":["cloudcode-pa.googleapis.com","oauth2.googleapis.com"],"google-antigravity":["daily-cloudcode-pa.googleapis.com","cloudcode-pa.googleapis.com","oauth2.googleapis.com"],openrouter:["openrouter.ai"],xai:["api.x.ai"]};function providerHostsOf(provider,model=null){if(provider!=="pi")return PROVIDER_HOSTS[provider]??[];const service=model===null?-1:model.indexOf("/");return service<=0?[]:PI_PROVIDER_HOSTS[model.slice(0,service)]??[]}export const REGISTRY_HOSTS={npm:["registry.npmjs.org","registry.yarnpkg.com","repo.yarnpkg.com","nodejs.org"],python:["pypi.org","files.pythonhosted.org"],rust:["crates.io","index.crates.io","static.crates.io"],go:["proxy.golang.org","sum.golang.org"],ruby:["rubygems.org","index.rubygems.org"],jvm:["repo.maven.apache.org","repo1.maven.org","plugins.gradle.org","services.gradle.org","downloads.gradle.org"]};const ECOSYSTEM_FILES={"package.json":"npm","package-lock.json":"npm","npm-shrinkwrap.json":"npm","yarn.lock":"npm","pnpm-lock.yaml":"npm","bun.lock":"npm","bun.lockb":"npm","pyproject.toml":"python","requirements.txt":"python",pipfile:"python","pipfile.lock":"python","poetry.lock":"python","uv.lock":"python","setup.py":"python","setup.cfg":"python","cargo.toml":"rust","cargo.lock":"rust","go.mod":"go","go.sum":"go",gemfile:"ruby","gemfile.lock":"ruby","pom.xml":"jvm","build.gradle":"jvm","build.gradle.kts":"jvm","settings.gradle":"jvm","settings.gradle.kts":"jvm"};export function ecosystemsOf(paths){const found=new Set;for(const path of paths){const name=basename(path).toLowerCase(),one=ECOSYSTEM_FILES[name]??(/^requirements[\w.-]*\.txt$/.test(name)?"python":void 0);one!==void 0&&found.add(one)}return[...found].sort()}const WALK_DEPTH=3,WALK_LIMIT=5e3,WALK_SKIP=new Set(["node_modules","vendor","target","dist","build","venv","__pycache__"]);export function repositoryEcosystems(repo){if(!folderAnswers(repo))return[];const paths=[],walk=(folder,depth)=>{let entries;try{entries=readdirSync(folder,{withFileTypes:!0})}catch{return}for(const entry of entries){if(paths.length>=WALK_LIMIT)return;entry.isFile()?paths.push(join(folder,entry.name)):entry.isDirectory()&&depth<WALK_DEPTH&&!entry.name.startsWith(".")&&!WALK_SKIP.has(entry.name)&&walk(join(folder,entry.name),depth+1)}};return walk(repo,0),ecosystemsOf(paths)}export function resolveNetwork(provider,project,ecosystems,model=null){if(project.mode==="open")return{version:NETWORK_POLICY_VERSION,mode:"open",hosts:[],loopback:project.loopback};const hosts=new Set([...providerHostsOf(provider,model),...ecosystems.flatMap(one=>REGISTRY_HOSTS[one]),...project.hosts]);return{version:NETWORK_POLICY_VERSION,mode:"allowlist",hosts:[...hosts].sort(),loopback:project.loopback}}function hostEntryAdmittedBy(entry,allowed){if(allowed.includes(entry))return!0;const bare=entry.startsWith("*.")?entry.slice(2):entry;return allowed.some(rule=>rule.startsWith("*.")&&bare.endsWith(rule.slice(1)))}export function intersectNetworks(a,b){const loopback=a.loopback==="any"&&b.loopback==="any"?"any":"proxy-only";if(a.mode==="open"&&b.mode==="open")return{version:NETWORK_POLICY_VERSION,mode:"open",hosts:[],loopback};if(a.mode==="open")return{version:NETWORK_POLICY_VERSION,mode:"allowlist",hosts:[...b.hosts].sort(),loopback};if(b.mode==="open")return{version:NETWORK_POLICY_VERSION,mode:"allowlist",hosts:[...a.hosts].sort(),loopback};const hosts=new Set;for(const one of a.hosts)hostEntryAdmittedBy(one,b.hosts)&&hosts.add(one);for(const one of b.hosts)hostEntryAdmittedBy(one,a.hosts)&&hosts.add(one);return{version:NETWORK_POLICY_VERSION,mode:"allowlist",hosts:[...hosts].sort(),loopback}}export function providerOnlyNetwork(provider,model=null){return{version:NETWORK_POLICY_VERSION,mode:"allowlist",hosts:[...new Set(providerHostsOf(provider,model))].sort(),loopback:"proxy-only"}}const NEEDS_LOCAL_SERVICES={antigravity:"Gemini"};export function localServicesRefusal(provider,network,platform=process.platform){const name=NEEDS_LOCAL_SERVICES[provider];return name===void 0||platform!=="darwin"||network!==void 0&&(network.mode==="open"||network.loopback==="any")?null:`${name} needs to reach its own helper on this Mac, and this project doesn't let builds reach local services, so nothing was started. To use ${name} here, allow local services in the project's network settings, or choose another agent.`}export function legacyNetwork(provider,ecosystems){return{...resolveNetwork(provider,{mode:"allowlist",hosts:[],loopback:"proxy-only"},ecosystems)}}export function networkFromValue(value){if(value===null||typeof value!="object"||Array.isArray(value))return null;const v=value,keys=Object.keys(v);if(keys.length!==4||!["version","mode","hosts","loopback"].every(key=>keys.includes(key))||v.version!==NETWORK_POLICY_VERSION||v.mode!=="allowlist"&&v.mode!=="open"||v.loopback!=="any"&&v.loopback!=="proxy-only"||!Array.isArray(v.hosts)||v.hosts.length>MAX_SNAPSHOT_HOSTS)return null;const hosts=[];for(const one of v.hosts){if(typeof one!="string"||normalizeHost(one)!==one)return null;hosts.push(one)}return v.mode==="open"&&hosts.length>0||new Set(hosts).size!==hosts.length||hosts.some((one,index)=>index>0&&hosts[index-1]>=one)?null:{version:NETWORK_POLICY_VERSION,mode:v.mode,hosts,loopback:v.loopback}}export function projectNetworkFromValue(value){if(value===null||typeof value!="object"||Array.isArray(value))return null;const v=value;if(Object.keys(v).length!==3||v.mode!=="allowlist"&&v.mode!=="open"||v.loopback!=="any"&&v.loopback!=="proxy-only"||!Array.isArray(v.hosts)||v.hosts.length>MAX_NETWORK_HOSTS)return null;const hosts=v.hosts.map(one=>typeof one=="string"?normalizeHost(one):null);return hosts.some(one=>one===null)?null:{mode:v.mode,hosts:[...new Set(hosts)].sort(),loopback:v.loopback}}export function unaccountedHosts(network,provider){const full=Object.values(REGISTRY_HOSTS).filter(hosts=>hosts.every(one=>network.hosts.includes(one))),own=PROVIDER_HOSTS[provider]??[],known=new Set([...own.length>0&&own.every(one=>network.hosts.includes(one))?own:[],...full.flat()]);return network.hosts.filter(one=>!known.has(one))}export function codexCommandsOffline(profile,platform=process.platform){return profile.provider!=="codex"&&profile.provider!=="openrouter"||platform==="darwin"?!1:!(profile.sandboxMode==="danger-full-access"&&profile.network?.mode==="open")}export function networkWords(network,provider,options){const offlineSuffix=options?.commandsOffline!==!0?"":network?.mode==="open"?" (Codex commands run offline until Full access is on)":" (Codex commands run offline — set a worktree setup command for dependencies)";if(network===null)return`Network: approved before network rules (provider and package registries only)${offlineSuffix}`;if(network.mode==="open")return`Network: open — any host${network.loopback==="proxy-only"?"":", and every local service on this Mac"}${offlineSuffix}`;const full=Object.entries(REGISTRY_HOSTS).filter(([,hosts])=>hosts.every(one=>network.hosts.includes(one))),own=PROVIDER_HOSTS[provider]??[],named=own.length>0&&own.every(one=>network.hosts.includes(one)),known=new Set([...named?own:[],...full.flatMap(([,hosts])=>hosts)]),added=network.hosts.filter(one=>!known.has(one)),parts=[...named?["the agent's provider"]:[],...full.map(([name])=>REGISTRY_NAMES[name])];return`Network: ${parts.length===0&&added.length===0?"no hosts":[parts.join(", "),added.length===0?"":`${parts.length===0?"":"and "}${added.join(", ")}`].filter(Boolean).join(", ")}`+(network.loopback==="any"?"; and every local service on this Mac":"")+offlineSuffix}const REGISTRY_NAMES={npm:"npm",python:"PyPI",rust:"crates.io",go:"the Go proxy",ruby:"RubyGems",jvm:"Maven and Gradle"},HOST_LIMIT=50;export function runNetworkFromValue(value){if(value===null||typeof value!="object"||Array.isArray(value))return null;const v=value;if(v.mode!=="open"&&v.mode!=="allowlist"||v.phase!=="agent")return null;const count=n=>typeof n=="number"&&Number.isSafeInteger(n)&&n>=0,out={mode:v.mode,phase:"agent"};if(v.via===!0&&(out.via=!0),v.hosts!==void 0){if(!count(v.hosts))return null;out.hosts=v.hosts}if(v.loopback!==void 0){if(v.loopback!=="any"&&v.loopback!=="proxy-only")return null;out.loopback=v.loopback}if(v.counts!==void 0){const c=v.counts;if(c===null||typeof c!="object"||!count(c.connections)||!count(c.refused)||!count(c.otherHosts)||!Array.isArray(c.hosts)||c.hosts.length>HOST_LIMIT)return null;const hosts=[];for(const one of c.hosts){const h=one;if(h===null||typeof h!="object"||typeof h.host!="string"||h.host.length>300||!count(h.connections)||!count(h.refused))return null;hosts.push({host:h.host,connections:h.connections,refused:h.refused})}out.counts={connections:c.connections,refused:c.refused,hosts,otherHosts:c.otherHosts}}return out}export function proxyEnv(proxy,loopback){const local=loopback==="proxy-only"?"":"localhost,127.0.0.1,::1";return{HTTPS_PROXY:proxy.url,https_proxy:proxy.url,HTTP_PROXY:proxy.url,http_proxy:proxy.url,ALL_PROXY:proxy.url,all_proxy:proxy.url,NO_PROXY:local,no_proxy:local,NODE_USE_ENV_PROXY:"1"}}export async function startEgressProxy(options){const addressAllowed=options.addressAllowed??isPublicAddress,upstreamPort=options.upstreamPort??(port2=>port2),lookup=options.lookup??(async host=>(await dnsLookup(host,{all:!0,verbatim:!0})).map(one=>one.address)),connectUpstream=options.connect??((addresses,port2,signal)=>connectFirst(addresses,port2,void 0,signal)),closing=new AbortController,isClosed=()=>closing.signal.aborted,secret=randomBytes(24).toString("base64url"),expected=Buffer.from(secret),sockets=new Set,byHost=new Map;let connections=0,refused=0,otherHosts=0;const count=(host,allowed,why)=>{allowed?connections++:refused++;const key=normalizeHost(host)??"(not a host name)";let entry=byHost.get(key);if(entry===void 0&&byHost.size>=HOST_LIMIT){otherHosts++;return}entry===void 0&&(entry={connections:0,refused:0},byHost.set(key,entry)),allowed?entry.connections++:entry.refused++;try{options.decided?.(key,allowed,why)}catch{}},authorized=incoming=>{const header=String(incoming.headers["proxy-authorization"]??""),basic=/^Basic ([A-Za-z0-9+/=]+)$/.exec(header)?.[1];if(basic===void 0)return!1;const decoded=Buffer.from(basic,"base64").toString("utf8"),colon=decoded.indexOf(":"),given=Buffer.from(colon<0?"":decoded.slice(colon+1));return given.length===expected.length&&timingSafeEqual(given,expected)},admit=async(host,port2,wantPort)=>{if(port2!==wantPort)return{ok:!1,why:`port ${port2} is not allowed`};if(options.open===!0?!anyHostByName(host):!hostAllowed(host,options.hosts))return{ok:!1,why:"not an approved host"};let addresses;try{const found=await untilClosed(closing.signal,()=>lookup(normalizeHost(host)));if(found===null||isClosed())return{ok:!1,why:"the proxy closed"};addresses=found}catch{return{ok:!1,why:"the host does not resolve"}}return addresses.length===0?{ok:!1,why:"the host does not resolve"}:addresses.every(addressAllowed)?{ok:!0,addresses}:{ok:!1,why:"not a public internet address"}},server=createServer((incoming,outgoing)=>{(async()=>{if(!authorized(incoming)){outgoing.writeHead(407,{"proxy-authenticate":'Basic realm="toolroll"'}).end();return}let url;try{url=new URL(incoming.url??"")}catch{outgoing.writeHead(400).end();return}const hostHeader=String(incoming.headers.host??"").toLowerCase(),sameHost=hostHeader===url.host.toLowerCase()||hostHeader===url.hostname.toLowerCase()||url.port===""&&hostHeader===`${url.hostname.toLowerCase()}:80`;if(url.protocol!=="http:"||url.username!==""||url.password!==""||!sameHost){count(url.hostname,!1,"not a plain web request for its own host"),outgoing.writeHead(403,{"content-type":"text/plain"}).end("Toolroll: this build may reach only its approved hosts.");return}const reached=await admit(url.hostname,Number(url.port||80),80);if(isClosed()){incoming.socket.destroy();return}if(!reached.ok){count(url.hostname,!1,reached.why),outgoing.writeHead(403,{"content-type":"text/plain"}).end(`Toolroll: ${url.hostname} is not one of this build's approved hosts.`);return}const upstream=await connectUpstream(reached.addresses,upstreamPort(80),closing.signal);if(isClosed()){upstream?.destroy(),incoming.socket.destroy();return}if(upstream===null){outgoing.writeHead(502).end();return}count(url.hostname,!0,"approved"),sockets.add(upstream),upstream.on("close",()=>sockets.delete(upstream));const headers={...incoming.headers};delete headers["proxy-connection"],delete headers["proxy-authorization"];const forward=httpRequest({createConnection:()=>upstream,method:incoming.method,path:`${url.pathname}${url.search}`,headers,setHost:!1},answer=>{outgoing.writeHead(answer.statusCode??502,answer.headers),answer.pipe(outgoing)});forward.on("error",()=>{outgoing.headersSent||outgoing.writeHead(502),outgoing.end()}),incoming.pipe(forward)})()});server.on("connect",(incoming,client,head)=>{sockets.add(client),client.on("close",()=>sockets.delete(client)),client.on("error",()=>client.destroy()),(async()=>{if(!authorized(incoming)){client.end(`HTTP/1.1 407 Proxy Authentication Required\r
|
|
2
2
|
Proxy-Authenticate: Basic realm="toolroll"\r
|
|
3
3
|
Content-Length: 0\r
|
|
4
4
|
\r
|
package/dist/engine-handoff.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{spawn}from"node:child_process";export const LINK_FD=3;const LINK=/^http:\/\/(?:127\.0\.0\.1|\[::1\]):[0-9]{1,5}\/login\/once\/[A-Za-z0-9_-]{43}$/;export function spawnWithLink(command,args,link,options={}){const held=spawnHoldingLink(command,args,link,options);return held.send(),held.child}export function spawnHoldingLink(command,args,link,options={}){if(!LINK.test(link))throw new Error("not a local one-time sign-in link");const code=link.slice(link.lastIndexOf("/")+1),env=options.env??process.env;if(args.some(one=>one.includes(code))||Object.entries(env).some(([name,value])=>name.includes(code)||(value??"").includes(code)))throw new Error("the sign-in link goes only over the pipe, never in arguments or the environment");const[stdin,stdout,stderr]=options.stdio??["inherit","inherit","inherit"],child=spawn(command,[...args],{cwd:options.cwd,env,stdio:options.control===!0?[stdin,stdout,stderr,"pipe","pipe"]:[stdin,stdout,stderr,"pipe"]}),pipe=child.stdio[LINK_FD];if(pipe==null||!("write"in pipe))throw child.kill(),new Error("no pipe for the sign-in link");pipe.on("error",()=>{});let sent=!1;return{child,send:()=>sent||child.exitCode!==null||child.signalCode!==null?!1:(sent=!0,pipe.end(`${link}
|
|
1
|
+
import{spawn}from"node:child_process";import{withoutLeadTokenEnv}from"./names.js";export const LINK_FD=3;const LINK=/^http:\/\/(?:127\.0\.0\.1|\[::1\]):[0-9]{1,5}\/login\/once\/[A-Za-z0-9_-]{43}$/;export function spawnWithLink(command,args,link,options={}){const held=spawnHoldingLink(command,args,link,options);return held.send(),held.child}export function spawnHoldingLink(command,args,link,options={}){if(!LINK.test(link))throw new Error("not a local one-time sign-in link");const code=link.slice(link.lastIndexOf("/")+1),env=withoutLeadTokenEnv(options.env??process.env);if(args.some(one=>one.includes(code))||Object.entries(env).some(([name,value])=>name.includes(code)||(value??"").includes(code)))throw new Error("the sign-in link goes only over the pipe, never in arguments or the environment");const[stdin,stdout,stderr]=options.stdio??["inherit","inherit","inherit"],child=spawn(command,[...args],{cwd:options.cwd,env,stdio:options.control===!0?[stdin,stdout,stderr,"pipe","pipe"]:[stdin,stdout,stderr,"pipe"]}),pipe=child.stdio[LINK_FD];if(pipe==null||!("write"in pipe))throw child.kill(),new Error("no pipe for the sign-in link");pipe.on("error",()=>{});let sent=!1;return{child,send:()=>sent||child.exitCode!==null||child.signalCode!==null?!1:(sent=!0,pipe.end(`${link}
|
|
2
2
|
`),!0)}}
|
package/dist/engine-reads.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{closeSync,constants as fsConstants,fstatSync,openSync,readSync,realpathSync}from"node:fs";import{dirname,join,sep}from"node:path";import{agentSaidOf,planProblemsOf}from"./store.js";import{codexOfflineDependencySuggestion,failedAttemptSentence,latestFinishedAttempt,stopSuggestionOf}from"./needs-you.js";import{pendingAgentChangeOf,planSourceOf,retryPinsOf}from"./local-owner-acts.js";import{assignmentOf,owedAcceptance,personCompletionRefusal}from"./assignment.js";import{assignmentCardOf}from"./assignment-presentation.js";import{behindMainOf,landedNowOf,upToDateNote}from"./merge-checklist.js";import{publishesThroughPullRequests}from"./local-landing.js";import{liveQuickCommand}from"./check-levels.js";import{assignmentStageOf,stageOfCode}from"./task-status.js";import{taskRoad}from"./first-run.js";import{stepRowsOf}from"./workspace-projection.js";import{approvalOf}from"./scope.js";import{approvalSummaryOf,summaryContextOf}from"./approval-summary.js";import{taskWorkSummaryOf}from"./work-summary.js";import{structuredHandoffView,terminalDiffView}from"./result-evidence-readers.js";import{parseReviewDiff,proofBundleView}from"./result-projection.js";import{parseReport}from"./scout-report.js";import{revisionSourceOf}from"./result-review.js";import{DIFF_CONTEXT_MAX,ENGINE_API_VERSION}from"./contracts/engine-api.js";import{agentSetupOf,agentUsesOf,detectionLines,NO_AGENT_YET,npmRegistryOf}from"./agent-detect.js";import{cleanSourcePathsFromNumstat,isTransientDiffBloat,readVerifiedArtifact,redactSecretLines,reportShotsOf,scanPatchForSecrets}from"./evidence.js";import{fastCompletionProblem}from"./fast-start.js";import{cleanLiveText,HIDDEN_LINE}from"./live-records.js";import{keyShaped}from"./agent-thread/session.js";import{viewedGitSync}from"./teardown-git.js";import{wasInterrupted}from"./run-ending.js";import{agentChoicesFor,routeOfTask}from"./agentconfig.js";const isResultRun=run=>run.finishedAt!==null&&(run.role==="builder"||run.role==="scout"),isTakeOverRun=run=>run.role==="builder"||run.role==="scout",VALID_SHA=/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/,validSha=value=>value!=null&&VALID_SHA.test(value)?value:null;export const takeOverRevisionOf=run=>validSha(run.headRevision)??validSha(run.baseRevision);const AUTOMATIC=new Set(["auto-check","auto-green"]);export function stepCardsOf({store,family,now,access,evidenceRoot,viewer=null,withChoices=!1}){const current=family.current,root=family.root,ref=store.lookupRef(current.id),scope=store.getScope(current.id),runs=ref===null?[]:store.runsFor(ref.id),assignment=assignmentOf(store,current.id,now,access,evidenceRoot),item=taskWorkSummaryOf(store,current.id,now,access),live=runs.find(run=>run.finishedAt===null)??null,planning=live?.role==="planner",card=assignment===null||item===null?null:assignmentCardOf(assignment,{workStatus:item.status,planning}),approved=approvalOf(scope).approved,report=ref?.deliverable==="report",plannerRuns=runs.filter(run=>run.role==="planner"),justCode=plannerRuns.length===0&&(ref?.plan??null)===null&&approved,facts={journey:current.state==="cancelled"||item===null?null:(()=>{const read=assignment!==null?assignmentStageOf(assignment,{token:item.status.token,views:item.status.views},planning):stageOfCode(item.status.token,{planning}),checks=card?.status.check??null;return taskRoad(read,approved,current.state==="done",{checks,report})})(),scout:report,status:card===null?null:{status:{headline:card.status.headline},attempts:card.attempts},approved:scope!==null&&approved&&scope.approvedBy!==null&&scope.approvedAt!==null?{by:scope.approvedBy,at:scope.approvedAt,automatic:AUTOMATIC.has(String(scope.approvalBasis??"")),rule:null}:null,approve:null,plan:plannerRuns.length===0&&ref?.plan==null?null:{lead:null,by:plannerRuns[0]?.provider??null,at:plannerRuns.find(run=>run.finishedAt!==null)?.finishedAt??null,planning},result:assignment?.receipt==null?null:{selected:assignment.receipt},thread:runs.filter(isResultRun).map(run=>({kind:"result",at:run.finishedAt}))},rows=stepRowsOf(facts),builds=runs.filter(run=>run.role==="builder"||run.role==="scout"||run.role==="repair"),reviews=runs.filter(run=>run.role==="reviewer"),behind={plan:plannerRuns.filter(run=>run.parentRun===null),approve:[],build:builds,checks:[],review:reviews,ready:[]},terms=scope===null||approved?null:(()=>{const summary=approvalSummaryOf(scope,summaryContextOf(store,current.id,scope,now));return{key:summary.key,revision:summary.revision,rows:[...summary.revisionChanges,...summary.decisions,...summary.why===null?[]:[{label:"Why model",words:summary.why}],...summary.differs].map(one=>({label:one.label,words:one.words,lines:"lines"in one?[...one.lines??[]]:[]})),warnings:summary.warnings.map(one=>one.words),usualLabel:summary.usualLabel,usual:summary.usual.map(one=>({label:one.label,words:one.words}))}})(),cards=current.state==="cancelled"?cancelledCards(builds,current.updatedAt??null):rows===null?null:rows.map(row=>({key:row.key,label:row.label,state:row.state,mark:row.mark,sentence:row.sentence,at:row.at,needsYou:row.needsYou,inChain:!(justCode&&(row.key==="plan"||row.key==="approve")),...runFacts(behind[row.key]),...row.key==="approve"&&terms!==null?{terms}:{}}));if(cards!==null&&reviews.length>0){const latest=reviews[0],state=latest.finishedAt===null?"current":latest.outcome==="failed"||latest.outcome==="refused"?"stuck":"done",at=cards.findIndex(one=>one.key==="ready");cards.splice(at===-1?cards.length:at,0,{key:"review",label:"Review",state,mark:state==="current"?"live":state==="stuck"?"stuck":"done",sentence:state==="current"?"Reviewing now":state==="stuck"?"The review didn't finish":"Reviewed",at:latest.finishedAt,needsYou:!1,inChain:!0,...runFacts(reviews)})}return{version:ENGINE_API_VERSION,task:{id:current.id,root:root.id,title:root.title,state:current.state,project:current.repo},chain:justCode?"just-code":"plan-first",headline:current.state==="cancelled"?"Cancelled":card?.status.headline??null,liveRun:live?.id??null,latestRun:runs.reduce((max,run)=>max===null||run.id>max?run.id:max,null),models:(()=>{const routed=routeOfTask(store,current.id,ref,now);return routed?.kind==="route"?routed.route.legs.map(leg=>({phase:leg.phase,provider:leg.provider,model:leg.model,chosen:leg.chosen})):null})(),cards,review:assignment!==null&&assignment.state==="ready-to-check"&&assignment.receipt!==null&&assignment.receipt.taskId===current.id?{run:assignment.receipt.runId,receipt:assignment.receipt.digest,source:revisionSourceOf(scope?.digest??null),accept:acceptFactsOf(store,assignment,viewer,evidenceRoot)}:null,shell:shellOf(store,family,assignment!==null&&assignment.state==="ready-to-check"&&assignment.receipt!==null&&assignment.receipt.taskId===current.id?assignment.receipt.runId:builds[0]?.id??null),failure:current.state==="failed"?failureOf(store,ref?.id??null,current.repo,builds):null,waiting:(()=>{const waiting=waitingOf(store,current.id,now);if(waiting===null)return null;const last=waiting.attempt==="plan"?latestFinishedPlanner(plannerRuns):latestFinishedAttempt(builds);return{...waiting,agentSaid:last!==null&&last.outcome==="failed"?agentSaidOf(store,last.id):null}})(),held:current.state==="cancelled"||current.state==="done"?null:heldOf(store,ref?.id??null,builds,now),retry:current.state==="failed"?(()=>{const pins=retryPinsOf(store,current.id);return pins===null?null:{run:pins.run,digest:pins.digest}})():null,planStopped:planStoppedOf(store,current.id,ref?.id??null,plannerRuns),plan:planAskOf(store,current.id,current.state,ref,scope,live!==null,now),planQueued:planQueuedOf(store,current.state,ref,scope,live!==null,now),approval:scope!==null&&approved&&scope.approvedBy!==null?{by:scope.approvedBy,you:viewer!==null&&scope.approvedBy===viewer,automatic:AUTOMATIC.has(String(scope.approvalBasis??""))}:null,scopeDigest:scope?.digest??null,agentChoices:scope===null||!withChoices?null:agentChoicesOf(store,current.id,ref,now),pendingAgentChange:ref===null?null:pendingAgentChangeOf(store,ref.id),landing:assignment===null?null:landedNowOf(store,assignment),...card?.status.check==="failed"||card?.status.check==="stale"||card?.status.check==="unreadable"?{check:card.status.check}:{},...(()=>{const offer=runChecksOfferOf(store,assignment,card?.status.check??null);return offer===null?{}:{runChecks:offer}})(),...(()=>{const offer=assignment===null||assignment.receipt?.taskId!==current.id?null:behindMainOfferOf(store,assignment,scope?.digest??null);return offer===null?{}:{behindMain:offer}})(),familyBuilds:familyBuildsOf(store,family,current.refId,runs),room:`task:${encodeURIComponent(root.id)}`}}function familyBuildsOf(store,family,currentRef,currentRuns){const isBuild=run=>run.role==="builder"||run.role==="scout"||run.role==="repair";return family.versions.flatMap(version=>version.refId===currentRef?currentRuns:store.runsFor(version.refId)).filter(isBuild).map(run=>run.id).sort((a,b)=>b-a)}function runChecksOfferOf(store,assignment,check){if(check!=="failed"&&check!=="stale"&&check!=="unreadable"&&check!=="not-run")return null;const receipt=assignment?.receipt??null;if(receipt===null||receipt.head===null||receipt.completionKind==="research-report"||assignment.repo===null||store.isDemo())return null;const level=store.liveVerifyCommand(assignment.repo)!==null?"full":liveQuickCommand(store,assignment.repo)!==null?"quick":null;return level===null?null:{run:receipt.runId,level}}function behindMainOfferOf(store,assignment,scopeDigest){const receipt=assignment.receipt;if(assignment.state!=="complete"||receipt===null||receipt.head===null||receipt.completionKind==="research-report"||assignment.repo===null||store.isDemo()||publishesThroughPullRequests(store,assignment.repo)||landedNowOf(store,assignment)!==null)return null;const standing=behindMainOf(store,assignment,void 0);return standing===null||standing.main===null||standing.behind===null||standing.behind===0||standing.conflict!==null?null:{run:receipt.runId,receipt:receipt.digest,source:revisionSourceOf(scopeDigest),main:standing.main,behind:standing.behind,note:upToDateNote(standing.main)}}export const SHELL_NO_RESULT="This build has no saved result yet. Wait for it to finish (or stop it), then open the build shell.",SHELL_NO_COMMIT="This build has no saved commit to open a terminal on.";function shellOf(store,family,runId){if(runId===null)return null;const run=resultRunsOf(store,family).find(one=>one.id===runId)??takeOverRunsOf(store,family).find(one=>one.id===runId)??null;return run===null?{run:runId,why:SHELL_NO_RESULT}:takeOverRevisionOf(run)===null?{run:runId,why:SHELL_NO_COMMIT}:{run:runId,why:null}}function failureOf(store,taskRef,repo,builds){const last=latestFinishedAttempt(builds),failedInARow=taskRef===null?0:Number(store.handle.prepare("SELECT strikes FROM task_ref WHERE id = ?").get(taskRef)?.strikes??0),agentSaid=last===null?null:agentSaidOf(store,last.id),codexHint=last===null||last.provider!=="codex"?null:codexOfflineDependencySuggestion({provider:last.provider,agentSaid,hasSetup:repo!==null&&store.liveWorktreeSetup(repo)!==null});return{line:failedAttemptSentence(last?.reason),failedInARow,suggestion:last===null?null:codexHint??stopSuggestionOf(last.reason),agentSaid}}function cancelledCards(builds,at){const out=[],latest=builds[0]??null;if(latest!==null){const failed=latest.outcome==="failed"||latest.outcome==="refused"||wasInterrupted(latest);out.push({key:"build",label:"Build",state:failed?"stuck":"done",mark:failed?"stuck":"done",sentence:failed?failedAttemptSentence(latest.reason).replace(/[.\s]+$/,""):"The build finished",at:latest.finishedAt,needsYou:!1,inChain:!0,...runFacts(builds)})}return out.push({key:"ready",label:"Cancelled",state:"skipped",mark:"skipped",sentence:"Cancelled: nothing else will run for this task.",at,needsYou:!1,inChain:!0,...runFacts([])}),out}function heldOf(store,taskRef,builds,now){if(taskRef===null)return null;const hold=store.activeHolds(taskRef,now).find(one=>one.ownerKind==="operator")??null;if(hold===null)return null;const last=latestFinishedAttempt(builds);return{id:hold.id,reason:hold.reason,lastFailure:last!==null&&last.outcome==="failed"?failedAttemptSentence(last.reason).replace(/[.\s]+$/,""):null}}export function waitingOf(store,taskId,now){return waitingForTasks(store,[taskId],now).get(taskId)??null}export function waitingForTasks(store,taskIds,now){const out=new Map,ids=[...new Set(taskIds)];if(ids.length===0)return out;const at=now.toISOString(),rows=store.handle.prepare(`SELECT task.id AS task,
|
|
1
|
+
import{closeSync,constants as fsConstants,fstatSync,openSync,readSync,realpathSync}from"node:fs";import{dirname,join,sep}from"node:path";import{agentSaidOf,planProblemsOf}from"./store.js";import{codexOfflineDependencySuggestion,failedAttemptSentence,latestFinishedAttempt,stopSuggestionOf}from"./needs-you.js";import{pendingAgentChangeOf,planSourceOf,retryPinsOf}from"./local-owner-acts.js";import{assignmentOf,owedAcceptance,personCompletionRefusal}from"./assignment.js";import{assignmentCardOf}from"./assignment-presentation.js";import{behindMainOf,landedNowOf,upToDateNote}from"./merge-checklist.js";import{publishesThroughPullRequests}from"./local-landing.js";import{liveQuickCommand}from"./check-levels.js";import{assignmentStageOf,stageOfCode}from"./task-status.js";import{taskRoad}from"./first-run.js";import{stepRowsOf}from"./workspace-projection.js";import{approvalOf}from"./scope.js";import{approvalSummaryOf,summaryContextOf}from"./approval-summary.js";import{approvalDecisionFor}from"./approval-decision.js";import{taskWorkSummaryOf}from"./work-summary.js";import{structuredHandoffView,terminalDiffView}from"./result-evidence-readers.js";import{parseReviewDiff,proofBundleView}from"./result-projection.js";import{parseReport}from"./scout-report.js";import{revisionSourceOf}from"./result-review.js";import{DIFF_CONTEXT_MAX,ENGINE_API_VERSION}from"./contracts/engine-api.js";import{agentSetupOf,agentUsesOf,detectionLines,NO_AGENT_YET,npmRegistryOf}from"./agent-detect.js";import{cleanSourcePathsFromNumstat,isTransientDiffBloat,readVerifiedArtifact,redactSecretLines,reportShotsOf,scanPatchForSecrets}from"./evidence.js";import{fastCompletionProblem}from"./fast-start.js";import{cleanLiveText,HIDDEN_LINE}from"./live-records.js";import{keyShaped}from"./agent-thread/session.js";import{viewedGitSync}from"./teardown-git.js";import{wasInterrupted}from"./run-ending.js";import{agentChoicesFor,routeOfTask}from"./agentconfig.js";const isResultRun=run=>run.finishedAt!==null&&(run.role==="builder"||run.role==="scout"),isTakeOverRun=run=>run.role==="builder"||run.role==="scout",VALID_SHA=/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/,validSha=value=>value!=null&&VALID_SHA.test(value)?value:null;export const takeOverRevisionOf=run=>validSha(run.headRevision)??validSha(run.baseRevision);const AUTOMATIC=new Set(["auto-check","auto-green"]);export function stepCardsOf({store,family,now,access,evidenceRoot,viewer=null,withChoices=!1,canSee=repo=>repo===null?access.principal==="operator"&&access.includeUnplaced===!0:access.repos===null||access.repos.includes(repo)}){const current=family.current,root=family.root,ref=store.lookupRef(current.id),scope=store.getScope(current.id),runs=ref===null?[]:store.runsFor(ref.id),assignment=assignmentOf(store,current.id,now,access,evidenceRoot),item=taskWorkSummaryOf(store,current.id,now,access),live=runs.find(run=>run.finishedAt===null)??null,planning=live?.role==="planner",card=assignment===null||item===null?null:assignmentCardOf(assignment,{workStatus:item.status,planning}),approved=approvalOf(scope).approved,report=ref?.deliverable==="report",plannerRuns=runs.filter(run=>run.role==="planner"),justCode=plannerRuns.length===0&&(ref?.plan??null)===null&&approved,facts={journey:current.state==="cancelled"||item===null?null:(()=>{const read=assignment!==null?assignmentStageOf(assignment,{token:item.status.token,views:item.status.views},planning):stageOfCode(item.status.token,{planning}),checks=card?.status.check??null;return taskRoad(read,approved,current.state==="done",{checks,report})})(),scout:report,status:card===null?null:{status:{headline:card.status.headline},attempts:card.attempts},approved:scope!==null&&approved&&scope.approvedBy!==null&&scope.approvedAt!==null?{by:scope.approvedBy,at:scope.approvedAt,automatic:AUTOMATIC.has(String(scope.approvalBasis??"")),rule:null}:null,approve:null,plan:plannerRuns.length===0&&ref?.plan==null?null:{lead:null,by:plannerRuns[0]?.provider??null,at:plannerRuns.find(run=>run.finishedAt!==null)?.finishedAt??null,planning},result:assignment?.receipt==null?null:{selected:assignment.receipt},thread:runs.filter(isResultRun).map(run=>({kind:"result",at:run.finishedAt}))},rows=stepRowsOf(facts),builds=runs.filter(run=>run.role==="builder"||run.role==="scout"||run.role==="repair"),reviews=runs.filter(run=>run.role==="reviewer"),behind={plan:plannerRuns.filter(run=>run.parentRun===null),approve:[],build:builds,checks:[],review:reviews,ready:[]},terms=scope===null||approved?null:(()=>{const summary=approvalSummaryOf(scope,summaryContextOf(store,current.id,scope,now));return{key:summary.key,revision:summary.revision,decision:approvalDecisionFor(store,current.id,scope,now,{evidenceRoot,access,viewer,canSee}),rows:[...summary.revisionChanges,...summary.decisions,...summary.why===null?[]:[{label:"Why model",words:summary.why}],...summary.differs].map(one=>({label:one.label,words:one.words,lines:"lines"in one?[...one.lines??[]]:[]})),warnings:summary.warnings.map(one=>one.words),usualLabel:summary.usualLabel,usual:summary.usual.map(one=>({label:one.label,words:one.words}))}})(),cards=current.state==="cancelled"?cancelledCards(builds,current.updatedAt??null):rows===null?null:rows.map(row=>({key:row.key,label:row.label,state:row.state,mark:row.mark,sentence:row.sentence,at:row.at,needsYou:row.needsYou,inChain:!(justCode&&(row.key==="plan"||row.key==="approve")),...runFacts(behind[row.key]),...row.key==="approve"&&terms!==null?{terms}:{}}));if(cards!==null&&reviews.length>0){const latest=reviews[0],state=latest.finishedAt===null?"current":latest.outcome==="failed"||latest.outcome==="refused"?"stuck":"done",at=cards.findIndex(one=>one.key==="ready");cards.splice(at===-1?cards.length:at,0,{key:"review",label:"Review",state,mark:state==="current"?"live":state==="stuck"?"stuck":"done",sentence:state==="current"?"Reviewing now":state==="stuck"?"The review didn't finish":"Reviewed",at:latest.finishedAt,needsYou:!1,inChain:!0,...runFacts(reviews)})}return{version:ENGINE_API_VERSION,task:{id:current.id,root:root.id,title:root.title,state:current.state,project:current.repo},chain:justCode?"just-code":"plan-first",headline:current.state==="cancelled"?"Cancelled":card?.status.headline??null,liveRun:live?.id??null,latestRun:runs.reduce((max,run)=>max===null||run.id>max?run.id:max,null),models:(()=>{const routed=routeOfTask(store,current.id,ref,now);return routed?.kind==="route"?routed.route.legs.map(leg=>({phase:leg.phase,provider:leg.provider,model:leg.model,chosen:leg.chosen})):null})(),cards,review:assignment!==null&&assignment.state==="ready-to-check"&&assignment.receipt!==null&&assignment.receipt.taskId===current.id?{run:assignment.receipt.runId,receipt:assignment.receipt.digest,source:revisionSourceOf(scope?.digest??null),accept:acceptFactsOf(store,assignment,viewer,evidenceRoot)}:null,shell:shellOf(store,family,assignment!==null&&assignment.state==="ready-to-check"&&assignment.receipt!==null&&assignment.receipt.taskId===current.id?assignment.receipt.runId:builds[0]?.id??null),failure:current.state==="failed"?failureOf(store,ref?.id??null,current.repo,builds):null,waiting:(()=>{const waiting=waitingOf(store,current.id,now);if(waiting===null)return null;const last=waiting.attempt==="plan"?latestFinishedPlanner(plannerRuns):latestFinishedAttempt(builds);return{...waiting,agentSaid:last!==null&&last.outcome==="failed"?agentSaidOf(store,last.id):null}})(),held:current.state==="cancelled"||current.state==="done"?null:heldOf(store,ref?.id??null,builds,now),retry:current.state==="failed"?(()=>{const pins=retryPinsOf(store,current.id);return pins===null?null:{run:pins.run,digest:pins.digest}})():null,planStopped:planStoppedOf(store,current.id,ref?.id??null,plannerRuns),plan:planAskOf(store,current.id,current.state,ref,scope,live!==null,now),planQueued:planQueuedOf(store,current.state,ref,scope,live!==null,now),approval:scope!==null&&approved&&scope.approvedBy!==null?{by:scope.approvedBy,you:viewer!==null&&scope.approvedBy===viewer,automatic:AUTOMATIC.has(String(scope.approvalBasis??""))}:null,scopeDigest:scope?.digest??null,agentChoices:scope===null||!withChoices?null:agentChoicesOf(store,current.id,ref,now),pendingAgentChange:ref===null?null:pendingAgentChangeOf(store,ref.id),landing:assignment===null?null:landedNowOf(store,assignment),...card?.status.check==="failed"||card?.status.check==="stale"||card?.status.check==="unreadable"?{check:card.status.check}:{},...(()=>{const offer=runChecksOfferOf(store,assignment,card?.status.check??null);return offer===null?{}:{runChecks:offer}})(),...(()=>{const offer=assignment===null||assignment.receipt?.taskId!==current.id?null:behindMainOfferOf(store,assignment,scope?.digest??null);return offer===null?{}:{behindMain:offer}})(),familyBuilds:familyBuildsOf(store,family,current.refId,runs),room:`task:${encodeURIComponent(root.id)}`}}function familyBuildsOf(store,family,currentRef,currentRuns){const isBuild=run=>run.role==="builder"||run.role==="scout"||run.role==="repair";return family.versions.flatMap(version=>version.refId===currentRef?currentRuns:store.runsFor(version.refId)).filter(isBuild).map(run=>run.id).sort((a,b)=>b-a)}function runChecksOfferOf(store,assignment,check){if(check!=="failed"&&check!=="stale"&&check!=="unreadable"&&check!=="not-run")return null;const receipt=assignment?.receipt??null;if(receipt===null||receipt.head===null||receipt.completionKind==="research-report"||assignment.repo===null||store.isDemo())return null;const level=store.liveVerifyCommand(assignment.repo)!==null?"full":liveQuickCommand(store,assignment.repo)!==null?"quick":null;return level===null?null:{run:receipt.runId,level}}function behindMainOfferOf(store,assignment,scopeDigest){const receipt=assignment.receipt;if(assignment.state!=="complete"||receipt===null||receipt.head===null||receipt.completionKind==="research-report"||assignment.repo===null||store.isDemo()||publishesThroughPullRequests(store,assignment.repo)||landedNowOf(store,assignment)!==null)return null;const standing=behindMainOf(store,assignment,void 0);return standing===null||standing.main===null||standing.behind===null||standing.behind===0||standing.conflict!==null?null:{run:receipt.runId,receipt:receipt.digest,source:revisionSourceOf(scopeDigest),main:standing.main,behind:standing.behind,note:upToDateNote(standing.main)}}export const SHELL_NO_RESULT="This build has no saved result yet. Wait for it to finish (or stop it), then open the build shell.",SHELL_NO_COMMIT="This build has no saved commit to open a terminal on.";function shellOf(store,family,runId){if(runId===null)return null;const run=resultRunsOf(store,family).find(one=>one.id===runId)??takeOverRunsOf(store,family).find(one=>one.id===runId)??null;return run===null?{run:runId,why:SHELL_NO_RESULT}:takeOverRevisionOf(run)===null?{run:runId,why:SHELL_NO_COMMIT}:{run:runId,why:null}}function failureOf(store,taskRef,repo,builds){const last=latestFinishedAttempt(builds),failedInARow=taskRef===null?0:Number(store.handle.prepare("SELECT strikes FROM task_ref WHERE id = ?").get(taskRef)?.strikes??0),agentSaid=last===null?null:agentSaidOf(store,last.id),codexHint=last===null||last.provider!=="codex"?null:codexOfflineDependencySuggestion({provider:last.provider,agentSaid,hasSetup:repo!==null&&store.liveWorktreeSetup(repo)!==null});return{line:failedAttemptSentence(last?.reason),failedInARow,suggestion:last===null?null:codexHint??stopSuggestionOf(last.reason),agentSaid}}function cancelledCards(builds,at){const out=[],latest=builds[0]??null;if(latest!==null){const failed=latest.outcome==="failed"||latest.outcome==="refused"||wasInterrupted(latest);out.push({key:"build",label:"Build",state:failed?"stuck":"done",mark:failed?"stuck":"done",sentence:failed?failedAttemptSentence(latest.reason).replace(/[.\s]+$/,""):"The build finished",at:latest.finishedAt,needsYou:!1,inChain:!0,...runFacts(builds)})}return out.push({key:"ready",label:"Cancelled",state:"skipped",mark:"skipped",sentence:"Cancelled: nothing else will run for this task.",at,needsYou:!1,inChain:!0,...runFacts([])}),out}function heldOf(store,taskRef,builds,now){if(taskRef===null)return null;const hold=store.activeHolds(taskRef,now).find(one=>one.ownerKind==="operator")??null;if(hold===null)return null;const last=latestFinishedAttempt(builds);return{id:hold.id,reason:hold.reason,lastFailure:last!==null&&last.outcome==="failed"?failedAttemptSentence(last.reason).replace(/[.\s]+$/,""):null}}export function waitingOf(store,taskId,now){return waitingForTasks(store,[taskId],now).get(taskId)??null}export function waitingForTasks(store,taskIds,now){const out=new Map,ids=[...new Set(taskIds)];if(ids.length===0)return out;const at=now.toISOString(),rows=store.handle.prepare(`SELECT task.id AS task,
|
|
2
2
|
EXISTS (SELECT 1 FROM hold WHERE hold.task_ref = task_ref.id AND hold.owner_kind = 'backoff' AND (hold.until IS NULL OR hold.until > ?)) AS held,
|
|
3
3
|
(SELECT hold.until FROM hold WHERE hold.task_ref = task_ref.id AND hold.owner_kind = 'backoff' AND (hold.until IS NULL OR hold.until > ?) ORDER BY hold.held_at, hold.id LIMIT 1) AS until,
|
|
4
4
|
(SELECT run.outcome FROM run WHERE run.task_ref = task_ref.id AND run.role IN ('builder', 'scout', 'repair', 'planner') AND NOT (run.role = 'planner' AND run.parent_run IS NOT NULL) AND (run.finished_at IS NOT NULL OR run.outcome IS NOT NULL) ORDER BY run.id DESC LIMIT 1) AS outcome,
|