@nylorun/core 0.3.0-beta → 0.5.0-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/compatibility.d.ts +48 -1
  3. package/dist/compatibility.js +192 -1
  4. package/dist/contracts.d.ts +562 -19
  5. package/dist/contracts.js +442 -29
  6. package/dist/define.d.ts +9 -3
  7. package/dist/define.js +3 -0
  8. package/dist/definition/assemble.js +35 -0
  9. package/dist/definition/bind-tool.js +3 -0
  10. package/dist/definition/bound.d.ts +3 -0
  11. package/dist/definition/builder.d.ts +5 -5
  12. package/dist/definition/declaration.d.ts +2 -2
  13. package/dist/definition/declaration.js +13 -1
  14. package/dist/definition/delegate.d.ts +35 -0
  15. package/dist/definition/delegate.js +72 -0
  16. package/dist/definition/from.js +15 -2
  17. package/dist/definition/helpers.d.ts +1 -1
  18. package/dist/definition/helpers.js +8 -1
  19. package/dist/definition/manifest.js +3 -0
  20. package/dist/definition/variant.d.ts +7 -0
  21. package/dist/definition/variant.js +87 -0
  22. package/dist/definition/workflow/build.d.ts +38 -0
  23. package/dist/definition/workflow/build.js +62 -0
  24. package/dist/definition/workflow/chain.d.ts +49 -0
  25. package/dist/definition/workflow/chain.js +41 -0
  26. package/dist/definition/workflow/diagnostics.d.ts +14 -0
  27. package/dist/definition/workflow/diagnostics.js +38 -0
  28. package/dist/definition/workflow/index.d.ts +18 -0
  29. package/dist/definition/workflow/index.js +10 -0
  30. package/dist/definition/workflow/loop.d.ts +54 -0
  31. package/dist/definition/workflow/loop.js +102 -0
  32. package/dist/definition/workflow/map.d.ts +17 -0
  33. package/dist/definition/workflow/map.js +46 -0
  34. package/dist/definition/workflow/parallel.d.ts +19 -0
  35. package/dist/definition/workflow/parallel.js +37 -0
  36. package/dist/definition/workflow/patch.d.ts +11 -0
  37. package/dist/definition/workflow/patch.js +45 -0
  38. package/dist/definition/workflow/runnable.d.ts +40 -0
  39. package/dist/definition/workflow/runnable.js +251 -0
  40. package/dist/definition/workflow/slot.d.ts +23 -0
  41. package/dist/definition/workflow/slot.js +16 -0
  42. package/dist/definition/workflow/switch.d.ts +26 -0
  43. package/dist/definition/workflow/switch.js +66 -0
  44. package/dist/definition/workflow/types.d.ts +25 -0
  45. package/dist/definition/workflow/types.js +7 -0
  46. package/dist/definition/workflow/verdict.d.ts +20 -0
  47. package/dist/definition/workflow/verdict.js +25 -0
  48. package/dist/index.d.ts +1 -0
  49. package/dist/types/agent.d.ts +5 -0
  50. package/dist/types/manifest.d.ts +5 -0
  51. package/dist/types/middleware.d.ts +5 -0
  52. package/dist/types/observe.d.ts +87 -1
  53. package/dist/types/tool.d.ts +11 -0
  54. package/dist/types/workflow.d.ts +106 -0
  55. package/dist/types/workflow.js +1 -0
  56. package/dist/utils/hash.d.ts +3 -2
  57. package/dist/utils/hash.js +1 -1
  58. package/package.json +1 -1
@@ -1,5 +1,6 @@
1
1
  import { HarnessError } from "../errors.js";
2
2
  import { normalizeToolDefinition, normalizedSchemasFor } from "./schema.js";
3
+ import { delegateOf } from "./delegate.js";
3
4
  /** Prepares an executable Tool and records its middleware slot provenance. */
4
5
  export function bindTool(item, owner) {
5
6
  const prepared = normalizeToolDefinition(item);
@@ -8,6 +9,7 @@ export function bindTool(item, owner) {
8
9
  if (typeof prepared.execute !== "function")
9
10
  throw new HarnessError("tool.invalid", `Tool '${prepared.name}' must provide execute()`);
10
11
  const schemas = normalizedSchemasFor(prepared);
12
+ const delegate = delegateOf(item);
11
13
  return Object.freeze({
12
14
  // Keep the original object identity so ToolRegistry WeakMap lookups succeed.
13
15
  source: item,
@@ -21,5 +23,6 @@ export function bindTool(item, owner) {
21
23
  ...(prepared.approval === undefined ? {} : { approval: prepared.approval }),
22
24
  ...(prepared.effects === undefined ? {} : { effects: prepared.effects }),
23
25
  owner: Object.freeze({ ...owner }),
26
+ ...(delegate === undefined ? {} : { delegate }),
24
27
  });
25
28
  }
@@ -2,6 +2,7 @@ import type { JsonObject } from "../types/shared.js";
2
2
  import type { McpServerManifest, SandboxManifest, SkillManifest } from "../types/manifest.js";
3
3
  import type { SkillRecord } from "../types/middleware.js";
4
4
  import type { HookManifest } from "../types/dynamics.js";
5
+ import type { Delegate } from "./delegate.js";
5
6
  import type { MiddlewareContributions, StepMiddleware } from "../types/middleware.js";
6
7
  import type { ToolApproval, ToolDefinition, ToolEffects, ToolExecutionContext, ToolInputSchema, ToolOutputSchema, ToolOwner, ToolRunResult, ToolSchema } from "../types/tool.js";
7
8
  export interface BoundToolDefinition<Info = unknown> extends Omit<ToolDefinition<ToolInputSchema, Info, ToolOutputSchema | undefined>, "inputSchema" | "outputSchema" | "execute" | "run" | "input" | "output"> {
@@ -12,6 +13,8 @@ export interface BoundToolDefinition<Info = unknown> extends Omit<ToolDefinition
12
13
  readonly effects?: ToolEffects;
13
14
  readonly owner: ToolOwner;
14
15
  readonly source: ToolDefinition<any, any, any>;
16
+ /** Set when this tool is an agent used as a tool; the engine runs it. */
17
+ readonly delegate?: Delegate;
15
18
  }
16
19
  export interface BoundMiddleware {
17
20
  readonly id: string;
@@ -1,9 +1,9 @@
1
1
  import type { BoundMiddleware } from "./bound.js";
2
- import type { CapabilityDeclaration, StepMiddleware } from "../types/middleware.js";
2
+ import type { CapabilityInput, StepMiddleware } from "../types/middleware.js";
3
3
  import type { BuildDiagnostic, JsonObject } from "../types/shared.js";
4
4
  import { HarnessError } from "../errors.js";
5
5
  import type { ToolDefinition, ToolSchemaSource, SchemaOutput } from "../types/tool.js";
6
- import type { BuiltAgent } from "../types/agent.js";
6
+ import type { AgentTool, BuiltAgent } from "../types/agent.js";
7
7
  import type { AgentManifest } from "../types/manifest.js";
8
8
  import type { AfterHook, BeforeHook, HookScope } from "../types/dynamics.js";
9
9
  import type { Implementations } from "./implementations.js";
@@ -15,8 +15,8 @@ export interface AgentOptions<Schema extends ToolSchemaSource | undefined = unde
15
15
  readonly description?: string;
16
16
  readonly metadata?: JsonObject;
17
17
  readonly instructions?: string | readonly string[];
18
- /** Top-level tools (H2). Composed as capability id `"agent"`. */
19
- readonly tools?: readonly ToolDefinition<any, any, any>[];
18
+ /** Top-level tools (H2), and agents used as tools. Composed as capability id `"agent"`. */
19
+ readonly tools?: readonly (ToolDefinition<any, any, any> | AgentTool)[];
20
20
  }
21
21
  interface BuilderSnapshot {
22
22
  readonly id: string;
@@ -56,7 +56,7 @@ export declare class AgentBuilder<Info = unknown, Schema extends ToolSchemaSourc
56
56
  toJSON(): AgentManifest;
57
57
  use(middleware: StepMiddleware<Info>): AgentBuilder<Info, Schema>;
58
58
  use(id: string, middleware: StepMiddleware<Info>): AgentBuilder<Info, Schema>;
59
- use(declaration: CapabilityDeclaration<Info>): AgentBuilder<Info, Schema>;
59
+ use(declaration: CapabilityInput<Info>): AgentBuilder<Info, Schema>;
60
60
  /**
61
61
  * Run `fn` before each turn (`"turn"`) or before every model call (`"step"`).
62
62
  * The returned Patch applies to the whole turn or to that one model call.
@@ -1,5 +1,5 @@
1
1
  import type { BoundMiddleware } from "./bound.js";
2
- import type { CapabilityDeclaration, StepMiddleware } from "../types/middleware.js";
2
+ import type { CapabilityInput, StepMiddleware } from "../types/middleware.js";
3
3
  import type { AfterHooks, BeforeHooks } from "../types/dynamics.js";
4
4
  export interface CompiledCapability {
5
5
  readonly bound: BoundMiddleware;
@@ -7,4 +7,4 @@ export interface CompiledCapability {
7
7
  readonly after?: AfterHooks<any>;
8
8
  readonly middleware?: StepMiddleware<any>;
9
9
  }
10
- export declare function compileDeclaration<State>(declaration: CapabilityDeclaration<State>): CompiledCapability;
10
+ export declare function compileDeclaration<State>(declaration: CapabilityInput<State>): CompiledCapability;
@@ -1,6 +1,7 @@
1
1
  import { hooksFrom } from "./hooks.js";
2
+ import { delegateTool, isAgentItem } from "./delegate.js";
2
3
  export function compileDeclaration(declaration) {
3
- const tools = copyItems(declaration.tools, declaration.id);
4
+ const tools = asTools(copyItems(declaration.tools, declaration.id));
4
5
  const instructions = copyItems(declaration.instructions, declaration.id);
5
6
  const model = declaration.model;
6
7
  const hooks = hooksFrom(declaration.before, declaration.after);
@@ -91,3 +92,14 @@ function copyItems(value, defaultSlot) {
91
92
  items: Object.freeze([...value.items]),
92
93
  });
93
94
  }
95
+ /** Agents placed in `tools` become the tools that delegate to them. */
96
+ function asTools(value) {
97
+ if (value === undefined)
98
+ return undefined;
99
+ if (!value.items.some(isAgentItem))
100
+ return value;
101
+ return Object.freeze({
102
+ slot: value.slot,
103
+ items: Object.freeze(value.items.map((item) => (isAgentItem(item) ? delegateTool(item) : item))),
104
+ });
105
+ }
@@ -0,0 +1,35 @@
1
+ import type { BuiltAgent } from "../types/agent.js";
2
+ import type { AgentManifest } from "../types/manifest.js";
3
+ import type { JsonObject } from "../types/shared.js";
4
+ import type { ToolDefinition } from "../types/tool.js";
5
+ /** An agent used as another agent's tool. The engine runs it; customer code never does. */
6
+ export interface Delegate {
7
+ /** The child's manifest, inlined into the parent's tool. */
8
+ readonly manifest: AgentManifest;
9
+ /** The authored child, when available locally. Absent when rebuilt from a manifest. */
10
+ readonly agent?: BuiltAgent;
11
+ }
12
+ /** Model-facing tool names: what every supported provider accepts. */
13
+ export declare const DELEGATE_NAME_PATTERN: RegExp;
14
+ /** The input every agent used as a tool accepts. Part of the hashed manifest; change deliberately. */
15
+ export declare const DELEGATE_INPUT_SCHEMA: JsonObject;
16
+ /** A built agent or an agent builder; both expose getBinding() and manifest. */
17
+ export declare function isAgentItem(value: unknown): value is Pick<BuiltAgent, "id" | "manifest" | "getBinding"> & {
18
+ build?: () => BuiltAgent;
19
+ };
20
+ /** Turn an agent placed in `tools` into the tool that delegates to it. */
21
+ export declare function delegateTool(item: unknown): ToolDefinition;
22
+ /** Rebuild the delegating tool from a manifest's `agent` body. */
23
+ export declare function delegateFromManifest(manifest: AgentManifest, tool: {
24
+ readonly description?: string;
25
+ readonly inputSchema: JsonObject;
26
+ }): ToolDefinition;
27
+ /** The delegate behind a tool definition, or behind the bound snapshot of one. */
28
+ export declare function delegateOf(tool: unknown): Delegate | undefined;
29
+ /** The agents a manifest delegates to, with the capability and tool that declare each. */
30
+ export declare function delegatesOf(manifest: AgentManifest): readonly {
31
+ readonly capabilityId: string;
32
+ readonly manifest: AgentManifest;
33
+ }[];
34
+ /** The manifest of the delegated agent `id`, or undefined. One level deep by construction. */
35
+ export declare function delegateManifest(manifest: AgentManifest, id: string): AgentManifest | undefined;
@@ -0,0 +1,72 @@
1
+ import { z } from "zod";
2
+ import { ToolError } from "./tool-error.js";
3
+ import { normalizeSchema } from "./schema.js";
4
+ import { schemaFromJSON } from "./schema-json.js";
5
+ /** Survives duplicate installed copies of core, like the error brands. */
6
+ const DELEGATE = Symbol.for("@nylorun/core/delegate");
7
+ /** Model-facing tool names: what every supported provider accepts. */
8
+ export const DELEGATE_NAME_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
9
+ const taskSchema = z
10
+ .object({
11
+ task: z
12
+ .string()
13
+ .min(1)
14
+ .describe("A complete, self-contained task. The agent sees nothing else."),
15
+ })
16
+ .strict();
17
+ /** The input every agent used as a tool accepts. Part of the hashed manifest; change deliberately. */
18
+ export const DELEGATE_INPUT_SCHEMA = normalizeSchema(taskSchema, "input").jsonSchema;
19
+ async function engineOnly() {
20
+ throw new ToolError("delegation.engine-only", "Agents used as tools are run by the Nylorun engine, not by an executor");
21
+ }
22
+ /** A built agent or an agent builder; both expose getBinding() and manifest. */
23
+ export function isAgentItem(value) {
24
+ if (value === null || typeof value !== "object")
25
+ return false;
26
+ const item = value;
27
+ return (typeof item.getBinding === "function" &&
28
+ typeof item.execute !== "function" &&
29
+ typeof item.run !== "function");
30
+ }
31
+ /** Turn an agent placed in `tools` into the tool that delegates to it. */
32
+ export function delegateTool(item) {
33
+ const candidate = item;
34
+ const agent = typeof candidate.build === "function" ? candidate.build() : candidate;
35
+ return withDelegate(agent.manifest, agent);
36
+ }
37
+ /** Rebuild the delegating tool from a manifest's `agent` body. */
38
+ export function delegateFromManifest(manifest, tool) {
39
+ return withDelegate(manifest, undefined, tool);
40
+ }
41
+ function withDelegate(manifest, agent, declared) {
42
+ const description = declared ? declared.description : manifest.description;
43
+ const definition = {
44
+ name: manifest.id,
45
+ ...(description === undefined ? {} : { description }),
46
+ inputSchema: declared ? schemaFromJSON(declared.inputSchema) : taskSchema,
47
+ execute: engineOnly,
48
+ };
49
+ const delegate = Object.freeze({ manifest, ...(agent ? { agent } : {}) });
50
+ Object.defineProperty(definition, DELEGATE, { value: delegate, enumerable: false });
51
+ return Object.freeze(definition);
52
+ }
53
+ /** The delegate behind a tool definition, or behind the bound snapshot of one. */
54
+ export function delegateOf(tool) {
55
+ if (tool === null || typeof tool !== "object")
56
+ return undefined;
57
+ const value = tool;
58
+ return value[DELEGATE] ?? (value.source === tool ? undefined : delegateOf(value.source));
59
+ }
60
+ /** The agents a manifest delegates to, with the capability and tool that declare each. */
61
+ export function delegatesOf(manifest) {
62
+ const found = [];
63
+ for (const capability of manifest.capabilities)
64
+ for (const tool of capability.tools ?? [])
65
+ if (tool.agent)
66
+ found.push({ capabilityId: capability.id, manifest: tool.agent });
67
+ return found;
68
+ }
69
+ /** The manifest of the delegated agent `id`, or undefined. One level deep by construction. */
70
+ export function delegateManifest(manifest, id) {
71
+ return delegatesOf(manifest).find((item) => item.manifest.id === id)?.manifest;
72
+ }
@@ -3,6 +3,7 @@ import { assembleAgent } from "./assemble.js";
3
3
  import { schemaFromJSON } from "./schema-json.js";
4
4
  import { copyJsonObject, deepFreeze } from "../utils/immutable.js";
5
5
  import { HOOK_POINTS, hasHook, hookListIssue } from "./hooks.js";
6
+ import { delegateFromManifest, delegateOf } from "./delegate.js";
6
7
  /** Rebuild an agent from manifest JSON + in-process implementations (T28). */
7
8
  export function agentFrom(json, implementations, options) {
8
9
  const manifest = normalizeManifest(json);
@@ -26,7 +27,9 @@ export function agentFrom(json, implementations, options) {
26
27
  (async (request, next) => {
27
28
  const advertised = [...tools, ...session];
28
29
  if (advertised.length)
29
- request.configuration.tools.set(capability.id, advertised.map((tool) => implementations[capability.id]?.tools?.[tool.name] ?? tool));
30
+ request.configuration.tools.set(capability.id, advertised.map((tool) => (delegateOf(tool)
31
+ ? tool
32
+ : implementations[capability.id]?.tools?.[tool.name]) ?? tool));
30
33
  if (capability.instructions)
31
34
  request.configuration.instructions.set(capability.id, capability.instructions);
32
35
  return next();
@@ -41,7 +44,7 @@ export function agentFrom(json, implementations, options) {
41
44
  hasMiddleware: impl.middleware !== undefined,
42
45
  tools: capability.tools !== undefined
43
46
  ? tools.map((tool) => {
44
- const live = impl.tools?.[tool.name];
47
+ const live = delegateOf(tool) ? tool : impl.tools?.[tool.name];
45
48
  if (!live)
46
49
  throw new HarnessError("agent.build-failed", `Missing tool implementation '${tool.name}' for capability '${capability.id}'`);
47
50
  return live;
@@ -117,6 +120,13 @@ function resolveTools(capability, tools) {
117
120
  return [];
118
121
  return capability.tools.flatMap((declared) => {
119
122
  const live = tools?.[declared.name];
123
+ // The engine runs agents used as tools; an authored delegate keeps its local child.
124
+ if (declared.agent)
125
+ return [
126
+ live && delegateOf(live)?.manifest.id === declared.agent.id
127
+ ? live
128
+ : delegateFromManifest(declared.agent, declared),
129
+ ];
120
130
  if (live)
121
131
  return [live];
122
132
  if ((declared.name === "load_skill" || declared.name === "read_skill_resource") &&
@@ -314,5 +324,8 @@ function normalizeTool(tool) {
314
324
  ...(tool.outputSchema === undefined
315
325
  ? {}
316
326
  : { outputSchema: tool.outputSchema }),
327
+ ...(tool.agent === undefined
328
+ ? {}
329
+ : { agent: normalizeManifest(tool.agent) }),
317
330
  });
318
331
  }
@@ -11,7 +11,7 @@ export declare function capability<Info = unknown>(declaration: {
11
11
  readonly id: string;
12
12
  readonly name?: string;
13
13
  readonly description?: string;
14
- readonly tools?: readonly ToolDefinition<any, Info, any>[];
14
+ readonly tools?: readonly (ToolDefinition<any, Info, any> | import("../types/agent.js").AgentTool)[];
15
15
  readonly instructions?: string | readonly string[];
16
16
  /** Run before each turn or before every model call (step). */
17
17
  readonly before?: import("../types/dynamics.js").BeforeHooks<Info>;
@@ -1,4 +1,5 @@
1
1
  import { prepareTool } from "./schema.js";
2
+ import { delegateTool, isAgentItem } from "./delegate.js";
2
3
  export const tool = (value) => prepareTool(value);
3
4
  /** @deprecated Prefer Runtime model resolution. Capability-disguised `.use({ model })` is not the taught path. */
4
5
  export const model = (value) => value;
@@ -17,7 +18,13 @@ export function capability(declaration) {
17
18
  ...(declaration.description === undefined
18
19
  ? {}
19
20
  : { description: declaration.description }),
20
- ...(declaration.tools === undefined ? {} : { tools: declaration.tools }),
21
+ ...(declaration.tools === undefined
22
+ ? {}
23
+ : {
24
+ tools: declaration.tools.map((item) => isAgentItem(item)
25
+ ? delegateTool(item)
26
+ : item),
27
+ }),
21
28
  ...(instructions === undefined ? {} : { instructions }),
22
29
  ...(declaration.before === undefined ? {} : { before: declaration.before }),
23
30
  ...(declaration.after === undefined ? {} : { after: declaration.after }),
@@ -1,5 +1,6 @@
1
1
  import { bindOutputContract } from "./output-contract.js";
2
2
  import { normalizedSchemasFor } from "./schema.js";
3
+ import { delegateOf } from "./delegate.js";
3
4
  import { copyJsonObject, deepFreeze } from "../utils/immutable.js";
4
5
  export function createManifest(input) {
5
6
  const capabilities = input.middleware.map((item) => projectCapability(item));
@@ -51,6 +52,7 @@ function projectCapability(item) {
51
52
  }
52
53
  function projectTool(tool) {
53
54
  const schemas = normalizedSchemasFor(tool);
55
+ const delegate = delegateOf(tool);
54
56
  return {
55
57
  name: tool.name,
56
58
  ...(tool.description === undefined
@@ -60,5 +62,6 @@ function projectTool(tool) {
60
62
  ...(schemas.outputSchema === undefined
61
63
  ? {}
62
64
  : { outputSchema: schemas.outputSchema.jsonSchema }),
65
+ ...(delegate === undefined ? {} : { agent: delegate.manifest }),
63
66
  };
64
67
  }
@@ -0,0 +1,7 @@
1
+ import type { AgentManifest } from "../types/manifest.js";
2
+ /**
3
+ * Whether `candidate` is a valid turn-manifest variant of the session's pinned
4
+ * manifest (`loops.md` §3.4). Hooks and setup (MCP, sandbox) are fixed;
5
+ * code-backed tools/skills/agents-as-tools are remove-only; plain data may change.
6
+ */
7
+ export declare function isVariantOf(candidate: AgentManifest, pinned: AgentManifest): boolean;
@@ -0,0 +1,87 @@
1
+ import { canonical } from "../utils/canonical.js";
2
+ function same(a, b) {
3
+ return canonical(a) === canonical(b);
4
+ }
5
+ function toolsByName(tools) {
6
+ const map = new Map();
7
+ for (const tool of tools ?? [])
8
+ map.set(tool.name, tool);
9
+ return map;
10
+ }
11
+ /** Candidate tools/skills/agents-as-tools may only be removed, never added or changed. */
12
+ function removeOnlyTools(pinned, candidate) {
13
+ const base = toolsByName(pinned);
14
+ for (const tool of candidate ?? []) {
15
+ const prior = base.get(tool.name);
16
+ if (!prior || !same(prior, tool))
17
+ return false;
18
+ }
19
+ return true;
20
+ }
21
+ function removeOnlySkills(pinned, candidate) {
22
+ const base = pinned ?? {};
23
+ for (const [name, skill] of Object.entries(candidate ?? {})) {
24
+ const prior = base[name];
25
+ if (!prior || !same(prior, skill))
26
+ return false;
27
+ }
28
+ return true;
29
+ }
30
+ /**
31
+ * Whether `candidate` is a valid turn-manifest variant of the session's pinned
32
+ * manifest (`loops.md` §3.4). Hooks and setup (MCP, sandbox) are fixed;
33
+ * code-backed tools/skills/agents-as-tools are remove-only; plain data may change.
34
+ */
35
+ export function isVariantOf(candidate, pinned) {
36
+ if (candidate.id !== pinned.id)
37
+ return false;
38
+ if (candidate.manifestSchemaVersion !== pinned.manifestSchemaVersion)
39
+ return false;
40
+ if (!same(candidate.runtime ?? {}, pinned.runtime ?? {}))
41
+ return false;
42
+ const pinnedById = new Map(pinned.capabilities.map((capability) => [capability.id, capability]));
43
+ const candidateById = new Map(candidate.capabilities.map((capability) => [capability.id, capability]));
44
+ for (const [, prior] of pinnedById) {
45
+ const next = candidateById.get(prior.id);
46
+ if (prior.hooks?.length) {
47
+ // Hooks — and any capability that registers them — must not change or be removed.
48
+ if (!next || !same(next.hooks, prior.hooks))
49
+ return false;
50
+ }
51
+ if (prior.mcpServers !== undefined) {
52
+ if (!next || !same(next.mcpServers, prior.mcpServers))
53
+ return false;
54
+ }
55
+ if (prior.sandbox !== undefined) {
56
+ if (!next || !same(next.sandbox, prior.sandbox))
57
+ return false;
58
+ }
59
+ }
60
+ for (const [id, next] of candidateById) {
61
+ const prior = pinnedById.get(id);
62
+ if (!prior)
63
+ return false; // cannot add capabilities
64
+ if (next.type !== prior.type)
65
+ return false;
66
+ if (!removeOnlyTools(prior.tools, next.tools))
67
+ return false;
68
+ if (!removeOnlySkills(prior.skills, next.skills))
69
+ return false;
70
+ // Free: name, description, metadata, instructions (and model once it exists).
71
+ if (prior.hooks?.length) {
72
+ if (!same(next.hooks, prior.hooks))
73
+ return false;
74
+ }
75
+ else if (next.hooks?.length) {
76
+ return false; // cannot add hooks
77
+ }
78
+ if (!same(next.mcpServers, prior.mcpServers))
79
+ return false;
80
+ if (!same(next.sandbox, prior.sandbox))
81
+ return false;
82
+ }
83
+ // Dropping a capability is allowed only when it had no hooks / MCP / sandbox
84
+ // (those are enforced above). Tools and skills on a dropped capability are
85
+ // removals, which §3.4 permits.
86
+ return true;
87
+ }
@@ -0,0 +1,38 @@
1
+ import type { AgentBinding } from "../binding.js";
2
+ import type { BuildDiagnostic, JsonObject, JsonValue } from "../../types/shared.js";
3
+ import type { WorkflowNode, WorkflowNodeImplementation } from "../../types/workflow.js";
4
+ import type { ToolSchemaSource } from "../../types/tool.js";
5
+ import type { BuiltWorkflow } from "./types.js";
6
+ export type BuildAccumulator = {
7
+ readonly agents: Record<string, AgentBinding>;
8
+ readonly nodes: Record<string, WorkflowNodeImplementation>;
9
+ readonly sandboxSpecs: JsonObject[];
10
+ };
11
+ export declare function emptyAccumulator(): BuildAccumulator;
12
+ export declare function mergeChild(acc: BuildAccumulator, child: {
13
+ readonly agents: Record<string, AgentBinding>;
14
+ readonly nodes: Record<string, WorkflowNodeImplementation>;
15
+ readonly sandboxSpecs: readonly JsonObject[];
16
+ }): void;
17
+ /**
18
+ * Every agent in the tree that declares a sandbox must declare an identical spec
19
+ * (workflows.md §8). Returns the common spec, or undefined when none declare one.
20
+ */
21
+ export declare function resolveWorkflowSandbox(specs: readonly JsonObject[]): {
22
+ sandbox?: JsonObject;
23
+ diagnostics: BuildDiagnostic[];
24
+ };
25
+ export type FinishOptions<In = JsonValue, Out = JsonValue> = {
26
+ readonly id: string;
27
+ readonly root: WorkflowNode;
28
+ readonly acc: BuildAccumulator;
29
+ readonly inputSchema?: ToolSchemaSource;
30
+ readonly outputSchema?: ToolSchemaSource;
31
+ /** Extra diagnostics collected by the primitive. */
32
+ readonly diagnostics?: readonly BuildDiagnostic[];
33
+ };
34
+ /**
35
+ * Assemble a BuiltWorkflow: non-enumerable getBinding, manifest-only toJSON,
36
+ * optional document-level sandbox (workflows.md §18).
37
+ */
38
+ export declare function finishWorkflow<In = JsonValue, Out = JsonValue>(options: FinishOptions<In, Out>): BuiltWorkflow<In, Out>;
@@ -0,0 +1,62 @@
1
+ import { canonical } from "../../utils/canonical.js";
2
+ import { diagnostic, fail } from "./diagnostics.js";
3
+ export function emptyAccumulator() {
4
+ return { agents: {}, nodes: {}, sandboxSpecs: [] };
5
+ }
6
+ export function mergeChild(acc, child) {
7
+ Object.assign(acc.agents, child.agents);
8
+ Object.assign(acc.nodes, child.nodes);
9
+ for (const spec of child.sandboxSpecs)
10
+ acc.sandboxSpecs.push(spec);
11
+ }
12
+ /**
13
+ * Every agent in the tree that declares a sandbox must declare an identical spec
14
+ * (workflows.md §8). Returns the common spec, or undefined when none declare one.
15
+ */
16
+ export function resolveWorkflowSandbox(specs) {
17
+ if (specs.length === 0)
18
+ return { diagnostics: [] };
19
+ const keys = new Set(specs.map((s) => canonical(s)));
20
+ if (keys.size > 1)
21
+ return {
22
+ diagnostics: [
23
+ diagnostic("workflow.sandbox-mismatch", "Every agent in the tree that declares a sandbox must declare an identical spec"),
24
+ ],
25
+ };
26
+ return { sandbox: specs[0], diagnostics: [] };
27
+ }
28
+ /**
29
+ * Assemble a BuiltWorkflow: non-enumerable getBinding, manifest-only toJSON,
30
+ * optional document-level sandbox (workflows.md §18).
31
+ */
32
+ export function finishWorkflow(options) {
33
+ const diagnostics = [...(options.diagnostics ?? [])];
34
+ const { sandbox, diagnostics: sandboxDiagnostics } = resolveWorkflowSandbox(options.acc.sandboxSpecs);
35
+ diagnostics.push(...sandboxDiagnostics);
36
+ if (diagnostics.length)
37
+ fail(diagnostics);
38
+ const manifest = {
39
+ kind: "workflow",
40
+ workflowSchemaVersion: 1,
41
+ id: options.id,
42
+ root: options.root,
43
+ ...(sandbox === undefined ? {} : { sandbox: sandbox }),
44
+ };
45
+ const binding = Object.freeze({
46
+ manifest,
47
+ nodes: Object.freeze({ ...options.acc.nodes }),
48
+ agents: Object.freeze({ ...options.acc.agents }),
49
+ });
50
+ const built = {
51
+ id: options.id,
52
+ manifest,
53
+ toJSON: () => manifest,
54
+ ...(options.inputSchema === undefined ? {} : { inputSchema: options.inputSchema }),
55
+ ...(options.outputSchema === undefined ? {} : { outputSchema: options.outputSchema }),
56
+ };
57
+ Object.defineProperty(built, "getBinding", {
58
+ value: () => binding,
59
+ enumerable: false,
60
+ });
61
+ return built;
62
+ }
@@ -0,0 +1,49 @@
1
+ import type { JsonValue } from "../../types/shared.js";
2
+ import type { ToolSchemaSource } from "../../types/tool.js";
3
+ import { type WorkflowRunnable } from "./runnable.js";
4
+ import type { ChildRef, Slot, SlotInputArgs } from "./slot.js";
5
+ import type { BuiltWorkflow, OutputOf } from "./types.js";
6
+ export type ChainStep = ChildRef;
7
+ type StepId<S> = S extends Slot<infer R, any, any, any> ? S extends {
8
+ readonly id: infer I extends string;
9
+ } ? I : RunnableId<R> : RunnableId<S>;
10
+ type RunnableId<R> = R extends {
11
+ readonly id: infer I extends string;
12
+ } ? I : R extends {
13
+ readonly name: infer N extends string;
14
+ } ? N : string;
15
+ type StepOutput<S> = S extends Slot<infer R, any, any, any> ? OutputOf<R> : OutputOf<S>;
16
+ /** Results object available to step K (earlier step outputs only). */
17
+ export type ResultsBefore<Steps extends readonly ChainStep[], K extends number> = {
18
+ readonly [I in keyof Steps as I extends `${infer N extends number}` ? N extends K ? never : `${N}` extends `${infer M extends number}` ? M extends number ? M extends K ? never : Compare<M, K> extends true ? StepId<Steps[M] & ChainStep> : never : never : never : never]: StepOutput<Steps[I & keyof Steps] & ChainStep>;
19
+ };
20
+ /** `true` when A < B (both number literals). Simplified: use a recursive counter for small tuples. */
21
+ type Compare<A extends number, B extends number> = A extends B ? false : LessThan<[...TupleOf<A>], [...TupleOf<B>]>;
22
+ type TupleOf<N extends number, Acc extends unknown[] = []> = Acc["length"] extends N ? Acc : TupleOf<N, [...Acc, unknown]>;
23
+ type LessThan<A extends unknown[], B extends unknown[]> = A["length"] extends B["length"] ? false : A extends [...B, ...unknown[]] ? false : B extends [...A, ...unknown[]] ? true : false;
24
+ /** Typed results accumulating through a steps tuple. */
25
+ export type ChainResults<Steps extends readonly ChainStep[]> = {
26
+ readonly [I in keyof Steps as StepId<Steps[I & keyof Steps] & ChainStep>]: StepOutput<Steps[I & keyof Steps] & ChainStep>;
27
+ };
28
+ export type LastOutput<Steps extends readonly ChainStep[]> = Steps extends readonly [
29
+ ...infer _Rest,
30
+ infer Last
31
+ ] ? StepOutput<Last & ChainStep> : JsonValue;
32
+ export interface ChainOptions<Steps extends readonly [ChainStep, ...ChainStep[]] = readonly [ChainStep, ...ChainStep[]], In = JsonValue, Out = LastOutput<Steps>> {
33
+ readonly id: string;
34
+ readonly steps: Steps;
35
+ readonly inputSchema?: ToolSchemaSource;
36
+ readonly outputSchema?: ToolSchemaSource;
37
+ }
38
+ /**
39
+ * Run steps in order. Each step's output is the next step's input unless a slot
40
+ * reshapes it. `results` exposes earlier step outputs to later slots (chain.md).
41
+ */
42
+ export declare function Chain<const Steps extends readonly [ChainStep, ...ChainStep[]], In = JsonValue>(options: ChainOptions<Steps, In>): BuiltWorkflow<In, LastOutput<Steps>>;
43
+ /** Helper type: a slot whose `input` may only read known earlier result keys. */
44
+ export type ChainSlot<Run extends WorkflowRunnable, PrevResults extends Readonly<Record<string, JsonValue>>, Value = JsonValue, Input = JsonValue> = {
45
+ readonly run: Run;
46
+ readonly id?: string;
47
+ readonly input?: (args: SlotInputArgs<Value, Input, PrevResults>) => JsonValue;
48
+ };
49
+ export {};
@@ -0,0 +1,41 @@
1
+ import { assertValidPathPart, diagnostic, fail, siblingUniquenessDiagnostics, } from "./diagnostics.js";
2
+ import { emptyAccumulator, finishWorkflow, mergeChild } from "./build.js";
3
+ import { remapNodeKeys, resolveChild, runnableId, } from "./runnable.js";
4
+ import { isSlot } from "./slot.js";
5
+ /**
6
+ * Run steps in order. Each step's output is the next step's input unless a slot
7
+ * reshapes it. `results` exposes earlier step outputs to later slots (chain.md).
8
+ */
9
+ export function Chain(options) {
10
+ const { id, steps } = options;
11
+ if (!id)
12
+ fail([diagnostic("chain.missing-id", "Chain requires id")]);
13
+ assertValidPathPart(id, "Chain id");
14
+ if (!steps || steps.length === 0)
15
+ fail([diagnostic("chain.empty-steps", "Chain steps must be non-empty")]);
16
+ const ids = steps.map((step) => runnableId(step));
17
+ const dupes = siblingUniquenessDiagnostics(ids, "Chain step");
18
+ if (dupes.length)
19
+ fail(dupes);
20
+ const acc = emptyAccumulator();
21
+ const stepNodes = [];
22
+ for (let i = 0; i < steps.length; i++) {
23
+ const step = steps[i];
24
+ const resolved = resolveChild(step);
25
+ assertValidPathPart(resolved.id, "Chain step id");
26
+ const stepPath = `${id}/${resolved.id}`;
27
+ mergeChild(acc, {
28
+ agents: resolved.agents,
29
+ nodes: remapNodeKeys(resolved.nodes, resolved.id, stepPath),
30
+ sandboxSpecs: resolved.sandboxSpecs,
31
+ });
32
+ stepNodes.push(resolved.node);
33
+ }
34
+ return finishWorkflow({
35
+ id,
36
+ root: { chain: { id, steps: stepNodes } },
37
+ acc,
38
+ inputSchema: options.inputSchema,
39
+ outputSchema: options.outputSchema,
40
+ });
41
+ }
@@ -0,0 +1,14 @@
1
+ import type { BuildDiagnostic } from "../../types/shared.js";
2
+ /** Thrown when a workflow primitive fails its build-time checks. */
3
+ export declare class WorkflowBuildError extends Error {
4
+ readonly diagnostics: readonly BuildDiagnostic[];
5
+ constructor(diagnostics: readonly BuildDiagnostic[]);
6
+ }
7
+ export declare function diagnostic(code: string, message: string, extra?: Partial<BuildDiagnostic>): BuildDiagnostic;
8
+ export declare function fail(diagnostics: readonly BuildDiagnostic[]): never;
9
+ export declare function failOne(code: string, message: string, extra?: Partial<BuildDiagnostic>): never;
10
+ /** Path parts: non-empty, with no `/`, `[` or `]`. */
11
+ export declare function isValidPathPart(part: string): boolean;
12
+ export declare function assertValidPathPart(part: string, label: string): void;
13
+ /** Record duplicate sibling path parts; returns diagnostics (does not throw). */
14
+ export declare function siblingUniquenessDiagnostics(parts: readonly string[], label: string): BuildDiagnostic[];