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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/LICENSE +54 -0
  2. package/LICENSE-APACHE +202 -0
  3. package/LICENSE-MIT +21 -0
  4. package/README.md +514 -2
  5. package/dist/agents/index.d.ts +5 -0
  6. package/dist/agents/index.js +6 -0
  7. package/dist/agents/index.js.map +1 -0
  8. package/dist/ai/index.d.ts +10 -0
  9. package/dist/ai/index.js +11 -0
  10. package/dist/ai/index.js.map +1 -0
  11. package/dist/ai/interrupted-write.d.ts +28 -0
  12. package/dist/ai/interrupted-write.js +52 -0
  13. package/dist/ai/interrupted-write.js.map +1 -0
  14. package/dist/ai/settle-denied.d.ts +17 -0
  15. package/dist/ai/settle-denied.js +25 -0
  16. package/dist/ai/settle-denied.js.map +1 -0
  17. package/dist/ai/tool-approval.d.ts +68 -0
  18. package/dist/ai/tool-approval.js +219 -0
  19. package/dist/ai/tool-approval.js.map +1 -0
  20. package/dist/ai/tool-result.d.ts +23 -0
  21. package/dist/ai/tool-result.js +20 -0
  22. package/dist/ai/tool-result.js.map +1 -0
  23. package/dist/byok/default-provider.d.ts +12 -0
  24. package/dist/byok/default-provider.js +72 -0
  25. package/dist/byok/default-provider.js.map +1 -0
  26. package/dist/byok/explicit-provider.d.ts +39 -0
  27. package/dist/byok/explicit-provider.js +80 -0
  28. package/dist/byok/explicit-provider.js.map +1 -0
  29. package/dist/byok/index.d.ts +8 -0
  30. package/dist/byok/index.js +9 -0
  31. package/dist/byok/index.js.map +1 -0
  32. package/dist/bytes.d.ts +17 -0
  33. package/dist/bytes.js +59 -0
  34. package/dist/bytes.js.map +1 -0
  35. package/dist/cost/ai-types.d.ts +26 -0
  36. package/dist/cost/ai-types.js +2 -0
  37. package/dist/cost/ai-types.js.map +1 -0
  38. package/dist/cost/budget-exceeded.d.ts +39 -0
  39. package/dist/cost/budget-exceeded.js +49 -0
  40. package/dist/cost/budget-exceeded.js.map +1 -0
  41. package/dist/cost/cost-guard.d.ts +63 -0
  42. package/dist/cost/cost-guard.js +278 -0
  43. package/dist/cost/cost-guard.js.map +1 -0
  44. package/dist/cost/estimate.d.ts +76 -0
  45. package/dist/cost/estimate.js +320 -0
  46. package/dist/cost/estimate.js.map +1 -0
  47. package/dist/cost/guarded-provider.d.ts +24 -0
  48. package/dist/cost/guarded-provider.js +19 -0
  49. package/dist/cost/guarded-provider.js.map +1 -0
  50. package/dist/cost/index.d.ts +12 -0
  51. package/dist/cost/index.js +12 -0
  52. package/dist/cost/index.js.map +1 -0
  53. package/dist/cost/spend.d.ts +13 -0
  54. package/dist/cost/spend.js +15 -0
  55. package/dist/cost/spend.js.map +1 -0
  56. package/dist/effect-key.d.ts +31 -0
  57. package/dist/effect-key.js +61 -0
  58. package/dist/effect-key.js.map +1 -0
  59. package/dist/effect-store-conformance.d.ts +24 -0
  60. package/dist/effect-store-conformance.js +140 -0
  61. package/dist/effect-store-conformance.js.map +1 -0
  62. package/dist/effect-store.d.ts +71 -0
  63. package/dist/effect-store.js +38 -0
  64. package/dist/effect-store.js.map +1 -0
  65. package/dist/egress.d.ts +74 -0
  66. package/dist/egress.js +174 -0
  67. package/dist/egress.js.map +1 -0
  68. package/dist/errors.d.ts +32 -0
  69. package/dist/errors.js +26 -0
  70. package/dist/errors.js.map +1 -0
  71. package/dist/guarded-write.d.ts +99 -0
  72. package/dist/guarded-write.js +245 -0
  73. package/dist/guarded-write.js.map +1 -0
  74. package/dist/hash.d.ts +24 -0
  75. package/dist/hash.js +121 -0
  76. package/dist/hash.js.map +1 -0
  77. package/dist/index.d.ts +27 -0
  78. package/dist/index.js +28 -0
  79. package/dist/index.js.map +1 -0
  80. package/dist/key-store.d.ts +37 -0
  81. package/dist/key-store.js +53 -0
  82. package/dist/key-store.js.map +1 -0
  83. package/dist/model-routes.d.ts +54 -0
  84. package/dist/model-routes.js +117 -0
  85. package/dist/model-routes.js.map +1 -0
  86. package/dist/model-url.d.ts +39 -0
  87. package/dist/model-url.js +79 -0
  88. package/dist/model-url.js.map +1 -0
  89. package/dist/outcome.d.ts +88 -0
  90. package/dist/outcome.js +140 -0
  91. package/dist/outcome.js.map +1 -0
  92. package/dist/pending-store.d.ts +45 -0
  93. package/dist/pending-store.js +36 -0
  94. package/dist/pending-store.js.map +1 -0
  95. package/dist/pending.d.ts +144 -0
  96. package/dist/pending.js +161 -0
  97. package/dist/pending.js.map +1 -0
  98. package/dist/plan-approval.d.ts +196 -0
  99. package/dist/plan-approval.js +357 -0
  100. package/dist/plan-approval.js.map +1 -0
  101. package/dist/plan-card.d.ts +34 -0
  102. package/dist/plan-card.js +56 -0
  103. package/dist/plan-card.js.map +1 -0
  104. package/dist/plan-ledger-conformance.d.ts +24 -0
  105. package/dist/plan-ledger-conformance.js +99 -0
  106. package/dist/plan-ledger-conformance.js.map +1 -0
  107. package/dist/plan-ledger.d.ts +14 -0
  108. package/dist/plan-ledger.js +42 -0
  109. package/dist/plan-ledger.js.map +1 -0
  110. package/dist/plan-run.d.ts +133 -0
  111. package/dist/plan-run.js +438 -0
  112. package/dist/plan-run.js.map +1 -0
  113. package/dist/render.d.ts +40 -0
  114. package/dist/render.js +92 -0
  115. package/dist/render.js.map +1 -0
  116. package/dist/signer.d.ts +42 -0
  117. package/dist/signer.js +128 -0
  118. package/dist/signer.js.map +1 -0
  119. package/dist/stores/cloudflare.d.ts +34 -0
  120. package/dist/stores/cloudflare.js +84 -0
  121. package/dist/stores/cloudflare.js.map +1 -0
  122. package/dist/stores/dynamodb.d.ts +27 -0
  123. package/dist/stores/dynamodb.js +139 -0
  124. package/dist/stores/dynamodb.js.map +1 -0
  125. package/dist/stores/lost-claim.d.ts +8 -0
  126. package/dist/stores/lost-claim.js +11 -0
  127. package/dist/stores/lost-claim.js.map +1 -0
  128. package/dist/stores/postgres.d.ts +30 -0
  129. package/dist/stores/postgres.js +79 -0
  130. package/dist/stores/postgres.js.map +1 -0
  131. package/dist/test-signer.d.ts +13 -0
  132. package/dist/test-signer.js +18 -0
  133. package/dist/test-signer.js.map +1 -0
  134. package/dist/testing.d.ts +8 -0
  135. package/dist/testing.js +9 -0
  136. package/dist/testing.js.map +1 -0
  137. package/llms.txt +212 -0
  138. package/package.json +107 -3
@@ -0,0 +1 @@
1
+ {"version":3,"file":"default-provider.js","sourceRoot":"","sources":["../../src/byok/default-provider.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE3C,oGAAoG;AACpG,MAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,mDAAmD,CAAC,CAAC;AAE1F,uGAAuG;AACvG,MAAM,eAAe,GAAG;IACtB,eAAe;IACf,gBAAgB;IAChB,YAAY;IACZ,oBAAoB;IACpB,aAAa;IACb,gBAAgB;IAChB,YAAY;IACZ,wBAAwB;IACxB,eAAe;IACf,iBAAiB;IACjB,oBAAoB;CACZ,CAAC;AAIX,SAAS,OAAO,CAAC,IAAY,EAAE,OAAgB;IAC7C,MAAM,EAAE,GAAG,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,OAAO,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;IAC9D,OAAO,IAAI,WAAW,CACpB,kBAAkB,EAClB,oBAAoB,EAAE,uBAAuB,IAAI,kJAAkJ,CACpM,CAAC;AACJ,CAAC;AAED,SAAS,gBAAgB;IACvB,MAAM,QAAQ,GAAqC,EAAE,oBAAoB,EAAE,IAAI,EAAE,CAAC;IAClF,KAAK,MAAM,IAAI,IAAI,eAAe,EAAE,CAAC;QACnC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,OAAgB,EAAE,EAAE;YACpC,MAAM,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QAC/B,CAAC,CAAC;IACJ,CAAC;IACD,MAAM,CAAC,cAAc,CAAC,QAAQ,EAAE,iBAAiB,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IACpE,OAAO,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AACjC,CAAC;AAED,qHAAqH;AACrH,qEAAqE;AACrE,SAAS,kBAAkB,CAAC,KAAc;IACxC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,iBAAiB,CAAC,KAAK,IAAI,CAAC;AACvH,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,uBAAuB;IACrC,MAAM,MAAM,GAAG,UAAmC,CAAC;IACnD,MAAM,OAAO,GAAG,MAAM,CAAC,uBAAuB,CAAC;IAC/C,IAAI,kBAAkB,CAAC,OAAO,CAAC;QAAE,OAAO;IACxC,2GAA2G;IAC3G,IAAI,OAAO,KAAK,SAAS,IAAI,OAAO,KAAK,IAAI,EAAE,CAAC;QAC9C,MAAM,IAAI,WAAW,CACnB,kBAAkB,EAClB,yLAAyL,CAC1L,CAAC;IACJ,CAAC;IACD,+GAA+G;IAC/G,yCAAyC;IACzC,MAAM,CAAC,cAAc,CAAC,MAAM,EAAE,yBAAyB,EAAE;QACvD,KAAK,EAAE,gBAAgB,EAAE;QACzB,QAAQ,EAAE,KAAK;QACf,UAAU,EAAE,IAAI;QAChB,YAAY,EAAE,IAAI;KACnB,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * `assertNoDefaultProvider()`: makes a string model id fail. In `ai` 7.0.162, `generateText`, `streamText` and the\n * other calls resolve a string model id through `globalThis.AI_SDK_DEFAULT_PROVIDER ?? gateway`, and the gateway is\n * Vercel AI Gateway, which authenticates with `AI_GATEWAY_API_KEY` or a Vercel OIDC token from the environment. Setting\n * the global to a provider that refuses every model closes that path before any request is built.\n */\nimport { SafetyError } from \"../errors.js\";\n\n// A registered symbol, so a second copy of the package recognises the refusing provider as its own.\nconst REFUSING_PROVIDER = Symbol.for(\"buildanagent.agent-safety.RefusingDefaultProvider\");\n\n// Every model factory `ai` 7.0.162 looks up on the default provider, in resolve-model.ts and batch.ts.\nconst MODEL_FACTORIES = [\n \"languageModel\",\n \"embeddingModel\",\n \"imageModel\",\n \"transcriptionModel\",\n \"speechModel\",\n \"rerankingModel\",\n \"videoModel\",\n \"speechTranslationModel\",\n \"decisionModel\",\n \"evaluationModel\",\n \"experimental_batch\",\n] as const;\n\ntype DefaultProviderGlobal = { AI_SDK_DEFAULT_PROVIDER?: unknown };\n\nfunction refusal(kind: string, modelId: unknown): SafetyError {\n const id = typeof modelId === \"string\" ? ` \"${modelId}\"` : \"\";\n return new SafetyError(\n \"default_provider\",\n `A string model id${id} was resolved for a ${kind}; string ids route through a default provider, which may use a credential nobody configured. Pass a model built with explicitProvider() instead.`,\n );\n}\n\nfunction refusingProvider(): object {\n const provider: Record<string | symbol, unknown> = { specificationVersion: \"v4\" };\n for (const kind of MODEL_FACTORIES) {\n provider[kind] = (modelId: unknown) => {\n throw refusal(kind, modelId);\n };\n }\n Object.defineProperty(provider, REFUSING_PROVIDER, { value: true });\n return Object.freeze(provider);\n}\n\n// The marker is not a security boundary: code that can write to `globalThis` can already install any provider before\n// this runs. It only recognises our own provider on a repeated call.\nfunction isRefusingProvider(value: unknown): boolean {\n return typeof value === \"object\" && value !== null && (value as Record<symbol, unknown>)[REFUSING_PROVIDER] === true;\n}\n\n/**\n * Makes every string model id fail with a `SafetyError`, code `default_provider`, before any request. It sets the AI\n * SDK's `globalThis.AI_SDK_DEFAULT_PROVIDER` to a provider whose model factories all throw, so a string id can never\n * fall through to Vercel AI Gateway and an ambient gateway key or OIDC token. Call it once at startup, before the\n * agent's first model call. Calling it again does nothing. The global is left read-only, so later code that assigns\n * another default provider throws a `TypeError` in strict mode rather than reopening the path.\n *\n * Throws a `SafetyError`, code `default_provider`, when another default provider is already set, because string ids\n * would then reach a provider whose credentials this package can't see. Clear that setting and pass models built with\n * `explicitProvider()` instead.\n */\nexport function assertNoDefaultProvider(): void {\n const global = globalThis as DefaultProviderGlobal;\n const current = global.AI_SDK_DEFAULT_PROVIDER;\n if (isRefusingProvider(current)) return;\n // `ai` reads the global with `??`, so null means \"unset\" there too and falls through to Vercel AI Gateway.\n if (current !== undefined && current !== null) {\n throw new SafetyError(\n \"default_provider\",\n \"globalThis.AI_SDK_DEFAULT_PROVIDER is already set, so string model ids would reach a provider whose credential nobody checked. Remove it and pass models built with explicitProvider().\",\n );\n }\n // Read-only, so a later plain assignment throws in strict code instead of quietly reopening the path. It stays\n // configurable, so a test can delete it.\n Object.defineProperty(global, \"AI_SDK_DEFAULT_PROVIDER\", {\n value: refusingProvider(),\n writable: false,\n enumerable: true,\n configurable: true,\n });\n}\n"]}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * `explicitProvider()`: an `@ai-sdk/anthropic` or `@ai-sdk/openai` provider built only from the key and base URL the
3
+ * caller passes. In the pinned provider builds, a missing `apiKey` falls back to `ANTHROPIC_API_KEY` or
4
+ * `OPENAI_API_KEY` and a missing `baseURL` to `ANTHROPIC_BASE_URL` or `OPENAI_BASE_URL`, while an empty `apiKey` is
5
+ * sent as is. This builder refuses both gaps up front and puts `egressGuard()` under the provider's `fetch`, so a
6
+ * request that would carry another key or reach another host fails before it is sent.
7
+ */
8
+ import { type AnthropicProvider } from "@ai-sdk/anthropic";
9
+ import { type OpenAIProvider } from "@ai-sdk/openai";
10
+ /** The providers `explicitProvider()` builds. */
11
+ export type ExplicitProviderName = "anthropic" | "openai";
12
+ /** The options of `explicitProvider()`. Every field but `fetch` is required, and none falls back to the environment. */
13
+ export interface ExplicitProviderOptions<PROVIDER extends ExplicitProviderName = ExplicitProviderName> {
14
+ readonly provider: PROVIDER;
15
+ /** The user's own key for this provider. It must be a non-empty string with no surrounding whitespace. */
16
+ readonly apiKey: string;
17
+ /**
18
+ * Where the provider sends requests, such as `https://api.anthropic.com/v1`, `https://api.openai.com/v1` or a
19
+ * Cloudflare AI Gateway endpoint like `https://gateway.ai.cloudflare.com/v1/<account>/<gateway>/anthropic`. It must
20
+ * use https, and it must not be Vercel AI Gateway.
21
+ */
22
+ readonly baseURL: string;
23
+ /**
24
+ * The token of a Cloudflare AI Gateway with authentication turned on. The guard sends it as `cf-aig-authorization`
25
+ * with every request, beside the provider key, and allows no other second credential. `baseURL` must then name one
26
+ * Cloudflare AI Gateway, `/v1/{account}/{gateway}/{provider}`, so the token can reach no other host or account. Left
27
+ * out, a request that carries `cf-aig-authorization` is refused. The package has no stored-key mode: `apiKey` is
28
+ * always sent, which Cloudflare treats as the request's own key.
29
+ */
30
+ readonly gatewayToken?: string;
31
+ /** The `fetch` that sends a request once the guard allows it. Defaults to `globalThis.fetch`. */
32
+ readonly fetch?: typeof fetch;
33
+ }
34
+ /** Builds an Anthropic provider on the user's key and base URL alone. */
35
+ export declare function explicitProvider(options: ExplicitProviderOptions<"anthropic">): AnthropicProvider;
36
+ /** Builds an OpenAI provider on the user's key and base URL alone. */
37
+ export declare function explicitProvider(options: ExplicitProviderOptions<"openai">): OpenAIProvider;
38
+ /** Builds the provider `options.provider` names, when that is known only at runtime. */
39
+ export declare function explicitProvider(options: ExplicitProviderOptions): AnthropicProvider | OpenAIProvider;
@@ -0,0 +1,80 @@
1
+ /**
2
+ * `explicitProvider()`: an `@ai-sdk/anthropic` or `@ai-sdk/openai` provider built only from the key and base URL the
3
+ * caller passes. In the pinned provider builds, a missing `apiKey` falls back to `ANTHROPIC_API_KEY` or
4
+ * `OPENAI_API_KEY` and a missing `baseURL` to `ANTHROPIC_BASE_URL` or `OPENAI_BASE_URL`, while an empty `apiKey` is
5
+ * sent as is. This builder refuses both gaps up front and puts `egressGuard()` under the provider's `fetch`, so a
6
+ * request that would carry another key or reach another host fails before it is sent.
7
+ */
8
+ import { createAnthropic } from "@ai-sdk/anthropic";
9
+ import { createOpenAI } from "@ai-sdk/openai";
10
+ import { checkGatewayToken, egressGuard, egressGuardWebSocket } from "../egress.js";
11
+ import { SafetyError } from "../errors.js";
12
+ import { cloudflareProviderMismatch, isCloudflareAiGatewayHost, parseModelBaseUrl } from "../model-url.js";
13
+ // Header values can't hold control characters, and a key with surrounding whitespace is almost always a paste error
14
+ // that the provider would reject with a confusing 401.
15
+ const UNUSABLE_KEY = /^\s|\s$|[\p{Cc}]/u;
16
+ function checkApiKey(apiKey, provider) {
17
+ if (typeof apiKey !== "string" || apiKey === "") {
18
+ throw new SafetyError("invalid_byok_config", `explicitProvider(${provider}) needs the user's apiKey, and got none`);
19
+ }
20
+ if (UNUSABLE_KEY.test(apiKey)) {
21
+ throw new SafetyError("invalid_byok_config", `explicitProvider(${provider}) got an apiKey with surrounding whitespace or a control character`);
22
+ }
23
+ return apiKey;
24
+ }
25
+ function checkBaseUrl(baseURL, provider) {
26
+ const parsed = parseModelBaseUrl(baseURL);
27
+ if (!parsed.ok)
28
+ throw new SafetyError("invalid_byok_config", `explicitProvider(${provider}): ${parsed.message}`);
29
+ if (isCloudflareAiGatewayHost(parsed.url.hostname)) {
30
+ const mismatch = cloudflareProviderMismatch(parsed.url.path, provider);
31
+ if (mismatch !== undefined)
32
+ throw new SafetyError("invalid_byok_config", `explicitProvider(${provider}): ${mismatch}`);
33
+ }
34
+ return baseURL;
35
+ }
36
+ function credentialFor(provider, apiKey) {
37
+ // Anthropic's provider sends the key in x-api-key, which is also where Cloudflare AI Gateway reads an Anthropic key;
38
+ // OpenAI's sends it as a bearer token.
39
+ return provider === "anthropic"
40
+ ? { header: "x-api-key", value: apiKey }
41
+ : { header: "authorization", value: `Bearer ${apiKey}` };
42
+ }
43
+ /**
44
+ * Builds an `@ai-sdk/anthropic` or `@ai-sdk/openai` provider that uses only the `apiKey` and `baseURL` you pass. It
45
+ * passes both to the provider, so the provider never reads `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`,
46
+ * `ANTHROPIC_BASE_URL` or `OPENAI_BASE_URL`. It sends every request through `egressGuard()`, and every OpenAI
47
+ * WebSocket handshake through the same checks, which refuse a request to another host or with another credential. A
48
+ * request to Cloudflare AI Gateway also carries `cf-aig-no-wholesale: true`. A gateway with authentication turned on
49
+ * needs its token in a `cf-aig-authorization` header: pass it as `gatewayToken`, and the guard sends it and allows no
50
+ * other second credential and no other host.
51
+ *
52
+ * Throws a `SafetyError`, code `invalid_byok_config`, before any request when the key is missing, empty or padded with
53
+ * whitespace, when the base URL is missing or breaks the guard's rules, when it points at Vercel AI Gateway, or when a
54
+ * `gatewayToken` is unusable or the base URL does not name one Cloudflare AI Gateway.
55
+ */
56
+ export function explicitProvider(options) {
57
+ const { provider } = options;
58
+ if (provider !== "anthropic" && provider !== "openai") {
59
+ throw new SafetyError("invalid_byok_config", "explicitProvider builds only the anthropic and openai providers");
60
+ }
61
+ const apiKey = checkApiKey(options.apiKey, provider);
62
+ const baseURL = checkBaseUrl(options.baseURL, provider);
63
+ const credential = credentialFor(provider, apiKey);
64
+ // Checked here first, so a refusal names explicitProvider and not the guard beneath it.
65
+ checkGatewayToken(options.gatewayToken, baseURL, `explicitProvider(${provider})`);
66
+ const gateway = options.gatewayToken === undefined ? {} : { gatewayToken: options.gatewayToken };
67
+ const guard = egressGuard({
68
+ baseURL,
69
+ credential,
70
+ ...gateway,
71
+ ...(options.fetch === undefined ? {} : { fetch: options.fetch }),
72
+ });
73
+ if (provider === "anthropic")
74
+ return createAnthropic({ apiKey, baseURL, fetch: guard });
75
+ // OpenAI's realtime transcription and speech translation open a WebSocket instead of calling fetch, so the
76
+ // handshake goes through the same checks.
77
+ const webSocket = egressGuardWebSocket({ baseURL, credential, ...gateway });
78
+ return createOpenAI({ apiKey, baseURL, fetch: guard, webSocket });
79
+ }
80
+ //# sourceMappingURL=explicit-provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"explicit-provider.js","sourceRoot":"","sources":["../../src/byok/explicit-provider.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAA0B,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAC5E,OAAO,EAAE,YAAY,EAAoD,MAAM,gBAAgB,CAAC;AAChG,OAAO,EAAE,iBAAiB,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KACjE,CAAC,CAAC;IACH,IAAI,QAAQ,KAAK,WAAW;QAAE,OAAO,eAAe,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IACxF,2GAA2G;IAC3G,0CAA0C;IAC1C,MAAM,SAAS,GAAG,oBAAoB,CAAC,EAAE,OAAO,EAAE,UAAU,EAAE,GAAG,OAAO,EAAE,CAEzE,CAAC;IACF,OAAO,YAAY,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC;AACpE,CAAC","sourcesContent":["/**\n * `explicitProvider()`: an `@ai-sdk/anthropic` or `@ai-sdk/openai` provider built only from the key and base URL the\n * caller passes. In the pinned provider builds, a missing `apiKey` falls back to `ANTHROPIC_API_KEY` or\n * `OPENAI_API_KEY` and a missing `baseURL` to `ANTHROPIC_BASE_URL` or `OPENAI_BASE_URL`, while an empty `apiKey` is\n * sent as is. This builder refuses both gaps up front and puts `egressGuard()` under the provider's `fetch`, so a\n * request that would carry another key or reach another host fails before it is sent.\n */\nimport { type AnthropicProvider, createAnthropic } from \"@ai-sdk/anthropic\";\nimport { createOpenAI, type OpenAIProvider, type OpenAIProviderSettings } from \"@ai-sdk/openai\";\nimport { checkGatewayToken, type EgressCredential, egressGuard, egressGuardWebSocket } from \"../egress.js\";\nimport { SafetyError } from \"../errors.js\";\nimport { cloudflareProviderMismatch, isCloudflareAiGatewayHost, parseModelBaseUrl } from \"../model-url.js\";\n\n/** The providers `explicitProvider()` builds. */\nexport type ExplicitProviderName = \"anthropic\" | \"openai\";\n\n/** The options of `explicitProvider()`. Every field but `fetch` is required, and none falls back to the environment. */\nexport interface ExplicitProviderOptions<PROVIDER extends ExplicitProviderName = ExplicitProviderName> {\n readonly provider: PROVIDER;\n /** The user's own key for this provider. It must be a non-empty string with no surrounding whitespace. */\n readonly apiKey: string;\n /**\n * Where the provider sends requests, such as `https://api.anthropic.com/v1`, `https://api.openai.com/v1` or a\n * Cloudflare AI Gateway endpoint like `https://gateway.ai.cloudflare.com/v1/<account>/<gateway>/anthropic`. It must\n * use https, and it must not be Vercel AI Gateway.\n */\n readonly baseURL: string;\n /**\n * The token of a Cloudflare AI Gateway with authentication turned on. The guard sends it as `cf-aig-authorization`\n * with every request, beside the provider key, and allows no other second credential. `baseURL` must then name one\n * Cloudflare AI Gateway, `/v1/{account}/{gateway}/{provider}`, so the token can reach no other host or account. Left\n * out, a request that carries `cf-aig-authorization` is refused. The package has no stored-key mode: `apiKey` is\n * always sent, which Cloudflare treats as the request's own key.\n */\n readonly gatewayToken?: string;\n /** The `fetch` that sends a request once the guard allows it. Defaults to `globalThis.fetch`. */\n readonly fetch?: typeof fetch;\n}\n\n// Header values can't hold control characters, and a key with surrounding whitespace is almost always a paste error\n// that the provider would reject with a confusing 401.\nconst UNUSABLE_KEY = /^\\s|\\s$|[\\p{Cc}]/u;\n\nfunction checkApiKey(apiKey: unknown, provider: string): string {\n if (typeof apiKey !== \"string\" || apiKey === \"\") {\n throw new SafetyError(\"invalid_byok_config\", `explicitProvider(${provider}) needs the user's apiKey, and got none`);\n }\n if (UNUSABLE_KEY.test(apiKey)) {\n throw new SafetyError(\n \"invalid_byok_config\",\n `explicitProvider(${provider}) got an apiKey with surrounding whitespace or a control character`,\n );\n }\n return apiKey;\n}\n\nfunction checkBaseUrl(baseURL: unknown, provider: string): string {\n const parsed = parseModelBaseUrl(baseURL);\n if (!parsed.ok) throw new SafetyError(\"invalid_byok_config\", `explicitProvider(${provider}): ${parsed.message}`);\n if (isCloudflareAiGatewayHost(parsed.url.hostname)) {\n const mismatch = cloudflareProviderMismatch(parsed.url.path, provider);\n if (mismatch !== undefined)\n throw new SafetyError(\"invalid_byok_config\", `explicitProvider(${provider}): ${mismatch}`);\n }\n return baseURL as string;\n}\n\nfunction credentialFor(provider: ExplicitProviderName, apiKey: string): EgressCredential {\n // Anthropic's provider sends the key in x-api-key, which is also where Cloudflare AI Gateway reads an Anthropic key;\n // OpenAI's sends it as a bearer token.\n return provider === \"anthropic\"\n ? { header: \"x-api-key\", value: apiKey }\n : { header: \"authorization\", value: `Bearer ${apiKey}` };\n}\n\n/** Builds an Anthropic provider on the user's key and base URL alone. */\nexport function explicitProvider(options: ExplicitProviderOptions<\"anthropic\">): AnthropicProvider;\n/** Builds an OpenAI provider on the user's key and base URL alone. */\nexport function explicitProvider(options: ExplicitProviderOptions<\"openai\">): OpenAIProvider;\n/** Builds the provider `options.provider` names, when that is known only at runtime. */\nexport function explicitProvider(options: ExplicitProviderOptions): AnthropicProvider | OpenAIProvider;\n/**\n * Builds an `@ai-sdk/anthropic` or `@ai-sdk/openai` provider that uses only the `apiKey` and `baseURL` you pass. It\n * passes both to the provider, so the provider never reads `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`,\n * `ANTHROPIC_BASE_URL` or `OPENAI_BASE_URL`. It sends every request through `egressGuard()`, and every OpenAI\n * WebSocket handshake through the same checks, which refuse a request to another host or with another credential. A\n * request to Cloudflare AI Gateway also carries `cf-aig-no-wholesale: true`. A gateway with authentication turned on\n * needs its token in a `cf-aig-authorization` header: pass it as `gatewayToken`, and the guard sends it and allows no\n * other second credential and no other host.\n *\n * Throws a `SafetyError`, code `invalid_byok_config`, before any request when the key is missing, empty or padded with\n * whitespace, when the base URL is missing or breaks the guard's rules, when it points at Vercel AI Gateway, or when a\n * `gatewayToken` is unusable or the base URL does not name one Cloudflare AI Gateway.\n */\nexport function explicitProvider(options: ExplicitProviderOptions): AnthropicProvider | OpenAIProvider {\n const { provider } = options;\n if (provider !== \"anthropic\" && provider !== \"openai\") {\n throw new SafetyError(\"invalid_byok_config\", \"explicitProvider builds only the anthropic and openai providers\");\n }\n const apiKey = checkApiKey(options.apiKey, provider);\n const baseURL = checkBaseUrl(options.baseURL, provider);\n const credential = credentialFor(provider, apiKey);\n // Checked here first, so a refusal names explicitProvider and not the guard beneath it.\n checkGatewayToken(options.gatewayToken, baseURL, `explicitProvider(${provider})`);\n const gateway = options.gatewayToken === undefined ? {} : { gatewayToken: options.gatewayToken };\n const guard = egressGuard({\n baseURL,\n credential,\n ...gateway,\n ...(options.fetch === undefined ? {} : { fetch: options.fetch }),\n });\n if (provider === \"anthropic\") return createAnthropic({ apiKey, baseURL, fetch: guard });\n // OpenAI's realtime transcription and speech translation open a WebSocket instead of calling fetch, so the\n // handshake goes through the same checks.\n const webSocket = egressGuardWebSocket({ baseURL, credential, ...gateway }) as NonNullable<\n OpenAIProviderSettings[\"webSocket\"]\n >;\n return createOpenAI({ apiKey, baseURL, fetch: guard, webSocket });\n}\n"]}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * `@buildanagent/agent-safety/byok`: model calls on the user's own key with no silent fallback, for the Vercel AI SDK.
3
+ * `explicitProvider()` builds `@ai-sdk/anthropic` and `@ai-sdk/openai` providers from a key and base URL the caller
4
+ * passes, behind `egressGuard()`, and `assertNoDefaultProvider()` makes string model ids fail. This subpath imports
5
+ * both provider packages, which are optional peer dependencies.
6
+ */
7
+ export { assertNoDefaultProvider } from "./default-provider.js";
8
+ export { type ExplicitProviderName, type ExplicitProviderOptions, explicitProvider } from "./explicit-provider.js";
@@ -0,0 +1,9 @@
1
+ /**
2
+ * `@buildanagent/agent-safety/byok`: model calls on the user's own key with no silent fallback, for the Vercel AI SDK.
3
+ * `explicitProvider()` builds `@ai-sdk/anthropic` and `@ai-sdk/openai` providers from a key and base URL the caller
4
+ * passes, behind `egressGuard()`, and `assertNoDefaultProvider()` makes string model ids fail. This subpath imports
5
+ * both provider packages, which are optional peer dependencies.
6
+ */
7
+ export { assertNoDefaultProvider } from "./default-provider.js";
8
+ export { explicitProvider } from "./explicit-provider.js";
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/byok/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAChE,OAAO,EAA2D,gBAAgB,EAAE,MAAM,wBAAwB,CAAC","sourcesContent":["/**\n * `@buildanagent/agent-safety/byok`: model calls on the user's own key with no silent fallback, for the Vercel AI SDK.\n * `explicitProvider()` builds `@ai-sdk/anthropic` and `@ai-sdk/openai` providers from a key and base URL the caller\n * passes, behind `egressGuard()`, and `assertNoDefaultProvider()` makes string model ids fail. This subpath imports\n * both provider packages, which are optional peer dependencies.\n */\nexport { assertNoDefaultProvider } from \"./default-provider.js\";\nexport { type ExplicitProviderName, type ExplicitProviderOptions, explicitProvider } from \"./explicit-provider.js\";\n"]}
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Byte helpers for the signers: base64url without padding (RFC 4648 §5), and a comparison whose running time doesn't
3
+ * depend on where two byte strings first differ. Web-standard APIs only, so they run on every target.
4
+ */
5
+ /** Encodes bytes as base64url with no padding. */
6
+ export declare function toBase64Url(bytes: Uint8Array): string;
7
+ /**
8
+ * Decodes unpadded base64url. Returns `undefined` for any text that isn't the canonical encoding of some bytes: a
9
+ * character outside the alphabet, padding, a length no encoding has, or unused low bits that aren't zero. Refusing a
10
+ * non-canonical form keeps one signature from having two spellings.
11
+ */
12
+ export declare function fromBase64Url(text: string): Uint8Array | undefined;
13
+ /**
14
+ * True when two byte strings are equal. It compares every byte, whatever the first difference, so the time it takes
15
+ * reveals only the lengths, which are public for a MAC.
16
+ */
17
+ export declare function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean;
package/dist/bytes.js ADDED
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Byte helpers for the signers: base64url without padding (RFC 4648 §5), and a comparison whose running time doesn't
3
+ * depend on where two byte strings first differ. Web-standard APIs only, so they run on every target.
4
+ */
5
+ const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
6
+ const VALUE = new Map([...ALPHABET].map((char, index) => [char, index]));
7
+ /** Encodes bytes as base64url with no padding. */
8
+ export function toBase64Url(bytes) {
9
+ let out = "";
10
+ for (let index = 0; index < bytes.length; index += 3) {
11
+ // Missing bytes of the last group count as zero; the characters they would fill are left off below.
12
+ const chunk = ((bytes[index] ?? 0) << 16) | ((bytes[index + 1] ?? 0) << 8) | (bytes[index + 2] ?? 0);
13
+ const chars = Math.min(4, Math.ceil(((bytes.length - index) * 8) / 6));
14
+ for (let shift = 0; shift < chars; shift++)
15
+ out += ALPHABET[(chunk >> (18 - 6 * shift)) & 63];
16
+ }
17
+ return out;
18
+ }
19
+ /**
20
+ * Decodes unpadded base64url. Returns `undefined` for any text that isn't the canonical encoding of some bytes: a
21
+ * character outside the alphabet, padding, a length no encoding has, or unused low bits that aren't zero. Refusing a
22
+ * non-canonical form keeps one signature from having two spellings.
23
+ */
24
+ export function fromBase64Url(text) {
25
+ if (text.length % 4 === 1)
26
+ return undefined;
27
+ const bytes = new Uint8Array(Math.floor((text.length * 6) / 8));
28
+ let buffer = 0;
29
+ let bits = 0;
30
+ let out = 0;
31
+ for (const char of text) {
32
+ const value = VALUE.get(char);
33
+ if (value === undefined)
34
+ return undefined;
35
+ buffer = ((buffer << 6) | value) & 0xffffff;
36
+ bits += 6;
37
+ if (bits >= 8) {
38
+ bits -= 8;
39
+ bytes[out++] = (buffer >> bits) & 0xff;
40
+ }
41
+ }
42
+ // The bits left over after the last whole byte must be zero, or two texts would decode to the same bytes.
43
+ if ((buffer & ((1 << bits) - 1)) !== 0)
44
+ return undefined;
45
+ return bytes;
46
+ }
47
+ /**
48
+ * True when two byte strings are equal. It compares every byte, whatever the first difference, so the time it takes
49
+ * reveals only the lengths, which are public for a MAC.
50
+ */
51
+ export function constantTimeEqual(a, b) {
52
+ if (a.length !== b.length)
53
+ return false;
54
+ let difference = 0;
55
+ for (let index = 0; index < a.length; index++)
56
+ difference |= (a[index] ?? 0) ^ (b[index] ?? 0);
57
+ return difference === 0;
58
+ }
59
+ //# sourceMappingURL=bytes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bytes.js","sourceRoot":"","s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I,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;IAC/F,OAAO,UAAU,KAAK,CAAC,CAAC;AAC1B,CAAC","sourcesContent":["/**\n * Byte helpers for the signers: base64url without padding (RFC 4648 §5), and a comparison whose running time doesn't\n * depend on where two byte strings first differ. Web-standard APIs only, so they run on every target.\n */\n\nconst ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\nconst VALUE = new Map([...ALPHABET].map((char, index) => [char, index]));\n\n/** Encodes bytes as base64url with no padding. */\nexport function toBase64Url(bytes: Uint8Array): string {\n let out = \"\";\n for (let index = 0; index < bytes.length; index += 3) {\n // Missing bytes of the last group count as zero; the characters they would fill are left off below.\n const chunk = ((bytes[index] ?? 0) << 16) | ((bytes[index + 1] ?? 0) << 8) | (bytes[index + 2] ?? 0);\n const chars = Math.min(4, Math.ceil(((bytes.length - index) * 8) / 6));\n for (let shift = 0; shift < chars; shift++) out += ALPHABET[(chunk >> (18 - 6 * shift)) & 63];\n }\n return out;\n}\n\n/**\n * Decodes unpadded base64url. Returns `undefined` for any text that isn't the canonical encoding of some bytes: a\n * character outside the alphabet, padding, a length no encoding has, or unused low bits that aren't zero. Refusing a\n * non-canonical form keeps one signature from having two spellings.\n */\nexport function fromBase64Url(text: string): Uint8Array | undefined {\n if (text.length % 4 === 1) return undefined;\n const bytes = new Uint8Array(Math.floor((text.length * 6) / 8));\n let buffer = 0;\n let bits = 0;\n let out = 0;\n for (const char of text) {\n const value = VALUE.get(char);\n if (value === undefined) return undefined;\n buffer = ((buffer << 6) | value) & 0xffffff;\n bits += 6;\n if (bits >= 8) {\n bits -= 8;\n bytes[out++] = (buffer >> bits) & 0xff;\n }\n }\n // The bits left over after the last whole byte must be zero, or two texts would decode to the same bytes.\n if ((buffer & ((1 << bits) - 1)) !== 0) return undefined;\n return bytes;\n}\n\n/**\n * True when two byte strings are equal. It compares every byte, whatever the first difference, so the time it takes\n * reveals only the lengths, which are public for a MAC.\n */\nexport function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let difference = 0;\n for (let index = 0; index < a.length; index++) difference |= (a[index] ?? 0) ^ (b[index] ?? 0);\n return difference === 0;\n}\n"]}
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The AI SDK's provider-level types, read off the `LanguageModelMiddleware` that `ai` exports, so this subpath needs
3
+ * no peer dependency beyond `ai` itself. They are the `@ai-sdk/provider` 4.x types `ai` 7.0.162 builds on.
4
+ */
5
+ import type { LanguageModelMiddleware } from "ai";
6
+ type WrapGenerate = NonNullable<LanguageModelMiddleware["wrapGenerate"]>;
7
+ type WrapStream = NonNullable<LanguageModelMiddleware["wrapStream"]>;
8
+ /** The options one provider request carries: `LanguageModelV4CallOptions`. */
9
+ export type CallOptions = Parameters<WrapGenerate>[0]["params"];
10
+ /** The model a middleware wraps: `LanguageModelV4`. */
11
+ export type InnerModel = Parameters<WrapGenerate>[0]["model"];
12
+ /** What `doGenerate` resolves to: `LanguageModelV4GenerateResult`. */
13
+ export type GenerateResult = Awaited<ReturnType<WrapGenerate>>;
14
+ /** What `doStream` resolves to: `LanguageModelV4StreamResult`. */
15
+ export type StreamResult = Awaited<ReturnType<WrapStream>>;
16
+ /** One part of a model's stream: `LanguageModelV4StreamPart`. */
17
+ export type StreamPart = StreamResult["stream"] extends ReadableStream<infer Part> ? Part : never;
18
+ /** The prompt one request sends: `LanguageModelV4Prompt`. */
19
+ export type Prompt = CallOptions["prompt"];
20
+ /** One message of a prompt: `LanguageModelV4Message`. */
21
+ export type PromptMessage = Prompt[number];
22
+ /** A response's token counts: `LanguageModelV4Usage`. */
23
+ export type ModelUsage = GenerateResult["usage"];
24
+ /** A tool one request offers: `LanguageModelV4FunctionTool` or `LanguageModelV4ProviderTool`. */
25
+ export type CallTool = NonNullable<CallOptions["tools"]>[number];
26
+ export {};
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ai-types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ai-types.js","sourceRoot":"","sources":["../../src/cost/ai-types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * The AI SDK's provider-level types, read off the `LanguageModelMiddleware` that `ai` exports, so this subpath needs\n * no peer dependency beyond `ai` itself. They are the `@ai-sdk/provider` 4.x types `ai` 7.0.162 builds on.\n */\nimport type { LanguageModelMiddleware } from \"ai\";\n\ntype WrapGenerate = NonNullable<LanguageModelMiddleware[\"wrapGenerate\"]>;\ntype WrapStream = NonNullable<LanguageModelMiddleware[\"wrapStream\"]>;\n\n/** The options one provider request carries: `LanguageModelV4CallOptions`. */\nexport type CallOptions = Parameters<WrapGenerate>[0][\"params\"];\n/** The model a middleware wraps: `LanguageModelV4`. */\nexport type InnerModel = Parameters<WrapGenerate>[0][\"model\"];\n/** What `doGenerate` resolves to: `LanguageModelV4GenerateResult`. */\nexport type GenerateResult = Awaited<ReturnType<WrapGenerate>>;\n/** What `doStream` resolves to: `LanguageModelV4StreamResult`. */\nexport type StreamResult = Awaited<ReturnType<WrapStream>>;\n/** One part of a model's stream: `LanguageModelV4StreamPart`. */\nexport type StreamPart = StreamResult[\"stream\"] extends ReadableStream<infer Part> ? Part : never;\n/** The prompt one request sends: `LanguageModelV4Prompt`. */\nexport type Prompt = CallOptions[\"prompt\"];\n/** One message of a prompt: `LanguageModelV4Message`. */\nexport type PromptMessage = Prompt[number];\n/** A response's token counts: `LanguageModelV4Usage`. */\nexport type ModelUsage = GenerateResult[\"usage\"];\n/** A tool one request offers: `LanguageModelV4FunctionTool` or `LanguageModelV4ProviderTool`. */\nexport type CallTool = NonNullable<CallOptions[\"tools\"]>[number];\n"]}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * `BudgetExceeded`: the refusal of a model call before it is sent. The AI SDK's retry wrapper retries only a provider
3
+ * error marked retryable, so this error ends the call on its first attempt and reaches the caller as a stop.
4
+ */
5
+ import { SafetyError } from "../errors.js";
6
+ /** Why a call was refused: its projection would pass the cap, or its price is unknown, so the cap can't be checked. */
7
+ export type BudgetRefusalCode = "budget_exceeded" | "unknown_price";
8
+ /** What a refusal reports. */
9
+ export interface BudgetRefusalInit {
10
+ readonly code: BudgetRefusalCode;
11
+ readonly message: string;
12
+ readonly capUsd: number;
13
+ readonly spentUsd: number;
14
+ readonly projectedUsd: number | null;
15
+ readonly provider: string;
16
+ readonly modelId: string;
17
+ }
18
+ /**
19
+ * Thrown by a cost guard instead of sending a model call. `spentUsd` is what the run or session had spent, together
20
+ * with what calls still in flight may cost, or `NaN` when the `Spend` returned no number of dollars, and
21
+ * `projectedUsd` is the most the refused call could have cost, or `null` when its price is unknown.
22
+ */
23
+ export declare class BudgetExceeded extends SafetyError {
24
+ readonly name = "BudgetExceeded";
25
+ readonly code: BudgetRefusalCode;
26
+ readonly capUsd: number;
27
+ readonly spentUsd: number;
28
+ readonly projectedUsd: number | null;
29
+ /** The `provider` of the refused model, as the AI SDK names it, such as `anthropic.messages`. */
30
+ readonly provider: string;
31
+ readonly modelId: string;
32
+ constructor(init: BudgetRefusalInit);
33
+ }
34
+ /**
35
+ * The `BudgetExceeded` behind an error from `generateText`, `streamText` or an agent, or `undefined` when the error
36
+ * isn't a budget refusal. A refusal on a retry reaches the caller inside the AI SDK's `RetryError`, as the last of its
37
+ * `errors`, so this looks there and in `cause` as well as at the error itself.
38
+ */
39
+ export declare function budgetRefusal(error: unknown): BudgetExceeded | undefined;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * `BudgetExceeded`: the refusal of a model call before it is sent. The AI SDK's retry wrapper retries only a provider
3
+ * error marked retryable, so this error ends the call on its first attempt and reaches the caller as a stop.
4
+ */
5
+ import { SafetyError } from "../errors.js";
6
+ // A registered symbol, so `budgetRefusal()` still recognises the error when two copies of the package are bundled.
7
+ const BUDGET_EXCEEDED = Symbol.for("buildanagent.agent-safety.BudgetExceeded");
8
+ /**
9
+ * Thrown by a cost guard instead of sending a model call. `spentUsd` is what the run or session had spent, together
10
+ * with what calls still in flight may cost, or `NaN` when the `Spend` returned no number of dollars, and
11
+ * `projectedUsd` is the most the refused call could have cost, or `null` when its price is unknown.
12
+ */
13
+ export class BudgetExceeded extends SafetyError {
14
+ name = "BudgetExceeded";
15
+ capUsd;
16
+ spentUsd;
17
+ projectedUsd;
18
+ /** The `provider` of the refused model, as the AI SDK names it, such as `anthropic.messages`. */
19
+ provider;
20
+ modelId;
21
+ constructor(init) {
22
+ super(init.code, init.message);
23
+ this.capUsd = init.capUsd;
24
+ this.spentUsd = init.spentUsd;
25
+ this.projectedUsd = init.projectedUsd;
26
+ this.provider = init.provider;
27
+ this.modelId = init.modelId;
28
+ Object.defineProperty(this, BUDGET_EXCEEDED, { value: true });
29
+ }
30
+ }
31
+ function isBudgetExceeded(error) {
32
+ return typeof error === "object" && error !== null && error[BUDGET_EXCEEDED] === true;
33
+ }
34
+ /**
35
+ * The `BudgetExceeded` behind an error from `generateText`, `streamText` or an agent, or `undefined` when the error
36
+ * isn't a budget refusal. A refusal on a retry reaches the caller inside the AI SDK's `RetryError`, as the last of its
37
+ * `errors`, so this looks there and in `cause` as well as at the error itself.
38
+ */
39
+ export function budgetRefusal(error) {
40
+ if (isBudgetExceeded(error))
41
+ return error;
42
+ if (typeof error !== "object" || error === null)
43
+ return undefined;
44
+ const { errors, cause } = error;
45
+ if (Array.isArray(errors) && isBudgetExceeded(errors.at(-1)))
46
+ return errors.at(-1);
47
+ return isBudgetExceeded(cause) ? cause : undefined;
48
+ }
49
+ //# sourceMappingURL=budget-exceeded.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"budget-exceeded.js","sourceRoot":"","sources":["../../src/cost/budget-exceeded.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE3C,mHAAmH;AACnH,MAAM,eAAe,GAAG,MAAM,CAAC,GAAG,CAAC,0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C;QAAE,OAAO,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,CAAmB,CAAC;IACrG,OAAO,gBAAgB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AACrD,CAAC","sourcesContent":["/**\n * `BudgetExceeded`: the refusal of a model call before it is sent. The AI SDK's retry wrapper retries only a provider\n * error marked retryable, so this error ends the call on its first attempt and reaches the caller as a stop.\n */\nimport { SafetyError } from \"../errors.js\";\n\n// A registered symbol, so `budgetRefusal()` still recognises the error when two copies of the package are bundled.\nconst BUDGET_EXCEEDED = Symbol.for(\"buildanagent.agent-safety.BudgetExceeded\");\n\n/** Why a call was refused: its projection would pass the cap, or its price is unknown, so the cap can't be checked. */\nexport type BudgetRefusalCode = \"budget_exceeded\" | \"unknown_price\";\n\n/** What a refusal reports. */\nexport interface BudgetRefusalInit {\n readonly code: BudgetRefusalCode;\n readonly message: string;\n readonly capUsd: number;\n readonly spentUsd: number;\n readonly projectedUsd: number | null;\n readonly provider: string;\n readonly modelId: string;\n}\n\n/**\n * Thrown by a cost guard instead of sending a model call. `spentUsd` is what the run or session had spent, together\n * with what calls still in flight may cost, or `NaN` when the `Spend` returned no number of dollars, and\n * `projectedUsd` is the most the refused call could have cost, or `null` when its price is unknown.\n */\nexport class BudgetExceeded extends SafetyError {\n override readonly name = \"BudgetExceeded\";\n declare readonly code: BudgetRefusalCode;\n readonly capUsd: number;\n readonly spentUsd: number;\n readonly projectedUsd: number | null;\n /** The `provider` of the refused model, as the AI SDK names it, such as `anthropic.messages`. */\n readonly provider: string;\n readonly modelId: string;\n\n constructor(init: BudgetRefusalInit) {\n super(init.code, init.message);\n this.capUsd = init.capUsd;\n this.spentUsd = init.spentUsd;\n this.projectedUsd = init.projectedUsd;\n this.provider = init.provider;\n this.modelId = init.modelId;\n Object.defineProperty(this, BUDGET_EXCEEDED, { value: true });\n }\n}\n\nfunction isBudgetExceeded(error: unknown): error is BudgetExceeded {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[BUDGET_EXCEEDED] === true;\n}\n\n/**\n * The `BudgetExceeded` behind an error from `generateText`, `streamText` or an agent, or `undefined` when the error\n * isn't a budget refusal. A refusal on a retry reaches the caller inside the AI SDK's `RetryError`, as the last of its\n * `errors`, so this looks there and in `cause` as well as at the error itself.\n */\nexport function budgetRefusal(error: unknown): BudgetExceeded | undefined {\n if (isBudgetExceeded(error)) return error;\n if (typeof error !== \"object\" || error === null) return undefined;\n const { errors, cause } = error as { errors?: unknown; cause?: unknown };\n if (Array.isArray(errors) && isBudgetExceeded(errors.at(-1))) return errors.at(-1) as BudgetExceeded;\n return isBudgetExceeded(cause) ? cause : undefined;\n}\n"]}
@@ -0,0 +1,63 @@
1
+ /**
2
+ * `costGuard()`: an AI SDK language-model middleware that refuses a call before it is sent when the spend so far plus
3
+ * the call's projected cost would pass a USD cap, the rule our SDK's loop applies too. In `ai` 7.0.162 each
4
+ * step and each retry calls the step model's `doGenerate` or `doStream`, so a wrapped model's middleware sees every
5
+ * provider request. The projection is the gateway's `projectCost()` over the gateway's `estimateInputTokens()`, the
6
+ * formula the SDK's loop uses, so both caps agree on what a call can cost.
7
+ */
8
+ import { type PriceCatalog } from "@buildanagent/gateway";
9
+ import type { LanguageModelMiddleware } from "ai";
10
+ import { type FileSizer } from "./estimate.js";
11
+ import type { Spend } from "./spend.js";
12
+ /** One call the guard let through, reported once its cost is known. */
13
+ export interface GuardedCall {
14
+ /** The model's `provider`, as the AI SDK names it, such as `anthropic.messages`. */
15
+ readonly provider: string;
16
+ readonly modelId: string;
17
+ /** The most the call could cost, which the guard checked against the cap before sending it. */
18
+ readonly projectedUsd: number;
19
+ /**
20
+ * What the call cost, priced from the usage its response reported, or `null` when the response reported none or the
21
+ * call was interrupted before it did. The guard then adds `projectedUsd` to the spend instead. After a response
22
+ * without usage it also refuses every later call with `unknown_price`; after an interrupted call it carries on.
23
+ */
24
+ readonly costUsd: number | null;
25
+ }
26
+ /** Options for `costGuard()`. */
27
+ export interface CostGuardOptions {
28
+ /** The most the run or session may spend, in USD: a finite number, 0 or more. */
29
+ readonly capUsd: number;
30
+ /** Where the spend is kept. A fresh `memorySpend()` caps one run; a `Spend` the whole session shares caps the session. */
31
+ readonly spend: Spend;
32
+ /** The price catalog to read rates from. Defaults to the gateway's `defaultCatalog`. */
33
+ readonly catalog?: PriceCatalog;
34
+ /**
35
+ * The output limit the guard sets on a call that sets none, and prices that call at. Left out, such a call is
36
+ * priced at the catalog's output limit for the model and sent unchanged.
37
+ */
38
+ readonly maxOutputTokens?: number;
39
+ /**
40
+ * The size of a file a request points at by URL or by provider reference, which holds none of its bytes: `{ bytes }`
41
+ * or `{ pages }`, or `undefined` when you don't know it. Bytes count as the base64 characters of the file, and each
42
+ * page as one image; the text a provider reads from a page isn't counted, so give bytes when you have them. A usable
43
+ * size is a whole number, up to 2 ** 32 bytes or 100,000 pages. The guard remembers each size it was given, so a
44
+ * tool loop asks once for each file.
45
+ *
46
+ * A file that is not an image and has no usable size, one whose `fileSize` throws included, is refused with
47
+ * `unknown_price`, because the guard can't tell what it costs. An image needs no size, because it counts at the
48
+ * largest per-image size a provider documents.
49
+ */
50
+ readonly fileSize?: FileSizer;
51
+ /** Called after each call the guard let through, once its cost is known. */
52
+ readonly onCallCost?: (call: GuardedCall) => void;
53
+ }
54
+ /**
55
+ * A language-model middleware that caps what calls through it may spend. Before each call it estimates the input
56
+ * tokens from the request, prices them and the call's output limit with the gateway's `projectCost()`, and throws
57
+ * `BudgetExceeded` without calling the provider if the spend so far plus that projection would pass `capUsd`. A model
58
+ * the catalog has no price for is refused before its first call, code `unknown_price`. After each call it adds the
59
+ * cost of the usage the response reported, read from a stream's `finish` part. A streamed call holds its projection
60
+ * against the cap until its stream ends or is cancelled, so read the stream to its end or cancel it. Wrap a whole
61
+ * provider with `guardedProvider()`, so a model `prepareStep` picks from it is capped too.
62
+ */
63
+ export declare function costGuard(options: CostGuardOptions): LanguageModelMiddleware;