@nylorun/harness 0.18.0-beta → 0.19.1-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 CHANGED
@@ -1,5 +1,33 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.19.1-beta
4
+
5
+ ### Patch Changes
6
+
7
+ - Pin core to the tested release.
8
+ - Updated dependencies [bf1c2da]
9
+ - Updated dependencies [ba1b239]
10
+ - Updated dependencies [bf1c2da]
11
+ - Updated dependencies [bf1c2da]
12
+ - Updated dependencies [bf1c2da]
13
+ - @nylorun/core@0.6.0-beta
14
+
15
+ ## 0.19.0-beta
16
+
17
+ ### Minor Changes
18
+
19
+ - fd9fd87: Add workflows: compose agents and `tool()` with `Chain`, `Switch`, `Parallel`, `Map`, and `Loop`. A workflow is a registered runnable (`kind: "workflow"`) with the same session API as an agent — `export const agents`, `saveAgent` (saves referenced agents first), `createSession`, `input` (`content` or `data`), `observe({ follow })`, `pending`, `approve`, `cancel`. Slots (`{ run, id?, input? }`) reshape data between nodes. The flow engine (`runFlowDurable`) returns effects only; `harness/src/loop/` and `runDurable` are unchanged.
20
+
21
+ HostEffect gains flow kinds `agent`, `tool` (node), `fn`, and `verify`, each with `path`, `key`, and `iterations`. The Runtime drives agent nodes through the public session contract (linked sessions, shared sandbox via `PutSession.sandbox`), offers `fn` / `verify` again on lease expiry, and routes executor Actions by `(workflowId, key)` with claim-scoped `ctx.sandbox`. Optional `message.manifest` is a turn-only variant of the session pin (turn manifests). Studio shows the manifest tree, live node status, and session links. Examples under `examples/agents/{chain,switch,parallel,map,loop,ship-feature}/`.
22
+
23
+ ### Patch Changes
24
+
25
+ - Pin core to the tested release.
26
+ - Updated dependencies [c49efed]
27
+ - Updated dependencies [c49efed]
28
+ - Updated dependencies [fd9fd87]
29
+ - @nylorun/core@0.5.0-beta
30
+
3
31
  ## 0.18.0-beta
4
32
 
5
33
  ### Minor Changes
package/HOST_CONTRACT.md CHANGED
@@ -4,11 +4,26 @@ Artifact: `@nylorun/harness@0.14.0-beta.3`. Package version is separate from pro
4
4
 
5
5
  ## HTTP (both hosts)
6
6
 
7
- Bearer application credentials: `PUT /v1/agents/:agentId` (`PutAgentRequest`: requestId, complete manifest, implementationVersion, optional pluginRoots); `PUT /v1/sessions/:sessionId` (`PutSessionRequest`: requestId, agentId, trusted ownerUserId, optional info, optional vaultIds, optional credentialSelections); `GET /v1/sessions/:sessionId`; `POST /v1/sessions/:sessionId/commands`; `GET /v1/sessions/:sessionId/items?cursor=...`; `GET /v1/sessions/:sessionId/events?cursor=...` (SSE, Last-Event-ID also accepted); vault administration `POST/GET/DELETE /v1/vaults` and `/v1/vaults/:vaultId/credentials`. Commands use `SessionCommandSchema`. Vault creates and credential rotations use `idempotencyKey`; requestId is excluded from comparison; the same key and body replay the stored metadata response; a changed body is 409. Credential responses omit secret values. `GET /v1/vaults?ownerUserId=` lists that user's vaults. A session attaches only vaults with the same ownerUserId. User vaults cannot see or attach the host vault. `GET /v1/host/model` returns `{configured:false}` or the active provider, model, authType, and optional baseUrl, never the secret. `PUT /v1/host/model` upserts a host provider credential and makes it active (idempotencyKey, requestId excluded from comparison). `PUT /v1/host/model/selection` switches the active provider/model among configured credentials without a new secret. `GET /v1/host/providers` lists configured providers with name, model, authType, lastUpdated, and active. `GET /v1/host/models` returns the public provider catalog. Executor credentials cannot call host model routes. A later session PUT may replace vaultIds and credentialSelections; agentId, ownerUserId, and info stay the creation identity. GET session returns id, agentId, ownerUserId, status, activeTurnId, vaultIds, credentialSelections, mcpSnapshot, mcpDiagnostics, plus inspectable waits/uncertainty as available. mcpSnapshot is null until the first turn discovers MCP tools; it is then pinned for the session and contains no secrets. pluginRoots are stored beside the agent definition and are not part of the manifest hash. History returns `{items: LiveEvent[], cursor: string|null}`; empty history cursor is null. `PUT /v1/executors` (`RegisterExecutorsRequest`: executors of agentId, implementationVersion, optional manifestHash, token of at least 16 characters) registers or rotates executor credentials on a running host and returns `{executors: [{agentId, implementationVersion, rotated}]}`. A token equal to the application credential, or duplicated within a request or across agents, is rejected. Registration is all-or-nothing and is persisted; an unchanged registration is idempotent and keeps open streams; a rotation ends the replaced token's streams and the replaced token stops authorizing. `DELETE /v1/executors/:agentId` removes a registration; an executor supplied to the process at startup is 409. `GET /v1/executors` lists agentId, implementationVersion, optional manifestHash, connected, and updatedAt, never tokens. Executor credentials cannot call vault routes, host model routes, or executor registration routes.
8
-
9
- Separate scoped executor bearer credentials: `GET /v1/executors/connect` emits `event: work_available` / `data: {"type":"work_available"}` after connection and committed work; `GET /v1/actions` returns `{actions: Action[]}`; `POST /v1/actions/:actionId/claim` uses ActionClaimRequest; `POST /v1/actions/:actionId/heartbeat` uses ActionHeartbeatRequest and returns leaseExpiresAt. Claim returns ActionClaim. Action result is the `action_result` session command with executor authorization, never observer authorization. Claim identity is server-generated and generation monotonically increases. Credentials authorize an executor by agentId. A manifestHash stored on an existing token is ignored, and claim requests do not send one. In-flight actions for that agent stay claimable after the registered digest changes. Clients cannot broaden their agent scope. Credentials are provisioned either to the process at startup or through `PUT /v1/executors`; startup-provided scopes apply to that process only, take precedence for their agentId, and are never persisted. Subscribe before discovery; rediscover after reconnect; notifications never authorize execution.
10
-
11
- Unauthenticated `GET /health` returns status, service, and, on hosts that publish them, version, a non-reversible scopeId digest of the database path, and pid. Clients treat these three as optional so an older host still parses.
7
+ Bearer application credentials: `PUT /v1/agents/:agentId` (`PutAgentRequest`: requestId, complete manifest, implementationVersion, optional pluginRoots); `PUT /v1/sessions/:sessionId` (`PutSessionRequest`: requestId, agentId, trusted ownerUserId, optional info, optional vaultIds, optional credentialSelections, optional `sandbox: { session }` to share another session's sandbox — same owner, identical specs); `GET /v1/sessions/:sessionId`; `POST /v1/sessions/:sessionId/commands`; `GET /v1/sessions/:sessionId/items?cursor=...`; `GET /v1/sessions/:sessionId/events?cursor=...` (SSE, Last-Event-ID also accepted); vault administration `POST/GET/DELETE /v1/vaults` and `/v1/vaults/:vaultId/credentials`. Commands use `SessionCommandSchema`. A `message` command is exactly one of `{ content: string }` or `{ data: JsonValue }`, plus optional `manifest` (turn-only agent variant; see Turn manifests below). Application principals may call `POST /v1/sessions/:id/sandbox/:tool` for session-scoped sandbox built-ins when the session has a sandbox and no active agent turn. Vault creates and credential rotations use `idempotencyKey`; requestId is excluded from comparison; the same key and body replay the stored metadata response; a changed body is 409. Credential responses omit secret values. `GET /v1/vaults?ownerUserId=` lists that user's vaults. A session attaches only vaults with the same ownerUserId. User vaults cannot see or attach the host vault. `GET /v1/tenant/model` returns `{configured:false}` or the active provider, model, authType, and optional baseUrl, never the secret. `PUT /v1/tenant/model` upserts a host-scope provider credential and makes it active (idempotencyKey, requestId excluded from comparison). `PUT /v1/tenant/model/selection` switches the active provider/model among configured credentials without a new secret. `GET /v1/tenant/providers` lists configured providers with name, model, authType, lastUpdated, and active. `GET /v1/tenant/models` returns the public provider catalog. Executor credentials cannot call tenant model routes. A later session PUT may replace vaultIds and credentialSelections; agentId, ownerUserId, and info stay the creation identity. GET session returns id, agentId, ownerUserId, status, activeTurnId, vaultIds, credentialSelections, mcpSnapshot, mcpDiagnostics, plus inspectable waits/uncertainty as available. mcpSnapshot is null until the first turn discovers MCP tools; it is then pinned for the session and contains no secrets. pluginRoots are stored beside the agent definition and are not part of the manifest hash. History returns `{items: LiveEvent[], cursor: string|null}`; empty history cursor is null. `PUT /v1/executors` (`RegisterExecutorsRequest`: executors of agentId, implementationVersion, optional manifestHash, token of at least 16 characters) registers or rotates executor credentials on a running Tenant and returns `{executors: [{agentId, implementationVersion, rotated}]}`. A token equal to the application credential, or duplicated within a request or across agents, is rejected. Registration is all-or-nothing and is persisted; an unchanged registration is idempotent and keeps open streams; a rotation ends the replaced token's streams and the replaced token stops authorizing. `DELETE /v1/executors/:agentId` removes a registration. `GET /v1/executors` lists agentId, implementationVersion, optional manifestHash, connected, and updatedAt, never tokens. Executor credentials cannot call vault routes, tenant model routes, or executor registration routes.
8
+
9
+ Separate executor bearer credentials: `GET /v1/executors/connect` emits `event: work_available` / `data: {"type":"work_available"}` after connection and committed work; `GET /v1/actions` returns `{actions: Action[]}`; `POST /v1/actions/:actionId/claim` uses ActionClaimRequest; `POST /v1/actions/:actionId/heartbeat` uses ActionHeartbeatRequest and returns leaseExpiresAt. Claim returns ActionClaim. Action result is the `action_result` session command with executor authorization, never observer authorization. Claim identity is server-generated and generation monotonically increases. Credentials authorize an executor by agentId within the selected Tenant (agent or workflow definition ids). A manifestHash stored on an existing token is ignored, and claim requests do not send one. In-flight actions for that agent stay claimable after the registered digest changes. Clients cannot broaden their agent id. Credentials are provisioned through `PUT /v1/executors`. Subscribe before discovery; rediscover after reconnect; notifications never authorize execution. Action rows may use `kind` `tool` | `hook` | `fn` | `verify`; workflow code carries `path` and `key` instead of `capabilityId` / `toolName`. Claim-scoped sandbox: `POST /v1/actions/:id/sandbox/:tool` with live `claimId` and `generation` runs on the action's session sandbox.
10
+
11
+ **Tenant and protocol headers.** Every Tenant route requires `Nylorun-Tenant`
12
+ (Tenant id matching `tn_` + 26 Crockford chars) and `Nylorun-Protocol` (client
13
+ protocol integer). Missing or malformed Tenant header → `400` before filesystem
14
+ access. Missing or unsupported protocol → `426` with
15
+ `{ status: "rejected", code: "protocol_unsupported", protocol }` before
16
+ authentication. A Tenant id in the query string or body is ignored. Selection of
17
+ a Tenant is not authentication: unknown Tenant, quarantined Tenant, and rejected
18
+ credential share an opaque `404` body. Admin routes use the Host admin key and
19
+ never accept a Tenant bearer. Vocabulary:
20
+ [runtime/src/CONTEXT.md](../runtime/src/CONTEXT.md).
21
+
22
+ Unauthenticated `GET /health` returns status, `service: "nylorun-runtime"`,
23
+ version, `hostId`, pid, and `protocol: { min, max, features }` (plus diagnostic
24
+ `coreVersion`). Clients treat unknown fields as optional so an older parser
25
+ still works. `GET /ready` is `200` only after the listener is up and Tenant
26
+ discovery has finished.
12
27
 
13
28
  All command idempotency keys bind to canonical request content within a session; requestId is transport metadata and is excluded from content comparison; exact semantic duplicates return the stored original response; changed content conflicts (409). A completed action's matching claim/generation/outcome returns its original receipt even after expiry. Conflicting duplicates and any other stale/expired claim are rejected. Heartbeat cannot resurrect an expired claim. Expired in-flight tool work is uncertain, not automatically reoffered. An expired `hook` action returns to pending and is offered again, because hooks are pure by contract; the next claim's generation fences the earlier one. Results after cancellation cannot resume a turn. Application observers cannot claim or submit action results. No hardcoded production credentials.
14
29
 
@@ -24,6 +39,12 @@ Host resolveEffect must bind the effect ID to the original request and reject dr
24
39
 
25
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`.
26
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`).
43
+
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
+
46
+ **Shared sandbox.** A workflow session has one sandbox for the tree. `PUT /v1/sessions/:id` accepts optional `sandbox: { session }` to attach another session's sandbox: same `ownerUserId`, same Tenant, identical sandbox specs; the owning session id keys the sandbox. Linked agent sessions created for agent nodes attach with `sandbox: { session: workflowSessionId }`. Application principals call `POST /v1/sessions/:id/sandbox/:tool` (`bash` | `read` | `write` | `edit` | `grep` | `glob`); refused while that session has an active agent turn. Executors call `POST /v1/actions/:id/sandbox/:tool` authorized by the live claim (`claimId` + `generation`); the SDK exposes this as `ctx.sandbox` on tool / fn / verify actions (undefined when the session has no sandbox). `session.sandbox` on the application client mirrors the session endpoint. Specs that differ across agents in a workflow tree fail at build / registration.
47
+
27
48
  ## Definitions, validation, compatibility
28
49
 
29
50
  `/define` is execution-free and browser-bundleable; Agent has no `.run()`. Explicit local execution uses `/run` run + bindingFromAgent(agent.build()). `/contracts` never imports checkpoint internals. Tools and before/after hooks are supported remotely. Arbitrary legacy middleware closures are rejected for durable definitions because they cannot be reconstructed from manifests. JSON schemas are reconstructed through Zod's JSON Schema importer; unsupported schemas fail closed. The original manifest document must survive reconstruction. Runtime is the only hasher: it hashes the accepted manifest and pins that digest on the session and on each action. Agents do not hash. Model configuration is host-owned. The executor claims by agent id. Runtime checks a successful tool result against the output schema copied onto the action and stores a schema mismatch as a failed outcome on a completed action.
package/README.md CHANGED
@@ -3,8 +3,7 @@
3
3
  Execution engine, checkpoints and durable host effects. Shared authoring and wire
4
4
  contracts live in `@nylorun/core`; applications use `@nylorun/agents`.
5
5
  OSS publishes harness for local Runtime; Cloud installs published packages from
6
- npm independently. See the
7
- [package architecture](../docs/design/package-architecture.md).
6
+ npm independently.
8
7
 
9
8
  Use `/run` for explicit execution, `/model/adapters` for provider format adapters,
10
9
  and `/compatibility` for checkpoint compatibility. Definitions and protocol
@@ -1,3 +1,5 @@
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
+ /** Flow engine version pinned on workflow checkpoints. */
5
+ export declare const FLOW_ENGINE_VERSION = "flow-1";
@@ -1,3 +1,5 @@
1
1
  export { checkCompatibility } from "./definition/compatibility.js";
2
2
  export const CHECKPOINT_VERSION = 1;
3
3
  export const ENGINE_VERSION = "hosted-2";
4
+ /** Flow engine version pinned on workflow checkpoints. */
5
+ export const FLOW_ENGINE_VERSION = "flow-1";
@@ -0,0 +1,8 @@
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>;
@@ -0,0 +1,27 @@
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
+ }
@@ -0,0 +1,21 @@
1
+ import type { JsonValue } from "@nylorun/core/define";
2
+ import { type WorkflowManifest } from "@nylorun/core/contracts";
3
+ import { FLOW_ENGINE_VERSION } from "../compatibility.js";
4
+ /** Private persistence contract for workflow sessions; not a session wire type. */
5
+ export interface FlowCheckpoint {
6
+ readonly version: 1;
7
+ readonly engineVersion: typeof FLOW_ENGINE_VERSION;
8
+ readonly manifestHash: string;
9
+ readonly sessionId: string;
10
+ readonly turnId: string;
11
+ /** Increment for each human/event continuation, not for an action result. */
12
+ readonly segment: number;
13
+ readonly input: JsonValue;
14
+ }
15
+ export declare function createFlowCheckpoint(input: {
16
+ manifest: WorkflowManifest;
17
+ sessionId: string;
18
+ turnId: string;
19
+ input: JsonValue;
20
+ segment?: number;
21
+ }): FlowCheckpoint;
@@ -0,0 +1,15 @@
1
+ import { WorkflowManifestSchema } from "@nylorun/core/contracts";
2
+ import { hashManifest } from "@nylorun/core/define";
3
+ import { CHECKPOINT_VERSION, FLOW_ENGINE_VERSION } from "../compatibility.js";
4
+ export function createFlowCheckpoint(input) {
5
+ WorkflowManifestSchema.parse(input.manifest);
6
+ return {
7
+ version: CHECKPOINT_VERSION,
8
+ engineVersion: FLOW_ENGINE_VERSION,
9
+ manifestHash: hashManifest(input.manifest),
10
+ sessionId: input.sessionId,
11
+ turnId: input.turnId,
12
+ segment: input.segment ?? 0,
13
+ input: input.input,
14
+ };
15
+ }
@@ -0,0 +1,39 @@
1
+ import type { JsonValue, WorkflowManifest } 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 FlowFailure } from "./types.js";
6
+ export type FlowEffectKind = "agent" | "tool" | "fn" | "verify";
7
+ export type FlowContext = {
8
+ readonly manifest: WorkflowManifest;
9
+ readonly checkpoint: FlowCheckpoint;
10
+ readonly host: DurableHost;
11
+ readonly signal?: AbortSignal;
12
+ /** Operator ceilings (Map items / Loop iterations). */
13
+ readonly limits: FlowOperatorLimits;
14
+ readonly pending: Map<string, "pending" | "uncertain">;
15
+ 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
+ /** Effect ids the engine wants cancelled after fail-fast. */
21
+ readonly cancelEffectIds: Set<string>;
22
+ effect(kind: FlowEffectKind, input: unknown, identity: {
23
+ path: string;
24
+ key: string;
25
+ iterations?: string;
26
+ }, context?: Record<string, unknown>): Promise<unknown>;
27
+ nearestResults(): Record<string, JsonValue>;
28
+ iterationsString(): string;
29
+ };
30
+ export declare function createFlowContext(options: {
31
+ readonly manifest: WorkflowManifest;
32
+ readonly checkpoint: FlowCheckpoint;
33
+ readonly host: DurableHost;
34
+ readonly signal?: AbortSignal;
35
+ readonly limits?: Partial<FlowOperatorLimits> | null;
36
+ }): FlowContext;
37
+ export declare function markFailFastCancels(ctx: FlowContext): void;
38
+ export declare function settleInFlight(ctx: FlowContext): Promise<void>;
39
+ export declare function failureOf(error: unknown, fallbackPath?: string): FlowFailure;
@@ -0,0 +1,100 @@
1
+ import { HostSuspension } from "../loop/host-suspension.js";
2
+ import { resolveOperatorLimits } from "./limits.js";
3
+ import { flowEffectId, iterationsOf, nodeKeyOf } from "./paths.js";
4
+ import { failedValueOf, FlowNodeError } from "./types.js";
5
+ export function createFlowContext(options) {
6
+ const pending = new Map();
7
+ const inFlight = new Set();
8
+ const cancelEffectIds = new Set();
9
+ const resultsStack = [];
10
+ const ctx = {
11
+ manifest: options.manifest,
12
+ checkpoint: options.checkpoint,
13
+ host: options.host,
14
+ signal: options.signal,
15
+ limits: resolveOperatorLimits(options.limits),
16
+ pending,
17
+ inFlight,
18
+ resultsStack,
19
+ iterations: [],
20
+ cancelEffectIds,
21
+ nearestResults() {
22
+ return resultsStack.length === 0 ? {} : resultsStack[resultsStack.length - 1];
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({
33
+ turnId: options.checkpoint.turnId,
34
+ segment: options.checkpoint.segment,
35
+ path: identity.path,
36
+ kind,
37
+ iterations,
38
+ });
39
+ if (cancelEffectIds.has(effectId))
40
+ throw new FlowNodeError({
41
+ code: "cancelled",
42
+ message: "Effect cancelled by fail-fast",
43
+ path: identity.path,
44
+ });
45
+ const request = JSON.parse(JSON.stringify({
46
+ effectId,
47
+ sessionId: options.checkpoint.sessionId,
48
+ turnId: options.checkpoint.turnId,
49
+ agentId: options.manifest.id,
50
+ manifestHash: options.checkpoint.manifestHash,
51
+ kind,
52
+ path: identity.path,
53
+ key,
54
+ iterations,
55
+ input,
56
+ context,
57
+ }));
58
+ const operation = options.host.resolveEffect(request);
59
+ inFlight.add(operation);
60
+ let result;
61
+ try {
62
+ result = await operation;
63
+ }
64
+ finally {
65
+ inFlight.delete(operation);
66
+ }
67
+ if (result.status !== "completed") {
68
+ pending.set(effectId, result.status);
69
+ throw new HostSuspension(effectId, result.status);
70
+ }
71
+ const failure = failedValueOf(result.outcome.value);
72
+ if (failure) {
73
+ throw new FlowNodeError({
74
+ ...failure,
75
+ path: failure.path ?? identity.path,
76
+ });
77
+ }
78
+ return result.outcome.value;
79
+ },
80
+ };
81
+ return ctx;
82
+ }
83
+ export function markFailFastCancels(ctx) {
84
+ for (const effectId of ctx.pending.keys())
85
+ ctx.cancelEffectIds.add(effectId);
86
+ }
87
+ export async function settleInFlight(ctx) {
88
+ await Promise.allSettled([...ctx.inFlight]);
89
+ }
90
+ export function failureOf(error, fallbackPath) {
91
+ if (error instanceof FlowNodeError) {
92
+ return {
93
+ ...error.failure,
94
+ path: error.failure.path ?? fallbackPath,
95
+ };
96
+ }
97
+ if (error instanceof Error && error.message)
98
+ return { code: "fn.failed", message: error.message, path: fallbackPath };
99
+ return { code: "fn.failed", message: String(error), path: fallbackPath };
100
+ }
@@ -0,0 +1,17 @@
1
+ import { type WorkflowManifest } from "@nylorun/core/contracts";
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
+ /**
7
+ * Deterministic flow interpreter for workflow manifests.
8
+ * One module per primitive; returns effects only (SD-I1).
9
+ */
10
+ export declare function runFlowDurable(options: {
11
+ manifest: WorkflowManifest;
12
+ checkpoint: FlowCheckpoint;
13
+ host: DurableHost;
14
+ signal?: AbortSignal;
15
+ /** Operator ceilings (`maxMapItems`, `maxLoopIterations`). Host/Runtime supplies these. */
16
+ limits?: Partial<FlowOperatorLimits> | null;
17
+ }): Promise<FlowDurableResult>;
@@ -0,0 +1,57 @@
1
+ import { HarnessError } from "@nylorun/core/define";
2
+ import { WorkflowManifestSchema } from "@nylorun/core/contracts";
3
+ import { hashManifest } from "@nylorun/core/define";
4
+ import { HostSuspension } from "../loop/host-suspension.js";
5
+ import { CHECKPOINT_VERSION, FLOW_ENGINE_VERSION } from "../compatibility.js";
6
+ import { createFlowContext, failureOf, settleInFlight } from "./context.js";
7
+ import { runNode, unwrapSlot } from "./node.js";
8
+ import { runLoop } from "./loop.js";
9
+ import { FlowNodeError } from "./types.js";
10
+ /**
11
+ * Deterministic flow interpreter for workflow manifests.
12
+ * One module per primitive; returns effects only (SD-I1).
13
+ */
14
+ export async function runFlowDurable(options) {
15
+ const { manifest, checkpoint, host, signal, limits } = options;
16
+ WorkflowManifestSchema.parse(manifest);
17
+ if (checkpoint.version !== CHECKPOINT_VERSION ||
18
+ checkpoint.engineVersion !== FLOW_ENGINE_VERSION ||
19
+ checkpoint.manifestHash !== hashManifest(manifest))
20
+ throw new HarnessError("execution.incompatible", "Incompatible flow checkpoint");
21
+ const root = manifest.root;
22
+ // Root Loop keeps the dedicated entry (history / verify wiring).
23
+ if ("loop" in root)
24
+ return runLoop({ manifest, checkpoint, host, signal, limits });
25
+ const ctx = createFlowContext({ manifest, checkpoint, host, signal, limits });
26
+ const { part } = unwrapSlot(root);
27
+ const rootPath = part;
28
+ try {
29
+ if (signal?.aborted)
30
+ return { status: "cancelled", checkpoint, result: { status: "cancelled" } };
31
+ const output = await runNode(ctx, root, rootPath, checkpoint.input);
32
+ return {
33
+ status: "completed",
34
+ checkpoint,
35
+ result: { status: "completed", output },
36
+ };
37
+ }
38
+ catch (error) {
39
+ await settleInFlight(ctx);
40
+ if (error instanceof HostSuspension) {
41
+ return {
42
+ status: [...ctx.pending.values()].includes("uncertain") ? "uncertain" : "waiting",
43
+ checkpoint,
44
+ effectIds: [...ctx.pending.keys()],
45
+ };
46
+ }
47
+ if (error instanceof FlowNodeError && error.failure.code === "cancelled")
48
+ return { status: "cancelled", checkpoint, result: { status: "cancelled" } };
49
+ const failure = failureOf(error, rootPath);
50
+ return {
51
+ status: "failed",
52
+ checkpoint,
53
+ result: { status: "failed", error: failure },
54
+ ...(ctx.cancelEffectIds.size > 0 ? { cancelEffectIds: [...ctx.cancelEffectIds] } : {}),
55
+ };
56
+ }
57
+ }
@@ -0,0 +1,7 @@
1
+ export { createFlowCheckpoint, type FlowCheckpoint } from "./checkpoint.js";
2
+ export { runFlowDurable } from "./engine.js";
3
+ export { runLoop, runLoopNode, agentTurnValue, AGENT_TURN_MARKER, type FlowDurableResult, type FlowRunResult, type AgentTurnValue, } from "./loop.js";
4
+ export { assertLoopIteration, assertMapItemCount, FLOW_OPERATOR_DEFAULTS, resolveOperatorLimits, type FlowOperatorLimits, } from "./limits.js";
5
+ export { flowEffectId, iterationsOf, joinPath, mapItemPath, nodeKeyOf } from "./paths.js";
6
+ export { nodePart, unwrapSlot, runNode } from "./node.js";
7
+ export { FlowNodeError, failedValueOf } from "./types.js";
@@ -0,0 +1,7 @@
1
+ export { createFlowCheckpoint } from "./checkpoint.js";
2
+ export { runFlowDurable } from "./engine.js";
3
+ export { runLoop, runLoopNode, agentTurnValue, AGENT_TURN_MARKER, } from "./loop.js";
4
+ export { assertLoopIteration, assertMapItemCount, FLOW_OPERATOR_DEFAULTS, resolveOperatorLimits, } from "./limits.js";
5
+ export { flowEffectId, iterationsOf, joinPath, mapItemPath, nodeKeyOf } from "./paths.js";
6
+ export { nodePart, unwrapSlot, runNode } from "./node.js";
7
+ export { FlowNodeError, failedValueOf } from "./types.js";
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Operator flow ceilings for the engine (`workflows.md` §13).
3
+ * Host-side assert helpers live in the Runtime package; harness duplicates the
4
+ * codes here so the engine never depends on Runtime.
5
+ * Codes must stay identical: `map.too-many-items`, `loop.too-many-iterations`.
6
+ */
7
+ export type FlowOperatorLimits = {
8
+ readonly maxMapItems: number;
9
+ readonly maxLoopIterations: number;
10
+ };
11
+ /** Same defaults as Runtime `FLOW_LIMIT_DEFAULTS` (item/iteration ceilings). */
12
+ export declare const FLOW_OPERATOR_DEFAULTS: FlowOperatorLimits;
13
+ export declare function resolveOperatorLimits(limits?: Partial<FlowOperatorLimits> | null): FlowOperatorLimits;
14
+ /**
15
+ * Map item ceiling. Exceeding raises `map.too-many-items` and nothing should start.
16
+ */
17
+ export declare function assertMapItemCount(count: number, limits: Pick<FlowOperatorLimits, "maxMapItems">, path?: string): void;
18
+ /**
19
+ * Loop operator ceiling. Exceeding raises `loop.too-many-iterations`.
20
+ * `n` is the 1-based iteration about to run.
21
+ */
22
+ export declare function assertLoopIteration(n: number, limits: Pick<FlowOperatorLimits, "maxLoopIterations">, path?: string): void;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Operator flow ceilings for the engine (`workflows.md` §13).
3
+ * Host-side assert helpers live in the Runtime package; harness duplicates the
4
+ * codes here so the engine never depends on Runtime.
5
+ * Codes must stay identical: `map.too-many-items`, `loop.too-many-iterations`.
6
+ */
7
+ import { FlowNodeError } from "./types.js";
8
+ /** Same defaults as Runtime `FLOW_LIMIT_DEFAULTS` (item/iteration ceilings). */
9
+ export const FLOW_OPERATOR_DEFAULTS = {
10
+ maxMapItems: 1000,
11
+ maxLoopIterations: 100,
12
+ };
13
+ export function resolveOperatorLimits(limits) {
14
+ return {
15
+ maxMapItems: limits?.maxMapItems ?? FLOW_OPERATOR_DEFAULTS.maxMapItems,
16
+ maxLoopIterations: limits?.maxLoopIterations ?? FLOW_OPERATOR_DEFAULTS.maxLoopIterations,
17
+ };
18
+ }
19
+ /**
20
+ * Map item ceiling. Exceeding raises `map.too-many-items` and nothing should start.
21
+ */
22
+ export function assertMapItemCount(count, limits, path) {
23
+ if (count > limits.maxMapItems)
24
+ throw new FlowNodeError({
25
+ code: "map.too-many-items",
26
+ message: `Map produced ${count} items; maxMapItems is ${limits.maxMapItems}`,
27
+ path,
28
+ });
29
+ }
30
+ /**
31
+ * Loop operator ceiling. Exceeding raises `loop.too-many-iterations`.
32
+ * `n` is the 1-based iteration about to run.
33
+ */
34
+ export function assertLoopIteration(n, limits, path) {
35
+ if (n > limits.maxLoopIterations)
36
+ throw new FlowNodeError({
37
+ code: "loop.too-many-iterations",
38
+ message: `Loop iteration ${n} exceeds maxLoopIterations ${limits.maxLoopIterations}`,
39
+ path,
40
+ });
41
+ }
@@ -0,0 +1,31 @@
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
+ /**
18
+ * Interpret a root Loop node. Returns effects only; the host journals outcomes.
19
+ */
20
+ export declare function runLoop(options: {
21
+ readonly manifest: WorkflowManifest;
22
+ readonly checkpoint: FlowCheckpoint;
23
+ readonly host: DurableHost;
24
+ readonly signal?: AbortSignal;
25
+ readonly limits?: Partial<FlowOperatorLimits> | null;
26
+ }): Promise<FlowDurableResult>;
27
+ /**
28
+ * Nested or root Loop body: run → verify → decide until `{ output }` or stop.
29
+ * Agent turn pinning / decide patches (`decision.agent`) are L5.
30
+ */
31
+ export declare function runLoopNode(ctx: FlowContext, loop: WorkflowLoopNode["loop"], path: string, input: JsonValue): Promise<JsonValue>;
@@ -0,0 +1,236 @@
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
+ 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
+ const root = manifest.root;
36
+ if (!("loop" in root))
37
+ throw new HarnessError("execution.invalid-state", "runLoop expects a loop root");
38
+ const ctx = createFlowContext({
39
+ manifest,
40
+ checkpoint,
41
+ host,
42
+ signal: options.signal,
43
+ limits: options.limits,
44
+ });
45
+ try {
46
+ if (options.signal?.aborted)
47
+ return { status: "cancelled", checkpoint, result: { status: "cancelled" } };
48
+ const output = await runLoopNode(ctx, root.loop, root.loop.id, checkpoint.input);
49
+ return {
50
+ status: "completed",
51
+ checkpoint,
52
+ result: { status: "completed", output },
53
+ };
54
+ }
55
+ catch (error) {
56
+ await settleInFlight(ctx);
57
+ if (error instanceof HostSuspension) {
58
+ return {
59
+ status: [...ctx.pending.values()].includes("uncertain") ? "uncertain" : "waiting",
60
+ checkpoint,
61
+ effectIds: [...ctx.pending.keys()],
62
+ };
63
+ }
64
+ if (error instanceof FlowNodeError && error.failure.code === "cancelled")
65
+ return { status: "cancelled", checkpoint, result: { status: "cancelled" } };
66
+ const failure = failureOf(error, root.loop.id);
67
+ return {
68
+ status: "failed",
69
+ checkpoint,
70
+ result: { status: "failed", error: failure },
71
+ ...(ctx.cancelEffectIds.size > 0 ? { cancelEffectIds: [...ctx.cancelEffectIds] } : {}),
72
+ };
73
+ }
74
+ }
75
+ /**
76
+ * Nested or root Loop body: run → verify → decide until `{ output }` or stop.
77
+ * Agent turn pinning / decide patches (`decision.agent`) are L5.
78
+ */
79
+ export async function runLoopNode(ctx, loop, path, input) {
80
+ let iteration = 1;
81
+ let currentInput = input;
82
+ const history = [];
83
+ const loopInput = input;
84
+ const runIsAgent = "agent" in loop.run;
85
+ // Session pin (first turn's manifest) and the patch carried within this run.
86
+ let pinnedAgent;
87
+ let currentAgent;
88
+ for (;;) {
89
+ if (ctx.signal?.aborted)
90
+ throw new FlowNodeError({ code: "cancelled", message: "cancelled", path });
91
+ // Operator ceiling before starting this iteration (WF-L3 / LOOP-A8).
92
+ assertLoopIteration(iteration, ctx.limits, path);
93
+ ctx.iterations = [...ctx.iterations, iteration];
94
+ const iterations = ctx.iterationsString();
95
+ try {
96
+ let runOutput;
97
+ if (runIsAgent) {
98
+ const agentId = loop.run.agent;
99
+ const agentPath = runPath(path, loop.run);
100
+ const rawAgent = await ctx.effect("agent", {
101
+ agentId,
102
+ input: currentInput,
103
+ path: agentPath,
104
+ ...(currentAgent ? { manifest: currentAgent } : {}),
105
+ }, { path: agentPath, key: nodeKeyOf(agentPath), iterations }, { loopPath: path, n: iteration });
106
+ const turned = readAgentTurn(rawAgent);
107
+ runOutput = turned.output;
108
+ if (turned.agent) {
109
+ // First turn establishes the session pin; later turns may be variants.
110
+ pinnedAgent ??= turned.agent;
111
+ currentAgent = turned.agent;
112
+ }
113
+ }
114
+ else {
115
+ runOutput = await runNode(ctx, loop.run, runPath(path, loop.run), currentInput, {
116
+ ownerInput: loopInput,
117
+ });
118
+ }
119
+ const verdict = await runVerify(ctx, loop.verify, path, {
120
+ input: loopInput,
121
+ output: runOutput,
122
+ iteration,
123
+ });
124
+ let decision;
125
+ try {
126
+ decision = (await ctx.effect("fn", {
127
+ output: runOutput,
128
+ verdict,
129
+ iteration,
130
+ input: loopInput,
131
+ history,
132
+ ...(currentAgent ? { agent: currentAgent } : {}),
133
+ }, { path, key: `${nodeKeyOf(path)}/decide`, iterations }, { loopPath: path, n: iteration, role: "decide" }));
134
+ }
135
+ catch (error) {
136
+ if (error instanceof FlowNodeError && error.failure.code === "fn.failed") {
137
+ throw new FlowNodeError({
138
+ code: "loop.stopped",
139
+ message: error.failure.message,
140
+ path,
141
+ });
142
+ }
143
+ if (error instanceof Error &&
144
+ !(error instanceof HostSuspension) &&
145
+ !(error instanceof FlowNodeError)) {
146
+ throw new FlowNodeError({
147
+ code: "loop.stopped",
148
+ message: error.message,
149
+ path,
150
+ });
151
+ }
152
+ throw error;
153
+ }
154
+ if ("output" in decision && !("input" in decision))
155
+ return decision.output;
156
+ if (!("input" in decision))
157
+ throw new HarnessError("execution.invalid-state", "Decide returned neither input nor output");
158
+ const next = decision;
159
+ if (next.agent !== undefined) {
160
+ if (!runIsAgent) {
161
+ invalidAgent(path, "Decide returned agent but Loop.run is not an agent");
162
+ }
163
+ if (pinnedAgent && !isVariantOf(next.agent, pinnedAgent)) {
164
+ invalidAgent(path, "Decide returned a manifest that is not a variant of the pinned agent");
165
+ }
166
+ currentAgent = next.agent;
167
+ }
168
+ history.push({ iteration, output: runOutput, verdict });
169
+ currentInput = next.input;
170
+ iteration += 1;
171
+ }
172
+ finally {
173
+ ctx.iterations.pop();
174
+ }
175
+ }
176
+ }
177
+ function runPath(loopPath, run) {
178
+ const { part } = unwrapSlot(run);
179
+ return joinPath(loopPath, part);
180
+ }
181
+ async function runVerify(ctx, verify, loopPath, args) {
182
+ const iterations = ctx.iterationsString();
183
+ if ("fn" in verify) {
184
+ try {
185
+ return (await ctx.effect("verify", args, { path: loopPath, key: nodeKeyOf(loopPath), iterations }, { loopPath, n: args.iteration }));
186
+ }
187
+ catch (error) {
188
+ if (error instanceof FlowNodeError) {
189
+ if (error.failure.code === "loop.verify-failed")
190
+ throw error;
191
+ throw new FlowNodeError({
192
+ code: "loop.verify-failed",
193
+ message: error.failure.message,
194
+ path: loopPath,
195
+ });
196
+ }
197
+ throw error;
198
+ }
199
+ }
200
+ // Verifier agent (or slot wrapping one): input is { task, response, iteration }.
201
+ const judgePayload = {
202
+ task: args.input,
203
+ response: args.output,
204
+ iteration: args.iteration,
205
+ };
206
+ try {
207
+ if ("slot" in verify) {
208
+ const { part } = unwrapSlot(verify);
209
+ const verifyPath = joinPath(loopPath, part);
210
+ const value = await runNode(ctx, verify, verifyPath, judgePayload);
211
+ return value;
212
+ }
213
+ if ("agent" in verify) {
214
+ const verifyPath = joinPath(loopPath, verify.agent);
215
+ 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" });
216
+ return value;
217
+ }
218
+ }
219
+ catch (error) {
220
+ if (error instanceof HostSuspension)
221
+ throw error;
222
+ if (error instanceof FlowNodeError) {
223
+ throw new FlowNodeError({
224
+ code: "loop.verify-failed",
225
+ message: error.failure.message,
226
+ path: loopPath,
227
+ });
228
+ }
229
+ throw new FlowNodeError({
230
+ code: "loop.verify-failed",
231
+ message: error instanceof Error ? error.message : String(error),
232
+ path: loopPath,
233
+ });
234
+ }
235
+ throw new HarnessError("execution.invalid-state", "Unsupported Loop.verify node");
236
+ }
@@ -0,0 +1,7 @@
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>;
@@ -0,0 +1,64 @@
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) }, { 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
+ }
@@ -0,0 +1,31 @@
1
+ import type { JsonValue } from "@nylorun/core/define";
2
+ import type { WorkflowNode } from "@nylorun/core";
3
+ import type { FlowContext } from "./context.js";
4
+ import { joinPath, mapItemPath, nodeKeyOf } from "./paths.js";
5
+ /** Path part / id for a node among its siblings. */
6
+ export declare function nodePart(node: WorkflowNode): string;
7
+ export type SlotUnwrap = {
8
+ readonly run: WorkflowNode;
9
+ readonly inputFn: boolean;
10
+ readonly part: string;
11
+ };
12
+ export declare function unwrapSlot(node: WorkflowNode): SlotUnwrap;
13
+ export type RunNodeOptions = {
14
+ /**
15
+ * Input of the primitive that owns the slot (`workflows.md` §4).
16
+ * Defaults to `input` (the value the child would receive without a reshape).
17
+ */
18
+ readonly ownerInput?: JsonValue;
19
+ /** Map item: slot `input` receives `{ value: item, input: mapInput, results, index }`. */
20
+ readonly map?: {
21
+ readonly item: JsonValue;
22
+ readonly mapInput: JsonValue;
23
+ readonly index: number;
24
+ };
25
+ };
26
+ /**
27
+ * Run any workflow node at `path` with `input`.
28
+ * Slots: optional `fn` reshape, then the wrapped runnable.
29
+ */
30
+ export declare function runNode(ctx: FlowContext, node: WorkflowNode, path: string, input: JsonValue, options?: RunNodeOptions): Promise<JsonValue>;
31
+ export { joinPath, mapItemPath, nodeKeyOf };
@@ -0,0 +1,90 @@
1
+ import { HarnessError } from "@nylorun/core/define";
2
+ import { joinPath, mapItemPath, nodeKeyOf } from "./paths.js";
3
+ import { runChain } from "./chain.js";
4
+ import { runSwitch } from "./switch.js";
5
+ import { runParallel } from "./parallel.js";
6
+ import { runMap } from "./map.js";
7
+ import { runLoopNode } from "./loop.js";
8
+ /** Path part / id for a node among its siblings. */
9
+ export function nodePart(node) {
10
+ if ("agent" in node)
11
+ return node.agent;
12
+ if ("tool" in node)
13
+ return node.tool.name;
14
+ if ("chain" in node)
15
+ return node.chain.id;
16
+ if ("switch" in node)
17
+ return node.switch.id;
18
+ if ("parallel" in node)
19
+ return node.parallel.id;
20
+ if ("map" in node)
21
+ return node.map.id;
22
+ if ("loop" in node)
23
+ return node.loop.id;
24
+ if ("slot" in node)
25
+ return node.slot.id ?? nodePart(node.slot.run);
26
+ throw new HarnessError("execution.invalid-state", "Unknown workflow node kind");
27
+ }
28
+ export function unwrapSlot(node) {
29
+ if ("slot" in node) {
30
+ return {
31
+ run: node.slot.run,
32
+ inputFn: !!node.slot.input,
33
+ part: node.slot.id ?? nodePart(node.slot.run),
34
+ };
35
+ }
36
+ return { run: node, inputFn: false, part: nodePart(node) };
37
+ }
38
+ /**
39
+ * Run any workflow node at `path` with `input`.
40
+ * Slots: optional `fn` reshape, then the wrapped runnable.
41
+ */
42
+ export async function runNode(ctx, node, path, input, options = {}) {
43
+ if ("slot" in node) {
44
+ let childInput = input;
45
+ if (node.slot.input) {
46
+ const results = ctx.nearestResults();
47
+ const fnArgs = options.map
48
+ ? {
49
+ value: options.map.item,
50
+ input: options.map.mapInput,
51
+ results,
52
+ index: options.map.index,
53
+ }
54
+ : {
55
+ value: input,
56
+ input: options.ownerInput ?? input,
57
+ results,
58
+ };
59
+ childInput = (await ctx.effect("fn", fnArgs, { path, key: nodeKeyOf(path) }, { role: "slot-input" }));
60
+ }
61
+ return runRunnable(ctx, node.slot.run, path, childInput);
62
+ }
63
+ return runRunnable(ctx, node, path, input);
64
+ }
65
+ async function runRunnable(ctx, node, path, input) {
66
+ if ("slot" in node)
67
+ return runNode(ctx, node, path, input);
68
+ if ("agent" in node)
69
+ return runAgent(ctx, node.agent, path, input);
70
+ if ("tool" in node)
71
+ return runTool(ctx, node.tool.name, path, input);
72
+ if ("chain" in node)
73
+ return runChain(ctx, node.chain, path, input);
74
+ if ("switch" in node)
75
+ return runSwitch(ctx, node.switch, path, input);
76
+ if ("parallel" in node)
77
+ return runParallel(ctx, node.parallel, path, input);
78
+ if ("map" in node)
79
+ return runMap(ctx, node.map, path, input);
80
+ if ("loop" in node)
81
+ return runLoopNode(ctx, node.loop, path, input);
82
+ throw new HarnessError("execution.invalid-state", "Unknown workflow node kind");
83
+ }
84
+ async function runAgent(ctx, agentId, path, input) {
85
+ return (await ctx.effect("agent", { agentId, input, path }, { path, key: nodeKeyOf(path) }));
86
+ }
87
+ async function runTool(ctx, name, path, input) {
88
+ return (await ctx.effect("tool", input, { path, key: nodeKeyOf(path) }, { toolName: name }));
89
+ }
90
+ export { joinPath, mapItemPath, nodeKeyOf };
@@ -0,0 +1,7 @@
1
+ import type { JsonValue } from "@nylorun/core/define";
2
+ import type { WorkflowParallelNode } from "@nylorun/core";
3
+ import type { FlowContext } from "./context.js";
4
+ /**
5
+ * Parallel: all branches ready at once; output object in declaration order; fail-fast.
6
+ */
7
+ export declare function runParallel(ctx: FlowContext, node: WorkflowParallelNode["parallel"], path: string, input: JsonValue): Promise<JsonValue>;
@@ -0,0 +1,47 @@
1
+ import { HostSuspension } from "../loop/host-suspension.js";
2
+ import { failureOf, markFailFastCancels } from "./context.js";
3
+ import { FlowNodeError } from "./types.js";
4
+ import { joinPath } from "./paths.js";
5
+ import { runNode } from "./node.js";
6
+ /**
7
+ * Parallel: all branches ready at once; output object in declaration order; fail-fast.
8
+ */
9
+ export async function runParallel(ctx, node, path, input) {
10
+ const names = Object.keys(node.branches);
11
+ const outputs = {};
12
+ const suspensions = [];
13
+ const failures = [];
14
+ await Promise.all(names.map(async (name) => {
15
+ const branch = node.branches[name];
16
+ const branchPath = joinPath(path, name);
17
+ try {
18
+ outputs[name] = await runNode(ctx, branch, branchPath, input);
19
+ }
20
+ catch (error) {
21
+ if (error instanceof HostSuspension) {
22
+ suspensions.push(error);
23
+ return;
24
+ }
25
+ failures.push(error instanceof FlowNodeError ? error : new FlowNodeError(failureOf(error, branchPath)));
26
+ }
27
+ }));
28
+ if (failures.length > 0) {
29
+ markFailFastCancels(ctx);
30
+ // First failure in declaration order wins when several settle together.
31
+ const ordered = failures.sort((a, b) => {
32
+ const ai = names.findIndex((n) => (a.failure.path ?? "").includes(`/${n}`) || a.failure.path?.endsWith(n));
33
+ const bi = names.findIndex((n) => (b.failure.path ?? "").includes(`/${n}`) || b.failure.path?.endsWith(n));
34
+ return (ai === -1 ? names.length : ai) - (bi === -1 ? names.length : bi);
35
+ });
36
+ throw ordered[0];
37
+ }
38
+ if (suspensions.length > 0) {
39
+ // Re-throw one suspension; pending map already holds every branch effect id.
40
+ throw suspensions[0];
41
+ }
42
+ // Declaration order.
43
+ const result = {};
44
+ for (const name of names)
45
+ result[name] = outputs[name];
46
+ return result;
47
+ }
@@ -0,0 +1,19 @@
1
+ /** Path, node key and iteration-vector helpers (workflows.md §6). */
2
+ export declare function joinPath(parent: string, part: string): string;
3
+ /**
4
+ * Map item path: `<map path>[index]/<each id>` (workflows.md §6).
5
+ * Example: `implement[2]/code`.
6
+ */
7
+ export declare function mapItemPath(mapPath: string, index: number, eachId: string): string;
8
+ /** Drop Map indices from a path to get the node key. */
9
+ export declare function nodeKeyOf(path: string): string;
10
+ /** Iteration vector string: enclosing Loop numbers outermost first, or "-" outside Loops. */
11
+ export declare function iterationsOf(vector: readonly number[]): string;
12
+ /** Effect id for a flow effect (workflows.md §10). */
13
+ export declare function flowEffectId(input: {
14
+ readonly turnId: string;
15
+ readonly segment: number;
16
+ readonly path: string;
17
+ readonly kind: string;
18
+ readonly iterations: string;
19
+ }): string;
@@ -0,0 +1,23 @@
1
+ /** Path, node key and iteration-vector helpers (workflows.md §6). */
2
+ export function joinPath(parent, part) {
3
+ return parent ? `${parent}/${part}` : part;
4
+ }
5
+ /**
6
+ * Map item path: `<map path>[index]/<each id>` (workflows.md §6).
7
+ * Example: `implement[2]/code`.
8
+ */
9
+ export function mapItemPath(mapPath, index, eachId) {
10
+ return `${mapPath}[${index}]/${eachId}`;
11
+ }
12
+ /** Drop Map indices from a path to get the node key. */
13
+ export function nodeKeyOf(path) {
14
+ return path.replace(/\[\d+]/g, "");
15
+ }
16
+ /** Iteration vector string: enclosing Loop numbers outermost first, or "-" outside Loops. */
17
+ export function iterationsOf(vector) {
18
+ return vector.length === 0 ? "-" : vector.join(".");
19
+ }
20
+ /** Effect id for a flow effect (workflows.md §10). */
21
+ export function flowEffectId(input) {
22
+ return `${input.turnId}:${input.segment}:flow:${input.path}:${input.kind}:${input.iterations}`;
23
+ }
@@ -0,0 +1,8 @@
1
+ import type { JsonValue } from "@nylorun/core/define";
2
+ import type { WorkflowSwitchNode } from "@nylorun/core";
3
+ import type { FlowContext } from "./context.js";
4
+ /**
5
+ * Switch: `fn` effect for `on`, select case or fail `switch.no-match`, run chosen case.
6
+ * The key is journaled so replay always takes the same case.
7
+ */
8
+ export declare function runSwitch(ctx: FlowContext, node: WorkflowSwitchNode["switch"], path: string, input: JsonValue): Promise<JsonValue>;
@@ -0,0 +1,35 @@
1
+ import { FlowNodeError } from "./types.js";
2
+ import { joinPath, nodeKeyOf } from "./paths.js";
3
+ import { runNode } from "./node.js";
4
+ /**
5
+ * Switch: `fn` effect for `on`, select case or fail `switch.no-match`, run chosen case.
6
+ * The key is journaled so replay always takes the same case.
7
+ */
8
+ export async function runSwitch(ctx, node, path, input) {
9
+ const key = await ctx.effect("fn", input, { path, key: `${nodeKeyOf(path)}/on` }, { role: "switch-on" });
10
+ if (typeof key !== "string") {
11
+ throw new FlowNodeError({
12
+ code: "fn.failed",
13
+ message: `Switch.on must return a string, got ${typeof key}`,
14
+ path,
15
+ });
16
+ }
17
+ let caseNode = node.cases[key];
18
+ let casePart = key;
19
+ if (!caseNode) {
20
+ if (node.default) {
21
+ caseNode = node.default;
22
+ casePart = "default";
23
+ }
24
+ else {
25
+ throw new FlowNodeError({
26
+ code: "switch.no-match",
27
+ message: `No Switch case matched key ${JSON.stringify(key)}`,
28
+ path,
29
+ });
30
+ }
31
+ }
32
+ // Selection is implied by the journaled `on` result; Runtime emits switch.selected.
33
+ const casePath = joinPath(path, casePart);
34
+ return runNode(ctx, caseNode, casePath, input);
35
+ }
@@ -0,0 +1,45 @@
1
+ import type { JsonValue } from "@nylorun/core/define";
2
+ import type { FlowCheckpoint } from "./checkpoint.js";
3
+ export type FlowRunResult = {
4
+ readonly status: "completed";
5
+ readonly output: JsonValue;
6
+ } | {
7
+ readonly status: "failed";
8
+ readonly error: {
9
+ readonly code: string;
10
+ readonly message: string;
11
+ readonly path?: string;
12
+ };
13
+ } | {
14
+ readonly status: "cancelled";
15
+ } | {
16
+ readonly status: "paused";
17
+ readonly pending: unknown;
18
+ };
19
+ export type FlowDurableResult = {
20
+ readonly status: "waiting" | "uncertain";
21
+ readonly checkpoint: FlowCheckpoint;
22
+ readonly effectIds: readonly string[];
23
+ } | {
24
+ readonly status: "completed" | "paused" | "cancelled";
25
+ readonly checkpoint: FlowCheckpoint;
26
+ readonly result: FlowRunResult;
27
+ } | {
28
+ readonly status: "failed";
29
+ readonly checkpoint: FlowCheckpoint;
30
+ readonly result: FlowRunResult;
31
+ /** Pending sibling effect ids to cancel after Parallel/Map fail-fast. */
32
+ readonly cancelEffectIds?: readonly string[];
33
+ };
34
+ export type FlowFailure = {
35
+ readonly code: string;
36
+ readonly message: string;
37
+ readonly path?: string;
38
+ };
39
+ /** Thrown when a node fails; unwinds to the engine root. */
40
+ export declare class FlowNodeError extends Error {
41
+ readonly failure: FlowFailure;
42
+ constructor(failure: FlowFailure);
43
+ }
44
+ /** Completed effect value that encodes a curated failure (executor / agent settle). */
45
+ export declare function failedValueOf(value: unknown): FlowFailure | undefined;
@@ -0,0 +1,22 @@
1
+ /** Thrown when a node fails; unwinds to the engine root. */
2
+ export class FlowNodeError extends Error {
3
+ failure;
4
+ constructor(failure) {
5
+ super(failure.message);
6
+ this.failure = failure;
7
+ this.name = "FlowNodeError";
8
+ }
9
+ }
10
+ /** Completed effect value that encodes a curated failure (executor / agent settle). */
11
+ export function failedValueOf(value) {
12
+ if (!value || typeof value !== "object")
13
+ return undefined;
14
+ const record = value;
15
+ if (record.kind !== "failed" || typeof record.code !== "string")
16
+ return undefined;
17
+ return {
18
+ code: record.code,
19
+ message: typeof record.message === "string" ? record.message : record.code,
20
+ ...(typeof record.path === "string" ? { path: record.path } : {}),
21
+ };
22
+ }
@@ -23,8 +23,11 @@ export interface HostEffect {
23
23
  readonly turnId: string;
24
24
  readonly agentId: string;
25
25
  readonly manifestHash: string;
26
- /** `delegation` journals when an agent used as a tool starts and settles; hosts record it and resolve it at once. */
27
- readonly kind: "model" | "tool" | "hook" | "delegation";
26
+ /**
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`, `tool` (node), `fn`, `verify` — each carries `path`, `key`, and `iterations`.
29
+ */
30
+ readonly kind: "model" | "tool" | "hook" | "delegation" | "agent" | "fn" | "verify";
28
31
  /** Set on work for an agent used as a tool; `agentId` stays the session's root agent. */
29
32
  readonly agent?: AgentRef;
30
33
  readonly capabilityId?: string;
@@ -35,6 +38,12 @@ export interface HostEffect {
35
38
  readonly scope: HookScope;
36
39
  readonly capabilityIds: readonly string[];
37
40
  };
41
+ /** Workflow node path (flow effects). */
42
+ readonly path?: string;
43
+ /** Workflow node key without Map indices (flow effects). */
44
+ readonly key?: string;
45
+ /** Iteration vector of enclosing Loops, outermost first (e.g. `"3"`, `"2.1"`); `"-"` outside Loops. */
46
+ readonly iterations?: string;
38
47
  readonly input: unknown;
39
48
  readonly context: Record<string, unknown>;
40
49
  }
@@ -29,5 +29,9 @@ 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
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";
33
37
  export type { ModelAdapter, ModelCandidate, ModelCall, ModelRequest } from "@nylorun/core/define";
package/dist/run/index.js CHANGED
@@ -36,3 +36,5 @@ 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";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nylorun/harness",
3
- "version": "0.18.0-beta",
3
+ "version": "0.19.1-beta",
4
4
  "description": "Nylorun's TypeScript agent execution engine. See github.com/nylorun/harness.",
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.4.0-beta"
79
+ "@nylorun/core": "0.6.0-beta"
80
80
  },
81
81
  "peerDependencies": {
82
82
  "zod": "^4.6.5"