@nylorun/harness 0.19.2-beta → 0.20.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 +36 -0
- package/HOST_CONTRACT.md +2 -2
- package/dist/compatibility.d.ts +11 -2
- package/dist/compatibility.js +10 -2
- package/dist/flow/checkpoint.d.ts +2 -2
- package/dist/flow/checkpoint.js +2 -2
- package/dist/flow/context.d.ts +1 -0
- package/dist/flow/context.js +1 -0
- package/dist/flow/engine.d.ts +3 -2
- package/dist/flow/engine.js +8 -4
- package/dist/flow/loop.d.ts +4 -0
- package/dist/flow/loop.js +3 -1
- package/dist/flow/map.js +1 -1
- package/dist/flow/node.js +27 -4
- package/dist/flow/paths.d.ts +6 -1
- package/dist/flow/paths.js +7 -2
- package/dist/flow/v2.d.ts +12 -0
- package/dist/flow/v2.js +370 -0
- package/dist/loop/delegation.d.ts +6 -0
- package/dist/loop/delegation.js +36 -15
- package/dist/run/durable.js +6 -0
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,41 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.20.0-beta
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 5278b4e: **Flow agents on workflow manifest v2.** A flow agent compiles to `workflowSchemaVersion: 2` and runs on the new `flow-2` engine; v1 workflows (`Chain`, `Switch`, `Parallel`, `Map`, `Loop`) keep running on `flow-1`, so in-flight runs finish as they began.
|
|
8
|
+
|
|
9
|
+
- **Manifest (core).** Any node may carry `id` and `input`; there are no slots. `chain` and `parallel` are bare collections, a Map is `{ map: { each } }` over its input, and a Loop has `max?` and `decide?`. The header adds `name`, `description`, `metadata`, `inputSchema` and `outputSchema`, and `agents` embeds every agent the flow runs, so one manifest hash covers the whole flow. `Agent.from(json, { nodes, agents })` rebuilds a flow agent. Path and key helpers (`leafPath`, `stageKey`, `forEachFlowNode`, `embeddedAgent`, …) are exported from `@nylorun/core/define`.
|
|
10
|
+
- **Paths (harness).** Linked agent sessions are named by the agent: its id, `[i]` per Map item, and a nested flow agent's id in front. Control stages add nothing, so wrapping a step in a Loop keeps its session. Functions are bound under stage keys (`route:on`, `@1.default.1:input`) and all receive `{ input, results, flowInput }`; `flowInput` works inside nested `flow()`. A Loop without `decide` retries with the verifier's feedback up to `max` and then fails with `loop.exhausted`. Nested flow agents run inline.
|
|
11
|
+
- **Runtime.** Leaves of a v2 workflow resolve from its embedded `agents` (with the workflow's plugin roots, keyed `<agent>/<capability>`) instead of the registry. `loop.iteration` is emitted only for a Loop's own agent turns.
|
|
12
|
+
- **Agents SDK.** `saveAgent(flowAgent)` PUTs one document; application mode registers the flow's executor with its manifest hash. An executor leaves `fn`, `verify` and tool actions of a v2 flow unclaimed when they belong to another manifest hash, because stage keys can shift between deploys; it reports each skipped action once through `onError`.
|
|
13
|
+
- **Studio.** Draws v2 manifests: agents and tools at their session paths, control stages at their stage keys, nested flow agents inline, and lights a Map's agent from its item sessions.
|
|
14
|
+
- Build diagnostics: `flow.duplicate-leaf`, `flow.duplicate-id`, `flow.agent-conflict`, `flow.v1-workflow`, `loop.invalid-verify`, `workflow.flow-agent-child`. Also fixes v1 flows passing an agent step's output to the next step still wrapped in the runtime's turn marker.
|
|
15
|
+
|
|
16
|
+
- 426fd27: **Flow agents as subagents.** `.subagents(flowAgent)` lets a ReAct agent delegate to a flow agent. The flow's workflow manifest v2 is inlined in the delegating tool (`ToolManifest.agent` may be a workflow manifest), so it is saved with the parent and served by the parent's executor, plugin roots included (`<flow>/<agent>/<capability>`).
|
|
17
|
+
|
|
18
|
+
- **Engine (harness).** A call to a flow subagent is one durable `agent` effect (`role: "delegate"`) between the delegation's start and settle points; the flow's output is the tool result, and a failed flow is a failed tool result. Local `run()` refuses flow subagents, which need the Runtime.
|
|
19
|
+
- **Runtime.** The effect starts a linked flow session from the parent's pinned manifest, fresh per call, and settles when the flow's turn ends. Cancelling any session now cascades to the linked sessions it started, not only a workflow's.
|
|
20
|
+
- **Core.** `delegation.flow-unsupported` now only reports a workflow built with `Chain`, `Switch`, `Parallel`, `Map` or `Loop`. New helpers: `flowDelegatesOf`, `flowDelegateManifest`, `isFlowDelegate`; `delegatesOf` lists only the ReAct agents run in-process.
|
|
21
|
+
|
|
22
|
+
### Patch Changes
|
|
23
|
+
|
|
24
|
+
- 8cda500: **Workflow functions and tool steps reach the executor.** Several workflow nodes asked the executor for a key that core never registered, so the executor never found the function and the turn waited forever.
|
|
25
|
+
|
|
26
|
+
- A Map's `over` and a slot's `input` now use the keys core registers (`<path>/over`, `<path>/input`), as Switch's `on` already did.
|
|
27
|
+
- A slot `input` that wraps a Map or Switch gets its own effect id, so it no longer collides with the `over` or `on` effect on the same path.
|
|
28
|
+
- A slot `id` that renames a nested workflow now renames the keys inside it too.
|
|
29
|
+
- A verifier slot's `input` is keyed under the verifier's path (`<loop>/<part>/input`).
|
|
30
|
+
- A tool step passes its output to the next step, not the `{ kind: "completed", output }` outcome around it. A denied tool call fails the flow with `tool.denied`.
|
|
31
|
+
|
|
32
|
+
- Pin core to the tested release.
|
|
33
|
+
- Updated dependencies [e537a82]
|
|
34
|
+
- Updated dependencies [5278b4e]
|
|
35
|
+
- Updated dependencies [426fd27]
|
|
36
|
+
- Updated dependencies [8cda500]
|
|
37
|
+
- @nylorun/core@0.8.0-beta
|
|
38
|
+
|
|
3
39
|
## 0.19.2-beta
|
|
4
40
|
|
|
5
41
|
### Patch Changes
|
package/HOST_CONTRACT.md
CHANGED
|
@@ -37,9 +37,9 @@ A terminal/paused result includes `result.state`. Save it. A new message uses a
|
|
|
37
37
|
|
|
38
38
|
Host resolveEffect must bind the effect ID to the original request and reject drift. Intent/outcome, action transitions, checkpoint settlement and canonical event/outbox writes must use runtime transactions. Restate journals individual effect boundaries, not the loop. Scheduling, storage, publication, lease policy and reconciliation remain runtime-owned.
|
|
39
39
|
|
|
40
|
-
Agents used as tools: a manifest tool with an `agent` body (the child manifest inlined; name equals the child id, description equals the child description, input is the standard `{task}` schema, no outputSchema, no nested agent tools, identical sandbox specs across the tree) is run by the engine inside the parent's `runDurable`, never by an executor. Its model, tool and hook effects carry `agent: {id, path, delegationId}` (`delegationId` is the parent tool call's invocationId), keep the root `agentId` and `manifestHash`, and use identity `<delegationId>/<inner identity>`; tool context `idempotencyKey` is prefixed the same way. Hosts resolve child effects against the child manifest (`delegateManifest`) for pinned tool schemas, sandbox and MCP routing, copy `agent` onto the Action, and include it in action event payloads. A `delegation` effect (identity `<delegationId>:started` or `<delegationId>:settled`, input `{task}` or `{status, outcome}`) must be recorded completed immediately with value null and publish `delegation.started` / `delegation.completed` exactly once; the journal makes replays silent. `DurableSessionTool.agentId` attaches discovered MCP tools to a child; MCP snapshot records and diagnostics carry `agentId`, and child plugin roots are keyed `<childId>/<capabilityId>`. Children share the session sandbox. `GET /v1/sessions/:id/items?agent=` filters history by `payload.agent.delegationId` or `payload.agent.path`. Existing checkpoints are unaffected; engine version stays `hosted-2`.
|
|
40
|
+
Agents used as tools: a manifest tool with an `agent` body (the child manifest inlined; name equals the child id, description equals the child description, input is the standard `{task}` schema, no outputSchema, no nested agent tools, identical sandbox specs across the tree) is run by the engine inside the parent's `runDurable`, never by an executor. Its model, tool and hook effects carry `agent: {id, path, delegationId}` (`delegationId` is the parent tool call's invocationId), keep the root `agentId` and `manifestHash`, and use identity `<delegationId>/<inner identity>`; tool context `idempotencyKey` is prefixed the same way. Hosts resolve child effects against the child manifest (`delegateManifest`) for pinned tool schemas, sandbox and MCP routing, copy `agent` onto the Action, and include it in action event payloads. A `delegation` effect (identity `<delegationId>:started` or `<delegationId>:settled`, input `{task}` or `{status, outcome}`) must be recorded completed immediately with value null and publish `delegation.started` / `delegation.completed` exactly once; the journal makes replays silent. `DurableSessionTool.agentId` attaches discovered MCP tools to a child; MCP snapshot records and diagnostics carry `agentId`, and child plugin roots are keyed `<childId>/<capabilityId>`. Children share the session sandbox. `GET /v1/sessions/:id/items?agent=` filters history by `payload.agent.delegationId` or `payload.agent.path`. Existing checkpoints are unaffected; engine version stays `hosted-2`. A tool whose `agent` body is a flow agent (workflow manifest v2) is not run in-process: the engine issues one `agent` effect (identity `<delegationId>:flow`, input `{agentId, input: task, path}`, context `{role: "delegate", delegationId}`, `agent` ref set) between the `delegation` start and settle points. The host starts a linked flow session from the pinned parent manifest's inlined flow (session id `derive(parentSessionId, path, "delegate", delegationId)`, plugin roots under `<flowId>/`), sends the task as its message, and completes the effect with the flow's output, or `{kind: "failed", code, message}`, when its turn ends. Cancelling the parent cascades to linked sessions.
|
|
41
41
|
|
|
42
|
-
**Workflows (flow engine).** Definitions with `kind: "workflow"` run through `createFlowCheckpoint` / `runFlowDurable` from `/run` (same `DurableResult` shape as `runDurable`). The turn loop in `harness/src/loop/` is unchanged. Flow effects extend `HostEffect.kind` with `agent`, `tool` (workflow tool node), `fn`, and `verify`. Each carries `path` (node address), `key` (path without Map indices), and `iterations` (enclosing Loop vector as a dotted string, or `"-"` outside Loops). Effect ids are `${turnId}:${segment}:flow:${path}:${kind}:${iterations}`. The host resolves `agent` effects only through the public session contract (create linked session, message with derived idempotency key, settle on linked `turn.completed` / failed / cancelled). `tool`, `fn`, and `verify` become Actions claimed by the workflow executor; Actions use `path` + `key` instead of `capabilityId` + `toolName`. `fn` and `verify` are pure or repeat-safe: on lease expiry they return to pending and are offered again; tool nodes become `uncertain` and are never re-run automatically. Parallelism comes from pending effects returned together; the Runtime caps concurrency with `RuntimeOptions.flow` / env (`maxConcurrency`, `maxMapItems`, `maxLoopIterations`).
|
|
42
|
+
**Workflows (flow engine).** Definitions with `kind: "workflow"` run through `createFlowCheckpoint` / `runFlowDurable` from `/run` (same `DurableResult` shape as `runDurable`). The turn loop in `harness/src/loop/` is unchanged. Flow effects extend `HostEffect.kind` with `agent`, `tool` (workflow tool node), `fn`, and `verify`. Each carries `path` (node address), `key` (path without Map indices), and `iterations` (enclosing Loop vector as a dotted string, or `"-"` outside Loops). Effect ids are `${turnId}:${segment}:flow:${path}:${kind}:${iterations}`. On workflow manifest v2 (engine `flow-2`), an `agent` or `tool` effect's `path` is the leaf path (the leaf's id, `[i]` per Map item, nested flow agent ids in front) and its `key` drops the indices; an `fn` or `verify` effect's `key` is the stage key plus `:input`, `:on`, `:verify` or `:decide`, and its `path` is the stage's site plus the same suffix. v2 `agent` effect input adds `flow` (nested flow agent ids, outermost first); the host resolves the leaf from the workflow manifest's embedded `agents` (`embeddedAgent`) and gives the linked session the leaf's manifest, its hash, and the workflow's plugin roots under `<agentId>/`. Checkpoints pin the engine: v1 manifests run on `flow-1`, v2 on `flow-2`. An executor refuses v2 flow actions whose `manifestHash` is not the manifest it serves. The host resolves `agent` effects only through the public session contract (create linked session, message with derived idempotency key, settle on linked `turn.completed` / failed / cancelled). `tool`, `fn`, and `verify` become Actions claimed by the workflow executor; Actions use `path` + `key` instead of `capabilityId` + `toolName`. `fn` and `verify` are pure or repeat-safe: on lease expiry they return to pending and are offered again; tool nodes become `uncertain` and are never re-run automatically. Parallelism comes from pending effects returned together; the Runtime caps concurrency with `RuntimeOptions.flow` / env (`maxConcurrency`, `maxMapItems`, `maxLoopIterations`).
|
|
43
43
|
|
|
44
44
|
**Turn manifests.** A `message` command may include optional `manifest`. Any app may use it (not only Loops). When present, the Runtime parses it with `AgentManifestSchema`, requires it to be a **variant** of the session's pinned manifest (id fixed; tools/skills/delegates may only shrink; hooks, MCP, and sandbox must not change), hashes and stores it by hash for that turn only (it does not latch — a later message without `manifest` uses the pin), and rebases `state.manifestHash` at turn start when the prior state hash and the turn hash are both the pin or validated variants of it. Invalid variants fail closed (`loop.invalid-agent` when a Loop decide supplies one).
|
|
45
45
|
|
package/dist/compatibility.d.ts
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
export { checkCompatibility } from "./definition/compatibility.js";
|
|
2
2
|
export declare const CHECKPOINT_VERSION = 1;
|
|
3
3
|
export declare const ENGINE_VERSION = "hosted-2";
|
|
4
|
-
/**
|
|
5
|
-
|
|
4
|
+
/**
|
|
5
|
+
* Flow engine version pinned on workflow checkpoints. Workflow manifest v2 runs on
|
|
6
|
+
* `flow-2`; v1 manifests keep running on `flow-1`, so in-flight v1 runs finish as they began.
|
|
7
|
+
*/
|
|
8
|
+
export declare const FLOW_ENGINE_VERSION = "flow-2";
|
|
9
|
+
export declare const FLOW_ENGINE_VERSION_V1 = "flow-1";
|
|
10
|
+
export type FlowEngineVersion = typeof FLOW_ENGINE_VERSION | typeof FLOW_ENGINE_VERSION_V1;
|
|
11
|
+
/** The engine a workflow manifest runs on. */
|
|
12
|
+
export declare function flowEngineVersionOf(manifest: {
|
|
13
|
+
readonly workflowSchemaVersion: number;
|
|
14
|
+
}): FlowEngineVersion;
|
package/dist/compatibility.js
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
export { checkCompatibility } from "./definition/compatibility.js";
|
|
2
2
|
export const CHECKPOINT_VERSION = 1;
|
|
3
3
|
export const ENGINE_VERSION = "hosted-2";
|
|
4
|
-
/**
|
|
5
|
-
|
|
4
|
+
/**
|
|
5
|
+
* Flow engine version pinned on workflow checkpoints. Workflow manifest v2 runs on
|
|
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
|
+
}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import type { JsonValue } from "@nylorun/core/define";
|
|
2
2
|
import { type WorkflowManifest } from "@nylorun/core/contracts";
|
|
3
|
-
import {
|
|
3
|
+
import { type FlowEngineVersion } from "../compatibility.js";
|
|
4
4
|
/** Private persistence contract for workflow sessions; not a session wire type. */
|
|
5
5
|
export interface FlowCheckpoint {
|
|
6
6
|
readonly version: 1;
|
|
7
|
-
readonly engineVersion:
|
|
7
|
+
readonly engineVersion: FlowEngineVersion;
|
|
8
8
|
readonly manifestHash: string;
|
|
9
9
|
readonly sessionId: string;
|
|
10
10
|
readonly turnId: string;
|
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, flowEngineVersionOf, } 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: flowEngineVersionOf(input.manifest),
|
|
9
9
|
manifestHash: hashManifest(input.manifest),
|
|
10
10
|
sessionId: input.sessionId,
|
|
11
11
|
turnId: input.turnId,
|
package/dist/flow/context.d.ts
CHANGED
package/dist/flow/context.js
CHANGED
package/dist/flow/engine.d.ts
CHANGED
|
@@ -4,8 +4,9 @@ import type { FlowCheckpoint } from "./checkpoint.js";
|
|
|
4
4
|
import type { FlowOperatorLimits } from "./limits.js";
|
|
5
5
|
import { type FlowDurableResult } from "./types.js";
|
|
6
6
|
/**
|
|
7
|
-
* Deterministic flow interpreter for workflow manifests.
|
|
8
|
-
*
|
|
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).
|
|
9
10
|
*/
|
|
10
11
|
export declare function runFlowDurable(options: {
|
|
11
12
|
manifest: WorkflowManifest;
|
package/dist/flow/engine.js
CHANGED
|
@@ -2,22 +2,26 @@ import { HarnessError } from "@nylorun/core/define";
|
|
|
2
2
|
import { WorkflowManifestSchema } from "@nylorun/core/contracts";
|
|
3
3
|
import { hashManifest } from "@nylorun/core/define";
|
|
4
4
|
import { HostSuspension } from "../loop/host-suspension.js";
|
|
5
|
-
import { CHECKPOINT_VERSION,
|
|
5
|
+
import { CHECKPOINT_VERSION, flowEngineVersionOf } from "../compatibility.js";
|
|
6
6
|
import { createFlowContext, failureOf, settleInFlight } from "./context.js";
|
|
7
7
|
import { runNode, unwrapSlot } from "./node.js";
|
|
8
8
|
import { runLoop } from "./loop.js";
|
|
9
|
+
import { runFlowV2 } from "./v2.js";
|
|
9
10
|
import { FlowNodeError } from "./types.js";
|
|
10
11
|
/**
|
|
11
|
-
* Deterministic flow interpreter for workflow manifests.
|
|
12
|
-
*
|
|
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).
|
|
13
15
|
*/
|
|
14
16
|
export async function runFlowDurable(options) {
|
|
15
17
|
const { manifest, checkpoint, host, signal, limits } = options;
|
|
16
18
|
WorkflowManifestSchema.parse(manifest);
|
|
17
19
|
if (checkpoint.version !== CHECKPOINT_VERSION ||
|
|
18
|
-
checkpoint.engineVersion !==
|
|
20
|
+
checkpoint.engineVersion !== flowEngineVersionOf(manifest) ||
|
|
19
21
|
checkpoint.manifestHash !== hashManifest(manifest))
|
|
20
22
|
throw new HarnessError("execution.incompatible", "Incompatible flow checkpoint");
|
|
23
|
+
if (manifest.workflowSchemaVersion === 2)
|
|
24
|
+
return runFlowV2({ manifest, checkpoint, host, signal, limits });
|
|
21
25
|
const root = manifest.root;
|
|
22
26
|
// Root Loop keeps the dedicated entry (history / verify wiring).
|
|
23
27
|
if ("loop" in root)
|
package/dist/flow/loop.d.ts
CHANGED
|
@@ -14,6 +14,10 @@ export type AgentTurnValue = {
|
|
|
14
14
|
readonly agent: AgentManifest;
|
|
15
15
|
};
|
|
16
16
|
export declare function agentTurnValue(output: JsonValue, agent: AgentManifest): AgentTurnValue;
|
|
17
|
+
export declare function readAgentTurn(value: unknown): {
|
|
18
|
+
output: JsonValue;
|
|
19
|
+
agent?: AgentManifest;
|
|
20
|
+
};
|
|
17
21
|
/**
|
|
18
22
|
* Interpret a root Loop node. Returns effects only; the host journals outcomes.
|
|
19
23
|
*/
|
package/dist/flow/loop.js
CHANGED
|
@@ -10,7 +10,7 @@ export const AGENT_TURN_MARKER = "__nylorunAgentTurn";
|
|
|
10
10
|
export function agentTurnValue(output, agent) {
|
|
11
11
|
return { [AGENT_TURN_MARKER]: 1, output, agent };
|
|
12
12
|
}
|
|
13
|
-
function readAgentTurn(value) {
|
|
13
|
+
export function readAgentTurn(value) {
|
|
14
14
|
if (value &&
|
|
15
15
|
typeof value === "object" &&
|
|
16
16
|
!Array.isArray(value) &&
|
|
@@ -32,6 +32,8 @@ function invalidAgent(path, message) {
|
|
|
32
32
|
*/
|
|
33
33
|
export async function runLoop(options) {
|
|
34
34
|
const { manifest, checkpoint, host } = options;
|
|
35
|
+
if (manifest.workflowSchemaVersion !== 1)
|
|
36
|
+
throw new HarnessError("execution.invalid-state", "runLoop expects a workflow manifest v1");
|
|
35
37
|
const root = manifest.root;
|
|
36
38
|
if (!("loop" in root))
|
|
37
39
|
throw new HarnessError("execution.invalid-state", "runLoop expects a loop root");
|
package/dist/flow/map.js
CHANGED
|
@@ -8,7 +8,7 @@ import { runNode, unwrapSlot } from "./node.js";
|
|
|
8
8
|
* Map: journal `over`, run each item concurrently at `<map>[i]/<each id>`; fail-fast.
|
|
9
9
|
*/
|
|
10
10
|
export async function runMap(ctx, node, path, input) {
|
|
11
|
-
const over = await ctx.effect("fn", input, { path, key: nodeKeyOf(path) }, { role: "map-over" });
|
|
11
|
+
const over = await ctx.effect("fn", input, { path, key: `${nodeKeyOf(path)}/over` }, { role: "map-over" });
|
|
12
12
|
if (!Array.isArray(over)) {
|
|
13
13
|
throw new FlowNodeError({
|
|
14
14
|
code: "map.not-a-list",
|
package/dist/flow/node.js
CHANGED
|
@@ -4,7 +4,8 @@ import { runChain } from "./chain.js";
|
|
|
4
4
|
import { runSwitch } from "./switch.js";
|
|
5
5
|
import { runParallel } from "./parallel.js";
|
|
6
6
|
import { runMap } from "./map.js";
|
|
7
|
-
import { runLoopNode } from "./loop.js";
|
|
7
|
+
import { readAgentTurn, runLoopNode } from "./loop.js";
|
|
8
|
+
import { FlowNodeError } from "./types.js";
|
|
8
9
|
/** Path part / id for a node among its siblings. */
|
|
9
10
|
export function nodePart(node) {
|
|
10
11
|
if ("agent" in node)
|
|
@@ -56,7 +57,7 @@ export async function runNode(ctx, node, path, input, options = {}) {
|
|
|
56
57
|
input: options.ownerInput ?? input,
|
|
57
58
|
results,
|
|
58
59
|
};
|
|
59
|
-
childInput = (await ctx.effect("fn", fnArgs, { path, key: nodeKeyOf(path) }, { role: "slot-input" }));
|
|
60
|
+
childInput = (await ctx.effect("fn", fnArgs, { path, key: `${nodeKeyOf(path)}/input`, role: "slot-input" }, { role: "slot-input" }));
|
|
60
61
|
}
|
|
61
62
|
return runRunnable(ctx, node.slot.run, path, childInput);
|
|
62
63
|
}
|
|
@@ -82,9 +83,31 @@ async function runRunnable(ctx, node, path, input) {
|
|
|
82
83
|
throw new HarnessError("execution.invalid-state", "Unknown workflow node kind");
|
|
83
84
|
}
|
|
84
85
|
async function runAgent(ctx, agentId, path, input) {
|
|
85
|
-
|
|
86
|
+
// The host marks a linked agent's output with its turn manifest for Loops; a step
|
|
87
|
+
// passes on the output only.
|
|
88
|
+
return readAgentTurn(await ctx.effect("agent", { agentId, input, path }, { path, key: nodeKeyOf(path) })).output;
|
|
86
89
|
}
|
|
87
90
|
async function runTool(ctx, name, path, input) {
|
|
88
|
-
|
|
91
|
+
const value = await ctx.effect("tool", input, { path, key: nodeKeyOf(path) }, { toolName: name });
|
|
92
|
+
return toolNodeOutput(value, path);
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* The executor settles a tool node like any tool: `{ kind: "completed", output }` or
|
|
96
|
+
* `{ kind: "denied", reason }`. The flow passes on the output only. Failed values are
|
|
97
|
+
* already raised by `ctx.effect`.
|
|
98
|
+
*/
|
|
99
|
+
function toolNodeOutput(value, path) {
|
|
100
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
101
|
+
return value;
|
|
102
|
+
const outcome = value;
|
|
103
|
+
if (outcome.kind === "completed" && "output" in outcome)
|
|
104
|
+
return outcome.output ?? null;
|
|
105
|
+
if (outcome.kind === "denied")
|
|
106
|
+
throw new FlowNodeError({
|
|
107
|
+
code: "tool.denied",
|
|
108
|
+
message: typeof outcome.reason === "string" ? outcome.reason : "Tool call denied",
|
|
109
|
+
path,
|
|
110
|
+
});
|
|
111
|
+
return value;
|
|
89
112
|
}
|
|
90
113
|
export { joinPath, mapItemPath, nodeKeyOf };
|
package/dist/flow/paths.d.ts
CHANGED
|
@@ -9,11 +9,16 @@ export declare function mapItemPath(mapPath: string, index: number, eachId: stri
|
|
|
9
9
|
export declare function nodeKeyOf(path: string): string;
|
|
10
10
|
/** Iteration vector string: enclosing Loop numbers outermost first, or "-" outside Loops. */
|
|
11
11
|
export declare function iterationsOf(vector: readonly number[]): string;
|
|
12
|
-
/**
|
|
12
|
+
/**
|
|
13
|
+
* Effect id for a flow effect (workflows.md §10).
|
|
14
|
+
* `role` separates two effects of one kind on one path, e.g. a slot `input`
|
|
15
|
+
* and the Map `over` or Switch `on` it wraps.
|
|
16
|
+
*/
|
|
13
17
|
export declare function flowEffectId(input: {
|
|
14
18
|
readonly turnId: string;
|
|
15
19
|
readonly segment: number;
|
|
16
20
|
readonly path: string;
|
|
17
21
|
readonly kind: string;
|
|
18
22
|
readonly iterations: string;
|
|
23
|
+
readonly role?: string;
|
|
19
24
|
}): string;
|
package/dist/flow/paths.js
CHANGED
|
@@ -17,7 +17,12 @@ export function nodeKeyOf(path) {
|
|
|
17
17
|
export function iterationsOf(vector) {
|
|
18
18
|
return vector.length === 0 ? "-" : vector.join(".");
|
|
19
19
|
}
|
|
20
|
-
/**
|
|
20
|
+
/**
|
|
21
|
+
* Effect id for a flow effect (workflows.md §10).
|
|
22
|
+
* `role` separates two effects of one kind on one path, e.g. a slot `input`
|
|
23
|
+
* and the Map `over` or Switch `on` it wraps.
|
|
24
|
+
*/
|
|
21
25
|
export function flowEffectId(input) {
|
|
22
|
-
|
|
26
|
+
const kind = input.role === undefined ? input.kind : `${input.kind}.${input.role}`;
|
|
27
|
+
return `${input.turnId}:${input.segment}:flow:${input.path}:${kind}:${input.iterations}`;
|
|
23
28
|
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type WorkflowManifestV2 } from "@nylorun/core/define";
|
|
2
|
+
import type { DurableHost } from "../run/durable.js";
|
|
3
|
+
import type { FlowCheckpoint } from "./checkpoint.js";
|
|
4
|
+
import { type FlowOperatorLimits } from "./limits.js";
|
|
5
|
+
import { type FlowDurableResult } from "./types.js";
|
|
6
|
+
export declare function runFlowV2(options: {
|
|
7
|
+
manifest: WorkflowManifestV2;
|
|
8
|
+
checkpoint: FlowCheckpoint;
|
|
9
|
+
host: DurableHost;
|
|
10
|
+
signal?: AbortSignal;
|
|
11
|
+
limits?: Partial<FlowOperatorLimits> | null;
|
|
12
|
+
}): Promise<FlowDurableResult>;
|
package/dist/flow/v2.js
ADDED
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Flow engine for workflow manifest v2 (`flow-2`).
|
|
3
|
+
*
|
|
4
|
+
* Differences from v1 (`flow-1`), per the Flow Agents design:
|
|
5
|
+
* - Agent and tool sessions are named by leaf paths: the leaf's id, `[i]` per Map
|
|
6
|
+
* item, under nested flow agents' ids. Control stages add nothing.
|
|
7
|
+
* - Functions are bound under stage keys (`route:on`, `@1.default.1:input`) and all
|
|
8
|
+
* receive `{ input, results, flowInput }`; `flowInput` is the nearest Agent's input.
|
|
9
|
+
* - Any node may carry `input`; there are no slots. A Map runs over its input.
|
|
10
|
+
* - A Loop without `decide` passes on a pass verdict and retries with the feedback,
|
|
11
|
+
* up to `max` attempts; `decide` returns `{ output }` or `{ retry, agent? }`.
|
|
12
|
+
* - Leaf agents come from the manifest's embedded `agents`; nested flow agents run
|
|
13
|
+
* inline with their own `flowInput` and `results`.
|
|
14
|
+
*/
|
|
15
|
+
import { HarnessError, isVariantOf } from "@nylorun/core/define";
|
|
16
|
+
import { ROOT_POSITION, childPosition, functionKey, indexSuffix, isWorkflowManifestV2, leafPart, leafPath, stageKey, } from "@nylorun/core/define";
|
|
17
|
+
import { HostSuspension } from "../loop/host-suspension.js";
|
|
18
|
+
import { createFlowContext, failureOf, markFailFastCancels, settleInFlight, } from "./context.js";
|
|
19
|
+
import { assertLoopIteration, assertMapItemCount } from "./limits.js";
|
|
20
|
+
import { iterationsOf } from "./paths.js";
|
|
21
|
+
import { readAgentTurn } from "./loop.js";
|
|
22
|
+
import { FlowNodeError } from "./types.js";
|
|
23
|
+
export async function runFlowV2(options) {
|
|
24
|
+
const { manifest, checkpoint, signal } = options;
|
|
25
|
+
const ctx = createFlowContext(options);
|
|
26
|
+
const scope = {
|
|
27
|
+
manifest,
|
|
28
|
+
flow: [],
|
|
29
|
+
pathPrefix: "",
|
|
30
|
+
keyPrefix: "",
|
|
31
|
+
pending: [],
|
|
32
|
+
indices: [],
|
|
33
|
+
iterations: [],
|
|
34
|
+
flowInput: checkpoint.input,
|
|
35
|
+
results: {},
|
|
36
|
+
};
|
|
37
|
+
try {
|
|
38
|
+
if (signal?.aborted)
|
|
39
|
+
return { status: "cancelled", checkpoint, result: { status: "cancelled" } };
|
|
40
|
+
const output = await runNode(ctx, scope, manifest.root, ROOT_POSITION, checkpoint.input);
|
|
41
|
+
return { status: "completed", checkpoint, result: { status: "completed", output } };
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
await settleInFlight(ctx);
|
|
45
|
+
if (error instanceof HostSuspension)
|
|
46
|
+
return {
|
|
47
|
+
status: [...ctx.pending.values()].includes("uncertain") ? "uncertain" : "waiting",
|
|
48
|
+
checkpoint,
|
|
49
|
+
effectIds: [...ctx.pending.keys()],
|
|
50
|
+
};
|
|
51
|
+
if (error instanceof FlowNodeError && error.failure.code === "cancelled")
|
|
52
|
+
return { status: "cancelled", checkpoint, result: { status: "cancelled" } };
|
|
53
|
+
return {
|
|
54
|
+
status: "failed",
|
|
55
|
+
checkpoint,
|
|
56
|
+
result: { status: "failed", error: failureOf(error, manifest.id) },
|
|
57
|
+
...(ctx.cancelEffectIds.size > 0 ? { cancelEffectIds: [...ctx.cancelEffectIds] } : {}),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/** Where a node's effects are recorded: a leaf's path, or its stage key plus Map indices. */
|
|
62
|
+
function siteOf(scope, node, key) {
|
|
63
|
+
const part = leafPart(node);
|
|
64
|
+
return part === undefined
|
|
65
|
+
? `${key}${indexSuffix(scope.indices)}`
|
|
66
|
+
: leafPath(scope.pathPrefix, part, scope.pending);
|
|
67
|
+
}
|
|
68
|
+
async function runNode(ctx, scope, node, position, input, agentOptions = {}) {
|
|
69
|
+
const key = stageKey(node, position, scope.keyPrefix);
|
|
70
|
+
const site = siteOf(scope, node, key);
|
|
71
|
+
let value = input;
|
|
72
|
+
if (node.input)
|
|
73
|
+
value = await callFn(ctx, scope, key, site, "input", stageArgs(scope, value));
|
|
74
|
+
if ("agent" in node)
|
|
75
|
+
return (await runAgent(ctx, scope, node, key, site, value, agentOptions)).output;
|
|
76
|
+
if ("tool" in node)
|
|
77
|
+
return runTool(ctx, scope, node.tool.name, key, site, value);
|
|
78
|
+
if ("chain" in node)
|
|
79
|
+
return runChain(ctx, scope, node.chain, position, value);
|
|
80
|
+
if ("switch" in node)
|
|
81
|
+
return runSwitch(ctx, scope, node.switch, key, site, position, value);
|
|
82
|
+
if ("parallel" in node)
|
|
83
|
+
return runParallel(ctx, scope, node.parallel, site, position, value);
|
|
84
|
+
if ("map" in node)
|
|
85
|
+
return runMap(ctx, scope, node.map.each, site, position, value);
|
|
86
|
+
if ("loop" in node)
|
|
87
|
+
return runLoop(ctx, scope, node.loop, key, site, position, value);
|
|
88
|
+
throw new HarnessError("execution.invalid-state", "Unknown workflow node kind");
|
|
89
|
+
}
|
|
90
|
+
function stageArgs(scope, input) {
|
|
91
|
+
return { input, results: scope.results, flowInput: scope.flowInput };
|
|
92
|
+
}
|
|
93
|
+
async function callFn(ctx, scope, key, site, role, args, context = {}) {
|
|
94
|
+
return (await ctx.effect(role === "verify" ? "verify" : "fn", args, {
|
|
95
|
+
path: `${site}:${role}`,
|
|
96
|
+
key: functionKey(key, role),
|
|
97
|
+
iterations: iterationsOf(scope.iterations),
|
|
98
|
+
}, { role, ...context }));
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* An agent node: a leaf agent runs as one turn in its own session; a nested flow agent
|
|
102
|
+
* runs inline, under its own id, with its own `flowInput` and `results`.
|
|
103
|
+
*/
|
|
104
|
+
async function runAgent(ctx, scope, node, key, site, input, options) {
|
|
105
|
+
const target = scope.manifest.agents[node.agent];
|
|
106
|
+
if (target === undefined)
|
|
107
|
+
throw new FlowNodeError({
|
|
108
|
+
code: "flow.unknown-agent",
|
|
109
|
+
message: `Agent '${node.agent}' is not embedded in flow agent '${scope.manifest.id}'`,
|
|
110
|
+
path: site,
|
|
111
|
+
});
|
|
112
|
+
if (isWorkflowManifestV2(target)) {
|
|
113
|
+
const flow = target;
|
|
114
|
+
const nested = {
|
|
115
|
+
manifest: flow,
|
|
116
|
+
flow: [...scope.flow, node.agent],
|
|
117
|
+
pathPrefix: site,
|
|
118
|
+
keyPrefix: key,
|
|
119
|
+
pending: [],
|
|
120
|
+
indices: scope.indices,
|
|
121
|
+
iterations: scope.iterations,
|
|
122
|
+
flowInput: input,
|
|
123
|
+
results: {},
|
|
124
|
+
};
|
|
125
|
+
return { output: await runNode(ctx, nested, flow.root, ROOT_POSITION, input) };
|
|
126
|
+
}
|
|
127
|
+
const raw = await ctx.effect("agent", {
|
|
128
|
+
agentId: node.agent,
|
|
129
|
+
input,
|
|
130
|
+
path: site,
|
|
131
|
+
...(scope.flow.length > 0 ? { flow: scope.flow } : {}),
|
|
132
|
+
...(options.manifest ? { manifest: options.manifest } : {}),
|
|
133
|
+
}, { path: site, key, iterations: iterationsOf(scope.iterations) }, options.context ?? {});
|
|
134
|
+
return readAgentTurn(raw);
|
|
135
|
+
}
|
|
136
|
+
async function runTool(ctx, scope, name, key, site, input) {
|
|
137
|
+
const value = (await ctx.effect("tool", input, { path: site, key, iterations: iterationsOf(scope.iterations) }, { toolName: name }));
|
|
138
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
139
|
+
return value;
|
|
140
|
+
const outcome = value;
|
|
141
|
+
if (outcome.kind === "completed" && "output" in outcome)
|
|
142
|
+
return outcome.output ?? null;
|
|
143
|
+
if (outcome.kind === "denied")
|
|
144
|
+
throw new FlowNodeError({
|
|
145
|
+
code: "tool.denied",
|
|
146
|
+
message: typeof outcome.reason === "string" ? outcome.reason : "Tool call denied",
|
|
147
|
+
path: site,
|
|
148
|
+
});
|
|
149
|
+
return value;
|
|
150
|
+
}
|
|
151
|
+
/** Steps in order; each step's output is the next one's input. `results` is lexical. */
|
|
152
|
+
async function runChain(ctx, scope, steps, position, input) {
|
|
153
|
+
const results = {};
|
|
154
|
+
const inner = { ...scope, results };
|
|
155
|
+
let current = input;
|
|
156
|
+
for (const [index, step] of steps.entries()) {
|
|
157
|
+
current = await runNode(ctx, inner, step, childPosition(position, index), current);
|
|
158
|
+
const name = step.id ?? leafPart(step);
|
|
159
|
+
if (name !== undefined)
|
|
160
|
+
results[name] = current;
|
|
161
|
+
}
|
|
162
|
+
return current;
|
|
163
|
+
}
|
|
164
|
+
/** `on` picks a case; the key is journaled, so replay always takes the same case. */
|
|
165
|
+
async function runSwitch(ctx, scope, node, key, site, position, input) {
|
|
166
|
+
const chosen = await callFn(ctx, scope, key, site, "on", stageArgs(scope, input));
|
|
167
|
+
if (typeof chosen !== "string")
|
|
168
|
+
throw new FlowNodeError({
|
|
169
|
+
code: "fn.failed",
|
|
170
|
+
message: `Switch on must return a case name, got ${typeof chosen}`,
|
|
171
|
+
path: site,
|
|
172
|
+
});
|
|
173
|
+
const caseNode = node.cases[chosen];
|
|
174
|
+
if (caseNode)
|
|
175
|
+
return runNode(ctx, scope, caseNode, childPosition(position, chosen), input);
|
|
176
|
+
if (node.default)
|
|
177
|
+
return runNode(ctx, scope, node.default, childPosition(position, "default"), input);
|
|
178
|
+
throw new FlowNodeError({
|
|
179
|
+
code: "switch.no-match",
|
|
180
|
+
message: `No Switch case is named ${JSON.stringify(chosen)} and there is no default case`,
|
|
181
|
+
path: site,
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
/** Run `tasks` together; fail fast on the first failure in declaration order. */
|
|
185
|
+
async function runTogether(ctx, tasks, pathOf) {
|
|
186
|
+
const outputs = new Array(tasks.length);
|
|
187
|
+
const suspensions = [];
|
|
188
|
+
const failures = [];
|
|
189
|
+
await Promise.all(tasks.map(async (task, index) => {
|
|
190
|
+
try {
|
|
191
|
+
outputs[index] = await task();
|
|
192
|
+
}
|
|
193
|
+
catch (error) {
|
|
194
|
+
if (error instanceof HostSuspension) {
|
|
195
|
+
suspensions.push(error);
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
failures.push({
|
|
199
|
+
index,
|
|
200
|
+
error: error instanceof FlowNodeError
|
|
201
|
+
? error
|
|
202
|
+
: new FlowNodeError(failureOf(error, pathOf(index))),
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
}));
|
|
206
|
+
if (failures.length > 0) {
|
|
207
|
+
markFailFastCancels(ctx);
|
|
208
|
+
failures.sort((a, b) => a.index - b.index);
|
|
209
|
+
throw failures[0].error;
|
|
210
|
+
}
|
|
211
|
+
if (suspensions.length > 0)
|
|
212
|
+
throw suspensions[0];
|
|
213
|
+
return outputs;
|
|
214
|
+
}
|
|
215
|
+
/** Every branch gets the same input; the output is keyed by branch, in declaration order. */
|
|
216
|
+
async function runParallel(ctx, scope, branches, site, position, input) {
|
|
217
|
+
const names = Object.keys(branches);
|
|
218
|
+
const outputs = await runTogether(ctx, names.map((name) => () => runNode(ctx, scope, branches[name], childPosition(position, name), input)), () => site);
|
|
219
|
+
const result = {};
|
|
220
|
+
names.forEach((name, index) => {
|
|
221
|
+
result[name] = outputs[index];
|
|
222
|
+
});
|
|
223
|
+
return result;
|
|
224
|
+
}
|
|
225
|
+
/** Runs `each` once per item of its input; the output is in item order. */
|
|
226
|
+
async function runMap(ctx, scope, each, site, position, input) {
|
|
227
|
+
if (!Array.isArray(input))
|
|
228
|
+
throw new FlowNodeError({
|
|
229
|
+
code: "map.not-a-list",
|
|
230
|
+
message: `A Map runs over its input, which must be an array; got ${input === null ? "null" : typeof input}`,
|
|
231
|
+
path: site,
|
|
232
|
+
});
|
|
233
|
+
assertMapItemCount(input.length, ctx.limits, site);
|
|
234
|
+
if (input.length === 0)
|
|
235
|
+
return [];
|
|
236
|
+
const eachPosition = childPosition(position, "each");
|
|
237
|
+
return runTogether(ctx, input.map((item, index) => () => runNode(ctx, { ...scope, pending: [...scope.pending, index], indices: [...scope.indices, index] }, each, eachPosition, item)), (index) => `${site}[${index}]`);
|
|
238
|
+
}
|
|
239
|
+
/** Run, verify, then stop or retry. The body keeps its session across attempts. */
|
|
240
|
+
async function runLoop(ctx, scope, loop, key, site, position, input) {
|
|
241
|
+
const history = [];
|
|
242
|
+
const runPosition = childPosition(position, "run");
|
|
243
|
+
const runIsLeaf = "agent" in loop.run &&
|
|
244
|
+
!isWorkflowManifestV2(scope.manifest.agents[loop.run.agent]);
|
|
245
|
+
let current = input;
|
|
246
|
+
let pinned;
|
|
247
|
+
let variant;
|
|
248
|
+
for (let iteration = 1;; iteration += 1) {
|
|
249
|
+
if (ctx.signal?.aborted)
|
|
250
|
+
throw new FlowNodeError({ code: "cancelled", message: "cancelled", path: site });
|
|
251
|
+
assertLoopIteration(iteration, ctx.limits, site);
|
|
252
|
+
const turn = { ...scope, iterations: [...scope.iterations, iteration] };
|
|
253
|
+
const loopContext = { loopPath: site, n: iteration };
|
|
254
|
+
let output;
|
|
255
|
+
if (runIsLeaf) {
|
|
256
|
+
const node = loop.run;
|
|
257
|
+
const runKey = stageKey(node, runPosition, scope.keyPrefix);
|
|
258
|
+
const runSite = siteOf(turn, node, runKey);
|
|
259
|
+
let value = current;
|
|
260
|
+
if (node.input)
|
|
261
|
+
value = await callFn(ctx, turn, runKey, runSite, "input", stageArgs(turn, value), loopContext);
|
|
262
|
+
const result = await runAgent(ctx, turn, node, runKey, runSite, value, {
|
|
263
|
+
context: loopContext,
|
|
264
|
+
...(variant ? { manifest: variant } : {}),
|
|
265
|
+
});
|
|
266
|
+
output = result.output;
|
|
267
|
+
if (result.agent) {
|
|
268
|
+
pinned ??= result.agent;
|
|
269
|
+
variant = result.agent;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
else
|
|
273
|
+
output = await runNode(ctx, turn, loop.run, runPosition, current);
|
|
274
|
+
const verdict = await runVerify(ctx, turn, loop.verify, key, site, position, {
|
|
275
|
+
input,
|
|
276
|
+
output,
|
|
277
|
+
iteration,
|
|
278
|
+
loopContext,
|
|
279
|
+
});
|
|
280
|
+
let decision;
|
|
281
|
+
if (loop.decide) {
|
|
282
|
+
try {
|
|
283
|
+
decision = (await callFn(ctx, turn, key, site, "decide", {
|
|
284
|
+
input,
|
|
285
|
+
output,
|
|
286
|
+
verdict,
|
|
287
|
+
iteration,
|
|
288
|
+
history,
|
|
289
|
+
...(variant ? { agent: variant } : {}),
|
|
290
|
+
results: turn.results,
|
|
291
|
+
flowInput: turn.flowInput,
|
|
292
|
+
}, loopContext));
|
|
293
|
+
}
|
|
294
|
+
catch (error) {
|
|
295
|
+
if (error instanceof FlowNodeError && error.failure.code === "fn.failed")
|
|
296
|
+
throw new FlowNodeError({
|
|
297
|
+
code: "loop.stopped",
|
|
298
|
+
message: error.failure.message,
|
|
299
|
+
path: site,
|
|
300
|
+
});
|
|
301
|
+
throw error;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
else
|
|
305
|
+
decision = verdict.pass ? { output } : { retry: verdict.feedback };
|
|
306
|
+
if (!decision || typeof decision !== "object")
|
|
307
|
+
throw new FlowNodeError({
|
|
308
|
+
code: "loop.invalid-decision",
|
|
309
|
+
message: "Loop decide must return { output } or { retry }",
|
|
310
|
+
path: site,
|
|
311
|
+
});
|
|
312
|
+
if ("output" in decision)
|
|
313
|
+
return decision.output;
|
|
314
|
+
if (!("retry" in decision))
|
|
315
|
+
throw new FlowNodeError({
|
|
316
|
+
code: "loop.invalid-decision",
|
|
317
|
+
message: "Loop decide must return { output } or { retry }",
|
|
318
|
+
path: site,
|
|
319
|
+
});
|
|
320
|
+
if (loop.max !== undefined && iteration >= loop.max)
|
|
321
|
+
throw new FlowNodeError({
|
|
322
|
+
code: "loop.exhausted",
|
|
323
|
+
message: `Loop stopped after ${loop.max} attempt${loop.max === 1 ? "" : "s"}` +
|
|
324
|
+
(verdict.pass ? "" : `: ${verdict.feedback}`),
|
|
325
|
+
path: site,
|
|
326
|
+
});
|
|
327
|
+
if (decision.agent !== undefined) {
|
|
328
|
+
if (!runIsLeaf)
|
|
329
|
+
throw new FlowNodeError({
|
|
330
|
+
code: "loop.invalid-agent",
|
|
331
|
+
message: "decide returned agent, but the Loop body is not an agent",
|
|
332
|
+
path: site,
|
|
333
|
+
});
|
|
334
|
+
if (pinned && !isVariantOf(decision.agent, pinned))
|
|
335
|
+
throw new FlowNodeError({
|
|
336
|
+
code: "loop.invalid-agent",
|
|
337
|
+
message: "decide returned a manifest that is not a variant of the body agent",
|
|
338
|
+
path: site,
|
|
339
|
+
});
|
|
340
|
+
variant = decision.agent;
|
|
341
|
+
}
|
|
342
|
+
history.push({ iteration, output, verdict });
|
|
343
|
+
current = decision.retry;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
async function runVerify(ctx, scope, verify, key, site, position, args) {
|
|
347
|
+
try {
|
|
348
|
+
if ("fn" in verify)
|
|
349
|
+
return (await callFn(ctx, scope, key, site, "verify", {
|
|
350
|
+
input: args.input,
|
|
351
|
+
output: args.output,
|
|
352
|
+
iteration: args.iteration,
|
|
353
|
+
results: scope.results,
|
|
354
|
+
flowInput: scope.flowInput,
|
|
355
|
+
}, args.loopContext));
|
|
356
|
+
// A verifier agent judges `{ task, response, iteration }` in a fresh session per attempt.
|
|
357
|
+
const judged = { task: args.input, response: args.output, iteration: args.iteration };
|
|
358
|
+
return (await runNode(ctx, scope, verify, childPosition(position, "verify"), judged, {
|
|
359
|
+
context: { ...args.loopContext, role: "verify-agent" },
|
|
360
|
+
}));
|
|
361
|
+
}
|
|
362
|
+
catch (error) {
|
|
363
|
+
if (error instanceof HostSuspension)
|
|
364
|
+
throw error;
|
|
365
|
+
const failure = failureOf(error, site);
|
|
366
|
+
if (failure.code === "loop.verify-failed")
|
|
367
|
+
throw error;
|
|
368
|
+
throw new FlowNodeError({ code: "loop.verify-failed", message: failure.message, path: site });
|
|
369
|
+
}
|
|
370
|
+
}
|
|
@@ -8,6 +8,12 @@ export interface DelegationHost {
|
|
|
8
8
|
readonly definition: AgentDefinition;
|
|
9
9
|
readonly onModelCall: ModelAdapter;
|
|
10
10
|
};
|
|
11
|
+
/**
|
|
12
|
+
* Run a flow agent used as a tool: the host starts it in its own linked session and
|
|
13
|
+
* returns the settled value (the flow's output, or a `{ kind: "failed" }` value). Only
|
|
14
|
+
* durable hosts can; local runs have no flow engine.
|
|
15
|
+
*/
|
|
16
|
+
flow?(delegate: Delegate, ref: AgentRef, task: string): Promise<JsonValue>;
|
|
11
17
|
/**
|
|
12
18
|
* Journal a lifecycle point exactly once. Local runs have nothing to journal. `callId` is
|
|
13
19
|
* the parent model's tool call id, for display only; it is not part of the point's identity.
|
package/dist/loop/delegation.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { HarnessError, isHarnessError } from "@nylorun/core/define";
|
|
1
|
+
import { HarnessError, isFlowDelegate, isHarnessError } from "@nylorun/core/define";
|
|
2
2
|
import { definitionFromBinding } from "../definition/agent-definition.js";
|
|
3
3
|
import { withNestedIds } from "../utils/ids.js";
|
|
4
4
|
import { initializeExecutionState } from "./initial-state.js";
|
|
@@ -40,20 +40,28 @@ export async function runDelegation(invocation, execute, call, delegate) {
|
|
|
40
40
|
let outcome;
|
|
41
41
|
let status = "failed";
|
|
42
42
|
try {
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
43
|
+
if (isFlowDelegate(delegate)) {
|
|
44
|
+
if (!host.flow)
|
|
45
|
+
throw new HarnessError("execution.invalid-input", `Agent '${ref.id}' is a flow agent; flow agents used as tools run on the Runtime`);
|
|
46
|
+
outcome = settleFlow(await host.flow(delegate, ref, task));
|
|
47
|
+
status = outcome.kind === "completed" ? "completed" : "failed";
|
|
48
|
+
}
|
|
49
|
+
else {
|
|
50
|
+
const child = host.child(delegate, ref);
|
|
51
|
+
const listener = options.onEvent;
|
|
52
|
+
const result = await withNestedIds(call.invocationId, () => execute(child.definition, {
|
|
53
|
+
input: task,
|
|
54
|
+
onModelCall: child.onModelCall,
|
|
55
|
+
signal,
|
|
56
|
+
...(options.info === undefined ? {} : { info: options.info }),
|
|
57
|
+
state: initializeExecutionState(child.definition, {
|
|
58
|
+
executionId: `${invocation.state.executionId}/${call.invocationId}`,
|
|
59
|
+
}),
|
|
60
|
+
...(listener ? { onEvent: (event) => listener({ ...event, agent: ref }) } : {}),
|
|
61
|
+
}, { delegated: ref }));
|
|
62
|
+
status = result.status;
|
|
63
|
+
outcome = settle(result);
|
|
64
|
+
}
|
|
57
65
|
}
|
|
58
66
|
catch (cause) {
|
|
59
67
|
// Durable hosts suspend children mid-flight; that must escape to the parent journal.
|
|
@@ -131,3 +139,16 @@ function lastText(result) {
|
|
|
131
139
|
}
|
|
132
140
|
return undefined;
|
|
133
141
|
}
|
|
142
|
+
/** A flow's settled value: its output, or the `{ kind: "failed" }` value the host records. */
|
|
143
|
+
function settleFlow(value) {
|
|
144
|
+
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
145
|
+
const record = value;
|
|
146
|
+
if (record.kind === "failed" && typeof record.code === "string")
|
|
147
|
+
return {
|
|
148
|
+
kind: "failed",
|
|
149
|
+
code: "delegation.failed",
|
|
150
|
+
message: `The agent failed (${record.code}: ${typeof record.message === "string" ? record.message : record.code}).`,
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
return settle({ status: "completed", output: value });
|
|
154
|
+
}
|
package/dist/run/durable.js
CHANGED
|
@@ -169,6 +169,12 @@ export async function runDurable(options) {
|
|
|
169
169
|
definition: hostedDefinition(delegate.manifest, ref),
|
|
170
170
|
onModelCall: modelCall(ref),
|
|
171
171
|
}),
|
|
172
|
+
// A flow agent used as a tool runs in its own linked session, like a flow's agent
|
|
173
|
+
// step: the host starts it, and the effect settles when its turn ends.
|
|
174
|
+
async flow(_delegate, ref, task) {
|
|
175
|
+
const outcome = await effect("agent", { agentId: ref.id, input: task, path: ref.path }, { role: "delegate", delegationId: ref.delegationId }, `${ref.delegationId}:flow`, { agent: ref });
|
|
176
|
+
return outcome.value;
|
|
177
|
+
},
|
|
172
178
|
async announce(phase, ref, payload, ids) {
|
|
173
179
|
await effect("delegation", payload, { ...ids }, `${ref.delegationId}:${phase}`, {
|
|
174
180
|
agent: ref,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nylorun/harness",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.20.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",
|
|
@@ -76,7 +76,7 @@
|
|
|
76
76
|
"zod": "^4.6.5"
|
|
77
77
|
},
|
|
78
78
|
"dependencies": {
|
|
79
|
-
"@nylorun/core": "0.
|
|
79
|
+
"@nylorun/core": "0.8.0-beta"
|
|
80
80
|
},
|
|
81
81
|
"peerDependencies": {
|
|
82
82
|
"zod": "^4.6.5"
|