@nylorun/core 0.26.0-beta → 0.28.0-beta

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 (47) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/README.md +6 -0
  3. package/dist/compatibility.d.ts +11 -2
  4. package/dist/compatibility.js +10 -0
  5. package/dist/contracts.d.ts +362 -0
  6. package/dist/contracts.js +131 -5
  7. package/dist/define.d.ts +2 -1
  8. package/dist/define.js +2 -1
  9. package/dist/definition/cron.d.ts +15 -0
  10. package/dist/definition/cron.js +155 -0
  11. package/dist/definition/sections.d.ts +11 -0
  12. package/dist/definition/sections.js +29 -20
  13. package/dist/folder/compile.d.ts +87 -0
  14. package/dist/folder/compile.js +1280 -0
  15. package/dist/folder/context.d.ts +97 -0
  16. package/dist/folder/context.js +79 -0
  17. package/dist/folder/decompile.d.ts +18 -0
  18. package/dist/folder/decompile.js +660 -0
  19. package/dist/folder/fix.d.ts +22 -0
  20. package/dist/folder/fix.js +191 -0
  21. package/dist/folder/flow.d.ts +42 -0
  22. package/dist/folder/flow.js +215 -0
  23. package/dist/folder/frontmatter.d.ts +21 -0
  24. package/dist/folder/frontmatter.js +91 -0
  25. package/dist/folder/index.d.ts +12 -0
  26. package/dist/folder/index.js +12 -0
  27. package/dist/folder/json-schema.d.ts +15 -0
  28. package/dist/folder/json-schema.js +212 -0
  29. package/dist/folder/json.d.ts +28 -0
  30. package/dist/folder/json.js +183 -0
  31. package/dist/folder/nested.d.ts +24 -0
  32. package/dist/folder/nested.js +378 -0
  33. package/dist/folder/plugins.d.ts +23 -0
  34. package/dist/folder/plugins.js +155 -0
  35. package/dist/folder/schemas.d.ts +8 -0
  36. package/dist/folder/schemas.js +238 -0
  37. package/dist/folder/suggest.d.ts +13 -0
  38. package/dist/folder/suggest.js +63 -0
  39. package/dist/schemas/agent-folder/agent-md.schema.json +143 -0
  40. package/dist/schemas/agent-folder/flow.schema.json +466 -0
  41. package/dist/schemas/agent-folder/mcp.schema.json +59 -0
  42. package/dist/schemas/agent-folder/runtime.schema.json +447 -0
  43. package/dist/schemas/agent-folder/tool.schema.json +77 -0
  44. package/dist/schemas/agent-folder/trigger-md.schema.json +65 -0
  45. package/dist/utils/runtime-limits.d.ts +8 -0
  46. package/dist/utils/runtime-limits.js +19 -0
  47. package/package.json +14 -3
@@ -0,0 +1,1280 @@
1
+ import { AGENT_MANIFEST_V8_SCHEMA_VERSION, AgentManifestV8Schema, ENVIRONMENT_NAME_PATTERN, HarnessIdSchema, RuntimeSectionSchema, TOOL_SECRET_NAME_PATTERN, TriggerSchema, isAgentManifestName, } from "../contracts.js";
2
+ import { cronScheduleIssue, isTimeZone, timeZoneNames } from "../definition/cron.js";
3
+ import { DELEGATE_NAME_PATTERN } from "../definition/delegate.js";
4
+ import { sectionGapsAt } from "../definition/sections.js";
5
+ import { DEFAULT_HARNESS } from "../utils/harness-id.js";
6
+ import { SKILL_ENTRY, skillFilePathIssue } from "../utils/definition-files.js";
7
+ import { parseMarkdown } from "./frontmatter.js";
8
+ import { parseJson, pointerOf } from "./json.js";
9
+ import { jsonSchemaIssues } from "./json-schema.js";
10
+ import { naturalCompare, suggestion, suggestions } from "./suggest.js";
11
+ import { folderParts, nestedTextPaths, scopedSchema } from "./nested.js";
12
+ /** The compiler format this version builds: a folder with no `format`, or `format: 1`. */
13
+ export const AGENT_FOLDER_COMPILER = "agent-folder/1";
14
+ /**
15
+ * What a folder may hold, unless `compileAgentFolder` is given other limits (a Tenant's Runtime
16
+ * limits `folderFiles`, `folderBytes` and `folderTextFileBytes`, which default to these).
17
+ */
18
+ export const AGENT_FOLDER_LIMITS = Object.freeze({
19
+ /** Files in one folder. */
20
+ files: 2000,
21
+ /** Every file's bytes together. */
22
+ totalBytes: 50 * 1024 * 1024,
23
+ /** One Markdown or JSON file the compiler reads. */
24
+ textFileBytes: 1024 * 1024,
25
+ });
26
+ const AGENT_FILE = "AGENT.md";
27
+ const RUNTIME_FILE = "runtime.json";
28
+ const MCP_FILE = "mcp.json";
29
+ const OUTPUT_SCHEMA_FILE = "output.schema.json";
30
+ const WORKSPACE = "/workspace";
31
+ const AGENT_PLUGINS_MCP_SCHEMA = "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json";
32
+ /**
33
+ * The schemas a JSON file of a folder may name in `$schema`, by the kind of file: ours first,
34
+ * whose documents `schemas.ts` builds from the key lists below.
35
+ */
36
+ export const FOLDER_SCHEMAS = "https://docs.nylorun.com/schemas/agent-folder/v1/";
37
+ export const SCHEMA_URLS = {
38
+ runtime: [`${FOLDER_SCHEMAS}runtime.json`, "https://docs.nylorun.com/schemas/runtime-manifest/v1.json"],
39
+ tool: [`${FOLDER_SCHEMAS}tool.json`],
40
+ mcp: [`${FOLDER_SCHEMAS}mcp.json`, AGENT_PLUGINS_MCP_SCHEMA],
41
+ flow: [`${FOLDER_SCHEMAS}flow.json`],
42
+ };
43
+ const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
44
+ export const AGENT_KEYS = ["name", "description", "format", "harness", "inputSchema", "outputSchema", "mcpServers", "skills", "memory", "loop", "metadata"];
45
+ const SKILL_KEYS = ["name", "description", "license", "compatibility", "metadata", "allowed-tools"];
46
+ export const TRIGGER_KEYS = ["schedule", "timezone", "at", "webhook", "session"];
47
+ export const MCP_KEYS = ["$schema", "mcpServers"];
48
+ export const SERVER_KEYS = ["type", "url", "headers"];
49
+ export const SERVER_SETTING_KEYS = ["deferred", "tools"];
50
+ /** What `AGENT.md` may also set for a plugin's server, which cannot know the agent's slot names. */
51
+ export const PLUGIN_SERVER_SETTING_KEYS = [...SERVER_SETTING_KEYS, "credential"];
52
+ export const TOOL_KEYS = ["description", "inputSchema", "outputSchema", "http"];
53
+ /** The loop settings our harness reads from `loop`: none yet. A custom harness reads its own. */
54
+ const NYLORUN_LOOP_KEYS = [];
55
+ /** The runtime fields only a sandbox has, and the ones only a pod has. */
56
+ const SANDBOX_FIELDS = ["image", "resources", "storage", "network", "setup", "files"];
57
+ const POD_FIELDS = ["image", "storage", "setup", "files"];
58
+ /** Headers that authenticate, whose value is a secret. */
59
+ const SECRET_HEADER = /^(?:authorization|x-api-key|api-key|cookie|.+-token)$/i;
60
+ /** Strings shaped like a token, by what they look like. */
61
+ const TOKEN_SHAPES = [
62
+ [/\bghp_[A-Za-z0-9]{20,}/, "a GitHub token (ghp_…)"],
63
+ [/\bgithub_pat_[A-Za-z0-9_]{20,}/, "a GitHub token (github_pat_…)"],
64
+ [/\bsk-[A-Za-z0-9_-]{16,}/, "an API key (sk-…)"],
65
+ [/\bxox[abp]-[A-Za-z0-9-]{10,}/, "a Slack token (xox…-)"],
66
+ [/\beyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]+/, "a JSON Web Token (eyJ…)"],
67
+ ];
68
+ /** What every secret warning says about where the folder goes, and where secrets usually go. */
69
+ const KEPT_AS_SOURCE = "The folder is kept byte-exact as the version's source, readable by anyone with agents:read";
70
+ const APPROVAL_REMOVED = 'approval is not set in an agent folder: tool approvals are the Tenant\'s tool policy, decided at the Tool Gate for every agent. To have a person approve a call, add a rule with "effect": "ask" for the tool to the Tenant\'s tool policy (nylorun tenant tool-policy put <file>, or PUT /v1/tenant/tool-policy)';
71
+ const isEnvFile = (name) => name === ".env" || name.startsWith(".env.");
72
+ /**
73
+ * Why a path looks like it holds a secret: an environment file anywhere, or a key file outside
74
+ * `skills/` and `files/` (where a skill or the disk may need one). Undefined when it does not.
75
+ */
76
+ function secretFileOf(path) {
77
+ const segments = path.split("/");
78
+ const base = segments.at(-1);
79
+ if (isEnvFile(base))
80
+ return "An environment file usually holds secrets";
81
+ if ((base.endsWith(".pem") || base.endsWith(".key")) && segments[0] !== "skills" && segments[0] !== "files")
82
+ return "A key file is a secret";
83
+ return undefined;
84
+ }
85
+ /** Whether a root file looks like a tool policy, which is the Tenant's and not the folder's. */
86
+ const isPolicyFile = (path) => path === "tool-policy.json" || path === "policy.json" || /^[^/]+\.policy\.json$/.test(path);
87
+ /** What a path is, or why the folder may not hold it. */
88
+ function classify(path) {
89
+ const segments = path.split("/");
90
+ const base = segments.at(-1);
91
+ // A folder inside this one classifies its own paths (folder/nested.ts).
92
+ if ((segments[0] === "agents" || segments[0] === "plugins") && segments.length >= 3)
93
+ return { kind: segments[0] === "agents" ? "nested" : "plugin" };
94
+ if (segments.includes(".git") || segments.includes("node_modules"))
95
+ return { code: "path_refused", error: ".git/ and node_modules/ are not part of an agent folder: leave them out of the upload" };
96
+ const top = segments[0];
97
+ if (path === AGENT_FILE)
98
+ return { kind: "agent" };
99
+ if (path === RUNTIME_FILE)
100
+ return { kind: "runtime" };
101
+ if (path === MCP_FILE)
102
+ return { kind: "mcp" };
103
+ if (segments.length === 1) {
104
+ if (base.toLowerCase() === "agent.md")
105
+ return { code: "wrong_name", error: `The root file is named ${AGENT_FILE}, in capitals` };
106
+ const stem = base.replace(/\.(?:ya?ml|jsonc|json5)$/, "");
107
+ if (stem !== base && ["runtime", "mcp", "AGENT"].includes(stem))
108
+ return { code: "wrong_syntax", error: `Write this file as ${stem === "AGENT" ? AGENT_FILE : `${stem}.json`}: an agent folder has one syntax per kind of file` };
109
+ if (path === "flow.json")
110
+ return { kind: "flow" };
111
+ if (base.endsWith(".schema.json"))
112
+ return { kind: "schema" };
113
+ return { kind: "other" };
114
+ }
115
+ if (top === "agents" || top === "plugins")
116
+ return {
117
+ code: "reserved_directory",
118
+ error: top === "agents" ? "agents/ holds one folder per agent, each with its AGENT.md" : "plugins/ holds one folder per Agent Plugin, each with its plugin.json",
119
+ };
120
+ if (top === "instructions")
121
+ return segments.length === 2 && base.endsWith(".md")
122
+ ? { kind: "instructions" }
123
+ : { code: "reserved_directory", error: "instructions/ holds Markdown files only, with no folders" };
124
+ if (top === "tools")
125
+ return segments.length === 2 && base.endsWith(".json")
126
+ ? { kind: "tool" }
127
+ : { code: "reserved_directory", error: "tools/ holds one JSON file per HTTP tool, named <tool>.json" };
128
+ if (top === "triggers")
129
+ return segments.length === 2 && base.endsWith(".md")
130
+ ? { kind: "trigger" }
131
+ : { code: "reserved_directory", error: "triggers/ holds one Markdown file per trigger, named <id>.md" };
132
+ if (top === "skills")
133
+ return segments.length >= 3 ? { kind: "skill" } : { code: "reserved_directory", error: "skills/ holds one folder per skill, each with its SKILL.md" };
134
+ if (top === "files")
135
+ return { kind: "file" };
136
+ if (top === "schemas")
137
+ return base.endsWith(".json") ? { kind: "schema" } : { code: "reserved_directory", error: "schemas/ holds JSON Schema files (.json)" };
138
+ if (top === ".nylorun")
139
+ return { kind: "other" };
140
+ if (base.endsWith(".schema.json"))
141
+ return { kind: "schema" };
142
+ return { kind: "other" };
143
+ }
144
+ /** The files the compiler reads: the Runtime and the CLI pass their bytes in. */
145
+ export function folderTextPaths(entries) {
146
+ const paths = [];
147
+ for (const entry of entries) {
148
+ const kind = classify(entry.path);
149
+ if (!("kind" in kind))
150
+ continue;
151
+ const textual = kind.kind === "agent" ||
152
+ kind.kind === "instructions" ||
153
+ kind.kind === "runtime" ||
154
+ kind.kind === "mcp" ||
155
+ kind.kind === "tool" ||
156
+ kind.kind === "trigger" ||
157
+ kind.kind === "schema" ||
158
+ kind.kind === "flow" ||
159
+ (kind.kind === "skill" && entry.path.split("/").length === 3 && entry.path.endsWith(`/${SKILL_ENTRY}`));
160
+ if (textual)
161
+ paths.push(entry.path);
162
+ }
163
+ paths.push(...nestedTextPaths(entries, folderTextPaths));
164
+ return paths.sort(compare);
165
+ }
166
+ const compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
167
+ /** Why `path` cannot name a file in a folder, or undefined when it can. */
168
+ function pathIssue(path) {
169
+ if (path.length === 0 || path.length > 1024)
170
+ return "must be 1 to 1024 characters";
171
+ if (path.includes("\\"))
172
+ return "must use / as its separator, not \\";
173
+ if (path.startsWith("/"))
174
+ return "must be relative to the folder";
175
+ if (/[\u0000-\u001f\u007f]/.test(path))
176
+ return "must not contain control characters";
177
+ if (path !== path.normalize("NFC"))
178
+ return "must be in Unicode NFC";
179
+ for (const segment of path.split("/"))
180
+ if (segment === "" || segment === "." || segment === "..")
181
+ return "must not have empty, . or .. segments";
182
+ return undefined;
183
+ }
184
+ const unknownKeyMessage = (key, known) => {
185
+ const close = suggestion(key, known);
186
+ return `Unknown key '${key}'.${close ? ` Did you mean '${close}'?` : ` Known keys: ${known.join(", ")}.`}`;
187
+ };
188
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
189
+ const show = (value) => JSON.stringify(value) ?? String(value);
190
+ /**
191
+ * Compiles an agent folder into agent manifest v8, with every diagnostic. `scope` is internal: the
192
+ * compiler sets it when it compiles a folder inside another (`agents/<id>/`, a plugin's parts).
193
+ */
194
+ export function compileAgentFolder(input, scope) {
195
+ const limits = { ...AGENT_FOLDER_LIMITS, ...input.limits };
196
+ const diagnostics = [];
197
+ const parsed = new Map();
198
+ const report = (severity, code, message, file, path, options = {}) => {
199
+ let at = options.at;
200
+ if (!at && file && path) {
201
+ const found = locate(parsed.get(file), path);
202
+ at = options.key ? (found?.key ?? found?.value) : found?.value;
203
+ }
204
+ const fix = options.fix ?? (options.rename && file && path ? renameFix(parsed.get(file), path, options.rename) : undefined);
205
+ diagnostics.push({
206
+ severity,
207
+ code,
208
+ message,
209
+ ...(file === undefined ? {} : { file }),
210
+ ...(at === undefined ? {} : { line: at.line, column: at.column }),
211
+ ...(options.pointer === undefined ? {} : { pointer: options.pointer }),
212
+ ...(fix === undefined ? {} : { fix }),
213
+ });
214
+ };
215
+ const error = (code, message, file, path, options = {}) => report("error", code, message, file, path, options);
216
+ // --- The entries ------------------------------------------------------------------------
217
+ const entries = [...input.entries].sort((a, b) => compare(a.path, b.path));
218
+ const byPath = new Map();
219
+ const folded = new Map();
220
+ let bytes = 0;
221
+ for (const entry of entries) {
222
+ const issue = pathIssue(entry.path);
223
+ if (issue) {
224
+ error("path_invalid", `The path ${JSON.stringify(entry.path.slice(0, 200))} ${issue}`, entry.path);
225
+ continue;
226
+ }
227
+ if (byPath.has(entry.path)) {
228
+ error("path_duplicate", "The folder lists this path twice", entry.path);
229
+ continue;
230
+ }
231
+ const lower = entry.path.toLowerCase();
232
+ const other = folded.get(lower);
233
+ if (other !== undefined) {
234
+ error("path_case", `This path and ${other} differ only in case, which some file systems cannot hold`, entry.path);
235
+ continue;
236
+ }
237
+ if (!/^[0-9a-f]{64}$/.test(entry.sha256)) {
238
+ error("path_invalid", "The file's sha256 is not 64 lowercase hex digits", entry.path);
239
+ continue;
240
+ }
241
+ folded.set(lower, entry.path);
242
+ byPath.set(entry.path, entry);
243
+ bytes += entry.size;
244
+ }
245
+ if (entries.length > limits.files)
246
+ error("limit_exceeded", `An agent folder holds at most ${limits.files} files; this one holds ${entries.length}`);
247
+ if (bytes > limits.totalBytes)
248
+ error("limit_exceeded", `An agent folder holds at most ${limits.totalBytes} bytes; this one holds ${bytes}`);
249
+ const kinds = new Map();
250
+ for (const path of byPath.keys()) {
251
+ const kind = classify(path);
252
+ if ("kind" in kind)
253
+ kinds.set(path, kind.kind);
254
+ else
255
+ error(kind.code, kind.error, path);
256
+ }
257
+ for (const [path, kind] of kinds) {
258
+ const secret = secretFileOf(path);
259
+ if (secret)
260
+ report("warning", "secret_file", `${secret}. ${KEPT_AS_SOURCE}${kind === "file" ? ", and files/ is copied to the Agent's disk" : ""}. A secret usually goes in a \${NAME} slot (in runtime.json, or a header in mcp.json), with its value set in the Agent's vault: leave this file out of the upload`, path);
261
+ else if (kind === "other" && isPolicyFile(path))
262
+ report("warning", "tool_policy_file", "This looks like a tool policy, and it is only kept with the source: tool policy is the Tenant's, for every agent, set with nylorun tenant tool-policy put <file> (PUT /v1/tenant/tool-policy)", path);
263
+ else if (kind === "other")
264
+ report("note", "file_not_compiled", "Kept with the source; not part of the agent", path);
265
+ }
266
+ const decoder = new TextDecoder("utf-8", { fatal: true });
267
+ /** The files with CRLF line ends, noted once each. */
268
+ const crlf = new Set();
269
+ /** The text of a file the compiler reads, or undefined after reporting why it has none. */
270
+ const textOf = (path) => {
271
+ const entry = byPath.get(path);
272
+ if (!entry)
273
+ return undefined;
274
+ if (entry.size > limits.textFileBytes) {
275
+ error("limit_exceeded", `A Markdown or JSON file holds at most ${limits.textFileBytes} bytes; this one holds ${entry.size}`, path);
276
+ return undefined;
277
+ }
278
+ const bytesOf = input.files.get(path);
279
+ if (!bytesOf) {
280
+ error("file_missing", "The compiler was not given this file's bytes", path);
281
+ return undefined;
282
+ }
283
+ let text;
284
+ try {
285
+ text = decoder.decode(bytesOf).replace(/^/, "");
286
+ }
287
+ catch {
288
+ error("not_utf8", "The file is not UTF-8 text", path);
289
+ return undefined;
290
+ }
291
+ // Read as LF, so nothing else changes: noted, with the fix.
292
+ if (text.includes("\r\n") && !crlf.has(path)) {
293
+ crlf.add(path);
294
+ report("note", "crlf", "The file has CRLF line ends, read as LF. Fix: save it with LF line ends", path, undefined, { fix: { kind: "crlf", file: path } });
295
+ }
296
+ return text;
297
+ };
298
+ const readJson = (path) => {
299
+ const text = textOf(path);
300
+ if (text === undefined)
301
+ return undefined;
302
+ const result = parseJson(text);
303
+ if (!result.ok) {
304
+ error("json_invalid", result.message, path, undefined, { at: result.at });
305
+ return undefined;
306
+ }
307
+ parsed.set(path, { path, positions: result.positions });
308
+ if (!isObject(result.value)) {
309
+ error("json_invalid", "The file holds a JSON object", path, []);
310
+ return undefined;
311
+ }
312
+ return result.value;
313
+ };
314
+ const readMarkdown = (path) => {
315
+ const text = textOf(path);
316
+ if (text === undefined)
317
+ return undefined;
318
+ const result = parseMarkdown(text);
319
+ if (!result.ok) {
320
+ error("frontmatter_invalid", result.message, path, undefined, { at: result.at });
321
+ return undefined;
322
+ }
323
+ parsed.set(path, { path, positions: result.positions });
324
+ return result;
325
+ };
326
+ const warn = (code, message, file, path, options = {}) => report("warning", code, message, file, path, options);
327
+ const checkKeys = (file, value, known, path = []) => {
328
+ for (const key of Object.keys(value))
329
+ if (known.includes(key))
330
+ continue;
331
+ else if (key === "approval")
332
+ error("approval_removed", APPROVAL_REMOVED, file, [...path, key], { key: true });
333
+ else
334
+ error("unknown_key", unknownKeyMessage(key, known), file, [...path, key], { key: true, rename: known });
335
+ };
336
+ /**
337
+ * `$schema` in a JSON file: accepted, and left out of the manifest. One that names the schema
338
+ * of another kind of file, or a schema that is not ours, is a warning: the path gives the kind.
339
+ */
340
+ const checkSchemaUrl = (file, kind, value, path = ["$schema"]) => {
341
+ const urls = kind === "schema" ? [] : SCHEMA_URLS[kind];
342
+ if (typeof value === "string" && (urls.includes(value) || (kind === "schema" && /^https?:\/\/json-schema\.org\//.test(value))))
343
+ return;
344
+ const names = { runtime: "runtime.json", tool: "a tool file (tools/<name>.json)", mcp: "mcp.json", flow: "flow.json", schema: "a JSON Schema" };
345
+ const other = Object.keys(SCHEMA_URLS).find((name) => typeof value === "string" && SCHEMA_URLS[name].includes(value));
346
+ const expected = kind === "schema" ? "a JSON Schema dialect, such as https://json-schema.org/draft/2020-12/schema" : urls.join(" or ");
347
+ warn("schema_url", other
348
+ ? `$schema names the schema of ${names[other]}, and this is ${names[kind]}: is the file in the right place? It is read as ${names[kind]}`
349
+ : `$schema ${show(value)} is not ${expected}: an editor may check this file against the wrong schema. It is read as ${names[kind]} either way`, file, path);
350
+ };
351
+ /** The schema files already checked: one named twice is checked once. */
352
+ const checkedSchemas = new Set();
353
+ /** Checks `schema` as JSON Schema and as the engine reads it; `path` is where it sits in `file`. */
354
+ const checkSchema = (file, path, schema, manifestPath) => {
355
+ if (path.length === 0) {
356
+ if (checkedSchemas.has(file))
357
+ return;
358
+ checkedSchemas.add(file);
359
+ }
360
+ if (schema.$schema !== undefined)
361
+ checkSchemaUrl(file, "schema", schema.$schema, [...path, "$schema"]);
362
+ for (const issue of jsonSchemaIssues(schema))
363
+ report(issue.severity, issue.severity === "error" ? "json_schema_invalid" : "json_schema_keyword", issue.message, file, [...path, ...issue.path], {
364
+ ...(issue.key ? { key: true } : {}),
365
+ ...(issue.known ? { rename: issue.known } : {}),
366
+ ...(manifestPath ? { pointer: pointerOf([...manifestPath, ...issue.path]) } : {}),
367
+ });
368
+ };
369
+ /**
370
+ * A literal header value that looks secret: any value of an authentication header, or a
371
+ * token-shaped string in any header. A warning, never a refusal: the value is the author's
372
+ * choice, and the warning says where it ends up.
373
+ */
374
+ const checkHeaderSecret = (file, path, header, value) => {
375
+ const shaped = TOKEN_SHAPES.find(([pattern]) => pattern.test(value))?.[1];
376
+ if (!shaped && (!SECRET_HEADER.test(header) || value.trim() === ""))
377
+ return;
378
+ const slot = header.toLowerCase() === "authorization" ? '"Bearer ${NAME}"' : '"${NAME}"';
379
+ warn("secret_literal", `${header} holds ${shaped ? `what looks like ${shaped}` : "a literal value, not a ${NAME} slot"}. ${KEPT_AS_SOURCE}, and the value goes into the manifest as written. Fix: write ${slot} and set the value in the Agent's vault`, file, path);
380
+ };
381
+ /** A trigger's cron and time zone, as the Runtime reads them when it is saved. */
382
+ const checkSchedule = (file, path, trigger) => {
383
+ if (typeof trigger.schedule === "string") {
384
+ const issue = cronScheduleIssue(trigger.schedule);
385
+ if (issue)
386
+ error("schedule_invalid", issue, file, [...path, "schedule"]);
387
+ }
388
+ if (typeof trigger.timezone === "string" && trigger.timezone !== "" && !isTimeZone(trigger.timezone)) {
389
+ const close = suggestion(trigger.timezone, timeZoneNames());
390
+ error("timezone_invalid", `timezone ${show(trigger.timezone)} is not an IANA time zone, such as Asia/Kolkata or America/New_York.${close ? ` Did you mean '${close}'?` : ""} Without one, the schedule is in UTC`, file, [...path, "timezone"]);
391
+ }
392
+ };
393
+ /** A JSON Schema a field names by path (`./x.json` from the root, `/x.json`), or inline. */
394
+ const schemaAt = (file, field, value, manifestPath) => {
395
+ if (isObject(value)) {
396
+ checkSchema(file, field, value, manifestPath);
397
+ return value;
398
+ }
399
+ if (typeof value !== "string") {
400
+ error("schema_invalid", "A schema is a JSON Schema object, or a path to a JSON Schema file", file, field);
401
+ return undefined;
402
+ }
403
+ // `/x` in a folder inside another names a file of the uploaded folder (folder/nested.ts).
404
+ if (scope && value.startsWith("/"))
405
+ return scopedSchema(scope, value, (code, message) => error(code, message, file, field));
406
+ const target = value.startsWith("/") ? value.slice(1) : value.replace(/^\.\//, "");
407
+ if (target.split("/").some((segment) => segment === ".." || segment === "")) {
408
+ error("path_outside", `${value} leaves the folder: a path names a file inside it`, file, field);
409
+ return undefined;
410
+ }
411
+ if (!byPath.has(target)) {
412
+ error("schema_missing", `${value} is not a file in the folder`, file, field);
413
+ return undefined;
414
+ }
415
+ if (kinds.get(target) !== "schema") {
416
+ error("schema_invalid", `${value} is not a JSON Schema file: name it *.schema.json or keep it under schemas/`, file, field);
417
+ return undefined;
418
+ }
419
+ const schema = readJson(target);
420
+ if (schema)
421
+ checkSchema(target, [], schema, manifestPath);
422
+ return schema;
423
+ };
424
+ // --- AGENT.md ---------------------------------------------------------------------------
425
+ if (!byPath.has(AGENT_FILE))
426
+ error("agent_missing", `An agent folder has an ${AGENT_FILE} at its root, with name and description in its frontmatter`);
427
+ const agent = byPath.has(AGENT_FILE) ? readMarkdown(AGENT_FILE) : undefined;
428
+ const front = agent?.data ?? {};
429
+ let name;
430
+ let description;
431
+ const harness = {};
432
+ const instructions = [];
433
+ let metadata;
434
+ const origins = [];
435
+ if (agent) {
436
+ if (!agent.hasFrontmatter)
437
+ error("frontmatter_missing", `${AGENT_FILE} opens with frontmatter between --- lines, with name and description`, AGENT_FILE, undefined, { at: { line: 1, column: 1 } });
438
+ checkKeys(AGENT_FILE, front, AGENT_KEYS);
439
+ if (typeof front.name !== "string" || front.name === "")
440
+ error("name_missing", "name is required: the agent manifest's name", AGENT_FILE, front.name === undefined ? undefined : ["name"]);
441
+ else if (!isAgentManifestName(front.name))
442
+ error("name_invalid", "name is 1-64 letters, digits, '.', '_' and '-', starting with a letter or digit", AGENT_FILE, ["name"]);
443
+ else if (input.name !== undefined && front.name !== input.name)
444
+ error("name_mismatch", `name is ${front.name}, and the folder is saved as ${input.name}: they must match`, AGENT_FILE, ["name"]);
445
+ else
446
+ name = front.name;
447
+ if (typeof front.description !== "string" || front.description.trim() === "")
448
+ error("description_missing", "description is required: what the agent does, in a sentence", AGENT_FILE, front.description === undefined ? undefined : ["description"]);
449
+ else
450
+ description = front.description.trim();
451
+ if (front.format !== undefined && front.format !== 1)
452
+ error("format_unsupported", `format ${JSON.stringify(front.format)} is not supported: this compiler builds format 1 (${AGENT_FOLDER_COMPILER})`, AGENT_FILE, ["format"]);
453
+ if (front.harness !== undefined) {
454
+ if (HarnessIdSchema.safeParse(front.harness).success)
455
+ harness.id = front.harness;
456
+ else
457
+ error("harness_invalid", "harness is the id of the harness that runs the loop, such as nylorun", AGENT_FILE, ["harness"]);
458
+ }
459
+ if (front.outputSchema !== undefined) {
460
+ const schema = schemaAt(AGENT_FILE, ["outputSchema"], front.outputSchema, ["harness", "outputSchema"]);
461
+ if (schema)
462
+ harness.outputSchema = schema;
463
+ }
464
+ for (const key of ["memory", "loop"]) {
465
+ if (front[key] === undefined)
466
+ continue;
467
+ if (isObject(front[key]))
468
+ harness[key] = front[key];
469
+ else
470
+ error("value_invalid", `${key} is a map`, AGENT_FILE, [key]);
471
+ }
472
+ // loop is the harness's own settings, passed to it each turn. Ours reads the keys it knows,
473
+ // so another key does nothing there: likely a typo, or meant for a custom harness.
474
+ if (isObject(front.loop) && (front.harness === undefined || front.harness === DEFAULT_HARNESS))
475
+ for (const key of Object.keys(front.loop))
476
+ if (!NYLORUN_LOOP_KEYS.includes(key)) {
477
+ const close = suggestion(key, NYLORUN_LOOP_KEYS);
478
+ warn("loop_key", `Unknown loop setting '${key}'.${close ? ` Did you mean '${close}'?` : ""} loop holds the harness's own settings, and the ${DEFAULT_HARNESS} harness reads ${NYLORUN_LOOP_KEYS.length === 0 ? "none yet" : NYLORUN_LOOP_KEYS.join(", ")}, so it is ignored`, AGENT_FILE, ["loop", key], { key: true });
479
+ }
480
+ if (front.metadata !== undefined) {
481
+ if (isObject(front.metadata))
482
+ metadata = front.metadata;
483
+ else
484
+ error("value_invalid", "metadata is a map", AGENT_FILE, ["metadata"]);
485
+ }
486
+ const body = trimBlankLines(agent.body);
487
+ if (body !== "")
488
+ instructions.push(body);
489
+ origins.push([["harness", "instructions"], { file: AGENT_FILE, path: [] }]);
490
+ for (const key of ["memory", "loop", "outputSchema"])
491
+ origins.push([["harness", key], { file: AGENT_FILE, path: [key] }]);
492
+ origins.push([["harness", "id"], { file: AGENT_FILE, path: ["harness"] }]);
493
+ }
494
+ // instructions/ in natural order: 2-style.md before 10-voice.md.
495
+ for (const path of [...kinds].filter(([, kind]) => kind === "instructions").map(([path]) => path).sort(naturalCompare)) {
496
+ const text = textOf(path);
497
+ if (text === undefined)
498
+ continue;
499
+ const trimmed = trimBlankLines(text);
500
+ if (trimmed !== "")
501
+ instructions.push(trimmed);
502
+ }
503
+ if (instructions.length > 0)
504
+ harness.instructions = instructions;
505
+ // A flow has no instructions of its own: its stages do.
506
+ else if (agent?.hasFrontmatter && ![...kinds.values()].includes("flow"))
507
+ warn("instructions_empty", `The agent has no instructions: ${AGENT_FILE}'s body is empty and instructions/ holds none, so the model gets the harness's own instructions only. Write them below the frontmatter`, AGENT_FILE, undefined, { at: { line: agent.bodyLine, column: 1 } });
508
+ // --- runtime.json ----------------------------------------------------------------------
509
+ let runtime;
510
+ if (byPath.has(RUNTIME_FILE)) {
511
+ const value = readJson(RUNTIME_FILE);
512
+ if (value) {
513
+ if ("$schema" in value)
514
+ checkSchemaUrl(RUNTIME_FILE, "runtime", value.$schema);
515
+ if ("extends" in value)
516
+ error("not_supported", "resolve extends before uploading: nylorun apply and packFolder send runtime.json merged with the file it names", RUNTIME_FILE, ["extends"], { key: true });
517
+ const { $schema: _, extends: __, ...rest } = value;
518
+ runtime = rest;
519
+ origins.push([["runtime"], { file: RUNTIME_FILE, path: [] }]);
520
+ if (isObject(rest.triggers))
521
+ for (const [id, trigger] of Object.entries(rest.triggers))
522
+ if (isObject(trigger))
523
+ checkSchedule(RUNTIME_FILE, ["triggers", id], trigger);
524
+ }
525
+ }
526
+ const derivedSlots = new Map();
527
+ /**
528
+ * A slot for `credential`, derived when runtime.json does not declare it. `at` places it in a
529
+ * file of a folder inside this one; in such a folder, the slot is the uploaded folder's.
530
+ */
531
+ const deriveSlot = (credential, type, url, file, path, header, at) => {
532
+ if (scope)
533
+ return scope.deriveSlot(credential, type, url, file, at ?? locate(parsed.get(file), path)?.value, header);
534
+ const declared = isObject(runtime?.secrets) ? runtime.secrets[credential] : undefined;
535
+ if (declared !== undefined)
536
+ return;
537
+ const existing = derivedSlots.get(credential);
538
+ if (existing) {
539
+ if (existing.url !== url || existing.slot.type !== type) {
540
+ const first = existing.at ?? locate(parsed.get(existing.file), existing.path)?.value;
541
+ error("credential_urls", `${credential} is the credential of ${existing.url} (${existing.file}${first ? `:${first.line}` : ""}) and of ${url}: a slot is bound to one URL, so give each URL its own slot`, file, path, { at });
542
+ }
543
+ return;
544
+ }
545
+ const slot = {
546
+ type,
547
+ url,
548
+ required: true,
549
+ ...(header ? { description: `Sets the ${header} header` } : {}),
550
+ };
551
+ derivedSlots.set(credential, { slot, file, path, url, ...(at === undefined ? {} : { at }) });
552
+ report("info", "slot_derived", `A ${type} slot ${credential} is derived for ${url}`, file, path, { pointer: pointerOf(["runtime", "secrets", credential]), at });
553
+ };
554
+ // agents/, flow.json and plugins/ (folder/nested.ts): hooked in below.
555
+ const parts = folderParts({
556
+ scope,
557
+ entries: byPath,
558
+ files: input.files,
559
+ kinds,
560
+ front,
561
+ agent,
562
+ harness,
563
+ origins,
564
+ diagnostics,
565
+ report,
566
+ readJson,
567
+ schemaAt,
568
+ checkSchemaUrl,
569
+ deriveSlot,
570
+ suggest: suggestion,
571
+ compile: compileAgentFolder,
572
+ folderTextPaths,
573
+ });
574
+ // --- mcp.json --------------------------------------------------------------------------
575
+ const servers = {};
576
+ let mcpRead = false;
577
+ if (byPath.has(MCP_FILE)) {
578
+ const value = readJson(MCP_FILE);
579
+ if (value) {
580
+ mcpRead = true;
581
+ checkKeys(MCP_FILE, value, MCP_KEYS);
582
+ if (value.$schema !== undefined)
583
+ checkSchemaUrl(MCP_FILE, "mcp", value.$schema);
584
+ const listed = value.mcpServers;
585
+ if (!isObject(listed))
586
+ error("mcp_invalid", "mcp.json holds mcpServers: a map of server names to servers", MCP_FILE, listed === undefined ? [] : ["mcpServers"]);
587
+ else
588
+ for (const [key, server] of Object.entries(listed)) {
589
+ const at = ["mcpServers", key];
590
+ if (!DELEGATE_NAME_PATTERN.test(key)) {
591
+ error("mcp_invalid", `MCP server name '${key}' may use only letters, digits, _ and -, up to 64 characters`, MCP_FILE, at, { key: true });
592
+ continue;
593
+ }
594
+ if (!isObject(server)) {
595
+ error("mcp_invalid", "An MCP server is a map with type, url and headers", MCP_FILE, at);
596
+ continue;
597
+ }
598
+ checkKeys(MCP_FILE, server, SERVER_KEYS, at);
599
+ const type = server.type;
600
+ if (type === undefined) {
601
+ error("mcp_type", "type is required: streamable-http or sse (a server with no type is a stdio server, and the Runtime runs remote MCP servers only)", MCP_FILE, at, { key: true });
602
+ continue;
603
+ }
604
+ if (type === "http") {
605
+ error("mcp_type", 'type "http" is Claude Code\'s name; Agent Plugins writes "streamable-http". Fix: change it to "streamable-http"', MCP_FILE, [...at, "type"]);
606
+ continue;
607
+ }
608
+ if (type === "stdio" || type === "ws") {
609
+ error("mcp_type", `type ${type} is not served: the Runtime runs remote MCP servers only (streamable-http or sse)`, MCP_FILE, [...at, "type"]);
610
+ continue;
611
+ }
612
+ if (type !== "streamable-http" && type !== "sse") {
613
+ error("mcp_type", "type is streamable-http or sse", MCP_FILE, [...at, "type"]);
614
+ continue;
615
+ }
616
+ if (typeof server.url !== "string" || server.url === "") {
617
+ error("mcp_invalid", "url is required: the server's own URL", MCP_FILE, server.url === undefined ? at : [...at, "url"]);
618
+ continue;
619
+ }
620
+ if (server.url.includes("${")) {
621
+ error("credential_placement", "${…} names a credential in a header only: a URL is not secret", MCP_FILE, [...at, "url"]);
622
+ continue;
623
+ }
624
+ const headers = {};
625
+ let credential;
626
+ let headersValid = true;
627
+ if (server.headers !== undefined && !isObject(server.headers)) {
628
+ error("mcp_invalid", "headers is a map of header names to strings", MCP_FILE, [...at, "headers"]);
629
+ headersValid = false;
630
+ }
631
+ for (const [header, raw] of Object.entries(isObject(server.headers) ? server.headers : {})) {
632
+ const path = [...at, "headers", header];
633
+ if (typeof raw !== "string") {
634
+ error("mcp_invalid", "A header's value is a string", MCP_FILE, path);
635
+ headersValid = false;
636
+ continue;
637
+ }
638
+ if (!raw.includes("${")) {
639
+ checkHeaderSecret(MCP_FILE, path, header, raw);
640
+ headers[header] = raw;
641
+ continue;
642
+ }
643
+ const placeholder = /^(Bearer )?\$\{([^}]*)\}$/.exec(raw);
644
+ const named = placeholder?.[2];
645
+ if (!placeholder || named === undefined || raw.indexOf("${") !== raw.lastIndexOf("${")) {
646
+ error("credential_placement", "A header names a credential as its whole value, ${NAME}, or as Bearer ${NAME}", MCP_FILE, path);
647
+ headersValid = false;
648
+ continue;
649
+ }
650
+ if (named.includes(":-") || named.includes(":")) {
651
+ error("credential_default", `\${${named}} has a default: a secret has none, and its value goes to the Agent's vault`, MCP_FILE, path);
652
+ headersValid = false;
653
+ continue;
654
+ }
655
+ if (!TOOL_SECRET_NAME_PATTERN.test(named)) {
656
+ error("credential_name", "A credential's name is 1-64 letters, digits, '.', '_' and '-'", MCP_FILE, path);
657
+ headersValid = false;
658
+ continue;
659
+ }
660
+ if (credential) {
661
+ error("credential_twice", `This server already names ${credential.name} in ${credential.header}: a server authenticates with one credential, in one header`, MCP_FILE, path);
662
+ headersValid = false;
663
+ continue;
664
+ }
665
+ const bearer = placeholder[1] !== undefined;
666
+ if (bearer && header.toLowerCase() !== "authorization") {
667
+ error("credential_placement", "Bearer ${NAME} goes in the Authorization header; another header takes ${NAME} alone", MCP_FILE, path);
668
+ headersValid = false;
669
+ continue;
670
+ }
671
+ credential = { name: named, header, type: bearer ? "bearer" : "headers", path };
672
+ }
673
+ if (!headersValid)
674
+ continue;
675
+ if (credential)
676
+ deriveSlot(credential.name, credential.type, server.url, MCP_FILE, credential.path, credential.type === "headers" ? credential.header : undefined);
677
+ servers[key] = {
678
+ name: key,
679
+ type,
680
+ url: server.url,
681
+ ...(Object.keys(headers).length === 0 ? {} : { headers }),
682
+ ...(credential ? { credential: credential.name } : {}),
683
+ };
684
+ origins.push([["harness", "mcpServers", key], { file: MCP_FILE, path: at }]);
685
+ if (credential)
686
+ origins.push([["harness", "mcpServers", key, "credential"], { file: MCP_FILE, path: credential.path }]);
687
+ }
688
+ }
689
+ }
690
+ parts.mergeServers(servers);
691
+ if (front.mcpServers !== undefined) {
692
+ if (!isObject(front.mcpServers))
693
+ error("value_invalid", "mcpServers is a map of server names to this agent's settings", AGENT_FILE, ["mcpServers"]);
694
+ else
695
+ for (const [key, settings] of Object.entries(front.mcpServers)) {
696
+ const at = ["mcpServers", key];
697
+ if (!servers[key]) {
698
+ if (byPath.has(MCP_FILE) && !mcpRead)
699
+ continue;
700
+ const close = suggestion(key, Object.keys(servers));
701
+ error("server_unknown", `No MCP server ${key} is declared in mcp.json.${close ? ` Did you mean '${close}'?` : ""}`, AGENT_FILE, at, { key: true });
702
+ continue;
703
+ }
704
+ if (!isObject(settings)) {
705
+ error("value_invalid", "A server's settings are a map: deferred and tools", AGENT_FILE, at);
706
+ continue;
707
+ }
708
+ // A plugin's server takes its credential here (folder/plugins.ts).
709
+ const fromPlugin = parts.serverCredential(servers, key, settings, at);
710
+ checkKeys(AGENT_FILE, settings, fromPlugin ? PLUGIN_SERVER_SETTING_KEYS : SERVER_SETTING_KEYS, at);
711
+ if ("credential" in settings && !fromPlugin)
712
+ continue;
713
+ // A tool's settings pass to the manifest as they are, so approval is refused here.
714
+ if (isObject(settings.tools))
715
+ for (const [tool, toolSettings] of Object.entries(settings.tools))
716
+ if (isObject(toolSettings) && "approval" in toolSettings)
717
+ error("approval_removed", APPROVAL_REMOVED, AGENT_FILE, [...at, "tools", tool, "approval"], { key: true });
718
+ for (const setting of SERVER_SETTING_KEYS)
719
+ if (settings[setting] !== undefined) {
720
+ servers[key][setting] = settings[setting];
721
+ origins.push([["harness", "mcpServers", key, setting], { file: AGENT_FILE, path: [...at, setting] }]);
722
+ }
723
+ }
724
+ }
725
+ if (Object.keys(servers).length > 0)
726
+ harness.mcpServers = servers;
727
+ // --- skills/ ---------------------------------------------------------------------------
728
+ /**
729
+ * The fix-it for a `SKILL.md`'s `secrets`: moved to `AGENT.md`'s skills block, as `migrate
730
+ * folder` writes it. Only the root agent's skills get secrets, and only a list of slot names
731
+ * moves, into an `AGENT.md` with frontmatter that lists none for the skill, or lists them all.
732
+ */
733
+ const movedSecrets = (file, skill, secrets) => {
734
+ if (scope || !agent?.hasFrontmatter)
735
+ return {};
736
+ if (!Array.isArray(secrets) || !secrets.every((item) => typeof item === "string" && ENVIRONMENT_NAME_PATTERN.test(item)))
737
+ return {};
738
+ if (front.skills !== undefined && !isObject(front.skills))
739
+ return {};
740
+ const settings = isObject(front.skills) ? front.skills[skill] : undefined;
741
+ if (settings !== undefined && !isObject(settings))
742
+ return {};
743
+ const listed = settings?.secrets;
744
+ if (listed !== undefined && !(Array.isArray(listed) && secrets.every((item) => listed.includes(item))))
745
+ return {};
746
+ return { fix: { kind: "move_skill_secrets", file, skill, secrets: [...new Set(secrets)] } };
747
+ };
748
+ const skills = {};
749
+ const skillFolders = new Map();
750
+ for (const [path, kind] of kinds)
751
+ if (kind === "skill") {
752
+ const folder = path.split("/")[1];
753
+ skillFolders.set(folder, [...(skillFolders.get(folder) ?? []), path]);
754
+ }
755
+ for (const [folder, paths] of skillFolders) {
756
+ const entryPath = `skills/${folder}/${SKILL_ENTRY}`;
757
+ if (!byPath.has(entryPath)) {
758
+ error("skill_invalid", `skills/${folder}/ has no ${SKILL_ENTRY}`, `skills/${folder}/${SKILL_ENTRY}`);
759
+ continue;
760
+ }
761
+ const markdown = readMarkdown(entryPath);
762
+ if (!markdown)
763
+ continue;
764
+ const data = markdown.data;
765
+ let valid = true;
766
+ for (const key of Object.keys(data)) {
767
+ if (key === "secrets") {
768
+ error("skill_secrets", `secrets is not an Agent Skills key: which secrets a skill gets is the agent's choice. Fix: move it to ${AGENT_FILE}'s skills block, as skills: { ${folder}: { secrets: [...] } }`, entryPath, ["secrets"], { key: true, ...movedSecrets(entryPath, folder, data.secrets) });
769
+ valid = false;
770
+ }
771
+ else if (!SKILL_KEYS.includes(key)) {
772
+ error("unknown_key", unknownKeyMessage(key, SKILL_KEYS), entryPath, [key], { key: true, rename: SKILL_KEYS });
773
+ valid = false;
774
+ }
775
+ }
776
+ const skillName = typeof data.name === "string" ? data.name.trim() : "";
777
+ const skillDescription = typeof data.description === "string" ? data.description.trim() : "";
778
+ if (!SKILL_NAME.test(skillName) || skillName.length > 64) {
779
+ error("skill_invalid", "name is required: 1-64 lowercase letters, digits and single hyphens", entryPath, data.name === undefined ? undefined : ["name"]);
780
+ valid = false;
781
+ }
782
+ else if (skillName !== folder) {
783
+ error("skill_invalid", `name is ${skillName}, and the skill's folder is ${folder}: they must match`, entryPath, ["name"]);
784
+ valid = false;
785
+ }
786
+ if (skillDescription === "" || skillDescription.length > 1024) {
787
+ error("skill_invalid", "description is required, at most 1024 characters", entryPath, data.description === undefined ? undefined : ["description"]);
788
+ valid = false;
789
+ }
790
+ const files = {};
791
+ for (const path of paths.sort(compare)) {
792
+ const relative = path.slice(`skills/${folder}/`.length);
793
+ const issue = skillFilePathIssue(relative);
794
+ if (issue) {
795
+ error("path_invalid", `A skill's file path ${issue}`, path);
796
+ valid = false;
797
+ continue;
798
+ }
799
+ files[relative] = `sha256:${byPath.get(path).sha256}`;
800
+ }
801
+ if (!valid)
802
+ continue;
803
+ skills[skillName] = { name: skillName, description: skillDescription, files };
804
+ origins.push([["harness", "skills", skillName], { file: entryPath, path: [] }]);
805
+ }
806
+ parts.mergeSkills(skills);
807
+ if (front.skills !== undefined) {
808
+ if (!isObject(front.skills))
809
+ error("value_invalid", "skills is a map of skill names to this agent's settings for them", AGENT_FILE, ["skills"]);
810
+ else
811
+ for (const [key, settings] of Object.entries(front.skills)) {
812
+ const at = ["skills", key];
813
+ if (!skills[key]) {
814
+ if (skillFolders.has(key))
815
+ continue;
816
+ const close = suggestion(key, [...skillFolders.keys()]);
817
+ error("skill_unknown", `No skill ${key} is in skills/.${close ? ` Did you mean '${close}'?` : ""}`, AGENT_FILE, at, { key: true });
818
+ continue;
819
+ }
820
+ if (!isObject(settings)) {
821
+ error("value_invalid", "A skill's settings are a map: secrets", AGENT_FILE, at);
822
+ continue;
823
+ }
824
+ checkKeys(AGENT_FILE, settings, ["secrets"], at);
825
+ const secrets = settings.secrets;
826
+ if (secrets === undefined)
827
+ continue;
828
+ if (!Array.isArray(secrets) || !secrets.every((item) => typeof item === "string" && ENVIRONMENT_NAME_PATTERN.test(item))) {
829
+ error("value_invalid", "secrets is a list of secret slot names, each an environment variable name", AGENT_FILE, [...at, "secrets"]);
830
+ continue;
831
+ }
832
+ if (secrets.length > 0)
833
+ skills[key].secrets = [...new Set(secrets)].sort();
834
+ origins.push([["harness", "skills", key, "secrets"], { file: AGENT_FILE, path: [...at, "secrets"] }]);
835
+ }
836
+ }
837
+ if (Object.keys(skills).length > 0)
838
+ harness.skills = skills;
839
+ // --- tools/ ----------------------------------------------------------------------------
840
+ const tools = [];
841
+ for (const path of [...kinds].filter(([, kind]) => kind === "tool").map(([path]) => path)) {
842
+ const toolName = path.slice("tools/".length, -".json".length);
843
+ if (!DELEGATE_NAME_PATTERN.test(toolName)) {
844
+ error("tool_invalid", `A tool's name comes from its file name: '${toolName}' may use only letters, digits, _ and -, up to 64 characters`, path);
845
+ continue;
846
+ }
847
+ const value = readJson(path);
848
+ if (!value)
849
+ continue;
850
+ if ("name" in value) {
851
+ error("tool_invalid", "A tool file takes no name: its file name is the tool's name", path, ["name"], { key: true });
852
+ continue;
853
+ }
854
+ if ("agent" in value) {
855
+ error("tool_invalid", `A tool file declares an HTTP tool: an agent used as a tool is a folder, agents/${toolName}/, with its AGENT.md`, path, ["agent"], { key: true });
856
+ continue;
857
+ }
858
+ if ("$schema" in value)
859
+ checkSchemaUrl(path, "tool", value.$schema);
860
+ checkKeys(path, value, [...TOOL_KEYS, "$schema"]);
861
+ if (!isObject(value.http)) {
862
+ error("tool_invalid", "A tool file declares an HTTP tool: http with its url", path, value.http === undefined ? [] : ["http"]);
863
+ continue;
864
+ }
865
+ const tool = { name: toolName };
866
+ const at = ["harness", "tools", tools.length];
867
+ if (value.description !== undefined)
868
+ tool.description = value.description;
869
+ const input = value.inputSchema === undefined ? undefined : schemaAt(path, ["inputSchema"], value.inputSchema, [...at, "inputSchema"]);
870
+ if (value.inputSchema === undefined)
871
+ error("tool_invalid", "inputSchema is required: the JSON Schema of the tool's input", path, []);
872
+ if (input)
873
+ tool.inputSchema = input;
874
+ if (value.outputSchema !== undefined) {
875
+ const output = schemaAt(path, ["outputSchema"], value.outputSchema, [...at, "outputSchema"]);
876
+ if (output)
877
+ tool.outputSchema = output;
878
+ }
879
+ tool.http = value.http;
880
+ const credential = value.http.credential;
881
+ if (typeof credential === "string" && typeof value.http.url === "string")
882
+ deriveSlot(credential, "bearer", value.http.url, path, ["http", "credential"]);
883
+ origins.push([["harness", "tools", tools.length], { file: path, path: [] }]);
884
+ tools.push(tool);
885
+ }
886
+ if (tools.length > 0)
887
+ harness.tools = tools;
888
+ // --- triggers/ -------------------------------------------------------------------------
889
+ const triggers = {};
890
+ /** Where each trigger's body (its prompt) starts. */
891
+ const bodyLines = new Map();
892
+ for (const path of [...kinds].filter(([, kind]) => kind === "trigger").map(([path]) => path)) {
893
+ const id = path.slice("triggers/".length, -".md".length);
894
+ const markdown = readMarkdown(path);
895
+ if (!markdown)
896
+ continue;
897
+ if (!markdown.hasFrontmatter) {
898
+ error("frontmatter_missing", "A trigger opens with frontmatter: schedule, at or webhook, and session", path, undefined, { at: { line: 1, column: 1 } });
899
+ continue;
900
+ }
901
+ checkKeys(path, markdown.data, TRIGGER_KEYS);
902
+ checkSchedule(path, [], markdown.data);
903
+ bodyLines.set(path, markdown.bodyLine);
904
+ const trigger = { ...markdown.data, prompt: trimBlankLines(markdown.body) };
905
+ if (isObject(runtime?.triggers) && id in runtime.triggers) {
906
+ error("trigger_twice", `Trigger ${id} is declared in runtime.json and in ${path}: keep one`, path);
907
+ continue;
908
+ }
909
+ triggers[id] = trigger;
910
+ origins.push([["runtime", "triggers", id], { file: path, path: [] }]);
911
+ }
912
+ // --- files/ ----------------------------------------------------------------------------
913
+ const seeded = {};
914
+ for (const [path, kind] of kinds)
915
+ if (kind === "file")
916
+ seeded[path.slice("files/".length)] = `sha256:${byPath.get(path).sha256}`;
917
+ // --- agents/, flow.json and plugins/ (folder/nested.ts) ----------------------------------
918
+ if (!parts.compose())
919
+ return finish(diagnostics);
920
+ // --- The runtime section -----------------------------------------------------------------
921
+ const needsRuntime = derivedSlots.size > 0 || Object.keys(triggers).length > 0 || Object.keys(seeded).length > 0;
922
+ if (!runtime && needsRuntime)
923
+ runtime = { kind: "none" };
924
+ if (runtime) {
925
+ if (derivedSlots.size > 0) {
926
+ const declared = isObject(runtime.secrets) ? runtime.secrets : {};
927
+ runtime.secrets = { ...declared, ...Object.fromEntries([...derivedSlots].map(([key, { slot }]) => [key, slot])) };
928
+ for (const [key, derived] of derivedSlots)
929
+ origins.push([["runtime", "secrets", key], { file: derived.file, path: derived.path }]);
930
+ }
931
+ if (Object.keys(triggers).length > 0)
932
+ runtime.triggers = { ...(isObject(runtime.triggers) ? runtime.triggers : {}), ...triggers };
933
+ if (Object.keys(seeded).length > 0) {
934
+ runtime.files = [...(Array.isArray(runtime.files) ? runtime.files : []), { path: WORKSPACE, files: seeded }];
935
+ origins.push([["runtime", "files"], { file: byPath.has(RUNTIME_FILE) ? RUNTIME_FILE : "files/", path: ["files"] }]);
936
+ }
937
+ }
938
+ // --- Every field checked as the Runtime checks the manifest ------------------------------
939
+ if (diagnostics.some((item) => item.severity === "error") || name === undefined || description === undefined)
940
+ return finish(diagnostics);
941
+ const document = {
942
+ manifestSchemaVersion: AGENT_MANIFEST_V8_SCHEMA_VERSION,
943
+ name,
944
+ description,
945
+ ...(metadata === undefined ? {} : { metadata }),
946
+ harness,
947
+ ...(runtime === undefined ? {} : { runtime }),
948
+ };
949
+ origins.push([["name"], { file: AGENT_FILE, path: ["name"] }], [["description"], { file: AGENT_FILE, path: ["description"] }], [["metadata"], { file: AGENT_FILE, path: ["metadata"] }]);
950
+ /** The file and field a manifest path came from, by the longest recorded origin. */
951
+ const fromOrigins = (path) => {
952
+ const origin = originOf(origins, path);
953
+ return origin ? { file: origin.file, path: [...origin.origin.path, ...path.slice(origin.prefix)] } : undefined;
954
+ };
955
+ // Triggers from triggers/ are checked against their own schema first, with the file's lines.
956
+ for (const [id, trigger] of Object.entries(triggers)) {
957
+ const file = `triggers/${id}.md`;
958
+ const result = TriggerSchema.safeParse(trigger);
959
+ if (result.success)
960
+ continue;
961
+ for (const issue of result.error.issues) {
962
+ // The prompt is the file's body, which has no key to point at.
963
+ if (issue.path[0] === "prompt")
964
+ error("prompt_empty", "The trigger's body is its prompt, and it is empty: write what the agent is asked each time the trigger fires", file, undefined, { at: { line: bodyLines.get(file) ?? 1, column: 1 }, pointer: pointerOf(["runtime", "triggers", id, "prompt"]) });
965
+ else
966
+ place(issue, ["runtime", "triggers", id], (path) => ({ file, path: path.slice(3) }));
967
+ }
968
+ }
969
+ const checked = AgentManifestV8Schema.safeParse(document);
970
+ if (!checked.success) {
971
+ for (const issue of checked.error.issues) {
972
+ if (issue.path[0] === "runtime" && issue.path[1] === "triggers" && typeof issue.path[2] === "string" && issue.path[2] in triggers)
973
+ continue;
974
+ place(issue, [], fromOrigins);
975
+ }
976
+ return finish(diagnostics);
977
+ }
978
+ if (diagnostics.some((item) => item.severity === "error"))
979
+ return finish(diagnostics);
980
+ const manifest = checked.data;
981
+ // --- What the Runtime checks at save, where it needs no Tenant ---------------------------
982
+ const hasRuntimeFile = byPath.has(RUNTIME_FILE);
983
+ // The harness and runtime sections against each other, at the field that asks. A nested
984
+ // folder has no runtime section of its own: the root checks the whole manifest it embeds.
985
+ for (const gap of scope ? [] : sectionGapsAt(manifest)) {
986
+ let at = fromOrigins(gap.path);
987
+ let fix = "";
988
+ if (gap.path[1] === "id")
989
+ fix = gap.message.includes("runtime.image")
990
+ ? ': add "image" to runtime.json'
991
+ : `: ${hasRuntimeFile ? 'set "kind": "pod" and the harness\'s "image" in runtime.json' : 'add runtime.json with "kind": "pod" and the harness\'s "image"'}, or leave harness out to run ${DEFAULT_HARNESS}`;
992
+ else if (gap.path[1] === "skills" && gap.path.length === 2) {
993
+ // What to change is the runtime's kind; with no runtime.json, the skill asks for it.
994
+ const skill = [...kinds].find(([, kind]) => kind === "skill")?.[0];
995
+ at = hasRuntimeFile ? { file: RUNTIME_FILE, path: ["kind"] } : skill ? { file: `skills/${skill.split("/")[1]}/${SKILL_ENTRY}`, path: [] } : at;
996
+ fix = hasRuntimeFile ? ': set "kind" to "virtual" or "pod" in runtime.json' : ': add runtime.json with "kind": "virtual" (or "pod")';
997
+ }
998
+ error("manifest_inconsistent", `${gap.message}${fix ? `. Fix${fix}` : ""}`, at?.file, at?.path, { pointer: pointerOf(gap.path) });
999
+ }
1000
+ // The runtime's kind against what the folder asks of it: a sandbox, or a pod's disk.
1001
+ const section = manifest.runtime;
1002
+ if (section && section.kind !== "pod")
1003
+ for (const field of section.kind === "none" ? SANDBOX_FIELDS : POD_FIELDS) {
1004
+ const value = section[field];
1005
+ if (value === undefined || (Array.isArray(value) && value.length === 0 && section.kind !== "none"))
1006
+ continue;
1007
+ const seededFrom = field === "files" ? [...kinds].find(([, kind]) => kind === "file")?.[0] : undefined;
1008
+ if (seededFrom) {
1009
+ error("runtime_kind", `files/ is copied to the Agent's disk under ${WORKSPACE} when a pod's disk is made or reset, and the runtime's kind is ${show(section.kind)}${hasRuntimeFile ? "" : " (the folder has no runtime.json)"}. Fix: ${hasRuntimeFile ? 'set "kind": "pod" in runtime.json' : 'add runtime.json with "kind": "pod"'}`, seededFrom, undefined, { pointer: "/runtime/files" });
1010
+ continue;
1011
+ }
1012
+ error("runtime_kind", section.kind === "none"
1013
+ ? `${field} is for an Agent with a sandbox: kind "none" has none. Fix: set "kind" to "virtual" or "pod"`
1014
+ : `${field} ${POD_ONLY[field]}`, RUNTIME_FILE, [field], { key: true, pointer: pointerOf(["runtime", field]) });
1015
+ }
1016
+ if (diagnostics.some((item) => item.severity === "error"))
1017
+ return finish(diagnostics);
1018
+ return finish(diagnostics, manifest);
1019
+ /** A schema issue in the compiler's words, at the file and field that wrote it. */
1020
+ function place(issue, base, where) {
1021
+ const full = [...base, ...issue.path];
1022
+ // A value that fits none of a union's forms: the issues of the form it comes closest to.
1023
+ if (issue.code === "invalid_union") {
1024
+ const closest = [...issue.errors].sort((a, b) => a.length - b.length)[0];
1025
+ if (closest && closest.length > 0) {
1026
+ for (const inner of closest)
1027
+ place(inner, full, where);
1028
+ return;
1029
+ }
1030
+ }
1031
+ const at = where(full);
1032
+ const value = valueAt(document, full);
1033
+ // A missing field whose name a typo'd key is close to: the unknown key's error names it.
1034
+ const parent = valueAt(document, full.slice(0, -1));
1035
+ const last = String(full.at(-1));
1036
+ if (value === undefined && isObject(parent) && Object.keys(parent).some((key) => key !== last && suggestion(key, [last]) === last))
1037
+ return;
1038
+ if (issue.code === "invalid_union" && issue.errors.length === 0) {
1039
+ // A discriminated union's tag fits none of its forms: name the tags it takes.
1040
+ const tags = discriminatorValues(full);
1041
+ if (tags.length > 0) {
1042
+ error("schema_invalid", issueMessage({ ...issue, code: "invalid_value", values: tags }, (at ? at.path : full).map(String).join("."), value), at?.file, at?.path, {
1043
+ pointer: pointerOf(full),
1044
+ });
1045
+ return;
1046
+ }
1047
+ }
1048
+ if (issue.code === "unrecognized_keys") {
1049
+ const known = knownKeys(full);
1050
+ for (const key of issue.keys)
1051
+ error("unknown_key", known.length ? unknownKeyMessage(key, known) : `Unknown key '${key}'`, at?.file, at ? [...at.path, key] : undefined, {
1052
+ key: true,
1053
+ rename: known,
1054
+ pointer: pointerOf([...full, key]),
1055
+ });
1056
+ return;
1057
+ }
1058
+ // The field as the file names it, or as the manifest does when no file holds it.
1059
+ const field = (at ? at.path : full).map(String).join(".");
1060
+ error("schema_invalid", issueMessage(issue, field, value), at?.file, at?.path, { pointer: pointerOf(full) });
1061
+ }
1062
+ }
1063
+ /** The tags a discriminated union at `path` of the manifest takes, such as a slot's `type`s. */
1064
+ function discriminatorValues(path) {
1065
+ if (path.length === 0)
1066
+ return [];
1067
+ let schema = AgentManifestV8Schema;
1068
+ for (const part of path.slice(0, -1)) {
1069
+ schema = descend(schema, part);
1070
+ if (!schema)
1071
+ return [];
1072
+ }
1073
+ const def = defOf(unwrap(schema));
1074
+ if (def?.type !== "union")
1075
+ return [];
1076
+ const tags = [];
1077
+ for (const option of def.options) {
1078
+ const tag = defOf(unwrap(shapeOf(option)?.[String(path.at(-1))]));
1079
+ if (tag?.type === "literal")
1080
+ tags.push(...tag.values.filter((item) => typeof item === "string"));
1081
+ }
1082
+ return tags;
1083
+ }
1084
+ /** Why a runtime field needs kind `pod`, as the Runtime says it. */
1085
+ const POD_ONLY = {
1086
+ image: 'is for kind "pod": a virtual Agent runs no images',
1087
+ storage: 'is for kind "pod": a virtual Agent has no volume',
1088
+ setup: 'is for kind "pod": it runs when a pod\'s disk is made or reset',
1089
+ files: 'is for kind "pod": they are copied when a pod\'s disk is made or reset',
1090
+ };
1091
+ /** A few fields' meaning, for "x is required". */
1092
+ const FIELD_HINTS = {
1093
+ session: 'a session id, or "new" for a new session each run',
1094
+ };
1095
+ /** The value at `path` in `root`, or undefined. */
1096
+ function valueAt(root, path) {
1097
+ let value = root;
1098
+ for (const part of path) {
1099
+ if (value === null || typeof value !== "object")
1100
+ return undefined;
1101
+ value = value[part];
1102
+ }
1103
+ return value;
1104
+ }
1105
+ const TYPE_TEXT = {
1106
+ string: "a string",
1107
+ number: "a number",
1108
+ int: "a whole number",
1109
+ boolean: "true or false",
1110
+ object: "a map",
1111
+ record: "a map",
1112
+ array: "a list",
1113
+ null: "null",
1114
+ };
1115
+ /** What a value is, as a person names it. */
1116
+ function valueText(value) {
1117
+ if (value === null)
1118
+ return "null";
1119
+ if (Array.isArray(value))
1120
+ return "a list";
1121
+ if (typeof value === "object")
1122
+ return "a map";
1123
+ if (typeof value === "string")
1124
+ return `the string ${show(value)}`;
1125
+ return String(value);
1126
+ }
1127
+ const orList = (items) => (items.length < 2 ? (items[0] ?? "") : `${items.slice(0, -1).join(", ")} or ${items.at(-1)}`);
1128
+ /**
1129
+ * A schema issue as the compiler says it: the field, what it takes and, for a value close to an
1130
+ * allowed one, a "did you mean". A message a schema wrote itself is kept, after the field.
1131
+ */
1132
+ function issueMessage(issue, field, value) {
1133
+ const named = field === "" ? "The manifest" : field;
1134
+ if (issue.code === "invalid_value") {
1135
+ const allowed = orList(issue.values.map((item) => show(item)));
1136
+ if (value === undefined)
1137
+ return `${named} is required: ${allowed}`;
1138
+ const close = typeof value === "string" ? suggestion(value, issue.values.filter((item) => typeof item === "string")) : undefined;
1139
+ return `${named} is ${allowed}, not ${show(value)}${close ? `. Did you mean '${close}'?` : ""}`;
1140
+ }
1141
+ const last = field.split(".").at(-1) ?? "";
1142
+ // zod's own wording starts so; a schema's own message does not, and may name the field itself.
1143
+ if (!/^(?:Invalid|Too (?:small|big)|Unrecognized)/.test(issue.message))
1144
+ return field === "" || issue.message.startsWith(`${last} `) ? issue.message : `${field}: ${issue.message}`;
1145
+ switch (issue.code) {
1146
+ case "invalid_type": {
1147
+ const expected = TYPE_TEXT[issue.expected] ?? `a ${issue.expected}`;
1148
+ return value === undefined ? `${named} is required: ${FIELD_HINTS[last] ?? expected}` : `${named} is ${expected}, not ${valueText(value)}`;
1149
+ }
1150
+ case "too_small":
1151
+ case "too_big": {
1152
+ const bound = Number(issue.code === "too_small" ? issue.minimum : issue.maximum);
1153
+ const most = issue.code === "too_small" ? "at least" : "at most";
1154
+ if (issue.origin === "string")
1155
+ return bound === 1 && issue.code === "too_small" ? `${named} is empty: write a value` : `${named} is ${most} ${bound} characters`;
1156
+ if (issue.origin === "array" || issue.origin === "set")
1157
+ return `${named} holds ${most} ${bound} item${bound === 1 ? "" : "s"}`;
1158
+ return `${named} is ${issue.inclusive === false ? (issue.code === "too_small" ? "above" : "below") : most} ${bound}${value === undefined ? "" : `, not ${valueText(value)}`}`;
1159
+ }
1160
+ case "invalid_format":
1161
+ return issue.format === "regex" && "pattern" in issue
1162
+ ? `${named} ${show(value)} does not have the form ${String(issue.pattern)}`
1163
+ : `${named} ${show(value)} is not a valid ${issue.format}`;
1164
+ case "not_multiple_of":
1165
+ return `${named} is a multiple of ${String(issue.divisor)}`;
1166
+ case "invalid_key":
1167
+ case "invalid_element": {
1168
+ const inner = issue.issues[0]?.message;
1169
+ return inner && !/^(?:Invalid|Too (?:small|big))/.test(inner) ? `${named}: ${inner}` : `${named} has a key that is not valid`;
1170
+ }
1171
+ default:
1172
+ return `${named} does not fit any form it can take`;
1173
+ }
1174
+ }
1175
+ function finish(diagnostics, manifest) {
1176
+ const order = { error: 0, warning: 1, info: 2, note: 3 };
1177
+ const sorted = [...diagnostics].sort((a, b) => order[a.severity] - order[b.severity] ||
1178
+ compare(a.file ?? "", b.file ?? "") ||
1179
+ (a.line ?? 0) - (b.line ?? 0) ||
1180
+ (a.column ?? 0) - (b.column ?? 0));
1181
+ return { ...(manifest === undefined ? {} : { manifest }), diagnostics: sorted, compiler: AGENT_FOLDER_COMPILER };
1182
+ }
1183
+ /** The closest recorded position for `path` in `file`: the field, else its nearest parent. */
1184
+ function locate(file, path) {
1185
+ if (!file)
1186
+ return undefined;
1187
+ for (let length = path.length; length >= 0; length--) {
1188
+ const found = file.positions.get(pointerOf(path.slice(0, length)));
1189
+ if (found)
1190
+ return found;
1191
+ }
1192
+ return undefined;
1193
+ }
1194
+ /**
1195
+ * The fix-it for the unknown key at `path` of `file`: renamed to the one of `known` closest to it.
1196
+ * None with two as close, with that key already beside it, or with no position for the key.
1197
+ */
1198
+ function renameFix(file, path, known) {
1199
+ const from = path.at(-1);
1200
+ const at = file?.positions.get(pointerOf(path))?.key;
1201
+ if (!file || !at || typeof from !== "string")
1202
+ return undefined;
1203
+ const [to, ...others] = suggestions(from, known);
1204
+ if (to === undefined || others.length > 0 || to === from || file.positions.has(pointerOf([...path.slice(0, -1), to])))
1205
+ return undefined;
1206
+ return { kind: "rename_key", file: file.path, line: at.line, column: at.column, from, to };
1207
+ }
1208
+ /** The origin recorded for the longest prefix of a manifest path. */
1209
+ function originOf(origins, path) {
1210
+ let best;
1211
+ for (const [prefix, origin] of origins) {
1212
+ if (prefix.length > path.length || (best && prefix.length <= best.prefix))
1213
+ continue;
1214
+ if (prefix.every((part, index) => String(part) === String(path[index])))
1215
+ best = { file: origin.file, origin, prefix: prefix.length };
1216
+ }
1217
+ return best;
1218
+ }
1219
+ /** The keys an object at `path` of `value` holds, for a "did you mean". */
1220
+ function knownKeys(path) {
1221
+ let schema = AgentManifestV8Schema;
1222
+ for (const part of path) {
1223
+ schema = descend(schema, part);
1224
+ if (!schema)
1225
+ return [];
1226
+ }
1227
+ const shape = shapeOf(schema);
1228
+ return shape ? Object.keys(shape) : [];
1229
+ }
1230
+ function defOf(schema) {
1231
+ return schema?._zod?.def;
1232
+ }
1233
+ function unwrap(schema) {
1234
+ for (let depth = 0; depth < 20; depth++) {
1235
+ const def = defOf(schema);
1236
+ if (!def)
1237
+ return schema;
1238
+ if (def.type === "optional" || def.type === "nullable" || def.type === "default" || def.type === "readonly" || def.type === "catch")
1239
+ schema = def.innerType;
1240
+ else if (def.type === "pipe")
1241
+ schema = def.in;
1242
+ else if (def.type === "lazy")
1243
+ schema = def.getter();
1244
+ else
1245
+ return schema;
1246
+ }
1247
+ return schema;
1248
+ }
1249
+ function shapeOf(schema) {
1250
+ const def = defOf(unwrap(schema));
1251
+ return def?.type === "object" ? def.shape : undefined;
1252
+ }
1253
+ function descend(schema, part) {
1254
+ const inner = unwrap(schema);
1255
+ const def = defOf(inner);
1256
+ if (!def)
1257
+ return undefined;
1258
+ if (def.type === "object")
1259
+ return def.shape[String(part)];
1260
+ if (def.type === "array")
1261
+ return def.element;
1262
+ if (def.type === "record")
1263
+ return def.valueType;
1264
+ if (def.type === "union")
1265
+ for (const option of def.options) {
1266
+ const found = descend(option, part);
1267
+ if (found)
1268
+ return found;
1269
+ }
1270
+ return undefined;
1271
+ }
1272
+ /** `text` without its leading and trailing blank lines; nothing else is touched. */
1273
+ function trimBlankLines(text) {
1274
+ const lines = text.replace(/\r\n/g, "\n").split("\n");
1275
+ while (lines.length > 0 && lines[0].trim() === "")
1276
+ lines.shift();
1277
+ while (lines.length > 0 && lines.at(-1).trim() === "")
1278
+ lines.pop();
1279
+ return lines.join("\n");
1280
+ }