@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/outcome.js
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The five write outcomes: what a tool that changes the world reports, so the harness can act on it and the model can
|
|
3
|
+
* read it. Each kind allows only the retry rules that are safe for it, and `unknown` never allows a fresh operation,
|
|
4
|
+
* because the first attempt may still have taken effect (close-sdk-gaps SG3).
|
|
5
|
+
*/
|
|
6
|
+
import { SafetyError } from "./errors.js";
|
|
7
|
+
/** The five outcome kinds, in the order the docs list them. */
|
|
8
|
+
export const OUTCOME_KINDS = Object.freeze([
|
|
9
|
+
"applied",
|
|
10
|
+
"not_applied",
|
|
11
|
+
"compensated",
|
|
12
|
+
"partial",
|
|
13
|
+
"unknown",
|
|
14
|
+
]);
|
|
15
|
+
/**
|
|
16
|
+
* The retry rule each kind gets when the tool sets none: a rejected write may run again with the same key, an undone
|
|
17
|
+
* one only as a new operation, a partial one goes to a person, and an unknown one is checked first.
|
|
18
|
+
*/
|
|
19
|
+
export const DEFAULT_RETRY = Object.freeze({
|
|
20
|
+
applied: "never",
|
|
21
|
+
not_applied: "same_key",
|
|
22
|
+
compensated: "new_operation_only",
|
|
23
|
+
partial: "never",
|
|
24
|
+
unknown: "reconcile_first",
|
|
25
|
+
});
|
|
26
|
+
/** The retry rules each kind allows, as `AllowedRetry` lists them. */
|
|
27
|
+
export const ALLOWED_RETRIES = Object.freeze({
|
|
28
|
+
applied: Object.freeze(["never"]),
|
|
29
|
+
not_applied: Object.freeze(["same_key", "new_operation_only", "never"]),
|
|
30
|
+
compensated: Object.freeze(["new_operation_only", "never"]),
|
|
31
|
+
partial: Object.freeze(["same_key", "reconcile_first", "never"]),
|
|
32
|
+
unknown: Object.freeze(["same_key", "reconcile_first", "never"]),
|
|
33
|
+
});
|
|
34
|
+
// AIP-193's rule for `reason`: upper snake case, no leading digit or underscore, no trailing underscore.
|
|
35
|
+
const REASON = /^[A-Z][A-Z0-9_]+[A-Z0-9]$/;
|
|
36
|
+
const MAX_REASON_LENGTH = 63;
|
|
37
|
+
function invalid(message) {
|
|
38
|
+
return new SafetyError("invalid_outcome", message);
|
|
39
|
+
}
|
|
40
|
+
function requireText(value, field) {
|
|
41
|
+
if (typeof value !== "string" || value.trim() === "")
|
|
42
|
+
throw invalid(`a write outcome's ${field} must be non-empty`);
|
|
43
|
+
}
|
|
44
|
+
function requireOptionalText(value, field) {
|
|
45
|
+
// A blank value would render as an empty sentence, such as "Current state: .", so it must be left out instead.
|
|
46
|
+
if (value !== undefined && (typeof value !== "string" || value.trim() === "")) {
|
|
47
|
+
throw invalid(`a write outcome's ${field} must be non-empty when it is set`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
function effectList(value, field) {
|
|
51
|
+
if (value === undefined)
|
|
52
|
+
return Object.freeze([]);
|
|
53
|
+
if (!Array.isArray(value) || !value.every((item) => typeof item === "string" && item.trim() !== "")) {
|
|
54
|
+
throw invalid(`a write outcome's ${field} must be a list of non-empty strings`);
|
|
55
|
+
}
|
|
56
|
+
return Object.freeze([...value]);
|
|
57
|
+
}
|
|
58
|
+
function checkReason(reason) {
|
|
59
|
+
if (reason === undefined)
|
|
60
|
+
return;
|
|
61
|
+
if (typeof reason !== "string" || reason.length > MAX_REASON_LENGTH || !REASON.test(reason)) {
|
|
62
|
+
throw invalid(`a write outcome's reason must be upper snake case and at most ${MAX_REASON_LENGTH} characters, ` +
|
|
63
|
+
`got ${JSON.stringify(reason)}`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
// The effect lists each kind can't hold, because the kind's own sentence would contradict them: a write that changed
|
|
67
|
+
// nothing has no effects, one that took effect undid nothing, and one that was undone holds none of its effects.
|
|
68
|
+
const FORBIDDEN_EFFECTS = {
|
|
69
|
+
applied: ["reverted"],
|
|
70
|
+
not_applied: ["applied", "reverted", "notReversible"],
|
|
71
|
+
compensated: ["applied"],
|
|
72
|
+
partial: [],
|
|
73
|
+
unknown: [],
|
|
74
|
+
};
|
|
75
|
+
function checkEffects(kind, lists) {
|
|
76
|
+
for (const field of FORBIDDEN_EFFECTS[kind]) {
|
|
77
|
+
if (lists[field].length > 0)
|
|
78
|
+
throw invalid(`a ${kind} outcome cannot list ${field} effects`);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function checkEffectKey(kind, retry, effectKey) {
|
|
82
|
+
// Without a key, a same-key retry of a write that may have taken effect could take effect twice. A not_applied
|
|
83
|
+
// write took no effect, so retrying it is safe with or without one.
|
|
84
|
+
if (retry === "same_key" && effectKey === undefined && (kind === "partial" || kind === "unknown")) {
|
|
85
|
+
throw invalid(`a ${kind} outcome can use retry "same_key" only with an effectKey`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
function checkKindAndRetry(kind, retry) {
|
|
89
|
+
if (!OUTCOME_KINDS.includes(kind))
|
|
90
|
+
throw invalid(`unknown outcome kind ${JSON.stringify(kind)}`);
|
|
91
|
+
const known = kind;
|
|
92
|
+
// Only a missing retry takes the default; `null` from a JSON caller fails the check below like any other value.
|
|
93
|
+
const chosen = retry === undefined ? DEFAULT_RETRY[known] : retry;
|
|
94
|
+
if (!ALLOWED_RETRIES[known].includes(chosen)) {
|
|
95
|
+
throw invalid(`a ${known} outcome cannot use retry ${JSON.stringify(chosen)}`);
|
|
96
|
+
}
|
|
97
|
+
return chosen;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Builds a write outcome, filling in the defaults and checking every field. The result is frozen.
|
|
101
|
+
*
|
|
102
|
+
* Throws a `SafetyError`, code `invalid_outcome`, for:
|
|
103
|
+
* - an unknown kind, or a retry rule the kind doesn't allow;
|
|
104
|
+
* - an empty `operation` or `next`, or an `operation` with leading or trailing spaces;
|
|
105
|
+
* - a blank effect or optional text field;
|
|
106
|
+
* - a `reason` that isn't upper snake case of at most 63 characters;
|
|
107
|
+
* - effects the kind contradicts: any effect on `not_applied`, `reverted` on `applied`, `applied` on `compensated`;
|
|
108
|
+
* - a `partial` or `unknown` outcome that allows a `same_key` retry without an `effectKey`.
|
|
109
|
+
*/
|
|
110
|
+
export function writeOutcome(init) {
|
|
111
|
+
const retry = checkKindAndRetry(init.kind, init.retry);
|
|
112
|
+
requireText(init.operation, "operation");
|
|
113
|
+
if (init.operation !== init.operation.trim())
|
|
114
|
+
throw invalid("a write outcome's operation must not start or end with spaces");
|
|
115
|
+
requireText(init.next, "next");
|
|
116
|
+
for (const field of ["effectKey", "currentState", "avoid"])
|
|
117
|
+
requireOptionalText(init[field], field);
|
|
118
|
+
checkReason(init.reason);
|
|
119
|
+
checkEffectKey(init.kind, retry, init.effectKey);
|
|
120
|
+
const lists = {
|
|
121
|
+
applied: effectList(init.applied, "applied"),
|
|
122
|
+
reverted: effectList(init.reverted, "reverted"),
|
|
123
|
+
notReversible: effectList(init.notReversible, "notReversible"),
|
|
124
|
+
};
|
|
125
|
+
checkEffects(init.kind, lists);
|
|
126
|
+
const outcome = {
|
|
127
|
+
kind: init.kind,
|
|
128
|
+
operation: init.operation,
|
|
129
|
+
...(init.effectKey === undefined ? {} : { effectKey: init.effectKey }),
|
|
130
|
+
...lists,
|
|
131
|
+
...(init.currentState === undefined ? {} : { currentState: init.currentState }),
|
|
132
|
+
retry,
|
|
133
|
+
next: init.next,
|
|
134
|
+
...(init.avoid === undefined ? {} : { avoid: init.avoid }),
|
|
135
|
+
...(init.reason === undefined ? {} : { reason: init.reason }),
|
|
136
|
+
};
|
|
137
|
+
// checkKindAndRetry has shown that `retry` is one the kind allows, which the spread above can't carry in its type.
|
|
138
|
+
return Object.freeze(outcome);
|
|
139
|
+
}
|
|
140
|
+
//# sourceMappingURL=outcome.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"outcome.js","sourceRoot":"","sources":["../src/outcome.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAoE1C,+DAA+D;AAC/D,MAAM,CAAC,MAAM,aAAa,GAA2B,MAAM,CAAC,MAAM,CAAC;IACjE,SAAS;IACT,aAAa;IACb,aAAa;IACb,SAAS;IACT,SAAS;CACV,CAAC,CAAC;AAEH;;;GAGG;AACH,MAAM,CAAC,MAAM,aAAa,GAAqD,MAAM,CAAC,MAAM,CAAC;IAC3F,OAAO,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AC,IAAI;QACf,GAAG,CAAC,IAAI,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC;QAC1D,GAAG,CAAC,IAAI,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC;KAC9D,CAAC;IACF,mHAAmH;IACnH,OAAO,MAAM,CAAC,MAAM,CAAC,OAAO,CAAiB,CAAC;AAChD,CAAC","sourcesContent":["/**\n * The five write outcomes: what a tool that changes the world reports, so the harness can act on it and the model can\n * read it. Each kind allows only the retry rules that are safe for it, and `unknown` never allows a fresh operation,\n * because the first attempt may still have taken effect (close-sdk-gaps SG3).\n */\nimport { SafetyError } from \"./errors.js\";\n\n/**\n * What a write did. `applied`: it took effect. `not_applied`: it was rejected before any effect. `compensated`: it\n * took effect and was then undone. `partial`: some effects hold and the rest could not be undone. `unknown`: nobody\n * knows whether it took effect, as after a timeout or a lost response.\n */\nexport type OutcomeKind = \"applied\" | \"not_applied\" | \"compensated\" | \"partial\" | \"unknown\";\n\n/**\n * When the same write may run again. `same_key`: retry with the same effect key, so it takes effect at most once.\n * `new_operation_only`: only as a new operation, if the user still wants it. `reconcile_first`: check what happened\n * before any retry. `never`: do not retry.\n */\nexport type Retry = \"same_key\" | \"new_operation_only\" | \"reconcile_first\" | \"never\";\n\n/** The retry rules each outcome kind allows. */\nexport interface AllowedRetry {\n applied: \"never\";\n not_applied: \"same_key\" | \"new_operation_only\" | \"never\";\n compensated: \"new_operation_only\" | \"never\";\n partial: \"same_key\" | \"reconcile_first\" | \"never\";\n unknown: \"same_key\" | \"reconcile_first\" | \"never\";\n}\n\n/** The fields every write outcome carries, whatever its kind. */\nexport interface OutcomeFields {\n /** The tool or business operation, such as `send_email`. */\n readonly operation: string;\n /** The key that makes a retry of this write take effect at most once. */\n readonly effectKey?: string;\n /** Effects that hold now. */\n readonly applied: readonly string[];\n /** Effects that were undone. */\n readonly reverted: readonly string[];\n /** Effects that happened and cannot be undone, such as \"email delivered 14:02\". */\n readonly notReversible: readonly string[];\n /** One line about the current state that the model can trust. */\n readonly currentState?: string;\n /** What the model should do next. */\n readonly next: string;\n /** What the model must not do, beyond what the kind already rules out. */\n readonly avoid?: string;\n /** A stable code for the cause, in upper snake case and at most 63 characters, such as `CARD_DECLINED`. */\n readonly reason?: string;\n}\n\n/** A write outcome of one kind, whose `retry` is one of the rules that kind allows. */\nexport type WriteOutcomeOf<K extends OutcomeKind> = OutcomeFields & {\n readonly kind: K;\n readonly retry: AllowedRetry[K];\n};\n\n/** What a write reports: one of the five kinds, with its retry rule and what the model should do next. */\nexport type WriteOutcome = { [K in OutcomeKind]: WriteOutcomeOf<K> }[OutcomeKind];\n\n/** The fields you can leave out of a write outcome, because `writeOutcome()` fills them in. */\ntype Defaulted = \"applied\" | \"reverted\" | \"notReversible\";\n\n/**\n * The input to `writeOutcome()`. `retry` defaults to the kind's rule in `DEFAULT_RETRY`, and the three effect lists\n * default to empty.\n */\nexport type WriteOutcomeInit = {\n [K in OutcomeKind]: Omit<OutcomeFields, Defaulted> &\n Partial<Pick<OutcomeFields, Defaulted>> & { readonly kind: K; readonly retry?: AllowedRetry[K] };\n}[OutcomeKind];\n\n/** The five outcome kinds, in the order the docs list them. */\nexport const OUTCOME_KINDS: readonly OutcomeKind[] = Object.freeze([\n \"applied\",\n \"not_applied\",\n \"compensated\",\n \"partial\",\n \"unknown\",\n]);\n\n/**\n * The retry rule each kind gets when the tool sets none: a rejected write may run again with the same key, an undone\n * one only as a new operation, a partial one goes to a person, and an unknown one is checked first.\n */\nexport const DEFAULT_RETRY: { readonly [K in OutcomeKind]: AllowedRetry[K] } = Object.freeze({\n applied: \"never\",\n not_applied: \"same_key\",\n compensated: \"new_operation_only\",\n partial: \"never\",\n unknown: \"reconcile_first\",\n});\n\n/** The retry rules each kind allows, as `AllowedRetry` lists them. */\nexport const ALLOWED_RETRIES: { readonly [K in OutcomeKind]: readonly AllowedRetry[K][] } = Object.freeze({\n applied: Object.freeze([\"never\"] as const),\n not_applied: Object.freeze([\"same_key\", \"new_operation_only\", \"never\"] as const),\n compensated: Object.freeze([\"new_operation_only\", \"never\"] as const),\n partial: Object.freeze([\"same_key\", \"reconcile_first\", \"never\"] as const),\n unknown: Object.freeze([\"same_key\", \"reconcile_first\", \"never\"] as const),\n});\n\n// AIP-193's rule for `reason`: upper snake case, no leading digit or underscore, no trailing underscore.\nconst REASON = /^[A-Z][A-Z0-9_]+[A-Z0-9]$/;\nconst MAX_REASON_LENGTH = 63;\n\nfunction invalid(message: string): SafetyError {\n return new SafetyError(\"invalid_outcome\", message);\n}\n\nfunction requireText(value: unknown, field: string): void {\n if (typeof value !== \"string\" || value.trim() === \"\") throw invalid(`a write outcome's ${field} must be non-empty`);\n}\n\nfunction requireOptionalText(value: unknown, field: string): void {\n // A blank value would render as an empty sentence, such as \"Current state: .\", so it must be left out instead.\n if (value !== undefined && (typeof value !== \"string\" || value.trim() === \"\")) {\n throw invalid(`a write outcome's ${field} must be non-empty when it is set`);\n }\n}\n\nfunction effectList(value: unknown, field: string): readonly string[] {\n if (value === undefined) return Object.freeze([]);\n if (!Array.isArray(value) || !value.every((item) => typeof item === \"string\" && item.trim() !== \"\")) {\n throw invalid(`a write outcome's ${field} must be a list of non-empty strings`);\n }\n return Object.freeze([...value]);\n}\n\nfunction checkReason(reason: unknown): void {\n if (reason === undefined) return;\n if (typeof reason !== \"string\" || reason.length > MAX_REASON_LENGTH || !REASON.test(reason)) {\n throw invalid(\n `a write outcome's reason must be upper snake case and at most ${MAX_REASON_LENGTH} characters, ` +\n `got ${JSON.stringify(reason)}`,\n );\n }\n}\n\n// The effect lists each kind can't hold, because the kind's own sentence would contradict them: a write that changed\n// nothing has no effects, one that took effect undid nothing, and one that was undone holds none of its effects.\nconst FORBIDDEN_EFFECTS: { readonly [K in OutcomeKind]: readonly Defaulted[] } = {\n applied: [\"reverted\"],\n not_applied: [\"applied\", \"reverted\", \"notReversible\"],\n compensated: [\"applied\"],\n partial: [],\n unknown: [],\n};\n\nfunction checkEffects(kind: OutcomeKind, lists: Readonly<Record<Defaulted, readonly string[]>>): void {\n for (const field of FORBIDDEN_EFFECTS[kind]) {\n if (lists[field].length > 0) throw invalid(`a ${kind} outcome cannot list ${field} effects`);\n }\n}\n\nfunction checkEffectKey(kind: OutcomeKind, retry: Retry, effectKey: unknown): void {\n // Without a key, a same-key retry of a write that may have taken effect could take effect twice. A not_applied\n // write took no effect, so retrying it is safe with or without one.\n if (retry === \"same_key\" && effectKey === undefined && (kind === \"partial\" || kind === \"unknown\")) {\n throw invalid(`a ${kind} outcome can use retry \"same_key\" only with an effectKey`);\n }\n}\n\nfunction checkKindAndRetry(kind: unknown, retry: unknown): Retry {\n if (!OUTCOME_KINDS.includes(kind as OutcomeKind)) throw invalid(`unknown outcome kind ${JSON.stringify(kind)}`);\n const known = kind as OutcomeKind;\n // Only a missing retry takes the default; `null` from a JSON caller fails the check below like any other value.\n const chosen = retry === undefined ? DEFAULT_RETRY[known] : retry;\n if (!(ALLOWED_RETRIES[known] as readonly unknown[]).includes(chosen)) {\n throw invalid(`a ${known} outcome cannot use retry ${JSON.stringify(chosen)}`);\n }\n return chosen as Retry;\n}\n\n/**\n * Builds a write outcome, filling in the defaults and checking every field. The result is frozen.\n *\n * Throws a `SafetyError`, code `invalid_outcome`, for:\n * - an unknown kind, or a retry rule the kind doesn't allow;\n * - an empty `operation` or `next`, or an `operation` with leading or trailing spaces;\n * - a blank effect or optional text field;\n * - a `reason` that isn't upper snake case of at most 63 characters;\n * - effects the kind contradicts: any effect on `not_applied`, `reverted` on `applied`, `applied` on `compensated`;\n * - a `partial` or `unknown` outcome that allows a `same_key` retry without an `effectKey`.\n */\nexport function writeOutcome(init: WriteOutcomeInit): WriteOutcome {\n const retry = checkKindAndRetry(init.kind, init.retry);\n requireText(init.operation, \"operation\");\n if (init.operation !== init.operation.trim())\n throw invalid(\"a write outcome's operation must not start or end with spaces\");\n requireText(init.next, \"next\");\n for (const field of [\"effectKey\", \"currentState\", \"avoid\"] as const) requireOptionalText(init[field], field);\n checkReason(init.reason);\n checkEffectKey(init.kind, retry, init.effectKey);\n const lists = {\n applied: effectList(init.applied, \"applied\"),\n reverted: effectList(init.reverted, \"reverted\"),\n notReversible: effectList(init.notReversible, \"notReversible\"),\n };\n checkEffects(init.kind, lists);\n const outcome = {\n kind: init.kind,\n operation: init.operation,\n ...(init.effectKey === undefined ? {} : { effectKey: init.effectKey }),\n ...lists,\n ...(init.currentState === undefined ? {} : { currentState: init.currentState }),\n retry,\n next: init.next,\n ...(init.avoid === undefined ? {} : { avoid: init.avoid }),\n ...(init.reason === undefined ? {} : { reason: init.reason }),\n };\n // checkKindAndRetry has shown that `retry` is one the kind allows, which the spread above can't carry in its type.\n return Object.freeze(outcome) as WriteOutcome;\n}\n"]}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `PendingStore`: where an agent keeps its signed pending requests between a pause and its resume, keyed by the tool
|
|
3
|
+
* call's id. A record is taken, not read, when the call resumes, so one approval runs its call at most once.
|
|
4
|
+
*/
|
|
5
|
+
import type { SignedPendingRequest } from "./pending.js";
|
|
6
|
+
/**
|
|
7
|
+
* Holds signed pending requests by call id. A store may live anywhere, even where others can write, because every
|
|
8
|
+
* record is verified against its signature before it counts. On a serverless host, use storage that outlives the
|
|
9
|
+
* isolate or function, such as Durable Object storage.
|
|
10
|
+
*
|
|
11
|
+
* `take()` must remove and return the record in one atomic step, or two concurrent resumes of one approval could
|
|
12
|
+
* both receive it and both run the call. Durable Object storage gives that within one object; elsewhere use an atomic
|
|
13
|
+
* primitive, such as Redis `GETDEL` or SQL `DELETE ... RETURNING`, never a read followed by a delete.
|
|
14
|
+
*
|
|
15
|
+
* A store is keyed by call id alone, so give each conversation its own store, or a Durable Object per chat, unless
|
|
16
|
+
* your model's call ids are unique across every conversation that shares it. Two pauses with one id replace each other,
|
|
17
|
+
* and the first one's approval then fails closed.
|
|
18
|
+
*
|
|
19
|
+
* A record is taken whenever its call comes back approved, even when the check then fails, so a forged approval uses
|
|
20
|
+
* up the real one and the model has to ask again. A call the person denies, or never answers, is never taken: expire
|
|
21
|
+
* records after a while, as `memoryPendingStore()` does, so the store doesn't grow without bound and the keys that
|
|
22
|
+
* signed old records can be pruned.
|
|
23
|
+
*/
|
|
24
|
+
export interface PendingStore {
|
|
25
|
+
/** Stores `request` under its `callId`, replacing any earlier request for that call. */
|
|
26
|
+
put(request: SignedPendingRequest): Promise<void>;
|
|
27
|
+
/** Removes and returns the request for `callId`, or `undefined` if there is none. It must do both atomically. */
|
|
28
|
+
take(callId: string): Promise<SignedPendingRequest | undefined>;
|
|
29
|
+
}
|
|
30
|
+
/** The options of `memoryPendingStore()`. */
|
|
31
|
+
export interface MemoryPendingStoreOptions {
|
|
32
|
+
/**
|
|
33
|
+
* How long a request stays in the store, in milliseconds, from when it was put. An older request is dropped, and
|
|
34
|
+
* an approval that arrives after that fails closed. Defaults to 24 hours.
|
|
35
|
+
*/
|
|
36
|
+
readonly maxAgeMs?: number;
|
|
37
|
+
/** Returns the current time in milliseconds. Defaults to `Date.now`. */
|
|
38
|
+
readonly now?: () => number;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* A `PendingStore` in this process's memory, for tests and single-process hosts. It stores a copy of each request and
|
|
42
|
+
* hands back a copy, so changing a request object outside the store never changes what the store holds. It drops each
|
|
43
|
+
* request `maxAgeMs` after it was put, so pauses nobody approves don't pile up.
|
|
44
|
+
*/
|
|
45
|
+
export declare function memoryPendingStore(options?: MemoryPendingStoreOptions): PendingStore;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
2
|
+
/**
|
|
3
|
+
* A `PendingStore` in this process's memory, for tests and single-process hosts. It stores a copy of each request and
|
|
4
|
+
* hands back a copy, so changing a request object outside the store never changes what the store holds. It drops each
|
|
5
|
+
* request `maxAgeMs` after it was put, so pauses nobody approves don't pile up.
|
|
6
|
+
*/
|
|
7
|
+
export function memoryPendingStore(options = {}) {
|
|
8
|
+
const maxAgeMs = options.maxAgeMs ?? DAY_MS;
|
|
9
|
+
const now = options.now ?? Date.now;
|
|
10
|
+
// In insertion order, which is also expiry order, because `put` re-inserts a replaced request at the end.
|
|
11
|
+
const requests = new Map();
|
|
12
|
+
const sweep = (time) => {
|
|
13
|
+
for (const [callId, entry] of requests) {
|
|
14
|
+
if (entry.expires > time)
|
|
15
|
+
break;
|
|
16
|
+
requests.delete(callId);
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
return {
|
|
20
|
+
async put(request) {
|
|
21
|
+
const time = now();
|
|
22
|
+
sweep(time);
|
|
23
|
+
requests.delete(request.callId);
|
|
24
|
+
requests.set(request.callId, { request: structuredClone(request), expires: time + maxAgeMs });
|
|
25
|
+
},
|
|
26
|
+
async take(callId) {
|
|
27
|
+
const time = now();
|
|
28
|
+
sweep(time);
|
|
29
|
+
const entry = requests.get(callId);
|
|
30
|
+
requests.delete(callId);
|
|
31
|
+
// Checked again here, because a clock that steps back can leave an expired entry behind a live one.
|
|
32
|
+
return entry !== undefined && entry.expires > time ? entry.request : undefined;
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
//# sourceMappingURL=pending-store.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pending-store.js","sourceRoot":"","sources":["../src/pending-store.ts"],"names":[],"mappings":"AA0CA,MAAM,MAAM,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAEnC;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAAC,OAAO,GAA8B,EAAE;IACxE,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,MAAM,CAAC;IAC5C,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC;IACpC,0GAA0G;IAC1G,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAgF,CAAC;IACzG,MAAM,KAAK,GAAG,CAAC,IAAY,EAAE,EAAE;QAC7B,KAAK,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,IAAI,QAAQ,EAAE,CAAC;YACvC,IAAI,KAAK,CAAC,OAAO,GAAG,IAAI;gBAAE,MAAM;YAChC,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAC1B,CAAC;IACH,CAAC,CAAC;IACF,OAAO;QACL,KAAK,CAAC,GAAG,CAAC,OAAO;YACf,MAAM,IAAI,GAAG,GAAG,EAAE,CAAC;YACnB,KAAK,CAAC,IAAI,CAAC,CAAC;YACZ,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;YAChC,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,eAAe,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,IAAI,GAAG,QAAQ,EAAE,CAAC,CAAC;QAChG,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,MAAM;YACf,MAAM,IAAI,GAAG,GAAG,EAAE,CAAC;YACnB,KAAK,CAAC,IAAI,CAAC,CAAC;YACZ,MAAM,KAAK,GAAG,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;YACnC,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YACxB,oGAAoG;YACpG,OAAO,KAAK,KAAK,SAAS,IAAI,KAAK,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;QACjF,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * `PendingStore`: where an agent keeps its signed pending requests between a pause and its resume, keyed by the tool\n * call's id. A record is taken, not read, when the call resumes, so one approval runs its call at most once.\n */\nimport type { SignedPendingRequest } from \"./pending.js\";\n\n/**\n * Holds signed pending requests by call id. A store may live anywhere, even where others can write, because every\n * record is verified against its signature before it counts. On a serverless host, use storage that outlives the\n * isolate or function, such as Durable Object storage.\n *\n * `take()` must remove and return the record in one atomic step, or two concurrent resumes of one approval could\n * both receive it and both run the call. Durable Object storage gives that within one object; elsewhere use an atomic\n * primitive, such as Redis `GETDEL` or SQL `DELETE ... RETURNING`, never a read followed by a delete.\n *\n * A store is keyed by call id alone, so give each conversation its own store, or a Durable Object per chat, unless\n * your model's call ids are unique across every conversation that shares it. Two pauses with one id replace each other,\n * and the first one's approval then fails closed.\n *\n * A record is taken whenever its call comes back approved, even when the check then fails, so a forged approval uses\n * up the real one and the model has to ask again. A call the person denies, or never answers, is never taken: expire\n * records after a while, as `memoryPendingStore()` does, so the store doesn't grow without bound and the keys that\n * signed old records can be pruned.\n */\nexport interface PendingStore {\n /** Stores `request` under its `callId`, replacing any earlier request for that call. */\n put(request: SignedPendingRequest): Promise<void>;\n /** Removes and returns the request for `callId`, or `undefined` if there is none. It must do both atomically. */\n take(callId: string): Promise<SignedPendingRequest | undefined>;\n}\n\n/** The options of `memoryPendingStore()`. */\nexport interface MemoryPendingStoreOptions {\n /**\n * How long a request stays in the store, in milliseconds, from when it was put. An older request is dropped, and\n * an approval that arrives after that fails closed. Defaults to 24 hours.\n */\n readonly maxAgeMs?: number;\n /** Returns the current time in milliseconds. Defaults to `Date.now`. */\n readonly now?: () => number;\n}\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\n\n/**\n * A `PendingStore` in this process's memory, for tests and single-process hosts. It stores a copy of each request and\n * hands back a copy, so changing a request object outside the store never changes what the store holds. It drops each\n * request `maxAgeMs` after it was put, so pauses nobody approves don't pile up.\n */\nexport function memoryPendingStore(options: MemoryPendingStoreOptions = {}): PendingStore {\n const maxAgeMs = options.maxAgeMs ?? DAY_MS;\n const now = options.now ?? Date.now;\n // In insertion order, which is also expiry order, because `put` re-inserts a replaced request at the end.\n const requests = new Map<string, { readonly request: SignedPendingRequest; readonly expires: number }>();\n const sweep = (time: number) => {\n for (const [callId, entry] of requests) {\n if (entry.expires > time) break;\n requests.delete(callId);\n }\n };\n return {\n async put(request) {\n const time = now();\n sweep(time);\n requests.delete(request.callId);\n requests.set(request.callId, { request: structuredClone(request), expires: time + maxAgeMs });\n },\n async take(callId) {\n const time = now();\n sweep(time);\n const entry = requests.get(callId);\n requests.delete(callId);\n // Checked again here, because a clock that steps back can leave an expired entry behind a live one.\n return entry !== undefined && entry.expires > time ? entry.request : undefined;\n },\n };\n}\n"]}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import type { ApprovalSigner } from "./signer.js";
|
|
2
|
+
/**
|
|
3
|
+
* A pause waiting for a person: an approval of one tool call, or a question about it. `signature` signs `id`, `kind`,
|
|
4
|
+
* `callId`, `tool`, `inputHash` and `policyVersion` under the key `keyId` names. `question`, `reason` and `createdAt`
|
|
5
|
+
* are shown to people and aren't signed, so never let them decide anything.
|
|
6
|
+
*/
|
|
7
|
+
export interface SignedPendingRequest {
|
|
8
|
+
/** The request's own id, which a `Resolution` names. */
|
|
9
|
+
id: string;
|
|
10
|
+
/** `approval` waits for allow or deny; `clarification` waits for an answer. */
|
|
11
|
+
kind: "approval" | "clarification";
|
|
12
|
+
/** The id of the tool call that waits. */
|
|
13
|
+
callId: string;
|
|
14
|
+
/** The tool's name. */
|
|
15
|
+
tool: string;
|
|
16
|
+
/** `canonicalInputHash()` of the call's input. */
|
|
17
|
+
inputHash: string;
|
|
18
|
+
/** The version of the policy that asked for the pause, if the host versions its policy. */
|
|
19
|
+
policyVersion?: string;
|
|
20
|
+
/**
|
|
21
|
+
* A MAC of the app data the run held when it paused, such as the signed-in customer, when it held any: the signer's
|
|
22
|
+
* signature over the app's canonical JSON, under the key `keyId` names and a domain tag of its own. The request's
|
|
23
|
+
* signature covers it, so the call runs only for the caller whose app data the host passes back. It is keyed, so
|
|
24
|
+
* reading it reveals nothing about a small value such as a customer id. A request without it, such as one signed
|
|
25
|
+
* before this field existed, binds no app data.
|
|
26
|
+
*/
|
|
27
|
+
appHash?: string;
|
|
28
|
+
/** The question a clarification asks. */
|
|
29
|
+
question?: string;
|
|
30
|
+
/** Why the call needs a person, as shown to the approver. */
|
|
31
|
+
reason?: string;
|
|
32
|
+
/** The id of the key that made `signature`. */
|
|
33
|
+
keyId: string;
|
|
34
|
+
/** The signature, as base64url. */
|
|
35
|
+
signature: string;
|
|
36
|
+
/** When the request was signed, as an ISO 8601 timestamp. */
|
|
37
|
+
createdAt: string;
|
|
38
|
+
}
|
|
39
|
+
/** A person's answer to a pending request: allow or deny for an approval, an answer for a clarification. */
|
|
40
|
+
export type Resolution = {
|
|
41
|
+
requestId: string;
|
|
42
|
+
decision: "allow" | "deny";
|
|
43
|
+
reason?: string;
|
|
44
|
+
by?: string;
|
|
45
|
+
} | {
|
|
46
|
+
requestId: string;
|
|
47
|
+
answer: string;
|
|
48
|
+
by?: string;
|
|
49
|
+
};
|
|
50
|
+
/** The fields `signPending()` signs and stores, with the call's input in place of its hash. */
|
|
51
|
+
export interface PendingFields {
|
|
52
|
+
readonly kind: "approval" | "clarification";
|
|
53
|
+
readonly callId: string;
|
|
54
|
+
readonly tool: string;
|
|
55
|
+
/** The tool call's input. `signPending()` stores its `canonicalInputHash()`, never the input itself. */
|
|
56
|
+
readonly input: unknown;
|
|
57
|
+
readonly policyVersion?: string;
|
|
58
|
+
/**
|
|
59
|
+
* The caller's app data. `signPending()` signs its canonical JSON with the signer, stores the MAC as `appHash`, and
|
|
60
|
+
* never stores the data itself. Two values are the same app when their RFC 8785 canonical JSON is the same.
|
|
61
|
+
*/
|
|
62
|
+
readonly app?: unknown;
|
|
63
|
+
readonly question?: string;
|
|
64
|
+
readonly reason?: string;
|
|
65
|
+
}
|
|
66
|
+
/** Where `signPending()` takes its request id and time from. Tests pass fixed ones. */
|
|
67
|
+
export interface SignPendingOptions {
|
|
68
|
+
/** Returns a fresh request id. Defaults to `crypto.randomUUID()`. */
|
|
69
|
+
readonly generateId?: () => string;
|
|
70
|
+
/** Returns the current time. Defaults to `new Date()`. */
|
|
71
|
+
readonly now?: () => Date;
|
|
72
|
+
}
|
|
73
|
+
/** The call a host is about to run, which a pending request must match before it runs. */
|
|
74
|
+
export interface PendingCall {
|
|
75
|
+
readonly callId: string;
|
|
76
|
+
readonly tool: string;
|
|
77
|
+
readonly input: unknown;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Why `verifyResolution()` refused. `malformed`: the stored request isn't a well-formed pending request.
|
|
81
|
+
* `unknown_request`: the resolution names another request. `signature_invalid`: the signature is wrong, or its key id
|
|
82
|
+
* isn't in the ring. `call_mismatch`: the call id or tool differs from the call about to run. `input_changed`: the
|
|
83
|
+
* input differs from the one that was signed. `app_mismatch`: the request is bound to app data, and the host passed
|
|
84
|
+
* none or other data. `resolution_mismatch`: the resolution doesn't fit the request's kind.
|
|
85
|
+
*/
|
|
86
|
+
export type RejectionCause = "malformed" | "unknown_request" | "signature_invalid" | "call_mismatch" | "input_changed" | "app_mismatch" | "resolution_mismatch";
|
|
87
|
+
/** What `verifyResolution()` returns: the resolution, once every check passed, or why it refused. */
|
|
88
|
+
export type ResolutionCheck = {
|
|
89
|
+
readonly ok: true;
|
|
90
|
+
readonly resolution: Resolution;
|
|
91
|
+
} | {
|
|
92
|
+
readonly ok: false;
|
|
93
|
+
readonly cause: RejectionCause;
|
|
94
|
+
};
|
|
95
|
+
/** The options of `verifyResolution()`. */
|
|
96
|
+
export interface VerifyResolutionOptions {
|
|
97
|
+
/** A signer that holds the key the request names. */
|
|
98
|
+
readonly signer: ApprovalSigner;
|
|
99
|
+
/** The call about to run, as the host has it now, not as the pending request records it. */
|
|
100
|
+
readonly call: PendingCall;
|
|
101
|
+
/**
|
|
102
|
+
* The app data the host has now. A request that is bound to app data is refused with `app_mismatch` unless the
|
|
103
|
+
* signer, under the request's own key, verifies this data's canonical JSON against the bound MAC, so leaving it
|
|
104
|
+
* out refuses a bound request. A request that binds none ignores it.
|
|
105
|
+
*/
|
|
106
|
+
readonly app?: unknown;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* The bytes a pending request's signature covers: a JSON array of a fixed tag, then the request id, kind, call id,
|
|
110
|
+
* tool name, input hash and policy version, in that order, with `null` for an absent policy version. A request bound
|
|
111
|
+
* to app data signs a second tag and adds the app hash last. Every field is a well-formed string, so `JSON.stringify`
|
|
112
|
+
* writes the same bytes on every runtime.
|
|
113
|
+
*/
|
|
114
|
+
export declare function pendingPayload(fields: Pick<SignedPendingRequest, "id" | "kind" | "callId" | "tool" | "inputHash" | "policyVersion" | "appHash">): Uint8Array;
|
|
115
|
+
/** The bytes the signer signs to MAC an app: a tag, then the app's canonical JSON. Throws `invalid_input` for an app with no canonical form. */
|
|
116
|
+
export declare function appPayload(app: unknown): Uint8Array;
|
|
117
|
+
/**
|
|
118
|
+
* Signs a pending request for a tool call. It hashes the input with `canonicalInputHash()`, signs the fields
|
|
119
|
+
* `pendingPayload()` lists with the signer's current key, and returns the request to store. The input itself isn't stored.
|
|
120
|
+
*
|
|
121
|
+
* Throws a `SafetyError`, code `invalid_pending`, for a blank or malformed field, and code `invalid_input` for an
|
|
122
|
+
* input with no canonical JSON form.
|
|
123
|
+
*/
|
|
124
|
+
export declare function signPending(fields: PendingFields, signer: ApprovalSigner, options?: SignPendingOptions): Promise<SignedPendingRequest>;
|
|
125
|
+
/**
|
|
126
|
+
* Checks a resolution against its stored pending request before the call runs, failing closed. It accepts only when
|
|
127
|
+
* the request is well formed, the resolution names it, the signature verifies under a key the signer holds, a request
|
|
128
|
+
* bound to app data gets the same app data back, the call id and tool match the call about to run, that call's input
|
|
129
|
+
* hashes to the signed hash, and the resolution fits the request's kind. The app is checked right after the
|
|
130
|
+
* signature, so a host resuming as another caller is told so whatever else is wrong with the request. Otherwise it
|
|
131
|
+
* returns `ok: false` with the first cause it found, and never throws for bad input.
|
|
132
|
+
*
|
|
133
|
+
* A passing check says the request is authentic and unchanged. It doesn't say current policy still allows the call:
|
|
134
|
+
* check that separately, just before the call runs.
|
|
135
|
+
*/
|
|
136
|
+
export declare function verifyResolution(pending: unknown, resolution: Resolution, options: VerifyResolutionOptions): Promise<ResolutionCheck>;
|
|
137
|
+
/**
|
|
138
|
+
* Runs current policy for an approved call just before it runs, after its pending request has verified. Resolve to
|
|
139
|
+
* `"allow"` to let the call run, or to `{ deny }` with a reason the model reads, so a policy that changed since the
|
|
140
|
+
* pause can still stop the call.
|
|
141
|
+
*/
|
|
142
|
+
export type Recheck = (pending: SignedPendingRequest, input: unknown) => Promise<"allow" | {
|
|
143
|
+
deny: string;
|
|
144
|
+
}>;
|
package/dist/pending.js
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The signed pending request: what an agent stores when a tool call waits for a person, and what it checks before the
|
|
3
|
+
* call runs. The signature covers D5's six fields in D5's order (request id, kind, call id, tool name, input hash and
|
|
4
|
+
* the optional policy version) and, for a request bound to a caller, a seventh, the app MAC, so a stored pause whose
|
|
5
|
+
* call, tool, input or caller changed no longer verifies. The shapes match build-sdk.md §3.3 field for field, because
|
|
6
|
+
* our SDK re-exports them.
|
|
7
|
+
*/
|
|
8
|
+
import { constantTimeEqual } from "./bytes.js";
|
|
9
|
+
import { SafetyError } from "./errors.js";
|
|
10
|
+
import { canonicalInputHash, canonicalJson } from "./hash.js";
|
|
11
|
+
// Ties a signature to this record and its layout, so it can't verify as some other signed record of this package. A
|
|
12
|
+
// request with no app MAC keeps the first layout, so every request signed before the MAC existed still verifies; a
|
|
13
|
+
// request with one signs a second layout that adds it, which a reader of the first layout refuses.
|
|
14
|
+
const PAYLOAD_TAG = "buildanagent.pending.v1";
|
|
15
|
+
const APP_PAYLOAD_TAG = "buildanagent.pending.v2";
|
|
16
|
+
// Ties an app MAC to this use, so the signer's signature over an app can't verify as a pending request or any other
|
|
17
|
+
// payload it signs.
|
|
18
|
+
const APP_MAC_TAG = "buildanagent.app.v1";
|
|
19
|
+
const KINDS = ["approval", "clarification"];
|
|
20
|
+
const INPUT_HASH = /^[0-9a-f]{64}$/;
|
|
21
|
+
const ENCODER = new TextEncoder();
|
|
22
|
+
function isText(value) {
|
|
23
|
+
return typeof value === "string" && value !== "" && value.isWellFormed();
|
|
24
|
+
}
|
|
25
|
+
function isOptionalText(value) {
|
|
26
|
+
return value === undefined || isText(value);
|
|
27
|
+
}
|
|
28
|
+
/** True when `value` has the shape of a pending request; a store's record is untrusted until this and the signature pass. */
|
|
29
|
+
function isWellFormed(value) {
|
|
30
|
+
if (typeof value !== "object" || value === null)
|
|
31
|
+
return false;
|
|
32
|
+
const p = value;
|
|
33
|
+
return ([p.id, p.callId, p.tool, p.keyId, p.signature, p.createdAt].every(isText) &&
|
|
34
|
+
KINDS.includes(p.kind) &&
|
|
35
|
+
typeof p.inputHash === "string" &&
|
|
36
|
+
INPUT_HASH.test(p.inputHash) &&
|
|
37
|
+
[p.policyVersion, p.question, p.reason].every(isOptionalText) &&
|
|
38
|
+
(p.appHash === undefined || isText(p.appHash)));
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The bytes a pending request's signature covers: a JSON array of a fixed tag, then the request id, kind, call id,
|
|
42
|
+
* tool name, input hash and policy version, in that order, with `null` for an absent policy version. A request bound
|
|
43
|
+
* to app data signs a second tag and adds the app hash last. Every field is a well-formed string, so `JSON.stringify`
|
|
44
|
+
* writes the same bytes on every runtime.
|
|
45
|
+
*/
|
|
46
|
+
export function pendingPayload(fields) {
|
|
47
|
+
const { id, kind, callId, tool, inputHash, policyVersion, appHash } = fields;
|
|
48
|
+
const head = [id, kind, callId, tool, inputHash, policyVersion ?? null];
|
|
49
|
+
const payload = appHash === undefined ? [PAYLOAD_TAG, ...head] : [APP_PAYLOAD_TAG, ...head, appHash];
|
|
50
|
+
return ENCODER.encode(JSON.stringify(payload));
|
|
51
|
+
}
|
|
52
|
+
function checkFields(fields, id) {
|
|
53
|
+
const bad = (what) => new SafetyError("invalid_pending", `a pending request's ${what}`);
|
|
54
|
+
if (!isText(id))
|
|
55
|
+
throw bad("id must be a non-empty, well-formed string");
|
|
56
|
+
if (!KINDS.includes(fields.kind))
|
|
57
|
+
throw bad(`kind must be "approval" or "clarification"`);
|
|
58
|
+
for (const field of ["callId", "tool"]) {
|
|
59
|
+
if (!isText(fields[field]))
|
|
60
|
+
throw bad(`${field} must be a non-empty, well-formed string`);
|
|
61
|
+
}
|
|
62
|
+
for (const field of ["policyVersion", "question", "reason"]) {
|
|
63
|
+
if (!isOptionalText(fields[field]))
|
|
64
|
+
throw bad(`${field} must be a non-empty, well-formed string when it is set`);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/** The bytes the signer signs to MAC an app: a tag, then the app's canonical JSON. Throws `invalid_input` for an app with no canonical form. */
|
|
68
|
+
export function appPayload(app) {
|
|
69
|
+
return ENCODER.encode(JSON.stringify([APP_MAC_TAG, canonicalJson(app)]));
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Signs a pending request for a tool call. It hashes the input with `canonicalInputHash()`, signs the fields
|
|
73
|
+
* `pendingPayload()` lists with the signer's current key, and returns the request to store. The input itself isn't stored.
|
|
74
|
+
*
|
|
75
|
+
* Throws a `SafetyError`, code `invalid_pending`, for a blank or malformed field, and code `invalid_input` for an
|
|
76
|
+
* input with no canonical JSON form.
|
|
77
|
+
*/
|
|
78
|
+
export async function signPending(fields, signer, options = {}) {
|
|
79
|
+
const id = (options.generateId ?? (() => crypto.randomUUID()))();
|
|
80
|
+
checkFields(fields, id);
|
|
81
|
+
const inputHash = await canonicalInputHash(fields.input);
|
|
82
|
+
const signed = { id, kind: fields.kind, callId: fields.callId, tool: fields.tool, inputHash };
|
|
83
|
+
const withPolicy = fields.policyVersion === undefined ? signed : { ...signed, policyVersion: fields.policyVersion };
|
|
84
|
+
const appHash = fields.app === undefined ? undefined : await signer.sign(appPayload(fields.app));
|
|
85
|
+
const bound = appHash === undefined ? withPolicy : { ...withPolicy, appHash };
|
|
86
|
+
const signature = await signer.sign(pendingPayload(bound));
|
|
87
|
+
return {
|
|
88
|
+
...bound,
|
|
89
|
+
...(fields.question === undefined ? {} : { question: fields.question }),
|
|
90
|
+
...(fields.reason === undefined ? {} : { reason: fields.reason }),
|
|
91
|
+
keyId: signer.keyId,
|
|
92
|
+
signature,
|
|
93
|
+
createdAt: (options.now ?? (() => new Date()))().toISOString(),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
function fitsKind(pending, resolution) {
|
|
97
|
+
if (pending.kind === "approval") {
|
|
98
|
+
return "decision" in resolution && (resolution.decision === "allow" || resolution.decision === "deny");
|
|
99
|
+
}
|
|
100
|
+
return "answer" in resolution && typeof resolution.answer === "string";
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* A request bound to app data needs the host's app to verify under the request's own key; a request that binds none
|
|
104
|
+
* accepts any. An app with no canonical form can't match, and the check never throws.
|
|
105
|
+
*/
|
|
106
|
+
async function appMatches(pending, app, signer) {
|
|
107
|
+
if (pending.appHash === undefined)
|
|
108
|
+
return true;
|
|
109
|
+
if (app === undefined)
|
|
110
|
+
return false;
|
|
111
|
+
try {
|
|
112
|
+
return await signer.verify(pending.keyId, appPayload(app), pending.appHash);
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
return false;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
async function inputMatches(pending, input) {
|
|
119
|
+
try {
|
|
120
|
+
return constantTimeEqual(ENCODER.encode(await canonicalInputHash(input)), ENCODER.encode(pending.inputHash));
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
// An input with no canonical form can't be the one that was signed, which had one.
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Checks a resolution against its stored pending request before the call runs, failing closed. It accepts only when
|
|
129
|
+
* the request is well formed, the resolution names it, the signature verifies under a key the signer holds, a request
|
|
130
|
+
* bound to app data gets the same app data back, the call id and tool match the call about to run, that call's input
|
|
131
|
+
* hashes to the signed hash, and the resolution fits the request's kind. The app is checked right after the
|
|
132
|
+
* signature, so a host resuming as another caller is told so whatever else is wrong with the request. Otherwise it
|
|
133
|
+
* returns `ok: false` with the first cause it found, and never throws for bad input.
|
|
134
|
+
*
|
|
135
|
+
* A passing check says the request is authentic and unchanged. It doesn't say current policy still allows the call:
|
|
136
|
+
* check that separately, just before the call runs.
|
|
137
|
+
*/
|
|
138
|
+
export async function verifyResolution(pending, resolution, options) {
|
|
139
|
+
if (!isWellFormed(pending))
|
|
140
|
+
return { ok: false, cause: "malformed" };
|
|
141
|
+
if (typeof resolution !== "object" || resolution === null || resolution.requestId !== pending.id) {
|
|
142
|
+
return { ok: false, cause: "unknown_request" };
|
|
143
|
+
}
|
|
144
|
+
// The signature comes first: until it verifies, no other field of the stored request is trusted.
|
|
145
|
+
if (!(await options.signer.verify(pending.keyId, pendingPayload(pending), pending.signature))) {
|
|
146
|
+
return { ok: false, cause: "signature_invalid" };
|
|
147
|
+
}
|
|
148
|
+
// Once the signature holds, the bound app is trusted, so it is checked before the call and the input: a request
|
|
149
|
+
// refused for any other reason would otherwise be asked again, and signed for whoever resumed it.
|
|
150
|
+
if (!(await appMatches(pending, options.app, options.signer)))
|
|
151
|
+
return { ok: false, cause: "app_mismatch" };
|
|
152
|
+
const { call } = options;
|
|
153
|
+
if (call.callId !== pending.callId || call.tool !== pending.tool)
|
|
154
|
+
return { ok: false, cause: "call_mismatch" };
|
|
155
|
+
if (!(await inputMatches(pending, call.input)))
|
|
156
|
+
return { ok: false, cause: "input_changed" };
|
|
157
|
+
if (!fitsKind(pending, resolution))
|
|
158
|
+
return { ok: false, cause: "resolution_mismatch" };
|
|
159
|
+
return { ok: true, resolution };
|
|
160
|
+
}
|
|
161
|
+
//# sourceMappingURL=pending.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pending.js","sourceRoot":"","sources":["../src/pending.ts"],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IAAI,CAAC,CAAC,MAAM,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE,cAAc,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC;QAC9F,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,mBAAmB,EAAE,CAAC;IACnD,CAAC;IACD,gHAAgH;IAChH,kGAAkG;IAClG,IAAI,CAAC,CAAC,MAAM,UAAU,CAAC,OAAO,EAAE,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;QAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,cAAc,EAAE,CAAC;IAC3G,MAAM,EAAE,IAAI,EAAE,GAAG,OAAO,CAAC;IACzB,IAAI,IAAI,CAAC,MAAM,KAAK,OAAO,CAAC,MAAM,IAAI,IAAI,CAAC,IAAI,KAAK,OAAO,CAAC,IAAI;QAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,eAAe,EAAE,CAAC;IAC/G,IAAI,CAAC,CAAC,MAAM,YAAY,CAAC,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;QAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,eAAe,EAAE,CAAC;IAC7F,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,UAAU,CAAC;QAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,qBAAqB,EAAE,CAAC;IACvF,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC;AAClC,CAAC","sourcesContent":["/**\n * The signed pending request: what an agent stores when a tool call waits for a person, and what it checks before the\n * call runs. The signature covers D5's six fields in D5's order (request id, kind, call id, tool name, input hash and\n * the optional policy version) and, for a request bound to a caller, a seventh, the app MAC, so a stored pause whose\n * call, tool, input or caller changed no longer verifies. The shapes match build-sdk.md §3.3 field for field, because\n * our SDK re-exports them.\n */\nimport { constantTimeEqual } from \"./bytes.js\";\nimport { SafetyError } from \"./errors.js\";\nimport { canonicalInputHash, canonicalJson } from \"./hash.js\";\nimport type { ApprovalSigner } from \"./signer.js\";\n\n/**\n * A pause waiting for a person: an approval of one tool call, or a question about it. `signature` signs `id`, `kind`,\n * `callId`, `tool`, `inputHash` and `policyVersion` under the key `keyId` names. `question`, `reason` and `createdAt`\n * are shown to people and aren't signed, so never let them decide anything.\n */\nexport interface SignedPendingRequest {\n /** The request's own id, which a `Resolution` names. */\n id: string;\n /** `approval` waits for allow or deny; `clarification` waits for an answer. */\n kind: \"approval\" | \"clarification\";\n /** The id of the tool call that waits. */\n callId: string;\n /** The tool's name. */\n tool: string;\n /** `canonicalInputHash()` of the call's input. */\n inputHash: string;\n /** The version of the policy that asked for the pause, if the host versions its policy. */\n policyVersion?: string;\n /**\n * A MAC of the app data the run held when it paused, such as the signed-in customer, when it held any: the signer's\n * signature over the app's canonical JSON, under the key `keyId` names and a domain tag of its own. The request's\n * signature covers it, so the call runs only for the caller whose app data the host passes back. It is keyed, so\n * reading it reveals nothing about a small value such as a customer id. A request without it, such as one signed\n * before this field existed, binds no app data.\n */\n appHash?: string;\n /** The question a clarification asks. */\n question?: string;\n /** Why the call needs a person, as shown to the approver. */\n reason?: string;\n /** The id of the key that made `signature`. */\n keyId: string;\n /** The signature, as base64url. */\n signature: string;\n /** When the request was signed, as an ISO 8601 timestamp. */\n createdAt: string;\n}\n\n/** A person's answer to a pending request: allow or deny for an approval, an answer for a clarification. */\nexport type Resolution =\n | { requestId: string; decision: \"allow\" | \"deny\"; reason?: string; by?: string }\n | { requestId: string; answer: string; by?: string };\n\n/** The fields `signPending()` signs and stores, with the call's input in place of its hash. */\nexport interface PendingFields {\n readonly kind: \"approval\" | \"clarification\";\n readonly callId: string;\n readonly tool: string;\n /** The tool call's input. `signPending()` stores its `canonicalInputHash()`, never the input itself. */\n readonly input: unknown;\n readonly policyVersion?: string;\n /**\n * The caller's app data. `signPending()` signs its canonical JSON with the signer, stores the MAC as `appHash`, and\n * never stores the data itself. Two values are the same app when their RFC 8785 canonical JSON is the same.\n */\n readonly app?: unknown;\n readonly question?: string;\n readonly reason?: string;\n}\n\n/** Where `signPending()` takes its request id and time from. Tests pass fixed ones. */\nexport interface SignPendingOptions {\n /** Returns a fresh request id. Defaults to `crypto.randomUUID()`. */\n readonly generateId?: () => string;\n /** Returns the current time. Defaults to `new Date()`. */\n readonly now?: () => Date;\n}\n\n/** The call a host is about to run, which a pending request must match before it runs. */\nexport interface PendingCall {\n readonly callId: string;\n readonly tool: string;\n readonly input: unknown;\n}\n\n/**\n * Why `verifyResolution()` refused. `malformed`: the stored request isn't a well-formed pending request.\n * `unknown_request`: the resolution names another request. `signature_invalid`: the signature is wrong, or its key id\n * isn't in the ring. `call_mismatch`: the call id or tool differs from the call about to run. `input_changed`: the\n * input differs from the one that was signed. `app_mismatch`: the request is bound to app data, and the host passed\n * none or other data. `resolution_mismatch`: the resolution doesn't fit the request's kind.\n */\nexport type RejectionCause =\n | \"malformed\"\n | \"unknown_request\"\n | \"signature_invalid\"\n | \"call_mismatch\"\n | \"input_changed\"\n | \"app_mismatch\"\n | \"resolution_mismatch\";\n\n/** What `verifyResolution()` returns: the resolution, once every check passed, or why it refused. */\nexport type ResolutionCheck =\n | { readonly ok: true; readonly resolution: Resolution }\n | { readonly ok: false; readonly cause: RejectionCause };\n\n/** The options of `verifyResolution()`. */\nexport interface VerifyResolutionOptions {\n /** A signer that holds the key the request names. */\n readonly signer: ApprovalSigner;\n /** The call about to run, as the host has it now, not as the pending request records it. */\n readonly call: PendingCall;\n /**\n * The app data the host has now. A request that is bound to app data is refused with `app_mismatch` unless the\n * signer, under the request's own key, verifies this data's canonical JSON against the bound MAC, so leaving it\n * out refuses a bound request. A request that binds none ignores it.\n */\n readonly app?: unknown;\n}\n\n// Ties a signature to this record and its layout, so it can't verify as some other signed record of this package. A\n// request with no app MAC keeps the first layout, so every request signed before the MAC existed still verifies; a\n// request with one signs a second layout that adds it, which a reader of the first layout refuses.\nconst PAYLOAD_TAG = \"buildanagent.pending.v1\";\nconst APP_PAYLOAD_TAG = \"buildanagent.pending.v2\";\n// Ties an app MAC to this use, so the signer's signature over an app can't verify as a pending request or any other\n// payload it signs.\nconst APP_MAC_TAG = \"buildanagent.app.v1\";\nconst KINDS: readonly string[] = [\"approval\", \"clarification\"];\nconst INPUT_HASH = /^[0-9a-f]{64}$/;\nconst ENCODER = new TextEncoder();\n\nfunction isText(value: unknown): value is string {\n return typeof value === \"string\" && value !== \"\" && value.isWellFormed();\n}\n\nfunction isOptionalText(value: unknown): boolean {\n return value === undefined || isText(value);\n}\n\n/** True when `value` has the shape of a pending request; a store's record is untrusted until this and the signature pass. */\nfunction isWellFormed(value: unknown): value is SignedPendingRequest {\n if (typeof value !== \"object\" || value === null) return false;\n const p = value as Record<string, unknown>;\n return (\n [p.id, p.callId, p.tool, p.keyId, p.signature, p.createdAt].every(isText) &&\n KINDS.includes(p.kind as string) &&\n typeof p.inputHash === \"string\" &&\n INPUT_HASH.test(p.inputHash) &&\n [p.policyVersion, p.question, p.reason].every(isOptionalText) &&\n (p.appHash === undefined || isText(p.appHash))\n );\n}\n\n/**\n * The bytes a pending request's signature covers: a JSON array of a fixed tag, then the request id, kind, call id,\n * tool name, input hash and policy version, in that order, with `null` for an absent policy version. A request bound\n * to app data signs a second tag and adds the app hash last. Every field is a well-formed string, so `JSON.stringify`\n * writes the same bytes on every runtime.\n */\nexport function pendingPayload(\n fields: Pick<SignedPendingRequest, \"id\" | \"kind\" | \"callId\" | \"tool\" | \"inputHash\" | \"policyVersion\" | \"appHash\">,\n): Uint8Array {\n const { id, kind, callId, tool, inputHash, policyVersion, appHash } = fields;\n const head = [id, kind, callId, tool, inputHash, policyVersion ?? null];\n const payload = appHash === undefined ? [PAYLOAD_TAG, ...head] : [APP_PAYLOAD_TAG, ...head, appHash];\n return ENCODER.encode(JSON.stringify(payload));\n}\n\nfunction checkFields(fields: PendingFields, id: unknown): void {\n const bad = (what: string) => new SafetyError(\"invalid_pending\", `a pending request's ${what}`);\n if (!isText(id)) throw bad(\"id must be a non-empty, well-formed string\");\n if (!KINDS.includes(fields.kind)) throw bad(`kind must be \"approval\" or \"clarification\"`);\n for (const field of [\"callId\", \"tool\"] as const) {\n if (!isText(fields[field])) throw bad(`${field} must be a non-empty, well-formed string`);\n }\n for (const field of [\"policyVersion\", \"question\", \"reason\"] as const) {\n if (!isOptionalText(fields[field])) throw bad(`${field} must be a non-empty, well-formed string when it is set`);\n }\n}\n\n/** The bytes the signer signs to MAC an app: a tag, then the app's canonical JSON. Throws `invalid_input` for an app with no canonical form. */\nexport function appPayload(app: unknown): Uint8Array {\n return ENCODER.encode(JSON.stringify([APP_MAC_TAG, canonicalJson(app)]));\n}\n\n/**\n * Signs a pending request for a tool call. It hashes the input with `canonicalInputHash()`, signs the fields\n * `pendingPayload()` lists with the signer's current key, and returns the request to store. The input itself isn't stored.\n *\n * Throws a `SafetyError`, code `invalid_pending`, for a blank or malformed field, and code `invalid_input` for an\n * input with no canonical JSON form.\n */\nexport async function signPending(\n fields: PendingFields,\n signer: ApprovalSigner,\n options: SignPendingOptions = {},\n): Promise<SignedPendingRequest> {\n const id = (options.generateId ?? (() => crypto.randomUUID()))();\n checkFields(fields, id);\n const inputHash = await canonicalInputHash(fields.input);\n const signed = { id, kind: fields.kind, callId: fields.callId, tool: fields.tool, inputHash };\n const withPolicy = fields.policyVersion === undefined ? signed : { ...signed, policyVersion: fields.policyVersion };\n const appHash = fields.app === undefined ? undefined : await signer.sign(appPayload(fields.app));\n const bound = appHash === undefined ? withPolicy : { ...withPolicy, appHash };\n const signature = await signer.sign(pendingPayload(bound));\n return {\n ...bound,\n ...(fields.question === undefined ? {} : { question: fields.question }),\n ...(fields.reason === undefined ? {} : { reason: fields.reason }),\n keyId: signer.keyId,\n signature,\n createdAt: (options.now ?? (() => new Date()))().toISOString(),\n };\n}\n\nfunction fitsKind(pending: SignedPendingRequest, resolution: Resolution): boolean {\n if (pending.kind === \"approval\") {\n return \"decision\" in resolution && (resolution.decision === \"allow\" || resolution.decision === \"deny\");\n }\n return \"answer\" in resolution && typeof resolution.answer === \"string\";\n}\n\n/**\n * A request bound to app data needs the host's app to verify under the request's own key; a request that binds none\n * accepts any. An app with no canonical form can't match, and the check never throws.\n */\nasync function appMatches(pending: SignedPendingRequest, app: unknown, signer: ApprovalSigner): Promise<boolean> {\n if (pending.appHash === undefined) return true;\n if (app === undefined) return false;\n try {\n return await signer.verify(pending.keyId, appPayload(app), pending.appHash);\n } catch {\n return false;\n }\n}\n\nasync function inputMatches(pending: SignedPendingRequest, input: unknown): Promise<boolean> {\n try {\n return constantTimeEqual(ENCODER.encode(await canonicalInputHash(input)), ENCODER.encode(pending.inputHash));\n } catch {\n // An input with no canonical form can't be the one that was signed, which had one.\n return false;\n }\n}\n\n/**\n * Checks a resolution against its stored pending request before the call runs, failing closed. It accepts only when\n * the request is well formed, the resolution names it, the signature verifies under a key the signer holds, a request\n * bound to app data gets the same app data back, the call id and tool match the call about to run, that call's input\n * hashes to the signed hash, and the resolution fits the request's kind. The app is checked right after the\n * signature, so a host resuming as another caller is told so whatever else is wrong with the request. Otherwise it\n * returns `ok: false` with the first cause it found, and never throws for bad input.\n *\n * A passing check says the request is authentic and unchanged. It doesn't say current policy still allows the call:\n * check that separately, just before the call runs.\n */\nexport async function verifyResolution(\n pending: unknown,\n resolution: Resolution,\n options: VerifyResolutionOptions,\n): Promise<ResolutionCheck> {\n if (!isWellFormed(pending)) return { ok: false, cause: \"malformed\" };\n if (typeof resolution !== \"object\" || resolution === null || resolution.requestId !== pending.id) {\n return { ok: false, cause: \"unknown_request\" };\n }\n // The signature comes first: until it verifies, no other field of the stored request is trusted.\n if (!(await options.signer.verify(pending.keyId, pendingPayload(pending), pending.signature))) {\n return { ok: false, cause: \"signature_invalid\" };\n }\n // Once the signature holds, the bound app is trusted, so it is checked before the call and the input: a request\n // refused for any other reason would otherwise be asked again, and signed for whoever resumed it.\n if (!(await appMatches(pending, options.app, options.signer))) return { ok: false, cause: \"app_mismatch\" };\n const { call } = options;\n if (call.callId !== pending.callId || call.tool !== pending.tool) return { ok: false, cause: \"call_mismatch\" };\n if (!(await inputMatches(pending, call.input))) return { ok: false, cause: \"input_changed\" };\n if (!fitsKind(pending, resolution)) return { ok: false, cause: \"resolution_mismatch\" };\n return { ok: true, resolution };\n}\n\n/**\n * Runs current policy for an approved call just before it runs, after its pending request has verified. Resolve to\n * `\"allow\"` to let the call run, or to `{ deny }` with a reason the model reads, so a policy that changed since the\n * pause can still stop the call.\n */\nexport type Recheck = (pending: SignedPendingRequest, input: unknown) => Promise<\"allow\" | { deny: string }>;\n"]}
|