@open-conduit/sdk 0.0.0-stage → 7.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/dist/actions.d.ts +145 -0
  4. package/dist/actions.js +281 -0
  5. package/dist/actiontest.d.ts +80 -0
  6. package/dist/actiontest.js +190 -0
  7. package/dist/artifactstore.d.ts +133 -0
  8. package/dist/artifactstore.js +364 -0
  9. package/dist/backup.d.ts +99 -0
  10. package/dist/backup.js +178 -0
  11. package/dist/containertest.d.ts +71 -0
  12. package/dist/containertest.js +294 -0
  13. package/dist/errors.d.ts +127 -0
  14. package/dist/errors.js +180 -0
  15. package/dist/executor.d.ts +374 -0
  16. package/dist/executor.js +556 -0
  17. package/dist/executortest.d.ts +183 -0
  18. package/dist/executortest.js +534 -0
  19. package/dist/extension.d.ts +855 -0
  20. package/dist/extension.js +1822 -0
  21. package/dist/feed.d.ts +20 -0
  22. package/dist/feed.js +88 -0
  23. package/dist/forward.d.ts +38 -0
  24. package/dist/forward.js +163 -0
  25. package/dist/forwardca.d.ts +21 -0
  26. package/dist/forwardca.js +144 -0
  27. package/dist/hooks.d.ts +108 -0
  28. package/dist/hooks.js +13 -0
  29. package/dist/host.d.ts +295 -0
  30. package/dist/host.js +486 -0
  31. package/dist/index.d.ts +34 -0
  32. package/dist/index.js +31 -0
  33. package/dist/jsonrpc.d.ts +39 -0
  34. package/dist/jsonrpc.js +350 -0
  35. package/dist/probe.d.ts +61 -0
  36. package/dist/probe.js +92 -0
  37. package/dist/providertest.d.ts +59 -0
  38. package/dist/providertest.js +168 -0
  39. package/dist/resources.d.ts +208 -0
  40. package/dist/resources.js +303 -0
  41. package/dist/sandbox.d.ts +84 -0
  42. package/dist/sandbox.js +85 -0
  43. package/dist/schema.d.ts +71 -0
  44. package/dist/schema.js +252 -0
  45. package/dist/setup.d.ts +145 -0
  46. package/dist/setup.js +179 -0
  47. package/dist/setuptest.d.ts +90 -0
  48. package/dist/setuptest.js +319 -0
  49. package/dist/storetest.d.ts +64 -0
  50. package/dist/storetest.js +740 -0
  51. package/dist/telemetry.d.ts +86 -0
  52. package/dist/telemetry.js +46 -0
  53. package/dist/testing.d.ts +756 -0
  54. package/dist/testing.js +2165 -0
  55. package/dist/toolbelt.d.ts +91 -0
  56. package/dist/toolbelt.js +216 -0
  57. package/dist/tunnel.d.ts +62 -0
  58. package/dist/tunnel.js +93 -0
  59. package/dist/wire.d.ts +5359 -0
  60. package/dist/wire.js +2211 -0
  61. package/package.json +29 -4
@@ -0,0 +1,91 @@
1
+ import type { ExecutionContext, Payload } from "./wire.js";
2
+ /** The Wait a parking call registered (client.Wait). */
3
+ export interface ToolWait {
4
+ id: string;
5
+ work_id?: string;
6
+ execution_id?: string;
7
+ state?: string;
8
+ /** What the Wait is for, in its owner's words. */
9
+ description?: string;
10
+ due_at?: string;
11
+ [field: string]: unknown;
12
+ }
13
+ /** One toolbelt call's answer (client.ToolResult): what the operation returns, and the wait when it parked the run. */
14
+ export interface ToolResult {
15
+ event?: Record<string, unknown>;
16
+ work?: Record<string, unknown>;
17
+ wait?: ToolWait;
18
+ context?: Payload;
19
+ output?: Payload;
20
+ }
21
+ /** The toolbelt refused a call: the host's status, code and message. */
22
+ export declare class ToolbeltError extends Error {
23
+ readonly status: number;
24
+ readonly code: string;
25
+ constructor(status: number, code: string, message: string);
26
+ }
27
+ /** A call after the turn ended, which never reached the host. */
28
+ export declare class TurnEnded extends Error {
29
+ readonly by: string;
30
+ constructor(by: string, operation: string);
31
+ }
32
+ /** How a turn ended: the operation that ended it, and the wait it parked on. */
33
+ export interface TurnEnd {
34
+ /** The operation whose result ended the turn. */
35
+ operation: string;
36
+ /** "wait" when a call parked the run, "declare_outcome" when one declared the outcome. */
37
+ by: "wait" | "declare_outcome";
38
+ wait?: ToolWait;
39
+ /** The wait's description, or the declared summary. */
40
+ summary: string;
41
+ }
42
+ export interface ToolbeltOptions {
43
+ /** unix:///absolute/path or https://host[:port][/path]. */
44
+ endpoint: string;
45
+ /** The bearer token; tokenFile is read at each call instead when set, since the host rotates it. */
46
+ token?: string;
47
+ tokenFile?: string;
48
+ }
49
+ export interface CallOptions {
50
+ /** The idempotency key: the host replays a request ID within one execution rather than running it again. */
51
+ requestId?: string;
52
+ signal?: AbortSignal;
53
+ }
54
+ /** The toolbelt of an attempt, from its execution context, or undefined when it has none. */
55
+ export declare function toolbelt(c: ExecutionContext): Toolbelt | undefined;
56
+ /** One turn's toolbelt. */
57
+ export declare class Toolbelt {
58
+ #private;
59
+ constructor(o: ToolbeltOptions);
60
+ /** How the turn ended, once a call parked the run or declared its outcome. */
61
+ get ended(): TurnEnd | undefined;
62
+ /**
63
+ * Calls an operation with its wire input: a builtin's own (wait's
64
+ * { description, types, ... }), an extension operation's { data }. Once
65
+ * the turn has ended it throws TurnEnded without calling.
66
+ */
67
+ call(operation: string, input: unknown, o?: CallOptions): Promise<ToolResult>;
68
+ /** Calls an extension's operation with data as its input's data. */
69
+ operation(name: string, data: unknown, o?: CallOptions): Promise<ToolResult>;
70
+ /** The Work's context and the run's inputs (read_context). */
71
+ readContext(o?: CallOptions): Promise<Payload | undefined>;
72
+ /** Parks the run until an Event of types (on the Work's keys) or the timeout comes, ending the turn. */
73
+ wait(w: {
74
+ description?: string;
75
+ types?: string[];
76
+ timeout?: string;
77
+ [field: string]: unknown;
78
+ }, o?: CallOptions): Promise<ToolResult>;
79
+ /** Declares the attempt's outcome, ending the turn. */
80
+ declareOutcome(kind: "completed" | "failed" | "handoff", summary: string, o?: CallOptions): Promise<ToolResult>;
81
+ /** What the token is granted: guidance, operation docs and every granted name (client.ToolbeltGuide). */
82
+ guide(signal?: AbortSignal): Promise<{
83
+ guidance: string[];
84
+ operations: {
85
+ name: string;
86
+ summary?: string;
87
+ input?: unknown;
88
+ }[];
89
+ granted: string[];
90
+ }>;
91
+ }
@@ -0,0 +1,216 @@
1
+ // The execution toolbelt, as an attempt's process reaches it: the host's
2
+ // API at the execution context's toolbelt endpoint (unix:///path, or
3
+ // https://host[:port][/path]), under its toolbelt token. It is not the
4
+ // extension protocol: this is what `os` and client.ToolbeltCall speak.
5
+ //
6
+ // One Toolbelt is one turn. A call whose result carries a wait has parked
7
+ // the run (the core wait, or any operation that parks it, such as a
8
+ // package's wait operation): the host has released the run's authority,
9
+ // so the turn is over, and every later call is refused here without
10
+ // reaching the host, as the chat-completions executor ends its turn. A
11
+ // declared outcome ends it too.
12
+ import { readFile } from "node:fs/promises";
13
+ import { request as httpRequest } from "node:http";
14
+ import { request as httpsRequest } from "node:https";
15
+ /** The toolbelt refused a call: the host's status, code and message. */
16
+ export class ToolbeltError extends Error {
17
+ status;
18
+ code;
19
+ constructor(status, code, message) {
20
+ super(`toolbelt: ${status} ${code}: ${message}`);
21
+ this.name = "ToolbeltError";
22
+ this.status = status;
23
+ this.code = code;
24
+ }
25
+ }
26
+ /** A call after the turn ended, which never reached the host. */
27
+ export class TurnEnded extends Error {
28
+ by;
29
+ constructor(by, operation) {
30
+ super(`toolbelt: not run: the turn ended with ${by} (${operation})`);
31
+ this.name = "TurnEnded";
32
+ this.by = by;
33
+ }
34
+ }
35
+ const builtins = new Set([
36
+ "read_context",
37
+ "emit",
38
+ "wait",
39
+ "declare_outcome",
40
+ "create_work",
41
+ "cancel_work",
42
+ ]);
43
+ /** The toolbelt of an attempt, from its execution context, or undefined when it has none. */
44
+ export function toolbelt(c) {
45
+ if (!c.toolbelt_endpoint || !(c.toolbelt_token || c.toolbelt_token_file))
46
+ return undefined;
47
+ return new Toolbelt({
48
+ endpoint: c.toolbelt_endpoint,
49
+ ...(c.toolbelt_token ? { token: c.toolbelt_token } : {}),
50
+ ...(c.toolbelt_token_file ? { tokenFile: c.toolbelt_token_file } : {}),
51
+ });
52
+ }
53
+ /** One turn's toolbelt. */
54
+ export class Toolbelt {
55
+ #o;
56
+ #base;
57
+ #socket;
58
+ #ended;
59
+ constructor(o) {
60
+ if (!o.token && !o.tokenFile)
61
+ throw new Error("toolbelt: no token");
62
+ this.#o = o;
63
+ if (o.endpoint.startsWith("unix://")) {
64
+ const path = o.endpoint.slice("unix://".length);
65
+ if (!path.startsWith("/"))
66
+ throw new Error("toolbelt: endpoint must be unix:///absolute/path");
67
+ this.#socket = path;
68
+ this.#base = new URL("http://localhost/v1/");
69
+ }
70
+ else {
71
+ const u = new URL(o.endpoint);
72
+ if (u.protocol !== "https:" || u.search || u.hash || u.username)
73
+ throw new Error("toolbelt: endpoint must be unix:///absolute/path or https://host[:port][/path]");
74
+ u.pathname = `${u.pathname.replace(/\/+$/, "")}/v1/`;
75
+ this.#base = u;
76
+ }
77
+ }
78
+ /** How the turn ended, once a call parked the run or declared its outcome. */
79
+ get ended() {
80
+ return this.#ended;
81
+ }
82
+ /**
83
+ * Calls an operation with its wire input: a builtin's own (wait's
84
+ * { description, types, ... }), an extension operation's { data }. Once
85
+ * the turn has ended it throws TurnEnded without calling.
86
+ */
87
+ async call(operation, input, o = {}) {
88
+ if (this.#ended !== undefined)
89
+ throw new TurnEnded(this.#ended.by, this.#ended.operation);
90
+ const out = (await this.#request("POST", "toolbelt/call", {
91
+ operation,
92
+ ...(input === undefined ? {} : { input }),
93
+ ...(o.requestId ? { request_id: o.requestId } : {}),
94
+ }, o.signal));
95
+ const result = out ?? {};
96
+ if (result.wait !== undefined && result.wait !== null) {
97
+ this.#ended = {
98
+ operation,
99
+ by: operation === "declare_outcome" ? "declare_outcome" : "wait",
100
+ wait: result.wait,
101
+ summary: result.wait.description ?? "",
102
+ };
103
+ }
104
+ else if (operation === "declare_outcome") {
105
+ const summary = input?.summary;
106
+ this.#ended = {
107
+ operation,
108
+ by: "declare_outcome",
109
+ summary: typeof summary === "string" ? summary : "",
110
+ };
111
+ }
112
+ return result;
113
+ }
114
+ /** Calls an extension's operation with data as its input's data. */
115
+ operation(name, data, o) {
116
+ if (builtins.has(name))
117
+ throw new Error(`toolbelt: ${name} is a builtin: use call`);
118
+ return this.call(name, { data: data ?? {} }, o);
119
+ }
120
+ /** The Work's context and the run's inputs (read_context). */
121
+ async readContext(o) {
122
+ return (await this.call("read_context", {}, o)).context;
123
+ }
124
+ /** Parks the run until an Event of types (on the Work's keys) or the timeout comes, ending the turn. */
125
+ wait(w, o) {
126
+ return this.call("wait", w, o);
127
+ }
128
+ /** Declares the attempt's outcome, ending the turn. */
129
+ declareOutcome(kind, summary, o) {
130
+ return this.call("declare_outcome", { kind, summary }, o);
131
+ }
132
+ /** What the token is granted: guidance, operation docs and every granted name (client.ToolbeltGuide). */
133
+ async guide(signal) {
134
+ const g = (await this.#request("GET", "toolbelt/guidance", undefined, signal));
135
+ return {
136
+ guidance: Array.isArray(g?.guidance) ? g.guidance : [],
137
+ operations: Array.isArray(g?.operations)
138
+ ? g.operations
139
+ : [],
140
+ granted: Array.isArray(g?.granted) ? g.granted : [],
141
+ };
142
+ }
143
+ async #token() {
144
+ if (this.#o.tokenFile) {
145
+ // As client.ReadTokenFile reads it: the daemon's {"token_id", "token"}, or the bare token.
146
+ const raw = (await readFile(this.#o.tokenFile, "utf8")).trim();
147
+ if (raw.startsWith("{")) {
148
+ let token;
149
+ try {
150
+ token = JSON.parse(raw).token;
151
+ }
152
+ catch {
153
+ token = undefined;
154
+ }
155
+ if (typeof token !== "string" || token === "")
156
+ throw new Error("toolbelt: the token file is malformed");
157
+ return token;
158
+ }
159
+ if (raw === "" || /\s/.test(raw))
160
+ throw new Error("toolbelt: the token file is malformed");
161
+ return raw;
162
+ }
163
+ return this.#o.token;
164
+ }
165
+ async #request(method, path, body, signal) {
166
+ const token = await this.#token();
167
+ const u = new URL(path, this.#base);
168
+ const payload = body === undefined ? undefined : JSON.stringify(body);
169
+ const headers = {
170
+ Authorization: `Bearer ${token}`,
171
+ };
172
+ if (payload !== undefined)
173
+ headers["Content-Type"] = "application/json";
174
+ const { status, text } = await new Promise((resolve, reject) => {
175
+ const send = u.protocol === "https:" ? httpsRequest : httpRequest;
176
+ const req = send(u, {
177
+ method,
178
+ headers,
179
+ ...(this.#socket ? { socketPath: this.#socket } : {}),
180
+ ...(signal ? { signal } : {}),
181
+ }, (res) => {
182
+ const chunks = [];
183
+ let size = 0;
184
+ res.on("data", (c) => {
185
+ size += c.length;
186
+ if (size > 64 << 20) {
187
+ req.destroy(new Error("toolbelt: answer too large"));
188
+ return;
189
+ }
190
+ chunks.push(c);
191
+ });
192
+ res.on("end", () => resolve({
193
+ status: res.statusCode ?? 0,
194
+ text: Buffer.concat(chunks).toString("utf8"),
195
+ }));
196
+ res.on("error", reject);
197
+ });
198
+ req.on("error", reject);
199
+ req.end(payload);
200
+ });
201
+ let env;
202
+ try {
203
+ env = text === "" ? {} : JSON.parse(text);
204
+ }
205
+ catch {
206
+ env = {};
207
+ }
208
+ if (status >= 400) {
209
+ const e = env.error;
210
+ if (!e?.code)
211
+ throw new ToolbeltError(status, "http_error", `status ${status}`);
212
+ throw new ToolbeltError(status, e.code, e.message ?? "");
213
+ }
214
+ return env.data ?? null;
215
+ }
216
+ }
@@ -0,0 +1,62 @@
1
+ import type { Context } from "./extension.js";
2
+ import { type Infer, type Type } from "./schema.js";
3
+ import { type FieldDecl } from "./wire.js";
4
+ /** One run of a tunnel (extension.TunnelRun). */
5
+ export interface TunnelRunRequest<C> {
6
+ type: string;
7
+ /** The webhook listener's local address (host:port): forward to it and nothing else. */
8
+ addr: string;
9
+ /** The operator's tunnel config (settings.webhooks.tunnel.config), decoded by the provider's schema. */
10
+ config: C;
11
+ }
12
+ /**
13
+ * Reports the tunnel's public URL as it changes, and "" while it is down.
14
+ * Calls reach the host one at a time, in order; the host refuses a URL
15
+ * checkPublicURL refuses, and the promise resolves either way.
16
+ */
17
+ export type PublishFn = (url: string) => Promise<void>;
18
+ /**
19
+ * A tunnel config the provider can't run with (extension.ErrTunnelConfig):
20
+ * the host doesn't start the run again until the config changes. Its
21
+ * message is what the operator reads, so it never quotes the config.
22
+ */
23
+ export declare class TunnelConfigError extends Error {
24
+ constructor(message: string);
25
+ }
26
+ /**
27
+ * Whether u can be where webhooks point (extension.CheckPublicURL): an
28
+ * http(s) URL with a host and no credentials. The host takes no other.
29
+ */
30
+ export declare function checkPublicURL(u: string): boolean;
31
+ /**
32
+ * A tunnel provider type (extension.TunnelProvider), which
33
+ * settings.webhooks.tunnel names: it exposes the host's webhook listener
34
+ * at a public URL.
35
+ *
36
+ * run keeps the tunnel to r.addr up until ctx.signal aborts, publishing
37
+ * each public URL as it changes and "" while the tunnel is down, then
38
+ * returns. Throw when the tunnel can't be kept up: the host publishes no
39
+ * URL, records the failure and starts run again after a growing wait,
40
+ * except after a TunnelConfigError. Returning before the signal aborts is
41
+ * the tunnel going down too.
42
+ */
43
+ export interface TunnelProviderSpec<S extends Type<unknown>> {
44
+ /** The tunnel config's schema: validate (kind tunnel) refuses a config it doesn't match. */
45
+ config?: S;
46
+ /** The tunnel config's fields, for adapters and the config editor (manifest tunnels[].fields). */
47
+ fields?: FieldDecl[];
48
+ /**
49
+ * Checks the schema can't express; throw to refuse the config. A
50
+ * ConfigError says which field is wrong and why; anything else thrown is
51
+ * reported only as invalid.
52
+ */
53
+ validate?: (config: Infer<S>) => void | Promise<void>;
54
+ run: (r: TunnelRunRequest<Infer<S>>, publish: PublishFn, ctx: Context) => void | Promise<void>;
55
+ }
56
+ /** @internal */
57
+ export interface TunnelHandler {
58
+ validate: (config: unknown) => Promise<void>;
59
+ run: (raw: unknown, ctx: Context) => Promise<unknown>;
60
+ }
61
+ /** @internal */
62
+ export declare function tunnelHandler<S extends Type<unknown>>(type: string, spec: TunnelProviderSpec<S>, params: <T extends Type<unknown>>(schema: T, raw: unknown) => Infer<T>): TunnelHandler;
package/dist/tunnel.js ADDED
@@ -0,0 +1,93 @@
1
+ // Tunnel providers: tunnel.run and validate (kind tunnel), as protocol/sdk
2
+ // serves sdk.Extension.Tunnels (protocol/sdk/surfaces.go). The host owns
3
+ // its webhook listener and decides what it serves; a tunnel provider
4
+ // exposes that listener's address at a public URL for as long as the host
5
+ // holds tunnel.run open, reporting each URL through tunnel.url, and stops
6
+ // when the host cancels the call.
7
+ import { Code, ConfigError, ProtocolError } from "./errors.js";
8
+ import { diagnose, matches, t } from "./schema.js";
9
+ import { TunnelRunParams } from "./wire.js";
10
+ /**
11
+ * A tunnel config the provider can't run with (extension.ErrTunnelConfig):
12
+ * the host doesn't start the run again until the config changes. Its
13
+ * message is what the operator reads, so it never quotes the config.
14
+ */
15
+ export class TunnelConfigError extends Error {
16
+ constructor(message) {
17
+ super(message);
18
+ this.name = "TunnelConfigError";
19
+ }
20
+ }
21
+ /**
22
+ * Whether u can be where webhooks point (extension.CheckPublicURL): an
23
+ * http(s) URL with a host and no credentials. The host takes no other.
24
+ */
25
+ export function checkPublicURL(u) {
26
+ let p;
27
+ try {
28
+ p = new URL(u);
29
+ }
30
+ catch {
31
+ return false;
32
+ }
33
+ return ((p.protocol === "https:" || p.protocol === "http:") &&
34
+ p.host !== "" &&
35
+ p.username === "" &&
36
+ p.password === "");
37
+ }
38
+ /** @internal */
39
+ export function tunnelHandler(type, spec, params) {
40
+ const schema = spec.config;
41
+ return {
42
+ validate: async (raw) => {
43
+ const c = raw ?? {};
44
+ if (schema !== undefined && !matches(schema, c)) {
45
+ const diagnostics = diagnose(schema, c);
46
+ if (diagnostics.length > 0)
47
+ throw new ConfigError(diagnostics);
48
+ throw new ProtocolError(Code.Invalid, "invalid tunnel config");
49
+ }
50
+ try {
51
+ await spec.validate?.(c);
52
+ }
53
+ catch (err) {
54
+ if (err instanceof ConfigError)
55
+ throw err;
56
+ throw new ProtocolError(Code.Invalid, "invalid tunnel config");
57
+ }
58
+ },
59
+ run: async (raw, ctx) => {
60
+ const p = params(TunnelRunParams, raw);
61
+ const c = p.config.data ?? {};
62
+ // A config that no longer matches (a package upgrade changed the
63
+ // schema) can't run until the operator changes it.
64
+ if (schema !== undefined && !matches(schema, c))
65
+ throw new ProtocolError(Code.Invalid, "the tunnel config doesn't match the provider's");
66
+ // One tunnel.url at a time, each answered before the next, so the
67
+ // host sees the URLs in the order the provider published them.
68
+ let last = Promise.resolve();
69
+ const publish = (url) => {
70
+ last = last.then(async () => {
71
+ try {
72
+ await ctx.host.call("tunnel.url", { run: p.run, url }, t.any(), ctx.signal);
73
+ }
74
+ catch (err) {
75
+ if (!ctx.signal.aborted)
76
+ process.stderr.write(`open-conduit sdk: tunnel ${type}: the host refused a URL: ${err instanceof Error ? err.message : String(err)}\n`);
77
+ }
78
+ });
79
+ return last;
80
+ };
81
+ try {
82
+ await spec.run({ type, addr: p.addr, config: c }, publish, ctx);
83
+ }
84
+ catch (err) {
85
+ if (err instanceof TunnelConfigError)
86
+ throw new ProtocolError(Code.Invalid, err.message);
87
+ throw err;
88
+ }
89
+ await last;
90
+ return {};
91
+ },
92
+ };
93
+ }