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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/LICENSE +54 -0
  2. package/LICENSE-APACHE +202 -0
  3. package/LICENSE-MIT +21 -0
  4. package/README.md +515 -0
  5. package/dist/agents/index.d.ts +5 -0
  6. package/dist/agents/index.js +6 -0
  7. package/dist/agents/index.js.map +1 -0
  8. package/dist/ai/index.d.ts +10 -0
  9. package/dist/ai/index.js +11 -0
  10. package/dist/ai/index.js.map +1 -0
  11. package/dist/ai/interrupted-write.d.ts +28 -0
  12. package/dist/ai/interrupted-write.js +52 -0
  13. package/dist/ai/interrupted-write.js.map +1 -0
  14. package/dist/ai/settle-denied.d.ts +17 -0
  15. package/dist/ai/settle-denied.js +25 -0
  16. package/dist/ai/settle-denied.js.map +1 -0
  17. package/dist/ai/tool-approval.d.ts +68 -0
  18. package/dist/ai/tool-approval.js +219 -0
  19. package/dist/ai/tool-approval.js.map +1 -0
  20. package/dist/ai/tool-result.d.ts +23 -0
  21. package/dist/ai/tool-result.js +20 -0
  22. package/dist/ai/tool-result.js.map +1 -0
  23. package/dist/byok/default-provider.d.ts +12 -0
  24. package/dist/byok/default-provider.js +72 -0
  25. package/dist/byok/default-provider.js.map +1 -0
  26. package/dist/byok/explicit-provider.d.ts +39 -0
  27. package/dist/byok/explicit-provider.js +80 -0
  28. package/dist/byok/explicit-provider.js.map +1 -0
  29. package/dist/byok/index.d.ts +8 -0
  30. package/dist/byok/index.js +9 -0
  31. package/dist/byok/index.js.map +1 -0
  32. package/dist/bytes.d.ts +17 -0
  33. package/dist/bytes.js +59 -0
  34. package/dist/bytes.js.map +1 -0
  35. package/dist/cost/ai-types.d.ts +26 -0
  36. package/dist/cost/ai-types.js +2 -0
  37. package/dist/cost/ai-types.js.map +1 -0
  38. package/dist/cost/budget-exceeded.d.ts +39 -0
  39. package/dist/cost/budget-exceeded.js +49 -0
  40. package/dist/cost/budget-exceeded.js.map +1 -0
  41. package/dist/cost/cost-guard.d.ts +63 -0
  42. package/dist/cost/cost-guard.js +278 -0
  43. package/dist/cost/cost-guard.js.map +1 -0
  44. package/dist/cost/estimate.d.ts +76 -0
  45. package/dist/cost/estimate.js +320 -0
  46. package/dist/cost/estimate.js.map +1 -0
  47. package/dist/cost/guarded-provider.d.ts +24 -0
  48. package/dist/cost/guarded-provider.js +19 -0
  49. package/dist/cost/guarded-provider.js.map +1 -0
  50. package/dist/cost/index.d.ts +12 -0
  51. package/dist/cost/index.js +12 -0
  52. package/dist/cost/index.js.map +1 -0
  53. package/dist/cost/spend.d.ts +13 -0
  54. package/dist/cost/spend.js +15 -0
  55. package/dist/cost/spend.js.map +1 -0
  56. package/dist/effect-key.d.ts +31 -0
  57. package/dist/effect-key.js +61 -0
  58. package/dist/effect-key.js.map +1 -0
  59. package/dist/effect-store-conformance.d.ts +24 -0
  60. package/dist/effect-store-conformance.js +140 -0
  61. package/dist/effect-store-conformance.js.map +1 -0
  62. package/dist/effect-store.d.ts +71 -0
  63. package/dist/effect-store.js +38 -0
  64. package/dist/effect-store.js.map +1 -0
  65. package/dist/egress.d.ts +74 -0
  66. package/dist/egress.js +174 -0
  67. package/dist/egress.js.map +1 -0
  68. package/dist/errors.d.ts +32 -0
  69. package/dist/errors.js +26 -0
  70. package/dist/errors.js.map +1 -0
  71. package/dist/guarded-write.d.ts +99 -0
  72. package/dist/guarded-write.js +245 -0
  73. package/dist/guarded-write.js.map +1 -0
  74. package/dist/hash.d.ts +24 -0
  75. package/dist/hash.js +121 -0
  76. package/dist/hash.js.map +1 -0
  77. package/dist/index.d.ts +27 -0
  78. package/dist/index.js +28 -0
  79. package/dist/index.js.map +1 -0
  80. package/dist/key-store.d.ts +37 -0
  81. package/dist/key-store.js +53 -0
  82. package/dist/key-store.js.map +1 -0
  83. package/dist/model-routes.d.ts +54 -0
  84. package/dist/model-routes.js +117 -0
  85. package/dist/model-routes.js.map +1 -0
  86. package/dist/model-url.d.ts +39 -0
  87. package/dist/model-url.js +79 -0
  88. package/dist/model-url.js.map +1 -0
  89. package/dist/outcome.d.ts +88 -0
  90. package/dist/outcome.js +140 -0
  91. package/dist/outcome.js.map +1 -0
  92. package/dist/pending-store.d.ts +45 -0
  93. package/dist/pending-store.js +36 -0
  94. package/dist/pending-store.js.map +1 -0
  95. package/dist/pending.d.ts +144 -0
  96. package/dist/pending.js +161 -0
  97. package/dist/pending.js.map +1 -0
  98. package/dist/plan-approval.d.ts +196 -0
  99. package/dist/plan-approval.js +357 -0
  100. package/dist/plan-approval.js.map +1 -0
  101. package/dist/plan-card.d.ts +34 -0
  102. package/dist/plan-card.js +56 -0
  103. package/dist/plan-card.js.map +1 -0
  104. package/dist/plan-ledger-conformance.d.ts +24 -0
  105. package/dist/plan-ledger-conformance.js +99 -0
  106. package/dist/plan-ledger-conformance.js.map +1 -0
  107. package/dist/plan-ledger.d.ts +14 -0
  108. package/dist/plan-ledger.js +42 -0
  109. package/dist/plan-ledger.js.map +1 -0
  110. package/dist/plan-run.d.ts +133 -0
  111. package/dist/plan-run.js +438 -0
  112. package/dist/plan-run.js.map +1 -0
  113. package/dist/render.d.ts +40 -0
  114. package/dist/render.js +92 -0
  115. package/dist/render.js.map +1 -0
  116. package/dist/signer.d.ts +42 -0
  117. package/dist/signer.js +128 -0
  118. package/dist/signer.js.map +1 -0
  119. package/dist/stores/cloudflare.d.ts +34 -0
  120. package/dist/stores/cloudflare.js +84 -0
  121. package/dist/stores/cloudflare.js.map +1 -0
  122. package/dist/stores/dynamodb.d.ts +27 -0
  123. package/dist/stores/dynamodb.js +139 -0
  124. package/dist/stores/dynamodb.js.map +1 -0
  125. package/dist/stores/lost-claim.d.ts +8 -0
  126. package/dist/stores/lost-claim.js +11 -0
  127. package/dist/stores/lost-claim.js.map +1 -0
  128. package/dist/stores/postgres.d.ts +30 -0
  129. package/dist/stores/postgres.js +79 -0
  130. package/dist/stores/postgres.js.map +1 -0
  131. package/dist/test-signer.d.ts +13 -0
  132. package/dist/test-signer.js +18 -0
  133. package/dist/test-signer.js.map +1 -0
  134. package/dist/testing.d.ts +8 -0
  135. package/dist/testing.js +9 -0
  136. package/dist/testing.js.map +1 -0
  137. package/llms.txt +212 -0
  138. package/package.json +108 -5
@@ -0,0 +1,28 @@
1
+ /**
2
+ * `repairInterruptedWrite()`: an interrupted write tool part as an `unknown` outcome. Cloudflare `AIChatAgent`
3
+ * (`@cloudflare/ai-chat` 0.12.2) repairs a tool part left without a result, such as one whose `execute()` died with an
4
+ * evicted isolate, before each turn. Its default `repairInterruptedToolPart` turns the part into an `output-error`
5
+ * that reads "The tool call was interrupted before a result was recorded.", which the model takes as a failure it may
6
+ * retry. For a write, the honest result is `unknown`: the call may have taken effect. The `ai` import is type-only.
7
+ */
8
+ import type { UIMessage } from "ai";
9
+ type Part = UIMessage["parts"][number];
10
+ /**
11
+ * Returns `part` settled as `output-available` with an `unknown` write outcome as its output, if its tool is one of
12
+ * `writes` and `execute` may have started, or `undefined` for any other tool or a part still streaming its input or
13
+ * awaiting approval, so the caller keeps the default repair for those. Use it in an
14
+ * `AIChatAgent`'s `repairInterruptedToolPart` override, and convert the stored messages with the agent's tools, so a
15
+ * tool whose `toModelOutput` calls `toAiToolResult()` hands the model the outcome as an `error-json` result.
16
+ *
17
+ * The outcome carries no effect key, because the repair runs synchronously and the key's hash is async. A tool wrapped
18
+ * in `guardedWrite()` finds its own record again when the model calls it for the same business key.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * protected override repairInterruptedToolPart(part: UIMessage["parts"][number]) {
23
+ * return repairInterruptedWrite(part, WRITE_TOOLS) ?? super.repairInterruptedToolPart(part);
24
+ * }
25
+ * ```
26
+ */
27
+ export declare function repairInterruptedWrite<PART extends Part>(part: PART, writes: ReadonlySet<string>): PART | undefined;
28
+ export {};
@@ -0,0 +1,52 @@
1
+ import { writeOutcome } from "../outcome.js";
2
+ function toolName(part) {
3
+ const tool = part;
4
+ if (typeof tool.toolCallId !== "string")
5
+ return undefined;
6
+ if (tool.type === "dynamic-tool")
7
+ return typeof tool.toolName === "string" ? tool.toolName : undefined;
8
+ return tool.type.startsWith("tool-") ? tool.type.slice("tool-".length) : undefined;
9
+ }
10
+ /** The outcome an interrupted call of `operation` reports: `unknown`, to be checked before any retry. */
11
+ function interrupted(operation) {
12
+ return writeOutcome({
13
+ kind: "unknown",
14
+ operation,
15
+ retry: "reconcile_first",
16
+ reason: "WRITE_INTERRUPTED",
17
+ currentState: "The call stopped before it recorded a result, so it may have taken effect.",
18
+ next: "Check whether it took effect before you do anything else, and tell the user if you cannot.",
19
+ });
20
+ }
21
+ /**
22
+ * Returns `part` settled as `output-available` with an `unknown` write outcome as its output, if its tool is one of
23
+ * `writes` and `execute` may have started, or `undefined` for any other tool or a part still streaming its input or
24
+ * awaiting approval, so the caller keeps the default repair for those. Use it in an
25
+ * `AIChatAgent`'s `repairInterruptedToolPart` override, and convert the stored messages with the agent's tools, so a
26
+ * tool whose `toModelOutput` calls `toAiToolResult()` hands the model the outcome as an `error-json` result.
27
+ *
28
+ * The outcome carries no effect key, because the repair runs synchronously and the key's hash is async. A tool wrapped
29
+ * in `guardedWrite()` finds its own record again when the model calls it for the same business key.
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * protected override repairInterruptedToolPart(part: UIMessage["parts"][number]) {
34
+ * return repairInterruptedWrite(part, WRITE_TOOLS) ?? super.repairInterruptedToolPart(part);
35
+ * }
36
+ * ```
37
+ */
38
+ export function repairInterruptedWrite(part, writes) {
39
+ const name = toolName(part);
40
+ if (name === undefined || !writes.has(name))
41
+ return undefined;
42
+ // `execute` starts only once the input is complete and any approval is granted, so a part in an earlier state never
43
+ // ran; the default repair, which reports a failure the model may retry, is the honest one for it.
44
+ const state = part.state;
45
+ if (state === "input-streaming" || state === "approval-requested")
46
+ return undefined;
47
+ // `ai` 7.0.162's UI message validator takes an `output-available` tool part with any output and no error text; an
48
+ // approval the part keeps is a granted one, because the agent settles a denied part as `output-denied` first.
49
+ const { errorText: _dropped, ...rest } = part;
50
+ return { ...rest, state: "output-available", output: interrupted(name) };
51
+ }
52
+ //# sourceMappingURL=interrupted-write.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"interrupted-write.js","sourceRoot":"","sources":["../../src/ai/interrupted-write.ts"],"names":[],"mappings":"AAQA,OAAO,EAAqB,YAAY,EAAE,MAAM,eAAe,CAAC;AAIhE,SAAS,QAAQ,CAAC,IAAU;IAC1B,MAAM,IAAI,GAAG,IAAkE,CAAC;IAChF,IAAI,OAAO,IAAI,CAAC,UAAU,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAC;IAC1D,IAAI,IAAI,CAAC,IAAI,KAAK,cAAc;QAAE,OAAO,OAAO,IAAI,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC;IACvG,OAAO,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AACrF,CAAC;AAED,yGAAyG;AACzG,SAAS,WAAW,CAAC,SAAiB;IACpC,OAAO,YAAY,CAAC;QAClB,IAAI,EAAE,SAAS;QACf,SAAS;QACT,KAAK,EAAE,iBAAiB;QACxB,MAAM,EAAE,mBAAmB;QAC3B,YAAY,EAAE,4EAA4E;QAC1F,IAAI,EAAE,4FAA4F;KACnG,CAAC,CAAC;AACL,CAAC;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,UAAU,sBAAsB,CAAoB,IAAU,EAAE,MAA2B;IAC/F,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC5B,IAAI,IAAI,KAAK,SAAS,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC;QAAE,OAAO,SAAS,CAAC;IAC9D,oHAAoH;IACpH,kGAAkG;IAClG,MAAM,KAAK,GAAI,IAA4B,CAAC,KAAK,CAAC;IAClD,IAAI,KAAK,KAAK,iBAAiB,IAAI,KAAK,KAAK,oBAAoB;QAAE,OAAO,SAAS,CAAC;IACpF,kHAAkH;IAClH,8GAA8G;IAC9G,MAAM,EAAE,SAAS,EAAE,QAAQ,EAAE,GAAG,IAAI,EAAE,GAAG,IAAsC,CAAC;IAChF,OAAO,EAAE,GAAG,IAAI,EAAE,KAAK,EAAE,kBAAkB,EAAE,MAAM,EAAE,WAAW,CAAC,IAAI,CAAC,EAAqB,CAAC;AAC9F,CAAC","sourcesContent":["/**\n * `repairInterruptedWrite()`: an interrupted write tool part as an `unknown` outcome. Cloudflare `AIChatAgent`\n * (`@cloudflare/ai-chat` 0.12.2) repairs a tool part left without a result, such as one whose `execute()` died with an\n * evicted isolate, before each turn. Its default `repairInterruptedToolPart` turns the part into an `output-error`\n * that reads \"The tool call was interrupted before a result was recorded.\", which the model takes as a failure it may\n * retry. For a write, the honest result is `unknown`: the call may have taken effect. The `ai` import is type-only.\n */\nimport type { UIMessage } from \"ai\";\nimport { type WriteOutcome, writeOutcome } from \"../outcome.js\";\n\ntype Part = UIMessage[\"parts\"][number];\n\nfunction toolName(part: Part): string | undefined {\n const tool = part as { type: string; toolName?: unknown; toolCallId?: unknown };\n if (typeof tool.toolCallId !== \"string\") return undefined;\n if (tool.type === \"dynamic-tool\") return typeof tool.toolName === \"string\" ? tool.toolName : undefined;\n return tool.type.startsWith(\"tool-\") ? tool.type.slice(\"tool-\".length) : undefined;\n}\n\n/** The outcome an interrupted call of `operation` reports: `unknown`, to be checked before any retry. */\nfunction interrupted(operation: string): WriteOutcome {\n return writeOutcome({\n kind: \"unknown\",\n operation,\n retry: \"reconcile_first\",\n reason: \"WRITE_INTERRUPTED\",\n currentState: \"The call stopped before it recorded a result, so it may have taken effect.\",\n next: \"Check whether it took effect before you do anything else, and tell the user if you cannot.\",\n });\n}\n\n/**\n * Returns `part` settled as `output-available` with an `unknown` write outcome as its output, if its tool is one of\n * `writes` and `execute` may have started, or `undefined` for any other tool or a part still streaming its input or\n * awaiting approval, so the caller keeps the default repair for those. Use it in an\n * `AIChatAgent`'s `repairInterruptedToolPart` override, and convert the stored messages with the agent's tools, so a\n * tool whose `toModelOutput` calls `toAiToolResult()` hands the model the outcome as an `error-json` result.\n *\n * The outcome carries no effect key, because the repair runs synchronously and the key's hash is async. A tool wrapped\n * in `guardedWrite()` finds its own record again when the model calls it for the same business key.\n *\n * @example\n * ```ts\n * protected override repairInterruptedToolPart(part: UIMessage[\"parts\"][number]) {\n * return repairInterruptedWrite(part, WRITE_TOOLS) ?? super.repairInterruptedToolPart(part);\n * }\n * ```\n */\nexport function repairInterruptedWrite<PART extends Part>(part: PART, writes: ReadonlySet<string>): PART | undefined {\n const name = toolName(part);\n if (name === undefined || !writes.has(name)) return undefined;\n // `execute` starts only once the input is complete and any approval is granted, so a part in an earlier state never\n // ran; the default repair, which reports a failure the model may retry, is the honest one for it.\n const state = (part as { state?: unknown }).state;\n if (state === \"input-streaming\" || state === \"approval-requested\") return undefined;\n // `ai` 7.0.162's UI message validator takes an `output-available` tool part with any output and no error text; an\n // approval the part keeps is a granted one, because the agent settles a denied part as `output-denied` first.\n const { errorText: _dropped, ...rest } = part as Part & { errorText?: unknown };\n return { ...rest, state: \"output-available\", output: interrupted(name) } as unknown as PART;\n}\n"]}
@@ -0,0 +1,17 @@
1
+ /**
2
+ * `settleDeniedApprovals()`: marks UI tool parts whose approved call `signedToolApproval()` denied on resume as denied,
3
+ * so a chat that stores UI messages doesn't replay the approval. `ai` streams a `tool-output-denied` chunk for such a
4
+ * call, but Cloudflare `agents` 0.33.0 treats that chunk as a replay once the stored part is `approval-responded`, so
5
+ * `AIChatAgent` keeps the part as approved and without a result. The next model step that converts it then fails with
6
+ * `AI_MissingToolResultsError`. The `ai` import is type-only.
7
+ */
8
+ import type { UIMessage } from "ai";
9
+ /**
10
+ * Returns `messages` with every tool part whose call id is in `denied`, and whose state is still
11
+ * `approval-responded`, moved to `output-denied` with its approval marked `approved: false`, as `ai`'s UI message
12
+ * types and validator require for that state. The approval keeps its id and the person's reason. Messages it doesn't
13
+ * change are returned as they are, so compare the result with `messages` to know whether to store it.
14
+ *
15
+ * Collect `denied` from `signedToolApproval()`'s `onRejected`, and keep it where your chat keeps its messages.
16
+ */
17
+ export declare function settleDeniedApprovals<MESSAGE extends UIMessage>(messages: readonly MESSAGE[], denied: ReadonlySet<string>): MESSAGE[];
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Returns `messages` with every tool part whose call id is in `denied`, and whose state is still
3
+ * `approval-responded`, moved to `output-denied` with its approval marked `approved: false`, as `ai`'s UI message
4
+ * types and validator require for that state. The approval keeps its id and the person's reason. Messages it doesn't
5
+ * change are returned as they are, so compare the result with `messages` to know whether to store it.
6
+ *
7
+ * Collect `denied` from `signedToolApproval()`'s `onRejected`, and keep it where your chat keeps its messages.
8
+ */
9
+ export function settleDeniedApprovals(messages, denied) {
10
+ return messages.map((message) => {
11
+ let changed = false;
12
+ const parts = message.parts.map((part) => {
13
+ const tool = part;
14
+ if (typeof tool.toolCallId !== "string" || tool.state !== "approval-responded" || !denied.has(tool.toolCallId)) {
15
+ return part;
16
+ }
17
+ changed = true;
18
+ // `ai` 7.0.162 validates an `output-denied` part's approval with `approved: z.literal(false)`.
19
+ return { ...part, state: "output-denied", approval: { ...tool.approval, approved: false } };
20
+ });
21
+ // The new part keeps its tool type, input and approval id; only its state and the approval's verdict change.
22
+ return changed ? { ...message, parts } : message;
23
+ });
24
+ }
25
+ //# sourceMappingURL=settle-denied.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"settle-denied.js","sourceRoot":"","sources":["../../src/ai/settle-denied.ts"],"names":[],"mappings":"AASA;;;;;;;GAOG;AACH,MAAM,UAAU,qBAAqB,CACnC,QAA4B,EAC5B,MAA2B;IAE3B,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE;QAC9B,IAAI,OAAO,GAAG,KAAK,CAAC;QACpB,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE;YACvC,MAAM,IAAI,GAAG,IAAoE,CAAC;YAClF,IAAI,OAAO,IAAI,CAAC,UAAU,KAAK,QAAQ,IAAI,IAAI,CAAC,KAAK,KAAK,oBAAoB,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;gBAC/G,OAAO,IAAI,CAAC;YACd,CAAC;YACD,OAAO,GAAG,IAAI,CAAC;YACf,+FAA+F;YAC/F,OAAO,EAAE,GAAG,IAAI,EAAE,KAAK,EAAE,eAAe,EAAE,QAAQ,EAAE,EAAE,GAAG,IAAI,CAAC,QAAQ,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,CAAC;QAC9F,CAAC,CAAC,CAAC;QACH,6GAA6G;QAC7G,OAAO,OAAO,CAAC,CAAC,CAAE,EAAE,GAAG,OAAO,EAAE,KAAK,EAAc,CAAC,CAAC,CAAC,OAAO,CAAC;IAChE,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * `settleDeniedApprovals()`: marks UI tool parts whose approved call `signedToolApproval()` denied on resume as denied,\n * so a chat that stores UI messages doesn't replay the approval. `ai` streams a `tool-output-denied` chunk for such a\n * call, but Cloudflare `agents` 0.33.0 treats that chunk as a replay once the stored part is `approval-responded`, so\n * `AIChatAgent` keeps the part as approved and without a result. The next model step that converts it then fails with\n * `AI_MissingToolResultsError`. The `ai` import is type-only.\n */\nimport type { UIMessage } from \"ai\";\n\n/**\n * Returns `messages` with every tool part whose call id is in `denied`, and whose state is still\n * `approval-responded`, moved to `output-denied` with its approval marked `approved: false`, as `ai`'s UI message\n * types and validator require for that state. The approval keeps its id and the person's reason. Messages it doesn't\n * change are returned as they are, so compare the result with `messages` to know whether to store it.\n *\n * Collect `denied` from `signedToolApproval()`'s `onRejected`, and keep it where your chat keeps its messages.\n */\nexport function settleDeniedApprovals<MESSAGE extends UIMessage>(\n messages: readonly MESSAGE[],\n denied: ReadonlySet<string>,\n): MESSAGE[] {\n return messages.map((message) => {\n let changed = false;\n const parts = message.parts.map((part) => {\n const tool = part as { toolCallId?: unknown; state?: unknown; approval?: object };\n if (typeof tool.toolCallId !== \"string\" || tool.state !== \"approval-responded\" || !denied.has(tool.toolCallId)) {\n return part;\n }\n changed = true;\n // `ai` 7.0.162 validates an `output-denied` part's approval with `approved: z.literal(false)`.\n return { ...part, state: \"output-denied\", approval: { ...tool.approval, approved: false } };\n });\n // The new part keeps its tool type, input and approval id; only its state and the approval's verdict change.\n return changed ? ({ ...message, parts } as MESSAGE) : message;\n });\n}\n"]}
@@ -0,0 +1,68 @@
1
+ /**
2
+ * `signedToolApproval()`: signed, fail-closed approvals over the AI SDK's call-level `toolApproval`. In `ai` 7.0.162,
3
+ * `generateText` and `streamText` call `toolApproval` once when a call is first seen, and again, inside
4
+ * `validateApprovedToolApprovals`, for every approved call in the incoming history before its `execute` runs. The
5
+ * adapter signs a pending request on the first call and verifies it on the second, then re-runs current policy, so a
6
+ * forged, stale or changed approval runs nothing. Cloudflare's `AIChatAgent` passes the same `toolApproval` to its own
7
+ * `streamText`, so one adapter serves both. The `ai` imports are type-only, so this subpath loads without `ai`.
8
+ */
9
+ import type { ToolApprovalConfiguration, ToolSet } from "ai";
10
+ import { type Recheck, type RejectionCause } from "../pending.js";
11
+ import type { PendingStore } from "../pending-store.js";
12
+ import type { ApprovalSigner } from "../signer.js";
13
+ /**
14
+ * Why `signedToolApproval()` denied an approved call: one of `verifyResolution()`'s causes, `unknown_request` when
15
+ * the store holds no pending request for the call, `policy_denied` when current policy or `recheck` said no, or
16
+ * `error` when a step threw.
17
+ */
18
+ export type ApprovalRejectionCause = RejectionCause | "policy_denied" | "error";
19
+ /** What `onRejected` receives when an approved call is denied. It holds no key material. */
20
+ export interface ApprovalRejection {
21
+ readonly callId: string;
22
+ readonly tool: string;
23
+ readonly cause: ApprovalRejectionCause;
24
+ /** The pending request's id, when the store held one. */
25
+ readonly requestId?: string;
26
+ /** What threw, for the cause `error`. */
27
+ readonly error?: unknown;
28
+ }
29
+ /** The options of `signedToolApproval()`. */
30
+ export interface SignedToolApprovalOptions<TOOLS extends ToolSet, RUNTIME_CONTEXT> {
31
+ /** Signs each pause and verifies it on resume. On a serverless host, use `hmacSigner()` over a persistent ring. */
32
+ readonly signer: ApprovalSigner;
33
+ /** Holds each pause until its resume. It must outlive the process when a pause may resume elsewhere. */
34
+ readonly store: PendingStore;
35
+ /**
36
+ * Which calls need a person: the same value you would pass as `toolApproval`. A tool's own `needsApproval` still
37
+ * applies when this policy has nothing to say about the tool.
38
+ */
39
+ readonly policy: ToolApprovalConfiguration<TOOLS, RUNTIME_CONTEXT>;
40
+ /** Runs current policy just before an approved call runs, and can turn the approval into a denial. */
41
+ readonly recheck: Recheck;
42
+ /** The version of your policy, signed into each pause so `recheck` can tell a pause made under an older one. */
43
+ readonly policyVersion?: string | (() => string | Promise<string>);
44
+ /**
45
+ * Called when an approved call is denied, with the cause, for your audit log. The adapter awaits what it returns,
46
+ * and if it throws, the error propagates and the call still does not run.
47
+ */
48
+ readonly onRejected?: (rejection: ApprovalRejection) => unknown;
49
+ /** Returns a fresh pending request id. Defaults to `crypto.randomUUID()`. */
50
+ readonly generateId?: () => string;
51
+ /** Returns the current time. Defaults to `new Date()`. */
52
+ readonly now?: () => Date;
53
+ }
54
+ /**
55
+ * Wraps an approval policy so every approval is signed, fails closed on resume, and is checked against current policy
56
+ * before the approved call runs. Pass the result as `toolApproval` to `generateText`, `streamText` or a
57
+ * `ToolLoopAgent`, or to the `streamText` in a Cloudflare `AIChatAgent`'s `onChatMessage`.
58
+ *
59
+ * When `policy` asks for a person, the adapter signs a pending request for the call and stores it by call id. When
60
+ * the call comes back approved, it takes that request from the store and runs it only if the request verifies, the
61
+ * call's id, tool and input match it, `policy` doesn't deny the call now, and `recheck` allows it. Otherwise the call
62
+ * is denied: its `execute` never runs, and the model reads a `not_applied` outcome that says why and what to do
63
+ * next. A pending request is used once, so a replayed approval is denied too.
64
+ *
65
+ * Keep the AI SDK's own `experimental_toolApprovalSecret` set as well. It is a second check, and it throws
66
+ * `InvalidToolApprovalSignatureError` for a bad signature instead of denying the call.
67
+ */
68
+ export declare function signedToolApproval<TOOLS extends ToolSet, RUNTIME_CONTEXT = unknown>(options: SignedToolApprovalOptions<TOOLS, RUNTIME_CONTEXT>): ToolApprovalConfiguration<TOOLS, RUNTIME_CONTEXT>;
@@ -0,0 +1,219 @@
1
+ import { SafetyError } from "../errors.js";
2
+ import { writeOutcome } from "../outcome.js";
3
+ import { signPending, verifyResolution } from "../pending.js";
4
+ import { renderOutcome } from "../render.js";
5
+ function normalize(status) {
6
+ if (status === undefined)
7
+ return { type: "not-applicable" };
8
+ if (typeof status === "string")
9
+ return { type: status };
10
+ return status;
11
+ }
12
+ function own(record, key) {
13
+ return record != null && Object.hasOwn(record, key) ? record[key] : undefined;
14
+ }
15
+ const AI_SCHEMA = Symbol.for("vercel.ai.schema");
16
+ /**
17
+ * Validates `value` against a tool's `contextSchema` the way `ai` 7.0.162's `asSchema` reads one: an `ai` schema
18
+ * object, a Standard Schema such as Zod's, or a function that returns either. Parsing can apply defaults and
19
+ * transforms, so the policy must see the parsed value, as it would without the adapter.
20
+ */
21
+ async function validateSchema(schema, value) {
22
+ try {
23
+ if (typeof schema === "object" && schema !== null && schema[AI_SCHEMA] === true) {
24
+ const validate = schema.validate;
25
+ if (validate == null)
26
+ return { ok: true, value };
27
+ const result = (await validate(value));
28
+ return result.success ? { ok: true, value: result.value } : { ok: false, cause: result.error };
29
+ }
30
+ if ((typeof schema === "object" || typeof schema === "function") && schema !== null && "~standard" in schema) {
31
+ const standard = schema["~standard"];
32
+ const result = (await standard.validate(value));
33
+ return "value" in result ? { ok: true, value: result.value } : { ok: false, cause: result.issues };
34
+ }
35
+ if (typeof schema === "function")
36
+ return validateSchema(schema(), value);
37
+ return { ok: false, cause: new TypeError("contextSchema is not a schema") };
38
+ }
39
+ catch (cause) {
40
+ return { ok: false, cause };
41
+ }
42
+ }
43
+ /** The tool's context as `ai` hands it to a per-tool policy or `needsApproval`: checked against its `contextSchema`. */
44
+ async function toolContext(args) {
45
+ const name = args.toolCall.toolName;
46
+ const context = own(args.toolsContext, name);
47
+ const schema = own(args.tools, name)?.contextSchema;
48
+ if (schema == null)
49
+ return context;
50
+ const result = await validateSchema(schema, context);
51
+ if (result.ok)
52
+ return result.value;
53
+ // `ai` throws here too, so the approval step fails as it would without the adapter.
54
+ throw new SafetyError("invalid_input", `the context of the tool ${JSON.stringify(name)} fails its contextSchema`, {
55
+ cause: result.cause,
56
+ });
57
+ }
58
+ async function deprecatedNeedsApproval(args) {
59
+ const { toolCall, tools, messages } = args;
60
+ const needs = own(tools, toolCall.toolName)?.needsApproval;
61
+ if (typeof needs !== "function")
62
+ return needs === true;
63
+ const context = await toolContext(args);
64
+ return ((await needs(toolCall.input, { toolCallId: toolCall.toolCallId, messages, context })) === true);
65
+ }
66
+ /** The status the policy gives a call now. With a generic function as `toolApproval`, `ai` skips `needsApproval`, so the adapter applies it. */
67
+ async function policyStatus(policy, args) {
68
+ const { toolCall } = args;
69
+ let status;
70
+ if (typeof policy === "function") {
71
+ status = normalize(await policy(args));
72
+ }
73
+ else {
74
+ const entry = own((policy ?? {}), toolCall.toolName);
75
+ if (typeof entry === "function") {
76
+ const options = {
77
+ toolCallId: toolCall.toolCallId,
78
+ messages: args.messages,
79
+ toolContext: await toolContext(args),
80
+ runtimeContext: args.runtimeContext,
81
+ };
82
+ status = normalize(await entry(toolCall.input, options));
83
+ }
84
+ else {
85
+ status = normalize(entry);
86
+ }
87
+ }
88
+ if (status.type === "not-applicable" && (await deprecatedNeedsApproval(args)))
89
+ return { type: "user-approval" };
90
+ return status;
91
+ }
92
+ /** True when the history ends with an approval of this call: the moment `ai` asks again before running it. */
93
+ function isApprovedResume(messages, callId) {
94
+ const last = messages.at(-1);
95
+ if (last?.role !== "tool")
96
+ return false;
97
+ const requests = new Set();
98
+ for (const message of messages) {
99
+ if (message.role !== "assistant" || typeof message.content === "string")
100
+ continue;
101
+ for (const part of message.content) {
102
+ if (part.type === "tool-approval-request" && part.toolCallId === callId)
103
+ requests.add(part.approvalId);
104
+ }
105
+ }
106
+ return last.content.some((part) => part.type === "tool-approval-response" && part.approved && requests.has(part.approvalId));
107
+ }
108
+ const NOT_VERIFIED_NEXT = "Call the tool again to ask for a new approval, or tell the user that it did not run";
109
+ /**
110
+ * A denial the model can act on: a rendered `not_applied` outcome as the denial's reason, in the same shape as
111
+ * `toAiToolResult()`'s value, so the sentence and the payload both reach the model.
112
+ */
113
+ function denial(tool, reason, next) {
114
+ try {
115
+ const retry = reason === "POLICY_DENIED" ? "never" : "same_key";
116
+ const outcome = writeOutcome({ kind: "not_applied", operation: tool, reason, next, retry });
117
+ const { text, payload } = renderOutcome(outcome);
118
+ return { type: "denied", reason: JSON.stringify({ message: text, ...payload }) };
119
+ }
120
+ catch {
121
+ // A tool name writeOutcome() refuses as an operation still gets a denial; only the wording is plainer.
122
+ return { type: "denied", reason: `The call did not run, and nothing changed. Next: ${next}.` };
123
+ }
124
+ }
125
+ function notVerified(args, cause, extra = {}) {
126
+ const { toolCallId: callId, toolName: tool } = args.toolCall;
127
+ return {
128
+ status: denial(tool, "APPROVAL_NOT_VERIFIED", NOT_VERIFIED_NEXT),
129
+ rejection: { callId, tool, cause, ...extra },
130
+ };
131
+ }
132
+ /**
133
+ * The second call for an approved call: take and verify the stored request, re-run current policy, then `recheck`.
134
+ * Every failure denies. It never calls `onRejected`, so a hook that throws can't be mistaken for a failed step.
135
+ */
136
+ async function resume(options, args) {
137
+ const { toolCall } = args;
138
+ const pending = await options.store.take(toolCall.toolCallId);
139
+ if (pending === undefined)
140
+ return notVerified(args, "unknown_request");
141
+ const call = { callId: toolCall.toolCallId, tool: toolCall.toolName, input: toolCall.input };
142
+ const check = await verifyResolution(pending, { requestId: pending.id, decision: "allow" }, { signer: options.signer, call });
143
+ if (!check.ok)
144
+ return notVerified(args, check.cause, { requestId: pending.id });
145
+ const now = await policyStatus(options.policy, args);
146
+ const policyDeny = now.type === "denied" ? (now.reason ?? "the approval policy now denies this call") : undefined;
147
+ const recheck = policyDeny === undefined ? await options.recheck(pending, toolCall.input) : undefined;
148
+ const deny = policyDeny ?? (typeof recheck === "object" && recheck !== null ? recheck.deny : undefined);
149
+ if (deny !== undefined || recheck !== "allow") {
150
+ const why = deny ?? "the policy check did not allow it";
151
+ const next = `Tell the user that current policy blocks this call: ${why}`;
152
+ return {
153
+ status: denial(toolCall.toolName, "POLICY_DENIED", next),
154
+ rejection: {
155
+ callId: toolCall.toolCallId,
156
+ tool: toolCall.toolName,
157
+ cause: "policy_denied",
158
+ requestId: pending.id,
159
+ },
160
+ };
161
+ }
162
+ // `ai` runs a call whose status here is anything but `denied`, so only a full pass returns `approved`.
163
+ return { status: { type: "approved" } };
164
+ }
165
+ /** The first call: ask the policy, and sign and store a pending request when it wants a person. */
166
+ async function pause(options, args) {
167
+ const status = await policyStatus(options.policy, args);
168
+ if (status.type !== "user-approval")
169
+ return status;
170
+ const { toolCall } = args;
171
+ const version = typeof options.policyVersion === "function" ? await options.policyVersion() : options.policyVersion;
172
+ const pending = await signPending({
173
+ kind: "approval",
174
+ callId: toolCall.toolCallId,
175
+ tool: toolCall.toolName,
176
+ input: toolCall.input,
177
+ ...(version === undefined ? {} : { policyVersion: version }),
178
+ ...(status.reason === undefined ? {} : { reason: status.reason }),
179
+ }, options.signer, { ...(options.generateId ? { generateId: options.generateId } : {}), ...(options.now ? { now: options.now } : {}) });
180
+ await options.store.put(pending);
181
+ return status;
182
+ }
183
+ /**
184
+ * Wraps an approval policy so every approval is signed, fails closed on resume, and is checked against current policy
185
+ * before the approved call runs. Pass the result as `toolApproval` to `generateText`, `streamText` or a
186
+ * `ToolLoopAgent`, or to the `streamText` in a Cloudflare `AIChatAgent`'s `onChatMessage`.
187
+ *
188
+ * When `policy` asks for a person, the adapter signs a pending request for the call and stores it by call id. When
189
+ * the call comes back approved, it takes that request from the store and runs it only if the request verifies, the
190
+ * call's id, tool and input match it, `policy` doesn't deny the call now, and `recheck` allows it. Otherwise the call
191
+ * is denied: its `execute` never runs, and the model reads a `not_applied` outcome that says why and what to do
192
+ * next. A pending request is used once, so a replayed approval is denied too.
193
+ *
194
+ * Keep the AI SDK's own `experimental_toolApprovalSecret` set as well. It is a second check, and it throws
195
+ * `InvalidToolApprovalSignatureError` for a bad signature instead of denying the call.
196
+ */
197
+ export function signedToolApproval(options) {
198
+ // The policy is only ever called with the arguments `ai` gave the adapter, so erasing its generics loses nothing.
199
+ const loose = options;
200
+ const approve = async (args) => {
201
+ if (!isApprovedResume(args.messages, args.toolCall.toolCallId))
202
+ return pause(loose, args);
203
+ let decision;
204
+ try {
205
+ decision = await resume(loose, args);
206
+ }
207
+ catch (error) {
208
+ // Fail closed: a store, signer, policy or recheck that throws denies the call instead of letting it run.
209
+ decision = notVerified(args, "error", { error });
210
+ }
211
+ // Outside the try, so onRejected runs once per denial, and an error it throws propagates as it is.
212
+ if (decision.rejection !== undefined)
213
+ await loose.onRejected?.(decision.rejection);
214
+ return decision.status;
215
+ };
216
+ // `ai` accepts a generic approval function for any tool set; its parameter type names the set's generics.
217
+ return approve;
218
+ }
219
+ //# sourceMappingURL=tool-approval.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-approval.js","sourceRoot":"","sources":["../../src/ai/tool-approval.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAqC,WAAW,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAEjG,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAiE7C,SAAS,SAAS,CAAC,MAAe;IAChC,IAAI,MAA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,MAAM,KAAK,CAAC,UAAU,EAAE,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;QACnF,OAAO,QAAQ,CAAC,MAAM,CAAC;IACzB,CAAC,CAAC;IACF,0GAA0G;IAC1G,OAAO,OAAuE,CAAC;AACjF,CAAC","sourcesContent":["/**\n * `signedToolApproval()`: signed, fail-closed approvals over the AI SDK's call-level `toolApproval`. In `ai` 7.0.162,\n * `generateText` and `streamText` call `toolApproval` once when a call is first seen, and again, inside\n * `validateApprovedToolApprovals`, for every approved call in the incoming history before its `execute` runs. The\n * adapter signs a pending request on the first call and verifies it on the second, then re-runs current policy, so a\n * forged, stale or changed approval runs nothing. Cloudflare's `AIChatAgent` passes the same `toolApproval` to its own\n * `streamText`, so one adapter serves both. The `ai` imports are type-only, so this subpath loads without `ai`.\n */\nimport type { ModelMessage, ToolApprovalConfiguration, ToolApprovalStatus, ToolSet } from \"ai\";\nimport { SafetyError } from \"../errors.js\";\nimport { writeOutcome } from \"../outcome.js\";\nimport { type Recheck, type RejectionCause, signPending, verifyResolution } from \"../pending.js\";\nimport type { PendingStore } from \"../pending-store.js\";\nimport { renderOutcome } from \"../render.js\";\nimport type { ApprovalSigner } from \"../signer.js\";\n\n/**\n * Why `signedToolApproval()` denied an approved call: one of `verifyResolution()`'s causes, `unknown_request` when\n * the store holds no pending request for the call, `policy_denied` when current policy or `recheck` said no, or\n * `error` when a step threw.\n */\nexport type ApprovalRejectionCause = RejectionCause | \"policy_denied\" | \"error\";\n\n/** What `onRejected` receives when an approved call is denied. It holds no key material. */\nexport interface ApprovalRejection {\n readonly callId: string;\n readonly tool: string;\n readonly cause: ApprovalRejectionCause;\n /** The pending request's id, when the store held one. */\n readonly requestId?: string;\n /** What threw, for the cause `error`. */\n readonly error?: unknown;\n}\n\n/** The options of `signedToolApproval()`. */\nexport interface SignedToolApprovalOptions<TOOLS extends ToolSet, RUNTIME_CONTEXT> {\n /** Signs each pause and verifies it on resume. On a serverless host, use `hmacSigner()` over a persistent ring. */\n readonly signer: ApprovalSigner;\n /** Holds each pause until its resume. It must outlive the process when a pause may resume elsewhere. */\n readonly store: PendingStore;\n /**\n * Which calls need a person: the same value you would pass as `toolApproval`. A tool's own `needsApproval` still\n * applies when this policy has nothing to say about the tool.\n */\n readonly policy: ToolApprovalConfiguration<TOOLS, RUNTIME_CONTEXT>;\n /** Runs current policy just before an approved call runs, and can turn the approval into a denial. */\n readonly recheck: Recheck;\n /** The version of your policy, signed into each pause so `recheck` can tell a pause made under an older one. */\n readonly policyVersion?: string | (() => string | Promise<string>);\n /**\n * Called when an approved call is denied, with the cause, for your audit log. The adapter awaits what it returns,\n * and if it throws, the error propagates and the call still does not run.\n */\n readonly onRejected?: (rejection: ApprovalRejection) => unknown;\n /** Returns a fresh pending 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 loose shapes the adapter reads. `ai` types them per tool set, which this file can't name without its generics.\ninterface Call {\n readonly toolCallId: string;\n readonly toolName: string;\n readonly input: unknown;\n}\ninterface ApprovalArgs {\n readonly toolCall: Call;\n readonly tools:\n | Readonly<Record<string, { readonly needsApproval?: unknown; readonly contextSchema?: unknown }>>\n | undefined;\n readonly toolsContext: Readonly<Record<string, unknown>> | undefined;\n readonly runtimeContext: unknown;\n readonly messages: readonly ModelMessage[];\n}\ntype Status = Exclude<ToolApprovalStatus, string | undefined>;\ntype PolicyFunction = (...args: unknown[]) => unknown;\n\nfunction normalize(status: unknown): Status {\n if (status === undefined) return { type: \"not-applicable\" };\n if (typeof status === \"string\") return { type: status } as Status;\n return status as Status;\n}\n\nfunction own<T>(record: Readonly<Record<string, T>> | undefined, key: string): T | undefined {\n return record != null && Object.hasOwn(record, key) ? record[key] : undefined;\n}\n\ntype Validated = { readonly ok: true; readonly value: unknown } | { readonly ok: false; readonly cause: unknown };\n\nconst AI_SCHEMA = Symbol.for(\"vercel.ai.schema\");\n\n/**\n * Validates `value` against a tool's `contextSchema` the way `ai` 7.0.162's `asSchema` reads one: an `ai` schema\n * object, a Standard Schema such as Zod's, or a function that returns either. Parsing can apply defaults and\n * transforms, so the policy must see the parsed value, as it would without the adapter.\n */\nasync function validateSchema(schema: unknown, value: unknown): Promise<Validated> {\n try {\n if (typeof schema === \"object\" && schema !== null && (schema as Record<symbol, unknown>)[AI_SCHEMA] === true) {\n const validate = (schema as { validate?: (value: unknown) => unknown }).validate;\n if (validate == null) return { ok: true, value };\n const result = (await validate(value)) as { success: boolean; value?: unknown; error?: unknown };\n return result.success ? { ok: true, value: result.value } : { ok: false, cause: result.error };\n }\n if ((typeof schema === \"object\" || typeof schema === \"function\") && schema !== null && \"~standard\" in schema) {\n const standard = (schema as { \"~standard\": { validate(value: unknown): unknown } })[\"~standard\"];\n const result = (await standard.validate(value)) as { value?: unknown; issues?: unknown };\n return \"value\" in result ? { ok: true, value: result.value } : { ok: false, cause: result.issues };\n }\n if (typeof schema === \"function\") return validateSchema((schema as () => unknown)(), value);\n return { ok: false, cause: new TypeError(\"contextSchema is not a schema\") };\n } catch (cause) {\n return { ok: false, cause };\n }\n}\n\n/** The tool's context as `ai` hands it to a per-tool policy or `needsApproval`: checked against its `contextSchema`. */\nasync function toolContext(args: ApprovalArgs): Promise<unknown> {\n const name = args.toolCall.toolName;\n const context = own(args.toolsContext, name);\n const schema = own(args.tools, name)?.contextSchema;\n if (schema == null) return context;\n const result = await validateSchema(schema, context);\n if (result.ok) return result.value;\n // `ai` throws here too, so the approval step fails as it would without the adapter.\n throw new SafetyError(\"invalid_input\", `the context of the tool ${JSON.stringify(name)} fails its contextSchema`, {\n cause: result.cause,\n });\n}\n\nasync function deprecatedNeedsApproval(args: ApprovalArgs): Promise<boolean> {\n const { toolCall, tools, messages } = args;\n const needs = own(tools, toolCall.toolName)?.needsApproval;\n if (typeof needs !== \"function\") return needs === true;\n const context = await toolContext(args);\n return (\n (await (needs as PolicyFunction)(toolCall.input, { toolCallId: toolCall.toolCallId, messages, context })) === true\n );\n}\n\n/** The status the policy gives a call now. With a generic function as `toolApproval`, `ai` skips `needsApproval`, so the adapter applies it. */\nasync function policyStatus(policy: unknown, args: ApprovalArgs): Promise<Status> {\n const { toolCall } = args;\n let status: Status;\n if (typeof policy === \"function\") {\n status = normalize(await (policy as PolicyFunction)(args));\n } else {\n const entry = own((policy ?? {}) as Record<string, unknown>, toolCall.toolName);\n if (typeof entry === \"function\") {\n const options = {\n toolCallId: toolCall.toolCallId,\n messages: args.messages,\n toolContext: await toolContext(args),\n runtimeContext: args.runtimeContext,\n };\n status = normalize(await (entry as PolicyFunction)(toolCall.input, options));\n } else {\n status = normalize(entry);\n }\n }\n if (status.type === \"not-applicable\" && (await deprecatedNeedsApproval(args))) return { type: \"user-approval\" };\n return status;\n}\n\n/** True when the history ends with an approval of this call: the moment `ai` asks again before running it. */\nfunction isApprovedResume(messages: readonly ModelMessage[], callId: string): boolean {\n const last = messages.at(-1);\n if (last?.role !== \"tool\") return false;\n const requests = new Set<string>();\n for (const message of messages) {\n if (message.role !== \"assistant\" || typeof message.content === \"string\") continue;\n for (const part of message.content) {\n if (part.type === \"tool-approval-request\" && part.toolCallId === callId) requests.add(part.approvalId);\n }\n }\n return last.content.some(\n (part) => part.type === \"tool-approval-response\" && part.approved && requests.has(part.approvalId),\n );\n}\n\nconst NOT_VERIFIED_NEXT = \"Call the tool again to ask for a new approval, or tell the user that it did not run\";\n\n/**\n * A denial the model can act on: a rendered `not_applied` outcome as the denial's reason, in the same shape as\n * `toAiToolResult()`'s value, so the sentence and the payload both reach the model.\n */\nfunction denial(tool: string, reason: \"APPROVAL_NOT_VERIFIED\" | \"POLICY_DENIED\", next: string): ToolApprovalStatus {\n try {\n const retry = reason === \"POLICY_DENIED\" ? \"never\" : \"same_key\";\n const outcome = writeOutcome({ kind: \"not_applied\", operation: tool, reason, next, retry });\n const { text, payload } = renderOutcome(outcome);\n return { type: \"denied\", reason: JSON.stringify({ message: text, ...payload }) };\n } catch {\n // A tool name writeOutcome() refuses as an operation still gets a denial; only the wording is plainer.\n return { type: \"denied\", reason: `The call did not run, and nothing changed. Next: ${next}.` };\n }\n}\n\n/** What the resume decided: the status for `ai`, and, for a denial, what `onRejected` receives. */\ninterface Decision {\n readonly status: ToolApprovalStatus;\n readonly rejection?: ApprovalRejection;\n}\n\ntype Options = SignedToolApprovalOptions<ToolSet, unknown>;\n\nfunction notVerified(\n args: ApprovalArgs,\n cause: ApprovalRejectionCause,\n extra: Partial<ApprovalRejection> = {},\n): Decision {\n const { toolCallId: callId, toolName: tool } = args.toolCall;\n return {\n status: denial(tool, \"APPROVAL_NOT_VERIFIED\", NOT_VERIFIED_NEXT),\n rejection: { callId, tool, cause, ...extra },\n };\n}\n\n/**\n * The second call for an approved call: take and verify the stored request, re-run current policy, then `recheck`.\n * Every failure denies. It never calls `onRejected`, so a hook that throws can't be mistaken for a failed step.\n */\nasync function resume(options: Options, args: ApprovalArgs): Promise<Decision> {\n const { toolCall } = args;\n const pending = await options.store.take(toolCall.toolCallId);\n if (pending === undefined) return notVerified(args, \"unknown_request\");\n const call = { callId: toolCall.toolCallId, tool: toolCall.toolName, input: toolCall.input };\n const check = await verifyResolution(\n pending,\n { requestId: pending.id, decision: \"allow\" },\n { signer: options.signer, call },\n );\n if (!check.ok) return notVerified(args, check.cause, { requestId: pending.id });\n const now = await policyStatus(options.policy, args);\n const policyDeny = now.type === \"denied\" ? (now.reason ?? \"the approval policy now denies this call\") : undefined;\n const recheck = policyDeny === undefined ? await options.recheck(pending, toolCall.input) : undefined;\n const deny = policyDeny ?? (typeof recheck === \"object\" && recheck !== null ? recheck.deny : undefined);\n if (deny !== undefined || recheck !== \"allow\") {\n const why = deny ?? \"the policy check did not allow it\";\n const next = `Tell the user that current policy blocks this call: ${why}`;\n return {\n status: denial(toolCall.toolName, \"POLICY_DENIED\", next),\n rejection: {\n callId: toolCall.toolCallId,\n tool: toolCall.toolName,\n cause: \"policy_denied\",\n requestId: pending.id,\n },\n };\n }\n // `ai` runs a call whose status here is anything but `denied`, so only a full pass returns `approved`.\n return { status: { type: \"approved\" } };\n}\n\n/** The first call: ask the policy, and sign and store a pending request when it wants a person. */\nasync function pause(options: Options, args: ApprovalArgs): Promise<Status> {\n const status = await policyStatus(options.policy, args);\n if (status.type !== \"user-approval\") return status;\n const { toolCall } = args;\n const version = typeof options.policyVersion === \"function\" ? await options.policyVersion() : options.policyVersion;\n const pending = await signPending(\n {\n kind: \"approval\",\n callId: toolCall.toolCallId,\n tool: toolCall.toolName,\n input: toolCall.input,\n ...(version === undefined ? {} : { policyVersion: version }),\n ...(status.reason === undefined ? {} : { reason: status.reason }),\n },\n options.signer,\n { ...(options.generateId ? { generateId: options.generateId } : {}), ...(options.now ? { now: options.now } : {}) },\n );\n await options.store.put(pending);\n return status;\n}\n\n/**\n * Wraps an approval policy so every approval is signed, fails closed on resume, and is checked against current policy\n * before the approved call runs. Pass the result as `toolApproval` to `generateText`, `streamText` or a\n * `ToolLoopAgent`, or to the `streamText` in a Cloudflare `AIChatAgent`'s `onChatMessage`.\n *\n * When `policy` asks for a person, the adapter signs a pending request for the call and stores it by call id. When\n * the call comes back approved, it takes that request from the store and runs it only if the request verifies, the\n * call's id, tool and input match it, `policy` doesn't deny the call now, and `recheck` allows it. Otherwise the call\n * is denied: its `execute` never runs, and the model reads a `not_applied` outcome that says why and what to do\n * next. A pending request is used once, so a replayed approval is denied too.\n *\n * Keep the AI SDK's own `experimental_toolApprovalSecret` set as well. It is a second check, and it throws\n * `InvalidToolApprovalSignatureError` for a bad signature instead of denying the call.\n */\nexport function signedToolApproval<TOOLS extends ToolSet, RUNTIME_CONTEXT = unknown>(\n options: SignedToolApprovalOptions<TOOLS, RUNTIME_CONTEXT>,\n): ToolApprovalConfiguration<TOOLS, RUNTIME_CONTEXT> {\n // The policy is only ever called with the arguments `ai` gave the adapter, so erasing its generics loses nothing.\n const loose = options as unknown as SignedToolApprovalOptions<ToolSet, unknown>;\n const approve = async (args: ApprovalArgs): Promise<ToolApprovalStatus> => {\n if (!isApprovedResume(args.messages, args.toolCall.toolCallId)) return pause(loose, args);\n let decision: Decision;\n try {\n decision = await resume(loose, args);\n } catch (error) {\n // Fail closed: a store, signer, policy or recheck that throws denies the call instead of letting it run.\n decision = notVerified(args, \"error\", { error });\n }\n // Outside the try, so onRejected runs once per denial, and an error it throws propagates as it is.\n if (decision.rejection !== undefined) await loose.onRejected?.(decision.rejection);\n return decision.status;\n };\n // `ai` accepts a generic approval function for any tool set; its parameter type names the set's generics.\n return approve as unknown as ToolApprovalConfiguration<TOOLS, RUNTIME_CONTEXT>;\n}\n"]}
@@ -0,0 +1,23 @@
1
+ /**
2
+ * `toAiToolResult()`: a write outcome as an `ai` tool result. In `ai` 7.0.162 a tool's `toModelOutput` returns one of
3
+ * the `ToolResultOutput` variants of `@ai-sdk/provider-utils` 5.0.74, and the `error-json` variant is the one that
4
+ * sets the provider's error flag, so every kind but `applied` uses it. The import is type-only, so this subpath loads
5
+ * without `ai` installed.
6
+ */
7
+ import type { ToolResultOutput } from "@ai-sdk/provider-utils";
8
+ import type { WriteOutcome } from "../outcome.js";
9
+ /**
10
+ * Turns a write outcome into the result the model reads, for use as a tool's `toModelOutput`. The value holds the
11
+ * rendered sentences as `message` beside the outcome's fields. It is an `error-json` result for every kind except
12
+ * `applied`, which is a `json` result.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * const refund = tool({
17
+ * inputSchema,
18
+ * execute: async (input) => issueRefund(input), // returns a WriteOutcome
19
+ * toModelOutput: ({ output }) => toAiToolResult(output),
20
+ * });
21
+ * ```
22
+ */
23
+ export declare function toAiToolResult(outcome: WriteOutcome): ToolResultOutput;
@@ -0,0 +1,20 @@
1
+ import { renderOutcome } from "../render.js";
2
+ /**
3
+ * Turns a write outcome into the result the model reads, for use as a tool's `toModelOutput`. The value holds the
4
+ * rendered sentences as `message` beside the outcome's fields. It is an `error-json` result for every kind except
5
+ * `applied`, which is a `json` result.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * const refund = tool({
10
+ * inputSchema,
11
+ * execute: async (input) => issueRefund(input), // returns a WriteOutcome
12
+ * toModelOutput: ({ output }) => toAiToolResult(output),
13
+ * });
14
+ * ```
15
+ */
16
+ export function toAiToolResult(outcome) {
17
+ const { text, payload, isError } = renderOutcome(outcome);
18
+ return { type: isError ? "error-json" : "json", value: { message: text, ...payload } };
19
+ }
20
+ //# sourceMappingURL=tool-result.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-result.js","sourceRoot":"","sources":["../../src/ai/tool-result.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAE7C;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,cAAc,CAAC,OAAqB;IAClD,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,aAAa,CAAC,OAAO,CAAC,CAAC;IAC1D,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,EAAE,CAAC;AACzF,CAAC","sourcesContent":["/**\n * `toAiToolResult()`: a write outcome as an `ai` tool result. In `ai` 7.0.162 a tool's `toModelOutput` returns one of\n * the `ToolResultOutput` variants of `@ai-sdk/provider-utils` 5.0.74, and the `error-json` variant is the one that\n * sets the provider's error flag, so every kind but `applied` uses it. The import is type-only, so this subpath loads\n * without `ai` installed.\n */\nimport type { ToolResultOutput } from \"@ai-sdk/provider-utils\";\nimport type { WriteOutcome } from \"../outcome.js\";\nimport { renderOutcome } from \"../render.js\";\n\n/**\n * Turns a write outcome into the result the model reads, for use as a tool's `toModelOutput`. The value holds the\n * rendered sentences as `message` beside the outcome's fields. It is an `error-json` result for every kind except\n * `applied`, which is a `json` result.\n *\n * @example\n * ```ts\n * const refund = tool({\n * inputSchema,\n * execute: async (input) => issueRefund(input), // returns a WriteOutcome\n * toModelOutput: ({ output }) => toAiToolResult(output),\n * });\n * ```\n */\nexport function toAiToolResult(outcome: WriteOutcome): ToolResultOutput {\n const { text, payload, isError } = renderOutcome(outcome);\n return { type: isError ? \"error-json\" : \"json\", value: { message: text, ...payload } };\n}\n"]}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Makes every string model id fail with a `SafetyError`, code `default_provider`, before any request. It sets the AI
3
+ * SDK's `globalThis.AI_SDK_DEFAULT_PROVIDER` to a provider whose model factories all throw, so a string id can never
4
+ * fall through to Vercel AI Gateway and an ambient gateway key or OIDC token. Call it once at startup, before the
5
+ * agent's first model call. Calling it again does nothing. The global is left read-only, so later code that assigns
6
+ * another default provider throws a `TypeError` in strict mode rather than reopening the path.
7
+ *
8
+ * Throws a `SafetyError`, code `default_provider`, when another default provider is already set, because string ids
9
+ * would then reach a provider whose credentials this package can't see. Clear that setting and pass models built with
10
+ * `explicitProvider()` instead.
11
+ */
12
+ export declare function assertNoDefaultProvider(): void;
@@ -0,0 +1,72 @@
1
+ /**
2
+ * `assertNoDefaultProvider()`: makes a string model id fail. In `ai` 7.0.162, `generateText`, `streamText` and the
3
+ * other calls resolve a string model id through `globalThis.AI_SDK_DEFAULT_PROVIDER ?? gateway`, and the gateway is
4
+ * Vercel AI Gateway, which authenticates with `AI_GATEWAY_API_KEY` or a Vercel OIDC token from the environment. Setting
5
+ * the global to a provider that refuses every model closes that path before any request is built.
6
+ */
7
+ import { SafetyError } from "../errors.js";
8
+ // A registered symbol, so a second copy of the package recognises the refusing provider as its own.
9
+ const REFUSING_PROVIDER = Symbol.for("buildanagent.agent-safety.RefusingDefaultProvider");
10
+ // Every model factory `ai` 7.0.162 looks up on the default provider, in resolve-model.ts and batch.ts.
11
+ const MODEL_FACTORIES = [
12
+ "languageModel",
13
+ "embeddingModel",
14
+ "imageModel",
15
+ "transcriptionModel",
16
+ "speechModel",
17
+ "rerankingModel",
18
+ "videoModel",
19
+ "speechTranslationModel",
20
+ "decisionModel",
21
+ "evaluationModel",
22
+ "experimental_batch",
23
+ ];
24
+ function refusal(kind, modelId) {
25
+ const id = typeof modelId === "string" ? ` "${modelId}"` : "";
26
+ return new SafetyError("default_provider", `A string model id${id} was resolved for a ${kind}; string ids route through a default provider, which may use a credential nobody configured. Pass a model built with explicitProvider() instead.`);
27
+ }
28
+ function refusingProvider() {
29
+ const provider = { specificationVersion: "v4" };
30
+ for (const kind of MODEL_FACTORIES) {
31
+ provider[kind] = (modelId) => {
32
+ throw refusal(kind, modelId);
33
+ };
34
+ }
35
+ Object.defineProperty(provider, REFUSING_PROVIDER, { value: true });
36
+ return Object.freeze(provider);
37
+ }
38
+ // The marker is not a security boundary: code that can write to `globalThis` can already install any provider before
39
+ // this runs. It only recognises our own provider on a repeated call.
40
+ function isRefusingProvider(value) {
41
+ return typeof value === "object" && value !== null && value[REFUSING_PROVIDER] === true;
42
+ }
43
+ /**
44
+ * Makes every string model id fail with a `SafetyError`, code `default_provider`, before any request. It sets the AI
45
+ * SDK's `globalThis.AI_SDK_DEFAULT_PROVIDER` to a provider whose model factories all throw, so a string id can never
46
+ * fall through to Vercel AI Gateway and an ambient gateway key or OIDC token. Call it once at startup, before the
47
+ * agent's first model call. Calling it again does nothing. The global is left read-only, so later code that assigns
48
+ * another default provider throws a `TypeError` in strict mode rather than reopening the path.
49
+ *
50
+ * Throws a `SafetyError`, code `default_provider`, when another default provider is already set, because string ids
51
+ * would then reach a provider whose credentials this package can't see. Clear that setting and pass models built with
52
+ * `explicitProvider()` instead.
53
+ */
54
+ export function assertNoDefaultProvider() {
55
+ const global = globalThis;
56
+ const current = global.AI_SDK_DEFAULT_PROVIDER;
57
+ if (isRefusingProvider(current))
58
+ return;
59
+ // `ai` reads the global with `??`, so null means "unset" there too and falls through to Vercel AI Gateway.
60
+ if (current !== undefined && current !== null) {
61
+ throw new SafetyError("default_provider", "globalThis.AI_SDK_DEFAULT_PROVIDER is already set, so string model ids would reach a provider whose credential nobody checked. Remove it and pass models built with explicitProvider().");
62
+ }
63
+ // Read-only, so a later plain assignment throws in strict code instead of quietly reopening the path. It stays
64
+ // configurable, so a test can delete it.
65
+ Object.defineProperty(global, "AI_SDK_DEFAULT_PROVIDER", {
66
+ value: refusingProvider(),
67
+ writable: false,
68
+ enumerable: true,
69
+ configurable: true,
70
+ });
71
+ }
72
+ //# sourceMappingURL=default-provider.js.map