@nylorun/harness 0.21.2-beta → 0.22.1-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,45 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.22.1-beta
4
+
5
+ ### Patch Changes
6
+
7
+ - Pin core to the tested release.
8
+ - Updated dependencies [8773586]
9
+ - Updated dependencies [e1bfb4b]
10
+ - Updated dependencies [5cfaed9]
11
+ - Updated dependencies [bd478ee]
12
+ - Updated dependencies [c0b604e]
13
+ - @nylorun/core@0.13.0-beta
14
+
15
+ ## 0.22.0-beta
16
+
17
+ ### Minor Changes
18
+
19
+ - b6bf1f5: **Harness API v1, in process (F6.1).** Every segment now runs in a harness: the advance takes the session's lease and offers the segment as a run, and the Tenant's own harness, in the same process, runs the engine and reports how it ended. Core settles it exactly as before. Nothing changes on the wire: protocol 5, durable checkpoint 1, engine `hosted-3` and the Action endpoint wire are the same.
20
+
21
+ - `@nylorun/core/harness-api`: the protocol (messages, Zod schemas, the effect request hash, transcript edits, an RPC channel with an in-process memory transport).
22
+ - `@nylorun/harness/api`: `createHarness({ channel, executors })`, a harness that leases runs, renews their leases, replays a run's recorded outcomes without asking, keeps transcripts by record cursor, and runs model, MCP and sandbox calls through the executors it is given.
23
+ - `@nylorun/runtime`: the Harness API server per Tenant (`TenantHandle.attachHarness`), the in-process harness, and the journal as the Record seam. A model call's journal row now stores the request's hash without its prompt, so a replay never sends a prompt twice. `NYLORUN_HARNESS_API=0` runs the engine in the advance as before, until F6.2 removes it. A Runtime older than this one may fail a turn that was in flight across a downgrade with drift.
24
+
25
+ - 8ed4ea6: **Harness service over WebSocket, with the workspace capability (F6.2).** A Runtime started with `NYLORUN_HARNESS=remote` runs no harness of its own: it opens the Harness API listener (`NYLORUN_HARNESS_LISTEN_HOST`/`_PORT`, default port 4200, `NYLORUN_HARNESS_ALLOWED_HOSTS`), which accepts only the harness credential (`NYLORUN_HARNESS_TOKEN`) on `/nylorun/harness/v1`. The runtime image's `--service harness` connects to it (`NYLORUN_HARNESS_URL`, `NYLORUN_HARNESS_TOKEN`, `NYLORUN_GATES_URL`, `NYLORUN_HARNESS_ROOT`) and runs the Tenant's segments, MCP servers and sandboxes with no store; it refuses to start with a database, the gates' or keys' credential, or Restate settings, and presents only run tokens at the gates. The in-process harness stays the default.
26
+
27
+ - `@nylorun/core/harness-api`: the `workspace.*` requests core sends to a harness that serves workspaces, `tenantId` in the `hello` answer, a workspace record on `sandbox.state` claims, and `TurnStart.options.holdMs`. Tenant and admin status report the Tenant's harnesses (`harness`).
28
+ - `@nylorun/harness/api`: `createHarness` declares capabilities, reports grants (`onGrant`) and the `hello` answer, readies MCP through `executors.prepare` (`session.mcp`), and holds a run while its Action is pending until core sends the outcome (`effect.resolved`).
29
+ - `@nylorun/runtime`: the WebSocket listener and client, `--service harness`, the workspace capability (`ctx.sandbox` is a `WorkspacePort`; sandbox tool routes, `save_artifact`, sweep and reset reach the harness's workspaces), the SandboxManager's records port, and held runs (`actionHoldMs`, default 5 minutes). `save_artifact` runs in core. `NYLORUN_HARNESS_API` and the engine run in the advance are removed; tests run with `NYLORUN_TEST_HARNESS=memory|json|ws`.
30
+
31
+ ### Patch Changes
32
+
33
+ - 167d01a: **A run core stops while it asks about a pending Action is no longer held.** When core cancelled a run, or stopped it for a shutdown, while the harness waited for core's answer to an Action's `effect.intent`, the harness then held the run for the whole `holdMs` (5 minutes by default): it listened for an abort that had already happened. The run kept its lease, and closing the Tenant waited for it. The harness now gives such a run back at once.
34
+ - Pin core to the tested release.
35
+ - Updated dependencies [b352feb]
36
+ - Updated dependencies [6077272]
37
+ - Updated dependencies [b6bf1f5]
38
+ - Updated dependencies [8ed4ea6]
39
+ - Updated dependencies [678e085]
40
+ - Updated dependencies [926711b]
41
+ - @nylorun/core@0.12.0-beta
42
+
3
43
  ## 0.21.2-beta
4
44
 
5
45
  ### Patch Changes
package/HOST_CONTRACT.md CHANGED
@@ -4,7 +4,7 @@ Artifact: `@nylorun/harness@0.14.0-beta.3`. Package version is separate from pro
4
4
 
5
5
  ## HTTP (both hosts)
6
6
 
7
- Bearer application credentials: `PUT /v1/agents/:agentId` (`PutAgentRequest`: requestId, complete manifest, implementationVersion, optional pluginRoots); `PUT /v1/sessions/:sessionId` (`PutSessionRequest`: requestId, agentId, trusted ownerUserId, optional info, optional vaultIds, optional credentialSelections, 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.
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` (application principals acting for no one; subjects and token callers are refused, protocol 7). 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
 
@@ -15,8 +15,7 @@ unsupported protocol → `426` with
15
15
  `{ status: "rejected", code: "protocol_unsupported", protocol }` before
16
16
  authentication. For one release the Host also serves protocol 4 clients, which
17
17
  send `Nylorun-Tenant`: a header naming the Host's Tenant is accepted, one naming
18
- another Tenant (or a malformed one), or a publishable key of another Tenant, is
19
- the opaque `404`. A Tenant id in the query string or body is ignored. A Tenant
18
+ another Tenant (or a malformed one) is the opaque `404`. A Tenant id in the query string or body is ignored. A Tenant
20
19
  that could not be opened, an unknown Tenant and a rejected credential share the
21
20
  opaque `404` body. Admin routes use the Host admin key and never accept a
22
21
  Tenant bearer; there are no Admin Tenant routes. Vocabulary:
@@ -36,7 +35,7 @@ All command idempotency keys bind to canonical request content within a session;
36
35
 
37
36
  `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.
38
37
 
39
- 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.
38
+ 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, except that a Harness API run may hold its lease for a pending Action's outcome (below). 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.
40
39
 
41
40
  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.
42
41
 
@@ -50,6 +49,22 @@ Agents used as tools: a manifest tool with an `agent` body (the child manifest i
50
49
 
51
50
  **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.
52
51
 
52
+ ## Harness API v1
53
+
54
+ The Runtime runs every segment through the Harness API (blueprint D37–D42): core keeps scheduling, the record, settle and takeover; a harness runs the engine. Protocol types, schemas, the request hash, transcript edits and the RPC channel are `@nylorun/core/harness-api` (`HARNESS_API_VERSION = 1`); the harness client is `@nylorun/harness/api` (`createHarness({channel, executors})`). A Tenant runs one harness in its own process over a memory channel, or (F6.2, `NYLORUN_HARNESS=remote`) harnesses connect to core's Harness API listener over WebSocket (`/nylorun/harness/v1`, the harness credential): `--service harness` runs one with its own MCP pool and sandboxes and no store, and serves the Tenant's workspaces (`workspace.*`). Protocol 5, durable checkpoint 1, engine `hosted-3` and the Action wire are unchanged.
55
+
56
+ Held runs (F6.2): when core answers an effect intent of an Action (a tool, hook, `fn` or `verify` an Action endpoint runs) with `pending`, the run may wait in its lease for the outcome (`effect.resolved`), at most `TurnStart.options.holdMs` (default 5 minutes) and never past the segment's yield budget, renewing as usual. The outcome resolves the effect locally and the segment goes on; past the hold the segment ends as waiting and the outcome resumes it by replay, as before. The journal is unchanged either way: the outcome is recorded before it is sent.
57
+
58
+ Frames: `{t:"req",id,m,p}`, `{t:"res",id,ok,r|e:{code,message}}`, `{t:"msg",m,p}`, `{t:"abort",id}`, `{t:"ping"}`. Error codes: `run_not_held`, `turn_cancelled`, `ownership_lost`, `effect_drift`, `invalid`, `unavailable`, `internal`; the message is today's (`Turn cancelled`, `Effect identity request drift`, …).
59
+
60
+ - **Work.** `hello` → `{api, sandbox:{backend}, renewEveryMs}`. A harness keeps one `lease` waiting; an advance that took a session's lease offers its segment, and the answer is `{run: {runId, sessionId, turnId, epoch, token?, tokenExpiresAt?}, input: TurnStart}`. A run is bound to the connection that leased it. `lease.renew` every `renewEveryMs` renews the session's ownership lease (`{ok:false}`: lost, abort with `ownership.lost`); `lease.release{reason}` gives the run back (`shutdown`, `ownership.lost`; a lost connection counts as `connection.lost`).
61
+ - **Input.** `TurnStart` (`type` `turn.start`, or `approval.answer` for approve/respond): `engine` (`agent` | `flow`), the turn's `manifest`, the segment's `checkpoint` with an empty transcript, `sessionTools`, the segment's completed `outcomes` (`{effectId, requestHash, outcome}`), `transcript.cursor`, `options` (`yieldAfter`, `flowLimits`, `fixtureModel`) and `routing` (root manifest, plugin roots, MCP snapshot, sandbox owner). Core aborts a run with `cancel{runId, reason, message}`, `reason` one of `cancel`, `shutdown`, `deadline`, `ownership.lost`.
62
+ - **Record.** `requestHash = sha256(canonical(requestIdentity(effect)))` (canonical JSON: keys by code unit, `undefined` dropped; a delegation's identity leaves out `context`). An effect in `outcomes` with the same hash resolves in the harness; another hash is drift. Any other effect is an `effect.intent{effect, requestHash}`: a model intent carries no `input`, so a prompt never crosses twice. Core journals the row with `requestHash` (a model row without `input`) and answers `completed`, `pending`, `uncertain`, or `execute` (`rejoin` for a call its gate recovers, P1.2/F4.1). The harness executes model, MCP and sandbox calls and reports `effect.outcome{value}` or `{error}` (uncertain); after a `shutdown` a recoverable call reports nothing and stays `invoking`. Core runs Actions, hooks, `fn`, `verify`, flow tool nodes, linked sessions and delegation journaling. Rows written before carry their full request and are hashed on read.
63
+ - **Transcript.** The cursor is the record seq of the last `transcript.updated`, `turn.cancelled` or `turn.failed`. A harness resumes from its cached transcript at that cursor, else reads it once (`transcript.read`). Outputs carry the agent's state without its transcript plus the `TranscriptUpdate[]` from the transcript the segment started with; core records them and answers with the new cursor.
64
+ - **Output.** `turn.completed`, `turn.paused`, `turn.waiting{status, effectIds}`, `turn.failed{status, error}` or `{thrown}`, and `checkpoint` for a yielded segment; answered `{cursor?}` once core settled it, idempotent per run and type. Core settles them exactly as the engine's own results, classifying aborts from its own signal.
65
+
66
+ A Runtime below F6.1 compares journal rows by their full request: downgrading one with a turn in flight can fail that turn with drift.
67
+
53
68
  ## Definitions, validation, compatibility
54
69
 
55
70
  `/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.
@@ -0,0 +1,16 @@
1
+ import type { AbortReason } from "@nylorun/core/harness-api";
2
+ /** Why a run's signal aborted: the reason core gave in `cancel`, or the harness's own. */
3
+ export declare class RunAbort extends Error {
4
+ readonly kind: AbortReason;
5
+ readonly name: string;
6
+ constructor(kind: AbortReason, message: string, options?: {
7
+ cause?: unknown;
8
+ });
9
+ }
10
+ /** The default message of each reason. */
11
+ export declare const ABORT_MESSAGES: Readonly<Record<AbortReason, string>>;
12
+ /**
13
+ * The kind of an aborted signal's reason, or `undefined` while it has not aborted. A reason
14
+ * that is not a `RunAbort` came from outside the run and counts as `shutdown`.
15
+ */
16
+ export declare function runAbortKind(signal: AbortSignal): AbortReason | undefined;
@@ -0,0 +1,25 @@
1
+ /** Why a run's signal aborted: the reason core gave in `cancel`, or the harness's own. */
2
+ export class RunAbort extends Error {
3
+ kind;
4
+ name = "RunAbort";
5
+ constructor(kind, message, options) {
6
+ super(message, options);
7
+ this.kind = kind;
8
+ }
9
+ }
10
+ /** The default message of each reason. */
11
+ export const ABORT_MESSAGES = {
12
+ cancel: "Turn cancelled",
13
+ shutdown: "The harness is stopping",
14
+ deadline: "The advance ran past its deadline",
15
+ "ownership.lost": "Ownership lost",
16
+ };
17
+ /**
18
+ * The kind of an aborted signal's reason, or `undefined` while it has not aborted. A reason
19
+ * that is not a `RunAbort` came from outside the run and counts as `shutdown`.
20
+ */
21
+ export function runAbortKind(signal) {
22
+ if (!signal.aborted)
23
+ return undefined;
24
+ return signal.reason instanceof RunAbort ? signal.reason.kind : "shutdown";
25
+ }
@@ -0,0 +1,44 @@
1
+ import type { ParamsOf, ResultOf, RunGrant, TurnStart } from "@nylorun/core/harness-api";
2
+ import type { DurableSessionTool, HostEffect } from "../run/durable.js";
3
+ /** A run as the harness holds it: the lease, what it started from, and its signal. */
4
+ export interface HarnessRun {
5
+ readonly runId: string;
6
+ /** The current grant; a renewal may replace its run token. */
7
+ readonly grant: RunGrant;
8
+ readonly start: TurnStart;
9
+ readonly signal: AbortSignal;
10
+ }
11
+ /**
12
+ * What runs the effects the harness executes: model calls, MCP tools and sandbox tools. Core
13
+ * runs everything else (Actions, hooks, flow work, linked sessions).
14
+ */
15
+ export interface HarnessExecutors {
16
+ /** A model call. A provider failure is a failure outcome; only an abort throws. */
17
+ model(effect: HostEffect, signal: AbortSignal, run: HarnessRun): Promise<unknown>;
18
+ /** An MCP or sandbox tool call, routed by `run.start.routing`. */
19
+ tool(effect: HostEffect, signal: AbortSignal, run: HarnessRun): Promise<unknown>;
20
+ /**
21
+ * Calls that outlive this process at their gate: a shutdown leaves them running there, and
22
+ * the next run re-sends them (`rejoin`) instead of marking them uncertain.
23
+ */
24
+ readonly recovers: {
25
+ readonly model: boolean;
26
+ remoteMcp(effect: HostEffect, run: HarnessRun): boolean;
27
+ };
28
+ /** Stops a recoverable tool call at its gate after a user cancel. Never rejects. */
29
+ cancelAtGate?(effect: HostEffect, run: HarnessRun): Promise<void>;
30
+ /**
31
+ * Readies the session's MCP servers before an agent's segment runs (F6.2): discovers their
32
+ * tools the first time, reconnects them after. `record` keeps what it found in the session
33
+ * (`session.mcp`; the first snapshot recorded wins) and answers the session's snapshot and
34
+ * tools, which the segment runs with. Undefined: nothing to change.
35
+ */
36
+ prepare?(run: HarnessRun, record: McpRecorder): Promise<PreparedRun | undefined>;
37
+ }
38
+ /** Records a session's MCP discovery in core (`session.mcp`). */
39
+ export type McpRecorder = (params: Omit<ParamsOf<"session.mcp">, "runId">) => Promise<ResultOf<"session.mcp">>;
40
+ /** The session's MCP snapshot and tools after `prepare`. */
41
+ export interface PreparedRun {
42
+ readonly sessionTools: readonly DurableSessionTool[];
43
+ readonly mcpSnapshot?: unknown;
44
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,54 @@
1
+ /**
2
+ * A harness: one long-running client of the Harness API that leases runs and runs them. It says
3
+ * `hello`, then always keeps one `lease` request waiting while it has room. Each run gets its
4
+ * own abort controller: core's `cancel` aborts it with core's reason, a renewal core refuses
5
+ * with `ownership.lost`, and `stop()` with `shutdown`. While a run is live it renews its lease
6
+ * every `renewEveryMs`; renewing stops once the run is aborted.
7
+ *
8
+ * A run whose Action is pending is held (F6.2): it waits up to `holdMs` for core's
9
+ * `effect.resolved` and goes on in the same lease, instead of ending the segment and being
10
+ * replayed by the next one.
11
+ */
12
+ import { type HarnessChannel, type ResultOf, type RunGrant } from "@nylorun/core/harness-api";
13
+ import type { HarnessExecutors } from "./executors.js";
14
+ export interface HarnessLogger {
15
+ warn(message: string, fields?: Record<string, unknown>): void;
16
+ }
17
+ export interface HarnessOptions {
18
+ readonly channel: HarnessChannel;
19
+ readonly executors: HarnessExecutors;
20
+ readonly logger?: HarnessLogger;
21
+ /** Runs held at once. Default: no limit. */
22
+ readonly maxRuns?: number;
23
+ /** Byte budget of the transcript cache. Default 256 MiB. */
24
+ readonly transcriptCacheMb?: number;
25
+ readonly name?: string;
26
+ readonly version?: string;
27
+ /** What `hello` declares: `workspace` when this harness serves the Tenant's workspaces. */
28
+ readonly capabilities?: {
29
+ readonly workspace?: unknown;
30
+ };
31
+ /** Sees core's answer to `hello` (the Tenant, the sandbox backend preference). */
32
+ onHello?(answer: ResultOf<"hello">): void;
33
+ /** Sees every grant a run gets: when it is leased, and each renewal with a new run token. */
34
+ onGrant?(grant: RunGrant): void;
35
+ /**
36
+ * The longest a run waits for a pending Action's outcome before its segment ends as waiting:
37
+ * core says how long each run may (`TurnStart.options.holdMs`), never past the segment's
38
+ * yield budget. Default: as long as core says.
39
+ */
40
+ readonly holdMs?: number;
41
+ }
42
+ export interface Harness {
43
+ /** Says `hello` and starts leasing. Resolves once `hello` is answered. */
44
+ start(): Promise<void>;
45
+ /**
46
+ * Stops leasing, aborts the runs with `shutdown`, and waits for them to give their leases
47
+ * back, at most `waitMs` (default: as long as they take). A run that ignores its abort is
48
+ * left behind: its lease lapses.
49
+ */
50
+ stop(waitMs?: number): Promise<void>;
51
+ /** Runs held now. */
52
+ readonly runs: number;
53
+ }
54
+ export declare function createHarness(options: HarnessOptions): Harness;
@@ -0,0 +1,190 @@
1
+ /**
2
+ * A harness: one long-running client of the Harness API that leases runs and runs them. It says
3
+ * `hello`, then always keeps one `lease` request waiting while it has room. Each run gets its
4
+ * own abort controller: core's `cancel` aborts it with core's reason, a renewal core refuses
5
+ * with `ownership.lost`, and `stop()` with `shutdown`. While a run is live it renews its lease
6
+ * every `renewEveryMs`; renewing stops once the run is aborted.
7
+ *
8
+ * A run whose Action is pending is held (F6.2): it waits up to `holdMs` for core's
9
+ * `effect.resolved` and goes on in the same lease, instead of ending the segment and being
10
+ * replayed by the next one.
11
+ */
12
+ import { HARNESS_API_VERSION, } from "@nylorun/core/harness-api";
13
+ import { ABORT_MESSAGES, RunAbort } from "./abort.js";
14
+ import { runTurn } from "./run.js";
15
+ import { TranscriptCache } from "./transcript-cache.js";
16
+ export function createHarness(options) {
17
+ const { channel, executors } = options;
18
+ const maxRuns = options.maxRuns ?? Infinity;
19
+ const cache = new TranscriptCache((options.transcriptCacheMb ?? 256) * 1024 * 1024);
20
+ const live = new Map();
21
+ const finished = new Set();
22
+ const leasing = new AbortController();
23
+ let renewEveryMs = 10_000;
24
+ let stopped = false;
25
+ let waiting = false;
26
+ const abort = (run, kind, message) => {
27
+ if (!run.controller.signal.aborted)
28
+ run.controller.abort(new RunAbort(kind, message ?? ABORT_MESSAGES[kind]));
29
+ };
30
+ channel.listen((method, params) => {
31
+ if (method === "effect.resolved") {
32
+ const { runId, effectId, outcome } = params;
33
+ const run = live.get(runId);
34
+ if (!run)
35
+ return;
36
+ const waiter = run.waiting.get(effectId);
37
+ if (waiter)
38
+ waiter(outcome);
39
+ else
40
+ run.resolved.set(effectId, outcome);
41
+ return;
42
+ }
43
+ if (method !== "cancel")
44
+ return;
45
+ const { runId, reason, message } = params;
46
+ const run = live.get(runId);
47
+ if (run)
48
+ abort(run, reason, message);
49
+ });
50
+ /** Waits for core's outcome of a pending Action of `run`, at most `ms`, or until it aborts. */
51
+ const hold = (held, effectId, ms) => {
52
+ const run = live.get(held.runId);
53
+ // Core may stop the run while it asks about the Action (a cancel, or a shutdown on close):
54
+ // its abort fired already, so a listener added now would never run, and the run would
55
+ // keep its lease for the whole hold.
56
+ if (!run || ms <= 0 || run.signal.aborted)
57
+ return Promise.resolve(undefined);
58
+ const known = run.resolved.get(effectId);
59
+ if (known) {
60
+ run.resolved.delete(effectId);
61
+ return Promise.resolve(known);
62
+ }
63
+ return new Promise((resolve) => {
64
+ const done = (outcome) => {
65
+ clearTimeout(timer);
66
+ run.waiting.delete(effectId);
67
+ run.signal.removeEventListener("abort", aborted);
68
+ resolve(outcome);
69
+ };
70
+ const aborted = () => done(undefined);
71
+ const timer = setTimeout(() => done(undefined), ms);
72
+ timer.unref?.();
73
+ run.waiting.set(effectId, done);
74
+ run.signal.addEventListener("abort", aborted, { once: true });
75
+ });
76
+ };
77
+ channel.onClose(() => {
78
+ for (const run of live.values())
79
+ abort(run, "shutdown", "The Harness API connection closed");
80
+ });
81
+ const renew = (run) => {
82
+ const timer = setInterval(() => {
83
+ if (run.controller.signal.aborted)
84
+ return clearInterval(timer);
85
+ channel.request("lease.renew", { runId: run.runId }).then((answer) => {
86
+ if (!answer.ok)
87
+ abort(run, "ownership.lost");
88
+ else if (answer.token && answer.token !== run.grant.token) {
89
+ run.grant = {
90
+ ...run.grant,
91
+ token: answer.token,
92
+ tokenExpiresAt: answer.tokenExpiresAt,
93
+ };
94
+ options.onGrant?.(run.grant);
95
+ }
96
+ }, (error) => {
97
+ if (!run.controller.signal.aborted)
98
+ options.logger?.warn("harness lease renewal failed", {
99
+ runId: run.runId,
100
+ message: error instanceof Error ? error.message : String(error),
101
+ });
102
+ });
103
+ }, renewEveryMs);
104
+ timer.unref?.();
105
+ return () => clearInterval(timer);
106
+ };
107
+ const begin = (grant, start) => {
108
+ const controller = new AbortController();
109
+ const run = {
110
+ runId: grant.runId,
111
+ grant,
112
+ start,
113
+ controller,
114
+ signal: controller.signal,
115
+ resolved: new Map(),
116
+ waiting: new Map(),
117
+ };
118
+ live.set(run.runId, run);
119
+ options.onGrant?.(grant);
120
+ const stopRenewing = renew(run);
121
+ const done = runTurn({
122
+ channel,
123
+ executors,
124
+ cache,
125
+ hold,
126
+ ...(options.holdMs === undefined ? {} : { holdMs: options.holdMs }),
127
+ }, run)
128
+ .catch((error) => options.logger?.warn("harness run failed", {
129
+ runId: run.runId,
130
+ message: error instanceof Error ? error.message : String(error),
131
+ }))
132
+ .finally(() => {
133
+ stopRenewing();
134
+ live.delete(run.runId);
135
+ finished.delete(done);
136
+ lease();
137
+ });
138
+ finished.add(done);
139
+ };
140
+ const lease = () => {
141
+ if (stopped || waiting || channel.closed || live.size >= maxRuns)
142
+ return;
143
+ waiting = true;
144
+ channel.request("lease", {}, leasing.signal).then(({ run, input }) => {
145
+ waiting = false;
146
+ begin(run, input);
147
+ lease();
148
+ }, (error) => {
149
+ waiting = false;
150
+ if (stopped || channel.closed)
151
+ return;
152
+ options.logger?.warn("harness lease failed", {
153
+ message: error instanceof Error ? error.message : String(error),
154
+ });
155
+ setTimeout(lease, 100).unref?.();
156
+ });
157
+ };
158
+ return {
159
+ get runs() {
160
+ return live.size;
161
+ },
162
+ async start() {
163
+ const hello = await channel.request("hello", {
164
+ api: HARNESS_API_VERSION,
165
+ name: options.name ?? "@nylorun/harness",
166
+ version: options.version ?? "0",
167
+ capabilities: options.capabilities?.workspace === undefined
168
+ ? {}
169
+ : { workspace: options.capabilities.workspace },
170
+ });
171
+ renewEveryMs = hello.renewEveryMs;
172
+ options.onHello?.(hello);
173
+ lease();
174
+ },
175
+ async stop(waitMs = Infinity) {
176
+ stopped = true;
177
+ leasing.abort(new RunAbort("shutdown", ABORT_MESSAGES.shutdown));
178
+ for (const run of live.values())
179
+ abort(run, "shutdown");
180
+ let timer;
181
+ await Promise.race([
182
+ Promise.allSettled([...finished]),
183
+ ...(Number.isFinite(waitMs)
184
+ ? [new Promise((resolve) => (timer = setTimeout(resolve, waitMs)))]
185
+ : []),
186
+ ]);
187
+ clearTimeout(timer);
188
+ },
189
+ };
190
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The engine's `DurableHost` over the Harness API. An effect whose outcome came with the run
3
+ * (same id, same request hash) resolves here; any other becomes an `effect.intent`. A model
4
+ * intent carries no prompt: core stores its hash. When core answers `execute`, the harness runs
5
+ * the call and reports its outcome. When it answers `pending` for an Action (a tool, hook, `fn`
6
+ * or `verify` an Action endpoint runs), the run may hold for its outcome (`options.hold`).
7
+ */
8
+ import { type HarnessChannel } from "@nylorun/core/harness-api";
9
+ import type { ActionOutcome } from "@nylorun/core/contracts";
10
+ import type { DurableHost } from "../run/durable.js";
11
+ import type { HarnessExecutors, HarnessRun } from "./executors.js";
12
+ export interface ApiHostOptions {
13
+ /** Waits for core's outcome of a pending Action; undefined when none came in time. */
14
+ readonly hold?: (effectId: string) => Promise<ActionOutcome | undefined>;
15
+ }
16
+ export declare function apiHost(channel: HarnessChannel, executors: HarnessExecutors, run: HarnessRun, options?: ApiHostOptions): DurableHost;
@@ -0,0 +1,85 @@
1
+ /**
2
+ * The engine's `DurableHost` over the Harness API. An effect whose outcome came with the run
3
+ * (same id, same request hash) resolves here; any other becomes an `effect.intent`. A model
4
+ * intent carries no prompt: core stores its hash. When core answers `execute`, the harness runs
5
+ * the call and reports its outcome. When it answers `pending` for an Action (a tool, hook, `fn`
6
+ * or `verify` an Action endpoint runs), the run may hold for its outcome (`options.hold`).
7
+ */
8
+ import { HarnessApiError, effectRequestHash, } from "@nylorun/core/harness-api";
9
+ import { runAbortKind } from "./abort.js";
10
+ /** Effects whose `pending` is an Action endpoint's work, which a run may hold for. */
11
+ const HELD_KINDS = new Set(["tool", "hook", "fn", "verify"]);
12
+ export function apiHost(channel, executors, run, options = {}) {
13
+ const recorded = new Map(run.start.outcomes.map((outcome) => [outcome.effectId, outcome]));
14
+ const { signal, runId } = run;
15
+ const ask = async (method, params) => {
16
+ try {
17
+ return await channel.request(method, params);
18
+ }
19
+ catch (error) {
20
+ // Core stopped the run: the engine sees the abort, as it would its own.
21
+ if (signal.aborted)
22
+ throw signal.reason;
23
+ throw error;
24
+ }
25
+ };
26
+ const execute = async (effect) => {
27
+ const model = effect.kind === "model";
28
+ try {
29
+ const value = model
30
+ ? await executors.model(effect, signal, run)
31
+ : await executors.tool(effect, signal, run);
32
+ return await ask("effect.outcome", { runId, effectId: effect.effectId, value });
33
+ }
34
+ catch (error) {
35
+ // Another owner decides what the effect became.
36
+ if (error instanceof HarnessApiError && error.code === "ownership_lost")
37
+ throw error;
38
+ const recoverable = model
39
+ ? executors.recovers.model
40
+ : executors.recovers.remoteMcp(effect, run);
41
+ const kind = runAbortKind(signal);
42
+ // The call goes on at its gate: the next run re-sends it and collects its outcome.
43
+ if (recoverable && kind === "shutdown")
44
+ throw error;
45
+ if (recoverable && !model && kind === "cancel")
46
+ await executors.cancelAtGate?.(effect, run);
47
+ return ask("effect.outcome", {
48
+ runId,
49
+ effectId: effect.effectId,
50
+ error: error instanceof Error ? error.message : String(error),
51
+ });
52
+ }
53
+ };
54
+ return {
55
+ async resolveEffect(effect) {
56
+ if (signal.aborted)
57
+ throw signal.reason;
58
+ const requestHash = effectRequestHash(effect);
59
+ const known = recorded.get(effect.effectId);
60
+ if (known) {
61
+ if (known.requestHash !== requestHash)
62
+ throw new HarnessApiError("effect_drift", "Effect identity request drift");
63
+ return { status: "completed", outcome: known.outcome };
64
+ }
65
+ const answer = await ask("effect.intent", { runId, effect: intentOf(effect), requestHash });
66
+ if (answer.status === "execute")
67
+ return execute(effect);
68
+ if (answer.status === "pending" && options.hold && HELD_KINDS.has(effect.kind)) {
69
+ const outcome = await options.hold(effect.effectId);
70
+ if (signal.aborted)
71
+ throw signal.reason;
72
+ if (outcome)
73
+ return { status: "completed", outcome };
74
+ }
75
+ return answer;
76
+ },
77
+ };
78
+ }
79
+ /** What crosses for an effect: a model call's prompt stays here. */
80
+ function intentOf(effect) {
81
+ if (effect.kind !== "model")
82
+ return effect;
83
+ const { input: _, ...intent } = effect;
84
+ return intent;
85
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * `@nylorun/harness/api`: a harness over the Harness API v1. It leases runs from core, resumes
3
+ * the engine with a DurableHost over the record, and runs model, MCP and sandbox calls through
4
+ * the executors it is given.
5
+ */
6
+ export { createHarness, type Harness, type HarnessLogger, type HarnessOptions } from "./harness.js";
7
+ export { ABORT_MESSAGES, RunAbort, runAbortKind } from "./abort.js";
8
+ export type { HarnessExecutors, HarnessRun, McpRecorder, PreparedRun } from "./executors.js";
9
+ export { apiHost } from "./host.js";
10
+ export { runTurn, type RunContext } from "./run.js";
11
+ export { TranscriptCache } from "./transcript-cache.js";
@@ -0,0 +1,10 @@
1
+ /**
2
+ * `@nylorun/harness/api`: a harness over the Harness API v1. It leases runs from core, resumes
3
+ * the engine with a DurableHost over the record, and runs model, MCP and sandbox calls through
4
+ * the executors it is given.
5
+ */
6
+ export { createHarness } from "./harness.js";
7
+ export { ABORT_MESSAGES, RunAbort, runAbortKind } from "./abort.js";
8
+ export { apiHost } from "./host.js";
9
+ export { runTurn } from "./run.js";
10
+ export { TranscriptCache } from "./transcript-cache.js";
@@ -0,0 +1,28 @@
1
+ /**
2
+ * One run: resume the engine from `turn.start` with the session's transcript (cached, or read
3
+ * once), run the segment over the API host, and report how it ended. Core settles it and
4
+ * answers with the record position the transcript is now at.
5
+ *
6
+ * A run core stopped for a shutdown or a lost lease is given back (`lease.release`); core
7
+ * settles nothing for it, as it never did for an advance it stopped.
8
+ */
9
+ import { type HarnessChannel } from "@nylorun/core/harness-api";
10
+ import type { ActionOutcome } from "@nylorun/core/contracts";
11
+ import type { HarnessExecutors, HarnessRun } from "./executors.js";
12
+ import type { TranscriptCache } from "./transcript-cache.js";
13
+ export interface RunContext {
14
+ readonly channel: HarnessChannel;
15
+ readonly executors: HarnessExecutors;
16
+ readonly cache: TranscriptCache;
17
+ /**
18
+ * Waits up to `ms` for core's outcome of a pending Action of the run (`effect.resolved`).
19
+ * Absent: a pending Action ends the segment.
20
+ */
21
+ readonly hold?: (run: HarnessRun, effectId: string, ms: number) => Promise<ActionOutcome | undefined>;
22
+ /**
23
+ * The longest this harness holds a run for a pending Action; core says how long each run
24
+ * may (`TurnStart.options.holdMs`), and never past its yield budget.
25
+ */
26
+ readonly holdMs?: number;
27
+ }
28
+ export declare function runTurn(ctx: RunContext, run: HarnessRun): Promise<void>;
@@ -0,0 +1,161 @@
1
+ /**
2
+ * One run: resume the engine from `turn.start` with the session's transcript (cached, or read
3
+ * once), run the segment over the API host, and report how it ended. Core settles it and
4
+ * answers with the record position the transcript is now at.
5
+ *
6
+ * A run core stopped for a shutdown or a lost lease is given back (`lease.release`); core
7
+ * settles nothing for it, as it never did for an advance it stopped.
8
+ */
9
+ import { transcriptOf, transcriptUpdates, withTranscript, } from "@nylorun/core/harness-api";
10
+ import { runDurable } from "../run/durable.js";
11
+ import { runFlowDurable } from "../flow/engine.js";
12
+ import { runAbortKind } from "./abort.js";
13
+ import { apiHost } from "./host.js";
14
+ const METHODS = {
15
+ completed: "turn.completed",
16
+ paused: "turn.paused",
17
+ yielded: "checkpoint",
18
+ waiting: "turn.waiting",
19
+ uncertain: "turn.waiting",
20
+ failed: "turn.failed",
21
+ cancelled: "turn.failed",
22
+ };
23
+ export async function runTurn(ctx, run) {
24
+ const { runId, signal } = run;
25
+ let { start } = run;
26
+ const sessionId = run.grant.sessionId;
27
+ const cursor = start.transcript.cursor;
28
+ const startedAt = Date.now();
29
+ let transcript = [];
30
+ let output;
31
+ let after;
32
+ try {
33
+ if (start.engine === "agent" && ctx.executors.prepare) {
34
+ const prepared = await ctx.executors.prepare(run, (params) => ctx.channel.request("session.mcp", { runId, ...params }));
35
+ if (prepared) {
36
+ start = {
37
+ ...start,
38
+ sessionTools: prepared.sessionTools,
39
+ routing: {
40
+ ...start.routing,
41
+ ...(prepared.mcpSnapshot === undefined ? {} : { mcpSnapshot: prepared.mcpSnapshot }),
42
+ },
43
+ };
44
+ // The executors route this run's MCP calls by the snapshot it now has.
45
+ run.start = start;
46
+ }
47
+ }
48
+ let checkpoint = start.checkpoint;
49
+ if (start.engine === "agent" && checkpoint.state) {
50
+ transcript = ctx.cache.get(sessionId, cursor) ?? (await read(ctx, run));
51
+ checkpoint = { ...checkpoint, state: withTranscript(checkpoint.state, transcript) };
52
+ }
53
+ const budget = start.options.yieldAfter?.ms;
54
+ const holdMs = Math.min(start.options.holdMs ?? 0, ctx.holdMs ?? Infinity);
55
+ const host = apiHost(ctx.channel, ctx.executors, run, {
56
+ ...(ctx.hold && holdMs > 0
57
+ ? {
58
+ // Never past the segment's yield budget: the turn rolls over there anyway.
59
+ hold: (effectId) => ctx.hold(run, effectId, Math.min(holdMs, budget === undefined ? Infinity : budget - (Date.now() - startedAt))),
60
+ }
61
+ : {}),
62
+ });
63
+ const result = start.engine === "flow"
64
+ ? await runFlowDurable({
65
+ manifest: start.manifest,
66
+ checkpoint: start.checkpoint,
67
+ signal,
68
+ host,
69
+ limits: start.options.flowLimits,
70
+ })
71
+ : await runDurable({
72
+ manifest: start.manifest,
73
+ checkpoint,
74
+ signal,
75
+ host,
76
+ sessionTools: start.sessionTools,
77
+ ...(start.options.yieldAfter ? { yieldAfter: start.options.yieldAfter } : {}),
78
+ });
79
+ ({ output, after } = outputOf(runId, result, transcript));
80
+ }
81
+ catch (error) {
82
+ output = {
83
+ runId,
84
+ thrown: {
85
+ ...(typeof error?.code === "string"
86
+ ? { code: error.code }
87
+ : {}),
88
+ message: error instanceof Error ? error.message : String(error),
89
+ },
90
+ };
91
+ }
92
+ const kind = runAbortKind(signal);
93
+ if (kind === "shutdown" || kind === "ownership.lost") {
94
+ await ctx.channel.request("lease.release", { runId, reason: kind }).catch(() => undefined);
95
+ return;
96
+ }
97
+ const status = output.status;
98
+ const settled = await ctx.channel
99
+ .request(status ? METHODS[status] : "turn.failed", output)
100
+ .catch(() => undefined);
101
+ // The cache follows the record: an edited transcript at the cursor core settled it at; a
102
+ // segment that waits leaves it as it started; a failure or cancel reverts it in the fold.
103
+ if (status === "waiting" || status === "uncertain") {
104
+ if (start.engine === "agent")
105
+ ctx.cache.put(sessionId, cursor, transcript);
106
+ }
107
+ else if (after && settled?.cursor !== undefined)
108
+ ctx.cache.put(sessionId, settled.cursor, after, estimate(ctx.cache, sessionId, transcript, output));
109
+ else
110
+ ctx.cache.delete(sessionId);
111
+ }
112
+ /** The edited transcript's size from the cached one's and the edits, without serializing it. */
113
+ function estimate(cache, sessionId, start, output) {
114
+ const base = cache.bytesOf(sessionId);
115
+ const updates = output.transcript ?? [];
116
+ if (base === undefined)
117
+ return undefined;
118
+ if (updates.length === 0)
119
+ return base;
120
+ const keep = updates[0].keep;
121
+ const kept = start.length === 0 ? 0 : Math.round((base * keep) / start.length);
122
+ return updates.reduce((sum, update) => sum + JSON.stringify(update.entries).length, kept);
123
+ }
124
+ async function read(ctx, run) {
125
+ try {
126
+ const { entries } = await ctx.channel.request("transcript.read", { runId: run.runId });
127
+ return entries;
128
+ }
129
+ catch (error) {
130
+ if (run.signal.aborted)
131
+ throw run.signal.reason;
132
+ throw error;
133
+ }
134
+ }
135
+ /** The engine's result as an output. An agent's state goes without its transcript. */
136
+ function outputOf(runId, result, start) {
137
+ if (result.status === "waiting" || result.status === "uncertain")
138
+ return { output: { runId, status: result.status, effectIds: [...result.effectIds] } };
139
+ const outcome = ("result" in result ? result.result : {});
140
+ const fields = {
141
+ ...(outcome.output !== undefined ? { output: outcome.output } : {}),
142
+ ...(outcome.pending !== undefined ? { pending: outcome.pending } : {}),
143
+ ...(outcome.error !== undefined ? { error: outcome.error } : {}),
144
+ ...("cancelEffectIds" in result && result.cancelEffectIds?.length
145
+ ? { cancelEffectIds: [...result.cancelEffectIds] }
146
+ : {}),
147
+ };
148
+ if (outcome.state === undefined)
149
+ return { output: { runId, status: result.status, ...fields } };
150
+ const after = transcriptOf(outcome.state);
151
+ return {
152
+ output: {
153
+ runId,
154
+ status: result.status,
155
+ state: withTranscript(outcome.state, []),
156
+ transcript: transcriptUpdates(start, after),
157
+ ...fields,
158
+ },
159
+ after,
160
+ };
161
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The transcripts of recent sessions, each at the record position (`cursor`) it was folded or
3
+ * settled at. A warm run whose `turn.start` names the cached cursor needs no `transcript.read`.
4
+ * Least recently used sessions are dropped past the byte budget (JSON size, estimated).
5
+ */
6
+ export declare class TranscriptCache {
7
+ private readonly maxBytes;
8
+ private readonly entries;
9
+ private bytes;
10
+ constructor(maxBytes: number);
11
+ /** The transcript of `sessionId` at `cursor`, or undefined. */
12
+ get(sessionId: string, cursor: number): readonly unknown[] | undefined;
13
+ /** Bytes of the cached transcript of `sessionId`, for estimating an edited one. */
14
+ bytesOf(sessionId: string): number | undefined;
15
+ put(sessionId: string, cursor: number, transcript: readonly unknown[], bytes?: number): void;
16
+ delete(sessionId: string): void;
17
+ get size(): number;
18
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * The transcripts of recent sessions, each at the record position (`cursor`) it was folded or
3
+ * settled at. A warm run whose `turn.start` names the cached cursor needs no `transcript.read`.
4
+ * Least recently used sessions are dropped past the byte budget (JSON size, estimated).
5
+ */
6
+ export class TranscriptCache {
7
+ maxBytes;
8
+ entries = new Map();
9
+ bytes = 0;
10
+ constructor(maxBytes) {
11
+ this.maxBytes = maxBytes;
12
+ }
13
+ /** The transcript of `sessionId` at `cursor`, or undefined. */
14
+ get(sessionId, cursor) {
15
+ const entry = this.entries.get(sessionId);
16
+ if (!entry || entry.cursor !== cursor)
17
+ return undefined;
18
+ this.entries.delete(sessionId);
19
+ this.entries.set(sessionId, entry);
20
+ return entry.transcript;
21
+ }
22
+ /** Bytes of the cached transcript of `sessionId`, for estimating an edited one. */
23
+ bytesOf(sessionId) {
24
+ return this.entries.get(sessionId)?.bytes;
25
+ }
26
+ put(sessionId, cursor, transcript, bytes) {
27
+ this.delete(sessionId);
28
+ const size = bytes ?? JSON.stringify(transcript).length;
29
+ if (size > this.maxBytes)
30
+ return;
31
+ this.entries.set(sessionId, { cursor, transcript, bytes: size });
32
+ this.bytes += size;
33
+ for (const [id, entry] of this.entries) {
34
+ if (this.bytes <= this.maxBytes)
35
+ break;
36
+ this.entries.delete(id);
37
+ this.bytes -= entry.bytes;
38
+ }
39
+ }
40
+ delete(sessionId) {
41
+ const entry = this.entries.get(sessionId);
42
+ if (!entry)
43
+ return;
44
+ this.entries.delete(sessionId);
45
+ this.bytes -= entry.bytes;
46
+ }
47
+ get size() {
48
+ return this.entries.size;
49
+ }
50
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nylorun/harness",
3
- "version": "0.21.2-beta",
3
+ "version": "0.22.1-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",
@@ -32,6 +32,10 @@
32
32
  "types": "./dist/run/index.d.ts",
33
33
  "import": "./dist/run/index.js"
34
34
  },
35
+ "./api": {
36
+ "types": "./dist/api/index.d.ts",
37
+ "import": "./dist/api/index.js"
38
+ },
35
39
  "./model/adapters": {
36
40
  "types": "./dist/loop/model/adapters.d.ts",
37
41
  "import": "./dist/loop/model/adapters.js"
@@ -71,13 +75,13 @@
71
75
  "devDependencies": {
72
76
  "@types/node": "^26.5.0",
73
77
  "@typescript/native": "npm:typescript@^7.0.2",
74
- "prettier": "^3.9.8",
78
+ "prettier": "^3.9.9",
75
79
  "typescript": "npm:@typescript/typescript6@^6.0.2",
76
- "vitest": "^5.0.1",
80
+ "vitest": "^5.0.2",
77
81
  "zod": "^4.6.5"
78
82
  },
79
83
  "dependencies": {
80
- "@nylorun/core": "0.11.0-beta"
84
+ "@nylorun/core": "0.13.0-beta"
81
85
  },
82
86
  "peerDependencies": {
83
87
  "zod": "^4.6.5"