@buildanagent/agent-safety 0.0.0-stage → 0.1.0-alpha.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/LICENSE +54 -0
  2. package/LICENSE-APACHE +202 -0
  3. package/LICENSE-MIT +21 -0
  4. package/README.md +514 -2
  5. package/dist/agents/index.d.ts +5 -0
  6. package/dist/agents/index.js +6 -0
  7. package/dist/agents/index.js.map +1 -0
  8. package/dist/ai/index.d.ts +10 -0
  9. package/dist/ai/index.js +11 -0
  10. package/dist/ai/index.js.map +1 -0
  11. package/dist/ai/interrupted-write.d.ts +28 -0
  12. package/dist/ai/interrupted-write.js +52 -0
  13. package/dist/ai/interrupted-write.js.map +1 -0
  14. package/dist/ai/settle-denied.d.ts +17 -0
  15. package/dist/ai/settle-denied.js +25 -0
  16. package/dist/ai/settle-denied.js.map +1 -0
  17. package/dist/ai/tool-approval.d.ts +68 -0
  18. package/dist/ai/tool-approval.js +219 -0
  19. package/dist/ai/tool-approval.js.map +1 -0
  20. package/dist/ai/tool-result.d.ts +23 -0
  21. package/dist/ai/tool-result.js +20 -0
  22. package/dist/ai/tool-result.js.map +1 -0
  23. package/dist/byok/default-provider.d.ts +12 -0
  24. package/dist/byok/default-provider.js +72 -0
  25. package/dist/byok/default-provider.js.map +1 -0
  26. package/dist/byok/explicit-provider.d.ts +39 -0
  27. package/dist/byok/explicit-provider.js +80 -0
  28. package/dist/byok/explicit-provider.js.map +1 -0
  29. package/dist/byok/index.d.ts +8 -0
  30. package/dist/byok/index.js +9 -0
  31. package/dist/byok/index.js.map +1 -0
  32. package/dist/bytes.d.ts +17 -0
  33. package/dist/bytes.js +59 -0
  34. package/dist/bytes.js.map +1 -0
  35. package/dist/cost/ai-types.d.ts +26 -0
  36. package/dist/cost/ai-types.js +2 -0
  37. package/dist/cost/ai-types.js.map +1 -0
  38. package/dist/cost/budget-exceeded.d.ts +39 -0
  39. package/dist/cost/budget-exceeded.js +49 -0
  40. package/dist/cost/budget-exceeded.js.map +1 -0
  41. package/dist/cost/cost-guard.d.ts +63 -0
  42. package/dist/cost/cost-guard.js +278 -0
  43. package/dist/cost/cost-guard.js.map +1 -0
  44. package/dist/cost/estimate.d.ts +76 -0
  45. package/dist/cost/estimate.js +320 -0
  46. package/dist/cost/estimate.js.map +1 -0
  47. package/dist/cost/guarded-provider.d.ts +24 -0
  48. package/dist/cost/guarded-provider.js +19 -0
  49. package/dist/cost/guarded-provider.js.map +1 -0
  50. package/dist/cost/index.d.ts +12 -0
  51. package/dist/cost/index.js +12 -0
  52. package/dist/cost/index.js.map +1 -0
  53. package/dist/cost/spend.d.ts +13 -0
  54. package/dist/cost/spend.js +15 -0
  55. package/dist/cost/spend.js.map +1 -0
  56. package/dist/effect-key.d.ts +31 -0
  57. package/dist/effect-key.js +61 -0
  58. package/dist/effect-key.js.map +1 -0
  59. package/dist/effect-store-conformance.d.ts +24 -0
  60. package/dist/effect-store-conformance.js +140 -0
  61. package/dist/effect-store-conformance.js.map +1 -0
  62. package/dist/effect-store.d.ts +71 -0
  63. package/dist/effect-store.js +38 -0
  64. package/dist/effect-store.js.map +1 -0
  65. package/dist/egress.d.ts +74 -0
  66. package/dist/egress.js +174 -0
  67. package/dist/egress.js.map +1 -0
  68. package/dist/errors.d.ts +32 -0
  69. package/dist/errors.js +26 -0
  70. package/dist/errors.js.map +1 -0
  71. package/dist/guarded-write.d.ts +99 -0
  72. package/dist/guarded-write.js +245 -0
  73. package/dist/guarded-write.js.map +1 -0
  74. package/dist/hash.d.ts +24 -0
  75. package/dist/hash.js +121 -0
  76. package/dist/hash.js.map +1 -0
  77. package/dist/index.d.ts +27 -0
  78. package/dist/index.js +28 -0
  79. package/dist/index.js.map +1 -0
  80. package/dist/key-store.d.ts +37 -0
  81. package/dist/key-store.js +53 -0
  82. package/dist/key-store.js.map +1 -0
  83. package/dist/model-routes.d.ts +54 -0
  84. package/dist/model-routes.js +117 -0
  85. package/dist/model-routes.js.map +1 -0
  86. package/dist/model-url.d.ts +39 -0
  87. package/dist/model-url.js +79 -0
  88. package/dist/model-url.js.map +1 -0
  89. package/dist/outcome.d.ts +88 -0
  90. package/dist/outcome.js +140 -0
  91. package/dist/outcome.js.map +1 -0
  92. package/dist/pending-store.d.ts +45 -0
  93. package/dist/pending-store.js +36 -0
  94. package/dist/pending-store.js.map +1 -0
  95. package/dist/pending.d.ts +144 -0
  96. package/dist/pending.js +161 -0
  97. package/dist/pending.js.map +1 -0
  98. package/dist/plan-approval.d.ts +196 -0
  99. package/dist/plan-approval.js +357 -0
  100. package/dist/plan-approval.js.map +1 -0
  101. package/dist/plan-card.d.ts +34 -0
  102. package/dist/plan-card.js +56 -0
  103. package/dist/plan-card.js.map +1 -0
  104. package/dist/plan-ledger-conformance.d.ts +24 -0
  105. package/dist/plan-ledger-conformance.js +99 -0
  106. package/dist/plan-ledger-conformance.js.map +1 -0
  107. package/dist/plan-ledger.d.ts +14 -0
  108. package/dist/plan-ledger.js +42 -0
  109. package/dist/plan-ledger.js.map +1 -0
  110. package/dist/plan-run.d.ts +133 -0
  111. package/dist/plan-run.js +438 -0
  112. package/dist/plan-run.js.map +1 -0
  113. package/dist/render.d.ts +40 -0
  114. package/dist/render.js +92 -0
  115. package/dist/render.js.map +1 -0
  116. package/dist/signer.d.ts +42 -0
  117. package/dist/signer.js +128 -0
  118. package/dist/signer.js.map +1 -0
  119. package/dist/stores/cloudflare.d.ts +34 -0
  120. package/dist/stores/cloudflare.js +84 -0
  121. package/dist/stores/cloudflare.js.map +1 -0
  122. package/dist/stores/dynamodb.d.ts +27 -0
  123. package/dist/stores/dynamodb.js +139 -0
  124. package/dist/stores/dynamodb.js.map +1 -0
  125. package/dist/stores/lost-claim.d.ts +8 -0
  126. package/dist/stores/lost-claim.js +11 -0
  127. package/dist/stores/lost-claim.js.map +1 -0
  128. package/dist/stores/postgres.d.ts +30 -0
  129. package/dist/stores/postgres.js +79 -0
  130. package/dist/stores/postgres.js.map +1 -0
  131. package/dist/test-signer.d.ts +13 -0
  132. package/dist/test-signer.js +18 -0
  133. package/dist/test-signer.js.map +1 -0
  134. package/dist/testing.d.ts +8 -0
  135. package/dist/testing.js +9 -0
  136. package/dist/testing.js.map +1 -0
  137. package/llms.txt +212 -0
  138. package/package.json +107 -3
package/dist/render.js ADDED
@@ -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/render.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAmD,YAAY,EAAE,MAAM,cAAc,CAAC;AA8B7F,2DAA2D;AAC3D,MAAM,QAAQ,GAA4C;IACxD,OAAO,EAAE,4BAA4B;IACrC,WAAW,EAAE,yDAAyD;IACtE,WAAW,EAAE,gDAAgD;IAC7D,OAAO,EAAE,0EAA0E;IACnF,OAAO,EAAE,oDAAoD;CAC9D,CAAC;AAEF,yFAAyF;AACzF,MAAM,QAAQ,GAA4C;IACxD,OAAO,EAAE,2CAA2C;IACpD,WAAW,EAAE,8BAA8B;IAC3C,WAAW,EAAE,2EAA2E;IACxF,OAAO,EAAE,iCAAiC;IAC1C,OAAO,EAAE,sFAAsF;CAChG,CAAC;AAEF,gHAAgH;AAChH,MAAM,KAAK,GAAsC;IAC/C,QAAQ,EAAE,gEAAgE;IAC1E,kBAAkB,EAAE,uEAAuE;IAC3F,eAAe,EAAE,4CAA4C;IAC7D,KAAK,EAAE,kBAAkB;CAC1B,CAAC;AAEF,kGAAkG;AAClG,MAAM,gBAAgB,GAAG,wEAAwE,CAAC;AAElG,SAAS,QAAQ,CAAC,IAAY;IAC5B,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI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,OAAO,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC;QAChE,GAAG,CAAC,OAAO,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC;KACpE,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,aAAa,CAAC,OAAqB;IACjD,kHAAkH;IAClH,iFAAiF;IACjF,MAAM,OAAO,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC;IACtC,OAAO,EAAE,IAAI,EAAE,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,SAAS,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;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;
package/dist/signer.js ADDED
@@ -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/signer.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;A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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,34 @@
1
+ /**
2
+ * `@buildanagent/agent-safety/stores/cloudflare`: the effect store and the plan ledger on a Durable Object's SQLite
3
+ * storage, `ctx.storage.sql`. SQL calls in a Durable Object complete synchronously, and none of the methods below
4
+ * awaits between its statements, so no other event in the object runs between two of them. The SQL still makes every
5
+ * change conditional, so the same code is correct if a host ever lets two callers interleave.
6
+ *
7
+ * A store belongs to one object: give every tenant or session that must keep its own records its own object, or pass
8
+ * records whose keys are already unique across tenants, as `effectKey()` makes them.
9
+ */
10
+ import type { EffectStore } from "../effect-store.js";
11
+ import type { PlanLedger } from "../plan-approval.js";
12
+ /** What a query returns here: the rows, and `RETURNING` makes the written ones count. */
13
+ export interface SqlCursorLike {
14
+ /** Every row the statement returned, each as an object keyed by column name. */
15
+ toArray(): Record<string, unknown>[];
16
+ }
17
+ /** The part of `SqlStorage` (`ctx.storage.sql`) these stores use. */
18
+ export interface SqlStorageLike {
19
+ /** Runs one SQL statement with its `?` placeholders bound, in order, to `bindings`. */
20
+ exec(query: string, ...bindings: unknown[]): SqlCursorLike;
21
+ }
22
+ /** Creates the two tables if they are not there, as every store of this module needs; call it once per object. */
23
+ export declare function createCloudflareTables(sql: SqlStorageLike): void;
24
+ /**
25
+ * An `EffectStore` on Durable Object SQLite. Each record is one row: its key, the attempt and state that the
26
+ * compare-and-set conditions read, and the record as JSON. Call `createCloudflareTables()` first.
27
+ */
28
+ export declare function durableObjectEffectStore(sql: SqlStorageLike): EffectStore;
29
+ /**
30
+ * A `PlanLedger` on Durable Object SQLite. A plan's claimed steps are rows `0` to `n - 1`, so the next step to claim
31
+ * is the row count, and a claim inserts its row only when the count equals its index. Call `createCloudflareTables()`
32
+ * first.
33
+ */
34
+ export declare function durableObjectPlanLedger(sql: SqlStorageLike): PlanLedger;
@@ -0,0 +1,84 @@
1
+ import { assertStepIndex } from "../plan-ledger.js";
2
+ import { lostClaim } from "./lost-claim.js";
3
+ const SCHEMA = [
4
+ `CREATE TABLE IF NOT EXISTS effect_records (
5
+ key TEXT PRIMARY KEY,
6
+ attempt INTEGER NOT NULL,
7
+ state TEXT NOT NULL,
8
+ record TEXT NOT NULL
9
+ )`,
10
+ `CREATE TABLE IF NOT EXISTS plan_steps (
11
+ plan_id TEXT NOT NULL,
12
+ step_index INTEGER NOT NULL,
13
+ PRIMARY KEY (plan_id, step_index)
14
+ )`,
15
+ ];
16
+ /** Creates the two tables if they are not there, as every store of this module needs; call it once per object. */
17
+ export function createCloudflareTables(sql) {
18
+ for (const statement of SCHEMA)
19
+ sql.exec(statement);
20
+ }
21
+ function parse(text) {
22
+ return JSON.parse(String(text));
23
+ }
24
+ /**
25
+ * An `EffectStore` on Durable Object SQLite. Each record is one row: its key, the attempt and state that the
26
+ * compare-and-set conditions read, and the record as JSON. Call `createCloudflareTables()` first.
27
+ */
28
+ export function durableObjectEffectStore(sql) {
29
+ const read = (key) => {
30
+ const [row] = sql.exec("SELECT record FROM effect_records WHERE key = ?", key).toArray();
31
+ return row === undefined ? undefined : parse(row.record);
32
+ };
33
+ const lost = (key) => lostClaim(key, read(key));
34
+ return {
35
+ async begin(record) {
36
+ const rows = sql
37
+ .exec(`INSERT INTO effect_records (key, attempt, state, record) VALUES (?, ?, ?, ?)
38
+ ON CONFLICT(key) DO NOTHING RETURNING key`, record.key, record.attempt, record.state, JSON.stringify(record))
39
+ .toArray();
40
+ return rows.length === 1 ? "started" : lost(record.key);
41
+ },
42
+ async takeOver(record) {
43
+ const rows = sql
44
+ .exec(`INSERT INTO effect_records (key, attempt, state, record) VALUES (?, ?, ?, ?)
45
+ ON CONFLICT(key) DO UPDATE SET attempt = excluded.attempt, state = excluded.state, record = excluded.record
46
+ WHERE effect_records.attempt = excluded.attempt - 1
47
+ RETURNING key`, record.key, record.attempt, record.state, JSON.stringify(record))
48
+ .toArray();
49
+ return rows.length === 1 ? "started" : lost(record.key);
50
+ },
51
+ async settle(record) {
52
+ const rows = sql
53
+ .exec(`UPDATE effect_records SET state = 'settled', record = ?
54
+ WHERE key = ? AND state = 'started' AND attempt = ?
55
+ RETURNING key`, JSON.stringify(record), record.key, record.attempt)
56
+ .toArray();
57
+ return rows.length === 1;
58
+ },
59
+ async get(key) {
60
+ return read(key);
61
+ },
62
+ };
63
+ }
64
+ /**
65
+ * A `PlanLedger` on Durable Object SQLite. A plan's claimed steps are rows `0` to `n - 1`, so the next step to claim
66
+ * is the row count, and a claim inserts its row only when the count equals its index. Call `createCloudflareTables()`
67
+ * first.
68
+ */
69
+ export function durableObjectPlanLedger(sql) {
70
+ return Object.freeze({
71
+ async claim(planId, stepIndex) {
72
+ assertStepIndex(stepIndex);
73
+ const [row] = sql.exec("SELECT count(*) AS passed FROM plan_steps WHERE plan_id = ?", planId).toArray();
74
+ const passed = Number(row?.passed ?? 0);
75
+ if (stepIndex < passed)
76
+ return "replayed";
77
+ if (stepIndex > passed)
78
+ return "out_of_order";
79
+ sql.exec("INSERT INTO plan_steps (plan_id, step_index) VALUES (?, ?)", planId, stepIndex);
80
+ return "claimed";
81
+ },
82
+ });
83
+ }
84
+ //# sourceMappingURL=cloudflare.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloudflare.js","sourceRoot":"","sources":["../../src/stores/cloudflare.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAc5C,MAAM,MAAM,GAAG;IACb;;;;;IAKE;IACF;;;;IAIE;CACH,CAAC;AAEF,kHAAkH;AAClH,MAAM,UAAU,sBAAsB,CAAC,GAAmB;IACxD,KAAK,MAAM,SAAS,IAAI,MAAM;QAAE,GAAG,CAAC,IAAI,CAAC,SAAS,CAA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AC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QAC1D,CAAC;QACD,KAAK,CAAC,MAAM,CAAC,MAAM;YACjB,MAAM,IAAI,GAAG,GAAG;iBACb,IAAI,CACH;;yBAEe,EACf,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,EACtB,MAAM,CAAC,GAAG,EACV,MAAM,CAAC,OAAO,CACf;iBACA,OAAO,EAAE,CAAC;YACb,OAAO,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC;QAC3B,CAAC;QACD,KAAK,CAAC,GAAG,CAAC,GAAG;YACX,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;QACnB,CAAC;KACF,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,uBAAuB,CAAC,GAAmB;IACzD,OAAO,MAAM,CAAC,MAAM,CAAC;QACnB,KAAK,CAAC,KAAK,CAAC,MAAc,EAAE,SAAiB;YAC3C,eAAe,CAAC,SAAS,CAAC,CAAC;YAC3B,MAAM,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,IAAI,CAAC,6DAA6D,EAAE,MAAM,CAAC,CAAC,OAAO,EAAE,CAAC;YACxG,MAAM,MAAM,GAAG,MAAM,CAAC,GAAG,EAAE,MAAM,IAAI,CAAC,CAAC,CAAC;YACxC,IAAI,SAAS,GAAG,MAAM;gBAAE,OAAO,UAAmB,CAAC;YACnD,IAAI,SAAS,GAAG,MAAM;gBAAE,OAAO,cAAuB,CAAC;YACvD,GAAG,CAAC,IAAI,CAAC,4DAA4D,EAAE,MAAM,EAAE,SAAS,CAAC,CAAC;YAC1F,OAAO,SAAkB,CAAC;QAC5B,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * `@buildanagent/agent-safety/stores/cloudflare`: the effect store and the plan ledger on a Durable Object's SQLite\n * storage, `ctx.storage.sql`. SQL calls in a Durable Object complete synchronously, and none of the methods below\n * awaits between its statements, so no other event in the object runs between two of them. The SQL still makes every\n * change conditional, so the same code is correct if a host ever lets two callers interleave.\n *\n * A store belongs to one object: give every tenant or session that must keep its own records its own object, or pass\n * records whose keys are already unique across tenants, as `effectKey()` makes them.\n */\nimport type { EffectClaim, EffectRecord, EffectStore } from \"../effect-store.js\";\nimport type { PlanLedger } from \"../plan-approval.js\";\nimport { assertStepIndex } from \"../plan-ledger.js\";\nimport { lostClaim } from \"./lost-claim.js\";\n\n/** What a query returns here: the rows, and `RETURNING` makes the written ones count. */\nexport interface SqlCursorLike {\n /** Every row the statement returned, each as an object keyed by column name. */\n toArray(): Record<string, unknown>[];\n}\n\n/** The part of `SqlStorage` (`ctx.storage.sql`) these stores use. */\nexport interface SqlStorageLike {\n /** Runs one SQL statement with its `?` placeholders bound, in order, to `bindings`. */\n exec(query: string, ...bindings: unknown[]): SqlCursorLike;\n}\n\nconst SCHEMA = [\n `CREATE TABLE IF NOT EXISTS effect_records (\n key TEXT PRIMARY KEY,\n attempt INTEGER NOT NULL,\n state TEXT NOT NULL,\n record TEXT NOT NULL\n )`,\n `CREATE TABLE IF NOT EXISTS plan_steps (\n plan_id TEXT NOT NULL,\n step_index INTEGER NOT NULL,\n PRIMARY KEY (plan_id, step_index)\n )`,\n];\n\n/** Creates the two tables if they are not there, as every store of this module needs; call it once per object. */\nexport function createCloudflareTables(sql: SqlStorageLike): void {\n for (const statement of SCHEMA) sql.exec(statement);\n}\n\nfunction parse(text: unknown): EffectRecord {\n return JSON.parse(String(text)) as EffectRecord;\n}\n\n/**\n * An `EffectStore` on Durable Object SQLite. Each record is one row: its key, the attempt and state that the\n * compare-and-set conditions read, and the record as JSON. Call `createCloudflareTables()` first.\n */\nexport function durableObjectEffectStore(sql: SqlStorageLike): EffectStore {\n const read = (key: string): EffectRecord | undefined => {\n const [row] = sql.exec(\"SELECT record FROM effect_records WHERE key = ?\", key).toArray();\n return row === undefined ? undefined : parse(row.record);\n };\n const lost = (key: string): EffectClaim => lostClaim(key, read(key));\n return {\n async begin(record) {\n const rows = sql\n .exec(\n `INSERT INTO effect_records (key, attempt, state, record) VALUES (?, ?, ?, ?)\n ON CONFLICT(key) DO NOTHING RETURNING key`,\n record.key,\n record.attempt,\n record.state,\n JSON.stringify(record),\n )\n .toArray();\n return rows.length === 1 ? \"started\" : lost(record.key);\n },\n async takeOver(record) {\n const rows = sql\n .exec(\n `INSERT INTO effect_records (key, attempt, state, record) VALUES (?, ?, ?, ?)\n ON CONFLICT(key) DO UPDATE SET attempt = excluded.attempt, state = excluded.state, record = excluded.record\n WHERE effect_records.attempt = excluded.attempt - 1\n RETURNING key`,\n record.key,\n record.attempt,\n record.state,\n JSON.stringify(record),\n )\n .toArray();\n return rows.length === 1 ? \"started\" : lost(record.key);\n },\n async settle(record) {\n const rows = sql\n .exec(\n `UPDATE effect_records SET state = 'settled', record = ?\n WHERE key = ? AND state = 'started' AND attempt = ?\n RETURNING key`,\n JSON.stringify(record),\n record.key,\n record.attempt,\n )\n .toArray();\n return rows.length === 1;\n },\n async get(key) {\n return read(key);\n },\n };\n}\n\n/**\n * A `PlanLedger` on Durable Object SQLite. A plan's claimed steps are rows `0` to `n - 1`, so the next step to claim\n * is the row count, and a claim inserts its row only when the count equals its index. Call `createCloudflareTables()`\n * first.\n */\nexport function durableObjectPlanLedger(sql: SqlStorageLike): PlanLedger {\n return Object.freeze({\n async claim(planId: string, stepIndex: number) {\n assertStepIndex(stepIndex);\n const [row] = sql.exec(\"SELECT count(*) AS passed FROM plan_steps WHERE plan_id = ?\", planId).toArray();\n const passed = Number(row?.passed ?? 0);\n if (stepIndex < passed) return \"replayed\" as const;\n if (stepIndex > passed) return \"out_of_order\" as const;\n sql.exec(\"INSERT INTO plan_steps (plan_id, step_index) VALUES (?, ?)\", planId, stepIndex);\n return \"claimed\" as const;\n },\n });\n}\n"]}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * `@buildanagent/agent-safety/stores/dynamodb`: the effect store and the plan ledger on DynamoDB, through an
3
+ * `@aws-sdk/client-dynamodb` client. Every change is a conditional write, so DynamoDB decides a race: `begin` is a put
4
+ * that needs the key to be absent, `takeOver` a put that needs the stored attempt to be the one before, and `settle` a
5
+ * put that needs the record to be `started` at this attempt. A plan's step claim is one transaction that checks the
6
+ * step before it and puts this one.
7
+ *
8
+ * Reads are consistent reads. The table needs one string partition key named `pk` and no sort key.
9
+ */
10
+ import { type DynamoDBClient } from "@aws-sdk/client-dynamodb";
11
+ import type { EffectStore } from "../effect-store.js";
12
+ import type { PlanLedger } from "../plan-approval.js";
13
+ /** The options of the DynamoDB stores. */
14
+ export interface DynamoStoreOptions {
15
+ /** The table that holds the records and the plan steps. */
16
+ readonly tableName: string;
17
+ }
18
+ /** An `EffectStore` on DynamoDB. */
19
+ export declare function dynamoEffectStore(client: DynamoDBClient, options: DynamoStoreOptions): EffectStore;
20
+ /**
21
+ * A `PlanLedger` on DynamoDB. Step `n` is an item that exists once the step passed. A claim of step `n` is one
22
+ * transaction: put the item for `n` if it is absent, and check that the item for `n - 1` exists. The transaction
23
+ * carries a `ClientRequestToken`, so an SDK retry of a claim that already took effect is answered as the same claim,
24
+ * not as a replay. When the transaction is refused because a condition was false, a read of the item for `n` tells
25
+ * `replayed` from `out_of_order`; a cancellation for any other reason is rethrown.
26
+ */
27
+ export declare function dynamoPlanLedger(client: DynamoDBClient, options: DynamoStoreOptions): PlanLedger;
@@ -0,0 +1,139 @@
1
+ /**
2
+ * `@buildanagent/agent-safety/stores/dynamodb`: the effect store and the plan ledger on DynamoDB, through an
3
+ * `@aws-sdk/client-dynamodb` client. Every change is a conditional write, so DynamoDB decides a race: `begin` is a put
4
+ * that needs the key to be absent, `takeOver` a put that needs the stored attempt to be the one before, and `settle` a
5
+ * put that needs the record to be `started` at this attempt. A plan's step claim is one transaction that checks the
6
+ * step before it and puts this one.
7
+ *
8
+ * Reads are consistent reads. The table needs one string partition key named `pk` and no sort key.
9
+ */
10
+ import { GetItemCommand, PutItemCommand, TransactWriteItemsCommand, } from "@aws-sdk/client-dynamodb";
11
+ import { assertStepIndex } from "../plan-ledger.js";
12
+ import { lostClaim } from "./lost-claim.js";
13
+ const effectPk = (key) => `effect#${key}`;
14
+ const stepPk = (planId, stepIndex) => `plan#${planId}#${stepIndex}`;
15
+ /** The item for a record. `token` names the call that wrote it, so that call can tell its own retried write apart. */
16
+ function item(record, token) {
17
+ return {
18
+ pk: { S: effectPk(record.key) },
19
+ attempt: { N: String(record.attempt) },
20
+ state: { S: record.state },
21
+ record: { S: JSON.stringify(record) },
22
+ token: { S: token },
23
+ };
24
+ }
25
+ const asSdkError = (error) => (typeof error === "object" && error !== null ? error : {});
26
+ /**
27
+ * The token on the item that made a put's condition false, or `undefined` when the answer isn't "the condition was
28
+ * false".
29
+ */
30
+ function failedConditionToken(error) {
31
+ const { name, Item } = asSdkError(error);
32
+ return name === "ConditionalCheckFailedException" ? { token: Item?.token?.S } : undefined;
33
+ }
34
+ /**
35
+ * Whether a transaction was refused because a condition was false. A cancellation for another reason, such as a
36
+ * conflict with another transaction or throttling, says nothing about the items, so it is not a refusal.
37
+ */
38
+ function transactionRefused(error) {
39
+ const { name, CancellationReasons } = asSdkError(error);
40
+ return (name === "TransactionCanceledException" &&
41
+ CancellationReasons?.some((r) => r.Code === "ConditionalCheckFailed") === true);
42
+ }
43
+ /** An `EffectStore` on DynamoDB. */
44
+ export function dynamoEffectStore(client, options) {
45
+ const { tableName } = options;
46
+ const read = async (key) => {
47
+ const { Item } = await client.send(new GetItemCommand({ TableName: tableName, Key: { pk: { S: effectPk(key) } }, ConsistentRead: true }));
48
+ return Item?.record?.S === undefined ? undefined : JSON.parse(Item.record.S);
49
+ };
50
+ const lost = async (key) => lostClaim(key, await read(key));
51
+ /**
52
+ * A put that needs `condition`, answering whether it took effect. The SDK retries a put after a timeout or a server
53
+ * error, and a retry of a put that already took effect fails its own condition. DynamoDB then returns the item that
54
+ * made it fail, and when that item carries this call's token it is this call's own write, so the put counts as won.
55
+ * Each call has a token of its own, so another caller's write never does.
56
+ */
57
+ const put = async (record, condition, names, values) => {
58
+ const token = crypto.randomUUID();
59
+ try {
60
+ await client.send(new PutItemCommand({
61
+ TableName: tableName,
62
+ Item: item(record, token),
63
+ ConditionExpression: condition,
64
+ ExpressionAttributeNames: names,
65
+ ...(values === undefined ? {} : { ExpressionAttributeValues: values }),
66
+ ReturnValuesOnConditionCheckFailure: "ALL_OLD",
67
+ }));
68
+ return true;
69
+ }
70
+ catch (error) {
71
+ const failed = failedConditionToken(error);
72
+ if (failed === undefined)
73
+ throw error;
74
+ return failed.token === token;
75
+ }
76
+ };
77
+ return {
78
+ async begin(record) {
79
+ return (await put(record, "attribute_not_exists(#pk)", { "#pk": "pk" })) ? "started" : lost(record.key);
80
+ },
81
+ async takeOver(record) {
82
+ const won = await put(record, "attribute_not_exists(#pk) OR #attempt = :previous", { "#pk": "pk", "#attempt": "attempt" }, { ":previous": { N: String(record.attempt - 1) } });
83
+ return won ? "started" : lost(record.key);
84
+ },
85
+ async settle(record) {
86
+ return put(record, "#state = :started AND #attempt = :attempt", { "#state": "state", "#attempt": "attempt" }, { ":started": { S: "started" }, ":attempt": { N: String(record.attempt) } });
87
+ },
88
+ get: read,
89
+ };
90
+ }
91
+ /**
92
+ * A `PlanLedger` on DynamoDB. Step `n` is an item that exists once the step passed. A claim of step `n` is one
93
+ * transaction: put the item for `n` if it is absent, and check that the item for `n - 1` exists. The transaction
94
+ * carries a `ClientRequestToken`, so an SDK retry of a claim that already took effect is answered as the same claim,
95
+ * not as a replay. When the transaction is refused because a condition was false, a read of the item for `n` tells
96
+ * `replayed` from `out_of_order`; a cancellation for any other reason is rethrown.
97
+ */
98
+ export function dynamoPlanLedger(client, options) {
99
+ const { tableName } = options;
100
+ const exists = async (planId, stepIndex) => {
101
+ const { Item } = await client.send(new GetItemCommand({ TableName: tableName, Key: { pk: { S: stepPk(planId, stepIndex) } }, ConsistentRead: true }));
102
+ return Item !== undefined;
103
+ };
104
+ return Object.freeze({
105
+ async claim(planId, stepIndex) {
106
+ assertStepIndex(stepIndex);
107
+ const put = {
108
+ Put: {
109
+ TableName: tableName,
110
+ Item: { pk: { S: stepPk(planId, stepIndex) } },
111
+ ConditionExpression: "attribute_not_exists(#pk)",
112
+ ExpressionAttributeNames: { "#pk": "pk" },
113
+ },
114
+ };
115
+ const earlier = stepIndex === 0
116
+ ? []
117
+ : [
118
+ {
119
+ ConditionCheck: {
120
+ TableName: tableName,
121
+ Key: { pk: { S: stepPk(planId, stepIndex - 1) } },
122
+ ConditionExpression: "attribute_exists(#pk)",
123
+ ExpressionAttributeNames: { "#pk": "pk" },
124
+ },
125
+ },
126
+ ];
127
+ try {
128
+ await client.send(new TransactWriteItemsCommand({ TransactItems: [...earlier, put], ClientRequestToken: crypto.randomUUID() }));
129
+ return "claimed";
130
+ }
131
+ catch (error) {
132
+ if (!transactionRefused(error))
133
+ throw error;
134
+ return (await exists(planId, stepIndex)) ? "replayed" : "out_of_order";
135
+ }
136
+ },
137
+ });
138
+ }
139
+ //# sourceMappingURL=dynamodb.js.map