@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
package/dist/compatibility.js
CHANGED
|
@@ -1,13 +1,5 @@
|
|
|
1
1
|
export { checkCompatibility } from "./definition/compatibility.js";
|
|
2
2
|
export const CHECKPOINT_VERSION = 1;
|
|
3
|
-
export const ENGINE_VERSION = "hosted-
|
|
4
|
-
/**
|
|
5
|
-
|
|
6
|
-
* `flow-2`; v1 manifests keep running on `flow-1`, so in-flight v1 runs finish as they began.
|
|
7
|
-
*/
|
|
8
|
-
export const FLOW_ENGINE_VERSION = "flow-2";
|
|
9
|
-
export const FLOW_ENGINE_VERSION_V1 = "flow-1";
|
|
10
|
-
/** The engine a workflow manifest runs on. */
|
|
11
|
-
export function flowEngineVersionOf(manifest) {
|
|
12
|
-
return manifest.workflowSchemaVersion === 2 ? FLOW_ENGINE_VERSION : FLOW_ENGINE_VERSION_V1;
|
|
13
|
-
}
|
|
3
|
+
export const ENGINE_VERSION = "hosted-4";
|
|
4
|
+
/** Flow engine version pinned on workflow checkpoints: workflow manifest v3 runs on `flow-3`. */
|
|
5
|
+
export const FLOW_ENGINE_VERSION = "flow-3";
|
|
@@ -3,7 +3,6 @@ import type { ToolRegistry } from "./registry.js";
|
|
|
3
3
|
import type { TurnOutputContract } from "@nylorun/core/define";
|
|
4
4
|
import type { AgentManifest } from "@nylorun/core/define";
|
|
5
5
|
import type { Implementations } from "@nylorun/core/define";
|
|
6
|
-
import { type HookRunner } from "../loop/step/hooks.js";
|
|
7
6
|
export interface AgentDefinition {
|
|
8
7
|
readonly id: string;
|
|
9
8
|
readonly middleware: readonly BoundMiddleware[];
|
|
@@ -12,8 +11,6 @@ export interface AgentDefinition {
|
|
|
12
11
|
readonly manifest: AgentManifest;
|
|
13
12
|
readonly hash: string;
|
|
14
13
|
readonly implementations: Implementations;
|
|
15
|
-
/** Runs one hook point. In-process by default; the durable host journals it as one effect. */
|
|
16
|
-
readonly runHooks: HookRunner;
|
|
17
14
|
}
|
|
18
15
|
export type { Implementations };
|
|
19
16
|
import type { AgentBinding } from "@nylorun/core/define";
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { localHookRunner } from "../loop/step/hooks.js";
|
|
2
1
|
import { bindingFromAgent, bindOutputContract } from "@nylorun/core/define";
|
|
3
2
|
import { ToolRegistry as Registry } from "./registry.js";
|
|
4
3
|
import { hashManifest } from "@nylorun/core/compatibility";
|
|
@@ -12,7 +11,6 @@ export function definitionFromBinding(binding) {
|
|
|
12
11
|
hash: hashManifest(binding.manifest),
|
|
13
12
|
middleware: binding.declarations,
|
|
14
13
|
implementations: binding.implementations,
|
|
15
|
-
runHooks: localHookRunner(binding.implementations),
|
|
16
14
|
registry: new Registry(binding.declarations, binding.tools),
|
|
17
15
|
...(binding.outputSchema ? { output: bindOutputContract(binding.outputSchema) } : {}),
|
|
18
16
|
});
|
|
@@ -11,7 +11,21 @@ export interface FlowCheckpoint {
|
|
|
11
11
|
/** Increment for each human/event continuation, not for an action result. */
|
|
12
12
|
readonly segment: number;
|
|
13
13
|
readonly input: JsonValue;
|
|
14
|
+
/**
|
|
15
|
+
* Answers to the flow's own interactions (a tool node's `ctx.approve` / `ctx.ask`), by
|
|
16
|
+
* interaction id. A flow resumes in the same segment, so its journaled effects replay; the
|
|
17
|
+
* tool that asked runs again as a new effect with its answer.
|
|
18
|
+
*/
|
|
19
|
+
readonly resumes?: Readonly<Record<string, FlowResume>>;
|
|
14
20
|
}
|
|
21
|
+
/** The answer to one flow interaction (`approve` or `respond`). */
|
|
22
|
+
export type FlowResume = {
|
|
23
|
+
readonly kind: "approval";
|
|
24
|
+
readonly approved: boolean;
|
|
25
|
+
} | {
|
|
26
|
+
readonly kind: "response";
|
|
27
|
+
readonly value: JsonValue;
|
|
28
|
+
};
|
|
15
29
|
export declare function createFlowCheckpoint(input: {
|
|
16
30
|
manifest: WorkflowManifest;
|
|
17
31
|
sessionId: string;
|
|
@@ -19,3 +33,5 @@ export declare function createFlowCheckpoint(input: {
|
|
|
19
33
|
input: JsonValue;
|
|
20
34
|
segment?: number;
|
|
21
35
|
}): FlowCheckpoint;
|
|
36
|
+
/** `checkpoint` with the answer to interaction `interactionId`. */
|
|
37
|
+
export declare function resumeFlowCheckpoint(checkpoint: FlowCheckpoint, interactionId: string, answer: FlowResume): FlowCheckpoint;
|
package/dist/flow/checkpoint.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { WorkflowManifestSchema } from "@nylorun/core/contracts";
|
|
2
2
|
import { hashManifest } from "@nylorun/core/define";
|
|
3
|
-
import { CHECKPOINT_VERSION,
|
|
3
|
+
import { CHECKPOINT_VERSION, FLOW_ENGINE_VERSION, } from "../compatibility.js";
|
|
4
4
|
export function createFlowCheckpoint(input) {
|
|
5
5
|
WorkflowManifestSchema.parse(input.manifest);
|
|
6
6
|
return {
|
|
7
7
|
version: CHECKPOINT_VERSION,
|
|
8
|
-
engineVersion:
|
|
8
|
+
engineVersion: FLOW_ENGINE_VERSION,
|
|
9
9
|
manifestHash: hashManifest(input.manifest),
|
|
10
10
|
sessionId: input.sessionId,
|
|
11
11
|
turnId: input.turnId,
|
|
@@ -13,3 +13,7 @@ export function createFlowCheckpoint(input) {
|
|
|
13
13
|
input: input.input,
|
|
14
14
|
};
|
|
15
15
|
}
|
|
16
|
+
/** `checkpoint` with the answer to interaction `interactionId`. */
|
|
17
|
+
export function resumeFlowCheckpoint(checkpoint, interactionId, answer) {
|
|
18
|
+
return { ...checkpoint, resumes: { ...checkpoint.resumes, [interactionId]: answer } };
|
|
19
|
+
}
|
package/dist/flow/context.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { WorkflowManifest } from "@nylorun/core/define";
|
|
2
2
|
import type { DurableHost } from "../run/durable.js";
|
|
3
3
|
import type { FlowCheckpoint } from "./checkpoint.js";
|
|
4
4
|
import { type FlowOperatorLimits } from "./limits.js";
|
|
5
|
-
import { type FlowFailure } from "./types.js";
|
|
6
|
-
export type FlowEffectKind = "agent" | "tool"
|
|
5
|
+
import { FlowPause, type FlowDurableResult, type FlowFailure, type FlowInteraction } from "./types.js";
|
|
6
|
+
export type FlowEffectKind = "agent" | "tool";
|
|
7
7
|
export type FlowContext = {
|
|
8
8
|
readonly manifest: WorkflowManifest;
|
|
9
9
|
readonly checkpoint: FlowCheckpoint;
|
|
@@ -12,21 +12,25 @@ export type FlowContext = {
|
|
|
12
12
|
/** Operator ceilings (Map items / Loop iterations). */
|
|
13
13
|
readonly limits: FlowOperatorLimits;
|
|
14
14
|
readonly pending: Map<string, "pending" | "uncertain">;
|
|
15
|
+
/** Interactions tool nodes wait on, by interaction id. */
|
|
16
|
+
readonly interactions: Map<string, FlowInteraction>;
|
|
15
17
|
readonly inFlight: Set<Promise<unknown>>;
|
|
16
|
-
/** Nearest enclosing Chain `results`, outermost first. */
|
|
17
|
-
readonly resultsStack: Array<Record<string, JsonValue>>;
|
|
18
|
-
/** Enclosing Loop iteration numbers, outermost first. */
|
|
19
|
-
iterations: number[];
|
|
20
18
|
/** Effect ids the engine wants cancelled after fail-fast. */
|
|
21
19
|
readonly cancelEffectIds: Set<string>;
|
|
22
20
|
effect(kind: FlowEffectKind, input: unknown, identity: {
|
|
23
21
|
path: string;
|
|
24
22
|
key: string;
|
|
25
|
-
iterations
|
|
23
|
+
iterations: string;
|
|
26
24
|
role?: string;
|
|
27
25
|
}, context?: Record<string, unknown>): Promise<unknown>;
|
|
28
|
-
|
|
29
|
-
|
|
26
|
+
/** The id `effect` gives an effect of `kind` at `identity`. */
|
|
27
|
+
effectIdOf(kind: FlowEffectKind, identity: {
|
|
28
|
+
path: string;
|
|
29
|
+
iterations: string;
|
|
30
|
+
role?: string;
|
|
31
|
+
}): string;
|
|
32
|
+
/** Records an interaction a tool node waits on; throw what it returns. */
|
|
33
|
+
pause(interaction: FlowInteraction): FlowPause;
|
|
30
34
|
};
|
|
31
35
|
export declare function createFlowContext(options: {
|
|
32
36
|
readonly manifest: WorkflowManifest;
|
|
@@ -35,6 +39,11 @@ export declare function createFlowContext(options: {
|
|
|
35
39
|
readonly signal?: AbortSignal;
|
|
36
40
|
readonly limits?: Partial<FlowOperatorLimits> | null;
|
|
37
41
|
}): FlowContext;
|
|
42
|
+
/**
|
|
43
|
+
* The result of a flow that unwound on a suspension: waiting (or uncertain) while any effect is
|
|
44
|
+
* pending, otherwise paused on the interactions its tool nodes wait on.
|
|
45
|
+
*/
|
|
46
|
+
export declare function suspendedResult(ctx: FlowContext): FlowDurableResult;
|
|
38
47
|
export declare function markFailFastCancels(ctx: FlowContext): void;
|
|
39
48
|
export declare function settleInFlight(ctx: FlowContext): Promise<void>;
|
|
40
49
|
export declare function failureOf(error: unknown, fallbackPath?: string): FlowFailure;
|
package/dist/flow/context.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { HostSuspension } from "../loop/host-suspension.js";
|
|
2
2
|
import { resolveOperatorLimits } from "./limits.js";
|
|
3
|
-
import { flowEffectId,
|
|
4
|
-
import { failedValueOf, FlowNodeError } from "./types.js";
|
|
3
|
+
import { flowEffectId, nodeKeyOf } from "./paths.js";
|
|
4
|
+
import { failedValueOf, FlowNodeError, FlowPause, } from "./types.js";
|
|
5
5
|
export function createFlowContext(options) {
|
|
6
6
|
const pending = new Map();
|
|
7
|
+
const interactions = new Map();
|
|
7
8
|
const inFlight = new Set();
|
|
8
9
|
const cancelEffectIds = new Set();
|
|
9
|
-
const resultsStack = [];
|
|
10
10
|
const ctx = {
|
|
11
11
|
manifest: options.manifest,
|
|
12
12
|
checkpoint: options.checkpoint,
|
|
@@ -14,29 +14,29 @@ export function createFlowContext(options) {
|
|
|
14
14
|
signal: options.signal,
|
|
15
15
|
limits: resolveOperatorLimits(options.limits),
|
|
16
16
|
pending,
|
|
17
|
+
interactions,
|
|
17
18
|
inFlight,
|
|
18
|
-
resultsStack,
|
|
19
|
-
iterations: [],
|
|
20
19
|
cancelEffectIds,
|
|
21
|
-
|
|
22
|
-
return
|
|
23
|
-
},
|
|
24
|
-
iterationsString() {
|
|
25
|
-
return iterationsOf(ctx.iterations);
|
|
26
|
-
},
|
|
27
|
-
async effect(kind, input, identity, context = {}) {
|
|
28
|
-
if (options.signal?.aborted)
|
|
29
|
-
throw new FlowNodeError({ code: "cancelled", message: "cancelled" });
|
|
30
|
-
const iterations = identity.iterations ?? ctx.iterationsString();
|
|
31
|
-
const key = identity.key || nodeKeyOf(identity.path);
|
|
32
|
-
const effectId = flowEffectId({
|
|
20
|
+
effectIdOf(kind, identity) {
|
|
21
|
+
return flowEffectId({
|
|
33
22
|
turnId: options.checkpoint.turnId,
|
|
34
23
|
segment: options.checkpoint.segment,
|
|
35
24
|
path: identity.path,
|
|
36
25
|
kind,
|
|
37
|
-
iterations,
|
|
26
|
+
iterations: identity.iterations,
|
|
38
27
|
...(identity.role === undefined ? {} : { role: identity.role }),
|
|
39
28
|
});
|
|
29
|
+
},
|
|
30
|
+
pause(interaction) {
|
|
31
|
+
interactions.set(interaction.interaction.id, interaction);
|
|
32
|
+
return new FlowPause(interaction);
|
|
33
|
+
},
|
|
34
|
+
async effect(kind, input, identity, context = {}) {
|
|
35
|
+
if (options.signal?.aborted)
|
|
36
|
+
throw new FlowNodeError({ code: "cancelled", message: "cancelled" });
|
|
37
|
+
const { iterations } = identity;
|
|
38
|
+
const key = identity.key || nodeKeyOf(identity.path);
|
|
39
|
+
const effectId = ctx.effectIdOf(kind, identity);
|
|
40
40
|
if (cancelEffectIds.has(effectId))
|
|
41
41
|
throw new FlowNodeError({
|
|
42
42
|
code: "cancelled",
|
|
@@ -81,6 +81,22 @@ export function createFlowContext(options) {
|
|
|
81
81
|
};
|
|
82
82
|
return ctx;
|
|
83
83
|
}
|
|
84
|
+
/**
|
|
85
|
+
* The result of a flow that unwound on a suspension: waiting (or uncertain) while any effect is
|
|
86
|
+
* pending, otherwise paused on the interactions its tool nodes wait on.
|
|
87
|
+
*/
|
|
88
|
+
export function suspendedResult(ctx) {
|
|
89
|
+
const { checkpoint } = ctx;
|
|
90
|
+
if (ctx.pending.size === 0 && ctx.interactions.size > 0) {
|
|
91
|
+
const pending = [...ctx.interactions.values()];
|
|
92
|
+
return { status: "paused", checkpoint, result: { status: "paused", pending } };
|
|
93
|
+
}
|
|
94
|
+
return {
|
|
95
|
+
status: [...ctx.pending.values()].includes("uncertain") ? "uncertain" : "waiting",
|
|
96
|
+
checkpoint,
|
|
97
|
+
effectIds: [...ctx.pending.keys()],
|
|
98
|
+
};
|
|
99
|
+
}
|
|
84
100
|
export function markFailFastCancels(ctx) {
|
|
85
101
|
for (const effectId of ctx.pending.keys())
|
|
86
102
|
ctx.cancelEffectIds.add(effectId);
|
|
@@ -96,6 +112,6 @@ export function failureOf(error, fallbackPath) {
|
|
|
96
112
|
};
|
|
97
113
|
}
|
|
98
114
|
if (error instanceof Error && error.message)
|
|
99
|
-
return { code: "
|
|
100
|
-
return { code: "
|
|
115
|
+
return { code: "flow.failed", message: error.message, path: fallbackPath };
|
|
116
|
+
return { code: "flow.failed", message: String(error), path: fallbackPath };
|
|
101
117
|
}
|
package/dist/flow/engine.d.ts
CHANGED
|
@@ -1,13 +1,31 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Flow engine for workflow manifest v3 (`flow-3`). A flow is data: every value a stage sees
|
|
3
|
+
* comes from the flow's input and the outputs of the agents and tools before it. Returns
|
|
4
|
+
* effects only (SD-I1).
|
|
5
|
+
*
|
|
6
|
+
* - The first stage gets the flow's input; every later stage gets the previous output.
|
|
7
|
+
* - A Switch reads the previous output: a string is the case name, and so is an object's
|
|
8
|
+
* `route` field. The chosen case gets the whole output.
|
|
9
|
+
* - A Map runs over the previous output when it is an array, or over its `items` array.
|
|
10
|
+
* - A Parallel gives every branch the same input; its output is keyed by branch.
|
|
11
|
+
* - A Loop runs its body, asks its verifier for a verdict, and stops on a pass or retries with
|
|
12
|
+
* the feedback, up to `max` attempts. The body keeps its session. A verifier agent gets
|
|
13
|
+
* `{ task, response, iteration }`; an HTTP verifier `{ input, output, iteration }`. A body
|
|
14
|
+
* that starts with an HTTP stage, which takes an object, is retried with the Loop's input.
|
|
15
|
+
* - An HTTP stage (a tool node with `http`) checks its input against its input schema, then
|
|
16
|
+
* runs as a `tool` effect the host makes through its Tool Gate. A failed request fails the
|
|
17
|
+
* stage with its code (`http.status`, `http.timeout`, `tool.invalid-output`, …).
|
|
18
|
+
* - Agent and tool sessions are named by leaf paths: the leaf's id, `[i]` per Map item,
|
|
19
|
+
* under nested flow agents' ids. Control stages add nothing.
|
|
20
|
+
* - Leaf agents come from the manifest's embedded `agents`; nested flow agents run inline
|
|
21
|
+
* with their own input. An agent effect carries its flow agent's input as `flowInput`
|
|
22
|
+
* when the stage's own input differs, so the host can show the agent the original request.
|
|
23
|
+
*/
|
|
24
|
+
import { type WorkflowManifest } from "@nylorun/core/define";
|
|
2
25
|
import type { DurableHost } from "../run/durable.js";
|
|
3
26
|
import type { FlowCheckpoint } from "./checkpoint.js";
|
|
4
|
-
import type
|
|
27
|
+
import { type FlowOperatorLimits } from "./limits.js";
|
|
5
28
|
import { type FlowDurableResult } from "./types.js";
|
|
6
|
-
/**
|
|
7
|
-
* Deterministic flow interpreter for workflow manifests. v2 manifests run on the
|
|
8
|
-
* `flow-2` engine (`./v2.ts`); v1 manifests on `flow-1`, one module per primitive.
|
|
9
|
-
* Returns effects only (SD-I1).
|
|
10
|
-
*/
|
|
11
29
|
export declare function runFlowDurable(options: {
|
|
12
30
|
manifest: WorkflowManifest;
|
|
13
31
|
checkpoint: FlowCheckpoint;
|
package/dist/flow/engine.js
CHANGED
|
@@ -1,61 +1,327 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Flow engine for workflow manifest v3 (`flow-3`). A flow is data: every value a stage sees
|
|
3
|
+
* comes from the flow's input and the outputs of the agents and tools before it. Returns
|
|
4
|
+
* effects only (SD-I1).
|
|
5
|
+
*
|
|
6
|
+
* - The first stage gets the flow's input; every later stage gets the previous output.
|
|
7
|
+
* - A Switch reads the previous output: a string is the case name, and so is an object's
|
|
8
|
+
* `route` field. The chosen case gets the whole output.
|
|
9
|
+
* - A Map runs over the previous output when it is an array, or over its `items` array.
|
|
10
|
+
* - A Parallel gives every branch the same input; its output is keyed by branch.
|
|
11
|
+
* - A Loop runs its body, asks its verifier for a verdict, and stops on a pass or retries with
|
|
12
|
+
* the feedback, up to `max` attempts. The body keeps its session. A verifier agent gets
|
|
13
|
+
* `{ task, response, iteration }`; an HTTP verifier `{ input, output, iteration }`. A body
|
|
14
|
+
* that starts with an HTTP stage, which takes an object, is retried with the Loop's input.
|
|
15
|
+
* - An HTTP stage (a tool node with `http`) checks its input against its input schema, then
|
|
16
|
+
* runs as a `tool` effect the host makes through its Tool Gate. A failed request fails the
|
|
17
|
+
* stage with its code (`http.status`, `http.timeout`, `tool.invalid-output`, …).
|
|
18
|
+
* - Agent and tool sessions are named by leaf paths: the leaf's id, `[i]` per Map item,
|
|
19
|
+
* under nested flow agents' ids. Control stages add nothing.
|
|
20
|
+
* - Leaf agents come from the manifest's embedded `agents`; nested flow agents run inline
|
|
21
|
+
* with their own input. An agent effect carries its flow agent's input as `flowInput`
|
|
22
|
+
* when the stage's own input differs, so the host can show the agent the original request.
|
|
23
|
+
*/
|
|
24
|
+
import { HarnessError, ROOT_POSITION, canonical, childPosition, hashManifest, indexSuffix, isVerdict, isWorkflowManifest, leafPart, leafPath, schemaFromJSON, stageKey, } from "@nylorun/core/define";
|
|
2
25
|
import { WorkflowManifestSchema } from "@nylorun/core/contracts";
|
|
3
|
-
import { hashManifest } from "@nylorun/core/define";
|
|
4
26
|
import { HostSuspension } from "../loop/host-suspension.js";
|
|
5
|
-
import { CHECKPOINT_VERSION,
|
|
6
|
-
import { createFlowContext, failureOf, settleInFlight } from "./context.js";
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
27
|
+
import { CHECKPOINT_VERSION, FLOW_ENGINE_VERSION } from "../compatibility.js";
|
|
28
|
+
import { createFlowContext, failureOf, markFailFastCancels, settleInFlight, suspendedResult, } from "./context.js";
|
|
29
|
+
import { assertLoopIteration, assertMapItemCount } from "./limits.js";
|
|
30
|
+
import { iterationsOf } from "./paths.js";
|
|
31
|
+
import { runToolEffect } from "./tool.js";
|
|
10
32
|
import { FlowNodeError } from "./types.js";
|
|
11
|
-
/**
|
|
12
|
-
* Deterministic flow interpreter for workflow manifests. v2 manifests run on the
|
|
13
|
-
* `flow-2` engine (`./v2.ts`); v1 manifests on `flow-1`, one module per primitive.
|
|
14
|
-
* Returns effects only (SD-I1).
|
|
15
|
-
*/
|
|
16
33
|
export async function runFlowDurable(options) {
|
|
17
|
-
const { manifest, checkpoint,
|
|
34
|
+
const { manifest, checkpoint, signal } = options;
|
|
18
35
|
WorkflowManifestSchema.parse(manifest);
|
|
19
36
|
if (checkpoint.version !== CHECKPOINT_VERSION ||
|
|
20
|
-
checkpoint.engineVersion !==
|
|
37
|
+
checkpoint.engineVersion !== FLOW_ENGINE_VERSION ||
|
|
21
38
|
checkpoint.manifestHash !== hashManifest(manifest))
|
|
22
39
|
throw new HarnessError("execution.incompatible", "Incompatible flow checkpoint");
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
40
|
+
const ctx = createFlowContext(options);
|
|
41
|
+
const scope = {
|
|
42
|
+
manifest,
|
|
43
|
+
flow: [],
|
|
44
|
+
pathPrefix: "",
|
|
45
|
+
keyPrefix: "",
|
|
46
|
+
pending: [],
|
|
47
|
+
indices: [],
|
|
48
|
+
iterations: [],
|
|
49
|
+
flowInput: checkpoint.input,
|
|
50
|
+
};
|
|
32
51
|
try {
|
|
33
52
|
if (signal?.aborted)
|
|
34
53
|
return { status: "cancelled", checkpoint, result: { status: "cancelled" } };
|
|
35
|
-
const output = await runNode(ctx, root,
|
|
36
|
-
return {
|
|
37
|
-
status: "completed",
|
|
38
|
-
checkpoint,
|
|
39
|
-
result: { status: "completed", output },
|
|
40
|
-
};
|
|
54
|
+
const output = await runNode(ctx, scope, manifest.root, ROOT_POSITION, checkpoint.input);
|
|
55
|
+
return { status: "completed", checkpoint, result: { status: "completed", output } };
|
|
41
56
|
}
|
|
42
57
|
catch (error) {
|
|
43
58
|
await settleInFlight(ctx);
|
|
44
|
-
if (error instanceof HostSuspension)
|
|
45
|
-
return
|
|
46
|
-
status: [...ctx.pending.values()].includes("uncertain") ? "uncertain" : "waiting",
|
|
47
|
-
checkpoint,
|
|
48
|
-
effectIds: [...ctx.pending.keys()],
|
|
49
|
-
};
|
|
50
|
-
}
|
|
59
|
+
if (error instanceof HostSuspension)
|
|
60
|
+
return suspendedResult(ctx);
|
|
51
61
|
if (error instanceof FlowNodeError && error.failure.code === "cancelled")
|
|
52
62
|
return { status: "cancelled", checkpoint, result: { status: "cancelled" } };
|
|
53
|
-
const failure = failureOf(error, rootPath);
|
|
54
63
|
return {
|
|
55
64
|
status: "failed",
|
|
56
65
|
checkpoint,
|
|
57
|
-
result: { status: "failed", error:
|
|
66
|
+
result: { status: "failed", error: failureOf(error, manifest.id) },
|
|
58
67
|
...(ctx.cancelEffectIds.size > 0 ? { cancelEffectIds: [...ctx.cancelEffectIds] } : {}),
|
|
59
68
|
};
|
|
60
69
|
}
|
|
61
70
|
}
|
|
71
|
+
/** Where a node's effects are recorded: a leaf's path, or its stage key plus Map indices. */
|
|
72
|
+
function siteOf(scope, node, key) {
|
|
73
|
+
const part = leafPart(node);
|
|
74
|
+
return part === undefined
|
|
75
|
+
? `${key}${indexSuffix(scope.indices)}`
|
|
76
|
+
: leafPath(scope.pathPrefix, part, scope.pending);
|
|
77
|
+
}
|
|
78
|
+
async function runNode(ctx, scope, node, position, input, context = {}) {
|
|
79
|
+
const key = stageKey(node, position, scope.keyPrefix);
|
|
80
|
+
const site = siteOf(scope, node, key);
|
|
81
|
+
if ("agent" in node)
|
|
82
|
+
return runAgent(ctx, scope, node, key, site, input, context);
|
|
83
|
+
if ("tool" in node)
|
|
84
|
+
return runTool(ctx, scope, node.tool, key, site, input);
|
|
85
|
+
if ("chain" in node)
|
|
86
|
+
return runChain(ctx, scope, node.chain, position, input);
|
|
87
|
+
if ("switch" in node)
|
|
88
|
+
return runSwitch(ctx, scope, node.switch, site, position, input);
|
|
89
|
+
if ("parallel" in node)
|
|
90
|
+
return runParallel(ctx, scope, node.parallel, site, position, input);
|
|
91
|
+
if ("map" in node)
|
|
92
|
+
return runMap(ctx, scope, node.map.each, site, position, input);
|
|
93
|
+
if ("loop" in node)
|
|
94
|
+
return runLoop(ctx, scope, node.loop, site, position, input);
|
|
95
|
+
throw new HarnessError("execution.invalid-state", "Unknown workflow node kind");
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* An agent node: a leaf agent runs as one turn in its own session; a nested flow agent
|
|
99
|
+
* runs inline, under its own id, with its own input.
|
|
100
|
+
*/
|
|
101
|
+
async function runAgent(ctx, scope, node, key, site, input, context) {
|
|
102
|
+
const target = scope.manifest.agents[node.agent];
|
|
103
|
+
if (target === undefined)
|
|
104
|
+
throw new FlowNodeError({
|
|
105
|
+
code: "flow.unknown-agent",
|
|
106
|
+
message: `Agent '${node.agent}' is not embedded in flow agent '${scope.manifest.id}'`,
|
|
107
|
+
path: site,
|
|
108
|
+
});
|
|
109
|
+
if (isWorkflowManifest(target)) {
|
|
110
|
+
const flow = target;
|
|
111
|
+
const nested = {
|
|
112
|
+
manifest: flow,
|
|
113
|
+
flow: [...scope.flow, node.agent],
|
|
114
|
+
pathPrefix: site,
|
|
115
|
+
keyPrefix: key,
|
|
116
|
+
pending: [],
|
|
117
|
+
indices: scope.indices,
|
|
118
|
+
iterations: scope.iterations,
|
|
119
|
+
flowInput: input,
|
|
120
|
+
};
|
|
121
|
+
return runNode(ctx, nested, flow.root, ROOT_POSITION, input);
|
|
122
|
+
}
|
|
123
|
+
return (await ctx.effect("agent", {
|
|
124
|
+
agentId: node.agent,
|
|
125
|
+
input,
|
|
126
|
+
path: site,
|
|
127
|
+
...(scope.flow.length > 0 ? { flow: scope.flow } : {}),
|
|
128
|
+
...(canonical(input) === canonical(scope.flowInput) ? {} : { flowInput: scope.flowInput }),
|
|
129
|
+
}, { path: site, key, iterations: iterationsOf(scope.iterations) }, context));
|
|
130
|
+
}
|
|
131
|
+
async function runTool(ctx, scope, tool, key, site, input) {
|
|
132
|
+
if (tool.http && tool.inputSchema) {
|
|
133
|
+
const checked = schemaFromJSON(tool.inputSchema).validate(input);
|
|
134
|
+
if (!checked.ok)
|
|
135
|
+
throw new FlowNodeError({
|
|
136
|
+
code: "tool.invalid-input",
|
|
137
|
+
message: `HTTP stage '${tool.name}' got ${describe(input)}, which does not match its input schema: ${checked.issues.map((issue) => issue.message).join("; ")}`,
|
|
138
|
+
path: site,
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
const value = await runToolEffect(ctx, tool.name, input, {
|
|
142
|
+
path: site,
|
|
143
|
+
key,
|
|
144
|
+
iterations: iterationsOf(scope.iterations),
|
|
145
|
+
});
|
|
146
|
+
return completedOutput(value, site);
|
|
147
|
+
}
|
|
148
|
+
/** The output of a settled tool outcome: `{ kind: "completed", output }`, or the value itself. */
|
|
149
|
+
function completedOutput(value, site) {
|
|
150
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
151
|
+
return value;
|
|
152
|
+
const outcome = value;
|
|
153
|
+
if (outcome.kind === "completed" && "output" in outcome)
|
|
154
|
+
return outcome.output ?? null;
|
|
155
|
+
if (outcome.kind === "denied")
|
|
156
|
+
throw new FlowNodeError({
|
|
157
|
+
code: "tool.denied",
|
|
158
|
+
message: typeof outcome.reason === "string" ? outcome.reason : "Tool call denied",
|
|
159
|
+
path: site,
|
|
160
|
+
});
|
|
161
|
+
return value;
|
|
162
|
+
}
|
|
163
|
+
/** Steps in order; each step's output is the next one's input. */
|
|
164
|
+
async function runChain(ctx, scope, steps, position, input) {
|
|
165
|
+
let current = input;
|
|
166
|
+
for (const [index, step] of steps.entries())
|
|
167
|
+
current = await runNode(ctx, scope, step, childPosition(position, index), current);
|
|
168
|
+
return current;
|
|
169
|
+
}
|
|
170
|
+
function isRecord(value) {
|
|
171
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
172
|
+
}
|
|
173
|
+
/** A short description of a value for a failure message. */
|
|
174
|
+
function describe(value) {
|
|
175
|
+
const text = JSON.stringify(value) ?? String(value);
|
|
176
|
+
return text.length > 80 ? `${text.slice(0, 77)}...` : text;
|
|
177
|
+
}
|
|
178
|
+
/** The case the previous output names: itself when a string, else its `route` field. */
|
|
179
|
+
async function runSwitch(ctx, scope, node, site, position, input) {
|
|
180
|
+
const name = typeof input === "string"
|
|
181
|
+
? input
|
|
182
|
+
: isRecord(input) && typeof input.route === "string"
|
|
183
|
+
? input.route
|
|
184
|
+
: undefined;
|
|
185
|
+
const chosen = name === undefined ? undefined : node.cases[name];
|
|
186
|
+
if (chosen)
|
|
187
|
+
return runNode(ctx, scope, chosen, childPosition(position, name), input);
|
|
188
|
+
if (node.default)
|
|
189
|
+
return runNode(ctx, scope, node.default, childPosition(position, "default"), input);
|
|
190
|
+
throw new FlowNodeError({
|
|
191
|
+
code: "switch.no-match",
|
|
192
|
+
message: name === undefined
|
|
193
|
+
? `Switch read ${describe(input)}, which names no case: the previous output must be a case name or an object with a string route field, and there is no default case`
|
|
194
|
+
: `Switch read the case name ${JSON.stringify(name)}, but no case has that name (cases: ${Object.keys(node.cases).join(", ")}) and there is no default case`,
|
|
195
|
+
path: site,
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
/** Run `tasks` together; fail fast on the first failure in declaration order. */
|
|
199
|
+
async function runTogether(ctx, tasks, pathOf) {
|
|
200
|
+
const outputs = new Array(tasks.length);
|
|
201
|
+
const suspensions = [];
|
|
202
|
+
const failures = [];
|
|
203
|
+
await Promise.all(tasks.map(async (task, index) => {
|
|
204
|
+
try {
|
|
205
|
+
outputs[index] = await task();
|
|
206
|
+
}
|
|
207
|
+
catch (error) {
|
|
208
|
+
if (error instanceof HostSuspension) {
|
|
209
|
+
suspensions.push(error);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
failures.push({
|
|
213
|
+
index,
|
|
214
|
+
error: error instanceof FlowNodeError
|
|
215
|
+
? error
|
|
216
|
+
: new FlowNodeError(failureOf(error, pathOf(index))),
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
}));
|
|
220
|
+
if (failures.length > 0) {
|
|
221
|
+
markFailFastCancels(ctx);
|
|
222
|
+
failures.sort((a, b) => a.index - b.index);
|
|
223
|
+
throw failures[0].error;
|
|
224
|
+
}
|
|
225
|
+
if (suspensions.length > 0)
|
|
226
|
+
throw suspensions[0];
|
|
227
|
+
return outputs;
|
|
228
|
+
}
|
|
229
|
+
/** Every branch gets the same input; the output is keyed by branch, in declaration order. */
|
|
230
|
+
async function runParallel(ctx, scope, branches, site, position, input) {
|
|
231
|
+
const names = Object.keys(branches);
|
|
232
|
+
const outputs = await runTogether(ctx, names.map((name) => () => runNode(ctx, scope, branches[name], childPosition(position, name), input)), () => site);
|
|
233
|
+
const result = {};
|
|
234
|
+
names.forEach((name, index) => {
|
|
235
|
+
result[name] = outputs[index];
|
|
236
|
+
});
|
|
237
|
+
return result;
|
|
238
|
+
}
|
|
239
|
+
/** Runs `each` once per item of the previous output, or of its `items`; output in item order. */
|
|
240
|
+
async function runMap(ctx, scope, each, site, position, input) {
|
|
241
|
+
const items = Array.isArray(input)
|
|
242
|
+
? input
|
|
243
|
+
: isRecord(input) && Array.isArray(input.items)
|
|
244
|
+
? input.items
|
|
245
|
+
: undefined;
|
|
246
|
+
if (!items)
|
|
247
|
+
throw new FlowNodeError({
|
|
248
|
+
code: "map.not-a-list",
|
|
249
|
+
message: `A Map runs over an array or { items: [...] }; got ${describe(input)}`,
|
|
250
|
+
path: site,
|
|
251
|
+
});
|
|
252
|
+
assertMapItemCount(items.length, ctx.limits, site);
|
|
253
|
+
if (items.length === 0)
|
|
254
|
+
return [];
|
|
255
|
+
const eachPosition = childPosition(position, "each");
|
|
256
|
+
return runTogether(ctx, items.map((item, index) => () => runNode(ctx, { ...scope, pending: [...scope.pending, index], indices: [...scope.indices, index] }, each, eachPosition, item)), (index) => `${site}[${index}]`);
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Run the body, ask the verifier agent, then stop on a pass or retry with the feedback. The
|
|
260
|
+
* body keeps its session across attempts; the verifier gets a fresh one per attempt.
|
|
261
|
+
*/
|
|
262
|
+
async function runLoop(ctx, scope, loop, site, position, input) {
|
|
263
|
+
const runPosition = childPosition(position, "run");
|
|
264
|
+
let current = input;
|
|
265
|
+
for (let iteration = 1;; iteration += 1) {
|
|
266
|
+
if (ctx.signal?.aborted)
|
|
267
|
+
throw new FlowNodeError({ code: "cancelled", message: "cancelled", path: site });
|
|
268
|
+
assertLoopIteration(iteration, ctx.limits, site);
|
|
269
|
+
const turn = { ...scope, iterations: [...scope.iterations, iteration] };
|
|
270
|
+
const loopContext = { loopPath: site, n: iteration };
|
|
271
|
+
const output = await runNode(ctx, turn, loop.run, runPosition, current, loopContext);
|
|
272
|
+
const verdict = await runVerify(ctx, turn, loop.verify, site, position, {
|
|
273
|
+
task: input,
|
|
274
|
+
response: output,
|
|
275
|
+
iteration,
|
|
276
|
+
context: loopContext,
|
|
277
|
+
});
|
|
278
|
+
if (verdict.pass)
|
|
279
|
+
return output;
|
|
280
|
+
if (iteration >= loop.max)
|
|
281
|
+
throw new FlowNodeError({
|
|
282
|
+
code: "loop.exhausted",
|
|
283
|
+
message: `Loop stopped after ${loop.max} attempt${loop.max === 1 ? "" : "s"}: ${verdict.feedback}`,
|
|
284
|
+
path: site,
|
|
285
|
+
});
|
|
286
|
+
current = startsWithHttpStage(loop.run) ? input : verdict.feedback;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
/** True when `node`'s first stage is an HTTP stage: it takes an object, never feedback text. */
|
|
290
|
+
function startsWithHttpStage(node) {
|
|
291
|
+
if ("chain" in node)
|
|
292
|
+
return node.chain.length > 0 && startsWithHttpStage(node.chain[0]);
|
|
293
|
+
return "tool" in node && node.tool.http !== undefined;
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* A verifier agent judges `{ task, response, iteration }`, an HTTP verifier
|
|
297
|
+
* `{ input, output, iteration }`; the output must be a verdict.
|
|
298
|
+
*/
|
|
299
|
+
async function runVerify(ctx, scope, verify, site, position, args) {
|
|
300
|
+
const at = childPosition(position, "verify");
|
|
301
|
+
let value;
|
|
302
|
+
try {
|
|
303
|
+
if ("http" in verify) {
|
|
304
|
+
const key = stageKey(verify, at, scope.keyPrefix);
|
|
305
|
+
const path = siteOf(scope, verify, key);
|
|
306
|
+
const raw = (await ctx.effect("tool", { input: args.task, output: args.response, iteration: args.iteration }, { path, key, iterations: iterationsOf(scope.iterations) }, { ...args.context, role: "verify-http" }));
|
|
307
|
+
value = completedOutput(raw, path);
|
|
308
|
+
}
|
|
309
|
+
else
|
|
310
|
+
value = await runNode(ctx, scope, verify, at, { task: args.task, response: args.response, iteration: args.iteration }, { ...args.context, role: "verify-agent" });
|
|
311
|
+
}
|
|
312
|
+
catch (error) {
|
|
313
|
+
if (error instanceof HostSuspension)
|
|
314
|
+
throw error;
|
|
315
|
+
const failure = failureOf(error, site);
|
|
316
|
+
if (failure.code === "loop.verify-failed")
|
|
317
|
+
throw error;
|
|
318
|
+
throw new FlowNodeError({ code: "loop.verify-failed", message: failure.message, path: site });
|
|
319
|
+
}
|
|
320
|
+
if (!isVerdict(value))
|
|
321
|
+
throw new FlowNodeError({
|
|
322
|
+
code: "loop.verify-failed",
|
|
323
|
+
message: `The verifier must return { pass: boolean, feedback?: string }, with feedback when pass is false; got ${describe(value)}`,
|
|
324
|
+
path: site,
|
|
325
|
+
});
|
|
326
|
+
return value;
|
|
327
|
+
}
|