@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,24 @@
1
+ /**
2
+ * The `EffectStore` conformance cases: what every store must do for `guardedWrite()` to run a write at most once. The
3
+ * memory store runs them in this package's tests, and each durable store, on Cloudflare, AWS or Vercel, runs the same
4
+ * list. The cases throw plain `Error`s and import no test runner, so any runner, and workerd, can call them.
5
+ */
6
+ import type { EffectStore } from "./effect-store.js";
7
+ /** One conformance case: a name a test runner can show, and a check that rejects if the store breaks the rule. */
8
+ export interface EffectStoreCase {
9
+ /** What the case checks, as a sentence. */
10
+ readonly name: string;
11
+ /** Runs the check against a fresh, empty store from `makeStore`. */
12
+ run(makeStore: () => EffectStore | Promise<EffectStore>): Promise<void>;
13
+ }
14
+ /**
15
+ * The cases every `EffectStore` must pass. Run each against a fresh store:
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * for (const conformance of effectStoreConformance()) {
20
+ * test(conformance.name, () => conformance.run(() => myEffectStore()));
21
+ * }
22
+ * ```
23
+ */
24
+ export declare function effectStoreConformance(): readonly EffectStoreCase[];
@@ -0,0 +1,140 @@
1
+ import { writeOutcome } from "./outcome.js";
2
+ const START = "2026-11-19T10:00:00.000Z";
3
+ function record(key, attempt = 1, changes = {}) {
4
+ return {
5
+ key,
6
+ scope: { tenant: "tenant-1", session: "session-1", branch: "main", toolCallId: `call-${attempt}` },
7
+ businessKey: "refund:4417",
8
+ operation: "refund_create",
9
+ inputHash: "a".repeat(64),
10
+ attempt,
11
+ state: "started",
12
+ startedAt: START,
13
+ leaseUntil: "2026-11-19T10:05:00.000Z",
14
+ ...changes,
15
+ };
16
+ }
17
+ function settled(key, attempt = 1) {
18
+ const outcome = writeOutcome({ kind: "applied", operation: "refund_create", effectKey: key, next: "Tell the user" });
19
+ return record(key, attempt, { state: "settled", outcome, settledAt: "2026-11-19T10:01:00.000Z" });
20
+ }
21
+ function check(condition, message) {
22
+ if (!condition)
23
+ throw new Error(`EffectStore conformance: ${message}`);
24
+ }
25
+ // Compares records as JSON, so a store that serializes them passes, while a missing or changed field fails.
26
+ function same(actual, expected, message) {
27
+ check(JSON.stringify(sorted(actual)) === JSON.stringify(sorted(expected)), message);
28
+ }
29
+ function sorted(value) {
30
+ if (Array.isArray(value))
31
+ return value.map(sorted);
32
+ if (typeof value !== "object" || value === null)
33
+ return value;
34
+ return Object.fromEntries(Object.entries(value)
35
+ .filter(([, item]) => item !== undefined)
36
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
37
+ .map(([key, item]) => [key, sorted(item)]));
38
+ }
39
+ const CASES = [
40
+ {
41
+ name: "begin stores a new record, and get returns it with every field",
42
+ async run(makeStore) {
43
+ const store = await makeStore();
44
+ check((await store.begin(record("k1"))) === "started", "begin of a new key must return started");
45
+ same(await store.get("k1"), record("k1"), "get must return the record begin stored");
46
+ check((await store.get("absent")) === undefined, "get of an absent key must return undefined");
47
+ },
48
+ },
49
+ {
50
+ name: "begin on a key that exists returns the existing record and replaces nothing",
51
+ async run(makeStore) {
52
+ const store = await makeStore();
53
+ await store.begin(record("k1"));
54
+ const claim = await store.begin(record("k1", 1, { inputHash: "b".repeat(64) }));
55
+ check(claim !== "started", "a second begin must not start");
56
+ same(claim === "started" ? undefined : claim.existing, record("k1"), "begin must return the stored record");
57
+ same(await store.get("k1"), record("k1"), "a second begin must not replace the record");
58
+ },
59
+ },
60
+ {
61
+ name: "of many concurrent begins on one key, exactly one starts",
62
+ async run(makeStore) {
63
+ const store = await makeStore();
64
+ const claims = await Promise.all(Array.from({ length: 8 }, () => store.begin(record("k1"))));
65
+ check(claims.filter((claim) => claim === "started").length === 1, "exactly one begin must start");
66
+ },
67
+ },
68
+ {
69
+ name: "takeOver succeeds only from the attempt before it",
70
+ async run(makeStore) {
71
+ const store = await makeStore();
72
+ await store.begin(record("k1"));
73
+ check((await store.takeOver(record("k1", 3))) !== "started", "a takeover that skips an attempt must fail");
74
+ check((await store.takeOver(record("k1", 2))) === "started", "a takeover from the stored attempt must start");
75
+ const stale = await store.takeOver(record("k1", 2));
76
+ check(stale !== "started", "a second takeover from the same attempt must fail");
77
+ same(stale === "started" ? undefined : stale.existing, record("k1", 2), "a failed takeover returns the record");
78
+ },
79
+ },
80
+ {
81
+ name: "of many concurrent takeovers from one attempt, exactly one starts",
82
+ async run(makeStore) {
83
+ const store = await makeStore();
84
+ await store.begin(record("k1"));
85
+ const claims = await Promise.all(Array.from({ length: 8 }, () => store.takeOver(record("k1", 2))));
86
+ check(claims.filter((claim) => claim === "started").length === 1, "exactly one takeover must start");
87
+ },
88
+ },
89
+ {
90
+ name: "takeOver of a settled record starts a new attempt",
91
+ async run(makeStore) {
92
+ const store = await makeStore();
93
+ await store.begin(record("k1"));
94
+ await store.settle(settled("k1"));
95
+ check((await store.takeOver(record("k1", 2))) === "started", "a settled record must be taken over");
96
+ same(await store.get("k1"), record("k1", 2), "the takeover must replace the settled record");
97
+ },
98
+ },
99
+ {
100
+ name: "settle stores the outcome only for the started attempt that holds the record",
101
+ async run(makeStore) {
102
+ const store = await makeStore();
103
+ await store.begin(record("k1"));
104
+ await store.takeOver(record("k1", 2));
105
+ check(!(await store.settle(settled("k1", 1))), "a settle from a superseded attempt must fail");
106
+ same(await store.get("k1"), record("k1", 2), "a failed settle must change nothing");
107
+ check(await store.settle(settled("k1", 2)), "a settle from the current attempt must succeed");
108
+ same(await store.get("k1"), settled("k1", 2), "get must return the settled record with its outcome");
109
+ check(!(await store.settle(settled("k1", 2))), "a second settle of a settled record must fail");
110
+ check(!(await store.settle(settled("absent"))), "a settle of an absent key must fail");
111
+ },
112
+ },
113
+ {
114
+ name: "a record changed after it was stored or read leaves the stored one as it was",
115
+ async run(makeStore) {
116
+ const store = await makeStore();
117
+ const original = { ...record("k1"), scope: { ...record("k1").scope } };
118
+ await store.begin(original);
119
+ original.scope.tenant = "someone-else";
120
+ const read = await store.get("k1");
121
+ if (read !== undefined)
122
+ read.scope.tenant = "someone-else";
123
+ same(await store.get("k1"), record("k1"), "the store must keep its own copy");
124
+ },
125
+ },
126
+ ];
127
+ /**
128
+ * The cases every `EffectStore` must pass. Run each against a fresh store:
129
+ *
130
+ * @example
131
+ * ```ts
132
+ * for (const conformance of effectStoreConformance()) {
133
+ * test(conformance.name, () => conformance.run(() => myEffectStore()));
134
+ * }
135
+ * ```
136
+ */
137
+ export function effectStoreConformance() {
138
+ return CASES;
139
+ }
140
+ //# sourceMappingURL=effect-store-conformance.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"effect-store-conformance.js","sourceRoot":"","sources":["../src/effect-store-conformance.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAU5C,MAAM,KAAK,GAAG,0BAA0B,CAAC;AAEzC,SAAS,MAAM,CAAC,GAAW,EAAE,OAAO,GAAG,CAAC,EAAE,OAAO,GAA0B,EAAE;IAC3E,OAAO;QACL,GAAG;QACH,KAAK,EAAE,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,QAAQ,OAAO,EAAE,EAAE;QAClG,WAAW,EAAE,aAAa;QAC1B,SAAS,EAAE,eAAe;QAC1B,SAAS,EAAE,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;QACzB,OAAO;QACP,KAAK,EAAE,SAAS;QAChB,SAAS,EAAE,KAAK;QAChB,UAAU,EAAE,0BAA0B;QACtC,GAAG,OAAO;KACX,CAAC;AACJ,CAAC;AAED,SAAS,OAAO,CAAC,GAAW,EAAE,OAAO,GAAG,CAAC;IACvC,MAAM,OAAO,GAAG,YAAY,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,SAAS,EAAE,eAAe,EAAE,SAAS,EAAE,GAAG,EA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AQ,GAAG,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC;YACvE,MAAM,KAAK,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;YAC3B,QAAQ,CAAC,KAA4B,CAAC,MAAM,GAAG,cAAc,CAAC;YAC/D,MAAM,IAAI,GAAG,MAAM,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;YACnC,IAAI,IAAI,KAAK,SAAS;gBAAG,IAAI,CAAC,KAA4B,CAAC,MAAM,GAAG,cAAc,CAAC;YACnF,IAAI,CAAC,MAAM,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,EAAE,kCAAkC,CAAC,CAAC;QAChF,CAAC;KACF;CACF,CAAC;AAEF;;;;;;;;;GASG;AACH,MAAM,UAAU,sBAAsB;IACpC,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["/**\n * The `EffectStore` conformance cases: what every store must do for `guardedWrite()` to run a write at most once. The\n * memory store runs them in this package's tests, and each durable store, on Cloudflare, AWS or Vercel, runs the same\n * list. The cases throw plain `Error`s and import no test runner, so any runner, and workerd, can call them.\n */\nimport type { EffectRecord, EffectStore } from \"./effect-store.js\";\nimport { writeOutcome } from \"./outcome.js\";\n\n/** One conformance case: a name a test runner can show, and a check that rejects if the store breaks the rule. */\nexport interface EffectStoreCase {\n /** What the case checks, as a sentence. */\n readonly name: string;\n /** Runs the check against a fresh, empty store from `makeStore`. */\n run(makeStore: () => EffectStore | Promise<EffectStore>): Promise<void>;\n}\n\nconst START = \"2026-11-19T10:00:00.000Z\";\n\nfunction record(key: string, attempt = 1, changes: Partial<EffectRecord> = {}): EffectRecord {\n return {\n key,\n scope: { tenant: \"tenant-1\", session: \"session-1\", branch: \"main\", toolCallId: `call-${attempt}` },\n businessKey: \"refund:4417\",\n operation: \"refund_create\",\n inputHash: \"a\".repeat(64),\n attempt,\n state: \"started\",\n startedAt: START,\n leaseUntil: \"2026-11-19T10:05:00.000Z\",\n ...changes,\n };\n}\n\nfunction settled(key: string, attempt = 1): EffectRecord {\n const outcome = writeOutcome({ kind: \"applied\", operation: \"refund_create\", effectKey: key, next: \"Tell the user\" });\n return record(key, attempt, { state: \"settled\", outcome, settledAt: \"2026-11-19T10:01:00.000Z\" });\n}\n\nfunction check(condition: boolean, message: string): void {\n if (!condition) throw new Error(`EffectStore conformance: ${message}`);\n}\n\n// Compares records as JSON, so a store that serializes them passes, while a missing or changed field fails.\nfunction same(actual: unknown, expected: unknown, message: string): void {\n check(JSON.stringify(sorted(actual)) === JSON.stringify(sorted(expected)), message);\n}\n\nfunction sorted(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sorted);\n if (typeof value !== \"object\" || value === null) return value;\n return Object.fromEntries(\n Object.entries(value)\n .filter(([, item]) => item !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([key, item]) => [key, sorted(item)]),\n );\n}\n\nconst CASES: readonly EffectStoreCase[] = [\n {\n name: \"begin stores a new record, and get returns it with every field\",\n async run(makeStore) {\n const store = await makeStore();\n check((await store.begin(record(\"k1\"))) === \"started\", \"begin of a new key must return started\");\n same(await store.get(\"k1\"), record(\"k1\"), \"get must return the record begin stored\");\n check((await store.get(\"absent\")) === undefined, \"get of an absent key must return undefined\");\n },\n },\n {\n name: \"begin on a key that exists returns the existing record and replaces nothing\",\n async run(makeStore) {\n const store = await makeStore();\n await store.begin(record(\"k1\"));\n const claim = await store.begin(record(\"k1\", 1, { inputHash: \"b\".repeat(64) }));\n check(claim !== \"started\", \"a second begin must not start\");\n same(claim === \"started\" ? undefined : claim.existing, record(\"k1\"), \"begin must return the stored record\");\n same(await store.get(\"k1\"), record(\"k1\"), \"a second begin must not replace the record\");\n },\n },\n {\n name: \"of many concurrent begins on one key, exactly one starts\",\n async run(makeStore) {\n const store = await makeStore();\n const claims = await Promise.all(Array.from({ length: 8 }, () => store.begin(record(\"k1\"))));\n check(claims.filter((claim) => claim === \"started\").length === 1, \"exactly one begin must start\");\n },\n },\n {\n name: \"takeOver succeeds only from the attempt before it\",\n async run(makeStore) {\n const store = await makeStore();\n await store.begin(record(\"k1\"));\n check((await store.takeOver(record(\"k1\", 3))) !== \"started\", \"a takeover that skips an attempt must fail\");\n check((await store.takeOver(record(\"k1\", 2))) === \"started\", \"a takeover from the stored attempt must start\");\n const stale = await store.takeOver(record(\"k1\", 2));\n check(stale !== \"started\", \"a second takeover from the same attempt must fail\");\n same(stale === \"started\" ? undefined : stale.existing, record(\"k1\", 2), \"a failed takeover returns the record\");\n },\n },\n {\n name: \"of many concurrent takeovers from one attempt, exactly one starts\",\n async run(makeStore) {\n const store = await makeStore();\n await store.begin(record(\"k1\"));\n const claims = await Promise.all(Array.from({ length: 8 }, () => store.takeOver(record(\"k1\", 2))));\n check(claims.filter((claim) => claim === \"started\").length === 1, \"exactly one takeover must start\");\n },\n },\n {\n name: \"takeOver of a settled record starts a new attempt\",\n async run(makeStore) {\n const store = await makeStore();\n await store.begin(record(\"k1\"));\n await store.settle(settled(\"k1\"));\n check((await store.takeOver(record(\"k1\", 2))) === \"started\", \"a settled record must be taken over\");\n same(await store.get(\"k1\"), record(\"k1\", 2), \"the takeover must replace the settled record\");\n },\n },\n {\n name: \"settle stores the outcome only for the started attempt that holds the record\",\n async run(makeStore) {\n const store = await makeStore();\n await store.begin(record(\"k1\"));\n await store.takeOver(record(\"k1\", 2));\n check(!(await store.settle(settled(\"k1\", 1))), \"a settle from a superseded attempt must fail\");\n same(await store.get(\"k1\"), record(\"k1\", 2), \"a failed settle must change nothing\");\n check(await store.settle(settled(\"k1\", 2)), \"a settle from the current attempt must succeed\");\n same(await store.get(\"k1\"), settled(\"k1\", 2), \"get must return the settled record with its outcome\");\n check(!(await store.settle(settled(\"k1\", 2))), \"a second settle of a settled record must fail\");\n check(!(await store.settle(settled(\"absent\"))), \"a settle of an absent key must fail\");\n },\n },\n {\n name: \"a record changed after it was stored or read leaves the stored one as it was\",\n async run(makeStore) {\n const store = await makeStore();\n const original = { ...record(\"k1\"), scope: { ...record(\"k1\").scope } };\n await store.begin(original);\n (original.scope as { tenant: string }).tenant = \"someone-else\";\n const read = await store.get(\"k1\");\n if (read !== undefined) (read.scope as { tenant: string }).tenant = \"someone-else\";\n same(await store.get(\"k1\"), record(\"k1\"), \"the store must keep its own copy\");\n },\n },\n];\n\n/**\n * The cases every `EffectStore` must pass. Run each against a fresh store:\n *\n * @example\n * ```ts\n * for (const conformance of effectStoreConformance()) {\n * test(conformance.name, () => conformance.run(() => myEffectStore()));\n * }\n * ```\n */\nexport function effectStoreConformance(): readonly EffectStoreCase[] {\n return CASES;\n}\n"]}
@@ -0,0 +1,71 @@
1
+ /**
2
+ * `EffectStore`: the effects ledger. It keeps one record per effect key, written before the write runs and settled with
3
+ * its outcome after, so a crash leaves a `started` record behind and the resume knows a write may have happened. Every
4
+ * change is a compare-and-set on the record's attempt number, so two processes can never both run one write.
5
+ */
6
+ import type { EffectScope } from "./effect-key.js";
7
+ import type { WriteOutcome } from "./outcome.js";
8
+ /**
9
+ * One write's entry in the effects ledger. A `started` record belongs to a live attempt until `leaseUntil`; after
10
+ * that, the attempt counts as crashed. A `settled` record holds the write's outcome.
11
+ */
12
+ export interface EffectRecord {
13
+ /** The effect key, from `effectKey()`. */
14
+ readonly key: string;
15
+ /** The scope of the call that last started this write. */
16
+ readonly scope: EffectScope;
17
+ /** The business key the tool declared, if any. */
18
+ readonly businessKey?: string;
19
+ /** The tool or business operation, such as `refund_create`. */
20
+ readonly operation: string;
21
+ /** `canonicalInputHash()` of the write's input, the same hash an approval signs. */
22
+ readonly inputHash: string;
23
+ /** Counts the attempts that have held this record: 1 for the first, one more for each takeover. */
24
+ readonly attempt: number;
25
+ /** `started` while an attempt may be running, `settled` once its outcome is recorded. */
26
+ readonly state: "started" | "settled";
27
+ /** The write's outcome, set when the record is settled. */
28
+ readonly outcome?: WriteOutcome;
29
+ /** When the current attempt started, as an ISO 8601 timestamp. */
30
+ readonly startedAt: string;
31
+ /** Until when the current attempt counts as live, as an ISO 8601 timestamp. */
32
+ readonly leaseUntil: string;
33
+ /** When the record was settled, as an ISO 8601 timestamp. */
34
+ readonly settledAt?: string;
35
+ }
36
+ /** What `begin()` and `takeOver()` return: `"started"` if the caller now holds the record, or the record that won. */
37
+ export type EffectClaim = "started" | {
38
+ readonly existing: EffectRecord;
39
+ };
40
+ /**
41
+ * Stores effect records by key. Each method must be atomic: on Durable Object storage, within one object; in SQL, as
42
+ * one statement such as `INSERT ... ON CONFLICT DO NOTHING` or `UPDATE ... WHERE attempt = ?`; never as a read
43
+ * followed by a write. A store that isn't atomic lets two processes both run one write.
44
+ *
45
+ * Keep records at least as long as a business key can come back, and longer than any idempotency window of the API the
46
+ * tool calls. A record that is gone lets the same business key run again.
47
+ */
48
+ export interface EffectStore {
49
+ /** Stores `record` if no record has its key, and returns `"started"`; otherwise returns the existing record. */
50
+ begin(record: EffectRecord): Promise<EffectClaim>;
51
+ /**
52
+ * Replaces the stored record with `record` if the stored one's attempt is `record.attempt - 1`, or stores it if no
53
+ * record has its key, and returns `"started"`; otherwise returns the stored record. The caller uses it to take over a
54
+ * crashed attempt or to retry a settled one under the same key.
55
+ */
56
+ takeOver(record: EffectRecord): Promise<EffectClaim>;
57
+ /**
58
+ * Replaces the stored record with `record`, a settled record, if the stored one is `started` with the same attempt,
59
+ * and returns true; otherwise changes nothing and returns false.
60
+ */
61
+ settle(record: EffectRecord): Promise<boolean>;
62
+ /** Returns the record for `key`, or `undefined` if there is none. */
63
+ get(key: string): Promise<EffectRecord | undefined>;
64
+ }
65
+ /**
66
+ * An `EffectStore` in this process's memory, for tests and single-process hosts. Each method runs without awaiting,
67
+ * so it is atomic within the process. It stores and returns copies, so changing a record object outside the store
68
+ * never changes what the store holds. Records are kept until the process ends; a process that restarts forgets them,
69
+ * so use a durable store wherever a crash must not repeat a write.
70
+ */
71
+ export declare function memoryEffectStore(): EffectStore;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * An `EffectStore` in this process's memory, for tests and single-process hosts. Each method runs without awaiting,
3
+ * so it is atomic within the process. It stores and returns copies, so changing a record object outside the store
4
+ * never changes what the store holds. Records are kept until the process ends; a process that restarts forgets them,
5
+ * so use a durable store wherever a crash must not repeat a write.
6
+ */
7
+ export function memoryEffectStore() {
8
+ const records = new Map();
9
+ const copy = (record) => structuredClone(record);
10
+ return {
11
+ async begin(record) {
12
+ const existing = records.get(record.key);
13
+ if (existing !== undefined)
14
+ return { existing: copy(existing) };
15
+ records.set(record.key, copy(record));
16
+ return "started";
17
+ },
18
+ async takeOver(record) {
19
+ const existing = records.get(record.key);
20
+ if (existing !== undefined && existing.attempt !== record.attempt - 1)
21
+ return { existing: copy(existing) };
22
+ records.set(record.key, copy(record));
23
+ return "started";
24
+ },
25
+ async settle(record) {
26
+ const existing = records.get(record.key);
27
+ if (existing === undefined || existing.state !== "started" || existing.attempt !== record.attempt)
28
+ return false;
29
+ records.set(record.key, copy(record));
30
+ return true;
31
+ },
32
+ async get(key) {
33
+ const existing = records.get(key);
34
+ return existing === undefined ? undefined : copy(existing);
35
+ },
36
+ };
37
+ }
38
+ //# sourceMappingURL=effect-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"effect-store.js","sourceRoot":"","sources":["../src/effect-store.ts"],"names":[],"mappings":"AAkEA;;;;;GAKG;AACH,MAAM,UAAU,iBAAiB;IAC/B,MAAM,OAAO,GAAG,IAAI,GAAG,EAAwB,CAAC;IAChD,MAAM,IAAI,GAAG,CAAC,MAAoB,EAAgB,EAAE,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC;IAC7E,OAAO;QACL,KAAK,CAAC,KAAK,CAAC,MAAM;YAChB,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YACzC,IAAI,QAAQ,KAAK,SAAS;gBAAE,OAAO,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ectStore`: the effects ledger. It keeps one record per effect key, written before the write runs and settled with\n * its outcome after, so a crash leaves a `started` record behind and the resume knows a write may have happened. Every\n * change is a compare-and-set on the record's attempt number, so two processes can never both run one write.\n */\nimport type { EffectScope } from \"./effect-key.js\";\nimport type { WriteOutcome } from \"./outcome.js\";\n\n/**\n * One write's entry in the effects ledger. A `started` record belongs to a live attempt until `leaseUntil`; after\n * that, the attempt counts as crashed. A `settled` record holds the write's outcome.\n */\nexport interface EffectRecord {\n /** The effect key, from `effectKey()`. */\n readonly key: string;\n /** The scope of the call that last started this write. */\n readonly scope: EffectScope;\n /** The business key the tool declared, if any. */\n readonly businessKey?: string;\n /** The tool or business operation, such as `refund_create`. */\n readonly operation: string;\n /** `canonicalInputHash()` of the write's input, the same hash an approval signs. */\n readonly inputHash: string;\n /** Counts the attempts that have held this record: 1 for the first, one more for each takeover. */\n readonly attempt: number;\n /** `started` while an attempt may be running, `settled` once its outcome is recorded. */\n readonly state: \"started\" | \"settled\";\n /** The write's outcome, set when the record is settled. */\n readonly outcome?: WriteOutcome;\n /** When the current attempt started, as an ISO 8601 timestamp. */\n readonly startedAt: string;\n /** Until when the current attempt counts as live, as an ISO 8601 timestamp. */\n readonly leaseUntil: string;\n /** When the record was settled, as an ISO 8601 timestamp. */\n readonly settledAt?: string;\n}\n\n/** What `begin()` and `takeOver()` return: `\"started\"` if the caller now holds the record, or the record that won. */\nexport type EffectClaim = \"started\" | { readonly existing: EffectRecord };\n\n/**\n * Stores effect records by key. Each method must be atomic: on Durable Object storage, within one object; in SQL, as\n * one statement such as `INSERT ... ON CONFLICT DO NOTHING` or `UPDATE ... WHERE attempt = ?`; never as a read\n * followed by a write. A store that isn't atomic lets two processes both run one write.\n *\n * Keep records at least as long as a business key can come back, and longer than any idempotency window of the API the\n * tool calls. A record that is gone lets the same business key run again.\n */\nexport interface EffectStore {\n /** Stores `record` if no record has its key, and returns `\"started\"`; otherwise returns the existing record. */\n begin(record: EffectRecord): Promise<EffectClaim>;\n /**\n * Replaces the stored record with `record` if the stored one's attempt is `record.attempt - 1`, or stores it if no\n * record has its key, and returns `\"started\"`; otherwise returns the stored record. The caller uses it to take over a\n * crashed attempt or to retry a settled one under the same key.\n */\n takeOver(record: EffectRecord): Promise<EffectClaim>;\n /**\n * Replaces the stored record with `record`, a settled record, if the stored one is `started` with the same attempt,\n * and returns true; otherwise changes nothing and returns false.\n */\n settle(record: EffectRecord): Promise<boolean>;\n /** Returns the record for `key`, or `undefined` if there is none. */\n get(key: string): Promise<EffectRecord | undefined>;\n}\n\n/**\n * An `EffectStore` in this process's memory, for tests and single-process hosts. Each method runs without awaiting,\n * so it is atomic within the process. It stores and returns copies, so changing a record object outside the store\n * never changes what the store holds. Records are kept until the process ends; a process that restarts forgets them,\n * so use a durable store wherever a crash must not repeat a write.\n */\nexport function memoryEffectStore(): EffectStore {\n const records = new Map<string, EffectRecord>();\n const copy = (record: EffectRecord): EffectRecord => structuredClone(record);\n return {\n async begin(record) {\n const existing = records.get(record.key);\n if (existing !== undefined) return { existing: copy(existing) };\n records.set(record.key, copy(record));\n return \"started\";\n },\n async takeOver(record) {\n const existing = records.get(record.key);\n if (existing !== undefined && existing.attempt !== record.attempt - 1) return { existing: copy(existing) };\n records.set(record.key, copy(record));\n return \"started\";\n },\n async settle(record) {\n const existing = records.get(record.key);\n if (existing === undefined || existing.state !== \"started\" || existing.attempt !== record.attempt) return false;\n records.set(record.key, copy(record));\n return true;\n },\n async get(key) {\n const existing = records.get(key);\n return existing === undefined ? undefined : copy(existing);\n },\n };\n}\n"]}
@@ -0,0 +1,74 @@
1
+ /** The header that carries a provider's key: `x-api-key` for Anthropic, `authorization` for OpenAI. */
2
+ export type CredentialHeader = "authorization" | "x-api-key";
3
+ /** The one credential a guarded request must carry. */
4
+ export interface EgressCredential {
5
+ /** The header the provider sends its key in. */
6
+ readonly header: CredentialHeader;
7
+ /** The header's exact value, such as `Bearer <key>` for `authorization` or the bare key for `x-api-key`. */
8
+ readonly value: string;
9
+ }
10
+ /** The options of `egressGuard()`. */
11
+ export interface EgressGuardOptions {
12
+ /** The base URL every request must stay under: same origin, and at or below its path. */
13
+ readonly baseURL: string;
14
+ /** The credential every request must carry, and the only one it may carry beside `gatewayToken`. */
15
+ readonly credential: EgressCredential;
16
+ /**
17
+ * The token of a Cloudflare AI Gateway with authentication turned on, which the gateway reads from
18
+ * `cf-aig-authorization`. The guard adds the header to each request, and it is the one other credential a request
19
+ * may carry. The base URL must name one Cloudflare AI Gateway, `/v1/{account}/{gateway}`, so the token can reach no
20
+ * other host or account. The token must be a non-empty string of printable ASCII characters with no whitespace, and
21
+ * it is never read from the environment.
22
+ */
23
+ readonly gatewayToken?: string;
24
+ /** The `fetch` that sends an allowed request. Defaults to `globalThis.fetch`, looked up on each request. */
25
+ readonly fetch?: typeof fetch;
26
+ }
27
+ /**
28
+ * Headers that carry a credential for some model provider or gateway. A guarded request carries the configured one
29
+ * and none of the others, so a second key can't ride along beside the user's.
30
+ */
31
+ export declare const CREDENTIAL_HEADERS: readonly string[];
32
+ /** The header that carries the token of a Cloudflare AI Gateway with authentication turned on. */
33
+ export declare const CLOUDFLARE_GATEWAY_TOKEN_HEADER = "cf-aig-authorization";
34
+ /** The header that tells Cloudflare AI Gateway never to bill a request to Cloudflare's own credentials. */
35
+ export declare const CLOUDFLARE_NO_WHOLESALE_HEADER = "cf-aig-no-wholesale";
36
+ /**
37
+ * The `cf-aig-authorization` value for a gateway token, or `undefined` when none is configured. `who` names the caller
38
+ * in a refusal. A token needs a base URL that names one gateway, `/v1/{account}/{gateway}` on a Cloudflare AI Gateway
39
+ * host, because a base URL of the host alone would let the token go to any account's gateway beneath it.
40
+ */
41
+ export declare function checkGatewayToken(token: unknown, baseURL: unknown, who?: string): string | undefined;
42
+ /**
43
+ * Wraps `fetch` so a model request leaves only for `baseURL` and only with `credential`. The returned function
44
+ * rejects with a `SafetyError`, code `egress_refused`, before anything is sent, when a request:
45
+ *
46
+ * - goes to another origin, or to a path outside the base URL's path;
47
+ * - carries no `credential.header`, or one whose value differs from `credential.value`;
48
+ * - carries any other credential header in `CREDENTIAL_HEADERS`. `cf-aig-authorization` is one of them, unless you
49
+ * configure a `gatewayToken`: the guard then adds `cf-aig-authorization: Bearer <token>`, and a request that
50
+ * carries that header with another value is refused too. Only that one gateway credential may ride along, and only to
51
+ * a Cloudflare AI Gateway host.
52
+ *
53
+ * Every request to a Cloudflare AI Gateway host also gets `cf-aig-no-wholesale: true`, so the gateway refuses to bill
54
+ * Cloudflare's credentials even when its own setting is off. Redirects are never followed, because a redirect would
55
+ * resend the key's header to wherever the response points. Error messages name headers, never their values.
56
+ *
57
+ * Throws a `SafetyError`, code `invalid_byok_config`, when the base URL or the credential is unusable, or when a
58
+ * `gatewayToken` is unusable or the base URL does not name one Cloudflare AI Gateway.
59
+ */
60
+ export declare function egressGuard(options: EgressGuardOptions): typeof fetch;
61
+ /** The WebSocket constructor shape the AI SDK's providers call, with the handshake headers as a plain object. */
62
+ export type GuardableWebSocket = new (url: string | URL, protocols?: string | string[], options?: {
63
+ headers?: Record<string, string | undefined>;
64
+ }) => unknown;
65
+ /**
66
+ * The WebSocket counterpart of `egressGuard()`, for a provider that opens a socket instead of calling `fetch`, such
67
+ * as `@ai-sdk/openai`'s realtime transcription. The handshake must pass the same checks before the socket opens, and
68
+ * a refused one throws the same `SafetyError`. `WebSocket` defaults to `globalThis.WebSocket`, looked up on each
69
+ * connection. It also refuses any subprotocol but `realtime`, because OpenAI's browser mode carries a key there. Not
70
+ * exported from the package root.
71
+ */
72
+ export declare function egressGuardWebSocket(options: Omit<EgressGuardOptions, "fetch"> & {
73
+ readonly WebSocket?: GuardableWebSocket;
74
+ }): GuardableWebSocket;
package/dist/egress.js ADDED
@@ -0,0 +1,174 @@
1
+ /**
2
+ * `egressGuard()`: a `fetch` wrapper that lets a model request leave only for one base URL and only with one
3
+ * credential, so a provider that picked up another key or host from the environment fails instead of sending.
4
+ */
5
+ import { SafetyError } from "./errors.js";
6
+ import { isCloudflareAiGatewayHost, isUnderBase, parseModelBaseUrl } from "./model-url.js";
7
+ /**
8
+ * Headers that carry a credential for some model provider or gateway. A guarded request carries the configured one
9
+ * and none of the others, so a second key can't ride along beside the user's.
10
+ */
11
+ export const CREDENTIAL_HEADERS = Object.freeze([
12
+ "authorization",
13
+ "x-api-key",
14
+ "api-key",
15
+ "x-goog-api-key",
16
+ "proxy-authorization",
17
+ "cf-aig-authorization",
18
+ ]);
19
+ /** The header that carries the token of a Cloudflare AI Gateway with authentication turned on. */
20
+ export const CLOUDFLARE_GATEWAY_TOKEN_HEADER = "cf-aig-authorization";
21
+ /** The header that tells Cloudflare AI Gateway never to bill a request to Cloudflare's own credentials. */
22
+ export const CLOUDFLARE_NO_WHOLESALE_HEADER = "cf-aig-no-wholesale";
23
+ function refuse(message) {
24
+ return new SafetyError("egress_refused", `egressGuard refused a model request: ${message}`);
25
+ }
26
+ /**
27
+ * Checks the headers of a request: the configured credential is there, and no other credential header is, except
28
+ * `cf-aig-authorization` carrying exactly the configured gateway token.
29
+ */
30
+ function checkCredentials(headers, credential, gatewayValue) {
31
+ const sent = headers.get(credential.header);
32
+ if (sent === null)
33
+ throw refuse(`it carries no ${credential.header} header`);
34
+ if (sent !== credential.value)
35
+ throw refuse(`its ${credential.header} header differs from the configured key`);
36
+ for (const name of CREDENTIAL_HEADERS) {
37
+ if (name === credential.header || !headers.has(name))
38
+ continue;
39
+ if (name === CLOUDFLARE_GATEWAY_TOKEN_HEADER && gatewayValue !== undefined) {
40
+ if (headers.get(name) !== gatewayValue)
41
+ throw refuse(`its ${name} header differs from the configured gateway token`);
42
+ continue;
43
+ }
44
+ throw refuse(`it carries a second credential header, ${name}`);
45
+ }
46
+ }
47
+ // A token is printable ASCII: a header value can't hold a control character or a character above U+00FF, and
48
+ // whitespace in a token is a paste error.
49
+ const USABLE_TOKEN = /^[\x21-\x7e]+$/;
50
+ /**
51
+ * The `cf-aig-authorization` value for a gateway token, or `undefined` when none is configured. `who` names the caller
52
+ * in a refusal. A token needs a base URL that names one gateway, `/v1/{account}/{gateway}` on a Cloudflare AI Gateway
53
+ * host, because a base URL of the host alone would let the token go to any account's gateway beneath it.
54
+ */
55
+ export function checkGatewayToken(token, baseURL, who = "egressGuard") {
56
+ if (token === undefined)
57
+ return undefined;
58
+ if (typeof token !== "string" || !USABLE_TOKEN.test(token)) {
59
+ throw new SafetyError("invalid_byok_config", `${who} needs a gatewayToken of printable ASCII characters, with no whitespace`);
60
+ }
61
+ const parsed = parseModelBaseUrl(baseURL);
62
+ if (!parsed.ok || !isCloudflareAiGatewayHost(parsed.url.hostname)) {
63
+ throw new SafetyError("invalid_byok_config", `${who} takes a gatewayToken only with a Cloudflare AI Gateway base URL, so the token can reach no other host`);
64
+ }
65
+ const [, version, account, gateway] = parsed.url.path.split("/");
66
+ if (version !== "v1" || !account || !gateway) {
67
+ throw new SafetyError("invalid_byok_config", `${who} takes a gatewayToken only with a base URL that names one gateway, /v1/{account}/{gateway}, so the token can reach no other account's gateway`);
68
+ }
69
+ return `Bearer ${token}`;
70
+ }
71
+ function checkCredential(credential) {
72
+ if (typeof credential !== "object" || credential === null) {
73
+ throw new SafetyError("invalid_byok_config", "egressGuard needs a credential");
74
+ }
75
+ if (credential.header !== "authorization" && credential.header !== "x-api-key") {
76
+ throw new SafetyError("invalid_byok_config", "egressGuard needs a credential header of authorization or x-api-key");
77
+ }
78
+ if (typeof credential.value !== "string" || credential.value.trim() === "") {
79
+ throw new SafetyError("invalid_byok_config", "egressGuard needs a non-empty credential value");
80
+ }
81
+ }
82
+ /**
83
+ * Wraps `fetch` so a model request leaves only for `baseURL` and only with `credential`. The returned function
84
+ * rejects with a `SafetyError`, code `egress_refused`, before anything is sent, when a request:
85
+ *
86
+ * - goes to another origin, or to a path outside the base URL's path;
87
+ * - carries no `credential.header`, or one whose value differs from `credential.value`;
88
+ * - carries any other credential header in `CREDENTIAL_HEADERS`. `cf-aig-authorization` is one of them, unless you
89
+ * configure a `gatewayToken`: the guard then adds `cf-aig-authorization: Bearer <token>`, and a request that
90
+ * carries that header with another value is refused too. Only that one gateway credential may ride along, and only to
91
+ * a Cloudflare AI Gateway host.
92
+ *
93
+ * Every request to a Cloudflare AI Gateway host also gets `cf-aig-no-wholesale: true`, so the gateway refuses to bill
94
+ * Cloudflare's credentials even when its own setting is off. Redirects are never followed, because a redirect would
95
+ * resend the key's header to wherever the response points. Error messages name headers, never their values.
96
+ *
97
+ * Throws a `SafetyError`, code `invalid_byok_config`, when the base URL or the credential is unusable, or when a
98
+ * `gatewayToken` is unusable or the base URL does not name one Cloudflare AI Gateway.
99
+ */
100
+ export function egressGuard(options) {
101
+ const check = outgoingCheck(options.baseURL, options.credential, options.gatewayToken);
102
+ const send = options.fetch;
103
+ return async (input, init) => {
104
+ const request = new Request(input, init);
105
+ const headers = check(new URL(request.url), request.headers);
106
+ const guarded = new Request(request, { headers, redirect: "manual" });
107
+ return (send ?? globalThis.fetch)(guarded);
108
+ };
109
+ }
110
+ /**
111
+ * Builds the check every guarded request passes: the URL stays under the base URL, the headers carry the credential
112
+ * and no other, and a Cloudflare AI Gateway request gains `cf-aig-no-wholesale`. Returns the headers to send.
113
+ */
114
+ function outgoingCheck(baseURL, credentialOption, gatewayToken) {
115
+ const parsed = parseModelBaseUrl(baseURL);
116
+ if (!parsed.ok)
117
+ throw new SafetyError("invalid_byok_config", `egressGuard: ${parsed.message}`);
118
+ const base = parsed.url;
119
+ checkCredential(credentialOption);
120
+ const credential = { header: credentialOption.header, value: credentialOption.value };
121
+ const gatewayValue = checkGatewayToken(gatewayToken, baseURL);
122
+ return (url, sent) => {
123
+ if (!isUnderBase(url, base))
124
+ throw refuse(`${url.host}${url.pathname} is outside the configured base URL`);
125
+ const headers = new Headers(sent);
126
+ checkCredentials(headers, credential, gatewayValue);
127
+ if (isCloudflareAiGatewayHost(url.hostname))
128
+ headers.set(CLOUDFLARE_NO_WHOLESALE_HEADER, "true");
129
+ if (gatewayValue !== undefined)
130
+ headers.set(CLOUDFLARE_GATEWAY_TOKEN_HEADER, gatewayValue);
131
+ return headers;
132
+ };
133
+ }
134
+ // OpenAI's browser mode sends its key as the `openai-insecure-api-key.<key>` subprotocol, which no header check sees,
135
+ // so only the plain `realtime` subprotocol may pass.
136
+ function checkSubprotocols(protocols) {
137
+ for (const protocol of protocols === undefined ? [] : [protocols].flat()) {
138
+ if (protocol !== "realtime")
139
+ throw refuse("a WebSocket subprotocol other than realtime could carry a key");
140
+ }
141
+ }
142
+ /**
143
+ * The WebSocket counterpart of `egressGuard()`, for a provider that opens a socket instead of calling `fetch`, such
144
+ * as `@ai-sdk/openai`'s realtime transcription. The handshake must pass the same checks before the socket opens, and
145
+ * a refused one throws the same `SafetyError`. `WebSocket` defaults to `globalThis.WebSocket`, looked up on each
146
+ * connection. It also refuses any subprotocol but `realtime`, because OpenAI's browser mode carries a key there. Not
147
+ * exported from the package root.
148
+ */
149
+ export function egressGuardWebSocket(options) {
150
+ const check = outgoingCheck(options.baseURL, options.credential, options.gatewayToken);
151
+ const open = options.WebSocket;
152
+ return function GuardedWebSocket(url, protocols, init) {
153
+ const target = new URL(url);
154
+ // The base URL is http(s); compare the handshake on the same scheme, then open the socket on the original one.
155
+ const asHttp = new URL(target);
156
+ if (asHttp.protocol === "wss:")
157
+ asHttp.protocol = "https:";
158
+ else if (asHttp.protocol === "ws:")
159
+ asHttp.protocol = "http:";
160
+ else
161
+ throw refuse(`a WebSocket must use wss or ws, not ${target.protocol}`);
162
+ checkSubprotocols(protocols);
163
+ const sent = new Headers();
164
+ for (const [name, value] of Object.entries(init?.headers ?? {}))
165
+ if (value !== undefined)
166
+ sent.set(name, value);
167
+ const headers = check(asHttp, sent);
168
+ const Socket = open ?? globalThis.WebSocket;
169
+ if (Socket === undefined)
170
+ throw refuse("no WebSocket implementation is available");
171
+ return new Socket(target, protocols, { headers: Object.fromEntries(headers) });
172
+ };
173
+ }
174
+ //# sourceMappingURL=egress.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"egress.js","sourceRoot":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AC,SAAS,CAAC;QACpF,IAAI,MAAM,KAAK,SAAS;YAAE,MAAM,MAAM,CAAC,0CAA0C,CAAC,CAAC;QACnF,OAAO,IAAI,MAAM,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,OAAO,EAAE,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;IACjF,CAAkC,CAAC;AACrC,CAAC","sourcesContent":["/**\n * `egressGuard()`: a `fetch` wrapper that lets a model request leave only for one base URL and only with one\n * credential, so a provider that picked up another key or host from the environment fails instead of sending.\n */\nimport { SafetyError } from \"./errors.js\";\nimport { isCloudflareAiGatewayHost, isUnderBase, parseModelBaseUrl } from \"./model-url.js\";\n\n/** The header that carries a provider's key: `x-api-key` for Anthropic, `authorization` for OpenAI. */\nexport type CredentialHeader = \"authorization\" | \"x-api-key\";\n\n/** The one credential a guarded request must carry. */\nexport interface EgressCredential {\n /** The header the provider sends its key in. */\n readonly header: CredentialHeader;\n /** The header's exact value, such as `Bearer <key>` for `authorization` or the bare key for `x-api-key`. */\n readonly value: string;\n}\n\n/** The options of `egressGuard()`. */\nexport interface EgressGuardOptions {\n /** The base URL every request must stay under: same origin, and at or below its path. */\n readonly baseURL: string;\n /** The credential every request must carry, and the only one it may carry beside `gatewayToken`. */\n readonly credential: EgressCredential;\n /**\n * The token of a Cloudflare AI Gateway with authentication turned on, which the gateway reads from\n * `cf-aig-authorization`. The guard adds the header to each request, and it is the one other credential a request\n * may carry. The base URL must name one Cloudflare AI Gateway, `/v1/{account}/{gateway}`, so the token can reach no\n * other host or account. The token must be a non-empty string of printable ASCII characters with no whitespace, and\n * it is never read from the environment.\n */\n readonly gatewayToken?: string;\n /** The `fetch` that sends an allowed request. Defaults to `globalThis.fetch`, looked up on each request. */\n readonly fetch?: typeof fetch;\n}\n\n/**\n * Headers that carry a credential for some model provider or gateway. A guarded request carries the configured one\n * and none of the others, so a second key can't ride along beside the user's.\n */\nexport const CREDENTIAL_HEADERS: readonly string[] = Object.freeze([\n \"authorization\",\n \"x-api-key\",\n \"api-key\",\n \"x-goog-api-key\",\n \"proxy-authorization\",\n \"cf-aig-authorization\",\n]);\n\n/** The header that carries the token of a Cloudflare AI Gateway with authentication turned on. */\nexport const CLOUDFLARE_GATEWAY_TOKEN_HEADER = \"cf-aig-authorization\";\n\n/** The header that tells Cloudflare AI Gateway never to bill a request to Cloudflare's own credentials. */\nexport const CLOUDFLARE_NO_WHOLESALE_HEADER = \"cf-aig-no-wholesale\";\n\nfunction refuse(message: string): SafetyError {\n return new SafetyError(\"egress_refused\", `egressGuard refused a model request: ${message}`);\n}\n\n/**\n * Checks the headers of a request: the configured credential is there, and no other credential header is, except\n * `cf-aig-authorization` carrying exactly the configured gateway token.\n */\nfunction checkCredentials(headers: Headers, credential: EgressCredential, gatewayValue: string | undefined): void {\n const sent = headers.get(credential.header);\n if (sent === null) throw refuse(`it carries no ${credential.header} header`);\n if (sent !== credential.value) throw refuse(`its ${credential.header} header differs from the configured key`);\n for (const name of CREDENTIAL_HEADERS) {\n if (name === credential.header || !headers.has(name)) continue;\n if (name === CLOUDFLARE_GATEWAY_TOKEN_HEADER && gatewayValue !== undefined) {\n if (headers.get(name) !== gatewayValue)\n throw refuse(`its ${name} header differs from the configured gateway token`);\n continue;\n }\n throw refuse(`it carries a second credential header, ${name}`);\n }\n}\n\n// A token is printable ASCII: a header value can't hold a control character or a character above U+00FF, and\n// whitespace in a token is a paste error.\nconst USABLE_TOKEN = /^[\\x21-\\x7e]+$/;\n\n/**\n * The `cf-aig-authorization` value for a gateway token, or `undefined` when none is configured. `who` names the caller\n * in a refusal. A token needs a base URL that names one gateway, `/v1/{account}/{gateway}` on a Cloudflare AI Gateway\n * host, because a base URL of the host alone would let the token go to any account's gateway beneath it.\n */\nexport function checkGatewayToken(token: unknown, baseURL: unknown, who = \"egressGuard\"): string | undefined {\n if (token === undefined) return undefined;\n if (typeof token !== \"string\" || !USABLE_TOKEN.test(token)) {\n throw new SafetyError(\n \"invalid_byok_config\",\n `${who} needs a gatewayToken of printable ASCII characters, with no whitespace`,\n );\n }\n const parsed = parseModelBaseUrl(baseURL);\n if (!parsed.ok || !isCloudflareAiGatewayHost(parsed.url.hostname)) {\n throw new SafetyError(\n \"invalid_byok_config\",\n `${who} takes a gatewayToken only with a Cloudflare AI Gateway base URL, so the token can reach no other host`,\n );\n }\n const [, version, account, gateway] = parsed.url.path.split(\"/\");\n if (version !== \"v1\" || !account || !gateway) {\n throw new SafetyError(\n \"invalid_byok_config\",\n `${who} takes a gatewayToken only with a base URL that names one gateway, /v1/{account}/{gateway}, so the token can reach no other account's gateway`,\n );\n }\n return `Bearer ${token}`;\n}\n\nfunction checkCredential(credential: EgressCredential | undefined): void {\n if (typeof credential !== \"object\" || credential === null) {\n throw new SafetyError(\"invalid_byok_config\", \"egressGuard needs a credential\");\n }\n if (credential.header !== \"authorization\" && credential.header !== \"x-api-key\") {\n throw new SafetyError(\"invalid_byok_config\", \"egressGuard needs a credential header of authorization or x-api-key\");\n }\n if (typeof credential.value !== \"string\" || credential.value.trim() === \"\") {\n throw new SafetyError(\"invalid_byok_config\", \"egressGuard needs a non-empty credential value\");\n }\n}\n\n/**\n * Wraps `fetch` so a model request leaves only for `baseURL` and only with `credential`. The returned function\n * rejects with a `SafetyError`, code `egress_refused`, before anything is sent, when a request:\n *\n * - goes to another origin, or to a path outside the base URL's path;\n * - carries no `credential.header`, or one whose value differs from `credential.value`;\n * - carries any other credential header in `CREDENTIAL_HEADERS`. `cf-aig-authorization` is one of them, unless you\n * configure a `gatewayToken`: the guard then adds `cf-aig-authorization: Bearer <token>`, and a request that\n * carries that header with another value is refused too. Only that one gateway credential may ride along, and only to\n * a Cloudflare AI Gateway host.\n *\n * Every request to a Cloudflare AI Gateway host also gets `cf-aig-no-wholesale: true`, so the gateway refuses to bill\n * Cloudflare's credentials even when its own setting is off. Redirects are never followed, because a redirect would\n * resend the key's header to wherever the response points. Error messages name headers, never their values.\n *\n * Throws a `SafetyError`, code `invalid_byok_config`, when the base URL or the credential is unusable, or when a\n * `gatewayToken` is unusable or the base URL does not name one Cloudflare AI Gateway.\n */\nexport function egressGuard(options: EgressGuardOptions): typeof fetch {\n const check = outgoingCheck(options.baseURL, options.credential, options.gatewayToken);\n const send = options.fetch;\n return async (input, init) => {\n const request = new Request(input, init);\n const headers = check(new URL(request.url), request.headers);\n const guarded = new Request(request, { headers, redirect: \"manual\" });\n return (send ?? globalThis.fetch)(guarded);\n };\n}\n\n/**\n * Builds the check every guarded request passes: the URL stays under the base URL, the headers carry the credential\n * and no other, and a Cloudflare AI Gateway request gains `cf-aig-no-wholesale`. Returns the headers to send.\n */\nfunction outgoingCheck(\n baseURL: string,\n credentialOption: EgressCredential,\n gatewayToken: string | undefined,\n): (url: URL, sent: Headers) => Headers {\n const parsed = parseModelBaseUrl(baseURL);\n if (!parsed.ok) throw new SafetyError(\"invalid_byok_config\", `egressGuard: ${parsed.message}`);\n const base = parsed.url;\n checkCredential(credentialOption);\n const credential = { header: credentialOption.header, value: credentialOption.value };\n const gatewayValue = checkGatewayToken(gatewayToken, baseURL);\n return (url, sent) => {\n if (!isUnderBase(url, base)) throw refuse(`${url.host}${url.pathname} is outside the configured base URL`);\n const headers = new Headers(sent);\n checkCredentials(headers, credential, gatewayValue);\n if (isCloudflareAiGatewayHost(url.hostname)) headers.set(CLOUDFLARE_NO_WHOLESALE_HEADER, \"true\");\n if (gatewayValue !== undefined) headers.set(CLOUDFLARE_GATEWAY_TOKEN_HEADER, gatewayValue);\n return headers;\n };\n}\n\n/** The WebSocket constructor shape the AI SDK's providers call, with the handshake headers as a plain object. */\nexport type GuardableWebSocket = new (\n url: string | URL,\n protocols?: string | string[],\n options?: { headers?: Record<string, string | undefined> },\n) => unknown;\n\n// OpenAI's browser mode sends its key as the `openai-insecure-api-key.<key>` subprotocol, which no header check sees,\n// so only the plain `realtime` subprotocol may pass.\nfunction checkSubprotocols(protocols: string | string[] | undefined): void {\n for (const protocol of protocols === undefined ? [] : [protocols].flat()) {\n if (protocol !== \"realtime\") throw refuse(\"a WebSocket subprotocol other than realtime could carry a key\");\n }\n}\n\n/**\n * The WebSocket counterpart of `egressGuard()`, for a provider that opens a socket instead of calling `fetch`, such\n * as `@ai-sdk/openai`'s realtime transcription. The handshake must pass the same checks before the socket opens, and\n * a refused one throws the same `SafetyError`. `WebSocket` defaults to `globalThis.WebSocket`, looked up on each\n * connection. It also refuses any subprotocol but `realtime`, because OpenAI's browser mode carries a key there. Not\n * exported from the package root.\n */\nexport function egressGuardWebSocket(\n options: Omit<EgressGuardOptions, \"fetch\"> & { readonly WebSocket?: GuardableWebSocket },\n): GuardableWebSocket {\n const check = outgoingCheck(options.baseURL, options.credential, options.gatewayToken);\n const open = options.WebSocket;\n return function GuardedWebSocket(\n url: string | URL,\n protocols?: string | string[],\n init?: { headers?: Record<string, string | undefined> },\n ) {\n const target = new URL(url);\n // The base URL is http(s); compare the handshake on the same scheme, then open the socket on the original one.\n const asHttp = new URL(target);\n if (asHttp.protocol === \"wss:\") asHttp.protocol = \"https:\";\n else if (asHttp.protocol === \"ws:\") asHttp.protocol = \"http:\";\n else throw refuse(`a WebSocket must use wss or ws, not ${target.protocol}`);\n checkSubprotocols(protocols);\n const sent = new Headers();\n for (const [name, value] of Object.entries(init?.headers ?? {})) if (value !== undefined) sent.set(name, value);\n const headers = check(asHttp, sent);\n const Socket = open ?? (globalThis as { WebSocket?: GuardableWebSocket }).WebSocket;\n if (Socket === undefined) throw refuse(\"no WebSocket implementation is available\");\n return new Socket(target, protocols, { headers: Object.fromEntries(headers) });\n } as unknown as GuardableWebSocket;\n}\n"]}