@nylorun/core 0.52.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,11 @@
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
+
3
9
  ## 0.52.0-beta
4
10
 
5
11
  ### Minor Changes
@@ -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)) {
@@ -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;
@@ -0,0 +1,207 @@
1
+ /**
2
+ * `agent-folder/3` → `agent-folder/4` (ADR-164): each subagent folder becomes one file,
3
+ * `agents/<id>.md`, and what it held moves into the manifest's library. `nylorun migrate folder
4
+ * <dir> --to 4` plans it here, applies it to a copy, and writes it only when the copy compiles to
5
+ * the same agent manifest.
6
+ *
7
+ * - `agents/<id>/AGENT.md` → `agents/<id>.md`, listing exactly what the subagent had: `tools`
8
+ * (its HTTP tools and Runtime plugin tools, or `[]`), and `skills` and `mcpServers` when the
9
+ * library holds more than it had. Its `plugins:` and `mcpServers.nylorun` go: a file inherits
10
+ * the root's.
11
+ * - Its `tools/`, `skills/` and `mcp.json` servers move to the root's; one the root already has, with
12
+ * the same bytes, is dropped. Under a root driven by a model loop, a tool that moves up joins the
13
+ * root's `disallowedTools`, so the root gains none.
14
+ * - `output.schema.json` → `agents/<id>.schema.json`; `flow.json` → `agents/<id>.flow.json`.
15
+ *
16
+ * It stops, naming why, on what it can't keep: a name the root holds with other bytes, a skill or
17
+ * server that would join a root driven by a model loop, instructions/, or any other file.
18
+ */
19
+ import { isMap, isSeq, parseDocument, YAMLSeq } from "yaml";
20
+ import { RUNTIME_SERVER } from "../plugins/index.js";
21
+ import { AGENT_FOLDER_V4 } from "./subagent-files.js";
22
+ /** Keeps long lines as written and lists as `[a, b]`. */
23
+ const YAML_OPTIONS = { lineWidth: 0, flowCollectionPadding: false };
24
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
25
+ function split(text) {
26
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
27
+ const bom = text.startsWith("") ? "" : "";
28
+ const lines = text.slice(bom.length).split(/\r?\n/);
29
+ if (lines[0]?.trimEnd() !== "---")
30
+ return undefined;
31
+ const end = lines.findIndex((line, index) => index > 0 && line.trimEnd() === "---");
32
+ if (end < 0)
33
+ return undefined;
34
+ return { front: lines.slice(1, end).join("\n"), body: lines.slice(end + 1).join(eol), eol, bom };
35
+ }
36
+ function join(parts, front) {
37
+ const lines = front.replace(/\n$/, "").split("\n");
38
+ return parts.bom + ["---", ...lines, "---"].join(parts.eol) + parts.eol + parts.body;
39
+ }
40
+ const flowList = (items) => {
41
+ const seq = new YAMLSeq();
42
+ seq.flow = true;
43
+ for (const item of items)
44
+ seq.add(item);
45
+ return seq;
46
+ };
47
+ /** Plans the migration of a format 3 folder to format 4. */
48
+ export function folderV4Plan(input) {
49
+ const sha = new Map(input.entries.map((entry) => [entry.path, entry.sha256]));
50
+ const flowRoot = sha.has("flow.json");
51
+ const rootText = input.text("AGENT.md");
52
+ const root = rootText === undefined ? undefined : split(rootText);
53
+ if (!root)
54
+ return { ok: false, reason: "AGENT.md has no frontmatter" };
55
+ const ids = [...new Set(input.entries.map((entry) => entry.path.split("/")).filter((segments) => segments[0] === "agents" && segments.length >= 3).map((segments) => segments[1]))].sort();
56
+ const writes = new Map();
57
+ const moves = [];
58
+ const deletes = [];
59
+ /** Library files after the migration, by path, with their hash. */
60
+ const library = new Map([...sha].filter(([path]) => path === "mcp.json" || /^(tools|skills|plugins)\//.test(path)));
61
+ const rootServers = (() => {
62
+ const text = input.text("mcp.json");
63
+ if (text === undefined)
64
+ return {};
65
+ const value = JSON.parse(text);
66
+ return isObject(value.mcpServers) ? { ...value.mcpServers } : {};
67
+ })();
68
+ const rootMcpBefore = JSON.stringify(rootServers);
69
+ const rootDenied = [];
70
+ for (const id of ids) {
71
+ const prefix = `agents/${id}/`;
72
+ const own = [...sha.keys()].filter((path) => path.startsWith(prefix)).map((path) => path.slice(prefix.length));
73
+ const where = (path) => `${prefix}${path}`;
74
+ if (sha.has(`agents/${id}.md`))
75
+ return { ok: false, reason: `agents/${id}.md already exists beside ${prefix}` };
76
+ const flow = own.includes("flow.json");
77
+ for (const path of own) {
78
+ if (path === "AGENT.md" || path === "output.schema.json" || (flow && path === "flow.json") || /^tools\/[^/]+\.json$/.test(path) || /^skills\//.test(path) || path === "mcp.json")
79
+ continue;
80
+ return {
81
+ ok: false,
82
+ reason: `${where(path)} has no place in agent-folder/4, which writes a subagent as one file: ${path.startsWith("instructions/") ? "join its instructions into the body of AGENT.md" : path.startsWith("agents/") ? "move a subagent driven by a flow's stages beside it by hand" : "move or remove it"} first`,
83
+ };
84
+ }
85
+ // HTTP tools: into the root's tools/.
86
+ for (const path of own.filter((item) => item.startsWith("tools/"))) {
87
+ const there = library.get(path);
88
+ if (there === sha.get(where(path)))
89
+ continue;
90
+ if (there !== undefined)
91
+ return { ok: false, reason: `${where(path)} and the root's ${path} differ: a library has one tool of a name. Rename one first` };
92
+ library.set(path, sha.get(where(path)));
93
+ moves.push([where(path), path]);
94
+ if (!flowRoot)
95
+ rootDenied.push(path.slice("tools/".length, -".json".length));
96
+ }
97
+ // Skills: into the root's skills/, which a root driven by a model loop would gain.
98
+ const skillNames = [...new Set(own.filter((item) => item.startsWith("skills/")).map((item) => item.split("/")[1]))];
99
+ for (const name of skillNames) {
100
+ const mine = own.filter((item) => item.startsWith(`skills/${name}/`));
101
+ const theirs = [...library.keys()].filter((path) => path.startsWith(`skills/${name}/`));
102
+ const same = theirs.length === mine.length && mine.every((path) => library.get(path) === sha.get(where(path)));
103
+ if (same)
104
+ continue;
105
+ if (theirs.length > 0)
106
+ return { ok: false, reason: `${prefix}skills/${name}/ and the root's skills/${name}/ differ: a library has one skill of a name. Rename one first` };
107
+ if (!flowRoot)
108
+ return { ok: false, reason: `${prefix}skills/${name}/ would join the root's skills, and the root agent would gain it: agent-folder/4 has no skill only a subagent sees. Keep this folder on agent-folder/3, or move the skill to the root first` };
109
+ for (const path of mine) {
110
+ library.set(path, sha.get(where(path)));
111
+ moves.push([where(path), path]);
112
+ }
113
+ }
114
+ // Servers: into the root's mcp.json, likewise.
115
+ if (own.includes("mcp.json")) {
116
+ const value = JSON.parse(input.text(where("mcp.json")) ?? "{}");
117
+ for (const [key, server] of Object.entries(isObject(value.mcpServers) ? value.mcpServers : {})) {
118
+ if (key in rootServers) {
119
+ if (JSON.stringify(rootServers[key]) !== JSON.stringify(server))
120
+ return { ok: false, reason: `${prefix}mcp.json and the root's mcp.json declare ${key} differently: a library has one server of a name. Rename one first` };
121
+ continue;
122
+ }
123
+ if (!flowRoot)
124
+ return { ok: false, reason: `${prefix}mcp.json's ${key} would join the root's servers, and the root agent would gain it: agent-folder/4 has no server only a subagent sees. Keep this folder on agent-folder/3, or move the server to the root first` };
125
+ rootServers[key] = server;
126
+ }
127
+ }
128
+ // The file.
129
+ const text = input.text(where("AGENT.md"));
130
+ const parts = text === undefined ? undefined : split(text);
131
+ if (!parts)
132
+ return { ok: false, reason: `${where("AGENT.md")} has no frontmatter` };
133
+ const doc = parseDocument(parts.front);
134
+ const data = (doc.toJS() ?? {});
135
+ doc.delete("plugins");
136
+ if (isMap(doc.get("mcpServers"))) {
137
+ doc.deleteIn(["mcpServers", RUNTIME_SERVER]);
138
+ if (doc.get("mcpServers").items.length === 0)
139
+ doc.delete("mcpServers");
140
+ }
141
+ if (flow) {
142
+ doc.set("flow", `./${id}.flow.json`);
143
+ moves.push([where("flow.json"), `agents/${id}.flow.json`]);
144
+ }
145
+ else {
146
+ const had = input.subagents.get(id);
147
+ if (!had)
148
+ return { ok: false, reason: `${prefix} did not compile as a subagent` };
149
+ doc.set("tools", flowList([...had.tools, ...had.pluginTools]));
150
+ if ([...library.keys()].some((path) => path.startsWith("skills/") || path.startsWith("plugins/"))) {
151
+ doc.delete("skills");
152
+ doc.set("skills", flowList(had.skills));
153
+ }
154
+ else if (isMap(doc.get("skills")) || isSeq(doc.get("skills")))
155
+ doc.delete("skills");
156
+ const anyServers = Object.keys(rootServers).length > 0 || [...library.keys()].some((path) => path.startsWith("plugins/"));
157
+ if (anyServers) {
158
+ const settings = isObject(data.mcpServers) ? data.mcpServers : {};
159
+ const kept = {};
160
+ for (const key of had.servers)
161
+ kept[key] = isObject(settings[key]) ? settings[key] : {};
162
+ doc.delete("mcpServers");
163
+ doc.set("mcpServers", doc.createNode(kept));
164
+ }
165
+ }
166
+ if (data.outputSchema !== undefined) {
167
+ const value = String(data.outputSchema);
168
+ if (value === "./output.schema.json" || value === "output.schema.json") {
169
+ doc.set("outputSchema", `./${id}.schema.json`);
170
+ moves.push([where("output.schema.json"), `agents/${id}.schema.json`]);
171
+ }
172
+ else if (!value.startsWith("/"))
173
+ return { ok: false, reason: `${where("AGENT.md")}'s outputSchema ${value} is a path inside the folder: write it from the root (/schemas/...) first` };
174
+ }
175
+ else if (own.includes("output.schema.json"))
176
+ return { ok: false, reason: `${where("output.schema.json")} is named by nothing: remove it first` };
177
+ writes.set(`agents/${id}.md`, join(parts, doc.toString(YAML_OPTIONS)));
178
+ for (const path of own)
179
+ deletes.push(where(path));
180
+ }
181
+ // The root: format 4, and the tools that moved up kept out of its own loop.
182
+ // Edited line by line, so the rest of the root's frontmatter stays as written.
183
+ const lines = root.front.split("\n");
184
+ const formatAt = lines.findIndex((line) => /^format\s*:/.test(line));
185
+ if (formatAt >= 0)
186
+ lines[formatAt] = `format: ${AGENT_FOLDER_V4}`;
187
+ else
188
+ lines.unshift(`format: ${AGENT_FOLDER_V4}`);
189
+ let front = lines.join("\n");
190
+ if (rootDenied.length > 0) {
191
+ const doc = parseDocument(front);
192
+ const existing = doc.get("disallowedTools");
193
+ if (existing === undefined)
194
+ front = `${front.replace(/\n$/, "")}\ndisallowedTools: [${[...new Set(rootDenied)].join(", ")}]`;
195
+ else {
196
+ doc.set("disallowedTools", flowList([...new Set([...(isSeq(existing) ? existing.toJSON() : []), ...rootDenied])]));
197
+ front = doc.toString(YAML_OPTIONS);
198
+ }
199
+ }
200
+ writes.set("AGENT.md", join(root, front));
201
+ if (JSON.stringify(rootServers) !== rootMcpBefore) {
202
+ const text = input.text("mcp.json");
203
+ const value = text === undefined ? {} : JSON.parse(text);
204
+ writes.set("mcp.json", `${JSON.stringify({ ...value, mcpServers: rootServers }, null, 2)}\n`);
205
+ }
206
+ return { ok: true, writes, moves, deletes };
207
+ }
@@ -313,7 +313,12 @@ function composeFlow(ctx) {
313
313
  });
314
314
  }
315
315
  const noted = new Set();
316
+ // agent-folder/4 (ADR-164): a flow root's mcp.json, skills/, plugins/ and tools are the library
317
+ // its stages draw on, not its own.
318
+ const library = !ctx.scope && ctx.engineFacts().v4 !== undefined;
316
319
  for (const [path, kind] of ctx.kinds) {
320
+ if (library)
321
+ break;
317
322
  const top = path.split("/").slice(0, 2).join("/");
318
323
  if (kind === "instructions")
319
324
  refuse("A manifest driven by a flow has no instructions: move this to the subagent under agents/ that needs it", path);
@@ -357,7 +362,7 @@ function composeFlow(ctx) {
357
362
  tools.set(String(tool.name), tool);
358
363
  const translated = translateFlow(tree, { agentIds: namespace.ids, agent: (id) => namespace.resolve(id), used: namespace.used, tools }, (code, message, file, path, options) => ctx.report("error", code, message, file, path, options), ctx.suggest);
359
364
  for (const name of tools.keys())
360
- if (!translated.toolsUsed.has(name))
365
+ if (!library && !translated.toolsUsed.has(name))
361
366
  ctx.report("error", "tool_unused", `No node of flow.json names ${name}: a flow holds only the tools its nodes name`, `tools/${name}.json`);
362
367
  if (isRoot) {
363
368
  const unused = namespace.ids.filter((id) => !namespace.used.has(id));
@@ -55,11 +55,12 @@ function fromZod(schema, defs, description) {
55
55
  * names one document for good): `AGENT.md` took `model` (Host feature `agent-model`), published
56
56
  * as `agent-md.1.json`, then `format: agent-folder/2` and `engine` (ADR-100), as `agent-md.2.json`,
57
57
  * then `engine.triggers` (D83), as `agent-md.3.json`, then `format: agent-folder/3` and
58
- * `plugins` (ADR-106), as `agent-md.4.json`, then `roles` (ADR-154), as `agent-md.5.json`;
58
+ * `plugins` (ADR-106), as `agent-md.4.json`, then `roles` (ADR-154), as `agent-md.5.json`, then
59
+ * `format: agent-folder/4` and a subagent file's keys (ADR-164), as `agent-md.6.json`;
59
60
  * `runtime.json` took a secret slot's `toolPrefix` (Host feature `secret-routing`), published as
60
61
  * `runtime.1.json`, then `limits.triggers` (D83), as `runtime.2.json`.
61
62
  */
62
- const REVISIONS = { "agent-md": 5, runtime: 2 };
63
+ const REVISIONS = { "agent-md": 6, runtime: 2 };
63
64
  /** One document: its `$id` from its kind, then the body, then the `$defs` its parts named. */
64
65
  function document(kind, title, description, body, defs) {
65
66
  const revision = REVISIONS[kind];
@@ -99,8 +100,8 @@ function agentMd() {
99
100
  name: { type: "string", pattern: AGENT_MANIFEST_NAME_PATTERN.source, description: "The agent manifest's name, the folder's when it is saved under one" },
100
101
  description: { type: "string", minLength: 1, description: "What the agent does, in a sentence" },
101
102
  format: {
102
- enum: [1, 2, 3, "agent-folder/1", "agent-folder/2", "agent-folder/3"],
103
- description: "The folder's format: agent-folder/1 (or 1, the default), which gets every engine feature by default; agent-folder/2 (or 2), which declares each in engine; or agent-folder/3 (or 3), which declares the Runtime's features as plugins",
103
+ enum: [1, 2, 3, 4, "agent-folder/1", "agent-folder/2", "agent-folder/3", "agent-folder/4"],
104
+ description: "The folder's format: agent-folder/1 (or 1, the default), which gets every engine feature by default; agent-folder/2 (or 2), which declares each in engine; agent-folder/3 (or 3), which declares the Runtime's features as plugins; or agent-folder/4 (or 4), agent-folder/3 with each subagent one file, agents/<id>.md, drawing on the manifest's library",
104
105
  },
105
106
  harness: fromZod(HarnessIdSchema, defs, "The harness that runs the loop: nylorun (ours, the default) or a custom harness's id"),
106
107
  inputSchema: ref("JsonSchemaOrPath", "A flow's input (a folder with flow.json); an agent's input is the message"),
@@ -168,7 +169,26 @@ function agentMd() {
168
169
  },
169
170
  metadata: { type: "object", description: "The manifest's metadata, as it is" },
170
171
  };
171
- return document("agent-md", "Nylorun agent folder: AGENT.md frontmatter", "The frontmatter of an agent folder's AGENT.md; the body below it is the instructions", { type: "object", properties, required: ["name", "description"], additionalProperties: false }, defs);
172
+ // agent-folder/4 (ADR-164): the narrowing keys a subagent file (agents/<id>.md) and the root take.
173
+ const toolNames = {
174
+ anyOf: [{ type: "array", items: { type: "string" } }, { type: "string" }],
175
+ };
176
+ const fileProperties = {
177
+ tools: { ...toolNames, description: "agent-folder/4: the only HTTP tools and Runtime plugin tools of the manifest's library this agent gets, by name ([read, grep, glob]); left out, a subagent file gets every one a subagent can use" },
178
+ disallowedTools: { ...toolNames, description: "agent-folder/4: library tools this agent does not get, by name" },
179
+ flow: { type: "string", description: "agent-folder/4, a subagent file: the flow file that drives it (./research.flow.json); its body is then empty" },
180
+ readonly: { type: "boolean", description: "agent-folder/4, a subagent file (Cursor's key): true reads as tools: [read, grep, glob] when tools is left out" },
181
+ };
182
+ return document("agent-md", "Nylorun agent folder: AGENT.md frontmatter", "The frontmatter of an agent folder's AGENT.md, or of a subagent file (agents/<id>.md, agent-folder/4); the body below it is the instructions", {
183
+ type: "object",
184
+ properties: {
185
+ ...properties,
186
+ skills: { anyOf: [properties.skills, { type: "array", items: { type: "string" }, description: "agent-folder/4, a subagent file: the only skills of the manifest's library it gets, by name" }] },
187
+ ...fileProperties,
188
+ },
189
+ required: ["name", "description"],
190
+ additionalProperties: false,
191
+ }, defs);
172
192
  }
173
193
  /** A trigger has exactly one of schedule, at and webhook (`TriggerSchema` refines it), and timezone goes with schedule. */
174
194
  const ONE_TRIGGER_KIND = [
@@ -0,0 +1,106 @@
1
+ /**
2
+ * `agent-folder/4` (ADR-164, D97): a subagent is one file, `agents/<id>.md`, and the manifest's
3
+ * `tools/`, `skills/`, `mcp.json`, `plugins/` and Runtime plugins are its **library**, which every
4
+ * model loop in it draws on: the root's own, and each subagent's, which inherits it and narrows it
5
+ * with `tools`, `disallowedTools`, `skills` and `mcpServers`.
6
+ *
7
+ * ```markdown
8
+ * ---
9
+ * name: history
10
+ * description: Searches the person's past work.
11
+ * tools: [search_work, get_task]
12
+ * ---
13
+ * You find earlier work for a bot…
14
+ * ```
15
+ *
16
+ * The compiler keeps every check it has by **expanding** format 4 into the layout format 3 already
17
+ * compiles: each `agents/<id>.md` becomes a virtual `agents/<id>/` holding the file's bytes as its
18
+ * `AGENT.md` and a copy of the library (the same bytes and hashes), or, for a file with `flow:`,
19
+ * its flow file and the library tools the flow names. The subagent's compile then narrows what it
20
+ * inherited (`narrowFront`, `narrowParts`), and every diagnostic is moved back to the file people
21
+ * wrote (`compileFormat4`). Pure, like the compiler.
22
+ */
23
+ import type { CompileAgentFolderInput, CompiledAgentFolder } from "./compile.js";
24
+ import { PLUGIN_NAMES, pluginTools, type PluginName } from "../plugins/index.js";
25
+ import type { ReportOptions } from "./context.js";
26
+ /** The format name a v4 folder writes. */
27
+ export declare const AGENT_FOLDER_V4 = "agent-folder/4";
28
+ /** Whether `value` names the v4 format: `agent-folder/4` or `4`. */
29
+ export declare function isFolderV4(value: unknown): boolean;
30
+ /** The keys a subagent file adds to `AGENT.md`'s, and the root's in format 4. */
31
+ export declare const SUBAGENT_FILE_KEYS: readonly ["tools", "disallowedTools", "flow", "readonly"];
32
+ /** The root's own narrowing keys in format 4. */
33
+ export declare const ROOT_V4_KEYS: readonly ["tools", "disallowedTools"];
34
+ /**
35
+ * Keys Claude Code and Cursor write that mean nothing here: noted and ignored, so their files drop
36
+ * in. `memory` is one only as a string (Claude Code's `user`, `project` or `local`).
37
+ */
38
+ export declare const HOST_KEYS: readonly ["model", "color", "permissionMode", "hooks", "maxTurns", "background", "isolation", "effort", "initialPrompt", "omitClaudeMd", "autoCompactWindow", "experimental", "is_background"];
39
+ /** Claude Code's tool names that are ours under another spelling. */
40
+ export declare const CLAUDE_TOOL_ALIASES: Readonly<Record<string, string>>;
41
+ /** The Runtime plugins only the root agent uses: a subagent never inherits them, and names their tools only with an error. */
42
+ export declare const ROOT_ONLY_PLUGINS: readonly PluginName[];
43
+ /** Whether the uploaded folder's `AGENT.md` names format 4, read quietly. */
44
+ export declare function folderIsV4(input: CompileAgentFolderInput): boolean;
45
+ /** A subagent file's id from its path, or undefined: `agents/<id>.md`. */
46
+ export declare function subagentFileId(path: string): string | undefined;
47
+ /** The path `flow:` names, from the file at `agents/<id>.md`: `./x` and `x` from `agents/`, `/x` from the root. */
48
+ export declare function flowPathOf(value: unknown): string | undefined;
49
+ /**
50
+ * Compiles a format 4 folder: expands its subagent files, compiles the result as `compile` does a
51
+ * format 3 folder, and moves each diagnostic back to the file people wrote.
52
+ */
53
+ export declare function compileFormat4(input: CompileAgentFolderInput, compile: (input: CompileAgentFolderInput) => CompiledAgentFolder): CompiledAgentFolder;
54
+ /** What a subagent file, or a format 4 root, keeps of what it inherits. Undefined: everything. */
55
+ export interface Narrowing {
56
+ /** The HTTP tools it keeps, by name; undefined keeps every one. */
57
+ readonly http?: ReadonlySet<string>;
58
+ /** HTTP tools it drops. */
59
+ readonly httpDenied: ReadonlySet<string>;
60
+ /** The skills it keeps; undefined keeps every one it may have. */
61
+ readonly skills?: readonly {
62
+ readonly name: string;
63
+ readonly index: number;
64
+ }[];
65
+ /** The servers it keeps: `mcpServers`' keys; undefined keeps every one it may have. */
66
+ readonly servers?: readonly string[];
67
+ /** A subagent file driven by a flow (`flow:`). */
68
+ readonly flow: boolean;
69
+ }
70
+ /** What `narrowFront` needs to know. */
71
+ export interface NarrowOptions {
72
+ readonly role: "root" | "subagent";
73
+ /** The HTTP tools this folder (or the expansion's copy of the library) holds. */
74
+ readonly httpTools: readonly string[];
75
+ /** The Runtime plugins to inherit from: the parent's (a subagent's), or the root's own. */
76
+ readonly plugins: readonly {
77
+ readonly name: PluginName;
78
+ readonly tools: readonly string[];
79
+ }[];
80
+ readonly error: (code: string, message: string, path?: readonly PropertyKey[], options?: ReportOptions) => void;
81
+ readonly note: (code: string, message: string, path?: readonly PropertyKey[], options?: ReportOptions) => void;
82
+ }
83
+ /**
84
+ * Reads and strips the format 4 keys of `front` (a subagent file's, or a v4 root's), noting other
85
+ * hosts' keys, and writes the Runtime `plugins:` and `mcpServers.nylorun` its tools leave on, so the
86
+ * format 3 compiler that follows sees a folder it knows. Returns what it keeps of the rest.
87
+ */
88
+ export declare function narrowFront(front: Record<string, unknown>, options: NarrowOptions): Narrowing;
89
+ /** What a subagent file may not inherit unnamed: the root's skills with secrets and servers with a credential. */
90
+ export interface RootSecrets {
91
+ readonly skills: readonly string[];
92
+ readonly servers: readonly string[];
93
+ }
94
+ /** The root's skills with secrets and plugin servers it gives a credential, read from its frontmatter. */
95
+ export declare function rootSecretsOf(front: Record<string, unknown>): RootSecrets;
96
+ /**
97
+ * Keeps, of the HTTP tools, skills and servers a subagent file inherited (or a v4 root holds),
98
+ * what its narrowing allows. A subagent also drops the root's skills with secrets and servers with
99
+ * a credential unless it names them, which then fail the checks that follow.
100
+ */
101
+ export declare function narrowParts(harness: Record<string, unknown>, narrowing: Narrowing, options: {
102
+ readonly role: "root" | "subagent";
103
+ readonly secrets: RootSecrets;
104
+ readonly error: (code: string, message: string, path?: readonly PropertyKey[], options?: ReportOptions) => void;
105
+ }): void;
106
+ export { PLUGIN_NAMES, pluginTools };
@@ -0,0 +1,440 @@
1
+ import { parseMarkdown } from "./frontmatter.js";
2
+ import { PLUGIN_NAMES, pluginOfTool, pluginTools, RUNTIME_SERVER } from "../plugins/index.js";
3
+ import { suggestion } from "./suggest.js";
4
+ /** The format name a v4 folder writes. */
5
+ export const AGENT_FOLDER_V4 = "agent-folder/4";
6
+ /** Whether `value` names the v4 format: `agent-folder/4` or `4`. */
7
+ export function isFolderV4(value) {
8
+ return value === 4 || value === AGENT_FOLDER_V4;
9
+ }
10
+ /** The keys a subagent file adds to `AGENT.md`'s, and the root's in format 4. */
11
+ export const SUBAGENT_FILE_KEYS = ["tools", "disallowedTools", "flow", "readonly"];
12
+ /** The root's own narrowing keys in format 4. */
13
+ export const ROOT_V4_KEYS = ["tools", "disallowedTools"];
14
+ /**
15
+ * Keys Claude Code and Cursor write that mean nothing here: noted and ignored, so their files drop
16
+ * in. `memory` is one only as a string (Claude Code's `user`, `project` or `local`).
17
+ */
18
+ export const HOST_KEYS = [
19
+ "model",
20
+ "color",
21
+ "permissionMode",
22
+ "hooks",
23
+ "maxTurns",
24
+ "background",
25
+ "isolation",
26
+ "effort",
27
+ "initialPrompt",
28
+ "omitClaudeMd",
29
+ "autoCompactWindow",
30
+ "experimental",
31
+ "is_background",
32
+ ];
33
+ /** Claude Code's tool names that are ours under another spelling. */
34
+ export const CLAUDE_TOOL_ALIASES = { Read: "read", Grep: "grep", Glob: "glob", Write: "write", Edit: "edit", Bash: "bash" };
35
+ /** Claude Code's other tool names: noted and ignored. */
36
+ const CLAUDE_TOOLS = ["WebFetch", "WebSearch", "Agent", "Task", "Skill", "TodoWrite", "NotebookEdit", "NotebookRead", "MultiEdit", "LS", "BashOutput", "KillShell", "KillBash", "ExitPlanMode", "SlashCommand", "ListMcpResourcesTool", "ReadMcpResourceTool"];
37
+ /** The Runtime plugins only the root agent uses: a subagent never inherits them, and names their tools only with an error. */
38
+ export const ROOT_ONLY_PLUGINS = ["nylorun-triggers", "nylorun-plan", "nylorun-interactions"];
39
+ /** The Runtime plugin a subagent inherits only when it names its tool. */
40
+ const NAMED_ONLY_PLUGINS = ["nylorun-memory"];
41
+ const READONLY_TOOLS = ["read", "grep", "glob"];
42
+ const AGENT_FILE = "AGENT.md";
43
+ const FLOW_FILE = "flow.json";
44
+ const decoder = new TextDecoder("utf-8", { fatal: true });
45
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
46
+ const compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
47
+ function textOf(bytes) {
48
+ if (!bytes)
49
+ return undefined;
50
+ try {
51
+ return decoder.decode(bytes).replace(/^/, "");
52
+ }
53
+ catch {
54
+ return undefined;
55
+ }
56
+ }
57
+ function frontOf(bytes) {
58
+ const text = textOf(bytes);
59
+ if (text === undefined)
60
+ return undefined;
61
+ const result = parseMarkdown(text);
62
+ return result.ok ? result.data : undefined;
63
+ }
64
+ function jsonOf(bytes) {
65
+ const text = textOf(bytes);
66
+ if (text === undefined)
67
+ return undefined;
68
+ try {
69
+ return JSON.parse(text);
70
+ }
71
+ catch {
72
+ return undefined;
73
+ }
74
+ }
75
+ /** Whether the uploaded folder's `AGENT.md` names format 4, read quietly. */
76
+ export function folderIsV4(input) {
77
+ return isFolderV4(frontOf(input.files.get(AGENT_FILE))?.format);
78
+ }
79
+ /** A subagent file's id from its path, or undefined: `agents/<id>.md`. */
80
+ export function subagentFileId(path) {
81
+ const match = /^agents\/([^/]+)\.md$/.exec(path);
82
+ return match?.[1];
83
+ }
84
+ /** The path `flow:` names, from the file at `agents/<id>.md`: `./x` and `x` from `agents/`, `/x` from the root. */
85
+ export function flowPathOf(value) {
86
+ if (typeof value !== "string" || value === "")
87
+ return undefined;
88
+ const target = value.startsWith("/") ? value.slice(1) : `agents/${value.replace(/^\.\//, "")}`;
89
+ return target.split("/").some((segment) => segment === "" || segment === "." || segment === "..") ? undefined : target;
90
+ }
91
+ /** The ids a flow's nodes name as `agent` and the names they name as `tool`. */
92
+ function flowNames(tree) {
93
+ const agents = new Set();
94
+ const tools = new Set();
95
+ const walk = (value) => {
96
+ if (Array.isArray(value))
97
+ value.forEach(walk);
98
+ else if (isObject(value)) {
99
+ if (typeof value.agent === "string")
100
+ agents.add(value.agent);
101
+ if (typeof value.tool === "string")
102
+ tools.add(value.tool);
103
+ Object.values(value).forEach(walk);
104
+ }
105
+ };
106
+ walk(tree);
107
+ return { agents, tools };
108
+ }
109
+ const isLibrary = (path) => path === "mcp.json" || /^(tools|skills|plugins)\//.test(path);
110
+ /**
111
+ * Compiles a format 4 folder: expands its subagent files, compiles the result as `compile` does a
112
+ * format 3 folder, and moves each diagnostic back to the file people wrote.
113
+ */
114
+ export function compileFormat4(input, compile) {
115
+ const byPath = new Map(input.entries.map((entry) => [entry.path, entry]));
116
+ const library = input.entries.filter((entry) => isLibrary(entry.path));
117
+ const ids = input.entries.map((entry) => subagentFileId(entry.path)).filter((id) => id !== undefined).sort(compare);
118
+ const fronts = new Map(ids.map((id) => [id, frontOf(input.files.get(`agents/${id}.md`)) ?? {}]));
119
+ const flowRoot = byPath.has(FLOW_FILE);
120
+ const entries = [];
121
+ const files = new Map(input.files);
122
+ const extra = [];
123
+ /** Where each subagent's flow file is, by id. */
124
+ const flows = new Map();
125
+ // A folder under agents/ is format 3's: refused, and left out of the expansion.
126
+ const folders = new Set();
127
+ for (const entry of input.entries) {
128
+ const segments = entry.path.split("/");
129
+ if (segments[0] === "agents" && segments.length >= 3) {
130
+ if (!folders.has(segments[1]))
131
+ extra.push({
132
+ severity: "error",
133
+ code: "subagent_folder",
134
+ message: `agents/${segments[1]}/ is a subagent folder, which agent-folder/4 writes as one file, agents/${segments[1]}.md, drawing on the manifest's tools/, skills/ and mcp.json. Fix: run nylorun migrate folder <dir> --to 4`,
135
+ file: `agents/${segments[1]}/${byPath.has(`agents/${segments[1]}/AGENT.md`) ? AGENT_FILE : segments.slice(2).join("/")}`,
136
+ });
137
+ folders.add(segments[1]);
138
+ continue;
139
+ }
140
+ entries.push(entry);
141
+ }
142
+ const add = (path, source) => {
143
+ if (entries.some((entry) => entry.path === path))
144
+ return;
145
+ entries.push({ path, size: source.size, sha256: source.sha256 });
146
+ const bytes = input.files.get(source.path);
147
+ if (bytes)
148
+ files.set(path, bytes);
149
+ };
150
+ /** Expands one subagent file at `prefix` (`agents/<id>/`); `nested` is a flow subagent's own agents/ under a root driven by a model loop. */
151
+ const expand = (prefix, id, namespace) => {
152
+ const source = byPath.get(`agents/${id}.md`);
153
+ if (!source)
154
+ return;
155
+ add(`${prefix}${AGENT_FILE}`, source);
156
+ const front = fronts.get(id) ?? {};
157
+ if (front.flow === undefined) {
158
+ for (const entry of library)
159
+ add(prefix + entry.path, entry);
160
+ return;
161
+ }
162
+ const flowPath = flowPathOf(front.flow);
163
+ const flowEntry = flowPath === undefined ? undefined : byPath.get(flowPath);
164
+ if (!flowEntry || !flowPath)
165
+ return;
166
+ flows.set(id, flowPath);
167
+ add(`${prefix}${FLOW_FILE}`, flowEntry);
168
+ const names = flowNames(jsonOf(input.files.get(flowPath)));
169
+ for (const tool of names.tools) {
170
+ const entry = byPath.get(`tools/${tool}.json`);
171
+ if (entry)
172
+ add(`${prefix}tools/${tool}.json`, entry);
173
+ }
174
+ // Its stages: the root's, when the root is a flow; else its own agents/, from the sibling files.
175
+ if (namespace === undefined)
176
+ return;
177
+ for (const stage of names.agents)
178
+ if (fronts.has(stage) && !entries.some((entry) => entry.path === `${namespace}${stage}/${AGENT_FILE}`))
179
+ expand(`${namespace}${stage}/`, stage, namespace);
180
+ };
181
+ for (const id of ids) {
182
+ const front = fronts.get(id) ?? {};
183
+ const prefix = `agents/${id}/`;
184
+ expand(prefix, id, front.flow !== undefined && !flowRoot ? `${prefix}agents/` : undefined);
185
+ }
186
+ const compiled = compile({ ...input, entries, files });
187
+ /** A path of the expansion, as the folder people wrote names it. */
188
+ const real = (path) => {
189
+ let rest = path;
190
+ let id;
191
+ for (;;) {
192
+ const match = /^agents\/([^/]+)\/(.*)$/.exec(rest);
193
+ if (!match || !fronts.has(match[1]))
194
+ break;
195
+ id = match[1];
196
+ rest = match[2];
197
+ }
198
+ if (id === undefined) {
199
+ const bare = /^agents\/([^/]+)$/.exec(path)?.[1];
200
+ return bare !== undefined && fronts.has(bare) ? `agents/${bare}.md` : path;
201
+ }
202
+ if (rest === AGENT_FILE || rest === "")
203
+ return `agents/${id}.md`;
204
+ if (rest === FLOW_FILE)
205
+ return flows.get(id) ?? `agents/${id}.md`;
206
+ return rest;
207
+ };
208
+ const seen = new Set();
209
+ const diagnostics = [];
210
+ for (const item of [...extra, ...compiled.diagnostics]) {
211
+ const moved = {
212
+ ...item,
213
+ ...(item.file === undefined ? {} : { file: real(item.file) }),
214
+ ...(item.fix === undefined ? {} : { fix: { ...item.fix, file: real(item.fix.file) } }),
215
+ };
216
+ const key = JSON.stringify([moved.severity, moved.code, moved.message, moved.file, moved.line, moved.column]);
217
+ if (seen.has(key))
218
+ continue;
219
+ seen.add(key);
220
+ diagnostics.push(moved);
221
+ }
222
+ const order = { error: 0, warning: 1, info: 2, note: 3 };
223
+ diagnostics.sort((a, b) => order[a.severity] - order[b.severity] || compare(a.file ?? "", b.file ?? "") || (a.line ?? 0) - (b.line ?? 0) || (a.column ?? 0) - (b.column ?? 0));
224
+ const failed = diagnostics.some((item) => item.severity === "error");
225
+ return { ...(failed || !compiled.manifest ? {} : { manifest: compiled.manifest }), diagnostics, compiler: AGENT_FOLDER_V4 };
226
+ }
227
+ /** A tool list as written: a YAML list, or a comma-separated string as Claude Code writes it. */
228
+ function namesOf(value) {
229
+ if (typeof value === "string")
230
+ return value
231
+ .split(",")
232
+ .map((name) => name.trim())
233
+ .filter((name) => name !== "")
234
+ .map((name) => ({ name, index: -1 }));
235
+ if (Array.isArray(value) && value.every((item) => typeof item === "string"))
236
+ return value.map((name, index) => ({ name: name.trim(), index }));
237
+ return undefined;
238
+ }
239
+ /**
240
+ * Reads and strips the format 4 keys of `front` (a subagent file's, or a v4 root's), noting other
241
+ * hosts' keys, and writes the Runtime `plugins:` and `mcpServers.nylorun` its tools leave on, so the
242
+ * format 3 compiler that follows sees a folder it knows. Returns what it keeps of the rest.
243
+ */
244
+ export function narrowFront(front, options) {
245
+ const { role, error, note } = options;
246
+ const subagent = role === "subagent";
247
+ if (subagent) {
248
+ for (const key of HOST_KEYS)
249
+ if (front[key] !== undefined) {
250
+ note("host_key", `${key} is a key other hosts write (Claude Code, Cursor), with no meaning here: ignored`, [key], { key: true });
251
+ delete front[key];
252
+ }
253
+ if (typeof front.memory === "string") {
254
+ note("host_key", "memory as a string is Claude Code's memory directory, with no meaning here: ignored. A subagent may view the Agent's memories when the root has them", ["memory"], { key: true });
255
+ delete front.memory;
256
+ }
257
+ }
258
+ const flow = subagent && front.flow !== undefined;
259
+ if (flow && typeof front.flow !== "string")
260
+ error("value_invalid", "flow is the path of the subagent's flow file, such as ./research.flow.json", ["flow"]);
261
+ if (flow)
262
+ for (const key of ["tools", "disallowedTools", "skills", "mcpServers", "readonly", "plugins"])
263
+ if (front[key] !== undefined)
264
+ error("flow_refused", `${key} belongs to a model loop: a subagent driven by a flow has none of its own, and its stages each have theirs`, [key], { key: true });
265
+ delete front.flow;
266
+ if (flow) {
267
+ for (const key of ["tools", "disallowedTools", "skills", "mcpServers", "readonly", "plugins"])
268
+ delete front[key];
269
+ return { httpDenied: new Set(), flow: true };
270
+ }
271
+ // The servers it names, before the Runtime's own (`nylorun`) is touched below: its allowlist.
272
+ const servers = subagent && isObject(front.mcpServers) ? Object.keys(front.mcpServers).filter((key) => key !== RUNTIME_SERVER) : undefined;
273
+ // tools and disallowedTools: HTTP tools and the Runtime plugins' tools, by name.
274
+ const known = [...new Set([...options.httpTools, ...options.plugins.flatMap((plugin) => plugin.tools)])];
275
+ const read = (key) => {
276
+ const value = front[key];
277
+ delete front[key];
278
+ if (value === undefined)
279
+ return undefined;
280
+ const names = namesOf(value);
281
+ if (!names) {
282
+ error("value_invalid", `${key} is a list of tool names, such as [read, grep, glob]`, [key]);
283
+ return [];
284
+ }
285
+ const kept = [];
286
+ for (const { name, index } of names) {
287
+ const at = index < 0 ? [key] : [key, index];
288
+ const alias = CLAUDE_TOOL_ALIASES[name];
289
+ if (alias !== undefined) {
290
+ note("tool_alias", `${name} is Claude Code's name for ${alias}: read as ${alias}. Fix: write ${alias}`, at);
291
+ if (known.includes(alias))
292
+ kept.push(alias);
293
+ else
294
+ error("library_unknown", `${alias} is not a tool this agent can have: its library holds ${known.join(", ") || "none"}`, at);
295
+ continue;
296
+ }
297
+ if (CLAUDE_TOOLS.includes(name) || name.startsWith("mcp__")) {
298
+ note("host_key", `${name} is Claude Code's tool name, with no meaning here: ignored${name.startsWith("mcp__") ? ". An MCP server's tools are narrowed with mcpServers" : ""}`, at);
299
+ continue;
300
+ }
301
+ if (!known.includes(name)) {
302
+ const close = suggestion(name, known);
303
+ error("library_unknown", `No tool ${name} is in the manifest's library (tools/ and the Runtime plugins it declares).${close ? ` Did you mean '${close}'?` : ""}`, at);
304
+ continue;
305
+ }
306
+ const plugin = pluginOfTool(name);
307
+ if (subagent && plugin && ROOT_ONLY_PLUGINS.includes(plugin)) {
308
+ error("library_unknown", `${name} is the root agent's (${plugin}): a subagent can't pause, set triggers or plan for the whole turn`, at);
309
+ continue;
310
+ }
311
+ kept.push(name);
312
+ }
313
+ return kept;
314
+ };
315
+ let allowed = read("tools");
316
+ const denied = new Set(read("disallowedTools") ?? []);
317
+ if (subagent && front.readonly !== undefined) {
318
+ if (typeof front.readonly !== "boolean")
319
+ error("value_invalid", "readonly is true or false", ["readonly"]);
320
+ else if (front.readonly && allowed === undefined) {
321
+ note("host_key", "readonly: true is Cursor's: read as tools: [read, grep, glob]", ["readonly"], { key: true });
322
+ allowed = READONLY_TOOLS.filter((tool) => known.includes(tool));
323
+ }
324
+ else if (front.readonly)
325
+ note("host_key", "readonly: true is Cursor's, and tools already lists what this subagent gets: ignored", ["readonly"], { key: true });
326
+ }
327
+ delete front.readonly;
328
+ const keep = (tool) => (allowed === undefined || allowed.includes(tool)) && !denied.has(tool);
329
+ // The Runtime plugins: a subagent inherits its parent's, but the root's only, and memory only
330
+ // when it names it; the root keeps its own. Either keeps only the tools it allows.
331
+ if (subagent && front.plugins !== undefined)
332
+ error("value_invalid", "plugins is the root agent's: a subagent file gets the root's Runtime plugins, narrowed with tools", ["plugins"], { key: true });
333
+ const plugins = subagent
334
+ ? options.plugins.filter((plugin) => !ROOT_ONLY_PLUGINS.includes(plugin.name) &&
335
+ (!NAMED_ONLY_PLUGINS.includes(plugin.name) || (allowed !== undefined && plugin.tools.some((tool) => allowed.includes(tool)))))
336
+ : options.plugins;
337
+ const on = plugins.filter((plugin) => plugin.tools.some(keep));
338
+ if (subagent) {
339
+ if (on.length > 0)
340
+ front.plugins = on.map((plugin) => plugin.name);
341
+ else
342
+ delete front.plugins;
343
+ }
344
+ const off = plugins.flatMap((plugin) => plugin.tools.filter((tool) => !keep(tool)));
345
+ if (off.length > 0) {
346
+ const servers = isObject(front.mcpServers) ? front.mcpServers : (front.mcpServers = {});
347
+ const settings = isObject(servers[RUNTIME_SERVER]) ? servers[RUNTIME_SERVER] : (servers[RUNTIME_SERVER] = {});
348
+ const tools = isObject(settings.tools) ? settings.tools : (settings.tools = {});
349
+ for (const tool of off)
350
+ if (on.some((plugin) => plugin.tools.includes(tool)) || !subagent)
351
+ tools[tool] = { enabled: false };
352
+ if (Object.keys(tools).length === 0)
353
+ delete servers[RUNTIME_SERVER];
354
+ if (Object.keys(servers).length === 0)
355
+ delete front.mcpServers;
356
+ }
357
+ const http = allowed === undefined ? undefined : new Set(allowed.filter((tool) => options.httpTools.includes(tool)));
358
+ const httpDenied = new Set([...denied].filter((tool) => options.httpTools.includes(tool)));
359
+ // skills: a list in a subagent file; the root's stays the map that gives skills secrets.
360
+ let skills;
361
+ if (subagent && front.skills !== undefined) {
362
+ const names = namesOf(front.skills);
363
+ if (!names)
364
+ error("value_invalid", "skills in a subagent file lists the library's skills it gets, by name: [checklist]. Only the root agent's skills get secrets", ["skills"]);
365
+ skills = names ?? [];
366
+ delete front.skills;
367
+ }
368
+ return {
369
+ ...(http === undefined ? {} : { http }),
370
+ httpDenied,
371
+ ...(skills === undefined ? {} : { skills }),
372
+ ...(servers === undefined ? {} : { servers }),
373
+ flow: false,
374
+ };
375
+ }
376
+ /** The root's skills with secrets and plugin servers it gives a credential, read from its frontmatter. */
377
+ export function rootSecretsOf(front) {
378
+ const skills = isObject(front.skills)
379
+ ? Object.entries(front.skills)
380
+ .filter(([, value]) => isObject(value) && Array.isArray(value.secrets) && value.secrets.length > 0)
381
+ .map(([key]) => key)
382
+ : [];
383
+ const servers = isObject(front.mcpServers)
384
+ ? Object.entries(front.mcpServers)
385
+ .filter(([, value]) => isObject(value) && value.credential !== undefined)
386
+ .map(([key]) => key)
387
+ : [];
388
+ return { skills, servers };
389
+ }
390
+ /**
391
+ * Keeps, of the HTTP tools, skills and servers a subagent file inherited (or a v4 root holds),
392
+ * what its narrowing allows. A subagent also drops the root's skills with secrets and servers with
393
+ * a credential unless it names them, which then fail the checks that follow.
394
+ */
395
+ export function narrowParts(harness, narrowing, options) {
396
+ if (narrowing.flow)
397
+ return;
398
+ if (Array.isArray(harness.tools)) {
399
+ const tools = harness.tools.filter((tool) => {
400
+ const name = String(tool.name);
401
+ if (tool.agent !== undefined)
402
+ return true;
403
+ return (narrowing.http === undefined || narrowing.http.has(name)) && !narrowing.httpDenied.has(name);
404
+ });
405
+ if (tools.length > 0)
406
+ harness.tools = tools;
407
+ else
408
+ delete harness.tools;
409
+ }
410
+ if (options.role !== "subagent")
411
+ return;
412
+ const skills = isObject(harness.skills) ? harness.skills : {};
413
+ if (narrowing.skills)
414
+ for (const { name, index } of narrowing.skills)
415
+ if (!(name in skills)) {
416
+ const close = suggestion(name, Object.keys(skills));
417
+ options.error("library_unknown", `No skill ${name} is in the manifest's library (skills/ and its plugins).${close ? ` Did you mean '${close}'?` : ""}`, ["skills", index]);
418
+ }
419
+ else if (options.secrets.skills.includes(name))
420
+ options.error("credential_unsupported", `Only the root agent's skills get secrets: ${name} gets them from the root's AGENT.md, so a subagent can't use it`, ["skills", index]);
421
+ for (const key of Object.keys(skills)) {
422
+ const named = narrowing.skills?.some((item) => item.name === key);
423
+ if ((narrowing.skills !== undefined && !named) || (!named && options.secrets.skills.includes(key)))
424
+ delete skills[key];
425
+ }
426
+ if (isObject(harness.skills) && Object.keys(skills).length === 0)
427
+ delete harness.skills;
428
+ const servers = isObject(harness.mcpServers) ? harness.mcpServers : {};
429
+ for (const [key, server] of Object.entries(servers)) {
430
+ const named = narrowing.servers?.includes(key) === true;
431
+ const secret = (isObject(server) && server.credential !== undefined) || options.secrets.servers.includes(key);
432
+ if (named && options.secrets.servers.includes(key))
433
+ options.error("credential_unsupported", `${key} authenticates with a credential the root's AGENT.md gives it, and a subagent's MCP servers take no credential: give the server to the root agent`, ["mcpServers", key]);
434
+ if ((narrowing.servers !== undefined && !named) || (!named && secret))
435
+ delete servers[key];
436
+ }
437
+ if (isObject(harness.mcpServers) && Object.keys(servers).length === 0)
438
+ delete harness.mcpServers;
439
+ }
440
+ export { PLUGIN_NAMES, pluginTools };
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "$schema": "https://json-schema.org/draft/2020-12/schema",
3
- "$id": "https://docs.nylorun.com/schemas/agent-folder/v1/agent-md.5.json",
3
+ "$id": "https://docs.nylorun.com/schemas/agent-folder/v1/agent-md.6.json",
4
4
  "title": "Nylorun agent folder: AGENT.md frontmatter",
5
- "description": "The frontmatter of an agent folder's AGENT.md; the body below it is the instructions",
5
+ "description": "The frontmatter of an agent folder's AGENT.md, or of a subagent file (agents/<id>.md, agent-folder/4); the body below it is the instructions",
6
6
  "type": "object",
7
7
  "properties": {
8
8
  "name": {
@@ -20,11 +20,13 @@
20
20
  1,
21
21
  2,
22
22
  3,
23
+ 4,
23
24
  "agent-folder/1",
24
25
  "agent-folder/2",
25
- "agent-folder/3"
26
+ "agent-folder/3",
27
+ "agent-folder/4"
26
28
  ],
27
- "description": "The folder's format: agent-folder/1 (or 1, the default), which gets every engine feature by default; agent-folder/2 (or 2), which declares each in engine; or agent-folder/3 (or 3), which declares the Runtime's features as plugins"
29
+ "description": "The folder's format: agent-folder/1 (or 1, the default), which gets every engine feature by default; agent-folder/2 (or 2), which declares each in engine; agent-folder/3 (or 3), which declares the Runtime's features as plugins; or agent-folder/4 (or 4), agent-folder/3 with each subagent one file, agents/<id>.md, drawing on the manifest's library"
28
30
  },
29
31
  "harness": {
30
32
  "type": "string",
@@ -50,22 +52,33 @@
50
52
  "description": "How this agent uses each MCP server of mcp.json or a plugin, by its name"
51
53
  },
52
54
  "skills": {
53
- "type": "object",
54
- "additionalProperties": {
55
- "type": "object",
56
- "properties": {
57
- "secrets": {
58
- "type": "array",
59
- "items": {
60
- "type": "string",
61
- "pattern": "^[A-Za-z_][A-Za-z0-9_]*$"
55
+ "anyOf": [
56
+ {
57
+ "type": "object",
58
+ "additionalProperties": {
59
+ "type": "object",
60
+ "properties": {
61
+ "secrets": {
62
+ "type": "array",
63
+ "items": {
64
+ "type": "string",
65
+ "pattern": "^[A-Za-z_][A-Za-z0-9_]*$"
66
+ },
67
+ "description": "The secret slots the skill's scripts read, as environment variables"
68
+ }
62
69
  },
63
- "description": "The secret slots the skill's scripts read, as environment variables"
64
- }
70
+ "additionalProperties": false
71
+ },
72
+ "description": "This agent's settings for each skill of skills/ or a plugin, by its name"
65
73
  },
66
- "additionalProperties": false
67
- },
68
- "description": "This agent's settings for each skill of skills/ or a plugin, by its name"
74
+ {
75
+ "type": "array",
76
+ "items": {
77
+ "type": "string"
78
+ },
79
+ "description": "agent-folder/4, a subagent file: the only skills of the manifest's library it gets, by name"
80
+ }
81
+ ]
69
82
  },
70
83
  "memory": {
71
84
  "type": "object",
@@ -206,6 +219,42 @@
206
219
  "metadata": {
207
220
  "type": "object",
208
221
  "description": "The manifest's metadata, as it is"
222
+ },
223
+ "tools": {
224
+ "anyOf": [
225
+ {
226
+ "type": "array",
227
+ "items": {
228
+ "type": "string"
229
+ }
230
+ },
231
+ {
232
+ "type": "string"
233
+ }
234
+ ],
235
+ "description": "agent-folder/4: the only HTTP tools and Runtime plugin tools of the manifest's library this agent gets, by name ([read, grep, glob]); left out, a subagent file gets every one a subagent can use"
236
+ },
237
+ "disallowedTools": {
238
+ "anyOf": [
239
+ {
240
+ "type": "array",
241
+ "items": {
242
+ "type": "string"
243
+ }
244
+ },
245
+ {
246
+ "type": "string"
247
+ }
248
+ ],
249
+ "description": "agent-folder/4: library tools this agent does not get, by name"
250
+ },
251
+ "flow": {
252
+ "type": "string",
253
+ "description": "agent-folder/4, a subagent file: the flow file that drives it (./research.flow.json); its body is then empty"
254
+ },
255
+ "readonly": {
256
+ "type": "boolean",
257
+ "description": "agent-folder/4, a subagent file (Cursor's key): true reads as tools: [read, grep, glob] when tools is left out"
209
258
  }
210
259
  },
211
260
  "required": [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nylorun/core",
3
- "version": "0.52.0-beta",
3
+ "version": "0.53.0-beta",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0",
6
6
  "description": "Shared agent definitions and wire contracts",