@nylorun/harness 0.22.1-beta → 0.23.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 +84 -0
- package/HOST_CONTRACT.md +17 -19
- package/README.md +5 -30
- package/dist/api/executors.d.ts +5 -4
- package/dist/api/harness.d.ts +0 -10
- package/dist/api/harness.js +1 -52
- package/dist/api/host.d.ts +2 -8
- package/dist/api/host.js +3 -15
- package/dist/api/run.d.ts +0 -11
- package/dist/api/run.js +1 -11
- package/dist/compatibility.d.ts +4 -12
- package/dist/compatibility.js +3 -11
- package/dist/definition/agent-definition.d.ts +0 -3
- package/dist/definition/agent-definition.js +0 -2
- package/dist/flow/checkpoint.d.ts +16 -0
- package/dist/flow/checkpoint.js +6 -2
- package/dist/flow/context.d.ts +19 -10
- package/dist/flow/context.js +36 -20
- package/dist/flow/engine.d.ts +25 -7
- package/dist/flow/engine.js +304 -38
- package/dist/flow/index.d.ts +3 -5
- package/dist/flow/index.js +3 -5
- package/dist/flow/paths.d.ts +1 -8
- package/dist/flow/paths.js +1 -12
- package/dist/flow/tool.d.ts +14 -0
- package/dist/flow/tool.js +67 -0
- package/dist/flow/types.d.ts +30 -3
- package/dist/flow/types.js +14 -1
- package/dist/loop/run.js +5 -134
- package/dist/loop/state.js +2 -22
- package/dist/loop/step/run.d.ts +1 -10
- package/dist/loop/step/run.js +2 -101
- package/dist/loop/step/runtime.d.ts +0 -17
- package/dist/run/durable.d.ts +7 -11
- package/dist/run/durable.js +14 -33
- package/dist/run/index.d.ts +3 -4
- package/dist/run/index.js +1 -2
- package/dist/types/execution.d.ts +5 -18
- package/package.json +2 -2
- package/dist/flow/chain.d.ts +0 -8
- package/dist/flow/chain.js +0 -27
- package/dist/flow/loop.d.ts +0 -35
- package/dist/flow/loop.js +0 -238
- package/dist/flow/map.d.ts +0 -7
- package/dist/flow/map.js +0 -64
- package/dist/flow/node.d.ts +0 -31
- package/dist/flow/node.js +0 -113
- package/dist/flow/parallel.d.ts +0 -7
- package/dist/flow/parallel.js +0 -47
- package/dist/flow/switch.d.ts +0 -8
- package/dist/flow/switch.js +0 -35
- package/dist/flow/v2.d.ts +0 -12
- package/dist/flow/v2.js +0 -370
- package/dist/loop/step/hooks.d.ts +0 -56
- package/dist/loop/step/hooks.js +0 -191
|
@@ -1,33 +1,16 @@
|
|
|
1
1
|
import type { ToolRegistry } from "../../definition/registry.js";
|
|
2
|
-
import type { AgentDefinition } from "../../definition/agent-definition.js";
|
|
3
2
|
import type { ModelAdapter } from "@nylorun/core/define";
|
|
4
3
|
import type { InputEvent, TranscriptEntry } from "@nylorun/core/define";
|
|
5
4
|
import type { ToolResult } from "@nylorun/core/define";
|
|
6
5
|
import type { BoundMiddleware } from "@nylorun/core/define";
|
|
7
6
|
import type { JsonValue } from "@nylorun/core/define";
|
|
8
|
-
import type { CallPatch } from "./hooks.js";
|
|
9
7
|
/** Compiled definition pieces plus the per-run model adapter for one step. */
|
|
10
8
|
export interface StepRuntime {
|
|
11
9
|
readonly middleware: readonly BoundMiddleware[];
|
|
12
10
|
readonly invoke: ModelAdapter;
|
|
13
11
|
readonly registry: ToolRegistry;
|
|
14
|
-
/** Full definition for before/after hooks (optional for middleware-only agents). */
|
|
15
|
-
readonly definition?: AgentDefinition;
|
|
16
12
|
/** Mutable session memory bag shared with tools. */
|
|
17
13
|
sessionState?: Record<string, JsonValue>;
|
|
18
|
-
/** Called after hook results are applied so the host can record. */
|
|
19
|
-
recordAfterDynamics?: () => Promise<void>;
|
|
20
|
-
}
|
|
21
|
-
/** Turn-scoped hook state carried into each step. */
|
|
22
|
-
export interface StepTurnHooks {
|
|
23
|
-
/** True for the first model call of a new turn: run before("turn"). */
|
|
24
|
-
readonly start: boolean;
|
|
25
|
-
/** Input that started the turn; hooks see it on every step, including retries. */
|
|
26
|
-
readonly input?: string;
|
|
27
|
-
/** Validated before("turn") patch applied to every step. */
|
|
28
|
-
readonly patch?: CallPatch;
|
|
29
|
-
/** Retries already requested by after("step") hooks this turn. */
|
|
30
|
-
readonly afterStepAttempts: number;
|
|
31
14
|
}
|
|
32
15
|
export interface StepInput {
|
|
33
16
|
readonly executionId: string;
|
package/dist/run/durable.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import type { AgentManifest } from "@nylorun/core/define";
|
|
2
2
|
import type { ExecutionInput, ExecutionState, RunResult } from "../types/execution.js";
|
|
3
3
|
import type { JsonObject } from "@nylorun/core/define";
|
|
4
|
-
import type {
|
|
5
|
-
import type { AgentRef,
|
|
4
|
+
import type { EffectOutcome } from "@nylorun/core/contracts";
|
|
5
|
+
import type { AgentRef, ApprovalMode } from "@nylorun/core/define";
|
|
6
6
|
import { ENGINE_VERSION } from "../compatibility.js";
|
|
7
7
|
/** Private persistence contract for hosts; this is not a session wire type. */
|
|
8
8
|
export interface DurableCheckpoint {
|
|
@@ -25,19 +25,13 @@ export interface HostEffect {
|
|
|
25
25
|
readonly manifestHash: string;
|
|
26
26
|
/**
|
|
27
27
|
* `delegation` journals when an agent used as a tool starts and settles; hosts record it and resolve it at once.
|
|
28
|
-
* Flow effects: `agent
|
|
28
|
+
* Flow effects: `agent` and `tool` (node) — each carries `path`, `key`, and `iterations`.
|
|
29
29
|
*/
|
|
30
|
-
readonly kind: "model" | "tool" | "
|
|
30
|
+
readonly kind: "model" | "tool" | "delegation" | "agent";
|
|
31
31
|
/** Set on work for an agent used as a tool; `agentId` stays the session's root agent. */
|
|
32
32
|
readonly agent?: AgentRef;
|
|
33
33
|
readonly capabilityId?: string;
|
|
34
34
|
readonly toolName?: string;
|
|
35
|
-
/** For `hook` effects: the hook point and every capability that registered it, in manifest order. */
|
|
36
|
-
readonly hook?: {
|
|
37
|
-
readonly at: HookAt;
|
|
38
|
-
readonly scope: HookScope;
|
|
39
|
-
readonly capabilityIds: readonly string[];
|
|
40
|
-
};
|
|
41
35
|
/** Workflow node path (flow effects). */
|
|
42
36
|
readonly path?: string;
|
|
43
37
|
/** Workflow node key without Map indices (flow effects). */
|
|
@@ -49,7 +43,7 @@ export interface HostEffect {
|
|
|
49
43
|
}
|
|
50
44
|
export type EffectResolution = {
|
|
51
45
|
readonly status: "completed";
|
|
52
|
-
readonly outcome:
|
|
46
|
+
readonly outcome: EffectOutcome;
|
|
53
47
|
} | {
|
|
54
48
|
readonly status: "pending" | "uncertain";
|
|
55
49
|
};
|
|
@@ -78,6 +72,8 @@ export interface DurableSessionTool {
|
|
|
78
72
|
readonly description?: string;
|
|
79
73
|
readonly inputSchema: JsonObject;
|
|
80
74
|
readonly outputSchema?: JsonObject;
|
|
75
|
+
/** `always`: each call waits for approval (a remote MCP server's `approval`). */
|
|
76
|
+
readonly approval?: ApprovalMode;
|
|
81
77
|
}
|
|
82
78
|
export declare function createDurableCheckpoint(input: {
|
|
83
79
|
manifest: AgentManifest;
|
package/dist/run/durable.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { HarnessError } from "@nylorun/core/define";
|
|
2
|
-
import { HOOK_POINTS, hasHook } from "@nylorun/core/define";
|
|
3
2
|
import { AgentManifestSchema } from "@nylorun/core/contracts";
|
|
4
|
-
import { agentFrom } from "@nylorun/core/define";
|
|
3
|
+
import { agentFrom, withHttpTarget } from "@nylorun/core/define";
|
|
5
4
|
import { definitionFor } from "../definition/agent-definition.js";
|
|
6
5
|
import { schemaFromJSON } from "@nylorun/core/define";
|
|
7
6
|
import { hashManifest } from "@nylorun/core/define";
|
|
@@ -79,6 +78,8 @@ export async function runDurable(options) {
|
|
|
79
78
|
...(tool.description === undefined ? {} : { description: tool.description }),
|
|
80
79
|
inputSchema: schemaFromJSON(tool.inputSchema),
|
|
81
80
|
...(tool.outputSchema ? { outputSchema: schemaFromJSON(tool.outputSchema) } : {}),
|
|
81
|
+
// Static approval: the engine asks before the call becomes an effect.
|
|
82
|
+
...(tool.approval === "always" ? { approval: () => true } : {}),
|
|
82
83
|
async execute(args, ctx) {
|
|
83
84
|
const previous = patchTail;
|
|
84
85
|
let release;
|
|
@@ -122,27 +123,29 @@ export async function runDurable(options) {
|
|
|
122
123
|
});
|
|
123
124
|
};
|
|
124
125
|
const sessionTools = options.sessionTools ?? [];
|
|
125
|
-
/** Rebuild one agent from its manifest with every tool
|
|
126
|
+
/** Rebuild one agent from its manifest with every tool routed through host effects. */
|
|
126
127
|
const hostedDefinition = (agent, ref) => {
|
|
127
128
|
const hostedTool = hostedTools(ref);
|
|
128
129
|
const owned = sessionTools.filter((tool) => (tool.agentId ?? manifest.id) === agent.id);
|
|
129
130
|
const implementations = {};
|
|
130
131
|
for (const capability of agent.capabilities) {
|
|
131
132
|
const tools = {};
|
|
132
|
-
// Agents used as tools are rebuilt from their manifest body; the engine runs them.
|
|
133
|
+
// Agents used as tools are rebuilt from their manifest body; the engine runs them. An
|
|
134
|
+
// HTTP tool keeps its target (the manifest's hash covers it) and runs as a host effect.
|
|
133
135
|
for (const tool of capability.tools ?? [])
|
|
134
|
-
if (
|
|
136
|
+
if (tool.http)
|
|
137
|
+
tools[tool.name] = withHttpTarget(hostedTool(capability.id, tool), {
|
|
138
|
+
http: tool.http,
|
|
139
|
+
...(tool.approval === undefined ? {} : { approval: tool.approval }),
|
|
140
|
+
});
|
|
141
|
+
else if (!tool.agent)
|
|
135
142
|
tools[tool.name] = hostedTool(capability.id, tool);
|
|
136
143
|
for (const tool of owned)
|
|
137
144
|
if (tool.capabilityId === capability.id)
|
|
138
145
|
tools[tool.name] = hostedTool(capability.id, tool);
|
|
139
|
-
implementations[capability.id] = {
|
|
140
|
-
tools,
|
|
141
|
-
// Hooks run through runHooks below, one effect per hook point; these only satisfy binding.
|
|
142
|
-
...hookPlaceholders(capability.hooks),
|
|
143
|
-
};
|
|
146
|
+
implementations[capability.id] = { tools };
|
|
144
147
|
}
|
|
145
|
-
|
|
148
|
+
return definitionFor(agentFrom(agent, implementations, owned.length === 0
|
|
146
149
|
? undefined
|
|
147
150
|
: {
|
|
148
151
|
sessionTools: owned.map((tool) => ({
|
|
@@ -150,18 +153,6 @@ export async function runDurable(options) {
|
|
|
150
153
|
name: tool.name,
|
|
151
154
|
})),
|
|
152
155
|
}));
|
|
153
|
-
// All capabilities registered at a hook point share one effect, so one Action delivery.
|
|
154
|
-
const runHooks = async ({ point, capabilityIds, args, identity }) => {
|
|
155
|
-
const outcome = await effect("hook", args, { info: checkpoint.info }, scoped(ref, identity), {
|
|
156
|
-
hook: { at: point.at, scope: point.scope, capabilityIds },
|
|
157
|
-
...(ref ? { agent: ref } : {}),
|
|
158
|
-
});
|
|
159
|
-
const results = outcome.value?.results;
|
|
160
|
-
return results !== null && typeof results === "object" && !Array.isArray(results)
|
|
161
|
-
? results
|
|
162
|
-
: {};
|
|
163
|
-
};
|
|
164
|
-
return Object.freeze({ ...definition, runHooks });
|
|
165
156
|
};
|
|
166
157
|
const modelCall = (ref) => async (call, ctx) => (await effect("model", call,
|
|
167
158
|
// The call already holds the whole prompt; journaling the request would store it twice.
|
|
@@ -217,13 +208,3 @@ export async function runDurable(options) {
|
|
|
217
208
|
function scoped(ref, identity) {
|
|
218
209
|
return ref ? `${ref.delegationId}/${identity}` : identity;
|
|
219
210
|
}
|
|
220
|
-
function hookPlaceholders(hooks) {
|
|
221
|
-
const placeholder = () => {
|
|
222
|
-
throw new HarnessError("execution.incompatible", "Hosted hooks run through the host effect");
|
|
223
|
-
};
|
|
224
|
-
const table = {};
|
|
225
|
-
for (const point of HOOK_POINTS)
|
|
226
|
-
if (hasHook(hooks, point.at, point.scope))
|
|
227
|
-
(table[point.at] ??= {})[point.scope] = placeholder;
|
|
228
|
-
return table;
|
|
229
|
-
}
|
package/dist/run/index.d.ts
CHANGED
|
@@ -29,9 +29,8 @@ export declare function bindingFromAgent(agent: BuiltAgent): RunBinding;
|
|
|
29
29
|
export { checkCompatibility, createExecutionState, validateExecutionState, execute };
|
|
30
30
|
export type { Implementations, ExecutionState, RunResult, RunOptions };
|
|
31
31
|
export { createDurableCheckpoint, runDurable } from "./durable.js";
|
|
32
|
-
export { createFlowCheckpoint, runFlowDurable } from "../flow/index.js";
|
|
32
|
+
export { createFlowCheckpoint, resumeFlowCheckpoint, runFlowDurable } from "../flow/index.js";
|
|
33
33
|
export type { DurableCheckpoint, DurableSessionTool, HostEffect, EffectResolution, DurableHost, DurableResult, } from "./durable.js";
|
|
34
|
-
export type { FlowCheckpoint } from "../flow/checkpoint.js";
|
|
35
|
-
export type { FlowDurableResult, FlowRunResult } from "../flow/types.js";
|
|
36
|
-
export { agentTurnValue, AGENT_TURN_MARKER, type AgentTurnValue } from "../flow/loop.js";
|
|
34
|
+
export type { FlowCheckpoint, FlowResume } from "../flow/checkpoint.js";
|
|
35
|
+
export type { FlowDurableResult, FlowInteraction, FlowRunResult } from "../flow/types.js";
|
|
37
36
|
export type { ModelAdapter, ModelCandidate, ModelCall, ModelRequest } from "@nylorun/core/define";
|
package/dist/run/index.js
CHANGED
|
@@ -36,5 +36,4 @@ export function bindingFromAgent(agent) {
|
|
|
36
36
|
}
|
|
37
37
|
export { checkCompatibility, createExecutionState, validateExecutionState, execute };
|
|
38
38
|
export { createDurableCheckpoint, runDurable } from "./durable.js";
|
|
39
|
-
export { createFlowCheckpoint, runFlowDurable } from "../flow/index.js";
|
|
40
|
-
export { agentTurnValue, AGENT_TURN_MARKER } from "../flow/loop.js";
|
|
39
|
+
export { createFlowCheckpoint, resumeFlowCheckpoint, runFlowDurable } from "../flow/index.js";
|
|
@@ -58,22 +58,9 @@ export interface ExecutionPlan {
|
|
|
58
58
|
readonly immediate: readonly ToolResult[];
|
|
59
59
|
readonly calls: readonly SavedToolCall[];
|
|
60
60
|
}
|
|
61
|
-
/**
|
|
62
|
-
export interface
|
|
61
|
+
/** The turn in flight, kept across a segment rollover or a crash. Cleared when the turn ends. */
|
|
62
|
+
export interface TurnState {
|
|
63
63
|
readonly turnId: string;
|
|
64
|
-
/** Text of the input that started the turn. */
|
|
65
|
-
readonly input?: string;
|
|
66
|
-
/** Validated before("turn") patch, applied to every step of the turn. */
|
|
67
|
-
readonly patch?: {
|
|
68
|
-
readonly capabilities?: Readonly<Record<string, boolean>>;
|
|
69
|
-
readonly tools?: Readonly<Record<string, boolean>>;
|
|
70
|
-
readonly instructions?: readonly string[];
|
|
71
|
-
};
|
|
72
|
-
/** Retries requested so far this turn, per hook point. */
|
|
73
|
-
readonly attempts: {
|
|
74
|
-
readonly afterStep: number;
|
|
75
|
-
readonly afterTurn: number;
|
|
76
|
-
};
|
|
77
64
|
}
|
|
78
65
|
/** Versioned continuation data, not a live execution object. */
|
|
79
66
|
export interface ExecutionState {
|
|
@@ -90,10 +77,10 @@ export interface ExecutionState {
|
|
|
90
77
|
readonly plan?: ExecutionPlan;
|
|
91
78
|
/** Abandoned actions retained for reconciliation, never automatically dispatched. */
|
|
92
79
|
readonly cancelledCalls?: readonly SavedToolCall[];
|
|
93
|
-
/**
|
|
94
|
-
readonly turn?:
|
|
80
|
+
/** The current turn; present only while a turn continues in a later segment. */
|
|
81
|
+
readonly turn?: TurnState;
|
|
95
82
|
/**
|
|
96
|
-
* Durable session memory (tools write via `ctx.state
|
|
83
|
+
* Durable session memory (tools write via `ctx.state`).
|
|
97
84
|
* Runtime persists this with the checkpoint.
|
|
98
85
|
*/
|
|
99
86
|
readonly state?: JsonObject;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nylorun/harness",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.23.0-beta",
|
|
4
4
|
"description": "Nylorun's TypeScript agent execution engine. See github.com/nylorun/agents.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -81,7 +81,7 @@
|
|
|
81
81
|
"zod": "^4.6.5"
|
|
82
82
|
},
|
|
83
83
|
"dependencies": {
|
|
84
|
-
"@nylorun/core": "0.
|
|
84
|
+
"@nylorun/core": "0.15.0-beta"
|
|
85
85
|
},
|
|
86
86
|
"peerDependencies": {
|
|
87
87
|
"zod": "^4.6.5"
|
package/dist/flow/chain.d.ts
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import type { JsonValue } from "@nylorun/core/define";
|
|
2
|
-
import type { WorkflowChainNode } from "@nylorun/core";
|
|
3
|
-
import type { FlowContext } from "./context.js";
|
|
4
|
-
/**
|
|
5
|
-
* Chain: steps in order; step 1 gets chain input; later steps get prior output
|
|
6
|
-
* unless a slot `input` reshapes. `results` is lexical for the nearest enclosing Chain.
|
|
7
|
-
*/
|
|
8
|
-
export declare function runChain(ctx: FlowContext, chain: WorkflowChainNode["chain"], path: string, input: JsonValue): Promise<JsonValue>;
|
package/dist/flow/chain.js
DELETED
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
import { joinPath } from "./paths.js";
|
|
2
|
-
import { runNode, unwrapSlot } from "./node.js";
|
|
3
|
-
/**
|
|
4
|
-
* Chain: steps in order; step 1 gets chain input; later steps get prior output
|
|
5
|
-
* unless a slot `input` reshapes. `results` is lexical for the nearest enclosing Chain.
|
|
6
|
-
*/
|
|
7
|
-
export async function runChain(ctx, chain, path, input) {
|
|
8
|
-
const results = {};
|
|
9
|
-
const chainInput = input;
|
|
10
|
-
ctx.resultsStack.push(results);
|
|
11
|
-
try {
|
|
12
|
-
let current = input;
|
|
13
|
-
for (const step of chain.steps) {
|
|
14
|
-
const { part } = unwrapSlot(step);
|
|
15
|
-
const stepPath = joinPath(path, part);
|
|
16
|
-
const output = await runNode(ctx, step, stepPath, current, {
|
|
17
|
-
ownerInput: chainInput,
|
|
18
|
-
});
|
|
19
|
-
results[part] = output;
|
|
20
|
-
current = output;
|
|
21
|
-
}
|
|
22
|
-
return current;
|
|
23
|
-
}
|
|
24
|
-
finally {
|
|
25
|
-
ctx.resultsStack.pop();
|
|
26
|
-
}
|
|
27
|
-
}
|
package/dist/flow/loop.d.ts
DELETED
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
import type { AgentManifest, JsonValue, WorkflowManifest } from "@nylorun/core/define";
|
|
2
|
-
import type { WorkflowLoopNode } from "@nylorun/core";
|
|
3
|
-
import type { DurableHost } from "../run/durable.js";
|
|
4
|
-
import type { FlowCheckpoint } from "./checkpoint.js";
|
|
5
|
-
import { type FlowContext } from "./context.js";
|
|
6
|
-
import { type FlowOperatorLimits } from "./limits.js";
|
|
7
|
-
import { type FlowDurableResult } from "./types.js";
|
|
8
|
-
export type { FlowDurableResult, FlowRunResult } from "./types.js";
|
|
9
|
-
/** Host may wrap agent-effect outcomes so the Loop learns the turn's manifest. */
|
|
10
|
-
export declare const AGENT_TURN_MARKER: "__nylorunAgentTurn";
|
|
11
|
-
export type AgentTurnValue = {
|
|
12
|
-
readonly [AGENT_TURN_MARKER]: 1;
|
|
13
|
-
readonly output: JsonValue;
|
|
14
|
-
readonly agent: AgentManifest;
|
|
15
|
-
};
|
|
16
|
-
export declare function agentTurnValue(output: JsonValue, agent: AgentManifest): AgentTurnValue;
|
|
17
|
-
export declare function readAgentTurn(value: unknown): {
|
|
18
|
-
output: JsonValue;
|
|
19
|
-
agent?: AgentManifest;
|
|
20
|
-
};
|
|
21
|
-
/**
|
|
22
|
-
* Interpret a root Loop node. Returns effects only; the host journals outcomes.
|
|
23
|
-
*/
|
|
24
|
-
export declare function runLoop(options: {
|
|
25
|
-
readonly manifest: WorkflowManifest;
|
|
26
|
-
readonly checkpoint: FlowCheckpoint;
|
|
27
|
-
readonly host: DurableHost;
|
|
28
|
-
readonly signal?: AbortSignal;
|
|
29
|
-
readonly limits?: Partial<FlowOperatorLimits> | null;
|
|
30
|
-
}): Promise<FlowDurableResult>;
|
|
31
|
-
/**
|
|
32
|
-
* Nested or root Loop body: run → verify → decide until `{ output }` or stop.
|
|
33
|
-
* Agent turn pinning / decide patches (`decision.agent`) are L5.
|
|
34
|
-
*/
|
|
35
|
-
export declare function runLoopNode(ctx: FlowContext, loop: WorkflowLoopNode["loop"], path: string, input: JsonValue): Promise<JsonValue>;
|
package/dist/flow/loop.js
DELETED
|
@@ -1,238 +0,0 @@
|
|
|
1
|
-
import { HarnessError, isVariantOf } from "@nylorun/core/define";
|
|
2
|
-
import { HostSuspension } from "../loop/host-suspension.js";
|
|
3
|
-
import { createFlowContext, failureOf, settleInFlight } from "./context.js";
|
|
4
|
-
import { assertLoopIteration } from "./limits.js";
|
|
5
|
-
import { joinPath, nodeKeyOf } from "./paths.js";
|
|
6
|
-
import { runNode, unwrapSlot } from "./node.js";
|
|
7
|
-
import { FlowNodeError } from "./types.js";
|
|
8
|
-
/** Host may wrap agent-effect outcomes so the Loop learns the turn's manifest. */
|
|
9
|
-
export const AGENT_TURN_MARKER = "__nylorunAgentTurn";
|
|
10
|
-
export function agentTurnValue(output, agent) {
|
|
11
|
-
return { [AGENT_TURN_MARKER]: 1, output, agent };
|
|
12
|
-
}
|
|
13
|
-
export function readAgentTurn(value) {
|
|
14
|
-
if (value &&
|
|
15
|
-
typeof value === "object" &&
|
|
16
|
-
!Array.isArray(value) &&
|
|
17
|
-
value[AGENT_TURN_MARKER] === 1 &&
|
|
18
|
-
"output" in value &&
|
|
19
|
-
"agent" in value) {
|
|
20
|
-
return {
|
|
21
|
-
output: value.output,
|
|
22
|
-
agent: value.agent,
|
|
23
|
-
};
|
|
24
|
-
}
|
|
25
|
-
return { output: value };
|
|
26
|
-
}
|
|
27
|
-
function invalidAgent(path, message) {
|
|
28
|
-
throw new FlowNodeError({ code: "loop.invalid-agent", message, path });
|
|
29
|
-
}
|
|
30
|
-
/**
|
|
31
|
-
* Interpret a root Loop node. Returns effects only; the host journals outcomes.
|
|
32
|
-
*/
|
|
33
|
-
export async function runLoop(options) {
|
|
34
|
-
const { manifest, checkpoint, host } = options;
|
|
35
|
-
if (manifest.workflowSchemaVersion !== 1)
|
|
36
|
-
throw new HarnessError("execution.invalid-state", "runLoop expects a workflow manifest v1");
|
|
37
|
-
const root = manifest.root;
|
|
38
|
-
if (!("loop" in root))
|
|
39
|
-
throw new HarnessError("execution.invalid-state", "runLoop expects a loop root");
|
|
40
|
-
const ctx = createFlowContext({
|
|
41
|
-
manifest,
|
|
42
|
-
checkpoint,
|
|
43
|
-
host,
|
|
44
|
-
signal: options.signal,
|
|
45
|
-
limits: options.limits,
|
|
46
|
-
});
|
|
47
|
-
try {
|
|
48
|
-
if (options.signal?.aborted)
|
|
49
|
-
return { status: "cancelled", checkpoint, result: { status: "cancelled" } };
|
|
50
|
-
const output = await runLoopNode(ctx, root.loop, root.loop.id, checkpoint.input);
|
|
51
|
-
return {
|
|
52
|
-
status: "completed",
|
|
53
|
-
checkpoint,
|
|
54
|
-
result: { status: "completed", output },
|
|
55
|
-
};
|
|
56
|
-
}
|
|
57
|
-
catch (error) {
|
|
58
|
-
await settleInFlight(ctx);
|
|
59
|
-
if (error instanceof HostSuspension) {
|
|
60
|
-
return {
|
|
61
|
-
status: [...ctx.pending.values()].includes("uncertain") ? "uncertain" : "waiting",
|
|
62
|
-
checkpoint,
|
|
63
|
-
effectIds: [...ctx.pending.keys()],
|
|
64
|
-
};
|
|
65
|
-
}
|
|
66
|
-
if (error instanceof FlowNodeError && error.failure.code === "cancelled")
|
|
67
|
-
return { status: "cancelled", checkpoint, result: { status: "cancelled" } };
|
|
68
|
-
const failure = failureOf(error, root.loop.id);
|
|
69
|
-
return {
|
|
70
|
-
status: "failed",
|
|
71
|
-
checkpoint,
|
|
72
|
-
result: { status: "failed", error: failure },
|
|
73
|
-
...(ctx.cancelEffectIds.size > 0 ? { cancelEffectIds: [...ctx.cancelEffectIds] } : {}),
|
|
74
|
-
};
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
/**
|
|
78
|
-
* Nested or root Loop body: run → verify → decide until `{ output }` or stop.
|
|
79
|
-
* Agent turn pinning / decide patches (`decision.agent`) are L5.
|
|
80
|
-
*/
|
|
81
|
-
export async function runLoopNode(ctx, loop, path, input) {
|
|
82
|
-
let iteration = 1;
|
|
83
|
-
let currentInput = input;
|
|
84
|
-
const history = [];
|
|
85
|
-
const loopInput = input;
|
|
86
|
-
const runIsAgent = "agent" in loop.run;
|
|
87
|
-
// Session pin (first turn's manifest) and the patch carried within this run.
|
|
88
|
-
let pinnedAgent;
|
|
89
|
-
let currentAgent;
|
|
90
|
-
for (;;) {
|
|
91
|
-
if (ctx.signal?.aborted)
|
|
92
|
-
throw new FlowNodeError({ code: "cancelled", message: "cancelled", path });
|
|
93
|
-
// Operator ceiling before starting this iteration (WF-L3 / LOOP-A8).
|
|
94
|
-
assertLoopIteration(iteration, ctx.limits, path);
|
|
95
|
-
ctx.iterations = [...ctx.iterations, iteration];
|
|
96
|
-
const iterations = ctx.iterationsString();
|
|
97
|
-
try {
|
|
98
|
-
let runOutput;
|
|
99
|
-
if (runIsAgent) {
|
|
100
|
-
const agentId = loop.run.agent;
|
|
101
|
-
const agentPath = runPath(path, loop.run);
|
|
102
|
-
const rawAgent = await ctx.effect("agent", {
|
|
103
|
-
agentId,
|
|
104
|
-
input: currentInput,
|
|
105
|
-
path: agentPath,
|
|
106
|
-
...(currentAgent ? { manifest: currentAgent } : {}),
|
|
107
|
-
}, { path: agentPath, key: nodeKeyOf(agentPath), iterations }, { loopPath: path, n: iteration });
|
|
108
|
-
const turned = readAgentTurn(rawAgent);
|
|
109
|
-
runOutput = turned.output;
|
|
110
|
-
if (turned.agent) {
|
|
111
|
-
// First turn establishes the session pin; later turns may be variants.
|
|
112
|
-
pinnedAgent ??= turned.agent;
|
|
113
|
-
currentAgent = turned.agent;
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
else {
|
|
117
|
-
runOutput = await runNode(ctx, loop.run, runPath(path, loop.run), currentInput, {
|
|
118
|
-
ownerInput: loopInput,
|
|
119
|
-
});
|
|
120
|
-
}
|
|
121
|
-
const verdict = await runVerify(ctx, loop.verify, path, {
|
|
122
|
-
input: loopInput,
|
|
123
|
-
output: runOutput,
|
|
124
|
-
iteration,
|
|
125
|
-
});
|
|
126
|
-
let decision;
|
|
127
|
-
try {
|
|
128
|
-
decision = (await ctx.effect("fn", {
|
|
129
|
-
output: runOutput,
|
|
130
|
-
verdict,
|
|
131
|
-
iteration,
|
|
132
|
-
input: loopInput,
|
|
133
|
-
history,
|
|
134
|
-
...(currentAgent ? { agent: currentAgent } : {}),
|
|
135
|
-
}, { path, key: `${nodeKeyOf(path)}/decide`, iterations }, { loopPath: path, n: iteration, role: "decide" }));
|
|
136
|
-
}
|
|
137
|
-
catch (error) {
|
|
138
|
-
if (error instanceof FlowNodeError && error.failure.code === "fn.failed") {
|
|
139
|
-
throw new FlowNodeError({
|
|
140
|
-
code: "loop.stopped",
|
|
141
|
-
message: error.failure.message,
|
|
142
|
-
path,
|
|
143
|
-
});
|
|
144
|
-
}
|
|
145
|
-
if (error instanceof Error &&
|
|
146
|
-
!(error instanceof HostSuspension) &&
|
|
147
|
-
!(error instanceof FlowNodeError)) {
|
|
148
|
-
throw new FlowNodeError({
|
|
149
|
-
code: "loop.stopped",
|
|
150
|
-
message: error.message,
|
|
151
|
-
path,
|
|
152
|
-
});
|
|
153
|
-
}
|
|
154
|
-
throw error;
|
|
155
|
-
}
|
|
156
|
-
if ("output" in decision && !("input" in decision))
|
|
157
|
-
return decision.output;
|
|
158
|
-
if (!("input" in decision))
|
|
159
|
-
throw new HarnessError("execution.invalid-state", "Decide returned neither input nor output");
|
|
160
|
-
const next = decision;
|
|
161
|
-
if (next.agent !== undefined) {
|
|
162
|
-
if (!runIsAgent) {
|
|
163
|
-
invalidAgent(path, "Decide returned agent but Loop.run is not an agent");
|
|
164
|
-
}
|
|
165
|
-
if (pinnedAgent && !isVariantOf(next.agent, pinnedAgent)) {
|
|
166
|
-
invalidAgent(path, "Decide returned a manifest that is not a variant of the pinned agent");
|
|
167
|
-
}
|
|
168
|
-
currentAgent = next.agent;
|
|
169
|
-
}
|
|
170
|
-
history.push({ iteration, output: runOutput, verdict });
|
|
171
|
-
currentInput = next.input;
|
|
172
|
-
iteration += 1;
|
|
173
|
-
}
|
|
174
|
-
finally {
|
|
175
|
-
ctx.iterations.pop();
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
function runPath(loopPath, run) {
|
|
180
|
-
const { part } = unwrapSlot(run);
|
|
181
|
-
return joinPath(loopPath, part);
|
|
182
|
-
}
|
|
183
|
-
async function runVerify(ctx, verify, loopPath, args) {
|
|
184
|
-
const iterations = ctx.iterationsString();
|
|
185
|
-
if ("fn" in verify) {
|
|
186
|
-
try {
|
|
187
|
-
return (await ctx.effect("verify", args, { path: loopPath, key: nodeKeyOf(loopPath), iterations }, { loopPath, n: args.iteration }));
|
|
188
|
-
}
|
|
189
|
-
catch (error) {
|
|
190
|
-
if (error instanceof FlowNodeError) {
|
|
191
|
-
if (error.failure.code === "loop.verify-failed")
|
|
192
|
-
throw error;
|
|
193
|
-
throw new FlowNodeError({
|
|
194
|
-
code: "loop.verify-failed",
|
|
195
|
-
message: error.failure.message,
|
|
196
|
-
path: loopPath,
|
|
197
|
-
});
|
|
198
|
-
}
|
|
199
|
-
throw error;
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
// Verifier agent (or slot wrapping one): input is { task, response, iteration }.
|
|
203
|
-
const judgePayload = {
|
|
204
|
-
task: args.input,
|
|
205
|
-
response: args.output,
|
|
206
|
-
iteration: args.iteration,
|
|
207
|
-
};
|
|
208
|
-
try {
|
|
209
|
-
if ("slot" in verify) {
|
|
210
|
-
const { part } = unwrapSlot(verify);
|
|
211
|
-
const verifyPath = joinPath(loopPath, part);
|
|
212
|
-
const value = await runNode(ctx, verify, verifyPath, judgePayload);
|
|
213
|
-
return value;
|
|
214
|
-
}
|
|
215
|
-
if ("agent" in verify) {
|
|
216
|
-
const verifyPath = joinPath(loopPath, verify.agent);
|
|
217
|
-
const value = await ctx.effect("agent", { agentId: verify.agent, input: judgePayload, path: verifyPath }, { path: verifyPath, key: nodeKeyOf(verifyPath), iterations }, { loopPath, n: args.iteration, role: "verify-agent" });
|
|
218
|
-
return value;
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
catch (error) {
|
|
222
|
-
if (error instanceof HostSuspension)
|
|
223
|
-
throw error;
|
|
224
|
-
if (error instanceof FlowNodeError) {
|
|
225
|
-
throw new FlowNodeError({
|
|
226
|
-
code: "loop.verify-failed",
|
|
227
|
-
message: error.failure.message,
|
|
228
|
-
path: loopPath,
|
|
229
|
-
});
|
|
230
|
-
}
|
|
231
|
-
throw new FlowNodeError({
|
|
232
|
-
code: "loop.verify-failed",
|
|
233
|
-
message: error instanceof Error ? error.message : String(error),
|
|
234
|
-
path: loopPath,
|
|
235
|
-
});
|
|
236
|
-
}
|
|
237
|
-
throw new HarnessError("execution.invalid-state", "Unsupported Loop.verify node");
|
|
238
|
-
}
|
package/dist/flow/map.d.ts
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import type { JsonValue } from "@nylorun/core/define";
|
|
2
|
-
import type { WorkflowMapNode } from "@nylorun/core";
|
|
3
|
-
import type { FlowContext } from "./context.js";
|
|
4
|
-
/**
|
|
5
|
-
* Map: journal `over`, run each item concurrently at `<map>[i]/<each id>`; fail-fast.
|
|
6
|
-
*/
|
|
7
|
-
export declare function runMap(ctx: FlowContext, node: WorkflowMapNode["map"], path: string, input: JsonValue): Promise<JsonValue>;
|
package/dist/flow/map.js
DELETED
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
import { HostSuspension } from "../loop/host-suspension.js";
|
|
2
|
-
import { failureOf, markFailFastCancels } from "./context.js";
|
|
3
|
-
import { assertMapItemCount } from "./limits.js";
|
|
4
|
-
import { FlowNodeError } from "./types.js";
|
|
5
|
-
import { mapItemPath, nodeKeyOf } from "./paths.js";
|
|
6
|
-
import { runNode, unwrapSlot } from "./node.js";
|
|
7
|
-
/**
|
|
8
|
-
* Map: journal `over`, run each item concurrently at `<map>[i]/<each id>`; fail-fast.
|
|
9
|
-
*/
|
|
10
|
-
export async function runMap(ctx, node, path, input) {
|
|
11
|
-
const over = await ctx.effect("fn", input, { path, key: `${nodeKeyOf(path)}/over` }, { role: "map-over" });
|
|
12
|
-
if (!Array.isArray(over)) {
|
|
13
|
-
throw new FlowNodeError({
|
|
14
|
-
code: "map.not-a-list",
|
|
15
|
-
message: "Map.over did not return an array",
|
|
16
|
-
path,
|
|
17
|
-
});
|
|
18
|
-
}
|
|
19
|
-
const items = over;
|
|
20
|
-
// Operator ceiling before any item starts (WF-L2 / MAP-E2).
|
|
21
|
-
assertMapItemCount(items.length, ctx.limits, path);
|
|
22
|
-
// Runtime emits map.items { path, count } after over is journaled.
|
|
23
|
-
if (items.length === 0)
|
|
24
|
-
return [];
|
|
25
|
-
const { part: eachPart } = unwrapSlot(node.each);
|
|
26
|
-
const outputs = new Array(items.length);
|
|
27
|
-
const suspensions = [];
|
|
28
|
-
const failures = [];
|
|
29
|
-
await Promise.all(items.map(async (item, index) => {
|
|
30
|
-
const itemPath = mapItemPath(path, index, eachPart);
|
|
31
|
-
try {
|
|
32
|
-
const eachNode = node.each;
|
|
33
|
-
if ("slot" in eachNode && eachNode.slot.input) {
|
|
34
|
-
outputs[index] = await runNode(ctx, eachNode, itemPath, item, {
|
|
35
|
-
map: { item, mapInput: input, index },
|
|
36
|
-
});
|
|
37
|
-
}
|
|
38
|
-
else {
|
|
39
|
-
outputs[index] = await runNode(ctx, eachNode, itemPath, item);
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
catch (error) {
|
|
43
|
-
if (error instanceof HostSuspension) {
|
|
44
|
-
suspensions.push(error);
|
|
45
|
-
return;
|
|
46
|
-
}
|
|
47
|
-
failures.push(error instanceof FlowNodeError ? error : new FlowNodeError(failureOf(error, itemPath)));
|
|
48
|
-
}
|
|
49
|
-
}));
|
|
50
|
-
if (failures.length > 0) {
|
|
51
|
-
markFailFastCancels(ctx);
|
|
52
|
-
failures.sort((a, b) => indexFromPath(a.failure.path) - indexFromPath(b.failure.path));
|
|
53
|
-
throw failures[0];
|
|
54
|
-
}
|
|
55
|
-
if (suspensions.length > 0)
|
|
56
|
-
throw suspensions[0];
|
|
57
|
-
return outputs;
|
|
58
|
-
}
|
|
59
|
-
function indexFromPath(path) {
|
|
60
|
-
if (!path)
|
|
61
|
-
return Number.MAX_SAFE_INTEGER;
|
|
62
|
-
const match = path.match(/\[(\d+)\]/);
|
|
63
|
-
return match ? Number(match[1]) : Number.MAX_SAFE_INTEGER;
|
|
64
|
-
}
|