@oked/openai-agents 0.0.0-stage → 0.6.21

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 the 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 the 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 any 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,185 @@
1
- # Temporary Holding Version
1
+ # @oked/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
+ [![npm version](https://img.shields.io/npm/v/@oked/openai-agents.svg)](https://www.npmjs.com/package/@oked/openai-agents)
4
+ [![License: Apache-2.0](https://img.shields.io/npm/l/@oked/openai-agents.svg)](./LICENSE)
5
+
6
+ OKed for the [OpenAI Agents SDK](https://openai.github.io/openai-agents-js/) (`@openai/agents`). Risky tool calls wait for a person, in Telegram or on the [web dashboard](https://oked.ai/dashboard), before they run. The iPhone app is coming soon.
7
+
8
+ Calling `approve()` yourself inside every tool still works. This package is the version you do not have to repeat.
9
+
10
+ ## Install
11
+
12
+ ```sh
13
+ npm install @oked/openai-agents
14
+ ```
15
+
16
+ `@openai/agents` is a peer dependency (`>=0.21.0`). You already have it if you are building an agent. Node.js 18 or newer. The Agents SDK imports `@modelcontextprotocol/client`, which asks for Node.js 20, so this package depends on that client directly and the import still resolves on Node.js 18. The first npm publish of this package is done by hand; after that it ships with the other `@oked/*` packages. Questions: [contact@oked.ai](mailto:contact@oked.ai).
17
+
18
+ ## One tool
19
+
20
+ `okedTool()` takes the same arguments as `tool()`. Sensitive calls wait. A denial, a timeout, or an error is the tool result the model sees, and your `execute` function is not called.
21
+
22
+ ```ts
23
+ import { Agent, run } from "@openai/agents";
24
+ import { z } from "zod";
25
+ import { okedTool } from "@oked/openai-agents";
26
+
27
+ const refundPayment = okedTool({
28
+ name: "refund_payment",
29
+ description: "Refund a charge",
30
+ parameters: z.object({ chargeId: z.string(), amount: z.number() }),
31
+ async execute({ chargeId, amount }) {
32
+ return `Refunded ${amount} on ${chargeId}`;
33
+ },
34
+ });
35
+
36
+ const agent = new Agent({
37
+ name: "Billing",
38
+ instructions: "Refund a charge only when the tool result says the refund ran.",
39
+ tools: [refundPayment],
40
+ });
41
+
42
+ const result = await run(agent, "Refund charge ch_123 for 20 dollars.");
43
+ console.log(result.finalOutput);
44
+ ```
45
+
46
+ Do not also set `needsApproval` on that tool. For function tools the Agents SDK has no in-process approval callback: `needsApproval` pauses the run until your code calls `state.approve()` or `state.reject()`. `okedTool()` is that approval. A second pause would ask twice, and only after you resumed the run.
47
+
48
+ ## A tool list
49
+
50
+ `withOkedTools()` wraps an array you already built.
51
+
52
+ ```ts
53
+ import { Agent, tool } from "@openai/agents";
54
+ import { z } from "zod";
55
+ import { withOkedTools } from "@oked/openai-agents";
56
+
57
+ const getOrder = tool({
58
+ name: "get_order",
59
+ description: "Look up an order",
60
+ parameters: z.object({ orderId: z.string() }),
61
+ async execute({ orderId }) {
62
+ return `Order ${orderId} is paid`;
63
+ },
64
+ });
65
+
66
+ const refundPayment = tool({
67
+ name: "refund_payment",
68
+ description: "Refund a charge",
69
+ parameters: z.object({ chargeId: z.string(), amount: z.number() }),
70
+ async execute({ chargeId, amount }) {
71
+ return `Refunded ${amount} on ${chargeId}`;
72
+ },
73
+ });
74
+
75
+ const agent = new Agent({
76
+ name: "Billing",
77
+ instructions: "Look up orders. Refund only when the tool result says the refund ran.",
78
+ // get_order is not a known read-only name, so it would otherwise be review.
79
+ tools: withOkedTools([getOrder, refundPayment], {
80
+ alwaysAllow: ["get_order"],
81
+ }),
82
+ });
83
+ ```
84
+
85
+ Wrapping a tool that is already wrapped is a no-op, so passing an `okedTool()` through `withOkedTools()` does not ask twice.
86
+
87
+ What each tool type does:
88
+
89
+ | Tool | What the wrapper does |
90
+ |---|---|
91
+ | Function tool | Gates `invoke` before your code runs. The model gets the decision as the tool result. |
92
+ | Local shell, `apply_patch` | Sets `needsApproval` and `onApproval`. The SDK resolves the call in-process. A rejection reason is the text the model sees. |
93
+ | Hosted MCP | Sets `require_approval` to `always` and `on_approval` to the same decision. The original tool object is not modified. |
94
+ | Hosted shell, computer, other hosted tools | Left unchanged. This process does not run them. Put `needsApproval` on them and use `settleOkedInterruptions()`, or keep the risky work in a function tool. |
95
+
96
+ Hosted shell prints a warning when it is left unchanged.
97
+
98
+ ## Tools that already pause
99
+
100
+ If you already use `needsApproval` and you are not wrapping the tool, resolve the pause with OKed and resume:
101
+
102
+ ```ts
103
+ import { run } from "@openai/agents";
104
+ import { settleOkedInterruptions } from "@oked/openai-agents";
105
+
106
+ let result = await run(agent, "Cancel order 17.");
107
+ while (result.interruptions?.length) {
108
+ await settleOkedInterruptions(result);
109
+ result = await run(agent, result.state);
110
+ }
111
+ ```
112
+
113
+ An approval calls `state.approve`. A denial, a timeout, or an error calls `state.reject` with a message. Nothing is left pending.
114
+
115
+ ## Auth
116
+
117
+ Provide a key in either place:
118
+
119
+ - `OKED_API_KEY` in the environment, or
120
+ - `~/.oked/config.json` (`{ "apiKey": "ok_..." }`)
121
+
122
+ Create a key from the [dashboard](https://oked.ai/dashboard) after you [sign up](https://oked.ai/signup). There is no pairing command in this package.
123
+
124
+ Each request sends `source: "openai-agents"` and `client: "@oked/openai-agents@<version>"`. Both are part of the receipt subject. An approval counts only when the signed receipt verifies.
125
+
126
+ ## Configuration
127
+
128
+ Pass a second argument to `okedTool()`, `withOkedTools()`, or `settleOkedInterruptions()`.
129
+
130
+ | Option | Default | Description |
131
+ |---|---|---|
132
+ | `apiKey` | `OKED_API_KEY`, then `~/.oked/config.json` | OKed API key. With no key, a sensitive call is denied. |
133
+ | `timeoutMs` | `630000` | How long to wait for a person, in milliseconds (10.5 minutes, so the backend's 10 minute expiry answers first). |
134
+ | `strictFailClosed` | `false` | When true, an unreachable approval service denies every sensitive call. Env `OKED_STRICT_FAIL_CLOSED`. |
135
+ | `minTier` | `"review"` | Lowest tier that asks. `warning` never blocks on its own. Env `OKED_MIN_TIER` is the fallback. |
136
+ | `alwaysApprove` | `[]` | Tool names that are always `high_stakes`. |
137
+ | `alwaysAllow` | `[]` | Tool names that are always safe. Skips rules and approval. |
138
+ | `cwd` | `process.cwd()` | Recorded on the approval. |
139
+ | `sessionId` | `context.sessionId` or `context.session_id` | String, or a function of the run context. |
140
+ | `deniedOutput` | none | Value returned when the tool has an output schema. It must match that schema. |
141
+
142
+ Unknown tool names are `review` (a person is required at the default `minTier`). Names the shared classifier already treats as read-only, such as `read_file`, stay safe. A `command` or `cmd` string is classified as a shell command, so `rm -rf` and `git push --force` are `high_stakes` even under a custom tool name.
143
+
144
+ If you set `timeoutMs` on the function tool itself, it is raised to at least the approval wait plus 60 seconds (690 seconds with the default wait). A shorter cap would abort the wait and hand the model a generic tool timeout.
145
+
146
+ `approve` replaces the client call. It is for tests. Leave it unset in production.
147
+
148
+ ## Behavior
149
+
150
+ | Tier | What happens |
151
+ |---|---|
152
+ | `safe` | Run immediately, no approval request |
153
+ | `warning` | Run, log to stderr, no approval request |
154
+ | `review` / `high_stakes` | Ask. Approve and the tool runs. Otherwise the model is told the tool did not run, and told not to retry it. |
155
+
156
+ A cached user rule that matches a safe or warning call sends that call to the approval service, which applies the rule. `alwaysAllow` does not consult rules.
157
+
158
+ Failure handling: no API key denies. An invalid key denies. A receipt that does not verify denies. HTTP 429 (too many approvals already waiting) denies until those are decided in Telegram or on the dashboard. An unreachable approval service denies `high_stakes` and, by default, allows lower tiers. Any other unexpected error denies. None of these run the tool.
159
+
160
+ ## Output schemas
161
+
162
+ A tool with `outputSchema` cannot return a free-form sentence. Pass `deniedOutput` that matches the schema so the model still sees a result:
163
+
164
+ ```ts
165
+ const refundPayment = okedTool(
166
+ {
167
+ name: "refund_payment",
168
+ description: "Refund a charge",
169
+ parameters: z.object({ chargeId: z.string(), amount: z.number() }),
170
+ outputSchema: z.object({ ok: z.boolean(), detail: z.string() }),
171
+ async execute({ chargeId, amount }) {
172
+ return { ok: true, detail: `Refunded ${amount} on ${chargeId}` };
173
+ },
174
+ },
175
+ {
176
+ deniedOutput: (denial) => ({ ok: false, detail: denial.message }),
177
+ },
178
+ );
179
+ ```
180
+
181
+ Without `deniedOutput`, the wrapper throws `OkedToolDeniedError` and the tool does not run.
182
+
183
+ ## License
184
+
185
+ [Apache-2.0](./LICENSE)
package/dist/gate.d.ts ADDED
@@ -0,0 +1,74 @@
1
+ import { type ApprovalRequest, type ApprovalResponse, type RiskTier, type Rule } from "@oked/sdk";
2
+ import { type OkedDenial } from "./messages.js";
3
+ /** Lowest tool timeoutMs we keep when the caller set one: the approval wait plus 60 seconds. */
4
+ export declare const OKED_TOOL_TIMEOUT_FLOOR_MS: number;
5
+ export interface OkedAgentsConfig {
6
+ /** OKed API key. Default: OKED_API_KEY, then ~/.oked/config.json. */
7
+ apiKey?: string;
8
+ /**
9
+ * How long to wait for a person, in milliseconds.
10
+ * Default 630000 (10.5 minutes), so the backend's 10 minute expiry answers first.
11
+ */
12
+ timeoutMs?: number;
13
+ /**
14
+ * When true, an unreachable approval service denies every sensitive call.
15
+ * When false (default), it denies high_stakes only. Env OKED_STRICT_FAIL_CLOSED.
16
+ */
17
+ strictFailClosed?: boolean;
18
+ /**
19
+ * Lowest tier that asks for a person. Default "review".
20
+ * warning never blocks on its own. Env OKED_MIN_TIER is the fallback.
21
+ */
22
+ minTier?: RiskTier;
23
+ /** Tool names that are always high_stakes, whatever the classifier says. */
24
+ alwaysApprove?: readonly string[];
25
+ /** Tool names that are always safe. Use sparingly. Skips rules and approval. */
26
+ alwaysAllow?: readonly string[];
27
+ /** Working directory recorded on the approval. Default process.cwd(). */
28
+ cwd?: string;
29
+ /**
30
+ * Session id recorded on the approval. A function receives the Agents SDK
31
+ * run context. When omitted, context.sessionId or context.session_id is used.
32
+ */
33
+ sessionId?: string | ((runContext: unknown) => string | undefined);
34
+ /**
35
+ * Structured value returned to the model when a tool declares an output
36
+ * schema. Without this, a denial throws OkedToolDeniedError instead of
37
+ * inventing a schema-shaped success.
38
+ */
39
+ deniedOutput?: (denial: OkedDenial) => unknown;
40
+ /** Replace stderr logging. */
41
+ log?: (message: string) => void;
42
+ /**
43
+ * Replace OKedClient.approve. Intended for tests. Production leaves this
44
+ * unset and uses the API key. Rules lookup is skipped unless getRules is set.
45
+ */
46
+ approve?: (request: ApprovalRequest) => Promise<ApprovalResponse>;
47
+ /** Replace the rules fetch. Used when a test, or a caller, already has rules. */
48
+ getRules?: () => Promise<Rule[]>;
49
+ }
50
+ export type GateResult = {
51
+ proceed: true;
52
+ tier: RiskTier;
53
+ } | {
54
+ proceed: false;
55
+ denial: OkedDenial;
56
+ };
57
+ export interface GateDeps {
58
+ apiKey: string;
59
+ strictFailClosed: boolean;
60
+ skipRules: boolean;
61
+ approve: (request: ApprovalRequest) => Promise<ApprovalResponse>;
62
+ getRules: () => Promise<Rule[]>;
63
+ heartbeat: () => Promise<void>;
64
+ /** True when approve() was injected, so we do not touch the network ourselves. */
65
+ injected: boolean;
66
+ }
67
+ export declare function toolTimeoutFloor(config?: OkedAgentsConfig): number;
68
+ export declare function createDeps(config?: OkedAgentsConfig): GateDeps;
69
+ /**
70
+ * Classify one call and, when a person is required, wait for approve().
71
+ * Does not run the tool. Callers turn `proceed: false` into a model-visible
72
+ * result and must not execute the underlying function.
73
+ */
74
+ export declare function decideToolCall(toolName: string, args: Record<string, unknown>, config: OkedAgentsConfig, deps: GateDeps, runContext?: unknown): Promise<GateResult>;
package/dist/gate.js ADDED
@@ -0,0 +1,234 @@
1
+ /**
2
+ * Decide whether one tool call may run.
3
+ *
4
+ * Safe and warning calls return without a prompt, unless a cached user rule
5
+ * matches (then the backend decides). review and high_stakes wait on
6
+ * approve(). An explicit denial, a timeout, a bad receipt, a bad key, and
7
+ * any unexpected error stop the tool. An unreachable backend follows
8
+ * degradedDecision: high_stakes denies, lower tiers allow unless
9
+ * strictFailClosed is set.
10
+ */
11
+ import { readFileSync } from "node:fs";
12
+ import { dirname, join } from "node:path";
13
+ import { fileURLToPath } from "node:url";
14
+ import { OKedClient, applyRules, classify, describe, describeFields, degradedDecision, lookupPrTitle, TIER_ORDER, DEFAULT_APPROVAL_TIMEOUT_MS, OKedAuthError, OKedBackendUnreachableError, OKedHttpError, OKedReceiptError, OKedTooManyPendingError, } from "@oked/sdk";
15
+ import { authMessage, deniedMessage, errorText, receiptMessage, timeoutMessage, unexpectedMessage, unpairedMessage, unreachableMessage, } from "./messages.js";
16
+ const CLIENT_ID = (() => {
17
+ try {
18
+ const pkgPath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
19
+ return `@oked/openai-agents@${JSON.parse(readFileSync(pkgPath, "utf-8")).version}`;
20
+ }
21
+ catch {
22
+ return "@oked/openai-agents";
23
+ }
24
+ })();
25
+ const SOURCE = "openai-agents";
26
+ /** Lowest tool timeoutMs we keep when the caller set one: the approval wait plus 60 seconds. */
27
+ export const OKED_TOOL_TIMEOUT_FLOOR_MS = DEFAULT_APPROVAL_TIMEOUT_MS + 60_000;
28
+ const APPROVAL_TIERS = new Set(["review", "high_stakes"]);
29
+ function defaultLog(message) {
30
+ process.stderr.write(`[OKed] ${message}\n`);
31
+ }
32
+ function positiveMs(value) {
33
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
34
+ }
35
+ export function toolTimeoutFloor(config) {
36
+ return (positiveMs(config?.timeoutMs) ?? DEFAULT_APPROVAL_TIMEOUT_MS) + 60_000;
37
+ }
38
+ export function createDeps(config = {}) {
39
+ if (config.approve) {
40
+ return {
41
+ apiKey: config.apiKey ?? "injected",
42
+ strictFailClosed: config.strictFailClosed ?? false,
43
+ skipRules: !config.getRules,
44
+ approve: config.approve,
45
+ getRules: config.getRules ?? (async () => []),
46
+ heartbeat: async () => { },
47
+ injected: true,
48
+ };
49
+ }
50
+ const timeout = positiveMs(config.timeoutMs);
51
+ const client = new OKedClient({
52
+ ...(config.apiKey ? { apiKey: config.apiKey } : {}),
53
+ ...(timeout ? { timeout } : {}),
54
+ ...(config.strictFailClosed !== undefined ? { strictFailClosed: config.strictFailClosed } : {}),
55
+ client: CLIENT_ID,
56
+ source: SOURCE,
57
+ });
58
+ return {
59
+ apiKey: client.apiKey,
60
+ strictFailClosed: config.strictFailClosed ?? client.strictFailClosed,
61
+ skipRules: false,
62
+ approve: (request) => client.approve(request),
63
+ getRules: config.getRules ?? (() => client.getRules()),
64
+ heartbeat: () => client.heartbeat(),
65
+ injected: false,
66
+ };
67
+ }
68
+ function cwdOf(config) {
69
+ return config.cwd ?? process.cwd();
70
+ }
71
+ function sessionOf(config, runContext) {
72
+ if (typeof config.sessionId === "function") {
73
+ const value = config.sessionId(runContext);
74
+ return typeof value === "string" && value ? value : undefined;
75
+ }
76
+ if (typeof config.sessionId === "string" && config.sessionId)
77
+ return config.sessionId;
78
+ if (!runContext || typeof runContext !== "object" || !("context" in runContext))
79
+ return undefined;
80
+ const ctx = runContext.context;
81
+ if (!ctx || typeof ctx !== "object")
82
+ return undefined;
83
+ const record = ctx;
84
+ if (typeof record.sessionId === "string" && record.sessionId)
85
+ return record.sessionId;
86
+ if (typeof record.session_id === "string" && record.session_id)
87
+ return record.session_id;
88
+ return undefined;
89
+ }
90
+ function resolveMinTier(config) {
91
+ const fromEnv = process.env.OKED_MIN_TIER;
92
+ const raw = config.minTier ?? (fromEnv && fromEnv in TIER_ORDER ? fromEnv : "review");
93
+ return raw in TIER_ORDER ? raw : "review";
94
+ }
95
+ function tierNeedsPerson(tier, config) {
96
+ if (!APPROVAL_TIERS.has(tier))
97
+ return false;
98
+ return TIER_ORDER[tier] >= TIER_ORDER[resolveMinTier(config)];
99
+ }
100
+ function classifyCall(toolName, args, config) {
101
+ if (config.alwaysApprove?.includes(toolName))
102
+ return "high_stakes";
103
+ return classify(toolName, args);
104
+ }
105
+ function denial(toolName, tier, decision, approvalId, message) {
106
+ return { proceed: false, denial: { toolName, tier, decision, approvalId, message } };
107
+ }
108
+ async function ruleMatches(toolName, args, tier, config, deps) {
109
+ if (!deps.apiKey || deps.skipRules)
110
+ return false;
111
+ let rules;
112
+ try {
113
+ rules = await deps.getRules();
114
+ }
115
+ catch {
116
+ return false;
117
+ }
118
+ if (!rules.length)
119
+ return false;
120
+ try {
121
+ const fields = describeFields(toolName, args, { cwd: cwdOf(config) }) ?? {};
122
+ const ruled = applyRules({ tier, fields }, rules, { cwd: cwdOf(config) });
123
+ return Boolean(ruled.appliedRuleId);
124
+ }
125
+ catch {
126
+ return false;
127
+ }
128
+ }
129
+ /**
130
+ * Classify one call and, when a person is required, wait for approve().
131
+ * Does not run the tool. Callers turn `proceed: false` into a model-visible
132
+ * result and must not execute the underlying function.
133
+ */
134
+ export async function decideToolCall(toolName, args, config, deps, runContext) {
135
+ const log = config.log ?? defaultLog;
136
+ if (!deps.injected && deps.apiKey) {
137
+ void deps.heartbeat().catch(() => { });
138
+ }
139
+ if (config.alwaysAllow?.includes(toolName)) {
140
+ return { proceed: true, tier: "safe" };
141
+ }
142
+ let tier;
143
+ try {
144
+ tier = classifyCall(toolName, args, config);
145
+ }
146
+ catch (err) {
147
+ log(`classifier error on ${toolName}: ${errorText(err)}`);
148
+ return denial(toolName, "review", "error", null, unexpectedMessage(toolName, `classifier: ${errorText(err)}`));
149
+ }
150
+ if (tier === "safe" || tier === "warning") {
151
+ const escalated = await ruleMatches(toolName, args, tier, config, deps);
152
+ if (!escalated) {
153
+ if (tier === "warning") {
154
+ const summary = args.file_path ?? args.path ?? args.command ?? toolName;
155
+ log(`WARNING ${toolName} ${String(summary)} - allowed`);
156
+ }
157
+ return { proceed: true, tier };
158
+ }
159
+ }
160
+ else if (!tierNeedsPerson(tier, config)) {
161
+ return { proceed: true, tier };
162
+ }
163
+ if (!deps.apiKey) {
164
+ log(`no API key - denying ${toolName}`);
165
+ return denial(toolName, tier, "error", null, unpairedMessage(toolName));
166
+ }
167
+ const cwd = cwdOf(config);
168
+ let description = toolName;
169
+ let fields;
170
+ try {
171
+ fields = describeFields(toolName, args, { cwd }) ?? undefined;
172
+ const prTitle = await lookupPrTitle(fields);
173
+ if (prTitle)
174
+ fields = describeFields(toolName, args, { cwd, prTitle }) ?? undefined;
175
+ description = describe(toolName, args, { cwd, prTitle }) || toolName;
176
+ }
177
+ catch (err) {
178
+ log(`could not describe ${toolName}: ${errorText(err)}`);
179
+ return denial(toolName, tier, "error", null, unexpectedMessage(toolName, errorText(err)));
180
+ }
181
+ log(`${toolName}: "${description}" - ${tier}`);
182
+ log("Requesting approval. Check Telegram or the web dashboard.");
183
+ try {
184
+ const result = await deps.approve({
185
+ action: toolName,
186
+ description,
187
+ tier,
188
+ fields,
189
+ tool_input: args,
190
+ session_id: sessionOf(config, runContext),
191
+ cwd,
192
+ });
193
+ if (result.approved) {
194
+ log(`Approved (${result.approval_id ?? "no id"})`);
195
+ return { proceed: true, tier };
196
+ }
197
+ if (result.decision === "timeout") {
198
+ log(`No decision in time (${result.approval_id ?? "no id"})`);
199
+ return denial(toolName, tier, "timeout", result.approval_id, timeoutMessage(toolName, description, result.approval_id));
200
+ }
201
+ log(`Denied (${result.approval_id ?? "no id"})`);
202
+ return denial(toolName, tier, "denied", result.approval_id, deniedMessage(toolName, description, result.approval_id));
203
+ }
204
+ catch (err) {
205
+ if (err instanceof OKedReceiptError) {
206
+ log(`receipt for ${toolName} did not verify: ${err.problems.join(", ")}`);
207
+ return denial(toolName, tier, "error", null, receiptMessage(toolName, err.problems));
208
+ }
209
+ if (err instanceof OKedAuthError) {
210
+ log(`invalid API key for ${toolName}`);
211
+ return denial(toolName, tier, "error", null, authMessage(toolName));
212
+ }
213
+ if (err instanceof OKedTooManyPendingError) {
214
+ log(`too many pending approvals - denying ${toolName}`);
215
+ return denial(toolName, tier, "error", null, `${err.message} The tool did not run. Do not run this action until those approvals are decided.`);
216
+ }
217
+ if (err instanceof OKedHttpError) {
218
+ log(`backend HTTP ${err.status} - denying ${toolName}`);
219
+ return denial(toolName, tier, "error", null, unexpectedMessage(toolName, err.message));
220
+ }
221
+ if (err instanceof OKedBackendUnreachableError) {
222
+ const outcome = degradedDecision(tier, { strictFailClosed: deps.strictFailClosed });
223
+ if (outcome === "allow") {
224
+ log(`approval service unreachable - ${toolName} (${tier}) allowed (degraded)`);
225
+ return { proceed: true, tier };
226
+ }
227
+ const why = deps.strictFailClosed ? "strict fail closed" : "high_stakes";
228
+ log(`approval service unreachable - denying ${toolName} (${why})`);
229
+ return denial(toolName, tier, "error", null, unreachableMessage(toolName, tier, why, errorText(err)));
230
+ }
231
+ log(`unexpected error for ${toolName}: ${errorText(err)}`);
232
+ return denial(toolName, tier, "error", null, unexpectedMessage(toolName, errorText(err)));
233
+ }
234
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @oked/openai-agents. Human approval for tools built with @openai/agents.
3
+ *
4
+ * okedTool() and withOkedTools() gate a tool before it runs. settleOkedInterruptions()
5
+ * resolves the SDK's own needsApproval pause. Denied, timed out, and failed
6
+ * approvals stop the tool and return a reason to the model.
7
+ */
8
+ export { OkedToolDeniedError } from "./messages.js";
9
+ export type { OkedDenial, OkedStopDecision } from "./messages.js";
10
+ export { OKED_TOOL_TIMEOUT_FLOOR_MS, toolTimeoutFloor } from "./gate.js";
11
+ export type { OkedAgentsConfig } from "./gate.js";
12
+ export { okedTool, withOkedTools, settleOkedInterruptions } from "./wrap.js";
13
+ export type { OkedRunLike } from "./wrap.js";
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * @oked/openai-agents. Human approval for tools built with @openai/agents.
3
+ *
4
+ * okedTool() and withOkedTools() gate a tool before it runs. settleOkedInterruptions()
5
+ * resolves the SDK's own needsApproval pause. Denied, timed out, and failed
6
+ * approvals stop the tool and return a reason to the model.
7
+ */
8
+ export { OkedToolDeniedError } from "./messages.js";
9
+ export { OKED_TOOL_TIMEOUT_FLOOR_MS, toolTimeoutFloor } from "./gate.js";
10
+ export { okedTool, withOkedTools, settleOkedInterruptions } from "./wrap.js";
@@ -0,0 +1,35 @@
1
+ import type { RiskTier } from "@oked/sdk";
2
+ /** Why a tool call was stopped. `error` covers auth, receipt, HTTP, and unexpected failures. */
3
+ export type OkedStopDecision = "denied" | "timeout" | "error";
4
+ /** What the model should see when a tool does not run. */
5
+ export interface OkedDenial {
6
+ toolName: string;
7
+ tier: RiskTier;
8
+ decision: OkedStopDecision;
9
+ /** Null when the request never got an id (for example a client-side timeout). */
10
+ approvalId: string | null;
11
+ /** Text returned to the model. The tool did not run. */
12
+ message: string;
13
+ }
14
+ /**
15
+ * Thrown when a denied tool declares an output schema and no `deniedOutput`
16
+ * was given. A free-form string would fail that schema, so the run stops
17
+ * instead of executing the tool or inventing a structured success.
18
+ */
19
+ export declare class OkedToolDeniedError extends Error {
20
+ readonly toolName: string;
21
+ readonly tier: RiskTier;
22
+ readonly decision: OkedStopDecision;
23
+ readonly approvalId: string | null;
24
+ constructor(denial: OkedDenial);
25
+ }
26
+ /** Final sentence for the model. A denial is not a transient tool error. */
27
+ export declare function finalDecision(text: string): string;
28
+ export declare function deniedMessage(toolName: string, description: string, approvalId: string | null): string;
29
+ export declare function timeoutMessage(toolName: string, description: string, approvalId: string | null): string;
30
+ export declare function unpairedMessage(toolName: string): string;
31
+ export declare function receiptMessage(toolName: string, problems: string[]): string;
32
+ export declare function authMessage(toolName: string): string;
33
+ export declare function unreachableMessage(toolName: string, tier: RiskTier, why: string, cause: string): string;
34
+ export declare function unexpectedMessage(toolName: string, cause: string): string;
35
+ export declare function errorText(err: unknown): string;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Thrown when a denied tool declares an output schema and no `deniedOutput`
3
+ * was given. A free-form string would fail that schema, so the run stops
4
+ * instead of executing the tool or inventing a structured success.
5
+ */
6
+ export class OkedToolDeniedError extends Error {
7
+ toolName;
8
+ tier;
9
+ decision;
10
+ approvalId;
11
+ constructor(denial) {
12
+ super(denial.message);
13
+ this.name = "OkedToolDeniedError";
14
+ this.toolName = denial.toolName;
15
+ this.tier = denial.tier;
16
+ this.decision = denial.decision;
17
+ this.approvalId = denial.approvalId;
18
+ }
19
+ }
20
+ function idNote(approvalId) {
21
+ return approvalId ? ` (approval ${approvalId})` : "";
22
+ }
23
+ /** Final sentence for the model. A denial is not a transient tool error. */
24
+ export function finalDecision(text) {
25
+ return (`${text} The tool did not run. This is a final decision. ` +
26
+ "Do NOT retry the same action. Stop and ask the user what to do instead.");
27
+ }
28
+ export function deniedMessage(toolName, description, approvalId) {
29
+ return finalDecision(`OKed: a person denied ${toolName}${idNote(approvalId)}. ${description}.`);
30
+ }
31
+ export function timeoutMessage(toolName, description, approvalId) {
32
+ return finalDecision(`OKed: no one responded in time for ${toolName}${idNote(approvalId)}. The approval timed out. ${description}.`);
33
+ }
34
+ export function unpairedMessage(toolName) {
35
+ return finalDecision(`OKed: no API key is configured, so ${toolName} was denied. ` +
36
+ "Set OKED_API_KEY, or put the key in ~/.oked/config.json. " +
37
+ "Decisions are made in Telegram or on the web dashboard.");
38
+ }
39
+ export function receiptMessage(toolName, problems) {
40
+ const why = problems.length ? problems.join(", ") : "invalid";
41
+ return finalDecision(`OKed: the approval receipt for ${toolName} did not verify (${why}), so this action is denied.`);
42
+ }
43
+ export function authMessage(toolName) {
44
+ return finalDecision(`OKed: the API key was rejected for ${toolName}. This is a configuration error, not a transient failure.`);
45
+ }
46
+ export function unreachableMessage(toolName, tier, why, cause) {
47
+ return finalDecision(`OKed: the approval service could not be reached (${cause}), so this ${tier} action ${toolName} was denied (${why}, fail closed).`);
48
+ }
49
+ export function unexpectedMessage(toolName, cause) {
50
+ return finalDecision(`OKed: unexpected error while approving ${toolName} (${cause}). Denied (fail closed).`);
51
+ }
52
+ export function errorText(err) {
53
+ if (err instanceof Error && err.message)
54
+ return err.message.replace(/\s+/g, " ").trim();
55
+ return String(err);
56
+ }
package/dist/wrap.d.ts ADDED
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Wire OKed into OpenAI Agents SDK tools.
3
+ *
4
+ * Function tools have no programmatic onApproval. needsApproval only pauses
5
+ * the run until the app calls state.approve or state.reject. Gating execute
6
+ * (and invoke) instead returns the decision to the model in the same turn
7
+ * and does not run the tool on a denial, a timeout, or an error.
8
+ *
9
+ * Local shell, apply_patch, and hosted MCP already accept an onApproval
10
+ * callback that resolves in-process. Those wrappers use that callback.
11
+ * Hosted shell runs outside this process, so it is left unchanged.
12
+ */
13
+ import { type FunctionTool, type Tool } from "@openai/agents";
14
+ import { type OkedAgentsConfig } from "./gate.js";
15
+ type AnyRecord = Record<string, unknown>;
16
+ type ApprovalState = {
17
+ approve: (item: unknown, options?: {
18
+ alwaysApprove?: boolean;
19
+ }) => void;
20
+ reject: (item: unknown, options?: {
21
+ alwaysReject?: boolean;
22
+ message?: string;
23
+ }) => void;
24
+ };
25
+ export interface OkedRunLike {
26
+ interruptions?: readonly unknown[];
27
+ state: ApprovalState;
28
+ }
29
+ /** Parse model arguments into the object classify() and approve() expect. */
30
+ export declare function parseToolInput(value: unknown): AnyRecord;
31
+ export declare function argsFromApprovalItem(item: unknown): {
32
+ name: string;
33
+ args: AnyRecord;
34
+ };
35
+ type ToolExecute = (args: unknown, runContext?: unknown, details?: unknown) => unknown;
36
+ /**
37
+ * Build one function tool whose execute waits for a person when the call is
38
+ * sensitive. Safe and warning calls run immediately. A denial, a timeout, or
39
+ * an error is returned to the model and execute is not called.
40
+ *
41
+ * Do not also set needsApproval. This wrapper is the approval. The SDK pause
42
+ * would ask a second time, and only after your own code resumed the run.
43
+ */
44
+ export declare function okedTool<Result = unknown>(options: {
45
+ name?: string;
46
+ description: string;
47
+ parameters: unknown;
48
+ execute: ToolExecute;
49
+ timeoutMs?: number;
50
+ outputSchema?: unknown;
51
+ [key: string]: unknown;
52
+ }, config?: OkedAgentsConfig): FunctionTool<unknown, any, Result>;
53
+ /**
54
+ * Wrap every tool in an agent tool list.
55
+ *
56
+ * Function tools are gated inside invoke. Local shell and apply_patch use
57
+ * onApproval. Hosted MCP is set to require approval and resolved with
58
+ * on_approval. Hosted shell, computer, and other hosted tools are returned
59
+ * unchanged: this process cannot stop them. Gate those with needsApproval
60
+ * and settleOkedInterruptions, or keep the risky work in a function tool.
61
+ *
62
+ * Wrapping a tool that is already wrapped is a no-op, so okedTool and
63
+ * withOkedTools can be combined without asking twice.
64
+ */
65
+ export declare function withOkedTools<T extends Tool>(tools: readonly T[], config?: OkedAgentsConfig): T[];
66
+ /**
67
+ * Resolve an Agents SDK interruption list with OKed.
68
+ *
69
+ * Use this when tools already set needsApproval and you did not wrap them.
70
+ * Approved calls are state.approve. Anything else is state.reject with a
71
+ * message the model sees when you resume. Pending interruptions are not
72
+ * left pending. Resume with run(agent, result.state).
73
+ */
74
+ export declare function settleOkedInterruptions(result: OkedRunLike, config?: OkedAgentsConfig): Promise<{
75
+ settled: number;
76
+ }>;
77
+ export {};
package/dist/wrap.js ADDED
@@ -0,0 +1,305 @@
1
+ /**
2
+ * Wire OKed into OpenAI Agents SDK tools.
3
+ *
4
+ * Function tools have no programmatic onApproval. needsApproval only pauses
5
+ * the run until the app calls state.approve or state.reject. Gating execute
6
+ * (and invoke) instead returns the decision to the model in the same turn
7
+ * and does not run the tool on a denial, a timeout, or an error.
8
+ *
9
+ * Local shell, apply_patch, and hosted MCP already accept an onApproval
10
+ * callback that resolves in-process. Those wrappers use that callback.
11
+ * Hosted shell runs outside this process, so it is left unchanged.
12
+ */
13
+ import { tool } from "@openai/agents";
14
+ import { OkedToolDeniedError } from "./messages.js";
15
+ import { createDeps, decideToolCall, toolTimeoutFloor, } from "./gate.js";
16
+ const WRAPPED = Symbol.for("@oked/openai-agents.wrapped");
17
+ function isWrapped(value) {
18
+ return Boolean(value[WRAPPED]);
19
+ }
20
+ function mark(value) {
21
+ value[WRAPPED] = true;
22
+ return value;
23
+ }
24
+ function cloneWith(value, overrides) {
25
+ const descriptors = Object.getOwnPropertyDescriptors(value);
26
+ for (const key of Reflect.ownKeys(overrides)) {
27
+ delete descriptors[key];
28
+ }
29
+ const clone = Object.create(Object.getPrototypeOf(value), descriptors);
30
+ return Object.assign(clone, overrides);
31
+ }
32
+ function asRecord(value) {
33
+ if (value && typeof value === "object" && !Array.isArray(value))
34
+ return value;
35
+ if (Array.isArray(value))
36
+ return { items: value };
37
+ if (value === undefined || value === null)
38
+ return {};
39
+ return { input: value };
40
+ }
41
+ /** Parse model arguments into the object classify() and approve() expect. */
42
+ export function parseToolInput(value) {
43
+ if (typeof value === "string") {
44
+ const trimmed = value.trim();
45
+ if (!trimmed)
46
+ return {};
47
+ try {
48
+ return asRecord(JSON.parse(trimmed));
49
+ }
50
+ catch {
51
+ return { input: value };
52
+ }
53
+ }
54
+ return asRecord(value);
55
+ }
56
+ function asObj(value) {
57
+ if (value && typeof value === "object")
58
+ return value;
59
+ return {};
60
+ }
61
+ function shellActionArgs(action) {
62
+ const record = asObj(action);
63
+ if (Array.isArray(record.commands)) {
64
+ const commands = record.commands.filter((item) => typeof item === "string");
65
+ return { command: commands.join(" && "), commands };
66
+ }
67
+ return asRecord(action);
68
+ }
69
+ function patchArgs(operation) {
70
+ const op = asObj(operation);
71
+ const path = typeof op.path === "string" ? op.path : undefined;
72
+ if (op.type === "delete_file" && path)
73
+ return { command: `rm -- ${path}`, path };
74
+ const args = {};
75
+ if (typeof op.type === "string")
76
+ args.operation = op.type;
77
+ if (path)
78
+ args.path = path;
79
+ if (typeof op.diff === "string")
80
+ args.diff = op.diff;
81
+ return args;
82
+ }
83
+ export function argsFromApprovalItem(item) {
84
+ const record = asObj(item);
85
+ const raw = asObj(record.rawItem);
86
+ const named = typeof record.name === "string" && record.name
87
+ ? record.name
88
+ : typeof raw.name === "string" && raw.name
89
+ ? raw.name
90
+ : "";
91
+ if (raw.type === "shell_call") {
92
+ return { name: named || "shell", args: shellActionArgs(raw.action) };
93
+ }
94
+ if (raw.type === "apply_patch_call") {
95
+ return { name: named || "apply_patch", args: patchArgs(raw.operation) };
96
+ }
97
+ const source = typeof record.arguments === "string"
98
+ ? record.arguments
99
+ : typeof raw.arguments === "string"
100
+ ? raw.arguments
101
+ : (record.arguments ?? raw.arguments);
102
+ return { name: named || "tool", args: parseToolInput(source) };
103
+ }
104
+ function blockResult(denial, hasOutputSchema, config) {
105
+ if (config.deniedOutput)
106
+ return config.deniedOutput(denial);
107
+ if (hasOutputSchema)
108
+ throw new OkedToolDeniedError(denial);
109
+ return denial.message;
110
+ }
111
+ function raisedTimeout(existing, config) {
112
+ if (typeof existing !== "number")
113
+ return undefined;
114
+ return Math.max(existing, toolTimeoutFloor(config));
115
+ }
116
+ function isHostedShell(candidate) {
117
+ const kind = candidate.environment?.type;
118
+ return kind === "container_auto" || kind === "container_reference";
119
+ }
120
+ async function onApprovalDecision(name, args, config, deps, runContext, previous, approvalItem) {
121
+ const decision = await decideToolCall(name, args, config, deps, runContext);
122
+ if (!decision.proceed)
123
+ return { approve: false, reason: decision.denial.message };
124
+ if (!previous)
125
+ return { approve: true };
126
+ try {
127
+ const extra = await previous(runContext, approvalItem);
128
+ if (!extra?.approve) {
129
+ return {
130
+ approve: false,
131
+ reason: extra?.reason ||
132
+ `OKed allowed ${name}, but the tool's own approval callback rejected it. The tool did not run.`,
133
+ };
134
+ }
135
+ return { approve: true };
136
+ }
137
+ catch (err) {
138
+ const message = err instanceof Error ? err.message : String(err);
139
+ return {
140
+ approve: false,
141
+ reason: `OKed: the tool's own approval callback for ${name} threw (${message}). The tool did not run.`,
142
+ };
143
+ }
144
+ }
145
+ function wrapFunctionTool(toolDef, config, deps) {
146
+ const originalInvoke = toolDef.invoke;
147
+ const hasOutputSchema = toolDef.outputSchema !== undefined;
148
+ const invoke = async (runContext, input, details) => {
149
+ const decision = await decideToolCall(toolDef.name, parseToolInput(input), config, deps, runContext);
150
+ if (!decision.proceed)
151
+ return blockResult(decision.denial, hasOutputSchema, config);
152
+ return originalInvoke(runContext, input, details);
153
+ };
154
+ const timeoutMs = raisedTimeout(toolDef.timeoutMs, config);
155
+ return mark(cloneWith(toolDef, { invoke, ...(timeoutMs !== undefined ? { timeoutMs } : {}) }));
156
+ }
157
+ function wrapShell(toolDef, config, deps) {
158
+ if (isHostedShell(toolDef)) {
159
+ const log = config.log ?? ((message) => process.stderr.write(`[OKed] ${message}\n`));
160
+ log(`cannot gate hosted shell tool "${toolDef.name}": the command runs outside this process. It was left unchanged.`);
161
+ return toolDef;
162
+ }
163
+ const previous = toolDef.onApproval;
164
+ const name = toolDef.name || "shell";
165
+ return mark(cloneWith(toolDef, {
166
+ needsApproval: async () => true,
167
+ onApproval: (runContext, approvalItem) => {
168
+ const parsed = argsFromApprovalItem(approvalItem);
169
+ const args = parsed.args.command !== undefined ? parsed.args : shellActionArgs(asObj(approvalItem).action);
170
+ return onApprovalDecision(parsed.name || name, args, config, deps, runContext, previous, approvalItem);
171
+ },
172
+ }));
173
+ }
174
+ function wrapPatch(toolDef, config, deps) {
175
+ const previous = toolDef.onApproval;
176
+ const name = toolDef.name || "apply_patch";
177
+ return mark(cloneWith(toolDef, {
178
+ needsApproval: async () => true,
179
+ onApproval: (runContext, approvalItem) => {
180
+ const parsed = argsFromApprovalItem(approvalItem);
181
+ return onApprovalDecision(parsed.name || name, parsed.args, config, deps, runContext, previous, approvalItem);
182
+ },
183
+ }));
184
+ }
185
+ function wrapHostedMcp(toolDef, config, deps) {
186
+ const providerData = { ...(toolDef.providerData ?? {}) };
187
+ const previous = providerData.on_approval;
188
+ const serverLabel = typeof providerData.server_label === "string" ? providerData.server_label : "hosted_mcp";
189
+ providerData.require_approval = "always";
190
+ providerData.on_approval = (runContext, approvalItem) => {
191
+ const parsed = argsFromApprovalItem(approvalItem);
192
+ return onApprovalDecision(parsed.name || serverLabel, parsed.args, config, deps, runContext, previous, approvalItem);
193
+ };
194
+ return mark(cloneWith(toolDef, { providerData }));
195
+ }
196
+ function wrapOne(candidate, config, deps) {
197
+ if (!candidate || typeof candidate !== "object" || typeof candidate.type !== "string") {
198
+ throw new TypeError("withOkedTools() expected an OpenAI Agents SDK tool.");
199
+ }
200
+ if (isWrapped(candidate))
201
+ return candidate;
202
+ const kind = candidate.type;
203
+ if (kind === "function" && typeof candidate.invoke === "function") {
204
+ return wrapFunctionTool(candidate, config, deps);
205
+ }
206
+ if (kind === "shell")
207
+ return wrapShell(candidate, config, deps);
208
+ if (kind === "apply_patch")
209
+ return wrapPatch(candidate, config, deps);
210
+ if (kind === "hosted_tool" &&
211
+ candidate.name === "hosted_mcp" &&
212
+ candidate.providerData?.type === "mcp") {
213
+ return wrapHostedMcp(candidate, config, deps);
214
+ }
215
+ return candidate;
216
+ }
217
+ /**
218
+ * Build one function tool whose execute waits for a person when the call is
219
+ * sensitive. Safe and warning calls run immediately. A denial, a timeout, or
220
+ * an error is returned to the model and execute is not called.
221
+ *
222
+ * Do not also set needsApproval. This wrapper is the approval. The SDK pause
223
+ * would ask a second time, and only after your own code resumed the run.
224
+ */
225
+ export function okedTool(options, config = {}) {
226
+ const deps = createDeps(config);
227
+ const userExecute = options.execute;
228
+ if (typeof userExecute !== "function") {
229
+ throw new TypeError("okedTool() requires an execute function.");
230
+ }
231
+ const hasOutputSchema = options.outputSchema !== undefined;
232
+ let resolvedName = options.name || userExecute.name || "tool";
233
+ const execute = async (args, runContext, details) => {
234
+ const decision = await decideToolCall(resolvedName, asRecord(args), config, deps, runContext);
235
+ if (!decision.proceed)
236
+ return blockResult(decision.denial, hasOutputSchema, config);
237
+ return userExecute(args, runContext, details);
238
+ };
239
+ if (userExecute.name) {
240
+ Object.defineProperty(execute, "name", { value: userExecute.name });
241
+ }
242
+ const timeoutMs = raisedTimeout(options.timeoutMs, config);
243
+ const { needsApproval: _needsApproval, timeoutMs: _timeoutMs, execute: _execute, ...rest } = options;
244
+ const created = tool({
245
+ ...rest,
246
+ execute,
247
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
248
+ });
249
+ resolvedName = created.name || resolvedName;
250
+ return mark(created);
251
+ }
252
+ /**
253
+ * Wrap every tool in an agent tool list.
254
+ *
255
+ * Function tools are gated inside invoke. Local shell and apply_patch use
256
+ * onApproval. Hosted MCP is set to require approval and resolved with
257
+ * on_approval. Hosted shell, computer, and other hosted tools are returned
258
+ * unchanged: this process cannot stop them. Gate those with needsApproval
259
+ * and settleOkedInterruptions, or keep the risky work in a function tool.
260
+ *
261
+ * Wrapping a tool that is already wrapped is a no-op, so okedTool and
262
+ * withOkedTools can be combined without asking twice.
263
+ */
264
+ export function withOkedTools(tools, config = {}) {
265
+ if (!Array.isArray(tools)) {
266
+ throw new TypeError("withOkedTools() expected an array of tools.");
267
+ }
268
+ const deps = createDeps(config);
269
+ return tools.map((item) => wrapOne(item, config, deps));
270
+ }
271
+ /**
272
+ * Resolve an Agents SDK interruption list with OKed.
273
+ *
274
+ * Use this when tools already set needsApproval and you did not wrap them.
275
+ * Approved calls are state.approve. Anything else is state.reject with a
276
+ * message the model sees when you resume. Pending interruptions are not
277
+ * left pending. Resume with run(agent, result.state).
278
+ */
279
+ export async function settleOkedInterruptions(result, config = {}) {
280
+ const interruptions = result.interruptions ?? [];
281
+ if (interruptions.length === 0)
282
+ return { settled: 0 };
283
+ const deps = createDeps(config);
284
+ for (const item of interruptions) {
285
+ const parsed = argsFromApprovalItem(item);
286
+ let message;
287
+ try {
288
+ const decision = await decideToolCall(parsed.name, parsed.args, config, deps, undefined);
289
+ if (decision.proceed) {
290
+ result.state.approve(item);
291
+ continue;
292
+ }
293
+ message = decision.denial.message;
294
+ }
295
+ catch (err) {
296
+ const cause = err instanceof Error ? err.message : String(err);
297
+ message =
298
+ `OKed: unexpected error while approving ${parsed.name} (${cause}). ` +
299
+ "The tool did not run. This is a final decision. Do NOT retry the same action. " +
300
+ "Stop and ask the user what to do instead.";
301
+ }
302
+ result.state.reject(item, { message });
303
+ }
304
+ return { settled: interruptions.length };
305
+ }
package/package.json CHANGED
@@ -1,6 +1,66 @@
1
1
  {
2
2
  "name": "@oked/openai-agents",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.6.21",
4
+ "description": "OKed for the OpenAI Agents SDK. Gates risky tool calls behind a human approval in Telegram or on the web dashboard.",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/index.js",
11
+ "types": "./dist/index.d.ts"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "README.md",
17
+ "LICENSE"
18
+ ],
19
+ "scripts": {
20
+ "prebuild": "npm run build --workspace=@oked/sdk",
21
+ "build": "tsc",
22
+ "dev": "tsc --watch",
23
+ "test": "npm run build && tsx --test test/*.test.ts",
24
+ "prepublishOnly": "npm run build"
25
+ },
26
+ "peerDependencies": {
27
+ "@openai/agents": ">=0.21.0"
28
+ },
29
+ "dependencies": {
30
+ "@modelcontextprotocol/client": "^2.0.0",
31
+ "@oked/sdk": "0.6.21"
32
+ },
33
+ "devDependencies": {
34
+ "@openai/agents": "^0.21.0",
35
+ "@types/node": "^22.13.10",
36
+ "tsx": "^4.22.0",
37
+ "typescript": "^5.6.0",
38
+ "zod": "^4.3.5"
39
+ },
40
+ "keywords": [
41
+ "openai",
42
+ "openai-agents",
43
+ "agents",
44
+ "approval",
45
+ "human-in-the-loop",
46
+ "ai-agent",
47
+ "hooks",
48
+ "oked"
49
+ ],
50
+ "repository": {
51
+ "type": "git",
52
+ "url": "git+https://github.com/oked-ai/oked-sdk.git",
53
+ "directory": "packages/openai-agents"
54
+ },
55
+ "bugs": {
56
+ "url": "https://github.com/oked-ai/oked-sdk/issues"
57
+ },
58
+ "homepage": "https://oked.ai",
59
+ "license": "Apache-2.0",
60
+ "engines": {
61
+ "node": ">=18"
62
+ },
63
+ "publishConfig": {
64
+ "access": "public"
65
+ }
66
+ }