@odingard/guardian-openai-agents 0.0.0-stage → 0.1.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,166 @@
1
- # Temporary Holding Version
1
+ # @odingard/guardian-openai-agents
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
+ OpenAI Agents SDK adapter for Guardian — every tool call goes through a
4
+ deterministic `ALLOW` / `ASK` / `DENY` authority decision before the tool
5
+ runs. The agent proposes; the human decides.
6
+
7
+ **Tested, but not yet proven against a live Guardian and a live model.** The
8
+ tests run the real Agents SDK runner with a scripted model and a stubbed
9
+ Guardian client.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ npm install @odingard/guardian-openai-agents @odingard/guardian-sdk @openai/agents zod
15
+ ```
16
+
17
+ `@openai/agents` (0.21.x) and `@odingard/guardian-sdk` are peer
18
+ dependencies.
19
+
20
+ ## Usage
21
+
22
+ `guardianTool` takes the same options as the Agents SDK's `tool()`, plus
23
+ the Guardian options. `createGuardianTool` binds the Guardian options once.
24
+
25
+ ```ts
26
+ import { Agent, run } from "@openai/agents";
27
+ import { z } from "zod";
28
+ import { createGuardianClient } from "@odingard/guardian-sdk";
29
+ import {
30
+ createGuardianTool,
31
+ findApprovalPending,
32
+ } from "@odingard/guardian-openai-agents";
33
+
34
+ const guardian = createGuardianClient({
35
+ baseUrl: "https://guardian-api.odingard.com",
36
+ credential: process.env.GUARDIAN_AGENT_CREDENTIAL!,
37
+ });
38
+
39
+ const governed = createGuardianTool({
40
+ client: guardian,
41
+ connectionId: "con_…",
42
+ agentName: "billing-agent",
43
+ });
44
+
45
+ const refundOrder = governed({
46
+ name: "refund_order",
47
+ description: "Refund an order",
48
+ parameters: z.object({ orderId: z.string(), amount: z.number() }),
49
+ execute: async ({ orderId, amount }) => refund(orderId, amount),
50
+ });
51
+
52
+ const agent = new Agent({ name: "Billing", tools: [refundOrder] });
53
+
54
+ try {
55
+ const result = await run(agent, "Refund order 42");
56
+ console.log(result.finalOutput);
57
+ } catch (err) {
58
+ const pending = findApprovalPending(err);
59
+ if (!pending) throw err;
60
+ // Show pending.requestId to a person. Poll until they decide or the
61
+ // request expires. The tool runs only after approval; a denial or expiry
62
+ // throws GuardianDenied.
63
+ for (;;) {
64
+ await new Promise((resolve) => setTimeout(resolve, 5000));
65
+ try {
66
+ const { output, receipt } = await pending.resume();
67
+ console.log("approved", output, receipt);
68
+ break;
69
+ } catch (again) {
70
+ if (findApprovalPending(again)) continue;
71
+ console.log("not approved", again);
72
+ break;
73
+ }
74
+ }
75
+ }
76
+ ```
77
+
78
+ `refund` stands for your own code. Nothing here has been run against a
79
+ live Guardian or a live model.
80
+
81
+ Register each tool once on the connection in the Guardian console
82
+ (Connections → tool server → "My own code (record-only)") and allow it for
83
+ the agent.
84
+
85
+ ## What each decision does
86
+
87
+ - `ALLOW` — Guardian issues a single-use capability. Your `execute` runs
88
+ once with the call's arguments, then the capability is redeemed and a
89
+ receipt recorded (`onReceipt` gets it). A failed redemption raises
90
+ `GuardianExecutionFailed` with `localEffectRan: true`. Without your own
91
+ `errorFunction`, the model is told the tool ran without a receipt and not
92
+ to call it again. If the SDK's own `timeoutMs` has already fired, the SDK
93
+ has told the model the tool timed out, and this failure is not reported
94
+ to the model.
95
+ - `ASK` — your `execute` does not run. By default the call throws
96
+ `GuardianApprovalPending`; the Agents SDK ends the run with a
97
+ `ToolCallError` that wraps it, and `findApprovalPending(err)` finds it.
98
+ After a person approves in Guardian, `pending.resume()` claims the
99
+ approval and runs the tool once. If they deny, or the request expires,
100
+ `resume()` throws `GuardianDenied` and the tool never runs. Before they
101
+ decide, `resume()` throws a new `GuardianApprovalPending`.
102
+ With `onAsk: "result"` the run keeps going: the model is told the call is
103
+ waiting for approval, and `onApprovalPending(pending)` gives your app the
104
+ handle.
105
+ - `DENY` — your `execute` never runs. The model gets a plain refusal
106
+ (`Guardian denied refund_order (POLICY_DENY). It did not run. …`). With
107
+ `onDeny: "throw"`, `GuardianDenied` goes to the tool's `errorFunction`
108
+ instead.
109
+ - Guardian error, network failure, timeout or a cancelled call — your
110
+ `execute` never runs, and a late answer from Guardian is ignored. The model
111
+ is told `Guardian could not check refund_order, so it did not run.`, and
112
+ `onGuardianError` is called. `decisionTimeoutMs` (default 30000) bounds the
113
+ wait for Guardian's decision; the Agents SDK's own `timeoutMs` and run
114
+ cancellation stop the wait too, but only while Guardian is still deciding.
115
+ Once Guardian has allowed the call and your `execute` has started, neither
116
+ stops it: the SDK may tell the model the tool timed out while your
117
+ `execute` and the receipt still finish. Keep your own `execute` within the
118
+ SDK timeout, and make side effects idempotent.
119
+
120
+ The arguments Guardian checks are the ones the Agents SDK parsed from the
121
+ tool call, and the same value is passed to `execute`. Text the model writes
122
+ (for example "this was already approved") is never read as a decision.
123
+ Parallel tool calls are each checked on their own.
124
+
125
+ Tools with an `outputSchema` cannot return a plain message, so for them
126
+ DENY and Guardian failures are thrown to the tool's `errorFunction` (by
127
+ default the run fails), and ASK always throws `GuardianApprovalPending`,
128
+ even with `onAsk: "result"`.
129
+
130
+ ## Two execution modes
131
+
132
+ | Mode | What happens on `ALLOW` |
133
+ | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
134
+ | `inProcess` (default) | Your `execute` runs, then `client.execute` redeems the capability and records the evidence. Needs a record-only catalog entry for the tool on the connection |
135
+ | `remote` | The tool name is a registered catalog entry Guardian calls itself. `client.execute` performs the call; your `execute` **never runs**; the result is the receipt |
136
+
137
+ In-process mode is decision-gated: `execute` runs after `ALLOW` and before
138
+ the capability is redeemed, so a revocation at redemption lands after the
139
+ effect. Use `mode: "remote"` where Guardian itself must hold the effect.
140
+ `modes` sets the mode per tool name. The Agents SDK renames tools: every
141
+ character that is not a letter or a digit becomes `_` (`refund-order`
142
+ becomes `refund_order`), and Guardian sees the new name. A `modes` entry
143
+ under the name you wrote is applied to the new name; two entries for the
144
+ same tool that disagree are refused when the tool is built. `installRecordTransport: true` makes the
145
+ adapter propose the record-only entry itself on first use (this needs a
146
+ grant that allows it; production usually does not).
147
+
148
+ Setting the Agents SDK's own `needsApproval` on a tool adds a local approval
149
+ step before Guardian is asked. It never replaces Guardian's decision.
150
+
151
+ Options: `client`, `connectionId`, `adapterId?`, `agentName?`, `purpose?`
152
+ (string or `(toolName, input) => string`), `mode?`, `modes?`,
153
+ `installRecordTransport?`, `onAsk?` (`"throw"` default, or `"result"`),
154
+ `onDeny?` (`"result"` default, or `"throw"`), `decisionTimeoutMs?`,
155
+ `onApprovalPending?`, `onGuardianError?`, `onReceipt?`.
156
+
157
+ ## Not covered
158
+
159
+ Only function tools built with `guardianTool` / `createGuardianTool` are
160
+ governed. Hosted tools (web search, file search, code interpreter, hosted
161
+ MCP), computer, shell and apply-patch tools, handoffs and agents used as
162
+ tools are not; put MCP servers behind `guardian-mcp` instead.
163
+
164
+ ## License
165
+
166
+ Apache-2.0
package/dist/index.js ADDED
@@ -0,0 +1,332 @@
1
+ // src/index.ts
2
+ import {
3
+ tool
4
+ } from "@openai/agents";
5
+
6
+ // src/core.ts
7
+ import {
8
+ createGuardianContext,
9
+ runThroughGuardian,
10
+ toArgumentsRecord,
11
+ GuardianApprovalPending,
12
+ GuardianDenied,
13
+ GuardianExecutionFailed,
14
+ GuardianRecordTransportRequired
15
+ } from "@odingard/guardian-sdk";
16
+
17
+ // src/gate.ts
18
+ var GuardianUnavailable = class extends Error {
19
+ toolName;
20
+ reason;
21
+ constructor(args) {
22
+ super(
23
+ `Guardian could not check "${args.toolName}" (${args.reason}); the tool did not run`
24
+ );
25
+ this.name = "GuardianUnavailable";
26
+ this.toolName = args.toolName;
27
+ this.reason = args.reason;
28
+ }
29
+ };
30
+ var CallGate = class {
31
+ client;
32
+ #state = "deciding";
33
+ #closedBy;
34
+ #timer;
35
+ #signal;
36
+ #onAbort;
37
+ #rejecters = /* @__PURE__ */ new Set();
38
+ #installIds = /* @__PURE__ */ new Set();
39
+ constructor(args) {
40
+ const { client, toolName, timeoutMs, signal } = args;
41
+ this.#timer = setTimeout(
42
+ () => this.#close(new GuardianUnavailable({ toolName, reason: "timeout" })),
43
+ timeoutMs
44
+ );
45
+ if (signal) {
46
+ this.#signal = signal;
47
+ this.#onAbort = () => this.#close(new GuardianUnavailable({ toolName, reason: "cancelled" }));
48
+ if (signal.aborted) {
49
+ this.#onAbort();
50
+ } else {
51
+ signal.addEventListener("abort", this.#onAbort, { once: true });
52
+ }
53
+ }
54
+ const decide = (fn) => (...a) => {
55
+ this.assertOpen();
56
+ if (this.#state !== "deciding") {
57
+ return fn(...a);
58
+ }
59
+ return new Promise((resolve, reject) => {
60
+ this.#rejecters.add(reject);
61
+ fn(...a).then(
62
+ (value) => {
63
+ this.#rejecters.delete(reject);
64
+ if (this.#closedBy) reject(this.#closedBy);
65
+ else resolve(value);
66
+ },
67
+ (err) => {
68
+ this.#rejecters.delete(reject);
69
+ reject(this.#closedBy ?? err);
70
+ }
71
+ );
72
+ });
73
+ };
74
+ const installIds = this.#installIds;
75
+ const noteInstall = (result) => {
76
+ const id = result?.requestId;
77
+ if (typeof id === "string" && id.length > 0) installIds.add(id);
78
+ };
79
+ const request = decide(
80
+ async (i) => {
81
+ const result = await client.request(i);
82
+ if (i.action === "mcp.install") noteInstall(result);
83
+ return result;
84
+ }
85
+ );
86
+ const claim = decide(async (id) => {
87
+ const result = await client.claim(id);
88
+ if (installIds.has(id)) noteInstall(result);
89
+ return result;
90
+ });
91
+ const executeInstall = decide(
92
+ (input) => client.execute(input)
93
+ );
94
+ const execute = (input) => {
95
+ if (installIds.has(input.requestId)) {
96
+ return executeInstall(input);
97
+ }
98
+ this.assertOpen();
99
+ this.commit();
100
+ return client.execute(input);
101
+ };
102
+ const overrides = { request, claim, execute };
103
+ this.client = new Proxy(client, {
104
+ get(target, prop, receiver) {
105
+ if (Object.prototype.hasOwnProperty.call(overrides, prop)) {
106
+ return overrides[prop];
107
+ }
108
+ const value = Reflect.get(target, prop, receiver);
109
+ return typeof value === "function" ? value.bind(target) : value;
110
+ }
111
+ });
112
+ }
113
+ get committed() {
114
+ return this.#state === "committed";
115
+ }
116
+ get closed() {
117
+ return this.#state === "closed";
118
+ }
119
+ /** Throws if the gate closed (timeout or cancel) before the tool started. */
120
+ assertOpen() {
121
+ if (this.#state === "closed" && this.#closedBy) {
122
+ throw this.#closedBy;
123
+ }
124
+ }
125
+ /** The tool (or Guardian's execution of it) is starting. */
126
+ commit() {
127
+ this.assertOpen();
128
+ if (this.#state === "deciding") {
129
+ this.#state = "committed";
130
+ this.#disarm();
131
+ }
132
+ }
133
+ /** The call settled; later `resume()` calls pass straight through. */
134
+ settle() {
135
+ if (this.#state !== "closed") {
136
+ this.#state = "settled";
137
+ this.#disarm();
138
+ }
139
+ }
140
+ #close(reason) {
141
+ if (this.#state !== "deciding") {
142
+ return;
143
+ }
144
+ this.#state = "closed";
145
+ this.#closedBy = reason;
146
+ this.#disarm();
147
+ for (const reject of this.#rejecters) {
148
+ reject(reason);
149
+ }
150
+ this.#rejecters.clear();
151
+ }
152
+ #disarm() {
153
+ if (this.#timer !== void 0) {
154
+ clearTimeout(this.#timer);
155
+ this.#timer = void 0;
156
+ }
157
+ if (this.#signal && this.#onAbort) {
158
+ this.#signal.removeEventListener("abort", this.#onAbort);
159
+ this.#onAbort = void 0;
160
+ }
161
+ }
162
+ };
163
+
164
+ // src/index.ts
165
+ var DEFAULT_DECISION_TIMEOUT_MS = 3e4;
166
+ var DEFAULT_TOOL_ERROR_MESSAGE = "An error occurred while running the tool. Please try again.";
167
+ function askMessage(toolName, requestId) {
168
+ return `Guardian is holding ${toolName} for a person to approve (requestId ${requestId}). It has not run. Do not call it again; tell the user it is waiting for approval.`;
169
+ }
170
+ function denyMessage(err) {
171
+ return `Guardian denied ${err.toolName} (${err.reasonCode}). It did not run. Do not retry the same call.`;
172
+ }
173
+ function unavailableMessage(toolName) {
174
+ return `Guardian could not check ${toolName}, so it did not run.`;
175
+ }
176
+ function executionFailedMessage(err) {
177
+ if (err.localEffectRan) {
178
+ return `${err.toolName} ran, but Guardian could not record it (${err.reasonCode}). Do not call it again; tell the user it ran without a receipt.`;
179
+ }
180
+ return `Guardian could not complete ${err.toolName} (${err.reasonCode}). Do not call it again; tell the user so they can check.`;
181
+ }
182
+ function remapModes(modes, writtenName, builtName) {
183
+ if (!modes || !writtenName || writtenName === builtName) {
184
+ return modes;
185
+ }
186
+ if (!Object.prototype.hasOwnProperty.call(modes, writtenName)) {
187
+ return modes;
188
+ }
189
+ const written = modes[writtenName];
190
+ const hasBuilt = Object.prototype.hasOwnProperty.call(modes, builtName);
191
+ if (hasBuilt && modes[builtName] !== written) {
192
+ throw new Error(
193
+ `Guardian modes disagree for tool "${writtenName}" (the Agents SDK names it "${builtName}"): set one entry`
194
+ );
195
+ }
196
+ return { ...modes, [builtName]: written };
197
+ }
198
+ function buildTool(shared, toolOptions) {
199
+ const { options } = shared;
200
+ const userExecute = toolOptions.execute;
201
+ const userErrorFunction = toolOptions.errorFunction;
202
+ const hasOutputSchema = typeof toolOptions.outputSchema !== "undefined";
203
+ const timeoutMs = options.decisionTimeoutMs ?? DEFAULT_DECISION_TIMEOUT_MS;
204
+ let coreOptions = {
205
+ ...options,
206
+ mode: options.mode ?? "inProcess",
207
+ installRecordTransport: options.installRecordTransport ?? false,
208
+ onAsk: "throw",
209
+ onDeny: "throw"
210
+ };
211
+ const onDeny = options.onDeny ?? "result";
212
+ const onAsk = options.onAsk ?? "throw";
213
+ let toolName = "";
214
+ const execute = async (input, runContext, details) => {
215
+ const gate = new CallGate({
216
+ client: options.client,
217
+ toolName,
218
+ timeoutMs,
219
+ ...details?.signal ? { signal: details.signal } : {}
220
+ });
221
+ const ctx = {
222
+ options: { ...coreOptions, client: gate.client },
223
+ ensured: shared.ensured
224
+ };
225
+ try {
226
+ const output = await runThroughGuardian(ctx, toolName, input, () => {
227
+ gate.commit();
228
+ return userExecute(input, runContext, details);
229
+ });
230
+ gate.settle();
231
+ return output;
232
+ } catch (err) {
233
+ const startedBeforeError = gate.committed;
234
+ gate.settle();
235
+ if (err instanceof GuardianApprovalPending) {
236
+ try {
237
+ await options.onApprovalPending?.(err);
238
+ } catch {
239
+ }
240
+ if (onAsk === "result" && !hasOutputSchema) {
241
+ return askMessage(toolName, err.requestId);
242
+ }
243
+ throw err;
244
+ }
245
+ if (err instanceof GuardianDenied) {
246
+ if (onDeny === "result" && !hasOutputSchema) {
247
+ return denyMessage(err);
248
+ }
249
+ throw err;
250
+ }
251
+ if (err instanceof GuardianExecutionFailed || err instanceof GuardianRecordTransportRequired || startedBeforeError) {
252
+ throw err;
253
+ }
254
+ try {
255
+ await options.onGuardianError?.({ toolName, error: err });
256
+ } catch {
257
+ }
258
+ const unavailable = err instanceof GuardianUnavailable ? err : new GuardianUnavailable({ toolName, reason: "error" });
259
+ if (hasOutputSchema) {
260
+ throw unavailable;
261
+ }
262
+ return unavailableMessage(toolName);
263
+ }
264
+ };
265
+ const errorFunction = async (context, error, details) => {
266
+ if (error instanceof GuardianApprovalPending) {
267
+ throw error;
268
+ }
269
+ if (typeof userErrorFunction === "function") {
270
+ return userErrorFunction(context, error, details);
271
+ }
272
+ if (userErrorFunction === null || hasOutputSchema) {
273
+ throw error;
274
+ }
275
+ if (error instanceof GuardianExecutionFailed) {
276
+ return executionFailedMessage(error);
277
+ }
278
+ if (error instanceof GuardianDenied) {
279
+ return denyMessage(error);
280
+ }
281
+ if (error instanceof GuardianUnavailable) {
282
+ return unavailableMessage(error.toolName);
283
+ }
284
+ return DEFAULT_TOOL_ERROR_MESSAGE;
285
+ };
286
+ const name = toolOptions.name ?? userExecute.name;
287
+ const built = tool({
288
+ ...toolOptions,
289
+ ...name ? { name } : {},
290
+ execute,
291
+ errorFunction
292
+ });
293
+ toolName = built.name;
294
+ const modes = remapModes(options.modes, name, built.name);
295
+ if (modes !== options.modes) {
296
+ coreOptions = { ...coreOptions, ...modes ? { modes } : {} };
297
+ }
298
+ return built;
299
+ }
300
+ function guardianTool(toolOptions, options) {
301
+ return buildTool(
302
+ { options, ensured: /* @__PURE__ */ new Set() },
303
+ toolOptions
304
+ );
305
+ }
306
+ function createGuardianTool(options) {
307
+ const shared = { options, ensured: /* @__PURE__ */ new Set() };
308
+ return (toolOptions) => buildTool(shared, toolOptions);
309
+ }
310
+ function findApprovalPending(err) {
311
+ let current = err;
312
+ for (let depth = 0; depth < 5 && current; depth += 1) {
313
+ if (current instanceof GuardianApprovalPending) {
314
+ return current;
315
+ }
316
+ const next = current.error ?? current.cause;
317
+ current = next;
318
+ }
319
+ return void 0;
320
+ }
321
+ export {
322
+ DEFAULT_DECISION_TIMEOUT_MS,
323
+ GuardianApprovalPending,
324
+ GuardianDenied,
325
+ GuardianExecutionFailed,
326
+ GuardianRecordTransportRequired,
327
+ GuardianUnavailable,
328
+ createGuardianTool,
329
+ findApprovalPending,
330
+ guardianTool,
331
+ toArgumentsRecord
332
+ };
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The governed-execution triad lives in the core SDK
3
+ * (`@odingard/guardian-sdk`, src/guard.ts) so every framework adapter, the
4
+ * MCP proxy and the plain `createGuard` helper share one implementation.
5
+ * This module re-exports it unchanged for the adapter.
6
+ */
7
+ export { createGuardianContext, runThroughGuardian, toArgumentsRecord, GuardianApprovalPending, GuardianDenied, GuardianExecutionFailed, GuardianRecordTransportRequired, type GuardianAdapterOptions, type GuardianContext, type GuardianDecisionResult, type GuardianMode, type GuardianResume, type GuardianToolMode, } from "@odingard/guardian-sdk";
@@ -0,0 +1,46 @@
1
+ import type { GuardianClient } from "@odingard/guardian-sdk";
2
+ /**
3
+ * Guardian did not answer in time, or the agent run cancelled the call
4
+ * while Guardian was still deciding. The tool did not run.
5
+ */
6
+ export declare class GuardianUnavailable extends Error {
7
+ readonly toolName: string;
8
+ readonly reason: "timeout" | "cancelled" | "error";
9
+ constructor(args: {
10
+ toolName: string;
11
+ reason: "timeout" | "cancelled" | "error";
12
+ });
13
+ }
14
+ /**
15
+ * Per-call gate around the Guardian client.
16
+ *
17
+ * While Guardian is deciding, the gate has a deadline and follows the
18
+ * agent run's abort signal. If either fires first, the gate closes for
19
+ * good: the pending Guardian call is abandoned, and every later client call
20
+ * and the tool itself are refused, so a late ALLOW can never run the tool.
21
+ *
22
+ * Once the tool starts (or Guardian is asked to execute the tool call) the
23
+ * gate is committed and stops interfering, so a started action is always
24
+ * recorded. Executing a record-transport install does not commit the gate:
25
+ * the deadline and the abort signal still apply to the tool call after it.
26
+ * Once the call has settled (for example an ASK handed back to the app),
27
+ * the gate opens so `resume()` can claim the approval later.
28
+ */
29
+ export declare class CallGate {
30
+ #private;
31
+ readonly client: GuardianClient;
32
+ constructor(args: {
33
+ client: GuardianClient;
34
+ toolName: string;
35
+ timeoutMs: number;
36
+ signal?: AbortSignal;
37
+ });
38
+ get committed(): boolean;
39
+ get closed(): boolean;
40
+ /** Throws if the gate closed (timeout or cancel) before the tool started. */
41
+ assertOpen(): void;
42
+ /** The tool (or Guardian's execution of it) is starting. */
43
+ commit(): void;
44
+ /** The call settled; later `resume()` calls pass straight through. */
45
+ settle(): void;
46
+ }
@@ -0,0 +1,70 @@
1
+ import { tool, type ToolInputParameters, type ToolOptions, type ToolOutputSchema, type UnknownContext } from "@openai/agents";
2
+ import { GuardianApprovalPending, type GuardianAdapterOptions } from "./core.js";
3
+ export { GuardianApprovalPending, GuardianDenied, GuardianExecutionFailed, GuardianRecordTransportRequired, toArgumentsRecord, type GuardianAdapterOptions, type GuardianDecisionResult, type GuardianMode, type GuardianResume, type GuardianToolMode, } from "./core.js";
4
+ export { GuardianUnavailable } from "./gate.js";
5
+ /** Default time to wait for Guardian's decision before failing closed. */
6
+ export declare const DEFAULT_DECISION_TIMEOUT_MS = 30000;
7
+ export type GuardianOpenAIAgentsOptions = GuardianAdapterOptions & Readonly<{
8
+ /**
9
+ * How long to wait for Guardian's decision, in milliseconds. Past it the
10
+ * call fails closed: the tool does not run, and a late answer is ignored.
11
+ * Default 30000. Waiting for a person is not part of this: an ASK comes
12
+ * back from Guardian at once.
13
+ */
14
+ decisionTimeoutMs?: number;
15
+ /**
16
+ * Called with the pending approval whenever Guardian answers ASK, before
17
+ * the call throws (onAsk "throw") or returns its message (onAsk
18
+ * "result"). Show `pending.requestId` to a person; after they approve in
19
+ * Guardian, `pending.resume()` claims the approval and runs the tool.
20
+ */
21
+ onApprovalPending?: (pending: GuardianApprovalPending) => void | PromiseLike<void>;
22
+ /**
23
+ * Called when Guardian could not be reached, failed, or did not answer
24
+ * in time. The tool did not run. For logging only.
25
+ */
26
+ onGuardianError?: (event: {
27
+ toolName: string;
28
+ error: unknown;
29
+ }) => void | PromiseLike<void>;
30
+ }>;
31
+ type GuardedTool<TParameters extends ToolInputParameters, Context, Result, TOutputSchema extends ToolOutputSchema | undefined> = ReturnType<typeof tool<TParameters, Context, Result, TOutputSchema>>;
32
+ /**
33
+ * A drop-in for the Agents SDK's `tool()`: same options, but every call
34
+ * goes through Guardian before `execute` runs.
35
+ *
36
+ * - ALLOW: `execute` runs once (in-process mode, the default) and the
37
+ * capability is redeemed to record a receipt. In remote mode Guardian
38
+ * performs the registered call itself and `execute` never runs.
39
+ * - ASK: `execute` does not run. By default the call throws
40
+ * `GuardianApprovalPending` out of `run()`; after a person approves,
41
+ * `pending.resume()` claims the approval and runs the tool. With
42
+ * `onAsk: "result"` the model is told the call is waiting instead.
43
+ * - DENY: `execute` never runs; the model gets a plain refusal
44
+ * (`onDeny: "throw"` throws `GuardianDenied` instead).
45
+ * - Guardian error, network failure, timeout or cancellation: `execute`
46
+ * never runs; the model is told Guardian could not check the call.
47
+ *
48
+ * In-process mode is decision-gated: `execute` runs after ALLOW and before
49
+ * the capability is redeemed, so a revocation at redemption lands after
50
+ * the effect (reported as `GuardianExecutionFailed` with
51
+ * `localEffectRan`). Use `mode: "remote"` where Guardian must hold the
52
+ * effect itself.
53
+ */
54
+ export declare function guardianTool<TParameters extends ToolInputParameters = undefined, Context = UnknownContext, Result = string, TOutputSchema extends ToolOutputSchema | undefined = undefined>(toolOptions: ToolOptions<TParameters, Context, TOutputSchema>, options: GuardianOpenAIAgentsOptions): GuardedTool<TParameters, Context, Result, TOutputSchema>;
55
+ /**
56
+ * `guardianTool` with the Guardian options bound once. Tools made by one
57
+ * factory share the record-transport cache.
58
+ *
59
+ * ```ts
60
+ * const governed = createGuardianTool({ client, connectionId: "con_…" });
61
+ * const refund = governed({ name: "refund_order", description, parameters, execute });
62
+ * ```
63
+ */
64
+ export declare function createGuardianTool(options: GuardianOpenAIAgentsOptions): <TParameters extends ToolInputParameters = undefined, Context = UnknownContext, Result = string, TOutputSchema extends ToolOutputSchema | undefined = undefined>(toolOptions: ToolOptions<TParameters, Context, TOutputSchema>) => GuardedTool<TParameters, Context, Result, TOutputSchema>;
65
+ /**
66
+ * Find the pending approval behind an error thrown by `run()`. The Agents
67
+ * SDK may hand the tool's error back as is or wrapped (for example in
68
+ * `ToolCallError.error`); this looks through both.
69
+ */
70
+ export declare function findApprovalPending(err: unknown): GuardianApprovalPending | undefined;
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "@odingard/guardian-openai-agents",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "OpenAI Agents 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:@openai/agents --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.3.8",
30
+ "@openai/agents": ">=0.21.0 <0.22.0"
31
+ },
32
+ "devDependencies": {
33
+ "@odingard/guardian-sdk": "^0.3.8",
34
+ "@openai/agents": "0.21.0",
35
+ "@types/node": "^22.20.5",
36
+ "esbuild": "^0.28.2",
37
+ "typescript": "^5.9.3",
38
+ "vitest": "^5.1.0",
39
+ "zod": "^4.6.7"
40
+ },
41
+ "engines": {
42
+ "node": ">=22"
43
+ },
44
+ "keywords": [
45
+ "guardian",
46
+ "ai-agents",
47
+ "authorization",
48
+ "authority",
49
+ "openai-agents",
50
+ "human-in-the-loop"
51
+ ],
52
+ "repository": {
53
+ "type": "git",
54
+ "url": "https://github.com/Odingard/guardian-sdk.git",
55
+ "directory": "packages/openai-agents"
56
+ },
57
+ "homepage": "https://odingard.com/guardian"
58
+ }