@buildanagent/harness 0.0.0-stage → 0.1.0-alpha.28
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 +716 -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 +5 -0
- package/dist/context/file-spill.js +25 -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 +6 -0
- package/dist/context/spill.js +14 -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 +34 -0
- package/dist/credentials/allowlist.js +77 -0
- package/dist/credentials/allowlist.js.map +1 -0
- package/dist/credentials/egress-proxy.d.ts +70 -0
- package/dist/credentials/egress-proxy.js +482 -0
- package/dist/credentials/egress-proxy.js.map +1 -0
- package/dist/credentials/index.d.ts +9 -0
- package/dist/credentials/index.js +10 -0
- package/dist/credentials/index.js.map +1 -0
- package/dist/credentials/scrub.d.ts +16 -0
- package/dist/credentials/scrub.js +93 -0
- package/dist/credentials/scrub.js.map +1 -0
- package/dist/errors.d.ts +56 -0
- package/dist/errors.js +63 -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 +35 -0
- package/dist/sandbox/base.js +60 -0
- package/dist/sandbox/base.js.map +1 -0
- package/dist/sandbox/docker/index.d.ts +35 -0
- package/dist/sandbox/docker/index.js +448 -0
- package/dist/sandbox/docker/index.js.map +1 -0
- package/dist/sandbox/errors.d.ts +16 -0
- package/dist/sandbox/errors.js +22 -0
- package/dist/sandbox/errors.js.map +1 -0
- package/dist/sandbox/host-files.d.ts +63 -0
- package/dist/sandbox/host-files.js +248 -0
- package/dist/sandbox/host-files.js.map +1 -0
- package/dist/sandbox/index.d.ts +8 -0
- package/dist/sandbox/index.js +8 -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/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 +35 -0
- package/dist/sandbox/srt/index.js +264 -0
- package/dist/sandbox/srt/index.js.map +1 -0
- package/dist/sandbox/srt/settings.d.ts +48 -0
- package/dist/sandbox/srt/settings.js +31 -0
- package/dist/sandbox/srt/settings.js.map +1 -0
- package/dist/sandbox/types.d.ts +88 -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 +34 -0
- package/dist/testing/fake-sandbox.js +221 -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 +361 -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/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 +8 -0
- package/dist/tools/index.js +8 -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 +435 -0
- package/package.json +118 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"websocket.js","sourceRoot":"","sources":["../../src/server/websocket.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAChF,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAE5C,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AACjE,OAAO,EAAE,OAAO,EAAE,MAAM,oBAA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AAC,CAAC,CAAC,MAAM,GAAG,OAAO,CAAC;gBAC3C,IAAI,GAAG,GAAG,CAAC;gBACX,IAAI,MAAM,IAAI,IAAI,CAAC,OAAO,CAAC,cAAc,EAAE,CAAC;oBAC1C,0CAA0C;oBAC1C,IAAI,CAAC,KAAK,CAAC,6BAA6B,IAAI,CAAC,OAAO,CAAC,cAAc,KAAK,EAAE,gBAAgB,CAAC,CAAC;oBAC5F,OAAO;gBACT,CAAC;gBACD,KAAK,GAAG,UAAU,CAAC,UAAU,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;YAC/C,CAAC,CAAC;YACF,KAAK,GAAG,UAAU,CAAC,UAAU,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QAC/C,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["/**\n * The WebSocket transport: one client on one socket, one JSON-RPC message per text frame. It takes the socket by the\n * standard `WebSocket` interface that Node and browsers share, so it needs no library and imports no Node module. Each\n * frame goes through the protocol's `JsonlFramer` as one line, so the rules for `\\r` and U+2028 are the stdio\n * transport's, and then through the same `RpcSession` that stdio uses, so a bad message gets the same answer. A text\n * frame arrives as a JavaScript string, never as bytes, so the framer's UTF-8 check can't fail; the transport refuses\n * a string with a lone surrogate itself, because UTF-8 can't carry one.\n *\n * A socket reports no event when its send buffer empties, so the transport polls `bufferedAmount` while the buffer is\n * over its bound. One poll timer runs at a time, shared by every message that waits, and it is cleared once there is\n * room or the transport stops.\n */\nimport { ErrorCodes, JsonlFramer, ProtocolError } from \"@buildanagent/protocol\";\nimport { HarnessError } from \"../errors.js\";\nimport type { Dispatcher } from \"./dispatcher.js\";\nimport { checkWriteTimeout, RpcSession } from \"./rpc-session.js\";\nimport { Stopper } from \"./stdio-streams.js\";\n\n/** A message event as the transport reads it: `data` is a string for a text frame and anything else for binary. */\nexport interface WebSocketMessageEvent {\n readonly data: unknown;\n}\n\n/** A close event as the transport reads it. Its `reason` is the peer's text, so the transport never logs it. */\nexport interface WebSocketCloseEvent {\n readonly code: number;\n}\n\n/**\n * A WebSocket as the transport uses it: the methods of the standard `WebSocket` interface, which the global `WebSocket`\n * of Node and browsers fits. A server-side socket must already be accepted and open when the transport takes it.\n */\nexport interface WebSocketLike {\n /** 1 while the socket is open; 2 and 3 once it is closing or closed. */\n readonly readyState: number;\n /**\n * The bytes sent but not yet handed to the network, which the transport's backpressure reads. A socket without it is\n * taken never to be full, so the transport writes to it without waiting.\n */\n readonly bufferedAmount?: number;\n /** Sends one text frame. */\n send(data: string): void;\n /**\n * Closes the socket with a status code and a short reason. It may throw for a code it refuses, as the standard\n * `WebSocket` does for any code but 1000 and 3000 to 4999.\n */\n close(code?: number, reason?: string): void;\n /** Adds the listener the transport reads frames with. */\n addEventListener(type: \"message\", listener: (event: WebSocketMessageEvent) => void): void;\n /** Adds the listener that tells the transport the peer closed the socket. */\n addEventListener(type: \"close\", listener: (event: WebSocketCloseEvent) => void): void;\n /** Adds the listener that tells the transport the socket failed. */\n addEventListener(type: \"error\", listener: (event: unknown) => void): void;\n /** Removes the frame listener when the transport stops. */\n removeEventListener(type: \"message\", listener: (event: WebSocketMessageEvent) => void): void;\n /** Removes the close listener when the transport stops. */\n removeEventListener(type: \"close\", listener: (event: WebSocketCloseEvent) => void): void;\n /** Removes the failure listener when the transport stops. */\n removeEventListener(type: \"error\", listener: (event: unknown) => void): void;\n}\n\n/** What `webSocketTransport()` takes besides the dispatcher and the socket. */\nexport interface WebSocketOptions {\n /**\n * The most bytes one frame may hold: a text frame counted as UTF-8 without one trailing `\\n` and then one trailing\n * `\\r`, as the stdio transport counts a line, and a binary frame by its byte length, which the transport reads\n * without reading the data. A longer frame is answered with `InvalidRequest`, and the transport then closes the\n * socket with code 1009, or 4009 on a socket that refuses 1009. Default 8 MiB, the stdio transport's bound on a line.\n */\n readonly maxMessageBytes?: number;\n /**\n * How many bytes may wait in the socket's send buffer before the transport waits for it to drain. While it waits,\n * the connection's queue holds the next message and drops live events past its size. Default 1 MiB.\n */\n readonly maxBufferedBytes?: number;\n /**\n * How long, in milliseconds, the send buffer may stay over `maxBufferedBytes` without shrinking. The clock restarts\n * each time the buffer shrinks, so a peer that reads slowly is never cut off; one that reads nothing for this long\n * stops the transport, which logs why and closes the socket with code 1008, or 4008 on a socket that refuses 1008.\n * The buffer is checked every 25 ms, so the stop comes up to 25 ms late. A whole number from 1 to 2,147,483,647, or\n * `Infinity` to wait forever. Default 30,000.\n */\n readonly writeTimeoutMs?: number;\n /** Stops the transport now: the connection closes, and the socket is closed with code 1000. */\n readonly signal?: AbortSignal;\n /**\n * Takes one line of the transport's own diagnostics, such as a frame it answered with an error or why it stopped. A\n * line never holds what the client sent. Default: diagnostics are dropped.\n */\n readonly log?: (line: string) => void;\n}\n\nconst OPEN = 1;\nconst DEFAULT_MAX_MESSAGE_BYTES = 8 * 1024 * 1024;\nconst DEFAULT_MAX_BUFFERED_BYTES = 1024 * 1024;\n/** How often a full send buffer is checked for room. */\nconst POLL_MS = 25;\n/** WebSocket close codes (RFC 6455 §7.4.1). */\nconst NORMAL = 1000;\nconst POLICY_VIOLATION = 1008;\nconst MESSAGE_TOO_BIG = 1009;\nconst INTERNAL_ERROR = 1011;\n/** Where the codes applications may use start (RFC 6455 §7.4.2): 1008 falls back to 4008. */\nconst APPLICATION_CODES = 4000;\n/** A close frame's reason holds at most 123 bytes of UTF-8 (RFC 6455 §5.5.1). */\nconst MAX_CLOSE_REASON_BYTES = 123;\n\nconst encoder = new TextEncoder();\nconst NEWLINE = encoder.encode(\"\\n\");\n\n/** `reason` cut to the bytes a close frame holds, on a whole character: `encodeInto()` writes only whole ones. */\nfunction closeReason(reason: string): string {\n const { read } = encoder.encodeInto(reason, new Uint8Array(MAX_CLOSE_REASON_BYTES));\n return reason.slice(0, read);\n}\n\nfunction checkBytes(name: string, value: number | undefined, fallback: number): number {\n if (value === undefined) return fallback;\n if (Number.isSafeInteger(value) && value > 0) return value;\n throw new HarnessError(\"invalid_transport_options\", `${name} must be a whole number of at least 1, got ${value}`);\n}\n\n/** A refusal the transport makes of a frame itself, before any JSON is read. */\nconst refusal = (message: string) =>\n new ProtocolError(\"invalid_request\", message, { rpcCode: ErrorCodes.InvalidRequest, requestId: null });\n\n/** A frame text with a lone surrogate, which has no UTF-8 form; `\\p{Surrogate}` with `u` matches no paired one. */\nconst LONE_SURROGATE = /\\p{Surrogate}/u;\n\n/** The refusal of a frame UTF-8 can't carry, as the framer refuses a line that isn't UTF-8. */\nconst notUtf8 = () =>\n new ProtocolError(\"invalid_json\", \"a frame is not valid UTF-8 JSON\", {\n rpcCode: ErrorCodes.ParseError,\n requestId: null,\n });\n\n/**\n * A binary frame's size in bytes, read from its `byteLength` (an `ArrayBuffer`, a typed array or a `Buffer`) or its\n * `size` (a `Blob`) without reading its data, or `undefined` when it has neither.\n */\nfunction binarySize(data: unknown): number | undefined {\n if (typeof data !== \"object\" || data === null) return undefined;\n const size = \"byteLength\" in data ? data.byteLength : \"size\" in data ? data.size : undefined;\n return typeof size === \"number\" ? size : undefined;\n}\n\n/**\n * `text` without one trailing `\\n` and then one trailing `\\r`, which the framer drops from a stdio line before it\n * counts the line, so a frame ending in `\\r\\n`, `\\n` or a lone `\\r` is bounded as that line is.\n */\nfunction withoutNewline(text: string): string {\n const line = text.endsWith(\"\\n\") ? text.slice(0, -1) : text;\n return line.endsWith(\"\\r\") ? line.slice(0, -1) : line;\n}\n\n/**\n * Serves one client over one open WebSocket, one JSON-RPC 2.0 message per text frame, and resolves once the client is\n * gone or the transport stops. The host accepts the socket, and whatever authenticates the peer happens there: the\n * transport authenticates nobody, so whoever holds the socket acts as the dispatcher's user.\n *\n * Each frame must hold exactly one message, one line of JSON; a trailing newline is allowed and not needed. A frame\n * that isn't JSON, or holds a lone surrogate, is answered with `ParseError`. A binary frame, a frame with more than one\n * line or none, a batch, and a message without a valid envelope are answered with `InvalidRequest`. The transport\n * never decodes a binary frame, so a binary, empty, multi-message or batch frame, and one that isn't JSON, is answered\n * with a `null` id; a message whose envelope is bad but holds a valid id is answered with that id. A malformed\n * response is only logged, because JSON-RPC never answers a response. None of these ends the transport, except a\n * frame over `maxMessageBytes`, text or binary, after which the socket is closed with code 1009. The transport also\n * stops once 128 of its error answers wait on a full send buffer. Each message the server sends is one text frame\n * with no trailing newline.\n *\n * What the server sends waits while the socket's `bufferedAmount` is over `maxBufferedBytes`, so a client that stops\n * reading holds the connection's queue, which drops live events past its size instead of buffering them. A buffer\n * that does not shrink for `writeTimeoutMs` stops the transport.\n *\n * The transport serves one socket. A client that reconnects comes back on a new socket, which the host serves with a\n * new call, and sends `session/open` with `fromSeq` to get the entries it missed; the dispatcher keeps the session,\n * its running turn and its pending requests meanwhile.\n *\n * The peer's close, or a socket error, stops the transport, and it logs the close code but never the peer's reason.\n * It closes the socket only when it stops itself: with 1008 when the client breaks a bound (128 error answers or\n * refusals unread, or a send buffer that never drains), 1009 for a frame that is too big, 1011 when the socket's\n * `send()` throws or the socket is still open after an error, and 1000 when `signal` aborts. The standard `WebSocket`\n * lets a client close only with 1000 or 3000 to 4999, so the global `WebSocket` of Node and browsers throws for 1008,\n * 1009 and 1011; a socket that throws for one of them is closed with 4008, 4009 or 4011 instead, with the same reason.\n * A socket that throws for that code too is left as it is, and the transport logs the error's name, never its message,\n * and still resolves. However it stops, it removes its listeners and closes the connection. A turn the client started\n * goes on in the dispatcher. An option out of range, or a socket that is not open, rejects with a `HarnessError`, code\n * `invalid_transport_options`, before the transport connects.\n */\nexport async function webSocketTransport(\n dispatcher: Dispatcher,\n socket: WebSocketLike,\n options: WebSocketOptions = {},\n): Promise<void> {\n const limits: Limits = {\n maxMessageBytes: checkBytes(\"maxMessageBytes\", options.maxMessageBytes, DEFAULT_MAX_MESSAGE_BYTES),\n maxBufferedBytes: checkBytes(\"maxBufferedBytes\", options.maxBufferedBytes, DEFAULT_MAX_BUFFERED_BYTES),\n writeTimeoutMs: checkWriteTimeout(options.writeTimeoutMs),\n };\n if (socket.readyState !== OPEN) {\n throw new HarnessError(\"invalid_transport_options\", \"the socket must be open when the transport takes it\");\n }\n await new WebSocketSession(dispatcher, socket, options.log ?? (() => undefined), limits).run(options.signal);\n}\n\ninterface Limits {\n readonly maxMessageBytes: number;\n readonly maxBufferedBytes: number;\n readonly writeTimeoutMs: number;\n}\n\n/** One socket's run of the transport, and the close code it owes the socket if it stops itself. */\nclass WebSocketSession {\n readonly #socket: WebSocketLike;\n readonly #log: (line: string) => void;\n readonly #limits: Limits;\n readonly #stopper = new Stopper();\n readonly #framer: JsonlFramer;\n readonly #rpc: RpcSession;\n /** The code to close the socket with once the run ends, or `undefined` when the peer already closed it. */\n #closeCode: number | undefined = POLICY_VIOLATION;\n /** The one wait for room while the send buffer is full, shared by every message sent meanwhile. */\n #full: Promise<void> | undefined;\n\n constructor(dispatcher: Dispatcher, socket: WebSocketLike, log: (line: string) => void, limits: Limits) {\n this.#socket = socket;\n this.#log = log;\n this.#limits = limits;\n // The frame is checked against the bound before it is framed, so the framer's own bound never cuts it.\n this.#framer = new JsonlFramer({ maxLineBytes: limits.maxMessageBytes });\n this.#rpc = new RpcSession(dispatcher, {\n label: \"websocket\",\n log,\n write: (line) => this.#send(line),\n // The client broke a bound, or the dispatcher closed the connection for refusals it left unread.\n stop: (why) => this.#stop(why, POLICY_VIOLATION),\n });\n }\n\n async run(signal: AbortSignal | undefined): Promise<void> {\n const stopped = new Promise<void>((resolve) => this.#stopper.onStop(resolve));\n const onMessage = (event: WebSocketMessageEvent) => this.#receive(event.data);\n const onClose = (event: WebSocketCloseEvent) => {\n const code = Number.isInteger(event.code) ? ` with code ${event.code}` : \"\";\n this.#stop(`the peer closed the socket${code}`, undefined);\n };\n // A standard socket closes after an error, and #closeSocket skips one that is no longer open; an adapter whose\n // socket stays open after an error is closed as a server failure.\n const onError = () => this.#stop(\"the socket failed\", INTERNAL_ERROR);\n const onAbort = () => this.#stop(\"the signal aborted\", NORMAL);\n this.#socket.addEventListener(\"message\", onMessage);\n this.#socket.addEventListener(\"close\", onClose);\n this.#socket.addEventListener(\"error\", onError);\n if (signal?.aborted) onAbort();\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n try {\n await stopped;\n } finally {\n signal?.removeEventListener(\"abort\", onAbort);\n this.#socket.removeEventListener(\"message\", onMessage);\n this.#socket.removeEventListener(\"close\", onClose);\n this.#socket.removeEventListener(\"error\", onError);\n this.#rpc.close();\n }\n const reason = this.#stopper.reason ?? \"the transport finished\";\n this.#closeSocket(reason);\n this.#log(`websocket: stopped: ${reason}`);\n }\n\n /** Stops the run once, remembering the close code the socket is owed: `undefined` when the peer already closed it. */\n #stop(why: string, closeCode: number | undefined): void {\n if (this.#stopper.stopped) return;\n this.#closeCode = closeCode;\n this.#stopper.stop(why);\n }\n\n /**\n * Closes the socket with the code it is owed. The standard `WebSocket` lets a client close only with 1000 or 3000 to\n * 4999 and throws for any other code, so a socket that refuses 1008, 1009 or 1011 is closed with 4008, 4009 or 4011,\n * the same code in the range applications may use.\n */\n #closeSocket(reason: string): void {\n const code = this.#closeCode;\n if (code === undefined || this.#socket.readyState !== OPEN) return;\n const text = closeReason(reason);\n let failure = this.#tryClose(code, text);\n if (failure !== undefined && code !== NORMAL) failure = this.#tryClose(APPLICATION_CODES + (code - NORMAL), text);\n if (failure === undefined) return;\n const name = failure instanceof Error ? failure.name : \"unknown error\";\n this.#log(`websocket: the socket could not be closed: ${name}`);\n }\n\n /** Calls `close()`, and returns what it threw, or `undefined` once it closed. */\n #tryClose(code: number, reason: string): unknown {\n try {\n this.#socket.close(code, reason);\n return undefined;\n } catch (error) {\n return error ?? new Error(\"close() threw\");\n }\n }\n\n /** Reads one frame: refuses what is not one text message, and hands the message to the session. */\n #receive(data: unknown): void {\n if (this.#stopper.stopped) return;\n if (typeof data !== \"string\") {\n this.#refuseBinary(data);\n return;\n }\n const text = withoutNewline(data);\n if (this.#tooBig(text)) {\n this.#refuseTooBig();\n return;\n }\n // `TextEncoder` would write a lone surrogate as U+FFFD, so the frame is refused as stdio refuses bad UTF-8.\n if (LONE_SURROGATE.test(text)) {\n this.#rpc.refuse(notUtf8(), ErrorCodes.ParseError, \"a frame\");\n return;\n }\n // The framer skips blank lines, so a newline left after the trailing one is refused here, before framing.\n if (text.includes(\"\\n\")) {\n this.#rpc.refuse(refusal(\"a frame must hold one message, on one line\"), ErrorCodes.InvalidRequest, \"a frame\");\n return;\n }\n const framed = this.#framer.push(encoder.encode(text));\n framed.push(...this.#framer.push(NEWLINE));\n // With no newline inside, the frame is one line: blank, which the framer skips, or one message.\n const [only] = framed;\n if (only === undefined) {\n this.#rpc.refuse(refusal(\"a frame must hold a message\"), ErrorCodes.InvalidRequest, \"a frame\");\n return;\n }\n if (only.ok) this.#rpc.handle(only.value);\n else this.#rpc.refuse(only.error, ErrorCodes.ParseError, \"a frame\");\n }\n\n /** Refuses a binary frame, without reading its data: a frame over the bound also stops the transport. */\n #refuseBinary(data: unknown): void {\n const size = binarySize(data);\n if (size !== undefined && size > this.#limits.maxMessageBytes) this.#refuseTooBig();\n else this.#rpc.refuse(refusal(\"a frame must be text, not binary\"), ErrorCodes.InvalidRequest, \"a frame\");\n }\n\n /** Answers a frame over the bound, then stops the transport, which closes the socket with 1009. */\n #refuseTooBig(): void {\n const why = `a frame went over the bound of ${this.#limits.maxMessageBytes} bytes`;\n this.#rpc.refuse(refusal(why), ErrorCodes.InvalidRequest, \"a frame\");\n this.#stop(why, MESSAGE_TOO_BIG);\n }\n\n /** Whether `text` holds more UTF-8 bytes than the bound, encoding it only when its length can't tell. */\n #tooBig(text: string): boolean {\n const bound = this.#limits.maxMessageBytes;\n // A UTF-16 code unit takes one to three bytes, and a pair of them four.\n if (text.length > bound) return true;\n if (text.length * 3 <= bound) return false;\n return encoder.encode(text).length > bound;\n }\n\n /** Sends one line as a frame and, when the send buffer is over its bound, returns the wait for room. */\n #send(line: string): PromiseLike<void> | undefined {\n if (this.#stopper.stopped) return undefined;\n try {\n // `encode()` ends the line with `\\n`; a frame is already one message, so it goes without.\n this.#socket.send(line.slice(0, -1));\n } catch (error) {\n // The socket may still be open, so it is closed as a server failure; the error's message is not logged.\n this.#stop(\n `the socket refused a frame: ${error instanceof Error ? error.name : \"unknown error\"}`,\n INTERNAL_ERROR,\n );\n return undefined;\n }\n if (this.#buffered() <= this.#limits.maxBufferedBytes) return undefined;\n this.#full ??= this.#room();\n return this.#full;\n }\n\n #buffered(): number {\n const amount = this.#socket.bufferedAmount;\n return typeof amount === \"number\" && Number.isFinite(amount) ? amount : 0;\n }\n\n /**\n * Resolves once the send buffer is back within its bound, or the transport stops. It checks every 25 ms with one\n * timer at a time, and stops the transport once the buffer has not shrunk for `writeTimeoutMs`. The timer is cleared\n * however the wait ends.\n */\n #room(): Promise<void> {\n return new Promise<void>((resolve) => {\n let timer: ReturnType<typeof globalThis.setTimeout> | undefined;\n let last = this.#buffered();\n let idleMs = 0;\n const done = () => {\n globalThis.clearTimeout(timer);\n off();\n this.#full = undefined;\n resolve();\n };\n const off = this.#stopper.onStop(done);\n const poll = () => {\n const now = this.#buffered();\n if (now <= this.#limits.maxBufferedBytes) {\n done();\n return;\n }\n idleMs = now < last ? 0 : idleMs + POLL_MS;\n last = now;\n if (idleMs >= this.#limits.writeTimeoutMs) {\n // Stopping ends this wait through `done`.\n this.#stop(`the peer read nothing for ${this.#limits.writeTimeoutMs} ms`, POLICY_VIOLATION);\n return;\n }\n timer = globalThis.setTimeout(poll, POLL_MS);\n };\n timer = globalThis.setTimeout(poll, POLL_MS);\n });\n }\n}\n"]}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type { Resolution, SignedPendingRequest } from "@buildanagent/sdk";
|
|
2
|
+
import type { CodeCallResult, Harness } from "../harness.js";
|
|
3
|
+
import { type PendingApproval } from "./rebuild.js";
|
|
4
|
+
import { type ResumeOptions, type TurnResult } from "./runner.js";
|
|
5
|
+
import type { Session } from "./session.js";
|
|
6
|
+
/** What a quorum policy says about one request: its answers are enough, not yet, a refusal, or too old. */
|
|
7
|
+
export type QuorumVerdict = "met" | "pending" | "rejected" | "expired";
|
|
8
|
+
/**
|
|
9
|
+
* Decides when a request has enough answers. `resolutions` are every answer written for the request so far, oldest
|
|
10
|
+
* first. The policy keeps its own clock, so it can expire a request by age or because the policy changed. `met` runs
|
|
11
|
+
* the call, `rejected` and `expired` turn it into a denial, and `pending` leaves it waiting.
|
|
12
|
+
*/
|
|
13
|
+
export interface QuorumPolicy {
|
|
14
|
+
/** Decides one waiting request from every answer recorded for it so far, oldest first. */
|
|
15
|
+
evaluate(request: SignedPendingRequest, resolutions: readonly Resolution[]): Promise<QuorumVerdict> | QuorumVerdict;
|
|
16
|
+
}
|
|
17
|
+
/** The default policy: the latest answer decides. Any answer that is not a deny runs the call, and a deny refuses it. */
|
|
18
|
+
export declare const oneResolution: QuorumPolicy;
|
|
19
|
+
/**
|
|
20
|
+
* A policy that needs `needed` allows from distinct approvers, named by `Resolution.by`. A deny as the latest answer
|
|
21
|
+
* refuses the call, and the allows before it do not count. An allow with no `by` counts as one anonymous approver, so a
|
|
22
|
+
* quorum above one needs the host to name them. Throws `invalid_permission_config` unless `needed` is a whole number
|
|
23
|
+
* of at least one.
|
|
24
|
+
*/
|
|
25
|
+
export declare function quorumOf(needed: number): QuorumPolicy;
|
|
26
|
+
/**
|
|
27
|
+
* The settings a resume takes besides the answers: a turn's settings, and what the answers cover. A code call's
|
|
28
|
+
* resolution reads `hostContext`, `signal`, `clock`, `newId`, `sticky`, `group` and `requesterId`, and ignores the
|
|
29
|
+
* rest: it makes no model call, so `budgetUsd` and the model settings have nothing to apply to.
|
|
30
|
+
*/
|
|
31
|
+
export interface ResolveOptions<H = unknown> extends Omit<ResumeOptions<H>, "resolutions" | "records"> {
|
|
32
|
+
/** Make each `allow` cover the same call again, for this run or for this session. */
|
|
33
|
+
readonly sticky?: "run" | "session";
|
|
34
|
+
/** For a shell tool, cover every command that starts with these words, not only the one approved. */
|
|
35
|
+
readonly commandPrefix?: readonly string[];
|
|
36
|
+
/** Apply each answer to every pending request of the step that has the same tool and the same input. */
|
|
37
|
+
readonly group?: boolean;
|
|
38
|
+
/** Who asked. An approver equal to it is refused: nobody approves their own request. */
|
|
39
|
+
readonly requesterId?: string;
|
|
40
|
+
}
|
|
41
|
+
/** The options of `createApprovals()`. */
|
|
42
|
+
export interface ApprovalsOptions {
|
|
43
|
+
/** When a request has enough answers. Default `oneResolution`. */
|
|
44
|
+
readonly quorum?: QuorumPolicy;
|
|
45
|
+
/** The secret values the host's credential store knows. A sticky allowance that covers one is refused. */
|
|
46
|
+
readonly secrets?: () => readonly string[] | Promise<readonly string[]>;
|
|
47
|
+
}
|
|
48
|
+
/** The approvals of one harness. */
|
|
49
|
+
export interface Approvals<H = unknown> {
|
|
50
|
+
/**
|
|
51
|
+
* The requests of the session that still wait, each with the input its call would run with once approved: a paused
|
|
52
|
+
* turn's, then the code calls', in the order they asked.
|
|
53
|
+
*/
|
|
54
|
+
pending(session: Session): Promise<PendingApproval[]>;
|
|
55
|
+
/**
|
|
56
|
+
* Answers waiting requests and resumes the turn. Each answer is written as an `approval_resolved` entry first. The
|
|
57
|
+
* quorum policy then decides each request: `met` goes to the SDK, which verifies the request's signature, call and
|
|
58
|
+
* input, so a tampered request runs nothing and is asked again; `rejected` and `expired` become denials; `pending`
|
|
59
|
+
* leaves the call waiting, and the turn ends `awaiting_approval` again. Each approved call goes through the permission
|
|
60
|
+
* pipeline again, and a deny now turns the approval into a denial. Calling it with no answers evaluates the policy
|
|
61
|
+
* for every request of a paused turn, which is how such a request expires. It leaves a code call's request waiting:
|
|
62
|
+
* the policy decides that call when it is next answered, so a late allow for an expired call comes back `denied`.
|
|
63
|
+
*
|
|
64
|
+
* An answer to a code call's request resolves that call alone and returns a `CodeCallResult`. The request is checked
|
|
65
|
+
* against its signature, the host context it binds and the call's recorded input before anything is written, and a
|
|
66
|
+
* request that fails throws `approval_refused` and runs nothing. The answer is then written and the quorum policy
|
|
67
|
+
* decides. `met` decides the call again with the pipeline, so a deny written since the pause wins, and then runs the
|
|
68
|
+
* tool with `options.hostContext` and `options.signal`, with no model call; `rejected` and `expired` deny it; `pending`
|
|
69
|
+
* returns `awaiting_approval`. A request whose call already has a result, or started before a crash, no longer waits,
|
|
70
|
+
* so its tool runs at most once.
|
|
71
|
+
*
|
|
72
|
+
* Throws `approval_not_pending` for a request that does not wait, `approval_unavailable` without a signer,
|
|
73
|
+
* `approver_is_requester` when an approver is the requester, `approval_reuse_refused` when a tool's `approvalReuse`
|
|
74
|
+
* forbids a sticky or grouped answer, `sticky_refused` for an interpreter prefix or a secret, and `invalid_code_call`
|
|
75
|
+
* for answers that name a code call together with any other request. The host fills `Resolution.by` only after it
|
|
76
|
+
* has authenticated the approver; the harness trusts what it is given.
|
|
77
|
+
*/
|
|
78
|
+
resolve(session: Session, resolutions: readonly Resolution[], options?: ResolveOptions<H>): Promise<TurnResult | CodeCallResult>;
|
|
79
|
+
}
|
|
80
|
+
/** Creates the approvals of `harness`, which needs a `signer` to check the requests it resumes. */
|
|
81
|
+
export declare function createApprovals<H = unknown>(harness: Harness<H>, settings?: ApprovalsOptions): Approvals<H>;
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import { HarnessError } from "../errors.js";
|
|
2
|
+
import { checkCodeCallRequest, codeCallEffectKey, finishCodeCall, inCodeCallQueue } from "./code-call.js";
|
|
3
|
+
import { codeCallRequestIds, pendingCodeCalls } from "./code-call-log.js";
|
|
4
|
+
import { pendingApprovals } from "./rebuild.js";
|
|
5
|
+
import { resumeTurn } from "./runner.js";
|
|
6
|
+
import { checkReuse, checkSticky, groupIdOf } from "./sticky.js";
|
|
7
|
+
const isDeny = (resolution) => "decision" in resolution && resolution.decision === "deny";
|
|
8
|
+
/** The default policy: the latest answer decides. Any answer that is not a deny runs the call, and a deny refuses it. */
|
|
9
|
+
export const oneResolution = {
|
|
10
|
+
evaluate(_request, resolutions) {
|
|
11
|
+
const latest = resolutions.at(-1);
|
|
12
|
+
if (latest === undefined)
|
|
13
|
+
return "pending";
|
|
14
|
+
return isDeny(latest) ? "rejected" : "met";
|
|
15
|
+
},
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* A policy that needs `needed` allows from distinct approvers, named by `Resolution.by`. A deny as the latest answer
|
|
19
|
+
* refuses the call, and the allows before it do not count. An allow with no `by` counts as one anonymous approver, so a
|
|
20
|
+
* quorum above one needs the host to name them. Throws `invalid_permission_config` unless `needed` is a whole number
|
|
21
|
+
* of at least one.
|
|
22
|
+
*/
|
|
23
|
+
export function quorumOf(needed) {
|
|
24
|
+
if (!Number.isInteger(needed) || needed < 1) {
|
|
25
|
+
throw new HarnessError("invalid_permission_config", `a quorum needs a whole number of approvers of at least 1, got ${needed}`);
|
|
26
|
+
}
|
|
27
|
+
return {
|
|
28
|
+
evaluate(_request, resolutions) {
|
|
29
|
+
if (resolutions.length === 0)
|
|
30
|
+
return "pending";
|
|
31
|
+
if (isDeny(resolutions.at(-1)))
|
|
32
|
+
return "rejected";
|
|
33
|
+
const approvers = new Set(resolutions.filter((resolution) => !isDeny(resolution)).map((resolution) => resolution.by ?? "(unnamed)"));
|
|
34
|
+
return approvers.size >= needed ? "met" : "pending";
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
const decisionOf = (resolution) => "decision" in resolution ? resolution.decision : undefined;
|
|
39
|
+
/** Copies an answer to the other requests of its group, each with the same decision, reason and approver. */
|
|
40
|
+
function expandGroup(resolutions, groups, groupOf) {
|
|
41
|
+
const out = new Map(resolutions.map((resolution) => [resolution.requestId, resolution]));
|
|
42
|
+
for (const resolution of resolutions) {
|
|
43
|
+
for (const other of groups.get(groupOf.get(resolution.requestId) ?? "") ?? []) {
|
|
44
|
+
if (!out.has(other))
|
|
45
|
+
out.set(other, { ...resolution, requestId: other });
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return [...out.values()];
|
|
49
|
+
}
|
|
50
|
+
/** The answers already written for each request, oldest first. */
|
|
51
|
+
function answersByRequest(path) {
|
|
52
|
+
const answers = new Map();
|
|
53
|
+
for (const entry of path) {
|
|
54
|
+
if (entry.type === "approval_resolved") {
|
|
55
|
+
answers.set(entry.resolution.requestId, [...(answers.get(entry.resolution.requestId) ?? []), entry.resolution]);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return answers;
|
|
59
|
+
}
|
|
60
|
+
/** Refuses an answer set that can't be applied: no signer, an answer twice, a request that doesn't wait, a self-approval. */
|
|
61
|
+
function checkAnswers(harness, waiting, resolutions, requesterId) {
|
|
62
|
+
if (harness.signer === undefined) {
|
|
63
|
+
throw new HarnessError("approval_unavailable", "the harness has no signer, so no approval can be checked");
|
|
64
|
+
}
|
|
65
|
+
const named = new Set();
|
|
66
|
+
for (const resolution of resolutions) {
|
|
67
|
+
if (named.has(resolution.requestId)) {
|
|
68
|
+
throw new HarnessError("approval_not_pending", `request ${resolution.requestId} is answered twice in one resume`);
|
|
69
|
+
}
|
|
70
|
+
named.add(resolution.requestId);
|
|
71
|
+
if (!waiting.has(resolution.requestId)) {
|
|
72
|
+
throw new HarnessError("approval_not_pending", `no request ${resolution.requestId} is waiting in this session`);
|
|
73
|
+
}
|
|
74
|
+
if (requesterId !== undefined && resolution.by === requesterId) {
|
|
75
|
+
throw new HarnessError("approver_is_requester", `the approver ${resolution.by} is the one who asked`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/** The synthetic denial for a request the policy refused or let expire, with the record that puts it in the log. */
|
|
80
|
+
function denial(requestId, verdict) {
|
|
81
|
+
const reason = verdict === "expired" ? "the approval expired" : "the approval was rejected";
|
|
82
|
+
return { resolution: { requestId, decision: "deny", reason, by: "policy" } };
|
|
83
|
+
}
|
|
84
|
+
/** An answer without what it would cover: a sticky allowance only takes effect once the quorum is met and the call runs. */
|
|
85
|
+
const plain = ({ resolution, groupId }) => ({
|
|
86
|
+
resolution,
|
|
87
|
+
...(groupId === undefined ? {} : { groupId }),
|
|
88
|
+
});
|
|
89
|
+
/** What the SDK is given for one request, and the entries to write for it, once the quorum policy has decided. */
|
|
90
|
+
function outcomeOf(verdict, requestId, answers, fresh) {
|
|
91
|
+
const latest = answers.at(-1);
|
|
92
|
+
if (verdict === "met" && latest !== undefined) {
|
|
93
|
+
const given = answers.findLast((answer) => !isDeny(answer)) ?? latest;
|
|
94
|
+
// A verdict that flips with no new answer (a clock, a policy) still writes the answer the run is given, unmarked.
|
|
95
|
+
return { forRun: given, records: fresh.length > 0 ? [...fresh] : [{ resolution: given }] };
|
|
96
|
+
}
|
|
97
|
+
if (verdict === "rejected" || verdict === "expired") {
|
|
98
|
+
// A person's own deny is already in the log; a refusal or an expiry by the policy gets an entry of its own.
|
|
99
|
+
if (verdict === "rejected" && latest !== undefined && isDeny(latest))
|
|
100
|
+
return { forRun: latest, records: fresh.map(plain) };
|
|
101
|
+
const refusal = denial(requestId, verdict);
|
|
102
|
+
return { forRun: refusal.resolution, records: [...fresh.map(plain), refusal] };
|
|
103
|
+
}
|
|
104
|
+
return { records: fresh.map((record) => ({ ...plain(record), quorum: "pending" })) };
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* What each waiting request gets once the quorum policy has looked at it: the answer the SDK applies for `met`, a denial
|
|
108
|
+
* for `rejected` and `expired`, and nothing for `pending`, whose new answers are marked as waited on so a crash
|
|
109
|
+
* of this resume never counts them as given. The records returned are the entries to write, denials by the policy
|
|
110
|
+
* included, so the log tells an expiry from any other refusal.
|
|
111
|
+
*/
|
|
112
|
+
async function settled(policy, waiting, earlier, records) {
|
|
113
|
+
const forRun = [];
|
|
114
|
+
const out = [];
|
|
115
|
+
for (const { request } of waiting) {
|
|
116
|
+
const fresh = records.filter((record) => record.resolution.requestId === request.id);
|
|
117
|
+
const answers = [...(earlier.get(request.id) ?? []), ...fresh.map((record) => record.resolution)];
|
|
118
|
+
const outcome = outcomeOf(await policy.evaluate(request, answers), request.id, answers, fresh);
|
|
119
|
+
if (outcome.forRun !== undefined)
|
|
120
|
+
forRun.push(outcome.forRun);
|
|
121
|
+
out.push(...outcome.records);
|
|
122
|
+
}
|
|
123
|
+
return { forRun, records: out };
|
|
124
|
+
}
|
|
125
|
+
/** Creates the approvals of `harness`, which needs a `signer` to check the requests it resumes. */
|
|
126
|
+
export function createApprovals(harness, settings = {}) {
|
|
127
|
+
const policy = settings.quorum ?? oneResolution;
|
|
128
|
+
return {
|
|
129
|
+
async pending(session) {
|
|
130
|
+
const path = await session.path();
|
|
131
|
+
return [...pendingApprovals(path), ...pendingCodeCalls(path).map(({ request, input }) => ({ request, input }))];
|
|
132
|
+
},
|
|
133
|
+
async resolve(session, resolutions, options = {}) {
|
|
134
|
+
if (options.sticky !== undefined && settings.quorum !== undefined) {
|
|
135
|
+
throw new HarnessError("sticky_refused", "a sticky allowance needs the default policy: one approver's click would otherwise skip the quorum on every later call");
|
|
136
|
+
}
|
|
137
|
+
const path = await session.path();
|
|
138
|
+
const codeRequests = codeCallRequestIds(path);
|
|
139
|
+
if (resolutions.some((resolution) => codeRequests.has(resolution.requestId))) {
|
|
140
|
+
if (resolutions.length !== 1) {
|
|
141
|
+
throw new HarnessError("invalid_code_call", "a code call's request is answered on its own, in a resolve() that answers nothing else");
|
|
142
|
+
}
|
|
143
|
+
const only = resolutions[0];
|
|
144
|
+
return inCodeCallQueue(session, () => resolveCodeCall(harness, session, policy, settings, only, options));
|
|
145
|
+
}
|
|
146
|
+
const waiting = pendingApprovals(path);
|
|
147
|
+
checkAnswers(harness, new Map(waiting.map((entry) => [entry.request.id, entry])), resolutions, options.requesterId);
|
|
148
|
+
const records = await recordsFor(harness, waiting, resolutions, options, await (settings.secrets?.() ?? []));
|
|
149
|
+
const { forRun, records: toWrite } = await settled(policy, waiting, answersByRequest(path), records);
|
|
150
|
+
return resumeTurn(session, harness, { ...options, resolutions: forRun, records: toWrite });
|
|
151
|
+
},
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
const nameOf = (harness, tool) => harness.registry.get(tool)?.canonicalName ?? tool;
|
|
155
|
+
const reuseOf = (harness, tool) => harness.registry.get(tool)?.approvalReuse ?? "both";
|
|
156
|
+
/** The group each waiting request belongs to: its requests, and the id each request's group has. */
|
|
157
|
+
async function groupsOf(harness, waiting) {
|
|
158
|
+
const groups = new Map();
|
|
159
|
+
const groupOf = new Map();
|
|
160
|
+
for (const { request, input } of waiting) {
|
|
161
|
+
const id = await groupIdOf(nameOf(harness, request.tool), input, request.inputHash);
|
|
162
|
+
groupOf.set(request.id, id);
|
|
163
|
+
groups.set(id, [...(groups.get(id) ?? []), request.id]);
|
|
164
|
+
}
|
|
165
|
+
return { groups, groupOf };
|
|
166
|
+
}
|
|
167
|
+
/** One entry to write: the answer, and, for an allow that is sticky, what it covers once the refusals have passed. */
|
|
168
|
+
function recordOf(harness, pending, resolution, groupId, options, secrets) {
|
|
169
|
+
const grouped = groupId === undefined ? {} : { groupId };
|
|
170
|
+
if (decisionOf(resolution) !== "allow" || options.sticky === undefined)
|
|
171
|
+
return { resolution, ...grouped };
|
|
172
|
+
const { request, input } = pending;
|
|
173
|
+
checkReuse(request.tool, reuseOf(harness, request.tool), "sticky");
|
|
174
|
+
checkSticky(input, options.commandPrefix, secrets);
|
|
175
|
+
const match = options.commandPrefix === undefined
|
|
176
|
+
? { inputHash: request.inputHash }
|
|
177
|
+
: { commandPrefix: [...options.commandPrefix] };
|
|
178
|
+
const version = request.policyVersion === undefined ? {} : { policyVersion: request.policyVersion };
|
|
179
|
+
return {
|
|
180
|
+
resolution,
|
|
181
|
+
sticky: options.sticky,
|
|
182
|
+
allowance: { tool: nameOf(harness, request.tool), ...match, ...version },
|
|
183
|
+
...grouped,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
/** The entries to write: each answer, expanded to its group, with what it covers beyond its own call. */
|
|
187
|
+
async function recordsFor(harness, waiting, resolutions, options, secrets) {
|
|
188
|
+
const { groups, groupOf } = options.group === true ? await groupsOf(harness, waiting) : { groups: new Map(), groupOf: new Map() };
|
|
189
|
+
const expanded = options.group === true ? expandGroup(resolutions, groups, groupOf) : [...resolutions];
|
|
190
|
+
const byId = new Map(waiting.map((entry) => [entry.request.id, entry]));
|
|
191
|
+
// Only a group that really joins requests needs its tool to allow one answer for several calls.
|
|
192
|
+
for (const resolution of expanded) {
|
|
193
|
+
const members = groups.get(groupOf.get(resolution.requestId) ?? "") ?? [];
|
|
194
|
+
const tool = byId.get(resolution.requestId).request.tool;
|
|
195
|
+
if (members.length > 1)
|
|
196
|
+
checkReuse(tool, reuseOf(harness, tool), "group");
|
|
197
|
+
}
|
|
198
|
+
return expanded.map((resolution) => recordOf(harness, byId.get(resolution.requestId), resolution, groupOf.get(resolution.requestId), options, secrets));
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Resolves one code call: the answer is checked against the call's signed request, written with what it covers, and
|
|
202
|
+
* settled by the quorum policy, and the call then waits, is denied, or runs with no model step.
|
|
203
|
+
*/
|
|
204
|
+
async function resolveCodeCall(harness, session, policy, settings, resolution, options) {
|
|
205
|
+
const path = await session.path();
|
|
206
|
+
const waiting = pendingCodeCalls(path);
|
|
207
|
+
checkAnswers(harness, new Map(waiting.map((entry) => [entry.request.id, entry])), [resolution], options.requesterId);
|
|
208
|
+
const call = waiting.find((entry) => entry.request.id === resolution.requestId);
|
|
209
|
+
await checkCodeCallRequest(harness, call, resolution, options.hostContext);
|
|
210
|
+
if (options.group === true)
|
|
211
|
+
checkReuse(call.request.tool, reuseOf(harness, call.request.tool), "group");
|
|
212
|
+
const record = recordOf(harness, call, resolution, undefined, options, await (settings.secrets?.() ?? []));
|
|
213
|
+
const outcome = await settled(policy, [call], answersByRequest(path), [record]);
|
|
214
|
+
const key = await codeCallEffectKey(session, harness, harness.registry.get(call.call.tool), call.call);
|
|
215
|
+
return finishCodeCall(harness, session, call, { forRun: outcome.forRun[0], records: outcome.records, effectKey: key }, options);
|
|
216
|
+
}
|
|
217
|
+
//# sourceMappingURL=approvals.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"approvals.js","sourceRoot":"","sources":["../../src/session/approvals.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OAAO,EAAE,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;IACvG,OAAO,cAAc,CACnB,OAAO,EACP,OAAO,EACP,IAAI,EACJ,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,SAAS,EAAE,GAAG,EAAE,EACvE,OAAO,CACR,CAAC;AACJ,CAAC","sourcesContent":["/**\n * `createApprovals()`: the pause and resume of a call that waits for a person. A gate `ask` ends a turn\n * `awaiting_approval` with the signed request in the log, as an `approval_requested` entry written before the harness's\n * own observers hear of it, and a code call that asks writes the same entry. `pending()` reads the requests that still\n * wait, and `resolve()` answers them from any process that can open the session and load the key ring, because the log\n * holds everything the resume needs. A turn's answers resume the turn; a code call's answer runs the call with no model\n * step. An answer may also cover more than its own call (sticky and grouped answers), and a quorum policy may need\n * several answers before a call runs.\n */\nimport type { SessionEntry } from \"@buildanagent/protocol\";\nimport type { Resolution, SignedPendingRequest } from \"@buildanagent/sdk\";\nimport { HarnessError } from \"../errors.js\";\nimport type { CodeCallResult, Harness } from \"../harness.js\";\nimport type { ApprovalReuse } from \"../tools/types.js\";\nimport { checkCodeCallRequest, codeCallEffectKey, finishCodeCall, inCodeCallQueue } from \"./code-call.js\";\nimport { codeCallRequestIds, pendingCodeCalls, type WaitingCodeCall } from \"./code-call-log.js\";\nimport { type PendingApproval, pendingApprovals } from \"./rebuild.js\";\nimport { type ResolutionRecord, type ResumeOptions, resumeTurn, type TurnResult } from \"./runner.js\";\nimport type { Session } from \"./session.js\";\nimport { checkReuse, checkSticky, groupIdOf } from \"./sticky.js\";\n\n/** What a quorum policy says about one request: its answers are enough, not yet, a refusal, or too old. */\nexport type QuorumVerdict = \"met\" | \"pending\" | \"rejected\" | \"expired\";\n\n/**\n * Decides when a request has enough answers. `resolutions` are every answer written for the request so far, oldest\n * first. The policy keeps its own clock, so it can expire a request by age or because the policy changed. `met` runs\n * the call, `rejected` and `expired` turn it into a denial, and `pending` leaves it waiting.\n */\nexport interface QuorumPolicy {\n /** Decides one waiting request from every answer recorded for it so far, oldest first. */\n evaluate(request: SignedPendingRequest, resolutions: readonly Resolution[]): Promise<QuorumVerdict> | QuorumVerdict;\n}\n\nconst isDeny = (resolution: Resolution): boolean => \"decision\" in resolution && resolution.decision === \"deny\";\n\n/** The default policy: the latest answer decides. Any answer that is not a deny runs the call, and a deny refuses it. */\nexport const oneResolution: QuorumPolicy = {\n evaluate(_request, resolutions) {\n const latest = resolutions.at(-1);\n if (latest === undefined) return \"pending\";\n return isDeny(latest) ? \"rejected\" : \"met\";\n },\n};\n\n/**\n * A policy that needs `needed` allows from distinct approvers, named by `Resolution.by`. A deny as the latest answer\n * refuses the call, and the allows before it do not count. An allow with no `by` counts as one anonymous approver, so a\n * quorum above one needs the host to name them. Throws `invalid_permission_config` unless `needed` is a whole number\n * of at least one.\n */\nexport function quorumOf(needed: number): QuorumPolicy {\n if (!Number.isInteger(needed) || needed < 1) {\n throw new HarnessError(\n \"invalid_permission_config\",\n `a quorum needs a whole number of approvers of at least 1, got ${needed}`,\n );\n }\n return {\n evaluate(_request, resolutions) {\n if (resolutions.length === 0) return \"pending\";\n if (isDeny(resolutions.at(-1) as Resolution)) return \"rejected\";\n const approvers = new Set(\n resolutions.filter((resolution) => !isDeny(resolution)).map((resolution) => resolution.by ?? \"(unnamed)\"),\n );\n return approvers.size >= needed ? \"met\" : \"pending\";\n },\n };\n}\n\n/**\n * The settings a resume takes besides the answers: a turn's settings, and what the answers cover. A code call's\n * resolution reads `hostContext`, `signal`, `clock`, `newId`, `sticky`, `group` and `requesterId`, and ignores the\n * rest: it makes no model call, so `budgetUsd` and the model settings have nothing to apply to.\n */\nexport interface ResolveOptions<H = unknown> extends Omit<ResumeOptions<H>, \"resolutions\" | \"records\"> {\n /** Make each `allow` cover the same call again, for this run or for this session. */\n readonly sticky?: \"run\" | \"session\";\n /** For a shell tool, cover every command that starts with these words, not only the one approved. */\n readonly commandPrefix?: readonly string[];\n /** Apply each answer to every pending request of the step that has the same tool and the same input. */\n readonly group?: boolean;\n /** Who asked. An approver equal to it is refused: nobody approves their own request. */\n readonly requesterId?: string;\n}\n\n/** The options of `createApprovals()`. */\nexport interface ApprovalsOptions {\n /** When a request has enough answers. Default `oneResolution`. */\n readonly quorum?: QuorumPolicy;\n /** The secret values the host's credential store knows. A sticky allowance that covers one is refused. */\n readonly secrets?: () => readonly string[] | Promise<readonly string[]>;\n}\n\n/** The approvals of one harness. */\nexport interface Approvals<H = unknown> {\n /**\n * The requests of the session that still wait, each with the input its call would run with once approved: a paused\n * turn's, then the code calls', in the order they asked.\n */\n pending(session: Session): Promise<PendingApproval[]>;\n /**\n * Answers waiting requests and resumes the turn. Each answer is written as an `approval_resolved` entry first. The\n * quorum policy then decides each request: `met` goes to the SDK, which verifies the request's signature, call and\n * input, so a tampered request runs nothing and is asked again; `rejected` and `expired` become denials; `pending`\n * leaves the call waiting, and the turn ends `awaiting_approval` again. Each approved call goes through the permission\n * pipeline again, and a deny now turns the approval into a denial. Calling it with no answers evaluates the policy\n * for every request of a paused turn, which is how such a request expires. It leaves a code call's request waiting:\n * the policy decides that call when it is next answered, so a late allow for an expired call comes back `denied`.\n *\n * An answer to a code call's request resolves that call alone and returns a `CodeCallResult`. The request is checked\n * against its signature, the host context it binds and the call's recorded input before anything is written, and a\n * request that fails throws `approval_refused` and runs nothing. The answer is then written and the quorum policy\n * decides. `met` decides the call again with the pipeline, so a deny written since the pause wins, and then runs the\n * tool with `options.hostContext` and `options.signal`, with no model call; `rejected` and `expired` deny it; `pending`\n * returns `awaiting_approval`. A request whose call already has a result, or started before a crash, no longer waits,\n * so its tool runs at most once.\n *\n * Throws `approval_not_pending` for a request that does not wait, `approval_unavailable` without a signer,\n * `approver_is_requester` when an approver is the requester, `approval_reuse_refused` when a tool's `approvalReuse`\n * forbids a sticky or grouped answer, `sticky_refused` for an interpreter prefix or a secret, and `invalid_code_call`\n * for answers that name a code call together with any other request. The host fills `Resolution.by` only after it\n * has authenticated the approver; the harness trusts what it is given.\n */\n resolve(\n session: Session,\n resolutions: readonly Resolution[],\n options?: ResolveOptions<H>,\n ): Promise<TurnResult | CodeCallResult>;\n}\n\nconst decisionOf = (resolution: Resolution): \"allow\" | \"deny\" | undefined =>\n \"decision\" in resolution ? resolution.decision : undefined;\n\n/** Copies an answer to the other requests of its group, each with the same decision, reason and approver. */\nfunction expandGroup(\n resolutions: readonly Resolution[],\n groups: ReadonlyMap<string, string[]>,\n groupOf: ReadonlyMap<string, string>,\n): Resolution[] {\n const out = new Map<string, Resolution>(resolutions.map((resolution) => [resolution.requestId, resolution]));\n for (const resolution of resolutions) {\n for (const other of groups.get(groupOf.get(resolution.requestId) ?? \"\") ?? []) {\n if (!out.has(other)) out.set(other, { ...resolution, requestId: other });\n }\n }\n return [...out.values()];\n}\n\n/** The answers already written for each request, oldest first. */\nfunction answersByRequest(path: readonly SessionEntry[]): Map<string, Resolution[]> {\n const answers = new Map<string, Resolution[]>();\n for (const entry of path) {\n if (entry.type === \"approval_resolved\") {\n answers.set(entry.resolution.requestId, [...(answers.get(entry.resolution.requestId) ?? []), entry.resolution]);\n }\n }\n return answers;\n}\n\n/** Refuses an answer set that can't be applied: no signer, an answer twice, a request that doesn't wait, a self-approval. */\nfunction checkAnswers<H>(\n harness: Harness<H>,\n waiting: ReadonlyMap<string, PendingApproval>,\n resolutions: readonly Resolution[],\n requesterId: string | undefined,\n): void {\n if (harness.signer === undefined) {\n throw new HarnessError(\"approval_unavailable\", \"the harness has no signer, so no approval can be checked\");\n }\n const named = new Set<string>();\n for (const resolution of resolutions) {\n if (named.has(resolution.requestId)) {\n throw new HarnessError(\"approval_not_pending\", `request ${resolution.requestId} is answered twice in one resume`);\n }\n named.add(resolution.requestId);\n if (!waiting.has(resolution.requestId)) {\n throw new HarnessError(\"approval_not_pending\", `no request ${resolution.requestId} is waiting in this session`);\n }\n if (requesterId !== undefined && resolution.by === requesterId) {\n throw new HarnessError(\"approver_is_requester\", `the approver ${resolution.by} is the one who asked`);\n }\n }\n}\n\n/** The synthetic denial for a request the policy refused or let expire, with the record that puts it in the log. */\nfunction denial(requestId: string, verdict: \"rejected\" | \"expired\"): ResolutionRecord {\n const reason = verdict === \"expired\" ? \"the approval expired\" : \"the approval was rejected\";\n return { resolution: { requestId, decision: \"deny\", reason, by: \"policy\" } };\n}\n\n/** An answer without what it would cover: a sticky allowance only takes effect once the quorum is met and the call runs. */\nconst plain = ({ resolution, groupId }: ResolutionRecord): ResolutionRecord => ({\n resolution,\n ...(groupId === undefined ? {} : { groupId }),\n});\n\n/** What the SDK is given for one request, and the entries to write for it, once the quorum policy has decided. */\nfunction outcomeOf(\n verdict: QuorumVerdict,\n requestId: string,\n answers: readonly Resolution[],\n fresh: readonly ResolutionRecord[],\n): { forRun?: Resolution; records: ResolutionRecord[] } {\n const latest = answers.at(-1);\n if (verdict === \"met\" && latest !== undefined) {\n const given = answers.findLast((answer) => !isDeny(answer)) ?? latest;\n // A verdict that flips with no new answer (a clock, a policy) still writes the answer the run is given, unmarked.\n return { forRun: given, records: fresh.length > 0 ? [...fresh] : [{ resolution: given }] };\n }\n if (verdict === \"rejected\" || verdict === \"expired\") {\n // A person's own deny is already in the log; a refusal or an expiry by the policy gets an entry of its own.\n if (verdict === \"rejected\" && latest !== undefined && isDeny(latest))\n return { forRun: latest, records: fresh.map(plain) };\n const refusal = denial(requestId, verdict);\n return { forRun: refusal.resolution, records: [...fresh.map(plain), refusal] };\n }\n return { records: fresh.map((record) => ({ ...plain(record), quorum: \"pending\" as const })) };\n}\n\n/**\n * What each waiting request gets once the quorum policy has looked at it: the answer the SDK applies for `met`, a denial\n * for `rejected` and `expired`, and nothing for `pending`, whose new answers are marked as waited on so a crash\n * of this resume never counts them as given. The records returned are the entries to write, denials by the policy\n * included, so the log tells an expiry from any other refusal.\n */\nasync function settled(\n policy: QuorumPolicy,\n waiting: readonly PendingApproval[],\n earlier: ReadonlyMap<string, Resolution[]>,\n records: readonly ResolutionRecord[],\n): Promise<{ forRun: Resolution[]; records: ResolutionRecord[] }> {\n const forRun: Resolution[] = [];\n const out: ResolutionRecord[] = [];\n for (const { request } of waiting) {\n const fresh = records.filter((record) => record.resolution.requestId === request.id);\n const answers = [...(earlier.get(request.id) ?? []), ...fresh.map((record) => record.resolution)];\n const outcome = outcomeOf(await policy.evaluate(request, answers), request.id, answers, fresh);\n if (outcome.forRun !== undefined) forRun.push(outcome.forRun);\n out.push(...outcome.records);\n }\n return { forRun, records: out };\n}\n\n/** Creates the approvals of `harness`, which needs a `signer` to check the requests it resumes. */\nexport function createApprovals<H = unknown>(harness: Harness<H>, settings: ApprovalsOptions = {}): Approvals<H> {\n const policy = settings.quorum ?? oneResolution;\n return {\n async pending(session) {\n const path = await session.path();\n return [...pendingApprovals(path), ...pendingCodeCalls(path).map(({ request, input }) => ({ request, input }))];\n },\n async resolve(session, resolutions, options = {}) {\n if (options.sticky !== undefined && settings.quorum !== undefined) {\n throw new HarnessError(\n \"sticky_refused\",\n \"a sticky allowance needs the default policy: one approver's click would otherwise skip the quorum on every later call\",\n );\n }\n const path = await session.path();\n const codeRequests = codeCallRequestIds(path);\n if (resolutions.some((resolution) => codeRequests.has(resolution.requestId))) {\n if (resolutions.length !== 1) {\n throw new HarnessError(\n \"invalid_code_call\",\n \"a code call's request is answered on its own, in a resolve() that answers nothing else\",\n );\n }\n const only = resolutions[0] as Resolution;\n return inCodeCallQueue(session, () => resolveCodeCall(harness, session, policy, settings, only, options));\n }\n const waiting = pendingApprovals(path);\n checkAnswers(\n harness,\n new Map(waiting.map((entry) => [entry.request.id, entry])),\n resolutions,\n options.requesterId,\n );\n const records = await recordsFor(harness, waiting, resolutions, options, await (settings.secrets?.() ?? []));\n const { forRun, records: toWrite } = await settled(policy, waiting, answersByRequest(path), records);\n return resumeTurn(session, harness, { ...options, resolutions: forRun, records: toWrite });\n },\n };\n}\n\nconst nameOf = <H>(harness: Harness<H>, tool: string): string => harness.registry.get(tool)?.canonicalName ?? tool;\nconst reuseOf = <H>(harness: Harness<H>, tool: string): ApprovalReuse =>\n harness.registry.get(tool)?.approvalReuse ?? \"both\";\n\n/** The group each waiting request belongs to: its requests, and the id each request's group has. */\nasync function groupsOf<H>(harness: Harness<H>, waiting: readonly PendingApproval[]) {\n const groups = new Map<string, string[]>();\n const groupOf = new Map<string, string>();\n for (const { request, input } of waiting) {\n const id = await groupIdOf(nameOf(harness, request.tool), input, request.inputHash);\n groupOf.set(request.id, id);\n groups.set(id, [...(groups.get(id) ?? []), request.id]);\n }\n return { groups, groupOf };\n}\n\n/** One entry to write: the answer, and, for an allow that is sticky, what it covers once the refusals have passed. */\nfunction recordOf<H>(\n harness: Harness<H>,\n pending: PendingApproval,\n resolution: Resolution,\n groupId: string | undefined,\n options: ResolveOptions<H>,\n secrets: readonly string[],\n): ResolutionRecord {\n const grouped = groupId === undefined ? {} : { groupId };\n if (decisionOf(resolution) !== \"allow\" || options.sticky === undefined) return { resolution, ...grouped };\n const { request, input } = pending;\n checkReuse(request.tool, reuseOf(harness, request.tool), \"sticky\");\n checkSticky(input, options.commandPrefix, secrets);\n const match =\n options.commandPrefix === undefined\n ? { inputHash: request.inputHash }\n : { commandPrefix: [...options.commandPrefix] };\n const version = request.policyVersion === undefined ? {} : { policyVersion: request.policyVersion };\n return {\n resolution,\n sticky: options.sticky,\n allowance: { tool: nameOf(harness, request.tool), ...match, ...version },\n ...grouped,\n };\n}\n\n/** The entries to write: each answer, expanded to its group, with what it covers beyond its own call. */\nasync function recordsFor<H>(\n harness: Harness<H>,\n waiting: readonly PendingApproval[],\n resolutions: readonly Resolution[],\n options: ResolveOptions<H>,\n secrets: readonly string[],\n): Promise<ResolutionRecord[]> {\n const { groups, groupOf } =\n options.group === true ? await groupsOf(harness, waiting) : { groups: new Map(), groupOf: new Map() };\n const expanded = options.group === true ? expandGroup(resolutions, groups, groupOf) : [...resolutions];\n const byId = new Map(waiting.map((entry) => [entry.request.id, entry]));\n // Only a group that really joins requests needs its tool to allow one answer for several calls.\n for (const resolution of expanded) {\n const members = groups.get(groupOf.get(resolution.requestId) ?? \"\") ?? [];\n const tool = (byId.get(resolution.requestId) as PendingApproval).request.tool;\n if (members.length > 1) checkReuse(tool, reuseOf(harness, tool), \"group\");\n }\n return expanded.map((resolution) =>\n recordOf(\n harness,\n byId.get(resolution.requestId) as PendingApproval,\n resolution,\n groupOf.get(resolution.requestId),\n options,\n secrets,\n ),\n );\n}\n\n/**\n * Resolves one code call: the answer is checked against the call's signed request, written with what it covers, and\n * settled by the quorum policy, and the call then waits, is denied, or runs with no model step.\n */\nasync function resolveCodeCall<H>(\n harness: Harness<H>,\n session: Session,\n policy: QuorumPolicy,\n settings: ApprovalsOptions,\n resolution: Resolution,\n options: ResolveOptions<H>,\n): Promise<CodeCallResult> {\n const path = await session.path();\n const waiting = pendingCodeCalls(path);\n checkAnswers(harness, new Map(waiting.map((entry) => [entry.request.id, entry])), [resolution], options.requesterId);\n const call = waiting.find((entry) => entry.request.id === resolution.requestId) as WaitingCodeCall;\n await checkCodeCallRequest(harness, call, resolution, options.hostContext);\n if (options.group === true) checkReuse(call.request.tool, reuseOf(harness, call.request.tool), \"group\");\n const record = recordOf(harness, call, resolution, undefined, options, await (settings.secrets?.() ?? []));\n const outcome = await settled(policy, [call], answersByRequest(path), [record]);\n const key = await codeCallEffectKey(session, harness, harness.registry.get(call.call.tool), call.call);\n return finishCodeCall(\n harness,\n session,\n call,\n { forRun: outcome.forRun[0], records: outcome.records, effectKey: key },\n options,\n );\n}\n"]}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the log says about each code call: its `code_call` entry, its result, its latest signed request, whether a person
|
|
3
|
+
* answered it, and whether it was let run. A call that was let run and has no result may have taken effect, so it is
|
|
4
|
+
* never run again: the crash rule a model call follows. A call that was answered but never let run did not run. A call
|
|
5
|
+
* with a request, no final answer and no such mark still waits for a person.
|
|
6
|
+
*/
|
|
7
|
+
import type { CodeCallEntry, SessionEntry, ToolResultEntry } from "@buildanagent/protocol";
|
|
8
|
+
import type { PendingApproval } from "./rebuild.js";
|
|
9
|
+
/** One code call as the log records it. */
|
|
10
|
+
export interface CodeCallRecord {
|
|
11
|
+
readonly call: CodeCallEntry & {
|
|
12
|
+
readonly id: string;
|
|
13
|
+
};
|
|
14
|
+
/** The call's `tool_result` entry, once it has one. */
|
|
15
|
+
readonly result?: SessionEntry & ToolResultEntry;
|
|
16
|
+
/** The call's latest signed request and the input it signs, when it asked for a person. */
|
|
17
|
+
readonly requested?: PendingApproval;
|
|
18
|
+
/**
|
|
19
|
+
* True once a person's answer to the call's request is final: an answer that no quorum still waits on, or the
|
|
20
|
+
* policy's refusal. A call that was answered no longer waits, whether it then ran or not.
|
|
21
|
+
*/
|
|
22
|
+
readonly answered: boolean;
|
|
23
|
+
/**
|
|
24
|
+
* True once nothing could refuse the call any more, so its tool may have started: an allow from the pipeline or a
|
|
25
|
+
* sticky allowance, or, after a person's allow, the pipeline's new decision when it is not a deny. Each is the last
|
|
26
|
+
* entry the call writes before its tool starts. A person's allow alone is not enough, because the checks after it can
|
|
27
|
+
* still deny the call, and a deny clears the mark.
|
|
28
|
+
*/
|
|
29
|
+
readonly letRun: boolean;
|
|
30
|
+
}
|
|
31
|
+
/** A code call that waits for a person: its request, the input the request signs, and its `code_call` entry. */
|
|
32
|
+
export interface WaitingCodeCall extends PendingApproval {
|
|
33
|
+
readonly call: CodeCallEntry & {
|
|
34
|
+
readonly id: string;
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/** Every code call on `path`, by call id, in the order they were made. */
|
|
38
|
+
export declare function codeCallsOf(path: readonly SessionEntry[]): Map<string, CodeCallRecord>;
|
|
39
|
+
/** The code calls on `path` that wait for a person: each asked, has no result, was never answered and never let run. */
|
|
40
|
+
export declare function pendingCodeCalls(path: readonly SessionEntry[]): WaitingCodeCall[];
|
|
41
|
+
/** The ids of every request on `path` that names a code call, waiting or not, so a resolution can be routed by it. */
|
|
42
|
+
export declare function codeCallRequestIds(path: readonly SessionEntry[]): Set<string>;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/** Folds a request or a resolution into the calls read so far. A resolution names only its request, so `callOfRequest` maps one to its call. */
|
|
2
|
+
function foldApproval(calls, callOfRequest, entry) {
|
|
3
|
+
if (entry.type === "approval_requested") {
|
|
4
|
+
const asked = calls.get(entry.request.callId);
|
|
5
|
+
if (asked === undefined)
|
|
6
|
+
return;
|
|
7
|
+
asked.requested = { request: entry.request, input: entry.input };
|
|
8
|
+
asked.answered = false;
|
|
9
|
+
asked.personAllowed = false;
|
|
10
|
+
callOfRequest.set(entry.request.id, entry.request.callId);
|
|
11
|
+
}
|
|
12
|
+
else if (entry.type === "approval_resolved" && entry.quorum === undefined) {
|
|
13
|
+
const answered = calls.get(callOfRequest.get(entry.resolution.requestId) ?? "");
|
|
14
|
+
if (answered === undefined)
|
|
15
|
+
return;
|
|
16
|
+
// The latest final answer decides: a policy's refusal written after a person's allow takes the allow back.
|
|
17
|
+
answered.answered = true;
|
|
18
|
+
answered.personAllowed = "decision" in entry.resolution && entry.resolution.decision === "allow";
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** Folds the pipeline's decision: an allow lets the call run, a deny refuses it, and an ask after a person's allow runs it. */
|
|
22
|
+
function foldDecision(draft, decision) {
|
|
23
|
+
if (decision === "deny")
|
|
24
|
+
draft.letRun = false;
|
|
25
|
+
else if (decision === "allow" || draft.personAllowed)
|
|
26
|
+
draft.letRun = true;
|
|
27
|
+
}
|
|
28
|
+
/** Folds one entry into the calls read so far. */
|
|
29
|
+
function fold(calls, callOfRequest, entry) {
|
|
30
|
+
if (entry.type === "code_call") {
|
|
31
|
+
calls.set(entry.callId, { call: entry, answered: false, personAllowed: false, letRun: false });
|
|
32
|
+
}
|
|
33
|
+
else if (entry.type === "tool_result") {
|
|
34
|
+
const draft = calls.get(entry.callId);
|
|
35
|
+
if (draft !== undefined)
|
|
36
|
+
draft.result ??= entry;
|
|
37
|
+
}
|
|
38
|
+
else if (entry.type === "permission_decision") {
|
|
39
|
+
const draft = calls.get(entry.callId);
|
|
40
|
+
if (draft !== undefined)
|
|
41
|
+
foldDecision(draft, entry.decision);
|
|
42
|
+
}
|
|
43
|
+
else
|
|
44
|
+
foldApproval(calls, callOfRequest, entry);
|
|
45
|
+
}
|
|
46
|
+
/** Every code call on `path`, by call id, in the order they were made. */
|
|
47
|
+
export function codeCallsOf(path) {
|
|
48
|
+
const calls = new Map();
|
|
49
|
+
const callOfRequest = new Map();
|
|
50
|
+
for (const entry of path)
|
|
51
|
+
fold(calls, callOfRequest, entry);
|
|
52
|
+
return calls;
|
|
53
|
+
}
|
|
54
|
+
/** The code calls on `path` that wait for a person: each asked, has no result, was never answered and never let run. */
|
|
55
|
+
export function pendingCodeCalls(path) {
|
|
56
|
+
return [...codeCallsOf(path).values()].flatMap(({ call, result, requested, answered, letRun }) => requested !== undefined && result === undefined && !answered && !letRun ? [{ ...requested, call }] : []);
|
|
57
|
+
}
|
|
58
|
+
/** The ids of every request on `path` that names a code call, waiting or not, so a resolution can be routed by it. */
|
|
59
|
+
export function codeCallRequestIds(path) {
|
|
60
|
+
const calls = new Set(path.flatMap((entry) => (entry.type === "code_call" ? [entry.callId] : [])));
|
|
61
|
+
return new Set(path.flatMap((entry) => entry.type === "approval_requested" && calls.has(entry.request.callId) ? [entry.request.id] : []));
|
|
62
|
+
}
|
|
63
|
+
//# sourceMappingURL=code-call-log.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"code-call-log.js","sourceRoot":"","sources":["../../src/session/code-call-log.ts"],"names":[],"mappings":"AA6CA,gJAAgJ;AAChJ,SAAS,YAAY,CAAC,KAAyB,EAAE,aAAkC,EAAE,KAAmB;IACtG,IAAI,KAAK,CAAC,IAAI,KAAK,oBAAoB,EAAE,CAAC;QACxC,MAAM,KAAK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,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,CAC/F,SAAS,KAAK,SAAS,IAAI,MAAM,KAAK,SAAS,IAAI,CAAC,QAAQ,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CACxG,CAAC;AACJ,CAAC;AAED,sHAAsH;AACtH,MAAM,UAAU,kBAAkB,CAAC,IAA6B;IAC9D,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IACnG,OAAO,IAAI,GAAG,CACZ,IAAI,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE,CACrB,KAAK,CAAC,IAAI,KAAK,oBAAoB,IAAI,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CACjG,CACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * What the log says about each code call: its `code_call` entry, its result, its latest signed request, whether a person\n * answered it, and whether it was let run. A call that was let run and has no result may have taken effect, so it is\n * never run again: the crash rule a model call follows. A call that was answered but never let run did not run. A call\n * with a request, no final answer and no such mark still waits for a person.\n */\nimport type { CodeCallEntry, SessionEntry, ToolResultEntry } from \"@buildanagent/protocol\";\nimport type { PendingApproval } from \"./rebuild.js\";\n\n/** One code call as the log records it. */\nexport interface CodeCallRecord {\n readonly call: CodeCallEntry & { readonly id: string };\n /** The call's `tool_result` entry, once it has one. */\n readonly result?: SessionEntry & ToolResultEntry;\n /** The call's latest signed request and the input it signs, when it asked for a person. */\n readonly requested?: PendingApproval;\n /**\n * True once a person's answer to the call's request is final: an answer that no quorum still waits on, or the\n * policy's refusal. A call that was answered no longer waits, whether it then ran or not.\n */\n readonly answered: boolean;\n /**\n * True once nothing could refuse the call any more, so its tool may have started: an allow from the pipeline or a\n * sticky allowance, or, after a person's allow, the pipeline's new decision when it is not a deny. Each is the last\n * entry the call writes before its tool starts. A person's allow alone is not enough, because the checks after it can\n * still deny the call, and a deny clears the mark.\n */\n readonly letRun: boolean;\n}\n\n/** A code call that waits for a person: its request, the input the request signs, and its `code_call` entry. */\nexport interface WaitingCodeCall extends PendingApproval {\n readonly call: CodeCallEntry & { readonly id: string };\n}\n\ninterface Draft {\n call: CodeCallEntry & { id: string };\n result?: SessionEntry & ToolResultEntry;\n requested?: PendingApproval;\n answered: boolean;\n /** A person's final allow, which the pipeline then decides again. */\n personAllowed: boolean;\n letRun: boolean;\n}\n\n/** Folds a request or a resolution into the calls read so far. A resolution names only its request, so `callOfRequest` maps one to its call. */\nfunction foldApproval(calls: Map<string, Draft>, callOfRequest: Map<string, string>, entry: SessionEntry): void {\n if (entry.type === \"approval_requested\") {\n const asked = calls.get(entry.request.callId);\n if (asked === undefined) return;\n asked.requested = { request: entry.request, input: entry.input };\n asked.answered = false;\n asked.personAllowed = false;\n callOfRequest.set(entry.request.id, entry.request.callId);\n } else if (entry.type === \"approval_resolved\" && entry.quorum === undefined) {\n const answered = calls.get(callOfRequest.get(entry.resolution.requestId) ?? \"\");\n if (answered === undefined) return;\n // The latest final answer decides: a policy's refusal written after a person's allow takes the allow back.\n answered.answered = true;\n answered.personAllowed = \"decision\" in entry.resolution && entry.resolution.decision === \"allow\";\n }\n}\n\n/** Folds the pipeline's decision: an allow lets the call run, a deny refuses it, and an ask after a person's allow runs it. */\nfunction foldDecision(draft: Draft, decision: \"allow\" | \"deny\" | \"ask\"): void {\n if (decision === \"deny\") draft.letRun = false;\n else if (decision === \"allow\" || draft.personAllowed) draft.letRun = true;\n}\n\n/** Folds one entry into the calls read so far. */\nfunction fold(calls: Map<string, Draft>, callOfRequest: Map<string, string>, entry: SessionEntry): void {\n if (entry.type === \"code_call\") {\n calls.set(entry.callId, { call: entry, answered: false, personAllowed: false, letRun: false });\n } else if (entry.type === \"tool_result\") {\n const draft = calls.get(entry.callId);\n if (draft !== undefined) draft.result ??= entry;\n } else if (entry.type === \"permission_decision\") {\n const draft = calls.get(entry.callId);\n if (draft !== undefined) foldDecision(draft, entry.decision);\n } else foldApproval(calls, callOfRequest, entry);\n}\n\n/** Every code call on `path`, by call id, in the order they were made. */\nexport function codeCallsOf(path: readonly SessionEntry[]): Map<string, CodeCallRecord> {\n const calls = new Map<string, Draft>();\n const callOfRequest = new Map<string, string>();\n for (const entry of path) fold(calls, callOfRequest, entry);\n return calls;\n}\n\n/** The code calls on `path` that wait for a person: each asked, has no result, was never answered and never let run. */\nexport function pendingCodeCalls(path: readonly SessionEntry[]): WaitingCodeCall[] {\n return [...codeCallsOf(path).values()].flatMap(({ call, result, requested, answered, letRun }) =>\n requested !== undefined && result === undefined && !answered && !letRun ? [{ ...requested, call }] : [],\n );\n}\n\n/** The ids of every request on `path` that names a code call, waiting or not, so a resolution can be routed by it. */\nexport function codeCallRequestIds(path: readonly SessionEntry[]): Set<string> {\n const calls = new Set(path.flatMap((entry) => (entry.type === \"code_call\" ? [entry.callId] : [])));\n return new Set(\n path.flatMap((entry) =>\n entry.type === \"approval_requested\" && calls.has(entry.request.callId) ? [entry.request.id] : [],\n ),\n );\n}\n"]}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { CodeCallEntry, SessionEntry, ToolResultEntry } from "@buildanagent/protocol";
|
|
2
|
+
import type { ToolResult } from "@buildanagent/sdk";
|
|
3
|
+
import type { Harness } from "../harness.js";
|
|
4
|
+
import type { RegisteredTool } from "../tools/types.js";
|
|
5
|
+
import type { Session } from "./session.js";
|
|
6
|
+
/** What writing the result needs: the session, the clock's time, the signal and the writer of one entry. */
|
|
7
|
+
export interface ResultWriter {
|
|
8
|
+
readonly session: Session;
|
|
9
|
+
readonly now: () => string;
|
|
10
|
+
readonly signal: AbortSignal;
|
|
11
|
+
readonly write: (body: ToolResultEntry) => Promise<SessionEntry>;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Writes the call's `tool_result` from what the tool returned. A result over the store's bound is cut to fit and
|
|
15
|
+
* written again, once at the bound and once at a quarter of it, so the call keeps its result and its outcome. Any other
|
|
16
|
+
* failure of the store is thrown: the call then has no result, and the next code call settles it as one that may have
|
|
17
|
+
* taken effect.
|
|
18
|
+
*/
|
|
19
|
+
export declare function writeCodeCallResult<H>(harness: Harness<H>, writer: ResultWriter, tool: RegisteredTool, call: CodeCallEntry, result: ToolResult<unknown>): Promise<SessionEntry>;
|