@nylorun/core 0.13.0-beta → 0.16.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 (90) hide show
  1. package/CHANGELOG.md +131 -0
  2. package/dist/compatibility.d.ts +68 -25
  3. package/dist/compatibility.js +67 -27
  4. package/dist/contracts.d.ts +325 -959
  5. package/dist/contracts.js +281 -516
  6. package/dist/define.d.ts +13 -10
  7. package/dist/define.js +7 -4
  8. package/dist/definition/assemble.d.ts +0 -3
  9. package/dist/definition/assemble.js +13 -19
  10. package/dist/definition/bind-agent.js +0 -2
  11. package/dist/definition/bind-tool.js +0 -1
  12. package/dist/definition/bound.d.ts +3 -10
  13. package/dist/definition/builder.d.ts +19 -55
  14. package/dist/definition/builder.js +19 -130
  15. package/dist/definition/capability.d.ts +3 -15
  16. package/dist/definition/capability.js +3 -25
  17. package/dist/definition/code-tools.d.ts +22 -0
  18. package/dist/definition/code-tools.js +46 -0
  19. package/dist/definition/declaration.d.ts +0 -3
  20. package/dist/definition/declaration.js +8 -11
  21. package/dist/definition/delegate.d.ts +7 -7
  22. package/dist/definition/flow/compile.d.ts +4 -5
  23. package/dist/definition/flow/compile.js +120 -72
  24. package/dist/definition/flow/from.d.ts +2 -2
  25. package/dist/definition/flow/from.js +14 -33
  26. package/dist/definition/flow/index.d.ts +2 -2
  27. package/dist/definition/flow/index.js +2 -2
  28. package/dist/definition/flow/paths.d.ts +32 -17
  29. package/dist/definition/flow/paths.js +35 -14
  30. package/dist/definition/flow/spec.d.ts +6 -9
  31. package/dist/definition/flow/spec.js +49 -31
  32. package/dist/definition/flow/types.d.ts +40 -116
  33. package/dist/definition/from.js +36 -41
  34. package/dist/definition/helpers.d.ts +1 -1
  35. package/dist/definition/helpers.js +1 -1
  36. package/dist/definition/http-tool.d.ts +66 -0
  37. package/dist/definition/http-tool.js +131 -0
  38. package/dist/definition/implementations.d.ts +0 -3
  39. package/dist/definition/manifest.js +5 -4
  40. package/dist/definition/mcp.d.ts +4 -2
  41. package/dist/definition/mcp.js +14 -18
  42. package/dist/definition/removed.d.ts +10 -0
  43. package/dist/definition/removed.js +26 -0
  44. package/dist/definition/sandbox-capability.d.ts +2 -0
  45. package/dist/definition/sandbox-capability.js +11 -1
  46. package/dist/definition/schema.js +0 -3
  47. package/dist/definition/skill-tools.d.ts +16 -2
  48. package/dist/definition/skill-tools.js +38 -31
  49. package/dist/definition/variant.d.ts +1 -1
  50. package/dist/definition/variant.js +3 -14
  51. package/dist/definition/workflow/diagnostics.d.ts +1 -7
  52. package/dist/definition/workflow/diagnostics.js +1 -24
  53. package/dist/definition/workflow/index.d.ts +3 -17
  54. package/dist/definition/workflow/index.js +2 -9
  55. package/dist/definition/workflow/runnable.d.ts +2 -34
  56. package/dist/definition/workflow/runnable.js +8 -142
  57. package/dist/definition/workflow/types.d.ts +1 -10
  58. package/dist/harness-api/messages.d.ts +24 -27
  59. package/dist/harness-api/messages.js +1 -1
  60. package/dist/harness-api/schema.d.ts +0 -16
  61. package/dist/harness-api/schema.js +5 -12
  62. package/dist/index.d.ts +1 -1
  63. package/dist/types/manifest.d.ts +41 -14
  64. package/dist/types/middleware.d.ts +11 -16
  65. package/dist/types/observe.d.ts +0 -6
  66. package/dist/types/tool.d.ts +0 -6
  67. package/dist/types/workflow.d.ts +54 -110
  68. package/dist/utils/definition-files.d.ts +31 -0
  69. package/dist/utils/definition-files.js +84 -0
  70. package/package.json +1 -1
  71. package/dist/definition/hooks.d.ts +0 -19
  72. package/dist/definition/hooks.js +0 -67
  73. package/dist/definition/workflow/build.d.ts +0 -28
  74. package/dist/definition/workflow/build.js +0 -40
  75. package/dist/definition/workflow/chain.d.ts +0 -49
  76. package/dist/definition/workflow/chain.js +0 -40
  77. package/dist/definition/workflow/loop.d.ts +0 -54
  78. package/dist/definition/workflow/loop.js +0 -100
  79. package/dist/definition/workflow/map.d.ts +0 -17
  80. package/dist/definition/workflow/map.js +0 -45
  81. package/dist/definition/workflow/parallel.d.ts +0 -19
  82. package/dist/definition/workflow/parallel.js +0 -36
  83. package/dist/definition/workflow/patch.d.ts +0 -11
  84. package/dist/definition/workflow/patch.js +0 -45
  85. package/dist/definition/workflow/slot.d.ts +0 -23
  86. package/dist/definition/workflow/slot.js +0 -16
  87. package/dist/definition/workflow/switch.d.ts +0 -26
  88. package/dist/definition/workflow/switch.js +0 -64
  89. package/dist/types/dynamics.d.ts +0 -101
  90. package/dist/types/dynamics.js +0 -1
@@ -1,7 +1,6 @@
1
1
  import type { StepMiddleware, CapabilityDeclaration } from "../types/middleware.js";
2
2
  import type { ToolDefinition } from "../types/tool.js";
3
3
  import type { AgentTool } from "../types/agent.js";
4
- import type { AfterHook, AfterHooks, BeforeHook, BeforeHooks } from "../types/dynamics.js";
5
4
  import type { ModelDirective } from "../types/model.js";
6
5
  export interface CapabilityIdentity {
7
6
  readonly id: string;
@@ -12,11 +11,7 @@ export interface CapabilityIdentity {
12
11
  export interface CapabilityOptions<Info = unknown> extends CapabilityIdentity {
13
12
  readonly tools?: readonly (ToolDefinition<any, Info, any> | AgentTool)[];
14
13
  readonly instructions?: string | readonly string[];
15
- /** Run before each turn or before every model call (step). */
16
- readonly before?: BeforeHooks<Info>;
17
- /** Run after every model call (step) or after the turn's final answer. */
18
- readonly after?: AfterHooks<Info>;
19
- /** @deprecated Prefer before / after hooks. */
14
+ /** @deprecated Runs in the local engine only. */
20
15
  readonly middleware?: StepMiddleware<Info>;
21
16
  /** @deprecated Model resolution is Runtime-owned; not projected into the manifest. */
22
17
  readonly model?: ModelDirective;
@@ -24,11 +19,9 @@ export interface CapabilityOptions<Info = unknown> extends CapabilityIdentity {
24
19
  type Parts<Info> = {
25
20
  readonly instructions?: readonly string[];
26
21
  readonly tools?: readonly (ToolDefinition<any, Info, any> | AgentTool)[];
27
- readonly before?: BeforeHooks<Info>;
28
- readonly after?: AfterHooks<Info>;
29
22
  };
30
23
  /**
31
- * A reusable bundle of instructions, tools and hooks, attached with `.capability()`.
24
+ * A reusable bundle of instructions and tools, attached with `.capability()`.
32
25
  * It has the same methods as a ReAct agent.
33
26
  */
34
27
  export declare class CapabilityBuilder<Info = unknown> {
@@ -38,18 +31,13 @@ export declare class CapabilityBuilder<Info = unknown> {
38
31
  instructions(...text: readonly string[]): CapabilityBuilder<Info>;
39
32
  tools(...tools: readonly ToolDefinition<any, Info, any>[]): CapabilityBuilder<Info>;
40
33
  subagents(...agents: readonly AgentTool[]): CapabilityBuilder<Info>;
41
- beforeTurn(fn: BeforeHook<"turn", Info>): CapabilityBuilder<Info>;
42
- beforeModel(fn: BeforeHook<"step", Info>): CapabilityBuilder<Info>;
43
- afterModel(fn: AfterHook<"step", Info>): CapabilityBuilder<Info>;
44
- afterTurn(fn: AfterHook<"turn", Info>): CapabilityBuilder<Info>;
45
34
  /** @internal The declaration `.capability()` attaches. */
46
35
  toDeclaration(): CapabilityDeclaration<Info>;
47
36
  private with;
48
- private hook;
49
37
  }
50
38
  export declare function isCapabilityBuilder(value: unknown): value is CapabilityBuilder<any>;
51
39
  /** Compose a reusable capability bundle: `capability({ id }).instructions(…).tools(…)`. */
52
40
  export declare function capability<Info = unknown>(identity: CapabilityIdentity): CapabilityBuilder<Info>;
53
- /** @deprecated Use `capability({ id }).instructions(…).tools(…).beforeTurn(…)`. */
41
+ /** @deprecated Use `capability({ id }).instructions(…).tools(…)`. */
54
42
  export declare function capability<Info = unknown>(declaration: CapabilityOptions<Info>): CapabilityDeclaration<Info>;
55
43
  export {};
@@ -3,7 +3,7 @@ import { delegateTool, isAgentItem } from "./delegate.js";
3
3
  import { deprecate } from "../utils/deprecate.js";
4
4
  const CAPABILITY = Symbol.for("nylorun.capability");
5
5
  /**
6
- * A reusable bundle of instructions, tools and hooks, attached with `.capability()`.
6
+ * A reusable bundle of instructions and tools, attached with `.capability()`.
7
7
  * It has the same methods as a ReAct agent.
8
8
  */
9
9
  export class CapabilityBuilder {
@@ -31,18 +31,6 @@ export class CapabilityBuilder {
31
31
  throw new HarnessError("configuration.invalid", ".subagents() takes agents; tools belong in .tools()");
32
32
  return this.with({ tools: [...(this.#parts.tools ?? []), ...agents] });
33
33
  }
34
- beforeTurn(fn) {
35
- return this.hook("before", "turn", fn);
36
- }
37
- beforeModel(fn) {
38
- return this.hook("before", "step", fn);
39
- }
40
- afterModel(fn) {
41
- return this.hook("after", "step", fn);
42
- }
43
- afterTurn(fn) {
44
- return this.hook("after", "turn", fn);
45
- }
46
34
  /** @internal The declaration `.capability()` attaches. */
47
35
  toDeclaration() {
48
36
  return declarationOf({ ...this.#identity, ...this.#parts });
@@ -50,19 +38,11 @@ export class CapabilityBuilder {
50
38
  with(parts) {
51
39
  return new CapabilityBuilder(this.#identity, { ...this.#parts, ...parts });
52
40
  }
53
- hook(at, scope, fn) {
54
- if (typeof fn !== "function")
55
- throw new HarnessError("configuration.invalid", `${at}${scope === "turn" ? "Turn" : "Model"}() requires a function`);
56
- const current = (this.#parts[at] ?? {});
57
- if (current[scope] !== undefined)
58
- throw new HarnessError("configuration.invalid", `Capability '${this.#identity.id}' already has a ${at}${scope === "turn" ? "Turn" : "Model"}() hook`);
59
- return this.with({ [at]: Object.freeze({ ...current, [scope]: fn }) });
60
- }
61
41
  }
62
42
  export function isCapabilityBuilder(value) {
63
43
  return !!value && typeof value === "object" && value[CAPABILITY] === true;
64
44
  }
65
- const LEGACY_FIELDS = ["tools", "instructions", "before", "after", "middleware", "model"];
45
+ const LEGACY_FIELDS = ["tools", "instructions", "middleware", "model"];
66
46
  export function capability(declaration) {
67
47
  const legacy = LEGACY_FIELDS.some((key) => declaration[key] !== undefined);
68
48
  if (!legacy)
@@ -71,7 +51,7 @@ export function capability(declaration) {
71
51
  ...(declaration.name === undefined ? {} : { name: declaration.name }),
72
52
  ...(declaration.description === undefined ? {} : { description: declaration.description }),
73
53
  });
74
- deprecate("NYLORUN_DEP_CAPABILITY_OPTIONS", "capability({ tools, instructions, before, after }) is deprecated. Use capability({ id }).instructions(…).tools(…).beforeTurn(…).");
54
+ deprecate("NYLORUN_DEP_CAPABILITY_OPTIONS", "capability({ tools, instructions }) is deprecated. Use capability({ id }).instructions(…).tools(…).");
75
55
  return declarationOf(declaration);
76
56
  }
77
57
  function declarationOf(declaration) {
@@ -94,8 +74,6 @@ function declarationOf(declaration) {
94
74
  : item),
95
75
  }),
96
76
  ...(instructions === undefined ? {} : { instructions }),
97
- ...(declaration.before === undefined ? {} : { before: declaration.before }),
98
- ...(declaration.after === undefined ? {} : { after: declaration.after }),
99
77
  ...(declaration.middleware === undefined
100
78
  ? {}
101
79
  : { middleware: declaration.middleware }),
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Tools that would run the developer's code (track R2 M6): an agent tool with no `http` and no
3
+ * `agent` that is not one of the Runtime's built-ins (sandbox tools, skill tools,
4
+ * `save_artifact`), and a flow agent's `tool` stage without `http`. The Runtime runs no code
5
+ * of yours during a session, so `PUT /v1/agents/:id` refuses a definition with one, and the
6
+ * SDK refuses it before sending. The local engine (`@nylorun/harness/run`) still runs
7
+ * `tool({ run })`.
8
+ */
9
+ import type { AgentManifest } from "../types/manifest.js";
10
+ import type { WorkflowManifest } from "../types/workflow.js";
11
+ /** One tool that would run the developer's code, and the definition that declares it. */
12
+ export interface CodeTool {
13
+ /** The tool's name, or a flow stage's tool name. */
14
+ readonly name: string;
15
+ /** The agent or flow agent that declares it. */
16
+ readonly owner: string;
17
+ readonly kind: "tool" | "stage";
18
+ }
19
+ /** Every code tool of a definition document, the agents it embeds or uses as tools included. */
20
+ export declare function codeToolsOf(manifest: AgentManifest | WorkflowManifest, into?: CodeTool[]): CodeTool[];
21
+ /** Why a definition with code tools is refused, naming the first; undefined when it has none. */
22
+ export declare function codeToolRefusal(manifest: AgentManifest | WorkflowManifest): string | undefined;
@@ -0,0 +1,46 @@
1
+ import { isSandboxToolName } from "../utils/sandbox.js";
2
+ import { forEachFlowNode } from "./flow/paths.js";
3
+ import { ARTIFACTS_CAPABILITY_ID, SAVE_ARTIFACT_TOOL } from "./sandbox-capability.js";
4
+ import { isSkillTool } from "./skill-tools.js";
5
+ /** Every code tool of a definition document, the agents it embeds or uses as tools included. */
6
+ export function codeToolsOf(manifest, into = []) {
7
+ if ("kind" in manifest && manifest.kind === "workflow") {
8
+ forEachFlowNode(manifest.root, ({ node }) => {
9
+ // An HTTP stage (`tool.http`) and an HTTP verifier are requests the Runtime makes.
10
+ if ("tool" in node && node.tool.http === undefined)
11
+ into.push({ name: node.tool.name, owner: manifest.id, kind: "stage" });
12
+ });
13
+ for (const agent of Object.values(manifest.agents))
14
+ codeToolsOf(agent, into);
15
+ return into;
16
+ }
17
+ for (const capability of manifest.capabilities)
18
+ for (const tool of capability.tools ?? []) {
19
+ if (tool.agent !== undefined)
20
+ codeToolsOf(tool.agent, into);
21
+ else if (!runsWithoutCode(capability, tool))
22
+ into.push({ name: tool.name, owner: manifest.id, kind: "tool" });
23
+ }
24
+ return into;
25
+ }
26
+ /** An HTTP tool, or a built-in the Runtime serves. */
27
+ function runsWithoutCode(capability, tool) {
28
+ if (tool.http !== undefined)
29
+ return true;
30
+ if (capability.sandbox !== undefined && isSandboxToolName(tool.name))
31
+ return true;
32
+ if (capability.id === ARTIFACTS_CAPABILITY_ID && tool.name === SAVE_ARTIFACT_TOOL)
33
+ return true;
34
+ return isSkillTool(capability, tool.name);
35
+ }
36
+ /** Why a definition with code tools is refused, naming the first; undefined when it has none. */
37
+ export function codeToolRefusal(manifest) {
38
+ const [first, ...rest] = codeToolsOf(manifest);
39
+ if (!first)
40
+ return undefined;
41
+ const what = first.kind === "stage"
42
+ ? `The tool stage '${first.name}' of flow agent '${first.owner}'`
43
+ : `Tool '${first.name}' of agent '${first.owner}'`;
44
+ const more = rest.length === 0 ? "" : ` (and ${rest.length} more)`;
45
+ return `${what}${more} runs your code, and the Runtime runs no code of yours during a session. Make it an http() tool or serve it from a remote MCP server (see MIGRATION.md).`;
46
+ }
@@ -1,10 +1,7 @@
1
1
  import type { BoundMiddleware } from "./bound.js";
2
2
  import type { CapabilityInput, StepMiddleware } from "../types/middleware.js";
3
- import type { AfterHooks, BeforeHooks } from "../types/dynamics.js";
4
3
  export interface CompiledCapability {
5
4
  readonly bound: BoundMiddleware;
6
- readonly before?: BeforeHooks<any>;
7
- readonly after?: AfterHooks<any>;
8
5
  readonly middleware?: StepMiddleware<any>;
9
6
  }
10
7
  export declare function compileDeclaration<State>(declaration: CapabilityInput<State>): CompiledCapability;
@@ -1,10 +1,13 @@
1
- import { hooksFrom } from "./hooks.js";
2
1
  import { delegateTool, isAgentItem } from "./delegate.js";
2
+ import { HarnessError } from "../errors.js";
3
+ import { REMOVED_CAPABILITY_FIELDS } from "./removed.js";
3
4
  export function compileDeclaration(declaration) {
5
+ for (const field of ["before", "after"])
6
+ if (declaration[field] !== undefined)
7
+ throw new HarnessError("configuration.invalid", `Capability '${declaration.id}': ${REMOVED_CAPABILITY_FIELDS.hooks}`);
4
8
  const tools = asTools(copyItems(declaration.tools, declaration.id));
5
9
  const instructions = copyItems(declaration.instructions, declaration.id);
6
10
  const model = declaration.model;
7
- const hooks = hooksFrom(declaration.before, declaration.after);
8
11
  const contributions = snapshotContributions(instructions?.items, tools?.items, model);
9
12
  const handle = async (request, next) => {
10
13
  if (tools)
@@ -28,7 +31,6 @@ export function compileDeclaration(declaration) {
28
31
  hasMiddleware: declaration.middleware !== undefined,
29
32
  tools: tools?.items,
30
33
  ...(contributions === undefined ? {} : { contributions }),
31
- ...(hooks === undefined ? {} : { hooks }),
32
34
  ...(declaration.type === undefined ? {} : { manifestType: declaration.type }),
33
35
  ...(declaration.metadata === undefined
34
36
  ? {}
@@ -37,10 +39,10 @@ export function compileDeclaration(declaration) {
37
39
  Object.keys(declaration.skills).length === 0
38
40
  ? {}
39
41
  : { skills: declaration.skills }),
40
- ...(declaration.skillRecords === undefined ||
41
- Object.keys(declaration.skillRecords).length === 0
42
+ ...(declaration.skillFiles === undefined ||
43
+ Object.keys(declaration.skillFiles).length === 0
42
44
  ? {}
43
- : { skillRecords: declaration.skillRecords }),
45
+ : { skillFiles: declaration.skillFiles }),
44
46
  ...(declaration.mcpServers === undefined ||
45
47
  Object.keys(declaration.mcpServers).length === 0
46
48
  ? {}
@@ -49,12 +51,7 @@ export function compileDeclaration(declaration) {
49
51
  ...(sandboxOf(declaration) === undefined
50
52
  ? {}
51
53
  : { sandbox: sandboxOf(declaration) }),
52
- ...(declaration.pluginRoot === undefined
53
- ? {}
54
- : { pluginRoot: declaration.pluginRoot }),
55
54
  },
56
- ...(declaration.before === undefined ? {} : { before: declaration.before }),
57
- ...(declaration.after === undefined ? {} : { after: declaration.after }),
58
55
  ...(declaration.middleware ? { middleware: declaration.middleware } : {}),
59
56
  };
60
57
  }
@@ -1,6 +1,6 @@
1
1
  import type { BuiltAgent } from "../types/agent.js";
2
2
  import type { AgentManifest } from "../types/manifest.js";
3
- import type { WorkflowManifestV2 } from "../types/workflow.js";
3
+ import type { WorkflowManifest } from "../types/workflow.js";
4
4
  import type { BuiltWorkflow } from "./workflow/types.js";
5
5
  import type { JsonObject } from "../types/shared.js";
6
6
  import type { ToolDefinition } from "../types/tool.js";
@@ -8,9 +8,9 @@ import type { ToolDefinition } from "../types/tool.js";
8
8
  export interface Delegate {
9
9
  /**
10
10
  * The child's manifest, inlined into the parent's tool. A flow agent's workflow manifest
11
- * v2 runs in its own linked session on the Runtime, not inside the parent's run.
11
+ * v3 runs in its own linked session on the Runtime, not inside the parent's run.
12
12
  */
13
- readonly manifest: AgentManifest | WorkflowManifestV2;
13
+ readonly manifest: AgentManifest | WorkflowManifest;
14
14
  /** The authored child, when available locally. Absent when rebuilt from a manifest. */
15
15
  readonly agent?: BuiltAgent;
16
16
  /** The authored flow agent, when the child is one and available locally. */
@@ -18,7 +18,7 @@ export interface Delegate {
18
18
  }
19
19
  /** True when the delegate is a flow agent, which runs in its own linked session. */
20
20
  export declare function isFlowDelegate(delegate: Delegate): delegate is Delegate & {
21
- readonly manifest: WorkflowManifestV2;
21
+ readonly manifest: WorkflowManifest;
22
22
  };
23
23
  /** Model-facing tool names: what every supported provider accepts. */
24
24
  export declare const DELEGATE_NAME_PATTERN: RegExp;
@@ -31,7 +31,7 @@ export declare function isAgentItem(value: unknown): value is Pick<BuiltAgent, "
31
31
  /** Turn an agent placed in `tools` into the tool that delegates to it. */
32
32
  export declare function delegateTool(item: unknown): ToolDefinition;
33
33
  /** Rebuild the delegating tool from a manifest's `agent` body. */
34
- export declare function delegateFromManifest(manifest: AgentManifest | WorkflowManifestV2, tool: {
34
+ export declare function delegateFromManifest(manifest: AgentManifest | WorkflowManifest, tool: {
35
35
  readonly description?: string;
36
36
  readonly inputSchema: JsonObject;
37
37
  }): ToolDefinition;
@@ -48,9 +48,9 @@ export declare function delegatesOf(manifest: AgentManifest): readonly {
48
48
  /** The flow agents a manifest delegates to: each runs in its own linked session. */
49
49
  export declare function flowDelegatesOf(manifest: AgentManifest): readonly {
50
50
  readonly capabilityId: string;
51
- readonly manifest: WorkflowManifestV2;
51
+ readonly manifest: WorkflowManifest;
52
52
  }[];
53
53
  /** The flow agent `id` a manifest delegates to, or undefined. */
54
- export declare function flowDelegateManifest(manifest: AgentManifest, id: string): WorkflowManifestV2 | undefined;
54
+ export declare function flowDelegateManifest(manifest: AgentManifest, id: string): WorkflowManifest | undefined;
55
55
  /** The manifest of the delegated agent `id`, or undefined. One level deep by construction. */
56
56
  export declare function delegateManifest(manifest: AgentManifest, id: string): AgentManifest | undefined;
@@ -1,10 +1,9 @@
1
1
  /**
2
- * Compile a flow agent's stages to workflow manifest v2.
2
+ * Compile a flow agent's stages to workflow manifest v3.
3
3
  *
4
- * Each stage becomes one node with optional `id` and `input`; leaf agents are
5
- * embedded in `agents`; user functions are bound under stage keys (`route:on`,
6
- * `@1.default.1:input`) and receive `{ input, results, flowInput }` from the engine
7
- * as written. Paths and keys follow `./paths.ts`.
4
+ * Each stage becomes one node with an optional `id`; leaf agents are embedded in
5
+ * `agents`; tool nodes are bound under their stage keys, except HTTP stages, which carry
6
+ * their `http` target and bind nothing. Paths and keys follow `./paths.ts`.
8
7
  */
9
8
  import type { JsonObject } from "../../types/shared.js";
10
9
  import type { ToolSchemaSource } from "../../types/tool.js";
@@ -1,3 +1,4 @@
1
+ import { httpToolOf, isHttpTarget } from "../http-tool.js";
1
2
  import { bindingFromAgent } from "../binding.js";
2
3
  import { bindOutputContract } from "../output-contract.js";
3
4
  import { copyJsonObject } from "../../utils/immutable.js";
@@ -6,13 +7,13 @@ import { diagnostic, fail } from "../workflow/diagnostics.js";
6
7
  import { isBuiltWorkflow } from "../workflow/types.js";
7
8
  import { bindToolNode, builtAgentOf, isToolDefinition, toolManifestNode, } from "../workflow/runnable.js";
8
9
  import { isFlowBuilder, isNamedChild } from "./spec.js";
9
- import { forEachFlowNode, functionKey, isWorkflowManifestV2, leafPart, } from "./paths.js";
10
+ import { forEachFlowNode, isWorkflowManifest, leafPart } from "./paths.js";
10
11
  /** Compile a flow agent. Throws `WorkflowBuildError` with diagnostics. */
11
12
  export function compileAgentFlow(options) {
12
13
  const stages = expand(options.stages);
13
14
  if (stages.length === 0)
14
15
  fail([
15
- diagnostic("flow.empty", `Flow agent '${options.id}' has no stages. Add .step(), .switch(), .parallel(), .map() or .loop().`),
16
+ diagnostic("flow.empty", `Flow agent '${options.id}' has no stages. Add .pipe(), .switch(), .parallel(), .map() or .loop().`),
16
17
  ]);
17
18
  const build = {
18
19
  id: options.id,
@@ -22,12 +23,13 @@ export function compileAgentFlow(options) {
22
23
  diagnostics: [],
23
24
  };
24
25
  const root = { chain: stages.map((stage) => compileStage(stage, build)) };
26
+ checkHttpInputs(root, build, options.inputSchema && jsonSchemaOf(options.inputSchema));
25
27
  const nodes = bindNodes(root, build);
26
28
  if (build.diagnostics.length)
27
29
  fail(build.diagnostics);
28
30
  const manifest = {
29
31
  kind: "workflow",
30
- workflowSchemaVersion: 2,
32
+ workflowSchemaVersion: 3,
31
33
  id: options.id,
32
34
  ...(options.name === undefined ? {} : { name: options.name }),
33
35
  ...(options.description === undefined ? {} : { description: options.description }),
@@ -56,14 +58,11 @@ export function compileAgentFlow(options) {
56
58
  Object.defineProperty(built, "getBinding", { value: () => binding, enumerable: false });
57
59
  return built;
58
60
  }
59
- /** Inline `.step(flow())` sequences that have no id or input into their parent. */
61
+ /** Inline `.pipe(flow())` sequences that have no id into their parent. */
60
62
  function expand(stages) {
61
63
  const out = [];
62
64
  for (const stage of stages) {
63
- if (stage.kind === "step" &&
64
- isFlowBuilder(stage.child) &&
65
- stage.id === undefined &&
66
- stage.input === undefined)
65
+ if (stage.kind === "step" && isFlowBuilder(stage.child) && stage.id === undefined)
67
66
  out.push(...expand(stage.child.stages));
68
67
  else
69
68
  out.push(stage);
@@ -71,67 +70,59 @@ function expand(stages) {
71
70
  return out;
72
71
  }
73
72
  function compileStage(stage, build) {
74
- const options = { id: stage.id, input: stage.input };
75
73
  switch (stage.kind) {
76
74
  case "step":
77
- return withOptions(childNode(stage.child, build), options, build);
75
+ return withId(childNode(stage.child, build), stage.id, build);
78
76
  case "switch": {
79
77
  const { default: fallback, ...cases } = stage.cases;
80
78
  const node = {
81
79
  switch: {
82
- on: { fn: true },
83
80
  cases: mapValues(cases, (child) => childNode(child, build)),
84
81
  ...(fallback === undefined ? {} : { default: childNode(fallback, build) }),
85
82
  },
86
83
  };
87
- attach(build, node, { on: stage.on });
88
- return withOptions(node, options, build);
84
+ return withId(node, stage.id, build);
89
85
  }
90
86
  case "parallel":
91
- return withOptions({ parallel: mapValues(stage.branches, (child) => childNode(child, build)) }, options, build);
87
+ return withId({ parallel: mapValues(stage.branches, (child) => childNode(child, build)) }, stage.id, build);
92
88
  case "map":
93
- return withOptions({ map: { each: childNode(stage.each, build) } }, options, build);
89
+ return withId({ map: { each: childNode(stage.each, build) } }, stage.id, build);
94
90
  case "loop":
95
- return withOptions(compileLoop(stage, build), options, build);
91
+ return withId(compileLoop(stage, build), stage.id, build);
96
92
  }
97
93
  }
98
94
  function compileLoop(stage, build) {
99
95
  const label = stage.id ?? "loop";
100
- if (stage.max !== undefined && (!Number.isInteger(stage.max) || stage.max < 1))
96
+ if (stage.max === undefined)
97
+ build.diagnostics.push(diagnostic("loop.max-required", `Loop '${label}' needs { max } so it cannot run forever`));
98
+ else if (!Number.isInteger(stage.max) || stage.max < 1)
101
99
  build.diagnostics.push(diagnostic("loop.invalid-max", `Loop '${label}' max must be a positive integer`));
102
- if (stage.max === undefined && stage.decide === undefined)
103
- build.diagnostics.push(diagnostic("loop.max-required", `Loop '${label}' needs { max } or { decide } so it cannot run forever`));
104
100
  // The body first, so agents are embedded in the order they run.
105
101
  const run = childNode(stage.body, build);
106
- let verify = { fn: true };
107
- const code = {};
108
- if (typeof stage.verify === "function")
109
- code.verify = stage.verify;
110
- else {
111
- const judge = childNode(stage.verify, build);
112
- if (!("agent" in judge)) {
113
- build.diagnostics.push(diagnostic("loop.invalid-verify", `Loop '${label}' verify must be a function or an agent, not a tool or flow()`));
114
- }
115
- else
116
- verify = judge;
117
- }
118
- if (stage.decide)
119
- code.decide = stage.decide;
120
- const node = {
102
+ return {
121
103
  loop: {
122
104
  run,
123
- verify,
124
- ...(Number.isInteger(stage.max) && stage.max > 0 ? { max: stage.max } : {}),
125
- ...(stage.decide === undefined ? {} : { decide: { fn: true } }),
105
+ verify: verifyNode(stage.verify, label, build),
106
+ max: Number.isInteger(stage.max) && stage.max > 0 ? stage.max : 1,
126
107
  },
127
108
  };
128
- attach(build, node, code);
129
- return node;
109
+ }
110
+ /** A Loop's verifier: a verifier agent, or an HTTP verifier (`http({ url })`). */
111
+ function verifyNode(verify, label, build) {
112
+ if (isHttpTarget(verify))
113
+ return { http: { ...verify.http } };
114
+ const node = isToolDefinition(verify) && httpToolOf(verify) ? undefined : childNode(verify, build);
115
+ if (node && "agent" in node)
116
+ return node;
117
+ build.diagnostics.push(diagnostic("loop.invalid-verify", node
118
+ ? `Loop '${label}' verify must be a verifier agent or an HTTP verifier, http({ url }), not a tool or flow()`
119
+ : `Loop '${label}' verify takes an HTTP verifier, http({ url }) with no name or input, not an HTTP tool`));
120
+ return { agent: "" };
130
121
  }
131
122
  /** A stage child: an agent, tool, nested flow agent, `flow()` or `.withId()` child. */
132
123
  function childNode(child, build) {
133
124
  if (isNamedChild(child))
134
- return withOptions(childNode(child.run, build), { id: child.id }, build);
125
+ return withId(childNode(child.run, build), child.id, build);
135
126
  if (isFlowBuilder(child)) {
136
127
  const stages = expand(child.stages);
137
128
  if (stages.length === 0) {
@@ -145,8 +136,19 @@ function childNode(child, build) {
145
136
  if (isToolDefinition(child)) {
146
137
  const tool = bindToolNode(child);
147
138
  const node = toolManifestNode(tool);
148
- attach(build, node, { tool });
149
- return node;
139
+ const target = httpToolOf(child);
140
+ if (!target) {
141
+ attach(build, node, { tool });
142
+ return node;
143
+ }
144
+ if (target.approval === "always")
145
+ build.diagnostics.push(diagnostic("flow.approval-unsupported", `HTTP stage '${tool.name}': approval on a flow stage is not supported yet`));
146
+ // The Runtime runs it through its Tool Gate: nothing is bound.
147
+ return { tool: { ...node.tool, http: { ...target.http } } };
148
+ }
149
+ if (isHttpTarget(child)) {
150
+ build.diagnostics.push(diagnostic("workflow.invalid-runnable", "http({ url }) without a name and an input is a Loop verifier; an HTTP stage needs http({ name, input, url })"));
151
+ return { chain: [] };
150
152
  }
151
153
  if (child && typeof child === "object") {
152
154
  const built = builtOf(child);
@@ -174,10 +176,6 @@ function agentLeaf(agent, build) {
174
176
  return { agent: resolved.id };
175
177
  }
176
178
  function nestedFlow(built, build) {
177
- if (!isWorkflowManifestV2(built.manifest)) {
178
- build.diagnostics.push(diagnostic("flow.v1-workflow", `Workflow '${built.id}' was built with Chain, Switch, Parallel, Map or Loop, so it can't be a step of flow agent '${build.id}'. Write it as a flow agent: Agent({ id: "${built.id}" }).step(…).`));
179
- return { chain: [] };
180
- }
181
179
  const binding = built.getBinding();
182
180
  embed(build, built.id, built.manifest);
183
181
  for (const [id, agent] of Object.entries(binding.agents))
@@ -202,22 +200,14 @@ function addBinding(build, id, binding) {
202
200
  else if (canonical(existing.manifest) !== canonical(binding.manifest))
203
201
  build.diagnostics.push(diagnostic("flow.agent-conflict", `Flow agent '${build.id}' uses two different agents with the id '${id}'. Give each agent its own id.`));
204
202
  }
205
- /** Put a stage's `id` and `input` on its node, wrapping it in a chain when it has its own. */
206
- function withOptions(node, options, build) {
207
- if (options.id === undefined && options.input === undefined)
203
+ /** Put a stage's `id` on its node, wrapping it in a chain when it has its own. */
204
+ function withId(node, id, build) {
205
+ if (id === undefined)
208
206
  return node;
209
- const clash = (options.id !== undefined && node.id !== undefined) ||
210
- (options.input !== undefined && node.input !== undefined);
211
- const target = clash ? { chain: [node] } : node;
212
- const next = {
213
- ...target,
214
- ...(options.id === undefined ? {} : { id: options.id }),
215
- ...(options.input === undefined ? {} : { input: { fn: true } }),
216
- };
217
- const code = { ...(clash ? {} : build.code.get(node)) };
218
- if (options.input)
219
- code.input = options.input;
220
- attach(build, next, code);
207
+ const clash = node.id !== undefined;
208
+ const next = { ...(clash ? { chain: [node] } : node), id };
209
+ if (!clash)
210
+ attach(build, next, build.code.get(node) ?? {});
221
211
  return next;
222
212
  }
223
213
  function attach(build, node, code) {
@@ -226,7 +216,7 @@ function attach(build, node, code) {
226
216
  }
227
217
  /**
228
218
  * Walk the finished tree: check that leaves and stage ids are unique, and bind each
229
- * node's code under its stage key.
219
+ * tool node's code under its stage key.
230
220
  */
231
221
  function bindNodes(root, build) {
232
222
  const nodes = {};
@@ -236,10 +226,10 @@ function bindNodes(root, build) {
236
226
  const part = leafPart(node);
237
227
  if (part !== undefined) {
238
228
  if (leaves.has(part) || ids.has(part))
239
- build.diagnostics.push(diagnostic("flow.duplicate-leaf", `'${part}' runs twice in flow agent '${build.id}'. Give one a new id: .step(x, { id: "${part}-2" }) or x.withId("${part}-2").`));
229
+ build.diagnostics.push(diagnostic("flow.duplicate-leaf", `'${part}' runs twice in flow agent '${build.id}'. Give one a new id: x.withId("${part}-2").`));
240
230
  leaves.add(part);
241
231
  }
242
- else if (node.id !== undefined) {
232
+ else if ("id" in node && node.id !== undefined) {
243
233
  if (ids.has(node.id) || leaves.has(node.id))
244
234
  build.diagnostics.push(diagnostic("flow.duplicate-id", `Two stages of flow agent '${build.id}' are named '${node.id}'. Stage ids must be unique.`));
245
235
  ids.add(node.id);
@@ -247,14 +237,6 @@ function bindNodes(root, build) {
247
237
  const code = build.code.get(node);
248
238
  if (!code)
249
239
  return;
250
- if (code.input)
251
- nodes[functionKey(key, "input")] = { kind: "fn", fn: code.input };
252
- if (code.on)
253
- nodes[functionKey(key, "on")] = { kind: "fn", fn: code.on };
254
- if (code.verify)
255
- nodes[functionKey(key, "verify")] = { kind: "verify", fn: code.verify };
256
- if (code.decide)
257
- nodes[functionKey(key, "decide")] = { kind: "fn", fn: code.decide };
258
240
  if (code.tool)
259
241
  nodes[key] = { kind: "tool", tool: code.tool };
260
242
  if (code.nested)
@@ -263,6 +245,72 @@ function bindNodes(root, build) {
263
245
  });
264
246
  return nodes;
265
247
  }
248
+ const TYPE_NAMES = {
249
+ string: "text",
250
+ array: "a list",
251
+ object: "an object",
252
+ number: "a number",
253
+ integer: "a number",
254
+ boolean: "a boolean",
255
+ null: "null",
256
+ };
257
+ /**
258
+ * Refuse an HTTP stage whose input is known at build time to be of the wrong JSON type: the
259
+ * stage before it returns text (an agent with no output schema), a list (a Map), or a schema of
260
+ * another type, or the flow's input schema does. Anything else is checked when the stage runs.
261
+ */
262
+ function checkHttpInputs(root, build, flowInput) {
263
+ const check = (node, before) => {
264
+ const first = firstStage(node);
265
+ if (!("tool" in first) || !first.tool.http)
266
+ return;
267
+ const wanted = first.tool.inputSchema?.type;
268
+ if (typeof wanted !== "string" || before.type === undefined || before.type === wanted)
269
+ return;
270
+ const takes = TYPE_NAMES[wanted] ?? wanted;
271
+ const returns = TYPE_NAMES[before.type] ?? before.type;
272
+ build.diagnostics.push(diagnostic("flow.input-mismatch", `HTTP stage '${first.tool.name}' takes ${takes} (its input schema), but ${before.what} returns ${returns}${before.hint ?? ""}`));
273
+ };
274
+ if ("chain" in root && root.chain.length > 0) {
275
+ const type = flowInput?.type;
276
+ if (typeof type === "string")
277
+ check(root.chain[0], { type, what: "the flow's input schema" });
278
+ }
279
+ forEachFlowNode(root, ({ node }) => {
280
+ if (!("chain" in node))
281
+ return;
282
+ node.chain.forEach((step, index) => {
283
+ if (index > 0)
284
+ check(step, outputOf(node.chain[index - 1], build));
285
+ });
286
+ });
287
+ }
288
+ /** The stage that gets a node's input. */
289
+ function firstStage(node) {
290
+ return "chain" in node && node.chain.length > 0 ? firstStage(node.chain[0]) : node;
291
+ }
292
+ /** What is known at build time of a node's output: its JSON type, if any. */
293
+ function outputOf(node, build) {
294
+ if ("chain" in node && node.chain.length > 0)
295
+ return outputOf(node.chain.at(-1), build);
296
+ if ("map" in node)
297
+ return { type: "array", what: "the Map before it" };
298
+ if ("parallel" in node)
299
+ return { type: "object", what: "the Parallel before it" };
300
+ const typeOf = (schema) => typeof schema?.type === "string" ? { type: schema.type } : {};
301
+ if ("tool" in node)
302
+ return { ...typeOf(node.tool.outputSchema), what: `tool '${node.tool.name}'` };
303
+ if ("agent" in node) {
304
+ const agent = build.agents[node.agent];
305
+ const what = `agent '${node.agent}'`;
306
+ if (!agent)
307
+ return { what };
308
+ if (agent.outputSchema || isWorkflowManifest(agent))
309
+ return { ...typeOf(agent.outputSchema), what };
310
+ return { type: "string", what, hint: `: give '${node.agent}' an .output() schema` };
311
+ }
312
+ return { what: "the stage before it" };
313
+ }
266
314
  function jsonSchemaOf(source) {
267
315
  return bindOutputContract(source).schema.jsonSchema;
268
316
  }
@@ -3,8 +3,8 @@ import type { Implementations } from "../implementations.js";
3
3
  import type { BuiltWorkflow } from "../workflow/types.js";
4
4
  /** The code a flow agent's manifest names, keyed as the manifest's stage keys. */
5
5
  export interface FlowImplementations {
6
- /** Stage functions (`route:on`, `@1:input`) and tool nodes (`open_pr`). */
7
- readonly nodes?: Readonly<Record<string, ((args: any) => unknown) | ToolDefinition<any, any, any>>>;
6
+ /** Tool nodes, by stage key (`open_pr`). */
7
+ readonly nodes?: Readonly<Record<string, ToolDefinition<any, any, any>>>;
8
8
  /** Implementations for each embedded agent, by agent id. */
9
9
  readonly agents?: Readonly<Record<string, Implementations<any>>>;
10
10
  }