@gutilab/sdk 0.0.0-stage → 0.10.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,414 @@
1
+ /**
2
+ * The SDK to write the agents of an orchestrator, in TypeScript. You define nodes, with their inputs, outputs and
3
+ * parameters as Zod schemas; the SDK declares them, keeps the agent connected, and runs the Steps the
4
+ * orchestrator assigns to it.
5
+ *
6
+ * Install it in the project of the agent, together with `zod` 4, at the version of your orchestrator. It runs
7
+ * under Node 24 or 26, from 24.11.0, where Node starts an agent written in TypeScript without a build step.
8
+ *
9
+ * ```sh
10
+ * npm install @gutilab/sdk@<version of your orchestrator> zod
11
+ * ```
12
+ *
13
+ * The API has two functions and one error class: `defineNode` defines a node, `runAgent` runs the agent, and
14
+ * `AgentError` carries each refusal with its code. An agent is a list of nodes, in `src/nodes.ts`:
15
+ *
16
+ * ```ts
17
+ * import { defineNode } from '@gutilab/sdk';
18
+ * import { z } from 'zod';
19
+ *
20
+ * export const ocr = defineNode({
21
+ * identifier: 'acme.ocr',
22
+ * version: '1.0.0',
23
+ * inputs: { file: z.string() },
24
+ * outputs: { text: z.string(), lang: z.string().optional() },
25
+ * parameters: { lang: z.enum(['fr', 'en']).default('fr') },
26
+ * async run({ inputs, parameters, signal, log }) {
27
+ * log.info(`Reading ${inputs.file} in ${parameters.lang}`);
28
+ * const response = await fetch(inputs.file, { signal });
29
+ * if (!response.ok) {
30
+ * throw new Error(`Cannot read ${inputs.file}: HTTP ${response.status}`);
31
+ * }
32
+ * return { text: await response.text(), lang: parameters.lang };
33
+ * },
34
+ * });
35
+ *
36
+ * // The nodes of this agent: `gutilab-sdk dev` and `gutilab-sdk validate` read this list, and `main.ts` runs it.
37
+ * export const nodes = [ocr];
38
+ * ```
39
+ *
40
+ * and the file that runs them, `src/main.ts`, started by `node src/main.ts`:
41
+ *
42
+ * ```ts
43
+ * import { runAgent } from '@gutilab/sdk';
44
+ * import { nodes } from './nodes.ts';
45
+ *
46
+ * const stop = new AbortController();
47
+ * process.once('SIGTERM', () => {
48
+ * stop.abort();
49
+ * });
50
+ *
51
+ * await runAgent({
52
+ * url: process.env.ORCHESTRATOR_URL ?? '',
53
+ * auth: { kind: 'agent', token: process.env.AGENT_TOKEN ?? '' },
54
+ * nodes,
55
+ * signal: stop.signal,
56
+ * });
57
+ * ```
58
+ *
59
+ * The command of the SDK writes these two files in a new project, then runs its nodes as a development agent,
60
+ * which declares them again each time a file changes. It reads a developer token from `DEVELOPER_TOKEN`:
61
+ *
62
+ * ```sh
63
+ * npx @gutilab/sdk@<version of your orchestrator> init my-agent
64
+ * cd my-agent
65
+ * npm install
66
+ * export DEVELOPER_TOKEN=<your developer token>
67
+ * npx --no gutilab-sdk dev --url wss://<host>/agents --environment <id of a development environment>
68
+ * ```
69
+ *
70
+ * In that project, `npx --no gutilab-sdk validate` checks the node definitions without connecting. `--no` keeps npx
71
+ * from downloading anything: outside a project where the SDK is installed, the command stops instead.
72
+ *
73
+ * @packageDocumentation
74
+ */
75
+ import { z } from "zod";
76
+ /**
77
+ * A refusal by the SDK or by the orchestrator, or the reason why a Step was interrupted (`signal.reason`). Its
78
+ * `code`, stable and in snake_case, says which one; `details`, when present, gives more information: the issues
79
+ * of a refused node definition, for example.
80
+ *
81
+ * @example
82
+ * ```ts @import.meta.vitest
83
+ * const error = new AgentError('invalid_token', 'The token is unknown, revoked or expired.');
84
+ * expect(error.code).toBe('invalid_token');
85
+ * ```
86
+ */
87
+ export declare class AgentError extends Error {
88
+ /** The stable code of the refusal, in snake_case: `invalid_token` or `invalid_node_definition`, for example. */
89
+ readonly code: string;
90
+ /** More information about the refusal, when there is some: the issues of a refused node definition, for example. */
91
+ readonly details?: unknown;
92
+ /**
93
+ * @param code The stable code of the refusal, in snake_case.
94
+ * @param message What a person reads: one line per issue, for a refused definition.
95
+ * @param details More information about the refusal, when there is some.
96
+ */
97
+ constructor(code: string, message: string, details?: unknown);
98
+ }
99
+ /**
100
+ * A node type declared by an agent: its identifier, its version, the timeout of a Step, 600,000 ms by default,
101
+ * its data ports and the schema of its parameters. Inputs and outputs share one namespace: a reserved name
102
+ * (`in`, `out`, `onFailure`, `error`) or a duplicate one, at its second occurrence, gives a custom issue at the
103
+ * path of its name, whose `params.fault` is `reserved_port_name` or `duplicate_port_name`.
104
+ *
105
+ * @example
106
+ * ```ts @import.meta.vitest
107
+ * const ocr = NodeType.parse({
108
+ * identifier: 'acme.ocr',
109
+ * version: '1.0.0',
110
+ * inputs: [{ name: 'file', type: { name: 'string' }, required: true }],
111
+ * outputs: [],
112
+ * parameterSchema: { type: 'object', properties: {}, additionalProperties: false },
113
+ * });
114
+ * expect(ocr.timeoutMs).toBe(600_000);
115
+ * ```
116
+ */
117
+ declare const NodeType: z.ZodObject<{
118
+ identifier: z.ZodString;
119
+ version: z.ZodString;
120
+ timeoutMs: z.ZodDefault<z.ZodInt>;
121
+ inputs: z.ZodArray<z.ZodObject<{
122
+ name: z.ZodString;
123
+ type: z.ZodDiscriminatedUnion<[z.ZodObject<{
124
+ name: z.ZodLiteral<"string">;
125
+ }, z.core.$strict>, z.ZodObject<{
126
+ name: z.ZodLiteral<"integer">;
127
+ }, z.core.$strict>, z.ZodObject<{
128
+ name: z.ZodLiteral<"float">;
129
+ }, z.core.$strict>, z.ZodObject<{
130
+ name: z.ZodLiteral<"boolean">;
131
+ }, z.core.$strict>, z.ZodObject<{
132
+ name: z.ZodLiteral<"json">;
133
+ }, z.core.$strict>, z.ZodObject<{
134
+ name: z.ZodLiteral<"enum">;
135
+ values: z.ZodArray<z.ZodString>;
136
+ }, z.core.$strict>, z.ZodObject<{
137
+ name: z.ZodLiteral<"array">;
138
+ items: z.ZodDiscriminatedUnion<readonly [z.ZodObject<{
139
+ name: z.ZodLiteral<"string">;
140
+ }, z.core.$strict>, z.ZodObject<{
141
+ name: z.ZodLiteral<"integer">;
142
+ }, z.core.$strict>, z.ZodObject<{
143
+ name: z.ZodLiteral<"float">;
144
+ }, z.core.$strict>, z.ZodObject<{
145
+ name: z.ZodLiteral<"boolean">;
146
+ }, z.core.$strict>, z.ZodObject<{
147
+ name: z.ZodLiteral<"json">;
148
+ }, z.core.$strict>, z.ZodObject<{
149
+ name: z.ZodLiteral<"enum">;
150
+ values: z.ZodArray<z.ZodString>;
151
+ }, z.core.$strict>], "name">;
152
+ }, z.core.$strict>], "name">;
153
+ required: z.ZodBoolean;
154
+ }, z.core.$strict>>;
155
+ outputs: z.ZodArray<z.ZodObject<{
156
+ name: z.ZodString;
157
+ type: z.ZodDiscriminatedUnion<[z.ZodObject<{
158
+ name: z.ZodLiteral<"string">;
159
+ }, z.core.$strict>, z.ZodObject<{
160
+ name: z.ZodLiteral<"integer">;
161
+ }, z.core.$strict>, z.ZodObject<{
162
+ name: z.ZodLiteral<"float">;
163
+ }, z.core.$strict>, z.ZodObject<{
164
+ name: z.ZodLiteral<"boolean">;
165
+ }, z.core.$strict>, z.ZodObject<{
166
+ name: z.ZodLiteral<"json">;
167
+ }, z.core.$strict>, z.ZodObject<{
168
+ name: z.ZodLiteral<"enum">;
169
+ values: z.ZodArray<z.ZodString>;
170
+ }, z.core.$strict>, z.ZodObject<{
171
+ name: z.ZodLiteral<"array">;
172
+ items: z.ZodDiscriminatedUnion<readonly [z.ZodObject<{
173
+ name: z.ZodLiteral<"string">;
174
+ }, z.core.$strict>, z.ZodObject<{
175
+ name: z.ZodLiteral<"integer">;
176
+ }, z.core.$strict>, z.ZodObject<{
177
+ name: z.ZodLiteral<"float">;
178
+ }, z.core.$strict>, z.ZodObject<{
179
+ name: z.ZodLiteral<"boolean">;
180
+ }, z.core.$strict>, z.ZodObject<{
181
+ name: z.ZodLiteral<"json">;
182
+ }, z.core.$strict>, z.ZodObject<{
183
+ name: z.ZodLiteral<"enum">;
184
+ values: z.ZodArray<z.ZodString>;
185
+ }, z.core.$strict>], "name">;
186
+ }, z.core.$strict>], "name">;
187
+ required: z.ZodBoolean;
188
+ }, z.core.$strict>>;
189
+ parameterSchema: z.ZodObject<{
190
+ $schema: z.ZodOptional<z.ZodLiteral<"https://json-schema.org/draft/2020-12/schema">>;
191
+ type: z.ZodLiteral<"object">;
192
+ properties: z.ZodPipe<z.ZodUnknown, z.ZodRecord<z.ZodString, z.ZodDiscriminatedUnion<[z.ZodObject<{
193
+ title: z.ZodOptional<z.ZodString>;
194
+ description: z.ZodOptional<z.ZodString>;
195
+ default: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnknown, z.ZodJSONSchema>, z.ZodTransform<unknown, z.core.util.JSONType>>>;
196
+ type: z.ZodLiteral<"string">;
197
+ enum: z.ZodOptional<z.ZodArray<z.ZodString>>;
198
+ minLength: z.ZodOptional<z.ZodInt>;
199
+ maxLength: z.ZodOptional<z.ZodInt>;
200
+ }, z.core.$strict>, z.ZodObject<{
201
+ title: z.ZodOptional<z.ZodString>;
202
+ description: z.ZodOptional<z.ZodString>;
203
+ default: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnknown, z.ZodJSONSchema>, z.ZodTransform<unknown, z.core.util.JSONType>>>;
204
+ type: z.ZodEnum<{
205
+ number: "number";
206
+ integer: "integer";
207
+ }>;
208
+ minimum: z.ZodOptional<z.ZodNumber>;
209
+ maximum: z.ZodOptional<z.ZodNumber>;
210
+ exclusiveMinimum: z.ZodOptional<z.ZodNumber>;
211
+ exclusiveMaximum: z.ZodOptional<z.ZodNumber>;
212
+ }, z.core.$strict>, z.ZodObject<{
213
+ title: z.ZodOptional<z.ZodString>;
214
+ description: z.ZodOptional<z.ZodString>;
215
+ default: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnknown, z.ZodJSONSchema>, z.ZodTransform<unknown, z.core.util.JSONType>>>;
216
+ type: z.ZodLiteral<"boolean">;
217
+ }, z.core.$strict>, z.ZodObject<{
218
+ title: z.ZodOptional<z.ZodString>;
219
+ description: z.ZodOptional<z.ZodString>;
220
+ default: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnknown, z.ZodJSONSchema>, z.ZodTransform<unknown, z.core.util.JSONType>>>;
221
+ type: z.ZodLiteral<"array">;
222
+ items: z.ZodDiscriminatedUnion<[z.ZodObject<{
223
+ title: z.ZodOptional<z.ZodString>;
224
+ description: z.ZodOptional<z.ZodString>;
225
+ default: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnknown, z.ZodJSONSchema>, z.ZodTransform<unknown, z.core.util.JSONType>>>;
226
+ type: z.ZodLiteral<"string">;
227
+ enum: z.ZodOptional<z.ZodArray<z.ZodString>>;
228
+ minLength: z.ZodOptional<z.ZodInt>;
229
+ maxLength: z.ZodOptional<z.ZodInt>;
230
+ }, z.core.$strict>, z.ZodObject<{
231
+ title: z.ZodOptional<z.ZodString>;
232
+ description: z.ZodOptional<z.ZodString>;
233
+ default: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnknown, z.ZodJSONSchema>, z.ZodTransform<unknown, z.core.util.JSONType>>>;
234
+ type: z.ZodEnum<{
235
+ number: "number";
236
+ integer: "integer";
237
+ }>;
238
+ minimum: z.ZodOptional<z.ZodNumber>;
239
+ maximum: z.ZodOptional<z.ZodNumber>;
240
+ exclusiveMinimum: z.ZodOptional<z.ZodNumber>;
241
+ exclusiveMaximum: z.ZodOptional<z.ZodNumber>;
242
+ }, z.core.$strict>, z.ZodObject<{
243
+ title: z.ZodOptional<z.ZodString>;
244
+ description: z.ZodOptional<z.ZodString>;
245
+ default: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnknown, z.ZodJSONSchema>, z.ZodTransform<unknown, z.core.util.JSONType>>>;
246
+ type: z.ZodLiteral<"boolean">;
247
+ }, z.core.$strict>], "type">;
248
+ minItems: z.ZodOptional<z.ZodInt>;
249
+ maxItems: z.ZodOptional<z.ZodInt>;
250
+ }, z.core.$strict>], "type">>>;
251
+ required: z.ZodOptional<z.ZodArray<z.ZodString>>;
252
+ additionalProperties: z.ZodLiteral<false>;
253
+ }, z.core.$strict>;
254
+ }, z.core.$strict>;
255
+ type NodeType = z.infer<typeof NodeType>;
256
+ /** The token an agent presents: an agent token, or a developer token and the id of its development environment. */
257
+ declare const Auth: z.ZodDiscriminatedUnion<[z.ZodObject<{
258
+ kind: z.ZodLiteral<"agent">;
259
+ token: z.ZodString;
260
+ }, z.core.$strict>, z.ZodObject<{
261
+ kind: z.ZodLiteral<"developer">;
262
+ token: z.ZodString;
263
+ environmentId: z.ZodUUID;
264
+ }, z.core.$strict>], "kind">;
265
+ type Auth = z.infer<typeof Auth>;
266
+ /** Zod schemas, one key per port or per parameter. */
267
+ type Schemas = Readonly<Record<string, z.ZodType>>;
268
+ /** No schema: what `inputs`, `outputs` or `parameters` is when the definition leaves it out. */
269
+ type NoSchema = Record<string, never>;
270
+ /** A value, directly or as a promise. */
271
+ type Awaitable<Value> = Value | Promise<Value>;
272
+ /**
273
+ * What `run` returns: its outputs, as the input of their schemas, directly or as a promise; or nothing, when no
274
+ * output is required.
275
+ */
276
+ type RunResult<Outputs extends Schemas> = NoSchema extends z.input<z.ZodObject<Outputs>> ? Awaitable<z.input<z.ZodObject<Outputs>>> | Awaitable<void> : Awaitable<z.input<z.ZodObject<Outputs>>>;
277
+ /** What the function of a node receives for one Step. */
278
+ type StepContext<Inputs extends Schemas, Parameters extends Schemas> = {
279
+ /** One key per input that has a value. For a Step, the SDK validates them with their schemas first. */
280
+ inputs: z.output<z.ZodObject<Inputs>>;
281
+ /** The parameters of the node. For a Step, the SDK validates them with their schemas and fills in each `.default()` first. */
282
+ parameters: z.output<z.ZodObject<Parameters>>;
283
+ /**
284
+ * Aborted when the result of the Step is no longer awaited: a cancellation, its timeout, or a connection the
285
+ * orchestrator closed for good or let expire, for example. Its `reason` is an `AgentError` whose `code` says
286
+ * why. Pass it to what the function awaits.
287
+ */
288
+ signal: AbortSignal;
289
+ /** Writes one log line of the Step, shown with its Execution. The call is synchronous and never throws. */
290
+ log: {
291
+ /** Writes a line at the `info` level. */
292
+ info(message: string): void;
293
+ /** Writes a line at the `warn` level. */
294
+ warn(message: string): void;
295
+ /** Writes a line at the `error` level. */
296
+ error(message: string): void;
297
+ };
298
+ /** The id of the Execution of the Step: write it in the logs of the agent, to find the Execution in the web interface. */
299
+ executionId: string;
300
+ /** The id of the Step: an idempotency key for an external call. */
301
+ stepId: string;
302
+ };
303
+ /** The definition of a node: what the developer writes, and gives to `defineNode`. */
304
+ type NodeDefinition<Inputs extends Schemas, Outputs extends Schemas, Parameters extends Schemas> = {
305
+ /** The namespaced identifier of the node type, `acme.ocr` for example. */
306
+ identifier: string;
307
+ /** Its semver version, `1.0.0` for example. */
308
+ version: string;
309
+ /** The timeout of a Step, in milliseconds: from 600,000, the default, 10 minutes, to 21,600,000, 6 hours. */
310
+ timeoutMs?: number;
311
+ /**
312
+ * One Zod schema per data input: its key is the name of the port. A port is `z.string()`, `z.int()`,
313
+ * `z.number()`, `z.boolean()`, `z.enum([...])`, `z.unknown()` or `z.array()` of one of them, plus `.optional()`.
314
+ */
315
+ inputs?: Inputs;
316
+ /** One Zod schema per data output, written as an input is. */
317
+ outputs?: Outputs;
318
+ /**
319
+ * One Zod schema per parameter, set in the editor: a string, an integer, a number, a boolean or an array of one
320
+ * of them, with its bounds, `z.enum([...])`, `.optional()`, `.default()`, `.describe()` and `.meta({ title })`.
321
+ */
322
+ parameters?: Parameters;
323
+ /** The function of the node, called for each Step. An exception fails the Step, with its message. */
324
+ run(context: StepContext<Inputs, Parameters>): RunResult<NoInfer<Outputs>>;
325
+ };
326
+ /** A defined node: what `defineNode` returns, and `runAgent` takes. */
327
+ type DefinedNode<Inputs extends Schemas, Outputs extends Schemas, Parameters extends Schemas> = {
328
+ /**
329
+ * The node type the agent will declare, as the orchestrator receives it:
330
+ * `{ identifier, version, timeoutMs, inputs, outputs, parameterSchema }`. `inputs` and `outputs` list the data
331
+ * ports, each `{ name, type, required }`, and `parameterSchema` is the JSON Schema of the parameters.
332
+ */
333
+ nodeType: NodeType;
334
+ /** The definition as it was written, with its types: call `definition.run` to test the node alone. Called this way, the function receives what the test gives it, neither validated nor filled in. */
335
+ definition: NodeDefinition<Inputs, Outputs, Parameters>;
336
+ };
337
+ /** A node of any definition: what `runAgent` takes in `nodes`. */
338
+ type AnyNode = DefinedNode<Schemas, Schemas, Schemas>;
339
+ /**
340
+ * Defines a node, to give to `runAgent`: the node type the agent will declare, read from the Zod schemas of the
341
+ * definition, and the definition itself. The definition is validated at once, with the schema the orchestrator
342
+ * applies to a declared node type: refused, it throws an `AgentError` of code `invalid_node_definition`, whose
343
+ * message gives one line per issue, naming the node, the field and the rule, and whose `details.issues` lists
344
+ * them, each `{ path, message }`.
345
+ *
346
+ * @example
347
+ * ```ts @import.meta.vitest
348
+ * const upper = defineNode({
349
+ * identifier: 'acme.upper',
350
+ * version: '1.0.0',
351
+ * inputs: { text: z.string() },
352
+ * outputs: { upper: z.string() },
353
+ * run: ({ inputs }) => ({ upper: inputs.text.toUpperCase() }),
354
+ * });
355
+ * expect(upper.nodeType.inputs).toStrictEqual([{ name: 'text', type: { name: 'string' }, required: true }]);
356
+ * expect(() => defineNode({ ...upper.definition, inputs: { text: z.email() } })).toThrow('acme.upper@1.0.0 inputs.text: a port is');
357
+ * ```
358
+ */
359
+ export declare function defineNode<Inputs extends Schemas = NoSchema, Outputs extends Schemas = NoSchema, Parameters extends Schemas = NoSchema>(definition: NodeDefinition<Inputs, Outputs, Parameters>): DefinedNode<Inputs, Outputs, Parameters>;
360
+ /** A change of state of the connection, that `onEvent` receives. */
361
+ type AgentEvent = {
362
+ /** The orchestrator accepted the agent: its connection is ready. */
363
+ type: 'connected';
364
+ /** The id of the connection on the orchestrator. */
365
+ connectionId: string;
366
+ /** True when the agent resumed its connection after a cut. */
367
+ resumed: boolean;
368
+ } | {
369
+ /** The socket of the agent closed, and the SDK will retry. */
370
+ type: 'disconnected';
371
+ /** The close code of the socket: 1006 for an unreachable orchestrator or a network cut. */
372
+ code: number;
373
+ /** The close reason of the socket, empty for a network cut. */
374
+ reason: string;
375
+ /** The delay before the next attempt, in milliseconds. */
376
+ retryInMs: number;
377
+ } | {
378
+ /** The graceful shutdown starts. */
379
+ type: 'draining';
380
+ /** How many Steps the agent still runs. */
381
+ runningSteps: number;
382
+ };
383
+ /** The options of `runAgent`. */
384
+ type AgentOptions = {
385
+ /** The address of the orchestrator, `wss://<host>/agents`: a `ws:` or `wss:` URL, without a fragment. */
386
+ url: string;
387
+ /**
388
+ * The token of the agent: `{ kind: 'agent', token }`, an agent token, or
389
+ * `{ kind: 'developer', token, environmentId }`, a developer token and the id of its development environment.
390
+ */
391
+ auth: Auth;
392
+ /** The nodes returned by `defineNode`. */
393
+ nodes: readonly AnyNode[];
394
+ /** How many Steps run at the same time, from 1 to 256; 1 by default. */
395
+ slots?: number;
396
+ /** Requests the graceful shutdown: the agent takes no more Step, finishes those it runs, then leaves. */
397
+ signal?: AbortSignal;
398
+ /** Receives the changes of state of the connection; without it, each one is written to standard error. */
399
+ onEvent?: (event: AgentEvent) => void;
400
+ };
401
+ /**
402
+ * Runs an agent: it connects to the orchestrator, declares its nodes and its slots, runs the Steps it is
403
+ * assigned and keeps its connection through network cuts. The promise lasts as long as the agent: it resolves
404
+ * after a graceful shutdown, requested by `signal`, and rejects with an `AgentError` when an option is refused,
405
+ * before any connection, or when the orchestrator refuses the agent for good, an unknown token for example.
406
+ *
407
+ * @example
408
+ * ```ts @import.meta.vitest
409
+ * const refused = runAgent({ url: 'https://orchestrator.example.com', auth: { kind: 'agent', token: 'token_agent_x' }, nodes: [] });
410
+ * await expect(refused).rejects.toMatchObject({ code: 'invalid_agent_options', message: 'url: Expected a ws:// or wss:// URL, without a fragment' });
411
+ * ```
412
+ */
413
+ export declare function runAgent(options: AgentOptions): Promise<void>;
414
+ export type { AgentEvent, AgentOptions, AnyNode, Awaitable, DefinedNode, NoSchema, NodeDefinition, RunResult, Schemas, StepContext };
package/dist/index.js ADDED
@@ -0,0 +1,148 @@
1
+ import { n as runAgent, o as NodeType, s as AgentError } from "./run-agent.js";
2
+ import { z } from "zod";
3
+ // src/define-node.ts
4
+ const NO_JSON_SCHEMA = "zod cannot write this schema as a JSON Schema, as it cannot for z.date() or z.bigint()";
5
+ const PORT_RULE = "a port is z.string(), z.int(), z.number(), z.boolean(), z.enum([...]), z.unknown() or z.array() of one of them, plus .optional()";
6
+ /**
7
+ * Le JSON Schema qu'émet chacun des six schémas d'un élément, lu vers son type de port : à l'identique,
8
+ * donc sans autre mot-clé (sdk.md § Ports). `z.int()` émet ses deux bornes d'entier sûr.
9
+ */
10
+ const ItemPortType = z.union([
11
+ z.strictObject({ type: z.literal("string") }).transform(() => ({ name: "string" })),
12
+ z.strictObject({
13
+ type: z.literal("integer"),
14
+ minimum: z.literal(Number.MIN_SAFE_INTEGER),
15
+ maximum: z.literal(Number.MAX_SAFE_INTEGER)
16
+ }).transform(() => ({ name: "integer" })),
17
+ z.strictObject({ type: z.literal("number") }).transform(() => ({ name: "float" })),
18
+ z.strictObject({ type: z.literal("boolean") }).transform(() => ({ name: "boolean" })),
19
+ z.strictObject({
20
+ type: z.literal("string"),
21
+ enum: z.array(z.string())
22
+ }).transform((schema) => ({
23
+ name: "enum",
24
+ values: schema.enum
25
+ })),
26
+ z.strictObject({}).transform(() => ({ name: "json" }))
27
+ ]);
28
+ /** Le JSON Schema d'un port : l'un des six d'un élément, ou un tableau de l'un d'eux. */
29
+ const DeclaredPortType = z.union([ItemPortType, z.strictObject({
30
+ type: z.literal("array"),
31
+ items: ItemPortType
32
+ }).transform(({ items }) => ({
33
+ name: "array",
34
+ items
35
+ }))]);
36
+ /** Ce que le SDK lit du JSON Schema d'un objet de ports : ses propriétés, et celles qui sont requises. */
37
+ const PortsSchema = z.object({
38
+ properties: z.record(z.string(), z.unknown()),
39
+ required: z.array(z.string()).default([])
40
+ });
41
+ /**
42
+ * Le JSON Schema de schémas Zod réunis en un objet strict, tel que le nœud accepte de les recevoir
43
+ * (`io: 'input'`) : un paramètre à `.default()` n'y est pas requis. Un schéma que zod ne sait pas écrire
44
+ * en JSON Schema, `z.date()` par exemple, ferait lever la conversion de l'objet entier : chaque schéma
45
+ * est donc essayé seul d'abord, et celui qui lève ajoute une faute et reste hors de l'objet.
46
+ */
47
+ function jsonSchemaOf(field, schemas, issues) {
48
+ const writable = Object.entries(schemas).filter(([name, schema]) => {
49
+ try {
50
+ z.toJSONSchema(schema, { io: "input" });
51
+ return true;
52
+ } catch {
53
+ issues.push({
54
+ path: [field, name],
55
+ message: NO_JSON_SCHEMA
56
+ });
57
+ return false;
58
+ }
59
+ });
60
+ return z.toJSONSchema(z.strictObject(Object.fromEntries(writable)), { io: "input" });
61
+ }
62
+ /**
63
+ * Les ports `data` que déclarent des schémas. Un schéma hors des sept formes ajoute une faute, et son
64
+ * port reste déclaré, en `json` : son nom est ainsi jugé avec les autres, réservé ou en double.
65
+ */
66
+ function declaredPorts(field, schemas, issues) {
67
+ const { properties, required } = PortsSchema.parse(jsonSchemaOf(field, schemas, issues));
68
+ return Object.entries(properties).map(([name, property]) => {
69
+ const type = DeclaredPortType.safeParse(property);
70
+ if (type.success) return {
71
+ name,
72
+ type: type.data,
73
+ required: required.includes(name)
74
+ };
75
+ issues.push({
76
+ path: [field, name],
77
+ message: `${PORT_RULE}; got ${JSON.stringify(property)}`
78
+ });
79
+ return {
80
+ name,
81
+ type: { name: "json" },
82
+ required: required.includes(name)
83
+ };
84
+ });
85
+ }
86
+ /**
87
+ * Le chemin d'une issue de la déclaration, dans les mots de la définition : le rang d'un port devient
88
+ * son nom, et `parameterSchema.properties` s'écrit `parameters`.
89
+ */
90
+ function definitionPath(path, declaration) {
91
+ const [field, key, ...rest] = path;
92
+ if (field === "parameterSchema") return ["parameters", ...rest.map(String)];
93
+ if ((field === "inputs" || field === "outputs") && typeof key === "number") return [
94
+ field,
95
+ ...declaration[field].map((port) => port.name).slice(key, key + 1),
96
+ ...rest.map(String)
97
+ ];
98
+ return path.map(String);
99
+ }
100
+ /** La valeur déclarée au chemin d'une issue : ce que le message d'une faute montre après `got`. */
101
+ function declaredAt(declaration, path) {
102
+ return path.reduce((value, key) => typeof value === "object" && value !== null ? Reflect.get(value, key) : void 0, declaration);
103
+ }
104
+ /**
105
+ * Defines a node, to give to `runAgent`: the node type the agent will declare, read from the Zod schemas of the
106
+ * definition, and the definition itself. The definition is validated at once, with the schema the orchestrator
107
+ * applies to a declared node type: refused, it throws an `AgentError` of code `invalid_node_definition`, whose
108
+ * message gives one line per issue, naming the node, the field and the rule, and whose `details.issues` lists
109
+ * them, each `{ path, message }`.
110
+ *
111
+ * @example
112
+ * ```ts @import.meta.vitest
113
+ * const upper = defineNode({
114
+ * identifier: 'acme.upper',
115
+ * version: '1.0.0',
116
+ * inputs: { text: z.string() },
117
+ * outputs: { upper: z.string() },
118
+ * run: ({ inputs }) => ({ upper: inputs.text.toUpperCase() }),
119
+ * });
120
+ * expect(upper.nodeType.inputs).toStrictEqual([{ name: 'text', type: { name: 'string' }, required: true }]);
121
+ * expect(() => defineNode({ ...upper.definition, inputs: { text: z.email() } })).toThrow('acme.upper@1.0.0 inputs.text: a port is');
122
+ * ```
123
+ */
124
+ function defineNode(definition) {
125
+ const issues = [];
126
+ const declaration = {
127
+ identifier: definition.identifier,
128
+ version: definition.version,
129
+ timeoutMs: definition.timeoutMs,
130
+ inputs: declaredPorts("inputs", definition.inputs ?? {}, issues),
131
+ outputs: declaredPorts("outputs", definition.outputs ?? {}, issues),
132
+ parameterSchema: jsonSchemaOf("parameters", definition.parameters ?? {}, issues)
133
+ };
134
+ const nodeType = NodeType.safeParse(declaration);
135
+ for (const issue of nodeType.error?.issues ?? []) issues.push({
136
+ path: definitionPath(issue.path, declaration),
137
+ message: `${issue.message}; got ${JSON.stringify(declaredAt(declaration, issue.path))}`
138
+ });
139
+ if (!nodeType.success || issues.length > 0) {
140
+ const label = `${definition.identifier}@${definition.version}`;
141
+ throw new AgentError("invalid_node_definition", issues.map(({ path, message }) => `${label} ${path.join(".")}: ${message}`).join("\n"), { issues });
142
+ }
143
+ return {
144
+ nodeType: nodeType.data,
145
+ definition
146
+ };
147
+ }
148
+ export { AgentError, defineNode, runAgent };
package/dist/main.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {}