@buildanagent/harness 0.0.0-stage → 0.1.0-alpha.29
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/LICENSE +54 -0
- package/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +21 -0
- package/README.md +822 -2
- package/dist/ablation.d.ts +2 -0
- package/dist/ablation.js +3 -0
- package/dist/ablation.js.map +1 -0
- package/dist/completion/check.d.ts +64 -0
- package/dist/completion/check.js +152 -0
- package/dist/completion/check.js.map +1 -0
- package/dist/completion/checks.d.ts +45 -0
- package/dist/completion/checks.js +173 -0
- package/dist/completion/checks.js.map +1 -0
- package/dist/completion/flags.d.ts +25 -0
- package/dist/completion/flags.js +87 -0
- package/dist/completion/flags.js.map +1 -0
- package/dist/completion/index.d.ts +8 -0
- package/dist/completion/index.js +9 -0
- package/dist/completion/index.js.map +1 -0
- package/dist/completion/snapshot.d.ts +33 -0
- package/dist/completion/snapshot.js +83 -0
- package/dist/completion/snapshot.js.map +1 -0
- package/dist/context/cap.d.ts +32 -0
- package/dist/context/cap.js +50 -0
- package/dist/context/cap.js.map +1 -0
- package/dist/context/estimate.d.ts +18 -0
- package/dist/context/estimate.js +20 -0
- package/dist/context/estimate.js.map +1 -0
- package/dist/context/file-spill.d.ts +15 -0
- package/dist/context/file-spill.js +40 -0
- package/dist/context/file-spill.js.map +1 -0
- package/dist/context/index.d.ts +10 -0
- package/dist/context/index.js +10 -0
- package/dist/context/index.js.map +1 -0
- package/dist/context/mask.d.ts +27 -0
- package/dist/context/mask.js +71 -0
- package/dist/context/mask.js.map +1 -0
- package/dist/context/mid-turn.d.ts +40 -0
- package/dist/context/mid-turn.js +82 -0
- package/dist/context/mid-turn.js.map +1 -0
- package/dist/context/policy.d.ts +9 -0
- package/dist/context/policy.js +140 -0
- package/dist/context/policy.js.map +1 -0
- package/dist/context/spill-ledger.d.ts +25 -0
- package/dist/context/spill-ledger.js +54 -0
- package/dist/context/spill-ledger.js.map +1 -0
- package/dist/context/spill.d.ts +10 -0
- package/dist/context/spill.js +18 -0
- package/dist/context/spill.js.map +1 -0
- package/dist/context/summarize.d.ts +53 -0
- package/dist/context/summarize.js +204 -0
- package/dist/context/summarize.js.map +1 -0
- package/dist/context/summary-template.d.ts +29 -0
- package/dist/context/summary-template.js +69 -0
- package/dist/context/summary-template.js.map +1 -0
- package/dist/context/types.d.ts +150 -0
- package/dist/context/types.js +2 -0
- package/dist/context/types.js.map +1 -0
- package/dist/context/write-cap.d.ts +19 -0
- package/dist/context/write-cap.js +41 -0
- package/dist/context/write-cap.js.map +1 -0
- package/dist/create-harness.d.ts +7 -0
- package/dist/create-harness.js +21 -0
- package/dist/create-harness.js.map +1 -0
- package/dist/credentials/addresses.d.ts +14 -0
- package/dist/credentials/addresses.js +144 -0
- package/dist/credentials/addresses.js.map +1 -0
- package/dist/credentials/allowlist.d.ts +54 -0
- package/dist/credentials/allowlist.js +134 -0
- package/dist/credentials/allowlist.js.map +1 -0
- package/dist/credentials/egress-policy.d.ts +69 -0
- package/dist/credentials/egress-policy.js +170 -0
- package/dist/credentials/egress-policy.js.map +1 -0
- package/dist/credentials/egress-proxy.d.ts +82 -0
- package/dist/credentials/egress-proxy.js +650 -0
- package/dist/credentials/egress-proxy.js.map +1 -0
- package/dist/credentials/git-route.d.ts +68 -0
- package/dist/credentials/git-route.js +288 -0
- package/dist/credentials/git-route.js.map +1 -0
- package/dist/credentials/index.d.ts +13 -0
- package/dist/credentials/index.js +14 -0
- package/dist/credentials/index.js.map +1 -0
- package/dist/credentials/scrub.d.ts +23 -0
- package/dist/credentials/scrub.js +115 -0
- package/dist/credentials/scrub.js.map +1 -0
- package/dist/errors.d.ts +60 -0
- package/dist/errors.js +67 -0
- package/dist/errors.js.map +1 -0
- package/dist/extensions/compose.d.ts +27 -0
- package/dist/extensions/compose.js +83 -0
- package/dist/extensions/compose.js.map +1 -0
- package/dist/extensions/context-files-node.d.ts +28 -0
- package/dist/extensions/context-files-node.js +74 -0
- package/dist/extensions/context-files-node.js.map +1 -0
- package/dist/extensions/context-files.d.ts +68 -0
- package/dist/extensions/context-files.js +214 -0
- package/dist/extensions/context-files.js.map +1 -0
- package/dist/extensions/digest.d.ts +6 -0
- package/dist/extensions/digest.js +68 -0
- package/dist/extensions/digest.js.map +1 -0
- package/dist/extensions/index.d.ts +10 -0
- package/dist/extensions/index.js +10 -0
- package/dist/extensions/index.js.map +1 -0
- package/dist/extensions/load.d.ts +42 -0
- package/dist/extensions/load.js +211 -0
- package/dist/extensions/load.js.map +1 -0
- package/dist/extensions/lock.d.ts +8 -0
- package/dist/extensions/lock.js +95 -0
- package/dist/extensions/lock.js.map +1 -0
- package/dist/extensions/node.d.ts +10 -0
- package/dist/extensions/node.js +11 -0
- package/dist/extensions/node.js.map +1 -0
- package/dist/extensions/project-dirs.d.ts +24 -0
- package/dist/extensions/project-dirs.js +97 -0
- package/dist/extensions/project-dirs.js.map +1 -0
- package/dist/extensions/skills-node.d.ts +34 -0
- package/dist/extensions/skills-node.js +123 -0
- package/dist/extensions/skills-node.js.map +1 -0
- package/dist/extensions/skills.d.ts +51 -0
- package/dist/extensions/skills.js +175 -0
- package/dist/extensions/skills.js.map +1 -0
- package/dist/extensions/trust-file.d.ts +3 -0
- package/dist/extensions/trust-file.js +62 -0
- package/dist/extensions/trust-file.js.map +1 -0
- package/dist/extensions/trust-store-node.d.ts +10 -0
- package/dist/extensions/trust-store-node.js +33 -0
- package/dist/extensions/trust-store-node.js.map +1 -0
- package/dist/extensions/types.d.ts +42 -0
- package/dist/extensions/types.js +2 -0
- package/dist/extensions/types.js.map +1 -0
- package/dist/harness.d.ts +156 -0
- package/dist/harness.js +2 -0
- package/dist/harness.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp/connection.d.ts +22 -0
- package/dist/mcp/connection.js +267 -0
- package/dist/mcp/connection.js.map +1 -0
- package/dist/mcp/content.d.ts +27 -0
- package/dist/mcp/content.js +177 -0
- package/dist/mcp/content.js.map +1 -0
- package/dist/mcp/errors.d.ts +19 -0
- package/dist/mcp/errors.js +21 -0
- package/dist/mcp/errors.js.map +1 -0
- package/dist/mcp/index.d.ts +10 -0
- package/dist/mcp/index.js +10 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/mcp/manager.d.ts +7 -0
- package/dist/mcp/manager.js +173 -0
- package/dist/mcp/manager.js.map +1 -0
- package/dist/mcp/record.d.ts +7 -0
- package/dist/mcp/record.js +20 -0
- package/dist/mcp/record.js.map +1 -0
- package/dist/mcp/stdio.d.ts +39 -0
- package/dist/mcp/stdio.js +382 -0
- package/dist/mcp/stdio.js.map +1 -0
- package/dist/mcp/types.d.ts +172 -0
- package/dist/mcp/types.js +2 -0
- package/dist/mcp/types.js.map +1 -0
- package/dist/memory/index.d.ts +2 -0
- package/dist/memory/index.js +3 -0
- package/dist/memory/index.js.map +1 -0
- package/dist/permissions/default-rules.d.ts +7 -0
- package/dist/permissions/default-rules.js +42 -0
- package/dist/permissions/default-rules.js.map +1 -0
- package/dist/permissions/errors.d.ts +11 -0
- package/dist/permissions/errors.js +14 -0
- package/dist/permissions/errors.js.map +1 -0
- package/dist/permissions/index.d.ts +9 -0
- package/dist/permissions/index.js +9 -0
- package/dist/permissions/index.js.map +1 -0
- package/dist/permissions/match.d.ts +33 -0
- package/dist/permissions/match.js +287 -0
- package/dist/permissions/match.js.map +1 -0
- package/dist/permissions/pipeline.d.ts +9 -0
- package/dist/permissions/pipeline.js +235 -0
- package/dist/permissions/pipeline.js.map +1 -0
- package/dist/permissions/rules.d.ts +22 -0
- package/dist/permissions/rules.js +74 -0
- package/dist/permissions/rules.js.map +1 -0
- package/dist/permissions/shadow.d.ts +5 -0
- package/dist/permissions/shadow.js +22 -0
- package/dist/permissions/shadow.js.map +1 -0
- package/dist/permissions/types.d.ts +104 -0
- package/dist/permissions/types.js +2 -0
- package/dist/permissions/types.js.map +1 -0
- package/dist/sandbox/base.d.ts +45 -0
- package/dist/sandbox/base.js +74 -0
- package/dist/sandbox/base.js.map +1 -0
- package/dist/sandbox/docker/index.d.ts +41 -0
- package/dist/sandbox/docker/index.js +497 -0
- package/dist/sandbox/docker/index.js.map +1 -0
- package/dist/sandbox/errors.d.ts +44 -0
- package/dist/sandbox/errors.js +57 -0
- package/dist/sandbox/errors.js.map +1 -0
- package/dist/sandbox/host-files.d.ts +65 -0
- package/dist/sandbox/host-files.js +258 -0
- package/dist/sandbox/host-files.js.map +1 -0
- package/dist/sandbox/index.d.ts +10 -0
- package/dist/sandbox/index.js +10 -0
- package/dist/sandbox/index.js.map +1 -0
- package/dist/sandbox/none.d.ts +17 -0
- package/dist/sandbox/none.js +108 -0
- package/dist/sandbox/none.js.map +1 -0
- package/dist/sandbox/policy.d.ts +49 -0
- package/dist/sandbox/policy.js +149 -0
- package/dist/sandbox/policy.js.map +1 -0
- package/dist/sandbox/process.d.ts +61 -0
- package/dist/sandbox/process.js +253 -0
- package/dist/sandbox/process.js.map +1 -0
- package/dist/sandbox/spawn-env.d.ts +20 -0
- package/dist/sandbox/spawn-env.js +128 -0
- package/dist/sandbox/spawn-env.js.map +1 -0
- package/dist/sandbox/srt/index.d.ts +38 -0
- package/dist/sandbox/srt/index.js +283 -0
- package/dist/sandbox/srt/index.js.map +1 -0
- package/dist/sandbox/srt/settings.d.ts +60 -0
- package/dist/sandbox/srt/settings.js +84 -0
- package/dist/sandbox/srt/settings.js.map +1 -0
- package/dist/sandbox/types.d.ts +125 -0
- package/dist/sandbox/types.js +6 -0
- package/dist/sandbox/types.js.map +1 -0
- package/dist/server/answers.d.ts +16 -0
- package/dist/server/answers.js +43 -0
- package/dist/server/answers.js.map +1 -0
- package/dist/server/connection.d.ts +99 -0
- package/dist/server/connection.js +309 -0
- package/dist/server/connection.js.map +1 -0
- package/dist/server/dispatcher.d.ts +86 -0
- package/dist/server/dispatcher.js +800 -0
- package/dist/server/dispatcher.js.map +1 -0
- package/dist/server/index.d.ts +13 -0
- package/dist/server/index.js +12 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/local-transport.d.ts +44 -0
- package/dist/server/local-transport.js +103 -0
- package/dist/server/local-transport.js.map +1 -0
- package/dist/server/outbox.d.ts +31 -0
- package/dist/server/outbox.js +130 -0
- package/dist/server/outbox.js.map +1 -0
- package/dist/server/params.d.ts +25 -0
- package/dist/server/params.js +112 -0
- package/dist/server/params.js.map +1 -0
- package/dist/server/protocol.schema.json +2448 -0
- package/dist/server/rpc-session.d.ts +43 -0
- package/dist/server/rpc-session.js +167 -0
- package/dist/server/rpc-session.js.map +1 -0
- package/dist/server/stdio-streams.d.ts +67 -0
- package/dist/server/stdio-streams.js +218 -0
- package/dist/server/stdio-streams.js.map +1 -0
- package/dist/server/stdio.d.ts +59 -0
- package/dist/server/stdio.js +189 -0
- package/dist/server/stdio.js.map +1 -0
- package/dist/server/websocket.d.ts +106 -0
- package/dist/server/websocket.js +327 -0
- package/dist/server/websocket.js.map +1 -0
- package/dist/session/approvals.d.ts +81 -0
- package/dist/session/approvals.js +217 -0
- package/dist/session/approvals.js.map +1 -0
- package/dist/session/code-call-log.d.ts +42 -0
- package/dist/session/code-call-log.js +63 -0
- package/dist/session/code-call-log.js.map +1 -0
- package/dist/session/code-call-result.d.ts +19 -0
- package/dist/session/code-call-result.js +95 -0
- package/dist/session/code-call-result.js.map +1 -0
- package/dist/session/code-call.d.ts +49 -0
- package/dist/session/code-call.js +345 -0
- package/dist/session/code-call.js.map +1 -0
- package/dist/session/effect-scope.d.ts +11 -0
- package/dist/session/effect-scope.js +10 -0
- package/dist/session/effect-scope.js.map +1 -0
- package/dist/session/errors.d.ts +19 -0
- package/dist/session/errors.js +27 -0
- package/dist/session/errors.js.map +1 -0
- package/dist/session/file-index.d.ts +8 -0
- package/dist/session/file-index.js +70 -0
- package/dist/session/file-index.js.map +1 -0
- package/dist/session/file-key-store.d.ts +16 -0
- package/dist/session/file-key-store.js +169 -0
- package/dist/session/file-key-store.js.map +1 -0
- package/dist/session/file-lock.d.ts +52 -0
- package/dist/session/file-lock.js +324 -0
- package/dist/session/file-lock.js.map +1 -0
- package/dist/session/index.d.ts +22 -0
- package/dist/session/index.js +20 -0
- package/dist/session/index.js.map +1 -0
- package/dist/session/jsonl-store.d.ts +37 -0
- package/dist/session/jsonl-store.js +386 -0
- package/dist/session/jsonl-store.js.map +1 -0
- package/dist/session/jsonl.d.ts +9 -0
- package/dist/session/jsonl.js +10 -0
- package/dist/session/jsonl.js.map +1 -0
- package/dist/session/lock.d.ts +19 -0
- package/dist/session/lock.js +2 -0
- package/dist/session/lock.js.map +1 -0
- package/dist/session/memory-store.d.ts +12 -0
- package/dist/session/memory-store.js +60 -0
- package/dist/session/memory-store.js.map +1 -0
- package/dist/session/migrate.d.ts +41 -0
- package/dist/session/migrate.js +86 -0
- package/dist/session/migrate.js.map +1 -0
- package/dist/session/pointer.d.ts +15 -0
- package/dist/session/pointer.js +22 -0
- package/dist/session/pointer.js.map +1 -0
- package/dist/session/rebuild.d.ts +53 -0
- package/dist/session/rebuild.js +230 -0
- package/dist/session/rebuild.js.map +1 -0
- package/dist/session/resume.d.ts +26 -0
- package/dist/session/resume.js +128 -0
- package/dist/session/resume.js.map +1 -0
- package/dist/session/retention.d.ts +97 -0
- package/dist/session/retention.js +702 -0
- package/dist/session/retention.js.map +1 -0
- package/dist/session/runner.d.ts +156 -0
- package/dist/session/runner.js +656 -0
- package/dist/session/runner.js.map +1 -0
- package/dist/session/scheduler.d.ts +47 -0
- package/dist/session/scheduler.js +85 -0
- package/dist/session/scheduler.js.map +1 -0
- package/dist/session/secret-key-store.d.ts +47 -0
- package/dist/session/secret-key-store.js +79 -0
- package/dist/session/secret-key-store.js.map +1 -0
- package/dist/session/session.d.ts +106 -0
- package/dist/session/session.js +353 -0
- package/dist/session/session.js.map +1 -0
- package/dist/session/sticky.d.ts +48 -0
- package/dist/session/sticky.js +232 -0
- package/dist/session/sticky.js.map +1 -0
- package/dist/session/store.d.ts +108 -0
- package/dist/session/store.js +163 -0
- package/dist/session/store.js.map +1 -0
- package/dist/telemetry/index.d.ts +2 -0
- package/dist/telemetry/index.js +3 -0
- package/dist/telemetry/index.js.map +1 -0
- package/dist/testing/fake-sandbox.d.ts +52 -0
- package/dist/testing/fake-sandbox.js +370 -0
- package/dist/testing/fake-sandbox.js.map +1 -0
- package/dist/testing/index.d.ts +10 -0
- package/dist/testing/index.js +11 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/key-store-conformance.d.ts +22 -0
- package/dist/testing/key-store-conformance.js +97 -0
- package/dist/testing/key-store-conformance.js.map +1 -0
- package/dist/testing/run-cases.d.ts +21 -0
- package/dist/testing/run-cases.js +20 -0
- package/dist/testing/run-cases.js.map +1 -0
- package/dist/testing/sandbox-conformance.d.ts +64 -0
- package/dist/testing/sandbox-conformance.js +468 -0
- package/dist/testing/sandbox-conformance.js.map +1 -0
- package/dist/testing/scheduler-conformance.d.ts +32 -0
- package/dist/testing/scheduler-conformance.js +72 -0
- package/dist/testing/scheduler-conformance.js.map +1 -0
- package/dist/testing/store-conformance.d.ts +21 -0
- package/dist/testing/store-conformance.js +320 -0
- package/dist/testing/store-conformance.js.map +1 -0
- package/dist/tools/builtins/bash.d.ts +9 -0
- package/dist/tools/builtins/bash.js +75 -0
- package/dist/tools/builtins/bash.js.map +1 -0
- package/dist/tools/builtins/builtins.d.ts +38 -0
- package/dist/tools/builtins/builtins.js +48 -0
- package/dist/tools/builtins/builtins.js.map +1 -0
- package/dist/tools/builtins/descriptions.d.ts +69 -0
- package/dist/tools/builtins/descriptions.js +94 -0
- package/dist/tools/builtins/descriptions.js.map +1 -0
- package/dist/tools/builtins/fetch.d.ts +12 -0
- package/dist/tools/builtins/fetch.js +157 -0
- package/dist/tools/builtins/fetch.js.map +1 -0
- package/dist/tools/builtins/files.d.ts +27 -0
- package/dist/tools/builtins/files.js +274 -0
- package/dist/tools/builtins/files.js.map +1 -0
- package/dist/tools/builtins/paths.d.ts +30 -0
- package/dist/tools/builtins/paths.js +62 -0
- package/dist/tools/builtins/paths.js.map +1 -0
- package/dist/tools/builtins/results.d.ts +15 -0
- package/dist/tools/builtins/results.js +31 -0
- package/dist/tools/builtins/results.js.map +1 -0
- package/dist/tools/builtins/search.d.ts +18 -0
- package/dist/tools/builtins/search.js +217 -0
- package/dist/tools/builtins/search.js.map +1 -0
- package/dist/tools/errors.d.ts +13 -0
- package/dist/tools/errors.js +17 -0
- package/dist/tools/errors.js.map +1 -0
- package/dist/tools/index.d.ts +12 -0
- package/dist/tools/index.js +11 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/tools/registry.d.ts +3 -0
- package/dist/tools/registry.js +234 -0
- package/dist/tools/registry.js.map +1 -0
- package/dist/tools/tool-search.d.ts +30 -0
- package/dist/tools/tool-search.js +118 -0
- package/dist/tools/tool-search.js.map +1 -0
- package/dist/tools/types.d.ts +106 -0
- package/dist/tools/types.js +2 -0
- package/dist/tools/types.js.map +1 -0
- package/llms.txt +469 -0
- package/package.json +118 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/sandbox/types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * The sandbox interface: a pluggable client with honest tiers. The host owns the policy and the approval, never the\n * model, and a backend that can't start throws instead of running unconfined (harness guide section 6, ADR 0020).\n */\n\n/** What a sandbox may touch. Roots are absolute directories; a backend that enforces them denies the rest. */\nexport interface SandboxPolicy {\n /** Directories the sandbox may read. The write roots are readable too. */\n readonly readRoots: readonly string[];\n /** Directories the sandbox may write. */\n readonly writeRoots: readonly string[];\n /** The hosts the sandbox may reach: `allow` names them, and `deny` names the ones that stay closed inside `allow`. */\n readonly network: { readonly allow: readonly string[]; readonly deny: readonly string[] };\n}\n\n/** When a denied action may be asked for again, which is the host's decision and never the sandbox's. */\nexport type ApprovalPolicy = \"on-request\" | \"granular\" | \"never\";\n\n/**\n * How strongly a backend confines a process. `none`: not at all. `os`: an operating-system sandbox that shares the\n * host's kernel. `container`: a container. `gvisor`: a user-space kernel. `microvm`: a virtual machine.\n */\nexport type SandboxTier = \"none\" | \"os\" | \"container\" | \"gvisor\" | \"microvm\";\n\n/**\n * What a backend claims to stop. `mistakes`: the agent's own errors, such as a write outside the workspace.\n * `exfiltration`: sending data to a host that is not allowed. `hostile_process`: a process that is trying to escape.\n * A backend lists a stop only when its tier and its applied policy deliver it, which `stopsFor()` computes: only a\n * `microvm` stops a `hostile_process`, and none of the backends in this package is one.\n */\nexport type SandboxStop = \"mistakes\" | \"exfiltration\" | \"hostile_process\";\n\n/** The workspace a sandbox is provisioned for: its root directory and the files to put there first. */\nexport interface WorkspaceManifest {\n /** The workspace's absolute root. Relative paths and working directories resolve against it. */\n readonly root: string;\n /** Files to write under the root before the first command, by path relative to it. */\n readonly files?: Readonly<Record<string, string | Uint8Array>>;\n}\n\n/** What the policy refused. `target` names the path or host, and `reason` says which rule. */\nexport interface SandboxDenial {\n readonly kind: \"filesystem_read\" | \"filesystem_write\" | \"network\";\n readonly target: string;\n readonly reason: string;\n}\n\n/**\n * What a command did: its exit status and output, or the denial that stopped it. A failing command is a result.\n * `exitCode` is 124 for a timeout, 127 for a program that can't be found, and 128 plus the signal's number for a\n * command that a signal killed, with `signal` naming it. `timedOut` is `true` only when the sandbox stopped the command\n * at its timeout, so a command that exits with 124 itself can be told apart. `truncated` is `true` when the output\n * passed the cap and the rest was dropped.\n */\nexport type ExecResult =\n | { exitCode: number; stdout: string; stderr: string; signal?: string; timedOut?: boolean; truncated?: boolean }\n | { denied: SandboxDenial };\n\n/** The options of `Sandbox.exec()`. */\nexport interface ExecOptions {\n /** The working directory, relative to the workspace root. Defaults to the root. */\n readonly cwd?: string;\n /** The command's whole environment. Build it with `spawnEnv()`: nothing else is added. */\n readonly env: Readonly<Record<string, string>>;\n /** Aborts the command and every process it started. An already aborted signal rejects before the command runs. */\n readonly signal: AbortSignal;\n /** Stops a command, and every process it started, that runs longer than this, with exit code 124. */\n readonly timeoutMs?: number;\n /** The most bytes of each of standard output and standard error to keep. Defaults to 8 MiB; the rest is dropped. */\n readonly maxOutputBytes?: number;\n}\n\n/**\n * What a backend can do besides provisioning. `resume`: reattach to a sandbox by its id, such as after `pause` or a lost\n * connection, or start one from a snapshot's id. `snapshot`: save a sandbox's state under an id that `resume` takes.\n * `pause`: suspend a sandbox, keeping its state, until `resume`. A local backend has none of them.\n */\nexport type SandboxCapability = \"resume\" | \"snapshot\" | \"pause\";\n\n/** A provisioned sandbox. */\nexport interface Sandbox {\n /** Runs `command`, an executable and its arguments with no shell, and resolves with what it did. */\n exec(command: readonly string[], options: ExecOptions): Promise<ExecResult>;\n /** Reads a file by path relative to the workspace root, or absolute. A missing file rejects with `sandbox_not_found`. */\n readFile(path: string): Promise<Uint8Array>;\n /** Writes a file by path relative to the workspace root, or absolute, making its folders. */\n writeFile(path: string, data: Uint8Array): Promise<void>;\n /** Stops what is still running, and releases the sandbox. Calling it again does nothing, and any other call afterwards rejects. */\n dispose(): Promise<void>;\n /** The id `SandboxClient.resume()` takes. Only a sandbox from a backend with the `resume` capability has one. */\n readonly id?: string;\n /**\n * The stops the applied policy delivers, as `stopsFor()` computes them from the read-back. A backend that reads its\n * policy back sets it when it provisions, and one that enforces nothing leaves it out.\n */\n readonly stops?: readonly SandboxStop[];\n /**\n * Reads back the policy the backend applied, from the backend's own record of it, such as the settings file it wrote\n * or the policy a hosted provider reports. A backend that claims any stop has it, and `provision()` compares its\n * answer with the request and throws `SandboxPolicyMismatchError` when they differ.\n */\n readBack?(): Promise<SandboxPolicy>;\n /** Saves the sandbox's state and resolves with an id that `resume()` starts a sandbox from. Needs `snapshot`. */\n snapshot?(): Promise<string>;\n /** Suspends the sandbox until `resume()` with its `id`. Needs `pause`. */\n pause?(): Promise<void>;\n}\n\n/** A sandbox backend. */\nexport interface SandboxClient {\n readonly tier: SandboxTier;\n /** The stops the backend claims for every policy it accepts. `provision()` checks them against the applied policy. */\n readonly stops: readonly SandboxStop[];\n /** What the backend can do besides provisioning. Leaving it out means none; call each one through its helper. */\n readonly capabilities?: readonly SandboxCapability[];\n /**\n * Provisions a sandbox, or throws `SandboxUnavailableError` when the backend can't start. It never falls back. A\n * backend that claims a stop reads its policy back first, and throws `SandboxPolicyMismatchError` on a difference.\n */\n provision(manifest: WorkspaceManifest, policy: SandboxPolicy): Promise<Sandbox>;\n /**\n * Reattaches to the sandbox with this id, or starts one from the snapshot with this id. `policy` is the policy it must\n * still apply. Needs `resume`; call it through `resumeSandbox()`, which checks the read-back.\n */\n resume?(id: string, policy: SandboxPolicy): Promise<Sandbox>;\n}\n"]}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reads a client's answers to the server's requests. An answer is checked before it reaches the approvals or a tool
|
|
3
|
+
* call, because it comes from outside the process: an approval answer must name the request it was asked about and
|
|
4
|
+
* nothing else, and a tool result must have the shape the SDK takes.
|
|
5
|
+
*/
|
|
6
|
+
import type { Resolution, SignedPendingRequest, ToolResult } from "@buildanagent/sdk";
|
|
7
|
+
/**
|
|
8
|
+
* The one resolution an answer to `approval/request` or `clarification/request` gives for `request`, or `undefined` when
|
|
9
|
+
* the answer is malformed, names another request, or gives more than one. An approval takes `allow` or `deny` with an
|
|
10
|
+
* optional `reason`; a clarification takes an `answer`. Either may carry `by`.
|
|
11
|
+
*/
|
|
12
|
+
export declare function resolutionOf(result: unknown, request: SignedPendingRequest): Resolution | undefined;
|
|
13
|
+
/** An error result the model reads, for a tool call the client could not run. */
|
|
14
|
+
export declare function toolError(text: string): ToolResult;
|
|
15
|
+
/** The tool result a client's answer to `tool/call` gives, or an error result when the answer is not one. */
|
|
16
|
+
export declare function toolResultOf(result: unknown, tool: string): ToolResult;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2
|
+
const optionalText = (value) => value === undefined || typeof value === "string";
|
|
3
|
+
/**
|
|
4
|
+
* The one resolution an answer to `approval/request` or `clarification/request` gives for `request`, or `undefined` when
|
|
5
|
+
* the answer is malformed, names another request, or gives more than one. An approval takes `allow` or `deny` with an
|
|
6
|
+
* optional `reason`; a clarification takes an `answer`. Either may carry `by`.
|
|
7
|
+
*/
|
|
8
|
+
export function resolutionOf(result, request) {
|
|
9
|
+
if (!isObject(result) || !Array.isArray(result.resolutions) || result.resolutions.length !== 1)
|
|
10
|
+
return undefined;
|
|
11
|
+
const [given] = result.resolutions;
|
|
12
|
+
if (!isObject(given) || given.requestId !== request.id || !optionalText(given.by))
|
|
13
|
+
return undefined;
|
|
14
|
+
const by = given.by === undefined ? {} : { by: given.by };
|
|
15
|
+
if (request.kind === "clarification") {
|
|
16
|
+
return typeof given.answer === "string" && given.decision === undefined
|
|
17
|
+
? { requestId: request.id, answer: given.answer, ...by }
|
|
18
|
+
: undefined;
|
|
19
|
+
}
|
|
20
|
+
if ((given.decision !== "allow" && given.decision !== "deny") || given.answer !== undefined)
|
|
21
|
+
return undefined;
|
|
22
|
+
if (!optionalText(given.reason))
|
|
23
|
+
return undefined;
|
|
24
|
+
return {
|
|
25
|
+
requestId: request.id,
|
|
26
|
+
decision: given.decision,
|
|
27
|
+
...(given.reason === undefined ? {} : { reason: given.reason }),
|
|
28
|
+
...by,
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/** An error result the model reads, for a tool call the client could not run. */
|
|
32
|
+
export function toolError(text) {
|
|
33
|
+
return { content: [{ type: "text", text }], isError: true };
|
|
34
|
+
}
|
|
35
|
+
/** The tool result a client's answer to `tool/call` gives, or an error result when the answer is not one. */
|
|
36
|
+
export function toolResultOf(result, tool) {
|
|
37
|
+
if (!isObject(result) || !Array.isArray(result.content) || typeof result.isError !== "boolean") {
|
|
38
|
+
return toolError(`the client's answer to the call to ${tool} is not a tool result`);
|
|
39
|
+
}
|
|
40
|
+
// The SDK checks each block, so a block of the wrong kind becomes an error result there.
|
|
41
|
+
return { content: result.content, isError: result.isError };
|
|
42
|
+
}
|
|
43
|
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M,EAAE,GAAG,EAAE,EAAE;YACxD,CAAC,CAAC,SAAS,CAAC;IAChB,CAAC;IACD,IAAI,CAAC,KAAK,CAAC,QAAQ,KAAK,OAAO,IAAI,KAAK,CAAC,QAAQ,KAAK,MAAM,CAAC,IAAI,KAAK,CAAC,MAAM,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IAC9G,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,MAAM,CAAC;QAAE,OAAO,SAAS,CAAC;IAClD,OAAO;QACL,SAAS,EAAE,OAAO,CAAC,EAAE;QACrB,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,GAAG,CAAC,KAAK,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,MAAgB,EAAE,CAAC;QACzE,GAAG,EAAE;KACN,CAAC;AACJ,CAAC;AAED,iFAAiF;AACjF,MAAM,UAAU,SAAS,CAAC,IAAY;IACpC,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AAC9D,CAAC;AAED,6GAA6G;AAC7G,MAAM,UAAU,YAAY,CAAC,MAAe,EAAE,IAAY;IACxD,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,OAAO,MAAM,CAAC,OAAO,KAAK,SAAS,EAAE,CAAC;QAC/F,OAAO,SAAS,CAAC,sCAAsC,IAAI,uBAAuB,CAAC,CAAC;IACtF,CAAC;IACD,yFAAyF;IACzF,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,OAAgC,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC;AACvF,CAAC","sourcesContent":["/**\n * Reads a client's answers to the server's requests. An answer is checked before it reaches the approvals or a tool\n * call, because it comes from outside the process: an approval answer must name the request it was asked about and\n * nothing else, and a tool result must have the shape the SDK takes.\n */\nimport type { Resolution, SignedPendingRequest, ToolResult } from \"@buildanagent/sdk\";\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst optionalText = (value: unknown): boolean => value === undefined || typeof value === \"string\";\n\n/**\n * The one resolution an answer to `approval/request` or `clarification/request` gives for `request`, or `undefined` when\n * the answer is malformed, names another request, or gives more than one. An approval takes `allow` or `deny` with an\n * optional `reason`; a clarification takes an `answer`. Either may carry `by`.\n */\nexport function resolutionOf(result: unknown, request: SignedPendingRequest): Resolution | undefined {\n if (!isObject(result) || !Array.isArray(result.resolutions) || result.resolutions.length !== 1) return undefined;\n const [given] = result.resolutions as unknown[];\n if (!isObject(given) || given.requestId !== request.id || !optionalText(given.by)) return undefined;\n const by = given.by === undefined ? {} : { by: given.by as string };\n if (request.kind === \"clarification\") {\n return typeof given.answer === \"string\" && given.decision === undefined\n ? { requestId: request.id, answer: given.answer, ...by }\n : undefined;\n }\n if ((given.decision !== \"allow\" && given.decision !== \"deny\") || given.answer !== undefined) return undefined;\n if (!optionalText(given.reason)) return undefined;\n return {\n requestId: request.id,\n decision: given.decision,\n ...(given.reason === undefined ? {} : { reason: given.reason as string }),\n ...by,\n };\n}\n\n/** An error result the model reads, for a tool call the client could not run. */\nexport function toolError(text: string): ToolResult {\n return { content: [{ type: \"text\", text }], isError: true };\n}\n\n/** The tool result a client's answer to `tool/call` gives, or an error result when the answer is not one. */\nexport function toolResultOf(result: unknown, tool: string): ToolResult {\n if (!isObject(result) || !Array.isArray(result.content) || typeof result.isError !== \"boolean\") {\n return toolError(`the client's answer to the call to ${tool} is not a tool result`);\n }\n // The SDK checks each block, so a block of the wrong kind becomes an error result there.\n return { content: result.content as ToolResult[\"content\"], isError: result.isError };\n}\n"]}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One client's end of the dispatcher: what it may see, what it has asked, and what the server has asked it. A
|
|
3
|
+
* connection receives only the events of the sessions it created or opened. It holds at most `limit` commands at a
|
|
4
|
+
* time, counting each until its response has gone out, so a client that sends faster than it reads is refused with
|
|
5
|
+
* `QueueFull` instead of growing the queue. At most `limit` refusals wait to go out, and past that the connection is
|
|
6
|
+
* closed, because a client that neither reads nor waits would otherwise grow the queue with refusals. What waits also
|
|
7
|
+
* bounds the server requests the connection holds: one per pending approval or clarification of a session it watches,
|
|
8
|
+
* and one per `client_request` tool call that a turn it started makes.
|
|
9
|
+
*/
|
|
10
|
+
import { type ClientCommand, type ClientMessage, type Id, type RpcError, type ServerMessage, type ServerNotification, type ServerRequest } from "@buildanagent/protocol";
|
|
11
|
+
import { type Deliver } from "./outbox.js";
|
|
12
|
+
/** A client's answer to a server request: its result, or the error it sent instead. */
|
|
13
|
+
export type ServerAnswer = {
|
|
14
|
+
readonly result: unknown;
|
|
15
|
+
} | {
|
|
16
|
+
readonly error: RpcError;
|
|
17
|
+
};
|
|
18
|
+
/** A server request the client has not answered yet. */
|
|
19
|
+
export interface Asked {
|
|
20
|
+
readonly session: string;
|
|
21
|
+
/** For an approval or a clarification, the id of the signed request it asks about. */
|
|
22
|
+
readonly pendingId?: string;
|
|
23
|
+
/** Called once with the client's answer. */
|
|
24
|
+
answer(answer: ServerAnswer): void;
|
|
25
|
+
/** Called once if the connection closes before an answer. */
|
|
26
|
+
lost(): void;
|
|
27
|
+
}
|
|
28
|
+
/** What a connection asks of the dispatcher it belongs to. */
|
|
29
|
+
export interface ConnectionHost {
|
|
30
|
+
/** Runs one command and returns its result, with what to do once the response has gone out. */
|
|
31
|
+
dispatch(connection: ServerConnection, command: ClientCommand & {
|
|
32
|
+
id: Id;
|
|
33
|
+
}): Promise<Dispatched>;
|
|
34
|
+
/** Forgets a connection that closed. */
|
|
35
|
+
detach(connection: ServerConnection): void;
|
|
36
|
+
}
|
|
37
|
+
/** A command's outcome: its result, and what runs right after its response has been queued. */
|
|
38
|
+
export interface Dispatched {
|
|
39
|
+
readonly result: unknown;
|
|
40
|
+
readonly after?: () => void;
|
|
41
|
+
}
|
|
42
|
+
/** An error the dispatcher answers a command with. */
|
|
43
|
+
export declare class Failure extends Error {
|
|
44
|
+
readonly rpc: RpcError;
|
|
45
|
+
constructor(code: number, message: string);
|
|
46
|
+
}
|
|
47
|
+
type EventMessage = Extract<ServerNotification, {
|
|
48
|
+
method: "event";
|
|
49
|
+
}>;
|
|
50
|
+
type SettledMessage = Extract<ServerNotification, {
|
|
51
|
+
method: "turn/settled";
|
|
52
|
+
}>;
|
|
53
|
+
/** One client's connection to the dispatcher, as the module comment describes. */
|
|
54
|
+
export declare class ServerConnection {
|
|
55
|
+
#private;
|
|
56
|
+
constructor(host: ConnectionHost, deliver: Deliver, limit: number, onClose?: () => void);
|
|
57
|
+
/** Whether the client is still connected. */
|
|
58
|
+
get open(): boolean;
|
|
59
|
+
/** Sends a message that belongs to no session's stream: a response or a cancel. */
|
|
60
|
+
send(message: ServerMessage): void;
|
|
61
|
+
/** Sends a session's `turn/settled` to a connection that watches it, after any replay that is being prepared. */
|
|
62
|
+
settled(message: SettledMessage): void;
|
|
63
|
+
/** Sends a live event of a session this connection watches, or holds it while the session is being opened. */
|
|
64
|
+
event(message: EventMessage): void;
|
|
65
|
+
watch(session: string): void;
|
|
66
|
+
/** Whether this connection created or opened the session. */
|
|
67
|
+
watching(session: string): boolean;
|
|
68
|
+
/** Starts holding a session's live events, so none is lost or sent early while its log is read. False if one is already held. */
|
|
69
|
+
hold(session: string): boolean;
|
|
70
|
+
/**
|
|
71
|
+
* Ends the hold of a failed open, and leaves the session as watched or unwatched as it was. A connection that
|
|
72
|
+
* already watched the session still gets what was held, because those messages are its live stream; one that did
|
|
73
|
+
* not gets nothing.
|
|
74
|
+
*/
|
|
75
|
+
unhold(session: string): void;
|
|
76
|
+
/**
|
|
77
|
+
* Watches the session: sends `replay`, which is never dropped, then what was held since `hold()`, leaving out an
|
|
78
|
+
* appended entry whose `seq` is at or before `replayedTo` because the replay already carried it.
|
|
79
|
+
*/
|
|
80
|
+
release(session: string, replay: readonly EventMessage[], replayedTo: number): void;
|
|
81
|
+
optIn(methods: readonly string[]): void;
|
|
82
|
+
optedIn(method: string): boolean;
|
|
83
|
+
/** Sends a server request and remembers it until the client answers, the server withdraws it, or the connection closes. */
|
|
84
|
+
ask(request: ServerRequest, asked: Asked): void;
|
|
85
|
+
/** Whether an approval or clarification about this signed request waits for this client's answer. */
|
|
86
|
+
asking(pendingId: string): boolean;
|
|
87
|
+
/** Withdraws a server request with `$/cancelRequest`. Returns false when it was already answered or withdrawn. */
|
|
88
|
+
withdraw(id: string): boolean;
|
|
89
|
+
/** Withdraws every request this client holds about one signed request, because someone else answered it. */
|
|
90
|
+
withdrawPending(pendingId: string): void;
|
|
91
|
+
/** Lets the client cancel its own `turn/start` by id until the turn settles. */
|
|
92
|
+
trackTurn(id: Id, cancel: () => void): void;
|
|
93
|
+
/** Stops tracking a turn, unless a later `turn/start` that reused the id has replaced its canceller. */
|
|
94
|
+
untrackTurn(id: Id, cancel: () => void): void;
|
|
95
|
+
close(): void;
|
|
96
|
+
/** Handles one message from the client, and resolves once its response, if it has one, is queued. */
|
|
97
|
+
receive(message: ClientMessage): Promise<void>;
|
|
98
|
+
}
|
|
99
|
+
export {};
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One client's end of the dispatcher: what it may see, what it has asked, and what the server has asked it. A
|
|
3
|
+
* connection receives only the events of the sessions it created or opened. It holds at most `limit` commands at a
|
|
4
|
+
* time, counting each until its response has gone out, so a client that sends faster than it reads is refused with
|
|
5
|
+
* `QueueFull` instead of growing the queue. At most `limit` refusals wait to go out, and past that the connection is
|
|
6
|
+
* closed, because a client that neither reads nor waits would otherwise grow the queue with refusals. What waits also
|
|
7
|
+
* bounds the server requests the connection holds: one per pending approval or clarification of a session it watches,
|
|
8
|
+
* and one per `client_request` tool call that a turn it started makes.
|
|
9
|
+
*/
|
|
10
|
+
import { ErrorCodes, } from "@buildanagent/protocol";
|
|
11
|
+
import { isHarnessError } from "../errors.js";
|
|
12
|
+
import { Outbox } from "./outbox.js";
|
|
13
|
+
/** An error the dispatcher answers a command with. */
|
|
14
|
+
export class Failure extends Error {
|
|
15
|
+
rpc;
|
|
16
|
+
constructor(code, message) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.rpc = { code, message };
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
const isId = (value) => typeof value === "string" || (typeof value === "number" && Number.isFinite(value));
|
|
22
|
+
/** One client's connection to the dispatcher, as the module comment describes. */
|
|
23
|
+
export class ServerConnection {
|
|
24
|
+
#host;
|
|
25
|
+
#outbox;
|
|
26
|
+
#limit;
|
|
27
|
+
#watching = new Set();
|
|
28
|
+
#held = new Map();
|
|
29
|
+
#optedIn = new Set();
|
|
30
|
+
#asked = new Map();
|
|
31
|
+
#turns = new Map();
|
|
32
|
+
#inFlight = 0;
|
|
33
|
+
#refusals = 0;
|
|
34
|
+
#open = true;
|
|
35
|
+
#onClose;
|
|
36
|
+
constructor(host, deliver, limit, onClose) {
|
|
37
|
+
this.#host = host;
|
|
38
|
+
this.#outbox = new Outbox(deliver, limit);
|
|
39
|
+
this.#limit = limit;
|
|
40
|
+
this.#onClose = onClose;
|
|
41
|
+
}
|
|
42
|
+
/** Whether the client is still connected. */
|
|
43
|
+
get open() {
|
|
44
|
+
return this.#open;
|
|
45
|
+
}
|
|
46
|
+
/** Sends a message that belongs to no session's stream: a response or a cancel. */
|
|
47
|
+
send(message) {
|
|
48
|
+
this.#outbox.push(message);
|
|
49
|
+
}
|
|
50
|
+
/** Sends a session's `turn/settled` to a connection that watches it, after any replay that is being prepared. */
|
|
51
|
+
settled(message) {
|
|
52
|
+
const held = this.#held.get(message.params.session);
|
|
53
|
+
if (held !== undefined)
|
|
54
|
+
held.messages.push(message);
|
|
55
|
+
else if (this.#watching.has(message.params.session))
|
|
56
|
+
this.#outbox.push(message);
|
|
57
|
+
}
|
|
58
|
+
/** Sends a live event of a session this connection watches, or holds it while the session is being opened. */
|
|
59
|
+
event(message) {
|
|
60
|
+
const held = this.#held.get(message.params.session);
|
|
61
|
+
if (held === undefined) {
|
|
62
|
+
if (this.#watching.has(message.params.session))
|
|
63
|
+
this.#outbox.push(message);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
// A hold lasts one read of the log, and is bounded as the queue is: past the bound, events are counted as dropped.
|
|
67
|
+
if (held.events < this.#limit) {
|
|
68
|
+
held.messages.push(message);
|
|
69
|
+
held.events += 1;
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
held.gapAt ??= held.messages.length;
|
|
73
|
+
const { seq } = message.params;
|
|
74
|
+
if (message.params.event.type === "entry_appended") {
|
|
75
|
+
held.droppedEntries = { first: held.droppedEntries?.first ?? seq, last: seq };
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
held.dropped += 1;
|
|
79
|
+
held.lastDroppedSeq = Math.max(held.lastDroppedSeq, seq);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
watch(session) {
|
|
84
|
+
this.#watching.add(session);
|
|
85
|
+
}
|
|
86
|
+
/** Whether this connection created or opened the session. */
|
|
87
|
+
watching(session) {
|
|
88
|
+
return this.#watching.has(session);
|
|
89
|
+
}
|
|
90
|
+
/** Starts holding a session's live events, so none is lost or sent early while its log is read. False if one is already held. */
|
|
91
|
+
hold(session) {
|
|
92
|
+
if (this.#held.has(session))
|
|
93
|
+
return false;
|
|
94
|
+
this.#held.set(session, {
|
|
95
|
+
messages: [],
|
|
96
|
+
events: 0,
|
|
97
|
+
dropped: 0,
|
|
98
|
+
lastDroppedSeq: -1,
|
|
99
|
+
droppedEntries: undefined,
|
|
100
|
+
gapAt: undefined,
|
|
101
|
+
});
|
|
102
|
+
return true;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Ends the hold of a failed open, and leaves the session as watched or unwatched as it was. A connection that
|
|
106
|
+
* already watched the session still gets what was held, because those messages are its live stream; one that did
|
|
107
|
+
* not gets nothing.
|
|
108
|
+
*/
|
|
109
|
+
unhold(session) {
|
|
110
|
+
if (this.#watching.has(session))
|
|
111
|
+
this.release(session, [], -1);
|
|
112
|
+
else
|
|
113
|
+
this.#held.delete(session);
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Watches the session: sends `replay`, which is never dropped, then what was held since `hold()`, leaving out an
|
|
117
|
+
* appended entry whose `seq` is at or before `replayedTo` because the replay already carried it.
|
|
118
|
+
*/
|
|
119
|
+
release(session, replay, replayedTo) {
|
|
120
|
+
const held = this.#held.get(session);
|
|
121
|
+
this.#held.delete(session);
|
|
122
|
+
this.#watching.add(session);
|
|
123
|
+
for (const message of replay)
|
|
124
|
+
this.#outbox.push(message, { keep: true });
|
|
125
|
+
const marker = () => {
|
|
126
|
+
const gap = held === undefined ? undefined : gapOf(held, replayedTo);
|
|
127
|
+
if (gap !== undefined)
|
|
128
|
+
this.#outbox.pushGap(session, gap.count, gap.seq);
|
|
129
|
+
};
|
|
130
|
+
for (const [index, message] of (held?.messages ?? []).entries()) {
|
|
131
|
+
// The drops began once the hold was full, so their marker goes out before what was held after them.
|
|
132
|
+
if (index === held?.gapAt)
|
|
133
|
+
marker();
|
|
134
|
+
if (message.method === "event" && message.params.event.type === "entry_appended") {
|
|
135
|
+
if (message.params.seq <= replayedTo)
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
this.#outbox.push(message);
|
|
139
|
+
}
|
|
140
|
+
if (held?.gapAt !== undefined && held.gapAt >= held.messages.length)
|
|
141
|
+
marker();
|
|
142
|
+
}
|
|
143
|
+
optIn(methods) {
|
|
144
|
+
for (const method of methods)
|
|
145
|
+
this.#optedIn.add(method);
|
|
146
|
+
}
|
|
147
|
+
optedIn(method) {
|
|
148
|
+
return this.#optedIn.has(method);
|
|
149
|
+
}
|
|
150
|
+
/** Sends a server request and remembers it until the client answers, the server withdraws it, or the connection closes. */
|
|
151
|
+
ask(request, asked) {
|
|
152
|
+
if (!this.#open) {
|
|
153
|
+
asked.lost();
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
this.#asked.set(request.id, asked);
|
|
157
|
+
this.#outbox.push(request);
|
|
158
|
+
}
|
|
159
|
+
/** Whether an approval or clarification about this signed request waits for this client's answer. */
|
|
160
|
+
asking(pendingId) {
|
|
161
|
+
for (const asked of this.#asked.values())
|
|
162
|
+
if (asked.pendingId === pendingId)
|
|
163
|
+
return true;
|
|
164
|
+
return false;
|
|
165
|
+
}
|
|
166
|
+
/** Withdraws a server request with `$/cancelRequest`. Returns false when it was already answered or withdrawn. */
|
|
167
|
+
withdraw(id) {
|
|
168
|
+
if (!this.#asked.delete(id))
|
|
169
|
+
return false;
|
|
170
|
+
if (this.#open)
|
|
171
|
+
this.send({ jsonrpc: "2.0", method: "$/cancelRequest", params: { id } });
|
|
172
|
+
return true;
|
|
173
|
+
}
|
|
174
|
+
/** Withdraws every request this client holds about one signed request, because someone else answered it. */
|
|
175
|
+
withdrawPending(pendingId) {
|
|
176
|
+
for (const [id, asked] of [...this.#asked])
|
|
177
|
+
if (asked.pendingId === pendingId)
|
|
178
|
+
this.withdraw(id);
|
|
179
|
+
}
|
|
180
|
+
/** Lets the client cancel its own `turn/start` by id until the turn settles. */
|
|
181
|
+
trackTurn(id, cancel) {
|
|
182
|
+
this.#turns.set(id, cancel);
|
|
183
|
+
}
|
|
184
|
+
/** Stops tracking a turn, unless a later `turn/start` that reused the id has replaced its canceller. */
|
|
185
|
+
untrackTurn(id, cancel) {
|
|
186
|
+
if (this.#turns.get(id) === cancel)
|
|
187
|
+
this.#turns.delete(id);
|
|
188
|
+
}
|
|
189
|
+
close() {
|
|
190
|
+
if (!this.#open)
|
|
191
|
+
return;
|
|
192
|
+
this.#open = false;
|
|
193
|
+
this.#outbox.close();
|
|
194
|
+
const asked = [...this.#asked.values()];
|
|
195
|
+
this.#asked.clear();
|
|
196
|
+
this.#turns.clear();
|
|
197
|
+
this.#held.clear();
|
|
198
|
+
this.#host.detach(this);
|
|
199
|
+
for (const request of asked)
|
|
200
|
+
request.lost();
|
|
201
|
+
// The transport learns of a close it did not ask for, such as one for refusals left unread.
|
|
202
|
+
try {
|
|
203
|
+
this.#onClose?.();
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
// A transport's own failure must not stop the close.
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
/** Handles one message from the client, and resolves once its response, if it has one, is queued. */
|
|
210
|
+
async receive(message) {
|
|
211
|
+
if (!this.#open)
|
|
212
|
+
return;
|
|
213
|
+
if (!("method" in message)) {
|
|
214
|
+
this.#answered(message);
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
if (!("id" in message)) {
|
|
218
|
+
if (message.method === "$/cancelRequest")
|
|
219
|
+
this.#cancel(message.params?.id);
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
await this.#command(message);
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Answers a command the full queue can't take with `QueueFull`. The refusal takes no command's place, but it waits to
|
|
226
|
+
* go out like any response, so a client that keeps sending without reading would grow the queue: once `limit`
|
|
227
|
+
* refusals wait, the server closes the connection instead.
|
|
228
|
+
*/
|
|
229
|
+
#refuse(id) {
|
|
230
|
+
if (this.#refusals >= this.#limit) {
|
|
231
|
+
this.close();
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
this.#refusals += 1;
|
|
235
|
+
this.#outbox.push({
|
|
236
|
+
jsonrpc: "2.0",
|
|
237
|
+
id,
|
|
238
|
+
error: { code: ErrorCodes.QueueFull, message: `the queue holds ${this.#limit} commands; send again later` },
|
|
239
|
+
}, {
|
|
240
|
+
onSent: () => {
|
|
241
|
+
this.#refusals -= 1;
|
|
242
|
+
},
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
/** A client's answer to a server request. One with an id this connection is not waiting on is ignored. */
|
|
246
|
+
#answered(message) {
|
|
247
|
+
if (typeof message.id !== "string")
|
|
248
|
+
return;
|
|
249
|
+
const asked = this.#asked.get(message.id);
|
|
250
|
+
if (asked === undefined)
|
|
251
|
+
return;
|
|
252
|
+
this.#asked.delete(message.id);
|
|
253
|
+
asked.answer("error" in message ? { error: message.error } : { result: message.result });
|
|
254
|
+
}
|
|
255
|
+
#cancel(id) {
|
|
256
|
+
if (isId(id))
|
|
257
|
+
this.#turns.get(id)?.();
|
|
258
|
+
}
|
|
259
|
+
async #command(command) {
|
|
260
|
+
if (this.#inFlight >= this.#limit) {
|
|
261
|
+
this.#refuse(command.id);
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
this.#inFlight += 1;
|
|
265
|
+
// The command holds its place until its response has gone out, so a client that doesn't read is refused soon.
|
|
266
|
+
const onSent = () => {
|
|
267
|
+
this.#inFlight -= 1;
|
|
268
|
+
};
|
|
269
|
+
let after;
|
|
270
|
+
try {
|
|
271
|
+
const outcome = await this.#host.dispatch(this, command);
|
|
272
|
+
after = outcome.after;
|
|
273
|
+
this.#outbox.push({ jsonrpc: "2.0", id: command.id, result: outcome.result }, { onSent });
|
|
274
|
+
}
|
|
275
|
+
catch (error) {
|
|
276
|
+
this.#outbox.push({ jsonrpc: "2.0", id: command.id, error: rpcErrorOf(error) }, { onSent });
|
|
277
|
+
}
|
|
278
|
+
finally {
|
|
279
|
+
// A closed outbox drops the response, so it never calls back.
|
|
280
|
+
if (!this.#open)
|
|
281
|
+
this.#inFlight = 0;
|
|
282
|
+
after?.();
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* What a hold really lost: its dropped events, less the entries the replay carried up to `replayedTo`. The marker's
|
|
288
|
+
* `seq` is never below `replayedTo`, because the client has everything up to there. `undefined` when nothing was lost.
|
|
289
|
+
*/
|
|
290
|
+
function gapOf(held, replayedTo) {
|
|
291
|
+
const entries = held.droppedEntries;
|
|
292
|
+
const lostEntries = entries === undefined ? 0 : Math.max(0, entries.last - Math.max(entries.first, replayedTo + 1) + 1);
|
|
293
|
+
const count = held.dropped + lostEntries;
|
|
294
|
+
if (count === 0)
|
|
295
|
+
return undefined;
|
|
296
|
+
return { count, seq: Math.max(held.lastDroppedSeq, entries?.last ?? -1, replayedTo) };
|
|
297
|
+
}
|
|
298
|
+
/** The error a failed command answers with. */
|
|
299
|
+
function rpcErrorOf(error) {
|
|
300
|
+
if (error instanceof Failure)
|
|
301
|
+
return error.rpc;
|
|
302
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
303
|
+
if (isHarnessError(error) && error.code === "entry_not_found")
|
|
304
|
+
return { code: ErrorCodes.InvalidParams, message };
|
|
305
|
+
if (isHarnessError(error) && error.code === "session_locked")
|
|
306
|
+
return { code: ErrorCodes.SessionLocked, message };
|
|
307
|
+
return { code: ErrorCodes.InternalError, message };
|
|
308
|
+
}
|
|
309
|
+
//# sourceMappingURL=connection.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connection.js","sourceRoot":"","sources":["../../src/server/connection.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAGL,UAAU,GAMX,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAgB,MAAM,EAAE,MAAM,aAAa,CAAC;AA8BnD,sDAAsD;AACtD,MAAM,OAAO,OAAQ,SAAQ,KAAK;IACvB,GAAG,CAAW;IACvB,YAAY,IAAY,EAAE,OAAe;QACvC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,GAAG,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;IAC/B,CAAC;CACF;AAyBD,MAAM,IAAI,GAAG,CAAC,KAAc,EAAe,EAAE,CAC3C,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,KAA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G,CAAC,CAAC,EAAE,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,UAAU,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;IACtG,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,GAAG,WAAW,CAAC;IACzC,IAAI,KAAK,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IAClC,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,cAAc,EAAE,OAAO,EAAE,IAAI,IAAI,CAAC,CAAC,EAAE,UAAU,CAAC,EAAE,CAAC;AACxF,CAAC;AAED,+CAA+C;AAC/C,SAAS,UAAU,CAAC,KAAc;IAChC,IAAI,KAAK,YAAY,OAAO;QAAE,OAAO,KAAK,CAAC,GAAG,CAAC;IAC/C,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACvE,IAAI,cAAc,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,iBAAiB;QAAE,OAAO,EAAE,IAAI,EAAE,UAAU,CAAC,aAAa,EAAE,OAAO,EAAE,CAAC;IAClH,IAAI,cAAc,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,gBAAgB;QAAE,OAAO,EAAE,IAAI,EAAE,UAAU,CAAC,aAAa,EAAE,OAAO,EAAE,CAAC;IACjH,OAAO,EAAE,IAAI,EAAE,UAAU,CAAC,aAAa,EAAE,OAAO,EAAE,CAAC;AACrD,CAAC","sourcesContent":["/**\n * One client's end of the dispatcher: what it may see, what it has asked, and what the server has asked it. A\n * connection receives only the events of the sessions it created or opened. It holds at most `limit` commands at a\n * time, counting each until its response has gone out, so a client that sends faster than it reads is refused with\n * `QueueFull` instead of growing the queue. At most `limit` refusals wait to go out, and past that the connection is\n * closed, because a client that neither reads nor waits would otherwise grow the queue with refusals. What waits also\n * bounds the server requests the connection holds: one per pending approval or clarification of a session it watches,\n * and one per `client_request` tool call that a turn it started makes.\n */\nimport {\n type ClientCommand,\n type ClientMessage,\n ErrorCodes,\n type Id,\n type RpcError,\n type ServerMessage,\n type ServerNotification,\n type ServerRequest,\n} from \"@buildanagent/protocol\";\nimport { isHarnessError } from \"../errors.js\";\nimport { type Deliver, Outbox } from \"./outbox.js\";\n\n/** A client's answer to a server request: its result, or the error it sent instead. */\nexport type ServerAnswer = { readonly result: unknown } | { readonly error: RpcError };\n\n/** A server request the client has not answered yet. */\nexport interface Asked {\n readonly session: string;\n /** For an approval or a clarification, the id of the signed request it asks about. */\n readonly pendingId?: string;\n /** Called once with the client's answer. */\n answer(answer: ServerAnswer): void;\n /** Called once if the connection closes before an answer. */\n lost(): void;\n}\n\n/** What a connection asks of the dispatcher it belongs to. */\nexport interface ConnectionHost {\n /** Runs one command and returns its result, with what to do once the response has gone out. */\n dispatch(connection: ServerConnection, command: ClientCommand & { id: Id }): Promise<Dispatched>;\n /** Forgets a connection that closed. */\n detach(connection: ServerConnection): void;\n}\n\n/** A command's outcome: its result, and what runs right after its response has been queued. */\nexport interface Dispatched {\n readonly result: unknown;\n readonly after?: () => void;\n}\n\n/** An error the dispatcher answers a command with. */\nexport class Failure extends Error {\n readonly rpc: RpcError;\n constructor(code: number, message: string) {\n super(message);\n this.rpc = { code, message };\n }\n}\n\ntype EventMessage = Extract<ServerNotification, { method: \"event\" }>;\ntype SettledMessage = Extract<ServerNotification, { method: \"turn/settled\" }>;\n\n/**\n * What a session sent while a `session/open` was reading its log, waiting to go out after the replay. Events count\n * against the bound. A `turn/settled` is always kept, and needs no bound of its own: the session runs one turn at a\n * time, so one read of the log sees few of them.\n */\ninterface Held {\n readonly messages: (EventMessage | SettledMessage)[];\n events: number;\n /** Dropped events that are not entries, and the latest `seq` among them. */\n dropped: number;\n lastDroppedSeq: number;\n /**\n * The first and last `seq` of the dropped entries. Once the hold is full every later entry is dropped, so the range\n * has no hole, and the replay may already carry its start.\n */\n droppedEntries: { first: number; last: number } | undefined;\n /** How many of `messages` came before the first drop, so the marker goes out where the drops were. */\n gapAt: number | undefined;\n}\n\nconst isId = (value: unknown): value is Id =>\n typeof value === \"string\" || (typeof value === \"number\" && Number.isFinite(value));\n\n/** One client's connection to the dispatcher, as the module comment describes. */\nexport class ServerConnection {\n readonly #host: ConnectionHost;\n readonly #outbox: Outbox;\n readonly #limit: number;\n readonly #watching = new Set<string>();\n readonly #held = new Map<string, Held>();\n readonly #optedIn = new Set<string>();\n readonly #asked = new Map<string, Asked>();\n readonly #turns = new Map<Id, () => void>();\n #inFlight = 0;\n #refusals = 0;\n #open = true;\n readonly #onClose: (() => void) | undefined;\n\n constructor(host: ConnectionHost, deliver: Deliver, limit: number, onClose?: () => void) {\n this.#host = host;\n this.#outbox = new Outbox(deliver, limit);\n this.#limit = limit;\n this.#onClose = onClose;\n }\n\n /** Whether the client is still connected. */\n get open(): boolean {\n return this.#open;\n }\n\n /** Sends a message that belongs to no session's stream: a response or a cancel. */\n send(message: ServerMessage): void {\n this.#outbox.push(message);\n }\n\n /** Sends a session's `turn/settled` to a connection that watches it, after any replay that is being prepared. */\n settled(message: SettledMessage): void {\n const held = this.#held.get(message.params.session);\n if (held !== undefined) held.messages.push(message);\n else if (this.#watching.has(message.params.session)) this.#outbox.push(message);\n }\n\n /** Sends a live event of a session this connection watches, or holds it while the session is being opened. */\n event(message: EventMessage): void {\n const held = this.#held.get(message.params.session);\n if (held === undefined) {\n if (this.#watching.has(message.params.session)) this.#outbox.push(message);\n return;\n }\n // A hold lasts one read of the log, and is bounded as the queue is: past the bound, events are counted as dropped.\n if (held.events < this.#limit) {\n held.messages.push(message);\n held.events += 1;\n } else {\n held.gapAt ??= held.messages.length;\n const { seq } = message.params;\n if (message.params.event.type === \"entry_appended\") {\n held.droppedEntries = { first: held.droppedEntries?.first ?? seq, last: seq };\n } else {\n held.dropped += 1;\n held.lastDroppedSeq = Math.max(held.lastDroppedSeq, seq);\n }\n }\n }\n\n watch(session: string): void {\n this.#watching.add(session);\n }\n\n /** Whether this connection created or opened the session. */\n watching(session: string): boolean {\n return this.#watching.has(session);\n }\n\n /** Starts holding a session's live events, so none is lost or sent early while its log is read. False if one is already held. */\n hold(session: string): boolean {\n if (this.#held.has(session)) return false;\n this.#held.set(session, {\n messages: [],\n events: 0,\n dropped: 0,\n lastDroppedSeq: -1,\n droppedEntries: undefined,\n gapAt: undefined,\n });\n return true;\n }\n\n /**\n * Ends the hold of a failed open, and leaves the session as watched or unwatched as it was. A connection that\n * already watched the session still gets what was held, because those messages are its live stream; one that did\n * not gets nothing.\n */\n unhold(session: string): void {\n if (this.#watching.has(session)) this.release(session, [], -1);\n else this.#held.delete(session);\n }\n\n /**\n * Watches the session: sends `replay`, which is never dropped, then what was held since `hold()`, leaving out an\n * appended entry whose `seq` is at or before `replayedTo` because the replay already carried it.\n */\n release(session: string, replay: readonly EventMessage[], replayedTo: number): void {\n const held = this.#held.get(session);\n this.#held.delete(session);\n this.#watching.add(session);\n for (const message of replay) this.#outbox.push(message, { keep: true });\n const marker = () => {\n const gap = held === undefined ? undefined : gapOf(held, replayedTo);\n if (gap !== undefined) this.#outbox.pushGap(session, gap.count, gap.seq);\n };\n for (const [index, message] of (held?.messages ?? []).entries()) {\n // The drops began once the hold was full, so their marker goes out before what was held after them.\n if (index === held?.gapAt) marker();\n if (message.method === \"event\" && message.params.event.type === \"entry_appended\") {\n if (message.params.seq <= replayedTo) continue;\n }\n this.#outbox.push(message);\n }\n if (held?.gapAt !== undefined && held.gapAt >= held.messages.length) marker();\n }\n\n optIn(methods: readonly string[]): void {\n for (const method of methods) this.#optedIn.add(method);\n }\n\n optedIn(method: string): boolean {\n return this.#optedIn.has(method);\n }\n\n /** Sends a server request and remembers it until the client answers, the server withdraws it, or the connection closes. */\n ask(request: ServerRequest, asked: Asked): void {\n if (!this.#open) {\n asked.lost();\n return;\n }\n this.#asked.set(request.id, asked);\n this.#outbox.push(request);\n }\n\n /** Whether an approval or clarification about this signed request waits for this client's answer. */\n asking(pendingId: string): boolean {\n for (const asked of this.#asked.values()) if (asked.pendingId === pendingId) return true;\n return false;\n }\n\n /** Withdraws a server request with `$/cancelRequest`. Returns false when it was already answered or withdrawn. */\n withdraw(id: string): boolean {\n if (!this.#asked.delete(id)) return false;\n if (this.#open) this.send({ jsonrpc: \"2.0\", method: \"$/cancelRequest\", params: { id } });\n return true;\n }\n\n /** Withdraws every request this client holds about one signed request, because someone else answered it. */\n withdrawPending(pendingId: string): void {\n for (const [id, asked] of [...this.#asked]) if (asked.pendingId === pendingId) this.withdraw(id);\n }\n\n /** Lets the client cancel its own `turn/start` by id until the turn settles. */\n trackTurn(id: Id, cancel: () => void): void {\n this.#turns.set(id, cancel);\n }\n\n /** Stops tracking a turn, unless a later `turn/start` that reused the id has replaced its canceller. */\n untrackTurn(id: Id, cancel: () => void): void {\n if (this.#turns.get(id) === cancel) this.#turns.delete(id);\n }\n\n close(): void {\n if (!this.#open) return;\n this.#open = false;\n this.#outbox.close();\n const asked = [...this.#asked.values()];\n this.#asked.clear();\n this.#turns.clear();\n this.#held.clear();\n this.#host.detach(this);\n for (const request of asked) request.lost();\n // The transport learns of a close it did not ask for, such as one for refusals left unread.\n try {\n this.#onClose?.();\n } catch {\n // A transport's own failure must not stop the close.\n }\n }\n\n /** Handles one message from the client, and resolves once its response, if it has one, is queued. */\n async receive(message: ClientMessage): Promise<void> {\n if (!this.#open) return;\n if (!(\"method\" in message)) {\n this.#answered(message);\n return;\n }\n if (!(\"id\" in message)) {\n if (message.method === \"$/cancelRequest\") this.#cancel(message.params?.id);\n return;\n }\n await this.#command(message as ClientCommand & { id: Id });\n }\n\n /**\n * Answers a command the full queue can't take with `QueueFull`. The refusal takes no command's place, but it waits to\n * go out like any response, so a client that keeps sending without reading would grow the queue: once `limit`\n * refusals wait, the server closes the connection instead.\n */\n #refuse(id: Id): void {\n if (this.#refusals >= this.#limit) {\n this.close();\n return;\n }\n this.#refusals += 1;\n this.#outbox.push(\n {\n jsonrpc: \"2.0\",\n id,\n error: { code: ErrorCodes.QueueFull, message: `the queue holds ${this.#limit} commands; send again later` },\n },\n {\n onSent: () => {\n this.#refusals -= 1;\n },\n },\n );\n }\n\n /** A client's answer to a server request. One with an id this connection is not waiting on is ignored. */\n #answered(message: Exclude<ClientMessage, ClientCommand>): void {\n if (typeof message.id !== \"string\") return;\n const asked = this.#asked.get(message.id);\n if (asked === undefined) return;\n this.#asked.delete(message.id);\n asked.answer(\"error\" in message ? { error: message.error } : { result: message.result });\n }\n\n #cancel(id: unknown): void {\n if (isId(id)) this.#turns.get(id)?.();\n }\n\n async #command(command: ClientCommand & { id: Id }): Promise<void> {\n if (this.#inFlight >= this.#limit) {\n this.#refuse(command.id);\n return;\n }\n this.#inFlight += 1;\n // The command holds its place until its response has gone out, so a client that doesn't read is refused soon.\n const onSent = () => {\n this.#inFlight -= 1;\n };\n let after: (() => void) | undefined;\n try {\n const outcome = await this.#host.dispatch(this, command);\n after = outcome.after;\n this.#outbox.push({ jsonrpc: \"2.0\", id: command.id, result: outcome.result as never }, { onSent });\n } catch (error) {\n this.#outbox.push({ jsonrpc: \"2.0\", id: command.id, error: rpcErrorOf(error) }, { onSent });\n } finally {\n // A closed outbox drops the response, so it never calls back.\n if (!this.#open) this.#inFlight = 0;\n after?.();\n }\n }\n}\n\n/**\n * What a hold really lost: its dropped events, less the entries the replay carried up to `replayedTo`. The marker's\n * `seq` is never below `replayedTo`, because the client has everything up to there. `undefined` when nothing was lost.\n */\nfunction gapOf(held: Held, replayedTo: number): { count: number; seq: number } | undefined {\n const entries = held.droppedEntries;\n const lostEntries =\n entries === undefined ? 0 : Math.max(0, entries.last - Math.max(entries.first, replayedTo + 1) + 1);\n const count = held.dropped + lostEntries;\n if (count === 0) return undefined;\n return { count, seq: Math.max(held.lastDroppedSeq, entries?.last ?? -1, replayedTo) };\n}\n\n/** The error a failed command answers with. */\nfunction rpcErrorOf(error: unknown): RpcError {\n if (error instanceof Failure) return error.rpc;\n const message = error instanceof Error ? error.message : String(error);\n if (isHarnessError(error) && error.code === \"entry_not_found\") return { code: ErrorCodes.InvalidParams, message };\n if (isHarnessError(error) && error.code === \"session_locked\") return { code: ErrorCodes.SessionLocked, message };\n return { code: ErrorCodes.InternalError, message };\n}\n"]}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The dispatcher: the one place every interface talks to. It takes the protocol's commands, runs turns through
|
|
3
|
+
* `runTurn()`, and sends the replies, the events and one `turn/settled` per turn back through each connection. The
|
|
4
|
+
* dispatcher holds no session state of its own beyond which turn runs where and which questions it has asked: the log
|
|
5
|
+
* is the state, so a client that joins late reads the log and a restart loses nothing. A turn holds the session's
|
|
6
|
+
* writer lock only while it runs, so another process that wants the session gets `locked` from its own `turn/start`.
|
|
7
|
+
*
|
|
8
|
+
* A call that needs a person ends its turn `awaiting_approval`. Once its `approval_requested` entry is durable, every
|
|
9
|
+
* connection that watches the session is asked with `approval/request` or `clarification/request`. The first answer
|
|
10
|
+
* wins: the others are withdrawn with `$/cancelRequest`, and the answer goes through `Approvals.resolve()`, which runs
|
|
11
|
+
* as a turn of its own once the session is free. A client that reconnects finds the request in `initialize` and is
|
|
12
|
+
* asked again when it opens the session.
|
|
13
|
+
*/
|
|
14
|
+
import { type ClientMessage } from "@buildanagent/protocol";
|
|
15
|
+
import type { CompletionSettings } from "../completion/check.js";
|
|
16
|
+
import type { Harness } from "../harness.js";
|
|
17
|
+
import { type Approvals } from "../session/approvals.js";
|
|
18
|
+
import type { SessionLock } from "../session/lock.js";
|
|
19
|
+
import type { SessionIndex } from "../session/pointer.js";
|
|
20
|
+
import { type TurnOptions } from "../session/runner.js";
|
|
21
|
+
import type { SessionStore } from "../session/store.js";
|
|
22
|
+
import type { Deliver } from "./outbox.js";
|
|
23
|
+
/** The methods a client must opt into, by listing each in the `capabilities` of its `initialize`. */
|
|
24
|
+
export declare const EXPERIMENTAL_METHODS: readonly ["session/checkout", "session/fork"];
|
|
25
|
+
/** The settings of `createDispatcher()`. */
|
|
26
|
+
export interface DispatcherOptions<H = unknown> {
|
|
27
|
+
readonly harness: Harness<H>;
|
|
28
|
+
readonly store: SessionStore;
|
|
29
|
+
readonly index: SessionIndex;
|
|
30
|
+
/** The writer lock a turn takes while it runs. Two dispatchers over one lock serve one session at a time. */
|
|
31
|
+
readonly lock: SessionLock;
|
|
32
|
+
/** Whose sessions this dispatcher serves. Every store call names this user. */
|
|
33
|
+
readonly userId: string;
|
|
34
|
+
/** What the harness adds to the SDK's capabilities in `initialize`. Default none. */
|
|
35
|
+
readonly capabilities?: readonly string[];
|
|
36
|
+
/** The name `initialize` reports. Default `buildanagent-harness`. */
|
|
37
|
+
readonly serverName?: string;
|
|
38
|
+
/** Settings every turn takes besides its input, resumes included. */
|
|
39
|
+
readonly turn?: Pick<TurnOptions<H>, "maxSteps" | "turnRetries" | "budgetUsd" | "modelOptions">;
|
|
40
|
+
/**
|
|
41
|
+
* The completion check for a session's turns, given the session's id. It returns the session's sandbox and
|
|
42
|
+
* environment, because one sandbox never serves every session, or `undefined` for a session with no check. Each
|
|
43
|
+
* `turn/start` calls it once. Default: no turn checks its completion.
|
|
44
|
+
*/
|
|
45
|
+
readonly completion?: (session: string) => CompletionSettings | undefined;
|
|
46
|
+
/** Makes session and turn ids. Default `crypto.randomUUID()`. */
|
|
47
|
+
readonly newId?: () => string;
|
|
48
|
+
/**
|
|
49
|
+
* How many commands each connection may have unanswered, and how many events may wait for a slow client before
|
|
50
|
+
* the server drops them. A whole number of at least 1. Default 128.
|
|
51
|
+
*/
|
|
52
|
+
readonly queueSize?: number;
|
|
53
|
+
/** The approvals a client's answers go through. Default `createApprovals(harness)`. */
|
|
54
|
+
readonly approvals?: Approvals<H>;
|
|
55
|
+
}
|
|
56
|
+
/** One client's end of the dispatcher: send it messages, and it calls back with what the server sends. */
|
|
57
|
+
export interface Connection {
|
|
58
|
+
/** Handles one message and resolves once its response, if it has one, is queued to go out. */
|
|
59
|
+
receive(message: ClientMessage): Promise<void>;
|
|
60
|
+
/**
|
|
61
|
+
* Stops delivering to this client. A turn it started goes on, and a tool call that waits on this client gets an
|
|
62
|
+
* error result. A request for a person stays in the log for the next client.
|
|
63
|
+
*/
|
|
64
|
+
close(): void;
|
|
65
|
+
}
|
|
66
|
+
/** What `Dispatcher.connect()` takes besides `send`. */
|
|
67
|
+
export interface ConnectOptions {
|
|
68
|
+
/**
|
|
69
|
+
* Called once when the connection closes, whether the caller closed it with `close()` or the server did. The server
|
|
70
|
+
* closes a connection for a client that leaves 128 refusals unread. A transport uses it to stop serving a connection that is gone.
|
|
71
|
+
*/
|
|
72
|
+
readonly onClose?: () => void;
|
|
73
|
+
}
|
|
74
|
+
/** The dispatcher `createDispatcher()` returns. */
|
|
75
|
+
export interface Dispatcher {
|
|
76
|
+
/**
|
|
77
|
+
* Adds a client. `send` gets every message the server sends it, one at a time and in order. A `send` that returns a
|
|
78
|
+
* promise holds the next message until it settles; while it waits, events past the queue size are dropped and an
|
|
79
|
+
* `events_dropped` event stands in for them.
|
|
80
|
+
*/
|
|
81
|
+
connect(send: Deliver, options?: ConnectOptions): Connection;
|
|
82
|
+
/** Interrupts every running turn and waits for each to settle. */
|
|
83
|
+
close(): Promise<void>;
|
|
84
|
+
}
|
|
85
|
+
/** Creates the dispatcher that serves `options.harness` over the protocol's commands. */
|
|
86
|
+
export declare function createDispatcher<H = unknown>(options: DispatcherOptions<H>): Dispatcher;
|