@nylorun/harness 0.19.2-beta → 0.21.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 +125 -0
- package/HOST_CONTRACT.md +11 -11
- package/README.md +2 -2
- package/dist/compatibility.d.ts +12 -3
- package/dist/compatibility.js +11 -3
- package/dist/flow/checkpoint.d.ts +2 -2
- package/dist/flow/checkpoint.js +2 -2
- package/dist/flow/context.d.ts +1 -0
- package/dist/flow/context.js +1 -0
- package/dist/flow/engine.d.ts +3 -2
- package/dist/flow/engine.js +8 -4
- package/dist/flow/loop.d.ts +4 -0
- package/dist/flow/loop.js +3 -1
- package/dist/flow/map.js +1 -1
- package/dist/flow/node.js +27 -4
- package/dist/flow/paths.d.ts +6 -1
- package/dist/flow/paths.js +7 -2
- package/dist/flow/types.d.ts +1 -1
- package/dist/flow/types.js +1 -1
- package/dist/flow/v2.d.ts +12 -0
- package/dist/flow/v2.js +370 -0
- package/dist/loop/compaction/index.d.ts +49 -0
- package/dist/loop/compaction/index.js +288 -0
- package/dist/loop/delegation.d.ts +14 -0
- package/dist/loop/delegation.js +39 -15
- package/dist/loop/model/normalize.js +1 -0
- package/dist/loop/model/project.js +34 -5
- package/dist/loop/run.js +58 -0
- package/dist/loop/step/run.js +9 -1
- package/dist/loop/transcript.js +20 -0
- package/dist/run/durable.d.ts +6 -1
- package/dist/run/durable.js +14 -3
- package/dist/types/execution.d.ts +8 -0
- package/package.json +4 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,130 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.21.0-beta
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 6ab4c59: **Long sessions on any model: compaction.** A session whose history outgrows the model's context window keeps going, on a 16k local model as on a 1M hosted one.
|
|
8
|
+
|
|
9
|
+
- **Compaction.**
|
|
10
|
+
- **When.** Before each model call the engine estimates the prompt: the last reported usage, plus about four characters per token for what came after. If the estimate would not leave room for the reply, the engine first compacts: it asks the model to summarize the older history, then keeps about the newest 20,000 tokens (at most 30% of the window) verbatim.
|
|
11
|
+
- **What it keeps.** The cut never separates a tool call from its result. The current turn's request is always kept. A later compaction merges with the earlier summary.
|
|
12
|
+
- **Overflow.** If a provider still reports a context overflow, the engine compacts once and asks again.
|
|
13
|
+
- **Storage.** The summary is a `compaction` transcript entry that replaces the older entries in the session state; the event log keeps the full history. The summary call is a journaled model effect, so replays are deterministic.
|
|
14
|
+
- **New event.** `context.compacted` (`trigger`, `tokensBefore`, `tokensAfter`).
|
|
15
|
+
- **Custom endpoints.**
|
|
16
|
+
- **Settings.** Model Settings take `settings: { contextWindow, maxTokens, reasoning, compat }` for a custom OpenAI-compatible provider (vLLM, SGLang, llama.cpp, Ollama, LM Studio). `compat` is passed to pi-ai: `thinkingFormat`, `thinkingTokenBudgetField`, `chatTemplateKwargs` and the rest.
|
|
17
|
+
- **Defaults.** Without settings, a custom endpoint is assumed to have a 32k window and an 8k output limit. They used to be 128k and 16k.
|
|
18
|
+
- **Where to set them.** `nylo configure` asks for the window and output limit. Studio's Model Settings shows all four fields.
|
|
19
|
+
- **Storage.**
|
|
20
|
+
- Model effects no longer journal the model request next to the call, so each call's prompt is stored once.
|
|
21
|
+
- When a turn ends, its model effects are slimmed to their identity and status; the transcript holds the answers.
|
|
22
|
+
- Session storage now grows with the window, not with the square of the session's length.
|
|
23
|
+
- **Core.**
|
|
24
|
+
- `TranscriptEntry` adds `compaction` (`TranscriptCompactionEntry`).
|
|
25
|
+
- `ModelAdapterContext.compaction` marks a summary call.
|
|
26
|
+
- `CustomModelSettings` / `CustomModelSettingsSchema` describe the custom endpoint settings.
|
|
27
|
+
|
|
28
|
+
- 6ab4c59: **Model calls don't strand sessions.** A model provider failure is now a known outcome, not a lost call. The Runtime retries what can be retried, and otherwise fails the turn with `model.<code>`, so the session accepts the next message instead of sitting `uncertain` until it is cancelled.
|
|
29
|
+
|
|
30
|
+
- **Runtime.**
|
|
31
|
+
|
|
32
|
+
- **Upgrade.** The model adapter moves to pi-ai 0.99.1 and always streams.
|
|
33
|
+
- **Per-call settings.**
|
|
34
|
+
- Every call carries the session id, so OpenAI and other providers reuse the prompt cache and route to the same backend.
|
|
35
|
+
- Provider auth no longer reads the process environment.
|
|
36
|
+
- Rate limits, overloads, timeouts and transient errors are retried: 3 attempts with backoff, honouring `Retry-After`.
|
|
37
|
+
- A stream that produces nothing for 300 s is aborted and retried. `TenantConfig.modelCall` sets attempts, backoff, the idle timeout and the request timeout.
|
|
38
|
+
- **Failures.** Anything else fails the turn with one of these codes:
|
|
39
|
+
|
|
40
|
+
- `model.context_overflow`, `model.rate_limited`, `model.overloaded`, `model.timeout`, `model.transient`
|
|
41
|
+
- `model.content_policy`, `model.auth` (whose message says where to fix the credential)
|
|
42
|
+
- `model.invalid_request`, `model.invalid_output`
|
|
43
|
+
|
|
44
|
+
Only a call whose outcome was lost, such as a Worker dying mid-call, is still `uncertain`.
|
|
45
|
+
|
|
46
|
+
- **Structured output.** A structured final answer is repaired (control characters, a Markdown code fence) before it is parsed.
|
|
47
|
+
- **Model history.** Replayed history keeps the model that produced each message, so a model switch no longer sends one model's signatures or tool-call ids to another. Reasoning from OpenAI-compatible servers (`reasoning_content`, `reasoning`) is sent back only within the turn that produced it.
|
|
48
|
+
|
|
49
|
+
- **Events.**
|
|
50
|
+
- `message.assistant` adds `model` (`provider`, `model`), `finishReason` and `usage`.
|
|
51
|
+
- A new `model.failed` transcript event (`code`, `message`, `retryable`) is written instead of `message.assistant` when a call fails.
|
|
52
|
+
- **Core and harness.**
|
|
53
|
+
- New types and helpers: `ModelFailureOutcome`, `ModelFailureCode`, `MODEL_FAILURE_CODES`, `isModelFailureOutcome`, `ModelProducer`.
|
|
54
|
+
- `PromptItem` assistant messages may carry `producer`.
|
|
55
|
+
- `ModelUsage` adds `cacheWriteTokens`.
|
|
56
|
+
- A model adapter may return a failure outcome.
|
|
57
|
+
- The durable engine version is `hosted-3`: a turn that is running when the Runtime is upgraded fails once with `execution.incompatible`, and the next message works.
|
|
58
|
+
- **CLI.**
|
|
59
|
+
- `nylo configure` passes a stable installation id to OAuth logins that need one (OpenAI "Sign in with ChatGPT"), stored as `cli-installation-id` in the Host root.
|
|
60
|
+
- A custom OpenAI-compatible provider now prompts for its API key instead of failing.
|
|
61
|
+
|
|
62
|
+
- 6ab4c59: **Long turns roll over.** A turn no longer fails when it runs past the 50-minute advance deadline.
|
|
63
|
+
|
|
64
|
+
- **How it works.** At a step boundary with no open work, a long turn ends its segment and continues in the next one: same turn, a new checkpoint, woken at once. By default this happens after 50 steps or 20 minutes in a segment; `TenantConfig.rollover` changes both.
|
|
65
|
+
- **What clients see.** A rolled-over turn emits no `turn.*` event, and clients still see one turn.
|
|
66
|
+
- **Storage.** Each finished segment's model effects are slimmed.
|
|
67
|
+
- **Harness.** `runDurable` takes `yieldAfter: { steps, ms }` and can return `yielded`, and `RunResult` adds `yielded`. The durable host writes the next checkpoint at `segment + 1` with `{ kind: "continue" }`. Agents used as tools never roll over.
|
|
68
|
+
|
|
69
|
+
### Patch Changes
|
|
70
|
+
|
|
71
|
+
- Pin core to the tested release.
|
|
72
|
+
- Updated dependencies [c7614a4]
|
|
73
|
+
- Updated dependencies [679c488]
|
|
74
|
+
- Updated dependencies [c85cd9e]
|
|
75
|
+
- Updated dependencies [4282d5f]
|
|
76
|
+
- Updated dependencies [82d95ef]
|
|
77
|
+
- Updated dependencies [f48f12f]
|
|
78
|
+
- Updated dependencies [50d0fb5]
|
|
79
|
+
- Updated dependencies [50d0fb5]
|
|
80
|
+
- Updated dependencies [c121144]
|
|
81
|
+
- Updated dependencies [6ab4c59]
|
|
82
|
+
- Updated dependencies [6ab4c59]
|
|
83
|
+
- Updated dependencies [2ab8ed1]
|
|
84
|
+
- Updated dependencies [c121144]
|
|
85
|
+
- Updated dependencies [9546ac7]
|
|
86
|
+
- Updated dependencies [9546ac7]
|
|
87
|
+
- Updated dependencies [9d52189]
|
|
88
|
+
- Updated dependencies [50d0fb5]
|
|
89
|
+
- Updated dependencies [18468d9]
|
|
90
|
+
- @nylorun/core@0.9.0-beta
|
|
91
|
+
|
|
92
|
+
## 0.20.0-beta
|
|
93
|
+
|
|
94
|
+
### Minor Changes
|
|
95
|
+
|
|
96
|
+
- 5278b4e: **Flow agents on workflow manifest v2.** A flow agent compiles to `workflowSchemaVersion: 2` and runs on the new `flow-2` engine; v1 workflows (`Chain`, `Switch`, `Parallel`, `Map`, `Loop`) keep running on `flow-1`, so in-flight runs finish as they began.
|
|
97
|
+
|
|
98
|
+
- **Manifest (core).** Any node may carry `id` and `input`; there are no slots. `chain` and `parallel` are bare collections, a Map is `{ map: { each } }` over its input, and a Loop has `max?` and `decide?`. The header adds `name`, `description`, `metadata`, `inputSchema` and `outputSchema`, and `agents` embeds every agent the flow runs, so one manifest hash covers the whole flow. `Agent.from(json, { nodes, agents })` rebuilds a flow agent. Path and key helpers (`leafPath`, `stageKey`, `forEachFlowNode`, `embeddedAgent`, …) are exported from `@nylorun/core/define`.
|
|
99
|
+
- **Paths (harness).** Linked agent sessions are named by the agent: its id, `[i]` per Map item, and a nested flow agent's id in front. Control stages add nothing, so wrapping a step in a Loop keeps its session. Functions are bound under stage keys (`route:on`, `@1.default.1:input`) and all receive `{ input, results, flowInput }`; `flowInput` works inside nested `flow()`. A Loop without `decide` retries with the verifier's feedback up to `max` and then fails with `loop.exhausted`. Nested flow agents run inline.
|
|
100
|
+
- **Runtime.** Leaves of a v2 workflow resolve from its embedded `agents` (with the workflow's plugin roots, keyed `<agent>/<capability>`) instead of the registry. `loop.iteration` is emitted only for a Loop's own agent turns.
|
|
101
|
+
- **Agents SDK.** `saveAgent(flowAgent)` PUTs one document; application mode registers the flow's executor with its manifest hash. An executor leaves `fn`, `verify` and tool actions of a v2 flow unclaimed when they belong to another manifest hash, because stage keys can shift between deploys; it reports each skipped action once through `onError`.
|
|
102
|
+
- **Studio.** Draws v2 manifests: agents and tools at their session paths, control stages at their stage keys, nested flow agents inline, and lights a Map's agent from its item sessions.
|
|
103
|
+
- Build diagnostics: `flow.duplicate-leaf`, `flow.duplicate-id`, `flow.agent-conflict`, `flow.v1-workflow`, `loop.invalid-verify`, `workflow.flow-agent-child`. Also fixes v1 flows passing an agent step's output to the next step still wrapped in the runtime's turn marker.
|
|
104
|
+
|
|
105
|
+
- 426fd27: **Flow agents as subagents.** `.subagents(flowAgent)` lets a ReAct agent delegate to a flow agent. The flow's workflow manifest v2 is inlined in the delegating tool (`ToolManifest.agent` may be a workflow manifest), so it is saved with the parent and served by the parent's executor, plugin roots included (`<flow>/<agent>/<capability>`).
|
|
106
|
+
|
|
107
|
+
- **Engine (harness).** A call to a flow subagent is one durable `agent` effect (`role: "delegate"`) between the delegation's start and settle points; the flow's output is the tool result, and a failed flow is a failed tool result. Local `run()` refuses flow subagents, which need the Runtime.
|
|
108
|
+
- **Runtime.** The effect starts a linked flow session from the parent's pinned manifest, fresh per call, and settles when the flow's turn ends. Cancelling any session now cascades to the linked sessions it started, not only a workflow's.
|
|
109
|
+
- **Core.** `delegation.flow-unsupported` now only reports a workflow built with `Chain`, `Switch`, `Parallel`, `Map` or `Loop`. New helpers: `flowDelegatesOf`, `flowDelegateManifest`, `isFlowDelegate`; `delegatesOf` lists only the ReAct agents run in-process.
|
|
110
|
+
|
|
111
|
+
### Patch Changes
|
|
112
|
+
|
|
113
|
+
- 8cda500: **Workflow functions and tool steps reach the executor.** Several workflow nodes asked the executor for a key that core never registered, so the executor never found the function and the turn waited forever.
|
|
114
|
+
|
|
115
|
+
- A Map's `over` and a slot's `input` now use the keys core registers (`<path>/over`, `<path>/input`), as Switch's `on` already did.
|
|
116
|
+
- A slot `input` that wraps a Map or Switch gets its own effect id, so it no longer collides with the `over` or `on` effect on the same path.
|
|
117
|
+
- A slot `id` that renames a nested workflow now renames the keys inside it too.
|
|
118
|
+
- A verifier slot's `input` is keyed under the verifier's path (`<loop>/<part>/input`).
|
|
119
|
+
- A tool step passes its output to the next step, not the `{ kind: "completed", output }` outcome around it. A denied tool call fails the flow with `tool.denied`.
|
|
120
|
+
|
|
121
|
+
- Pin core to the tested release.
|
|
122
|
+
- Updated dependencies [e537a82]
|
|
123
|
+
- Updated dependencies [5278b4e]
|
|
124
|
+
- Updated dependencies [426fd27]
|
|
125
|
+
- Updated dependencies [8cda500]
|
|
126
|
+
- @nylorun/core@0.8.0-beta
|
|
127
|
+
|
|
3
128
|
## 0.19.2-beta
|
|
4
129
|
|
|
5
130
|
### Patch Changes
|
package/HOST_CONTRACT.md
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
# Durable execution and session protocol — beta freeze
|
|
2
2
|
|
|
3
|
-
Artifact: `@nylorun/harness@0.14.0-beta.3`. Package version is separate from protocol 1, definition schema 4, durable checkpoint 1 / engine `hosted-
|
|
3
|
+
Artifact: `@nylorun/harness@0.14.0-beta.3`. Package version is separate from protocol 1, definition schema 4, durable checkpoint 1 / engine `hosted-3`, and inner execution checkpoint 1. Public execution API and shared contracts are the compatibility boundary. Cloud installs published npm packages and does not import the OSS Runtime.
|
|
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, optional `sandbox
|
|
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` — `false`, `{ session }` to share another session's sandbox (same owner), or an inline `{ image?, network?: { allow }, resources? }` checked against the Tenant's limits; omitted means the Tenant default; fixed for the session's life); `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. 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/endpoints` (`PutEndpointsRequest`: endpoints of agentId, url, implementationVersion, optional manifestHash, timeoutMs and maxConcurrent) registers the Action endpoint that runs each agent's Actions and returns them with their health; `GET /v1/endpoints` lists them, `DELETE /v1/endpoints/:agentId` removes one, and `POST /v1/endpoints/:agentId/ping` sends a signed ping through it. Registering an endpoint delivers the agent's pending Actions. Only application principals, never subjects, manage endpoints.
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
**Action endpoints (protocol 3).** The Runtime POSTs each Action to its agent's endpoint as `ActionDelivery` `{type: "action", action, sandbox}` (or `{type: "ping"}`), signed with a delivery token in `Nylorun-Signature`: an ES256 JWT (`typ` `nylorun-delivery+jwt`, `kid` from the Tenant's public JWKS at `GET /v1/access/jwks`, readable without a credential) whose `aud` is the registered URL, `sub` the Action id (or `ping`), `gen` the delivery generation, `bdy` the base64url SHA-256 of the body, and `exp` at most 900 s ahead. Before sending, the Action becomes `delivering` with a new `generation` and a `deadlineAt`, and `action.delivered` is published. The endpoint answers `200` with the tool value (with `Nylorun-Outcome: 1`, a tagged outcome), `202` to finish in the background, `409` when it serves a different manifest (retried), `429`/`503` to be retried later, or another `4xx` to fail the Action (`endpoint.rejected`). A background delivery keeps its deadline with `POST /v1/actions/:id/heartbeat` (delivery token; returns `{token, deadlineAt}`, `409` once the Action was cancelled, lost or delivered again) and settles with `POST /v1/actions/:id/result` `{value}`, whose receipt is idempotent. The delivery token authorizes only those routes and `POST /v1/actions/:id/sandbox/:tool` for its own Action and generation, and is refused from browsers. A delivery that may have been received but was never answered is lost: a `tool` becomes `uncertain`; a `hook`, `fn` or `verify` returns to pending and is delivered again, and the new generation fences the earlier one. An endpoint that cannot be reached is retried with backoff and `action.delivery_failed`. Cancelling a turn aborts its deliveries. Action rows may use `kind` `tool` | `hook` | `fn` | `verify`; workflow code carries `path` and `key` instead of `capabilityId` / `toolName`.
|
|
10
10
|
|
|
11
11
|
**Tenant and protocol headers.** Every Tenant route requires `Nylorun-Tenant`
|
|
12
12
|
(Tenant id matching `tn_` + 26 Crockford chars) and `Nylorun-Protocol` (client
|
|
@@ -25,28 +25,28 @@ version, `hostId`, pid, and `protocol: { min, max, features }` (plus diagnostic
|
|
|
25
25
|
still works. `GET /ready` is `200` only after the listener is up and Tenant
|
|
26
26
|
discovery has finished.
|
|
27
27
|
|
|
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
|
|
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 background result posted again for the same delivery returns its original receipt; a different outcome, or a result for a lost, cancelled or redelivered generation, is rejected (`409`). Heartbeat cannot resurrect a lost delivery. Lost tool work is uncertain, not automatically delivered again. A lost `hook` action returns to pending and is delivered again, because hooks are pure by contract. Results after cancellation cannot resume a turn. Only a delivery token can submit an action result. No hardcoded production credentials.
|
|
29
29
|
|
|
30
30
|
## Engine host
|
|
31
31
|
|
|
32
|
-
`createDurableCheckpoint({manifest,sessionId,turnId,input,state?,info?,segment?})`, `runDurable({manifest,checkpoint,host,signal?,sessionTools?})` from `/run`. `DurableHost.resolveEffect(HostEffect)` atomically creates or reads an individually identified effect and returns `{status:'completed',outcome:{value,statePatch?}}` or `{status:'pending'|'uncertain'}`. Model effect `input` is the complete ModelCall (instructions/history/tools/output schema); context contains a
|
|
32
|
+
`createDurableCheckpoint({manifest,sessionId,turnId,input,state?,info?,segment?})`, `runDurable({manifest,checkpoint,host,signal?,sessionTools?})` from `/run`. `DurableHost.resolveEffect(HostEffect)` atomically creates or reads an individually identified effect and returns `{status:'completed',outcome:{value,statePatch?}}` or `{status:'pending'|'uncertain'}`. Model effect `input` is the complete ModelCall (instructions/history/tools/output schema); context contains invocationId and, for a call that summarizes history, `compaction: {trigger, tokensBefore, keptTokens}` (its invocationId starts with `compaction-`). When history no longer fits the model's window, the engine replaces the older transcript entries with one `compaction` entry and keeps the rest; hosts publish `context.compacted` for such a call instead of `message.assistant`. Its completed value is a ModelCandidate, a string, or a failure outcome `{kind:'failed', code, message, retryable, retryAfterMs?}` for a provider failure the Runtime classified (codes in `MODEL_FAILURE_CODES`); the engine fails the step with `model.<code>`. A classified failure is a known outcome, not a lost one, so it is never `uncertain`. Runtime provider code owns credentials and invocation. Tool effects have capabilityId, toolName, serialized input and context. Tool result value is a ToolOutcome or a plain tool output; statePatch contains changed session keys. A `hook` effect runs one hook point for every capability that registered it: `hook` is `{at: "before"|"after", scope: "turn"|"step", capabilityIds}` in manifest order, and its effect id ends in a stable name (`before-turn`, `before-step:<stepId>`, `after-step:<stepId>`, `after-turn:<stepId>`). Its completed value is `{results: {[capabilityId]: Patch | Decision | TurnDecision}}`. `before-turn` is issued only in a turn's first segment. Tool context includes invocationId, resume, state, info and stable idempotencyKey. Customer implementationVersion is pinned by the runtime outside durable checkpoints.
|
|
33
33
|
|
|
34
34
|
Persist checkpoint BEFORE scheduling, effect intent BEFORE provider invocation or notification, and outcome BEFORE resumption. Journaling an entire runDurable call as one replayable operation is forbidden. The durable path deterministically reconstructs a segment from its immutable starting checkpoint and individually cached effect outcomes. A waiting result returns that starting checkpoint: do not replace it with an intermediate preview. The journal is required continuation data and must be retained with the checkpoint. Stable IDs include turn/segment and deterministic invocation identity. There is no live continuation or request-held promise while waiting. Runtimes serialize work per session, check cancellation before effects and before settlement, and fence ownership. Lost provider acknowledgement becomes uncertain; do not repeat it merely because a worker restarts.
|
|
35
35
|
|
|
36
|
-
A terminal/paused result includes `result.state`. Save it. A new message uses a new turnId with prior completed state. Approval/response resumes paused state via a new checkpoint, same turnId, `segment + 1`, with `{kind:'approve',interactionId,approved}` or `{kind:'respond',interactionId,value}`. An action result simply reruns the SAME suspended checkpoint/segment after recording the outcome. Paused plan records pending interactions/deferred calls; waiting on remote action is distinct from a human wait. Cancellation is host-owned and must fence both running and pending work. Runtime supplies canonical events; execution observations are not wire events and reconstruction must not republish duplicate history.
|
|
36
|
+
A terminal/paused result includes `result.state`. Save it. A new message uses a new turnId with prior completed state. Approval/response resumes paused state via a new checkpoint, same turnId, `segment + 1`, with `{kind:'approve',interactionId,approved}` or `{kind:'respond',interactionId,value}`. An action result simply reruns the SAME suspended checkpoint/segment after recording the outcome. `runDurable({yieldAfter: {steps, ms}})` lets a long turn end a segment at a step boundary with status `yielded` (Model Calls §10): the result state is mid-turn (status `active`, `turn` kept); save it, write a new checkpoint for the same turnId at `segment + 1` with input `{kind:'continue'}`, and schedule it. A yielded segment emits no `turn.*` event, and its effects are never read again. Paused plan records pending interactions/deferred calls; waiting on remote action is distinct from a human wait. Cancellation is host-owned and must fence both running and pending work. Runtime supplies canonical events; execution observations are not wire events and reconstruction must not republish duplicate history.
|
|
37
37
|
|
|
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,
|
|
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, delivery policy and reconciliation remain runtime-owned.
|
|
39
39
|
|
|
40
|
-
Agents used as tools: a manifest tool with an `agent` body (the child manifest inlined; name equals the child id, description equals the child description, input is the standard `{task}` schema, no outputSchema, no nested agent tools, identical sandbox specs across the tree) is run by the engine inside the parent's `runDurable`, never
|
|
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 — in a session opened with a sandbox the Runtime adds the same `nylorun.sandbox` capability to the root and each inlined child) is run by the engine inside the parent's `runDurable`, never delivered to an endpoint. Its model, tool and hook effects carry `agent: {id, path, delegationId}` (`delegationId` is the parent tool call's invocationId), keep the root `agentId` and `manifestHash`, and use identity `<delegationId>/<inner identity>`; tool context `idempotencyKey` is prefixed the same way. Hosts resolve child effects against the child manifest (`delegateManifest`) for pinned tool schemas, sandbox and MCP routing, copy `agent` onto the Action, and include it in action event payloads. A `delegation` effect (identity `<delegationId>:started` or `<delegationId>:settled`, input `{task}` or `{status, outcome}`) must be recorded completed immediately with value null and publish `delegation.started` / `delegation.completed` exactly once; the journal makes replays silent. `DurableSessionTool.agentId` attaches discovered MCP tools to a child; MCP snapshot records and diagnostics carry `agentId`, and child plugin roots are keyed `<childId>/<capabilityId>`. Children share the session sandbox. `GET /v1/sessions/:id/items?agent=` filters history by `payload.agent.delegationId` or `payload.agent.path`. Existing checkpoints are unaffected; engine version stays `hosted-2`. A tool whose `agent` body is a flow agent (workflow manifest v2) is not run in-process: the engine issues one `agent` effect (identity `<delegationId>:flow`, input `{agentId, input: task, path}`, context `{role: "delegate", delegationId}`, `agent` ref set) between the `delegation` start and settle points. The host starts a linked flow session from the pinned parent manifest's inlined flow (session id `derive(parentSessionId, path, "delegate", delegationId)`, plugin roots under `<flowId>/`), sends the task as its message, and completes the effect with the flow's output, or `{kind: "failed", code, message}`, when its turn ends. Cancelling the parent cascades to linked sessions.
|
|
41
41
|
|
|
42
|
-
**Workflows (flow engine).** Definitions with `kind: "workflow"` run through `createFlowCheckpoint` / `runFlowDurable` from `/run` (same `DurableResult` shape as `runDurable`). The turn loop in `harness/src/loop/` is unchanged. Flow effects extend `HostEffect.kind` with `agent`, `tool` (workflow tool node), `fn`, and `verify`. Each carries `path` (node address), `key` (path without Map indices), and `iterations` (enclosing Loop vector as a dotted string, or `"-"` outside Loops). Effect ids are `${turnId}:${segment}:flow:${path}:${kind}:${iterations}`. The host resolves `agent` effects only through the public session contract (create linked session, message with derived idempotency key, settle on linked `turn.completed` / failed / cancelled). `tool`, `fn`, and `verify` become Actions
|
|
42
|
+
**Workflows (flow engine).** Definitions with `kind: "workflow"` run through `createFlowCheckpoint` / `runFlowDurable` from `/run` (same `DurableResult` shape as `runDurable`). The turn loop in `harness/src/loop/` is unchanged. Flow effects extend `HostEffect.kind` with `agent`, `tool` (workflow tool node), `fn`, and `verify`. Each carries `path` (node address), `key` (path without Map indices), and `iterations` (enclosing Loop vector as a dotted string, or `"-"` outside Loops). Effect ids are `${turnId}:${segment}:flow:${path}:${kind}:${iterations}`. On workflow manifest v2 (engine `flow-2`), an `agent` or `tool` effect's `path` is the leaf path (the leaf's id, `[i]` per Map item, nested flow agent ids in front) and its `key` drops the indices; an `fn` or `verify` effect's `key` is the stage key plus `:input`, `:on`, `:verify` or `:decide`, and its `path` is the stage's site plus the same suffix. v2 `agent` effect input adds `flow` (nested flow agent ids, outermost first); the host resolves the leaf from the workflow manifest's embedded `agents` (`embeddedAgent`) and gives the linked session the leaf's manifest, its hash, and the workflow's plugin roots under `<agentId>/`. Checkpoints pin the engine: v1 manifests run on `flow-1`, v2 on `flow-2`. An Action endpoint answers `409` to v2 flow actions whose `manifestHash` is not the manifest it serves, and the Runtime delivers them again later. 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 delivered to the workflow's endpoint; Actions use `path` + `key` instead of `capabilityId` + `toolName`. `fn` and `verify` are pure or repeat-safe: a lost delivery returns them to pending and they are delivered again; tool nodes become `uncertain` and are never re-run automatically. Parallelism comes from pending effects returned together; the Runtime caps concurrency with `RuntimeOptions.flow` / env (`maxConcurrency`, `maxMapItems`, `maxLoopIterations`).
|
|
43
43
|
|
|
44
44
|
**Turn manifests.** A `message` command may include optional `manifest`. Any app may use it (not only Loops). When present, the Runtime parses it with `AgentManifestSchema`, requires it to be a **variant** of the session's pinned manifest (id fixed; tools/skills/delegates may only shrink; hooks, MCP, and sandbox must not change), hashes and stores it by hash for that turn only (it does not latch — a later message without `manifest` uses the pin), and rebases `state.manifestHash` at turn start when the prior state hash and the turn hash are both the pin or validated variants of it. Invalid variants fail closed (`loop.invalid-agent` when a Loop decide supplies one).
|
|
45
45
|
|
|
46
|
-
**Shared sandbox.**
|
|
46
|
+
**Shared sandbox.** Definitions declare no sandbox; a session is opened with one (`PutSessionRequest.sandbox`), resolved against the Tenant's limits and pinned on the session. An agent session's pinned manifest is its definition plus capability `nylorun.sandbox` (the six built-ins, the sandbox instructions and the resolved spec), so its hash differs from the definition's; a workflow session's manifest is unchanged and its sandbox is stored beside it. A tree has one sandbox, keyed by the owning session id. `sandbox: { session }` attaches another session's sandbox (same `ownerUserId`, same Tenant); a session whose definition declares none inherits the owner's spec and tools. Linked agent sessions created for agent nodes attach with `sandbox: { session: workflowSessionId }` and inherit the same way. Application principals call `POST /v1/sessions/:id/sandbox/:tool` (`bash` | `read` | `write` | `edit` | `grep` | `glob`); refused while that session has an active agent turn. Action endpoints call `POST /v1/actions/:id/sandbox/:tool` with the delivery token, while that generation is being delivered; 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. Registration refuses a definition that declares a sandbox; definitions stored before Sandboxes v3 keep theirs.
|
|
47
47
|
|
|
48
48
|
## Definitions, validation, compatibility
|
|
49
49
|
|
|
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.
|
|
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. Actions are delivered to the endpoint registered for their 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.
|
|
51
51
|
|
|
52
52
|
No session migration, arbitrary checkpoint migration, broad model-support, or conformance claims follow from compiling this interface. Studio and conformance tooling remain outside production harness.
|
package/README.md
CHANGED
|
@@ -90,7 +90,7 @@ often your code runs:
|
|
|
90
90
|
|
|
91
91
|
`Patch` is capabilities/tools/instructions/state/block, with no `model`. Registered
|
|
92
92
|
hooks are listed in the manifest (`capabilities[].hooks`). In a Runtime each hook point
|
|
93
|
-
is one
|
|
93
|
+
is one delivery to your Action endpoint per turn or per model call, whatever the
|
|
94
94
|
number of capabilities using it, so prefer `"turn"` when a decision does not change
|
|
95
95
|
within a turn.
|
|
96
96
|
|
|
@@ -107,4 +107,4 @@ Local explicit engine execution retains middleware. Durable manifests reject arb
|
|
|
107
107
|
|
|
108
108
|
## Client types
|
|
109
109
|
|
|
110
|
-
The authoritative session/action wire schemas live in `/contracts` and do not import durable checkpoint types. Use `@nylorun/agents` for the session client and
|
|
110
|
+
The authoritative session/action wire schemas live in `/contracts` and do not import durable checkpoint types. Use `@nylorun/agents` for the session client and the Action endpoint (`createActionHandler`). Historical root client types remain for deferred local tooling; they are not the new wire contract.
|
package/dist/compatibility.d.ts
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
export { checkCompatibility } from "./definition/compatibility.js";
|
|
2
2
|
export declare const CHECKPOINT_VERSION = 1;
|
|
3
|
-
export declare const ENGINE_VERSION = "hosted-
|
|
4
|
-
/**
|
|
5
|
-
|
|
3
|
+
export declare const ENGINE_VERSION = "hosted-3";
|
|
4
|
+
/**
|
|
5
|
+
* Flow engine version pinned on workflow checkpoints. Workflow manifest v2 runs on
|
|
6
|
+
* `flow-2`; v1 manifests keep running on `flow-1`, so in-flight v1 runs finish as they began.
|
|
7
|
+
*/
|
|
8
|
+
export declare const FLOW_ENGINE_VERSION = "flow-2";
|
|
9
|
+
export declare const FLOW_ENGINE_VERSION_V1 = "flow-1";
|
|
10
|
+
export type FlowEngineVersion = typeof FLOW_ENGINE_VERSION | typeof FLOW_ENGINE_VERSION_V1;
|
|
11
|
+
/** The engine a workflow manifest runs on. */
|
|
12
|
+
export declare function flowEngineVersionOf(manifest: {
|
|
13
|
+
readonly workflowSchemaVersion: number;
|
|
14
|
+
}): FlowEngineVersion;
|
package/dist/compatibility.js
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
export { checkCompatibility } from "./definition/compatibility.js";
|
|
2
2
|
export const CHECKPOINT_VERSION = 1;
|
|
3
|
-
export const ENGINE_VERSION = "hosted-
|
|
4
|
-
/**
|
|
5
|
-
|
|
3
|
+
export const ENGINE_VERSION = "hosted-3";
|
|
4
|
+
/**
|
|
5
|
+
* Flow engine version pinned on workflow checkpoints. Workflow manifest v2 runs on
|
|
6
|
+
* `flow-2`; v1 manifests keep running on `flow-1`, so in-flight v1 runs finish as they began.
|
|
7
|
+
*/
|
|
8
|
+
export const FLOW_ENGINE_VERSION = "flow-2";
|
|
9
|
+
export const FLOW_ENGINE_VERSION_V1 = "flow-1";
|
|
10
|
+
/** The engine a workflow manifest runs on. */
|
|
11
|
+
export function flowEngineVersionOf(manifest) {
|
|
12
|
+
return manifest.workflowSchemaVersion === 2 ? FLOW_ENGINE_VERSION : FLOW_ENGINE_VERSION_V1;
|
|
13
|
+
}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import type { JsonValue } from "@nylorun/core/define";
|
|
2
2
|
import { type WorkflowManifest } from "@nylorun/core/contracts";
|
|
3
|
-
import {
|
|
3
|
+
import { type FlowEngineVersion } from "../compatibility.js";
|
|
4
4
|
/** Private persistence contract for workflow sessions; not a session wire type. */
|
|
5
5
|
export interface FlowCheckpoint {
|
|
6
6
|
readonly version: 1;
|
|
7
|
-
readonly engineVersion:
|
|
7
|
+
readonly engineVersion: FlowEngineVersion;
|
|
8
8
|
readonly manifestHash: string;
|
|
9
9
|
readonly sessionId: string;
|
|
10
10
|
readonly turnId: string;
|
package/dist/flow/checkpoint.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { WorkflowManifestSchema } from "@nylorun/core/contracts";
|
|
2
2
|
import { hashManifest } from "@nylorun/core/define";
|
|
3
|
-
import { CHECKPOINT_VERSION,
|
|
3
|
+
import { CHECKPOINT_VERSION, flowEngineVersionOf, } from "../compatibility.js";
|
|
4
4
|
export function createFlowCheckpoint(input) {
|
|
5
5
|
WorkflowManifestSchema.parse(input.manifest);
|
|
6
6
|
return {
|
|
7
7
|
version: CHECKPOINT_VERSION,
|
|
8
|
-
engineVersion:
|
|
8
|
+
engineVersion: flowEngineVersionOf(input.manifest),
|
|
9
9
|
manifestHash: hashManifest(input.manifest),
|
|
10
10
|
sessionId: input.sessionId,
|
|
11
11
|
turnId: input.turnId,
|
package/dist/flow/context.d.ts
CHANGED
package/dist/flow/context.js
CHANGED
package/dist/flow/engine.d.ts
CHANGED
|
@@ -4,8 +4,9 @@ import type { FlowCheckpoint } from "./checkpoint.js";
|
|
|
4
4
|
import type { FlowOperatorLimits } from "./limits.js";
|
|
5
5
|
import { type FlowDurableResult } from "./types.js";
|
|
6
6
|
/**
|
|
7
|
-
* Deterministic flow interpreter for workflow manifests.
|
|
8
|
-
*
|
|
7
|
+
* Deterministic flow interpreter for workflow manifests. v2 manifests run on the
|
|
8
|
+
* `flow-2` engine (`./v2.ts`); v1 manifests on `flow-1`, one module per primitive.
|
|
9
|
+
* Returns effects only (SD-I1).
|
|
9
10
|
*/
|
|
10
11
|
export declare function runFlowDurable(options: {
|
|
11
12
|
manifest: WorkflowManifest;
|
package/dist/flow/engine.js
CHANGED
|
@@ -2,22 +2,26 @@ import { HarnessError } from "@nylorun/core/define";
|
|
|
2
2
|
import { WorkflowManifestSchema } from "@nylorun/core/contracts";
|
|
3
3
|
import { hashManifest } from "@nylorun/core/define";
|
|
4
4
|
import { HostSuspension } from "../loop/host-suspension.js";
|
|
5
|
-
import { CHECKPOINT_VERSION,
|
|
5
|
+
import { CHECKPOINT_VERSION, flowEngineVersionOf } from "../compatibility.js";
|
|
6
6
|
import { createFlowContext, failureOf, settleInFlight } from "./context.js";
|
|
7
7
|
import { runNode, unwrapSlot } from "./node.js";
|
|
8
8
|
import { runLoop } from "./loop.js";
|
|
9
|
+
import { runFlowV2 } from "./v2.js";
|
|
9
10
|
import { FlowNodeError } from "./types.js";
|
|
10
11
|
/**
|
|
11
|
-
* Deterministic flow interpreter for workflow manifests.
|
|
12
|
-
*
|
|
12
|
+
* Deterministic flow interpreter for workflow manifests. v2 manifests run on the
|
|
13
|
+
* `flow-2` engine (`./v2.ts`); v1 manifests on `flow-1`, one module per primitive.
|
|
14
|
+
* Returns effects only (SD-I1).
|
|
13
15
|
*/
|
|
14
16
|
export async function runFlowDurable(options) {
|
|
15
17
|
const { manifest, checkpoint, host, signal, limits } = options;
|
|
16
18
|
WorkflowManifestSchema.parse(manifest);
|
|
17
19
|
if (checkpoint.version !== CHECKPOINT_VERSION ||
|
|
18
|
-
checkpoint.engineVersion !==
|
|
20
|
+
checkpoint.engineVersion !== flowEngineVersionOf(manifest) ||
|
|
19
21
|
checkpoint.manifestHash !== hashManifest(manifest))
|
|
20
22
|
throw new HarnessError("execution.incompatible", "Incompatible flow checkpoint");
|
|
23
|
+
if (manifest.workflowSchemaVersion === 2)
|
|
24
|
+
return runFlowV2({ manifest, checkpoint, host, signal, limits });
|
|
21
25
|
const root = manifest.root;
|
|
22
26
|
// Root Loop keeps the dedicated entry (history / verify wiring).
|
|
23
27
|
if ("loop" in root)
|
package/dist/flow/loop.d.ts
CHANGED
|
@@ -14,6 +14,10 @@ export type AgentTurnValue = {
|
|
|
14
14
|
readonly agent: AgentManifest;
|
|
15
15
|
};
|
|
16
16
|
export declare function agentTurnValue(output: JsonValue, agent: AgentManifest): AgentTurnValue;
|
|
17
|
+
export declare function readAgentTurn(value: unknown): {
|
|
18
|
+
output: JsonValue;
|
|
19
|
+
agent?: AgentManifest;
|
|
20
|
+
};
|
|
17
21
|
/**
|
|
18
22
|
* Interpret a root Loop node. Returns effects only; the host journals outcomes.
|
|
19
23
|
*/
|
package/dist/flow/loop.js
CHANGED
|
@@ -10,7 +10,7 @@ export const AGENT_TURN_MARKER = "__nylorunAgentTurn";
|
|
|
10
10
|
export function agentTurnValue(output, agent) {
|
|
11
11
|
return { [AGENT_TURN_MARKER]: 1, output, agent };
|
|
12
12
|
}
|
|
13
|
-
function readAgentTurn(value) {
|
|
13
|
+
export function readAgentTurn(value) {
|
|
14
14
|
if (value &&
|
|
15
15
|
typeof value === "object" &&
|
|
16
16
|
!Array.isArray(value) &&
|
|
@@ -32,6 +32,8 @@ function invalidAgent(path, message) {
|
|
|
32
32
|
*/
|
|
33
33
|
export async function runLoop(options) {
|
|
34
34
|
const { manifest, checkpoint, host } = options;
|
|
35
|
+
if (manifest.workflowSchemaVersion !== 1)
|
|
36
|
+
throw new HarnessError("execution.invalid-state", "runLoop expects a workflow manifest v1");
|
|
35
37
|
const root = manifest.root;
|
|
36
38
|
if (!("loop" in root))
|
|
37
39
|
throw new HarnessError("execution.invalid-state", "runLoop expects a loop root");
|
package/dist/flow/map.js
CHANGED
|
@@ -8,7 +8,7 @@ import { runNode, unwrapSlot } from "./node.js";
|
|
|
8
8
|
* Map: journal `over`, run each item concurrently at `<map>[i]/<each id>`; fail-fast.
|
|
9
9
|
*/
|
|
10
10
|
export async function runMap(ctx, node, path, input) {
|
|
11
|
-
const over = await ctx.effect("fn", input, { path, key: nodeKeyOf(path) }, { role: "map-over" });
|
|
11
|
+
const over = await ctx.effect("fn", input, { path, key: `${nodeKeyOf(path)}/over` }, { role: "map-over" });
|
|
12
12
|
if (!Array.isArray(over)) {
|
|
13
13
|
throw new FlowNodeError({
|
|
14
14
|
code: "map.not-a-list",
|
package/dist/flow/node.js
CHANGED
|
@@ -4,7 +4,8 @@ import { runChain } from "./chain.js";
|
|
|
4
4
|
import { runSwitch } from "./switch.js";
|
|
5
5
|
import { runParallel } from "./parallel.js";
|
|
6
6
|
import { runMap } from "./map.js";
|
|
7
|
-
import { runLoopNode } from "./loop.js";
|
|
7
|
+
import { readAgentTurn, runLoopNode } from "./loop.js";
|
|
8
|
+
import { FlowNodeError } from "./types.js";
|
|
8
9
|
/** Path part / id for a node among its siblings. */
|
|
9
10
|
export function nodePart(node) {
|
|
10
11
|
if ("agent" in node)
|
|
@@ -56,7 +57,7 @@ export async function runNode(ctx, node, path, input, options = {}) {
|
|
|
56
57
|
input: options.ownerInput ?? input,
|
|
57
58
|
results,
|
|
58
59
|
};
|
|
59
|
-
childInput = (await ctx.effect("fn", fnArgs, { path, key: nodeKeyOf(path) }, { role: "slot-input" }));
|
|
60
|
+
childInput = (await ctx.effect("fn", fnArgs, { path, key: `${nodeKeyOf(path)}/input`, role: "slot-input" }, { role: "slot-input" }));
|
|
60
61
|
}
|
|
61
62
|
return runRunnable(ctx, node.slot.run, path, childInput);
|
|
62
63
|
}
|
|
@@ -82,9 +83,31 @@ async function runRunnable(ctx, node, path, input) {
|
|
|
82
83
|
throw new HarnessError("execution.invalid-state", "Unknown workflow node kind");
|
|
83
84
|
}
|
|
84
85
|
async function runAgent(ctx, agentId, path, input) {
|
|
85
|
-
|
|
86
|
+
// The host marks a linked agent's output with its turn manifest for Loops; a step
|
|
87
|
+
// passes on the output only.
|
|
88
|
+
return readAgentTurn(await ctx.effect("agent", { agentId, input, path }, { path, key: nodeKeyOf(path) })).output;
|
|
86
89
|
}
|
|
87
90
|
async function runTool(ctx, name, path, input) {
|
|
88
|
-
|
|
91
|
+
const value = await ctx.effect("tool", input, { path, key: nodeKeyOf(path) }, { toolName: name });
|
|
92
|
+
return toolNodeOutput(value, path);
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* The Action endpoint settles a tool node like any tool: `{ kind: "completed", output }` or
|
|
96
|
+
* `{ kind: "denied", reason }`. The flow passes on the output only. Failed values are
|
|
97
|
+
* already raised by `ctx.effect`.
|
|
98
|
+
*/
|
|
99
|
+
function toolNodeOutput(value, path) {
|
|
100
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
101
|
+
return value;
|
|
102
|
+
const outcome = value;
|
|
103
|
+
if (outcome.kind === "completed" && "output" in outcome)
|
|
104
|
+
return outcome.output ?? null;
|
|
105
|
+
if (outcome.kind === "denied")
|
|
106
|
+
throw new FlowNodeError({
|
|
107
|
+
code: "tool.denied",
|
|
108
|
+
message: typeof outcome.reason === "string" ? outcome.reason : "Tool call denied",
|
|
109
|
+
path,
|
|
110
|
+
});
|
|
111
|
+
return value;
|
|
89
112
|
}
|
|
90
113
|
export { joinPath, mapItemPath, nodeKeyOf };
|
package/dist/flow/paths.d.ts
CHANGED
|
@@ -9,11 +9,16 @@ export declare function mapItemPath(mapPath: string, index: number, eachId: stri
|
|
|
9
9
|
export declare function nodeKeyOf(path: string): string;
|
|
10
10
|
/** Iteration vector string: enclosing Loop numbers outermost first, or "-" outside Loops. */
|
|
11
11
|
export declare function iterationsOf(vector: readonly number[]): string;
|
|
12
|
-
/**
|
|
12
|
+
/**
|
|
13
|
+
* Effect id for a flow effect (workflows.md §10).
|
|
14
|
+
* `role` separates two effects of one kind on one path, e.g. a slot `input`
|
|
15
|
+
* and the Map `over` or Switch `on` it wraps.
|
|
16
|
+
*/
|
|
13
17
|
export declare function flowEffectId(input: {
|
|
14
18
|
readonly turnId: string;
|
|
15
19
|
readonly segment: number;
|
|
16
20
|
readonly path: string;
|
|
17
21
|
readonly kind: string;
|
|
18
22
|
readonly iterations: string;
|
|
23
|
+
readonly role?: string;
|
|
19
24
|
}): string;
|
package/dist/flow/paths.js
CHANGED
|
@@ -17,7 +17,12 @@ export function nodeKeyOf(path) {
|
|
|
17
17
|
export function iterationsOf(vector) {
|
|
18
18
|
return vector.length === 0 ? "-" : vector.join(".");
|
|
19
19
|
}
|
|
20
|
-
/**
|
|
20
|
+
/**
|
|
21
|
+
* Effect id for a flow effect (workflows.md §10).
|
|
22
|
+
* `role` separates two effects of one kind on one path, e.g. a slot `input`
|
|
23
|
+
* and the Map `over` or Switch `on` it wraps.
|
|
24
|
+
*/
|
|
21
25
|
export function flowEffectId(input) {
|
|
22
|
-
|
|
26
|
+
const kind = input.role === undefined ? input.kind : `${input.kind}.${input.role}`;
|
|
27
|
+
return `${input.turnId}:${input.segment}:flow:${input.path}:${kind}:${input.iterations}`;
|
|
23
28
|
}
|
package/dist/flow/types.d.ts
CHANGED
|
@@ -41,5 +41,5 @@ export declare class FlowNodeError extends Error {
|
|
|
41
41
|
readonly failure: FlowFailure;
|
|
42
42
|
constructor(failure: FlowFailure);
|
|
43
43
|
}
|
|
44
|
-
/** Completed effect value that encodes a curated failure (
|
|
44
|
+
/** Completed effect value that encodes a curated failure (Action endpoint / agent settle). */
|
|
45
45
|
export declare function failedValueOf(value: unknown): FlowFailure | undefined;
|
package/dist/flow/types.js
CHANGED
|
@@ -7,7 +7,7 @@ export class FlowNodeError extends Error {
|
|
|
7
7
|
this.name = "FlowNodeError";
|
|
8
8
|
}
|
|
9
9
|
}
|
|
10
|
-
/** Completed effect value that encodes a curated failure (
|
|
10
|
+
/** Completed effect value that encodes a curated failure (Action endpoint / agent settle). */
|
|
11
11
|
export function failedValueOf(value) {
|
|
12
12
|
if (!value || typeof value !== "object")
|
|
13
13
|
return undefined;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type WorkflowManifestV2 } from "@nylorun/core/define";
|
|
2
|
+
import type { DurableHost } from "../run/durable.js";
|
|
3
|
+
import type { FlowCheckpoint } from "./checkpoint.js";
|
|
4
|
+
import { type FlowOperatorLimits } from "./limits.js";
|
|
5
|
+
import { type FlowDurableResult } from "./types.js";
|
|
6
|
+
export declare function runFlowV2(options: {
|
|
7
|
+
manifest: WorkflowManifestV2;
|
|
8
|
+
checkpoint: FlowCheckpoint;
|
|
9
|
+
host: DurableHost;
|
|
10
|
+
signal?: AbortSignal;
|
|
11
|
+
limits?: Partial<FlowOperatorLimits> | null;
|
|
12
|
+
}): Promise<FlowDurableResult>;
|