@brud/sdk 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Akkhar-Labs
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,71 @@
1
- # Temporary Holding Version
1
+ # @brud/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The BrudOS SDK: the friendly way to write and test participants for the BrudOS kernel.
4
+
5
+ ## What is BrudOS?
6
+
7
+ BrudOS is a small kernel you embed in a program to build software out of independent pieces, called **participants**, that do not have to trust each other. The kernel gives every participant an identity, lets each participant decide who may call its APIs, and enforces that on every call.
8
+
9
+ The kernel has no abilities of its own: it does not read files, use the network or run commands. That makes it a good base for plugin systems and AI-agent runtimes, where you need to know exactly who was allowed to do what.
10
+
11
+ > **Status: beta (0.0.x).** The core works and is tested, but APIs may still change before 1.0.
12
+
13
+ ## Which package do I need?
14
+
15
+ BrudOS is published as four packages. Install only what you need.
16
+
17
+ | Package | Use it to | Install |
18
+ |---|---|---|
19
+ | [`@brud/kernel`](https://www.npmjs.com/package/@brud/kernel) | The engine. Embed it in your program to run participants. | `npm install @brud/kernel` |
20
+ | **`@brud/sdk`** (this package) | Write and test participants (plugins, services, agent tools). | `npm install @brud/sdk @brud/kernel` |
21
+ | [`@brud/daemon`](https://www.npmjs.com/package/@brud/daemon) | Run kernels as a local background process that editors, agents and scripts connect to. | `npm install @brud/daemon` |
22
+ | [`@brud/protocol`](https://www.npmjs.com/package/@brud/protocol) | The message types the daemon and its clients share. Installed with the daemon; you only need it directly to write your own client. | `npm install @brud/protocol` |
23
+
24
+ New to BrudOS? Start with the [introduction](https://github.com/rahatarch/brud/tree/main/docs-next/01-introduction/what-is-brudos.md) and the [getting-started guide](https://github.com/rahatarch/brud/tree/main/docs-next/02-getting-started).
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ npm install @brud/sdk @brud/kernel
30
+ ```
31
+
32
+ Requires Node.js 22 or newer. `@brud/kernel` is a peer dependency, so install both.
33
+
34
+ ## What you get
35
+
36
+ | Import | Use it for |
37
+ |---|---|
38
+ | `@brud/sdk/participant` | `defineParticipant` to describe a participant, and `byCapability` to give different callers different views of an API |
39
+ | `@brud/sdk/testing` | `bootTestKernel`, to run your participant on a real kernel inside a test |
40
+ | `@brud/sdk` | Small helpers for validating plain JSON |
41
+
42
+ ## Example
43
+
44
+ A participant that offers one API, `acme.greet`:
45
+
46
+ ```js
47
+ import { defineParticipant } from '@brud/sdk/participant';
48
+
49
+ export const createService = defineParticipant({
50
+ id: 'acme.greeter',
51
+ description: 'Says hello',
52
+ create: () => ({ greet: (name) => `hello, ${name}` }),
53
+ exposes: {
54
+ 'acme.greet': {
55
+ version: 1,
56
+ scope: 'any',
57
+ handle: (caller, ctx) => ({ greet: (name) => ctx.instance.greet(name) }),
58
+ },
59
+ },
60
+ });
61
+ ```
62
+
63
+ The participant that offers an API decides who may use it. Here `scope: 'any'` lets any participant call `acme.greet`, and `byCapability` lets you hand different callers different handles. To run it, list the file in a `brud.config.json` and boot it with `@brud/kernel`. The [tutorial](https://github.com/rahatarch/brud/tree/main/docs-next/02-getting-started/your-first-participant.md) walks through it end to end.
64
+
65
+ ## Documentation
66
+
67
+ [Getting started](https://github.com/rahatarch/brud/tree/main/docs-next/02-getting-started) · [Concepts](https://github.com/rahatarch/brud/tree/main/docs-next/03-concepts) · [Report an issue](https://github.com/rahatarch/brud/issues)
68
+
69
+ ## License
70
+
71
+ [Apache-2.0](LICENSE)
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The kernel contract this SDK targets. The kernel does not yet export a
3
+ * contract version (plan decision S-4); until it does, the SDK records the
4
+ * kernel line it is built and tested against.
5
+ */
6
+ export declare const SDK_VERSION = "0.0.2";
7
+ /** Kernel package line (`major.minor`) this SDK is built and tested against. */
8
+ export declare const SDK_TARGET_KERNEL = "0.0";
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The kernel contract this SDK targets. The kernel does not yet export a
3
+ * contract version (plan decision S-4); until it does, the SDK records the
4
+ * kernel line it is built and tested against.
5
+ */
6
+ export const SDK_VERSION = '0.0.2';
7
+ /** Kernel package line (`major.minor`) this SDK is built and tested against. */
8
+ export const SDK_TARGET_KERNEL = '0.0';
@@ -0,0 +1,7 @@
1
+ /** Stable codes of errors the SDK raises itself (kernel errors pass through unchanged). */
2
+ export type SdkErrorCode = 'SDK_DEFINITION_INVALID' | 'SDK_INSTANCE_NOT_READY' | 'SDK_NOT_PLAIN';
3
+ /** An error raised by the SDK, with a stable `code`. */
4
+ export declare class SdkError extends Error {
5
+ readonly code: SdkErrorCode;
6
+ constructor(code: SdkErrorCode, message: string);
7
+ }
@@ -0,0 +1,9 @@
1
+ /** An error raised by the SDK, with a stable `code`. */
2
+ export class SdkError extends Error {
3
+ code;
4
+ constructor(code, message) {
5
+ super(message);
6
+ this.name = 'SdkError';
7
+ this.code = code;
8
+ }
9
+ }
@@ -0,0 +1,16 @@
1
+ /** Whether `name` is a valid participant, exposure or event name (`acme.notes`, `brud.settings.reader`). */
2
+ export declare function isValidName(name: string): boolean;
3
+ /** The binding key of an exposure: `name@major`. */
4
+ export declare function exposureKey(name: string, major: number): string;
5
+ /**
6
+ * Validates a name.
7
+ *
8
+ * @throws {SdkError} `SDK_DEFINITION_INVALID` when it is not valid.
9
+ */
10
+ export declare function assertName(name: unknown, what: string): string;
11
+ /**
12
+ * Validates a major version (a positive integer; default 1).
13
+ *
14
+ * @throws {SdkError} `SDK_DEFINITION_INVALID` when it is not.
15
+ */
16
+ export declare function assertMajor(version: unknown, what: string): number;
@@ -0,0 +1,33 @@
1
+ import { SdkError } from './errors.js';
2
+ const NAME = /^[a-z][a-z0-9-]*(\.[a-z0-9][a-z0-9-]*)+$/u;
3
+ /** Whether `name` is a valid participant, exposure or event name (`acme.notes`, `brud.settings.reader`). */
4
+ export function isValidName(name) {
5
+ return NAME.test(name);
6
+ }
7
+ /** The binding key of an exposure: `name@major`. */
8
+ export function exposureKey(name, major) {
9
+ return `${name}@${String(major)}`;
10
+ }
11
+ /**
12
+ * Validates a name.
13
+ *
14
+ * @throws {SdkError} `SDK_DEFINITION_INVALID` when it is not valid.
15
+ */
16
+ export function assertName(name, what) {
17
+ if (typeof name !== 'string' || !isValidName(name)) {
18
+ throw new SdkError('SDK_DEFINITION_INVALID', `${what} "${String(name)}" is not a valid dotted lower-case name`);
19
+ }
20
+ return name;
21
+ }
22
+ /**
23
+ * Validates a major version (a positive integer; default 1).
24
+ *
25
+ * @throws {SdkError} `SDK_DEFINITION_INVALID` when it is not.
26
+ */
27
+ export function assertMajor(version, what) {
28
+ const major = version ?? 1;
29
+ if (typeof major !== 'number' || !Number.isInteger(major) || major < 1) {
30
+ throw new SdkError('SDK_DEFINITION_INVALID', `${what}: version must be a positive integer major`);
31
+ }
32
+ return major;
33
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Whether a value is plain JSON — what may cross to a caged participant:
3
+ * null, booleans, finite numbers, strings, arrays and plain objects.
4
+ */
5
+ export declare function isPlainJson(value: unknown, depth?: number): boolean;
6
+ /**
7
+ * Asserts a value is plain JSON.
8
+ *
9
+ * @throws {SdkError} `SDK_NOT_PLAIN` when it is not.
10
+ */
11
+ export declare function assertPlain<T>(value: T, label?: string): T;
@@ -0,0 +1,37 @@
1
+ import { SdkError } from './errors.js';
2
+ const MAX_DEPTH = 64;
3
+ /**
4
+ * Whether a value is plain JSON — what may cross to a caged participant:
5
+ * null, booleans, finite numbers, strings, arrays and plain objects.
6
+ */
7
+ export function isPlainJson(value, depth = 0) {
8
+ if (depth > MAX_DEPTH) {
9
+ return false;
10
+ }
11
+ if (value === null || typeof value === 'boolean' || typeof value === 'string') {
12
+ return true;
13
+ }
14
+ if (typeof value === 'number') {
15
+ return Number.isFinite(value);
16
+ }
17
+ if (Array.isArray(value)) {
18
+ return value.every((item) => isPlainJson(item, depth + 1));
19
+ }
20
+ if (typeof value === 'object') {
21
+ const prototype = Object.getPrototypeOf(value);
22
+ return (prototype === Object.prototype || prototype === null)
23
+ && Object.values(value).every((item) => isPlainJson(item, depth + 1));
24
+ }
25
+ return false;
26
+ }
27
+ /**
28
+ * Asserts a value is plain JSON.
29
+ *
30
+ * @throws {SdkError} `SDK_NOT_PLAIN` when it is not.
31
+ */
32
+ export function assertPlain(value, label = 'value') {
33
+ if (!isPlainJson(value)) {
34
+ throw new SdkError('SDK_NOT_PLAIN', `${label} is not plain JSON`);
35
+ }
36
+ return value;
37
+ }
@@ -0,0 +1,5 @@
1
+ export { SDK_TARGET_KERNEL, SDK_VERSION } from './core/contract.js';
2
+ export { SdkError } from './core/errors.js';
3
+ export type { SdkErrorCode } from './core/errors.js';
4
+ export { assertPlain, isPlainJson } from './core/plain.js';
5
+ export { assertMajor, assertName, exposureKey, isValidName } from './core/names.js';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { SDK_TARGET_KERNEL, SDK_VERSION } from './core/contract.js';
2
+ export { SdkError } from './core/errors.js';
3
+ export { assertPlain, isPlainJson } from './core/plain.js';
4
+ export { assertMajor, assertName, exposureKey, isValidName } from './core/names.js';
@@ -0,0 +1,19 @@
1
+ import type { ExposedApiCaller } from '@brud/kernel';
2
+ import type { ExposureHandle, ParticipantContext } from './defineParticipant.js';
3
+ /** Methods one capability (or the shared part) contributes to a handle. */
4
+ export type Surface<TInstance extends object> = (ctx: ParticipantContext<TInstance>, caller: ExposedApiCaller) => Record<string, unknown>;
5
+ /**
6
+ * Builds a handle shaped by the caller's capabilities: each listed capability
7
+ * the caller holds adds its surface; `shared` is added for any admitted caller;
8
+ * a caller holding none of the listed capabilities gets `null` (refused).
9
+ *
10
+ * ```ts
11
+ * handle: byCapability(
12
+ * { 'notes:write': (ctx) => ({ add: … }), 'notes:admin': (ctx) => ({ purge: … }) },
13
+ * { shared: (ctx) => ({ list: … }) },
14
+ * )
15
+ * ```
16
+ */
17
+ export declare function byCapability<TInstance extends object>(surfaces: Readonly<Record<string, Surface<TInstance>>>, options?: {
18
+ readonly shared?: Surface<TInstance>;
19
+ }): ExposureHandle<TInstance>;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Builds a handle shaped by the caller's capabilities: each listed capability
3
+ * the caller holds adds its surface; `shared` is added for any admitted caller;
4
+ * a caller holding none of the listed capabilities gets `null` (refused).
5
+ *
6
+ * ```ts
7
+ * handle: byCapability(
8
+ * { 'notes:write': (ctx) => ({ add: … }), 'notes:admin': (ctx) => ({ purge: … }) },
9
+ * { shared: (ctx) => ({ list: … }) },
10
+ * )
11
+ * ```
12
+ */
13
+ export function byCapability(surfaces, options) {
14
+ return (caller, ctx) => {
15
+ const granted = Object.entries(surfaces).filter(([capability]) => caller.capabilities.has(capability));
16
+ if (granted.length === 0) {
17
+ return null;
18
+ }
19
+ return Object.freeze(Object.assign({}, options?.shared?.(ctx, caller), ...granted.map(([, surface]) => surface(ctx, caller))));
20
+ };
21
+ }
@@ -0,0 +1,85 @@
1
+ import { type ExposedApiCaller, type ExposedApiRefusal, type ExposedApiResolveOptions, type EventDeclaration, type InterceptionDeclaration, type InterceptionPointDeclaration, type KernelServiceModuleContext, type KindDeclaration, type ServiceContext, type ServiceDescriptor, type ServiceTier } from '@brud/kernel';
2
+ /** Who may reach an exposure, by call origin (kernel scope semantics). */
3
+ export type ExposureScope = 'kernel' | 'runtime' | 'host' | 'any';
4
+ /** What a participant's code sees: its id, options, instance, and `resolve`. */
5
+ export interface ParticipantContext<TInstance extends object> {
6
+ /** The participant's declared id (its name; the kernel issues its identity). */
7
+ readonly id: string;
8
+ /** Composition options passed to the service module. */
9
+ readonly options: Readonly<Record<string, unknown>>;
10
+ /** Boot options the kernel hands this participant (e.g. `settings.root`). */
11
+ readonly bootOptions: Readonly<Record<string, unknown>>;
12
+ /** Boot logger the kernel hands this participant, when one is configured. */
13
+ readonly logger: ServiceContext['logger'];
14
+ /** The instance `create` returned. */
15
+ readonly instance: TInstance;
16
+ /** True once the kernel is running and `resolve` is live. */
17
+ readonly running: boolean;
18
+ /**
19
+ * Resolves another giver's exposure, as this participant. Returns `null` when
20
+ * scope or policy refuses, and before the participant is running.
21
+ */
22
+ resolve<T = unknown>(name: string, options?: ExposedApiResolveOptions): T | null;
23
+ /**
24
+ * Why the most recent `resolve` returned `null`, or `null` when it succeeded.
25
+ * Before the participant is running (for example in `create`) exposures are
26
+ * not attached yet, so this reports `no-call-context`.
27
+ */
28
+ lastRefusal(): ExposedApiRefusal | null;
29
+ }
30
+ /**
31
+ * Builds the handle a caller receives (the exposure's Layer 2 projection).
32
+ * Runs at resolve time with the real caller's view; return `null` to refuse.
33
+ */
34
+ export type ExposureHandle<TInstance extends object> = (caller: ExposedApiCaller, ctx: ParticipantContext<TInstance>) => object | null;
35
+ /** One exposure a participant gives. */
36
+ export interface ExposureDefinition<TInstance extends object> {
37
+ /** Major version (default 1). */
38
+ readonly version?: number;
39
+ /** Origins admitted (default `runtime`). */
40
+ readonly scope?: ExposureScope;
41
+ /** Layer 1 policy (`policyVersion: 2`), evaluated by the kernel before `handle`. */
42
+ readonly policy?: Readonly<Record<string, unknown>>;
43
+ /** The caller-shaped handle. */
44
+ readonly handle: ExposureHandle<TInstance>;
45
+ }
46
+ /** A participant, defined once. */
47
+ export interface ParticipantDefinition<TInstance extends object> {
48
+ /** Dotted lower-case id, e.g. `acme.notes`. */
49
+ readonly id: string;
50
+ readonly description?: string;
51
+ /** Default `userland`. */
52
+ readonly tier?: ServiceTier;
53
+ /** Capabilities this participant requests for itself. */
54
+ readonly requests?: readonly string[];
55
+ /** Exposures, keyed by exposure name. */
56
+ readonly exposes?: Readonly<Record<string, ExposureDefinition<TInstance>>>;
57
+ /** Events this participant declares it may emit. Validated by the kernel when the participant is admitted. */
58
+ readonly events?: readonly EventDeclaration[];
59
+ /** Exposures of other givers this participant intercepts. Implement `intercept` on the instance. */
60
+ readonly interceptions?: readonly InterceptionDeclaration[];
61
+ /** Interception points on this participant's own exposures, naming the interceptors it admits by token id. */
62
+ readonly interceptionPoints?: readonly InterceptionPointDeclaration[];
63
+ /** Syntax kinds this participant serves. Each names one of its own exposures, which dispatches the kind. */
64
+ readonly kinds?: readonly KindDeclaration[];
65
+ /** Builds the participant's instance. */
66
+ readonly create: (ctx: ParticipantContext<TInstance>) => TInstance;
67
+ /** Runs once the kernel is running (`resolve` is live). */
68
+ readonly onRunning?: (ctx: ParticipantContext<TInstance>) => void | Promise<void>;
69
+ }
70
+ /** A service module's `createService`. */
71
+ export type CreateService<TInstance extends object> = (context?: KernelServiceModuleContext) => ServiceDescriptor<TInstance>;
72
+ /**
73
+ * Defines a participant and returns its service module's `createService`.
74
+ *
75
+ * The result is the exact descriptor the kernel accepts (token, manifest,
76
+ * exposure bindings, lifecycle); the kernel validates and enforces it as if it
77
+ * were hand-written. Export it as `createService`:
78
+ *
79
+ * ```ts
80
+ * export const createService = defineParticipant({ id: 'acme.notes', create: () => new Notes(), exposes: { … } });
81
+ * ```
82
+ *
83
+ * @throws {SdkError} `SDK_DEFINITION_INVALID` for an invalid definition.
84
+ */
85
+ export declare function defineParticipant<TInstance extends object>(definition: ParticipantDefinition<TInstance>): CreateService<TInstance>;
@@ -0,0 +1,98 @@
1
+ import { ExposedApiRegistryToken, createServiceToken, withExposureBindings, } from '@brud/kernel';
2
+ import { SdkError } from '../core/errors.js';
3
+ import { assertMajor, assertName, exposureKey } from '../core/names.js';
4
+ /** What `lastRefusal` reports before the registry is attached. */
5
+ const NOT_ATTACHED = Object.freeze({
6
+ code: 'no-call-context',
7
+ message: 'no kernel call context: exposures are not attached yet (for example during synchronous create)',
8
+ });
9
+ /**
10
+ * Defines a participant and returns its service module's `createService`.
11
+ *
12
+ * The result is the exact descriptor the kernel accepts (token, manifest,
13
+ * exposure bindings, lifecycle); the kernel validates and enforces it as if it
14
+ * were hand-written. Export it as `createService`:
15
+ *
16
+ * ```ts
17
+ * export const createService = defineParticipant({ id: 'acme.notes', create: () => new Notes(), exposes: { … } });
18
+ * ```
19
+ *
20
+ * @throws {SdkError} `SDK_DEFINITION_INVALID` for an invalid definition.
21
+ */
22
+ export function defineParticipant(definition) {
23
+ const id = assertName(definition.id, 'participant id');
24
+ const tier = definition.tier ?? 'userland';
25
+ const exposures = Object.entries(definition.exposes ?? {}).map(([name, exposure]) => ({
26
+ name: assertName(name, `exposure of ${id}`),
27
+ major: assertMajor(exposure.version, `exposure ${name}`),
28
+ exposure,
29
+ }));
30
+ if (typeof definition.create !== 'function') {
31
+ throw new SdkError('SDK_DEFINITION_INVALID', `participant ${id}: create must be a function`);
32
+ }
33
+ const manifest = Object.freeze({
34
+ requests: { capabilities: [...(definition.requests ?? [])] },
35
+ exposures: exposures.map(({ name, major, exposure }) => ({
36
+ name,
37
+ version: major,
38
+ scope: exposure.scope ?? 'runtime',
39
+ ...(exposure.policy === undefined ? {} : { policy: exposure.policy }),
40
+ })),
41
+ events: [...(definition.events ?? [])],
42
+ ...(definition.interceptions === undefined ? {} : { interceptions: [...definition.interceptions] }),
43
+ ...(definition.interceptionPoints === undefined ? {} : { interceptionPoints: [...definition.interceptionPoints] }),
44
+ ...(definition.kinds === undefined ? {} : { kinds: [...definition.kinds] }),
45
+ });
46
+ const token = createServiceToken(id, definition.description ?? `Participant "${id}"`);
47
+ return (moduleContext) => ({
48
+ token,
49
+ tier,
50
+ dependencies: [],
51
+ manifest,
52
+ factory: (bootContext) => {
53
+ let registry;
54
+ let instance;
55
+ const ctx = {
56
+ id,
57
+ options: moduleContext?.options ?? {},
58
+ bootOptions: bootContext?.options ?? {},
59
+ logger: bootContext?.logger,
60
+ get instance() {
61
+ if (instance === undefined) {
62
+ throw new SdkError('SDK_INSTANCE_NOT_READY', `participant ${id}: the instance is not created yet`);
63
+ }
64
+ return instance;
65
+ },
66
+ get running() {
67
+ return registry !== undefined;
68
+ },
69
+ resolve: (name, options) => registry === undefined ? null : registry.resolve(name, options),
70
+ lastRefusal: () => registry === undefined ? NOT_ATTACHED : registry.lastRefusal(),
71
+ };
72
+ const created = definition.create(ctx);
73
+ if (created === null || typeof created !== 'object') {
74
+ throw new SdkError('SDK_DEFINITION_INVALID', `participant ${id}: create must return an object`);
75
+ }
76
+ instance = created;
77
+ const own = created.onRunning;
78
+ Object.defineProperty(created, 'onRunning', {
79
+ value: async (broker) => {
80
+ registry = broker.requestAccess({ callerId: id, tier, options: {} }, ExposedApiRegistryToken);
81
+ if (typeof own === 'function') {
82
+ await own.call(created, broker);
83
+ }
84
+ await definition.onRunning?.(ctx);
85
+ },
86
+ enumerable: false,
87
+ configurable: true,
88
+ });
89
+ const bindings = {};
90
+ for (const { name, major, exposure } of exposures) {
91
+ bindings[exposureKey(name, major)] = {
92
+ projection: (_service, caller) => exposure.handle(caller, ctx),
93
+ };
94
+ }
95
+ return withExposureBindings(created, bindings);
96
+ },
97
+ });
98
+ }
@@ -0,0 +1,4 @@
1
+ export { defineParticipant } from './defineParticipant.js';
2
+ export type { CreateService, ExposureDefinition, ExposureHandle, ExposureScope, ParticipantContext, ParticipantDefinition, } from './defineParticipant.js';
3
+ export { byCapability } from './byCapability.js';
4
+ export type { Surface } from './byCapability.js';
@@ -0,0 +1,2 @@
1
+ export { defineParticipant } from './defineParticipant.js';
2
+ export { byCapability } from './byCapability.js';
@@ -0,0 +1,27 @@
1
+ import { type BrudKernel } from '@brud/kernel';
2
+ /** One participant in a test composition: a module path, or a module source to write. */
3
+ export interface TestEntry {
4
+ /** Absolute path of a service module. */
5
+ readonly path?: string;
6
+ /** Full source of an ES module exporting `createService` (written to a temp file). */
7
+ readonly source?: string;
8
+ /**
9
+ * Composition officialness (W-01). Native modules run only when official, so
10
+ * native test entries default to `true`.
11
+ */
12
+ readonly official?: boolean;
13
+ }
14
+ /** Teardown registration, as `node:test`'s `t.after`. */
15
+ export interface TestTeardown {
16
+ after(fn: () => Promise<void> | void): void;
17
+ }
18
+ /**
19
+ * Boots the real kernel with its hardcores plus `entries`, in order — the way
20
+ * a product boots. Shuts down and cleans up through `t.after`.
21
+ *
22
+ * @param t - The test context.
23
+ * @param entries - Participants, in composition order.
24
+ * @param options - Extra composition options.
25
+ * @returns The running kernel.
26
+ */
27
+ export declare function bootTestKernel(t: TestTeardown, entries: readonly TestEntry[], options?: Readonly<Record<string, unknown>>): Promise<BrudKernel>;
@@ -0,0 +1,49 @@
1
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises';
2
+ import { tmpdir } from 'node:os';
3
+ import { isAbsolute, join } from 'node:path';
4
+ import { bootKernel, provisionIdentityRegistryStorage } from '@brud/kernel';
5
+ /**
6
+ * The kernel's hardcore service modules. Kept here until the kernel exports
7
+ * its hardcore set (plan decision S-3).
8
+ */
9
+ const HARDCORE_MODULES = ['identityRegistry', 'exposedApiRegistry', 'parser', 'router', 'wasmCage', 'events', 'interception']
10
+ .map((name) => `kernel:serviceModules/${name}.js`);
11
+ /**
12
+ * Boots the real kernel with its hardcores plus `entries`, in order — the way
13
+ * a product boots. Shuts down and cleans up through `t.after`.
14
+ *
15
+ * @param t - The test context.
16
+ * @param entries - Participants, in composition order.
17
+ * @param options - Extra composition options.
18
+ * @returns The running kernel.
19
+ */
20
+ export async function bootTestKernel(t, entries, options = {}) {
21
+ const root = await mkdtemp(join(tmpdir(), 'brud-sdk-'));
22
+ let kernel;
23
+ t.after(async () => {
24
+ if (kernel?.lifecycleState === 'RUNNING') {
25
+ await kernel.shutdown();
26
+ }
27
+ await rm(root, { recursive: true, force: true });
28
+ });
29
+ const services = HARDCORE_MODULES.map((path) => ({ path, official: true }));
30
+ for (const [index, entry] of entries.entries()) {
31
+ let path = entry.path;
32
+ if (entry.source !== undefined) {
33
+ path = join(root, `participant-${String(index)}.mjs`);
34
+ await writeFile(path, entry.source, 'utf8');
35
+ }
36
+ if (path === undefined || !isAbsolute(path)) {
37
+ throw new TypeError(`test entry ${String(index)} needs an absolute path or a source`);
38
+ }
39
+ services.push({ path, official: entry.official ?? true });
40
+ }
41
+ const identityPath = join(root, 'identity.json');
42
+ const configPath = join(root, 'brud.config.json');
43
+ await writeFile(configPath, JSON.stringify({ services }), 'utf8');
44
+ provisionIdentityRegistryStorage(identityPath);
45
+ kernel = await bootKernel(configPath, {
46
+ options: { 'identity.registry.path': identityPath, 'router.root': root, ...options },
47
+ });
48
+ return kernel;
49
+ }
@@ -0,0 +1,2 @@
1
+ export { bootTestKernel } from './harness.js';
2
+ export type { TestEntry, TestTeardown } from './harness.js';
@@ -0,0 +1 @@
1
+ export { bootTestKernel } from './harness.js';
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@brud/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.2",
4
+ "description": "The BrudOS SDK: define, compose, test and ship participants on the Brud kernel",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "./participant": {
15
+ "types": "./dist/participant/index.d.ts",
16
+ "import": "./dist/participant/index.js",
17
+ "default": "./dist/participant/index.js"
18
+ },
19
+ "./testing": {
20
+ "types": "./dist/testing/index.d.ts",
21
+ "import": "./dist/testing/index.js",
22
+ "default": "./dist/testing/index.js"
23
+ },
24
+ "./package.json": "./package.json"
25
+ },
26
+ "files": [
27
+ "dist"
28
+ ],
29
+ "engines": {
30
+ "node": ">=22"
31
+ },
32
+ "scripts": {
33
+ "build": "tsc -p tsconfig.json",
34
+ "typecheck": "tsc -p tsconfig.json --noEmit",
35
+ "test": "node --import tsx --test __tests__/*.test.ts"
36
+ },
37
+ "peerDependencies": {
38
+ "@brud/kernel": "^0.0.2"
39
+ },
40
+ "devDependencies": {
41
+ "@types/node": "22.x"
42
+ },
43
+ "license": "Apache-2.0",
44
+ "repository": {
45
+ "type": "git",
46
+ "url": "git+https://github.com/rahatarch/brud.git",
47
+ "directory": "packages/sdk"
48
+ },
49
+ "homepage": "https://github.com/rahatarch/brud/tree/main/docs-next",
50
+ "bugs": {
51
+ "url": "https://github.com/rahatarch/brud/issues"
52
+ },
53
+ "publishConfig": {
54
+ "access": "public"
55
+ },
56
+ "keywords": [
57
+ "brud",
58
+ "brudos",
59
+ "kernel",
60
+ "participants"
61
+ ]
62
+ }