@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.
Files changed (364) hide show
  1. package/LICENSE +54 -0
  2. package/LICENSE-APACHE +202 -0
  3. package/LICENSE-MIT +21 -0
  4. package/README.md +716 -2
  5. package/dist/ablation.d.ts +2 -0
  6. package/dist/ablation.js +3 -0
  7. package/dist/ablation.js.map +1 -0
  8. package/dist/completion/check.d.ts +64 -0
  9. package/dist/completion/check.js +152 -0
  10. package/dist/completion/check.js.map +1 -0
  11. package/dist/completion/checks.d.ts +45 -0
  12. package/dist/completion/checks.js +173 -0
  13. package/dist/completion/checks.js.map +1 -0
  14. package/dist/completion/flags.d.ts +25 -0
  15. package/dist/completion/flags.js +87 -0
  16. package/dist/completion/flags.js.map +1 -0
  17. package/dist/completion/index.d.ts +8 -0
  18. package/dist/completion/index.js +9 -0
  19. package/dist/completion/index.js.map +1 -0
  20. package/dist/completion/snapshot.d.ts +33 -0
  21. package/dist/completion/snapshot.js +83 -0
  22. package/dist/completion/snapshot.js.map +1 -0
  23. package/dist/context/cap.d.ts +32 -0
  24. package/dist/context/cap.js +50 -0
  25. package/dist/context/cap.js.map +1 -0
  26. package/dist/context/estimate.d.ts +18 -0
  27. package/dist/context/estimate.js +20 -0
  28. package/dist/context/estimate.js.map +1 -0
  29. package/dist/context/file-spill.d.ts +5 -0
  30. package/dist/context/file-spill.js +25 -0
  31. package/dist/context/file-spill.js.map +1 -0
  32. package/dist/context/index.d.ts +10 -0
  33. package/dist/context/index.js +10 -0
  34. package/dist/context/index.js.map +1 -0
  35. package/dist/context/mask.d.ts +27 -0
  36. package/dist/context/mask.js +71 -0
  37. package/dist/context/mask.js.map +1 -0
  38. package/dist/context/mid-turn.d.ts +40 -0
  39. package/dist/context/mid-turn.js +82 -0
  40. package/dist/context/mid-turn.js.map +1 -0
  41. package/dist/context/policy.d.ts +9 -0
  42. package/dist/context/policy.js +140 -0
  43. package/dist/context/policy.js.map +1 -0
  44. package/dist/context/spill-ledger.d.ts +25 -0
  45. package/dist/context/spill-ledger.js +54 -0
  46. package/dist/context/spill-ledger.js.map +1 -0
  47. package/dist/context/spill.d.ts +6 -0
  48. package/dist/context/spill.js +14 -0
  49. package/dist/context/spill.js.map +1 -0
  50. package/dist/context/summarize.d.ts +53 -0
  51. package/dist/context/summarize.js +204 -0
  52. package/dist/context/summarize.js.map +1 -0
  53. package/dist/context/summary-template.d.ts +29 -0
  54. package/dist/context/summary-template.js +69 -0
  55. package/dist/context/summary-template.js.map +1 -0
  56. package/dist/context/types.d.ts +150 -0
  57. package/dist/context/types.js +2 -0
  58. package/dist/context/types.js.map +1 -0
  59. package/dist/context/write-cap.d.ts +19 -0
  60. package/dist/context/write-cap.js +41 -0
  61. package/dist/context/write-cap.js.map +1 -0
  62. package/dist/create-harness.d.ts +7 -0
  63. package/dist/create-harness.js +21 -0
  64. package/dist/create-harness.js.map +1 -0
  65. package/dist/credentials/addresses.d.ts +14 -0
  66. package/dist/credentials/addresses.js +144 -0
  67. package/dist/credentials/addresses.js.map +1 -0
  68. package/dist/credentials/allowlist.d.ts +34 -0
  69. package/dist/credentials/allowlist.js +77 -0
  70. package/dist/credentials/allowlist.js.map +1 -0
  71. package/dist/credentials/egress-proxy.d.ts +70 -0
  72. package/dist/credentials/egress-proxy.js +482 -0
  73. package/dist/credentials/egress-proxy.js.map +1 -0
  74. package/dist/credentials/index.d.ts +9 -0
  75. package/dist/credentials/index.js +10 -0
  76. package/dist/credentials/index.js.map +1 -0
  77. package/dist/credentials/scrub.d.ts +16 -0
  78. package/dist/credentials/scrub.js +93 -0
  79. package/dist/credentials/scrub.js.map +1 -0
  80. package/dist/errors.d.ts +56 -0
  81. package/dist/errors.js +63 -0
  82. package/dist/errors.js.map +1 -0
  83. package/dist/extensions/compose.d.ts +27 -0
  84. package/dist/extensions/compose.js +83 -0
  85. package/dist/extensions/compose.js.map +1 -0
  86. package/dist/extensions/context-files-node.d.ts +28 -0
  87. package/dist/extensions/context-files-node.js +74 -0
  88. package/dist/extensions/context-files-node.js.map +1 -0
  89. package/dist/extensions/context-files.d.ts +68 -0
  90. package/dist/extensions/context-files.js +214 -0
  91. package/dist/extensions/context-files.js.map +1 -0
  92. package/dist/extensions/digest.d.ts +6 -0
  93. package/dist/extensions/digest.js +68 -0
  94. package/dist/extensions/digest.js.map +1 -0
  95. package/dist/extensions/index.d.ts +10 -0
  96. package/dist/extensions/index.js +10 -0
  97. package/dist/extensions/index.js.map +1 -0
  98. package/dist/extensions/load.d.ts +42 -0
  99. package/dist/extensions/load.js +211 -0
  100. package/dist/extensions/load.js.map +1 -0
  101. package/dist/extensions/lock.d.ts +8 -0
  102. package/dist/extensions/lock.js +95 -0
  103. package/dist/extensions/lock.js.map +1 -0
  104. package/dist/extensions/node.d.ts +10 -0
  105. package/dist/extensions/node.js +11 -0
  106. package/dist/extensions/node.js.map +1 -0
  107. package/dist/extensions/project-dirs.d.ts +24 -0
  108. package/dist/extensions/project-dirs.js +97 -0
  109. package/dist/extensions/project-dirs.js.map +1 -0
  110. package/dist/extensions/skills-node.d.ts +34 -0
  111. package/dist/extensions/skills-node.js +123 -0
  112. package/dist/extensions/skills-node.js.map +1 -0
  113. package/dist/extensions/skills.d.ts +51 -0
  114. package/dist/extensions/skills.js +175 -0
  115. package/dist/extensions/skills.js.map +1 -0
  116. package/dist/extensions/trust-file.d.ts +3 -0
  117. package/dist/extensions/trust-file.js +62 -0
  118. package/dist/extensions/trust-file.js.map +1 -0
  119. package/dist/extensions/trust-store-node.d.ts +10 -0
  120. package/dist/extensions/trust-store-node.js +33 -0
  121. package/dist/extensions/trust-store-node.js.map +1 -0
  122. package/dist/extensions/types.d.ts +42 -0
  123. package/dist/extensions/types.js +2 -0
  124. package/dist/extensions/types.js.map +1 -0
  125. package/dist/harness.d.ts +156 -0
  126. package/dist/harness.js +2 -0
  127. package/dist/harness.js.map +1 -0
  128. package/dist/index.d.ts +4 -0
  129. package/dist/index.js +5 -0
  130. package/dist/index.js.map +1 -0
  131. package/dist/mcp/connection.d.ts +22 -0
  132. package/dist/mcp/connection.js +267 -0
  133. package/dist/mcp/connection.js.map +1 -0
  134. package/dist/mcp/content.d.ts +27 -0
  135. package/dist/mcp/content.js +177 -0
  136. package/dist/mcp/content.js.map +1 -0
  137. package/dist/mcp/errors.d.ts +19 -0
  138. package/dist/mcp/errors.js +21 -0
  139. package/dist/mcp/errors.js.map +1 -0
  140. package/dist/mcp/index.d.ts +10 -0
  141. package/dist/mcp/index.js +10 -0
  142. package/dist/mcp/index.js.map +1 -0
  143. package/dist/mcp/manager.d.ts +7 -0
  144. package/dist/mcp/manager.js +173 -0
  145. package/dist/mcp/manager.js.map +1 -0
  146. package/dist/mcp/record.d.ts +7 -0
  147. package/dist/mcp/record.js +20 -0
  148. package/dist/mcp/record.js.map +1 -0
  149. package/dist/mcp/stdio.d.ts +39 -0
  150. package/dist/mcp/stdio.js +382 -0
  151. package/dist/mcp/stdio.js.map +1 -0
  152. package/dist/mcp/types.d.ts +172 -0
  153. package/dist/mcp/types.js +2 -0
  154. package/dist/mcp/types.js.map +1 -0
  155. package/dist/memory/index.d.ts +2 -0
  156. package/dist/memory/index.js +3 -0
  157. package/dist/memory/index.js.map +1 -0
  158. package/dist/permissions/default-rules.d.ts +7 -0
  159. package/dist/permissions/default-rules.js +42 -0
  160. package/dist/permissions/default-rules.js.map +1 -0
  161. package/dist/permissions/errors.d.ts +11 -0
  162. package/dist/permissions/errors.js +14 -0
  163. package/dist/permissions/errors.js.map +1 -0
  164. package/dist/permissions/index.d.ts +9 -0
  165. package/dist/permissions/index.js +9 -0
  166. package/dist/permissions/index.js.map +1 -0
  167. package/dist/permissions/match.d.ts +33 -0
  168. package/dist/permissions/match.js +287 -0
  169. package/dist/permissions/match.js.map +1 -0
  170. package/dist/permissions/pipeline.d.ts +9 -0
  171. package/dist/permissions/pipeline.js +235 -0
  172. package/dist/permissions/pipeline.js.map +1 -0
  173. package/dist/permissions/rules.d.ts +22 -0
  174. package/dist/permissions/rules.js +74 -0
  175. package/dist/permissions/rules.js.map +1 -0
  176. package/dist/permissions/shadow.d.ts +5 -0
  177. package/dist/permissions/shadow.js +22 -0
  178. package/dist/permissions/shadow.js.map +1 -0
  179. package/dist/permissions/types.d.ts +104 -0
  180. package/dist/permissions/types.js +2 -0
  181. package/dist/permissions/types.js.map +1 -0
  182. package/dist/sandbox/base.d.ts +35 -0
  183. package/dist/sandbox/base.js +60 -0
  184. package/dist/sandbox/base.js.map +1 -0
  185. package/dist/sandbox/docker/index.d.ts +35 -0
  186. package/dist/sandbox/docker/index.js +448 -0
  187. package/dist/sandbox/docker/index.js.map +1 -0
  188. package/dist/sandbox/errors.d.ts +16 -0
  189. package/dist/sandbox/errors.js +22 -0
  190. package/dist/sandbox/errors.js.map +1 -0
  191. package/dist/sandbox/host-files.d.ts +63 -0
  192. package/dist/sandbox/host-files.js +248 -0
  193. package/dist/sandbox/host-files.js.map +1 -0
  194. package/dist/sandbox/index.d.ts +8 -0
  195. package/dist/sandbox/index.js +8 -0
  196. package/dist/sandbox/index.js.map +1 -0
  197. package/dist/sandbox/none.d.ts +17 -0
  198. package/dist/sandbox/none.js +108 -0
  199. package/dist/sandbox/none.js.map +1 -0
  200. package/dist/sandbox/process.d.ts +61 -0
  201. package/dist/sandbox/process.js +253 -0
  202. package/dist/sandbox/process.js.map +1 -0
  203. package/dist/sandbox/spawn-env.d.ts +20 -0
  204. package/dist/sandbox/spawn-env.js +128 -0
  205. package/dist/sandbox/spawn-env.js.map +1 -0
  206. package/dist/sandbox/srt/index.d.ts +35 -0
  207. package/dist/sandbox/srt/index.js +264 -0
  208. package/dist/sandbox/srt/index.js.map +1 -0
  209. package/dist/sandbox/srt/settings.d.ts +48 -0
  210. package/dist/sandbox/srt/settings.js +31 -0
  211. package/dist/sandbox/srt/settings.js.map +1 -0
  212. package/dist/sandbox/types.d.ts +88 -0
  213. package/dist/sandbox/types.js +6 -0
  214. package/dist/sandbox/types.js.map +1 -0
  215. package/dist/server/answers.d.ts +16 -0
  216. package/dist/server/answers.js +43 -0
  217. package/dist/server/answers.js.map +1 -0
  218. package/dist/server/connection.d.ts +99 -0
  219. package/dist/server/connection.js +309 -0
  220. package/dist/server/connection.js.map +1 -0
  221. package/dist/server/dispatcher.d.ts +86 -0
  222. package/dist/server/dispatcher.js +800 -0
  223. package/dist/server/dispatcher.js.map +1 -0
  224. package/dist/server/index.d.ts +13 -0
  225. package/dist/server/index.js +12 -0
  226. package/dist/server/index.js.map +1 -0
  227. package/dist/server/local-transport.d.ts +44 -0
  228. package/dist/server/local-transport.js +103 -0
  229. package/dist/server/local-transport.js.map +1 -0
  230. package/dist/server/outbox.d.ts +31 -0
  231. package/dist/server/outbox.js +130 -0
  232. package/dist/server/outbox.js.map +1 -0
  233. package/dist/server/params.d.ts +25 -0
  234. package/dist/server/params.js +112 -0
  235. package/dist/server/params.js.map +1 -0
  236. package/dist/server/protocol.schema.json +2448 -0
  237. package/dist/server/rpc-session.d.ts +43 -0
  238. package/dist/server/rpc-session.js +167 -0
  239. package/dist/server/rpc-session.js.map +1 -0
  240. package/dist/server/stdio-streams.d.ts +67 -0
  241. package/dist/server/stdio-streams.js +218 -0
  242. package/dist/server/stdio-streams.js.map +1 -0
  243. package/dist/server/stdio.d.ts +59 -0
  244. package/dist/server/stdio.js +189 -0
  245. package/dist/server/stdio.js.map +1 -0
  246. package/dist/server/websocket.d.ts +106 -0
  247. package/dist/server/websocket.js +327 -0
  248. package/dist/server/websocket.js.map +1 -0
  249. package/dist/session/approvals.d.ts +81 -0
  250. package/dist/session/approvals.js +217 -0
  251. package/dist/session/approvals.js.map +1 -0
  252. package/dist/session/code-call-log.d.ts +42 -0
  253. package/dist/session/code-call-log.js +63 -0
  254. package/dist/session/code-call-log.js.map +1 -0
  255. package/dist/session/code-call-result.d.ts +19 -0
  256. package/dist/session/code-call-result.js +95 -0
  257. package/dist/session/code-call-result.js.map +1 -0
  258. package/dist/session/code-call.d.ts +49 -0
  259. package/dist/session/code-call.js +345 -0
  260. package/dist/session/code-call.js.map +1 -0
  261. package/dist/session/effect-scope.d.ts +11 -0
  262. package/dist/session/effect-scope.js +10 -0
  263. package/dist/session/effect-scope.js.map +1 -0
  264. package/dist/session/errors.d.ts +19 -0
  265. package/dist/session/errors.js +27 -0
  266. package/dist/session/errors.js.map +1 -0
  267. package/dist/session/file-index.d.ts +8 -0
  268. package/dist/session/file-index.js +70 -0
  269. package/dist/session/file-index.js.map +1 -0
  270. package/dist/session/file-key-store.d.ts +16 -0
  271. package/dist/session/file-key-store.js +169 -0
  272. package/dist/session/file-key-store.js.map +1 -0
  273. package/dist/session/file-lock.d.ts +52 -0
  274. package/dist/session/file-lock.js +324 -0
  275. package/dist/session/file-lock.js.map +1 -0
  276. package/dist/session/index.d.ts +22 -0
  277. package/dist/session/index.js +20 -0
  278. package/dist/session/index.js.map +1 -0
  279. package/dist/session/jsonl-store.d.ts +37 -0
  280. package/dist/session/jsonl-store.js +386 -0
  281. package/dist/session/jsonl-store.js.map +1 -0
  282. package/dist/session/jsonl.d.ts +9 -0
  283. package/dist/session/jsonl.js +10 -0
  284. package/dist/session/jsonl.js.map +1 -0
  285. package/dist/session/lock.d.ts +19 -0
  286. package/dist/session/lock.js +2 -0
  287. package/dist/session/lock.js.map +1 -0
  288. package/dist/session/memory-store.d.ts +12 -0
  289. package/dist/session/memory-store.js +60 -0
  290. package/dist/session/memory-store.js.map +1 -0
  291. package/dist/session/migrate.d.ts +41 -0
  292. package/dist/session/migrate.js +86 -0
  293. package/dist/session/migrate.js.map +1 -0
  294. package/dist/session/pointer.d.ts +15 -0
  295. package/dist/session/pointer.js +22 -0
  296. package/dist/session/pointer.js.map +1 -0
  297. package/dist/session/rebuild.d.ts +53 -0
  298. package/dist/session/rebuild.js +230 -0
  299. package/dist/session/rebuild.js.map +1 -0
  300. package/dist/session/resume.d.ts +26 -0
  301. package/dist/session/resume.js +128 -0
  302. package/dist/session/resume.js.map +1 -0
  303. package/dist/session/retention.d.ts +97 -0
  304. package/dist/session/retention.js +702 -0
  305. package/dist/session/retention.js.map +1 -0
  306. package/dist/session/runner.d.ts +156 -0
  307. package/dist/session/runner.js +656 -0
  308. package/dist/session/runner.js.map +1 -0
  309. package/dist/session/scheduler.d.ts +47 -0
  310. package/dist/session/scheduler.js +85 -0
  311. package/dist/session/scheduler.js.map +1 -0
  312. package/dist/session/secret-key-store.d.ts +47 -0
  313. package/dist/session/secret-key-store.js +79 -0
  314. package/dist/session/secret-key-store.js.map +1 -0
  315. package/dist/session/session.d.ts +106 -0
  316. package/dist/session/session.js +353 -0
  317. package/dist/session/session.js.map +1 -0
  318. package/dist/session/sticky.d.ts +48 -0
  319. package/dist/session/sticky.js +232 -0
  320. package/dist/session/sticky.js.map +1 -0
  321. package/dist/session/store.d.ts +108 -0
  322. package/dist/session/store.js +163 -0
  323. package/dist/session/store.js.map +1 -0
  324. package/dist/telemetry/index.d.ts +2 -0
  325. package/dist/telemetry/index.js +3 -0
  326. package/dist/telemetry/index.js.map +1 -0
  327. package/dist/testing/fake-sandbox.d.ts +34 -0
  328. package/dist/testing/fake-sandbox.js +221 -0
  329. package/dist/testing/fake-sandbox.js.map +1 -0
  330. package/dist/testing/index.d.ts +10 -0
  331. package/dist/testing/index.js +11 -0
  332. package/dist/testing/index.js.map +1 -0
  333. package/dist/testing/key-store-conformance.d.ts +22 -0
  334. package/dist/testing/key-store-conformance.js +97 -0
  335. package/dist/testing/key-store-conformance.js.map +1 -0
  336. package/dist/testing/run-cases.d.ts +21 -0
  337. package/dist/testing/run-cases.js +20 -0
  338. package/dist/testing/run-cases.js.map +1 -0
  339. package/dist/testing/sandbox-conformance.d.ts +64 -0
  340. package/dist/testing/sandbox-conformance.js +361 -0
  341. package/dist/testing/sandbox-conformance.js.map +1 -0
  342. package/dist/testing/scheduler-conformance.d.ts +32 -0
  343. package/dist/testing/scheduler-conformance.js +72 -0
  344. package/dist/testing/scheduler-conformance.js.map +1 -0
  345. package/dist/testing/store-conformance.d.ts +21 -0
  346. package/dist/testing/store-conformance.js +320 -0
  347. package/dist/testing/store-conformance.js.map +1 -0
  348. package/dist/tools/errors.d.ts +13 -0
  349. package/dist/tools/errors.js +17 -0
  350. package/dist/tools/errors.js.map +1 -0
  351. package/dist/tools/index.d.ts +8 -0
  352. package/dist/tools/index.js +8 -0
  353. package/dist/tools/index.js.map +1 -0
  354. package/dist/tools/registry.d.ts +3 -0
  355. package/dist/tools/registry.js +234 -0
  356. package/dist/tools/registry.js.map +1 -0
  357. package/dist/tools/tool-search.d.ts +30 -0
  358. package/dist/tools/tool-search.js +118 -0
  359. package/dist/tools/tool-search.js.map +1 -0
  360. package/dist/tools/types.d.ts +106 -0
  361. package/dist/tools/types.js +2 -0
  362. package/dist/tools/types.js.map +1 -0
  363. package/llms.txt +435 -0
  364. package/package.json +118 -3
@@ -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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry.js","sourceRoot":"","sources":["../../src/tools/registry.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAiB,MAAM,uBAAuB,CAAC;AAC5F,OAAO,EAAE,UAAU,EAAuB,MAAM,mBAAmB,CAAC;AACpE,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAcjD,MAAM,QAAQ,GAAG,EAAE,CAAC;AACpB,MAAM,QAAQ,GAAsB,CAAC,YAAY,EAAE,gBAAgB,CAAC,CAAC;AACrE,MAAM,SAAS,GAAsB,CAAC,QAAQ,EAAE,UAAU,EAAE,QAAQ,CAAC,CAAC;AACtE,MAAM,MAAM,GAAsB,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;AAC3D,MAAM,MAAM,GAAsB,CAAC,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AACtE,MAAM,aAAa,GAAsB,CAAC,SAAS,EAAE,WAAW,EAAE,QAAQ,CAAC,CAAC;AAE5E,SAA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AAE,OAAO;QAChC,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,QAAQ,CAAC,CAAC;QACnE,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,aAAa,KAAK,KAAK,IAAI,KAAK,CAAC,IAAI,CAAC,KAAK,KAAK,KAAK,CAAC,CAAC;QACvG,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,aAAa,EAAE,CAAC;YACnD,MAAM,IAAI,kBAAkB,CAAC,KAAK,EAAE,oDAAoD,CAAC,CAAC;QAC5F,CAAC;IACH,CAAC;CACF;AAED,iCAAiC;AACjC,MAAM,UAAU,kBAAkB;IAChC,OAAO,IAAI,QAAQ,EAAE,CAAC;AACxB,CAAC","sourcesContent":["/**\n * `createToolRegistry()`: one registry for the tools of every source. It names each tool once, at registration, refuses\n * duplicates, sets exposure per source, and hands the run its definitions in an order that does not move.\n */\nimport { estimateInputTokens, isCanonicalName, type WireTool } from \"@buildanagent/gateway\";\nimport { defineTool, type ToolDefinition } from \"@buildanagent/sdk\";\nimport { HarnessError } from \"../errors.js\";\nimport { DuplicateToolError } from \"./errors.js\";\nimport 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\nconst MAX_NAME = 64;\nconst PATTERNS: readonly string[] = [\"in_process\", \"client_request\"];\nconst EXPOSURES: readonly string[] = [\"direct\", \"deferred\", \"hidden\"];\nconst TRUSTS: readonly string[] = [\"trusted\", \"untrusted\"];\nconst REUSES: readonly string[] = [\"sticky\", \"group\", \"both\", \"none\"];\nconst PLAIN_SOURCES: readonly string[] = [\"builtin\", \"extension\", \"client\"];\n\nfunction invalid(why: string): never {\n throw new HarnessError(\"invalid_tool_registration\", `a tool registration ${why}`);\n}\n\nfunction checkOneOf(field: string, value: unknown, allowed: readonly string[]): void {\n if (value !== undefined && !(typeof value === \"string\" && allowed.includes(value))) {\n invalid(`has a ${field} of ${JSON.stringify(value)}, which must be one of ${allowed.join(\", \")}`);\n }\n}\n\nfunction isMcp(source: ToolSource): source is `mcp:${string}` {\n return source.startsWith(\"mcp:\");\n}\n\nfunction checkSource(source: unknown): asserts source is ToolSource {\n const ok =\n typeof source === \"string\" &&\n (PLAIN_SOURCES.includes(source) || (source.startsWith(\"mcp:\") && source.length > \"mcp:\".length));\n if (!ok)\n invalid(`has a source of ${JSON.stringify(source)}, which must be builtin, extension, client or mcp:<server>`);\n}\n\n/** Checks a registration's fields, so a typo fails here and not when a request is built. */\nfunction check(tool: ToolRegistration): void {\n if (typeof tool?.name !== \"string\" || tool.name === \"\") invalid(\"needs a non-empty name\");\n checkSource(tool.source);\n checkOneOf(\"pattern\", tool.pattern, PATTERNS);\n checkOneOf(\"exposure\", tool.exposure, EXPOSURES);\n checkOneOf(\"outputTrust\", tool.outputTrust, TRUSTS);\n checkOneOf(\"approvalReuse\", tool.approvalReuse, REUSES);\n for (const [field, value] of [\n [\"remoteAgent\", tool.remoteAgent],\n [\"override\", tool.override],\n ] as const) {\n if (value !== undefined && typeof value !== \"boolean\") invalid(`has a ${field} that is not true or false`);\n }\n if (tool.alias !== undefined && (typeof tool.alias !== \"string\" || tool.alias === \"\")) invalid(\"has a blank alias\");\n if (typeof (tool.definition as Partial<ToolDefinition> | undefined)?.execute !== \"function\") {\n invalid(\"needs a definition from defineTool(), whose execute is a function\");\n }\n}\n\n/** Checks the definition as the run will see it, under the canonical name, since an MCP tool's own name is cleaned. */\nfunction checkDefinition(definition: ToolDefinition<unknown, unknown, unknown>, canonicalName: string): void {\n try {\n defineTool({ ...definition, name: canonicalName });\n } catch (error) {\n invalid(`has a definition that defineTool() refuses: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\n// FNV-1a, 32 bits, as 8 hex digits: deterministic on every runtime and synchronous, which a collision suffix needs. It\n// tells names apart and guards nothing, so it is not a cryptographic hash.\nfunction shortHash(text: string): string {\n let hash = 0x811c9dc5;\n for (const char of text) {\n hash = Math.imul(hash ^ (char.codePointAt(0) ?? 0), 0x01000193) >>> 0;\n }\n return hash.toString(16).padStart(8, \"0\");\n}\n\nconst clean = (part: string): string => part.replace(/[^A-Za-z0-9_-]/g, \"_\");\n// A part with letters, digits and hyphens, joined by single underscores, can't be mistaken for two parts by the `__` between them.\nconst PLAIN_PART = /^[A-Za-z0-9-]+(?:_[A-Za-z0-9-]+)*$/;\n\n/** `base`, or `base` cut to fit with `_<hash>` after it, when a suffix is needed or the name is too long. */\nfunction suffixed(base: string, source: string, name: string): string {\n const suffix = `_${shortHash(`${source}\\u0000${name}`)}`;\n return `${base.slice(0, MAX_NAME - suffix.length)}${suffix}`;\n}\n\ninterface Entry {\n tool: RegisteredTool;\n name: string;\n}\n\nfunction trustOf(registration: ToolRegistration): OutputTrust {\n if (registration.outputTrust !== undefined) return registration.outputTrust;\n return isMcp(registration.source) || registration.remoteAgent === true ? \"untrusted\" : \"trusted\";\n}\n\n/**\n * A wire description of a tool, enough to count its tokens. A Standard Schema describes itself, and `register()`\n * refuses one that can't, so the empty object schema is only a fallback the types require.\n */\nfunction wireOf(definition: ToolDefinition<unknown, unknown, unknown>): WireTool {\n const schema = definition.inputSchema as unknown as Record<string, unknown>;\n const standard = schema[\"~standard\"] as { jsonSchema?: { input?(options: { target: string }): unknown } } | undefined;\n const described = standard === undefined ? schema : standard.jsonSchema?.input?.({ target: \"draft-2020-12\" });\n const inputSchema = described ?? { type: \"object\" };\n return {\n name: definition.name,\n description: definition.description,\n inputSchema: inputSchema as Record<string, unknown>,\n };\n}\n\nclass Registry implements ToolRegistry {\n readonly #entries: Entry[] = [];\n readonly #exposures = new Map<string, ToolExposure>();\n\n register(registration: ToolRegistration): RegisteredTool {\n check(registration);\n const { name, source } = registration;\n const canonicalName = this.#canonicalFor(registration);\n checkDefinition(registration.definition, canonicalName);\n const existing = this.#entries.findIndex((entry) => entry.tool.canonicalName === canonicalName);\n const replaces = existing >= 0 ? this.#entries[existing] : undefined;\n if (replaces !== undefined && !this.#mayReplace(registration, replaces)) {\n throw new DuplicateToolError(canonicalName, `${replaces.tool.source} already holds it`);\n }\n this.#checkNameAgainstAliases(canonicalName, replaces);\n this.#checkAlias(registration.alias, canonicalName, replaces);\n const tool: RegisteredTool = {\n canonicalName,\n name,\n ...(registration.alias === undefined ? {} : { alias: registration.alias }),\n source,\n pattern: (registration.pattern ?? \"in_process\") as HostPattern,\n exposure: registration.exposure ?? this.#exposures.get(source) ?? (isMcp(source) ? \"deferred\" : \"direct\"),\n outputTrust: trustOf(registration),\n approvalReuse: (registration.approvalReuse ?? \"both\") as ApprovalReuse,\n remoteAgent: registration.remoteAgent === true,\n definition: registration.definition,\n };\n if (replaces === undefined) this.#entries.push({ tool, name });\n else this.#entries[existing] = { tool, name };\n return tool;\n }\n\n registerAll(registrations: readonly ToolRegistration[]): RegisteredTool[] {\n if (!Array.isArray(registrations)) invalid(\"list needs to be an array\");\n // `register()` changes only the entry list, so a copy of it is the whole state to put back.\n const before = [...this.#entries];\n try {\n return registrations.map((registration) => this.register(registration));\n } catch (error) {\n this.#entries.splice(0, this.#entries.length, ...before);\n throw error;\n }\n }\n\n get(name: string): RegisteredTool | undefined {\n const byName = this.#entries.find((entry) => entry.tool.canonicalName === name);\n return (byName ?? this.#entries.find((entry) => entry.tool.alias === name))?.tool;\n }\n\n list(): readonly RegisteredTool[] {\n return this.#entries.map((entry) => entry.tool);\n }\n\n setExposure(source: ToolSource, exposure: ToolExposure): void {\n checkSource(source);\n checkOneOf(\"exposure\", exposure, EXPOSURES);\n this.#exposures.set(source, exposure);\n this.#entries.forEach((entry, index) => {\n if (entry.tool.source === source) this.#entries[index] = { ...entry, tool: { ...entry.tool, exposure } };\n });\n }\n\n definitions<H = undefined>(wrap?: ToolWrapper<H>, hostContext?: H): ToolDefinition<unknown, unknown, unknown>[] {\n if (wrap !== undefined && typeof wrap !== \"function\") invalid(\"needs a wrapper that is a function\");\n return this.#entries.map(({ tool }) => {\n const wrapped = wrap === undefined ? tool.definition : wrap(tool, hostContext as H);\n // The registry has the last word on the name and the exposure, so a wrapper can't rename or expose a tool.\n return defineTool<unknown, unknown, unknown>({ ...wrapped, name: tool.canonicalName, exposure: tool.exposure });\n });\n }\n\n activeTools(activated: ReadonlySet<string>): string[] {\n return this.#entries\n .filter(({ tool }) => tool.exposure === \"direct\" || activated.has(tool.canonicalName))\n .map(({ tool }) => tool.canonicalName);\n }\n\n preambleTokens(options: PreambleOptions = {}): number {\n const tools = this.#entries.filter(({ tool }) => tool.exposure === \"direct\");\n const wire = tools.map(({ tool }) => wireOf({ ...tool.definition, name: tool.canonicalName }));\n return estimateInputTokens({ system: options.system ?? \"\", messages: [], tools: wire });\n }\n\n /**\n * The canonical name: an MCP tool is namespaced, and any other name is used as it is. A part that needs cleaning, or\n * holds `__` and so could blur the namespace, adds a hash of the source and name, so a name depends on its tool and\n * never on what was registered before it.\n */\n #canonicalFor({ name, alias, source }: ToolRegistration): string {\n if (!isMcp(source)) {\n for (const taken of [name, alias]) {\n if (taken?.toLowerCase().startsWith(\"mcp__\")) {\n invalid(`has the name or alias ${JSON.stringify(taken)}, and only an MCP tool takes the mcp__ prefix`);\n }\n }\n if (!isCanonicalName(name)) {\n invalid(`has the name ${JSON.stringify(name)}, which must be 1 to 64 characters from A-Z, a-z, 0-9, _ and -`);\n }\n return name;\n }\n const server = source.slice(\"mcp:\".length);\n const base = `mcp__${clean(server)}__${clean(name)}`;\n const plain = PLAIN_PART.test(server) && PLAIN_PART.test(name) && base.length <= MAX_NAME;\n const canonical = plain ? base : suffixed(base, source, name);\n const taken = this.#entries.find((entry) => entry.tool.canonicalName === canonical);\n if (taken === undefined) return canonical;\n const same = taken.tool.source === source && taken.name === name;\n const why = same ? `${source} already registered a tool named \"${name}\"` : `${taken.tool.source} already holds it`;\n throw new DuplicateToolError(canonical, why);\n }\n\n /** Whether `registration` may take the place of `existing`: only a non-MCP tool that says so, over a built-in. */\n #mayReplace(registration: ToolRegistration, existing: Entry): boolean {\n return registration.override === true && existing.tool.source === \"builtin\" && registration.source !== \"builtin\";\n }\n\n /** A new canonical name may not equal another tool's alias, or `get()` would find the wrong tool. */\n #checkNameAgainstAliases(canonicalName: string, replaces: Entry | undefined): void {\n const clash = this.#entries.find((entry) => entry !== replaces && entry.tool.alias === canonicalName);\n if (clash !== undefined)\n throw new DuplicateToolError(canonicalName, `${clash.tool.canonicalName} uses it as an alias`);\n }\n\n /** An alias is unique among aliases, and no tool's canonical name is another tool's alias. */\n #checkAlias(alias: string | undefined, canonicalName: string, replaces: Entry | undefined): void {\n if (alias === undefined) return;\n const others = this.#entries.filter((entry) => entry !== replaces);\n const clash = others.find((entry) => entry.tool.canonicalName === alias || entry.tool.alias === alias);\n if (clash !== undefined || alias === canonicalName) {\n throw new DuplicateToolError(alias, \"another tool already uses it as a name or an alias\");\n }\n }\n}\n\n/** Creates an empty registry. */\nexport function createToolRegistry(): ToolRegistry {\n return new Registry();\n}\n"]}
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Tool search: how a model finds a deferred tool and has it sent from the next request on. The tool names the matches,
3
+ * and the interceptor turns the names it recorded into `activeTools`, so a deferred tool is absent until it is asked for.
4
+ */
5
+ import type { Interceptors, ToolDefinition } from "@buildanagent/sdk";
6
+ import type { ToolRegistry } from "./types.js";
7
+ /** The options of `toolSearchTool()`. */
8
+ export interface ToolSearchOptions {
9
+ /** Where the tool records the names it activates. Pass the same set to `toolSearchInterceptors()`. */
10
+ readonly activated: Set<string>;
11
+ /** The most tools one search activates. Default 5. */
12
+ readonly maxResults?: number;
13
+ }
14
+ /**
15
+ * The `tool_search` tool: it searches the registry's `deferred` tools by the words of a query, records the best
16
+ * matches in `options.activated` and tells the model their names, plus the descriptions of trusted tools. `hidden`
17
+ * tools are never found, because hiding one means the model should not learn it exists. Results are in registration order among equal scores.
18
+ */
19
+ export declare function toolSearchTool(registry: ToolRegistry, options: ToolSearchOptions): ToolDefinition<{
20
+ query: string;
21
+ }, {
22
+ activated: string[];
23
+ }, unknown>;
24
+ /**
25
+ * The interceptor that sends what tool search activated. Each model call's `activeTools` is the run's tools, plus
26
+ * `tool_search`, plus the activated names the registry holds. Register `toolSearchTool()` in the registry first, then
27
+ * take `registry.definitions()` after the last registration, because the SDK throws when `activeTools` names a tool the
28
+ * run does not hold. Pass the same set to the tool, and a new one for each run.
29
+ */
30
+ export declare function toolSearchInterceptors(registry: ToolRegistry, activated: ReadonlySet<string>): Interceptors;
@@ -0,0 +1,118 @@
1
+ import { HarnessError } from "../errors.js";
2
+ const DEFAULT_MAX_RESULTS = 5;
3
+ // Words that match nearly every description, so they would make every deferred tool a candidate.
4
+ const STOP_WORDS = new Set(["the", "for", "and", "with", "that", "this", "from", "are", "you", "your", "use", "can"]);
5
+ function words(text) {
6
+ return text
7
+ .toLowerCase()
8
+ .split(/[^a-z0-9]+/)
9
+ .filter((word) => word !== "");
10
+ }
11
+ /**
12
+ * How many of the query's words match a word of a tool's name, alias or description. A word matches when one begins
13
+ * with the other, so `issue` finds `issues`, and a word of under three letters, such as `an`, matches nothing.
14
+ */
15
+ function scoreOf(query, haystack) {
16
+ // A repeated word counts once, so repeating one cannot outrank a tool that matches more of what was asked.
17
+ const matches = (word) => word.length >= 3 &&
18
+ !STOP_WORDS.has(word) &&
19
+ haystack.some((have) => have.length >= 3 && !STOP_WORDS.has(have) && (have.startsWith(word) || word.startsWith(have)));
20
+ return new Set(query.filter(matches)).size;
21
+ }
22
+ /**
23
+ * A tool's score for a query. A tool with untrusted output, such as an MCP tool, is scored on its name and alias, and its
24
+ * description adds at most one match, so a server that stuffs a description with keywords can't outrank every tool.
25
+ */
26
+ function scoreFor(wanted, tool) {
27
+ const named = words(`${tool.name} ${tool.alias ?? ""}`);
28
+ const described = words(tool.definition.description);
29
+ if (tool.outputTrust === "trusted")
30
+ return scoreOf(wanted, [...named, ...described]);
31
+ return scoreOf(wanted, named) + Math.min(1, scoreOf(wanted, described));
32
+ }
33
+ /** The best matches, at most `max`, and at most half of them, rounded down but at least one, from one untrusted source. */
34
+ function best(matches, max) {
35
+ const perSource = Math.max(1, Math.floor(max / 2));
36
+ const taken = new Map();
37
+ const kept = [];
38
+ for (const match of matches) {
39
+ if (kept.length === max)
40
+ break;
41
+ const source = match.tool.source;
42
+ if (match.tool.outputTrust === "untrusted") {
43
+ const count = taken.get(source) ?? 0;
44
+ if (count >= perSource)
45
+ continue;
46
+ taken.set(source, count + 1);
47
+ }
48
+ kept.push(match);
49
+ }
50
+ return kept;
51
+ }
52
+ /** One line of the search's result. An untrusted tool's description is the server's text, so only its name is given. */
53
+ function lineOf(tool) {
54
+ if (tool.outputTrust === "trusted")
55
+ return `- ${tool.canonicalName}: ${tool.definition.description}`;
56
+ return `- ${tool.canonicalName} (from ${tool.source}; its own description comes with its definition)`;
57
+ }
58
+ /**
59
+ * The `tool_search` tool: it searches the registry's `deferred` tools by the words of a query, records the best
60
+ * matches in `options.activated` and tells the model their names, plus the descriptions of trusted tools. `hidden`
61
+ * tools are never found, because hiding one means the model should not learn it exists. Results are in registration order among equal scores.
62
+ */
63
+ export function toolSearchTool(registry, options) {
64
+ if (!(options?.activated instanceof Set)) {
65
+ throw new HarnessError("invalid_tool_registration", "toolSearchTool() needs an activated set");
66
+ }
67
+ const max = options.maxResults ?? DEFAULT_MAX_RESULTS;
68
+ if (!Number.isInteger(max) || max < 1) {
69
+ throw new HarnessError("invalid_tool_registration", `toolSearchTool() needs a maxResults of 1 or more, got ${String(max)}`);
70
+ }
71
+ return {
72
+ name: "tool_search",
73
+ description: "Find a tool you do not have yet. Describe what you need in a few words, and the matching tools become available on your next step.",
74
+ inputSchema: {
75
+ type: "object",
76
+ properties: { query: { type: "string", description: "What the tool should do, in a few words." } },
77
+ required: ["query"],
78
+ },
79
+ async execute({ query }) {
80
+ const wanted = words(query);
81
+ const ranked = registry
82
+ .list()
83
+ .filter((tool) => tool.exposure === "deferred")
84
+ // The name it was registered under, not the canonical one, so `mcp` and the server's name match nothing by themselves.
85
+ .map((tool) => ({ tool, score: scoreFor(wanted, tool) }))
86
+ .filter((match) => match.score > 0)
87
+ .sort((a, b) => b.score - a.score);
88
+ const matches = best(ranked, max);
89
+ const activated = matches.map(({ tool }) => tool.canonicalName);
90
+ for (const name of activated)
91
+ options.activated.add(name);
92
+ const text = activated.length === 0
93
+ ? `No tool matches "${query}". Try other words.`
94
+ : `These tools are available on your next step:\n${matches.map(({ tool }) => lineOf(tool)).join("\n")}`;
95
+ return { content: [{ type: "text", text }], structured: { activated } };
96
+ },
97
+ };
98
+ }
99
+ /**
100
+ * The interceptor that sends what tool search activated. Each model call's `activeTools` is the run's tools, plus
101
+ * `tool_search`, plus the activated names the registry holds. Register `toolSearchTool()` in the registry first, then
102
+ * take `registry.definitions()` after the last registration, because the SDK throws when `activeTools` names a tool the
103
+ * run does not hold. Pass the same set to the tool, and a new one for each run.
104
+ */
105
+ export function toolSearchInterceptors(registry, activated) {
106
+ if (!registry.list().some((tool) => tool.canonicalName === "tool_search")) {
107
+ throw new HarnessError("invalid_tool_registration", "toolSearchInterceptors() needs the registry to hold the tool_search tool under that name, because every request sends it by that name");
108
+ }
109
+ return {
110
+ beforeModelCall: ({ context }) => {
111
+ const known = new Set(registry.list().map((tool) => tool.canonicalName));
112
+ const held = [...activated].filter((name) => known.has(name));
113
+ // The search tool is always sent, so a source set to deferred or hidden can't leave the model with no way to find a tool.
114
+ return { activeTools: [...new Set([...context.tools.map((tool) => tool.name), ...held, "tool_search"])] };
115
+ },
116
+ };
117
+ }
118
+ //# sourceMappingURL=tool-search.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-search.js","sourceRoot":"","sources":["../../src/tools/tool-search.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAG5C,MAAM,mBAAmB,GA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AO,EAAE,EAAE,EAAE;YAC/B,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC;YACzE,MAAM,IAAI,GAAG,CAAC,GAAG,SAAS,CAAC,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC;YAC9D,0HAA0H;YAC1H,OAAO,EAAE,WAAW,EAAE,CAAC,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,IAAI,EAAE,aAAa,CAAC,CAAC,CAAC,EAAE,CAAC;QAC5G,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Tool search: how a model finds a deferred tool and has it sent from the next request on. The tool names the matches,\n * and the interceptor turns the names it recorded into `activeTools`, so a deferred tool is absent until it is asked for.\n */\nimport type { Interceptors, ToolDefinition } from \"@buildanagent/sdk\";\nimport { HarnessError } from \"../errors.js\";\nimport type { RegisteredTool, ToolRegistry } from \"./types.js\";\n\nconst DEFAULT_MAX_RESULTS = 5;\n// Words that match nearly every description, so they would make every deferred tool a candidate.\nconst STOP_WORDS = new Set([\"the\", \"for\", \"and\", \"with\", \"that\", \"this\", \"from\", \"are\", \"you\", \"your\", \"use\", \"can\"]);\n\n/** The options of `toolSearchTool()`. */\nexport interface ToolSearchOptions {\n /** Where the tool records the names it activates. Pass the same set to `toolSearchInterceptors()`. */\n readonly activated: Set<string>;\n /** The most tools one search activates. Default 5. */\n readonly maxResults?: number;\n}\n\nfunction words(text: string): string[] {\n return text\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((word) => word !== \"\");\n}\n\n/**\n * How many of the query's words match a word of a tool's name, alias or description. A word matches when one begins\n * with the other, so `issue` finds `issues`, and a word of under three letters, such as `an`, matches nothing.\n */\nfunction scoreOf(query: readonly string[], haystack: readonly string[]): number {\n // A repeated word counts once, so repeating one cannot outrank a tool that matches more of what was asked.\n const matches = (word: string) =>\n word.length >= 3 &&\n !STOP_WORDS.has(word) &&\n haystack.some(\n (have) => have.length >= 3 && !STOP_WORDS.has(have) && (have.startsWith(word) || word.startsWith(have)),\n );\n return new Set(query.filter(matches)).size;\n}\n\n/**\n * A tool's score for a query. A tool with untrusted output, such as an MCP tool, is scored on its name and alias, and its\n * description adds at most one match, so a server that stuffs a description with keywords can't outrank every tool.\n */\nfunction scoreFor(wanted: readonly string[], tool: RegisteredTool): number {\n const named = words(`${tool.name} ${tool.alias ?? \"\"}`);\n const described = words(tool.definition.description);\n if (tool.outputTrust === \"trusted\") return scoreOf(wanted, [...named, ...described]);\n return scoreOf(wanted, named) + Math.min(1, scoreOf(wanted, described));\n}\n\n/** The best matches, at most `max`, and at most half of them, rounded down but at least one, from one untrusted source. */\nfunction best(matches: readonly { tool: RegisteredTool; score: number }[], max: number) {\n const perSource = Math.max(1, Math.floor(max / 2));\n const taken = new Map<string, number>();\n const kept: { tool: RegisteredTool; score: number }[] = [];\n for (const match of matches) {\n if (kept.length === max) break;\n const source = match.tool.source;\n if (match.tool.outputTrust === \"untrusted\") {\n const count = taken.get(source) ?? 0;\n if (count >= perSource) continue;\n taken.set(source, count + 1);\n }\n kept.push(match);\n }\n return kept;\n}\n\n/** One line of the search's result. An untrusted tool's description is the server's text, so only its name is given. */\nfunction lineOf(tool: RegisteredTool): string {\n if (tool.outputTrust === \"trusted\") return `- ${tool.canonicalName}: ${tool.definition.description}`;\n return `- ${tool.canonicalName} (from ${tool.source}; its own description comes with its definition)`;\n}\n\n/**\n * The `tool_search` tool: it searches the registry's `deferred` tools by the words of a query, records the best\n * matches in `options.activated` and tells the model their names, plus the descriptions of trusted tools. `hidden`\n * tools are never found, because hiding one means the model should not learn it exists. Results are in registration order among equal scores.\n */\nexport function toolSearchTool(\n registry: ToolRegistry,\n options: ToolSearchOptions,\n): ToolDefinition<{ query: string }, { activated: string[] }, unknown> {\n if (!(options?.activated instanceof Set)) {\n throw new HarnessError(\"invalid_tool_registration\", \"toolSearchTool() needs an activated set\");\n }\n const max = options.maxResults ?? DEFAULT_MAX_RESULTS;\n if (!Number.isInteger(max) || max < 1) {\n throw new HarnessError(\n \"invalid_tool_registration\",\n `toolSearchTool() needs a maxResults of 1 or more, got ${String(max)}`,\n );\n }\n return {\n name: \"tool_search\",\n description:\n \"Find a tool you do not have yet. Describe what you need in a few words, and the matching tools become available on your next step.\",\n inputSchema: {\n type: \"object\",\n properties: { query: { type: \"string\", description: \"What the tool should do, in a few words.\" } },\n required: [\"query\"],\n },\n async execute({ query }) {\n const wanted = words(query);\n const ranked = registry\n .list()\n .filter((tool) => tool.exposure === \"deferred\")\n // The name it was registered under, not the canonical one, so `mcp` and the server's name match nothing by themselves.\n .map((tool) => ({ tool, score: scoreFor(wanted, tool) }))\n .filter((match) => match.score > 0)\n .sort((a, b) => b.score - a.score);\n const matches = best(ranked, max);\n const activated = matches.map(({ tool }) => tool.canonicalName);\n for (const name of activated) options.activated.add(name);\n const text =\n activated.length === 0\n ? `No tool matches \"${query}\". Try other words.`\n : `These tools are available on your next step:\\n${matches.map(({ tool }) => lineOf(tool)).join(\"\\n\")}`;\n return { content: [{ type: \"text\", text }], structured: { activated } };\n },\n };\n}\n\n/**\n * The interceptor that sends what tool search activated. Each model call's `activeTools` is the run's tools, plus\n * `tool_search`, plus the activated names the registry holds. Register `toolSearchTool()` in the registry first, then\n * take `registry.definitions()` after the last registration, because the SDK throws when `activeTools` names a tool the\n * run does not hold. Pass the same set to the tool, and a new one for each run.\n */\nexport function toolSearchInterceptors(registry: ToolRegistry, activated: ReadonlySet<string>): Interceptors {\n if (!registry.list().some((tool) => tool.canonicalName === \"tool_search\")) {\n throw new HarnessError(\n \"invalid_tool_registration\",\n \"toolSearchInterceptors() needs the registry to hold the tool_search tool under that name, because every request sends it by that name\",\n );\n }\n return {\n beforeModelCall: ({ context }) => {\n const known = new Set(registry.list().map((tool) => tool.canonicalName));\n const held = [...activated].filter((name) => known.has(name));\n // The search tool is always sent, so a source set to deferred or hidden can't leave the model with no way to find a tool.\n return { activeTools: [...new Set([...context.tools.map((tool) => tool.name), ...held, \"tool_search\"])] };\n },\n };\n}\n"]}
@@ -0,0 +1,106 @@
1
+ /**
2
+ * The registry's types: where a tool comes from, how the model reaches it, and what the harness records about it. The
3
+ * registry holds one `RegisteredTool` per tool of every source, so permission rules, tool search and the session log
4
+ * read one description of each.
5
+ */
6
+ import type { ToolDefinition } from "@buildanagent/sdk";
7
+ /** Where a tool comes from: the harness, an in-process extension, one MCP server (`mcp:<server>`) or the client. */
8
+ export type ToolSource = "builtin" | "extension" | `mcp:${string}` | "client";
9
+ /** How a tool's code is reached: in this process, or by asking the client through a `tool/call` server request. */
10
+ export type HostPattern = "in_process" | "client_request";
11
+ /** Whether a request sends the tool: `direct` always, `deferred` once tool search names it, `hidden` only when named. */
12
+ export type ToolExposure = "direct" | "deferred" | "hidden";
13
+ /** Whether a tool's output may carry instructions an attacker wrote. */
14
+ export type OutputTrust = "trusted" | "untrusted";
15
+ /** Which approvals may cover later calls: a sticky one, a grouped one, both, or none, so each call asks. */
16
+ export type ApprovalReuse = "sticky" | "group" | "both" | "none";
17
+ /** A tool as the registry holds it, with its canonical name and every default resolved. */
18
+ export interface RegisteredTool {
19
+ /** The name every request, permission rule and log entry uses. */
20
+ readonly canonicalName: string;
21
+ /** The name the tool was registered under, before any namespace or hash. */
22
+ readonly name: string;
23
+ /** A native or display name that a rule may match too. It never replaces the canonical name. */
24
+ readonly alias?: string;
25
+ readonly source: ToolSource;
26
+ readonly pattern: HostPattern;
27
+ readonly exposure: ToolExposure;
28
+ /** `untrusted` for an MCP tool and a tool that calls a remote agent, `trusted` otherwise, unless the tool declares it. */
29
+ readonly outputTrust: OutputTrust;
30
+ /** Defaults to `both`. */
31
+ readonly approvalReuse: ApprovalReuse;
32
+ /** True for a tool that calls a remote agent, whose replies are untrusted input. */
33
+ readonly remoteAgent: boolean;
34
+ readonly definition: ToolDefinition<unknown, unknown, unknown>;
35
+ }
36
+ /** What `register()` takes: the tool, where it comes from, and any default it overrides. */
37
+ export interface ToolRegistration {
38
+ /** The name the source knows the tool by. For an MCP tool it is the server's tool name, which the registry namespaces. */
39
+ readonly name: string;
40
+ readonly source: ToolSource;
41
+ /** Defaults to `in_process`. */
42
+ readonly pattern?: HostPattern;
43
+ readonly alias?: string;
44
+ /** Defaults to the source's exposure, which is `deferred` for MCP and `direct` for every other source. */
45
+ readonly exposure?: ToolExposure;
46
+ /** Defaults by source, as `RegisteredTool.outputTrust` says. */
47
+ readonly outputTrust?: OutputTrust;
48
+ /** Set it for a tool that calls a remote agent, so its output defaults to `untrusted`. */
49
+ readonly remoteAgent?: boolean;
50
+ readonly approvalReuse?: ApprovalReuse;
51
+ /** Lets an extension, client or other non-MCP tool replace a built-in of the same name. It replaces nothing else. */
52
+ readonly override?: boolean;
53
+ readonly definition: ToolDefinition<unknown, unknown, unknown>;
54
+ }
55
+ /**
56
+ * Wraps one registered tool's definition for a turn: a write cap, shadow mode or a sandbox binding, with the turn's
57
+ * host context. The registry sets the result's name and exposure, so a wrapper can't rename a tool or expose it.
58
+ */
59
+ export type ToolWrapper<H = unknown> = (tool: RegisteredTool, hostContext: H) => ToolDefinition<unknown, unknown, unknown>;
60
+ /** The options of `preambleTokens()`. */
61
+ export interface PreambleOptions {
62
+ /** The system prompt, counted with the tool definitions. Left out, only the tools count. */
63
+ readonly system?: string;
64
+ }
65
+ /** One registry for the tools of every source. */
66
+ export interface ToolRegistry {
67
+ /**
68
+ * Adds a tool and returns it as registered. Throws a `DuplicateToolError` when the canonical name or alias is
69
+ * taken, and a `HarnessError`, code `invalid_tool_registration`, for a name, source or option that is unusable. An
70
+ * MCP tool whose server or tool name needs cleaning, holds `__`, starts or ends with `_`, or runs past 64 characters gets a hash of its source
71
+ * and name in its canonical name, so the name depends on the tool alone. Only a final name that is still taken throws.
72
+ */
73
+ register(tool: ToolRegistration): RegisteredTool;
74
+ /**
75
+ * Registers every tool in the list, or none of them: when one registration throws, the tools registered before it in
76
+ * the list are removed again and the error is thrown. Returns the tools as registered, in the list's order.
77
+ */
78
+ registerAll(tools: readonly ToolRegistration[]): RegisteredTool[];
79
+ /** The tool with this canonical name or alias, or `undefined`. */
80
+ get(name: string): RegisteredTool | undefined;
81
+ /** Every tool, in registration order. A replaced built-in keeps its place. */
82
+ list(): readonly RegisteredTool[];
83
+ /**
84
+ * Sets the exposure of every tool of `source`, and of each one registered after. An explicit exposure on a tool is
85
+ * replaced. A run keeps the exposure `definitions()` gave its tools, so take `definitions()` again for the next run.
86
+ * A `RegisteredTool` that `register()` or `get()` returned earlier is a snapshot, so call `get()` again to read the
87
+ * current exposure.
88
+ */
89
+ setExposure(source: ToolSource, exposure: ToolExposure): void;
90
+ /**
91
+ * The definitions for one turn, for `RunOptions.tools`, in registration order so the cached prefix never moves when
92
+ * a tool activates. Each tool goes through `wrap`, which defaults to the tool's own definition.
93
+ */
94
+ definitions<H = undefined>(wrap?: ToolWrapper<H>, hostContext?: H): ToolDefinition<unknown, unknown, unknown>[];
95
+ /**
96
+ * The registry's own tools a request sends: every `direct` tool and every tool named in `activated`, in
97
+ * registration order, and a name the registry doesn't hold is left out. It is not the complete list when the run also
98
+ * has tools from outside the registry, so `toolSearchInterceptors()` builds its list from the request instead.
99
+ */
100
+ activeTools(activated: ReadonlySet<string>): string[];
101
+ /**
102
+ * An estimate of the tokens a request carries before any message: the system prompt and every `direct` tool. A
103
+ * tool whose schema can't describe itself counts as an empty object schema.
104
+ */
105
+ preambleTokens(options?: PreambleOptions): number;
106
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/tools/types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * The registry's types: where a tool comes from, how the model reaches it, and what the harness records about it. The\n * registry holds one `RegisteredTool` per tool of every source, so permission rules, tool search and the session log\n * read one description of each.\n */\nimport type { ToolDefinition } from \"@buildanagent/sdk\";\n\n/** Where a tool comes from: the harness, an in-process extension, one MCP server (`mcp:<server>`) or the client. */\nexport type ToolSource = \"builtin\" | \"extension\" | `mcp:${string}` | \"client\";\n\n/** How a tool's code is reached: in this process, or by asking the client through a `tool/call` server request. */\nexport type HostPattern = \"in_process\" | \"client_request\";\n\n/** Whether a request sends the tool: `direct` always, `deferred` once tool search names it, `hidden` only when named. */\nexport type ToolExposure = \"direct\" | \"deferred\" | \"hidden\";\n\n/** Whether a tool's output may carry instructions an attacker wrote. */\nexport type OutputTrust = \"trusted\" | \"untrusted\";\n\n/** Which approvals may cover later calls: a sticky one, a grouped one, both, or none, so each call asks. */\nexport type ApprovalReuse = \"sticky\" | \"group\" | \"both\" | \"none\";\n\n/** A tool as the registry holds it, with its canonical name and every default resolved. */\nexport interface RegisteredTool {\n /** The name every request, permission rule and log entry uses. */\n readonly canonicalName: string;\n /** The name the tool was registered under, before any namespace or hash. */\n readonly name: string;\n /** A native or display name that a rule may match too. It never replaces the canonical name. */\n readonly alias?: string;\n readonly source: ToolSource;\n readonly pattern: HostPattern;\n readonly exposure: ToolExposure;\n /** `untrusted` for an MCP tool and a tool that calls a remote agent, `trusted` otherwise, unless the tool declares it. */\n readonly outputTrust: OutputTrust;\n /** Defaults to `both`. */\n readonly approvalReuse: ApprovalReuse;\n /** True for a tool that calls a remote agent, whose replies are untrusted input. */\n readonly remoteAgent: boolean;\n readonly definition: ToolDefinition<unknown, unknown, unknown>;\n}\n\n/** What `register()` takes: the tool, where it comes from, and any default it overrides. */\nexport interface ToolRegistration {\n /** The name the source knows the tool by. For an MCP tool it is the server's tool name, which the registry namespaces. */\n readonly name: string;\n readonly source: ToolSource;\n /** Defaults to `in_process`. */\n readonly pattern?: HostPattern;\n readonly alias?: string;\n /** Defaults to the source's exposure, which is `deferred` for MCP and `direct` for every other source. */\n readonly exposure?: ToolExposure;\n /** Defaults by source, as `RegisteredTool.outputTrust` says. */\n readonly outputTrust?: OutputTrust;\n /** Set it for a tool that calls a remote agent, so its output defaults to `untrusted`. */\n readonly remoteAgent?: boolean;\n readonly approvalReuse?: ApprovalReuse;\n /** Lets an extension, client or other non-MCP tool replace a built-in of the same name. It replaces nothing else. */\n readonly override?: boolean;\n readonly definition: ToolDefinition<unknown, unknown, unknown>;\n}\n\n/**\n * Wraps one registered tool's definition for a turn: a write cap, shadow mode or a sandbox binding, with the turn's\n * host context. The registry sets the result's name and exposure, so a wrapper can't rename a tool or expose it.\n */\nexport type ToolWrapper<H = unknown> = (\n tool: RegisteredTool,\n hostContext: H,\n) => ToolDefinition<unknown, unknown, unknown>;\n\n/** The options of `preambleTokens()`. */\nexport interface PreambleOptions {\n /** The system prompt, counted with the tool definitions. Left out, only the tools count. */\n readonly system?: string;\n}\n\n/** One registry for the tools of every source. */\nexport interface ToolRegistry {\n /**\n * Adds a tool and returns it as registered. Throws a `DuplicateToolError` when the canonical name or alias is\n * taken, and a `HarnessError`, code `invalid_tool_registration`, for a name, source or option that is unusable. An\n * MCP tool whose server or tool name needs cleaning, holds `__`, starts or ends with `_`, or runs past 64 characters gets a hash of its source\n * and name in its canonical name, so the name depends on the tool alone. Only a final name that is still taken throws.\n */\n register(tool: ToolRegistration): RegisteredTool;\n /**\n * Registers every tool in the list, or none of them: when one registration throws, the tools registered before it in\n * the list are removed again and the error is thrown. Returns the tools as registered, in the list's order.\n */\n registerAll(tools: readonly ToolRegistration[]): RegisteredTool[];\n /** The tool with this canonical name or alias, or `undefined`. */\n get(name: string): RegisteredTool | undefined;\n /** Every tool, in registration order. A replaced built-in keeps its place. */\n list(): readonly RegisteredTool[];\n /**\n * Sets the exposure of every tool of `source`, and of each one registered after. An explicit exposure on a tool is\n * replaced. A run keeps the exposure `definitions()` gave its tools, so take `definitions()` again for the next run.\n * A `RegisteredTool` that `register()` or `get()` returned earlier is a snapshot, so call `get()` again to read the\n * current exposure.\n */\n setExposure(source: ToolSource, exposure: ToolExposure): void;\n /**\n * The definitions for one turn, for `RunOptions.tools`, in registration order so the cached prefix never moves when\n * a tool activates. Each tool goes through `wrap`, which defaults to the tool's own definition.\n */\n definitions<H = undefined>(wrap?: ToolWrapper<H>, hostContext?: H): ToolDefinition<unknown, unknown, unknown>[];\n /**\n * The registry's own tools a request sends: every `direct` tool and every tool named in `activated`, in\n * registration order, and a name the registry doesn't hold is left out. It is not the complete list when the run also\n * has tools from outside the registry, so `toolSearchInterceptors()` builds its list from the request instead.\n */\n activeTools(activated: ReadonlySet<string>): string[];\n /**\n * An estimate of the tokens a request carries before any message: the system prompt and every `direct` tool. A\n * tool whose schema can't describe itself counts as an empty object schema.\n */\n preambleTokens(options?: PreambleOptions): number;\n}\n"]}