@nylorun/harness 0.16.0-beta → 0.18.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 +30 -0
- package/HOST_CONTRACT.md +9 -5
- package/README.md +26 -6
- package/dist/compatibility.d.ts +1 -1
- package/dist/compatibility.js +1 -1
- package/dist/definition/agent-definition.d.ts +3 -0
- package/dist/definition/agent-definition.js +2 -0
- package/dist/loop/delegation.d.ts +32 -0
- package/dist/loop/delegation.js +136 -0
- package/dist/loop/dispatch.js +56 -0
- package/dist/loop/invocation.d.ts +7 -1
- package/dist/loop/invocation.js +2 -0
- package/dist/loop/run.d.ts +2 -1
- package/dist/loop/run.js +148 -8
- package/dist/loop/state.js +23 -0
- package/dist/loop/step/hooks.d.ts +56 -0
- package/dist/loop/step/hooks.js +191 -0
- package/dist/loop/step/model-configuration.d.ts +5 -0
- package/dist/loop/step/model-configuration.js +14 -1
- package/dist/loop/step/run.d.ts +9 -1
- package/dist/loop/step/run.js +47 -29
- package/dist/loop/step/runtime.d.ts +14 -2
- package/dist/run/durable.d.ts +13 -1
- package/dist/run/durable.js +124 -84
- package/dist/types/client.d.ts +1 -1
- package/dist/types/execution.d.ts +23 -2
- package/dist/utils/ids.d.ts +2 -0
- package/dist/utils/ids.js +5 -0
- package/package.json +2 -2
- package/dist/loop/step/dynamics.d.ts +0 -29
- package/dist/loop/step/dynamics.js +0 -149
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,35 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.18.0-beta
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 1cd7dc7: Add subagents: put an agent in another agent's `tools` (`Agent({ tools: [lookupOrder, researcher] })` or `.use({ tools: [researcher] })`) and the model can delegate to it. The tool is named after the agent's id, takes `{ task: string }`, and its description is the agent's `description`, which is now required for an agent used as a tool. The engine runs the child inside the parent's turn as a durable branch: fresh context, its own tools and hooks served by the root agent's executor, its own MCP servers, the session's sandbox, and only its final output (or `outputSchema` result) returned. Empty output, failures (with partial output marked as evidence), and requests for input or approval inside a child reach the parent as failed tool results. Parallel delegation calls run concurrently, completed child work is never re-run on replay, and cancelling the session cancels every child.
|
|
8
|
+
|
|
9
|
+
v1 is one level deep and non-interactive. Nested delegation, child tools that declare `approval`, and differing sandboxes across the tree fail the build with a named diagnostic. The manifest adds an optional `agent` body on a tool (schema version unchanged), actions and effects carry `agent: { id, path, delegationId }`, tool context gains `ctx.agent`, the durable host resolves a new `delegation` effect kind, and the Runtime emits `delegation.started` / `delegation.completed` events and filters history with `?agent=` (`session.history({ agent })`). Studio shows delegations, labels child actions with their agent, and filters events by agent.
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- Pin core to the tested release.
|
|
14
|
+
- Updated dependencies [1cd7dc7]
|
|
15
|
+
- @nylorun/core@0.4.0-beta
|
|
16
|
+
|
|
17
|
+
## 0.17.0-beta
|
|
18
|
+
|
|
19
|
+
### Minor Changes
|
|
20
|
+
|
|
21
|
+
- b8d822a: Breaking beta: replace `beforeModelCall` / `afterModelCall` with scoped hooks. Register `before("turn" | "step", fn)` and `after("step" | "turn", fn)` on the agent, or `before: { turn, step }` / `after: { step, turn }` on a capability. `before("turn")` runs once per turn and its `Patch` applies to every model call in the turn; the new `after("turn")` returns a `TurnDecision` for the final answer. `after` hooks take one argument and receive `attempt`, and `retry` now retries instead of failing the run. The manifest moves to `manifestSchemaVersion: 4` with `capabilities[].hooks`, and `BeforeModelCallFn`, `AfterModelCallFn` and the `beforeModelCall` / `afterModelCall` action kinds are removed. Every capability registered at a hook point now runs in one `hook` executor action, an expired hook claim is offered again instead of becoming uncertain, and the durable engine version is `hosted-2`. Hook toggles now hide a capability's tools, or one tool of a multi-tool capability, instead of having no effect or failing. Studio lists each capability's hooks with how often they run and labels hook actions. See MIGRATION.md.
|
|
22
|
+
|
|
23
|
+
### Patch Changes
|
|
24
|
+
|
|
25
|
+
- b8d822a: Studio Model Settings lists multiple vault-stored providers, adds credentials through a sheet, and switches the active provider/model via Runtime host vault APIs.
|
|
26
|
+
- Pin core to the tested release.
|
|
27
|
+
- Updated dependencies [b8d822a]
|
|
28
|
+
- Updated dependencies [b8d822a]
|
|
29
|
+
- Updated dependencies [b8d822a]
|
|
30
|
+
- Updated dependencies [b8d822a]
|
|
31
|
+
- @nylorun/core@0.3.0-beta
|
|
32
|
+
|
|
3
33
|
## 0.16.0-beta
|
|
4
34
|
|
|
5
35
|
### Minor Changes
|
package/HOST_CONTRACT.md
CHANGED
|
@@ -1,18 +1,20 @@
|
|
|
1
1
|
# Durable execution and session protocol — beta freeze
|
|
2
2
|
|
|
3
|
-
Artifact: `@nylorun/harness@0.14.0-beta.3`. Package version is separate from protocol 1, definition schema
|
|
3
|
+
Artifact: `@nylorun/harness@0.14.0-beta.3`. Package version is separate from protocol 1, definition schema 4, durable checkpoint 1 / engine `hosted-2`, and inner execution checkpoint 1. Public execution API and shared contracts are the compatibility boundary. Cloud installs published npm packages and does not import the OSS Runtime.
|
|
4
4
|
|
|
5
5
|
## HTTP (both hosts)
|
|
6
6
|
|
|
7
|
-
Bearer application credentials: `PUT /v1/agents/:agentId` (`PutAgentRequest`: requestId, complete manifest, implementationVersion, optional pluginRoots); `PUT /v1/sessions/:sessionId` (`PutSessionRequest`: requestId, agentId, trusted ownerUserId, optional info, optional vaultIds, optional credentialSelections); `GET /v1/sessions/:sessionId`; `POST /v1/sessions/:sessionId/commands`; `GET /v1/sessions/:sessionId/items?cursor=...`; `GET /v1/sessions/:sessionId/events?cursor=...` (SSE, Last-Event-ID also accepted); vault administration `POST/GET/DELETE /v1/vaults` and `/v1/vaults/:vaultId/credentials`. Commands use `SessionCommandSchema`. Vault creates and credential rotations use `idempotencyKey`; requestId is excluded from comparison; the same key and body replay the stored metadata response; a changed body is 409. Credential responses omit secret values. `GET /v1/vaults?ownerUserId=` lists that user's vaults. A session attaches only vaults with the same ownerUserId. A later session PUT may replace vaultIds and credentialSelections; agentId, ownerUserId, and info stay the creation identity. GET session returns id, agentId, ownerUserId, status, activeTurnId, vaultIds, credentialSelections, mcpSnapshot, mcpDiagnostics, plus inspectable waits/uncertainty as available. mcpSnapshot is null until the first turn discovers MCP tools; it is then pinned for the session and contains no secrets. pluginRoots are stored beside the agent definition and are not part of the manifest hash. History returns `{items: LiveEvent[], cursor: string|null}`; empty history cursor is null. Executor credentials cannot call vault routes.
|
|
7
|
+
Bearer application credentials: `PUT /v1/agents/:agentId` (`PutAgentRequest`: requestId, complete manifest, implementationVersion, optional pluginRoots); `PUT /v1/sessions/:sessionId` (`PutSessionRequest`: requestId, agentId, trusted ownerUserId, optional info, optional vaultIds, optional credentialSelections); `GET /v1/sessions/:sessionId`; `POST /v1/sessions/:sessionId/commands`; `GET /v1/sessions/:sessionId/items?cursor=...`; `GET /v1/sessions/:sessionId/events?cursor=...` (SSE, Last-Event-ID also accepted); vault administration `POST/GET/DELETE /v1/vaults` and `/v1/vaults/:vaultId/credentials`. Commands use `SessionCommandSchema`. Vault creates and credential rotations use `idempotencyKey`; requestId is excluded from comparison; the same key and body replay the stored metadata response; a changed body is 409. Credential responses omit secret values. `GET /v1/vaults?ownerUserId=` lists that user's vaults. A session attaches only vaults with the same ownerUserId. User vaults cannot see or attach the host vault. `GET /v1/host/model` returns `{configured:false}` or the active provider, model, authType, and optional baseUrl, never the secret. `PUT /v1/host/model` upserts a host provider credential and makes it active (idempotencyKey, requestId excluded from comparison). `PUT /v1/host/model/selection` switches the active provider/model among configured credentials without a new secret. `GET /v1/host/providers` lists configured providers with name, model, authType, lastUpdated, and active. `GET /v1/host/models` returns the public provider catalog. Executor credentials cannot call host model routes. A later session PUT may replace vaultIds and credentialSelections; agentId, ownerUserId, and info stay the creation identity. GET session returns id, agentId, ownerUserId, status, activeTurnId, vaultIds, credentialSelections, mcpSnapshot, mcpDiagnostics, plus inspectable waits/uncertainty as available. mcpSnapshot is null until the first turn discovers MCP tools; it is then pinned for the session and contains no secrets. pluginRoots are stored beside the agent definition and are not part of the manifest hash. History returns `{items: LiveEvent[], cursor: string|null}`; empty history cursor is null. `PUT /v1/executors` (`RegisterExecutorsRequest`: executors of agentId, implementationVersion, optional manifestHash, token of at least 16 characters) registers or rotates executor credentials on a running host and returns `{executors: [{agentId, implementationVersion, rotated}]}`. A token equal to the application credential, or duplicated within a request or across agents, is rejected. Registration is all-or-nothing and is persisted; an unchanged registration is idempotent and keeps open streams; a rotation ends the replaced token's streams and the replaced token stops authorizing. `DELETE /v1/executors/:agentId` removes a registration; an executor supplied to the process at startup is 409. `GET /v1/executors` lists agentId, implementationVersion, optional manifestHash, connected, and updatedAt, never tokens. Executor credentials cannot call vault routes, host model routes, or executor registration routes.
|
|
8
8
|
|
|
9
|
-
Separate scoped executor bearer credentials: `GET /v1/executors/connect` emits `event: work_available` / `data: {"type":"work_available"}` after connection and committed work; `GET /v1/actions` returns `{actions: Action[]}`; `POST /v1/actions/:actionId/claim` uses ActionClaimRequest; `POST /v1/actions/:actionId/heartbeat` uses ActionHeartbeatRequest and returns leaseExpiresAt. Claim returns ActionClaim. Action result is the `action_result` session command with executor authorization, never observer authorization. Claim identity is server-generated and generation monotonically increases. Credentials authorize an executor by agentId. A manifestHash stored on an existing token is ignored, and claim requests do not send one. In-flight actions for that agent stay claimable after the registered digest changes. Clients cannot broaden their agent scope. Subscribe before discovery; rediscover after reconnect; notifications never authorize execution.
|
|
9
|
+
Separate scoped executor bearer credentials: `GET /v1/executors/connect` emits `event: work_available` / `data: {"type":"work_available"}` after connection and committed work; `GET /v1/actions` returns `{actions: Action[]}`; `POST /v1/actions/:actionId/claim` uses ActionClaimRequest; `POST /v1/actions/:actionId/heartbeat` uses ActionHeartbeatRequest and returns leaseExpiresAt. Claim returns ActionClaim. Action result is the `action_result` session command with executor authorization, never observer authorization. Claim identity is server-generated and generation monotonically increases. Credentials authorize an executor by agentId. A manifestHash stored on an existing token is ignored, and claim requests do not send one. In-flight actions for that agent stay claimable after the registered digest changes. Clients cannot broaden their agent scope. Credentials are provisioned either to the process at startup or through `PUT /v1/executors`; startup-provided scopes apply to that process only, take precedence for their agentId, and are never persisted. Subscribe before discovery; rediscover after reconnect; notifications never authorize execution.
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
Unauthenticated `GET /health` returns status, service, and, on hosts that publish them, version, a non-reversible scopeId digest of the database path, and pid. Clients treat these three as optional so an older host still parses.
|
|
12
|
+
|
|
13
|
+
All command idempotency keys bind to canonical request content within a session; requestId is transport metadata and is excluded from content comparison; exact semantic duplicates return the stored original response; changed content conflicts (409). A completed action's matching claim/generation/outcome returns its original receipt even after expiry. Conflicting duplicates and any other stale/expired claim are rejected. Heartbeat cannot resurrect an expired claim. Expired in-flight tool work is uncertain, not automatically reoffered. An expired `hook` action returns to pending and is offered again, because hooks are pure by contract; the next claim's generation fences the earlier one. Results after cancellation cannot resume a turn. Application observers cannot claim or submit action results. No hardcoded production credentials.
|
|
12
14
|
|
|
13
15
|
## Engine host
|
|
14
16
|
|
|
15
|
-
`createDurableCheckpoint({manifest,sessionId,turnId,input,state?,info?,segment?})`, `runDurable({manifest,checkpoint,host,signal?,sessionTools?})` from `/run`. `DurableHost.resolveEffect(HostEffect)` atomically creates or reads an individually identified effect and returns `{status:'completed',outcome:{value,statePatch?}}` or `{status:'pending'|'uncertain'}`. Model effect `input` is the complete ModelCall (instructions/history/tools/output schema); context contains a JSON projection of ModelRequest and invocationId. Its completed value is a ModelCandidate or string. Runtime provider code owns credentials and invocation.
|
|
17
|
+
`createDurableCheckpoint({manifest,sessionId,turnId,input,state?,info?,segment?})`, `runDurable({manifest,checkpoint,host,signal?,sessionTools?})` from `/run`. `DurableHost.resolveEffect(HostEffect)` atomically creates or reads an individually identified effect and returns `{status:'completed',outcome:{value,statePatch?}}` or `{status:'pending'|'uncertain'}`. Model effect `input` is the complete ModelCall (instructions/history/tools/output schema); context contains a JSON projection of ModelRequest and invocationId. Its completed value is a ModelCandidate or string. Runtime provider code owns credentials and invocation. Tool effects have capabilityId, toolName, serialized input and context. Tool result value is a ToolOutcome or a plain tool output; statePatch contains changed session keys. A `hook` effect runs one hook point for every capability that registered it: `hook` is `{at: "before"|"after", scope: "turn"|"step", capabilityIds}` in manifest order, and its effect id ends in a stable name (`before-turn`, `before-step:<stepId>`, `after-step:<stepId>`, `after-turn:<stepId>`). Its completed value is `{results: {[capabilityId]: Patch | Decision | TurnDecision}}`. `before-turn` is issued only in a turn's first segment. Tool context includes invocationId, resume, state, info and stable idempotencyKey. Customer implementationVersion is pinned by the runtime outside durable checkpoints.
|
|
16
18
|
|
|
17
19
|
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.
|
|
18
20
|
|
|
@@ -20,6 +22,8 @@ A terminal/paused result includes `result.state`. Save it. A new message uses a
|
|
|
20
22
|
|
|
21
23
|
Host resolveEffect must bind the effect ID to the original request and reject drift. Intent/outcome, action transitions, checkpoint settlement and canonical event/outbox writes must use runtime transactions. Restate journals individual effect boundaries, not the loop. Scheduling, storage, publication, lease policy and reconciliation remain runtime-owned.
|
|
22
24
|
|
|
25
|
+
Agents used as tools: a manifest tool with an `agent` body (the child manifest inlined; name equals the child id, description equals the child description, input is the standard `{task}` schema, no outputSchema, no nested agent tools, identical sandbox specs across the tree) is run by the engine inside the parent's `runDurable`, never by an executor. Its model, tool and hook effects carry `agent: {id, path, delegationId}` (`delegationId` is the parent tool call's invocationId), keep the root `agentId` and `manifestHash`, and use identity `<delegationId>/<inner identity>`; tool context `idempotencyKey` is prefixed the same way. Hosts resolve child effects against the child manifest (`delegateManifest`) for pinned tool schemas, sandbox and MCP routing, copy `agent` onto the Action, and include it in action event payloads. A `delegation` effect (identity `<delegationId>:started` or `<delegationId>:settled`, input `{task}` or `{status, outcome}`) must be recorded completed immediately with value null and publish `delegation.started` / `delegation.completed` exactly once; the journal makes replays silent. `DurableSessionTool.agentId` attaches discovered MCP tools to a child; MCP snapshot records and diagnostics carry `agentId`, and child plugin roots are keyed `<childId>/<capabilityId>`. Children share the session sandbox. `GET /v1/sessions/:id/items?agent=` filters history by `payload.agent.delegationId` or `payload.agent.path`. Existing checkpoints are unaffected; engine version stays `hosted-2`.
|
|
26
|
+
|
|
23
27
|
## Definitions, validation, compatibility
|
|
24
28
|
|
|
25
29
|
`/define` is execution-free and browser-bundleable; Agent has no `.run()`. Explicit local execution uses `/run` run + bindingFromAgent(agent.build()). `/contracts` never imports checkpoint internals. Tools and before/after hooks are supported remotely. Arbitrary legacy middleware closures are rejected for durable definitions because they cannot be reconstructed from manifests. JSON schemas are reconstructed through Zod's JSON Schema importer; unsupported schemas fail closed. The original manifest document must survive reconstruction. Runtime is the only hasher: it hashes the accepted manifest and pins that digest on the session and on each action. Agents do not hash. Model configuration is host-owned. The executor claims by agent id. Runtime checks a successful tool result against the output schema copied onto the action and stores a schema mismatch as a failed outcome on a completed action.
|
package/README.md
CHANGED
|
@@ -35,8 +35,8 @@ export const supportAgent = Agent({
|
|
|
35
35
|
instructions: "You help customers with orders. Be brief.",
|
|
36
36
|
tools: [lookup],
|
|
37
37
|
})
|
|
38
|
-
.use(capability({ id: "policy",
|
|
39
|
-
.
|
|
38
|
+
.use(capability({ id: "policy", after: { step: ({ text }) => ({}) } }))
|
|
39
|
+
.before("turn", ({ info }) => ({ instructions: [`Tenant ${info?.tenantId}`] }));
|
|
40
40
|
|
|
41
41
|
// Optional: .build() is a no-op facade
|
|
42
42
|
const agent = supportAgent.build();
|
|
@@ -76,11 +76,31 @@ Prefer `input` / `output` / `run`. Legacy `inputSchema` / `execute` and tagged `
|
|
|
76
76
|
|
|
77
77
|
Definitions must not import `@nylorun/runtime`.
|
|
78
78
|
|
|
79
|
-
##
|
|
79
|
+
## Hooks
|
|
80
80
|
|
|
81
|
-
`
|
|
82
|
-
`
|
|
83
|
-
|
|
81
|
+
Register a hook with `before(scope, fn)` / `after(scope, fn)` on the agent, or
|
|
82
|
+
`before: { turn, step }` / `after: { step, turn }` on a capability. The scope says how
|
|
83
|
+
often your code runs:
|
|
84
|
+
|
|
85
|
+
| Hook | Runs | Returns |
|
|
86
|
+
| ---------------- | -------------------------------------------- | -------------------------------------------------- |
|
|
87
|
+
| `before("turn")` | Once per turn, before the first model call | `Patch`, applied to every model call in the turn |
|
|
88
|
+
| `before("step")` | Before every model call | `Patch` for that call, layered over the turn patch |
|
|
89
|
+
| `after("step")` | After every model response, before tools run | `Decision` (text/deny/approve/retry/block) |
|
|
90
|
+
| `after("turn")` | Once, on the final answer | `TurnDecision` (text or output/retry/block) |
|
|
91
|
+
|
|
92
|
+
`Patch` is capabilities/tools/instructions/state/block, with no `model`. Registered
|
|
93
|
+
hooks are listed in the manifest (`capabilities[].hooks`). In a Runtime each hook point
|
|
94
|
+
is one network round trip to your executor per turn or per model call, whatever the
|
|
95
|
+
number of capabilities using it, so prefer `"turn"` when a decision does not change
|
|
96
|
+
within a turn.
|
|
97
|
+
|
|
98
|
+
Hooks may run more than once when a delivery is retried, so keep side effects in
|
|
99
|
+
tools. `retry` is never capped by the engine: every `after` hook receives `attempt`,
|
|
100
|
+
so bound it yourself, for example
|
|
101
|
+
`attempt < 2 ? { retry: "Be specific" } : { block: "No usable answer" }`.
|
|
102
|
+
|
|
103
|
+
Local explicit engine execution retains middleware. Durable manifests reject arbitrary middleware closures; use hooks.
|
|
84
104
|
|
|
85
105
|
## Checkpoint / durability
|
|
86
106
|
|
package/dist/compatibility.d.ts
CHANGED
package/dist/compatibility.js
CHANGED
|
@@ -3,6 +3,7 @@ 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
|
+
import { type HookRunner } from "../loop/step/hooks.js";
|
|
6
7
|
export interface AgentDefinition {
|
|
7
8
|
readonly id: string;
|
|
8
9
|
readonly middleware: readonly BoundMiddleware[];
|
|
@@ -11,6 +12,8 @@ export interface AgentDefinition {
|
|
|
11
12
|
readonly manifest: AgentManifest;
|
|
12
13
|
readonly hash: string;
|
|
13
14
|
readonly implementations: Implementations;
|
|
15
|
+
/** Runs one hook point. In-process by default; the durable host journals it as one effect. */
|
|
16
|
+
readonly runHooks: HookRunner;
|
|
14
17
|
}
|
|
15
18
|
export type { Implementations };
|
|
16
19
|
import type { AgentBinding } from "@nylorun/core/define";
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { localHookRunner } from "../loop/step/hooks.js";
|
|
1
2
|
import { bindingFromAgent, bindOutputContract } from "@nylorun/core/define";
|
|
2
3
|
import { ToolRegistry as Registry } from "./registry.js";
|
|
3
4
|
import { hashManifest } from "@nylorun/core/compatibility";
|
|
@@ -11,6 +12,7 @@ export function definitionFromBinding(binding) {
|
|
|
11
12
|
hash: hashManifest(binding.manifest),
|
|
12
13
|
middleware: binding.declarations,
|
|
13
14
|
implementations: binding.implementations,
|
|
15
|
+
runHooks: localHookRunner(binding.implementations),
|
|
14
16
|
registry: new Registry(binding.declarations, binding.tools),
|
|
15
17
|
...(binding.outputSchema ? { output: bindOutputContract(binding.outputSchema) } : {}),
|
|
16
18
|
});
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { AgentRef, Delegate, JsonObject, JsonValue, ModelAdapter, ToolOutcome } from "@nylorun/core/define";
|
|
2
|
+
import type { AgentDefinition } from "../definition/agent-definition.js";
|
|
3
|
+
import type { RunOptions, RunResult } from "../types/execution.js";
|
|
4
|
+
import type { Invocation } from "./invocation.js";
|
|
5
|
+
/** How one agent used as a tool is built and journaled. Durable hosts supply their own. */
|
|
6
|
+
export interface DelegationHost {
|
|
7
|
+
child(delegate: Delegate, ref: AgentRef): {
|
|
8
|
+
readonly definition: AgentDefinition;
|
|
9
|
+
readonly onModelCall: ModelAdapter;
|
|
10
|
+
};
|
|
11
|
+
/** Journal a lifecycle point exactly once. Local runs have nothing to journal. */
|
|
12
|
+
announce?(phase: "started" | "settled", ref: AgentRef, payload: JsonObject): Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
/** Engine-internal options for execute(); not part of the public RunOptions. */
|
|
15
|
+
export interface ExecuteInternals {
|
|
16
|
+
readonly delegation?: DelegationHost;
|
|
17
|
+
/** Set when this invocation is an agent used as a tool. */
|
|
18
|
+
readonly delegated?: AgentRef;
|
|
19
|
+
}
|
|
20
|
+
/** Codes are curated: a child's provider error bodies never reach the parent's context. */
|
|
21
|
+
export declare const INTERACTION_UNSUPPORTED = "Agents used as tools can't ask for input, approval or a wait yet; do this work on the parent agent.";
|
|
22
|
+
/** In-process children, built from the authored agent and sharing the parent's model callable. */
|
|
23
|
+
export declare function localDelegation(onModelCall: ModelAdapter): DelegationHost;
|
|
24
|
+
/** Run one agent used as a tool to settlement. Only its final output returns to the parent. */
|
|
25
|
+
export declare function runDelegation(invocation: Invocation, execute: (agent: AgentDefinition, options: RunOptions<any>, internals: ExecuteInternals) => Promise<RunResult<JsonValue>>, call: {
|
|
26
|
+
readonly turnId: string;
|
|
27
|
+
readonly stepId: string;
|
|
28
|
+
readonly callId: string;
|
|
29
|
+
readonly invocationId: string;
|
|
30
|
+
readonly toolName: string;
|
|
31
|
+
readonly args: JsonValue;
|
|
32
|
+
}, delegate: Delegate): Promise<ToolOutcome>;
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { HarnessError, isHarnessError } from "@nylorun/core/define";
|
|
2
|
+
import { definitionFromBinding } from "../definition/agent-definition.js";
|
|
3
|
+
import { withNestedIds } from "../utils/ids.js";
|
|
4
|
+
import { initializeExecutionState } from "./initial-state.js";
|
|
5
|
+
import { textFromOutput } from "./model/normalize.js";
|
|
6
|
+
import { HostSuspension } from "./host-suspension.js";
|
|
7
|
+
/** Codes are curated: a child's provider error bodies never reach the parent's context. */
|
|
8
|
+
export const INTERACTION_UNSUPPORTED = "Agents used as tools can't ask for input, approval or a wait yet; do this work on the parent agent.";
|
|
9
|
+
const PARTIAL_LIMIT = 4_000;
|
|
10
|
+
/** In-process children, built from the authored agent and sharing the parent's model callable. */
|
|
11
|
+
export function localDelegation(onModelCall) {
|
|
12
|
+
return {
|
|
13
|
+
child(delegate, ref) {
|
|
14
|
+
if (!delegate.agent)
|
|
15
|
+
throw new HarnessError("execution.invalid-input", `Agent '${ref.id}' is used as a tool but has no local implementation; build the parent from authored agents`);
|
|
16
|
+
return { definition: definitionFromBinding(delegate.agent.getBinding()), onModelCall };
|
|
17
|
+
},
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
/** Run one agent used as a tool to settlement. Only its final output returns to the parent. */
|
|
21
|
+
export async function runDelegation(invocation, execute, call, delegate) {
|
|
22
|
+
const { signal, options } = invocation;
|
|
23
|
+
const ref = {
|
|
24
|
+
id: delegate.manifest.id,
|
|
25
|
+
path: `${invocation.agent.id}/${delegate.manifest.id}`,
|
|
26
|
+
delegationId: call.invocationId,
|
|
27
|
+
};
|
|
28
|
+
const ids = {
|
|
29
|
+
turnId: call.turnId,
|
|
30
|
+
stepId: call.stepId,
|
|
31
|
+
callId: call.callId,
|
|
32
|
+
invocationId: call.invocationId,
|
|
33
|
+
toolName: call.toolName,
|
|
34
|
+
agent: ref,
|
|
35
|
+
};
|
|
36
|
+
const task = call.args.task;
|
|
37
|
+
const host = invocation.delegation ?? localDelegation(options.onModelCall);
|
|
38
|
+
await host.announce?.("started", ref, { task });
|
|
39
|
+
invocation.observe({ type: "delegation.started", ...ids, attributes: { task } });
|
|
40
|
+
let outcome;
|
|
41
|
+
let status = "failed";
|
|
42
|
+
try {
|
|
43
|
+
const child = host.child(delegate, ref);
|
|
44
|
+
const listener = options.onEvent;
|
|
45
|
+
const result = await withNestedIds(call.invocationId, () => execute(child.definition, {
|
|
46
|
+
input: task,
|
|
47
|
+
onModelCall: child.onModelCall,
|
|
48
|
+
signal,
|
|
49
|
+
...(options.info === undefined ? {} : { info: options.info }),
|
|
50
|
+
state: initializeExecutionState(child.definition, {
|
|
51
|
+
executionId: `${invocation.state.executionId}/${call.invocationId}`,
|
|
52
|
+
}),
|
|
53
|
+
...(listener ? { onEvent: (event) => listener({ ...event, agent: ref }) } : {}),
|
|
54
|
+
}, { delegated: ref }));
|
|
55
|
+
status = result.status;
|
|
56
|
+
outcome = settle(result);
|
|
57
|
+
}
|
|
58
|
+
catch (cause) {
|
|
59
|
+
// Durable hosts suspend children mid-flight; that must escape to the parent journal.
|
|
60
|
+
if (cause instanceof HostSuspension)
|
|
61
|
+
throw cause;
|
|
62
|
+
// Construction or setup failures still settle the journaled delegation; the parent
|
|
63
|
+
// sees the same failed tool result as an empty or crashed child.
|
|
64
|
+
if (isHarnessError(cause))
|
|
65
|
+
outcome = { kind: "failed", code: cause.code, message: cause.message };
|
|
66
|
+
else if (cause instanceof Error)
|
|
67
|
+
outcome = { kind: "failed", code: "delegation.failed", message: cause.message };
|
|
68
|
+
else
|
|
69
|
+
outcome = { kind: "failed", code: "delegation.failed", message: String(cause) };
|
|
70
|
+
}
|
|
71
|
+
await host.announce?.("settled", ref, {
|
|
72
|
+
status,
|
|
73
|
+
outcome: outcome,
|
|
74
|
+
});
|
|
75
|
+
invocation.observe({
|
|
76
|
+
type: "delegation.completed",
|
|
77
|
+
...ids,
|
|
78
|
+
status,
|
|
79
|
+
attributes: outcome.kind === "completed"
|
|
80
|
+
? {
|
|
81
|
+
callId: call.callId,
|
|
82
|
+
toolName: call.toolName,
|
|
83
|
+
kind: "completed",
|
|
84
|
+
output: outcome.output,
|
|
85
|
+
}
|
|
86
|
+
: {
|
|
87
|
+
callId: call.callId,
|
|
88
|
+
toolName: call.toolName,
|
|
89
|
+
kind: "failed",
|
|
90
|
+
code: outcome.code,
|
|
91
|
+
message: outcome.message,
|
|
92
|
+
},
|
|
93
|
+
});
|
|
94
|
+
return outcome;
|
|
95
|
+
}
|
|
96
|
+
/** "Done" means settled with real output; empty or unfinished work is a failure with evidence. */
|
|
97
|
+
function settle(result) {
|
|
98
|
+
if (result.status === "completed") {
|
|
99
|
+
const output = result.output;
|
|
100
|
+
if (output === null || (typeof output === "string" && output.trim() === ""))
|
|
101
|
+
return {
|
|
102
|
+
kind: "failed",
|
|
103
|
+
code: "delegation.empty-output",
|
|
104
|
+
message: "The agent finished without an answer.",
|
|
105
|
+
};
|
|
106
|
+
return { kind: "completed", output };
|
|
107
|
+
}
|
|
108
|
+
if (result.status === "cancelled")
|
|
109
|
+
return { kind: "failed", code: "tool.cancelled", message: "The agent was cancelled." };
|
|
110
|
+
if (result.status === "paused")
|
|
111
|
+
return {
|
|
112
|
+
kind: "failed",
|
|
113
|
+
code: "delegation.interaction-unsupported",
|
|
114
|
+
message: INTERACTION_UNSUPPORTED,
|
|
115
|
+
};
|
|
116
|
+
const reason = result.error.code;
|
|
117
|
+
const curated = reason.startsWith("execution.") ? reason : `${reason}: ${result.error.message}`;
|
|
118
|
+
const partial = lastText(result);
|
|
119
|
+
return {
|
|
120
|
+
kind: "failed",
|
|
121
|
+
code: "delegation.failed",
|
|
122
|
+
message: `The agent failed (${curated}).` +
|
|
123
|
+
(partial ? `\nPartial output (evidence, not an answer):\n${partial}` : ""),
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
function lastText(result) {
|
|
127
|
+
for (let index = result.state.transcript.length - 1; index >= 0; index--) {
|
|
128
|
+
const entry = result.state.transcript[index];
|
|
129
|
+
if (entry.kind !== "candidate")
|
|
130
|
+
continue;
|
|
131
|
+
const text = textFromOutput(entry.candidate.output).trim();
|
|
132
|
+
if (text)
|
|
133
|
+
return text.length > PARTIAL_LIMIT ? `${text.slice(0, PARTIAL_LIMIT)}…` : text;
|
|
134
|
+
}
|
|
135
|
+
return undefined;
|
|
136
|
+
}
|
package/dist/loop/dispatch.js
CHANGED
|
@@ -6,9 +6,25 @@ import { copyJson } from "@nylorun/core/define";
|
|
|
6
6
|
import { createSessionStateBag } from "./initial-state.js";
|
|
7
7
|
import { toolResult } from "./tool-result.js";
|
|
8
8
|
import { isWaitSignal, WaitSignal } from "./waits.js";
|
|
9
|
+
import { INTERACTION_UNSUPPORTED, runDelegation } from "./delegation.js";
|
|
10
|
+
import { execute } from "./run.js";
|
|
9
11
|
export async function dispatchPlan(invocation) {
|
|
10
12
|
const { signal, definitions, options, observe, record } = invocation;
|
|
11
13
|
let plan = invocation.state.plan;
|
|
14
|
+
if (invocation.delegated && plan.calls.some((call) => call.status === "interaction")) {
|
|
15
|
+
// Agents used as tools can't pause; the model sees why and can continue without the call.
|
|
16
|
+
plan = {
|
|
17
|
+
...plan,
|
|
18
|
+
calls: plan.calls.map((call) => call.status === "interaction"
|
|
19
|
+
? copyJson({
|
|
20
|
+
...call,
|
|
21
|
+
status: "settled",
|
|
22
|
+
result: unsupported(call.callId, call.toolName),
|
|
23
|
+
})
|
|
24
|
+
: call),
|
|
25
|
+
};
|
|
26
|
+
invocation.state = { ...invocation.state, plan };
|
|
27
|
+
}
|
|
12
28
|
if (plan.calls.some((call) => call.status === "interaction" && call.interactionPhase === "before")) {
|
|
13
29
|
for (const call of plan.calls)
|
|
14
30
|
if (call.status === "interaction")
|
|
@@ -61,6 +77,16 @@ export async function dispatchPlan(invocation) {
|
|
|
61
77
|
let outcome;
|
|
62
78
|
try {
|
|
63
79
|
signal.throwIfAborted();
|
|
80
|
+
if (definition.delegate) {
|
|
81
|
+
const result = toolResult(call, definition, await runDelegation(invocation, execute, { ...eventIds, args: call.args }, definition.delegate));
|
|
82
|
+
observe({
|
|
83
|
+
type: "tool.completed",
|
|
84
|
+
...eventIds,
|
|
85
|
+
outcome: result.kind,
|
|
86
|
+
attributes: result,
|
|
87
|
+
});
|
|
88
|
+
return copyJson({ ...call, status: "settled", result });
|
|
89
|
+
}
|
|
64
90
|
if (definition.approval && !call.resume) {
|
|
65
91
|
const decision = await definition.approval(call.args);
|
|
66
92
|
const prompt = typeof decision === "string"
|
|
@@ -101,6 +127,10 @@ export async function dispatchPlan(invocation) {
|
|
|
101
127
|
...(redelivering || call.status === "active" ? { redelivery: true } : {}),
|
|
102
128
|
state: stateApi,
|
|
103
129
|
session: { id: invocation.state.executionId },
|
|
130
|
+
agent: invocation.delegated ?? {
|
|
131
|
+
id: invocation.agent.id,
|
|
132
|
+
path: invocation.agent.id,
|
|
133
|
+
},
|
|
104
134
|
progress(message, data) {
|
|
105
135
|
observe({
|
|
106
136
|
type: "tool.progress",
|
|
@@ -161,6 +191,13 @@ export async function dispatchPlan(invocation) {
|
|
|
161
191
|
outcome = normalizeOutcome(raw);
|
|
162
192
|
if (!outcome || typeof outcome !== "object")
|
|
163
193
|
throw new HarnessError("tool.invalid-tool-result", "Tool returned an invalid outcome");
|
|
194
|
+
if (invocation.delegated &&
|
|
195
|
+
(outcome.kind === "interaction-required" || outcome.kind === "deferred"))
|
|
196
|
+
outcome = {
|
|
197
|
+
kind: "failed",
|
|
198
|
+
code: "delegation.interaction-unsupported",
|
|
199
|
+
message: INTERACTION_UNSUPPORTED,
|
|
200
|
+
};
|
|
164
201
|
if (outcome.kind === "interaction-required") {
|
|
165
202
|
if (!["approval", "response"].includes(outcome.interaction.kind) ||
|
|
166
203
|
typeof outcome.interaction.prompt !== "string")
|
|
@@ -200,6 +237,16 @@ export async function dispatchPlan(invocation) {
|
|
|
200
237
|
catch (cause) {
|
|
201
238
|
if (cause instanceof HostSuspension)
|
|
202
239
|
throw cause;
|
|
240
|
+
if (isWaitSignal(cause) && invocation.delegated) {
|
|
241
|
+
const result = unsupported(call.callId, call.toolName);
|
|
242
|
+
observe({
|
|
243
|
+
type: "tool.completed",
|
|
244
|
+
...eventIds,
|
|
245
|
+
outcome: result.kind,
|
|
246
|
+
attributes: result,
|
|
247
|
+
});
|
|
248
|
+
return copyJson({ ...call, status: "settled", result });
|
|
249
|
+
}
|
|
203
250
|
if (isWaitSignal(cause)) {
|
|
204
251
|
if (cause.outcome.kind === "interaction-required") {
|
|
205
252
|
return copyJson({
|
|
@@ -305,6 +352,15 @@ export async function dispatchPlan(invocation) {
|
|
|
305
352
|
};
|
|
306
353
|
await record();
|
|
307
354
|
}
|
|
355
|
+
function unsupported(callId, toolName) {
|
|
356
|
+
return {
|
|
357
|
+
callId,
|
|
358
|
+
toolName,
|
|
359
|
+
kind: "failed",
|
|
360
|
+
code: "delegation.interaction-unsupported",
|
|
361
|
+
message: INTERACTION_UNSUPPORTED,
|
|
362
|
+
};
|
|
363
|
+
}
|
|
308
364
|
function normalizeOutcome(raw) {
|
|
309
365
|
if (raw && typeof raw === "object" && "kind" in raw) {
|
|
310
366
|
const kind = raw.kind;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { AgentDefinition } from "../definition/agent-definition.js";
|
|
2
|
-
import type { BoundToolDefinition } from "@nylorun/core/define";
|
|
2
|
+
import type { AgentRef, BoundToolDefinition } from "@nylorun/core/define";
|
|
3
|
+
import type { DelegationHost, ExecuteInternals } from "./delegation.js";
|
|
3
4
|
import type { ExecutionState, RunOptions } from "../types/execution.js";
|
|
4
5
|
import type { ObserveEvent } from "@nylorun/core/define";
|
|
5
6
|
import type { JsonValue } from "@nylorun/core/define";
|
|
@@ -9,6 +10,10 @@ export interface Invocation {
|
|
|
9
10
|
readonly options: RunOptions<any>;
|
|
10
11
|
readonly signal: AbortSignal;
|
|
11
12
|
readonly definitions: Map<string, BoundToolDefinition>;
|
|
13
|
+
/** Builds agents used as tools; absent means in-process children. */
|
|
14
|
+
readonly delegation?: DelegationHost;
|
|
15
|
+
/** Set when this invocation is itself an agent used as a tool. */
|
|
16
|
+
readonly delegated?: AgentRef;
|
|
12
17
|
state: ExecutionState;
|
|
13
18
|
/** Mutable durable session memory for this invocation. */
|
|
14
19
|
sessionBag: Record<string, JsonValue>;
|
|
@@ -21,4 +26,5 @@ export declare function createInvocation(input: {
|
|
|
21
26
|
readonly options: RunOptions<any>;
|
|
22
27
|
readonly state: ExecutionState;
|
|
23
28
|
readonly definitions: Map<string, BoundToolDefinition>;
|
|
29
|
+
readonly internals?: ExecuteInternals;
|
|
24
30
|
}): Invocation;
|
package/dist/loop/invocation.js
CHANGED
|
@@ -8,6 +8,8 @@ export function createInvocation(input) {
|
|
|
8
8
|
options: input.options,
|
|
9
9
|
signal: input.options.signal ?? new AbortController().signal,
|
|
10
10
|
definitions: input.definitions,
|
|
11
|
+
...(input.internals?.delegation ? { delegation: input.internals.delegation } : {}),
|
|
12
|
+
...(input.internals?.delegated ? { delegated: input.internals.delegated } : {}),
|
|
11
13
|
state: input.state,
|
|
12
14
|
sessionBag: { ...(input.state.state ?? {}) },
|
|
13
15
|
};
|
package/dist/loop/run.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { AgentDefinition } from "../definition/agent-definition.js";
|
|
2
2
|
import type { RunOptions, RunResult } from "../types/execution.js";
|
|
3
3
|
import type { JsonValue } from "@nylorun/core/define";
|
|
4
|
+
import type { ExecuteInternals } from "./delegation.js";
|
|
4
5
|
/** All mutable progress belongs to this invocation and is discarded when it settles. */
|
|
5
|
-
export declare function execute(agent: AgentDefinition, options: RunOptions<any
|
|
6
|
+
export declare function execute(agent: AgentDefinition, options: RunOptions<any>, internals?: ExecuteInternals): Promise<RunResult<JsonValue>>;
|