apex-code 0.0.1-alpha.1 → 0.0.1-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 +24 -0
- package/README.md +66 -681
- package/dist/cli/args.d.ts +5 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +45 -6
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/auth-command.d.ts.map +1 -1
- package/dist/cli/auth-command.js +3 -3
- package/dist/cli/auth-command.js.map +1 -1
- package/dist/cli/cost-command.d.ts +19 -0
- package/dist/cli/cost-command.d.ts.map +1 -0
- package/dist/cli/cost-command.js +107 -0
- package/dist/cli/cost-command.js.map +1 -0
- package/dist/cli/startup-ui.d.ts +1 -1
- package/dist/cli/startup-ui.d.ts.map +1 -1
- package/dist/cli/startup-ui.js +1 -2
- package/dist/cli/startup-ui.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +45 -16
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +2 -2
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +14 -7
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +2 -0
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session-services.d.ts +9 -0
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +30 -4
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +46 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +137 -19
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +6 -6
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +1 -1
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/context/deferred-schemas.d.ts +92 -0
- package/dist/core/context/deferred-schemas.d.ts.map +1 -0
- package/dist/core/context/deferred-schemas.js +74 -0
- package/dist/core/context/deferred-schemas.js.map +1 -0
- package/dist/core/context/eviction.d.ts +47 -0
- package/dist/core/context/eviction.d.ts.map +1 -0
- package/dist/core/context/eviction.js +83 -0
- package/dist/core/context/eviction.js.map +1 -0
- package/dist/core/context/pipeline.d.ts +90 -0
- package/dist/core/context/pipeline.d.ts.map +1 -0
- package/dist/core/context/pipeline.js +109 -0
- package/dist/core/context/pipeline.js.map +1 -0
- package/dist/core/credential-failover.d.ts +30 -0
- package/dist/core/credential-failover.d.ts.map +1 -0
- package/dist/core/credential-failover.js +46 -0
- package/dist/core/credential-failover.js.map +1 -0
- package/dist/core/credential-pool.d.ts +60 -0
- package/dist/core/credential-pool.d.ts.map +1 -0
- package/dist/core/credential-pool.js +84 -0
- package/dist/core/credential-pool.js.map +1 -0
- package/dist/core/delegation/agents.d.ts +15 -0
- package/dist/core/delegation/agents.d.ts.map +1 -0
- package/dist/core/delegation/agents.js +55 -0
- package/dist/core/delegation/agents.js.map +1 -0
- package/dist/core/delegation/ceiling.d.ts +29 -0
- package/dist/core/delegation/ceiling.d.ts.map +1 -0
- package/dist/core/delegation/ceiling.js +34 -0
- package/dist/core/delegation/ceiling.js.map +1 -0
- package/dist/core/delegation/runtime.d.ts +94 -0
- package/dist/core/delegation/runtime.d.ts.map +1 -0
- package/dist/core/delegation/runtime.js +117 -0
- package/dist/core/delegation/runtime.js.map +1 -0
- package/dist/core/durable-state/daemon.d.ts +37 -0
- package/dist/core/durable-state/daemon.d.ts.map +1 -0
- package/dist/core/durable-state/daemon.js +62 -0
- package/dist/core/durable-state/daemon.js.map +1 -0
- package/dist/core/durable-state/provenance.d.ts +7 -0
- package/dist/core/durable-state/provenance.d.ts.map +1 -0
- package/dist/core/durable-state/provenance.js +24 -0
- package/dist/core/durable-state/provenance.js.map +1 -0
- package/dist/core/durable-state/sqlite.d.ts +84 -0
- package/dist/core/durable-state/sqlite.d.ts.map +1 -0
- package/dist/core/durable-state/sqlite.js +331 -0
- package/dist/core/durable-state/sqlite.js.map +1 -0
- package/dist/core/environment.d.ts +12 -0
- package/dist/core/environment.d.ts.map +1 -0
- package/dist/core/environment.js +69 -0
- package/dist/core/environment.js.map +1 -0
- package/dist/core/evidence-policy.d.ts +17 -0
- package/dist/core/evidence-policy.d.ts.map +1 -0
- package/dist/core/evidence-policy.js +25 -0
- package/dist/core/evidence-policy.js.map +1 -0
- package/dist/core/evidence.d.ts +16 -0
- package/dist/core/evidence.d.ts.map +1 -0
- package/dist/core/evidence.js +51 -0
- package/dist/core/evidence.js.map +1 -0
- package/dist/core/experimental.d.ts.map +1 -1
- package/dist/core/experimental.js +2 -1
- package/dist/core/experimental.js.map +1 -1
- package/dist/core/extensions/types.d.ts +2 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/index.d.ts +1 -0
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +1 -0
- package/dist/core/index.js.map +1 -1
- package/dist/core/model-config.d.ts +8 -0
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-config.js +21 -5
- package/dist/core/model-config.js.map +1 -1
- package/dist/core/model-resolver.d.ts +20 -0
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +59 -0
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-runtime.d.ts +73 -0
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +225 -8
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/observability/aggregate.d.ts +21 -0
- package/dist/core/observability/aggregate.d.ts.map +1 -0
- package/dist/core/observability/aggregate.js +36 -0
- package/dist/core/observability/aggregate.js.map +1 -0
- package/dist/core/observability/otlp.d.ts +66 -0
- package/dist/core/observability/otlp.d.ts.map +1 -0
- package/dist/core/observability/otlp.js +95 -0
- package/dist/core/observability/otlp.js.map +1 -0
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +3 -2
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/permissions/gate.d.ts +35 -0
- package/dist/core/permissions/gate.d.ts.map +1 -0
- package/dist/core/permissions/gate.js +72 -0
- package/dist/core/permissions/gate.js.map +1 -0
- package/dist/core/permissions/modes.d.ts +18 -0
- package/dist/core/permissions/modes.d.ts.map +1 -0
- package/dist/core/permissions/modes.js +57 -0
- package/dist/core/permissions/modes.js.map +1 -0
- package/dist/core/permissions/responder.d.ts +30 -0
- package/dist/core/permissions/responder.d.ts.map +1 -0
- package/dist/core/permissions/responder.js +32 -0
- package/dist/core/permissions/responder.js.map +1 -0
- package/dist/core/permissions/rules.d.ts +34 -0
- package/dist/core/permissions/rules.d.ts.map +1 -0
- package/dist/core/permissions/rules.js +74 -0
- package/dist/core/permissions/rules.js.map +1 -0
- package/dist/core/permissions/startup.d.ts +33 -0
- package/dist/core/permissions/startup.d.ts.map +1 -0
- package/dist/core/permissions/startup.js +55 -0
- package/dist/core/permissions/startup.js.map +1 -0
- package/dist/core/permissions/store.d.ts +114 -0
- package/dist/core/permissions/store.d.ts.map +1 -0
- package/dist/core/permissions/store.js +229 -0
- package/dist/core/permissions/store.js.map +1 -0
- package/dist/core/project-trust.d.ts.map +1 -1
- package/dist/core/project-trust.js +1 -1
- package/dist/core/project-trust.js.map +1 -1
- package/dist/core/provider-attribution.d.ts.map +1 -1
- package/dist/core/provider-attribution.js +6 -7
- package/dist/core/provider-attribution.js.map +1 -1
- package/dist/core/remote-catalog-provider.d.ts +2 -2
- package/dist/core/remote-catalog-provider.d.ts.map +1 -1
- package/dist/core/remote-catalog-provider.js +20 -16
- package/dist/core/remote-catalog-provider.js.map +1 -1
- package/dist/core/sandbox/child-entry.d.ts +2 -0
- package/dist/core/sandbox/child-entry.d.ts.map +1 -0
- package/dist/core/sandbox/child-entry.js +11 -0
- package/dist/core/sandbox/child-entry.js.map +1 -0
- package/dist/core/sandbox/cli-launch.d.ts +27 -0
- package/dist/core/sandbox/cli-launch.d.ts.map +1 -0
- package/dist/core/sandbox/cli-launch.js +133 -0
- package/dist/core/sandbox/cli-launch.js.map +1 -0
- package/dist/core/sandbox/cli-supervisor.d.ts +25 -0
- package/dist/core/sandbox/cli-supervisor.d.ts.map +1 -0
- package/dist/core/sandbox/cli-supervisor.js +57 -0
- package/dist/core/sandbox/cli-supervisor.js.map +1 -0
- package/dist/core/sandbox/linux-backend.d.ts +18 -0
- package/dist/core/sandbox/linux-backend.d.ts.map +1 -0
- package/dist/core/sandbox/linux-backend.js +186 -0
- package/dist/core/sandbox/linux-backend.js.map +1 -0
- package/dist/core/sandbox/macos-backend.d.ts +18 -0
- package/dist/core/sandbox/macos-backend.d.ts.map +1 -0
- package/dist/core/sandbox/macos-backend.js +195 -0
- package/dist/core/sandbox/macos-backend.js.map +1 -0
- package/dist/core/sandbox/network-proxy.d.ts +19 -0
- package/dist/core/sandbox/network-proxy.d.ts.map +1 -0
- package/dist/core/sandbox/network-proxy.js +79 -0
- package/dist/core/sandbox/network-proxy.js.map +1 -0
- package/dist/core/sandbox/policy.d.ts +32 -0
- package/dist/core/sandbox/policy.d.ts.map +1 -0
- package/dist/core/sandbox/policy.js +38 -0
- package/dist/core/sandbox/policy.js.map +1 -0
- package/dist/core/sandbox/supervisor.d.ts +31 -0
- package/dist/core/sandbox/supervisor.d.ts.map +1 -0
- package/dist/core/sandbox/supervisor.js +18 -0
- package/dist/core/sandbox/supervisor.js.map +1 -0
- package/dist/core/sandbox/violations.d.ts +23 -0
- package/dist/core/sandbox/violations.d.ts.map +1 -0
- package/dist/core/sandbox/violations.js +30 -0
- package/dist/core/sandbox/violations.js.map +1 -0
- package/dist/core/sdk.d.ts +20 -36
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +129 -2
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-manager.d.ts +41 -2
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +57 -0
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/session-share.d.ts +16 -0
- package/dist/core/session-share.d.ts.map +1 -0
- package/dist/core/session-share.js +22 -0
- package/dist/core/session-share.js.map +1 -0
- package/dist/core/settings-manager.d.ts +38 -9
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +39 -24
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +5 -5
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/timings.d.ts +1 -1
- package/dist/core/timings.d.ts.map +1 -1
- package/dist/core/timings.js +3 -2
- package/dist/core/timings.js.map +1 -1
- package/dist/core/tools/ask-user.d.ts +25 -0
- package/dist/core/tools/ask-user.d.ts.map +1 -0
- package/dist/core/tools/ask-user.js +49 -0
- package/dist/core/tools/ask-user.js.map +1 -0
- package/dist/core/tools/bash-command-segments.d.ts +22 -0
- package/dist/core/tools/bash-command-segments.d.ts.map +1 -0
- package/dist/core/tools/bash-command-segments.js +128 -0
- package/dist/core/tools/bash-command-segments.js.map +1 -0
- package/dist/core/tools/bash.d.ts +26 -3
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +105 -16
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/contract.d.ts +156 -0
- package/dist/core/tools/contract.d.ts.map +1 -0
- package/dist/core/tools/contract.js +48 -0
- package/dist/core/tools/contract.js.map +1 -0
- package/dist/core/tools/delegate.d.ts +38 -0
- package/dist/core/tools/delegate.d.ts.map +1 -0
- package/dist/core/tools/delegate.js +66 -0
- package/dist/core/tools/delegate.js.map +1 -0
- package/dist/core/tools/edit.d.ts +2 -2
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +24 -0
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/find.d.ts +2 -2
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +12 -0
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.d.ts +2 -2
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +12 -0
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/index.d.ts +29 -4
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +118 -2
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/ls.d.ts +2 -2
- package/dist/core/tools/ls.d.ts.map +1 -1
- package/dist/core/tools/ls.js +12 -0
- package/dist/core/tools/ls.js.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +1 -1
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/core/tools/path-permission.d.ts +18 -0
- package/dist/core/tools/path-permission.d.ts.map +1 -0
- package/dist/core/tools/path-permission.js +28 -0
- package/dist/core/tools/path-permission.js.map +1 -0
- package/dist/core/tools/plan-present.d.ts +27 -0
- package/dist/core/tools/plan-present.d.ts.map +1 -0
- package/dist/core/tools/plan-present.js +55 -0
- package/dist/core/tools/plan-present.js.map +1 -0
- package/dist/core/tools/read.d.ts +2 -2
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +12 -0
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/test.d.ts +34 -0
- package/dist/core/tools/test.d.ts.map +1 -0
- package/dist/core/tools/test.js +75 -0
- package/dist/core/tools/test.js.map +1 -0
- package/dist/core/tools/todo-write.d.ts +31 -0
- package/dist/core/tools/todo-write.d.ts.map +1 -0
- package/dist/core/tools/todo-write.js +51 -0
- package/dist/core/tools/todo-write.js.map +1 -0
- package/dist/core/tools/tool-definition-wrapper.d.ts +13 -2
- package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.js +11 -1
- package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
- package/dist/core/tools/tool-schema.d.ts +22 -0
- package/dist/core/tools/tool-schema.d.ts.map +1 -0
- package/dist/core/tools/tool-schema.js +45 -0
- package/dist/core/tools/tool-schema.js.map +1 -0
- package/dist/core/tools/web-fetch.d.ts +26 -0
- package/dist/core/tools/web-fetch.d.ts.map +1 -0
- package/dist/core/tools/web-fetch.js +62 -0
- package/dist/core/tools/web-fetch.js.map +1 -0
- package/dist/core/tools/web-search.d.ts +26 -0
- package/dist/core/tools/web-search.d.ts.map +1 -0
- package/dist/core/tools/web-search.js +53 -0
- package/dist/core/tools/web-search.js.map +1 -0
- package/dist/core/tools/write.d.ts +6 -2
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js +32 -1
- package/dist/core/tools/write.js.map +1 -1
- package/dist/core/usage-performance-store.d.ts +56 -0
- package/dist/core/usage-performance-store.d.ts.map +1 -0
- package/dist/core/usage-performance-store.js +85 -0
- package/dist/core/usage-performance-store.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +48 -6
- package/dist/main.js.map +1 -1
- package/dist/migrations.d.ts.map +1 -1
- package/dist/migrations.js +2 -2
- package/dist/migrations.js.map +1 -1
- package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/config-selector.js +9 -6
- package/dist/modes/interactive/components/config-selector.js.map +1 -1
- package/dist/modes/interactive/components/first-time-setup.d.ts +1 -4
- package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -1
- package/dist/modes/interactive/components/first-time-setup.js +11 -39
- package/dist/modes/interactive/components/first-time-setup.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts +8 -1
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +49 -20
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +2 -2
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +6 -6
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +2 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/external-editor.d.ts.map +1 -1
- package/dist/modes/interactive/external-editor.js +58 -9
- package/dist/modes/interactive/external-editor.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +2 -3
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +92 -104
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/theme/theme-schema.json +2 -2
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +15 -10
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/rpc-entry.d.ts.map +1 -1
- package/dist/rpc-entry.js +2 -1
- package/dist/rpc-entry.js.map +1 -1
- package/dist/server/create-harness.d.ts +1 -1
- package/dist/server/create-harness.d.ts.map +1 -1
- package/dist/server/create-harness.js +6 -5
- package/dist/server/create-harness.js.map +1 -1
- package/dist/testing/replay/metrics.d.ts +24 -0
- package/dist/testing/replay/metrics.d.ts.map +1 -0
- package/dist/testing/replay/metrics.js +35 -0
- package/dist/testing/replay/metrics.js.map +1 -0
- package/dist/testing/replay/recorded-provider.d.ts +10 -0
- package/dist/testing/replay/recorded-provider.d.ts.map +1 -0
- package/dist/testing/replay/recorded-provider.js +108 -0
- package/dist/testing/replay/recorded-provider.js.map +1 -0
- package/dist/testing/replay/runner.d.ts +56 -0
- package/dist/testing/replay/runner.d.ts.map +1 -0
- package/dist/testing/replay/runner.js +406 -0
- package/dist/testing/replay/runner.js.map +1 -0
- package/dist/utils/apex-code-user-agent.d.ts +2 -0
- package/dist/utils/apex-code-user-agent.d.ts.map +1 -0
- package/dist/utils/apex-code-user-agent.js +5 -0
- package/dist/utils/apex-code-user-agent.js.map +1 -0
- package/dist/utils/clipboard-image.d.ts.map +1 -1
- package/dist/utils/clipboard-image.js +1 -1
- package/dist/utils/clipboard-image.js.map +1 -1
- package/dist/utils/tools-manager.d.ts +32 -0
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +198 -100
- package/dist/utils/tools-manager.js.map +1 -1
- package/dist/utils/version-check.d.ts +5 -5
- package/dist/utils/version-check.d.ts.map +1 -1
- package/dist/utils/version-check.js +23 -14
- package/dist/utils/version-check.js.map +1 -1
- package/dist/utils/windows-self-update.d.ts.map +1 -1
- package/dist/utils/windows-self-update.js +1 -1
- package/dist/utils/windows-self-update.js.map +1 -1
- package/docs/compaction.md +21 -21
- package/docs/containerization.md +24 -21
- package/docs/custom-provider.md +9 -9
- package/docs/development.md +11 -11
- package/docs/environment-variables.md +36 -77
- package/docs/extensions.md +47 -47
- package/docs/index.md +12 -24
- package/docs/json.md +6 -6
- package/docs/keybindings.md +3 -3
- package/docs/llama-cpp.md +7 -7
- package/docs/models.md +11 -11
- package/docs/packages.md +46 -42
- package/docs/prompt-templates.md +3 -3
- package/docs/providers.md +10 -10
- package/docs/quickstart.md +49 -32
- package/docs/rpc.md +11 -11
- package/docs/sdk.md +4 -4
- package/docs/security.md +18 -18
- package/docs/session-format.md +9 -9
- package/docs/sessions.md +13 -13
- package/docs/settings.md +10 -14
- package/docs/shell-aliases.md +1 -1
- package/docs/skills.md +8 -8
- package/docs/terminal-setup.md +12 -12
- package/docs/termux.md +4 -4
- package/docs/themes.md +8 -8
- package/docs/tmux.md +4 -4
- package/docs/tui.md +3 -3
- package/docs/usage.md +54 -51
- package/docs/windows.md +1 -1
- package/npm-shrinkwrap.json +5 -5
- package/package.json +2 -3
- package/dist/core/telemetry.d.ts +0 -3
- package/dist/core/telemetry.d.ts.map +0 -1
- package/dist/core/telemetry.js +0 -9
- package/dist/core/telemetry.js.map +0 -1
- package/dist/utils/pi-user-agent.d.ts +0 -2
- package/dist/utils/pi-user-agent.d.ts.map +0 -1
- package/dist/utils/pi-user-agent.js +0 -5
- package/dist/utils/pi-user-agent.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth-storage.d.ts","sourceRoot":"","sources":["../../src/core/auth-storage.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,oBAAoB,EAAE,UAAU,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAU/G,KAAK,eAAe,GAAG,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;AAElD,KAAK,UAAU,CAAC,CAAC,IAAI;IACpB,MAAM,EAAE,CAAC,CAAC;IACV,IAAI,CAAC,EAAE,MAAM,CAAC;CACd,CAAC;AAkBF,MAAM,WAAW,kBAAkB;IAClC,QAAQ,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,KAAK,UAAU,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IACnE,aAAa,CAAC,CAAC,EACd,EAAE,EAAE,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,KAAK,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,EAC3D,OAAO,CAAC,EAAE,oBAAoB,GAC5B,OAAO,CAAC,CAAC,CAAC,CAAC;CACd;AAED,qBAAa,sBAAuB,YAAW,kBAAkB;IAChE,OAAO,CAAC,QAAQ,CAAS;IAEzB,YAAY,QAAQ,GAAE,MAAyC,EAE9D;IAED,OAAO,CAAC,eAAe;IAOvB,OAAO,CAAC,gBAAgB;IAOxB,OAAO,CAAC,wBAAwB;IA2BhC,QAAQ,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,KAAK,UAAU,CAAC,CAAC,CAAC,GAAG,CAAC,CAmBjE;YAEa,gBAAgB;IAyCxB,aAAa,CAAC,CAAC,EACpB,EAAE,E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sourcesContent":["/**\n * CredentialStore implementation backed by auth.json.\n * Provider auth orchestration belongs to ModelRuntime and pi-ai Models.\n */\n\nimport type { AuthOperationOptions, Credential, CredentialInfo, CredentialStore } from \"@earendil-works/pi-ai\";\nimport { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\";\nimport { dirname, join } from \"path\";\nimport lockfile from \"proper-lockfile\";\nimport { setTimeout as sleep } from \"timers/promises\";\nimport { getAgentDir } from \"../config.ts\";\nimport { raceWithAbortSignal } from \"../utils/abort.ts\";\nimport { getFileRevision, normalizePath } from \"../utils/paths.ts\";\nimport { isCommandConfigValue, resolveConfigValue } from \"./resolve-config-value.ts\";\n\ntype AuthStorageData = Record<string, Credential>;\n\ntype LockResult<T> = {\n\tresult: T;\n\tnext?: string;\n};\n\nconst AUTH_FILE_WRITE_OPTIONS = { encoding: \"utf-8\", mode: 0o600 } as const;\n\ntype AuthFileReload = {\n\tcontroller: AbortController;\n\tpromise: Promise<AuthStorageData>;\n\treaders: number;\n};\n\ntype AuthFileReadState = {\n\tdata: AuthStorageData;\n\trevision?: string;\n\treload?: AuthFileReload;\n};\n\nlet sharedAuthFileReadState: { authPath: string; readState: AuthFileReadState } | undefined;\n\nexport interface AuthStorageBackend {\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T;\n\twithLockAsync<T>(\n\t\tfn: (current: string | undefined) => Promise<LockResult<T>>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<T>;\n}\n\nexport class FileAuthStorageBackend implements AuthStorageBackend {\n\tprivate authPath: string;\n\n\tconstructor(authPath: string = join(getAgentDir(), \"auth.json\")) {\n\t\tthis.authPath = normalizePath(authPath);\n\t}\n\n\tprivate ensureParentDir(): void {\n\t\tconst dir = dirname(this.authPath);\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true, mode: 0o700 });\n\t\t}\n\t}\n\n\tprivate ensureFileExists(): void {\n\t\tif (!existsSync(this.authPath)) {\n\t\t\twriteFileSync(this.authPath, \"{}\", AUTH_FILE_WRITE_OPTIONS);\n\t\t\tchmodSync(this.authPath, 0o600);\n\t\t}\n\t}\n\n\tprivate acquireLockSyncWithRetry(path: string): () => void {\n\t\tconst maxAttempts = 10;\n\t\tconst delayMs = 20;\n\t\tlet lastError: unknown;\n\n\t\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn lockfile.lockSync(path, { realpath: false });\n\t\t\t} catch (error) {\n\t\t\t\tconst code =\n\t\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tlastError = error;\n\t\t\t\tconst start = Date.now();\n\t\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t\t// Sleep synchronously to avoid changing callers to async.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow (lastError as Error) ?? new Error(\"Failed to acquire auth storage lock\");\n\t}\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tthis.ensureParentDir();\n\t\tthis.ensureFileExists();\n\n\t\tlet release: (() => void) | undefined;\n\t\ttry {\n\t\t\trelease = this.acquireLockSyncWithRetry(this.authPath);\n\t\t\tconst current = existsSync(this.authPath) ? readFileSync(this.authPath, \"utf-8\") : undefined;\n\t\t\tconst { result, next } = fn(current);\n\t\t\tif (next !== undefined) {\n\t\t\t\twriteFileSync(this.authPath, next, AUTH_FILE_WRITE_OPTIONS);\n\t\t\t\tchmodSync(this.authPath, 0o600);\n\t\t\t}\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\trelease();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async acquireLockAsync(\n\t\tsignal: AbortSignal | undefined,\n\t\tonCompromised: (error: Error) => void,\n\t): Promise<() => Promise<void>> {\n\t\tconst staleMs = 30_000;\n\t\tconst maxDelayMs = 2_000;\n\t\tconst deadline = Date.now() + staleMs;\n\t\tlet retry = 0;\n\t\twhile (true) {\n\t\t\tsignal?.throwIfAborted();\n\t\t\tlet release: (() => Promise<void>) | undefined;\n\t\t\ttry {\n\t\t\t\trelease = await lockfile.lock(this.authPath, {\n\t\t\t\t\trealpath: false,\n\t\t\t\t\tretries: 0,\n\t\t\t\t\tstale: staleMs,\n\t\t\t\t\tonCompromised,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tsignal?.throwIfAborted();\n\t\t\t\tconst code =\n\t\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tconst remainingMs = deadline - Date.now();\n\t\t\t\tif (code !== \"ELOCKED\" || remainingMs <= 0) throw error;\n\t\t\t\tconst baseDelayMs = Math.min(10 * 2 ** retry, maxDelayMs / 2);\n\t\t\t\tretry++;\n\t\t\t\tconst delayMs = Math.min(Math.round(baseDelayMs * (1 + Math.random())), remainingMs);\n\t\t\t\tif (signal) await sleep(delayMs, undefined, { signal });\n\t\t\t\telse await sleep(delayMs);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (signal?.aborted) {\n\t\t\t\tawait release();\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t}\n\t\t\treturn release;\n\t\t}\n\t}\n\n\tasync withLockAsync<T>(\n\t\tfn: (current: string | undefined) => Promise<LockResult<T>>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<T> {\n\t\toptions?.signal?.throwIfAborted();\n\t\tthis.ensureParentDir();\n\t\tthis.ensureFileExists();\n\n\t\tlet release: (() => Promise<void>) | undefined;\n\t\tlet lockCompromised = false;\n\t\tlet lockCompromisedError: Error | undefined;\n\t\tconst throwIfCompromised = () => {\n\t\t\tif (lockCompromised) {\n\t\t\t\tthrow lockCompromisedError ?? new Error(\"Auth storage lock was compromised\");\n\t\t\t}\n\t\t};\n\n\t\ttry {\n\t\t\trelease = await this.acquireLockAsync(options?.signal, (error) => {\n\t\t\t\tlockCompromised = true;\n\t\t\t\tlockCompromisedError = error;\n\t\t\t});\n\n\t\t\tthrowIfCompromised();\n\t\t\toptions?.signal?.throwIfAborted();\n\t\t\tconst current = existsSync(this.authPath) ? readFileSync(this.authPath, \"utf-8\") : undefined;\n\t\t\tconst { result, next } = await fn(current);\n\t\t\tthrowIfCompromised();\n\t\t\toptions?.signal?.throwIfAborted();\n\t\t\tif (next !== undefined) {\n\t\t\t\twriteFileSync(this.authPath, next, AUTH_FILE_WRITE_OPTIONS);\n\t\t\t\tchmodSync(this.authPath, 0o600);\n\t\t\t}\n\t\t\tthrowIfCompromised();\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\ttry {\n\t\t\t\t\tawait release();\n\t\t\t\t} catch {\n\t\t\t\t\t// Ignore unlock errors when lock is compromised.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport class ReadOnlyAuthStorage implements CredentialStore {\n\tprivate readonly authPath: string;\n\tprivate data: AuthStorageData | undefined;\n\n\tconstructor(authPath: string = join(getAgentDir(), \"auth.json\")) {\n\t\tthis.authPath = normalizePath(authPath);\n\t}\n\n\tprivate load(): AuthStorageData {\n\t\tif (this.data) return this.data;\n\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(readFileSync(this.authPath, \"utf-8\"));\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n\t\t\t\tthis.data = {};\n\t\t\t\treturn this.data;\n\t\t\t}\n\t\t\tthrow new Error(`Failed to read auth.json: ${error instanceof Error ? error.message : String(error)}`);\n\t\t}\n\n\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n\t\t\tthrow new Error(\"Invalid auth.json: expected an object\");\n\t\t}\n\t\tfor (const [providerId, credential] of Object.entries(parsed)) {\n\t\t\tif (typeof credential !== \"object\" || credential === null || Array.isArray(credential)) {\n\t\t\t\tthrow new Error(`Invalid auth.json credential for provider \"${providerId}\"`);\n\t\t\t}\n\t\t\tconst value = credential as Record<string, unknown>;\n\t\t\tif (value.type === \"api_key\") {\n\t\t\t\tconst validKey = value.key === undefined || typeof value.key === \"string\";\n\t\t\t\tconst validEnv =\n\t\t\t\t\tvalue.env === undefined ||\n\t\t\t\t\t(typeof value.env === \"object\" &&\n\t\t\t\t\t\tvalue.env !== null &&\n\t\t\t\t\t\t!Array.isArray(value.env) &&\n\t\t\t\t\t\tObject.values(value.env).every((entry) => typeof entry === \"string\"));\n\t\t\t\tif (validKey && validEnv) continue;\n\t\t\t} else if (\n\t\t\t\tvalue.type === \"oauth\" &&\n\t\t\t\ttypeof value.access === \"string\" &&\n\t\t\t\ttypeof value.refresh === \"string\" &&\n\t\t\t\ttypeof value.expires === \"number\" &&\n\t\t\t\tNumber.isFinite(value.expires)\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow new Error(`Invalid auth.json credential for provider \"${providerId}\"`);\n\t\t}\n\n\t\tthis.data = parsed as AuthStorageData;\n\t\treturn this.data;\n\t}\n\n\tasync read(providerId: string, options?: AuthOperationOptions): Promise<Credential | undefined> {\n\t\toptions?.signal?.throwIfAborted();\n\t\tconst credential = this.load()[providerId];\n\t\toptions?.signal?.throwIfAborted();\n\t\tif (!credential) return undefined;\n\t\tif (credential.type !== \"api_key\" || !credential.key || isCommandConfigValue(credential.key)) {\n\t\t\treturn structuredClone(credential);\n\t\t}\n\t\treturn { ...credential, key: resolveConfigValue(credential.key, credential.env) };\n\t}\n\n\tasync list(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]> {\n\t\toptions?.signal?.throwIfAborted();\n\t\tconst credentials = Object.entries(this.load()).map(([providerId, credential]) => ({\n\t\t\tproviderId,\n\t\t\ttype: credential.type,\n\t\t}));\n\t\toptions?.signal?.throwIfAborted();\n\t\treturn credentials;\n\t}\n\n\tasync modify(\n\t\t_providerId: string,\n\t\t_fn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t\t_options?: AuthOperationOptions,\n\t): Promise<Credential | undefined> {\n\t\tthrow new Error(\"Read-only credential storage cannot modify auth.json\");\n\t}\n\n\tasync delete(_providerId: string, _options?: AuthOperationOptions): Promise<void> {\n\t\tthrow new Error(\"Read-only credential storage cannot modify auth.json\");\n\t}\n}\n\nexport class InMemoryAuthStorageBackend implements AuthStorageBackend {\n\tprivate value: string | undefined;\n\tprivate asyncChain: Promise<unknown> = Promise.resolve();\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tconst { result, next } = fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n\n\twithLockAsync<T>(\n\t\tfn: (current: string | undefined) => Promise<LockResult<T>>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<T> {\n\t\tconst previous = this.asyncChain;\n\t\tconst operation = (async () => {\n\t\t\tawait previous.catch(() => {});\n\t\t\toptions?.signal?.throwIfAborted();\n\t\t\tconst { result, next } = await fn(this.value);\n\t\t\toptions?.signal?.throwIfAborted();\n\t\t\tif (next !== undefined) {\n\t\t\t\tthis.value = next;\n\t\t\t}\n\t\t\treturn result;\n\t\t})();\n\t\tthis.asyncChain = operation.catch(() => {});\n\t\treturn raceWithAbortSignal(operation, options?.signal);\n\t}\n}\n\n/**\n * Credential storage backed by a JSON file.\n */\nexport class AuthStorage implements CredentialStore {\n\tprivate storage: AuthStorageBackend;\n\tprivate authPath: string | undefined;\n\tprivate readState: AuthFileReadState;\n\n\tprivate constructor(storage: AuthStorageBackend, authPath?: string) {\n\t\tthis.storage = storage;\n\t\tthis.authPath = authPath;\n\t\tthis.readState =\n\t\t\tauthPath && sharedAuthFileReadState?.authPath === authPath ? sharedAuthFileReadState.readState : { data: {} };\n\t\tif (authPath && !sharedAuthFileReadState) {\n\t\t\tsharedAuthFileReadState = { authPath, readState: this.readState };\n\t\t}\n\t\tif (authPath) {\n\t\t\tconst revision = getFileRevision(authPath);\n\t\t\tif (revision !== undefined && revision === this.readState.revision) return;\n\t\t}\n\t\tthis.reload();\n\t}\n\n\tstatic create(authPath: string = join(getAgentDir(), \"auth.json\")): AuthStorage {\n\t\tconst normalizedAuthPath = normalizePath(authPath);\n\t\treturn new AuthStorage(new FileAuthStorageBackend(normalizedAuthPath), normalizedAuthPath);\n\t}\n\n\tstatic fromStorage(storage: AuthStorageBackend): AuthStorage {\n\t\treturn new AuthStorage(storage);\n\t}\n\n\tstatic inMemory(data: AuthStorageData = {}): AuthStorage {\n\t\tconst storage = new InMemoryAuthStorageBackend();\n\t\tstorage.withLock(() => ({ result: undefined, next: JSON.stringify(data, null, 2) }));\n\t\treturn AuthStorage.fromStorage(storage);\n\t}\n\n\tprivate parseStorageData(content: string | undefined): AuthStorageData {\n\t\tif (!content) {\n\t\t\treturn {};\n\t\t}\n\t\treturn JSON.parse(content) as AuthStorageData;\n\t}\n\n\tprivate updateReadState(data: AuthStorageData, revision?: string): void {\n\t\tthis.readState.data = data;\n\t\tthis.readState.revision = revision;\n\t}\n\n\t/**\n\t * Reload credentials from storage.\n\t */\n\treload(): void {\n\t\tlet content: string | undefined;\n\t\tlet revision: string | undefined;\n\t\ttry {\n\t\t\tthis.storage.withLock((current) => {\n\t\t\t\tcontent = current;\n\t\t\t\trevision = this.authPath ? getFileRevision(this.authPath) : undefined;\n\t\t\t\treturn { result: undefined };\n\t\t\t});\n\t\t\tthis.updateReadState(this.parseStorageData(content), revision);\n\t\t} catch {\n\t\t\t// Preserve the last valid in-memory snapshot.\n\t\t}\n\t}\n\n\tprivate async reloadFromStorageAsync(options?: AuthOperationOptions): Promise<AuthStorageData> {\n\t\treturn this.storage.withLockAsync(async (content) => {\n\t\t\tconst currentData = this.parseStorageData(content);\n\t\t\tconst revision = this.authPath ? getFileRevision(this.authPath) : undefined;\n\t\t\tthis.updateReadState(currentData, revision);\n\t\t\treturn { result: currentData };\n\t\t}, options);\n\t}\n\n\tprivate async readLatestData(options?: AuthOperationOptions): Promise<AuthStorageData> {\n\t\toptions?.signal?.throwIfAborted();\n\t\tif (!this.authPath) {\n\t\t\tconst reload = this.reloadFromStorageAsync(options);\n\t\t\treturn options?.signal ? reload : reload.catch(() => this.readState.data);\n\t\t}\n\t\tconst revision = getFileRevision(this.authPath);\n\t\tif (revision !== undefined && revision === this.readState.revision) return this.readState.data;\n\t\tif (!this.readState.reload) {\n\t\t\tconst controller = new AbortController();\n\t\t\tconst reload: AuthFileReload = {\n\t\t\t\tcontroller,\n\t\t\t\tpromise: this.reloadFromStorageAsync({ signal: controller.signal }),\n\t\t\t\treaders: 0,\n\t\t\t};\n\t\t\tthis.readState.reload = reload;\n\t\t\tvoid reload.promise.then(\n\t\t\t\t() => {\n\t\t\t\t\tif (this.readState.reload === reload) this.readState.reload = undefined;\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tif (this.readState.reload === reload) this.readState.reload = undefined;\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\n\t\tconst reload = this.readState.reload;\n\t\treload.readers++;\n\t\ttry {\n\t\t\tconst result = raceWithAbortSignal(reload.promise, options?.signal);\n\t\t\treturn options?.signal ? await result : await result.catch(() => this.readState.data);\n\t\t} finally {\n\t\t\treload.readers--;\n\t\t\tif (reload.readers === 0 && this.readState.reload === reload) {\n\t\t\t\tthis.readState.reload = undefined;\n\t\t\t\treload.controller.abort();\n\t\t\t}\n\t\t}\n\t}\n\n\tasync read(provider: string, options?: AuthOperationOptions): Promise<Credential | undefined> {\n\t\tconst credential = (await this.readLatestData(options))[provider];\n\t\toptions?.signal?.throwIfAborted();\n\t\tif (credential?.type !== \"api_key\") return credential;\n\t\tif (credential.key === undefined) return credential;\n\t\treturn { ...credential, key: resolveConfigValue(credential.key, credential.env) };\n\t}\n\n\tasync modify(\n\t\tprovider: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<Credential | undefined> {\n\t\tlet latestData = this.readState.data;\n\t\tlet revision: string | undefined;\n\t\tconst result = await this.storage.withLockAsync(async (content) => {\n\t\t\tconst currentData = this.parseStorageData(content);\n\t\t\tconst next = await fn(currentData[provider]);\n\t\t\tif (next === undefined) {\n\t\t\t\tlatestData = currentData;\n\t\t\t\trevision = this.authPath ? getFileRevision(this.authPath) : undefined;\n\t\t\t\treturn { result: currentData[provider] };\n\t\t\t}\n\n\t\t\tconst merged: AuthStorageData = { ...currentData, [provider]: next };\n\t\t\tlatestData = merged;\n\t\t\treturn { result: next, next: JSON.stringify(merged, null, 2) };\n\t\t}, options);\n\t\tthis.updateReadState(latestData, revision);\n\t\treturn result;\n\t}\n\n\tasync delete(provider: string, options?: AuthOperationOptions): Promise<void> {\n\t\tlet latestData = this.readState.data;\n\t\tawait this.storage.withLockAsync(async (content) => {\n\t\t\tconst currentData = this.parseStorageData(content);\n\t\t\tdelete currentData[provider];\n\t\t\tlatestData = currentData;\n\t\t\treturn { result: undefined, next: JSON.stringify(currentData, null, 2) };\n\t\t}, options);\n\t\tthis.updateReadState(latestData);\n\t}\n\n\t/** List credential metadata without resolving configured key values. */\n\tasync list(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]> {\n\t\tconst entries = Object.entries(await this.readLatestData(options));\n\t\toptions?.signal?.throwIfAborted();\n\t\treturn entries.map(([providerId, credential]) => ({ providerId, type: credential.type }));\n\t}\n}\n\n/**\n * One-off synchronous read of a stored credential from an auth.json file,\n * without instantiating a store or resolving configured key values.\n */\nexport function readStoredCredential(\n\tproviderId: string,\n\tauthPath: string = join(getAgentDir(), \"auth.json\"),\n): Credential | undefined {\n\ttry {\n\t\tconst data = JSON.parse(readFileSync(normalizePath(authPath), \"utf-8\")) as AuthStorageData;\n\t\treturn data[providerId];\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"auth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,OAAO,CAAC,QAAQ,CAAqB;IACrC,OAAO,CAAC,SAAS,CAAoB;IAErC,OAAO,eAaN;IAED,MAAM,CAAC,MAAM,CAAC,QAAQ,GAAE,MAAsB,GAAG,WAAW,CAG3D;IAED,MAAM,CAAC,WAAW,CAAC,OAAO,EAAE,kBAAkB,GAAG,WAAW,CAE3D;IAED,MAAM,CAAC,QAAQ,CAAC,IAAI,GAAE,eAAoB,GAAG,WAAW,CAIvD;IAED,OAAO,CAAC,gBAAgB;IAOxB,OAAO,CAAC,eAAe;IAKvB;;OAEG;IACH,MAAM,IAAI,IAAI,CAab;YAEa,sBAAsB;YAStB,cAAc;IAwCtB,IAAI,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,oBAAoB,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAM5F;IAEK,MAAM,CACX,QAAQ,EAAE,MAAM,EAChB,EAAE,EAAE,CAAC,OAAO,EAAE,UAAU,GAAG,SAAS,KAAK,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,EACxE,OAAO,CAAC,EAAE,oBAAoB,GAC5B,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAkBjC;IAEK,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,oBAAoB,GAAG,OAAO,CAAC,IAAI,CAAC,CAS5E;IAED,wEAAwE;IAClE,IAAI,CAAC,OAAO,CAAC,EAAE,oBAAoB,GAAG,OAAO,CAAC,SAAS,cAAc,EAAE,CAAC,CAI7E;CACD;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,GAAE,MAAsB,GAAG,UAAU,GAAG,SAAS,CAOjH","sourcesContent":["/**\n * CredentialStore implementation backed by auth.json.\n * Provider auth orchestration belongs to ModelRuntime and pi-ai Models.\n */\n\nimport type { AuthOperationOptions, Credential, CredentialInfo, CredentialStore } from \"@earendil-works/pi-ai\";\nimport { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\";\nimport { dirname } from \"path\";\nimport lockfile from \"proper-lockfile\";\nimport { setTimeout as sleep } from \"timers/promises\";\nimport { getAuthPath } from \"../config.ts\";\nimport { raceWithAbortSignal } from \"../utils/abort.ts\";\nimport { getFileRevision, normalizePath } from \"../utils/paths.ts\";\nimport { isCommandConfigValue, resolveConfigValue } from \"./resolve-config-value.ts\";\n\ntype AuthStorageData = Record<string, Credential>;\n\ntype LockResult<T> = {\n\tresult: T;\n\tnext?: string;\n};\n\nconst AUTH_FILE_WRITE_OPTIONS = { encoding: \"utf-8\", mode: 0o600 } as const;\n\ntype AuthFileReload = {\n\tcontroller: AbortController;\n\tpromise: Promise<AuthStorageData>;\n\treaders: number;\n};\n\ntype AuthFileReadState = {\n\tdata: AuthStorageData;\n\trevision?: string;\n\treload?: AuthFileReload;\n};\n\nlet sharedAuthFileReadState: { authPath: string; readState: AuthFileReadState } | undefined;\n\nexport interface AuthStorageBackend {\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T;\n\twithLockAsync<T>(\n\t\tfn: (current: string | undefined) => Promise<LockResult<T>>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<T>;\n}\n\nexport class FileAuthStorageBackend implements AuthStorageBackend {\n\tprivate authPath: string;\n\n\tconstructor(authPath: string = getAuthPath()) {\n\t\tthis.authPath = normalizePath(authPath);\n\t}\n\n\tprivate ensureParentDir(): void {\n\t\tconst dir = dirname(this.authPath);\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true, mode: 0o700 });\n\t\t}\n\t}\n\n\tprivate ensureFileExists(): void {\n\t\tif (!existsSync(this.authPath)) {\n\t\t\twriteFileSync(this.authPath, \"{}\", AUTH_FILE_WRITE_OPTIONS);\n\t\t\tchmodSync(this.authPath, 0o600);\n\t\t}\n\t}\n\n\tprivate acquireLockSyncWithRetry(path: string): () => void {\n\t\tconst maxAttempts = 10;\n\t\tconst delayMs = 20;\n\t\tlet lastError: unknown;\n\n\t\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn lockfile.lockSync(path, { realpath: false });\n\t\t\t} catch (error) {\n\t\t\t\tconst code =\n\t\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tlastError = error;\n\t\t\t\tconst start = Date.now();\n\t\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t\t// Sleep synchronously to avoid changing callers to async.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow (lastError as Error) ?? new Error(\"Failed to acquire auth storage lock\");\n\t}\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tthis.ensureParentDir();\n\t\tthis.ensureFileExists();\n\n\t\tlet release: (() => void) | undefined;\n\t\ttry {\n\t\t\trelease = this.acquireLockSyncWithRetry(this.authPath);\n\t\t\tconst current = existsSync(this.authPath) ? readFileSync(this.authPath, \"utf-8\") : undefined;\n\t\t\tconst { result, next } = fn(current);\n\t\t\tif (next !== undefined) {\n\t\t\t\twriteFileSync(this.authPath, next, AUTH_FILE_WRITE_OPTIONS);\n\t\t\t\tchmodSync(this.authPath, 0o600);\n\t\t\t}\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\trelease();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async acquireLockAsync(\n\t\tsignal: AbortSignal | undefined,\n\t\tonCompromised: (error: Error) => void,\n\t): Promise<() => Promise<void>> {\n\t\tconst staleMs = 30_000;\n\t\tconst maxDelayMs = 2_000;\n\t\tconst deadline = Date.now() + staleMs;\n\t\tlet retry = 0;\n\t\twhile (true) {\n\t\t\tsignal?.throwIfAborted();\n\t\t\tlet release: (() => Promise<void>) | undefined;\n\t\t\ttry {\n\t\t\t\trelease = await lockfile.lock(this.authPath, {\n\t\t\t\t\trealpath: false,\n\t\t\t\t\tretries: 0,\n\t\t\t\t\tstale: staleMs,\n\t\t\t\t\tonCompromised,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tsignal?.throwIfAborted();\n\t\t\t\tconst code =\n\t\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tconst remainingMs = deadline - Date.now();\n\t\t\t\tif (code !== \"ELOCKED\" || remainingMs <= 0) throw error;\n\t\t\t\tconst baseDelayMs = Math.min(10 * 2 ** retry, maxDelayMs / 2);\n\t\t\t\tretry++;\n\t\t\t\tconst delayMs = Math.min(Math.round(baseDelayMs * (1 + Math.random())), remainingMs);\n\t\t\t\tif (signal) await sleep(delayMs, undefined, { signal });\n\t\t\t\telse await sleep(delayMs);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (signal?.aborted) {\n\t\t\t\tawait release();\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t}\n\t\t\treturn release;\n\t\t}\n\t}\n\n\tasync withLockAsync<T>(\n\t\tfn: (current: string | undefined) => Promise<LockResult<T>>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<T> {\n\t\toptions?.signal?.throwIfAborted();\n\t\tthis.ensureParentDir();\n\t\tthis.ensureFileExists();\n\n\t\tlet release: (() => Promise<void>) | undefined;\n\t\tlet lockCompromised = false;\n\t\tlet lockCompromisedError: Error | undefined;\n\t\tconst throwIfCompromised = () => {\n\t\t\tif (lockCompromised) {\n\t\t\t\tthrow lockCompromisedError ?? new Error(\"Auth storage lock was compromised\");\n\t\t\t}\n\t\t};\n\n\t\ttry {\n\t\t\trelease = await this.acquireLockAsync(options?.signal, (error) => {\n\t\t\t\tlockCompromised = true;\n\t\t\t\tlockCompromisedError = error;\n\t\t\t});\n\n\t\t\tthrowIfCompromised();\n\t\t\toptions?.signal?.throwIfAborted();\n\t\t\tconst current = existsSync(this.authPath) ? readFileSync(this.authPath, \"utf-8\") : undefined;\n\t\t\tconst { result, next } = await fn(current);\n\t\t\tthrowIfCompromised();\n\t\t\toptions?.signal?.throwIfAborted();\n\t\t\tif (next !== undefined) {\n\t\t\t\twriteFileSync(this.authPath, next, AUTH_FILE_WRITE_OPTIONS);\n\t\t\t\tchmodSync(this.authPath, 0o600);\n\t\t\t}\n\t\t\tthrowIfCompromised();\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\ttry {\n\t\t\t\t\tawait release();\n\t\t\t\t} catch {\n\t\t\t\t\t// Ignore unlock errors when lock is compromised.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport class ReadOnlyAuthStorage implements CredentialStore {\n\tprivate readonly authPath: string;\n\tprivate data: AuthStorageData | undefined;\n\n\tconstructor(authPath: string = getAuthPath()) {\n\t\tthis.authPath = normalizePath(authPath);\n\t}\n\n\tprivate load(): AuthStorageData {\n\t\tif (this.data) return this.data;\n\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(readFileSync(this.authPath, \"utf-8\"));\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n\t\t\t\tthis.data = {};\n\t\t\t\treturn this.data;\n\t\t\t}\n\t\t\tthrow new Error(`Failed to read auth.json: ${error instanceof Error ? error.message : String(error)}`);\n\t\t}\n\n\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n\t\t\tthrow new Error(\"Invalid auth.json: expected an object\");\n\t\t}\n\t\tfor (const [providerId, credential] of Object.entries(parsed)) {\n\t\t\tif (typeof credential !== \"object\" || credential === null || Array.isArray(credential)) {\n\t\t\t\tthrow new Error(`Invalid auth.json credential for provider \"${providerId}\"`);\n\t\t\t}\n\t\t\tconst value = credential as Record<string, unknown>;\n\t\t\tif (value.type === \"api_key\") {\n\t\t\t\tconst validKey = value.key === undefined || typeof value.key === \"string\";\n\t\t\t\tconst validEnv =\n\t\t\t\t\tvalue.env === undefined ||\n\t\t\t\t\t(typeof value.env === \"object\" &&\n\t\t\t\t\t\tvalue.env !== null &&\n\t\t\t\t\t\t!Array.isArray(value.env) &&\n\t\t\t\t\t\tObject.values(value.env).every((entry) => typeof entry === \"string\"));\n\t\t\t\tif (validKey && validEnv) continue;\n\t\t\t} else if (\n\t\t\t\tvalue.type === \"oauth\" &&\n\t\t\t\ttypeof value.access === \"string\" &&\n\t\t\t\ttypeof value.refresh === \"string\" &&\n\t\t\t\ttypeof value.expires === \"number\" &&\n\t\t\t\tNumber.isFinite(value.expires)\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow new Error(`Invalid auth.json credential for provider \"${providerId}\"`);\n\t\t}\n\n\t\tthis.data = parsed as AuthStorageData;\n\t\treturn this.data;\n\t}\n\n\tasync read(providerId: string, options?: AuthOperationOptions): Promise<Credential | undefined> {\n\t\toptions?.signal?.throwIfAborted();\n\t\tconst credential = this.load()[providerId];\n\t\toptions?.signal?.throwIfAborted();\n\t\tif (!credential) return undefined;\n\t\tif (credential.type !== \"api_key\" || !credential.key || isCommandConfigValue(credential.key)) {\n\t\t\treturn structuredClone(credential);\n\t\t}\n\t\treturn { ...credential, key: resolveConfigValue(credential.key, credential.env) };\n\t}\n\n\tasync list(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]> {\n\t\toptions?.signal?.throwIfAborted();\n\t\tconst credentials = Object.entries(this.load()).map(([providerId, credential]) => ({\n\t\t\tproviderId,\n\t\t\ttype: credential.type,\n\t\t}));\n\t\toptions?.signal?.throwIfAborted();\n\t\treturn credentials;\n\t}\n\n\tasync modify(\n\t\t_providerId: string,\n\t\t_fn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t\t_options?: AuthOperationOptions,\n\t): Promise<Credential | undefined> {\n\t\tthrow new Error(\"Read-only credential storage cannot modify auth.json\");\n\t}\n\n\tasync delete(_providerId: string, _options?: AuthOperationOptions): Promise<void> {\n\t\tthrow new Error(\"Read-only credential storage cannot modify auth.json\");\n\t}\n}\n\nexport class InMemoryAuthStorageBackend implements AuthStorageBackend {\n\tprivate value: string | undefined;\n\tprivate asyncChain: Promise<unknown> = Promise.resolve();\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tconst { result, next } = fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n\n\twithLockAsync<T>(\n\t\tfn: (current: string | undefined) => Promise<LockResult<T>>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<T> {\n\t\tconst previous = this.asyncChain;\n\t\tconst operation = (async () => {\n\t\t\tawait previous.catch(() => {});\n\t\t\toptions?.signal?.throwIfAborted();\n\t\t\tconst { result, next } = await fn(this.value);\n\t\t\toptions?.signal?.throwIfAborted();\n\t\t\tif (next !== undefined) {\n\t\t\t\tthis.value = next;\n\t\t\t}\n\t\t\treturn result;\n\t\t})();\n\t\tthis.asyncChain = operation.catch(() => {});\n\t\treturn raceWithAbortSignal(operation, options?.signal);\n\t}\n}\n\n/**\n * Credential storage backed by a JSON file.\n */\nexport class AuthStorage implements CredentialStore {\n\tprivate storage: AuthStorageBackend;\n\tprivate authPath: string | undefined;\n\tprivate readState: AuthFileReadState;\n\n\tprivate constructor(storage: AuthStorageBackend, authPath?: string) {\n\t\tthis.storage = storage;\n\t\tthis.authPath = authPath;\n\t\tthis.readState =\n\t\t\tauthPath && sharedAuthFileReadState?.authPath === authPath ? sharedAuthFileReadState.readState : { data: {} };\n\t\tif (authPath && !sharedAuthFileReadState) {\n\t\t\tsharedAuthFileReadState = { authPath, readState: this.readState };\n\t\t}\n\t\tif (authPath) {\n\t\t\tconst revision = getFileRevision(authPath);\n\t\t\tif (revision !== undefined && revision === this.readState.revision) return;\n\t\t}\n\t\tthis.reload();\n\t}\n\n\tstatic create(authPath: string = getAuthPath()): AuthStorage {\n\t\tconst normalizedAuthPath = normalizePath(authPath);\n\t\treturn new AuthStorage(new FileAuthStorageBackend(normalizedAuthPath), normalizedAuthPath);\n\t}\n\n\tstatic fromStorage(storage: AuthStorageBackend): AuthStorage {\n\t\treturn new AuthStorage(storage);\n\t}\n\n\tstatic inMemory(data: AuthStorageData = {}): AuthStorage {\n\t\tconst storage = new InMemoryAuthStorageBackend();\n\t\tstorage.withLock(() => ({ result: undefined, next: JSON.stringify(data, null, 2) }));\n\t\treturn AuthStorage.fromStorage(storage);\n\t}\n\n\tprivate parseStorageData(content: string | undefined): AuthStorageData {\n\t\tif (!content) {\n\t\t\treturn {};\n\t\t}\n\t\treturn JSON.parse(content) as AuthStorageData;\n\t}\n\n\tprivate updateReadState(data: AuthStorageData, revision?: string): void {\n\t\tthis.readState.data = data;\n\t\tthis.readState.revision = revision;\n\t}\n\n\t/**\n\t * Reload credentials from storage.\n\t */\n\treload(): void {\n\t\tlet content: string | undefined;\n\t\tlet revision: string | undefined;\n\t\ttry {\n\t\t\tthis.storage.withLock((current) => {\n\t\t\t\tcontent = current;\n\t\t\t\trevision = this.authPath ? getFileRevision(this.authPath) : undefined;\n\t\t\t\treturn { result: undefined };\n\t\t\t});\n\t\t\tthis.updateReadState(this.parseStorageData(content), revision);\n\t\t} catch {\n\t\t\t// Preserve the last valid in-memory snapshot.\n\t\t}\n\t}\n\n\tprivate async reloadFromStorageAsync(options?: AuthOperationOptions): Promise<AuthStorageData> {\n\t\treturn this.storage.withLockAsync(async (content) => {\n\t\t\tconst currentData = this.parseStorageData(content);\n\t\t\tconst revision = this.authPath ? getFileRevision(this.authPath) : undefined;\n\t\t\tthis.updateReadState(currentData, revision);\n\t\t\treturn { result: currentData };\n\t\t}, options);\n\t}\n\n\tprivate async readLatestData(options?: AuthOperationOptions): Promise<AuthStorageData> {\n\t\toptions?.signal?.throwIfAborted();\n\t\tif (!this.authPath) {\n\t\t\tconst reload = this.reloadFromStorageAsync(options);\n\t\t\treturn options?.signal ? reload : reload.catch(() => this.readState.data);\n\t\t}\n\t\tconst revision = getFileRevision(this.authPath);\n\t\tif (revision !== undefined && revision === this.readState.revision) return this.readState.data;\n\t\tif (!this.readState.reload) {\n\t\t\tconst controller = new AbortController();\n\t\t\tconst reload: AuthFileReload = {\n\t\t\t\tcontroller,\n\t\t\t\tpromise: this.reloadFromStorageAsync({ signal: controller.signal }),\n\t\t\t\treaders: 0,\n\t\t\t};\n\t\t\tthis.readState.reload = reload;\n\t\t\tvoid reload.promise.then(\n\t\t\t\t() => {\n\t\t\t\t\tif (this.readState.reload === reload) this.readState.reload = undefined;\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tif (this.readState.reload === reload) this.readState.reload = undefined;\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\n\t\tconst reload = this.readState.reload;\n\t\treload.readers++;\n\t\ttry {\n\t\t\tconst result = raceWithAbortSignal(reload.promise, options?.signal);\n\t\t\treturn options?.signal ? await result : await result.catch(() => this.readState.data);\n\t\t} finally {\n\t\t\treload.readers--;\n\t\t\tif (reload.readers === 0 && this.readState.reload === reload) {\n\t\t\t\tthis.readState.reload = undefined;\n\t\t\t\treload.controller.abort();\n\t\t\t}\n\t\t}\n\t}\n\n\tasync read(provider: string, options?: AuthOperationOptions): Promise<Credential | undefined> {\n\t\tconst credential = (await this.readLatestData(options))[provider];\n\t\toptions?.signal?.throwIfAborted();\n\t\tif (credential?.type !== \"api_key\") return credential;\n\t\tif (credential.key === undefined) return credential;\n\t\treturn { ...credential, key: resolveConfigValue(credential.key, credential.env) };\n\t}\n\n\tasync modify(\n\t\tprovider: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<Credential | undefined> {\n\t\tlet latestData = this.readState.data;\n\t\tlet revision: string | undefined;\n\t\tconst result = await this.storage.withLockAsync(async (content) => {\n\t\t\tconst currentData = this.parseStorageData(content);\n\t\t\tconst next = await fn(currentData[provider]);\n\t\t\tif (next === undefined) {\n\t\t\t\tlatestData = currentData;\n\t\t\t\trevision = this.authPath ? getFileRevision(this.authPath) : undefined;\n\t\t\t\treturn { result: currentData[provider] };\n\t\t\t}\n\n\t\t\tconst merged: AuthStorageData = { ...currentData, [provider]: next };\n\t\t\tlatestData = merged;\n\t\t\treturn { result: next, next: JSON.stringify(merged, null, 2) };\n\t\t}, options);\n\t\tthis.updateReadState(latestData, revision);\n\t\treturn result;\n\t}\n\n\tasync delete(provider: string, options?: AuthOperationOptions): Promise<void> {\n\t\tlet latestData = this.readState.data;\n\t\tawait this.storage.withLockAsync(async (content) => {\n\t\t\tconst currentData = this.parseStorageData(content);\n\t\t\tdelete currentData[provider];\n\t\t\tlatestData = currentData;\n\t\t\treturn { result: undefined, next: JSON.stringify(currentData, null, 2) };\n\t\t}, options);\n\t\tthis.updateReadState(latestData);\n\t}\n\n\t/** List credential metadata without resolving configured key values. */\n\tasync list(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]> {\n\t\tconst entries = Object.entries(await this.readLatestData(options));\n\t\toptions?.signal?.throwIfAborted();\n\t\treturn entries.map(([providerId, credential]) => ({ providerId, type: credential.type }));\n\t}\n}\n\n/**\n * One-off synchronous read of a stored credential from an auth.json file,\n * without instantiating a store or resolving configured key values.\n */\nexport function readStoredCredential(providerId: string, authPath: string = getAuthPath()): Credential | undefined {\n\ttry {\n\t\tconst data = JSON.parse(readFileSync(normalizePath(authPath), \"utf-8\")) as AuthStorageData;\n\t\treturn data[providerId];\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n"]}
|
|
@@ -3,10 +3,10 @@
|
|
|
3
3
|
* Provider auth orchestration belongs to ModelRuntime and pi-ai Models.
|
|
4
4
|
*/
|
|
5
5
|
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
6
|
-
import { dirname
|
|
6
|
+
import { dirname } from "path";
|
|
7
7
|
import lockfile from "proper-lockfile";
|
|
8
8
|
import { setTimeout as sleep } from "timers/promises";
|
|
9
|
-
import {
|
|
9
|
+
import { getAuthPath } from "../config.js";
|
|
10
10
|
import { raceWithAbortSignal } from "../utils/abort.js";
|
|
11
11
|
import { getFileRevision, normalizePath } from "../utils/paths.js";
|
|
12
12
|
import { isCommandConfigValue, resolveConfigValue } from "./resolve-config-value.js";
|
|
@@ -14,7 +14,7 @@ const AUTH_FILE_WRITE_OPTIONS = { encoding: "utf-8", mode: 0o600 };
|
|
|
14
14
|
let sharedAuthFileReadState;
|
|
15
15
|
export class FileAuthStorageBackend {
|
|
16
16
|
authPath;
|
|
17
|
-
constructor(authPath =
|
|
17
|
+
constructor(authPath = getAuthPath()) {
|
|
18
18
|
this.authPath = normalizePath(authPath);
|
|
19
19
|
}
|
|
20
20
|
ensureParentDir() {
|
|
@@ -158,7 +158,7 @@ export class FileAuthStorageBackend {
|
|
|
158
158
|
export class ReadOnlyAuthStorage {
|
|
159
159
|
authPath;
|
|
160
160
|
data;
|
|
161
|
-
constructor(authPath =
|
|
161
|
+
constructor(authPath = getAuthPath()) {
|
|
162
162
|
this.authPath = normalizePath(authPath);
|
|
163
163
|
}
|
|
164
164
|
load() {
|
|
@@ -280,7 +280,7 @@ export class AuthStorage {
|
|
|
280
280
|
}
|
|
281
281
|
this.reload();
|
|
282
282
|
}
|
|
283
|
-
static create(authPath =
|
|
283
|
+
static create(authPath = getAuthPath()) {
|
|
284
284
|
const normalizedAuthPath = normalizePath(authPath);
|
|
285
285
|
return new AuthStorage(new FileAuthStorageBackend(normalizedAuthPath), normalizedAuthPath);
|
|
286
286
|
}
|
|
@@ -415,7 +415,7 @@ export class AuthStorage {
|
|
|
415
415
|
* One-off synchronous read of a stored credential from an auth.json file,
|
|
416
416
|
* without instantiating a store or resolving configured key values.
|
|
417
417
|
*/
|
|
418
|
-
export function readStoredCredential(providerId, authPath =
|
|
418
|
+
export function readStoredCredential(providerId, authPath = getAuthPath()) {
|
|
419
419
|
try {
|
|
420
420
|
const data = JSON.parse(readFileSync(normalizePath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YAAY,CAAC,aAAa,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,CAAoB,CAAC;QAC3F,OAAO,IAAI,CAAC,UAAU,CAAC,CAAC;IACzB,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,SAAS,CAAC;IAClB,CAAC;AAAA,CACD","sourcesContent":["/**\n * CredentialStore implementation backed by auth.json.\n * Provider auth orchestration belongs to ModelRuntime and pi-ai Models.\n */\n\nimport type { AuthOperationOptions, Credential, CredentialInfo, CredentialStore } from \"@earendil-works/pi-ai\";\nimport { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\";\nimport { dirname, join } from \"path\";\nimport lockfile from \"proper-lockfile\";\nimport { setTimeout as sleep } from \"timers/promises\";\nimport { getAgentDir } from \"../config.ts\";\nimport { raceWithAbortSignal } from \"../utils/abort.ts\";\nimport { getFileRevision, normalizePath } from \"../utils/paths.ts\";\nimport { isCommandConfigValue, resolveConfigValue } from \"./resolve-config-value.ts\";\n\ntype AuthStorageData = Record<string, Credential>;\n\ntype LockResult<T> = {\n\tresult: T;\n\tnext?: string;\n};\n\nconst AUTH_FILE_WRITE_OPTIONS = { encoding: \"utf-8\", mode: 0o600 } as const;\n\ntype AuthFileReload = {\n\tcontroller: AbortController;\n\tpromise: Promise<AuthStorageData>;\n\treaders: number;\n};\n\ntype AuthFileReadState = {\n\tdata: AuthStorageData;\n\trevision?: string;\n\treload?: AuthFileReload;\n};\n\nlet sharedAuthFileReadState: { authPath: string; readState: AuthFileReadState } | undefined;\n\nexport interface AuthStorageBackend {\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T;\n\twithLockAsync<T>(\n\t\tfn: (current: string | undefined) => Promise<LockResult<T>>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<T>;\n}\n\nexport class FileAuthStorageBackend implements AuthStorageBackend {\n\tprivate authPath: string;\n\n\tconstructor(authPath: string = join(getAgentDir(), \"auth.json\")) {\n\t\tthis.authPath = normalizePath(authPath);\n\t}\n\n\tprivate ensureParentDir(): void {\n\t\tconst dir = dirname(this.authPath);\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true, mode: 0o700 });\n\t\t}\n\t}\n\n\tprivate ensureFileExists(): void {\n\t\tif (!existsSync(this.authPath)) {\n\t\t\twriteFileSync(this.authPath, \"{}\", AUTH_FILE_WRITE_OPTIONS);\n\t\t\tchmodSync(this.authPath, 0o600);\n\t\t}\n\t}\n\n\tprivate acquireLockSyncWithRetry(path: string): () => void {\n\t\tconst maxAttempts = 10;\n\t\tconst delayMs = 20;\n\t\tlet lastError: unknown;\n\n\t\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn lockfile.lockSync(path, { realpath: false });\n\t\t\t} catch (error) {\n\t\t\t\tconst code =\n\t\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tlastError = error;\n\t\t\t\tconst start = Date.now();\n\t\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t\t// Sleep synchronously to avoid changing callers to async.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow (lastError as Error) ?? new Error(\"Failed to acquire auth storage lock\");\n\t}\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tthis.ensureParentDir();\n\t\tthis.ensureFileExists();\n\n\t\tlet release: (() => void) | undefined;\n\t\ttry {\n\t\t\trelease = this.acquireLockSyncWithRetry(this.authPath);\n\t\t\tconst current = existsSync(this.authPath) ? readFileSync(this.authPath, \"utf-8\") : undefined;\n\t\t\tconst { result, next } = fn(current);\n\t\t\tif (next !== undefined) {\n\t\t\t\twriteFileSync(this.authPath, next, AUTH_FILE_WRITE_OPTIONS);\n\t\t\t\tchmodSync(this.authPath, 0o600);\n\t\t\t}\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\trelease();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async acquireLockAsync(\n\t\tsignal: AbortSignal | undefined,\n\t\tonCompromised: (error: Error) => void,\n\t): Promise<() => Promise<void>> {\n\t\tconst staleMs = 30_000;\n\t\tconst maxDelayMs = 2_000;\n\t\tconst deadline = Date.now() + staleMs;\n\t\tlet retry = 0;\n\t\twhile (true) {\n\t\t\tsignal?.throwIfAborted();\n\t\t\tlet release: (() => Promise<void>) | undefined;\n\t\t\ttry {\n\t\t\t\trelease = await lockfile.lock(this.authPath, {\n\t\t\t\t\trealpath: false,\n\t\t\t\t\tretries: 0,\n\t\t\t\t\tstale: staleMs,\n\t\t\t\t\tonCompromised,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tsignal?.throwIfAborted();\n\t\t\t\tconst code =\n\t\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tconst remainingMs = deadline - Date.now();\n\t\t\t\tif (code !== \"ELOCKED\" || remainingMs <= 0) throw error;\n\t\t\t\tconst baseDelayMs = Math.min(10 * 2 ** retry, maxDelayMs / 2);\n\t\t\t\tretry++;\n\t\t\t\tconst delayMs = Math.min(Math.round(baseDelayMs * (1 + Math.random())), remainingMs);\n\t\t\t\tif (signal) await sleep(delayMs, undefined, { signal });\n\t\t\t\telse await sleep(delayMs);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (signal?.aborted) {\n\t\t\t\tawait release();\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t}\n\t\t\treturn release;\n\t\t}\n\t}\n\n\tasync withLockAsync<T>(\n\t\tfn: (current: string | undefined) => Promise<LockResult<T>>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<T> {\n\t\toptions?.signal?.throwIfAborted();\n\t\tthis.ensureParentDir();\n\t\tthis.ensureFileExists();\n\n\t\tlet release: (() => Promise<void>) | undefined;\n\t\tlet lockCompromised = false;\n\t\tlet lockCompromisedError: Error | undefined;\n\t\tconst throwIfCompromised = () => {\n\t\t\tif (lockCompromised) {\n\t\t\t\tthrow lockCompromisedError ?? new Error(\"Auth storage lock was compromised\");\n\t\t\t}\n\t\t};\n\n\t\ttry {\n\t\t\trelease = await this.acquireLockAsync(options?.signal, (error) => {\n\t\t\t\tlockCompromised = true;\n\t\t\t\tlockCompromisedError = error;\n\t\t\t});\n\n\t\t\tthrowIfCompromised();\n\t\t\toptions?.signal?.throwIfAborted();\n\t\t\tconst current = existsSync(this.authPath) ? readFileSync(this.authPath, \"utf-8\") : undefined;\n\t\t\tconst { result, next } = await fn(current);\n\t\t\tthrowIfCompromised();\n\t\t\toptions?.signal?.throwIfAborted();\n\t\t\tif (next !== undefined) {\n\t\t\t\twriteFileSync(this.authPath, next, AUTH_FILE_WRITE_OPTIONS);\n\t\t\t\tchmodSync(this.authPath, 0o600);\n\t\t\t}\n\t\t\tthrowIfCompromised();\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\ttry {\n\t\t\t\t\tawait release();\n\t\t\t\t} catch {\n\t\t\t\t\t// Ignore unlock errors when lock is compromised.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport class ReadOnlyAuthStorage implements CredentialStore {\n\tprivate readonly authPath: string;\n\tprivate data: AuthStorageData | undefined;\n\n\tconstructor(authPath: string = join(getAgentDir(), \"auth.json\")) {\n\t\tthis.authPath = normalizePath(authPath);\n\t}\n\n\tprivate load(): AuthStorageData {\n\t\tif (this.data) return this.data;\n\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(readFileSync(this.authPath, \"utf-8\"));\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n\t\t\t\tthis.data = {};\n\t\t\t\treturn this.data;\n\t\t\t}\n\t\t\tthrow new Error(`Failed to read auth.json: ${error instanceof Error ? error.message : String(error)}`);\n\t\t}\n\n\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n\t\t\tthrow new Error(\"Invalid auth.json: expected an object\");\n\t\t}\n\t\tfor (const [providerId, credential] of Object.entries(parsed)) {\n\t\t\tif (typeof credential !== \"object\" || credential === null || Array.isArray(credential)) {\n\t\t\t\tthrow new Error(`Invalid auth.json credential for provider \"${providerId}\"`);\n\t\t\t}\n\t\t\tconst value = credential as Record<string, unknown>;\n\t\t\tif (value.type === \"api_key\") {\n\t\t\t\tconst validKey = value.key === undefined || typeof value.key === \"string\";\n\t\t\t\tconst validEnv =\n\t\t\t\t\tvalue.env === undefined ||\n\t\t\t\t\t(typeof value.env === \"object\" &&\n\t\t\t\t\t\tvalue.env !== null &&\n\t\t\t\t\t\t!Array.isArray(value.env) &&\n\t\t\t\t\t\tObject.values(value.env).every((entry) => typeof entry === \"string\"));\n\t\t\t\tif (validKey && validEnv) continue;\n\t\t\t} else if (\n\t\t\t\tvalue.type === \"oauth\" &&\n\t\t\t\ttypeof value.access === \"string\" &&\n\t\t\t\ttypeof value.refresh === \"string\" &&\n\t\t\t\ttypeof value.expires === \"number\" &&\n\t\t\t\tNumber.isFinite(value.expires)\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow new Error(`Invalid auth.json credential for provider \"${providerId}\"`);\n\t\t}\n\n\t\tthis.data = parsed as AuthStorageData;\n\t\treturn this.data;\n\t}\n\n\tasync read(providerId: string, options?: AuthOperationOptions): Promise<Credential | undefined> {\n\t\toptions?.signal?.throwIfAborted();\n\t\tconst credential = this.load()[providerId];\n\t\toptions?.signal?.throwIfAborted();\n\t\tif (!credential) return undefined;\n\t\tif (credential.type !== \"api_key\" || !credential.key || isCommandConfigValue(credential.key)) {\n\t\t\treturn structuredClone(credential);\n\t\t}\n\t\treturn { ...credential, key: resolveConfigValue(credential.key, credential.env) };\n\t}\n\n\tasync list(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]> {\n\t\toptions?.signal?.throwIfAborted();\n\t\tconst credentials = Object.entries(this.load()).map(([providerId, credential]) => ({\n\t\t\tproviderId,\n\t\t\ttype: credential.type,\n\t\t}));\n\t\toptions?.signal?.throwIfAborted();\n\t\treturn credentials;\n\t}\n\n\tasync modify(\n\t\t_providerId: string,\n\t\t_fn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t\t_options?: AuthOperationOptions,\n\t): Promise<Credential | undefined> {\n\t\tthrow new Error(\"Read-only credential storage cannot modify auth.json\");\n\t}\n\n\tasync delete(_providerId: string, _options?: AuthOperationOptions): Promise<void> {\n\t\tthrow new Error(\"Read-only credential storage cannot modify auth.json\");\n\t}\n}\n\nexport class InMemoryAuthStorageBackend implements AuthStorageBackend {\n\tprivate value: string | undefined;\n\tprivate asyncChain: Promise<unknown> = Promise.resolve();\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tconst { result, next } = fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n\n\twithLockAsync<T>(\n\t\tfn: (current: string | undefined) => Promise<LockResult<T>>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<T> {\n\t\tconst previous = this.asyncChain;\n\t\tconst operation = (async () => {\n\t\t\tawait previous.catch(() => {});\n\t\t\toptions?.signal?.throwIfAborted();\n\t\t\tconst { result, next } = await fn(this.value);\n\t\t\toptions?.signal?.throwIfAborted();\n\t\t\tif (next !== undefined) {\n\t\t\t\tthis.value = next;\n\t\t\t}\n\t\t\treturn result;\n\t\t})();\n\t\tthis.asyncChain = operation.catch(() => {});\n\t\treturn raceWithAbortSignal(operation, options?.signal);\n\t}\n}\n\n/**\n * Credential storage backed by a JSON file.\n */\nexport class AuthStorage implements CredentialStore {\n\tprivate storage: AuthStorageBackend;\n\tprivate authPath: string | undefined;\n\tprivate readState: AuthFileReadState;\n\n\tprivate constructor(storage: AuthStorageBackend, authPath?: string) {\n\t\tthis.storage = storage;\n\t\tthis.authPath = authPath;\n\t\tthis.readState =\n\t\t\tauthPath && sharedAuthFileReadState?.authPath === authPath ? sharedAuthFileReadState.readState : { data: {} };\n\t\tif (authPath && !sharedAuthFileReadState) {\n\t\t\tsharedAuthFileReadState = { authPath, readState: this.readState };\n\t\t}\n\t\tif (authPath) {\n\t\t\tconst revision = getFileRevision(authPath);\n\t\t\tif (revision !== undefined && revision === this.readState.revision) return;\n\t\t}\n\t\tthis.reload();\n\t}\n\n\tstatic create(authPath: string = join(getAgentDir(), \"auth.json\")): AuthStorage {\n\t\tconst normalizedAuthPath = normalizePath(authPath);\n\t\treturn new AuthStorage(new FileAuthStorageBackend(normalizedAuthPath), normalizedAuthPath);\n\t}\n\n\tstatic fromStorage(storage: AuthStorageBackend): AuthStorage {\n\t\treturn new AuthStorage(storage);\n\t}\n\n\tstatic inMemory(data: AuthStorageData = {}): AuthStorage {\n\t\tconst storage = new InMemoryAuthStorageBackend();\n\t\tstorage.withLock(() => ({ result: undefined, next: JSON.stringify(data, null, 2) }));\n\t\treturn AuthStorage.fromStorage(storage);\n\t}\n\n\tprivate parseStorageData(content: string | undefined): AuthStorageData {\n\t\tif (!content) {\n\t\t\treturn {};\n\t\t}\n\t\treturn JSON.parse(content) as AuthStorageData;\n\t}\n\n\tprivate updateReadState(data: AuthStorageData, revision?: string): void {\n\t\tthis.readState.data = data;\n\t\tthis.readState.revision = revision;\n\t}\n\n\t/**\n\t * Reload credentials from storage.\n\t */\n\treload(): void {\n\t\tlet content: string | undefined;\n\t\tlet revision: string | undefined;\n\t\ttry {\n\t\t\tthis.storage.withLock((current) => {\n\t\t\t\tcontent = current;\n\t\t\t\trevision = this.authPath ? getFileRevision(this.authPath) : undefined;\n\t\t\t\treturn { result: undefined };\n\t\t\t});\n\t\t\tthis.updateReadState(this.parseStorageData(content), revision);\n\t\t} catch {\n\t\t\t// Preserve the last valid in-memory snapshot.\n\t\t}\n\t}\n\n\tprivate async reloadFromStorageAsync(options?: AuthOperationOptions): Promise<AuthStorageData> {\n\t\treturn this.storage.withLockAsync(async (content) => {\n\t\t\tconst currentData = this.parseStorageData(content);\n\t\t\tconst revision = this.authPath ? getFileRevision(this.authPath) : undefined;\n\t\t\tthis.updateReadState(currentData, revision);\n\t\t\treturn { result: currentData };\n\t\t}, options);\n\t}\n\n\tprivate async readLatestData(options?: AuthOperationOptions): Promise<AuthStorageData> {\n\t\toptions?.signal?.throwIfAborted();\n\t\tif (!this.authPath) {\n\t\t\tconst reload = this.reloadFromStorageAsync(options);\n\t\t\treturn options?.signal ? reload : reload.catch(() => this.readState.data);\n\t\t}\n\t\tconst revision = getFileRevision(this.authPath);\n\t\tif (revision !== undefined && revision === this.readState.revision) return this.readState.data;\n\t\tif (!this.readState.reload) {\n\t\t\tconst controller = new AbortController();\n\t\t\tconst reload: AuthFileReload = {\n\t\t\t\tcontroller,\n\t\t\t\tpromise: this.reloadFromStorageAsync({ signal: controller.signal }),\n\t\t\t\treaders: 0,\n\t\t\t};\n\t\t\tthis.readState.reload = reload;\n\t\t\tvoid reload.promise.then(\n\t\t\t\t() => {\n\t\t\t\t\tif (this.readState.reload === reload) this.readState.reload = undefined;\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tif (this.readState.reload === reload) this.readState.reload = undefined;\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\n\t\tconst reload = this.readState.reload;\n\t\treload.readers++;\n\t\ttry {\n\t\t\tconst result = raceWithAbortSignal(reload.promise, options?.signal);\n\t\t\treturn options?.signal ? await result : await result.catch(() => this.readState.data);\n\t\t} finally {\n\t\t\treload.readers--;\n\t\t\tif (reload.readers === 0 && this.readState.reload === reload) {\n\t\t\t\tthis.readState.reload = undefined;\n\t\t\t\treload.controller.abort();\n\t\t\t}\n\t\t}\n\t}\n\n\tasync read(provider: string, options?: AuthOperationOptions): Promise<Credential | undefined> {\n\t\tconst credential = (await this.readLatestData(options))[provider];\n\t\toptions?.signal?.throwIfAborted();\n\t\tif (credential?.type !== \"api_key\") return credential;\n\t\tif (credential.key === undefined) return credential;\n\t\treturn { ...credential, key: resolveConfigValue(credential.key, credential.env) };\n\t}\n\n\tasync modify(\n\t\tprovider: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<Credential | undefined> {\n\t\tlet latestData = this.readState.data;\n\t\tlet revision: string | undefined;\n\t\tconst result = await this.storage.withLockAsync(async (content) => {\n\t\t\tconst currentData = this.parseStorageData(content);\n\t\t\tconst next = await fn(currentData[provider]);\n\t\t\tif (next === undefined) {\n\t\t\t\tlatestData = currentData;\n\t\t\t\trevision = this.authPath ? getFileRevision(this.authPath) : undefined;\n\t\t\t\treturn { result: currentData[provider] };\n\t\t\t}\n\n\t\t\tconst merged: AuthStorageData = { ...currentData, [provider]: next };\n\t\t\tlatestData = merged;\n\t\t\treturn { result: next, next: JSON.stringify(merged, null, 2) };\n\t\t}, options);\n\t\tthis.updateReadState(latestData, revision);\n\t\treturn result;\n\t}\n\n\tasync delete(provider: string, options?: AuthOperationOptions): Promise<void> {\n\t\tlet latestData = this.readState.data;\n\t\tawait this.storage.withLockAsync(async (content) => {\n\t\t\tconst currentData = this.parseStorageData(content);\n\t\t\tdelete currentData[provider];\n\t\t\tlatestData = currentData;\n\t\t\treturn { result: undefined, next: JSON.stringify(currentData, null, 2) };\n\t\t}, options);\n\t\tthis.updateReadState(latestData);\n\t}\n\n\t/** List credential metadata without resolving configured key values. */\n\tasync list(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]> {\n\t\tconst entries = Object.entries(await this.readLatestData(options));\n\t\toptions?.signal?.throwIfAborted();\n\t\treturn entries.map(([providerId, credential]) => ({ providerId, type: credential.type }));\n\t}\n}\n\n/**\n * One-off synchronous read of a stored credential from an auth.json file,\n * without instantiating a store or resolving configured key values.\n */\nexport function readStoredCredential(\n\tproviderId: string,\n\tauthPath: string = join(getAgentDir(), \"auth.json\"),\n): Credential | undefined {\n\ttry {\n\t\tconst data = JSON.parse(readFileSync(normalizePath(authPath), \"utf-8\")) as AuthStorageData;\n\t\treturn data[providerId];\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"auth-storage.js","sourceRoot":"","sources":["../../src/core/auth-storage.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,IAAI,CAAC;AACnF,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC/B,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AACvC,OAAO,EAAE,UAAU,IAAI,KAAK,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AACnE,OAAO,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AASrF,MAAM,uBAAuB,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAW,CAAC;AAc5E,IAAI,uBAAuF,CAAC;AAU5F,MAAM,OAAO,sBAAsB;IAC1B,QAAQ,CAAS;IAEzB,YAAY,QAAQ,GAAW,WAAW,EAAE,EAAE;QAC7C,IAAI,CAAC,QAAQ,GAAG,aAAa,CAAC,QAAQ,CAAC,CAAC;IAAA,CACxC;IAEO,eAAe,GAAS;QAC/B,MAAM,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACnC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;YACtB,SAAS,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAA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AQ,CAAC,EAAE,OAAO,CAAC,CAAoB,CAAC;QAC3F,OAAO,IAAI,CAAC,UAAU,CAAC,CAAC;IACzB,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,SAAS,CAAC;IAClB,CAAC;AAAA,CACD","sourcesContent":["/**\n * CredentialStore implementation backed by auth.json.\n * Provider auth orchestration belongs to ModelRuntime and pi-ai Models.\n */\n\nimport type { AuthOperationOptions, Credential, CredentialInfo, CredentialStore } from \"@earendil-works/pi-ai\";\nimport { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\";\nimport { dirname } from \"path\";\nimport lockfile from \"proper-lockfile\";\nimport { setTimeout as sleep } from \"timers/promises\";\nimport { getAuthPath } from \"../config.ts\";\nimport { raceWithAbortSignal } from \"../utils/abort.ts\";\nimport { getFileRevision, normalizePath } from \"../utils/paths.ts\";\nimport { isCommandConfigValue, resolveConfigValue } from \"./resolve-config-value.ts\";\n\ntype AuthStorageData = Record<string, Credential>;\n\ntype LockResult<T> = {\n\tresult: T;\n\tnext?: string;\n};\n\nconst AUTH_FILE_WRITE_OPTIONS = { encoding: \"utf-8\", mode: 0o600 } as const;\n\ntype AuthFileReload = {\n\tcontroller: AbortController;\n\tpromise: Promise<AuthStorageData>;\n\treaders: number;\n};\n\ntype AuthFileReadState = {\n\tdata: AuthStorageData;\n\trevision?: string;\n\treload?: AuthFileReload;\n};\n\nlet sharedAuthFileReadState: { authPath: string; readState: AuthFileReadState } | undefined;\n\nexport interface AuthStorageBackend {\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T;\n\twithLockAsync<T>(\n\t\tfn: (current: string | undefined) => Promise<LockResult<T>>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<T>;\n}\n\nexport class FileAuthStorageBackend implements AuthStorageBackend {\n\tprivate authPath: string;\n\n\tconstructor(authPath: string = getAuthPath()) {\n\t\tthis.authPath = normalizePath(authPath);\n\t}\n\n\tprivate ensureParentDir(): void {\n\t\tconst dir = dirname(this.authPath);\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true, mode: 0o700 });\n\t\t}\n\t}\n\n\tprivate ensureFileExists(): void {\n\t\tif (!existsSync(this.authPath)) {\n\t\t\twriteFileSync(this.authPath, \"{}\", AUTH_FILE_WRITE_OPTIONS);\n\t\t\tchmodSync(this.authPath, 0o600);\n\t\t}\n\t}\n\n\tprivate acquireLockSyncWithRetry(path: string): () => void {\n\t\tconst maxAttempts = 10;\n\t\tconst delayMs = 20;\n\t\tlet lastError: unknown;\n\n\t\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn lockfile.lockSync(path, { realpath: false });\n\t\t\t} catch (error) {\n\t\t\t\tconst code =\n\t\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tlastError = error;\n\t\t\t\tconst start = Date.now();\n\t\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t\t// Sleep synchronously to avoid changing callers to async.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow (lastError as Error) ?? new Error(\"Failed to acquire auth storage lock\");\n\t}\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tthis.ensureParentDir();\n\t\tthis.ensureFileExists();\n\n\t\tlet release: (() => void) | undefined;\n\t\ttry {\n\t\t\trelease = this.acquireLockSyncWithRetry(this.authPath);\n\t\t\tconst current = existsSync(this.authPath) ? readFileSync(this.authPath, \"utf-8\") : undefined;\n\t\t\tconst { result, next } = fn(current);\n\t\t\tif (next !== undefined) {\n\t\t\t\twriteFileSync(this.authPath, next, AUTH_FILE_WRITE_OPTIONS);\n\t\t\t\tchmodSync(this.authPath, 0o600);\n\t\t\t}\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\trelease();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async acquireLockAsync(\n\t\tsignal: AbortSignal | undefined,\n\t\tonCompromised: (error: Error) => void,\n\t): Promise<() => Promise<void>> {\n\t\tconst staleMs = 30_000;\n\t\tconst maxDelayMs = 2_000;\n\t\tconst deadline = Date.now() + staleMs;\n\t\tlet retry = 0;\n\t\twhile (true) {\n\t\t\tsignal?.throwIfAborted();\n\t\t\tlet release: (() => Promise<void>) | undefined;\n\t\t\ttry {\n\t\t\t\trelease = await lockfile.lock(this.authPath, {\n\t\t\t\t\trealpath: false,\n\t\t\t\t\tretries: 0,\n\t\t\t\t\tstale: staleMs,\n\t\t\t\t\tonCompromised,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tsignal?.throwIfAborted();\n\t\t\t\tconst code =\n\t\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tconst remainingMs = deadline - Date.now();\n\t\t\t\tif (code !== \"ELOCKED\" || remainingMs <= 0) throw error;\n\t\t\t\tconst baseDelayMs = Math.min(10 * 2 ** retry, maxDelayMs / 2);\n\t\t\t\tretry++;\n\t\t\t\tconst delayMs = Math.min(Math.round(baseDelayMs * (1 + Math.random())), remainingMs);\n\t\t\t\tif (signal) await sleep(delayMs, undefined, { signal });\n\t\t\t\telse await sleep(delayMs);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (signal?.aborted) {\n\t\t\t\tawait release();\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t}\n\t\t\treturn release;\n\t\t}\n\t}\n\n\tasync withLockAsync<T>(\n\t\tfn: (current: string | undefined) => Promise<LockResult<T>>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<T> {\n\t\toptions?.signal?.throwIfAborted();\n\t\tthis.ensureParentDir();\n\t\tthis.ensureFileExists();\n\n\t\tlet release: (() => Promise<void>) | undefined;\n\t\tlet lockCompromised = false;\n\t\tlet lockCompromisedError: Error | undefined;\n\t\tconst throwIfCompromised = () => {\n\t\t\tif (lockCompromised) {\n\t\t\t\tthrow lockCompromisedError ?? new Error(\"Auth storage lock was compromised\");\n\t\t\t}\n\t\t};\n\n\t\ttry {\n\t\t\trelease = await this.acquireLockAsync(options?.signal, (error) => {\n\t\t\t\tlockCompromised = true;\n\t\t\t\tlockCompromisedError = error;\n\t\t\t});\n\n\t\t\tthrowIfCompromised();\n\t\t\toptions?.signal?.throwIfAborted();\n\t\t\tconst current = existsSync(this.authPath) ? readFileSync(this.authPath, \"utf-8\") : undefined;\n\t\t\tconst { result, next } = await fn(current);\n\t\t\tthrowIfCompromised();\n\t\t\toptions?.signal?.throwIfAborted();\n\t\t\tif (next !== undefined) {\n\t\t\t\twriteFileSync(this.authPath, next, AUTH_FILE_WRITE_OPTIONS);\n\t\t\t\tchmodSync(this.authPath, 0o600);\n\t\t\t}\n\t\t\tthrowIfCompromised();\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\ttry {\n\t\t\t\t\tawait release();\n\t\t\t\t} catch {\n\t\t\t\t\t// Ignore unlock errors when lock is compromised.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport class ReadOnlyAuthStorage implements CredentialStore {\n\tprivate readonly authPath: string;\n\tprivate data: AuthStorageData | undefined;\n\n\tconstructor(authPath: string = getAuthPath()) {\n\t\tthis.authPath = normalizePath(authPath);\n\t}\n\n\tprivate load(): AuthStorageData {\n\t\tif (this.data) return this.data;\n\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(readFileSync(this.authPath, \"utf-8\"));\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n\t\t\t\tthis.data = {};\n\t\t\t\treturn this.data;\n\t\t\t}\n\t\t\tthrow new Error(`Failed to read auth.json: ${error instanceof Error ? error.message : String(error)}`);\n\t\t}\n\n\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n\t\t\tthrow new Error(\"Invalid auth.json: expected an object\");\n\t\t}\n\t\tfor (const [providerId, credential] of Object.entries(parsed)) {\n\t\t\tif (typeof credential !== \"object\" || credential === null || Array.isArray(credential)) {\n\t\t\t\tthrow new Error(`Invalid auth.json credential for provider \"${providerId}\"`);\n\t\t\t}\n\t\t\tconst value = credential as Record<string, unknown>;\n\t\t\tif (value.type === \"api_key\") {\n\t\t\t\tconst validKey = value.key === undefined || typeof value.key === \"string\";\n\t\t\t\tconst validEnv =\n\t\t\t\t\tvalue.env === undefined ||\n\t\t\t\t\t(typeof value.env === \"object\" &&\n\t\t\t\t\t\tvalue.env !== null &&\n\t\t\t\t\t\t!Array.isArray(value.env) &&\n\t\t\t\t\t\tObject.values(value.env).every((entry) => typeof entry === \"string\"));\n\t\t\t\tif (validKey && validEnv) continue;\n\t\t\t} else if (\n\t\t\t\tvalue.type === \"oauth\" &&\n\t\t\t\ttypeof value.access === \"string\" &&\n\t\t\t\ttypeof value.refresh === \"string\" &&\n\t\t\t\ttypeof value.expires === \"number\" &&\n\t\t\t\tNumber.isFinite(value.expires)\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow new Error(`Invalid auth.json credential for provider \"${providerId}\"`);\n\t\t}\n\n\t\tthis.data = parsed as AuthStorageData;\n\t\treturn this.data;\n\t}\n\n\tasync read(providerId: string, options?: AuthOperationOptions): Promise<Credential | undefined> {\n\t\toptions?.signal?.throwIfAborted();\n\t\tconst credential = this.load()[providerId];\n\t\toptions?.signal?.throwIfAborted();\n\t\tif (!credential) return undefined;\n\t\tif (credential.type !== \"api_key\" || !credential.key || isCommandConfigValue(credential.key)) {\n\t\t\treturn structuredClone(credential);\n\t\t}\n\t\treturn { ...credential, key: resolveConfigValue(credential.key, credential.env) };\n\t}\n\n\tasync list(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]> {\n\t\toptions?.signal?.throwIfAborted();\n\t\tconst credentials = Object.entries(this.load()).map(([providerId, credential]) => ({\n\t\t\tproviderId,\n\t\t\ttype: credential.type,\n\t\t}));\n\t\toptions?.signal?.throwIfAborted();\n\t\treturn credentials;\n\t}\n\n\tasync modify(\n\t\t_providerId: string,\n\t\t_fn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t\t_options?: AuthOperationOptions,\n\t): Promise<Credential | undefined> {\n\t\tthrow new Error(\"Read-only credential storage cannot modify auth.json\");\n\t}\n\n\tasync delete(_providerId: string, _options?: AuthOperationOptions): Promise<void> {\n\t\tthrow new Error(\"Read-only credential storage cannot modify auth.json\");\n\t}\n}\n\nexport class InMemoryAuthStorageBackend implements AuthStorageBackend {\n\tprivate value: string | undefined;\n\tprivate asyncChain: Promise<unknown> = Promise.resolve();\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tconst { result, next } = fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n\n\twithLockAsync<T>(\n\t\tfn: (current: string | undefined) => Promise<LockResult<T>>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<T> {\n\t\tconst previous = this.asyncChain;\n\t\tconst operation = (async () => {\n\t\t\tawait previous.catch(() => {});\n\t\t\toptions?.signal?.throwIfAborted();\n\t\t\tconst { result, next } = await fn(this.value);\n\t\t\toptions?.signal?.throwIfAborted();\n\t\t\tif (next !== undefined) {\n\t\t\t\tthis.value = next;\n\t\t\t}\n\t\t\treturn result;\n\t\t})();\n\t\tthis.asyncChain = operation.catch(() => {});\n\t\treturn raceWithAbortSignal(operation, options?.signal);\n\t}\n}\n\n/**\n * Credential storage backed by a JSON file.\n */\nexport class AuthStorage implements CredentialStore {\n\tprivate storage: AuthStorageBackend;\n\tprivate authPath: string | undefined;\n\tprivate readState: AuthFileReadState;\n\n\tprivate constructor(storage: AuthStorageBackend, authPath?: string) {\n\t\tthis.storage = storage;\n\t\tthis.authPath = authPath;\n\t\tthis.readState =\n\t\t\tauthPath && sharedAuthFileReadState?.authPath === authPath ? sharedAuthFileReadState.readState : { data: {} };\n\t\tif (authPath && !sharedAuthFileReadState) {\n\t\t\tsharedAuthFileReadState = { authPath, readState: this.readState };\n\t\t}\n\t\tif (authPath) {\n\t\t\tconst revision = getFileRevision(authPath);\n\t\t\tif (revision !== undefined && revision === this.readState.revision) return;\n\t\t}\n\t\tthis.reload();\n\t}\n\n\tstatic create(authPath: string = getAuthPath()): AuthStorage {\n\t\tconst normalizedAuthPath = normalizePath(authPath);\n\t\treturn new AuthStorage(new FileAuthStorageBackend(normalizedAuthPath), normalizedAuthPath);\n\t}\n\n\tstatic fromStorage(storage: AuthStorageBackend): AuthStorage {\n\t\treturn new AuthStorage(storage);\n\t}\n\n\tstatic inMemory(data: AuthStorageData = {}): AuthStorage {\n\t\tconst storage = new InMemoryAuthStorageBackend();\n\t\tstorage.withLock(() => ({ result: undefined, next: JSON.stringify(data, null, 2) }));\n\t\treturn AuthStorage.fromStorage(storage);\n\t}\n\n\tprivate parseStorageData(content: string | undefined): AuthStorageData {\n\t\tif (!content) {\n\t\t\treturn {};\n\t\t}\n\t\treturn JSON.parse(content) as AuthStorageData;\n\t}\n\n\tprivate updateReadState(data: AuthStorageData, revision?: string): void {\n\t\tthis.readState.data = data;\n\t\tthis.readState.revision = revision;\n\t}\n\n\t/**\n\t * Reload credentials from storage.\n\t */\n\treload(): void {\n\t\tlet content: string | undefined;\n\t\tlet revision: string | undefined;\n\t\ttry {\n\t\t\tthis.storage.withLock((current) => {\n\t\t\t\tcontent = current;\n\t\t\t\trevision = this.authPath ? getFileRevision(this.authPath) : undefined;\n\t\t\t\treturn { result: undefined };\n\t\t\t});\n\t\t\tthis.updateReadState(this.parseStorageData(content), revision);\n\t\t} catch {\n\t\t\t// Preserve the last valid in-memory snapshot.\n\t\t}\n\t}\n\n\tprivate async reloadFromStorageAsync(options?: AuthOperationOptions): Promise<AuthStorageData> {\n\t\treturn this.storage.withLockAsync(async (content) => {\n\t\t\tconst currentData = this.parseStorageData(content);\n\t\t\tconst revision = this.authPath ? getFileRevision(this.authPath) : undefined;\n\t\t\tthis.updateReadState(currentData, revision);\n\t\t\treturn { result: currentData };\n\t\t}, options);\n\t}\n\n\tprivate async readLatestData(options?: AuthOperationOptions): Promise<AuthStorageData> {\n\t\toptions?.signal?.throwIfAborted();\n\t\tif (!this.authPath) {\n\t\t\tconst reload = this.reloadFromStorageAsync(options);\n\t\t\treturn options?.signal ? reload : reload.catch(() => this.readState.data);\n\t\t}\n\t\tconst revision = getFileRevision(this.authPath);\n\t\tif (revision !== undefined && revision === this.readState.revision) return this.readState.data;\n\t\tif (!this.readState.reload) {\n\t\t\tconst controller = new AbortController();\n\t\t\tconst reload: AuthFileReload = {\n\t\t\t\tcontroller,\n\t\t\t\tpromise: this.reloadFromStorageAsync({ signal: controller.signal }),\n\t\t\t\treaders: 0,\n\t\t\t};\n\t\t\tthis.readState.reload = reload;\n\t\t\tvoid reload.promise.then(\n\t\t\t\t() => {\n\t\t\t\t\tif (this.readState.reload === reload) this.readState.reload = undefined;\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tif (this.readState.reload === reload) this.readState.reload = undefined;\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\n\t\tconst reload = this.readState.reload;\n\t\treload.readers++;\n\t\ttry {\n\t\t\tconst result = raceWithAbortSignal(reload.promise, options?.signal);\n\t\t\treturn options?.signal ? await result : await result.catch(() => this.readState.data);\n\t\t} finally {\n\t\t\treload.readers--;\n\t\t\tif (reload.readers === 0 && this.readState.reload === reload) {\n\t\t\t\tthis.readState.reload = undefined;\n\t\t\t\treload.controller.abort();\n\t\t\t}\n\t\t}\n\t}\n\n\tasync read(provider: string, options?: AuthOperationOptions): Promise<Credential | undefined> {\n\t\tconst credential = (await this.readLatestData(options))[provider];\n\t\toptions?.signal?.throwIfAborted();\n\t\tif (credential?.type !== \"api_key\") return credential;\n\t\tif (credential.key === undefined) return credential;\n\t\treturn { ...credential, key: resolveConfigValue(credential.key, credential.env) };\n\t}\n\n\tasync modify(\n\t\tprovider: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<Credential | undefined> {\n\t\tlet latestData = this.readState.data;\n\t\tlet revision: string | undefined;\n\t\tconst result = await this.storage.withLockAsync(async (content) => {\n\t\t\tconst currentData = this.parseStorageData(content);\n\t\t\tconst next = await fn(currentData[provider]);\n\t\t\tif (next === undefined) {\n\t\t\t\tlatestData = currentData;\n\t\t\t\trevision = this.authPath ? getFileRevision(this.authPath) : undefined;\n\t\t\t\treturn { result: currentData[provider] };\n\t\t\t}\n\n\t\t\tconst merged: AuthStorageData = { ...currentData, [provider]: next };\n\t\t\tlatestData = merged;\n\t\t\treturn { result: next, next: JSON.stringify(merged, null, 2) };\n\t\t}, options);\n\t\tthis.updateReadState(latestData, revision);\n\t\treturn result;\n\t}\n\n\tasync delete(provider: string, options?: AuthOperationOptions): Promise<void> {\n\t\tlet latestData = this.readState.data;\n\t\tawait this.storage.withLockAsync(async (content) => {\n\t\t\tconst currentData = this.parseStorageData(content);\n\t\t\tdelete currentData[provider];\n\t\t\tlatestData = currentData;\n\t\t\treturn { result: undefined, next: JSON.stringify(currentData, null, 2) };\n\t\t}, options);\n\t\tthis.updateReadState(latestData);\n\t}\n\n\t/** List credential metadata without resolving configured key values. */\n\tasync list(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]> {\n\t\tconst entries = Object.entries(await this.readLatestData(options));\n\t\toptions?.signal?.throwIfAborted();\n\t\treturn entries.map(([providerId, credential]) => ({ providerId, type: credential.type }));\n\t}\n}\n\n/**\n * One-off synchronous read of a stored credential from an auth.json file,\n * without instantiating a store or resolving configured key values.\n */\nexport function readStoredCredential(providerId: string, authPath: string = getAuthPath()): Credential | undefined {\n\ttry {\n\t\tconst data = JSON.parse(readFileSync(normalizePath(authPath), \"utf-8\")) as AuthStorageData;\n\t\treturn data[providerId];\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bash-executor.d.ts","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAQH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAOtD,MAAM,WAAW,mBAAmB;IACnC,+DAA+D;IAC/D,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAClC,mCAAmC;IACnC,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAED,MAAM,WAAW,UAAU;IAC1B,sEAAsE;IACtE,MAAM,EAAE,MAAM,CAAC;IACf,wDAAwD;IACxD,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,mDAAmD;IACnD,SAAS,EAAE,OAAO,CAAC;IACnB,uCAAuC;IACvC,SAAS,EAAE,OAAO,CAAC;IACnB,yFAAyF;IACzF,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAMD;;;GAGG;AACH,wBAAsB,yBAAyB,CAC9C,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,cAAc,EAC1B,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,UAAU,CAAC,CAqGrB","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { createWriteStream, type WriteStream } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { sanitizeBinaryOutput } from \"../utils/shell.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"./tools/truncate.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized) */\n\tonChunk?: (chunk: string) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFileStream: WriteStream | undefined;\n\tlet totalBytes = 0;\n\n\tconst ensureTempFile = () => {\n\t\tif (tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\ttempFilePath = join(tmpdir(), `
|
|
1
|
+
{"version":3,"file":"bash-executor.d.ts","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAQH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAOtD,MAAM,WAAW,mBAAmB;IACnC,+DAA+D;IAC/D,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAClC,mCAAmC;IACnC,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAED,MAAM,WAAW,UAAU;IAC1B,sEAAsE;IACtE,MAAM,EAAE,MAAM,CAAC;IACf,wDAAwD;IACxD,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,mDAAmD;IACnD,SAAS,EAAE,OAAO,CAAC;IACnB,uCAAuC;IACvC,SAAS,EAAE,OAAO,CAAC;IACnB,yFAAyF;IACzF,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAMD;;;GAGG;AACH,wBAAsB,yBAAyB,CAC9C,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,cAAc,EAC1B,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,UAAU,CAAC,CAqGrB","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { createWriteStream, type WriteStream } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { sanitizeBinaryOutput } from \"../utils/shell.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"./tools/truncate.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized) */\n\tonChunk?: (chunk: string) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFileStream: WriteStream | undefined;\n\tlet totalBytes = 0;\n\n\tconst ensureTempFile = () => {\n\t\tif (tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\ttempFilePath = join(tmpdir(), `apex-code-bash-${id}.log`);\n\t\ttempFileStream = createWriteStream(tempFilePath);\n\t\tfor (const chunk of outputChunks) {\n\t\t\ttempFileStream.write(chunk);\n\t\t}\n\t};\n\n\tconst decoder = new TextDecoder();\n\n\tconst onData = (data: Buffer) => {\n\t\ttotalBytes += data.length;\n\n\t\t// Sanitize: strip ANSI, replace binary garbage, normalize newlines\n\t\tconst text = sanitizeBinaryOutput(stripAnsi(decoder.decode(data, { stream: true }))).replace(/\\r/g, \"\");\n\n\t\t// Start writing to temp file if exceeds threshold\n\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\tensureTempFile();\n\t\t}\n\n\t\tif (tempFileStream) {\n\t\t\ttempFileStream.write(text);\n\t\t}\n\n\t\t// Keep rolling buffer\n\t\toutputChunks.push(text);\n\t\toutputBytes += text.length;\n\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\tconst removed = outputChunks.shift()!;\n\t\t\toutputBytes -= removed.length;\n\t\t}\n\n\t\t// Stream to callback\n\t\tif (options?.onChunk) {\n\t\t\toptions.onChunk(text);\n\t\t}\n\t};\n\n\ttry {\n\t\tconst result = await operations.exec(command, cwd, {\n\t\t\tonData,\n\t\t\tsignal: options?.signal,\n\t\t});\n\n\t\tconst fullOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateTail(fullOutput);\n\t\tif (truncationResult.truncated) {\n\t\t\tensureTempFile();\n\t\t}\n\t\tif (tempFileStream) {\n\t\t\ttempFileStream.end();\n\t\t}\n\t\tconst cancelled = options?.signal?.aborted ?? false;\n\n\t\treturn {\n\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\texitCode: cancelled ? undefined : (result.exitCode ?? undefined),\n\t\t\tcancelled,\n\t\t\ttruncated: truncationResult.truncated,\n\t\t\tfullOutputPath: tempFilePath,\n\t\t};\n\t} catch (err) {\n\t\t// Check if it was an abort\n\t\tif (options?.signal?.aborted) {\n\t\t\tconst fullOutput = outputChunks.join(\"\");\n\t\t\tconst truncationResult = truncateTail(fullOutput);\n\t\t\tif (truncationResult.truncated) {\n\t\t\t\tensureTempFile();\n\t\t\t}\n\t\t\tif (tempFileStream) {\n\t\t\t\ttempFileStream.end();\n\t\t\t}\n\t\t\treturn {\n\t\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\t\texitCode: undefined,\n\t\t\t\tcancelled: true,\n\t\t\t\ttruncated: truncationResult.truncated,\n\t\t\t\tfullOutputPath: tempFilePath,\n\t\t\t};\n\t\t}\n\n\t\tif (tempFileStream) {\n\t\t\ttempFileStream.end();\n\t\t}\n\n\t\tthrow err;\n\t}\n}\n"]}
|
|
@@ -31,7 +31,7 @@ export async function executeBashWithOperations(command, cwd, operations, option
|
|
|
31
31
|
return;
|
|
32
32
|
}
|
|
33
33
|
const id = randomBytes(8).toString("hex");
|
|
34
|
-
tempFilePath = join(tmpdir(), `
|
|
34
|
+
tempFilePath = join(tmpdir(), `apex-code-bash-${id}.log`);
|
|
35
35
|
tempFileStream = createWriteStream(tempFilePath);
|
|
36
36
|
for (const chunk of outputChunks) {
|
|
37
37
|
tempFileStream.write(chunk);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bash-executor.js","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"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AM,EAAE,OAAO,IAAI,KAAK,CAAC;QAEpD,OAAO;YACN,MAAM,EAAE,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC,UAAU;YAC1E,QAAQ,EAAE,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,IAAI,SAAS,CAAC;YAChE,SAAS;YACT,SAAS,EAAE,gBAAgB,CAAC,SAAS;YACrC,cAAc,EAAE,YAAY;SAC5B,CAAC;IACH,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACd,2BAA2B;QAC3B,IAAI,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;YAC9B,MAAM,UAAU,GAAG,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YACzC,MAAM,gBAAgB,GAAG,YAAY,CAAC,UAAU,CAAC,CAAC;YAClD,IAAI,gBAAgB,CAAC,SAAS,EAAE,CAAC;gBAChC,cAAc,EAAE,CAAC;YAClB,CAAC;YACD,IAAI,cAAc,EAAE,CAAC;gBACpB,cAAc,CAAC,GAAG,EAAE,CAAC;YACtB,CAAC;YACD,OAAO;gBACN,MAAM,EAAE,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC,UAAU;gBAC1E,QAAQ,EAAE,SAAS;gBACnB,SAAS,EAAE,IAAI;gBACf,SAAS,EAAE,gBAAgB,CAAC,SAAS;gBACrC,cAAc,EAAE,YAAY;aAC5B,CAAC;QACH,CAAC;QAED,IAAI,cAAc,EAAE,CAAC;YACpB,cAAc,CAAC,GAAG,EAAE,CAAC;QACtB,CAAC;QAED,MAAM,GAAG,CAAC;IACX,CAAC;AAAA,CACD","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { createWriteStream, type WriteStream } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { sanitizeBinaryOutput } from \"../utils/shell.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"./tools/truncate.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized) */\n\tonChunk?: (chunk: string) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFileStream: WriteStream | undefined;\n\tlet totalBytes = 0;\n\n\tconst ensureTempFile = () => {\n\t\tif (tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\ttempFilePath = join(tmpdir(), `apex-code-bash-${id}.log`);\n\t\ttempFileStream = createWriteStream(tempFilePath);\n\t\tfor (const chunk of outputChunks) {\n\t\t\ttempFileStream.write(chunk);\n\t\t}\n\t};\n\n\tconst decoder = new TextDecoder();\n\n\tconst onData = (data: Buffer) => {\n\t\ttotalBytes += data.length;\n\n\t\t// Sanitize: strip ANSI, replace binary garbage, normalize newlines\n\t\tconst text = sanitizeBinaryOutput(stripAnsi(decoder.decode(data, { stream: true }))).replace(/\\r/g, \"\");\n\n\t\t// Start writing to temp file if exceeds threshold\n\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\tensureTempFile();\n\t\t}\n\n\t\tif (tempFileStream) {\n\t\t\ttempFileStream.write(text);\n\t\t}\n\n\t\t// Keep rolling buffer\n\t\toutputChunks.push(text);\n\t\toutputBytes += text.length;\n\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\tconst removed = outputChunks.shift()!;\n\t\t\toutputBytes -= removed.length;\n\t\t}\n\n\t\t// Stream to callback\n\t\tif (options?.onChunk) {\n\t\t\toptions.onChunk(text);\n\t\t}\n\t};\n\n\ttry {\n\t\tconst result = await operations.exec(command, cwd, {\n\t\t\tonData,\n\t\t\tsignal: options?.signal,\n\t\t});\n\n\t\tconst fullOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateTail(fullOutput);\n\t\tif (truncationResult.truncated) {\n\t\t\tensureTempFile();\n\t\t}\n\t\tif (tempFileStream) {\n\t\t\ttempFileStream.end();\n\t\t}\n\t\tconst cancelled = options?.signal?.aborted ?? false;\n\n\t\treturn {\n\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\texitCode: cancelled ? undefined : (result.exitCode ?? undefined),\n\t\t\tcancelled,\n\t\t\ttruncated: truncationResult.truncated,\n\t\t\tfullOutputPath: tempFilePath,\n\t\t};\n\t} catch (err) {\n\t\t// Check if it was an abort\n\t\tif (options?.signal?.aborted) {\n\t\t\tconst fullOutput = outputChunks.join(\"\");\n\t\t\tconst truncationResult = truncateTail(fullOutput);\n\t\t\tif (truncationResult.truncated) {\n\t\t\t\tensureTempFile();\n\t\t\t}\n\t\t\tif (tempFileStream) {\n\t\t\t\ttempFileStream.end();\n\t\t\t}\n\t\t\treturn {\n\t\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\t\texitCode: undefined,\n\t\t\t\tcancelled: true,\n\t\t\t\ttruncated: truncationResult.truncated,\n\t\t\t\tfullOutputPath: tempFilePath,\n\t\t\t};\n\t\t}\n\n\t\tif (tempFileStream) {\n\t\t\ttempFileStream.end();\n\t\t}\n\n\t\tthrow err;\n\t}\n}\n"]}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deferred-schema resolution — announce-by-name projection and explicit load path.
|
|
3
|
+
*
|
|
4
|
+
* Ordering context (`docs/architecture/contracts.md` § 2, "Context pipeline order —
|
|
5
|
+
* settled"): deferred-schema resolution is the first of three stages applied at the
|
|
6
|
+
* `transformContext` seam —
|
|
7
|
+
*
|
|
8
|
+
* deferred-schema resolution → tool-result eviction → compaction
|
|
9
|
+
*
|
|
10
|
+
* — because it changes the static prefix (system prompt + tool definitions) that both
|
|
11
|
+
* later stages measure themselves against. This module implements only that first
|
|
12
|
+
* stage's two primitives; wiring it into `transformContext` is task 3.3.
|
|
13
|
+
*
|
|
14
|
+
* `ContextSpec.deferSchema` (`core/tools/contract.ts`) is the per-tool flag this
|
|
15
|
+
* module reads: a tool with `deferSchema: true` is announced to the model by name and
|
|
16
|
+
* description only — its full JSON parameter schema is withheld from the static
|
|
17
|
+
* prefix — and materialized on demand through `loadDeferredSchema` when a later
|
|
18
|
+
* wiring stage needs the real schema for a tool the model decided to call.
|
|
19
|
+
*
|
|
20
|
+
* Both functions are pure: everything they need arrives as a parameter, nothing is
|
|
21
|
+
* read from a global tool registry, and neither performs I/O.
|
|
22
|
+
*/
|
|
23
|
+
/**
|
|
24
|
+
* Minimal shape this module needs from a tool definition. Any richer type — e.g.
|
|
25
|
+
* `ApexToolDefinition` from `core/tools/contract.ts` — satisfies this structurally,
|
|
26
|
+
* so a caller can pass its real tool-definition array directly with no adapter.
|
|
27
|
+
*/
|
|
28
|
+
export interface DeferrableTool {
|
|
29
|
+
name: string;
|
|
30
|
+
description: string;
|
|
31
|
+
/**
|
|
32
|
+
* The tool's full parameter schema (a TypeBox `TSchema` on `ApexToolDefinition` in
|
|
33
|
+
* this repo, but this module treats it as opaque — it never inspects, validates,
|
|
34
|
+
* or transforms its shape, only copies or withholds it whole).
|
|
35
|
+
*/
|
|
36
|
+
parameters: unknown;
|
|
37
|
+
contract: {
|
|
38
|
+
context: {
|
|
39
|
+
deferSchema: boolean;
|
|
40
|
+
};
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* A tool as announced to the model: name, description, and a parameter schema that is
|
|
45
|
+
* either the tool's real schema (`deferSchema: false`) or the stub below
|
|
46
|
+
* (`deferSchema: true`).
|
|
47
|
+
*/
|
|
48
|
+
export interface AnnouncedTool {
|
|
49
|
+
name: string;
|
|
50
|
+
description: string;
|
|
51
|
+
parameters: unknown;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Stub schema substituted for a deferred tool's real parameters in the announce-by-name
|
|
55
|
+
* projection. An empty object schema rather than `undefined`/omission, so a provider
|
|
56
|
+
* that requires a `parameters`/`input_schema` field on every tool entry still receives
|
|
57
|
+
* a well-formed one.
|
|
58
|
+
*/
|
|
59
|
+
export declare const DEFERRED_SCHEMA_STUB: Readonly<{
|
|
60
|
+
type: "object";
|
|
61
|
+
properties: Record<string, never>;
|
|
62
|
+
}>;
|
|
63
|
+
/**
|
|
64
|
+
* Announce-by-name projection (context pipeline stage 1, "deferred-schema
|
|
65
|
+
* resolution").
|
|
66
|
+
*
|
|
67
|
+
* Tools with `contract.context.deferSchema === true` are represented by name and
|
|
68
|
+
* description only; their `parameters` field is replaced with `DEFERRED_SCHEMA_STUB`.
|
|
69
|
+
* Tools with `deferSchema === false` pass through with their real schema unchanged
|
|
70
|
+
* (the same reference, so deep- and reference-equality both hold).
|
|
71
|
+
*
|
|
72
|
+
* Pure: same length and order as `tools` in, no field other than `parameters` is
|
|
73
|
+
* altered, no global state is read.
|
|
74
|
+
*/
|
|
75
|
+
export declare function announceToolsByName<T extends DeferrableTool>(tools: readonly T[]): AnnouncedTool[];
|
|
76
|
+
/**
|
|
77
|
+
* Explicit load path (context pipeline stage 1's counterpart): given a tool name,
|
|
78
|
+
* returns its real, full parameter schema — the mechanism a later wiring stage
|
|
79
|
+
* (task 3.3) calls when the model needs the real schema for a deferred tool it
|
|
80
|
+
* decided to call.
|
|
81
|
+
*
|
|
82
|
+
* Looks up `name` in `tools` and returns that tool's real `parameters`, regardless of
|
|
83
|
+
* whether `deferSchema` is `true` or `false` — a tool that never deferred its schema
|
|
84
|
+
* still has a well-defined "real schema" to return, and the caller should not have to
|
|
85
|
+
* branch on `deferSchema` before loading.
|
|
86
|
+
*
|
|
87
|
+
* Throws if no tool named `name` exists in `tools`. Does not throw for a tool whose
|
|
88
|
+
* `deferSchema` is `false`; that is a valid no-op returning the same schema the
|
|
89
|
+
* announce-by-name projection already showed for it.
|
|
90
|
+
*/
|
|
91
|
+
export declare function loadDeferredSchema<T extends DeferrableTool>(tools: readonly T[], name: string): unknown;
|
|
92
|
+
//# sourceMappingURL=deferred-schemas.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"deferred-schemas.d.ts","sourceRoot":"","sources":["../../../src/core/context/deferred-schemas.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB;;;;OAIG;IACH,UAAU,EAAE,OAAO,CAAC;IACpB,QAAQ,EAAE;QACT,OAAO,EAAE;YACR,WAAW,EAAE,OAAO,CAAC;SACrB,CAAC;KACF,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,WAAW,aAAa;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,OAAO,CAAC;CACpB;AAED;;;;;GAKG;AACH,eAAO,MAAM,oBAAoB,EAAE,QAAQ,CAAC;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;CAAE,CAG/F,CAAC;AAEH;;;;;;;;;;;GAWG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,SAAS,cAAc,EAAE,KAAK,EAAE,SAAS,CAAC,EAAE,GAAG,aAAa,EAAE,CAMlG;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,SAAS,cAAc,EAAE,KAAK,EAAE,SAAS,CAAC,EAAE,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAMvG","sourcesContent":["/**\n * Deferred-schema resolution — announce-by-name projection and explicit load path.\n *\n * Ordering context (`docs/architecture/contracts.md` § 2, \"Context pipeline order —\n * settled\"): deferred-schema resolution is the first of three stages applied at the\n * `transformContext` seam —\n *\n * deferred-schema resolution → tool-result eviction → compaction\n *\n * — because it changes the static prefix (system prompt + tool definitions) that both\n * later stages measure themselves against. This module implements only that first\n * stage's two primitives; wiring it into `transformContext` is task 3.3.\n *\n * `ContextSpec.deferSchema` (`core/tools/contract.ts`) is the per-tool flag this\n * module reads: a tool with `deferSchema: true` is announced to the model by name and\n * description only — its full JSON parameter schema is withheld from the static\n * prefix — and materialized on demand through `loadDeferredSchema` when a later\n * wiring stage needs the real schema for a tool the model decided to call.\n *\n * Both functions are pure: everything they need arrives as a parameter, nothing is\n * read from a global tool registry, and neither performs I/O.\n */\n\n/**\n * Minimal shape this module needs from a tool definition. Any richer type — e.g.\n * `ApexToolDefinition` from `core/tools/contract.ts` — satisfies this structurally,\n * so a caller can pass its real tool-definition array directly with no adapter.\n */\nexport interface DeferrableTool {\n\tname: string;\n\tdescription: string;\n\t/**\n\t * The tool's full parameter schema (a TypeBox `TSchema` on `ApexToolDefinition` in\n\t * this repo, but this module treats it as opaque — it never inspects, validates,\n\t * or transforms its shape, only copies or withholds it whole).\n\t */\n\tparameters: unknown;\n\tcontract: {\n\t\tcontext: {\n\t\t\tdeferSchema: boolean;\n\t\t};\n\t};\n}\n\n/**\n * A tool as announced to the model: name, description, and a parameter schema that is\n * either the tool's real schema (`deferSchema: false`) or the stub below\n * (`deferSchema: true`).\n */\nexport interface AnnouncedTool {\n\tname: string;\n\tdescription: string;\n\tparameters: unknown;\n}\n\n/**\n * Stub schema substituted for a deferred tool's real parameters in the announce-by-name\n * projection. An empty object schema rather than `undefined`/omission, so a provider\n * that requires a `parameters`/`input_schema` field on every tool entry still receives\n * a well-formed one.\n */\nexport const DEFERRED_SCHEMA_STUB: Readonly<{ type: \"object\"; properties: Record<string, never> }> = Object.freeze({\n\ttype: \"object\",\n\tproperties: {},\n});\n\n/**\n * Announce-by-name projection (context pipeline stage 1, \"deferred-schema\n * resolution\").\n *\n * Tools with `contract.context.deferSchema === true` are represented by name and\n * description only; their `parameters` field is replaced with `DEFERRED_SCHEMA_STUB`.\n * Tools with `deferSchema === false` pass through with their real schema unchanged\n * (the same reference, so deep- and reference-equality both hold).\n *\n * Pure: same length and order as `tools` in, no field other than `parameters` is\n * altered, no global state is read.\n */\nexport function announceToolsByName<T extends DeferrableTool>(tools: readonly T[]): AnnouncedTool[] {\n\treturn tools.map((tool) => ({\n\t\tname: tool.name,\n\t\tdescription: tool.description,\n\t\tparameters: tool.contract.context.deferSchema ? DEFERRED_SCHEMA_STUB : tool.parameters,\n\t}));\n}\n\n/**\n * Explicit load path (context pipeline stage 1's counterpart): given a tool name,\n * returns its real, full parameter schema — the mechanism a later wiring stage\n * (task 3.3) calls when the model needs the real schema for a deferred tool it\n * decided to call.\n *\n * Looks up `name` in `tools` and returns that tool's real `parameters`, regardless of\n * whether `deferSchema` is `true` or `false` — a tool that never deferred its schema\n * still has a well-defined \"real schema\" to return, and the caller should not have to\n * branch on `deferSchema` before loading.\n *\n * Throws if no tool named `name` exists in `tools`. Does not throw for a tool whose\n * `deferSchema` is `false`; that is a valid no-op returning the same schema the\n * announce-by-name projection already showed for it.\n */\nexport function loadDeferredSchema<T extends DeferrableTool>(tools: readonly T[], name: string): unknown {\n\tconst tool = tools.find((candidate) => candidate.name === name);\n\tif (!tool) {\n\t\tthrow new Error(`loadDeferredSchema: no tool named \"${name}\" in the provided definitions`);\n\t}\n\treturn tool.parameters;\n}\n"]}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deferred-schema resolution — announce-by-name projection and explicit load path.
|
|
3
|
+
*
|
|
4
|
+
* Ordering context (`docs/architecture/contracts.md` § 2, "Context pipeline order —
|
|
5
|
+
* settled"): deferred-schema resolution is the first of three stages applied at the
|
|
6
|
+
* `transformContext` seam —
|
|
7
|
+
*
|
|
8
|
+
* deferred-schema resolution → tool-result eviction → compaction
|
|
9
|
+
*
|
|
10
|
+
* — because it changes the static prefix (system prompt + tool definitions) that both
|
|
11
|
+
* later stages measure themselves against. This module implements only that first
|
|
12
|
+
* stage's two primitives; wiring it into `transformContext` is task 3.3.
|
|
13
|
+
*
|
|
14
|
+
* `ContextSpec.deferSchema` (`core/tools/contract.ts`) is the per-tool flag this
|
|
15
|
+
* module reads: a tool with `deferSchema: true` is announced to the model by name and
|
|
16
|
+
* description only — its full JSON parameter schema is withheld from the static
|
|
17
|
+
* prefix — and materialized on demand through `loadDeferredSchema` when a later
|
|
18
|
+
* wiring stage needs the real schema for a tool the model decided to call.
|
|
19
|
+
*
|
|
20
|
+
* Both functions are pure: everything they need arrives as a parameter, nothing is
|
|
21
|
+
* read from a global tool registry, and neither performs I/O.
|
|
22
|
+
*/
|
|
23
|
+
/**
|
|
24
|
+
* Stub schema substituted for a deferred tool's real parameters in the announce-by-name
|
|
25
|
+
* projection. An empty object schema rather than `undefined`/omission, so a provider
|
|
26
|
+
* that requires a `parameters`/`input_schema` field on every tool entry still receives
|
|
27
|
+
* a well-formed one.
|
|
28
|
+
*/
|
|
29
|
+
export const DEFERRED_SCHEMA_STUB = Object.freeze({
|
|
30
|
+
type: "object",
|
|
31
|
+
properties: {},
|
|
32
|
+
});
|
|
33
|
+
/**
|
|
34
|
+
* Announce-by-name projection (context pipeline stage 1, "deferred-schema
|
|
35
|
+
* resolution").
|
|
36
|
+
*
|
|
37
|
+
* Tools with `contract.context.deferSchema === true` are represented by name and
|
|
38
|
+
* description only; their `parameters` field is replaced with `DEFERRED_SCHEMA_STUB`.
|
|
39
|
+
* Tools with `deferSchema === false` pass through with their real schema unchanged
|
|
40
|
+
* (the same reference, so deep- and reference-equality both hold).
|
|
41
|
+
*
|
|
42
|
+
* Pure: same length and order as `tools` in, no field other than `parameters` is
|
|
43
|
+
* altered, no global state is read.
|
|
44
|
+
*/
|
|
45
|
+
export function announceToolsByName(tools) {
|
|
46
|
+
return tools.map((tool) => ({
|
|
47
|
+
name: tool.name,
|
|
48
|
+
description: tool.description,
|
|
49
|
+
parameters: tool.contract.context.deferSchema ? DEFERRED_SCHEMA_STUB : tool.parameters,
|
|
50
|
+
}));
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Explicit load path (context pipeline stage 1's counterpart): given a tool name,
|
|
54
|
+
* returns its real, full parameter schema — the mechanism a later wiring stage
|
|
55
|
+
* (task 3.3) calls when the model needs the real schema for a deferred tool it
|
|
56
|
+
* decided to call.
|
|
57
|
+
*
|
|
58
|
+
* Looks up `name` in `tools` and returns that tool's real `parameters`, regardless of
|
|
59
|
+
* whether `deferSchema` is `true` or `false` — a tool that never deferred its schema
|
|
60
|
+
* still has a well-defined "real schema" to return, and the caller should not have to
|
|
61
|
+
* branch on `deferSchema` before loading.
|
|
62
|
+
*
|
|
63
|
+
* Throws if no tool named `name` exists in `tools`. Does not throw for a tool whose
|
|
64
|
+
* `deferSchema` is `false`; that is a valid no-op returning the same schema the
|
|
65
|
+
* announce-by-name projection already showed for it.
|
|
66
|
+
*/
|
|
67
|
+
export function loadDeferredSchema(tools, name) {
|
|
68
|
+
const tool = tools.find((candidate) => candidate.name === name);
|
|
69
|
+
if (!tool) {
|
|
70
|
+
throw new Error(`loadDeferredSchema: no tool named "${name}" in the provided definitions`);
|
|
71
|
+
}
|
|
72
|
+
return tool.parameters;
|
|
73
|
+
}
|
|
74
|
+
//# sourceMappingURL=deferred-schemas.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"deferred-schemas.js","sourceRoot":"","sources":["../../../src/core/context/deferred-schemas.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAkCH;;;;;GAKG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAoE,MAAM,CAAC,MAAM,CAAC;IAClH,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,EAAE;CACd,CAAC,CAAC;AAEH;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,mBAAmB,CAA2B,KAAmB,EAAmB;IACnG,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;QAC3B,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,UAAU,EAAE,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,IAAI,CAAC,UAAU;KACtF,CAAC,CAAC,CAAC;AAAA,CACJ;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,kBAAkB,CAA2B,KAAmB,EAAE,IAAY,EAAW;IACxG,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC;IAChE,IAAI,CAAC,IAAI,EAAE,CAAC;QACX,MAAM,IAAI,KAAK,CAAC,sCAAsC,IAAI,+BAA+B,CAAC,CAAC;IAC5F,CAAC;IACD,OAAO,IAAI,CAAC,UAAU,CAAC;AAAA,CACvB","sourcesContent":["/**\n * Deferred-schema resolution — announce-by-name projection and explicit load path.\n *\n * Ordering context (`docs/architecture/contracts.md` § 2, \"Context pipeline order —\n * settled\"): deferred-schema resolution is the first of three stages applied at the\n * `transformContext` seam —\n *\n * deferred-schema resolution → tool-result eviction → compaction\n *\n * — because it changes the static prefix (system prompt + tool definitions) that both\n * later stages measure themselves against. This module implements only that first\n * stage's two primitives; wiring it into `transformContext` is task 3.3.\n *\n * `ContextSpec.deferSchema` (`core/tools/contract.ts`) is the per-tool flag this\n * module reads: a tool with `deferSchema: true` is announced to the model by name and\n * description only — its full JSON parameter schema is withheld from the static\n * prefix — and materialized on demand through `loadDeferredSchema` when a later\n * wiring stage needs the real schema for a tool the model decided to call.\n *\n * Both functions are pure: everything they need arrives as a parameter, nothing is\n * read from a global tool registry, and neither performs I/O.\n */\n\n/**\n * Minimal shape this module needs from a tool definition. Any richer type — e.g.\n * `ApexToolDefinition` from `core/tools/contract.ts` — satisfies this structurally,\n * so a caller can pass its real tool-definition array directly with no adapter.\n */\nexport interface DeferrableTool {\n\tname: string;\n\tdescription: string;\n\t/**\n\t * The tool's full parameter schema (a TypeBox `TSchema` on `ApexToolDefinition` in\n\t * this repo, but this module treats it as opaque — it never inspects, validates,\n\t * or transforms its shape, only copies or withholds it whole).\n\t */\n\tparameters: unknown;\n\tcontract: {\n\t\tcontext: {\n\t\t\tdeferSchema: boolean;\n\t\t};\n\t};\n}\n\n/**\n * A tool as announced to the model: name, description, and a parameter schema that is\n * either the tool's real schema (`deferSchema: false`) or the stub below\n * (`deferSchema: true`).\n */\nexport interface AnnouncedTool {\n\tname: string;\n\tdescription: string;\n\tparameters: unknown;\n}\n\n/**\n * Stub schema substituted for a deferred tool's real parameters in the announce-by-name\n * projection. An empty object schema rather than `undefined`/omission, so a provider\n * that requires a `parameters`/`input_schema` field on every tool entry still receives\n * a well-formed one.\n */\nexport const DEFERRED_SCHEMA_STUB: Readonly<{ type: \"object\"; properties: Record<string, never> }> = Object.freeze({\n\ttype: \"object\",\n\tproperties: {},\n});\n\n/**\n * Announce-by-name projection (context pipeline stage 1, \"deferred-schema\n * resolution\").\n *\n * Tools with `contract.context.deferSchema === true` are represented by name and\n * description only; their `parameters` field is replaced with `DEFERRED_SCHEMA_STUB`.\n * Tools with `deferSchema === false` pass through with their real schema unchanged\n * (the same reference, so deep- and reference-equality both hold).\n *\n * Pure: same length and order as `tools` in, no field other than `parameters` is\n * altered, no global state is read.\n */\nexport function announceToolsByName<T extends DeferrableTool>(tools: readonly T[]): AnnouncedTool[] {\n\treturn tools.map((tool) => ({\n\t\tname: tool.name,\n\t\tdescription: tool.description,\n\t\tparameters: tool.contract.context.deferSchema ? DEFERRED_SCHEMA_STUB : tool.parameters,\n\t}));\n}\n\n/**\n * Explicit load path (context pipeline stage 1's counterpart): given a tool name,\n * returns its real, full parameter schema — the mechanism a later wiring stage\n * (task 3.3) calls when the model needs the real schema for a deferred tool it\n * decided to call.\n *\n * Looks up `name` in `tools` and returns that tool's real `parameters`, regardless of\n * whether `deferSchema` is `true` or `false` — a tool that never deferred its schema\n * still has a well-defined \"real schema\" to return, and the caller should not have to\n * branch on `deferSchema` before loading.\n *\n * Throws if no tool named `name` exists in `tools`. Does not throw for a tool whose\n * `deferSchema` is `false`; that is a valid no-op returning the same schema the\n * announce-by-name projection already showed for it.\n */\nexport function loadDeferredSchema<T extends DeferrableTool>(tools: readonly T[], name: string): unknown {\n\tconst tool = tools.find((candidate) => candidate.name === name);\n\tif (!tool) {\n\t\tthrow new Error(`loadDeferredSchema: no tool named \"${name}\" in the provided definitions`);\n\t}\n\treturn tool.parameters;\n}\n"]}
|