@niwa-labs/plugin 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Niwa Labs contributors
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/README.md CHANGED
@@ -1,3 +1,3 @@
1
- # Temporary Holding Version
1
+ # @niwa-labs/plugin
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 plugin authoring API: `plugin()`, the `PluginApi` type, `offerKey`, `CallerBinding`, and offer data that other packages reference without depending back on their owners.
package/package.json CHANGED
@@ -1,6 +1,13 @@
1
1
  {
2
2
  "name": "@niwa-labs/plugin",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.0",
4
+ "license": "MIT",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": "./src/index.ts"
8
+ },
9
+ "dependencies": {
10
+ "@niwa-labs/core": "0.0.0",
11
+ "zod": "^4.6.7"
12
+ }
13
+ }
package/src/binding.ts ADDED
@@ -0,0 +1,45 @@
1
+ // How a plugin knows what address a caller speaks as.
2
+
3
+ import type { Address, Caller } from "@niwa-labs/core";
4
+
5
+ /**
6
+ * How the module knows what address a caller speaks as.
7
+ *
8
+ * The identity of a caller is bound by the transport, never taken from a payload a model
9
+ * wrote. The binding is where that identity becomes an address:
10
+ * the client of an MCP session is the session, the client of the owner is the owner.
11
+ */
12
+ export type CallerBinding = (caller: Caller) => Address | undefined;
13
+
14
+ export interface MessagesOptions {
15
+ /**
16
+ * The address a caller speaks as.
17
+ *
18
+ * Return undefined for a caller that stands for nobody in particular: the host itself, or a
19
+ * handler of a plugin that has no address of its own. Default: a client speaks as itself,
20
+ * and nobody else speaks as anybody.
21
+ */
22
+ bind?: CallerBinding;
23
+ }
24
+
25
+ /**
26
+ * The default binding: a client speaks as itself, unless its token says it is the owner.
27
+ *
28
+ * A connection whose principal is the owner speaks as the owner, so the owner can be answered
29
+ * through a surface; every other client speaks as itself, whatever it calls itself. The host and
30
+ * a handler stand for nobody: the host is the runtime, and a handler belongs to a plugin, not to
31
+ * an address.
32
+ *
33
+ * The identity of a caller is bound by the transport, never by a payload: the principal comes from the
34
+ * token the connection showed in `hello`.
35
+ */
36
+ function defaultBind(caller: Caller): Address | undefined {
37
+ if (caller.kind !== "client") return undefined;
38
+ if (caller.principal?.kind === "owner") return { kind: "owner" };
39
+ return { kind: "client", id: caller.id };
40
+ }
41
+
42
+ /** The binding the options ask for. */
43
+ export function bindingOf(opts?: MessagesOptions): CallerBinding {
44
+ return opts?.bind ?? defaultBind;
45
+ }
package/src/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ // The plugin entry: how a plugin is written.
2
+
3
+ export * from "./plugin.ts";
4
+ export * from "./plugin-types.ts";
5
+ export * from "./binding.ts";
6
+ export * from "./offers.ts";
7
+ export * from "./trigger.ts";
package/src/offers.ts ADDED
@@ -0,0 +1,207 @@
1
+ /**
2
+ * What a plugin offers to the plugins that read it (`api.offer`, `api.offers`): the built-in workflows a plugin ships
3
+ * go to the workflow module, the timers it needs to the timers. The points and the shape of what is offered live here,
4
+ * so the offering plugin imports no reader.
5
+ *
6
+ * Built-in workflows: scripts a plugin ships in its own tree and niwa runs by itself. A plugin offers each one in its setup —
7
+ * `api.offer(BUILTIN_WORKFLOW, { name, file, description, triggers })` — and the workflow module, installed after it,
8
+ * does the rest when the host starts: it registers the file (its code is stored under the home, its version is the hash
9
+ * of its source closure, so a changed file in a new build of niwa is a new version by itself) and installs it on the
10
+ * `on` of the script, under a profile that is exactly its `uses`. A built-in the plugin no longer offers is
11
+ * uninstalled. The pair (plugin, name) finds the same `wf-…` again on every start, so nothing is made twice.
12
+ *
13
+ * The owner does not edit a built-in: registering a file under its id and uninstalling it are refused; it is turned
14
+ * off by the option of the plugin that offers it.
15
+ */
16
+
17
+ import { z } from "zod";
18
+
19
+ import type { RecordType } from "@niwa-labs/core";
20
+ import { offerKey } from "./plugin.ts";
21
+ import type { OfferKey } from "./plugin-types.ts";
22
+
23
+ /** One built-in workflow, as its plugin offers it. */
24
+ export interface BuiltinWorkflow {
25
+ /** Its name among the built-ins of the plugin: with the plugin, what finds it again across restarts. */
26
+ readonly name: string;
27
+ /** The script: an absolute path inside the plugin's own tree. */
28
+ readonly file: string;
29
+ /** A few words on one line: what it is registered and installed under. */
30
+ readonly description: string;
31
+ /**
32
+ * The record types its `on` names, other than the records of scripts: the workflow module starts runs on them as
33
+ * on the `triggers` it is given, so the owner does not list them. A type is given by its name when the plugin that
34
+ * declares it is not one the offering plugin imports (`"timer.fired"`): it must be declared by a plugin installed
35
+ * before the workflow module.
36
+ */
37
+ readonly triggers?: ReadonlyArray<RecordType<any> | string>;
38
+ /**
39
+ * Each new version comes in as a candidate: it is registered, and neither the latest version of the workflow nor its
40
+ * installation moves to it until it is promoted. Before a version was accepted, the candidate is shown and starts on
41
+ * nothing.
42
+ */
43
+ readonly gated?: boolean;
44
+ /** This built-in runs the plugin's trials and may promote their checked versions. */
45
+ readonly suite?: true;
46
+ }
47
+
48
+ /** Where a plugin offers a built-in workflow: `api.offer(BUILTIN_WORKFLOW, { name, file, description, triggers })`. */
49
+ export const BUILTIN_WORKFLOW: OfferKey<BuiltinWorkflow> = offerKey("workflow.builtin", "workflow");
50
+
51
+ /**
52
+ * What a timer does with the dues it missed while the host was down.
53
+ *
54
+ * - "once": one firing for all the missed dues.
55
+ * - "skip": nothing for the missed dues.
56
+ */
57
+ export type MissedRule = "once" | "skip";
58
+
59
+ /** What every timer has, whatever its schedule. */
60
+ interface TimerBase {
61
+ /** The id of the timer: the author's name for it, which the firings carry. */
62
+ readonly id: string;
63
+ /** A few words a person reads in a list. Without one, the schedule is the description. */
64
+ readonly description?: string;
65
+ /** What to do with the dues missed while the host was down. Default: "once". */
66
+ readonly missed?: MissedRule;
67
+ }
68
+
69
+ /**
70
+ * One timer: when it fires, and what it does with the dues it missed.
71
+ *
72
+ * A timer has exactly one schedule: a period (`every`), a moment (`at`) or a time of day
73
+ * (`daily`). A timer with none would never fire and a timer with two is not a choice anybody can
74
+ * make, so neither is a definition.
75
+ */
76
+ export type TimerDef = TimerBase &
77
+ (
78
+ | {
79
+ /** The period, in milliseconds. The timer fires again every period. */
80
+ readonly every: number;
81
+ readonly at?: never;
82
+ readonly daily?: never;
83
+ }
84
+ | {
85
+ /** The moment, in milliseconds since the epoch. The timer fires once. */
86
+ readonly at: number;
87
+ readonly every?: never;
88
+ readonly daily?: never;
89
+ }
90
+ | {
91
+ /** The time of day, "HH:MM" in local time. The timer fires every day at that time. */
92
+ readonly daily: string;
93
+ readonly every?: never;
94
+ readonly at?: never;
95
+ }
96
+ );
97
+
98
+ /**
99
+ * A timer as a plugin offers it: the plain definition, or the trigger that carries one (`timer.daily("04:00", { id })`).
100
+ * The data of a firing is what the trigger is a record type of.
101
+ */
102
+ export type TimerOffer = TimerDef | { readonly kind: "trigger"; readonly timer: string; readonly def: TimerDef };
103
+
104
+ /**
105
+ * Where a plugin offers a timer it needs (`api.offer(TIMER_OFFER, { id, daily: "04:00" })`): the timers
106
+ * plugin schedules it with the ones it is given, so the owner does not list it. A timer of the same id in the
107
+ * owner's list is the one that is scheduled.
108
+ */
109
+ export const TIMER_OFFER: OfferKey<TimerOffer> = offerKey("timer", "timers");
110
+
111
+ /**
112
+ * A client module a plugin offers to the cockpit: where its source is on the host. The host lists the
113
+ * modules (`niwa.cockpit.catalog`) with a hash of their code, and the web server builds and serves them to the
114
+ * browser; the plugin never imports the module, so the host process loads no React.
115
+ */
116
+ export interface CockpitModuleOffer {
117
+ /** The id of the module, the id of the cockpit plugin it exports: lowercase words joined by `-` or `.`. */
118
+ readonly id: string;
119
+ /** The module's entry: an absolute path to a source file inside the plugin's own tree. */
120
+ readonly entry: string;
121
+ /** Stylesheets the module needs: absolute paths of files inside the plugin's own tree. */
122
+ readonly styles?: readonly string[];
123
+ }
124
+
125
+ /**
126
+ * Where a plugin offers its cockpit module: `api.offer(COCKPIT_MODULE, { id, entry })`. The host itself reads the
127
+ * point, so no plugin has to be installed to read it.
128
+ */
129
+ export const COCKPIT_MODULE: OfferKey<CockpitModuleOffer> = offerKey("cockpit.module", "host");
130
+
131
+ /**
132
+ * An agent as a plugin defines it: the agents module serves it as it serves the agents of its own
133
+ * options. The name is the agent's address (`agent:<name>`); it runs on a harness installation or on a
134
+ * role, is told its prompt and character, and its sessions see the niwa actions of its hands.
135
+ */
136
+ interface AgentOfferBase {
137
+ readonly name: string;
138
+ readonly prompt: string;
139
+ readonly character?: string;
140
+ readonly hands?: readonly string[];
141
+ readonly tools?: "all" | "niwa-only" | { readonly allow: readonly string[] };
142
+ readonly project?: { readonly cwd: string; readonly direction?: string };
143
+ }
144
+
145
+ /**
146
+ * An agent runs on exactly one of a harness installation (`harness`) and a role (`role`): an offer with
147
+ * neither would not be an agent and one with both is not a choice anybody can make, so neither is an offer.
148
+ */
149
+ export type AgentOffer = AgentOfferBase &
150
+ (
151
+ | { readonly harness: string; readonly role?: never }
152
+ | { readonly role: string; readonly harness?: never }
153
+ );
154
+
155
+ /** Where a plugin defines an agent it needs (`api.offer(AGENT, { name, harness, prompt })`): the agents module reads it. */
156
+ export const AGENT: OfferKey<AgentOffer> = offerKey("agent", "agents");
157
+
158
+ /**
159
+ * Operations a plugin began outside niwa that have not ended (a merge armed on a forge, a message
160
+ * scheduled elsewhere), as a plugin offers them to whoever reports what a hold of a run leaves
161
+ * behind: a hold stops the run's own writes, but what was begun elsewhere goes on, and the person
162
+ * holding the run should be told.
163
+ *
164
+ * `list` names an action of the offering plugin that reads and takes no input; it answers
165
+ * `{ items }`, each item what the plugin says of one operation, and may carry the action that calls
166
+ * it off (`cancel`, with its input), which the person is shown and the report never runs.
167
+ */
168
+ export interface PendingExternal {
169
+ /** What the operations are, for a person reading the hold: "armed merges". */
170
+ readonly label: string;
171
+ /** The name of the action that lists them. */
172
+ readonly list: string;
173
+ }
174
+
175
+ /** The action that calls one pending operation off, as the plugin that lists it says it. */
176
+ export const PendingCancelSchema = z.object({ action: z.string().min(1), input: z.record(z.string(), z.unknown()) });
177
+
178
+ /** One pending operation: what the plugin says of it, and how to call it off when it can be. */
179
+ export const PendingExternalItemSchema = z.looseObject({ cancel: PendingCancelSchema.optional() });
180
+ export type PendingExternalItem = z.output<typeof PendingExternalItemSchema>;
181
+
182
+ /** What the listing action of a `PendingExternal` answers. */
183
+ export const PendingExternalAnswerSchema = z.object({ items: z.array(PendingExternalItemSchema) });
184
+
185
+ /**
186
+ * Where a plugin offers the operations it has pending (`api.offer(PENDING_EXTERNAL, { label, list })`).
187
+ * The host reads the point, so no plugin has to be installed for the offer to be served: where nobody
188
+ * reports holds, the offer is not read.
189
+ */
190
+ export const PENDING_EXTERNAL: OfferKey<PendingExternal> = offerKey("pending.external", "host");
191
+
192
+ /**
193
+ * A package a plugin gives scripts: a package of `@niwa-labs` that is installed where the plugin is and not among the
194
+ * packages niwa runs with (`@niwa-labs/forge`, whose `/flow` entry a delivery script imports). The workflow module, when
195
+ * the host has one, reads it once the plugins are installed: a stored copy of a script finds the package by its name as
196
+ * it finds niwa's own, its manifest names it with its version, and a script process in a box may read it. It is offered
197
+ * to the host, so a plugin offers it whether or not the host runs scripts, and in any order.
198
+ */
199
+ export interface ScriptPackage {
200
+ /** The name of the package: `@niwa-labs/<name>`. */
201
+ readonly name: string;
202
+ /** The folder of the package, an absolute path: the one whose `package.json` has that name. */
203
+ readonly root: string;
204
+ }
205
+
206
+ /** Where a plugin offers a package to scripts: `api.offer(SCRIPT_PACKAGE, { name, root })`. */
207
+ export const SCRIPT_PACKAGE: OfferKey<ScriptPackage> = offerKey("script.package", "host");
@@ -0,0 +1,408 @@
1
+ // The contracts of a plugin: what a plugin is given and what it hands over.
2
+ import type { z } from "zod";
3
+ import type { SEAL_VERSION } from "./plugin.ts";
4
+ import type { Subscribable } from "./trigger.ts";
5
+
6
+ import type {
7
+ Action,
8
+ ArtifactStore,
9
+ ActionRef,
10
+ Effect,
11
+ AdjustFn,
12
+ Ask,
13
+ Asker,
14
+ AuthorizeHow,
15
+ Caller,
16
+ EmitOptions,
17
+ EmitBatch,
18
+ Grant,
19
+ GuardFn,
20
+ Handler,
21
+ JournalReader,
22
+ LiveFrame,
23
+ PluginName,
24
+ PluginVersion,
25
+ RecordType,
26
+ SecretStore,
27
+ StoredRecord,
28
+ Timestamp,
29
+ Token,
30
+ Verb,
31
+ Narrowed,
32
+ RecordQuery,
33
+ PathFilter,
34
+ RuleSpec,
35
+ } from "@niwa-labs/core";
36
+
37
+ /**
38
+ * Where a new subscription starts: `"now"`, the position of the journal when it is installed, or
39
+ * `"start"`, the beginning of the journal. A subscription that was installed before goes on from
40
+ * the position it reached, whatever this says.
41
+ */
42
+ export type SubscriptionStart = "now" | "start";
43
+
44
+ /** How deep a subscription may wake on records its own invocations caused. */
45
+ export interface Reentry {
46
+ /** How many of its own invocations may stand on the chain of causes of a record that wakes it. */
47
+ readonly depth: number;
48
+ }
49
+
50
+ /** Keys are compared within a subscription. Numbers must be finite. */
51
+ export type SubscriptionKey = string | number;
52
+
53
+ export interface KeyedConcurrency<T> {
54
+ /**
55
+ * Select the key from the same data the handler receives. Use a pure, synchronous function
56
+ * and keep the key mapping stable for the subscription while it has unfinished invocations.
57
+ * If selection fails, the host reports the record and stops scanning this subscription there.
58
+ */
59
+ readonly by: (data: T) => SubscriptionKey;
60
+ }
61
+
62
+ /** A limit on unfinished invocations, or one unfinished invocation per key. */
63
+ export type SubscriptionConcurrency<T> = number | KeyedConcurrency<T>;
64
+
65
+ export interface HandlerOptions<T = unknown> {
66
+ /** Handler name inside the plugin. Default: the record type name. */
67
+ id?: string;
68
+ /**
69
+ * Equality on fields of the data, by field name or dotted path: only records whose data holds
70
+ * every field wake the handler. What equality cannot say, the handler checks itself.
71
+ */
72
+ filter?: PathFilter<T>;
73
+ /** Where the subscription starts when it is new. Default: `"now"`. */
74
+ from?: SubscriptionStart;
75
+ /**
76
+ * How many records of the subscription run at once. Default: 1, one after the other: the next
77
+ * record starts when the one before it is done, and a record that waits or is paused holds the
78
+ * ones after it. `Infinity` lets every record run as soon as it is admitted. With `{ by }`,
79
+ * records with the same key run in order, and records with other keys can pass a busy key.
80
+ * Waiting and paused invocations continue to hold their keys.
81
+ */
82
+ concurrency?: SubscriptionConcurrency<T>;
83
+ /**
84
+ * A subscription is not woken by a record its own invocations caused. A reentrant one is, down to
85
+ * the depth it gives; past it the record is passed over and the host says so.
86
+ */
87
+ reentrant?: Reentry;
88
+ /**
89
+ * The record types this handler needs another plugin to declare, because the work it does
90
+ * writes or waits for them (a durable sleep needs the timers). The host refuses to serve when
91
+ * one of them is declared by nobody: the handler would fail or wait for ever. Name the plugin
92
+ * that produces a type in its `provider`, so the refusal can say what to install.
93
+ */
94
+ requires?: readonly RecordType<any>[];
95
+ }
96
+
97
+ /**
98
+ * A query a subscription is woken by: the one query of the core, without a position of its own. A
99
+ * query value that does carry a `from` is refused by the host when it reads the subscriber.
100
+ */
101
+ export type SubscriberQuery = Omit<RecordQuery<any>, "from">;
102
+
103
+ /**
104
+ * A subscription a plugin reads from the journal: its own records are data, not code registered at
105
+ * setup. Its id, with the plugin's name, is its identity: its position and its own chain of causes.
106
+ */
107
+ export interface Subscriber {
108
+ /** Its name inside the plugin; it has no "/". */
109
+ readonly id: string;
110
+ /**
111
+ * The records it is woken by: a record that answers any of the queries, each the query of the core
112
+ * (types as names or families, equality on paths of their data, the stream). The position it
113
+ * reads after is `from` below, never the query's own.
114
+ */
115
+ readonly queries: ReadonlyArray<SubscriberQuery>;
116
+ /** The position it starts after when it is new: where it was made. */
117
+ readonly from: number;
118
+ /** The position after which it admits nothing: where it ended. */
119
+ readonly until?: number;
120
+ /** How many records run at once, or one at a time per selected key. Default 1. */
121
+ readonly concurrency?: SubscriptionConcurrency<unknown>;
122
+ readonly handler: Handler<unknown>;
123
+ }
124
+
125
+ /**
126
+ * The state of one plugin: values by key, owned by that plugin.
127
+ *
128
+ * A change is one named operation, not a read followed later by a write, so two handlers cannot
129
+ * lose each other's updates. Inside an invocation a read is recorded: on a replay it returns
130
+ * what was read the first time, so code never sees today's state while it is continuing
131
+ * yesterday's computation.
132
+ */
133
+ export interface StateHandle<T> {
134
+ /** The name of this key inside its plugin. */
135
+ readonly name: string;
136
+ /** The current value. Inside an invocation this is a recorded read. */
137
+ get(): T;
138
+ /** Replace the value. This is one committed change. */
139
+ set(value: T): T;
140
+ /**
141
+ * Change the value with a function of the current one.
142
+ *
143
+ * The function runs against the value as it is at this moment and the change is committed in
144
+ * the same turn, so a concurrent update cannot be lost between the two.
145
+ */
146
+ update(fn: (current: T) => T): T;
147
+ /**
148
+ * Return the current value and reset it to the initial one, in one committed change.
149
+ *
150
+ * A task that finishes while the batch is taken lands in the next batch, not in a hole. After a
151
+ * crash and a restart the same invocation takes the same batch again.
152
+ */
153
+ take(): T;
154
+ }
155
+
156
+ /**
157
+ * What a service is given when it starts.
158
+ *
159
+ * A service is work the host runs for as long as it serves: a scheduler, a poller, a ticker.
160
+ * It is not a handler and not an invocation: nothing wakes it, and it has no step.
161
+ */
162
+ export interface ServiceContext {
163
+ /**
164
+ * Write an external input: it starts its own chain (root = its own id, cause = null).
165
+ *
166
+ * Only a type the plugin declared is accepted. With an explicit id the write is idempotent:
167
+ * the same id with the same content returns the record that is already committed.
168
+ */
169
+ emit<T>(type: RecordType<T>, data: T, opts?: EmitOptions): Promise<StoredRecord>;
170
+ emitAll<const T extends readonly RecordType<any>[]>(entries: EmitBatch<T, EmitOptions>): Promise<StoredRecord[]>;
171
+ /** The clock, in milliseconds since the epoch. */
172
+ now(): Timestamp;
173
+ /**
174
+ * Run `fn` at the moment `at`, in milliseconds since the epoch.
175
+ *
176
+ * The returned function cancels it: a moment that will not come must not fire. The moment is
177
+ * read from the clock of the host, so a test may move the time of the host instead of waiting.
178
+ */
179
+ schedule(at: number, fn: () => void | Promise<void>): () => void;
180
+ }
181
+
182
+ /**
183
+ * A service: work the host runs while it serves.
184
+ *
185
+ * It returns the function that stops it. The host calls that when the host closes or when the
186
+ * plugin is unloaded, and waits for it when it is a promise: what the service owns must be
187
+ * released before the host is gone.
188
+ */
189
+ export type Service = (ctx: ServiceContext) => () => void | Promise<void>;
190
+
191
+ /**
192
+ * A point where plugins offer something to another plugin that reads it: the built-in workflows a
193
+ * plugin ships go to the workflow module, the timers it needs to the timers. Offers are matched by
194
+ * the name of the key, as actions are by theirs, so the offering plugin need not import the reader.
195
+ *
196
+ * `reader` is the plugin that reads the point: a host where a plugin offers to a reader that is not
197
+ * installed refuses to serve, as it does for a trigger nobody declares.
198
+ */
199
+ export interface OfferKey<T> {
200
+ readonly kind: "offer";
201
+ readonly name: string;
202
+ readonly reader: string;
203
+ /** The type of what is offered; never set, only carried. */
204
+ readonly _value?: T;
205
+ }
206
+
207
+ /** One offer, with the plugin that made it: the host says who offered, the offer does not. */
208
+ export interface Offered<T> {
209
+ readonly plugin: PluginName;
210
+ readonly value: T;
211
+ }
212
+
213
+ /** What a plugin needs the host to serve: see `PluginApi.needs`. */
214
+ export interface PluginNeeds {
215
+ /** Actions the plugin calls, by reference or by name. */
216
+ readonly actions?: ReadonlyArray<ActionRef<any, any, any> | string>;
217
+ /** Record types the plugin writes or waits for, by declaration or by name. */
218
+ readonly types?: ReadonlyArray<RecordType<any> | string>;
219
+ }
220
+
221
+ /** What a plugin's setup function receives. */
222
+ export interface PluginApi {
223
+ /** Declare record types this plugin writes or handles. */
224
+ declare(...types: RecordType<any>[]): void;
225
+ /** Offer a value at a point another plugin reads (`OfferKey`): the host records which plugin offered it. */
226
+ offer<T>(key: OfferKey<T>, value: T): void;
227
+ /**
228
+ * What the plugins offer at a point, in the order they were installed, with who offered each.
229
+ *
230
+ * Read in the setup, it holds the offers of the plugins installed before this one and its own,
231
+ * as `recordType` does, and a plugin installed later that offers there is refused: install it
232
+ * first. Read later (a service, an action), it holds the offers of every installed plugin.
233
+ */
234
+ offers<T>(key: OfferKey<T>): Offered<T>[];
235
+ /**
236
+ * Run work for as long as the host serves.
237
+ *
238
+ * The service starts when the host starts serving, and stops when the host closes or the
239
+ * plugin is unloaded. What it writes through `ctx.emit` starts its own chain: a service is
240
+ * not inside an invocation, so it has no cause to give it.
241
+ */
242
+ service(start: Service): void;
243
+ /** Register an action callable by name from handlers and clients. */
244
+ action(a: Action<any, any>): void;
245
+ /**
246
+ * Actions that grow from the journal: read at every lookup and every description, so an action a
247
+ * record made is served from the moment it is committed. A declared action of the same name wins.
248
+ */
249
+ catalog(read: () => readonly Action<any, any>[]): void;
250
+ /**
251
+ * Run before an action and may change its input. The intercept is kept by the action's name,
252
+ * so a typed reference is enough: a plugin need not hold the action it adjusts.
253
+ *
254
+ * The intercept sees the parsed input, `I`, not what a caller may write down (`In`): it runs
255
+ * after the schema, so a branded field is branded here.
256
+ */
257
+ adjust<I, In = I>(action: ActionRef<I, any, In>, fn: AdjustFn<NoInfer<I>>): void;
258
+ /** Run before an action and may deny it. Like `adjust`, a typed reference is enough. */
259
+ guard<I, In = I>(action: ActionRef<I, any, In>, fn: GuardFn<NoInfer<I>>): void;
260
+ /**
261
+ * Send a live frame on a channel.
262
+ *
263
+ * A frame is not a record: it is never written to the journal, and a subscriber that is not
264
+ * connected misses it. Nothing may depend on having received
265
+ * a frame; the complete message is committed as a record when it is complete.
266
+ */
267
+ live(channel: string, frame: LiveFrame): void;
268
+ /**
269
+ * Handle the records of a type, or of a trigger over one (`timer.daily("21:00")`): one invocation
270
+ * for each record, admitted once. See `HandlerOptions` for where it starts, what it lets through
271
+ * and how many run at once.
272
+ */
273
+ on<T>(source: Subscribable<T>, handler: Handler<T>): void;
274
+ on<T>(source: Subscribable<T>, opts: HandlerOptions<NoInfer<T>>, handler: Handler<T>): void;
275
+ /**
276
+ * Subscriptions that grow from the journal, as `catalog` is for actions: read at every look for new
277
+ * work, each served like a handler of this plugin under its own id. An installed workflow is one.
278
+ */
279
+ subscribers(read: () => readonly Subscriber[]): void;
280
+ /**
281
+ * Declare a value of this plugin's state.
282
+ *
283
+ * The value belongs to the plugin and only the plugin writes it. Every change is a record, so
284
+ * who changed a value and why is visible without a separate history feature.
285
+ */
286
+ state<T>(name: string, schema: z.ZodType<T>, initial: T): StateHandle<T>;
287
+ /**
288
+ * A few counts of what this plugin holds now (runs by state, open requests), which
289
+ * `niwa.host.status` shows. Read when asked, from the journal or the state the plugin keeps.
290
+ */
291
+ summarize(read: () => Record<string, number>): void;
292
+ /**
293
+ * What this plugin needs the host to serve besides its own registrations: actions it calls and
294
+ * record types it writes or waits for, whoever declares them (`request.ask` of the requests
295
+ * plugin, `timer.fired` of the timers). The host refuses to serve when one is missing and says which
296
+ * plugin needs it. Actions are the ones plugins declare; an action a catalog reads from the journal
297
+ * cannot be needed. May be called more than once: the needs add up.
298
+ */
299
+ needs(needs: PluginNeeds): void;
300
+ /**
301
+ * The record type of this name, when this plugin or one installed before it declares it.
302
+ *
303
+ * For a plugin that is given a type by name: the plugin that declares the type is installed first.
304
+ */
305
+ recordType(name: string): RecordType<any> | undefined;
306
+ /**
307
+ * The journal, when the host is serving.
308
+ *
309
+ * A plugin that builds a read model of what the journal holds needs to read it. It is a
310
+ * function, not a value, because the journal opens when the host starts serving — after the
311
+ * plugin is installed. The answer is undefined before that, and after the host closes, and
312
+ * the plugin must say so rather than call an empty journal empty.
313
+ */
314
+ journal?: () => JournalReader | undefined;
315
+ /**
316
+ * Wait until a record is committed, or `ms` milliseconds have passed: for a read that blocks until
317
+ * something happens. The caller looks again after it; a commit may be a record it does not want.
318
+ */
319
+ untilCommit(ms: number): Promise<void>;
320
+ /**
321
+ * The path of the unix socket this host serves on, with the links of its home resolved: the name a
322
+ * sandbox that works by path matches, and where a process that talks to the host connects. The home
323
+ * exists once the host serves.
324
+ */
325
+ socket(): string;
326
+ /** The home of this host, with the links resolved: where `owner.token` and `host.key` are. */
327
+ home(): string;
328
+ /**
329
+ * The artifacts of this host: data too large for a record (`ARTIFACT_THRESHOLD`), kept whole by its
330
+ * digest and durable before the reference to it is returned. A record holds the reference.
331
+ */
332
+ readonly artifacts: ArtifactStore;
333
+ /** The secrets of the host's owner, resolved by name where they are used. A record holds `secret("name")`. */
334
+ readonly secrets: SecretStore;
335
+ /**
336
+ * Write a record of one of this plugin's own types, from work the plugin runs by itself.
337
+ *
338
+ * An action writes through its own `emit`. This is for what has no calling action — a sign of
339
+ * life that arrives from a harness long after the action that started it returned. Only a type
340
+ * the plugin declared is accepted; the runtime sets the actor (the host) and starts a chain of
341
+ * its own. It fails when the host is not serving.
342
+ *
343
+ * With an explicit id the write is idempotent: the same id with the same content returns the
344
+ * record that is already committed, and the same id with different content is an integrity
345
+ * error. That is what a fact that may arrive twice needs — an update from Telegram, say.
346
+ */
347
+ emit<T>(type: RecordType<T>, data: T, opts?: EmitOptions): Promise<StoredRecord>;
348
+ emitAll<const T extends readonly RecordType<any>[]>(entries: EmitBatch<T, EmitOptions>): Promise<StoredRecord[]>;
349
+ /**
350
+ * Make a token for a subject this plugin starts: a session or a run. Nothing else — the owner
351
+ * and the plugins are the host's to make. The token is the only time the secret is seen; the
352
+ * journal keeps its HMAC. `grant` is what the subject may do, as `narrow` computed it from the
353
+ * rights of `parent`, who started it.
354
+ */
355
+ issueToken(kind: "session" | "run", id: string, opts: { grant: Grant; parent: Caller }): Token;
356
+ /**
357
+ * The rights of a subject started at `caller`'s request: what `caller` has, narrowed to what was
358
+ * asked for, or the masks that were asked for and are not its own. A caller that nothing
359
+ * limits (the host, a plugin, a handler) is given what it asks.
360
+ */
361
+ narrow(caller: Caller, requested: readonly RuleSpec[]): Narrowed;
362
+ /**
363
+ * What `caller` may do: its grant, or `"unlimited"` when nothing limits it. A caller
364
+ * whose grant was closed, or that the emergency switch stopped, has a grant with no rules.
365
+ * Ask it with `match` from the grant of niwa to know whether a name may be called.
366
+ */
367
+ rights(caller: Caller): Grant | "unlimited";
368
+ /**
369
+ * The effect class of an action the host serves, by its name; undefined for a name nothing
370
+ * serves. What a plugin that narrows rules by itself needs: a mask never grants an
371
+ * irreversible action, so a narrowing is told which names are.
372
+ */
373
+ effectOf(name: string): Effect | undefined;
374
+ /**
375
+ * Hold `caller` to its grant for one `verb` on one `name`, as `decide()` does for a call: the
376
+ * decision of a subject a grant limits is recorded, and a refusal is a `DeniedError` that carries
377
+ * `{ grant, missing }`. A caller that nothing limits is let through. A plugin that acts for a
378
+ * subject of its own (a workflow run) asks it before each thing the subject does. A call that meets
379
+ * a rule that asks puts the question to the owner exactly as a call at the door does, with the
380
+ * `input` and the `reason` of the call; an emit or a read under such a rule is a denial.
381
+ */
382
+ authorize(caller: Caller, verb: Verb, name: string, how?: AuthorizeHow): Promise<void>;
383
+ /**
384
+ * A named grant with no holder, for what this plugin owns: the value the profile has until
385
+ * the owner sets one. It is read when a subject is born, so it may follow state that changes.
386
+ */
387
+ profile(name: string, rules: () => readonly RuleSpec[]): void;
388
+ /**
389
+ * Put the question of an `ask` rule to the owner: what the host calls when a call meets a
390
+ * rule that asks and no answer is in force. A host without one denies such a call.
391
+ */
392
+ asker(ask: Asker): void;
393
+ /**
394
+ * Set a profile this plugin declared with `profile`. The owner's own `access.profile.set`
395
+ * is not open to a plugin; this one is limited to what the plugin owns.
396
+ */
397
+ setProfile(name: string, rules: readonly RuleSpec[], by: Caller): Grant;
398
+ }
399
+
400
+ export interface Plugin {
401
+ kind: "plugin";
402
+ name: PluginName;
403
+ /** Explicit version or a hash of the setup function's source. */
404
+ version: PluginVersion;
405
+ setup(api: PluginApi): void;
406
+ /** Finishes the default version once the setup has run (`sealVersion`); absent when explicit. */
407
+ readonly [SEAL_VERSION]?: (handlers: readonly string[]) => void;
408
+ }
package/src/plugin.ts ADDED
@@ -0,0 +1,216 @@
1
+ // A plugin: the unit the host installs, replaces and unloads.
2
+ //
3
+ // A plugin owns its name, its version and its registrations. The version is
4
+ // what pins work in flight to the code that started it: when a plugin is
5
+ // replaced, the host keeps the handlers of the earlier version under
6
+ // `${handlerId}@${version}`, so an invocation admitted on one version finishes
7
+ // on that version and new records are handled by the new one.
8
+ //
9
+ // The version is derived from the code by default: the setup source and the source of every
10
+ // handler it registers, wherever the handler is defined. Changed code is a new version, the same
11
+ // code after a restart is the same version. A plugin whose behavior changes without that text
12
+ // changing passes an explicit version.
13
+
14
+ import { actionName, CannotRemoveHandler } from "@niwa-labs/core";
15
+ import type { HandlerOptions, OfferKey, Plugin, PluginApi } from "./plugin-types.ts";
16
+ import type { Subscribable } from "./trigger.ts";
17
+ import type { Handler, PluginName, PluginVersion, RecordType } from "@niwa-labs/core";
18
+
19
+ /** The name of the action that installs a plugin from a file. */
20
+ export const PLUGIN_INSTALL = actionName("plugin.install");
21
+ export const PLUGIN_UNINSTALL = actionName("plugin.uninstall");
22
+
23
+ /**
24
+ * Plugin names: lowercase words joined by dashes (`night-digest`), grouped by `/` (`rin/memory`).
25
+ *
26
+ * The group is what a grant's `@target` can name (`plugin.install@rin/*`). The name is everything
27
+ * before the last `/` of the handler id (`${pluginName}/${handlerName}`), so a handler name has no
28
+ * `/`, and the name must be stable: the handler id is written into the journal and read back by
29
+ * every later run.
30
+ */
31
+ const PLUGIN_NAME_PATTERN = /^[a-z][a-z0-9-]*(\/[a-z][a-z0-9-]*)*$/;
32
+
33
+ /**
34
+ * The name of a plugin. Constructed only here.
35
+ *
36
+ * @throws when the name cannot be part of a handler id.
37
+ */
38
+ export function pluginName(name: string): PluginName {
39
+ if (typeof name !== "string" || !PLUGIN_NAME_PATTERN.test(name)) {
40
+ throw new Error(
41
+ `plugin name "${String(name)}" must match ${PLUGIN_NAME_PATTERN.source}`,
42
+ );
43
+ }
44
+ return name as PluginName;
45
+ }
46
+
47
+ /**
48
+ * A point where plugins offer values that the plugin `reader` reads (`api.offer`, `api.offers`). Two keys
49
+ * of one name are one point: the offering plugin makes its own key and need not import the reader.
50
+ */
51
+ export function offerKey<T>(name: string, reader: string): OfferKey<T> {
52
+ if (name.length === 0) throw new Error("an offer key has a name");
53
+ return { kind: "offer", name, reader };
54
+ }
55
+
56
+ /**
57
+ * The version of a plugin. Constructed only here.
58
+ *
59
+ * The version is compared for equality and written into the journal, so it is
60
+ * an opaque non-empty string: `1.0.0`, `r3`, or the hash below.
61
+ *
62
+ * @throws when the version is empty.
63
+ */
64
+ export function pluginVersion(version: string): PluginVersion {
65
+ if (typeof version !== "string" || version.length === 0) {
66
+ throw new Error("plugin version must not be empty");
67
+ }
68
+ return version as PluginVersion;
69
+ }
70
+
71
+ /** A hash of the code, so a version depends only on the code, not on the process or the time. */
72
+ function hashOfCode(parts: readonly string[]): PluginVersion {
73
+ return pluginVersion(BigInt.asUintN(64, BigInt(Bun.hash(parts.join("\n\0\n")))).toString(16));
74
+ }
75
+
76
+ /**
77
+ * The text of a handler as the version sees it: its id and its source. A handler defined outside
78
+ * the setup function is not in the setup's text, so the host hands the handlers over when it runs
79
+ * the setup (`sealVersion`).
80
+ */
81
+ export function handlerSource(id: string, run: Handler<any>): string {
82
+ return `${id}\n${run.toString()}`;
83
+ }
84
+
85
+ /**
86
+ * The key of the method a plugin made by `plugin()` carries to finish its default version. It is
87
+ * a registry symbol, so the host finds it on a plugin built by another copy of this package.
88
+ */
89
+ export const SEAL_VERSION: unique symbol = Symbol.for("niwa.plugin.sealVersion") as never;
90
+
91
+ /**
92
+ * Finish the default version of a plugin once its setup has run: it then covers the handlers too.
93
+ *
94
+ * A plugin with an explicit version, or one that was not made by `plugin()`, keeps its version.
95
+ * Until the setup has run the version is the hash of the setup text alone.
96
+ */
97
+ export function sealVersion(source: Plugin, handlers: readonly string[]): void {
98
+ source[SEAL_VERSION]?.(handlers);
99
+ }
100
+
101
+ /**
102
+ * What a setup function may be: one that returns nothing. A function that returns a promise, or one
103
+ * that may (`void | Promise<void>`), is refused when the plugin is made, because the host runs the setup and goes on without waiting for
104
+ * it, so everything an asynchronous setup declared after its first `await` would be lost.
105
+ */
106
+ type SynchronousSetup<S extends (api: PluginApi) => unknown> =
107
+ [Extract<ReturnType<S>, PromiseLike<unknown>>] extends [never] ? unknown : never;
108
+
109
+ /** Did the setup return a promise (or any thenable)? */
110
+ function isThenable(value: unknown): boolean {
111
+ return (typeof value === "object" || typeof value === "function") && value !== null && typeof (value as { then?: unknown }).then === "function";
112
+ }
113
+
114
+ interface PluginOptions {
115
+ /**
116
+ * The explicit version of the plugin. Default: a hash of the setup code and of
117
+ * its handlers' code once the host has run the setup, so the same code always
118
+ * carries the same version and changed code carries a new one.
119
+ */
120
+ version?: string;
121
+ }
122
+
123
+ /**
124
+ * A plugin: a name, a version and a setup function that declares record types,
125
+ * actions and handlers through the api it receives.
126
+ *
127
+ * The setup function is not called here. The host calls it when the plugin is
128
+ * installed, so that a plugin can be created before the host exists and
129
+ * installed later.
130
+ *
131
+ * @throws when the name is not a valid plugin name, when the version is empty,
132
+ * or when there is no setup function.
133
+ */
134
+ export function plugin<S extends (api: PluginApi) => void>(
135
+ name: string,
136
+ setup: S & SynchronousSetup<S>,
137
+ opts?: PluginOptions,
138
+ ): Plugin {
139
+ if (typeof setup !== "function") {
140
+ throw new Error(`plugin "${String(name)}" needs a setup function`);
141
+ }
142
+ const explicit = opts?.version === undefined ? undefined : pluginVersion(opts.version);
143
+ let derived: PluginVersion | undefined;
144
+ return {
145
+ kind: "plugin",
146
+ name: pluginName(name),
147
+ get version() {
148
+ return explicit ?? derived ?? hashOfCode([setup.toString()]);
149
+ },
150
+ setup,
151
+ ...(explicit === undefined && {
152
+ [SEAL_VERSION]: (handlers: readonly string[]) => {
153
+ derived = hashOfCode([setup.toString(), ...handlers]);
154
+ },
155
+ }),
156
+ };
157
+ }
158
+
159
+ /**
160
+ * The plugin without one of its handlers: the same name, the same registrations, and a version
161
+ * of its own, so installing it replaces the plugin and work in flight finishes on the old one.
162
+ *
163
+ * The handler is named as the plugin names it, by the id it gives it (or the name of the type).
164
+ *
165
+ * @throws {CannotRemoveHandler} when the plugin declares no handler of that name, or when that is
166
+ * its only handler.
167
+ */
168
+ export function withoutHandler(source: Plugin, handler: string): Plugin {
169
+ return {
170
+ kind: "plugin",
171
+ name: source.name,
172
+ // Read when asked: the version of the source is final only once its setup has run, and it is
173
+ // the setup of this plugin that runs it (below).
174
+ get version() {
175
+ // The pair is hashed from its JSON text: whatever the handler is called, one pair has one text,
176
+ // so "a" then "b" never meets a single handler named "a-without-b", and the version stays the
177
+ // same length however many handlers were taken away one after another.
178
+ return hashOfCode([JSON.stringify([source.version, "without", handler])]);
179
+ },
180
+ setup(api) {
181
+ let removed = false;
182
+ let kept = 0;
183
+ const sources: string[] = [];
184
+ const on = (
185
+ type: Subscribable<any>,
186
+ optsOrHandler: HandlerOptions<any> | Handler<any>,
187
+ maybeHandler?: Handler<any>,
188
+ ): void => {
189
+ const [options, run]: [HandlerOptions<any>, Handler<any> | undefined] =
190
+ typeof optsOrHandler === "function" ? [{}, optsOrHandler] : [optsOrHandler, maybeHandler];
191
+ if (run === undefined) throw new TypeError(`a handler of "${type.name}" is missing`);
192
+ const name = options.id ?? type.name;
193
+ sources.push(handlerSource(name, run));
194
+ if (name === handler) {
195
+ removed = true;
196
+ return;
197
+ }
198
+ kept += 1;
199
+ api.on(type, options, run);
200
+ };
201
+ const returned: unknown = source.setup({ ...api, on });
202
+ if (isThenable(returned)) {
203
+ // What the promise does later is nobody's to see: it must not fail the process on its own.
204
+ Promise.resolve(returned).catch(() => undefined);
205
+ throw new TypeError(
206
+ `plugin "${source.name}" has an asynchronous setup: a setup runs to its end before the plugin is installed, so it must not return a promise`,
207
+ );
208
+ }
209
+ // The source's own version covers all its handlers, the removed one too: the same code has
210
+ // the same version whether it is installed whole or without a handler.
211
+ sealVersion(source, sources);
212
+ if (!removed) throw new CannotRemoveHandler(source.name, handler, "unknown");
213
+ if (kept === 0) throw new CannotRemoveHandler(source.name, handler, "last");
214
+ },
215
+ };
216
+ }
package/src/trigger.ts ADDED
@@ -0,0 +1,63 @@
1
+ /**
2
+ * A trigger: a record type with a filter on it, made once and handed to `api.on` — the firings of one
3
+ * timer, the messages to sessions.
4
+ *
5
+ * A trigger is not a record type: it is never declared, and it names the type it narrows. Its filter
6
+ * is equality on paths of the data, as every subscription's is. Two triggers of one type are two
7
+ * subscriptions, so each names the handler it makes. A trigger carries what its records need besides
8
+ * the subscription: the plugin that writes them, so a host without it says what to install, and an
9
+ * offer the subscribing plugin makes so that they are written at all (the schedule of a timer).
10
+ */
11
+
12
+ import type { PathFilter, RecordType } from "@niwa-labs/core";
13
+
14
+ import type { OfferKey } from "./plugin-types.ts";
15
+
16
+ /** What a plugin offers when it subscribes to a trigger: a value at a point another plugin reads. */
17
+ export interface TriggerOffer<V> {
18
+ readonly key: OfferKey<V>;
19
+ readonly value: V;
20
+ }
21
+
22
+ export interface Trigger<T> {
23
+ readonly kind: "trigger";
24
+ /** The record type the trigger narrows. */
25
+ readonly type: RecordType<T>;
26
+ /** Equality on paths of the data: the records of the type the trigger watches. */
27
+ readonly filter: PathFilter<T>;
28
+ /** The name a handler of the trigger gets when it does not name itself. */
29
+ readonly name: string;
30
+ /** The plugin that writes the records: named when no installed plugin declares the type. */
31
+ readonly provider?: string;
32
+ /** What a plugin that subscribes offers, so that the records are written: the host makes the offer for it. */
33
+ readonly offer?: TriggerOffer<any>;
34
+ }
35
+
36
+ /**
37
+ * A trigger over a type: the records whose data holds the filter, under a handler name of its own.
38
+ *
39
+ * The offer is checked here, as `api.offer` checks it: the value is what the key is the point of. The
40
+ * trigger keeps the pair it was given; the type that was checked is not carried further.
41
+ */
42
+ export function trigger<T, V = never>(
43
+ type: RecordType<T>,
44
+ spec: { readonly name: string; readonly filter: PathFilter<T>; readonly provider?: string; readonly offer?: { readonly key: OfferKey<V>; readonly value: NoInfer<V> } },
45
+ ): Trigger<T> {
46
+ if (spec.name.length === 0) throw new TypeError(`a trigger of "${type.name}" needs a name for its handlers`);
47
+ return {
48
+ kind: "trigger",
49
+ type,
50
+ filter: spec.filter,
51
+ name: spec.name,
52
+ ...(spec.provider === undefined ? {} : { provider: spec.provider }),
53
+ ...(spec.offer === undefined ? {} : { offer: spec.offer }),
54
+ };
55
+ }
56
+
57
+ /** What `api.on` takes: a record type, or a trigger over one. */
58
+ export type Subscribable<T> = RecordType<T> | Trigger<T>;
59
+
60
+ /** Is it a trigger, not a plain record type? */
61
+ export function isTrigger<T>(source: Subscribable<T>): source is Trigger<T> {
62
+ return source.kind === "trigger";
63
+ }
@@ -0,0 +1,50 @@
1
+ // The package entry: the authoring functions, the offer points, and the caller binding.
2
+
3
+ import { expect, test } from "bun:test";
4
+
5
+ import { BUILTIN_WORKFLOW, TIMER_OFFER, bindingOf, offerKey, plugin, pluginName, pluginVersion, withoutHandler } from "../src/index.ts";
6
+
7
+ test("plugin names are lowercase words joined by dashes and grouped by a slash", () => {
8
+ expect(pluginName("night-digest")).toBe("night-digest");
9
+ expect(pluginName("rin/memory")).toBe("rin/memory");
10
+ expect(() => pluginName("Night")).toThrow();
11
+ expect(() => pluginName("a//b")).toThrow();
12
+ });
13
+
14
+ test("a plugin version is a non-empty string", () => {
15
+ expect(pluginVersion("r3")).toBe("r3");
16
+ expect(() => pluginVersion("")).toThrow();
17
+ });
18
+
19
+ test("an offer key names its point and the plugin that reads it", () => {
20
+ expect(offerKey("x.y", "reader")).toEqual({ kind: "offer", name: "x.y", reader: "reader" });
21
+ expect(() => offerKey("", "reader")).toThrow();
22
+ expect(BUILTIN_WORKFLOW.reader).toBe("workflow");
23
+ expect(TIMER_OFFER.reader).toBe("timers");
24
+ });
25
+
26
+ test("the default binding makes a client speak as itself and the owner as the owner", () => {
27
+ const bind = bindingOf();
28
+ expect(bind({ kind: "host" } as never)).toBeUndefined();
29
+ expect(bind({ kind: "client", id: "c1" } as never)).toEqual({ kind: "client", id: "c1" });
30
+ expect(bind({ kind: "client", id: "c1", principal: { kind: "owner" } } as never)).toEqual({ kind: "owner" });
31
+ const custom = () => undefined;
32
+ expect(bindingOf({ bind: custom })).toBe(custom);
33
+ });
34
+
35
+ test("removing handlers one after another never meets removing one handler of a longer name", () => {
36
+ const source = plugin("two-steps", () => undefined, { version: "1" });
37
+ const stepwise = withoutHandler(withoutHandler(source, "a"), "b");
38
+ const single = withoutHandler(source, "a-without-b");
39
+ expect(stepwise.version).not.toBe(single.version);
40
+ expect(withoutHandler(withoutHandler(source, "b"), "a").version).not.toBe(stepwise.version);
41
+ expect(withoutHandler(source, "a").version).not.toBe(source.version);
42
+ });
43
+
44
+ test("the version of a plugin without handlers does not grow with the removals", () => {
45
+ const source = plugin("many-steps", () => undefined, { version: "1" });
46
+ let stepwise = source;
47
+ for (let index = 0; index < 18; index += 1) stepwise = withoutHandler(stepwise, `h${String(index)}`);
48
+ expect(stepwise.version.length).toBeLessThan(64);
49
+ expect(stepwise.version).not.toBe(withoutHandler(source, "h0").version);
50
+ });
@@ -0,0 +1,54 @@
1
+ // Code that a plugin author writes. A line ending in `// error` must not compile; every other line must.
2
+
3
+ import { record } from "@niwa-labs/core";
4
+ import type { RecordQuery } from "@niwa-labs/core";
5
+ import { z } from "zod";
6
+
7
+ import { offerKey, plugin, trigger as triggerOf, AGENT, TIMER_OFFER } from "../../src/index.ts";
8
+ import type { AgentOffer, PluginApi, Subscriber, TimerDef, TimerOffer, Trigger } from "../../src/index.ts";
9
+
10
+ plugin("typing-sync", (api) => {
11
+ api.declare();
12
+ });
13
+ plugin("typing-expression", (api) => api.declare());
14
+ plugin("typing-named", function setup(api: PluginApi) {
15
+ api.declare();
16
+ });
17
+ plugin("typing-async", async (api) => { // error
18
+ api.declare();
19
+ });
20
+ plugin("typing-promise", (api) => Promise.resolve(api.declare())); // error
21
+ plugin("typing-async-named", async function setup(api: PluginApi) { api.declare(); }); // error
22
+ plugin("typing-maybe-async", (api: PluginApi): void | Promise<void> => api.declare()); // error
23
+
24
+ export const every: TimerDef = { id: "a", every: 1000 };
25
+ export const at: TimerDef = { id: "a", at: 1000, missed: "skip" };
26
+ export const daily: TimerDef = { id: "a", daily: "04:00", description: "d" };
27
+ export const none: TimerDef = { id: "a" }; // error
28
+ export const two: TimerDef = { id: "a", every: 1000, daily: "04:00" }; // error
29
+ export const three: TimerDef = { id: "a", every: 1000, at: 1, daily: "04:00" }; // error
30
+
31
+ type Firing = Trigger<{ timer: string; due: number; at: number }>;
32
+ declare const trigger: Firing & { readonly timer: string; readonly def: TimerDef };
33
+ declare const unscheduled: Firing & { readonly timer: string };
34
+ export const plain: TimerOffer = { id: "a", every: 1000 };
35
+ export const carried: TimerOffer = trigger;
36
+ export const bare: TimerOffer = unscheduled; // error
37
+
38
+ const Ping = record("typing.ping", z.object({ who: z.string() }));
39
+ export const offered = triggerOf(Ping, { name: "ping", filter: {}, offer: { key: TIMER_OFFER, value: { id: "a", every: 1000 } } });
40
+ export const offerOfAnother = triggerOf(Ping, { name: "ping", filter: {}, offer: { key: TIMER_OFFER, value: 123 } }); // error
41
+ export const offerOfNone = triggerOf(Ping, { name: "ping", filter: {}, offer: { key: offerKey<string>("typing.point", "reader"), value: "x" } });
42
+ export const wrongOffer = triggerOf(Ping, { name: "ping", filter: {}, offer: { key: offerKey<string>("typing.point", "reader"), value: 1 } }); // error
43
+
44
+ plugin("typing-agents", (api) => {
45
+ api.offer(AGENT, { name: "a", harness: "h", prompt: "p" });
46
+ api.offer(AGENT, { name: "a", role: "r", prompt: "p" });
47
+ api.offer(AGENT, { name: "a", prompt: "p" }); // error
48
+ api.offer(AGENT, { name: "a", harness: "h", role: "r", prompt: "p" }); // error
49
+ });
50
+ export const anAgent: AgentOffer = { name: "a", role: "r", prompt: "p" };
51
+
52
+ declare const aQuery: RecordQuery;
53
+ export const byStream: Subscriber["queries"] = [{ types: ["a.*"], filter: { x: 1 }, stream: "s" }, aQuery];
54
+ export const placed: Subscriber["queries"] = [{ types: ["a.*"], from: 3 }]; // error
@@ -0,0 +1,32 @@
1
+ // What the types of the package refuse: the fixture marks every line that must not compile.
2
+
3
+ import { readFileSync } from "node:fs";
4
+ import { dirname, join } from "node:path";
5
+
6
+ import { expect, test } from "bun:test";
7
+ import ts from "typescript";
8
+
9
+ const ROOT = join(import.meta.dir, "../../..");
10
+ const FIXTURE = join(import.meta.dir, "fixtures/typing.ts");
11
+
12
+ /** The lines of the fixture the compiler refuses, as the compiler reports them. */
13
+ function refusedLines(): number[] {
14
+ const config = ts.readConfigFile(join(ROOT, "tsconfig.base.json"), ts.sys.readFile);
15
+ const parsed = ts.parseJsonConfigFileContent(config.config, ts.sys, ROOT);
16
+ const program = ts.createProgram([FIXTURE], { ...parsed.options, typeRoots: [join(ROOT, "node_modules/@types")] });
17
+ const source = program.getSourceFile(FIXTURE);
18
+ if (source === undefined) throw new Error("the fixture is not in the program");
19
+ const reported = [...program.getSyntacticDiagnostics(source), ...program.getSemanticDiagnostics(source)];
20
+ const lines = reported.map((diagnostic) => source.getLineAndCharacterOfPosition(diagnostic.start ?? 0).line + 1);
21
+ return [...new Set(lines)].sort((a, b) => a - b);
22
+ }
23
+
24
+ test("a setup that may return a promise, a timer with no schedule or two, an agent on both a harness and a role or on neither, a trigger with an offer of another type, an offered trigger without its definition, and a subscriber query literal with a position of its own do not compile", () => {
25
+ const marked = readFileSync(FIXTURE, "utf8")
26
+ .split("\n")
27
+ .flatMap((line, index) => (line.endsWith("// error") ? [index + 1] : []));
28
+ expect(marked.length).toBeGreaterThan(0);
29
+ const refused = refusedLines();
30
+ expect(refused).toEqual(marked);
31
+ expect(dirname(FIXTURE)).toContain("fixtures");
32
+ }, 60_000);
package/tsconfig.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "include": [
4
+ "src"
5
+ ]
6
+ }