@nylorun/core 0.6.0-beta → 0.8.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 +66 -0
- package/dist/compatibility.d.ts +13 -2
- package/dist/compatibility.js +19 -1
- package/dist/contracts.d.ts +247 -0
- package/dist/contracts.js +353 -4
- package/dist/define.d.ts +10 -2
- package/dist/define.js +5 -1
- package/dist/definition/assemble.js +7 -0
- package/dist/definition/builder.d.ts +122 -16
- package/dist/definition/builder.js +354 -53
- package/dist/definition/capability.d.ts +55 -0
- package/dist/definition/capability.js +104 -0
- package/dist/definition/delegate.d.ts +25 -4
- package/dist/definition/delegate.js +34 -6
- package/dist/definition/flow/compile.d.ts +25 -0
- package/dist/definition/flow/compile.js +302 -0
- package/dist/definition/flow/from.d.ts +11 -0
- package/dist/definition/flow/from.js +78 -0
- package/dist/definition/flow/index.d.ts +11 -0
- package/dist/definition/flow/index.js +11 -0
- package/dist/definition/flow/paths.d.ts +60 -0
- package/dist/definition/flow/paths.js +90 -0
- package/dist/definition/flow/spec.d.ts +66 -0
- package/dist/definition/flow/spec.js +130 -0
- package/dist/definition/flow/types.d.ts +159 -0
- package/dist/definition/flow/types.js +1 -0
- package/dist/definition/from.js +5 -1
- package/dist/definition/helpers.d.ts +1 -16
- package/dist/definition/helpers.js +1 -30
- package/dist/definition/mcp.d.ts +37 -0
- package/dist/definition/mcp.js +81 -0
- package/dist/definition/sandbox.d.ts +29 -0
- package/dist/definition/sandbox.js +93 -0
- package/dist/definition/workflow/loop.js +2 -2
- package/dist/definition/workflow/runnable.d.ts +13 -1
- package/dist/definition/workflow/runnable.js +11 -7
- package/dist/types/manifest.d.ts +4 -2
- package/dist/types/workflow.d.ts +72 -3
- package/dist/utils/deprecate.d.ts +3 -0
- package/dist/utils/deprecate.js +25 -0
- package/package.json +2 -2
|
@@ -1,14 +1,25 @@
|
|
|
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";
|
|
4
|
+
import type { BuiltWorkflow } from "./workflow/types.js";
|
|
3
5
|
import type { JsonObject } from "../types/shared.js";
|
|
4
6
|
import type { ToolDefinition } from "../types/tool.js";
|
|
5
7
|
/** An agent used as another agent's tool. The engine runs it; customer code never does. */
|
|
6
8
|
export interface Delegate {
|
|
7
|
-
/**
|
|
8
|
-
|
|
9
|
+
/**
|
|
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.
|
|
12
|
+
*/
|
|
13
|
+
readonly manifest: AgentManifest | WorkflowManifestV2;
|
|
9
14
|
/** The authored child, when available locally. Absent when rebuilt from a manifest. */
|
|
10
15
|
readonly agent?: BuiltAgent;
|
|
16
|
+
/** The authored flow agent, when the child is one and available locally. */
|
|
17
|
+
readonly workflow?: BuiltWorkflow;
|
|
11
18
|
}
|
|
19
|
+
/** True when the delegate is a flow agent, which runs in its own linked session. */
|
|
20
|
+
export declare function isFlowDelegate(delegate: Delegate): delegate is Delegate & {
|
|
21
|
+
readonly manifest: WorkflowManifestV2;
|
|
22
|
+
};
|
|
12
23
|
/** Model-facing tool names: what every supported provider accepts. */
|
|
13
24
|
export declare const DELEGATE_NAME_PATTERN: RegExp;
|
|
14
25
|
/** The input every agent used as a tool accepts. Part of the hashed manifest; change deliberately. */
|
|
@@ -20,16 +31,26 @@ export declare function isAgentItem(value: unknown): value is Pick<BuiltAgent, "
|
|
|
20
31
|
/** Turn an agent placed in `tools` into the tool that delegates to it. */
|
|
21
32
|
export declare function delegateTool(item: unknown): ToolDefinition;
|
|
22
33
|
/** Rebuild the delegating tool from a manifest's `agent` body. */
|
|
23
|
-
export declare function delegateFromManifest(manifest: AgentManifest, tool: {
|
|
34
|
+
export declare function delegateFromManifest(manifest: AgentManifest | WorkflowManifestV2, tool: {
|
|
24
35
|
readonly description?: string;
|
|
25
36
|
readonly inputSchema: JsonObject;
|
|
26
37
|
}): ToolDefinition;
|
|
27
38
|
/** The delegate behind a tool definition, or behind the bound snapshot of one. */
|
|
28
39
|
export declare function delegateOf(tool: unknown): Delegate | undefined;
|
|
29
|
-
/**
|
|
40
|
+
/**
|
|
41
|
+
* The ReAct agents a manifest delegates to, which the engine runs inside the parent's run,
|
|
42
|
+
* with the capability that declares each. Flow agents are in `flowDelegatesOf`.
|
|
43
|
+
*/
|
|
30
44
|
export declare function delegatesOf(manifest: AgentManifest): readonly {
|
|
31
45
|
readonly capabilityId: string;
|
|
32
46
|
readonly manifest: AgentManifest;
|
|
33
47
|
}[];
|
|
48
|
+
/** The flow agents a manifest delegates to: each runs in its own linked session. */
|
|
49
|
+
export declare function flowDelegatesOf(manifest: AgentManifest): readonly {
|
|
50
|
+
readonly capabilityId: string;
|
|
51
|
+
readonly manifest: WorkflowManifestV2;
|
|
52
|
+
}[];
|
|
53
|
+
/** The flow agent `id` a manifest delegates to, or undefined. */
|
|
54
|
+
export declare function flowDelegateManifest(manifest: AgentManifest, id: string): WorkflowManifestV2 | undefined;
|
|
34
55
|
/** The manifest of the delegated agent `id`, or undefined. One level deep by construction. */
|
|
35
56
|
export declare function delegateManifest(manifest: AgentManifest, id: string): AgentManifest | undefined;
|
|
@@ -4,6 +4,10 @@ import { normalizeSchema } from "./schema.js";
|
|
|
4
4
|
import { schemaFromJSON } from "./schema-json.js";
|
|
5
5
|
/** Survives duplicate installed copies of core, like the error brands. */
|
|
6
6
|
const DELEGATE = Symbol.for("@nylorun/core/delegate");
|
|
7
|
+
/** True when the delegate is a flow agent, which runs in its own linked session. */
|
|
8
|
+
export function isFlowDelegate(delegate) {
|
|
9
|
+
return delegate.manifest.kind === "workflow";
|
|
10
|
+
}
|
|
7
11
|
/** Model-facing tool names: what every supported provider accepts. */
|
|
8
12
|
export const DELEGATE_NAME_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
|
|
9
13
|
const taskSchema = z
|
|
@@ -31,14 +35,18 @@ export function isAgentItem(value) {
|
|
|
31
35
|
/** Turn an agent placed in `tools` into the tool that delegates to it. */
|
|
32
36
|
export function delegateTool(item) {
|
|
33
37
|
const candidate = item;
|
|
34
|
-
const
|
|
35
|
-
|
|
38
|
+
const built = typeof candidate.build === "function" ? candidate.build() : candidate;
|
|
39
|
+
if (built.manifest.kind === "workflow") {
|
|
40
|
+
const workflow = built;
|
|
41
|
+
return withDelegate(workflow.manifest, undefined, undefined, workflow);
|
|
42
|
+
}
|
|
43
|
+
return withDelegate(built.manifest, built);
|
|
36
44
|
}
|
|
37
45
|
/** Rebuild the delegating tool from a manifest's `agent` body. */
|
|
38
46
|
export function delegateFromManifest(manifest, tool) {
|
|
39
47
|
return withDelegate(manifest, undefined, tool);
|
|
40
48
|
}
|
|
41
|
-
function withDelegate(manifest, agent, declared) {
|
|
49
|
+
function withDelegate(manifest, agent, declared, workflow) {
|
|
42
50
|
const description = declared ? declared.description : manifest.description;
|
|
43
51
|
const definition = {
|
|
44
52
|
name: manifest.id,
|
|
@@ -46,7 +54,11 @@ function withDelegate(manifest, agent, declared) {
|
|
|
46
54
|
inputSchema: declared ? schemaFromJSON(declared.inputSchema) : taskSchema,
|
|
47
55
|
execute: engineOnly,
|
|
48
56
|
};
|
|
49
|
-
const delegate = Object.freeze({
|
|
57
|
+
const delegate = Object.freeze({
|
|
58
|
+
manifest,
|
|
59
|
+
...(agent ? { agent } : {}),
|
|
60
|
+
...(workflow ? { workflow } : {}),
|
|
61
|
+
});
|
|
50
62
|
Object.defineProperty(definition, DELEGATE, { value: delegate, enumerable: false });
|
|
51
63
|
return Object.freeze(definition);
|
|
52
64
|
}
|
|
@@ -57,15 +69,31 @@ export function delegateOf(tool) {
|
|
|
57
69
|
const value = tool;
|
|
58
70
|
return value[DELEGATE] ?? (value.source === tool ? undefined : delegateOf(value.source));
|
|
59
71
|
}
|
|
60
|
-
/**
|
|
72
|
+
/**
|
|
73
|
+
* The ReAct agents a manifest delegates to, which the engine runs inside the parent's run,
|
|
74
|
+
* with the capability that declares each. Flow agents are in `flowDelegatesOf`.
|
|
75
|
+
*/
|
|
61
76
|
export function delegatesOf(manifest) {
|
|
62
77
|
const found = [];
|
|
63
78
|
for (const capability of manifest.capabilities)
|
|
64
79
|
for (const tool of capability.tools ?? [])
|
|
65
|
-
if (tool.agent)
|
|
80
|
+
if (tool.agent && !("kind" in tool.agent))
|
|
81
|
+
found.push({ capabilityId: capability.id, manifest: tool.agent });
|
|
82
|
+
return found;
|
|
83
|
+
}
|
|
84
|
+
/** The flow agents a manifest delegates to: each runs in its own linked session. */
|
|
85
|
+
export function flowDelegatesOf(manifest) {
|
|
86
|
+
const found = [];
|
|
87
|
+
for (const capability of manifest.capabilities)
|
|
88
|
+
for (const tool of capability.tools ?? [])
|
|
89
|
+
if (tool.agent && "kind" in tool.agent)
|
|
66
90
|
found.push({ capabilityId: capability.id, manifest: tool.agent });
|
|
67
91
|
return found;
|
|
68
92
|
}
|
|
93
|
+
/** The flow agent `id` a manifest delegates to, or undefined. */
|
|
94
|
+
export function flowDelegateManifest(manifest, id) {
|
|
95
|
+
return flowDelegatesOf(manifest).find((item) => item.manifest.id === id)?.manifest;
|
|
96
|
+
}
|
|
69
97
|
/** The manifest of the delegated agent `id`, or undefined. One level deep by construction. */
|
|
70
98
|
export function delegateManifest(manifest, id) {
|
|
71
99
|
return delegatesOf(manifest).find((item) => item.manifest.id === id)?.manifest;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compile a flow agent's stages to workflow manifest v2.
|
|
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`.
|
|
8
|
+
*/
|
|
9
|
+
import type { JsonObject } from "../../types/shared.js";
|
|
10
|
+
import type { ToolSchemaSource } from "../../types/tool.js";
|
|
11
|
+
import type { SandboxManifest } from "../../types/manifest.js";
|
|
12
|
+
import { type BuiltWorkflow } from "../workflow/types.js";
|
|
13
|
+
import { type FlowStage } from "./spec.js";
|
|
14
|
+
export interface CompileFlowOptions {
|
|
15
|
+
readonly id: string;
|
|
16
|
+
readonly name?: string;
|
|
17
|
+
readonly description?: string;
|
|
18
|
+
readonly metadata?: JsonObject;
|
|
19
|
+
readonly stages: readonly FlowStage[];
|
|
20
|
+
readonly inputSchema?: ToolSchemaSource;
|
|
21
|
+
readonly outputSchema?: ToolSchemaSource;
|
|
22
|
+
readonly sandbox?: SandboxManifest;
|
|
23
|
+
}
|
|
24
|
+
/** Compile a flow agent. Throws `WorkflowBuildError` with diagnostics. */
|
|
25
|
+
export declare function compileAgentFlow(options: CompileFlowOptions): BuiltWorkflow;
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
import { bindingFromAgent } from "../binding.js";
|
|
2
|
+
import { bindOutputContract } from "../output-contract.js";
|
|
3
|
+
import { copyJsonObject } from "../../utils/immutable.js";
|
|
4
|
+
import { canonical } from "../../utils/canonical.js";
|
|
5
|
+
import { diagnostic, fail } from "../workflow/diagnostics.js";
|
|
6
|
+
import { isBuiltWorkflow } from "../workflow/types.js";
|
|
7
|
+
import { bindToolNode, builtAgentOf, isToolDefinition, sandboxSpecsOf, toolManifestNode, } from "../workflow/runnable.js";
|
|
8
|
+
import { isFlowBuilder, isNamedChild } from "./spec.js";
|
|
9
|
+
import { forEachFlowNode, functionKey, isWorkflowManifestV2, leafPart, } from "./paths.js";
|
|
10
|
+
/** Compile a flow agent. Throws `WorkflowBuildError` with diagnostics. */
|
|
11
|
+
export function compileAgentFlow(options) {
|
|
12
|
+
const stages = expand(options.stages);
|
|
13
|
+
if (stages.length === 0)
|
|
14
|
+
fail([
|
|
15
|
+
diagnostic("flow.empty", `Flow agent '${options.id}' has no stages. Add .step(), .switch(), .parallel(), .map() or .loop().`),
|
|
16
|
+
]);
|
|
17
|
+
const build = {
|
|
18
|
+
id: options.id,
|
|
19
|
+
code: new WeakMap(),
|
|
20
|
+
agents: {},
|
|
21
|
+
bindings: {},
|
|
22
|
+
sandboxSpecs: [],
|
|
23
|
+
diagnostics: [],
|
|
24
|
+
};
|
|
25
|
+
const root = { chain: stages.map((stage) => compileStage(stage, build)) };
|
|
26
|
+
const nodes = bindNodes(root, build);
|
|
27
|
+
const sandbox = flowSandbox(options.id, options.sandbox, build);
|
|
28
|
+
if (build.diagnostics.length)
|
|
29
|
+
fail(build.diagnostics);
|
|
30
|
+
const manifest = {
|
|
31
|
+
kind: "workflow",
|
|
32
|
+
workflowSchemaVersion: 2,
|
|
33
|
+
id: options.id,
|
|
34
|
+
...(options.name === undefined ? {} : { name: options.name }),
|
|
35
|
+
...(options.description === undefined ? {} : { description: options.description }),
|
|
36
|
+
...(options.metadata === undefined
|
|
37
|
+
? {}
|
|
38
|
+
: { metadata: copyJsonObject(options.metadata, "metadata") }),
|
|
39
|
+
...(options.inputSchema === undefined ? {} : { inputSchema: jsonSchemaOf(options.inputSchema) }),
|
|
40
|
+
...(options.outputSchema === undefined
|
|
41
|
+
? {}
|
|
42
|
+
: { outputSchema: jsonSchemaOf(options.outputSchema) }),
|
|
43
|
+
...(sandbox === undefined ? {} : { sandbox }),
|
|
44
|
+
root,
|
|
45
|
+
agents: build.agents,
|
|
46
|
+
};
|
|
47
|
+
const binding = Object.freeze({
|
|
48
|
+
manifest,
|
|
49
|
+
nodes: Object.freeze(nodes),
|
|
50
|
+
agents: Object.freeze({ ...build.bindings }),
|
|
51
|
+
});
|
|
52
|
+
const built = {
|
|
53
|
+
id: options.id,
|
|
54
|
+
manifest,
|
|
55
|
+
toJSON: () => manifest,
|
|
56
|
+
...(options.inputSchema === undefined ? {} : { inputSchema: options.inputSchema }),
|
|
57
|
+
...(options.outputSchema === undefined ? {} : { outputSchema: options.outputSchema }),
|
|
58
|
+
};
|
|
59
|
+
Object.defineProperty(built, "getBinding", { value: () => binding, enumerable: false });
|
|
60
|
+
return built;
|
|
61
|
+
}
|
|
62
|
+
/** Inline `.step(flow())` sequences that have no id or input into their parent. */
|
|
63
|
+
function expand(stages) {
|
|
64
|
+
const out = [];
|
|
65
|
+
for (const stage of stages) {
|
|
66
|
+
if (stage.kind === "step" &&
|
|
67
|
+
isFlowBuilder(stage.child) &&
|
|
68
|
+
stage.id === undefined &&
|
|
69
|
+
stage.input === undefined)
|
|
70
|
+
out.push(...expand(stage.child.stages));
|
|
71
|
+
else
|
|
72
|
+
out.push(stage);
|
|
73
|
+
}
|
|
74
|
+
return out;
|
|
75
|
+
}
|
|
76
|
+
function compileStage(stage, build) {
|
|
77
|
+
const options = { id: stage.id, input: stage.input };
|
|
78
|
+
switch (stage.kind) {
|
|
79
|
+
case "step":
|
|
80
|
+
return withOptions(childNode(stage.child, build), options, build);
|
|
81
|
+
case "switch": {
|
|
82
|
+
const { default: fallback, ...cases } = stage.cases;
|
|
83
|
+
const node = {
|
|
84
|
+
switch: {
|
|
85
|
+
on: { fn: true },
|
|
86
|
+
cases: mapValues(cases, (child) => childNode(child, build)),
|
|
87
|
+
...(fallback === undefined ? {} : { default: childNode(fallback, build) }),
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
attach(build, node, { on: stage.on });
|
|
91
|
+
return withOptions(node, options, build);
|
|
92
|
+
}
|
|
93
|
+
case "parallel":
|
|
94
|
+
return withOptions({ parallel: mapValues(stage.branches, (child) => childNode(child, build)) }, options, build);
|
|
95
|
+
case "map":
|
|
96
|
+
return withOptions({ map: { each: childNode(stage.each, build) } }, options, build);
|
|
97
|
+
case "loop":
|
|
98
|
+
return withOptions(compileLoop(stage, build), options, build);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
function compileLoop(stage, build) {
|
|
102
|
+
const label = stage.id ?? "loop";
|
|
103
|
+
if (stage.max !== undefined && (!Number.isInteger(stage.max) || stage.max < 1))
|
|
104
|
+
build.diagnostics.push(diagnostic("loop.invalid-max", `Loop '${label}' max must be a positive integer`));
|
|
105
|
+
if (stage.max === undefined && stage.decide === undefined)
|
|
106
|
+
build.diagnostics.push(diagnostic("loop.max-required", `Loop '${label}' needs { max } or { decide } so it cannot run forever`));
|
|
107
|
+
// The body first, so agents are embedded in the order they run.
|
|
108
|
+
const run = childNode(stage.body, build);
|
|
109
|
+
let verify = { fn: true };
|
|
110
|
+
const code = {};
|
|
111
|
+
if (typeof stage.verify === "function")
|
|
112
|
+
code.verify = stage.verify;
|
|
113
|
+
else {
|
|
114
|
+
const judge = childNode(stage.verify, build);
|
|
115
|
+
if (!("agent" in judge)) {
|
|
116
|
+
build.diagnostics.push(diagnostic("loop.invalid-verify", `Loop '${label}' verify must be a function or an agent, not a tool or flow()`));
|
|
117
|
+
}
|
|
118
|
+
else
|
|
119
|
+
verify = judge;
|
|
120
|
+
}
|
|
121
|
+
if (stage.decide)
|
|
122
|
+
code.decide = stage.decide;
|
|
123
|
+
const node = {
|
|
124
|
+
loop: {
|
|
125
|
+
run,
|
|
126
|
+
verify,
|
|
127
|
+
...(Number.isInteger(stage.max) && stage.max > 0 ? { max: stage.max } : {}),
|
|
128
|
+
...(stage.decide === undefined ? {} : { decide: { fn: true } }),
|
|
129
|
+
},
|
|
130
|
+
};
|
|
131
|
+
attach(build, node, code);
|
|
132
|
+
return node;
|
|
133
|
+
}
|
|
134
|
+
/** A stage child: an agent, tool, nested flow agent, `flow()` or `.withId()` child. */
|
|
135
|
+
function childNode(child, build) {
|
|
136
|
+
if (isNamedChild(child))
|
|
137
|
+
return withOptions(childNode(child.run, build), { id: child.id }, build);
|
|
138
|
+
if (isFlowBuilder(child)) {
|
|
139
|
+
const stages = expand(child.stages);
|
|
140
|
+
if (stages.length === 0) {
|
|
141
|
+
build.diagnostics.push(diagnostic("flow.empty", "A flow() has no stages"));
|
|
142
|
+
return { chain: [] };
|
|
143
|
+
}
|
|
144
|
+
if (stages.length === 1)
|
|
145
|
+
return compileStage(stages[0], build);
|
|
146
|
+
return { chain: stages.map((stage) => compileStage(stage, build)) };
|
|
147
|
+
}
|
|
148
|
+
if (isToolDefinition(child)) {
|
|
149
|
+
const tool = bindToolNode(child);
|
|
150
|
+
const node = toolManifestNode(tool);
|
|
151
|
+
attach(build, node, { tool });
|
|
152
|
+
return node;
|
|
153
|
+
}
|
|
154
|
+
if (child && typeof child === "object") {
|
|
155
|
+
const built = builtOf(child);
|
|
156
|
+
if (built && isBuiltWorkflow(built))
|
|
157
|
+
return nestedFlow(built, build);
|
|
158
|
+
if (built)
|
|
159
|
+
return agentLeaf(built, build);
|
|
160
|
+
}
|
|
161
|
+
build.diagnostics.push(diagnostic("workflow.invalid-runnable", "A flow stage needs an agent, a tool or a flow()"));
|
|
162
|
+
return { chain: [] };
|
|
163
|
+
}
|
|
164
|
+
function builtOf(child) {
|
|
165
|
+
if (isBuiltWorkflow(child))
|
|
166
|
+
return child;
|
|
167
|
+
if ("getBinding" in child && "manifest" in child)
|
|
168
|
+
return child;
|
|
169
|
+
if ("build" in child && typeof child.build === "function")
|
|
170
|
+
return child.build();
|
|
171
|
+
return undefined;
|
|
172
|
+
}
|
|
173
|
+
function agentLeaf(agent, build) {
|
|
174
|
+
const resolved = builtAgentOf(agent);
|
|
175
|
+
embed(build, resolved.id, resolved.manifest);
|
|
176
|
+
addBinding(build, resolved.id, bindingFromAgent(resolved));
|
|
177
|
+
build.sandboxSpecs.push(...sandboxSpecsOf(resolved));
|
|
178
|
+
return { agent: resolved.id };
|
|
179
|
+
}
|
|
180
|
+
function nestedFlow(built, build) {
|
|
181
|
+
if (!isWorkflowManifestV2(built.manifest)) {
|
|
182
|
+
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(…).`));
|
|
183
|
+
return { chain: [] };
|
|
184
|
+
}
|
|
185
|
+
const binding = built.getBinding();
|
|
186
|
+
embed(build, built.id, built.manifest);
|
|
187
|
+
for (const [id, agent] of Object.entries(binding.agents))
|
|
188
|
+
addBinding(build, id, agent);
|
|
189
|
+
if (built.manifest.sandbox !== undefined)
|
|
190
|
+
build.sandboxSpecs.push(built.manifest.sandbox);
|
|
191
|
+
const node = { agent: built.id };
|
|
192
|
+
attach(build, node, { nested: binding });
|
|
193
|
+
return node;
|
|
194
|
+
}
|
|
195
|
+
function embed(build, id, manifest) {
|
|
196
|
+
const existing = build.agents[id];
|
|
197
|
+
if (existing === undefined) {
|
|
198
|
+
build.agents[id] = manifest;
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
if (canonical(existing) !== canonical(manifest))
|
|
202
|
+
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.`));
|
|
203
|
+
}
|
|
204
|
+
function addBinding(build, id, binding) {
|
|
205
|
+
const existing = build.bindings[id];
|
|
206
|
+
if (existing === undefined)
|
|
207
|
+
build.bindings[id] = binding;
|
|
208
|
+
else if (canonical(existing.manifest) !== canonical(binding.manifest))
|
|
209
|
+
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.`));
|
|
210
|
+
}
|
|
211
|
+
/** Put a stage's `id` and `input` on its node, wrapping it in a chain when it has its own. */
|
|
212
|
+
function withOptions(node, options, build) {
|
|
213
|
+
if (options.id === undefined && options.input === undefined)
|
|
214
|
+
return node;
|
|
215
|
+
const clash = (options.id !== undefined && node.id !== undefined) ||
|
|
216
|
+
(options.input !== undefined && node.input !== undefined);
|
|
217
|
+
const target = clash ? { chain: [node] } : node;
|
|
218
|
+
const next = {
|
|
219
|
+
...target,
|
|
220
|
+
...(options.id === undefined ? {} : { id: options.id }),
|
|
221
|
+
...(options.input === undefined ? {} : { input: { fn: true } }),
|
|
222
|
+
};
|
|
223
|
+
const code = { ...(clash ? {} : build.code.get(node)) };
|
|
224
|
+
if (options.input)
|
|
225
|
+
code.input = options.input;
|
|
226
|
+
attach(build, next, code);
|
|
227
|
+
return next;
|
|
228
|
+
}
|
|
229
|
+
function attach(build, node, code) {
|
|
230
|
+
const existing = build.code.get(node) ?? {};
|
|
231
|
+
build.code.set(node, { ...existing, ...code });
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Walk the finished tree: check that leaves and stage ids are unique, and bind each
|
|
235
|
+
* node's code under its stage key.
|
|
236
|
+
*/
|
|
237
|
+
function bindNodes(root, build) {
|
|
238
|
+
const nodes = {};
|
|
239
|
+
const leaves = new Set();
|
|
240
|
+
const ids = new Set();
|
|
241
|
+
forEachFlowNode(root, ({ node, key }) => {
|
|
242
|
+
const part = leafPart(node);
|
|
243
|
+
if (part !== undefined) {
|
|
244
|
+
if (leaves.has(part) || ids.has(part))
|
|
245
|
+
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").`));
|
|
246
|
+
leaves.add(part);
|
|
247
|
+
}
|
|
248
|
+
else if (node.id !== undefined) {
|
|
249
|
+
if (ids.has(node.id) || leaves.has(node.id))
|
|
250
|
+
build.diagnostics.push(diagnostic("flow.duplicate-id", `Two stages of flow agent '${build.id}' are named '${node.id}'. Stage ids must be unique.`));
|
|
251
|
+
ids.add(node.id);
|
|
252
|
+
}
|
|
253
|
+
const code = build.code.get(node);
|
|
254
|
+
if (!code)
|
|
255
|
+
return;
|
|
256
|
+
if (code.input)
|
|
257
|
+
nodes[functionKey(key, "input")] = { kind: "fn", fn: code.input };
|
|
258
|
+
if (code.on)
|
|
259
|
+
nodes[functionKey(key, "on")] = { kind: "fn", fn: code.on };
|
|
260
|
+
if (code.verify)
|
|
261
|
+
nodes[functionKey(key, "verify")] = { kind: "verify", fn: code.verify };
|
|
262
|
+
if (code.decide)
|
|
263
|
+
nodes[functionKey(key, "decide")] = { kind: "fn", fn: code.decide };
|
|
264
|
+
if (code.tool)
|
|
265
|
+
nodes[key] = { kind: "tool", tool: code.tool };
|
|
266
|
+
if (code.nested)
|
|
267
|
+
for (const [inner, impl] of Object.entries(code.nested.nodes))
|
|
268
|
+
nodes[`${key}/${inner}`] = impl;
|
|
269
|
+
});
|
|
270
|
+
return nodes;
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* The flow's sandbox. Agents that declare a sandbox with options must all declare the
|
|
274
|
+
* same one, and match the flow's own when it declares one; `.sandbox()` with no options
|
|
275
|
+
* uses the flow's.
|
|
276
|
+
*/
|
|
277
|
+
function flowSandbox(id, declared, build) {
|
|
278
|
+
const specific = build.sandboxSpecs.filter((spec) => Object.keys(spec).length > 0);
|
|
279
|
+
const kinds = new Set(specific.map((spec) => canonical(spec)));
|
|
280
|
+
if (declared !== undefined && Object.keys(declared).length > 0)
|
|
281
|
+
kinds.add(canonical(declared));
|
|
282
|
+
if (kinds.size > 1) {
|
|
283
|
+
build.diagnostics.push(diagnostic("workflow.sandbox-mismatch", `The agents in flow agent '${id}' declare different sandboxes. Declare the sandbox once on the flow with .sandbox({ … }) and give the agents .sandbox() with no options.`));
|
|
284
|
+
return undefined;
|
|
285
|
+
}
|
|
286
|
+
if (declared !== undefined && Object.keys(declared).length > 0)
|
|
287
|
+
return declared;
|
|
288
|
+
if (specific.length > 0)
|
|
289
|
+
return specific[0];
|
|
290
|
+
if (declared !== undefined || build.sandboxSpecs.length > 0)
|
|
291
|
+
return {};
|
|
292
|
+
return undefined;
|
|
293
|
+
}
|
|
294
|
+
function jsonSchemaOf(source) {
|
|
295
|
+
return bindOutputContract(source).schema.jsonSchema;
|
|
296
|
+
}
|
|
297
|
+
function mapValues(record, fn) {
|
|
298
|
+
const out = {};
|
|
299
|
+
for (const [key, value] of Object.entries(record))
|
|
300
|
+
out[key] = fn(value, key);
|
|
301
|
+
return out;
|
|
302
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { ToolDefinition } from "../../types/tool.js";
|
|
2
|
+
import type { Implementations } from "../implementations.js";
|
|
3
|
+
import type { BuiltWorkflow } from "../workflow/types.js";
|
|
4
|
+
/** The code a flow agent's manifest names, keyed as the manifest's stage keys. */
|
|
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>>>;
|
|
8
|
+
/** Implementations for each embedded agent, by agent id. */
|
|
9
|
+
readonly agents?: Readonly<Record<string, Implementations<any>>>;
|
|
10
|
+
}
|
|
11
|
+
export declare function flowFrom(json: unknown, implementations?: FlowImplementations): BuiltWorkflow;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rebuild a flow agent from its workflow manifest v2 plus the code its stage keys name,
|
|
3
|
+
* the way `Agent.from` rebuilds a ReAct agent from its manifest and implementations.
|
|
4
|
+
*/
|
|
5
|
+
import { HarnessError } from "../../errors.js";
|
|
6
|
+
import { WorkflowManifestSchema } from "../../contracts.js";
|
|
7
|
+
import { agentFrom } from "../from.js";
|
|
8
|
+
import { deepFreeze } from "../../utils/immutable.js";
|
|
9
|
+
import { bindToolNode } from "../workflow/runnable.js";
|
|
10
|
+
import { forEachFlowNode, functionKey, isWorkflowManifestV2 } from "./paths.js";
|
|
11
|
+
export function flowFrom(json, implementations = {}) {
|
|
12
|
+
const manifest = deepFreeze(JSON.parse(JSON.stringify(WorkflowManifestSchema.parse(json))));
|
|
13
|
+
if (!isWorkflowManifestV2(manifest))
|
|
14
|
+
throw new HarnessError("agent.build-failed", "Agent.from reads workflow manifest v2; rebuild a v1 workflow with Chain, Switch, Parallel, Map or Loop");
|
|
15
|
+
const needs = [];
|
|
16
|
+
const agents = {};
|
|
17
|
+
collect(manifest, "", needs, agents);
|
|
18
|
+
const nodes = {};
|
|
19
|
+
const given = implementations.nodes ?? {};
|
|
20
|
+
const missing = [];
|
|
21
|
+
for (const need of needs) {
|
|
22
|
+
const impl = given[need.key];
|
|
23
|
+
if (impl === undefined) {
|
|
24
|
+
missing.push(need.key);
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
if (need.kind === "tool") {
|
|
28
|
+
if (typeof impl === "function")
|
|
29
|
+
throw new HarnessError("agent.build-failed", `'${need.key}' is a tool node: pass a tool, not a function`);
|
|
30
|
+
nodes[need.key] = { kind: "tool", tool: bindToolNode(impl) };
|
|
31
|
+
}
|
|
32
|
+
else {
|
|
33
|
+
if (typeof impl !== "function")
|
|
34
|
+
throw new HarnessError("agent.build-failed", `'${need.key}' is a flow function: pass a function`);
|
|
35
|
+
nodes[need.key] = { kind: need.kind, fn: impl };
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
if (missing.length)
|
|
39
|
+
throw new HarnessError("agent.build-failed", `Missing flow implementation${missing.length === 1 ? "" : "s"}: ${missing.join(", ")}`);
|
|
40
|
+
const unknown = Object.keys(given).filter((key) => !needs.some((need) => need.key === key));
|
|
41
|
+
if (unknown.length)
|
|
42
|
+
throw new HarnessError("agent.build-failed", `Flow agent '${manifest.id}' has no stage key${unknown.length === 1 ? "" : "s"} ${unknown.join(", ")}`);
|
|
43
|
+
const bindings = {};
|
|
44
|
+
for (const [id, agent] of Object.entries(agents))
|
|
45
|
+
bindings[id] = agentFrom(agent, implementations.agents?.[id] ?? {}).getBinding();
|
|
46
|
+
const binding = Object.freeze({
|
|
47
|
+
manifest,
|
|
48
|
+
nodes: Object.freeze(nodes),
|
|
49
|
+
agents: Object.freeze(bindings),
|
|
50
|
+
});
|
|
51
|
+
const built = { id: manifest.id, manifest, toJSON: () => manifest };
|
|
52
|
+
Object.defineProperty(built, "getBinding", { value: () => binding, enumerable: false });
|
|
53
|
+
return built;
|
|
54
|
+
}
|
|
55
|
+
/** Every stage key the manifest binds code under, and every embedded ReAct agent. */
|
|
56
|
+
function collect(flow, prefix, needs, agents) {
|
|
57
|
+
forEachFlowNode(flow.root, ({ node, key }) => {
|
|
58
|
+
if (node.input)
|
|
59
|
+
needs.push({ key: functionKey(key, "input"), kind: "fn" });
|
|
60
|
+
if ("tool" in node)
|
|
61
|
+
needs.push({ key, kind: "tool" });
|
|
62
|
+
if ("switch" in node)
|
|
63
|
+
needs.push({ key: functionKey(key, "on"), kind: "fn" });
|
|
64
|
+
if ("loop" in node) {
|
|
65
|
+
if ("fn" in node.loop.verify)
|
|
66
|
+
needs.push({ key: functionKey(key, "verify"), kind: "verify" });
|
|
67
|
+
if (node.loop.decide)
|
|
68
|
+
needs.push({ key: functionKey(key, "decide"), kind: "fn" });
|
|
69
|
+
}
|
|
70
|
+
if ("agent" in node) {
|
|
71
|
+
const target = flow.agents[node.agent];
|
|
72
|
+
if (isWorkflowManifestV2(target))
|
|
73
|
+
collect(target, key, needs, agents);
|
|
74
|
+
else
|
|
75
|
+
agents[node.agent] = target;
|
|
76
|
+
}
|
|
77
|
+
}, { prefix });
|
|
78
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Flow } from "./types.js";
|
|
2
|
+
export { FlowBuilder, isFlowBuilder } from "./spec.js";
|
|
3
|
+
export { compileAgentFlow } from "./compile.js";
|
|
4
|
+
export type { FlowImplementations } from "./from.js";
|
|
5
|
+
export { ROOT_POSITION, childPosition, embeddedAgent, forEachFlowNode, functionKey, indexSuffix, isLeafNode, isWorkflowManifestV2, leafPart, leafPath, stageKey, stripIndices, type FlowFunctionRole, type FlowNodeVisit, } from "./paths.js";
|
|
6
|
+
export type * from "./types.js";
|
|
7
|
+
/**
|
|
8
|
+
* A sequence with no id, for a switch case, parallel branch, map item or loop body
|
|
9
|
+
* that is more than one step: `flow().step(planner).map(implementer)`.
|
|
10
|
+
*/
|
|
11
|
+
export declare function flow<In = any>(): Flow<In>;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { FlowBuilder } from "./spec.js";
|
|
2
|
+
export { FlowBuilder, isFlowBuilder } from "./spec.js";
|
|
3
|
+
export { compileAgentFlow } from "./compile.js";
|
|
4
|
+
export { ROOT_POSITION, childPosition, embeddedAgent, forEachFlowNode, functionKey, indexSuffix, isLeafNode, isWorkflowManifestV2, leafPart, leafPath, stageKey, stripIndices, } from "./paths.js";
|
|
5
|
+
/**
|
|
6
|
+
* A sequence with no id, for a switch case, parallel branch, map item or loop body
|
|
7
|
+
* that is more than one step: `flow().step(planner).map(implementer)`.
|
|
8
|
+
*/
|
|
9
|
+
export function flow() {
|
|
10
|
+
return new FlowBuilder();
|
|
11
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Paths and keys for workflow manifest v2 (Flow Agents). Shared by the compiler, the
|
|
3
|
+
* flow engine, the executor and Studio, so every package names a node the same way.
|
|
4
|
+
*
|
|
5
|
+
* - A **leaf path** names an agent or tool session: the leaf's id (its `id`, or the
|
|
6
|
+
* agent's id or tool name), with `[i]` for each Map item it runs in, under the ids of
|
|
7
|
+
* any nested flow agents. Control stages and `flow()` add nothing, so wrapping a step
|
|
8
|
+
* in a Loop or moving it out of a Switch keeps its session.
|
|
9
|
+
* - A **stage key** names a node for binding functions: a leaf's id, a control stage's
|
|
10
|
+
* `id`, or else its position from the flow root (`@1.default.1`). Function keys add
|
|
11
|
+
* `:input`, `:on`, `:verify` or `:decide`.
|
|
12
|
+
*/
|
|
13
|
+
import type { WorkflowAgentNodeV2, WorkflowManifestV2, WorkflowNodeV2, WorkflowToolNodeV2 } from "../../types/workflow.js";
|
|
14
|
+
import type { AgentManifest } from "../../types/manifest.js";
|
|
15
|
+
/** Position of a flow's root node. */
|
|
16
|
+
export declare const ROOT_POSITION = "@";
|
|
17
|
+
export type FlowFunctionRole = "input" | "on" | "verify" | "decide";
|
|
18
|
+
export declare function isWorkflowManifestV2(manifest: {
|
|
19
|
+
readonly kind?: unknown;
|
|
20
|
+
readonly workflowSchemaVersion?: unknown;
|
|
21
|
+
} | undefined): manifest is WorkflowManifestV2;
|
|
22
|
+
export declare function isLeafNode(node: WorkflowNodeV2): node is WorkflowAgentNodeV2 | WorkflowToolNodeV2;
|
|
23
|
+
/** A leaf's path part: its `id`, else the agent id or tool name. Undefined for control nodes. */
|
|
24
|
+
export declare function leafPart(node: WorkflowNodeV2): string | undefined;
|
|
25
|
+
/** The position of a child: `@` + index for the root's children, else `parent.segment`. */
|
|
26
|
+
export declare function childPosition(parent: string, segment: string | number): string;
|
|
27
|
+
/**
|
|
28
|
+
* A node's stage key: a leaf's path part, a control node's `id`, or its position.
|
|
29
|
+
* `prefix` is the key of the nested flow agent the node runs in, if any.
|
|
30
|
+
*/
|
|
31
|
+
export declare function stageKey(node: WorkflowNodeV2, position: string, prefix?: string): string;
|
|
32
|
+
export declare function functionKey(key: string, role: FlowFunctionRole): string;
|
|
33
|
+
/** `[0][2]` for Map item indices, outermost first. */
|
|
34
|
+
export declare function indexSuffix(indices: readonly number[]): string;
|
|
35
|
+
/** A leaf's session path: `prefix/part[i]…`. */
|
|
36
|
+
export declare function leafPath(prefix: string, part: string, indices?: readonly number[]): string;
|
|
37
|
+
/** Drop Map indices from a path: the key a leaf's code is bound under. */
|
|
38
|
+
export declare function stripIndices(path: string): string;
|
|
39
|
+
export interface FlowNodeVisit {
|
|
40
|
+
readonly node: WorkflowNodeV2;
|
|
41
|
+
readonly position: string;
|
|
42
|
+
/** Stage key, including the nested flow agent prefix. */
|
|
43
|
+
readonly key: string;
|
|
44
|
+
/** How the node sits in its parent: `step`, `case`, `default`, `branch`, `each`, `run` or `verify`. */
|
|
45
|
+
readonly role: "root" | "step" | "case" | "default" | "branch" | "each" | "run" | "verify";
|
|
46
|
+
/** True when an enclosing Map runs this node once per item. */
|
|
47
|
+
readonly inMap: boolean;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Visit every node of one flow, parents first. Nested flow agents are not entered:
|
|
51
|
+
* their nodes live in their own manifest under `agents`.
|
|
52
|
+
*/
|
|
53
|
+
export declare function forEachFlowNode(root: WorkflowNodeV2, visit: (entry: FlowNodeVisit) => void, options?: {
|
|
54
|
+
readonly prefix?: string;
|
|
55
|
+
}): void;
|
|
56
|
+
/**
|
|
57
|
+
* The embedded agent an agent node names, looked up through the nested flow agents
|
|
58
|
+
* (`flow`, outermost first) the node runs in.
|
|
59
|
+
*/
|
|
60
|
+
export declare function embeddedAgent(manifest: WorkflowManifestV2, flow: readonly string[], agentId: string): AgentManifest | WorkflowManifestV2 | undefined;
|