@buildanagent/harness 0.0.0-stage → 0.1.0-alpha.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +54 -0
- package/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +21 -0
- package/README.md +822 -2
- package/dist/ablation.d.ts +2 -0
- package/dist/ablation.js +3 -0
- package/dist/ablation.js.map +1 -0
- package/dist/completion/check.d.ts +64 -0
- package/dist/completion/check.js +152 -0
- package/dist/completion/check.js.map +1 -0
- package/dist/completion/checks.d.ts +45 -0
- package/dist/completion/checks.js +173 -0
- package/dist/completion/checks.js.map +1 -0
- package/dist/completion/flags.d.ts +25 -0
- package/dist/completion/flags.js +87 -0
- package/dist/completion/flags.js.map +1 -0
- package/dist/completion/index.d.ts +8 -0
- package/dist/completion/index.js +9 -0
- package/dist/completion/index.js.map +1 -0
- package/dist/completion/snapshot.d.ts +33 -0
- package/dist/completion/snapshot.js +83 -0
- package/dist/completion/snapshot.js.map +1 -0
- package/dist/context/cap.d.ts +32 -0
- package/dist/context/cap.js +50 -0
- package/dist/context/cap.js.map +1 -0
- package/dist/context/estimate.d.ts +18 -0
- package/dist/context/estimate.js +20 -0
- package/dist/context/estimate.js.map +1 -0
- package/dist/context/file-spill.d.ts +15 -0
- package/dist/context/file-spill.js +40 -0
- package/dist/context/file-spill.js.map +1 -0
- package/dist/context/index.d.ts +10 -0
- package/dist/context/index.js +10 -0
- package/dist/context/index.js.map +1 -0
- package/dist/context/mask.d.ts +27 -0
- package/dist/context/mask.js +71 -0
- package/dist/context/mask.js.map +1 -0
- package/dist/context/mid-turn.d.ts +40 -0
- package/dist/context/mid-turn.js +82 -0
- package/dist/context/mid-turn.js.map +1 -0
- package/dist/context/policy.d.ts +9 -0
- package/dist/context/policy.js +140 -0
- package/dist/context/policy.js.map +1 -0
- package/dist/context/spill-ledger.d.ts +25 -0
- package/dist/context/spill-ledger.js +54 -0
- package/dist/context/spill-ledger.js.map +1 -0
- package/dist/context/spill.d.ts +10 -0
- package/dist/context/spill.js +18 -0
- package/dist/context/spill.js.map +1 -0
- package/dist/context/summarize.d.ts +53 -0
- package/dist/context/summarize.js +204 -0
- package/dist/context/summarize.js.map +1 -0
- package/dist/context/summary-template.d.ts +29 -0
- package/dist/context/summary-template.js +69 -0
- package/dist/context/summary-template.js.map +1 -0
- package/dist/context/types.d.ts +150 -0
- package/dist/context/types.js +2 -0
- package/dist/context/types.js.map +1 -0
- package/dist/context/write-cap.d.ts +19 -0
- package/dist/context/write-cap.js +41 -0
- package/dist/context/write-cap.js.map +1 -0
- package/dist/create-harness.d.ts +7 -0
- package/dist/create-harness.js +21 -0
- package/dist/create-harness.js.map +1 -0
- package/dist/credentials/addresses.d.ts +14 -0
- package/dist/credentials/addresses.js +144 -0
- package/dist/credentials/addresses.js.map +1 -0
- package/dist/credentials/allowlist.d.ts +54 -0
- package/dist/credentials/allowlist.js +134 -0
- package/dist/credentials/allowlist.js.map +1 -0
- package/dist/credentials/egress-policy.d.ts +69 -0
- package/dist/credentials/egress-policy.js +170 -0
- package/dist/credentials/egress-policy.js.map +1 -0
- package/dist/credentials/egress-proxy.d.ts +82 -0
- package/dist/credentials/egress-proxy.js +650 -0
- package/dist/credentials/egress-proxy.js.map +1 -0
- package/dist/credentials/git-route.d.ts +68 -0
- package/dist/credentials/git-route.js +288 -0
- package/dist/credentials/git-route.js.map +1 -0
- package/dist/credentials/index.d.ts +13 -0
- package/dist/credentials/index.js +14 -0
- package/dist/credentials/index.js.map +1 -0
- package/dist/credentials/scrub.d.ts +23 -0
- package/dist/credentials/scrub.js +115 -0
- package/dist/credentials/scrub.js.map +1 -0
- package/dist/errors.d.ts +60 -0
- package/dist/errors.js +67 -0
- package/dist/errors.js.map +1 -0
- package/dist/extensions/compose.d.ts +27 -0
- package/dist/extensions/compose.js +83 -0
- package/dist/extensions/compose.js.map +1 -0
- package/dist/extensions/context-files-node.d.ts +28 -0
- package/dist/extensions/context-files-node.js +74 -0
- package/dist/extensions/context-files-node.js.map +1 -0
- package/dist/extensions/context-files.d.ts +68 -0
- package/dist/extensions/context-files.js +214 -0
- package/dist/extensions/context-files.js.map +1 -0
- package/dist/extensions/digest.d.ts +6 -0
- package/dist/extensions/digest.js +68 -0
- package/dist/extensions/digest.js.map +1 -0
- package/dist/extensions/index.d.ts +10 -0
- package/dist/extensions/index.js +10 -0
- package/dist/extensions/index.js.map +1 -0
- package/dist/extensions/load.d.ts +42 -0
- package/dist/extensions/load.js +211 -0
- package/dist/extensions/load.js.map +1 -0
- package/dist/extensions/lock.d.ts +8 -0
- package/dist/extensions/lock.js +95 -0
- package/dist/extensions/lock.js.map +1 -0
- package/dist/extensions/node.d.ts +10 -0
- package/dist/extensions/node.js +11 -0
- package/dist/extensions/node.js.map +1 -0
- package/dist/extensions/project-dirs.d.ts +24 -0
- package/dist/extensions/project-dirs.js +97 -0
- package/dist/extensions/project-dirs.js.map +1 -0
- package/dist/extensions/skills-node.d.ts +34 -0
- package/dist/extensions/skills-node.js +123 -0
- package/dist/extensions/skills-node.js.map +1 -0
- package/dist/extensions/skills.d.ts +51 -0
- package/dist/extensions/skills.js +175 -0
- package/dist/extensions/skills.js.map +1 -0
- package/dist/extensions/trust-file.d.ts +3 -0
- package/dist/extensions/trust-file.js +62 -0
- package/dist/extensions/trust-file.js.map +1 -0
- package/dist/extensions/trust-store-node.d.ts +10 -0
- package/dist/extensions/trust-store-node.js +33 -0
- package/dist/extensions/trust-store-node.js.map +1 -0
- package/dist/extensions/types.d.ts +42 -0
- package/dist/extensions/types.js +2 -0
- package/dist/extensions/types.js.map +1 -0
- package/dist/harness.d.ts +156 -0
- package/dist/harness.js +2 -0
- package/dist/harness.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp/connection.d.ts +22 -0
- package/dist/mcp/connection.js +267 -0
- package/dist/mcp/connection.js.map +1 -0
- package/dist/mcp/content.d.ts +27 -0
- package/dist/mcp/content.js +177 -0
- package/dist/mcp/content.js.map +1 -0
- package/dist/mcp/errors.d.ts +19 -0
- package/dist/mcp/errors.js +21 -0
- package/dist/mcp/errors.js.map +1 -0
- package/dist/mcp/index.d.ts +10 -0
- package/dist/mcp/index.js +10 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/mcp/manager.d.ts +7 -0
- package/dist/mcp/manager.js +173 -0
- package/dist/mcp/manager.js.map +1 -0
- package/dist/mcp/record.d.ts +7 -0
- package/dist/mcp/record.js +20 -0
- package/dist/mcp/record.js.map +1 -0
- package/dist/mcp/stdio.d.ts +39 -0
- package/dist/mcp/stdio.js +382 -0
- package/dist/mcp/stdio.js.map +1 -0
- package/dist/mcp/types.d.ts +172 -0
- package/dist/mcp/types.js +2 -0
- package/dist/mcp/types.js.map +1 -0
- package/dist/memory/index.d.ts +2 -0
- package/dist/memory/index.js +3 -0
- package/dist/memory/index.js.map +1 -0
- package/dist/permissions/default-rules.d.ts +7 -0
- package/dist/permissions/default-rules.js +42 -0
- package/dist/permissions/default-rules.js.map +1 -0
- package/dist/permissions/errors.d.ts +11 -0
- package/dist/permissions/errors.js +14 -0
- package/dist/permissions/errors.js.map +1 -0
- package/dist/permissions/index.d.ts +9 -0
- package/dist/permissions/index.js +9 -0
- package/dist/permissions/index.js.map +1 -0
- package/dist/permissions/match.d.ts +33 -0
- package/dist/permissions/match.js +287 -0
- package/dist/permissions/match.js.map +1 -0
- package/dist/permissions/pipeline.d.ts +9 -0
- package/dist/permissions/pipeline.js +235 -0
- package/dist/permissions/pipeline.js.map +1 -0
- package/dist/permissions/rules.d.ts +22 -0
- package/dist/permissions/rules.js +74 -0
- package/dist/permissions/rules.js.map +1 -0
- package/dist/permissions/shadow.d.ts +5 -0
- package/dist/permissions/shadow.js +22 -0
- package/dist/permissions/shadow.js.map +1 -0
- package/dist/permissions/types.d.ts +104 -0
- package/dist/permissions/types.js +2 -0
- package/dist/permissions/types.js.map +1 -0
- package/dist/sandbox/base.d.ts +45 -0
- package/dist/sandbox/base.js +74 -0
- package/dist/sandbox/base.js.map +1 -0
- package/dist/sandbox/docker/index.d.ts +41 -0
- package/dist/sandbox/docker/index.js +497 -0
- package/dist/sandbox/docker/index.js.map +1 -0
- package/dist/sandbox/errors.d.ts +44 -0
- package/dist/sandbox/errors.js +57 -0
- package/dist/sandbox/errors.js.map +1 -0
- package/dist/sandbox/host-files.d.ts +65 -0
- package/dist/sandbox/host-files.js +258 -0
- package/dist/sandbox/host-files.js.map +1 -0
- package/dist/sandbox/index.d.ts +10 -0
- package/dist/sandbox/index.js +10 -0
- package/dist/sandbox/index.js.map +1 -0
- package/dist/sandbox/none.d.ts +17 -0
- package/dist/sandbox/none.js +108 -0
- package/dist/sandbox/none.js.map +1 -0
- package/dist/sandbox/policy.d.ts +49 -0
- package/dist/sandbox/policy.js +149 -0
- package/dist/sandbox/policy.js.map +1 -0
- package/dist/sandbox/process.d.ts +61 -0
- package/dist/sandbox/process.js +253 -0
- package/dist/sandbox/process.js.map +1 -0
- package/dist/sandbox/spawn-env.d.ts +20 -0
- package/dist/sandbox/spawn-env.js +128 -0
- package/dist/sandbox/spawn-env.js.map +1 -0
- package/dist/sandbox/srt/index.d.ts +38 -0
- package/dist/sandbox/srt/index.js +283 -0
- package/dist/sandbox/srt/index.js.map +1 -0
- package/dist/sandbox/srt/settings.d.ts +60 -0
- package/dist/sandbox/srt/settings.js +84 -0
- package/dist/sandbox/srt/settings.js.map +1 -0
- package/dist/sandbox/types.d.ts +125 -0
- package/dist/sandbox/types.js +6 -0
- package/dist/sandbox/types.js.map +1 -0
- package/dist/server/answers.d.ts +16 -0
- package/dist/server/answers.js +43 -0
- package/dist/server/answers.js.map +1 -0
- package/dist/server/connection.d.ts +99 -0
- package/dist/server/connection.js +309 -0
- package/dist/server/connection.js.map +1 -0
- package/dist/server/dispatcher.d.ts +86 -0
- package/dist/server/dispatcher.js +800 -0
- package/dist/server/dispatcher.js.map +1 -0
- package/dist/server/index.d.ts +13 -0
- package/dist/server/index.js +12 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/local-transport.d.ts +44 -0
- package/dist/server/local-transport.js +103 -0
- package/dist/server/local-transport.js.map +1 -0
- package/dist/server/outbox.d.ts +31 -0
- package/dist/server/outbox.js +130 -0
- package/dist/server/outbox.js.map +1 -0
- package/dist/server/params.d.ts +25 -0
- package/dist/server/params.js +112 -0
- package/dist/server/params.js.map +1 -0
- package/dist/server/protocol.schema.json +2448 -0
- package/dist/server/rpc-session.d.ts +43 -0
- package/dist/server/rpc-session.js +167 -0
- package/dist/server/rpc-session.js.map +1 -0
- package/dist/server/stdio-streams.d.ts +67 -0
- package/dist/server/stdio-streams.js +218 -0
- package/dist/server/stdio-streams.js.map +1 -0
- package/dist/server/stdio.d.ts +59 -0
- package/dist/server/stdio.js +189 -0
- package/dist/server/stdio.js.map +1 -0
- package/dist/server/websocket.d.ts +106 -0
- package/dist/server/websocket.js +327 -0
- package/dist/server/websocket.js.map +1 -0
- package/dist/session/approvals.d.ts +81 -0
- package/dist/session/approvals.js +217 -0
- package/dist/session/approvals.js.map +1 -0
- package/dist/session/code-call-log.d.ts +42 -0
- package/dist/session/code-call-log.js +63 -0
- package/dist/session/code-call-log.js.map +1 -0
- package/dist/session/code-call-result.d.ts +19 -0
- package/dist/session/code-call-result.js +95 -0
- package/dist/session/code-call-result.js.map +1 -0
- package/dist/session/code-call.d.ts +49 -0
- package/dist/session/code-call.js +345 -0
- package/dist/session/code-call.js.map +1 -0
- package/dist/session/effect-scope.d.ts +11 -0
- package/dist/session/effect-scope.js +10 -0
- package/dist/session/effect-scope.js.map +1 -0
- package/dist/session/errors.d.ts +19 -0
- package/dist/session/errors.js +27 -0
- package/dist/session/errors.js.map +1 -0
- package/dist/session/file-index.d.ts +8 -0
- package/dist/session/file-index.js +70 -0
- package/dist/session/file-index.js.map +1 -0
- package/dist/session/file-key-store.d.ts +16 -0
- package/dist/session/file-key-store.js +169 -0
- package/dist/session/file-key-store.js.map +1 -0
- package/dist/session/file-lock.d.ts +52 -0
- package/dist/session/file-lock.js +324 -0
- package/dist/session/file-lock.js.map +1 -0
- package/dist/session/index.d.ts +22 -0
- package/dist/session/index.js +20 -0
- package/dist/session/index.js.map +1 -0
- package/dist/session/jsonl-store.d.ts +37 -0
- package/dist/session/jsonl-store.js +386 -0
- package/dist/session/jsonl-store.js.map +1 -0
- package/dist/session/jsonl.d.ts +9 -0
- package/dist/session/jsonl.js +10 -0
- package/dist/session/jsonl.js.map +1 -0
- package/dist/session/lock.d.ts +19 -0
- package/dist/session/lock.js +2 -0
- package/dist/session/lock.js.map +1 -0
- package/dist/session/memory-store.d.ts +12 -0
- package/dist/session/memory-store.js +60 -0
- package/dist/session/memory-store.js.map +1 -0
- package/dist/session/migrate.d.ts +41 -0
- package/dist/session/migrate.js +86 -0
- package/dist/session/migrate.js.map +1 -0
- package/dist/session/pointer.d.ts +15 -0
- package/dist/session/pointer.js +22 -0
- package/dist/session/pointer.js.map +1 -0
- package/dist/session/rebuild.d.ts +53 -0
- package/dist/session/rebuild.js +230 -0
- package/dist/session/rebuild.js.map +1 -0
- package/dist/session/resume.d.ts +26 -0
- package/dist/session/resume.js +128 -0
- package/dist/session/resume.js.map +1 -0
- package/dist/session/retention.d.ts +97 -0
- package/dist/session/retention.js +702 -0
- package/dist/session/retention.js.map +1 -0
- package/dist/session/runner.d.ts +156 -0
- package/dist/session/runner.js +656 -0
- package/dist/session/runner.js.map +1 -0
- package/dist/session/scheduler.d.ts +47 -0
- package/dist/session/scheduler.js +85 -0
- package/dist/session/scheduler.js.map +1 -0
- package/dist/session/secret-key-store.d.ts +47 -0
- package/dist/session/secret-key-store.js +79 -0
- package/dist/session/secret-key-store.js.map +1 -0
- package/dist/session/session.d.ts +106 -0
- package/dist/session/session.js +353 -0
- package/dist/session/session.js.map +1 -0
- package/dist/session/sticky.d.ts +48 -0
- package/dist/session/sticky.js +232 -0
- package/dist/session/sticky.js.map +1 -0
- package/dist/session/store.d.ts +108 -0
- package/dist/session/store.js +163 -0
- package/dist/session/store.js.map +1 -0
- package/dist/telemetry/index.d.ts +2 -0
- package/dist/telemetry/index.js +3 -0
- package/dist/telemetry/index.js.map +1 -0
- package/dist/testing/fake-sandbox.d.ts +52 -0
- package/dist/testing/fake-sandbox.js +370 -0
- package/dist/testing/fake-sandbox.js.map +1 -0
- package/dist/testing/index.d.ts +10 -0
- package/dist/testing/index.js +11 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/key-store-conformance.d.ts +22 -0
- package/dist/testing/key-store-conformance.js +97 -0
- package/dist/testing/key-store-conformance.js.map +1 -0
- package/dist/testing/run-cases.d.ts +21 -0
- package/dist/testing/run-cases.js +20 -0
- package/dist/testing/run-cases.js.map +1 -0
- package/dist/testing/sandbox-conformance.d.ts +64 -0
- package/dist/testing/sandbox-conformance.js +468 -0
- package/dist/testing/sandbox-conformance.js.map +1 -0
- package/dist/testing/scheduler-conformance.d.ts +32 -0
- package/dist/testing/scheduler-conformance.js +72 -0
- package/dist/testing/scheduler-conformance.js.map +1 -0
- package/dist/testing/store-conformance.d.ts +21 -0
- package/dist/testing/store-conformance.js +320 -0
- package/dist/testing/store-conformance.js.map +1 -0
- package/dist/tools/builtins/bash.d.ts +9 -0
- package/dist/tools/builtins/bash.js +75 -0
- package/dist/tools/builtins/bash.js.map +1 -0
- package/dist/tools/builtins/builtins.d.ts +38 -0
- package/dist/tools/builtins/builtins.js +48 -0
- package/dist/tools/builtins/builtins.js.map +1 -0
- package/dist/tools/builtins/descriptions.d.ts +69 -0
- package/dist/tools/builtins/descriptions.js +94 -0
- package/dist/tools/builtins/descriptions.js.map +1 -0
- package/dist/tools/builtins/fetch.d.ts +12 -0
- package/dist/tools/builtins/fetch.js +157 -0
- package/dist/tools/builtins/fetch.js.map +1 -0
- package/dist/tools/builtins/files.d.ts +27 -0
- package/dist/tools/builtins/files.js +274 -0
- package/dist/tools/builtins/files.js.map +1 -0
- package/dist/tools/builtins/paths.d.ts +30 -0
- package/dist/tools/builtins/paths.js +62 -0
- package/dist/tools/builtins/paths.js.map +1 -0
- package/dist/tools/builtins/results.d.ts +15 -0
- package/dist/tools/builtins/results.js +31 -0
- package/dist/tools/builtins/results.js.map +1 -0
- package/dist/tools/builtins/search.d.ts +18 -0
- package/dist/tools/builtins/search.js +217 -0
- package/dist/tools/builtins/search.js.map +1 -0
- package/dist/tools/errors.d.ts +13 -0
- package/dist/tools/errors.js +17 -0
- package/dist/tools/errors.js.map +1 -0
- package/dist/tools/index.d.ts +12 -0
- package/dist/tools/index.js +11 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/tools/registry.d.ts +3 -0
- package/dist/tools/registry.js +234 -0
- package/dist/tools/registry.js.map +1 -0
- package/dist/tools/tool-search.d.ts +30 -0
- package/dist/tools/tool-search.js +118 -0
- package/dist/tools/tool-search.js.map +1 -0
- package/dist/tools/types.d.ts +106 -0
- package/dist/tools/types.js +2 -0
- package/dist/tools/types.js.map +1 -0
- package/llms.txt +469 -0
- package/package.json +118 -3
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `grep` and `glob`: read-only search, run inside the sandbox with `find` and `grep`, so a pattern the model wrote is
|
|
3
|
+
* matched by a sandboxed process with a timeout and never by a regular expression in the host's own loop. Both list
|
|
4
|
+
* files with `find`, which never follows a symlink, and filter the list here with the permission rules' own glob
|
|
5
|
+
* matcher, so `glob` and `grep`'s file filter read a pattern the same way on every backend.
|
|
6
|
+
*/
|
|
7
|
+
import { defineTool } from "@buildanagent/sdk";
|
|
8
|
+
import { globToRegExp } from "../../permissions/match.js";
|
|
9
|
+
import { BUILTIN_TOOL_DEFAULTS } from "./descriptions.js";
|
|
10
|
+
import { WORKSPACE_KEY } from "./files.js";
|
|
11
|
+
import { checkPath } from "./paths.js";
|
|
12
|
+
import { deniedResult, errorResult, failureResult, textResult } from "./results.js";
|
|
13
|
+
const ENCODER = new TextEncoder();
|
|
14
|
+
const DECODER = new TextDecoder();
|
|
15
|
+
// The most bytes of a command's standard error a warning quotes, so many unreadable files can't flood the result.
|
|
16
|
+
const WARNING_BYTES = 2048;
|
|
17
|
+
/** The line that tells the model a command failed on part of its input, quoting its first lines of standard error. */
|
|
18
|
+
function warningOf(what, result) {
|
|
19
|
+
const stderr = result.stderr.trim();
|
|
20
|
+
const quoted = stderr.length > WARNING_BYTES ? `${stderr.slice(0, WARNING_BYTES)}...` : stderr;
|
|
21
|
+
return `\n[${what} exited with ${result.exitCode}, so some files may be missing: ${quoted}]`;
|
|
22
|
+
}
|
|
23
|
+
async function exec(deps, command, options, signal) {
|
|
24
|
+
return deps.sandbox.exec(command, { env: deps.env, signal, ...options });
|
|
25
|
+
}
|
|
26
|
+
/** `path` as a `find -path` pattern that matches only itself. */
|
|
27
|
+
const literalPattern = (path) => path.replace(/[\\*?[\]]/g, "\\$&");
|
|
28
|
+
/** Lists the regular files under `base` inside the sandbox, skipping the folders search never enters. */
|
|
29
|
+
async function listFiles(deps, base, timeoutMs, signal) {
|
|
30
|
+
const skipped = BUILTIN_TOOL_DEFAULTS.search.skippedFolders.flatMap((name, index) => index === 0 ? ["-name", name] : ["-o", "-name", name]);
|
|
31
|
+
// The starting point is exempt from the prune, so a search of `node_modules` itself still lists its files.
|
|
32
|
+
const prune = ["(", "!", "-path", literalPattern(base), "(", ...skipped, ")", "-prune", ")"];
|
|
33
|
+
const command = ["find", base, ...prune, "-o", "-type", "f", "-print0"];
|
|
34
|
+
let result;
|
|
35
|
+
try {
|
|
36
|
+
result = await exec(deps, command, { timeoutMs }, signal);
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
return { result: failureResult(error) };
|
|
40
|
+
}
|
|
41
|
+
if ("denied" in result)
|
|
42
|
+
return { result: deniedResult(result.denied) };
|
|
43
|
+
const names = result.stdout.split("\u0000");
|
|
44
|
+
// The last name is empty after a whole listing, and only part of a path when the output was cut.
|
|
45
|
+
names.pop();
|
|
46
|
+
// find exits with 1 when it could not read part of the tree, and still prints what it could: keep that.
|
|
47
|
+
if (result.exitCode !== 0 && names.length === 0) {
|
|
48
|
+
return { result: errorResult(`Listing ${base} failed with exit code ${result.exitCode}: ${result.stderr.trim()}`) };
|
|
49
|
+
}
|
|
50
|
+
const warning = result.exitCode === 0 ? "" : warningOf("find", result);
|
|
51
|
+
return { files: names, cut: result.truncated === true, warning };
|
|
52
|
+
}
|
|
53
|
+
// A base of "/" already ends in the separator, so the slice starts right after it.
|
|
54
|
+
const relativeTo = (base, path) => path === base ? (path.split("/").at(-1) ?? "") : path.slice(base === "/" ? 1 : base.length + 1);
|
|
55
|
+
/** A filter for the listed files: an absolute glob matches the whole path, and a relative one the path below `base`. */
|
|
56
|
+
function matcher(pattern, base, byName) {
|
|
57
|
+
const regex = globToRegExp(pattern);
|
|
58
|
+
if (pattern.startsWith("/"))
|
|
59
|
+
return (path) => regex.test(path);
|
|
60
|
+
if (byName && !pattern.includes("/"))
|
|
61
|
+
return (path) => regex.test(path.split("/").at(-1) ?? "");
|
|
62
|
+
return (path) => regex.test(relativeTo(base, path));
|
|
63
|
+
}
|
|
64
|
+
async function globFiles(deps, input, signal) {
|
|
65
|
+
const checked = checkPath(deps.bounds, input.path ?? deps.bounds.root, "read");
|
|
66
|
+
if ("refused" in checked)
|
|
67
|
+
return errorResult(checked.refused);
|
|
68
|
+
const listing = await listFiles(deps, checked.path, BUILTIN_TOOL_DEFAULTS.glob.timeoutMs, signal);
|
|
69
|
+
if ("result" in listing)
|
|
70
|
+
return listing.result;
|
|
71
|
+
const matches = matcher(input.pattern, checked.path, false);
|
|
72
|
+
const found = listing.files.filter(matches).sort();
|
|
73
|
+
const cut = `${listing.cut ? "\n[the file listing was cut, so some matches may be missing]" : ""}${listing.warning}`;
|
|
74
|
+
if (found.length === 0)
|
|
75
|
+
return textResult(`No file under ${checked.path} matches ${input.pattern}.${cut}`);
|
|
76
|
+
return textResult(`${found.join("\n")}${cut}`, { files: found.length });
|
|
77
|
+
}
|
|
78
|
+
/** The `glob` tool. */
|
|
79
|
+
export function globTool(deps) {
|
|
80
|
+
return defineTool({
|
|
81
|
+
name: "glob",
|
|
82
|
+
description: BUILTIN_TOOL_DEFAULTS.glob.description,
|
|
83
|
+
inputSchema: {
|
|
84
|
+
type: "object",
|
|
85
|
+
properties: {
|
|
86
|
+
pattern: { type: "string", minLength: 1, description: "The glob to match, such as `**/*.ts`." },
|
|
87
|
+
path: { type: "string", description: "The folder to search, relative to the workspace root or absolute." },
|
|
88
|
+
},
|
|
89
|
+
required: ["pattern"],
|
|
90
|
+
additionalProperties: false,
|
|
91
|
+
},
|
|
92
|
+
firstParty: true,
|
|
93
|
+
annotations: { readOnlyHint: true },
|
|
94
|
+
resourceKey: () => WORKSPACE_KEY,
|
|
95
|
+
execute: (input, ctx) => globFiles(deps, input, ctx.signal),
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Where grep's first match in `stdout` is: the file of `batch` that the output starts with, and its line number. grep
|
|
100
|
+
* prints `path:line:text`, and a path may itself hold a colon, so the path is matched against the files searched.
|
|
101
|
+
*/
|
|
102
|
+
function firstMatch(stdout, batch) {
|
|
103
|
+
const path = batch.find((file) => stdout.startsWith(`${file}:`));
|
|
104
|
+
if (path === undefined)
|
|
105
|
+
return {};
|
|
106
|
+
const line = /^(\d+):/.exec(stdout.slice(path.length + 1))?.[1];
|
|
107
|
+
return line === undefined ? { path } : { path, line: Number(line) };
|
|
108
|
+
}
|
|
109
|
+
/** The longest start of `text` that ends a line and fits in `bytes` UTF-8 bytes. */
|
|
110
|
+
function wholeLines(text, bytes) {
|
|
111
|
+
const encoded = ENCODER.encode(text);
|
|
112
|
+
if (encoded.length <= bytes)
|
|
113
|
+
return text.endsWith("\n") ? text : text.slice(0, text.lastIndexOf("\n") + 1);
|
|
114
|
+
const end = encoded.subarray(0, bytes).lastIndexOf(10);
|
|
115
|
+
return DECODER.decode(encoded.subarray(0, end + 1));
|
|
116
|
+
}
|
|
117
|
+
/** Runs one `grep` command over `batch`, and returns what it did, or the result that ends the call. */
|
|
118
|
+
async function grepBatch(deps, flags, batch, signal) {
|
|
119
|
+
const { timeoutMs, maxOutputBytes } = BUILTIN_TOOL_DEFAULTS.grep;
|
|
120
|
+
let result;
|
|
121
|
+
try {
|
|
122
|
+
result = await exec(deps, ["grep", ...flags, "--", ...batch], { timeoutMs, maxOutputBytes }, signal);
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
return { result: failureResult(error) };
|
|
126
|
+
}
|
|
127
|
+
return "denied" in result ? { result: deniedResult(result.denied) } : result;
|
|
128
|
+
}
|
|
129
|
+
const CUT_NOTICE = `\n[the matches passed ${BUILTIN_TOOL_DEFAULTS.grep.maxOutputBytes} bytes, so the rest were dropped and some files ` +
|
|
130
|
+
"were not searched; narrow the pattern, path or glob to see them]";
|
|
131
|
+
/**
|
|
132
|
+
* Runs `grep` over `files` in batches, and returns the matching lines, or the result that ends the call. The lines stop
|
|
133
|
+
* at the tool's output cap, across all the batches, and a batch with a file grep could not read keeps its matches and
|
|
134
|
+
* adds a warning. The call fails only when no batch matched and one failed, as an unreadable pattern makes every one.
|
|
135
|
+
*/
|
|
136
|
+
async function grepFiles(deps, input, files, signal) {
|
|
137
|
+
const { filesPerCommand } = BUILTIN_TOOL_DEFAULTS.search;
|
|
138
|
+
const { maxOutputBytes } = BUILTIN_TOOL_DEFAULTS.grep;
|
|
139
|
+
const flags = ["-n", "-H", "-I", "-E", ...(input.ignore_case === true ? ["-i"] : []), "-e", input.pattern];
|
|
140
|
+
let lines = "";
|
|
141
|
+
let size = 0;
|
|
142
|
+
let failed;
|
|
143
|
+
const warning = () => (failed === undefined ? "" : warningOf("grep", failed));
|
|
144
|
+
for (let at = 0; at < files.length; at += filesPerCommand) {
|
|
145
|
+
const batch = files.slice(at, at + filesPerCommand);
|
|
146
|
+
const result = await grepBatch(deps, flags, batch, signal);
|
|
147
|
+
if ("result" in result)
|
|
148
|
+
return result;
|
|
149
|
+
// grep exits with 1 when nothing matched, and with 2 for an error, such as a file it can't read or a bad pattern.
|
|
150
|
+
if (result.exitCode > 1)
|
|
151
|
+
failed ??= result;
|
|
152
|
+
// A cut stream ends part way through a line, so only its whole lines are kept.
|
|
153
|
+
const kept = wholeLines(result.stdout, maxOutputBytes - size);
|
|
154
|
+
lines += kept;
|
|
155
|
+
size += ENCODER.encode(kept).length;
|
|
156
|
+
if (result.truncated === true || kept.length < result.stdout.length) {
|
|
157
|
+
// A match whose line alone passes the cap leaves no whole line to show, but it is still a match: say so, so the
|
|
158
|
+
// model never reads that the pattern matched nothing.
|
|
159
|
+
const tooLong = lines === "" && result.stdout !== "" ? { tooLong: firstMatch(result.stdout, batch) } : {};
|
|
160
|
+
return { lines, notes: `${CUT_NOTICE}${warning()}`, ...tooLong };
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
if (failed !== undefined && lines === "")
|
|
164
|
+
return { result: errorResult(`grep failed: ${failed.stderr.trim()}`) };
|
|
165
|
+
return { lines, notes: warning() };
|
|
166
|
+
}
|
|
167
|
+
/** The sentence for matches whose lines are each too long to show: they exist, where the first is, and what to do. */
|
|
168
|
+
function tooLongSentence(base, pattern, first) {
|
|
169
|
+
const { maxOutputBytes } = BUILTIN_TOOL_DEFAULTS.grep;
|
|
170
|
+
const where = first.path === undefined
|
|
171
|
+
? ""
|
|
172
|
+
: ` The first is in ${first.path}${first.line === undefined ? "" : `, on line ${first.line}`}.`;
|
|
173
|
+
return (`Lines under ${base} match ${pattern}, but the first matching line is longer than ${maxOutputBytes} bytes, so ` +
|
|
174
|
+
`none can be shown.${where} Narrow the pattern, path or glob, or read the matching file with read, in parts.`);
|
|
175
|
+
}
|
|
176
|
+
async function grep(deps, input, signal) {
|
|
177
|
+
const checked = checkPath(deps.bounds, input.path ?? deps.bounds.root, "read");
|
|
178
|
+
if ("refused" in checked)
|
|
179
|
+
return errorResult(checked.refused);
|
|
180
|
+
const listing = await listFiles(deps, checked.path, BUILTIN_TOOL_DEFAULTS.grep.timeoutMs, signal);
|
|
181
|
+
if ("result" in listing)
|
|
182
|
+
return listing.result;
|
|
183
|
+
const files = input.glob === undefined ? listing.files : listing.files.filter(matcher(input.glob, checked.path, true));
|
|
184
|
+
const found = files.length === 0 ? { lines: "", notes: "" } : await grepFiles(deps, input, [...files].sort(), signal);
|
|
185
|
+
if ("result" in found)
|
|
186
|
+
return found.result;
|
|
187
|
+
const cut = listing.cut ? "\n[the file listing was cut, so some files were not searched]" : "";
|
|
188
|
+
const notes = `${found.notes}${cut}${listing.warning}`;
|
|
189
|
+
if (found.tooLong !== undefined)
|
|
190
|
+
return textResult(`${tooLongSentence(checked.path, input.pattern, found.tooLong)}${notes}`);
|
|
191
|
+
if (found.lines === "")
|
|
192
|
+
return textResult(`No line under ${checked.path} matches ${input.pattern}.${notes}`);
|
|
193
|
+
return textResult(`${found.lines.trimEnd()}${notes}`);
|
|
194
|
+
}
|
|
195
|
+
/** The `grep` tool. */
|
|
196
|
+
export function grepTool(deps) {
|
|
197
|
+
return defineTool({
|
|
198
|
+
name: "grep",
|
|
199
|
+
description: BUILTIN_TOOL_DEFAULTS.grep.description,
|
|
200
|
+
inputSchema: {
|
|
201
|
+
type: "object",
|
|
202
|
+
properties: {
|
|
203
|
+
pattern: { type: "string", minLength: 1, description: "The extended regular expression to find." },
|
|
204
|
+
path: { type: "string", description: "The file or folder to search. Default the workspace root." },
|
|
205
|
+
glob: { type: "string", description: "Only files that match this glob, such as `*.ts`." },
|
|
206
|
+
ignore_case: { type: "boolean", description: "Match without regard to case." },
|
|
207
|
+
},
|
|
208
|
+
required: ["pattern"],
|
|
209
|
+
additionalProperties: false,
|
|
210
|
+
},
|
|
211
|
+
firstParty: true,
|
|
212
|
+
annotations: { readOnlyHint: true },
|
|
213
|
+
resourceKey: () => WORKSPACE_KEY,
|
|
214
|
+
execute: (input, ctx) => grep(deps, input, ctx.signal),
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
//# sourceMappingURL=search.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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QAAQ,EAAE,WAAW,EAAE,2DAA2D,EAAE;gBAClG,IAAI,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,kDAAkD,EAAE;gBACzF,WAAW,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,+BAA+B,EAAE;aAC/E;YACD,QAAQ,EAAE,CAAC,SAAS,CAAC;YACrB,oBAAoB,EAAE,KAAK;SAC5B;QACD,UAAU,EAAE,IAAI;QAChB,WAAW,EAAE,EAAE,YAAY,EAAE,IAAI,EAAE;QACnC,WAAW,EAAE,GAAG,EAAE,CAAC,aAAa;QAChC,OAAO,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,MAAM,CAAC;KACvD,CAAY,CAAC;AAChB,CAAC","sourcesContent":["/**\n * `grep` and `glob`: read-only search, run inside the sandbox with `find` and `grep`, so a pattern the model wrote is\n * matched by a sandboxed process with a timeout and never by a regular expression in the host's own loop. Both list\n * files with `find`, which never follows a symlink, and filter the list here with the permission rules' own glob\n * matcher, so `glob` and `grep`'s file filter read a pattern the same way on every backend.\n */\nimport { defineTool, type ToolDefinition, type ToolResult } from \"@buildanagent/sdk\";\nimport { globToRegExp } from \"../../permissions/match.js\";\nimport type { ExecResult } from \"../../sandbox/types.js\";\nimport { BUILTIN_TOOL_DEFAULTS } from \"./descriptions.js\";\nimport { type FileDeps, WORKSPACE_KEY } from \"./files.js\";\nimport { checkPath } from \"./paths.js\";\nimport { deniedResult, errorResult, failureResult, textResult } from \"./results.js\";\n\ntype AnyTool = ToolDefinition<unknown, unknown, unknown>;\n\nconst ENCODER = new TextEncoder();\nconst DECODER = new TextDecoder();\n\n/** What the search tools share with the file tools, plus the environment their commands run with. */\nexport interface SearchDeps extends FileDeps {\n readonly env: Readonly<Record<string, string>>;\n}\n\n/**\n * Either the files under `base` (with a warning when `find` could not read part of the tree) or the result that ends\n * the call: a refusal, a denial or a listing that produced nothing.\n */\ntype Listing =\n | { readonly files: readonly string[]; readonly cut: boolean; readonly warning: string }\n | { readonly result: ToolResult };\n\n// The most bytes of a command's standard error a warning quotes, so many unreadable files can't flood the result.\nconst WARNING_BYTES = 2048;\n\n/** The line that tells the model a command failed on part of its input, quoting its first lines of standard error. */\nfunction warningOf(what: string, result: { exitCode: number; stderr: string }): string {\n const stderr = result.stderr.trim();\n const quoted = stderr.length > WARNING_BYTES ? `${stderr.slice(0, WARNING_BYTES)}...` : stderr;\n return `\\n[${what} exited with ${result.exitCode}, so some files may be missing: ${quoted}]`;\n}\n\nasync function exec(\n deps: SearchDeps,\n command: string[],\n options: { readonly timeoutMs: number; readonly maxOutputBytes?: number },\n signal: AbortSignal,\n): Promise<ExecResult> {\n return deps.sandbox.exec(command, { env: deps.env, signal, ...options });\n}\n\n/** `path` as a `find -path` pattern that matches only itself. */\nconst literalPattern = (path: string): string => path.replace(/[\\\\*?[\\]]/g, \"\\\\$&\");\n\n/** Lists the regular files under `base` inside the sandbox, skipping the folders search never enters. */\nasync function listFiles(deps: SearchDeps, base: string, timeoutMs: number, signal: AbortSignal): Promise<Listing> {\n const skipped = BUILTIN_TOOL_DEFAULTS.search.skippedFolders.flatMap((name, index) =>\n index === 0 ? [\"-name\", name] : [\"-o\", \"-name\", name],\n );\n // The starting point is exempt from the prune, so a search of `node_modules` itself still lists its files.\n const prune = [\"(\", \"!\", \"-path\", literalPattern(base), \"(\", ...skipped, \")\", \"-prune\", \")\"];\n const command = [\"find\", base, ...prune, \"-o\", \"-type\", \"f\", \"-print0\"];\n let result: ExecResult;\n try {\n result = await exec(deps, command, { timeoutMs }, signal);\n } catch (error) {\n return { result: failureResult(error) };\n }\n if (\"denied\" in result) return { result: deniedResult(result.denied) };\n const names = result.stdout.split(\"\\u0000\");\n // The last name is empty after a whole listing, and only part of a path when the output was cut.\n names.pop();\n // find exits with 1 when it could not read part of the tree, and still prints what it could: keep that.\n if (result.exitCode !== 0 && names.length === 0) {\n return { result: errorResult(`Listing ${base} failed with exit code ${result.exitCode}: ${result.stderr.trim()}`) };\n }\n const warning = result.exitCode === 0 ? \"\" : warningOf(\"find\", result);\n return { files: names, cut: result.truncated === true, warning };\n}\n\n// A base of \"/\" already ends in the separator, so the slice starts right after it.\nconst relativeTo = (base: string, path: string): string =>\n path === base ? (path.split(\"/\").at(-1) ?? \"\") : path.slice(base === \"/\" ? 1 : base.length + 1);\n\n/** A filter for the listed files: an absolute glob matches the whole path, and a relative one the path below `base`. */\nfunction matcher(pattern: string, base: string, byName: boolean): (path: string) => boolean {\n const regex = globToRegExp(pattern);\n if (pattern.startsWith(\"/\")) return (path) => regex.test(path);\n if (byName && !pattern.includes(\"/\")) return (path) => regex.test(path.split(\"/\").at(-1) ?? \"\");\n return (path) => regex.test(relativeTo(base, path));\n}\n\ninterface GlobInput {\n readonly pattern: string;\n readonly path?: string;\n}\n\nasync function globFiles(deps: SearchDeps, input: GlobInput, signal: AbortSignal): Promise<ToolResult> {\n const checked = checkPath(deps.bounds, input.path ?? deps.bounds.root, \"read\");\n if (\"refused\" in checked) return errorResult(checked.refused);\n const listing = await listFiles(deps, checked.path, BUILTIN_TOOL_DEFAULTS.glob.timeoutMs, signal);\n if (\"result\" in listing) return listing.result;\n const matches = matcher(input.pattern, checked.path, false);\n const found = listing.files.filter(matches).sort();\n const cut = `${listing.cut ? \"\\n[the file listing was cut, so some matches may be missing]\" : \"\"}${listing.warning}`;\n if (found.length === 0) return textResult(`No file under ${checked.path} matches ${input.pattern}.${cut}`);\n return textResult(`${found.join(\"\\n\")}${cut}`, { files: found.length });\n}\n\n/** The `glob` tool. */\nexport function globTool(deps: SearchDeps): AnyTool {\n return defineTool<GlobInput>({\n name: \"glob\",\n description: BUILTIN_TOOL_DEFAULTS.glob.description,\n inputSchema: {\n type: \"object\",\n properties: {\n pattern: { type: \"string\", minLength: 1, description: \"The glob to match, such as `**/*.ts`.\" },\n path: { type: \"string\", description: \"The folder to search, relative to the workspace root or absolute.\" },\n },\n required: [\"pattern\"],\n additionalProperties: false,\n },\n firstParty: true,\n annotations: { readOnlyHint: true },\n resourceKey: () => WORKSPACE_KEY,\n execute: (input, ctx) => globFiles(deps, input, ctx.signal),\n }) as AnyTool;\n}\n\ninterface GrepInput {\n readonly pattern: string;\n readonly path?: string;\n readonly glob?: string;\n readonly ignore_case?: boolean;\n}\n\n/**\n * What the grep commands found: the matching lines, the notices that say what they may have missed, and, when matches\n * were found but none fits whole, where the first one is.\n */\ninterface Found {\n readonly lines: string;\n readonly notes: string;\n readonly tooLong?: { readonly path?: string; readonly line?: number };\n}\n\n/**\n * Where grep's first match in `stdout` is: the file of `batch` that the output starts with, and its line number. grep\n * prints `path:line:text`, and a path may itself hold a colon, so the path is matched against the files searched.\n */\nfunction firstMatch(stdout: string, batch: readonly string[]): { path?: string; line?: number } {\n const path = batch.find((file) => stdout.startsWith(`${file}:`));\n if (path === undefined) return {};\n const line = /^(\\d+):/.exec(stdout.slice(path.length + 1))?.[1];\n return line === undefined ? { path } : { path, line: Number(line) };\n}\n\n/** The longest start of `text` that ends a line and fits in `bytes` UTF-8 bytes. */\nfunction wholeLines(text: string, bytes: number): string {\n const encoded = ENCODER.encode(text);\n if (encoded.length <= bytes) return text.endsWith(\"\\n\") ? text : text.slice(0, text.lastIndexOf(\"\\n\") + 1);\n const end = encoded.subarray(0, bytes).lastIndexOf(10);\n return DECODER.decode(encoded.subarray(0, end + 1));\n}\n\n/** Runs one `grep` command over `batch`, and returns what it did, or the result that ends the call. */\nasync function grepBatch(\n deps: SearchDeps,\n flags: readonly string[],\n batch: readonly string[],\n signal: AbortSignal,\n): Promise<Extract<ExecResult, { exitCode: number }> | { readonly result: ToolResult }> {\n const { timeoutMs, maxOutputBytes } = BUILTIN_TOOL_DEFAULTS.grep;\n let result: ExecResult;\n try {\n result = await exec(deps, [\"grep\", ...flags, \"--\", ...batch], { timeoutMs, maxOutputBytes }, signal);\n } catch (error) {\n return { result: failureResult(error) };\n }\n return \"denied\" in result ? { result: deniedResult(result.denied) } : result;\n}\n\nconst CUT_NOTICE =\n `\\n[the matches passed ${BUILTIN_TOOL_DEFAULTS.grep.maxOutputBytes} bytes, so the rest were dropped and some files ` +\n \"were not searched; narrow the pattern, path or glob to see them]\";\n\n/**\n * Runs `grep` over `files` in batches, and returns the matching lines, or the result that ends the call. The lines stop\n * at the tool's output cap, across all the batches, and a batch with a file grep could not read keeps its matches and\n * adds a warning. The call fails only when no batch matched and one failed, as an unreadable pattern makes every one.\n */\nasync function grepFiles(\n deps: SearchDeps,\n input: GrepInput,\n files: readonly string[],\n signal: AbortSignal,\n): Promise<Found | { readonly result: ToolResult }> {\n const { filesPerCommand } = BUILTIN_TOOL_DEFAULTS.search;\n const { maxOutputBytes } = BUILTIN_TOOL_DEFAULTS.grep;\n const flags = [\"-n\", \"-H\", \"-I\", \"-E\", ...(input.ignore_case === true ? [\"-i\"] : []), \"-e\", input.pattern];\n let lines = \"\";\n let size = 0;\n let failed: Extract<ExecResult, { exitCode: number }> | undefined;\n const warning = () => (failed === undefined ? \"\" : warningOf(\"grep\", failed));\n for (let at = 0; at < files.length; at += filesPerCommand) {\n const batch = files.slice(at, at + filesPerCommand);\n const result = await grepBatch(deps, flags, batch, signal);\n if (\"result\" in result) return result;\n // grep exits with 1 when nothing matched, and with 2 for an error, such as a file it can't read or a bad pattern.\n if (result.exitCode > 1) failed ??= result;\n // A cut stream ends part way through a line, so only its whole lines are kept.\n const kept = wholeLines(result.stdout, maxOutputBytes - size);\n lines += kept;\n size += ENCODER.encode(kept).length;\n if (result.truncated === true || kept.length < result.stdout.length) {\n // A match whose line alone passes the cap leaves no whole line to show, but it is still a match: say so, so the\n // model never reads that the pattern matched nothing.\n const tooLong = lines === \"\" && result.stdout !== \"\" ? { tooLong: firstMatch(result.stdout, batch) } : {};\n return { lines, notes: `${CUT_NOTICE}${warning()}`, ...tooLong };\n }\n }\n if (failed !== undefined && lines === \"\") return { result: errorResult(`grep failed: ${failed.stderr.trim()}`) };\n return { lines, notes: warning() };\n}\n\n/** The sentence for matches whose lines are each too long to show: they exist, where the first is, and what to do. */\nfunction tooLongSentence(base: string, pattern: string, first: { path?: string; line?: number }): string {\n const { maxOutputBytes } = BUILTIN_TOOL_DEFAULTS.grep;\n const where =\n first.path === undefined\n ? \"\"\n : ` The first is in ${first.path}${first.line === undefined ? \"\" : `, on line ${first.line}`}.`;\n return (\n `Lines under ${base} match ${pattern}, but the first matching line is longer than ${maxOutputBytes} bytes, so ` +\n `none can be shown.${where} Narrow the pattern, path or glob, or read the matching file with read, in parts.`\n );\n}\n\nasync function grep(deps: SearchDeps, input: GrepInput, signal: AbortSignal): Promise<ToolResult> {\n const checked = checkPath(deps.bounds, input.path ?? deps.bounds.root, \"read\");\n if (\"refused\" in checked) return errorResult(checked.refused);\n const listing = await listFiles(deps, checked.path, BUILTIN_TOOL_DEFAULTS.grep.timeoutMs, signal);\n if (\"result\" in listing) return listing.result;\n const files =\n input.glob === undefined ? listing.files : listing.files.filter(matcher(input.glob, checked.path, true));\n const found = files.length === 0 ? { lines: \"\", notes: \"\" } : await grepFiles(deps, input, [...files].sort(), signal);\n if (\"result\" in found) return found.result;\n const cut = listing.cut ? \"\\n[the file listing was cut, so some files were not searched]\" : \"\";\n const notes = `${found.notes}${cut}${listing.warning}`;\n if (found.tooLong !== undefined)\n return textResult(`${tooLongSentence(checked.path, input.pattern, found.tooLong)}${notes}`);\n if (found.lines === \"\") return textResult(`No line under ${checked.path} matches ${input.pattern}.${notes}`);\n return textResult(`${found.lines.trimEnd()}${notes}`);\n}\n\n/** The `grep` tool. */\nexport function grepTool(deps: SearchDeps): AnyTool {\n return defineTool<GrepInput>({\n name: \"grep\",\n description: BUILTIN_TOOL_DEFAULTS.grep.description,\n inputSchema: {\n type: \"object\",\n properties: {\n pattern: { type: \"string\", minLength: 1, description: \"The extended regular expression to find.\" },\n path: { type: \"string\", description: \"The file or folder to search. Default the workspace root.\" },\n glob: { type: \"string\", description: \"Only files that match this glob, such as `*.ts`.\" },\n ignore_case: { type: \"boolean\", description: \"Match without regard to case.\" },\n },\n required: [\"pattern\"],\n additionalProperties: false,\n },\n firstParty: true,\n annotations: { readOnlyHint: true },\n resourceKey: () => WORKSPACE_KEY,\n execute: (input, ctx) => grep(deps, input, ctx.signal),\n }) as AnyTool;\n}\n"]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** The tool registry's named error: a `HarnessError` with the code `duplicate_tool` and the name that collided. */
|
|
2
|
+
import { HarnessError } from "../errors.js";
|
|
3
|
+
/**
|
|
4
|
+
* Thrown by `register()` when a registry already holds a tool, or an alias, by that name. An extension that means to
|
|
5
|
+
* replace a built-in passes `override: true`. An MCP tool whose name needs cleaning gets a hash in its name, and this
|
|
6
|
+
* error is for a final name that is still taken.
|
|
7
|
+
*/
|
|
8
|
+
export declare class DuplicateToolError extends HarnessError {
|
|
9
|
+
readonly name = "DuplicateToolError";
|
|
10
|
+
/** The canonical name or alias that is already taken. */
|
|
11
|
+
readonly toolName: string;
|
|
12
|
+
constructor(toolName: string, why: string);
|
|
13
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** The tool registry's named error: a `HarnessError` with the code `duplicate_tool` and the name that collided. */
|
|
2
|
+
import { HarnessError } from "../errors.js";
|
|
3
|
+
/**
|
|
4
|
+
* Thrown by `register()` when a registry already holds a tool, or an alias, by that name. An extension that means to
|
|
5
|
+
* replace a built-in passes `override: true`. An MCP tool whose name needs cleaning gets a hash in its name, and this
|
|
6
|
+
* error is for a final name that is still taken.
|
|
7
|
+
*/
|
|
8
|
+
export class DuplicateToolError extends HarnessError {
|
|
9
|
+
name = "DuplicateToolError";
|
|
10
|
+
/** The canonical name or alias that is already taken. */
|
|
11
|
+
toolName;
|
|
12
|
+
constructor(toolName, why) {
|
|
13
|
+
super("duplicate_tool", `the tool name "${toolName}" is already registered: ${why}`);
|
|
14
|
+
this.toolName = toolName;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/tools/errors.ts"],"names":[],"mappings":"AAAA,mHAAmH;AACnH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAE5C;;;;GAIG;AACH,MAAM,OAAO,kBAAmB,SAAQ,YAAY;IAChC,IAAI,GAAG,oBAAoB,CAAC;IAC9C,yDAAyD;IAChD,QAAQ,CAAS;IAE1B,YAAY,QAAgB,EAAE,GAAW;QACvC,KAAK,CAAC,gBAAgB,EAAE,kBAAkB,QAAQ,4BAA4B,GAAG,EAAE,CAAC,CAAC;QACrF,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,CAAC;CACF","sourcesContent":["/** The tool registry's named error: a `HarnessError` with the code `duplicate_tool` and the name that collided. */\nimport { HarnessError } from \"../errors.js\";\n\n/**\n * Thrown by `register()` when a registry already holds a tool, or an alias, by that name. An extension that means to\n * replace a built-in passes `override: true`. An MCP tool whose name needs cleaning gets a hash in its name, and this\n * error is for a final name that is still taken.\n */\nexport class DuplicateToolError extends HarnessError {\n override readonly name = \"DuplicateToolError\";\n /** The canonical name or alias that is already taken. */\n readonly toolName: string;\n\n constructor(toolName: string, why: string) {\n super(\"duplicate_tool\", `the tool name \"${toolName}\" is already registered: ${why}`);\n this.toolName = toolName;\n }\n}\n"]}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@buildanagent/harness/tools`: the tool registry, which names, defers and wraps the tools of every source, the
|
|
3
|
+
* tool search that activates deferred ones, and the built-in tools, which reach files, commands and the web only
|
|
4
|
+
* through a sandbox and an egress proxy.
|
|
5
|
+
*/
|
|
6
|
+
export { type BuiltinToolsOptions, builtinTools } from "./builtins/builtins.js";
|
|
7
|
+
export { BUILTIN_TOOL_DEFAULTS, BUILTIN_TOOLS_HASH } from "./builtins/descriptions.js";
|
|
8
|
+
export type { FetchProxy } from "./builtins/fetch.js";
|
|
9
|
+
export { DuplicateToolError } from "./errors.js";
|
|
10
|
+
export { createToolRegistry } from "./registry.js";
|
|
11
|
+
export { type ToolSearchOptions, toolSearchInterceptors, toolSearchTool } from "./tool-search.js";
|
|
12
|
+
export type { ApprovalReuse, HostPattern, OutputTrust, PreambleOptions, RegisteredTool, ToolExposure, ToolRegistration, ToolRegistry, ToolSource, ToolWrapper, } from "./types.js";
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@buildanagent/harness/tools`: the tool registry, which names, defers and wraps the tools of every source, the
|
|
3
|
+
* tool search that activates deferred ones, and the built-in tools, which reach files, commands and the web only
|
|
4
|
+
* through a sandbox and an egress proxy.
|
|
5
|
+
*/
|
|
6
|
+
export { builtinTools } from "./builtins/builtins.js";
|
|
7
|
+
export { BUILTIN_TOOL_DEFAULTS, BUILTIN_TOOLS_HASH } from "./builtins/descriptions.js";
|
|
8
|
+
export { DuplicateToolError } from "./errors.js";
|
|
9
|
+
export { createToolRegistry } from "./registry.js";
|
|
10
|
+
export { toolSearchInterceptors, toolSearchTool } from "./tool-search.js";
|
|
11
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/tools/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAA4B,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAChF,OAAO,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAEvF,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,EAA0B,sBAAsB,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC","sourcesContent":["/**\n * `@buildanagent/harness/tools`: the tool registry, which names, defers and wraps the tools of every source, the\n * tool search that activates deferred ones, and the built-in tools, which reach files, commands and the web only\n * through a sandbox and an egress proxy.\n */\nexport { type BuiltinToolsOptions, builtinTools } from \"./builtins/builtins.js\";\nexport { BUILTIN_TOOL_DEFAULTS, BUILTIN_TOOLS_HASH } from \"./builtins/descriptions.js\";\nexport type { FetchProxy } from \"./builtins/fetch.js\";\nexport { DuplicateToolError } from \"./errors.js\";\nexport { createToolRegistry } from \"./registry.js\";\nexport { type ToolSearchOptions, toolSearchInterceptors, toolSearchTool } from \"./tool-search.js\";\nexport type {\n ApprovalReuse,\n HostPattern,\n OutputTrust,\n PreambleOptions,\n RegisteredTool,\n ToolExposure,\n ToolRegistration,\n ToolRegistry,\n ToolSource,\n ToolWrapper,\n} from \"./types.js\";\n"]}
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `createToolRegistry()`: one registry for the tools of every source. It names each tool once, at registration, refuses
|
|
3
|
+
* duplicates, sets exposure per source, and hands the run its definitions in an order that does not move.
|
|
4
|
+
*/
|
|
5
|
+
import { estimateInputTokens, isCanonicalName } from "@buildanagent/gateway";
|
|
6
|
+
import { defineTool } from "@buildanagent/sdk";
|
|
7
|
+
import { HarnessError } from "../errors.js";
|
|
8
|
+
import { DuplicateToolError } from "./errors.js";
|
|
9
|
+
const MAX_NAME = 64;
|
|
10
|
+
const PATTERNS = ["in_process", "client_request"];
|
|
11
|
+
const EXPOSURES = ["direct", "deferred", "hidden"];
|
|
12
|
+
const TRUSTS = ["trusted", "untrusted"];
|
|
13
|
+
const REUSES = ["sticky", "group", "both", "none"];
|
|
14
|
+
const PLAIN_SOURCES = ["builtin", "extension", "client"];
|
|
15
|
+
function invalid(why) {
|
|
16
|
+
throw new HarnessError("invalid_tool_registration", `a tool registration ${why}`);
|
|
17
|
+
}
|
|
18
|
+
function checkOneOf(field, value, allowed) {
|
|
19
|
+
if (value !== undefined && !(typeof value === "string" && allowed.includes(value))) {
|
|
20
|
+
invalid(`has a ${field} of ${JSON.stringify(value)}, which must be one of ${allowed.join(", ")}`);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function isMcp(source) {
|
|
24
|
+
return source.startsWith("mcp:");
|
|
25
|
+
}
|
|
26
|
+
function checkSource(source) {
|
|
27
|
+
const ok = typeof source === "string" &&
|
|
28
|
+
(PLAIN_SOURCES.includes(source) || (source.startsWith("mcp:") && source.length > "mcp:".length));
|
|
29
|
+
if (!ok)
|
|
30
|
+
invalid(`has a source of ${JSON.stringify(source)}, which must be builtin, extension, client or mcp:<server>`);
|
|
31
|
+
}
|
|
32
|
+
/** Checks a registration's fields, so a typo fails here and not when a request is built. */
|
|
33
|
+
function check(tool) {
|
|
34
|
+
if (typeof tool?.name !== "string" || tool.name === "")
|
|
35
|
+
invalid("needs a non-empty name");
|
|
36
|
+
checkSource(tool.source);
|
|
37
|
+
checkOneOf("pattern", tool.pattern, PATTERNS);
|
|
38
|
+
checkOneOf("exposure", tool.exposure, EXPOSURES);
|
|
39
|
+
checkOneOf("outputTrust", tool.outputTrust, TRUSTS);
|
|
40
|
+
checkOneOf("approvalReuse", tool.approvalReuse, REUSES);
|
|
41
|
+
for (const [field, value] of [
|
|
42
|
+
["remoteAgent", tool.remoteAgent],
|
|
43
|
+
["override", tool.override],
|
|
44
|
+
]) {
|
|
45
|
+
if (value !== undefined && typeof value !== "boolean")
|
|
46
|
+
invalid(`has a ${field} that is not true or false`);
|
|
47
|
+
}
|
|
48
|
+
if (tool.alias !== undefined && (typeof tool.alias !== "string" || tool.alias === ""))
|
|
49
|
+
invalid("has a blank alias");
|
|
50
|
+
if (typeof tool.definition?.execute !== "function") {
|
|
51
|
+
invalid("needs a definition from defineTool(), whose execute is a function");
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/** Checks the definition as the run will see it, under the canonical name, since an MCP tool's own name is cleaned. */
|
|
55
|
+
function checkDefinition(definition, canonicalName) {
|
|
56
|
+
try {
|
|
57
|
+
defineTool({ ...definition, name: canonicalName });
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
invalid(`has a definition that defineTool() refuses: ${error instanceof Error ? error.message : String(error)}`);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
// FNV-1a, 32 bits, as 8 hex digits: deterministic on every runtime and synchronous, which a collision suffix needs. It
|
|
64
|
+
// tells names apart and guards nothing, so it is not a cryptographic hash.
|
|
65
|
+
function shortHash(text) {
|
|
66
|
+
let hash = 0x811c9dc5;
|
|
67
|
+
for (const char of text) {
|
|
68
|
+
hash = Math.imul(hash ^ (char.codePointAt(0) ?? 0), 0x01000193) >>> 0;
|
|
69
|
+
}
|
|
70
|
+
return hash.toString(16).padStart(8, "0");
|
|
71
|
+
}
|
|
72
|
+
const clean = (part) => part.replace(/[^A-Za-z0-9_-]/g, "_");
|
|
73
|
+
// A part with letters, digits and hyphens, joined by single underscores, can't be mistaken for two parts by the `__` between them.
|
|
74
|
+
const PLAIN_PART = /^[A-Za-z0-9-]+(?:_[A-Za-z0-9-]+)*$/;
|
|
75
|
+
/** `base`, or `base` cut to fit with `_<hash>` after it, when a suffix is needed or the name is too long. */
|
|
76
|
+
function suffixed(base, source, name) {
|
|
77
|
+
const suffix = `_${shortHash(`${source}\u0000${name}`)}`;
|
|
78
|
+
return `${base.slice(0, MAX_NAME - suffix.length)}${suffix}`;
|
|
79
|
+
}
|
|
80
|
+
function trustOf(registration) {
|
|
81
|
+
if (registration.outputTrust !== undefined)
|
|
82
|
+
return registration.outputTrust;
|
|
83
|
+
return isMcp(registration.source) || registration.remoteAgent === true ? "untrusted" : "trusted";
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* A wire description of a tool, enough to count its tokens. A Standard Schema describes itself, and `register()`
|
|
87
|
+
* refuses one that can't, so the empty object schema is only a fallback the types require.
|
|
88
|
+
*/
|
|
89
|
+
function wireOf(definition) {
|
|
90
|
+
const schema = definition.inputSchema;
|
|
91
|
+
const standard = schema["~standard"];
|
|
92
|
+
const described = standard === undefined ? schema : standard.jsonSchema?.input?.({ target: "draft-2020-12" });
|
|
93
|
+
const inputSchema = described ?? { type: "object" };
|
|
94
|
+
return {
|
|
95
|
+
name: definition.name,
|
|
96
|
+
description: definition.description,
|
|
97
|
+
inputSchema: inputSchema,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
class Registry {
|
|
101
|
+
#entries = [];
|
|
102
|
+
#exposures = new Map();
|
|
103
|
+
register(registration) {
|
|
104
|
+
check(registration);
|
|
105
|
+
const { name, source } = registration;
|
|
106
|
+
const canonicalName = this.#canonicalFor(registration);
|
|
107
|
+
checkDefinition(registration.definition, canonicalName);
|
|
108
|
+
const existing = this.#entries.findIndex((entry) => entry.tool.canonicalName === canonicalName);
|
|
109
|
+
const replaces = existing >= 0 ? this.#entries[existing] : undefined;
|
|
110
|
+
if (replaces !== undefined && !this.#mayReplace(registration, replaces)) {
|
|
111
|
+
throw new DuplicateToolError(canonicalName, `${replaces.tool.source} already holds it`);
|
|
112
|
+
}
|
|
113
|
+
this.#checkNameAgainstAliases(canonicalName, replaces);
|
|
114
|
+
this.#checkAlias(registration.alias, canonicalName, replaces);
|
|
115
|
+
const tool = {
|
|
116
|
+
canonicalName,
|
|
117
|
+
name,
|
|
118
|
+
...(registration.alias === undefined ? {} : { alias: registration.alias }),
|
|
119
|
+
source,
|
|
120
|
+
pattern: (registration.pattern ?? "in_process"),
|
|
121
|
+
exposure: registration.exposure ?? this.#exposures.get(source) ?? (isMcp(source) ? "deferred" : "direct"),
|
|
122
|
+
outputTrust: trustOf(registration),
|
|
123
|
+
approvalReuse: (registration.approvalReuse ?? "both"),
|
|
124
|
+
remoteAgent: registration.remoteAgent === true,
|
|
125
|
+
definition: registration.definition,
|
|
126
|
+
};
|
|
127
|
+
if (replaces === undefined)
|
|
128
|
+
this.#entries.push({ tool, name });
|
|
129
|
+
else
|
|
130
|
+
this.#entries[existing] = { tool, name };
|
|
131
|
+
return tool;
|
|
132
|
+
}
|
|
133
|
+
registerAll(registrations) {
|
|
134
|
+
if (!Array.isArray(registrations))
|
|
135
|
+
invalid("list needs to be an array");
|
|
136
|
+
// `register()` changes only the entry list, so a copy of it is the whole state to put back.
|
|
137
|
+
const before = [...this.#entries];
|
|
138
|
+
try {
|
|
139
|
+
return registrations.map((registration) => this.register(registration));
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
this.#entries.splice(0, this.#entries.length, ...before);
|
|
143
|
+
throw error;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
get(name) {
|
|
147
|
+
const byName = this.#entries.find((entry) => entry.tool.canonicalName === name);
|
|
148
|
+
return (byName ?? this.#entries.find((entry) => entry.tool.alias === name))?.tool;
|
|
149
|
+
}
|
|
150
|
+
list() {
|
|
151
|
+
return this.#entries.map((entry) => entry.tool);
|
|
152
|
+
}
|
|
153
|
+
setExposure(source, exposure) {
|
|
154
|
+
checkSource(source);
|
|
155
|
+
checkOneOf("exposure", exposure, EXPOSURES);
|
|
156
|
+
this.#exposures.set(source, exposure);
|
|
157
|
+
this.#entries.forEach((entry, index) => {
|
|
158
|
+
if (entry.tool.source === source)
|
|
159
|
+
this.#entries[index] = { ...entry, tool: { ...entry.tool, exposure } };
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
definitions(wrap, hostContext) {
|
|
163
|
+
if (wrap !== undefined && typeof wrap !== "function")
|
|
164
|
+
invalid("needs a wrapper that is a function");
|
|
165
|
+
return this.#entries.map(({ tool }) => {
|
|
166
|
+
const wrapped = wrap === undefined ? tool.definition : wrap(tool, hostContext);
|
|
167
|
+
// The registry has the last word on the name and the exposure, so a wrapper can't rename or expose a tool.
|
|
168
|
+
return defineTool({ ...wrapped, name: tool.canonicalName, exposure: tool.exposure });
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
activeTools(activated) {
|
|
172
|
+
return this.#entries
|
|
173
|
+
.filter(({ tool }) => tool.exposure === "direct" || activated.has(tool.canonicalName))
|
|
174
|
+
.map(({ tool }) => tool.canonicalName);
|
|
175
|
+
}
|
|
176
|
+
preambleTokens(options = {}) {
|
|
177
|
+
const tools = this.#entries.filter(({ tool }) => tool.exposure === "direct");
|
|
178
|
+
const wire = tools.map(({ tool }) => wireOf({ ...tool.definition, name: tool.canonicalName }));
|
|
179
|
+
return estimateInputTokens({ system: options.system ?? "", messages: [], tools: wire });
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* The canonical name: an MCP tool is namespaced, and any other name is used as it is. A part that needs cleaning, or
|
|
183
|
+
* holds `__` and so could blur the namespace, adds a hash of the source and name, so a name depends on its tool and
|
|
184
|
+
* never on what was registered before it.
|
|
185
|
+
*/
|
|
186
|
+
#canonicalFor({ name, alias, source }) {
|
|
187
|
+
if (!isMcp(source)) {
|
|
188
|
+
for (const taken of [name, alias]) {
|
|
189
|
+
if (taken?.toLowerCase().startsWith("mcp__")) {
|
|
190
|
+
invalid(`has the name or alias ${JSON.stringify(taken)}, and only an MCP tool takes the mcp__ prefix`);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
if (!isCanonicalName(name)) {
|
|
194
|
+
invalid(`has the name ${JSON.stringify(name)}, which must be 1 to 64 characters from A-Z, a-z, 0-9, _ and -`);
|
|
195
|
+
}
|
|
196
|
+
return name;
|
|
197
|
+
}
|
|
198
|
+
const server = source.slice("mcp:".length);
|
|
199
|
+
const base = `mcp__${clean(server)}__${clean(name)}`;
|
|
200
|
+
const plain = PLAIN_PART.test(server) && PLAIN_PART.test(name) && base.length <= MAX_NAME;
|
|
201
|
+
const canonical = plain ? base : suffixed(base, source, name);
|
|
202
|
+
const taken = this.#entries.find((entry) => entry.tool.canonicalName === canonical);
|
|
203
|
+
if (taken === undefined)
|
|
204
|
+
return canonical;
|
|
205
|
+
const same = taken.tool.source === source && taken.name === name;
|
|
206
|
+
const why = same ? `${source} already registered a tool named "${name}"` : `${taken.tool.source} already holds it`;
|
|
207
|
+
throw new DuplicateToolError(canonical, why);
|
|
208
|
+
}
|
|
209
|
+
/** Whether `registration` may take the place of `existing`: only a non-MCP tool that says so, over a built-in. */
|
|
210
|
+
#mayReplace(registration, existing) {
|
|
211
|
+
return registration.override === true && existing.tool.source === "builtin" && registration.source !== "builtin";
|
|
212
|
+
}
|
|
213
|
+
/** A new canonical name may not equal another tool's alias, or `get()` would find the wrong tool. */
|
|
214
|
+
#checkNameAgainstAliases(canonicalName, replaces) {
|
|
215
|
+
const clash = this.#entries.find((entry) => entry !== replaces && entry.tool.alias === canonicalName);
|
|
216
|
+
if (clash !== undefined)
|
|
217
|
+
throw new DuplicateToolError(canonicalName, `${clash.tool.canonicalName} uses it as an alias`);
|
|
218
|
+
}
|
|
219
|
+
/** An alias is unique among aliases, and no tool's canonical name is another tool's alias. */
|
|
220
|
+
#checkAlias(alias, canonicalName, replaces) {
|
|
221
|
+
if (alias === undefined)
|
|
222
|
+
return;
|
|
223
|
+
const others = this.#entries.filter((entry) => entry !== replaces);
|
|
224
|
+
const clash = others.find((entry) => entry.tool.canonicalName === alias || entry.tool.alias === alias);
|
|
225
|
+
if (clash !== undefined || alias === canonicalName) {
|
|
226
|
+
throw new DuplicateToolError(alias, "another tool already uses it as a name or an alias");
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
/** Creates an empty registry. */
|
|
231
|
+
export function createToolRegistry() {
|
|
232
|
+
return new Registry();
|
|
233
|
+
}
|
|
234
|
+
//# sourceMappingURL=registry.js.map
|