apex-code 0.0.1-alpha.8 → 0.0.4
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 +231 -0
- package/README.md +9 -8
- package/dist/cli/args.d.ts +26 -1
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +72 -10
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/file-processor.d.ts.map +1 -1
- package/dist/cli/file-processor.js +2 -1
- package/dist/cli/file-processor.js.map +1 -1
- package/dist/cli/mcp-command.d.ts +9 -0
- package/dist/cli/mcp-command.d.ts.map +1 -0
- package/dist/cli/mcp-command.js +53 -0
- package/dist/cli/mcp-command.js.map +1 -0
- package/dist/cli/project-trust.d.ts.map +1 -1
- package/dist/cli/project-trust.js +3 -1
- package/dist/cli/project-trust.js.map +1 -1
- package/dist/cli/startup-ui.d.ts.map +1 -1
- package/dist/cli/startup-ui.js +2 -1
- package/dist/cli/startup-ui.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +94 -5
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +3 -2
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +45 -18
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session-services.d.ts +3 -0
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +1 -0
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +183 -15
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +728 -117
- 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 -7
- 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 +7 -0
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/checkpoints/git-checkpoints.d.ts +39 -0
- package/dist/core/checkpoints/git-checkpoints.d.ts.map +1 -0
- package/dist/core/checkpoints/git-checkpoints.js +251 -0
- package/dist/core/checkpoints/git-checkpoints.js.map +1 -0
- package/dist/core/checkpoints/session-checkpoints.d.ts +23 -0
- package/dist/core/checkpoints/session-checkpoints.d.ts.map +1 -0
- package/dist/core/checkpoints/session-checkpoints.js +36 -0
- package/dist/core/checkpoints/session-checkpoints.js.map +1 -0
- package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
- package/dist/core/compaction/branch-summarization.js +7 -3
- package/dist/core/compaction/branch-summarization.js.map +1 -1
- package/dist/core/compaction/compaction.d.ts +9 -3
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +59 -36
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/defaults.d.ts +1 -0
- package/dist/core/defaults.d.ts.map +1 -1
- package/dist/core/defaults.js +9 -0
- package/dist/core/defaults.js.map +1 -1
- package/dist/core/delegation/runtime.d.ts +6 -5
- package/dist/core/delegation/runtime.d.ts.map +1 -1
- package/dist/core/delegation/runtime.js +4 -3
- package/dist/core/delegation/runtime.js.map +1 -1
- package/dist/core/durable-state/sqlite.d.ts.map +1 -1
- package/dist/core/durable-state/sqlite.js +26 -2
- package/dist/core/durable-state/sqlite.js.map +1 -1
- package/dist/core/exec.d.ts.map +1 -1
- package/dist/core/exec.js +5 -2
- package/dist/core/exec.js.map +1 -1
- package/dist/core/extensions/index.d.ts +2 -2
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +123 -50
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +5 -0
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +45 -1
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/source-runtime.d.ts +14 -0
- package/dist/core/extensions/source-runtime.d.ts.map +1 -0
- package/dist/core/extensions/source-runtime.js +56 -0
- package/dist/core/extensions/source-runtime.js.map +1 -0
- package/dist/core/extensions/types.d.ts +60 -11
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js +3 -0
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/footer-data-provider.d.ts +1 -1
- package/dist/core/footer-data-provider.d.ts.map +1 -1
- package/dist/core/footer-data-provider.js +1 -1
- package/dist/core/footer-data-provider.js.map +1 -1
- package/dist/core/formatter-lifecycle.d.ts +69 -0
- package/dist/core/formatter-lifecycle.d.ts.map +1 -0
- package/dist/core/formatter-lifecycle.js +360 -0
- package/dist/core/formatter-lifecycle.js.map +1 -0
- package/dist/core/hooks/command-handler.d.ts +19 -0
- package/dist/core/hooks/command-handler.d.ts.map +1 -0
- package/dist/core/hooks/command-handler.js +112 -0
- package/dist/core/hooks/command-handler.js.map +1 -0
- package/dist/core/hooks/http-handler.d.ts +10 -0
- package/dist/core/hooks/http-handler.d.ts.map +1 -0
- package/dist/core/hooks/http-handler.js +36 -0
- package/dist/core/hooks/http-handler.js.map +1 -0
- package/dist/core/hooks/loader.d.ts +29 -0
- package/dist/core/hooks/loader.d.ts.map +1 -0
- package/dist/core/hooks/loader.js +139 -0
- package/dist/core/hooks/loader.js.map +1 -0
- package/dist/core/hooks/runtime.d.ts +13 -0
- package/dist/core/hooks/runtime.d.ts.map +1 -0
- package/dist/core/hooks/runtime.js +63 -0
- package/dist/core/hooks/runtime.js.map +1 -0
- package/dist/core/hooks/types.d.ts +83 -0
- package/dist/core/hooks/types.d.ts.map +1 -0
- package/dist/core/hooks/types.js +24 -0
- package/dist/core/hooks/types.js.map +1 -0
- package/dist/core/keybindings.d.ts +20 -19
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +26 -5
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/mcp/config.d.ts +16 -0
- package/dist/core/mcp/config.d.ts.map +1 -0
- package/dist/core/mcp/config.js +166 -0
- package/dist/core/mcp/config.js.map +1 -0
- package/dist/core/mcp/connector.d.ts +35 -0
- package/dist/core/mcp/connector.d.ts.map +1 -0
- package/dist/core/mcp/connector.js +105 -0
- package/dist/core/mcp/connector.js.map +1 -0
- package/dist/core/mcp/contract.d.ts +19 -0
- package/dist/core/mcp/contract.d.ts.map +1 -0
- package/dist/core/mcp/contract.js +89 -0
- package/dist/core/mcp/contract.js.map +1 -0
- package/dist/core/mcp/mcp-tool.d.ts +32 -0
- package/dist/core/mcp/mcp-tool.d.ts.map +1 -0
- package/dist/core/mcp/mcp-tool.js +171 -0
- package/dist/core/mcp/mcp-tool.js.map +1 -0
- package/dist/core/mcp/metadata-cache.d.ts +29 -0
- package/dist/core/mcp/metadata-cache.d.ts.map +1 -0
- package/dist/core/mcp/metadata-cache.js +99 -0
- package/dist/core/mcp/metadata-cache.js.map +1 -0
- package/dist/core/mcp/oauth/authorize.d.ts +21 -0
- package/dist/core/mcp/oauth/authorize.d.ts.map +1 -0
- package/dist/core/mcp/oauth/authorize.js +32 -0
- package/dist/core/mcp/oauth/authorize.js.map +1 -0
- package/dist/core/mcp/oauth/discover.d.ts +27 -0
- package/dist/core/mcp/oauth/discover.d.ts.map +1 -0
- package/dist/core/mcp/oauth/discover.js +116 -0
- package/dist/core/mcp/oauth/discover.js.map +1 -0
- package/dist/core/mcp/oauth/flow.d.ts +31 -0
- package/dist/core/mcp/oauth/flow.d.ts.map +1 -0
- package/dist/core/mcp/oauth/flow.js +175 -0
- package/dist/core/mcp/oauth/flow.js.map +1 -0
- package/dist/core/mcp/oauth/mcp-token.d.ts +51 -0
- package/dist/core/mcp/oauth/mcp-token.d.ts.map +1 -0
- package/dist/core/mcp/oauth/mcp-token.js +129 -0
- package/dist/core/mcp/oauth/mcp-token.js.map +1 -0
- package/dist/core/mcp/oauth/pkce.d.ts +12 -0
- package/dist/core/mcp/oauth/pkce.d.ts.map +1 -0
- package/dist/core/mcp/oauth/pkce.js +11 -0
- package/dist/core/mcp/oauth/pkce.js.map +1 -0
- package/dist/core/mcp/oauth/register.d.ts +16 -0
- package/dist/core/mcp/oauth/register.d.ts.map +1 -0
- package/dist/core/mcp/oauth/register.js +42 -0
- package/dist/core/mcp/oauth/register.js.map +1 -0
- package/dist/core/mcp/oauth/token-client.d.ts +33 -0
- package/dist/core/mcp/oauth/token-client.d.ts.map +1 -0
- package/dist/core/mcp/oauth/token-client.js +65 -0
- package/dist/core/mcp/oauth/token-client.js.map +1 -0
- package/dist/core/mcp/runtime.d.ts +20 -0
- package/dist/core/mcp/runtime.d.ts.map +1 -0
- package/dist/core/mcp/runtime.js +37 -0
- package/dist/core/mcp/runtime.js.map +1 -0
- package/dist/core/mcp/schema.d.ts +22 -0
- package/dist/core/mcp/schema.d.ts.map +1 -0
- package/dist/core/mcp/schema.js +20 -0
- package/dist/core/mcp/schema.js.map +1 -0
- package/dist/core/mcp/server-manager.d.ts +43 -0
- package/dist/core/mcp/server-manager.d.ts.map +1 -0
- package/dist/core/mcp/server-manager.js +142 -0
- package/dist/core/mcp/server-manager.js.map +1 -0
- package/dist/core/mcp/types.d.ts +100 -0
- package/dist/core/mcp/types.d.ts.map +1 -0
- package/dist/core/mcp/types.js +8 -0
- package/dist/core/mcp/types.js.map +1 -0
- package/dist/core/model-config.d.ts +5 -0
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-config.js +3 -1
- package/dist/core/model-config.js.map +1 -1
- package/dist/core/model-resolver.d.ts +1 -0
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +14 -8
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/models-store.d.ts.map +1 -1
- package/dist/core/models-store.js +2 -1
- package/dist/core/models-store.js.map +1 -1
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +22 -14
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/permissions/gate.d.ts.map +1 -1
- package/dist/core/permissions/gate.js +45 -4
- package/dist/core/permissions/gate.js.map +1 -1
- package/dist/core/permissions/operations.d.ts +20 -0
- package/dist/core/permissions/operations.d.ts.map +1 -0
- package/dist/core/permissions/operations.js +9 -0
- package/dist/core/permissions/operations.js.map +1 -0
- package/dist/core/permissions/policy-command.d.ts +42 -0
- package/dist/core/permissions/policy-command.d.ts.map +1 -0
- package/dist/core/permissions/policy-command.js +44 -0
- package/dist/core/permissions/policy-command.js.map +1 -0
- package/dist/core/permissions/responder.d.ts +49 -2
- package/dist/core/permissions/responder.d.ts.map +1 -1
- package/dist/core/permissions/responder.js +20 -8
- package/dist/core/permissions/responder.js.map +1 -1
- package/dist/core/permissions/rules.d.ts.map +1 -1
- package/dist/core/permissions/rules.js +11 -1
- package/dist/core/permissions/rules.js.map +1 -1
- package/dist/core/permissions/store.d.ts +18 -0
- package/dist/core/permissions/store.d.ts.map +1 -1
- package/dist/core/permissions/store.js +89 -8
- package/dist/core/permissions/store.js.map +1 -1
- package/dist/core/pi-manifest.d.ts.map +1 -1
- package/dist/core/pi-manifest.js +2 -1
- package/dist/core/pi-manifest.js.map +1 -1
- package/dist/core/policy-executor.d.ts +47 -0
- package/dist/core/policy-executor.d.ts.map +1 -0
- package/dist/core/policy-executor.js +228 -0
- package/dist/core/policy-executor.js.map +1 -0
- package/dist/core/policy-loader.d.ts +72 -0
- package/dist/core/policy-loader.d.ts.map +1 -0
- package/dist/core/policy-loader.js +195 -0
- package/dist/core/policy-loader.js.map +1 -0
- package/dist/core/project-trust.d.ts +1 -1
- package/dist/core/project-trust.d.ts.map +1 -1
- package/dist/core/project-trust.js.map +1 -1
- package/dist/core/remote-catalog-provider.d.ts.map +1 -1
- package/dist/core/remote-catalog-provider.js +2 -1
- package/dist/core/remote-catalog-provider.js.map +1 -1
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +3 -2
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/sandbox/bwrap-arguments.d.ts +41 -0
- package/dist/core/sandbox/bwrap-arguments.d.ts.map +1 -0
- package/dist/core/sandbox/bwrap-arguments.js +136 -0
- package/dist/core/sandbox/bwrap-arguments.js.map +1 -0
- package/dist/core/sandbox/child-entry.d.ts.map +1 -1
- package/dist/core/sandbox/child-entry.js +3 -1
- package/dist/core/sandbox/child-entry.js.map +1 -1
- package/dist/core/sandbox/cli-launch.d.ts +84 -4
- package/dist/core/sandbox/cli-launch.d.ts.map +1 -1
- package/dist/core/sandbox/cli-launch.js +115 -16
- package/dist/core/sandbox/cli-launch.js.map +1 -1
- package/dist/core/sandbox/cli-supervisor.d.ts +2 -0
- package/dist/core/sandbox/cli-supervisor.d.ts.map +1 -1
- package/dist/core/sandbox/cli-supervisor.js +50 -2
- package/dist/core/sandbox/cli-supervisor.js.map +1 -1
- package/dist/core/sandbox/full-access.d.ts +28 -0
- package/dist/core/sandbox/full-access.d.ts.map +1 -0
- package/dist/core/sandbox/full-access.js +63 -0
- package/dist/core/sandbox/full-access.js.map +1 -0
- package/dist/core/sandbox/git-identity.d.ts +57 -0
- package/dist/core/sandbox/git-identity.d.ts.map +1 -0
- package/dist/core/sandbox/git-identity.js +78 -0
- package/dist/core/sandbox/git-identity.js.map +1 -0
- package/dist/core/sandbox/host-approval.d.ts +42 -0
- package/dist/core/sandbox/host-approval.d.ts.map +1 -0
- package/dist/core/sandbox/host-approval.js +99 -0
- package/dist/core/sandbox/host-approval.js.map +1 -0
- package/dist/core/sandbox/linux-backend.d.ts +14 -0
- package/dist/core/sandbox/linux-backend.d.ts.map +1 -1
- package/dist/core/sandbox/linux-backend.js +158 -80
- package/dist/core/sandbox/linux-backend.js.map +1 -1
- package/dist/core/sandbox/macos-backend.d.ts +5 -0
- package/dist/core/sandbox/macos-backend.d.ts.map +1 -1
- package/dist/core/sandbox/macos-backend.js +164 -5
- package/dist/core/sandbox/macos-backend.js.map +1 -1
- package/dist/core/sandbox/network-proxy.d.ts +19 -0
- package/dist/core/sandbox/network-proxy.d.ts.map +1 -1
- package/dist/core/sandbox/network-proxy.js +93 -19
- package/dist/core/sandbox/network-proxy.js.map +1 -1
- package/dist/core/sandbox/policy.d.ts +8 -0
- package/dist/core/sandbox/policy.d.ts.map +1 -1
- package/dist/core/sandbox/policy.js +29 -12
- package/dist/core/sandbox/policy.js.map +1 -1
- package/dist/core/sandbox/profiles.d.ts +25 -0
- package/dist/core/sandbox/profiles.d.ts.map +1 -0
- package/dist/core/sandbox/profiles.js +23 -0
- package/dist/core/sandbox/profiles.js.map +1 -0
- package/dist/core/sandbox/rpc/command-client.d.ts +28 -0
- package/dist/core/sandbox/rpc/command-client.d.ts.map +1 -0
- package/dist/core/sandbox/rpc/command-client.js +86 -0
- package/dist/core/sandbox/rpc/command-client.js.map +1 -0
- package/dist/core/sandbox/rpc/command-proxy.d.ts +48 -0
- package/dist/core/sandbox/rpc/command-proxy.d.ts.map +1 -0
- package/dist/core/sandbox/rpc/command-proxy.js +120 -0
- package/dist/core/sandbox/rpc/command-proxy.js.map +1 -0
- package/dist/core/sandbox/rpc/credential-proxy.d.ts.map +1 -1
- package/dist/core/sandbox/rpc/credential-proxy.js +2 -96
- package/dist/core/sandbox/rpc/credential-proxy.js.map +1 -1
- package/dist/core/sandbox/rpc/framing.d.ts +35 -0
- package/dist/core/sandbox/rpc/framing.d.ts.map +1 -0
- package/dist/core/sandbox/rpc/framing.js +114 -0
- package/dist/core/sandbox/rpc/framing.js.map +1 -0
- package/dist/core/sandbox/rpc/git-credential-helper.d.ts +47 -0
- package/dist/core/sandbox/rpc/git-credential-helper.d.ts.map +1 -0
- package/dist/core/sandbox/rpc/git-credential-helper.js +222 -0
- package/dist/core/sandbox/rpc/git-credential-helper.js.map +1 -0
- package/dist/core/sandbox/rpc/git-credential-proxy.d.ts +66 -0
- package/dist/core/sandbox/rpc/git-credential-proxy.d.ts.map +1 -0
- package/dist/core/sandbox/rpc/git-credential-proxy.js +209 -0
- package/dist/core/sandbox/rpc/git-credential-proxy.js.map +1 -0
- package/dist/core/sandbox/supervisor-temp.d.ts +18 -0
- package/dist/core/sandbox/supervisor-temp.d.ts.map +1 -0
- package/dist/core/sandbox/supervisor-temp.js +21 -0
- package/dist/core/sandbox/supervisor-temp.js.map +1 -0
- package/dist/core/sandbox/supervisor.d.ts +12 -1
- package/dist/core/sandbox/supervisor.d.ts.map +1 -1
- package/dist/core/sandbox/supervisor.js +15 -1
- package/dist/core/sandbox/supervisor.js.map +1 -1
- package/dist/core/sandbox/terminal-handoff.d.ts +68 -0
- package/dist/core/sandbox/terminal-handoff.d.ts.map +1 -0
- package/dist/core/sandbox/terminal-handoff.js +221 -0
- package/dist/core/sandbox/terminal-handoff.js.map +1 -0
- package/dist/core/sandbox/terminal-size.d.ts +13 -0
- package/dist/core/sandbox/terminal-size.d.ts.map +1 -1
- package/dist/core/sandbox/terminal-size.js +23 -2
- package/dist/core/sandbox/terminal-size.js.map +1 -1
- package/dist/core/sdk.d.ts +24 -2
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +63 -4
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-export.d.ts +4 -0
- package/dist/core/session-export.d.ts.map +1 -0
- package/dist/core/session-export.js +32 -0
- package/dist/core/session-export.js.map +1 -0
- package/dist/core/session-manager.d.ts +13 -1
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +34 -6
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-diagnostics.d.ts +9 -0
- package/dist/core/settings-diagnostics.d.ts.map +1 -0
- package/dist/core/settings-diagnostics.js +21 -0
- package/dist/core/settings-diagnostics.js.map +1 -0
- package/dist/core/settings-manager.d.ts +172 -1
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +160 -11
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/skills.js +51 -33
- package/dist/core/skills.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +4 -1
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +8 -2
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tools/background-shell.d.ts +39 -0
- package/dist/core/tools/background-shell.d.ts.map +1 -0
- package/dist/core/tools/background-shell.js +81 -0
- package/dist/core/tools/background-shell.js.map +1 -0
- package/dist/core/tools/bash-command-segments.d.ts.map +1 -1
- package/dist/core/tools/bash-command-segments.js +2 -0
- package/dist/core/tools/bash-command-segments.js.map +1 -1
- package/dist/core/tools/bash.d.ts +44 -16
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +264 -32
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/contract-snapshot.d.ts +58 -0
- package/dist/core/tools/contract-snapshot.d.ts.map +1 -0
- package/dist/core/tools/contract-snapshot.js +51 -0
- package/dist/core/tools/contract-snapshot.js.map +1 -0
- package/dist/core/tools/contract.d.ts +53 -5
- package/dist/core/tools/contract.d.ts.map +1 -1
- package/dist/core/tools/contract.js +22 -2
- package/dist/core/tools/contract.js.map +1 -1
- package/dist/core/tools/delegate.d.ts +6 -4
- package/dist/core/tools/delegate.d.ts.map +1 -1
- package/dist/core/tools/delegate.js +21 -11
- package/dist/core/tools/delegate.js.map +1 -1
- package/dist/core/tools/edit-diff.d.ts +48 -5
- package/dist/core/tools/edit-diff.d.ts.map +1 -1
- package/dist/core/tools/edit-diff.js +217 -8
- package/dist/core/tools/edit-diff.js.map +1 -1
- package/dist/core/tools/edit.d.ts +8 -0
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +72 -10
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +5 -2
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +5 -2
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/index.d.ts +14 -2
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +12 -0
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/ls.d.ts.map +1 -1
- package/dist/core/tools/ls.js +5 -2
- package/dist/core/tools/ls.js.map +1 -1
- package/dist/core/tools/lsp.d.ts +19 -1
- package/dist/core/tools/lsp.d.ts.map +1 -1
- package/dist/core/tools/lsp.js +163 -10
- package/dist/core/tools/lsp.js.map +1 -1
- package/dist/core/tools/path-permission.d.ts +3 -0
- package/dist/core/tools/path-permission.d.ts.map +1 -1
- package/dist/core/tools/path-permission.js +16 -4
- package/dist/core/tools/path-permission.js.map +1 -1
- package/dist/core/tools/path-utils.d.ts +27 -2
- package/dist/core/tools/path-utils.d.ts.map +1 -1
- package/dist/core/tools/path-utils.js +221 -4
- package/dist/core/tools/path-utils.js.map +1 -1
- package/dist/core/tools/powershell.d.ts +16 -0
- package/dist/core/tools/powershell.d.ts.map +1 -0
- package/dist/core/tools/powershell.js +39 -0
- package/dist/core/tools/powershell.js.map +1 -0
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +20 -11
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/test.d.ts +54 -9
- package/dist/core/tools/test.d.ts.map +1 -1
- package/dist/core/tools/test.js +239 -19
- package/dist/core/tools/test.js.map +1 -1
- package/dist/core/tools/write.d.ts +7 -0
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js +64 -9
- package/dist/core/tools/write.js.map +1 -1
- package/dist/core/trust-manager.d.ts.map +1 -1
- package/dist/core/trust-manager.js +2 -1
- package/dist/core/trust-manager.js.map +1 -1
- package/dist/core/verification-lifecycle.d.ts +77 -0
- package/dist/core/verification-lifecycle.d.ts.map +1 -0
- package/dist/core/verification-lifecycle.js +146 -0
- package/dist/core/verification-lifecycle.js.map +1 -0
- package/dist/core/workspace/artifacts.d.ts +45 -0
- package/dist/core/workspace/artifacts.d.ts.map +1 -0
- package/dist/core/workspace/artifacts.js +165 -0
- package/dist/core/workspace/artifacts.js.map +1 -0
- package/dist/core/workspace/comparison.d.ts +27 -0
- package/dist/core/workspace/comparison.d.ts.map +1 -0
- package/dist/core/workspace/comparison.js +94 -0
- package/dist/core/workspace/comparison.js.map +1 -0
- package/dist/core/workspace/git-observer.d.ts +48 -0
- package/dist/core/workspace/git-observer.d.ts.map +1 -0
- package/dist/core/workspace/git-observer.js +346 -0
- package/dist/core/workspace/git-observer.js.map +1 -0
- package/dist/core/workspace/projection.d.ts +3 -0
- package/dist/core/workspace/projection.d.ts.map +1 -0
- package/dist/core/workspace/projection.js +56 -0
- package/dist/core/workspace/projection.js.map +1 -0
- package/dist/core/workspace/state.d.ts +133 -0
- package/dist/core/workspace/state.d.ts.map +1 -0
- package/dist/core/workspace/state.js +96 -0
- package/dist/core/workspace/state.js.map +1 -0
- package/dist/extensions/llama/client.d.ts +6 -0
- package/dist/extensions/llama/client.d.ts.map +1 -1
- package/dist/extensions/llama/client.js +7 -0
- package/dist/extensions/llama/client.js.map +1 -1
- package/dist/extensions/llama/index.d.ts.map +1 -1
- package/dist/extensions/llama/index.js +2 -0
- package/dist/extensions/llama/index.js.map +1 -1
- package/dist/extensions/llama/provider.d.ts +3 -1
- package/dist/extensions/llama/provider.d.ts.map +1 -1
- package/dist/extensions/llama/provider.js +29 -4
- package/dist/extensions/llama/provider.js.map +1 -1
- package/dist/index.d.ts +8 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -4
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts +6 -0
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +58 -23
- package/dist/main.js.map +1 -1
- package/dist/migrations.d.ts.map +1 -1
- package/dist/migrations.js +4 -3
- package/dist/migrations.js.map +1 -1
- package/dist/modes/acp/server.d.ts +55 -0
- package/dist/modes/acp/server.d.ts.map +1 -0
- package/dist/modes/acp/server.js +244 -0
- package/dist/modes/acp/server.js.map +1 -0
- package/dist/modes/acp/translate.d.ts +37 -0
- package/dist/modes/acp/translate.d.ts.map +1 -0
- package/dist/modes/acp/translate.js +50 -0
- package/dist/modes/acp/translate.js.map +1 -0
- package/dist/modes/index.d.ts +1 -0
- package/dist/modes/index.d.ts.map +1 -1
- package/dist/modes/index.js +1 -0
- package/dist/modes/index.js.map +1 -1
- package/dist/modes/interactive/components/assistant-message.d.ts +29 -0
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js +182 -23
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/bash-execution.d.ts +7 -0
- package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/bash-execution.js +20 -0
- package/dist/modes/interactive/components/bash-execution.js.map +1 -1
- package/dist/modes/interactive/components/custom-editor.d.ts +9 -4
- package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-editor.js +20 -9
- package/dist/modes/interactive/components/custom-editor.js.map +1 -1
- package/dist/modes/interactive/components/extension-selector.d.ts +7 -1
- package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-selector.js +7 -3
- package/dist/modes/interactive/components/extension-selector.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts +19 -0
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +70 -10
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts +10 -3
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +56 -14
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/permission-preview.d.ts +15 -0
- package/dist/modes/interactive/components/permission-preview.d.ts.map +1 -0
- package/dist/modes/interactive/components/permission-preview.js +33 -0
- package/dist/modes/interactive/components/permission-preview.js.map +1 -0
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +2 -2
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +9 -2
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +128 -56
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/settings-submenu.d.ts +72 -0
- package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -0
- package/dist/modes/interactive/components/settings-submenu.js +165 -0
- package/dist/modes/interactive/components/settings-submenu.js.map +1 -0
- package/dist/modes/interactive/components/thinking-selector.d.ts +15 -3
- package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.js +74 -17
- package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +23 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +64 -10
- 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 +2 -1
- package/dist/modes/interactive/external-editor.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +45 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +395 -43
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/theme/theme.d.ts +12 -0
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +20 -9
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/dist/modes/json-event.d.ts +16 -13
- package/dist/modes/json-event.d.ts.map +1 -1
- package/dist/modes/json-event.js +20 -6
- package/dist/modes/json-event.js.map +1 -1
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +27 -12
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +7 -0
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +7 -0
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +3 -0
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +12 -0
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/package-manager-cli.d.ts +1 -0
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +196 -10
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/utils/frontmatter.d.ts.map +1 -1
- package/dist/utils/frontmatter.js +2 -1
- package/dist/utils/frontmatter.js.map +1 -1
- package/dist/utils/management-http.d.ts +5 -3
- package/dist/utils/management-http.d.ts.map +1 -1
- package/dist/utils/management-http.js +14 -10
- package/dist/utils/management-http.js.map +1 -1
- package/dist/utils/shell.d.ts +3 -0
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +23 -9
- package/dist/utils/shell.js.map +1 -1
- package/dist/utils/syntax-highlight.d.ts +1 -0
- package/dist/utils/syntax-highlight.d.ts.map +1 -1
- package/dist/utils/syntax-highlight.js +60 -1
- package/dist/utils/syntax-highlight.js.map +1 -1
- package/dist/utils/text.d.ts +8 -0
- package/dist/utils/text.d.ts.map +1 -0
- package/dist/utils/text.js +9 -0
- package/dist/utils/text.js.map +1 -0
- package/dist/utils/version-check.d.ts.map +1 -1
- package/dist/utils/version-check.js +6 -4
- package/dist/utils/version-check.js.map +1 -1
- package/docs/compaction.md +19 -0
- package/docs/custom-provider.md +12 -9
- package/docs/environment-variables.md +1 -1
- package/docs/extensions.md +35 -7
- package/docs/json.md +7 -2
- package/docs/keybindings.md +9 -9
- package/docs/llama-cpp.md +2 -0
- package/docs/models.md +8 -2
- package/docs/packages.md +2 -2
- package/docs/quickstart.md +1 -1
- package/docs/rpc.md +32 -3
- package/docs/sdk.md +32 -2
- package/docs/settings.md +23 -7
- package/docs/skills.md +4 -3
- package/docs/terminal-setup.md +23 -7
- package/docs/usage.md +10 -5
- package/docs/windows.md +24 -2
- package/examples/extensions/border-status-editor.ts +1 -1
- package/examples/extensions/built-in-tool-renderer.ts +8 -4
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/git-checkpoint.ts +24 -36
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/minimal-mode.ts +2 -2
- package/examples/extensions/notify.ts +3 -1
- package/examples/extensions/permission-gate.ts +1 -1
- package/examples/extensions/plan-mode/index.ts +1 -1
- package/examples/extensions/rpc-demo.ts +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/subagent/README.md +1 -1
- package/examples/extensions/subagent/index.ts +6 -1
- package/examples/extensions/titlebar-spinner.ts +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/examples/rpc-extension-ui.ts +1 -1
- package/examples/sdk/06-extensions.ts +1 -1
- package/examples/sdk/README.md +1 -1
- package/npm-shrinkwrap.json +439 -405
- package/package.json +17 -17
- package/dist/server/create-harness.d.ts +0 -26
- package/dist/server/create-harness.d.ts.map +0 -1
- package/dist/server/create-harness.js +0 -107
- package/dist/server/create-harness.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"defaults.d.ts","sourceRoot":"","sources":["../../src/core/defaults.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAE1D,eAAO,MAAM,sBAAsB,EAAE,aAAwB,CAAC","sourcesContent":["import type { ThinkingLevel } from \"apex-code-agent-core\";\n\nexport const DEFAULT_THINKING_LEVEL: ThinkingLevel = \"medium\";\n"]}
|
|
1
|
+
{"version":3,"file":"defaults.d.ts","sourceRoot":"","sources":["../../src/core/defaults.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAE1D,eAAO,MAAM,sBAAsB,EAAE,aAAwB,CAAC;AAC9D,eAAO,MAAM,sBAAsB,EAAE,SAAS,aAAa,EAQ1D,CAAC","sourcesContent":["import type { ThinkingLevel } from \"apex-code-agent-core\";\n\nexport const DEFAULT_THINKING_LEVEL: ThinkingLevel = \"medium\";\nexport const THINKING_LEVEL_OPTIONS: readonly ThinkingLevel[] = [\n\t\"off\",\n\t\"minimal\",\n\t\"low\",\n\t\"medium\",\n\t\"high\",\n\t\"xhigh\",\n\t\"max\",\n];\n"]}
|
package/dist/core/defaults.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"defaults.js","sourceRoot":"","sources":["../../src/core/defaults.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,sBAAsB,GAAkB,QAAQ,CAAC","sourcesContent":["import type { ThinkingLevel } from \"apex-code-agent-core\";\n\nexport const DEFAULT_THINKING_LEVEL: ThinkingLevel = \"medium\";\n"]}
|
|
1
|
+
{"version":3,"file":"defaults.js","sourceRoot":"","sources":["../../src/core/defaults.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,sBAAsB,GAAkB,QAAQ,CAAC;AAC9D,MAAM,CAAC,MAAM,sBAAsB,GAA6B;IAC/D,KAAK;IACL,SAAS;IACT,KAAK;IACL,QAAQ;IACR,MAAM;IACN,OAAO;IACP,KAAK;CACL,CAAC","sourcesContent":["import type { ThinkingLevel } from \"apex-code-agent-core\";\n\nexport const DEFAULT_THINKING_LEVEL: ThinkingLevel = \"medium\";\nexport const THINKING_LEVEL_OPTIONS: readonly ThinkingLevel[] = [\n\t\"off\",\n\t\"minimal\",\n\t\"low\",\n\t\"medium\",\n\t\"high\",\n\t\"xhigh\",\n\t\"max\",\n];\n"]}
|
|
@@ -5,14 +5,15 @@
|
|
|
5
5
|
* agent whose authority can never exceed its parent's.
|
|
6
6
|
*
|
|
7
7
|
* Agent definitions and child-session construction are both injected rather than
|
|
8
|
-
* built in here: agent discovery
|
|
9
|
-
* markdown
|
|
10
|
-
*
|
|
8
|
+
* built in here: production agent discovery lives in `core/delegation/agents.ts`
|
|
9
|
+
* (markdown + frontmatter, parsed on lookup) and plugs in through the same
|
|
10
|
+
* resolver interface a test fixture implements; child-session construction is
|
|
11
|
+
* injected so this module stays free of
|
|
11
12
|
* `AgentSession`/`createAgentSession` and therefore free of the import cycle that
|
|
12
13
|
* would create (`sdk.ts` already imports `agent-session.ts`).
|
|
13
14
|
*/
|
|
14
15
|
import type { Capability } from "../tools/contract.ts";
|
|
15
|
-
/** A delegatable agent's static configuration. Markdown + frontmatter in production (
|
|
16
|
+
/** A delegatable agent's static configuration. Markdown + frontmatter in production (`agents.ts`); a plain object in tests. */
|
|
16
17
|
export interface AgentDefinition {
|
|
17
18
|
name: string;
|
|
18
19
|
description: string;
|
|
@@ -22,7 +23,7 @@ export interface AgentDefinition {
|
|
|
22
23
|
model?: string;
|
|
23
24
|
systemPrompt: string;
|
|
24
25
|
}
|
|
25
|
-
/** Resolve an agent type to its definition, or `undefined` if unknown.
|
|
26
|
+
/** Resolve an agent type to its definition, or `undefined` if unknown. Production implements this over markdown/frontmatter (`agents.ts`); tests inject plain functions with the same shape. */
|
|
26
27
|
export type AgentDefinitionResolver = (agentType: string) => AgentDefinition | undefined;
|
|
27
28
|
/** A running or completed child, as far as the runtime needs to know. */
|
|
28
29
|
export interface ChildSessionHandle {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/runtime.ts"],"names":[],"mapp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,kBAAkB,EAAE,MAAM,CAAC;IAC3B,sFAAsF;IACtF,mBAAmB,CAAC,EAAE,MAAM,MAAM,CAAC;IACnC,iBAAiB,EAAE,CAAC,OAAO,EAAE,wBAAwB,KAAK,OAAO,CAAC,kBAAkB,CAAC,CAAC;CACtF;AAED,MAAM,WAAW,gBAAgB;IAChC,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,iFAAiF;IACjF,QAAQ,CAAC,EAAE,MAAM,CAAC;CAClB;AAoBD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,aAAa,CAClC,OAAO,EAAE,wBAAwB,EACjC,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE;IAAE,UAAU,CAAC,EAAE,OAAO,CAAA;CAAO,GACpC,OAAO,CAAC,gBAAgB,CAAC,CA8D3B;AAED,uGAAuG;AACvG,wBAAsB,wBAAwB,CAC7C,OAAO,EAAE,wBAAwB,EACjC,QAAQ,EAAE,MAAM,EAChB,iBAAiB,CAAC,EAAE,MAAM,GACxB,OAAO,CAAC,gBAAgB,CAAC,CAS3B","sourcesContent":["/**\n * The delegation runtime (roadmap Phase 5, ADR 0008, task 5.2). Consumes the\n * capability ceiling (ceiling.ts) and a derived permission store\n * (`../permissions/store.ts`'s `DerivedPermissionRuleStore`) to run a real child\n * agent whose authority can never exceed its parent's.\n *\n * Agent definitions and child-session construction are both injected rather than\n * built in here: agent discovery is a test fixture in this task and becomes real\n * markdown/frontmatter discovery in task 5.5 (`core/delegation/agents.ts`, not yet\n * written); child-session construction is injected so this module stays free of\n * `AgentSession`/`createAgentSession` and therefore free of the import cycle that\n * would create (`sdk.ts` already imports `agent-session.ts`).\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { mkdirSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport type { Capability } from \"../tools/contract.ts\";\nimport { computeCapabilityCeiling } from \"./ceiling.ts\";\n\n/** A delegatable agent's static configuration. Markdown + frontmatter in production (task 5.5); a plain object in tests until then. */\nexport interface AgentDefinition {\n\tname: string;\n\tdescription: string;\n\t/** Tool names this agent may use. Never trusted directly -- the runtime derives the actual child tool list from the computed capability set, not from this list verbatim. */\n\ttools: string[];\n\t/** Optional model id. Falls back to the parent's current model when unset or unresolvable. */\n\tmodel?: string;\n\tsystemPrompt: string;\n}\n\n/** Resolve an agent type to its definition, or `undefined` if unknown. A plain function fixture in this task; real markdown/frontmatter discovery (task 5.5) is just a different implementation of the same shape. */\nexport type AgentDefinitionResolver = (agentType: string) => AgentDefinition | undefined;\n\n/** A running or completed child, as far as the runtime needs to know. */\nexport interface ChildSessionHandle {\n\t/** Run the task to completion and return the child's final output text. */\n\trun(task: string): Promise<{ output: string }>;\n\t/** Release the child's resources. Always called, including after a failed run. */\n\tdispose(): void;\n}\n\nexport interface BuildChildSessionRequest {\n\tagentType: string;\n\tdefinition: AgentDefinition;\n\t/** The child's tool allowlist, already ceiling-checked -- exactly `definition.tools`, never narrowed. */\n\ttoolNames: string[];\n\t/** The child's own recursion depth (the parent's depth + 1), for the runtime constructing it to record on the child's session header (task 5.3). */\n\tdepth: number;\n\t/** Stable id used for the child session and its artifact directory. */\n\tsessionId: string;\n\t/** Per-child artifact root, created before the child session is constructed. */\n\tartifactDir?: string;\n}\n\nexport interface DelegationRuntimeOptions {\n\tresolveAgent: AgentDefinitionResolver;\n\t/** The parent's own effective capability set (its authority), unexpanded -- `exec` expansion happens inside the ceiling check, not here. */\n\tgetParentCapabilities: () => ReadonlySet<Capability>;\n\t/** Capability set a named tool requires, from the live registry. `undefined` for an unknown tool name. */\n\tgetToolCapabilities: (toolName: string) => ReadonlySet<Capability> | undefined;\n\t/** The parent session's own recursion depth (`SessionManager.getDelegationDepth()`), read fresh at delegation time. */\n\tgetDelegationDepth: () => number;\n\t/** Delegation is refused once `getDelegationDepth() >= maxDelegationDepth` -- assigned by the runtime, not by the tool, so the bound applies to any future delegation entry point. */\n\tmaxDelegationDepth: number;\n\t/** Parent session directory. When supplied, child artifacts are rooted beneath it. */\n\tgetParentSessionDir?: () => string;\n\tbuildChildSession: (request: BuildChildSessionRequest) => Promise<ChildSessionHandle>;\n}\n\nexport interface DelegationResult {\n\tagentType: string;\n\ttask: string;\n\toutput: string;\n\t/** Present for background work; pass this handle to retrieveDelegationResult. */\n\thandleId?: string;\n}\n\ninterface BackgroundDelegation {\n\tagentType: string;\n\tpromise: Promise<DelegationResult>;\n}\n\n// Results deliberately stay available for the lifetime of their parent runtime.\n// Phase 5 promises in-process retrieval only; restart durability belongs to Phase 6.\nconst backgroundByRuntime = new WeakMap<object, Map<string, BackgroundDelegation>>();\n\nfunction background(options: DelegationRuntimeOptions): Map<string, BackgroundDelegation> {\n\tlet value = backgroundByRuntime.get(options);\n\tif (!value) {\n\t\tvalue = new Map();\n\t\tbackgroundByRuntime.set(options, value);\n\t}\n\treturn value;\n}\n\n/**\n * Run one delegation to completion. Throws rather than returning a failure value,\n * matching this codebase's convention for model-facing routine failures (e.g.\n * `tool_schema`'s unknown-tool case, `web_search`'s unconfigured-backend case): a\n * thrown `Error` here is caught by the agent loop and surfaces as a normal,\n * model-readable `isError` tool result, not a fatal turn failure.\n *\n * The capability check is all-or-nothing by design (ceiling.ts): a definition\n * requesting a tool the parent's own capabilities cannot cover refuses the whole\n * delegation, naming the capability, rather than silently building a child missing\n * that one tool. `buildChildSession` is therefore never called for a refused\n * delegation -- there is no code path that produces a child holding a capability\n * outside the ceiling.\n *\n * The depth check (task 5.3) runs right after agent-type resolution and before the\n * capability check, so recursion is bounded regardless of what is being delegated --\n * a refusal at the bound still names the agent type, but never reaches the ceiling\n * or `buildChildSession`. `buildChildSession` receives the child's depth (parent + 1)\n * so the caller can record it on the child's own session header.\n */\nexport async function runDelegation(\n\toptions: DelegationRuntimeOptions,\n\tagentType: string,\n\ttask: string,\n\trequest: { background?: boolean } = {},\n): Promise<DelegationResult> {\n\tconst definition = options.resolveAgent(agentType);\n\tif (!definition) {\n\t\tthrow new Error(`Unknown agent type \"${agentType}\".`);\n\t}\n\n\tconst depth = options.getDelegationDepth();\n\tif (depth >= options.maxDelegationDepth) {\n\t\tthrow new Error(\n\t\t\t`Delegation depth limit (${options.maxDelegationDepth}) reached at depth ${depth}; cannot delegate to agent \"${agentType}\" further.`,\n\t\t);\n\t}\n\n\tconst requestedCapabilities = new Set<Capability>();\n\tfor (const toolName of definition.tools) {\n\t\tconst capabilities = options.getToolCapabilities(toolName);\n\t\tif (!capabilities) {\n\t\t\tthrow new Error(`Agent \"${agentType}\" requests unknown tool \"${toolName}\".`);\n\t\t}\n\t\tfor (const capability of capabilities) requestedCapabilities.add(capability);\n\t}\n\n\tconst ceiling = computeCapabilityCeiling(options.getParentCapabilities(), requestedCapabilities);\n\tif (!ceiling.allowed) {\n\t\tthrow new Error(\n\t\t\t`Delegating to agent \"${agentType}\" requires capability \"${ceiling.deniedCapability}\", which exceeds the parent's authority.`,\n\t\t);\n\t}\n\n\tconst sessionId = randomUUID();\n\tlet artifactDir: string | undefined;\n\tconst parentSessionDir = options.getParentSessionDir?.();\n\tif (parentSessionDir) {\n\t\tconst parentRoot = resolve(parentSessionDir);\n\t\tartifactDir = join(parentRoot, \"delegations\", sessionId);\n\t\tmkdirSync(artifactDir, { recursive: true });\n\t}\n\tconst child = await options.buildChildSession({\n\t\tagentType,\n\t\tdefinition,\n\t\ttoolNames: definition.tools,\n\t\tdepth: depth + 1,\n\t\tsessionId,\n\t\tartifactDir,\n\t});\n\tconst execute = async (): Promise<DelegationResult> => {\n\t\ttry {\n\t\t\tconst { output } = await child.run(task);\n\t\t\treturn { agentType, task, output };\n\t\t} finally {\n\t\t\tchild.dispose();\n\t\t}\n\t};\n\tif (!request.background) return execute();\n\tconst handleId = sessionId;\n\tconst promise = execute();\n\t// Retrieval owns propagation of a child failure; mark the background promise\n\t// observed now so a child that fails before retrieval does not become an\n\t// unhandled rejection.\n\tvoid promise.catch(() => {});\n\tbackground(options).set(handleId, { agentType, promise });\n\treturn { agentType, task, output: `Delegation started. Retrieve result with handle \"${handleId}\".`, handleId };\n}\n\n/** Retrieve a background delegation. Running children are awaited; unknown handles fail explicitly. */\nexport async function retrieveDelegationResult(\n\toptions: DelegationRuntimeOptions,\n\thandleId: string,\n\texpectedAgentType?: string,\n): Promise<DelegationResult> {\n\tconst entry = background(options).get(handleId);\n\tif (!entry) throw new Error(`Unknown delegation handle \"${handleId}\".`);\n\tif (expectedAgentType !== undefined && entry.agentType !== expectedAgentType) {\n\t\tthrow new Error(\n\t\t\t`Delegation handle \"${handleId}\" belongs to agent \"${entry.agentType}\", not \"${expectedAgentType}\".`,\n\t\t);\n\t}\n\treturn entry.promise;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/runtime.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAKH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAGvD,+HAA+H;AAC/H,MAAM,WAAW,eAAe;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,6KAA6K;IAC7K,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,8FAA8F;IAC9F,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,YAAY,EAAE,MAAM,CAAC;CACrB;AAED,gMAAgM;AAChM,MAAM,MAAM,uBAAuB,GAAG,CAAC,SAAS,EAAE,MAAM,KAAK,eAAe,GAAG,SAAS,CAAC;AAEzF,yEAAyE;AACzE,MAAM,WAAW,kBAAkB;IAClC,2EAA2E;IAC3E,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC/C,kFAAkF;IAClF,OAAO,IAAI,IAAI,CAAC;CAChB;AAED,MAAM,WAAW,wBAAwB;IACxC,SAAS,EAAE,MAAM,CA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AC,EAAE,MAAM,GACxB,OAAO,CAAC,gBAAgB,CAAC,CAS3B","sourcesContent":["/**\n * The delegation runtime (roadmap Phase 5, ADR 0008, task 5.2). Consumes the\n * capability ceiling (ceiling.ts) and a derived permission store\n * (`../permissions/store.ts`'s `DerivedPermissionRuleStore`) to run a real child\n * agent whose authority can never exceed its parent's.\n *\n * Agent definitions and child-session construction are both injected rather than\n * built in here: production agent discovery lives in `core/delegation/agents.ts`\n * (markdown + frontmatter, parsed on lookup) and plugs in through the same\n * resolver interface a test fixture implements; child-session construction is\n * injected so this module stays free of\n * `AgentSession`/`createAgentSession` and therefore free of the import cycle that\n * would create (`sdk.ts` already imports `agent-session.ts`).\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { mkdirSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport type { Capability } from \"../tools/contract.ts\";\nimport { computeCapabilityCeiling } from \"./ceiling.ts\";\n\n/** A delegatable agent's static configuration. Markdown + frontmatter in production (`agents.ts`); a plain object in tests. */\nexport interface AgentDefinition {\n\tname: string;\n\tdescription: string;\n\t/** Tool names this agent may use. Never trusted directly -- the runtime derives the actual child tool list from the computed capability set, not from this list verbatim. */\n\ttools: string[];\n\t/** Optional model id. Falls back to the parent's current model when unset or unresolvable. */\n\tmodel?: string;\n\tsystemPrompt: string;\n}\n\n/** Resolve an agent type to its definition, or `undefined` if unknown. Production implements this over markdown/frontmatter (`agents.ts`); tests inject plain functions with the same shape. */\nexport type AgentDefinitionResolver = (agentType: string) => AgentDefinition | undefined;\n\n/** A running or completed child, as far as the runtime needs to know. */\nexport interface ChildSessionHandle {\n\t/** Run the task to completion and return the child's final output text. */\n\trun(task: string): Promise<{ output: string }>;\n\t/** Release the child's resources. Always called, including after a failed run. */\n\tdispose(): void;\n}\n\nexport interface BuildChildSessionRequest {\n\tagentType: string;\n\tdefinition: AgentDefinition;\n\t/** The child's tool allowlist, already ceiling-checked -- exactly `definition.tools`, never narrowed. */\n\ttoolNames: string[];\n\t/** The child's own recursion depth (the parent's depth + 1), for the runtime constructing it to record on the child's session header (task 5.3). */\n\tdepth: number;\n\t/** Stable id used for the child session and its artifact directory. */\n\tsessionId: string;\n\t/** Per-child artifact root, created before the child session is constructed. */\n\tartifactDir?: string;\n}\n\nexport interface DelegationRuntimeOptions {\n\tresolveAgent: AgentDefinitionResolver;\n\t/** The parent's own effective capability set (its authority), unexpanded -- `exec` expansion happens inside the ceiling check, not here. */\n\tgetParentCapabilities: () => ReadonlySet<Capability>;\n\t/** Capability set a named tool requires, from the live registry. `undefined` for an unknown tool name. */\n\tgetToolCapabilities: (toolName: string) => ReadonlySet<Capability> | undefined;\n\t/** The parent session's own recursion depth (`SessionManager.getDelegationDepth()`), read fresh at delegation time. */\n\tgetDelegationDepth: () => number;\n\t/** Delegation is refused once `getDelegationDepth() >= maxDelegationDepth` -- assigned by the runtime, not by the tool, so the bound applies to any future delegation entry point. */\n\tmaxDelegationDepth: number;\n\t/** Parent session directory. When supplied, child artifacts are rooted beneath it. */\n\tgetParentSessionDir?: () => string;\n\tbuildChildSession: (request: BuildChildSessionRequest) => Promise<ChildSessionHandle>;\n}\n\nexport interface DelegationResult {\n\tagentType: string;\n\ttask: string;\n\toutput: string;\n\t/** Present for background work; pass this handle to retrieveDelegationResult. */\n\thandleId?: string;\n}\n\ninterface BackgroundDelegation {\n\tagentType: string;\n\tpromise: Promise<DelegationResult>;\n}\n\n// Results deliberately stay available for the lifetime of their parent runtime.\n// Phase 5 promises in-process retrieval only; restart durability belongs to Phase 6.\nconst backgroundByRuntime = new WeakMap<object, Map<string, BackgroundDelegation>>();\n\nfunction background(options: DelegationRuntimeOptions): Map<string, BackgroundDelegation> {\n\tlet value = backgroundByRuntime.get(options);\n\tif (!value) {\n\t\tvalue = new Map();\n\t\tbackgroundByRuntime.set(options, value);\n\t}\n\treturn value;\n}\n\n/**\n * Run one delegation to completion. Throws rather than returning a failure value,\n * matching this codebase's convention for model-facing routine failures (e.g.\n * `tool_schema`'s unknown-tool case, `web_search`'s unconfigured-backend case): a\n * thrown `Error` here is caught by the agent loop and surfaces as a normal,\n * model-readable `isError` tool result, not a fatal turn failure.\n *\n * The capability check is all-or-nothing by design (ceiling.ts): a definition\n * requesting a tool the parent's own capabilities cannot cover refuses the whole\n * delegation, naming the capability, rather than silently building a child missing\n * that one tool. `buildChildSession` is therefore never called for a refused\n * delegation -- there is no code path that produces a child holding a capability\n * outside the ceiling.\n *\n * The depth check (task 5.3) runs right after agent-type resolution and before the\n * capability check, so recursion is bounded regardless of what is being delegated --\n * a refusal at the bound still names the agent type, but never reaches the ceiling\n * or `buildChildSession`. `buildChildSession` receives the child's depth (parent + 1)\n * so the caller can record it on the child's own session header.\n */\nexport async function runDelegation(\n\toptions: DelegationRuntimeOptions,\n\tagentType: string,\n\ttask: string,\n\trequest: { background?: boolean } = {},\n): Promise<DelegationResult> {\n\tconst definition = options.resolveAgent(agentType);\n\tif (!definition) {\n\t\tthrow new Error(`Unknown agent type \"${agentType}\".`);\n\t}\n\n\tconst depth = options.getDelegationDepth();\n\tif (depth >= options.maxDelegationDepth) {\n\t\tthrow new Error(\n\t\t\t`Delegation depth limit (${options.maxDelegationDepth}) reached at depth ${depth}; cannot delegate to agent \"${agentType}\" further.`,\n\t\t);\n\t}\n\n\tconst requestedCapabilities = new Set<Capability>();\n\tfor (const toolName of definition.tools) {\n\t\tconst capabilities = options.getToolCapabilities(toolName);\n\t\tif (!capabilities) {\n\t\t\tthrow new Error(`Agent \"${agentType}\" requests unknown tool \"${toolName}\".`);\n\t\t}\n\t\tfor (const capability of capabilities) requestedCapabilities.add(capability);\n\t}\n\n\tconst ceiling = computeCapabilityCeiling(options.getParentCapabilities(), requestedCapabilities);\n\tif (!ceiling.allowed) {\n\t\tthrow new Error(\n\t\t\t`Delegating to agent \"${agentType}\" requires capability \"${ceiling.deniedCapability}\", which exceeds the parent's authority.`,\n\t\t);\n\t}\n\n\tconst sessionId = randomUUID();\n\tlet artifactDir: string | undefined;\n\tconst parentSessionDir = options.getParentSessionDir?.();\n\tif (parentSessionDir) {\n\t\tconst parentRoot = resolve(parentSessionDir);\n\t\tartifactDir = join(parentRoot, \"delegations\", sessionId);\n\t\tmkdirSync(artifactDir, { recursive: true });\n\t}\n\tconst child = await options.buildChildSession({\n\t\tagentType,\n\t\tdefinition,\n\t\ttoolNames: definition.tools,\n\t\tdepth: depth + 1,\n\t\tsessionId,\n\t\tartifactDir,\n\t});\n\tconst execute = async (): Promise<DelegationResult> => {\n\t\ttry {\n\t\t\tconst { output } = await child.run(task);\n\t\t\treturn { agentType, task, output };\n\t\t} finally {\n\t\t\tchild.dispose();\n\t\t}\n\t};\n\tif (!request.background) return execute();\n\tconst handleId = sessionId;\n\tconst promise = execute();\n\t// Retrieval owns propagation of a child failure; mark the background promise\n\t// observed now so a child that fails before retrieval does not become an\n\t// unhandled rejection.\n\tvoid promise.catch(() => {});\n\tbackground(options).set(handleId, { agentType, promise });\n\treturn { agentType, task, output: `Delegation started. Retrieve result with handle \"${handleId}\".`, handleId };\n}\n\n/** Retrieve a background delegation. Running children are awaited; unknown handles fail explicitly. */\nexport async function retrieveDelegationResult(\n\toptions: DelegationRuntimeOptions,\n\thandleId: string,\n\texpectedAgentType?: string,\n): Promise<DelegationResult> {\n\tconst entry = background(options).get(handleId);\n\tif (!entry) throw new Error(`Unknown delegation handle \"${handleId}\".`);\n\tif (expectedAgentType !== undefined && entry.agentType !== expectedAgentType) {\n\t\tthrow new Error(\n\t\t\t`Delegation handle \"${handleId}\" belongs to agent \"${entry.agentType}\", not \"${expectedAgentType}\".`,\n\t\t);\n\t}\n\treturn entry.promise;\n}\n"]}
|
|
@@ -5,9 +5,10 @@
|
|
|
5
5
|
* agent whose authority can never exceed its parent's.
|
|
6
6
|
*
|
|
7
7
|
* Agent definitions and child-session construction are both injected rather than
|
|
8
|
-
* built in here: agent discovery
|
|
9
|
-
* markdown
|
|
10
|
-
*
|
|
8
|
+
* built in here: production agent discovery lives in `core/delegation/agents.ts`
|
|
9
|
+
* (markdown + frontmatter, parsed on lookup) and plugs in through the same
|
|
10
|
+
* resolver interface a test fixture implements; child-session construction is
|
|
11
|
+
* injected so this module stays free of
|
|
11
12
|
* `AgentSession`/`createAgentSession` and therefore free of the import cycle that
|
|
12
13
|
* would create (`sdk.ts` already imports `agent-session.ts`).
|
|
13
14
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../../src/core/delegation/runtime.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAE1C,OAAO,EAAE,wBAAwB,EAAE,MAAM,cAAc,CAAC;AAiExD,gFAAgF;AAChF,qFAAqF;AACrF,MAAM,mBAAmB,GAAG,IAAI,OAAO,EAA6C,CAAC;AAErF,SAAS,UAAU,CAAC,OAAiC,EAAqC;IACzF,IAAI,KAAK,GAAG,mBAAmB,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAC7C,IAAI,CAAC,KAAK,EAAE,CAAC;QACZ,KAAK,GAAG,IAAI,GAAG,EAAE,CAAC;QAClB,mBAAmB,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IACzC,CAAC;IACD,OAAO,KAAK,CAAC;AAAA,CACb;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,CAAC,KAAK,UAAU,aAAa,CAClC,OAAiC,EACjC,SAAiB,EACjB,IAAY,EACZ,OAAO,GAA6B,EAAE,EACV;IAC5B,MAAM,UAAU,GAAG,OAAO,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;IACnD,IAAI,CAAC,UAAU,EAAE,CAAC;QACjB,MAAM,IAAI,KAAK,CAAC,uBAAuB,SAAS,IAAI,CAAC,CAAC;IACvD,CA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IAAI,KAAK,CAAC,8BAA8B,QAAQ,IAAI,CAAC,CAAC;IACxE,IAAI,iBAAiB,KAAK,SAAS,IAAI,KAAK,CAAC,SAAS,KAAK,iBAAiB,EAAE,CAAC;QAC9E,MAAM,IAAI,KAAK,CACd,sBAAsB,QAAQ,uBAAuB,KAAK,CAAC,SAAS,WAAW,iBAAiB,IAAI,CACpG,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAC,OAAO,CAAC;AAAA,CACrB","sourcesContent":["/**\n * The delegation runtime (roadmap Phase 5, ADR 0008, task 5.2). Consumes the\n * capability ceiling (ceiling.ts) and a derived permission store\n * (`../permissions/store.ts`'s `DerivedPermissionRuleStore`) to run a real child\n * agent whose authority can never exceed its parent's.\n *\n * Agent definitions and child-session construction are both injected rather than\n * built in here: agent discovery is a test fixture in this task and becomes real\n * markdown/frontmatter discovery in task 5.5 (`core/delegation/agents.ts`, not yet\n * written); child-session construction is injected so this module stays free of\n * `AgentSession`/`createAgentSession` and therefore free of the import cycle that\n * would create (`sdk.ts` already imports `agent-session.ts`).\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { mkdirSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport type { Capability } from \"../tools/contract.ts\";\nimport { computeCapabilityCeiling } from \"./ceiling.ts\";\n\n/** A delegatable agent's static configuration. Markdown + frontmatter in production (task 5.5); a plain object in tests until then. */\nexport interface AgentDefinition {\n\tname: string;\n\tdescription: string;\n\t/** Tool names this agent may use. Never trusted directly -- the runtime derives the actual child tool list from the computed capability set, not from this list verbatim. */\n\ttools: string[];\n\t/** Optional model id. Falls back to the parent's current model when unset or unresolvable. */\n\tmodel?: string;\n\tsystemPrompt: string;\n}\n\n/** Resolve an agent type to its definition, or `undefined` if unknown. A plain function fixture in this task; real markdown/frontmatter discovery (task 5.5) is just a different implementation of the same shape. */\nexport type AgentDefinitionResolver = (agentType: string) => AgentDefinition | undefined;\n\n/** A running or completed child, as far as the runtime needs to know. */\nexport interface ChildSessionHandle {\n\t/** Run the task to completion and return the child's final output text. */\n\trun(task: string): Promise<{ output: string }>;\n\t/** Release the child's resources. Always called, including after a failed run. */\n\tdispose(): void;\n}\n\nexport interface BuildChildSessionRequest {\n\tagentType: string;\n\tdefinition: AgentDefinition;\n\t/** The child's tool allowlist, already ceiling-checked -- exactly `definition.tools`, never narrowed. */\n\ttoolNames: string[];\n\t/** The child's own recursion depth (the parent's depth + 1), for the runtime constructing it to record on the child's session header (task 5.3). */\n\tdepth: number;\n\t/** Stable id used for the child session and its artifact directory. */\n\tsessionId: string;\n\t/** Per-child artifact root, created before the child session is constructed. */\n\tartifactDir?: string;\n}\n\nexport interface DelegationRuntimeOptions {\n\tresolveAgent: AgentDefinitionResolver;\n\t/** The parent's own effective capability set (its authority), unexpanded -- `exec` expansion happens inside the ceiling check, not here. */\n\tgetParentCapabilities: () => ReadonlySet<Capability>;\n\t/** Capability set a named tool requires, from the live registry. `undefined` for an unknown tool name. */\n\tgetToolCapabilities: (toolName: string) => ReadonlySet<Capability> | undefined;\n\t/** The parent session's own recursion depth (`SessionManager.getDelegationDepth()`), read fresh at delegation time. */\n\tgetDelegationDepth: () => number;\n\t/** Delegation is refused once `getDelegationDepth() >= maxDelegationDepth` -- assigned by the runtime, not by the tool, so the bound applies to any future delegation entry point. */\n\tmaxDelegationDepth: number;\n\t/** Parent session directory. When supplied, child artifacts are rooted beneath it. */\n\tgetParentSessionDir?: () => string;\n\tbuildChildSession: (request: BuildChildSessionRequest) => Promise<ChildSessionHandle>;\n}\n\nexport interface DelegationResult {\n\tagentType: string;\n\ttask: string;\n\toutput: string;\n\t/** Present for background work; pass this handle to retrieveDelegationResult. */\n\thandleId?: string;\n}\n\ninterface BackgroundDelegation {\n\tagentType: string;\n\tpromise: Promise<DelegationResult>;\n}\n\n// Results deliberately stay available for the lifetime of their parent runtime.\n// Phase 5 promises in-process retrieval only; restart durability belongs to Phase 6.\nconst backgroundByRuntime = new WeakMap<object, Map<string, BackgroundDelegation>>();\n\nfunction background(options: DelegationRuntimeOptions): Map<string, BackgroundDelegation> {\n\tlet value = backgroundByRuntime.get(options);\n\tif (!value) {\n\t\tvalue = new Map();\n\t\tbackgroundByRuntime.set(options, value);\n\t}\n\treturn value;\n}\n\n/**\n * Run one delegation to completion. Throws rather than returning a failure value,\n * matching this codebase's convention for model-facing routine failures (e.g.\n * `tool_schema`'s unknown-tool case, `web_search`'s unconfigured-backend case): a\n * thrown `Error` here is caught by the agent loop and surfaces as a normal,\n * model-readable `isError` tool result, not a fatal turn failure.\n *\n * The capability check is all-or-nothing by design (ceiling.ts): a definition\n * requesting a tool the parent's own capabilities cannot cover refuses the whole\n * delegation, naming the capability, rather than silently building a child missing\n * that one tool. `buildChildSession` is therefore never called for a refused\n * delegation -- there is no code path that produces a child holding a capability\n * outside the ceiling.\n *\n * The depth check (task 5.3) runs right after agent-type resolution and before the\n * capability check, so recursion is bounded regardless of what is being delegated --\n * a refusal at the bound still names the agent type, but never reaches the ceiling\n * or `buildChildSession`. `buildChildSession` receives the child's depth (parent + 1)\n * so the caller can record it on the child's own session header.\n */\nexport async function runDelegation(\n\toptions: DelegationRuntimeOptions,\n\tagentType: string,\n\ttask: string,\n\trequest: { background?: boolean } = {},\n): Promise<DelegationResult> {\n\tconst definition = options.resolveAgent(agentType);\n\tif (!definition) {\n\t\tthrow new Error(`Unknown agent type \"${agentType}\".`);\n\t}\n\n\tconst depth = options.getDelegationDepth();\n\tif (depth >= options.maxDelegationDepth) {\n\t\tthrow new Error(\n\t\t\t`Delegation depth limit (${options.maxDelegationDepth}) reached at depth ${depth}; cannot delegate to agent \"${agentType}\" further.`,\n\t\t);\n\t}\n\n\tconst requestedCapabilities = new Set<Capability>();\n\tfor (const toolName of definition.tools) {\n\t\tconst capabilities = options.getToolCapabilities(toolName);\n\t\tif (!capabilities) {\n\t\t\tthrow new Error(`Agent \"${agentType}\" requests unknown tool \"${toolName}\".`);\n\t\t}\n\t\tfor (const capability of capabilities) requestedCapabilities.add(capability);\n\t}\n\n\tconst ceiling = computeCapabilityCeiling(options.getParentCapabilities(), requestedCapabilities);\n\tif (!ceiling.allowed) {\n\t\tthrow new Error(\n\t\t\t`Delegating to agent \"${agentType}\" requires capability \"${ceiling.deniedCapability}\", which exceeds the parent's authority.`,\n\t\t);\n\t}\n\n\tconst sessionId = randomUUID();\n\tlet artifactDir: string | undefined;\n\tconst parentSessionDir = options.getParentSessionDir?.();\n\tif (parentSessionDir) {\n\t\tconst parentRoot = resolve(parentSessionDir);\n\t\tartifactDir = join(parentRoot, \"delegations\", sessionId);\n\t\tmkdirSync(artifactDir, { recursive: true });\n\t}\n\tconst child = await options.buildChildSession({\n\t\tagentType,\n\t\tdefinition,\n\t\ttoolNames: definition.tools,\n\t\tdepth: depth + 1,\n\t\tsessionId,\n\t\tartifactDir,\n\t});\n\tconst execute = async (): Promise<DelegationResult> => {\n\t\ttry {\n\t\t\tconst { output } = await child.run(task);\n\t\t\treturn { agentType, task, output };\n\t\t} finally {\n\t\t\tchild.dispose();\n\t\t}\n\t};\n\tif (!request.background) return execute();\n\tconst handleId = sessionId;\n\tconst promise = execute();\n\t// Retrieval owns propagation of a child failure; mark the background promise\n\t// observed now so a child that fails before retrieval does not become an\n\t// unhandled rejection.\n\tvoid promise.catch(() => {});\n\tbackground(options).set(handleId, { agentType, promise });\n\treturn { agentType, task, output: `Delegation started. Retrieve result with handle \"${handleId}\".`, handleId };\n}\n\n/** Retrieve a background delegation. Running children are awaited; unknown handles fail explicitly. */\nexport async function retrieveDelegationResult(\n\toptions: DelegationRuntimeOptions,\n\thandleId: string,\n\texpectedAgentType?: string,\n): Promise<DelegationResult> {\n\tconst entry = background(options).get(handleId);\n\tif (!entry) throw new Error(`Unknown delegation handle \"${handleId}\".`);\n\tif (expectedAgentType !== undefined && entry.agentType !== expectedAgentType) {\n\t\tthrow new Error(\n\t\t\t`Delegation handle \"${handleId}\" belongs to agent \"${entry.agentType}\", not \"${expectedAgentType}\".`,\n\t\t);\n\t}\n\treturn entry.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,iBAAiB,IAAI,CACpG,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAC,OAAO,CAAC;AAAA,CACrB","sourcesContent":["/**\n * The delegation runtime (roadmap Phase 5, ADR 0008, task 5.2). Consumes the\n * capability ceiling (ceiling.ts) and a derived permission store\n * (`../permissions/store.ts`'s `DerivedPermissionRuleStore`) to run a real child\n * agent whose authority can never exceed its parent's.\n *\n * Agent definitions and child-session construction are both injected rather than\n * built in here: production agent discovery lives in `core/delegation/agents.ts`\n * (markdown + frontmatter, parsed on lookup) and plugs in through the same\n * resolver interface a test fixture implements; child-session construction is\n * injected so this module stays free of\n * `AgentSession`/`createAgentSession` and therefore free of the import cycle that\n * would create (`sdk.ts` already imports `agent-session.ts`).\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { mkdirSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport type { Capability } from \"../tools/contract.ts\";\nimport { computeCapabilityCeiling } from \"./ceiling.ts\";\n\n/** A delegatable agent's static configuration. Markdown + frontmatter in production (`agents.ts`); a plain object in tests. */\nexport interface AgentDefinition {\n\tname: string;\n\tdescription: string;\n\t/** Tool names this agent may use. Never trusted directly -- the runtime derives the actual child tool list from the computed capability set, not from this list verbatim. */\n\ttools: string[];\n\t/** Optional model id. Falls back to the parent's current model when unset or unresolvable. */\n\tmodel?: string;\n\tsystemPrompt: string;\n}\n\n/** Resolve an agent type to its definition, or `undefined` if unknown. Production implements this over markdown/frontmatter (`agents.ts`); tests inject plain functions with the same shape. */\nexport type AgentDefinitionResolver = (agentType: string) => AgentDefinition | undefined;\n\n/** A running or completed child, as far as the runtime needs to know. */\nexport interface ChildSessionHandle {\n\t/** Run the task to completion and return the child's final output text. */\n\trun(task: string): Promise<{ output: string }>;\n\t/** Release the child's resources. Always called, including after a failed run. */\n\tdispose(): void;\n}\n\nexport interface BuildChildSessionRequest {\n\tagentType: string;\n\tdefinition: AgentDefinition;\n\t/** The child's tool allowlist, already ceiling-checked -- exactly `definition.tools`, never narrowed. */\n\ttoolNames: string[];\n\t/** The child's own recursion depth (the parent's depth + 1), for the runtime constructing it to record on the child's session header (task 5.3). */\n\tdepth: number;\n\t/** Stable id used for the child session and its artifact directory. */\n\tsessionId: string;\n\t/** Per-child artifact root, created before the child session is constructed. */\n\tartifactDir?: string;\n}\n\nexport interface DelegationRuntimeOptions {\n\tresolveAgent: AgentDefinitionResolver;\n\t/** The parent's own effective capability set (its authority), unexpanded -- `exec` expansion happens inside the ceiling check, not here. */\n\tgetParentCapabilities: () => ReadonlySet<Capability>;\n\t/** Capability set a named tool requires, from the live registry. `undefined` for an unknown tool name. */\n\tgetToolCapabilities: (toolName: string) => ReadonlySet<Capability> | undefined;\n\t/** The parent session's own recursion depth (`SessionManager.getDelegationDepth()`), read fresh at delegation time. */\n\tgetDelegationDepth: () => number;\n\t/** Delegation is refused once `getDelegationDepth() >= maxDelegationDepth` -- assigned by the runtime, not by the tool, so the bound applies to any future delegation entry point. */\n\tmaxDelegationDepth: number;\n\t/** Parent session directory. When supplied, child artifacts are rooted beneath it. */\n\tgetParentSessionDir?: () => string;\n\tbuildChildSession: (request: BuildChildSessionRequest) => Promise<ChildSessionHandle>;\n}\n\nexport interface DelegationResult {\n\tagentType: string;\n\ttask: string;\n\toutput: string;\n\t/** Present for background work; pass this handle to retrieveDelegationResult. */\n\thandleId?: string;\n}\n\ninterface BackgroundDelegation {\n\tagentType: string;\n\tpromise: Promise<DelegationResult>;\n}\n\n// Results deliberately stay available for the lifetime of their parent runtime.\n// Phase 5 promises in-process retrieval only; restart durability belongs to Phase 6.\nconst backgroundByRuntime = new WeakMap<object, Map<string, BackgroundDelegation>>();\n\nfunction background(options: DelegationRuntimeOptions): Map<string, BackgroundDelegation> {\n\tlet value = backgroundByRuntime.get(options);\n\tif (!value) {\n\t\tvalue = new Map();\n\t\tbackgroundByRuntime.set(options, value);\n\t}\n\treturn value;\n}\n\n/**\n * Run one delegation to completion. Throws rather than returning a failure value,\n * matching this codebase's convention for model-facing routine failures (e.g.\n * `tool_schema`'s unknown-tool case, `web_search`'s unconfigured-backend case): a\n * thrown `Error` here is caught by the agent loop and surfaces as a normal,\n * model-readable `isError` tool result, not a fatal turn failure.\n *\n * The capability check is all-or-nothing by design (ceiling.ts): a definition\n * requesting a tool the parent's own capabilities cannot cover refuses the whole\n * delegation, naming the capability, rather than silently building a child missing\n * that one tool. `buildChildSession` is therefore never called for a refused\n * delegation -- there is no code path that produces a child holding a capability\n * outside the ceiling.\n *\n * The depth check (task 5.3) runs right after agent-type resolution and before the\n * capability check, so recursion is bounded regardless of what is being delegated --\n * a refusal at the bound still names the agent type, but never reaches the ceiling\n * or `buildChildSession`. `buildChildSession` receives the child's depth (parent + 1)\n * so the caller can record it on the child's own session header.\n */\nexport async function runDelegation(\n\toptions: DelegationRuntimeOptions,\n\tagentType: string,\n\ttask: string,\n\trequest: { background?: boolean } = {},\n): Promise<DelegationResult> {\n\tconst definition = options.resolveAgent(agentType);\n\tif (!definition) {\n\t\tthrow new Error(`Unknown agent type \"${agentType}\".`);\n\t}\n\n\tconst depth = options.getDelegationDepth();\n\tif (depth >= options.maxDelegationDepth) {\n\t\tthrow new Error(\n\t\t\t`Delegation depth limit (${options.maxDelegationDepth}) reached at depth ${depth}; cannot delegate to agent \"${agentType}\" further.`,\n\t\t);\n\t}\n\n\tconst requestedCapabilities = new Set<Capability>();\n\tfor (const toolName of definition.tools) {\n\t\tconst capabilities = options.getToolCapabilities(toolName);\n\t\tif (!capabilities) {\n\t\t\tthrow new Error(`Agent \"${agentType}\" requests unknown tool \"${toolName}\".`);\n\t\t}\n\t\tfor (const capability of capabilities) requestedCapabilities.add(capability);\n\t}\n\n\tconst ceiling = computeCapabilityCeiling(options.getParentCapabilities(), requestedCapabilities);\n\tif (!ceiling.allowed) {\n\t\tthrow new Error(\n\t\t\t`Delegating to agent \"${agentType}\" requires capability \"${ceiling.deniedCapability}\", which exceeds the parent's authority.`,\n\t\t);\n\t}\n\n\tconst sessionId = randomUUID();\n\tlet artifactDir: string | undefined;\n\tconst parentSessionDir = options.getParentSessionDir?.();\n\tif (parentSessionDir) {\n\t\tconst parentRoot = resolve(parentSessionDir);\n\t\tartifactDir = join(parentRoot, \"delegations\", sessionId);\n\t\tmkdirSync(artifactDir, { recursive: true });\n\t}\n\tconst child = await options.buildChildSession({\n\t\tagentType,\n\t\tdefinition,\n\t\ttoolNames: definition.tools,\n\t\tdepth: depth + 1,\n\t\tsessionId,\n\t\tartifactDir,\n\t});\n\tconst execute = async (): Promise<DelegationResult> => {\n\t\ttry {\n\t\t\tconst { output } = await child.run(task);\n\t\t\treturn { agentType, task, output };\n\t\t} finally {\n\t\t\tchild.dispose();\n\t\t}\n\t};\n\tif (!request.background) return execute();\n\tconst handleId = sessionId;\n\tconst promise = execute();\n\t// Retrieval owns propagation of a child failure; mark the background promise\n\t// observed now so a child that fails before retrieval does not become an\n\t// unhandled rejection.\n\tvoid promise.catch(() => {});\n\tbackground(options).set(handleId, { agentType, promise });\n\treturn { agentType, task, output: `Delegation started. Retrieve result with handle \"${handleId}\".`, handleId };\n}\n\n/** Retrieve a background delegation. Running children are awaited; unknown handles fail explicitly. */\nexport async function retrieveDelegationResult(\n\toptions: DelegationRuntimeOptions,\n\thandleId: string,\n\texpectedAgentType?: string,\n): Promise<DelegationResult> {\n\tconst entry = background(options).get(handleId);\n\tif (!entry) throw new Error(`Unknown delegation handle \"${handleId}\".`);\n\tif (expectedAgentType !== undefined && entry.agentType !== expectedAgentType) {\n\t\tthrow new Error(\n\t\t\t`Delegation handle \"${handleId}\" belongs to agent \"${entry.agentType}\", not \"${expectedAgentType}\".`,\n\t\t);\n\t}\n\treturn entry.promise;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sqlite.d.ts","sourceRoot":"","sources":["../../../src/core/durable-state/sqlite.ts"],"names":[],"mappings":"AAGA,iEAAiE;AACjE,eAAO,MAAM,oCAAoC,IAAI,CAAC;AAEtD,MAAM,MAAM,mBAAmB,GAA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AAE,MAAM,CAAC;KACd,GAAG,kBAAkB,CAAC;IACvB,YAAY,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvD,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,kBAAkB,GAAG,SAAS,CAAC;IAC5D,sBAAsB,CAAC,GAAG,EAAE,mBAAmB,GAAG,IAAI,CAAC;IACvD,oBAAoB,IAAI,mBAAmB,EAAE,CAAC;IAC9C,qBAAqB,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,CAAC;IACpD,KAAK,IAAI,IAAI,CAAC;CACd;AA4HD,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,GAAG,iBAAiB,CAsPrE","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { DatabaseSync } from \"node:sqlite\";\n\n/** Current schema for the daemon-owned durable-state sidecar. */\nexport const CURRENT_DURABLE_STATE_SCHEMA_VERSION = 4;\n\nexport type CommandJournalState = \"created\" | \"running\" | \"completed\" | \"failed\" | \"interrupted\";\n\nexport type SessionLeaseMode = \"shared\" | \"exclusive\";\nexport interface SessionLeaseRecord {\n\tsessionId: string;\n\townerId: string;\n\tmode: SessionLeaseMode;\n\texpiresAt: string;\n}\n\nexport interface CommandJournalRecord {\n\tid: string;\n\tsessionId: string;\n\tcommand: string;\n\tstate: CommandJournalState;\n\tcreatedAt: string;\n\tupdatedAt: string;\n\trecoveryReason?: string;\n}\n\nconst COMMAND_TRANSITIONS: Record<CommandJournalState, readonly CommandJournalState[]> = {\n\tcreated: [\"running\", \"failed\", \"interrupted\"],\n\trunning: [\"completed\", \"failed\", \"interrupted\"],\n\tcompleted: [],\n\tfailed: [],\n\tinterrupted: [],\n};\n\nconst TABLES = [\n\t\"cache_entries\",\n\t\"command_journal\",\n\t\"daemon_metadata\",\n\t\"model_performance\",\n\t\"schema_migrations\",\n\t\"session_leases\",\n] as const;\n\n/** Columns added to `model_performance` in schema version 4 (roadmap Phase 8). */\nconst MODEL_PERFORMANCE_V4_COLUMNS: ReadonlyArray<readonly [string, string]> = [\n\t[\"session_id\", \"TEXT\"],\n\t[\"role\", \"TEXT\"],\n\t[\"credential_identity\", \"TEXT\"],\n\t[\"outcome\", \"TEXT\"],\n\t[\"failure_kind\", \"TEXT\"],\n\t[\"input_tokens\", \"INTEGER\"],\n\t[\"output_tokens\", \"INTEGER\"],\n\t[\"cache_read_tokens\", \"INTEGER\"],\n\t[\"cache_write_tokens\", \"INTEGER\"],\n\t[\"cost\", \"REAL\"],\n];\n\n/**\n * Plain, domain-independent row shape for `model_performance`. Deliberately not the\n * richer `UsagePerformanceSample` (which carries a branded `CredentialIdentity` and a\n * nested `usage` object) — this module owns SQLite schema and writes only, never\n * `ModelRuntime`'s domain types, to avoid a circular import between the two.\n */\nexport interface UsagePerformanceRow {\n\tprovider: string;\n\tmodelId: string;\n\tttftMs: number | null;\n\tgenerationMs: number | null;\n\tsampledAt: string;\n\tsessionId: string | null;\n\trole: string | null;\n\tcredentialIdentity: string | null;\n\toutcome: string | null;\n\tfailureKind: string | null;\n\tinputTokens: number | null;\n\toutputTokens: number | null;\n\tcacheReadTokens: number | null;\n\tcacheWriteTokens: number | null;\n\tcost: number | null;\n}\n\nexport interface RecoveryDiagnostic {\n\tcommandId: string;\n\tsessionId: string;\n\tpreviousState: \"created\" | \"running\";\n\tstate: \"interrupted\";\n\treason: string;\n\trecoveredAt: string;\n}\n\nexport interface DurableStateStore {\n\tschemaVersion(): number;\n\ttableNames(): string[];\n\tcolumns(tableName: string): string[];\n\tbeginCommand(input: { id?: string; sessionId: string; command: string }): CommandJournalRecord;\n\trunCommand<T>(input: { id?: string; sessionId: string; command: string }, operation: () => Promise<T>): Promise<T>;\n\ttransitionCommand(id: string, state: Exclude<CommandJournalState, \"created\">, reason?: string): CommandJournalRecord;\n\tgetCommand(id: string): CommandJournalRecord | undefined;\n\tcommandCount(): number;\n\trecoverUnfinishedCommands(reason?: string): CommandJournalRecord[];\n\trecoverUnfinishedCommandsWithDiagnostics(reason?: string): RecoveryDiagnostic[];\n\tacquireLease(input: {\n\t\tsessionId: string;\n\t\townerId: string;\n\t\tmode: SessionLeaseMode;\n\t\tttlMs: number;\n\t}): SessionLeaseRecord;\n\treleaseLease(sessionId: string, ownerId: string): void;\n\tgetLease(sessionId: string): SessionLeaseRecord | undefined;\n\trecordUsagePerformance(row: UsagePerformanceRow): void;\n\tlistUsagePerformance(): UsagePerformanceRow[];\n\tpruneUsagePerformance(olderThanIso: string): number;\n\tclose(): void;\n}\n\nfunction readSchemaVersion(database: DatabaseSync): number {\n\tconst row = database.prepare(\"SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations\").get() as\n\t\t| { version: number }\n\t\t| undefined;\n\treturn row?.version ?? 0;\n}\n\nfunction createSchema(database: DatabaseSync): void {\n\tdatabase.exec(`\n\t\tCREATE TABLE IF NOT EXISTS schema_migrations (\n\t\t\tversion INTEGER PRIMARY KEY,\n\t\t\tapplied_at TEXT NOT NULL\n\t\t);\n\t\tCREATE TABLE IF NOT EXISTS daemon_metadata (\n\t\t\tkey TEXT PRIMARY KEY,\n\t\t\tvalue TEXT NOT NULL\n\t\t);\n\t\tCREATE TABLE IF NOT EXISTS command_journal (\n\t\t\tid TEXT PRIMARY KEY,\n\t\t\tsession_id TEXT NOT NULL,\n\t\t\tcommand TEXT NOT NULL,\n\t\t\tstate TEXT NOT NULL,\n\t\t\trecovery_reason TEXT,\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\tupdated_at TEXT NOT NULL\n\t\t);\n\t\tCREATE TABLE IF NOT EXISTS session_leases (\n\t\t\tsession_id TEXT NOT NULL,\n\t\t\towner_id TEXT NOT NULL,\n\t\t\tmode TEXT NOT NULL,\n\t\t\texpires_at TEXT NOT NULL,\n\t\t\tPRIMARY KEY (session_id, owner_id)\n\t\t);\n\t\tCREATE TABLE IF NOT EXISTS model_performance (\n\t\t\tid INTEGER PRIMARY KEY,\n\t\t\tprovider TEXT NOT NULL,\n\t\t\tmodel_id TEXT NOT NULL,\n\t\t\tttft_ms REAL,\n\t\t\tgeneration_ms REAL,\n\t\t\tsampled_at TEXT NOT NULL,\n\t\t\tsession_id TEXT,\n\t\t\trole TEXT,\n\t\t\tcredential_identity TEXT,\n\t\t\toutcome TEXT,\n\t\t\tfailure_kind TEXT,\n\t\t\tinput_tokens INTEGER,\n\t\t\toutput_tokens INTEGER,\n\t\t\tcache_read_tokens INTEGER,\n\t\t\tcache_write_tokens INTEGER,\n\t\t\tcost REAL\n\t\t);\n\t\tCREATE TABLE IF NOT EXISTS cache_entries (\n\t\t\tkey TEXT PRIMARY KEY,\n\t\t\tvalue BLOB NOT NULL,\n\t\t\texpires_at TEXT\n\t\t);\n\t`);\n}\n\nfunction readCommand(database: DatabaseSync, id: string): CommandJournalRecord | undefined {\n\tconst row = database\n\t\t.prepare(\n\t\t\t\"SELECT id, session_id, command, state, recovery_reason, created_at, updated_at FROM command_journal WHERE id = ?\",\n\t\t)\n\t\t.get(id) as\n\t\t| {\n\t\t\t\tid: string;\n\t\t\t\tsession_id: string;\n\t\t\t\tcommand: string;\n\t\t\t\tstate: CommandJournalState;\n\t\t\t\trecovery_reason: string | null;\n\t\t\t\tcreated_at: string;\n\t\t\t\tupdated_at: string;\n\t\t }\n\t\t| undefined;\n\tif (!row) return undefined;\n\treturn {\n\t\tid: row.id,\n\t\tsessionId: row.session_id,\n\t\tcommand: row.command,\n\t\tstate: row.state,\n\t\tcreatedAt: row.created_at,\n\t\tupdatedAt: row.updated_at,\n\t\t...(row.recovery_reason ? { recoveryReason: row.recovery_reason } : {}),\n\t};\n}\n\nfunction readLeases(database: DatabaseSync, sessionId: string): SessionLeaseRecord[] {\n\tconst rows = database\n\t\t.prepare(\n\t\t\t\"SELECT session_id, owner_id, mode, expires_at FROM session_leases WHERE session_id = ? ORDER BY owner_id\",\n\t\t)\n\t\t.all(sessionId) as Array<{ session_id: string; owner_id: string; mode: SessionLeaseMode; expires_at: string }>;\n\treturn rows.map((row) => ({\n\t\tsessionId: row.session_id,\n\t\townerId: row.owner_id,\n\t\tmode: row.mode,\n\t\texpiresAt: row.expires_at,\n\t}));\n}\n\nfunction readLease(database: DatabaseSync, sessionId: string): SessionLeaseRecord | undefined {\n\treturn readLeases(database, sessionId)[0];\n}\n\nfunction transitionCommand(\n\tdatabase: DatabaseSync,\n\tid: string,\n\tstate: Exclude<CommandJournalState, \"created\">,\n\treason?: string,\n): CommandJournalRecord {\n\tconst current = readCommand(database, id);\n\tif (!current) throw new Error(`Unknown command journal entry: ${id}`);\n\tif (!COMMAND_TRANSITIONS[current.state].includes(state))\n\t\tthrow new Error(`Invalid command transition: ${current.state} -> ${state}`);\n\tconst now = new Date().toISOString();\n\tdatabase\n\t\t.prepare(\"UPDATE command_journal SET state = ?, recovery_reason = ?, updated_at = ? WHERE id = ?\")\n\t\t.run(state, reason ?? null, now, id);\n\treturn readCommand(database, id)!;\n}\n\nexport function openDurableStateStore(path: string): DurableStateStore {\n\tconst database = new DatabaseSync(path);\n\ttry {\n\t\tdatabase.exec(\"BEGIN IMMEDIATE\");\n\t\tcreateSchema(database);\n\t\tconst version = readSchemaVersion(database);\n\t\tif (version > CURRENT_DURABLE_STATE_SCHEMA_VERSION) {\n\t\t\tdatabase.exec(\"ROLLBACK\");\n\t\t\tthrow new Error(\n\t\t\t\t`Durable state database schema version ${version} is newer than this version (${CURRENT_DURABLE_STATE_SCHEMA_VERSION})`,\n\t\t\t);\n\t\t}\n\t\tif (version < 2) {\n\t\t\tconst commandColumns = database.prepare('PRAGMA table_info(\"command_journal\")').all() as Array<{\n\t\t\t\tname: string;\n\t\t\t}>;\n\t\t\tif (!commandColumns.some((column) => column.name === \"recovery_reason\"))\n\t\t\t\tdatabase.exec(\"ALTER TABLE command_journal ADD COLUMN recovery_reason TEXT\");\n\t\t}\n\t\tif (version < 3 && version > 0) {\n\t\t\tdatabase.exec(`\n\t\t\t\tALTER TABLE session_leases RENAME TO session_leases_v2;\n\t\t\t\tCREATE TABLE session_leases (\n\t\t\t\t\tsession_id TEXT NOT NULL,\n\t\t\t\t\towner_id TEXT NOT NULL,\n\t\t\t\t\tmode TEXT NOT NULL,\n\t\t\t\t\texpires_at TEXT NOT NULL,\n\t\t\t\t\tPRIMARY KEY (session_id, owner_id)\n\t\t\t\t);\n\t\t\t\tINSERT INTO session_leases (session_id, owner_id, mode, expires_at)\n\t\t\t\tSELECT session_id, owner_id, mode, expires_at FROM session_leases_v2;\n\t\t\t\tDROP TABLE session_leases_v2;\n\t\t\t`);\n\t\t}\n\t\tif (version < 4 && version > 0) {\n\t\t\tconst modelPerformanceColumns = database.prepare('PRAGMA table_info(\"model_performance\")').all() as Array<{\n\t\t\t\tname: string;\n\t\t\t}>;\n\t\t\tconst existingNames = new Set(modelPerformanceColumns.map((column) => column.name));\n\t\t\tfor (const [name, type] of MODEL_PERFORMANCE_V4_COLUMNS) {\n\t\t\t\tif (!existingNames.has(name)) database.exec(`ALTER TABLE model_performance ADD COLUMN ${name} ${type}`);\n\t\t\t}\n\t\t\tdatabase.exec(\"DROP TABLE IF EXISTS usage_totals\");\n\t\t}\n\t\tif (version < CURRENT_DURABLE_STATE_SCHEMA_VERSION) {\n\t\t\tdatabase\n\t\t\t\t.prepare(\"INSERT INTO schema_migrations (version, applied_at) VALUES (?, ?)\")\n\t\t\t\t.run(CURRENT_DURABLE_STATE_SCHEMA_VERSION, new Date().toISOString());\n\t\t}\n\t\tdatabase.exec(\"COMMIT\");\n\t} catch (error) {\n\t\ttry {\n\t\t\tdatabase.exec(\"ROLLBACK\");\n\t\t} catch {\n\t\t\t// Preserve the original migration error.\n\t\t}\n\t\tdatabase.close();\n\t\tthrow error;\n\t}\n\n\treturn {\n\t\tschemaVersion: () => readSchemaVersion(database),\n\t\ttableNames: () => {\n\t\t\tconst rows = database\n\t\t\t\t.prepare(\"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name\")\n\t\t\t\t.all() as Array<{ name: string }>;\n\t\t\treturn rows.map((row) => row.name);\n\t\t},\n\t\tcolumns: (tableName) => {\n\t\t\tif (!TABLES.includes(tableName as (typeof TABLES)[number]))\n\t\t\t\tthrow new Error(`Unknown durable-state table: ${tableName}`);\n\t\t\tconst rows = database.prepare(`PRAGMA table_info(\"${tableName}\")`).all() as Array<{ name: string }>;\n\t\t\treturn rows.map((row) => row.name);\n\t\t},\n\t\tbeginCommand: ({ id = randomUUID(), sessionId, command }) => {\n\t\t\tconst now = new Date().toISOString();\n\t\t\tdatabase\n\t\t\t\t.prepare(\n\t\t\t\t\t\"INSERT INTO command_journal (id, session_id, command, state, created_at, updated_at) VALUES (?, ?, ?, 'created', ?, ?)\",\n\t\t\t\t)\n\t\t\t\t.run(id, sessionId, command, now, now);\n\t\t\treturn readCommand(database, id)!;\n\t\t},\n\t\trunCommand: async (input, operation) => {\n\t\t\tconst entry = (() => {\n\t\t\t\tconst id = input.id ?? randomUUID();\n\t\t\t\tconst now = new Date().toISOString();\n\t\t\t\tdatabase\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\"INSERT INTO command_journal (id, session_id, command, state, created_at, updated_at) VALUES (?, ?, ?, 'created', ?, ?)\",\n\t\t\t\t\t)\n\t\t\t\t\t.run(id, input.sessionId, input.command, now, now);\n\t\t\t\treturn readCommand(database, id)!;\n\t\t\t})();\n\t\t\ttransitionCommand(database, entry.id, \"running\");\n\t\t\ttry {\n\t\t\t\tconst result = await operation();\n\t\t\t\ttransitionCommand(database, entry.id, \"completed\");\n\t\t\t\treturn result;\n\t\t\t} catch (error) {\n\t\t\t\ttransitionCommand(database, entry.id, \"failed\");\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\ttransitionCommand: (id, state, reason) => {\n\t\t\tconst current = readCommand(database, id);\n\t\t\tif (!current) throw new Error(`Unknown command journal entry: ${id}`);\n\t\t\tif (!COMMAND_TRANSITIONS[current.state].includes(state))\n\t\t\t\tthrow new Error(`Invalid command transition: ${current.state} -> ${state}`);\n\t\t\tconst now = new Date().toISOString();\n\t\t\tdatabase\n\t\t\t\t.prepare(\"UPDATE command_journal SET state = ?, recovery_reason = ?, updated_at = ? WHERE id = ?\")\n\t\t\t\t.run(state, reason ?? null, now, id);\n\t\t\treturn readCommand(database, id)!;\n\t\t},\n\t\tgetCommand: (id) => readCommand(database, id),\n\t\tcommandCount: () =>\n\t\t\t(database.prepare(\"SELECT COUNT(*) AS count FROM command_journal\").get() as { count: number }).count,\n\t\trecoverUnfinishedCommands: (reason = \"daemon restarted before command completion\") => {\n\t\t\tconst rows = database\n\t\t\t\t.prepare(\"SELECT id FROM command_journal WHERE state IN ('created', 'running')\")\n\t\t\t\t.all() as Array<{ id: string }>;\n\t\t\treturn rows.map(({ id }) => {\n\t\t\t\tconst current = readCommand(database, id)!;\n\t\t\t\treturn current.state === \"interrupted\" ? current : transitionCommand(database, id, \"interrupted\", reason);\n\t\t\t});\n\t\t},\n\t\trecoverUnfinishedCommandsWithDiagnostics: (reason = \"daemon restarted before command completion\") => {\n\t\t\tconst recoveredAt = new Date().toISOString();\n\t\t\tconst rows = database\n\t\t\t\t.prepare(\"SELECT id, session_id, state FROM command_journal WHERE state IN ('created', 'running')\")\n\t\t\t\t.all() as Array<{ id: string; session_id: string; state: \"created\" | \"running\" }>;\n\t\t\treturn rows.map((row) => {\n\t\t\t\ttransitionCommand(database, row.id, \"interrupted\", reason);\n\t\t\t\treturn {\n\t\t\t\t\tcommandId: row.id,\n\t\t\t\t\tsessionId: row.session_id,\n\t\t\t\t\tpreviousState: row.state,\n\t\t\t\t\tstate: \"interrupted\" as const,\n\t\t\t\t\treason,\n\t\t\t\t\trecoveredAt,\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\tacquireLease: ({ sessionId, ownerId, mode, ttlMs }) => {\n\t\t\tif (!Number.isFinite(ttlMs) || ttlMs <= 0) throw new Error(\"Lease TTL must be positive\");\n\t\t\tdatabase.exec(\"BEGIN IMMEDIATE\");\n\t\t\ttry {\n\t\t\t\tdatabase.prepare(\"DELETE FROM session_leases WHERE expires_at <= ?\").run(new Date().toISOString());\n\t\t\t\tconst active = readLeases(database, sessionId).filter((lease) => lease.ownerId !== ownerId);\n\t\t\t\tif (active.some((lease) => lease.mode === \"exclusive\") || (mode === \"exclusive\" && active.length > 0)) {\n\t\t\t\t\tthrow new Error(`Session lease is held for ${sessionId}`);\n\t\t\t\t}\n\t\t\t\tconst expiresAt = new Date(Date.now() + ttlMs).toISOString();\n\t\t\t\tdatabase\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\"INSERT INTO session_leases (session_id, owner_id, mode, expires_at) VALUES (?, ?, ?, ?) ON CONFLICT(session_id, owner_id) DO UPDATE SET mode=excluded.mode, expires_at=excluded.expires_at\",\n\t\t\t\t\t)\n\t\t\t\t\t.run(sessionId, ownerId, mode, expiresAt);\n\t\t\t\tdatabase.exec(\"COMMIT\");\n\t\t\t\treturn readLeases(database, sessionId).find((lease) => lease.ownerId === ownerId)!;\n\t\t\t} catch (error) {\n\t\t\t\tdatabase.exec(\"ROLLBACK\");\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\treleaseLease: (sessionId, ownerId) => {\n\t\t\tdatabase.prepare(\"DELETE FROM session_leases WHERE session_id = ? AND owner_id = ?\").run(sessionId, ownerId);\n\t\t},\n\t\tgetLease: (sessionId) => readLease(database, sessionId),\n\t\trecordUsagePerformance: (row) => {\n\t\t\tdatabase\n\t\t\t\t.prepare(\n\t\t\t\t\t`INSERT INTO model_performance (\n\t\t\t\t\t\tprovider, model_id, ttft_ms, generation_ms, sampled_at,\n\t\t\t\t\t\tsession_id, role, credential_identity, outcome, failure_kind,\n\t\t\t\t\t\tinput_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost\n\t\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n\t\t\t\t)\n\t\t\t\t.run(\n\t\t\t\t\trow.provider,\n\t\t\t\t\trow.modelId,\n\t\t\t\t\trow.ttftMs,\n\t\t\t\t\trow.generationMs,\n\t\t\t\t\trow.sampledAt,\n\t\t\t\t\trow.sessionId,\n\t\t\t\t\trow.role,\n\t\t\t\t\trow.credentialIdentity,\n\t\t\t\t\trow.outcome,\n\t\t\t\t\trow.failureKind,\n\t\t\t\t\trow.inputTokens,\n\t\t\t\t\trow.outputTokens,\n\t\t\t\t\trow.cacheReadTokens,\n\t\t\t\t\trow.cacheWriteTokens,\n\t\t\t\t\trow.cost,\n\t\t\t\t);\n\t\t},\n\t\tlistUsagePerformance: () =>\n\t\t\t(\n\t\t\t\tdatabase\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`SELECT provider, model_id, ttft_ms, generation_ms, sampled_at, session_id, role,\n\t\t\t\t\t\t\tcredential_identity, outcome, failure_kind, input_tokens, output_tokens,\n\t\t\t\t\t\t\tcache_read_tokens, cache_write_tokens, cost\n\t\t\t\t\t\tFROM model_performance ORDER BY id ASC`,\n\t\t\t\t\t)\n\t\t\t\t\t.all() as Array<{\n\t\t\t\t\tprovider: string;\n\t\t\t\t\tmodel_id: string;\n\t\t\t\t\tttft_ms: number | null;\n\t\t\t\t\tgeneration_ms: number | null;\n\t\t\t\t\tsampled_at: string;\n\t\t\t\t\tsession_id: string | null;\n\t\t\t\t\trole: string | null;\n\t\t\t\t\tcredential_identity: string | null;\n\t\t\t\t\toutcome: string | null;\n\t\t\t\t\tfailure_kind: string | null;\n\t\t\t\t\tinput_tokens: number | null;\n\t\t\t\t\toutput_tokens: number | null;\n\t\t\t\t\tcache_read_tokens: number | null;\n\t\t\t\t\tcache_write_tokens: number | null;\n\t\t\t\t\tcost: number | null;\n\t\t\t\t}>\n\t\t\t).map((row) => ({\n\t\t\t\tprovider: row.provider,\n\t\t\t\tmodelId: row.model_id,\n\t\t\t\tttftMs: row.ttft_ms,\n\t\t\t\tgenerationMs: row.generation_ms,\n\t\t\t\tsampledAt: row.sampled_at,\n\t\t\t\tsessionId: row.session_id,\n\t\t\t\trole: row.role,\n\t\t\t\tcredentialIdentity: row.credential_identity,\n\t\t\t\toutcome: row.outcome,\n\t\t\t\tfailureKind: row.failure_kind,\n\t\t\t\tinputTokens: row.input_tokens,\n\t\t\t\toutputTokens: row.output_tokens,\n\t\t\t\tcacheReadTokens: row.cache_read_tokens,\n\t\t\t\tcacheWriteTokens: row.cache_write_tokens,\n\t\t\t\tcost: row.cost,\n\t\t\t})),\n\t\tpruneUsagePerformance: (olderThanIso) => {\n\t\t\tconst result = database.prepare(\"DELETE FROM model_performance WHERE sampled_at < ?\").run(olderThanIso);\n\t\t\treturn Number(result.changes);\n\t\t},\n\t\tclose: () => database.close(),\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sqlite.d.ts","sourceRoot":"","sources":["../../../src/core/durable-state/sqlite.ts"],"names":[],"mappings":"AAkCA,iEAAiE;AACjE,eAAO,MAAM,oCAAoC,IAAI,CAAC;AAEtD,MAAM,MAAM,mBAAmB,GAAG,SAAS,GAAG,SAAS,GAAG,WAAW,GAAG,QAAQ,GAAG,aAAa,CAAC;AAEjG,MAAM,MAAM,gBAAgB,GAAG,QAAQ,GAAG,WAAW,CAAC;AACtD,MAAM,WAAW,kBAAkB;IAClC,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,gBAAgB,CAAC;IACvB,SAAS,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,oBAAoB;IACpC,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,mBAAmB,CAAC;IAC3B,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAiCD;;;;;GAKG;AACH,MAAM,WAAW,mBAAmB;IACnC,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,E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AM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IACnH,iBAAiB,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,mBAAmB,EAAE,SAAS,CAAC,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,oBAAoB,CAAC;IACrH,UAAU,CAAC,EAAE,EAAE,MAAM,GAAG,oBAAoB,GAAG,SAAS,CAAC;IACzD,YAAY,IAAI,MAAM,CAAC;IACvB,yBAAyB,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,oBAAoB,EAAE,CAAC;IACnE,wCAAwC,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,kBAAkB,EAAE,CAAC;IAChF,YAAY,CAAC,KAAK,EAAE;QACnB,SAAS,EAAE,MAAM,CAAC;QAClB,OAAO,EAAE,MAAM,CAAC;QAChB,IAAI,EAAE,gBAAgB,CAAC;QACvB,KAAK,EAAE,MAAM,CAAC;KACd,GAAG,kBAAkB,CAAC;IACvB,YAAY,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvD,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,kBAAkB,GAAG,SAAS,CAAC;IAC5D,sBAAsB,CAAC,GAAG,EAAE,mBAAmB,GAAG,IAAI,CAAC;IACvD,oBAAoB,IAAI,mBAAmB,EAAE,CAAC;IAC9C,qBAAqB,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,CAAC;IACpD,KAAK,IAAI,IAAI,CAAC;CACd;AA4HD,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,GAAG,iBAAiB,CAuPrE","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { createRequire } from \"node:module\";\nimport type { DatabaseSync } from \"node:sqlite\";\n\n/**\n * `bun build --compile` bundles this module into the standalone binary, and Bun does not\n * implement `node:sqlite` at all — not under `bun run`, not compiled. A static\n * `import { DatabaseSync } from \"node:sqlite\"` therefore breaks the standalone binary. Bun\n * ships its own `bun:sqlite`, whose `Database` exposes the same `.exec` / `.prepare(sql).get\n * /.all/.run` / `.close` surface this module relies on (verified directly against 1.3.14),\n * so the fix is to pick the binding at runtime rather than pull in either module statically.\n *\n * `createRequire` plus a runtime-computed specifier is load-bearing: it's what keeps this\n * `require(\"node:sqlite\")` call from being resolved when Bun bundles the compiled binary\n * (the branch is never taken under Bun, but the bundler would still try to resolve every\n * import it can see statically). A plain top-level `import` of either module — or a\n * dynamic `import()` with a literal specifier — does not get that exemption.\n */\nconst requireSqliteModule = createRequire(import.meta.url);\n\n/** The subset of `DatabaseSync` / `bun:sqlite`'s `Database` this module actually uses. */\ntype SqliteDatabaseConstructor = new (path: string) => DatabaseSync;\n\nfunction loadSqliteDatabaseConstructor(): SqliteDatabaseConstructor {\n\tif (typeof (globalThis as { Bun?: unknown }).Bun !== \"undefined\") {\n\t\tconst { Database } = requireSqliteModule(\"bun:sqlite\") as { Database: SqliteDatabaseConstructor };\n\t\treturn Database;\n\t}\n\tconst { DatabaseSync: NodeDatabaseSync } = requireSqliteModule(\"node:sqlite\") as {\n\t\tDatabaseSync: SqliteDatabaseConstructor;\n\t};\n\treturn NodeDatabaseSync;\n}\n\n/** Current schema for the daemon-owned durable-state sidecar. */\nexport const CURRENT_DURABLE_STATE_SCHEMA_VERSION = 4;\n\nexport type CommandJournalState = \"created\" | \"running\" | \"completed\" | \"failed\" | \"interrupted\";\n\nexport type SessionLeaseMode = \"shared\" | \"exclusive\";\nexport interface SessionLeaseRecord {\n\tsessionId: string;\n\townerId: string;\n\tmode: SessionLeaseMode;\n\texpiresAt: string;\n}\n\nexport interface CommandJournalRecord {\n\tid: string;\n\tsessionId: string;\n\tcommand: string;\n\tstate: CommandJournalState;\n\tcreatedAt: string;\n\tupdatedAt: string;\n\trecoveryReason?: string;\n}\n\nconst COMMAND_TRANSITIONS: Record<CommandJournalState, readonly CommandJournalState[]> = {\n\tcreated: [\"running\", \"failed\", \"interrupted\"],\n\trunning: [\"completed\", \"failed\", \"interrupted\"],\n\tcompleted: [],\n\tfailed: [],\n\tinterrupted: [],\n};\n\nconst TABLES = [\n\t\"cache_entries\",\n\t\"command_journal\",\n\t\"daemon_metadata\",\n\t\"model_performance\",\n\t\"schema_migrations\",\n\t\"session_leases\",\n] as const;\n\n/** Columns added to `model_performance` in schema version 4 (roadmap Phase 8). */\nconst MODEL_PERFORMANCE_V4_COLUMNS: ReadonlyArray<readonly [string, string]> = [\n\t[\"session_id\", \"TEXT\"],\n\t[\"role\", \"TEXT\"],\n\t[\"credential_identity\", \"TEXT\"],\n\t[\"outcome\", \"TEXT\"],\n\t[\"failure_kind\", \"TEXT\"],\n\t[\"input_tokens\", \"INTEGER\"],\n\t[\"output_tokens\", \"INTEGER\"],\n\t[\"cache_read_tokens\", \"INTEGER\"],\n\t[\"cache_write_tokens\", \"INTEGER\"],\n\t[\"cost\", \"REAL\"],\n];\n\n/**\n * Plain, domain-independent row shape for `model_performance`. Deliberately not the\n * richer `UsagePerformanceSample` (which carries a branded `CredentialIdentity` and a\n * nested `usage` object) — this module owns SQLite schema and writes only, never\n * `ModelRuntime`'s domain types, to avoid a circular import between the two.\n */\nexport interface UsagePerformanceRow {\n\tprovider: string;\n\tmodelId: string;\n\tttftMs: number | null;\n\tgenerationMs: number | null;\n\tsampledAt: string;\n\tsessionId: string | null;\n\trole: string | null;\n\tcredentialIdentity: string | null;\n\toutcome: string | null;\n\tfailureKind: string | null;\n\tinputTokens: number | null;\n\toutputTokens: number | null;\n\tcacheReadTokens: number | null;\n\tcacheWriteTokens: number | null;\n\tcost: number | null;\n}\n\nexport interface RecoveryDiagnostic {\n\tcommandId: string;\n\tsessionId: string;\n\tpreviousState: \"created\" | \"running\";\n\tstate: \"interrupted\";\n\treason: string;\n\trecoveredAt: string;\n}\n\nexport interface DurableStateStore {\n\tschemaVersion(): number;\n\ttableNames(): string[];\n\tcolumns(tableName: string): string[];\n\tbeginCommand(input: { id?: string; sessionId: string; command: string }): CommandJournalRecord;\n\trunCommand<T>(input: { id?: string; sessionId: string; command: string }, operation: () => Promise<T>): Promise<T>;\n\ttransitionCommand(id: string, state: Exclude<CommandJournalState, \"created\">, reason?: string): CommandJournalRecord;\n\tgetCommand(id: string): CommandJournalRecord | undefined;\n\tcommandCount(): number;\n\trecoverUnfinishedCommands(reason?: string): CommandJournalRecord[];\n\trecoverUnfinishedCommandsWithDiagnostics(reason?: string): RecoveryDiagnostic[];\n\tacquireLease(input: {\n\t\tsessionId: string;\n\t\townerId: string;\n\t\tmode: SessionLeaseMode;\n\t\tttlMs: number;\n\t}): SessionLeaseRecord;\n\treleaseLease(sessionId: string, ownerId: string): void;\n\tgetLease(sessionId: string): SessionLeaseRecord | undefined;\n\trecordUsagePerformance(row: UsagePerformanceRow): void;\n\tlistUsagePerformance(): UsagePerformanceRow[];\n\tpruneUsagePerformance(olderThanIso: string): number;\n\tclose(): void;\n}\n\nfunction readSchemaVersion(database: DatabaseSync): number {\n\tconst row = database.prepare(\"SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations\").get() as\n\t\t| { version: number }\n\t\t| undefined;\n\treturn row?.version ?? 0;\n}\n\nfunction createSchema(database: DatabaseSync): void {\n\tdatabase.exec(`\n\t\tCREATE TABLE IF NOT EXISTS schema_migrations (\n\t\t\tversion INTEGER PRIMARY KEY,\n\t\t\tapplied_at TEXT NOT NULL\n\t\t);\n\t\tCREATE TABLE IF NOT EXISTS daemon_metadata (\n\t\t\tkey TEXT PRIMARY KEY,\n\t\t\tvalue TEXT NOT NULL\n\t\t);\n\t\tCREATE TABLE IF NOT EXISTS command_journal (\n\t\t\tid TEXT PRIMARY KEY,\n\t\t\tsession_id TEXT NOT NULL,\n\t\t\tcommand TEXT NOT NULL,\n\t\t\tstate TEXT NOT NULL,\n\t\t\trecovery_reason TEXT,\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\tupdated_at TEXT NOT NULL\n\t\t);\n\t\tCREATE TABLE IF NOT EXISTS session_leases (\n\t\t\tsession_id TEXT NOT NULL,\n\t\t\towner_id TEXT NOT NULL,\n\t\t\tmode TEXT NOT NULL,\n\t\t\texpires_at TEXT NOT NULL,\n\t\t\tPRIMARY KEY (session_id, owner_id)\n\t\t);\n\t\tCREATE TABLE IF NOT EXISTS model_performance (\n\t\t\tid INTEGER PRIMARY KEY,\n\t\t\tprovider TEXT NOT NULL,\n\t\t\tmodel_id TEXT NOT NULL,\n\t\t\tttft_ms REAL,\n\t\t\tgeneration_ms REAL,\n\t\t\tsampled_at TEXT NOT NULL,\n\t\t\tsession_id TEXT,\n\t\t\trole TEXT,\n\t\t\tcredential_identity TEXT,\n\t\t\toutcome TEXT,\n\t\t\tfailure_kind TEXT,\n\t\t\tinput_tokens INTEGER,\n\t\t\toutput_tokens INTEGER,\n\t\t\tcache_read_tokens INTEGER,\n\t\t\tcache_write_tokens INTEGER,\n\t\t\tcost REAL\n\t\t);\n\t\tCREATE TABLE IF NOT EXISTS cache_entries (\n\t\t\tkey TEXT PRIMARY KEY,\n\t\t\tvalue BLOB NOT NULL,\n\t\t\texpires_at TEXT\n\t\t);\n\t`);\n}\n\nfunction readCommand(database: DatabaseSync, id: string): CommandJournalRecord | undefined {\n\tconst row = database\n\t\t.prepare(\n\t\t\t\"SELECT id, session_id, command, state, recovery_reason, created_at, updated_at FROM command_journal WHERE id = ?\",\n\t\t)\n\t\t.get(id) as\n\t\t| {\n\t\t\t\tid: string;\n\t\t\t\tsession_id: string;\n\t\t\t\tcommand: string;\n\t\t\t\tstate: CommandJournalState;\n\t\t\t\trecovery_reason: string | null;\n\t\t\t\tcreated_at: string;\n\t\t\t\tupdated_at: string;\n\t\t }\n\t\t| undefined;\n\tif (!row) return undefined;\n\treturn {\n\t\tid: row.id,\n\t\tsessionId: row.session_id,\n\t\tcommand: row.command,\n\t\tstate: row.state,\n\t\tcreatedAt: row.created_at,\n\t\tupdatedAt: row.updated_at,\n\t\t...(row.recovery_reason ? { recoveryReason: row.recovery_reason } : {}),\n\t};\n}\n\nfunction readLeases(database: DatabaseSync, sessionId: string): SessionLeaseRecord[] {\n\tconst rows = database\n\t\t.prepare(\n\t\t\t\"SELECT session_id, owner_id, mode, expires_at FROM session_leases WHERE session_id = ? ORDER BY owner_id\",\n\t\t)\n\t\t.all(sessionId) as Array<{ session_id: string; owner_id: string; mode: SessionLeaseMode; expires_at: string }>;\n\treturn rows.map((row) => ({\n\t\tsessionId: row.session_id,\n\t\townerId: row.owner_id,\n\t\tmode: row.mode,\n\t\texpiresAt: row.expires_at,\n\t}));\n}\n\nfunction readLease(database: DatabaseSync, sessionId: string): SessionLeaseRecord | undefined {\n\treturn readLeases(database, sessionId)[0];\n}\n\nfunction transitionCommand(\n\tdatabase: DatabaseSync,\n\tid: string,\n\tstate: Exclude<CommandJournalState, \"created\">,\n\treason?: string,\n): CommandJournalRecord {\n\tconst current = readCommand(database, id);\n\tif (!current) throw new Error(`Unknown command journal entry: ${id}`);\n\tif (!COMMAND_TRANSITIONS[current.state].includes(state))\n\t\tthrow new Error(`Invalid command transition: ${current.state} -> ${state}`);\n\tconst now = new Date().toISOString();\n\tdatabase\n\t\t.prepare(\"UPDATE command_journal SET state = ?, recovery_reason = ?, updated_at = ? WHERE id = ?\")\n\t\t.run(state, reason ?? null, now, id);\n\treturn readCommand(database, id)!;\n}\n\nexport function openDurableStateStore(path: string): DurableStateStore {\n\tconst Sqlite = loadSqliteDatabaseConstructor();\n\tconst database = new Sqlite(path);\n\ttry {\n\t\tdatabase.exec(\"BEGIN IMMEDIATE\");\n\t\tcreateSchema(database);\n\t\tconst version = readSchemaVersion(database);\n\t\tif (version > CURRENT_DURABLE_STATE_SCHEMA_VERSION) {\n\t\t\tdatabase.exec(\"ROLLBACK\");\n\t\t\tthrow new Error(\n\t\t\t\t`Durable state database schema version ${version} is newer than this version (${CURRENT_DURABLE_STATE_SCHEMA_VERSION})`,\n\t\t\t);\n\t\t}\n\t\tif (version < 2) {\n\t\t\tconst commandColumns = database.prepare('PRAGMA table_info(\"command_journal\")').all() as Array<{\n\t\t\t\tname: string;\n\t\t\t}>;\n\t\t\tif (!commandColumns.some((column) => column.name === \"recovery_reason\"))\n\t\t\t\tdatabase.exec(\"ALTER TABLE command_journal ADD COLUMN recovery_reason TEXT\");\n\t\t}\n\t\tif (version < 3 && version > 0) {\n\t\t\tdatabase.exec(`\n\t\t\t\tALTER TABLE session_leases RENAME TO session_leases_v2;\n\t\t\t\tCREATE TABLE session_leases (\n\t\t\t\t\tsession_id TEXT NOT NULL,\n\t\t\t\t\towner_id TEXT NOT NULL,\n\t\t\t\t\tmode TEXT NOT NULL,\n\t\t\t\t\texpires_at TEXT NOT NULL,\n\t\t\t\t\tPRIMARY KEY (session_id, owner_id)\n\t\t\t\t);\n\t\t\t\tINSERT INTO session_leases (session_id, owner_id, mode, expires_at)\n\t\t\t\tSELECT session_id, owner_id, mode, expires_at FROM session_leases_v2;\n\t\t\t\tDROP TABLE session_leases_v2;\n\t\t\t`);\n\t\t}\n\t\tif (version < 4 && version > 0) {\n\t\t\tconst modelPerformanceColumns = database.prepare('PRAGMA table_info(\"model_performance\")').all() as Array<{\n\t\t\t\tname: string;\n\t\t\t}>;\n\t\t\tconst existingNames = new Set(modelPerformanceColumns.map((column) => column.name));\n\t\t\tfor (const [name, type] of MODEL_PERFORMANCE_V4_COLUMNS) {\n\t\t\t\tif (!existingNames.has(name)) database.exec(`ALTER TABLE model_performance ADD COLUMN ${name} ${type}`);\n\t\t\t}\n\t\t\tdatabase.exec(\"DROP TABLE IF EXISTS usage_totals\");\n\t\t}\n\t\tif (version < CURRENT_DURABLE_STATE_SCHEMA_VERSION) {\n\t\t\tdatabase\n\t\t\t\t.prepare(\"INSERT INTO schema_migrations (version, applied_at) VALUES (?, ?)\")\n\t\t\t\t.run(CURRENT_DURABLE_STATE_SCHEMA_VERSION, new Date().toISOString());\n\t\t}\n\t\tdatabase.exec(\"COMMIT\");\n\t} catch (error) {\n\t\ttry {\n\t\t\tdatabase.exec(\"ROLLBACK\");\n\t\t} catch {\n\t\t\t// Preserve the original migration error.\n\t\t}\n\t\tdatabase.close();\n\t\tthrow error;\n\t}\n\n\treturn {\n\t\tschemaVersion: () => readSchemaVersion(database),\n\t\ttableNames: () => {\n\t\t\tconst rows = database\n\t\t\t\t.prepare(\"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name\")\n\t\t\t\t.all() as Array<{ name: string }>;\n\t\t\treturn rows.map((row) => row.name);\n\t\t},\n\t\tcolumns: (tableName) => {\n\t\t\tif (!TABLES.includes(tableName as (typeof TABLES)[number]))\n\t\t\t\tthrow new Error(`Unknown durable-state table: ${tableName}`);\n\t\t\tconst rows = database.prepare(`PRAGMA table_info(\"${tableName}\")`).all() as Array<{ name: string }>;\n\t\t\treturn rows.map((row) => row.name);\n\t\t},\n\t\tbeginCommand: ({ id = randomUUID(), sessionId, command }) => {\n\t\t\tconst now = new Date().toISOString();\n\t\t\tdatabase\n\t\t\t\t.prepare(\n\t\t\t\t\t\"INSERT INTO command_journal (id, session_id, command, state, created_at, updated_at) VALUES (?, ?, ?, 'created', ?, ?)\",\n\t\t\t\t)\n\t\t\t\t.run(id, sessionId, command, now, now);\n\t\t\treturn readCommand(database, id)!;\n\t\t},\n\t\trunCommand: async (input, operation) => {\n\t\t\tconst entry = (() => {\n\t\t\t\tconst id = input.id ?? randomUUID();\n\t\t\t\tconst now = new Date().toISOString();\n\t\t\t\tdatabase\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\"INSERT INTO command_journal (id, session_id, command, state, created_at, updated_at) VALUES (?, ?, ?, 'created', ?, ?)\",\n\t\t\t\t\t)\n\t\t\t\t\t.run(id, input.sessionId, input.command, now, now);\n\t\t\t\treturn readCommand(database, id)!;\n\t\t\t})();\n\t\t\ttransitionCommand(database, entry.id, \"running\");\n\t\t\ttry {\n\t\t\t\tconst result = await operation();\n\t\t\t\ttransitionCommand(database, entry.id, \"completed\");\n\t\t\t\treturn result;\n\t\t\t} catch (error) {\n\t\t\t\ttransitionCommand(database, entry.id, \"failed\");\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\ttransitionCommand: (id, state, reason) => {\n\t\t\tconst current = readCommand(database, id);\n\t\t\tif (!current) throw new Error(`Unknown command journal entry: ${id}`);\n\t\t\tif (!COMMAND_TRANSITIONS[current.state].includes(state))\n\t\t\t\tthrow new Error(`Invalid command transition: ${current.state} -> ${state}`);\n\t\t\tconst now = new Date().toISOString();\n\t\t\tdatabase\n\t\t\t\t.prepare(\"UPDATE command_journal SET state = ?, recovery_reason = ?, updated_at = ? WHERE id = ?\")\n\t\t\t\t.run(state, reason ?? null, now, id);\n\t\t\treturn readCommand(database, id)!;\n\t\t},\n\t\tgetCommand: (id) => readCommand(database, id),\n\t\tcommandCount: () =>\n\t\t\t(database.prepare(\"SELECT COUNT(*) AS count FROM command_journal\").get() as { count: number }).count,\n\t\trecoverUnfinishedCommands: (reason = \"daemon restarted before command completion\") => {\n\t\t\tconst rows = database\n\t\t\t\t.prepare(\"SELECT id FROM command_journal WHERE state IN ('created', 'running')\")\n\t\t\t\t.all() as Array<{ id: string }>;\n\t\t\treturn rows.map(({ id }) => {\n\t\t\t\tconst current = readCommand(database, id)!;\n\t\t\t\treturn current.state === \"interrupted\" ? current : transitionCommand(database, id, \"interrupted\", reason);\n\t\t\t});\n\t\t},\n\t\trecoverUnfinishedCommandsWithDiagnostics: (reason = \"daemon restarted before command completion\") => {\n\t\t\tconst recoveredAt = new Date().toISOString();\n\t\t\tconst rows = database\n\t\t\t\t.prepare(\"SELECT id, session_id, state FROM command_journal WHERE state IN ('created', 'running')\")\n\t\t\t\t.all() as Array<{ id: string; session_id: string; state: \"created\" | \"running\" }>;\n\t\t\treturn rows.map((row) => {\n\t\t\t\ttransitionCommand(database, row.id, \"interrupted\", reason);\n\t\t\t\treturn {\n\t\t\t\t\tcommandId: row.id,\n\t\t\t\t\tsessionId: row.session_id,\n\t\t\t\t\tpreviousState: row.state,\n\t\t\t\t\tstate: \"interrupted\" as const,\n\t\t\t\t\treason,\n\t\t\t\t\trecoveredAt,\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\tacquireLease: ({ sessionId, ownerId, mode, ttlMs }) => {\n\t\t\tif (!Number.isFinite(ttlMs) || ttlMs <= 0) throw new Error(\"Lease TTL must be positive\");\n\t\t\tdatabase.exec(\"BEGIN IMMEDIATE\");\n\t\t\ttry {\n\t\t\t\tdatabase.prepare(\"DELETE FROM session_leases WHERE expires_at <= ?\").run(new Date().toISOString());\n\t\t\t\tconst active = readLeases(database, sessionId).filter((lease) => lease.ownerId !== ownerId);\n\t\t\t\tif (active.some((lease) => lease.mode === \"exclusive\") || (mode === \"exclusive\" && active.length > 0)) {\n\t\t\t\t\tthrow new Error(`Session lease is held for ${sessionId}`);\n\t\t\t\t}\n\t\t\t\tconst expiresAt = new Date(Date.now() + ttlMs).toISOString();\n\t\t\t\tdatabase\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\"INSERT INTO session_leases (session_id, owner_id, mode, expires_at) VALUES (?, ?, ?, ?) ON CONFLICT(session_id, owner_id) DO UPDATE SET mode=excluded.mode, expires_at=excluded.expires_at\",\n\t\t\t\t\t)\n\t\t\t\t\t.run(sessionId, ownerId, mode, expiresAt);\n\t\t\t\tdatabase.exec(\"COMMIT\");\n\t\t\t\treturn readLeases(database, sessionId).find((lease) => lease.ownerId === ownerId)!;\n\t\t\t} catch (error) {\n\t\t\t\tdatabase.exec(\"ROLLBACK\");\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\treleaseLease: (sessionId, ownerId) => {\n\t\t\tdatabase.prepare(\"DELETE FROM session_leases WHERE session_id = ? AND owner_id = ?\").run(sessionId, ownerId);\n\t\t},\n\t\tgetLease: (sessionId) => readLease(database, sessionId),\n\t\trecordUsagePerformance: (row) => {\n\t\t\tdatabase\n\t\t\t\t.prepare(\n\t\t\t\t\t`INSERT INTO model_performance (\n\t\t\t\t\t\tprovider, model_id, ttft_ms, generation_ms, sampled_at,\n\t\t\t\t\t\tsession_id, role, credential_identity, outcome, failure_kind,\n\t\t\t\t\t\tinput_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost\n\t\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n\t\t\t\t)\n\t\t\t\t.run(\n\t\t\t\t\trow.provider,\n\t\t\t\t\trow.modelId,\n\t\t\t\t\trow.ttftMs,\n\t\t\t\t\trow.generationMs,\n\t\t\t\t\trow.sampledAt,\n\t\t\t\t\trow.sessionId,\n\t\t\t\t\trow.role,\n\t\t\t\t\trow.credentialIdentity,\n\t\t\t\t\trow.outcome,\n\t\t\t\t\trow.failureKind,\n\t\t\t\t\trow.inputTokens,\n\t\t\t\t\trow.outputTokens,\n\t\t\t\t\trow.cacheReadTokens,\n\t\t\t\t\trow.cacheWriteTokens,\n\t\t\t\t\trow.cost,\n\t\t\t\t);\n\t\t},\n\t\tlistUsagePerformance: () =>\n\t\t\t(\n\t\t\t\tdatabase\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`SELECT provider, model_id, ttft_ms, generation_ms, sampled_at, session_id, role,\n\t\t\t\t\t\t\tcredential_identity, outcome, failure_kind, input_tokens, output_tokens,\n\t\t\t\t\t\t\tcache_read_tokens, cache_write_tokens, cost\n\t\t\t\t\t\tFROM model_performance ORDER BY id ASC`,\n\t\t\t\t\t)\n\t\t\t\t\t.all() as Array<{\n\t\t\t\t\tprovider: string;\n\t\t\t\t\tmodel_id: string;\n\t\t\t\t\tttft_ms: number | null;\n\t\t\t\t\tgeneration_ms: number | null;\n\t\t\t\t\tsampled_at: string;\n\t\t\t\t\tsession_id: string | null;\n\t\t\t\t\trole: string | null;\n\t\t\t\t\tcredential_identity: string | null;\n\t\t\t\t\toutcome: string | null;\n\t\t\t\t\tfailure_kind: string | null;\n\t\t\t\t\tinput_tokens: number | null;\n\t\t\t\t\toutput_tokens: number | null;\n\t\t\t\t\tcache_read_tokens: number | null;\n\t\t\t\t\tcache_write_tokens: number | null;\n\t\t\t\t\tcost: number | null;\n\t\t\t\t}>\n\t\t\t).map((row) => ({\n\t\t\t\tprovider: row.provider,\n\t\t\t\tmodelId: row.model_id,\n\t\t\t\tttftMs: row.ttft_ms,\n\t\t\t\tgenerationMs: row.generation_ms,\n\t\t\t\tsampledAt: row.sampled_at,\n\t\t\t\tsessionId: row.session_id,\n\t\t\t\trole: row.role,\n\t\t\t\tcredentialIdentity: row.credential_identity,\n\t\t\t\toutcome: row.outcome,\n\t\t\t\tfailureKind: row.failure_kind,\n\t\t\t\tinputTokens: row.input_tokens,\n\t\t\t\toutputTokens: row.output_tokens,\n\t\t\t\tcacheReadTokens: row.cache_read_tokens,\n\t\t\t\tcacheWriteTokens: row.cache_write_tokens,\n\t\t\t\tcost: row.cost,\n\t\t\t})),\n\t\tpruneUsagePerformance: (olderThanIso) => {\n\t\t\tconst result = database.prepare(\"DELETE FROM model_performance WHERE sampled_at < ?\").run(olderThanIso);\n\t\t\treturn Number(result.changes);\n\t\t},\n\t\tclose: () => database.close(),\n\t};\n}\n"]}
|
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import {
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
/**
|
|
4
|
+
* `bun build --compile` bundles this module into the standalone binary, and Bun does not
|
|
5
|
+
* implement `node:sqlite` at all — not under `bun run`, not compiled. A static
|
|
6
|
+
* `import { DatabaseSync } from "node:sqlite"` therefore breaks the standalone binary. Bun
|
|
7
|
+
* ships its own `bun:sqlite`, whose `Database` exposes the same `.exec` / `.prepare(sql).get
|
|
8
|
+
* /.all/.run` / `.close` surface this module relies on (verified directly against 1.3.14),
|
|
9
|
+
* so the fix is to pick the binding at runtime rather than pull in either module statically.
|
|
10
|
+
*
|
|
11
|
+
* `createRequire` plus a runtime-computed specifier is load-bearing: it's what keeps this
|
|
12
|
+
* `require("node:sqlite")` call from being resolved when Bun bundles the compiled binary
|
|
13
|
+
* (the branch is never taken under Bun, but the bundler would still try to resolve every
|
|
14
|
+
* import it can see statically). A plain top-level `import` of either module — or a
|
|
15
|
+
* dynamic `import()` with a literal specifier — does not get that exemption.
|
|
16
|
+
*/
|
|
17
|
+
const requireSqliteModule = createRequire(import.meta.url);
|
|
18
|
+
function loadSqliteDatabaseConstructor() {
|
|
19
|
+
if (typeof globalThis.Bun !== "undefined") {
|
|
20
|
+
const { Database } = requireSqliteModule("bun:sqlite");
|
|
21
|
+
return Database;
|
|
22
|
+
}
|
|
23
|
+
const { DatabaseSync: NodeDatabaseSync } = requireSqliteModule("node:sqlite");
|
|
24
|
+
return NodeDatabaseSync;
|
|
25
|
+
}
|
|
3
26
|
/** Current schema for the daemon-owned durable-state sidecar. */
|
|
4
27
|
export const CURRENT_DURABLE_STATE_SCHEMA_VERSION = 4;
|
|
5
28
|
const COMMAND_TRANSITIONS = {
|
|
@@ -128,7 +151,8 @@ function transitionCommand(database, id, state, reason) {
|
|
|
128
151
|
return readCommand(database, id);
|
|
129
152
|
}
|
|
130
153
|
export function openDurableStateStore(path) {
|
|
131
|
-
const
|
|
154
|
+
const Sqlite = loadSqliteDatabaseConstructor();
|
|
155
|
+
const database = new Sqlite(path);
|
|
132
156
|
try {
|
|
133
157
|
database.exec("BEGIN IMMEDIATE");
|
|
134
158
|
createSchema(database);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sqlite.js","sourceRoot":"","sources":["../../../src/core/durable-state/sqlite.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3C,iEAAiE;AACjE,MAAM,CAAC,MAAM,oCAAoC,GAAG,CAAC,CAAC;AAsBtD,MAAM,mBAAmB,GAAgE;IACxF,OAAO,EAAE,CAAC,SAAS,EAAE,QAAQ,EAAE,aAAa,CAAC;IAC7C,OAAO,EAAE,CAAC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AS,EAAE,GAAG,CAAC,UAAU;YACzB,SAAS,EAAE,GAAG,CAAC,UAAU;YACzB,IAAI,EAAE,GAAG,CAAC,IAAI;YACd,kBAAkB,EAAE,GAAG,CAAC,mBAAmB;YAC3C,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,WAAW,EAAE,GAAG,CAAC,YAAY;YAC7B,WAAW,EAAE,GAAG,CAAC,YAAY;YAC7B,YAAY,EAAE,GAAG,CAAC,aAAa;YAC/B,eAAe,EAAE,GAAG,CAAC,iBAAiB;YACtC,gBAAgB,EAAE,GAAG,CAAC,kBAAkB;YACxC,IAAI,EAAE,GAAG,CAAC,IAAI;SACd,CAAC,CAAC;QACJ,qBAAqB,EAAE,CAAC,YAAY,EAAE,EAAE,CAAC;YACxC,MAAM,MAAM,GAAG,QAAQ,CAAC,OAAO,CAAC,oDAAoD,CAAC,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;YACxG,OAAO,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QAAA,CAC9B;QACD,KAAK,EAAE,GAAG,EAAE,CAAC,QAAQ,CAAC,KAAK,EAAE;KAC7B,CAAC;AAAA,CACF","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { DatabaseSync } from \"node:sqlite\";\n\n/** Current schema for the daemon-owned durable-state sidecar. */\nexport const CURRENT_DURABLE_STATE_SCHEMA_VERSION = 4;\n\nexport type CommandJournalState = \"created\" | \"running\" | \"completed\" | \"failed\" | \"interrupted\";\n\nexport type SessionLeaseMode = \"shared\" | \"exclusive\";\nexport interface SessionLeaseRecord {\n\tsessionId: string;\n\townerId: string;\n\tmode: SessionLeaseMode;\n\texpiresAt: string;\n}\n\nexport interface CommandJournalRecord {\n\tid: string;\n\tsessionId: string;\n\tcommand: string;\n\tstate: CommandJournalState;\n\tcreatedAt: string;\n\tupdatedAt: string;\n\trecoveryReason?: string;\n}\n\nconst COMMAND_TRANSITIONS: Record<CommandJournalState, readonly CommandJournalState[]> = {\n\tcreated: [\"running\", \"failed\", \"interrupted\"],\n\trunning: [\"completed\", \"failed\", \"interrupted\"],\n\tcompleted: [],\n\tfailed: [],\n\tinterrupted: [],\n};\n\nconst TABLES = [\n\t\"cache_entries\",\n\t\"command_journal\",\n\t\"daemon_metadata\",\n\t\"model_performance\",\n\t\"schema_migrations\",\n\t\"session_leases\",\n] as const;\n\n/** Columns added to `model_performance` in schema version 4 (roadmap Phase 8). */\nconst MODEL_PERFORMANCE_V4_COLUMNS: ReadonlyArray<readonly [string, string]> = [\n\t[\"session_id\", \"TEXT\"],\n\t[\"role\", \"TEXT\"],\n\t[\"credential_identity\", \"TEXT\"],\n\t[\"outcome\", \"TEXT\"],\n\t[\"failure_kind\", \"TEXT\"],\n\t[\"input_tokens\", \"INTEGER\"],\n\t[\"output_tokens\", \"INTEGER\"],\n\t[\"cache_read_tokens\", \"INTEGER\"],\n\t[\"cache_write_tokens\", \"INTEGER\"],\n\t[\"cost\", \"REAL\"],\n];\n\n/**\n * Plain, domain-independent row shape for `model_performance`. Deliberately not the\n * richer `UsagePerformanceSample` (which carries a branded `CredentialIdentity` and a\n * nested `usage` object) — this module owns SQLite schema and writes only, never\n * `ModelRuntime`'s domain types, to avoid a circular import between the two.\n */\nexport interface UsagePerformanceRow {\n\tprovider: string;\n\tmodelId: string;\n\tttftMs: number | null;\n\tgenerationMs: number | null;\n\tsampledAt: string;\n\tsessionId: string | null;\n\trole: string | null;\n\tcredentialIdentity: string | null;\n\toutcome: string | null;\n\tfailureKind: string | null;\n\tinputTokens: number | null;\n\toutputTokens: number | null;\n\tcacheReadTokens: number | null;\n\tcacheWriteTokens: number | null;\n\tcost: number | null;\n}\n\nexport interface RecoveryDiagnostic {\n\tcommandId: string;\n\tsessionId: string;\n\tpreviousState: \"created\" | \"running\";\n\tstate: \"interrupted\";\n\treason: string;\n\trecoveredAt: string;\n}\n\nexport interface DurableStateStore {\n\tschemaVersion(): number;\n\ttableNames(): string[];\n\tcolumns(tableName: string): string[];\n\tbeginCommand(input: { id?: string; sessionId: string; command: string }): CommandJournalRecord;\n\trunCommand<T>(input: { id?: string; sessionId: string; command: string }, operation: () => Promise<T>): Promise<T>;\n\ttransitionCommand(id: string, state: Exclude<CommandJournalState, \"created\">, reason?: string): CommandJournalRecord;\n\tgetCommand(id: string): CommandJournalRecord | undefined;\n\tcommandCount(): number;\n\trecoverUnfinishedCommands(reason?: string): CommandJournalRecord[];\n\trecoverUnfinishedCommandsWithDiagnostics(reason?: string): RecoveryDiagnostic[];\n\tacquireLease(input: {\n\t\tsessionId: string;\n\t\townerId: string;\n\t\tmode: SessionLeaseMode;\n\t\tttlMs: number;\n\t}): SessionLeaseRecord;\n\treleaseLease(sessionId: string, ownerId: string): void;\n\tgetLease(sessionId: string): SessionLeaseRecord | undefined;\n\trecordUsagePerformance(row: UsagePerformanceRow): void;\n\tlistUsagePerformance(): UsagePerformanceRow[];\n\tpruneUsagePerformance(olderThanIso: string): number;\n\tclose(): void;\n}\n\nfunction readSchemaVersion(database: DatabaseSync): number {\n\tconst row = database.prepare(\"SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations\").get() as\n\t\t| { version: number }\n\t\t| undefined;\n\treturn row?.version ?? 0;\n}\n\nfunction createSchema(database: DatabaseSync): void {\n\tdatabase.exec(`\n\t\tCREATE TABLE IF NOT EXISTS schema_migrations (\n\t\t\tversion INTEGER PRIMARY KEY,\n\t\t\tapplied_at TEXT NOT NULL\n\t\t);\n\t\tCREATE TABLE IF NOT EXISTS daemon_metadata (\n\t\t\tkey TEXT PRIMARY KEY,\n\t\t\tvalue TEXT NOT NULL\n\t\t);\n\t\tCREATE TABLE IF NOT EXISTS command_journal (\n\t\t\tid TEXT PRIMARY KEY,\n\t\t\tsession_id TEXT NOT NULL,\n\t\t\tcommand TEXT NOT NULL,\n\t\t\tstate TEXT NOT NULL,\n\t\t\trecovery_reason TEXT,\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\tupdated_at TEXT NOT NULL\n\t\t);\n\t\tCREATE TABLE IF NOT EXISTS session_leases (\n\t\t\tsession_id TEXT NOT NULL,\n\t\t\towner_id TEXT NOT NULL,\n\t\t\tmode TEXT NOT NULL,\n\t\t\texpires_at TEXT NOT NULL,\n\t\t\tPRIMARY KEY (session_id, owner_id)\n\t\t);\n\t\tCREATE TABLE IF NOT EXISTS model_performance (\n\t\t\tid INTEGER PRIMARY KEY,\n\t\t\tprovider TEXT NOT NULL,\n\t\t\tmodel_id TEXT NOT NULL,\n\t\t\tttft_ms REAL,\n\t\t\tgeneration_ms REAL,\n\t\t\tsampled_at TEXT NOT NULL,\n\t\t\tsession_id TEXT,\n\t\t\trole TEXT,\n\t\t\tcredential_identity TEXT,\n\t\t\toutcome TEXT,\n\t\t\tfailure_kind TEXT,\n\t\t\tinput_tokens INTEGER,\n\t\t\toutput_tokens INTEGER,\n\t\t\tcache_read_tokens INTEGER,\n\t\t\tcache_write_tokens INTEGER,\n\t\t\tcost REAL\n\t\t);\n\t\tCREATE TABLE IF NOT EXISTS cache_entries (\n\t\t\tkey TEXT PRIMARY KEY,\n\t\t\tvalue BLOB NOT NULL,\n\t\t\texpires_at TEXT\n\t\t);\n\t`);\n}\n\nfunction readCommand(database: DatabaseSync, id: string): CommandJournalRecord | undefined {\n\tconst row = database\n\t\t.prepare(\n\t\t\t\"SELECT id, session_id, command, state, recovery_reason, created_at, updated_at FROM command_journal WHERE id = ?\",\n\t\t)\n\t\t.get(id) as\n\t\t| {\n\t\t\t\tid: string;\n\t\t\t\tsession_id: string;\n\t\t\t\tcommand: string;\n\t\t\t\tstate: CommandJournalState;\n\t\t\t\trecovery_reason: string | null;\n\t\t\t\tcreated_at: string;\n\t\t\t\tupdated_at: string;\n\t\t }\n\t\t| undefined;\n\tif (!row) return undefined;\n\treturn {\n\t\tid: row.id,\n\t\tsessionId: row.session_id,\n\t\tcommand: row.command,\n\t\tstate: row.state,\n\t\tcreatedAt: row.created_at,\n\t\tupdatedAt: row.updated_at,\n\t\t...(row.recovery_reason ? { recoveryReason: row.recovery_reason } : {}),\n\t};\n}\n\nfunction readLeases(database: DatabaseSync, sessionId: string): SessionLeaseRecord[] {\n\tconst rows = database\n\t\t.prepare(\n\t\t\t\"SELECT session_id, owner_id, mode, expires_at FROM session_leases WHERE session_id = ? ORDER BY owner_id\",\n\t\t)\n\t\t.all(sessionId) as Array<{ session_id: string; owner_id: string; mode: SessionLeaseMode; expires_at: string }>;\n\treturn rows.map((row) => ({\n\t\tsessionId: row.session_id,\n\t\townerId: row.owner_id,\n\t\tmode: row.mode,\n\t\texpiresAt: row.expires_at,\n\t}));\n}\n\nfunction readLease(database: DatabaseSync, sessionId: string): SessionLeaseRecord | undefined {\n\treturn readLeases(database, sessionId)[0];\n}\n\nfunction transitionCommand(\n\tdatabase: DatabaseSync,\n\tid: string,\n\tstate: Exclude<CommandJournalState, \"created\">,\n\treason?: string,\n): CommandJournalRecord {\n\tconst current = readCommand(database, id);\n\tif (!current) throw new Error(`Unknown command journal entry: ${id}`);\n\tif (!COMMAND_TRANSITIONS[current.state].includes(state))\n\t\tthrow new Error(`Invalid command transition: ${current.state} -> ${state}`);\n\tconst now = new Date().toISOString();\n\tdatabase\n\t\t.prepare(\"UPDATE command_journal SET state = ?, recovery_reason = ?, updated_at = ? WHERE id = ?\")\n\t\t.run(state, reason ?? null, now, id);\n\treturn readCommand(database, id)!;\n}\n\nexport function openDurableStateStore(path: string): DurableStateStore {\n\tconst database = new DatabaseSync(path);\n\ttry {\n\t\tdatabase.exec(\"BEGIN IMMEDIATE\");\n\t\tcreateSchema(database);\n\t\tconst version = readSchemaVersion(database);\n\t\tif (version > CURRENT_DURABLE_STATE_SCHEMA_VERSION) {\n\t\t\tdatabase.exec(\"ROLLBACK\");\n\t\t\tthrow new Error(\n\t\t\t\t`Durable state database schema version ${version} is newer than this version (${CURRENT_DURABLE_STATE_SCHEMA_VERSION})`,\n\t\t\t);\n\t\t}\n\t\tif (version < 2) {\n\t\t\tconst commandColumns = database.prepare('PRAGMA table_info(\"command_journal\")').all() as Array<{\n\t\t\t\tname: string;\n\t\t\t}>;\n\t\t\tif (!commandColumns.some((column) => column.name === \"recovery_reason\"))\n\t\t\t\tdatabase.exec(\"ALTER TABLE command_journal ADD COLUMN recovery_reason TEXT\");\n\t\t}\n\t\tif (version < 3 && version > 0) {\n\t\t\tdatabase.exec(`\n\t\t\t\tALTER TABLE session_leases RENAME TO session_leases_v2;\n\t\t\t\tCREATE TABLE session_leases (\n\t\t\t\t\tsession_id TEXT NOT NULL,\n\t\t\t\t\towner_id TEXT NOT NULL,\n\t\t\t\t\tmode TEXT NOT NULL,\n\t\t\t\t\texpires_at TEXT NOT NULL,\n\t\t\t\t\tPRIMARY KEY (session_id, owner_id)\n\t\t\t\t);\n\t\t\t\tINSERT INTO session_leases (session_id, owner_id, mode, expires_at)\n\t\t\t\tSELECT session_id, owner_id, mode, expires_at FROM session_leases_v2;\n\t\t\t\tDROP TABLE session_leases_v2;\n\t\t\t`);\n\t\t}\n\t\tif (version < 4 && version > 0) {\n\t\t\tconst modelPerformanceColumns = database.prepare('PRAGMA table_info(\"model_performance\")').all() as Array<{\n\t\t\t\tname: string;\n\t\t\t}>;\n\t\t\tconst existingNames = new Set(modelPerformanceColumns.map((column) => column.name));\n\t\t\tfor (const [name, type] of MODEL_PERFORMANCE_V4_COLUMNS) {\n\t\t\t\tif (!existingNames.has(name)) database.exec(`ALTER TABLE model_performance ADD COLUMN ${name} ${type}`);\n\t\t\t}\n\t\t\tdatabase.exec(\"DROP TABLE IF EXISTS usage_totals\");\n\t\t}\n\t\tif (version < CURRENT_DURABLE_STATE_SCHEMA_VERSION) {\n\t\t\tdatabase\n\t\t\t\t.prepare(\"INSERT INTO schema_migrations (version, applied_at) VALUES (?, ?)\")\n\t\t\t\t.run(CURRENT_DURABLE_STATE_SCHEMA_VERSION, new Date().toISOString());\n\t\t}\n\t\tdatabase.exec(\"COMMIT\");\n\t} catch (error) {\n\t\ttry {\n\t\t\tdatabase.exec(\"ROLLBACK\");\n\t\t} catch {\n\t\t\t// Preserve the original migration error.\n\t\t}\n\t\tdatabase.close();\n\t\tthrow error;\n\t}\n\n\treturn {\n\t\tschemaVersion: () => readSchemaVersion(database),\n\t\ttableNames: () => {\n\t\t\tconst rows = database\n\t\t\t\t.prepare(\"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name\")\n\t\t\t\t.all() as Array<{ name: string }>;\n\t\t\treturn rows.map((row) => row.name);\n\t\t},\n\t\tcolumns: (tableName) => {\n\t\t\tif (!TABLES.includes(tableName as (typeof TABLES)[number]))\n\t\t\t\tthrow new Error(`Unknown durable-state table: ${tableName}`);\n\t\t\tconst rows = database.prepare(`PRAGMA table_info(\"${tableName}\")`).all() as Array<{ name: string }>;\n\t\t\treturn rows.map((row) => row.name);\n\t\t},\n\t\tbeginCommand: ({ id = randomUUID(), sessionId, command }) => {\n\t\t\tconst now = new Date().toISOString();\n\t\t\tdatabase\n\t\t\t\t.prepare(\n\t\t\t\t\t\"INSERT INTO command_journal (id, session_id, command, state, created_at, updated_at) VALUES (?, ?, ?, 'created', ?, ?)\",\n\t\t\t\t)\n\t\t\t\t.run(id, sessionId, command, now, now);\n\t\t\treturn readCommand(database, id)!;\n\t\t},\n\t\trunCommand: async (input, operation) => {\n\t\t\tconst entry = (() => {\n\t\t\t\tconst id = input.id ?? randomUUID();\n\t\t\t\tconst now = new Date().toISOString();\n\t\t\t\tdatabase\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\"INSERT INTO command_journal (id, session_id, command, state, created_at, updated_at) VALUES (?, ?, ?, 'created', ?, ?)\",\n\t\t\t\t\t)\n\t\t\t\t\t.run(id, input.sessionId, input.command, now, now);\n\t\t\t\treturn readCommand(database, id)!;\n\t\t\t})();\n\t\t\ttransitionCommand(database, entry.id, \"running\");\n\t\t\ttry {\n\t\t\t\tconst result = await operation();\n\t\t\t\ttransitionCommand(database, entry.id, \"completed\");\n\t\t\t\treturn result;\n\t\t\t} catch (error) {\n\t\t\t\ttransitionCommand(database, entry.id, \"failed\");\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\ttransitionCommand: (id, state, reason) => {\n\t\t\tconst current = readCommand(database, id);\n\t\t\tif (!current) throw new Error(`Unknown command journal entry: ${id}`);\n\t\t\tif (!COMMAND_TRANSITIONS[current.state].includes(state))\n\t\t\t\tthrow new Error(`Invalid command transition: ${current.state} -> ${state}`);\n\t\t\tconst now = new Date().toISOString();\n\t\t\tdatabase\n\t\t\t\t.prepare(\"UPDATE command_journal SET state = ?, recovery_reason = ?, updated_at = ? WHERE id = ?\")\n\t\t\t\t.run(state, reason ?? null, now, id);\n\t\t\treturn readCommand(database, id)!;\n\t\t},\n\t\tgetCommand: (id) => readCommand(database, id),\n\t\tcommandCount: () =>\n\t\t\t(database.prepare(\"SELECT COUNT(*) AS count FROM command_journal\").get() as { count: number }).count,\n\t\trecoverUnfinishedCommands: (reason = \"daemon restarted before command completion\") => {\n\t\t\tconst rows = database\n\t\t\t\t.prepare(\"SELECT id FROM command_journal WHERE state IN ('created', 'running')\")\n\t\t\t\t.all() as Array<{ id: string }>;\n\t\t\treturn rows.map(({ id }) => {\n\t\t\t\tconst current = readCommand(database, id)!;\n\t\t\t\treturn current.state === \"interrupted\" ? current : transitionCommand(database, id, \"interrupted\", reason);\n\t\t\t});\n\t\t},\n\t\trecoverUnfinishedCommandsWithDiagnostics: (reason = \"daemon restarted before command completion\") => {\n\t\t\tconst recoveredAt = new Date().toISOString();\n\t\t\tconst rows = database\n\t\t\t\t.prepare(\"SELECT id, session_id, state FROM command_journal WHERE state IN ('created', 'running')\")\n\t\t\t\t.all() as Array<{ id: string; session_id: string; state: \"created\" | \"running\" }>;\n\t\t\treturn rows.map((row) => {\n\t\t\t\ttransitionCommand(database, row.id, \"interrupted\", reason);\n\t\t\t\treturn {\n\t\t\t\t\tcommandId: row.id,\n\t\t\t\t\tsessionId: row.session_id,\n\t\t\t\t\tpreviousState: row.state,\n\t\t\t\t\tstate: \"interrupted\" as const,\n\t\t\t\t\treason,\n\t\t\t\t\trecoveredAt,\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\tacquireLease: ({ sessionId, ownerId, mode, ttlMs }) => {\n\t\t\tif (!Number.isFinite(ttlMs) || ttlMs <= 0) throw new Error(\"Lease TTL must be positive\");\n\t\t\tdatabase.exec(\"BEGIN IMMEDIATE\");\n\t\t\ttry {\n\t\t\t\tdatabase.prepare(\"DELETE FROM session_leases WHERE expires_at <= ?\").run(new Date().toISOString());\n\t\t\t\tconst active = readLeases(database, sessionId).filter((lease) => lease.ownerId !== ownerId);\n\t\t\t\tif (active.some((lease) => lease.mode === \"exclusive\") || (mode === \"exclusive\" && active.length > 0)) {\n\t\t\t\t\tthrow new Error(`Session lease is held for ${sessionId}`);\n\t\t\t\t}\n\t\t\t\tconst expiresAt = new Date(Date.now() + ttlMs).toISOString();\n\t\t\t\tdatabase\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\"INSERT INTO session_leases (session_id, owner_id, mode, expires_at) VALUES (?, ?, ?, ?) ON CONFLICT(session_id, owner_id) DO UPDATE SET mode=excluded.mode, expires_at=excluded.expires_at\",\n\t\t\t\t\t)\n\t\t\t\t\t.run(sessionId, ownerId, mode, expiresAt);\n\t\t\t\tdatabase.exec(\"COMMIT\");\n\t\t\t\treturn readLeases(database, sessionId).find((lease) => lease.ownerId === ownerId)!;\n\t\t\t} catch (error) {\n\t\t\t\tdatabase.exec(\"ROLLBACK\");\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\treleaseLease: (sessionId, ownerId) => {\n\t\t\tdatabase.prepare(\"DELETE FROM session_leases WHERE session_id = ? AND owner_id = ?\").run(sessionId, ownerId);\n\t\t},\n\t\tgetLease: (sessionId) => readLease(database, sessionId),\n\t\trecordUsagePerformance: (row) => {\n\t\t\tdatabase\n\t\t\t\t.prepare(\n\t\t\t\t\t`INSERT INTO model_performance (\n\t\t\t\t\t\tprovider, model_id, ttft_ms, generation_ms, sampled_at,\n\t\t\t\t\t\tsession_id, role, credential_identity, outcome, failure_kind,\n\t\t\t\t\t\tinput_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost\n\t\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n\t\t\t\t)\n\t\t\t\t.run(\n\t\t\t\t\trow.provider,\n\t\t\t\t\trow.modelId,\n\t\t\t\t\trow.ttftMs,\n\t\t\t\t\trow.generationMs,\n\t\t\t\t\trow.sampledAt,\n\t\t\t\t\trow.sessionId,\n\t\t\t\t\trow.role,\n\t\t\t\t\trow.credentialIdentity,\n\t\t\t\t\trow.outcome,\n\t\t\t\t\trow.failureKind,\n\t\t\t\t\trow.inputTokens,\n\t\t\t\t\trow.outputTokens,\n\t\t\t\t\trow.cacheReadTokens,\n\t\t\t\t\trow.cacheWriteTokens,\n\t\t\t\t\trow.cost,\n\t\t\t\t);\n\t\t},\n\t\tlistUsagePerformance: () =>\n\t\t\t(\n\t\t\t\tdatabase\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`SELECT provider, model_id, ttft_ms, generation_ms, sampled_at, session_id, role,\n\t\t\t\t\t\t\tcredential_identity, outcome, failure_kind, input_tokens, output_tokens,\n\t\t\t\t\t\t\tcache_read_tokens, cache_write_tokens, cost\n\t\t\t\t\t\tFROM model_performance ORDER BY id ASC`,\n\t\t\t\t\t)\n\t\t\t\t\t.all() as Array<{\n\t\t\t\t\tprovider: string;\n\t\t\t\t\tmodel_id: string;\n\t\t\t\t\tttft_ms: number | null;\n\t\t\t\t\tgeneration_ms: number | null;\n\t\t\t\t\tsampled_at: string;\n\t\t\t\t\tsession_id: string | null;\n\t\t\t\t\trole: string | null;\n\t\t\t\t\tcredential_identity: string | null;\n\t\t\t\t\toutcome: string | null;\n\t\t\t\t\tfailure_kind: string | null;\n\t\t\t\t\tinput_tokens: number | null;\n\t\t\t\t\toutput_tokens: number | null;\n\t\t\t\t\tcache_read_tokens: number | null;\n\t\t\t\t\tcache_write_tokens: number | null;\n\t\t\t\t\tcost: number | null;\n\t\t\t\t}>\n\t\t\t).map((row) => ({\n\t\t\t\tprovider: row.provider,\n\t\t\t\tmodelId: row.model_id,\n\t\t\t\tttftMs: row.ttft_ms,\n\t\t\t\tgenerationMs: row.generation_ms,\n\t\t\t\tsampledAt: row.sampled_at,\n\t\t\t\tsessionId: row.session_id,\n\t\t\t\trole: row.role,\n\t\t\t\tcredentialIdentity: row.credential_identity,\n\t\t\t\toutcome: row.outcome,\n\t\t\t\tfailureKind: row.failure_kind,\n\t\t\t\tinputTokens: row.input_tokens,\n\t\t\t\toutputTokens: row.output_tokens,\n\t\t\t\tcacheReadTokens: row.cache_read_tokens,\n\t\t\t\tcacheWriteTokens: row.cache_write_tokens,\n\t\t\t\tcost: row.cost,\n\t\t\t})),\n\t\tpruneUsagePerformance: (olderThanIso) => {\n\t\t\tconst result = database.prepare(\"DELETE FROM model_performance WHERE sampled_at < ?\").run(olderThanIso);\n\t\t\treturn Number(result.changes);\n\t\t},\n\t\tclose: () => database.close(),\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sqlite.js","sourceRoot":"","sources":["../../../src/core/durable-state/sqlite.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAG5C;;;;;;;;;;;;;GAaG;AACH,MAAM,mBAAmB,GAAG,aAAa,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;AAK3D,SAAS,6BAA6B,GAA8B;IACnE,IAAI,OAAQ,UAAgC,CAAC,GAAG,KAAK,WAAW,EAAE,CAAC;QAClE,MAAM,EAAE,QAAQ,EAAE,GAAG,mBAAmB,CAAC,YAAY,CAA4C,CAAC;QAClG,OAAO,QAAQ,CAAC;IACjB,CAAC;IACD,MAAM,EAAE,YAAY,EAAE,gBAAgB,EAAE,GAAG,mBAAmB,CAAC,aAAa,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CAEzB,QAAQ;aACN,OAAO,CACP;;;6CAGuC,CACvC;aACA,GAAG,EAiBL,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;YACf,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,OAAO,EAAE,GAAG,CAAC,QAAQ;YACrB,MAAM,EAAE,GAAG,CAAC,OAAO;YACnB,YAAY,EAAE,GAAG,CAAC,aAAa;YAC/B,SAAS,EAAE,GAAG,CAAC,UAAU;YACzB,SAAS,EAAE,GAAG,CAAC,UAAU;YACzB,IAAI,EAAE,GAAG,CAAC,IAAI;YACd,kBAAkB,EAAE,GAAG,CAAC,mBAAmB;YAC3C,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,WAAW,EAAE,GAAG,CAAC,YAAY;YAC7B,WAAW,EAAE,GAAG,CAAC,YAAY;YAC7B,YAAY,EAAE,GAAG,CAAC,aAAa;YAC/B,eAAe,EAAE,GAAG,CAAC,iBAAiB;YACtC,gBAAgB,EAAE,GAAG,CAAC,kBAAkB;YACxC,IAAI,EAAE,GAAG,CAAC,IAAI;SACd,CAAC,CAAC;QACJ,qBAAqB,EAAE,CAAC,YAAY,EAAE,EAAE,CAAC;YACxC,MAAM,MAAM,GAAG,QAAQ,CAAC,OAAO,CAAC,oDAAoD,CAAC,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;YACxG,OAAO,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QAAA,CAC9B;QACD,KAAK,EAAE,GAAG,EAAE,CAAC,QAAQ,CAAC,KAAK,EAAE;KAC7B,CAAC;AAAA,CACF","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { createRequire } from \"node:module\";\nimport type { DatabaseSync } from \"node:sqlite\";\n\n/**\n * `bun build --compile` bundles this module into the standalone binary, and Bun does not\n * implement `node:sqlite` at all — not under `bun run`, not compiled. A static\n * `import { DatabaseSync } from \"node:sqlite\"` therefore breaks the standalone binary. Bun\n * ships its own `bun:sqlite`, whose `Database` exposes the same `.exec` / `.prepare(sql).get\n * /.all/.run` / `.close` surface this module relies on (verified directly against 1.3.14),\n * so the fix is to pick the binding at runtime rather than pull in either module statically.\n *\n * `createRequire` plus a runtime-computed specifier is load-bearing: it's what keeps this\n * `require(\"node:sqlite\")` call from being resolved when Bun bundles the compiled binary\n * (the branch is never taken under Bun, but the bundler would still try to resolve every\n * import it can see statically). A plain top-level `import` of either module — or a\n * dynamic `import()` with a literal specifier — does not get that exemption.\n */\nconst requireSqliteModule = createRequire(import.meta.url);\n\n/** The subset of `DatabaseSync` / `bun:sqlite`'s `Database` this module actually uses. */\ntype SqliteDatabaseConstructor = new (path: string) => DatabaseSync;\n\nfunction loadSqliteDatabaseConstructor(): SqliteDatabaseConstructor {\n\tif (typeof (globalThis as { Bun?: unknown }).Bun !== \"undefined\") {\n\t\tconst { Database } = requireSqliteModule(\"bun:sqlite\") as { Database: SqliteDatabaseConstructor };\n\t\treturn Database;\n\t}\n\tconst { DatabaseSync: NodeDatabaseSync } = requireSqliteModule(\"node:sqlite\") as {\n\t\tDatabaseSync: SqliteDatabaseConstructor;\n\t};\n\treturn NodeDatabaseSync;\n}\n\n/** Current schema for the daemon-owned durable-state sidecar. */\nexport const CURRENT_DURABLE_STATE_SCHEMA_VERSION = 4;\n\nexport type CommandJournalState = \"created\" | \"running\" | \"completed\" | \"failed\" | \"interrupted\";\n\nexport type SessionLeaseMode = \"shared\" | \"exclusive\";\nexport interface SessionLeaseRecord {\n\tsessionId: string;\n\townerId: string;\n\tmode: SessionLeaseMode;\n\texpiresAt: string;\n}\n\nexport interface CommandJournalRecord {\n\tid: string;\n\tsessionId: string;\n\tcommand: string;\n\tstate: CommandJournalState;\n\tcreatedAt: string;\n\tupdatedAt: string;\n\trecoveryReason?: string;\n}\n\nconst COMMAND_TRANSITIONS: Record<CommandJournalState, readonly CommandJournalState[]> = {\n\tcreated: [\"running\", \"failed\", \"interrupted\"],\n\trunning: [\"completed\", \"failed\", \"interrupted\"],\n\tcompleted: [],\n\tfailed: [],\n\tinterrupted: [],\n};\n\nconst TABLES = [\n\t\"cache_entries\",\n\t\"command_journal\",\n\t\"daemon_metadata\",\n\t\"model_performance\",\n\t\"schema_migrations\",\n\t\"session_leases\",\n] as const;\n\n/** Columns added to `model_performance` in schema version 4 (roadmap Phase 8). */\nconst MODEL_PERFORMANCE_V4_COLUMNS: ReadonlyArray<readonly [string, string]> = [\n\t[\"session_id\", \"TEXT\"],\n\t[\"role\", \"TEXT\"],\n\t[\"credential_identity\", \"TEXT\"],\n\t[\"outcome\", \"TEXT\"],\n\t[\"failure_kind\", \"TEXT\"],\n\t[\"input_tokens\", \"INTEGER\"],\n\t[\"output_tokens\", \"INTEGER\"],\n\t[\"cache_read_tokens\", \"INTEGER\"],\n\t[\"cache_write_tokens\", \"INTEGER\"],\n\t[\"cost\", \"REAL\"],\n];\n\n/**\n * Plain, domain-independent row shape for `model_performance`. Deliberately not the\n * richer `UsagePerformanceSample` (which carries a branded `CredentialIdentity` and a\n * nested `usage` object) — this module owns SQLite schema and writes only, never\n * `ModelRuntime`'s domain types, to avoid a circular import between the two.\n */\nexport interface UsagePerformanceRow {\n\tprovider: string;\n\tmodelId: string;\n\tttftMs: number | null;\n\tgenerationMs: number | null;\n\tsampledAt: string;\n\tsessionId: string | null;\n\trole: string | null;\n\tcredentialIdentity: string | null;\n\toutcome: string | null;\n\tfailureKind: string | null;\n\tinputTokens: number | null;\n\toutputTokens: number | null;\n\tcacheReadTokens: number | null;\n\tcacheWriteTokens: number | null;\n\tcost: number | null;\n}\n\nexport interface RecoveryDiagnostic {\n\tcommandId: string;\n\tsessionId: string;\n\tpreviousState: \"created\" | \"running\";\n\tstate: \"interrupted\";\n\treason: string;\n\trecoveredAt: string;\n}\n\nexport interface DurableStateStore {\n\tschemaVersion(): number;\n\ttableNames(): string[];\n\tcolumns(tableName: string): string[];\n\tbeginCommand(input: { id?: string; sessionId: string; command: string }): CommandJournalRecord;\n\trunCommand<T>(input: { id?: string; sessionId: string; command: string }, operation: () => Promise<T>): Promise<T>;\n\ttransitionCommand(id: string, state: Exclude<CommandJournalState, \"created\">, reason?: string): CommandJournalRecord;\n\tgetCommand(id: string): CommandJournalRecord | undefined;\n\tcommandCount(): number;\n\trecoverUnfinishedCommands(reason?: string): CommandJournalRecord[];\n\trecoverUnfinishedCommandsWithDiagnostics(reason?: string): RecoveryDiagnostic[];\n\tacquireLease(input: {\n\t\tsessionId: string;\n\t\townerId: string;\n\t\tmode: SessionLeaseMode;\n\t\tttlMs: number;\n\t}): SessionLeaseRecord;\n\treleaseLease(sessionId: string, ownerId: string): void;\n\tgetLease(sessionId: string): SessionLeaseRecord | undefined;\n\trecordUsagePerformance(row: UsagePerformanceRow): void;\n\tlistUsagePerformance(): UsagePerformanceRow[];\n\tpruneUsagePerformance(olderThanIso: string): number;\n\tclose(): void;\n}\n\nfunction readSchemaVersion(database: DatabaseSync): number {\n\tconst row = database.prepare(\"SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations\").get() as\n\t\t| { version: number }\n\t\t| undefined;\n\treturn row?.version ?? 0;\n}\n\nfunction createSchema(database: DatabaseSync): void {\n\tdatabase.exec(`\n\t\tCREATE TABLE IF NOT EXISTS schema_migrations (\n\t\t\tversion INTEGER PRIMARY KEY,\n\t\t\tapplied_at TEXT NOT NULL\n\t\t);\n\t\tCREATE TABLE IF NOT EXISTS daemon_metadata (\n\t\t\tkey TEXT PRIMARY KEY,\n\t\t\tvalue TEXT NOT NULL\n\t\t);\n\t\tCREATE TABLE IF NOT EXISTS command_journal (\n\t\t\tid TEXT PRIMARY KEY,\n\t\t\tsession_id TEXT NOT NULL,\n\t\t\tcommand TEXT NOT NULL,\n\t\t\tstate TEXT NOT NULL,\n\t\t\trecovery_reason TEXT,\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\tupdated_at TEXT NOT NULL\n\t\t);\n\t\tCREATE TABLE IF NOT EXISTS session_leases (\n\t\t\tsession_id TEXT NOT NULL,\n\t\t\towner_id TEXT NOT NULL,\n\t\t\tmode TEXT NOT NULL,\n\t\t\texpires_at TEXT NOT NULL,\n\t\t\tPRIMARY KEY (session_id, owner_id)\n\t\t);\n\t\tCREATE TABLE IF NOT EXISTS model_performance (\n\t\t\tid INTEGER PRIMARY KEY,\n\t\t\tprovider TEXT NOT NULL,\n\t\t\tmodel_id TEXT NOT NULL,\n\t\t\tttft_ms REAL,\n\t\t\tgeneration_ms REAL,\n\t\t\tsampled_at TEXT NOT NULL,\n\t\t\tsession_id TEXT,\n\t\t\trole TEXT,\n\t\t\tcredential_identity TEXT,\n\t\t\toutcome TEXT,\n\t\t\tfailure_kind TEXT,\n\t\t\tinput_tokens INTEGER,\n\t\t\toutput_tokens INTEGER,\n\t\t\tcache_read_tokens INTEGER,\n\t\t\tcache_write_tokens INTEGER,\n\t\t\tcost REAL\n\t\t);\n\t\tCREATE TABLE IF NOT EXISTS cache_entries (\n\t\t\tkey TEXT PRIMARY KEY,\n\t\t\tvalue BLOB NOT NULL,\n\t\t\texpires_at TEXT\n\t\t);\n\t`);\n}\n\nfunction readCommand(database: DatabaseSync, id: string): CommandJournalRecord | undefined {\n\tconst row = database\n\t\t.prepare(\n\t\t\t\"SELECT id, session_id, command, state, recovery_reason, created_at, updated_at FROM command_journal WHERE id = ?\",\n\t\t)\n\t\t.get(id) as\n\t\t| {\n\t\t\t\tid: string;\n\t\t\t\tsession_id: string;\n\t\t\t\tcommand: string;\n\t\t\t\tstate: CommandJournalState;\n\t\t\t\trecovery_reason: string | null;\n\t\t\t\tcreated_at: string;\n\t\t\t\tupdated_at: string;\n\t\t }\n\t\t| undefined;\n\tif (!row) return undefined;\n\treturn {\n\t\tid: row.id,\n\t\tsessionId: row.session_id,\n\t\tcommand: row.command,\n\t\tstate: row.state,\n\t\tcreatedAt: row.created_at,\n\t\tupdatedAt: row.updated_at,\n\t\t...(row.recovery_reason ? { recoveryReason: row.recovery_reason } : {}),\n\t};\n}\n\nfunction readLeases(database: DatabaseSync, sessionId: string): SessionLeaseRecord[] {\n\tconst rows = database\n\t\t.prepare(\n\t\t\t\"SELECT session_id, owner_id, mode, expires_at FROM session_leases WHERE session_id = ? ORDER BY owner_id\",\n\t\t)\n\t\t.all(sessionId) as Array<{ session_id: string; owner_id: string; mode: SessionLeaseMode; expires_at: string }>;\n\treturn rows.map((row) => ({\n\t\tsessionId: row.session_id,\n\t\townerId: row.owner_id,\n\t\tmode: row.mode,\n\t\texpiresAt: row.expires_at,\n\t}));\n}\n\nfunction readLease(database: DatabaseSync, sessionId: string): SessionLeaseRecord | undefined {\n\treturn readLeases(database, sessionId)[0];\n}\n\nfunction transitionCommand(\n\tdatabase: DatabaseSync,\n\tid: string,\n\tstate: Exclude<CommandJournalState, \"created\">,\n\treason?: string,\n): CommandJournalRecord {\n\tconst current = readCommand(database, id);\n\tif (!current) throw new Error(`Unknown command journal entry: ${id}`);\n\tif (!COMMAND_TRANSITIONS[current.state].includes(state))\n\t\tthrow new Error(`Invalid command transition: ${current.state} -> ${state}`);\n\tconst now = new Date().toISOString();\n\tdatabase\n\t\t.prepare(\"UPDATE command_journal SET state = ?, recovery_reason = ?, updated_at = ? WHERE id = ?\")\n\t\t.run(state, reason ?? null, now, id);\n\treturn readCommand(database, id)!;\n}\n\nexport function openDurableStateStore(path: string): DurableStateStore {\n\tconst Sqlite = loadSqliteDatabaseConstructor();\n\tconst database = new Sqlite(path);\n\ttry {\n\t\tdatabase.exec(\"BEGIN IMMEDIATE\");\n\t\tcreateSchema(database);\n\t\tconst version = readSchemaVersion(database);\n\t\tif (version > CURRENT_DURABLE_STATE_SCHEMA_VERSION) {\n\t\t\tdatabase.exec(\"ROLLBACK\");\n\t\t\tthrow new Error(\n\t\t\t\t`Durable state database schema version ${version} is newer than this version (${CURRENT_DURABLE_STATE_SCHEMA_VERSION})`,\n\t\t\t);\n\t\t}\n\t\tif (version < 2) {\n\t\t\tconst commandColumns = database.prepare('PRAGMA table_info(\"command_journal\")').all() as Array<{\n\t\t\t\tname: string;\n\t\t\t}>;\n\t\t\tif (!commandColumns.some((column) => column.name === \"recovery_reason\"))\n\t\t\t\tdatabase.exec(\"ALTER TABLE command_journal ADD COLUMN recovery_reason TEXT\");\n\t\t}\n\t\tif (version < 3 && version > 0) {\n\t\t\tdatabase.exec(`\n\t\t\t\tALTER TABLE session_leases RENAME TO session_leases_v2;\n\t\t\t\tCREATE TABLE session_leases (\n\t\t\t\t\tsession_id TEXT NOT NULL,\n\t\t\t\t\towner_id TEXT NOT NULL,\n\t\t\t\t\tmode TEXT NOT NULL,\n\t\t\t\t\texpires_at TEXT NOT NULL,\n\t\t\t\t\tPRIMARY KEY (session_id, owner_id)\n\t\t\t\t);\n\t\t\t\tINSERT INTO session_leases (session_id, owner_id, mode, expires_at)\n\t\t\t\tSELECT session_id, owner_id, mode, expires_at FROM session_leases_v2;\n\t\t\t\tDROP TABLE session_leases_v2;\n\t\t\t`);\n\t\t}\n\t\tif (version < 4 && version > 0) {\n\t\t\tconst modelPerformanceColumns = database.prepare('PRAGMA table_info(\"model_performance\")').all() as Array<{\n\t\t\t\tname: string;\n\t\t\t}>;\n\t\t\tconst existingNames = new Set(modelPerformanceColumns.map((column) => column.name));\n\t\t\tfor (const [name, type] of MODEL_PERFORMANCE_V4_COLUMNS) {\n\t\t\t\tif (!existingNames.has(name)) database.exec(`ALTER TABLE model_performance ADD COLUMN ${name} ${type}`);\n\t\t\t}\n\t\t\tdatabase.exec(\"DROP TABLE IF EXISTS usage_totals\");\n\t\t}\n\t\tif (version < CURRENT_DURABLE_STATE_SCHEMA_VERSION) {\n\t\t\tdatabase\n\t\t\t\t.prepare(\"INSERT INTO schema_migrations (version, applied_at) VALUES (?, ?)\")\n\t\t\t\t.run(CURRENT_DURABLE_STATE_SCHEMA_VERSION, new Date().toISOString());\n\t\t}\n\t\tdatabase.exec(\"COMMIT\");\n\t} catch (error) {\n\t\ttry {\n\t\t\tdatabase.exec(\"ROLLBACK\");\n\t\t} catch {\n\t\t\t// Preserve the original migration error.\n\t\t}\n\t\tdatabase.close();\n\t\tthrow error;\n\t}\n\n\treturn {\n\t\tschemaVersion: () => readSchemaVersion(database),\n\t\ttableNames: () => {\n\t\t\tconst rows = database\n\t\t\t\t.prepare(\"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name\")\n\t\t\t\t.all() as Array<{ name: string }>;\n\t\t\treturn rows.map((row) => row.name);\n\t\t},\n\t\tcolumns: (tableName) => {\n\t\t\tif (!TABLES.includes(tableName as (typeof TABLES)[number]))\n\t\t\t\tthrow new Error(`Unknown durable-state table: ${tableName}`);\n\t\t\tconst rows = database.prepare(`PRAGMA table_info(\"${tableName}\")`).all() as Array<{ name: string }>;\n\t\t\treturn rows.map((row) => row.name);\n\t\t},\n\t\tbeginCommand: ({ id = randomUUID(), sessionId, command }) => {\n\t\t\tconst now = new Date().toISOString();\n\t\t\tdatabase\n\t\t\t\t.prepare(\n\t\t\t\t\t\"INSERT INTO command_journal (id, session_id, command, state, created_at, updated_at) VALUES (?, ?, ?, 'created', ?, ?)\",\n\t\t\t\t)\n\t\t\t\t.run(id, sessionId, command, now, now);\n\t\t\treturn readCommand(database, id)!;\n\t\t},\n\t\trunCommand: async (input, operation) => {\n\t\t\tconst entry = (() => {\n\t\t\t\tconst id = input.id ?? randomUUID();\n\t\t\t\tconst now = new Date().toISOString();\n\t\t\t\tdatabase\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\"INSERT INTO command_journal (id, session_id, command, state, created_at, updated_at) VALUES (?, ?, ?, 'created', ?, ?)\",\n\t\t\t\t\t)\n\t\t\t\t\t.run(id, input.sessionId, input.command, now, now);\n\t\t\t\treturn readCommand(database, id)!;\n\t\t\t})();\n\t\t\ttransitionCommand(database, entry.id, \"running\");\n\t\t\ttry {\n\t\t\t\tconst result = await operation();\n\t\t\t\ttransitionCommand(database, entry.id, \"completed\");\n\t\t\t\treturn result;\n\t\t\t} catch (error) {\n\t\t\t\ttransitionCommand(database, entry.id, \"failed\");\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\ttransitionCommand: (id, state, reason) => {\n\t\t\tconst current = readCommand(database, id);\n\t\t\tif (!current) throw new Error(`Unknown command journal entry: ${id}`);\n\t\t\tif (!COMMAND_TRANSITIONS[current.state].includes(state))\n\t\t\t\tthrow new Error(`Invalid command transition: ${current.state} -> ${state}`);\n\t\t\tconst now = new Date().toISOString();\n\t\t\tdatabase\n\t\t\t\t.prepare(\"UPDATE command_journal SET state = ?, recovery_reason = ?, updated_at = ? WHERE id = ?\")\n\t\t\t\t.run(state, reason ?? null, now, id);\n\t\t\treturn readCommand(database, id)!;\n\t\t},\n\t\tgetCommand: (id) => readCommand(database, id),\n\t\tcommandCount: () =>\n\t\t\t(database.prepare(\"SELECT COUNT(*) AS count FROM command_journal\").get() as { count: number }).count,\n\t\trecoverUnfinishedCommands: (reason = \"daemon restarted before command completion\") => {\n\t\t\tconst rows = database\n\t\t\t\t.prepare(\"SELECT id FROM command_journal WHERE state IN ('created', 'running')\")\n\t\t\t\t.all() as Array<{ id: string }>;\n\t\t\treturn rows.map(({ id }) => {\n\t\t\t\tconst current = readCommand(database, id)!;\n\t\t\t\treturn current.state === \"interrupted\" ? current : transitionCommand(database, id, \"interrupted\", reason);\n\t\t\t});\n\t\t},\n\t\trecoverUnfinishedCommandsWithDiagnostics: (reason = \"daemon restarted before command completion\") => {\n\t\t\tconst recoveredAt = new Date().toISOString();\n\t\t\tconst rows = database\n\t\t\t\t.prepare(\"SELECT id, session_id, state FROM command_journal WHERE state IN ('created', 'running')\")\n\t\t\t\t.all() as Array<{ id: string; session_id: string; state: \"created\" | \"running\" }>;\n\t\t\treturn rows.map((row) => {\n\t\t\t\ttransitionCommand(database, row.id, \"interrupted\", reason);\n\t\t\t\treturn {\n\t\t\t\t\tcommandId: row.id,\n\t\t\t\t\tsessionId: row.session_id,\n\t\t\t\t\tpreviousState: row.state,\n\t\t\t\t\tstate: \"interrupted\" as const,\n\t\t\t\t\treason,\n\t\t\t\t\trecoveredAt,\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\tacquireLease: ({ sessionId, ownerId, mode, ttlMs }) => {\n\t\t\tif (!Number.isFinite(ttlMs) || ttlMs <= 0) throw new Error(\"Lease TTL must be positive\");\n\t\t\tdatabase.exec(\"BEGIN IMMEDIATE\");\n\t\t\ttry {\n\t\t\t\tdatabase.prepare(\"DELETE FROM session_leases WHERE expires_at <= ?\").run(new Date().toISOString());\n\t\t\t\tconst active = readLeases(database, sessionId).filter((lease) => lease.ownerId !== ownerId);\n\t\t\t\tif (active.some((lease) => lease.mode === \"exclusive\") || (mode === \"exclusive\" && active.length > 0)) {\n\t\t\t\t\tthrow new Error(`Session lease is held for ${sessionId}`);\n\t\t\t\t}\n\t\t\t\tconst expiresAt = new Date(Date.now() + ttlMs).toISOString();\n\t\t\t\tdatabase\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\"INSERT INTO session_leases (session_id, owner_id, mode, expires_at) VALUES (?, ?, ?, ?) ON CONFLICT(session_id, owner_id) DO UPDATE SET mode=excluded.mode, expires_at=excluded.expires_at\",\n\t\t\t\t\t)\n\t\t\t\t\t.run(sessionId, ownerId, mode, expiresAt);\n\t\t\t\tdatabase.exec(\"COMMIT\");\n\t\t\t\treturn readLeases(database, sessionId).find((lease) => lease.ownerId === ownerId)!;\n\t\t\t} catch (error) {\n\t\t\t\tdatabase.exec(\"ROLLBACK\");\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\treleaseLease: (sessionId, ownerId) => {\n\t\t\tdatabase.prepare(\"DELETE FROM session_leases WHERE session_id = ? AND owner_id = ?\").run(sessionId, ownerId);\n\t\t},\n\t\tgetLease: (sessionId) => readLease(database, sessionId),\n\t\trecordUsagePerformance: (row) => {\n\t\t\tdatabase\n\t\t\t\t.prepare(\n\t\t\t\t\t`INSERT INTO model_performance (\n\t\t\t\t\t\tprovider, model_id, ttft_ms, generation_ms, sampled_at,\n\t\t\t\t\t\tsession_id, role, credential_identity, outcome, failure_kind,\n\t\t\t\t\t\tinput_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost\n\t\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n\t\t\t\t)\n\t\t\t\t.run(\n\t\t\t\t\trow.provider,\n\t\t\t\t\trow.modelId,\n\t\t\t\t\trow.ttftMs,\n\t\t\t\t\trow.generationMs,\n\t\t\t\t\trow.sampledAt,\n\t\t\t\t\trow.sessionId,\n\t\t\t\t\trow.role,\n\t\t\t\t\trow.credentialIdentity,\n\t\t\t\t\trow.outcome,\n\t\t\t\t\trow.failureKind,\n\t\t\t\t\trow.inputTokens,\n\t\t\t\t\trow.outputTokens,\n\t\t\t\t\trow.cacheReadTokens,\n\t\t\t\t\trow.cacheWriteTokens,\n\t\t\t\t\trow.cost,\n\t\t\t\t);\n\t\t},\n\t\tlistUsagePerformance: () =>\n\t\t\t(\n\t\t\t\tdatabase\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`SELECT provider, model_id, ttft_ms, generation_ms, sampled_at, session_id, role,\n\t\t\t\t\t\t\tcredential_identity, outcome, failure_kind, input_tokens, output_tokens,\n\t\t\t\t\t\t\tcache_read_tokens, cache_write_tokens, cost\n\t\t\t\t\t\tFROM model_performance ORDER BY id ASC`,\n\t\t\t\t\t)\n\t\t\t\t\t.all() as Array<{\n\t\t\t\t\tprovider: string;\n\t\t\t\t\tmodel_id: string;\n\t\t\t\t\tttft_ms: number | null;\n\t\t\t\t\tgeneration_ms: number | null;\n\t\t\t\t\tsampled_at: string;\n\t\t\t\t\tsession_id: string | null;\n\t\t\t\t\trole: string | null;\n\t\t\t\t\tcredential_identity: string | null;\n\t\t\t\t\toutcome: string | null;\n\t\t\t\t\tfailure_kind: string | null;\n\t\t\t\t\tinput_tokens: number | null;\n\t\t\t\t\toutput_tokens: number | null;\n\t\t\t\t\tcache_read_tokens: number | null;\n\t\t\t\t\tcache_write_tokens: number | null;\n\t\t\t\t\tcost: number | null;\n\t\t\t\t}>\n\t\t\t).map((row) => ({\n\t\t\t\tprovider: row.provider,\n\t\t\t\tmodelId: row.model_id,\n\t\t\t\tttftMs: row.ttft_ms,\n\t\t\t\tgenerationMs: row.generation_ms,\n\t\t\t\tsampledAt: row.sampled_at,\n\t\t\t\tsessionId: row.session_id,\n\t\t\t\trole: row.role,\n\t\t\t\tcredentialIdentity: row.credential_identity,\n\t\t\t\toutcome: row.outcome,\n\t\t\t\tfailureKind: row.failure_kind,\n\t\t\t\tinputTokens: row.input_tokens,\n\t\t\t\toutputTokens: row.output_tokens,\n\t\t\t\tcacheReadTokens: row.cache_read_tokens,\n\t\t\t\tcacheWriteTokens: row.cache_write_tokens,\n\t\t\t\tcost: row.cost,\n\t\t\t})),\n\t\tpruneUsagePerformance: (olderThanIso) => {\n\t\t\tconst result = database.prepare(\"DELETE FROM model_performance WHERE sampled_at < ?\").run(olderThanIso);\n\t\t\treturn Number(result.changes);\n\t\t},\n\t\tclose: () => database.close(),\n\t};\n}\n"]}
|
package/dist/core/exec.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"exec.d.ts","sourceRoot":"","sources":["../../src/core/exec.ts"],"names":[],"mappings":"AAAA;;GAEG;AAKH;;GAEG;AACH,MAAM,WAAW,WAAW;IAC3B,wCAAwC;IACxC,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,8BAA8B;IAC9B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,wBAAwB;IACxB,GAAG,CAAC,EAAE,MAAM,CAAC;CACb;AAED;;GAEG;AACH,MAAM,WAAW,UAAU;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,OAAO,CAAC;CAChB;AAED;;;GAGG;AACH,wBAAsB,WAAW,CAChC,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,EAAE,EACd,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,UAAU,CAAC,
|
|
1
|
+
{"version":3,"file":"exec.d.ts","sourceRoot":"","sources":["../../src/core/exec.ts"],"names":[],"mappings":"AAAA;;GAEG;AAKH;;GAEG;AACH,MAAM,WAAW,WAAW;IAC3B,wCAAwC;IACxC,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,8BAA8B;IAC9B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,wBAAwB;IACxB,GAAG,CAAC,EAAE,MAAM,CAAC;CACb;AAED;;GAEG;AACH,MAAM,WAAW,UAAU;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,OAAO,CAAC;CAChB;AAED;;;GAGG;AACH,wBAAsB,WAAW,CAChC,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,EAAE,EACd,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,UAAU,CAAC,CAuErB","sourcesContent":["/**\n * Shared command execution utilities for extensions and custom tools.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { waitForChildProcess } from \"../utils/child-process.ts\";\n\n/**\n * Options for executing shell commands.\n */\nexport interface ExecOptions {\n\t/** AbortSignal to cancel the command */\n\tsignal?: AbortSignal;\n\t/** Timeout in milliseconds */\n\ttimeout?: number;\n\t/** Working directory */\n\tcwd?: string;\n}\n\n/**\n * Result of executing a shell command.\n */\nexport interface ExecResult {\n\tstdout: string;\n\tstderr: string;\n\tcode: number;\n\tkilled: boolean;\n}\n\n/**\n * Execute a shell command and return stdout/stderr/code.\n * Supports timeout and abort signal.\n */\nexport async function execCommand(\n\tcommand: string,\n\targs: string[],\n\tcwd: string,\n\toptions?: ExecOptions,\n): Promise<ExecResult> {\n\treturn new Promise((resolve) => {\n\t\tconst proc = spawn(command, args, {\n\t\t\tcwd,\n\t\t\tshell: false,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t});\n\n\t\tlet stdout = \"\";\n\t\tlet stderr = \"\";\n\t\tlet killed = false;\n\t\tlet timeoutId: NodeJS.Timeout | undefined;\n\n\t\tconst killProcess = () => {\n\t\t\tif (!killed) {\n\t\t\t\tkilled = true;\n\t\t\t\tproc.kill(\"SIGTERM\");\n\t\t\t\t// Force kill after 5 seconds if SIGTERM doesn't work.\n\t\t\t\t// unref'd: an aborted command must not hold the process open\n\t\t\t\t// for the escalation window on normal exit.\n\t\t\t\tconst forceKillTimer = setTimeout(() => {\n\t\t\t\t\tif (!proc.killed) {\n\t\t\t\t\t\tproc.kill(\"SIGKILL\");\n\t\t\t\t\t}\n\t\t\t\t}, 5000);\n\t\t\t\tforceKillTimer.unref();\n\t\t\t}\n\t\t};\n\n\t\t// Handle abort signal\n\t\tif (options?.signal) {\n\t\t\tif (options.signal.aborted) {\n\t\t\t\tkillProcess();\n\t\t\t} else {\n\t\t\t\toptions.signal.addEventListener(\"abort\", killProcess, { once: true });\n\t\t\t}\n\t\t}\n\n\t\t// Handle timeout\n\t\tif (options?.timeout && options.timeout > 0) {\n\t\t\ttimeoutId = setTimeout(() => {\n\t\t\t\tkillProcess();\n\t\t\t}, options.timeout);\n\t\t}\n\n\t\tproc.stdout?.on(\"data\", (data) => {\n\t\t\tstdout += data.toString();\n\t\t});\n\n\t\tproc.stderr?.on(\"data\", (data) => {\n\t\t\tstderr += data.toString();\n\t\t});\n\n\t\t// Wait for process termination without hanging on inherited stdio handles\n\t\t// held open by detached descendants.\n\t\twaitForChildProcess(proc)\n\t\t\t.then((code) => {\n\t\t\t\tif (timeoutId) clearTimeout(timeoutId);\n\t\t\t\tif (options?.signal) {\n\t\t\t\t\toptions.signal.removeEventListener(\"abort\", killProcess);\n\t\t\t\t}\n\t\t\t\tresolve({ stdout, stderr, code: code ?? 0, killed });\n\t\t\t})\n\t\t\t.catch((_err) => {\n\t\t\t\tif (timeoutId) clearTimeout(timeoutId);\n\t\t\t\tif (options?.signal) {\n\t\t\t\t\toptions.signal.removeEventListener(\"abort\", killProcess);\n\t\t\t\t}\n\t\t\t\tresolve({ stdout, stderr, code: 1, killed });\n\t\t\t});\n\t});\n}\n"]}
|
package/dist/core/exec.js
CHANGED
|
@@ -22,12 +22,15 @@ export async function execCommand(command, args, cwd, options) {
|
|
|
22
22
|
if (!killed) {
|
|
23
23
|
killed = true;
|
|
24
24
|
proc.kill("SIGTERM");
|
|
25
|
-
// Force kill after 5 seconds if SIGTERM doesn't work
|
|
26
|
-
|
|
25
|
+
// Force kill after 5 seconds if SIGTERM doesn't work.
|
|
26
|
+
// unref'd: an aborted command must not hold the process open
|
|
27
|
+
// for the escalation window on normal exit.
|
|
28
|
+
const forceKillTimer = setTimeout(() => {
|
|
27
29
|
if (!proc.killed) {
|
|
28
30
|
proc.kill("SIGKILL");
|
|
29
31
|
}
|
|
30
32
|
}, 5000);
|
|
33
|
+
forceKillTimer.unref();
|
|
31
34
|
}
|
|
32
35
|
};
|
|
33
36
|
// Handle abort signal
|
package/dist/core/exec.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"exec.js","sourceRoot":"","sources":["../../src/core/exec.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAwBhE;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAChC,OAAe,EACf,IAAc,EACd,GAAW,EACX,OAAqB,EACC;IACtB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC;QAC/B,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,EAAE,IAAI,EAAE;YACjC,GAAG;YACH,KAAK,EAAE,KAAK;YACZ,KAAK,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM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C;YACvC,IAAI,OAAO,EAAE,MAAM,EAAE,CAAC;gBACrB,OAAO,CAAC,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;YAC1D,CAAC;YACD,OAAO,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;QAAA,CACrD,CAAC;aACD,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;YAChB,IAAI,SAAS;gBAAE,YAAY,CAAC,SAAS,CAAC,CAAC;YACvC,IAAI,OAAO,EAAE,MAAM,EAAE,CAAC;gBACrB,OAAO,CAAC,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;YAC1D,CAAC;YACD,OAAO,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;QAAA,CAC7C,CAAC,CAAC;IAAA,CACJ,CAAC,CAAC;AAAA,CACH","sourcesContent":["/**\n * Shared command execution utilities for extensions and custom tools.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { waitForChildProcess } from \"../utils/child-process.ts\";\n\n/**\n * Options for executing shell commands.\n */\nexport interface ExecOptions {\n\t/** AbortSignal to cancel the command */\n\tsignal?: AbortSignal;\n\t/** Timeout in milliseconds */\n\ttimeout?: number;\n\t/** Working directory */\n\tcwd?: string;\n}\n\n/**\n * Result of executing a shell command.\n */\nexport interface ExecResult {\n\tstdout: string;\n\tstderr: string;\n\tcode: number;\n\tkilled: boolean;\n}\n\n/**\n * Execute a shell command and return stdout/stderr/code.\n * Supports timeout and abort signal.\n */\nexport async function execCommand(\n\tcommand: string,\n\targs: string[],\n\tcwd: string,\n\toptions?: ExecOptions,\n): Promise<ExecResult> {\n\treturn new Promise((resolve) => {\n\t\tconst proc = spawn(command, args, {\n\t\t\tcwd,\n\t\t\tshell: false,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t});\n\n\t\tlet stdout = \"\";\n\t\tlet stderr = \"\";\n\t\tlet killed = false;\n\t\tlet timeoutId: NodeJS.Timeout | undefined;\n\n\t\tconst killProcess = () => {\n\t\t\tif (!killed) {\n\t\t\t\tkilled = true;\n\t\t\t\tproc.kill(\"SIGTERM\");\n\t\t\t\t// Force kill after 5 seconds if SIGTERM doesn't work.\n\t\t\t\t// unref'd: an aborted command must not hold the process open\n\t\t\t\t// for the escalation window on normal exit.\n\t\t\t\tconst forceKillTimer = setTimeout(() => {\n\t\t\t\t\tif (!proc.killed) {\n\t\t\t\t\t\tproc.kill(\"SIGKILL\");\n\t\t\t\t\t}\n\t\t\t\t}, 5000);\n\t\t\t\tforceKillTimer.unref();\n\t\t\t}\n\t\t};\n\n\t\t// Handle abort signal\n\t\tif (options?.signal) {\n\t\t\tif (options.signal.aborted) {\n\t\t\t\tkillProcess();\n\t\t\t} else {\n\t\t\t\toptions.signal.addEventListener(\"abort\", killProcess, { once: true });\n\t\t\t}\n\t\t}\n\n\t\t// Handle timeout\n\t\tif (options?.timeout && options.timeout > 0) {\n\t\t\ttimeoutId = setTimeout(() => {\n\t\t\t\tkillProcess();\n\t\t\t}, options.timeout);\n\t\t}\n\n\t\tproc.stdout?.on(\"data\", (data) => {\n\t\t\tstdout += data.toString();\n\t\t});\n\n\t\tproc.stderr?.on(\"data\", (data) => {\n\t\t\tstderr += data.toString();\n\t\t});\n\n\t\t// Wait for process termination without hanging on inherited stdio handles\n\t\t// held open by detached descendants.\n\t\twaitForChildProcess(proc)\n\t\t\t.then((code) => {\n\t\t\t\tif (timeoutId) clearTimeout(timeoutId);\n\t\t\t\tif (options?.signal) {\n\t\t\t\t\toptions.signal.removeEventListener(\"abort\", killProcess);\n\t\t\t\t}\n\t\t\t\tresolve({ stdout, stderr, code: code ?? 0, killed });\n\t\t\t})\n\t\t\t.catch((_err) => {\n\t\t\t\tif (timeoutId) clearTimeout(timeoutId);\n\t\t\t\tif (options?.signal) {\n\t\t\t\t\toptions.signal.removeEventListener(\"abort\", killProcess);\n\t\t\t\t}\n\t\t\t\tresolve({ stdout, stderr, code: 1, killed });\n\t\t\t});\n\t});\n}\n"]}
|
|
@@ -6,7 +6,7 @@ export type { SourceInfo } from "../source-info.ts";
|
|
|
6
6
|
export { createExtensionRuntime, discoverAndLoadExtensions, loadExtensionFromFactory, loadExtensions, } from "./loader.ts";
|
|
7
7
|
export type { ExtensionErrorListener, ForkHandler, NavigateTreeHandler, NewSessionHandler, ShutdownHandler, SwitchSessionHandler, } from "./runner.ts";
|
|
8
8
|
export { ExtensionRunner } from "./runner.ts";
|
|
9
|
-
export type { AfterProviderResponseEvent, AgentEndEvent, AgentSettledEvent, AgentStartEvent, AgentToolResult, AgentToolUpdateCallback, AppendEntryHandler, AppKeybinding, AutocompleteProviderFactory, BashToolCallEvent, BashToolResultEvent, BeforeAgentStartEvent, BeforeAgentStartEventResult, BeforeProviderHeadersEvent, BeforeProviderRequestEvent, BeforeProviderRequestEventResult, BuildSystemPromptOptions, CompactOptions, ContextEvent, ContextEventResult, ContextUsage, CustomToolCallEvent, CustomToolResultEvent, EditorFactory, EditToolCallEvent, EditToolResultEvent, EntryRenderer, EntryRenderOptions, ExecOptions, ExecResult, Extension, ExtensionActions, ExtensionAPI, ExtensionCommandContext, ExtensionCommandContextActions, ExtensionContext, ExtensionContextActions, ExtensionError, ExtensionEvent, ExtensionFactory, ExtensionFlag, ExtensionHandler, ExtensionMode, ExtensionRuntime, ExtensionShortcut, ExtensionUIContext, ExtensionUIDialogOptions, ExtensionWidgetOptions, FindToolCallEvent, FindToolResultEvent, GetActiveToolsHandler, GetAllToolsHandler, GetCommandsHandler, GetThinkingLevelHandler, GrepToolCallEvent, GrepToolResultEvent, InlineExtension, InputEvent, InputEventResult, InputSource, KeybindingsManager, LoadExtensionsResult, LsToolCallEvent, LsToolResultEvent, MarkdownTransformContext, MarkdownTransformer, MessageEndEvent, MessageRenderer, MessageRenderOptions, MessageStartEvent, MessageUpdateEvent, ModelSelectEvent, ModelSelectSource, ProjectTrustContext, ProjectTrustEvent, ProjectTrustEventDecision, ProjectTrustEventResult, ProjectTrustHandler, ProviderConfig, ProviderModelConfig, ReadToolCallEvent, ReadToolResultEvent, RegisteredCommand, RegisteredTool, ReplacedSessionContext, ResolvedCommand, ResourcesDiscoverEvent, ResourcesDiscoverResult, SendMessageHandler, SendUserMessageHandler, SessionBeforeCompactEvent, SessionBeforeCompactResult, SessionBeforeForkEvent, SessionBeforeForkResult, SessionBeforeSwitchEvent, SessionBeforeSwitchResult, SessionBeforeTreeEvent, SessionBeforeTreeResult, SessionCompactEvent, SessionEvent, SessionInfoChangedEvent, SessionShutdownEvent, SessionStartEvent, SessionTreeEvent, SetActiveToolsHandler, SetLabelHandler, SetModelHandler, SetThinkingLevelHandler, TerminalInputHandler, ToolCallEvent, ToolCallEventResult, ToolDefinition, ToolExecutionEndEvent, ToolExecutionMode, ToolExecutionStartEvent, ToolExecutionUpdateEvent, ToolInfo, ToolRenderResultOptions, ToolResultEvent, ToolResultEventResult, TreePreparation, TurnEndEvent, TurnStartEvent, UserBashEvent, UserBashEventResult, WidgetPlacement, WorkingIndicatorOptions, WriteToolCallEvent, WriteToolResultEvent, } from "./types.ts";
|
|
10
|
-
export { defineTool, isBashToolResult, isEditToolResult, isFindToolResult, isGrepToolResult, isLsToolResult, isReadToolResult, isToolCallEventType, isWriteToolResult, } from "./types.ts";
|
|
9
|
+
export type { AfterProviderResponseEvent, AgentEndEvent, AgentSettledEvent, AgentStartEvent, AgentToolResult, AgentToolUpdateCallback, AppendEntryHandler, AppKeybinding, AutocompleteProviderFactory, BashToolCallEvent, BashToolResultEvent, BeforeAgentStartEvent, BeforeAgentStartEventResult, BeforeProviderHeadersEvent, BeforeProviderRequestEvent, BeforeProviderRequestEventResult, BuildSystemPromptOptions, CompactOptions, ContextEvent, ContextEventResult, ContextUsage, CustomToolCallEvent, CustomToolResultEvent, EditorFactory, EditToolCallEvent, EditToolResultEvent, EntryRenderer, EntryRenderOptions, ExecOptions, ExecResult, Extension, ExtensionActions, ExtensionAPI, ExtensionCommandContext, ExtensionCommandContextActions, ExtensionContext, ExtensionContextActions, ExtensionError, ExtensionEvent, ExtensionFactory, ExtensionFlag, ExtensionHandler, ExtensionMode, ExtensionRuntime, ExtensionShortcut, ExtensionUIContext, ExtensionUIDialogOptions, ExtensionWidgetOptions, FindToolCallEvent, FindToolResultEvent, GetActiveToolsHandler, GetAllToolsHandler, GetCommandsHandler, GetThinkingLevelHandler, GrepToolCallEvent, GrepToolResultEvent, InlineExtension, InputEvent, InputEventResult, InputSource, KeybindingsManager, LoadExtensionsResult, LsToolCallEvent, LsToolResultEvent, MarkdownTransformContext, MarkdownTransformer, MessageEndEvent, MessageRenderer, MessageRenderOptions, MessageStartEvent, MessageUpdateEvent, ModelSelectEvent, ModelSelectSource, PowerShellToolCallEvent, PowerShellToolResultEvent, ProjectTrustContext, ProjectTrustEvent, ProjectTrustEventDecision, ProjectTrustEventResult, ProjectTrustHandler, ProviderConfig, ProviderModelConfig, ReadToolCallEvent, ReadToolResultEvent, RegisteredCommand, RegisteredTool, ReplacedSessionContext, ResolvedCommand, ResourcesDiscoverEvent, ResourcesDiscoverResult, SendMessageHandler, SendUserMessageHandler, SessionBeforeCompactEvent, SessionBeforeCompactResult, SessionBeforeForkEvent, SessionBeforeForkResult, SessionBeforeSwitchEvent, SessionBeforeSwitchResult, SessionBeforeTreeEvent, SessionBeforeTreeResult, SessionCompactEvent, SessionCompactFailedEvent, SessionEvent, SessionInfoChangedEvent, SessionShutdownEvent, SessionStartEvent, SessionTreeEvent, SetActiveToolsHandler, SetLabelHandler, SetModelHandler, SetThinkingLevelHandler, TerminalInputHandler, ToolCallEvent, ToolCallEventResult, ToolDefinition, ToolExecutionEndEvent, ToolExecutionMode, ToolExecutionStartEvent, ToolExecutionUpdateEvent, ToolInfo, ToolRenderResultOptions, ToolResultEvent, ToolResultEventResult, TreePreparation, TurnEndEvent, TurnStartEvent, UIPromptEndEvent, UIPromptKind, UIPromptStartEvent, UserBashEvent, UserBashEventResult, WidgetPlacement, WorkingIndicatorOptions, WriteToolCallEvent, WriteToolResultEvent, } from "./types.ts";
|
|
10
|
+
export { defineTool, isBashToolResult, isEditToolResult, isFindToolResult, isGrepToolResult, isLsToolResult, isPowerShellToolResult, isReadToolResult, isToolCallEventType, isWriteToolResult, } from "./types.ts";
|
|
11
11
|
export { wrapRegisteredTool, wrapRegisteredTools } from "./wrapper.ts";
|
|
12
12
|
//# sourceMappingURL=index.d.ts.map
|