@nylorun/core 0.27.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 (43) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +3 -1
  3. package/dist/contracts.d.ts +153 -1
  4. package/dist/contracts.js +62 -7
  5. package/dist/define.d.ts +2 -1
  6. package/dist/define.js +2 -1
  7. package/dist/definition/cron.d.ts +15 -0
  8. package/dist/definition/cron.js +155 -0
  9. package/dist/definition/sections.d.ts +11 -0
  10. package/dist/definition/sections.js +29 -20
  11. package/dist/folder/compile.d.ts +43 -5
  12. package/dist/folder/compile.js +499 -88
  13. package/dist/folder/context.d.ts +97 -0
  14. package/dist/folder/context.js +79 -0
  15. package/dist/folder/decompile.d.ts +18 -0
  16. package/dist/folder/decompile.js +660 -0
  17. package/dist/folder/fix.d.ts +22 -0
  18. package/dist/folder/fix.js +191 -0
  19. package/dist/folder/flow.d.ts +42 -0
  20. package/dist/folder/flow.js +215 -0
  21. package/dist/folder/frontmatter.d.ts +5 -2
  22. package/dist/folder/frontmatter.js +8 -4
  23. package/dist/folder/index.d.ts +7 -2
  24. package/dist/folder/index.js +6 -1
  25. package/dist/folder/json-schema.d.ts +15 -0
  26. package/dist/folder/json-schema.js +212 -0
  27. package/dist/folder/nested.d.ts +24 -0
  28. package/dist/folder/nested.js +378 -0
  29. package/dist/folder/plugins.d.ts +23 -0
  30. package/dist/folder/plugins.js +155 -0
  31. package/dist/folder/schemas.d.ts +8 -0
  32. package/dist/folder/schemas.js +238 -0
  33. package/dist/folder/suggest.d.ts +13 -0
  34. package/dist/folder/suggest.js +63 -0
  35. package/dist/schemas/agent-folder/agent-md.schema.json +143 -0
  36. package/dist/schemas/agent-folder/flow.schema.json +466 -0
  37. package/dist/schemas/agent-folder/mcp.schema.json +59 -0
  38. package/dist/schemas/agent-folder/runtime.schema.json +447 -0
  39. package/dist/schemas/agent-folder/tool.schema.json +77 -0
  40. package/dist/schemas/agent-folder/trigger-md.schema.json +65 -0
  41. package/dist/utils/runtime-limits.d.ts +8 -0
  42. package/dist/utils/runtime-limits.js +19 -0
  43. package/package.json +8 -2
@@ -1,11 +1,20 @@
1
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";
2
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";
3
6
  import { SKILL_ENTRY, skillFilePathIssue } from "../utils/definition-files.js";
4
7
  import { parseMarkdown } from "./frontmatter.js";
5
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";
6
12
  /** The compiler format this version builds: a folder with no `format`, or `format: 1`. */
7
13
  export const AGENT_FOLDER_COMPILER = "agent-folder/1";
8
- /** What a folder may hold. Fixed in this version; Tenant settings come later. */
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
+ */
9
18
  export const AGENT_FOLDER_LIMITS = Object.freeze({
10
19
  /** Files in one folder. */
11
20
  files: 2000,
@@ -20,25 +29,71 @@ const MCP_FILE = "mcp.json";
20
29
  const OUTPUT_SCHEMA_FILE = "output.schema.json";
21
30
  const WORKSPACE = "/workspace";
22
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
+ };
23
43
  const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
24
- const AGENT_KEYS = ["name", "description", "format", "harness", "outputSchema", "mcpServers", "skills", "memory", "loop", "metadata"];
44
+ export const AGENT_KEYS = ["name", "description", "format", "harness", "inputSchema", "outputSchema", "mcpServers", "skills", "memory", "loop", "metadata"];
25
45
  const SKILL_KEYS = ["name", "description", "license", "compatibility", "metadata", "allowed-tools"];
26
- const TRIGGER_KEYS = ["schedule", "timezone", "at", "webhook", "session"];
27
- const SERVER_KEYS = ["type", "url", "headers"];
28
- const SERVER_SETTING_KEYS = ["deferred", "tools"];
29
- const TOOL_KEYS = ["description", "inputSchema", "outputSchema", "http", "approval"];
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)';
30
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);
31
87
  /** What a path is, or why the folder may not hold it. */
32
88
  function classify(path) {
33
89
  const segments = path.split("/");
34
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" };
35
94
  if (segments.includes(".git") || segments.includes("node_modules"))
36
95
  return { code: "path_refused", error: ".git/ and node_modules/ are not part of an agent folder: leave them out of the upload" };
37
- if (isEnvFile(base))
38
- return { code: "secret_file", error: "Environment files hold secrets and never go in an agent folder: a secret is a slot in runtime.json, and its value goes to the Agent's vault" };
39
96
  const top = segments[0];
40
- if ((base.endsWith(".pem") || base.endsWith(".key")) && top !== "skills" && top !== "files")
41
- return { code: "secret_file", error: "Key files never go in an agent folder outside skills/ and files/: a secret is a slot in runtime.json, and its value goes to the Agent's vault" };
42
97
  if (path === AGENT_FILE)
43
98
  return { kind: "agent" };
44
99
  if (path === RUNTIME_FILE)
@@ -52,15 +107,15 @@ function classify(path) {
52
107
  if (stem !== base && ["runtime", "mcp", "AGENT"].includes(stem))
53
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` };
54
109
  if (path === "flow.json")
55
- return { code: "not_supported", error: `Flows (flow.json) are not in ${AGENT_FOLDER_COMPILER} yet: save the flow as JSON or with the TypeScript builder` };
110
+ return { kind: "flow" };
56
111
  if (base.endsWith(".schema.json"))
57
112
  return { kind: "schema" };
58
113
  return { kind: "other" };
59
114
  }
60
115
  if (top === "agents" || top === "plugins")
61
116
  return {
62
- code: "not_supported",
63
- error: `${top}/ is not in ${AGENT_FOLDER_COMPILER} yet: ${top === "agents" ? "subagents and flows" : "vendored Agent Plugins"} come in a later version`,
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",
64
119
  };
65
120
  if (top === "instructions")
66
121
  return segments.length === 2 && base.endsWith(".md")
@@ -100,10 +155,12 @@ export function folderTextPaths(entries) {
100
155
  kind.kind === "tool" ||
101
156
  kind.kind === "trigger" ||
102
157
  kind.kind === "schema" ||
158
+ kind.kind === "flow" ||
103
159
  (kind.kind === "skill" && entry.path.split("/").length === 3 && entry.path.endsWith(`/${SKILL_ENTRY}`));
104
160
  if (textual)
105
161
  paths.push(entry.path);
106
162
  }
163
+ paths.push(...nestedTextPaths(entries, folderTextPaths));
107
164
  return paths.sort(compare);
108
165
  }
109
166
  const compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
@@ -124,36 +181,18 @@ function pathIssue(path) {
124
181
  return "must not have empty, . or .. segments";
125
182
  return undefined;
126
183
  }
127
- /** The closest of `known` to `name`, when one is close enough to be a typo. */
128
- function suggestion(name, known) {
129
- let best;
130
- for (const candidate of known) {
131
- const distance = editDistance(name.toLowerCase(), candidate.toLowerCase());
132
- if (distance <= Math.max(2, Math.floor(candidate.length / 3)) && (!best || distance < best.distance))
133
- best = { value: candidate, distance };
134
- }
135
- return best?.value;
136
- }
137
- function editDistance(a, b) {
138
- const row = Array.from({ length: b.length + 1 }, (_, index) => index);
139
- for (let i = 1; i <= a.length; i++) {
140
- let previous = row[0];
141
- row[0] = i;
142
- for (let j = 1; j <= b.length; j++) {
143
- const current = row[j];
144
- row[j] = Math.min(row[j] + 1, row[j - 1] + 1, previous + (a[i - 1] === b[j - 1] ? 0 : 1));
145
- previous = current;
146
- }
147
- }
148
- return row[b.length];
149
- }
150
184
  const unknownKeyMessage = (key, known) => {
151
185
  const close = suggestion(key, known);
152
186
  return `Unknown key '${key}'.${close ? ` Did you mean '${close}'?` : ` Known keys: ${known.join(", ")}.`}`;
153
187
  };
154
188
  const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
155
- /** Compiles an agent folder into agent manifest v8, with every diagnostic. */
156
- export function compileAgentFolder(input) {
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 };
157
196
  const diagnostics = [];
158
197
  const parsed = new Map();
159
198
  const report = (severity, code, message, file, path, options = {}) => {
@@ -162,6 +201,7 @@ export function compileAgentFolder(input) {
162
201
  const found = locate(parsed.get(file), path);
163
202
  at = options.key ? (found?.key ?? found?.value) : found?.value;
164
203
  }
204
+ const fix = options.fix ?? (options.rename && file && path ? renameFix(parsed.get(file), path, options.rename) : undefined);
165
205
  diagnostics.push({
166
206
  severity,
167
207
  code,
@@ -169,6 +209,7 @@ export function compileAgentFolder(input) {
169
209
  ...(file === undefined ? {} : { file }),
170
210
  ...(at === undefined ? {} : { line: at.line, column: at.column }),
171
211
  ...(options.pointer === undefined ? {} : { pointer: options.pointer }),
212
+ ...(fix === undefined ? {} : { fix }),
172
213
  });
173
214
  };
174
215
  const error = (code, message, file, path, options = {}) => report("error", code, message, file, path, options);
@@ -201,10 +242,10 @@ export function compileAgentFolder(input) {
201
242
  byPath.set(entry.path, entry);
202
243
  bytes += entry.size;
203
244
  }
204
- if (entries.length > AGENT_FOLDER_LIMITS.files)
205
- error("limit_exceeded", `An agent folder holds at most ${AGENT_FOLDER_LIMITS.files} files; this one holds ${entries.length}`);
206
- if (bytes > AGENT_FOLDER_LIMITS.totalBytes)
207
- error("limit_exceeded", `An agent folder holds at most ${AGENT_FOLDER_LIMITS.totalBytes} bytes; this one holds ${bytes}`);
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}`);
208
249
  const kinds = new Map();
209
250
  for (const path of byPath.keys()) {
210
251
  const kind = classify(path);
@@ -213,17 +254,25 @@ export function compileAgentFolder(input) {
213
254
  else
214
255
  error(kind.code, kind.error, path);
215
256
  }
216
- for (const [path, kind] of kinds)
217
- if (kind === "other")
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")
218
264
  report("note", "file_not_compiled", "Kept with the source; not part of the agent", path);
265
+ }
219
266
  const decoder = new TextDecoder("utf-8", { fatal: true });
267
+ /** The files with CRLF line ends, noted once each. */
268
+ const crlf = new Set();
220
269
  /** The text of a file the compiler reads, or undefined after reporting why it has none. */
221
270
  const textOf = (path) => {
222
271
  const entry = byPath.get(path);
223
272
  if (!entry)
224
273
  return undefined;
225
- if (entry.size > AGENT_FOLDER_LIMITS.textFileBytes) {
226
- error("limit_exceeded", `A Markdown or JSON file holds at most ${AGENT_FOLDER_LIMITS.textFileBytes} bytes; this one holds ${entry.size}`, path);
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);
227
276
  return undefined;
228
277
  }
229
278
  const bytesOf = input.files.get(path);
@@ -231,13 +280,20 @@ export function compileAgentFolder(input) {
231
280
  error("file_missing", "The compiler was not given this file's bytes", path);
232
281
  return undefined;
233
282
  }
283
+ let text;
234
284
  try {
235
- return decoder.decode(bytesOf).replace(/^/, "");
285
+ text = decoder.decode(bytesOf).replace(/^/, "");
236
286
  }
237
287
  catch {
238
288
  error("not_utf8", "The file is not UTF-8 text", path);
239
289
  return undefined;
240
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;
241
297
  };
242
298
  const readJson = (path) => {
243
299
  const text = textOf(path);
@@ -267,19 +323,86 @@ export function compileAgentFolder(input) {
267
323
  parsed.set(path, { path, positions: result.positions });
268
324
  return result;
269
325
  };
326
+ const warn = (code, message, file, path, options = {}) => report("warning", code, message, file, path, options);
270
327
  const checkKeys = (file, value, known, path = []) => {
271
328
  for (const key of Object.keys(value))
272
- if (!known.includes(key))
273
- error("unknown_key", unknownKeyMessage(key, known), file, [...path, key], { key: true });
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
+ }
274
392
  };
275
393
  /** A JSON Schema a field names by path (`./x.json` from the root, `/x.json`), or inline. */
276
- const schemaAt = (file, field, value) => {
277
- if (isObject(value))
394
+ const schemaAt = (file, field, value, manifestPath) => {
395
+ if (isObject(value)) {
396
+ checkSchema(file, field, value, manifestPath);
278
397
  return value;
398
+ }
279
399
  if (typeof value !== "string") {
280
400
  error("schema_invalid", "A schema is a JSON Schema object, or a path to a JSON Schema file", file, field);
281
401
  return undefined;
282
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));
283
406
  const target = value.startsWith("/") ? value.slice(1) : value.replace(/^\.\//, "");
284
407
  if (target.split("/").some((segment) => segment === ".." || segment === "")) {
285
408
  error("path_outside", `${value} leaves the folder: a path names a file inside it`, file, field);
@@ -293,7 +416,10 @@ export function compileAgentFolder(input) {
293
416
  error("schema_invalid", `${value} is not a JSON Schema file: name it *.schema.json or keep it under schemas/`, file, field);
294
417
  return undefined;
295
418
  }
296
- return readJson(target);
419
+ const schema = readJson(target);
420
+ if (schema)
421
+ checkSchema(target, [], schema, manifestPath);
422
+ return schema;
297
423
  };
298
424
  // --- AGENT.md ---------------------------------------------------------------------------
299
425
  if (!byPath.has(AGENT_FILE))
@@ -331,7 +457,7 @@ export function compileAgentFolder(input) {
331
457
  error("harness_invalid", "harness is the id of the harness that runs the loop, such as nylorun", AGENT_FILE, ["harness"]);
332
458
  }
333
459
  if (front.outputSchema !== undefined) {
334
- const schema = schemaAt(AGENT_FILE, ["outputSchema"], front.outputSchema);
460
+ const schema = schemaAt(AGENT_FILE, ["outputSchema"], front.outputSchema, ["harness", "outputSchema"]);
335
461
  if (schema)
336
462
  harness.outputSchema = schema;
337
463
  }
@@ -343,6 +469,14 @@ export function compileAgentFolder(input) {
343
469
  else
344
470
  error("value_invalid", `${key} is a map`, AGENT_FILE, [key]);
345
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
+ }
346
480
  if (front.metadata !== undefined) {
347
481
  if (isObject(front.metadata))
348
482
  metadata = front.metadata;
@@ -357,7 +491,8 @@ export function compileAgentFolder(input) {
357
491
  origins.push([["harness", key], { file: AGENT_FILE, path: [key] }]);
358
492
  origins.push([["harness", "id"], { file: AGENT_FILE, path: ["harness"] }]);
359
493
  }
360
- for (const path of [...kinds].filter(([, kind]) => kind === "instructions").map(([path]) => path)) {
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)) {
361
496
  const text = textOf(path);
362
497
  if (text === undefined)
363
498
  continue;
@@ -367,31 +502,43 @@ export function compileAgentFolder(input) {
367
502
  }
368
503
  if (instructions.length > 0)
369
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 } });
370
508
  // --- runtime.json ----------------------------------------------------------------------
371
509
  let runtime;
372
510
  if (byPath.has(RUNTIME_FILE)) {
373
511
  const value = readJson(RUNTIME_FILE);
374
512
  if (value) {
375
513
  if ("$schema" in value)
376
- error("schema_key", "runtime.json takes no $schema: the path gives the kind, and the folder its format", RUNTIME_FILE, ["$schema"], { key: true });
514
+ checkSchemaUrl(RUNTIME_FILE, "runtime", value.$schema);
377
515
  if ("extends" in value)
378
- error("not_supported", `extends is not in ${AGENT_FOLDER_COMPILER} yet: write the whole runtime section here`, RUNTIME_FILE, ["extends"], { key: true });
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 });
379
517
  const { $schema: _, extends: __, ...rest } = value;
380
518
  runtime = rest;
381
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);
382
524
  }
383
525
  }
384
526
  const derivedSlots = new Map();
385
- /** A slot for `credential`, derived when runtime.json does not declare it. */
386
- const deriveSlot = (credential, type, url, file, path, header) => {
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);
387
534
  const declared = isObject(runtime?.secrets) ? runtime.secrets[credential] : undefined;
388
535
  if (declared !== undefined)
389
536
  return;
390
537
  const existing = derivedSlots.get(credential);
391
538
  if (existing) {
392
539
  if (existing.url !== url || existing.slot.type !== type) {
393
- const at = locate(parsed.get(existing.file), existing.path)?.value;
394
- error("credential_urls", `${credential} is the credential of ${existing.url} (${existing.file}${at ? `:${at.line}` : ""}) and of ${url}: a slot is bound to one URL, so give each URL its own slot`, file, path);
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 });
395
542
  }
396
543
  return;
397
544
  }
@@ -401,9 +548,29 @@ export function compileAgentFolder(input) {
401
548
  required: true,
402
549
  ...(header ? { description: `Sets the ${header} header` } : {}),
403
550
  };
404
- derivedSlots.set(credential, { slot, file, path, url });
405
- report("info", "slot_derived", `A ${type} slot ${credential} is derived for ${url}`, file, path, { pointer: pointerOf(["runtime", "secrets", credential]) });
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 });
406
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
+ });
407
574
  // --- mcp.json --------------------------------------------------------------------------
408
575
  const servers = {};
409
576
  let mcpRead = false;
@@ -411,9 +578,9 @@ export function compileAgentFolder(input) {
411
578
  const value = readJson(MCP_FILE);
412
579
  if (value) {
413
580
  mcpRead = true;
414
- checkKeys(MCP_FILE, value, ["$schema", "mcpServers"]);
415
- if (value.$schema !== undefined && value.$schema !== AGENT_PLUGINS_MCP_SCHEMA)
416
- error("schema_key", `$schema in mcp.json names the Agent Plugins 1.0.0 MCP schema (${AGENT_PLUGINS_MCP_SCHEMA}), or is left out`, MCP_FILE, ["$schema"]);
581
+ checkKeys(MCP_FILE, value, MCP_KEYS);
582
+ if (value.$schema !== undefined)
583
+ checkSchemaUrl(MCP_FILE, "mcp", value.$schema);
417
584
  const listed = value.mcpServers;
418
585
  if (!isObject(listed))
419
586
  error("mcp_invalid", "mcp.json holds mcpServers: a map of server names to servers", MCP_FILE, listed === undefined ? [] : ["mcpServers"]);
@@ -469,6 +636,7 @@ export function compileAgentFolder(input) {
469
636
  continue;
470
637
  }
471
638
  if (!raw.includes("${")) {
639
+ checkHeaderSecret(MCP_FILE, path, header, raw);
472
640
  headers[header] = raw;
473
641
  continue;
474
642
  }
@@ -514,9 +682,12 @@ export function compileAgentFolder(input) {
514
682
  ...(credential ? { credential: credential.name } : {}),
515
683
  };
516
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 }]);
517
687
  }
518
688
  }
519
689
  }
690
+ parts.mergeServers(servers);
520
691
  if (front.mcpServers !== undefined) {
521
692
  if (!isObject(front.mcpServers))
522
693
  error("value_invalid", "mcpServers is a map of server names to this agent's settings", AGENT_FILE, ["mcpServers"]);
@@ -534,9 +705,16 @@ export function compileAgentFolder(input) {
534
705
  error("value_invalid", "A server's settings are a map: deferred and tools", AGENT_FILE, at);
535
706
  continue;
536
707
  }
537
- checkKeys(AGENT_FILE, settings, SERVER_SETTING_KEYS, at);
538
- if ("credential" in settings)
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)
539
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 });
540
718
  for (const setting of SERVER_SETTING_KEYS)
541
719
  if (settings[setting] !== undefined) {
542
720
  servers[key][setting] = settings[setting];
@@ -547,6 +725,26 @@ export function compileAgentFolder(input) {
547
725
  if (Object.keys(servers).length > 0)
548
726
  harness.mcpServers = servers;
549
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
+ };
550
748
  const skills = {};
551
749
  const skillFolders = new Map();
552
750
  for (const [path, kind] of kinds)
@@ -567,11 +765,11 @@ export function compileAgentFolder(input) {
567
765
  let valid = true;
568
766
  for (const key of Object.keys(data)) {
569
767
  if (key === "secrets") {
570
- 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 });
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) });
571
769
  valid = false;
572
770
  }
573
771
  else if (!SKILL_KEYS.includes(key)) {
574
- error("unknown_key", unknownKeyMessage(key, SKILL_KEYS), entryPath, [key], { key: true });
772
+ error("unknown_key", unknownKeyMessage(key, SKILL_KEYS), entryPath, [key], { key: true, rename: SKILL_KEYS });
575
773
  valid = false;
576
774
  }
577
775
  }
@@ -605,6 +803,7 @@ export function compileAgentFolder(input) {
605
803
  skills[skillName] = { name: skillName, description: skillDescription, files };
606
804
  origins.push([["harness", "skills", skillName], { file: entryPath, path: [] }]);
607
805
  }
806
+ parts.mergeSkills(skills);
608
807
  if (front.skills !== undefined) {
609
808
  if (!isObject(front.skills))
610
809
  error("value_invalid", "skills is a map of skill names to this agent's settings for them", AGENT_FILE, ["skills"]);
@@ -653,32 +852,31 @@ export function compileAgentFolder(input) {
653
852
  continue;
654
853
  }
655
854
  if ("agent" in value) {
656
- error("not_supported", `A subagent as a tool is not in ${AGENT_FOLDER_COMPILER} yet`, path, ["agent"], { key: true });
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 });
657
856
  continue;
658
857
  }
659
858
  if ("$schema" in value)
660
- error("schema_key", "A tool file takes no $schema: the path gives the kind", path, ["$schema"], { key: true });
859
+ checkSchemaUrl(path, "tool", value.$schema);
661
860
  checkKeys(path, value, [...TOOL_KEYS, "$schema"]);
662
861
  if (!isObject(value.http)) {
663
862
  error("tool_invalid", "A tool file declares an HTTP tool: http with its url", path, value.http === undefined ? [] : ["http"]);
664
863
  continue;
665
864
  }
666
865
  const tool = { name: toolName };
866
+ const at = ["harness", "tools", tools.length];
667
867
  if (value.description !== undefined)
668
868
  tool.description = value.description;
669
- const input = value.inputSchema === undefined ? undefined : schemaAt(path, ["inputSchema"], value.inputSchema);
869
+ const input = value.inputSchema === undefined ? undefined : schemaAt(path, ["inputSchema"], value.inputSchema, [...at, "inputSchema"]);
670
870
  if (value.inputSchema === undefined)
671
871
  error("tool_invalid", "inputSchema is required: the JSON Schema of the tool's input", path, []);
672
872
  if (input)
673
873
  tool.inputSchema = input;
674
874
  if (value.outputSchema !== undefined) {
675
- const output = schemaAt(path, ["outputSchema"], value.outputSchema);
875
+ const output = schemaAt(path, ["outputSchema"], value.outputSchema, [...at, "outputSchema"]);
676
876
  if (output)
677
877
  tool.outputSchema = output;
678
878
  }
679
879
  tool.http = value.http;
680
- if (value.approval !== undefined)
681
- tool.approval = value.approval;
682
880
  const credential = value.http.credential;
683
881
  if (typeof credential === "string" && typeof value.http.url === "string")
684
882
  deriveSlot(credential, "bearer", value.http.url, path, ["http", "credential"]);
@@ -689,6 +887,8 @@ export function compileAgentFolder(input) {
689
887
  harness.tools = tools;
690
888
  // --- triggers/ -------------------------------------------------------------------------
691
889
  const triggers = {};
890
+ /** Where each trigger's body (its prompt) starts. */
891
+ const bodyLines = new Map();
692
892
  for (const path of [...kinds].filter(([, kind]) => kind === "trigger").map(([path]) => path)) {
693
893
  const id = path.slice("triggers/".length, -".md".length);
694
894
  const markdown = readMarkdown(path);
@@ -699,6 +899,8 @@ export function compileAgentFolder(input) {
699
899
  continue;
700
900
  }
701
901
  checkKeys(path, markdown.data, TRIGGER_KEYS);
902
+ checkSchedule(path, [], markdown.data);
903
+ bodyLines.set(path, markdown.bodyLine);
702
904
  const trigger = { ...markdown.data, prompt: trimBlankLines(markdown.body) };
703
905
  if (isObject(runtime?.triggers) && id in runtime.triggers) {
704
906
  error("trigger_twice", `Trigger ${id} is declared in runtime.json and in ${path}: keep one`, path);
@@ -712,6 +914,9 @@ export function compileAgentFolder(input) {
712
914
  for (const [path, kind] of kinds)
713
915
  if (kind === "file")
714
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);
715
920
  // --- The runtime section -----------------------------------------------------------------
716
921
  const needsRuntime = derivedSlots.size > 0 || Object.keys(triggers).length > 0 || Object.keys(seeded).length > 0;
717
922
  if (!runtime && needsRuntime)
@@ -742,37 +947,229 @@ export function compileAgentFolder(input) {
742
947
  ...(runtime === undefined ? {} : { runtime }),
743
948
  };
744
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
+ };
745
955
  // Triggers from triggers/ are checked against their own schema first, with the file's lines.
746
956
  for (const [id, trigger] of Object.entries(triggers)) {
957
+ const file = `triggers/${id}.md`;
747
958
  const result = TriggerSchema.safeParse(trigger);
748
959
  if (result.success)
749
960
  continue;
750
- for (const issue of result.error.issues)
751
- issueDiagnostic(issue, ["runtime", "triggers", id], `triggers/${id}.md`, issue.path);
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
+ }
752
968
  }
753
969
  const checked = AgentManifestV8Schema.safeParse(document);
754
- if (!checked.success)
970
+ if (!checked.success) {
755
971
  for (const issue of checked.error.issues) {
756
972
  if (issue.path[0] === "runtime" && issue.path[1] === "triggers" && typeof issue.path[2] === "string" && issue.path[2] in triggers)
757
973
  continue;
758
- const origin = originOf(origins, issue.path);
759
- issueDiagnostic(issue, [], origin?.file, origin ? [...origin.origin.path, ...issue.path.slice(origin.prefix)] : undefined);
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]) });
760
1015
  }
761
1016
  if (diagnostics.some((item) => item.severity === "error"))
762
1017
  return finish(diagnostics);
763
- return finish(diagnostics, checked.success ? checked.data : undefined);
764
- function issueDiagnostic(issue, prefix, file, path) {
765
- const pointer = pointerOf([...prefix, ...issue.path]);
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
+ }
766
1048
  if (issue.code === "unrecognized_keys") {
767
- const known = knownKeys([...prefix, ...issue.path]);
1049
+ const known = knownKeys(full);
768
1050
  for (const key of issue.keys)
769
- error("unknown_key", known.length ? unknownKeyMessage(key, known) : `Unknown key '${key}'`, file, path ? [...path, key] : undefined, { key: true, pointer: pointerOf([...prefix, ...issue.path, key]) });
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
+ });
770
1056
  return;
771
1057
  }
772
1058
  // The field as the file names it, or as the manifest does when no file holds it.
773
- const shown = file && path ? path : [...prefix, ...issue.path];
774
- const field = shown.length ? `${shown.map(String).join(".")}: ` : "";
775
- error("schema_invalid", `${field}${issue.message}`, file, path, { pointer });
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`;
776
1173
  }
777
1174
  }
778
1175
  function finish(diagnostics, manifest) {
@@ -794,6 +1191,20 @@ function locate(file, path) {
794
1191
  }
795
1192
  return undefined;
796
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
+ }
797
1208
  /** The origin recorded for the longest prefix of a manifest path. */
798
1209
  function originOf(origins, path) {
799
1210
  let best;