@nylorun/harness 0.17.0-beta → 0.19.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 +30 -0
- package/HOST_CONTRACT.md +28 -5
- package/dist/compatibility.d.ts +2 -0
- package/dist/compatibility.js +2 -0
- package/dist/flow/chain.d.ts +8 -0
- package/dist/flow/chain.js +27 -0
- package/dist/flow/checkpoint.d.ts +21 -0
- package/dist/flow/checkpoint.js +15 -0
- package/dist/flow/context.d.ts +39 -0
- package/dist/flow/context.js +100 -0
- package/dist/flow/engine.d.ts +17 -0
- package/dist/flow/engine.js +57 -0
- package/dist/flow/index.d.ts +7 -0
- package/dist/flow/index.js +7 -0
- package/dist/flow/limits.d.ts +22 -0
- package/dist/flow/limits.js +41 -0
- package/dist/flow/loop.d.ts +31 -0
- package/dist/flow/loop.js +236 -0
- package/dist/flow/map.d.ts +7 -0
- package/dist/flow/map.js +64 -0
- package/dist/flow/node.d.ts +31 -0
- package/dist/flow/node.js +90 -0
- package/dist/flow/parallel.d.ts +7 -0
- package/dist/flow/parallel.js +47 -0
- package/dist/flow/paths.d.ts +19 -0
- package/dist/flow/paths.js +23 -0
- package/dist/flow/switch.d.ts +8 -0
- package/dist/flow/switch.js +35 -0
- package/dist/flow/types.d.ts +45 -0
- package/dist/flow/types.js +22 -0
- package/dist/loop/delegation.d.ts +32 -0
- package/dist/loop/delegation.js +136 -0
- package/dist/loop/dispatch.js +56 -0
- package/dist/loop/invocation.d.ts +7 -1
- package/dist/loop/invocation.js +2 -0
- package/dist/loop/run.d.ts +2 -1
- package/dist/loop/run.js +2 -2
- package/dist/run/durable.d.ts +16 -2
- package/dist/run/durable.js +109 -81
- package/dist/run/index.d.ts +4 -0
- package/dist/run/index.js +2 -0
- package/dist/types/execution.d.ts +3 -1
- package/dist/utils/ids.d.ts +2 -0
- package/dist/utils/ids.js +5 -0
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,35 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.19.0-beta
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 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.
|
|
8
|
+
|
|
9
|
+
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}/`.
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- Pin core to the tested release.
|
|
14
|
+
- Updated dependencies [c49efed]
|
|
15
|
+
- Updated dependencies [c49efed]
|
|
16
|
+
- Updated dependencies [fd9fd87]
|
|
17
|
+
- @nylorun/core@0.5.0-beta
|
|
18
|
+
|
|
19
|
+
## 0.18.0-beta
|
|
20
|
+
|
|
21
|
+
### Minor Changes
|
|
22
|
+
|
|
23
|
+
- 1cd7dc7: Add subagents: put an agent in another agent's `tools` (`Agent({ tools: [lookupOrder, researcher] })` or `.use({ tools: [researcher] })`) and the model can delegate to it. The tool is named after the agent's id, takes `{ task: string }`, and its description is the agent's `description`, which is now required for an agent used as a tool. The engine runs the child inside the parent's turn as a durable branch: fresh context, its own tools and hooks served by the root agent's executor, its own MCP servers, the session's sandbox, and only its final output (or `outputSchema` result) returned. Empty output, failures (with partial output marked as evidence), and requests for input or approval inside a child reach the parent as failed tool results. Parallel delegation calls run concurrently, completed child work is never re-run on replay, and cancelling the session cancels every child.
|
|
24
|
+
|
|
25
|
+
v1 is one level deep and non-interactive. Nested delegation, child tools that declare `approval`, and differing sandboxes across the tree fail the build with a named diagnostic. The manifest adds an optional `agent` body on a tool (schema version unchanged), actions and effects carry `agent: { id, path, delegationId }`, tool context gains `ctx.agent`, the durable host resolves a new `delegation` effect kind, and the Runtime emits `delegation.started` / `delegation.completed` events and filters history with `?agent=` (`session.history({ agent })`). Studio shows delegations, labels child actions with their agent, and filters events by agent.
|
|
26
|
+
|
|
27
|
+
### Patch Changes
|
|
28
|
+
|
|
29
|
+
- Pin core to the tested release.
|
|
30
|
+
- Updated dependencies [1cd7dc7]
|
|
31
|
+
- @nylorun/core@0.4.0-beta
|
|
32
|
+
|
|
3
33
|
## 0.17.0-beta
|
|
4
34
|
|
|
5
35
|
### 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/
|
|
8
|
-
|
|
9
|
-
Separate
|
|
10
|
-
|
|
11
|
-
|
|
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
|
|
|
@@ -22,6 +37,14 @@ A terminal/paused result includes `result.state`. Save it. A new message uses a
|
|
|
22
37
|
|
|
23
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.
|
|
24
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`.
|
|
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
|
+
|
|
25
48
|
## Definitions, validation, compatibility
|
|
26
49
|
|
|
27
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/dist/compatibility.d.ts
CHANGED
|
@@ -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";
|
package/dist/compatibility.js
CHANGED
|
@@ -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>;
|