@odingard/guardian-vercel-ai 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,111 @@
1
- # Temporary Holding Version
1
+ # @odingard/guardian-vercel-ai
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Vercel AI SDK adapter for Guardian — route every tool `execute` through a
4
+ deterministic `ALLOW` / `ASK` / `DENY` authority decision before anything
5
+ runs. The agent proposes; the human decides.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @odingard/guardian-vercel-ai @odingard/guardian-sdk ai
11
+ ```
12
+
13
+ `ai` and `@odingard/guardian-sdk` are peer dependencies.
14
+
15
+ ## Two execution modes
16
+
17
+ | Mode | When to use | What happens on `ALLOW` |
18
+ | --- | --- | --- |
19
+ | `remote` (default) | The tool name is a registered Guardian catalog entry — a bounded HTTP(S) endpoint Guardian calls itself | `client.execute` performs the call; the call resolves to `{ guardian: { decision: "ALLOW", requestId, receipt } }`. The local `execute` impl **never runs** |
20
+ | `inProcess` (opt-in) | The local `execute` impl IS the tool — the common framework case | The impl runs (only after the capability is issued), then `client.execute` redeems + records the evidence; the call resolves to the impl's output |
21
+
22
+ Set `mode` for every tool or `modes` per tool name:
23
+
24
+ ```ts
25
+ withGuardian(tools, {
26
+ client,
27
+ connectionId: "con_…",
28
+ modes: { refund_order: "inProcess" }, // everything else remote
29
+ });
30
+ ```
31
+
32
+ `inProcess` needs a `transport: "record"` catalog entry on the connection so
33
+ `execute` commits evidence instead of performing an HTTP call. The adapter
34
+ auto-proposes `mcp.install` of that entry the first time each tool is called
35
+ (it goes through the same ALLOW/ASK/DENY gate — a human may need to approve
36
+ it once). **This requires the WO-021 control plane**; a client that can't
37
+ form the proposal raises `GuardianRecordTransportRequired` before any
38
+ network call. Pass `installRecordTransport: false` to opt out (entries must
39
+ then be installed some other way).
40
+
41
+ ## Usage
42
+
43
+ ```ts
44
+ import { tool } from "ai";
45
+ import { z } from "zod";
46
+ import { createGuardianClient } from "@odingard/guardian-sdk";
47
+ import {
48
+ GuardianApprovalPending,
49
+ GuardianDenied,
50
+ withGuardian,
51
+ } from "@odingard/guardian-vercel-ai";
52
+
53
+ const guardian = createGuardianClient({
54
+ baseUrl: "https://guardian-api.odingard.com",
55
+ credential: process.env.GUARDIAN_AGENT_CREDENTIAL!,
56
+ });
57
+
58
+ const tools = withGuardian(
59
+ {
60
+ refund_order: tool({
61
+ description: "Refund an order",
62
+ inputSchema: z.object({ orderId: z.string(), amount: z.number() }),
63
+ execute: async ({ orderId, amount }) => refund(orderId, amount),
64
+ }),
65
+ },
66
+ {
67
+ client: guardian,
68
+ connectionId: "con_…",
69
+ agentName: "billing-agent",
70
+ mode: "inProcess",
71
+ },
72
+ );
73
+
74
+ try {
75
+ await generateText({ model, tools, prompt });
76
+ } catch (err) {
77
+ if (err instanceof GuardianApprovalPending) {
78
+ // err.requestId — surface to a human approver, then:
79
+ const { output, receipt } = await err.resume();
80
+ } else if (err instanceof GuardianDenied) {
81
+ // err.reasonCode — refused before execution
82
+ }
83
+ }
84
+ ```
85
+
86
+ ## What the triad means here
87
+
88
+ - `ALLOW` — Guardian mints a single-use capability. Remote: `client.execute`
89
+ performs the catalog call and returns the receipt. In-process: the local
90
+ impl runs, then `client.execute` redeems + records it. A failed
91
+ redemption throws `GuardianExecutionFailed` — and in `inProcess` mode the
92
+ impl's own error propagates before the record call.
93
+ - `ASK` — throws `GuardianApprovalPending` carrying `requestId`. After the
94
+ human approves in Guardian, `pending.resume()` claims the capability and
95
+ completes the call. With `onAsk: "result"` the tool instead returns a
96
+ serializable `{ guardian: { decision: "ASK", requestId, … } }` to the
97
+ model.
98
+ - `DENY` — throws `GuardianDenied` carrying `reasonCode` (or returns
99
+ `{ guardian: { decision: "DENY", … } }` with `onDeny: "result"`).
100
+
101
+ Nothing runs before a decision, and no tool ever runs without a capability
102
+ issued for that exact request.
103
+
104
+ Options: `client`, `connectionId`, `adapterId?`, `agentName?`, `mode?`,
105
+ `modes?`, `installRecordTransport?`, `purpose?` (string or
106
+ `(toolName, input) => string`), `onAsk?`, `onDeny?`, `onReceipt?` (called
107
+ with `{ toolName, requestId, receipt }` after each `ALLOW`).
108
+
109
+ ## License
110
+
111
+ Apache-2.0
package/dist/index.js ADDED
@@ -0,0 +1,373 @@
1
+ // src/core.ts
2
+ var GuardianDenied = class extends Error {
3
+ decision = "DENY";
4
+ toolName;
5
+ reasonCode;
6
+ requestId;
7
+ constructor(args) {
8
+ super(
9
+ `Guardian denied "${args.toolName}" (reasonCode=${args.reasonCode})` + (args.requestId ? ` requestId=${args.requestId}` : "")
10
+ );
11
+ this.name = "GuardianDenied";
12
+ this.toolName = args.toolName;
13
+ this.reasonCode = args.reasonCode;
14
+ this.requestId = args.requestId;
15
+ }
16
+ };
17
+ var GuardianExecutionFailed = class extends Error {
18
+ toolName;
19
+ requestId;
20
+ reasonCode;
21
+ /**
22
+ * inProcess only: the local tool already ran before Guardian's final
23
+ * redemption refused it. The effect happened without a recorded receipt;
24
+ * treat it as an incident, never as a successful governed action.
25
+ */
26
+ localEffectRan;
27
+ constructor(args) {
28
+ super(
29
+ `Guardian execution of "${args.toolName}" failed (requestId=${args.requestId}, reasonCode=${args.reasonCode}${args.localEffectRan ? ", localEffectRan=true" : ""})`
30
+ );
31
+ this.name = "GuardianExecutionFailed";
32
+ this.toolName = args.toolName;
33
+ this.requestId = args.requestId;
34
+ this.reasonCode = args.reasonCode;
35
+ this.localEffectRan = args.localEffectRan ?? false;
36
+ }
37
+ };
38
+ var GuardianRecordTransportRequired = class extends Error {
39
+ toolName;
40
+ constructor(args) {
41
+ super(
42
+ `Guardian in-process mode for "${args.toolName}" requires a record-transport catalog entry (transport: "record"), which needs the updated Guardian control plane \u2014 auto-install was rejected by the client before it reached the network`
43
+ );
44
+ this.name = "GuardianRecordTransportRequired";
45
+ this.toolName = args.toolName;
46
+ }
47
+ };
48
+ var GuardianApprovalPending = class extends Error {
49
+ decision = "ASK";
50
+ requestId;
51
+ toolName;
52
+ input;
53
+ #resume;
54
+ constructor(args, resume) {
55
+ super(
56
+ `Guardian held "${args.toolName}" for human approval (requestId=${args.requestId})`
57
+ );
58
+ this.name = "GuardianApprovalPending";
59
+ this.requestId = args.requestId;
60
+ this.toolName = args.toolName;
61
+ this.input = args.input;
62
+ this.#resume = resume;
63
+ }
64
+ /** Claim + execute + finish after the human approves. */
65
+ resume() {
66
+ return this.#resume();
67
+ }
68
+ };
69
+ function createGuardianContext(options) {
70
+ return { options, ensured: /* @__PURE__ */ new Set() };
71
+ }
72
+ function toolModeFor(options, toolName) {
73
+ return options.modes?.[toolName] ?? options.mode ?? "remote";
74
+ }
75
+ function toArgumentsRecord(input) {
76
+ if (input !== null && typeof input === "object" && !Array.isArray(input)) {
77
+ return input;
78
+ }
79
+ return input === void 0 ? {} : { input };
80
+ }
81
+ function resolvePurpose(options, toolName, input) {
82
+ if (typeof options.purpose === "function") {
83
+ return options.purpose(toolName, input);
84
+ }
85
+ if (typeof options.purpose === "string") {
86
+ return options.purpose;
87
+ }
88
+ const agent = options.agentName ?? "agent";
89
+ return `${agent} invoked ${toolName}`;
90
+ }
91
+ function deny(options, toolName, reasonCode, requestId) {
92
+ if (options.onDeny === "result") {
93
+ return {
94
+ guardian: {
95
+ decision: "DENY",
96
+ toolName,
97
+ reasonCode,
98
+ ...requestId ? { requestId } : {},
99
+ message: `Guardian denied ${toolName} (${reasonCode}). Do not retry the same call.`
100
+ }
101
+ };
102
+ }
103
+ throw new GuardianDenied({
104
+ toolName,
105
+ reasonCode,
106
+ ...requestId ? { requestId } : {}
107
+ });
108
+ }
109
+ function isLocalValidationError(err) {
110
+ return typeof err === "object" && err !== null && Array.isArray(err.issues);
111
+ }
112
+ async function ensureRecordTransport(ctx, toolName, input, runTool) {
113
+ const { options } = ctx;
114
+ if (options.installRecordTransport === false) {
115
+ return;
116
+ }
117
+ const key = `${options.connectionId}:${toolName}`;
118
+ if (ctx.ensured.has(key)) {
119
+ return;
120
+ }
121
+ let result;
122
+ try {
123
+ result = await options.client.request({
124
+ action: "mcp.install",
125
+ connectionId: options.connectionId,
126
+ tool: {
127
+ name: toolName,
128
+ description: `In-process tool "${toolName}" \u2014 evidence record only (registered by a Guardian framework adapter)`,
129
+ transport: "record"
130
+ },
131
+ ...options.adapterId ? { adapterId: options.adapterId } : {},
132
+ purpose: `Register in-process tool ${toolName} for evidence recording`
133
+ });
134
+ } catch (err) {
135
+ if (isLocalValidationError(err)) {
136
+ throw new GuardianRecordTransportRequired({ toolName });
137
+ }
138
+ throw err;
139
+ }
140
+ if (!result.ok) {
141
+ if (result.reasonCode === "TOOL_ALREADY_INSTALLED") {
142
+ ctx.ensured.add(key);
143
+ return;
144
+ }
145
+ return deny(options, toolName, result.reasonCode, void 0);
146
+ }
147
+ if (result.decision === "ALLOW" && result.capabilityToken) {
148
+ const executed = await options.client.execute({
149
+ requestId: result.requestId,
150
+ capabilityToken: result.capabilityToken
151
+ });
152
+ if (!executed.ok) {
153
+ throw new GuardianExecutionFailed({
154
+ toolName,
155
+ requestId: result.requestId,
156
+ reasonCode: executed.reasonCode
157
+ });
158
+ }
159
+ ctx.ensured.add(key);
160
+ return;
161
+ }
162
+ if (result.decision === "ASK") {
163
+ const requestId = result.requestId;
164
+ if (options.onAsk === "result") {
165
+ return {
166
+ guardian: {
167
+ decision: "ASK",
168
+ requestId,
169
+ toolName,
170
+ message: `Installing the record-transport catalog entry for ${toolName} needs human approval (requestId ${requestId}). Retry the tool call after approval.`
171
+ }
172
+ };
173
+ }
174
+ const resumeInstall = async () => {
175
+ const claimed = await options.client.claim(requestId);
176
+ if (claimed.ok && claimed.decision === "ALLOW" && claimed.capabilityToken) {
177
+ const executed = await options.client.execute({
178
+ requestId: claimed.requestId,
179
+ capabilityToken: claimed.capabilityToken
180
+ });
181
+ if (!executed.ok) {
182
+ throw new GuardianExecutionFailed({
183
+ toolName,
184
+ requestId: claimed.requestId,
185
+ reasonCode: executed.reasonCode
186
+ });
187
+ }
188
+ ctx.ensured.add(key);
189
+ const output = await runThroughGuardian(ctx, toolName, input, runTool);
190
+ return {
191
+ requestId: claimed.requestId,
192
+ receipt: executed.receipt,
193
+ output
194
+ };
195
+ }
196
+ if (claimed.ok && claimed.decision === "ASK") {
197
+ throw new GuardianApprovalPending(
198
+ { requestId: claimed.requestId, toolName, input },
199
+ resumeInstall
200
+ );
201
+ }
202
+ throw new GuardianDenied({
203
+ toolName,
204
+ reasonCode: claimed.ok ? claimed.reasonCode ?? "MISSING_CAPABILITY" : claimed.reasonCode,
205
+ ...claimed.ok ? { requestId: claimed.requestId } : {}
206
+ });
207
+ };
208
+ throw new GuardianApprovalPending(
209
+ { requestId, toolName, input },
210
+ resumeInstall
211
+ );
212
+ }
213
+ return deny(
214
+ options,
215
+ toolName,
216
+ result.reasonCode ?? "MISSING_CAPABILITY",
217
+ result.requestId
218
+ );
219
+ }
220
+ async function settle(ctx, toolName, input, result, runTool) {
221
+ const { options } = ctx;
222
+ const mode = toolModeFor(options, toolName);
223
+ if (!result.ok) {
224
+ const heldRequestId = result.requestId;
225
+ if (result.reasonCode === "APPROVAL_REQUIRED" && typeof heldRequestId === "string" && heldRequestId.length > 0) {
226
+ return settle(
227
+ ctx,
228
+ toolName,
229
+ input,
230
+ {
231
+ ok: true,
232
+ requestId: heldRequestId,
233
+ decision: "ASK",
234
+ reasonCode: result.reasonCode
235
+ },
236
+ runTool
237
+ );
238
+ }
239
+ return deny(options, toolName, result.reasonCode, void 0);
240
+ }
241
+ if (result.decision === "ALLOW" && result.capabilityToken) {
242
+ const requestId = result.requestId;
243
+ if (mode === "remote") {
244
+ const executed2 = await options.client.execute({
245
+ requestId,
246
+ capabilityToken: result.capabilityToken
247
+ });
248
+ if (!executed2.ok) {
249
+ throw new GuardianExecutionFailed({
250
+ toolName,
251
+ requestId,
252
+ reasonCode: executed2.reasonCode
253
+ });
254
+ }
255
+ await options.onReceipt?.({
256
+ toolName,
257
+ requestId,
258
+ receipt: executed2.receipt
259
+ });
260
+ return {
261
+ guardian: {
262
+ decision: "ALLOW",
263
+ requestId,
264
+ toolName,
265
+ receipt: executed2.receipt
266
+ }
267
+ };
268
+ }
269
+ const output = await runTool();
270
+ const executed = await options.client.execute({
271
+ requestId,
272
+ capabilityToken: result.capabilityToken
273
+ });
274
+ if (!executed.ok) {
275
+ throw new GuardianExecutionFailed({
276
+ toolName,
277
+ requestId,
278
+ reasonCode: executed.reasonCode,
279
+ localEffectRan: true
280
+ });
281
+ }
282
+ await options.onReceipt?.({ toolName, requestId, receipt: executed.receipt });
283
+ return output;
284
+ }
285
+ if (result.decision === "ASK") {
286
+ const resume = async () => {
287
+ const claimed = await options.client.claim(result.requestId);
288
+ let receipt;
289
+ const output = await settle(
290
+ {
291
+ ...ctx,
292
+ options: {
293
+ ...options,
294
+ onReceipt: async (event) => {
295
+ receipt = event.receipt;
296
+ await options.onReceipt?.(event);
297
+ }
298
+ }
299
+ },
300
+ toolName,
301
+ input,
302
+ claimed,
303
+ runTool
304
+ );
305
+ return { requestId: result.requestId, receipt, output };
306
+ };
307
+ if (options.onAsk === "result") {
308
+ return {
309
+ guardian: {
310
+ decision: "ASK",
311
+ requestId: result.requestId,
312
+ toolName,
313
+ message: `Held for human approval. After approval, claim requestId ${result.requestId} and re-run the tool.`
314
+ }
315
+ };
316
+ }
317
+ throw new GuardianApprovalPending(
318
+ { requestId: result.requestId, toolName, input },
319
+ resume
320
+ );
321
+ }
322
+ return deny(
323
+ options,
324
+ toolName,
325
+ result.reasonCode ?? "MISSING_CAPABILITY",
326
+ result.requestId
327
+ );
328
+ }
329
+ async function runThroughGuardian(ctx, toolName, input, runTool) {
330
+ const { options } = ctx;
331
+ if (toolModeFor(options, toolName) === "inProcess") {
332
+ const gate = await ensureRecordTransport(ctx, toolName, input, runTool);
333
+ if (gate !== void 0) {
334
+ return gate;
335
+ }
336
+ }
337
+ const result = await options.client.request({
338
+ action: "tool.invoke",
339
+ connectionId: options.connectionId,
340
+ toolName,
341
+ arguments: toArgumentsRecord(input),
342
+ ...options.adapterId ? { adapterId: options.adapterId } : {},
343
+ purpose: resolvePurpose(options, toolName, input)
344
+ });
345
+ return settle(ctx, toolName, input, result, runTool);
346
+ }
347
+
348
+ // src/index.ts
349
+ function withGuardian(tools, options) {
350
+ const ctx = createGuardianContext(options);
351
+ const wrapped = {};
352
+ for (const [toolName, definition] of Object.entries(tools)) {
353
+ const execute = definition.execute;
354
+ wrapped[toolName] = typeof execute === "function" ? {
355
+ ...definition,
356
+ execute: (input, callOptions) => runThroughGuardian(
357
+ ctx,
358
+ toolName,
359
+ input,
360
+ () => execute(input, callOptions)
361
+ )
362
+ } : definition;
363
+ }
364
+ return wrapped;
365
+ }
366
+ export {
367
+ GuardianApprovalPending,
368
+ GuardianDenied,
369
+ GuardianExecutionFailed,
370
+ GuardianRecordTransportRequired,
371
+ toArgumentsRecord,
372
+ withGuardian
373
+ };
@@ -0,0 +1,177 @@
1
+ import type { GuardianClient, GuardianRequestResult } from "@odingard/guardian-sdk";
2
+ /**
3
+ * Shared triad semantics for the framework adapters — identical to
4
+ * mcp-server/src/dispatch.ts: a tool never runs unless Guardian issued a
5
+ * capability for this exact request.
6
+ *
7
+ * Two execution modes:
8
+ *
9
+ * - `remote` (default): the tool is a registered catalog entry — a bounded
10
+ * HTTPS call Guardian executes itself. `client.execute` IS the execution;
11
+ * the local `execute`/`func` implementation is never run.
12
+ * - `inProcess` (opt-in): the local implementation is the tool. After ALLOW
13
+ * the impl runs first, then `client.execute` redeems the capability and
14
+ * records the evidence — which requires a `transport: "record"` catalog
15
+ * entry on the connection (auto-installed via `mcp.install`; needs the
16
+ * WO-021 control plane).
17
+ */
18
+ /** Thrown (or returned) when Guardian refuses an action before execution. */
19
+ export declare class GuardianDenied extends Error {
20
+ readonly decision: "DENY";
21
+ readonly toolName: string;
22
+ readonly reasonCode: string;
23
+ readonly requestId: string | undefined;
24
+ constructor(args: {
25
+ toolName: string;
26
+ reasonCode: string;
27
+ requestId?: string;
28
+ });
29
+ }
30
+ /** ALLOW was decided but redeeming the capability failed. */
31
+ export declare class GuardianExecutionFailed extends Error {
32
+ readonly toolName: string;
33
+ readonly requestId: string;
34
+ readonly reasonCode: string;
35
+ /**
36
+ * inProcess only: the local tool already ran before Guardian's final
37
+ * redemption refused it. The effect happened without a recorded receipt;
38
+ * treat it as an incident, never as a successful governed action.
39
+ */
40
+ readonly localEffectRan: boolean;
41
+ constructor(args: {
42
+ toolName: string;
43
+ requestId: string;
44
+ reasonCode: string;
45
+ localEffectRan?: boolean;
46
+ });
47
+ }
48
+ /**
49
+ * `inProcess` mode needs a record-transport catalog entry on the tool
50
+ * connection so `execute` commits evidence without an HTTP call. Thrown when
51
+ * the auto-install proposal could not even be formed — the SDK/control
52
+ * plane in use predates the `transport: "record"` tool kind (WO-021).
53
+ */
54
+ export declare class GuardianRecordTransportRequired extends Error {
55
+ readonly toolName: string;
56
+ constructor(args: {
57
+ toolName: string;
58
+ });
59
+ }
60
+ export type GuardianResume<Output> = () => Promise<{
61
+ requestId: string;
62
+ receipt: unknown;
63
+ output: Output | GuardianDecisionResult;
64
+ }>;
65
+ /**
66
+ * Guardian held the action for human approval (`ASK`). Carries the requestId
67
+ * the app needs to surface to the approver; `resume()` claims the approved
68
+ * capability, executes it, and finishes the call — never before approval.
69
+ */
70
+ export declare class GuardianApprovalPending<Output = unknown> extends Error {
71
+ #private;
72
+ readonly decision: "ASK";
73
+ readonly requestId: string;
74
+ readonly toolName: string;
75
+ readonly input: unknown;
76
+ constructor(args: {
77
+ requestId: string;
78
+ toolName: string;
79
+ input: unknown;
80
+ }, resume: GuardianResume<Output>);
81
+ /** Claim + execute + finish after the human approves. */
82
+ resume(): Promise<{
83
+ requestId: string;
84
+ receipt: unknown;
85
+ output: GuardianDecisionResult | Output;
86
+ }>;
87
+ }
88
+ /**
89
+ * Serializable decision handed back to the model: ASK/DENY when mode is
90
+ * "result", plus the ALLOW receipt a remote-mode call resolves to.
91
+ */
92
+ export type GuardianDecisionResult = {
93
+ guardian: {
94
+ decision: "ALLOW";
95
+ requestId: string;
96
+ toolName: string;
97
+ receipt: unknown;
98
+ };
99
+ } | {
100
+ guardian: {
101
+ decision: "ASK";
102
+ requestId: string;
103
+ toolName: string;
104
+ message: string;
105
+ };
106
+ } | {
107
+ guardian: {
108
+ decision: "DENY";
109
+ toolName: string;
110
+ reasonCode: string;
111
+ requestId?: string;
112
+ message: string;
113
+ };
114
+ };
115
+ export type GuardianMode = "throw" | "result";
116
+ /**
117
+ * `remote`: the tool name is a registered Guardian catalog entry and the
118
+ * server performs the bounded HTTPS call — the local impl never runs.
119
+ * `inProcess`: the local impl IS the tool; it runs only after the capability
120
+ * is issued and its evidence is recorded via execute afterwards.
121
+ */
122
+ export type GuardianToolMode = "remote" | "inProcess";
123
+ export type GuardianAdapterOptions = Readonly<{
124
+ client: GuardianClient;
125
+ /** Tool connection id the proposals are authorized against. */
126
+ connectionId: string;
127
+ /** Adapter audience for executes; defaults to the tool adapter. */
128
+ adapterId?: string;
129
+ /** Human label for the agent in audit + default purpose strings. */
130
+ agentName?: string;
131
+ /** Static purpose or per-call purpose shown to approvers. */
132
+ purpose?: string | ((toolName: string, input: unknown) => string);
133
+ /**
134
+ * Execution mode applied to every wrapped tool: "remote" (default) defers
135
+ * execution to the Guardian catalog entry; "inProcess" runs the local
136
+ * implementation and records the evidence. See `modes` for per-tool
137
+ * overrides.
138
+ */
139
+ mode?: GuardianToolMode;
140
+ /** Per-tool-name mode overrides, e.g. `{ refund_order: "remote" }`. */
141
+ modes?: Readonly<Record<string, GuardianToolMode>>;
142
+ /**
143
+ * inProcess only: auto-propose `mcp.install` of a `transport: "record"`
144
+ * catalog entry for each wrapped tool that lacks one. Default true;
145
+ * requires the WO-021 control plane — a pre-WO-021 SDK raises
146
+ * `GuardianRecordTransportRequired` before any network call.
147
+ */
148
+ installRecordTransport?: boolean;
149
+ /** What ASK does inside the wrapped call. Default "throw". */
150
+ onAsk?: GuardianMode;
151
+ /** What DENY does inside the wrapped call. Default "throw". */
152
+ onDeny?: GuardianMode;
153
+ /** Called with the execution receipt after every ALLOW. */
154
+ onReceipt?: (event: {
155
+ toolName: string;
156
+ requestId: string;
157
+ receipt: unknown;
158
+ }) => void | PromiseLike<void>;
159
+ }>;
160
+ /** Per-wrapper state: which record-transport entries were already ensured. */
161
+ export type GuardianContext = {
162
+ options: GuardianAdapterOptions;
163
+ ensured: Set<string>;
164
+ };
165
+ export declare function createGuardianContext(options: GuardianAdapterOptions): GuardianContext;
166
+ export declare function toolModeFor(options: GuardianAdapterOptions, toolName: string): GuardianToolMode;
167
+ export declare function toArgumentsRecord(input: unknown): Record<string, unknown>;
168
+ /**
169
+ * The triad applied to an already-answered request (request or claim).
170
+ * remote: ALLOW → execute (Guardian performs the call) → receipt is the
171
+ * output; the local impl never runs.
172
+ * inProcess: ALLOW → run the impl → execute redeems + records → impl output.
173
+ * ASK → pending handle; DENY → typed denial.
174
+ */
175
+ export declare function settle<Output>(ctx: GuardianContext, toolName: string, input: unknown, result: GuardianRequestResult, runTool: () => Output | PromiseLike<Output>): Promise<Output | GuardianDecisionResult>;
176
+ /** Ensure the record-transport entry (inProcess), propose, settle. */
177
+ export declare function runThroughGuardian<Output>(ctx: GuardianContext, toolName: string, input: unknown, runTool: () => Output | PromiseLike<Output>): Promise<Output | GuardianDecisionResult>;
@@ -0,0 +1,21 @@
1
+ import type { ToolSet } from "ai";
2
+ import { type GuardianAdapterOptions } from "./core.js";
3
+ export { GuardianApprovalPending, GuardianDenied, GuardianExecutionFailed, GuardianRecordTransportRequired, toArgumentsRecord, type GuardianAdapterOptions, type GuardianDecisionResult, type GuardianMode, type GuardianToolMode, } from "./core.js";
4
+ export type GuardianVercelAIOptions = GuardianAdapterOptions;
5
+ /**
6
+ * Wrap a Vercel AI SDK tool set so every tool's `execute` routes through
7
+ * Guardian.
8
+ *
9
+ * - mode "remote" (default): the tool name is a registered Guardian catalog
10
+ * entry — `client.execute` performs the bounded HTTPS call and the local
11
+ * `execute` impl never runs; the call resolves to the ALLOW receipt.
12
+ * - mode "inProcess" (opt-in, `mode`/`modes` options): the local impl IS the
13
+ * tool — it runs only once ALLOW issues the capability, and `execute`
14
+ * redeems + records the evidence afterwards (auto-installs a
15
+ * `transport: "record"` catalog entry via `mcp.install`; WO-021).
16
+ *
17
+ * ASK throws `GuardianApprovalPending` (or a result object with
18
+ * onAsk: "result"); DENY throws `GuardianDenied` (or a result object with
19
+ * onDeny: "result"). Tools without an `execute` pass through unchanged.
20
+ */
21
+ export declare function withGuardian<T extends ToolSet>(tools: T, options: GuardianVercelAIOptions): T;
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@odingard/guardian-vercel-ai",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Vercel AI SDK adapter — route an agent's tool calls through Guardian for a deterministic ALLOW/ASK/DENY decision before anything executes.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist-dts/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ }
12
+ },
13
+ "files": [
14
+ "dist",
15
+ "dist-dts",
16
+ "README.md",
17
+ "LICENSE"
18
+ ],
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
22
+ "scripts": {
23
+ "build": "esbuild src/index.ts --bundle --platform=node --format=esm --target=node22 --external:ai --external:@odingard/guardian-sdk --outfile=dist/index.js && tsc -p tsconfig.build.json",
24
+ "test": "vitest run",
25
+ "typecheck": "tsc -p tsconfig.json",
26
+ "prepublishOnly": "npm run build && npm test"
27
+ },
28
+ "peerDependencies": {
29
+ "@odingard/guardian-sdk": "^0.2.0",
30
+ "ai": "^5.0.0 || ^6.0.0 || ^7.0.0"
31
+ },
32
+ "devDependencies": {
33
+ "@odingard/guardian-sdk": "^0.2.0",
34
+ "@types/node": "^22.20.5",
35
+ "ai": "^7.0.159",
36
+ "esbuild": "^0.28.2",
37
+ "typescript": "^5.9.3",
38
+ "vitest": "^3.2.4"
39
+ },
40
+ "engines": {
41
+ "node": ">=22"
42
+ },
43
+ "keywords": [
44
+ "guardian",
45
+ "ai-agents",
46
+ "authorization",
47
+ "authority",
48
+ "vercel-ai-sdk",
49
+ "human-in-the-loop"
50
+ ],
51
+ "repository": {
52
+ "type": "git",
53
+ "url": "https://github.com/Odingard/guardian-sdk.git",
54
+ "directory": "packages/vercel-ai"
55
+ },
56
+ "homepage": "https://guardian.odingard.com"
57
+ }