@nylorun/core 0.51.0-beta → 0.53.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @nylorun/core
2
2
 
3
+ ## 0.53.0-beta
4
+
5
+ ### Minor Changes
6
+
7
+ - 8ab577f: Subagents are files (ADR-164): a manifest's files in the new `format: agent-folder/4` write each subagent as one file, `agents/<id>.md`, as Claude Code and Cursor do. The root's `tools/`, `skills/`, `mcp.json`, `plugins/` and Runtime plugins are the manifest's library: a subagent file gets everything in it that a subagent can use, and narrows it with `tools`, `disallowedTools`, `skills` and `mcpServers`; the root can narrow its own tools with `tools` and `disallowedTools`; `flow: ./<id>.flow.json` drives a subagent with a flow; a manifest driven by a flow may hold the library its stages draw on. Claude Code's and Cursor's keys (`model`, `color`, `readonly`, …) and tool names (`Read`, `Grep`, …) are noted and read. A subagent folder in format 4 is `subagent_folder`, and a subagent file in an older format `subagent_file`. `nylorun migrate folder <dir> --to 4` turns each subagent folder into a file and writes only when the folder compiles to the same agent manifest. Formats 1 to 3, the agent manifest JSON, the API, the harness and delegation's one level are unchanged. The Runtime accepts format 4 uploads with this core.
8
+
9
+ ## 0.52.0-beta
10
+
11
+ ### Minor Changes
12
+
13
+ - b9b0965: A subagent used as a tool receives `{ task }` as a string, so one that declares an `inputSchema` that can't take a string is now refused when it is built or saved (ADR-162): `delegation.input` in the builder and the manifest contract, `delegation_input` in a manifest's files. Before, the manifest saved and the flow's first stage got a string it didn't declare. Messages and Studio now use ADR-162's words: an agent manifest is driven by a model loop or by a flow, and a flow's stages can be subagents; "flow agent" is no longer a kind. Studio's Agent manifests list filters by **Driven by** (Model loop or Flow), a flow's section is **Stages**, and a subagent used as a tool shows as "Subagent". No code, diagnostic code or wire format changes.
14
+
3
15
  ## 0.51.0-beta
4
16
 
5
17
  ### Minor Changes
package/dist/contracts.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { z } from "zod";
3
3
  import { SANDBOX_NETWORK_PRESETS, SANDBOX_TOOL_NAMES, isSandboxHostPattern, parseSandboxDuration, parseSandboxSize, } from "./utils/sandbox.js";
4
4
  import { REMOVED_MANIFEST_FIELDS, REMOVED_RUNTIME_SECTION_FIELDS, agentManifestVersionIssue, manifestVersionIssue, workflowVersionIssue, } from "./definition/removed.js";
5
- import { DELEGATE_INPUT_SCHEMA, DELEGATE_NAME_PATTERN } from "./definition/delegate.js";
5
+ import { DELEGATE_INPUT_SCHEMA, DELEGATE_NAME_PATTERN, delegateInputIssue } from "./definition/delegate.js";
6
6
  import { stdioMcpRefusal } from "./definition/mcp.js";
7
7
  import { APPROVAL_MODES, HTTP_TOOL_METHODS, httpInputIssue, httpUrlIssue, httpUrlTemplateIssue, httpVerifierIssue, } from "./definition/http-tool.js";
8
8
  import { canonical } from "./utils/canonical.js";
@@ -348,7 +348,10 @@ function delegationIssues(manifest, issue) {
348
348
  issue(`Agent tool '${tool.name}' must take the standard { task } input`);
349
349
  if (tool.outputSchema !== undefined)
350
350
  issue(`Agent tool '${tool.name}' must not declare outputSchema; the agent's outputSchema applies`);
351
- // A flow agent runs in its own linked session; its leaves may delegate in turn.
351
+ const input = delegateInputIssue(child.id, child.inputSchema);
352
+ if (input)
353
+ issue(input);
354
+ // A subagent driven by a flow runs in its own linked session; its steps may delegate in turn.
352
355
  if ("kind" in child)
353
356
  continue;
354
357
  if (child.tools?.some((item) => item.agent !== undefined))
@@ -1,6 +1,6 @@
1
1
  import { bindAgent } from "./bind-agent.js";
2
2
  import { createManifest, SESSION_PART_ID } from "./manifest.js";
3
- import { DELEGATE_NAME_PATTERN, delegateOf, delegatesOf } from "./delegate.js";
3
+ import { DELEGATE_NAME_PATTERN, delegateInputIssue, delegateOf, delegatesOf } from "./delegate.js";
4
4
  const diagnostic = (code, message, extra = {}) => Object.freeze({ code, message, ...extra });
5
5
  export function assembleAgent(parts, identity) {
6
6
  const diagnostics = [];
@@ -84,7 +84,10 @@ function delegationDiagnostics(items) {
84
84
  found.push(diagnostic("delegation.invalid-name", `Agent '${child.id}' is used as a tool, so its id must be 1-64 letters, digits, '_' or '-'`, extra));
85
85
  if (!child.description?.trim())
86
86
  found.push(diagnostic("delegation.description-required", `Agent '${child.id}' is used as a tool and needs a description: the parent's model reads it to decide when to delegate`, extra));
87
- // A flow agent runs in its own linked session; its agents may delegate in turn.
87
+ const input = delegateInputIssue(child.id, child.inputSchema);
88
+ if (input)
89
+ found.push(diagnostic("delegation.input", input, extra));
90
+ // A subagent driven by a flow runs in its own linked session; its steps may delegate in turn.
88
91
  if (child.kind === "workflow")
89
92
  continue;
90
93
  const nested = delegatesOf(child)[0];
@@ -255,11 +255,11 @@ export class AgentBuilder {
255
255
  const diagnostic = kind === "react"
256
256
  ? Object.freeze({
257
257
  code: "flow.no-model",
258
- message: `'${snapshot.id}' is a flow agent, which runs no model. Move .${method} to an agent passed to .pipe().`,
258
+ message: `'${snapshot.id}' is driven by a flow, which runs no model loop. Move .${method} to a subagent passed to .pipe().`,
259
259
  })
260
260
  : Object.freeze({
261
261
  code: "agent.mixed-body",
262
- message: `'${snapshot.id}' is a ReAct agent. An agent is either a ReAct loop or a flow: put the ReAct part in its own Agent and add it with .pipe().`,
262
+ message: `'${snapshot.id}' is driven by a model loop. An agent manifest is driven by a model loop or by a flow, not both: put the model loop in a subagent and add it with .pipe().`,
263
263
  });
264
264
  return { body: snapshot.body, diagnostics: addDiagnostics(snapshot.diagnostics, [diagnostic]) };
265
265
  }
@@ -25,7 +25,7 @@ export function codeToolRefusal(manifest) {
25
25
  if (!first)
26
26
  return undefined;
27
27
  const what = first.kind === "stage"
28
- ? `The tool stage '${first.name}' of flow agent '${first.owner}'`
28
+ ? `The tool stage '${first.name}' of the flow of '${first.owner}'`
29
29
  : `Tool '${first.name}' of agent '${first.owner}'`;
30
30
  const more = rest.length === 0 ? "" : ` (and ${rest.length} more)`;
31
31
  return `${what}${more} runs your code, but the Runtime runs agents from their manifests alone. Make it an http() tool or serve it from a remote MCP server (see MIGRATION.md).`;
@@ -29,6 +29,15 @@ export declare const MODEL_TOOL_NAME_MAX = 64;
29
29
  export declare const DELEGATE_NAME_PATTERN: RegExp;
30
30
  /** The input every agent used as a tool accepts. Part of the hashed manifest; change deliberately. */
31
31
  export declare const DELEGATE_INPUT_SCHEMA: JsonObject;
32
+ /**
33
+ * Whether a subagent's own `inputSchema` can take the task a tool call hands it: any string.
34
+ * False when its `type` excludes `"string"`, when it pins the value (`const`, `enum`), or when
35
+ * no branch of `anyOf`/`oneOf` (or not every branch of `allOf`) can take one. Other keywords
36
+ * (`minLength`, `pattern`) narrow which strings fit and are left to the run (ADR-162).
37
+ */
38
+ export declare function acceptsTaskInput(schema: unknown): boolean;
39
+ /** Why a subagent used as a tool can't take its task, or undefined when it can (ADR-162). */
40
+ export declare function delegateInputIssue(id: string, inputSchema: unknown): string | undefined;
32
41
  /** A built agent or an agent builder; both expose getBinding() and manifest. */
33
42
  export declare function isAgentItem(value: unknown): value is Pick<BuiltAgent, "id" | "manifest" | "getBinding"> & {
34
43
  build?: () => BuiltAgent;
@@ -25,6 +25,43 @@ const taskSchema = z
25
25
  .strict();
26
26
  /** The input every agent used as a tool accepts. Part of the hashed manifest; change deliberately. */
27
27
  export const DELEGATE_INPUT_SCHEMA = normalizeSchema(taskSchema, "input").jsonSchema;
28
+ /**
29
+ * Whether a subagent's own `inputSchema` can take the task a tool call hands it: any string.
30
+ * False when its `type` excludes `"string"`, when it pins the value (`const`, `enum`), or when
31
+ * no branch of `anyOf`/`oneOf` (or not every branch of `allOf`) can take one. Other keywords
32
+ * (`minLength`, `pattern`) narrow which strings fit and are left to the run (ADR-162).
33
+ */
34
+ export function acceptsTaskInput(schema) {
35
+ if (schema === true || schema === undefined)
36
+ return true;
37
+ if (schema === false || schema === null || typeof schema !== "object" || Array.isArray(schema))
38
+ return false;
39
+ const value = schema;
40
+ if ("const" in value || "enum" in value)
41
+ return false;
42
+ const type = value.type;
43
+ if (typeof type === "string" && type !== "string")
44
+ return false;
45
+ if (Array.isArray(type) && !type.includes("string"))
46
+ return false;
47
+ const branches = (key) => (Array.isArray(value[key]) ? value[key] : undefined);
48
+ const anyOf = branches("anyOf");
49
+ if (anyOf && !anyOf.some(acceptsTaskInput))
50
+ return false;
51
+ const oneOf = branches("oneOf");
52
+ if (oneOf && !oneOf.some(acceptsTaskInput))
53
+ return false;
54
+ const allOf = branches("allOf");
55
+ if (allOf && !allOf.every(acceptsTaskInput))
56
+ return false;
57
+ return true;
58
+ }
59
+ /** Why a subagent used as a tool can't take its task, or undefined when it can (ADR-162). */
60
+ export function delegateInputIssue(id, inputSchema) {
61
+ if (inputSchema === undefined || acceptsTaskInput(inputSchema))
62
+ return undefined;
63
+ return `'${id}' is used as a tool, so it receives { task } as a string; its inputSchema must accept a string or be left out`;
64
+ }
28
65
  async function engineOnly() {
29
66
  throw new ToolError("delegation.engine-only", "Agents used as tools are run by the Nylorun engine, not by an executor");
30
67
  }
@@ -13,7 +13,7 @@ export function compileAgentFlow(options) {
13
13
  const stages = expand(options.stages);
14
14
  if (stages.length === 0)
15
15
  fail([
16
- diagnostic("flow.empty", `Flow agent '${options.id}' has no stages. Add .pipe(), .switch(), .parallel(), .map() or .loop().`),
16
+ diagnostic("flow.empty", `'${options.id}' is driven by a flow with no stages. Add .pipe(), .switch(), .parallel(), .map() or .loop().`),
17
17
  ]);
18
18
  const build = {
19
19
  id: options.id,
@@ -189,14 +189,14 @@ function embed(build, id, manifest) {
189
189
  return;
190
190
  }
191
191
  if (canonical(existing) !== canonical(manifest))
192
- build.diagnostics.push(diagnostic("flow.agent-conflict", `Flow agent '${build.id}' uses two different agents with the id '${id}'. Give each agent its own id.`));
192
+ build.diagnostics.push(diagnostic("flow.agent-conflict", `The flow of '${build.id}' uses two different subagents with the id '${id}'. Give each subagent its own id.`));
193
193
  }
194
194
  function addBinding(build, id, binding) {
195
195
  const existing = build.bindings[id];
196
196
  if (existing === undefined)
197
197
  build.bindings[id] = binding;
198
198
  else if (canonical(existing.manifest) !== canonical(binding.manifest))
199
- build.diagnostics.push(diagnostic("flow.agent-conflict", `Flow agent '${build.id}' uses two different agents with the id '${id}'. Give each agent its own id.`));
199
+ build.diagnostics.push(diagnostic("flow.agent-conflict", `The flow of '${build.id}' uses two different subagents with the id '${id}'. Give each subagent its own id.`));
200
200
  }
201
201
  /** Put a stage's `id` on its node, wrapping it in a chain when it has its own. */
202
202
  function withId(node, id, build) {
@@ -224,12 +224,12 @@ function bindNodes(root, build) {
224
224
  const part = leafPart(node);
225
225
  if (part !== undefined) {
226
226
  if (leaves.has(part) || ids.has(part))
227
- build.diagnostics.push(diagnostic("flow.duplicate-leaf", `'${part}' runs twice in flow agent '${build.id}'. Give one a new id: x.withId("${part}-2").`));
227
+ build.diagnostics.push(diagnostic("flow.duplicate-leaf", `'${part}' runs twice in the flow of '${build.id}'. Give one a new id: x.withId("${part}-2").`));
228
228
  leaves.add(part);
229
229
  }
230
230
  else if ("id" in node && node.id !== undefined) {
231
231
  if (ids.has(node.id) || leaves.has(node.id))
232
- build.diagnostics.push(diagnostic("flow.duplicate-id", `Two stages of flow agent '${build.id}' are named '${node.id}'. Stage ids must be unique.`));
232
+ build.diagnostics.push(diagnostic("flow.duplicate-id", `Two stages of the flow of '${build.id}' are named '${node.id}'. Stage ids must be unique.`));
233
233
  ids.add(node.id);
234
234
  }
235
235
  const code = build.code.get(node);
@@ -30,7 +30,7 @@ export function flowFrom(json, implementations = {}) {
30
30
  throw new HarnessError("agent.build-failed", `Missing flow implementation${missing.length === 1 ? "" : "s"}: ${missing.join(", ")}`);
31
31
  const unknown = Object.keys(given).filter((key) => !needs.includes(key));
32
32
  if (unknown.length)
33
- throw new HarnessError("agent.build-failed", `Flow agent '${manifest.id}' has no tool node${unknown.length === 1 ? "" : "s"} ${unknown.join(", ")}`);
33
+ throw new HarnessError("agent.build-failed", `The flow of '${manifest.id}' has no tool node${unknown.length === 1 ? "" : "s"} ${unknown.join(", ")}`);
34
34
  const bindings = {};
35
35
  for (const [id, agent] of Object.entries(agents))
36
36
  bindings[id] = agentFrom(agent, implementations.agents?.[id] ?? {}).getBinding();
@@ -6,7 +6,7 @@ export declare const AGENT_FOLDER_COMPILER = "agent-folder/1";
6
6
  * The formats this compiler builds: `agent-folder/1`, and `agent-folder/2` (ADR-100), whose
7
7
  * folder declares every engine feature it uses (`folder/engine.ts`).
8
8
  */
9
- export declare const AGENT_FOLDER_FORMATS: readonly ["agent-folder/1", "agent-folder/2", "agent-folder/3"];
9
+ export declare const AGENT_FOLDER_FORMATS: readonly ["agent-folder/1", "agent-folder/2", "agent-folder/3", "agent-folder/4"];
10
10
  export type AgentFolderFormat = (typeof AGENT_FOLDER_FORMATS)[number];
11
11
  /**
12
12
  * What a folder may hold, unless `compileAgentFolder` is given other limits (a Tenant's Runtime
@@ -2,6 +2,8 @@ import { AGENT_MANIFEST_V8_SCHEMA_VERSION, AGENT_MODEL_MAX_CHARS, AGENT_ROLE_PAT
2
2
  import { cronScheduleIssue, isTimeZone, timeZoneNames } from "../definition/cron.js";
3
3
  import { RUNTIME_SERVER } from "../plugins/index.js";
4
4
  import { enginePlugins, isFolderV3, pluginSkillNames, v3Declarations } from "./v3.js";
5
+ import { compileFormat4, folderIsV4, isFolderV4, narrowFront, narrowParts, rootSecretsOf } from "./subagent-files.js";
6
+ import { isPluginName, pluginTools } from "../plugins/index.js";
5
7
  import { DELEGATE_NAME_PATTERN } from "../definition/delegate.js";
6
8
  import { sectionGapsAt } from "../definition/sections.js";
7
9
  import { DEFAULT_HARNESS } from "../utils/harness-id.js";
@@ -18,7 +20,7 @@ export const AGENT_FOLDER_COMPILER = "agent-folder/1";
18
20
  * The formats this compiler builds: `agent-folder/1`, and `agent-folder/2` (ADR-100), whose
19
21
  * folder declares every engine feature it uses (`folder/engine.ts`).
20
22
  */
21
- export const AGENT_FOLDER_FORMATS = ["agent-folder/1", "agent-folder/2", "agent-folder/3"];
23
+ export const AGENT_FOLDER_FORMATS = ["agent-folder/1", "agent-folder/2", "agent-folder/3", "agent-folder/4"];
22
24
  /**
23
25
  * What a folder may hold, unless `compileAgentFolder` is given other limits (a Tenant's Runtime
24
26
  * limits `folderFiles`, `folderBytes` and `folderTextFileBytes`, which default to these).
@@ -135,10 +137,21 @@ function classify(path) {
135
137
  return { kind: "schema" };
136
138
  return { kind: "other" };
137
139
  }
140
+ // agent-folder/4 (ADR-164): a subagent is a file, with its flow file and schemas beside it.
141
+ if (top === "agents" && segments.length === 2) {
142
+ if (base.endsWith(".flow.json"))
143
+ return { kind: "subagent_flow" };
144
+ if (base.endsWith(".schema.json"))
145
+ return { kind: "schema" };
146
+ if (base.endsWith(".md"))
147
+ return { kind: "subagent_file" };
148
+ }
138
149
  if (top === "agents" || top === "plugins")
139
150
  return {
140
151
  code: "reserved_directory",
141
- 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",
152
+ error: top === "agents"
153
+ ? "agents/ holds one file per subagent, agents/<id>.md (agent-folder/4), or one folder per subagent, each with its AGENT.md (agent-folder/3 and older)"
154
+ : "plugins/ holds one folder per Agent Plugin, each with its plugin.json",
142
155
  };
143
156
  if (top === "instructions")
144
157
  return segments.length === 2 && base.endsWith(".md")
@@ -183,6 +196,8 @@ export function folderTextPaths(entries) {
183
196
  kind.kind === "schema" ||
184
197
  kind.kind === "flow" ||
185
198
  kind.kind === "engine_text" ||
199
+ kind.kind === "subagent_file" ||
200
+ kind.kind === "subagent_flow" ||
186
201
  (kind.kind === "skill" && entry.path.split("/").length === 3 && entry.path.endsWith(`/${SKILL_ENTRY}`));
187
202
  if (textual)
188
203
  paths.push(entry.path);
@@ -219,6 +234,12 @@ const show = (value) => JSON.stringify(value) ?? String(value);
219
234
  * compiler sets it when it compiles a folder inside another (`agents/<id>/`, a plugin's parts).
220
235
  */
221
236
  export function compileAgentFolder(input, scope) {
237
+ // agent-folder/4 (ADR-164): its subagent files, expanded into the layout format 3 compiles.
238
+ if (!scope && folderIsV4(input))
239
+ return compileFormat4(input, (expanded) => compileFolder(expanded, undefined));
240
+ return compileFolder(input, scope);
241
+ }
242
+ function compileFolder(input, scope) {
222
243
  const limits = { ...AGENT_FOLDER_LIMITS, ...input.limits };
223
244
  const diagnostics = [];
224
245
  /** The folder's format: the uploaded folder's `format`, which a folder inside it shares. */
@@ -448,6 +469,10 @@ export function compileAgentFolder(input, scope) {
448
469
  // `/x` in a folder inside another names a file of the uploaded folder (folder/nested.ts).
449
470
  if (scope && value.startsWith("/"))
450
471
  return scopedSchema(scope, value, (code, message) => error(code, message, file, field));
472
+ // In a format 4 subagent file, `./x` is beside the file, under agents/; in its copy of the
473
+ // library, it is the library file's, from the root (folder/subagent-files.ts).
474
+ if (scope && scope.role !== "plugin" && scope.engineFacts?.v4 !== undefined)
475
+ return scopedSchema(scope, file === AGENT_FILE ? `/agents/${value.replace(/^\.\//, "")}` : `/${value.replace(/^\.\//, "")}`, (code, message) => error(code, message, file, field));
451
476
  const target = value.startsWith("/") ? value.slice(1) : value.replace(/^\.\//, "");
452
477
  if (target.split("/").some((segment) => segment === ".." || segment === "")) {
453
478
  error("path_outside", `${value} leaves the folder: a path names a file inside it`, file, field);
@@ -477,23 +502,64 @@ export function compileAgentFolder(input, scope) {
477
502
  const instructions = [];
478
503
  let metadata;
479
504
  const origins = [];
505
+ /** agent-folder/4 (ADR-164): the uploaded folder is format 4, or this is one of its subagent files. */
506
+ const v4File = scope !== undefined && scope.role !== "plugin" && scope.engineFacts?.v4 !== undefined;
507
+ let v4Root = false;
508
+ /** What a format 4 subagent file, or root, keeps of what it inherits (folder/subagent-files.ts). */
509
+ let narrowing;
510
+ /** A format 4 root's frontmatter before it narrows itself: its library, which subagents inherit. */
511
+ let libraryFront;
512
+ let rootSecrets;
513
+ let libraryPlugins;
480
514
  if (agent) {
481
515
  if (!agent.hasFrontmatter)
482
516
  error("frontmatter_missing", `${AGENT_FILE} opens with frontmatter between --- lines, with name and description`, AGENT_FILE, undefined, { at: { line: 1, column: 1 } });
517
+ v4Root = !scope && isFolderV4(front.format);
518
+ if (v4Root || v4File) {
519
+ if (v4Root)
520
+ rootSecrets = rootSecretsOf(front);
521
+ if (v4Root && [...kinds.values()].includes("flow")) {
522
+ for (const key of ["tools", "disallowedTools"])
523
+ if (front[key] !== undefined) {
524
+ error("flow_refused", `${key} belongs to a model loop: a manifest driven by a flow has none, and each subagent narrows its own`, AGENT_FILE, [key], { key: true });
525
+ delete front[key];
526
+ }
527
+ }
528
+ else {
529
+ if (v4Root && (front.tools !== undefined || front.disallowedTools !== undefined)) {
530
+ libraryFront = JSON.parse(JSON.stringify(front));
531
+ delete libraryFront.tools;
532
+ delete libraryFront.disallowedTools;
533
+ }
534
+ const httpTools = [...kinds].filter(([, kind]) => kind === "tool").map(([path]) => path.slice("tools/".length, -".json".length));
535
+ const plugins = v4File
536
+ ? (scope.engineFacts.plugins ?? [])
537
+ : Array.isArray(front.plugins)
538
+ ? front.plugins.filter(isPluginName).map((name) => ({ name, tools: pluginTools(name) }))
539
+ : [];
540
+ narrowing = narrowFront(front, {
541
+ role: v4File ? "subagent" : "root",
542
+ httpTools,
543
+ plugins,
544
+ error: (code, message, path, options) => error(code, message, AGENT_FILE, path, options),
545
+ note: (code, message, path, options) => report("note", code, message, AGENT_FILE, path, options),
546
+ });
547
+ }
548
+ }
483
549
  checkKeys(AGENT_FILE, front, AGENT_KEYS);
484
550
  if (typeof front.name !== "string" || front.name === "")
485
551
  error("name_missing", "name is required: the agent manifest's name", AGENT_FILE, front.name === undefined ? undefined : ["name"]);
486
552
  else if (!isAgentManifestName(front.name))
487
553
  error("name_invalid", "name is 1-64 letters, digits, '.', '_' and '-', starting with a letter or digit", AGENT_FILE, ["name"]);
488
554
  else if (input.name !== undefined && front.name !== input.name)
489
- error("name_mismatch", `name is ${front.name}, and the folder is saved as ${input.name}: they must match`, AGENT_FILE, ["name"]);
555
+ error("name_mismatch", v4File ? `name is ${front.name}, and the file is agents/${input.name}.md: they must match` : `name is ${front.name}, and the folder is saved as ${input.name}: they must match`, AGENT_FILE, ["name"]);
490
556
  else
491
557
  name = front.name;
492
558
  if (typeof front.description !== "string" || front.description.trim() === "")
493
559
  error("description_missing", "description is required: what the agent does, in a sentence", AGENT_FILE, front.description === undefined ? undefined : ["description"]);
494
560
  else
495
561
  description = front.description.trim();
496
- if (!scope && isFolderV3(front.format)) {
562
+ if (!scope && (isFolderV3(front.format) || isFolderV4(front.format))) {
497
563
  v3 = true;
498
564
  format = 2;
499
565
  }
@@ -510,6 +576,9 @@ export function compileAgentFolder(input, scope) {
510
576
  role,
511
577
  ...(scope?.engineFacts?.plugins === undefined ? {} : { parent: scope.engineFacts.plugins }),
512
578
  });
579
+ // A format 4 root that narrows itself: its library, as it was before, is what subagents inherit.
580
+ if (libraryFront)
581
+ libraryPlugins = v3Declarations(libraryFront, { error: () => { }, computer: earlyComputer(), role: "root" })?.plugins;
513
582
  delete front.memory;
514
583
  delete front.loop;
515
584
  if (isObject(front.mcpServers)) {
@@ -519,7 +588,8 @@ export function compileAgentFolder(input, scope) {
519
588
  else
520
589
  delete front.mcpServers;
521
590
  }
522
- if (v3Plugins) {
591
+ // A flow has no model loop, so nothing to declare: its stages declare their own.
592
+ if (v3Plugins && ![...kinds.values()].includes("flow")) {
523
593
  if (v3Plugins.memory)
524
594
  front.memory = v3Plugins.memory;
525
595
  if (v3Plugins.loop)
@@ -619,6 +689,15 @@ export function compileAgentFolder(input, scope) {
619
689
  // A flow has no instructions of its own: its stages do.
620
690
  else if (agent?.hasFrontmatter && ![...kinds.values()].includes("flow"))
621
691
  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 } });
692
+ // A subagent file outside agent-folder/4 (ADR-164).
693
+ if (!v4Root && !v4File)
694
+ for (const [path, kind] of kinds)
695
+ if (kind === "subagent_file" || kind === "subagent_flow") {
696
+ const id = path.slice("agents/".length).replace(/(\.flow\.json|\.md)$/, "");
697
+ error("subagent_file", kind === "subagent_file"
698
+ ? `agents/${id}.md is a subagent file, which agent-folder/4 reads. Fix: add format: agent-folder/4 to AGENT.md (nylorun migrate folder <dir> --to 4 moves every subagent folder to a file), or write it as agents/${id}/AGENT.md`
699
+ : `${path} is a subagent's flow file, which agent-folder/4 reads. Fix: add format: agent-folder/4 to AGENT.md, or write it as agents/${id}/flow.json`, path);
700
+ }
622
701
  // --- runtime.json ----------------------------------------------------------------------
623
702
  let runtime;
624
703
  if (byPath.has(RUNTIME_FILE)) {
@@ -661,7 +740,7 @@ export function compileAgentFolder(input, scope) {
661
740
  }
662
741
  else if ([...kinds.values()].includes("flow")) {
663
742
  if (front.engine !== undefined)
664
- error("flow_refused", "engine is an agent's: set it in the AGENT.md of each agent under agents/ that uses an engine feature", AGENT_FILE, ["engine"], { key: true });
743
+ error("flow_refused", "engine belongs to a model loop: set it in the AGENT.md of each subagent under agents/ that uses an engine feature", AGENT_FILE, ["engine"], { key: true });
665
744
  }
666
745
  else {
667
746
  declared = engineDeclarations(front.engine, {
@@ -704,7 +783,8 @@ export function compileAgentFolder(input, scope) {
704
783
  format,
705
784
  computer,
706
785
  ...(format === 2 && declared ? { engine: declared.engine } : {}),
707
- ...(v3 ? { v3: true, plugins: v3Plugins?.plugins ?? [] } : {}),
786
+ ...(v3 ? { v3: true, plugins: libraryPlugins ?? v3Plugins?.plugins ?? [] } : {}),
787
+ ...(v4Root ? { v4: rootSecrets ?? { skills: [], servers: [] } } : {}),
708
788
  memory: isObject(front.memory),
709
789
  selfWake: isObject(runtime) && runtime.selfWake === true,
710
790
  };
@@ -1077,6 +1157,13 @@ export function compileAgentFolder(input, scope) {
1077
1157
  }
1078
1158
  if (tools.length > 0)
1079
1159
  harness.tools = tools;
1160
+ // agent-folder/4 (ADR-164): what a subagent file, or the root, keeps of the library.
1161
+ if (narrowing)
1162
+ narrowParts(harness, narrowing, {
1163
+ role: v4File ? "subagent" : "root",
1164
+ secrets: scope?.engineFacts?.v4 ?? { skills: [], servers: [] },
1165
+ error: (code, message, path, options) => error(code, message, AGENT_FILE, path, options),
1166
+ });
1080
1167
  // --- triggers/ -------------------------------------------------------------------------
1081
1168
  const triggers = {};
1082
1169
  /** Where each trigger's body (its prompt) starts. */
@@ -25,6 +25,12 @@ export interface EngineScopeFacts {
25
25
  readonly name: import("../plugins/index.js").PluginName;
26
26
  readonly tools: readonly string[];
27
27
  }[];
28
+ /**
29
+ * The uploaded folder is `agent-folder/4` (ADR-164): its folders under `agents/` are subagent
30
+ * files, expanded with the library. What they may not inherit unnamed: the root's skills with
31
+ * secrets and servers it gives a credential.
32
+ */
33
+ readonly v4?: import("./subagent-files.js").RootSecrets;
28
34
  }
29
35
  type Fail = (code: string, message: string, path?: readonly PropertyKey[], options?: ReportOptions) => void;
30
36
  /**
@@ -12,3 +12,5 @@ export { AGENT_FOLDER_SCHEMA_KINDS, agentFolderJsonSchemas, type AgentFolderSche
12
12
  export { applyFolderFixes, type AppliedFolderFixes } from "./fix.js";
13
13
  export { AGENT_FOLDER_V3, isFolderV3 } from "./v3.js";
14
14
  export { folderV3Edit, type FolderV3Edit } from "./migrate-v3.js";
15
+ export { AGENT_FOLDER_V4, isFolderV4 } from "./subagent-files.js";
16
+ export { folderV4Plan, type FolderV4Input, type FolderV4Plan } from "./migrate-v4.js";
@@ -12,3 +12,5 @@ export { AGENT_FOLDER_SCHEMA_KINDS, agentFolderJsonSchemas } from "./schemas.js"
12
12
  export { applyFolderFixes } from "./fix.js";
13
13
  export { AGENT_FOLDER_V3, isFolderV3 } from "./v3.js";
14
14
  export { folderV3Edit } from "./migrate-v3.js";
15
+ export { AGENT_FOLDER_V4, isFolderV4 } from "./subagent-files.js";
16
+ export { folderV4Plan } from "./migrate-v4.js";
@@ -0,0 +1,33 @@
1
+ /** A folder's file as the migration reads it: its path and hash, and its text when it is one the migration edits. */
2
+ export interface FolderV4Input {
3
+ readonly entries: readonly {
4
+ readonly path: string;
5
+ readonly sha256: string;
6
+ }[];
7
+ /** The text of a file, for `AGENT.md` files and `mcp.json` files. */
8
+ readonly text: (path: string) => string | undefined;
9
+ /**
10
+ * What each subagent has, by id, from the folder compiled as it is: its HTTP tool names, its
11
+ * Runtime plugin tools, its skills and its servers.
12
+ */
13
+ readonly subagents: ReadonlyMap<string, {
14
+ readonly tools: readonly string[];
15
+ readonly pluginTools: readonly string[];
16
+ readonly skills: readonly string[];
17
+ readonly servers: readonly string[];
18
+ }>;
19
+ }
20
+ export type FolderV4Plan = {
21
+ readonly ok: true;
22
+ /** Files to write, by path, with their text. */
23
+ readonly writes: ReadonlyMap<string, string>;
24
+ /** Files to copy, from → to. */
25
+ readonly moves: readonly (readonly [string, string])[];
26
+ /** Files to delete once the rest is written: every file of every subagent folder. */
27
+ readonly deletes: readonly string[];
28
+ } | {
29
+ readonly ok: false;
30
+ readonly reason: string;
31
+ };
32
+ /** Plans the migration of a format 3 folder to format 4. */
33
+ export declare function folderV4Plan(input: FolderV4Input): FolderV4Plan;