@nylorun/harness 0.26.0-beta → 0.27.0-beta
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +47 -0
- package/HOST_CONTRACT.md +13 -11
- package/README.md +11 -12
- package/dist/api/harness.d.ts +1 -1
- package/dist/api/harness.js +2 -2
- package/dist/definition/agent-definition.d.ts +2 -2
- package/dist/definition/agent-definition.js +2 -2
- package/dist/definition/registry.d.ts +3 -3
- package/dist/definition/registry.js +12 -15
- package/dist/loop/compaction/index.d.ts +4 -2
- package/dist/loop/compaction/index.js +78 -8
- package/dist/loop/dispatch.js +1 -1
- package/dist/loop/model/project.d.ts +6 -0
- package/dist/loop/model/project.js +59 -18
- package/dist/loop/run.js +2 -2
- package/dist/loop/state.js +0 -1
- package/dist/loop/step/canonicalize.d.ts +1 -3
- package/dist/loop/step/canonicalize.js +0 -15
- package/dist/loop/step/model-configuration.d.ts +4 -13
- package/dist/loop/step/model-configuration.js +12 -70
- package/dist/loop/step/resolve.js +0 -1
- package/dist/loop/step/run.js +33 -12
- package/dist/loop/step/runtime.d.ts +2 -2
- package/dist/loop/step/seal.js +0 -17
- package/dist/loop/step/slot-assembly.d.ts +5 -5
- package/dist/loop/step/slot-assembly.js +5 -5
- package/dist/loop/step/step-context.d.ts +5 -19
- package/dist/loop/step/step-context.js +9 -195
- package/dist/loop/transcript.js +7 -1
- package/dist/run/durable.d.ts +1 -3
- package/dist/run/durable.js +25 -27
- package/dist/types/execution.d.ts +0 -1
- package/package.json +2 -2
- package/dist/loop/step/compose.d.ts +0 -5
- package/dist/loop/step/compose.js +0 -109
- package/dist/loop/step/context-draft.d.ts +0 -8
- package/dist/loop/step/context-draft.js +0 -48
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,52 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.27.0-beta
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- c96b9a8: **An agent manifest is flat: manifest v7, a `runtime` block the Runtime writes, and tools known by name (protocol 13, Harness API 3).** A manifest listed capabilities, each with its own instructions, tools, skills and servers, and the Runtime added its own as more capabilities. Now the agent's parts sit at the top level, a plugin's skills and servers say which plugin brought them, and what the Runtime adds to a session's agent is one `runtime` block. A fresh start: the Runtime speaks protocol 13 only, so save your agents again; sessions from protocol 12 do not carry over. See MIGRATION.md.
|
|
8
|
+
|
|
9
|
+
- **Manifest v7.** `{ manifestSchemaVersion: 7, id, name?, description?, metadata?, outputSchema?, instructions?, tools?, skills?, mcpServers?, runtime? }`. Versions 3 to 6 and a `capabilities` field are refused with a message to rebuild. `SkillManifest.plugin` and `McpServerManifest.plugin` are `{ name, version? }`, set by `.plugin(dir)` from `plugin.json`.
|
|
10
|
+
- **The `runtime` block.** `{ sandbox?, tools?, instructions? }`, written only by the Runtime when a session pins the agent: the sandbox spec and tools, `save_artifact`, `read_artifact`, `load_skill` and `read_skill_resource`, the skill catalog and the notes that go with them. A definition or a turn variant that sets it is refused. `runtimeManifestFor` in `@nylorun/core/define` replaces `sandboxCapabilityManifest`, `artifactsCapabilityManifest` and `toolsCapabilityManifest`. `.skills()` and `.plugin()` no longer add the skill tools or the catalog.
|
|
11
|
+
- **Names.** An agent's tool may not take a Runtime tool's name (`RUNTIME_TOOL_NAMES`) or contain `__`, and names are unique across tools, skills and servers.
|
|
12
|
+
- **Turn variants** may remove tools, tighten MCP servers and change instructions, name, description and metadata. Skills are fixed, and a variant never sets `runtime` or changes `outputSchema`.
|
|
13
|
+
- **Tools by name.** `capabilityId` is gone from `tool.completed`, `mcp.discovered`, tool call rows, `EffectIntent`, gate requests, checkpoints and `SessionToolRef`. An HTTP tool's `server` is its URL's host. `Implementations` is `{ tools }`, keyed by tool name (`Agent.from(json, { tools })`), `AgentBinding.declarations` is `parts`, and observe events say `partId`.
|
|
14
|
+
- **Harness API 3.** `hello.capabilities` is `features`, and the `harness` pseudo-capability is gone: a native tool is known by its name, and one whose name is taken fails the turn at its start. `createHarness({ features })` in `@nylorun/harness`. `examples/harness-minimal` speaks it.
|
|
15
|
+
- **Studio.** The Agent tab shows instructions, tools (HTTP and agent badges), skills and MCP servers, each skill and server with its plugin's badge and a filter by plugin, and a session's Runtime section: its sandbox, tools and instructions.
|
|
16
|
+
- `@nylorun/core`: `PROTOCOL_VERSION` 13, `HOST_PROTOCOL` `{ min: 13, max: 13 }`, required feature `flat-manifest`, `HARNESS_API_VERSION` 3; `PluginLabel`, `RuntimeManifest`, `RUNTIME_TOOL_NAMES`, `isRuntimeToolName`, `runtimeToolOf`, `isSkillTool`, `SKILLS_USAGE` and `formatSkillCatalog` in `/define`.
|
|
17
|
+
- `@nylorun/agents`, `@nylorun/admin`, `@nylorun/studio` and `nylorun` send protocol 13.
|
|
18
|
+
|
|
19
|
+
- 94bf329: **Each model says what it reads, a file it does not read is refused before a turn starts, and a file is an artifact the model reads again after its turn (protocol 12).** A message could name any file, and a model that could not read it failed the turn at its model call; every later turn sent the file's bytes again. Now the Runtime knows what the Tenant's model reads, checks a message's files when it is accepted, and sends a file's bytes only in the turn that brought it. Protocol 12 only adds to 11: the Runtime serves both.
|
|
20
|
+
|
|
21
|
+
- **Model inputs.** A model reads `text`, and `image`, `pdf`, `office`, `audio` or `video` when its catalog says so or the operator adds it where its API carries it natively (images everywhere; PDFs on the Anthropic, OpenAI, Azure and Google APIs; Office documents on the OpenAI Responses APIs; audio and video on Google's APIs and OpenAI-compatible completions). `GET /v1/tenant/models` gives each model `inputs` and `addableInputs`, `GET /v1/tenant/providers` each provider's `inputs`, and **`PUT /v1/tenant/models/inputs`** (the Management API; `admin.models.setInputs({ provider, model, inputs })`) sets the added ones, kept in the Tenant setting `model.inputs`. The Model Gate gives the provider adapter a model with an added image, so it is sent.
|
|
22
|
+
- **A custom endpoint reads text only by default.** It used to be sent images. Set `settings.inputs` on `PUT /v1/tenant/model` (`image`, `pdf`, `audio`, `video`) for what yours reads; `office` is refused there. See MIGRATION.md.
|
|
23
|
+
- **The accept check.** A message naming a file of a type the Tenant's model does not read is `422 attachment_unsupported`, with `details.parts` (`artifactId`, `name`, `mediaType`, `reason`), and no turn starts. Only the type is checked, never the size. Without a model in the vault nothing is refused.
|
|
24
|
+
- **Files as artifacts.** After its turn a file is a reference line, `[Uploaded artifact "name" · <artifactId> v<n> · read_artifact to view]` (a tool's: `[Tool <name> returned artifact …]`). Our harness sends the turn's own files once more, as media, in one user message after the conversation, so a message reads the same in every later call. At the gate, an image the model reads is an image, a text file a `<file>` block, and any other file, or one that cannot be read, a note: no file fails a call. PDFs, Office documents, audio and video are notes until the gate sends them natively.
|
|
25
|
+
- **`read_artifact` for every agent.** Every agent's session has it (an agent that declares its own keeps it), so every agent session pins its definition with it added. It takes a `version`, reads the Tenant-wide artifacts the session's messages named, and shows any file the Tenant's model reads; one it does not read fails `artifact.unsupported`.
|
|
26
|
+
- **Compaction** keeps the summarized part's reference lines (`files` on the compaction entry), and counts the turn's files by type and size in its token estimate.
|
|
27
|
+
- `@nylorun/core`: `PROTOCOL_VERSION` 12, required feature `model-inputs`, `HOST_PROTOCOL` `{ min: 11, max: 12 }`, error code `attachment_unsupported`; `MODEL_INPUTS`, `ModelInputSchema`, `PutModelInputsRequestSchema`, `ModelInputsViewSchema`, `CustomModelSettings.inputs`; `mediaReferenceLine` and `mediaReferenceOf` in `/define`; `TranscriptCompactionEntry.files`.
|
|
28
|
+
- `@nylorun/agents`, `@nylorun/studio` and `nylorun` send protocol 12.
|
|
29
|
+
|
|
30
|
+
- b5ea2b5: **An agent is its manifest: step middleware and capability bundles are removed from authoring.** The Runtime already refused middleware; now the local engine runs none either, and an agent is built only from the builder's own methods. No protocol change. See MIGRATION.md.
|
|
31
|
+
|
|
32
|
+
- **Removed:** `.use()`, `.capability()`, `capability()`, `CapabilityBuilder`, `middleware()`, `model()`, `StepMiddleware`, `StepRequest`, `StepResponse`, and `Implementations[id].middleware`. To reuse tools and instructions, write a function that adds them; a bundle you publish is an Agent Plugin.
|
|
33
|
+
- **`@nylorun/agents`:** the standalone `skills()`, `plugin()` and `mcp()` factories are removed; use `.skills(dir)`, `.plugin(dir)` and `.mcp(servers)`. `.skills()` takes no options: the part takes the folder's name.
|
|
34
|
+
- **`@nylorun/harness`:** each step offers the definition's tools and instructions in order. The `middleware.entered`, `middleware.completed` and `middleware.lease-violation` observe events are gone, and a model request carries no `model` directive or runtime context items.
|
|
35
|
+
|
|
36
|
+
### Patch Changes
|
|
37
|
+
|
|
38
|
+
- Pin core to the tested release.
|
|
39
|
+
- Updated dependencies [3a32a57]
|
|
40
|
+
- Updated dependencies [af90d1e]
|
|
41
|
+
- Updated dependencies [104f24f]
|
|
42
|
+
- Updated dependencies [c96b9a8]
|
|
43
|
+
- Updated dependencies [94bf329]
|
|
44
|
+
- Updated dependencies [b5ea2b5]
|
|
45
|
+
- Updated dependencies [aff9bb8]
|
|
46
|
+
- Updated dependencies [f44c018]
|
|
47
|
+
- Updated dependencies [c8e640b]
|
|
48
|
+
- @nylorun/core@0.21.0-beta
|
|
49
|
+
|
|
3
50
|
## 0.26.0-beta
|
|
4
51
|
|
|
5
52
|
### Minor Changes
|
package/HOST_CONTRACT.md
CHANGED
|
@@ -4,9 +4,9 @@ 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
|
|
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.
|
|
8
8
|
|
|
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
|
|
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
|
|
|
11
11
|
**Tenant and protocol headers.** A Host serves the one Tenant of its
|
|
12
12
|
installation, and nothing in a request selects it (protocol 5). Every Tenant
|
|
@@ -15,7 +15,9 @@ 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
|
|
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
|
|
19
21
|
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
|
|
20
22
|
Tenant that could not be opened and an unknown Tenant share the opaque `404`
|
|
21
23
|
body. A missing or rejected credential is `401` (`credential_required`,
|
|
@@ -37,7 +39,7 @@ All command idempotency keys bind to canonical request content within a session;
|
|
|
37
39
|
|
|
38
40
|
## Engine host
|
|
39
41
|
|
|
40
|
-
`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
|
|
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.
|
|
41
43
|
|
|
42
44
|
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.
|
|
43
45
|
|
|
@@ -45,17 +47,17 @@ A terminal/paused result includes `result.state`. Save it. A new message uses a
|
|
|
45
47
|
|
|
46
48
|
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.
|
|
47
49
|
|
|
48
|
-
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
|
|
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.
|
|
49
51
|
|
|
50
|
-
**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 `
|
|
52
|
+
**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`).
|
|
51
53
|
|
|
52
|
-
**Turn manifests.** A `message` command may include optional `manifest`. Any app may use it (not only Loops). When present, the Runtime parses it with `AgentManifestSchema`, requires it to be a **variant** of the session's pinned manifest (id fixed; tools
|
|
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.
|
|
53
55
|
|
|
54
|
-
**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
|
|
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.
|
|
55
57
|
|
|
56
|
-
## Harness API
|
|
58
|
+
## Harness API 3
|
|
57
59
|
|
|
58
|
-
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 =
|
|
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.
|
|
59
61
|
|
|
60
62
|
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`, …).
|
|
61
63
|
|
|
@@ -71,6 +73,6 @@ A Runtime below F6.1 compares journal rows by their full request: downgrading on
|
|
|
71
73
|
|
|
72
74
|
## Definitions, validation, compatibility
|
|
73
75
|
|
|
74
|
-
`/define` is execution-free and browser-bundleable; Agent has no `.run()`. Explicit local execution uses `/run` run + bindingFromAgent(agent.build()). `/contracts` never imports checkpoint internals. Tools are supported remotely.
|
|
76
|
+
`/define` is execution-free and browser-bundleable; Agent has no `.run()`. Explicit local execution uses `/run` run + bindingFromAgent(agent.build()). `/contracts` never imports checkpoint internals. Tools are supported remotely. JSON schemas are reconstructed through Zod's JSON Schema importer; unsupported schemas fail closed. The original manifest document must survive reconstruction. Runtime is the only hasher: it hashes the accepted manifest and pins that digest on the session. Agents do not hash. Model configuration is host-owned. The Runtime refuses a definition whose tools would run the developer's code. It checks an HTTP tool's answer against the tool's output schema and records a mismatch as the failed outcome `tool.invalid-output`.
|
|
75
77
|
|
|
76
78
|
No session migration, arbitrary checkpoint migration, broad model-support, or conformance claims follow from compiling this interface. Studio and conformance tooling remain outside production harness.
|
package/README.md
CHANGED
|
@@ -19,7 +19,7 @@ provider call.
|
|
|
19
19
|
## Compose an agent
|
|
20
20
|
|
|
21
21
|
```ts
|
|
22
|
-
import { Agent, tool, ToolError
|
|
22
|
+
import { Agent, tool, ToolError } from "@nylorun/agents/define";
|
|
23
23
|
import { z } from "zod";
|
|
24
24
|
|
|
25
25
|
const lookup = tool({
|
|
@@ -33,21 +33,20 @@ const lookup = tool({
|
|
|
33
33
|
},
|
|
34
34
|
});
|
|
35
35
|
|
|
36
|
-
export const supportAgent = Agent({
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
instructions: "You help customers with orders. Be brief.",
|
|
40
|
-
tools: [lookup],
|
|
41
|
-
}).capability(capability({ id: "policy" }).instructions("Never promise a refund."));
|
|
36
|
+
export const supportAgent = Agent({ id: "support", name: "Support" })
|
|
37
|
+
.instructions("You help customers with orders. Be brief.", "Never promise a refund.")
|
|
38
|
+
.tools(lookup);
|
|
42
39
|
|
|
43
40
|
// Optional: .build() is a no-op facade
|
|
44
41
|
const agent = supportAgent.build();
|
|
45
42
|
|
|
46
|
-
JSON.stringify(supportAgent); // manifest
|
|
47
|
-
Agent.from(supportAgent.toJSON(),
|
|
43
|
+
JSON.stringify(supportAgent); // manifest v7: { manifestSchemaVersion: 7, id, name, instructions, tools }
|
|
44
|
+
Agent.from(supportAgent.toJSON(), { tools: { lookup_order: lookup } });
|
|
48
45
|
```
|
|
49
46
|
|
|
50
|
-
|
|
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.
|
|
48
|
+
|
|
49
|
+
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.
|
|
51
50
|
|
|
52
51
|
## Run the loop
|
|
53
52
|
|
|
@@ -78,8 +77,8 @@ Prefer `input` / `output` / `run`. Legacy `inputSchema` / `execute` and tagged `
|
|
|
78
77
|
|
|
79
78
|
Definitions must not import `@nylorun/runtime`.
|
|
80
79
|
|
|
81
|
-
|
|
82
|
-
|
|
80
|
+
There is no step middleware: a hosted agent is its manifest, and the Runtime runs it from
|
|
81
|
+
that alone.
|
|
83
82
|
|
|
84
83
|
## Checkpoint / durability
|
|
85
84
|
|
package/dist/api/harness.d.ts
CHANGED
|
@@ -21,7 +21,7 @@ export interface HarnessOptions {
|
|
|
21
21
|
readonly name?: string;
|
|
22
22
|
readonly version?: string;
|
|
23
23
|
/** What `hello` declares: `workspace` when this harness serves the Tenant's workspaces. */
|
|
24
|
-
readonly
|
|
24
|
+
readonly features?: {
|
|
25
25
|
readonly workspace?: unknown;
|
|
26
26
|
};
|
|
27
27
|
/** Sees core's answer to `hello` (the Tenant, the sandbox backend preference). */
|
package/dist/api/harness.js
CHANGED
|
@@ -113,9 +113,9 @@ export function createHarness(options) {
|
|
|
113
113
|
api: HARNESS_API_VERSION,
|
|
114
114
|
name: options.name ?? DEFAULT_HARNESS,
|
|
115
115
|
version: options.version ?? "0",
|
|
116
|
-
|
|
116
|
+
features: options.features?.workspace === undefined
|
|
117
117
|
? {}
|
|
118
|
-
: { workspace: options.
|
|
118
|
+
: { workspace: options.features.workspace },
|
|
119
119
|
});
|
|
120
120
|
renewEveryMs = hello.renewEveryMs;
|
|
121
121
|
options.onHello?.(hello);
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { DefinitionPart } from "@nylorun/core/define";
|
|
2
2
|
import type { ToolRegistry } from "./registry.js";
|
|
3
3
|
import type { TurnOutputContract } from "@nylorun/core/define";
|
|
4
4
|
import type { AgentManifest } from "@nylorun/core/define";
|
|
5
5
|
import type { Implementations } from "@nylorun/core/define";
|
|
6
6
|
export interface AgentDefinition {
|
|
7
7
|
readonly id: string;
|
|
8
|
-
readonly
|
|
8
|
+
readonly parts: readonly DefinitionPart[];
|
|
9
9
|
readonly registry: ToolRegistry;
|
|
10
10
|
readonly output?: TurnOutputContract;
|
|
11
11
|
readonly manifest: AgentManifest;
|
|
@@ -9,9 +9,9 @@ export function definitionFromBinding(binding) {
|
|
|
9
9
|
id: binding.manifest.id,
|
|
10
10
|
manifest: binding.manifest,
|
|
11
11
|
hash: hashManifest(binding.manifest),
|
|
12
|
-
|
|
12
|
+
parts: binding.parts,
|
|
13
13
|
implementations: binding.implementations,
|
|
14
|
-
registry: new Registry(binding.
|
|
14
|
+
registry: new Registry(binding.parts, binding.tools),
|
|
15
15
|
...(binding.outputSchema ? { output: bindOutputContract(binding.outputSchema) } : {}),
|
|
16
16
|
});
|
|
17
17
|
}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { DefinitionPart, BoundToolDefinition } from "@nylorun/core/define";
|
|
2
2
|
import type { ToolReference } from "../types/execution.js";
|
|
3
3
|
/** Definition-only lookup; no per-run selections or progress live here. */
|
|
4
4
|
export declare class ToolRegistry {
|
|
5
5
|
private readonly tools;
|
|
6
|
-
private readonly
|
|
7
|
-
constructor(
|
|
6
|
+
private readonly registered;
|
|
7
|
+
constructor(parts: readonly DefinitionPart[], snapshots?: readonly BoundToolDefinition[]);
|
|
8
8
|
reference(tool: BoundToolDefinition): ToolReference;
|
|
9
9
|
restore(reference: ToolReference): BoundToolDefinition;
|
|
10
10
|
}
|
|
@@ -5,25 +5,22 @@ import { copyJson } from "@nylorun/core/define";
|
|
|
5
5
|
/** Definition-only lookup; no per-run selections or progress live here. */
|
|
6
6
|
export class ToolRegistry {
|
|
7
7
|
tools = new Map();
|
|
8
|
-
|
|
9
|
-
constructor(
|
|
10
|
-
for (const
|
|
11
|
-
for (const tool of [...(
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
this.owners.set(tool, capability.id);
|
|
8
|
+
registered = new WeakSet();
|
|
9
|
+
constructor(parts, snapshots) {
|
|
10
|
+
for (const part of parts) {
|
|
11
|
+
for (const tool of [...(part.tools ?? []), ...(part.sessionTools ?? [])]) {
|
|
12
|
+
if (this.tools.has(tool.name) || this.registered.has(tool))
|
|
13
|
+
throw new HarnessError("tool.invalid", `Duplicate registered tool '${tool.name}'`);
|
|
14
|
+
this.tools.set(tool.name, snapshots?.find((snapshot) => snapshot.source === tool) ??
|
|
15
|
+
bindTool(tool, { partId: part.id, slot: part.id }));
|
|
16
|
+
this.registered.add(tool);
|
|
18
17
|
}
|
|
19
18
|
}
|
|
20
19
|
}
|
|
21
20
|
reference(tool) {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
throw new HarnessError("tool.unregistered", `Tool '${tool.name}' is not registered. Declare it in capability.tools.`);
|
|
21
|
+
if (!this.registered.has(tool.source))
|
|
22
|
+
throw new HarnessError("tool.unregistered", `Tool '${tool.name}' is not registered. Declare it with .tools().`);
|
|
25
23
|
const reference = copyJson({
|
|
26
|
-
capabilityId,
|
|
27
24
|
toolName: tool.source.name,
|
|
28
25
|
descriptor: descriptor(tool),
|
|
29
26
|
});
|
|
@@ -33,7 +30,7 @@ export class ToolRegistry {
|
|
|
33
30
|
restore(reference) {
|
|
34
31
|
if ("familyId" in reference || "binding" in reference || "version" in reference)
|
|
35
32
|
throw new HarnessError("execution.incompatible", "Saved state uses a removed tool-family reference. Register an ordinary tool and start a new execution.");
|
|
36
|
-
const registered = this.tools.get(
|
|
33
|
+
const registered = this.tools.get(reference.toolName);
|
|
37
34
|
if (!registered || canonical(descriptor(registered)) !== canonical(reference.descriptor))
|
|
38
35
|
throw new HarnessError("execution.incompatible", `Missing or changed registered tool '${reference.toolName}'`);
|
|
39
36
|
return registered;
|
|
@@ -18,9 +18,11 @@ export declare function contextBudget(transcript: readonly TranscriptEntry[]): C
|
|
|
18
18
|
/**
|
|
19
19
|
* Tokens the next prompt needs: the last reported usage, which already counts the
|
|
20
20
|
* instructions, tools and everything before it, plus an estimate of what came after.
|
|
21
|
-
* Without usage, everything is estimated.
|
|
21
|
+
* Without usage, everything is estimated. The files of turn `turnId` go to the model as media
|
|
22
|
+
* (protocol 12) and count by their size; those of an earlier turn the reported call carried are
|
|
23
|
+
* reference lines now, and come off it.
|
|
22
24
|
*/
|
|
23
|
-
export declare function estimateTokens(transcript: readonly TranscriptEntry[]): number;
|
|
25
|
+
export declare function estimateTokens(transcript: readonly TranscriptEntry[], turnId?: string): number;
|
|
24
26
|
/** A rough token count of what one entry contributes to a prompt. */
|
|
25
27
|
export declare function entryTokens(entry: TranscriptEntry): number;
|
|
26
28
|
/**
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { HarnessError, isModelFailureOutcome } from "@nylorun/core/define";
|
|
1
|
+
import { HarnessError, isModelFailureOutcome, mediaReferenceLine, mediaReferenceOf, } from "@nylorun/core/define";
|
|
2
2
|
/** Characters per token for the heuristic estimate; the reserve absorbs its error. */
|
|
3
3
|
const CHARS_PER_TOKEN = 4;
|
|
4
4
|
/** The kept tail is at most this many tokens, and at most this share of the window. */
|
|
@@ -33,9 +33,12 @@ export function contextBudget(transcript) {
|
|
|
33
33
|
/**
|
|
34
34
|
* Tokens the next prompt needs: the last reported usage, which already counts the
|
|
35
35
|
* instructions, tools and everything before it, plus an estimate of what came after.
|
|
36
|
-
* Without usage, everything is estimated.
|
|
36
|
+
* Without usage, everything is estimated. The files of turn `turnId` go to the model as media
|
|
37
|
+
* (protocol 12) and count by their size; those of an earlier turn the reported call carried are
|
|
38
|
+
* reference lines now, and come off it.
|
|
37
39
|
*/
|
|
38
|
-
export function estimateTokens(transcript) {
|
|
40
|
+
export function estimateTokens(transcript, turnId) {
|
|
41
|
+
const live = (item) => (item.turnId === turnId ? fileTokens(item) : 0);
|
|
39
42
|
for (let index = transcript.length - 1; index >= 0; index--) {
|
|
40
43
|
const entry = transcript[index];
|
|
41
44
|
if (entry.kind !== "candidate" || !entry.candidate.usage)
|
|
@@ -48,9 +51,62 @@ export function estimateTokens(transcript) {
|
|
|
48
51
|
(usage.outputTokens ?? 0);
|
|
49
52
|
if (reported <= 0)
|
|
50
53
|
continue;
|
|
51
|
-
|
|
54
|
+
const dropped = entry.turnId === turnId
|
|
55
|
+
? 0
|
|
56
|
+
: transcript
|
|
57
|
+
.slice(0, index)
|
|
58
|
+
.reduce((sum, item) => sum + (item.turnId === entry.turnId ? fileTokens(item) : 0), 0);
|
|
59
|
+
return Math.max(0, reported -
|
|
60
|
+
dropped +
|
|
61
|
+
transcript.slice(index + 1).reduce((sum, item) => sum + entryTokens(item) + live(item), 0));
|
|
52
62
|
}
|
|
53
|
-
return transcript.reduce((sum, item) => sum + entryTokens(item), 0);
|
|
63
|
+
return transcript.reduce((sum, item) => sum + entryTokens(item) + live(item), 0);
|
|
64
|
+
}
|
|
65
|
+
/** Tokens per image, and the most one other file counts for, in the estimate. */
|
|
66
|
+
const IMAGE_TOKENS = 1_600;
|
|
67
|
+
const FILE_TOKENS_MAX = 100_000;
|
|
68
|
+
/** A rough token count of the files an entry names, as media: by type and size. */
|
|
69
|
+
function fileTokens(entry) {
|
|
70
|
+
return filesOf(entry).reduce((sum, { part }) => {
|
|
71
|
+
const size = mediaReferenceOf(part.reference)?.size ?? 0;
|
|
72
|
+
const type = part.mediaType.split(";")[0].trim().toLowerCase();
|
|
73
|
+
if (type.startsWith("image/"))
|
|
74
|
+
return sum + IMAGE_TOKENS;
|
|
75
|
+
if (isTextType(type))
|
|
76
|
+
return sum + Math.ceil(size / CHARS_PER_TOKEN);
|
|
77
|
+
return sum + Math.min(Math.ceil(size / 8), FILE_TOKENS_MAX);
|
|
78
|
+
}, 0);
|
|
79
|
+
}
|
|
80
|
+
function isTextType(type) {
|
|
81
|
+
return (type.startsWith("text/") ||
|
|
82
|
+
type.endsWith("+json") ||
|
|
83
|
+
type.endsWith("+xml") ||
|
|
84
|
+
[
|
|
85
|
+
"application/json",
|
|
86
|
+
"application/xml",
|
|
87
|
+
"application/yaml",
|
|
88
|
+
"application/x-yaml",
|
|
89
|
+
"application/javascript",
|
|
90
|
+
].includes(type));
|
|
91
|
+
}
|
|
92
|
+
/** The files an entry names (protocol 12): a message's media parts, and a tool result's files. */
|
|
93
|
+
function filesOf(entry) {
|
|
94
|
+
if (entry.kind === "input") {
|
|
95
|
+
const event = entry.event;
|
|
96
|
+
if ((event.kind !== "user-message" && event.kind !== "interrupt") ||
|
|
97
|
+
!("content" in event) ||
|
|
98
|
+
!event.content)
|
|
99
|
+
return [];
|
|
100
|
+
return event.content.flatMap((part) => part.type === "media" ? [{ line: mediaReferenceLine(part, "uploaded"), part }] : []);
|
|
101
|
+
}
|
|
102
|
+
if (entry.kind === "tool-results")
|
|
103
|
+
return entry.results.flatMap((result) => result.kind === "completed" && result.files
|
|
104
|
+
? result.files.map((part) => ({
|
|
105
|
+
line: mediaReferenceLine(part, { tool: result.toolName }),
|
|
106
|
+
part,
|
|
107
|
+
}))
|
|
108
|
+
: []);
|
|
109
|
+
return [];
|
|
54
110
|
}
|
|
55
111
|
/** A rough token count of what one entry contributes to a prompt. */
|
|
56
112
|
export function entryTokens(entry) {
|
|
@@ -84,7 +140,7 @@ export function findCut(transcript, keepTokens) {
|
|
|
84
140
|
*/
|
|
85
141
|
export async function compact(input) {
|
|
86
142
|
const { transcript } = input;
|
|
87
|
-
const tokensBefore = estimateTokens(transcript);
|
|
143
|
+
const tokensBefore = estimateTokens(transcript, input.turnId);
|
|
88
144
|
const window = input.budget?.contextWindow ?? tokensBefore;
|
|
89
145
|
const keepTokens = Math.max(1, Math.min(KEEP_TOKENS, Math.floor(window * KEEP_SHARE)));
|
|
90
146
|
const cut = findCut(transcript, keepTokens);
|
|
@@ -98,6 +154,15 @@ export async function compact(input) {
|
|
|
98
154
|
entry.turnId === input.turnId &&
|
|
99
155
|
(entry.event.kind === "user-message" || entry.event.kind === "interrupt"));
|
|
100
156
|
const tail = [...request, ...transcript.slice(cut)];
|
|
157
|
+
// The files the summarized part named stay readable by their reference lines (protocol 12).
|
|
158
|
+
const files = [
|
|
159
|
+
...new Set([
|
|
160
|
+
...(previous?.files ?? []),
|
|
161
|
+
...older
|
|
162
|
+
.filter((entry) => !request.includes(entry))
|
|
163
|
+
.flatMap((entry) => filesOf(entry).map(({ line }) => line)),
|
|
164
|
+
]),
|
|
165
|
+
];
|
|
101
166
|
const keptTokens = tail.reduce((sum, entry) => sum + entryTokens(entry), 0);
|
|
102
167
|
const reserve = input.budget?.reserve ?? DEFAULT_RESERVE;
|
|
103
168
|
const maxOutputTokens = Math.max(256, Math.floor(reserve * 0.8));
|
|
@@ -141,6 +206,7 @@ export async function compact(input) {
|
|
|
141
206
|
trigger: input.trigger,
|
|
142
207
|
tokensBefore,
|
|
143
208
|
tokensAfter: keptTokens + Math.ceil(summary.length / CHARS_PER_TOKEN),
|
|
209
|
+
...(files.length > 0 ? { files } : {}),
|
|
144
210
|
};
|
|
145
211
|
return Object.freeze([Object.freeze(entry), ...tail]);
|
|
146
212
|
}
|
|
@@ -151,6 +217,7 @@ export function summaryPrompt(entry) {
|
|
|
151
217
|
"<summary>",
|
|
152
218
|
entry.summary,
|
|
153
219
|
"</summary>",
|
|
220
|
+
...(entry.files?.length ? ["Files in this session:", ...entry.files] : []),
|
|
154
221
|
].join("\n");
|
|
155
222
|
}
|
|
156
223
|
const SYSTEM = [
|
|
@@ -245,7 +312,7 @@ function entryText(entry, clip) {
|
|
|
245
312
|
if (event.kind === "user-message" || event.kind === "interrupt")
|
|
246
313
|
return `[User]: ${"content" in event && event.content
|
|
247
314
|
? event.content
|
|
248
|
-
.map((part) =>
|
|
315
|
+
.map((part) => part.type === "text" ? part.text : mediaReferenceLine(part, "uploaded"))
|
|
249
316
|
.join(" ")
|
|
250
317
|
: (event.text ?? "")}`;
|
|
251
318
|
if (event.kind === "approve")
|
|
@@ -269,7 +336,10 @@ function entryText(entry, clip) {
|
|
|
269
336
|
case "tool-results":
|
|
270
337
|
return entry.results
|
|
271
338
|
.map((result) => result.kind === "completed"
|
|
272
|
-
?
|
|
339
|
+
? [
|
|
340
|
+
`[Tool ${result.toolName} result]: ${clipped(result.output, clip)}`,
|
|
341
|
+
...(result.files ?? []).map((file) => mediaReferenceLine(file, { tool: result.toolName })),
|
|
342
|
+
].join("\n")
|
|
273
343
|
: result.kind === "denied"
|
|
274
344
|
? `[Tool ${result.toolName} denied]: ${result.reason ?? ""}`
|
|
275
345
|
: `[Tool ${result.toolName} failed]: ${result.message}`)
|
package/dist/loop/dispatch.js
CHANGED
|
@@ -70,7 +70,7 @@ export async function dispatchPlan(invocation) {
|
|
|
70
70
|
callId: call.callId,
|
|
71
71
|
invocationId: call.invocationId,
|
|
72
72
|
toolName: call.toolName,
|
|
73
|
-
|
|
73
|
+
partId: definition.owner.partId,
|
|
74
74
|
slot: definition.owner.slot,
|
|
75
75
|
};
|
|
76
76
|
observe({ type: "tool.started", ...eventIds, attributes: { args: call.args } });
|
|
@@ -1,2 +1,8 @@
|
|
|
1
1
|
import type { ModelCall, ModelRequest } from "@nylorun/core/define";
|
|
2
|
+
/**
|
|
3
|
+
* The model call for `request`. Every file in the transcript is its reference line (protocol 12),
|
|
4
|
+
* so a message projects the same in every later call. The files of the turn in progress (its
|
|
5
|
+
* messages, tool results and `read_artifact` loads) also go once, as media, in one user message
|
|
6
|
+
* after the conversation and the context: their bytes reach the model only in their own turn.
|
|
7
|
+
*/
|
|
2
8
|
export declare function projectModelCall(request: ModelRequest): ModelCall;
|