@nylorun/harness 0.27.1-beta → 0.29.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.
Files changed (75) hide show
  1. package/CHANGELOG.md +131 -0
  2. package/HOST_CONTRACT.md +15 -13
  3. package/README.md +3 -1
  4. package/dist/api/executors.d.ts +79 -11
  5. package/dist/api/harness.d.ts +83 -2
  6. package/dist/api/harness.js +43 -4
  7. package/dist/api/host.d.ts +30 -2
  8. package/dist/api/host.js +156 -8
  9. package/dist/api/index.d.ts +21 -6
  10. package/dist/api/index.js +19 -4
  11. package/dist/api/run.d.ts +3 -0
  12. package/dist/api/run.js +91 -16
  13. package/dist/flow/context.d.ts +3 -0
  14. package/dist/flow/context.js +2 -1
  15. package/dist/flow/engine.d.ts +2 -0
  16. package/dist/flow/engine.js +10 -7
  17. package/dist/flow/limits.d.ts +8 -5
  18. package/dist/flow/limits.js +11 -7
  19. package/dist/index.d.ts +9 -0
  20. package/dist/index.js +9 -0
  21. package/dist/loop/compaction/config.d.ts +39 -0
  22. package/dist/loop/compaction/config.js +29 -0
  23. package/dist/loop/compaction/index.d.ts +18 -8
  24. package/dist/loop/compaction/index.js +57 -66
  25. package/dist/loop/config.d.ts +20 -0
  26. package/dist/loop/config.js +17 -0
  27. package/dist/loop/delegation.d.ts +3 -0
  28. package/dist/loop/delegation.js +14 -10
  29. package/dist/loop/invocation.d.ts +3 -0
  30. package/dist/loop/invocation.js +2 -0
  31. package/dist/loop/model/files.d.ts +77 -0
  32. package/dist/loop/model/files.js +168 -0
  33. package/dist/loop/model/json-answer.d.ts +26 -0
  34. package/dist/loop/model/json-answer.js +125 -0
  35. package/dist/loop/model/project.d.ts +14 -4
  36. package/dist/loop/model/project.js +70 -41
  37. package/dist/loop/options.js +11 -3
  38. package/dist/loop/run.js +15 -5
  39. package/dist/loop/state.d.ts +6 -1
  40. package/dist/loop/state.js +19 -0
  41. package/dist/loop/step/canonicalize.d.ts +11 -2
  42. package/dist/loop/step/canonicalize.js +21 -5
  43. package/dist/loop/step/resolve.js +1 -0
  44. package/dist/loop/step/run.js +20 -3
  45. package/dist/loop/step/runtime.d.ts +6 -0
  46. package/dist/loop/step/seal.js +8 -2
  47. package/dist/loop/step/step-context.js +1 -1
  48. package/dist/run/durable.d.ts +58 -3
  49. package/dist/run/durable.js +104 -33
  50. package/dist/tools/artifacts.d.ts +33 -0
  51. package/dist/tools/artifacts.js +323 -0
  52. package/dist/tools/engine-tools.d.ts +50 -0
  53. package/dist/tools/engine-tools.js +42 -0
  54. package/dist/tools/mcp.d.ts +92 -0
  55. package/dist/tools/mcp.js +240 -0
  56. package/dist/tools/memory.d.ts +16 -0
  57. package/dist/tools/memory.js +140 -0
  58. package/dist/tools/outputs.d.ts +23 -0
  59. package/dist/tools/outputs.js +193 -0
  60. package/dist/tools/results.d.ts +108 -0
  61. package/dist/tools/results.js +329 -0
  62. package/dist/tools/sandbox.d.ts +35 -0
  63. package/dist/tools/sandbox.js +129 -0
  64. package/dist/tools/skills.d.ts +94 -0
  65. package/dist/tools/skills.js +243 -0
  66. package/dist/tools/text-page.d.ts +20 -0
  67. package/dist/tools/text-page.js +64 -0
  68. package/dist/tools/tool-search.d.ts +56 -0
  69. package/dist/tools/tool-search.js +174 -0
  70. package/dist/tools/trace.d.ts +13 -0
  71. package/dist/tools/trace.js +34 -0
  72. package/dist/tools/wake.d.ts +13 -0
  73. package/dist/tools/wake.js +33 -0
  74. package/dist/types/execution.d.ts +35 -1
  75. package/package.json +7 -7
package/CHANGELOG.md CHANGED
@@ -1,5 +1,136 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.29.0-beta
4
+
5
+ ### Minor Changes
6
+
7
+ - 22c61ce: Protocol 16, Agents from one manifest (track T2), a fresh start. An agent manifest (v8) is one versioned document at `/v1/agent-manifests/{name}` with a `harness` section (what runs inside the loop, including the harness's id) and a `runtime` section (what an environment manifest said). The Runtime checks the two against each other when it is saved (`422 manifest_inconsistent` with `details.gaps`), in place of `requires` at session open. Agent definitions and environment manifests are gone.
8
+
9
+ Environments are Agents: `/v1/agents/{id}` and its sub-routes, made from a saved manifest only (`manifest: "name"` tracks it, `"name@n"` pins a version; either resolves once, into `resolvedVersion`), with a derived `state` (`working`, `sleeping`, `input_required`, `failing`, `paused`) and `attention`. Every session runs on one Agent (`PUT /v1/sessions/{id} { agent, ownerUserId }`) and pins its manifest version. No session is special (D71). Error codes, events (`agent.*`), scopes (`agents:write`, `agent-manifests:write`) and identity-file grants (`agents`) say Agent; model budget scope `agent` is `manifest`. Harness API 5: `turn.start.agent` replaces `turn.start.environment`, with `definition` and `loop`. Migration 0032 closes older sessions (`protocol_16`) and drops Environments with their disks and vaults.
10
+
11
+ The SDK has `client.agentManifests`, `client.agents` and `composeManifest(dir)` for three-file authoring; the CLI has `nylorun apply`, `nylorun agent-manifests`, `nylorun agents` and `nylorun migrate v8`; Studio has an Agents screen, an Agent page and an Agent manifests screen. See MIGRATION.md.
12
+
13
+ - bf942ed: Our engine offers the `memory` tool (track T5, D72). An agent whose version sets `harness.memory` gets one `memory` tool with Anthropic's memory tool schema (`view`, `create`, `str_replace`, `insert`, `delete`, `rename`; `view` only for a `read_only` agent and an agent used as a tool), our memory rules followed by the agent's `instructions`, and its memory index pinned after the instructions as user-role context: kept for the session so the prompt prefix stays cacheable (`ExecutionState.pinned`), and re-pinned after a compaction. Each command's parameters are checked before a call is sent (`checkMemoryCall` in `@nylorun/core/contracts`, which the Runtime also uses), and a call named `memory.<command>` or `memory/<command>` runs as `memory` with that command (`memoryAliasOf`). `ModelRequest.pinned` carries the pinned text; `memoryTool` and `memoryIndexBlock` are exported for your own harness.
14
+ - ffeb3bb: `schedule_wake` (track T4, D77). An agent manifest's `runtime.selfWake: true` offers the agent `schedule_wake`: `{in | at, note}` books its session's next turn, replacing the booking before, and `{cancel: true}` removes it. The Runtime serves the call in its own transaction (a new effect target, `{kind: "runtime", operation: "schedule_wake"}`, additive on Harness API 5; `turn.start.agent.selfWake` tells a harness to offer it), so a replayed turn books once. The booking fires as a trigger run of kind `wake`, its note the turn's message with `cause.kind: "self"`. New session events `wake.booked` and `wake.cancelled`, tool call kind `runtime`, and Runtime limits `wakeMaxAheadMs` and `wakeNoteChars`.
15
+ - 9e60e40: Protocol 17, a queue per session (track T4, D76). A message sent while the session's turn runs or waits is queued (`{status: "queued", queuedMessageId, position}`, `message.queued`) and starts the next turn when this one ends, with every queued message, each its own user message (`queue.taken`); a cancel ends the turn, not the queue. `delivery: "reject"` keeps the refusal, now `409 session_busy`, and a protocol 16 client's messages default to it, so the Host serves protocol 16 and 17. The queue holds at most the Runtime limit `sessionQueuedMessages` (`429 queue_full`), and session reads count `queuedMessages`. Our engine takes `{kind: "messages", messages}` as a turn's input. The SDK's `input` and `inputParts` take `delivery`, and the CLI's `sessions send` takes `--reject-if-busy`. See MIGRATION.md.
16
+
17
+ ### Patch Changes
18
+
19
+ - 3a575d7: Track T3, versions per turn: a turn's first segment takes the manifest version its session's Agent runs then, so a session moves with its Agent between turns and keeps one version through every segment, approval and rollover of a turn. A turn whose message named a variant, and a flow's sessions, keep the version they pinned; a changed loop manifest drops the session's MCP snapshot. The turn span names the version (`nylorun.manifest.version`). Our engine takes a new version's output schema at the next turn.
20
+ - Pin core to the tested release.
21
+ - Updated dependencies [218b078]
22
+ - Updated dependencies [22c61ce]
23
+ - Updated dependencies [1ded443]
24
+ - Updated dependencies [76dcd11]
25
+ - Updated dependencies [bf942ed]
26
+ - Updated dependencies [4fa160d]
27
+ - Updated dependencies [9fed948]
28
+ - Updated dependencies [ffeb3bb]
29
+ - Updated dependencies [9e60e40]
30
+ - Updated dependencies [f85483d]
31
+ - Updated dependencies [ae54de7]
32
+ - @nylorun/core@0.24.0-beta
33
+
34
+ ## 0.28.0-beta
35
+
36
+ ### Minor Changes
37
+
38
+ - 0a2fbc5: **Artifacts reach the harness through the Harness API; `read_artifact` and `save_artifact` run in the harness (protocol 15, Harness API 4).** The first step of the harness boundary: model-facing work belongs to the harness, and the Runtime offers primitives and holds limits and access. A fresh start for agent sessions: the Runtime speaks protocol 15 only. See MIGRATION.md.
39
+
40
+ - **The artifact seam.** A harness reads and writes the artifacts of the run it holds: `artifact.read {artifactId, version?, offset?, length?}` answers the version's metadata (`ArtifactMetaSchema`) and its bytes from `offset`, at most `turn.start.limits.chunkBytes`; `artifact.write` (`begin`, `chunk`, `commit`, `abort`) makes a file artifact of the session or a new version of one of its own, streamed with backpressure into the Object store and committed in Postgres within the Tenant's and the Environment's artifact limits. The scope is always the run's session: its own artifacts, and the Tenant-wide ones its messages named; anything else is the new error code `not_found`, alike. A write's `key` makes it idempotent within the session (`artifact_versions.write_key`, migration 0028), and its `effectId` links the artifact to a tool call of the turn, whose call id `artifact.created` carries. An upload the run leaves open commits nothing. Client helpers: `readArtifact`, `openArtifactWrite`, `writeArtifactBytes`, `toBase64` and `fromBase64` in `@nylorun/core/harness-api`.
41
+ - **Our harness runs the artifact tools.** `read_artifact` (every agent) and `save_artifact` (with a sandbox) are our engine's tools, defined in `@nylorun/harness` (`artifactToolsFor`, `runArtifactTool`) and run over the seam and the run's sandbox files (`HarnessExecutors.files`, `SandboxManager.writeBytes`); their calls are kind `harness`. `save_artifact` keys its write by its effect id. `read_artifact` takes `path` with a sandbox, which copies the whole artifact into it, and hands a file of any other type to the model as a file of the result (the Model Gate writes the note for one the model does not read; `artifact.unsupported` is gone). Its page is harness configuration, `createHarness({ artifactPageBytes })` (32 KiB by default), and now always ends on a whole character. `runDurable` takes `engineTools`; `apiHost` takes the engine's configuration.
42
+ - **The Runtime pins no artifact tools.** `runtimeManifestFor` has no `save` or `read`; `RUNTIME_TOOL_NAMES` no longer holds the two names, so an author tool may take one (our harness then refuses the turn). A session without a sandbox or skills pins its definition unchanged. Core no longer runs either tool (`tenant/artifact-tool.ts` is gone). Migration 0029 closes every agent session that pinned them (`closedReason: "protocol_15"`, `409 session_closed`); workflow sessions carry over.
43
+ - **Media types are core's.** `contentTypeFor`, `essence`, `normalizeContentType`, `isText`, `isModelImage`, `modelInputOf`, `inputLabel`, `extensionFor`, `unreadableReason`, `MODEL_IMAGE_TYPES` and `DEFAULT_CONTENT_TYPE` are exported from `@nylorun/core/contracts`, for the Runtime and harnesses alike.
44
+ - `PROTOCOL_VERSION` 15 with required feature `harness-boundary`; `HARNESS_API_VERSION` 4. The SDKs and the CLI send protocol 15.
45
+
46
+ - ebe7348: **The harness decides how files reach the model; the Model Gate only fetches and translates (protocol 15).** The second step of the harness boundary, still protocol 15 and Harness API 4. See MIGRATION.md.
47
+
48
+ - **Any file may be sent.** A message naming a file the model does not read is accepted: `422 attachment_unsupported` and its error code are gone, and AG-UI and A2A accept such files too. Files are still held to the artifact size limits at upload.
49
+ - **`turn.start.model`** is the model descriptor (`ModelDescriptorSchema`): the provider, id, inputs, context window and output limit of the model the turn's calls use, absent for flows and without a model. One resolution (`model/descriptor.ts`) serves it, the catalog's inputs and the gate.
50
+ - **Our engine shows each file.** An image or document the model reads goes as its artifact reference, a text file is read over the artifact seam and inlined as a `<file>` block, and anything else (past `modelFileBytes`, a kind the model does not read) is a note it writes. `fileView`, `representFiles`, `fileBlock`, `fileNote` and `mediaReferenceLine` (moved from `@nylorun/core/define`) are exported from `@nylorun/harness`. A budget from the descriptor bounds the prompt before the first answer, and compaction counts files as the model gets them.
51
+ - **The Model Gate refuses instead of writing notes.** A text file as a media part, or a kind the model or its API does not read, fails the call with the new model failure code `unsupported_input`; a reference it cannot fetch fails `invalid_request`. Nothing is sent, and neither is retried.
52
+ - **Structured answers are the engine's.** `ModelCall.outputSchema` is removed: our engine writes the JSON instruction and parses the answer (fenced, with control characters repaired; `parseJsonWithRepair` ported from pi-ai). `message.assistant` for a structured answer now carries its JSON text.
53
+ - **`read_artifact`** refuses a file the turn's model does not read (`artifact.unsupported`, with the reason).
54
+ - `unreadableReason` is removed; `isOffice` joins the media type helpers in `@nylorun/core/contracts`.
55
+ - Studio's file picker accepts every file, and the refusal chips are gone.
56
+
57
+ - ff6470e: **The harness writes the model's instructions and defines the sandbox and skill tools; no `runtime` block (protocol 15).** The third step of the harness boundary, still protocol 15 and Harness API 4. See MIGRATION.md.
58
+
59
+ - **No `runtime` block.** The Runtime no longer pins model-facing text or tools on a session's manifest: a session pins its definition as registered (`manifestHash` equals `definitionHash`) and keeps its sandbox spec on the session. The manifest schema refuses `runtime` with what replaces it (`REMOVED_MANIFEST_FIELDS`). `runtimeManifestFor`, `runtimeToolOf`, `RuntimeManifest`, `RUNTIME_TOOL_NAMES`, `isRuntimeToolName`, `createSandboxTools`, `SANDBOX_INSTRUCTIONS`, the skill tool names, `isSkillTool`, `SKILLS_USAGE`, `formatSkillCatalog` and `skillOfToolCall` leave `@nylorun/core/define`; `RUNTIME_PART_ID` is `SESSION_PART_ID` (`"session"`), and `agentFrom` takes `sessionInstructions`. `@nylorun/agents` no longer re-exports the skill catalog helpers. Migration 0030 closes the agent sessions that still pinned a `runtime` block (`closedReason: "protocol_15"`).
60
+ - **`turn.start` states facts.** `environment` (`TurnEnvironmentSchema`: `{id, kind, sandbox?: {workspace}}`) and `routing.sandbox.spec` (the pinned spec) join the agent's `skills`.
61
+ - **Our engine words them.** `@nylorun/harness` writes the skill catalog, the sandbox note and the skills' folder note, and defines the six sandbox tools, `load_skill` and `read_skill_resource`, in the order and bytes the `runtime` block had, so the prompt's prefix is unchanged (`engineToolsFor`, `sandboxTools`, `sandboxInstructions`, `skillCatalogText`, `skillFolderNote`, `skillTools`, all exported for a harness of your own). The skill tools run in the harness over `definition.file` (`runSkillTool`), and core no longer runs them (`tenant/skill-tool.ts` is gone). The sandbox tools' limits are harness configuration (`createHarness({ sandboxTools })`, `harnessExecutors({ sandboxTools })`, `DEFAULT_SANDBOX_TOOL_LIMITS`), as is the most a skill read takes into the context (`createHarness({ skillReadBytes })`, 10 MiB by default), held to the run's `limits.recordEntryBytes`.
62
+ - **Effects name their target.** A tool effect carries `target: {kind: "mcp" | "http" | "sandbox" | "harness" | "platform"}` (`EffectTargetSchema`) and may carry `skill`; the record routes by the kind, never by the tool's name, and a call without a target or one the session lacks is `tool.unavailable`. `hello.features.tools` and `NativeToolSchema` are removed, no tool name is reserved, and the record keeps the skill the intent names when the agent has it. A skill tool's `tool.completed` is `kind: "harness"` (it was `platform`).
63
+ - **Studio** drops the manifest panel's Runtime section: it shows the sandbox tools when the session's Environment has a sandbox.
64
+
65
+ - f443475: **The harness builds the MCP tool list and shapes tool results; tools are identified by server and tool (protocol 15).** The fourth step of the harness boundary, still protocol 15 and Harness API 4. See MIGRATION.md.
66
+
67
+ - **Tools have an identity.** An MCP tool call's target is `{kind: "mcp", server, tool}` (the server's own name for the tool) and an HTTP tool call's `{kind: "http", tool}` (its declared name); `platform` is gone. `toolName` is the model's name, for display. The record checks an MCP call against the session's discovery (`tool.unknown`) and the turn's tool settings (`tool.disabled`), and `tool.completed`, tool-call rows (`tool`), approvals (`Approve server / tool?`, `interaction.tool`) and traces (`nylorun.tool.identity`) carry the identity. The Tool Gate matches a call to its journaled target.
68
+ - **Tool policy keys on identity.** A rule's `tool` is the tool's identity, never the model's name. A rule whose `tool` has `__` in it is refused at `PUT /v1/tenant/tool-policy`; a stored one makes the policy unreadable, so every call is denied (and `GET` answers `409`) until the policy names the tool by `server` and `tool`.
69
+ - **`turn.start.mcp` states facts.** The session pins what its servers listed, raw (`McpSnapshot` v2: servers, scrubbed instructions, tools as named); each turn gets `mcp` (`McpFactsSchema`: every tool with `enabled` and the manifest's `deferred` hint) in place of `sessionTools` and `routing.mcpSnapshot`, and `session.mcp` answers `{mcp}`. `mcp.discovered` has no `renamed` or `deferred`. Migration 0031 closes the sessions that pinned the former snapshot (`closedReason: "protocol_15"`).
70
+ - **Our engine names, defers and searches.** `@nylorun/harness` names MCP tools (`mcpToolName`, `mcpToolNames`, within the 64-character provider ceiling), defers them by the manifest's setting or the model's window and pins that layout in its state (`mcpToolSet`, `McpLayout`), and runs `tool_search` (BM25) itself; core's `tool_search`, `deferredToolsTools`, `TOOL_SEARCH_TOOL` and `TOOL_CALL_TOOL` leave `@nylorun/core/define`, and `runDurable` takes `mcp` instead of `sessionTools`.
71
+ - **Our engine shapes tool results.** Core no longer stores large or binary tool results: the record refuses an outcome past `limits.recordEntryBytes` (`limit_exceeded`). Our engine spills them with `artifact.write`, keyed by the call and its bytes (`spillKey`), with a preview, an image as a file for a model that reads images, and one budget per step (`shapeToolOutcome`, `StepBudget`, exported for a harness of your own). The Tool Gate still scrubs credentials and refuses answers past `limits.toolAnswerBytes`.
72
+ - **Harness configuration.** `createHarness({ mcpTools, toolResults })` sets the deferral share, characters per token, fallback window, the note's instruction length, `tool_search`'s limits, the inline cap, preview head and tail, step budget, stub, small size and entry envelope (`DEFAULT_MCP_TOOL_CONFIG`, `DEFAULT_TOOL_RESULT_CONFIG`).
73
+ - **The MCP preview** names tools as Nylorun's engine would (`modelName`, `renamed`) and shows a server's instructions uncut.
74
+ - **Studio** shows an MCP tool as `server / tool` in tool and approval cards, with the model's name, and links the artifacts a tool's result was stored in.
75
+ - **`examples/harness-minimal`** spills a large `bash` output with `artifact.write` and keeps a preview; its README shows how a harness of your own offers MCP tools.
76
+
77
+ - cf425c6: **The harness mounts skills and saves outputs; the in-process harness uses the gates; compaction is a transcript edit (protocol 15).** The fifth step of the harness boundary, still protocol 15 and Harness API 4. See MIGRATION.md.
78
+
79
+ - **Skill folders are our engine's.** Before each sandbox call our engine mounts each skill version of the turn's tree at `/skills/<name>@<hash>/` with `executors.files.mount`, reading the bytes over `definition.file`; the SandboxManager only writes them (`mountFolder`), once per open sandbox (`present` after). `SandboxManager.mountSkills`, its `definitionFile` port and `SandboxSessionRef.manifest` are gone, and the operator sandbox route mounts nothing.
80
+ - **The outputs folder is our engine's (Q5).** At a completed turn's end in a sandbox our engine saves `/workspace/outputs` as the session's `outputs` folder before `turn.completed`, over the new folder mode of `artifact.write` (`kind: "folder"`, `file`, chunks named by hash, `unchanged`, `refused`). Core takes every byte, checks each file's hash before content is stored under it, dedupes, and keeps the content epoch and quotas. Versions say `source: "engine"`; `artifact.export.skipped` and `artifact.export.failed` are harness claims. Core's export (`artifacts/export.ts`, the `WorkspaceReader`, `workspace.read` listing and bytes calls) is removed.
81
+ - **No limit literals.** The new Runtime limit `folderEntries` (10,000; a count, its ceiling from the manifest's one string) replaces `EXPORT_MAX_FILES`, and `createHarness({ outputs: { dir, maxBytes } })` (`/workspace/outputs`, 1 GiB) replaces `EXPORT_MAX_BYTES`. `RUNTIME_LIMIT_CEILINGS` entries are `{value, unit, why}`.
82
+ - **In-process parity.** Every model call goes through the Model Gate: a scripted model is served by `providerModelGate`, metered like any. The MCP pool opens every server through the Tool Gate (`openRemote` is required; the in-process gate's `openMcp` finds the server in the session's pinned manifest and authorizes it with the vault). `ModelRoute` is `{tenantId, modelGate}`; `TenantContext.modelProvider`, `useVaultModel` and `workspaces` are gone.
83
+ - **Compaction is a transcript edit (Q4).** Summary calls say `purpose: "summary"` (no `message.assistant`), and the segment's edit that replaced the history says `kind: "compaction"` with its facts and summary calls (`CompactionFactsSchema`, `transcriptUpdates(..., compaction)`). Core checks the calls and writes one `context.compacted`, which loses `partial`.
84
+
85
+ - dc75e58: **Host timings, retries and engine settings are configuration with defaults (B15).** Still protocol 15 and Harness API 4. See MIGRATION.md and DEPLOYMENT.md ("Host tuning").
86
+
87
+ - **Host tuning.** The Runtime processes' timeouts, retries, poll intervals and internal sizes are one typed schema with a default each (`HostTuningSchema`, `runtime/server/src/tuning.ts`): keys, the Harness API, the API's streams, the Host, the Object store, the Tenant, its sweep, Durable Session Execution, Restate, Postgres, Durable Streams and the relay, the gates, egress-gate, sandbox pods, harnesses and traces. An operator sets any part in `NYLORUN_TUNING` (JSON), parsed with the stack configuration and read once at start; every default is the value before. An unknown key or a value past its ceiling (Node's longest timer, S3's part sizes, S2's batch, the sandboxes service's wait) stops the process naming the key. Core hands a sandbox pod's engine the `harness` and `engine` groups the operator set. `nylorun start` passes `NYLORUN_TUNING` to the runtime, gateway and harness containers.
88
+ - **Our engine's loop is configuration.** `createHarness` takes `compaction` (`CompactionConfig`, `DEFAULT_COMPACTION_CONFIG`: the kept tail, the reply's reserve, the estimate), `partialOutputChars` (a failed agent-as-tool's output its parent sees), `resendDelaysMs` and `leaseRetryMs`; `runDurable` takes `loop` (`LoopConfig`), which an invocation hands its agents used as tools. `EngineToolConfig` is `EngineConfig`. The Runtime's harness host passes the tuning's `engine` group to `createHarness`.
89
+ - **Kept as constants**, each justified where it is defined: Node's longest timer, S3's part sizes and object key, S2's batch, the sandboxes service's longest wait and pod variable, the `environment.egress` event's 16 running turns, W3C's 512-character `tracestate`, and the 24-hour floor of a wake's dedupe key.
90
+
91
+ - 23774c4: **The last hard-coded limits are configuration (harness boundary B15c).** Still protocol 15 and Harness API 4. Every default is the value before. See MIGRATION.md, and DEPLOYMENT.md's Runtime limits and Host tuning.
92
+
93
+ - **21 more Runtime limits** (`GET`/`PUT /v1/tenant/limits`): a message's parts (`messageParts`), page sizes (`pageItems`, `exportPageItems`, `environmentEventItems`; a page asked larger holds that many), labels (`artifactLabels`, `labelKeyChars`, `labelValueChars`), a manifest's setup command, descriptions and secret hosts (`setupCommandChars`, `manifestDescriptionChars`, `secretDescriptionChars`, `secretHosts`), a failed pod's reason (`setupReasonChars`, `setupCommandExcerptChars`), secret values (`secretValueChars`), the tool policy and budgets (`toolRules`, `toolRuleFieldChars`, `toolRuleTextChars`, `modelBudgets`) and flows (`flowConcurrency`, `flowMapItems`, `flowLoopIterations`, replacing the `NYLORUN_FLOW_*` variables no Host read). Request schemas lose these maxima; the Runtime checks the Tenant's.
94
+ - **More Host tuning** (`NYLORUN_TUNING`): token lifetimes and clock tolerance (`keys.*`), the advance deadline and grace (`execution.*`), `nylorun-operate`'s waits, the credential store's lock, sweep arming, Postgres batches and the replication pool, a basin repair's log cadence, egress sockets, the engine poll and sandbox memory floor, MCP listing pages and diagnostics, sandbox helper commands, the scrub threshold, exec event and local stream sizes; and in the engine, `flowValueChars` and `toolResults.minPreviewBytes`.
95
+ - **The CLI's own waits are `NYLORUN_CLI_TUNING`**: `nylorun start`'s waits and polls, the Compose healthchecks and WAL cap, and `nylorun local sandbox`'s waits.
96
+ - **Studio follows the Runtime's limits**: no upload cap of its own, the Tenant's `requestBodyBytes` read for a write it parses past the default (`@nylorun/agents` exports `RUNTIME_LIMIT_DEFAULTS`), no CPU cap in its form.
97
+ - **Kept, each justified where it is defined**: Linux's `MAX_ARG_STRLEN` (a setup command's ceiling) and `PATH_MAX` (a link target), a model-facing tool name's 64 characters, RFC 6838's media type length, Postgres's 65,535 bind parameters, a tmpfs page, and identifier grammars (the protocol's).
98
+
99
+ - b1e815d: **Runtime limits are a Tenant setting, and harnesses get them in `turn.start.limits`.**
100
+
101
+ - What one record entry, model call, model file, tool answer, custom harness state and Harness API chunk may hold is the new Management API setting `GET`/`PUT /v1/tenant/limits` (`{ limits: { recordEntryBytes, modelCallBytes, modelFileBytes, toolAnswerBytes, harnessStateBytes, chunkBytes } }`), also `admin.settings.limits` and `nylorun tenant settings limits [get | put <file|->]`.
102
+ - The defaults are today's sizes (`RUNTIME_LIMIT_DEFAULTS`): 960 KiB, 32 MiB, 8 MiB, 8 MiB, 256 KiB and 16 MiB. A limit left out of a `PUT` takes its default.
103
+ - Each limit has a ceiling a dependency sets (`RUNTIME_LIMIT_CEILINGS`): S2's 1 MiB record less 64 KiB for the event's envelope, the 64 MiB Harness API frame, the longest JavaScript string. A limit above its ceiling is `400`, naming the ceiling.
104
+ - Each is read from the Tenant's database where it is checked; nothing keeps it.
105
+ - **The record holds every write to `recordEntryBytes`.** An event whose payload, or an effect outcome whose value, is larger, whoever wrote it, is refused with `limit_exceeded`: `413` (`details.limit: "recordEntryBytes"`) to an API client, the new Harness API error code `limit_exceeded` to a harness. A harness's claimed event past it is refused rather than dropped. Before, such an event reached a record S2 could not take.
106
+ - **The gates read the setting.** The Model Gate refuses a body past `modelCallBytes` and a file past `modelFileBytes`; the Tool Gate keeps no MCP or HTTP answer past `toolAnswerBytes` (`mcp.too-large`, `http.too-large`) and reads no tool body past it. A custom harness's state past `harnessStateBytes` fails its turn with `limit_exceeded` (it was `invalid`), and a `definition.file` range longer than `chunkBytes` is `limit_exceeded`. Core's step budget for tool results is unchanged (256 KiB), or half `recordEntryBytes` when that is less.
107
+ - **`turn.start` carries `limits`** (`RuntimeLimitsSchema`), the limits in force when the segment started. Harness API 3 and protocol 14 are unchanged, but `TurnStartSchema` is strict: a harness built against an older `@nylorun/core` refuses a `turn.start` with `limits`, so upgrade a custom harness with the Runtime. Our harness asks for skill files `limits.chunkBytes` at a time, and holds MCP answers on its own connections to `limits.toolAnswerBytes`. `createHarness` takes `onStart(grant, start)`.
108
+ - **Removed exports:** `MAX_MODEL_CALL_BYTES`, `MAX_TOOL_BODY_BYTES`, `MAX_HARNESS_STATE_BYTES` and `DEFINITION_FILE_CHUNK_BYTES` from `@nylorun/core`. Added: `RuntimeLimitsSchema`, `RUNTIME_LIMIT_DEFAULTS`, `RUNTIME_LIMIT_CEILINGS`, `runtimeLimitsOf`, `runtimeLimitIssues`, `limitExceededMessage`, `S2_RECORD_MAX_BYTES`, `RECORD_ENVELOPE_RESERVE_BYTES`, `JS_STRING_MAX_LENGTH` and the `TenantLimits*` schemas.
109
+
110
+ - 6772612: **The remaining request, upload, token and sandbox limits are Tenant settings (harness boundary B15).** Still protocol 15 and Harness API 4. See MIGRATION.md and DEPLOYMENT.md's Runtime limits.
111
+
112
+ - **27 more Runtime limits** in `GET`/`PUT /v1/tenant/limits`, each with today's value as its default and a ceiling from a dependency (a JavaScript string or timer, a request read as one string, a Harness API frame, a JavaScript number): request bodies and inline files (`requestBodyBytes`, `inlineFileBytes`), `a2aWaitMs`, `errorExcerptChars`, `traceContentBytes`, an Environment's labels, setup and input files (`environmentLabels`, `environmentSetupCommands`, `environmentFiles`, `environmentFilesPerEntry`, `environmentSecretSlots`, `setupCommandMs`, `setupOutputChars`), disk versions (`diskVersionEntries`, `diskVersionBytes`, `diskLeaseMs`, `diskPodWaitMs`; an Environment's manifest may lower the first two with `limits.disk`), model calls (`modelRequestMs`, `modelIdleMs`, `modelAttempts`, `modelRetryDelayMs`, `modelProviderRetries`, `modelRetryDelayMaxMs`, read by the gates for each call) and tools (`toolAttempts`, `httpToolTimeoutMs`, `mcpPreviewMs`, `mcpMetadataBytes`, and the new `mcpSnapshotBytes`: what a session pins of its MCP servers' tools and instructions, past which a server is left out with a diagnostic).
113
+ - **Schema maxima are checked against the Tenant's limits**: an Environment's labels, setup commands, input files, files per entry, secret slots and setup timeout, and an HTTP tool's `timeoutMs` (at deploy and at each call). `limits.environments` and `lifecycle.stopGrace` lose their arbitrary caps; an identity file's issuer takes any number of grants and `jwksFetch` settings.
114
+ - **`turn.start.limits` carries only a harness's limits** (`HarnessLimitsSchema`, `harnessLimitsOf`), and a harness drops one it does not know. `transcriptUpdates` takes `recordEntryBytes` and fills each event up to it; `CHUNK_BYTES` is gone.
115
+ - **Constants a dependency or a standard fixes stay, named for it**: a token is read up to Node's `http.maxHeaderSize`; artifact names and folder paths keep `FILE_NAME_MAX` (255) and `FILE_PATH_MAX` (1,024); a skill file's path is what `FILE_PATH_MAX` leaves under its mount folder; `tracestate` keeps W3C's 512.
116
+ - **Removed**: `ENVIRONMENT_LABELS_MAX`, `ENVIRONMENT_SETUP_MAX`, `ENVIRONMENT_SETUP_TIMEOUT_MAX_MS` (now `ENVIRONMENT_SETUP_TIMEOUT_DEFAULT`), `ENVIRONMENT_FILES_MAX`, `ENVIRONMENT_SECRET_SLOTS_MAX`, `TOKEN_ENVIRONMENT_GRANTS_MAX`, `HTTP_TOOL_MAX_TIMEOUT_MS`, `READ_ARTIFACT_MAX_BYTES` and `CHUNK_BYTES` from `@nylorun/core`; the image checks (`decodeImageBase64`, `validateImageBytes`, `IMAGE_MEDIA_TYPES`, `MAX_IMAGE_BYTES`), the Tenant configuration's `modelCall` and `TrustedIssuersOptions`' `refetchMs`/`maxAgeMs` from `@nylorun/runtime`. Studio's Environment form no longer caps setup commands and input files at 16: the Runtime checks the Tenant's limit.
117
+
118
+ ### Patch Changes
119
+
120
+ - 8715ad8: The fixture model reads its `fixture:*` script in a turn that carries a file. Our harness ends such a turn with a user message listing the files (`FILES_MESSAGE_HEADER`, now exported by `@nylorun/harness`), and the fixture model read that message instead: it answered "I remember: …" and called no tool. It now skips that message, for the script and for the tool result it answers after.
121
+ - Pin core to the tested release.
122
+ - Updated dependencies [0a2fbc5]
123
+ - Updated dependencies [ebe7348]
124
+ - Updated dependencies [ff6470e]
125
+ - Updated dependencies [f443475]
126
+ - Updated dependencies [cf425c6]
127
+ - Updated dependencies [23774c4]
128
+ - Updated dependencies [b1e815d]
129
+ - Updated dependencies [2459430]
130
+ - Updated dependencies [f2e9b0a]
131
+ - Updated dependencies [6772612]
132
+ - @nylorun/core@0.23.0-beta
133
+
3
134
  ## 0.27.1-beta
4
135
 
5
136
  ### 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); `PUT /v1/sessions/:sessionId` (`PutSessionRequest`: requestId, agentId, trusted ownerUserId, optional info, optional `environment` — the id of an Environment (protocol 11): its sandbox (kinds `virtual` and `pod`) and its vault are the session's, with the recipe it applies pinned at open; omitted means no sandbox and no credentials; 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). Environments (`PUT/GET/DELETE /v1/environments/:environmentId`, `/stop`, `/reset`, `/events`, disk versions) and their secrets (`PUT/GET/DELETE /v1/environments/:environmentId/secrets/:name` and `GET .../secrets`: names, types and bindings, never a value) are Runtime API routes. Bearer management keys (the Management API, protocol 8; an application key there is `403 key_role_mismatch`): the `/v1/tenant/*` model routes below, the tool policy (`/v1/tenant/tool-policy`) and the Tenant's settings. 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. An Environment whose owner guard (`ownerUserId`) names another owner cannot be named by the session (the opaque `404`). `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, each model with the inputs it reads (`inputs`) and those the operator may add (`addableInputs`); `PUT /v1/tenant/models/inputs` sets the added ones (protocol 12), and `GET /v1/tenant/providers` gives each provider's `inputs`. agentId, ownerUserId, info and environment stay the creation identity. GET session returns id, agentId, ownerUserId, status, activeTurnId, `environment: { id, version } | null`, the pinned `harness`, `closedReason` on a closed session, 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. History returns `{items: LiveEvent[], cursor: string|null}`; empty history cursor is null.
7
+ Bearer application credentials: `PUT /v1/agents/:agentId` (`PutAgentRequest`: requestId, complete manifest, implementationVersion); `PUT /v1/sessions/:sessionId` (`PutSessionRequest`: requestId, agentId, trusted ownerUserId, optional info, optional `environment` — the id of an Environment (protocol 11): its sandbox (kinds `virtual` and `pod`) and its vault are the session's, with the recipe it applies pinned at open; omitted means no sandbox and no credentials; 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). Environments (`PUT/GET/DELETE /v1/environments/:environmentId`, `/stop`, `/reset`, `/events`, disk versions) and their secrets (`PUT/GET/DELETE /v1/environments/:environmentId/secrets/:name` and `GET .../secrets`: names, types and bindings, never a value) are Runtime API routes. Bearer management keys (the Management API, protocol 8; an application key there is `403 key_role_mismatch`): the `/v1/tenant/*` model routes below, the tool policy (`/v1/tenant/tool-policy`) and the Tenant's settings. 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. An Environment whose owner guard (`ownerUserId`) names another owner cannot be named by the session (the opaque `404`). `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, each model with the inputs it reads (`inputs`) and those the operator may add (`addableInputs`); `PUT /v1/tenant/models/inputs` sets the added ones (protocol 12), and `GET /v1/tenant/providers` gives each provider's `inputs`. agentId, ownerUserId, info and environment stay the creation identity. GET session returns id, agentId, ownerUserId, status, activeTurnId, `environment: { id, version } | null`, the pinned `harness`, `closedReason` on a closed session, 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 (v2, protocol 15: what the servers listed, by their own tool names, disabled tools included) and contains no secrets. History returns `{items: LiveEvent[], cursor: string|null}`; empty history cursor is null.
8
8
 
9
9
  **Manifest-only agents (protocol 8, track R2).** The Runtime runs the whole agent from its manifest and its definition files, and never calls the developer's code during a session: Action endpoints, delivery tokens, background tools and held runs are gone (`/v1/endpoints` and `/v1/actions/*` answer `404`). An agent's tools are HTTP tools (`http`), remote MCP servers, agents used as tools and the Runtime's built-ins. `PUT /v1/agents/:agentId` refuses (`400`) a definition with a tool that has no `http` and no `agent`, and a flow agent with a `tool` stage (`codeToolRefusal` in `/define`); a tool effect the Runtime cannot run fails with `tool.unavailable`. `tool({ run })` runs only in the local engine (`/run`).
10
10
 
@@ -15,9 +15,11 @@ unsupported protocol → `426` with
15
15
  `{ status: "rejected", code: "protocol_unsupported", protocol }` before
16
16
  authentication, except that a request with neither `Nylorun-Protocol` nor
17
17
  `Authorization` gets the route's `401` challenge (protocol 9). The Host serves
18
- protocol 13 only (protocol 13 changed the agent manifest to v7, the flat manifest, so a protocol 11 or 12
19
- client is answered `426`; protocol 12 added model inputs and refuses a message naming a
20
- file the Tenant's model does not read with `422 attachment_unsupported`). A `Nylorun-Tenant` header naming the Host's Tenant is
18
+ protocol 15 only (protocol 15 moved `read_artifact` and `save_artifact` to the harness, a fresh start for
19
+ agent sessions, and the choice of how each file reaches the model: a message may name any file,
20
+ `turn.start.model` describes the model, and the Model Gate only fetches and translates; protocol
21
+ 13 changed the agent manifest to v7, the flat manifest, so an older client is answered `426`;
22
+ protocol 12 added model inputs). A `Nylorun-Tenant` header naming the Host's Tenant is
21
23
  accepted, one naming another Tenant (or a malformed one) is the opaque `404`. A Tenant id in the query string or body is ignored. A
22
24
  Tenant that could not be opened and an unknown Tenant share the opaque `404`
23
25
  body. A missing or rejected credential is `401` (`credential_required`,
@@ -35,11 +37,11 @@ Tenant is open; a Tenant that cannot be opened fails it with its cause
35
37
  (`schema-too-new`, `kek-missing`, `database-layout-old`, …), also reported in
36
38
  `nylorun-operate status` inside the runtime container (`nylorun status` on a local Tenant).
37
39
 
38
- 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). Tool calls are delivered at least once (R5): an MCP or HTTP call a crash, a shutdown or a lost gate hop interrupted is sent again with the same key, its effect id (`Idempotency-Key`, or `_meta["nylorun/idempotency-key"]` for MCP), up to 3 sends; then, and for a sandbox or core-served call at once, it fails to the model as `tool.interrupted` and is not run again. No tool call leaves its session `uncertain`. Results after cancellation cannot resume a turn. No hardcoded production credentials.
40
+ 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). Tool calls are delivered at least once (R5): an MCP or HTTP call a crash, a shutdown or a lost gate hop interrupted is sent again with the same key, its effect id (`Idempotency-Key`, or `_meta["nylorun/idempotency-key"]` for MCP), up to 3 sends; then, and for a sandbox or harness call at once, it fails to the model as `tool.interrupted` and is not run again. No tool call leaves its session `uncertain`. Results after cancellation cannot resume a turn. No hardcoded production credentials.
39
41
 
40
42
  ## Engine host
41
43
 
42
- `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 toolName (a tool is known by its name alone: the agent's `tools`, the pinned `runtime.tools` and the session tools never share one), serialized input and context. Tool result value is a ToolOutcome or a plain tool output; statePatch contains changed session keys. Tool context includes invocationId, resume, state, info and stable idempotencyKey. Customer implementationVersion is pinned by the runtime outside durable checkpoints.
44
+ `createDurableCheckpoint({manifest,sessionId,turnId,input,state?,info?,segment?})`, `runDurable({manifest,checkpoint,host,signal?,mcp?,engineTools?})` from `/run` (`engineTools(agent)`: what our engine adds to each agent of the tree, `{tools, instructions}` from `engineToolsFor(agent, turn.start.environment, options)`: the sandbox, skill and artifact tools and their text, offered after the agent's own tools and before the MCP tools, not hashed; `mcp`: the session's MCP tools as our engine offers them, `mcpToolSet(turn.start.mcp, manifest, {config, model?, layout?, taken?})`, in place of `sessionTools` (protocol 15): named for the model, deferred tools behind `tool_search` and `tool_call`, each call targeting the tool's identity, with the layout the segment's state keeps as `mcpLayout`, not hashed). `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 a call that summarizes history says `purpose: "summary"` (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; `runDurable` answers the root agent's summary calls of the segment (`summaryEffectIds`), and the API host marks the segment's transcript edit `kind: "compaction"` with them and the entry's facts (Q4, protocol 15). Hosts record no `message.assistant` for a summary call, and publish one `context.compacted` per compaction edit. 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 toolName (the name the model called, for display), `target` (what runs the call, by identity, protocol 15: `{kind: "mcp", server, tool}` with the server's own tool name, `{kind: "http", tool}` with the declared name, `{kind: "sandbox"}` or `{kind: "harness"}`; the host routes by it, never by name, and it is in the request hash; an author's code tool has none, and the host fails it), optional `skill`, serialized input and context. The agent's `tools`, our engine's and the MCP tools never share a name: a clash fails the turn (`agent.build-failed`); an MCP tool whose name is taken is left out. Tool result value is a ToolOutcome or a plain tool output, shaped by the API host before it is recorded (`shapeToolOutcome`, `StepBudget`: one record entry at most, the rest stored as artifacts keyed by `spillKey`); statePatch contains changed session keys. Tool context includes invocationId, resume, state, info and stable idempotencyKey. Customer implementationVersion is pinned by the runtime outside durable checkpoints.
43
45
 
44
46
  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. Tool calls are the exception: they are re-sent with their key, as above.
45
47
 
@@ -47,23 +49,23 @@ A terminal/paused result includes `result.state`. Save it. A new message uses a
47
49
 
48
50
  Host resolveEffect must bind the effect ID to the original request and reject drift. Intent/outcome, checkpoint settlement and canonical event/outbox writes must use runtime transactions. The Runtime journals individual effect boundaries, not the loop, in the Session Store under the advance's lease; Durable Session Execution (Restate) only runs one advance per session at a time and delivers wakes and timers, and journals no effects. Scheduling, storage, publication, delivery policy and reconciliation remain runtime-owned.
49
51
 
50
- 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 pins the same `runtime` block's sandbox on the root and each inlined child) is run by the engine inside the parent's `runDurable`. Its model and tool 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, and include `agent` in `tool.completed` 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`. 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 v3) 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)`), 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.
52
+ 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; the tree shares the session's one sandbox, whose spec the session keeps) is run by the engine inside the parent's `runDurable`. Its model and tool 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 and MCP routing, and include `agent` in `tool.completed` payloads; our engine gives each child its own skill tools and the session's sandbox tools. 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`. 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 v3) 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)`), 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.
51
53
 
52
54
  **Workflows (flow engine).** Definitions with `kind: "workflow"` (workflow manifest v3) run through `createFlowCheckpoint` / `runFlowDurable` from `/run` (same `DurableResult` shape as `runDurable`) on engine `flow-3`; checkpoints pin it, and v1/v2 manifests are refused. The turn loop in `runtime/harness/src/loop/` is unchanged. A flow runs no developer code: its effects are `agent` (a leaf agent's turn) and `tool` (a workflow tool node). Each carries `path` (the leaf path: the leaf's id, `[i]` per Map item, nested flow agent ids in front), `key` (the path without Map indices) and `iterations` (enclosing Loop vector as a dotted string, or `"-"` outside Loops). Effect ids are `${turnId}:${segment}:flow:${path}:${kind}:${iterations}`. The first stage gets the flow's input and each later stage the previous output; a Switch reads it (a string, or its `route` field), a Map runs over it (an array, or its `items`), and a Loop asks a verifier (an agent, or an HTTP verifier) for a verdict (`{ pass, feedback? }`) and retries the body with the feedback, up to `max`. `agent` effect input is `{ agentId, input, path, flow?, flowInput? }`: `flow` names the nested flow agents, outermost first; `flowInput` is the flow agent's input, sent when the stage's input differs, and the host puts it in the linked message as the original request before the stage's input. Effect `context` carries `loopPath` and `n` for a Loop's turns, and `role: "verify-agent"` for its verifier, which gets a fresh session per attempt and whose verdict the host records as `loop.verified`. The host resolves the leaf from the workflow manifest's embedded `agents` (`embeddedAgent`) and gives the linked session the leaf's manifest and its hash, only through the public session contract (create linked session, message with derived idempotency key, settle on linked `turn.completed` / failed / cancelled). A `tool` effect carries `path` + `key` instead of `toolName`. A code tool node (no `http`) runs only in the local engine: the Runtime refuses a flow with one at save and fails such an effect with `tool.unavailable`. The `tool` effects of an HTTP stage (a tool node with `http`, input checked against its schema first) and of an HTTP verifier (`loop.verify: { http }`, input `{ input, output, iteration }`, `context.role: "verify-http"`, at the verify position's key) are requests the host makes through its Tool Gate as for an agent's HTTP tool, the effect id as `Idempotency-Key`, the HTTP outcome (`{ kind: "completed", output }` or `{ kind: "failed", code, message }`) as the value, and an HTTP verifier's verdict recorded as `loop.verified`; a Loop body that starts with an HTTP stage is retried with the Loop's input. A lost HTTP stage is sent again with the same key, as an agent's HTTP tool call is (R5). Parallelism comes from pending effects returned together; the Runtime caps concurrency with `RuntimeOptions.flow` / env (`maxConcurrency`, `maxMapItems`, `maxLoopIterations`).
53
55
 
54
- **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, `outputSchema` and skills fixed, plugin labels included; tools and delegates may only be removed; MCP servers may only be tightened; it never sets `runtime`, and the turn runs with the pin's), 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.
56
+ **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, `outputSchema` and skills fixed, plugin labels included; tools and delegates may only be removed; MCP servers may only be tightened; it has no `runtime` field), 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.
55
57
 
56
- **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 the `runtime` block (`runtimeManifestFor` in `/define`: the resolved spec, the six built-ins and the sandbox instructions, `save_artifact` and `read_artifact`, and `load_skill` and `read_skill_resource` with the skill catalog when the agent has skills), so its hash differs from the definition's; a definition or a turn variant that sets `runtime` is refused; 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. `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.
58
+ **Shared sandbox.** Definitions declare no sandbox; a session is opened with one (its Environment's), resolved against the Tenant's limits and pinned on the session (`Session.sandbox`). Since protocol 15 a session's manifest is its definition as registered, so its hash is the definition's: `turn.start` carries the spec as `routing.sandbox.spec` and the facts as `environment` (`{id, kind, sandbox?: {workspace}}`), and the harness writes the sandbox's instructions and defines the six sandbox tools, and `load_skill` and `read_skill_resource` with the skill catalog when the agent has skills (`engineToolsFor` in `@nylorun/harness`); a definition or a turn variant that sets `runtime` is refused; a workflow session's sandbox is stored beside its manifest the same way. 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. `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.
57
59
 
58
- ## Harness API 3
60
+ ## Harness API 5
59
61
 
60
- 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. Three version numbers apply: the transport (path `/nylorun/harness/v1`, header `Nylorun-Harness-Api: 1`), the messages (`HARNESS_API_VERSION = 3`; core refuses a `hello` naming another `api`; 3 renamed `hello.capabilities` to `features` and dropped `capabilityId` from effect intents, MCP server refs, HTTP call bodies and MCP records) and the Runtime protocol, which only the Runtime and Management APIs carry. The whole contract is `@nylorun/core/harness-api` (R4.5): frames and messages, the transport and the pod join (`HostJoinRequestSchema`, `HostJoinAnswerSchema`), the Model and Tool Gate bodies (`ModelCallBodySchema`, `ToolCallBodySchema`, `HttpCallBodySchema`, MCP bodies, `GATE_ERROR_CODES`), the MCP snapshot (`McpSnapshotSchema`), transcript entries (`TranscriptEntrySchema`) and the effect id rule (`effectIdOf`: `<turnId>:<segment>:<kind>:<identity>`; a run gets back only its segment's outcomes), the request hash, transcript edits and the RPC channel; the Runtime validates with the same schemas, and the build writes them as one JSON Schema document (`@nylorun/core/harness-api/schema.json`). `TurnStart.trace` (optional W3C `traceparent`) is the turn's trace context when the Runtime traces. With the Tenant's fixture model on (`TurnStart.options.fixtureModel`, informational), the Model Gate answers model calls itself, metered like any model (provider `fixture`, cost 0), so a harness calls the gate as usual. Harness ids (R4.1): `hello.name` is the harness's id (ours says `nylorun`; `@nylorun/harness` is refused); a session pins its Environment's harness, else `nylorun`, and only a connection of that id takes its runs; a credential binds its id (the harness token is ours, a custom harness has its own from `nylorun-operate harness token put <id>`, a pod's host is its Environment's harness). A harness's state is its own (R4.2): core stores it unread; a custom harness's is at most 256 KiB, it cannot pause for approvals, and the tools it declares in `hello` (`features.tools`, known by name; a name the agent or the Runtime already uses fails the turn at its start) are journaled like built-ins. Events carry who wrote them (R4.9): `harness` with its id, `runId` and evidence `claimed` for what a harness reported. v2 removed held runs, `TurnStart.options.holdMs` and `effect.resolved`, with track R2; the harness client is `@nylorun/harness/api` (`createHarness({channel, executors, features?})`). 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.*`). Durable checkpoint 1 is unchanged.
62
+ 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. Three version numbers apply: the transport (path `/nylorun/harness/v1`, header `Nylorun-Harness-Api: 1`), the messages (`HARNESS_API_VERSION = 5`; core refuses a `hello` naming another `api`; 5 (protocol 16) replaced `turn.start.environment` with `turn.start.agent` (`{id, kind, sandbox?}`, the Agent the session runs on) and added `turn.start.definition` (`{name, version}`, the agent manifest version the session pinned) and `turn.start.loop` (the harness section's `loop`); 4 added the artifact seam, `artifact.read` and `artifact.write`, over which a harness reads and writes its run's session's artifacts, the error code `not_found`, `turn.start.model`, `turn.start.environment` and `turn.start.mcp` (the session's MCP discovery as raw facts), and each tool effect's `target` (an MCP or HTTP tool's identity), the folder mode of `artifact.write` (`kind: "folder"`, `file`, `refused`), `purpose: "summary"` on model intents, compaction edits (`kind: "compaction"` with `CompactionFactsSchema`) and the claims `artifact.export.skipped` and `artifact.export.failed`, and removed `hello.features.tools`, `turn.start.sessionTools`, `routing.mcpSnapshot`, the `platform` target and the `workspace.read` listing and bytes calls (core exports no outputs); 3 renamed `hello.capabilities` to `features` and dropped `capabilityId` from effect intents, MCP server refs, HTTP call bodies and MCP records) and the Runtime protocol, which only the Runtime and Management APIs carry. The whole contract is `@nylorun/core/harness-api` (R4.5): frames and messages, the transport and the pod join (`HostJoinRequestSchema`, `HostJoinAnswerSchema`), the Model and Tool Gate bodies (`ModelCallBodySchema`, `ToolCallBodySchema`, `HttpCallBodySchema`, MCP bodies, `GATE_ERROR_CODES`), the MCP snapshot (`McpSnapshotSchema`), transcript entries (`TranscriptEntrySchema`) and the effect id rule (`effectIdOf`: `<turnId>:<segment>:<kind>:<identity>`; a run gets back only its segment's outcomes), the request hash, transcript edits and the RPC channel; the Runtime validates with the same schemas, and the build writes them as one JSON Schema document (`@nylorun/core/harness-api/schema.json`). `TurnStart.trace` (optional W3C `traceparent`) is the turn's trace context when the Runtime traces. With the Tenant's fixture model on (`TurnStart.options.fixtureModel`, informational), the Model Gate answers model calls itself, metered like any model (provider `fixture`, cost 0), so a harness calls the gate as usual. Harness ids (R4.1): `hello.name` is the harness's id (ours says `nylorun`; `@nylorun/harness` is refused); a session pins its Environment's harness, else `nylorun`, and only a connection of that id takes its runs; a credential binds its id (the harness token is ours, a custom harness has its own from `nylorun-operate harness token put <id>`, a pod's host is its Environment's harness). A harness's state is its own (R4.2): core stores it unread; a custom harness's is at most 256 KiB, it cannot pause for approvals, and a tool it runs itself is a `harness` effect, journaled like ours. Events carry who wrote them (R4.9): `harness` with its id, `runId` and evidence `claimed` for what a harness reported. v2 removed held runs, `TurnStart.options.holdMs` and `effect.resolved`, with track R2; the harness client is `@nylorun/harness/api` (`createHarness({channel, executors, features?, mcpTools?, toolResults?, outputs?})`: `mcpTools` how our engine defers MCP tools and `tool_search`'s limits, `toolResults` how it shapes tool results, `outputs` its outputs folder's directory and byte bound, each partial over its defaults). Its executors' `files` (`read`, `write`, `list`, `mount`) are the sandbox files our engine decides about: before each `sandbox` call it mounts each skill version of the turn's tree at `/skills/<name>@<hash>/` (the host only writes, `present` when the sandbox holds it), and at a completed turn's end in a sandbox it saves `/workspace/outputs` as the session's `outputs` folder over the artifact seam before `turn.completed`. Placement changes none of it (protocol 15): the in-process harness calls models through the Model Gate (a scripted model's gate in tests), opens MCP servers through the Tool Gate, and reads skill bytes over `definition.file`. 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.*`). Durable checkpoint 1 is unchanged.
61
63
 
62
64
  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`, …).
63
65
 
64
66
  - **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`).
65
- - **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`.
66
- - **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 runs model, MCP, HTTP and sandbox calls through the executors it is given (a model call reaches its provider through the Runtime's Model Gate, never from the harness) and reports `effect.outcome{value}` or `{error}` (uncertain for a model call; a tool call's error fails it to the model as `tool.interrupted`); after a `shutdown` a recoverable call reports nothing and stays `invoking`. An intent for a tool row still `invoking` is a re-send (R5): core counts it and answers `execute` for an MCP or HTTP call under 3 sends, else the call's `tool.interrupted` outcome. A harness whose gate hop lost a call's answer asks again with the same intent. The Tool Gate runs a run's tool call only when its `Idempotency-Key` names an `invoking` row of the run's turn for the same tool and input (`400 key_required`, `409 effect_not_journaled`). Core applies the Tenant's tool policy to an MCP or HTTP tool intent (R5 step 2): one it refuses is answered `completed` with a `tool.denied` failure, and one it holds for a person is answered `pending` (the segment ends waiting; the turn pauses with an `approval` interaction whose id is the effect id, and the call is `execute`d once approved). Core runs flow work, linked sessions, delegation journaling and its built-in tools, and fails a tool that would run the developer's code (`tool.unavailable`). Rows written before carry their full request and are hashed on read.
67
+ - **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, `mcp` (the session's MCP facts once discovered: each server's tools, raw, with `enabled` and a `deferred` hint; `session.mcp` records a snapshot and answers them), the segment's completed `outcomes` (`{effectId, requestHash, outcome}`), `transcript.cursor`, `options` (`yieldAfter`, `flowLimits`, `fixtureModel`) and `routing` (root manifest, plugin roots, sandbox owner). Core aborts a run with `cancel{runId, reason, message}`, `reason` one of `cancel`, `shutdown`, `deadline`, `ownership.lost`.
68
+ - **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 runs model, MCP, HTTP and sandbox calls through the executors it is given (a model call reaches its provider through the Runtime's Model Gate, never from the harness) and reports `effect.outcome{value}` or `{error}` (uncertain for a model call; a tool call's error fails it to the model as `tool.interrupted`; a value past `limits.recordEntryBytes` is `limit_exceeded`, since the harness shapes tool results, not core); after a `shutdown` a recoverable call reports nothing and stays `invoking`. An intent for a tool row still `invoking` is a re-send (R5): core counts it and answers `execute` for an MCP or HTTP call under 3 sends, else the call's `tool.interrupted` outcome. A harness whose gate hop lost a call's answer asks again with the same intent. The Tool Gate runs a run's tool call only when its `Idempotency-Key` names an `invoking` row of the run's turn for the same tool and input, an MCP call's row targeting the same agent, server and raw tool name (`400 key_required`, `409 effect_not_journaled`). Core applies the Tenant's tool policy to an MCP or HTTP tool intent (R5 step 2), by the target's identity, never the model's name: one it refuses is answered `completed` with a `tool.denied` failure, and one it holds for a person is answered `pending` (the segment ends waiting; the turn pauses with an `approval` interaction whose id is the effect id, and the call is `execute`d once approved). Core runs flow work, linked sessions and delegation journaling, no tool of its own, and fails a tool that would run the developer's code (`tool.unavailable`), an MCP tool the session did not discover (`tool.unknown`) and one the turn disables (`tool.disabled`). Rows written before carry their full request and are hashed on read.
67
69
  - **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.
68
70
  - **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.
69
71
 
package/README.md CHANGED
@@ -44,7 +44,9 @@ JSON.stringify(supportAgent); // manifest v7: { manifestSchemaVersion: 7, id, na
44
44
  Agent.from(supportAgent.toJSON(), { tools: { lookup_order: lookup } });
45
45
  ```
46
46
 
47
- The manifest is flat: the agent's `instructions`, `tools`, `skills` and `mcpServers` are top-level, and a skill or server from an Agent Plugin carries its `plugin` label. A tool is known by its name alone, so an agent's tool may not take a name the Runtime serves (the sandbox, artifact and skill tools, `tool_search`, `tool_call`) or contain `__`. When a session pins the agent, the Runtime adds its `runtime` block (`runtimeManifestFor`): the sandbox and its tools, the artifact tools and the skill tools with the skill catalog.
47
+ The manifest is flat: the agent's `instructions`, `tools`, `skills` and `mcpServers` are top-level, and a skill or server from an Agent Plugin carries its `plugin` label. A tool's name may not contain `__` (an MCP server's tools). A session pins the manifest as registered; when our harness runs a turn it adds the model-facing text and tools from the facts the Runtime states (`engineToolsFor`): the sandbox tools and note with a sandbox, the skill tools with the skill catalog, and the artifact tools. It also makes the session's MCP tools from `turn.start.mcp`, the servers' tools by their own names (`mcpToolSet`, protocol 15): it names each for the model (`server__tool`, within 64 characters, `mcpToolName`), skips the ones the turn disables, defers an agent's tools behind `tool_search` and `tool_call` when they would take more than a tenth of the model's context window or the manifest says so, and keeps that layout in its state (`mcpLayout`) while the facts stay the same. Each tool call names what runs it (its effect `target`: an MCP tool's `{server, tool}`, an HTTP tool's declared name), so no name is reserved: a name two of the model's tools share fails the turn.
48
+
49
+ Our harness fits every tool result to the record before it reports it (`shapeToolOutcome`, `StepBudget`): a large or binary result is stored as file artifacts of the session, keyed by its effect (`spillKey`), and the model gets a preview it reads on with `read_artifact`. `createHarness({ mcpTools, toolResults })` sets both (`DEFAULT_MCP_TOOL_CONFIG`, `DEFAULT_TOOL_RESULT_CONFIG`), and a harness of your own may reuse these exports from `@nylorun/harness`.
48
50
 
49
51
  Each builder call (`.instructions()`, `.tools()`, `.subagents()`, `.mcp()`, `.output()`) returns a **new** agent; the engine offers the agent's instructions and tools to the model on every step. Do **not** put `model` on `Agent({})` — Runtime resolves and calls the model.
50
52
 
@@ -1,5 +1,5 @@
1
- import type { McpSnapshot, ParamsOf, ResultOf, RunGrant, TurnStart } from "@nylorun/core/harness-api";
2
- import type { DurableSessionTool, HostEffect } from "../run/durable.js";
1
+ import type { McpFacts, ParamsOf, ResultOf, RunGrant, TurnStart } from "@nylorun/core/harness-api";
2
+ import type { HostEffect } from "../run/durable.js";
3
3
  /** A run as the harness holds it: the lease, what it started from, and its signal. */
4
4
  export interface HarnessRun {
5
5
  readonly runId: string;
@@ -8,15 +8,79 @@ export interface HarnessRun {
8
8
  readonly start: TurnStart;
9
9
  readonly signal: AbortSignal;
10
10
  }
11
+ /** A failed tool outcome, as the model sees it. */
12
+ export interface FailedFileOutcome {
13
+ readonly kind: "failed";
14
+ readonly code: string;
15
+ readonly message: string;
16
+ readonly retryable?: boolean;
17
+ }
18
+ /** One regular file under a directory `HarnessFiles.list` listed. */
19
+ export interface HarnessFileEntry {
20
+ /** Relative to the directory listed, `/`-separated, never `.` or `..` segments. */
21
+ readonly path: string;
22
+ readonly size: number;
23
+ }
11
24
  /**
12
- * What runs the effects the harness executes: model calls, MCP, HTTP and sandbox tools. Core
13
- * runs everything else (flow work, linked sessions, its own built-in tools).
25
+ * The run's sandbox files, which our engine decides about and the host only executes (protocol
26
+ * 15): bytes for its artifact tools (`save_artifact` reads a file, `read_artifact` with `path`
27
+ * writes one), a listing and reads for the outputs folder it saves at a turn's end, and the skill
28
+ * folders it mounts before a sandbox call. Each runs in the session's sandbox queue. Paths are the
29
+ * model's: relative ones resolve in the workspace. A session without a sandbox, or a sandbox that
30
+ * cannot start, answers a failed outcome.
31
+ */
32
+ export interface HarnessFiles {
33
+ /** A file's bytes: `missing` when there is none, failed when it is larger than `maxBytes`. */
34
+ read(run: HarnessRun, path: string, maxBytes: number, signal: AbortSignal): Promise<{
35
+ readonly kind: "read";
36
+ readonly path: string;
37
+ readonly bytes: Uint8Array;
38
+ } | {
39
+ readonly kind: "missing";
40
+ readonly path: string;
41
+ } | FailedFileOutcome>;
42
+ /** Writes `body` to a file as it comes, making its folders; replaces a file there. */
43
+ write(run: HarnessRun, path: string, body: AsyncIterable<Uint8Array>, signal: AbortSignal): Promise<{
44
+ readonly kind: "written";
45
+ readonly path: string;
46
+ readonly size: number;
47
+ } | FailedFileOutcome>;
48
+ /**
49
+ * The regular files under directory `dir`, recursively, in path order: at most `maxEntries`,
50
+ * with `truncated` when there are more. `missing` when `dir` is not a directory, or the sandbox
51
+ * was never created (nothing is started to look).
52
+ */
53
+ list(run: HarnessRun, dir: string, maxEntries: number, signal: AbortSignal): Promise<{
54
+ readonly kind: "listed";
55
+ readonly entries: readonly HarnessFileEntry[];
56
+ readonly truncated: boolean;
57
+ } | {
58
+ readonly kind: "missing";
59
+ } | FailedFileOutcome>;
60
+ /**
61
+ * Writes `files` (path in `folder` to `sha256:<hex>`) to `folder`, read-only, each one's bytes
62
+ * from `read`: `mounted`. A folder this sandbox already holds, since it last started, is
63
+ * `present`, and nothing is written. A partial copy a failed mount left is replaced.
64
+ */
65
+ mount(run: HarnessRun, folder: string, files: Readonly<Record<string, string>>, read: (sha256: string) => AsyncIterable<Uint8Array>, signal: AbortSignal): Promise<{
66
+ readonly kind: "mounted" | "present";
67
+ } | FailedFileOutcome>;
68
+ }
69
+ /**
70
+ * What runs the effects the harness executes: model calls (always through the Model Gate), MCP,
71
+ * HTTP and sandbox tools, and the sandbox files our engine uses. Our engine runs its own tools (`harness` calls:
72
+ * the skill tools over `definition.file`, the artifact tools over the artifact seam,
73
+ * `tool_search` over the run's MCP tools) and shapes every tool result before it is recorded;
74
+ * core runs flow work and linked sessions.
14
75
  */
15
76
  export interface HarnessExecutors {
16
77
  /** A model call. A provider failure is a failure outcome; only an abort throws. */
17
78
  model(effect: HostEffect, signal: AbortSignal, run: HarnessRun): Promise<unknown>;
18
79
  /**
19
- * An MCP, HTTP or sandbox tool call, routed by `run.start.routing`. `call.traceparent` is the
80
+ * An MCP, HTTP or sandbox tool call, routed by its `target` and `run.start.routing`: an MCP
81
+ * call names its server and the server's own tool name, an HTTP call the declared tool, and a
82
+ * `sandbox` call runs in the sandbox `routing.sandbox.spec` names. What it answers is the
83
+ * tool's whole result: our engine shapes it before it is recorded. `call.traceparent` is the
20
84
  * call's span context from core's `execute` answer (R7.4): a sandbox command gets it as
21
85
  * `TRACEPARENT`.
22
86
  */
@@ -40,11 +104,16 @@ export interface HarnessExecutors {
40
104
  resends?(effect: HostEffect, error: unknown, run: HarnessRun): boolean;
41
105
  /**
42
106
  * Readies the session's MCP servers before an agent's segment runs (F6.2): discovers their
43
- * tools the first time, reconnects them after. `record` keeps what it found in the session
44
- * (`session.mcp`; the first snapshot recorded wins) and answers the session's snapshot and
45
- * tools, which the segment runs with. Undefined: nothing to change.
107
+ * tools when the run has no MCP facts yet (`turn.start.mcp`), reconnects them after. `record`
108
+ * keeps what it found in the session (`session.mcp`; the first snapshot recorded wins) and
109
+ * answers the facts the segment runs with. Undefined: nothing to change.
46
110
  */
47
111
  prepare?(run: HarnessRun, record: McpRecorder): Promise<PreparedRun | undefined>;
112
+ /**
113
+ * The run's sandbox files. Undefined: a `path` of an artifact tool fails `artifact.no_sandbox`,
114
+ * no skill folder is mounted and no outputs folder is saved.
115
+ */
116
+ readonly files?: HarnessFiles;
48
117
  }
49
118
  /** What core's `execute` answer says of a tool call beside running it (R7.4). */
50
119
  export interface ToolCallContext {
@@ -52,8 +121,7 @@ export interface ToolCallContext {
52
121
  }
53
122
  /** Records a session's MCP discovery in core (`session.mcp`). */
54
123
  export type McpRecorder = (params: Omit<ParamsOf<"session.mcp">, "runId">) => Promise<ResultOf<"session.mcp">>;
55
- /** The session's MCP snapshot and tools after `prepare`. */
124
+ /** The session's MCP facts after `prepare`, as the turn sees them. */
56
125
  export interface PreparedRun {
57
- readonly sessionTools: readonly DurableSessionTool[];
58
- readonly mcpSnapshot?: McpSnapshot;
126
+ readonly mcp?: McpFacts;
59
127
  }
@@ -5,8 +5,22 @@
5
5
  * with `ownership.lost`, and `stop()` with `shutdown`. While a run is live it renews its lease
6
6
  * every `renewEveryMs`; renewing stops once the run is aborted.
7
7
  */
8
- import { type HarnessChannel, type ResultOf, type RunGrant } from "@nylorun/core/harness-api";
8
+ import { type HarnessChannel, type ResultOf, type RunGrant, type TurnStart } from "@nylorun/core/harness-api";
9
+ import { type SandboxToolLimits } from "../tools/sandbox.js";
10
+ import { type McpToolConfig } from "../tools/mcp.js";
11
+ import { type ToolResultConfig } from "../tools/results.js";
12
+ import { type OutputsConfig } from "../tools/outputs.js";
9
13
  import type { HarnessExecutors } from "./executors.js";
14
+ import type { CompactionConfig } from "../loop/compaction/config.js";
15
+ /** The transcript cache's budget when the harness sets none, in MiB. */
16
+ export declare const DEFAULT_TRANSCRIPT_CACHE_MB = 256;
17
+ /** How soon a `lease` request that failed is sent again, by default. */
18
+ export declare const DEFAULT_LEASE_RETRY_MS = 100;
19
+ /**
20
+ * The waits before each resend of a tool call whose gate hop lost its answer (R5.3), by default;
21
+ * the last repeats.
22
+ */
23
+ export declare const DEFAULT_RESEND_DELAYS_MS: readonly number[];
10
24
  export interface HarnessLogger {
11
25
  warn(message: string, fields?: Record<string, unknown>): void;
12
26
  }
@@ -16,8 +30,68 @@ export interface HarnessOptions {
16
30
  readonly logger?: HarnessLogger;
17
31
  /** Runs held at once. Default: no limit. */
18
32
  readonly maxRuns?: number;
19
- /** Byte budget of the transcript cache. Default 256 MiB. */
33
+ /** Byte budget of the transcript cache, in MiB. Default `DEFAULT_TRANSCRIPT_CACHE_MB` (256). */
20
34
  readonly transcriptCacheMb?: number;
35
+ /** How soon a `lease` request that failed is sent again. Default `DEFAULT_LEASE_RETRY_MS` (100 ms). */
36
+ readonly leaseRetryMs?: number;
37
+ /**
38
+ * The waits before each resend of a tool call whose gate hop lost its answer (R5.3); the last
39
+ * repeats. Default `DEFAULT_RESEND_DELAYS_MS` (1, 2, then 4 s).
40
+ */
41
+ readonly resendDelaysMs?: readonly number[];
42
+ /**
43
+ * Compaction (Model Calls §8): the kept tail, the reply's reserve, the estimate. Each left out
44
+ * is its default (`DEFAULT_COMPACTION_CONFIG`).
45
+ */
46
+ readonly compaction?: Partial<CompactionConfig>;
47
+ /**
48
+ * How many characters of a failed agent-as-tool's last output its parent sees. Default
49
+ * `DEFAULT_PARTIAL_OUTPUT_CHARS` (4,000).
50
+ */
51
+ readonly partialOutputChars?: number;
52
+ /**
53
+ * How many characters of a value a flow's failure message quotes. Default
54
+ * `DEFAULT_FLOW_VALUE_CHARS` (80).
55
+ */
56
+ readonly flowValueChars?: number;
57
+ /**
58
+ * The most bytes one `read_artifact` page holds, escaped as JSON: what one call shows the model
59
+ * of a text artifact. Default `DEFAULT_ARTIFACT_PAGE_BYTES` (32 KiB). A page is also held to the
60
+ * run's `turn.start.limits.chunkBytes`.
61
+ */
62
+ readonly artifactPageBytes?: number;
63
+ /**
64
+ * The sandbox tools' limits, which our engine writes into their schemas: the `bash` timeouts,
65
+ * the `read` and `grep` counts. Each left out is its default (`DEFAULT_SANDBOX_TOOL_LIMITS`).
66
+ * The executors that run the calls take the same (`harnessExecutors({ sandboxTools })`).
67
+ */
68
+ readonly sandboxTools?: Partial<SandboxToolLimits>;
69
+ /**
70
+ * The most bytes of one skill file `load_skill` and `read_skill_resource` read into the model's
71
+ * context. Default `DEFAULT_SKILL_READ_BYTES` (10 MiB); an answer is also held to the run's
72
+ * `turn.start.limits.recordEntryBytes`, since it is one record entry.
73
+ */
74
+ readonly skillReadBytes?: number;
75
+ /**
76
+ * How our engine offers the session's MCP tools: when it defers them (`deferShare` of the
77
+ * model's context window at `charsPerToken`, `fallbackContextWindow` without a model), how much
78
+ * of a server's instructions the deferred tools' note shows, and `tool_search`'s limits. Each
79
+ * left out is its default (`DEFAULT_MCP_TOOL_CONFIG`).
80
+ */
81
+ readonly mcpTools?: Partial<McpToolConfig>;
82
+ /**
83
+ * How our engine shapes tool results before it records them: the inline cap, the preview's head
84
+ * and tail, the step budget (held under the run's `limits.recordEntryBytes` less
85
+ * `entryEnvelopeBytes`), the stub and the size never shaped. Each left out is its default
86
+ * (`DEFAULT_TOOL_RESULT_CONFIG`).
87
+ */
88
+ readonly toolResults?: Partial<ToolResultConfig>;
89
+ /**
90
+ * Our engine's outputs folder: the directory it saves as the session's `outputs` folder artifact
91
+ * when a turn completes in a sandbox, and the most bytes one save stores. Each left out is its
92
+ * default (`DEFAULT_OUTPUTS_CONFIG`: `/workspace/outputs`, 1 GiB).
93
+ */
94
+ readonly outputs?: Partial<OutputsConfig>;
21
95
  readonly name?: string;
22
96
  readonly version?: string;
23
97
  /** What `hello` declares: `workspace` when this harness serves the Tenant's workspaces. */
@@ -28,6 +102,11 @@ export interface HarnessOptions {
28
102
  onHello?(answer: ResultOf<"hello">): void;
29
103
  /** Sees every grant a run gets: when it is leased, and each renewal with a new run token. */
30
104
  onGrant?(grant: RunGrant): void;
105
+ /**
106
+ * Sees each run's `turn.start` when it is leased: the Runtime limits in force
107
+ * (`start.limits`) among the rest.
108
+ */
109
+ onStart?(grant: RunGrant, start: TurnStart): void;
31
110
  }
32
111
  export interface Harness {
33
112
  /** Says `hello` and starts leasing. Resolves once `hello` is answered. */
@@ -41,4 +120,6 @@ export interface Harness {
41
120
  /** Runs held now. */
42
121
  readonly runs: number;
43
122
  }
123
+ /** The default of the harness's `artifactPageBytes` setting: one `read_artifact` page. */
124
+ export declare const DEFAULT_ARTIFACT_PAGE_BYTES: number;
44
125
  export declare function createHarness(options: HarnessOptions): Harness;