@buildanagent/harness 0.0.0-bootstrap.0 → 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 +717 -0
  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 +119 -5
@@ -0,0 +1,93 @@
1
+ /** What replaces a secret. */
2
+ export const REDACTED = "[REDACTED]";
3
+ // Fields that give an entry its shape and place in the log. A secret is never one of them, and changing one would break
4
+ // the log, so they are left alone at the top of an entry.
5
+ const STRUCTURAL = new Set(["type", "id", "parentId", "seq", "timestamp", "origin", "formatVersion"]);
6
+ /** The standard and URL-safe base64 of `bytes`, without padding. */
7
+ function base64Of(bytes) {
8
+ let binary = "";
9
+ for (const byte of bytes)
10
+ binary += String.fromCharCode(byte);
11
+ const standard = btoa(binary).replace(/=+$/, "");
12
+ return [standard, standard.replaceAll("+", "-").replaceAll("/", "_")];
13
+ }
14
+ // The fewest base64 characters worth looking for, so a short secret's pieces don't redact ordinary text.
15
+ const MIN_BASE64_PIECE = 8;
16
+ /**
17
+ * The base64 forms of a secret: alone, and as part of longer text. Base64 packs three bytes into four characters, so a
18
+ * secret that follows a prefix such as `user:` encodes differently by its offset in the group. The encodings at all three
19
+ * offsets are kept, trimmed to the groups the secret fills, because the groups at its edges depend on its neighbours.
20
+ */
21
+ function base64Forms(text) {
22
+ const secret = new TextEncoder().encode(text);
23
+ const found = new Set(base64Of(secret));
24
+ for (let offset = 0; offset < 3; offset += 1) {
25
+ const shifted = new Uint8Array(offset + secret.length);
26
+ shifted.set(secret, offset);
27
+ const groups = Math.floor(shifted.length / 3);
28
+ for (const form of base64Of(shifted)) {
29
+ const piece = form.slice(offset === 0 ? 0 : 4, groups * 4);
30
+ if (piece.length >= MIN_BASE64_PIECE)
31
+ found.add(piece);
32
+ }
33
+ }
34
+ return [...found];
35
+ }
36
+ /**
37
+ * The forms a secret takes when something copies it: as written, percent-encoded, escaped inside JSON, and base64 (which
38
+ * is how a Basic authorization header carries one). Longest first, so a secret that contains another is removed whole.
39
+ */
40
+ function forms(secrets) {
41
+ const found = new Set();
42
+ for (const secret of secrets) {
43
+ if (secret === "")
44
+ continue;
45
+ found.add(secret);
46
+ found.add(encodeURIComponent(secret));
47
+ found.add(JSON.stringify(secret).slice(1, -1));
48
+ for (const form of base64Forms(secret))
49
+ found.add(form);
50
+ }
51
+ found.delete("");
52
+ return [...found].sort((a, b) => b.length - a.length);
53
+ }
54
+ function scrubText(text, patterns) {
55
+ let result = text;
56
+ for (const pattern of patterns) {
57
+ if (result.includes(pattern))
58
+ result = result.replaceAll(pattern, REDACTED);
59
+ }
60
+ return result;
61
+ }
62
+ function scrubValue(value, patterns) {
63
+ if (typeof value === "string")
64
+ return scrubText(value, patterns);
65
+ if (Array.isArray(value))
66
+ return value.map((item) => scrubValue(item, patterns));
67
+ if (value !== null && typeof value === "object") {
68
+ const out = {};
69
+ for (const [key, inner] of Object.entries(value))
70
+ out[scrubText(key, patterns)] = scrubValue(inner, patterns);
71
+ return out;
72
+ }
73
+ return value;
74
+ }
75
+ /**
76
+ * Returns a copy of `entry` with every secret replaced by `[REDACTED]`, in every string value and every key, at any depth.
77
+ * A secret is also removed when it appears percent-encoded, JSON-escaped or in base64. The entry's `type`, `id`,
78
+ * `parentId`, `seq`, `timestamp`, `origin` and `formatVersion` are kept as they are. An empty secret is ignored, and a short one redacts
79
+ * every place it occurs, so pass real credentials. The input is not changed.
80
+ */
81
+ export function scrubSecrets(entry, secrets) {
82
+ const patterns = forms(secrets);
83
+ if (patterns.length === 0)
84
+ return { ...entry };
85
+ const out = {};
86
+ for (const [key, value] of Object.entries(entry)) {
87
+ out[STRUCTURAL.has(key) ? key : scrubText(key, patterns)] = STRUCTURAL.has(key)
88
+ ? value
89
+ : scrubValue(value, patterns);
90
+ }
91
+ return out;
92
+ }
93
+ //# sourceMappingURL=scrub.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scrub.js","sourceRoot":"","sources":["../../src/credentials/scrub.ts"],"names":[],"mappings":"AAQA,8BAA8B;AAC9B,MAAM,CAAC,MAAM,QAAQ,GAAG,YAAY,CAAC;AAErC,wHAAwH;AACxH,0DAA0D;AAC1D,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,eAAe,CAAC,CAAC,CAAC;AAEtG,oEAAoE;AACpE,SAAS,QAAQ,CAAC,KAAiB;IACjC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,KAAK,MAAM,IAAI,IAAI,KAAK;QAAE,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;IAC9D,MAAM,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IACjD,OAAO,CAAC,QAAQ,EAAE,QAAQ,CAAC,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC;AACxE,CAAC;AAED,yGAAyG;AACzG,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAE3B;;;;GAIG;AACH,SAAS,WAAW,CAAC,IAAY;IAC/B,MAAM,MAAM,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAC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;QAC9G,OAAO,GAAG,CAAC;IACb,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAAyB,KAAQ,EAAE,OAA0B;IACvF,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,CAAC;IAChC,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,GAAG,KAAK,EAAE,CAAC;IAC/C,MAAM,GAAG,GAA4B,EAAE,CAAC;IACxC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACjD,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC,GAAG,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC;YAC7E,CAAC,CAAC,KAAK;YACP,CAAC,CAAC,UAAU,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;IAClC,CAAC;IACD,OAAO,GAAQ,CAAC;AAClB,CAAC","sourcesContent":["/**\n * `scrubSecrets()`: removes known secrets from a session entry before it is appended, so a credential that reached a\n * tool result, a model message or an error never reaches the log. It is the net under the credential boundary, not the\n * boundary itself: the boundary keeps the secret out of the sandbox, and this catches what a host-side tool wrote\n * anyway. It is pure and portable.\n */\nimport type { SessionEntry } from \"@buildanagent/protocol\";\n\n/** What replaces a secret. */\nexport const REDACTED = \"[REDACTED]\";\n\n// Fields that give an entry its shape and place in the log. A secret is never one of them, and changing one would break\n// the log, so they are left alone at the top of an entry.\nconst STRUCTURAL = new Set([\"type\", \"id\", \"parentId\", \"seq\", \"timestamp\", \"origin\", \"formatVersion\"]);\n\n/** The standard and URL-safe base64 of `bytes`, without padding. */\nfunction base64Of(bytes: Uint8Array): string[] {\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n const standard = btoa(binary).replace(/=+$/, \"\");\n return [standard, standard.replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\")];\n}\n\n// The fewest base64 characters worth looking for, so a short secret's pieces don't redact ordinary text.\nconst MIN_BASE64_PIECE = 8;\n\n/**\n * The base64 forms of a secret: alone, and as part of longer text. Base64 packs three bytes into four characters, so a\n * secret that follows a prefix such as `user:` encodes differently by its offset in the group. The encodings at all three\n * offsets are kept, trimmed to the groups the secret fills, because the groups at its edges depend on its neighbours.\n */\nfunction base64Forms(text: string): string[] {\n const secret = new TextEncoder().encode(text);\n const found = new Set(base64Of(secret));\n for (let offset = 0; offset < 3; offset += 1) {\n const shifted = new Uint8Array(offset + secret.length);\n shifted.set(secret, offset);\n const groups = Math.floor(shifted.length / 3);\n for (const form of base64Of(shifted)) {\n const piece = form.slice(offset === 0 ? 0 : 4, groups * 4);\n if (piece.length >= MIN_BASE64_PIECE) found.add(piece);\n }\n }\n return [...found];\n}\n\n/**\n * The forms a secret takes when something copies it: as written, percent-encoded, escaped inside JSON, and base64 (which\n * is how a Basic authorization header carries one). Longest first, so a secret that contains another is removed whole.\n */\nfunction forms(secrets: readonly string[]): string[] {\n const found = new Set<string>();\n for (const secret of secrets) {\n if (secret === \"\") continue;\n found.add(secret);\n found.add(encodeURIComponent(secret));\n found.add(JSON.stringify(secret).slice(1, -1));\n for (const form of base64Forms(secret)) found.add(form);\n }\n found.delete(\"\");\n return [...found].sort((a, b) => b.length - a.length);\n}\n\nfunction scrubText(text: string, patterns: readonly string[]): string {\n let result = text;\n for (const pattern of patterns) {\n if (result.includes(pattern)) result = result.replaceAll(pattern, REDACTED);\n }\n return result;\n}\n\nfunction scrubValue(value: unknown, patterns: readonly string[]): unknown {\n if (typeof value === \"string\") return scrubText(value, patterns);\n if (Array.isArray(value)) return value.map((item) => scrubValue(item, patterns));\n if (value !== null && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [key, inner] of Object.entries(value)) out[scrubText(key, patterns)] = scrubValue(inner, patterns);\n return out;\n }\n return value;\n}\n\n/**\n * Returns a copy of `entry` with every secret replaced by `[REDACTED]`, in every string value and every key, at any depth.\n * A secret is also removed when it appears percent-encoded, JSON-escaped or in base64. The entry's `type`, `id`,\n * `parentId`, `seq`, `timestamp`, `origin` and `formatVersion` are kept as they are. An empty secret is ignored, and a short one redacts\n * every place it occurs, so pass real credentials. The input is not changed.\n */\nexport function scrubSecrets<T extends SessionEntry>(entry: T, secrets: readonly string[]): T {\n const patterns = forms(secrets);\n if (patterns.length === 0) return { ...entry };\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(entry)) {\n out[STRUCTURAL.has(key) ? key : scrubText(key, patterns)] = STRUCTURAL.has(key)\n ? value\n : scrubValue(value, patterns);\n }\n return out as T;\n}\n"]}
@@ -0,0 +1,56 @@
1
+ /**
2
+ * `HarnessError`: the harness's error for programmer errors and for a sandbox that can't do what it was asked. Two
3
+ * subclasses keep their own names for the cases callers catch by class: `SandboxUnavailableError` and
4
+ * `SandboxDeniedError`, both in `./sandbox`.
5
+ */
6
+ /** Why a `HarnessError` was thrown. */
7
+ export type HarnessErrorCode = "sandbox_unavailable" | "sandbox_denied" | "sandbox_disposed" | "sandbox_not_found" | "sandbox_io_failed" | "egress_denied" | "invalid_egress_options" | "unsafe_sandbox_not_acknowledged" | "invalid_sandbox_options" | "invalid_spawn_env" | "duplicate_tool" | "invalid_tool_registration" | "invalid_permission_config" | "invalid_lock_options" | "session_locked" | "session_read_only" | "entry_not_found" | "unsupported_format" | "invalid_turn_options" | "invalid_context_options" | "invalid_dispatcher_options" | "invalid_transport_options" | "spill_unavailable" | "invalid_extension" | "extension_hash_mismatch" | "approval_not_pending" | "approval_unavailable" | "sticky_refused" | "approval_reuse_refused" | "approver_is_requester" | "approval_refused" | "invalid_code_call" | "invalid_key_store" | "key_store_read_only" | "session_conflict" | "entry_too_large" | "invalid_session_entry" | "invalid_session_key" | "invalid_retention" | "session_corrupt" | "invalid_completion_config" | "invalid_mcp_config" | "mcp_connect_failed" | "mcp_tool_list_refused" | "mcp_call_failed";
8
+ /**
9
+ * Thrown for a mistake in how the harness is called, and for a sandbox that is unavailable or refuses a file operation.
10
+ * `sandbox_unavailable`: a backend can't start (`SandboxUnavailableError`). `sandbox_denied`: the policy refused a file
11
+ * read or write (`SandboxDeniedError`). `sandbox_disposed`: the sandbox was disposed before the call.
12
+ * `sandbox_not_found`: a file to read doesn't exist. `sandbox_io_failed`: a file call failed for a reason that is
13
+ * neither a missing file nor a denial. `unsafe_sandbox_not_acknowledged`: `noneSandbox()` was called without `unsafe:
14
+ * true`. `invalid_sandbox_options`: a sandbox option, manifest or command is unusable. `invalid_spawn_env`:
15
+ * `spawnEnv()` was given a name or value that can't be part of a clean environment. `duplicate_tool`: a tool registry
16
+ * already holds a tool or alias by that name (`DuplicateToolError`). `invalid_tool_registration`: a tool registration
17
+ * or a registry option is unusable, such as a name that breaks the canonical rule or an unknown source.
18
+ * `invalid_permission_config`: an allow rule makes the host callback unreachable (`PermissionConfigError`).
19
+ * `invalid_lock_options`: a file lock was given a lease, renewal interval or host name it can't use. `session_locked`:
20
+ * another writer holds the session. `session_read_only`: a session opened without a lock was asked to write.
21
+ * `entry_not_found`: an entry id is in no file of the session. `unsupported_format`: a session file's format can't be
22
+ * read or migrated, its header names none, or the store can't read it as written. `invalid_turn_options`: a turn's
23
+ * options can't be used, such as a tool allowlist that names a tool the registry lacks, or a hook that changed the
24
+ * model inside a turn.
25
+ * `invalid_context_options`: a context policy's setting can't be used, such as a write cap with no spill store or a mask
26
+ * step of zero. `invalid_dispatcher_options`: a dispatcher's setting can't be used, such as a queue size of zero.
27
+ * `invalid_transport_options`: a transport's setting can't be used, such as a write timeout of zero.
28
+ * `spill_unavailable`: a spill store can't write, such as the file store on a runtime without Node's file
29
+ * system. `invalid_extension`: an extension has no name or version, two share a name, or a project extension's module does not export one. `extension_hash_mismatch`: a project extension's files hash differently from the lock file, or the lock file does not list it. `approval_not_pending`: a resolution names a request that is not waiting.
30
+ * `approval_unavailable`: the harness has no signer, so no approval can be checked. `sticky_refused`: a sticky
31
+ * allowance would cover an interpreter prefix or a secret. `approval_reuse_refused`: the tool's `approvalReuse` forbids
32
+ * a sticky or grouped answer. `approver_is_requester`: the approver is the one who asked. `approval_refused`: a code
33
+ * call's signed request failed its check when it was resolved, so nothing ran and nothing was written.
34
+ * `invalid_code_call`: `Harness.invokeTool()` or a code call's resolution was given something it can't run, such as a
35
+ * tool the registry lacks or a compensation that names no call that ran. `invalid_key_store`: a key
36
+ * file or key secret is unreadable or malformed, or a key file is readable by others. `key_store_read_only`: a key store
37
+ * with no `rotate()` or `prune()` was asked to rotate or prune. `session_conflict`: an append found the log in a state it did
38
+ * not expect (`ConflictError`). `entry_too_large`: an entry is over the store's size bound (`EntryTooLargeError`).
39
+ * `invalid_session_entry`: an entry is not valid or is out of place, such as a first entry that is not a header.
40
+ * `invalid_session_key`: a user or session id the store can't use. `invalid_retention`: a retention period that is not a
41
+ * positive number, or an action other than `archive` and `purge`. `session_corrupt`: a log file has a bad line before
42
+ * its last line. `invalid_completion_config`: `.agents/harness.json` is not JSON, or its `completionChecks` is not a list
43
+ * of commands. `invalid_mcp_config`: an MCP server's configuration can't be used, such as a name outside the allowed
44
+ * characters or two servers with one name. `mcp_connect_failed`: an MCP server did not start, did not finish the
45
+ * handshake in time, or closed before it did (`McpError`). `mcp_tool_list_refused`: an MCP server listed tools the
46
+ * harness refuses, such as two with one name, so none of its tools was registered (`McpError`). `mcp_call_failed`: an
47
+ * MCP tool call ended without a result, because the server closed, timed out, asked for input or answered with an
48
+ * error (`McpError`).
49
+ */
50
+ export declare class HarnessError extends Error {
51
+ readonly name: string;
52
+ readonly code: HarnessErrorCode;
53
+ constructor(code: HarnessErrorCode, message: string, options?: ErrorOptions);
54
+ }
55
+ /** True for a `HarnessError`, including one from another copy of the package. */
56
+ export declare function isHarnessError(error: unknown): error is HarnessError;
package/dist/errors.js ADDED
@@ -0,0 +1,63 @@
1
+ /**
2
+ * `HarnessError`: the harness's error for programmer errors and for a sandbox that can't do what it was asked. Two
3
+ * subclasses keep their own names for the cases callers catch by class: `SandboxUnavailableError` and
4
+ * `SandboxDeniedError`, both in `./sandbox`.
5
+ */
6
+ // A registered symbol, so the guard still works when two copies of the package are bundled.
7
+ const HARNESS_ERROR = Symbol.for("buildanagent.harness.HarnessError");
8
+ /**
9
+ * Thrown for a mistake in how the harness is called, and for a sandbox that is unavailable or refuses a file operation.
10
+ * `sandbox_unavailable`: a backend can't start (`SandboxUnavailableError`). `sandbox_denied`: the policy refused a file
11
+ * read or write (`SandboxDeniedError`). `sandbox_disposed`: the sandbox was disposed before the call.
12
+ * `sandbox_not_found`: a file to read doesn't exist. `sandbox_io_failed`: a file call failed for a reason that is
13
+ * neither a missing file nor a denial. `unsafe_sandbox_not_acknowledged`: `noneSandbox()` was called without `unsafe:
14
+ * true`. `invalid_sandbox_options`: a sandbox option, manifest or command is unusable. `invalid_spawn_env`:
15
+ * `spawnEnv()` was given a name or value that can't be part of a clean environment. `duplicate_tool`: a tool registry
16
+ * already holds a tool or alias by that name (`DuplicateToolError`). `invalid_tool_registration`: a tool registration
17
+ * or a registry option is unusable, such as a name that breaks the canonical rule or an unknown source.
18
+ * `invalid_permission_config`: an allow rule makes the host callback unreachable (`PermissionConfigError`).
19
+ * `invalid_lock_options`: a file lock was given a lease, renewal interval or host name it can't use. `session_locked`:
20
+ * another writer holds the session. `session_read_only`: a session opened without a lock was asked to write.
21
+ * `entry_not_found`: an entry id is in no file of the session. `unsupported_format`: a session file's format can't be
22
+ * read or migrated, its header names none, or the store can't read it as written. `invalid_turn_options`: a turn's
23
+ * options can't be used, such as a tool allowlist that names a tool the registry lacks, or a hook that changed the
24
+ * model inside a turn.
25
+ * `invalid_context_options`: a context policy's setting can't be used, such as a write cap with no spill store or a mask
26
+ * step of zero. `invalid_dispatcher_options`: a dispatcher's setting can't be used, such as a queue size of zero.
27
+ * `invalid_transport_options`: a transport's setting can't be used, such as a write timeout of zero.
28
+ * `spill_unavailable`: a spill store can't write, such as the file store on a runtime without Node's file
29
+ * system. `invalid_extension`: an extension has no name or version, two share a name, or a project extension's module does not export one. `extension_hash_mismatch`: a project extension's files hash differently from the lock file, or the lock file does not list it. `approval_not_pending`: a resolution names a request that is not waiting.
30
+ * `approval_unavailable`: the harness has no signer, so no approval can be checked. `sticky_refused`: a sticky
31
+ * allowance would cover an interpreter prefix or a secret. `approval_reuse_refused`: the tool's `approvalReuse` forbids
32
+ * a sticky or grouped answer. `approver_is_requester`: the approver is the one who asked. `approval_refused`: a code
33
+ * call's signed request failed its check when it was resolved, so nothing ran and nothing was written.
34
+ * `invalid_code_call`: `Harness.invokeTool()` or a code call's resolution was given something it can't run, such as a
35
+ * tool the registry lacks or a compensation that names no call that ran. `invalid_key_store`: a key
36
+ * file or key secret is unreadable or malformed, or a key file is readable by others. `key_store_read_only`: a key store
37
+ * with no `rotate()` or `prune()` was asked to rotate or prune. `session_conflict`: an append found the log in a state it did
38
+ * not expect (`ConflictError`). `entry_too_large`: an entry is over the store's size bound (`EntryTooLargeError`).
39
+ * `invalid_session_entry`: an entry is not valid or is out of place, such as a first entry that is not a header.
40
+ * `invalid_session_key`: a user or session id the store can't use. `invalid_retention`: a retention period that is not a
41
+ * positive number, or an action other than `archive` and `purge`. `session_corrupt`: a log file has a bad line before
42
+ * its last line. `invalid_completion_config`: `.agents/harness.json` is not JSON, or its `completionChecks` is not a list
43
+ * of commands. `invalid_mcp_config`: an MCP server's configuration can't be used, such as a name outside the allowed
44
+ * characters or two servers with one name. `mcp_connect_failed`: an MCP server did not start, did not finish the
45
+ * handshake in time, or closed before it did (`McpError`). `mcp_tool_list_refused`: an MCP server listed tools the
46
+ * harness refuses, such as two with one name, so none of its tools was registered (`McpError`). `mcp_call_failed`: an
47
+ * MCP tool call ended without a result, because the server closed, timed out, asked for input or answered with an
48
+ * error (`McpError`).
49
+ */
50
+ export class HarnessError extends Error {
51
+ name = "HarnessError";
52
+ code;
53
+ constructor(code, message, options) {
54
+ super(message, options);
55
+ this.code = code;
56
+ Object.defineProperty(this, HARNESS_ERROR, { value: true });
57
+ }
58
+ }
59
+ /** True for a `HarnessError`, including one from another copy of the package. */
60
+ export function isHarnessError(error) {
61
+ return typeof error === "object" && error !== null && error[HARNESS_ERROR] === true;
62
+ }
63
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAkDH,4FAA4F;AAC5F,MAAM,aAAa,GAAG,MAAM,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAC;AAEtE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AACH,MAAM,OAAO,YAAa,SAAQ,KAAK;IACnB,IAAI,GAAW,cAAc,CAAC;IACvC,IAAI,CAAmB;IAEhC,YAAY,IAAsB,EAAE,OAAe,EAAE,OAAsB;QACzE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,aAAa,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC9D,CAAC;CACF;AAED,iFAAiF;AACjF,MAAM,UAAU,cAAc,CAAC,KAAc;IAC3C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,aAAa,CAAC,KAAK,IAAI,CAAC;AACnH,CAAC","sourcesContent":["/**\n * `HarnessError`: the harness's error for programmer errors and for a sandbox that can't do what it was asked. Two\n * subclasses keep their own names for the cases callers catch by class: `SandboxUnavailableError` and\n * `SandboxDeniedError`, both in `./sandbox`.\n */\n\n/** Why a `HarnessError` was thrown. */\nexport type HarnessErrorCode =\n | \"sandbox_unavailable\"\n | \"sandbox_denied\"\n | \"sandbox_disposed\"\n | \"sandbox_not_found\"\n | \"sandbox_io_failed\"\n | \"egress_denied\"\n | \"invalid_egress_options\"\n | \"unsafe_sandbox_not_acknowledged\"\n | \"invalid_sandbox_options\"\n | \"invalid_spawn_env\"\n | \"duplicate_tool\"\n | \"invalid_tool_registration\"\n | \"invalid_permission_config\"\n | \"invalid_lock_options\"\n | \"session_locked\"\n | \"session_read_only\"\n | \"entry_not_found\"\n | \"unsupported_format\"\n | \"invalid_turn_options\"\n | \"invalid_context_options\"\n | \"invalid_dispatcher_options\"\n | \"invalid_transport_options\"\n | \"spill_unavailable\"\n | \"invalid_extension\"\n | \"extension_hash_mismatch\"\n | \"approval_not_pending\"\n | \"approval_unavailable\"\n | \"sticky_refused\"\n | \"approval_reuse_refused\"\n | \"approver_is_requester\"\n | \"approval_refused\"\n | \"invalid_code_call\"\n | \"invalid_key_store\"\n | \"key_store_read_only\"\n | \"session_conflict\"\n | \"entry_too_large\"\n | \"invalid_session_entry\"\n | \"invalid_session_key\"\n | \"invalid_retention\"\n | \"session_corrupt\"\n | \"invalid_completion_config\"\n | \"invalid_mcp_config\"\n | \"mcp_connect_failed\"\n | \"mcp_tool_list_refused\"\n | \"mcp_call_failed\";\n\n// A registered symbol, so the guard still works when two copies of the package are bundled.\nconst HARNESS_ERROR = Symbol.for(\"buildanagent.harness.HarnessError\");\n\n/**\n * Thrown for a mistake in how the harness is called, and for a sandbox that is unavailable or refuses a file operation.\n * `sandbox_unavailable`: a backend can't start (`SandboxUnavailableError`). `sandbox_denied`: the policy refused a file\n * read or write (`SandboxDeniedError`). `sandbox_disposed`: the sandbox was disposed before the call.\n * `sandbox_not_found`: a file to read doesn't exist. `sandbox_io_failed`: a file call failed for a reason that is\n * neither a missing file nor a denial. `unsafe_sandbox_not_acknowledged`: `noneSandbox()` was called without `unsafe:\n * true`. `invalid_sandbox_options`: a sandbox option, manifest or command is unusable. `invalid_spawn_env`:\n * `spawnEnv()` was given a name or value that can't be part of a clean environment. `duplicate_tool`: a tool registry\n * already holds a tool or alias by that name (`DuplicateToolError`). `invalid_tool_registration`: a tool registration\n * or a registry option is unusable, such as a name that breaks the canonical rule or an unknown source.\n * `invalid_permission_config`: an allow rule makes the host callback unreachable (`PermissionConfigError`).\n * `invalid_lock_options`: a file lock was given a lease, renewal interval or host name it can't use. `session_locked`:\n * another writer holds the session. `session_read_only`: a session opened without a lock was asked to write.\n * `entry_not_found`: an entry id is in no file of the session. `unsupported_format`: a session file's format can't be\n * read or migrated, its header names none, or the store can't read it as written. `invalid_turn_options`: a turn's\n * options can't be used, such as a tool allowlist that names a tool the registry lacks, or a hook that changed the\n * model inside a turn.\n * `invalid_context_options`: a context policy's setting can't be used, such as a write cap with no spill store or a mask\n * step of zero. `invalid_dispatcher_options`: a dispatcher's setting can't be used, such as a queue size of zero.\n * `invalid_transport_options`: a transport's setting can't be used, such as a write timeout of zero.\n * `spill_unavailable`: a spill store can't write, such as the file store on a runtime without Node's file\n * system. `invalid_extension`: an extension has no name or version, two share a name, or a project extension's module does not export one. `extension_hash_mismatch`: a project extension's files hash differently from the lock file, or the lock file does not list it. `approval_not_pending`: a resolution names a request that is not waiting.\n * `approval_unavailable`: the harness has no signer, so no approval can be checked. `sticky_refused`: a sticky\n * allowance would cover an interpreter prefix or a secret. `approval_reuse_refused`: the tool's `approvalReuse` forbids\n * a sticky or grouped answer. `approver_is_requester`: the approver is the one who asked. `approval_refused`: a code\n * call's signed request failed its check when it was resolved, so nothing ran and nothing was written.\n * `invalid_code_call`: `Harness.invokeTool()` or a code call's resolution was given something it can't run, such as a\n * tool the registry lacks or a compensation that names no call that ran. `invalid_key_store`: a key\n * file or key secret is unreadable or malformed, or a key file is readable by others. `key_store_read_only`: a key store\n * with no `rotate()` or `prune()` was asked to rotate or prune. `session_conflict`: an append found the log in a state it did\n * not expect (`ConflictError`). `entry_too_large`: an entry is over the store's size bound (`EntryTooLargeError`).\n * `invalid_session_entry`: an entry is not valid or is out of place, such as a first entry that is not a header.\n * `invalid_session_key`: a user or session id the store can't use. `invalid_retention`: a retention period that is not a\n * positive number, or an action other than `archive` and `purge`. `session_corrupt`: a log file has a bad line before\n * its last line. `invalid_completion_config`: `.agents/harness.json` is not JSON, or its `completionChecks` is not a list\n * of commands. `invalid_mcp_config`: an MCP server's configuration can't be used, such as a name outside the allowed\n * characters or two servers with one name. `mcp_connect_failed`: an MCP server did not start, did not finish the\n * handshake in time, or closed before it did (`McpError`). `mcp_tool_list_refused`: an MCP server listed tools the\n * harness refuses, such as two with one name, so none of its tools was registered (`McpError`). `mcp_call_failed`: an\n * MCP tool call ended without a result, because the server closed, timed out, asked for input or answered with an\n * error (`McpError`).\n */\nexport class HarnessError extends Error {\n override readonly name: string = \"HarnessError\";\n readonly code: HarnessErrorCode;\n\n constructor(code: HarnessErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n Object.defineProperty(this, HARNESS_ERROR, { value: true });\n }\n}\n\n/** True for a `HarnessError`, including one from another copy of the package. */\nexport function isHarnessError(error: unknown): error is HarnessError {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[HARNESS_ERROR] === true;\n}\n"]}
@@ -0,0 +1,27 @@
1
+ /** Composing extensions: their hooks become one set of interceptors and one list of observers, and their tools register. */
2
+ import { type Interceptors, type Observer } from "@buildanagent/sdk";
3
+ import type { ToolRegistry } from "../tools/types.js";
4
+ import type { Extension, ExtensionLoadedRecord, TrustStore } from "./types.js";
5
+ /**
6
+ * Joins the extensions' interceptors, in the order given, by the SDK's composition rules, and their observers. A
7
+ * hook that throws fails the moment it belongs to, as `composeInterceptors()` says, so one extension's gate that fails
8
+ * closed fails the whole turn's gate closed.
9
+ */
10
+ export declare function composeExtensions(extensions: readonly Extension[]): {
11
+ readonly interceptors: Interceptors;
12
+ readonly observers: readonly Observer[];
13
+ };
14
+ /** Registers every extension's tools in `registry` with source `extension`. A duplicate name is the registry's error. */
15
+ export declare function registerExtensionTools(registry: ToolRegistry, extensions: readonly Extension[]): void;
16
+ /** The digest of `data`, as `sha256:` and hex. A string is hashed as its UTF-8 bytes. */
17
+ export declare function sha256(data: string | Uint8Array): Promise<string>;
18
+ /** The records for extensions written in code: their hash covers the name and version, since there are no files. */
19
+ export declare function recordsOf(extensions: readonly Extension[]): Promise<ExtensionLoadedRecord[]>;
20
+ /**
21
+ * A trust store in memory, for tests and for a host that decides trust itself. It compares paths exactly as given and
22
+ * touches no file system, so it runs on every runtime. The loaders ask a store only about a project's real path, so
23
+ * pass real paths: a folder spelled through a link, such as `/tmp/proj` where `/tmp` links to `/private/tmp`, is not
24
+ * the folder they ask about. On Node, `realPathTrustStore()` in `@buildanagent/harness/extensions/node` resolves each
25
+ * folder to its real path for you.
26
+ */
27
+ export declare function memoryTrustStore(trusted?: readonly string[]): TrustStore;
@@ -0,0 +1,83 @@
1
+ /** Composing extensions: their hooks become one set of interceptors and one list of observers, and their tools register. */
2
+ import { composeInterceptors } from "@buildanagent/sdk";
3
+ import { HarnessError } from "../errors.js";
4
+ /** An extension that is not usable: no name, or the name is taken. */
5
+ function checkNames(extensions) {
6
+ const seen = new Set();
7
+ for (const extension of extensions) {
8
+ if (extension.name.trim() === "" || extension.version.trim() === "") {
9
+ throw new HarnessError("invalid_extension", "an extension needs a name and a version");
10
+ }
11
+ if (seen.has(extension.name)) {
12
+ throw new HarnessError("invalid_extension", `two extensions are named "${extension.name}"`);
13
+ }
14
+ seen.add(extension.name);
15
+ }
16
+ }
17
+ /**
18
+ * Joins the extensions' interceptors, in the order given, by the SDK's composition rules, and their observers. A
19
+ * hook that throws fails the moment it belongs to, as `composeInterceptors()` says, so one extension's gate that fails
20
+ * closed fails the whole turn's gate closed.
21
+ */
22
+ export function composeExtensions(extensions) {
23
+ checkNames(extensions);
24
+ // Only the extensions that have interceptors join: an empty set counts as fail-closed and would undo the others'
25
+ // `continue`, and with none at all the result is empty, so a host that joins it with its own keeps its own setting.
26
+ const sets = extensions.flatMap((extension) => extension.interceptors === undefined ? [] : [extension.interceptors]);
27
+ return {
28
+ interceptors: sets.length === 0 ? {} : composeInterceptors(...sets),
29
+ observers: extensions.flatMap((extension) => extension.observers ?? []),
30
+ };
31
+ }
32
+ /** Registers every extension's tools in `registry` with source `extension`. A duplicate name is the registry's error. */
33
+ export function registerExtensionTools(registry, extensions) {
34
+ checkNames(extensions);
35
+ // Every tool is checked before the first is registered, so a bad one leaves the registry as it was.
36
+ const names = new Set();
37
+ for (const tool of extensions.flatMap((extension) => extension.tools ?? [])) {
38
+ if (typeof tool.name !== "string" || typeof tool.definition !== "object" || tool.definition === null) {
39
+ throw new HarnessError("invalid_extension", "an extension tool needs a name and a definition");
40
+ }
41
+ if (names.has(tool.name) || (registry.get(tool.name) !== undefined && tool.override !== true)) {
42
+ throw new HarnessError("duplicate_tool", `the extension tool "${tool.name}" has the name of a tool that is already registered`);
43
+ }
44
+ names.add(tool.name);
45
+ }
46
+ for (const extension of extensions) {
47
+ for (const tool of extension.tools ?? [])
48
+ registry.register({ ...tool, source: "extension" });
49
+ }
50
+ }
51
+ /** The digest of `data`, as `sha256:` and hex. A string is hashed as its UTF-8 bytes. */
52
+ export async function sha256(data) {
53
+ const bytes = typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data);
54
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
55
+ return `sha256:${[...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
56
+ }
57
+ /** The records for extensions written in code: their hash covers the name and version, since there are no files. */
58
+ export async function recordsOf(extensions) {
59
+ return Promise.all(extensions.map(async (extension) => ({
60
+ name: extension.name,
61
+ tier: "in_process",
62
+ contentHash: await sha256(`${extension.name}@${extension.version}`),
63
+ })));
64
+ }
65
+ /**
66
+ * A trust store in memory, for tests and for a host that decides trust itself. It compares paths exactly as given and
67
+ * touches no file system, so it runs on every runtime. The loaders ask a store only about a project's real path, so
68
+ * pass real paths: a folder spelled through a link, such as `/tmp/proj` where `/tmp` links to `/private/tmp`, is not
69
+ * the folder they ask about. On Node, `realPathTrustStore()` in `@buildanagent/harness/extensions/node` resolves each
70
+ * folder to its real path for you.
71
+ */
72
+ export function memoryTrustStore(trusted = []) {
73
+ const roots = new Set(trusted);
74
+ return {
75
+ async isTrusted(projectRoot) {
76
+ return roots.has(projectRoot);
77
+ },
78
+ async trust(projectRoot) {
79
+ roots.add(projectRoot);
80
+ },
81
+ };
82
+ }
83
+ //# sourceMappingURL=compose.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compose.js","sourceRoot":"","sources":["../../src/extensions/compose.ts"],"names":[],"mappings":"AAAA,4HAA4H;AAC5H,OAAO,EAAE,mBAAmB,EAAoC,MAAM,mBAAmB,CAAC;AAC1F,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAI5C,sEAAsE;AACtE,SAAS,UAAU,CAAC,UAAgC;IAClD,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACnC,IAAI,SAAS,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,IAAI,SAAS,CAAC,OAAO,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC;YACpE,MAAM,IAAI,YAAY,CAAC,mBAAmB,EAAE,yCAAyC,CAAC,CAAC;QACzF,CAAC;QACD,IAAI,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC;YAC7B,MAAM,IAAI,YAAY,CAAC,mBAAmB,EAAE,6BAA6B,SAAS,CAAC,IAAI,GAAG,CAAC,CAAC;QAC9F,CAAC;QACD,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;IAC3B,CAAC;AACH,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,iBAAiB,CAAC,UAAgC;IAIhE,UAAU,CAAC,UAAU,CAAC,CAAC;IACvB,iHAAiH;IACjH,oHAAoH;IACpH,MAAM,IAAI,GAAG,UAAU,CAAC,OAAO,CAAC,CAAC,SAAS,E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;AAED;;;;;;GAMG;AACH,MAAM,UAAU,gBAAgB,CAAC,OAAO,GAAsB,EAAE;IAC9D,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC;IAC/B,OAAO;QACL,KAAK,CAAC,SAAS,CAAC,WAAW;YACzB,OAAO,KAAK,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;QAChC,CAAC;QACD,KAAK,CAAC,KAAK,CAAC,WAAW;YACrB,KAAK,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;QACzB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/** Composing extensions: their hooks become one set of interceptors and one list of observers, and their tools register. */\nimport { composeInterceptors, type Interceptors, type Observer } from \"@buildanagent/sdk\";\nimport { HarnessError } from \"../errors.js\";\nimport type { ToolRegistry } from \"../tools/types.js\";\nimport type { Extension, ExtensionLoadedRecord, TrustStore } from \"./types.js\";\n\n/** An extension that is not usable: no name, or the name is taken. */\nfunction checkNames(extensions: readonly Extension[]): void {\n const seen = new Set<string>();\n for (const extension of extensions) {\n if (extension.name.trim() === \"\" || extension.version.trim() === \"\") {\n throw new HarnessError(\"invalid_extension\", \"an extension needs a name and a version\");\n }\n if (seen.has(extension.name)) {\n throw new HarnessError(\"invalid_extension\", `two extensions are named \"${extension.name}\"`);\n }\n seen.add(extension.name);\n }\n}\n\n/**\n * Joins the extensions' interceptors, in the order given, by the SDK's composition rules, and their observers. A\n * hook that throws fails the moment it belongs to, as `composeInterceptors()` says, so one extension's gate that fails\n * closed fails the whole turn's gate closed.\n */\nexport function composeExtensions(extensions: readonly Extension[]): {\n readonly interceptors: Interceptors;\n readonly observers: readonly Observer[];\n} {\n checkNames(extensions);\n // Only the extensions that have interceptors join: an empty set counts as fail-closed and would undo the others'\n // `continue`, and with none at all the result is empty, so a host that joins it with its own keeps its own setting.\n const sets = extensions.flatMap((extension) =>\n extension.interceptors === undefined ? [] : [extension.interceptors],\n );\n return {\n interceptors: sets.length === 0 ? {} : composeInterceptors(...sets),\n observers: extensions.flatMap((extension) => extension.observers ?? []),\n };\n}\n\n/** Registers every extension's tools in `registry` with source `extension`. A duplicate name is the registry's error. */\nexport function registerExtensionTools(registry: ToolRegistry, extensions: readonly Extension[]): void {\n checkNames(extensions);\n // Every tool is checked before the first is registered, so a bad one leaves the registry as it was.\n const names = new Set<string>();\n for (const tool of extensions.flatMap((extension) => extension.tools ?? [])) {\n if (typeof tool.name !== \"string\" || typeof tool.definition !== \"object\" || tool.definition === null) {\n throw new HarnessError(\"invalid_extension\", \"an extension tool needs a name and a definition\");\n }\n if (names.has(tool.name) || (registry.get(tool.name) !== undefined && tool.override !== true)) {\n throw new HarnessError(\n \"duplicate_tool\",\n `the extension tool \"${tool.name}\" has the name of a tool that is already registered`,\n );\n }\n names.add(tool.name);\n }\n for (const extension of extensions) {\n for (const tool of extension.tools ?? []) registry.register({ ...tool, source: \"extension\" });\n }\n}\n\n/** The digest of `data`, as `sha256:` and hex. A string is hashed as its UTF-8 bytes. */\nexport async function sha256(data: string | Uint8Array): Promise<string> {\n const bytes = typeof data === \"string\" ? new TextEncoder().encode(data) : new Uint8Array(data);\n const digest = await globalThis.crypto.subtle.digest(\"SHA-256\", bytes);\n return `sha256:${[...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\n/** The records for extensions written in code: their hash covers the name and version, since there are no files. */\nexport async function recordsOf(extensions: readonly Extension[]): Promise<ExtensionLoadedRecord[]> {\n return Promise.all(\n extensions.map(async (extension) => ({\n name: extension.name,\n tier: \"in_process\" as const,\n contentHash: await sha256(`${extension.name}@${extension.version}`),\n })),\n );\n}\n\n/**\n * A trust store in memory, for tests and for a host that decides trust itself. It compares paths exactly as given and\n * touches no file system, so it runs on every runtime. The loaders ask a store only about a project's real path, so\n * pass real paths: a folder spelled through a link, such as `/tmp/proj` where `/tmp` links to `/private/tmp`, is not\n * the folder they ask about. On Node, `realPathTrustStore()` in `@buildanagent/harness/extensions/node` resolves each\n * folder to its real path for you.\n */\nexport function memoryTrustStore(trusted: readonly string[] = []): TrustStore {\n const roots = new Set(trusted);\n return {\n async isTrusted(projectRoot) {\n return roots.has(projectRoot);\n },\n async trust(projectRoot) {\n roots.add(projectRoot);\n },\n };\n}\n"]}
@@ -0,0 +1,28 @@
1
+ import { type ContextFile, type PlanSource } from "./context-files.js";
2
+ /** The context files found, and why any were skipped. */
3
+ export interface FoundContextFiles {
4
+ /**
5
+ * Every file read, outermost folder first, so the file nearest the working directory comes last. `AGENTS.md` comes
6
+ * before `CLAUDE.md` in a folder. They are not yet held to `CONTEXT_FILES_MAX_TOTAL_BYTES`: `projectContext()` does
7
+ * that and says in the block which it left out.
8
+ */
9
+ readonly files: ContextFile[];
10
+ /** One line for each file skipped, such as a link that leaves the project. */
11
+ readonly notices: string[];
12
+ }
13
+ /**
14
+ * Reads the `AGENTS.md` and `CLAUDE.md` of `cwd` and of every folder above it up to the repository root (the first
15
+ * folder with a `.git`; with none, `cwd` alone). These files load whether or not the project is trusted, because they
16
+ * are text and not code, and `projectContext()` labels them untrusted. A `CLAUDE.md` that links to the `AGENTS.md`
17
+ * beside it is read once. A link that leaves the project is skipped with a notice, so a cloned repository cannot pull
18
+ * in a file such as `~/.ssh/id_rsa`. Each file is cut at 64 KiB. Every file read is returned, however long they are
19
+ * together: pass them to `projectContext()`, which holds them to 128 KiB, leaves out the outermost first and tells
20
+ * the model in the block which it left out.
21
+ */
22
+ export declare function contextFiles(cwd: string): Promise<FoundContextFiles>;
23
+ /**
24
+ * A plan source that reads `.agents/plan.md` and `.agents/progress.json` under `root` each time it is called. A file
25
+ * that does not exist is left out, a link that leaves `root` is skipped with a notice, and a progress file that is not
26
+ * valid JSON is still shown, with a notice, because a half-written file is what a crash leaves behind.
27
+ */
28
+ export declare function planFileSource(root: string): PlanSource;
@@ -0,0 +1,74 @@
1
+ /** Reading the files `projectContext()` shows the model: `AGENTS.md`, `CLAUDE.md`, and the plan and progress files. Node-only. */
2
+ import { join, resolve } from "node:path";
3
+ import { CONTEXT_FILE_MAX_BYTES, PLAN_FILE, PROGRESS_FILE, } from "./context-files.js";
4
+ import { projectDirs, readProjectFile } from "./project-dirs.js";
5
+ const NAMES = ["AGENTS.md", "CLAUDE.md"];
6
+ /**
7
+ * Reads the `AGENTS.md` and `CLAUDE.md` of `cwd` and of every folder above it up to the repository root (the first
8
+ * folder with a `.git`; with none, `cwd` alone). These files load whether or not the project is trusted, because they
9
+ * are text and not code, and `projectContext()` labels them untrusted. A `CLAUDE.md` that links to the `AGENTS.md`
10
+ * beside it is read once. A link that leaves the project is skipped with a notice, so a cloned repository cannot pull
11
+ * in a file such as `~/.ssh/id_rsa`. Each file is cut at 64 KiB. Every file read is returned, however long they are
12
+ * together: pass them to `projectContext()`, which holds them to 128 KiB, leaves out the outermost first and tells
13
+ * the model in the block which it left out.
14
+ */
15
+ export async function contextFiles(cwd) {
16
+ const dirs = await projectDirs(cwd);
17
+ const root = dirs.at(-1);
18
+ const result = { files: [], notices: [] };
19
+ const seen = new Set();
20
+ for (const dir of [...dirs].reverse()) {
21
+ for (const name of NAMES) {
22
+ const path = join(dir, name);
23
+ const read = await readProjectFile(root, path, CONTEXT_FILE_MAX_BYTES);
24
+ if (read === undefined)
25
+ continue;
26
+ if ("notice" in read) {
27
+ result.notices.push(read.notice);
28
+ continue;
29
+ }
30
+ if (seen.has(read.real))
31
+ continue;
32
+ seen.add(read.real);
33
+ result.files.push({ path, text: read.text, truncated: read.truncated });
34
+ }
35
+ }
36
+ return result;
37
+ }
38
+ /**
39
+ * A plan source that reads `.agents/plan.md` and `.agents/progress.json` under `root` each time it is called. A file
40
+ * that does not exist is left out, a link that leaves `root` is skipped with a notice, and a progress file that is not
41
+ * valid JSON is still shown, with a notice, because a half-written file is what a crash leaves behind.
42
+ */
43
+ export function planFileSource(root) {
44
+ const base = resolve(root);
45
+ return async () => {
46
+ const notices = [];
47
+ const get = async (file) => {
48
+ const read = await readProjectFile(base, join(base, file), CONTEXT_FILE_MAX_BYTES);
49
+ if (read === undefined)
50
+ return undefined;
51
+ if ("notice" in read) {
52
+ notices.push(read.notice);
53
+ return undefined;
54
+ }
55
+ return read;
56
+ };
57
+ const plan = await get(PLAN_FILE);
58
+ const progress = await get(PROGRESS_FILE);
59
+ if (progress !== undefined && !progress.truncated) {
60
+ try {
61
+ JSON.parse(progress.text);
62
+ }
63
+ catch {
64
+ notices.push(`${PROGRESS_FILE} is not valid JSON, so it is shown as written`);
65
+ }
66
+ }
67
+ return {
68
+ ...(plan === undefined ? {} : { plan: { text: plan.text, truncated: plan.truncated } }),
69
+ ...(progress === undefined ? {} : { progress: { text: progress.text, truncated: progress.truncated } }),
70
+ ...(notices.length === 0 ? {} : { notices }),
71
+ };
72
+ };
73
+ }
74
+ //# sourceMappingURL=context-files-node.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context-files-node.js","sourceRoot":"","sources":["../../src/extensions/context-files-node.ts"],"names":[],"mappings":"AAAA,kIAAkI;AAClI,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EACL,sBAAsB,EAEtB,SAAS,EAGT,aAAa,GACd,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAcjE,MAAM,KAAK,GAAG,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;AAEzC;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,GAAW;IAC5C,MAAM,IAAI,GAAG,MAAM,WAAW,CAAC,GAAG,CAAC,CAAC;IACpC,MAAM,IAAI,GAAG,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAW,CAAC;IACnC,MAAM,MAAM,GAAsB,EAAE,KAAK,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;IAC7D,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,KAAK,MAAM,GAAG,I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AAO,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;gBAC1B,OAAO,SAAS,CAAC;YACnB,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC,CAAC;QACF,MAAM,IAAI,GAAG,MAAM,GAAG,CAAC,SAAS,CAAC,CAAC;QAClC,MAAM,QAAQ,GAAG,MAAM,GAAG,CAAC,aAAa,CAAC,CAAC;QAC1C,IAAI,QAAQ,KAAK,SAAS,IAAI,CAAC,QAAQ,CAAC,SAAS,EAAE,CAAC;YAClD,IAAI,CAAC;gBACH,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;YAC5B,CAAC;YAAC,MAAM,CAAC;gBACP,OAAO,CAAC,IAAI,CAAC,GAAG,aAAa,+CAA+C,CAAC,CAAC;YAChF,CAAC;QACH,CAAC;QACD,OAAO;YACL,GAAG,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC;YACvF,GAAG,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,EAAE,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE,SAAS,EAAE,QAAQ,CAAC,SAAS,EAAE,EAAE,CAAC;YACvG,GAAG,CAAC,OAAO,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC;SAC7C,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/** Reading the files `projectContext()` shows the model: `AGENTS.md`, `CLAUDE.md`, and the plan and progress files. Node-only. */\nimport { join, resolve } from \"node:path\";\nimport {\n CONTEXT_FILE_MAX_BYTES,\n type ContextFile,\n PLAN_FILE,\n type PlanFiles,\n type PlanSource,\n PROGRESS_FILE,\n} from \"./context-files.js\";\nimport { projectDirs, readProjectFile } from \"./project-dirs.js\";\n\n/** The context files found, and why any were skipped. */\nexport interface FoundContextFiles {\n /**\n * Every file read, outermost folder first, so the file nearest the working directory comes last. `AGENTS.md` comes\n * before `CLAUDE.md` in a folder. They are not yet held to `CONTEXT_FILES_MAX_TOTAL_BYTES`: `projectContext()` does\n * that and says in the block which it left out.\n */\n readonly files: ContextFile[];\n /** One line for each file skipped, such as a link that leaves the project. */\n readonly notices: string[];\n}\n\nconst NAMES = [\"AGENTS.md\", \"CLAUDE.md\"];\n\n/**\n * Reads the `AGENTS.md` and `CLAUDE.md` of `cwd` and of every folder above it up to the repository root (the first\n * folder with a `.git`; with none, `cwd` alone). These files load whether or not the project is trusted, because they\n * are text and not code, and `projectContext()` labels them untrusted. A `CLAUDE.md` that links to the `AGENTS.md`\n * beside it is read once. A link that leaves the project is skipped with a notice, so a cloned repository cannot pull\n * in a file such as `~/.ssh/id_rsa`. Each file is cut at 64 KiB. Every file read is returned, however long they are\n * together: pass them to `projectContext()`, which holds them to 128 KiB, leaves out the outermost first and tells\n * the model in the block which it left out.\n */\nexport async function contextFiles(cwd: string): Promise<FoundContextFiles> {\n const dirs = await projectDirs(cwd);\n const root = dirs.at(-1) as string;\n const result: FoundContextFiles = { files: [], notices: [] };\n const seen = new Set<string>();\n for (const dir of [...dirs].reverse()) {\n for (const name of NAMES) {\n const path = join(dir, name);\n const read = await readProjectFile(root, path, CONTEXT_FILE_MAX_BYTES);\n if (read === undefined) continue;\n if (\"notice\" in read) {\n result.notices.push(read.notice);\n continue;\n }\n if (seen.has(read.real)) continue;\n seen.add(read.real);\n result.files.push({ path, text: read.text, truncated: read.truncated });\n }\n }\n return result;\n}\n\n/**\n * A plan source that reads `.agents/plan.md` and `.agents/progress.json` under `root` each time it is called. A file\n * that does not exist is left out, a link that leaves `root` is skipped with a notice, and a progress file that is not\n * valid JSON is still shown, with a notice, because a half-written file is what a crash leaves behind.\n */\nexport function planFileSource(root: string): PlanSource {\n const base = resolve(root);\n return async (): Promise<PlanFiles> => {\n const notices: string[] = [];\n const get = async (file: string) => {\n const read = await readProjectFile(base, join(base, file), CONTEXT_FILE_MAX_BYTES);\n if (read === undefined) return undefined;\n if (\"notice\" in read) {\n notices.push(read.notice);\n return undefined;\n }\n return read;\n };\n const plan = await get(PLAN_FILE);\n const progress = await get(PROGRESS_FILE);\n if (progress !== undefined && !progress.truncated) {\n try {\n JSON.parse(progress.text);\n } catch {\n notices.push(`${PROGRESS_FILE} is not valid JSON, so it is shown as written`);\n }\n }\n return {\n ...(plan === undefined ? {} : { plan: { text: plan.text, truncated: plan.truncated } }),\n ...(progress === undefined ? {} : { progress: { text: progress.text, truncated: progress.truncated } }),\n ...(notices.length === 0 ? {} : { notices }),\n };\n };\n}\n"]}
@@ -0,0 +1,68 @@
1
+ import type { Extension } from "./types.js";
2
+ /** The most bytes of one context, plan or progress file the harness reads. A longer file is cut and says so. */
3
+ export declare const CONTEXT_FILE_MAX_BYTES: number;
4
+ /**
5
+ * The most bytes of all the `AGENTS.md` and `CLAUDE.md` files together, as UTF-8. Past it the outermost files are left
6
+ * out first, so the files nearest the work stay. The block is added after the context policy has counted the request,
7
+ * so this limit is what keeps it from crowding out the conversation.
8
+ */
9
+ export declare const CONTEXT_FILES_MAX_TOTAL_BYTES: number;
10
+ /** The plan file, relative to the project root. Free Markdown: the goal, the steps, and which are done. */
11
+ export declare const PLAN_FILE = ".agents/plan.md";
12
+ /** The progress file, relative to the project root. A JSON document: where the task stands and what comes next. */
13
+ export declare const PROGRESS_FILE = ".agents/progress.json";
14
+ /** One `AGENTS.md` or `CLAUDE.md` the project holds. */
15
+ export interface ContextFile {
16
+ /** The path the file was found at. */
17
+ readonly path: string;
18
+ readonly text: string;
19
+ /** True when the file was longer than `CONTEXT_FILE_MAX_BYTES` and `text` is its start. */
20
+ readonly truncated: boolean;
21
+ }
22
+ /** What a plan source found: the text of each file that exists, and a note for each that could not be used. */
23
+ export interface PlanFiles {
24
+ readonly plan?: {
25
+ readonly text: string;
26
+ readonly truncated: boolean;
27
+ };
28
+ readonly progress?: {
29
+ readonly text: string;
30
+ readonly truncated: boolean;
31
+ };
32
+ readonly notices?: readonly string[];
33
+ }
34
+ /** Reads the plan and progress files. `planFileSource()` does it from disk; a host with another store passes its own. */
35
+ export type PlanSource = () => Promise<PlanFiles>;
36
+ /** The system prompt's account of the plan files, for a task too long for one context. */
37
+ export declare function planPrompt(): string;
38
+ /** `system` followed by the plan-file convention. */
39
+ export declare function withPlanConvention(system: string): string;
40
+ /** The `source` value with every character that could end the attribute or the tag, or start a line, percent-encoded. */
41
+ export declare const attribute: (value: string) => string;
42
+ /**
43
+ * The text of the leading block: a note saying what it is, then each file in its own labelled section. Files come in
44
+ * the order given, and the plan and progress files last. Returns `""` when there is nothing to show.
45
+ */
46
+ export declare function contextText(files: readonly ContextFile[], plan?: PlanFiles): string;
47
+ /** The settings of `projectContext()`. */
48
+ export interface ProjectContextOptions {
49
+ /** The `AGENTS.md` and `CLAUDE.md` files, as `contextFiles()` found them. Read once, so the block's bytes stay put. */
50
+ readonly files?: readonly ContextFile[];
51
+ /** Where the plan and progress files are read. They are read again at the first model call of every run. */
52
+ readonly plan?: PlanSource;
53
+ }
54
+ /**
55
+ * An extension that puts the context files, and the plan and progress files, at the start of every request. The view
56
+ * is built for each call and the transcript is not changed, so the text is in the first request after a compaction and
57
+ * after a resume, whatever the summary kept. The context files together are held to `CONTEXT_FILES_MAX_TOTAL_BYTES`:
58
+ * past it the outermost are left out, and the block says which. The context files form one text block with the same
59
+ * bytes on every call. The plan and progress files form a second block after it, immediately before the first
60
+ * message's own content.
61
+ *
62
+ * The plan and progress files are read from the source at a run's first model call, which is what a resume or a new
63
+ * turn is, and the same text is sent for the rest of the run, so the model's edits during a run show in the next one.
64
+ * A plan edit still changes the first message. A provider caches a prompt by its prefix, so the next run's first call
65
+ * reads none of the conversation from the cache. Everything after the system prompt and tools is sent uncached once,
66
+ * and the run's later calls read it from the cache again.
67
+ */
68
+ export declare function projectContext(options?: ProjectContextOptions): Extension;