@opscompass/harness-client 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,4534 @@
1
+ // packages/harness-client/src/client-context.ts
2
+ var invalid = () => {
3
+ throw new Error("Invalid client or page context.");
4
+ };
5
+ function fields(value, keys) {
6
+ if (!value || typeof value !== "object" || Array.isArray(value)) return invalid();
7
+ const descriptors = Object.getOwnPropertyDescriptors(value);
8
+ if (Reflect.ownKeys(value).some((key) => typeof key !== "string" || !keys.includes(key))) return invalid();
9
+ const result = {};
10
+ for (const [key, descriptor] of Object.entries(descriptors)) {
11
+ if (!("value" in descriptor)) return invalid();
12
+ result[key] = descriptor.value;
13
+ }
14
+ return result;
15
+ }
16
+ function text(value, limit, identifier2 = true) {
17
+ if (typeof value !== "string" || !value.trim() || value.length > limit || /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u.test(value)) return invalid();
18
+ if (identifier2 && !/^[A-Za-z0-9][A-Za-z0-9._:/ -]*$/u.test(value)) return invalid();
19
+ return value;
20
+ }
21
+ function snapshotClientContext(value) {
22
+ if (value === void 0) throw new Error("Client context is required.");
23
+ const data = fields(value, ["clients"]);
24
+ if (!Array.isArray(data.clients)) return invalid();
25
+ const entries2 = Object.getOwnPropertyDescriptors(data.clients);
26
+ const length = entries2.length?.value;
27
+ if (!Number.isInteger(length) || length < 1 || length > 4) return invalid();
28
+ const keys = ["length", ...Array.from({ length }, (_, i) => String(i))];
29
+ if (Reflect.ownKeys(data.clients).some((key) => typeof key !== "string" || !keys.includes(key))) return invalid();
30
+ const clients = [];
31
+ for (let index = 0; index < length; index++) {
32
+ const entry = entries2[String(index)];
33
+ if (!entry || !("value" in entry)) return invalid();
34
+ const item = fields(entry.value, ["id", "version"]);
35
+ const id = text(item.id, 80);
36
+ if (clients.some((client) => client.id === id)) return invalid();
37
+ clients.push(Object.freeze({ id, ..."version" in item ? { version: text(item.version, 64) } : {} }));
38
+ }
39
+ return Object.freeze({ clients: Object.freeze(clients) });
40
+ }
41
+ function snapshotPageContext(value) {
42
+ if (value === void 0) return void 0;
43
+ const item = fields(value, ["id", "title"]);
44
+ return Object.freeze({ id: text(item.id, 80), ..."title" in item ? { title: text(item.title, 160, false) } : {} });
45
+ }
46
+
47
+ // packages/harness-client/node_modules/@earendil-works/pi-ai/dist/utils/event-stream.js
48
+ var FifoQueue = class {
49
+ incoming = [];
50
+ outgoing = [];
51
+ get length() {
52
+ return this.incoming.length + this.outgoing.length;
53
+ }
54
+ enqueue(value) {
55
+ this.incoming.push(value);
56
+ }
57
+ dequeue() {
58
+ if (this.outgoing.length === 0) {
59
+ while (this.incoming.length > 0) {
60
+ this.outgoing.push(this.incoming.pop());
61
+ }
62
+ }
63
+ return this.outgoing.pop();
64
+ }
65
+ };
66
+ var EventStream = class {
67
+ queue = new FifoQueue();
68
+ waiting = new FifoQueue();
69
+ done = false;
70
+ finalResultPromise;
71
+ resolveFinalResult;
72
+ isComplete;
73
+ extractResult;
74
+ constructor(isComplete, extractResult) {
75
+ this.isComplete = isComplete;
76
+ this.extractResult = extractResult;
77
+ this.finalResultPromise = new Promise((resolve) => {
78
+ this.resolveFinalResult = resolve;
79
+ });
80
+ }
81
+ push(event) {
82
+ if (this.done)
83
+ return;
84
+ if (this.isComplete(event)) {
85
+ this.done = true;
86
+ this.resolveFinalResult(this.extractResult(event));
87
+ }
88
+ const waiter = this.waiting.dequeue();
89
+ if (waiter) {
90
+ waiter({ value: event, done: false });
91
+ } else {
92
+ this.queue.enqueue(event);
93
+ }
94
+ }
95
+ end(result) {
96
+ this.done = true;
97
+ if (result !== void 0) {
98
+ this.resolveFinalResult(result);
99
+ }
100
+ while (this.waiting.length > 0) {
101
+ const waiter = this.waiting.dequeue();
102
+ waiter({ value: void 0, done: true });
103
+ }
104
+ }
105
+ async *[Symbol.asyncIterator]() {
106
+ while (true) {
107
+ if (this.queue.length > 0) {
108
+ yield this.queue.dequeue();
109
+ } else if (this.done) {
110
+ return;
111
+ } else {
112
+ const result = await new Promise((resolve) => this.waiting.enqueue(resolve));
113
+ if (result.done)
114
+ return;
115
+ yield result.value;
116
+ }
117
+ }
118
+ }
119
+ result() {
120
+ return this.finalResultPromise;
121
+ }
122
+ };
123
+ var AssistantMessageEventStream = class extends EventStream {
124
+ #startedAt = Date.now();
125
+ #startedAtMonotonic = performance.now();
126
+ constructor() {
127
+ super((event) => event.type === "done" || event.type === "error", (event) => {
128
+ if (event.type === "done") {
129
+ return event.message;
130
+ } else if (event.type === "error") {
131
+ return event.error;
132
+ }
133
+ throw new Error("Unexpected event type for final result");
134
+ });
135
+ }
136
+ push(event) {
137
+ if (event.type === "done")
138
+ this.#time(event.message);
139
+ else if (event.type === "error")
140
+ this.#time(event.error);
141
+ super.push(event);
142
+ }
143
+ end(result) {
144
+ if (result !== void 0)
145
+ this.#time(result);
146
+ super.end(result);
147
+ }
148
+ #time(message) {
149
+ if (this.done || message.durationMs !== void 0 || message.timestamp < this.#startedAt)
150
+ return;
151
+ message.durationMs = Math.max(0, Math.round(performance.now() - this.#startedAtMonotonic));
152
+ }
153
+ };
154
+ function createAssistantMessageEventStream() {
155
+ return new AssistantMessageEventStream();
156
+ }
157
+
158
+ // packages/harness-client/node_modules/@earendil-works/pi-ai/dist/utils/text.js
159
+ function contentText(content, separator = "\n") {
160
+ if (typeof content === "string")
161
+ return content;
162
+ return content.filter((block) => block.type === "text").map((block) => block.text).join(separator);
163
+ }
164
+ function getSystemMessageText(message) {
165
+ const parts = [contentText(message.content)];
166
+ for (const text2 of Object.values(message.sections ?? {})) {
167
+ if (text2 !== null)
168
+ parts.push(text2);
169
+ }
170
+ return parts.filter((part) => part.length > 0).join("\n\n");
171
+ }
172
+
173
+ // packages/harness-client/node_modules/@earendil-works/pi-ai/dist/utils/identity.js
174
+ var PI_ATTRIBUTION = { name: "pi", url: "https://pi.dev", categories: ["cli-agent"] };
175
+ function mergeClientIdentity(...sources) {
176
+ let merged;
177
+ for (const source of sources) {
178
+ if (!source)
179
+ continue;
180
+ merged = { ...merged };
181
+ if (source.userAgent !== void 0)
182
+ merged.userAgent = source.userAgent;
183
+ if (source.attribution !== void 0)
184
+ merged.attribution = source.attribution;
185
+ if (source.version !== void 0)
186
+ merged.version = source.version;
187
+ }
188
+ return merged;
189
+ }
190
+
191
+ // packages/harness-client/node_modules/@earendil-works/pi-ai/dist/utils/transcript.js
192
+ function createInitialSystemMessage(systemPrompt, tools) {
193
+ const hasSystemPrompt = systemPrompt !== void 0 && systemPrompt.length > 0;
194
+ const hasTools = tools !== void 0 && tools.length > 0;
195
+ if (!hasSystemPrompt && !hasTools)
196
+ return void 0;
197
+ return {
198
+ role: "system",
199
+ content: systemPrompt ?? "",
200
+ ...hasTools ? { toolsAdded: tools } : {},
201
+ timestamp: 0
202
+ };
203
+ }
204
+ function normalizeContext(context) {
205
+ const initialMessage = createInitialSystemMessage(context.systemPrompt, context.tools);
206
+ const messages = initialMessage ? [initialMessage, ...context.messages] : context.messages;
207
+ return { messages };
208
+ }
209
+ function isSystemMessage(message) {
210
+ return message.role === "system";
211
+ }
212
+ function getCurrentTools(messages) {
213
+ const tools = /* @__PURE__ */ new Map();
214
+ for (const message of messages) {
215
+ if (!isSystemMessage(message))
216
+ continue;
217
+ for (const tool of message.toolsRemoved ?? [])
218
+ tools.delete(tool.name);
219
+ for (const tool of message.toolsAdded ?? [])
220
+ tools.set(tool.name, tool);
221
+ }
222
+ return [...tools.values()];
223
+ }
224
+ function getCurrentSystemMessage(messages) {
225
+ const content = [];
226
+ const sections = /* @__PURE__ */ new Map();
227
+ let timestamp;
228
+ for (const message of messages) {
229
+ if (!isSystemMessage(message))
230
+ continue;
231
+ timestamp ??= message.timestamp;
232
+ const text2 = contentText(message.content);
233
+ if (text2.length > 0)
234
+ content.push(text2);
235
+ for (const [name, value] of Object.entries(message.sections ?? {})) {
236
+ if (value === null)
237
+ sections.delete(name);
238
+ else
239
+ sections.set(name, value);
240
+ }
241
+ }
242
+ const tools = getCurrentTools(messages);
243
+ if (timestamp === void 0 && tools.length === 0)
244
+ return void 0;
245
+ return {
246
+ role: "system",
247
+ content: content.join("\n\n"),
248
+ ...sections.size > 0 ? { sections: Object.fromEntries(sections) } : {},
249
+ ...tools.length > 0 ? { toolsAdded: tools } : {},
250
+ timestamp: timestamp ?? 0
251
+ };
252
+ }
253
+ function getCurrentSystemPrompt(messages) {
254
+ const message = getCurrentSystemMessage(messages);
255
+ return message ? getSystemMessageText(message) : "";
256
+ }
257
+ function toToolDeclaration(tool) {
258
+ return {
259
+ name: tool.name,
260
+ description: tool.description,
261
+ parameters: JSON.parse(JSON.stringify(tool.parameters)),
262
+ ...tool.constrainedSampling === void 0 ? {} : { constrainedSampling: tool.constrainedSampling }
263
+ };
264
+ }
265
+ function declarationsEqual(left, right) {
266
+ return JSON.stringify(toToolDeclaration(left)) === JSON.stringify(toToolDeclaration(right));
267
+ }
268
+ function getToolStateChanges(previous, current) {
269
+ const previousTools = new Map(previous.map((tool) => [tool.name, tool]));
270
+ const currentTools = new Map(current.map((tool) => [tool.name, tool]));
271
+ return {
272
+ toolsAdded: current.filter((tool) => {
273
+ const previousTool = previousTools.get(tool.name);
274
+ return previousTool === void 0 || !declarationsEqual(previousTool, tool);
275
+ }).map(toToolDeclaration),
276
+ toolsRemoved: previous.filter((tool) => {
277
+ const currentTool = currentTools.get(tool.name);
278
+ return currentTool === void 0 || !declarationsEqual(tool, currentTool);
279
+ }).map((tool) => ({ name: tool.name }))
280
+ };
281
+ }
282
+
283
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/checks.js
284
+ var ALWAYS = () => true;
285
+ var NEVER = () => false;
286
+ var IS_STRING = (v) => typeof v === "string";
287
+ var IS_NUMBER = (v) => Number.isFinite(v);
288
+ var IS_INTEGER = (v) => Number.isInteger(v);
289
+ var IS_BOOLEAN = (v) => typeof v === "boolean";
290
+ var IS_NULL = (v) => v === null;
291
+ var IS_ARRAY = (v) => Array.isArray(v);
292
+ var IS_BYTES = (v) => v instanceof Uint8Array;
293
+ var IS_BIGINT = (v) => typeof v === "bigint";
294
+ var IS_UNDEFINED = (v) => v === void 0;
295
+ var IS_OBJECT = (v) => isObject(v);
296
+ function isObject(v) {
297
+ return typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof Uint8Array);
298
+ }
299
+ var TYPE_CHECKS = /* @__PURE__ */ new Map([
300
+ ["string", IS_STRING],
301
+ ["number", IS_NUMBER],
302
+ ["integer", IS_INTEGER],
303
+ ["boolean", IS_BOOLEAN],
304
+ ["null", IS_NULL],
305
+ ["array", IS_ARRAY],
306
+ ["object", IS_OBJECT],
307
+ ["bytes", IS_BYTES],
308
+ ["bigint", IS_BIGINT],
309
+ ["undefined", IS_UNDEFINED]
310
+ ]);
311
+ var leaves = new WeakMap([
312
+ [IS_STRING, [1, void 0]],
313
+ [IS_NUMBER, [2, void 0]],
314
+ [IS_INTEGER, [3, void 0]],
315
+ [IS_BOOLEAN, [4, void 0]],
316
+ [IS_NULL, [5, void 0]],
317
+ [ALWAYS, [6, void 0]]
318
+ ]);
319
+ function leafOf(check) {
320
+ return leaves.get(check);
321
+ }
322
+ function leaf(code, arg, check) {
323
+ leaves.set(check, [code, arg]);
324
+ return check;
325
+ }
326
+ var Bounds = class {
327
+ min;
328
+ max;
329
+ xmin;
330
+ xmax;
331
+ constructor(min, max, xmin, xmax) {
332
+ this.min = min;
333
+ this.max = max;
334
+ this.xmin = xmin;
335
+ this.xmax = xmax;
336
+ }
337
+ };
338
+ function leafOk(code, x, arg) {
339
+ switch (code) {
340
+ case 1:
341
+ return typeof x === "string";
342
+ case 2:
343
+ return Number.isFinite(x);
344
+ case 3:
345
+ return Number.isInteger(x);
346
+ case 4:
347
+ return typeof x === "boolean";
348
+ case 5:
349
+ return x === null;
350
+ case 7:
351
+ return x === arg;
352
+ case 8: {
353
+ const list = arg;
354
+ for (let i = 0; i < list.length; i++)
355
+ if (list[i] === x)
356
+ return true;
357
+ return false;
358
+ }
359
+ case 9:
360
+ return (typeBits(x) & arg) !== 0;
361
+ case 10:
362
+ return Number.isInteger(x) && inBounds(x, arg);
363
+ case 11:
364
+ return Number.isFinite(x) && inBounds(x, arg);
365
+ case 12:
366
+ return typeof x === "string" && lengthOk(x, arg.min, arg.max);
367
+ case 13:
368
+ return typeof x === "string" && arg.test(x);
369
+ default:
370
+ return true;
371
+ }
372
+ }
373
+ function inBounds(x, b) {
374
+ return x >= b.min && x <= b.max && x > b.xmin && x < b.xmax;
375
+ }
376
+ var GUARD_NONE = 0;
377
+ var GUARD_STRICT = 1;
378
+ var GUARD_LOOSE = 2;
379
+ var CODE = 15;
380
+ var REQUIRED = 16;
381
+ var INHERITED = 32;
382
+ function and(parts) {
383
+ switch (parts.length) {
384
+ case 0:
385
+ return ALWAYS;
386
+ case 1:
387
+ return parts[0];
388
+ case 2: {
389
+ const [a, b] = parts;
390
+ return (v) => a(v) && b(v);
391
+ }
392
+ case 3: {
393
+ const [a, b, c] = parts;
394
+ return (v) => a(v) && b(v) && c(v);
395
+ }
396
+ default:
397
+ return (v) => {
398
+ for (let i = 0; i < parts.length; i++)
399
+ if (!parts[i](v))
400
+ return false;
401
+ return true;
402
+ };
403
+ }
404
+ }
405
+ function indirect(slot) {
406
+ return (v) => slot.check(v);
407
+ }
408
+ function scopedCheck(scope, uri, check) {
409
+ return (v) => {
410
+ scope.push(uri);
411
+ const ok = check(v);
412
+ scope.pop();
413
+ return ok;
414
+ };
415
+ }
416
+ function typeCheck(types) {
417
+ if (types.length === 1)
418
+ return (typeof types[0] === "string" ? TYPE_CHECKS.get(types[0]) : void 0) ?? NEVER;
419
+ return maskCheck(typeMask(types));
420
+ }
421
+ var TYPE_BITS = /* @__PURE__ */ new Map([
422
+ ["string", 1],
423
+ ["number", 2],
424
+ ["integer", 4],
425
+ ["boolean", 8],
426
+ ["null", 16],
427
+ ["array", 32],
428
+ ["object", 64],
429
+ ["bytes", 128],
430
+ ["bigint", 256],
431
+ ["undefined", 512]
432
+ ]);
433
+ function typeMask(types) {
434
+ let mask = 0;
435
+ for (const t of types)
436
+ if (typeof t === "string")
437
+ mask |= TYPE_BITS.get(t) ?? 0;
438
+ return mask;
439
+ }
440
+ function typeBits(v) {
441
+ switch (typeof v) {
442
+ case "string":
443
+ return 1;
444
+ case "number":
445
+ return Number.isInteger(v) ? 6 : Number.isFinite(v) ? 2 : 0;
446
+ case "boolean":
447
+ return 8;
448
+ case "object":
449
+ return v === null ? 16 : Array.isArray(v) ? 32 : v instanceof Uint8Array ? 128 : 64;
450
+ case "bigint":
451
+ return 256;
452
+ case "undefined":
453
+ return 512;
454
+ default:
455
+ return 0;
456
+ }
457
+ }
458
+ function maskCheck(mask) {
459
+ return leaf(9, mask, (v) => (typeBits(v) & mask) !== 0);
460
+ }
461
+ function maskedAnyCheck(mask, checks) {
462
+ if (checks.length === 0)
463
+ return maskCheck(mask);
464
+ const rest = checks.length === 1 ? checks[0] : anyCheck(checks);
465
+ return (v) => (typeBits(v) & mask) !== 0 || rest(v);
466
+ }
467
+ function bytesCheck(min, max) {
468
+ return (v) => v instanceof Uint8Array && v.length >= min && v.length <= max;
469
+ }
470
+ function codePoints(s) {
471
+ let n = 0;
472
+ for (let i = 0; i < s.length; i++, n++) {
473
+ const c = s.charCodeAt(i);
474
+ if (c >= 55296 && c <= 56319 && i + 1 < s.length) {
475
+ const next = s.charCodeAt(i + 1);
476
+ if (next >= 56320 && next <= 57343)
477
+ i++;
478
+ }
479
+ }
480
+ return n;
481
+ }
482
+ function lengthOk(s, min, max) {
483
+ const units = s.length;
484
+ if (units < min)
485
+ return false;
486
+ if (units < 2 * min && codePoints(s) < min)
487
+ return false;
488
+ return units <= max || codePoints(s) <= max;
489
+ }
490
+ function stringCheck(strict, min, max, re, format) {
491
+ if (re !== void 0 && min === 0 && max === Number.POSITIVE_INFINITY && format === void 0) {
492
+ return strict ? leaf(13, re, (v) => typeof v === "string" && re.test(v)) : (v) => typeof v !== "string" || re.test(v);
493
+ }
494
+ if (re === void 0 && format === void 0) {
495
+ return strict ? leaf(12, new Bounds(min, max, 0, 0), (v) => typeof v === "string" && lengthOk(v, min, max)) : (v) => typeof v !== "string" || lengthOk(v, min, max);
496
+ }
497
+ return (v) => {
498
+ if (typeof v !== "string")
499
+ return !strict;
500
+ return lengthOk(v, min, max) && (re === void 0 || re.test(v)) && (format === void 0 || format(v));
501
+ };
502
+ }
503
+ function numberCheck(mode, min, max, xmin, xmax, multipleOf) {
504
+ const check = (v) => {
505
+ if (typeof v !== "number" && typeof v !== "bigint")
506
+ return mode === 0;
507
+ if (mode === 3 ? typeof v !== "bigint" : mode !== 0 && !Number.isFinite(v))
508
+ return false;
509
+ if (mode === 2 && !Number.isInteger(v))
510
+ return false;
511
+ return v >= min && v <= max && v > xmin && v < xmax && (multipleOf === void 0 || isMultiple(v, multipleOf));
512
+ };
513
+ const plain = typeof min === "number" && typeof max === "number" && typeof xmin === "number" && typeof xmax === "number";
514
+ if (mode === 0 || mode === 3 || multipleOf !== void 0 || !plain)
515
+ return check;
516
+ return leaf(mode === 2 ? 10 : 11, new Bounds(min, max, xmin, xmax), check);
517
+ }
518
+ function isMultiple(v, d) {
519
+ if (typeof v === "bigint" || typeof d === "bigint") {
520
+ if (typeof v === "number" && !Number.isInteger(v) || typeof d === "number" && !Number.isInteger(d))
521
+ return false;
522
+ const divisor = BigInt(d);
523
+ return divisor !== 0n && BigInt(v) % divisor === 0n;
524
+ }
525
+ const q = v / d;
526
+ if (Number.isInteger(q))
527
+ return true;
528
+ if (!Number.isFinite(q))
529
+ return v % d === 0;
530
+ const [vc, ve] = decimal(v);
531
+ const [dc, de] = decimal(d);
532
+ return ve >= de ? vc * 10n ** BigInt(ve - de) % dc === 0n : vc % (dc * 10n ** BigInt(de - ve)) === 0n;
533
+ }
534
+ function decimal(x) {
535
+ const [mantissa, exponent = "0"] = Math.abs(x).toString().split("e");
536
+ const point = mantissa.indexOf(".");
537
+ const fraction = point < 0 ? 0 : mantissa.length - point - 1;
538
+ return [BigInt(mantissa.replace(".", "")), Number(exponent) - fraction];
539
+ }
540
+ function guardObject(inner, strict) {
541
+ return strict ? (v) => isObject(v) && inner(v) : (v) => !isObject(v) || inner(v);
542
+ }
543
+ function guardArray(inner, strict) {
544
+ return strict ? (v) => Array.isArray(v) && inner(v) : (v) => !Array.isArray(v) || inner(v);
545
+ }
546
+ function declaredObject(entries2, requiredCount, closed, guard) {
547
+ const n = entries2.length;
548
+ return (v) => {
549
+ if (guard !== GUARD_NONE && !isObject(v))
550
+ return guard === GUARD_LOOSE;
551
+ const o = v;
552
+ let required = 0;
553
+ let next = 0;
554
+ for (const k in o) {
555
+ let i = next;
556
+ if (entries2[i] !== k) {
557
+ i = 0;
558
+ while (i < n && entries2[i] !== k)
559
+ i += 3;
560
+ if (i === n) {
561
+ if (closed)
562
+ return false;
563
+ continue;
564
+ }
565
+ }
566
+ next = i + 3;
567
+ const x = o[k];
568
+ const f = entries2[i + 2];
569
+ if (x === void 0 && !(f & REQUIRED))
570
+ continue;
571
+ const c = f & CODE;
572
+ if (c !== 0 ? !leafOk(c, x, entries2[i + 1]) : !entries2[i + 1](x))
573
+ return false;
574
+ if (f & REQUIRED)
575
+ required++;
576
+ }
577
+ return required === requiredCount;
578
+ };
579
+ }
580
+ function openObject(entries2, keys, extraRequired, patterns, additional, guard) {
581
+ const known = patterns.length > 0 || additional !== void 0 ? new Set(keys) : void 0;
582
+ return (v) => {
583
+ if (guard !== GUARD_NONE && !isObject(v))
584
+ return guard === GUARD_LOOSE;
585
+ const o = v;
586
+ for (let i = 0; i < entries2.length; i += 3) {
587
+ const k = entries2[i];
588
+ const x = o[k];
589
+ const f = entries2[i + 2];
590
+ if (x === void 0 && !(f & REQUIRED && Object.hasOwn(o, k)) || f & INHERITED && !Object.hasOwn(o, k)) {
591
+ if (f & REQUIRED)
592
+ return false;
593
+ continue;
594
+ }
595
+ const c = f & CODE;
596
+ if (c !== 0 ? !leafOk(c, x, entries2[i + 1]) : !entries2[i + 1](x))
597
+ return false;
598
+ }
599
+ for (let i = 0; i < extraRequired.length; i++)
600
+ if (!Object.hasOwn(o, extraRequired[i]))
601
+ return false;
602
+ if (known === void 0)
603
+ return true;
604
+ for (const k of Object.keys(o)) {
605
+ let matched = known.has(k);
606
+ for (let i = 0; i < patterns.length; i++) {
607
+ if (patterns[i][0].test(k)) {
608
+ matched = true;
609
+ if (!patterns[i][1](o[k]))
610
+ return false;
611
+ }
612
+ }
613
+ if (!matched && additional !== void 0 && !additional(o[k]))
614
+ return false;
615
+ }
616
+ return true;
617
+ };
618
+ }
619
+ function propertyNamesCheck(check) {
620
+ return (v) => {
621
+ for (const k in v)
622
+ if (!check(k))
623
+ return false;
624
+ return true;
625
+ };
626
+ }
627
+ function propertyCountCheck(min, max) {
628
+ return (v) => {
629
+ let n = 0;
630
+ for (const _ in v)
631
+ n++;
632
+ return n >= min && n <= max;
633
+ };
634
+ }
635
+ function dependentRequiredCheck(entries2) {
636
+ return (v) => {
637
+ const o = v;
638
+ for (const [k, list] of entries2)
639
+ if (Object.hasOwn(o, k)) {
640
+ for (const r of list)
641
+ if (!Object.hasOwn(o, r))
642
+ return false;
643
+ }
644
+ return true;
645
+ };
646
+ }
647
+ function dependentSchemasCheck(entries2) {
648
+ return (v) => {
649
+ for (const [k, check] of entries2)
650
+ if (Object.hasOwn(v, k) && !check(v))
651
+ return false;
652
+ return true;
653
+ };
654
+ }
655
+ var NO_LEAF = [0, void 0];
656
+ function listCheck(guard, min, max, prefix, rest) {
657
+ const n = prefix.length;
658
+ const [code, arg] = (rest === void 0 ? void 0 : leafOf(rest)) ?? NO_LEAF;
659
+ return (v) => {
660
+ if (!Array.isArray(v))
661
+ return guard === GUARD_LOOSE;
662
+ const length = v.length;
663
+ if (length < min || length > max)
664
+ return false;
665
+ const m = length < n ? length : n;
666
+ for (let i = 0; i < m; i++)
667
+ if (!prefix[i](v[i]))
668
+ return false;
669
+ if (rest === void 0)
670
+ return true;
671
+ if (code !== 0) {
672
+ for (let i = n; i < length; i++)
673
+ if (!leafOk(code, v[i], arg))
674
+ return false;
675
+ return true;
676
+ }
677
+ for (let i = n; i < length; i++)
678
+ if (!rest(v[i]))
679
+ return false;
680
+ return true;
681
+ };
682
+ }
683
+ function itemsCheck(prefix, rest) {
684
+ return listCheck(GUARD_NONE, 0, Number.POSITIVE_INFINITY, prefix, rest);
685
+ }
686
+ function lengthCheck(min, max) {
687
+ return (v) => v.length >= min && v.length <= max;
688
+ }
689
+ function containsCheck(check, min, max) {
690
+ return (v) => {
691
+ const list = v;
692
+ let n = 0;
693
+ for (let i = 0; i < list.length; i++)
694
+ if (check(list[i]) && ++n > max)
695
+ return false;
696
+ return n >= min;
697
+ };
698
+ }
699
+ function uniqueCheck(v) {
700
+ const list = v;
701
+ for (let i = 1; i < list.length; i++)
702
+ for (let j = 0; j < i; j++)
703
+ if (deepEqual(list[i], list[j]))
704
+ return false;
705
+ return true;
706
+ }
707
+ function enumCheck(values) {
708
+ const primitives = values.filter((x) => typeof x !== "object" || x === null);
709
+ if (primitives.length === values.length && primitives.length <= 8) {
710
+ return leaf(8, primitives, (v) => {
711
+ for (let i = 0; i < primitives.length; i++)
712
+ if (primitives[i] === v)
713
+ return true;
714
+ return false;
715
+ });
716
+ }
717
+ const set = new Set(primitives);
718
+ const objects = values.filter((x) => typeof x === "object" && x !== null);
719
+ return (v) => set.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o));
720
+ }
721
+ function constCheck(value) {
722
+ if (typeof value !== "object" || value === null)
723
+ return leaf(7, value, (v) => v === value);
724
+ return (v) => deepEqual(v, value);
725
+ }
726
+ function anyCheck(checks) {
727
+ return (v) => {
728
+ for (let i = 0; i < checks.length; i++)
729
+ if (checks[i](v))
730
+ return true;
731
+ return false;
732
+ };
733
+ }
734
+ function oneCheck(checks) {
735
+ return (v) => {
736
+ let n = 0;
737
+ for (let i = 0; i < checks.length; i++)
738
+ if (checks[i](v) && ++n > 1)
739
+ return false;
740
+ return n === 1;
741
+ };
742
+ }
743
+ function notCheck(check) {
744
+ return (v) => !check(v);
745
+ }
746
+ function ifCheck(cond, then, otherwise) {
747
+ return (v) => cond(v) ? then(v) : otherwise(v);
748
+ }
749
+ function taggedCheck(key, tags, checks) {
750
+ return (v) => {
751
+ if (!isObject(v))
752
+ return false;
753
+ const tag = v[key];
754
+ for (let i = 0; i < tags.length; i++)
755
+ if (tags[i] === tag)
756
+ return checks[i](v);
757
+ return false;
758
+ };
759
+ }
760
+ function deepEqual(a, b) {
761
+ if (a === b)
762
+ return true;
763
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null)
764
+ return false;
765
+ const array = Array.isArray(a);
766
+ if (array !== Array.isArray(b))
767
+ return false;
768
+ if (array) {
769
+ const x2 = a;
770
+ const y2 = b;
771
+ if (x2.length !== y2.length)
772
+ return false;
773
+ for (let i = 0; i < x2.length; i++)
774
+ if (!deepEqual(x2[i], y2[i]))
775
+ return false;
776
+ return true;
777
+ }
778
+ const x = a;
779
+ const y = b;
780
+ const keys = Object.keys(x);
781
+ if (keys.length !== Object.keys(y).length)
782
+ return false;
783
+ for (const k of keys)
784
+ if (!Object.hasOwn(y, k) || !deepEqual(x[k], y[k]))
785
+ return false;
786
+ return true;
787
+ }
788
+
789
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/resolver.js
790
+ var DEFAULT_BASE = "https://json-schema.invalid/root.json";
791
+ var Resolver = class {
792
+ draft;
793
+ /** The base URI the root schema is walked from; walkers apply the root's own `$id` through `baseFor`. */
794
+ rootBase = DEFAULT_BASE;
795
+ /** Schema object to the base URI it was indexed under. */
796
+ baseOf = /* @__PURE__ */ new Map();
797
+ /** URI (with a `#name` fragment) of every `$dynamicAnchor`, to its schema. */
798
+ dynamicAnchors = /* @__PURE__ */ new Map();
799
+ root;
800
+ options;
801
+ registry = /* @__PURE__ */ new Map();
802
+ rejectUnresolved;
803
+ /** The references that named nothing and resolved to `false` (with `unresolvedRefs: "reject"`). */
804
+ unresolved = /* @__PURE__ */ new Set();
805
+ resources = /* @__PURE__ */ new Map();
806
+ anchors = /* @__PURE__ */ new Map();
807
+ indexed = false;
808
+ constructor(root, options) {
809
+ this.draft = options.draft === "7" ? "7" : "2020-12";
810
+ this.root = root;
811
+ this.options = options;
812
+ this.rejectUnresolved = options.unresolvedRefs === "reject";
813
+ }
814
+ /**
815
+ * The base URI of `node`, whose parent has `base`: its `$id` changes it, unless draft 7 makes the `$id` inert. Once
816
+ * the schema is indexed, the indexed base (a resolved reference target already has its own).
817
+ */
818
+ baseFor(node, base) {
819
+ let indexed = this.baseOf.get(node);
820
+ if (indexed !== void 0)
821
+ return indexed;
822
+ const id = node.$id;
823
+ if (typeof id !== "string")
824
+ return base;
825
+ if (!this.indexed) {
826
+ this.ensureIndexed();
827
+ indexed = this.baseOf.get(node);
828
+ if (indexed !== void 0)
829
+ return indexed;
830
+ }
831
+ if (this.draft === "7" && (typeof node.$ref === "string" || id.startsWith("#")))
832
+ return base;
833
+ return documentOf(resolveUri(id, base));
834
+ }
835
+ /** Indexes the root schema and the registered documents' URIs (once). */
836
+ ensureIndexed() {
837
+ if (this.indexed)
838
+ return;
839
+ this.indexed = true;
840
+ for (const [uri, schema] of Object.entries(this.options.schemas ?? {})) {
841
+ this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema);
842
+ }
843
+ this.resources.set(DEFAULT_BASE, this.root);
844
+ this.index(this.root, DEFAULT_BASE);
845
+ }
846
+ /**
847
+ * The schema a reference names, with the base URI it compiles under. Throws if it names nothing, or, with
848
+ * `unresolvedRefs: "reject"`, resolves to `false`, the schema no value passes.
849
+ */
850
+ resolve(ref, base) {
851
+ this.ensureIndexed();
852
+ if (!this.rejectUnresolved)
853
+ return this.find(ref, base);
854
+ try {
855
+ return this.find(ref, base);
856
+ } catch {
857
+ this.unresolved.add(resolveUri(ref, base));
858
+ return { node: false, base };
859
+ }
860
+ }
861
+ /** Whether `ref`, from `base`, named nothing and resolved to `false`. */
862
+ isUnresolved(ref, base) {
863
+ return this.unresolved.has(resolveUri(ref, base));
864
+ }
865
+ find(ref, base) {
866
+ const uri = resolveUri(ref, base);
867
+ const doc = documentOf(uri);
868
+ const fragment = uri.length > doc.length ? decodeURIComponent(uri.slice(doc.length + 1)) : "";
869
+ const root = this.resources.has(doc) ? this.resources.get(doc) : this.load(doc);
870
+ if (root === void 0)
871
+ throw new Error(`Unresolved $ref ${ref} (no schema registered for ${doc})`);
872
+ if (fragment === "")
873
+ return { node: root, base: doc };
874
+ if (fragment.startsWith("/"))
875
+ return this.pointer(root, doc, fragment);
876
+ const target = this.anchors.get(`${doc}#${fragment}`);
877
+ if (target === void 0)
878
+ throw new Error(`Unresolved $ref ${ref} (no anchor ${fragment} in ${doc})`);
879
+ return { node: target, base: this.baseOf.get(target) ?? doc };
880
+ }
881
+ /** Whether `node` is the root of the schema resource at `base`. */
882
+ isResource(node, base) {
883
+ this.ensureIndexed();
884
+ return this.resources.get(base) === node;
885
+ }
886
+ // Walks only keywords that hold subschemas: an `$id` inside `enum`, `const` or an unknown keyword names nothing.
887
+ index(node, base) {
888
+ if (!isSchemaObject(node) || this.baseOf.has(node))
889
+ return;
890
+ let b = base;
891
+ const refOnly = this.draft === "7" && typeof node.$ref === "string";
892
+ if (!refOnly && typeof node.$id === "string") {
893
+ if (this.draft === "7" && node.$id.startsWith("#"))
894
+ this.anchors.set(documentOf(b) + node.$id, node);
895
+ else {
896
+ const uri = resolveUri(node.$id, b);
897
+ b = documentOf(uri);
898
+ this.resources.set(b, node);
899
+ if (uri.length > b.length + 1)
900
+ this.anchors.set(uri, node);
901
+ }
902
+ }
903
+ this.baseOf.set(node, b);
904
+ if (refOnly)
905
+ return;
906
+ if (this.draft !== "7") {
907
+ if (typeof node.$anchor === "string")
908
+ this.anchors.set(`${b}#${node.$anchor}`, node);
909
+ if (typeof node.$dynamicAnchor === "string") {
910
+ this.anchors.set(`${b}#${node.$dynamicAnchor}`, node);
911
+ this.dynamicAnchors.set(`${b}#${node.$dynamicAnchor}`, node);
912
+ }
913
+ }
914
+ for (const key of SCHEMA_KEYWORDS)
915
+ this.index(node[key], b);
916
+ for (const key of MAP_KEYWORDS) {
917
+ const map = node[key];
918
+ if (isSchemaObject(map))
919
+ for (const k of Object.keys(map))
920
+ this.index(map[k], b);
921
+ }
922
+ for (const key of ARRAY_KEYWORDS) {
923
+ const list = node[key];
924
+ if (Array.isArray(list))
925
+ for (const s of list)
926
+ this.index(s, b);
927
+ }
928
+ }
929
+ load(doc) {
930
+ const schema = this.registry.get(doc);
931
+ if (schema === void 0)
932
+ return void 0;
933
+ this.resources.set(doc, schema);
934
+ this.index(schema, doc);
935
+ return schema;
936
+ }
937
+ pointer(root, base, fragment) {
938
+ let node = root;
939
+ let b = base;
940
+ for (const raw of fragment.split("/").slice(1)) {
941
+ const key = raw.replace(/~1/g, "/").replace(/~0/g, "~");
942
+ node = typeof node === "object" && node !== null && Object.hasOwn(node, key) ? node[key] : void 0;
943
+ if (node === void 0)
944
+ throw new Error(`Unresolved $ref #${fragment} in ${base}`);
945
+ if (typeof node === "object" && node !== null)
946
+ b = this.baseOf.get(node) ?? b;
947
+ }
948
+ return { node, base: b };
949
+ }
950
+ };
951
+ var SCHEMA_KEYWORDS = [
952
+ "additionalProperties",
953
+ "propertyNames",
954
+ "contains",
955
+ "not",
956
+ "if",
957
+ "then",
958
+ "else",
959
+ "unevaluatedProperties",
960
+ "unevaluatedItems",
961
+ "additionalItems",
962
+ "contentSchema",
963
+ "items"
964
+ ];
965
+ var MAP_KEYWORDS = ["properties", "patternProperties", "$defs", "definitions", "dependentSchemas", "dependencies"];
966
+ var ARRAY_KEYWORDS = ["allOf", "anyOf", "oneOf", "prefixItems", "items"];
967
+ function isSchemaObject(value) {
968
+ return typeof value === "object" && value !== null && !Array.isArray(value);
969
+ }
970
+ function resolveUri(ref, base) {
971
+ try {
972
+ return new URL(ref, base).href;
973
+ } catch {
974
+ return ref.startsWith("#") ? documentOf(base) + ref : ref;
975
+ }
976
+ }
977
+ function documentOf(uri) {
978
+ const hash = uri.indexOf("#");
979
+ return hash < 0 ? uri : uri.slice(0, hash);
980
+ }
981
+
982
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/shared.js
983
+ function sharedRegex(source) {
984
+ const hit = regexes.get(source)?.deref();
985
+ if (hit !== void 0)
986
+ return hit;
987
+ let re;
988
+ try {
989
+ re = new RegExp(source, "u");
990
+ } catch {
991
+ re = new RegExp(source);
992
+ }
993
+ regexes.set(source, new WeakRef(re));
994
+ regexCleanup.register(re, source);
995
+ return re;
996
+ }
997
+ var regexes = /* @__PURE__ */ new Map();
998
+ var regexCleanup = new FinalizationRegistry((source) => {
999
+ if (regexes.get(source)?.deref() === void 0)
1000
+ regexes.delete(source);
1001
+ });
1002
+
1003
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/coerce.js
1004
+ var Coercer = class {
1005
+ c;
1006
+ schema;
1007
+ /**
1008
+ * The (schema node, value) pairs pass 2 is converting through a re-entry point, as a stack. Conversion can enter
1009
+ * a node again with the same value only through a `$ref` or by wrapping a single value into an array (also for
1010
+ * schemas that cycle through shared JS objects): a recursive schema that meets a value no branch accepts would
1011
+ * convert it without end. A pair already on the stack (primitives by value, objects by reference) leaves the value
1012
+ * unchanged. Only those two points push, so schemas without references or wraps pay nothing.
1013
+ */
1014
+ entered = [];
1015
+ /** How often a re-entry was cut short in this coerce() call; results computed across one are not memoized. */
1016
+ cuts = 0;
1017
+ /**
1018
+ * Results of `$ref` targets by (node, value) within one coerce() call: a recursive union whose branches all
1019
+ * convert the same children (and all fail) would convert them once per branch, exponentially in the depth.
1020
+ */
1021
+ memo = void 0;
1022
+ constructor(compiler2, schema) {
1023
+ this.c = compiler2;
1024
+ this.schema = schema;
1025
+ }
1026
+ /** `value` coerced: a copy along the changed paths only, or `value` itself when nothing changes. */
1027
+ coerce(value) {
1028
+ const base = this.c.r.rootBase;
1029
+ const withoutNulls = this.dropOptionalNulls(value, this.schema, base);
1030
+ return this.coerceTypes(this.convertOnly(withoutNulls), this.schema, base);
1031
+ }
1032
+ /** Pass 2 alone, as TypeBox's `Value.Convert` (the TypeBox conformance tests run it). */
1033
+ convertOnly(value) {
1034
+ try {
1035
+ return this.convert(this.schema, this.c.r.rootBase, value);
1036
+ } finally {
1037
+ this.memo = void 0;
1038
+ this.cuts = 0;
1039
+ }
1040
+ }
1041
+ /** `node` converted for `value` at a re-entry point: unchanged when that pair is already being converted. */
1042
+ reenter(node, base, value, memoize) {
1043
+ const entered = this.entered;
1044
+ for (let i = 0; i < entered.length; i += 2) {
1045
+ if (entered[i] === node && Object.is(entered[i + 1], value)) {
1046
+ this.cuts++;
1047
+ return value;
1048
+ }
1049
+ }
1050
+ const memo = memoize ? this.memo?.get(node) : void 0;
1051
+ if (memo?.has(value))
1052
+ return memo.get(value);
1053
+ const cuts = this.cuts;
1054
+ entered.push(node, value);
1055
+ let result;
1056
+ try {
1057
+ result = this.convert(node, base, value);
1058
+ } finally {
1059
+ entered.length -= 2;
1060
+ }
1061
+ if (memoize && this.cuts === cuts) {
1062
+ this.memo ??= /* @__PURE__ */ new Map();
1063
+ let values = this.memo.get(node);
1064
+ if (values === void 0) {
1065
+ values = /* @__PURE__ */ new Map();
1066
+ this.memo.set(node, values);
1067
+ }
1068
+ values.set(value, result);
1069
+ }
1070
+ return result;
1071
+ }
1072
+ /** Whether `value` passes the schema `node`; undefined when `node` cannot be compiled. */
1073
+ passes(node, base, value) {
1074
+ try {
1075
+ return this.c.check(node, this.baseOf(node, base))(value);
1076
+ } catch {
1077
+ return void 0;
1078
+ }
1079
+ }
1080
+ baseOf(node, base) {
1081
+ return isSchemaObject(node) ? this.c.r.baseFor(node, base) : base;
1082
+ }
1083
+ // ---------------------------------------------------------------------------------------------------------------
1084
+ // Pass 1: optional nulls
1085
+ // ---------------------------------------------------------------------------------------------------------------
1086
+ dropOptionalNulls(value, schema, base) {
1087
+ if (!isSchemaObject(schema))
1088
+ return value;
1089
+ const b = this.baseOf(schema, base);
1090
+ if (Array.isArray(value)) {
1091
+ return mapItems(value, (item, i) => {
1092
+ const itemSchema = itemSchemaAt(schema, i);
1093
+ return itemSchema === void 0 ? item : this.dropOptionalNulls(item, itemSchema, b);
1094
+ });
1095
+ }
1096
+ if (!isPlainObject(value))
1097
+ return value;
1098
+ const properties = isSchemaObject(schema.properties) ? schema.properties : {};
1099
+ const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : [];
1100
+ const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0;
1101
+ if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema.properties))
1102
+ return value;
1103
+ const required = new Set(Array.isArray(schema.required) ? schema.required : []);
1104
+ let out;
1105
+ const set = (key, next) => {
1106
+ if (next === (out ?? value)[key])
1107
+ return;
1108
+ out ??= { ...value };
1109
+ out[key] = next;
1110
+ };
1111
+ for (const [key, property] of Object.entries(properties)) {
1112
+ if (!Object.hasOwn(value, key))
1113
+ continue;
1114
+ const isRef = isSchemaObject(property) && typeof property.$ref === "string";
1115
+ if (value[key] === null && !required.has(key) && !isRef && this.passes(property, b, null) === false) {
1116
+ out ??= { ...value };
1117
+ delete out[key];
1118
+ continue;
1119
+ }
1120
+ set(key, this.dropOptionalNulls(value[key], property, b));
1121
+ }
1122
+ if (patterns.length > 0 || additional !== void 0) {
1123
+ for (const key of Object.keys(value)) {
1124
+ let matched = Object.hasOwn(properties, key);
1125
+ for (const [pattern, item] of patterns) {
1126
+ if (!pattern.test(key))
1127
+ continue;
1128
+ matched = true;
1129
+ set(key, this.dropOptionalNulls((out ?? value)[key], item, b));
1130
+ }
1131
+ if (!matched && additional !== void 0)
1132
+ set(key, this.dropOptionalNulls(value[key], additional, b));
1133
+ }
1134
+ }
1135
+ return out ?? value;
1136
+ }
1137
+ // ---------------------------------------------------------------------------------------------------------------
1138
+ // Pass 2: TypeBox's conversion rules
1139
+ // ---------------------------------------------------------------------------------------------------------------
1140
+ convert(node, base, value) {
1141
+ if (!isSchemaObject(node))
1142
+ return value;
1143
+ const b = this.baseOf(node, base);
1144
+ if (typeof node.$ref === "string") {
1145
+ let target;
1146
+ try {
1147
+ target = this.c.r.resolve(node.$ref, b);
1148
+ } catch {
1149
+ return value;
1150
+ }
1151
+ return isSchemaObject(target.node) ? this.reenter(target.node, target.base, value, true) : value;
1152
+ }
1153
+ return this.convertNode(node, b, value);
1154
+ }
1155
+ /** One schema node's conversion: its first keyword among `const`, `enum`, the unions, `allOf` and `type`. */
1156
+ convertNode(node, b, value) {
1157
+ if (Object.hasOwn(node, "const"))
1158
+ return convertLiteral(node.const, value);
1159
+ if (Array.isArray(node.enum))
1160
+ return this.convertEnum(node, node.enum, b, value);
1161
+ if (Array.isArray(node.anyOf))
1162
+ return this.convertUnion(node, node.anyOf, b, value);
1163
+ if (Array.isArray(node.oneOf))
1164
+ return this.convertUnion(node, node.oneOf, b, value);
1165
+ if (Array.isArray(node.allOf)) {
1166
+ let next = value;
1167
+ for (const member of node.allOf)
1168
+ next = this.convert(member, b, next);
1169
+ return this.convertMembers(node, b, next);
1170
+ }
1171
+ switch (node.type) {
1172
+ case "string":
1173
+ return orValue(tryString(value), value);
1174
+ case "number":
1175
+ return orValue(tryNumber(value), value);
1176
+ case "integer": {
1177
+ const result = tryNumber(value);
1178
+ return result === void 0 ? value : Math.trunc(result.value);
1179
+ }
1180
+ case "boolean":
1181
+ return orValue(tryBoolean(value), value);
1182
+ case "null":
1183
+ return orValue(tryNull(value), value);
1184
+ case "bigint":
1185
+ return orValue(tryBigInt(value), value);
1186
+ case "undefined":
1187
+ return orValue(tryUndefined(value), value);
1188
+ case "array":
1189
+ return this.convertArray(node, b, value);
1190
+ case "object":
1191
+ return this.convertObject(node, b, value);
1192
+ case void 0:
1193
+ if (node.properties !== void 0 || node.patternProperties !== void 0) {
1194
+ return this.convertObject(node, b, value);
1195
+ }
1196
+ if (node.items !== void 0 || node.prefixItems !== void 0)
1197
+ return this.convertArray(node, b, value);
1198
+ return value;
1199
+ default:
1200
+ return value;
1201
+ }
1202
+ }
1203
+ /** An enum is a union of its values: a member stays, else the first value the input converts to. */
1204
+ convertEnum(node, values, base, value) {
1205
+ if (values.some((member) => member === value))
1206
+ return value;
1207
+ for (const member of values) {
1208
+ const candidate = convertLiteral(member, value);
1209
+ if (candidate !== value && this.passes(node, base, candidate) === true)
1210
+ return candidate;
1211
+ }
1212
+ return value;
1213
+ }
1214
+ /**
1215
+ * A value one branch accepts stays; else the first branch's conversion that the whole union accepts. Branches are
1216
+ * converted in order and only until one is accepted, so a later recursive branch is not entered needlessly. A node
1217
+ * that also declares members (plain JSON Schema; TypeBox's never do) converts them into each candidate before it is
1218
+ * checked, so a branch is not discarded for a sibling property that is converted after it.
1219
+ */
1220
+ convertUnion(node, branches, base, value) {
1221
+ if (branches.some((branch) => this.passes(branch, base, value) === true))
1222
+ return this.convertMembers(node, base, value);
1223
+ for (const branch of branches) {
1224
+ const candidate = this.convertMembers(node, base, this.convert(branch, base, value));
1225
+ if (this.passes(node, base, candidate) === true)
1226
+ return candidate;
1227
+ }
1228
+ return this.convertMembers(node, base, value);
1229
+ }
1230
+ /** The object members of a union or intersection node, when it declares any. */
1231
+ convertMembers(node, base, value) {
1232
+ const declares = node.properties !== void 0 || node.patternProperties !== void 0 || node.additionalProperties !== void 0;
1233
+ return declares ? this.convertObject(node, base, value) : value;
1234
+ }
1235
+ convertArray(node, base, value) {
1236
+ const prefix = Array.isArray(node.items) ? node.items : Array.isArray(node.prefixItems) ? node.prefixItems : void 0;
1237
+ if (prefix !== void 0) {
1238
+ if (!Array.isArray(value))
1239
+ return value;
1240
+ const rest = Array.isArray(node.items) ? void 0 : node.items;
1241
+ return mapItems(value, (item2, i) => {
1242
+ const schema = i < prefix.length ? prefix[i] : rest;
1243
+ return schema === void 0 ? item2 : this.convert(schema, base, item2);
1244
+ });
1245
+ }
1246
+ if (Array.isArray(value)) {
1247
+ return node.items === void 0 ? value : mapItems(value, (item2) => this.convert(node.items, base, item2));
1248
+ }
1249
+ const item = node.items;
1250
+ return [isSchemaObject(item) ? this.reenter(item, base, value, false) : value];
1251
+ }
1252
+ convertObject(node, base, value) {
1253
+ if (!isPlainObject(value))
1254
+ return value;
1255
+ const properties = isSchemaObject(node.properties) ? node.properties : {};
1256
+ const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema]) => [sharedRegex(pattern), schema]) : [];
1257
+ const additional = isSchemaObject(node.additionalProperties) ? node.additionalProperties : void 0;
1258
+ let out;
1259
+ for (const key of Object.keys(value)) {
1260
+ if (value[key] === void 0)
1261
+ continue;
1262
+ let next = value[key];
1263
+ let matched = Object.hasOwn(properties, key);
1264
+ if (matched)
1265
+ next = this.convert(properties[key], base, next);
1266
+ for (const [pattern, schema] of patterns) {
1267
+ if (!pattern.test(key))
1268
+ continue;
1269
+ matched = true;
1270
+ next = this.convert(schema, base, next);
1271
+ }
1272
+ if (!matched && additional !== void 0)
1273
+ next = this.convert(additional, base, next);
1274
+ if (next !== value[key]) {
1275
+ out ??= { ...value };
1276
+ out[key] = next;
1277
+ }
1278
+ }
1279
+ return out ?? value;
1280
+ }
1281
+ // ---------------------------------------------------------------------------------------------------------------
1282
+ // Pass 3: primitive coercion by type
1283
+ // ---------------------------------------------------------------------------------------------------------------
1284
+ coerceTypes(value, schema, base) {
1285
+ if (!isSchemaObject(schema))
1286
+ return value;
1287
+ const b = this.baseOf(schema, base);
1288
+ let next = value;
1289
+ if (Array.isArray(schema.allOf))
1290
+ for (const member of schema.allOf)
1291
+ next = this.coerceTypes(next, member, b);
1292
+ if (Array.isArray(schema.anyOf))
1293
+ next = this.coerceUnion(next, schema.anyOf, b);
1294
+ if (Array.isArray(schema.oneOf))
1295
+ next = this.coerceUnion(next, schema.oneOf, b);
1296
+ const types = typesOf(schema);
1297
+ const matchesUnionMember = types.length > 1 && types.some((type) => matchesType(next, type));
1298
+ if (types.length > 0 && !matchesUnionMember) {
1299
+ for (const type of types) {
1300
+ const candidate = coercePrimitive(next, type);
1301
+ if (candidate !== next) {
1302
+ next = candidate;
1303
+ break;
1304
+ }
1305
+ }
1306
+ }
1307
+ if (types.includes("object") && isPlainObject(next))
1308
+ next = this.coerceProperties(next, schema, b);
1309
+ if (types.includes("array") && Array.isArray(next))
1310
+ next = this.coerceItems(next, schema, b);
1311
+ return next;
1312
+ }
1313
+ coerceUnion(value, branches, base) {
1314
+ for (const branch of branches)
1315
+ if (this.passes(branch, base, value) === true)
1316
+ return value;
1317
+ for (const branch of branches) {
1318
+ const coerced = this.coerceTypes(value, branch, base);
1319
+ if (this.passes(branch, base, coerced) === true)
1320
+ return coerced;
1321
+ }
1322
+ return value;
1323
+ }
1324
+ coerceProperties(value, schema, base) {
1325
+ const properties = isSchemaObject(schema.properties) ? schema.properties : {};
1326
+ const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : [];
1327
+ const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0;
1328
+ let out;
1329
+ const set = (key, next) => {
1330
+ if (next === (out ?? value)[key])
1331
+ return;
1332
+ out ??= { ...value };
1333
+ out[key] = next;
1334
+ };
1335
+ for (const [key, property] of Object.entries(properties)) {
1336
+ if (key in value)
1337
+ set(key, this.coerceTypes(value[key], property, base));
1338
+ }
1339
+ for (const key of Object.keys(value)) {
1340
+ let matched = Object.hasOwn(properties, key);
1341
+ for (const [pattern, item] of patterns) {
1342
+ if (!pattern.test(key))
1343
+ continue;
1344
+ matched = true;
1345
+ set(key, this.coerceTypes((out ?? value)[key], item, base));
1346
+ }
1347
+ if (!matched && additional !== void 0)
1348
+ set(key, this.coerceTypes(value[key], additional, base));
1349
+ }
1350
+ return out ?? value;
1351
+ }
1352
+ coerceItems(value, schema, base) {
1353
+ return mapItems(value, (item, i) => {
1354
+ const itemSchema = itemSchemaAt(schema, i);
1355
+ return isSchemaObject(itemSchema) ? this.coerceTypes(item, itemSchema, base) : item;
1356
+ });
1357
+ }
1358
+ };
1359
+ function itemSchemaAt(schema, index) {
1360
+ if (Array.isArray(schema.items))
1361
+ return schema.items[index];
1362
+ if (Array.isArray(schema.prefixItems) && index < schema.prefixItems.length)
1363
+ return schema.prefixItems[index];
1364
+ return schema.items;
1365
+ }
1366
+ function mapItems(items, map) {
1367
+ let out;
1368
+ for (let i = 0; i < items.length; i++) {
1369
+ const next = map(items[i], i);
1370
+ if (next === items[i])
1371
+ continue;
1372
+ out ??= items.slice();
1373
+ out[i] = next;
1374
+ }
1375
+ return out ?? items;
1376
+ }
1377
+ function orValue(result, value) {
1378
+ return result === void 0 ? value : result.value;
1379
+ }
1380
+ function convertLiteral(literal, value) {
1381
+ if (literal === value)
1382
+ return value;
1383
+ const result = typeof literal === "string" ? tryString(value) : typeof literal === "number" ? tryNumber(value) : typeof literal === "boolean" ? tryBoolean(value) : typeof literal === "bigint" ? tryBigInt(value) : void 0;
1384
+ return result !== void 0 && result.value === literal ? result.value : value;
1385
+ }
1386
+ function tryString(value) {
1387
+ if (typeof value === "bigint" || typeof value === "boolean" || isFiniteNumber(value))
1388
+ return { value: String(value) };
1389
+ if (value === null)
1390
+ return { value: "null" };
1391
+ if (typeof value === "string")
1392
+ return { value };
1393
+ if (value === void 0)
1394
+ return { value: "" };
1395
+ return void 0;
1396
+ }
1397
+ var MAX_BIGINT = BigInt(Number.MAX_SAFE_INTEGER);
1398
+ var MIN_BIGINT = BigInt(Number.MIN_SAFE_INTEGER);
1399
+ function tryNumber(value) {
1400
+ if (typeof value === "bigint")
1401
+ return value <= MAX_BIGINT && value >= MIN_BIGINT ? { value: Number(value) } : void 0;
1402
+ if (typeof value === "boolean")
1403
+ return { value: value ? 1 : 0 };
1404
+ if (isFiniteNumber(value))
1405
+ return { value };
1406
+ if (value === null || value === void 0)
1407
+ return { value: 0 };
1408
+ if (typeof value !== "string")
1409
+ return void 0;
1410
+ const coerced = +value;
1411
+ if (Number.isFinite(coerced))
1412
+ return { value: coerced };
1413
+ const lowercase = value.toLowerCase();
1414
+ if (lowercase === "false")
1415
+ return { value: 0 };
1416
+ if (lowercase === "true")
1417
+ return { value: 1 };
1418
+ const big = bigIntOfString(value);
1419
+ return big !== void 0 && big <= MAX_BIGINT && big >= MIN_BIGINT ? { value: Number(big) } : void 0;
1420
+ }
1421
+ function bigIntOfString(value) {
1422
+ if (/^-?(0|[1-9]\d*)n$/.test(value))
1423
+ return BigInt(value.slice(0, -1));
1424
+ if (/^-?(0|[1-9]\d*)\.\d+$/.test(value))
1425
+ return BigInt(value.split(".")[0]);
1426
+ if (/^-?(0|[1-9]\d*)$/.test(value))
1427
+ return BigInt(value);
1428
+ return void 0;
1429
+ }
1430
+ function tryBigInt(value) {
1431
+ if (typeof value === "bigint")
1432
+ return { value };
1433
+ if (typeof value === "boolean")
1434
+ return { value: value ? 1n : 0n };
1435
+ if (isFiniteNumber(value))
1436
+ return { value: BigInt(Math.trunc(value)) };
1437
+ if (value === null || value === void 0)
1438
+ return { value: 0n };
1439
+ if (typeof value !== "string")
1440
+ return void 0;
1441
+ const big = bigIntOfString(value);
1442
+ if (big !== void 0)
1443
+ return { value: big };
1444
+ const lowercase = value.toLowerCase();
1445
+ return lowercase === "false" ? { value: 0n } : lowercase === "true" ? { value: 1n } : void 0;
1446
+ }
1447
+ function tryUndefined(value) {
1448
+ if (value === void 0 || value === null || value === 0n || value === false || value === 0)
1449
+ return { value: void 0 };
1450
+ if (typeof value !== "string")
1451
+ return void 0;
1452
+ const lowercase = value.toLowerCase();
1453
+ return lowercase === "undefined" || lowercase === "null" || value === "" || value === "0" ? { value: void 0 } : void 0;
1454
+ }
1455
+ function tryBoolean(value) {
1456
+ if (typeof value === "bigint")
1457
+ return value === 0n ? { value: false } : value === 1n ? { value: true } : void 0;
1458
+ if (typeof value === "boolean")
1459
+ return { value };
1460
+ if (isFiniteNumber(value))
1461
+ return value === 0 ? { value: false } : value === 1 ? { value: true } : void 0;
1462
+ if (value === null || value === void 0)
1463
+ return { value: false };
1464
+ if (typeof value !== "string")
1465
+ return void 0;
1466
+ const lowercase = value.toLowerCase();
1467
+ if (lowercase === "false" || value === "0")
1468
+ return { value: false };
1469
+ if (lowercase === "true" || value === "1")
1470
+ return { value: true };
1471
+ return void 0;
1472
+ }
1473
+ function tryNull(value) {
1474
+ if (typeof value === "bigint")
1475
+ return value === 0n ? { value: null } : void 0;
1476
+ if (typeof value === "boolean")
1477
+ return value === false ? { value: null } : void 0;
1478
+ if (isFiniteNumber(value))
1479
+ return value === 0 ? { value: null } : void 0;
1480
+ if (value === null || value === void 0)
1481
+ return { value: null };
1482
+ if (typeof value !== "string")
1483
+ return void 0;
1484
+ const lowercase = value.toLowerCase();
1485
+ return lowercase === "undefined" || lowercase === "null" || value === "" || value === "0" ? { value: null } : void 0;
1486
+ }
1487
+ function isFiniteNumber(value) {
1488
+ return typeof value === "number" && Number.isFinite(value);
1489
+ }
1490
+ function typesOf(schema) {
1491
+ if (typeof schema.type === "string")
1492
+ return [schema.type];
1493
+ if (Array.isArray(schema.type))
1494
+ return schema.type.filter((type) => typeof type === "string");
1495
+ return [];
1496
+ }
1497
+ function matchesType(value, type) {
1498
+ switch (type) {
1499
+ case "number":
1500
+ return Number.isFinite(value);
1501
+ case "integer":
1502
+ return typeof value === "number" && Number.isInteger(value);
1503
+ case "boolean":
1504
+ return typeof value === "boolean";
1505
+ case "string":
1506
+ return typeof value === "string";
1507
+ case "null":
1508
+ return value === null;
1509
+ case "bigint":
1510
+ return typeof value === "bigint";
1511
+ case "undefined":
1512
+ return value === void 0;
1513
+ case "array":
1514
+ return Array.isArray(value);
1515
+ case "object":
1516
+ return isPlainObject(value);
1517
+ default:
1518
+ return false;
1519
+ }
1520
+ }
1521
+ function coercePrimitive(value, type) {
1522
+ switch (type) {
1523
+ case "number":
1524
+ case "integer": {
1525
+ if (value === null)
1526
+ return 0;
1527
+ if (typeof value === "string" && value.trim() !== "") {
1528
+ const parsed = Number(value);
1529
+ if (type === "number" ? Number.isFinite(parsed) : Number.isInteger(parsed))
1530
+ return parsed;
1531
+ }
1532
+ if (typeof value === "boolean")
1533
+ return value ? 1 : 0;
1534
+ return value;
1535
+ }
1536
+ case "boolean":
1537
+ if (value === null)
1538
+ return false;
1539
+ if (value === "true" || value === 1)
1540
+ return true;
1541
+ if (value === "false" || value === 0)
1542
+ return false;
1543
+ return value;
1544
+ case "string":
1545
+ if (value === null)
1546
+ return "";
1547
+ if (typeof value === "number" || typeof value === "boolean")
1548
+ return String(value);
1549
+ return value;
1550
+ case "null":
1551
+ return value === "" || value === 0 || value === false ? null : value;
1552
+ default:
1553
+ return value;
1554
+ }
1555
+ }
1556
+ function isPlainObject(value) {
1557
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1558
+ }
1559
+
1560
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/annotations.js
1561
+ function newAnnotations() {
1562
+ return { props: null, allProps: false, items: 0, allItems: false, indexes: null };
1563
+ }
1564
+ function merge(a, b) {
1565
+ if (b.props !== null)
1566
+ for (const k of b.props)
1567
+ addProp(a, k);
1568
+ a.allProps ||= b.allProps;
1569
+ if (b.items > a.items)
1570
+ a.items = b.items;
1571
+ a.allItems ||= b.allItems;
1572
+ if (b.indexes !== null)
1573
+ for (const i of b.indexes)
1574
+ addIndex(a, i);
1575
+ }
1576
+ function addProp(a, key) {
1577
+ if (a.props === null)
1578
+ a.props = /* @__PURE__ */ new Set();
1579
+ a.props.add(key);
1580
+ }
1581
+ function addIndex(a, index) {
1582
+ if (a.indexes === null)
1583
+ a.indexes = /* @__PURE__ */ new Set();
1584
+ a.indexes.add(index);
1585
+ }
1586
+ var ANNOTATING_TRUE = () => true;
1587
+ var ANNOTATING_FALSE = () => false;
1588
+ function indirectAnnotating(slot) {
1589
+ return (v, a) => slot.check(v, a);
1590
+ }
1591
+ function ignoreAnnotations(check) {
1592
+ return (v) => check(v);
1593
+ }
1594
+ function withFreshAnnotations(check) {
1595
+ return (v) => check(v, newAnnotations());
1596
+ }
1597
+ function scopedAnnotating(scope, uri, check) {
1598
+ return (v, a) => {
1599
+ scope.push(uri);
1600
+ const ok = check(v, a);
1601
+ scope.pop();
1602
+ return ok;
1603
+ };
1604
+ }
1605
+ function isolateAnnotations(check) {
1606
+ return (v, a) => {
1607
+ const b = newAnnotations();
1608
+ if (!check(v, b))
1609
+ return false;
1610
+ merge(a, b);
1611
+ return true;
1612
+ };
1613
+ }
1614
+ function annotateAll(plain, parts) {
1615
+ return (v, a) => {
1616
+ if (!plain(v))
1617
+ return false;
1618
+ for (let i = 0; i < parts.length; i++)
1619
+ if (!parts[i](v, a))
1620
+ return false;
1621
+ return true;
1622
+ };
1623
+ }
1624
+ function annotateObject(props, patterns, additional) {
1625
+ const declared = new Set(props.map(([k]) => k));
1626
+ return (v, a) => {
1627
+ if (!isObject(v))
1628
+ return true;
1629
+ const seen = [];
1630
+ for (const [k, check] of props) {
1631
+ if (!Object.hasOwn(v, k))
1632
+ continue;
1633
+ if (!check(v[k]))
1634
+ return false;
1635
+ seen.push(k);
1636
+ }
1637
+ for (const k of Object.keys(v)) {
1638
+ let matched = declared.has(k);
1639
+ for (const [re, check] of patterns) {
1640
+ if (re.test(k)) {
1641
+ if (!check(v[k]))
1642
+ return false;
1643
+ matched = true;
1644
+ seen.push(k);
1645
+ }
1646
+ }
1647
+ if (!matched && additional !== void 0) {
1648
+ if (!additional(v[k]))
1649
+ return false;
1650
+ seen.push(k);
1651
+ }
1652
+ }
1653
+ for (const k of seen)
1654
+ addProp(a, k);
1655
+ return true;
1656
+ };
1657
+ }
1658
+ function annotateArray(prefix, rest, contains, minContains, maxContains) {
1659
+ return (v, a) => {
1660
+ if (!Array.isArray(v))
1661
+ return true;
1662
+ const m = Math.min(v.length, prefix.length);
1663
+ for (let i = 0; i < m; i++)
1664
+ if (!prefix[i](v[i]))
1665
+ return false;
1666
+ if (rest !== void 0) {
1667
+ for (let i = prefix.length; i < v.length; i++)
1668
+ if (!rest(v[i]))
1669
+ return false;
1670
+ a.allItems = true;
1671
+ }
1672
+ if (m > a.items)
1673
+ a.items = m;
1674
+ if (contains !== void 0) {
1675
+ let n = 0;
1676
+ for (let i = 0; i < v.length; i++) {
1677
+ if (contains(v[i])) {
1678
+ n++;
1679
+ addIndex(a, i);
1680
+ }
1681
+ }
1682
+ if (n < minContains || n > maxContains)
1683
+ return false;
1684
+ }
1685
+ return true;
1686
+ };
1687
+ }
1688
+ function annotateAny(branches, exactlyOne) {
1689
+ return (v, a) => {
1690
+ let n = 0;
1691
+ for (const branch of branches) {
1692
+ const b = newAnnotations();
1693
+ if (branch(v, b)) {
1694
+ n++;
1695
+ merge(a, b);
1696
+ }
1697
+ }
1698
+ return exactlyOne ? n === 1 : n > 0;
1699
+ };
1700
+ }
1701
+ function annotateIf(cond, then, otherwise) {
1702
+ return (v, a) => {
1703
+ const b = newAnnotations();
1704
+ if (cond(v, b)) {
1705
+ merge(a, b);
1706
+ return then === void 0 || then(v, a);
1707
+ }
1708
+ return otherwise === void 0 || otherwise(v, a);
1709
+ };
1710
+ }
1711
+ function annotateDependent(key, check) {
1712
+ return (v, a) => !isObject(v) || !Object.hasOwn(v, key) || check(v, a);
1713
+ }
1714
+ function unevaluatedProperties(check) {
1715
+ return (v, a) => {
1716
+ if (!isObject(v) || a.allProps)
1717
+ return true;
1718
+ for (const k of Object.keys(v))
1719
+ if (!(a.props?.has(k) ?? false) && !check(v[k]))
1720
+ return false;
1721
+ a.allProps = true;
1722
+ return true;
1723
+ };
1724
+ }
1725
+ function unevaluatedItems(check) {
1726
+ return (v, a) => {
1727
+ if (!Array.isArray(v) || a.allItems)
1728
+ return true;
1729
+ for (let i = a.items; i < v.length; i++)
1730
+ if (!(a.indexes?.has(i) ?? false) && !check(v[i]))
1731
+ return false;
1732
+ a.allItems = true;
1733
+ return true;
1734
+ };
1735
+ }
1736
+
1737
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/compiler.js
1738
+ var RESTART = /* @__PURE__ */ Symbol("restart");
1739
+ var Compiler = class {
1740
+ r;
1741
+ draft;
1742
+ formats;
1743
+ /** Whether checks track the dynamic scope (the schema has a bookended `$dynamicRef`). */
1744
+ dynamic;
1745
+ schema;
1746
+ scope;
1747
+ cache = /* @__PURE__ */ new Map();
1748
+ annotatingCache = /* @__PURE__ */ new Map();
1749
+ constructor(schema, options, dynamic) {
1750
+ this.schema = schema;
1751
+ this.r = new Resolver(schema, options);
1752
+ this.draft = this.r.draft;
1753
+ this.formats = options.formats;
1754
+ this.dynamic = dynamic;
1755
+ this.scope = [];
1756
+ }
1757
+ /** The check of the root schema. */
1758
+ root() {
1759
+ return this.check(this.schema, this.r.rootBase);
1760
+ }
1761
+ /** The check of a schema (cached by schema object; a recursive reference goes through an indirection). */
1762
+ check(node, base) {
1763
+ if (node === true)
1764
+ return ALWAYS;
1765
+ if (node === false)
1766
+ return NEVER;
1767
+ if (!isSchemaObject(node))
1768
+ throw new Error(`A schema must be an object or a boolean, got ${JSON.stringify(node)}`);
1769
+ const cached = this.cache.get(node);
1770
+ if (cached !== void 0)
1771
+ return cached;
1772
+ const bare = this.bareType(node);
1773
+ if (bare !== void 0)
1774
+ return bare;
1775
+ const slot = { check: void 0 };
1776
+ this.cache.set(node, indirect(slot));
1777
+ const check = this.build(node, this.r.baseFor(node, base));
1778
+ slot.check = check;
1779
+ this.cache.set(node, check);
1780
+ return check;
1781
+ }
1782
+ build(node, base) {
1783
+ if (this.draft === "7" && typeof node.$ref === "string")
1784
+ return this.ref(node.$ref, base);
1785
+ if (this.draft !== "7" && (node.unevaluatedProperties !== void 0 || node.unevaluatedItems !== void 0)) {
1786
+ return withFreshAnnotations(this.annotating(node, base));
1787
+ }
1788
+ const check = this.plain(node, base);
1789
+ return this.dynamic && this.r.isResource(node, base) ? scopedCheck(this.scope, base, check) : check;
1790
+ }
1791
+ /**
1792
+ * The module-level check of a schema that is only a `type` (with annotations), `ALWAYS` for one with no assertion
1793
+ * at all; undefined for every other schema. These are the most common subschemas and cost nothing to share.
1794
+ */
1795
+ bareType(node) {
1796
+ let type;
1797
+ for (const k in node) {
1798
+ if (k === "type")
1799
+ type = node.type;
1800
+ else if (!NEUTRAL_KEYWORDS.has(k))
1801
+ return void 0;
1802
+ }
1803
+ if (type === void 0)
1804
+ return ALWAYS;
1805
+ return typeof type === "string" ? TYPE_CHECKS.get(type) : void 0;
1806
+ }
1807
+ /** Every keyword of `node`, not tracking annotations. */
1808
+ plain(node, base) {
1809
+ const parts = [];
1810
+ const types = node.type === void 0 ? void 0 : Array.isArray(node.type) ? node.type : [node.type];
1811
+ const single = types?.length === 1 ? types[0] : void 0;
1812
+ let typeInGroup = false;
1813
+ if (single === "bytes") {
1814
+ parts.push(bytesCheck(number(node.minLength) ?? 0, number(node.maxLength) ?? Number.POSITIVE_INFINITY));
1815
+ typeInGroup = true;
1816
+ } else {
1817
+ const string = this.stringGroup(node, single === "string");
1818
+ if (string !== void 0)
1819
+ parts.push(string);
1820
+ const numeric = single === "number" || single === "integer" || single === "bigint";
1821
+ const mode = single === "number" ? 1 : single === "integer" ? 2 : single === "bigint" ? 3 : 0;
1822
+ const number2 = this.numberGroup(node, mode);
1823
+ if (number2 !== void 0)
1824
+ parts.push(number2);
1825
+ const object = this.objectGroup(node, base, single === "object");
1826
+ if (object !== void 0)
1827
+ parts.push(object);
1828
+ const array = this.arrayGroup(node, base, single === "array");
1829
+ if (array !== void 0)
1830
+ parts.push(array);
1831
+ typeInGroup = single === "string" && string !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0;
1832
+ }
1833
+ if (types !== void 0 && !typeInGroup)
1834
+ parts.unshift(typeCheck(types));
1835
+ this.inPlace(node, base, parts);
1836
+ return and(parts);
1837
+ }
1838
+ // The keywords that apply to the value itself, whatever its type.
1839
+ inPlace(node, base, parts) {
1840
+ if (Array.isArray(node.enum))
1841
+ parts.push(enumCheck(node.enum));
1842
+ if (Object.hasOwn(node, "const"))
1843
+ parts.push(constCheck(node.const));
1844
+ if (Array.isArray(node.allOf))
1845
+ parts.push(and(node.allOf.map((s) => this.check(s, base))));
1846
+ if (Array.isArray(node.anyOf))
1847
+ parts.push(this.union(node.anyOf, base, false));
1848
+ if (Array.isArray(node.oneOf))
1849
+ parts.push(this.union(node.oneOf, base, true));
1850
+ if (node.not !== void 0)
1851
+ parts.push(notCheck(this.check(node.not, base)));
1852
+ if (node.if !== void 0 && (node.then !== void 0 || node.else !== void 0)) {
1853
+ const then = node.then === void 0 ? ALWAYS : this.check(node.then, base);
1854
+ const otherwise = node.else === void 0 ? ALWAYS : this.check(node.else, base);
1855
+ parts.push(ifCheck(this.check(node.if, base), then, otherwise));
1856
+ }
1857
+ if (typeof node.$ref === "string")
1858
+ parts.push(this.ref(node.$ref, base));
1859
+ if (this.draft !== "7" && typeof node.$dynamicRef === "string") {
1860
+ parts.push(this.dynamicRef(node.$dynamicRef, base));
1861
+ }
1862
+ }
1863
+ union(branches, base, exactlyOne) {
1864
+ const checks = () => branches.map((s) => this.check(s, base));
1865
+ return constUnion(branches, exactlyOne) ?? this.tagged(branches, base) ?? (exactlyOne ? oneCheck(checks()) : anyOf(checks()));
1866
+ }
1867
+ ref(ref, base) {
1868
+ const target = this.r.resolve(ref, base);
1869
+ const check = this.check(target.node, target.base);
1870
+ return this.dynamic && target.base !== base ? scopedCheck(this.scope, target.base, check) : check;
1871
+ }
1872
+ dynamicRef(ref, base) {
1873
+ const resolved = this.bookended(ref, base);
1874
+ if (resolved === void 0)
1875
+ return this.ref(ref, base);
1876
+ const { initial, name } = resolved;
1877
+ const fallback = this.check(initial.node, initial.base);
1878
+ const lookup = this.dynamicLookup(name, (node, b) => this.check(node, b));
1879
+ const scope = this.scope;
1880
+ return (v) => {
1881
+ for (let i = 0; i < scope.length; i++) {
1882
+ const check = lookup(scope[i]);
1883
+ if (check !== null)
1884
+ return check(v);
1885
+ }
1886
+ return fallback(v);
1887
+ };
1888
+ }
1889
+ /** The initial target and anchor name of a `$dynamicRef` that resolves dynamically, or undefined for a plain ref. */
1890
+ bookended(ref, base) {
1891
+ const initial = this.r.resolve(ref, base);
1892
+ const uri = resolveUri(ref, base);
1893
+ const name = uri.slice(documentOf(uri).length + 1);
1894
+ const anchored = isSchemaObject(initial.node) && initial.node.$dynamicAnchor === name;
1895
+ if (name === "" || name.startsWith("/") || !anchored)
1896
+ return void 0;
1897
+ if (!this.dynamic)
1898
+ throw RESTART;
1899
+ return { initial, name };
1900
+ }
1901
+ // Resolved at run time against the dynamic scope, so a schema with a bookended $dynamicRef keeps its compiler.
1902
+ dynamicLookup(name, compile2) {
1903
+ const found = /* @__PURE__ */ new Map();
1904
+ return (uri) => {
1905
+ const key = `${uri}#${name}`;
1906
+ let check = found.get(key);
1907
+ if (check === void 0) {
1908
+ const target = this.r.dynamicAnchors.get(key);
1909
+ check = target === void 0 ? null : compile2(target, this.r.baseOf.get(target) ?? uri);
1910
+ found.set(key, check);
1911
+ }
1912
+ return check;
1913
+ };
1914
+ }
1915
+ /** anyOf/oneOf whose branches are all objects with a distinct required const on one key: the tag picks the branch. */
1916
+ tagged(branches, base) {
1917
+ if (branches.length < 2)
1918
+ return void 0;
1919
+ const resolved = [];
1920
+ for (const branch of branches) {
1921
+ if (!isSchemaObject(branch))
1922
+ return void 0;
1923
+ const ref = typeof branch.$ref === "string" && Object.keys(branch).length === 1 ? branch.$ref : void 0;
1924
+ const node = ref === void 0 ? branch : this.r.resolve(ref, this.r.baseFor(branch, base)).node;
1925
+ if (!isSchemaObject(node))
1926
+ return void 0;
1927
+ resolved.push(node);
1928
+ }
1929
+ const first = resolved[0].properties;
1930
+ if (!isSchemaObject(first))
1931
+ return void 0;
1932
+ for (const key of Object.keys(first)) {
1933
+ const tags = resolved.map((s) => tagOf(s, key));
1934
+ if (tags.some((t) => t === void 0) || new Set(tags).size !== tags.length)
1935
+ continue;
1936
+ return taggedCheck(key, tags, branches.map((s) => this.check(s, base)));
1937
+ }
1938
+ return void 0;
1939
+ }
1940
+ stringGroup(node, strict) {
1941
+ const min = number(node.minLength) ?? 0;
1942
+ const max = number(node.maxLength) ?? Number.POSITIVE_INFINITY;
1943
+ const re = typeof node.pattern === "string" ? sharedRegex(node.pattern) : void 0;
1944
+ const format = this.formats !== void 0 && typeof node.format === "string" && Object.hasOwn(this.formats, node.format) ? this.formats[node.format] : void 0;
1945
+ if (min === 0 && max === Number.POSITIVE_INFINITY && re === void 0 && format === void 0)
1946
+ return void 0;
1947
+ return stringCheck(strict, min, max, re, format);
1948
+ }
1949
+ numberGroup(node, mode) {
1950
+ const min = bound(node.minimum);
1951
+ const max = bound(node.maximum);
1952
+ const xmin = bound(node.exclusiveMinimum);
1953
+ const xmax = bound(node.exclusiveMaximum);
1954
+ const multipleOf = bound(node.multipleOf);
1955
+ if ([min, max, xmin, xmax, multipleOf].every((x) => x === void 0))
1956
+ return void 0;
1957
+ const inf = Number.POSITIVE_INFINITY;
1958
+ return numberCheck(mode, min ?? -inf, max ?? inf, xmin ?? -inf, xmax ?? inf, multipleOf);
1959
+ }
1960
+ objectGroup(node, base, strict) {
1961
+ const onlyCore = OBJECT_EXTRAS.every((k) => node[k] === void 0);
1962
+ const core = this.objectCore(node, base, onlyCore ? strict ? GUARD_STRICT : GUARD_LOOSE : GUARD_NONE);
1963
+ if (core !== void 0 && onlyCore)
1964
+ return core;
1965
+ const parts = core === void 0 ? [] : [core];
1966
+ if (node.propertyNames !== void 0)
1967
+ parts.push(propertyNamesCheck(this.check(node.propertyNames, base)));
1968
+ const minProperties = number(node.minProperties);
1969
+ const maxProperties = number(node.maxProperties);
1970
+ if (minProperties !== void 0 || maxProperties !== void 0) {
1971
+ parts.push(propertyCountCheck(minProperties ?? 0, maxProperties ?? Number.POSITIVE_INFINITY));
1972
+ }
1973
+ const dependentRequired = [];
1974
+ const dependentSchemas = [];
1975
+ if (this.draft !== "7") {
1976
+ for (const [k, list] of entries(node.dependentRequired))
1977
+ if (Array.isArray(list))
1978
+ dependentRequired.push([k, list]);
1979
+ for (const [k, s] of entries(node.dependentSchemas))
1980
+ dependentSchemas.push([k, this.check(s, base)]);
1981
+ }
1982
+ for (const [k, d] of entries(node.dependencies)) {
1983
+ if (Array.isArray(d))
1984
+ dependentRequired.push([k, d]);
1985
+ else
1986
+ dependentSchemas.push([k, this.check(d, base)]);
1987
+ }
1988
+ if (dependentRequired.length > 0)
1989
+ parts.push(dependentRequiredCheck(dependentRequired));
1990
+ if (dependentSchemas.length > 0)
1991
+ parts.push(dependentSchemasCheck(dependentSchemas));
1992
+ if (parts.length === 0)
1993
+ return strict ? IS_OBJECT : void 0;
1994
+ return guardObject(and(parts), strict);
1995
+ }
1996
+ objectCore(node, base, guard) {
1997
+ const properties = isSchemaObject(node.properties) ? node.properties : {};
1998
+ const required = Array.isArray(node.required) ? node.required.filter((k) => typeof k === "string") : [];
1999
+ const patterns = isSchemaObject(node.patternProperties) ? node.patternProperties : {};
2000
+ const additional = node.additionalProperties;
2001
+ const keys = Object.keys(properties);
2002
+ const patternKeys = Object.keys(patterns);
2003
+ if (keys.length + required.length + patternKeys.length === 0 && (additional === void 0 || additional === true)) {
2004
+ return void 0;
2005
+ }
2006
+ const entries2 = [];
2007
+ for (const k of keys) {
2008
+ const check = this.check(properties[k], base);
2009
+ const leaf2 = leafOf(check);
2010
+ const flags = (leaf2?.[0] ?? 0) | (required.includes(k) ? REQUIRED : 0) | (k in Object.prototype ? INHERITED : 0);
2011
+ entries2.push(k, leaf2 === void 0 ? check : leaf2[1], flags);
2012
+ }
2013
+ const extraRequired = required.filter((k) => !Object.hasOwn(properties, k));
2014
+ const pats = patternKeys.map((p) => [sharedRegex(p), this.check(patterns[p], base)]);
2015
+ const extra = additional === void 0 || additional === true ? void 0 : this.check(additional, base);
2016
+ if (pats.length === 0 && extraRequired.length === 0 && (extra === void 0 || additional === false)) {
2017
+ const requiredCount = keys.filter((k) => required.includes(k)).length;
2018
+ return declaredObject(entries2, requiredCount, additional === false, guard);
2019
+ }
2020
+ return openObject(entries2, keys, extraRequired, pats, extra, guard);
2021
+ }
2022
+ arrayGroup(node, base, strict) {
2023
+ let prefix = [];
2024
+ let rest;
2025
+ if (Array.isArray(node.items)) {
2026
+ prefix = node.items;
2027
+ rest = node.additionalItems;
2028
+ } else {
2029
+ if (this.draft !== "7" && Array.isArray(node.prefixItems))
2030
+ prefix = node.prefixItems;
2031
+ rest = node.items;
2032
+ }
2033
+ const prefixChecks = prefix.map((s) => this.check(s, base));
2034
+ const restCheck = rest === void 0 || rest === true ? void 0 : this.check(rest, base);
2035
+ const minItems = number(node.minItems);
2036
+ const maxItems = number(node.maxItems);
2037
+ if (node.contains === void 0 && node.uniqueItems !== true && (prefixChecks.length > 0 || restCheck !== void 0)) {
2038
+ const guard = strict ? GUARD_STRICT : GUARD_LOOSE;
2039
+ return listCheck(guard, minItems ?? 0, maxItems ?? Number.POSITIVE_INFINITY, prefixChecks, restCheck);
2040
+ }
2041
+ const parts = [];
2042
+ if (prefixChecks.length > 0 || restCheck !== void 0)
2043
+ parts.push(itemsCheck(prefixChecks, restCheck));
2044
+ if (minItems !== void 0 || maxItems !== void 0) {
2045
+ parts.push(lengthCheck(minItems ?? 0, maxItems ?? Number.POSITIVE_INFINITY));
2046
+ }
2047
+ if (node.contains !== void 0) {
2048
+ const min = this.draft === "7" ? 1 : number(node.minContains) ?? 1;
2049
+ const max = this.draft === "7" ? Number.POSITIVE_INFINITY : number(node.maxContains) ?? Number.POSITIVE_INFINITY;
2050
+ parts.push(containsCheck(this.check(node.contains, base), min, max));
2051
+ }
2052
+ if (node.uniqueItems === true)
2053
+ parts.push(uniqueCheck);
2054
+ if (parts.length === 0)
2055
+ return strict ? IS_ARRAY : void 0;
2056
+ return guardArray(and(parts), strict);
2057
+ }
2058
+ /** The annotating check of a schema evaluated in place (only below `unevaluatedProperties`/`unevaluatedItems`). */
2059
+ annotating(node, base) {
2060
+ if (node === true)
2061
+ return ANNOTATING_TRUE;
2062
+ if (node === false)
2063
+ return ANNOTATING_FALSE;
2064
+ if (!isSchemaObject(node))
2065
+ throw new Error(`A schema must be an object or a boolean, got ${JSON.stringify(node)}`);
2066
+ const cached = this.annotatingCache.get(node);
2067
+ if (cached !== void 0)
2068
+ return cached;
2069
+ const slot = { check: void 0 };
2070
+ this.annotatingCache.set(node, indirectAnnotating(slot));
2071
+ const check = this.buildAnnotating(node, this.r.baseFor(node, base));
2072
+ slot.check = check;
2073
+ this.annotatingCache.set(node, check);
2074
+ return check;
2075
+ }
2076
+ buildAnnotating(node, base) {
2077
+ const rest = {};
2078
+ let annotates = false;
2079
+ for (const k of Object.keys(node)) {
2080
+ if (ANNOTATING.has(k))
2081
+ annotates = true;
2082
+ else
2083
+ rest[k] = node[k];
2084
+ }
2085
+ const plain = this.plain(rest, base);
2086
+ const parts = [];
2087
+ if (annotates)
2088
+ this.annotatingParts(node, base, parts);
2089
+ const all = parts.length === 0 ? ignoreAnnotations(plain) : annotateAll(plain, parts);
2090
+ const own = node.unevaluatedProperties !== void 0 || node.unevaluatedItems !== void 0 ? isolateAnnotations(all) : all;
2091
+ return this.dynamic && this.r.isResource(node, base) ? scopedAnnotating(this.scope, base, own) : own;
2092
+ }
2093
+ annotatingParts(node, base, parts) {
2094
+ if (node.properties !== void 0 || node.patternProperties !== void 0 || node.additionalProperties !== void 0) {
2095
+ const props = entries(node.properties).map(([k, s]) => [k, this.check(s, base)]);
2096
+ const pats = entries(node.patternProperties).map(([p, s]) => [sharedRegex(p), this.check(s, base)]);
2097
+ const extra = node.additionalProperties === void 0 ? void 0 : this.check(node.additionalProperties, base);
2098
+ parts.push(annotateObject(props, pats, extra));
2099
+ }
2100
+ if (node.prefixItems !== void 0 || node.items !== void 0 || node.contains !== void 0) {
2101
+ const prefix = Array.isArray(node.prefixItems) ? node.prefixItems : Array.isArray(node.items) ? node.items : [];
2102
+ const rest = Array.isArray(node.items) ? node.additionalItems : node.items;
2103
+ parts.push(annotateArray(prefix.map((s) => this.check(s, base)), rest === void 0 ? void 0 : this.check(rest, base), node.contains === void 0 ? void 0 : this.check(node.contains, base), number(node.minContains) ?? 1, number(node.maxContains) ?? Number.POSITIVE_INFINITY));
2104
+ }
2105
+ if (Array.isArray(node.allOf))
2106
+ for (const s of node.allOf)
2107
+ parts.push(this.annotating(s, base));
2108
+ if (Array.isArray(node.anyOf))
2109
+ parts.push(annotateAny(node.anyOf.map((s) => this.annotating(s, base)), false));
2110
+ if (Array.isArray(node.oneOf))
2111
+ parts.push(annotateAny(node.oneOf.map((s) => this.annotating(s, base)), true));
2112
+ if (node.if !== void 0) {
2113
+ const then = node.then === void 0 ? void 0 : this.annotating(node.then, base);
2114
+ const otherwise = node.else === void 0 ? void 0 : this.annotating(node.else, base);
2115
+ parts.push(annotateIf(this.annotating(node.if, base), then, otherwise));
2116
+ }
2117
+ if (typeof node.$ref === "string")
2118
+ parts.push(this.annotatingRef(node.$ref, base));
2119
+ if (typeof node.$dynamicRef === "string")
2120
+ parts.push(this.annotatingDynamicRef(node.$dynamicRef, base));
2121
+ for (const [k, s] of entries(node.dependentSchemas))
2122
+ parts.push(annotateDependent(k, this.annotating(s, base)));
2123
+ if (node.unevaluatedProperties !== void 0) {
2124
+ parts.push(unevaluatedProperties(this.check(node.unevaluatedProperties, base)));
2125
+ }
2126
+ if (node.unevaluatedItems !== void 0)
2127
+ parts.push(unevaluatedItems(this.check(node.unevaluatedItems, base)));
2128
+ }
2129
+ annotatingRef(ref, base) {
2130
+ const target = this.r.resolve(ref, base);
2131
+ const check = this.annotating(target.node, target.base);
2132
+ return this.dynamic && target.base !== base ? scopedAnnotating(this.scope, target.base, check) : check;
2133
+ }
2134
+ annotatingDynamicRef(ref, base) {
2135
+ const resolved = this.bookended(ref, base);
2136
+ if (resolved === void 0)
2137
+ return this.annotatingRef(ref, base);
2138
+ const { initial, name } = resolved;
2139
+ const fallback = this.annotating(initial.node, initial.base);
2140
+ const lookup = this.dynamicLookup(name, (node, b) => this.annotating(node, b));
2141
+ const scope = this.scope;
2142
+ return (v, a) => {
2143
+ for (let i = 0; i < scope.length; i++) {
2144
+ const check = lookup(scope[i]);
2145
+ if (check !== null)
2146
+ return check(v, a);
2147
+ }
2148
+ return fallback(v, a);
2149
+ };
2150
+ }
2151
+ };
2152
+ var NEUTRAL_KEYWORDS = /* @__PURE__ */ new Set([
2153
+ "$schema",
2154
+ "$comment",
2155
+ "title",
2156
+ "description",
2157
+ "default",
2158
+ "examples",
2159
+ "deprecated",
2160
+ "readOnly",
2161
+ "writeOnly",
2162
+ "$defs",
2163
+ "definitions",
2164
+ "contentEncoding",
2165
+ "contentMediaType",
2166
+ "minContains",
2167
+ "maxContains",
2168
+ "$vocabulary"
2169
+ ]);
2170
+ var OBJECT_EXTRAS = [
2171
+ "propertyNames",
2172
+ "minProperties",
2173
+ "maxProperties",
2174
+ "dependentRequired",
2175
+ "dependentSchemas",
2176
+ "dependencies"
2177
+ ];
2178
+ var ANNOTATING = /* @__PURE__ */ new Set([
2179
+ "properties",
2180
+ "patternProperties",
2181
+ "additionalProperties",
2182
+ "prefixItems",
2183
+ "items",
2184
+ "additionalItems",
2185
+ "contains",
2186
+ "minContains",
2187
+ "maxContains",
2188
+ "allOf",
2189
+ "anyOf",
2190
+ "oneOf",
2191
+ "if",
2192
+ "then",
2193
+ "else",
2194
+ "$ref",
2195
+ "$dynamicRef",
2196
+ "dependentSchemas",
2197
+ "unevaluatedProperties",
2198
+ "unevaluatedItems"
2199
+ ]);
2200
+ function constUnion(branches, exactlyOne) {
2201
+ const values = [];
2202
+ for (const branch of branches) {
2203
+ if (!isSchemaObject(branch) || !Object.hasOwn(branch, "const"))
2204
+ return void 0;
2205
+ for (const k of Object.keys(branch))
2206
+ if (k !== "const" && !NEUTRAL_KEYWORDS.has(k))
2207
+ return void 0;
2208
+ if (typeof branch.const === "object" && branch.const !== null)
2209
+ return void 0;
2210
+ if (exactlyOne && values.includes(branch.const))
2211
+ return void 0;
2212
+ values.push(branch.const);
2213
+ }
2214
+ return enumCheck(values);
2215
+ }
2216
+ function anyOf(checks) {
2217
+ const types = [];
2218
+ const rest = [];
2219
+ for (const check of checks) {
2220
+ const type = BARE_TYPES.get(check);
2221
+ if (type === void 0)
2222
+ rest.push(check);
2223
+ else
2224
+ types.push(type);
2225
+ }
2226
+ return types.length === 0 ? anyCheck(rest) : maskedAnyCheck(typeMask(types), rest);
2227
+ }
2228
+ var BARE_TYPES = new Map([...TYPE_CHECKS].map(([type, check]) => [check, type]));
2229
+ function tagOf(branch, key) {
2230
+ const properties = branch.properties;
2231
+ if (branch.type !== "object" || !Array.isArray(branch.required) || !branch.required.includes(key))
2232
+ return void 0;
2233
+ const tag = isSchemaObject(properties) ? properties[key] : void 0;
2234
+ if (!isSchemaObject(tag) || !Object.hasOwn(tag, "const"))
2235
+ return void 0;
2236
+ return typeof tag.const === "object" && tag.const !== null ? void 0 : tag.const;
2237
+ }
2238
+ function bound(value) {
2239
+ return typeof value === "number" || typeof value === "bigint" ? value : void 0;
2240
+ }
2241
+ function number(value) {
2242
+ return typeof value === "number" ? value : void 0;
2243
+ }
2244
+ function entries(value) {
2245
+ return isSchemaObject(value) ? Object.entries(value) : [];
2246
+ }
2247
+
2248
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/explain.js
2249
+ var Explainer = class {
2250
+ c;
2251
+ schema;
2252
+ /**
2253
+ * The errors of `$ref` targets for object values, within one errors() call: a recursive union explains each branch
2254
+ * to pick the one to blame, and every branch would explain the same children again, exponentially in the depth.
2255
+ */
2256
+ memo = void 0;
2257
+ constructor(compiler2, schema) {
2258
+ this.c = compiler2;
2259
+ this.schema = schema;
2260
+ compiler2.root();
2261
+ }
2262
+ /** The errors of `value`, at least one (`value` failed the check). */
2263
+ errors(value) {
2264
+ const out = [];
2265
+ try {
2266
+ this.walk(this.schema, this.c.r.rootBase, value, "", out);
2267
+ } finally {
2268
+ this.memo = void 0;
2269
+ }
2270
+ if (out.length === 0)
2271
+ out.push({ path: "", keyword: "schema", message: "invalid" });
2272
+ return out;
2273
+ }
2274
+ ok(node, base, v) {
2275
+ return this.c.check(node, base)(v);
2276
+ }
2277
+ // For $dynamicRef schemas this check runs outside the original dynamic scope, so their errors are approximate.
2278
+ walk(node, base, v, path, out) {
2279
+ if (node === true)
2280
+ return;
2281
+ if (node === false) {
2282
+ out.push({ path, keyword: "false", message: "no value is allowed here" });
2283
+ return;
2284
+ }
2285
+ if (!isSchemaObject(node))
2286
+ return;
2287
+ const b = this.c.r.baseFor(node, base);
2288
+ if (this.ok(node, b, v))
2289
+ return;
2290
+ const start = out.length;
2291
+ const push = (keyword, message, at = path) => {
2292
+ out.push({ path: at, keyword, message });
2293
+ };
2294
+ if (this.c.draft === "7" && typeof node.$ref === "string") {
2295
+ this.walkRef(node.$ref, b, v, path, out);
2296
+ return;
2297
+ }
2298
+ if (node.type !== void 0) {
2299
+ const types = Array.isArray(node.type) ? node.type : [node.type];
2300
+ const checks = types.map((t) => (typeof t === "string" ? TYPE_CHECKS.get(t) : void 0) ?? NEVER);
2301
+ if (!checks.some((check) => check(v))) {
2302
+ push("type", `expected ${types.join(" or ")}, got ${typeName(v)}`);
2303
+ return;
2304
+ }
2305
+ }
2306
+ if (Array.isArray(node.enum) && !enumCheck(node.enum)(v))
2307
+ push("enum", `expected one of ${listValues(node.enum)}`);
2308
+ if (Object.hasOwn(node, "const") && !constCheck(node.const)(v))
2309
+ push("const", `expected ${JSON.stringify(node.const)}`);
2310
+ if (typeof v === "string" && node.type !== "bytes")
2311
+ this.walkString(node, v, push);
2312
+ if (v instanceof Uint8Array && node.type === "bytes")
2313
+ this.walkBytes(node, v, push);
2314
+ if (typeof v === "number" || typeof v === "bigint")
2315
+ this.walkNumber(node, v, push);
2316
+ if (isObject(v))
2317
+ this.walkObject(node, b, v, path, out, push);
2318
+ if (Array.isArray(v))
2319
+ this.walkArray(node, b, v, path, out, push);
2320
+ if (Array.isArray(node.allOf))
2321
+ for (const s of node.allOf)
2322
+ this.walk(s, b, v, path, out);
2323
+ if (Array.isArray(node.anyOf))
2324
+ this.walkUnion(node.anyOf, b, v, path, out, false);
2325
+ if (Array.isArray(node.oneOf))
2326
+ this.walkUnion(node.oneOf, b, v, path, out, true);
2327
+ if (node.not !== void 0 && this.ok(node.not, b, v))
2328
+ push("not", "must not match the schema in not");
2329
+ if (node.if !== void 0) {
2330
+ const branch = this.ok(node.if, b, v) ? node.then : node.else;
2331
+ if (branch !== void 0)
2332
+ this.walk(branch, b, v, path, out);
2333
+ }
2334
+ if (typeof node.$ref === "string")
2335
+ this.walkRef(node.$ref, b, v, path, out);
2336
+ if (out.length === start && (node.unevaluatedProperties !== void 0 || node.unevaluatedItems !== void 0)) {
2337
+ this.walkUnevaluated(node, b, v, path, out);
2338
+ }
2339
+ if (out.length === start && typeof node.$dynamicRef === "string") {
2340
+ push("$dynamicRef", "does not match the dynamically referenced schema");
2341
+ }
2342
+ }
2343
+ walkRef(ref, base, v, path, out) {
2344
+ const target = this.c.r.resolve(ref, base);
2345
+ if (target.node === false && this.c.r.isUnresolved(ref, base)) {
2346
+ out.push({ path, keyword: "$ref", message: `unresolved reference ${ref}` });
2347
+ return;
2348
+ }
2349
+ if (!isSchemaObject(target.node) || typeof v !== "object" || v === null) {
2350
+ this.walk(target.node, target.base, v, path, out);
2351
+ return;
2352
+ }
2353
+ this.memo ??= /* @__PURE__ */ new Map();
2354
+ let values = this.memo.get(target.node);
2355
+ const known = values?.get(v);
2356
+ if (known !== void 0 && known.path === path) {
2357
+ out.push(...known.errors);
2358
+ return;
2359
+ }
2360
+ const errors = [];
2361
+ this.walk(target.node, target.base, v, path, errors);
2362
+ if (values === void 0) {
2363
+ values = /* @__PURE__ */ new Map();
2364
+ this.memo.set(target.node, values);
2365
+ }
2366
+ values.set(v, { path, errors });
2367
+ out.push(...errors);
2368
+ }
2369
+ walkString(node, v, push) {
2370
+ const n = codePoints(v);
2371
+ if (typeof node.minLength === "number" && n < node.minLength) {
2372
+ push("minLength", `expected at least ${node.minLength} characters`);
2373
+ }
2374
+ if (typeof node.maxLength === "number" && n > node.maxLength) {
2375
+ push("maxLength", `expected at most ${node.maxLength} characters`);
2376
+ }
2377
+ if (typeof node.pattern === "string" && !sharedRegex(node.pattern).test(v)) {
2378
+ push("pattern", `expected to match ${node.pattern}`);
2379
+ }
2380
+ const formats2 = this.c.formats;
2381
+ const format = formats2 !== void 0 && typeof node.format === "string" && Object.hasOwn(formats2, node.format) ? formats2[node.format] : void 0;
2382
+ if (format !== void 0 && !format(v))
2383
+ push("format", `expected format ${node.format}`);
2384
+ }
2385
+ walkBytes(node, v, push) {
2386
+ if (typeof node.minLength === "number" && v.length < node.minLength) {
2387
+ push("minLength", `expected at least ${node.minLength} bytes`);
2388
+ }
2389
+ if (typeof node.maxLength === "number" && v.length > node.maxLength) {
2390
+ push("maxLength", `expected at most ${node.maxLength} bytes`);
2391
+ }
2392
+ }
2393
+ // Numbers and bigints alike: bounds of either kind compare with values of either kind.
2394
+ walkNumber(node, v, push) {
2395
+ const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf } = node;
2396
+ if (isBound(minimum) && v < minimum)
2397
+ push("minimum", `expected >= ${minimum}`);
2398
+ if (isBound(maximum) && v > maximum)
2399
+ push("maximum", `expected <= ${maximum}`);
2400
+ if (isBound(exclusiveMinimum) && v <= exclusiveMinimum)
2401
+ push("exclusiveMinimum", `expected > ${exclusiveMinimum}`);
2402
+ if (isBound(exclusiveMaximum) && v >= exclusiveMaximum)
2403
+ push("exclusiveMaximum", `expected < ${exclusiveMaximum}`);
2404
+ if (isBound(multipleOf) && !isMultiple(v, multipleOf))
2405
+ push("multipleOf", `expected a multiple of ${multipleOf}`);
2406
+ }
2407
+ walkObject(node, b, v, path, out, push) {
2408
+ const properties = isSchemaObject(node.properties) ? node.properties : {};
2409
+ const required = Array.isArray(node.required) ? node.required : [];
2410
+ for (const k of required) {
2411
+ if (typeof k !== "string")
2412
+ continue;
2413
+ const accepted = v[k] === void 0 && Object.hasOwn(properties, k) && this.ok(properties[k], b, void 0);
2414
+ if (!Object.hasOwn(v, k) || v[k] === void 0 && !accepted)
2415
+ push("required", "missing", pointer(path, k));
2416
+ }
2417
+ for (const k of Object.keys(properties)) {
2418
+ if (Object.hasOwn(v, k) && v[k] !== void 0)
2419
+ this.walk(properties[k], b, v[k], pointer(path, k), out);
2420
+ }
2421
+ const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties) : [];
2422
+ for (const k of Object.keys(v)) {
2423
+ let matched = Object.hasOwn(properties, k);
2424
+ for (const [p, s] of patterns) {
2425
+ if (sharedRegex(p).test(k)) {
2426
+ matched = true;
2427
+ this.walk(s, b, v[k], pointer(path, k), out);
2428
+ }
2429
+ }
2430
+ if (!matched && node.additionalProperties !== void 0) {
2431
+ if (node.additionalProperties === false)
2432
+ push("additionalProperties", "unknown field", pointer(path, k));
2433
+ else
2434
+ this.walk(node.additionalProperties, b, v[k], pointer(path, k), out);
2435
+ }
2436
+ if (node.propertyNames !== void 0 && !this.ok(node.propertyNames, b, k)) {
2437
+ push("propertyNames", "invalid property name", pointer(path, k));
2438
+ }
2439
+ }
2440
+ const count = Object.keys(v).length;
2441
+ if (typeof node.minProperties === "number" && count < node.minProperties) {
2442
+ push("minProperties", `expected at least ${node.minProperties} properties`);
2443
+ }
2444
+ if (typeof node.maxProperties === "number" && count > node.maxProperties) {
2445
+ push("maxProperties", `expected at most ${node.maxProperties} properties`);
2446
+ }
2447
+ const dependencies = {
2448
+ ...this.c.draft === "7" || !isSchemaObject(node.dependentRequired) ? {} : node.dependentRequired,
2449
+ ...isSchemaObject(node.dependencies) ? node.dependencies : {}
2450
+ };
2451
+ for (const [k, d] of Object.entries(dependencies)) {
2452
+ if (!Object.hasOwn(v, k))
2453
+ continue;
2454
+ if (!Array.isArray(d))
2455
+ this.walk(d, b, v, path, out);
2456
+ else
2457
+ for (const r of d)
2458
+ if (!Object.hasOwn(v, r))
2459
+ push("dependentRequired", `required when ${k} is present`, pointer(path, r));
2460
+ }
2461
+ if (this.c.draft !== "7" && isSchemaObject(node.dependentSchemas)) {
2462
+ for (const [k, s] of Object.entries(node.dependentSchemas))
2463
+ if (Object.hasOwn(v, k))
2464
+ this.walk(s, b, v, path, out);
2465
+ }
2466
+ }
2467
+ walkArray(node, b, v, path, out, push) {
2468
+ let prefix = [];
2469
+ let rest;
2470
+ if (Array.isArray(node.items)) {
2471
+ prefix = node.items;
2472
+ rest = node.additionalItems;
2473
+ } else {
2474
+ if (this.c.draft !== "7" && Array.isArray(node.prefixItems))
2475
+ prefix = node.prefixItems;
2476
+ rest = node.items;
2477
+ }
2478
+ for (let i = 0; i < v.length; i++) {
2479
+ const s = i < prefix.length ? prefix[i] : rest;
2480
+ if (s !== void 0)
2481
+ this.walk(s, b, v[i], `${path}/${i}`, out);
2482
+ }
2483
+ if (typeof node.minItems === "number" && v.length < node.minItems) {
2484
+ push("minItems", `expected at least ${node.minItems} items`);
2485
+ }
2486
+ if (typeof node.maxItems === "number" && v.length > node.maxItems) {
2487
+ push("maxItems", `expected at most ${node.maxItems} items`);
2488
+ }
2489
+ if (node.uniqueItems === true && !uniqueCheck(v))
2490
+ push("uniqueItems", "expected unique items");
2491
+ if (node.contains !== void 0) {
2492
+ const draft7 = this.c.draft === "7";
2493
+ const min = draft7 || typeof node.minContains !== "number" ? 1 : node.minContains;
2494
+ const max = draft7 || typeof node.maxContains !== "number" ? Number.POSITIVE_INFINITY : node.maxContains;
2495
+ if (!containsCheck(this.c.check(node.contains, b), min, max)(v)) {
2496
+ push("contains", containsMessage(min, max));
2497
+ }
2498
+ }
2499
+ }
2500
+ walkUnion(branches, b, v, path, out, exactlyOne) {
2501
+ const matches = branches.filter((s) => this.ok(s, b, v)).length;
2502
+ if (matches === 1 || !exactlyOne && matches > 0)
2503
+ return;
2504
+ const keyword = exactlyOne ? "oneOf" : "anyOf";
2505
+ if (matches > 1) {
2506
+ out.push({ path, keyword, message: "matches more than one alternative" });
2507
+ return;
2508
+ }
2509
+ const tag = this.tagOf(branches, b);
2510
+ if (tag !== void 0 && isObject(v)) {
2511
+ const i = tag.values.indexOf(v[tag.key]);
2512
+ if (i < 0)
2513
+ out.push({
2514
+ path: pointer(path, tag.key),
2515
+ keyword,
2516
+ message: `expected one of ${listValues(tag.values)}`
2517
+ });
2518
+ else
2519
+ this.walk(branches[i], b, v, path, out);
2520
+ return;
2521
+ }
2522
+ let best;
2523
+ for (const s of branches) {
2524
+ const errors = [];
2525
+ this.walk(s, b, v, path, errors);
2526
+ if (errors.length === 0)
2527
+ continue;
2528
+ const declared = isObject(v) ? this.declaredKeys(s, b, v) : 0;
2529
+ const better = best === void 0 || declared > best.declared || declared === best.declared && errors[0].path.length > best.errors[0].path.length;
2530
+ if (better)
2531
+ best = { errors, declared };
2532
+ }
2533
+ out.push(...best?.errors ?? [{ path, keyword, message: "matches no alternative" }]);
2534
+ }
2535
+ /** How many of the keys of `v` the branch `s` (through a `$ref`) declares in `properties`. */
2536
+ declaredKeys(s, b, v) {
2537
+ const node = isSchemaObject(s) && typeof s.$ref === "string" ? this.c.r.resolve(s.$ref, this.c.r.baseFor(s, b)).node : s;
2538
+ const properties = isSchemaObject(node) && isSchemaObject(node.properties) ? node.properties : {};
2539
+ return Object.keys(v).filter((k) => Object.hasOwn(properties, k)).length;
2540
+ }
2541
+ tagOf(branches, b) {
2542
+ const resolved = branches.map((s) => isSchemaObject(s) && typeof s.$ref === "string" ? this.c.r.resolve(s.$ref, this.c.r.baseFor(s, b)).node : s);
2543
+ const first = resolved[0];
2544
+ if (!isSchemaObject(first) || !isSchemaObject(first.properties))
2545
+ return void 0;
2546
+ for (const key of Object.keys(first.properties)) {
2547
+ const values = resolved.map((s) => {
2548
+ const tag = isSchemaObject(s) && isSchemaObject(s.properties) ? s.properties[key] : void 0;
2549
+ return isSchemaObject(tag) ? tag.const : void 0;
2550
+ });
2551
+ const primitive = values.every((x) => x !== void 0 && (typeof x !== "object" || x === null));
2552
+ if (primitive && new Set(values).size === values.length)
2553
+ return { key, values };
2554
+ }
2555
+ return void 0;
2556
+ }
2557
+ walkUnevaluated(node, b, v, path, out) {
2558
+ const { unevaluatedProperties: unevaluatedProperties2, unevaluatedItems: unevaluatedItems2, $id: _id, ...rest } = node;
2559
+ const a = newAnnotations();
2560
+ this.c.annotating(rest, b)(v, a);
2561
+ if (isObject(v) && unevaluatedProperties2 !== void 0 && !a.allProps) {
2562
+ for (const k of Object.keys(v)) {
2563
+ if (a.props?.has(k))
2564
+ continue;
2565
+ if (unevaluatedProperties2 === false) {
2566
+ out.push({ path: pointer(path, k), keyword: "unevaluatedProperties", message: "unknown field" });
2567
+ } else
2568
+ this.walk(unevaluatedProperties2, b, v[k], pointer(path, k), out);
2569
+ }
2570
+ }
2571
+ if (Array.isArray(v) && unevaluatedItems2 !== void 0 && !a.allItems) {
2572
+ for (let i = a.items; i < v.length; i++) {
2573
+ if (a.indexes?.has(i))
2574
+ continue;
2575
+ if (unevaluatedItems2 === false) {
2576
+ out.push({ path: `${path}/${i}`, keyword: "unevaluatedItems", message: "unexpected item" });
2577
+ } else
2578
+ this.walk(unevaluatedItems2, b, v[i], `${path}/${i}`, out);
2579
+ }
2580
+ }
2581
+ }
2582
+ };
2583
+ var LISTED_VALUES = 20;
2584
+ function listValues(values) {
2585
+ if (values.length <= LISTED_VALUES)
2586
+ return JSON.stringify(values);
2587
+ const listed = JSON.stringify(values.slice(0, LISTED_VALUES));
2588
+ return `${listed.slice(0, -1)}, ... and ${values.length - LISTED_VALUES} more]`;
2589
+ }
2590
+ function containsMessage(min, max) {
2591
+ if (max === Number.POSITIVE_INFINITY)
2592
+ return `expected at least ${min} matching ${min === 1 ? "item" : "items"}`;
2593
+ if (min === 0)
2594
+ return `expected at most ${max} matching ${max === 1 ? "item" : "items"}`;
2595
+ return `expected between ${min} and ${max} matching items`;
2596
+ }
2597
+ function isBound(value) {
2598
+ return typeof value === "number" || typeof value === "bigint";
2599
+ }
2600
+ function pointer(path, key) {
2601
+ return `${path}/${String(key).replace(/~/g, "~0").replace(/\//g, "~1")}`;
2602
+ }
2603
+ function typeName(v) {
2604
+ if (v === null)
2605
+ return "null";
2606
+ if (Array.isArray(v))
2607
+ return "array";
2608
+ if (v instanceof Uint8Array)
2609
+ return "bytes";
2610
+ if (typeof v === "bigint")
2611
+ return "bigint";
2612
+ if (typeof v === "number" && Number.isInteger(v))
2613
+ return "integer";
2614
+ if (typeof v === "number" && !Number.isFinite(v))
2615
+ return String(v);
2616
+ return typeof v;
2617
+ }
2618
+
2619
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/validator.js
2620
+ function compile(schema, options = NO_OPTIONS) {
2621
+ const check = compileCheck(schema, options);
2622
+ return options.coerce === true ? new CoercingValidator(schema, options, check) : new Validator(schema, options, check);
2623
+ }
2624
+ var NO_OPTIONS = Object.freeze({});
2625
+ var Validator = class {
2626
+ /** Whether `value` is valid. A plain function: it may be passed around without its validator. */
2627
+ check;
2628
+ schema;
2629
+ options;
2630
+ explainer = void 0;
2631
+ constructor(schema, options, check) {
2632
+ this.check = check;
2633
+ this.schema = schema;
2634
+ this.options = options;
2635
+ }
2636
+ /**
2637
+ * Why `value` is invalid: one error per failing keyword, `[]` when it is valid. Built on the first failure and
2638
+ * kept, so a validator whose values always pass never pays for it.
2639
+ */
2640
+ errors(value) {
2641
+ if (this.check(value))
2642
+ return [];
2643
+ this.explainer ??= new Explainer(compiler(this.schema, this.options), this.schema);
2644
+ return this.explainer.errors(value);
2645
+ }
2646
+ /**
2647
+ * `value` itself when it is valid, else its errors: check() and errors() in one result, without coercion.
2648
+ *
2649
+ * Not TypeBox's `Value.Parse`, which also clones, fills defaults, converts and strips undeclared properties before
2650
+ * it checks. This only checks: the strict replacement where `Value.Parse` is used to validate (its other steps
2651
+ * change nothing for a valid value of a schema without defaults or extra properties). Use `parse()` with
2652
+ * `coerce: true` for conversion.
2653
+ */
2654
+ validate(value) {
2655
+ return this.check(value) ? { ok: true, value } : { ok: false, errors: this.errors(value) };
2656
+ }
2657
+ };
2658
+ var CoercingValidator = class extends Validator {
2659
+ coercer = void 0;
2660
+ /**
2661
+ * `value` coerced towards the schema: numeric strings to numbers, `"true"` to `true`, a single value to a one-item
2662
+ * array, an optional `null` dropped, the first union branch the value converts to (the README lists every rule).
2663
+ * Only the changed paths are copied; `value` comes back itself when nothing changes, and is never modified. Values
2664
+ * that cannot be coerced stay as they are. The rules are built on the first call.
2665
+ */
2666
+ coerce(value) {
2667
+ this.coercer ??= new Coercer(compiler(this.schema, this.options), this.schema);
2668
+ return this.coercer.coerce(value);
2669
+ }
2670
+ /** Coerces `value`, then checks it: the coerced value when it is valid, else its errors. */
2671
+ parse(value) {
2672
+ return this.validate(this.coerce(value));
2673
+ }
2674
+ };
2675
+ function compileCheck(schema, options) {
2676
+ return compiler(schema, options).root();
2677
+ }
2678
+ function compiler(schema, options) {
2679
+ const plain = new Compiler(schema, options, false);
2680
+ try {
2681
+ plain.root();
2682
+ return plain;
2683
+ } catch (error) {
2684
+ if (error !== RESTART)
2685
+ throw error;
2686
+ return new Compiler(schema, options, true);
2687
+ }
2688
+ }
2689
+
2690
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/date.js
2691
+ var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
2692
+ var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
2693
+ function IsLeapYear(year) {
2694
+ return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
2695
+ }
2696
+ function IsDate(value) {
2697
+ const matches = DATE.exec(value);
2698
+ if (!matches)
2699
+ return false;
2700
+ const year = +matches[1];
2701
+ const month = +matches[2];
2702
+ const day = +matches[3];
2703
+ return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && IsLeapYear(year) ? 29 : DAYS[month]);
2704
+ }
2705
+
2706
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/time.js
2707
+ var TIME = /^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:([Zz])|([+-])(\d\d):(\d\d))?$/;
2708
+ function IsTime(value, strictTimeZone = true) {
2709
+ const matches = TIME.exec(value);
2710
+ if (!matches)
2711
+ return false;
2712
+ if (strictTimeZone && !matches[4] && !matches[5])
2713
+ return false;
2714
+ const hr = +matches[1];
2715
+ const min = +matches[2];
2716
+ const sec = +matches[3];
2717
+ if (hr > 23 || min > 59 || sec > 60)
2718
+ return false;
2719
+ if (matches[5]) {
2720
+ const tzH2 = +matches[6];
2721
+ const tzM2 = +matches[7];
2722
+ if (tzH2 > 23 || tzM2 > 59)
2723
+ return false;
2724
+ }
2725
+ if (sec < 60)
2726
+ return true;
2727
+ const tzSign = matches[5] === "-" ? -1 : 1;
2728
+ const tzH = +(matches[6] || 0);
2729
+ const tzM = +(matches[7] || 0);
2730
+ const totalUtcMin = hr * 60 + min - tzSign * (tzH * 60 + tzM);
2731
+ return (totalUtcMin % 1440 + 1440) % 1440 === 1439;
2732
+ }
2733
+
2734
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/date_time.js
2735
+ function IsDateTime(value) {
2736
+ const dateTime = value.split(/T/i);
2737
+ return dateTime.length === 2 && IsDate(dateTime[0]) && IsTime(dateTime[1]);
2738
+ }
2739
+
2740
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/duration.js
2741
+ var Duration = /^P((\d+Y(\d+M(\d+D)?)?|\d+M(\d+D)?|\d+D)(T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S))?|T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S)|\d+W)$/;
2742
+ function IsDuration(value) {
2743
+ return Duration.test(value);
2744
+ }
2745
+
2746
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/email.js
2747
+ var Email = /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[^"\\]|\\[\x20-\x7e])*")@(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*|\[(?:IPv6:[a-f0-9:]+|(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?:\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3})\])$/i;
2748
+ function IsEmail(value) {
2749
+ return Email.test(value);
2750
+ }
2751
+
2752
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/idna/pattern/pattern.js
2753
+ var RE_RULE_HYPHEN_PLACEMENT = /^(?!-).*(?<!-)$/;
2754
+ var RE_RULE_NOT_RESERVED_ACE = /^(?!..--)/;
2755
+ var RE_ASCII_LDH = /^[a-zA-Z0-9-]*$/;
2756
+ var RE_NON_ASCII = /[^\p{ASCII}]/u;
2757
+ var RE_ASCII_DIGIT = /[0-9]/;
2758
+ var RE_ARABIC_INDIC_DIGIT = /[\u{0660}-\u{0669}]/u;
2759
+ var RE_EXT_ARABIC_INDIC_DIGIT = /[\u{06f0}-\u{06f9}]/u;
2760
+ var RE_COMMON_SEPARATOR = /[\u{002e}\u{002c}\u{003a}\u{002f}]/u;
2761
+ var RE_EUROPEAN_SEPARATOR = /[\u{002d}\u{002b}]/u;
2762
+ var RE_MARK_NONSPACING = /\p{Mn}/u;
2763
+ var RE_MARK_SPACING_COMBINING = /\p{Mc}/u;
2764
+ var RE_COMBINING_MARK = /[\p{Mn}\p{Mc}\p{Me}]/u;
2765
+ var RE_LETTER = /\p{L}/u;
2766
+ var RE_NUMBER_DECIMAL = /\p{Nd}/u;
2767
+ var RE_SCRIPT_GREEK = /\p{Script=Greek}/u;
2768
+ var RE_SCRIPT_HEBREW = /\p{Script=Hebrew}/u;
2769
+ var RE_SCRIPT_JAPANESE = /[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u;
2770
+ var RE_SCRIPT_ARABIC_LETTER = /[\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Mandaic}]/u;
2771
+ var RE_VIRAMA = /[\u{094d}\u{09cd}\u{0a4d}\u{0acd}\u{0b4d}\u{0bcd}\u{0c4d}\u{0ccd}\u{0d3b}\u{0d3c}\u{0d4d}\u{0dca}\u{1b44}\u{1baa}\u{1bab}\u{a9c0}\u{11046}\u{1107f}\u{110b9}\u{11133}\u{11134}\u{111c0}\u{11235}\u{1134d}\u{11442}\u{114c2}\u{115bf}\u{1163f}\u{116b6}\u{11c3f}\u{11d44}\u{11d45}]/u;
2772
+ var RE_RFC5892_DISALLOWED = /[\u{0640}\u{07fa}\u{302e}\u{302f}\u{3031}\u{3032}\u{3033}\u{3034}\u{3035}\u{303b}]/u;
2773
+ var RE_CONTEXTO_EXCEPTIONS = /[\u{00b7}\u{0375}\u{05f3}\u{05f4}\u{200c}\u{200d}\u{30fb}]/u;
2774
+ var RE_PVALID_EXCEPTIONS = /[\u{00df}\u{03c2}\u{06fd}\u{06fe}\u{0f0b}\u{3007}]/u;
2775
+ var RE_EUROPEAN_NUMBER = new RegExp([RE_ASCII_DIGIT, RE_EXT_ARABIC_INDIC_DIGIT].map((regexp) => regexp.source).join("|"), "u");
2776
+ var RE_PERMITTED_CATEGORY = new RegExp([
2777
+ RE_LETTER,
2778
+ RE_EUROPEAN_SEPARATOR,
2779
+ RE_COMMON_SEPARATOR,
2780
+ RE_NUMBER_DECIMAL,
2781
+ RE_MARK_NONSPACING,
2782
+ RE_MARK_SPACING_COMBINING,
2783
+ RE_CONTEXTO_EXCEPTIONS,
2784
+ RE_PVALID_EXCEPTIONS
2785
+ ].map((regexp) => regexp.source).join("|"), "u");
2786
+
2787
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/idna/label/ascii.js
2788
+ function IsAsciiLabel(value) {
2789
+ return RE_RULE_HYPHEN_PLACEMENT.test(value) && RE_RULE_NOT_RESERVED_ACE.test(value) && RE_ASCII_LDH.test(value);
2790
+ }
2791
+
2792
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/idna/format/puny.js
2793
+ var PUNYCODE_BASE = 36;
2794
+ var PUNYCODE_TMIN = 1;
2795
+ var PUNYCODE_TMAX = 26;
2796
+ var PUNYCODE_SKEW = 38;
2797
+ var PUNYCODE_DAMP = 700;
2798
+ var PUNYCODE_INITIAL_BIAS = 72;
2799
+ var PUNYCODE_INITIAL_N = 128;
2800
+ function ThrowDontCare() {
2801
+ throw null;
2802
+ }
2803
+ function IsAcePrefixed(value) {
2804
+ return value.toLowerCase().startsWith("xn--");
2805
+ }
2806
+ function Adapt(delta, numPoints, firstTime) {
2807
+ delta = firstTime ? Math.floor(delta / PUNYCODE_DAMP) : delta >> 1;
2808
+ delta += Math.floor(delta / numPoints);
2809
+ let k = 0;
2810
+ while (delta > (PUNYCODE_BASE - PUNYCODE_TMIN) * PUNYCODE_TMAX >> 1) {
2811
+ delta = Math.floor(delta / (PUNYCODE_BASE - PUNYCODE_TMIN));
2812
+ k += PUNYCODE_BASE;
2813
+ }
2814
+ return k + Math.floor((PUNYCODE_BASE - PUNYCODE_TMIN + 1) * delta / (delta + PUNYCODE_SKEW));
2815
+ }
2816
+ function Decode(value) {
2817
+ const output = [];
2818
+ let n = PUNYCODE_INITIAL_N;
2819
+ let i = 0;
2820
+ let bias = PUNYCODE_INITIAL_BIAS;
2821
+ const delimIdx = value.lastIndexOf("-");
2822
+ if (delimIdx > 0) {
2823
+ for (let j = 0; j < delimIdx; j++) {
2824
+ const cp = value.charCodeAt(j);
2825
+ if (cp >= 128)
2826
+ ThrowDontCare();
2827
+ output.push(cp);
2828
+ }
2829
+ }
2830
+ let inIdx = delimIdx < 0 ? 0 : delimIdx + 1;
2831
+ while (inIdx < value.length) {
2832
+ const oldi = i;
2833
+ let w = 1;
2834
+ let k = PUNYCODE_BASE;
2835
+ while (true) {
2836
+ if (inIdx >= value.length)
2837
+ ThrowDontCare();
2838
+ const ch = value.charCodeAt(inIdx++);
2839
+ let digit;
2840
+ if (ch >= 97 && ch <= 122)
2841
+ digit = ch - 97;
2842
+ else if (ch >= 48 && ch <= 57)
2843
+ digit = ch - 48 + 26;
2844
+ else
2845
+ ThrowDontCare();
2846
+ i += digit * w;
2847
+ const t = k <= bias ? PUNYCODE_TMIN : k >= bias + PUNYCODE_TMAX ? PUNYCODE_TMAX : k - bias;
2848
+ if (digit < t)
2849
+ break;
2850
+ w *= PUNYCODE_BASE - t;
2851
+ k += PUNYCODE_BASE;
2852
+ }
2853
+ const outLen = output.length + 1;
2854
+ bias = Adapt(i - oldi, outLen, oldi === 0);
2855
+ n += Math.floor(i / outLen);
2856
+ i %= outLen;
2857
+ output.splice(i, 0, n);
2858
+ i++;
2859
+ }
2860
+ return String.fromCodePoint(...output);
2861
+ }
2862
+ function DigitToChar(digit) {
2863
+ return digit < 26 ? String.fromCharCode(digit + 97) : String.fromCharCode(digit - 26 + 48);
2864
+ }
2865
+ var RE_REPLACE_NON_ASCII = new RegExp(RE_NON_ASCII.source, "gu");
2866
+ function Encode(input) {
2867
+ const basic = input.replace(RE_REPLACE_NON_ASCII, "");
2868
+ const basicLength = basic.length;
2869
+ const result = basicLength > 0 ? [basic, "-"] : [];
2870
+ const codePoints2 = Array.from(input, (char) => char.codePointAt(0));
2871
+ let n = PUNYCODE_INITIAL_N;
2872
+ let delta = 0;
2873
+ let bias = PUNYCODE_INITIAL_BIAS;
2874
+ let handledCPCount = basicLength;
2875
+ while (handledCPCount < codePoints2.length) {
2876
+ let m = Infinity;
2877
+ for (const cp of codePoints2) {
2878
+ if (cp >= n && cp < m)
2879
+ m = cp;
2880
+ }
2881
+ delta += (m - n) * (handledCPCount + 1);
2882
+ n = m;
2883
+ for (const cp of codePoints2) {
2884
+ if (cp < n)
2885
+ delta++;
2886
+ if (cp === n) {
2887
+ let q = delta;
2888
+ for (let k = PUNYCODE_BASE; ; k += PUNYCODE_BASE) {
2889
+ const t = k <= bias ? PUNYCODE_TMIN : k >= bias + PUNYCODE_TMAX ? PUNYCODE_TMAX : k - bias;
2890
+ if (q < t)
2891
+ break;
2892
+ const digit = t + (q - t) % (PUNYCODE_BASE - t);
2893
+ result.push(DigitToChar(digit));
2894
+ q = Math.floor((q - t) / (PUNYCODE_BASE - t));
2895
+ }
2896
+ result.push(DigitToChar(q));
2897
+ bias = Adapt(delta, handledCPCount + 1, handledCPCount === basicLength);
2898
+ delta = 0;
2899
+ handledCPCount++;
2900
+ }
2901
+ }
2902
+ delta++;
2903
+ n++;
2904
+ }
2905
+ return result.join("");
2906
+ }
2907
+
2908
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/idna/format/bidi.js
2909
+ var RE_RTL_ALLOWED = /^(?:R|AL|AN|EN|ES|CS|ET|ON|BN|NSM)$/;
2910
+ var RE_LTR_ALLOWED = /^(?:L|EN|ES|CS|ET|ON|BN|NSM)$/;
2911
+ var RE_RTL_CLASSES = /^(?:R|AL|AN)$/;
2912
+ function HasBidiChars(value) {
2913
+ if (IsAcePrefixed(value)) {
2914
+ try {
2915
+ return HasRightToLeftCharacters(Decode(value.slice(4).toLowerCase()));
2916
+ } catch {
2917
+ return false;
2918
+ }
2919
+ }
2920
+ return HasRightToLeftCharacters(value);
2921
+ }
2922
+ function GetBidiClass(codePoint) {
2923
+ const char = String.fromCodePoint(codePoint);
2924
+ return RE_EUROPEAN_NUMBER.test(char) ? "EN" : RE_ARABIC_INDIC_DIGIT.test(char) ? "AN" : (
2925
+ // Pattern.RE_EUROPEAN_SEPARATOR.test(char) ? 'ES' : // (no-spec-coverage)
2926
+ // Pattern.RE_COMMON_SEPARATOR.test(char) ? 'CS' : // (no-spec-coverage)
2927
+ RE_MARK_NONSPACING.test(char) ? "NSM" : RE_SCRIPT_HEBREW.test(char) ? "R" : RE_SCRIPT_ARABIC_LETTER.test(char) ? "AL" : RE_LETTER.test(char) ? "L" : "ON"
2928
+ );
2929
+ }
2930
+ function HasRightToLeftCharacters(value) {
2931
+ for (const ch of value)
2932
+ if (RE_RTL_CLASSES.test(GetBidiClass(ch.codePointAt(0))))
2933
+ return true;
2934
+ return false;
2935
+ }
2936
+ function SatisfiesBidiRule(value) {
2937
+ let isRtl = false;
2938
+ let allowed = RE_LTR_ALLOWED;
2939
+ let sawEN = false;
2940
+ let sawAN = false;
2941
+ let isFirst = true;
2942
+ for (const ch of value) {
2943
+ const bidiClass = GetBidiClass(ch.codePointAt(0));
2944
+ if (isFirst) {
2945
+ if (bidiClass !== "L" && bidiClass !== "R" && bidiClass !== "AL")
2946
+ return false;
2947
+ isRtl = bidiClass === "R" || bidiClass === "AL";
2948
+ allowed = isRtl ? RE_RTL_ALLOWED : RE_LTR_ALLOWED;
2949
+ isFirst = false;
2950
+ }
2951
+ if (!allowed.test(bidiClass))
2952
+ return false;
2953
+ if (bidiClass === "EN")
2954
+ sawEN = true;
2955
+ else if (bidiClass === "AN")
2956
+ sawAN = true;
2957
+ }
2958
+ if (isRtl && sawEN && sawAN)
2959
+ return false;
2960
+ return true;
2961
+ }
2962
+
2963
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/idna/label/unicode.js
2964
+ function ExceedsMaxALabelLength(value) {
2965
+ return RE_NON_ASCII.test(value) && Encode(value).length + 4 > 63;
2966
+ }
2967
+ function HasInvalidHyphens(chars) {
2968
+ if (chars[0] === "-" || chars[chars.length - 1] === "-")
2969
+ return true;
2970
+ return chars.slice(2).join("").startsWith("--");
2971
+ }
2972
+ function IsUnicodeLabel(value) {
2973
+ if (ExceedsMaxALabelLength(value))
2974
+ return false;
2975
+ if (HasRightToLeftCharacters(value) && !SatisfiesBidiRule(value))
2976
+ return false;
2977
+ const chars = [...value];
2978
+ const codePoints2 = chars.map((c) => c.codePointAt(0));
2979
+ const length = codePoints2.length;
2980
+ if (HasInvalidHyphens(chars))
2981
+ return false;
2982
+ if (RE_COMBINING_MARK.test(chars[0]))
2983
+ return false;
2984
+ let hasJapanese = false;
2985
+ for (let i = 0; i < length; i++) {
2986
+ const codePoint = codePoints2[i];
2987
+ const char = chars[i];
2988
+ if (RE_RFC5892_DISALLOWED.test(char))
2989
+ return false;
2990
+ if (!RE_PERMITTED_CATEGORY.test(char))
2991
+ return false;
2992
+ if (RE_SCRIPT_JAPANESE.test(char))
2993
+ hasJapanese = true;
2994
+ const prev = codePoints2[i - 1], next = codePoints2[i + 1];
2995
+ switch (codePoint) {
2996
+ case 183:
2997
+ if (prev !== 108 || next !== 108)
2998
+ return false;
2999
+ break;
3000
+ // MIDDLE DOT (Catalan)
3001
+ case 885:
3002
+ if (!next || !RE_SCRIPT_GREEK.test(chars[i + 1]))
3003
+ return false;
3004
+ break;
3005
+ // Greek KERAIA
3006
+ case 1523:
3007
+ case 1524:
3008
+ if (!prev || !RE_SCRIPT_HEBREW.test(chars[i - 1]))
3009
+ return false;
3010
+ break;
3011
+ // Hebrew GERESH
3012
+ case 8204:
3013
+ if (!prev || prev < 128 && !RE_VIRAMA.test(chars[i - 1]))
3014
+ return false;
3015
+ break;
3016
+ case 8205:
3017
+ if (!prev || !RE_VIRAMA.test(chars[i - 1]))
3018
+ return false;
3019
+ break;
3020
+ case 12539:
3021
+ break;
3022
+ }
3023
+ }
3024
+ if (value.includes("\u30FB") && !hasJapanese)
3025
+ return false;
3026
+ return true;
3027
+ }
3028
+
3029
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/idna/label/puny.js
3030
+ function IsPunyLabel(value) {
3031
+ if (!IsAcePrefixed(value))
3032
+ return false;
3033
+ try {
3034
+ const body = value.slice(4).toLowerCase();
3035
+ if (body.lastIndexOf("-") === 0)
3036
+ return false;
3037
+ const decoded = Decode(body);
3038
+ if (!RE_NON_ASCII.test(decoded))
3039
+ return false;
3040
+ return IsUnicodeLabel(decoded);
3041
+ } catch {
3042
+ return false;
3043
+ }
3044
+ }
3045
+
3046
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/idna/hostname.js
3047
+ function IsValidLabelLength(value) {
3048
+ return value.length > 0 && value.length <= 63;
3049
+ }
3050
+ function IsLabel(value) {
3051
+ return IsValidLabelLength(value) && (IsPunyLabel(value) || IsAsciiLabel(value));
3052
+ }
3053
+ function IsHostname(value) {
3054
+ if (value.length === 0 || value.length > 253)
3055
+ return false;
3056
+ if (value.charCodeAt(value.length - 1) === 46)
3057
+ return false;
3058
+ return value.split(".").every((label) => IsLabel(label));
3059
+ }
3060
+
3061
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/idna/idn-hostname.js
3062
+ function IsValidLabelLength2(value) {
3063
+ return value.length > 0 && value.length <= 63;
3064
+ }
3065
+ function IsLabel2(value) {
3066
+ return IsValidLabelLength2(value) && (IsPunyLabel(value) || IsUnicodeLabel(value));
3067
+ }
3068
+ function NormalizeHostname(value) {
3069
+ return value.replace(/[\uff01-\uff5e]/g, (char) => String.fromCharCode(char.charCodeAt(0) - 65248)).normalize("NFC").replace(/[\u00ad\u034f\u180b-\u180d\u200b\ufe00-\ufe0f\u{e0100}-\u{e01ef}]/gu, "").replace(/[\u002E\u3002\uFF0E\uFF61]/g, ".");
3070
+ }
3071
+ function IsIdnHostname(value) {
3072
+ if (value.length === 0 || value.includes(" "))
3073
+ return false;
3074
+ const normalized = NormalizeHostname(value);
3075
+ if (normalized.length > 253)
3076
+ return false;
3077
+ const labels = normalized.split(".");
3078
+ const hasBidiChars = labels.some((label) => HasBidiChars(label));
3079
+ return labels.every((label) => IsLabel2(label) && (!hasBidiChars || SatisfiesBidiRule(label)));
3080
+ }
3081
+
3082
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/hostname.js
3083
+ function IsHostname2(value) {
3084
+ return IsHostname(value);
3085
+ }
3086
+
3087
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/idn_email.js
3088
+ var IdnEmail = /^(?:[A-Za-z0-9!#$%&'*+/=?^_`{|}~\u{0080}-\u{10FFFF}-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~\u{0080}-\u{10FFFF}-]+)*|"(?:[^"\\]|\\.)*")@[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?<!-)(?:\.[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?<!-))*$/iu;
3089
+ function IsIdnEmail(value) {
3090
+ return IdnEmail.test(value.normalize("NFC"));
3091
+ }
3092
+
3093
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/idn_hostname.js
3094
+ function IsIdnHostname2(value) {
3095
+ return IsIdnHostname(value);
3096
+ }
3097
+
3098
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/ipv4.js
3099
+ var IPv4 = /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;
3100
+ function IsIPv4(value) {
3101
+ return IPv4.test(value);
3102
+ }
3103
+
3104
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/ipv6.js
3105
+ var IPv6 = /^(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:)?[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)$/i;
3106
+ function IsIPv6(value) {
3107
+ return IPv6.test(value);
3108
+ }
3109
+
3110
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/iri.js
3111
+ var IpvFutureMatchMaxLength = 2048;
3112
+ var IpvFutureMatch = /\[[vV][0-9a-fA-F]+\.[^\]]+\]/;
3113
+ var InvalidIriChars = /[\x00-\x20<>^`{|}\\]/;
3114
+ var InvalidPercentEncoding = /%(?![0-9a-fA-F]{2})/;
3115
+ function NarrowIpvFuture(value) {
3116
+ return value.length < IpvFutureMatchMaxLength ? value.replace(IpvFutureMatch, "[::1]") : value;
3117
+ }
3118
+ function IsIri(value) {
3119
+ if (InvalidIriChars.test(value))
3120
+ return false;
3121
+ if (InvalidPercentEncoding.test(value))
3122
+ return false;
3123
+ return URL.canParse(NarrowIpvFuture(value));
3124
+ }
3125
+
3126
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/iri_reference.js
3127
+ var InvalidIriChars2 = /[\x00-\x20\x7F\\]|%(?![0-9a-fA-F]{2})/;
3128
+ var MalformedScheme = /^[a-zA-Z][a-zA-Z0-9+\-.]*\/\//;
3129
+ function IsIriReference(value) {
3130
+ return !InvalidIriChars2.test(value) && !MalformedScheme.test(value) && URL.canParse(value, "http://example.com");
3131
+ }
3132
+
3133
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/json_pointer.js
3134
+ var JsonPointer = /^(?:\/(?:[^~/]|~0|~1)*)*$/;
3135
+ function IsJsonPointer(value) {
3136
+ return JsonPointer.test(value);
3137
+ }
3138
+
3139
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/json_pointer_uri_fragment.js
3140
+ var JsonPointerUriFragment = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;
3141
+ function IsJsonPointerUriFragment(value) {
3142
+ return JsonPointerUriFragment.test(value);
3143
+ }
3144
+
3145
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/regex.js
3146
+ function IsRegex(value) {
3147
+ try {
3148
+ new RegExp(value, "u");
3149
+ return true;
3150
+ } catch {
3151
+ return false;
3152
+ }
3153
+ }
3154
+
3155
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/relative_json_pointer.js
3156
+ var RelativeJsonPointer = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;
3157
+ function IsRelativeJsonPointer(value) {
3158
+ return RelativeJsonPointer.test(value);
3159
+ }
3160
+
3161
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/uri.js
3162
+ var Uri = /^[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
3163
+ function IsUri(value) {
3164
+ return Uri.test(value);
3165
+ }
3166
+
3167
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/uri_reference.js
3168
+ var UriReference = /^(?:[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
3169
+ function IsUriReference(value) {
3170
+ return UriReference.test(value);
3171
+ }
3172
+
3173
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/uri_template.js
3174
+ var UriTemplate = /^(?:(?:[^\x00-\x20"<>%\\^`{|}\x7f]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?)*\})*$/i;
3175
+ function IsUriTemplate(value) {
3176
+ return UriTemplate.test(value);
3177
+ }
3178
+
3179
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/url.js
3180
+ function IsUrl(value) {
3181
+ return URL.canParse(value);
3182
+ }
3183
+
3184
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/typebox/uuid.js
3185
+ var Uuid = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
3186
+ function IsUuid(value) {
3187
+ return Uuid.test(value);
3188
+ }
3189
+
3190
+ // packages/harness-client/node_modules/@earendil-works/pi-schema/dist/formats/index.js
3191
+ var formats = Object.freeze({
3192
+ date: IsDate,
3193
+ "date-time": IsDateTime,
3194
+ duration: IsDuration,
3195
+ email: IsEmail,
3196
+ hostname: IsHostname2,
3197
+ "idn-email": IsIdnEmail,
3198
+ "idn-hostname": IsIdnHostname2,
3199
+ ipv4: IsIPv4,
3200
+ ipv6: IsIPv6,
3201
+ iri: IsIri,
3202
+ "iri-reference": IsIriReference,
3203
+ "json-pointer": IsJsonPointer,
3204
+ "json-pointer-uri-fragment": IsJsonPointerUriFragment,
3205
+ regex: IsRegex,
3206
+ "relative-json-pointer": IsRelativeJsonPointer,
3207
+ time: IsTime,
3208
+ uri: IsUri,
3209
+ "uri-reference": IsUriReference,
3210
+ "uri-template": IsUriTemplate,
3211
+ url: IsUrl,
3212
+ uuid: IsUuid
3213
+ });
3214
+
3215
+ // packages/harness-client/node_modules/@earendil-works/pi-ai/dist/utils/validation.js
3216
+ var validatorCache = /* @__PURE__ */ new WeakMap();
3217
+ function getValidator(schema) {
3218
+ const cached = validatorCache.get(schema);
3219
+ if (cached) {
3220
+ return cached;
3221
+ }
3222
+ const validator = compile(schema, { formats, coerce: true, unresolvedRefs: "reject" });
3223
+ validatorCache.set(schema, validator);
3224
+ return validator;
3225
+ }
3226
+ function formatValidationPath(pointer2) {
3227
+ if (pointer2 === "")
3228
+ return "root";
3229
+ return pointer2.slice(1).split("/").map((segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~")).join(".");
3230
+ }
3231
+ function validateToolArguments(tool, toolCall) {
3232
+ if (toolCall.argumentsError) {
3233
+ throw new Error(`Invalid arguments for tool "${toolCall.name}": ${toolCall.argumentsError}`);
3234
+ }
3235
+ const result = getValidator(tool.parameters).parse(structuredClone(toolCall.arguments));
3236
+ if (result.ok) {
3237
+ return result.value;
3238
+ }
3239
+ const errors = result.errors.map((error) => ` - ${formatValidationPath(error.path)}: ${error.message}`).join("\n");
3240
+ const errorMessage = `Validation failed for tool "${toolCall.name}":
3241
+ ${errors}
3242
+
3243
+ Received arguments:
3244
+ ${JSON.stringify(toolCall.arguments, null, 2)}`;
3245
+ throw new Error(errorMessage);
3246
+ }
3247
+
3248
+ // packages/harness-client/node_modules/@earendil-works/pi-agent-core/dist/stream-fn.js
3249
+ var defaultStreamFn;
3250
+ function getDefaultStreamFn() {
3251
+ if (!defaultStreamFn) {
3252
+ throw new Error("No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().");
3253
+ }
3254
+ return defaultStreamFn;
3255
+ }
3256
+
3257
+ // packages/harness-client/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js
3258
+ var DEFAULT_AGENT_IDENTITY = { attribution: PI_ATTRIBUTION };
3259
+ async function runAgentLoop(prompts, context, config, emit, signal, streamFn) {
3260
+ const initialMessages = declareToolChanges(context, prompts);
3261
+ const newMessages = [...initialMessages];
3262
+ const currentContext = {
3263
+ ...context,
3264
+ messages: [...context.messages, ...initialMessages]
3265
+ };
3266
+ await emit({ type: "agent_start" });
3267
+ await emit({ type: "turn_start" });
3268
+ for (const message of initialMessages) {
3269
+ await emit({ type: "message_start", message });
3270
+ await emit({ type: "message_end", message });
3271
+ }
3272
+ await runLoop(currentContext, newMessages, config, signal, emit, streamFn ?? getDefaultStreamFn());
3273
+ return newMessages;
3274
+ }
3275
+ async function runAgentLoopContinue(context, config, emit, signal, streamFn) {
3276
+ if (context.messages.length === 0) {
3277
+ throw new Error("Cannot continue: no messages in context");
3278
+ }
3279
+ if (context.messages[context.messages.length - 1].role === "assistant") {
3280
+ throw new Error("Cannot continue from message role: assistant");
3281
+ }
3282
+ const newMessages = [];
3283
+ const currentContext = { ...context };
3284
+ await emit({ type: "agent_start" });
3285
+ await emit({ type: "turn_start" });
3286
+ await runLoop(currentContext, newMessages, config, signal, emit, streamFn ?? getDefaultStreamFn());
3287
+ return newMessages;
3288
+ }
3289
+ async function runLoop(initialContext, newMessages, initialConfig, signal, emit, streamFunction) {
3290
+ let currentContext = initialContext;
3291
+ let config = initialConfig;
3292
+ let lastCompletedTurn;
3293
+ let explicitContinuation = false;
3294
+ let pendingMessages = await config.getSteeringMessages?.() || [];
3295
+ while (true) {
3296
+ let hasMoreToolCalls = true;
3297
+ while (hasMoreToolCalls || pendingMessages.length > 0) {
3298
+ let preparedMessages = [];
3299
+ if (lastCompletedTurn) {
3300
+ const nextTurnSnapshot = await config.prepareNextTurn?.(lastCompletedTurn);
3301
+ if (nextTurnSnapshot) {
3302
+ currentContext = nextTurnSnapshot.context ?? currentContext;
3303
+ preparedMessages = nextTurnSnapshot.messages ?? [];
3304
+ config = {
3305
+ ...config,
3306
+ model: nextTurnSnapshot.model ?? config.model,
3307
+ reasoning: nextTurnSnapshot.thinkingLevel === void 0 ? config.reasoning : nextTurnSnapshot.thinkingLevel === "off" ? void 0 : nextTurnSnapshot.thinkingLevel
3308
+ };
3309
+ }
3310
+ if (pendingMessages.length === 0) {
3311
+ pendingMessages = await config.getSteeringMessages?.() || [];
3312
+ }
3313
+ await emit({ type: "turn_start" });
3314
+ }
3315
+ for (const message2 of declareToolChanges(currentContext, [...preparedMessages, ...pendingMessages])) {
3316
+ await emit({ type: "message_start", message: message2 });
3317
+ await emit({ type: "message_end", message: message2 });
3318
+ currentContext.messages.push(message2);
3319
+ newMessages.push(message2);
3320
+ }
3321
+ pendingMessages = [];
3322
+ const requestUpdate = await config.prepareRequest?.({
3323
+ context: currentContext,
3324
+ model: config.model,
3325
+ thinkingLevel: config.reasoning ?? "off"
3326
+ }, signal);
3327
+ if (requestUpdate) {
3328
+ currentContext = requestUpdate.context ?? currentContext;
3329
+ config = {
3330
+ ...config,
3331
+ model: requestUpdate.model ?? config.model,
3332
+ reasoning: requestUpdate.thinkingLevel === void 0 ? config.reasoning : requestUpdate.thinkingLevel === "off" ? void 0 : requestUpdate.thinkingLevel
3333
+ };
3334
+ }
3335
+ const message = await streamAssistantResponse(currentContext, config, signal, emit, streamFunction);
3336
+ newMessages.push(message);
3337
+ if (message.stopReason === "error" || message.stopReason === "aborted") {
3338
+ lastCompletedTurn = {
3339
+ message,
3340
+ toolResults: [],
3341
+ context: currentContext,
3342
+ newMessages
3343
+ };
3344
+ await config.finishTurn?.(lastCompletedTurn, signal);
3345
+ await emit({ type: "turn_end", message, toolResults: [] });
3346
+ await emit({ type: "agent_end", messages: newMessages });
3347
+ return;
3348
+ }
3349
+ const toolCalls = message.content.filter((c) => c.type === "toolCall");
3350
+ const toolResults = [];
3351
+ hasMoreToolCalls = false;
3352
+ if (toolCalls.length > 0) {
3353
+ const executedToolBatch = message.stopReason === "length" ? await failToolCallsFromTruncatedMessage(toolCalls, emit) : await executeToolCalls(currentContext, message, config, signal, emit);
3354
+ toolResults.push(...executedToolBatch.messages);
3355
+ hasMoreToolCalls = !executedToolBatch.terminate;
3356
+ for (const result of toolResults) {
3357
+ currentContext.messages.push(result);
3358
+ newMessages.push(result);
3359
+ }
3360
+ }
3361
+ lastCompletedTurn = {
3362
+ message,
3363
+ toolResults,
3364
+ context: currentContext,
3365
+ newMessages
3366
+ };
3367
+ const decision = await config.finishTurn?.(lastCompletedTurn, signal);
3368
+ await emit({ type: "turn_end", message, toolResults });
3369
+ if (decision?.action === "end") {
3370
+ await emit({ type: "agent_end", messages: newMessages });
3371
+ return;
3372
+ }
3373
+ explicitContinuation = decision?.action === "continue";
3374
+ pendingMessages = await config.getSteeringMessages?.() || [];
3375
+ if (hasMoreToolCalls || pendingMessages.length > 0) {
3376
+ explicitContinuation = false;
3377
+ }
3378
+ }
3379
+ const followUpMessages = await config.getFollowUpMessages?.() || [];
3380
+ if (followUpMessages.length > 0) {
3381
+ explicitContinuation = false;
3382
+ pendingMessages = followUpMessages;
3383
+ continue;
3384
+ }
3385
+ if (explicitContinuation) {
3386
+ explicitContinuation = false;
3387
+ continue;
3388
+ }
3389
+ break;
3390
+ }
3391
+ await emit({ type: "agent_end", messages: newMessages });
3392
+ }
3393
+ function declareToolChanges(context, pendingMessages) {
3394
+ let systemIndex = -1;
3395
+ for (let i = pendingMessages.length - 1; i >= 0; i--) {
3396
+ if (pendingMessages[i].role === "system") {
3397
+ systemIndex = i;
3398
+ break;
3399
+ }
3400
+ }
3401
+ const pending = pendingMessages[systemIndex];
3402
+ const baseline = pending ? pendingMessages.map((message, index2) => index2 === systemIndex ? withToolChanges(pending, NO_CHANGES) : message) : pendingMessages;
3403
+ const changes = getToolStateChanges(getCurrentTools([...context.messages, ...baseline]), (context.tools ?? []).map(toToolDeclaration));
3404
+ const unchanged = changes.toolsAdded.length === 0 && changes.toolsRemoved.length === 0;
3405
+ if (pending) {
3406
+ if (unchanged && !pending.toolsAdded?.length && !pending.toolsRemoved?.length)
3407
+ return pendingMessages;
3408
+ return baseline.map((message, index2) => index2 === systemIndex ? withToolChanges(pending, changes) : message);
3409
+ }
3410
+ if (unchanged)
3411
+ return pendingMessages;
3412
+ const update = withToolChanges({ role: "system", content: "", timestamp: Date.now() }, changes);
3413
+ const insertIndex = pendingMessages.findIndex((message) => message.role !== "system");
3414
+ const index = insertIndex === -1 ? pendingMessages.length : insertIndex;
3415
+ return [...pendingMessages.slice(0, index), update, ...pendingMessages.slice(index)];
3416
+ }
3417
+ var NO_CHANGES = { toolsAdded: [], toolsRemoved: [] };
3418
+ function withToolChanges(message, { toolsAdded, toolsRemoved }) {
3419
+ const { toolsAdded: _added, toolsRemoved: _removed, ...rest } = message;
3420
+ return {
3421
+ ...rest,
3422
+ ...toolsAdded.length > 0 ? { toolsAdded } : {},
3423
+ ...toolsRemoved.length > 0 ? { toolsRemoved } : {}
3424
+ };
3425
+ }
3426
+ async function streamAssistantResponse(context, config, signal, emit, streamFunction) {
3427
+ let messages = context.messages;
3428
+ if (config.transformContext) {
3429
+ messages = await config.transformContext(messages, signal);
3430
+ }
3431
+ const llmMessages = await config.convertToLlm(messages);
3432
+ const llmContext = normalizeContext({ messages: llmMessages });
3433
+ const resolvedApiKey = (config.getApiKey ? await config.getApiKey(config.model.provider) : void 0) || config.apiKey;
3434
+ const response = await streamFunction(config.model, llmContext, {
3435
+ ...config,
3436
+ apiKey: resolvedApiKey,
3437
+ identity: mergeClientIdentity(DEFAULT_AGENT_IDENTITY, config.identity),
3438
+ signal
3439
+ });
3440
+ const result = async () => Object.assign(await response.result(), { thinkingLevel: config.reasoning ?? "off" });
3441
+ let partialMessage = null;
3442
+ let addedPartial = false;
3443
+ for await (const event of response) {
3444
+ switch (event.type) {
3445
+ case "start":
3446
+ partialMessage = event.partial;
3447
+ context.messages.push(partialMessage);
3448
+ addedPartial = true;
3449
+ await emit({ type: "message_start", message: { ...partialMessage } });
3450
+ break;
3451
+ case "text_start":
3452
+ case "text_delta":
3453
+ case "text_end":
3454
+ case "thinking_start":
3455
+ case "thinking_delta":
3456
+ case "thinking_end":
3457
+ case "toolcall_start":
3458
+ case "toolcall_delta":
3459
+ case "toolcall_end":
3460
+ if (partialMessage) {
3461
+ partialMessage = event.partial;
3462
+ context.messages[context.messages.length - 1] = partialMessage;
3463
+ await emit({
3464
+ type: "message_update",
3465
+ assistantMessageEvent: event,
3466
+ message: { ...partialMessage }
3467
+ });
3468
+ }
3469
+ break;
3470
+ case "done":
3471
+ case "error": {
3472
+ const finalMessage2 = await result();
3473
+ if (addedPartial) {
3474
+ context.messages[context.messages.length - 1] = finalMessage2;
3475
+ } else {
3476
+ context.messages.push(finalMessage2);
3477
+ }
3478
+ if (!addedPartial) {
3479
+ await emit({ type: "message_start", message: { ...finalMessage2 } });
3480
+ }
3481
+ await emit({ type: "message_end", message: finalMessage2 });
3482
+ return finalMessage2;
3483
+ }
3484
+ }
3485
+ }
3486
+ const finalMessage = await result();
3487
+ if (addedPartial) {
3488
+ context.messages[context.messages.length - 1] = finalMessage;
3489
+ } else {
3490
+ context.messages.push(finalMessage);
3491
+ await emit({ type: "message_start", message: { ...finalMessage } });
3492
+ }
3493
+ await emit({ type: "message_end", message: finalMessage });
3494
+ return finalMessage;
3495
+ }
3496
+ async function failToolCallsFromTruncatedMessage(toolCalls, emit) {
3497
+ const messages = [];
3498
+ for (const toolCall of toolCalls) {
3499
+ await emit({
3500
+ type: "tool_execution_start",
3501
+ toolCallId: toolCall.id,
3502
+ toolName: toolCall.name,
3503
+ args: toolCall.arguments
3504
+ });
3505
+ const finalized = {
3506
+ toolCall,
3507
+ result: createErrorToolResult(`Tool call "${toolCall.name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`),
3508
+ isError: true
3509
+ };
3510
+ await emitToolExecutionEnd(finalized, emit);
3511
+ const toolResultMessage = createToolResultMessage(finalized);
3512
+ await emitToolResultMessage(toolResultMessage, emit);
3513
+ messages.push(toolResultMessage);
3514
+ }
3515
+ return { messages, terminate: false };
3516
+ }
3517
+ async function executeToolCalls(currentContext, assistantMessage, config, signal, emit) {
3518
+ const toolCalls = assistantMessage.content.filter((c) => c.type === "toolCall");
3519
+ const hasSequentialToolCall = toolCalls.some((tc) => currentContext.tools?.find((t) => t.name === tc.name)?.executionMode === "sequential");
3520
+ if (config.toolExecution === "sequential" || hasSequentialToolCall) {
3521
+ return executeToolCallsSequential(currentContext, assistantMessage, toolCalls, config, signal, emit);
3522
+ }
3523
+ return executeToolCallsParallel(currentContext, assistantMessage, toolCalls, config, signal, emit);
3524
+ }
3525
+ async function executeToolCallsSequential(currentContext, assistantMessage, toolCalls, config, signal, emit) {
3526
+ const finalizedCalls = [];
3527
+ const messages = [];
3528
+ for (const toolCall of toolCalls) {
3529
+ await emit({
3530
+ type: "tool_execution_start",
3531
+ toolCallId: toolCall.id,
3532
+ toolName: toolCall.name,
3533
+ args: toolCall.arguments
3534
+ });
3535
+ const preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);
3536
+ let finalized;
3537
+ if (preparation.kind === "immediate") {
3538
+ finalized = {
3539
+ toolCall,
3540
+ result: preparation.result,
3541
+ isError: preparation.isError
3542
+ };
3543
+ } else {
3544
+ const executed = await executePreparedToolCall(preparation, signal, emitToolExecutionUpdate(toolCall, emit));
3545
+ finalized = await finalizeExecutedToolCall(currentContext, assistantMessage, preparation, executed, config, signal);
3546
+ }
3547
+ await emitToolExecutionEnd(finalized, emit);
3548
+ const toolResultMessage = createToolResultMessage(finalized);
3549
+ await emitToolResultMessage(toolResultMessage, emit);
3550
+ finalizedCalls.push(finalized);
3551
+ messages.push(toolResultMessage);
3552
+ }
3553
+ return {
3554
+ messages,
3555
+ terminate: shouldTerminateToolBatch(finalizedCalls)
3556
+ };
3557
+ }
3558
+ async function executeToolCallsParallel(currentContext, assistantMessage, toolCalls, config, signal, emit) {
3559
+ const finalizedCalls = [];
3560
+ for (const toolCall of toolCalls) {
3561
+ await emit({
3562
+ type: "tool_execution_start",
3563
+ toolCallId: toolCall.id,
3564
+ toolName: toolCall.name,
3565
+ args: toolCall.arguments
3566
+ });
3567
+ const preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);
3568
+ if (preparation.kind === "immediate") {
3569
+ const finalized = {
3570
+ toolCall,
3571
+ result: preparation.result,
3572
+ isError: preparation.isError
3573
+ };
3574
+ await emitToolExecutionEnd(finalized, emit);
3575
+ finalizedCalls.push(finalized);
3576
+ continue;
3577
+ }
3578
+ finalizedCalls.push(async () => {
3579
+ if (signal?.aborted) {
3580
+ const finalized2 = {
3581
+ toolCall,
3582
+ result: createErrorToolResult("Operation aborted"),
3583
+ isError: true
3584
+ };
3585
+ await emitToolExecutionEnd(finalized2, emit);
3586
+ return finalized2;
3587
+ }
3588
+ const executed = await executePreparedToolCall(preparation, signal, emitToolExecutionUpdate(toolCall, emit));
3589
+ const finalized = await finalizeExecutedToolCall(currentContext, assistantMessage, preparation, executed, config, signal);
3590
+ await emitToolExecutionEnd(finalized, emit);
3591
+ return finalized;
3592
+ });
3593
+ }
3594
+ const orderedFinalizedCalls = await Promise.all(finalizedCalls.map((entry) => typeof entry === "function" ? entry() : Promise.resolve(entry)));
3595
+ const messages = [];
3596
+ for (const finalized of orderedFinalizedCalls) {
3597
+ const toolResultMessage = createToolResultMessage(finalized);
3598
+ await emitToolResultMessage(toolResultMessage, emit);
3599
+ messages.push(toolResultMessage);
3600
+ }
3601
+ return {
3602
+ messages,
3603
+ terminate: shouldTerminateToolBatch(orderedFinalizedCalls)
3604
+ };
3605
+ }
3606
+ function shouldTerminateToolBatch(finalizedCalls) {
3607
+ return finalizedCalls.length > 0 && finalizedCalls.every((finalized) => finalized.result.terminate === true);
3608
+ }
3609
+ function prepareToolCallArguments(tool, toolCall) {
3610
+ if (!tool.prepareArguments) {
3611
+ return toolCall;
3612
+ }
3613
+ const preparedArguments = tool.prepareArguments(toolCall.arguments);
3614
+ if (preparedArguments === toolCall.arguments) {
3615
+ return toolCall;
3616
+ }
3617
+ return {
3618
+ ...toolCall,
3619
+ arguments: preparedArguments
3620
+ };
3621
+ }
3622
+ async function prepareToolCall(currentContext, assistantMessage, toolCall, config, signal, tools = currentContext.tools ?? []) {
3623
+ if (signal?.aborted) {
3624
+ return {
3625
+ kind: "immediate",
3626
+ result: createErrorToolResult("Operation aborted"),
3627
+ isError: true
3628
+ };
3629
+ }
3630
+ const tool = tools.find((t) => t.name === toolCall.name);
3631
+ if (!tool) {
3632
+ return {
3633
+ kind: "immediate",
3634
+ result: createErrorToolResult(`Tool ${toolCall.name} not found`),
3635
+ isError: true
3636
+ };
3637
+ }
3638
+ try {
3639
+ const preparedToolCall = prepareToolCallArguments(tool, toolCall);
3640
+ const validatedArgs = validateToolArguments(tool, preparedToolCall);
3641
+ if (config.beforeToolCall) {
3642
+ const beforeResult = await config.beforeToolCall({
3643
+ assistantMessage,
3644
+ toolCall,
3645
+ args: validatedArgs,
3646
+ context: currentContext
3647
+ }, signal);
3648
+ if (signal?.aborted) {
3649
+ return {
3650
+ kind: "immediate",
3651
+ result: createErrorToolResult("Operation aborted"),
3652
+ isError: true
3653
+ };
3654
+ }
3655
+ if (beforeResult?.block) {
3656
+ const result = createErrorToolResult(beforeResult.reason || "Tool execution was blocked");
3657
+ if (beforeResult.terminate === true) {
3658
+ result.terminate = true;
3659
+ }
3660
+ return {
3661
+ kind: "immediate",
3662
+ result,
3663
+ isError: true
3664
+ };
3665
+ }
3666
+ }
3667
+ return {
3668
+ kind: "prepared",
3669
+ toolCall,
3670
+ tool,
3671
+ args: validatedArgs
3672
+ };
3673
+ } catch (error) {
3674
+ return {
3675
+ kind: "immediate",
3676
+ result: createErrorToolResult(error instanceof Error ? error.message : String(error)),
3677
+ isError: true
3678
+ };
3679
+ }
3680
+ }
3681
+ function emitToolExecutionUpdate(toolCall, emit) {
3682
+ return (partialResult) => emit({
3683
+ type: "tool_execution_update",
3684
+ toolCallId: toolCall.id,
3685
+ toolName: toolCall.name,
3686
+ args: toolCall.arguments,
3687
+ partialResult
3688
+ });
3689
+ }
3690
+ async function executePreparedToolCall(prepared, signal, onUpdate) {
3691
+ const updateEvents = [];
3692
+ let acceptingUpdates = true;
3693
+ const startedAt = performance.now();
3694
+ const elapsed = () => Math.round(performance.now() - startedAt);
3695
+ try {
3696
+ const result = await prepared.tool.execute(prepared.toolCall.id, prepared.args, signal, (partialResult) => {
3697
+ if (!acceptingUpdates)
3698
+ return;
3699
+ updateEvents.push(Promise.resolve(onUpdate(partialResult)));
3700
+ });
3701
+ const durationMs = elapsed();
3702
+ acceptingUpdates = false;
3703
+ await Promise.all(updateEvents);
3704
+ return { result, isError: result.isError === true, durationMs };
3705
+ } catch (error) {
3706
+ const durationMs = elapsed();
3707
+ acceptingUpdates = false;
3708
+ await Promise.all(updateEvents);
3709
+ return {
3710
+ result: createErrorToolResult(error instanceof Error ? error.message : String(error)),
3711
+ isError: true,
3712
+ durationMs
3713
+ };
3714
+ } finally {
3715
+ acceptingUpdates = false;
3716
+ }
3717
+ }
3718
+ async function finalizeExecutedToolCall(currentContext, assistantMessage, prepared, executed, config, signal) {
3719
+ let result = executed.result;
3720
+ let isError = executed.isError;
3721
+ if (config.afterToolCall) {
3722
+ try {
3723
+ const afterResult = await config.afterToolCall({
3724
+ assistantMessage,
3725
+ toolCall: prepared.toolCall,
3726
+ args: prepared.args,
3727
+ result,
3728
+ isError,
3729
+ context: currentContext
3730
+ }, signal);
3731
+ if (afterResult) {
3732
+ const structuredContent = afterResult.structuredContent ?? (afterResult.content ? void 0 : result.structuredContent);
3733
+ result = {
3734
+ ...result,
3735
+ content: afterResult.content ?? result.content,
3736
+ details: afterResult.details ?? result.details,
3737
+ usage: afterResult.usage ?? result.usage,
3738
+ terminate: afterResult.terminate ?? result.terminate
3739
+ };
3740
+ if (structuredContent === void 0)
3741
+ delete result.structuredContent;
3742
+ else
3743
+ result.structuredContent = structuredContent;
3744
+ isError = afterResult.isError ?? isError;
3745
+ }
3746
+ } catch (error) {
3747
+ result = createErrorToolResult(error instanceof Error ? error.message : String(error));
3748
+ isError = true;
3749
+ }
3750
+ }
3751
+ return {
3752
+ toolCall: prepared.toolCall,
3753
+ result,
3754
+ isError,
3755
+ durationMs: executed.durationMs
3756
+ };
3757
+ }
3758
+ function createErrorToolResult(message) {
3759
+ return {
3760
+ content: [{ type: "text", text: message }],
3761
+ details: {}
3762
+ };
3763
+ }
3764
+ async function emitToolExecutionEnd(finalized, emit) {
3765
+ await emit({
3766
+ type: "tool_execution_end",
3767
+ toolCallId: finalized.toolCall.id,
3768
+ toolName: finalized.toolCall.name,
3769
+ result: finalized.result,
3770
+ isError: finalized.isError,
3771
+ ...finalized.durationMs === void 0 ? {} : { durationMs: finalized.durationMs }
3772
+ });
3773
+ }
3774
+ function createToolResultMessage(finalized) {
3775
+ return {
3776
+ role: "toolResult",
3777
+ toolCallId: finalized.toolCall.id,
3778
+ toolName: finalized.toolCall.name,
3779
+ // Untyped tools (JS extensions) can return results without content; normalize
3780
+ // so the null never enters session history or provider payloads.
3781
+ content: finalized.result.content ?? [],
3782
+ details: finalized.result.details,
3783
+ usage: finalized.result.usage,
3784
+ isError: finalized.isError,
3785
+ ...finalized.durationMs === void 0 ? {} : { durationMs: finalized.durationMs },
3786
+ timestamp: Date.now()
3787
+ };
3788
+ }
3789
+ async function emitToolResultMessage(toolResultMessage, emit) {
3790
+ await emit({ type: "message_start", message: toolResultMessage });
3791
+ await emit({ type: "message_end", message: toolResultMessage });
3792
+ }
3793
+
3794
+ // packages/harness-client/node_modules/@earendil-works/pi-agent-core/dist/agent.js
3795
+ function defaultConvertToLlm(messages) {
3796
+ return messages.filter((message) => message.role === "system" || message.role === "user" || message.role === "assistant" || message.role === "toolResult");
3797
+ }
3798
+ var EMPTY_USAGE = {
3799
+ input: 0,
3800
+ output: 0,
3801
+ cacheRead: 0,
3802
+ cacheWrite: 0,
3803
+ totalTokens: 0,
3804
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
3805
+ };
3806
+ var DEFAULT_MODEL = {
3807
+ id: "unknown",
3808
+ name: "unknown",
3809
+ api: "unknown",
3810
+ provider: "unknown",
3811
+ baseUrl: "",
3812
+ reasoning: false,
3813
+ input: [],
3814
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
3815
+ contextWindow: 0,
3816
+ maxTokens: 0
3817
+ };
3818
+ function createMutableAgentState(initialState) {
3819
+ let tools = initialState?.tools?.slice() ?? [];
3820
+ let messages = initialState?.messages?.slice() ?? [];
3821
+ const initialMessage = createInitialSystemMessage(initialState?.systemPrompt, tools.map(toToolDeclaration));
3822
+ if (messages[0]?.role !== "system" && initialMessage)
3823
+ messages.unshift(initialMessage);
3824
+ return {
3825
+ get systemPrompt() {
3826
+ return getCurrentSystemPrompt(messages);
3827
+ },
3828
+ model: initialState?.model ?? DEFAULT_MODEL,
3829
+ thinkingLevel: initialState?.thinkingLevel ?? "off",
3830
+ get tools() {
3831
+ return tools;
3832
+ },
3833
+ set tools(nextTools) {
3834
+ tools = nextTools.slice();
3835
+ },
3836
+ get messages() {
3837
+ return messages;
3838
+ },
3839
+ set messages(nextMessages) {
3840
+ messages = nextMessages.slice();
3841
+ },
3842
+ isStreaming: false,
3843
+ streamingMessage: void 0,
3844
+ pendingToolCalls: /* @__PURE__ */ new Set(),
3845
+ errorMessage: void 0
3846
+ };
3847
+ }
3848
+ var PendingMessageQueue = class {
3849
+ messages = [];
3850
+ mode;
3851
+ constructor(mode) {
3852
+ this.mode = mode;
3853
+ }
3854
+ enqueue(message) {
3855
+ this.messages.push(message);
3856
+ }
3857
+ hasItems() {
3858
+ return this.messages.length > 0;
3859
+ }
3860
+ peek() {
3861
+ if (this.mode === "all")
3862
+ return this.messages.slice();
3863
+ const first = this.messages[0];
3864
+ return first ? [first] : [];
3865
+ }
3866
+ drain() {
3867
+ const drained = this.peek();
3868
+ this.messages = this.messages.slice(drained.length);
3869
+ return drained;
3870
+ }
3871
+ clear() {
3872
+ this.messages = [];
3873
+ }
3874
+ };
3875
+ var Agent = class {
3876
+ _state;
3877
+ listeners = /* @__PURE__ */ new Set();
3878
+ steeringQueue;
3879
+ followUpQueue;
3880
+ convertToLlm;
3881
+ transformContext;
3882
+ streamFunction;
3883
+ getApiKey;
3884
+ onPayload;
3885
+ onResponse;
3886
+ onProviderStreamEvent;
3887
+ beforeToolCall;
3888
+ afterToolCall;
3889
+ finishTurn;
3890
+ prepareRequest;
3891
+ prepareNextTurn;
3892
+ prepareNextTurnWithContext;
3893
+ activeRun;
3894
+ /** Session identifier forwarded to providers for cache-aware backends. */
3895
+ sessionId;
3896
+ /** Optional per-level thinking token budgets forwarded to the stream function. */
3897
+ thinkingBudgets;
3898
+ /** Preferred transport forwarded to the stream function. */
3899
+ transport;
3900
+ /** Optional cap for provider-requested retry delays. */
3901
+ maxRetryDelayMs;
3902
+ /** Tool execution strategy for assistant messages that contain multiple tool calls. */
3903
+ toolExecution;
3904
+ /** Request identity forwarded to the stream function, over `DEFAULT_AGENT_IDENTITY`. */
3905
+ identity;
3906
+ constructor(options) {
3907
+ const runtimeOptions = options ?? {};
3908
+ this._state = createMutableAgentState(runtimeOptions.initialState);
3909
+ this.convertToLlm = runtimeOptions.convertToLlm ?? defaultConvertToLlm;
3910
+ this.transformContext = runtimeOptions.transformContext;
3911
+ this.streamFunction = runtimeOptions.streamFn ?? getDefaultStreamFn();
3912
+ this.getApiKey = runtimeOptions.getApiKey;
3913
+ this.onPayload = runtimeOptions.onPayload;
3914
+ this.onResponse = runtimeOptions.onResponse;
3915
+ this.onProviderStreamEvent = runtimeOptions.onProviderStreamEvent;
3916
+ this.beforeToolCall = runtimeOptions.beforeToolCall;
3917
+ this.afterToolCall = runtimeOptions.afterToolCall;
3918
+ this.finishTurn = runtimeOptions.finishTurn;
3919
+ this.prepareRequest = runtimeOptions.prepareRequest;
3920
+ this.prepareNextTurn = runtimeOptions.prepareNextTurn;
3921
+ this.prepareNextTurnWithContext = runtimeOptions.prepareNextTurnWithContext;
3922
+ this.steeringQueue = new PendingMessageQueue(runtimeOptions.steeringMode ?? "one-at-a-time");
3923
+ this.followUpQueue = new PendingMessageQueue(runtimeOptions.followUpMode ?? "one-at-a-time");
3924
+ this.sessionId = runtimeOptions.sessionId;
3925
+ this.thinkingBudgets = runtimeOptions.thinkingBudgets;
3926
+ this.transport = runtimeOptions.transport ?? "auto";
3927
+ this.maxRetryDelayMs = runtimeOptions.maxRetryDelayMs;
3928
+ this.toolExecution = runtimeOptions.toolExecution ?? "parallel";
3929
+ this.identity = runtimeOptions.identity;
3930
+ }
3931
+ /**
3932
+ * Subscribe to agent lifecycle events.
3933
+ *
3934
+ * Listener promises are awaited in subscription order and are included in
3935
+ * the current run's settlement. Listeners also receive the active abort
3936
+ * signal for the current run.
3937
+ *
3938
+ * `agent_end` is the final emitted event for a run, but the agent does not
3939
+ * become idle until all awaited listeners for that event have settled.
3940
+ */
3941
+ subscribe(listener) {
3942
+ this.listeners.add(listener);
3943
+ return () => this.listeners.delete(listener);
3944
+ }
3945
+ /**
3946
+ * Current agent state.
3947
+ *
3948
+ * Assigning `state.tools` or `state.messages` copies the provided top-level array.
3949
+ */
3950
+ get state() {
3951
+ return this._state;
3952
+ }
3953
+ /** Controls how queued steering messages are drained. */
3954
+ set steeringMode(mode) {
3955
+ this.steeringQueue.mode = mode;
3956
+ }
3957
+ get steeringMode() {
3958
+ return this.steeringQueue.mode;
3959
+ }
3960
+ /** Controls how queued follow-up messages are drained. */
3961
+ set followUpMode(mode) {
3962
+ this.followUpQueue.mode = mode;
3963
+ }
3964
+ get followUpMode() {
3965
+ return this.followUpQueue.mode;
3966
+ }
3967
+ /** Queue a message to be injected after the current assistant turn finishes. */
3968
+ steer(message) {
3969
+ this.steeringQueue.enqueue(message);
3970
+ }
3971
+ /** Queue a message to run only after the agent would otherwise stop. */
3972
+ followUp(message) {
3973
+ this.followUpQueue.enqueue(message);
3974
+ }
3975
+ /** Remove all queued steering messages. */
3976
+ clearSteeringQueue() {
3977
+ this.steeringQueue.clear();
3978
+ }
3979
+ /** Remove all queued follow-up messages. */
3980
+ clearFollowUpQueue() {
3981
+ this.followUpQueue.clear();
3982
+ }
3983
+ /** Remove all queued steering and follow-up messages. */
3984
+ clearAllQueues() {
3985
+ this.clearSteeringQueue();
3986
+ this.clearFollowUpQueue();
3987
+ }
3988
+ /** Returns true when either queue still contains pending messages. */
3989
+ hasQueuedMessages() {
3990
+ return this.steeringQueue.hasItems() || this.followUpQueue.hasItems();
3991
+ }
3992
+ /** Preview the messages selected for the next turn without consuming them. */
3993
+ peekQueuedMessages() {
3994
+ const steering = this.steeringQueue.peek();
3995
+ return steering.length > 0 ? steering : this.followUpQueue.peek();
3996
+ }
3997
+ /** Active abort signal for the current run, if any. */
3998
+ get signal() {
3999
+ return this.activeRun?.abortController.signal;
4000
+ }
4001
+ /** Abort the current run, if one is active. */
4002
+ abort() {
4003
+ this.activeRun?.abortController.abort();
4004
+ }
4005
+ /**
4006
+ * Resolve when the current run and all awaited event listeners have finished.
4007
+ *
4008
+ * This resolves after `agent_end` listeners settle.
4009
+ */
4010
+ waitForIdle() {
4011
+ return this.activeRun?.promise ?? Promise.resolve();
4012
+ }
4013
+ /** Clear conversation state and queues while retaining the replayed prompt/tool baseline. */
4014
+ reset() {
4015
+ if (this.activeRun) {
4016
+ throw new Error("Agent is already processing. Wait for completion before resetting.");
4017
+ }
4018
+ const baseline = getCurrentSystemMessage(this._state.messages);
4019
+ this._state.messages = baseline ? [baseline] : [];
4020
+ this._state.isStreaming = false;
4021
+ this._state.streamingMessage = void 0;
4022
+ this._state.pendingToolCalls = /* @__PURE__ */ new Set();
4023
+ this._state.errorMessage = void 0;
4024
+ this.clearFollowUpQueue();
4025
+ this.clearSteeringQueue();
4026
+ }
4027
+ async prompt(input, images) {
4028
+ if (this.activeRun) {
4029
+ throw new Error("Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.");
4030
+ }
4031
+ const messages = this.normalizePromptInput(input, images);
4032
+ await this.runPromptMessages(messages);
4033
+ }
4034
+ /** Continue from the current transcript. The last message must be a user or tool-result message. */
4035
+ async continue() {
4036
+ if (this.activeRun) {
4037
+ throw new Error("Agent is already processing. Wait for completion before continuing.");
4038
+ }
4039
+ const lastMessage = this._state.messages[this._state.messages.length - 1];
4040
+ if (!lastMessage || this._state.messages.every((message) => message.role === "system")) {
4041
+ throw new Error("No messages to continue from");
4042
+ }
4043
+ if (lastMessage.role === "assistant") {
4044
+ const queuedSteering = this.steeringQueue.drain();
4045
+ if (queuedSteering.length > 0) {
4046
+ await this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });
4047
+ return;
4048
+ }
4049
+ const queuedFollowUps = this.followUpQueue.drain();
4050
+ if (queuedFollowUps.length > 0) {
4051
+ await this.runPromptMessages(queuedFollowUps);
4052
+ return;
4053
+ }
4054
+ throw new Error("Cannot continue from message role: assistant");
4055
+ }
4056
+ await this.runContinuation();
4057
+ }
4058
+ normalizePromptInput(input, images) {
4059
+ if (Array.isArray(input)) {
4060
+ return input;
4061
+ }
4062
+ if (typeof input !== "string") {
4063
+ return [input];
4064
+ }
4065
+ const content = [{ type: "text", text: input }];
4066
+ if (images && images.length > 0) {
4067
+ content.push(...images);
4068
+ }
4069
+ return [{ role: "user", content, timestamp: Date.now() }];
4070
+ }
4071
+ async runPromptMessages(messages, options = {}) {
4072
+ await this.runWithLifecycle(async (signal) => {
4073
+ await runAgentLoop(messages, this.createContextSnapshot(), this.createLoopConfig(options), (event) => this.processEvents(event), signal, this.streamFunction);
4074
+ });
4075
+ }
4076
+ async runContinuation() {
4077
+ await this.runWithLifecycle(async (signal) => {
4078
+ await runAgentLoopContinue(this.createContextSnapshot(), this.createLoopConfig(), (event) => this.processEvents(event), signal, this.streamFunction);
4079
+ });
4080
+ }
4081
+ createContextSnapshot() {
4082
+ return {
4083
+ messages: this._state.messages.slice(),
4084
+ tools: this._state.tools.slice()
4085
+ };
4086
+ }
4087
+ createLoopConfig(options = {}) {
4088
+ let skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;
4089
+ return {
4090
+ model: this._state.model,
4091
+ reasoning: this._state.thinkingLevel === "off" ? void 0 : this._state.thinkingLevel,
4092
+ sessionId: this.sessionId,
4093
+ onPayload: this.onPayload,
4094
+ onResponse: this.onResponse,
4095
+ onProviderStreamEvent: this.onProviderStreamEvent,
4096
+ transport: this.transport,
4097
+ thinkingBudgets: this.thinkingBudgets,
4098
+ maxRetryDelayMs: this.maxRetryDelayMs,
4099
+ identity: this.identity,
4100
+ toolExecution: this.toolExecution,
4101
+ beforeToolCall: this.beforeToolCall,
4102
+ afterToolCall: this.afterToolCall,
4103
+ finishTurn: this.finishTurn,
4104
+ prepareRequest: this.prepareRequest,
4105
+ prepareNextTurn: this.prepareNextTurnWithContext || this.prepareNextTurn ? async (context) => {
4106
+ if (this.prepareNextTurnWithContext) {
4107
+ return await this.prepareNextTurnWithContext(context, this.signal);
4108
+ }
4109
+ return await this.prepareNextTurn?.(this.signal);
4110
+ } : void 0,
4111
+ convertToLlm: this.convertToLlm,
4112
+ transformContext: this.transformContext,
4113
+ getApiKey: this.getApiKey,
4114
+ getSteeringMessages: async () => {
4115
+ if (skipInitialSteeringPoll) {
4116
+ skipInitialSteeringPoll = false;
4117
+ return [];
4118
+ }
4119
+ return this.steeringQueue.drain();
4120
+ },
4121
+ getFollowUpMessages: async () => this.followUpQueue.drain()
4122
+ };
4123
+ }
4124
+ async runWithLifecycle(executor) {
4125
+ if (this.activeRun) {
4126
+ throw new Error("Agent is already processing.");
4127
+ }
4128
+ const abortController = new AbortController();
4129
+ let resolvePromise = () => {
4130
+ };
4131
+ const promise = new Promise((resolve) => {
4132
+ resolvePromise = resolve;
4133
+ });
4134
+ this.activeRun = { promise, resolve: resolvePromise, abortController };
4135
+ this._state.isStreaming = true;
4136
+ this._state.streamingMessage = void 0;
4137
+ this._state.errorMessage = void 0;
4138
+ try {
4139
+ await executor(abortController.signal);
4140
+ } catch (error) {
4141
+ await this.handleRunFailure(error, abortController.signal.aborted);
4142
+ } finally {
4143
+ this.finishRun();
4144
+ }
4145
+ }
4146
+ async handleRunFailure(error, aborted) {
4147
+ const failureMessage = {
4148
+ role: "assistant",
4149
+ content: [{ type: "text", text: "" }],
4150
+ api: this._state.model.api,
4151
+ provider: this._state.model.provider,
4152
+ model: this._state.model.id,
4153
+ usage: EMPTY_USAGE,
4154
+ stopReason: aborted ? "aborted" : "error",
4155
+ errorMessage: error instanceof Error ? error.message : String(error),
4156
+ timestamp: Date.now()
4157
+ };
4158
+ await this.processEvents({ type: "message_start", message: failureMessage });
4159
+ await this.processEvents({ type: "message_end", message: failureMessage });
4160
+ await this.processEvents({ type: "turn_end", message: failureMessage, toolResults: [] });
4161
+ await this.processEvents({ type: "agent_end", messages: [failureMessage] });
4162
+ }
4163
+ finishRun() {
4164
+ this._state.isStreaming = false;
4165
+ this._state.streamingMessage = void 0;
4166
+ this._state.pendingToolCalls = /* @__PURE__ */ new Set();
4167
+ this.activeRun?.resolve();
4168
+ this.activeRun = void 0;
4169
+ }
4170
+ /**
4171
+ * Reduce internal state for a loop event, then await listeners.
4172
+ *
4173
+ * `agent_end` only means no further loop events will be emitted. The run is
4174
+ * considered idle later, after all awaited listeners for `agent_end` finish
4175
+ * and `finishRun()` clears runtime-owned state.
4176
+ */
4177
+ async processEvents(event) {
4178
+ switch (event.type) {
4179
+ case "message_start":
4180
+ this._state.streamingMessage = event.message;
4181
+ break;
4182
+ case "message_update":
4183
+ this._state.streamingMessage = event.message;
4184
+ break;
4185
+ case "message_end":
4186
+ this._state.streamingMessage = void 0;
4187
+ this._state.messages.push(event.message);
4188
+ break;
4189
+ case "tool_execution_start": {
4190
+ const pendingToolCalls = new Set(this._state.pendingToolCalls);
4191
+ pendingToolCalls.add(event.toolCallId);
4192
+ this._state.pendingToolCalls = pendingToolCalls;
4193
+ break;
4194
+ }
4195
+ case "tool_execution_end": {
4196
+ const pendingToolCalls = new Set(this._state.pendingToolCalls);
4197
+ pendingToolCalls.delete(event.toolCallId);
4198
+ this._state.pendingToolCalls = pendingToolCalls;
4199
+ break;
4200
+ }
4201
+ case "turn_end":
4202
+ if (event.message.role === "assistant" && event.message.errorMessage) {
4203
+ this._state.errorMessage = event.message.errorMessage;
4204
+ }
4205
+ break;
4206
+ case "agent_end":
4207
+ this._state.streamingMessage = void 0;
4208
+ break;
4209
+ }
4210
+ const signal = this.activeRun?.abortController.signal;
4211
+ if (!signal) {
4212
+ throw new Error("Agent listener invoked outside active run");
4213
+ }
4214
+ for (const listener of this.listeners) {
4215
+ await listener(event, signal);
4216
+ }
4217
+ }
4218
+ };
4219
+
4220
+ // packages/harness-client/src/remote-run.ts
4221
+ function identifier(value) {
4222
+ if (typeof value !== "string" || !/^[A-Za-z0-9|_-]{1,128}$/u.test(value)) throw new Error("Invalid remote scope identifier.");
4223
+ return value;
4224
+ }
4225
+ var RemoteRun = class {
4226
+ scope;
4227
+ runId;
4228
+ abortController = new AbortController();
4229
+ operations = /* @__PURE__ */ new Map();
4230
+ currentState = "running";
4231
+ inferenceCount = 0;
4232
+ resourceCount = 0;
4233
+ constructor(scope, runId) {
4234
+ this.scope = Object.freeze({ userId: identifier(scope.userId), companyId: identifier(scope.companyId), sessionId: identifier(scope.sessionId) });
4235
+ this.runId = identifier(runId);
4236
+ Object.defineProperty(this, "scope", { writable: false });
4237
+ Object.defineProperty(this, "runId", { writable: false });
4238
+ }
4239
+ get state() {
4240
+ return this.currentState;
4241
+ }
4242
+ get signal() {
4243
+ return this.abortController.signal;
4244
+ }
4245
+ begin(kind, operationId) {
4246
+ if (this.state !== "running") throw new Error("Remote run is no longer active.");
4247
+ identifier(operationId);
4248
+ if (this.operations.has(operationId)) throw new Error("Operation outcome must be reconciled; automatic replay is forbidden.");
4249
+ if (kind === "inference") {
4250
+ if (this.inferenceCount >= 2) throw new Error("Bounded inference limit reached.");
4251
+ this.inferenceCount += 1;
4252
+ } else if (kind === "resource") {
4253
+ if (this.resourceCount >= 1) throw new Error("Bounded Resources read limit reached.");
4254
+ this.resourceCount += 1;
4255
+ } else throw new Error("Unsupported remote operation.");
4256
+ const operation = Object.freeze({ ...this.scope, runId: this.runId, operationId, kind });
4257
+ this.operations.set(operationId, { operation, sequence: -1 });
4258
+ return operation;
4259
+ }
4260
+ accept(operation, sequence) {
4261
+ const pending = this.operations.get(operation.operationId);
4262
+ if (this.state !== "running" || !pending || !Number.isSafeInteger(sequence) || sequence <= pending.sequence) return false;
4263
+ if (Object.keys(pending.operation).some((key) => pending.operation[key] !== operation[key])) return false;
4264
+ pending.sequence = sequence;
4265
+ return true;
4266
+ }
4267
+ complete() {
4268
+ if (this.state !== "running") throw new Error("Remote run is no longer active.");
4269
+ this.currentState = "completed";
4270
+ }
4271
+ cancel() {
4272
+ this.stop("cancelled");
4273
+ }
4274
+ interrupt() {
4275
+ this.stop("interrupted");
4276
+ }
4277
+ stop(state) {
4278
+ if (this.state !== "running") return;
4279
+ this.currentState = state;
4280
+ this.abortController.abort();
4281
+ }
4282
+ };
4283
+
4284
+ // packages/harness-client/src/events.ts
4285
+ var record = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
4286
+ function projectBrowserManagedEvent(input) {
4287
+ const event = record(input);
4288
+ if (!event) return;
4289
+ const update = record(event.assistantMessageEvent);
4290
+ if (event.type === "message_update" && update?.type === "text_delta" && typeof update.delta === "string") {
4291
+ return Object.freeze({ type: "message_update", assistantMessageEvent: Object.freeze({ type: "text_delta", delta: update.delta }) });
4292
+ }
4293
+ const message = record(event.message);
4294
+ if (event.type !== "message_end" || message?.role !== "assistant" || !Array.isArray(message.content)) return;
4295
+ const stopReason = message.stopReason;
4296
+ if (stopReason !== "stop" && stopReason !== "toolUse" && stopReason !== "length" && stopReason !== "error" && stopReason !== "aborted") return;
4297
+ const content = Object.freeze(message.content.flatMap((value) => {
4298
+ const block = record(value);
4299
+ return block?.type === "text" && typeof block.text === "string" ? [Object.freeze({ type: "text", text: block.text })] : [];
4300
+ }));
4301
+ return Object.freeze({ type: "message_end", message: Object.freeze({ role: "assistant", stopReason, content }) });
4302
+ }
4303
+
4304
+ // packages/harness-client/src/index.ts
4305
+ var usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } };
4306
+ var model = { id: "managed-default", name: "Company-managed model", provider: "opscompass-managed", api: "openai-responses", baseUrl: "", input: ["text"], reasoning: false, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, contextWindow: 4096, maxTokens: 512 };
4307
+ function createBrowserManagedHarness(options) {
4308
+ const clientContext = snapshotClientContext(options.clientContext);
4309
+ const scope = Object.freeze({ ...options.scope });
4310
+ const fetch2 = options.fetch || globalThis.fetch;
4311
+ let active;
4312
+ let disposed = false;
4313
+ let uncertain = false;
4314
+ const inputEndpoint = options.endpoint;
4315
+ if (typeof inputEndpoint !== "string" || !inputEndpoint || inputEndpoint.includes("\\") || /[\s?#]/u.test(inputEndpoint) || inputEndpoint.startsWith("//")) throw new Error("Invalid trusted AI Access endpoint.");
4316
+ const absolute = /^https?:\/\//iu.test(inputEndpoint);
4317
+ const pageUrl = globalThis.location?.href;
4318
+ if (!absolute && (!inputEndpoint.startsWith("/") || !pageUrl)) throw new Error("AI Access endpoint requires an absolute URL or a browser-root-relative path.");
4319
+ const url = absolute ? new URL(inputEndpoint) : new URL(inputEndpoint, pageUrl);
4320
+ if (url.username || url.password || url.protocol !== "https:" && !(url.protocol === "http:" && ["127.0.0.1", "localhost"].includes(url.hostname))) throw new Error("AI Access requires HTTPS or a loopback fixture.");
4321
+ const endpoint = url.href.replace(/\/$/u, "");
4322
+ async function accessToken(signal) {
4323
+ if (signal.aborted) throw new Error("Identity request cancelled.");
4324
+ let listener = () => {
4325
+ };
4326
+ try {
4327
+ return await Promise.race([options.getAccessToken(), new Promise((_resolve, reject) => {
4328
+ listener = () => reject(new Error("Identity request cancelled."));
4329
+ signal.addEventListener("abort", listener, { once: true });
4330
+ if (signal.aborted) listener();
4331
+ })]);
4332
+ } finally {
4333
+ signal.removeEventListener("abort", listener);
4334
+ }
4335
+ }
4336
+ async function request(action, body, signal, onSubmit) {
4337
+ if (disposed && action !== "cancel") throw new Error("Chat disposed before submission.");
4338
+ const tokenValue = await (signal ? accessToken(signal) : options.getAccessToken());
4339
+ if (disposed && action !== "cancel") throw new Error("Chat disposed before submission.");
4340
+ if (signal?.aborted) throw new Error("Run stopped before submission.");
4341
+ if (typeof tokenValue !== "string" || !tokenValue.trim()) throw new Error("API identity unavailable.");
4342
+ onSubmit?.();
4343
+ const response = await fetch2(`${endpoint}/${action}`, {
4344
+ method: "POST",
4345
+ headers: { Authorization: `Bearer ${tokenValue}`, "Content-Type": "application/json" },
4346
+ body: JSON.stringify(body),
4347
+ signal,
4348
+ credentials: "omit",
4349
+ redirect: "error"
4350
+ });
4351
+ if (!response.ok) throw new Error(`AI_ACCESS_${response.status}`);
4352
+ return response;
4353
+ }
4354
+ function stop() {
4355
+ const current = active;
4356
+ if (!current || current.run.state !== "running") return;
4357
+ if (current.createSubmitted && !current.created) uncertain = true;
4358
+ current.run.cancel();
4359
+ current.agent.abort();
4360
+ options.onState?.("cancelled");
4361
+ if (current.created) void request("cancel", { ...current.run.scope, runId: current.run.runId, operationId: current.operation?.operationId || "run-control", kind: "cancel" }, AbortSignal.timeout(2e3)).catch(() => {
4362
+ });
4363
+ }
4364
+ return {
4365
+ get state() {
4366
+ return active?.run.state || "idle";
4367
+ },
4368
+ async prompt(input, promptOptions) {
4369
+ if (uncertain && active?.createSubmitted && !active.created) {
4370
+ throw new Error("Run creation outcome is unknown. The SDK has no lookup for this create. The host must verify the outcome before starting a fresh client.");
4371
+ }
4372
+ if (disposed || uncertain || active?.run.state === "running") throw new Error("Chat is busy, disposed or requires outcome reconciliation.");
4373
+ if (!input.trim() || input.length > 2e3) throw new Error("A bounded prompt is required.");
4374
+ const pageContext = snapshotPageContext(promptOptions?.pageContext);
4375
+ let run = new RemoteRun(scope, "pending-" + crypto.randomUUID());
4376
+ const current = { run, agent: void 0, operation: void 0, created: false, createSubmitted: false };
4377
+ const agent = new Agent({
4378
+ initialState: { model, systemPrompt: "Use the bounded get_resource tool when needed.", tools: [{
4379
+ name: "get_resource",
4380
+ label: "Read resource",
4381
+ description: "Read one authorized resource.",
4382
+ parameters: { type: "object", properties: { resourceId: { type: "integer", minimum: 1 } }, required: ["resourceId"], additionalProperties: false },
4383
+ replay: "never",
4384
+ async execute(toolCallId, params) {
4385
+ try {
4386
+ const operation = run.begin("resource", crypto.randomUUID());
4387
+ const response = await request("resource", { ...operation, toolCallId, resourceId: params.resourceId }, run.signal, () => {
4388
+ current.operation = operation;
4389
+ });
4390
+ const result = await response.json();
4391
+ if (!run.accept(result.operation, result.sequence)) throw new Error("Stale tool result rejected.");
4392
+ return { content: [{ type: "text", text: JSON.stringify(result.result) }], details: result.result };
4393
+ } catch (error) {
4394
+ if (run.state === "running") {
4395
+ run.interrupt();
4396
+ uncertain = true;
4397
+ current.agent.abort();
4398
+ options.onState?.("interrupted");
4399
+ }
4400
+ throw error;
4401
+ }
4402
+ }
4403
+ }] },
4404
+ beforeToolCall: async () => run.signal.aborted ? { block: true, reason: "Run cancelled" } : void 0,
4405
+ streamFn: () => {
4406
+ const stream = createAssistantMessageEventStream();
4407
+ const partial = { role: "assistant", content: [], api: model.api, provider: model.provider, model: model.id, usage: structuredClone(usage), stopReason: "pending", timestamp: Date.now() };
4408
+ void (async () => {
4409
+ let reader;
4410
+ try {
4411
+ const operation = run.begin("inference", crypto.randomUUID());
4412
+ const response = await request("inference", { ...operation, modelId: model.id, prompt: input, clientContext, ...pageContext ? { pageContext } : {} }, run.signal, () => {
4413
+ current.operation = operation;
4414
+ });
4415
+ if (!response.headers.get("content-type")?.startsWith("text/event-stream") || !response.body) throw new Error("Invalid AI Access stream.");
4416
+ reader = response.body.getReader();
4417
+ const decoder = new TextDecoder();
4418
+ let buffer = "";
4419
+ let bytes = 0;
4420
+ let terminal;
4421
+ stream.push({ type: "start", partial });
4422
+ const consume = (line) => {
4423
+ if (!line.startsWith("data: ")) return;
4424
+ const event = JSON.parse(line.slice(6));
4425
+ if (!run.accept(event.operation, event.sequence)) throw new Error("Stale inference event rejected.");
4426
+ if (terminal) throw new Error("Event after terminal response.");
4427
+ if (event.type === "error") throw new Error("AI Access operation interrupted; reconcile before retry.");
4428
+ if (event.type === "delta" && typeof event.text === "string") {
4429
+ if (!partial.content.length) {
4430
+ partial.content.push({ type: "text", text: "" });
4431
+ stream.push({ type: "text_start", contentIndex: 0, partial });
4432
+ }
4433
+ partial.content[0].text += event.text;
4434
+ stream.push({ type: "text_delta", contentIndex: 0, delta: event.text, partial });
4435
+ } else if (event.type === "message" && event.message?.role === "assistant" && ["stop", "toolUse"].includes(event.message.stopReason)) {
4436
+ terminal = event.message;
4437
+ } else throw new Error("Invalid AI Access event.");
4438
+ };
4439
+ for (; ; ) {
4440
+ const next = await reader.read();
4441
+ if (next.done) break;
4442
+ bytes += next.value.byteLength;
4443
+ if (bytes > 262144) throw new Error("AI Access stream limit exceeded.");
4444
+ buffer += decoder.decode(next.value, { stream: true });
4445
+ const lines = buffer.split("\n");
4446
+ buffer = lines.pop() || "";
4447
+ for (const line of lines) consume(line);
4448
+ }
4449
+ buffer += decoder.decode();
4450
+ if (buffer) consume(buffer);
4451
+ if (!terminal) throw new Error("Incomplete AI Access stream; outcome unknown.");
4452
+ if (run.state !== "running") throw new Error("Run is no longer active.");
4453
+ stream.push({ type: "done", reason: terminal.stopReason, message: terminal });
4454
+ } catch {
4455
+ if (run.state === "running") {
4456
+ run.interrupt();
4457
+ uncertain = true;
4458
+ options.onState?.("interrupted");
4459
+ current.agent.abort();
4460
+ }
4461
+ partial.stopReason = run.state === "cancelled" ? "aborted" : "error";
4462
+ partial.errorMessage = "AI Access interrupted. No automatic retry was attempted.";
4463
+ stream.push({ type: "error", reason: partial.stopReason, error: partial });
4464
+ } finally {
4465
+ if (reader) {
4466
+ await reader.cancel().catch(() => {
4467
+ });
4468
+ reader.releaseLock();
4469
+ }
4470
+ stream.end();
4471
+ }
4472
+ })();
4473
+ return stream;
4474
+ }
4475
+ });
4476
+ current.agent = agent;
4477
+ active = current;
4478
+ agent.subscribe((event) => {
4479
+ if (disposed) return;
4480
+ if (run.state !== "running" && !(run.state === "interrupted" && event.type === "message_end" && event.message.role === "assistant")) return;
4481
+ const projected = projectBrowserManagedEvent(event);
4482
+ if (projected) options.onEvent?.(projected);
4483
+ });
4484
+ options.onState?.("running");
4485
+ const deadline = setTimeout(() => {
4486
+ if (run.state === "running") {
4487
+ run.interrupt();
4488
+ uncertain = true;
4489
+ agent.abort();
4490
+ options.onState?.("interrupted");
4491
+ }
4492
+ }, 1e4);
4493
+ try {
4494
+ const response = await request("create", { ...scope, kind: "create" }, run.signal, () => {
4495
+ current.createSubmitted = true;
4496
+ });
4497
+ const created = await response.json();
4498
+ if (run.signal.aborted) return;
4499
+ if (typeof created.runId !== "string" || !/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(created.runId)) throw new Error("Invalid server-created run.");
4500
+ run = new RemoteRun(scope, created.runId);
4501
+ current.run = run;
4502
+ current.created = true;
4503
+ await agent.prompt(input);
4504
+ if (run.state === "running") {
4505
+ run.complete();
4506
+ options.onState?.("completed");
4507
+ }
4508
+ } catch {
4509
+ if (run.state === "running") {
4510
+ run.interrupt();
4511
+ uncertain = true;
4512
+ agent.abort();
4513
+ options.onState?.("interrupted");
4514
+ }
4515
+ } finally {
4516
+ clearTimeout(deadline);
4517
+ }
4518
+ },
4519
+ stop,
4520
+ async reconcile() {
4521
+ if (!active?.operation) throw new Error("No operation to reconcile.");
4522
+ const response = await request("status", { ...active.operation, kind: "status" }, AbortSignal.timeout(2e3));
4523
+ return response.json();
4524
+ },
4525
+ dispose() {
4526
+ disposed = true;
4527
+ stop();
4528
+ }
4529
+ };
4530
+ }
4531
+ export {
4532
+ RemoteRun,
4533
+ createBrowserManagedHarness
4534
+ };