@oked/langgraph 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 +201 -0
- package/README.md +143 -2
- package/dist/gate.d.ts +94 -0
- package/dist/gate.js +269 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +152 -0
- package/package.json +68 -4
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,144 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @oked/langgraph
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@oked/langgraph)
|
|
4
|
+
[](./LICENSE)
|
|
5
|
+
|
|
6
|
+
OKed for [LangGraph.js](https://github.com/langchain-ai/langgraphjs) and LangChain tools. Wrap a tool, and a risky call waits for a person in Telegram or on the [web dashboard](https://oked.ai/dashboard) before it runs. The iPhone app is coming soon.
|
|
7
|
+
|
|
8
|
+
`withOkedApproval` wraps one tool. `withOkedApprovals` wraps a list. Pass that list to `ToolNode` or `createReactAgent`. Denied, timed out, and failed approvals do not run the tool. The model gets a result that says the action was not run.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm install @oked/langgraph
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
`@langchain/core` is a peer dependency (`>=0.2.31`). `@langchain/langgraph` is an optional peer (`>=0.2.0`): install it if you use `ToolNode` or `createReactAgent`. You already have both if you are building a LangGraph agent. Node.js 18 or newer.
|
|
17
|
+
|
|
18
|
+
Set a key before the process starts:
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
export OKED_API_KEY=ok_...
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Create a key from the [dashboard](https://oked.ai/dashboard) after you [sign up](https://oked.ai/signup). You can also run `oked init --key-only` from [`@oked/claude-code`](../claude-code). A key in `~/.oked/config.json` (`{ "apiKey": "ok_..." }`) works when the environment variable is unset.
|
|
25
|
+
|
|
26
|
+
## Quick start
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import { createReactAgent } from "@langchain/langgraph/prebuilt";
|
|
30
|
+
import { withOkedApprovals } from "@oked/langgraph";
|
|
31
|
+
|
|
32
|
+
const agent = createReactAgent({
|
|
33
|
+
llm,
|
|
34
|
+
tools: withOkedApprovals([searchDocs, sendEmail, refundOrder]),
|
|
35
|
+
});
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
One tool:
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
import { withOkedApproval } from "@oked/langgraph";
|
|
42
|
+
|
|
43
|
+
const sendEmail = withOkedApproval(rawSendEmail, { tier: "high_stakes" });
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
A tool node:
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
import { ToolNode } from "@langchain/langgraph/prebuilt";
|
|
50
|
+
import { withOkedApprovals } from "@oked/langgraph";
|
|
51
|
+
|
|
52
|
+
const toolNode = new ToolNode(
|
|
53
|
+
withOkedApprovals([searchDocs, sendEmail], {
|
|
54
|
+
alwaysApprove: ["sendEmail"],
|
|
55
|
+
alwaysAllow: ["searchDocs"],
|
|
56
|
+
}),
|
|
57
|
+
);
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
`name`, `description`, and `schema` are unchanged, so the same objects can go to `bindTools`. `createAgent` from the `langchain` package takes the wrapped list the same way.
|
|
61
|
+
|
|
62
|
+
The wrapper gates `invoke`, `call`, `func`, and `batch`. `ToolNode` and `createReactAgent` call `invoke`. On an approval, that call is forwarded with the same arguments and the same config, including `configurable.thread_id` (recorded as the approval session).
|
|
63
|
+
|
|
64
|
+
## Why this is not interrupt()
|
|
65
|
+
|
|
66
|
+
LangGraph's `interrupt()`, and `interruptBefore` / `interruptAfter` on `createReactAgent`, pause the graph until the code that invoked the graph resumes it with `Command({ resume })`. That person is whoever is driving the process. They need a checkpointer, and a resume that forgets to check the decision runs the tool.
|
|
67
|
+
|
|
68
|
+
OKed's person is on Telegram or the web dashboard. `approve()` already waits for them (10 minutes on the server, 630 seconds in the client). Doing that wait inside the tool, before the tool body, means:
|
|
69
|
+
|
|
70
|
+
- `ToolNode` and `createReactAgent` do not need a checkpointer or a resume step.
|
|
71
|
+
- A denial cannot be skipped by resuming the graph.
|
|
72
|
+
- One denied call does not cancel a sibling tool call in the same turn. Each tool waits on its own.
|
|
73
|
+
- The model receives a tool result either way, so the turn can continue.
|
|
74
|
+
|
|
75
|
+
The process has to stay up for the wait. If it is killed first, the tool does not run. There is no checkpoint to resume, because the approval is not a graph interrupt. Allow at least 630 seconds for a gated call. `timeoutMs` changes the client wait. A timeout is a denial.
|
|
76
|
+
|
|
77
|
+
`gateToolCall` is the same decision without wrapping, for a node you wrote yourself. Run the tool only when `run` is true. Otherwise return `message` to the model and do not call the tool.
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
import { ToolMessage } from "@langchain/core/messages";
|
|
81
|
+
import { gateToolCall } from "@oked/langgraph";
|
|
82
|
+
|
|
83
|
+
const gate = await gateToolCall(call.name, call.args, { config });
|
|
84
|
+
if (!gate.run) {
|
|
85
|
+
return new ToolMessage({
|
|
86
|
+
content: gate.message,
|
|
87
|
+
tool_call_id: call.id,
|
|
88
|
+
status: "error",
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## Auth and receipts
|
|
94
|
+
|
|
95
|
+
Each request sends `source: "langgraph"` and `client: "@oked/langgraph@<version>"`. Both are part of the receipt subject. An approval counts only when the signed receipt verifies. A missing or invalid receipt denies the tool.
|
|
96
|
+
|
|
97
|
+
`OKED_REQUIRE_RECEIPT=0` is only for a backend that does not sign receipts.
|
|
98
|
+
|
|
99
|
+
## Behavior
|
|
100
|
+
|
|
101
|
+
Same tiers as the other integrations. Unknown tool names are `review` (approval required) unless you set `tier`, `alwaysAllow`, or `minTier`.
|
|
102
|
+
|
|
103
|
+
| Tier | What happens |
|
|
104
|
+
|---|---|
|
|
105
|
+
| `safe` | Run immediately. No approval request, unless a cached user rule matches. |
|
|
106
|
+
| `warning` | Run, and log a line to stderr. No approval request, unless a cached user rule matches. |
|
|
107
|
+
| `review` / `high_stakes` | Wait for a person. Approve, and the tool runs with the original arguments. Otherwise it does not run, and the model is told not to retry. |
|
|
108
|
+
|
|
109
|
+
A tool with a string `command` or `cmd` is classified as a shell command. A tool with a path and a content string is classified as a file write.
|
|
110
|
+
|
|
111
|
+
Failure handling, when the tool would have needed a person:
|
|
112
|
+
|
|
113
|
+
| What happened | Result |
|
|
114
|
+
|---|---|
|
|
115
|
+
| Person denies | Tool does not run. |
|
|
116
|
+
| Approval window expires (`timeout`) | Tool does not run. A client-side abort is the same denial, not an outage. |
|
|
117
|
+
| No API key | Tool does not run. LangGraph has no separate permission prompt to defer to. |
|
|
118
|
+
| Invalid API key, bad receipt, HTTP 429, other HTTP error, unexpected error | Tool does not run. |
|
|
119
|
+
| Backend unreachable, tier `high_stakes` | Tool does not run. |
|
|
120
|
+
| Backend unreachable, lower tier | Tool runs, and a warning is logged, unless `OKED_STRICT_FAIL_CLOSED=1` (or `strictFailClosed: true`), which denies every sensitive call during an outage. |
|
|
121
|
+
|
|
122
|
+
The text returned to the model always says the action was not run and not to retry the same call. `ToolNode` receives that as a `ToolMessage` with `status: "error"`. Throwing would let `ToolNode` replace the reason with "Please fix your mistakes", which reads as a transient error.
|
|
123
|
+
|
|
124
|
+
A cached user rule can send a `safe` or `warning` call to the backend, which applies the rule and signs the receipt. Edit rules in Telegram (Rule on the card) or on the dashboard (the gear on a card, or Rules).
|
|
125
|
+
|
|
126
|
+
## Options
|
|
127
|
+
|
|
128
|
+
| Option | Role |
|
|
129
|
+
|---|---|
|
|
130
|
+
| `apiKey` | Overrides `OKED_API_KEY` and `~/.oked/config.json`. |
|
|
131
|
+
| `timeoutMs` | Client wait, in milliseconds. Default 630000. |
|
|
132
|
+
| `strictFailClosed` | Deny every sensitive call when the backend is unreachable. |
|
|
133
|
+
| `minTier` | Lowest tier that waits. Default `review`. `OKED_MIN_TIER` is the fallback. `warning` never waits on tier alone. |
|
|
134
|
+
| `alwaysApprove` | Exact tool names that always wait, at `high_stakes`. |
|
|
135
|
+
| `alwaysAllow` | Exact tool names that never wait. The tool runs. |
|
|
136
|
+
| `tier` | Use this tier instead of the classifier. `alwaysAllow` and `alwaysApprove` still win. |
|
|
137
|
+
| `sessionId` | Stored on the approval. Wins over `config.configurable.thread_id`. |
|
|
138
|
+
| `cwd` | Stored on the approval. Default `process.cwd()`. |
|
|
139
|
+
|
|
140
|
+
`createOkedClient(options)` builds the client the wrappers use (`source: "langgraph"`). Pass it as `client` if several custom `gateToolCall`s should share one. Tests pass a fake `client` with `approve`, `getRules`, `heartbeat`, `apiKey`, and `strictFailClosed`.
|
|
141
|
+
|
|
142
|
+
## License
|
|
143
|
+
|
|
144
|
+
[Apache-2.0](./LICENSE). Questions: [contact@oked.ai](mailto:contact@oked.ai).
|
package/dist/gate.d.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { OKedClient, type ApprovalRequest, type ApprovalResponse, type RiskTier, type Rule } from "@oked/sdk";
|
|
2
|
+
/**
|
|
3
|
+
* Enough of `OKedClient` for the gate. Tests pass a fake. Application code
|
|
4
|
+
* can omit `client` and let the wrapper build one.
|
|
5
|
+
*/
|
|
6
|
+
export interface OkedApprovalClient {
|
|
7
|
+
readonly apiKey: string;
|
|
8
|
+
readonly strictFailClosed: boolean;
|
|
9
|
+
approve(request: ApprovalRequest): Promise<ApprovalResponse>;
|
|
10
|
+
heartbeat(): Promise<void>;
|
|
11
|
+
getRules(): Promise<Rule[]>;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* A LangChain tool, or any object ToolNode can call. The wrapper keeps the
|
|
15
|
+
* original object and only replaces execution.
|
|
16
|
+
*/
|
|
17
|
+
export interface OkedToolLike {
|
|
18
|
+
name: string;
|
|
19
|
+
description?: string;
|
|
20
|
+
schema?: unknown;
|
|
21
|
+
invoke: (...args: any[]) => any;
|
|
22
|
+
}
|
|
23
|
+
export interface OkedLangGraphOptions {
|
|
24
|
+
/** OKed API key. Defaults to `OKED_API_KEY`, then `~/.oked/config.json`. */
|
|
25
|
+
apiKey?: string;
|
|
26
|
+
/** How long to wait for a person, in milliseconds. Default 630000. */
|
|
27
|
+
timeoutMs?: number;
|
|
28
|
+
/**
|
|
29
|
+
* When true, an unreachable backend denies every sensitive tool. When
|
|
30
|
+
* false (default), only `high_stakes` is denied during an outage.
|
|
31
|
+
* `OKED_STRICT_FAIL_CLOSED=1` sets the same flag on a client this package
|
|
32
|
+
* constructs.
|
|
33
|
+
*/
|
|
34
|
+
strictFailClosed?: boolean;
|
|
35
|
+
/**
|
|
36
|
+
* Lowest tier that waits for a person. Default `review` (so `safe` and
|
|
37
|
+
* `warning` run). `OKED_MIN_TIER` is used when this is omitted. Only
|
|
38
|
+
* `review` and `high_stakes` ever wait; `warning` is logged and runs.
|
|
39
|
+
*/
|
|
40
|
+
minTier?: RiskTier;
|
|
41
|
+
/** Tool names that always wait, at tier `high_stakes`. Exact match. */
|
|
42
|
+
alwaysApprove?: readonly string[];
|
|
43
|
+
/** Tool names that never wait. Exact match. The tool runs. */
|
|
44
|
+
alwaysAllow?: readonly string[];
|
|
45
|
+
/**
|
|
46
|
+
* Use this tier instead of the classifier. `alwaysAllow` and
|
|
47
|
+
* `alwaysApprove` still win. `safe` and `warning` run without a prompt
|
|
48
|
+
* unless a cached user rule matches.
|
|
49
|
+
*/
|
|
50
|
+
tier?: RiskTier;
|
|
51
|
+
/** Recorded on the approval. Wins over `config.configurable.thread_id`. */
|
|
52
|
+
sessionId?: string;
|
|
53
|
+
/** Recorded on the approval. Default `process.cwd()`. */
|
|
54
|
+
cwd?: string;
|
|
55
|
+
/**
|
|
56
|
+
* LangGraph runnable config from `tool.invoke`. When `sessionId` is unset,
|
|
57
|
+
* `configurable.thread_id` (then `configurable.session_id`) is the session.
|
|
58
|
+
*/
|
|
59
|
+
config?: unknown;
|
|
60
|
+
/** Receives log lines. Default writes `[OKed] ...` to stderr. */
|
|
61
|
+
log?: (msg: string) => void;
|
|
62
|
+
/**
|
|
63
|
+
* Client to use. Omit this in application code. Tests pass a fake with
|
|
64
|
+
* `approve`, `getRules`, and `heartbeat`.
|
|
65
|
+
*/
|
|
66
|
+
client?: OkedApprovalClient;
|
|
67
|
+
}
|
|
68
|
+
export interface OkedGateResult {
|
|
69
|
+
/** When true, the original tool may run. When false, it must not. */
|
|
70
|
+
run: boolean;
|
|
71
|
+
tier: RiskTier;
|
|
72
|
+
/** Set when `run` is false. Show this to the model. The tool did not run. */
|
|
73
|
+
message?: string;
|
|
74
|
+
decision?: "approved" | "denied" | "timeout";
|
|
75
|
+
approvalId?: string | null;
|
|
76
|
+
/** True when an unreachable backend allowed a non-high-stakes action. */
|
|
77
|
+
degraded?: boolean;
|
|
78
|
+
}
|
|
79
|
+
/** Arguments the model sent, whether `invoke` got a tool call or raw input. */
|
|
80
|
+
export declare function toolInputRecord(input: unknown): Record<string, unknown>;
|
|
81
|
+
/**
|
|
82
|
+
* Build the client the gate uses when the caller did not pass one.
|
|
83
|
+
* `source` is `langgraph`, which is part of the receipt subject.
|
|
84
|
+
*/
|
|
85
|
+
export declare function createOkedClient(options?: OkedLangGraphOptions): OKedClient;
|
|
86
|
+
/**
|
|
87
|
+
* Classify one tool call and, when the tier needs a person, wait.
|
|
88
|
+
* `run: false` means the tool body must not run. The message is for the model.
|
|
89
|
+
* Safe and warning calls run unless a cached user rule matches, in which case
|
|
90
|
+
* the backend decides. No API key denies, because LangGraph would run the tool.
|
|
91
|
+
* A denial, a timeout, a bad receipt, a bad key, and any unexpected error deny.
|
|
92
|
+
* An unreachable backend follows `degradedDecision`.
|
|
93
|
+
*/
|
|
94
|
+
export declare function gateToolCall(toolName: string, toolInput: Record<string, unknown>, options?: OkedLangGraphOptions): Promise<OkedGateResult>;
|
package/dist/gate.js
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Decide whether one LangChain tool call may run.
|
|
3
|
+
*
|
|
4
|
+
* The wait is `OKedClient.approve()`, the same call the other integrations
|
|
5
|
+
* use. LangGraph's `interrupt()` is a different mechanism: it pauses the
|
|
6
|
+
* graph until the caller resumes it, and that caller is not the person on
|
|
7
|
+
* Telegram or the dashboard. Gating here, before the tool body, needs no
|
|
8
|
+
* checkpointer and cannot be skipped by resuming the graph.
|
|
9
|
+
*/
|
|
10
|
+
import { readFileSync } from "node:fs";
|
|
11
|
+
import { dirname, join } from "node:path";
|
|
12
|
+
import { fileURLToPath } from "node:url";
|
|
13
|
+
import { OKedClient, applyRules, classify, degradedDecision, describe, describeFields, lookupPrTitle, TIER_ORDER, OKedAuthError, OKedBackendUnreachableError, OKedHttpError, OKedReceiptError, OKedTooManyPendingError, } from "@oked/sdk";
|
|
14
|
+
const CLIENT_ID = (() => {
|
|
15
|
+
try {
|
|
16
|
+
const pkgPath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
|
|
17
|
+
return `@oked/langgraph@${JSON.parse(readFileSync(pkgPath, "utf-8")).version}`;
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return "@oked/langgraph";
|
|
21
|
+
}
|
|
22
|
+
})();
|
|
23
|
+
const APPROVAL_TIERS = new Set(["review", "high_stakes"]);
|
|
24
|
+
const TIERS = new Set(["safe", "warning", "review", "high_stakes"]);
|
|
25
|
+
function isTier(value) {
|
|
26
|
+
return typeof value === "string" && TIERS.has(value);
|
|
27
|
+
}
|
|
28
|
+
function defaultLog(msg) {
|
|
29
|
+
process.stderr.write(`[OKed] ${msg}\n`);
|
|
30
|
+
}
|
|
31
|
+
function blocked(lead) {
|
|
32
|
+
return `${lead} This action was not run. Do NOT retry the same action. Stop and ask the user what to do instead.`;
|
|
33
|
+
}
|
|
34
|
+
function errorText(err) {
|
|
35
|
+
if (err instanceof Error)
|
|
36
|
+
return `${err.name}: ${err.message}`;
|
|
37
|
+
return String(err);
|
|
38
|
+
}
|
|
39
|
+
function isRecord(value) {
|
|
40
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
41
|
+
}
|
|
42
|
+
/** Arguments the model sent, whether `invoke` got a tool call or raw input. */
|
|
43
|
+
export function toolInputRecord(input) {
|
|
44
|
+
if (isRecord(input) && input.type === "tool_call" && "args" in input) {
|
|
45
|
+
const args = input.args;
|
|
46
|
+
if (isRecord(args))
|
|
47
|
+
return args;
|
|
48
|
+
if (typeof args === "string")
|
|
49
|
+
return { input: args };
|
|
50
|
+
return { input: args };
|
|
51
|
+
}
|
|
52
|
+
if (isRecord(input))
|
|
53
|
+
return input;
|
|
54
|
+
if (typeof input === "string")
|
|
55
|
+
return { input };
|
|
56
|
+
return { input };
|
|
57
|
+
}
|
|
58
|
+
function resolveMinTier(options) {
|
|
59
|
+
const fromOptions = options?.minTier;
|
|
60
|
+
if (isTier(fromOptions))
|
|
61
|
+
return fromOptions;
|
|
62
|
+
const env = process.env.OKED_MIN_TIER;
|
|
63
|
+
if (isTier(env))
|
|
64
|
+
return env;
|
|
65
|
+
return "review";
|
|
66
|
+
}
|
|
67
|
+
function resolveTier(toolName, toolInput, options) {
|
|
68
|
+
if (options?.alwaysAllow?.includes(toolName))
|
|
69
|
+
return "safe";
|
|
70
|
+
if (options?.alwaysApprove?.includes(toolName))
|
|
71
|
+
return "high_stakes";
|
|
72
|
+
const override = options?.tier;
|
|
73
|
+
if (isTier(override))
|
|
74
|
+
return override;
|
|
75
|
+
return classify(toolName, toolInput);
|
|
76
|
+
}
|
|
77
|
+
function sessionIdOf(options) {
|
|
78
|
+
if (options?.sessionId)
|
|
79
|
+
return options.sessionId;
|
|
80
|
+
const config = options?.config;
|
|
81
|
+
if (!isRecord(config))
|
|
82
|
+
return undefined;
|
|
83
|
+
const configurable = config.configurable;
|
|
84
|
+
if (!isRecord(configurable))
|
|
85
|
+
return undefined;
|
|
86
|
+
if (typeof configurable.thread_id === "string" && configurable.thread_id) {
|
|
87
|
+
return configurable.thread_id;
|
|
88
|
+
}
|
|
89
|
+
if (typeof configurable.session_id === "string" && configurable.session_id) {
|
|
90
|
+
return configurable.session_id;
|
|
91
|
+
}
|
|
92
|
+
return undefined;
|
|
93
|
+
}
|
|
94
|
+
function cwdOf(options) {
|
|
95
|
+
return options?.cwd ?? process.cwd();
|
|
96
|
+
}
|
|
97
|
+
function summaryOf(toolName, toolInput) {
|
|
98
|
+
const summary = toolInput.file_path ?? toolInput.path ?? toolInput.command ?? toolInput.cmd ?? toolName;
|
|
99
|
+
return typeof summary === "string" ? summary : toolName;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Build the client the gate uses when the caller did not pass one.
|
|
103
|
+
* `source` is `langgraph`, which is part of the receipt subject.
|
|
104
|
+
*/
|
|
105
|
+
export function createOkedClient(options) {
|
|
106
|
+
return new OKedClient({
|
|
107
|
+
...(options?.apiKey ? { apiKey: options.apiKey } : {}),
|
|
108
|
+
...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),
|
|
109
|
+
...(options?.strictFailClosed !== undefined ? { strictFailClosed: options.strictFailClosed } : {}),
|
|
110
|
+
client: CLIENT_ID,
|
|
111
|
+
source: "langgraph",
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
function clientOf(options) {
|
|
115
|
+
return options?.client ?? createOkedClient(options);
|
|
116
|
+
}
|
|
117
|
+
async function rulesWantBackend(client, tier, fields, cwd) {
|
|
118
|
+
if (!client.apiKey)
|
|
119
|
+
return false;
|
|
120
|
+
try {
|
|
121
|
+
const rules = await client.getRules();
|
|
122
|
+
if (rules.length === 0)
|
|
123
|
+
return false;
|
|
124
|
+
const decision = applyRules({ tier, fields: fields ?? {} }, rules, { cwd });
|
|
125
|
+
return Boolean(decision.appliedRuleId);
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
// A failed rules lookup must not block a tool that would otherwise run.
|
|
129
|
+
return false;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Classify one tool call and, when the tier needs a person, wait.
|
|
134
|
+
* `run: false` means the tool body must not run. The message is for the model.
|
|
135
|
+
* Safe and warning calls run unless a cached user rule matches, in which case
|
|
136
|
+
* the backend decides. No API key denies, because LangGraph would run the tool.
|
|
137
|
+
* A denial, a timeout, a bad receipt, a bad key, and any unexpected error deny.
|
|
138
|
+
* An unreachable backend follows `degradedDecision`.
|
|
139
|
+
*/
|
|
140
|
+
export async function gateToolCall(toolName, toolInput, options) {
|
|
141
|
+
const log = options?.log ?? defaultLog;
|
|
142
|
+
const client = clientOf(options);
|
|
143
|
+
const cwd = cwdOf(options);
|
|
144
|
+
if (client.apiKey)
|
|
145
|
+
void client.heartbeat().catch(() => { });
|
|
146
|
+
let tier;
|
|
147
|
+
try {
|
|
148
|
+
tier = resolveTier(toolName, toolInput, options);
|
|
149
|
+
}
|
|
150
|
+
catch (err) {
|
|
151
|
+
log(`classifier error on ${toolName}: ${errorText(err)}`);
|
|
152
|
+
return {
|
|
153
|
+
run: false,
|
|
154
|
+
tier: "review",
|
|
155
|
+
message: blocked(`OKed: could not classify ${toolName} (${errorText(err)}).`),
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
const minTier = resolveMinTier(options);
|
|
159
|
+
const needsApproval = APPROVAL_TIERS.has(tier) && TIER_ORDER[tier] >= TIER_ORDER[minTier];
|
|
160
|
+
let fields = describeFields(toolName, toolInput, { cwd }) ?? undefined;
|
|
161
|
+
if (!needsApproval) {
|
|
162
|
+
const escalated = await rulesWantBackend(client, tier, fields, cwd);
|
|
163
|
+
if (!escalated) {
|
|
164
|
+
if (tier === "warning") {
|
|
165
|
+
log(`WARNING ${toolName} ${summaryOf(toolName, toolInput)} - allowed (inside project)`);
|
|
166
|
+
}
|
|
167
|
+
return { run: true, tier };
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (!client.apiKey) {
|
|
171
|
+
log(`no API key - denying ${toolName}`);
|
|
172
|
+
return {
|
|
173
|
+
run: false,
|
|
174
|
+
tier,
|
|
175
|
+
message: blocked(`OKed: no API key is configured for ${toolName}. Set OKED_API_KEY, or put an apiKey in ~/.oked/config.json.`),
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
try {
|
|
179
|
+
const prTitle = await lookupPrTitle(fields);
|
|
180
|
+
if (prTitle)
|
|
181
|
+
fields = describeFields(toolName, toolInput, { cwd, prTitle }) ?? undefined;
|
|
182
|
+
const description = describe(toolName, toolInput, { cwd, prTitle });
|
|
183
|
+
log(`${toolName}: "${description}" - ${tier}`);
|
|
184
|
+
log("Requesting approval... (Telegram or the web dashboard)");
|
|
185
|
+
const result = await client.approve({
|
|
186
|
+
action: toolName,
|
|
187
|
+
description,
|
|
188
|
+
tier,
|
|
189
|
+
fields,
|
|
190
|
+
tool_input: toolInput,
|
|
191
|
+
session_id: sessionIdOf(options),
|
|
192
|
+
cwd,
|
|
193
|
+
});
|
|
194
|
+
if (result.approved) {
|
|
195
|
+
log(`Approved (${result.approval_id})`);
|
|
196
|
+
return { run: true, tier, decision: "approved", approvalId: result.approval_id };
|
|
197
|
+
}
|
|
198
|
+
if (result.decision === "timeout") {
|
|
199
|
+
log(result.approval_id ? `No decision in time (${result.approval_id})` : "No decision in time");
|
|
200
|
+
const idNote = result.approval_id ? ` (approval ${result.approval_id})` : "";
|
|
201
|
+
return {
|
|
202
|
+
run: false,
|
|
203
|
+
tier,
|
|
204
|
+
decision: "timeout",
|
|
205
|
+
approvalId: result.approval_id,
|
|
206
|
+
message: blocked(`USER did not respond to ${toolName} via OKed${idNote}. The approval window expired.`),
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
log(`Denied (${result.approval_id})`);
|
|
210
|
+
const idNote = result.approval_id ? ` (approval ${result.approval_id})` : "";
|
|
211
|
+
return {
|
|
212
|
+
run: false,
|
|
213
|
+
tier,
|
|
214
|
+
decision: "denied",
|
|
215
|
+
approvalId: result.approval_id,
|
|
216
|
+
message: blocked(`USER DENIED ${toolName} via OKed${idNote}. This is a final human decision.`),
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
catch (err) {
|
|
220
|
+
if (err instanceof OKedReceiptError) {
|
|
221
|
+
log(`Approval receipt did not verify (${err.problems.join(", ")}) - action denied`);
|
|
222
|
+
return {
|
|
223
|
+
run: false,
|
|
224
|
+
tier,
|
|
225
|
+
message: blocked(`OKed: the approval receipt for ${toolName} did not verify (${err.problems.join(", ")}).`),
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
if (err instanceof OKedAuthError) {
|
|
229
|
+
log(`Invalid API key (HTTP ${err.status}) - action denied`);
|
|
230
|
+
return {
|
|
231
|
+
run: false,
|
|
232
|
+
tier,
|
|
233
|
+
message: blocked(`OKed: invalid API key for ${toolName} (HTTP ${err.status}). This is a configuration error, not a transient failure.`),
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
if (err instanceof OKedTooManyPendingError) {
|
|
237
|
+
log("Too many pending approvals (HTTP 429) - action denied");
|
|
238
|
+
return { run: false, tier, message: blocked(err.message) };
|
|
239
|
+
}
|
|
240
|
+
if (err instanceof OKedHttpError) {
|
|
241
|
+
log(`Backend error HTTP ${err.status} - action denied (fail-safe)`);
|
|
242
|
+
return {
|
|
243
|
+
run: false,
|
|
244
|
+
tier,
|
|
245
|
+
message: blocked(`OKed: backend error HTTP ${err.status}${err.detail ? `: ${err.detail}` : ""} (fail-safe).`),
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
if (err instanceof OKedBackendUnreachableError) {
|
|
249
|
+
const decision = degradedDecision(tier, { strictFailClosed: client.strictFailClosed });
|
|
250
|
+
if (decision === "allow") {
|
|
251
|
+
log(`Backend unreachable - ${toolName} (${tier}) allowed (degraded; non-high-stakes)`);
|
|
252
|
+
return { run: true, tier, degraded: true };
|
|
253
|
+
}
|
|
254
|
+
const why = client.strictFailClosed ? "strict fail-closed" : "high-stakes";
|
|
255
|
+
log(`Backend unreachable - ${toolName} (${tier}) denied (${why}, fail-safe)`);
|
|
256
|
+
return {
|
|
257
|
+
run: false,
|
|
258
|
+
tier,
|
|
259
|
+
message: blocked(`OKed backend unreachable. This ${tier} action is denied (${why}, fail-safe).`),
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
log(`Unexpected error (${errorText(err)}) - action denied (fail-safe)`);
|
|
263
|
+
return {
|
|
264
|
+
run: false,
|
|
265
|
+
tier,
|
|
266
|
+
message: blocked(`OKed: unexpected error (fail-safe) for ${toolName}: ${errorText(err)}.`),
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { createOkedClient, gateToolCall, type OkedLangGraphOptions, type OkedToolLike } from "./gate.js";
|
|
2
|
+
/**
|
|
3
|
+
* Wrap one LangChain tool. `name`, `description`, and `schema` are unchanged,
|
|
4
|
+
* so `bindTools` still sees the original tool. The body runs only after an
|
|
5
|
+
* approval when the tier requires one.
|
|
6
|
+
*/
|
|
7
|
+
export declare function withOkedApproval<T extends OkedToolLike>(tool: T, options?: OkedLangGraphOptions): T;
|
|
8
|
+
/**
|
|
9
|
+
* Wrap each tool with one shared client. Pass the array to `new ToolNode(tools)`
|
|
10
|
+
* or `createReactAgent({ llm, tools })`. An already wrapped tool is left as it is.
|
|
11
|
+
*/
|
|
12
|
+
export declare function withOkedApprovals<T extends OkedToolLike>(tools: readonly T[], options?: OkedLangGraphOptions): T[];
|
|
13
|
+
export { createOkedClient, gateToolCall };
|
|
14
|
+
export type { OkedApprovalClient, OkedGateResult, OkedLangGraphOptions, OkedToolLike, } from "./gate.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @oked/langgraph. Gate LangChain tools with OKed before they run.
|
|
3
|
+
*
|
|
4
|
+
* `withOkedApproval` / `withOkedApprovals` return the same tools, with
|
|
5
|
+
* `invoke` (and `call`, `func`, and `batch`) waiting on `approve()` when the
|
|
6
|
+
* call is `review` or `high_stakes`. Pass the result to `ToolNode` or
|
|
7
|
+
* `createReactAgent`. A denial or a timeout does not call the tool. The model
|
|
8
|
+
* gets an error `ToolMessage` (or a string, when you invoked the tool with
|
|
9
|
+
* raw arguments) that says the action was not run.
|
|
10
|
+
*
|
|
11
|
+
* This does not call LangGraph `interrupt()`. That pause is for the process
|
|
12
|
+
* that resumes the graph. The person who decides here is on Telegram or the
|
|
13
|
+
* web dashboard, and `approve()` already waits for them.
|
|
14
|
+
*/
|
|
15
|
+
import { ToolMessage } from "@langchain/core/messages";
|
|
16
|
+
import { createOkedClient, gateToolCall, toolInputRecord, } from "./gate.js";
|
|
17
|
+
const WRAPPED = Symbol.for("oked.langgraph.wrapped");
|
|
18
|
+
function isRecord(value) {
|
|
19
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
20
|
+
}
|
|
21
|
+
function isToolCall(input) {
|
|
22
|
+
return isRecord(input) && input.type === "tool_call" && typeof input.name === "string" && "args" in input;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* A result the model can read. ToolNode passes a real ToolMessage through.
|
|
26
|
+
* A thrown error would be rewritten as "Please fix your mistakes", which
|
|
27
|
+
* sounds transient, so a denial is a normal return with status "error".
|
|
28
|
+
* A string return would be marked success. Raw `invoke` (no tool call id)
|
|
29
|
+
* gets the same text as a string.
|
|
30
|
+
*/
|
|
31
|
+
function denialResult(toolName, input, message) {
|
|
32
|
+
if (!isToolCall(input))
|
|
33
|
+
return message;
|
|
34
|
+
const id = typeof input.id === "string" ? input.id : "";
|
|
35
|
+
return new ToolMessage({
|
|
36
|
+
content: message,
|
|
37
|
+
name: toolName,
|
|
38
|
+
tool_call_id: id,
|
|
39
|
+
status: "error",
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
function configFromFuncArgs(args) {
|
|
43
|
+
const third = args[2];
|
|
44
|
+
if (isRecord(third))
|
|
45
|
+
return third;
|
|
46
|
+
const second = args[1];
|
|
47
|
+
if (isRecord(second) && "configurable" in second)
|
|
48
|
+
return second;
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
function makeRunner(tool, options) {
|
|
52
|
+
const invoke = tool.invoke;
|
|
53
|
+
return async (input, config) => {
|
|
54
|
+
const gate = await gateToolCall(tool.name, toolInputRecord(input), {
|
|
55
|
+
...options,
|
|
56
|
+
config,
|
|
57
|
+
});
|
|
58
|
+
if (!gate.run) {
|
|
59
|
+
return denialResult(tool.name, input, gate.message ?? "OKed: this action was not run.");
|
|
60
|
+
}
|
|
61
|
+
return Reflect.apply(invoke, tool, [input, config]);
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Wrap one LangChain tool. `name`, `description`, and `schema` are unchanged,
|
|
66
|
+
* so `bindTools` still sees the original tool. The body runs only after an
|
|
67
|
+
* approval when the tier requires one.
|
|
68
|
+
*/
|
|
69
|
+
export function withOkedApproval(tool, options) {
|
|
70
|
+
if (tool === null || typeof tool !== "object") {
|
|
71
|
+
throw new TypeError("OKed: withOkedApproval expected a LangChain tool");
|
|
72
|
+
}
|
|
73
|
+
if (tool[WRAPPED] === true)
|
|
74
|
+
return tool;
|
|
75
|
+
if (typeof tool.name !== "string" || tool.name.length === 0) {
|
|
76
|
+
throw new TypeError("OKed: withOkedApproval expected a tool with a name");
|
|
77
|
+
}
|
|
78
|
+
if (typeof tool.invoke !== "function") {
|
|
79
|
+
throw new TypeError(`OKed: tool "${tool.name}" has no invoke function`);
|
|
80
|
+
}
|
|
81
|
+
const opts = options?.client ? options : { ...options, client: createOkedClient(options) };
|
|
82
|
+
const run = makeRunner(tool, opts);
|
|
83
|
+
return new Proxy(tool, {
|
|
84
|
+
get(target, prop, _receiver) {
|
|
85
|
+
if (prop === WRAPPED)
|
|
86
|
+
return true;
|
|
87
|
+
if (prop === "invoke") {
|
|
88
|
+
return (input, config) => run(input, config);
|
|
89
|
+
}
|
|
90
|
+
if (prop === "call") {
|
|
91
|
+
const call = Reflect.get(target, "call", target);
|
|
92
|
+
if (typeof call !== "function")
|
|
93
|
+
return undefined;
|
|
94
|
+
return async (...args) => {
|
|
95
|
+
const gate = await gateToolCall(target.name, toolInputRecord(args[0]), {
|
|
96
|
+
...opts,
|
|
97
|
+
config: args[1],
|
|
98
|
+
});
|
|
99
|
+
if (!gate.run)
|
|
100
|
+
return denialResult(target.name, args[0], gate.message ?? "OKed: this action was not run.");
|
|
101
|
+
return Reflect.apply(call, target, args);
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
if (prop === "func") {
|
|
105
|
+
const func = Reflect.get(target, "func", target);
|
|
106
|
+
if (typeof func !== "function")
|
|
107
|
+
return func;
|
|
108
|
+
return async (...args) => {
|
|
109
|
+
const gate = await gateToolCall(target.name, toolInputRecord(args[0]), {
|
|
110
|
+
...opts,
|
|
111
|
+
config: configFromFuncArgs(args),
|
|
112
|
+
});
|
|
113
|
+
if (!gate.run)
|
|
114
|
+
return gate.message ?? "OKed: this action was not run.";
|
|
115
|
+
return Reflect.apply(func, target, args);
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
if (prop === "batch") {
|
|
119
|
+
const batch = Reflect.get(target, "batch", target);
|
|
120
|
+
if (typeof batch !== "function")
|
|
121
|
+
return batch;
|
|
122
|
+
return (inputs, ...rest) => {
|
|
123
|
+
if (!Array.isArray(inputs))
|
|
124
|
+
return Reflect.apply(batch, target, [inputs, ...rest]);
|
|
125
|
+
const config = rest[0];
|
|
126
|
+
return Promise.all(inputs.map((input) => run(input, config)));
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
// Bind to the original tool, not the proxy, so methods that use
|
|
130
|
+
// private fields keep working. invoke/call/func/batch are the
|
|
131
|
+
// execution paths and are gated above.
|
|
132
|
+
const value = Reflect.get(target, prop, target);
|
|
133
|
+
if (typeof value === "function")
|
|
134
|
+
return value.bind(target);
|
|
135
|
+
return value;
|
|
136
|
+
},
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Wrap each tool with one shared client. Pass the array to `new ToolNode(tools)`
|
|
141
|
+
* or `createReactAgent({ llm, tools })`. An already wrapped tool is left as it is.
|
|
142
|
+
*/
|
|
143
|
+
export function withOkedApprovals(tools, options) {
|
|
144
|
+
if (!Array.isArray(tools)) {
|
|
145
|
+
throw new TypeError("OKed: withOkedApprovals expected an array of tools");
|
|
146
|
+
}
|
|
147
|
+
const shared = options?.client
|
|
148
|
+
? options
|
|
149
|
+
: { ...options, client: createOkedClient(options) };
|
|
150
|
+
return tools.map((tool) => withOkedApproval(tool, shared));
|
|
151
|
+
}
|
|
152
|
+
export { createOkedClient, gateToolCall };
|
package/package.json
CHANGED
|
@@ -1,6 +1,70 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@oked/langgraph",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.6.21",
|
|
4
|
+
"description": "OKed for LangGraph and LangChain. Wraps a tool so a risky call waits for a human approval before it runs.",
|
|
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 && node src/langgraph.test.mjs",
|
|
24
|
+
"prepublishOnly": "npm run build"
|
|
25
|
+
},
|
|
26
|
+
"peerDependencies": {
|
|
27
|
+
"@langchain/core": ">=0.2.31",
|
|
28
|
+
"@langchain/langgraph": ">=0.2.0"
|
|
29
|
+
},
|
|
30
|
+
"peerDependenciesMeta": {
|
|
31
|
+
"@langchain/langgraph": {
|
|
32
|
+
"optional": true
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"@oked/sdk": "0.6.21"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@langchain/core": "0.3.80",
|
|
40
|
+
"@langchain/langgraph": "0.4.9",
|
|
41
|
+
"@types/node": "^22.13.10",
|
|
42
|
+
"typescript": "^5.6.0",
|
|
43
|
+
"zod": "^3.25.32"
|
|
44
|
+
},
|
|
45
|
+
"keywords": [
|
|
46
|
+
"oked",
|
|
47
|
+
"langgraph",
|
|
48
|
+
"langchain",
|
|
49
|
+
"ai-agent",
|
|
50
|
+
"approval",
|
|
51
|
+
"human-in-the-loop",
|
|
52
|
+
"hooks"
|
|
53
|
+
],
|
|
54
|
+
"repository": {
|
|
55
|
+
"type": "git",
|
|
56
|
+
"url": "git+https://github.com/oked-ai/oked-sdk.git",
|
|
57
|
+
"directory": "packages/langgraph"
|
|
58
|
+
},
|
|
59
|
+
"bugs": {
|
|
60
|
+
"url": "https://github.com/oked-ai/oked-sdk/issues"
|
|
61
|
+
},
|
|
62
|
+
"homepage": "https://oked.ai",
|
|
63
|
+
"license": "Apache-2.0",
|
|
64
|
+
"engines": {
|
|
65
|
+
"node": ">=18"
|
|
66
|
+
},
|
|
67
|
+
"publishConfig": {
|
|
68
|
+
"access": "public"
|
|
69
|
+
}
|
|
70
|
+
}
|