@byokit/openclaw 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/LICENSE +202 -0
  3. package/README.md +174 -0
  4. package/dist/approvals.d.ts +29 -0
  5. package/dist/approvals.js +200 -0
  6. package/dist/bridge.d.ts +78 -0
  7. package/dist/bridge.js +345 -0
  8. package/dist/classify.d.ts +4 -0
  9. package/dist/classify.js +14 -0
  10. package/dist/config.d.ts +13 -0
  11. package/dist/config.js +74 -0
  12. package/dist/constants.d.ts +3 -0
  13. package/dist/constants.js +13 -0
  14. package/dist/device.d.ts +63 -0
  15. package/dist/device.js +192 -0
  16. package/dist/engine.d.ts +43 -0
  17. package/dist/engine.js +212 -0
  18. package/dist/generated/events.d.ts +61 -0
  19. package/dist/generated/events.js +1 -0
  20. package/dist/generated/methods.d.ts +2368 -0
  21. package/dist/generated/methods.js +1 -0
  22. package/dist/generated/params.d.ts +1717 -0
  23. package/dist/generated/params.js +5 -0
  24. package/dist/generated/report.json +1356 -0
  25. package/dist/index.d.ts +4 -0
  26. package/dist/index.js +5 -0
  27. package/dist/kit.d.ts +108 -0
  28. package/dist/kit.js +655 -0
  29. package/dist/link.d.ts +24 -0
  30. package/dist/link.js +273 -0
  31. package/dist/members.d.ts +11 -0
  32. package/dist/members.js +23 -0
  33. package/dist/migrate.d.ts +22 -0
  34. package/dist/migrate.js +118 -0
  35. package/dist/notices.d.ts +9 -0
  36. package/dist/notices.js +75 -0
  37. package/dist/routes.d.ts +9 -0
  38. package/dist/routes.js +15 -0
  39. package/dist/routes.json +398 -0
  40. package/dist/runs.d.ts +14 -0
  41. package/dist/runs.js +110 -0
  42. package/dist/signin.d.ts +24 -0
  43. package/dist/signin.js +251 -0
  44. package/dist/testing/contract.d.ts +12 -0
  45. package/dist/testing/contract.js +250 -0
  46. package/dist/testing/fake-gateway.d.ts +19 -0
  47. package/dist/testing/fake-gateway.js +378 -0
  48. package/dist/testing/index.d.ts +3 -0
  49. package/dist/testing/index.js +4 -0
  50. package/dist/testing/model-stub.d.ts +29 -0
  51. package/dist/testing/model-stub.js +182 -0
  52. package/dist/transport.d.ts +22 -0
  53. package/dist/transport.js +94 -0
  54. package/dist/types.d.ts +125 -0
  55. package/dist/types.js +2 -0
  56. package/dist/words.d.ts +12 -0
  57. package/dist/words.js +26 -0
  58. package/dist/words.json +20 -0
  59. package/engine/package-lock.json +4680 -0
  60. package/engine/package.json +1 -0
  61. package/package.json +68 -0
  62. package/plugin/index.js +183 -0
  63. package/plugin/package.json +1 -0
  64. package/policy/policy.mjs +197 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,47 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ ## 0.1.0 (2026-09-29)
6
+
7
+ - First release on npm (docs/runtime-kits.md §10). `examples/openclaw-kit` (O12) is the whole flow from a phone
8
+ browser: pair, sign in with ChatGPT by device code, a streamed run, a tool that asks first, Allow and Deny. Its
9
+ e2e runs in CI from the packed packages against the fake Gateway; `LIVE.md` is the real-engine check.
10
+ - `.` and `./device` export the kit's sentences (`words`, `stateWords`, `toAccountView`, `WordKey`, `AccountView`),
11
+ and `./device` the types a device screen needs (`Approval`, `Decision`, `KitState`, `Route`, `RunEnd`, `RunEvent`,
12
+ `SignInView`).
13
+ - FIX: `oc.signin.view`'s `ready` (and so `openclawDevice(link).signIn.view(p).ready`) is the member's sign-in to that
14
+ provider, not the engine being up. Before, a phone's `phaseOf` said `done` while the device code was still showing,
15
+ and a member who was never signed in looked signed in.
16
+ - FIX: `signIn.view(p)` drops a finished sign-in once its account is gone (signed out over the link, on the computer,
17
+ or by the engine), so it no longer shows that old sign-in as done.
18
+ - Depends on @byokit/link 0.3.2.
19
+ - Depends on @byokit/relay 0.2.1.
20
+
21
+ - FIX: the account an app picks for a run is now the one the engine calls and bills. `RunSpec.model`
22
+ (`'provider/model'`, also `oc.run`'s `model` and `openclawDevice(link).run(message, { model })`) goes to the engine as
23
+ that run's own provider and model, with no fallback to another provider or model. A provider the member isn't
24
+ signed in to ends the run `signed-out` before the engine is called. A malformed reference, or one carrying an
25
+ `@profile` sign-in pin, is refused. Leaving it out sends the same request as before. The choice is per provider:
26
+ with two sign-ins for one provider the engine may still switch between them, so a single sign-in can't be picked.
27
+
28
+ - Typed device pass-through (G4, docs/runtime-kits.md 7.2): `openclawDevice(link).call<M>(method, params)` returns
29
+ `GatewayResult<M>` from the generated table (params now required, as on the kit), `events()` yields
30
+ `OpenClawLinkEvent` frames, and `./device` re-exports the table types. The device gains `sessions()` (`oc.sessions`,
31
+ *view*) and `signOut(p)` (`oc.signout`).
32
+ - FIX: `GatewayParams` for every anyOf/oneOf method now carries each branch's full property set from the pin's `protocol.schema.json` (re-emitted into `src/generated/params.ts` by `npm run gen:openclaw`), so `kit.call('cron.run', { id, mode: 'force' })` compiles; branch requirements the old types dropped (`cron.scratch.set` content, `cron.update` patch) and oneOf exclusions (`sessions.dispatch`, `exec.approvals.node.set`, `audit.run.inspect`, spelled as `prop?: never`) are enforced the way the gateway validates them.
33
+ - SECURITY: the operator install policy blocks any skill request whose kind contains `depend` (e.g. `skill-dependency-install`) even under an own root; previously only `installSpec` installer fields were checked.
34
+ - FIX: the trusted-skill version check uses `request.origin.version` when present and falls back to the `SKILL.md` frontmatter version, so reviewed bundled skills without a frontmatter version match their trusted entry.
35
+ - SECURITY: the bridge aborts the `AbortSignal` handed to `host.call` when that call's plugin socket closes or errors before the reply is written, so an aborted run no longer leaves the sandboxed command running; the listener is removed after a normal reply.
36
+ - SECURITY: the bridge plugin's `before_tool_call` relays every tool call to `ToolHost.gate`, engine builtins (`web_fetch`, `web_search`, memory and skill tools) included; before, anything outside `tools` ran ungated. The gate gets a fourth argument `{ builtin }`, an allowed builtin gets no permit or ticket, an unregistered session key is denied unless `allowOnce` matches, and a kit with no host blocks every tool. `KitOptions.gateBuiltins: false` restores gating only the app's tools. `prepare` now rewrites a stale `plugin/index.js`, so existing state dirs pick the gate up. A tool name the engine would rename before the hook (not `/^[a-z][a-z0-9_]*$/`, or `bash`/`cron`) is refused at construction, so an app tool never reaches the gate marked builtin.
37
+ - FIX: the packed `dist/words.d.ts` keeps `with { type: 'json' }` on its `./words.json` import, so a strict NodeNext consumer with `skipLibCheck: false` no longer fails with TS1543.
38
+ - FIX: `gatewayTransport` reads the Crewhouse legacy `device.json` shape (`deviceId`, `publicKeyPem`, `privateKeyPem`) as well as the kit's (`privateKey`, `publicKey`); an existing file is only read, never rewritten, and a file holding neither shape fails naming the file.
39
+ - FIX: `OpenClawKit.call()` before `start()` returns a rejected promise (`gateway not ready`) instead of throwing synchronously.
40
+ - The bridge no longer keys behavior on the plugin id: `KitOptions.bridge` (`socketName`, `paramPrefix`,
41
+ validated, defaulting to `bridge.sock` / `__byokit`) replaces the `crewhouse` special-cases, and
42
+ `startModelStub` takes a configurable `idPattern` and routing marker instead of a fixed prompt grammar
43
+ (docs/runtime-kits.md §§5.5/5.9; adopting apps pass their own values explicitly).
44
+
45
+ - `./testing`: the fake Gateway (`fakeGateway`), the contract suite (`openclawContract`, also run against the real
46
+ pinned engine) and the scripted model (`startModelStub`/`useModelStub`), ported from Crewhouse's test stubs with the
47
+ script grammar unchanged (docs/runtime-kits.md §5.11).
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,174 @@
1
+ <h1 align="center">@byokit/openclaw</h1>
2
+
3
+ <p align="center">
4
+ <a href="https://www.npmjs.com/package/@byokit/openclaw"><img alt="npm" src="https://img.shields.io/npm/v/@byokit/openclaw?style=flat" /></a>
5
+ <a href="https://github.com/umeranjum17/byokit/actions/workflows/ci.yml"><img alt="CI" src="https://img.shields.io/github/actions/workflow/status/umeranjum17/byokit/ci.yml?style=flat&branch=main" /></a>
6
+ <a href="LICENSE"><img alt="Apache 2.0" src="https://img.shields.io/badge/license-Apache--2.0-666?style=flat" /></a>
7
+ </p>
8
+
9
+ <p align="center"><strong>The OpenClaw runtime kit: one object that runs the pinned engine for your app.</strong><br/>
10
+ It drives the pinned OpenClaw engine (<code>openclaw@2026.8.1</code>, protocol 4) through one kit object. The
11
+ aggregator's full operator surface stays available as typed pass-through calls (<code>call</code> for every operator
12
+ method, <code>callDynamic</code> for the rest), with plain-words helpers for members, sign-in, runs, approvals and
13
+ config. For apps built on OpenClaw, where the engine holds the subscriptions.</p>
14
+
15
+ ## Install
16
+
17
+ ```sh
18
+ npm install @byokit/openclaw
19
+ ```
20
+
21
+ [![npm](https://img.shields.io/npm/v/@byokit/openclaw?style=flat&label=)](https://www.npmjs.com/package/@byokit/openclaw) · [Latest release](https://github.com/umeranjum17/byokit/releases?q=openclaw-v) · [All releases](https://github.com/umeranjum17/byokit/releases)
22
+
23
+ Node 22.18 or later. The kit brings the engine with it: the first `start()` installs the pinned `openclaw@2026.8.1`
24
+ under your `stateDir` (a few minutes, needs the network once), and later starts run from there. For a whole app, a
25
+ phone page that pairs, signs in with ChatGPT, runs and answers approvals, see
26
+ [`examples/openclaw-kit`](../../examples/openclaw-kit).
27
+
28
+ ## Quickstart
29
+
30
+ Start the engine, add a member, sign them in with a subscription, run a message (typechecked; running it installs
31
+ the pinned engine and needs a real ChatGPT sign-in, so it is not run here):
32
+
33
+ ```ts
34
+ import { OpenClawKit } from '@byokit/openclaw';
35
+
36
+ const kit = new OpenClawKit({ stateDir: './openclaw-state' });
37
+ await kit.start(); // installs the pinned engine under stateDir, spawns it, connects
38
+
39
+ await kit.ensureMember('ana');
40
+ const signIn = kit.signIn('ana', { authChoice: 'openai-device-code', via: 'code' }, (view) => console.log(view));
41
+ await signIn.done;
42
+
43
+ const end = await kit.run(
44
+ { member: 'ana', sessionKey: 'agent:ana:main', message: 'Say hello.' },
45
+ (e) => { if (e.type === 'text') console.log(e.text); },
46
+ );
47
+ console.log(end);
48
+ await kit.stop();
49
+ ```
50
+
51
+ To choose which of a member's accounts a run uses, pass `model: 'provider/model'` in the run spec (for example
52
+ `'openai/gpt-5.1'`, where `provider` is an id `kit.providers(member)` lists). That provider is the one called and billed for this run only, with no fallback to another
53
+ provider or model. If the member isn't signed in to it, the run ends `{ ok: false, kind: 'signed-out' }` and the
54
+ engine is never called. Leave `model` out to keep the engine's own choice. A specific sign-in (`@profile`) can't be
55
+ picked per run: the pinned engine may still switch to another sign-in for the same provider.
56
+
57
+ The same kit runs offline against the fake Gateway from `@byokit/openclaw/testing` (no engine, no network, no
58
+ account), and lists the sign-in routes it offers:
59
+
60
+ ```ts
61
+ import { mkdtempSync, rmSync } from 'node:fs';
62
+ import { tmpdir } from 'node:os';
63
+ import { join } from 'node:path';
64
+ import { OpenClawKit } from '@byokit/openclaw';
65
+ import { fakeGateway } from '@byokit/openclaw/testing';
66
+
67
+ const stateDir = mkdtempSync(join(tmpdir(), 'openclaw-readme-'));
68
+ const kit = new OpenClawKit({ stateDir, spawnEngine: false, transport: fakeGateway().factory });
69
+ try {
70
+ await kit.start();
71
+ console.log('state:', kit.state.phase, '| protocol:', kit.hello?.protocol);
72
+ await kit.ensureMember('ana');
73
+ const end = await kit.run(
74
+ { member: 'ana', sessionKey: 'agent:ana:main', message: 'Say hello.' },
75
+ (e) => console.log('event:', JSON.stringify(e)),
76
+ );
77
+ console.log('end:', JSON.stringify(end));
78
+ for (const r of kit.routes().filter((r) => r.offer))
79
+ console.log(`route: ${r.choice.padEnd(26)} ${r.billing.padEnd(12)} ${r.via}`);
80
+ } finally {
81
+ await kit.stop();
82
+ rmSync(stateDir, { recursive: true, force: true });
83
+ }
84
+ ```
85
+
86
+ Its output, run from this repo with Node:
87
+
88
+ ```text
89
+ state: ready | protocol: 4
90
+ event: {"type":"text","text":"fake: Say hello."}
91
+ event: {"type":"text","text":"fake: Say hello."}
92
+ end: {"ok":true,"text":"fake: Say hello."}
93
+ route: openai subscription browser
94
+ route: openai-device-code subscription code
95
+ route: xai-oauth subscription code
96
+ route: github-copilot subscription code
97
+ route: github-copilot-enterprise subscription code
98
+ route: minimax-global-oauth subscription code
99
+ route: minimax-cn-oauth subscription code
100
+ ```
101
+
102
+ Every offered route is a subscription sign-in. Each `Route` carries `billing` (`subscription`, `api` or `local`), so
103
+ an app labels any other route it shows; API-billed routes are not offered by default.
104
+
105
+ ## API at a glance
106
+
107
+ Entries:
108
+
109
+ - `.` is the host side: `OpenClawKit`, engine supervision, config invariants, approvals (Node).
110
+ - `./device` is the portable client for phones and browsers (no Node imports).
111
+ - `./link` is the host-side `@byokit/link` adapter: member-checked ops, sealed approval push (Node).
112
+ - `./testing` holds `fakeGateway`, the `openclawContract` suite and the scripted model stub.
113
+
114
+ | Export | What it does |
115
+ | --- | --- |
116
+ | `OpenClawKit` (`.`) | Prepares, starts, supervises and stops the engine. `call` / `callDynamic` pass through to the Gateway, `onEvent` listens. Helpers: `ensureMember`, `routes`, `providers`, `signedIn`, `signIn`, `signOut`, `migrateRetainedLogin`, `confirmRetainedLogin`, `run`, `steer`, `abort`, `approvals`, `onApproval`, `decide`, `allowOnce`, `disallowOnce`, `patchConfig`, `memoryLimited`, `doctorContext` |
117
+ | `ENGINE_VERSION`, `PROTOCOL_VERSION`, `OPERATOR_SCOPES` (`.`) | The pinned engine version, its protocol and the operator scopes the kit connects with |
118
+ | `KitOptions`, `RunSpec`, `RunEvent`, `RunEnd`, `Route`, `Approval`, `Decision`, `ToolSpec`, `ToolHost`, `KitState`, ... (`.`) | Public types (docs/runtime-kits.md §5.2) |
119
+ | `openclawDevice(link)` (`./device`) | Portable client: state, routes, sign-in, runs, steer, abort, approvals, events, sealed notices, pass-through `call` |
120
+ | `LinkRefused`, `openNotice` (`./device`) | The host's own refusal as an error; opens a sealed approval notice |
121
+ | `words`, `stateWords`, `toAccountView` (`.`, `./device`) | The kit's sentences, so a phone shows the words the computer does; `toAccountView` feeds `@byokit/ui-core`'s `phaseOf` |
122
+ | `openclawLink(kit, o)` (`./link`) | `handle` / `stream` / `allow` for a `@byokit/link` `Host`, checked per member, plus `onAction` for relay push actions |
123
+ | `serve(o)` (`./link`) | Binds the link host per reach and returns its URLs |
124
+ | `fakeGateway`, `openclawContract`, `startModelStub`, `useModelStub` (`./testing`) | In-memory Gateway, the contract suite and the scripted model for tests |
125
+
126
+ ## Phones and browsers
127
+
128
+ The host side serves member-checked ops over `@byokit/link`; the phone or browser uses the portable client:
129
+
130
+ ```ts
131
+ import { Host, keyPair, type DeviceLink } from '@byokit/link';
132
+ import { OpenClawKit } from '@byokit/openclaw';
133
+ import { openclawLink, serve } from '@byokit/openclaw/link';
134
+ import { openclawDevice } from '@byokit/openclaw/device';
135
+
136
+ // On the computer (Node): member-checked ops over @byokit/link, served per reach.
137
+ declare const kit: OpenClawKit;
138
+ declare const ask: (question: string) => Promise<boolean>; // your own prompt
139
+ const api = openclawLink(kit, { memberOf: (grant) => (grant.meta as { member?: string } | undefined)?.member });
140
+ const host = await Host.open({
141
+ keys: keyPair(),
142
+ name: 'My computer',
143
+ confirm: ({ name, words }) => ask(`Pair ${name}? Check it shows “${words}”.`),
144
+ ...api,
145
+ });
146
+ const served = await serve({ host, port: 8787, via: 'lan' });
147
+ console.log(served.urls);
148
+
149
+ // On the phone or in the browser: the portable client over a paired DeviceLink.
150
+ declare const link: DeviceLink;
151
+ const oc = openclawDevice(link);
152
+ for await (const e of oc.run('Say hello.')) console.log(e);
153
+ ```
154
+
155
+ ## Isolation and billing
156
+
157
+ The kit writes only under the `stateDir` the app passes. It spawns the engine with an explicit isolated environment
158
+ (never `process.env`), reads no environment variables except `PATH` to find `npm`, and never bills an API behind the
159
+ person's back (memory search is never a paid provider).
160
+
161
+ ## Status
162
+
163
+ Pinned to OpenClaw `2026.8.1` (protocol 4); `ENGINE_VERSION` and `PROTOCOL_VERSION` carry the pin. Signatures are
164
+ frozen (docs/runtime-kits.md §5).
165
+
166
+ ## Links
167
+
168
+ - [byokit](../../README.md), the repo root
169
+ - [docs/runtime-kits.md](../../docs/runtime-kits.md), the binding spec for this kit (§5)
170
+ - [CHANGELOG.md](CHANGELOG.md)
171
+
172
+ ## License
173
+
174
+ Apache-2.0. See [LICENSE](LICENSE) and [NOTICE](../../NOTICE).
@@ -0,0 +1,29 @@
1
+ import type { Bridge } from './bridge.ts';
2
+ import type { Approval, Decision, GatewayTransport, Member } from './types.ts';
3
+ export declare class Approvals {
4
+ private readonly request;
5
+ private readonly bridge;
6
+ private readonly approvals;
7
+ private readonly listeners;
8
+ constructor(o: {
9
+ request: GatewayTransport['request'];
10
+ bridge: Pick<Bridge, 'resolveAsk'>;
11
+ });
12
+ handleEvent(e: {
13
+ event: string;
14
+ payload?: unknown;
15
+ }): void;
16
+ add(a: Approval): void;
17
+ remove(id: string): void;
18
+ list(member?: Member): Approval[];
19
+ on(fn: (a: Approval, change: 'added' | 'resolved') => void): () => void;
20
+ /**
21
+ * Drop native approvals and replay the engine's current lists (N9): after a reconnect the engine may have
22
+ * resolved entries this kit still shows. Gate asks live in the bridge and are untouched. Rows are only
23
+ * trusted with a string id; anything else is skipped, never invented.
24
+ */
25
+ resync(): Promise<void>;
26
+ decide(id: string, d: Decision): Promise<void>;
27
+ private answersFor;
28
+ private emit;
29
+ }
@@ -0,0 +1,200 @@
1
+ // Native approvals: exec.approval.*, plugin.approval.* and question.* surfaced through the same Approval shape (5.9, O5).
2
+ import { randomBytes } from 'node:crypto';
3
+ import { MEMBER_ID } from "./members.js";
4
+ const strip = (a) => {
5
+ const { native, ...approval } = a;
6
+ void native;
7
+ return approval;
8
+ };
9
+ const REQUESTED = {
10
+ 'exec.approval.requested': 'exec',
11
+ 'plugin.approval.requested': 'plugin',
12
+ 'question.requested': 'question',
13
+ };
14
+ const RESOLVED = new Set(['exec.approval.resolved', 'plugin.approval.resolved', 'question.resolved']);
15
+ const isRecord = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
16
+ const asString = (v) => (typeof v === 'string' && v.length > 0 ? v : undefined);
17
+ const memberOfKey = (key) => {
18
+ const m = /^agent:([a-z][a-z0-9-]{0,31}):/.exec(key);
19
+ return m?.[1];
20
+ };
21
+ /**
22
+ * Member attribution: the request detail's agent first, else the `agent:<member>:` session key (5.9). The real
23
+ * engine nests exec/plugin details under `request` (question events stay flat); unattributed approvals carry ''
24
+ * so they can never match a member id (B2).
25
+ */
26
+ function attribute(payload) {
27
+ const detail = isRecord(payload.request) ? payload.request : payload;
28
+ const agent = asString(detail.agentId);
29
+ const key = asString(detail.sessionKey);
30
+ const fromKey = key ? memberOfKey(key) : undefined;
31
+ const member = agent ?? fromKey ?? asString(detail.member) ?? '';
32
+ return { member, ...(key ? { sessionKey: key } : {}) };
33
+ }
34
+ /** Exec policy modes (`off|on-miss|always`) ride in `request.ask`; they are not something a person said (B8). */
35
+ const POLICY_MODES = new Set(['off', 'on-miss', 'always']);
36
+ const askText = (detail) => {
37
+ const ask = asString(detail.ask);
38
+ return ask && !POLICY_MODES.has(ask) ? ask : undefined;
39
+ };
40
+ function summaryOf(source, payload) {
41
+ const detail = isRecord(payload.request) ? payload.request : payload;
42
+ if (source === 'exec')
43
+ return asString(detail.command) ? `run ${detail.command}` : (askText(detail) ?? 'approve an action');
44
+ if (source === 'plugin')
45
+ return asString(detail.title) ?? askText(detail) ?? 'approve an action';
46
+ const questions = detail.questions;
47
+ if (Array.isArray(questions)) {
48
+ const first = questions.map((q) => (isRecord(q) ? asString(q.question) ?? asString(q.header) : undefined)).find(Boolean);
49
+ if (first)
50
+ return first;
51
+ }
52
+ return 'answer a question';
53
+ }
54
+ function expiresOf(payload, fallbackMs) {
55
+ const at = typeof payload.expiresAtMs === 'number' ? payload.expiresAtMs : Date.now() + fallbackMs;
56
+ return at;
57
+ }
58
+ export class Approvals {
59
+ request;
60
+ bridge;
61
+ approvals = new Map();
62
+ listeners = new Set();
63
+ constructor(o) {
64
+ this.request = o.request;
65
+ this.bridge = o.bridge;
66
+ }
67
+ handleEvent(e) {
68
+ const payload = isRecord(e.payload) ? e.payload : {};
69
+ const source = REQUESTED[e.event];
70
+ if (source) {
71
+ const id = asString(payload.id) ?? randomBytes(12).toString('base64url');
72
+ if (this.approvals.has(id))
73
+ return;
74
+ const { member, sessionKey } = attribute(payload);
75
+ const detail = isRecord(payload.request) ? payload.request : payload;
76
+ const now = Date.now();
77
+ const approval = {
78
+ id,
79
+ source,
80
+ member,
81
+ ...(sessionKey ? { sessionKey } : {}),
82
+ ...(asString(detail.tool) ?? asString(detail.toolName) ? { tool: (asString(detail.tool) ?? asString(detail.toolName)) } : {}),
83
+ summary: summaryOf(source, payload),
84
+ ...('questions' in detail ? { input: detail.questions } : {}),
85
+ at: typeof payload.createdAtMs === 'number' ? payload.createdAtMs : now,
86
+ expires: expiresOf(payload, 180_000),
87
+ native: { source, id },
88
+ };
89
+ this.approvals.set(id, approval);
90
+ this.emit(approval, 'added');
91
+ return;
92
+ }
93
+ if (RESOLVED.has(e.event)) {
94
+ const id = asString(payload.id);
95
+ if (id)
96
+ this.remove(id);
97
+ }
98
+ return;
99
+ }
100
+ add(a) {
101
+ if (this.approvals.has(a.id))
102
+ return;
103
+ this.approvals.set(a.id, a);
104
+ this.emit(a, 'added');
105
+ }
106
+ remove(id) {
107
+ const a = this.approvals.get(id);
108
+ if (!a)
109
+ return;
110
+ this.approvals.delete(id);
111
+ this.emit(strip(a), 'resolved');
112
+ }
113
+ list(member) {
114
+ const all = [...this.approvals.values()].map(strip);
115
+ if (member === undefined)
116
+ return all;
117
+ if (!MEMBER_ID.test(member))
118
+ return [];
119
+ return all.filter((a) => a.member === member);
120
+ }
121
+ on(fn) {
122
+ this.listeners.add(fn);
123
+ return () => {
124
+ this.listeners.delete(fn);
125
+ };
126
+ }
127
+ /**
128
+ * Drop native approvals and replay the engine's current lists (N9): after a reconnect the engine may have
129
+ * resolved entries this kit still shows. Gate asks live in the bridge and are untouched. Rows are only
130
+ * trusted with a string id; anything else is skipped, never invented.
131
+ */
132
+ async resync() {
133
+ for (const [id, a] of this.approvals) {
134
+ if (!a.native)
135
+ continue;
136
+ this.approvals.delete(id);
137
+ this.emit(strip(a), 'resolved');
138
+ }
139
+ const lists = {
140
+ 'exec.approval.list': 'exec.approval.requested',
141
+ 'plugin.approval.list': 'plugin.approval.requested',
142
+ };
143
+ for (const [method, event] of Object.entries(lists)) {
144
+ let answer;
145
+ try {
146
+ answer = await this.request(method, {});
147
+ }
148
+ catch {
149
+ continue;
150
+ }
151
+ const rows = Array.isArray(answer)
152
+ ? answer
153
+ : isRecord(answer)
154
+ ? (['approvals', 'items', 'records', 'entries'].map((k) => answer[k]).find(Array.isArray) ?? [])
155
+ : [];
156
+ for (const row of rows) {
157
+ if (!isRecord(row) || typeof row.id !== 'string')
158
+ continue;
159
+ this.handleEvent({ event, payload: row });
160
+ }
161
+ }
162
+ }
163
+ async decide(id, d) {
164
+ const a = this.approvals.get(id);
165
+ if (!a)
166
+ throw new Error(`unknown approval: ${id}`);
167
+ if (a.source === 'gate') {
168
+ if (!this.bridge.resolveAsk(id, d))
169
+ throw new Error(`unknown approval: ${id}`);
170
+ return;
171
+ }
172
+ const native = a.native;
173
+ if (!native)
174
+ throw new Error(`unknown approval: ${id}`);
175
+ if (native.source === 'exec' || native.source === 'plugin') {
176
+ const method = native.source === 'exec' ? 'exec.approval.resolve' : 'plugin.approval.resolve';
177
+ await this.request(method, { id: native.id, decision: d.allow ? 'allow-once' : 'deny' });
178
+ return;
179
+ }
180
+ if (d.allow) {
181
+ await this.request('question.resolve', { id: native.id, answers: this.answersFor(a, d.answer) });
182
+ }
183
+ else {
184
+ await this.request('question.resolve', { id: native.id, cancel: true });
185
+ }
186
+ }
187
+ answersFor(a, answer) {
188
+ if (isRecord(answer) && 'answers' in answer)
189
+ return answer;
190
+ const questions = Array.isArray(a.input) ? a.input : [];
191
+ const ids = questions.filter(isRecord).map((q) => asString(q.questionId)).filter(Boolean);
192
+ if (ids.length === 1 && Array.isArray(answer))
193
+ return { answers: { [ids[0]]: answer } };
194
+ throw new Error('a question approval needs answers for its questions');
195
+ }
196
+ emit(a, change) {
197
+ for (const fn of this.listeners)
198
+ fn(a, change);
199
+ }
200
+ }