@nylorun/harness 0.20.0-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 CHANGED
@@ -1,5 +1,94 @@
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
+
3
92
  ## 0.20.0-beta
4
93
 
5
94
  ### Minor 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-2`, 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.
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: { 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.
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
- 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.
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 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.
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 JSON projection of ModelRequest and invocationId. Its completed value is a ModelCandidate or string. 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.
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, lease policy and reconciliation remain runtime-owned.
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 by an executor. Its model, tool and hook effects carry `agent: {id, path, delegationId}` (`delegationId` is the parent tool call's invocationId), keep the root `agentId` and `manifestHash`, and use identity `<delegationId>/<inner identity>`; tool context `idempotencyKey` is prefixed the same way. Hosts resolve child effects against the child manifest (`delegateManifest`) for pinned tool schemas, sandbox and MCP routing, copy `agent` onto the Action, and include it in action event payloads. A `delegation` effect (identity `<delegationId>:started` or `<delegationId>:settled`, input `{task}` or `{status, outcome}`) must be recorded completed immediately with value null and publish `delegation.started` / `delegation.completed` exactly once; the journal makes replays silent. `DurableSessionTool.agentId` attaches discovered MCP tools to a child; MCP snapshot records and diagnostics carry `agentId`, and child plugin roots are keyed `<childId>/<capabilityId>`. Children share the session sandbox. `GET /v1/sessions/:id/items?agent=` filters history by `payload.agent.delegationId` or `payload.agent.path`. Existing checkpoints are unaffected; engine version stays `hosted-2`. A tool whose `agent` body is a flow agent (workflow manifest v2) is not run in-process: the engine issues one `agent` effect (identity `<delegationId>:flow`, input `{agentId, input: task, path}`, context `{role: "delegate", delegationId}`, `agent` ref set) between the `delegation` start and settle points. The host starts a linked flow session from the pinned parent manifest's inlined flow (session id `derive(parentSessionId, path, "delegate", delegationId)`, plugin roots under `<flowId>/`), sends the task as its message, and completes the effect with the flow's output, or `{kind: "failed", code, message}`, when its turn ends. Cancelling the parent cascades to linked sessions.
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}`. On workflow manifest v2 (engine `flow-2`), an `agent` or `tool` effect's `path` is the leaf path (the leaf's id, `[i]` per Map item, nested flow agent ids in front) and its `key` drops the indices; an `fn` or `verify` effect's `key` is the stage key plus `:input`, `:on`, `:verify` or `:decide`, and its `path` is the stage's site plus the same suffix. v2 `agent` effect input adds `flow` (nested flow agent ids, outermost first); the host resolves the leaf from the workflow manifest's embedded `agents` (`embeddedAgent`) and gives the linked session the leaf's manifest, its hash, and the workflow's plugin roots under `<agentId>/`. Checkpoints pin the engine: v1 manifests run on `flow-1`, v2 on `flow-2`. An executor refuses v2 flow actions whose `manifestHash` is not the manifest it serves. The host resolves `agent` effects only through the public session contract (create linked session, message with derived idempotency key, settle on linked `turn.completed` / failed / cancelled). `tool`, `fn`, and `verify` become Actions claimed by the workflow executor; Actions use `path` + `key` instead of `capabilityId` + `toolName`. `fn` and `verify` are pure or repeat-safe: on lease expiry they return to pending and are offered again; tool nodes become `uncertain` and are never re-run automatically. Parallelism comes from pending effects returned together; the Runtime caps concurrency with `RuntimeOptions.flow` / env (`maxConcurrency`, `maxMapItems`, `maxLoopIterations`).
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.** 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.
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. 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.
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 network round trip to your executor per turn or per model call, whatever the
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 SSE executor. Historical root client types remain for deferred local tooling; they are not the new wire contract.
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.
@@ -1,6 +1,6 @@
1
1
  export { checkCompatibility } from "./definition/compatibility.js";
2
2
  export declare const CHECKPOINT_VERSION = 1;
3
- export declare const ENGINE_VERSION = "hosted-2";
3
+ export declare const ENGINE_VERSION = "hosted-3";
4
4
  /**
5
5
  * Flow engine version pinned on workflow checkpoints. Workflow manifest v2 runs on
6
6
  * `flow-2`; v1 manifests keep running on `flow-1`, so in-flight v1 runs finish as they began.
@@ -1,6 +1,6 @@
1
1
  export { checkCompatibility } from "./definition/compatibility.js";
2
2
  export const CHECKPOINT_VERSION = 1;
3
- export const ENGINE_VERSION = "hosted-2";
3
+ export const ENGINE_VERSION = "hosted-3";
4
4
  /**
5
5
  * Flow engine version pinned on workflow checkpoints. Workflow manifest v2 runs on
6
6
  * `flow-2`; v1 manifests keep running on `flow-1`, so in-flight v1 runs finish as they began.
package/dist/flow/node.js CHANGED
@@ -92,7 +92,7 @@ async function runTool(ctx, name, path, input) {
92
92
  return toolNodeOutput(value, path);
93
93
  }
94
94
  /**
95
- * The executor settles a tool node like any tool: `{ kind: "completed", output }` or
95
+ * The Action endpoint settles a tool node like any tool: `{ kind: "completed", output }` or
96
96
  * `{ kind: "denied", reason }`. The flow passes on the output only. Failed values are
97
97
  * already raised by `ctx.effect`.
98
98
  */
@@ -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 (executor / agent settle). */
44
+ /** Completed effect value that encodes a curated failure (Action endpoint / agent settle). */
45
45
  export declare function failedValueOf(value: unknown): FlowFailure | undefined;
@@ -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 (executor / agent settle). */
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,49 @@
1
+ /**
2
+ * Compaction (Model Calls §8): when history no longer fits the model's window, the engine
3
+ * asks the model to summarize the older part and keeps the rest verbatim.
4
+ *
5
+ * The cut rules and the summary format are adapted from the compaction in pi's
6
+ * `pi-agent-core` (MIT, Copyright (c) Earendil Works), rewritten for Nylorun's transcript.
7
+ */
8
+ import type { ModelAdapter, TranscriptCompactionEntry, TranscriptEntry } from "@nylorun/core/define";
9
+ export interface ContextBudget {
10
+ readonly contextWindow: number;
11
+ readonly reserve: number;
12
+ }
13
+ /**
14
+ * The window and output limit the adapter reported on the latest candidate
15
+ * (`evidence.extras.contextWindow`, `maxOutputTokens`). Undefined until a model has answered.
16
+ */
17
+ export declare function contextBudget(transcript: readonly TranscriptEntry[]): ContextBudget | undefined;
18
+ /**
19
+ * Tokens the next prompt needs: the last reported usage, which already counts the
20
+ * instructions, tools and everything before it, plus an estimate of what came after.
21
+ * Without usage, everything is estimated.
22
+ */
23
+ export declare function estimateTokens(transcript: readonly TranscriptEntry[]): number;
24
+ /** A rough token count of what one entry contributes to a prompt. */
25
+ export declare function entryTokens(entry: TranscriptEntry): number;
26
+ /**
27
+ * Where the kept tail starts. It keeps about `keepTokens` of the newest entries, never
28
+ * starts with tool results (their call stays with them), and never keeps the previous
29
+ * summary. Returns 0 or 1 when there is nothing older to summarize.
30
+ */
31
+ export declare function findCut(transcript: readonly TranscriptEntry[], keepTokens: number): number;
32
+ export interface CompactionInput {
33
+ readonly transcript: readonly TranscriptEntry[];
34
+ readonly executionId: string;
35
+ readonly turnId: string;
36
+ readonly stepId: string;
37
+ readonly trigger: "threshold" | "overflow";
38
+ readonly budget: ContextBudget | undefined;
39
+ readonly invoke: ModelAdapter;
40
+ readonly signal: AbortSignal;
41
+ }
42
+ /**
43
+ * Summarize everything before the cut with one model call and return the new transcript,
44
+ * or undefined when there is nothing older to summarize. The current turn's messages from
45
+ * the user stay verbatim even when the cut falls inside the turn.
46
+ */
47
+ export declare function compact(input: CompactionInput): Promise<readonly TranscriptEntry[] | undefined>;
48
+ /** How a compaction entry reaches the model: a user message ahead of the kept tail. */
49
+ export declare function summaryPrompt(entry: TranscriptCompactionEntry): string;
@@ -0,0 +1,288 @@
1
+ import { HarnessError, isModelFailureOutcome } from "@nylorun/core/define";
2
+ /** Characters per token for the heuristic estimate; the reserve absorbs its error. */
3
+ const CHARS_PER_TOKEN = 4;
4
+ /** The kept tail is at most this many tokens, and at most this share of the window. */
5
+ const KEEP_TOKENS = 20_000;
6
+ const KEEP_SHARE = 0.3;
7
+ /** Room held back for the reply when the adapter does not report an output limit. */
8
+ const DEFAULT_RESERVE = 8_192;
9
+ const MAX_RESERVE = 16_384;
10
+ /** Tool inputs and results are clipped to this many characters in the summarizer's input. */
11
+ const CLIP = 2_000;
12
+ /** Tokens the summary instructions, format and previous summary take in a summary call. */
13
+ const SUMMARY_OVERHEAD = 1_024;
14
+ /**
15
+ * The window and output limit the adapter reported on the latest candidate
16
+ * (`evidence.extras.contextWindow`, `maxOutputTokens`). Undefined until a model has answered.
17
+ */
18
+ export function contextBudget(transcript) {
19
+ for (let index = transcript.length - 1; index >= 0; index--) {
20
+ const entry = transcript[index];
21
+ if (entry.kind !== "candidate")
22
+ continue;
23
+ const extras = entry.candidate.evidence?.extras;
24
+ const window = extras?.contextWindow;
25
+ if (typeof window !== "number" || window <= 0)
26
+ continue;
27
+ const output = extras?.maxOutputTokens;
28
+ const reserve = Math.min(typeof output === "number" && output > 0 ? output : DEFAULT_RESERVE, MAX_RESERVE, Math.floor(window / 4));
29
+ return { contextWindow: window, reserve };
30
+ }
31
+ return undefined;
32
+ }
33
+ /**
34
+ * Tokens the next prompt needs: the last reported usage, which already counts the
35
+ * instructions, tools and everything before it, plus an estimate of what came after.
36
+ * Without usage, everything is estimated.
37
+ */
38
+ export function estimateTokens(transcript) {
39
+ for (let index = transcript.length - 1; index >= 0; index--) {
40
+ const entry = transcript[index];
41
+ if (entry.kind !== "candidate" || !entry.candidate.usage)
42
+ continue;
43
+ const usage = entry.candidate.usage;
44
+ const reported = usage.totalTokens ??
45
+ (usage.inputTokens ?? 0) +
46
+ (usage.cachedTokens ?? 0) +
47
+ (usage.cacheWriteTokens ?? 0) +
48
+ (usage.outputTokens ?? 0);
49
+ if (reported <= 0)
50
+ continue;
51
+ return reported + transcript.slice(index + 1).reduce((sum, item) => sum + entryTokens(item), 0);
52
+ }
53
+ return transcript.reduce((sum, item) => sum + entryTokens(item), 0);
54
+ }
55
+ /** A rough token count of what one entry contributes to a prompt. */
56
+ export function entryTokens(entry) {
57
+ return Math.ceil(entryText(entry, Number.POSITIVE_INFINITY).length / CHARS_PER_TOKEN);
58
+ }
59
+ /**
60
+ * Where the kept tail starts. It keeps about `keepTokens` of the newest entries, never
61
+ * starts with tool results (their call stays with them), and never keeps the previous
62
+ * summary. Returns 0 or 1 when there is nothing older to summarize.
63
+ */
64
+ export function findCut(transcript, keepTokens) {
65
+ const first = transcript[0]?.kind === "compaction" ? 1 : 0;
66
+ let kept = 0;
67
+ let cut = transcript.length;
68
+ while (cut > first) {
69
+ const tokens = entryTokens(transcript[cut - 1]);
70
+ if (kept + tokens > keepTokens && cut < transcript.length)
71
+ break;
72
+ kept += tokens;
73
+ cut--;
74
+ }
75
+ // Tool results belong with the call that asked for them.
76
+ while (cut > first && transcript[cut]?.kind === "tool-results")
77
+ cut--;
78
+ return cut;
79
+ }
80
+ /**
81
+ * Summarize everything before the cut with one model call and return the new transcript,
82
+ * or undefined when there is nothing older to summarize. The current turn's messages from
83
+ * the user stay verbatim even when the cut falls inside the turn.
84
+ */
85
+ export async function compact(input) {
86
+ const { transcript } = input;
87
+ const tokensBefore = estimateTokens(transcript);
88
+ const window = input.budget?.contextWindow ?? tokensBefore;
89
+ const keepTokens = Math.max(1, Math.min(KEEP_TOKENS, Math.floor(window * KEEP_SHARE)));
90
+ const cut = findCut(transcript, keepTokens);
91
+ const previous = transcript[0]?.kind === "compaction" ? transcript[0] : undefined;
92
+ const start = previous ? 1 : 0;
93
+ if (cut <= start)
94
+ return undefined;
95
+ const older = transcript.slice(start, cut);
96
+ // The user's request for the turn in progress is never summarized away.
97
+ const request = older.filter((entry) => entry.kind === "input" &&
98
+ entry.turnId === input.turnId &&
99
+ (entry.event.kind === "user-message" || entry.event.kind === "interrupt"));
100
+ const tail = [...request, ...transcript.slice(cut)];
101
+ const keptTokens = tail.reduce((sum, entry) => sum + entryTokens(entry), 0);
102
+ const reserve = input.budget?.reserve ?? DEFAULT_RESERVE;
103
+ const maxOutputTokens = Math.max(256, Math.floor(reserve * 0.8));
104
+ // The summarizer sees at most what fits its window: older history is summarized in
105
+ // chunks, each merged into the running summary. A single call would fail on a provider,
106
+ // or lose the start of the history on a server that truncates silently.
107
+ const chunkTokens = input.budget
108
+ ? Math.max(1_000, input.budget.contextWindow - reserve - SUMMARY_OVERHEAD)
109
+ : Number.POSITIVE_INFINITY;
110
+ const chunks = chunked(older, chunkTokens);
111
+ // A step can compact before its call and again after an overflow; each is its own effect.
112
+ const base = `compaction-${input.stepId}${input.trigger === "overflow" ? "-overflow" : ""}`;
113
+ let summary = previous?.summary;
114
+ for (const [index, chunk] of chunks.entries()) {
115
+ const last = index === chunks.length - 1;
116
+ const outcome = await input.invoke(summaryCall(input, chunk, summary, maxOutputTokens), {
117
+ request: summaryRequest(input),
118
+ invocationId: index === 0 ? base : `${base}-${index}`,
119
+ signal: input.signal,
120
+ compaction: {
121
+ trigger: input.trigger,
122
+ tokensBefore,
123
+ keptTokens,
124
+ ...(last ? {} : { partial: true }),
125
+ },
126
+ reportPreparedCall() { },
127
+ });
128
+ if (isModelFailureOutcome(outcome))
129
+ throw new HarnessError(`model.${outcome.code}`, `Compacting the conversation failed: ${outcome.message}`);
130
+ summary = summaryText(outcome).trim();
131
+ if (!summary)
132
+ throw new HarnessError("model.invalid_output", "Compacting the conversation failed: the model returned an empty summary.");
133
+ }
134
+ if (!summary)
135
+ throw new HarnessError("model.invalid_output", "Compacting the conversation failed: the model returned an empty summary.");
136
+ const entry = {
137
+ kind: "compaction",
138
+ turnId: input.turnId,
139
+ stepId: input.stepId,
140
+ summary,
141
+ trigger: input.trigger,
142
+ tokensBefore,
143
+ tokensAfter: keptTokens + Math.ceil(summary.length / CHARS_PER_TOKEN),
144
+ };
145
+ return Object.freeze([Object.freeze(entry), ...tail]);
146
+ }
147
+ /** How a compaction entry reaches the model: a user message ahead of the kept tail. */
148
+ export function summaryPrompt(entry) {
149
+ return [
150
+ "Earlier parts of this conversation were summarized to fit the context window.",
151
+ "<summary>",
152
+ entry.summary,
153
+ "</summary>",
154
+ ].join("\n");
155
+ }
156
+ const SYSTEM = [
157
+ "You summarize a conversation between a user and an AI agent that uses tools, so the agent",
158
+ "can continue the work with a shorter context. Write for the agent, not the user.",
159
+ "Keep facts exactly: names, identifiers, paths, numbers, decisions and open problems.",
160
+ "Do not invent anything and do not continue the task yourself.",
161
+ ].join(" ");
162
+ const FORMAT = [
163
+ "Write the summary with these sections, leaving out a section that has nothing:",
164
+ "## Goal",
165
+ "## Constraints and preferences",
166
+ "## Progress",
167
+ "## Key decisions",
168
+ "## Next steps",
169
+ "## Critical context",
170
+ "If a previous summary is given, merge it with the new conversation into one summary.",
171
+ ].join("\n");
172
+ /** Consecutive runs of entries whose summarizer input stays under `limit` tokens. */
173
+ function chunked(entries, limit) {
174
+ const chunks = [];
175
+ let current = [];
176
+ let size = 0;
177
+ for (const entry of entries) {
178
+ const tokens = Math.ceil(entryText(entry, CLIP).length / CHARS_PER_TOKEN);
179
+ if (current.length && size + tokens > limit) {
180
+ chunks.push(current);
181
+ current = [];
182
+ size = 0;
183
+ }
184
+ current.push(entry);
185
+ size += tokens;
186
+ }
187
+ if (current.length)
188
+ chunks.push(current);
189
+ return chunks;
190
+ }
191
+ function summaryCall(input, older, previous, maxOutputTokens) {
192
+ const conversation = older
193
+ .map((entry) => entryText(entry, CLIP))
194
+ .filter((text) => text !== "")
195
+ .join("\n\n");
196
+ const text = [
197
+ ...(previous ? ["<previous-summary>", previous, "</previous-summary>", ""] : []),
198
+ "<conversation>",
199
+ conversation,
200
+ "</conversation>",
201
+ "",
202
+ FORMAT,
203
+ ].join("\n");
204
+ const prompt = [
205
+ { kind: "instructions", role: "system", content: [{ type: "text", text: SYSTEM }] },
206
+ { kind: "message", role: "user", content: [{ type: "text", text }] },
207
+ ];
208
+ return {
209
+ prompt,
210
+ tools: [],
211
+ model: { controls: { maxOutputTokens } },
212
+ executionId: input.executionId,
213
+ };
214
+ }
215
+ function summaryRequest(input) {
216
+ return {
217
+ executionId: input.executionId,
218
+ turnId: input.turnId,
219
+ stepId: input.stepId,
220
+ configuration: {
221
+ version: 1,
222
+ instructions: [],
223
+ tools: [],
224
+ toolContracts: [],
225
+ contributors: [],
226
+ },
227
+ instructions: [SYSTEM],
228
+ context: { items: [], contributors: [] },
229
+ transcript: [],
230
+ arrivals: [],
231
+ toolResults: [],
232
+ tools: [],
233
+ };
234
+ }
235
+ function summaryText(outcome) {
236
+ if (typeof outcome === "string")
237
+ return outcome;
238
+ return outcome.output.flatMap((block) => (block.type === "text" ? [block.text] : [])).join("");
239
+ }
240
+ /** The model-visible text of one entry, with tool payloads clipped to `clip` characters. */
241
+ function entryText(entry, clip) {
242
+ switch (entry.kind) {
243
+ case "input": {
244
+ const event = entry.event;
245
+ if (event.kind === "user-message" || event.kind === "interrupt")
246
+ return `[User]: ${"content" in event && event.content
247
+ ? event.content
248
+ .map((part) => (part.type === "text" ? part.text : `[${part.mediaType}]`))
249
+ .join(" ")
250
+ : (event.text ?? "")}`;
251
+ if (event.kind === "approve")
252
+ return `[User ${event.approved ? "approved" : "denied"} a request]`;
253
+ if (event.kind === "respond")
254
+ return `[User answered]: ${clipped(event.value, clip)}`;
255
+ return "";
256
+ }
257
+ case "candidate":
258
+ return entry.candidate.output
259
+ .flatMap((block) => {
260
+ if (block.type === "text")
261
+ return block.text ? [`[Assistant]: ${block.text}`] : [];
262
+ if (block.type === "json")
263
+ return [`[Assistant]: ${clipped(block.value, clip)}`];
264
+ if (block.type === "tool-call")
265
+ return [`[Assistant called ${block.name}]: ${clipped(block.args, clip)}`];
266
+ return [];
267
+ })
268
+ .join("\n");
269
+ case "tool-results":
270
+ return entry.results
271
+ .map((result) => result.kind === "completed"
272
+ ? `[Tool ${result.toolName} result]: ${clipped(result.output, clip)}`
273
+ : result.kind === "denied"
274
+ ? `[Tool ${result.toolName} denied]: ${result.reason ?? ""}`
275
+ : `[Tool ${result.toolName} failed]: ${result.message}`)
276
+ .join("\n");
277
+ case "final":
278
+ return "";
279
+ case "compaction":
280
+ return summaryPrompt(entry);
281
+ }
282
+ }
283
+ function clipped(value, clip) {
284
+ const text = typeof value === "string" ? value : JSON.stringify(value ?? null);
285
+ return text.length <= clip
286
+ ? text
287
+ : `${text.slice(0, clip)}… [${text.length - clip} more characters]`;
288
+ }
@@ -27,6 +27,14 @@ export interface ExecuteInternals {
27
27
  readonly delegation?: DelegationHost;
28
28
  /** Set when this invocation is an agent used as a tool. */
29
29
  readonly delegated?: AgentRef;
30
+ /**
31
+ * Segment rollover (Model Calls §10): end the invocation with `yielded` at the next step
32
+ * boundary once this many steps ran, or this much time passed, in this invocation.
33
+ */
34
+ readonly yieldAfter?: {
35
+ readonly steps?: number;
36
+ readonly ms?: number;
37
+ };
30
38
  }
31
39
  /** Codes are curated: a child's provider error bodies never reach the parent's context. */
32
40
  export declare const INTERACTION_UNSUPPORTED = "Agents used as tools can't ask for input, approval or a wait yet; do this work on the parent agent.";
@@ -118,6 +118,9 @@ function settle(result) {
118
118
  code: "delegation.interaction-unsupported",
119
119
  message: INTERACTION_UNSUPPORTED,
120
120
  };
121
+ // Agents used as tools run inside one step of their parent and never roll over.
122
+ if (result.status === "yielded")
123
+ return { kind: "failed", code: "delegation.failed", message: "The agent stopped early." };
121
124
  const reason = result.error.code;
122
125
  const curated = reason.startsWith("execution.") ? reason : `${reason}: ${result.error.message}`;
123
126
  const partial = lastText(result);
@@ -12,6 +12,7 @@ const USAGE_TOKEN_KEYS = [
12
12
  "outputTokens",
13
13
  "totalTokens",
14
14
  "cachedTokens",
15
+ "cacheWriteTokens",
15
16
  "reasoningTokens",
16
17
  ];
17
18
  export function normalizeDirective(value) {
@@ -1,9 +1,10 @@
1
1
  import { copyJson, freezeGraph } from "@nylorun/core/define";
2
+ import { summaryPrompt } from "../compaction/index.js";
2
3
  export function projectModelCall(request) {
3
4
  return freezeGraph({
4
5
  prompt: Object.freeze([
5
6
  ...projectInstructions(request.instructions),
6
- ...request.transcript.flatMap(projectEntry),
7
+ ...request.transcript.flatMap((entry) => projectEntry(entry, request.turnId)),
7
8
  ...projectContext(request.context),
8
9
  ]),
9
10
  tools: Object.freeze(request.configuration.tools.map((tool) => Object.freeze({
@@ -42,7 +43,7 @@ function renderContext(items) {
42
43
  "</runtime-context>",
43
44
  ].join("\n");
44
45
  }
45
- function projectEntry(entry) {
46
+ function projectEntry(entry, turnId) {
46
47
  if (entry.kind === "input") {
47
48
  if (entry.event.kind !== "user-message" && entry.event.kind !== "interrupt")
48
49
  return [];
@@ -64,8 +65,12 @@ function projectEntry(entry) {
64
65
  }
65
66
  if (entry.kind === "candidate") {
66
67
  const content = entry.candidate.output.flatMap((block) => {
67
- if (block.type === "text" ||
68
- (block.type === "reasoning" && block.providerMetadata !== undefined))
68
+ if (block.type === "text")
69
+ return [Object.freeze({ ...block })];
70
+ // Reasoning an adapter marked `replay: "turn"` is sent back only within its own turn.
71
+ if (block.type === "reasoning" &&
72
+ block.providerMetadata !== undefined &&
73
+ (block.providerMetadata.replay !== "turn" || entry.turnId === turnId))
69
74
  return [Object.freeze({ ...block })];
70
75
  if (block.type === "json")
71
76
  return [textPart(JSON.stringify(block.value))];
@@ -85,10 +90,22 @@ function projectEntry(entry) {
85
90
  });
86
91
  if (content.length === 0)
87
92
  return [];
88
- return [freezeItem({ kind: "message", role: "assistant", content: Object.freeze(content) })];
93
+ const producer = producerOf(entry.candidate.evidence?.extras?.producer);
94
+ return [
95
+ freezeItem({
96
+ kind: "message",
97
+ role: "assistant",
98
+ content: Object.freeze(content),
99
+ ...(producer ? { producer } : {}),
100
+ }),
101
+ ];
89
102
  }
90
103
  if (entry.kind === "tool-results")
91
104
  return entry.results.map(projectToolResult);
105
+ if (entry.kind === "compaction")
106
+ return [
107
+ freezeItem({ kind: "message", role: "user", content: [textPart(summaryPrompt(entry))] }),
108
+ ];
92
109
  return [];
93
110
  }
94
111
  function projectToolResult(result) {
@@ -121,3 +138,15 @@ function freezeItem(item) {
121
138
  content: Object.freeze(item.content.map((part) => Object.freeze(part))),
122
139
  });
123
140
  }
141
+ function producerOf(value) {
142
+ if (!value || typeof value !== "object" || Array.isArray(value))
143
+ return undefined;
144
+ const producer = value;
145
+ if (typeof producer.provider !== "string" || typeof producer.model !== "string")
146
+ return undefined;
147
+ return Object.freeze({
148
+ provider: producer.provider,
149
+ model: producer.model,
150
+ ...(typeof producer.api === "string" ? { api: producer.api } : {}),
151
+ });
152
+ }
package/dist/loop/run.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { HostSuspension } from "./host-suspension.js";
2
2
  import { HarnessError, isHarnessError } from "@nylorun/core/define";
3
3
  import { runStep } from "./step/run.js";
4
+ import { compact, contextBudget, estimateTokens } from "./compaction/index.js";
4
5
  import { createId } from "../utils/ids.js";
5
6
  import { copyJson } from "@nylorun/core/define";
6
7
  import { dispatchPlan } from "./dispatch.js";
@@ -35,6 +36,29 @@ export async function execute(agent, options, internals = {}) {
35
36
  signal.throwIfAborted();
36
37
  let turnId;
37
38
  let stepNumber;
39
+ /** Steps run and when this invocation started, for segment rollover. */
40
+ let stepsRun = 0;
41
+ const started = Date.now();
42
+ /** One compaction and retry per overflow; reset once a step succeeds. */
43
+ let overflowCompacted = false;
44
+ /** Summarize older history into a compaction entry (Model Calls §8). */
45
+ const compactHistory = async (trigger, stepId) => {
46
+ const next = await compact({
47
+ transcript: invocation.state.transcript,
48
+ executionId: invocation.state.executionId,
49
+ turnId,
50
+ stepId,
51
+ trigger,
52
+ budget: contextBudget(invocation.state.transcript),
53
+ invoke: options.onModelCall,
54
+ signal,
55
+ });
56
+ if (!next)
57
+ return false;
58
+ invocation.state = { ...invocation.state, transcript: next };
59
+ await record();
60
+ return true;
61
+ };
38
62
  let arrivals = [];
39
63
  let toolResults = [];
40
64
  const hooked = hasAnyHooks(agent);
@@ -62,6 +86,7 @@ export async function execute(agent, options, internals = {}) {
62
86
  1 +
63
87
  invocation.state.transcript.filter((entry) => entry.kind === "candidate" && entry.turnId === turnId).length;
64
88
  invocation.state = { ...invocation.state, status: "active" };
89
+ toolResults = lastResults(invocation.state);
65
90
  await record();
66
91
  }
67
92
  else {
@@ -94,7 +119,24 @@ export async function execute(agent, options, internals = {}) {
94
119
  }
95
120
  for (;; stepNumber++) {
96
121
  signal.throwIfAborted();
122
+ // Segment rollover: end this segment between steps; the host continues the turn.
123
+ const yieldAfter = internals.yieldAfter;
124
+ if (yieldAfter &&
125
+ stepsRun > 0 &&
126
+ !invocation.state.plan &&
127
+ ((yieldAfter.steps !== undefined && stepsRun >= yieldAfter.steps) ||
128
+ (yieldAfter.ms !== undefined && Date.now() - started >= yieldAfter.ms))) {
129
+ if (!invocation.state.turn)
130
+ setTurn(() => ({ turnId, attempts: { afterStep: 0, afterTurn: 0 } }));
131
+ return finish({ status: "yielded" });
132
+ }
133
+ stepsRun++;
97
134
  const stepId = createId("step");
135
+ // Keep the next prompt inside the model's window, before it is sent.
136
+ const budget = contextBudget(invocation.state.transcript);
137
+ if (budget &&
138
+ estimateTokens(invocation.state.transcript) > budget.contextWindow - budget.reserve)
139
+ await compactHistory("threshold", stepId);
98
140
  const snapshot = {
99
141
  id: invocation.state.executionId,
100
142
  status: "running",
@@ -151,6 +193,16 @@ export async function execute(agent, options, internals = {}) {
151
193
  ...turn,
152
194
  attempts: { ...turn.attempts, afterStep: turn.attempts.afterStep + 1 },
153
195
  }));
196
+ // The prompt did not fit: compact once and ask again with the same inputs.
197
+ if (result.output.kind === "tripwire" &&
198
+ result.output.tripwire.code === "model.context_overflow" &&
199
+ !overflowCompacted) {
200
+ overflowCompacted = true;
201
+ if (await compactHistory("overflow", stepId))
202
+ continue;
203
+ }
204
+ if (result.output.kind !== "tripwire")
205
+ overflowCompacted = false;
154
206
  let candidate = result.candidate;
155
207
  let finalOutput = result.output.kind === "final" ? result.output.output : undefined;
156
208
  let turnDecision = {};
@@ -350,6 +402,12 @@ async function finishInvocation(invocation, result) {
350
402
  ],
351
403
  };
352
404
  }
405
+ if (result.status === "yielded") {
406
+ // Mid-turn: the state keeps its turn and stays active, so `continue` picks it up.
407
+ invocation.state = { ...invocation.state, status: "active" };
408
+ await invocation.record();
409
+ return { status: "yielded", state: invocation.state };
410
+ }
353
411
  if (result.status !== "paused" && invocation.state.turn) {
354
412
  const { turn: _turn, ...rest } = invocation.state;
355
413
  invocation.state = rest;
@@ -1,6 +1,6 @@
1
1
  import { HostSuspension } from "../host-suspension.js";
2
2
  import { normalizeCandidate } from "../model/normalize.js";
3
- import { HarnessError, isHarnessError } from "@nylorun/core/define";
3
+ import { HarnessError, isHarnessError, isModelFailureOutcome } from "@nylorun/core/define";
4
4
  import { copyJson } from "@nylorun/core/define";
5
5
  import { runMiddleware } from "./compose.js";
6
6
  import { ContextDraft } from "./context-draft.js";
@@ -149,6 +149,14 @@ export async function runStep(input) {
149
149
  });
150
150
  if (input.signal.aborted)
151
151
  throw input.signal.reason;
152
+ // A provider failure the adapter classified ends the step with `model.<code>`.
153
+ if (isModelFailureOutcome(outcome))
154
+ throw new HarnessError(`model.${outcome.code}`, outcome.message, {
155
+ details: {
156
+ retryable: outcome.retryable,
157
+ ...(outcome.retryAfterMs === undefined ? {} : { retryAfterMs: outcome.retryAfterMs }),
158
+ },
159
+ });
152
160
  const minted = context.mintFromModel(normalizeCandidate(outcome));
153
161
  const candidate = context.currentCandidate;
154
162
  if (!candidate)
@@ -60,6 +60,26 @@ function entryAt(value, index) {
60
60
  });
61
61
  return result;
62
62
  }
63
+ case "compaction": {
64
+ exactKeys(entry, ["kind", "turnId", "stepId", "summary", "trigger", "tokensBefore", "tokensAfter"], `Transcript entry ${index}`);
65
+ requiredString(entry.stepId, `Transcript entry ${index} stepId`);
66
+ if (typeof entry.summary !== "string")
67
+ fail(`Transcript entry ${index} summary`);
68
+ if (entry.trigger !== "threshold" && entry.trigger !== "overflow")
69
+ fail(`Transcript entry ${index} trigger`);
70
+ for (const key of ["tokensBefore", "tokensAfter"])
71
+ if (!Number.isInteger(entry[key]) || entry[key] < 0)
72
+ fail(`Transcript entry ${index} ${key}`);
73
+ return Object.freeze({
74
+ kind: "compaction",
75
+ turnId: entry.turnId,
76
+ stepId: entry.stepId,
77
+ summary: entry.summary,
78
+ trigger: entry.trigger,
79
+ tokensBefore: entry.tokensBefore,
80
+ tokensAfter: entry.tokensAfter,
81
+ });
82
+ }
63
83
  case "final":
64
84
  exactKeys(entry, ["kind", "turnId", "stepId", "output"], `Transcript entry ${index}`);
65
85
  requiredString(entry.stepId, `Transcript entry ${index} stepId`);
@@ -65,7 +65,7 @@ export type DurableResult = {
65
65
  readonly checkpoint: DurableCheckpoint;
66
66
  readonly effectIds: readonly string[];
67
67
  } | {
68
- readonly status: "completed" | "paused" | "cancelled" | "failed";
68
+ readonly status: "completed" | "paused" | "cancelled" | "failed" | "yielded";
69
69
  readonly checkpoint: DurableCheckpoint;
70
70
  readonly result: RunResult<unknown>;
71
71
  };
@@ -98,4 +98,9 @@ export declare function runDurable(options: {
98
98
  host: DurableHost;
99
99
  signal?: AbortSignal;
100
100
  sessionTools?: readonly DurableSessionTool[];
101
+ /** Segment rollover (Model Calls §10): yield after this many steps or milliseconds. */
102
+ yieldAfter?: {
103
+ readonly steps?: number;
104
+ readonly ms?: number;
105
+ };
101
106
  }): Promise<DurableResult>;
@@ -150,7 +150,7 @@ export async function runDurable(options) {
150
150
  name: tool.name,
151
151
  })),
152
152
  }));
153
- // All capabilities registered at a hook point share one effect, so one executor round trip.
153
+ // All capabilities registered at a hook point share one effect, so one Action delivery.
154
154
  const runHooks = async ({ point, capabilityIds, args, identity }) => {
155
155
  const outcome = await effect("hook", args, { info: checkpoint.info }, scoped(ref, identity), {
156
156
  hook: { at: point.at, scope: point.scope, capabilityIds },
@@ -163,7 +163,12 @@ export async function runDurable(options) {
163
163
  };
164
164
  return Object.freeze({ ...definition, runHooks });
165
165
  };
166
- const modelCall = (ref) => async (call, ctx) => (await effect("model", call, { request: ctx.request, invocationId: ctx.invocationId }, scoped(ref, ctx.invocationId), ref ? { agent: ref } : {})).value;
166
+ const modelCall = (ref) => async (call, ctx) => (await effect("model", call,
167
+ // The call already holds the whole prompt; journaling the request would store it twice.
168
+ {
169
+ invocationId: ctx.invocationId,
170
+ ...(ctx.compaction ? { compaction: ctx.compaction } : {}),
171
+ }, scoped(ref, ctx.invocationId), ref ? { agent: ref } : {})).value;
167
172
  const delegation = {
168
173
  child: (delegate, ref) => ({
169
174
  definition: hostedDefinition(delegate.manifest, ref),
@@ -193,7 +198,7 @@ export async function runDurable(options) {
193
198
  info: checkpoint.info,
194
199
  signal: options.signal,
195
200
  onModelCall: modelCall(),
196
- }, { delegation }));
201
+ }, { delegation, ...(options.yieldAfter ? { yieldAfter: options.yieldAfter } : {}) }));
197
202
  return { status: result.status, checkpoint: { ...checkpoint, state: result.state }, result };
198
203
  }
199
204
  catch (error) {
@@ -132,4 +132,12 @@ export type RunResult<Output = string> = {
132
132
  readonly status: "failed";
133
133
  readonly state: ExecutionState;
134
134
  readonly error: Tripwire;
135
+ }
136
+ /**
137
+ * A durable segment ended at a step boundary so the turn continues in a new segment
138
+ * (Model Calls §10). The state is mid-turn; resume it with `{ kind: "continue" }`.
139
+ */
140
+ | {
141
+ readonly status: "yielded";
142
+ readonly state: ExecutionState;
135
143
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nylorun/harness",
3
- "version": "0.20.0-beta",
3
+ "version": "0.21.0-beta",
4
4
  "description": "Nylorun's TypeScript agent execution engine. See github.com/nylorun/agents.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -65,7 +65,8 @@
65
65
  "format": "prettier --write .",
66
66
  "format:check": "prettier --check .",
67
67
  "clean": "node -e \"import('node:fs').then(({rmSync})=>rmSync('dist',{recursive:true,force:true}))\"",
68
- "prepack": "npm run build"
68
+ "prepack": "npm run build",
69
+ "eval:compaction": "vitest run test/compaction-eval.test.ts"
69
70
  },
70
71
  "devDependencies": {
71
72
  "@types/node": "^26.5.0",
@@ -76,7 +77,7 @@
76
77
  "zod": "^4.6.5"
77
78
  },
78
79
  "dependencies": {
79
- "@nylorun/core": "0.8.0-beta"
80
+ "@nylorun/core": "0.9.0-beta"
80
81
  },
81
82
  "peerDependencies": {
82
83
  "zod": "^4.6.5"