@bastani/atomic 0.9.21-alpha.1 → 0.9.21-alpha.2
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 +27 -0
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/CHANGELOG.md +11 -0
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/subagents/src/extension/index.bundle.mjs +292 -60
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +11 -0
- package/dist/builtin/workflows/builtin/adversarial-verification.js +3 -3
- package/dist/builtin/workflows/builtin/{chunk-cw86srkf.js → chunk-632fxeb8.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-w18kbz63.js → chunk-94f8zfz1.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-kspvwc24.js → chunk-9cm2ckq2.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-jaj27rqc.js → chunk-a1ar035d.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-wh19f5ee.js → chunk-d3xhj946.js} +5 -4
- package/dist/builtin/workflows/builtin/{chunk-crw7q5g1.js → chunk-gyjck9z8.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-maqv731g.js → chunk-hj8mh07f.js} +10 -6
- package/dist/builtin/workflows/builtin/{chunk-0nrgfbag.js → chunk-kb7s3gx2.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-73c5tayt.js → chunk-kgn5wz1c.js} +19 -1
- package/dist/builtin/workflows/builtin/{chunk-2hak3b7g.js → chunk-nkj4qhj6.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-bzdvx2xr.js → chunk-r97ndfvt.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-vkmpdat4.js → chunk-wf876n16.js} +1 -1
- package/dist/builtin/workflows/builtin/classify-and-act.js +3 -3
- package/dist/builtin/workflows/builtin/fan-out-and-synthesize.js +3 -3
- package/dist/builtin/workflows/builtin/generate-and-filter.js +3 -3
- package/dist/builtin/workflows/builtin/goal.js +4 -4
- package/dist/builtin/workflows/builtin/index.js +12 -12
- package/dist/builtin/workflows/builtin/loop-until-done.js +3 -3
- package/dist/builtin/workflows/builtin/open-claude-design.js +3 -3
- package/dist/builtin/workflows/builtin/ralph.js +4 -4
- package/dist/builtin/workflows/builtin/steering-context.js +1 -1
- package/dist/builtin/workflows/builtin/tournament.js +3 -3
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +40 -11
- package/dist/builtin/workflows/src/index.js +9 -3
- package/dist/builtin/workflows/src/shared/authoring-contract-stage.d.ts +6 -1
- package/dist/cli/auth-command.js +5 -0
- package/dist/cli/auth-command.js.map +1 -1
- package/dist/cli/credential-print.js +2 -0
- package/dist/cli/credential-print.js.map +1 -1
- package/dist/cli/experimental/command.js +5 -2
- package/dist/cli/experimental/command.js.map +1 -1
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +4 -4
- package/dist/config.js +4 -4
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
- package/dist/core/agent-session-extension-bindings.js +9 -4
- package/dist/core/agent-session-extension-bindings.js.map +1 -1
- package/dist/core/agent-session-methods.d.ts +4 -4
- package/dist/core/agent-session-methods.d.ts.map +1 -1
- package/dist/core/agent-session-methods.js.map +1 -1
- package/dist/core/agent-session-prompt.d.ts +4 -4
- package/dist/core/agent-session-prompt.d.ts.map +1 -1
- package/dist/core/agent-session-prompt.js +38 -15
- package/dist/core/agent-session-prompt.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +14 -9
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session-types.d.ts +4 -1
- package/dist/core/agent-session-types.d.ts.map +1 -1
- package/dist/core/agent-session-types.js.map +1 -1
- package/dist/core/agent-session.d.ts +1 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +140 -95
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-storage-backends.js +2 -3
- package/dist/core/auth-storage-backends.js.map +1 -1
- package/dist/core/auth-storage.js +4 -1
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/builtin-resource-loader.js +9 -0
- package/dist/core/builtin-resource-loader.js.map +1 -1
- package/dist/core/cache-warmer.js +8 -1
- package/dist/core/cache-warmer.js.map +1 -1
- package/dist/core/compaction/range-planner.js +6 -0
- package/dist/core/compaction/range-planner.js.map +1 -1
- package/dist/core/execution-model-router.d.ts +13 -3
- package/dist/core/execution-model-router.d.ts.map +1 -1
- package/dist/core/execution-model-router.js +227 -131
- package/dist/core/execution-model-router.js.map +1 -1
- package/dist/core/export-html/template-js/entries-navigation.js +16 -6
- package/dist/core/export-html/template-js/initialization.js +34 -11
- package/dist/core/export-html/template.css +10 -0
- package/dist/core/export-html/template.js +50 -17
- package/dist/core/extensions/context-types.d.ts +2 -0
- package/dist/core/extensions/context-types.d.ts.map +1 -1
- package/dist/core/extensions/context-types.js.map +1 -1
- package/dist/core/extensions/host-input.js +8 -4
- package/dist/core/extensions/host-input.js.map +1 -1
- package/dist/core/extensions/reactive-widget.js +1 -0
- package/dist/core/extensions/reactive-widget.js.map +1 -1
- package/dist/core/extensions/runner-context.d.ts +1 -0
- package/dist/core/extensions/runner-context.d.ts.map +1 -1
- package/dist/core/extensions/runner-context.js +4 -0
- package/dist/core/extensions/runner-context.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +1 -0
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +48 -30
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/runtime-types.d.ts +1 -0
- package/dist/core/extensions/runtime-types.d.ts.map +1 -1
- package/dist/core/extensions/runtime-types.js.map +1 -1
- package/dist/core/extensions/workflow-activity-hub.js +9 -7
- package/dist/core/extensions/workflow-activity-hub.js.map +1 -1
- package/dist/core/footer-data-provider.js +24 -23
- package/dist/core/footer-data-provider.js.map +1 -1
- package/dist/core/keybindings.js +1 -0
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/mandatory-resource-loader.js +4 -1
- package/dist/core/mandatory-resource-loader.js.map +1 -1
- package/dist/core/model-config.js +2 -0
- package/dist/core/model-config.js.map +1 -1
- package/dist/core/model-registry.js +1 -0
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/{model-routing-task.d.ts → model-routing-bytes.d.ts} +1 -4
- package/dist/core/model-routing-bytes.d.ts.map +1 -0
- package/dist/core/model-routing-bytes.js +33 -0
- package/dist/core/model-routing-bytes.js.map +1 -0
- package/dist/core/model-routing-candidates.d.ts +42 -0
- package/dist/core/model-routing-candidates.d.ts.map +1 -0
- package/dist/core/model-routing-candidates.js +309 -0
- package/dist/core/model-routing-candidates.js.map +1 -0
- package/dist/core/model-routing-constraints.d.ts +4 -0
- package/dist/core/model-routing-constraints.d.ts.map +1 -1
- package/dist/core/model-routing-constraints.js +13 -1
- package/dist/core/model-routing-constraints.js.map +1 -1
- package/dist/core/model-routing-debug.d.ts +9 -0
- package/dist/core/model-routing-debug.d.ts.map +1 -0
- package/dist/core/model-routing-debug.js +14 -0
- package/dist/core/model-routing-debug.js.map +1 -0
- package/dist/core/model-routing-evals.d.ts +50 -0
- package/dist/core/model-routing-evals.d.ts.map +1 -0
- package/dist/core/model-routing-evals.js +190 -0
- package/dist/core/model-routing-evals.js.map +1 -0
- package/dist/core/model-routing-needs.d.ts +75 -0
- package/dist/core/model-routing-needs.d.ts.map +1 -0
- package/dist/core/model-routing-needs.js +176 -0
- package/dist/core/model-routing-needs.js.map +1 -0
- package/dist/core/model-runtime-streaming.js +3 -0
- package/dist/core/model-runtime-streaming.js.map +1 -1
- package/dist/core/model-runtime.js +26 -14
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/models-store.js +2 -3
- package/dist/core/models-store.js.map +1 -1
- package/dist/core/output-guard.js +1 -0
- package/dist/core/output-guard.js.map +1 -1
- package/dist/core/package-manager-paths.d.ts +2 -1
- package/dist/core/package-manager-paths.d.ts.map +1 -1
- package/dist/core/package-manager-paths.js +4 -3
- package/dist/core/package-manager-paths.js.map +1 -1
- package/dist/core/package-manager.js +1 -0
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/resource-loader-assets.d.ts.map +1 -1
- package/dist/core/resource-loader-assets.js +9 -7
- package/dist/core/resource-loader-assets.js.map +1 -1
- package/dist/core/resource-loader-core.js +49 -0
- package/dist/core/resource-loader-core.js.map +1 -1
- package/dist/core/runtime-credentials.js +2 -1
- package/dist/core/runtime-credentials.js.map +1 -1
- package/dist/core/session-cwd.js +1 -0
- package/dist/core/session-cwd.js.map +1 -1
- package/dist/core/session-manager-archive.d.ts.map +1 -1
- package/dist/core/session-manager-archive.js +4 -2
- package/dist/core/session-manager-archive.js.map +1 -1
- package/dist/core/session-manager-core.js +11 -7
- package/dist/core/session-manager-core.js.map +1 -1
- package/dist/core/session-manager-storage.d.ts +10 -4
- package/dist/core/session-manager-storage.d.ts.map +1 -1
- package/dist/core/session-manager-storage.js +12 -6
- package/dist/core/session-manager-storage.js.map +1 -1
- package/dist/core/settings-manager-basic-accessors.d.ts +2 -1
- package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
- package/dist/core/settings-manager-basic-accessors.js +21 -0
- package/dist/core/settings-manager-basic-accessors.js.map +1 -1
- package/dist/core/settings-manager-core.js +13 -7
- package/dist/core/settings-manager-core.js.map +1 -1
- package/dist/core/settings-manager.d.ts +1 -1
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/settings-storage.js +6 -0
- package/dist/core/settings-storage.js.map +1 -1
- package/dist/core/settings-types.d.ts +8 -0
- package/dist/core/settings-types.d.ts.map +1 -1
- package/dist/core/settings-types.js.map +1 -1
- package/dist/core/structured-output/index.d.ts.map +1 -1
- package/dist/core/structured-output/index.js +4 -1
- package/dist/core/structured-output/index.js.map +1 -1
- package/dist/core/structured-output/invalid-output.js +1 -0
- package/dist/core/structured-output/invalid-output.js.map +1 -1
- package/dist/core/tasks/agent-adapter.js +5 -3
- package/dist/core/tasks/agent-adapter.js.map +1 -1
- package/dist/core/tasks/child-command-owner.js +3 -7
- package/dist/core/tasks/child-command-owner.js.map +1 -1
- package/dist/core/tasks/completion.js +5 -1
- package/dist/core/tasks/completion.js.map +1 -1
- package/dist/core/tasks/owner-store.js +12 -8
- package/dist/core/tasks/owner-store.js.map +1 -1
- package/dist/core/tasks/supervisor.js +14 -35
- package/dist/core/tasks/supervisor.js.map +1 -1
- package/dist/core/tools/ask-user-question/state/build-questionnaire.js +13 -4
- package/dist/core/tools/ask-user-question/state/build-questionnaire.js.map +1 -1
- package/dist/core/tools/ask-user-question/state/questionnaire-session.js +11 -1
- package/dist/core/tools/ask-user-question/state/questionnaire-session.js.map +1 -1
- package/dist/core/tools/ask-user-question/view/components/chat-row-view.js +1 -0
- package/dist/core/tools/ask-user-question/view/components/chat-row-view.js.map +1 -1
- package/dist/core/tools/ask-user-question/view/components/multi-select-view.js +1 -0
- package/dist/core/tools/ask-user-question/view/components/multi-select-view.js.map +1 -1
- package/dist/core/tools/ask-user-question/view/components/option-list-view.js +1 -0
- package/dist/core/tools/ask-user-question/view/components/option-list-view.js.map +1 -1
- package/dist/core/tools/ask-user-question/view/components/preview/markdown-content-cache.js +5 -0
- package/dist/core/tools/ask-user-question/view/components/preview/markdown-content-cache.js.map +1 -1
- package/dist/core/tools/ask-user-question/view/components/preview/preview-block-renderer.js +2 -0
- package/dist/core/tools/ask-user-question/view/components/preview/preview-block-renderer.js.map +1 -1
- package/dist/core/tools/ask-user-question/view/components/preview/preview-pane.js +13 -8
- package/dist/core/tools/ask-user-question/view/components/preview/preview-pane.js.map +1 -1
- package/dist/core/tools/ask-user-question/view/components/submit-picker.js +1 -0
- package/dist/core/tools/ask-user-question/view/components/submit-picker.js.map +1 -1
- package/dist/core/tools/ask-user-question/view/components/tab-bar.js +1 -0
- package/dist/core/tools/ask-user-question/view/components/tab-bar.js.map +1 -1
- package/dist/core/tools/ask-user-question/view/components/wrapping-select.js +30 -24
- package/dist/core/tools/ask-user-question/view/components/wrapping-select.js.map +1 -1
- package/dist/core/tools/ask-user-question/view/dialog-builder.js +5 -0
- package/dist/core/tools/ask-user-question/view/dialog-builder.js.map +1 -1
- package/dist/core/tools/ask-user-question/view/props-adapter.js +8 -0
- package/dist/core/tools/ask-user-question/view/props-adapter.js.map +1 -1
- package/dist/core/tools/ask-user-question/view/tab-content-strategy.js +4 -4
- package/dist/core/tools/ask-user-question/view/tab-content-strategy.js.map +1 -1
- package/dist/core/tools/bash.js +5 -8
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/edit-batch.js +4 -0
- package/dist/core/tools/edit-batch.js.map +1 -1
- package/dist/core/tools/edit.js +2 -0
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/file-mutation-coordinator.js +9 -0
- package/dist/core/tools/file-mutation-coordinator.js.map +1 -1
- package/dist/core/tools/find.js +1 -1
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/hashline-engine/fs.js +1 -1
- package/dist/core/tools/hashline-engine/fs.js.map +1 -1
- package/dist/core/tools/hashline-engine/input.js +4 -0
- package/dist/core/tools/hashline-engine/input.js.map +1 -1
- package/dist/core/tools/hashline-engine/mismatch.js +6 -0
- package/dist/core/tools/hashline-engine/mismatch.js.map +1 -1
- package/dist/core/tools/hashline-engine/patcher.js +13 -0
- package/dist/core/tools/hashline-engine/patcher.js.map +1 -1
- package/dist/core/tools/hashline-engine/recovery.js +1 -0
- package/dist/core/tools/hashline-engine/recovery.js.map +1 -1
- package/dist/core/tools/output-accumulator.js +20 -13
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/core/tools/persisted-output-file.js +9 -3
- package/dist/core/tools/persisted-output-file.js.map +1 -1
- package/dist/core/tools/resource-selectors.js +1 -0
- package/dist/core/tools/resource-selectors.js.map +1 -1
- package/dist/core/tools/write.js +1 -0
- package/dist/core/tools/write.js.map +1 -1
- package/dist/core/trust-manager.js +1 -0
- package/dist/core/trust-manager.js.map +1 -1
- package/dist/core/workflow-stage-admission.js +17 -10
- package/dist/core/workflow-stage-admission.js.map +1 -1
- package/dist/extensions/llama/client.js +2 -0
- package/dist/extensions/llama/client.js.map +1 -1
- package/dist/extensions/llama/huggingface-ui.js +17 -9
- package/dist/extensions/llama/huggingface-ui.js.map +1 -1
- package/dist/extensions/llama/huggingface.js +2 -0
- package/dist/extensions/llama/huggingface.js.map +1 -1
- package/dist/extensions/llama/ui.js +11 -3
- package/dist/extensions/llama/ui.js.map +1 -1
- package/dist/index.d.ts +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/modes/interactive/components/armin.js +10 -6
- package/dist/modes/interactive/components/armin.js.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js +10 -2
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/atomic-working-status.js +10 -2
- package/dist/modes/interactive/components/atomic-working-status.js.map +1 -1
- package/dist/modes/interactive/components/bash-execution.js +9 -4
- package/dist/modes/interactive/components/bash-execution.js.map +1 -1
- package/dist/modes/interactive/components/bordered-loader.js +3 -0
- package/dist/modes/interactive/components/bordered-loader.js.map +1 -1
- package/dist/modes/interactive/components/branch-summary-message.js +4 -1
- package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
- package/dist/modes/interactive/components/chat-message-renderer.js +2 -1
- package/dist/modes/interactive/components/chat-message-renderer.js.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-state.js +63 -31
- package/dist/modes/interactive/components/chat-session-host-state.js.map +1 -1
- package/dist/modes/interactive/components/chat-session-host.js +8 -1
- package/dist/modes/interactive/components/chat-session-host.js.map +1 -1
- package/dist/modes/interactive/components/chat-transcript.js +24 -14
- package/dist/modes/interactive/components/chat-transcript.js.map +1 -1
- package/dist/modes/interactive/components/compaction-boundary-message.js +2 -1
- package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -1
- package/dist/modes/interactive/components/config-selector-list.js +15 -6
- package/dist/modes/interactive/components/config-selector-list.js.map +1 -1
- package/dist/modes/interactive/components/config-selector.js +7 -1
- package/dist/modes/interactive/components/config-selector.js.map +1 -1
- package/dist/modes/interactive/components/countdown-timer.js +2 -0
- package/dist/modes/interactive/components/countdown-timer.js.map +1 -1
- package/dist/modes/interactive/components/custom-editor.js +21 -1
- package/dist/modes/interactive/components/custom-editor.js.map +1 -1
- package/dist/modes/interactive/components/custom-entry.js +4 -1
- package/dist/modes/interactive/components/custom-entry.js.map +1 -1
- package/dist/modes/interactive/components/custom-message.js +9 -1
- package/dist/modes/interactive/components/custom-message.js.map +1 -1
- package/dist/modes/interactive/components/daxnuts.js +8 -6
- package/dist/modes/interactive/components/daxnuts.js.map +1 -1
- package/dist/modes/interactive/components/dynamic-border.js +1 -0
- package/dist/modes/interactive/components/dynamic-border.js.map +1 -1
- package/dist/modes/interactive/components/extension-editor.js +7 -1
- package/dist/modes/interactive/components/extension-editor.js.map +1 -1
- package/dist/modes/interactive/components/extension-input.js +8 -2
- package/dist/modes/interactive/components/extension-input.js.map +1 -1
- package/dist/modes/interactive/components/extension-selector.js +9 -1
- package/dist/modes/interactive/components/extension-selector.js.map +1 -1
- package/dist/modes/interactive/components/first-time-setup.js +4 -2
- package/dist/modes/interactive/components/first-time-setup.js.map +1 -1
- package/dist/modes/interactive/components/footer.js +5 -2
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/host-input-form.js +13 -2
- package/dist/modes/interactive/components/host-input-form.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +9 -3
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +24 -12
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.js +12 -3
- package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
- package/dist/modes/interactive/components/reserved-bottom-overlay.js +11 -2
- package/dist/modes/interactive/components/reserved-bottom-overlay.js.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.js +13 -8
- package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
- package/dist/modes/interactive/components/scroll-widget.js +4 -0
- package/dist/modes/interactive/components/scroll-widget.js.map +1 -1
- package/dist/modes/interactive/components/session-selector-header.js +11 -7
- package/dist/modes/interactive/components/session-selector-header.js.map +1 -1
- package/dist/modes/interactive/components/session-selector-list.js +25 -12
- package/dist/modes/interactive/components/session-selector-list.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +23 -15
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector-submenus.js +19 -1
- package/dist/modes/interactive/components/settings-selector-submenus.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +1 -0
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/show-images-selector.js +1 -0
- package/dist/modes/interactive/components/show-images-selector.js.map +1 -1
- package/dist/modes/interactive/components/skill-invocation-message.js +4 -1
- package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
- package/dist/modes/interactive/components/startup-identity.js +8 -3
- package/dist/modes/interactive/components/startup-identity.js.map +1 -1
- package/dist/modes/interactive/components/task-completion-message.js +2 -0
- package/dist/modes/interactive/components/task-completion-message.js.map +1 -1
- package/dist/modes/interactive/components/task-detail.js +2 -0
- package/dist/modes/interactive/components/task-detail.js.map +1 -1
- package/dist/modes/interactive/components/task-inspector.js +22 -12
- package/dist/modes/interactive/components/task-inspector.js.map +1 -1
- package/dist/modes/interactive/components/task-list.js +2 -0
- package/dist/modes/interactive/components/task-list.js.map +1 -1
- package/dist/modes/interactive/components/task-live-transcript.js +8 -3
- package/dist/modes/interactive/components/task-live-transcript.js.map +1 -1
- package/dist/modes/interactive/components/task-navigation.js +5 -2
- package/dist/modes/interactive/components/task-navigation.js.map +1 -1
- package/dist/modes/interactive/components/task-row.js +2 -0
- package/dist/modes/interactive/components/task-row.js.map +1 -1
- package/dist/modes/interactive/components/theme-selector.js +2 -0
- package/dist/modes/interactive/components/theme-selector.js.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.js +7 -1
- package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +25 -10
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/components/transcript-follow-indicator.js +1 -0
- package/dist/modes/interactive/components/transcript-follow-indicator.js.map +1 -1
- package/dist/modes/interactive/components/tree-selector-component.js +7 -3
- package/dist/modes/interactive/components/tree-selector-component.js.map +1 -1
- package/dist/modes/interactive/components/tree-selector-help.js +1 -0
- package/dist/modes/interactive/components/tree-selector-help.js.map +1 -1
- package/dist/modes/interactive/components/tree-selector-label-input.js +6 -2
- package/dist/modes/interactive/components/tree-selector-label-input.js.map +1 -1
- package/dist/modes/interactive/components/tree-selector-list.js +4 -0
- package/dist/modes/interactive/components/tree-selector-list.js.map +1 -1
- package/dist/modes/interactive/components/trust-selector.js +6 -0
- package/dist/modes/interactive/components/trust-selector.js.map +1 -1
- package/dist/modes/interactive/components/user-message-selector.js +6 -3
- package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
- package/dist/modes/interactive/components/user-message.js +5 -0
- package/dist/modes/interactive/components/user-message.js.map +1 -1
- package/dist/modes/interactive/components/working-status.js +1 -0
- package/dist/modes/interactive/components/working-status.js.map +1 -1
- package/dist/modes/interactive/interactive-autocomplete.js +2 -0
- package/dist/modes/interactive/interactive-autocomplete.js.map +1 -1
- package/dist/modes/interactive/interactive-extension-runtime.js +1 -0
- package/dist/modes/interactive/interactive-extension-runtime.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-base.js +162 -120
- package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-helpers.js +3 -0
- package/dist/modes/interactive/interactive-mode-helpers.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-surface.d.ts +0 -6
- package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
- package/dist/modes/interactive/interactive-resource-disclosure.js +0 -4
- package/dist/modes/interactive/interactive-resource-disclosure.js.map +1 -1
- package/dist/modes/interactive/interactive-resource-rendering.js +0 -12
- package/dist/modes/interactive/interactive-resource-rendering.js.map +1 -1
- package/dist/modes/interactive/interactive-startup-chat-container.js +1 -4
- package/dist/modes/interactive/interactive-startup-chat-container.js.map +1 -1
- package/dist/modes/interactive/model-catalog-refresh.js +1 -3
- package/dist/modes/interactive/model-catalog-refresh.js.map +1 -1
- package/dist/modes/interactive/theme/color-utils.d.ts +5 -0
- package/dist/modes/interactive/theme/color-utils.d.ts.map +1 -1
- package/dist/modes/interactive/theme/color-utils.js +11 -0
- package/dist/modes/interactive/theme/color-utils.js.map +1 -1
- package/dist/modes/interactive/theme/global-theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/global-theme.js +4 -3
- package/dist/modes/interactive/theme/global-theme.js.map +1 -1
- package/dist/modes/interactive/theme/theme-class.js +7 -0
- package/dist/modes/interactive/theme/theme-class.js.map +1 -1
- package/dist/modes/interactive/theme/theme-controller.js +9 -2
- package/dist/modes/interactive/theme/theme-controller.js.map +1 -1
- package/dist/modes/interactive-engine/activity-watchdog.js +8 -3
- package/dist/modes/interactive-engine/activity-watchdog.js.map +1 -1
- package/dist/modes/interactive-engine/engine-custom-ui.js +12 -8
- package/dist/modes/interactive-engine/engine-custom-ui.js.map +1 -1
- package/dist/modes/interactive-engine/engine-dialog-host.js +7 -3
- package/dist/modes/interactive-engine/engine-dialog-host.js.map +1 -1
- package/dist/modes/interactive-engine/engine-health.js +23 -13
- package/dist/modes/interactive-engine/engine-health.js.map +1 -1
- package/dist/modes/interactive-engine/engine-input-form.js +3 -2
- package/dist/modes/interactive-engine/engine-input-form.js.map +1 -1
- package/dist/modes/interactive-engine/engine-monitor.js +13 -1
- package/dist/modes/interactive-engine/engine-monitor.js.map +1 -1
- package/dist/modes/interactive-engine/engine-project-trust.js +2 -1
- package/dist/modes/interactive-engine/engine-project-trust.js.map +1 -1
- package/dist/modes/interactive-engine/engine-render-service.js +7 -4
- package/dist/modes/interactive-engine/engine-render-service.js.map +1 -1
- package/dist/modes/interactive-engine/engine-session-picker.js +3 -2
- package/dist/modes/interactive-engine/engine-session-picker.js.map +1 -1
- package/dist/modes/interactive-engine/input-form-host.js +5 -1
- package/dist/modes/interactive-engine/input-form-host.js.map +1 -1
- package/dist/modes/interactive-engine/isolated-runtime.js +37 -23
- package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
- package/dist/modes/interactive-engine/remote-command-catalog.js +4 -3
- package/dist/modes/interactive-engine/remote-command-catalog.js.map +1 -1
- package/dist/modes/interactive-engine/remote-component.js +24 -12
- package/dist/modes/interactive-engine/remote-component.js.map +1 -1
- package/dist/modes/interactive-engine/remote-frame-clamp.js +3 -3
- package/dist/modes/interactive-engine/remote-frame-clamp.js.map +1 -1
- package/dist/modes/interactive-engine/remote-model-catalog.js +5 -4
- package/dist/modes/interactive-engine/remote-model-catalog.js.map +1 -1
- package/dist/modes/interactive-engine/remote-queue-pause.js +3 -1
- package/dist/modes/interactive-engine/remote-queue-pause.js.map +1 -1
- package/dist/modes/interactive-engine/remote-renderer.js +24 -13
- package/dist/modes/interactive-engine/remote-renderer.js.map +1 -1
- package/dist/modes/interactive-engine/resource-readiness-error.js +1 -0
- package/dist/modes/interactive-engine/resource-readiness-error.js.map +1 -1
- package/dist/modes/interactive-engine/session-picker-host.js +5 -1
- package/dist/modes/interactive-engine/session-picker-host.js.map +1 -1
- package/dist/modes/interactive-engine/terminal-mode-controller.js +2 -1
- package/dist/modes/interactive-engine/terminal-mode-controller.js.map +1 -1
- package/dist/modes/rpc/queued-writer.js +13 -4
- package/dist/modes/rpc/queued-writer.js.map +1 -1
- package/dist/modes/rpc/rpc-bash-request-owners.js +2 -1
- package/dist/modes/rpc/rpc-bash-request-owners.js.map +1 -1
- package/dist/modes/rpc/rpc-client-api.d.ts +8 -4
- package/dist/modes/rpc/rpc-client-api.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client-api.js +10 -3
- package/dist/modes/rpc/rpc-client-api.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +35 -22
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-command-handler.js +6 -6
- package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
- package/dist/modes/rpc/rpc-event-buffer.js +3 -1
- package/dist/modes/rpc/rpc-event-buffer.js.map +1 -1
- package/dist/modes/rpc/rpc-generation-buffer.js +1 -3
- package/dist/modes/rpc/rpc-generation-buffer.js.map +1 -1
- package/dist/modes/rpc/rpc-keybindings-reload.js +4 -1
- package/dist/modes/rpc/rpc-keybindings-reload.js.map +1 -1
- package/dist/modes/rpc/rpc-output-buffer.js +3 -4
- package/dist/modes/rpc/rpc-output-buffer.js.map +1 -1
- package/dist/modes/rpc/rpc-pending-requests.js +1 -3
- package/dist/modes/rpc/rpc-pending-requests.js.map +1 -1
- package/dist/modes/rpc/rpc-provider-auth.js +3 -1
- package/dist/modes/rpc/rpc-provider-auth.js.map +1 -1
- package/dist/modes/rpc/rpc-resource-readiness.js +4 -5
- package/dist/modes/rpc/rpc-resource-readiness.js.map +1 -1
- package/dist/modes/rpc/rpc-session-binding.js +15 -0
- package/dist/modes/rpc/rpc-session-binding.js.map +1 -1
- package/dist/modes/rpc/rpc-terminal-drain.js +3 -0
- package/dist/modes/rpc/rpc-terminal-drain.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +10 -1
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/docs/models/evals.md +883 -39
- package/docs/models/model-selection.md +7 -8
- package/docs/rpc/examples.md +1 -1
- package/docs/rpc/protocol.md +9 -3
- package/docs/sdk/structured-decisions.md +1 -1
- package/docs/sdk.md +3 -3
- package/docs/settings.md +24 -3
- package/docs/subagents/reference.md +22 -4
- package/docs/subagents.md +2 -0
- package/docs/usage.md +3 -3
- package/docs/workflows/api-reference.md +1 -1
- package/docs/workflows/authoring.md +1 -7
- package/docs/workflows/builtins.md +1 -1
- package/docs/workflows/reliable-design.md +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/test.ts +5 -5
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/rpc-client.ts +1 -1
- package/examples/rpc-extension-ui.ts +1 -1
- package/npm-shrinkwrap.json +70 -33
- package/package.json +6 -7
- package/dist/core/model-routing-task.d.ts.map +0 -1
- package/dist/core/model-routing-task.js +0 -120
- package/dist/core/model-routing-task.js.map +0 -1
|
@@ -51078,7 +51078,9 @@ import { createStructuredOutputCapture, runCallback as runCallback2 } from "@bas
|
|
|
51078
51078
|
import {
|
|
51079
51079
|
AutoRoutingInferenceError,
|
|
51080
51080
|
convertToLlm,
|
|
51081
|
-
|
|
51081
|
+
isModelRoutingDebugEnabled,
|
|
51082
|
+
parseModelConstraints,
|
|
51083
|
+
setsProviders
|
|
51082
51084
|
} from "@bastani/atomic";
|
|
51083
51085
|
|
|
51084
51086
|
// dist/builtin/workflows/src/runs/shared/model-fallback-candidates.ts
|
|
@@ -51819,6 +51821,7 @@ function stripWorkflowOnlyOptions(options, defaultSessionDir, meta, pendingStage
|
|
|
51819
51821
|
fallbackModels: _fallbackModels,
|
|
51820
51822
|
fallbackThinkingLevels: _fallbackThinkingLevels,
|
|
51821
51823
|
modelConstraints: _modelConstraints,
|
|
51824
|
+
taskNeeds: _taskNeeds,
|
|
51822
51825
|
inheritedModelConstraints: _inheritedModelConstraints,
|
|
51823
51826
|
routerSelection: _routerSelection,
|
|
51824
51827
|
context,
|
|
@@ -52673,7 +52676,9 @@ class StageSessionController {
|
|
|
52673
52676
|
stageName: this.opts.stageName,
|
|
52674
52677
|
constraints,
|
|
52675
52678
|
signal: this.startupWait.signal,
|
|
52676
|
-
selection: options?.routerSelection
|
|
52679
|
+
selection: options?.routerSelection,
|
|
52680
|
+
...options?.taskNeeds ? { taskNeeds: options.taskNeeds } : {},
|
|
52681
|
+
...setsProviders(parseModelConstraints(options?.modelConstraints)) ? { overrideProviderSettings: true } : {}
|
|
52677
52682
|
});
|
|
52678
52683
|
} catch (error) {
|
|
52679
52684
|
this.startupWait.signal.throwIfAborted();
|
|
@@ -52681,7 +52686,8 @@ class StageSessionController {
|
|
|
52681
52686
|
if (!(error instanceof AutoRoutingInferenceError) || error.currentModelRoute === undefined)
|
|
52682
52687
|
throw error;
|
|
52683
52688
|
this.modelRoute = error.currentModelRoute;
|
|
52684
|
-
|
|
52689
|
+
if (isModelRoutingDebugEnabled())
|
|
52690
|
+
this.modelCatalog?.recordWarning?.(`workflows: stage auto routing failed; running "${this.opts.stageName}" on the current chat model ${this.modelRoute.modelOverride}.`);
|
|
52685
52691
|
}
|
|
52686
52692
|
this.modelRoute.assertCurrent();
|
|
52687
52693
|
this.meta.stageOptions = { ...options, model: this.modelRoute.modelOverride };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Workflow authoring primitives, stage/session contracts, and task option types. */
|
|
2
|
-
import type { ModelConstraints, ModelRoute, ModelRouterOutput } from "@bastani/atomic";
|
|
2
|
+
import type { ModelConstraints, ModelRoute, ModelRouterOutput, TaskNeeds } from "@bastani/atomic";
|
|
3
3
|
import type { Static, TSchema } from "typebox";
|
|
4
4
|
export type { Static, TSchema };
|
|
5
5
|
export type WorkflowSerializablePrimitive = string | number | boolean | null;
|
|
@@ -90,6 +90,9 @@ export interface WorkflowModelCatalogPort {
|
|
|
90
90
|
constraints: readonly ModelConstraints[];
|
|
91
91
|
signal?: AbortSignal;
|
|
92
92
|
selection?: ModelRouterOutput;
|
|
93
|
+
taskNeeds?: TaskNeeds;
|
|
94
|
+
/** The stage's own constraints set a provider list, replacing the user's provider settings. */
|
|
95
|
+
overrideProviderSettings?: boolean;
|
|
93
96
|
}): Promise<ModelRoute>;
|
|
94
97
|
readonly currentModel?: WorkflowModelValue;
|
|
95
98
|
readonly preferredProvider?: string;
|
|
@@ -130,6 +133,8 @@ export interface StageOptions<TSchemaDef extends TSchema | undefined = TSchema |
|
|
|
130
133
|
readonly model?: WorkflowModelValue;
|
|
131
134
|
/** Hard restrictions for automatic model selection and its execution fallbacks. */
|
|
132
135
|
readonly modelConstraints?: ModelConstraints;
|
|
136
|
+
/** What the author already knows about the task, for `model: "auto"`; routing asks only for the rest. */
|
|
137
|
+
readonly taskNeeds?: TaskNeeds;
|
|
133
138
|
readonly mcp?: StageMcpOptions;
|
|
134
139
|
readonly tools?: readonly string[];
|
|
135
140
|
readonly noTools?: "all" | "builtin";
|
package/dist/cli/auth-command.js
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
import { APP_NAME } from "../config.js";
|
|
2
2
|
export class AuthCommandError extends Error {
|
|
3
|
+
// Declared and assigned explicitly rather than as a constructor parameter
|
|
4
|
+
// property: `tsconfig.base.json` sets `erasableSyntaxOnly`, under which a
|
|
5
|
+
// parameter property is TS1294. Root `tsc --noEmit` does not surface it,
|
|
6
|
+
// but the shipped build does.
|
|
7
|
+
exitCode;
|
|
3
8
|
constructor(message, exitCode = 1) {
|
|
4
9
|
super(message);
|
|
5
10
|
this.exitCode = exitCode;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth-command.js","sourceRoot":"","sources":["../../src/cli/auth-command.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAgBxC,MAAM,OAAO,gBAAiB,SAAQ,KAAK;IAO1C,YAAY,OAAe,EAAE,QAAQ,GAAG,CAAC;QACxC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,QAAQ,GAAG,QAAQ,CA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,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACvF,MAAM,IAAI,gBAAgB,CAAC,gDAAgD,CAAC,CAAC;IAC9E,CAAC;IACD,IAAI,CAAC,QAAQ,IAAI,CAAC,KAAK,EAAE,CAAC;QACzB,MAAM,IAAI,gBAAgB,CAAC,8DAA8D,CAAC,CAAC;IAC5F,CAAC;IACD,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;AAC5B,CAAC","sourcesContent":["import { APP_NAME } from \"../config.js\";\nimport type { Args } from \"./args.ts\";\n\nexport type AuthCommandKind = \"check\" | \"api_key\" | \"bearer_token\";\n\nexport interface AuthCommand {\n\tkind: AuthCommandKind;\n\t/** Remaining argv for the normal parser. */\n\targs: string[];\n\tjson: boolean;\n\t/** `auth check` emits a resolved credential only with this explicit opt-in. */\n\tcredentials: boolean;\n\tnoRefresh: boolean;\n\tminExpiryMs?: number;\n}\n\nexport class AuthCommandError extends Error {\n\t// Declared and assigned explicitly rather than as a constructor parameter\n\t// property: `tsconfig.base.json` sets `erasableSyntaxOnly`, under which a\n\t// parameter property is TS1294. Root `tsc --noEmit` does not surface it,\n\t// but the shipped build does.\n\treadonly exitCode: number;\n\n\tconstructor(message: string, exitCode = 1) {\n\t\tsuper(message);\n\t\tthis.exitCode = exitCode;\n\t\tthis.name = \"AuthCommandError\";\n\t}\n}\n\nconst AUTH_COMMAND_USAGE: Record<AuthCommandKind, string> = {\n\tcheck: `${APP_NAME} auth check [--provider <provider>] [--model <model>] [--json] [--credentials] [--no-refresh]`,\n\tapi_key: `${APP_NAME} auth print-api-key --model <model> [--provider <provider>]`,\n\tbearer_token: `${APP_NAME} auth print-bearer-token --model <model> [--provider <provider>] [--min-expiry <duration>]`,\n};\n\nexport function getAuthCommandName(kind: AuthCommandKind): string {\n\treturn kind === \"check\" ? \"auth check\" : kind === \"api_key\" ? \"auth print-api-key\" : \"auth print-bearer-token\";\n}\n\nexport function getAuthCommandUsage(kind: AuthCommandKind): string {\n\treturn AUTH_COMMAND_USAGE[kind];\n}\n\nexport function isAuthCommandHelp(args: string[]): boolean {\n\tif (args[0] !== \"auth\") return false;\n\tif (args[1] === undefined || args[1] === \"help\" || args[1] === \"--help\" || args[1] === \"-h\") return true;\n\tconst terminator = args.indexOf(\"--\", 2);\n\tconst flags = args.slice(2, terminator === -1 ? undefined : terminator);\n\t// Checks accept direct help flags. The print commands reserve every extra\n\t// parser flag, including --help, as a usage error to keep their export stream narrow.\n\treturn args[1] === \"check\" && (flags.includes(\"--help\") || flags.includes(\"-h\"));\n}\n\nexport function printAuthCommandHelp(): void {\n\tconsole.error(`Usage:\n ${APP_NAME} auth print-api-key --model <model> [--provider <provider>]\n ${APP_NAME} auth print-bearer-token --model <model> [--provider <provider>] [--min-expiry <duration>]\n ${APP_NAME} auth check [--provider <provider>] [--model <model>] [--json] [--credentials] [--no-refresh]\n\nCredential print commands write one configured credential alone on stdout. Everything else —\nwarnings, provider selection, refresh notices, and help — goes to stderr. --model is\nrequired for these exports, so no ambient model can emit a credential you did not name.\n\nAuth checks require at least one of --provider or --model. They print ready, not_ready,\nor invalid on stdout and refresh expired OAuth credentials by default; --no-refresh\nprevents a refresh and any auth.json mutation. --json includes the resolved provider\nwhen one is found, plus auth type and a reason when it is not ready. --credentials is\nan explicit export that needs --provider or an exact --model target; on a ready check\nit writes the credential, or includes it in JSON. A non-ready raw export leaves stdout\nempty and reports status on stderr.\n\n--min-expiry accepts ms, s, m, or h (for example 30m) and applies only to\nprint-bearer-token, where it defaults to 30m. A token with less than that\nremaining is refreshed first. It remains reserved after --, so print-api-key\nstill rejects it in either spelling.\n\nCredential-export exit codes:\n 0 credential written to stdout\n 1 usage error\n 2 no credential configured\n 3 provider ambiguous\n 4 credential kind unsupported for that provider\n 5 refresh failed (the stored credential is left untouched)\n 6 provider cannot mint a token that lives long enough\n 7 the provider's OAuth credential could not be used\n 8 the credential could not be written (nothing was emitted)\n 9 the credential was written only in part; stdout holds an unusable\n fragment, which the caller must discard rather than use\n\nAuth-check exit codes:\n 0 provider is ready\n 1 provider is not ready\n 2 auth state or command is invalid\n 8 with --credentials, the credential could not be written\n 9 with --credentials, only part of the credential was written`);\n}\n\nfunction parseDuration(value: string | undefined, exitCode: number): number {\n\tconst match = value ? /^(\\d+)(ms|s|m|h)$/iu.exec(value) : undefined;\n\tif (!match) throw new AuthCommandError(\"--min-expiry must use a duration such as 30m or 1h\", exitCode);\n\tconst unit = match[2].toLowerCase();\n\tconst scale = unit === \"ms\" ? 1 : unit === \"s\" ? 1_000 : unit === \"m\" ? 60_000 : 3_600_000;\n\treturn Number(match[1]) * scale;\n}\n\n/** Parse the `atomic auth` command surface before normal startup. */\nexport function parseAuthCommand(args: string[]): AuthCommand | undefined {\n\tif (args[0] !== \"auth\") return undefined;\n\n\tconst kind: AuthCommandKind | undefined =\n\t\targs[1] === \"check\"\n\t\t\t? \"check\"\n\t\t\t: args[1] === \"print-api-key\"\n\t\t\t\t? \"api_key\"\n\t\t\t\t: args[1] === \"print-bearer-token\"\n\t\t\t\t\t? \"bearer_token\"\n\t\t\t\t\t: undefined;\n\tif (!kind) {\n\t\tthrow new AuthCommandError(\n\t\t\t`Unknown auth command \"${args[1] ?? \"\"}\". Use \"${APP_NAME} auth print-api-key\", \"${APP_NAME} auth print-bearer-token\", or \"${APP_NAME} auth check\".`,\n\t\t);\n\t}\n\n\tconst exitCode = kind === \"check\" ? 2 : 1;\n\tconst commandArgs: string[] = [];\n\tlet json = false;\n\tlet credentials = false;\n\tlet noRefresh = false;\n\tlet minExpiryMs: number | undefined;\n\tlet optionsEnded = false;\n\tfor (let index = 2; index < args.length; index++) {\n\t\tconst arg = args[index];\n\t\tif (arg === \"--\") {\n\t\t\toptionsEnded = true;\n\t\t\tcommandArgs.push(arg);\n\t\t\tcontinue;\n\t\t}\n\t\tconst inlineMinExpiry = arg.startsWith(\"--min-expiry=\") ? arg.slice(\"--min-expiry=\".length) : undefined;\n\t\tif (arg === \"--min-expiry\" || inlineMinExpiry !== undefined) {\n\t\t\tif (kind !== \"bearer_token\") {\n\t\t\t\tthrow new AuthCommandError(\"--min-expiry is only supported by print-bearer-token\", exitCode);\n\t\t\t}\n\t\t\tminExpiryMs = parseDuration(inlineMinExpiry ?? args[++index], exitCode);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!optionsEnded && (arg === \"--json\" || arg === \"--credentials\" || arg === \"--no-refresh\")) {\n\t\t\tif (kind !== \"check\") throw new AuthCommandError(`${arg} is only supported by auth check`, exitCode);\n\t\t\tif (arg === \"--json\") json = true;\n\t\t\telse if (arg === \"--credentials\") credentials = true;\n\t\t\telse noRefresh = true;\n\t\t\tcontinue;\n\t\t}\n\t\tcommandArgs.push(arg);\n\t}\n\n\treturn minExpiryMs === undefined\n\t\t? { kind, args: commandArgs, json, credentials, noRefresh }\n\t\t: { kind, args: commandArgs, json, credentials, noRefresh, minExpiryMs };\n}\n\nexport function validateAuthCheckArgs(args: Args): { provider?: string; model?: string } {\n\tconst provider = args.provider?.trim() || undefined;\n\tconst model = args.model?.trim() || undefined;\n\tif (args.unknownFlags.size > 0) {\n\t\tconst option = args.unknownFlags.keys().next().value;\n\t\tthrow new AuthCommandError(`Unknown option --${option} for \"auth check\".`);\n\t}\n\tif (args.apiKey !== undefined || args.messages.length > 0 || args.fileArgs.length > 0) {\n\t\tthrow new AuthCommandError(\"Auth checks only accept --provider and --model\");\n\t}\n\tif (!provider && !model) {\n\t\tthrow new AuthCommandError(\"Auth checks require --provider <provider> or --model <model>\");\n\t}\n\treturn { provider, model };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"auth-command.js","sourceRoot":"","sources":["../../src/cli/auth-command.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAgBxC,MAAM,OAAO,gBAAiB,SAAQ,KAAK;IAC1C,0EAA0E;IAC1E,0EAA0E;IAC1E,yEAAyE;IACzE,8BAA8B;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,MAAM,IAAI,gBAAgB,CAAC,oBAAoB,MAAM,oBAAoB,CAAC,CAAC;IAC5E,CAAC;IACD,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACvF,MAAM,IAAI,gBAAgB,CAAC,gDAAgD,CAAC,CAAC;IAC9E,CAAC;IACD,IAAI,CAAC,QAAQ,IAAI,CAAC,KAAK,EAAE,CAAC;QACzB,MAAM,IAAI,gBAAgB,CAAC,8DAA8D,CAAC,CAAC;IAC5F,CAAC;IACD,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;AAC5B,CAAC","sourcesContent":["import { APP_NAME } from \"../config.js\";\nimport type { Args } from \"./args.ts\";\n\nexport type AuthCommandKind = \"check\" | \"api_key\" | \"bearer_token\";\n\nexport interface AuthCommand {\n\tkind: AuthCommandKind;\n\t/** Remaining argv for the normal parser. */\n\targs: string[];\n\tjson: boolean;\n\t/** `auth check` emits a resolved credential only with this explicit opt-in. */\n\tcredentials: boolean;\n\tnoRefresh: boolean;\n\tminExpiryMs?: number;\n}\n\nexport class AuthCommandError extends Error {\n\t// Declared and assigned explicitly rather than as a constructor parameter\n\t// property: `tsconfig.base.json` sets `erasableSyntaxOnly`, under which a\n\t// parameter property is TS1294. Root `tsc --noEmit` does not surface it,\n\t// but the shipped build does.\n\treadonly exitCode: number;\n\n\tconstructor(message: string, exitCode = 1) {\n\t\tsuper(message);\n\t\tthis.exitCode = exitCode;\n\t\tthis.name = \"AuthCommandError\";\n\t}\n}\n\nconst AUTH_COMMAND_USAGE: Record<AuthCommandKind, string> = {\n\tcheck: `${APP_NAME} auth check [--provider <provider>] [--model <model>] [--json] [--credentials] [--no-refresh]`,\n\tapi_key: `${APP_NAME} auth print-api-key --model <model> [--provider <provider>]`,\n\tbearer_token: `${APP_NAME} auth print-bearer-token --model <model> [--provider <provider>] [--min-expiry <duration>]`,\n};\n\nexport function getAuthCommandName(kind: AuthCommandKind): string {\n\treturn kind === \"check\" ? \"auth check\" : kind === \"api_key\" ? \"auth print-api-key\" : \"auth print-bearer-token\";\n}\n\nexport function getAuthCommandUsage(kind: AuthCommandKind): string {\n\treturn AUTH_COMMAND_USAGE[kind];\n}\n\nexport function isAuthCommandHelp(args: string[]): boolean {\n\tif (args[0] !== \"auth\") return false;\n\tif (args[1] === undefined || args[1] === \"help\" || args[1] === \"--help\" || args[1] === \"-h\") return true;\n\tconst terminator = args.indexOf(\"--\", 2);\n\tconst flags = args.slice(2, terminator === -1 ? undefined : terminator);\n\t// Checks accept direct help flags. The print commands reserve every extra\n\t// parser flag, including --help, as a usage error to keep their export stream narrow.\n\treturn args[1] === \"check\" && (flags.includes(\"--help\") || flags.includes(\"-h\"));\n}\n\nexport function printAuthCommandHelp(): void {\n\tconsole.error(`Usage:\n ${APP_NAME} auth print-api-key --model <model> [--provider <provider>]\n ${APP_NAME} auth print-bearer-token --model <model> [--provider <provider>] [--min-expiry <duration>]\n ${APP_NAME} auth check [--provider <provider>] [--model <model>] [--json] [--credentials] [--no-refresh]\n\nCredential print commands write one configured credential alone on stdout. Everything else —\nwarnings, provider selection, refresh notices, and help — goes to stderr. --model is\nrequired for these exports, so no ambient model can emit a credential you did not name.\n\nAuth checks require at least one of --provider or --model. They print ready, not_ready,\nor invalid on stdout and refresh expired OAuth credentials by default; --no-refresh\nprevents a refresh and any auth.json mutation. --json includes the resolved provider\nwhen one is found, plus auth type and a reason when it is not ready. --credentials is\nan explicit export that needs --provider or an exact --model target; on a ready check\nit writes the credential, or includes it in JSON. A non-ready raw export leaves stdout\nempty and reports status on stderr.\n\n--min-expiry accepts ms, s, m, or h (for example 30m) and applies only to\nprint-bearer-token, where it defaults to 30m. A token with less than that\nremaining is refreshed first. It remains reserved after --, so print-api-key\nstill rejects it in either spelling.\n\nCredential-export exit codes:\n 0 credential written to stdout\n 1 usage error\n 2 no credential configured\n 3 provider ambiguous\n 4 credential kind unsupported for that provider\n 5 refresh failed (the stored credential is left untouched)\n 6 provider cannot mint a token that lives long enough\n 7 the provider's OAuth credential could not be used\n 8 the credential could not be written (nothing was emitted)\n 9 the credential was written only in part; stdout holds an unusable\n fragment, which the caller must discard rather than use\n\nAuth-check exit codes:\n 0 provider is ready\n 1 provider is not ready\n 2 auth state or command is invalid\n 8 with --credentials, the credential could not be written\n 9 with --credentials, only part of the credential was written`);\n}\n\nfunction parseDuration(value: string | undefined, exitCode: number): number {\n\tconst match = value ? /^(\\d+)(ms|s|m|h)$/iu.exec(value) : undefined;\n\tif (!match) throw new AuthCommandError(\"--min-expiry must use a duration such as 30m or 1h\", exitCode);\n\tconst unit = match[2].toLowerCase();\n\tconst scale = unit === \"ms\" ? 1 : unit === \"s\" ? 1_000 : unit === \"m\" ? 60_000 : 3_600_000;\n\treturn Number(match[1]) * scale;\n}\n\n/** Parse the `atomic auth` command surface before normal startup. */\nexport function parseAuthCommand(args: string[]): AuthCommand | undefined {\n\tif (args[0] !== \"auth\") return undefined;\n\n\tconst kind: AuthCommandKind | undefined =\n\t\targs[1] === \"check\"\n\t\t\t? \"check\"\n\t\t\t: args[1] === \"print-api-key\"\n\t\t\t\t? \"api_key\"\n\t\t\t\t: args[1] === \"print-bearer-token\"\n\t\t\t\t\t? \"bearer_token\"\n\t\t\t\t\t: undefined;\n\tif (!kind) {\n\t\tthrow new AuthCommandError(\n\t\t\t`Unknown auth command \"${args[1] ?? \"\"}\". Use \"${APP_NAME} auth print-api-key\", \"${APP_NAME} auth print-bearer-token\", or \"${APP_NAME} auth check\".`,\n\t\t);\n\t}\n\n\tconst exitCode = kind === \"check\" ? 2 : 1;\n\tconst commandArgs: string[] = [];\n\tlet json = false;\n\tlet credentials = false;\n\tlet noRefresh = false;\n\tlet minExpiryMs: number | undefined;\n\tlet optionsEnded = false;\n\tfor (let index = 2; index < args.length; index++) {\n\t\tconst arg = args[index];\n\t\tif (arg === \"--\") {\n\t\t\toptionsEnded = true;\n\t\t\tcommandArgs.push(arg);\n\t\t\tcontinue;\n\t\t}\n\t\tconst inlineMinExpiry = arg.startsWith(\"--min-expiry=\") ? arg.slice(\"--min-expiry=\".length) : undefined;\n\t\tif (arg === \"--min-expiry\" || inlineMinExpiry !== undefined) {\n\t\t\tif (kind !== \"bearer_token\") {\n\t\t\t\tthrow new AuthCommandError(\"--min-expiry is only supported by print-bearer-token\", exitCode);\n\t\t\t}\n\t\t\tminExpiryMs = parseDuration(inlineMinExpiry ?? args[++index], exitCode);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!optionsEnded && (arg === \"--json\" || arg === \"--credentials\" || arg === \"--no-refresh\")) {\n\t\t\tif (kind !== \"check\") throw new AuthCommandError(`${arg} is only supported by auth check`, exitCode);\n\t\t\tif (arg === \"--json\") json = true;\n\t\t\telse if (arg === \"--credentials\") credentials = true;\n\t\t\telse noRefresh = true;\n\t\t\tcontinue;\n\t\t}\n\t\tcommandArgs.push(arg);\n\t}\n\n\treturn minExpiryMs === undefined\n\t\t? { kind, args: commandArgs, json, credentials, noRefresh }\n\t\t: { kind, args: commandArgs, json, credentials, noRefresh, minExpiryMs };\n}\n\nexport function validateAuthCheckArgs(args: Args): { provider?: string; model?: string } {\n\tconst provider = args.provider?.trim() || undefined;\n\tconst model = args.model?.trim() || undefined;\n\tif (args.unknownFlags.size > 0) {\n\t\tconst option = args.unknownFlags.keys().next().value;\n\t\tthrow new AuthCommandError(`Unknown option --${option} for \"auth check\".`);\n\t}\n\tif (args.apiKey !== undefined || args.messages.length > 0 || args.fileArgs.length > 0) {\n\t\tthrow new AuthCommandError(\"Auth checks only accept --provider and --model\");\n\t}\n\tif (!provider && !model) {\n\t\tthrow new AuthCommandError(\"Auth checks require --provider <provider> or --model <model>\");\n\t}\n\treturn { provider, model };\n}\n"]}
|
|
@@ -51,6 +51,8 @@ export const EXIT_CODES = {
|
|
|
51
51
|
/** The codes whose contract is an empty stdout. See `EXIT_CODES`. */
|
|
52
52
|
export const STDOUT_EMPTY_ON_EXIT = new Set(Object.keys(EXIT_CODES).filter((code) => code !== "CredentialTruncated"));
|
|
53
53
|
export class CredentialPrintError extends Error {
|
|
54
|
+
code;
|
|
55
|
+
exitCode;
|
|
54
56
|
constructor(code, message, options) {
|
|
55
57
|
super(message, options);
|
|
56
58
|
this.name = "CredentialPrintError";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"credential-print.js","sourceRoot":"","sources":["../../src/cli/credential-print.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAE5D,OAAO,EAAE,cAAc,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAKlG,8EAA8E;AAC9E,MAAM,CAAC,MAAM,kCAAkC,GAAG,EAAE,GAAG,MAAM,CAAC;AAiB9D;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,UAAU,GAA6C;IACnE,KAAK,EAAE,CAAC;IACR,sBAAsB,EAAE,CAAC;IACzB,iBAAiB,EAAE,CAAC;IACpB,0BAA0B,EAAE,CAAC;IAC7B,aAAa,EAAE,CAAC;IAChB,sBAAsB,EAAE,CAAC;IACzB,gBAAgB,EAAE,CAAC;IACnB,oBAAoB,EAAE,CAAC;IACvB,mBAAmB,EAAE,CAAC;CACtB,CAAC;AAEF,qEAAqE;AACrE,MAAM,CAAC,MAAM,oBAAoB,GAA0C,IAAI,GAAG,CAChF,MAAM,CAAC,IAAI,CAAC,UAAU,CAAgC,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,KAAK,qBAAqB,CAAC,CACxG,CAAC;AAEF,MAAM,OAAO,oBAAqB,SAAQ,KAAK;IAI9C,YAAY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CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC9B,IAAI,iBAAiB;YAAE,MAAM,iBAAiB,CAAC;QAC/C,MAAM,UAAU,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,QAAQ,CAAC;QACvC,MAAM,IAAI,GAAG,UAAU,CAAC,CAAC,CAAC,iBAAiB,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QACxE,IAAI,IAAI,CAAC,QAAQ,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,OAAO,EAAE,CAAC;YAC7D,MAAM,IAAI,oBAAoB,CAC7B,4BAA4B,EAC5B,aAAa,UAAU,4CAA4C,CACnE,CAAC;QACH,CAAC;QACD,IAAI,IAAI,CAAC,QAAQ,IAAI,IAAI,KAAK,cAAc,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACpE,MAAM,IAAI,oBAAoB,CAC7B,4BAA4B,EAC5B,aAAa,UAAU,gDAAgD,CACvE,CAAC;QACH,CAAC;QACD,MAAM,IAAI,oBAAoB,CAC7B,wBAAwB,EACxB,aAAa,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,oBAAoB,gBAAgB,CAClF,CAAC;IACH,CAAC;IAED,MAAM,IAAI,oBAAoB,CAC7B,mBAAmB,EACnB,UAAU,IAAI,CAAC,KAAK,wCAAwC,WAAW;SACrE,GAAG,CAAC,CAAC,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC,UAAU,CAAC;SACnC,IAAI,CAAC,IAAI,CAAC,wBAAwB,CACpC,CAAC;AACH,CAAC","sourcesContent":["/**\n * `atomic auth print-api-key` / `atomic auth print-bearer-token` and the\n * explicit `atomic auth check --credentials` export path.\n *\n * The only door in Atomic whose purpose is emitting a secret. Everything here\n * exists to keep that egress narrow:\n * - the secret leaves as a `Secret`, which cannot be interpolated, serialized,\n * or inspected, and is consumed exactly once by the stdout writer;\n * - every export has an explicit target: the print commands require `--model`,\n * and auth checks require `--provider` or an exact `--model` plus\n * `--credentials`;\n * - there is no `--output <file>` and no clipboard path — stdout only;\n * - every failure is a distinct exit code, and stdout stays empty on all of\n * them but one — `CredentialTruncated` (exit 9) exists to report the case\n * where it cannot be, because bytes already left and cannot be recalled;\n * - a failed OAuth refresh never mutates the stored credential.\n *\n * One residual, and it is upstream: when a model infers several eligible\n * providers, each is asked for its credential before the ambiguity is known, so\n * a *successful* refresh can rotate and persist a credential this command then\n * declines to emit (exit 3). See the note on the `getAuth()` call in the\n * candidate loop.\n */\n\nimport { inspect } from \"node:util\";\nimport type { Api, AuthType, Model } from \"@bastani/pi-ai\";\nimport { ModelsError } from \"@bastani/pi-ai\";\nimport { resolveCliModel } from \"../core/model-resolver.ts\";\nimport type { ModelRuntime } from \"../core/model-runtime.js\";\nimport { flushRawStdout, RawStdoutWriteError, writeRawStdoutOnce } from \"../core/output-guard.ts\";\nimport type { Args } from \"./args.ts\";\n\nexport type CredentialPrintKind = \"api_key\" | \"bearer_token\";\n\n/** Bearer tokens are refreshed unless they still have this much life left. */\nexport const DEFAULT_BEARER_TOKEN_MIN_EXPIRY_MS = 30 * 60_000;\n\n/**\n * Failure taxonomy. Each member owns one exit code, so a caller can branch on\n * the status without parsing stderr.\n */\nexport type CredentialPrintErrorCode =\n\t| \"Usage\"\n\t| \"NoCredentialConfigured\"\n\t| \"ProviderAmbiguous\"\n\t| \"KindUnsupportedForProvider\"\n\t| \"RefreshFailed\"\n\t| \"MinValidityUnreachable\"\n\t| \"OAuthUnavailable\"\n\t| \"CredentialNotEmitted\"\n\t| \"CredentialTruncated\";\n\n/**\n * Exported so a test can walk the whole taxonomy: every declared code has to\n * name an exercised path, and the record type makes a new member without an\n * exit code a compile error rather than a review miss.\n *\n * Every one of these leaves stdout empty except `CredentialTruncated`, which\n * exists to report the one case where it cannot be: bytes already went out and\n * cannot be recalled. `STDOUT_EMPTY_ON_EXIT` names that split so the taxonomy\n * test asserts it rather than assuming it.\n */\nexport const EXIT_CODES: Record<CredentialPrintErrorCode, number> = {\n\tUsage: 1,\n\tNoCredentialConfigured: 2,\n\tProviderAmbiguous: 3,\n\tKindUnsupportedForProvider: 4,\n\tRefreshFailed: 5,\n\tMinValidityUnreachable: 6,\n\tOAuthUnavailable: 7,\n\tCredentialNotEmitted: 8,\n\tCredentialTruncated: 9,\n};\n\n/** The codes whose contract is an empty stdout. See `EXIT_CODES`. */\nexport const STDOUT_EMPTY_ON_EXIT: ReadonlySet<CredentialPrintErrorCode> = new Set(\n\t(Object.keys(EXIT_CODES) as CredentialPrintErrorCode[]).filter((code) => code !== \"CredentialTruncated\"),\n);\n\nexport class CredentialPrintError extends Error {\n\treadonly code: CredentialPrintErrorCode;\n\treadonly exitCode: number;\n\n\tconstructor(code: CredentialPrintErrorCode, message: string, options?: { cause?: unknown }) {\n\t\tsuper(message, options);\n\t\tthis.name = \"CredentialPrintError\";\n\t\tthis.code = code;\n\t\tthis.exitCode = EXIT_CODES[code];\n\t}\n}\n\n/**\n * A credential in transit.\n *\n * Every path that would copy the value into a string is closed: `toString`,\n * `toJSON`, and `Symbol.toPrimitive` throw rather than return, so a template\n * literal, `JSON.stringify`, or string concatenation fails loudly instead of\n * leaking into a log line, a transcript, or an error message. `inspect` — which\n * `console.log` and Node's error formatting use — renders a placeholder.\n *\n * `take()` is the single exit, and it works once.\n */\nexport class Secret {\n\t#value: string | undefined;\n\n\tconstructor(value: string) {\n\t\tthis.#value = value;\n\t}\n\n\t/** Consume the secret. A second call is a bug, not a second read. */\n\ttake(): string {\n\t\tconst value = this.#value;\n\t\tif (value === undefined) {\n\t\t\tthrow new Error(\"Secret has already been consumed\");\n\t\t}\n\t\tthis.#value = undefined;\n\t\treturn value;\n\t}\n\n\ttoString(): never {\n\t\tthrow new Error(\"A Secret cannot be converted to a string; use take()\");\n\t}\n\n\ttoJSON(): never {\n\t\tthrow new Error(\"A Secret cannot be serialized; use take()\");\n\t}\n\n\t[Symbol.toPrimitive](): never {\n\t\tthrow new Error(\"A Secret cannot be interpolated; use take()\");\n\t}\n\n\t[inspect.custom](): string {\n\t\treturn \"[Secret]\";\n\t}\n}\n\n/** Public readiness fields emitted with a credential under `auth check --json --credentials`. */\nexport interface CredentialJsonFields {\n\tstatus: string;\n\tprovider: string;\n\tauthType?: string;\n}\n\n/**\n * The only function in `src` that opens a `Secret`.\n *\n * Its two `Secret.take()` calls are the only call sites in `src`, and the\n * source-wide credential-egress test pins that list. This function builds one\n * payload and returns it only to `emitCredential`; no caller receives a plain\n * credential string.\n */\nfunction credentialPayload(secret: Secret, jsonFields: CredentialJsonFields | undefined): string {\n\tif (jsonFields === undefined) return `${secret.take()}\\n`;\n\n\tconst { status, provider, authType } = jsonFields;\n\tif (\n\t\ttypeof status !== \"string\" ||\n\t\ttypeof provider !== \"string\" ||\n\t\t(authType !== undefined && typeof authType !== \"string\")\n\t) {\n\t\tthrow new Error(\"Invalid credential JSON fields\");\n\t}\n\n\t// Allowlist the non-secret envelope before opening the Secret. That leaves no\n\t// formatter, logger, or error path between take() and the guarded stdout write.\n\tconst fields = JSON.stringify({\n\t\tstatus,\n\t\tprovider,\n\t\t...(authType === undefined ? {} : { authType }),\n\t});\n\tif (fields === undefined || !fields.startsWith(\"{\") || !fields.endsWith(\"}\")) {\n\t\tthrow new Error(\"Invalid credential JSON envelope\");\n\t}\n\treturn `${fields.slice(0, -1)},\"credentials\":${JSON.stringify(secret.take())}}\\n`;\n}\n\n/**\n * The single credential egress in `src`.\n *\n * `credentialPayload` opens the secret only while building this one payload,\n * and this guarded write is the only path that hands it to real stdout. A\n * caller — `main.ts` included — receives a `Secret` it cannot read, print, or\n * serialize, so it cannot add a second export path without crossing this door.\n * `test/credential-print.test.ts` pins both the `take()` sites and every\n * data-bearing real-stdout write in `packages/coding-agent/src`.\n *\n * A failed payload write is answered from the stream rather than from the shape\n * of the error, because `bytesWritten` says how much of the credential actually\n * left and the right report differs for each amount.\n *\n * Nothing left — the write call threw, or the callback failed with the counter\n * unmoved — is `CredentialNotEmitted` (exit 8) with stdout provably empty,\n * which is what that exit promises. It must not fall through to the caller's\n * credential-resolution catch, which would report exit 2.\n *\n * All of it left and the failure came after: the caller holds the credential it\n * asked for, so this is reported on stderr with the exit code left at 0, for\n * the same reason the trailing drain is. A non-zero exit over a stream carrying\n * a whole credential is the thing this door never produces.\n *\n * Part of it left is neither. Those bytes cannot be recalled, so stdout is not\n * empty and cannot be made empty; but they are a fragment, not a credential,\n * and reporting success over them would hand a caller a truncated secret it\n * cannot tell from a whole one. That case gets `CredentialTruncated` (exit 9),\n * the one code in this taxonomy whose contract is *not* an empty stdout —\n * stated as such in `EXIT_CODES` and asserted through `STDOUT_EMPTY_ON_EXIT`,\n * rather than left for a caller to discover.\n */\nexport async function emitCredential(secret: Secret, jsonFields: CredentialJsonFields | undefined): Promise<void> {\n\tconst payload = credentialPayload(secret, jsonFields);\n\ttry {\n\t\tawait writeRawStdoutOnce(payload);\n\t} catch (error) {\n\t\tif (error instanceof RawStdoutWriteError && error.emitted === \"all\") {\n\t\t\t// The caller holds the whole credential. Exiting non-zero here would be\n\t\t\t// a non-zero exit over a stream carrying it, which this door never does.\n\t\t\tconsole.error(\n\t\t\t\t`Warning: the credential reached stdout but the write did not complete cleanly: ${error.message}`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (error instanceof RawStdoutWriteError && error.emitted === \"partial\") {\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"CredentialTruncated\",\n\t\t\t\t\"Only part of the credential reached stdout; discard the output, it is not a usable credential\",\n\t\t\t\t{ cause: error },\n\t\t\t);\n\t\t}\n\t\tthrow new CredentialPrintError(\n\t\t\t\"CredentialNotEmitted\",\n\t\t\t\"Failed to write the credential to stdout; nothing was emitted\",\n\t\t\t{ cause: error },\n\t\t);\n\t}\n\ttry {\n\t\tawait flushRawStdout();\n\t} catch (error) {\n\t\tconsole.error(\n\t\t\t`Warning: the credential was written to stdout but the stream did not drain cleanly: ${\n\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t}`,\n\t\t);\n\t}\n}\n\n/**\n * The single place a thrown value becomes an exit code for this door.\n *\n * `main.ts` routes every failure through here. Every code it can produce leaves\n * stdout empty, so an exit code from this door never contradicts the stream.\n */\nexport function toCredentialPrintError(error: unknown): CredentialPrintError {\n\tif (error instanceof CredentialPrintError) return error;\n\treturn new CredentialPrintError(\n\t\t\"NoCredentialConfigured\",\n\t\terror instanceof Error ? error.message : \"Failed to resolve credential\",\n\t\t{ cause: error },\n\t);\n}\n\n/**\n * The only two fields of `Args` this door accepts.\n *\n * Validation is an allowlist rather than a list of refusals, because the\n * refusal list only held while the dispatcher happened to ignore every other\n * flag. `--export <path>`, `--session-dir <path>`, `--print`, and `--help` are\n * all parsed by `parseArgs`; under an exclusion check they passed silently and\n * the door's \"no file sink\" guarantee rested on a downstream accident.\n */\nconst ACCEPTED_ARG_FIELDS: ReadonlySet<string> = new Set([\"model\", \"provider\"]);\n\n/** Names every field of a parsed `Args` that the caller actually set. */\nfunction populatedArgFields(args: Args): string[] {\n\tconst populated: string[] = [];\n\tfor (const [field, value] of Object.entries(args)) {\n\t\tif (ACCEPTED_ARG_FIELDS.has(field) || value === undefined) continue;\n\t\tif (Array.isArray(value)) {\n\t\t\tif (value.length > 0) populated.push(field);\n\t\t} else if (value instanceof Map) {\n\t\t\tif (value.size > 0) populated.push(field);\n\t\t} else {\n\t\t\tpopulated.push(field);\n\t\t}\n\t}\n\treturn populated;\n}\n\nexport function validateCredentialPrintArgs(args: Args): void {\n\tif (!args.model?.trim()) {\n\t\tthrow new CredentialPrintError(\"Usage\", \"Credential printing requires --model <model>\");\n\t}\n\tif (args.apiKey !== undefined) {\n\t\tthrow new CredentialPrintError(\n\t\t\t\"Usage\",\n\t\t\t\"Credential printing reads configured credentials; --api-key is not supported\",\n\t\t);\n\t}\n\tconst refused = populatedArgFields(args);\n\tif (refused.length > 0) {\n\t\tthrow new CredentialPrintError(\n\t\t\t\"Usage\",\n\t\t\t`Credential printing only accepts --provider and --model (refused: ${refused.join(\", \")})`,\n\t\t);\n\t}\n}\n\n/**\n * Provider-supplied text with anything credential-bearing masked.\n *\n * A failed refresh is reported on stderr, and the provider composes that\n * message. Most describe the failure; some quote the request they sent or the\n * body they got back, either of which can carry the very value this door exists\n * to keep off every stream except stdout. Masking keeps the diagnosis — which\n * is what makes the exit code actionable — without putting the secret in a log,\n * a terminal scrollback, or a CI transcript.\n *\n * Two passes, because either alone leaves a gap. Shape catches a value wherever\n * it appears, but only for the formats that announce themselves. Context\n * catches an opaque value — an `x-api-key`, which is just bytes — by the name it\n * is filed under, in the header, JSON, and query spellings a quoted request or\n * response body uses.\n */\nconst CREDENTIAL_SHAPES: readonly RegExp[] = [\n\t// `Authorization: Bearer <token>`, the form an echoed request header takes.\n\t/\\bBearer\\s+[\\w.~+/-]+=*/giu,\n\t// JWTs, which several providers return verbatim in an error body.\n\t/\\beyJ[\\w-]{8,}\\.[\\w-]{8,}\\.[\\w-]+/gu,\n\t// Prefixed API keys: sk-…, sk_live_…, api-key-…, and the same shapes again.\n\t/\\b(?:sk|pk|rk|api|key|tok|token|secret)[-_][\\w-]{12,}/giu,\n];\n\n/**\n * Field names whose value is the credential, however opaque that value looks.\n * `x-api-key` is the case shape-matching cannot reach: the value is just bytes.\n */\nconst CREDENTIAL_FIELD_NAME =\n\t\"(?:x-)?(?:api[-_]?key|apikey|auth(?:orization)?|access[-_]?token|refresh[-_]?token|id[-_]?token|client[-_]?secret|secret[-_]?key|private[-_]?key|session[-_]?key|password|passwd|token|secret|key)\";\n\n/**\n * Auth schemes that stand between the field name and the value it introduces.\n *\n * Without them the header matcher stops at the space after `Bearer`: it redacts\n * the scheme and leaves the token, and having consumed the `Bearer` the shape\n * pass depends on, that pass can no longer reach the token either. An opaque\n * `Authorization: Bearer <token>` then survives both passes.\n */\nconst CREDENTIAL_AUTH_SCHEME = \"(?:Bearer|Basic|Digest|Token|ApiKey|OAuth)\";\n\nconst CREDENTIAL_CONTEXTS: readonly RegExp[] = [\n\t// Header or YAML-ish: `x-api-key: abc123`, to end of line, and the scheme\n\t// form `Authorization: Bearer abc123` with it.\n\tnew RegExp(String.raw`\\b${CREDENTIAL_FIELD_NAME}\\s*:\\s*(?:${CREDENTIAL_AUTH_SCHEME}\\s+)?[^\\s,;}\"']+`, \"giu\"),\n\t// JSON: `\"api_key\": \"abc123\"` / `'token':'abc123'`, quoted value.\n\tnew RegExp(String.raw`([\"']?)${CREDENTIAL_FIELD_NAME}\\1\\s*:\\s*([\"'])(?:(?!\\2).)*\\2`, \"giu\"),\n\t// Query string or form body: `?api_key=abc123&…`.\n\tnew RegExp(String.raw`\\b${CREDENTIAL_FIELD_NAME}\\s*=\\s*[^\\s&,;}\"']+`, \"giu\"),\n];\n\nexport function redactCredentialShapes(text: string): string {\n\tconst byContext = CREDENTIAL_CONTEXTS.reduce(\n\t\t(masked, context) =>\n\t\t\tmasked.replace(context, (match) => {\n\t\t\t\t// Keep the field name so the diagnosis still says which one failed;\n\t\t\t\t// replace only what follows the separator.\n\t\t\t\tconst separator = /[:=]/u.exec(match);\n\t\t\t\treturn separator ? `${match.slice(0, separator.index + 1)} [redacted]` : \"[redacted]\";\n\t\t\t}),\n\t\ttext,\n\t);\n\treturn CREDENTIAL_SHAPES.reduce((masked, shape) => masked.replace(shape, \"[redacted]\"), byContext);\n}\n\n/**\n * The literal phrase pi-ai throws when a refresh itself failed, from inside\n * `credentials.modify` and therefore before anything is persisted. This is the\n * only oauth-coded error that can claim the stored credential was left alone.\n */\nexport const OAUTH_REFRESH_FAILED_PHRASE = \"OAuth refresh failed for\";\n\n/**\n * The literal phrase pi-ai throws when a refresh succeeded but the rotated\n * token still expires inside the requested window. It is the only signal that\n * separates exit 6 from exit 5.\n */\nexport const OAUTH_EXPIRES_TOO_SOON_PHRASE = \"expires too soon\";\n\n/**\n * pi-ai raises three different `oauth`-coded failures from\n * `dist/auth/resolve.js`, and only one of them is a failed refresh.\n *\n * `OAuth auth derivation failed for <provider>` is thrown after\n * `credentials.modify` has already persisted a rotated credential, and also on\n * the branch where no refresh was attempted at all — so it gets its own code\n * and a message that makes no claim about the stored credential. Treating it as\n * `RefreshFailed` asserted a rollback the command never verified.\n *\n * Classification reads the raw message, because redaction could rewrite the\n * phrase it matches on; only the text that becomes a user-facing message is\n * redacted. The unredacted error stays reachable as `cause`, which this door\n * never logs.\n *\n * `test/credential-print.test.ts` pins both phrases against the installed\n * pi-ai build, so an upstream rewording fails the suite rather than silently\n * collapsing exit 6 into exit 5.\n */\nexport function classifyOAuthFailure(error: ModelsError): CredentialPrintError {\n\tconst detail = redactCredentialShapes(error.message);\n\tif (error.message.includes(OAUTH_EXPIRES_TOO_SOON_PHRASE)) {\n\t\treturn new CredentialPrintError(\n\t\t\t\"MinValidityUnreachable\",\n\t\t\t`The provider refreshed the token but it still expires sooner than requested: ${detail}`,\n\t\t\t{ cause: error },\n\t\t);\n\t}\n\tif (error.message.startsWith(OAUTH_REFRESH_FAILED_PHRASE)) {\n\t\treturn new CredentialPrintError(\"RefreshFailed\", `${detail} (the stored credential was left untouched)`, {\n\t\t\tcause: error,\n\t\t});\n\t}\n\treturn new CredentialPrintError(\"OAuthUnavailable\", detail, { cause: error });\n}\n\n/**\n * Providers whose credential the caller could have meant.\n *\n * With `--provider` the caller named one, so failing to resolve it is an error.\n * Without it, eligibility is *not* narrowed to providers holding a persisted\n * credential: a provider authenticated by an environment variable or a custom\n * resolver has nothing in `auth.json`, and filtering on that list dropped it\n * before `getAuth()` could produce its working key. Candidacy is therefore\n * \"offers the named model\", and `getAuth()` — the same call a real request\n * makes — decides which candidate actually authenticates.\n */\nfunction candidateModels(args: Args, modelRuntime: ModelRuntime): Model<Api>[] {\n\tif (args.provider) {\n\t\tconst resolved = resolveCliModel({ cliProvider: args.provider, cliModel: args.model, modelRuntime });\n\t\tif (resolved.error || !resolved.model) {\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"NoCredentialConfigured\",\n\t\t\t\tresolved.error ?? \"Unable to resolve the requested provider/model\",\n\t\t\t);\n\t\t}\n\t\treturn [resolved.model];\n\t}\n\n\tconst models: Model<Api>[] = [];\n\tfor (const provider of modelRuntime.getProviders()) {\n\t\tconst resolved = resolveCliModel({ cliProvider: provider.id, cliModel: args.model, modelRuntime });\n\t\tif (resolved.model && !resolved.error && !resolved.warning?.includes(\"Using custom model id\")) {\n\t\t\tmodels.push(resolved.model);\n\t\t}\n\t}\n\tif (models.length === 0) {\n\t\tthrow new CredentialPrintError(\n\t\t\t\"NoCredentialConfigured\",\n\t\t\t`Model \"${args.model}\" not found among the available providers. Use --list-models to see available models.`,\n\t\t);\n\t}\n\treturn models;\n}\n\nfunction bearerFromHeaders(headers: Record<string, unknown> | undefined): string | undefined {\n\tconst authorization = Object.entries(headers ?? {}).find(([name]) => name.toLowerCase() === \"authorization\")?.[1];\n\treturn typeof authorization === \"string\" ? /^Bearer\\s+(.+)$/iu.exec(authorization)?.[1] : undefined;\n}\n\n/**\n * Resolve exactly one credential for a named provider/model pair.\n *\n * Goes through `ModelRuntime.getAuth()`, the same request-auth path a real\n * model call uses, so an OAuth credential is refreshed and persisted by the one\n * implementation that already handles concurrent refresh under a lock.\n */\nexport async function resolveCredentialForPrint(\n\targs: Args,\n\tmodelRuntime: ModelRuntime,\n\tkind: CredentialPrintKind,\n\tminExpiryMs?: number,\n): Promise<Secret> {\n\tvalidateCredentialPrintArgs(args);\n\n\t// The effective auth type per candidate provider, taken from the runtime\n\t// rather than from auth.json.\n\t//\n\t// `checkAuth` reports what a provider would actually authenticate with,\n\t// including a credential supplied by an environment variable or a custom\n\t// resolver that persists nothing, and it answers without refreshing OAuth.\n\t// `listCredentials()` sees only what was stored, which both hid working\n\t// credentials and — for a provider offering an API key *and* OAuth — could not\n\t// say which of the two a request would use. Provider capability cannot say\n\t// either: several providers send an API key as `Authorization: Bearer`, so\n\t// neither that header nor `apiKey` identifies the credential's kind on its own.\n\tconst wantedAuthType: AuthType = kind === \"api_key\" ? \"api_key\" : \"oauth\";\n\tconst resolvedAuthTypes = new Map<string, AuthType | undefined>();\n\tconst models = candidateModels(args, modelRuntime);\n\tfor (const { provider } of models) {\n\t\tif (resolvedAuthTypes.has(provider)) continue;\n\t\tresolvedAuthTypes.set(provider, (await modelRuntime.checkAuth(provider))?.type);\n\t}\n\t// A named provider, or a single candidate, is the one the caller meant, so its\n\t// authentication failure is reported with its own exit code. Among several\n\t// inferred candidates a failure only means \"not this one\" — reporting it would\n\t// let an unrelated provider that happens to offer the model decide the exit\n\t// code for a request another candidate can satisfy.\n\tconst authFailureIsFatal = args.provider !== undefined || models.length === 1;\n\n\tconst credentials: Array<{ providerId: string; value: string }> = [];\n\t// The classified diagnosis from a candidate that could not authenticate.\n\t// Skipping a candidate must not discard why it failed: a refresh that failed,\n\t// or a token that cannot reach the requested validity, is the real answer if\n\t// nothing else produces a credential, and keeping it is what leaves exits 5\n\t// and 6 reachable instead of collapsing every inferred failure into exit 2.\n\t// It holds a `CredentialPrintError`, never a credential — the provider's text\n\t// is redacted on the way in.\n\tlet deferredDiagnosis: CredentialPrintError | undefined;\n\tfor (const model of models) {\n\t\tconst type = resolvedAuthTypes.get(model.provider);\n\t\tif (type !== wantedAuthType) continue;\n\n\t\t// Every eligible candidate is asked here, before `ProviderAmbiguous` is\n\t\t// known, so an ambiguous export can refresh and persist credentials it\n\t\t// emits nothing for. Deciding eligibility earlier is not available:\n\t\t// `checkAuth()` is the only non-mutating probe and cannot tell a candidate\n\t\t// that will authenticate from one that will fail, which is what keeps\n\t\t// exits 5 and 6 reachable. Nor does resolving without refreshing exist —\n\t\t// `resolveStoredOAuth` in `@bastani/pi-ai` refreshes whenever the\n\t\t// token falls inside `max(DEFAULT_OAUTH_MINIMUM_VALIDITY_MS,\n\t\t// minOAuthValidityMs ?? 0)`, so omitting `minOAuthValidityMs` only lowers\n\t\t// that window to five minutes and drops the post-refresh check exit 6 is\n\t\t// decided by. Bounded: the refresh rotates a valid credential, it does not\n\t\t// invalidate one. Closing it needs a non-mutating probe upstream.\n\t\tlet auth: Awaited<ReturnType<ModelRuntime[\"getAuth\"]>>;\n\t\ttry {\n\t\t\tauth = await modelRuntime.getAuth(\n\t\t\t\tmodel,\n\t\t\t\tkind === \"bearer_token\" ? { minOAuthValidityMs: minExpiryMs ?? DEFAULT_BEARER_TOKEN_MIN_EXPIRY_MS } : {},\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst diagnosis =\n\t\t\t\terror instanceof ModelsError && error.code === \"oauth\" ? classifyOAuthFailure(error) : undefined;\n\t\t\tif (!authFailureIsFatal) {\n\t\t\t\tdeferredDiagnosis ??= diagnosis;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (diagnosis) throw diagnosis;\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"NoCredentialConfigured\",\n\t\t\t\tredactCredentialShapes(error instanceof Error ? error.message : String(error)),\n\t\t\t\t{ cause: error },\n\t\t\t);\n\t\t}\n\n\t\tconst value =\n\t\t\tkind === \"bearer_token\" ? (auth?.auth.apiKey ?? bearerFromHeaders(auth?.auth.headers)) : auth?.auth.apiKey;\n\t\tif (value) credentials.push({ providerId: model.provider, value });\n\t}\n\n\tif (credentials.length === 1) return new Secret(credentials[0].value);\n\n\tif (credentials.length === 0) {\n\t\tif (deferredDiagnosis) throw deferredDiagnosis;\n\t\tconst providerId = models[0]?.provider;\n\t\tconst type = providerId ? resolvedAuthTypes.get(providerId) : undefined;\n\t\tif (args.provider && kind === \"api_key\" && type === \"oauth\") {\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"KindUnsupportedForProvider\",\n\t\t\t\t`Provider \"${providerId}\" is configured with OAuth, not an API key`,\n\t\t\t);\n\t\t}\n\t\tif (args.provider && kind === \"bearer_token\" && type === \"api_key\") {\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"KindUnsupportedForProvider\",\n\t\t\t\t`Provider \"${providerId}\" is not configured with an OAuth bearer token`,\n\t\t\t);\n\t\t}\n\t\tthrow new CredentialPrintError(\n\t\t\t\"NoCredentialConfigured\",\n\t\t\t`No usable ${kind === \"api_key\" ? \"API key\" : \"OAuth bearer token\"} is configured`,\n\t\t);\n\t}\n\n\tthrow new CredentialPrintError(\n\t\t\"ProviderAmbiguous\",\n\t\t`Model \"${args.model}\" has multiple configured providers (${credentials\n\t\t\t.map(({ providerId }) => providerId)\n\t\t\t.join(\", \")}). Specify --provider.`,\n\t);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"credential-print.js","sourceRoot":"","sources":["../../src/cli/credential-print.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAE5D,OAAO,EAAE,cAAc,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAKlG,8EAA8E;AAC9E,MAAM,CAAC,MAAM,kCAAkC,GAAG,EAAE,GAAG,MAAM,CAAC;AAiB9D;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,UAAU,GAA6C;IACnE,KAAK,EAAE,CAAC;IACR,sBAAsB,EAAE,CAAC;IACzB,iBAAiB,EAAE,CAAC;IACpB,0BAA0B,EAAE,CAAC;IAC7B,aAAa,EAAE,CAAC;IAChB,sBAAsB,EAAE,CAAC;IACzB,gBAAgB,EAAE,CAAC;IACnB,oBAAoB,EAAE,CAAC;IACvB,mBAAmB,EAAE,CAAC;CACtB,CAAC;AAEF,qEAAqE;AACrE,MAAM,CAAC,MAAM,oBAAoB,GAA0C,IAAI,GAAG,CAChF,MAAM,CAAC,IAAI,CAAC,UAAU,CAAgC,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,KAAK,qBAAqB,CAAC,CACxG,CAAC;AAEF,MAAM,OAAO,oBAAqB,SAAQ,KAAK;IAC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CAAC,CAAC,KAAK,CAAC,CAAC;IAEtE,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC9B,IAAI,iBAAiB;YAAE,MAAM,iBAAiB,CAAC;QAC/C,MAAM,UAAU,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,QAAQ,CAAC;QACvC,MAAM,IAAI,GAAG,UAAU,CAAC,CAAC,CAAC,iBAAiB,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QACxE,IAAI,IAAI,CAAC,QAAQ,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,OAAO,EAAE,CAAC;YAC7D,MAAM,IAAI,oBAAoB,CAC7B,4BAA4B,EAC5B,aAAa,UAAU,4CAA4C,CACnE,CAAC;QACH,CAAC;QACD,IAAI,IAAI,CAAC,QAAQ,IAAI,IAAI,KAAK,cAAc,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACpE,MAAM,IAAI,oBAAoB,CAC7B,4BAA4B,EAC5B,aAAa,UAAU,gDAAgD,CACvE,CAAC;QACH,CAAC;QACD,MAAM,IAAI,oBAAoB,CAC7B,wBAAwB,EACxB,aAAa,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,oBAAoB,gBAAgB,CAClF,CAAC;IACH,CAAC;IAED,MAAM,IAAI,oBAAoB,CAC7B,mBAAmB,EACnB,UAAU,IAAI,CAAC,KAAK,wCAAwC,WAAW;SACrE,GAAG,CAAC,CAAC,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC,UAAU,CAAC;SACnC,IAAI,CAAC,IAAI,CAAC,wBAAwB,CACpC,CAAC;AACH,CAAC","sourcesContent":["/**\n * `atomic auth print-api-key` / `atomic auth print-bearer-token` and the\n * explicit `atomic auth check --credentials` export path.\n *\n * The only door in Atomic whose purpose is emitting a secret. Everything here\n * exists to keep that egress narrow:\n * - the secret leaves as a `Secret`, which cannot be interpolated, serialized,\n * or inspected, and is consumed exactly once by the stdout writer;\n * - every export has an explicit target: the print commands require `--model`,\n * and auth checks require `--provider` or an exact `--model` plus\n * `--credentials`;\n * - there is no `--output <file>` and no clipboard path — stdout only;\n * - every failure is a distinct exit code, and stdout stays empty on all of\n * them but one — `CredentialTruncated` (exit 9) exists to report the case\n * where it cannot be, because bytes already left and cannot be recalled;\n * - a failed OAuth refresh never mutates the stored credential.\n *\n * One residual, and it is upstream: when a model infers several eligible\n * providers, each is asked for its credential before the ambiguity is known, so\n * a *successful* refresh can rotate and persist a credential this command then\n * declines to emit (exit 3). See the note on the `getAuth()` call in the\n * candidate loop.\n */\n\nimport { inspect } from \"node:util\";\nimport type { Api, AuthType, Model } from \"@bastani/pi-ai\";\nimport { ModelsError } from \"@bastani/pi-ai\";\nimport { resolveCliModel } from \"../core/model-resolver.ts\";\nimport type { ModelRuntime } from \"../core/model-runtime.js\";\nimport { flushRawStdout, RawStdoutWriteError, writeRawStdoutOnce } from \"../core/output-guard.ts\";\nimport type { Args } from \"./args.ts\";\n\nexport type CredentialPrintKind = \"api_key\" | \"bearer_token\";\n\n/** Bearer tokens are refreshed unless they still have this much life left. */\nexport const DEFAULT_BEARER_TOKEN_MIN_EXPIRY_MS = 30 * 60_000;\n\n/**\n * Failure taxonomy. Each member owns one exit code, so a caller can branch on\n * the status without parsing stderr.\n */\nexport type CredentialPrintErrorCode =\n\t| \"Usage\"\n\t| \"NoCredentialConfigured\"\n\t| \"ProviderAmbiguous\"\n\t| \"KindUnsupportedForProvider\"\n\t| \"RefreshFailed\"\n\t| \"MinValidityUnreachable\"\n\t| \"OAuthUnavailable\"\n\t| \"CredentialNotEmitted\"\n\t| \"CredentialTruncated\";\n\n/**\n * Exported so a test can walk the whole taxonomy: every declared code has to\n * name an exercised path, and the record type makes a new member without an\n * exit code a compile error rather than a review miss.\n *\n * Every one of these leaves stdout empty except `CredentialTruncated`, which\n * exists to report the one case where it cannot be: bytes already went out and\n * cannot be recalled. `STDOUT_EMPTY_ON_EXIT` names that split so the taxonomy\n * test asserts it rather than assuming it.\n */\nexport const EXIT_CODES: Record<CredentialPrintErrorCode, number> = {\n\tUsage: 1,\n\tNoCredentialConfigured: 2,\n\tProviderAmbiguous: 3,\n\tKindUnsupportedForProvider: 4,\n\tRefreshFailed: 5,\n\tMinValidityUnreachable: 6,\n\tOAuthUnavailable: 7,\n\tCredentialNotEmitted: 8,\n\tCredentialTruncated: 9,\n};\n\n/** The codes whose contract is an empty stdout. See `EXIT_CODES`. */\nexport const STDOUT_EMPTY_ON_EXIT: ReadonlySet<CredentialPrintErrorCode> = new Set(\n\t(Object.keys(EXIT_CODES) as CredentialPrintErrorCode[]).filter((code) => code !== \"CredentialTruncated\"),\n);\n\nexport class CredentialPrintError extends Error {\n\treadonly code: CredentialPrintErrorCode;\n\treadonly exitCode: number;\n\n\tconstructor(code: CredentialPrintErrorCode, message: string, options?: { cause?: unknown }) {\n\t\tsuper(message, options);\n\t\tthis.name = \"CredentialPrintError\";\n\t\tthis.code = code;\n\t\tthis.exitCode = EXIT_CODES[code];\n\t}\n}\n\n/**\n * A credential in transit.\n *\n * Every path that would copy the value into a string is closed: `toString`,\n * `toJSON`, and `Symbol.toPrimitive` throw rather than return, so a template\n * literal, `JSON.stringify`, or string concatenation fails loudly instead of\n * leaking into a log line, a transcript, or an error message. `inspect` — which\n * `console.log` and Node's error formatting use — renders a placeholder.\n *\n * `take()` is the single exit, and it works once.\n */\nexport class Secret {\n\t#value: string | undefined;\n\n\tconstructor(value: string) {\n\t\tthis.#value = value;\n\t}\n\n\t/** Consume the secret. A second call is a bug, not a second read. */\n\ttake(): string {\n\t\tconst value = this.#value;\n\t\tif (value === undefined) {\n\t\t\tthrow new Error(\"Secret has already been consumed\");\n\t\t}\n\t\tthis.#value = undefined;\n\t\treturn value;\n\t}\n\n\ttoString(): never {\n\t\tthrow new Error(\"A Secret cannot be converted to a string; use take()\");\n\t}\n\n\ttoJSON(): never {\n\t\tthrow new Error(\"A Secret cannot be serialized; use take()\");\n\t}\n\n\t[Symbol.toPrimitive](): never {\n\t\tthrow new Error(\"A Secret cannot be interpolated; use take()\");\n\t}\n\n\t[inspect.custom](): string {\n\t\treturn \"[Secret]\";\n\t}\n}\n\n/** Public readiness fields emitted with a credential under `auth check --json --credentials`. */\nexport interface CredentialJsonFields {\n\tstatus: string;\n\tprovider: string;\n\tauthType?: string;\n}\n\n/**\n * The only function in `src` that opens a `Secret`.\n *\n * Its two `Secret.take()` calls are the only call sites in `src`, and the\n * source-wide credential-egress test pins that list. This function builds one\n * payload and returns it only to `emitCredential`; no caller receives a plain\n * credential string.\n */\nfunction credentialPayload(secret: Secret, jsonFields: CredentialJsonFields | undefined): string {\n\tif (jsonFields === undefined) return `${secret.take()}\\n`;\n\n\tconst { status, provider, authType } = jsonFields;\n\tif (\n\t\ttypeof status !== \"string\" ||\n\t\ttypeof provider !== \"string\" ||\n\t\t(authType !== undefined && typeof authType !== \"string\")\n\t) {\n\t\tthrow new Error(\"Invalid credential JSON fields\");\n\t}\n\n\t// Allowlist the non-secret envelope before opening the Secret. That leaves no\n\t// formatter, logger, or error path between take() and the guarded stdout write.\n\tconst fields = JSON.stringify({\n\t\tstatus,\n\t\tprovider,\n\t\t...(authType === undefined ? {} : { authType }),\n\t});\n\tif (fields === undefined || !fields.startsWith(\"{\") || !fields.endsWith(\"}\")) {\n\t\tthrow new Error(\"Invalid credential JSON envelope\");\n\t}\n\treturn `${fields.slice(0, -1)},\"credentials\":${JSON.stringify(secret.take())}}\\n`;\n}\n\n/**\n * The single credential egress in `src`.\n *\n * `credentialPayload` opens the secret only while building this one payload,\n * and this guarded write is the only path that hands it to real stdout. A\n * caller — `main.ts` included — receives a `Secret` it cannot read, print, or\n * serialize, so it cannot add a second export path without crossing this door.\n * `test/credential-print.test.ts` pins both the `take()` sites and every\n * data-bearing real-stdout write in `packages/coding-agent/src`.\n *\n * A failed payload write is answered from the stream rather than from the shape\n * of the error, because `bytesWritten` says how much of the credential actually\n * left and the right report differs for each amount.\n *\n * Nothing left — the write call threw, or the callback failed with the counter\n * unmoved — is `CredentialNotEmitted` (exit 8) with stdout provably empty,\n * which is what that exit promises. It must not fall through to the caller's\n * credential-resolution catch, which would report exit 2.\n *\n * All of it left and the failure came after: the caller holds the credential it\n * asked for, so this is reported on stderr with the exit code left at 0, for\n * the same reason the trailing drain is. A non-zero exit over a stream carrying\n * a whole credential is the thing this door never produces.\n *\n * Part of it left is neither. Those bytes cannot be recalled, so stdout is not\n * empty and cannot be made empty; but they are a fragment, not a credential,\n * and reporting success over them would hand a caller a truncated secret it\n * cannot tell from a whole one. That case gets `CredentialTruncated` (exit 9),\n * the one code in this taxonomy whose contract is *not* an empty stdout —\n * stated as such in `EXIT_CODES` and asserted through `STDOUT_EMPTY_ON_EXIT`,\n * rather than left for a caller to discover.\n */\nexport async function emitCredential(secret: Secret, jsonFields: CredentialJsonFields | undefined): Promise<void> {\n\tconst payload = credentialPayload(secret, jsonFields);\n\ttry {\n\t\tawait writeRawStdoutOnce(payload);\n\t} catch (error) {\n\t\tif (error instanceof RawStdoutWriteError && error.emitted === \"all\") {\n\t\t\t// The caller holds the whole credential. Exiting non-zero here would be\n\t\t\t// a non-zero exit over a stream carrying it, which this door never does.\n\t\t\tconsole.error(\n\t\t\t\t`Warning: the credential reached stdout but the write did not complete cleanly: ${error.message}`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (error instanceof RawStdoutWriteError && error.emitted === \"partial\") {\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"CredentialTruncated\",\n\t\t\t\t\"Only part of the credential reached stdout; discard the output, it is not a usable credential\",\n\t\t\t\t{ cause: error },\n\t\t\t);\n\t\t}\n\t\tthrow new CredentialPrintError(\n\t\t\t\"CredentialNotEmitted\",\n\t\t\t\"Failed to write the credential to stdout; nothing was emitted\",\n\t\t\t{ cause: error },\n\t\t);\n\t}\n\ttry {\n\t\tawait flushRawStdout();\n\t} catch (error) {\n\t\tconsole.error(\n\t\t\t`Warning: the credential was written to stdout but the stream did not drain cleanly: ${\n\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t}`,\n\t\t);\n\t}\n}\n\n/**\n * The single place a thrown value becomes an exit code for this door.\n *\n * `main.ts` routes every failure through here. Every code it can produce leaves\n * stdout empty, so an exit code from this door never contradicts the stream.\n */\nexport function toCredentialPrintError(error: unknown): CredentialPrintError {\n\tif (error instanceof CredentialPrintError) return error;\n\treturn new CredentialPrintError(\n\t\t\"NoCredentialConfigured\",\n\t\terror instanceof Error ? error.message : \"Failed to resolve credential\",\n\t\t{ cause: error },\n\t);\n}\n\n/**\n * The only two fields of `Args` this door accepts.\n *\n * Validation is an allowlist rather than a list of refusals, because the\n * refusal list only held while the dispatcher happened to ignore every other\n * flag. `--export <path>`, `--session-dir <path>`, `--print`, and `--help` are\n * all parsed by `parseArgs`; under an exclusion check they passed silently and\n * the door's \"no file sink\" guarantee rested on a downstream accident.\n */\nconst ACCEPTED_ARG_FIELDS: ReadonlySet<string> = new Set([\"model\", \"provider\"]);\n\n/** Names every field of a parsed `Args` that the caller actually set. */\nfunction populatedArgFields(args: Args): string[] {\n\tconst populated: string[] = [];\n\tfor (const [field, value] of Object.entries(args)) {\n\t\tif (ACCEPTED_ARG_FIELDS.has(field) || value === undefined) continue;\n\t\tif (Array.isArray(value)) {\n\t\t\tif (value.length > 0) populated.push(field);\n\t\t} else if (value instanceof Map) {\n\t\t\tif (value.size > 0) populated.push(field);\n\t\t} else {\n\t\t\tpopulated.push(field);\n\t\t}\n\t}\n\treturn populated;\n}\n\nexport function validateCredentialPrintArgs(args: Args): void {\n\tif (!args.model?.trim()) {\n\t\tthrow new CredentialPrintError(\"Usage\", \"Credential printing requires --model <model>\");\n\t}\n\tif (args.apiKey !== undefined) {\n\t\tthrow new CredentialPrintError(\n\t\t\t\"Usage\",\n\t\t\t\"Credential printing reads configured credentials; --api-key is not supported\",\n\t\t);\n\t}\n\tconst refused = populatedArgFields(args);\n\tif (refused.length > 0) {\n\t\tthrow new CredentialPrintError(\n\t\t\t\"Usage\",\n\t\t\t`Credential printing only accepts --provider and --model (refused: ${refused.join(\", \")})`,\n\t\t);\n\t}\n}\n\n/**\n * Provider-supplied text with anything credential-bearing masked.\n *\n * A failed refresh is reported on stderr, and the provider composes that\n * message. Most describe the failure; some quote the request they sent or the\n * body they got back, either of which can carry the very value this door exists\n * to keep off every stream except stdout. Masking keeps the diagnosis — which\n * is what makes the exit code actionable — without putting the secret in a log,\n * a terminal scrollback, or a CI transcript.\n *\n * Two passes, because either alone leaves a gap. Shape catches a value wherever\n * it appears, but only for the formats that announce themselves. Context\n * catches an opaque value — an `x-api-key`, which is just bytes — by the name it\n * is filed under, in the header, JSON, and query spellings a quoted request or\n * response body uses.\n */\nconst CREDENTIAL_SHAPES: readonly RegExp[] = [\n\t// `Authorization: Bearer <token>`, the form an echoed request header takes.\n\t/\\bBearer\\s+[\\w.~+/-]+=*/giu,\n\t// JWTs, which several providers return verbatim in an error body.\n\t/\\beyJ[\\w-]{8,}\\.[\\w-]{8,}\\.[\\w-]+/gu,\n\t// Prefixed API keys: sk-…, sk_live_…, api-key-…, and the same shapes again.\n\t/\\b(?:sk|pk|rk|api|key|tok|token|secret)[-_][\\w-]{12,}/giu,\n];\n\n/**\n * Field names whose value is the credential, however opaque that value looks.\n * `x-api-key` is the case shape-matching cannot reach: the value is just bytes.\n */\nconst CREDENTIAL_FIELD_NAME =\n\t\"(?:x-)?(?:api[-_]?key|apikey|auth(?:orization)?|access[-_]?token|refresh[-_]?token|id[-_]?token|client[-_]?secret|secret[-_]?key|private[-_]?key|session[-_]?key|password|passwd|token|secret|key)\";\n\n/**\n * Auth schemes that stand between the field name and the value it introduces.\n *\n * Without them the header matcher stops at the space after `Bearer`: it redacts\n * the scheme and leaves the token, and having consumed the `Bearer` the shape\n * pass depends on, that pass can no longer reach the token either. An opaque\n * `Authorization: Bearer <token>` then survives both passes.\n */\nconst CREDENTIAL_AUTH_SCHEME = \"(?:Bearer|Basic|Digest|Token|ApiKey|OAuth)\";\n\nconst CREDENTIAL_CONTEXTS: readonly RegExp[] = [\n\t// Header or YAML-ish: `x-api-key: abc123`, to end of line, and the scheme\n\t// form `Authorization: Bearer abc123` with it.\n\tnew RegExp(String.raw`\\b${CREDENTIAL_FIELD_NAME}\\s*:\\s*(?:${CREDENTIAL_AUTH_SCHEME}\\s+)?[^\\s,;}\"']+`, \"giu\"),\n\t// JSON: `\"api_key\": \"abc123\"` / `'token':'abc123'`, quoted value.\n\tnew RegExp(String.raw`([\"']?)${CREDENTIAL_FIELD_NAME}\\1\\s*:\\s*([\"'])(?:(?!\\2).)*\\2`, \"giu\"),\n\t// Query string or form body: `?api_key=abc123&…`.\n\tnew RegExp(String.raw`\\b${CREDENTIAL_FIELD_NAME}\\s*=\\s*[^\\s&,;}\"']+`, \"giu\"),\n];\n\nexport function redactCredentialShapes(text: string): string {\n\tconst byContext = CREDENTIAL_CONTEXTS.reduce(\n\t\t(masked, context) =>\n\t\t\tmasked.replace(context, (match) => {\n\t\t\t\t// Keep the field name so the diagnosis still says which one failed;\n\t\t\t\t// replace only what follows the separator.\n\t\t\t\tconst separator = /[:=]/u.exec(match);\n\t\t\t\treturn separator ? `${match.slice(0, separator.index + 1)} [redacted]` : \"[redacted]\";\n\t\t\t}),\n\t\ttext,\n\t);\n\treturn CREDENTIAL_SHAPES.reduce((masked, shape) => masked.replace(shape, \"[redacted]\"), byContext);\n}\n\n/**\n * The literal phrase pi-ai throws when a refresh itself failed, from inside\n * `credentials.modify` and therefore before anything is persisted. This is the\n * only oauth-coded error that can claim the stored credential was left alone.\n */\nexport const OAUTH_REFRESH_FAILED_PHRASE = \"OAuth refresh failed for\";\n\n/**\n * The literal phrase pi-ai throws when a refresh succeeded but the rotated\n * token still expires inside the requested window. It is the only signal that\n * separates exit 6 from exit 5.\n */\nexport const OAUTH_EXPIRES_TOO_SOON_PHRASE = \"expires too soon\";\n\n/**\n * pi-ai raises three different `oauth`-coded failures from\n * `dist/auth/resolve.js`, and only one of them is a failed refresh.\n *\n * `OAuth auth derivation failed for <provider>` is thrown after\n * `credentials.modify` has already persisted a rotated credential, and also on\n * the branch where no refresh was attempted at all — so it gets its own code\n * and a message that makes no claim about the stored credential. Treating it as\n * `RefreshFailed` asserted a rollback the command never verified.\n *\n * Classification reads the raw message, because redaction could rewrite the\n * phrase it matches on; only the text that becomes a user-facing message is\n * redacted. The unredacted error stays reachable as `cause`, which this door\n * never logs.\n *\n * `test/credential-print.test.ts` pins both phrases against the installed\n * pi-ai build, so an upstream rewording fails the suite rather than silently\n * collapsing exit 6 into exit 5.\n */\nexport function classifyOAuthFailure(error: ModelsError): CredentialPrintError {\n\tconst detail = redactCredentialShapes(error.message);\n\tif (error.message.includes(OAUTH_EXPIRES_TOO_SOON_PHRASE)) {\n\t\treturn new CredentialPrintError(\n\t\t\t\"MinValidityUnreachable\",\n\t\t\t`The provider refreshed the token but it still expires sooner than requested: ${detail}`,\n\t\t\t{ cause: error },\n\t\t);\n\t}\n\tif (error.message.startsWith(OAUTH_REFRESH_FAILED_PHRASE)) {\n\t\treturn new CredentialPrintError(\"RefreshFailed\", `${detail} (the stored credential was left untouched)`, {\n\t\t\tcause: error,\n\t\t});\n\t}\n\treturn new CredentialPrintError(\"OAuthUnavailable\", detail, { cause: error });\n}\n\n/**\n * Providers whose credential the caller could have meant.\n *\n * With `--provider` the caller named one, so failing to resolve it is an error.\n * Without it, eligibility is *not* narrowed to providers holding a persisted\n * credential: a provider authenticated by an environment variable or a custom\n * resolver has nothing in `auth.json`, and filtering on that list dropped it\n * before `getAuth()` could produce its working key. Candidacy is therefore\n * \"offers the named model\", and `getAuth()` — the same call a real request\n * makes — decides which candidate actually authenticates.\n */\nfunction candidateModels(args: Args, modelRuntime: ModelRuntime): Model<Api>[] {\n\tif (args.provider) {\n\t\tconst resolved = resolveCliModel({ cliProvider: args.provider, cliModel: args.model, modelRuntime });\n\t\tif (resolved.error || !resolved.model) {\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"NoCredentialConfigured\",\n\t\t\t\tresolved.error ?? \"Unable to resolve the requested provider/model\",\n\t\t\t);\n\t\t}\n\t\treturn [resolved.model];\n\t}\n\n\tconst models: Model<Api>[] = [];\n\tfor (const provider of modelRuntime.getProviders()) {\n\t\tconst resolved = resolveCliModel({ cliProvider: provider.id, cliModel: args.model, modelRuntime });\n\t\tif (resolved.model && !resolved.error && !resolved.warning?.includes(\"Using custom model id\")) {\n\t\t\tmodels.push(resolved.model);\n\t\t}\n\t}\n\tif (models.length === 0) {\n\t\tthrow new CredentialPrintError(\n\t\t\t\"NoCredentialConfigured\",\n\t\t\t`Model \"${args.model}\" not found among the available providers. Use --list-models to see available models.`,\n\t\t);\n\t}\n\treturn models;\n}\n\nfunction bearerFromHeaders(headers: Record<string, unknown> | undefined): string | undefined {\n\tconst authorization = Object.entries(headers ?? {}).find(([name]) => name.toLowerCase() === \"authorization\")?.[1];\n\treturn typeof authorization === \"string\" ? /^Bearer\\s+(.+)$/iu.exec(authorization)?.[1] : undefined;\n}\n\n/**\n * Resolve exactly one credential for a named provider/model pair.\n *\n * Goes through `ModelRuntime.getAuth()`, the same request-auth path a real\n * model call uses, so an OAuth credential is refreshed and persisted by the one\n * implementation that already handles concurrent refresh under a lock.\n */\nexport async function resolveCredentialForPrint(\n\targs: Args,\n\tmodelRuntime: ModelRuntime,\n\tkind: CredentialPrintKind,\n\tminExpiryMs?: number,\n): Promise<Secret> {\n\tvalidateCredentialPrintArgs(args);\n\n\t// The effective auth type per candidate provider, taken from the runtime\n\t// rather than from auth.json.\n\t//\n\t// `checkAuth` reports what a provider would actually authenticate with,\n\t// including a credential supplied by an environment variable or a custom\n\t// resolver that persists nothing, and it answers without refreshing OAuth.\n\t// `listCredentials()` sees only what was stored, which both hid working\n\t// credentials and — for a provider offering an API key *and* OAuth — could not\n\t// say which of the two a request would use. Provider capability cannot say\n\t// either: several providers send an API key as `Authorization: Bearer`, so\n\t// neither that header nor `apiKey` identifies the credential's kind on its own.\n\tconst wantedAuthType: AuthType = kind === \"api_key\" ? \"api_key\" : \"oauth\";\n\tconst resolvedAuthTypes = new Map<string, AuthType | undefined>();\n\tconst models = candidateModels(args, modelRuntime);\n\tfor (const { provider } of models) {\n\t\tif (resolvedAuthTypes.has(provider)) continue;\n\t\tresolvedAuthTypes.set(provider, (await modelRuntime.checkAuth(provider))?.type);\n\t}\n\t// A named provider, or a single candidate, is the one the caller meant, so its\n\t// authentication failure is reported with its own exit code. Among several\n\t// inferred candidates a failure only means \"not this one\" — reporting it would\n\t// let an unrelated provider that happens to offer the model decide the exit\n\t// code for a request another candidate can satisfy.\n\tconst authFailureIsFatal = args.provider !== undefined || models.length === 1;\n\n\tconst credentials: Array<{ providerId: string; value: string }> = [];\n\t// The classified diagnosis from a candidate that could not authenticate.\n\t// Skipping a candidate must not discard why it failed: a refresh that failed,\n\t// or a token that cannot reach the requested validity, is the real answer if\n\t// nothing else produces a credential, and keeping it is what leaves exits 5\n\t// and 6 reachable instead of collapsing every inferred failure into exit 2.\n\t// It holds a `CredentialPrintError`, never a credential — the provider's text\n\t// is redacted on the way in.\n\tlet deferredDiagnosis: CredentialPrintError | undefined;\n\tfor (const model of models) {\n\t\tconst type = resolvedAuthTypes.get(model.provider);\n\t\tif (type !== wantedAuthType) continue;\n\n\t\t// Every eligible candidate is asked here, before `ProviderAmbiguous` is\n\t\t// known, so an ambiguous export can refresh and persist credentials it\n\t\t// emits nothing for. Deciding eligibility earlier is not available:\n\t\t// `checkAuth()` is the only non-mutating probe and cannot tell a candidate\n\t\t// that will authenticate from one that will fail, which is what keeps\n\t\t// exits 5 and 6 reachable. Nor does resolving without refreshing exist —\n\t\t// `resolveStoredOAuth` in `@bastani/pi-ai` refreshes whenever the\n\t\t// token falls inside `max(DEFAULT_OAUTH_MINIMUM_VALIDITY_MS,\n\t\t// minOAuthValidityMs ?? 0)`, so omitting `minOAuthValidityMs` only lowers\n\t\t// that window to five minutes and drops the post-refresh check exit 6 is\n\t\t// decided by. Bounded: the refresh rotates a valid credential, it does not\n\t\t// invalidate one. Closing it needs a non-mutating probe upstream.\n\t\tlet auth: Awaited<ReturnType<ModelRuntime[\"getAuth\"]>>;\n\t\ttry {\n\t\t\tauth = await modelRuntime.getAuth(\n\t\t\t\tmodel,\n\t\t\t\tkind === \"bearer_token\" ? { minOAuthValidityMs: minExpiryMs ?? DEFAULT_BEARER_TOKEN_MIN_EXPIRY_MS } : {},\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst diagnosis =\n\t\t\t\terror instanceof ModelsError && error.code === \"oauth\" ? classifyOAuthFailure(error) : undefined;\n\t\t\tif (!authFailureIsFatal) {\n\t\t\t\tdeferredDiagnosis ??= diagnosis;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (diagnosis) throw diagnosis;\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"NoCredentialConfigured\",\n\t\t\t\tredactCredentialShapes(error instanceof Error ? error.message : String(error)),\n\t\t\t\t{ cause: error },\n\t\t\t);\n\t\t}\n\n\t\tconst value =\n\t\t\tkind === \"bearer_token\" ? (auth?.auth.apiKey ?? bearerFromHeaders(auth?.auth.headers)) : auth?.auth.apiKey;\n\t\tif (value) credentials.push({ providerId: model.provider, value });\n\t}\n\n\tif (credentials.length === 1) return new Secret(credentials[0].value);\n\n\tif (credentials.length === 0) {\n\t\tif (deferredDiagnosis) throw deferredDiagnosis;\n\t\tconst providerId = models[0]?.provider;\n\t\tconst type = providerId ? resolvedAuthTypes.get(providerId) : undefined;\n\t\tif (args.provider && kind === \"api_key\" && type === \"oauth\") {\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"KindUnsupportedForProvider\",\n\t\t\t\t`Provider \"${providerId}\" is configured with OAuth, not an API key`,\n\t\t\t);\n\t\t}\n\t\tif (args.provider && kind === \"bearer_token\" && type === \"api_key\") {\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"KindUnsupportedForProvider\",\n\t\t\t\t`Provider \"${providerId}\" is not configured with an OAuth bearer token`,\n\t\t\t);\n\t\t}\n\t\tthrow new CredentialPrintError(\n\t\t\t\"NoCredentialConfigured\",\n\t\t\t`No usable ${kind === \"api_key\" ? \"API key\" : \"OAuth bearer token\"} is configured`,\n\t\t);\n\t}\n\n\tthrow new CredentialPrintError(\n\t\t\"ProviderAmbiguous\",\n\t\t`Model \"${args.model}\" has multiple configured providers (${credentials\n\t\t\t.map(({ providerId }) => providerId)\n\t\t\t.join(\", \")}). Specify --provider.`,\n\t);\n}\n"]}
|
|
@@ -5,9 +5,12 @@ export function stringOption(name) {
|
|
|
5
5
|
return valueOption(name, (value) => ({ ok: true, value }));
|
|
6
6
|
}
|
|
7
7
|
export class Command {
|
|
8
|
+
name;
|
|
9
|
+
options = new Map();
|
|
10
|
+
subcommands = new Map();
|
|
11
|
+
builder;
|
|
12
|
+
commandAction;
|
|
8
13
|
constructor(name) {
|
|
9
|
-
this.options = new Map();
|
|
10
|
-
this.subcommands = new Map();
|
|
11
14
|
this.name = name;
|
|
12
15
|
}
|
|
13
16
|
option(option) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"command.js","sourceRoot":"","sources":["../../../src/cli/experimental/command.ts"],"names":[],"mappings":"AAqBA,MAAM,UAAU,WAAW,CAC1B,IAAmB,EACnB,KAA0D;IAE1D,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;AACxB,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,IAAmB;IAC/C,OAAO,WAAW,CAAC,IAAI,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;AAC5D,CAAC;AAgCD,MAAM,OAAO,OAAO;IAWnB,YAAY,IAAY;QALP,YAAO,GAAG,IAAI,GAAG,EAAkC,CAAC;QACpD,gBAAW,GAAG,IAAI,GAAG,EAA6B,CAAC;QAKnE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAClB,CAAC;IAED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AM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;YAC7C,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBACvB,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,6BAA6B,CAAC,CAAC;gBACzD,SAAS;YACV,CAAC;YACD,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;YACnC,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC;gBAChB,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;gBACjC,SAAS;YACV,CAAC;YACD,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YAC1B,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACjC,CAAC;QACD,OAAO,MAAM,CAAC;IACf,CAAC;CACD","sourcesContent":["export interface NamedCommandInvocation {\n\treadonly command: string;\n}\n\nexport type CommandParseResult<TInvocation extends NamedCommandInvocation = NamedCommandInvocation> =\n\t| { readonly ok: true; readonly command: TInvocation }\n\t| { readonly ok: false; readonly errors: readonly string[] };\n\nexport type CommandExecutionResult<TInvocation extends NamedCommandInvocation = NamedCommandInvocation> =\n\t| { readonly ok: true; readonly command: TInvocation }\n\t| { readonly ok: false; readonly errors: readonly string[] };\n\nexport type CommandOptionParseResult<TValue> =\n\t| { readonly ok: true; readonly value: TValue }\n\t| { readonly ok: false; readonly error: string };\n\nexport interface CommandOption<TValue> {\n\treadonly name: `--${string}`;\n\tparse(value: string): CommandOptionParseResult<TValue>;\n}\n\nexport function valueOption<TValue>(\n\tname: `--${string}`,\n\tparse: (value: string) => CommandOptionParseResult<TValue>,\n): CommandOption<TValue> {\n\treturn { name, parse };\n}\n\nexport function stringOption(name: `--${string}`): CommandOption<string> {\n\treturn valueOption(name, (value) => ({ ok: true, value }));\n}\n\nexport interface ParsedCommandInput {\n\treadonly remainingArgs: readonly string[];\n\tvalue<TValue>(option: CommandOption<TValue>): TValue | undefined;\n\tvalues<TValue>(option: CommandOption<TValue>): readonly TValue[];\n}\n\nexport type CommandBuildResult<TInvocation extends NamedCommandInvocation> =\n\t| { readonly ok: true; readonly command: TInvocation }\n\t| { readonly ok: false; readonly errors: readonly string[] };\n\ninterface MutableParsedCommandInput {\n\treadonly values: Map<string, unknown[]>;\n\treadonly remainingArgs: string[];\n\treadonly errors: string[];\n}\n\ntype CommandBuilder<TInvocation extends NamedCommandInvocation> = (\n\tinput: ParsedCommandInput,\n) => CommandBuildResult<TInvocation>;\n\ntype CommandAction<TInvocation extends NamedCommandInvocation, TContext> = (\n\tcommand: TInvocation,\n\tcontext: TContext,\n) => void | Promise<void>;\n\ninterface RegisteredCommand {\n\tparse(argv: readonly string[]): CommandParseResult;\n\texecute(argv: readonly string[], context: unknown): Promise<CommandExecutionResult>;\n}\n\nexport class Command<\n\tTOwnInvocation extends NamedCommandInvocation,\n\tTContext,\n\tTInvocation extends NamedCommandInvocation = TOwnInvocation,\n> {\n\treadonly name: string;\n\tprivate readonly options = new Map<string, CommandOption<unknown>>();\n\tprivate readonly subcommands = new Map<string, RegisteredCommand>();\n\tprivate builder?: CommandBuilder<TOwnInvocation>;\n\tprivate commandAction?: CommandAction<TOwnInvocation, TContext>;\n\n\tconstructor(name: string) {\n\t\tthis.name = name;\n\t}\n\n\toption<TValue>(option: CommandOption<TValue>): this {\n\t\tif (this.options.has(option.name)) {\n\t\t\tthrow new Error(`Option ${option.name} is already registered for ${this.name}`);\n\t\t}\n\t\tthis.options.set(option.name, option);\n\t\treturn this;\n\t}\n\n\tbuild(builder: CommandBuilder<TOwnInvocation>): this {\n\t\tthis.builder = builder;\n\t\treturn this;\n\t}\n\n\taction(action: CommandAction<TOwnInvocation, TContext>): this {\n\t\tthis.commandAction = action;\n\t\treturn this;\n\t}\n\n\tcommand<\n\t\tTSubcommandOwnInvocation extends NamedCommandInvocation,\n\t\tTSubcommandContext,\n\t\tTSubcommandInvocation extends NamedCommandInvocation,\n\t>(\n\t\tcommand: Command<TSubcommandOwnInvocation, TSubcommandContext, TSubcommandInvocation>,\n\t): Command<TOwnInvocation, TContext & TSubcommandContext, TInvocation | TSubcommandInvocation> {\n\t\tif (this.subcommands.has(command.name)) throw new Error(`Command ${command.name} is already registered`);\n\t\tthis.subcommands.set(command.name, {\n\t\t\tparse: (argv) => command.parse(argv),\n\t\t\texecute: (argv, context) => command.execute(argv, context as TSubcommandContext),\n\t\t});\n\t\treturn this as unknown as Command<\n\t\t\tTOwnInvocation,\n\t\t\tTContext & TSubcommandContext,\n\t\t\tTInvocation | TSubcommandInvocation\n\t\t>;\n\t}\n\n\tparse(argv: readonly string[]): CommandParseResult<TInvocation> {\n\t\tconst selected = this.select(argv);\n\t\tif (selected) return selected.command.parse(selected.argv) as CommandParseResult<TInvocation>;\n\t\treturn this.parseOwn(argv) as CommandParseResult<TInvocation>;\n\t}\n\n\tasync execute(argv: readonly string[], context: TContext): Promise<CommandExecutionResult<TInvocation>> {\n\t\tconst selected = this.select(argv);\n\t\tif (selected) {\n\t\t\treturn selected.command.execute(selected.argv, context) as Promise<CommandExecutionResult<TInvocation>>;\n\t\t}\n\n\t\tconst parsed = this.parseOwn(argv);\n\t\tif (!parsed.ok) return parsed;\n\t\tif (!this.commandAction) throw new Error(`Command ${this.name} does not define an action`);\n\t\tawait this.commandAction(parsed.command, context);\n\t\treturn { ok: true, command: parsed.command as unknown as TInvocation };\n\t}\n\n\tprivate select(argv: readonly string[]): { command: RegisteredCommand; argv: readonly string[] } | undefined {\n\t\tconst candidate = argv[0];\n\t\tif (candidate === undefined) return undefined;\n\t\tconst command = this.subcommands.get(candidate);\n\t\treturn command ? { command, argv: argv.slice(1) } : undefined;\n\t}\n\n\tprivate parseOwn(argv: readonly string[]): CommandParseResult<TOwnInvocation> {\n\t\tif (!this.builder) throw new Error(`Command ${this.name} does not define a builder`);\n\t\tconst parsed = this.parseOptions(argv);\n\t\tconst input: ParsedCommandInput = {\n\t\t\tremainingArgs: parsed.remainingArgs,\n\t\t\tvalue: <TValue>(option: CommandOption<TValue>) => parsed.values.get(option.name)?.[0] as TValue | undefined,\n\t\t\tvalues: <TValue>(option: CommandOption<TValue>) => (parsed.values.get(option.name) ?? []) as readonly TValue[],\n\t\t};\n\t\tconst built = this.builder(input);\n\t\tconst errors = [...parsed.errors, ...(built.ok ? [] : built.errors)];\n\t\tif (errors.length > 0) return { ok: false, errors };\n\t\tif (!built.ok) throw new Error(`Command ${this.name} failed without an error`);\n\t\treturn { ok: true, command: built.command };\n\t}\n\n\tprivate parseOptions(argv: readonly string[]): MutableParsedCommandInput {\n\t\tconst parsed: MutableParsedCommandInput = {\n\t\t\tvalues: new Map(),\n\t\t\tremainingArgs: [],\n\t\t\terrors: [],\n\t\t};\n\t\tfor (let index = 0; index < argv.length; index++) {\n\t\t\tconst argument = argv[index]!;\n\t\t\tif (argument === \"--\") {\n\t\t\t\tparsed.remainingArgs.push(...argv.slice(index));\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tconst equals = argument.indexOf(\"=\");\n\t\t\tconst name = equals === -1 ? argument : argument.slice(0, equals);\n\t\t\tconst option = this.options.get(name);\n\t\t\tif (!option) {\n\t\t\t\tparsed.remainingArgs.push(...argv.slice(index));\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tlet value = equals === -1 ? undefined : argument.slice(equals + 1);\n\t\t\tif (value === undefined) {\n\t\t\t\tconst next = argv[index + 1];\n\t\t\t\tif (next !== undefined && !next.startsWith(\"-\")) {\n\t\t\t\t\tvalue = next;\n\t\t\t\t\tindex++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (value === undefined || value === \"\") {\n\t\t\t\tparsed.errors.push(`${name} requires a value`);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst values = parsed.values.get(name) ?? [];\n\t\t\tif (values.length > 0) {\n\t\t\t\tparsed.errors.push(`${name} may only be specified once`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst result = option.parse(value);\n\t\t\tif (!result.ok) {\n\t\t\t\tparsed.errors.push(result.error);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvalues.push(result.value);\n\t\t\tparsed.values.set(name, values);\n\t\t}\n\t\treturn parsed;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"command.js","sourceRoot":"","sources":["../../../src/cli/experimental/command.ts"],"names":[],"mappings":"AAqBA,MAAM,UAAU,WAAW,CAC1B,IAAmB,EACnB,KAA0D;IAE1D,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;AACxB,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,IAAmB;IAC/C,OAAO,WAAW,CAAC,IAAI,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;AAC5D,CAAC;AAgCD,MAAM,OAAO,OAAO;IAKV,IAAI,CAAS;IACL,OAAO,GAAG,IAAI,GAAG,EAAkC,CAAC;IACpD,WAAW,GAAG,IAAI,GAAG,EAA6B,CAAC;IAC5D,OAAO,CAAkC;IACzC,aAAa,CAA2C;IAEhE,YAAY,IAAY;QACvB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAClB,CAAC;IAED,MAAM,CAAS,MAA6B;QAC3C,IAAI,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC;YACnC,MAAM,IAAI,KAAK,CAAC,UAAU,MAAM,CAAC,IAAI,8BAA8B,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;QACjF,CAAC;QACD,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACtC,OAAO,IAAI,CAAC;IACb,CAAC;IAED,KAAK,CAAC,OAAuC;QAC5C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AAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;gBACjC,SAAS;YACV,CAAC;YACD,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YAC1B,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACjC,CAAC;QACD,OAAO,MAAM,CAAC;IACf,CAAC;CACD","sourcesContent":["export interface NamedCommandInvocation {\n\treadonly command: string;\n}\n\nexport type CommandParseResult<TInvocation extends NamedCommandInvocation = NamedCommandInvocation> =\n\t| { readonly ok: true; readonly command: TInvocation }\n\t| { readonly ok: false; readonly errors: readonly string[] };\n\nexport type CommandExecutionResult<TInvocation extends NamedCommandInvocation = NamedCommandInvocation> =\n\t| { readonly ok: true; readonly command: TInvocation }\n\t| { readonly ok: false; readonly errors: readonly string[] };\n\nexport type CommandOptionParseResult<TValue> =\n\t| { readonly ok: true; readonly value: TValue }\n\t| { readonly ok: false; readonly error: string };\n\nexport interface CommandOption<TValue> {\n\treadonly name: `--${string}`;\n\tparse(value: string): CommandOptionParseResult<TValue>;\n}\n\nexport function valueOption<TValue>(\n\tname: `--${string}`,\n\tparse: (value: string) => CommandOptionParseResult<TValue>,\n): CommandOption<TValue> {\n\treturn { name, parse };\n}\n\nexport function stringOption(name: `--${string}`): CommandOption<string> {\n\treturn valueOption(name, (value) => ({ ok: true, value }));\n}\n\nexport interface ParsedCommandInput {\n\treadonly remainingArgs: readonly string[];\n\tvalue<TValue>(option: CommandOption<TValue>): TValue | undefined;\n\tvalues<TValue>(option: CommandOption<TValue>): readonly TValue[];\n}\n\nexport type CommandBuildResult<TInvocation extends NamedCommandInvocation> =\n\t| { readonly ok: true; readonly command: TInvocation }\n\t| { readonly ok: false; readonly errors: readonly string[] };\n\ninterface MutableParsedCommandInput {\n\treadonly values: Map<string, unknown[]>;\n\treadonly remainingArgs: string[];\n\treadonly errors: string[];\n}\n\ntype CommandBuilder<TInvocation extends NamedCommandInvocation> = (\n\tinput: ParsedCommandInput,\n) => CommandBuildResult<TInvocation>;\n\ntype CommandAction<TInvocation extends NamedCommandInvocation, TContext> = (\n\tcommand: TInvocation,\n\tcontext: TContext,\n) => void | Promise<void>;\n\ninterface RegisteredCommand {\n\tparse(argv: readonly string[]): CommandParseResult;\n\texecute(argv: readonly string[], context: unknown): Promise<CommandExecutionResult>;\n}\n\nexport class Command<\n\tTOwnInvocation extends NamedCommandInvocation,\n\tTContext,\n\tTInvocation extends NamedCommandInvocation = TOwnInvocation,\n> {\n\treadonly name: string;\n\tprivate readonly options = new Map<string, CommandOption<unknown>>();\n\tprivate readonly subcommands = new Map<string, RegisteredCommand>();\n\tprivate builder?: CommandBuilder<TOwnInvocation>;\n\tprivate commandAction?: CommandAction<TOwnInvocation, TContext>;\n\n\tconstructor(name: string) {\n\t\tthis.name = name;\n\t}\n\n\toption<TValue>(option: CommandOption<TValue>): this {\n\t\tif (this.options.has(option.name)) {\n\t\t\tthrow new Error(`Option ${option.name} is already registered for ${this.name}`);\n\t\t}\n\t\tthis.options.set(option.name, option);\n\t\treturn this;\n\t}\n\n\tbuild(builder: CommandBuilder<TOwnInvocation>): this {\n\t\tthis.builder = builder;\n\t\treturn this;\n\t}\n\n\taction(action: CommandAction<TOwnInvocation, TContext>): this {\n\t\tthis.commandAction = action;\n\t\treturn this;\n\t}\n\n\tcommand<\n\t\tTSubcommandOwnInvocation extends NamedCommandInvocation,\n\t\tTSubcommandContext,\n\t\tTSubcommandInvocation extends NamedCommandInvocation,\n\t>(\n\t\tcommand: Command<TSubcommandOwnInvocation, TSubcommandContext, TSubcommandInvocation>,\n\t): Command<TOwnInvocation, TContext & TSubcommandContext, TInvocation | TSubcommandInvocation> {\n\t\tif (this.subcommands.has(command.name)) throw new Error(`Command ${command.name} is already registered`);\n\t\tthis.subcommands.set(command.name, {\n\t\t\tparse: (argv) => command.parse(argv),\n\t\t\texecute: (argv, context) => command.execute(argv, context as TSubcommandContext),\n\t\t});\n\t\treturn this as unknown as Command<\n\t\t\tTOwnInvocation,\n\t\t\tTContext & TSubcommandContext,\n\t\t\tTInvocation | TSubcommandInvocation\n\t\t>;\n\t}\n\n\tparse(argv: readonly string[]): CommandParseResult<TInvocation> {\n\t\tconst selected = this.select(argv);\n\t\tif (selected) return selected.command.parse(selected.argv) as CommandParseResult<TInvocation>;\n\t\treturn this.parseOwn(argv) as CommandParseResult<TInvocation>;\n\t}\n\n\tasync execute(argv: readonly string[], context: TContext): Promise<CommandExecutionResult<TInvocation>> {\n\t\tconst selected = this.select(argv);\n\t\tif (selected) {\n\t\t\treturn selected.command.execute(selected.argv, context) as Promise<CommandExecutionResult<TInvocation>>;\n\t\t}\n\n\t\tconst parsed = this.parseOwn(argv);\n\t\tif (!parsed.ok) return parsed;\n\t\tif (!this.commandAction) throw new Error(`Command ${this.name} does not define an action`);\n\t\tawait this.commandAction(parsed.command, context);\n\t\treturn { ok: true, command: parsed.command as unknown as TInvocation };\n\t}\n\n\tprivate select(argv: readonly string[]): { command: RegisteredCommand; argv: readonly string[] } | undefined {\n\t\tconst candidate = argv[0];\n\t\tif (candidate === undefined) return undefined;\n\t\tconst command = this.subcommands.get(candidate);\n\t\treturn command ? { command, argv: argv.slice(1) } : undefined;\n\t}\n\n\tprivate parseOwn(argv: readonly string[]): CommandParseResult<TOwnInvocation> {\n\t\tif (!this.builder) throw new Error(`Command ${this.name} does not define a builder`);\n\t\tconst parsed = this.parseOptions(argv);\n\t\tconst input: ParsedCommandInput = {\n\t\t\tremainingArgs: parsed.remainingArgs,\n\t\t\tvalue: <TValue>(option: CommandOption<TValue>) => parsed.values.get(option.name)?.[0] as TValue | undefined,\n\t\t\tvalues: <TValue>(option: CommandOption<TValue>) => (parsed.values.get(option.name) ?? []) as readonly TValue[],\n\t\t};\n\t\tconst built = this.builder(input);\n\t\tconst errors = [...parsed.errors, ...(built.ok ? [] : built.errors)];\n\t\tif (errors.length > 0) return { ok: false, errors };\n\t\tif (!built.ok) throw new Error(`Command ${this.name} failed without an error`);\n\t\treturn { ok: true, command: built.command };\n\t}\n\n\tprivate parseOptions(argv: readonly string[]): MutableParsedCommandInput {\n\t\tconst parsed: MutableParsedCommandInput = {\n\t\t\tvalues: new Map(),\n\t\t\tremainingArgs: [],\n\t\t\terrors: [],\n\t\t};\n\t\tfor (let index = 0; index < argv.length; index++) {\n\t\t\tconst argument = argv[index]!;\n\t\t\tif (argument === \"--\") {\n\t\t\t\tparsed.remainingArgs.push(...argv.slice(index));\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tconst equals = argument.indexOf(\"=\");\n\t\t\tconst name = equals === -1 ? argument : argument.slice(0, equals);\n\t\t\tconst option = this.options.get(name);\n\t\t\tif (!option) {\n\t\t\t\tparsed.remainingArgs.push(...argv.slice(index));\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tlet value = equals === -1 ? undefined : argument.slice(equals + 1);\n\t\t\tif (value === undefined) {\n\t\t\t\tconst next = argv[index + 1];\n\t\t\t\tif (next !== undefined && !next.startsWith(\"-\")) {\n\t\t\t\t\tvalue = next;\n\t\t\t\t\tindex++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (value === undefined || value === \"\") {\n\t\t\t\tparsed.errors.push(`${name} requires a value`);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst values = parsed.values.get(name) ?? [];\n\t\t\tif (values.length > 0) {\n\t\t\t\tparsed.errors.push(`${name} may only be specified once`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst result = option.parse(value);\n\t\t\tif (!result.ok) {\n\t\t\t\tparsed.errors.push(result.error);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvalues.push(result.value);\n\t\t\tparsed.values.set(name, values);\n\t\t}\n\t\treturn parsed;\n\t}\n}\n"]}
|
package/dist/cli.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* CLI entry point for the refactored coding agent.
|
|
4
4
|
* Uses main.ts with AgentSession and new mode modules.
|
|
5
5
|
*
|
|
6
|
-
* Test with:
|
|
6
|
+
* Test with: bun src/cli.ts [args...]
|
|
7
7
|
*
|
|
8
8
|
* Deliberately keeps the static entry graph to config, compile-cache support,
|
|
9
9
|
* attribution, and the disabled-by-default lifecycle seam. The full CLI graph
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA;;;;;;;;;GASG;AACH,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAClE,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAC/D,OAAO,EAAE,4BAA4B,EAAE,MAAM,0BAA0B,CAAC;AAExE,mBAAmB,CAAC,eAAe,CAAC,CAAC;AAErC,4BAA4B,EAAE,CAAC;AAE/B,OAAO,CAAC,KAAK,GAAG,QAAQ,CAAC;AACzB,OAAO,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC,WAAW,EAAE,eAAe,CAAC,GAAG,MAAM,CAAC;AAC/D,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAG,eAAe,CAAC;AACvC,OAAO,CAAC,WAAW,GAAG,CAAC,GAAG,EAAE,GAAE,CAAC,CAA+B,CAAC;AAE/D,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AAEnC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,WAAW,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC;IACjD,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IACrB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACjB,CAAC;AAED,0EAA0E;AAC1E,mDAAmD;AACnD,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,2BAA2B,CAAC,EAAE,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,CAChF,CAAC,CAAC,EAAE,uBAAuB,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,EAAE;IAC3C,uBAAuB,EAAE,CAAC;IAC1B,IAAI,CAAC,IAAI,CAAC,CAAC;AACZ,CAAC,CACD,CAAC","sourcesContent":["#!/usr/bin/env node\n/**\n * CLI entry point for the refactored coding agent.\n * Uses main.ts with AgentSession and new mode modules.\n *\n * Test with:
|
|
1
|
+
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA;;;;;;;;;GASG;AACH,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAClE,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAC/D,OAAO,EAAE,4BAA4B,EAAE,MAAM,0BAA0B,CAAC;AAExE,mBAAmB,CAAC,eAAe,CAAC,CAAC;AAErC,4BAA4B,EAAE,CAAC;AAE/B,OAAO,CAAC,KAAK,GAAG,QAAQ,CAAC;AACzB,OAAO,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC,WAAW,EAAE,eAAe,CAAC,GAAG,MAAM,CAAC;AAC/D,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAG,eAAe,CAAC;AACvC,OAAO,CAAC,WAAW,GAAG,CAAC,GAAG,EAAE,GAAE,CAAC,CAA+B,CAAC;AAE/D,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AAEnC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,WAAW,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC;IACjD,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IACrB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACjB,CAAC;AAED,0EAA0E;AAC1E,mDAAmD;AACnD,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,2BAA2B,CAAC,EAAE,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,CAChF,CAAC,CAAC,EAAE,uBAAuB,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,EAAE;IAC3C,uBAAuB,EAAE,CAAC;IAC1B,IAAI,CAAC,IAAI,CAAC,CAAC;AACZ,CAAC,CACD,CAAC","sourcesContent":["#!/usr/bin/env node\n/**\n * CLI entry point for the refactored coding agent.\n * Uses main.ts with AgentSession and new mode modules.\n *\n * Test with: bun src/cli.ts [args...]\n *\n * Deliberately keeps the static entry graph to config, compile-cache support,\n * attribution, and the disabled-by-default lifecycle seam. The full CLI graph\n * loads dynamically so metadata fast paths (for example `--version`) skip it.\n */\nimport { APP_NAME, VERSION } from \"./config.js\";\nimport { markLifecycleTiming } from \"./core/lifecycle-timings.ts\";\nimport { ATOMIC_AI_AGENT } from \"./utils/agent-attribution.ts\";\nimport { enablePersistentCompileCache } from \"./utils/compile-cache.ts\";\n\nmarkLifecycleTiming(\"process-entry\");\n\nenablePersistentCompileCache();\n\nprocess.title = APP_NAME;\nprocess.env[`${APP_NAME.toUpperCase()}_CODING_AGENT`] = \"true\";\nprocess.env.AI_AGENT = ATOMIC_AI_AGENT;\nprocess.emitWarning = (() => {}) as typeof process.emitWarning;\n\nconst args = process.argv.slice(2);\n\nif (args[0] === \"--version\" || args[0] === \"-v\") {\n\tconsole.log(VERSION);\n\tprocess.exit(0);\n}\n\n// No top-level await: the compiled binary is built with --bytecode (CJS),\n// which forbids TLA anywhere in the bundled graph.\nvoid Promise.all([import(\"./core/http-dispatcher.ts\"), import(\"./main.ts\")]).then(\n\t([{ configureHttpDispatcher }, { main }]) => {\n\t\tconfigureHttpDispatcher();\n\t\tmain(args);\n\t},\n);\n"]}
|
package/dist/config.d.ts
CHANGED
|
@@ -16,21 +16,21 @@ export declare function getUpdateInstruction(packageName: string): string;
|
|
|
16
16
|
* Get the base directory for resolving package assets (themes, package.json, README.md, CHANGELOG.md).
|
|
17
17
|
* - For Bun binary: returns the directory containing the executable
|
|
18
18
|
* - For Node.js (dist/): returns __dirname (the dist/ directory)
|
|
19
|
-
* - For
|
|
19
|
+
* - For source (src/): returns parent directory (the package root)
|
|
20
20
|
*/
|
|
21
21
|
export declare function getPackageDir(): string;
|
|
22
22
|
/**
|
|
23
23
|
* Get path to built-in themes directory (shipped with package)
|
|
24
24
|
* - For Bun binary: theme/ next to executable
|
|
25
25
|
* - For Node.js (dist/): dist/modes/interactive/theme/
|
|
26
|
-
* - For
|
|
26
|
+
* - For source (src/): src/modes/interactive/theme/
|
|
27
27
|
*/
|
|
28
28
|
export declare function getThemesDir(): string;
|
|
29
29
|
/**
|
|
30
30
|
* Get path to HTML export template directory (shipped with package)
|
|
31
31
|
* - For Bun binary: export-html/ next to executable
|
|
32
32
|
* - For Node.js (dist/): dist/core/export-html/
|
|
33
|
-
* - For
|
|
33
|
+
* - For source (src/): src/core/export-html/
|
|
34
34
|
*/
|
|
35
35
|
export declare function getExportTemplateDir(): string;
|
|
36
36
|
/** Get path to package.json */
|
|
@@ -47,7 +47,7 @@ export declare function getChangelogPath(): string;
|
|
|
47
47
|
* Get path to built-in interactive assets directory.
|
|
48
48
|
* - For Bun binary: assets/ next to executable
|
|
49
49
|
* - For Node.js (dist/): dist/modes/interactive/assets/
|
|
50
|
-
* - For
|
|
50
|
+
* - For source (src/): src/modes/interactive/assets/
|
|
51
51
|
*/
|
|
52
52
|
export declare function getInteractiveAssetsDir(): string;
|
|
53
53
|
/** Get path to a bundled interactive asset */
|
package/dist/config.js
CHANGED
|
@@ -59,7 +59,7 @@ export function getUpdateInstruction(packageName) {
|
|
|
59
59
|
* Get the base directory for resolving package assets (themes, package.json, README.md, CHANGELOG.md).
|
|
60
60
|
* - For Bun binary: returns the directory containing the executable
|
|
61
61
|
* - For Node.js (dist/): returns __dirname (the dist/ directory)
|
|
62
|
-
* - For
|
|
62
|
+
* - For source (src/): returns parent directory (the package root)
|
|
63
63
|
*/
|
|
64
64
|
export function getPackageDir() {
|
|
65
65
|
// Allow override via environment variable (useful for Nix/Guix where store paths tokenize poorly).
|
|
@@ -95,7 +95,7 @@ function getModuleAssetRoot() {
|
|
|
95
95
|
* Get path to built-in themes directory (shipped with package)
|
|
96
96
|
* - For Bun binary: theme/ next to executable
|
|
97
97
|
* - For Node.js (dist/): dist/modes/interactive/theme/
|
|
98
|
-
* - For
|
|
98
|
+
* - For source (src/): src/modes/interactive/theme/
|
|
99
99
|
*/
|
|
100
100
|
export function getThemesDir() {
|
|
101
101
|
if (isBunBinary) {
|
|
@@ -107,7 +107,7 @@ export function getThemesDir() {
|
|
|
107
107
|
* Get path to HTML export template directory (shipped with package)
|
|
108
108
|
* - For Bun binary: export-html/ next to executable
|
|
109
109
|
* - For Node.js (dist/): dist/core/export-html/
|
|
110
|
-
* - For
|
|
110
|
+
* - For source (src/): src/core/export-html/
|
|
111
111
|
*/
|
|
112
112
|
export function getExportTemplateDir() {
|
|
113
113
|
if (isBunBinary) {
|
|
@@ -139,7 +139,7 @@ export function getChangelogPath() {
|
|
|
139
139
|
* Get path to built-in interactive assets directory.
|
|
140
140
|
* - For Bun binary: assets/ next to executable
|
|
141
141
|
* - For Node.js (dist/): dist/modes/interactive/assets/
|
|
142
|
-
* - For
|
|
142
|
+
* - For source (src/): src/modes/interactive/assets/
|
|
143
143
|
*/
|
|
144
144
|
export function getInteractiveAssetsDir() {
|
|
145
145
|
if (isBunBinary) {
|