@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.
Files changed (41) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/dist/compatibility.d.ts +13 -2
  3. package/dist/compatibility.js +19 -1
  4. package/dist/contracts.d.ts +247 -0
  5. package/dist/contracts.js +353 -4
  6. package/dist/define.d.ts +10 -2
  7. package/dist/define.js +5 -1
  8. package/dist/definition/assemble.js +7 -0
  9. package/dist/definition/builder.d.ts +122 -16
  10. package/dist/definition/builder.js +354 -53
  11. package/dist/definition/capability.d.ts +55 -0
  12. package/dist/definition/capability.js +104 -0
  13. package/dist/definition/delegate.d.ts +25 -4
  14. package/dist/definition/delegate.js +34 -6
  15. package/dist/definition/flow/compile.d.ts +25 -0
  16. package/dist/definition/flow/compile.js +302 -0
  17. package/dist/definition/flow/from.d.ts +11 -0
  18. package/dist/definition/flow/from.js +78 -0
  19. package/dist/definition/flow/index.d.ts +11 -0
  20. package/dist/definition/flow/index.js +11 -0
  21. package/dist/definition/flow/paths.d.ts +60 -0
  22. package/dist/definition/flow/paths.js +90 -0
  23. package/dist/definition/flow/spec.d.ts +66 -0
  24. package/dist/definition/flow/spec.js +130 -0
  25. package/dist/definition/flow/types.d.ts +159 -0
  26. package/dist/definition/flow/types.js +1 -0
  27. package/dist/definition/from.js +5 -1
  28. package/dist/definition/helpers.d.ts +1 -16
  29. package/dist/definition/helpers.js +1 -30
  30. package/dist/definition/mcp.d.ts +37 -0
  31. package/dist/definition/mcp.js +81 -0
  32. package/dist/definition/sandbox.d.ts +29 -0
  33. package/dist/definition/sandbox.js +93 -0
  34. package/dist/definition/workflow/loop.js +2 -2
  35. package/dist/definition/workflow/runnable.d.ts +13 -1
  36. package/dist/definition/workflow/runnable.js +11 -7
  37. package/dist/types/manifest.d.ts +4 -2
  38. package/dist/types/workflow.d.ts +72 -3
  39. package/dist/utils/deprecate.d.ts +3 -0
  40. package/dist/utils/deprecate.js +25 -0
  41. package/package.json +2 -2
@@ -0,0 +1,90 @@
1
+ /** Position of a flow's root node. */
2
+ export const ROOT_POSITION = "@";
3
+ export function isWorkflowManifestV2(manifest) {
4
+ return manifest?.kind === "workflow" && manifest.workflowSchemaVersion === 2;
5
+ }
6
+ export function isLeafNode(node) {
7
+ return "agent" in node || "tool" in node;
8
+ }
9
+ /** A leaf's path part: its `id`, else the agent id or tool name. Undefined for control nodes. */
10
+ export function leafPart(node) {
11
+ if ("agent" in node)
12
+ return node.id ?? node.agent;
13
+ if ("tool" in node)
14
+ return node.id ?? node.tool.name;
15
+ return undefined;
16
+ }
17
+ /** The position of a child: `@` + index for the root's children, else `parent.segment`. */
18
+ export function childPosition(parent, segment) {
19
+ return parent === ROOT_POSITION ? `${ROOT_POSITION}${segment}` : `${parent}.${segment}`;
20
+ }
21
+ /**
22
+ * A node's stage key: a leaf's path part, a control node's `id`, or its position.
23
+ * `prefix` is the key of the nested flow agent the node runs in, if any.
24
+ */
25
+ export function stageKey(node, position, prefix = "") {
26
+ const own = leafPart(node) ?? node.id ?? position;
27
+ return prefix ? `${prefix}/${own}` : own;
28
+ }
29
+ export function functionKey(key, role) {
30
+ return `${key}:${role}`;
31
+ }
32
+ /** `[0][2]` for Map item indices, outermost first. */
33
+ export function indexSuffix(indices) {
34
+ return indices.map((index) => `[${index}]`).join("");
35
+ }
36
+ /** A leaf's session path: `prefix/part[i]…`. */
37
+ export function leafPath(prefix, part, indices = []) {
38
+ const own = `${part}${indexSuffix(indices)}`;
39
+ return prefix ? `${prefix}/${own}` : own;
40
+ }
41
+ /** Drop Map indices from a path: the key a leaf's code is bound under. */
42
+ export function stripIndices(path) {
43
+ return path.replace(/\[\d+]/g, "");
44
+ }
45
+ /**
46
+ * Visit every node of one flow, parents first. Nested flow agents are not entered:
47
+ * their nodes live in their own manifest under `agents`.
48
+ */
49
+ export function forEachFlowNode(root, visit, options = {}) {
50
+ const prefix = options.prefix ?? "";
51
+ const walk = (node, position, role, inMap) => {
52
+ visit({ node, position, key: stageKey(node, position, prefix), role, inMap });
53
+ if ("chain" in node)
54
+ node.chain.forEach((child, index) => walk(child, childPosition(position, index), "step", inMap));
55
+ else if ("switch" in node) {
56
+ for (const [name, child] of Object.entries(node.switch.cases))
57
+ walk(child, childPosition(position, name), "case", inMap);
58
+ if (node.switch.default)
59
+ walk(node.switch.default, childPosition(position, "default"), "default", inMap);
60
+ }
61
+ else if ("parallel" in node) {
62
+ for (const [name, child] of Object.entries(node.parallel))
63
+ walk(child, childPosition(position, name), "branch", inMap);
64
+ }
65
+ else if ("map" in node)
66
+ walk(node.map.each, childPosition(position, "each"), "each", true);
67
+ else if ("loop" in node) {
68
+ walk(node.loop.run, childPosition(position, "run"), "run", inMap);
69
+ if ("agent" in node.loop.verify)
70
+ walk(node.loop.verify, childPosition(position, "verify"), "verify", inMap);
71
+ }
72
+ };
73
+ walk(root, ROOT_POSITION, "root", false);
74
+ }
75
+ /**
76
+ * The embedded agent an agent node names, looked up through the nested flow agents
77
+ * (`flow`, outermost first) the node runs in.
78
+ */
79
+ export function embeddedAgent(manifest, flow, agentId) {
80
+ let scope = manifest;
81
+ for (const id of flow) {
82
+ const next = isWorkflowManifestV2(scope)
83
+ ? scope.agents[id]
84
+ : undefined;
85
+ if (!next || !isWorkflowManifestV2(next))
86
+ return undefined;
87
+ scope = next;
88
+ }
89
+ return isWorkflowManifestV2(scope) ? scope.agents[agentId] : undefined;
90
+ }
@@ -0,0 +1,66 @@
1
+ /** A function in a flow stage: `input`, `on`, `verify` or `decide`. */
2
+ export type FlowFn = (args: any) => unknown;
3
+ /** A child given a new step id with `.withId()`. */
4
+ export interface NamedChild {
5
+ readonly [NAMED]: true;
6
+ readonly run: unknown;
7
+ readonly id: string;
8
+ }
9
+ export type FlowStage = {
10
+ readonly kind: "step";
11
+ readonly child: unknown;
12
+ readonly id?: string;
13
+ readonly input?: FlowFn;
14
+ } | {
15
+ readonly kind: "switch";
16
+ readonly cases: Readonly<Record<string, unknown>>;
17
+ readonly on: FlowFn;
18
+ readonly id?: string;
19
+ readonly input?: FlowFn;
20
+ } | {
21
+ readonly kind: "parallel";
22
+ readonly branches: Readonly<Record<string, unknown>>;
23
+ readonly id?: string;
24
+ readonly input?: FlowFn;
25
+ } | {
26
+ readonly kind: "map";
27
+ readonly each: unknown;
28
+ readonly id?: string;
29
+ readonly input?: FlowFn;
30
+ } | {
31
+ readonly kind: "loop";
32
+ readonly body: unknown;
33
+ readonly verify: unknown;
34
+ readonly max?: number;
35
+ readonly decide?: FlowFn;
36
+ readonly id?: string;
37
+ readonly input?: FlowFn;
38
+ };
39
+ export declare const NAMED: unique symbol;
40
+ export declare function named(run: unknown, id: string): NamedChild;
41
+ export declare function isNamedChild(value: unknown): value is NamedChild;
42
+ type Options = Readonly<Record<string, unknown>> | undefined;
43
+ export declare function stepStage(child: unknown, options?: Options): FlowStage;
44
+ export declare function switchStage(cases: unknown, options?: Options): FlowStage;
45
+ export declare function parallelStage(branches: unknown, options?: Options): FlowStage;
46
+ export declare function mapStage(each: unknown, options?: Options): FlowStage;
47
+ export declare function loopStage(body: unknown, options?: Options): FlowStage;
48
+ /**
49
+ * A sequence of stages with no id, for a switch case, parallel branch, map item or
50
+ * loop body that is more than one step. It has the same stage methods as a flow agent.
51
+ */
52
+ export declare class FlowBuilder {
53
+ #private;
54
+ constructor(stages?: readonly FlowStage[]);
55
+ /** @internal The stages, in order. */
56
+ get stages(): readonly FlowStage[];
57
+ step(child: unknown, options?: Options): FlowBuilder;
58
+ switch(cases: unknown, options?: Options): FlowBuilder;
59
+ parallel(branches: unknown, options?: Options): FlowBuilder;
60
+ map(each: unknown, options?: Options): FlowBuilder;
61
+ loop(body: unknown, options?: Options): FlowBuilder;
62
+ /** Give this sequence a step id where there is no options object. */
63
+ withId(id: string): NamedChild;
64
+ }
65
+ export declare function isFlowBuilder(value: unknown): value is FlowBuilder;
66
+ export {};
@@ -0,0 +1,130 @@
1
+ import { HarnessError } from "../../errors.js";
2
+ export const NAMED = Symbol.for("nylorun.flow.named");
3
+ const FLOW = Symbol.for("nylorun.flow");
4
+ export function named(run, id) {
5
+ if (typeof id !== "string" || id.length === 0)
6
+ throw new HarnessError("configuration.invalid", ".withId() requires a non-empty id");
7
+ return Object.freeze({ [NAMED]: true, run, id });
8
+ }
9
+ export function isNamedChild(value) {
10
+ return !!value && typeof value === "object" && value[NAMED] === true;
11
+ }
12
+ const HINTS = {
13
+ over: "A Map runs over its input. Use { input: ({ input }) => list } to pick the list.",
14
+ from: "Use { input } to compute a step's input.",
15
+ as: "Use { id } to name a step.",
16
+ name: "Use { id } to name a stage.",
17
+ default: "Put default among the cases: .switch({ ...cases, default }, { on }).",
18
+ };
19
+ function checkOptions(method, options, allowed) {
20
+ if (options === undefined)
21
+ return;
22
+ if (!options || typeof options !== "object" || Array.isArray(options))
23
+ throw new HarnessError("configuration.invalid", `${method} options must be an object`);
24
+ for (const key of Object.keys(options)) {
25
+ if (allowed.includes(key))
26
+ continue;
27
+ const hint = HINTS[key] ? ` ${HINTS[key]}` : "";
28
+ throw new HarnessError("configuration.invalid", `Unknown option '${key}' for ${method}. Allowed: ${allowed.join(", ")}.${hint}`);
29
+ }
30
+ if (options.id !== undefined && (typeof options.id !== "string" || options.id.length === 0))
31
+ throw new HarnessError("configuration.invalid", `${method} id must be a non-empty string`);
32
+ if (options.input !== undefined && typeof options.input !== "function")
33
+ throw new HarnessError("configuration.invalid", `${method} input must be a function`);
34
+ }
35
+ function requireChild(method, child) {
36
+ if (child === undefined || child === null)
37
+ throw new HarnessError("configuration.invalid", `${method} requires an agent, tool or flow()`);
38
+ }
39
+ function requireRecord(method, label, value) {
40
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).length === 0)
41
+ throw new HarnessError("configuration.invalid", `${method} requires a non-empty object of ${label}`);
42
+ return value;
43
+ }
44
+ function common(options) {
45
+ return {
46
+ ...(options?.id === undefined ? {} : { id: options.id }),
47
+ ...(options?.input === undefined ? {} : { input: options.input }),
48
+ };
49
+ }
50
+ export function stepStage(child, options) {
51
+ checkOptions(".step()", options, ["id", "input"]);
52
+ requireChild(".step()", child);
53
+ return Object.freeze({ kind: "step", child, ...common(options) });
54
+ }
55
+ export function switchStage(cases, options) {
56
+ checkOptions(".switch()", options, ["on", "id", "input"]);
57
+ const record = requireRecord(".switch()", "cases", cases);
58
+ if (typeof options?.on !== "function")
59
+ throw new HarnessError("configuration.invalid", ".switch() requires { on: ({ input }) => caseName }");
60
+ return Object.freeze({
61
+ kind: "switch",
62
+ cases: Object.freeze({ ...record }),
63
+ on: options.on,
64
+ ...common(options),
65
+ });
66
+ }
67
+ export function parallelStage(branches, options) {
68
+ checkOptions(".parallel()", options, ["id", "input"]);
69
+ const record = requireRecord(".parallel()", "branches", branches);
70
+ return Object.freeze({ kind: "parallel", branches: Object.freeze({ ...record }), ...common(options) });
71
+ }
72
+ export function mapStage(each, options) {
73
+ checkOptions(".map()", options, ["id", "input"]);
74
+ requireChild(".map()", each);
75
+ return Object.freeze({ kind: "map", each, ...common(options) });
76
+ }
77
+ export function loopStage(body, options) {
78
+ checkOptions(".loop()", options, ["verify", "max", "decide", "id", "input"]);
79
+ requireChild(".loop()", body);
80
+ if (options?.verify === undefined)
81
+ throw new HarnessError("configuration.invalid", ".loop() requires { verify }: a function or a verifier agent");
82
+ if (options.decide !== undefined && typeof options.decide !== "function")
83
+ throw new HarnessError("configuration.invalid", ".loop() decide must be a function");
84
+ return Object.freeze({
85
+ kind: "loop",
86
+ body,
87
+ verify: options.verify,
88
+ ...(options.max === undefined ? {} : { max: options.max }),
89
+ ...(options.decide === undefined ? {} : { decide: options.decide }),
90
+ ...common(options),
91
+ });
92
+ }
93
+ // ── flow(): a sequence with no id ────────────────────────────────────────────
94
+ /**
95
+ * A sequence of stages with no id, for a switch case, parallel branch, map item or
96
+ * loop body that is more than one step. It has the same stage methods as a flow agent.
97
+ */
98
+ export class FlowBuilder {
99
+ #stages;
100
+ constructor(stages = []) {
101
+ this.#stages = Object.freeze([...stages]);
102
+ Object.defineProperty(this, FLOW, { value: true });
103
+ }
104
+ /** @internal The stages, in order. */
105
+ get stages() {
106
+ return this.#stages;
107
+ }
108
+ step(child, options) {
109
+ return new FlowBuilder([...this.#stages, stepStage(child, options)]);
110
+ }
111
+ switch(cases, options) {
112
+ return new FlowBuilder([...this.#stages, switchStage(cases, options)]);
113
+ }
114
+ parallel(branches, options) {
115
+ return new FlowBuilder([...this.#stages, parallelStage(branches, options)]);
116
+ }
117
+ map(each, options) {
118
+ return new FlowBuilder([...this.#stages, mapStage(each, options)]);
119
+ }
120
+ loop(body, options) {
121
+ return new FlowBuilder([...this.#stages, loopStage(body, options)]);
122
+ }
123
+ /** Give this sequence a step id where there is no options object. */
124
+ withId(id) {
125
+ return named(this, id);
126
+ }
127
+ }
128
+ export function isFlowBuilder(value) {
129
+ return !!value && typeof value === "object" && value[FLOW] === true;
130
+ }
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Types for flow agents: each stage's output types the next stage's `input`, and
3
+ * `results` gains an entry for every step whose id is known at compile time.
4
+ */
5
+ import type { SandboxManifest, AgentManifest } from "../../types/manifest.js";
6
+ import type { SchemaOutput, ToolSchemaSource } from "../../types/tool.js";
7
+ import type { Verdict } from "../../types/workflow.js";
8
+ import type { BuiltWorkflow } from "../workflow/types.js";
9
+ /** What every flow function receives. */
10
+ export type StageArgs<Cur = any, Results = Readonly<Record<string, any>>, In = any> = {
11
+ readonly input: Cur;
12
+ readonly results: Results;
13
+ /** The input of the nearest Agent. */
14
+ readonly flowInput: In;
15
+ };
16
+ /** What a function inside a nested `flow()` receives: the same as a top-level stage. */
17
+ export type NestedStageArgs<Cur = any, Results = Readonly<Record<string, any>>> = StageArgs<Cur, Results, any>;
18
+ /** A child renamed with `.withId()`. */
19
+ export interface Named<R = unknown> {
20
+ readonly run: R;
21
+ readonly id: string;
22
+ readonly __output?: FlowOut<R>;
23
+ }
24
+ /** The output type a flow child produces: `any` when nothing declares it. */
25
+ export type FlowOut<C> = C extends {
26
+ readonly __output?: infer O;
27
+ } ? unknown extends O ? any : O : C extends BuiltWorkflow<any, infer O> ? O : any;
28
+ /** A child's step id, when it is a string literal. */
29
+ export type IdOf<C> = C extends {
30
+ readonly __id?: infer I;
31
+ } ? I extends string ? I : string : string;
32
+ export type AddResult<Results, K extends string, V> = string extends K ? Results : Results & {
33
+ readonly [P in K]: V;
34
+ };
35
+ /** Case names `on` may return: any string when there is a `default` case. */
36
+ export type CaseKey<Cases> = "default" extends keyof Cases ? string : Extract<keyof Cases, string>;
37
+ export type CasesOut<Cases> = {
38
+ [K in keyof Cases]: FlowOut<Cases[K]>;
39
+ }[keyof Cases];
40
+ export type BranchesOut<Branches> = {
41
+ readonly [K in keyof Branches]: FlowOut<Branches[K]>;
42
+ };
43
+ export type LoopVerifyFn<Cur, Out> = (args: {
44
+ readonly input: Cur;
45
+ readonly output: Out;
46
+ readonly iteration: number;
47
+ readonly results: Readonly<Record<string, any>>;
48
+ readonly flowInput: any;
49
+ }) => Verdict | Promise<Verdict>;
50
+ export type LoopDecideArgs<Cur, Out> = {
51
+ readonly input: Cur;
52
+ readonly output: Out;
53
+ readonly verdict: Verdict;
54
+ readonly iteration: number;
55
+ readonly history: readonly {
56
+ readonly iteration: number;
57
+ readonly output: Out;
58
+ readonly verdict: Verdict;
59
+ }[];
60
+ /** The body agent's manifest, when the body is an agent: pass a variant back in `agent`. */
61
+ readonly agent?: AgentManifest;
62
+ readonly results: Readonly<Record<string, any>>;
63
+ readonly flowInput: any;
64
+ };
65
+ export type LoopChoice<Out> = {
66
+ readonly output: Out;
67
+ } | {
68
+ readonly retry: unknown;
69
+ readonly agent?: AgentManifest;
70
+ };
71
+ type Final<Cur, Out> = [Out] extends [never] ? Cur : Out;
72
+ /**
73
+ * A flow agent: an `Agent` whose body is a flow. Returned by `.input()` and by every
74
+ * stage method, so ReAct methods such as `.instructions()` are not available on it.
75
+ */
76
+ export interface FlowAgentBuilder<Info = unknown, In = any, Cur = any, Results = {}, Out = never, Id extends string = string> extends BuiltWorkflow<In, Final<Cur, Out>> {
77
+ readonly id: Id;
78
+ /** Phantom carrier for the agent's id. */
79
+ readonly __id?: Id;
80
+ /** Phantom carrier for the context type hooks see. */
81
+ readonly __info?: Info;
82
+ build(): BuiltWorkflow<In, Final<Cur, Out>>;
83
+ /** Give this flow agent a new step id where there is no options object. */
84
+ withId(id: string): Named<this>;
85
+ output<S extends ToolSchemaSource>(schema: S): FlowAgentBuilder<Info, In, Cur, Results, SchemaOutput<S>, Id>;
86
+ /** The one sandbox every agent in the flow shares. */
87
+ sandbox(spec?: SandboxManifest): FlowAgentBuilder<Info, In, Cur, Results, Out, Id>;
88
+ step<C, const StepId extends string = IdOf<C>>(child: C, options?: {
89
+ readonly id?: StepId;
90
+ readonly input?: (args: StageArgs<Cur, Results, In>) => unknown;
91
+ }): FlowAgentBuilder<Info, In, FlowOut<C>, AddResult<Results, StepId, FlowOut<C>>, Out, Id>;
92
+ switch<const Cases extends Readonly<Record<string, unknown>>, T, const StageId extends string = string>(cases: Cases, options: {
93
+ readonly input: (args: StageArgs<Cur, Results, In>) => T;
94
+ readonly on: (args: StageArgs<T, Results, In>) => CaseKey<Cases>;
95
+ readonly id?: StageId;
96
+ }): FlowAgentBuilder<Info, In, CasesOut<Cases>, AddResult<Results, StageId, CasesOut<Cases>>, Out, Id>;
97
+ switch<const Cases extends Readonly<Record<string, unknown>>, const StageId extends string = string>(cases: Cases, options: {
98
+ readonly on: (args: StageArgs<Cur, Results, In>) => CaseKey<Cases>;
99
+ readonly id?: StageId;
100
+ }): FlowAgentBuilder<Info, In, CasesOut<Cases>, AddResult<Results, StageId, CasesOut<Cases>>, Out, Id>;
101
+ parallel<const Branches extends Readonly<Record<string, unknown>>, const StageId extends string = string>(branches: Branches, options?: {
102
+ readonly id?: StageId;
103
+ readonly input?: (args: StageArgs<Cur, Results, In>) => unknown;
104
+ }): FlowAgentBuilder<Info, In, BranchesOut<Branches>, AddResult<Results, StageId, BranchesOut<Branches>>, Out, Id>;
105
+ map<E, const StageId extends string = string>(each: E, ...options: Cur extends readonly unknown[] ? [options?: {
106
+ readonly id?: StageId;
107
+ readonly input?: (args: StageArgs<Cur, Results, In>) => readonly unknown[];
108
+ }] : [options: {
109
+ readonly id?: StageId;
110
+ readonly input: (args: StageArgs<Cur, Results, In>) => readonly unknown[];
111
+ }]): FlowAgentBuilder<Info, In, FlowOut<E>[], AddResult<Results, StageId, FlowOut<E>[]>, Out, Id>;
112
+ loop<B, const StageId extends string = string>(body: B, options: {
113
+ readonly verify: LoopVerifyFn<Cur, FlowOut<B>> | object;
114
+ readonly max?: number;
115
+ readonly decide?: (args: LoopDecideArgs<Cur, FlowOut<B>>) => LoopChoice<FlowOut<B>>;
116
+ readonly id?: StageId;
117
+ readonly input?: (args: StageArgs<Cur, Results, In>) => unknown;
118
+ }): FlowAgentBuilder<Info, In, FlowOut<B>, AddResult<Results, StageId, FlowOut<B>>, Out, Id>;
119
+ }
120
+ /**
121
+ * A `flow()`: a sequence with no id, for a switch case, parallel branch, map item or
122
+ * loop body that is more than one step.
123
+ */
124
+ export interface Flow<Cur = any, Results = {}> {
125
+ readonly __output?: Cur;
126
+ withId(id: string): Named<this>;
127
+ step<C, const StepId extends string = IdOf<C>>(child: C, options?: {
128
+ readonly id?: StepId;
129
+ readonly input?: (args: NestedStageArgs<Cur, Results>) => unknown;
130
+ }): Flow<FlowOut<C>, AddResult<Results, StepId, FlowOut<C>>>;
131
+ switch<const Cases extends Readonly<Record<string, unknown>>, T, const StageId extends string = string>(cases: Cases, options: {
132
+ readonly input: (args: NestedStageArgs<Cur, Results>) => T;
133
+ readonly on: (args: NestedStageArgs<T, Results>) => CaseKey<Cases>;
134
+ readonly id?: StageId;
135
+ }): Flow<CasesOut<Cases>, AddResult<Results, StageId, CasesOut<Cases>>>;
136
+ switch<const Cases extends Readonly<Record<string, unknown>>, const StageId extends string = string>(cases: Cases, options: {
137
+ readonly on: (args: NestedStageArgs<Cur, Results>) => CaseKey<Cases>;
138
+ readonly id?: StageId;
139
+ }): Flow<CasesOut<Cases>, AddResult<Results, StageId, CasesOut<Cases>>>;
140
+ parallel<const Branches extends Readonly<Record<string, unknown>>, const StageId extends string = string>(branches: Branches, options?: {
141
+ readonly id?: StageId;
142
+ readonly input?: (args: NestedStageArgs<Cur, Results>) => unknown;
143
+ }): Flow<BranchesOut<Branches>, AddResult<Results, StageId, BranchesOut<Branches>>>;
144
+ map<E, const StageId extends string = string>(each: E, ...options: Cur extends readonly unknown[] ? [options?: {
145
+ readonly id?: StageId;
146
+ readonly input?: (args: NestedStageArgs<Cur, Results>) => readonly unknown[];
147
+ }] : [options: {
148
+ readonly id?: StageId;
149
+ readonly input: (args: NestedStageArgs<Cur, Results>) => readonly unknown[];
150
+ }]): Flow<FlowOut<E>[], AddResult<Results, StageId, FlowOut<E>[]>>;
151
+ loop<B, const StageId extends string = string>(body: B, options: {
152
+ readonly verify: LoopVerifyFn<Cur, FlowOut<B>> | object;
153
+ readonly max?: number;
154
+ readonly decide?: (args: LoopDecideArgs<Cur, FlowOut<B>>) => LoopChoice<FlowOut<B>>;
155
+ readonly id?: StageId;
156
+ readonly input?: (args: NestedStageArgs<Cur, Results>) => unknown;
157
+ }): Flow<FlowOut<B>, AddResult<Results, StageId, FlowOut<B>>>;
158
+ }
159
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -326,6 +326,10 @@ function normalizeTool(tool) {
326
326
  : { outputSchema: tool.outputSchema }),
327
327
  ...(tool.agent === undefined
328
328
  ? {}
329
- : { agent: normalizeManifest(tool.agent) }),
329
+ : {
330
+ agent: "kind" in tool.agent
331
+ ? deepFreeze(JSON.parse(JSON.stringify(tool.agent)))
332
+ : normalizeManifest(tool.agent),
333
+ }),
330
334
  });
331
335
  }
@@ -6,20 +6,5 @@ export declare const tool: <InputSchema extends ToolInputSchema, Info = unknown,
6
6
  export declare const model: <T extends ModelAdapter>(value: T) => T;
7
7
  /** @deprecated Prefer `before` / `after` hooks. Kept through 1.0. */
8
8
  export declare const middleware: <T extends StepMiddleware>(value: T) => T;
9
- /** Compose a reusable capability bundle (tools, instructions, optional hooks). */
10
- export declare function capability<Info = unknown>(declaration: {
11
- readonly id: string;
12
- readonly name?: string;
13
- readonly description?: string;
14
- readonly tools?: readonly (ToolDefinition<any, Info, any> | import("../types/agent.js").AgentTool)[];
15
- readonly instructions?: string | readonly string[];
16
- /** Run before each turn or before every model call (step). */
17
- readonly before?: import("../types/dynamics.js").BeforeHooks<Info>;
18
- /** Run after every model call (step) or after the turn's final answer. */
19
- readonly after?: import("../types/dynamics.js").AfterHooks<Info>;
20
- /** @deprecated Prefer before / after hooks. */
21
- readonly middleware?: StepMiddleware<Info>;
22
- /** @deprecated Model resolution is Runtime-owned; not projected into the manifest. */
23
- readonly model?: import("../types/model.js").ModelDirective;
24
- }): import("../types/middleware.js").CapabilityDeclaration<Info>;
9
+ export { capability } from "./capability.js";
25
10
  export type { ToolSchemaSource };
@@ -1,36 +1,7 @@
1
1
  import { prepareTool } from "./schema.js";
2
- import { delegateTool, isAgentItem } from "./delegate.js";
3
2
  export const tool = (value) => prepareTool(value);
4
3
  /** @deprecated Prefer Runtime model resolution. Capability-disguised `.use({ model })` is not the taught path. */
5
4
  export const model = (value) => value;
6
5
  /** @deprecated Prefer `before` / `after` hooks. Kept through 1.0. */
7
6
  export const middleware = (value) => value;
8
- /** Compose a reusable capability bundle (tools, instructions, optional hooks). */
9
- export function capability(declaration) {
10
- const instructions = declaration.instructions === undefined
11
- ? undefined
12
- : typeof declaration.instructions === "string"
13
- ? [declaration.instructions]
14
- : declaration.instructions;
15
- return {
16
- id: declaration.id,
17
- ...(declaration.name === undefined ? {} : { name: declaration.name }),
18
- ...(declaration.description === undefined
19
- ? {}
20
- : { description: declaration.description }),
21
- ...(declaration.tools === undefined
22
- ? {}
23
- : {
24
- tools: declaration.tools.map((item) => isAgentItem(item)
25
- ? delegateTool(item)
26
- : item),
27
- }),
28
- ...(instructions === undefined ? {} : { instructions }),
29
- ...(declaration.before === undefined ? {} : { before: declaration.before }),
30
- ...(declaration.after === undefined ? {} : { after: declaration.after }),
31
- ...(declaration.middleware === undefined
32
- ? {}
33
- : { middleware: declaration.middleware }),
34
- ...(declaration.model === undefined ? {} : { model: declaration.model }),
35
- };
36
- }
7
+ export { capability } from "./capability.js";
@@ -0,0 +1,37 @@
1
+ import type { CapabilityDeclaration } from "../types/middleware.js";
2
+ import type { McpServerManifest } from "../types/manifest.js";
3
+ type WithOptionalName<T> = T extends {
4
+ readonly name: string;
5
+ } ? Omit<T, "name"> & {
6
+ readonly name?: string;
7
+ } : never;
8
+ /** An MCP server as written by an author: `name` defaults to the server's key. */
9
+ export type McpServerSpec = WithOptionalName<McpServerManifest>;
10
+ export interface McpOptions {
11
+ /** Capability id. Defaults to `"mcp"`. */
12
+ readonly id?: string;
13
+ }
14
+ export interface McpCapability extends CapabilityDeclaration {
15
+ readonly mcpServers: Readonly<Record<string, McpServerManifest>>;
16
+ }
17
+ export declare class McpError extends Error {
18
+ readonly code: string;
19
+ constructor(code: string, message: string);
20
+ }
21
+ /**
22
+ * Declare MCP servers as one capability.
23
+ *
24
+ * Prefer `Agent(...).mcp({ ... })`. Each key names a server; its `name` defaults to
25
+ * the key and, when given, must equal it. Supported transports are `stdio`,
26
+ * `streamable-http`, and `sse` (see https://agent-plugins.org/plugin-authors/mcp-servers).
27
+ *
28
+ * ```ts
29
+ * Agent({ id: "assistant" }).mcp({
30
+ * github: { type: "streamable-http", url: "https://mcp.example.com/github" },
31
+ * })
32
+ * ```
33
+ */
34
+ export declare function mcp(servers: Readonly<Record<string, McpServerSpec>>, options?: McpOptions): McpCapability;
35
+ /** Validate a map of MCP servers and fill each `name` from its key. */
36
+ export declare function normalizeMcpServers(servers: Readonly<Record<string, McpServerSpec>>, caller?: string): Readonly<Record<string, McpServerManifest>>;
37
+ export {};
@@ -0,0 +1,81 @@
1
+ export class McpError extends Error {
2
+ code;
3
+ constructor(code, message) {
4
+ super(message);
5
+ this.name = "McpError";
6
+ this.code = code;
7
+ }
8
+ }
9
+ /**
10
+ * Declare MCP servers as one capability.
11
+ *
12
+ * Prefer `Agent(...).mcp({ ... })`. Each key names a server; its `name` defaults to
13
+ * the key and, when given, must equal it. Supported transports are `stdio`,
14
+ * `streamable-http`, and `sse` (see https://agent-plugins.org/plugin-authors/mcp-servers).
15
+ *
16
+ * ```ts
17
+ * Agent({ id: "assistant" }).mcp({
18
+ * github: { type: "streamable-http", url: "https://mcp.example.com/github" },
19
+ * })
20
+ * ```
21
+ */
22
+ export function mcp(servers, options = {}) {
23
+ const id = options.id ?? "mcp";
24
+ return { id, mcpServers: normalizeMcpServers(servers, "mcp()") };
25
+ }
26
+ /** Validate a map of MCP servers and fill each `name` from its key. */
27
+ export function normalizeMcpServers(servers, caller = "mcp()") {
28
+ if (!isRecord(servers)) {
29
+ throw new McpError("mcp.invalid", `${caller} expects a non-empty map of MCP servers`);
30
+ }
31
+ const entries = Object.entries(servers);
32
+ if (entries.length === 0) {
33
+ throw new McpError("mcp.empty", `${caller} requires at least one MCP server`);
34
+ }
35
+ const mcpServers = {};
36
+ for (const [key, spec] of entries) {
37
+ const server = isRecord(spec) && spec.name === undefined ? { ...spec, name: key } : spec;
38
+ if (!isMcpServer(server)) {
39
+ throw new McpError("mcp.invalid-server", `MCP server '${key}' is not a valid stdio, streamable-http, or sse declaration`);
40
+ }
41
+ if (server.name !== key) {
42
+ throw new McpError("mcp.name-mismatch", `MCP server key '${key}' must equal the server name '${server.name}'`);
43
+ }
44
+ mcpServers[key] = freezeServer(server);
45
+ }
46
+ return Object.freeze(mcpServers);
47
+ }
48
+ function freezeServer(server) {
49
+ if (server.type === "stdio") {
50
+ return Object.freeze({
51
+ name: server.name,
52
+ type: "stdio",
53
+ command: server.command,
54
+ ...(server.args === undefined ? {} : { args: Object.freeze([...server.args]) }),
55
+ ...(server.env === undefined
56
+ ? {}
57
+ : { env: Object.freeze({ ...server.env }) }),
58
+ ...(server.cwd === undefined ? {} : { cwd: server.cwd }),
59
+ });
60
+ }
61
+ return Object.freeze({
62
+ name: server.name,
63
+ type: server.type,
64
+ url: server.url,
65
+ ...(server.headers === undefined
66
+ ? {}
67
+ : { headers: Object.freeze({ ...server.headers }) }),
68
+ });
69
+ }
70
+ function isMcpServer(value) {
71
+ if (!isRecord(value) || typeof value.name !== "string" || !value.name)
72
+ return false;
73
+ if (value.type === "stdio")
74
+ return typeof value.command === "string" && value.command.length > 0;
75
+ if (value.type === "streamable-http" || value.type === "sse")
76
+ return typeof value.url === "string" && value.url.length > 0;
77
+ return false;
78
+ }
79
+ function isRecord(value) {
80
+ return !!value && typeof value === "object" && !Array.isArray(value);
81
+ }