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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/LICENSE +54 -0
  2. package/LICENSE-APACHE +202 -0
  3. package/LICENSE-MIT +21 -0
  4. package/README.md +515 -0
  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 +108 -5
@@ -0,0 +1,32 @@
1
+ /**
2
+ * `SafetyError`: the safety package's error for programmer errors, such as a write outcome with a malformed reason, an
3
+ * input that has no canonical JSON form, a key ring that can't sign, or a model request that would use a credential
4
+ * nobody configured. Its subclass `BudgetExceeded`, in the `./cost` subpath, is the refusal of a model call that would
5
+ * pass a USD cap.
6
+ */
7
+ /**
8
+ * Why a `SafetyError` was thrown. `invalid_outcome`: a write outcome breaks a rule. `invalid_input`: a tool input has
9
+ * no canonical JSON form, or a tool's context fails its `contextSchema`. `invalid_key_ring`: a signer's keys or key ids
10
+ * can't be used. `invalid_pending`: the fields of a pending request can't be signed. `invalid_byok_config`: a model
11
+ * provider's key or base URL is empty, malformed or points at a gateway that may bill another credential.
12
+ * `egress_refused`: a model request would leave for another host or carry another credential. `default_provider`: code
13
+ * resolved a string model id, or another default provider is set, so a call could reach a gateway nobody configured.
14
+ * `invalid_plan`: a plan's steps, state reads or expiry can't be signed or shown, such as a plan whose steps are out of
15
+ * order. `invalid_effect`: a guarded write's scope, business key or options break a rule. `invalid_budget`: a cost
16
+ * guard's cap is not a finite number of dollars, 0 or more. `budget_exceeded`: a model call was refused before it was
17
+ * sent, because what the run or session has spent plus the call's projected cost would pass its USD cap.
18
+ * `unknown_price`: a model call was refused before it was sent, because the model has no catalog price, an earlier
19
+ * call reported no usage or the request holds a file with no known size, so the cap can't be checked.
20
+ */
21
+ export type SafetyErrorCode = "invalid_outcome" | "invalid_input" | "invalid_key_ring" | "invalid_pending" | "invalid_plan" | "invalid_byok_config" | "egress_refused" | "default_provider" | "invalid_effect" | "invalid_budget" | "budget_exceeded" | "unknown_price";
22
+ /**
23
+ * Thrown for a mistake in how the safety package is called, and, as its subclass `BudgetExceeded`, for a model call
24
+ * refused under a USD cap. A write that fails is an outcome, never this error.
25
+ */
26
+ export declare class SafetyError extends Error {
27
+ readonly name: string;
28
+ readonly code: SafetyErrorCode;
29
+ constructor(code: SafetyErrorCode, message: string, options?: ErrorOptions);
30
+ }
31
+ /** True for a `SafetyError`, including one from another copy of the package. */
32
+ export declare function isSafetyError(error: unknown): error is SafetyError;
package/dist/errors.js ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * `SafetyError`: the safety package's error for programmer errors, such as a write outcome with a malformed reason, an
3
+ * input that has no canonical JSON form, a key ring that can't sign, or a model request that would use a credential
4
+ * nobody configured. Its subclass `BudgetExceeded`, in the `./cost` subpath, is the refusal of a model call that would
5
+ * pass a USD cap.
6
+ */
7
+ // A registered symbol, so the guard still works when two copies of the package are bundled.
8
+ const SAFETY_ERROR = Symbol.for("buildanagent.agent-safety.SafetyError");
9
+ /**
10
+ * Thrown for a mistake in how the safety package is called, and, as its subclass `BudgetExceeded`, for a model call
11
+ * refused under a USD cap. A write that fails is an outcome, never this error.
12
+ */
13
+ export class SafetyError extends Error {
14
+ name = "SafetyError";
15
+ code;
16
+ constructor(code, message, options) {
17
+ super(message, options);
18
+ this.code = code;
19
+ Object.defineProperty(this, SAFETY_ERROR, { value: true });
20
+ }
21
+ }
22
+ /** True for a `SafetyError`, including one from another copy of the package. */
23
+ export function isSafetyError(error) {
24
+ return typeof error === "object" && error !== null && error[SAFETY_ERROR] === true;
25
+ }
26
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AA8BH,4FAA4F;AAC5F,MAAM,YAAY,GAAG,MAAM,CAAC,GAAG,CAAC,uCAAuC,CAAC,CAAC;AAEzE;;;GAGG;AACH,MAAM,OAAO,WAAY,SAAQ,KAAK;IAClB,IAAI,GAAW,aAAa,CAAC;IACtC,IAAI,CAAkB;IAE/B,YAAY,IAAqB,EAAE,OAAe,EAAE,OAAsB;QACxE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7D,CAAC;CACF;AAED,gFAAgF;AAChF,MAAM,UAAU,aAAa,CAAC,KAAc;IAC1C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,YAAY,CAAC,KAAK,IAAI,CAAC;AAClH,CAAC","sourcesContent":["/**\n * `SafetyError`: the safety package's error for programmer errors, such as a write outcome with a malformed reason, an\n * input that has no canonical JSON form, a key ring that can't sign, or a model request that would use a credential\n * nobody configured. Its subclass `BudgetExceeded`, in the `./cost` subpath, is the refusal of a model call that would\n * pass a USD cap.\n */\n\n/**\n * Why a `SafetyError` was thrown. `invalid_outcome`: a write outcome breaks a rule. `invalid_input`: a tool input has\n * no canonical JSON form, or a tool's context fails its `contextSchema`. `invalid_key_ring`: a signer's keys or key ids\n * can't be used. `invalid_pending`: the fields of a pending request can't be signed. `invalid_byok_config`: a model\n * provider's key or base URL is empty, malformed or points at a gateway that may bill another credential.\n * `egress_refused`: a model request would leave for another host or carry another credential. `default_provider`: code\n * resolved a string model id, or another default provider is set, so a call could reach a gateway nobody configured.\n * `invalid_plan`: a plan's steps, state reads or expiry can't be signed or shown, such as a plan whose steps are out of\n * order. `invalid_effect`: a guarded write's scope, business key or options break a rule. `invalid_budget`: a cost\n * guard's cap is not a finite number of dollars, 0 or more. `budget_exceeded`: a model call was refused before it was\n * sent, because what the run or session has spent plus the call's projected cost would pass its USD cap.\n * `unknown_price`: a model call was refused before it was sent, because the model has no catalog price, an earlier\n * call reported no usage or the request holds a file with no known size, so the cap can't be checked.\n */\nexport type SafetyErrorCode =\n | \"invalid_outcome\"\n | \"invalid_input\"\n | \"invalid_key_ring\"\n | \"invalid_pending\"\n | \"invalid_plan\"\n | \"invalid_byok_config\"\n | \"egress_refused\"\n | \"default_provider\"\n | \"invalid_effect\"\n | \"invalid_budget\"\n | \"budget_exceeded\"\n | \"unknown_price\";\n\n// A registered symbol, so the guard still works when two copies of the package are bundled.\nconst SAFETY_ERROR = Symbol.for(\"buildanagent.agent-safety.SafetyError\");\n\n/**\n * Thrown for a mistake in how the safety package is called, and, as its subclass `BudgetExceeded`, for a model call\n * refused under a USD cap. A write that fails is an outcome, never this error.\n */\nexport class SafetyError extends Error {\n override readonly name: string = \"SafetyError\";\n readonly code: SafetyErrorCode;\n\n constructor(code: SafetyErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n Object.defineProperty(this, SAFETY_ERROR, { value: true });\n }\n}\n\n/** True for a `SafetyError`, including one from another copy of the package. */\nexport function isSafetyError(error: unknown): error is SafetyError {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[SAFETY_ERROR] === true;\n}\n"]}
@@ -0,0 +1,99 @@
1
+ /**
2
+ * `guardedWrite()`: persist before execute. It stores an effect record before the write runs and settles it with the
3
+ * outcome after, and it treats a record left `started` by a crash as `unknown` until the tool's `reconcile` hook reads
4
+ * the external system's state. An `unknown` write is never run again under a fresh key, because the first attempt may
5
+ * have taken effect (close-sdk-gaps SG3; rewind report, "Two ledgers, and the first fields to add").
6
+ *
7
+ * The store's answers map onto the IETF Idempotency-Key draft's statuses, as the server rollback report sets out: the
8
+ * same key with a different input is the draft's 422 and is refused, and a live attempt is its 409, so the caller
9
+ * waits and retries under the same key.
10
+ */
11
+ import { type EffectScope } from "./effect-key.js";
12
+ import type { EffectStore } from "./effect-store.js";
13
+ import { type WriteOutcome } from "./outcome.js";
14
+ /**
15
+ * How a retry can find out what an earlier attempt of the write did. `idempotency_key`: the external API dedupes by
16
+ * the key `run` sends, as Stripe's `Idempotency-Key` header does. `reconcile`: the API ignores keys, but the tool's
17
+ * `reconcile` hook can find the write by a field the tool sets, such as a message id. `unknown_only`: neither, so an
18
+ * interrupted attempt stays `unknown` for good and a person must check it; put such a tool behind an approval.
19
+ */
20
+ export type WriteDedupe = "idempotency_key" | "reconcile" | "unknown_only";
21
+ /** The options of `guardedWrite()`. */
22
+ export interface GuardedWriteOptions<T> {
23
+ /** Where the effect records live. Use a durable store wherever a crash must not repeat the write. */
24
+ readonly store: EffectStore;
25
+ /** The tenant, session, branch and tool call the write was asked for. */
26
+ readonly scope: EffectScope;
27
+ /**
28
+ * The business operation the write performs, such as `refund:{orderId}`. Set it for every tool that sends, submits,
29
+ * pays or deletes, so a regenerated turn or a new session maps to the same effect. One business key names one
30
+ * operation for good: a write the user asks for again as a new operation, such as a second refund of one order,
31
+ * needs a new business key, such as one that adds the request's own id.
32
+ */
33
+ readonly businessKey?: string;
34
+ /** The tool or business operation, such as `refund_create`. */
35
+ readonly operation: string;
36
+ /** The tool's input. Its canonical hash is stored; a later call with the same key and another input is refused. */
37
+ readonly input: unknown;
38
+ /** How a retry finds out what an earlier attempt did. */
39
+ readonly dedupe: WriteDedupe;
40
+ /** Runs the write. Pass `key` to the external API's idempotency header, or set it where `reconcile` can find it. */
41
+ run(key: string): Promise<T>;
42
+ /** Turns what `run` returned into the write's outcome. `key` is the effect key, for an outcome that names it. */
43
+ toOutcome(result: T, key: string): WriteOutcome;
44
+ /**
45
+ * Turns an error `run` threw into an outcome, for errors the tool knows took no effect, such as a validation
46
+ * failure. Without it, every error from `run` is `unknown`, because the request may have reached the system. `key` is
47
+ * the effect key, which an `unknown` or `partial` outcome needs for a `same_key` retry.
48
+ */
49
+ onError?(error: unknown, key: string): WriteOutcome;
50
+ /**
51
+ * Reads the external system's state by key, for a resume after a crash or an `unknown` outcome. Return the outcome
52
+ * if the write took effect or was rejected, or `"not_found"` if it never reached the system, and the write then
53
+ * runs again under the same key. Required for `dedupe: "reconcile"`, refused for `"unknown_only"`.
54
+ */
55
+ reconcile?(key: string): Promise<WriteOutcome | "not_found">;
56
+ /**
57
+ * How long a started attempt counts as live, in milliseconds. A call that finds a live attempt gets `unknown` with
58
+ * reason `IN_PROGRESS`; once the lease lapses, the attempt counts as crashed. Make it longer than the slowest write
59
+ * plus the clock skew between the hosts that share the store, because the lease is read on the resuming host's clock.
60
+ * Defaults to five minutes.
61
+ */
62
+ readonly leaseMs?: number;
63
+ /** Returns the current time in milliseconds. Defaults to `Date.now`. */
64
+ readonly now?: () => number;
65
+ }
66
+ /**
67
+ * Runs a write at most once per effect key. It stores an effect record before `run` starts and settles it with the
68
+ * outcome after, so a crash in between leaves evidence that the write may have happened:
69
+ *
70
+ * - A new key runs the write and returns its outcome, with the effect key stamped on it.
71
+ * - A settled key returns its stored outcome without running, unless that outcome allows a `same_key` retry.
72
+ * - The same key with a different input or operation returns `not_applied`, reason `IDEMPOTENCY_KEY_REUSED`, and
73
+ * sends nothing.
74
+ * - A key whose attempt is still live, perhaps in another process, returns `unknown`, reason `IN_PROGRESS`, with a
75
+ * `same_key` retry, and runs nothing.
76
+ * - A key whose attempt crashed, because its lease lapsed, calls `reconcile`: a found write returns its outcome, and
77
+ * `"not_found"` runs the write once more under the same key. Without `reconcile`, it returns `unknown`, reason
78
+ * `WRITE_INTERRUPTED`, and runs nothing: its retry is `reconcile_first`, or `never` for `dedupe: "unknown_only"`.
79
+ * - A settled `unknown` or `partial` outcome whose retry isn't `never` calls `reconcile` the same way.
80
+ *
81
+ * The key comes from `effectKey()`, and no option lets a caller pick another one. With a business key, a write whose
82
+ * outcome is `unknown` can therefore never run again under a fresh key. Without one, the key holds the tool call id,
83
+ * so only a resume of the same call finds the record, and a fresh call is a fresh write.
84
+ *
85
+ * It rejects with a `SafetyError`, code `invalid_effect`, for an empty scope field, business key or operation, or for a
86
+ * `dedupe` that doesn't match the `reconcile` hook.
87
+ *
88
+ * @example
89
+ * ```ts
90
+ * const outcome = await guardedWrite({
91
+ * store, scope, businessKey: `refund:${input.orderId}`, operation: "refund_create", input,
92
+ * dedupe: "idempotency_key",
93
+ * run: (key) => payments.refunds.create(input, { idempotencyKey: key }),
94
+ * toOutcome: (refund) =>
95
+ * writeOutcome({ kind: "applied", operation: "refund_create", next: `Tell the user ${refund.id} is on its way` }),
96
+ * });
97
+ * ```
98
+ */
99
+ export declare function guardedWrite<T>(options: GuardedWriteOptions<T>): Promise<WriteOutcome>;
@@ -0,0 +1,245 @@
1
+ /**
2
+ * `guardedWrite()`: persist before execute. It stores an effect record before the write runs and settles it with the
3
+ * outcome after, and it treats a record left `started` by a crash as `unknown` until the tool's `reconcile` hook reads
4
+ * the external system's state. An `unknown` write is never run again under a fresh key, because the first attempt may
5
+ * have taken effect (close-sdk-gaps SG3; rewind report, "Two ledgers, and the first fields to add").
6
+ *
7
+ * The store's answers map onto the IETF Idempotency-Key draft's statuses, as the server rollback report sets out: the
8
+ * same key with a different input is the draft's 422 and is refused, and a live attempt is its 409, so the caller
9
+ * waits and retries under the same key.
10
+ */
11
+ import { checkEffectScope, effectKey } from "./effect-key.js";
12
+ import { SafetyError } from "./errors.js";
13
+ import { canonicalInputHash } from "./hash.js";
14
+ import { writeOutcome } from "./outcome.js";
15
+ const DEFAULT_LEASE_MS = 5 * 60 * 1000;
16
+ // A takeover lost to another process is re-read this many times before the call reports the write as in progress.
17
+ const MAX_REREADS = 2;
18
+ function invalid(message) {
19
+ return new SafetyError("invalid_effect", message);
20
+ }
21
+ function checkOptions(options) {
22
+ checkEffectScope(options.scope, options.businessKey);
23
+ if (typeof options.operation !== "string" || options.operation.trim() === "") {
24
+ throw invalid("a guarded write's operation must be non-empty");
25
+ }
26
+ if (!["idempotency_key", "reconcile", "unknown_only"].includes(options.dedupe)) {
27
+ throw invalid(`unknown dedupe ${JSON.stringify(options.dedupe)}`);
28
+ }
29
+ if (options.dedupe === "reconcile" && options.reconcile === undefined) {
30
+ throw invalid('a guarded write with dedupe "reconcile" needs a reconcile hook');
31
+ }
32
+ if (options.dedupe === "unknown_only" && options.reconcile !== undefined) {
33
+ throw invalid('a guarded write with dedupe "unknown_only" cannot have a reconcile hook; use "reconcile"');
34
+ }
35
+ const lease = options.leaseMs ?? DEFAULT_LEASE_MS;
36
+ if (!Number.isSafeInteger(lease) || lease <= 0)
37
+ throw invalid("a guarded write's leaseMs must be a positive integer");
38
+ }
39
+ /** The outcome with this write's effect key, unless the tool set one; checked again, so a stored one is re-checked. */
40
+ function stamped(ctx, outcome) {
41
+ return writeOutcome(outcome.effectKey === undefined ? { ...outcome, effectKey: ctx.key } : outcome);
42
+ }
43
+ /** The outcome of an attempt that may have taken effect and that nothing has checked yet. */
44
+ function unchecked(ctx, reason, why) {
45
+ const { operation, dedupe } = ctx.options;
46
+ if (dedupe === "unknown_only") {
47
+ return writeOutcome({
48
+ kind: "unknown",
49
+ operation,
50
+ effectKey: ctx.key,
51
+ retry: "never",
52
+ reason,
53
+ currentState: `${why} The system it calls offers no way to check.`,
54
+ next: "Tell the user it may have taken effect, and ask a person to check before anyone asks for it again.",
55
+ });
56
+ }
57
+ return writeOutcome({
58
+ kind: "unknown",
59
+ operation,
60
+ effectKey: ctx.key,
61
+ retry: "reconcile_first",
62
+ reason,
63
+ currentState: why,
64
+ next: "Check whether it took effect before you do anything else, and tell the user if you cannot.",
65
+ });
66
+ }
67
+ function inProgress(ctx) {
68
+ return writeOutcome({
69
+ kind: "unknown",
70
+ operation: ctx.options.operation,
71
+ effectKey: ctx.key,
72
+ retry: "same_key",
73
+ reason: "IN_PROGRESS",
74
+ currentState: "Another attempt at this write is still running.",
75
+ next: "Wait, then call the tool again for the same request.",
76
+ });
77
+ }
78
+ function keyReused(ctx) {
79
+ return writeOutcome({
80
+ kind: "not_applied",
81
+ operation: ctx.options.operation,
82
+ effectKey: ctx.key,
83
+ retry: "never",
84
+ reason: "IDEMPOTENCY_KEY_REUSED",
85
+ currentState: "An earlier write with the same business key had a different input, so this one was not sent.",
86
+ next: "Tell the user that an earlier, different request already holds this business key.",
87
+ });
88
+ }
89
+ function startedRecord(ctx, attempt) {
90
+ const time = ctx.now();
91
+ const { scope, businessKey, operation } = ctx.options;
92
+ return {
93
+ key: ctx.key,
94
+ scope,
95
+ ...(businessKey === undefined ? {} : { businessKey }),
96
+ operation,
97
+ inputHash: ctx.inputHash,
98
+ attempt,
99
+ state: "started",
100
+ startedAt: new Date(time).toISOString(),
101
+ leaseUntil: new Date(time + ctx.leaseMs).toISOString(),
102
+ };
103
+ }
104
+ async function settle(ctx, record, outcome) {
105
+ const settled = { ...record, state: "settled", outcome, settledAt: new Date(ctx.now()).toISOString() };
106
+ // A false answer means another process took the record over after this attempt's lease lapsed. Both attempts used
107
+ // one key, so this outcome is still what this attempt did, and the caller gets it either way.
108
+ await ctx.options.store.settle(settled);
109
+ return outcome;
110
+ }
111
+ async function execute(ctx, record) {
112
+ let result;
113
+ try {
114
+ result = await ctx.options.run(ctx.key);
115
+ }
116
+ catch (error) {
117
+ const { onError } = ctx.options;
118
+ if (onError === undefined) {
119
+ return settle(ctx, record, unchecked(ctx, "WRITE_FAILED", "The write threw before it reported a result."));
120
+ }
121
+ return report(ctx, record, () => onError(error, ctx.key), "The write threw, and its error could not be read.");
122
+ }
123
+ return report(ctx, record, () => ctx.options.toOutcome(result, ctx.key), "The write ran, but its outcome could not be read.");
124
+ }
125
+ /**
126
+ * Settles the tool's own outcome. If the tool's hook throws, or returns an invalid outcome, the record still settles as
127
+ * `unknown`, saying `why`, and the hook's error is rethrown, even when that settle fails too.
128
+ */
129
+ async function report(ctx, record, hook, why) {
130
+ let outcome;
131
+ try {
132
+ outcome = stamped(ctx, hook());
133
+ }
134
+ catch (error) {
135
+ // A settle that fails leaves the record started, which a later call reads as crashed, so it stays unknown anyway.
136
+ await settle(ctx, record, unchecked(ctx, "REPORT_FAILED", why)).catch(() => undefined);
137
+ throw error;
138
+ }
139
+ return settle(ctx, record, outcome);
140
+ }
141
+ /** Takes the record over under a new attempt, then runs `then`; a lost takeover re-reads the winner's record. */
142
+ async function retake(ctx, existing, depth, then) {
143
+ const record = startedRecord(ctx, existing.attempt + 1);
144
+ const claim = await ctx.options.store.takeOver(record);
145
+ return claim === "started" ? then(record) : resume(ctx, claim.existing, depth + 1);
146
+ }
147
+ /** Resumes an attempt that may have taken effect: reconcile under a fresh lease, or report `unknown`. */
148
+ async function recover(ctx, existing, depth, fallback) {
149
+ const { reconcile } = ctx.options;
150
+ if (reconcile === undefined)
151
+ return fallback;
152
+ return retake(ctx, existing, depth, async (record) => {
153
+ let found;
154
+ try {
155
+ found = await reconcile(ctx.key);
156
+ }
157
+ catch {
158
+ return settle(ctx, record, unchecked(ctx, "RECONCILE_FAILED", "Checking the earlier attempt failed."));
159
+ }
160
+ if (found === "not_found")
161
+ return execute(ctx, record);
162
+ return report(ctx, record, () => found, "The earlier attempt was checked, but the check's outcome is invalid.");
163
+ });
164
+ }
165
+ /** True for a settled outcome that may run again under the same key. */
166
+ function rerunnable(ctx, outcome) {
167
+ if (outcome.retry !== "same_key")
168
+ return false;
169
+ // A rejected write changed nothing, so it may run again whatever the system does with keys; a partial or unknown
170
+ // one may run again only where the system dedupes by key.
171
+ return outcome.kind === "not_applied" || ctx.options.dedupe === "idempotency_key";
172
+ }
173
+ async function resume(ctx, existing, depth) {
174
+ if (existing.inputHash !== ctx.inputHash || existing.operation !== ctx.options.operation)
175
+ return keyReused(ctx);
176
+ if (existing.state === "started") {
177
+ if (depth > MAX_REREADS || Date.parse(existing.leaseUntil) > ctx.now())
178
+ return inProgress(ctx);
179
+ const crashed = unchecked(ctx, "WRITE_INTERRUPTED", "An earlier attempt stopped before it recorded an outcome.");
180
+ return recover(ctx, existing, depth, crashed);
181
+ }
182
+ if (existing.outcome === undefined)
183
+ throw invalid(`the settled effect record ${existing.key} has no outcome`);
184
+ const outcome = stamped(ctx, existing.outcome);
185
+ if (depth > MAX_REREADS)
186
+ return outcome;
187
+ if (rerunnable(ctx, outcome))
188
+ return retake(ctx, existing, depth, (record) => execute(ctx, record));
189
+ // An unknown or partial outcome that a check could settle goes to `reconcile`; one marked `never` stays as it is.
190
+ if ((outcome.kind === "unknown" || outcome.kind === "partial") && outcome.retry !== "never") {
191
+ return recover(ctx, existing, depth, outcome);
192
+ }
193
+ return outcome;
194
+ }
195
+ /**
196
+ * Runs a write at most once per effect key. It stores an effect record before `run` starts and settles it with the
197
+ * outcome after, so a crash in between leaves evidence that the write may have happened:
198
+ *
199
+ * - A new key runs the write and returns its outcome, with the effect key stamped on it.
200
+ * - A settled key returns its stored outcome without running, unless that outcome allows a `same_key` retry.
201
+ * - The same key with a different input or operation returns `not_applied`, reason `IDEMPOTENCY_KEY_REUSED`, and
202
+ * sends nothing.
203
+ * - A key whose attempt is still live, perhaps in another process, returns `unknown`, reason `IN_PROGRESS`, with a
204
+ * `same_key` retry, and runs nothing.
205
+ * - A key whose attempt crashed, because its lease lapsed, calls `reconcile`: a found write returns its outcome, and
206
+ * `"not_found"` runs the write once more under the same key. Without `reconcile`, it returns `unknown`, reason
207
+ * `WRITE_INTERRUPTED`, and runs nothing: its retry is `reconcile_first`, or `never` for `dedupe: "unknown_only"`.
208
+ * - A settled `unknown` or `partial` outcome whose retry isn't `never` calls `reconcile` the same way.
209
+ *
210
+ * The key comes from `effectKey()`, and no option lets a caller pick another one. With a business key, a write whose
211
+ * outcome is `unknown` can therefore never run again under a fresh key. Without one, the key holds the tool call id,
212
+ * so only a resume of the same call finds the record, and a fresh call is a fresh write.
213
+ *
214
+ * It rejects with a `SafetyError`, code `invalid_effect`, for an empty scope field, business key or operation, or for a
215
+ * `dedupe` that doesn't match the `reconcile` hook.
216
+ *
217
+ * @example
218
+ * ```ts
219
+ * const outcome = await guardedWrite({
220
+ * store, scope, businessKey: `refund:${input.orderId}`, operation: "refund_create", input,
221
+ * dedupe: "idempotency_key",
222
+ * run: (key) => payments.refunds.create(input, { idempotencyKey: key }),
223
+ * toOutcome: (refund) =>
224
+ * writeOutcome({ kind: "applied", operation: "refund_create", next: `Tell the user ${refund.id} is on its way` }),
225
+ * });
226
+ * ```
227
+ */
228
+ export async function guardedWrite(options) {
229
+ checkOptions(options);
230
+ const [key, inputHash] = await Promise.all([
231
+ effectKey(options.scope, options.businessKey),
232
+ canonicalInputHash(options.input),
233
+ ]);
234
+ const ctx = {
235
+ options,
236
+ key,
237
+ inputHash,
238
+ now: options.now ?? Date.now,
239
+ leaseMs: options.leaseMs ?? DEFAULT_LEASE_MS,
240
+ };
241
+ const record = startedRecord(ctx, 1);
242
+ const claim = await options.store.begin(record);
243
+ return claim === "started" ? execute(ctx, record) : resume(ctx, claim.existing, 0);
244
+ }
245
+ //# sourceMappingURL=guarded-write.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guarded-write.js","sourceRoot":"","sources":["../src/guarded-write.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,gBAAgB,EAAoB,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAEhF,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EAAqB,YAAY,EAAE,MAAM,cAAc,CAAC;AAwD/D,MAAM,gBAAgB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;AACvC,kHAAkH;AAClH,MAAM,WAAW,GAAG,CAAC,CAAC;AAUtB,SAAS,OAAO,CAAC,OAAe;IAC9B,OAAO,IAAI,WAAW,CAAC,gBAAgB,EAAE,OAAO,CAAC,CAAC;AACpD,CAAC;AAED,SAAS,YAAY,CAAI,OAA+B;IACtD,gBAAgB,CAAC,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,WAAW,CAAC,CAAC;IACrD,IAAI,OAAO,OAAO,CAAC,SAAS,KAAK,QAAQ,IAAI,OAAO,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC;QAC7E,MAAM,OAAO,CAAC,+CAA+C,CAAC,CAAC;IACjE,CAAC;IACD,IAAI,CAAC,CAAC,iBAAiB,EAAE,WAAW,EAA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CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;QACzC,SAAS,CAAC,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,WAAW,CAAC;QAC7C,kBAAkB,CAAC,OAAO,CAAC,KAAK,CAAC;KAClC,CAAC,CAAC;IACH,MAAM,GAAG,GAAe;QACtB,OAAO;QACP,GAAG;QACH,SAAS;QACT,GAAG,EAAE,OAAO,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG;QAC5B,OAAO,EAAE,OAAO,CAAC,OAAO,IAAI,gBAAgB;KAC7C,CAAC;IACF,MAAM,MAAM,GAAG,aAAa,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;IACrC,MAAM,KAAK,GAAG,MAAM,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IAChD,OAAO,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC;AACrF,CAAC","sourcesContent":["/**\n * `guardedWrite()`: persist before execute. It stores an effect record before the write runs and settles it with the\n * outcome after, and it treats a record left `started` by a crash as `unknown` until the tool's `reconcile` hook reads\n * the external system's state. An `unknown` write is never run again under a fresh key, because the first attempt may\n * have taken effect (close-sdk-gaps SG3; rewind report, \"Two ledgers, and the first fields to add\").\n *\n * The store's answers map onto the IETF Idempotency-Key draft's statuses, as the server rollback report sets out: the\n * same key with a different input is the draft's 422 and is refused, and a live attempt is its 409, so the caller\n * waits and retries under the same key.\n */\nimport { checkEffectScope, type EffectScope, effectKey } from \"./effect-key.js\";\nimport type { EffectRecord, EffectStore } from \"./effect-store.js\";\nimport { SafetyError } from \"./errors.js\";\nimport { canonicalInputHash } from \"./hash.js\";\nimport { type WriteOutcome, writeOutcome } from \"./outcome.js\";\n\n/**\n * How a retry can find out what an earlier attempt of the write did. `idempotency_key`: the external API dedupes by\n * the key `run` sends, as Stripe's `Idempotency-Key` header does. `reconcile`: the API ignores keys, but the tool's\n * `reconcile` hook can find the write by a field the tool sets, such as a message id. `unknown_only`: neither, so an\n * interrupted attempt stays `unknown` for good and a person must check it; put such a tool behind an approval.\n */\nexport type WriteDedupe = \"idempotency_key\" | \"reconcile\" | \"unknown_only\";\n\n/** The options of `guardedWrite()`. */\nexport interface GuardedWriteOptions<T> {\n /** Where the effect records live. Use a durable store wherever a crash must not repeat the write. */\n readonly store: EffectStore;\n /** The tenant, session, branch and tool call the write was asked for. */\n readonly scope: EffectScope;\n /**\n * The business operation the write performs, such as `refund:{orderId}`. Set it for every tool that sends, submits,\n * pays or deletes, so a regenerated turn or a new session maps to the same effect. One business key names one\n * operation for good: a write the user asks for again as a new operation, such as a second refund of one order,\n * needs a new business key, such as one that adds the request's own id.\n */\n readonly businessKey?: string;\n /** The tool or business operation, such as `refund_create`. */\n readonly operation: string;\n /** The tool's input. Its canonical hash is stored; a later call with the same key and another input is refused. */\n readonly input: unknown;\n /** How a retry finds out what an earlier attempt did. */\n readonly dedupe: WriteDedupe;\n /** Runs the write. Pass `key` to the external API's idempotency header, or set it where `reconcile` can find it. */\n run(key: string): Promise<T>;\n /** Turns what `run` returned into the write's outcome. `key` is the effect key, for an outcome that names it. */\n toOutcome(result: T, key: string): WriteOutcome;\n /**\n * Turns an error `run` threw into an outcome, for errors the tool knows took no effect, such as a validation\n * failure. Without it, every error from `run` is `unknown`, because the request may have reached the system. `key` is\n * the effect key, which an `unknown` or `partial` outcome needs for a `same_key` retry.\n */\n onError?(error: unknown, key: string): WriteOutcome;\n /**\n * Reads the external system's state by key, for a resume after a crash or an `unknown` outcome. Return the outcome\n * if the write took effect or was rejected, or `\"not_found\"` if it never reached the system, and the write then\n * runs again under the same key. Required for `dedupe: \"reconcile\"`, refused for `\"unknown_only\"`.\n */\n reconcile?(key: string): Promise<WriteOutcome | \"not_found\">;\n /**\n * How long a started attempt counts as live, in milliseconds. A call that finds a live attempt gets `unknown` with\n * reason `IN_PROGRESS`; once the lease lapses, the attempt counts as crashed. Make it longer than the slowest write\n * plus the clock skew between the hosts that share the store, because the lease is read on the resuming host's clock.\n * Defaults to five minutes.\n */\n readonly leaseMs?: number;\n /** Returns the current time in milliseconds. Defaults to `Date.now`. */\n readonly now?: () => number;\n}\n\nconst DEFAULT_LEASE_MS = 5 * 60 * 1000;\n// A takeover lost to another process is re-read this many times before the call reports the write as in progress.\nconst MAX_REREADS = 2;\n\ninterface Context<T> {\n readonly options: GuardedWriteOptions<T>;\n readonly key: string;\n readonly inputHash: string;\n readonly now: () => number;\n readonly leaseMs: number;\n}\n\nfunction invalid(message: string): SafetyError {\n return new SafetyError(\"invalid_effect\", message);\n}\n\nfunction checkOptions<T>(options: GuardedWriteOptions<T>): void {\n checkEffectScope(options.scope, options.businessKey);\n if (typeof options.operation !== \"string\" || options.operation.trim() === \"\") {\n throw invalid(\"a guarded write's operation must be non-empty\");\n }\n if (![\"idempotency_key\", \"reconcile\", \"unknown_only\"].includes(options.dedupe)) {\n throw invalid(`unknown dedupe ${JSON.stringify(options.dedupe)}`);\n }\n if (options.dedupe === \"reconcile\" && options.reconcile === undefined) {\n throw invalid('a guarded write with dedupe \"reconcile\" needs a reconcile hook');\n }\n if (options.dedupe === \"unknown_only\" && options.reconcile !== undefined) {\n throw invalid('a guarded write with dedupe \"unknown_only\" cannot have a reconcile hook; use \"reconcile\"');\n }\n const lease = options.leaseMs ?? DEFAULT_LEASE_MS;\n if (!Number.isSafeInteger(lease) || lease <= 0) throw invalid(\"a guarded write's leaseMs must be a positive integer\");\n}\n\n/** The outcome with this write's effect key, unless the tool set one; checked again, so a stored one is re-checked. */\nfunction stamped(ctx: Context<unknown>, outcome: WriteOutcome): WriteOutcome {\n return writeOutcome(outcome.effectKey === undefined ? { ...outcome, effectKey: ctx.key } : outcome);\n}\n\n/** The outcome of an attempt that may have taken effect and that nothing has checked yet. */\nfunction unchecked(ctx: Context<unknown>, reason: string, why: string): WriteOutcome {\n const { operation, dedupe } = ctx.options;\n if (dedupe === \"unknown_only\") {\n return writeOutcome({\n kind: \"unknown\",\n operation,\n effectKey: ctx.key,\n retry: \"never\",\n reason,\n currentState: `${why} The system it calls offers no way to check.`,\n next: \"Tell the user it may have taken effect, and ask a person to check before anyone asks for it again.\",\n });\n }\n return writeOutcome({\n kind: \"unknown\",\n operation,\n effectKey: ctx.key,\n retry: \"reconcile_first\",\n reason,\n currentState: why,\n next: \"Check whether it took effect before you do anything else, and tell the user if you cannot.\",\n });\n}\n\nfunction inProgress(ctx: Context<unknown>): WriteOutcome {\n return writeOutcome({\n kind: \"unknown\",\n operation: ctx.options.operation,\n effectKey: ctx.key,\n retry: \"same_key\",\n reason: \"IN_PROGRESS\",\n currentState: \"Another attempt at this write is still running.\",\n next: \"Wait, then call the tool again for the same request.\",\n });\n}\n\nfunction keyReused(ctx: Context<unknown>): WriteOutcome {\n return writeOutcome({\n kind: \"not_applied\",\n operation: ctx.options.operation,\n effectKey: ctx.key,\n retry: \"never\",\n reason: \"IDEMPOTENCY_KEY_REUSED\",\n currentState: \"An earlier write with the same business key had a different input, so this one was not sent.\",\n next: \"Tell the user that an earlier, different request already holds this business key.\",\n });\n}\n\nfunction startedRecord(ctx: Context<unknown>, attempt: number): EffectRecord {\n const time = ctx.now();\n const { scope, businessKey, operation } = ctx.options;\n return {\n key: ctx.key,\n scope,\n ...(businessKey === undefined ? {} : { businessKey }),\n operation,\n inputHash: ctx.inputHash,\n attempt,\n state: \"started\",\n startedAt: new Date(time).toISOString(),\n leaseUntil: new Date(time + ctx.leaseMs).toISOString(),\n };\n}\n\nasync function settle(ctx: Context<unknown>, record: EffectRecord, outcome: WriteOutcome): Promise<WriteOutcome> {\n const settled: EffectRecord = { ...record, state: \"settled\", outcome, settledAt: new Date(ctx.now()).toISOString() };\n // A false answer means another process took the record over after this attempt's lease lapsed. Both attempts used\n // one key, so this outcome is still what this attempt did, and the caller gets it either way.\n await ctx.options.store.settle(settled);\n return outcome;\n}\n\nasync function execute<T>(ctx: Context<T>, record: EffectRecord): Promise<WriteOutcome> {\n let result: T;\n try {\n result = await ctx.options.run(ctx.key);\n } catch (error) {\n const { onError } = ctx.options;\n if (onError === undefined) {\n return settle(ctx, record, unchecked(ctx, \"WRITE_FAILED\", \"The write threw before it reported a result.\"));\n }\n return report(ctx, record, () => onError(error, ctx.key), \"The write threw, and its error could not be read.\");\n }\n return report(\n ctx,\n record,\n () => ctx.options.toOutcome(result, ctx.key),\n \"The write ran, but its outcome could not be read.\",\n );\n}\n\n/**\n * Settles the tool's own outcome. If the tool's hook throws, or returns an invalid outcome, the record still settles as\n * `unknown`, saying `why`, and the hook's error is rethrown, even when that settle fails too.\n */\nasync function report(\n ctx: Context<unknown>,\n record: EffectRecord,\n hook: () => WriteOutcome,\n why: string,\n): Promise<WriteOutcome> {\n let outcome: WriteOutcome;\n try {\n outcome = stamped(ctx, hook());\n } catch (error) {\n // A settle that fails leaves the record started, which a later call reads as crashed, so it stays unknown anyway.\n await settle(ctx, record, unchecked(ctx, \"REPORT_FAILED\", why)).catch(() => undefined);\n throw error;\n }\n return settle(ctx, record, outcome);\n}\n\n/** Takes the record over under a new attempt, then runs `then`; a lost takeover re-reads the winner's record. */\nasync function retake<T>(\n ctx: Context<T>,\n existing: EffectRecord,\n depth: number,\n then: (record: EffectRecord) => Promise<WriteOutcome>,\n): Promise<WriteOutcome> {\n const record = startedRecord(ctx, existing.attempt + 1);\n const claim = await ctx.options.store.takeOver(record);\n return claim === \"started\" ? then(record) : resume(ctx, claim.existing, depth + 1);\n}\n\n/** Resumes an attempt that may have taken effect: reconcile under a fresh lease, or report `unknown`. */\nasync function recover<T>(\n ctx: Context<T>,\n existing: EffectRecord,\n depth: number,\n fallback: WriteOutcome,\n): Promise<WriteOutcome> {\n const { reconcile } = ctx.options;\n if (reconcile === undefined) return fallback;\n return retake(ctx, existing, depth, async (record) => {\n let found: WriteOutcome | \"not_found\";\n try {\n found = await reconcile(ctx.key);\n } catch {\n return settle(ctx, record, unchecked(ctx, \"RECONCILE_FAILED\", \"Checking the earlier attempt failed.\"));\n }\n if (found === \"not_found\") return execute(ctx, record);\n return report(ctx, record, () => found, \"The earlier attempt was checked, but the check's outcome is invalid.\");\n });\n}\n\n/** True for a settled outcome that may run again under the same key. */\nfunction rerunnable(ctx: Context<unknown>, outcome: WriteOutcome): boolean {\n if (outcome.retry !== \"same_key\") return false;\n // A rejected write changed nothing, so it may run again whatever the system does with keys; a partial or unknown\n // one may run again only where the system dedupes by key.\n return outcome.kind === \"not_applied\" || ctx.options.dedupe === \"idempotency_key\";\n}\n\nasync function resume<T>(ctx: Context<T>, existing: EffectRecord, depth: number): Promise<WriteOutcome> {\n if (existing.inputHash !== ctx.inputHash || existing.operation !== ctx.options.operation) return keyReused(ctx);\n if (existing.state === \"started\") {\n if (depth > MAX_REREADS || Date.parse(existing.leaseUntil) > ctx.now()) return inProgress(ctx);\n const crashed = unchecked(ctx, \"WRITE_INTERRUPTED\", \"An earlier attempt stopped before it recorded an outcome.\");\n return recover(ctx, existing, depth, crashed);\n }\n if (existing.outcome === undefined) throw invalid(`the settled effect record ${existing.key} has no outcome`);\n const outcome = stamped(ctx, existing.outcome);\n if (depth > MAX_REREADS) return outcome;\n if (rerunnable(ctx, outcome)) return retake(ctx, existing, depth, (record) => execute(ctx, record));\n // An unknown or partial outcome that a check could settle goes to `reconcile`; one marked `never` stays as it is.\n if ((outcome.kind === \"unknown\" || outcome.kind === \"partial\") && outcome.retry !== \"never\") {\n return recover(ctx, existing, depth, outcome);\n }\n return outcome;\n}\n\n/**\n * Runs a write at most once per effect key. It stores an effect record before `run` starts and settles it with the\n * outcome after, so a crash in between leaves evidence that the write may have happened:\n *\n * - A new key runs the write and returns its outcome, with the effect key stamped on it.\n * - A settled key returns its stored outcome without running, unless that outcome allows a `same_key` retry.\n * - The same key with a different input or operation returns `not_applied`, reason `IDEMPOTENCY_KEY_REUSED`, and\n * sends nothing.\n * - A key whose attempt is still live, perhaps in another process, returns `unknown`, reason `IN_PROGRESS`, with a\n * `same_key` retry, and runs nothing.\n * - A key whose attempt crashed, because its lease lapsed, calls `reconcile`: a found write returns its outcome, and\n * `\"not_found\"` runs the write once more under the same key. Without `reconcile`, it returns `unknown`, reason\n * `WRITE_INTERRUPTED`, and runs nothing: its retry is `reconcile_first`, or `never` for `dedupe: \"unknown_only\"`.\n * - A settled `unknown` or `partial` outcome whose retry isn't `never` calls `reconcile` the same way.\n *\n * The key comes from `effectKey()`, and no option lets a caller pick another one. With a business key, a write whose\n * outcome is `unknown` can therefore never run again under a fresh key. Without one, the key holds the tool call id,\n * so only a resume of the same call finds the record, and a fresh call is a fresh write.\n *\n * It rejects with a `SafetyError`, code `invalid_effect`, for an empty scope field, business key or operation, or for a\n * `dedupe` that doesn't match the `reconcile` hook.\n *\n * @example\n * ```ts\n * const outcome = await guardedWrite({\n * store, scope, businessKey: `refund:${input.orderId}`, operation: \"refund_create\", input,\n * dedupe: \"idempotency_key\",\n * run: (key) => payments.refunds.create(input, { idempotencyKey: key }),\n * toOutcome: (refund) =>\n * writeOutcome({ kind: \"applied\", operation: \"refund_create\", next: `Tell the user ${refund.id} is on its way` }),\n * });\n * ```\n */\nexport async function guardedWrite<T>(options: GuardedWriteOptions<T>): Promise<WriteOutcome> {\n checkOptions(options);\n const [key, inputHash] = await Promise.all([\n effectKey(options.scope, options.businessKey),\n canonicalInputHash(options.input),\n ]);\n const ctx: Context<T> = {\n options,\n key,\n inputHash,\n now: options.now ?? Date.now,\n leaseMs: options.leaseMs ?? DEFAULT_LEASE_MS,\n };\n const record = startedRecord(ctx, 1);\n const claim = await options.store.begin(record);\n return claim === \"started\" ? execute(ctx, record) : resume(ctx, claim.existing, 0);\n}\n"]}
package/dist/hash.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Hashes a tool input: the SHA-256 of its canonical JSON (RFC 8785), as 64 lowercase hex digits. Two inputs whose
3
+ * object keys differ only in order get the same hash, and any changed value gives a different one. Object properties
4
+ * set to `undefined` are left out, as `JSON.stringify` leaves them out. The hash is async, because Web Crypto's
5
+ * digest is.
6
+ *
7
+ * It rejects with a `SafetyError`, code `invalid_input`, for a value that has no single JSON form:
8
+ * - `undefined`, or a hole, in an array;
9
+ * - a number that isn't finite;
10
+ * - a string with a lone surrogate;
11
+ * - a bigint, symbol or function;
12
+ * - an object that isn't plain, such as a `Date` (a plain object's prototype is `null` or any realm's
13
+ * `Object.prototype`);
14
+ * - an object or array that contains itself.
15
+ */
16
+ export declare function canonicalInputHash(input: unknown): Promise<string>;
17
+ /**
18
+ * The canonical JSON (RFC 8785) text `canonicalInputHash()` hashes, read from the value once and synchronously, with
19
+ * the same errors. `planCard()` parses it back, so a card shows the exact value its hash covers. Not exported from
20
+ * the package.
21
+ */
22
+ export declare function canonicalJson(input: unknown): string;
23
+ /** The SHA-256 of canonical JSON text from `canonicalJson()`, as 64 lowercase hex digits. Not exported from the package. */
24
+ export declare function canonicalTextHash(text: string): Promise<string>;
package/dist/hash.js ADDED
@@ -0,0 +1,121 @@
1
+ /**
2
+ * `canonicalInputHash()`: one hash per tool input, whatever order its keys arrive in. Approvals sign it and effect
3
+ * records store it, so both must compute it the same way on every runtime: canonical JSON as RFC 8785 (JCS) defines
4
+ * it, hashed with Web Crypto's SHA-256. Web Crypto is read as the bare `crypto` global, the same object as
5
+ * `globalThis.crypto`, because the Workers types declare it as a `const`, which `typeof globalThis` lacks.
6
+ */
7
+ import { SafetyError } from "./errors.js";
8
+ const ENCODER = new TextEncoder();
9
+ function invalid(path, why) {
10
+ return new SafetyError("invalid_input", `the input at ${path} ${why}, so it has no canonical JSON form`);
11
+ }
12
+ function canonicalString(value, path) {
13
+ // JCS refuses lone surrogates, which JSON.stringify would escape instead.
14
+ if (!value.isWellFormed())
15
+ throw invalid(path, "holds a lone surrogate");
16
+ return JSON.stringify(value);
17
+ }
18
+ function canonicalNumber(value, path) {
19
+ if (!Number.isFinite(value))
20
+ throw invalid(path, `is ${value}`);
21
+ // JCS serializes numbers as ECMAScript does, which JSON.stringify follows, including -0 as 0.
22
+ return JSON.stringify(value);
23
+ }
24
+ // Plain means a null prototype or any realm's `Object.prototype`, whose own prototype is null: an object made in a
25
+ // `vm` context or an iframe is as plain as one made here, while a `Date` or class instance is not.
26
+ function isPlainObject(value) {
27
+ const prototype = Object.getPrototypeOf(value);
28
+ return prototype === null || Object.getPrototypeOf(prototype) === null;
29
+ }
30
+ function byKey([a], [b]) {
31
+ // JCS sorts property names by UTF-16 code units, which is what `<` compares.
32
+ return a < b ? -1 : a > b ? 1 : 0;
33
+ }
34
+ // `ancestors` holds the objects and arrays that enclose the current value, so a cycle throws instead of recursing
35
+ // until the stack runs out. A value shared by two siblings is no cycle, so it is removed again on the way out.
36
+ function canonicalObject(value, path, ancestors) {
37
+ // Each property is read once, so a getter or a Proxy can't be counted as present and then read as undefined.
38
+ const entries = Object.entries(value)
39
+ .filter(([, item]) => item !== undefined)
40
+ .sort(byKey);
41
+ const members = entries.map(([key, item]) => `${canonicalString(key, `${path}'s property name`)}:${canonical(item, `${path}.${key}`, ancestors)}`);
42
+ return `{${members.join(",")}}`;
43
+ }
44
+ function canonicalArray(value, path, ancestors) {
45
+ // An index loop, because `map` skips the holes of a sparse array and `join` would then write `[1,,3]`.
46
+ const items = [];
47
+ for (let index = 0; index < value.length; index++) {
48
+ const itemPath = `${path}[${index}]`;
49
+ if (!(index in value))
50
+ throw invalid(itemPath, "is a hole in a sparse array");
51
+ const item = value[index];
52
+ if (item === undefined)
53
+ throw invalid(itemPath, "is undefined");
54
+ items.push(canonical(item, itemPath, ancestors));
55
+ }
56
+ return `[${items.join(",")}]`;
57
+ }
58
+ function nested(value, path, ancestors, write) {
59
+ if (ancestors.has(value))
60
+ throw invalid(path, "refers back to an object that contains it");
61
+ ancestors.add(value);
62
+ try {
63
+ return write();
64
+ }
65
+ finally {
66
+ ancestors.delete(value);
67
+ }
68
+ }
69
+ function describeType(value) {
70
+ if (value === undefined)
71
+ return "undefined";
72
+ return typeof value === "object" ? "an object that isn't plain" : `a ${typeof value}`;
73
+ }
74
+ function canonical(value, path, ancestors) {
75
+ if (value === null || typeof value === "boolean")
76
+ return JSON.stringify(value);
77
+ if (typeof value === "string")
78
+ return canonicalString(value, path);
79
+ if (typeof value === "number")
80
+ return canonicalNumber(value, path);
81
+ if (Array.isArray(value))
82
+ return nested(value, path, ancestors, () => canonicalArray(value, path, ancestors));
83
+ if (typeof value === "object" && isPlainObject(value)) {
84
+ return nested(value, path, ancestors, () => canonicalObject(value, path, ancestors));
85
+ }
86
+ throw invalid(path, `is ${describeType(value)}`);
87
+ }
88
+ function hex(bytes) {
89
+ return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
90
+ }
91
+ /**
92
+ * Hashes a tool input: the SHA-256 of its canonical JSON (RFC 8785), as 64 lowercase hex digits. Two inputs whose
93
+ * object keys differ only in order get the same hash, and any changed value gives a different one. Object properties
94
+ * set to `undefined` are left out, as `JSON.stringify` leaves them out. The hash is async, because Web Crypto's
95
+ * digest is.
96
+ *
97
+ * It rejects with a `SafetyError`, code `invalid_input`, for a value that has no single JSON form:
98
+ * - `undefined`, or a hole, in an array;
99
+ * - a number that isn't finite;
100
+ * - a string with a lone surrogate;
101
+ * - a bigint, symbol or function;
102
+ * - an object that isn't plain, such as a `Date` (a plain object's prototype is `null` or any realm's
103
+ * `Object.prototype`);
104
+ * - an object or array that contains itself.
105
+ */
106
+ export async function canonicalInputHash(input) {
107
+ return canonicalTextHash(canonicalJson(input));
108
+ }
109
+ /**
110
+ * The canonical JSON (RFC 8785) text `canonicalInputHash()` hashes, read from the value once and synchronously, with
111
+ * the same errors. `planCard()` parses it back, so a card shows the exact value its hash covers. Not exported from
112
+ * the package.
113
+ */
114
+ export function canonicalJson(input) {
115
+ return canonical(input, "$", new Set());
116
+ }
117
+ /** The SHA-256 of canonical JSON text from `canonicalJson()`, as 64 lowercase hex digits. Not exported from the package. */
118
+ export async function canonicalTextHash(text) {
119
+ return hex(await crypto.subtle.digest("SHA-256", ENCODER.encode(text)));
120
+ }
121
+ //# sourceMappingURL=hash.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hash.js","sourceRoot":"","sources":["../src/hash.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAElC,SAAS,OAAO,CAAC,IAAY,EAAE,GAAW;IACxC,OAAO,IAAI,WAAW,CAAC,eAAe,EAAE,gBAAgB,IAAI,IAAI,GAAG,oCAAoC,CAAC,CAAC;AAC3G,CAAC;AAED,SAAS,eAAe,CAAC,KAAa,EAAE,IAAY;IAClD,0EAA0E;IAC1E,IAAI,CAAC,KAAK,CAAC,YAAY,EAAE;QAAE,MAAM,OAAO,CAAC,IAAI,EAAE,wBAAwB,CAAC,CAAC;IACzE,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AAC/B,CAAC;AAED,SAAS,eAAe,CAAC,KAAa,EAAE,IAAY;IAClD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,MAAM,OAAO,CAAC,IAAI,EAAE,MAAM,KAAK,EAAE,CAAC,CAAC;IAChE,8FAA8F;IAC9F,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AAC/B,CAAC;AAED,mHAAmH;AACnH,mGAAmG;AACnG,SAAS,aAAa,CAAC,KAAa;IAClC,MAAM,SAAS,GAAG,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;IAC/C,OAAO,SAAS,KAAK,IAAI,IAAI,MAAM,CAAC,cAAc,CAAC,SAAS,CAAC,KAAK,IAAI,CAAC;AACzE,CAAC;AAED,SAAS,KAAK,CAAC,CAAC,CAAC,CAAoB,EAAE,CAAC,CAAC,CAAoB;IAC3D,6EAA6E;IAC7E,OAAO,CAAC,GAAG,CAAC,CAAC,CA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ys arrive in. Approvals sign it and effect\n * records store it, so both must compute it the same way on every runtime: canonical JSON as RFC 8785 (JCS) defines\n * it, hashed with Web Crypto's SHA-256. Web Crypto is read as the bare `crypto` global, the same object as\n * `globalThis.crypto`, because the Workers types declare it as a `const`, which `typeof globalThis` lacks.\n */\nimport { SafetyError } from \"./errors.js\";\n\nconst ENCODER = new TextEncoder();\n\nfunction invalid(path: string, why: string): SafetyError {\n return new SafetyError(\"invalid_input\", `the input at ${path} ${why}, so it has no canonical JSON form`);\n}\n\nfunction canonicalString(value: string, path: string): string {\n // JCS refuses lone surrogates, which JSON.stringify would escape instead.\n if (!value.isWellFormed()) throw invalid(path, \"holds a lone surrogate\");\n return JSON.stringify(value);\n}\n\nfunction canonicalNumber(value: number, path: string): string {\n if (!Number.isFinite(value)) throw invalid(path, `is ${value}`);\n // JCS serializes numbers as ECMAScript does, which JSON.stringify follows, including -0 as 0.\n return JSON.stringify(value);\n}\n\n// Plain means a null prototype or any realm's `Object.prototype`, whose own prototype is null: an object made in a\n// `vm` context or an iframe is as plain as one made here, while a `Date` or class instance is not.\nfunction isPlainObject(value: object): value is Record<string, unknown> {\n const prototype = Object.getPrototypeOf(value);\n return prototype === null || Object.getPrototypeOf(prototype) === null;\n}\n\nfunction byKey([a]: [string, unknown], [b]: [string, unknown]): number {\n // JCS sorts property names by UTF-16 code units, which is what `<` compares.\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n// `ancestors` holds the objects and arrays that enclose the current value, so a cycle throws instead of recursing\n// until the stack runs out. A value shared by two siblings is no cycle, so it is removed again on the way out.\nfunction canonicalObject(value: Record<string, unknown>, path: string, ancestors: Set<object>): string {\n // Each property is read once, so a getter or a Proxy can't be counted as present and then read as undefined.\n const entries = Object.entries(value)\n .filter(([, item]) => item !== undefined)\n .sort(byKey);\n const members = entries.map(\n ([key, item]) =>\n `${canonicalString(key, `${path}'s property name`)}:${canonical(item, `${path}.${key}`, ancestors)}`,\n );\n return `{${members.join(\",\")}}`;\n}\n\nfunction canonicalArray(value: readonly unknown[], path: string, ancestors: Set<object>): string {\n // An index loop, because `map` skips the holes of a sparse array and `join` would then write `[1,,3]`.\n const items: string[] = [];\n for (let index = 0; index < value.length; index++) {\n const itemPath = `${path}[${index}]`;\n if (!(index in value)) throw invalid(itemPath, \"is a hole in a sparse array\");\n const item = value[index];\n if (item === undefined) throw invalid(itemPath, \"is undefined\");\n items.push(canonical(item, itemPath, ancestors));\n }\n return `[${items.join(\",\")}]`;\n}\n\nfunction nested(value: object, path: string, ancestors: Set<object>, write: () => string): string {\n if (ancestors.has(value)) throw invalid(path, \"refers back to an object that contains it\");\n ancestors.add(value);\n try {\n return write();\n } finally {\n ancestors.delete(value);\n }\n}\n\nfunction describeType(value: unknown): string {\n if (value === undefined) return \"undefined\";\n return typeof value === \"object\" ? \"an object that isn't plain\" : `a ${typeof value}`;\n}\n\nfunction canonical(value: unknown, path: string, ancestors: Set<object>): string {\n if (value === null || typeof value === \"boolean\") return JSON.stringify(value);\n if (typeof value === \"string\") return canonicalString(value, path);\n if (typeof value === \"number\") return canonicalNumber(value, path);\n if (Array.isArray(value)) return nested(value, path, ancestors, () => canonicalArray(value, path, ancestors));\n if (typeof value === \"object\" && isPlainObject(value)) {\n return nested(value, path, ancestors, () => canonicalObject(value, path, ancestors));\n }\n throw invalid(path, `is ${describeType(value)}`);\n}\n\nfunction hex(bytes: ArrayBuffer): string {\n return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Hashes a tool input: the SHA-256 of its canonical JSON (RFC 8785), as 64 lowercase hex digits. Two inputs whose\n * object keys differ only in order get the same hash, and any changed value gives a different one. Object properties\n * set to `undefined` are left out, as `JSON.stringify` leaves them out. The hash is async, because Web Crypto's\n * digest is.\n *\n * It rejects with a `SafetyError`, code `invalid_input`, for a value that has no single JSON form:\n * - `undefined`, or a hole, in an array;\n * - a number that isn't finite;\n * - a string with a lone surrogate;\n * - a bigint, symbol or function;\n * - an object that isn't plain, such as a `Date` (a plain object's prototype is `null` or any realm's\n * `Object.prototype`);\n * - an object or array that contains itself.\n */\nexport async function canonicalInputHash(input: unknown): Promise<string> {\n return canonicalTextHash(canonicalJson(input));\n}\n\n/**\n * The canonical JSON (RFC 8785) text `canonicalInputHash()` hashes, read from the value once and synchronously, with\n * the same errors. `planCard()` parses it back, so a card shows the exact value its hash covers. Not exported from\n * the package.\n */\nexport function canonicalJson(input: unknown): string {\n return canonical(input, \"$\", new Set());\n}\n\n/** The SHA-256 of canonical JSON text from `canonicalJson()`, as 64 lowercase hex digits. Not exported from the package. */\nexport async function canonicalTextHash(text: string): Promise<string> {\n return hex(await crypto.subtle.digest(\"SHA-256\", ENCODER.encode(text)));\n}\n"]}