@open-conduit/sdk 0.0.0-stage → 7.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 Alex Young
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,13 @@
1
- # Temporary Holding Version
1
+ # @open-conduit/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
+ Build an [Open Conduit](https://github.com/open-conduit/open-conduit) extension in TypeScript: serve protocol version 1 on stdin and stdout, call the host (KV, `event.accept`, `ingress.deliver`, secrets, artifacts, state reads), declare each operation, source, route and Work kind once, and unit-test it on an in-memory host (`@open-conduit/sdk/testing`) so the manifest is derived from the code.
4
+
5
+ The guide is [Writing an extension in TypeScript](https://open-conduit.github.io/open-conduit/architecture/extension-packaging/#writing-an-extension-in-typescript). [`protocol/examples/weather`](../../protocol/examples/weather) is a complete package that `make certify` certifies.
6
+
7
+ ```sh
8
+ npm ci
9
+ npm run typecheck
10
+ npm test
11
+ ```
12
+
13
+ Node 22.18 or later. The tests run the TypeScript sources directly with Node's type stripping.
@@ -0,0 +1,99 @@
1
+ /** The protocol's own error codes (protocol/protocol.go). */
2
+ export declare const Code: {
3
+ UnsupportedVersion: string;
4
+ MethodNotFound: string;
5
+ Invalid: string;
6
+ Unsupported: string;
7
+ Unauthorized: string;
8
+ Undeclared: string;
9
+ NotFound: string;
10
+ Conflict: string;
11
+ CausalLimit: string;
12
+ NotAdoptable: string;
13
+ NotAccepting: string;
14
+ NothingToAttach: string;
15
+ NotLive: string;
16
+ ResourceSetup: string;
17
+ ResourceNotFound: string;
18
+ ResourceExhausted: string;
19
+ SandboxDenied: string;
20
+ SandboxUnavailable: string;
21
+ ContainerRunning: string;
22
+ ContainerUnconfirmed: string;
23
+ SiteUnavailable: string;
24
+ NoCapacity: string;
25
+ RetryAfter: string;
26
+ Reentrant: string;
27
+ Overloaded: string;
28
+ Cancelled: string;
29
+ ShuttingDown: string;
30
+ Internal: string;
31
+ Schema: string;
32
+ KVDowngrade: string;
33
+ };
34
+ /** Reports whether code is one of the protocol's own codes. */
35
+ export declare function isProtocolCode(code: string): boolean;
36
+ /**
37
+ * An authored protocol error: one of the protocol's own codes. The host
38
+ * refuses with these (not_found from kv.get is never thrown; conflict from
39
+ * kv.commit is), and an extension may throw one to refuse a host request.
40
+ */
41
+ export declare class ProtocolError extends Error {
42
+ readonly code: string;
43
+ /** The message as it crossed the wire. */
44
+ readonly detail: string;
45
+ readonly resetAt: string | undefined;
46
+ /** A config refusal's diagnostics (ConfigError), as they crossed. */
47
+ readonly diagnostics: ConfigDiagnostic[];
48
+ constructor(code: string, detail?: string, resetAt?: string, diagnostics?: ConfigDiagnostic[]);
49
+ }
50
+ /**
51
+ * One thing wrong with a config object (extension.ConfigDiagnostic): the
52
+ * JSON pointer of the field within the object ("/jobs/1/cron", "" for the
53
+ * object itself), a stable snake_case code and a message saying what is
54
+ * wrong and what is allowed. The host shows it to the operator, so the
55
+ * message must never quote a configured value.
56
+ */
57
+ export interface ConfigDiagnostic {
58
+ path: string;
59
+ code: string;
60
+ message: string;
61
+ }
62
+ /**
63
+ * A refusal of a config object that says why: throw one from an entry
64
+ * type's validate hook and the host reports each diagnostic at its field's
65
+ * full path. Anything else thrown is reported only as invalid.
66
+ */
67
+ export declare class ConfigError extends Error {
68
+ readonly diagnostics: ConfigDiagnostic[];
69
+ constructor(diagnostics: ConfigDiagnostic[]);
70
+ constructor(path: string, code: string, message: string);
71
+ }
72
+ /** The JSON pointer of a path of object keys and array indexes. */
73
+ export declare function pointer(...parts: (string | number)[]): string;
74
+ /**
75
+ * An operation's refusal, which reaches the calling agent verbatim: a code
76
+ * of the extension's own ([a-z][a-z0-9_]*) and a message the agent reads.
77
+ * Throw one from an operation handler; anything else thrown is "internal".
78
+ */
79
+ export declare class OperationError extends Error {
80
+ readonly code: string;
81
+ constructor(code: string, message: string);
82
+ }
83
+ /** The error a request answered after its caller cancelled it. */
84
+ export declare class CancelledError extends Error {
85
+ constructor();
86
+ }
87
+ /** The connection to the host closed (it exited, or the stream broke). */
88
+ export declare class TransportError extends Error {
89
+ constructor(reason?: string);
90
+ }
91
+ /** Decode returns the error for an authored error received from the host. */
92
+ export declare function decode(code: string, message: string, resetAt?: string, diagnostics?: ConfigDiagnostic[]): Error;
93
+ /** The code and message an error crosses the wire with. */
94
+ export declare function encode(err: unknown): {
95
+ code: string;
96
+ message: string;
97
+ resetAt?: string;
98
+ diagnostics?: ConfigDiagnostic[];
99
+ };
package/dist/errors.js ADDED
@@ -0,0 +1,143 @@
1
+ // Errors that cross the wire, as protocol/errors.go defines them: an
2
+ // authored error is a stable code and a short, secret-free message, sent as
3
+ // JSON-RPC code -32000 with data.code. Anything else crosses as "internal"
4
+ // with no detail, which stays in the sender's own log (stderr).
5
+ /** The protocol's own error codes (protocol/protocol.go). */
6
+ export const Code = {
7
+ UnsupportedVersion: "unsupported_protocol_version",
8
+ MethodNotFound: "method_not_found",
9
+ Invalid: "invalid",
10
+ Unsupported: "unsupported",
11
+ Unauthorized: "unauthorized",
12
+ Undeclared: "undeclared",
13
+ NotFound: "not_found",
14
+ Conflict: "conflict",
15
+ CausalLimit: "causal_limit",
16
+ NotAdoptable: "not_adoptable",
17
+ NotAccepting: "not_accepting",
18
+ NothingToAttach: "nothing_to_attach",
19
+ NotLive: "not_live",
20
+ ResourceSetup: "resource_setup_failed",
21
+ ResourceNotFound: "resource_not_found",
22
+ ResourceExhausted: "resource_exhausted",
23
+ SandboxDenied: "sandbox_denied",
24
+ SandboxUnavailable: "sandbox_unavailable",
25
+ ContainerRunning: "container_running",
26
+ ContainerUnconfirmed: "container_unconfirmed",
27
+ SiteUnavailable: "site_unavailable",
28
+ NoCapacity: "no_capacity",
29
+ RetryAfter: "retry_after",
30
+ Reentrant: "reentrant_call",
31
+ Overloaded: "overloaded",
32
+ Cancelled: "cancelled",
33
+ ShuttingDown: "shutting_down",
34
+ Internal: "internal",
35
+ Schema: "unreadable_schema",
36
+ KVDowngrade: "kv_downgrade",
37
+ };
38
+ const known = new Set(Object.values(Code));
39
+ /** Reports whether code is one of the protocol's own codes. */
40
+ export function isProtocolCode(code) {
41
+ return known.has(code);
42
+ }
43
+ /**
44
+ * An authored protocol error: one of the protocol's own codes. The host
45
+ * refuses with these (not_found from kv.get is never thrown; conflict from
46
+ * kv.commit is), and an extension may throw one to refuse a host request.
47
+ */
48
+ export class ProtocolError extends Error {
49
+ code;
50
+ /** The message as it crossed the wire. */
51
+ detail;
52
+ resetAt;
53
+ /** A config refusal's diagnostics (ConfigError), as they crossed. */
54
+ diagnostics;
55
+ constructor(code, detail = "", resetAt, diagnostics = []) {
56
+ super(detail === "" ? `protocol: ${code}` : `protocol: ${code}: ${detail}`);
57
+ this.name = "ProtocolError";
58
+ this.code = code;
59
+ this.detail = detail;
60
+ this.resetAt = resetAt;
61
+ this.diagnostics = diagnostics;
62
+ }
63
+ }
64
+ /**
65
+ * A refusal of a config object that says why: throw one from an entry
66
+ * type's validate hook and the host reports each diagnostic at its field's
67
+ * full path. Anything else thrown is reported only as invalid.
68
+ */
69
+ export class ConfigError extends Error {
70
+ diagnostics;
71
+ constructor(first, code, message) {
72
+ const diagnostics = typeof first === "string"
73
+ ? [{ path: first, code: code ?? "", message: message ?? "" }]
74
+ : first;
75
+ super("invalid config: " +
76
+ diagnostics
77
+ .map((d) => `${d.path || "config"}: ${d.code}: ${d.message}`)
78
+ .join("; "));
79
+ this.name = "ConfigError";
80
+ this.diagnostics = diagnostics;
81
+ }
82
+ }
83
+ /** The JSON pointer of a path of object keys and array indexes. */
84
+ export function pointer(...parts) {
85
+ return parts
86
+ .map((p) => "/" + String(p).replaceAll("~", "~0").replaceAll("/", "~1"))
87
+ .join("");
88
+ }
89
+ /**
90
+ * An operation's refusal, which reaches the calling agent verbatim: a code
91
+ * of the extension's own ([a-z][a-z0-9_]*) and a message the agent reads.
92
+ * Throw one from an operation handler; anything else thrown is "internal".
93
+ */
94
+ export class OperationError extends Error {
95
+ code;
96
+ constructor(code, message) {
97
+ super(message);
98
+ this.name = "OperationError";
99
+ this.code = code;
100
+ }
101
+ }
102
+ /** The error a request answered after its caller cancelled it. */
103
+ export class CancelledError extends Error {
104
+ constructor() {
105
+ super("request cancelled");
106
+ this.name = "CancelledError";
107
+ }
108
+ }
109
+ /** The connection to the host closed (it exited, or the stream broke). */
110
+ export class TransportError extends Error {
111
+ constructor(reason = "transport closed") {
112
+ super(`protocol: ${reason}`);
113
+ this.name = "TransportError";
114
+ }
115
+ }
116
+ /** Decode returns the error for an authored error received from the host. */
117
+ export function decode(code, message, resetAt, diagnostics = []) {
118
+ return isProtocolCode(code)
119
+ ? new ProtocolError(code, message, resetAt, code === Code.Invalid ? diagnostics : [])
120
+ : new OperationError(code, message);
121
+ }
122
+ /** The code and message an error crosses the wire with. */
123
+ export function encode(err) {
124
+ if (err instanceof ConfigError && err.diagnostics.length > 0)
125
+ return {
126
+ code: Code.Invalid,
127
+ message: "invalid config",
128
+ diagnostics: err.diagnostics,
129
+ };
130
+ if (err instanceof ProtocolError) {
131
+ const message = err.detail === "" ? err.code : err.detail;
132
+ return err.resetAt === undefined
133
+ ? { code: err.code, message }
134
+ : { code: err.code, message, resetAt: err.resetAt };
135
+ }
136
+ if (err instanceof OperationError)
137
+ return { code: err.code, message: err.message };
138
+ if (err instanceof CancelledError ||
139
+ (err instanceof Error && err.name === "AbortError")) {
140
+ return { code: Code.Cancelled, message: "request cancelled" };
141
+ }
142
+ return { code: Code.Internal, message: "internal error" };
143
+ }
@@ -0,0 +1,360 @@
1
+ import { type Readable, Writable } from "node:stream";
2
+ import { type DeliveryInput, Host, type Put } from "./host.js";
3
+ import { type Infer, type Type } from "./schema.js";
4
+ import { type AcceptedEvent, type Authority, type CertificationFile, type ConfigEntry, type ConnectionEntry, type Dependency, type Emitted, type Event, type Family, type Manifest, type PushResult, type Route, type RouteDecision, type RouteInput, type RouteSample, RouteSamplesParams, type Scan, type Scope, type Snapshot, type TaskRunResult, type WaitRequest } from "./wire.js";
5
+ /** The protocol versions this SDK speaks. */
6
+ export declare const ProtocolVersions: number[];
7
+ /** What a handler can reach besides its input. */
8
+ export interface Context {
9
+ host: Host;
10
+ /** Aborts when the host cancels the request. */
11
+ signal: AbortSignal;
12
+ }
13
+ export interface CallContext extends Context {
14
+ /** The scope, Work and grant the call runs under. */
15
+ authority: Authority;
16
+ /** The caller's idempotency key: a retried call carries the same one. */
17
+ requestId: string;
18
+ }
19
+ export interface OperationSpec<S extends Type<unknown>, Out> {
20
+ /** The input's schema (t.object({}) for none); the handler receives what it accepts. */
21
+ input: S;
22
+ /** What the operation does, in one line (at most 200 bytes). */
23
+ summary?: string;
24
+ /** When an agent should call the operation, in Markdown. */
25
+ guidance?: string;
26
+ /**
27
+ * What a call does in a person's words, for whoever is asked to approve
28
+ * it: a phrase that follows "wants to", with {field} for a top-level
29
+ * input value (e.g. "deploy {service} to {env}"; one line, at most 200
30
+ * bytes).
31
+ */
32
+ wants?: string;
33
+ /** A capability the operation answers, routed by name (e.g. "git.credential"). */
34
+ serves?: string;
35
+ /** The payload schema the output is sent as (default "<operation>.v1"). */
36
+ output?: string;
37
+ /** Returns the output's data, or throws OperationError to refuse. */
38
+ handler: (input: Infer<S>, ctx: CallContext) => Out | Promise<Out>;
39
+ }
40
+ /** The fields every kind of operation declares. */
41
+ interface OperationDoc<S extends Type<unknown>> {
42
+ /** The input's schema (t.object({}) for none); the handler receives what it accepts. */
43
+ input: S;
44
+ /** What the operation does, in one line (at most 200 bytes). */
45
+ summary?: string;
46
+ /** When an agent should call the operation, in Markdown. */
47
+ guidance?: string;
48
+ /** What a call does in a person's words, as for OperationSpec.wants. */
49
+ wants?: string;
50
+ /** The payload schema the output is sent as (default "<operation>.v1"). */
51
+ output?: string;
52
+ }
53
+ /** What a wait operation's handler returns: what the Work waits for, and what the caller is told. */
54
+ export interface WaitOut {
55
+ /** The Events (and time) that end the wait; keys left out mean every key the Work owns. */
56
+ wait: WaitRequest;
57
+ /** Events on keys the Work doesn't own (another Work's, or one no Work owns yet) to alias into it. */
58
+ dependencies?: Dependency[];
59
+ /** The output's data, returned to the caller as the operation's output. */
60
+ output?: unknown;
61
+ }
62
+ export interface WaitSpec<S extends Type<unknown>> extends OperationDoc<S> {
63
+ /** Turns a call into a wait the host parks the Work on; throws OperationError to refuse. */
64
+ handler: (input: Infer<S>, ctx: CallContext) => WaitOut | Promise<WaitOut>;
65
+ }
66
+ /** What an emission's commit writes and returns. It must be pure and deterministic: the host may run it again. */
67
+ export interface CommitOut {
68
+ /** KV writes in the extension's own namespaces, committed with the Event. */
69
+ records?: Put[];
70
+ /** The output's data, returned to the caller. */
71
+ output?: unknown;
72
+ }
73
+ /** What an emit operation's handler returns: the one Event to emit, of a family the extension declares. */
74
+ export interface EmitOut {
75
+ event: Event;
76
+ /** An accepted Event in the source's namespace the emission derives from, instead of the attempt's trigger. */
77
+ cause?: string;
78
+ /** The emission's identity across executions: at most one Event is accepted per scope and once. */
79
+ once?: string;
80
+ /** Runs in the accepting transaction once the Event is accepted (declare the operation with commit: true). */
81
+ commit?: (emitted: Emitted) => CommitOut;
82
+ }
83
+ export interface EmitSpec<S extends Type<unknown>> extends OperationDoc<S> {
84
+ /** The handler's plans may carry a commit that writes records with the Event. */
85
+ commit?: boolean;
86
+ /** Turns a call into the Event to emit; throws OperationError to refuse. */
87
+ handler: (input: Infer<S>, ctx: CallContext) => EmitOut | Promise<EmitOut>;
88
+ }
89
+ /** One scope's entry of an entry type, with its config decoded. */
90
+ export interface EntryOf<C> {
91
+ scopeId: string;
92
+ name: string;
93
+ config: C;
94
+ /** The secret names the entry may resolve with host.secrets. */
95
+ secrets: string[];
96
+ connection?: ConnectionEntry;
97
+ }
98
+ export interface EntryTypeSpec<S extends Type<unknown>> {
99
+ /** The entry's config schema. A config it refuses is invalid before the daemon applies it. */
100
+ config: S;
101
+ /**
102
+ * Checks the schema can't express; throw to refuse the config. Throw a
103
+ * ConfigError to say which field is wrong and why: the host reports
104
+ * each of its diagnostics at the field's full path. Anything else
105
+ * thrown is reported only as invalid.
106
+ */
107
+ validate?: (config: Infer<S>) => void | Promise<void>;
108
+ /** Receives every entry of the type on each configuration generation. */
109
+ configure?: (entries: EntryOf<Infer<S>>[], ctx: Context) => void | Promise<void>;
110
+ }
111
+ /** A source an ingress entry registers, with whatever the extension keeps for it. */
112
+ export interface SourceSpec<D = unknown> {
113
+ /** Its registration name: the extension's name, or that and "/" and more (as "<name>/<scope>/<entry>"). */
114
+ name: string;
115
+ /** Its correlation keys' source: the extension's name, or that and "/" and more. */
116
+ namespace: string;
117
+ scopeId: string;
118
+ /** How often the host reconciles it, in whole seconds (at least one). */
119
+ intervalSeconds: number;
120
+ /** Serve the type's webhook for it at /<name> (default: whenever the type has one). */
121
+ webhook?: boolean;
122
+ /** What the handlers need for it: a client, its settings. */
123
+ data?: D;
124
+ }
125
+ /** A delivery the host pushes to a source, with its body as bytes. */
126
+ export interface PushDelivery {
127
+ id: string;
128
+ receivedAt: string;
129
+ contentType?: string;
130
+ body: Uint8Array;
131
+ }
132
+ /** One HTTP request on a source's webhook path. */
133
+ export interface WebhookRequest {
134
+ path: string;
135
+ method: string;
136
+ query: string;
137
+ headers: Headers;
138
+ body: Uint8Array;
139
+ /** When the delivery was first received, by the listener or a forwarder in front of it. */
140
+ receivedAt: string;
141
+ /** The forwarder's delivery ID, when one is configured ("" otherwise). */
142
+ forwardId: string;
143
+ }
144
+ export interface WebhookResponse {
145
+ /** Default 200. A 2xx tells the sender its delivery is durably accepted. */
146
+ status?: number;
147
+ headers?: Record<string, string | string[]>;
148
+ body?: Uint8Array | string;
149
+ }
150
+ export interface WebhookContext extends Context {
151
+ /**
152
+ * Hands a verified delivery to this source: the host calls push with it
153
+ * and answers once its Events are durably accepted. receivedAt defaults
154
+ * to the request's.
155
+ */
156
+ deliver: (delivery: DeliveryInput) => Promise<{
157
+ accepted: AcceptedEvent[];
158
+ added: boolean[];
159
+ }>;
160
+ }
161
+ export interface IngressTypeSpec<S extends Type<unknown>, D> {
162
+ /** The entry's config schema, as for entryType. */
163
+ config: S;
164
+ /** Checks the schema can't express, as for entryType. */
165
+ validate?: (config: Infer<S>) => void | Promise<void>;
166
+ /** The families its sources observe (declared in the manifest, at least one). */
167
+ families: [Family, ...Family[]];
168
+ /** Each configuration generation: the sources the type's entries register. */
169
+ sources: (entries: EntryOf<Infer<S>>[], ctx: Context) => SourceSpec<D>[] | Promise<SourceSpec<D>[]>;
170
+ /** Maps a delivery to observations (and events of families that aren't re-derivable). */
171
+ push?: (source: SourceSpec<D>, delivery: PushDelivery, ctx: Context) => PushResult | Promise<PushResult>;
172
+ /**
173
+ * Reads one page of what the source holds now. Without it every scan is
174
+ * an empty partial page, which never says anything is gone.
175
+ */
176
+ reconcile?: (source: SourceSpec<D>, scan: Scan, ctx: Context) => Snapshot | Promise<Snapshot>;
177
+ /**
178
+ * Serves a request on a source's webhook path: verify it (the vendor's
179
+ * own signature), then ctx.deliver it before answering.
180
+ */
181
+ webhook?: (source: SourceSpec<D>, request: WebhookRequest, ctx: WebhookContext) => WebhookResponse | Promise<WebhookResponse>;
182
+ /** The largest webhook body the host reads, in bytes (default 1 MiB). */
183
+ webhookMaxBytes?: number;
184
+ }
185
+ /** A route's call: the Event, its scope, the Work it already reaches, the route, and the route's config decoded. */
186
+ export interface RouteCall<C> extends RouteInput {
187
+ config: C;
188
+ }
189
+ export interface SampleCall<C> {
190
+ scope: Scope;
191
+ route: Route;
192
+ /** The host's clock, for samples whose data carries a time. */
193
+ now: string;
194
+ config: C;
195
+ }
196
+ export interface RouteSpec<S extends Type<unknown>> {
197
+ /** The route config's schema; checked before the daemon applies a config. */
198
+ config?: S;
199
+ /** Decides what an Event does: open Work, reach the Work it has, or nothing. No side effects. */
200
+ match: (call: RouteCall<Infer<S>>, ctx: Context) => RouteDecision | Promise<RouteDecision>;
201
+ /**
202
+ * Sample Events for a route trace, built from the route's and scope's
203
+ * config so they trace as written; IDs are stable. No side effects.
204
+ */
205
+ samples?: (call: SampleCall<Infer<S>>, ctx: Context) => RouteSample[] | Promise<RouteSample[]>;
206
+ }
207
+ export interface WorkKindSpec {
208
+ /** Its Work stays open across triggers. */
209
+ standing?: boolean;
210
+ /** Its Work runs on a clock: a dry run starts none of it. */
211
+ timed?: boolean;
212
+ /** Its Work does all its work in one attempt: a handoff completes it. */
213
+ runOnce?: boolean;
214
+ /** Picks, from a Work's pending inputs, the index of the one that triggers its next execution. */
215
+ trigger?: (inputs: Event[]) => number;
216
+ }
217
+ export interface CheckContext extends Context {
218
+ deep: boolean;
219
+ /** The read-only view of the configuration (protocol.CheckConfig). */
220
+ config: unknown;
221
+ }
222
+ /** A check returns its detail line, and throws to fail with the error's message as detail. */
223
+ export type CheckFn = (ctx: CheckContext) => string | Promise<string>;
224
+ /**
225
+ * A task may return when it next has something to do and what wakes it
226
+ * sooner (at most an hour off); returning nothing keeps its interval.
227
+ */
228
+ export type TaskFn = (ctx: Context) => void | TaskRunResult | Promise<void | TaskRunResult>;
229
+ export type MigrateFn = (from: number, to: number, ctx: Context) => void | Promise<void>;
230
+ export interface Options {
231
+ /** The extension's own version (required). */
232
+ version: string;
233
+ /** The display name operators read (default: the name). */
234
+ title?: string;
235
+ summary?: string;
236
+ /** The package's command (default ["<name>-extension"]). */
237
+ command?: string[];
238
+ /** Host services beyond the extension's own surfaces it uses. */
239
+ permissions?: string[];
240
+ /** The layout version of the extension's own KV namespaces. */
241
+ kvVersion?: number;
242
+ /** A directory of playbooks, relative to the package's manifest, the host offers agents. */
243
+ playbooks?: string;
244
+ }
245
+ type Kind = "handler" | "wait" | "emit";
246
+ interface Op {
247
+ kind: Kind;
248
+ run: (data: unknown, ctx: CallContext) => Promise<unknown>;
249
+ }
250
+ /** A registered source, with the handlers of its type. */
251
+ interface Registered {
252
+ spec: SourceSpec<unknown>;
253
+ type: IngressHandlers;
254
+ }
255
+ interface IngressHandlers {
256
+ push?: (s: SourceSpec<unknown>, d: PushDelivery, ctx: Context) => PushResult | Promise<PushResult>;
257
+ reconcile?: (s: SourceSpec<unknown>, scan: Scan, ctx: Context) => Snapshot | Promise<Snapshot>;
258
+ webhook?: (s: SourceSpec<unknown>, r: WebhookRequest, ctx: WebhookContext) => WebhookResponse | Promise<WebhookResponse>;
259
+ }
260
+ interface EntryType {
261
+ /** Throws ConfigError (or a bare refusal) for a config it refuses. */
262
+ validate: (config: unknown) => Promise<void>;
263
+ /** An ingress type returns the sources its entries register. */
264
+ configure: (entries: ConfigEntry[], ctx: Context) => Promise<Registered[]>;
265
+ }
266
+ interface RouteHandler {
267
+ validate: (config: unknown) => Promise<void>;
268
+ match: (input: RouteInput, ctx: Context) => Promise<RouteDecision>;
269
+ samples: (p: RouteSamplesParams, ctx: Context) => Promise<RouteSample[]>;
270
+ }
271
+ /** Starts an extension named name whose manifest its registrations fill in. */
272
+ export declare function extension(name: string, o: Options): Extension;
273
+ export declare class Extension {
274
+ #private;
275
+ readonly manifest: Manifest;
276
+ constructor(name: string, o: Options);
277
+ /** Registers a request/response toolbelt operation and declares it. */
278
+ operation<S extends Type<unknown>, Out>(name: string, spec: OperationSpec<S, Out>): this;
279
+ /**
280
+ * Registers an operation that suspends the calling Work until an Event
281
+ * (or a time) comes, and declares it with kind wait: "wait until this
282
+ * ticket is resolved".
283
+ */
284
+ wait<S extends Type<unknown>>(name: string, spec: WaitSpec<S>): this;
285
+ /**
286
+ * Registers an operation that emits one Event of a family the extension
287
+ * declares, and declares it with kind emit (and commit, when spec.commit).
288
+ */
289
+ emit<S extends Type<unknown>>(name: string, spec: EmitSpec<S>): this;
290
+ /** Declares a scope entry type: an "extensions" entry in a scope's config. */
291
+ entryType<S extends Type<unknown>>(type: string, spec: EntryTypeSpec<S>): this;
292
+ /**
293
+ * Declares a scope entry type whose entries own event sources, with the
294
+ * families they observe. Each configuration generation, sources names
295
+ * the sources the entries register; the host then reconciles each every
296
+ * intervalSeconds through reconcile, pushes deliveries to it through
297
+ * push, and sends requests on its webhook path (/<source name>) to
298
+ * webhook.
299
+ */
300
+ ingressType<S extends Type<unknown>, D>(type: string, spec: IngressTypeSpec<S, D>): this;
301
+ /**
302
+ * Registers a route handler and declares it: what an Event does (open
303
+ * Work, reach the Work it already has, or nothing). A spec with samples
304
+ * is declared as offering them, so route traces and the routes.decisions
305
+ * certification apply; one with config has its routes' config checked.
306
+ */
307
+ route<S extends Type<unknown> = Type<Record<string, unknown>>>(handler: string, spec: RouteSpec<S>): this;
308
+ /** Declares a kind of Work the extension's routes create, with its lifecycle. */
309
+ workKind(kind: string, spec?: WorkKindSpec): this;
310
+ /** Registers a doctor check and declares it. */
311
+ check(name: string, fn: CheckFn, o?: {
312
+ deep?: boolean;
313
+ }): this;
314
+ /** Registers a task the host runs every intervalSeconds (at least one) and declares it. */
315
+ task(name: string, intervalSeconds: number, fn: TaskFn): this;
316
+ /** Declares event families the extension derives through host.accept or emits (an ingress type's come with it). */
317
+ family(...families: Family[]): this;
318
+ /**
319
+ * Declares a payload schema the extension writes and reads, named
320
+ * <extension>.<thing> and written as <name>.v<N>: the versions it can
321
+ * read, ascending, the highest being the one it writes. The host refuses
322
+ * an Event (ingress, event.accept or emitted) whose data names any other.
323
+ */
324
+ schema(name: string, ...versions: number[]): this;
325
+ /** Upgrades the extension's KV namespaces to kvVersion. It must be idempotent: a crash mid-way retries it. */
326
+ onMigrate(fn: MigrateFn): this;
327
+ /** Sets the package's certification.json content (package-certification). */
328
+ certification(file: CertificationFile): this;
329
+ /** Serves the extension on input and output (tests pass a pair of in-memory streams). */
330
+ serve(input: Readable, output: Writable): Server;
331
+ /**
332
+ * The entry point of a packaged extension: `package-manifest` prints the
333
+ * manifest, `package-certification` the certification file, and anything
334
+ * else serves on stdin and stdout until stdin closes, then exits.
335
+ */
336
+ main(argv?: string[]): Promise<void>;
337
+ /** @internal */
338
+ _served(): {
339
+ operations: Map<string, Op>;
340
+ checks: Map<string, CheckFn>;
341
+ tasks: Map<string, TaskFn>;
342
+ entryTypes: Map<string, EntryType>;
343
+ routes: Map<string, RouteHandler>;
344
+ triggers: Map<string, (inputs: Event[]) => number>;
345
+ migrate: MigrateFn | undefined;
346
+ };
347
+ }
348
+ /** One served connection. */
349
+ export declare class Server {
350
+ #private;
351
+ readonly host: Host;
352
+ constructor(ext: Extension, input: Readable, output: Writable);
353
+ /** Resolves when the connection ends. */
354
+ get done(): Promise<void>;
355
+ /** The private state directory the host gave at initialize. */
356
+ get stateDir(): string;
357
+ /** Ends the connection. */
358
+ close(): void;
359
+ }
360
+ export {};