@clawkeepers/shared 0.1.0-beta.1

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ControlStackAI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,206 @@
1
+ OpenClaw OS
2
+ Copyright (c) 2026 ControlStackAI
3
+ Original project contributions are licensed under the MIT License; see LICENSE.
4
+ Third-party and adapted material retains its applicable license terms.
5
+
6
+ OpenClaw (https://github.com/openclaw/openclaw) provides the separately installed,
7
+ unmodified agent runtime, Gateway and public plugin interfaces. Its pinned
8
+ v2026.9.2 license is MIT, copyright (c) 2026 OpenClaw Foundation; its own
9
+ THIRD_PARTY_NOTICES.md applies to incorporated upstream dependencies.
10
+
11
+ Cloudflare OS (https://github.com/cloudflare/cloudflare-os), by Cloudflare and
12
+ its contributors, provides architectural foundations and adapted material:
13
+ capability introductions, gatekeepers, approval/simulation contracts, observers,
14
+ and kernel review/authoring guidance. OpenClaw OS contributors modified these
15
+ contracts and documents for a self-hosted, single-process, tool-calling plugin
16
+ runtime. Cloudflare OS Starter (https://github.com/cloudflare/cloudflare-os-starter)
17
+ informed wrapper-owned customization and the upgrade discipline.
18
+
19
+ Cloudflare OS and Cloudflare OS Starter are Apache-2.0 licensed. Their retained
20
+ material is not relicensed by the project's MIT license. The applicable Apache
21
+ License 2.0 text is reproduced below. The original source distribution includes
22
+ further provenance in docs/acknowledgments.md. Other dependencies retain their
23
+ respective licenses and notices, including generated THIRD-PARTY-NOTICES for
24
+ bundled dependencies.
25
+
26
+ This is an independent project, not an upstream-endorsed product. No affiliation,
27
+ endorsement or rights to upstream trademarks are implied.
28
+
29
+ --- Apache License 2.0: retained Cloudflare material ---
30
+
31
+ Apache License
32
+ Version 2.0, January 2004
33
+ http://www.apache.org/licenses/
34
+
35
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
36
+
37
+ 1. Definitions.
38
+
39
+ "License" shall mean the terms and conditions for use, reproduction,
40
+ and distribution as defined by Sections 1 through 9 of this document.
41
+
42
+ "Licensor" shall mean the copyright owner or entity authorized by
43
+ the copyright owner that is granting the License.
44
+
45
+ "Legal Entity" shall mean the union of the acting entity and all
46
+ other entities that control, are controlled by, or are under common
47
+ control with that entity. For the purposes of this definition,
48
+ "control" means (i) the power, direct or indirect, to cause the
49
+ direction or management of such entity, whether by contract or
50
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
51
+ outstanding shares, or (iii) beneficial ownership of such entity.
52
+
53
+ "You" (or "Your") shall mean an individual or Legal Entity
54
+ exercising permissions granted by this License.
55
+
56
+ "Source" form shall mean the preferred form for making modifications,
57
+ including but not limited to software source code, documentation
58
+ source, and configuration files.
59
+
60
+ "Object" form shall mean any form resulting from mechanical
61
+ transformation or translation of a Source form, including but
62
+ not limited to compiled object code, generated documentation,
63
+ and conversions to other media types.
64
+
65
+ "Work" shall mean the work of authorship, whether in Source or
66
+ Object form, made available under the License, as indicated by a
67
+ copyright notice that is included in or attached to the work
68
+ (an example is provided in the Appendix below).
69
+
70
+ "Derivative Works" shall mean any work, whether in Source or Object
71
+ form, that is based on (or derived from) the Work and for which the
72
+ editorial revisions, annotations, elaborations, or other modifications
73
+ represent, as a whole, an original work of authorship. For the purposes
74
+ of this License, Derivative Works shall not include works that remain
75
+ separable from, or merely link (or bind by name) to the interfaces of,
76
+ the Work and Derivative Works thereof.
77
+
78
+ "Contribution" shall mean any work of authorship, including
79
+ the original version of the Work and any modifications or additions
80
+ to that Work or Derivative Works thereof, that is intentionally
81
+ submitted to Licensor for inclusion in the Work by the copyright owner
82
+ or by an individual or Legal Entity authorized to submit on behalf of
83
+ the copyright owner. For the purposes of this definition, "submitted"
84
+ means any form of electronic, verbal, or written communication sent
85
+ to the Licensor or its representatives, including but not limited to
86
+ communication on electronic mailing lists, source code control systems,
87
+ and issue tracking systems that are managed by, or on behalf of, the
88
+ Licensor for the purpose of discussing and improving the Work, but
89
+ excluding communication that is conspicuously marked or otherwise
90
+ designated in writing by the copyright owner as "Not a Contribution."
91
+
92
+ "Contributor" shall mean Licensor and any individual or Legal Entity
93
+ on behalf of whom a Contribution has been received by Licensor and
94
+ subsequently incorporated within the Work.
95
+
96
+ 2. Grant of Copyright License. Subject to the terms and conditions of
97
+ this License, each Contributor hereby grants to You a perpetual,
98
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
99
+ copyright license to reproduce, prepare Derivative Works of,
100
+ publicly display, publicly perform, sublicense, and distribute the
101
+ Work and such Derivative Works in Source or Object form.
102
+
103
+ 3. Grant of Patent License. Subject to the terms and conditions of
104
+ this License, each Contributor hereby grants to You a perpetual,
105
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
106
+ (except as stated in this section) patent license to make, have made,
107
+ use, offer to sell, sell, import, and otherwise transfer the Work,
108
+ where such license applies only to those patent claims licensable
109
+ by such Contributor that are necessarily infringed by their
110
+ Contribution(s) alone or by combination of their Contribution(s)
111
+ with the Work to which such Contribution(s) was submitted. If You
112
+ institute patent litigation against any entity (including a
113
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
114
+ or a Contribution incorporated within the Work constitutes direct
115
+ or contributory patent infringement, then any patent licenses
116
+ granted to You under this License for that Work shall terminate
117
+ as of the date such litigation is filed.
118
+
119
+ 4. Redistribution. You may reproduce and distribute copies of the
120
+ Work or Derivative Works thereof in any medium, with or without
121
+ modifications, and in Source or Object form, provided that You
122
+ meet the following conditions:
123
+
124
+ (a) You must give any other recipients of the Work or
125
+ Derivative Works a copy of this License; and
126
+
127
+ (b) You must cause any modified files to carry prominent notices
128
+ stating that You changed the files; and
129
+
130
+ (c) You must retain, in the Source form of any Derivative Works
131
+ that You distribute, all copyright, patent, trademark, and
132
+ attribution notices from the Source form of the Work,
133
+ excluding those notices that do not pertain to any part of
134
+ the Derivative Works; and
135
+
136
+ (d) If the Work includes a "NOTICE" text file as part of its
137
+ distribution, then any Derivative Works that You distribute must
138
+ include a readable copy of the attribution notices contained
139
+ within such NOTICE file, excluding those notices that do not
140
+ pertain to any part of the Derivative Works, in at least one
141
+ of the following places: within a NOTICE text file distributed
142
+ as part of the Derivative Works; within the Source form or
143
+ documentation, if provided along with the Derivative Works; or,
144
+ within a display generated by the Derivative Works, if and
145
+ wherever such third-party notices normally appear. The contents
146
+ of the NOTICE file are for informational purposes only and
147
+ do not modify the License. You may add Your own attribution
148
+ notices within Derivative Works that You distribute, alongside
149
+ or as an addendum to the NOTICE text from the Work, provided
150
+ that such additional attribution notices cannot be construed
151
+ as modifying the License.
152
+
153
+ You may add Your own copyright statement to Your modifications and
154
+ may provide additional or different license terms and conditions
155
+ for use, reproduction, or distribution of Your modifications, or
156
+ for any such Derivative Works as a whole, provided Your use,
157
+ reproduction, and distribution of the Work otherwise complies with
158
+ the conditions stated in this License.
159
+
160
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
161
+ any Contribution intentionally submitted for inclusion in the Work
162
+ by You to the Licensor shall be under the terms and conditions of
163
+ this License, without any additional terms or conditions.
164
+ Notwithstanding the above, nothing herein shall supersede or modify
165
+ the terms of any separate license agreement you may have executed
166
+ with Licensor regarding such Contributions.
167
+
168
+ 6. Trademarks. This License does not grant permission to use the trade
169
+ names, trademarks, service marks, or product names of the Licensor,
170
+ except as required for reasonable and customary use in describing the
171
+ origin of the Work and reproducing the content of the NOTICE file.
172
+
173
+ 7. Disclaimer of Warranty. Unless required by applicable law or
174
+ agreed to in writing, Licensor provides the Work (and each
175
+ Contributor provides its Contributions) on an "AS IS" BASIS,
176
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
177
+ implied, including, without limitation, any warranties or conditions
178
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
179
+ PARTICULAR PURPOSE. You are solely responsible for determining the
180
+ appropriateness of using or redistributing the Work and assume any
181
+ risks associated with Your exercise of permissions under this License.
182
+
183
+ 8. Limitation of Liability. In no event and under no legal theory,
184
+ whether in tort (including negligence), contract, or otherwise,
185
+ unless required by applicable law (such as deliberate and grossly
186
+ negligent acts) or agreed to in writing, shall any Contributor be
187
+ liable to You for damages, including any direct, indirect, special,
188
+ incidental, or consequential damages of any character arising as a
189
+ result of this License or out of the use or inability to use the
190
+ Work (including but not limited to damages for loss of goodwill,
191
+ work stoppage, computer failure or malfunction, or any and all
192
+ other commercial damages or losses), even if such Contributor
193
+ has been advised of the possibility of such damages.
194
+
195
+ 9. Accepting Warranty or Additional Liability. While redistributing
196
+ the Work or Derivative Works thereof, You may choose to offer,
197
+ and charge a fee for, acceptance of support, warranty, indemnity,
198
+ or other liability obligations and/or rights consistent with this
199
+ License. However, in accepting such obligations, You may act only
200
+ on Your own behalf and on Your sole responsibility, not on behalf
201
+ of any other Contributor, and only if You agree to indemnify,
202
+ defend, and hold each Contributor harmless for any liability
203
+ incurred by, or claims asserted against, such Contributor by reason
204
+ of your accepting any such warranty or additional liability.
205
+
206
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,17 @@
1
+ # @clawkeepers/shared
2
+
3
+ Contracts for plan §4.3. **Kernel bar:** every exported member is documented. This package depends only on TypeBox.
4
+
5
+ `src/schemas.ts` supplies strict JSON schemas for resource/tool metadata, observations and actions, dry-pass and tool
6
+ results, private verifier transport, credential-free account/vendor/resource summaries, grants, queue rows, audit records,
7
+ status, and operator request payloads. Unknown fields are rejected. Identity comes from trusted RPC context, never a payload.
8
+
9
+ Queues, vendors, accounts, sessions and `SessionCallContext` are process-local interfaces, not wire types. Do not serialize
10
+ live implementations or approval callbacks. Normalize optional void decision results to `{}` for their wire schemas.
11
+ `PendingAction.descriptionJson` must also be parsed and checked with `ActionDescriptionSchema` by the store adapter.
12
+ Metadata schemas do not prove authorization or validate vendor business rules; those remain the kernel/kit's responsibility.
13
+
14
+ Grant handles use eight lowercase Crockford base32 symbols (`0-9a-hjkmnp-tv-z`), including the plan's `7k3m9q2p` example.
15
+ The old scaffold's all-alphanumeric regex was not base32. No runtime grant data has shipped yet.
16
+
17
+ Checks: `pnpm --filter @clawkeepers/shared test` and `pnpm --filter @clawkeepers/shared typecheck`.
@@ -0,0 +1,591 @@
1
+ import { TSchema, Type, Static } from 'typebox';
2
+
3
+ /**
4
+ * OpenClaw OS gatekeeper contracts — adapted from cloudflare-os `packages/workshop-shared/src/gatekeeper.ts`
5
+ * for a single-process, tool-calling runtime. See docs/implementation-plan.md §4.3.
6
+ *
7
+ * Kernel bar: every exported member is doc-commented. Do not add members without updating the plan.
8
+ */
9
+
10
+ /** A resource type this gatekeeper can grant, keyed by URL pattern. */
11
+ interface SupportedResource {
12
+ /** URLPattern string, e.g. "https://github.com/:owner/:repo". */
13
+ urlPattern: string;
14
+ /** Stable id for this resource type within the vendor, e.g. "repo". */
15
+ type: string;
16
+ /** Human-readable label; never includes credentials. */
17
+ title: string;
18
+ /** Human-readable explanation; never includes credentials. */
19
+ description: string;
20
+ /** If true, this type can be granted independently (scopes requested only for enabled types). */
21
+ grantable: boolean;
22
+ /** Observer strategy for bindings of this type (plan §4.7). */
23
+ observerStrategy: "private-only" | "acl-check" | "dataset-tracking" | "low-stakes";
24
+ /** Tool names available for a grant of this type. */
25
+ tools: string[];
26
+ }
27
+ /** Human-readable description of a read. Everything needed to decide, display, and audit. */
28
+ interface ObservationDescription {
29
+ /** Human-readable label; never includes credentials. */
30
+ title: string;
31
+ /** Markdown. Must include every detail relevant to approval. Never includes secrets. */
32
+ description: string;
33
+ /** Blunt stopgap: block if the session is shared, and put the grant into lockdown (observations only). */
34
+ prohibitAllSharing?: boolean;
35
+ /** Observers who must not see this data; the kernel blocks the observation if any is still present. */
36
+ excludeObservers?: string[];
37
+ }
38
+ /** Stable policy key; auto-approval rules match on `tag`. Treat as an enum. */
39
+ interface ActionKind {
40
+ /** Stable policy identifier; not a display label. */
41
+ tag: string;
42
+ /** Operator-facing name for this action kind. */
43
+ label: string;
44
+ }
45
+ /** Description of a side-effecting action, submitted before it is performed. */
46
+ interface ActionDescription {
47
+ /** Human-readable label; never includes credentials. */
48
+ title: string;
49
+ /** Human-readable explanation; never includes credentials. */
50
+ description: string;
51
+ /** Optional stable key for operator auto-approval policy. */
52
+ actionKind?: ActionKind;
53
+ /** Gatekeeper author's verdict that this specific action is safe to auto-apply if the user opted in for its kind. */
54
+ autoApprovable?: boolean;
55
+ /** True if the gatekeeper implements revertAction() for this action. */
56
+ implementsRevert: boolean;
57
+ /** If true, do NOT simulate: block the tool call until the human decides (maps to OpenClaw requireApproval). */
58
+ awaitDecision?: boolean;
59
+ /** Structured payload for the approval UI. Never includes secrets. */
60
+ preview?: unknown;
61
+ }
62
+ /** Handed to a gatekeeper session by the kernel. A gatekeeper never constructs one. */
63
+ interface ApprovalQueue {
64
+ /** Must be awaited before returning any data to the agent. Throws to deny. */
65
+ authorizeObservation(d: ObservationDescription): Promise<void>;
66
+ /** Fully asynchronous: returns as soon as the action is recorded. The human may decide days later. */
67
+ submitAction(actionId: number, d: ActionDescription): Promise<void>;
68
+ }
69
+ /** Result shape returned to the agent by gatekeeper tools. */
70
+ interface ToolResult {
71
+ /** Agent-visible text blocks. */
72
+ content: Array<{
73
+ type: "text";
74
+ text: string;
75
+ }>;
76
+ /** Optional structured result data; never credential material. */
77
+ details?: unknown;
78
+ }
79
+ /** Per-call context supplied by the kernel from its before_tool_call stash (plan §5.2). */
80
+ interface SessionCallContext {
81
+ /** Trusted agent identity supplied by the kernel. */
82
+ agentId: string;
83
+ /** Trusted session identity supplied by the kernel. */
84
+ sessionKey: string;
85
+ /** Upstream run identifier when available. */
86
+ runId?: string;
87
+ /** Upstream call identifier used for correlation. */
88
+ toolCallId?: string;
89
+ /** Kernel-owned approval queue; never supplied by tool parameters. */
90
+ queue: ApprovalQueue;
91
+ /** Present when the session has observers beyond its owner. */
92
+ observers?: string[];
93
+ /** True during the kernel's dry pass: return the description, perform no side effects. */
94
+ dryRun?: boolean;
95
+ /** Trusted pre-recorded synchronous approval. Never populated from tool parameters or serialized over RPC. */
96
+ actionApproval?: {
97
+ /** Exact upstream call that was approved. */
98
+ toolCallId: string;
99
+ /** Exact tool whose action was approved. */
100
+ tool: string;
101
+ /** Exact validated parameters retained by the kernel at approval time. */
102
+ params: Record<string, unknown>;
103
+ };
104
+ }
105
+ /** One live binding of (grant → gatekeeper resource) inside one agent session. */
106
+ interface GatekeeperSession {
107
+ /** Execute a tool of this resource type. `params` were validated against the tool schema by OpenClaw. */
108
+ call(tool: string, params: Record<string, unknown>, ctx: SessionCallContext): Promise<ToolResult | DryRunResult>;
109
+ /** Revoke this live session and deny subsequent calls. */
110
+ close(): Promise<void>;
111
+ }
112
+ /** What a dry pass returns: the description the kernel needs to decide before the real call. */
113
+ type DryRunResult = {
114
+ kind: "observation";
115
+ description: ObservationDescription;
116
+ } | {
117
+ kind: "action";
118
+ description: ActionDescription;
119
+ };
120
+ /** Opaque to everyone but the gatekeeper that minted it. */
121
+ interface ObserverVerifier {
122
+ /** Vendor that minted this opaque verifier. */
123
+ readonly vendor: string;
124
+ /** Private verifier material, not an agent-visible resource identifier. */
125
+ readonly opaque: string;
126
+ }
127
+ /** Per-resource instance. Created by the kernel through resolveGrant(). */
128
+ interface Gatekeeper {
129
+ /** Describe this object without returning credentials. */
130
+ describe(): Promise<{
131
+ resource: SupportedResource;
132
+ title: string;
133
+ suggestedName: string;
134
+ }>;
135
+ /** List action kinds eligible for an explicit operator policy. */
136
+ getAutoApprovableActions(): Promise<ActionKind[]>;
137
+ /** Bind a kernel-owned queue to this resource session. */
138
+ startSession(queue: ApprovalQueue): Promise<GatekeeperSession>;
139
+ /** Perform a previously submitted action for real. Idempotent. */
140
+ applyAction(actionId: number): Promise<void>;
141
+ /** Discard a pending action and its simulated effects. */
142
+ rejectAction(actionId: number): Promise<void | {
143
+ restart?: boolean;
144
+ }>;
145
+ /** Undo an applied action if implementsRevert. */
146
+ revertAction?(actionId: number): Promise<void | {
147
+ message?: string;
148
+ canRetry?: boolean;
149
+ }>;
150
+ /** Throw if this observer may not see everything this instance has read. */
151
+ addObserver(id: string, verifier: ObserverVerifier): Promise<void>;
152
+ /** Remove an observer from this resource instance. */
153
+ removeObserver(id: string): Promise<void>;
154
+ }
155
+ /** Per-operator account (one OAuth identity or static credential). */
156
+ interface GatekeeperAccount {
157
+ /** Describe this object without returning credentials. */
158
+ describe(): Promise<{
159
+ email?: string;
160
+ displayName?: string;
161
+ expiresAt?: number;
162
+ }>;
163
+ /** List the resource types supported by this account or vendor. */
164
+ getSupportedResources(): Promise<SupportedResource[]>;
165
+ /** Returns a Gatekeeper for the resource a URL denotes, with credentials bound. Called BEFORE any grant exists. */
166
+ getGatekeeperFor(url: string): Promise<{
167
+ gatekeeper: Gatekeeper;
168
+ resource: SupportedResource;
169
+ resourceKey: string;
170
+ }>;
171
+ /** Mint an opaque verifier that proves *this account's* access, for observer checks. */
172
+ getVerifier(): Promise<ObserverVerifier>;
173
+ /** Revoke the account credentials and active access. */
174
+ revoke(): Promise<void>;
175
+ /** Start account reconnection using a fresh authorization nonce. */
176
+ reconnect(): Promise<{
177
+ url: string;
178
+ }>;
179
+ }
180
+ /** Definition of one agent-facing tool. Registered with OpenClaw by the kernel, never by the gatekeeper. */
181
+ interface GatekeeperToolDef {
182
+ /** gk_<vendor>_<resource>_<verb> */
183
+ name: string;
184
+ /** Which SupportedResource.type it belongs to. */
185
+ resourceType: string;
186
+ /** Whether this tool reads or changes the external resource. */
187
+ kind: "observation" | "action";
188
+ /** NEVER mentions approvals, queues, caching, OAuth, or simulation. */
189
+ description: string;
190
+ /** Must include `grant: Type.String()`. */
191
+ parameters: TSchema;
192
+ /** Optional schema for structured agent-visible output. */
193
+ outputSchema?: TSchema;
194
+ }
195
+ /** Top-level vendor entry. One per gatekeeper plugin. */
196
+ interface GatekeeperVendor {
197
+ /** Stable vendor namespace. */
198
+ vendor: string;
199
+ /** Version of the OS gatekeeper contract. */
200
+ apiVersion: 1;
201
+ /** Describe this object without returning credentials. */
202
+ describe(): Promise<{
203
+ title: string;
204
+ description: string;
205
+ icon?: string;
206
+ autoProvisionsAccount?: boolean;
207
+ }>;
208
+ /** Start OAuth (or equivalent). The returned URL must embed a cryptographic nonce. */
209
+ connectAccount(operatorId: string, opts?: {
210
+ resourceTypes?: string[];
211
+ /** Kernel-minted callback nonce; preserve it as the authorization URL's exact state value. */
212
+ state?: string;
213
+ /** Fixed local callback path; resolve only against the vendor's configured public origin. */
214
+ callbackPath?: string;
215
+ }): Promise<{
216
+ url: string;
217
+ }>;
218
+ /** Exchange a nonce-validated code for the bound operator. Keep credentials within the vendor;
219
+ * preserve provider account/PKCE checks and store the result before resolving. The kernel never sees tokens. */
220
+ completeConnection?(operatorId: string, opts: {
221
+ code: string;
222
+ state: string;
223
+ resourceTypes?: string[];
224
+ }): Promise<void>;
225
+ /** For vendors that need no user auth (fs, mcp with static config). */
226
+ createAccount?(operatorId: string): Promise<GatekeeperAccount>;
227
+ /** Return this operator’s account, or null when disconnected. */
228
+ getAccount(operatorId: string): Promise<GatekeeperAccount | null>;
229
+ /** List the resource types supported by this account or vendor. */
230
+ getSupportedResources(): Promise<SupportedResource[]>;
231
+ /** Tool definitions for every tool this vendor exposes; the kernel registers them. */
232
+ getTools(): Promise<GatekeeperToolDef[]>;
233
+ }
234
+
235
+ /** Capability records (plan §4.4). Stored by the kernel in <stateDir>/os/clawos.sqlite. */
236
+ /** Lifecycle state of an introduced capability. */
237
+ type GrantStatus = "pending" | "active" | "revoked" | "lockdown";
238
+ /** A grant: one agent's access to one resource through one gatekeeper. */
239
+ interface Grant {
240
+ /** Opaque agent-visible handle, e.g. "grant:7k3m9q2p". Never encodes the resource. */
241
+ handle: string;
242
+ /** Agent that owns the capability. */
243
+ agentId: string;
244
+ /** Cell trust boundary that owns the capability. */
245
+ cellId: string;
246
+ /** Stable gatekeeper vendor namespace. */
247
+ vendor: string;
248
+ /** Resource type within its vendor. */
249
+ resourceType: string;
250
+ /** Vendor-specific key, e.g. "owner/repo". Never shown to the agent unless the operator marks it visible. */
251
+ resourceKey: string;
252
+ /** Whose account backs it. */
253
+ operatorId: string;
254
+ /** Agent-wide or restricted to one exact session. */
255
+ scope: "agent" | `session:${string}`;
256
+ /** Whether observers may use this capability. */
257
+ audience: "owner-only" | "shared";
258
+ /** Current lifecycle state. */
259
+ status: GrantStatus;
260
+ /** Creation time in Unix milliseconds. */
261
+ createdAt: number;
262
+ /** Authority that requested the introduction. */
263
+ createdBy: "operator" | "agent-request";
264
+ /** Optional expiry in Unix milliseconds. */
265
+ expiresAt?: number;
266
+ /** Short operator-chosen title shown in the grant table. */
267
+ title?: string;
268
+ }
269
+ /** A queued action awaiting a human decision. */
270
+ interface PendingAction {
271
+ /** Kernel queue record identifier. */
272
+ id: number;
273
+ /** Stable identifier for the resource instance. */
274
+ gatekeeperInstance: string;
275
+ /** Monotonic per-instance action identifier. */
276
+ actionId: number;
277
+ /** Serialized ActionDescription, validated before storage. */
278
+ descriptionJson: string;
279
+ /** Current lifecycle state. */
280
+ status: "pending" | "applied" | "rejected" | "reverted" | "failed";
281
+ /** Submission time in Unix milliseconds. */
282
+ submittedAt: number;
283
+ /** Trusted operator identity that decided this action. */
284
+ decidedBy?: string;
285
+ /** Decision time in Unix milliseconds. */
286
+ decidedAt?: number;
287
+ /** Application time in Unix milliseconds. */
288
+ appliedAt?: number;
289
+ /** Sanitized error code or fixed message only. */
290
+ error?: string;
291
+ }
292
+ /** Audit record shape (plan §4.8). One JSON object per line in os/audit/YYYY-MM-DD.jsonl. */
293
+ interface AuditRecord {
294
+ /** UTC audit timestamp. */
295
+ ts: string;
296
+ /** Cell trust boundary. */
297
+ cell: string;
298
+ /** Agent that owns the capability. */
299
+ agentId?: string;
300
+ /** Trusted session correlation key. */
301
+ sessionKey?: string;
302
+ /** Allowlisted audit event category. */
303
+ kind: "observation" | "action.submit" | "action.decide" | "action.apply" | "action.revert" | "grant" | "auth" | "tool" | "install" | "egress";
304
+ /** Stable gatekeeper vendor namespace. */
305
+ vendor?: string;
306
+ /** Resource type within its vendor. */
307
+ resourceType?: string;
308
+ /** Opaque capability handle. */
309
+ handle?: string;
310
+ /** Monotonic per-instance action identifier. */
311
+ actionId?: number;
312
+ /** Safe audit label, never raw vendor content. */
313
+ title: string;
314
+ /** Decision category, not raw vendor content. */
315
+ decision?: string;
316
+ /** Trusted authority responsible for this event. */
317
+ by?: string;
318
+ /** Elapsed time in milliseconds. */
319
+ durationMs?: number;
320
+ /** Whether the operation succeeded. */
321
+ ok?: boolean;
322
+ }
323
+ /** Canonical lowercase Crockford base32 handle; excludes ambiguous i/l/o/u. */
324
+ declare const GRANT_HANDLE_RE: RegExp;
325
+
326
+ /** JSON wire contracts. Runtime queues, sessions, accounts and vendors are never serialized. */
327
+
328
+ /** JSON-only extension payloads: functions and other runtime values are not wire data. */
329
+ declare const JsonValueSchema: Type.TCyclic<{
330
+ Value: Type.TUnion<[Type.TNull, Type.TBoolean, Type.TNumber, Type.TString, Type.TArray<Type.TRef<"Value">>, Type.TRecord<"^.*$", Type.TRef<"Value">>]>;
331
+ }, "Value">;
332
+ /** Canonical opaque capability handle; never a vendor resource identifier. */
333
+ declare const GrantHandle: Type.TString;
334
+ /** Provider-portable OS tool name, bounded to 64 ASCII characters. */
335
+ declare const ToolNameSchema: Type.TString;
336
+ /** Resource discovery metadata, not proof of a loaded driver or an active grant. */
337
+ declare const SupportedResourceSchema: Type.TObject<{
338
+ urlPattern: Type.TString;
339
+ type: Type.TString;
340
+ title: Type.TString;
341
+ description: Type.TString;
342
+ grantable: Type.TBoolean;
343
+ observerStrategy: Type.TEnum<["private-only", "acl-check", "dataset-tracking", "low-stakes"]>;
344
+ tools: Type.TArray<Type.TString>;
345
+ }>;
346
+ /** Description passed to the kernel before observation data is returned. */
347
+ declare const ObservationDescriptionSchema: Type.TObject<{
348
+ title: Type.TString;
349
+ description: Type.TString;
350
+ prohibitAllSharing: Type.TOptional<Type.TBoolean>;
351
+ excludeObservers: Type.TOptional<Type.TArray<Type.TString>>;
352
+ }>;
353
+ /** Stable action-policy key and human-readable label. */
354
+ declare const ActionKindSchema: Type.TObject<{
355
+ tag: Type.TString;
356
+ label: Type.TString;
357
+ }>;
358
+ /** Deferred action metadata; never raw credentials or vendor request bodies. */
359
+ declare const ActionDescriptionSchema: Type.TObject<{
360
+ title: Type.TString;
361
+ description: Type.TString;
362
+ actionKind: Type.TOptional<Type.TObject<{
363
+ tag: Type.TString;
364
+ label: Type.TString;
365
+ }>>;
366
+ autoApprovable: Type.TOptional<Type.TBoolean>;
367
+ implementsRevert: Type.TBoolean;
368
+ awaitDecision: Type.TOptional<Type.TBoolean>;
369
+ preview: Type.TOptional<Type.TCyclic<{
370
+ Value: Type.TUnion<[Type.TNull, Type.TBoolean, Type.TNumber, Type.TString, Type.TArray<Type.TRef<"Value">>, Type.TRecord<"^.*$", Type.TRef<"Value">>]>;
371
+ }, "Value">>;
372
+ }>;
373
+ /** Discriminated dry-pass response; cannot contain a live session or execute function. */
374
+ declare const DryRunResultSchema: Type.TUnion<[Type.TObject<{
375
+ kind: Type.TLiteral<"observation">;
376
+ description: Type.TObject<{
377
+ title: Type.TString;
378
+ description: Type.TString;
379
+ prohibitAllSharing: Type.TOptional<Type.TBoolean>;
380
+ excludeObservers: Type.TOptional<Type.TArray<Type.TString>>;
381
+ }>;
382
+ }>, Type.TObject<{
383
+ kind: Type.TLiteral<"action">;
384
+ description: Type.TObject<{
385
+ title: Type.TString;
386
+ description: Type.TString;
387
+ actionKind: Type.TOptional<Type.TObject<{
388
+ tag: Type.TString;
389
+ label: Type.TString;
390
+ }>>;
391
+ autoApprovable: Type.TOptional<Type.TBoolean>;
392
+ implementsRevert: Type.TBoolean;
393
+ awaitDecision: Type.TOptional<Type.TBoolean>;
394
+ preview: Type.TOptional<Type.TCyclic<{
395
+ Value: Type.TUnion<[Type.TNull, Type.TBoolean, Type.TNumber, Type.TString, Type.TArray<Type.TRef<"Value">>, Type.TRecord<"^.*$", Type.TRef<"Value">>]>;
396
+ }, "Value">>;
397
+ }>;
398
+ }>]>;
399
+ /** Agent-visible result blocks and optional JSON details. */
400
+ declare const ToolResultSchema: Type.TObject<{
401
+ content: Type.TArray<Type.TObject<{
402
+ type: Type.TLiteral<"text">;
403
+ text: Type.TString;
404
+ }>>;
405
+ details: Type.TOptional<Type.TCyclic<{
406
+ Value: Type.TUnion<[Type.TNull, Type.TBoolean, Type.TNumber, Type.TString, Type.TArray<Type.TRef<"Value">>, Type.TRecord<"^.*$", Type.TRef<"Value">>]>;
407
+ }, "Value">>;
408
+ }>;
409
+ /** Private account-to-account verifier; must not be exposed in agent catalogs. */
410
+ declare const ObserverVerifierSchema: Type.TObject<{
411
+ vendor: Type.TString;
412
+ opaque: Type.TString;
413
+ }>;
414
+ /** Cached tool metadata. The kit also checks resource mappings and required string grant parameters. */
415
+ declare const GatekeeperToolDefSchema: Type.TObject<{
416
+ name: Type.TString;
417
+ resourceType: Type.TString;
418
+ kind: Type.TEnum<["observation", "action"]>;
419
+ description: Type.TString;
420
+ parameters: Type.TRecord<"^.*$", Type.TCyclic<{
421
+ Value: Type.TUnion<[Type.TNull, Type.TBoolean, Type.TNumber, Type.TString, Type.TArray<Type.TRef<"Value">>, Type.TRecord<"^.*$", Type.TRef<"Value">>]>;
422
+ }, "Value">>;
423
+ outputSchema: Type.TOptional<Type.TRecord<"^.*$", Type.TCyclic<{
424
+ Value: Type.TUnion<[Type.TNull, Type.TBoolean, Type.TNumber, Type.TString, Type.TArray<Type.TRef<"Value">>, Type.TRecord<"^.*$", Type.TRef<"Value">>]>;
425
+ }, "Value">>>;
426
+ }>;
427
+ /** Credential-free account summary returned by account.describe(). */
428
+ declare const AccountDescriptionSchema: Type.TObject<{
429
+ email: Type.TOptional<Type.TString>;
430
+ displayName: Type.TOptional<Type.TString>;
431
+ expiresAt: Type.TOptional<Type.TInteger>;
432
+ }>;
433
+ /** Credential-free vendor summary returned by vendor.describe(). */
434
+ declare const VendorDescriptionSchema: Type.TObject<{
435
+ title: Type.TString;
436
+ description: Type.TString;
437
+ icon: Type.TOptional<Type.TString>;
438
+ autoProvisionsAccount: Type.TOptional<Type.TBoolean>;
439
+ }>;
440
+ /** Credential-free per-resource summary returned by gatekeeper.describe(). */
441
+ declare const GatekeeperDescriptionSchema: Type.TObject<{
442
+ resource: Type.TObject<{
443
+ urlPattern: Type.TString;
444
+ type: Type.TString;
445
+ title: Type.TString;
446
+ description: Type.TString;
447
+ grantable: Type.TBoolean;
448
+ observerStrategy: Type.TEnum<["private-only", "acl-check", "dataset-tracking", "low-stakes"]>;
449
+ tools: Type.TArray<Type.TString>;
450
+ }>;
451
+ title: Type.TString;
452
+ suggestedName: Type.TString;
453
+ }>;
454
+ /** Authorization redirect sent only to an operator, never an audit record. */
455
+ declare const ConnectionResultSchema: Type.TObject<{
456
+ url: Type.TString;
457
+ }>;
458
+ /** Optional effect of rejecting an action. A void runtime result is normalized to an empty object. */
459
+ declare const RejectActionResultSchema: Type.TObject<{
460
+ restart: Type.TOptional<Type.TBoolean>;
461
+ }>;
462
+ /** Optional effect of reverting an action; messages must already be sanitized. */
463
+ declare const RevertActionResultSchema: Type.TObject<{
464
+ message: Type.TOptional<Type.TString>;
465
+ canRetry: Type.TOptional<Type.TBoolean>;
466
+ }>;
467
+ /** Persisted capability record; it is not the redacted agent catalog entry. */
468
+ declare const GrantSchema: Type.TObject<{
469
+ handle: Type.TString;
470
+ agentId: Type.TString;
471
+ cellId: Type.TString;
472
+ vendor: Type.TString;
473
+ resourceType: Type.TString;
474
+ resourceKey: Type.TString;
475
+ operatorId: Type.TString;
476
+ scope: Type.TUnion<[Type.TLiteral<"agent">, Type.TTemplateLiteral<"^session:.*$">]>;
477
+ audience: Type.TEnum<["owner-only", "shared"]>;
478
+ status: Type.TEnum<["pending", "active", "revoked", "lockdown"]>;
479
+ createdAt: Type.TInteger;
480
+ createdBy: Type.TEnum<["operator", "agent-request"]>;
481
+ expiresAt: Type.TOptional<Type.TInteger>;
482
+ title: Type.TOptional<Type.TString>;
483
+ }>;
484
+ /** Kernel action queue row. Parse descriptionJson separately with ActionDescriptionSchema. */
485
+ declare const PendingActionSchema: Type.TObject<{
486
+ id: Type.TInteger;
487
+ gatekeeperInstance: Type.TString;
488
+ actionId: Type.TInteger;
489
+ descriptionJson: Type.TString;
490
+ status: Type.TEnum<["pending", "applied", "rejected", "reverted", "failed"]>;
491
+ submittedAt: Type.TInteger;
492
+ decidedBy: Type.TOptional<Type.TString>;
493
+ decidedAt: Type.TOptional<Type.TInteger>;
494
+ appliedAt: Type.TOptional<Type.TInteger>;
495
+ error: Type.TOptional<Type.TString>;
496
+ }>;
497
+ /** Allowlisted audit record shape; unknown fields (including headers and bodies) are rejected. */
498
+ declare const AuditRecordSchema: Type.TObject<{
499
+ ts: Type.TString;
500
+ cell: Type.TString;
501
+ agentId: Type.TOptional<Type.TString>;
502
+ sessionKey: Type.TOptional<Type.TString>;
503
+ kind: Type.TEnum<["observation", "action.submit", "action.decide", "action.apply", "action.revert", "grant", "auth", "tool", "install", "egress"]>;
504
+ vendor: Type.TOptional<Type.TString>;
505
+ resourceType: Type.TOptional<Type.TString>;
506
+ handle: Type.TOptional<Type.TString>;
507
+ actionId: Type.TOptional<Type.TInteger>;
508
+ title: Type.TString;
509
+ decision: Type.TOptional<Type.TString>;
510
+ by: Type.TOptional<Type.TString>;
511
+ durationMs: Type.TOptional<Type.TNumber>;
512
+ ok: Type.TOptional<Type.TBoolean>;
513
+ }>;
514
+ /** Kernel health/status response. */
515
+ declare const OsStatus: Type.TObject<{
516
+ cell: Type.TString;
517
+ upstreamVersion: Type.TString;
518
+ kernelVersion: Type.TString;
519
+ healthy: Type.TBoolean;
520
+ maintenance: Type.TBoolean;
521
+ gatekeepers: Type.TArray<Type.TObject<{
522
+ vendor: Type.TString;
523
+ healthy: Type.TBoolean;
524
+ accounts: Type.TInteger;
525
+ }>>;
526
+ pendingApprovals: Type.TInteger;
527
+ pendingRequests: Type.TInteger;
528
+ lastUpdate: Type.TOptional<Type.TObject<{
529
+ to: Type.TString;
530
+ ok: Type.TBoolean;
531
+ at: Type.TString;
532
+ }>>;
533
+ }>;
534
+ /** TypeScript view of the kernel status wire response. */
535
+ type OsStatus = Static<typeof OsStatus>;
536
+ /** Operator introduction request. Identity comes from authenticated RPC context, never this payload. */
537
+ declare const IntroduceParams: Type.TObject<{
538
+ agentId: Type.TString;
539
+ url: Type.TString;
540
+ title: Type.TOptional<Type.TString>;
541
+ audience: Type.TOptional<Type.TEnum<["owner-only", "shared"]>>;
542
+ }>;
543
+ /** Operator decision request. IDs are positive safe integers and cannot repeat. */
544
+ declare const ApprovalDecisionParams: Type.TObject<{
545
+ ids: Type.TUnion<[Type.TArray<Type.TInteger>, Type.TLiteral<"all">]>;
546
+ }>;
547
+ /** Exact capability revocation request. */
548
+ declare const RevokeGrantParams: Type.TObject<{
549
+ handle: Type.TString;
550
+ }>;
551
+ /** Agent access request; does not grant authority by itself. */
552
+ declare const RequestAccessParams: Type.TObject<{
553
+ url: Type.TString;
554
+ reason: Type.TString;
555
+ }>;
556
+ /** Optional filter for operator grant listing. */
557
+ declare const ListGrantsParams: Type.TObject<{
558
+ agentId: Type.TOptional<Type.TString>;
559
+ }>;
560
+ /** Account connection request. Operator identity is supplied by authenticated RPC context. */
561
+ declare const ConnectGatekeeperParams: Type.TObject<{
562
+ vendor: Type.TString;
563
+ resourceTypes: Type.TOptional<Type.TArray<Type.TString>>;
564
+ }>;
565
+
566
+ /** Operator-owned rules. Hash rules authorize regular staged files only, never an unmeasured directory. */
567
+ interface InstallRules {
568
+ allowSources?: string[];
569
+ allowHashes?: string[];
570
+ }
571
+ /** Common documented fields supplied by both upstream install boundaries. */
572
+ interface InstallMaterial {
573
+ targetType: string;
574
+ sourcePath: string;
575
+ sourcePathKind: string;
576
+ request: {
577
+ kind: string;
578
+ mode: string;
579
+ requestedSpecifier?: string;
580
+ };
581
+ }
582
+ /** Minimal versioned upstream policy response; reasons never contain source material. */
583
+ interface InstallVerdict {
584
+ protocolVersion: 1;
585
+ decision: "allow" | "block";
586
+ reason?: string;
587
+ }
588
+ /** Match an entire requested specifier, with only `*` as a wildcard. No origin/name/hash labels are authority. */
589
+ declare function evaluateInstall(rules: InstallRules | undefined, material: InstallMaterial): InstallVerdict;
590
+
591
+ export { AccountDescriptionSchema, type ActionDescription, ActionDescriptionSchema, type ActionKind, ActionKindSchema, ApprovalDecisionParams, type ApprovalQueue, type AuditRecord, AuditRecordSchema, ConnectGatekeeperParams, ConnectionResultSchema, type DryRunResult, DryRunResultSchema, GRANT_HANDLE_RE, type Gatekeeper, type GatekeeperAccount, GatekeeperDescriptionSchema, type GatekeeperSession, type GatekeeperToolDef, GatekeeperToolDefSchema, type GatekeeperVendor, type Grant, GrantHandle, GrantSchema, type GrantStatus, type InstallMaterial, type InstallRules, type InstallVerdict, IntroduceParams, JsonValueSchema, ListGrantsParams, type ObservationDescription, ObservationDescriptionSchema, type ObserverVerifier, ObserverVerifierSchema, OsStatus, type PendingAction, PendingActionSchema, RejectActionResultSchema, RequestAccessParams, RevertActionResultSchema, RevokeGrantParams, type SessionCallContext, type SupportedResource, SupportedResourceSchema, ToolNameSchema, type ToolResult, ToolResultSchema, VendorDescriptionSchema, evaluateInstall };
package/dist/index.js ADDED
@@ -0,0 +1,218 @@
1
+ // src/grant.ts
2
+ var GRANT_HANDLE_RE = /^grant:[0-9a-hjkmnp-tv-z]{8}$/;
3
+
4
+ // src/schemas.ts
5
+ import { Type } from "typebox";
6
+ var closed = { additionalProperties: false };
7
+ var text = Type.String({ minLength: 1 });
8
+ var namespace = Type.String({ pattern: "^[a-z][a-z0-9_]*$" });
9
+ var timestamp = Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER });
10
+ var actionId = Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER });
11
+ var JsonValueSchema = Type.Cyclic({ Value: Type.Union([
12
+ Type.Null(),
13
+ Type.Boolean(),
14
+ Type.Number(),
15
+ Type.String(),
16
+ Type.Array(Type.Ref("Value")),
17
+ Type.Record(Type.String(), Type.Ref("Value"))
18
+ ]) }, "Value");
19
+ var GrantHandle = Type.String({ pattern: GRANT_HANDLE_RE.source });
20
+ var ToolNameSchema = Type.String({ pattern: "^gk_[a-z0-9]+(?:_[a-z0-9]+){2,}$", maxLength: 64 });
21
+ var SupportedResourceSchema = Type.Object({
22
+ urlPattern: text,
23
+ type: namespace,
24
+ title: text,
25
+ description: Type.String(),
26
+ grantable: Type.Boolean(),
27
+ observerStrategy: Type.Enum(["private-only", "acl-check", "dataset-tracking", "low-stakes"]),
28
+ tools: Type.Array(ToolNameSchema, { uniqueItems: true })
29
+ }, closed);
30
+ var ObservationDescriptionSchema = Type.Object({
31
+ title: text,
32
+ description: Type.String(),
33
+ prohibitAllSharing: Type.Optional(Type.Boolean()),
34
+ excludeObservers: Type.Optional(Type.Array(text, { uniqueItems: true }))
35
+ }, closed);
36
+ var ActionKindSchema = Type.Object({ tag: text, label: text }, closed);
37
+ var ActionDescriptionSchema = Type.Object({
38
+ title: text,
39
+ description: Type.String(),
40
+ actionKind: Type.Optional(ActionKindSchema),
41
+ autoApprovable: Type.Optional(Type.Boolean()),
42
+ implementsRevert: Type.Boolean(),
43
+ awaitDecision: Type.Optional(Type.Boolean()),
44
+ preview: Type.Optional(JsonValueSchema)
45
+ }, closed);
46
+ var DryRunResultSchema = Type.Union([
47
+ Type.Object({ kind: Type.Literal("observation"), description: ObservationDescriptionSchema }, closed),
48
+ Type.Object({ kind: Type.Literal("action"), description: ActionDescriptionSchema }, closed)
49
+ ]);
50
+ var ToolResultSchema = Type.Object({
51
+ content: Type.Array(Type.Object({ type: Type.Literal("text"), text: Type.String() }, closed)),
52
+ details: Type.Optional(JsonValueSchema)
53
+ }, closed);
54
+ var ObserverVerifierSchema = Type.Object({ vendor: namespace, opaque: text }, closed);
55
+ var GatekeeperToolDefSchema = Type.Object({
56
+ name: ToolNameSchema,
57
+ resourceType: namespace,
58
+ kind: Type.Enum(["observation", "action"]),
59
+ description: text,
60
+ parameters: Type.Record(Type.String(), JsonValueSchema),
61
+ outputSchema: Type.Optional(Type.Record(Type.String(), JsonValueSchema))
62
+ }, closed);
63
+ var AccountDescriptionSchema = Type.Object({
64
+ email: Type.Optional(text),
65
+ displayName: Type.Optional(text),
66
+ expiresAt: Type.Optional(timestamp)
67
+ }, closed);
68
+ var VendorDescriptionSchema = Type.Object({
69
+ title: text,
70
+ description: Type.String(),
71
+ icon: Type.Optional(text),
72
+ autoProvisionsAccount: Type.Optional(Type.Boolean())
73
+ }, closed);
74
+ var GatekeeperDescriptionSchema = Type.Object({ resource: SupportedResourceSchema, title: text, suggestedName: text }, closed);
75
+ var ConnectionResultSchema = Type.Object({ url: text }, closed);
76
+ var RejectActionResultSchema = Type.Object({ restart: Type.Optional(Type.Boolean()) }, closed);
77
+ var RevertActionResultSchema = Type.Object({ message: Type.Optional(Type.String()), canRetry: Type.Optional(Type.Boolean()) }, closed);
78
+ var GrantSchema = Type.Object({
79
+ handle: GrantHandle,
80
+ agentId: text,
81
+ cellId: text,
82
+ vendor: namespace,
83
+ resourceType: namespace,
84
+ resourceKey: text,
85
+ operatorId: text,
86
+ scope: Type.Union([Type.Literal("agent"), Type.TemplateLiteral([Type.Literal("session:"), Type.String()], { pattern: "^session:.+$" })]),
87
+ audience: Type.Enum(["owner-only", "shared"]),
88
+ status: Type.Enum(["pending", "active", "revoked", "lockdown"]),
89
+ createdAt: timestamp,
90
+ createdBy: Type.Enum(["operator", "agent-request"]),
91
+ expiresAt: Type.Optional(timestamp),
92
+ title: Type.Optional(Type.String())
93
+ }, closed);
94
+ var PendingActionSchema = Type.Object({
95
+ id: actionId,
96
+ gatekeeperInstance: text,
97
+ actionId,
98
+ descriptionJson: text,
99
+ status: Type.Enum(["pending", "applied", "rejected", "reverted", "failed"]),
100
+ submittedAt: timestamp,
101
+ decidedBy: Type.Optional(text),
102
+ decidedAt: Type.Optional(timestamp),
103
+ appliedAt: Type.Optional(timestamp),
104
+ error: Type.Optional(Type.String())
105
+ }, closed);
106
+ var AuditRecordSchema = Type.Object({
107
+ ts: Type.String({ pattern: "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{3})?Z$" }),
108
+ cell: text,
109
+ agentId: Type.Optional(text),
110
+ sessionKey: Type.Optional(text),
111
+ kind: Type.Enum(["observation", "action.submit", "action.decide", "action.apply", "action.revert", "grant", "auth", "tool", "install", "egress"]),
112
+ vendor: Type.Optional(namespace),
113
+ resourceType: Type.Optional(namespace),
114
+ handle: Type.Optional(GrantHandle),
115
+ actionId: Type.Optional(actionId),
116
+ title: Type.String(),
117
+ decision: Type.Optional(text),
118
+ by: Type.Optional(text),
119
+ durationMs: Type.Optional(Type.Number({ minimum: 0 })),
120
+ ok: Type.Optional(Type.Boolean())
121
+ }, closed);
122
+ var OsStatus = Type.Object({
123
+ cell: text,
124
+ upstreamVersion: text,
125
+ kernelVersion: text,
126
+ healthy: Type.Boolean(),
127
+ maintenance: Type.Boolean(),
128
+ gatekeepers: Type.Array(Type.Object({ vendor: namespace, healthy: Type.Boolean(), accounts: timestamp }, closed)),
129
+ pendingApprovals: timestamp,
130
+ pendingRequests: timestamp,
131
+ lastUpdate: Type.Optional(Type.Object({ to: text, ok: Type.Boolean(), at: text }, closed))
132
+ }, closed);
133
+ var IntroduceParams = Type.Object({
134
+ agentId: text,
135
+ url: text,
136
+ title: Type.Optional(Type.String()),
137
+ audience: Type.Optional(Type.Enum(["owner-only", "shared"]))
138
+ }, closed);
139
+ var ApprovalDecisionParams = Type.Object({ ids: Type.Union([
140
+ Type.Array(actionId, { minItems: 1, uniqueItems: true }),
141
+ Type.Literal("all")
142
+ ]) }, closed);
143
+ var RevokeGrantParams = Type.Object({ handle: GrantHandle }, closed);
144
+ var RequestAccessParams = Type.Object({ url: text, reason: text }, closed);
145
+ var ListGrantsParams = Type.Object({ agentId: Type.Optional(text) }, closed);
146
+ var ConnectGatekeeperParams = Type.Object({ vendor: namespace, resourceTypes: Type.Optional(Type.Array(namespace, { uniqueItems: true })) }, closed);
147
+
148
+ // src/install-policy.ts
149
+ import { createHash } from "crypto";
150
+ import { constants, closeSync, fstatSync, openSync, readSync } from "fs";
151
+ var blocked = () => ({ protocolVersion: 1, decision: "block", reason: "Install material is not authorized by cell policy." });
152
+ function evaluateInstall(rules, material) {
153
+ try {
154
+ if (!rules || !["plugin", "skill"].includes(material.targetType) || !["install", "update"].includes(material.request.mode) || typeof material.request.kind !== "string" || typeof material.sourcePath !== "string" || !material.sourcePath.startsWith("/") || !["file", "directory"].includes(material.sourcePathKind)) return blocked();
155
+ for (const entries of [rules.allowSources, rules.allowHashes]) if (entries !== void 0 && (!Array.isArray(entries) || entries.some((s) => typeof s !== "string" || s.length === 0 || s.length > 4096))) return blocked();
156
+ const specifier = material.request.requestedSpecifier;
157
+ if (typeof specifier === "string" && registrySpecifierSafe(specifier) && specifier.length > 0 && specifier.length <= 4096 && !/[\x00-\x20\x7f]/u.test(specifier) && rules.allowSources?.some((pattern) => new RegExp(`^${pattern.split("*").map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`, "u").test(specifier))) return { protocolVersion: 1, decision: "allow" };
158
+ if (material.sourcePathKind === "file" && rules.allowHashes?.length) {
159
+ const fd = openSync(material.sourcePath, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
160
+ try {
161
+ const before = fstatSync(fd);
162
+ if (!before.isFile() || before.size > 16 * 1024 * 1024) return blocked();
163
+ const bytes = Buffer.alloc(before.size + 1);
164
+ let length = 0;
165
+ while (length < bytes.length) {
166
+ const n = readSync(fd, bytes, length, bytes.length - length, null);
167
+ if (n === 0) break;
168
+ length += n;
169
+ }
170
+ if (length !== before.size) return blocked();
171
+ const hash = `sha256:${createHash("sha256").update(bytes.subarray(0, length)).digest("hex")}`;
172
+ const after = fstatSync(fd);
173
+ if (before.size === after.size && before.mtimeMs === after.mtimeMs && before.ctimeMs === after.ctimeMs && rules.allowHashes.includes(hash)) return { protocolVersion: 1, decision: "allow" };
174
+ } finally {
175
+ closeSync(fd);
176
+ }
177
+ }
178
+ } catch {
179
+ }
180
+ return blocked();
181
+ }
182
+ function registrySpecifierSafe(specifier) {
183
+ const prefixed = /^(?:npm|clawhub):/.test(specifier);
184
+ const value = prefixed ? specifier.slice(specifier.indexOf(":") + 1) : specifier;
185
+ if (!prefixed && !value.startsWith("@") && !/^[a-z0-9][a-z0-9._-]*(?:@|$)/.test(value)) return true;
186
+ return /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*(?:@[A-Za-z0-9._+~^<>=|*-]+)?$/.test(value);
187
+ }
188
+ export {
189
+ AccountDescriptionSchema,
190
+ ActionDescriptionSchema,
191
+ ActionKindSchema,
192
+ ApprovalDecisionParams,
193
+ AuditRecordSchema,
194
+ ConnectGatekeeperParams,
195
+ ConnectionResultSchema,
196
+ DryRunResultSchema,
197
+ GRANT_HANDLE_RE,
198
+ GatekeeperDescriptionSchema,
199
+ GatekeeperToolDefSchema,
200
+ GrantHandle,
201
+ GrantSchema,
202
+ IntroduceParams,
203
+ JsonValueSchema,
204
+ ListGrantsParams,
205
+ ObservationDescriptionSchema,
206
+ ObserverVerifierSchema,
207
+ OsStatus,
208
+ PendingActionSchema,
209
+ RejectActionResultSchema,
210
+ RequestAccessParams,
211
+ RevertActionResultSchema,
212
+ RevokeGrantParams,
213
+ SupportedResourceSchema,
214
+ ToolNameSchema,
215
+ ToolResultSchema,
216
+ VendorDescriptionSchema,
217
+ evaluateInstall
218
+ };
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@clawkeepers/shared",
3
+ "version": "0.1.0-beta.1",
4
+ "description": "Contracts for OpenClaw OS: gatekeeper interfaces, approval queue, grants.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "files": [
9
+ "dist",
10
+ "LICENSE",
11
+ "NOTICE",
12
+ "README.md"
13
+ ],
14
+ "dependencies": {
15
+ "typebox": "1.1.39"
16
+ },
17
+ "devDependencies": {
18
+ "tsup": "8.5.0",
19
+ "typescript": "5.9.2",
20
+ "vitest": "3.2.4",
21
+ "@types/node": "22.18.0"
22
+ },
23
+ "license": "MIT",
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/clawkeeper/openclaw-os.git",
27
+ "directory": "packages/clawos-shared"
28
+ },
29
+ "private": false,
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "exports": {
34
+ ".": {
35
+ "types": "./dist/index.d.ts",
36
+ "import": "./dist/index.js"
37
+ }
38
+ },
39
+ "engines": {
40
+ "node": ">=22.22.3"
41
+ },
42
+ "scripts": {
43
+ "build": "tsup src/index.ts --format esm --dts --clean",
44
+ "test": "vitest run",
45
+ "typecheck": "tsc -p tsconfig.json --noEmit"
46
+ }
47
+ }