@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.
package/dist/main.js ADDED
@@ -0,0 +1,292 @@
1
+ #!/usr/bin/env node
2
+ import { a as DEFAULT_LIMITS, i as faultLines, o as NodeType, r as declarationIssues, s as AgentError, t as connectAgent } from "./run-agent.js";
3
+ import { Command } from "commander";
4
+ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, watch, writeFileSync } from "node:fs";
5
+ import { dirname, join, resolve, sep } from "node:path";
6
+ import { registerHooks } from "node:module";
7
+ import { fileURLToPath, pathToFileURL } from "node:url";
8
+ import { z } from "zod";
9
+ // package.json
10
+ var version = "0.10.0-rc.1";
11
+ // src/nodes-file.ts
12
+ /** Ce que le SDK lit d'un nœud rendu par `defineNode` : sa déclaration, et sa fonction. */
13
+ const DefinedNode = z.object({
14
+ nodeType: NodeType,
15
+ definition: z.object({ run: z.custom((run) => typeof run === "function") })
16
+ });
17
+ function isNode(value) {
18
+ return DefinedNode.safeParse(value).success;
19
+ }
20
+ /** Ce que le SDK lit du module d'un fichier de nœuds : sa liste `nodes`. */
21
+ const NodesModule = z.object({ nodes: z.array(z.unknown()) });
22
+ function invalid(file, message) {
23
+ return new AgentError("invalid_nodes_file", `${file}: ${message}`);
24
+ }
25
+ /**
26
+ * Le fichier de nœuds d'un projet d'agent, celui qui exporte la liste `nodes` : `export const nodes = [ocr, wait];`.
27
+ * `load()` l'importe et rend cette liste ; `directory` est son dossier, en chemin absolu.
28
+ *
29
+ * Chaque `load()` relit le fichier et les modules ES qu'il importe de son dossier, `node_modules` excepté : c'est ce
30
+ * qui laisse le mode dev redéclarer un nœud modifié sans redémarrer. Node garde en mémoire un module déjà
31
+ * importé, sous son adresse ; un hook de résolution (`registerHooks`) donne donc aux fichiers de ce dossier
32
+ * une adresse nouvelle à chaque chargement. Les modules des chargements précédents restent en mémoire
33
+ * jusqu'à la fin du processus.
34
+ *
35
+ * Un fichier absent, sans liste `nodes`, ou dont un élément ne vient pas de `defineNode`, lève une `AgentError`
36
+ * de code `invalid_nodes_file` ; ce que lève le fichier lui-même, une définition refusée par exemple, passe tel quel.
37
+ *
38
+ * @example
39
+ * ```ts @import.meta.vitest
40
+ * const missing = nodesFile('/nowhere/src/nodes.ts');
41
+ * expect(missing.directory).toBe('/nowhere/src');
42
+ * await expect(missing.load()).rejects.toMatchObject({ code: 'invalid_nodes_file' });
43
+ * ```
44
+ */
45
+ function nodesFile(file) {
46
+ const path = existsSync(file) ? realpathSync(file) : resolve(file);
47
+ const directory = dirname(path);
48
+ const root = pathToFileURL(`${directory}${sep}`).href;
49
+ let generation = 0;
50
+ registerHooks({ resolve(specifier, context, nextResolve) {
51
+ const resolved = nextResolve(specifier, context);
52
+ if (!resolved.url.startsWith(root) || resolved.url.includes("/node_modules/")) return resolved;
53
+ const url = new URL(resolved.url);
54
+ url.searchParams.set("load", String(generation));
55
+ return {
56
+ ...resolved,
57
+ url: url.href
58
+ };
59
+ } });
60
+ return {
61
+ directory,
62
+ async load() {
63
+ if (!existsSync(path)) throw invalid(file, "no such file; give the file that exports the nodes of the agent, src/nodes.ts by default");
64
+ generation += 1;
65
+ const exported = NodesModule.safeParse(await import(pathToFileURL(path).href));
66
+ if (!exported.success) throw invalid(file, "expected the list of the nodes of the agent, as in `export const nodes = [ocr, wait];`");
67
+ const { nodes } = exported.data;
68
+ const strangers = nodes.flatMap((node, index) => isNode(node) ? [] : [`nodes[${String(index)}]`]);
69
+ if (strangers.length > 0) throw invalid(file, `${strangers.join(", ")}: expected a node made by defineNode`);
70
+ return nodes.filter(isNode);
71
+ }
72
+ };
73
+ }
74
+ // src/dev.ts
75
+ /**
76
+ * Le délai entre une modification et la redéclaration : un éditeur écrit un fichier en plusieurs fois, et
77
+ * plusieurs fichiers d'un coup.
78
+ */
79
+ const RELOAD_DELAY_MS = 100;
80
+ /** Les `NodeType` de ces nœuds, nommés : `acme.ocr@1.0.0, acme.wait@1.0.0`. */
81
+ function labelsOf(nodes) {
82
+ return nodes.length === 0 ? "no node type" : nodes.map(({ nodeType }) => `${nodeType.identifier}@${nodeType.version}`).join(", ");
83
+ }
84
+ /**
85
+ * Le refus d'une déclaration par l'orchestrator, avec une ligne par faute dans son message, qui nomme le nœud
86
+ * de `nodes` en cause ; toute autre erreur, telle quelle.
87
+ *
88
+ * @example
89
+ * ```ts @import.meta.vitest
90
+ * const fault = { index: 3, code: 'node_type_limit_reached', path: [], message: 'Limit reached' };
91
+ * const refusal = new AgentError('invalid_declaration', 'Refused', { faults: [fault] });
92
+ * expect(withFaults(refusal, [])).toMatchObject({ message: 'Refused\nnodeTypes[3]: Limit reached (node_type_limit_reached)' });
93
+ * ```
94
+ */
95
+ function withFaults(error, nodes) {
96
+ if (!(error instanceof AgentError) || error.code !== "invalid_declaration") return error;
97
+ const lines = faultLines(nodes.map(({ nodeType }) => nodeType), error.details);
98
+ return new AgentError(error.code, [error.message, ...lines].join("\n"), error.details);
99
+ }
100
+ /**
101
+ * Ce que la commande écrit d'une erreur : le message d'une `AgentError`, écrit pour le développeur ; pour toute
102
+ * autre, une faute de syntaxe du fichier de nœuds par exemple, sa pile, qui donne le fichier et la ligne.
103
+ *
104
+ * @example
105
+ * ```ts @import.meta.vitest
106
+ * expect(explained(new AgentError('invalid_token', 'The token is unknown, revoked or expired.'))).toBe('The token is unknown, revoked or expired.');
107
+ * expect(explained(new TypeError('x is not a function'))).toContain('TypeError: x is not a function\n at ');
108
+ * expect(explained('unreadable')).toBe('unreadable');
109
+ * ```
110
+ */
111
+ function explained(error) {
112
+ if (error instanceof AgentError) return error.message;
113
+ return error instanceof Error && error.stack !== void 0 ? error.stack : String(error);
114
+ }
115
+ /**
116
+ * Le mode dev : connecte un agent avec un `DeveloperToken`, sur un `Environment` `development`, où ses versions
117
+ * sont enregistrées en `-dev-<userId>`, puis surveille le dossier du fichier de nœuds. À chaque modification, il
118
+ * relit le fichier et redéclare ses nœuds par `declare`, sans se reconnecter. Un fichier qui ne se charge plus,
119
+ * une déclaration au-delà des plafonds reçus dans `hello` ou refusée par l'orchestrator s'écrivent, et la
120
+ * déclaration précédente reste en place. La promesse est celle de `runAgent`.
121
+ */
122
+ async function runDev(options) {
123
+ const { file, url, environmentId, token, signal, write } = options;
124
+ const source = nodesFile(file);
125
+ let declared = await source.load();
126
+ const agent = connectAgent({
127
+ url,
128
+ auth: {
129
+ kind: "developer",
130
+ token,
131
+ environmentId
132
+ },
133
+ nodes: declared,
134
+ signal
135
+ }, "1.0");
136
+ write(`Connecting to ${url} with ${labelsOf(declared)}, from ${file}`);
137
+ async function reload() {
138
+ let next = [];
139
+ try {
140
+ next = await source.load();
141
+ await agent.redeclare(next);
142
+ declared = next;
143
+ write(`Declared again: ${labelsOf(next)}`);
144
+ } catch (error) {
145
+ if (!signal.aborted) write(`Not declared again, the previous declaration stays:\n${explained(withFaults(error, next))}`);
146
+ }
147
+ }
148
+ let reloads = Promise.resolve();
149
+ let timer;
150
+ const watcher = watch(source.directory, { recursive: true }, (event, changed) => {
151
+ if (changed?.split(sep).includes("node_modules") === true) return;
152
+ clearTimeout(timer);
153
+ timer = setTimeout(() => {
154
+ reloads = reloads.then(reload);
155
+ }, RELOAD_DELAY_MS);
156
+ });
157
+ try {
158
+ await agent.done;
159
+ } catch (error) {
160
+ throw withFaults(error, declared);
161
+ } finally {
162
+ clearTimeout(timer);
163
+ watcher.close();
164
+ }
165
+ }
166
+ // src/init.ts
167
+ /** Le gabarit d'un projet d'agent, livré dans le paquet : à côté de `src/` dans le dépôt, de `dist/` dans l'archive. */
168
+ const TEMPLATE = fileURLToPath(new URL("../template/", import.meta.url));
169
+ /**
170
+ * Chaque fichier d'un projet créé, et le fichier du gabarit dont il vient. Deux noms changent :
171
+ * - `gitignore` : npm ne livre pas un fichier nommé `.gitignore` ;
172
+ * - les sources en `.ts.txt` : en `.ts`, ESLint et les autres outils du dépôt jugeraient un code qui importe
173
+ * `@gutilab/sdk`, qu'ils ne savent pas résoudre ici. `package.test.ts` type le projet créé.
174
+ */
175
+ const FILES = [
176
+ [".gitignore", "gitignore"],
177
+ ["package.json", "package.json"],
178
+ ["src/main.ts", "src/main.ts.txt"],
179
+ ["src/nodes.ts", "src/nodes.ts.txt"],
180
+ ["tsconfig.json", "tsconfig.json"]
181
+ ];
182
+ /**
183
+ * Crée un projet d'agent dans `directory`, depuis le gabarit du paquet, avec le SDK à la version `version`,
184
+ * celle qui crée le projet (sdk.md § Installer). Rend les fichiers écrits. Le dossier est créé s'il manque ;
185
+ * un dossier qui n'est pas vide, ou un fichier, lève une `AgentError` de code `invalid_directory`, sans rien écrire.
186
+ *
187
+ * @example
188
+ * ```ts @import.meta.vitest
189
+ * const { mkdtempSync, rmSync } = await import('node:fs');
190
+ * const directory = mkdtempSync('/tmp/sdk-init-example-');
191
+ * expect(initProject(directory, '1.2.3')).toContain('src/nodes.ts');
192
+ * expect(() => initProject(directory, '1.2.3')).toThrow('is not empty');
193
+ * rmSync(directory, { recursive: true });
194
+ * ```
195
+ */
196
+ function initProject(directory, version) {
197
+ if (existsSync(directory)) {
198
+ const fault = statSync(directory).isDirectory() ? readdirSync(directory).length > 0 && "is not empty" : "is not a directory";
199
+ if (fault !== false) throw new AgentError("invalid_directory", `${directory} ${fault}: give a new directory, or an empty one`);
200
+ }
201
+ for (const [written, source] of FILES) {
202
+ const content = readFileSync(join(TEMPLATE, source), "utf8");
203
+ const target = join(directory, written);
204
+ mkdirSync(dirname(target), { recursive: true });
205
+ writeFileSync(target, written === "package.json" ? manifestOf(content, version) : content);
206
+ }
207
+ return FILES.map(([written]) => written);
208
+ }
209
+ /** Le manifeste du projet créé : celui du gabarit, dans son ordre, le SDK à la version donnée. */
210
+ function manifestOf(template, version) {
211
+ const manifest = JSON.parse(template, (key, value) => key === "@gutilab/sdk" ? version : value);
212
+ return `${JSON.stringify(manifest, null, 2)}\n`;
213
+ }
214
+ // src/cli.ts
215
+ /** Le fichier de nœuds que lisent `dev` et `validate` sans argument : celui du gabarit. */
216
+ const NODES_FILE = "src/nodes.ts";
217
+ /**
218
+ * La commande `gutilab-sdk` (sdk.md § Commande) : `init` crée un projet d'agent depuis le gabarit du paquet,
219
+ * `dev` lance ses nœuds en mode développement et les redéclare à chaque modification, `validate` vérifie ses
220
+ * définitions sans se connecter. `--help` donne la version du protocole agent que parle le SDK. Une commande
221
+ * refusée écrit pourquoi sur la sortie d'erreur, et sort avec le code 1.
222
+ *
223
+ * @example
224
+ * ```ts @import.meta.vitest
225
+ * expect(createCli().name()).toBe('gutilab-sdk');
226
+ * expect(createCli().commands.map((command) => command.name())).toStrictEqual(['init', 'dev', 'validate']);
227
+ * ```
228
+ */
229
+ function createCli() {
230
+ const cli = new Command("gutilab-sdk").description(`Write and run orchestrator agents (agent protocol 1.0).`).version(version);
231
+ /** Écrit une ligne sur la sortie standard de la commande. */
232
+ function write(line) {
233
+ cli.configureOutput().writeOut?.(`${line}\n`);
234
+ }
235
+ /** Lance une sous-commande ; ce qu'elle lève s'écrit sur la sortie d'erreur, et la commande sort avec le code 1. */
236
+ async function guarded(run) {
237
+ try {
238
+ await run();
239
+ } catch (error) {
240
+ cli.error(explained(error), { exitCode: 1 });
241
+ }
242
+ }
243
+ cli.command("init").description("Create an agent project in a new directory, from the template of this SDK.").argument("<directory>", "the directory of the project, new or empty").action((directory) => guarded(() => {
244
+ const written = initProject(directory, version);
245
+ write([
246
+ `Created an agent project in ${directory}:`,
247
+ ...written.map((file) => ` ${file}`),
248
+ "Next:",
249
+ ` cd ${directory}`,
250
+ " npm install",
251
+ " export DEVELOPER_TOKEN=<your developer token>",
252
+ " npx --no gutilab-sdk dev --url wss://<your orchestrator>/agents --environment <environment id>"
253
+ ].join("\n"));
254
+ }));
255
+ cli.command("dev").description("Run the nodes of a file as a development agent, and declare them again each time a file of its directory changes.").argument("[file]", "the file that exports the list `nodes`", NODES_FILE).requiredOption("--url <url>", "the address of the orchestrator: wss://<host>/agents").requiredOption("--environment <id>", "the id of a development environment").addHelpText("after", "\nThe developer token is read from the environment variable DEVELOPER_TOKEN, never from the command line.").action((file, options) => guarded(async () => {
256
+ const token = process.env.DEVELOPER_TOKEN;
257
+ if (token === void 0 || token === "") throw new AgentError("missing_developer_token", "Set the environment variable DEVELOPER_TOKEN to your developer token: export DEVELOPER_TOKEN=<your developer token>");
258
+ const stop = new AbortController();
259
+ const release = () => {
260
+ process.off("SIGINT", abort);
261
+ process.off("SIGTERM", abort);
262
+ };
263
+ function abort() {
264
+ stop.abort();
265
+ release();
266
+ }
267
+ process.on("SIGINT", abort);
268
+ process.on("SIGTERM", abort);
269
+ try {
270
+ await runDev({
271
+ file,
272
+ url: options.url,
273
+ environmentId: options.environment,
274
+ token,
275
+ signal: stop.signal,
276
+ write
277
+ });
278
+ } finally {
279
+ release();
280
+ }
281
+ }));
282
+ cli.command("validate").description("Check the node definitions of a file without connecting, against the default limits of an orchestrator.").argument("[file]", "the file that exports the list `nodes`", NODES_FILE).action((file) => guarded(async () => {
283
+ const nodes = await nodesFile(file).load();
284
+ const issues = declarationIssues(nodes.map(({ nodeType }) => nodeType), 1, DEFAULT_LIMITS);
285
+ if (issues.length > 0) throw new AgentError("invalid_declaration", issues.join("\n"));
286
+ write(`${file} is valid: ${labelsOf(nodes)}`);
287
+ }));
288
+ return cli;
289
+ }
290
+ // src/main.ts
291
+ await createCli().parseAsync();
292
+ export {};