@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.
- package/LICENSE +54 -0
- package/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +21 -0
- package/README.md +514 -2
- package/dist/agents/index.d.ts +5 -0
- package/dist/agents/index.js +6 -0
- package/dist/agents/index.js.map +1 -0
- package/dist/ai/index.d.ts +10 -0
- package/dist/ai/index.js +11 -0
- package/dist/ai/index.js.map +1 -0
- package/dist/ai/interrupted-write.d.ts +28 -0
- package/dist/ai/interrupted-write.js +52 -0
- package/dist/ai/interrupted-write.js.map +1 -0
- package/dist/ai/settle-denied.d.ts +17 -0
- package/dist/ai/settle-denied.js +25 -0
- package/dist/ai/settle-denied.js.map +1 -0
- package/dist/ai/tool-approval.d.ts +68 -0
- package/dist/ai/tool-approval.js +219 -0
- package/dist/ai/tool-approval.js.map +1 -0
- package/dist/ai/tool-result.d.ts +23 -0
- package/dist/ai/tool-result.js +20 -0
- package/dist/ai/tool-result.js.map +1 -0
- package/dist/byok/default-provider.d.ts +12 -0
- package/dist/byok/default-provider.js +72 -0
- package/dist/byok/default-provider.js.map +1 -0
- package/dist/byok/explicit-provider.d.ts +39 -0
- package/dist/byok/explicit-provider.js +80 -0
- package/dist/byok/explicit-provider.js.map +1 -0
- package/dist/byok/index.d.ts +8 -0
- package/dist/byok/index.js +9 -0
- package/dist/byok/index.js.map +1 -0
- package/dist/bytes.d.ts +17 -0
- package/dist/bytes.js +59 -0
- package/dist/bytes.js.map +1 -0
- package/dist/cost/ai-types.d.ts +26 -0
- package/dist/cost/ai-types.js +2 -0
- package/dist/cost/ai-types.js.map +1 -0
- package/dist/cost/budget-exceeded.d.ts +39 -0
- package/dist/cost/budget-exceeded.js +49 -0
- package/dist/cost/budget-exceeded.js.map +1 -0
- package/dist/cost/cost-guard.d.ts +63 -0
- package/dist/cost/cost-guard.js +278 -0
- package/dist/cost/cost-guard.js.map +1 -0
- package/dist/cost/estimate.d.ts +76 -0
- package/dist/cost/estimate.js +320 -0
- package/dist/cost/estimate.js.map +1 -0
- package/dist/cost/guarded-provider.d.ts +24 -0
- package/dist/cost/guarded-provider.js +19 -0
- package/dist/cost/guarded-provider.js.map +1 -0
- package/dist/cost/index.d.ts +12 -0
- package/dist/cost/index.js +12 -0
- package/dist/cost/index.js.map +1 -0
- package/dist/cost/spend.d.ts +13 -0
- package/dist/cost/spend.js +15 -0
- package/dist/cost/spend.js.map +1 -0
- package/dist/effect-key.d.ts +31 -0
- package/dist/effect-key.js +61 -0
- package/dist/effect-key.js.map +1 -0
- package/dist/effect-store-conformance.d.ts +24 -0
- package/dist/effect-store-conformance.js +140 -0
- package/dist/effect-store-conformance.js.map +1 -0
- package/dist/effect-store.d.ts +71 -0
- package/dist/effect-store.js +38 -0
- package/dist/effect-store.js.map +1 -0
- package/dist/egress.d.ts +74 -0
- package/dist/egress.js +174 -0
- package/dist/egress.js.map +1 -0
- package/dist/errors.d.ts +32 -0
- package/dist/errors.js +26 -0
- package/dist/errors.js.map +1 -0
- package/dist/guarded-write.d.ts +99 -0
- package/dist/guarded-write.js +245 -0
- package/dist/guarded-write.js.map +1 -0
- package/dist/hash.d.ts +24 -0
- package/dist/hash.js +121 -0
- package/dist/hash.js.map +1 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.js +28 -0
- package/dist/index.js.map +1 -0
- package/dist/key-store.d.ts +37 -0
- package/dist/key-store.js +53 -0
- package/dist/key-store.js.map +1 -0
- package/dist/model-routes.d.ts +54 -0
- package/dist/model-routes.js +117 -0
- package/dist/model-routes.js.map +1 -0
- package/dist/model-url.d.ts +39 -0
- package/dist/model-url.js +79 -0
- package/dist/model-url.js.map +1 -0
- package/dist/outcome.d.ts +88 -0
- package/dist/outcome.js +140 -0
- package/dist/outcome.js.map +1 -0
- package/dist/pending-store.d.ts +45 -0
- package/dist/pending-store.js +36 -0
- package/dist/pending-store.js.map +1 -0
- package/dist/pending.d.ts +144 -0
- package/dist/pending.js +161 -0
- package/dist/pending.js.map +1 -0
- package/dist/plan-approval.d.ts +196 -0
- package/dist/plan-approval.js +357 -0
- package/dist/plan-approval.js.map +1 -0
- package/dist/plan-card.d.ts +34 -0
- package/dist/plan-card.js +56 -0
- package/dist/plan-card.js.map +1 -0
- package/dist/plan-ledger-conformance.d.ts +24 -0
- package/dist/plan-ledger-conformance.js +99 -0
- package/dist/plan-ledger-conformance.js.map +1 -0
- package/dist/plan-ledger.d.ts +14 -0
- package/dist/plan-ledger.js +42 -0
- package/dist/plan-ledger.js.map +1 -0
- package/dist/plan-run.d.ts +133 -0
- package/dist/plan-run.js +438 -0
- package/dist/plan-run.js.map +1 -0
- package/dist/render.d.ts +40 -0
- package/dist/render.js +92 -0
- package/dist/render.js.map +1 -0
- package/dist/signer.d.ts +42 -0
- package/dist/signer.js +128 -0
- package/dist/signer.js.map +1 -0
- package/dist/stores/cloudflare.d.ts +34 -0
- package/dist/stores/cloudflare.js +84 -0
- package/dist/stores/cloudflare.js.map +1 -0
- package/dist/stores/dynamodb.d.ts +27 -0
- package/dist/stores/dynamodb.js +139 -0
- package/dist/stores/dynamodb.js.map +1 -0
- package/dist/stores/lost-claim.d.ts +8 -0
- package/dist/stores/lost-claim.js +11 -0
- package/dist/stores/lost-claim.js.map +1 -0
- package/dist/stores/postgres.d.ts +30 -0
- package/dist/stores/postgres.js +79 -0
- package/dist/stores/postgres.js.map +1 -0
- package/dist/test-signer.d.ts +13 -0
- package/dist/test-signer.js +18 -0
- package/dist/test-signer.js.map +1 -0
- package/dist/testing.d.ts +8 -0
- package/dist/testing.js +9 -0
- package/dist/testing.js.map +1 -0
- package/llms.txt +212 -0
- package/package.json +107 -3
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@buildanagent/agent-safety`: the safety core. It holds typed write outcomes that the harness can act on and the
|
|
3
|
+
* model can read; the canonical input hash that approvals sign and effect records store; the signers and signed pending
|
|
4
|
+
* requests that make an approval fail closed; the signed plan approval, which lets a person approve a whole plan once
|
|
5
|
+
* and expires when the state it was computed from changes; `guardedWrite()` and the effect records that keep a crash or
|
|
6
|
+
* a regenerated turn from repeating a write; and the egress guard and route check that keep every model call on the
|
|
7
|
+
* user's own key. This entry imports no third-party SDK; the adapters for `ai` and Cloudflare `agents` live in the
|
|
8
|
+
* `./ai`, `./byok` and `./agents` subpaths.
|
|
9
|
+
*/
|
|
10
|
+
export { type EffectScope, effectKey } from "./effect-key.js";
|
|
11
|
+
export { type EffectClaim, type EffectRecord, type EffectStore, memoryEffectStore } from "./effect-store.js";
|
|
12
|
+
export { CLOUDFLARE_GATEWAY_TOKEN_HEADER, CLOUDFLARE_NO_WHOLESALE_HEADER, CREDENTIAL_HEADERS, type CredentialHeader, type EgressCredential, type EgressGuardOptions, egressGuard, } from "./egress.js";
|
|
13
|
+
export { isSafetyError, SafetyError, type SafetyErrorCode } from "./errors.js";
|
|
14
|
+
export { type GuardedWriteOptions, guardedWrite, type WriteDedupe } from "./guarded-write.js";
|
|
15
|
+
export { canonicalInputHash } from "./hash.js";
|
|
16
|
+
export { type KeyRing, type KeyStore, parseKeyRing, signerFromKeyStore } from "./key-store.js";
|
|
17
|
+
export { type CloudflareAiGatewaySettings, checkModelRoutes, MODEL_ROUTE_SETTINGS_AS_OF, type ModelRoute, type ModelRouteProblem, type ModelRouteProblemCode, type ModelRouteProvider, type ModelRoutesConfig, type ModelRoutesReport, } from "./model-routes.js";
|
|
18
|
+
export { CLOUDFLARE_AI_GATEWAY_HOST } from "./model-url.js";
|
|
19
|
+
export { ALLOWED_RETRIES, type AllowedRetry, DEFAULT_RETRY, OUTCOME_KINDS, type OutcomeFields, type OutcomeKind, type Retry, type WriteOutcome, type WriteOutcomeInit, type WriteOutcomeOf, writeOutcome, } from "./outcome.js";
|
|
20
|
+
export { type PendingCall, type PendingFields, pendingPayload, type Recheck, type RejectionCause, type Resolution, type ResolutionCheck, type SignedPendingRequest, type SignPendingOptions, signPending, type VerifyResolutionOptions, verifyResolution, } from "./pending.js";
|
|
21
|
+
export { type MemoryPendingStoreOptions, memoryPendingStore, type PendingStore } from "./pending-store.js";
|
|
22
|
+
export { lintPlan, type PlanApproval, type PlanFields, type PlanLedger, type PlanLint, type PlanStep, type PlanStepCall, type PlanStepCheck, type PlanStepInit, type SignPlanOptions, type StateRead, type StateValue, type StepClass, signPlan, stateHash, type VerifyPlanStepOptions, verifyPlanBeforeStep, } from "./plan-approval.js";
|
|
23
|
+
export { type PlanCard, type PlanCardStep, planCard } from "./plan-card.js";
|
|
24
|
+
export { memoryPlanLedger } from "./plan-ledger.js";
|
|
25
|
+
export { type PlanFailureReason, type PlanOutcome, type PlanScope, type PlanStepImpl, planWriteOutcome, type RunPlanOptions, renderPlanOutcome, runPlan, } from "./plan-run.js";
|
|
26
|
+
export { type OutcomePayload, type RenderedOutcome, renderOutcome } from "./render.js";
|
|
27
|
+
export { type ApprovalSigner, ephemeralSigner, type HmacSignerOptions, hmacSigner, MIN_KEY_BYTES, } from "./signer.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@buildanagent/agent-safety`: the safety core. It holds typed write outcomes that the harness can act on and the
|
|
3
|
+
* model can read; the canonical input hash that approvals sign and effect records store; the signers and signed pending
|
|
4
|
+
* requests that make an approval fail closed; the signed plan approval, which lets a person approve a whole plan once
|
|
5
|
+
* and expires when the state it was computed from changes; `guardedWrite()` and the effect records that keep a crash or
|
|
6
|
+
* a regenerated turn from repeating a write; and the egress guard and route check that keep every model call on the
|
|
7
|
+
* user's own key. This entry imports no third-party SDK; the adapters for `ai` and Cloudflare `agents` live in the
|
|
8
|
+
* `./ai`, `./byok` and `./agents` subpaths.
|
|
9
|
+
*/
|
|
10
|
+
export { effectKey } from "./effect-key.js";
|
|
11
|
+
export { memoryEffectStore } from "./effect-store.js";
|
|
12
|
+
export { CLOUDFLARE_GATEWAY_TOKEN_HEADER, CLOUDFLARE_NO_WHOLESALE_HEADER, CREDENTIAL_HEADERS, egressGuard, } from "./egress.js";
|
|
13
|
+
export { isSafetyError, SafetyError } from "./errors.js";
|
|
14
|
+
export { guardedWrite } from "./guarded-write.js";
|
|
15
|
+
export { canonicalInputHash } from "./hash.js";
|
|
16
|
+
export { parseKeyRing, signerFromKeyStore } from "./key-store.js";
|
|
17
|
+
export { checkModelRoutes, MODEL_ROUTE_SETTINGS_AS_OF, } from "./model-routes.js";
|
|
18
|
+
export { CLOUDFLARE_AI_GATEWAY_HOST } from "./model-url.js";
|
|
19
|
+
export { ALLOWED_RETRIES, DEFAULT_RETRY, OUTCOME_KINDS, writeOutcome, } from "./outcome.js";
|
|
20
|
+
export { pendingPayload, signPending, verifyResolution, } from "./pending.js";
|
|
21
|
+
export { memoryPendingStore } from "./pending-store.js";
|
|
22
|
+
export { lintPlan, signPlan, stateHash, verifyPlanBeforeStep, } from "./plan-approval.js";
|
|
23
|
+
export { planCard } from "./plan-card.js";
|
|
24
|
+
export { memoryPlanLedger } from "./plan-ledger.js";
|
|
25
|
+
export { planWriteOutcome, renderPlanOutcome, runPlan, } from "./plan-run.js";
|
|
26
|
+
export { renderOutcome } from "./render.js";
|
|
27
|
+
export { ephemeralSigner, hmacSigner, MIN_KEY_BYTES, } from "./signer.js";
|
|
28
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAoB,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC9D,OAAO,EAAyD,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAC7G,OAAO,EACL,+BAA+B,EAC/B,8BAA8B,EAC9B,kBAAkB,EAIlB,WAAW,GACZ,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,aAAa,EAAE,WAAW,EAAwB,MAAM,aAAa,CAAC;AAC/E,OAAO,EAA4B,YAAY,EAAoB,MAAM,oBAAoB,CAAC;AAC9F,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EAA+B,YAAY,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAC/F,OAAO,EAEL,gBAAgB,EAChB,0BAA0B,GAO3B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,gBAAgB,CAAC;AAC5D,OAAO,EACL,eAAe,EAEf,aAAa,EACb,aAAa,EAOb,YAAY,GACb,MAAM,cAAc,CAAC;AACtB,OAAO,EAGL,cAAc,EAOd,WAAW,EAEX,gBAAgB,GACjB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAkC,kBAAkB,EAAqB,MAAM,oBAAoB,CAAC;AAC3G,OAAO,EACL,QAAQ,EAaR,QAAQ,EACR,SAAS,EAET,oBAAoB,GACrB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAoC,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC5E,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAKL,gBAAgB,EAEhB,iBAAiB,EACjB,OAAO,GACR,MAAM,eAAe,CAAC;AACvB,OAAO,EAA6C,aAAa,EAAE,MAAM,aAAa,CAAC;AACvF,OAAO,EAEL,eAAe,EAEf,UAAU,EACV,aAAa,GACd,MAAM,aAAa,CAAC","sourcesContent":["/**\n * `@buildanagent/agent-safety`: the safety core. It holds typed write outcomes that the harness can act on and the\n * model can read; the canonical input hash that approvals sign and effect records store; the signers and signed pending\n * requests that make an approval fail closed; the signed plan approval, which lets a person approve a whole plan once\n * and expires when the state it was computed from changes; `guardedWrite()` and the effect records that keep a crash or\n * a regenerated turn from repeating a write; and the egress guard and route check that keep every model call on the\n * user's own key. This entry imports no third-party SDK; the adapters for `ai` and Cloudflare `agents` live in the\n * `./ai`, `./byok` and `./agents` subpaths.\n */\n\nexport { type EffectScope, effectKey } from \"./effect-key.js\";\nexport { type EffectClaim, type EffectRecord, type EffectStore, memoryEffectStore } from \"./effect-store.js\";\nexport {\n CLOUDFLARE_GATEWAY_TOKEN_HEADER,\n CLOUDFLARE_NO_WHOLESALE_HEADER,\n CREDENTIAL_HEADERS,\n type CredentialHeader,\n type EgressCredential,\n type EgressGuardOptions,\n egressGuard,\n} from \"./egress.js\";\nexport { isSafetyError, SafetyError, type SafetyErrorCode } from \"./errors.js\";\nexport { type GuardedWriteOptions, guardedWrite, type WriteDedupe } from \"./guarded-write.js\";\nexport { canonicalInputHash } from \"./hash.js\";\nexport { type KeyRing, type KeyStore, parseKeyRing, signerFromKeyStore } from \"./key-store.js\";\nexport {\n type CloudflareAiGatewaySettings,\n checkModelRoutes,\n MODEL_ROUTE_SETTINGS_AS_OF,\n type ModelRoute,\n type ModelRouteProblem,\n type ModelRouteProblemCode,\n type ModelRouteProvider,\n type ModelRoutesConfig,\n type ModelRoutesReport,\n} from \"./model-routes.js\";\nexport { CLOUDFLARE_AI_GATEWAY_HOST } from \"./model-url.js\";\nexport {\n ALLOWED_RETRIES,\n type AllowedRetry,\n DEFAULT_RETRY,\n OUTCOME_KINDS,\n type OutcomeFields,\n type OutcomeKind,\n type Retry,\n type WriteOutcome,\n type WriteOutcomeInit,\n type WriteOutcomeOf,\n writeOutcome,\n} from \"./outcome.js\";\nexport {\n type PendingCall,\n type PendingFields,\n pendingPayload,\n type Recheck,\n type RejectionCause,\n type Resolution,\n type ResolutionCheck,\n type SignedPendingRequest,\n type SignPendingOptions,\n signPending,\n type VerifyResolutionOptions,\n verifyResolution,\n} from \"./pending.js\";\nexport { type MemoryPendingStoreOptions, memoryPendingStore, type PendingStore } from \"./pending-store.js\";\nexport {\n lintPlan,\n type PlanApproval,\n type PlanFields,\n type PlanLedger,\n type PlanLint,\n type PlanStep,\n type PlanStepCall,\n type PlanStepCheck,\n type PlanStepInit,\n type SignPlanOptions,\n type StateRead,\n type StateValue,\n type StepClass,\n signPlan,\n stateHash,\n type VerifyPlanStepOptions,\n verifyPlanBeforeStep,\n} from \"./plan-approval.js\";\nexport { type PlanCard, type PlanCardStep, planCard } from \"./plan-card.js\";\nexport { memoryPlanLedger } from \"./plan-ledger.js\";\nexport {\n type PlanFailureReason,\n type PlanOutcome,\n type PlanScope,\n type PlanStepImpl,\n planWriteOutcome,\n type RunPlanOptions,\n renderPlanOutcome,\n runPlan,\n} from \"./plan-run.js\";\nexport { type OutcomePayload, type RenderedOutcome, renderOutcome } from \"./render.js\";\nexport {\n type ApprovalSigner,\n ephemeralSigner,\n type HmacSignerOptions,\n hmacSigner,\n MIN_KEY_BYTES,\n} from \"./signer.js\";\n"]}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { type ApprovalSigner } from "./signer.js";
|
|
2
|
+
/** A key ring: every key a signer may verify with, by id, and the id of the key that signs. */
|
|
3
|
+
export interface KeyRing {
|
|
4
|
+
/** Every key the signer may verify with, by key id. Each key is 32 or more random bytes. */
|
|
5
|
+
readonly keys: Readonly<Record<string, Uint8Array>>;
|
|
6
|
+
/** The id of the key that signs, which must be one of `keys`. */
|
|
7
|
+
readonly current: string;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* A host's key ring store. `load()` returns the ring. `rotate()` adds a new current key and returns its id, and
|
|
11
|
+
* `prune()` removes the keys no unresolved pause names, other than the current one, and returns their ids; a store
|
|
12
|
+
* backed by a read-only secret leaves both out.
|
|
13
|
+
*/
|
|
14
|
+
export interface KeyStore {
|
|
15
|
+
/** Returns the current ring. */
|
|
16
|
+
load(): Promise<KeyRing>;
|
|
17
|
+
/** Adds a new key, makes it `current` and returns its id. Leave it out for a read-only store. */
|
|
18
|
+
rotate?(): Promise<string>;
|
|
19
|
+
/**
|
|
20
|
+
* Removes every key whose id is not in `inUse`, the ids that unresolved pauses still name, except the current key,
|
|
21
|
+
* which it always keeps, and returns the removed ids. A pause whose key is gone fails closed, so pass every id a
|
|
22
|
+
* stored pending request names.
|
|
23
|
+
*/
|
|
24
|
+
prune?(inUse: Set<string>): Promise<string[]>;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Reads a key ring from JSON text such as a secret's value: `{"current":"2026-11","keys":{"2026-11":"<key>"}}`,
|
|
28
|
+
* where each key is base64url without padding. Generate a key with 32 random bytes, for example
|
|
29
|
+
* `openssl rand -base64 32 | tr '+/' '-_' | tr -d '='`.
|
|
30
|
+
*
|
|
31
|
+
* Throws a `SafetyError`, code `invalid_key_ring`, when the text isn't such an object or a key isn't base64url. The
|
|
32
|
+
* error never holds a key's value, but it repeats key ids as the text spells them, so don't show it where the text
|
|
33
|
+
* itself must stay secret. `hmacSigner()` checks the rest: key lengths, ids and `current`.
|
|
34
|
+
*/
|
|
35
|
+
export declare function parseKeyRing(text: string): KeyRing;
|
|
36
|
+
/** Loads the ring from `store` and returns `hmacSigner()` over it. Load it again to pick up a rotated ring. */
|
|
37
|
+
export declare function signerFromKeyStore(store: KeyStore): Promise<ApprovalSigner>;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `KeyStore`: where a host keeps its approval key ring. Only `load()` is required, so a read-only cloud secret can
|
|
3
|
+
* back the ring, and rotation is then the platform's job (ADR 0035). `parseKeyRing()` reads the ring from the text of
|
|
4
|
+
* such a secret.
|
|
5
|
+
*/
|
|
6
|
+
import { fromBase64Url } from "./bytes.js";
|
|
7
|
+
import { SafetyError } from "./errors.js";
|
|
8
|
+
import { hmacSigner } from "./signer.js";
|
|
9
|
+
function invalid(message) {
|
|
10
|
+
return new SafetyError("invalid_key_ring", message);
|
|
11
|
+
}
|
|
12
|
+
function parseJson(text) {
|
|
13
|
+
try {
|
|
14
|
+
return JSON.parse(text);
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
// The parser's message can quote the text around the error, which here is key material, so it is dropped.
|
|
18
|
+
throw invalid("the key ring is not valid JSON");
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Reads a key ring from JSON text such as a secret's value: `{"current":"2026-11","keys":{"2026-11":"<key>"}}`,
|
|
23
|
+
* where each key is base64url without padding. Generate a key with 32 random bytes, for example
|
|
24
|
+
* `openssl rand -base64 32 | tr '+/' '-_' | tr -d '='`.
|
|
25
|
+
*
|
|
26
|
+
* Throws a `SafetyError`, code `invalid_key_ring`, when the text isn't such an object or a key isn't base64url. The
|
|
27
|
+
* error never holds a key's value, but it repeats key ids as the text spells them, so don't show it where the text
|
|
28
|
+
* itself must stay secret. `hmacSigner()` checks the rest: key lengths, ids and `current`.
|
|
29
|
+
*/
|
|
30
|
+
export function parseKeyRing(text) {
|
|
31
|
+
const value = parseJson(text);
|
|
32
|
+
if (typeof value !== "object" || value === null)
|
|
33
|
+
throw invalid("the key ring must be a JSON object");
|
|
34
|
+
const { current, keys } = value;
|
|
35
|
+
if (typeof current !== "string")
|
|
36
|
+
throw invalid("the key ring's current must be a string");
|
|
37
|
+
if (typeof keys !== "object" || keys === null || Array.isArray(keys)) {
|
|
38
|
+
throw invalid("the key ring's keys must be an object of key id to base64url key");
|
|
39
|
+
}
|
|
40
|
+
const decoded = {};
|
|
41
|
+
for (const [id, encoded] of Object.entries(keys)) {
|
|
42
|
+
const bytes = typeof encoded === "string" ? fromBase64Url(encoded) : undefined;
|
|
43
|
+
if (bytes === undefined)
|
|
44
|
+
throw invalid(`the key ${JSON.stringify(id)} must be unpadded base64url`);
|
|
45
|
+
Object.defineProperty(decoded, id, { value: bytes, enumerable: true });
|
|
46
|
+
}
|
|
47
|
+
return { keys: decoded, current };
|
|
48
|
+
}
|
|
49
|
+
/** Loads the ring from `store` and returns `hmacSigner()` over it. Load it again to pick up a rotated ring. */
|
|
50
|
+
export async function signerFromKeyStore(store) {
|
|
51
|
+
return hmacSigner(await store.load());
|
|
52
|
+
}
|
|
53
|
+
//# sourceMappingURL=key-store.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"key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AO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAC/E,IAAI,KAAK,KAAK,SAAS;YAAE,MAAM,OAAO,CAAC,WAAW,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,6BAA6B,CAAC,CAAC;QACnG,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC;IACzE,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AACpC,CAAC;AAED,+GAA+G;AAC/G,MAAM,CAAC,KAAK,UAAU,kBAAkB,CAAC,KAAe;IACtD,OAAO,UAAU,CAAC,MAAM,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC;AACxC,CAAC","sourcesContent":["/**\n * `KeyStore`: where a host keeps its approval key ring. Only `load()` is required, so a read-only cloud secret can\n * back the ring, and rotation is then the platform's job (ADR 0035). `parseKeyRing()` reads the ring from the text of\n * such a secret.\n */\nimport { fromBase64Url } from \"./bytes.js\";\nimport { SafetyError } from \"./errors.js\";\nimport { type ApprovalSigner, hmacSigner } from \"./signer.js\";\n\n/** A key ring: every key a signer may verify with, by id, and the id of the key that signs. */\nexport interface KeyRing {\n /** Every key the signer may verify with, by key id. Each key is 32 or more random bytes. */\n readonly keys: Readonly<Record<string, Uint8Array>>;\n /** The id of the key that signs, which must be one of `keys`. */\n readonly current: string;\n}\n\n/**\n * A host's key ring store. `load()` returns the ring. `rotate()` adds a new current key and returns its id, and\n * `prune()` removes the keys no unresolved pause names, other than the current one, and returns their ids; a store\n * backed by a read-only secret leaves both out.\n */\nexport interface KeyStore {\n /** Returns the current ring. */\n load(): Promise<KeyRing>;\n /** Adds a new key, makes it `current` and returns its id. Leave it out for a read-only store. */\n rotate?(): Promise<string>;\n /**\n * Removes every key whose id is not in `inUse`, the ids that unresolved pauses still name, except the current key,\n * which it always keeps, and returns the removed ids. A pause whose key is gone fails closed, so pass every id a\n * stored pending request names.\n */\n prune?(inUse: Set<string>): Promise<string[]>;\n}\n\nfunction invalid(message: string): SafetyError {\n return new SafetyError(\"invalid_key_ring\", message);\n}\n\nfunction parseJson(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n // The parser's message can quote the text around the error, which here is key material, so it is dropped.\n throw invalid(\"the key ring is not valid JSON\");\n }\n}\n\n/**\n * Reads a key ring from JSON text such as a secret's value: `{\"current\":\"2026-11\",\"keys\":{\"2026-11\":\"<key>\"}}`,\n * where each key is base64url without padding. Generate a key with 32 random bytes, for example\n * `openssl rand -base64 32 | tr '+/' '-_' | tr -d '='`.\n *\n * Throws a `SafetyError`, code `invalid_key_ring`, when the text isn't such an object or a key isn't base64url. The\n * error never holds a key's value, but it repeats key ids as the text spells them, so don't show it where the text\n * itself must stay secret. `hmacSigner()` checks the rest: key lengths, ids and `current`.\n */\nexport function parseKeyRing(text: string): KeyRing {\n const value = parseJson(text);\n if (typeof value !== \"object\" || value === null) throw invalid(\"the key ring must be a JSON object\");\n const { current, keys } = value as Record<string, unknown>;\n if (typeof current !== \"string\") throw invalid(\"the key ring's current must be a string\");\n if (typeof keys !== \"object\" || keys === null || Array.isArray(keys)) {\n throw invalid(\"the key ring's keys must be an object of key id to base64url key\");\n }\n const decoded: Record<string, Uint8Array> = {};\n for (const [id, encoded] of Object.entries(keys)) {\n const bytes = typeof encoded === \"string\" ? fromBase64Url(encoded) : undefined;\n if (bytes === undefined) throw invalid(`the key ${JSON.stringify(id)} must be unpadded base64url`);\n Object.defineProperty(decoded, id, { value: bytes, enumerable: true });\n }\n return { keys: decoded, current };\n}\n\n/** Loads the ring from `store` and returns `hmacSigner()` over it. Load it again to pick up a rotated ring. */\nexport async function signerFromKeyStore(store: KeyStore): Promise<ApprovalSigner> {\n return hmacSigner(await store.load());\n}\n"]}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The date of the gateway documentation the checker's setting names come from: Cloudflare AI Gateway's Unified
|
|
3
|
+
* Billing page (`byok_only`, "Require provider credentials") and Vercel AI Gateway's BYOK page ("Fallback to Vercel
|
|
4
|
+
* Keys"). A field the checker doesn't know fails the check, so a renamed setting is caught rather than passed.
|
|
5
|
+
*/
|
|
6
|
+
export declare const MODEL_ROUTE_SETTINGS_AS_OF = "2026-11-18";
|
|
7
|
+
/** The providers a model route may name. */
|
|
8
|
+
export type ModelRouteProvider = "anthropic" | "openai";
|
|
9
|
+
/** The Cloudflare AI Gateway settings a route through that gateway must record. */
|
|
10
|
+
export interface CloudflareAiGatewaySettings {
|
|
11
|
+
/** Cloudflare's "Require provider credentials": the gateway refuses to bill its own credentials. Must be `true`. */
|
|
12
|
+
readonly byok_only: boolean;
|
|
13
|
+
}
|
|
14
|
+
/** One model route a deploy configures: which provider, at which base URL, and the gateway's settings if it has one. */
|
|
15
|
+
export interface ModelRoute {
|
|
16
|
+
readonly provider: ModelRouteProvider;
|
|
17
|
+
readonly baseURL: string;
|
|
18
|
+
/** Required when `baseURL` is on Cloudflare AI Gateway, and not allowed otherwise. */
|
|
19
|
+
readonly cloudflareAiGateway?: CloudflareAiGatewaySettings;
|
|
20
|
+
}
|
|
21
|
+
/** The model routes a deploy step produces, which `checkModelRoutes()` reads. */
|
|
22
|
+
export interface ModelRoutesConfig {
|
|
23
|
+
readonly routes: readonly ModelRoute[];
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Why a configuration failed. `invalid_config`: it doesn't have the shape `ModelRoutesConfig` describes.
|
|
27
|
+
* `unknown_field`: it names a field the checker doesn't know. `invalid_base_url`: a base URL breaks the rules
|
|
28
|
+
* `egressGuard()` applies. `vercel_ai_gateway`: a route goes through Vercel AI Gateway. `provider_mismatch`: a route
|
|
29
|
+
* through Cloudflare AI Gateway uses an endpoint other than its own provider's. `byok_only_missing` and
|
|
30
|
+
* `byok_only_off`: a route through Cloudflare AI Gateway doesn't record `byok_only: true`.
|
|
31
|
+
*/
|
|
32
|
+
export type ModelRouteProblemCode = "invalid_config" | "unknown_field" | "invalid_base_url" | "vercel_ai_gateway" | "provider_mismatch" | "byok_only_missing" | "byok_only_off";
|
|
33
|
+
/** One reason a configuration failed. */
|
|
34
|
+
export interface ModelRouteProblem {
|
|
35
|
+
readonly code: ModelRouteProblemCode;
|
|
36
|
+
/** The index of the route at fault, or absent for a problem with the configuration as a whole. */
|
|
37
|
+
readonly route?: number;
|
|
38
|
+
readonly message: string;
|
|
39
|
+
}
|
|
40
|
+
/** What `checkModelRoutes()` found. `ok` is true only when `problems` is empty. */
|
|
41
|
+
export interface ModelRoutesReport {
|
|
42
|
+
readonly ok: boolean;
|
|
43
|
+
readonly problems: readonly ModelRouteProblem[];
|
|
44
|
+
/** The documentation date the checker was written against, `MODEL_ROUTE_SETTINGS_AS_OF`. */
|
|
45
|
+
readonly settingsAsOf: string;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Checks the model routes a deploy configures and reports every problem, so a deploy gate can fail on any of them.
|
|
49
|
+
* The check fails closed: a configuration that isn't a `ModelRoutesConfig`, lists no routes or names an unknown field
|
|
50
|
+
* fails, as does a route through Vercel AI Gateway, whose fallback to Vercel's own keys is a team dashboard setting
|
|
51
|
+
* that no configuration records. A route through Cloudflare AI Gateway passes only with `byok_only: true` and a base
|
|
52
|
+
* URL on its own provider's endpoint.
|
|
53
|
+
*/
|
|
54
|
+
export declare function checkModelRoutes(config: unknown): ModelRoutesReport;
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `checkModelRoutes()`: the deploy check that every model route keeps the user's own key. A route through Cloudflare
|
|
3
|
+
* AI Gateway passes only with `byok_only: true`, and a route through Vercel AI Gateway never passes.
|
|
4
|
+
*/
|
|
5
|
+
import { cloudflareProviderMismatch, isCloudflareAiGatewayHost, parseModelBaseUrl } from "./model-url.js";
|
|
6
|
+
/**
|
|
7
|
+
* The date of the gateway documentation the checker's setting names come from: Cloudflare AI Gateway's Unified
|
|
8
|
+
* Billing page (`byok_only`, "Require provider credentials") and Vercel AI Gateway's BYOK page ("Fallback to Vercel
|
|
9
|
+
* Keys"). A field the checker doesn't know fails the check, so a renamed setting is caught rather than passed.
|
|
10
|
+
*/
|
|
11
|
+
export const MODEL_ROUTE_SETTINGS_AS_OF = "2026-11-18";
|
|
12
|
+
const CONFIG_FIELDS = new Set(["routes"]);
|
|
13
|
+
const ROUTE_FIELDS = new Set(["provider", "baseURL", "cloudflareAiGateway"]);
|
|
14
|
+
const CLOUDFLARE_FIELDS = new Set(["byok_only"]);
|
|
15
|
+
const PROVIDERS = new Set(["anthropic", "openai"]);
|
|
16
|
+
// Provider names that mean "let the AI SDK's gateway pick the credential".
|
|
17
|
+
const GATEWAY_PROVIDERS = new Set(["gateway", "vercel"]);
|
|
18
|
+
function isRecord(value) {
|
|
19
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
20
|
+
}
|
|
21
|
+
function unknownFields(value, known, where, route) {
|
|
22
|
+
return Object.keys(value)
|
|
23
|
+
.filter((key) => !known.has(key))
|
|
24
|
+
.map((key) => withRoute({ code: "unknown_field", message: `${where} has unknown field ${key}` }, route));
|
|
25
|
+
}
|
|
26
|
+
function withRoute(problem, route) {
|
|
27
|
+
return route === undefined ? problem : { ...problem, route };
|
|
28
|
+
}
|
|
29
|
+
function checkProvider(provider, route) {
|
|
30
|
+
if (typeof provider === "string" && PROVIDERS.has(provider))
|
|
31
|
+
return [];
|
|
32
|
+
if (typeof provider === "string" && GATEWAY_PROVIDERS.has(provider)) {
|
|
33
|
+
return [{ code: "vercel_ai_gateway", route, message: `provider ${provider} routes through Vercel AI Gateway` }];
|
|
34
|
+
}
|
|
35
|
+
return [{ code: "invalid_config", route, message: "provider must be anthropic or openai" }];
|
|
36
|
+
}
|
|
37
|
+
function checkCloudflareSettings(settings, route) {
|
|
38
|
+
const missing = {
|
|
39
|
+
code: "byok_only_missing",
|
|
40
|
+
route,
|
|
41
|
+
message: "a route through Cloudflare AI Gateway must record cloudflareAiGateway.byok_only: true",
|
|
42
|
+
};
|
|
43
|
+
if (settings === undefined)
|
|
44
|
+
return [missing];
|
|
45
|
+
if (!isRecord(settings))
|
|
46
|
+
return [{ code: "invalid_config", route, message: "cloudflareAiGateway must be an object" }];
|
|
47
|
+
const problems = unknownFields(settings, CLOUDFLARE_FIELDS, "cloudflareAiGateway", route);
|
|
48
|
+
const byokOnly = settings.byok_only;
|
|
49
|
+
if (byokOnly === undefined)
|
|
50
|
+
problems.push(missing);
|
|
51
|
+
else if (byokOnly === false) {
|
|
52
|
+
problems.push({ code: "byok_only_off", route, message: "Cloudflare AI Gateway's byok_only is false" });
|
|
53
|
+
}
|
|
54
|
+
else if (byokOnly !== true) {
|
|
55
|
+
problems.push({ code: "invalid_config", route, message: "cloudflareAiGateway.byok_only must be a boolean" });
|
|
56
|
+
}
|
|
57
|
+
return problems;
|
|
58
|
+
}
|
|
59
|
+
function checkRoute(value, route) {
|
|
60
|
+
if (!isRecord(value))
|
|
61
|
+
return [{ code: "invalid_config", route, message: "a route must be an object" }];
|
|
62
|
+
const problems = [...unknownFields(value, ROUTE_FIELDS, "the route", route), ...checkProvider(value.provider, route)];
|
|
63
|
+
const parsed = parseModelBaseUrl(value.baseURL);
|
|
64
|
+
if (!parsed.ok)
|
|
65
|
+
return [...problems, { code: parsed.problem, route, message: parsed.message }];
|
|
66
|
+
// A deployed agent can't reach the deployer's loopback, so a plain-http base URL would fail at runtime.
|
|
67
|
+
if (parsed.url.origin.startsWith("http:")) {
|
|
68
|
+
problems.push({
|
|
69
|
+
code: "invalid_base_url",
|
|
70
|
+
route,
|
|
71
|
+
message: "a deployed route's base URL must use https, not a loopback http URL",
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
if (isCloudflareAiGatewayHost(parsed.url.hostname)) {
|
|
75
|
+
const mismatch = typeof value.provider === "string" && PROVIDERS.has(value.provider)
|
|
76
|
+
? cloudflareProviderMismatch(parsed.url.path, value.provider)
|
|
77
|
+
: undefined;
|
|
78
|
+
if (mismatch !== undefined)
|
|
79
|
+
problems.push({ code: "provider_mismatch", route, message: mismatch });
|
|
80
|
+
problems.push(...checkCloudflareSettings(value.cloudflareAiGateway, route));
|
|
81
|
+
}
|
|
82
|
+
else if (value.cloudflareAiGateway !== undefined) {
|
|
83
|
+
problems.push({
|
|
84
|
+
code: "invalid_config",
|
|
85
|
+
route,
|
|
86
|
+
message: "cloudflareAiGateway is set on a route whose base URL isn't on Cloudflare AI Gateway",
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
return problems;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Checks the model routes a deploy configures and reports every problem, so a deploy gate can fail on any of them.
|
|
93
|
+
* The check fails closed: a configuration that isn't a `ModelRoutesConfig`, lists no routes or names an unknown field
|
|
94
|
+
* fails, as does a route through Vercel AI Gateway, whose fallback to Vercel's own keys is a team dashboard setting
|
|
95
|
+
* that no configuration records. A route through Cloudflare AI Gateway passes only with `byok_only: true` and a base
|
|
96
|
+
* URL on its own provider's endpoint.
|
|
97
|
+
*/
|
|
98
|
+
export function checkModelRoutes(config) {
|
|
99
|
+
const report = (problems) => ({
|
|
100
|
+
ok: problems.length === 0,
|
|
101
|
+
problems,
|
|
102
|
+
settingsAsOf: MODEL_ROUTE_SETTINGS_AS_OF,
|
|
103
|
+
});
|
|
104
|
+
if (!isRecord(config))
|
|
105
|
+
return report([{ code: "invalid_config", message: "the configuration must be an object" }]);
|
|
106
|
+
const problems = unknownFields(config, CONFIG_FIELDS, "the configuration");
|
|
107
|
+
const routes = config.routes;
|
|
108
|
+
if (!Array.isArray(routes) || routes.length === 0) {
|
|
109
|
+
problems.push({ code: "invalid_config", message: "the configuration must list at least one route" });
|
|
110
|
+
return report(problems);
|
|
111
|
+
}
|
|
112
|
+
routes.forEach((route, index) => {
|
|
113
|
+
problems.push(...checkRoute(route, index));
|
|
114
|
+
});
|
|
115
|
+
return report(problems);
|
|
116
|
+
}
|
|
117
|
+
//# sourceMappingURL=model-routes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"model-routes.js","sourceRoot":"","sources":["../src/model-routes.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,0BAA0B,EAAE,yBAAyB,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAE1G;;;;GAIG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,YAAY,CAAC;AAwDvD,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;AAC1C,MAAM,YAAY,GAAG,IAAI,GAAG,CAAC,CAAC,UAAU,EAAE,SAAS,EAAE,qBAAqB,CAAC,CAAC,CAAC;AAC7E,MAAM,iBAAiB,GAAG,IAAI,GAAG,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC;AACjD,MAAM,SAAS,GAAG,IAAI,GAAG,CAAS,CAAC,WAAW,EAAE,QAAQ,CAAC,CAAC,CAAC;AAC3D,2EAA2E;AAC3E,MAAM,iBAAiB,GAAG,IAAI,GAAG,CAAC,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC,CAAC;AAEzD,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC;AAED,SAAS,aAAa,CAAC,KAA8B,EAAE,KAAkB,EAAE,KAAa,EAAE,KAAc;IACtG,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC;SACtB,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;SAChC,GAAG,CACF,CAAC,GAAG,EAAqB,EAAE,CACzB,SAAS,CAAC,EAAE,IAAI,EAAE,eAAe,EAAE,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AC,CAAC,CAAC;IACnH,MAAM,QAAQ,GAAG,aAAa,CAAC,MAAM,EAAE,aAAa,EAAE,mBAAmB,CAAC,CAAC;IAC3E,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC;IAC7B,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAClD,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,gBAAgB,EAAE,OAAO,EAAE,gDAAgD,EAAE,CAAC,CAAC;QACrG,OAAO,MAAM,CAAC,QAAQ,CAAC,CAAC;IAC1B,CAAC;IACD,MAAM,CAAC,OAAO,CAAC,CAAC,KAAc,EAAE,KAAK,EAAE,EAAE;QACvC,QAAQ,CAAC,IAAI,CAAC,GAAG,UAAU,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;IAC7C,CAAC,CAAC,CAAC;IACH,OAAO,MAAM,CAAC,QAAQ,CAAC,CAAC;AAC1B,CAAC","sourcesContent":["/**\n * `checkModelRoutes()`: the deploy check that every model route keeps the user's own key. A route through Cloudflare\n * AI Gateway passes only with `byok_only: true`, and a route through Vercel AI Gateway never passes.\n */\nimport { cloudflareProviderMismatch, isCloudflareAiGatewayHost, parseModelBaseUrl } from \"./model-url.js\";\n\n/**\n * The date of the gateway documentation the checker's setting names come from: Cloudflare AI Gateway's Unified\n * Billing page (`byok_only`, \"Require provider credentials\") and Vercel AI Gateway's BYOK page (\"Fallback to Vercel\n * Keys\"). A field the checker doesn't know fails the check, so a renamed setting is caught rather than passed.\n */\nexport const MODEL_ROUTE_SETTINGS_AS_OF = \"2026-11-18\";\n\n/** The providers a model route may name. */\nexport type ModelRouteProvider = \"anthropic\" | \"openai\";\n\n/** The Cloudflare AI Gateway settings a route through that gateway must record. */\nexport interface CloudflareAiGatewaySettings {\n /** Cloudflare's \"Require provider credentials\": the gateway refuses to bill its own credentials. Must be `true`. */\n readonly byok_only: boolean;\n}\n\n/** One model route a deploy configures: which provider, at which base URL, and the gateway's settings if it has one. */\nexport interface ModelRoute {\n readonly provider: ModelRouteProvider;\n readonly baseURL: string;\n /** Required when `baseURL` is on Cloudflare AI Gateway, and not allowed otherwise. */\n readonly cloudflareAiGateway?: CloudflareAiGatewaySettings;\n}\n\n/** The model routes a deploy step produces, which `checkModelRoutes()` reads. */\nexport interface ModelRoutesConfig {\n readonly routes: readonly ModelRoute[];\n}\n\n/**\n * Why a configuration failed. `invalid_config`: it doesn't have the shape `ModelRoutesConfig` describes.\n * `unknown_field`: it names a field the checker doesn't know. `invalid_base_url`: a base URL breaks the rules\n * `egressGuard()` applies. `vercel_ai_gateway`: a route goes through Vercel AI Gateway. `provider_mismatch`: a route\n * through Cloudflare AI Gateway uses an endpoint other than its own provider's. `byok_only_missing` and\n * `byok_only_off`: a route through Cloudflare AI Gateway doesn't record `byok_only: true`.\n */\nexport type ModelRouteProblemCode =\n | \"invalid_config\"\n | \"unknown_field\"\n | \"invalid_base_url\"\n | \"vercel_ai_gateway\"\n | \"provider_mismatch\"\n | \"byok_only_missing\"\n | \"byok_only_off\";\n\n/** One reason a configuration failed. */\nexport interface ModelRouteProblem {\n readonly code: ModelRouteProblemCode;\n /** The index of the route at fault, or absent for a problem with the configuration as a whole. */\n readonly route?: number;\n readonly message: string;\n}\n\n/** What `checkModelRoutes()` found. `ok` is true only when `problems` is empty. */\nexport interface ModelRoutesReport {\n readonly ok: boolean;\n readonly problems: readonly ModelRouteProblem[];\n /** The documentation date the checker was written against, `MODEL_ROUTE_SETTINGS_AS_OF`. */\n readonly settingsAsOf: string;\n}\n\nconst CONFIG_FIELDS = new Set([\"routes\"]);\nconst ROUTE_FIELDS = new Set([\"provider\", \"baseURL\", \"cloudflareAiGateway\"]);\nconst CLOUDFLARE_FIELDS = new Set([\"byok_only\"]);\nconst PROVIDERS = new Set<string>([\"anthropic\", \"openai\"]);\n// Provider names that mean \"let the AI SDK's gateway pick the credential\".\nconst GATEWAY_PROVIDERS = new Set([\"gateway\", \"vercel\"]);\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction unknownFields(value: Record<string, unknown>, known: Set<string>, where: string, route?: number) {\n return Object.keys(value)\n .filter((key) => !known.has(key))\n .map(\n (key): ModelRouteProblem =>\n withRoute({ code: \"unknown_field\", message: `${where} has unknown field ${key}` }, route),\n );\n}\n\nfunction withRoute(problem: Omit<ModelRouteProblem, \"route\">, route: number | undefined): ModelRouteProblem {\n return route === undefined ? problem : { ...problem, route };\n}\n\nfunction checkProvider(provider: unknown, route: number): ModelRouteProblem[] {\n if (typeof provider === \"string\" && PROVIDERS.has(provider)) return [];\n if (typeof provider === \"string\" && GATEWAY_PROVIDERS.has(provider)) {\n return [{ code: \"vercel_ai_gateway\", route, message: `provider ${provider} routes through Vercel AI Gateway` }];\n }\n return [{ code: \"invalid_config\", route, message: \"provider must be anthropic or openai\" }];\n}\n\nfunction checkCloudflareSettings(settings: unknown, route: number): ModelRouteProblem[] {\n const missing: ModelRouteProblem = {\n code: \"byok_only_missing\",\n route,\n message: \"a route through Cloudflare AI Gateway must record cloudflareAiGateway.byok_only: true\",\n };\n if (settings === undefined) return [missing];\n if (!isRecord(settings)) return [{ code: \"invalid_config\", route, message: \"cloudflareAiGateway must be an object\" }];\n const problems = unknownFields(settings, CLOUDFLARE_FIELDS, \"cloudflareAiGateway\", route);\n const byokOnly = settings.byok_only;\n if (byokOnly === undefined) problems.push(missing);\n else if (byokOnly === false) {\n problems.push({ code: \"byok_only_off\", route, message: \"Cloudflare AI Gateway's byok_only is false\" });\n } else if (byokOnly !== true) {\n problems.push({ code: \"invalid_config\", route, message: \"cloudflareAiGateway.byok_only must be a boolean\" });\n }\n return problems;\n}\n\nfunction checkRoute(value: unknown, route: number): ModelRouteProblem[] {\n if (!isRecord(value)) return [{ code: \"invalid_config\", route, message: \"a route must be an object\" }];\n const problems = [...unknownFields(value, ROUTE_FIELDS, \"the route\", route), ...checkProvider(value.provider, route)];\n const parsed = parseModelBaseUrl(value.baseURL);\n if (!parsed.ok) return [...problems, { code: parsed.problem, route, message: parsed.message }];\n // A deployed agent can't reach the deployer's loopback, so a plain-http base URL would fail at runtime.\n if (parsed.url.origin.startsWith(\"http:\")) {\n problems.push({\n code: \"invalid_base_url\",\n route,\n message: \"a deployed route's base URL must use https, not a loopback http URL\",\n });\n }\n if (isCloudflareAiGatewayHost(parsed.url.hostname)) {\n const mismatch =\n typeof value.provider === \"string\" && PROVIDERS.has(value.provider)\n ? cloudflareProviderMismatch(parsed.url.path, value.provider)\n : undefined;\n if (mismatch !== undefined) problems.push({ code: \"provider_mismatch\", route, message: mismatch });\n problems.push(...checkCloudflareSettings(value.cloudflareAiGateway, route));\n } else if (value.cloudflareAiGateway !== undefined) {\n problems.push({\n code: \"invalid_config\",\n route,\n message: \"cloudflareAiGateway is set on a route whose base URL isn't on Cloudflare AI Gateway\",\n });\n }\n return problems;\n}\n\n/**\n * Checks the model routes a deploy configures and reports every problem, so a deploy gate can fail on any of them.\n * The check fails closed: a configuration that isn't a `ModelRoutesConfig`, lists no routes or names an unknown field\n * fails, as does a route through Vercel AI Gateway, whose fallback to Vercel's own keys is a team dashboard setting\n * that no configuration records. A route through Cloudflare AI Gateway passes only with `byok_only: true` and a base\n * URL on its own provider's endpoint.\n */\nexport function checkModelRoutes(config: unknown): ModelRoutesReport {\n const report = (problems: ModelRouteProblem[]): ModelRoutesReport => ({\n ok: problems.length === 0,\n problems,\n settingsAsOf: MODEL_ROUTE_SETTINGS_AS_OF,\n });\n if (!isRecord(config)) return report([{ code: \"invalid_config\", message: \"the configuration must be an object\" }]);\n const problems = unknownFields(config, CONFIG_FIELDS, \"the configuration\");\n const routes = config.routes;\n if (!Array.isArray(routes) || routes.length === 0) {\n problems.push({ code: \"invalid_config\", message: \"the configuration must list at least one route\" });\n return report(problems);\n }\n routes.forEach((route: unknown, index) => {\n problems.push(...checkRoute(route, index));\n });\n return report(problems);\n}\n"]}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The rules a model provider's base URL must meet before a key may travel to it, shared by `egressGuard()`,
|
|
3
|
+
* `explicitProvider()` and `checkModelRoutes()` so the three never disagree.
|
|
4
|
+
*/
|
|
5
|
+
/** The host of Cloudflare AI Gateway's provider endpoints, as in `https://gateway.ai.cloudflare.com/v1/…`. */
|
|
6
|
+
export declare const CLOUDFLARE_AI_GATEWAY_HOST = "gateway.ai.cloudflare.com";
|
|
7
|
+
/** Why a base URL was refused. */
|
|
8
|
+
export type BaseUrlProblem = "invalid_base_url" | "vercel_ai_gateway";
|
|
9
|
+
/** A base URL that passed the rules: the origin and the path prefix every request must stay under. */
|
|
10
|
+
export interface ModelBaseUrl {
|
|
11
|
+
readonly origin: string;
|
|
12
|
+
/** The base URL's path without a trailing slash, such as `/v1`, or the empty string for the root. */
|
|
13
|
+
readonly path: string;
|
|
14
|
+
readonly hostname: string;
|
|
15
|
+
}
|
|
16
|
+
export type ParsedBaseUrl = {
|
|
17
|
+
readonly ok: true;
|
|
18
|
+
readonly url: ModelBaseUrl;
|
|
19
|
+
} | {
|
|
20
|
+
readonly ok: false;
|
|
21
|
+
readonly problem: BaseUrlProblem;
|
|
22
|
+
readonly message: string;
|
|
23
|
+
};
|
|
24
|
+
/** True for a Cloudflare AI Gateway host. */
|
|
25
|
+
export declare function isCloudflareAiGatewayHost(hostname: string): boolean;
|
|
26
|
+
/**
|
|
27
|
+
* Checks a base URL: an absolute `https:` URL (or `http:` on a loopback host, for a local proxy), with no user name,
|
|
28
|
+
* password, query or fragment, and not on Vercel AI Gateway. The messages name the rule, never the URL's contents
|
|
29
|
+
* beyond its host.
|
|
30
|
+
*/
|
|
31
|
+
export declare function parseModelBaseUrl(baseURL: unknown): ParsedBaseUrl;
|
|
32
|
+
/**
|
|
33
|
+
* Checks that a Cloudflare AI Gateway base URL's path starts with `provider`'s endpoint,
|
|
34
|
+
* `/v1/{account}/{gateway}/{provider}`, so a key meant for one provider never reaches the gateway's endpoint for
|
|
35
|
+
* another. Returns why it doesn't, or `undefined` when it does. The message names the rule, never the path.
|
|
36
|
+
*/
|
|
37
|
+
export declare function cloudflareProviderMismatch(path: string, provider: string): string | undefined;
|
|
38
|
+
/** True when `url` lies on `base`'s origin and at or under its path, and its path holds no encoded separator. */
|
|
39
|
+
export declare function isUnderBase(url: URL, base: ModelBaseUrl): boolean;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The rules a model provider's base URL must meet before a key may travel to it, shared by `egressGuard()`,
|
|
3
|
+
* `explicitProvider()` and `checkModelRoutes()` so the three never disagree.
|
|
4
|
+
*/
|
|
5
|
+
/** The host of Cloudflare AI Gateway's provider endpoints, as in `https://gateway.ai.cloudflare.com/v1/…`. */
|
|
6
|
+
export const CLOUDFLARE_AI_GATEWAY_HOST = "gateway.ai.cloudflare.com";
|
|
7
|
+
// The host `@ai-sdk/gateway` 4.0.135 sends to when no base URL is given. Vercel AI Gateway falls back to Vercel's
|
|
8
|
+
// own billed keys unless a team dashboard setting is off, and nothing a deploy produces records that setting, so the
|
|
9
|
+
// package refuses the host outright (close-sdk-gaps SG4).
|
|
10
|
+
const VERCEL_AI_GATEWAY_HOST = "ai-gateway.vercel.sh";
|
|
11
|
+
const LOOPBACK = /^(?:localhost|127(?:\.\d{1,3}){3}|\[::1\])$/;
|
|
12
|
+
function hostIs(hostname, host) {
|
|
13
|
+
return hostname === host || hostname.endsWith(`.${host}`);
|
|
14
|
+
}
|
|
15
|
+
/** True for a Cloudflare AI Gateway host. */
|
|
16
|
+
export function isCloudflareAiGatewayHost(hostname) {
|
|
17
|
+
return hostIs(hostname.toLowerCase(), CLOUDFLARE_AI_GATEWAY_HOST);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Checks a base URL: an absolute `https:` URL (or `http:` on a loopback host, for a local proxy), with no user name,
|
|
21
|
+
* password, query or fragment, and not on Vercel AI Gateway. The messages name the rule, never the URL's contents
|
|
22
|
+
* beyond its host.
|
|
23
|
+
*/
|
|
24
|
+
export function parseModelBaseUrl(baseURL) {
|
|
25
|
+
const refuse = (message) => ({ ok: false, problem: "invalid_base_url", message });
|
|
26
|
+
if (typeof baseURL !== "string" || baseURL.trim() === "")
|
|
27
|
+
return refuse("the base URL is missing or empty");
|
|
28
|
+
let url;
|
|
29
|
+
try {
|
|
30
|
+
url = new URL(baseURL);
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return refuse("the base URL is not an absolute URL");
|
|
34
|
+
}
|
|
35
|
+
const hostname = url.hostname.toLowerCase();
|
|
36
|
+
// DNS resolves `host.` to `host`, so a trailing dot would slip past every exact host comparison below.
|
|
37
|
+
if (hostname.endsWith("."))
|
|
38
|
+
return refuse("the base URL's host must not end in a dot");
|
|
39
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && LOOPBACK.test(hostname))) {
|
|
40
|
+
return refuse(`the base URL must use https (http only on a loopback host), not ${url.protocol}`);
|
|
41
|
+
}
|
|
42
|
+
if (url.username !== "" || url.password !== "")
|
|
43
|
+
return refuse("the base URL must not carry a user name or password");
|
|
44
|
+
if (url.search !== "" || url.hash !== "")
|
|
45
|
+
return refuse("the base URL must not carry a query or fragment");
|
|
46
|
+
if (hasEncodedSeparator(url.pathname))
|
|
47
|
+
return refuse("the base URL's path must not hold an encoded / or \\");
|
|
48
|
+
if (hostIs(hostname, VERCEL_AI_GATEWAY_HOST)) {
|
|
49
|
+
return {
|
|
50
|
+
ok: false,
|
|
51
|
+
problem: "vercel_ai_gateway",
|
|
52
|
+
message: `${hostname} is Vercel AI Gateway, which may fall back to Vercel's own keys; call the provider directly or through a Cloudflare AI Gateway set to byok_only`,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
return { ok: true, url: { origin: url.origin, path: url.pathname.replace(/\/+$/, ""), hostname } };
|
|
56
|
+
}
|
|
57
|
+
// The URL parser resolves `..` and `%2e%2e` but keeps `%2F` and `%5C`, which a server that decodes before routing
|
|
58
|
+
// would read as separators, so `/v1/..%2fadmin` would pass a prefix check and still leave the base path.
|
|
59
|
+
function hasEncodedSeparator(pathname) {
|
|
60
|
+
return /%2f|%5c/i.test(pathname);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Checks that a Cloudflare AI Gateway base URL's path starts with `provider`'s endpoint,
|
|
64
|
+
* `/v1/{account}/{gateway}/{provider}`, so a key meant for one provider never reaches the gateway's endpoint for
|
|
65
|
+
* another. Returns why it doesn't, or `undefined` when it does. The message names the rule, never the path.
|
|
66
|
+
*/
|
|
67
|
+
export function cloudflareProviderMismatch(path, provider) {
|
|
68
|
+
const segments = path.split("/");
|
|
69
|
+
if (segments[1] === "v1" && segments[2] !== "" && segments[3] !== "" && segments[4] === provider)
|
|
70
|
+
return undefined;
|
|
71
|
+
return `a Cloudflare AI Gateway base URL for ${provider} must start /v1/{account}/{gateway}/${provider}`;
|
|
72
|
+
}
|
|
73
|
+
/** True when `url` lies on `base`'s origin and at or under its path, and its path holds no encoded separator. */
|
|
74
|
+
export function isUnderBase(url, base) {
|
|
75
|
+
if (url.origin !== base.origin || hasEncodedSeparator(url.pathname))
|
|
76
|
+
return false;
|
|
77
|
+
return base.path === "" || url.pathname === base.path || url.pathname.startsWith(`${base.path}/`);
|
|
78
|
+
}
|
|
79
|
+
//# sourceMappingURL=model-url.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"model-url.js","sourceRoot":"","sources":["../src/model-url.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,8GAA8G;AAC9G,MAAM,CAAC,MAAM,0BAA0B,GAAG,2BAA2B,CAAC;AAEtE,kHAAkH;AAClH,qHAAqH;AACrH,0DAA0D;AAC1D,MAAM,sBAAsB,GAAG,sBAAsB,CAAC;AAEtD,MAAM,QAAQ,GAAG,6CAA6C,CAAC;AAiB/D,SAAS,MAAM,CAAC,QAAgB,EAAE,IAAY;IAC5C,OA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M,UAAU,WAAW,CAAC,GAAQ,EAAE,IAAkB;IACtD,IAAI,GAAG,CAAC,MAAM,KAAK,IAAI,CAAC,MAAM,IAAI,mBAAmB,CAAC,GAAG,CAAC,QAAQ,CAAC;QAAE,OAAO,KAAK,CAAC;IAClF,OAAO,IAAI,CAAC,IAAI,KAAK,EAAE,IAAI,GAAG,CAAC,QAAQ,KAAK,IAAI,CAAC,IAAI,IAAI,GAAG,CAAC,QAAQ,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC;AACpG,CAAC","sourcesContent":["/**\n * The rules a model provider's base URL must meet before a key may travel to it, shared by `egressGuard()`,\n * `explicitProvider()` and `checkModelRoutes()` so the three never disagree.\n */\n\n/** The host of Cloudflare AI Gateway's provider endpoints, as in `https://gateway.ai.cloudflare.com/v1/…`. */\nexport const CLOUDFLARE_AI_GATEWAY_HOST = \"gateway.ai.cloudflare.com\";\n\n// The host `@ai-sdk/gateway` 4.0.135 sends to when no base URL is given. Vercel AI Gateway falls back to Vercel's\n// own billed keys unless a team dashboard setting is off, and nothing a deploy produces records that setting, so the\n// package refuses the host outright (close-sdk-gaps SG4).\nconst VERCEL_AI_GATEWAY_HOST = \"ai-gateway.vercel.sh\";\n\nconst LOOPBACK = /^(?:localhost|127(?:\\.\\d{1,3}){3}|\\[::1\\])$/;\n\n/** Why a base URL was refused. */\nexport type BaseUrlProblem = \"invalid_base_url\" | \"vercel_ai_gateway\";\n\n/** A base URL that passed the rules: the origin and the path prefix every request must stay under. */\nexport interface ModelBaseUrl {\n readonly origin: string;\n /** The base URL's path without a trailing slash, such as `/v1`, or the empty string for the root. */\n readonly path: string;\n readonly hostname: string;\n}\n\nexport type ParsedBaseUrl =\n | { readonly ok: true; readonly url: ModelBaseUrl }\n | { readonly ok: false; readonly problem: BaseUrlProblem; readonly message: string };\n\nfunction hostIs(hostname: string, host: string): boolean {\n return hostname === host || hostname.endsWith(`.${host}`);\n}\n\n/** True for a Cloudflare AI Gateway host. */\nexport function isCloudflareAiGatewayHost(hostname: string): boolean {\n return hostIs(hostname.toLowerCase(), CLOUDFLARE_AI_GATEWAY_HOST);\n}\n\n/**\n * Checks a base URL: an absolute `https:` URL (or `http:` on a loopback host, for a local proxy), with no user name,\n * password, query or fragment, and not on Vercel AI Gateway. The messages name the rule, never the URL's contents\n * beyond its host.\n */\nexport function parseModelBaseUrl(baseURL: unknown): ParsedBaseUrl {\n const refuse = (message: string): ParsedBaseUrl => ({ ok: false, problem: \"invalid_base_url\", message });\n if (typeof baseURL !== \"string\" || baseURL.trim() === \"\") return refuse(\"the base URL is missing or empty\");\n let url: URL;\n try {\n url = new URL(baseURL);\n } catch {\n return refuse(\"the base URL is not an absolute URL\");\n }\n const hostname = url.hostname.toLowerCase();\n // DNS resolves `host.` to `host`, so a trailing dot would slip past every exact host comparison below.\n if (hostname.endsWith(\".\")) return refuse(\"the base URL's host must not end in a dot\");\n if (url.protocol !== \"https:\" && !(url.protocol === \"http:\" && LOOPBACK.test(hostname))) {\n return refuse(`the base URL must use https (http only on a loopback host), not ${url.protocol}`);\n }\n if (url.username !== \"\" || url.password !== \"\") return refuse(\"the base URL must not carry a user name or password\");\n if (url.search !== \"\" || url.hash !== \"\") return refuse(\"the base URL must not carry a query or fragment\");\n if (hasEncodedSeparator(url.pathname)) return refuse(\"the base URL's path must not hold an encoded / or \\\\\");\n if (hostIs(hostname, VERCEL_AI_GATEWAY_HOST)) {\n return {\n ok: false,\n problem: \"vercel_ai_gateway\",\n message: `${hostname} is Vercel AI Gateway, which may fall back to Vercel's own keys; call the provider directly or through a Cloudflare AI Gateway set to byok_only`,\n };\n }\n return { ok: true, url: { origin: url.origin, path: url.pathname.replace(/\\/+$/, \"\"), hostname } };\n}\n\n// The URL parser resolves `..` and `%2e%2e` but keeps `%2F` and `%5C`, which a server that decodes before routing\n// would read as separators, so `/v1/..%2fadmin` would pass a prefix check and still leave the base path.\nfunction hasEncodedSeparator(pathname: string): boolean {\n return /%2f|%5c/i.test(pathname);\n}\n\n/**\n * Checks that a Cloudflare AI Gateway base URL's path starts with `provider`'s endpoint,\n * `/v1/{account}/{gateway}/{provider}`, so a key meant for one provider never reaches the gateway's endpoint for\n * another. Returns why it doesn't, or `undefined` when it does. The message names the rule, never the path.\n */\nexport function cloudflareProviderMismatch(path: string, provider: string): string | undefined {\n const segments = path.split(\"/\");\n if (segments[1] === \"v1\" && segments[2] !== \"\" && segments[3] !== \"\" && segments[4] === provider) return undefined;\n return `a Cloudflare AI Gateway base URL for ${provider} must start /v1/{account}/{gateway}/${provider}`;\n}\n\n/** True when `url` lies on `base`'s origin and at or under its path, and its path holds no encoded separator. */\nexport function isUnderBase(url: URL, base: ModelBaseUrl): boolean {\n if (url.origin !== base.origin || hasEncodedSeparator(url.pathname)) return false;\n return base.path === \"\" || url.pathname === base.path || url.pathname.startsWith(`${base.path}/`);\n}\n"]}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a write did. `applied`: it took effect. `not_applied`: it was rejected before any effect. `compensated`: it
|
|
3
|
+
* took effect and was then undone. `partial`: some effects hold and the rest could not be undone. `unknown`: nobody
|
|
4
|
+
* knows whether it took effect, as after a timeout or a lost response.
|
|
5
|
+
*/
|
|
6
|
+
export type OutcomeKind = "applied" | "not_applied" | "compensated" | "partial" | "unknown";
|
|
7
|
+
/**
|
|
8
|
+
* When the same write may run again. `same_key`: retry with the same effect key, so it takes effect at most once.
|
|
9
|
+
* `new_operation_only`: only as a new operation, if the user still wants it. `reconcile_first`: check what happened
|
|
10
|
+
* before any retry. `never`: do not retry.
|
|
11
|
+
*/
|
|
12
|
+
export type Retry = "same_key" | "new_operation_only" | "reconcile_first" | "never";
|
|
13
|
+
/** The retry rules each outcome kind allows. */
|
|
14
|
+
export interface AllowedRetry {
|
|
15
|
+
applied: "never";
|
|
16
|
+
not_applied: "same_key" | "new_operation_only" | "never";
|
|
17
|
+
compensated: "new_operation_only" | "never";
|
|
18
|
+
partial: "same_key" | "reconcile_first" | "never";
|
|
19
|
+
unknown: "same_key" | "reconcile_first" | "never";
|
|
20
|
+
}
|
|
21
|
+
/** The fields every write outcome carries, whatever its kind. */
|
|
22
|
+
export interface OutcomeFields {
|
|
23
|
+
/** The tool or business operation, such as `send_email`. */
|
|
24
|
+
readonly operation: string;
|
|
25
|
+
/** The key that makes a retry of this write take effect at most once. */
|
|
26
|
+
readonly effectKey?: string;
|
|
27
|
+
/** Effects that hold now. */
|
|
28
|
+
readonly applied: readonly string[];
|
|
29
|
+
/** Effects that were undone. */
|
|
30
|
+
readonly reverted: readonly string[];
|
|
31
|
+
/** Effects that happened and cannot be undone, such as "email delivered 14:02". */
|
|
32
|
+
readonly notReversible: readonly string[];
|
|
33
|
+
/** One line about the current state that the model can trust. */
|
|
34
|
+
readonly currentState?: string;
|
|
35
|
+
/** What the model should do next. */
|
|
36
|
+
readonly next: string;
|
|
37
|
+
/** What the model must not do, beyond what the kind already rules out. */
|
|
38
|
+
readonly avoid?: string;
|
|
39
|
+
/** A stable code for the cause, in upper snake case and at most 63 characters, such as `CARD_DECLINED`. */
|
|
40
|
+
readonly reason?: string;
|
|
41
|
+
}
|
|
42
|
+
/** A write outcome of one kind, whose `retry` is one of the rules that kind allows. */
|
|
43
|
+
export type WriteOutcomeOf<K extends OutcomeKind> = OutcomeFields & {
|
|
44
|
+
readonly kind: K;
|
|
45
|
+
readonly retry: AllowedRetry[K];
|
|
46
|
+
};
|
|
47
|
+
/** What a write reports: one of the five kinds, with its retry rule and what the model should do next. */
|
|
48
|
+
export type WriteOutcome = {
|
|
49
|
+
[K in OutcomeKind]: WriteOutcomeOf<K>;
|
|
50
|
+
}[OutcomeKind];
|
|
51
|
+
/** The fields you can leave out of a write outcome, because `writeOutcome()` fills them in. */
|
|
52
|
+
type Defaulted = "applied" | "reverted" | "notReversible";
|
|
53
|
+
/**
|
|
54
|
+
* The input to `writeOutcome()`. `retry` defaults to the kind's rule in `DEFAULT_RETRY`, and the three effect lists
|
|
55
|
+
* default to empty.
|
|
56
|
+
*/
|
|
57
|
+
export type WriteOutcomeInit = {
|
|
58
|
+
[K in OutcomeKind]: Omit<OutcomeFields, Defaulted> & Partial<Pick<OutcomeFields, Defaulted>> & {
|
|
59
|
+
readonly kind: K;
|
|
60
|
+
readonly retry?: AllowedRetry[K];
|
|
61
|
+
};
|
|
62
|
+
}[OutcomeKind];
|
|
63
|
+
/** The five outcome kinds, in the order the docs list them. */
|
|
64
|
+
export declare const OUTCOME_KINDS: readonly OutcomeKind[];
|
|
65
|
+
/**
|
|
66
|
+
* The retry rule each kind gets when the tool sets none: a rejected write may run again with the same key, an undone
|
|
67
|
+
* one only as a new operation, a partial one goes to a person, and an unknown one is checked first.
|
|
68
|
+
*/
|
|
69
|
+
export declare const DEFAULT_RETRY: {
|
|
70
|
+
readonly [K in OutcomeKind]: AllowedRetry[K];
|
|
71
|
+
};
|
|
72
|
+
/** The retry rules each kind allows, as `AllowedRetry` lists them. */
|
|
73
|
+
export declare const ALLOWED_RETRIES: {
|
|
74
|
+
readonly [K in OutcomeKind]: readonly AllowedRetry[K][];
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* Builds a write outcome, filling in the defaults and checking every field. The result is frozen.
|
|
78
|
+
*
|
|
79
|
+
* Throws a `SafetyError`, code `invalid_outcome`, for:
|
|
80
|
+
* - an unknown kind, or a retry rule the kind doesn't allow;
|
|
81
|
+
* - an empty `operation` or `next`, or an `operation` with leading or trailing spaces;
|
|
82
|
+
* - a blank effect or optional text field;
|
|
83
|
+
* - a `reason` that isn't upper snake case of at most 63 characters;
|
|
84
|
+
* - effects the kind contradicts: any effect on `not_applied`, `reverted` on `applied`, `applied` on `compensated`;
|
|
85
|
+
* - a `partial` or `unknown` outcome that allows a `same_key` retry without an `effectKey`.
|
|
86
|
+
*/
|
|
87
|
+
export declare function writeOutcome(init: WriteOutcomeInit): WriteOutcome;
|
|
88
|
+
export {};
|