apex-code 0.0.1-alpha.9 → 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 +150 -2
- package/README.md +9 -8
- package/dist/cli/args.d.ts +25 -1
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +43 -1
- package/dist/cli/args.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.map +1 -1
- package/dist/config.js +24 -5
- 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 +157 -8
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +565 -22
- package/dist/core/agent-session.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 +4 -3
- package/dist/core/compaction/branch-summarization.js.map +1 -1
- package/dist/core/compaction/compaction.d.ts +5 -0
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +19 -5
- package/dist/core/compaction/compaction.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/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 +1 -1
- package/dist/core/extensions/index.d.ts.map +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 +8 -2
- 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 +22 -2
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.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/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/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/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/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 +22 -0
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +53 -1
- package/dist/core/sdk.js.map +1 -1
- 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 +32 -5
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-manager.d.ts +163 -1
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +107 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +2 -0
- package/dist/core/slash-commands.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 +30 -15
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +228 -12
- 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 -0
- package/dist/core/tools/edit-diff.d.ts.map +1 -1
- package/dist/core/tools/edit-diff.js +215 -3
- 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 +53 -7
- 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 +10 -1
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +3 -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/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/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/provider.d.ts +3 -1
- package/dist/extensions/llama/provider.d.ts.map +1 -1
- package/dist/extensions/llama/provider.js +27 -6
- package/dist/extensions/llama/provider.js.map +1 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts +3 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +41 -9
- package/dist/main.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.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +6 -6
- 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 +2 -0
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +10 -0
- package/dist/modes/interactive/components/settings-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/interactive-mode.d.ts +34 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +231 -26
- 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 +15 -5
- package/dist/modes/interactive/theme/theme.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.map +1 -1
- package/dist/package-manager-cli.js +0 -6
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +6 -4
- package/dist/utils/shell.js.map +1 -1
- 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 +4 -0
- package/docs/custom-provider.md +7 -7
- package/docs/environment-variables.md +1 -1
- package/docs/extensions.md +18 -0
- package/docs/keybindings.md +1 -1
- package/docs/quickstart.md +1 -1
- package/docs/rpc.md +23 -0
- package/docs/sdk.md +25 -0
- package/docs/settings.md +12 -4
- package/docs/terminal-setup.md +12 -0
- package/docs/usage.md +4 -3
- 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/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/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +194 -46
- package/package.json +14 -12
- 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":"compaction.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,WAAW,EAAyC,kBAAkB,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAEvH,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAE9D,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EACN,mBAAmB,EAGnB,6BAA6B,GAC7B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACN,gBAAgB,EAChB,aAAa,EACb,yBAAyB,EAEzB,oBAAoB,EACpB,2BAA2B,EAC3B,qBAAqB,GACrB,MAAM,YAAY,CAAC;AAYpB;;GAEG;AACH,SAAS,qBAAqB,CAC7B,QAAwB,EACxB,OAAuB,EACvB,mBAA2B,EACV;IACjB,MAAM,OAAO,GAAG,aAAa,EAAE,CAAC;IAEhC,+DAA+D;IAC/D,IAAI,mBAAmB,IAAI,CAAC,EAAE,CAAC;QAC9B,MAAM,cAAc,GAAG,OAAO,CAAC,mBAAmB,CAAoB,CAAC;QACvE,IAAI,CAAC,cAAc,CAAC,QAAQ,IAAI,cAAc,CAAC,OAAO,EAAE,CAAC;YACxD,qDAAqD;YACrD,MAAM,OAAO,GAAG,cAAc,CAAC,OAA4B,CAAC;YAC5D,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE,CAAC;gBACtC,KAAK,MAAM,CAAC,IAAI,OAAO,CAAC,SAAS;oBAAE,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;YACxD,CAAC;YACD,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,aAAa,CAAC,EAAE,CAAC;gBAC1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AC1B,SAAkB,EACwB;IAC1C,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,CACzB,IAAI,CAAC,KAAK,CAAC,GAAG,GAAG,aAAa,CAAC,EAC/B,KAAK,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,iBAAiB,CAChE,CAAC,CAAC,iCAAiC;IACpC,MAAM,WAAW,GAAG,YAAY,CAAC,QAAQ,CAAC,CAAC;IAC3C,MAAM,gBAAgB,GAAG,qBAAqB,CAAC,WAAW,CAAC,CAAC;IAC5D,MAAM,UAAU,GAAG,mBAAmB,gBAAgB,wBAAwB,gCAAgC,EAAE,CAAC;IAEjH,MAAM,QAAQ,GAAG,MAAM,qBAAqB,CAC3C,KAAK,EACL,yBAAyB,CAAC,UAAU,CAAC,EACrC,0BAA0B,CAAC,KAAK,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,aAAa,EAAE,SAAS,CAAC,EACpG,QAAQ,EACR,KAAK,EACL,SAAS,CACT,CAAC;IAEF,IAAI,QAAQ,CAAC,UAAU,KAAK,OAAO,EAAE,CAAC;QACrC,MAAM,IAAI,KAAK,CAAC,qCAAqC,QAAQ,CAAC,YAAY,IAAI,eAAe,EAAE,CAAC,CAAC;IAClG,CAAC;IACD,IAAI,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,UAAU,CAAC,EAAE,CAAC;QACjE,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;IACvE,CAAC;IAED,OAAO;QACN,IAAI,EAAE,WAAW,CAAC,QAAQ,CAAC,OAAO,CAAC;QACnC,KAAK,EAAE,QAAQ,CAAC,KAAK;KACrB,CAAC;AAAA,CACF","sourcesContent":["/**\n * Context compaction for long sessions.\n *\n * Pure functions for compaction logic. The session manager handles I/O,\n * and after compaction the session is reloaded.\n */\n\nimport { contentText, type RetryCallbacks, type RetryPolicy, retryAssistantCall, uuidv7 } from \"@earendil-works/pi-ai\";\nimport type { AssistantMessage, Context, Model, SimpleStreamOptions, Usage } from \"@earendil-works/pi-ai/compat\";\nimport { completeSimple } from \"@earendil-works/pi-ai/compat\";\nimport type { AgentMessage, StreamFn, ThinkingLevel } from \"apex-code-agent-core\";\nimport { convertToLlm } from \"../messages.ts\";\nimport {\n\tbuildSessionContext,\n\ttype CompactionEntry,\n\ttype SessionEntry,\n\tsessionEntryToContextMessages,\n} from \"../session-manager.ts\";\nimport {\n\tcomputeFileLists,\n\tcreateFileOps,\n\textractFileOpsFromMessage,\n\ttype FileOperations,\n\tformatFileOperations,\n\tSUMMARIZATION_SYSTEM_PROMPT,\n\tserializeConversation,\n} from \"./utils.ts\";\n\n// ============================================================================\n// File Operation Tracking\n// ============================================================================\n\n/** Details stored in CompactionEntry.details for file tracking */\nexport interface CompactionDetails {\n\treadFiles: string[];\n\tmodifiedFiles: string[];\n}\n\n/**\n * Extract file operations from messages and previous compaction entries.\n */\nfunction extractFileOperations(\n\tmessages: AgentMessage[],\n\tentries: SessionEntry[],\n\tprevCompactionIndex: number,\n): FileOperations {\n\tconst fileOps = createFileOps();\n\n\t// Collect from previous compaction's details (if pi-generated)\n\tif (prevCompactionIndex >= 0) {\n\t\tconst prevCompaction = entries[prevCompactionIndex] as CompactionEntry;\n\t\tif (!prevCompaction.fromHook && prevCompaction.details) {\n\t\t\t// fromHook field kept for session file compatibility\n\t\t\tconst details = prevCompaction.details as CompactionDetails;\n\t\t\tif (Array.isArray(details.readFiles)) {\n\t\t\t\tfor (const f of details.readFiles) fileOps.read.add(f);\n\t\t\t}\n\t\t\tif (Array.isArray(details.modifiedFiles)) {\n\t\t\t\tfor (const f of details.modifiedFiles) fileOps.edited.add(f);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Extract from tool calls in messages\n\tfor (const msg of messages) {\n\t\textractFileOpsFromMessage(msg, fileOps);\n\t}\n\n\treturn fileOps;\n}\n\n// ============================================================================\n// Message Extraction\n// ============================================================================\n\n/**\n * Extract AgentMessage from an entry if it produces one.\n * Returns undefined for entries that don't contribute to LLM context.\n */\nfunction getMessageFromEntryForCompaction(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"compaction\") {\n\t\treturn undefined;\n\t}\n\treturn sessionEntryToContextMessages(entry)[0];\n}\n\n/** Result from compact() - SessionManager adds uuid/parentUuid when saving */\nexport interface CompactionResult<T = unknown> {\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\testimatedTokensAfter?: number;\n\t/** Usage from the LLM call(s) that generated this summary, if available */\n\tusage?: Usage;\n\t/** Extension-specific data (e.g., ArtifactIndex, version markers for structured compaction) */\n\tdetails?: T;\n}\n\nfunction combineUsage(first: Usage, second: Usage): Usage {\n\treturn {\n\t\tinput: first.input + second.input,\n\t\toutput: first.output + second.output,\n\t\tcacheRead: first.cacheRead + second.cacheRead,\n\t\tcacheWrite: first.cacheWrite + second.cacheWrite,\n\t\t...(first.cacheWrite1h !== undefined || second.cacheWrite1h !== undefined\n\t\t\t? { cacheWrite1h: (first.cacheWrite1h ?? 0) + (second.cacheWrite1h ?? 0) }\n\t\t\t: {}),\n\t\t...(first.reasoning !== undefined || second.reasoning !== undefined\n\t\t\t? { reasoning: (first.reasoning ?? 0) + (second.reasoning ?? 0) }\n\t\t\t: {}),\n\t\ttotalTokens: first.totalTokens + second.totalTokens,\n\t\tcost: {\n\t\t\tinput: first.cost.input + second.cost.input,\n\t\t\toutput: first.cost.output + second.cost.output,\n\t\t\tcacheRead: first.cost.cacheRead + second.cost.cacheRead,\n\t\t\tcacheWrite: first.cost.cacheWrite + second.cost.cacheWrite,\n\t\t\ttotal: first.cost.total + second.cost.total,\n\t\t},\n\t};\n}\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface CompactionSettings {\n\tenabled: boolean;\n\treserveTokens: number;\n\tkeepRecentTokens: number;\n}\n\nexport const DEFAULT_COMPACTION_SETTINGS: CompactionSettings = {\n\tenabled: true,\n\treserveTokens: 16384,\n\tkeepRecentTokens: 20000,\n};\n\n// ============================================================================\n// Token calculation\n// ============================================================================\n\n/**\n * Calculate total context tokens from usage.\n * Uses the native totalTokens field when available, falls back to computing from components.\n */\nexport function calculateContextTokens(usage: Usage): number {\n\treturn usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;\n}\n\n/**\n * Get usage from an assistant message if available.\n * Skips aborted, error, and all-zero usage messages as they don't have valid usage data.\n */\nfunction getAssistantUsage(msg: AgentMessage): Usage | undefined {\n\tif (msg.role === \"assistant\" && \"usage\" in msg) {\n\t\tconst assistantMsg = msg as AssistantMessage;\n\t\tif (\n\t\t\tassistantMsg.stopReason !== \"aborted\" &&\n\t\t\tassistantMsg.stopReason !== \"error\" &&\n\t\t\tassistantMsg.usage &&\n\t\t\tcalculateContextTokens(assistantMsg.usage) > 0\n\t\t) {\n\t\t\treturn assistantMsg.usage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * Find the last valid assistant message usage from session entries.\n */\nexport function getLastAssistantUsage(entries: SessionEntry[]): Usage | undefined {\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type === \"message\") {\n\t\t\tconst usage = getAssistantUsage(entry.message);\n\t\t\tif (usage) return usage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nexport interface ContextUsageEstimate {\n\ttokens: number;\n\tusageTokens: number;\n\ttrailingTokens: number;\n\tlastUsageIndex: number | null;\n}\n\nfunction getLastAssistantUsageInfo(messages: AgentMessage[]): { usage: Usage; index: number } | undefined {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst usage = getAssistantUsage(messages[i]);\n\t\tif (usage) return { usage, index: i };\n\t}\n\treturn undefined;\n}\n\n/**\n * Estimate context tokens from messages, using the last assistant usage when available.\n * If there are messages after the last usage, estimate their tokens with estimateTokens.\n */\nexport function estimateContextTokens(messages: AgentMessage[]): ContextUsageEstimate {\n\tconst usageInfo = getLastAssistantUsageInfo(messages);\n\n\tif (!usageInfo) {\n\t\tlet estimated = 0;\n\t\tfor (const message of messages) {\n\t\t\testimated += estimateTokens(message);\n\t\t}\n\t\treturn {\n\t\t\ttokens: estimated,\n\t\t\tusageTokens: 0,\n\t\t\ttrailingTokens: estimated,\n\t\t\tlastUsageIndex: null,\n\t\t};\n\t}\n\n\tconst usageTokens = calculateContextTokens(usageInfo.usage);\n\tlet trailingTokens = 0;\n\tfor (let i = usageInfo.index + 1; i < messages.length; i++) {\n\t\ttrailingTokens += estimateTokens(messages[i]);\n\t}\n\n\treturn {\n\t\ttokens: usageTokens + trailingTokens,\n\t\tusageTokens,\n\t\ttrailingTokens,\n\t\tlastUsageIndex: usageInfo.index,\n\t};\n}\n\n/**\n * Check if compaction should trigger based on context usage.\n */\nexport function shouldCompact(contextTokens: number, contextWindow: number, settings: CompactionSettings): boolean {\n\tif (!settings.enabled) return false;\n\treturn contextTokens > contextWindow - settings.reserveTokens;\n}\n\n// ============================================================================\n// Cut point detection\n// ============================================================================\n\nconst ESTIMATED_IMAGE_CHARS = 4800;\n\nfunction estimateTextAndImageContentChars(content: string | Array<{ type: string; text?: string }>): number {\n\tif (typeof content === \"string\") {\n\t\treturn content.length;\n\t}\n\n\tlet chars = 0;\n\tfor (const block of content) {\n\t\tif (block.type === \"text\" && block.text) {\n\t\t\tchars += block.text.length;\n\t\t} else if (block.type === \"image\") {\n\t\t\tchars += ESTIMATED_IMAGE_CHARS;\n\t\t}\n\t}\n\treturn chars;\n}\n\n/**\n * Estimate token count for a message using chars/4 heuristic.\n * This is conservative (overestimates tokens).\n */\nexport function estimateTokens(message: AgentMessage): number {\n\tlet chars = 0;\n\n\tswitch (message.role) {\n\t\tcase \"user\": {\n\t\t\tchars = estimateTextAndImageContentChars(\n\t\t\t\t(message as { content: string | Array<{ type: string; text?: string }> }).content,\n\t\t\t);\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"assistant\": {\n\t\t\tconst assistant = message as AssistantMessage;\n\t\t\tfor (const block of assistant.content) {\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tchars += block.text.length;\n\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\tchars += block.thinking.length;\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tchars += block.name.length + JSON.stringify(block.arguments).length;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"custom\":\n\t\tcase \"toolResult\": {\n\t\t\tchars = estimateTextAndImageContentChars(message.content);\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"bashExecution\": {\n\t\t\tchars = message.command.length + message.output.length;\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"branchSummary\":\n\t\tcase \"compactionSummary\": {\n\t\t\tchars = message.summary.length;\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nfunction isCutPointMessage(message: AgentMessage): boolean {\n\tswitch (message.role) {\n\t\tcase \"user\":\n\t\tcase \"assistant\":\n\t\tcase \"bashExecution\":\n\t\tcase \"custom\":\n\t\tcase \"branchSummary\":\n\t\tcase \"compactionSummary\":\n\t\t\treturn true;\n\t\tcase \"toolResult\":\n\t\t\treturn false;\n\t}\n\treturn false;\n}\n\nfunction isTurnStartMessage(message: AgentMessage): boolean {\n\tswitch (message.role) {\n\t\tcase \"user\":\n\t\tcase \"bashExecution\":\n\t\tcase \"custom\":\n\t\tcase \"branchSummary\":\n\t\tcase \"compactionSummary\":\n\t\t\treturn true;\n\t\tcase \"assistant\":\n\t\tcase \"toolResult\":\n\t\t\treturn false;\n\t}\n\treturn false;\n}\n\nfunction isTurnStartEntry(entry: SessionEntry): boolean {\n\tif (entry.type === \"compaction\") {\n\t\treturn false;\n\t}\n\treturn sessionEntryToContextMessages(entry).some(isTurnStartMessage);\n}\n\n/**\n * Find valid cut points: indices of context-visible user-like or assistant messages.\n * Never cut at tool results (they must follow their tool call).\n * When we cut at an assistant message with tool calls, its tool results follow it\n * and will be kept.\n */\nfunction findValidCutPoints(entries: SessionEntry[], startIndex: number, endIndex: number): number[] {\n\tconst cutPoints: number[] = [];\n\tfor (let i = startIndex; i < endIndex; i++) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type === \"compaction\") {\n\t\t\tcontinue;\n\t\t}\n\t\tif (sessionEntryToContextMessages(entry).some(isCutPointMessage)) {\n\t\t\tcutPoints.push(i);\n\t\t}\n\t}\n\treturn cutPoints;\n}\n\n/**\n * Find the context-visible user-role message that starts the turn containing the given entry index.\n * Returns -1 if no turn start found before the index.\n */\nexport function findTurnStartIndex(entries: SessionEntry[], entryIndex: number, startIndex: number): number {\n\tfor (let i = entryIndex; i >= startIndex; i--) {\n\t\tif (isTurnStartEntry(entries[i])) {\n\t\t\treturn i;\n\t\t}\n\t}\n\treturn -1;\n}\n\nexport interface CutPointResult {\n\t/** Index of first entry to keep */\n\tfirstKeptEntryIndex: number;\n\t/** Index of user message that starts the turn being split, or -1 if not splitting */\n\tturnStartIndex: number;\n\t/** Whether this cut splits a turn (cut point is not a user message) */\n\tisSplitTurn: boolean;\n}\n\n/**\n * Find the cut point in session entries that keeps approximately `keepRecentTokens`.\n *\n * Algorithm: Walk backwards from newest, accumulating estimated message sizes.\n * Stop when we've accumulated >= keepRecentTokens. Cut at that point.\n *\n * Can cut at user OR assistant messages (never tool results). When cutting at an\n * assistant message with tool calls, its tool results come after and will be kept.\n *\n * Returns CutPointResult with:\n * - firstKeptEntryIndex: the entry index to start keeping from\n * - turnStartIndex: if cutting mid-turn, the user message that started that turn\n * - isSplitTurn: whether we're cutting in the middle of a turn\n *\n * Only considers entries between `startIndex` and `endIndex` (exclusive).\n */\nexport function findCutPoint(\n\tentries: SessionEntry[],\n\tstartIndex: number,\n\tendIndex: number,\n\tkeepRecentTokens: number,\n): CutPointResult {\n\tconst cutPoints = findValidCutPoints(entries, startIndex, endIndex);\n\n\tif (cutPoints.length === 0) {\n\t\treturn { firstKeptEntryIndex: startIndex, turnStartIndex: -1, isSplitTurn: false };\n\t}\n\n\t// Walk backwards from newest, accumulating estimated message sizes\n\tlet accumulatedTokens = 0;\n\tlet cutIndex = cutPoints[0]; // Default: keep from first message (not header)\n\n\tfor (let i = endIndex - 1; i >= startIndex; i--) {\n\t\tconst entry = entries[i];\n\t\tconst messageTokens = sessionEntryToContextMessages(entry).reduce(\n\t\t\t(sum, message) => sum + estimateTokens(message),\n\t\t\t0,\n\t\t);\n\t\tif (messageTokens === 0) continue;\n\t\taccumulatedTokens += messageTokens;\n\n\t\t// Check if we've exceeded the budget\n\t\tif (accumulatedTokens >= keepRecentTokens) {\n\t\t\t// Find the closest valid cut point at or after this entry\n\t\t\tfor (let c = 0; c < cutPoints.length; c++) {\n\t\t\t\tif (cutPoints[c] >= i) {\n\t\t\t\t\tcutIndex = cutPoints[c];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Scan backwards from cutIndex to include adjacent metadata entries that do not affect context.\n\twhile (cutIndex > startIndex) {\n\t\tconst prevEntry = entries[cutIndex - 1];\n\t\t// Stop at compaction boundaries or context-visible entries.\n\t\tif (prevEntry.type === \"compaction\" || sessionEntryToContextMessages(prevEntry).length > 0) {\n\t\t\tbreak;\n\t\t}\n\t\tcutIndex--;\n\t}\n\n\t// Determine if this is a split turn\n\tconst cutEntry = entries[cutIndex];\n\tconst startsTurn = isTurnStartEntry(cutEntry);\n\tconst turnStartIndex = startsTurn ? -1 : findTurnStartIndex(entries, cutIndex, startIndex);\n\n\treturn {\n\t\tfirstKeptEntryIndex: cutIndex,\n\t\tturnStartIndex,\n\t\tisSplitTurn: !startsTurn && turnStartIndex !== -1,\n\t};\n}\n\n// ============================================================================\n// Summarization\n// ============================================================================\n\nconst SUMMARIZATION_PROMPT = `The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.\n\nUse this EXACT format:\n\n## Goal\n[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]\n\n## Constraints & Preferences\n- [Any constraints, preferences, or requirements mentioned by user]\n- [Or \"(none)\" if none were mentioned]\n\n## Progress\n### Done\n- [x] [Completed tasks/changes]\n\n### In Progress\n- [ ] [Current work]\n\n### Blocked\n- [Issues preventing progress, if any]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [Ordered list of what should happen next]\n\n## Critical Context\n- [Any data, examples, or references needed to continue]\n- [Or \"(none)\" if not applicable]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\nconst UPDATE_SUMMARIZATION_INSTRUCTIONS = `Update the existing structured summary with new information. RULES:\n- PRESERVE all existing information from the previous summary\n- ADD new progress, decisions, and context from the new messages\n- UPDATE the Progress section: move items from \"In Progress\" to \"Done\" when completed\n- UPDATE \"Next Steps\" based on what was accomplished\n- PRESERVE exact file paths, function names, and error messages\n- If something is no longer relevant, you may remove it\n\nUse this EXACT format:\n\n## Goal\n[Preserve existing goals, add new ones if the task expanded]\n\n## Constraints & Preferences\n- [Preserve existing, add new ones discovered]\n\n## Progress\n### Done\n- [x] [Include previously done items AND newly completed items]\n\n### In Progress\n- [ ] [Current work - update based on progress]\n\n### Blocked\n- [Current blockers - remove if resolved]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale] (preserve all previous, add new)\n\n## Next Steps\n1. [Update based on current state]\n\n## Critical Context\n- [Preserve important context, add new if needed]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\nconst UPDATE_SUMMARIZATION_PROMPT = `The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.\n\n${UPDATE_SUMMARIZATION_INSTRUCTIONS}`;\n\nfunction createSummarizationOptions(\n\tmodel: Model<any>,\n\tmaxTokens: number,\n\tapiKey: string | undefined,\n\theaders: Record<string, string> | undefined,\n\tenv: Record<string, string> | undefined,\n\tsignal: AbortSignal | undefined,\n\tthinkingLevel: ThinkingLevel | undefined,\n\tsessionId: string | undefined,\n): SimpleStreamOptions {\n\tconst options: SimpleStreamOptions = { maxTokens, signal, apiKey, headers, env, sessionId };\n\tif (model.reasoning && thinkingLevel && thinkingLevel !== \"off\") {\n\t\toptions.reasoning = thinkingLevel;\n\t}\n\treturn options;\n}\n\n/**\n * Shared choke point for every compaction/branch-summary summarization call. Wraps the\n * single LLM call in {@link retryAssistantCall} so transient stream drops (e.g.\n * `terminated`, socket close) honor the configured retry policy instead of failing\n * the whole compaction on the first attempt. Deterministic errors and aborts return\n * immediately (see {@link retryAssistantCall}).\n */\nexport async function completeSummarization(\n\tmodel: Model<any>,\n\tcontext: Context,\n\toptions: SimpleStreamOptions,\n\tstreamFn?: StreamFn,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n): Promise<AssistantMessage> {\n\t// Avoid cache writes for one-off summaries. Reuse caller-supplied routing when available;\n\t// callers without a session ID, including branch summaries, receive a fresh routing ID.\n\tconst requestOptions: SimpleStreamOptions = {\n\t\t...options,\n\t\tcacheRetention: \"none\",\n\t\tsessionId: options.sessionId ?? uuidv7(),\n\t\ttoolChoice: \"none\",\n\t};\n\tconst produce = async (): Promise<AssistantMessage> =>\n\t\tstreamFn\n\t\t\t? (await streamFn(model, context, requestOptions)).result()\n\t\t\t: completeSimple(model, context, requestOptions);\n\treturn retryAssistantCall(produce, retry, requestOptions.signal, callbacks);\n}\n\n/**\n * Generate a summary of the conversation using the LLM.\n * If previousSummary is provided, uses the update prompt to merge.\n */\nexport async function generateSummary(\n\tcurrentMessages: AgentMessage[],\n\tmodel: Model<any>,\n\treserveTokens: number,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tcustomInstructions?: string,\n\tpreviousSummary?: string,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n\tenv?: Record<string, string>,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n\tsessionId?: string,\n): Promise<string> {\n\treturn (\n\t\tawait generateSummaryWithUsage(\n\t\t\tcurrentMessages,\n\t\t\tmodel,\n\t\t\treserveTokens,\n\t\t\tapiKey,\n\t\t\theaders,\n\t\t\tsignal,\n\t\t\tcustomInstructions,\n\t\t\tpreviousSummary,\n\t\t\tthinkingLevel,\n\t\t\tstreamFn,\n\t\t\tenv,\n\t\t\tretry,\n\t\t\tcallbacks,\n\t\t\tsessionId,\n\t\t)\n\t).text;\n}\n\n/** Build the provider context for a standalone summary request. */\nfunction buildSummarizationContext(promptText: string): Context {\n\treturn {\n\t\tsystemPrompt: SUMMARIZATION_SYSTEM_PROMPT,\n\t\tmessages: [\n\t\t\t{\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: [{ type: \"text\", text: promptText }],\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t},\n\t\t],\n\t};\n}\n\n/** Generate or update a conversation summary and return its provider usage. */\nexport async function generateSummaryWithUsage(\n\tcurrentMessages: AgentMessage[],\n\tmodel: Model<any>,\n\treserveTokens: number,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tcustomInstructions?: string,\n\tpreviousSummary?: string,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n\tenv?: Record<string, string>,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n\tsessionId?: string,\n): Promise<{ text: string; usage: Usage }> {\n\tconst maxTokens = Math.min(\n\t\tMath.floor(0.8 * reserveTokens),\n\t\tmodel.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY,\n\t);\n\n\t// Use update prompt if we have a previous summary, otherwise initial prompt\n\tlet basePrompt = previousSummary ? UPDATE_SUMMARIZATION_PROMPT : SUMMARIZATION_PROMPT;\n\tif (customInstructions) {\n\t\tbasePrompt = `${basePrompt}\\n\\nAdditional focus: ${customInstructions}`;\n\t}\n\n\t// Serialize conversation to text so model doesn't try to continue it\n\t// Convert to LLM messages first (handles custom types like bashExecution, custom, etc.)\n\tconst llmMessages = convertToLlm(currentMessages);\n\tconst conversationText = serializeConversation(llmMessages);\n\n\t// Build the prompt with conversation wrapped in tags\n\tlet promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n`;\n\tif (previousSummary) {\n\t\tpromptText += `<previous-summary>\\n${previousSummary}\\n</previous-summary>\\n\\n`;\n\t}\n\tpromptText += basePrompt;\n\n\tconst completionOptions = createSummarizationOptions(\n\t\tmodel,\n\t\tmaxTokens,\n\t\tapiKey,\n\t\theaders,\n\t\tenv,\n\t\tsignal,\n\t\tthinkingLevel,\n\t\tsessionId,\n\t);\n\n\tconst response = await completeSummarization(\n\t\tmodel,\n\t\tbuildSummarizationContext(promptText),\n\t\tcompletionOptions,\n\t\tstreamFn,\n\t\tretry,\n\t\tcallbacks,\n\t);\n\n\tif (response.stopReason === \"error\") {\n\t\tthrow new Error(`Summarization failed: ${response.errorMessage || \"Unknown error\"}`);\n\t}\n\tif (response.content.some((block) => block.type === \"toolCall\")) {\n\t\tthrow new Error(\"Summarization attempted to call a tool\");\n\t}\n\n\tconst textContent = contentText(response.content);\n\n\treturn { text: textContent, usage: response.usage };\n}\n\n// ============================================================================\n// Compaction Preparation (for extensions)\n// ============================================================================\n\nexport interface CompactionPreparation {\n\t/** UUID of first entry to keep */\n\tfirstKeptEntryId: string;\n\t/** Messages that will be summarized and discarded */\n\tmessagesToSummarize: AgentMessage[];\n\t/** Messages that will be turned into turn prefix summary (if splitting) */\n\tturnPrefixMessages: AgentMessage[];\n\t/** Whether this is a split turn (cut point in middle of turn) */\n\tisSplitTurn: boolean;\n\ttokensBefore: number;\n\t/** Summary from previous compaction, for iterative update */\n\tpreviousSummary?: string;\n\t/** File operations extracted from messagesToSummarize */\n\tfileOps: FileOperations;\n\t/** Compaction settions from settings.jsonl\t*/\n\tsettings: CompactionSettings;\n}\n\nexport function prepareCompaction(\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n): CompactionPreparation | undefined {\n\tif (pathEntries.length > 0 && pathEntries[pathEntries.length - 1].type === \"compaction\") {\n\t\treturn undefined;\n\t}\n\n\tlet prevCompactionIndex = -1;\n\tfor (let i = pathEntries.length - 1; i >= 0; i--) {\n\t\tif (pathEntries[i].type === \"compaction\") {\n\t\t\tprevCompactionIndex = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tlet previousSummary: string | undefined;\n\tlet boundaryStart = 0;\n\tif (prevCompactionIndex >= 0) {\n\t\tconst prevCompaction = pathEntries[prevCompactionIndex] as CompactionEntry;\n\t\tpreviousSummary = prevCompaction.summary;\n\t\tconst firstKeptEntryIndex = pathEntries.findIndex((entry) => entry.id === prevCompaction.firstKeptEntryId);\n\t\tboundaryStart = firstKeptEntryIndex >= 0 ? firstKeptEntryIndex : prevCompactionIndex + 1;\n\t}\n\tconst boundaryEnd = pathEntries.length;\n\n\tconst tokensBefore = estimateContextTokens(buildSessionContext(pathEntries).messages).tokens;\n\n\tconst cutPoint = findCutPoint(pathEntries, boundaryStart, boundaryEnd, settings.keepRecentTokens);\n\n\t// Get UUID of first kept entry\n\tconst firstKeptEntry = pathEntries[cutPoint.firstKeptEntryIndex];\n\tif (!firstKeptEntry?.id) {\n\t\treturn undefined; // Session needs migration\n\t}\n\tconst firstKeptEntryId = firstKeptEntry.id;\n\n\tconst historyEnd = cutPoint.isSplitTurn ? cutPoint.turnStartIndex : cutPoint.firstKeptEntryIndex;\n\n\t// Messages to summarize (will be discarded after summary)\n\tconst messagesToSummarize: AgentMessage[] = [];\n\tfor (let i = boundaryStart; i < historyEnd; i++) {\n\t\tconst msg = getMessageFromEntryForCompaction(pathEntries[i]);\n\t\tif (msg) messagesToSummarize.push(msg);\n\t}\n\n\t// Messages for turn prefix summary (if splitting a turn)\n\tconst turnPrefixMessages: AgentMessage[] = [];\n\tif (cutPoint.isSplitTurn) {\n\t\tfor (let i = cutPoint.turnStartIndex; i < cutPoint.firstKeptEntryIndex; i++) {\n\t\t\tconst msg = getMessageFromEntryForCompaction(pathEntries[i]);\n\t\t\tif (msg) turnPrefixMessages.push(msg);\n\t\t}\n\t}\n\n\tif (messagesToSummarize.length === 0 && turnPrefixMessages.length === 0) {\n\t\treturn undefined;\n\t}\n\n\t// Extract file operations from messages and previous compaction\n\tconst fileOps = extractFileOperations(messagesToSummarize, pathEntries, prevCompactionIndex);\n\n\t// Also extract file ops from turn prefix if splitting\n\tif (cutPoint.isSplitTurn) {\n\t\tfor (const msg of turnPrefixMessages) {\n\t\t\textractFileOpsFromMessage(msg, fileOps);\n\t\t}\n\t}\n\n\treturn {\n\t\tfirstKeptEntryId,\n\t\tmessagesToSummarize,\n\t\tturnPrefixMessages,\n\t\tisSplitTurn: cutPoint.isSplitTurn,\n\t\ttokensBefore,\n\t\tpreviousSummary,\n\t\tfileOps,\n\t\tsettings,\n\t};\n}\n\n// ============================================================================\n// Main compaction function\n// ============================================================================\n\nconst TURN_PREFIX_SUMMARIZATION_PROMPT = `This is the PREFIX of a turn that was too large to keep. The SUFFIX (recent work) is retained.\n\nSummarize the prefix to provide context for the retained suffix:\n\n## Original Request\n[What did the user ask for in this turn?]\n\n## Early Progress\n- [Key decisions and work done in the prefix]\n\n## Context for Suffix\n- [Information needed to understand the retained recent work]\n\nBe concise. Focus on what's needed to understand the kept suffix.`;\n\n/**\n * Generate summaries for compaction using prepared data.\n * Returns CompactionResult - SessionManager adds uuid/parentUuid when saving.\n *\n * @param preparation - Pre-calculated preparation from prepareCompaction()\n * @param customInstructions - Optional custom focus for the summary\n * @param sessionId - Optional routing session ID forwarded without enabling prompt caching\n */\nexport async function compact(\n\tpreparation: CompactionPreparation,\n\tmodel: Model<any>,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tcustomInstructions?: string,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n\tenv?: Record<string, string>,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n\tsessionId?: string,\n): Promise<CompactionResult> {\n\tconst {\n\t\tfirstKeptEntryId,\n\t\tmessagesToSummarize,\n\t\tturnPrefixMessages,\n\t\tisSplitTurn,\n\t\ttokensBefore,\n\t\tpreviousSummary,\n\t\tfileOps,\n\t\tsettings,\n\t} = preparation;\n\n\t// Generate summaries and merge into one\n\tlet summary: string;\n\tlet summaryUsage: Usage;\n\n\tif (isSplitTurn && turnPrefixMessages.length > 0) {\n\t\tlet historyText = \"No prior history.\";\n\t\tlet historyUsage: Usage | undefined;\n\t\tif (messagesToSummarize.length > 0) {\n\t\t\tconst historyResult = await generateSummaryWithUsage(\n\t\t\t\tmessagesToSummarize,\n\t\t\t\tmodel,\n\t\t\t\tsettings.reserveTokens,\n\t\t\t\tapiKey,\n\t\t\t\theaders,\n\t\t\t\tsignal,\n\t\t\t\tcustomInstructions,\n\t\t\t\tpreviousSummary,\n\t\t\t\tthinkingLevel,\n\t\t\t\tstreamFn,\n\t\t\t\tenv,\n\t\t\t\tretry,\n\t\t\t\tcallbacks,\n\t\t\t\tsessionId,\n\t\t\t);\n\t\t\thistoryText = historyResult.text;\n\t\t\thistoryUsage = historyResult.usage;\n\t\t}\n\t\tconst turnPrefixResult = await generateTurnPrefixSummary(\n\t\t\tturnPrefixMessages,\n\t\t\tmodel,\n\t\t\tsettings.reserveTokens,\n\t\t\tapiKey,\n\t\t\theaders,\n\t\t\tenv,\n\t\t\tsignal,\n\t\t\tthinkingLevel,\n\t\t\tstreamFn,\n\t\t\tretry,\n\t\t\tcallbacks,\n\t\t\tsessionId,\n\t\t);\n\t\t// Merge into single summary\n\t\tsummary = `${historyText}\\n\\n---\\n\\n**Turn Context (split turn):**\\n\\n${turnPrefixResult.text}`;\n\t\tsummaryUsage = historyUsage ? combineUsage(historyUsage, turnPrefixResult.usage) : turnPrefixResult.usage;\n\t} else {\n\t\t// Just generate history summary\n\t\tconst result = await generateSummaryWithUsage(\n\t\t\tmessagesToSummarize,\n\t\t\tmodel,\n\t\t\tsettings.reserveTokens,\n\t\t\tapiKey,\n\t\t\theaders,\n\t\t\tsignal,\n\t\t\tcustomInstructions,\n\t\t\tpreviousSummary,\n\t\t\tthinkingLevel,\n\t\t\tstreamFn,\n\t\t\tenv,\n\t\t\tretry,\n\t\t\tcallbacks,\n\t\t\tsessionId,\n\t\t);\n\t\tsummary = result.text;\n\t\tsummaryUsage = result.usage;\n\t}\n\n\t// Compute file lists and append to summary\n\tconst { readFiles, modifiedFiles } = computeFileLists(fileOps);\n\tsummary += formatFileOperations(readFiles, modifiedFiles);\n\n\tif (!firstKeptEntryId) {\n\t\tthrow new Error(\"First kept entry has no UUID - session may need migration\");\n\t}\n\n\treturn {\n\t\tsummary,\n\t\tfirstKeptEntryId,\n\t\ttokensBefore,\n\t\tusage: summaryUsage,\n\t\tdetails: { readFiles, modifiedFiles } as CompactionDetails,\n\t};\n}\n\n/**\n * Generate a summary for a turn prefix (when splitting a turn).\n */\nasync function generateTurnPrefixSummary(\n\tmessages: AgentMessage[],\n\tmodel: Model<any>,\n\treserveTokens: number,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tenv?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n\tsessionId?: string,\n): Promise<{ text: string; usage: Usage }> {\n\tconst maxTokens = Math.min(\n\t\tMath.floor(0.5 * reserveTokens),\n\t\tmodel.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY,\n\t); // Smaller budget for turn prefix\n\tconst llmMessages = convertToLlm(messages);\n\tconst conversationText = serializeConversation(llmMessages);\n\tconst promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n${TURN_PREFIX_SUMMARIZATION_PROMPT}`;\n\n\tconst response = await completeSummarization(\n\t\tmodel,\n\t\tbuildSummarizationContext(promptText),\n\t\tcreateSummarizationOptions(model, maxTokens, apiKey, headers, env, signal, thinkingLevel, sessionId),\n\t\tstreamFn,\n\t\tretry,\n\t\tcallbacks,\n\t);\n\n\tif (response.stopReason === \"error\") {\n\t\tthrow new Error(`Turn prefix summarization failed: ${response.errorMessage || \"Unknown error\"}`);\n\t}\n\tif (response.content.some((block) => block.type === \"toolCall\")) {\n\t\tthrow new Error(\"Turn prefix summarization attempted to call a tool\");\n\t}\n\n\treturn {\n\t\ttext: contentText(response.content),\n\t\tusage: response.usage,\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"compaction.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,WAAW,EAAyC,kBAAkB,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAEvH,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAE9D,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EACN,mBAAmB,EAGnB,6BAA6B,GAC7B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACN,gBAAgB,EAChB,aAAa,EACb,yBAAyB,EAEzB,oBAAoB,EACpB,2BAA2B,EAC3B,qBAAqB,GACrB,MAAM,YAAY,CAAC;AAYpB;;GAEG;AACH,SAAS,qBAAqB,CAC7B,QAAwB,EACxB,OAAuB,EACvB,mBAA2B,EACV;IACjB,MAAM,OAAO,GAAG,aAAa,EAAE,CAAC;IAEhC,+DAA+D;IAC/D,IAAI,mBAAmB,IAAI,CAAC,EAAE,CAAC;QAC9B,MAAM,cAAc,GAAG,OAAO,CAAC,mBAAmB,CAAoB,CAAC;QACvE,IAAI,CAAC,cAAc,CAAC,QAAQ,IAAI,cAAc,CAAC,OAAO,EAAE,CAAC;YACxD,qDAAqD;YACrD,MAAM,OAAO,GAAG,cAAc,CAAC,OAA4B,CAAC;YAC5D,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,CAA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AAC;IAEF,MAAM,OAAO,GAAG,uBAAuB,CAAC,QAAQ,EAAE,2BAA2B,CAAC,CAAC;IAC/E,IAAI,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;IAC1B,CAAC;IACD,IAAI,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,UAAU,CAAC,EAAE,CAAC;QACjE,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;IACvE,CAAC;IAED,OAAO;QACN,IAAI,EAAE,WAAW,CAAC,QAAQ,CAAC,OAAO,CAAC;QACnC,KAAK,EAAE,QAAQ,CAAC,KAAK;KACrB,CAAC;AAAA,CACF","sourcesContent":["/**\n * Context compaction for long sessions.\n *\n * Pure functions for compaction logic. The session manager handles I/O,\n * and after compaction the session is reloaded.\n */\n\nimport { contentText, type RetryCallbacks, type RetryPolicy, retryAssistantCall, uuidv7 } from \"@earendil-works/pi-ai\";\nimport type { AssistantMessage, Context, Model, SimpleStreamOptions, Usage } from \"@earendil-works/pi-ai/compat\";\nimport { completeSimple } from \"@earendil-works/pi-ai/compat\";\nimport type { AgentMessage, StreamFn, ThinkingLevel } from \"apex-code-agent-core\";\nimport { convertToLlm } from \"../messages.ts\";\nimport {\n\tbuildSessionContext,\n\ttype CompactionEntry,\n\ttype SessionEntry,\n\tsessionEntryToContextMessages,\n} from \"../session-manager.ts\";\nimport {\n\tcomputeFileLists,\n\tcreateFileOps,\n\textractFileOpsFromMessage,\n\ttype FileOperations,\n\tformatFileOperations,\n\tSUMMARIZATION_SYSTEM_PROMPT,\n\tserializeConversation,\n} from \"./utils.ts\";\n\n// ============================================================================\n// File Operation Tracking\n// ============================================================================\n\n/** Details stored in CompactionEntry.details for file tracking */\nexport interface CompactionDetails {\n\treadFiles: string[];\n\tmodifiedFiles: string[];\n}\n\n/**\n * Extract file operations from messages and previous compaction entries.\n */\nfunction extractFileOperations(\n\tmessages: AgentMessage[],\n\tentries: SessionEntry[],\n\tprevCompactionIndex: number,\n): FileOperations {\n\tconst fileOps = createFileOps();\n\n\t// Collect from previous compaction's details (if pi-generated)\n\tif (prevCompactionIndex >= 0) {\n\t\tconst prevCompaction = entries[prevCompactionIndex] as CompactionEntry;\n\t\tif (!prevCompaction.fromHook && prevCompaction.details) {\n\t\t\t// fromHook field kept for session file compatibility\n\t\t\tconst details = prevCompaction.details as CompactionDetails;\n\t\t\tif (Array.isArray(details.readFiles)) {\n\t\t\t\tfor (const f of details.readFiles) fileOps.read.add(f);\n\t\t\t}\n\t\t\tif (Array.isArray(details.modifiedFiles)) {\n\t\t\t\tfor (const f of details.modifiedFiles) fileOps.edited.add(f);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Extract from tool calls in messages\n\tfor (const msg of messages) {\n\t\textractFileOpsFromMessage(msg, fileOps);\n\t}\n\n\treturn fileOps;\n}\n\n// ============================================================================\n// Message Extraction\n// ============================================================================\n\n/**\n * Extract AgentMessage from an entry if it produces one.\n * Returns undefined for entries that don't contribute to LLM context.\n */\nfunction getMessageFromEntryForCompaction(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"compaction\") {\n\t\treturn undefined;\n\t}\n\treturn sessionEntryToContextMessages(entry)[0];\n}\n\n/** Result from compact() - SessionManager adds uuid/parentUuid when saving */\nexport interface CompactionResult<T = unknown> {\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\testimatedTokensAfter?: number;\n\t/** Usage from the LLM call(s) that generated this summary, if available */\n\tusage?: Usage;\n\t/** Extension-specific data (e.g., ArtifactIndex, version markers for structured compaction) */\n\tdetails?: T;\n}\n\nfunction combineUsage(first: Usage, second: Usage): Usage {\n\treturn {\n\t\tinput: first.input + second.input,\n\t\toutput: first.output + second.output,\n\t\tcacheRead: first.cacheRead + second.cacheRead,\n\t\tcacheWrite: first.cacheWrite + second.cacheWrite,\n\t\t...(first.cacheWrite1h !== undefined || second.cacheWrite1h !== undefined\n\t\t\t? { cacheWrite1h: (first.cacheWrite1h ?? 0) + (second.cacheWrite1h ?? 0) }\n\t\t\t: {}),\n\t\t...(first.reasoning !== undefined || second.reasoning !== undefined\n\t\t\t? { reasoning: (first.reasoning ?? 0) + (second.reasoning ?? 0) }\n\t\t\t: {}),\n\t\ttotalTokens: first.totalTokens + second.totalTokens,\n\t\tcost: {\n\t\t\tinput: first.cost.input + second.cost.input,\n\t\t\toutput: first.cost.output + second.cost.output,\n\t\t\tcacheRead: first.cost.cacheRead + second.cost.cacheRead,\n\t\t\tcacheWrite: first.cost.cacheWrite + second.cost.cacheWrite,\n\t\t\ttotal: first.cost.total + second.cost.total,\n\t\t},\n\t};\n}\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface CompactionSettings {\n\tenabled: boolean;\n\treserveTokens: number;\n\tkeepRecentTokens: number;\n}\n\nexport const DEFAULT_COMPACTION_SETTINGS: CompactionSettings = {\n\tenabled: true,\n\treserveTokens: 16384,\n\tkeepRecentTokens: 20000,\n};\n\n// ============================================================================\n// Token calculation\n// ============================================================================\n\n/**\n * Calculate total context tokens from usage.\n * Uses the native totalTokens field when available, falls back to computing from components.\n */\nexport function calculateContextTokens(usage: Usage): number {\n\treturn usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;\n}\n\n/**\n * Get usage from an assistant message if available.\n * Skips aborted, error, and all-zero usage messages as they don't have valid usage data.\n */\nfunction getAssistantUsage(msg: AgentMessage): Usage | undefined {\n\tif (msg.role === \"assistant\" && \"usage\" in msg) {\n\t\tconst assistantMsg = msg as AssistantMessage;\n\t\tif (\n\t\t\tassistantMsg.stopReason !== \"aborted\" &&\n\t\t\tassistantMsg.stopReason !== \"error\" &&\n\t\t\tassistantMsg.usage &&\n\t\t\tcalculateContextTokens(assistantMsg.usage) > 0\n\t\t) {\n\t\t\treturn assistantMsg.usage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * Find the last valid assistant message usage from session entries.\n */\nexport function getLastAssistantUsage(entries: SessionEntry[]): Usage | undefined {\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type === \"message\") {\n\t\t\tconst usage = getAssistantUsage(entry.message);\n\t\t\tif (usage) return usage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nexport interface ContextUsageEstimate {\n\ttokens: number;\n\tusageTokens: number;\n\ttrailingTokens: number;\n\tlastUsageIndex: number | null;\n}\n\nfunction getLastAssistantUsageInfo(messages: AgentMessage[]): { usage: Usage; index: number } | undefined {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst usage = getAssistantUsage(messages[i]);\n\t\tif (usage) return { usage, index: i };\n\t}\n\treturn undefined;\n}\n\n/**\n * Estimate context tokens from messages, using the last assistant usage when available.\n * If there are messages after the last usage, estimate their tokens with estimateTokens.\n */\nexport function estimateContextTokens(messages: AgentMessage[]): ContextUsageEstimate {\n\tconst usageInfo = getLastAssistantUsageInfo(messages);\n\n\tif (!usageInfo) {\n\t\tlet estimated = 0;\n\t\tfor (const message of messages) {\n\t\t\testimated += estimateTokens(message);\n\t\t}\n\t\treturn {\n\t\t\ttokens: estimated,\n\t\t\tusageTokens: 0,\n\t\t\ttrailingTokens: estimated,\n\t\t\tlastUsageIndex: null,\n\t\t};\n\t}\n\n\tconst usageTokens = calculateContextTokens(usageInfo.usage);\n\tlet trailingTokens = 0;\n\tfor (let i = usageInfo.index + 1; i < messages.length; i++) {\n\t\ttrailingTokens += estimateTokens(messages[i]);\n\t}\n\n\treturn {\n\t\ttokens: usageTokens + trailingTokens,\n\t\tusageTokens,\n\t\ttrailingTokens,\n\t\tlastUsageIndex: usageInfo.index,\n\t};\n}\n\n/**\n * Check if compaction should trigger based on context usage.\n */\nexport function shouldCompact(contextTokens: number, contextWindow: number, settings: CompactionSettings): boolean {\n\tif (!settings.enabled) return false;\n\treturn contextTokens > contextWindow - settings.reserveTokens;\n}\n\n// ============================================================================\n// Cut point detection\n// ============================================================================\n\nconst ESTIMATED_IMAGE_CHARS = 4800;\n\nfunction estimateTextAndImageContentChars(content: string | Array<{ type: string; text?: string }>): number {\n\tif (typeof content === \"string\") {\n\t\treturn content.length;\n\t}\n\n\tlet chars = 0;\n\tfor (const block of content) {\n\t\tif (block.type === \"text\" && block.text) {\n\t\t\tchars += block.text.length;\n\t\t} else if (block.type === \"image\") {\n\t\t\tchars += ESTIMATED_IMAGE_CHARS;\n\t\t}\n\t}\n\treturn chars;\n}\n\n/**\n * Estimate token count for a message using chars/4 heuristic.\n * This is conservative (overestimates tokens).\n */\nexport function estimateTokens(message: AgentMessage): number {\n\tlet chars = 0;\n\n\tswitch (message.role) {\n\t\tcase \"user\": {\n\t\t\tchars = estimateTextAndImageContentChars(\n\t\t\t\t(message as { content: string | Array<{ type: string; text?: string }> }).content,\n\t\t\t);\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"assistant\": {\n\t\t\tconst assistant = message as AssistantMessage;\n\t\t\tfor (const block of assistant.content) {\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tchars += block.text.length;\n\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\tchars += block.thinking.length;\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tchars += block.name.length + JSON.stringify(block.arguments).length;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"custom\":\n\t\tcase \"toolResult\": {\n\t\t\tchars = estimateTextAndImageContentChars(message.content);\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"bashExecution\": {\n\t\t\tchars = message.command.length + message.output.length;\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"branchSummary\":\n\t\tcase \"compactionSummary\": {\n\t\t\tchars = message.summary.length;\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nfunction isCutPointMessage(message: AgentMessage): boolean {\n\tswitch (message.role) {\n\t\tcase \"user\":\n\t\tcase \"assistant\":\n\t\tcase \"bashExecution\":\n\t\tcase \"custom\":\n\t\tcase \"branchSummary\":\n\t\tcase \"compactionSummary\":\n\t\t\treturn true;\n\t\tcase \"toolResult\":\n\t\t\treturn false;\n\t}\n\treturn false;\n}\n\nfunction isTurnStartMessage(message: AgentMessage): boolean {\n\tswitch (message.role) {\n\t\tcase \"user\":\n\t\tcase \"bashExecution\":\n\t\tcase \"custom\":\n\t\tcase \"branchSummary\":\n\t\tcase \"compactionSummary\":\n\t\t\treturn true;\n\t\tcase \"assistant\":\n\t\tcase \"toolResult\":\n\t\t\treturn false;\n\t}\n\treturn false;\n}\n\nfunction isTurnStartEntry(entry: SessionEntry): boolean {\n\tif (entry.type === \"compaction\") {\n\t\treturn false;\n\t}\n\treturn sessionEntryToContextMessages(entry).some(isTurnStartMessage);\n}\n\n/**\n * Find valid cut points: indices of context-visible user-like or assistant messages.\n * Never cut at tool results (they must follow their tool call).\n * When we cut at an assistant message with tool calls, its tool results follow it\n * and will be kept.\n */\nfunction findValidCutPoints(entries: SessionEntry[], startIndex: number, endIndex: number): number[] {\n\tconst cutPoints: number[] = [];\n\tfor (let i = startIndex; i < endIndex; i++) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type === \"compaction\") {\n\t\t\tcontinue;\n\t\t}\n\t\tif (sessionEntryToContextMessages(entry).some(isCutPointMessage)) {\n\t\t\tcutPoints.push(i);\n\t\t}\n\t}\n\treturn cutPoints;\n}\n\n/**\n * Find the context-visible user-role message that starts the turn containing the given entry index.\n * Returns -1 if no turn start found before the index.\n */\nexport function findTurnStartIndex(entries: SessionEntry[], entryIndex: number, startIndex: number): number {\n\tfor (let i = entryIndex; i >= startIndex; i--) {\n\t\tif (isTurnStartEntry(entries[i])) {\n\t\t\treturn i;\n\t\t}\n\t}\n\treturn -1;\n}\n\nexport interface CutPointResult {\n\t/** Index of first entry to keep */\n\tfirstKeptEntryIndex: number;\n\t/** Index of user message that starts the turn being split, or -1 if not splitting */\n\tturnStartIndex: number;\n\t/** Whether this cut splits a turn (cut point is not a user message) */\n\tisSplitTurn: boolean;\n}\n\n/**\n * Find the cut point in session entries that keeps approximately `keepRecentTokens`.\n *\n * Algorithm: Walk backwards from newest, accumulating estimated message sizes.\n * Stop when we've accumulated >= keepRecentTokens. Cut at that point.\n *\n * Can cut at user OR assistant messages (never tool results). When cutting at an\n * assistant message with tool calls, its tool results come after and will be kept.\n *\n * Returns CutPointResult with:\n * - firstKeptEntryIndex: the entry index to start keeping from\n * - turnStartIndex: if cutting mid-turn, the user message that started that turn\n * - isSplitTurn: whether we're cutting in the middle of a turn\n *\n * Only considers entries between `startIndex` and `endIndex` (exclusive).\n */\nexport function findCutPoint(\n\tentries: SessionEntry[],\n\tstartIndex: number,\n\tendIndex: number,\n\tkeepRecentTokens: number,\n): CutPointResult {\n\tconst cutPoints = findValidCutPoints(entries, startIndex, endIndex);\n\n\tif (cutPoints.length === 0) {\n\t\treturn { firstKeptEntryIndex: startIndex, turnStartIndex: -1, isSplitTurn: false };\n\t}\n\n\t// Walk backwards from newest, accumulating estimated message sizes\n\tlet accumulatedTokens = 0;\n\tlet cutIndex = cutPoints[0]; // Default: keep from first message (not header)\n\n\tfor (let i = endIndex - 1; i >= startIndex; i--) {\n\t\tconst entry = entries[i];\n\t\tconst messageTokens = sessionEntryToContextMessages(entry).reduce(\n\t\t\t(sum, message) => sum + estimateTokens(message),\n\t\t\t0,\n\t\t);\n\t\tif (messageTokens === 0) continue;\n\t\taccumulatedTokens += messageTokens;\n\n\t\t// Check if we've exceeded the budget\n\t\tif (accumulatedTokens >= keepRecentTokens) {\n\t\t\t// Find the closest valid cut point at or after this entry\n\t\t\tfor (let c = 0; c < cutPoints.length; c++) {\n\t\t\t\tif (cutPoints[c] >= i) {\n\t\t\t\t\tcutIndex = cutPoints[c];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Scan backwards from cutIndex to include adjacent metadata entries that do not affect context.\n\twhile (cutIndex > startIndex) {\n\t\tconst prevEntry = entries[cutIndex - 1];\n\t\t// Stop at compaction boundaries or context-visible entries.\n\t\tif (prevEntry.type === \"compaction\" || sessionEntryToContextMessages(prevEntry).length > 0) {\n\t\t\tbreak;\n\t\t}\n\t\tcutIndex--;\n\t}\n\n\t// Determine if this is a split turn\n\tconst cutEntry = entries[cutIndex];\n\tconst startsTurn = isTurnStartEntry(cutEntry);\n\tconst turnStartIndex = startsTurn ? -1 : findTurnStartIndex(entries, cutIndex, startIndex);\n\n\treturn {\n\t\tfirstKeptEntryIndex: cutIndex,\n\t\tturnStartIndex,\n\t\tisSplitTurn: !startsTurn && turnStartIndex !== -1,\n\t};\n}\n\n// ============================================================================\n// Summarization\n// ============================================================================\n\nconst SUMMARIZATION_PROMPT = `The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.\n\nUse this EXACT format:\n\n## Goal\n[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]\n\n## Constraints & Preferences\n- [Any constraints, preferences, or requirements mentioned by user]\n- [Or \"(none)\" if none were mentioned]\n\n## Progress\n### Done\n- [x] [Completed tasks/changes]\n\n### In Progress\n- [ ] [Current work]\n\n### Blocked\n- [Issues preventing progress, if any]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [Ordered list of what should happen next]\n\n## Critical Context\n- [Any data, examples, or references needed to continue]\n- [Or \"(none)\" if not applicable]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\nconst UPDATE_SUMMARIZATION_INSTRUCTIONS = `Update the existing structured summary with new information. RULES:\n- PRESERVE all existing information from the previous summary\n- ADD new progress, decisions, and context from the new messages\n- UPDATE the Progress section: move items from \"In Progress\" to \"Done\" when completed\n- UPDATE \"Next Steps\" based on what was accomplished\n- PRESERVE exact file paths, function names, and error messages\n- If something is no longer relevant, you may remove it\n\nUse this EXACT format:\n\n## Goal\n[Preserve existing goals, add new ones if the task expanded]\n\n## Constraints & Preferences\n- [Preserve existing, add new ones discovered]\n\n## Progress\n### Done\n- [x] [Include previously done items AND newly completed items]\n\n### In Progress\n- [ ] [Current work - update based on progress]\n\n### Blocked\n- [Current blockers - remove if resolved]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale] (preserve all previous, add new)\n\n## Next Steps\n1. [Update based on current state]\n\n## Critical Context\n- [Preserve important context, add new if needed]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\nconst UPDATE_SUMMARIZATION_PROMPT = `The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.\n\n${UPDATE_SUMMARIZATION_INSTRUCTIONS}`;\n\n/**\n * Returns an error message when a summarization response cannot safely be persisted.\n * A length stop contains partial text and must not become a session checkpoint.\n */\nexport function getSummarizationFailure(response: AssistantMessage, label: string): string | undefined {\n\tif (response.stopReason === \"error\") {\n\t\treturn `${label} failed: ${response.errorMessage || \"Unknown error\"}`;\n\t}\n\tif (response.stopReason === \"length\") {\n\t\treturn `${label} failed: generation hit the token cap and the summary is incomplete`;\n\t}\n\treturn undefined;\n}\n\nfunction createSummarizationOptions(\n\tmodel: Model<any>,\n\tmaxTokens: number,\n\tapiKey: string | undefined,\n\theaders: Record<string, string> | undefined,\n\tenv: Record<string, string> | undefined,\n\tsignal: AbortSignal | undefined,\n\tthinkingLevel: ThinkingLevel | undefined,\n\tsessionId: string | undefined,\n): SimpleStreamOptions {\n\tconst options: SimpleStreamOptions = { maxTokens, signal, apiKey, headers, env, sessionId };\n\tif (model.reasoning && thinkingLevel && thinkingLevel !== \"off\") {\n\t\toptions.reasoning = thinkingLevel;\n\t}\n\treturn options;\n}\n\n/**\n * Shared choke point for every compaction/branch-summary summarization call. Wraps the\n * single LLM call in {@link retryAssistantCall} so transient stream drops (e.g.\n * `terminated`, socket close) honor the configured retry policy instead of failing\n * the whole compaction on the first attempt. Deterministic errors and aborts return\n * immediately (see {@link retryAssistantCall}).\n */\nexport async function completeSummarization(\n\tmodel: Model<any>,\n\tcontext: Context,\n\toptions: SimpleStreamOptions,\n\tstreamFn?: StreamFn,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n): Promise<AssistantMessage> {\n\t// Avoid cache writes for one-off summaries. Reuse caller-supplied routing when available;\n\t// callers without a session ID, including branch summaries, receive a fresh routing ID.\n\tconst requestOptions: SimpleStreamOptions = {\n\t\t...options,\n\t\tcacheRetention: \"none\",\n\t\tsessionId: options.sessionId ?? uuidv7(),\n\t};\n\tconst produce = async (): Promise<AssistantMessage> =>\n\t\tstreamFn\n\t\t\t? (await streamFn(model, context, requestOptions)).result()\n\t\t\t: completeSimple(model, context, requestOptions);\n\treturn retryAssistantCall(produce, retry, requestOptions.signal, callbacks);\n}\n\n/**\n * Generate a summary of the conversation using the LLM.\n * If previousSummary is provided, uses the update prompt to merge.\n */\nexport async function generateSummary(\n\tcurrentMessages: AgentMessage[],\n\tmodel: Model<any>,\n\treserveTokens: number,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tcustomInstructions?: string,\n\tpreviousSummary?: string,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n\tenv?: Record<string, string>,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n\tsessionId?: string,\n): Promise<string> {\n\treturn (\n\t\tawait generateSummaryWithUsage(\n\t\t\tcurrentMessages,\n\t\t\tmodel,\n\t\t\treserveTokens,\n\t\t\tapiKey,\n\t\t\theaders,\n\t\t\tsignal,\n\t\t\tcustomInstructions,\n\t\t\tpreviousSummary,\n\t\t\tthinkingLevel,\n\t\t\tstreamFn,\n\t\t\tenv,\n\t\t\tretry,\n\t\t\tcallbacks,\n\t\t\tsessionId,\n\t\t)\n\t).text;\n}\n\n/** Build the provider context for a standalone summary request. */\nfunction buildSummarizationContext(promptText: string): Context {\n\treturn {\n\t\tsystemPrompt: SUMMARIZATION_SYSTEM_PROMPT,\n\t\tmessages: [\n\t\t\t{\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: [{ type: \"text\", text: promptText }],\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t},\n\t\t],\n\t};\n}\n\n/** Generate or update a conversation summary and return its provider usage. */\nexport async function generateSummaryWithUsage(\n\tcurrentMessages: AgentMessage[],\n\tmodel: Model<any>,\n\treserveTokens: number,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tcustomInstructions?: string,\n\tpreviousSummary?: string,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n\tenv?: Record<string, string>,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n\tsessionId?: string,\n): Promise<{ text: string; usage: Usage }> {\n\tconst maxTokens = Math.min(\n\t\tMath.floor(0.8 * reserveTokens),\n\t\tmodel.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY,\n\t);\n\n\t// Use update prompt if we have a previous summary, otherwise initial prompt\n\tlet basePrompt = previousSummary ? UPDATE_SUMMARIZATION_PROMPT : SUMMARIZATION_PROMPT;\n\tif (customInstructions) {\n\t\tbasePrompt = `${basePrompt}\\n\\nAdditional focus: ${customInstructions}`;\n\t}\n\n\t// Serialize conversation to text so model doesn't try to continue it\n\t// Convert to LLM messages first (handles custom types like bashExecution, custom, etc.)\n\tconst llmMessages = convertToLlm(currentMessages);\n\tconst conversationText = serializeConversation(llmMessages);\n\n\t// Build the prompt with conversation wrapped in tags\n\tlet promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n`;\n\tif (previousSummary) {\n\t\tpromptText += `<previous-summary>\\n${previousSummary}\\n</previous-summary>\\n\\n`;\n\t}\n\tpromptText += basePrompt;\n\n\tconst completionOptions = createSummarizationOptions(\n\t\tmodel,\n\t\tmaxTokens,\n\t\tapiKey,\n\t\theaders,\n\t\tenv,\n\t\tsignal,\n\t\tthinkingLevel,\n\t\tsessionId,\n\t);\n\n\tconst response = await completeSummarization(\n\t\tmodel,\n\t\tbuildSummarizationContext(promptText),\n\t\tcompletionOptions,\n\t\tstreamFn,\n\t\tretry,\n\t\tcallbacks,\n\t);\n\n\tconst failure = getSummarizationFailure(response, \"Summarization\");\n\tif (failure) {\n\t\tthrow new Error(failure);\n\t}\n\tif (response.content.some((block) => block.type === \"toolCall\")) {\n\t\tthrow new Error(\"Summarization attempted to call a tool\");\n\t}\n\n\tconst textContent = contentText(response.content);\n\n\treturn { text: textContent, usage: response.usage };\n}\n\n// ============================================================================\n// Compaction Preparation (for extensions)\n// ============================================================================\n\nexport interface CompactionPreparation {\n\t/** UUID of first entry to keep */\n\tfirstKeptEntryId: string;\n\t/** Messages that will be summarized and discarded */\n\tmessagesToSummarize: AgentMessage[];\n\t/** Messages that will be turned into turn prefix summary (if splitting) */\n\tturnPrefixMessages: AgentMessage[];\n\t/** Whether this is a split turn (cut point in middle of turn) */\n\tisSplitTurn: boolean;\n\ttokensBefore: number;\n\t/** Summary from previous compaction, for iterative update */\n\tpreviousSummary?: string;\n\t/** File operations extracted from messagesToSummarize */\n\tfileOps: FileOperations;\n\t/** Compaction settions from settings.jsonl\t*/\n\tsettings: CompactionSettings;\n}\n\nexport function prepareCompaction(\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n): CompactionPreparation | undefined {\n\tif (pathEntries.length > 0 && pathEntries[pathEntries.length - 1].type === \"compaction\") {\n\t\treturn undefined;\n\t}\n\n\tlet prevCompactionIndex = -1;\n\tfor (let i = pathEntries.length - 1; i >= 0; i--) {\n\t\tif (pathEntries[i].type === \"compaction\") {\n\t\t\tprevCompactionIndex = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tlet previousSummary: string | undefined;\n\tlet boundaryStart = 0;\n\tif (prevCompactionIndex >= 0) {\n\t\tconst prevCompaction = pathEntries[prevCompactionIndex] as CompactionEntry;\n\t\tpreviousSummary = prevCompaction.summary;\n\t\tconst firstKeptEntryIndex = pathEntries.findIndex((entry) => entry.id === prevCompaction.firstKeptEntryId);\n\t\tboundaryStart = firstKeptEntryIndex >= 0 ? firstKeptEntryIndex : prevCompactionIndex + 1;\n\t}\n\tconst boundaryEnd = pathEntries.length;\n\n\tconst tokensBefore = estimateContextTokens(buildSessionContext(pathEntries).messages).tokens;\n\n\tconst cutPoint = findCutPoint(pathEntries, boundaryStart, boundaryEnd, settings.keepRecentTokens);\n\n\t// Get UUID of first kept entry\n\tconst firstKeptEntry = pathEntries[cutPoint.firstKeptEntryIndex];\n\tif (!firstKeptEntry?.id) {\n\t\treturn undefined; // Session needs migration\n\t}\n\tconst firstKeptEntryId = firstKeptEntry.id;\n\n\tconst historyEnd = cutPoint.isSplitTurn ? cutPoint.turnStartIndex : cutPoint.firstKeptEntryIndex;\n\n\t// Messages to summarize (will be discarded after summary)\n\tconst messagesToSummarize: AgentMessage[] = [];\n\tfor (let i = boundaryStart; i < historyEnd; i++) {\n\t\tconst msg = getMessageFromEntryForCompaction(pathEntries[i]);\n\t\tif (msg) messagesToSummarize.push(msg);\n\t}\n\n\t// Messages for turn prefix summary (if splitting a turn)\n\tconst turnPrefixMessages: AgentMessage[] = [];\n\tif (cutPoint.isSplitTurn) {\n\t\tfor (let i = cutPoint.turnStartIndex; i < cutPoint.firstKeptEntryIndex; i++) {\n\t\t\tconst msg = getMessageFromEntryForCompaction(pathEntries[i]);\n\t\t\tif (msg) turnPrefixMessages.push(msg);\n\t\t}\n\t}\n\n\tif (messagesToSummarize.length === 0 && turnPrefixMessages.length === 0) {\n\t\treturn undefined;\n\t}\n\n\t// Extract file operations from messages and previous compaction\n\tconst fileOps = extractFileOperations(messagesToSummarize, pathEntries, prevCompactionIndex);\n\n\t// Also extract file ops from turn prefix if splitting\n\tif (cutPoint.isSplitTurn) {\n\t\tfor (const msg of turnPrefixMessages) {\n\t\t\textractFileOpsFromMessage(msg, fileOps);\n\t\t}\n\t}\n\n\treturn {\n\t\tfirstKeptEntryId,\n\t\tmessagesToSummarize,\n\t\tturnPrefixMessages,\n\t\tisSplitTurn: cutPoint.isSplitTurn,\n\t\ttokensBefore,\n\t\tpreviousSummary,\n\t\tfileOps,\n\t\tsettings,\n\t};\n}\n\n// ============================================================================\n// Main compaction function\n// ============================================================================\n\nconst TURN_PREFIX_SUMMARIZATION_PROMPT = `This is the PREFIX of a turn that was too large to keep. The SUFFIX (recent work) is retained.\n\nSummarize the prefix to provide context for the retained suffix:\n\n## Original Request\n[What did the user ask for in this turn?]\n\n## Early Progress\n- [Key decisions and work done in the prefix]\n\n## Context for Suffix\n- [Information needed to understand the retained recent work]\n\nBe concise. Focus on what's needed to understand the kept suffix.`;\n\n/**\n * Generate summaries for compaction using prepared data.\n * Returns CompactionResult - SessionManager adds uuid/parentUuid when saving.\n *\n * @param preparation - Pre-calculated preparation from prepareCompaction()\n * @param customInstructions - Optional custom focus for the summary\n * @param sessionId - Optional routing session ID forwarded without enabling prompt caching\n */\nexport async function compact(\n\tpreparation: CompactionPreparation,\n\tmodel: Model<any>,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tcustomInstructions?: string,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n\tenv?: Record<string, string>,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n\tsessionId?: string,\n): Promise<CompactionResult> {\n\tconst {\n\t\tfirstKeptEntryId,\n\t\tmessagesToSummarize,\n\t\tturnPrefixMessages,\n\t\tisSplitTurn,\n\t\ttokensBefore,\n\t\tpreviousSummary,\n\t\tfileOps,\n\t\tsettings,\n\t} = preparation;\n\n\t// Generate summaries and merge into one\n\tlet summary: string;\n\tlet summaryUsage: Usage;\n\n\tif (isSplitTurn && turnPrefixMessages.length > 0) {\n\t\tlet historyText = \"No prior history.\";\n\t\tlet historyUsage: Usage | undefined;\n\t\tif (messagesToSummarize.length > 0) {\n\t\t\tconst historyResult = await generateSummaryWithUsage(\n\t\t\t\tmessagesToSummarize,\n\t\t\t\tmodel,\n\t\t\t\tsettings.reserveTokens,\n\t\t\t\tapiKey,\n\t\t\t\theaders,\n\t\t\t\tsignal,\n\t\t\t\tcustomInstructions,\n\t\t\t\tpreviousSummary,\n\t\t\t\tthinkingLevel,\n\t\t\t\tstreamFn,\n\t\t\t\tenv,\n\t\t\t\tretry,\n\t\t\t\tcallbacks,\n\t\t\t\tsessionId,\n\t\t\t);\n\t\t\thistoryText = historyResult.text;\n\t\t\thistoryUsage = historyResult.usage;\n\t\t}\n\t\tconst turnPrefixResult = await generateTurnPrefixSummary(\n\t\t\tturnPrefixMessages,\n\t\t\tmodel,\n\t\t\tsettings.reserveTokens,\n\t\t\tapiKey,\n\t\t\theaders,\n\t\t\tenv,\n\t\t\tsignal,\n\t\t\tthinkingLevel,\n\t\t\tstreamFn,\n\t\t\tretry,\n\t\t\tcallbacks,\n\t\t\tsessionId,\n\t\t);\n\t\t// Merge into single summary\n\t\tsummary = `${historyText}\\n\\n---\\n\\n**Turn Context (split turn):**\\n\\n${turnPrefixResult.text}`;\n\t\tsummaryUsage = historyUsage ? combineUsage(historyUsage, turnPrefixResult.usage) : turnPrefixResult.usage;\n\t} else {\n\t\t// Just generate history summary\n\t\tconst result = await generateSummaryWithUsage(\n\t\t\tmessagesToSummarize,\n\t\t\tmodel,\n\t\t\tsettings.reserveTokens,\n\t\t\tapiKey,\n\t\t\theaders,\n\t\t\tsignal,\n\t\t\tcustomInstructions,\n\t\t\tpreviousSummary,\n\t\t\tthinkingLevel,\n\t\t\tstreamFn,\n\t\t\tenv,\n\t\t\tretry,\n\t\t\tcallbacks,\n\t\t\tsessionId,\n\t\t);\n\t\tsummary = result.text;\n\t\tsummaryUsage = result.usage;\n\t}\n\n\t// Compute file lists and append to summary\n\tconst { readFiles, modifiedFiles } = computeFileLists(fileOps);\n\tsummary += formatFileOperations(readFiles, modifiedFiles);\n\n\tif (!firstKeptEntryId) {\n\t\tthrow new Error(\"First kept entry has no UUID - session may need migration\");\n\t}\n\n\treturn {\n\t\tsummary,\n\t\tfirstKeptEntryId,\n\t\ttokensBefore,\n\t\tusage: summaryUsage,\n\t\tdetails: { readFiles, modifiedFiles } as CompactionDetails,\n\t};\n}\n\n/**\n * Generate a summary for a turn prefix (when splitting a turn).\n */\nasync function generateTurnPrefixSummary(\n\tmessages: AgentMessage[],\n\tmodel: Model<any>,\n\treserveTokens: number,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tenv?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n\tsessionId?: string,\n): Promise<{ text: string; usage: Usage }> {\n\tconst maxTokens = Math.min(\n\t\tMath.floor(0.5 * reserveTokens),\n\t\tmodel.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY,\n\t); // Smaller budget for turn prefix\n\tconst llmMessages = convertToLlm(messages);\n\tconst conversationText = serializeConversation(llmMessages);\n\tconst promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n${TURN_PREFIX_SUMMARIZATION_PROMPT}`;\n\n\tconst response = await completeSummarization(\n\t\tmodel,\n\t\tbuildSummarizationContext(promptText),\n\t\tcreateSummarizationOptions(model, maxTokens, apiKey, headers, env, signal, thinkingLevel, sessionId),\n\t\tstreamFn,\n\t\tretry,\n\t\tcallbacks,\n\t);\n\n\tconst failure = getSummarizationFailure(response, \"Turn prefix summarization\");\n\tif (failure) {\n\t\tthrow new Error(failure);\n\t}\n\tif (response.content.some((block) => block.type === \"toolCall\")) {\n\t\tthrow new Error(\"Turn prefix summarization attempted to call a tool\");\n\t}\n\n\treturn {\n\t\ttext: contentText(response.content),\n\t\tusage: response.usage,\n\t};\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":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAKH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAGvD,uIAAuI;AACvI,MAAM,WAAW,eAAe;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,6KAA6K;IAC7K,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,8FAA8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AE,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,CAAC;IAClB,UAAU,EAAE,eAAe,CAAC;IAC5B,yGAAyG;IACzG,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,oJAAoJ;IACpJ,KAAK,EAAE,MAAM,CAAC;IACd,uEAAuE;IACvE,SAAS,EAAE,MAAM,CAAC;IAClB,gFAAgF;IAChF,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,wBAAwB;IACxC,YAAY,EAAE,uBAAuB,CAAC;IACtC,4IAA4I;IAC5I,qBAAqB,EAAE,MAAM,WAAW,CAAC,UAAU,CAAC,CAAC;IACrD,0GAA0G;IAC1G,mBAAmB,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,WAAW,CAAC,UAAU,CAAC,GAAG,SAAS,CAAC;IAC/E,uHAAuH;IACvH,kBAAkB,EAAE,MAAM,MAAM,CAAC;IACjC,sLAAsL;IACtL,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: 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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;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.promise;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../../src/core/delegation/runtime.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,IAAI,EAAE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KAAK,CAAC,OAAO,EAAE,CAAC;QACjB,CAAC;IAAA,CACD,CAAC;IACF,IAAI,CAAC,OAAO,CAAC,UAAU;QAAE,OAAO,OAAO,EAAE,CAAC;IAC1C,MAAM,QAAQ,GAAG,SAAS,CAAC;IAC3B,MAAM,OAAO,GAAG,OAAO,EAAE,CAAC;IAC1B,6EAA6E;IAC7E,yEAAyE;IACzE,uBAAuB;IACvB,KAAK,OAAO,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,EAAC,CAAC,CAAC,CAAC;IAC7B,UAAU,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,QAAQ,EAAE,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC,CAAC;IAC1D,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,EAAE,oDAAoD,QAAQ,IAAI,EAAE,QAAQ,EAAE,CAAC;AAAA,CAC/G;AAED,uGAAuG;AACvG,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC7C,OAAiC,EACjC,QAAgB,EAChB,iBAA0B,EACE;IAC5B,MAAM,KAAK,GAAG,UAAU,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAChD,IAAI,CAAC,KAAK;QAAE,MAAM,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: 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"]}
|
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,M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,qCAAqC;QACrC,mBAAmB,CAAC,IAAI,CAAC;aACvB,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;YACf,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,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, 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, UserBashEvent, UserBashEventResult, WidgetPlacement, WorkingIndicatorOptions, WriteToolCallEvent, WriteToolResultEvent, } 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
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
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,YAAY,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AACjF,YAAY,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EACN,sBAAsB,EACtB,yBAAyB,EACzB,wBAAwB,EACxB,cAAc,GACd,MAAM,aAAa,CAAC;AACrB,YAAY,EACX,sBAAsB,EACtB,WAAW,EACX,mBAAmB,EACnB,iBAAiB,EACjB,eAAe,EACf,oBAAoB,GACpB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,YAAY,EACX,0BAA0B,EAC1B,aAAa,EACb,iBAAiB,EACjB,eAAe,EAEf,eAAe,EACf,uBAAuB,EACvB,kBAAkB,EAElB,aAAa,EACb,2BAA2B,EAE3B,iBAAiB,EACjB,mBAAmB,EACnB,qBAAqB,EACrB,2BAA2B,EAC3B,0BAA0B,EAC1B,0BAA0B,EAC1B,gCAAgC,EAChC,wBAAwB,EAExB,cAAc,EAEd,YAAY,EAEZ,kBAAkB,EAClB,YAAY,EACZ,mBAAmB,EACnB,qBAA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,aAAa,EACb,mBAAmB,EAEnB,cAAc,EAEd,qBAAqB,EAErB,iBAAiB,EACjB,uBAAuB,EACvB,wBAAwB,EACxB,QAAQ,EACR,uBAAuB,EACvB,eAAe,EACf,qBAAqB,EACrB,eAAe,EACf,YAAY,EACZ,cAAc,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,YAAY,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AACjF,YAAY,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EACN,sBAAsB,EACtB,yBAAyB,EACzB,wBAAwB,EACxB,cAAc,GACd,MAAM,aAAa,CAAC;AACrB,YAAY,EACX,sBAAsB,EACtB,WAAW,EACX,mBAAmB,EACnB,iBAAiB,EACjB,eAAe,EACf,oBAAoB,GACpB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,YAAY,EACX,0BAA0B,EAC1B,aAAa,EACb,iBAAiB,EACjB,eAAe,EAEf,eAAe,EACf,uBAAuB,EACvB,kBAAkB,EAElB,aAAa,EACb,2BAA2B,EAE3B,iBAAiB,EACjB,mBAAmB,EACnB,qBAAqB,EACrB,2BAA2B,EAC3B,0BAA0B,EAC1B,0BAA0B,EAC1B,gCAAgC,EAChC,wBAAwB,EAExB,cAAc,EAEd,YAAY,EAEZ,kBAAkB,EAClB,YAAY,EACZ,mBAAmB,EACnB,qBAAqB,EACrB,aAAa,EACb,iBAAiB,EACjB,mBAAmB,EAEnB,aAAa,EACb,kBAAkB,EAClB,WAAW,EACX,UAAU,EACV,SAAS,EACT,gBAAgB,EAEhB,YAAY,EACZ,uBAAuB,EACvB,8BAA8B,EAC9B,gBAAgB,EAChB,uBAAuB,EAEvB,cAAc,EACd,cAAc,EACd,gBAAgB,EAChB,aAAa,EACb,gBAAgB,EAChB,aAA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BAAuB,EACvB,kBAAkB,EAClB,oBAAoB,GACpB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACN,UAAU,EACV,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,cAAc,EACd,sBAAsB,EACtB,gBAAgB,EAChB,mBAAmB,EACnB,iBAAiB,GACjB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC","sourcesContent":["/**\n * Extension system for lifecycle events and custom tools.\n */\n\nexport type { SlashCommandInfo, SlashCommandSource } from \"../slash-commands.ts\";\nexport type { SourceInfo } from \"../source-info.ts\";\nexport {\n\tcreateExtensionRuntime,\n\tdiscoverAndLoadExtensions,\n\tloadExtensionFromFactory,\n\tloadExtensions,\n} from \"./loader.ts\";\nexport type {\n\tExtensionErrorListener,\n\tForkHandler,\n\tNavigateTreeHandler,\n\tNewSessionHandler,\n\tShutdownHandler,\n\tSwitchSessionHandler,\n} from \"./runner.ts\";\nexport { ExtensionRunner } from \"./runner.ts\";\nexport type {\n\tAfterProviderResponseEvent,\n\tAgentEndEvent,\n\tAgentSettledEvent,\n\tAgentStartEvent,\n\t// Re-exports\n\tAgentToolResult,\n\tAgentToolUpdateCallback,\n\tAppendEntryHandler,\n\t// App keybindings (for custom editors)\n\tAppKeybinding,\n\tAutocompleteProviderFactory,\n\t// Events - Tool (ToolCallEvent types)\n\tBashToolCallEvent,\n\tBashToolResultEvent,\n\tBeforeAgentStartEvent,\n\tBeforeAgentStartEventResult,\n\tBeforeProviderHeadersEvent,\n\tBeforeProviderRequestEvent,\n\tBeforeProviderRequestEventResult,\n\tBuildSystemPromptOptions,\n\t// Context\n\tCompactOptions,\n\t// Events - Agent\n\tContextEvent,\n\t// Event Results\n\tContextEventResult,\n\tContextUsage,\n\tCustomToolCallEvent,\n\tCustomToolResultEvent,\n\tEditorFactory,\n\tEditToolCallEvent,\n\tEditToolResultEvent,\n\t// Message and Entry Rendering\n\tEntryRenderer,\n\tEntryRenderOptions,\n\tExecOptions,\n\tExecResult,\n\tExtension,\n\tExtensionActions,\n\t// API\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionCommandContextActions,\n\tExtensionContext,\n\tExtensionContextActions,\n\t// Errors\n\tExtensionError,\n\tExtensionEvent,\n\tExtensionFactory,\n\tExtensionFlag,\n\tExtensionHandler,\n\tExtensionMode,\n\t// Runtime\n\tExtensionRuntime,\n\tExtensionShortcut,\n\tExtensionUIContext,\n\tExtensionUIDialogOptions,\n\tExtensionWidgetOptions,\n\tFindToolCallEvent,\n\tFindToolResultEvent,\n\tGetActiveToolsHandler,\n\tGetAllToolsHandler,\n\tGetCommandsHandler,\n\tGetThinkingLevelHandler,\n\tGrepToolCallEvent,\n\tGrepToolResultEvent,\n\tInlineExtension,\n\t// Events - Input\n\tInputEvent,\n\tInputEventResult,\n\tInputSource,\n\tKeybindingsManager,\n\tLoadExtensionsResult,\n\tLsToolCallEvent,\n\tLsToolResultEvent,\n\tMarkdownTransformContext,\n\tMarkdownTransformer,\n\t// Events - Message\n\tMessageEndEvent,\n\tMessageRenderer,\n\tMessageRenderOptions,\n\tMessageStartEvent,\n\tMessageUpdateEvent,\n\tModelSelectEvent,\n\tModelSelectSource,\n\tPowerShellToolCallEvent,\n\tPowerShellToolResultEvent,\n\tProjectTrustContext,\n\tProjectTrustEvent,\n\tProjectTrustEventDecision,\n\tProjectTrustEventResult,\n\tProjectTrustHandler,\n\t// Provider Registration\n\tProviderConfig,\n\tProviderModelConfig,\n\tReadToolCallEvent,\n\tReadToolResultEvent,\n\t// Commands\n\tRegisteredCommand,\n\tRegisteredTool,\n\tReplacedSessionContext,\n\tResolvedCommand,\n\t// Events - Resources\n\tResourcesDiscoverEvent,\n\tResourcesDiscoverResult,\n\tSendMessageHandler,\n\tSendUserMessageHandler,\n\tSessionBeforeCompactEvent,\n\tSessionBeforeCompactResult,\n\tSessionBeforeForkEvent,\n\tSessionBeforeForkResult,\n\tSessionBeforeSwitchEvent,\n\tSessionBeforeSwitchResult,\n\tSessionBeforeTreeEvent,\n\tSessionBeforeTreeResult,\n\tSessionCompactEvent,\n\tSessionCompactFailedEvent,\n\tSessionEvent,\n\tSessionInfoChangedEvent,\n\tSessionShutdownEvent,\n\t// Events - Session\n\tSessionStartEvent,\n\tSessionTreeEvent,\n\tSetActiveToolsHandler,\n\tSetLabelHandler,\n\tSetModelHandler,\n\tSetThinkingLevelHandler,\n\tTerminalInputHandler,\n\t// Events - Tool\n\tToolCallEvent,\n\tToolCallEventResult,\n\t// Tools\n\tToolDefinition,\n\t// Events - Tool Execution\n\tToolExecutionEndEvent,\n\t// Tool execution mode\n\tToolExecutionMode,\n\tToolExecutionStartEvent,\n\tToolExecutionUpdateEvent,\n\tToolInfo,\n\tToolRenderResultOptions,\n\tToolResultEvent,\n\tToolResultEventResult,\n\tTreePreparation,\n\tTurnEndEvent,\n\tTurnStartEvent,\n\tUIPromptEndEvent,\n\tUIPromptKind,\n\tUIPromptStartEvent,\n\t// Events - User Bash\n\tUserBashEvent,\n\tUserBashEventResult,\n\tWidgetPlacement,\n\tWorkingIndicatorOptions,\n\tWriteToolCallEvent,\n\tWriteToolResultEvent,\n} from \"./types.ts\";\n// Type guards\nexport {\n\tdefineTool,\n\tisBashToolResult,\n\tisEditToolResult,\n\tisFindToolResult,\n\tisGrepToolResult,\n\tisLsToolResult,\n\tisPowerShellToolResult,\n\tisReadToolResult,\n\tisToolCallEventType,\n\tisWriteToolResult,\n} from \"./types.ts\";\nexport { wrapRegisteredTool, wrapRegisteredTools } from \"./wrapper.ts\";\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/extensions/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,OAAO,EACN,sBAAsB,EACtB,yBAAyB,EACzB,wBAAwB,EACxB,cAAc,GACd,MAAM,aAAa,CAAC;AASrB,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/extensions/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,OAAO,EACN,sBAAsB,EACtB,yBAAyB,EACzB,wBAAwB,EACxB,cAAc,GACd,MAAM,aAAa,CAAC;AASrB,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AA+J9C,cAAc;AACd,OAAO,EACN,UAAU,EACV,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,cAAc,EACd,sBAAsB,EACtB,gBAAgB,EAChB,mBAAmB,EACnB,iBAAiB,GACjB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC","sourcesContent":["/**\n * Extension system for lifecycle events and custom tools.\n */\n\nexport type { SlashCommandInfo, SlashCommandSource } from \"../slash-commands.ts\";\nexport type { SourceInfo } from \"../source-info.ts\";\nexport {\n\tcreateExtensionRuntime,\n\tdiscoverAndLoadExtensions,\n\tloadExtensionFromFactory,\n\tloadExtensions,\n} from \"./loader.ts\";\nexport type {\n\tExtensionErrorListener,\n\tForkHandler,\n\tNavigateTreeHandler,\n\tNewSessionHandler,\n\tShutdownHandler,\n\tSwitchSessionHandler,\n} from \"./runner.ts\";\nexport { ExtensionRunner } from \"./runner.ts\";\nexport type {\n\tAfterProviderResponseEvent,\n\tAgentEndEvent,\n\tAgentSettledEvent,\n\tAgentStartEvent,\n\t// Re-exports\n\tAgentToolResult,\n\tAgentToolUpdateCallback,\n\tAppendEntryHandler,\n\t// App keybindings (for custom editors)\n\tAppKeybinding,\n\tAutocompleteProviderFactory,\n\t// Events - Tool (ToolCallEvent types)\n\tBashToolCallEvent,\n\tBashToolResultEvent,\n\tBeforeAgentStartEvent,\n\tBeforeAgentStartEventResult,\n\tBeforeProviderHeadersEvent,\n\tBeforeProviderRequestEvent,\n\tBeforeProviderRequestEventResult,\n\tBuildSystemPromptOptions,\n\t// Context\n\tCompactOptions,\n\t// Events - Agent\n\tContextEvent,\n\t// Event Results\n\tContextEventResult,\n\tContextUsage,\n\tCustomToolCallEvent,\n\tCustomToolResultEvent,\n\tEditorFactory,\n\tEditToolCallEvent,\n\tEditToolResultEvent,\n\t// Message and Entry Rendering\n\tEntryRenderer,\n\tEntryRenderOptions,\n\tExecOptions,\n\tExecResult,\n\tExtension,\n\tExtensionActions,\n\t// API\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionCommandContextActions,\n\tExtensionContext,\n\tExtensionContextActions,\n\t// Errors\n\tExtensionError,\n\tExtensionEvent,\n\tExtensionFactory,\n\tExtensionFlag,\n\tExtensionHandler,\n\tExtensionMode,\n\t// Runtime\n\tExtensionRuntime,\n\tExtensionShortcut,\n\tExtensionUIContext,\n\tExtensionUIDialogOptions,\n\tExtensionWidgetOptions,\n\tFindToolCallEvent,\n\tFindToolResultEvent,\n\tGetActiveToolsHandler,\n\tGetAllToolsHandler,\n\tGetCommandsHandler,\n\tGetThinkingLevelHandler,\n\tGrepToolCallEvent,\n\tGrepToolResultEvent,\n\tInlineExtension,\n\t// Events - Input\n\tInputEvent,\n\tInputEventResult,\n\tInputSource,\n\tKeybindingsManager,\n\tLoadExtensionsResult,\n\tLsToolCallEvent,\n\tLsToolResultEvent,\n\tMarkdownTransformContext,\n\tMarkdownTransformer,\n\t// Events - Message\n\tMessageEndEvent,\n\tMessageRenderer,\n\tMessageRenderOptions,\n\tMessageStartEvent,\n\tMessageUpdateEvent,\n\tModelSelectEvent,\n\tModelSelectSource,\n\tPowerShellToolCallEvent,\n\tPowerShellToolResultEvent,\n\tProjectTrustContext,\n\tProjectTrustEvent,\n\tProjectTrustEventDecision,\n\tProjectTrustEventResult,\n\tProjectTrustHandler,\n\t// Provider Registration\n\tProviderConfig,\n\tProviderModelConfig,\n\tReadToolCallEvent,\n\tReadToolResultEvent,\n\t// Commands\n\tRegisteredCommand,\n\tRegisteredTool,\n\tReplacedSessionContext,\n\tResolvedCommand,\n\t// Events - Resources\n\tResourcesDiscoverEvent,\n\tResourcesDiscoverResult,\n\tSendMessageHandler,\n\tSendUserMessageHandler,\n\tSessionBeforeCompactEvent,\n\tSessionBeforeCompactResult,\n\tSessionBeforeForkEvent,\n\tSessionBeforeForkResult,\n\tSessionBeforeSwitchEvent,\n\tSessionBeforeSwitchResult,\n\tSessionBeforeTreeEvent,\n\tSessionBeforeTreeResult,\n\tSessionCompactEvent,\n\tSessionCompactFailedEvent,\n\tSessionEvent,\n\tSessionInfoChangedEvent,\n\tSessionShutdownEvent,\n\t// Events - Session\n\tSessionStartEvent,\n\tSessionTreeEvent,\n\tSetActiveToolsHandler,\n\tSetLabelHandler,\n\tSetModelHandler,\n\tSetThinkingLevelHandler,\n\tTerminalInputHandler,\n\t// Events - Tool\n\tToolCallEvent,\n\tToolCallEventResult,\n\t// Tools\n\tToolDefinition,\n\t// Events - Tool Execution\n\tToolExecutionEndEvent,\n\t// Tool execution mode\n\tToolExecutionMode,\n\tToolExecutionStartEvent,\n\tToolExecutionUpdateEvent,\n\tToolInfo,\n\tToolRenderResultOptions,\n\tToolResultEvent,\n\tToolResultEventResult,\n\tTreePreparation,\n\tTurnEndEvent,\n\tTurnStartEvent,\n\tUIPromptEndEvent,\n\tUIPromptKind,\n\tUIPromptStartEvent,\n\t// Events - User Bash\n\tUserBashEvent,\n\tUserBashEventResult,\n\tWidgetPlacement,\n\tWorkingIndicatorOptions,\n\tWriteToolCallEvent,\n\tWriteToolResultEvent,\n} from \"./types.ts\";\n// Type guards\nexport {\n\tdefineTool,\n\tisBashToolResult,\n\tisEditToolResult,\n\tisFindToolResult,\n\tisGrepToolResult,\n\tisLsToolResult,\n\tisPowerShellToolResult,\n\tisReadToolResult,\n\tisToolCallEventType,\n\tisWriteToolResult,\n} from \"./types.ts\";\nexport { wrapRegisteredTool, wrapRegisteredTools } from \"./wrapper.ts\";\n"]}
|