@buildanagent/sdk 0.1.0-alpha.7 → 0.1.0-alpha.9

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 (61) hide show
  1. package/README.md +91 -4
  2. package/dist/compose.d.ts +2 -1
  3. package/dist/compose.js +10 -4
  4. package/dist/compose.js.map +1 -1
  5. package/dist/errors.d.ts +2 -1
  6. package/dist/errors.js +2 -1
  7. package/dist/errors.js.map +1 -1
  8. package/dist/events.d.ts +18 -4
  9. package/dist/events.js +1 -0
  10. package/dist/events.js.map +1 -1
  11. package/dist/hook-checks.js +17 -0
  12. package/dist/hook-checks.js.map +1 -1
  13. package/dist/hook-runner.d.ts +10 -0
  14. package/dist/hook-runner.js +86 -9
  15. package/dist/hook-runner.js.map +1 -1
  16. package/dist/hooks.d.ts +9 -4
  17. package/dist/hooks.js.map +1 -1
  18. package/dist/index.d.ts +9 -3
  19. package/dist/index.js +7 -2
  20. package/dist/index.js.map +1 -1
  21. package/dist/loop.d.ts +5 -0
  22. package/dist/loop.js +26 -3
  23. package/dist/loop.js.map +1 -1
  24. package/dist/otel/attributes.d.ts +43 -0
  25. package/dist/otel/attributes.js +50 -0
  26. package/dist/otel/attributes.js.map +1 -0
  27. package/dist/otel/content.d.ts +17 -0
  28. package/dist/otel/content.js +48 -0
  29. package/dist/otel/content.js.map +1 -0
  30. package/dist/otel/index.d.ts +6 -2
  31. package/dist/otel/index.js +6 -2
  32. package/dist/otel/index.js.map +1 -1
  33. package/dist/otel/observer.d.ts +82 -0
  34. package/dist/otel/observer.js +300 -0
  35. package/dist/otel/observer.js.map +1 -0
  36. package/dist/pauses.d.ts +32 -0
  37. package/dist/pauses.js +46 -0
  38. package/dist/pauses.js.map +1 -0
  39. package/dist/result.d.ts +27 -3
  40. package/dist/result.js.map +1 -1
  41. package/dist/run.d.ts +19 -3
  42. package/dist/run.js +17 -1
  43. package/dist/run.js.map +1 -1
  44. package/dist/tools/pipeline.d.ts +19 -3
  45. package/dist/tools/pipeline.js +24 -5
  46. package/dist/tools/pipeline.js.map +1 -1
  47. package/dist/vendor/agent-safety/bytes.d.ts +17 -0
  48. package/dist/vendor/agent-safety/bytes.js +59 -0
  49. package/dist/vendor/agent-safety/bytes.js.map +1 -0
  50. package/dist/vendor/agent-safety/errors.d.ts +8 -4
  51. package/dist/vendor/agent-safety/errors.js +2 -2
  52. package/dist/vendor/agent-safety/errors.js.map +1 -1
  53. package/dist/vendor/agent-safety/hash.js +3 -2
  54. package/dist/vendor/agent-safety/hash.js.map +1 -1
  55. package/dist/vendor/agent-safety/pending.d.ts +119 -0
  56. package/dist/vendor/agent-safety/pending.js +122 -0
  57. package/dist/vendor/agent-safety/pending.js.map +1 -0
  58. package/dist/vendor/agent-safety/signer.d.ts +42 -0
  59. package/dist/vendor/agent-safety/signer.js +128 -0
  60. package/dist/vendor/agent-safety/signer.js.map +1 -0
  61. package/package.json +4 -2
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/vendor/agent-safety/errors.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAKH,4FAA4F;AAC5F,MAAM,YAAY,GAAG,MAAM,CAAC,GAAG,CAAC,uCAAuC,CAAC,CAAC;AAEzE,oHAAoH;AACpH,MAAM,OAAO,WAAY,SAAQ,KAAK;IAClB,IAAI,GAAG,aAAa,CAAC;IAC9B,IAAI,CAAkB;IAE/B,YAAY,IAAqB,EAAE,OAAe,EAAE,OAAsB;QACxE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7D,CAAC;CACF;AAED,gFAAgF;AAChF,MAAM,UAAU,aAAa,CAAC,KAAc;IAC1C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,YAAY,CAAC,KAAK,IAAI,CAAC;AAClH,CAAC","sourcesContent":["/**\n * `SafetyError`: the safety package's error for programmer errors, such as a write outcome with a malformed reason or\n * an input that has no canonical JSON form.\n */\n\n/** Why a `SafetyError` was thrown. */\nexport type SafetyErrorCode = \"invalid_outcome\" | \"invalid_input\";\n\n// A registered symbol, so the guard still works when two copies of the package are bundled.\nconst SAFETY_ERROR = Symbol.for(\"buildanagent.agent-safety.SafetyError\");\n\n/** Thrown for a mistake in how the safety package is called. A write that fails is an outcome, never this error. */\nexport class SafetyError extends Error {\n override readonly name = \"SafetyError\";\n readonly code: SafetyErrorCode;\n\n constructor(code: SafetyErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n Object.defineProperty(this, SAFETY_ERROR, { value: true });\n }\n}\n\n/** True for a `SafetyError`, including one from another copy of the package. */\nexport function isSafetyError(error: unknown): error is SafetyError {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[SAFETY_ERROR] === true;\n}\n"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/vendor/agent-safety/errors.ts"],"names":[],"mappings":"AAAA;;;GAGG;AASH,4FAA4F;AAC5F,MAAM,YAAY,GAAG,MAAM,CAAC,GAAG,CAAC,uCAAuC,CAAC,CAAC;AAEzE,oHAAoH;AACpH,MAAM,OAAO,WAAY,SAAQ,KAAK;IAClB,IAAI,GAAG,aAAa,CAAC;IAC9B,IAAI,CAAkB;IAE/B,YAAY,IAAqB,EAAE,OAAe,EAAE,OAAsB;QACxE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7D,CAAC;CACF;AAED,gFAAgF;AAChF,MAAM,UAAU,aAAa,CAAC,KAAc;IAC1C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,YAAY,CAAC,KAAK,IAAI,CAAC;AAClH,CAAC","sourcesContent":["/**\n * `SafetyError`: the safety package's error for programmer errors, such as a write outcome with a malformed reason, an\n * input that has no canonical JSON form, or a key ring that can't sign.\n */\n\n/**\n * Why a `SafetyError` was thrown. `invalid_outcome`: a write outcome breaks a rule. `invalid_input`: a tool input has\n * no canonical JSON form, or a tool's context fails its `contextSchema`. `invalid_key_ring`: a signer's keys or key\n * ids can't be used. `invalid_pending`: the fields of a pending request can't be signed.\n */\nexport type SafetyErrorCode = \"invalid_outcome\" | \"invalid_input\" | \"invalid_key_ring\" | \"invalid_pending\";\n\n// A registered symbol, so the guard still works when two copies of the package are bundled.\nconst SAFETY_ERROR = Symbol.for(\"buildanagent.agent-safety.SafetyError\");\n\n/** Thrown for a mistake in how the safety package is called. A write that fails is an outcome, never this error. */\nexport class SafetyError extends Error {\n override readonly name = \"SafetyError\";\n readonly code: SafetyErrorCode;\n\n constructor(code: SafetyErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n Object.defineProperty(this, SAFETY_ERROR, { value: true });\n }\n}\n\n/** True for a `SafetyError`, including one from another copy of the package. */\nexport function isSafetyError(error: unknown): error is SafetyError {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[SAFETY_ERROR] === true;\n}\n"]}
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * `canonicalInputHash()`: one hash per tool input, whatever order its keys arrive in. Approvals sign it and effect
3
3
  * records store it, so both must compute it the same way on every runtime: canonical JSON as RFC 8785 (JCS) defines
4
- * it, hashed with Web Crypto's SHA-256.
4
+ * it, hashed with Web Crypto's SHA-256. Web Crypto is read as the bare `crypto` global, the same object as
5
+ * `globalThis.crypto`, because the Workers types declare it as a `const`, which `typeof globalThis` lacks.
5
6
  */
6
7
  import { SafetyError } from "./errors.js";
7
8
  const ENCODER = new TextEncoder();
@@ -104,6 +105,6 @@ function hex(bytes) {
104
105
  */
105
106
  export async function canonicalInputHash(input) {
106
107
  const text = canonical(input, "$", new Set());
107
- return hex(await globalThis.crypto.subtle.digest("SHA-256", ENCODER.encode(text)));
108
+ return hex(await crypto.subtle.digest("SHA-256", ENCODER.encode(text)));
108
109
  }
109
110
  //# sourceMappingURL=hash.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"hash.js","sourceRoot":"","sources":["../../../src/vendor/agent-safety/hash.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAElC,SAAS,OAAO,CAAC,IAAY,EAAE,GAAW;IACxC,OAAO,IAAI,WAAW,CAAC,eAAe,EAAE,gBAAgB,IAAI,IAAI,GAAG,oCAAoC,CAAC,CAAC;AAC3G,CAAC;AAED,SAAS,eAAe,CAAC,KAAa,EAAE,IAAY;IAClD,0EAA0E;IAC1E,IAAI,CAAC,KAAK,CAAC,YAAY,EAAE;QAAE,MAAM,OAAO,CAAC,IAAI,EAAE,wBAAwB,CAAC,CAAC;IACzE,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AAC/B,CAAC;AAED,SAAS,eAAe,CAAC,KAAa,EAAE,IAAY;IAClD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,MAAM,OAAO,CAAC,IAAI,EAAE,MAAM,KAAK,EAAE,CAAC,CAAC;IAChE,8FAA8F;IAC9F,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AAC/B,CAAC;AAED,mHAAmH;AACnH,mGAAmG;AACnG,SAAS,aAAa,CAAC,KAAa;IAClC,MAAM,SAAS,GAAG,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;IAC/C,OAAO,SAAS,KAAK,IAAI,IAAI,MAAM,CAAC,cAAc,C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vals sign it and effect\n * records store it, so both must compute it the same way on every runtime: canonical JSON as RFC 8785 (JCS) defines\n * it, hashed with Web Crypto's SHA-256.\n */\nimport { SafetyError } from \"./errors.js\";\n\nconst ENCODER = new TextEncoder();\n\nfunction invalid(path: string, why: string): SafetyError {\n return new SafetyError(\"invalid_input\", `the input at ${path} ${why}, so it has no canonical JSON form`);\n}\n\nfunction canonicalString(value: string, path: string): string {\n // JCS refuses lone surrogates, which JSON.stringify would escape instead.\n if (!value.isWellFormed()) throw invalid(path, \"holds a lone surrogate\");\n return JSON.stringify(value);\n}\n\nfunction canonicalNumber(value: number, path: string): string {\n if (!Number.isFinite(value)) throw invalid(path, `is ${value}`);\n // JCS serializes numbers as ECMAScript does, which JSON.stringify follows, including -0 as 0.\n return JSON.stringify(value);\n}\n\n// Plain means a null prototype or any realm's `Object.prototype`, whose own prototype is null: an object made in a\n// `vm` context or an iframe is as plain as one made here, while a `Date` or class instance is not.\nfunction isPlainObject(value: object): value is Record<string, unknown> {\n const prototype = Object.getPrototypeOf(value);\n return prototype === null || Object.getPrototypeOf(prototype) === null;\n}\n\nfunction byKey([a]: [string, unknown], [b]: [string, unknown]): number {\n // JCS sorts property names by UTF-16 code units, which is what `<` compares.\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n// `ancestors` holds the objects and arrays that enclose the current value, so a cycle throws instead of recursing\n// until the stack runs out. A value shared by two siblings is no cycle, so it is removed again on the way out.\nfunction canonicalObject(value: Record<string, unknown>, path: string, ancestors: Set<object>): string {\n // Each property is read once, so a getter or a Proxy can't be counted as present and then read as undefined.\n const entries = Object.entries(value)\n .filter(([, item]) => item !== undefined)\n .sort(byKey);\n const members = entries.map(\n ([key, item]) =>\n `${canonicalString(key, `${path}'s property name`)}:${canonical(item, `${path}.${key}`, ancestors)}`,\n );\n return `{${members.join(\",\")}}`;\n}\n\nfunction canonicalArray(value: readonly unknown[], path: string, ancestors: Set<object>): string {\n // An index loop, because `map` skips the holes of a sparse array and `join` would then write `[1,,3]`.\n const items: string[] = [];\n for (let index = 0; index < value.length; index++) {\n const itemPath = `${path}[${index}]`;\n if (!(index in value)) throw invalid(itemPath, \"is a hole in a sparse array\");\n const item = value[index];\n if (item === undefined) throw invalid(itemPath, \"is undefined\");\n items.push(canonical(item, itemPath, ancestors));\n }\n return `[${items.join(\",\")}]`;\n}\n\nfunction nested(value: object, path: string, ancestors: Set<object>, write: () => string): string {\n if (ancestors.has(value)) throw invalid(path, \"refers back to an object that contains it\");\n ancestors.add(value);\n try {\n return write();\n } finally {\n ancestors.delete(value);\n }\n}\n\nfunction describeType(value: unknown): string {\n if (value === undefined) return \"undefined\";\n return typeof value === \"object\" ? \"an object that isn't plain\" : `a ${typeof value}`;\n}\n\nfunction canonical(value: unknown, path: string, ancestors: Set<object>): string {\n if (value === null || typeof value === \"boolean\") return JSON.stringify(value);\n if (typeof value === \"string\") return canonicalString(value, path);\n if (typeof value === \"number\") return canonicalNumber(value, path);\n if (Array.isArray(value)) return nested(value, path, ancestors, () => canonicalArray(value, path, ancestors));\n if (typeof value === \"object\" && isPlainObject(value)) {\n return nested(value, path, ancestors, () => canonicalObject(value, path, ancestors));\n }\n throw invalid(path, `is ${describeType(value)}`);\n}\n\nfunction hex(bytes: ArrayBuffer): string {\n return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Hashes a tool input: the SHA-256 of its canonical JSON (RFC 8785), as 64 lowercase hex digits. Two inputs whose\n * object keys differ only in order get the same hash, and any changed value gives a different one. Object properties\n * set to `undefined` are left out, as `JSON.stringify` leaves them out. The hash is async, because Web Crypto's\n * digest is.\n *\n * It rejects with a `SafetyError`, code `invalid_input`, for a value that has no single JSON form:\n * - `undefined`, or a hole, in an array;\n * - a number that isn't finite;\n * - a string with a lone surrogate;\n * - a bigint, symbol or function;\n * - an object that isn't plain, such as a `Date` (a plain object's prototype is `null` or any realm's\n * `Object.prototype`);\n * - an object or array that contains itself.\n */\nexport async function canonicalInputHash(input: unknown): Promise<string> {\n const text = canonical(input, \"$\", new Set());\n return hex(await globalThis.crypto.subtle.digest(\"SHA-256\", ENCODER.encode(text)));\n}\n"]}
1
+ {"version":3,"file":"hash.js","sourceRoot":"","sources":["../../../src/vendor/agent-safety/hash.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAElC,SAAS,OAAO,CAAC,IAAY,EAAE,GAAW;IACxC,OAAO,IAAI,WAAW,CAAC,eAAe,EAAE,gBAAgB,IAAI,IAAI,GAAG,oCAAoC,CAAC,CAAC;AAC3G,CAAC;AAED,SAAS,eAAe,CAAC,KAAa,EAAE,IAAY;IAClD,0EAA0E;IAC1E,IAAI,CAAC,KAAK,CAAC,YAAY,EAAE;QAAE,MAAM,OAAO,CAAC,IAAI,EAAE,wBAAwB,CAAC,CAAC;IACzE,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AAC/B,CAAC;AAED,SAAS,eAAe,CAAC,KAAa,EAAE,IAAY;IAClD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,MAAM,OAAO,CAAC,IAAI,EAAE,MAAM,KAAK,EAAE,CAAC,CAAC;IAChE,8FAA8F;IAC9F,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AAC/B,CAAC;AAED,mHAAmH;AACnH,mGAAmG;AACnG,SAAS,aAAa,CAAC,KAAa;IAClC,MAAM,SAAS,GAAG,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;IAC/C,OAAO,SAAS,KAAK,IAAI,IAAI,MAAM,CAAC,cAAc,CAAC,SAAS,CAAC,KAAK,IAAI,CAAC;AACzE,CAAC;AAED,SAAS,KAAK,CAAC,CAAC,CAAC,CAAoB,EAAE,CAAC,CAAC,CAAoB;IAC3D,6EAA6E;IAC7E,OA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AC,KAAK,EAAE,IAAI,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC,cAAc,CAAC,KAAK,EAAE,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC;IAC9G,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,aAAa,CAAC,KAAK,CAAC,EAAE,CAAC;QACtD,OAAO,MAAM,CAAC,KAAK,EAAE,IAAI,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC,eAAe,CAAC,KAAK,EAAE,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC;IACvF,CAAC;IACD,MAAM,OAAO,CAAC,IAAI,EAAE,MAAM,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;AACnD,CAAC;AAED,SAAS,GAAG,CAAC,KAAkB;IAC7B,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AAClG,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,KAAK,UAAU,kBAAkB,CAAC,KAAc;IACrD,MAAM,IAAI,GAAG,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,GAAG,EAAE,CAAC,CAAC;IAC9C,OAAO,GAAG,CAAC,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAC1E,CAAC","sourcesContent":["/**\n * `canonicalInputHash()`: one hash per tool input, whatever order its keys arrive in. Approvals sign it and effect\n * records store it, so both must compute it the same way on every runtime: canonical JSON as RFC 8785 (JCS) defines\n * it, hashed with Web Crypto's SHA-256. Web Crypto is read as the bare `crypto` global, the same object as\n * `globalThis.crypto`, because the Workers types declare it as a `const`, which `typeof globalThis` lacks.\n */\nimport { SafetyError } from \"./errors.js\";\n\nconst ENCODER = new TextEncoder();\n\nfunction invalid(path: string, why: string): SafetyError {\n return new SafetyError(\"invalid_input\", `the input at ${path} ${why}, so it has no canonical JSON form`);\n}\n\nfunction canonicalString(value: string, path: string): string {\n // JCS refuses lone surrogates, which JSON.stringify would escape instead.\n if (!value.isWellFormed()) throw invalid(path, \"holds a lone surrogate\");\n return JSON.stringify(value);\n}\n\nfunction canonicalNumber(value: number, path: string): string {\n if (!Number.isFinite(value)) throw invalid(path, `is ${value}`);\n // JCS serializes numbers as ECMAScript does, which JSON.stringify follows, including -0 as 0.\n return JSON.stringify(value);\n}\n\n// Plain means a null prototype or any realm's `Object.prototype`, whose own prototype is null: an object made in a\n// `vm` context or an iframe is as plain as one made here, while a `Date` or class instance is not.\nfunction isPlainObject(value: object): value is Record<string, unknown> {\n const prototype = Object.getPrototypeOf(value);\n return prototype === null || Object.getPrototypeOf(prototype) === null;\n}\n\nfunction byKey([a]: [string, unknown], [b]: [string, unknown]): number {\n // JCS sorts property names by UTF-16 code units, which is what `<` compares.\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n// `ancestors` holds the objects and arrays that enclose the current value, so a cycle throws instead of recursing\n// until the stack runs out. A value shared by two siblings is no cycle, so it is removed again on the way out.\nfunction canonicalObject(value: Record<string, unknown>, path: string, ancestors: Set<object>): string {\n // Each property is read once, so a getter or a Proxy can't be counted as present and then read as undefined.\n const entries = Object.entries(value)\n .filter(([, item]) => item !== undefined)\n .sort(byKey);\n const members = entries.map(\n ([key, item]) =>\n `${canonicalString(key, `${path}'s property name`)}:${canonical(item, `${path}.${key}`, ancestors)}`,\n );\n return `{${members.join(\",\")}}`;\n}\n\nfunction canonicalArray(value: readonly unknown[], path: string, ancestors: Set<object>): string {\n // An index loop, because `map` skips the holes of a sparse array and `join` would then write `[1,,3]`.\n const items: string[] = [];\n for (let index = 0; index < value.length; index++) {\n const itemPath = `${path}[${index}]`;\n if (!(index in value)) throw invalid(itemPath, \"is a hole in a sparse array\");\n const item = value[index];\n if (item === undefined) throw invalid(itemPath, \"is undefined\");\n items.push(canonical(item, itemPath, ancestors));\n }\n return `[${items.join(\",\")}]`;\n}\n\nfunction nested(value: object, path: string, ancestors: Set<object>, write: () => string): string {\n if (ancestors.has(value)) throw invalid(path, \"refers back to an object that contains it\");\n ancestors.add(value);\n try {\n return write();\n } finally {\n ancestors.delete(value);\n }\n}\n\nfunction describeType(value: unknown): string {\n if (value === undefined) return \"undefined\";\n return typeof value === \"object\" ? \"an object that isn't plain\" : `a ${typeof value}`;\n}\n\nfunction canonical(value: unknown, path: string, ancestors: Set<object>): string {\n if (value === null || typeof value === \"boolean\") return JSON.stringify(value);\n if (typeof value === \"string\") return canonicalString(value, path);\n if (typeof value === \"number\") return canonicalNumber(value, path);\n if (Array.isArray(value)) return nested(value, path, ancestors, () => canonicalArray(value, path, ancestors));\n if (typeof value === \"object\" && isPlainObject(value)) {\n return nested(value, path, ancestors, () => canonicalObject(value, path, ancestors));\n }\n throw invalid(path, `is ${describeType(value)}`);\n}\n\nfunction hex(bytes: ArrayBuffer): string {\n return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Hashes a tool input: the SHA-256 of its canonical JSON (RFC 8785), as 64 lowercase hex digits. Two inputs whose\n * object keys differ only in order get the same hash, and any changed value gives a different one. Object properties\n * set to `undefined` are left out, as `JSON.stringify` leaves them out. The hash is async, because Web Crypto's\n * digest is.\n *\n * It rejects with a `SafetyError`, code `invalid_input`, for a value that has no single JSON form:\n * - `undefined`, or a hole, in an array;\n * - a number that isn't finite;\n * - a string with a lone surrogate;\n * - a bigint, symbol or function;\n * - an object that isn't plain, such as a `Date` (a plain object's prototype is `null` or any realm's\n * `Object.prototype`);\n * - an object or array that contains itself.\n */\nexport async function canonicalInputHash(input: unknown): Promise<string> {\n const text = canonical(input, \"$\", new Set());\n return hex(await crypto.subtle.digest(\"SHA-256\", ENCODER.encode(text)));\n}\n"]}
@@ -0,0 +1,119 @@
1
+ import type { ApprovalSigner } from "./signer.js";
2
+ /**
3
+ * A pause waiting for a person: an approval of one tool call, or a question about it. `signature` signs `id`, `kind`,
4
+ * `callId`, `tool`, `inputHash` and `policyVersion` under the key `keyId` names. `question`, `reason` and `createdAt`
5
+ * are shown to people and aren't signed, so never let them decide anything.
6
+ */
7
+ export interface SignedPendingRequest {
8
+ /** The request's own id, which a `Resolution` names. */
9
+ id: string;
10
+ /** `approval` waits for allow or deny; `clarification` waits for an answer. */
11
+ kind: "approval" | "clarification";
12
+ /** The id of the tool call that waits. */
13
+ callId: string;
14
+ /** The tool's name. */
15
+ tool: string;
16
+ /** `canonicalInputHash()` of the call's input. */
17
+ inputHash: string;
18
+ /** The version of the policy that asked for the pause, if the host versions its policy. */
19
+ policyVersion?: string;
20
+ /** The question a clarification asks. */
21
+ question?: string;
22
+ /** Why the call needs a person, as shown to the approver. */
23
+ reason?: string;
24
+ /** The id of the key that made `signature`. */
25
+ keyId: string;
26
+ /** The signature, as base64url. */
27
+ signature: string;
28
+ /** When the request was signed, as an ISO 8601 timestamp. */
29
+ createdAt: string;
30
+ }
31
+ /** A person's answer to a pending request: allow or deny for an approval, an answer for a clarification. */
32
+ export type Resolution = {
33
+ requestId: string;
34
+ decision: "allow" | "deny";
35
+ reason?: string;
36
+ by?: string;
37
+ } | {
38
+ requestId: string;
39
+ answer: string;
40
+ by?: string;
41
+ };
42
+ /** The fields `signPending()` signs and stores, with the call's input in place of its hash. */
43
+ export interface PendingFields {
44
+ readonly kind: "approval" | "clarification";
45
+ readonly callId: string;
46
+ readonly tool: string;
47
+ /** The tool call's input. `signPending()` stores its `canonicalInputHash()`, never the input itself. */
48
+ readonly input: unknown;
49
+ readonly policyVersion?: string;
50
+ readonly question?: string;
51
+ readonly reason?: string;
52
+ }
53
+ /** Where `signPending()` takes its request id and time from. Tests pass fixed ones. */
54
+ export interface SignPendingOptions {
55
+ /** Returns a fresh request id. Defaults to `crypto.randomUUID()`. */
56
+ readonly generateId?: () => string;
57
+ /** Returns the current time. Defaults to `new Date()`. */
58
+ readonly now?: () => Date;
59
+ }
60
+ /** The call a host is about to run, which a pending request must match before it runs. */
61
+ export interface PendingCall {
62
+ readonly callId: string;
63
+ readonly tool: string;
64
+ readonly input: unknown;
65
+ }
66
+ /**
67
+ * Why `verifyResolution()` refused. `malformed`: the stored request isn't a well-formed pending request.
68
+ * `unknown_request`: the resolution names another request. `signature_invalid`: the signature is wrong, or its key id
69
+ * isn't in the ring. `call_mismatch`: the call id or tool differs from the call about to run. `input_changed`: the
70
+ * input differs from the one that was signed. `resolution_mismatch`: the resolution doesn't fit the request's kind.
71
+ */
72
+ export type RejectionCause = "malformed" | "unknown_request" | "signature_invalid" | "call_mismatch" | "input_changed" | "resolution_mismatch";
73
+ /** What `verifyResolution()` returns: the resolution, once every check passed, or why it refused. */
74
+ export type ResolutionCheck = {
75
+ readonly ok: true;
76
+ readonly resolution: Resolution;
77
+ } | {
78
+ readonly ok: false;
79
+ readonly cause: RejectionCause;
80
+ };
81
+ /** The options of `verifyResolution()`. */
82
+ export interface VerifyResolutionOptions {
83
+ /** A signer that holds the key the request names. */
84
+ readonly signer: ApprovalSigner;
85
+ /** The call about to run, as the host has it now, not as the pending request records it. */
86
+ readonly call: PendingCall;
87
+ }
88
+ /**
89
+ * The bytes a pending request's signature covers: a JSON array of a fixed tag, then the request id, kind, call id,
90
+ * tool name, input hash and policy version, in that order, with `null` for an absent policy version. Every field is a well-formed string, so `JSON.stringify` writes the same bytes
91
+ * on every runtime.
92
+ */
93
+ export declare function pendingPayload(fields: Pick<SignedPendingRequest, "id" | "kind" | "callId" | "tool" | "inputHash" | "policyVersion">): Uint8Array;
94
+ /**
95
+ * Signs a pending request for a tool call. It hashes the input with `canonicalInputHash()`, signs the six fields
96
+ * `pendingPayload()` lists with the signer's current key, and returns the request to store. The input itself isn't stored.
97
+ *
98
+ * Throws a `SafetyError`, code `invalid_pending`, for a blank or malformed field, and code `invalid_input` for an
99
+ * input with no canonical JSON form.
100
+ */
101
+ export declare function signPending(fields: PendingFields, signer: ApprovalSigner, options?: SignPendingOptions): Promise<SignedPendingRequest>;
102
+ /**
103
+ * Checks a resolution against its stored pending request before the call runs, failing closed. It accepts only when
104
+ * the request is well formed, the resolution names it, the signature verifies under a key the signer holds, the call
105
+ * id and tool match the call about to run, that call's input hashes to the signed hash, and the resolution fits the
106
+ * request's kind. Otherwise it returns `ok: false` with the first cause it found, and never throws for bad input.
107
+ *
108
+ * A passing check says the request is authentic and unchanged. It doesn't say current policy still allows the call:
109
+ * check that separately, just before the call runs.
110
+ */
111
+ export declare function verifyResolution(pending: unknown, resolution: Resolution, options: VerifyResolutionOptions): Promise<ResolutionCheck>;
112
+ /**
113
+ * Runs current policy for an approved call just before it runs, after its pending request has verified. Resolve to
114
+ * `"allow"` to let the call run, or to `{ deny }` with a reason the model reads, so a policy that changed since the
115
+ * pause can still stop the call.
116
+ */
117
+ export type Recheck = (pending: SignedPendingRequest, input: unknown) => Promise<"allow" | {
118
+ deny: string;
119
+ }>;
@@ -0,0 +1,122 @@
1
+ /**
2
+ * The signed pending request: what an agent stores when a tool call waits for a person, and what it checks before the
3
+ * call runs. The signature covers D5's six fields in D5's order (request id, kind, call id, tool name, input hash and
4
+ * the optional policy version), so a stored pause whose call, tool or input changed no longer verifies. The shapes
5
+ * match build-sdk.md §3.3 field for field, because our SDK re-exports them.
6
+ */
7
+ import { constantTimeEqual } from "./bytes.js";
8
+ import { SafetyError } from "./errors.js";
9
+ import { canonicalInputHash } from "./hash.js";
10
+ // Ties a signature to this record and its layout, so it can't verify as some other signed record of this package.
11
+ const PAYLOAD_TAG = "buildanagent.pending.v1";
12
+ const KINDS = ["approval", "clarification"];
13
+ const INPUT_HASH = /^[0-9a-f]{64}$/;
14
+ const ENCODER = new TextEncoder();
15
+ function isText(value) {
16
+ return typeof value === "string" && value !== "" && value.isWellFormed();
17
+ }
18
+ function isOptionalText(value) {
19
+ return value === undefined || isText(value);
20
+ }
21
+ /** True when `value` has the shape of a pending request; a store's record is untrusted until this and the signature pass. */
22
+ function isWellFormed(value) {
23
+ if (typeof value !== "object" || value === null)
24
+ return false;
25
+ const p = value;
26
+ return ([p.id, p.callId, p.tool, p.keyId, p.signature, p.createdAt].every(isText) &&
27
+ KINDS.includes(p.kind) &&
28
+ typeof p.inputHash === "string" &&
29
+ INPUT_HASH.test(p.inputHash) &&
30
+ [p.policyVersion, p.question, p.reason].every(isOptionalText));
31
+ }
32
+ /**
33
+ * The bytes a pending request's signature covers: a JSON array of a fixed tag, then the request id, kind, call id,
34
+ * tool name, input hash and policy version, in that order, with `null` for an absent policy version. Every field is a well-formed string, so `JSON.stringify` writes the same bytes
35
+ * on every runtime.
36
+ */
37
+ export function pendingPayload(fields) {
38
+ const { id, kind, callId, tool, inputHash, policyVersion } = fields;
39
+ return ENCODER.encode(JSON.stringify([PAYLOAD_TAG, id, kind, callId, tool, inputHash, policyVersion ?? null]));
40
+ }
41
+ function checkFields(fields, id) {
42
+ const bad = (what) => new SafetyError("invalid_pending", `a pending request's ${what}`);
43
+ if (!isText(id))
44
+ throw bad("id must be a non-empty, well-formed string");
45
+ if (!KINDS.includes(fields.kind))
46
+ throw bad(`kind must be "approval" or "clarification"`);
47
+ for (const field of ["callId", "tool"]) {
48
+ if (!isText(fields[field]))
49
+ throw bad(`${field} must be a non-empty, well-formed string`);
50
+ }
51
+ for (const field of ["policyVersion", "question", "reason"]) {
52
+ if (!isOptionalText(fields[field]))
53
+ throw bad(`${field} must be a non-empty, well-formed string when it is set`);
54
+ }
55
+ }
56
+ /**
57
+ * Signs a pending request for a tool call. It hashes the input with `canonicalInputHash()`, signs the six fields
58
+ * `pendingPayload()` lists with the signer's current key, and returns the request to store. The input itself isn't stored.
59
+ *
60
+ * Throws a `SafetyError`, code `invalid_pending`, for a blank or malformed field, and code `invalid_input` for an
61
+ * input with no canonical JSON form.
62
+ */
63
+ export async function signPending(fields, signer, options = {}) {
64
+ const id = (options.generateId ?? (() => crypto.randomUUID()))();
65
+ checkFields(fields, id);
66
+ const inputHash = await canonicalInputHash(fields.input);
67
+ const signed = { id, kind: fields.kind, callId: fields.callId, tool: fields.tool, inputHash };
68
+ const withPolicy = fields.policyVersion === undefined ? signed : { ...signed, policyVersion: fields.policyVersion };
69
+ const signature = await signer.sign(pendingPayload(withPolicy));
70
+ return {
71
+ ...withPolicy,
72
+ ...(fields.question === undefined ? {} : { question: fields.question }),
73
+ ...(fields.reason === undefined ? {} : { reason: fields.reason }),
74
+ keyId: signer.keyId,
75
+ signature,
76
+ createdAt: (options.now ?? (() => new Date()))().toISOString(),
77
+ };
78
+ }
79
+ function fitsKind(pending, resolution) {
80
+ if (pending.kind === "approval") {
81
+ return "decision" in resolution && (resolution.decision === "allow" || resolution.decision === "deny");
82
+ }
83
+ return "answer" in resolution && typeof resolution.answer === "string";
84
+ }
85
+ async function inputMatches(pending, input) {
86
+ try {
87
+ return constantTimeEqual(ENCODER.encode(await canonicalInputHash(input)), ENCODER.encode(pending.inputHash));
88
+ }
89
+ catch {
90
+ // An input with no canonical form can't be the one that was signed, which had one.
91
+ return false;
92
+ }
93
+ }
94
+ /**
95
+ * Checks a resolution against its stored pending request before the call runs, failing closed. It accepts only when
96
+ * the request is well formed, the resolution names it, the signature verifies under a key the signer holds, the call
97
+ * id and tool match the call about to run, that call's input hashes to the signed hash, and the resolution fits the
98
+ * request's kind. Otherwise it returns `ok: false` with the first cause it found, and never throws for bad input.
99
+ *
100
+ * A passing check says the request is authentic and unchanged. It doesn't say current policy still allows the call:
101
+ * check that separately, just before the call runs.
102
+ */
103
+ export async function verifyResolution(pending, resolution, options) {
104
+ if (!isWellFormed(pending))
105
+ return { ok: false, cause: "malformed" };
106
+ if (typeof resolution !== "object" || resolution === null || resolution.requestId !== pending.id) {
107
+ return { ok: false, cause: "unknown_request" };
108
+ }
109
+ // The signature comes first: until it verifies, no other field of the stored request is trusted.
110
+ if (!(await options.signer.verify(pending.keyId, pendingPayload(pending), pending.signature))) {
111
+ return { ok: false, cause: "signature_invalid" };
112
+ }
113
+ const { call } = options;
114
+ if (call.callId !== pending.callId || call.tool !== pending.tool)
115
+ return { ok: false, cause: "call_mismatch" };
116
+ if (!(await inputMatches(pending, call.input)))
117
+ return { ok: false, cause: "input_changed" };
118
+ if (!fitsKind(pending, resolution))
119
+ return { ok: false, cause: "resolution_mismatch" };
120
+ return { ok: true, resolution };
121
+ }
122
+ //# sourceMappingURL=pending.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pending.js","sourceRoot":"","sources":["../../../src/vendor/agent-safety/pending.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AA4F/C,kHAAkH;AAClH,MAAM,WAAW,GAAG,yBAAyB,CAAC;AAC9C,MAAM,KAAK,GAAsB,CAAC,UAAU,EAAE,eAAe,CAAC,CAAC;AAC/D,MAAM,UAAU,GAAG,gBAAgB,CAAC;AACpC,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAElC,SAAS,MAAM,CAAC,KAAc;IAC5B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,EAAE,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;AAC3E,CAAC;AAED,SAAS,cAAc,CAAC,KAAc;IACpC,OAAO,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC;AAC9C,CAAC;AAED,6HAA6H;AAC7H,SAAS,YAAY,CAAC,KAAc;IAClC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,KAAK,CAAC;IAC9D,MAAM,CAAC,GAAG,KAAgC,CAAC;IAC3C,OAAO,CACL,CAAC,CAAC,CAA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EAAE,KAAK,EAAE,WAAW,EAAE,CAAC;IACrE,IAAI,OAAO,UAAU,KAAK,QAAQ,IAAI,UAAU,KAAK,IAAI,IAAI,UAAU,CAAC,SAAS,KAAK,OAAO,CAAC,EAAE,EAAE,CAAC;QACjG,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,iBAAiB,EAAE,CAAC;IACjD,CAAC;IACD,iGAAiG;IACjG,IAAI,CAAC,CAAC,MAAM,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE,cAAc,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC;QAC9F,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,mBAAmB,EAAE,CAAC;IACnD,CAAC;IACD,MAAM,EAAE,IAAI,EAAE,GAAG,OAAO,CAAC;IACzB,IAAI,IAAI,CAAC,MAAM,KAAK,OAAO,CAAC,MAAM,IAAI,IAAI,CAAC,IAAI,KAAK,OAAO,CAAC,IAAI;QAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,eAAe,EAAE,CAAC;IAC/G,IAAI,CAAC,CAAC,MAAM,YAAY,CAAC,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;QAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,eAAe,EAAE,CAAC;IAC7F,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,UAAU,CAAC;QAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,qBAAqB,EAAE,CAAC;IACvF,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC;AAClC,CAAC","sourcesContent":["/**\n * The signed pending request: what an agent stores when a tool call waits for a person, and what it checks before the\n * call runs. The signature covers D5's six fields in D5's order (request id, kind, call id, tool name, input hash and\n * the optional policy version), so a stored pause whose call, tool or input changed no longer verifies. The shapes\n * match build-sdk.md §3.3 field for field, because our SDK re-exports them.\n */\nimport { constantTimeEqual } from \"./bytes.js\";\nimport { SafetyError } from \"./errors.js\";\nimport { canonicalInputHash } from \"./hash.js\";\nimport type { ApprovalSigner } from \"./signer.js\";\n\n/**\n * A pause waiting for a person: an approval of one tool call, or a question about it. `signature` signs `id`, `kind`,\n * `callId`, `tool`, `inputHash` and `policyVersion` under the key `keyId` names. `question`, `reason` and `createdAt`\n * are shown to people and aren't signed, so never let them decide anything.\n */\nexport interface SignedPendingRequest {\n /** The request's own id, which a `Resolution` names. */\n id: string;\n /** `approval` waits for allow or deny; `clarification` waits for an answer. */\n kind: \"approval\" | \"clarification\";\n /** The id of the tool call that waits. */\n callId: string;\n /** The tool's name. */\n tool: string;\n /** `canonicalInputHash()` of the call's input. */\n inputHash: string;\n /** The version of the policy that asked for the pause, if the host versions its policy. */\n policyVersion?: string;\n /** The question a clarification asks. */\n question?: string;\n /** Why the call needs a person, as shown to the approver. */\n reason?: string;\n /** The id of the key that made `signature`. */\n keyId: string;\n /** The signature, as base64url. */\n signature: string;\n /** When the request was signed, as an ISO 8601 timestamp. */\n createdAt: string;\n}\n\n/** A person's answer to a pending request: allow or deny for an approval, an answer for a clarification. */\nexport type Resolution =\n | { requestId: string; decision: \"allow\" | \"deny\"; reason?: string; by?: string }\n | { requestId: string; answer: string; by?: string };\n\n/** The fields `signPending()` signs and stores, with the call's input in place of its hash. */\nexport interface PendingFields {\n readonly kind: \"approval\" | \"clarification\";\n readonly callId: string;\n readonly tool: string;\n /** The tool call's input. `signPending()` stores its `canonicalInputHash()`, never the input itself. */\n readonly input: unknown;\n readonly policyVersion?: string;\n readonly question?: string;\n readonly reason?: string;\n}\n\n/** Where `signPending()` takes its request id and time from. Tests pass fixed ones. */\nexport interface SignPendingOptions {\n /** Returns a fresh request id. Defaults to `crypto.randomUUID()`. */\n readonly generateId?: () => string;\n /** Returns the current time. Defaults to `new Date()`. */\n readonly now?: () => Date;\n}\n\n/** The call a host is about to run, which a pending request must match before it runs. */\nexport interface PendingCall {\n readonly callId: string;\n readonly tool: string;\n readonly input: unknown;\n}\n\n/**\n * Why `verifyResolution()` refused. `malformed`: the stored request isn't a well-formed pending request.\n * `unknown_request`: the resolution names another request. `signature_invalid`: the signature is wrong, or its key id\n * isn't in the ring. `call_mismatch`: the call id or tool differs from the call about to run. `input_changed`: the\n * input differs from the one that was signed. `resolution_mismatch`: the resolution doesn't fit the request's kind.\n */\nexport type RejectionCause =\n | \"malformed\"\n | \"unknown_request\"\n | \"signature_invalid\"\n | \"call_mismatch\"\n | \"input_changed\"\n | \"resolution_mismatch\";\n\n/** What `verifyResolution()` returns: the resolution, once every check passed, or why it refused. */\nexport type ResolutionCheck =\n | { readonly ok: true; readonly resolution: Resolution }\n | { readonly ok: false; readonly cause: RejectionCause };\n\n/** The options of `verifyResolution()`. */\nexport interface VerifyResolutionOptions {\n /** A signer that holds the key the request names. */\n readonly signer: ApprovalSigner;\n /** The call about to run, as the host has it now, not as the pending request records it. */\n readonly call: PendingCall;\n}\n\n// Ties a signature to this record and its layout, so it can't verify as some other signed record of this package.\nconst PAYLOAD_TAG = \"buildanagent.pending.v1\";\nconst KINDS: readonly string[] = [\"approval\", \"clarification\"];\nconst INPUT_HASH = /^[0-9a-f]{64}$/;\nconst ENCODER = new TextEncoder();\n\nfunction isText(value: unknown): value is string {\n return typeof value === \"string\" && value !== \"\" && value.isWellFormed();\n}\n\nfunction isOptionalText(value: unknown): boolean {\n return value === undefined || isText(value);\n}\n\n/** True when `value` has the shape of a pending request; a store's record is untrusted until this and the signature pass. */\nfunction isWellFormed(value: unknown): value is SignedPendingRequest {\n if (typeof value !== \"object\" || value === null) return false;\n const p = value as Record<string, unknown>;\n return (\n [p.id, p.callId, p.tool, p.keyId, p.signature, p.createdAt].every(isText) &&\n KINDS.includes(p.kind as string) &&\n typeof p.inputHash === \"string\" &&\n INPUT_HASH.test(p.inputHash) &&\n [p.policyVersion, p.question, p.reason].every(isOptionalText)\n );\n}\n\n/**\n * The bytes a pending request's signature covers: a JSON array of a fixed tag, then the request id, kind, call id,\n * tool name, input hash and policy version, in that order, with `null` for an absent policy version. Every field is a well-formed string, so `JSON.stringify` writes the same bytes\n * on every runtime.\n */\nexport function pendingPayload(\n fields: Pick<SignedPendingRequest, \"id\" | \"kind\" | \"callId\" | \"tool\" | \"inputHash\" | \"policyVersion\">,\n): Uint8Array {\n const { id, kind, callId, tool, inputHash, policyVersion } = fields;\n return ENCODER.encode(JSON.stringify([PAYLOAD_TAG, id, kind, callId, tool, inputHash, policyVersion ?? null]));\n}\n\nfunction checkFields(fields: PendingFields, id: unknown): void {\n const bad = (what: string) => new SafetyError(\"invalid_pending\", `a pending request's ${what}`);\n if (!isText(id)) throw bad(\"id must be a non-empty, well-formed string\");\n if (!KINDS.includes(fields.kind)) throw bad(`kind must be \"approval\" or \"clarification\"`);\n for (const field of [\"callId\", \"tool\"] as const) {\n if (!isText(fields[field])) throw bad(`${field} must be a non-empty, well-formed string`);\n }\n for (const field of [\"policyVersion\", \"question\", \"reason\"] as const) {\n if (!isOptionalText(fields[field])) throw bad(`${field} must be a non-empty, well-formed string when it is set`);\n }\n}\n\n/**\n * Signs a pending request for a tool call. It hashes the input with `canonicalInputHash()`, signs the six fields\n * `pendingPayload()` lists with the signer's current key, and returns the request to store. The input itself isn't stored.\n *\n * Throws a `SafetyError`, code `invalid_pending`, for a blank or malformed field, and code `invalid_input` for an\n * input with no canonical JSON form.\n */\nexport async function signPending(\n fields: PendingFields,\n signer: ApprovalSigner,\n options: SignPendingOptions = {},\n): Promise<SignedPendingRequest> {\n const id = (options.generateId ?? (() => crypto.randomUUID()))();\n checkFields(fields, id);\n const inputHash = await canonicalInputHash(fields.input);\n const signed = { id, kind: fields.kind, callId: fields.callId, tool: fields.tool, inputHash };\n const withPolicy = fields.policyVersion === undefined ? signed : { ...signed, policyVersion: fields.policyVersion };\n const signature = await signer.sign(pendingPayload(withPolicy));\n return {\n ...withPolicy,\n ...(fields.question === undefined ? {} : { question: fields.question }),\n ...(fields.reason === undefined ? {} : { reason: fields.reason }),\n keyId: signer.keyId,\n signature,\n createdAt: (options.now ?? (() => new Date()))().toISOString(),\n };\n}\n\nfunction fitsKind(pending: SignedPendingRequest, resolution: Resolution): boolean {\n if (pending.kind === \"approval\") {\n return \"decision\" in resolution && (resolution.decision === \"allow\" || resolution.decision === \"deny\");\n }\n return \"answer\" in resolution && typeof resolution.answer === \"string\";\n}\n\nasync function inputMatches(pending: SignedPendingRequest, input: unknown): Promise<boolean> {\n try {\n return constantTimeEqual(ENCODER.encode(await canonicalInputHash(input)), ENCODER.encode(pending.inputHash));\n } catch {\n // An input with no canonical form can't be the one that was signed, which had one.\n return false;\n }\n}\n\n/**\n * Checks a resolution against its stored pending request before the call runs, failing closed. It accepts only when\n * the request is well formed, the resolution names it, the signature verifies under a key the signer holds, the call\n * id and tool match the call about to run, that call's input hashes to the signed hash, and the resolution fits the\n * request's kind. Otherwise it returns `ok: false` with the first cause it found, and never throws for bad input.\n *\n * A passing check says the request is authentic and unchanged. It doesn't say current policy still allows the call:\n * check that separately, just before the call runs.\n */\nexport async function verifyResolution(\n pending: unknown,\n resolution: Resolution,\n options: VerifyResolutionOptions,\n): Promise<ResolutionCheck> {\n if (!isWellFormed(pending)) return { ok: false, cause: \"malformed\" };\n if (typeof resolution !== \"object\" || resolution === null || resolution.requestId !== pending.id) {\n return { ok: false, cause: \"unknown_request\" };\n }\n // The signature comes first: until it verifies, no other field of the stored request is trusted.\n if (!(await options.signer.verify(pending.keyId, pendingPayload(pending), pending.signature))) {\n return { ok: false, cause: \"signature_invalid\" };\n }\n const { call } = options;\n if (call.callId !== pending.callId || call.tool !== pending.tool) return { ok: false, cause: \"call_mismatch\" };\n if (!(await inputMatches(pending, call.input))) return { ok: false, cause: \"input_changed\" };\n if (!fitsKind(pending, resolution)) return { ok: false, cause: \"resolution_mismatch\" };\n return { ok: true, resolution };\n}\n\n/**\n * Runs current policy for an approved call just before it runs, after its pending request has verified. Resolve to\n * `\"allow\"` to let the call run, or to `{ deny }` with a reason the model reads, so a policy that changed since the\n * pause can still stop the call.\n */\nexport type Recheck = (pending: SignedPendingRequest, input: unknown) => Promise<\"allow\" | { deny: string }>;\n"]}
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Signs and verifies the payload of a pending request. `keyId` names the key `sign()` uses now; `verify()` accepts a
3
+ * signature from any key the signer holds. `verify()` resolves to `false` for an unknown key id or a malformed or
4
+ * wrong signature, and never throws for bad input.
5
+ */
6
+ export interface ApprovalSigner {
7
+ /** The id of the key that `sign()` uses. */
8
+ readonly keyId: string;
9
+ /** Signs `payload` with the current key. */
10
+ sign(payload: Uint8Array): Promise<string>;
11
+ /** True only when `signature` is the signature of `payload` under the key named `keyId`. */
12
+ verify(keyId: string, payload: Uint8Array, signature: string): Promise<boolean>;
13
+ }
14
+ /** The options of `hmacSigner()`: every key the signer may verify with, by id, and the id of the one it signs with. */
15
+ export interface HmacSignerOptions {
16
+ /** Each key's raw bytes, at least 32 of them, under its key id. */
17
+ readonly keys: Readonly<Record<string, Uint8Array>>;
18
+ /** The id of the key that signs. It must be one of `keys`. */
19
+ readonly current: string;
20
+ }
21
+ /** The shortest key `hmacSigner()` accepts: one SHA-256 output, the length RFC 2104 recommends as the minimum. */
22
+ export declare const MIN_KEY_BYTES = 32;
23
+ /**
24
+ * A signer over a key ring, for any host where a pause may resume in another process: it signs with the key named
25
+ * `current` and verifies with any key in `keys`. To rotate, add a new key, make it current, and keep the old one in
26
+ * the ring until no unresolved pause names it.
27
+ *
28
+ * The keys are copied, so later changes to the arrays you pass have no effect. Throws a `SafetyError`, code
29
+ * `invalid_key_ring`, for an empty ring, a key shorter than 32 bytes, a malformed key id, or a `current` that isn't in
30
+ * the ring. No error, log line or signer property ever holds a key's bytes.
31
+ */
32
+ export declare function hmacSigner(options: HmacSignerOptions): ApprovalSigner;
33
+ /**
34
+ * A signer whose key is random and lives only in this process: every call in one process returns the same signer, and
35
+ * no other process can verify what it signs. Its key id is random too, so another process rejects the signature as
36
+ * one from an unknown key.
37
+ *
38
+ * Use it only where a pause resumes in the process that made it. On a serverless host an isolate or function can be
39
+ * recycled between a pause and its resume, and the pause then fails closed; pass `hmacSigner()` over a persistent key
40
+ * ring there instead.
41
+ */
42
+ export declare function ephemeralSigner(): ApprovalSigner;
@@ -0,0 +1,128 @@
1
+ /**
2
+ * The approval signers. Every signature names the key that made it, so a verifier can hold a ring of keys and rotate
3
+ * the current one without stranding stored pauses (D5, ADR 0005). Each signer is HMAC-SHA-256 through Web Crypto, and
4
+ * a key's bytes stay inside a non-extractable `CryptoKey` once imported: no signer exposes, logs or serializes a key.
5
+ * Web Crypto is the bare `crypto` global, as in hash.ts, so the file type-checks against the Workers types too.
6
+ */
7
+ import { constantTimeEqual, fromBase64Url, toBase64Url } from "./bytes.js";
8
+ import { SafetyError } from "./errors.js";
9
+ const HMAC = { name: "HMAC", hash: "SHA-256" };
10
+ const MAC_BYTES = 32;
11
+ /** The shortest key `hmacSigner()` accepts: one SHA-256 output, the length RFC 2104 recommends as the minimum. */
12
+ export const MIN_KEY_BYTES = 32;
13
+ // Key ids are written into stored records and may appear in logs, so they are short and plain.
14
+ const KEY_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/;
15
+ function invalidRing(message) {
16
+ return new SafetyError("invalid_key_ring", message);
17
+ }
18
+ function checkKeyId(keyId, what) {
19
+ if (typeof keyId !== "string" || !KEY_ID.test(keyId)) {
20
+ throw invalidRing(`${what} must be 1 to 64 letters, digits, '.', '_', ':' or '-', starting with a letter or digit`);
21
+ }
22
+ return keyId;
23
+ }
24
+ /** A signer over `keyFor`, which returns the key for an id it holds and `undefined` for any other. */
25
+ function macSigner(keyId, keyFor) {
26
+ // A copy of the view's own bytes: `new Uint8Array(view)` would read a DataView as empty and convert a wider typed
27
+ // array element by element, so two different payloads could share a MAC.
28
+ const bytesOf = (payload) => new Uint8Array(payload.buffer, payload.byteOffset, payload.byteLength).slice();
29
+ const mac = async (key, payload) => new Uint8Array(await crypto.subtle.sign("HMAC", await key, bytesOf(payload)));
30
+ return Object.freeze({
31
+ keyId,
32
+ async sign(payload) {
33
+ if (!ArrayBuffer.isView(payload))
34
+ throw new SafetyError("invalid_pending", "a signed payload must be bytes");
35
+ // keyFor() holds the current key by construction, so it is present.
36
+ const key = keyFor(keyId);
37
+ return toBase64Url(await mac(key, payload));
38
+ },
39
+ async verify(id, payload, signature) {
40
+ if (typeof id !== "string" || typeof signature !== "string" || !ArrayBuffer.isView(payload))
41
+ return false;
42
+ const key = keyFor(id);
43
+ if (key === undefined)
44
+ return false;
45
+ const given = fromBase64Url(signature);
46
+ if (given === undefined || given.length !== MAC_BYTES)
47
+ return false;
48
+ // Recompute and compare in constant time, rather than trust the runtime's verify() to be constant-time.
49
+ return constantTimeEqual(given, await mac(key, payload));
50
+ },
51
+ });
52
+ }
53
+ /** Copies each key, so a caller that later changes its array can't change the ring, and checks ids and lengths. */
54
+ function copyRing(keys) {
55
+ if (typeof keys !== "object" || keys === null)
56
+ throw invalidRing("keys must be an object of key id to key bytes");
57
+ const ring = new Map();
58
+ for (const [id, bytes] of Object.entries(keys)) {
59
+ checkKeyId(id, `the key id ${JSON.stringify(id)}`);
60
+ if (!(bytes instanceof Uint8Array) || bytes.length < MIN_KEY_BYTES) {
61
+ // The message names the key id only: a key's bytes never reach an error, a log or a stored record.
62
+ throw invalidRing(`the key ${JSON.stringify(id)} must be a Uint8Array of at least ${MIN_KEY_BYTES} bytes`);
63
+ }
64
+ ring.set(id, new Uint8Array(bytes));
65
+ }
66
+ if (ring.size === 0)
67
+ throw invalidRing("keys must hold at least one key");
68
+ return ring;
69
+ }
70
+ /**
71
+ * A signer over a key ring, for any host where a pause may resume in another process: it signs with the key named
72
+ * `current` and verifies with any key in `keys`. To rotate, add a new key, make it current, and keep the old one in
73
+ * the ring until no unresolved pause names it.
74
+ *
75
+ * The keys are copied, so later changes to the arrays you pass have no effect. Throws a `SafetyError`, code
76
+ * `invalid_key_ring`, for an empty ring, a key shorter than 32 bytes, a malformed key id, or a `current` that isn't in
77
+ * the ring. No error, log line or signer property ever holds a key's bytes.
78
+ */
79
+ export function hmacSigner(options) {
80
+ const ring = copyRing(options.keys);
81
+ const current = checkKeyId(options.current, "current");
82
+ if (!ring.has(current))
83
+ throw invalidRing(`current names the key ${JSON.stringify(current)}, which keys lacks`);
84
+ const imported = new Map();
85
+ return macSigner(current, (id) => {
86
+ const cached = imported.get(id);
87
+ if (cached !== undefined)
88
+ return cached;
89
+ const bytes = ring.get(id);
90
+ if (bytes === undefined)
91
+ return undefined;
92
+ const key = crypto.subtle.importKey("raw", bytes, HMAC, false, ["sign"]);
93
+ imported.set(id, key);
94
+ // The CryptoKey now holds the key, so the copy is wiped and dropped.
95
+ bytes.fill(0);
96
+ ring.delete(id);
97
+ return key;
98
+ });
99
+ }
100
+ let ephemeral;
101
+ function hex(bytes) {
102
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
103
+ }
104
+ /**
105
+ * A signer whose key is random and lives only in this process: every call in one process returns the same signer, and
106
+ * no other process can verify what it signs. Its key id is random too, so another process rejects the signature as
107
+ * one from an unknown key.
108
+ *
109
+ * Use it only where a pause resumes in the process that made it. On a serverless host an isolate or function can be
110
+ * recycled between a pause and its resume, and the pause then fails closed; pass `hmacSigner()` over a persistent key
111
+ * ring there instead.
112
+ */
113
+ export function ephemeralSigner() {
114
+ if (ephemeral === undefined) {
115
+ const keyId = `ephemeral-${hex(crypto.getRandomValues(new Uint8Array(8)))}`;
116
+ let key;
117
+ ephemeral = macSigner(keyId, (id) => {
118
+ if (id !== keyId)
119
+ return undefined;
120
+ // Generated on first use and never extractable, so the key's bytes never exist outside Web Crypto. An HMAC key
121
+ // is one secret key, never a pair, which the Workers types' wider return type doesn't express.
122
+ key ??= crypto.subtle.generateKey({ ...HMAC, length: 256 }, false, ["sign"]);
123
+ return key;
124
+ });
125
+ }
126
+ return ephemeral;
127
+ }
128
+ //# sourceMapping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,EAAE,EAAE,KAAK,EAAE,CAAC,MAAM,CAAC,CAAuB,CAAC;YACnG,OAAO,GAAG,CAAC;QACb,CAAC,CAAC,CAAC;IACL,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["/**\n * The approval signers. Every signature names the key that made it, so a verifier can hold a ring of keys and rotate\n * the current one without stranding stored pauses (D5, ADR 0005). Each signer is HMAC-SHA-256 through Web Crypto, and\n * a key's bytes stay inside a non-extractable `CryptoKey` once imported: no signer exposes, logs or serializes a key.\n * Web Crypto is the bare `crypto` global, as in hash.ts, so the file type-checks against the Workers types too.\n */\nimport { constantTimeEqual, fromBase64Url, toBase64Url } from \"./bytes.js\";\nimport { SafetyError } from \"./errors.js\";\n\n/**\n * Signs and verifies the payload of a pending request. `keyId` names the key `sign()` uses now; `verify()` accepts a\n * signature from any key the signer holds. `verify()` resolves to `false` for an unknown key id or a malformed or\n * wrong signature, and never throws for bad input.\n */\nexport interface ApprovalSigner {\n /** The id of the key that `sign()` uses. */\n readonly keyId: string;\n /** Signs `payload` with the current key. */\n sign(payload: Uint8Array): Promise<string>;\n /** True only when `signature` is the signature of `payload` under the key named `keyId`. */\n verify(keyId: string, payload: Uint8Array, signature: string): Promise<boolean>;\n}\n\n/** The options of `hmacSigner()`: every key the signer may verify with, by id, and the id of the one it signs with. */\nexport interface HmacSignerOptions {\n /** Each key's raw bytes, at least 32 of them, under its key id. */\n readonly keys: Readonly<Record<string, Uint8Array>>;\n /** The id of the key that signs. It must be one of `keys`. */\n readonly current: string;\n}\n\nconst HMAC = { name: \"HMAC\", hash: \"SHA-256\" } as const;\nconst MAC_BYTES = 32;\n/** The shortest key `hmacSigner()` accepts: one SHA-256 output, the length RFC 2104 recommends as the minimum. */\nexport const MIN_KEY_BYTES = 32;\n// Key ids are written into stored records and may appear in logs, so they are short and plain.\nconst KEY_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/;\n\nfunction invalidRing(message: string): SafetyError {\n return new SafetyError(\"invalid_key_ring\", message);\n}\n\nfunction checkKeyId(keyId: unknown, what: string): string {\n if (typeof keyId !== \"string\" || !KEY_ID.test(keyId)) {\n throw invalidRing(`${what} must be 1 to 64 letters, digits, '.', '_', ':' or '-', starting with a letter or digit`);\n }\n return keyId;\n}\n\n/** A signer over `keyFor`, which returns the key for an id it holds and `undefined` for any other. */\nfunction macSigner(keyId: string, keyFor: (id: string) => Promise<CryptoKey> | undefined): ApprovalSigner {\n // A copy of the view's own bytes: `new Uint8Array(view)` would read a DataView as empty and convert a wider typed\n // array element by element, so two different payloads could share a MAC.\n const bytesOf = (payload: ArrayBufferView) =>\n new Uint8Array(payload.buffer, payload.byteOffset, payload.byteLength).slice();\n const mac = async (key: Promise<CryptoKey>, payload: ArrayBufferView) =>\n new Uint8Array(await crypto.subtle.sign(\"HMAC\", await key, bytesOf(payload)));\n return Object.freeze({\n keyId,\n async sign(payload: Uint8Array): Promise<string> {\n if (!ArrayBuffer.isView(payload)) throw new SafetyError(\"invalid_pending\", \"a signed payload must be bytes\");\n // keyFor() holds the current key by construction, so it is present.\n const key = keyFor(keyId) as Promise<CryptoKey>;\n return toBase64Url(await mac(key, payload));\n },\n async verify(id: string, payload: Uint8Array, signature: string): Promise<boolean> {\n if (typeof id !== \"string\" || typeof signature !== \"string\" || !ArrayBuffer.isView(payload)) return false;\n const key = keyFor(id);\n if (key === undefined) return false;\n const given = fromBase64Url(signature);\n if (given === undefined || given.length !== MAC_BYTES) return false;\n // Recompute and compare in constant time, rather than trust the runtime's verify() to be constant-time.\n return constantTimeEqual(given, await mac(key, payload));\n },\n });\n}\n\n/** Copies each key, so a caller that later changes its array can't change the ring, and checks ids and lengths. */\nfunction copyRing(keys: unknown): Map<string, Uint8Array<ArrayBuffer>> {\n if (typeof keys !== \"object\" || keys === null) throw invalidRing(\"keys must be an object of key id to key bytes\");\n const ring = new Map<string, Uint8Array<ArrayBuffer>>();\n for (const [id, bytes] of Object.entries(keys)) {\n checkKeyId(id, `the key id ${JSON.stringify(id)}`);\n if (!(bytes instanceof Uint8Array) || bytes.length < MIN_KEY_BYTES) {\n // The message names the key id only: a key's bytes never reach an error, a log or a stored record.\n throw invalidRing(`the key ${JSON.stringify(id)} must be a Uint8Array of at least ${MIN_KEY_BYTES} bytes`);\n }\n ring.set(id, new Uint8Array(bytes));\n }\n if (ring.size === 0) throw invalidRing(\"keys must hold at least one key\");\n return ring;\n}\n\n/**\n * A signer over a key ring, for any host where a pause may resume in another process: it signs with the key named\n * `current` and verifies with any key in `keys`. To rotate, add a new key, make it current, and keep the old one in\n * the ring until no unresolved pause names it.\n *\n * The keys are copied, so later changes to the arrays you pass have no effect. Throws a `SafetyError`, code\n * `invalid_key_ring`, for an empty ring, a key shorter than 32 bytes, a malformed key id, or a `current` that isn't in\n * the ring. No error, log line or signer property ever holds a key's bytes.\n */\nexport function hmacSigner(options: HmacSignerOptions): ApprovalSigner {\n const ring = copyRing(options.keys);\n const current = checkKeyId(options.current, \"current\");\n if (!ring.has(current)) throw invalidRing(`current names the key ${JSON.stringify(current)}, which keys lacks`);\n const imported = new Map<string, Promise<CryptoKey>>();\n return macSigner(current, (id) => {\n const cached = imported.get(id);\n if (cached !== undefined) return cached;\n const bytes = ring.get(id);\n if (bytes === undefined) return undefined;\n const key = crypto.subtle.importKey(\"raw\", bytes, HMAC, false, [\"sign\"]);\n imported.set(id, key);\n // The CryptoKey now holds the key, so the copy is wiped and dropped.\n bytes.fill(0);\n ring.delete(id);\n return key;\n });\n}\n\nlet ephemeral: ApprovalSigner | undefined;\n\nfunction hex(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * A signer whose key is random and lives only in this process: every call in one process returns the same signer, and\n * no other process can verify what it signs. Its key id is random too, so another process rejects the signature as\n * one from an unknown key.\n *\n * Use it only where a pause resumes in the process that made it. On a serverless host an isolate or function can be\n * recycled between a pause and its resume, and the pause then fails closed; pass `hmacSigner()` over a persistent key\n * ring there instead.\n */\nexport function ephemeralSigner(): ApprovalSigner {\n if (ephemeral === undefined) {\n const keyId = `ephemeral-${hex(crypto.getRandomValues(new Uint8Array(8)))}`;\n let key: Promise<CryptoKey> | undefined;\n ephemeral = macSigner(keyId, (id) => {\n if (id !== keyId) return undefined;\n // Generated on first use and never extractable, so the key's bytes never exist outside Web Crypto. An HMAC key\n // is one secret key, never a pair, which the Workers types' wider return type doesn't express.\n key ??= crypto.subtle.generateKey({ ...HMAC, length: 256 }, false, [\"sign\"]) as Promise<CryptoKey>;\n return key;\n });\n }\n return ephemeral;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@buildanagent/sdk",
3
- "version": "0.1.0-alpha.7",
3
+ "version": "0.1.0-alpha.9",
4
4
  "description": "The buildanagent SDK: the agent loop, tools, hooks, signed pauses and budgets over the gateway.",
5
5
  "license": "Apache-2.0 OR MIT",
6
6
  "repository": {
@@ -37,10 +37,12 @@
37
37
  "dependencies": {
38
38
  "@earendil-works/pi-schema": "1.5.2",
39
39
  "@standard-schema/spec": "1.1.0",
40
- "@buildanagent/gateway": "0.1.0-alpha.7"
40
+ "@buildanagent/gateway": "0.1.0-alpha.9"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@cfworker/json-schema": "4.1.6",
44
+ "@opentelemetry/api": "1.9.1",
45
+ "@opentelemetry/sdk-trace": "2.12.1",
44
46
  "miniflare": "5.20261103.0-beta",
45
47
  "zod": "4.6.7",
46
48
  "@buildanagent/agent-safety": "0.0.0"