@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/LICENSE +21 -0
- package/README.md +678 -2
- package/dist/index.d.ts +414 -0
- package/dist/index.js +148 -0
- package/dist/main.d.ts +1 -0
- package/dist/main.js +292 -0
- package/dist/run-agent.js +1532 -0
- package/package.json +26 -3
- package/template/gitignore +1 -0
- package/template/package.json +19 -0
- package/template/src/main.ts.txt +14 -0
- package/template/src/nodes.ts.txt +21 -0
- package/template/tsconfig.json +12 -0
|
@@ -0,0 +1,1532 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { createBirpc } from "birpc";
|
|
3
|
+
// src/agent-error.ts
|
|
4
|
+
/**
|
|
5
|
+
* A refusal by the SDK or by the orchestrator, or the reason why a Step was interrupted (`signal.reason`). Its
|
|
6
|
+
* `code`, stable and in snake_case, says which one; `details`, when present, gives more information: the issues
|
|
7
|
+
* of a refused node definition, for example.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```ts @import.meta.vitest
|
|
11
|
+
* const error = new AgentError('invalid_token', 'The token is unknown, revoked or expired.');
|
|
12
|
+
* expect(error.code).toBe('invalid_token');
|
|
13
|
+
* ```
|
|
14
|
+
*/
|
|
15
|
+
var AgentError = class extends Error {
|
|
16
|
+
/** The stable code of the refusal, in snake_case: `invalid_token` or `invalid_node_definition`, for example. */
|
|
17
|
+
code;
|
|
18
|
+
/** More information about the refusal, when there is some: the issues of a refused node definition, for example. */
|
|
19
|
+
details;
|
|
20
|
+
/**
|
|
21
|
+
* @param code The stable code of the refusal, in snake_case.
|
|
22
|
+
* @param message What a person reads: one line per issue, for a refused definition.
|
|
23
|
+
* @param details More information about the refusal, when there is some.
|
|
24
|
+
*/
|
|
25
|
+
constructor(code, message, details) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.name = "AgentError";
|
|
28
|
+
this.code = code;
|
|
29
|
+
this.details = details;
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
// ../../packages/contracts/domain/json-value.ts
|
|
33
|
+
/** Le nombre maximal de niveaux d'une valeur JSON libre : chaque tableau ou objet en compte un. */
|
|
34
|
+
const MAX_JSON_DEPTH = 64;
|
|
35
|
+
/**
|
|
36
|
+
* Dit si une valeur imbrique plus de MAX_JSON_DEPTH tableaux ou objets. Le parcours est itératif :
|
|
37
|
+
* une valeur de 100 000 niveaux ne fait pas déborder la pile, comme le ferait `z.json()`.
|
|
38
|
+
*
|
|
39
|
+
* @example
|
|
40
|
+
* ```ts @import.meta.vitest
|
|
41
|
+
* expect(nestsTooDeep([[1]])).toBe(false);
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
function nestsTooDeep(value) {
|
|
45
|
+
const stack = [[value, 0]];
|
|
46
|
+
for (let entry = stack.pop(); entry !== void 0; entry = stack.pop()) {
|
|
47
|
+
const [current, depth] = entry;
|
|
48
|
+
if (typeof current === "object" && current !== null) {
|
|
49
|
+
if (depth >= MAX_JSON_DEPTH) return true;
|
|
50
|
+
for (const child of Object.values(current)) stack.push([child, depth + 1]);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Un surrogate isolé : avec le drapeau `u`, une paire de surrogates est un seul point de code, hors de la catégorie
|
|
57
|
+
* `Cs` ; seule une moitié de paire sans l'autre y tombe.
|
|
58
|
+
*/
|
|
59
|
+
const LONE_SURROGATE = /\p{Cs}/u;
|
|
60
|
+
/**
|
|
61
|
+
* Dit si une colonne JSONB de Postgres range ce texte : elle refuse le caractère U+0000 et le surrogate isolé, dans
|
|
62
|
+
* une chaîne comme dans une clé (security.md § Règles aux frontières).
|
|
63
|
+
*
|
|
64
|
+
* @example
|
|
65
|
+
* ```ts @import.meta.vitest
|
|
66
|
+
* expect(isStorable('a\u0000')).toBe(false);
|
|
67
|
+
* expect(isStorable('\ud800')).toBe(false);
|
|
68
|
+
* expect(isStorable('😀')).toBe(true);
|
|
69
|
+
* ```
|
|
70
|
+
*/
|
|
71
|
+
function isStorable(text) {
|
|
72
|
+
return !text.includes("\0") && !LONE_SURROGATE.test(text);
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Dit si une valeur JSON porte, dans une chaîne ou une clé, à toute profondeur, un texte que la colonne JSONB refuse.
|
|
76
|
+
* Le parcours est itératif, comme celui de nestsTooDeep, et ne descend, comme lui, que dans un tableau ou un objet.
|
|
77
|
+
* Il ne se lance que sur une valeur d'au plus MAX_JSON_DEPTH niveaux : une valeur qui se contient elle-même ne le
|
|
78
|
+
* fait donc pas boucler, ni une fonction, dont nestsTooDeep ne compte pas les propriétés.
|
|
79
|
+
*
|
|
80
|
+
* @example
|
|
81
|
+
* ```ts @import.meta.vitest
|
|
82
|
+
* expect(holdsUnstorableText({ a: ['b', 'c\u0000'] })).toBe(true);
|
|
83
|
+
* expect(holdsUnstorableText({ '\ud800': 1 })).toBe(true);
|
|
84
|
+
* expect(holdsUnstorableText({ a: '😀' })).toBe(false);
|
|
85
|
+
* ```
|
|
86
|
+
*/
|
|
87
|
+
function holdsUnstorableText(value) {
|
|
88
|
+
const stack = [value];
|
|
89
|
+
while (stack.length > 0) {
|
|
90
|
+
const current = stack.pop();
|
|
91
|
+
if (typeof current === "string") {
|
|
92
|
+
if (!isStorable(current)) return true;
|
|
93
|
+
} else if (typeof current === "object" && current !== null) for (const [key, child] of Object.entries(current)) stack.push(key, child);
|
|
94
|
+
}
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* La valeur JSON libre de contracts, bornée à 64 niveaux avant `z.json()` : au-delà, une issue
|
|
99
|
+
* custom au chemin de la valeur, sans exception. Elle refuse de même, d'une seule issue au chemin de la valeur, le
|
|
100
|
+
* caractère U+0000 et le surrogate isolé dans chacune de ses chaînes et de ses clés : la colonne JSONB qui la range
|
|
101
|
+
* les refuserait (security.md § Règles aux frontières).
|
|
102
|
+
*
|
|
103
|
+
* @example
|
|
104
|
+
* ```ts @import.meta.vitest
|
|
105
|
+
* expect(JsonValue.safeParse({ a: [1, 'b', null] }).success).toBe(true);
|
|
106
|
+
* expect(JsonValue.safeParse({ a: ['b\u0000'] }).success).toBe(false);
|
|
107
|
+
* ```
|
|
108
|
+
*/
|
|
109
|
+
const JsonValue = z.unknown().superRefine((value, context) => {
|
|
110
|
+
if (nestsTooDeep(value)) {
|
|
111
|
+
context.addIssue({
|
|
112
|
+
code: "custom",
|
|
113
|
+
message: `JSON value nests more than ${String(MAX_JSON_DEPTH)} levels`
|
|
114
|
+
});
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
if (holdsUnstorableText(value)) context.addIssue({
|
|
118
|
+
code: "custom",
|
|
119
|
+
message: "JSON value holds U+0000 or a lone surrogate"
|
|
120
|
+
});
|
|
121
|
+
}).pipe(z.json());
|
|
122
|
+
/**
|
|
123
|
+
* Une chaîne libre qu'une colonne JSONB range : sans caractère U+0000 ni surrogate isolé. Elle lit chaque chaîne
|
|
124
|
+
* libre rangée en JSONB hors d'une JsonValue : une clé de constants, de parameters, de TriggerParameters ou de
|
|
125
|
+
* Result.outputs, une valeur de Switch ou d'enum, le port d'un bout de fil, title et description d'un schéma de
|
|
126
|
+
* paramètres (security.md § Règles aux frontières).
|
|
127
|
+
*
|
|
128
|
+
* @example
|
|
129
|
+
* ```ts @import.meta.vitest
|
|
130
|
+
* expect(StorableString.safeParse('😀').success).toBe(true);
|
|
131
|
+
* expect(StorableString.safeParse('a\u0000').success).toBe(false);
|
|
132
|
+
* ```
|
|
133
|
+
*/
|
|
134
|
+
const StorableString = z.string().refine(isStorable, { message: "String holds U+0000 or a lone surrogate" });
|
|
135
|
+
// ../../packages/contracts/domain/port.ts
|
|
136
|
+
/**
|
|
137
|
+
* Le nom d'un port déclaré, d'un paramètre de NodeType, d'un paramètre ou d'une sortie du workflow,
|
|
138
|
+
* d'une entrée de Condition ; la longueur se contrôle avant le motif (engine.md § Ports et types).
|
|
139
|
+
*
|
|
140
|
+
* @example
|
|
141
|
+
* ```ts @import.meta.vitest
|
|
142
|
+
* expect(PortName.safeParse('pageCount').success).toBe(true);
|
|
143
|
+
* ```
|
|
144
|
+
*/
|
|
145
|
+
const PortName = z.string().max(64, { abort: true }).regex(/^[a-zA-Z][a-zA-Z0-9_]*$/);
|
|
146
|
+
/**
|
|
147
|
+
* Ajoute une issue custom à chaque nom déjà vu, au chemin de sa seconde occurrence.
|
|
148
|
+
*
|
|
149
|
+
* @example
|
|
150
|
+
* ```ts @import.meta.vitest
|
|
151
|
+
* const Names = z.array(z.string()).superRefine((names, context) => {
|
|
152
|
+
* addDuplicateIssues(names, (index) => ['values', index], context);
|
|
153
|
+
* });
|
|
154
|
+
* expect(Names.safeParse(['a', 'a']).error?.issues.map((issue) => issue.path)).toStrictEqual([['values', 1]]);
|
|
155
|
+
* ```
|
|
156
|
+
*/
|
|
157
|
+
function addDuplicateIssues(names, pathOf, context) {
|
|
158
|
+
const seen = /* @__PURE__ */ new Set();
|
|
159
|
+
names.forEach((name, index) => {
|
|
160
|
+
if (seen.has(name)) context.addIssue({
|
|
161
|
+
code: "custom",
|
|
162
|
+
message: `${name} is already used`,
|
|
163
|
+
path: pathOf(index)
|
|
164
|
+
});
|
|
165
|
+
else seen.add(name);
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Les valeurs d'un PortType enum : 1 à 256 chaînes non vides et distinctes, sans autre format que
|
|
170
|
+
* celui de StorableString ; un doublon est refusé à sa seconde occurrence.
|
|
171
|
+
*
|
|
172
|
+
* @example
|
|
173
|
+
* ```ts @import.meta.vitest
|
|
174
|
+
* expect(EnumValues.safeParse(['low', 'en-cours']).success).toBe(true);
|
|
175
|
+
* ```
|
|
176
|
+
*/
|
|
177
|
+
const EnumValues = z.array(StorableString.min(1)).min(1).max(256).superRefine((values, context) => {
|
|
178
|
+
addDuplicateIssues(values, (index) => [index], context);
|
|
179
|
+
});
|
|
180
|
+
const ITEM_PORT_TYPES = [
|
|
181
|
+
z.strictObject({ name: z.literal("string") }),
|
|
182
|
+
z.strictObject({ name: z.literal("integer") }),
|
|
183
|
+
z.strictObject({ name: z.literal("float") }),
|
|
184
|
+
z.strictObject({ name: z.literal("boolean") }),
|
|
185
|
+
z.strictObject({ name: z.literal("json") }),
|
|
186
|
+
z.strictObject({
|
|
187
|
+
name: z.literal("enum"),
|
|
188
|
+
values: EnumValues
|
|
189
|
+
})
|
|
190
|
+
];
|
|
191
|
+
/**
|
|
192
|
+
* Le type d'un port data, un objet discriminé par `name` ; les éléments d'un array sont de tout
|
|
193
|
+
* type sauf array (engine.md § Ports et types).
|
|
194
|
+
*
|
|
195
|
+
* @example
|
|
196
|
+
* ```ts @import.meta.vitest
|
|
197
|
+
* const type = { name: 'array', items: { name: 'enum', values: ['low', 'high'] } };
|
|
198
|
+
* expect(PortType.parse(type)).toStrictEqual(type);
|
|
199
|
+
* ```
|
|
200
|
+
*/
|
|
201
|
+
const PortType = z.discriminatedUnion("name", [...ITEM_PORT_TYPES, z.strictObject({
|
|
202
|
+
name: z.literal("array"),
|
|
203
|
+
items: z.discriminatedUnion("name", ITEM_PORT_TYPES)
|
|
204
|
+
})]);
|
|
205
|
+
/**
|
|
206
|
+
* La sorte d'un port : exec porte le flot de contrôle, data une valeur typée.
|
|
207
|
+
*
|
|
208
|
+
* @example
|
|
209
|
+
* ```ts @import.meta.vitest
|
|
210
|
+
* expect(PortKind.parse('exec')).toBe('exec');
|
|
211
|
+
* ```
|
|
212
|
+
*/
|
|
213
|
+
const PortKind = z.enum(["exec", "data"]);
|
|
214
|
+
/**
|
|
215
|
+
* Le sens d'un port : une entrée ou une sortie de son nœud.
|
|
216
|
+
*
|
|
217
|
+
* @example
|
|
218
|
+
* ```ts @import.meta.vitest
|
|
219
|
+
* expect(PortDirection.parse('in')).toBe('in');
|
|
220
|
+
* ```
|
|
221
|
+
*/
|
|
222
|
+
const PortDirection = z.enum(["in", "out"]);
|
|
223
|
+
z.discriminatedUnion("kind", [z.strictObject({
|
|
224
|
+
name: z.string().min(1),
|
|
225
|
+
kind: PortKind.extract(["exec"]),
|
|
226
|
+
direction: PortDirection,
|
|
227
|
+
required: z.boolean()
|
|
228
|
+
}), z.strictObject({
|
|
229
|
+
name: z.string().min(1),
|
|
230
|
+
kind: PortKind.extract(["data"]),
|
|
231
|
+
direction: PortDirection,
|
|
232
|
+
required: z.boolean(),
|
|
233
|
+
type: PortType
|
|
234
|
+
})]);
|
|
235
|
+
/**
|
|
236
|
+
* Un port data qu'un agent déclare pour son NodeType (protocol.md § declare).
|
|
237
|
+
*
|
|
238
|
+
* @example
|
|
239
|
+
* ```ts @import.meta.vitest
|
|
240
|
+
* const declaration = { name: 'pageCount', type: { name: 'integer' }, required: true };
|
|
241
|
+
* expect(DataPortDeclaration.parse(declaration)).toStrictEqual(declaration);
|
|
242
|
+
* ```
|
|
243
|
+
*/
|
|
244
|
+
const DataPortDeclaration = z.strictObject({
|
|
245
|
+
name: PortName,
|
|
246
|
+
type: PortType,
|
|
247
|
+
required: z.boolean()
|
|
248
|
+
});
|
|
249
|
+
// ../../packages/contracts/domain/parameter-schema.ts
|
|
250
|
+
/** Une longueur ou un nombre d'éléments : un entier ≥ 0. */
|
|
251
|
+
const Count = z.int().min(0).optional();
|
|
252
|
+
/**
|
|
253
|
+
* Les annotations communes à chaque propriété, sans effet sur les valeurs. Le catalogue les range en
|
|
254
|
+
* JSONB : title et description sont des StorableString, et `default` est lu par JsonValue, borné à 64
|
|
255
|
+
* niveaux, avant que checkDefault le juge par le schéma de valeur de sa propriété. Un default imbriqué
|
|
256
|
+
* en profondeur rend une issue au lieu de lever. Son type reste `unknown`, par le `transform` :
|
|
257
|
+
* le type récursif de JsonValue dans un NodeType ferait lever TS2589 à Hono RPC, dans la réponse du
|
|
258
|
+
* catalogue (backend.md § Workflow et brouillons).
|
|
259
|
+
*/
|
|
260
|
+
const Annotations = z.strictObject({
|
|
261
|
+
title: StorableString.optional(),
|
|
262
|
+
description: StorableString.optional(),
|
|
263
|
+
default: JsonValue.transform((value) => value).optional()
|
|
264
|
+
});
|
|
265
|
+
const StringProperty = Annotations.extend({
|
|
266
|
+
type: z.literal("string"),
|
|
267
|
+
enum: EnumValues.optional(),
|
|
268
|
+
minLength: Count,
|
|
269
|
+
maxLength: Count
|
|
270
|
+
});
|
|
271
|
+
const NumericProperty = Annotations.extend({
|
|
272
|
+
type: z.enum(["integer", "number"]),
|
|
273
|
+
minimum: z.number().optional(),
|
|
274
|
+
maximum: z.number().optional(),
|
|
275
|
+
exclusiveMinimum: z.number().optional(),
|
|
276
|
+
exclusiveMaximum: z.number().optional()
|
|
277
|
+
});
|
|
278
|
+
const BooleanProperty = Annotations.extend({ type: z.literal("boolean") });
|
|
279
|
+
/** Le schéma de valeur d'une propriété string, integer, number ou boolean. */
|
|
280
|
+
function itemValues(item) {
|
|
281
|
+
switch (item.type) {
|
|
282
|
+
case "string": {
|
|
283
|
+
let values = z.string();
|
|
284
|
+
if (item.minLength !== void 0) values = values.min(item.minLength);
|
|
285
|
+
if (item.maxLength !== void 0) values = values.max(item.maxLength);
|
|
286
|
+
const allowed = item.enum;
|
|
287
|
+
return allowed === void 0 ? values : values.refine((value) => allowed.includes(value), { message: "Value not in enum" });
|
|
288
|
+
}
|
|
289
|
+
case "integer":
|
|
290
|
+
case "number": {
|
|
291
|
+
let values = item.type === "integer" ? z.int() : z.number();
|
|
292
|
+
if (item.minimum !== void 0) values = values.gte(item.minimum);
|
|
293
|
+
if (item.maximum !== void 0) values = values.lte(item.maximum);
|
|
294
|
+
if (item.exclusiveMinimum !== void 0) values = values.gt(item.exclusiveMinimum);
|
|
295
|
+
if (item.exclusiveMaximum !== void 0) values = values.lt(item.exclusiveMaximum);
|
|
296
|
+
return values;
|
|
297
|
+
}
|
|
298
|
+
case "boolean": return z.boolean();
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
/** Refuse un `default` que le schéma de valeur de sa propriété refuse, au chemin `default`. */
|
|
302
|
+
function checkDefault(values) {
|
|
303
|
+
return (property, context) => {
|
|
304
|
+
if (property.default !== void 0 && !values(property).safeParse(property.default).success) context.addIssue({
|
|
305
|
+
code: "custom",
|
|
306
|
+
message: "Default value does not match its property",
|
|
307
|
+
path: ["default"]
|
|
308
|
+
});
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
const ItemSchema = z.discriminatedUnion("type", [
|
|
312
|
+
StringProperty,
|
|
313
|
+
NumericProperty,
|
|
314
|
+
BooleanProperty
|
|
315
|
+
]).superRefine(checkDefault(itemValues));
|
|
316
|
+
const ArrayProperty = Annotations.extend({
|
|
317
|
+
type: z.literal("array"),
|
|
318
|
+
items: ItemSchema,
|
|
319
|
+
minItems: Count,
|
|
320
|
+
maxItems: Count
|
|
321
|
+
});
|
|
322
|
+
/**
|
|
323
|
+
* Le plus d'éléments d'une valeur de paramètre tableau, quelle que soit sa maxItems : la borne des
|
|
324
|
+
* fils d'un Graph. Zod juge la longueur avant les éléments : un tableau trop long rend une seule
|
|
325
|
+
* issue too_big, et non une par élément.
|
|
326
|
+
*/
|
|
327
|
+
const MAX_ARRAY_ITEMS = 4096;
|
|
328
|
+
/** Le schéma de valeur d'une propriété ; chaque mot-clé s'applique avec les autres. */
|
|
329
|
+
function propertyValues(property) {
|
|
330
|
+
if (property.type !== "array") return itemValues(property);
|
|
331
|
+
let values = z.array(itemValues(property.items)).max(Math.min(property.maxItems ?? MAX_ARRAY_ITEMS, MAX_ARRAY_ITEMS));
|
|
332
|
+
if (property.minItems !== void 0) values = values.min(property.minItems);
|
|
333
|
+
return values;
|
|
334
|
+
}
|
|
335
|
+
const ParameterProperty = z.discriminatedUnion("type", [
|
|
336
|
+
StringProperty,
|
|
337
|
+
NumericProperty,
|
|
338
|
+
BooleanProperty,
|
|
339
|
+
ArrayProperty
|
|
340
|
+
]).superRefine(checkDefault(propertyValues));
|
|
341
|
+
/**
|
|
342
|
+
* z.record retire en silence une clé propre `__proto__` (celle que crée JSON.parse) : elle est
|
|
343
|
+
* refusée avant lui, comme toute clé hors du sous-ensemble. Il garde aussi constants et
|
|
344
|
+
* parameters d'un nœud (graph.ts).
|
|
345
|
+
*
|
|
346
|
+
* @example
|
|
347
|
+
* ```ts @import.meta.vitest
|
|
348
|
+
* const Numbers = WithoutProtoKey.pipe(z.record(z.string(), z.number()));
|
|
349
|
+
* expect(Numbers.safeParse(JSON.parse('{"__proto__":1}')).success).toBe(false);
|
|
350
|
+
* ```
|
|
351
|
+
*/
|
|
352
|
+
const WithoutProtoKey = z.unknown().refine((input) => typeof input !== "object" || input === null || !Object.hasOwn(input, "__proto__"), { message: "Unrecognized key: \"__proto__\"" });
|
|
353
|
+
/**
|
|
354
|
+
* Le schéma de paramètres d'un NodeType : le sous-ensemble de JSON Schema 2020-12 de protocol.md
|
|
355
|
+
* § Schéma de paramètres, un objet plat de 32 propriétés au plus. Une clé inconnue est refusée à
|
|
356
|
+
* tous les niveaux, au chemin de l'objet qui la contient.
|
|
357
|
+
*
|
|
358
|
+
* @example
|
|
359
|
+
* ```ts @import.meta.vitest
|
|
360
|
+
* const schema = {
|
|
361
|
+
* type: 'object',
|
|
362
|
+
* properties: { lang: { type: 'string', enum: ['fr', 'en'] } },
|
|
363
|
+
* required: ['lang'],
|
|
364
|
+
* additionalProperties: false,
|
|
365
|
+
* };
|
|
366
|
+
* expect(ParameterSchema.parse(schema)).toStrictEqual(schema);
|
|
367
|
+
* ```
|
|
368
|
+
*/
|
|
369
|
+
const ParameterSchema = z.strictObject({
|
|
370
|
+
$schema: z.literal("https://json-schema.org/draft/2020-12/schema").optional(),
|
|
371
|
+
type: z.literal("object"),
|
|
372
|
+
properties: WithoutProtoKey.pipe(z.record(PortName, ParameterProperty).refine((properties) => Object.keys(properties).length <= 32, { message: "At most 32 parameters" })),
|
|
373
|
+
required: z.array(z.string()).optional(),
|
|
374
|
+
additionalProperties: z.literal(false)
|
|
375
|
+
}).superRefine((schema, context) => {
|
|
376
|
+
const seen = /* @__PURE__ */ new Set();
|
|
377
|
+
schema.required?.forEach((name, index) => {
|
|
378
|
+
if (!Object.hasOwn(schema.properties, name) || seen.has(name)) context.addIssue({
|
|
379
|
+
code: "custom",
|
|
380
|
+
message: "Each required name must be a distinct key of properties",
|
|
381
|
+
path: ["required", index]
|
|
382
|
+
});
|
|
383
|
+
else seen.add(name);
|
|
384
|
+
});
|
|
385
|
+
});
|
|
386
|
+
// ../../packages/contracts/domain/node-type.ts
|
|
387
|
+
/**
|
|
388
|
+
* L'expression proposée par semver.org pour une version 2.0.0 (« suggested regular expression »),
|
|
389
|
+
* ses groupes capturants rendus non capturants :
|
|
390
|
+
* ^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$
|
|
391
|
+
*/
|
|
392
|
+
const SEMVER = /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?:[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
|
|
393
|
+
/** Les noms des ports que la plateforme fixe sur chaque nœud d'agent (engine.md § Nœuds d'agent). */
|
|
394
|
+
const RESERVED_PORT_NAMES = /* @__PURE__ */ new Set([
|
|
395
|
+
"in",
|
|
396
|
+
"out",
|
|
397
|
+
"onFailure",
|
|
398
|
+
"error"
|
|
399
|
+
]);
|
|
400
|
+
/**
|
|
401
|
+
* L'identifiant d'un NodeType : des segments en minuscules séparés par des points, deux au moins ;
|
|
402
|
+
* la longueur se contrôle avant le motif (protocol.md § declare).
|
|
403
|
+
*
|
|
404
|
+
* @example
|
|
405
|
+
* ```ts @import.meta.vitest
|
|
406
|
+
* expect(NodeTypeIdentifier.safeParse('acme.ocr').success).toBe(true);
|
|
407
|
+
* ```
|
|
408
|
+
*/
|
|
409
|
+
const NodeTypeIdentifier = z.string().max(128, { abort: true }).regex(/^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+$/);
|
|
410
|
+
/**
|
|
411
|
+
* La version d'un NodeType, semver 2.0.0, de 64 caractères au plus (protocol.md § declare).
|
|
412
|
+
*
|
|
413
|
+
* @example
|
|
414
|
+
* ```ts @import.meta.vitest
|
|
415
|
+
* expect(NodeTypeVersion.safeParse('1.0.0-rc.1+build.5').success).toBe(true);
|
|
416
|
+
* ```
|
|
417
|
+
*/
|
|
418
|
+
const NodeTypeVersion = z.string().max(64, { abort: true }).regex(SEMVER);
|
|
419
|
+
/**
|
|
420
|
+
* A node type declared by an agent: its identifier, its version, the timeout of a Step, 600,000 ms by default,
|
|
421
|
+
* its data ports and the schema of its parameters. Inputs and outputs share one namespace: a reserved name
|
|
422
|
+
* (`in`, `out`, `onFailure`, `error`) or a duplicate one, at its second occurrence, gives a custom issue at the
|
|
423
|
+
* path of its name, whose `params.fault` is `reserved_port_name` or `duplicate_port_name`.
|
|
424
|
+
*
|
|
425
|
+
* @example
|
|
426
|
+
* ```ts @import.meta.vitest
|
|
427
|
+
* const ocr = NodeType.parse({
|
|
428
|
+
* identifier: 'acme.ocr',
|
|
429
|
+
* version: '1.0.0',
|
|
430
|
+
* inputs: [{ name: 'file', type: { name: 'string' }, required: true }],
|
|
431
|
+
* outputs: [],
|
|
432
|
+
* parameterSchema: { type: 'object', properties: {}, additionalProperties: false },
|
|
433
|
+
* });
|
|
434
|
+
* expect(ocr.timeoutMs).toBe(600_000);
|
|
435
|
+
* ```
|
|
436
|
+
*/
|
|
437
|
+
const NodeType = z.strictObject({
|
|
438
|
+
identifier: NodeTypeIdentifier,
|
|
439
|
+
version: NodeTypeVersion,
|
|
440
|
+
timeoutMs: z.int().min(6e5).max(216e5).default(6e5),
|
|
441
|
+
inputs: z.array(DataPortDeclaration).max(32),
|
|
442
|
+
outputs: z.array(DataPortDeclaration).max(32),
|
|
443
|
+
parameterSchema: ParameterSchema
|
|
444
|
+
}).superRefine((nodeType, context) => {
|
|
445
|
+
const seen = /* @__PURE__ */ new Set();
|
|
446
|
+
for (const list of ["inputs", "outputs"]) nodeType[list].forEach(({ name }, index) => {
|
|
447
|
+
let fault;
|
|
448
|
+
if (RESERVED_PORT_NAMES.has(name)) fault = "reserved_port_name";
|
|
449
|
+
else if (seen.has(name)) fault = "duplicate_port_name";
|
|
450
|
+
seen.add(name);
|
|
451
|
+
if (fault !== void 0) context.addIssue({
|
|
452
|
+
code: "custom",
|
|
453
|
+
message: `Port name ${name} is reserved or already used`,
|
|
454
|
+
path: [
|
|
455
|
+
list,
|
|
456
|
+
index,
|
|
457
|
+
"name"
|
|
458
|
+
],
|
|
459
|
+
params: { fault }
|
|
460
|
+
});
|
|
461
|
+
});
|
|
462
|
+
});
|
|
463
|
+
z.strictObject({
|
|
464
|
+
identifier: NodeTypeIdentifier,
|
|
465
|
+
version: z.string().max(105, { abort: true }).regex(SEMVER)
|
|
466
|
+
});
|
|
467
|
+
// ../../packages/contracts/protocol/closure.ts
|
|
468
|
+
/**
|
|
469
|
+
* Le code WebSocket de chaque motif de fermeture d'un socket par l'orchestrator
|
|
470
|
+
* (protocol.md § Fermeture) ; le motif est aussi la raison de la trame de fermeture.
|
|
471
|
+
*
|
|
472
|
+
* @example
|
|
473
|
+
* ```ts @import.meta.vitest
|
|
474
|
+
* expect(CLOSE_CODES.malformed_message).toBe(4000);
|
|
475
|
+
* ```
|
|
476
|
+
*/
|
|
477
|
+
const CLOSE_CODES = {
|
|
478
|
+
malformed_message: 4e3,
|
|
479
|
+
handshake_timeout: 4001,
|
|
480
|
+
unsupported_protocol_version: 4002,
|
|
481
|
+
invalid_token: 4003,
|
|
482
|
+
environment_forbidden: 4004,
|
|
483
|
+
unknown_connection: 4005,
|
|
484
|
+
invalid_declaration: 4006,
|
|
485
|
+
too_many_node_types: 4007,
|
|
486
|
+
heartbeat_timeout: 4008,
|
|
487
|
+
access_revoked: 4009,
|
|
488
|
+
superseded: 4010
|
|
489
|
+
};
|
|
490
|
+
/** Les plafonds que la réponse à `hello` transmet, à leur valeur par défaut (protocol.md § Plafonds). */
|
|
491
|
+
const DEFAULT_LIMITS = {
|
|
492
|
+
maxMessageBytes: 2097152,
|
|
493
|
+
maxNodeTypes: 512,
|
|
494
|
+
maxParameterSchemaBytes: 65536,
|
|
495
|
+
maxOutputBytes: 262144,
|
|
496
|
+
maxLogLineBytes: 4096,
|
|
497
|
+
maxFailureMessageBytes: 4096
|
|
498
|
+
};
|
|
499
|
+
// ../../packages/contracts/protocol/version.ts
|
|
500
|
+
/**
|
|
501
|
+
* Une version du protocole, `major.minor` : deux entiers sans zéro initial, 16 caractères au plus ;
|
|
502
|
+
* la longueur se contrôle avant le motif.
|
|
503
|
+
*
|
|
504
|
+
* @example
|
|
505
|
+
* ```ts @import.meta.vitest
|
|
506
|
+
* expect(ProtocolVersion.safeParse('1.12').success).toBe(true);
|
|
507
|
+
* expect(ProtocolVersion.safeParse('1.0.0').success).toBe(false);
|
|
508
|
+
* ```
|
|
509
|
+
*/
|
|
510
|
+
const ProtocolVersion = z.string().max(16, { abort: true }).regex(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/);
|
|
511
|
+
// ../../packages/contracts/protocol/messages.ts
|
|
512
|
+
/** The token an agent presents: an agent token, or a developer token and the id of its development environment. */
|
|
513
|
+
const Auth = z.discriminatedUnion("kind", [z.strictObject({
|
|
514
|
+
kind: z.literal("agent"),
|
|
515
|
+
token: z.string().min(1).max(256)
|
|
516
|
+
}), z.strictObject({
|
|
517
|
+
kind: z.literal("developer"),
|
|
518
|
+
token: z.string().min(1).max(256),
|
|
519
|
+
environmentId: z.uuid()
|
|
520
|
+
})]);
|
|
521
|
+
/**
|
|
522
|
+
* Une déclaration, l'argument de `declare` et le champ `declaration` de `hello`. Le contenu de
|
|
523
|
+
* chaque `nodeTypes[i]` n'est pas lu ici : `readDeclaration` en fait des fautes, qui refusent la
|
|
524
|
+
* déclaration sans fermer la connexion (protocol.md § Déclaration).
|
|
525
|
+
*
|
|
526
|
+
* @example
|
|
527
|
+
* ```ts @import.meta.vitest
|
|
528
|
+
* expect(Declaration.safeParse({ slots: 4, nodeTypes: [] }).success).toBe(true);
|
|
529
|
+
* expect(Declaration.safeParse({ slots: 300, nodeTypes: [] }).success).toBe(false);
|
|
530
|
+
* ```
|
|
531
|
+
*/
|
|
532
|
+
const Declaration = z.strictObject({
|
|
533
|
+
slots: z.int().min(1).max(256),
|
|
534
|
+
nodeTypes: z.array(z.unknown())
|
|
535
|
+
});
|
|
536
|
+
/**
|
|
537
|
+
* La reprise d'une connexion : son identifiant, et les `Step` que l'agent tient encore, sans doublon,
|
|
538
|
+
* 256 au plus, le nombre maximal de `Slot`. La longueur se juge avant le contenu : un tableau hostile
|
|
539
|
+
* d'un million d'éléments ne donne qu'une issue.
|
|
540
|
+
*/
|
|
541
|
+
const Resume = z.strictObject({
|
|
542
|
+
connectionId: z.uuid(),
|
|
543
|
+
heldStepIds: z.array(z.uuid()).max(256).superRefine((stepIds, context) => {
|
|
544
|
+
addDuplicateIssues(stepIds, (index) => [index], context);
|
|
545
|
+
})
|
|
546
|
+
});
|
|
547
|
+
z.strictObject({
|
|
548
|
+
protocolVersion: ProtocolVersion,
|
|
549
|
+
auth: Auth,
|
|
550
|
+
declaration: Declaration,
|
|
551
|
+
resume: Resume.optional()
|
|
552
|
+
});
|
|
553
|
+
/** Les plafonds réglés sur l'orchestrator, que le SDK vérifie avant d'envoyer (protocol.md § Plafonds). */
|
|
554
|
+
const Limits = z.object({
|
|
555
|
+
maxMessageBytes: z.int().min(1),
|
|
556
|
+
maxNodeTypes: z.int().min(1),
|
|
557
|
+
maxParameterSchemaBytes: z.int().min(1),
|
|
558
|
+
maxOutputBytes: z.int().min(1),
|
|
559
|
+
maxLogLineBytes: z.int().min(1),
|
|
560
|
+
maxFailureMessageBytes: z.int().min(1)
|
|
561
|
+
});
|
|
562
|
+
/** La réponse à un `hello` accepté. */
|
|
563
|
+
const HelloResponse = z.object({
|
|
564
|
+
connectionId: z.uuid(),
|
|
565
|
+
protocolVersion: ProtocolVersion,
|
|
566
|
+
heartbeat: z.object({
|
|
567
|
+
intervalMs: z.int().min(1),
|
|
568
|
+
timeoutMs: z.int().min(1)
|
|
569
|
+
}),
|
|
570
|
+
limits: Limits,
|
|
571
|
+
steps: z.array(z.object({
|
|
572
|
+
stepId: z.uuid(),
|
|
573
|
+
lastLogSeq: z.int().min(0)
|
|
574
|
+
})),
|
|
575
|
+
cancelledStepIds: z.array(z.uuid())
|
|
576
|
+
});
|
|
577
|
+
z.strictObject({
|
|
578
|
+
stepId: z.uuid(),
|
|
579
|
+
lines: z.array(z.strictObject({
|
|
580
|
+
seq: z.int().min(1).max(0x7fffffff),
|
|
581
|
+
level: z.enum([
|
|
582
|
+
"info",
|
|
583
|
+
"warn",
|
|
584
|
+
"error"
|
|
585
|
+
]),
|
|
586
|
+
message: StorableString,
|
|
587
|
+
at: z.iso.datetime().refine((value) => !value.startsWith("0000-"), { message: "year 0000 is not a date" })
|
|
588
|
+
})).min(1).max(4096)
|
|
589
|
+
});
|
|
590
|
+
/**
|
|
591
|
+
* L'argument de `result` : le résultat d'un `Step`, ses sorties s'il a réussi, son message sinon.
|
|
592
|
+
*
|
|
593
|
+
* @example
|
|
594
|
+
* ```ts @import.meta.vitest
|
|
595
|
+
* const failed = { stepId: '0199f3a2-7c41-7d2e-9b8a-5f0e6d4c3b2a', status: 'failed', message: 'HTTP 404' };
|
|
596
|
+
* expect(Result.parse(failed)).toStrictEqual(failed);
|
|
597
|
+
* ```
|
|
598
|
+
*/
|
|
599
|
+
const Result = z.discriminatedUnion("status", [z.strictObject({
|
|
600
|
+
stepId: z.uuid(),
|
|
601
|
+
status: z.literal("succeeded"),
|
|
602
|
+
outputs: z.record(StorableString, JsonValue)
|
|
603
|
+
}), z.strictObject({
|
|
604
|
+
stepId: z.uuid(),
|
|
605
|
+
status: z.literal("failed"),
|
|
606
|
+
message: StorableString
|
|
607
|
+
})]);
|
|
608
|
+
/** L'argument d'`assign` : un `Step`, déjà `running`, attribué à la connexion. */
|
|
609
|
+
const Assign = z.object({
|
|
610
|
+
executionId: z.uuid(),
|
|
611
|
+
stepId: z.uuid(),
|
|
612
|
+
nodeType: z.object({
|
|
613
|
+
identifier: NodeTypeIdentifier,
|
|
614
|
+
version: NodeTypeVersion
|
|
615
|
+
}),
|
|
616
|
+
parameters: z.record(z.string(), JsonValue),
|
|
617
|
+
inputs: z.record(z.string(), JsonValue),
|
|
618
|
+
timeoutMs: z.int().min(6e5).max(216e5)
|
|
619
|
+
});
|
|
620
|
+
/** Pourquoi un `Step` a quitté `running` sans résultat (protocol.md § Annulation). */
|
|
621
|
+
const CancelReason = z.enum([
|
|
622
|
+
"execution_cancelled",
|
|
623
|
+
"execution_failed",
|
|
624
|
+
"execution_succeeded",
|
|
625
|
+
"race_lost",
|
|
626
|
+
"timeout"
|
|
627
|
+
]);
|
|
628
|
+
/** L'argument de `cancel` : le `Step` à interrompre, et pourquoi. */
|
|
629
|
+
const Cancel = z.object({
|
|
630
|
+
stepId: z.uuid(),
|
|
631
|
+
reason: CancelReason
|
|
632
|
+
});
|
|
633
|
+
/** Une faute d'une déclaration : le `NodeType` en cause, son code, le chemin du champ fautif. */
|
|
634
|
+
const DeclarationFault = z.object({
|
|
635
|
+
index: z.int().min(0),
|
|
636
|
+
code: z.enum([
|
|
637
|
+
"invalid_node_type",
|
|
638
|
+
"unsupported_parameter_schema",
|
|
639
|
+
"parameter_schema_too_large",
|
|
640
|
+
"reserved_port_name",
|
|
641
|
+
"duplicate_port_name",
|
|
642
|
+
"duplicate_node_type",
|
|
643
|
+
"dev_version_forbidden",
|
|
644
|
+
"immutable_version_changed",
|
|
645
|
+
"node_type_limit_reached"
|
|
646
|
+
]),
|
|
647
|
+
path: z.array(z.union([z.string(), z.int()])),
|
|
648
|
+
message: z.string()
|
|
649
|
+
});
|
|
650
|
+
/**
|
|
651
|
+
* Une erreur du protocole, la réponse d'une procédure refusée : la forme commune de la plateforme,
|
|
652
|
+
* avec les codes des refus de protocol.md.
|
|
653
|
+
*
|
|
654
|
+
* @example
|
|
655
|
+
* ```ts @import.meta.vitest
|
|
656
|
+
* const refusal = { error: { code: 'invalid_token', message: 'The token is unknown, revoked or expired.' } };
|
|
657
|
+
* expect(ProtocolError.parse(refusal)).toStrictEqual(refusal);
|
|
658
|
+
* ```
|
|
659
|
+
*/
|
|
660
|
+
const ProtocolError = z.object({ error: z.object({
|
|
661
|
+
code: z.enum([
|
|
662
|
+
"malformed_message",
|
|
663
|
+
"unsupported_protocol_version",
|
|
664
|
+
"invalid_token",
|
|
665
|
+
"environment_forbidden",
|
|
666
|
+
"unknown_connection",
|
|
667
|
+
"invalid_declaration",
|
|
668
|
+
"too_many_node_types",
|
|
669
|
+
"internal_error"
|
|
670
|
+
]),
|
|
671
|
+
message: z.string(),
|
|
672
|
+
details: z.unknown().optional()
|
|
673
|
+
}) });
|
|
674
|
+
// src/agent-options.ts
|
|
675
|
+
/** Une adresse que le `WebSocket` de Node accepte : `ws:` ou `wss:`, sans fragment. */
|
|
676
|
+
function isAgentUrl(url) {
|
|
677
|
+
if (!URL.canParse(url)) return false;
|
|
678
|
+
const { protocol, hash } = new URL(url);
|
|
679
|
+
return ["ws:", "wss:"].includes(protocol) && hash === "";
|
|
680
|
+
}
|
|
681
|
+
/** Ce que le SDK contrôle des options avant toute connexion ; `signal` et `onEvent` sont gardés par TypeScript. */
|
|
682
|
+
const CheckedOptions = z.object({
|
|
683
|
+
url: z.string().refine(isAgentUrl, { message: "Expected a ws:// or wss:// URL, without a fragment" }),
|
|
684
|
+
auth: Auth,
|
|
685
|
+
nodes: z.array(z.object({ nodeType: z.object({
|
|
686
|
+
identifier: z.string(),
|
|
687
|
+
version: z.string()
|
|
688
|
+
}) })).superRefine((nodes, context) => {
|
|
689
|
+
addDuplicateIssues(nodes.map(({ nodeType }) => `${nodeType.identifier}@${nodeType.version}`), (index) => [index], context);
|
|
690
|
+
}),
|
|
691
|
+
slots: z.int().min(1).max(256).default(1)
|
|
692
|
+
});
|
|
693
|
+
/**
|
|
694
|
+
* Contrôle les options de `runAgent`, et rend le nombre de `Slot`, 1 par défaut. Une option absente ou hors
|
|
695
|
+
* de ses bornes, ou deux nœuds de même identifiant et de même version, lèvent une `AgentError` de code
|
|
696
|
+
* `invalid_agent_options`, dont le message donne une ligne par faute et `details.issues` leur liste.
|
|
697
|
+
*
|
|
698
|
+
* @example
|
|
699
|
+
* ```ts @import.meta.vitest
|
|
700
|
+
* const options = { url: 'wss://orchestrator.example.com/agents', auth: { kind: 'agent' as const, token: 'token_agent_x' }, nodes: [] };
|
|
701
|
+
* expect(checkedSlots(options)).toBe(1);
|
|
702
|
+
* expect(() => checkedSlots({ ...options, slots: 300 })).toThrow('slots: Too big');
|
|
703
|
+
* ```
|
|
704
|
+
*/
|
|
705
|
+
function checkedSlots(options) {
|
|
706
|
+
const checked = CheckedOptions.safeParse(options);
|
|
707
|
+
if (checked.success) return checked.data.slots;
|
|
708
|
+
const issues = checked.error.issues.map(({ path, message }) => ({
|
|
709
|
+
path: path.map(String),
|
|
710
|
+
message
|
|
711
|
+
}));
|
|
712
|
+
throw new AgentError("invalid_agent_options", issues.map(({ path, message }) => `${path.join(".")}: ${message}`).join("\n"), { issues });
|
|
713
|
+
}
|
|
714
|
+
/**
|
|
715
|
+
* `onEvent`, gardé : une exception de la fonction du développeur s'écrit sur la sortie d'erreur, et l'agent
|
|
716
|
+
* continue. Sans cette garde, elle arrêterait l'agent au milieu d'une reprise, sans régler sa promesse.
|
|
717
|
+
*
|
|
718
|
+
* @example
|
|
719
|
+
* ```ts @import.meta.vitest
|
|
720
|
+
* const seen: AgentEvent[] = [];
|
|
721
|
+
* const listener = guardedListener((event) => void seen.push(event));
|
|
722
|
+
* listener({ type: 'draining', runningSteps: 0 });
|
|
723
|
+
* expect(seen).toStrictEqual([{ type: 'draining', runningSteps: 0 }]);
|
|
724
|
+
* ```
|
|
725
|
+
*/
|
|
726
|
+
function guardedListener(onEvent) {
|
|
727
|
+
return (event) => {
|
|
728
|
+
try {
|
|
729
|
+
onEvent(event);
|
|
730
|
+
} catch (error) {
|
|
731
|
+
process.stderr.write(`gutilab-sdk onEvent threw: ${String(error)}\n`);
|
|
732
|
+
}
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
/** Écrit un événement sur la sortie d'erreur, en une ligne : ce que fait le SDK sans `onEvent`. */
|
|
736
|
+
function writeEvent(event) {
|
|
737
|
+
process.stderr.write(`gutilab-sdk ${JSON.stringify(event)}\n`);
|
|
738
|
+
}
|
|
739
|
+
// src/closure.ts
|
|
740
|
+
/**
|
|
741
|
+
* Le délai du SDK pour la réponse à `hello`, compté de l'ouverture de son essai : `RECONNECT_GRACE` par
|
|
742
|
+
* défaut, plus 10 s (ADR 0068).
|
|
743
|
+
*/
|
|
744
|
+
const HELLO_TIMEOUT_MS = 13e4;
|
|
745
|
+
/** Les délais entre deux essais de connexion ; le dernier se répète (sdk.md § Connexion). */
|
|
746
|
+
const RETRY_DELAYS_MS = [
|
|
747
|
+
1e3,
|
|
748
|
+
2e3,
|
|
749
|
+
5e3,
|
|
750
|
+
1e4,
|
|
751
|
+
3e4
|
|
752
|
+
];
|
|
753
|
+
/** Le code WebSocket d'un message trop gros, que `ws` ferme lui-même (protocol.md § Fermeture). */
|
|
754
|
+
const MESSAGE_TOO_LARGE = 1009;
|
|
755
|
+
/** Les fermetures définitives, où réessayer ne servirait à rien : le code de l'`AgentError`, et son message par défaut. */
|
|
756
|
+
const DEFINITIVE = /* @__PURE__ */ new Map([
|
|
757
|
+
[MESSAGE_TOO_LARGE, {
|
|
758
|
+
code: "message_too_large",
|
|
759
|
+
message: ""
|
|
760
|
+
}],
|
|
761
|
+
[CLOSE_CODES.malformed_message, {
|
|
762
|
+
code: "malformed_message",
|
|
763
|
+
message: "The orchestrator did not understand a message of the SDK: this is a defect of the SDK, please report it."
|
|
764
|
+
}],
|
|
765
|
+
[CLOSE_CODES.unsupported_protocol_version, {
|
|
766
|
+
code: "unsupported_protocol_version",
|
|
767
|
+
message: "The orchestrator does not speak the protocol version of this SDK."
|
|
768
|
+
}],
|
|
769
|
+
[CLOSE_CODES.invalid_token, {
|
|
770
|
+
code: "invalid_token",
|
|
771
|
+
message: "The token is unknown, revoked or expired."
|
|
772
|
+
}],
|
|
773
|
+
[CLOSE_CODES.environment_forbidden, {
|
|
774
|
+
code: "environment_forbidden",
|
|
775
|
+
message: "The environment is unknown, is a production one, or the developer has no role on its project."
|
|
776
|
+
}],
|
|
777
|
+
[CLOSE_CODES.invalid_declaration, {
|
|
778
|
+
code: "invalid_declaration",
|
|
779
|
+
message: "The orchestrator refused the declared node types."
|
|
780
|
+
}],
|
|
781
|
+
[CLOSE_CODES.too_many_node_types, {
|
|
782
|
+
code: "too_many_node_types",
|
|
783
|
+
message: ""
|
|
784
|
+
}],
|
|
785
|
+
[CLOSE_CODES.access_revoked, {
|
|
786
|
+
code: "access_revoked",
|
|
787
|
+
message: "The orchestrator closed the connection: the token was revoked or has expired, or its developer lost the role on the project."
|
|
788
|
+
}]
|
|
789
|
+
]);
|
|
790
|
+
/**
|
|
791
|
+
* La fermeture que vaut l'échec d'un appel. Un refus de l'orchestrator porte son code, que suit la fermeture
|
|
792
|
+
* du même motif. Tout autre échec, `internal_error` compris, est un appel non acquitté : le SDK ferme son
|
|
793
|
+
* socket, et la reprise le renvoie.
|
|
794
|
+
*
|
|
795
|
+
* @example
|
|
796
|
+
* ```ts @import.meta.vitest
|
|
797
|
+
* const refusal = { code: 'invalid_token' as const, message: 'The token is unknown, revoked or expired.' };
|
|
798
|
+
* expect(closureOf({ error: refusal })).toStrictEqual({ code: 4003, reason: 'invalid_token', refusal });
|
|
799
|
+
* expect(closureOf(new Error('socket closed'))).toStrictEqual({ code: 1000, reason: 'internal_error' });
|
|
800
|
+
* ```
|
|
801
|
+
*/
|
|
802
|
+
function closureOf(failure) {
|
|
803
|
+
const refusal = ProtocolError.safeParse(failure);
|
|
804
|
+
if (!refusal.success || refusal.data.error.code === "internal_error") return {
|
|
805
|
+
code: 1e3,
|
|
806
|
+
reason: "internal_error"
|
|
807
|
+
};
|
|
808
|
+
const { code } = refusal.data.error;
|
|
809
|
+
return {
|
|
810
|
+
code: CLOSE_CODES[code],
|
|
811
|
+
reason: code,
|
|
812
|
+
refusal: refusal.data.error
|
|
813
|
+
};
|
|
814
|
+
}
|
|
815
|
+
/**
|
|
816
|
+
* L'`AgentError` d'une fermeture définitive, qui rejette `runAgent` ; rien pour une coupure, que le SDK
|
|
817
|
+
* reprend. Elle garde le message et les `details` du refus de l'orchestrator. `nodeCount` est le nombre de
|
|
818
|
+
* `NodeType` de l'agent tant que `hello` n'est pas accepté : les deux refus de sa déclaration, partie avant
|
|
819
|
+
* les plafonds, le disent.
|
|
820
|
+
*
|
|
821
|
+
* @example
|
|
822
|
+
* ```ts @import.meta.vitest
|
|
823
|
+
* expect(definitiveError({ code: 4009, reason: 'access_revoked' }, 2)?.code).toBe('access_revoked');
|
|
824
|
+
* expect(definitiveError({ code: 1009, reason: '' }, 600)?.message).toContain('600 node types');
|
|
825
|
+
* expect(definitiveError({ code: 1009, reason: '' }, undefined)?.message).not.toContain('node types');
|
|
826
|
+
* expect(definitiveError({ code: 1006, reason: '' }, 2)).toBeUndefined();
|
|
827
|
+
* ```
|
|
828
|
+
*/
|
|
829
|
+
function definitiveError(closure, nodeCount) {
|
|
830
|
+
const known = DEFINITIVE.get(closure.code);
|
|
831
|
+
if (known === void 0) return;
|
|
832
|
+
const { refusal } = closure;
|
|
833
|
+
if (closure.code === MESSAGE_TOO_LARGE) {
|
|
834
|
+
const cause = nodeCount === void 0 ? "a batch of log lines, or the result of a Step" : `the declaration of this agent, ${String(nodeCount)} node types: split its nodes between several agents, or shorten their parameter schemas`;
|
|
835
|
+
return new AgentError(known.code, `The orchestrator closed the connection on a message larger than it accepts (AGENT_MAX_MESSAGE_BYTES, 2 MiB by default): ${cause}.`);
|
|
836
|
+
}
|
|
837
|
+
if (closure.code === CLOSE_CODES.too_many_node_types) return new AgentError(known.code, `The orchestrator refused the declaration of this agent, ${String(nodeCount ?? "too many")} node types: ${refusal?.message ?? "it holds too many node types"}. Split its nodes between several agents, or raise AGENT_MAX_NODE_TYPES on the orchestrator.`);
|
|
838
|
+
return new AgentError(known.code, refusal?.message ?? known.message, refusal?.details);
|
|
839
|
+
}
|
|
840
|
+
/**
|
|
841
|
+
* Le délai avant l'essai de connexion de rang `attempt`, compté de 0 depuis la dernière connexion acceptée.
|
|
842
|
+
*
|
|
843
|
+
* @example
|
|
844
|
+
* ```ts @import.meta.vitest
|
|
845
|
+
* expect([0, 1, 2, 3, 4, 5, 60].map(retryDelayMs)).toStrictEqual([1000, 2000, 5000, 10_000, 30_000, 30_000, 30_000]);
|
|
846
|
+
* ```
|
|
847
|
+
*/
|
|
848
|
+
function retryDelayMs(attempt) {
|
|
849
|
+
return RETRY_DELAYS_MS[Math.min(attempt, RETRY_DELAYS_MS.length - 1)] ?? 0;
|
|
850
|
+
}
|
|
851
|
+
// src/declaration.ts
|
|
852
|
+
/** Ce qu'un message porte en plus de son contenu : l'enveloppe de birpc, une centaine d'octets, comptés large. */
|
|
853
|
+
const MESSAGE_ENVELOPE_BYTES = 1024;
|
|
854
|
+
/** Le nom d'un `NodeType` dans un message : `acme.ocr@1.0.0`. */
|
|
855
|
+
function labelOf({ identifier, version }) {
|
|
856
|
+
return `${identifier}@${version}`;
|
|
857
|
+
}
|
|
858
|
+
/**
|
|
859
|
+
* Les fautes d'une déclaration, jugée avant son envoi avec les plafonds de l'orchestrator, ceux que `hello` a
|
|
860
|
+
* transmis ou ceux par défaut : le nombre de `NodeType`, la taille de chaque schéma de paramètres, un
|
|
861
|
+
* `NodeType` déclaré deux fois, et la taille du message entier, enveloppe comprise. Une ligne par faute ;
|
|
862
|
+
* aucune, la déclaration peut partir (protocol.md § Plafonds). Les tailles sont celles du JSON, en octets
|
|
863
|
+
* UTF-8, comme l'orchestrator les mesure.
|
|
864
|
+
*
|
|
865
|
+
* @example
|
|
866
|
+
* ```ts @import.meta.vitest
|
|
867
|
+
* const { DEFAULT_LIMITS } = await import('@orchestrator/contracts/protocol');
|
|
868
|
+
* const nodeType = { identifier: 'acme.ocr', version: '1.0.0', timeoutMs: 600_000, inputs: [], outputs: [], parameterSchema: {} };
|
|
869
|
+
* expect(declarationIssues([nodeType], 1, DEFAULT_LIMITS)).toStrictEqual([]);
|
|
870
|
+
* expect(declarationIssues([nodeType, nodeType], 1, DEFAULT_LIMITS)).toStrictEqual(['acme.ocr@1.0.0: declared twice']);
|
|
871
|
+
* ```
|
|
872
|
+
*/
|
|
873
|
+
function declarationIssues(nodeTypes, slots, limits) {
|
|
874
|
+
const issues = [];
|
|
875
|
+
if (nodeTypes.length > limits.maxNodeTypes) issues.push(`A declaration holds at most ${String(limits.maxNodeTypes)} node types; got ${String(nodeTypes.length)}`);
|
|
876
|
+
const seen = /* @__PURE__ */ new Set();
|
|
877
|
+
for (const nodeType of nodeTypes) {
|
|
878
|
+
const label = labelOf(nodeType);
|
|
879
|
+
if (Buffer.byteLength(JSON.stringify(nodeType.parameterSchema)) > limits.maxParameterSchemaBytes) issues.push(`${label} parameters: Parameter schema exceeds ${String(limits.maxParameterSchemaBytes)} bytes`);
|
|
880
|
+
if (seen.has(label)) issues.push(`${label}: declared twice`);
|
|
881
|
+
seen.add(label);
|
|
882
|
+
}
|
|
883
|
+
const bytes = Buffer.byteLength(JSON.stringify({
|
|
884
|
+
slots,
|
|
885
|
+
nodeTypes
|
|
886
|
+
})) + MESSAGE_ENVELOPE_BYTES;
|
|
887
|
+
if (bytes > limits.maxMessageBytes) issues.push(`The declaration takes ${String(bytes)} bytes, and a message holds at most ${String(limits.maxMessageBytes)}: split the nodes between several agents, or shorten their parameter schemas`);
|
|
888
|
+
return issues;
|
|
889
|
+
}
|
|
890
|
+
/** Les `details` du refus `invalid_declaration` de l'orchestrator (protocol.md § declare). */
|
|
891
|
+
const RefusalDetails = z.object({ faults: z.array(DeclarationFault) });
|
|
892
|
+
/**
|
|
893
|
+
* Les fautes d'une déclaration que l'orchestrator a refusée (`invalid_declaration`), lues dans les `details` de
|
|
894
|
+
* son refus : une ligne par faute, qui nomme le nœud, le champ, la règle et son code. Rien pour des `details`
|
|
895
|
+
* sans fautes lisibles.
|
|
896
|
+
*
|
|
897
|
+
* @example
|
|
898
|
+
* ```ts @import.meta.vitest
|
|
899
|
+
* const nodeType = { identifier: 'acme.ocr', version: '1.0.0', timeoutMs: 600_000, inputs: [], outputs: [], parameterSchema: {} };
|
|
900
|
+
* const fault = { index: 0, code: 'duplicate_node_type', path: [], message: 'Declared twice' };
|
|
901
|
+
* expect(faultLines([nodeType], { faults: [fault] })).toStrictEqual(['acme.ocr@1.0.0: Declared twice (duplicate_node_type)']);
|
|
902
|
+
* ```
|
|
903
|
+
*/
|
|
904
|
+
function faultLines(nodeTypes, details) {
|
|
905
|
+
return (RefusalDetails.safeParse(details).data?.faults ?? []).map(({ index, code, path, message }) => {
|
|
906
|
+
const declared = nodeTypes[index];
|
|
907
|
+
return `${[declared === void 0 ? `nodeTypes[${String(index)}]` : labelOf(declared), path.join(".")].filter((part) => part !== "").join(" ")}: ${message} (${code})`;
|
|
908
|
+
});
|
|
909
|
+
}
|
|
910
|
+
// src/held-step.ts
|
|
911
|
+
/** La borne du tampon : les lignes non acquittées d'un `Step` tiennent en 1 Mo. */
|
|
912
|
+
const MAX_BUFFERED_LOG_BYTES = 1048576;
|
|
913
|
+
/** Le plus grand lot de lignes d'un `log` (protocol.md § log). */
|
|
914
|
+
const MAX_BATCH_LINES = 4096;
|
|
915
|
+
/** Ce que coûte une ligne au tampon, en plus des octets de son message, comme au budget de l'orchestrator. */
|
|
916
|
+
const LINE_COST_BYTES = 64;
|
|
917
|
+
/** Le coût d'une ligne : une ligne vide ne s'accumule pas sans fin. */
|
|
918
|
+
function costOf(message) {
|
|
919
|
+
return Buffer.byteLength(message) + LINE_COST_BYTES;
|
|
920
|
+
}
|
|
921
|
+
/** Un `Step` tout juste attribué : aucune ligne, aucun résultat. */
|
|
922
|
+
function heldStep(stepId) {
|
|
923
|
+
return {
|
|
924
|
+
stepId,
|
|
925
|
+
interruption: new AbortController(),
|
|
926
|
+
lines: [],
|
|
927
|
+
bufferedBytes: 0,
|
|
928
|
+
lastSeq: 0,
|
|
929
|
+
droppedLines: 0,
|
|
930
|
+
delivering: false
|
|
931
|
+
};
|
|
932
|
+
}
|
|
933
|
+
/**
|
|
934
|
+
* Range une ligne de log dans le tampon du `Step`, à son `seq`. Le tampon plein, la ligne est jetée, et toutes
|
|
935
|
+
* les suivantes avec elle jusqu'au prochain acquittement, même une plus courte : `seq` continue de compter,
|
|
936
|
+
* donc le trou se voit. Un tampon vide prend toute ligne : aucun acquittement à venir ne le rouvrirait.
|
|
937
|
+
*
|
|
938
|
+
* @example
|
|
939
|
+
* ```ts @import.meta.vitest
|
|
940
|
+
* const step = heldStep('0199f3a2-7c41-7d2e-9b8a-5f0e6d4c3b2a');
|
|
941
|
+
* bufferLine(step, 'info', 'a'.repeat(MAX_BUFFERED_LOG_BYTES), '2026-11-23T09:30:00.000Z');
|
|
942
|
+
* bufferLine(step, 'info', 'dropped', '2026-11-23T09:30:01.000Z');
|
|
943
|
+
* bufferLine(step, 'info', '', '2026-11-23T09:30:02.000Z');
|
|
944
|
+
* expect(step.lines.map((line) => line.seq)).toStrictEqual([1]);
|
|
945
|
+
* expect(step).toMatchObject({ lastSeq: 3, droppedLines: 2 });
|
|
946
|
+
* ```
|
|
947
|
+
*/
|
|
948
|
+
function bufferLine(step, level, message, at) {
|
|
949
|
+
step.lastSeq += 1;
|
|
950
|
+
const bytes = costOf(message);
|
|
951
|
+
const full = step.lines.length > 0 && step.bufferedBytes + bytes > 1048576;
|
|
952
|
+
if (step.droppedLines > 0 || full) {
|
|
953
|
+
step.droppedLines += 1;
|
|
954
|
+
return;
|
|
955
|
+
}
|
|
956
|
+
step.lines.push({
|
|
957
|
+
seq: step.lastSeq,
|
|
958
|
+
level,
|
|
959
|
+
message,
|
|
960
|
+
at
|
|
961
|
+
});
|
|
962
|
+
step.bufferedBytes += bytes;
|
|
963
|
+
}
|
|
964
|
+
/**
|
|
965
|
+
* Le prochain lot d'un `log` : les premières lignes du tampon, 4 096 au plus, tant que leur JSON tient en
|
|
966
|
+
* `maxBytes` octets, ce qu'un message laisse aux lignes. Le lot prend toujours la première : aucun lot plus petit
|
|
967
|
+
* ne la ferait partir.
|
|
968
|
+
*
|
|
969
|
+
* @example
|
|
970
|
+
* ```ts @import.meta.vitest
|
|
971
|
+
* const step = heldStep('0199f3a2-7c41-7d2e-9b8a-5f0e6d4c3b2a');
|
|
972
|
+
* bufferLine(step, 'info', 'first', '2026-11-23T09:30:00.000Z');
|
|
973
|
+
* bufferLine(step, 'info', 'second', '2026-11-23T09:30:01.000Z');
|
|
974
|
+
* expect(nextBatch(step.lines, 100).map((line) => line.message)).toStrictEqual(['first']);
|
|
975
|
+
* ```
|
|
976
|
+
*/
|
|
977
|
+
function nextBatch(lines, maxBytes) {
|
|
978
|
+
let bytes = 0;
|
|
979
|
+
let count = 0;
|
|
980
|
+
for (const line of lines.slice(0, MAX_BATCH_LINES)) {
|
|
981
|
+
bytes += Buffer.byteLength(JSON.stringify(line)) + 1;
|
|
982
|
+
if (count > 0 && bytes > maxBytes) break;
|
|
983
|
+
count += 1;
|
|
984
|
+
}
|
|
985
|
+
return lines.slice(0, count);
|
|
986
|
+
}
|
|
987
|
+
/**
|
|
988
|
+
* Retire du tampon les lignes que l'orchestrator a enregistrées, jusqu'à `seq` compris. Des lignes ont été
|
|
989
|
+
* jetées depuis : une ligne `warn` donne leur nombre, à la suite, et le tampon reprend.
|
|
990
|
+
*
|
|
991
|
+
* @example
|
|
992
|
+
* ```ts @import.meta.vitest
|
|
993
|
+
* const step = heldStep('0199f3a2-7c41-7d2e-9b8a-5f0e6d4c3b2a');
|
|
994
|
+
* bufferLine(step, 'info', 'kept', '2026-11-23T09:30:00.000Z');
|
|
995
|
+
* bufferLine(step, 'info', 'sent later', '2026-11-23T09:30:01.000Z');
|
|
996
|
+
* acknowledgeLines(step, 1, '2026-11-23T09:30:02.000Z');
|
|
997
|
+
* expect(step.lines.map((line) => line.message)).toStrictEqual(['sent later']);
|
|
998
|
+
* ```
|
|
999
|
+
*/
|
|
1000
|
+
function acknowledgeLines(step, seq, at) {
|
|
1001
|
+
step.lines = step.lines.filter((line) => line.seq > seq);
|
|
1002
|
+
if (step.droppedLines > 0) {
|
|
1003
|
+
step.lastSeq += 1;
|
|
1004
|
+
step.lines.push({
|
|
1005
|
+
seq: step.lastSeq,
|
|
1006
|
+
level: "warn",
|
|
1007
|
+
message: `${String(step.droppedLines)} log lines dropped: the agent held more than ${String(MAX_BUFFERED_LOG_BYTES)} bytes of lines the orchestrator had not acknowledged`,
|
|
1008
|
+
at
|
|
1009
|
+
});
|
|
1010
|
+
step.droppedLines = 0;
|
|
1011
|
+
}
|
|
1012
|
+
step.bufferedBytes = step.lines.reduce((sum, line) => sum + costOf(line.message), 0);
|
|
1013
|
+
}
|
|
1014
|
+
// src/step.ts
|
|
1015
|
+
/** Ce que le SDK dit à la fonction d'un nœud, par `signal.reason`, pour chaque motif d'un `cancel`. */
|
|
1016
|
+
const INTERRUPTION_MESSAGES = {
|
|
1017
|
+
execution_cancelled: "A user cancelled the Execution.",
|
|
1018
|
+
execution_failed: "Another Step of the Execution failed.",
|
|
1019
|
+
execution_succeeded: "The Execution reached its End while this Step was still running.",
|
|
1020
|
+
race_lost: "Another branch won the race of a Join(any).",
|
|
1021
|
+
timeout: "The Step exceeded its timeout."
|
|
1022
|
+
};
|
|
1023
|
+
/**
|
|
1024
|
+
* La raison de l'interruption d'un `Step` que l'orchestrator annule, ou dont le `timeout` est dépassé : une
|
|
1025
|
+
* `AgentError`, dont le code est le `reason` du `cancel` (sdk.md § Annulation et timeout).
|
|
1026
|
+
*
|
|
1027
|
+
* @example
|
|
1028
|
+
* ```ts @import.meta.vitest
|
|
1029
|
+
* expect(interruption('race_lost')).toMatchObject({ code: 'race_lost', message: 'Another branch won the race of a Join(any).' });
|
|
1030
|
+
* ```
|
|
1031
|
+
*/
|
|
1032
|
+
function interruption(reason) {
|
|
1033
|
+
return new AgentError(reason, INTERRUPTION_MESSAGES[reason]);
|
|
1034
|
+
}
|
|
1035
|
+
/**
|
|
1036
|
+
* Le texte d'une valeur que la fonction d'un nœud lève ou logue. Une valeur dont la lecture lève, un objet sans
|
|
1037
|
+
* prototype par exemple, donne un texte fixe : ni un log ni un échec ne fait tomber l'agent.
|
|
1038
|
+
*/
|
|
1039
|
+
function textOf(read) {
|
|
1040
|
+
try {
|
|
1041
|
+
return String(read());
|
|
1042
|
+
} catch {
|
|
1043
|
+
return "[unreadable value]";
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
/**
|
|
1047
|
+
* Un texte que l'orchestrator range, coupé à son plafond : U+0000 et un surrogate isolé, que Postgres refuse,
|
|
1048
|
+
* y deviennent U+FFFD, puis le texte est coupé à `maxBytes` octets UTF-8, sur une frontière de caractère. Sert
|
|
1049
|
+
* chaque ligne de log et chaque message d'échec (sdk.md § Sorties et échec).
|
|
1050
|
+
*
|
|
1051
|
+
* @example
|
|
1052
|
+
* ```ts @import.meta.vitest
|
|
1053
|
+
* expect(storableText('a\u0000b', 4096)).toBe('a\ufffdb');
|
|
1054
|
+
* expect(storableText('ééé', 5)).toBe('éé');
|
|
1055
|
+
* ```
|
|
1056
|
+
*/
|
|
1057
|
+
function storableText(text, maxBytes) {
|
|
1058
|
+
const storable = textOf(() => text).replaceAll("\0", "�").replaceAll(/\p{Cs}/gu, "�");
|
|
1059
|
+
const bytes = Buffer.from(storable);
|
|
1060
|
+
if (bytes.length <= maxBytes) return storable;
|
|
1061
|
+
return new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes.subarray(0, maxBytes), { stream: true });
|
|
1062
|
+
}
|
|
1063
|
+
/** Une ligne par issue d'une lecture : le champ, dans les mots de la définition du nœud, puis la règle. */
|
|
1064
|
+
function issueLines(field, error) {
|
|
1065
|
+
return (error?.issues ?? []).map((issue) => `${[field, ...issue.path].join(".")}: ${issue.message}`);
|
|
1066
|
+
}
|
|
1067
|
+
/**
|
|
1068
|
+
* Exécute un `Step` attribué, et rend son résultat (sdk.md § Exécuter un Step) : les entrées et les paramètres
|
|
1069
|
+
* reçus sont validés par les schémas du nœud, qui remplissent les `.default()` ; la fonction du nœud est
|
|
1070
|
+
* appelée ; ses sorties sont validées par leurs schémas, puis vérifiées, valeurs JSON que l'orchestrator range,
|
|
1071
|
+
* et mesurées, en octets de leur JSON, contre `limits.maxOutputBytes`. Tout refus, comme une exception de la
|
|
1072
|
+
* fonction, rend un résultat `failed`, dont le message nomme le champ ; `node` absent, l'agent ne définit pas le
|
|
1073
|
+
* `NodeType` de l'assignation.
|
|
1074
|
+
*/
|
|
1075
|
+
async function stepResult(node, assign, handles, limits) {
|
|
1076
|
+
const { stepId, executionId, nodeType } = assign;
|
|
1077
|
+
const failed = (message) => ({
|
|
1078
|
+
stepId,
|
|
1079
|
+
status: "failed",
|
|
1080
|
+
message: storableText(message, limits.maxFailureMessageBytes)
|
|
1081
|
+
});
|
|
1082
|
+
if (node === void 0) return failed(`This agent does not define the node type ${nodeType.identifier}@${nodeType.version}`);
|
|
1083
|
+
const { definition } = node;
|
|
1084
|
+
try {
|
|
1085
|
+
const inputs = await z.strictObject({ ...definition.inputs }).safeParseAsync(assign.inputs);
|
|
1086
|
+
const parameters = await z.strictObject({ ...definition.parameters }).safeParseAsync(assign.parameters);
|
|
1087
|
+
if (!inputs.success || !parameters.success) return failed([...issueLines("inputs", inputs.error), ...issueLines("parameters", parameters.error)].join("\n"));
|
|
1088
|
+
const returned = await definition.run({
|
|
1089
|
+
inputs: inputs.data,
|
|
1090
|
+
parameters: parameters.data,
|
|
1091
|
+
...handles,
|
|
1092
|
+
executionId,
|
|
1093
|
+
stepId
|
|
1094
|
+
});
|
|
1095
|
+
const outputs = await z.strictObject({ ...definition.outputs }).safeParseAsync(returned ?? {});
|
|
1096
|
+
if (!outputs.success) return failed(issueLines("outputs", outputs.error).join("\n"));
|
|
1097
|
+
const present = Object.fromEntries(Object.entries(outputs.data).filter(([, value]) => value !== void 0));
|
|
1098
|
+
const result = Result.safeParse({
|
|
1099
|
+
stepId,
|
|
1100
|
+
status: "succeeded",
|
|
1101
|
+
outputs: present
|
|
1102
|
+
});
|
|
1103
|
+
if (!result.success) return failed(result.error.issues.map((issue) => `${issue.path.join(".")}: not a storable JSON value (${issue.message})`).join("\n"));
|
|
1104
|
+
if (Buffer.byteLength(JSON.stringify(present)) > limits.maxOutputBytes) return failed(`Step outputs exceed the limit of ${String(limits.maxOutputBytes)} bytes`);
|
|
1105
|
+
return result.data;
|
|
1106
|
+
} catch (error) {
|
|
1107
|
+
return failed(textOf(() => error instanceof Error ? error.message : error));
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
// src/run-agent.ts
|
|
1111
|
+
/**
|
|
1112
|
+
* Un message reçu de l'orchestrator, dans son enveloppe de birpc (protocol.md § Transport) : un appel, ou la
|
|
1113
|
+
* réponse à un appel. Une clé inconnue est ignorée, comme dans chaque message que lit l'agent.
|
|
1114
|
+
*/
|
|
1115
|
+
const Envelope = z.union([z.object({
|
|
1116
|
+
t: z.literal("q"),
|
|
1117
|
+
i: z.string().optional(),
|
|
1118
|
+
m: z.string(),
|
|
1119
|
+
a: z.array(z.unknown())
|
|
1120
|
+
}), z.object({
|
|
1121
|
+
t: z.literal("s"),
|
|
1122
|
+
i: z.string(),
|
|
1123
|
+
r: z.unknown().optional(),
|
|
1124
|
+
e: z.unknown().optional()
|
|
1125
|
+
})]);
|
|
1126
|
+
/**
|
|
1127
|
+
* Lit un message reçu de l'orchestrator ; rien pour un message illisible : une trame binaire, du JSON
|
|
1128
|
+
* invalide, ou une autre enveloppe. birpc lèverait sur chacun, hors de portée du SDK.
|
|
1129
|
+
*
|
|
1130
|
+
* @example
|
|
1131
|
+
* ```ts @import.meta.vitest
|
|
1132
|
+
* expect(readEnvelope('{"t":"q","i":"k3","m":"heartbeat","a":[]}')).toStrictEqual({ t: 'q', i: 'k3', m: 'heartbeat', a: [] });
|
|
1133
|
+
* expect(['not json', 'null', '{"t":"x"}', new Blob(['{}'])].map(readEnvelope)).toStrictEqual([undefined, undefined, undefined, undefined]);
|
|
1134
|
+
* ```
|
|
1135
|
+
*/
|
|
1136
|
+
function readEnvelope(data) {
|
|
1137
|
+
try {
|
|
1138
|
+
return Envelope.safeParse(JSON.parse(String(data))).data;
|
|
1139
|
+
} catch {
|
|
1140
|
+
return;
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
/**
|
|
1144
|
+
* Runs an agent: it connects to the orchestrator, declares its nodes and its slots, runs the Steps it is
|
|
1145
|
+
* assigned and keeps its connection through network cuts. The promise lasts as long as the agent: it resolves
|
|
1146
|
+
* after a graceful shutdown, requested by `signal`, and rejects with an `AgentError` when an option is refused,
|
|
1147
|
+
* before any connection, or when the orchestrator refuses the agent for good, an unknown token for example.
|
|
1148
|
+
*
|
|
1149
|
+
* @example
|
|
1150
|
+
* ```ts @import.meta.vitest
|
|
1151
|
+
* const refused = runAgent({ url: 'https://orchestrator.example.com', auth: { kind: 'agent', token: 'token_agent_x' }, nodes: [] });
|
|
1152
|
+
* await expect(refused).rejects.toMatchObject({ code: 'invalid_agent_options', message: 'url: Expected a ws:// or wss:// URL, without a fragment' });
|
|
1153
|
+
* ```
|
|
1154
|
+
*/
|
|
1155
|
+
async function runAgent(options) {
|
|
1156
|
+
await connectAgent(options, "1.0").done;
|
|
1157
|
+
}
|
|
1158
|
+
/** Le refus d'une redéclaration par un agent qui s'arrête, ou arrêté. */
|
|
1159
|
+
function agentStopped() {
|
|
1160
|
+
return new AgentError("agent_stopped", "The agent is stopping: it declares no node any more.");
|
|
1161
|
+
}
|
|
1162
|
+
/**
|
|
1163
|
+
* `runAgent`, avec deux choses de plus, hors de l'API publique : la version du protocole en paramètre, pour un
|
|
1164
|
+
* test de conformité qui en annonce une que l'orchestrator refuse, et `redeclare`, pour le mode dev de la CLI.
|
|
1165
|
+
* Des options refusées lèvent.
|
|
1166
|
+
*/
|
|
1167
|
+
function connectAgent(options, protocolVersion) {
|
|
1168
|
+
const slots = checkedSlots(options);
|
|
1169
|
+
const { url, auth, signal } = options;
|
|
1170
|
+
const emit = guardedListener(options.onEvent ?? writeEvent);
|
|
1171
|
+
let redeclare = () => Promise.reject(agentStopped());
|
|
1172
|
+
if (signal?.aborted === true) return {
|
|
1173
|
+
done: Promise.resolve(),
|
|
1174
|
+
redeclare
|
|
1175
|
+
};
|
|
1176
|
+
return {
|
|
1177
|
+
done: new Promise((resolve, reject) => {
|
|
1178
|
+
let nodes = options.nodes;
|
|
1179
|
+
let wanted;
|
|
1180
|
+
let ended = false;
|
|
1181
|
+
const held = /* @__PURE__ */ new Map();
|
|
1182
|
+
let connectionId;
|
|
1183
|
+
let current;
|
|
1184
|
+
let retry;
|
|
1185
|
+
let attempt = 0;
|
|
1186
|
+
let draining = false;
|
|
1187
|
+
const limits = { ...DEFAULT_LIMITS };
|
|
1188
|
+
/** Quitte le socket en cours, sans rien décider de la suite. */
|
|
1189
|
+
function leave(link, closure) {
|
|
1190
|
+
current = void 0;
|
|
1191
|
+
clearTimeout(link.timer);
|
|
1192
|
+
link.rpc.$close();
|
|
1193
|
+
if (link.socket.readyState !== WebSocket.CLOSED) link.socket.close(closure.code, closure.reason);
|
|
1194
|
+
}
|
|
1195
|
+
/** Met fin à l'agent : plus de socket, plus d'essai, plus d'écoute de `signal`. */
|
|
1196
|
+
function end() {
|
|
1197
|
+
ended = true;
|
|
1198
|
+
wanted?.settle(agentStopped());
|
|
1199
|
+
wanted = void 0;
|
|
1200
|
+
clearTimeout(retry);
|
|
1201
|
+
signal?.removeEventListener("abort", stop);
|
|
1202
|
+
if (current !== void 0) leave(current, {
|
|
1203
|
+
code: 1e3,
|
|
1204
|
+
reason: ""
|
|
1205
|
+
});
|
|
1206
|
+
}
|
|
1207
|
+
/** Interrompt un `Step` et le lâche : ce que sa fonction rend, lève ou écrit ensuite est jeté. */
|
|
1208
|
+
function abandon(step, reason) {
|
|
1209
|
+
held.delete(step.stepId);
|
|
1210
|
+
clearTimeout(step.timeout);
|
|
1211
|
+
step.interruption.abort(reason);
|
|
1212
|
+
}
|
|
1213
|
+
function abandonAll(reason) {
|
|
1214
|
+
for (const step of [...held.values()]) abandon(step, reason);
|
|
1215
|
+
}
|
|
1216
|
+
/**
|
|
1217
|
+
* La fin d'un socket, la seule : fermé par l'orchestrator, ou quitté par le SDK sur un refus, un appel
|
|
1218
|
+
* non acquitté ou un délai. Une fermeture définitive rejette `runAgent` ; toute autre est une coupure, que
|
|
1219
|
+
* l'essai suivant reprend (sdk.md § Connexion). Un socket déjà quitté n'y passe plus : c'est le cas de
|
|
1220
|
+
* `superseded`, la connexion vivant alors sur son nouveau socket.
|
|
1221
|
+
*/
|
|
1222
|
+
function lose(link, closure) {
|
|
1223
|
+
if (link !== current) return;
|
|
1224
|
+
const error = definitiveError(closure, link.ready ? void 0 : nodes.length);
|
|
1225
|
+
leave(link, closure);
|
|
1226
|
+
if (error !== void 0) {
|
|
1227
|
+
abandonAll(error);
|
|
1228
|
+
end();
|
|
1229
|
+
reject(error);
|
|
1230
|
+
return;
|
|
1231
|
+
}
|
|
1232
|
+
if (closure.code === CLOSE_CODES.unknown_connection) {
|
|
1233
|
+
abandonAll(new AgentError("step_abandoned", "The connection expired on the orchestrator."));
|
|
1234
|
+
connectionId = void 0;
|
|
1235
|
+
if (draining) {
|
|
1236
|
+
end();
|
|
1237
|
+
resolve();
|
|
1238
|
+
return;
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
const retryInMs = retryDelayMs(attempt);
|
|
1242
|
+
attempt += 1;
|
|
1243
|
+
emit({
|
|
1244
|
+
type: "disconnected",
|
|
1245
|
+
code: closure.code,
|
|
1246
|
+
reason: closure.reason,
|
|
1247
|
+
retryInMs
|
|
1248
|
+
});
|
|
1249
|
+
retry = setTimeout(connect, retryInMs);
|
|
1250
|
+
}
|
|
1251
|
+
/** Sans aucun message pendant le silence toléré, le SDK ferme son socket et reprend sa connexion. */
|
|
1252
|
+
function watchSilence(link) {
|
|
1253
|
+
clearTimeout(link.timer);
|
|
1254
|
+
link.timer = setTimeout(() => {
|
|
1255
|
+
lose(link, {
|
|
1256
|
+
code: CLOSE_CODES.heartbeat_timeout,
|
|
1257
|
+
reason: "heartbeat_timeout"
|
|
1258
|
+
});
|
|
1259
|
+
}, link.silenceMs);
|
|
1260
|
+
}
|
|
1261
|
+
/** Dernier pas de l'arrêt propre : plus d'attribution, plus de `Step` tenu, l'agent annonce son arrêt. */
|
|
1262
|
+
function leaveWhenDrained() {
|
|
1263
|
+
const link = current;
|
|
1264
|
+
if (!draining || link === void 0 || !link.emptied || held.size > 0) return;
|
|
1265
|
+
link.rpc.bye().then(() => {
|
|
1266
|
+
end();
|
|
1267
|
+
resolve();
|
|
1268
|
+
}, (error) => {
|
|
1269
|
+
lose(link, closureOf(error));
|
|
1270
|
+
});
|
|
1271
|
+
}
|
|
1272
|
+
/** Arrêt propre, sur une connexion prête : la déclaration vide arrête les attributions, puis `bye`. */
|
|
1273
|
+
async function drain(link) {
|
|
1274
|
+
if (!link.emptied) try {
|
|
1275
|
+
await link.rpc.declare({
|
|
1276
|
+
slots,
|
|
1277
|
+
nodeTypes: []
|
|
1278
|
+
});
|
|
1279
|
+
link.emptied = true;
|
|
1280
|
+
} catch (error) {
|
|
1281
|
+
lose(link, closureOf(error));
|
|
1282
|
+
return;
|
|
1283
|
+
}
|
|
1284
|
+
leaveWhenDrained();
|
|
1285
|
+
}
|
|
1286
|
+
/**
|
|
1287
|
+
* Envoie la déclaration demandée, sur une connexion prête, donc avec les plafonds que son `hello` a reçus :
|
|
1288
|
+
* au-delà, rien ne part, et la demande est refusée. Acquittée, ses nœuds deviennent ceux de l'agent. Refusée
|
|
1289
|
+
* par l'orchestrator, l'ancienne reste en place des deux côtés, et la connexion reste ouverte
|
|
1290
|
+
* (protocol.md § Déclaration). Un appel non acquitté quitte le socket : la reprise la renvoie.
|
|
1291
|
+
*/
|
|
1292
|
+
async function announce(link) {
|
|
1293
|
+
const sent = wanted;
|
|
1294
|
+
if (sent === void 0 || draining) return;
|
|
1295
|
+
const nodeTypes = sent.nodes.map((node) => node.nodeType);
|
|
1296
|
+
const issues = declarationIssues(nodeTypes, slots, limits);
|
|
1297
|
+
if (issues.length > 0) {
|
|
1298
|
+
wanted = void 0;
|
|
1299
|
+
sent.settle(new AgentError("invalid_declaration", issues.join("\n")));
|
|
1300
|
+
return;
|
|
1301
|
+
}
|
|
1302
|
+
try {
|
|
1303
|
+
await link.rpc.declare({
|
|
1304
|
+
slots,
|
|
1305
|
+
nodeTypes
|
|
1306
|
+
});
|
|
1307
|
+
} catch (error) {
|
|
1308
|
+
const closure = closureOf(error);
|
|
1309
|
+
if (closure.refusal?.code !== "invalid_declaration") {
|
|
1310
|
+
lose(link, closure);
|
|
1311
|
+
return;
|
|
1312
|
+
}
|
|
1313
|
+
wanted = void 0;
|
|
1314
|
+
sent.settle(new AgentError("invalid_declaration", closure.refusal.message, closure.refusal.details));
|
|
1315
|
+
return;
|
|
1316
|
+
}
|
|
1317
|
+
nodes = sent.nodes;
|
|
1318
|
+
link.emptied = nodeTypes.length === 0;
|
|
1319
|
+
wanted = void 0;
|
|
1320
|
+
sent.settle();
|
|
1321
|
+
}
|
|
1322
|
+
/**
|
|
1323
|
+
* Livre ce qu'un `Step` a de prêt, sur une connexion prête : ses lignes non acquittées, puis son
|
|
1324
|
+
* résultat, une fois toutes ses lignes acquittées. Rien ne part d'un `Step` interrompu, lâché ou encore
|
|
1325
|
+
* tenu : ce que sa fonction écrit, rend ou lève est jeté. Un appel non acquitté quitte le socket : la
|
|
1326
|
+
* reprise renvoie ce qui reste.
|
|
1327
|
+
*/
|
|
1328
|
+
async function deliver(step) {
|
|
1329
|
+
const link = current;
|
|
1330
|
+
if (link === void 0 || !link.ready || step.delivering) return;
|
|
1331
|
+
step.delivering = true;
|
|
1332
|
+
const awaited = () => held.get(step.stepId) === step && !step.interruption.signal.aborted;
|
|
1333
|
+
try {
|
|
1334
|
+
while (awaited() && step.lines.length > 0) {
|
|
1335
|
+
const lines = nextBatch(step.lines, limits.maxMessageBytes - MESSAGE_ENVELOPE_BYTES);
|
|
1336
|
+
await link.rpc.log({
|
|
1337
|
+
stepId: step.stepId,
|
|
1338
|
+
lines
|
|
1339
|
+
});
|
|
1340
|
+
acknowledgeLines(step, lines.at(-1)?.seq ?? 0, (/* @__PURE__ */ new Date()).toISOString());
|
|
1341
|
+
}
|
|
1342
|
+
if (awaited() && step.result !== void 0) {
|
|
1343
|
+
await link.rpc.result(step.result);
|
|
1344
|
+
if (held.delete(step.stepId)) leaveWhenDrained();
|
|
1345
|
+
}
|
|
1346
|
+
} catch (error) {
|
|
1347
|
+
lose(link, closureOf(error));
|
|
1348
|
+
} finally {
|
|
1349
|
+
step.delivering = false;
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
/**
|
|
1353
|
+
* Un `cancel` de l'orchestrator : le résultat du `Step` n'est plus attendu, sa fonction est interrompue,
|
|
1354
|
+
* et l'agent le lâche. Un `Step` que l'agent ne tient plus est ignoré.
|
|
1355
|
+
*/
|
|
1356
|
+
function interrupt(stepId, reason) {
|
|
1357
|
+
const step = held.get(stepId);
|
|
1358
|
+
if (step === void 0) return;
|
|
1359
|
+
abandon(step, interruption(reason));
|
|
1360
|
+
leaveWhenDrained();
|
|
1361
|
+
}
|
|
1362
|
+
/** Exécute un `Step` attribué, puis livre son résultat. */
|
|
1363
|
+
function run(assign) {
|
|
1364
|
+
const { stepId, nodeType, timeoutMs } = assign;
|
|
1365
|
+
const step = heldStep(stepId);
|
|
1366
|
+
held.set(stepId, step);
|
|
1367
|
+
step.timeout = setTimeout(() => {
|
|
1368
|
+
step.interruption.abort(interruption("timeout"));
|
|
1369
|
+
}, timeoutMs);
|
|
1370
|
+
const log = (level) => (message) => {
|
|
1371
|
+
const line = storableText(message, limits.maxLogLineBytes);
|
|
1372
|
+
bufferLine(step, level, line, (/* @__PURE__ */ new Date()).toISOString());
|
|
1373
|
+
deliver(step);
|
|
1374
|
+
};
|
|
1375
|
+
stepResult(nodes.find((defined) => defined.nodeType.identifier === nodeType.identifier && defined.nodeType.version === nodeType.version), assign, {
|
|
1376
|
+
signal: step.interruption.signal,
|
|
1377
|
+
log: {
|
|
1378
|
+
info: log("info"),
|
|
1379
|
+
warn: log("warn"),
|
|
1380
|
+
error: log("error")
|
|
1381
|
+
}
|
|
1382
|
+
}, limits).then((result) => {
|
|
1383
|
+
clearTimeout(step.timeout);
|
|
1384
|
+
step.result = result;
|
|
1385
|
+
deliver(step);
|
|
1386
|
+
});
|
|
1387
|
+
}
|
|
1388
|
+
/**
|
|
1389
|
+
* La réponse à `hello` : la connexion est prête. Des `Step` tenus à l'envoi de `hello`, `sent`, seuls
|
|
1390
|
+
* restent ceux que l'orchestrator attend encore, à partir de la dernière ligne qu'il a enregistrée. Un
|
|
1391
|
+
* `Step` attribué depuis reste : son `assign` peut arriver avec la réponse, et être lu avant elle.
|
|
1392
|
+
*/
|
|
1393
|
+
function accept(link, response, sent) {
|
|
1394
|
+
link.ready = true;
|
|
1395
|
+
link.silenceMs = response.heartbeat.timeoutMs;
|
|
1396
|
+
Object.assign(limits, response.limits);
|
|
1397
|
+
watchSilence(link);
|
|
1398
|
+
attempt = 0;
|
|
1399
|
+
const resumed = response.connectionId === connectionId;
|
|
1400
|
+
connectionId = response.connectionId;
|
|
1401
|
+
emit({
|
|
1402
|
+
type: "connected",
|
|
1403
|
+
connectionId,
|
|
1404
|
+
resumed
|
|
1405
|
+
});
|
|
1406
|
+
for (const step of sent) {
|
|
1407
|
+
const expected = response.steps.find(({ stepId }) => stepId === step.stepId);
|
|
1408
|
+
if (expected === void 0) abandon(step, new AgentError("step_abandoned", "The orchestrator no longer awaits this Step from this connection."));
|
|
1409
|
+
else acknowledgeLines(step, expected.lastLogSeq, (/* @__PURE__ */ new Date()).toISOString());
|
|
1410
|
+
}
|
|
1411
|
+
for (const step of held.values()) deliver(step);
|
|
1412
|
+
if (draining) drain(link);
|
|
1413
|
+
announce(link);
|
|
1414
|
+
}
|
|
1415
|
+
/** Ouvre un socket et y appelle `hello` : une nouvelle connexion, ou la reprise de celle que l'agent tient. */
|
|
1416
|
+
function connect() {
|
|
1417
|
+
const socket = new WebSocket(url);
|
|
1418
|
+
let receive = () => void 0;
|
|
1419
|
+
const link = {
|
|
1420
|
+
socket,
|
|
1421
|
+
ready: false,
|
|
1422
|
+
emptied: false,
|
|
1423
|
+
silenceMs: 0,
|
|
1424
|
+
rpc: createBirpc({
|
|
1425
|
+
heartbeat() {},
|
|
1426
|
+
assign(message) {
|
|
1427
|
+
run(Assign.parse(message));
|
|
1428
|
+
},
|
|
1429
|
+
cancel(message) {
|
|
1430
|
+
const { stepId, reason } = Cancel.parse(message);
|
|
1431
|
+
interrupt(stepId, reason);
|
|
1432
|
+
}
|
|
1433
|
+
}, {
|
|
1434
|
+
post: (data) => {
|
|
1435
|
+
socket.send(data);
|
|
1436
|
+
},
|
|
1437
|
+
on: (listener) => {
|
|
1438
|
+
receive = listener;
|
|
1439
|
+
},
|
|
1440
|
+
serialize: JSON.stringify,
|
|
1441
|
+
deserialize: (envelope) => envelope,
|
|
1442
|
+
timeout: -1
|
|
1443
|
+
})
|
|
1444
|
+
};
|
|
1445
|
+
current = link;
|
|
1446
|
+
link.timer = setTimeout(() => {
|
|
1447
|
+
lose(link, {
|
|
1448
|
+
code: CLOSE_CODES.handshake_timeout,
|
|
1449
|
+
reason: "handshake_timeout"
|
|
1450
|
+
});
|
|
1451
|
+
}, HELLO_TIMEOUT_MS);
|
|
1452
|
+
socket.addEventListener("open", () => {
|
|
1453
|
+
const sent = [...held.values()];
|
|
1454
|
+
const nodeTypes = draining ? [] : nodes.map((node) => node.nodeType);
|
|
1455
|
+
link.rpc.hello({
|
|
1456
|
+
protocolVersion,
|
|
1457
|
+
auth,
|
|
1458
|
+
declaration: {
|
|
1459
|
+
slots,
|
|
1460
|
+
nodeTypes
|
|
1461
|
+
},
|
|
1462
|
+
...connectionId === void 0 ? {} : { resume: {
|
|
1463
|
+
connectionId,
|
|
1464
|
+
heldStepIds: sent.map(({ stepId }) => stepId)
|
|
1465
|
+
} }
|
|
1466
|
+
}).then((response) => {
|
|
1467
|
+
link.emptied = nodeTypes.length === 0;
|
|
1468
|
+
accept(link, HelloResponse.parse(response), sent);
|
|
1469
|
+
}).catch((error) => {
|
|
1470
|
+
lose(link, closureOf(error));
|
|
1471
|
+
});
|
|
1472
|
+
});
|
|
1473
|
+
socket.addEventListener("message", (event) => {
|
|
1474
|
+
if (link !== current) return;
|
|
1475
|
+
const envelope = readEnvelope(event.data);
|
|
1476
|
+
if (envelope === void 0) {
|
|
1477
|
+
lose(link, {
|
|
1478
|
+
code: 1e3,
|
|
1479
|
+
reason: "unreadable_message"
|
|
1480
|
+
});
|
|
1481
|
+
return;
|
|
1482
|
+
}
|
|
1483
|
+
if (link.ready) watchSilence(link);
|
|
1484
|
+
receive(envelope);
|
|
1485
|
+
});
|
|
1486
|
+
socket.addEventListener("close", (event) => {
|
|
1487
|
+
lose(link, {
|
|
1488
|
+
code: event.code,
|
|
1489
|
+
reason: event.reason
|
|
1490
|
+
});
|
|
1491
|
+
});
|
|
1492
|
+
}
|
|
1493
|
+
/** `signal` est interrompu : l'arrêt propre commence (sdk.md § Arrêt). */
|
|
1494
|
+
function stop() {
|
|
1495
|
+
if (connectionId === void 0) {
|
|
1496
|
+
end();
|
|
1497
|
+
resolve();
|
|
1498
|
+
return;
|
|
1499
|
+
}
|
|
1500
|
+
draining = true;
|
|
1501
|
+
const runningSteps = [...held.values()].filter((step) => step.result === void 0).length;
|
|
1502
|
+
emit({
|
|
1503
|
+
type: "draining",
|
|
1504
|
+
runningSteps
|
|
1505
|
+
});
|
|
1506
|
+
if (current?.ready === true) drain(current);
|
|
1507
|
+
}
|
|
1508
|
+
redeclare = (next) => new Promise((resolveDeclared, rejectDeclared) => {
|
|
1509
|
+
if (ended || draining) {
|
|
1510
|
+
rejectDeclared(agentStopped());
|
|
1511
|
+
return;
|
|
1512
|
+
}
|
|
1513
|
+
if (wanted !== void 0) {
|
|
1514
|
+
rejectDeclared(new AgentError("declaration_pending", "The previous declaration is not acknowledged yet."));
|
|
1515
|
+
return;
|
|
1516
|
+
}
|
|
1517
|
+
wanted = {
|
|
1518
|
+
nodes: next,
|
|
1519
|
+
settle: (refusal) => {
|
|
1520
|
+
if (refusal === void 0) resolveDeclared();
|
|
1521
|
+
else rejectDeclared(refusal);
|
|
1522
|
+
}
|
|
1523
|
+
};
|
|
1524
|
+
if (current?.ready === true) announce(current);
|
|
1525
|
+
});
|
|
1526
|
+
signal?.addEventListener("abort", stop);
|
|
1527
|
+
connect();
|
|
1528
|
+
}),
|
|
1529
|
+
redeclare: (next) => redeclare(next)
|
|
1530
|
+
};
|
|
1531
|
+
}
|
|
1532
|
+
export { DEFAULT_LIMITS as a, faultLines as i, runAgent as n, NodeType as o, declarationIssues as r, AgentError as s, connectAgent as t };
|