@infernetprotocol/liquid-agent 0.0.0-stage → 0.1.66

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +15 -2
  3. package/fixtures/contract.json +6 -0
  4. package/fixtures/invalid/episode-extra-field.json +275 -0
  5. package/fixtures/invalid/episode-no-capture.json +265 -0
  6. package/fixtures/invalid/episode-unknown-action.json +274 -0
  7. package/fixtures/invalid/model-manifest-bad-hash.json +92 -0
  8. package/fixtures/invalid/predict-negative-seq.json +48 -0
  9. package/fixtures/invalid/proposal-bad-abstain.json +31 -0
  10. package/fixtures/invalid/proposal-confidence-range.json +31 -0
  11. package/fixtures/invalid/session-bad-seq.json +17 -0
  12. package/fixtures/invalid/train-job-bad-family.json +44 -0
  13. package/fixtures/invalid/train-job-zero-lr.json +44 -0
  14. package/fixtures/valid/action-proposal.json +27 -0
  15. package/fixtures/valid/dataset-bundle.json +3747 -0
  16. package/fixtures/valid/dataset-manifest.json +126 -0
  17. package/fixtures/valid/episode.json +270 -0
  18. package/fixtures/valid/inference-session.json +13 -0
  19. package/fixtures/valid/model-manifest.json +88 -0
  20. package/fixtures/valid/predict-request.json +44 -0
  21. package/fixtures/valid/train-job.json +40 -0
  22. package/package.json +28 -3
  23. package/runtime/infernet_liquid/__init__.py +6 -0
  24. package/runtime/infernet_liquid/__main__.py +95 -0
  25. package/runtime/infernet_liquid/bench.py +125 -0
  26. package/runtime/infernet_liquid/bundle.py +63 -0
  27. package/runtime/infernet_liquid/canonical.py +75 -0
  28. package/runtime/infernet_liquid/data.py +121 -0
  29. package/runtime/infernet_liquid/errors.py +13 -0
  30. package/runtime/infernet_liquid/evaluate.py +145 -0
  31. package/runtime/infernet_liquid/export.py +136 -0
  32. package/runtime/infernet_liquid/features.py +105 -0
  33. package/runtime/infernet_liquid/models.py +63 -0
  34. package/runtime/infernet_liquid/schema.py +155 -0
  35. package/runtime/infernet_liquid/secretscan.py +64 -0
  36. package/runtime/infernet_liquid/server.py +251 -0
  37. package/runtime/infernet_liquid/sessions.py +279 -0
  38. package/runtime/infernet_liquid/synth.py +194 -0
  39. package/runtime/infernet_liquid/train.py +136 -0
  40. package/runtime/pyproject.toml +14 -0
  41. package/runtime/requirements-cuda.lock +461 -0
  42. package/runtime/requirements.lock +344 -0
  43. package/schemas/action-proposal.schema.json +40 -0
  44. package/schemas/common.schema.json +88 -0
  45. package/schemas/dataset-bundle.schema.json +15 -0
  46. package/schemas/dataset-manifest.schema.json +100 -0
  47. package/schemas/episode.schema.json +71 -0
  48. package/schemas/inference-session.schema.json +23 -0
  49. package/schemas/model-manifest.schema.json +103 -0
  50. package/schemas/predict-request.schema.json +20 -0
  51. package/schemas/train-job.schema.json +75 -0
  52. package/src/canonical.js +49 -0
  53. package/src/contract.js +62 -0
  54. package/src/dataset.js +133 -0
  55. package/src/index.js +13 -0
  56. package/src/runtime.js +206 -0
  57. package/src/secrets.js +79 -0
  58. package/src/validate.js +161 -0
package/src/runtime.js ADDED
@@ -0,0 +1,206 @@
1
+ /**
2
+ * Locate, install and talk to the isolated `infernet-liquid` Python runtime.
3
+ *
4
+ * The runtime is never installed implicitly: `setupRuntime()` runs only from
5
+ * `infernet model runtime setup` (or a caller that asked the operator first).
6
+ * It builds a venv from the hash-pinned lock under
7
+ * ~/.infernet/liquid/<lock>-<lock-hash-12>/ so a lock change gets a fresh venv.
8
+ * Node never imports Python; everything crosses a stdio NDJSON pipe.
9
+ */
10
+
11
+ import { spawn, spawnSync } from "node:child_process";
12
+ import { createHash } from "node:crypto";
13
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
14
+ import os from "node:os";
15
+ import path from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+ import { ERROR_CODES, RUNTIME_PROTOCOL_VERSION } from "./contract.js";
18
+
19
+ export const RUNTIME_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "runtime");
20
+ export const MIN_PYTHON = [3, 11];
21
+
22
+ export function lockFile(accelerator = "cpu") {
23
+ return path.join(RUNTIME_DIR, accelerator === "cuda" ? "requirements-cuda.lock" : "requirements.lock");
24
+ }
25
+
26
+ export function lockHash(accelerator = "cpu") {
27
+ return `sha256:${createHash("sha256").update(readFileSync(lockFile(accelerator))).digest("hex")}`;
28
+ }
29
+
30
+ export function runtimeHome(env = process.env) {
31
+ return env.INFERNET_LIQUID_HOME ?? path.join(env.HOME ?? os.homedir(), ".infernet", "liquid");
32
+ }
33
+
34
+ export function venvDir(accelerator = "cpu", env = process.env) {
35
+ return path.join(runtimeHome(env), `${accelerator}-${lockHash(accelerator).slice(7, 19)}`);
36
+ }
37
+
38
+ function venvPython(dir) {
39
+ return process.platform === "win32" ? path.join(dir, "Scripts", "python.exe") : path.join(dir, "bin", "python");
40
+ }
41
+
42
+ /** Where the runtime would run from, or null when it is not installed. */
43
+ export function resolveRuntime({ env = process.env, accelerator } = {}) {
44
+ if (env.INFERNET_LIQUID_PYTHON) {
45
+ return { python: env.INFERNET_LIQUID_PYTHON, accelerator: env.INFERNET_LIQUID_LOCK ?? "cpu", source: "env" };
46
+ }
47
+ for (const acc of accelerator ? [accelerator] : ["cuda", "cpu"]) {
48
+ const dir = venvDir(acc, env);
49
+ if (existsSync(path.join(dir, "installed.json")) && existsSync(venvPython(dir))) {
50
+ return { python: venvPython(dir), accelerator: acc, source: dir };
51
+ }
52
+ }
53
+ return null;
54
+ }
55
+
56
+ function pythonVersion(bin) {
57
+ const r = spawnSync(bin, ["-c", "import sys;print('%d.%d' % sys.version_info[:2])"], { encoding: "utf8" });
58
+ if (r.status !== 0) return null;
59
+ const [maj, min] = r.stdout.trim().split(".").map(Number);
60
+ return [maj, min];
61
+ }
62
+
63
+ export function findBasePython(env = process.env) {
64
+ const candidates = [env.INFERNET_LIQUID_BASE_PYTHON, "python3.13", "python3.12", "python3.11", "python3", "python"].filter(Boolean);
65
+ for (const bin of candidates) {
66
+ const v = pythonVersion(bin);
67
+ if (v && (v[0] > MIN_PYTHON[0] || (v[0] === MIN_PYTHON[0] && v[1] >= MIN_PYTHON[1]))) return { bin, version: v.join(".") };
68
+ }
69
+ return null;
70
+ }
71
+
72
+ /**
73
+ * Create the venv and install the locked dependencies (pip --require-hashes).
74
+ * `log` receives progress lines. Returns the resolved runtime.
75
+ */
76
+ export async function setupRuntime({ accelerator = "cpu", env = process.env, log = () => {} } = {}) {
77
+ const base = findBasePython(env);
78
+ if (!base) throw Object.assign(new Error("Python 3.11+ not found; install python3 (3.11 or newer) first"), { code: "E_RUNTIME_MISSING" });
79
+ const dir = venvDir(accelerator, env);
80
+ mkdirSync(path.dirname(dir), { recursive: true });
81
+ const run = (cmd, args) =>
82
+ new Promise((resolve, reject) => {
83
+ log(`$ ${cmd} ${args.join(" ")}`);
84
+ const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"], env: { ...env, PIP_DISABLE_PIP_VERSION_CHECK: "1" } });
85
+ child.stdout.on("data", (b) => log(b.toString().trimEnd()));
86
+ child.stderr.on("data", (b) => log(b.toString().trimEnd()));
87
+ child.on("error", reject);
88
+ child.on("exit", (code) => (code === 0 ? resolve() : reject(new Error(`${cmd} exited ${code}`))));
89
+ });
90
+ if (!existsSync(venvPython(dir))) await run(base.bin, ["-m", "venv", dir]);
91
+ await run(venvPython(dir), ["-m", "pip", "install", "--require-hashes", "--no-deps", "-r", lockFile(accelerator)]);
92
+ const marker = { lock_hash: lockHash(accelerator), accelerator, python: base.version, installed_at: new Date().toISOString() };
93
+ writeFileSync(path.join(dir, "installed.json"), JSON.stringify(marker, null, 2) + "\n");
94
+ return { python: venvPython(dir), accelerator, source: dir };
95
+ }
96
+
97
+ export class RuntimeError extends Error {
98
+ constructor({ code, message, retriable, ...extra }) {
99
+ super(message);
100
+ this.code = code;
101
+ this.retriable = retriable ?? ERROR_CODES[code]?.retriable ?? false;
102
+ Object.assign(this, extra);
103
+ }
104
+ }
105
+
106
+ /**
107
+ * One long-lived runtime process. `request(op, params, {onEvent, timeoutMs})`
108
+ * resolves with the result or rejects with a RuntimeError carrying the
109
+ * contract's error code.
110
+ */
111
+ export class LiquidRuntime {
112
+ constructor({ python, accelerator = "cpu", args = [], env = process.env, spawnImpl = spawn } = {}) {
113
+ const rt = python ? { python, accelerator } : resolveRuntime({ env });
114
+ if (!rt) {
115
+ throw new RuntimeError({
116
+ code: "E_RUNTIME_MISSING",
117
+ message: "the infernet-liquid runtime is not installed; run `infernet model runtime setup` (downloads PyTorch + ncps, about 1 GB on CPU)"
118
+ });
119
+ }
120
+ this.child = spawnImpl(rt.python, ["-m", "infernet_liquid", "serve", ...args], {
121
+ stdio: ["pipe", "pipe", "pipe"],
122
+ env: { ...env, PYTHONPATH: RUNTIME_DIR, PYTHONUNBUFFERED: "1", INFERNET_LIQUID_LOCK: rt.accelerator }
123
+ });
124
+ this.pending = new Map();
125
+ this.seq = 0;
126
+ this.buf = "";
127
+ this.stderr = "";
128
+ this.closed = false;
129
+ this.child.stdout.setEncoding("utf8");
130
+ this.child.stdout.on("data", (chunk) => this.#onData(chunk));
131
+ this.child.stderr?.on("data", (b) => {
132
+ this.stderr = (this.stderr + b.toString()).slice(-8192);
133
+ });
134
+ this.child.on("exit", (code) => {
135
+ this.closed = true;
136
+ for (const p of this.pending.values()) {
137
+ p.reject(new RuntimeError({ code: "E_RUNTIME", message: `infernet-liquid exited ${code}${this.stderr ? `: ${this.stderr.trim().split("\n").slice(-3).join(" | ")}` : ""}` }));
138
+ }
139
+ this.pending.clear();
140
+ });
141
+ this.child.on("error", (err) => {
142
+ this.closed = true;
143
+ for (const p of this.pending.values()) p.reject(new RuntimeError({ code: "E_RUNTIME_MISSING", message: err.message }));
144
+ this.pending.clear();
145
+ });
146
+ }
147
+
148
+ #onData(chunk) {
149
+ this.buf += chunk;
150
+ let i;
151
+ while ((i = this.buf.indexOf("\n")) >= 0) {
152
+ const line = this.buf.slice(0, i).trim();
153
+ this.buf = this.buf.slice(i + 1);
154
+ if (!line) continue;
155
+ let msg;
156
+ try {
157
+ msg = JSON.parse(line);
158
+ } catch {
159
+ continue;
160
+ }
161
+ const p = this.pending.get(msg.id);
162
+ if (!p) continue;
163
+ if (msg.event) {
164
+ p.onEvent?.(msg);
165
+ continue;
166
+ }
167
+ this.pending.delete(msg.id);
168
+ clearTimeout(p.timer);
169
+ if (msg.ok) p.resolve(msg.result);
170
+ else p.reject(new RuntimeError(msg.error ?? { code: "E_RUNTIME", message: "unknown runtime error" }));
171
+ }
172
+ }
173
+
174
+ /** Send one op. `onId` receives the request id (to `cancel` a train/evaluate). */
175
+ request(op, params = {}, { onEvent, timeoutMs, onId } = {}) {
176
+ if (this.closed) return Promise.reject(new RuntimeError({ code: "E_RUNTIME", message: "runtime is not running" }));
177
+ const id = `r${++this.seq}`;
178
+ onId?.(id);
179
+ return new Promise((resolve, reject) => {
180
+ const entry = { resolve, reject, onEvent, timer: null };
181
+ if (timeoutMs) {
182
+ entry.timer = setTimeout(() => {
183
+ this.pending.delete(id);
184
+ if (op === "train" || op === "evaluate") this.child.stdin.write(JSON.stringify({ v: RUNTIME_PROTOCOL_VERSION, id: `c${id}`, op: "cancel", target: id }) + "\n");
185
+ reject(new RuntimeError({ code: "E_TIMEOUT", message: `${op} timed out after ${timeoutMs} ms` }));
186
+ }, timeoutMs);
187
+ }
188
+ this.pending.set(id, entry);
189
+ this.child.stdin.write(JSON.stringify({ v: RUNTIME_PROTOCOL_VERSION, id, op, ...params }) + "\n");
190
+ });
191
+ }
192
+
193
+ cancel(id) {
194
+ return this.request("cancel", { target: id }, { timeoutMs: 10000 });
195
+ }
196
+
197
+ async close() {
198
+ if (this.closed) return;
199
+ try {
200
+ await this.request("shutdown", {}, { timeoutMs: 5000 });
201
+ } catch {
202
+ /* fall through to kill */
203
+ }
204
+ if (!this.closed) this.child.kill("SIGTERM");
205
+ }
206
+ }
package/src/secrets.js ADDED
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Secret scan for anything that may leave the device or reach a log.
3
+ * Episodes must never carry credentials, cookies, tokens or card numbers;
4
+ * redaction happens at capture, this is the second fence before export,
5
+ * upload or training. Mirrored in runtime/infernet_liquid/secrets.py.
6
+ */
7
+
8
+ export const SCANNER_VERSION = "1";
9
+
10
+ const PATTERNS = [
11
+ ["private_key", /-----BEGIN [A-Z ]*PRIVATE KEY-----/],
12
+ ["jwt", /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/],
13
+ ["aws_access_key", /\b(AKIA|ASIA)[0-9A-Z]{16}\b/],
14
+ ["github_token", /\bgh[pousr]_[A-Za-z0-9]{30,}\b/],
15
+ ["slack_token", /\bxox[abprs]-[A-Za-z0-9-]{10,}/],
16
+ ["api_key", /\b(sk|pk|rk)[-_](live|test|proj|ant)?[-_]?[A-Za-z0-9]{20,}\b/],
17
+ ["bearer", /\bBearer\s+[A-Za-z0-9._~+/=-]{16,}/i],
18
+ ["cookie", /\b(set-cookie|cookie)\s*:/i],
19
+ ["password_assignment", /\b(pass(word)?|passwd|pwd|secret|api[_-]?key|token)\s*[:=]\s*\S{4,}/i]
20
+ ];
21
+
22
+ // Structural fields are hashes/ids/timestamps; long digit runs there are not cards.
23
+ const STRUCTURAL = /(_hash|_ref|_id|_at|_ms|^seed$|^dt_ms$|^t_ms$)$/;
24
+
25
+ function luhn(digits) {
26
+ let sum = 0;
27
+ let alt = false;
28
+ for (let i = digits.length - 1; i >= 0; i -= 1) {
29
+ let d = digits.charCodeAt(i) - 48;
30
+ if (alt) {
31
+ d *= 2;
32
+ if (d > 9) d -= 9;
33
+ }
34
+ sum += d;
35
+ alt = !alt;
36
+ }
37
+ return sum % 10 === 0;
38
+ }
39
+
40
+ export function scanText(text) {
41
+ const hits = [];
42
+ for (const [name, re] of PATTERNS) if (re.test(text)) hits.push(name);
43
+ for (const m of text.matchAll(/(?:\d[ -]?){13,19}/g)) {
44
+ const digits = m[0].replace(/[ -]/g, "");
45
+ if (digits.length >= 13 && digits.length <= 19 && luhn(digits)) {
46
+ hits.push("card_number");
47
+ break;
48
+ }
49
+ }
50
+ return hits;
51
+ }
52
+
53
+ /** Walk any JSON value; returns [{path, kinds}] for every string that looks secret. */
54
+ export function scanSecrets(value, at = "") {
55
+ const out = [];
56
+ const walk = (v, p, key) => {
57
+ if (typeof v === "string") {
58
+ if (key && STRUCTURAL.test(key)) return;
59
+ const kinds = scanText(v);
60
+ if (kinds.length) out.push({ path: p, kinds });
61
+ } else if (Array.isArray(v)) {
62
+ v.forEach((x, i) => walk(x, `${p}/${i}`, key));
63
+ } else if (v && typeof v === "object") {
64
+ for (const [k, x] of Object.entries(v)) walk(x, `${p}/${k}`, k);
65
+ }
66
+ };
67
+ walk(value, at, null);
68
+ return out;
69
+ }
70
+
71
+ export function assertNoSecrets(value, label = "payload") {
72
+ const hits = scanSecrets(value);
73
+ if (hits.length) {
74
+ const err = new Error(`${label} contains what looks like a secret at ${hits.slice(0, 3).map((h) => `${h.path} (${h.kinds.join(",")})`).join("; ")}; redact it before export`);
75
+ err.code = "E_SECRET_DETECTED";
76
+ err.hits = hits;
77
+ throw err;
78
+ }
79
+ }
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Dependency-free validator for the JSON Schema subset the liquid-agent/v1
3
+ * schemas use: type, const, enum, properties, required, additionalProperties,
4
+ * items, min/maxItems, uniqueItems, min/maxLength, pattern, minimum, maximum,
5
+ * exclusiveMinimum, anyOf, $ref (same file or sibling file) and
6
+ * format: date-time. A keyword outside that list is a schema bug and throws, so
7
+ * the subset cannot silently grow. runtime/infernet_liquid/schema.py mirrors it.
8
+ */
9
+
10
+ import { readFileSync, readdirSync } from "node:fs";
11
+ import path from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+
14
+ export const SCHEMA_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "schemas");
15
+
16
+ const KNOWN = new Set([
17
+ "$schema", "$id", "$defs", "$ref", "title", "description", "type", "const", "enum",
18
+ "properties", "required", "additionalProperties", "items", "minItems", "maxItems",
19
+ "uniqueItems", "minLength", "maxLength", "pattern", "minimum", "maximum",
20
+ "exclusiveMinimum", "anyOf", "format"
21
+ ]);
22
+
23
+ const DATE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
24
+
25
+ /** kind → schema file. */
26
+ export const SCHEMA_FILES = Object.freeze({
27
+ episode: "episode.schema.json",
28
+ dataset_manifest: "dataset-manifest.schema.json",
29
+ dataset_bundle: "dataset-bundle.schema.json",
30
+ train_job: "train-job.schema.json",
31
+ model_manifest: "model-manifest.schema.json",
32
+ inference_session: "inference-session.schema.json",
33
+ predict_request: "predict-request.schema.json",
34
+ action_proposal: "action-proposal.schema.json"
35
+ });
36
+
37
+ let registry = null;
38
+
39
+ function loadRegistry() {
40
+ if (registry) return registry;
41
+ registry = new Map();
42
+ for (const file of readdirSync(SCHEMA_DIR).filter((f) => f.endsWith(".schema.json")).sort()) {
43
+ registry.set(file, JSON.parse(readFileSync(path.join(SCHEMA_DIR, file), "utf8")));
44
+ }
45
+ return registry;
46
+ }
47
+
48
+ export function schemaFiles() {
49
+ return [...loadRegistry().keys()];
50
+ }
51
+
52
+ function resolveRef(ref, baseFile) {
53
+ const [file, frag] = ref.split("#");
54
+ const target = file ? file : baseFile;
55
+ const root = loadRegistry().get(target);
56
+ if (!root) throw new Error(`schema $ref to unknown file: ${ref}`);
57
+ let node = root;
58
+ if (frag) {
59
+ for (const part of frag.split("/").filter(Boolean)) {
60
+ node = node?.[part];
61
+ if (node === undefined) throw new Error(`schema $ref not found: ${ref}`);
62
+ }
63
+ }
64
+ return { node, file: target };
65
+ }
66
+
67
+ function typeOf(v) {
68
+ if (v === null) return "null";
69
+ if (Array.isArray(v)) return "array";
70
+ if (typeof v === "number") return Number.isInteger(v) ? "integer" : "number";
71
+ return typeof v;
72
+ }
73
+
74
+ function typeMatches(want, v) {
75
+ const got = typeOf(v);
76
+ if (want === "number") return got === "number" || got === "integer";
77
+ return want === got;
78
+ }
79
+
80
+ function check(schema, value, at, file, errors) {
81
+ for (const key of Object.keys(schema)) {
82
+ if (!KNOWN.has(key)) throw new Error(`schema keyword not supported by the subset validator: ${key} (${file})`);
83
+ }
84
+ if (schema.$ref) {
85
+ const { node, file: f } = resolveRef(schema.$ref, file);
86
+ check(node, value, at, f, errors);
87
+ }
88
+ if (schema.anyOf) {
89
+ const ok = schema.anyOf.some((s) => {
90
+ const e = [];
91
+ check(s, value, at, file, e);
92
+ return e.length === 0;
93
+ });
94
+ if (!ok) errors.push({ path: at, message: "does not match any allowed shape" });
95
+ return;
96
+ }
97
+ if ("const" in schema && JSON.stringify(schema.const) !== JSON.stringify(value)) {
98
+ errors.push({ path: at, message: `must equal ${JSON.stringify(schema.const)}` });
99
+ return;
100
+ }
101
+ if (schema.enum && !schema.enum.some((e) => e === value)) {
102
+ errors.push({ path: at, message: `must be one of ${schema.enum.join(", ")}` });
103
+ return;
104
+ }
105
+ if (schema.type && !typeMatches(schema.type, value)) {
106
+ errors.push({ path: at, message: `must be ${schema.type}` });
107
+ return;
108
+ }
109
+ const t = typeOf(value);
110
+ if (t === "string") {
111
+ if (schema.minLength !== undefined && [...value].length < schema.minLength) errors.push({ path: at, message: `shorter than ${schema.minLength}` });
112
+ if (schema.maxLength !== undefined && [...value].length > schema.maxLength) errors.push({ path: at, message: `longer than ${schema.maxLength}` });
113
+ if (schema.pattern && !new RegExp(schema.pattern, "u").test(value)) errors.push({ path: at, message: `does not match ${schema.pattern}` });
114
+ if (schema.format === "date-time" && (!DATE_TIME.test(value) || Number.isNaN(Date.parse(value)))) errors.push({ path: at, message: "not an RFC 3339 date-time" });
115
+ }
116
+ if (t === "number" || t === "integer") {
117
+ if (schema.minimum !== undefined && value < schema.minimum) errors.push({ path: at, message: `below ${schema.minimum}` });
118
+ if (schema.maximum !== undefined && value > schema.maximum) errors.push({ path: at, message: `above ${schema.maximum}` });
119
+ if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push({ path: at, message: `must be > ${schema.exclusiveMinimum}` });
120
+ }
121
+ if (t === "array") {
122
+ if (schema.minItems !== undefined && value.length < schema.minItems) errors.push({ path: at, message: `fewer than ${schema.minItems} items` });
123
+ if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push({ path: at, message: `more than ${schema.maxItems} items` });
124
+ if (schema.uniqueItems && new Set(value.map((v) => JSON.stringify(v))).size !== value.length) errors.push({ path: at, message: "items must be unique" });
125
+ if (schema.items) value.forEach((v, i) => check(schema.items, v, `${at}/${i}`, file, errors));
126
+ }
127
+ if (t === "object") {
128
+ for (const req of schema.required ?? []) {
129
+ if (!(req in value)) errors.push({ path: `${at}/${req}`, message: "is required" });
130
+ }
131
+ const props = schema.properties ?? {};
132
+ for (const [k, v] of Object.entries(value)) {
133
+ if (k in props) check(props[k], v, `${at}/${k}`, file, errors);
134
+ else if (schema.additionalProperties === false) errors.push({ path: `${at}/${k}`, message: "is not allowed" });
135
+ else if (schema.additionalProperties && typeof schema.additionalProperties === "object") check(schema.additionalProperties, v, `${at}/${k}`, file, errors);
136
+ }
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Validate `value` against a liquid-agent/v1 schema. `kind` defaults to
142
+ * value.kind. Returns { ok, errors: [{path, message}] }.
143
+ */
144
+ export function validate(value, kind = value?.kind) {
145
+ const file = SCHEMA_FILES[kind];
146
+ if (!file) return { ok: false, errors: [{ path: "/kind", message: `unknown kind: ${kind}` }] };
147
+ const errors = [];
148
+ check(loadRegistry().get(file), value, "", file, errors);
149
+ return { ok: errors.length === 0, errors };
150
+ }
151
+
152
+ export function assertValid(value, kind) {
153
+ const r = validate(value, kind);
154
+ if (!r.ok) {
155
+ const err = new Error(`${kind ?? value?.kind ?? "object"} failed liquid-agent/v1 validation: ${r.errors.slice(0, 5).map((e) => `${e.path || "/"} ${e.message}`).join("; ")}`);
156
+ err.code = "E_SCHEMA";
157
+ err.errors = r.errors;
158
+ throw err;
159
+ }
160
+ return value;
161
+ }