@buildanagent/sdk 0.1.0-alpha.0 → 0.1.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +425 -6
  2. package/dist/budget.d.ts +33 -0
  3. package/dist/budget.js +55 -0
  4. package/dist/budget.js.map +1 -0
  5. package/dist/compose.d.ts +26 -0
  6. package/dist/compose.js +157 -0
  7. package/dist/compose.js.map +1 -0
  8. package/dist/errors.d.ts +49 -0
  9. package/dist/errors.js +57 -0
  10. package/dist/errors.js.map +1 -0
  11. package/dist/events.d.ts +168 -0
  12. package/dist/events.js +32 -0
  13. package/dist/events.js.map +1 -0
  14. package/dist/freeze.d.ts +11 -0
  15. package/dist/freeze.js +42 -0
  16. package/dist/freeze.js.map +1 -0
  17. package/dist/hook-checks.d.ts +31 -0
  18. package/dist/hook-checks.js +130 -0
  19. package/dist/hook-checks.js.map +1 -0
  20. package/dist/hook-runner.d.ts +96 -0
  21. package/dist/hook-runner.js +372 -0
  22. package/dist/hook-runner.js.map +1 -0
  23. package/dist/hooks.d.ts +183 -0
  24. package/dist/hooks.js +2 -0
  25. package/dist/hooks.js.map +1 -0
  26. package/dist/index.d.ts +26 -3
  27. package/dist/index.js +21 -3
  28. package/dist/index.js.map +1 -1
  29. package/dist/loop.d.ts +67 -0
  30. package/dist/loop.js +644 -0
  31. package/dist/loop.js.map +1 -0
  32. package/dist/observers.d.ts +31 -0
  33. package/dist/observers.js +98 -0
  34. package/dist/observers.js.map +1 -0
  35. package/dist/otel/attributes.d.ts +43 -0
  36. package/dist/otel/attributes.js +50 -0
  37. package/dist/otel/attributes.js.map +1 -0
  38. package/dist/otel/content.d.ts +17 -0
  39. package/dist/otel/content.js +48 -0
  40. package/dist/otel/content.js.map +1 -0
  41. package/dist/otel/index.d.ts +6 -2
  42. package/dist/otel/index.js +6 -2
  43. package/dist/otel/index.js.map +1 -1
  44. package/dist/otel/observer.d.ts +82 -0
  45. package/dist/otel/observer.js +300 -0
  46. package/dist/otel/observer.js.map +1 -0
  47. package/dist/pauses.d.ts +61 -0
  48. package/dist/pauses.js +83 -0
  49. package/dist/pauses.js.map +1 -0
  50. package/dist/progress.d.ts +34 -0
  51. package/dist/progress.js +139 -0
  52. package/dist/progress.js.map +1 -0
  53. package/dist/result.d.ts +134 -0
  54. package/dist/result.js +2 -0
  55. package/dist/result.js.map +1 -0
  56. package/dist/resume.d.ts +76 -0
  57. package/dist/resume.js +237 -0
  58. package/dist/resume.js.map +1 -0
  59. package/dist/run.d.ts +214 -0
  60. package/dist/run.js +327 -0
  61. package/dist/run.js.map +1 -0
  62. package/dist/steering.d.ts +52 -0
  63. package/dist/steering.js +104 -0
  64. package/dist/steering.js.map +1 -0
  65. package/dist/testing/scripted-model.d.ts +17 -2
  66. package/dist/testing/scripted-model.js +22 -4
  67. package/dist/testing/scripted-model.js.map +1 -1
  68. package/dist/tools/coerce.d.ts +15 -0
  69. package/dist/tools/coerce.js +93 -0
  70. package/dist/tools/coerce.js.map +1 -0
  71. package/dist/tools/define.d.ts +54 -0
  72. package/dist/tools/define.js +121 -0
  73. package/dist/tools/define.js.map +1 -0
  74. package/dist/tools/format-error.d.ts +13 -0
  75. package/dist/tools/format-error.js +66 -0
  76. package/dist/tools/format-error.js.map +1 -0
  77. package/dist/tools/outcome.d.ts +7 -0
  78. package/dist/tools/outcome.js +30 -0
  79. package/dist/tools/outcome.js.map +1 -0
  80. package/dist/tools/pipeline.d.ts +111 -0
  81. package/dist/tools/pipeline.js +382 -0
  82. package/dist/tools/pipeline.js.map +1 -0
  83. package/dist/tools/scheduler.d.ts +33 -0
  84. package/dist/tools/scheduler.js +51 -0
  85. package/dist/tools/scheduler.js.map +1 -0
  86. package/dist/tools/schema.d.ts +20 -0
  87. package/dist/tools/schema.js +100 -0
  88. package/dist/tools/schema.js.map +1 -0
  89. package/dist/tools/types.d.ts +196 -0
  90. package/dist/tools/types.js +2 -0
  91. package/dist/tools/types.js.map +1 -0
  92. package/dist/vendor/agent-safety/bytes.d.ts +17 -0
  93. package/dist/vendor/agent-safety/bytes.js +59 -0
  94. package/dist/vendor/agent-safety/bytes.js.map +1 -0
  95. package/dist/vendor/agent-safety/errors.d.ts +22 -0
  96. package/dist/vendor/agent-safety/errors.js +22 -0
  97. package/dist/vendor/agent-safety/errors.js.map +1 -0
  98. package/dist/vendor/agent-safety/hash.d.ts +16 -0
  99. package/dist/vendor/agent-safety/hash.js +110 -0
  100. package/dist/vendor/agent-safety/hash.js.map +1 -0
  101. package/dist/vendor/agent-safety/outcome.d.ts +88 -0
  102. package/dist/vendor/agent-safety/outcome.js +140 -0
  103. package/dist/vendor/agent-safety/outcome.js.map +1 -0
  104. package/dist/vendor/agent-safety/pending.d.ts +119 -0
  105. package/dist/vendor/agent-safety/pending.js +122 -0
  106. package/dist/vendor/agent-safety/pending.js.map +1 -0
  107. package/dist/vendor/agent-safety/render.d.ts +40 -0
  108. package/dist/vendor/agent-safety/render.js +92 -0
  109. package/dist/vendor/agent-safety/render.js.map +1 -0
  110. package/dist/vendor/agent-safety/signer.d.ts +42 -0
  111. package/dist/vendor/agent-safety/signer.js +128 -0
  112. package/dist/vendor/agent-safety/signer.js.map +1 -0
  113. package/dist/version.d.ts +2 -0
  114. package/dist/version.js +8 -0
  115. package/dist/version.js.map +1 -0
  116. package/package.json +13 -3
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hash.js","sourceRoot":"","sources":["../../../src/vendor/agent-safety/hash.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAElC,SAAS,OAAO,CAAC,IAAY,EAAE,GAAW;IACxC,OAAO,IAAI,WAAW,CAAC,eAAe,EAAE,gBAAgB,IAAI,IAAI,GAAG,oCAAoC,CAAC,CAAC;AAC3G,CAAC;AAED,SAAS,eAAe,CAAC,KAAa,EAAE,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B,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AAClG,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,KAAK,UAAU,kBAAkB,CAAC,KAAc;IACrD,MAAM,IAAI,GAAG,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,GAAG,EAAE,CAAC,CAAC;IAC9C,OAAO,GAAG,CAAC,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAC1E,CAAC","sourcesContent":["/**\n * `canonicalInputHash()`: one hash per tool input, whatever order its keys arrive in. Approvals sign it and effect\n * records store it, so both must compute it the same way on every runtime: canonical JSON as RFC 8785 (JCS) defines\n * it, hashed with Web Crypto's SHA-256. Web Crypto is read as the bare `crypto` global, the same object as\n * `globalThis.crypto`, because the Workers types declare it as a `const`, which `typeof globalThis` lacks.\n */\nimport { SafetyError } from \"./errors.js\";\n\nconst ENCODER = new TextEncoder();\n\nfunction invalid(path: string, why: string): SafetyError {\n return new SafetyError(\"invalid_input\", `the input at ${path} ${why}, so it has no canonical JSON form`);\n}\n\nfunction canonicalString(value: string, path: string): string {\n // JCS refuses lone surrogates, which JSON.stringify would escape instead.\n if (!value.isWellFormed()) throw invalid(path, \"holds a lone surrogate\");\n return JSON.stringify(value);\n}\n\nfunction canonicalNumber(value: number, path: string): string {\n if (!Number.isFinite(value)) throw invalid(path, `is ${value}`);\n // JCS serializes numbers as ECMAScript does, which JSON.stringify follows, including -0 as 0.\n return JSON.stringify(value);\n}\n\n// Plain means a null prototype or any realm's `Object.prototype`, whose own prototype is null: an object made in a\n// `vm` context or an iframe is as plain as one made here, while a `Date` or class instance is not.\nfunction isPlainObject(value: object): value is Record<string, unknown> {\n const prototype = Object.getPrototypeOf(value);\n return prototype === null || Object.getPrototypeOf(prototype) === null;\n}\n\nfunction byKey([a]: [string, unknown], [b]: [string, unknown]): number {\n // JCS sorts property names by UTF-16 code units, which is what `<` compares.\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n// `ancestors` holds the objects and arrays that enclose the current value, so a cycle throws instead of recursing\n// until the stack runs out. A value shared by two siblings is no cycle, so it is removed again on the way out.\nfunction canonicalObject(value: Record<string, unknown>, path: string, ancestors: Set<object>): string {\n // Each property is read once, so a getter or a Proxy can't be counted as present and then read as undefined.\n const entries = Object.entries(value)\n .filter(([, item]) => item !== undefined)\n .sort(byKey);\n const members = entries.map(\n ([key, item]) =>\n `${canonicalString(key, `${path}'s property name`)}:${canonical(item, `${path}.${key}`, ancestors)}`,\n );\n return `{${members.join(\",\")}}`;\n}\n\nfunction canonicalArray(value: readonly unknown[], path: string, ancestors: Set<object>): string {\n // An index loop, because `map` skips the holes of a sparse array and `join` would then write `[1,,3]`.\n const items: string[] = [];\n for (let index = 0; index < value.length; index++) {\n const itemPath = `${path}[${index}]`;\n if (!(index in value)) throw invalid(itemPath, \"is a hole in a sparse array\");\n const item = value[index];\n if (item === undefined) throw invalid(itemPath, \"is undefined\");\n items.push(canonical(item, itemPath, ancestors));\n }\n return `[${items.join(\",\")}]`;\n}\n\nfunction nested(value: object, path: string, ancestors: Set<object>, write: () => string): string {\n if (ancestors.has(value)) throw invalid(path, \"refers back to an object that contains it\");\n ancestors.add(value);\n try {\n return write();\n } finally {\n ancestors.delete(value);\n }\n}\n\nfunction describeType(value: unknown): string {\n if (value === undefined) return \"undefined\";\n return typeof value === \"object\" ? \"an object that isn't plain\" : `a ${typeof value}`;\n}\n\nfunction canonical(value: unknown, path: string, ancestors: Set<object>): string {\n if (value === null || typeof value === \"boolean\") return JSON.stringify(value);\n if (typeof value === \"string\") return canonicalString(value, path);\n if (typeof value === \"number\") return canonicalNumber(value, path);\n if (Array.isArray(value)) return nested(value, path, ancestors, () => canonicalArray(value, path, ancestors));\n if (typeof value === \"object\" && isPlainObject(value)) {\n return nested(value, path, ancestors, () => canonicalObject(value, path, ancestors));\n }\n throw invalid(path, `is ${describeType(value)}`);\n}\n\nfunction hex(bytes: ArrayBuffer): string {\n return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Hashes a tool input: the SHA-256 of its canonical JSON (RFC 8785), as 64 lowercase hex digits. Two inputs whose\n * object keys differ only in order get the same hash, and any changed value gives a different one. Object properties\n * set to `undefined` are left out, as `JSON.stringify` leaves them out. The hash is async, because Web Crypto's\n * digest is.\n *\n * It rejects with a `SafetyError`, code `invalid_input`, for a value that has no single JSON form:\n * - `undefined`, or a hole, in an array;\n * - a number that isn't finite;\n * - a string with a lone surrogate;\n * - a bigint, symbol or function;\n * - an object that isn't plain, such as a `Date` (a plain object's prototype is `null` or any realm's\n * `Object.prototype`);\n * - an object or array that contains itself.\n */\nexport async function canonicalInputHash(input: unknown): Promise<string> {\n const text = canonical(input, \"$\", new Set());\n return hex(await crypto.subtle.digest(\"SHA-256\", ENCODER.encode(text)));\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 {};
@@ -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/vendor/agent-safety/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,EAAE,OAAO;IAChB,WAAW,EAAE,UAAU;IACvB,WAAW,EAAE,oBAAoB;IACjC,OAAO,EAAE,OAAO;IAChB,OAAO,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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,119 @@
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
+ /** The question a clarification asks. */
21
+ question?: string;
22
+ /** Why the call needs a person, as shown to the approver. */
23
+ reason?: string;
24
+ /** The id of the key that made `signature`. */
25
+ keyId: string;
26
+ /** The signature, as base64url. */
27
+ signature: string;
28
+ /** When the request was signed, as an ISO 8601 timestamp. */
29
+ createdAt: string;
30
+ }
31
+ /** A person's answer to a pending request: allow or deny for an approval, an answer for a clarification. */
32
+ export type Resolution = {
33
+ requestId: string;
34
+ decision: "allow" | "deny";
35
+ reason?: string;
36
+ by?: string;
37
+ } | {
38
+ requestId: string;
39
+ answer: string;
40
+ by?: string;
41
+ };
42
+ /** The fields `signPending()` signs and stores, with the call's input in place of its hash. */
43
+ export interface PendingFields {
44
+ readonly kind: "approval" | "clarification";
45
+ readonly callId: string;
46
+ readonly tool: string;
47
+ /** The tool call's input. `signPending()` stores its `canonicalInputHash()`, never the input itself. */
48
+ readonly input: unknown;
49
+ readonly policyVersion?: string;
50
+ readonly question?: string;
51
+ readonly reason?: string;
52
+ }
53
+ /** Where `signPending()` takes its request id and time from. Tests pass fixed ones. */
54
+ export interface SignPendingOptions {
55
+ /** Returns a fresh request id. Defaults to `crypto.randomUUID()`. */
56
+ readonly generateId?: () => string;
57
+ /** Returns the current time. Defaults to `new Date()`. */
58
+ readonly now?: () => Date;
59
+ }
60
+ /** The call a host is about to run, which a pending request must match before it runs. */
61
+ export interface PendingCall {
62
+ readonly callId: string;
63
+ readonly tool: string;
64
+ readonly input: unknown;
65
+ }
66
+ /**
67
+ * Why `verifyResolution()` refused. `malformed`: the stored request isn't a well-formed pending request.
68
+ * `unknown_request`: the resolution names another request. `signature_invalid`: the signature is wrong, or its key id
69
+ * isn't in the ring. `call_mismatch`: the call id or tool differs from the call about to run. `input_changed`: the
70
+ * input differs from the one that was signed. `resolution_mismatch`: the resolution doesn't fit the request's kind.
71
+ */
72
+ export type RejectionCause = "malformed" | "unknown_request" | "signature_invalid" | "call_mismatch" | "input_changed" | "resolution_mismatch";
73
+ /** What `verifyResolution()` returns: the resolution, once every check passed, or why it refused. */
74
+ export type ResolutionCheck = {
75
+ readonly ok: true;
76
+ readonly resolution: Resolution;
77
+ } | {
78
+ readonly ok: false;
79
+ readonly cause: RejectionCause;
80
+ };
81
+ /** The options of `verifyResolution()`. */
82
+ export interface VerifyResolutionOptions {
83
+ /** A signer that holds the key the request names. */
84
+ readonly signer: ApprovalSigner;
85
+ /** The call about to run, as the host has it now, not as the pending request records it. */
86
+ readonly call: PendingCall;
87
+ }
88
+ /**
89
+ * The bytes a pending request's signature covers: a JSON array of a fixed tag, then the request id, kind, call id,
90
+ * tool name, input hash and policy version, in that order, with `null` for an absent policy version. Every field is a well-formed string, so `JSON.stringify` writes the same bytes
91
+ * on every runtime.
92
+ */
93
+ export declare function pendingPayload(fields: Pick<SignedPendingRequest, "id" | "kind" | "callId" | "tool" | "inputHash" | "policyVersion">): Uint8Array;
94
+ /**
95
+ * Signs a pending request for a tool call. It hashes the input with `canonicalInputHash()`, signs the six fields
96
+ * `pendingPayload()` lists with the signer's current key, and returns the request to store. The input itself isn't stored.
97
+ *
98
+ * Throws a `SafetyError`, code `invalid_pending`, for a blank or malformed field, and code `invalid_input` for an
99
+ * input with no canonical JSON form.
100
+ */
101
+ export declare function signPending(fields: PendingFields, signer: ApprovalSigner, options?: SignPendingOptions): Promise<SignedPendingRequest>;
102
+ /**
103
+ * Checks a resolution against its stored pending request before the call runs, failing closed. It accepts only when
104
+ * the request is well formed, the resolution names it, the signature verifies under a key the signer holds, the call
105
+ * id and tool match the call about to run, that call's input hashes to the signed hash, and the resolution fits the
106
+ * request's kind. Otherwise it returns `ok: false` with the first cause it found, and never throws for bad input.
107
+ *
108
+ * A passing check says the request is authentic and unchanged. It doesn't say current policy still allows the call:
109
+ * check that separately, just before the call runs.
110
+ */
111
+ export declare function verifyResolution(pending: unknown, resolution: Resolution, options: VerifyResolutionOptions): Promise<ResolutionCheck>;
112
+ /**
113
+ * Runs current policy for an approved call just before it runs, after its pending request has verified. Resolve to
114
+ * `"allow"` to let the call run, or to `{ deny }` with a reason the model reads, so a policy that changed since the
115
+ * pause can still stop the call.
116
+ */
117
+ export type Recheck = (pending: SignedPendingRequest, input: unknown) => Promise<"allow" | {
118
+ deny: string;
119
+ }>;
@@ -0,0 +1,122 @@
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), so a stored pause whose call, tool or input changed no longer verifies. The shapes
5
+ * match build-sdk.md §3.3 field for field, because our SDK re-exports them.
6
+ */
7
+ import { constantTimeEqual } from "./bytes.js";
8
+ import { SafetyError } from "./errors.js";
9
+ import { canonicalInputHash } from "./hash.js";
10
+ // Ties a signature to this record and its layout, so it can't verify as some other signed record of this package.
11
+ const PAYLOAD_TAG = "buildanagent.pending.v1";
12
+ const KINDS = ["approval", "clarification"];
13
+ const INPUT_HASH = /^[0-9a-f]{64}$/;
14
+ const ENCODER = new TextEncoder();
15
+ function isText(value) {
16
+ return typeof value === "string" && value !== "" && value.isWellFormed();
17
+ }
18
+ function isOptionalText(value) {
19
+ return value === undefined || isText(value);
20
+ }
21
+ /** True when `value` has the shape of a pending request; a store's record is untrusted until this and the signature pass. */
22
+ function isWellFormed(value) {
23
+ if (typeof value !== "object" || value === null)
24
+ return false;
25
+ const p = value;
26
+ return ([p.id, p.callId, p.tool, p.keyId, p.signature, p.createdAt].every(isText) &&
27
+ KINDS.includes(p.kind) &&
28
+ typeof p.inputHash === "string" &&
29
+ INPUT_HASH.test(p.inputHash) &&
30
+ [p.policyVersion, p.question, p.reason].every(isOptionalText));
31
+ }
32
+ /**
33
+ * The bytes a pending request's signature covers: a JSON array of a fixed tag, then the request id, kind, call id,
34
+ * tool name, input hash and policy version, in that order, with `null` for an absent policy version. Every field is a well-formed string, so `JSON.stringify` writes the same bytes
35
+ * on every runtime.
36
+ */
37
+ export function pendingPayload(fields) {
38
+ const { id, kind, callId, tool, inputHash, policyVersion } = fields;
39
+ return ENCODER.encode(JSON.stringify([PAYLOAD_TAG, id, kind, callId, tool, inputHash, policyVersion ?? null]));
40
+ }
41
+ function checkFields(fields, id) {
42
+ const bad = (what) => new SafetyError("invalid_pending", `a pending request's ${what}`);
43
+ if (!isText(id))
44
+ throw bad("id must be a non-empty, well-formed string");
45
+ if (!KINDS.includes(fields.kind))
46
+ throw bad(`kind must be "approval" or "clarification"`);
47
+ for (const field of ["callId", "tool"]) {
48
+ if (!isText(fields[field]))
49
+ throw bad(`${field} must be a non-empty, well-formed string`);
50
+ }
51
+ for (const field of ["policyVersion", "question", "reason"]) {
52
+ if (!isOptionalText(fields[field]))
53
+ throw bad(`${field} must be a non-empty, well-formed string when it is set`);
54
+ }
55
+ }
56
+ /**
57
+ * Signs a pending request for a tool call. It hashes the input with `canonicalInputHash()`, signs the six fields
58
+ * `pendingPayload()` lists with the signer's current key, and returns the request to store. The input itself isn't stored.
59
+ *
60
+ * Throws a `SafetyError`, code `invalid_pending`, for a blank or malformed field, and code `invalid_input` for an
61
+ * input with no canonical JSON form.
62
+ */
63
+ export async function signPending(fields, signer, options = {}) {
64
+ const id = (options.generateId ?? (() => crypto.randomUUID()))();
65
+ checkFields(fields, id);
66
+ const inputHash = await canonicalInputHash(fields.input);
67
+ const signed = { id, kind: fields.kind, callId: fields.callId, tool: fields.tool, inputHash };
68
+ const withPolicy = fields.policyVersion === undefined ? signed : { ...signed, policyVersion: fields.policyVersion };
69
+ const signature = await signer.sign(pendingPayload(withPolicy));
70
+ return {
71
+ ...withPolicy,
72
+ ...(fields.question === undefined ? {} : { question: fields.question }),
73
+ ...(fields.reason === undefined ? {} : { reason: fields.reason }),
74
+ keyId: signer.keyId,
75
+ signature,
76
+ createdAt: (options.now ?? (() => new Date()))().toISOString(),
77
+ };
78
+ }
79
+ function fitsKind(pending, resolution) {
80
+ if (pending.kind === "approval") {
81
+ return "decision" in resolution && (resolution.decision === "allow" || resolution.decision === "deny");
82
+ }
83
+ return "answer" in resolution && typeof resolution.answer === "string";
84
+ }
85
+ async function inputMatches(pending, input) {
86
+ try {
87
+ return constantTimeEqual(ENCODER.encode(await canonicalInputHash(input)), ENCODER.encode(pending.inputHash));
88
+ }
89
+ catch {
90
+ // An input with no canonical form can't be the one that was signed, which had one.
91
+ return false;
92
+ }
93
+ }
94
+ /**
95
+ * Checks a resolution against its stored pending request before the call runs, failing closed. It accepts only when
96
+ * the request is well formed, the resolution names it, the signature verifies under a key the signer holds, the call
97
+ * id and tool match the call about to run, that call's input hashes to the signed hash, and the resolution fits the
98
+ * request's kind. Otherwise it returns `ok: false` with the first cause it found, and never throws for bad input.
99
+ *
100
+ * A passing check says the request is authentic and unchanged. It doesn't say current policy still allows the call:
101
+ * check that separately, just before the call runs.
102
+ */
103
+ export async function verifyResolution(pending, resolution, options) {
104
+ if (!isWellFormed(pending))
105
+ return { ok: false, cause: "malformed" };
106
+ if (typeof resolution !== "object" || resolution === null || resolution.requestId !== pending.id) {
107
+ return { ok: false, cause: "unknown_request" };
108
+ }
109
+ // The signature comes first: until it verifies, no other field of the stored request is trusted.
110
+ if (!(await options.signer.verify(pending.keyId, pendingPayload(pending), pending.signature))) {
111
+ return { ok: false, cause: "signature_invalid" };
112
+ }
113
+ const { call } = options;
114
+ if (call.callId !== pending.callId || call.tool !== pending.tool)
115
+ return { ok: false, cause: "call_mismatch" };
116
+ if (!(await inputMatches(pending, call.input)))
117
+ return { ok: false, cause: "input_changed" };
118
+ if (!fitsKind(pending, resolution))
119
+ return { ok: false, cause: "resolution_mismatch" };
120
+ return { ok: true, resolution };
121
+ }
122
+ //# sourceMappingURL=pending.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pending.js","sourceRoot":"","sources":["../../../src/vendor/agent-safety/pending.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AA4F/C,kHAAkH;AAClH,MAAM,WAAW,GAAG,yBAAyB,CAAC;AAC9C,MAAM,KAAK,GAAsB,CAAC,UAAU,EAAE,eAAe,CAAC,CAAC;AAC/D,MAAM,UAAU,GAAG,gBAAgB,CAAC;AACpC,MAAM,OAAO,GAAG,IAAI,W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AY,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), so a stored pause whose call, tool or input changed no longer verifies. The shapes\n * match build-sdk.md §3.3 field for field, because our SDK re-exports them.\n */\nimport { constantTimeEqual } from \"./bytes.js\";\nimport { SafetyError } from \"./errors.js\";\nimport { canonicalInputHash } 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 /** 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 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. `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 | \"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\n// Ties a signature to this record and its layout, so it can't verify as some other signed record of this package.\nconst PAYLOAD_TAG = \"buildanagent.pending.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 );\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. Every field is a well-formed string, so `JSON.stringify` writes the same bytes\n * on every runtime.\n */\nexport function pendingPayload(\n fields: Pick<SignedPendingRequest, \"id\" | \"kind\" | \"callId\" | \"tool\" | \"inputHash\" | \"policyVersion\">,\n): Uint8Array {\n const { id, kind, callId, tool, inputHash, policyVersion } = fields;\n return ENCODER.encode(JSON.stringify([PAYLOAD_TAG, id, kind, callId, tool, inputHash, policyVersion ?? null]));\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/**\n * Signs a pending request for a tool call. It hashes the input with `canonicalInputHash()`, signs the six 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 signature = await signer.sign(pendingPayload(withPolicy));\n return {\n ...withPolicy,\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\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, the call\n * id and tool match the call about to run, that call's input hashes to the signed hash, and the resolution fits the\n * request's kind. Otherwise it 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 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"]}
@@ -0,0 +1,40 @@
1
+ /**
2
+ * `renderOutcome()`: turns a write outcome into what the model reads. The outcome travels in the tool result's body,
3
+ * as a sentence and a structured payload, with the provider's error flag set as well, because some adapters drop the
4
+ * flag and some SDKs hide text blocks once structured content is set (server rollback report).
5
+ */
6
+ import { type OutcomeKind, type Retry, type WriteOutcome } from "./outcome.js";
7
+ /**
8
+ * The structured half of a rendered outcome: the outcome's own fields, as plain JSON. Optional fields the outcome
9
+ * leaves out are left out here too.
10
+ */
11
+ export type OutcomePayload = {
12
+ readonly kind: OutcomeKind;
13
+ readonly operation: string;
14
+ readonly effectKey?: string;
15
+ readonly applied: readonly string[];
16
+ readonly reverted: readonly string[];
17
+ readonly notReversible: readonly string[];
18
+ readonly currentState?: string;
19
+ readonly retry: Retry;
20
+ readonly next: string;
21
+ readonly avoid?: string;
22
+ readonly reason?: string;
23
+ };
24
+ /** A write outcome as the model reads it. */
25
+ export interface RenderedOutcome {
26
+ /** Sentences that say what happened, what to do next and what not to do. */
27
+ readonly text: string;
28
+ /** The outcome's fields, for a model or a harness that reads structured results. */
29
+ readonly payload: OutcomePayload;
30
+ /** True for every kind except `applied`: the provider's error flag, where the provider has one. */
31
+ readonly isError: boolean;
32
+ }
33
+ /**
34
+ * Renders a write outcome for the model: sentences that name what happened, what to do next and what not to do, the
35
+ * outcome's fields as a JSON payload, and whether the provider's error flag should be set. Put both the text and the
36
+ * payload in the tool result, because some SDKs show the model only one of them. It first checks the outcome as
37
+ * `writeOutcome()` does, so an outcome built by hand that breaks a rule throws a `SafetyError`, code
38
+ * `invalid_outcome`.
39
+ */
40
+ export declare function renderOutcome(outcome: WriteOutcome): RenderedOutcome;