@buildanagent/sdk 0.1.0-alpha.1 → 0.1.0-alpha.11

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 (116) hide show
  1. package/README.md +424 -5
  2. package/dist/budget.d.ts +33 -0
  3. package/dist/budget.js +55 -0
  4. package/dist/budget.js.map +1 -0
  5. package/dist/compose.d.ts +26 -0
  6. package/dist/compose.js +157 -0
  7. package/dist/compose.js.map +1 -0
  8. package/dist/errors.d.ts +49 -0
  9. package/dist/errors.js +57 -0
  10. package/dist/errors.js.map +1 -0
  11. package/dist/events.d.ts +168 -0
  12. package/dist/events.js +32 -0
  13. package/dist/events.js.map +1 -0
  14. package/dist/freeze.d.ts +11 -0
  15. package/dist/freeze.js +42 -0
  16. package/dist/freeze.js.map +1 -0
  17. package/dist/hook-checks.d.ts +31 -0
  18. package/dist/hook-checks.js +130 -0
  19. package/dist/hook-checks.js.map +1 -0
  20. package/dist/hook-runner.d.ts +96 -0
  21. package/dist/hook-runner.js +372 -0
  22. package/dist/hook-runner.js.map +1 -0
  23. package/dist/hooks.d.ts +183 -0
  24. package/dist/hooks.js +2 -0
  25. package/dist/hooks.js.map +1 -0
  26. package/dist/index.d.ts +26 -3
  27. package/dist/index.js +21 -3
  28. package/dist/index.js.map +1 -1
  29. package/dist/loop.d.ts +67 -0
  30. package/dist/loop.js +644 -0
  31. package/dist/loop.js.map +1 -0
  32. package/dist/observers.d.ts +31 -0
  33. package/dist/observers.js +98 -0
  34. package/dist/observers.js.map +1 -0
  35. package/dist/otel/attributes.d.ts +43 -0
  36. package/dist/otel/attributes.js +50 -0
  37. package/dist/otel/attributes.js.map +1 -0
  38. package/dist/otel/content.d.ts +17 -0
  39. package/dist/otel/content.js +48 -0
  40. package/dist/otel/content.js.map +1 -0
  41. package/dist/otel/index.d.ts +6 -2
  42. package/dist/otel/index.js +6 -2
  43. package/dist/otel/index.js.map +1 -1
  44. package/dist/otel/observer.d.ts +82 -0
  45. package/dist/otel/observer.js +300 -0
  46. package/dist/otel/observer.js.map +1 -0
  47. package/dist/pauses.d.ts +61 -0
  48. package/dist/pauses.js +83 -0
  49. package/dist/pauses.js.map +1 -0
  50. package/dist/progress.d.ts +34 -0
  51. package/dist/progress.js +139 -0
  52. package/dist/progress.js.map +1 -0
  53. package/dist/result.d.ts +134 -0
  54. package/dist/result.js +2 -0
  55. package/dist/result.js.map +1 -0
  56. package/dist/resume.d.ts +76 -0
  57. package/dist/resume.js +237 -0
  58. package/dist/resume.js.map +1 -0
  59. package/dist/run.d.ts +214 -0
  60. package/dist/run.js +327 -0
  61. package/dist/run.js.map +1 -0
  62. package/dist/steering.d.ts +52 -0
  63. package/dist/steering.js +104 -0
  64. package/dist/steering.js.map +1 -0
  65. package/dist/testing/scripted-model.d.ts +12 -2
  66. package/dist/testing/scripted-model.js +19 -2
  67. package/dist/testing/scripted-model.js.map +1 -1
  68. package/dist/tools/coerce.d.ts +15 -0
  69. package/dist/tools/coerce.js +93 -0
  70. package/dist/tools/coerce.js.map +1 -0
  71. package/dist/tools/define.d.ts +54 -0
  72. package/dist/tools/define.js +121 -0
  73. package/dist/tools/define.js.map +1 -0
  74. package/dist/tools/format-error.d.ts +13 -0
  75. package/dist/tools/format-error.js +66 -0
  76. package/dist/tools/format-error.js.map +1 -0
  77. package/dist/tools/outcome.d.ts +7 -0
  78. package/dist/tools/outcome.js +30 -0
  79. package/dist/tools/outcome.js.map +1 -0
  80. package/dist/tools/pipeline.d.ts +111 -0
  81. package/dist/tools/pipeline.js +382 -0
  82. package/dist/tools/pipeline.js.map +1 -0
  83. package/dist/tools/scheduler.d.ts +33 -0
  84. package/dist/tools/scheduler.js +51 -0
  85. package/dist/tools/scheduler.js.map +1 -0
  86. package/dist/tools/schema.d.ts +20 -0
  87. package/dist/tools/schema.js +100 -0
  88. package/dist/tools/schema.js.map +1 -0
  89. package/dist/tools/types.d.ts +196 -0
  90. package/dist/tools/types.js +2 -0
  91. package/dist/tools/types.js.map +1 -0
  92. package/dist/vendor/agent-safety/bytes.d.ts +17 -0
  93. package/dist/vendor/agent-safety/bytes.js +59 -0
  94. package/dist/vendor/agent-safety/bytes.js.map +1 -0
  95. package/dist/vendor/agent-safety/errors.d.ts +23 -0
  96. package/dist/vendor/agent-safety/errors.js +22 -0
  97. package/dist/vendor/agent-safety/errors.js.map +1 -0
  98. package/dist/vendor/agent-safety/hash.d.ts +16 -0
  99. package/dist/vendor/agent-safety/hash.js +110 -0
  100. package/dist/vendor/agent-safety/hash.js.map +1 -0
  101. package/dist/vendor/agent-safety/outcome.d.ts +88 -0
  102. package/dist/vendor/agent-safety/outcome.js +140 -0
  103. package/dist/vendor/agent-safety/outcome.js.map +1 -0
  104. package/dist/vendor/agent-safety/pending.d.ts +119 -0
  105. package/dist/vendor/agent-safety/pending.js +122 -0
  106. package/dist/vendor/agent-safety/pending.js.map +1 -0
  107. package/dist/vendor/agent-safety/render.d.ts +40 -0
  108. package/dist/vendor/agent-safety/render.js +92 -0
  109. package/dist/vendor/agent-safety/render.js.map +1 -0
  110. package/dist/vendor/agent-safety/signer.d.ts +42 -0
  111. package/dist/vendor/agent-safety/signer.js +128 -0
  112. package/dist/vendor/agent-safety/signer.js.map +1 -0
  113. package/dist/version.d.ts +2 -0
  114. package/dist/version.js +8 -0
  115. package/dist/version.js.map +1 -0
  116. package/package.json +13 -3
@@ -0,0 +1,92 @@
1
+ /**
2
+ * `renderOutcome()`: turns a write outcome into what the model reads. The outcome travels in the tool result's body,
3
+ * as a sentence and a structured payload, with the provider's error flag set as well, because some adapters drop the
4
+ * flag and some SDKs hide text blocks once structured content is set (server rollback report).
5
+ */
6
+ import { writeOutcome } from "./outcome.js";
7
+ // What happened, per kind. `{op}` is the operation's name.
8
+ const HAPPENED = {
9
+ applied: "The {op} call took effect.",
10
+ not_applied: "The {op} call did not take effect, and nothing changed.",
11
+ compensated: "The {op} call took effect and was then undone.",
12
+ partial: "The {op} call only partly took effect, and the rest could not be undone.",
13
+ unknown: "It is not known whether the {op} call took effect.",
14
+ };
15
+ // What the model must not do, per kind, from the server rollback report's outcome table.
16
+ const MUST_NOT = {
17
+ applied: "Do not run it again for the same request.",
18
+ not_applied: "Do not say that it happened.",
19
+ compensated: "Do not say that it took effect, and do not hide what could not be undone.",
20
+ partial: "Do not present it as a success.",
21
+ unknown: "Do not say that it happened or that it failed, and do not retry it as a new request.",
22
+ };
23
+ // What a retry may look like, per rule. `applied` takes no retry sentence, because its kind sentence covers it.
24
+ const RETRY = {
25
+ same_key: "Retrying this same call is safe; it takes effect at most once.",
26
+ new_operation_only: "Try again only as a new request, and only if the user still wants it.",
27
+ reconcile_first: "Check its current status before any retry.",
28
+ never: "Do not retry it.",
29
+ };
30
+ // A same-key retry with no key is safe only for not_applied, whose first attempt changed nothing.
31
+ const KEYLESS_SAME_KEY = "Retrying this same call is safe, because this attempt changed nothing.";
32
+ function sentence(text) {
33
+ const trimmed = text.trim();
34
+ return /[.!?]$/.test(trimmed) ? trimmed : `${trimmed}.`;
35
+ }
36
+ function effects(label, list) {
37
+ // Each effect loses its own end punctuation, so "email sent." doesn't render as "email sent..".
38
+ const items = list.map((item) => item.trim().replace(/[.!?]+$/, ""));
39
+ return items.length === 0 ? [] : [`${label}: ${items.join("; ")}.`];
40
+ }
41
+ // A same-key retry takes effect at most once only when there is a key. renderOutcome() checks the outcome first, and
42
+ // writeOutcome() allows a keyless one only for not_applied, so only that kind reaches the keyless sentence.
43
+ function retrySentence(outcome) {
44
+ if (outcome.retry === "same_key" && outcome.effectKey === undefined && outcome.kind === "not_applied") {
45
+ return KEYLESS_SAME_KEY;
46
+ }
47
+ return RETRY[outcome.retry];
48
+ }
49
+ function describe(outcome) {
50
+ const parts = [
51
+ // A function replacer, so `$&` or `$'` in an operation's name is copied, not read as a replacement pattern.
52
+ HAPPENED[outcome.kind].replace("{op}", () => outcome.operation),
53
+ ...effects("Still in effect", outcome.applied),
54
+ ...effects("Undone", outcome.reverted),
55
+ ...effects("Cannot be undone", outcome.notReversible),
56
+ ...(outcome.currentState === undefined ? [] : [`Current state: ${sentence(outcome.currentState)}`]),
57
+ `Next: ${sentence(outcome.next)}`,
58
+ ...(outcome.kind === "applied" ? [] : [retrySentence(outcome)]),
59
+ MUST_NOT[outcome.kind],
60
+ ...(outcome.avoid === undefined ? [] : [sentence(outcome.avoid)]),
61
+ ];
62
+ return parts.join(" ");
63
+ }
64
+ function toPayload(outcome) {
65
+ return {
66
+ kind: outcome.kind,
67
+ operation: outcome.operation,
68
+ ...(outcome.effectKey === undefined ? {} : { effectKey: outcome.effectKey }),
69
+ applied: [...outcome.applied],
70
+ reverted: [...outcome.reverted],
71
+ notReversible: [...outcome.notReversible],
72
+ ...(outcome.currentState === undefined ? {} : { currentState: outcome.currentState }),
73
+ retry: outcome.retry,
74
+ next: outcome.next,
75
+ ...(outcome.avoid === undefined ? {} : { avoid: outcome.avoid }),
76
+ ...(outcome.reason === undefined ? {} : { reason: outcome.reason }),
77
+ };
78
+ }
79
+ /**
80
+ * Renders a write outcome for the model: sentences that name what happened, what to do next and what not to do, the
81
+ * outcome's fields as a JSON payload, and whether the provider's error flag should be set. Put both the text and the
82
+ * payload in the tool result, because some SDKs show the model only one of them. It first checks the outcome as
83
+ * `writeOutcome()` does, so an outcome built by hand that breaks a rule throws a `SafetyError`, code
84
+ * `invalid_outcome`.
85
+ */
86
+ export function renderOutcome(outcome) {
87
+ // `WriteOutcome` is a plain type, so a tool can build one as a literal or revive one from JSON. Checking it again
88
+ // here holds every outcome the model reads to the rules writeOutcome() enforces.
89
+ const checked = writeOutcome(outcome);
90
+ return { text: describe(checked), payload: toPayload(checked), isError: checked.kind !== "applied" };
91
+ }
92
+ //# sourceMappingURL=render.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render.js","sourceRoot":"","sources":["../../../src/vendor/agent-safety/render.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAmD,YAAY,EAAE,MAAM,cAAc,CAAC;AA8B7F,2DAA2D;AAC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AACvG,CAAC","sourcesContent":["/**\n * `renderOutcome()`: turns a write outcome into what the model reads. The outcome travels in the tool result's body,\n * as a sentence and a structured payload, with the provider's error flag set as well, because some adapters drop the\n * flag and some SDKs hide text blocks once structured content is set (server rollback report).\n */\nimport { type OutcomeKind, type Retry, type WriteOutcome, writeOutcome } from \"./outcome.js\";\n\n/**\n * The structured half of a rendered outcome: the outcome's own fields, as plain JSON. Optional fields the outcome\n * leaves out are left out here too.\n */\nexport type OutcomePayload = {\n readonly kind: OutcomeKind;\n readonly operation: string;\n readonly effectKey?: string;\n readonly applied: readonly string[];\n readonly reverted: readonly string[];\n readonly notReversible: readonly string[];\n readonly currentState?: string;\n readonly retry: Retry;\n readonly next: string;\n readonly avoid?: string;\n readonly reason?: string;\n};\n\n/** A write outcome as the model reads it. */\nexport interface RenderedOutcome {\n /** Sentences that say what happened, what to do next and what not to do. */\n readonly text: string;\n /** The outcome's fields, for a model or a harness that reads structured results. */\n readonly payload: OutcomePayload;\n /** True for every kind except `applied`: the provider's error flag, where the provider has one. */\n readonly isError: boolean;\n}\n\n// What happened, per kind. `{op}` is the operation's name.\nconst HAPPENED: { readonly [K in OutcomeKind]: string } = {\n applied: \"The {op} call took effect.\",\n not_applied: \"The {op} call did not take effect, and nothing changed.\",\n compensated: \"The {op} call took effect and was then undone.\",\n partial: \"The {op} call only partly took effect, and the rest could not be undone.\",\n unknown: \"It is not known whether the {op} call took effect.\",\n};\n\n// What the model must not do, per kind, from the server rollback report's outcome table.\nconst MUST_NOT: { readonly [K in OutcomeKind]: string } = {\n applied: \"Do not run it again for the same request.\",\n not_applied: \"Do not say that it happened.\",\n compensated: \"Do not say that it took effect, and do not hide what could not be undone.\",\n partial: \"Do not present it as a success.\",\n unknown: \"Do not say that it happened or that it failed, and do not retry it as a new request.\",\n};\n\n// What a retry may look like, per rule. `applied` takes no retry sentence, because its kind sentence covers it.\nconst RETRY: { readonly [R in Retry]: string } = {\n same_key: \"Retrying this same call is safe; it takes effect at most once.\",\n new_operation_only: \"Try again only as a new request, and only if the user still wants it.\",\n reconcile_first: \"Check its current status before any retry.\",\n never: \"Do not retry it.\",\n};\n\n// A same-key retry with no key is safe only for not_applied, whose first attempt changed nothing.\nconst KEYLESS_SAME_KEY = \"Retrying this same call is safe, because this attempt changed nothing.\";\n\nfunction sentence(text: string): string {\n const trimmed = text.trim();\n return /[.!?]$/.test(trimmed) ? trimmed : `${trimmed}.`;\n}\n\nfunction effects(label: string, list: readonly string[]): string[] {\n // Each effect loses its own end punctuation, so \"email sent.\" doesn't render as \"email sent..\".\n const items = list.map((item) => item.trim().replace(/[.!?]+$/, \"\"));\n return items.length === 0 ? [] : [`${label}: ${items.join(\"; \")}.`];\n}\n\n// A same-key retry takes effect at most once only when there is a key. renderOutcome() checks the outcome first, and\n// writeOutcome() allows a keyless one only for not_applied, so only that kind reaches the keyless sentence.\nfunction retrySentence(outcome: WriteOutcome): string {\n if (outcome.retry === \"same_key\" && outcome.effectKey === undefined && outcome.kind === \"not_applied\") {\n return KEYLESS_SAME_KEY;\n }\n return RETRY[outcome.retry];\n}\n\nfunction describe(outcome: WriteOutcome): string {\n const parts = [\n // A function replacer, so `$&` or `$'` in an operation's name is copied, not read as a replacement pattern.\n HAPPENED[outcome.kind].replace(\"{op}\", () => outcome.operation),\n ...effects(\"Still in effect\", outcome.applied),\n ...effects(\"Undone\", outcome.reverted),\n ...effects(\"Cannot be undone\", outcome.notReversible),\n ...(outcome.currentState === undefined ? [] : [`Current state: ${sentence(outcome.currentState)}`]),\n `Next: ${sentence(outcome.next)}`,\n ...(outcome.kind === \"applied\" ? [] : [retrySentence(outcome)]),\n MUST_NOT[outcome.kind],\n ...(outcome.avoid === undefined ? [] : [sentence(outcome.avoid)]),\n ];\n return parts.join(\" \");\n}\n\nfunction toPayload(outcome: WriteOutcome): OutcomePayload {\n return {\n kind: outcome.kind,\n operation: outcome.operation,\n ...(outcome.effectKey === undefined ? {} : { effectKey: outcome.effectKey }),\n applied: [...outcome.applied],\n reverted: [...outcome.reverted],\n notReversible: [...outcome.notReversible],\n ...(outcome.currentState === undefined ? {} : { currentState: outcome.currentState }),\n retry: outcome.retry,\n next: outcome.next,\n ...(outcome.avoid === undefined ? {} : { avoid: outcome.avoid }),\n ...(outcome.reason === undefined ? {} : { reason: outcome.reason }),\n };\n}\n\n/**\n * Renders a write outcome for the model: sentences that name what happened, what to do next and what not to do, the\n * outcome's fields as a JSON payload, and whether the provider's error flag should be set. Put both the text and the\n * payload in the tool result, because some SDKs show the model only one of them. It first checks the outcome as\n * `writeOutcome()` does, so an outcome built by hand that breaks a rule throws a `SafetyError`, code\n * `invalid_outcome`.\n */\nexport function renderOutcome(outcome: WriteOutcome): RenderedOutcome {\n // `WriteOutcome` is a plain type, so a tool can build one as a literal or revive one from JSON. Checking it again\n // here holds every outcome the model reads to the rules writeOutcome() enforces.\n const checked = writeOutcome(outcome);\n return { text: describe(checked), payload: toPayload(checked), isError: checked.kind !== \"applied\" };\n}\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
+ //# sourceMappingURL=signer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signer.js","sourceRoot":"","sources":["../../../src/vendor/agent-safety/signer.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAC3E,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAwB1C,MAAM,IAAI,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,EAAW,CAAC;AACxD,MAAM,SAAS,GAAG,EAAE,CAAC;AACrB,kHAAkH;AAClH,MAAM,CAAC,MAAM,aAAa,GAAG,EAAE,CAAC;AAChC,+FAA+F;AAC/F,MAAM,MAAM,GAAG,oCAAoC,CAAC;AAEpD,SAAS,WAAW,CAAC,OAAe;IAClC,OAAO,IAAI,WAAW,CAAC,kBAAkB,EAAE,OAAO,CAAC,CAAC;AACtD,CAAC;AAED,SAAS,UAAU,CAAC,KAAc,EAAE,IAAY;IAC9C,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QACrD,MAAM,WAAW,CAAC,GAAG,IAAI,yFAAyF,CA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M,UAAU,eAAe;IAC7B,IAAI,SAAS,KAAK,SAAS,EAAE,CAAC;QAC5B,MAAM,KAAK,GAAG,aAAa,GAAG,CAAC,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QAC5E,IAAI,GAAmC,CAAC;QACxC,SAAS,GAAG,SAAS,CAAC,KAAK,EAAE,CAAC,EAAE,EAAE,EAAE;YAClC,IAAI,EAAE,KAAK,KAAK;gBAAE,OAAO,SAAS,CAAC;YACnC,+GAA+G;YAC/G,+FAA+F;YAC/F,GAAG,KAAK,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,GAAG,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"]}
@@ -0,0 +1,2 @@
1
+ /** The version of `@buildanagent/sdk` in use, such as `0.1.0-alpha.1`. */
2
+ export declare const SDK_VERSION: string;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The SDK's own version, read from its package.json so it can't drift from the published version. `run_start`
3
+ * carries it, so a stored session records which SDK wrote it.
4
+ */
5
+ import packageJson from "../package.json" with { type: "json" };
6
+ /** The version of `@buildanagent/sdk` in use, such as `0.1.0-alpha.1`. */
7
+ export const SDK_VERSION = packageJson.version;
8
+ //# sourceMappingURL=version.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../src/version.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,WAAW,MAAM,iBAAiB,CAAC,OAAO,IAAI,EAAE,MAAM,EAAE,CAAC;AAEhE,0EAA0E;AAC1E,MAAM,CAAC,MAAM,WAAW,GAAW,WAAW,CAAC,OAAO,CAAC","sourcesContent":["/**\n * The SDK's own version, read from its package.json so it can't drift from the published version. `run_start`\n * carries it, so a stored session records which SDK wrote it.\n */\nimport packageJson from \"../package.json\" with { type: \"json\" };\n\n/** The version of `@buildanagent/sdk` in use, such as `0.1.0-alpha.1`. */\nexport const SDK_VERSION: string = packageJson.version;\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@buildanagent/sdk",
3
- "version": "0.1.0-alpha.1",
3
+ "version": "0.1.0-alpha.11",
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": {
@@ -12,7 +12,7 @@
12
12
  "type": "module",
13
13
  "sideEffects": false,
14
14
  "engines": {
15
- "node": ">=22"
15
+ "node": ">=22.19.0"
16
16
  },
17
17
  "files": [
18
18
  "dist",
@@ -35,7 +35,17 @@
35
35
  }
36
36
  },
37
37
  "dependencies": {
38
- "@buildanagent/gateway": "0.1.0-alpha.1"
38
+ "@earendil-works/pi-schema": "1.5.2",
39
+ "@standard-schema/spec": "1.1.0",
40
+ "@buildanagent/gateway": "0.1.0-alpha.11"
41
+ },
42
+ "devDependencies": {
43
+ "@cfworker/json-schema": "4.1.6",
44
+ "@opentelemetry/api": "1.9.1",
45
+ "@opentelemetry/sdk-trace": "2.12.1",
46
+ "miniflare": "5.20261103.0-beta",
47
+ "zod": "4.6.7",
48
+ "@buildanagent/agent-safety": "0.0.0"
39
49
  },
40
50
  "scripts": {
41
51
  "build": "node ../../scripts/clean-dist.mjs && tsc -p tsconfig.build.json",