@nylorun/harness 0.16.0-beta → 0.17.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 +16 -0
- package/HOST_CONTRACT.md +7 -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/run.js +146 -6
- 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 +8 -1
- package/dist/run/durable.js +31 -19
- package/dist/types/client.d.ts +1 -1
- package/dist/types/execution.d.ts +20 -1
- 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,21 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.17.0-beta
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 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.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- 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.
|
|
12
|
+
- Pin core to the tested release.
|
|
13
|
+
- Updated dependencies [b8d822a]
|
|
14
|
+
- Updated dependencies [b8d822a]
|
|
15
|
+
- Updated dependencies [b8d822a]
|
|
16
|
+
- Updated dependencies [b8d822a]
|
|
17
|
+
- @nylorun/core@0.3.0-beta
|
|
18
|
+
|
|
3
19
|
## 0.16.0-beta
|
|
4
20
|
|
|
5
21
|
### 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
|
|
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
|
});
|
package/dist/loop/run.js
CHANGED
|
@@ -2,10 +2,12 @@ import { HostSuspension } from "./host-suspension.js";
|
|
|
2
2
|
import { HarnessError, isHarnessError } from "@nylorun/core/define";
|
|
3
3
|
import { runStep } from "./step/run.js";
|
|
4
4
|
import { createId } from "../utils/ids.js";
|
|
5
|
+
import { copyJson } from "@nylorun/core/define";
|
|
5
6
|
import { dispatchPlan } from "./dispatch.js";
|
|
6
7
|
import { createInvocation } from "./invocation.js";
|
|
7
8
|
import { openExecution, validateRunOptions } from "./options.js";
|
|
8
9
|
import { applyResume } from "./resume.js";
|
|
10
|
+
import { asDecisions, callHooks, hasAnyHooks, mergeTurnDecisions, projectInput, } from "./step/hooks.js";
|
|
9
11
|
/** All mutable progress belongs to this invocation and is discarded when it settles. */
|
|
10
12
|
export async function execute(agent, options) {
|
|
11
13
|
validateRunOptions(options);
|
|
@@ -35,6 +37,15 @@ export async function execute(agent, options) {
|
|
|
35
37
|
let stepNumber;
|
|
36
38
|
let arrivals = [];
|
|
37
39
|
let toolResults = [];
|
|
40
|
+
const hooked = hasAnyHooks(agent);
|
|
41
|
+
let turnStart = false;
|
|
42
|
+
const setTurn = (update) => {
|
|
43
|
+
const turn = invocation.state.turn ?? {
|
|
44
|
+
turnId,
|
|
45
|
+
attempts: { afterStep: 0, afterTurn: 0 },
|
|
46
|
+
};
|
|
47
|
+
invocation.state = { ...invocation.state, turn: update(turn) };
|
|
48
|
+
};
|
|
38
49
|
if (invocation.state.plan) {
|
|
39
50
|
turnId = invocation.state.plan.turnId;
|
|
40
51
|
stepNumber = invocation.state.plan.stepNumber + 1;
|
|
@@ -44,6 +55,15 @@ export async function execute(agent, options) {
|
|
|
44
55
|
return finish({ status: "paused" });
|
|
45
56
|
toolResults = lastResults(invocation.state);
|
|
46
57
|
}
|
|
58
|
+
else if (invocation.state.turn) {
|
|
59
|
+
// Crash-continue inside a turn that already ran before("turn"): keep the turn.
|
|
60
|
+
turnId = invocation.state.turn.turnId;
|
|
61
|
+
stepNumber =
|
|
62
|
+
1 +
|
|
63
|
+
invocation.state.transcript.filter((entry) => entry.kind === "candidate" && entry.turnId === turnId).length;
|
|
64
|
+
invocation.state = { ...invocation.state, status: "active" };
|
|
65
|
+
await record();
|
|
66
|
+
}
|
|
47
67
|
else {
|
|
48
68
|
turnId = createId("turn");
|
|
49
69
|
stepNumber = 1;
|
|
@@ -58,6 +78,18 @@ export async function execute(agent, options) {
|
|
|
58
78
|
...arrivals.map((event) => ({ kind: "input", turnId, event })),
|
|
59
79
|
],
|
|
60
80
|
};
|
|
81
|
+
if (hooked) {
|
|
82
|
+
const text = projectInput(arrivals);
|
|
83
|
+
invocation.state = {
|
|
84
|
+
...invocation.state,
|
|
85
|
+
turn: {
|
|
86
|
+
turnId,
|
|
87
|
+
...(text === undefined ? {} : { input: text }),
|
|
88
|
+
attempts: { afterStep: 0, afterTurn: 0 },
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
turnStart = true;
|
|
92
|
+
}
|
|
61
93
|
await record();
|
|
62
94
|
}
|
|
63
95
|
for (;; stepNumber++) {
|
|
@@ -93,14 +125,53 @@ export async function execute(agent, options) {
|
|
|
93
125
|
info: options.info,
|
|
94
126
|
observe,
|
|
95
127
|
output: agent.output,
|
|
128
|
+
...(hooked
|
|
129
|
+
? {
|
|
130
|
+
turn: {
|
|
131
|
+
start: turnStart,
|
|
132
|
+
...(invocation.state.turn?.input === undefined
|
|
133
|
+
? {}
|
|
134
|
+
: { input: invocation.state.turn.input }),
|
|
135
|
+
...(invocation.state.turn?.patch === undefined
|
|
136
|
+
? {}
|
|
137
|
+
: { patch: invocation.state.turn.patch }),
|
|
138
|
+
afterStepAttempts: invocation.state.turn?.attempts.afterStep ?? 0,
|
|
139
|
+
},
|
|
140
|
+
}
|
|
141
|
+
: {}),
|
|
96
142
|
});
|
|
97
143
|
signal.throwIfAborted();
|
|
98
|
-
|
|
144
|
+
turnStart = false;
|
|
145
|
+
if (result.turnPatch) {
|
|
146
|
+
const patch = result.turnPatch;
|
|
147
|
+
setTurn((turn) => ({ ...turn, patch }));
|
|
148
|
+
}
|
|
149
|
+
if (result.retried)
|
|
150
|
+
setTurn((turn) => ({
|
|
151
|
+
...turn,
|
|
152
|
+
attempts: { ...turn.attempts, afterStep: turn.attempts.afterStep + 1 },
|
|
153
|
+
}));
|
|
154
|
+
let candidate = result.candidate;
|
|
155
|
+
let finalOutput = result.output.kind === "final" ? result.output.output : undefined;
|
|
156
|
+
let turnDecision = {};
|
|
157
|
+
if (hooked && result.output.kind === "final" && result.retry === undefined) {
|
|
158
|
+
turnDecision = mergeTurnDecisions(asDecisions(await callHooks(agent, { at: "after", scope: "turn" }, {
|
|
159
|
+
...(agent.output || typeof finalOutput !== "string" ? {} : { text: finalOutput }),
|
|
160
|
+
output: finalOutput ?? null,
|
|
161
|
+
info: options.info,
|
|
162
|
+
state: { ...invocation.sessionBag },
|
|
163
|
+
attempt: invocation.state.turn?.attempts.afterTurn ?? 0,
|
|
164
|
+
}, `after-turn:${stepId}`)));
|
|
165
|
+
const replaced = replaceAnswer(turnDecision, candidate, agent.output);
|
|
166
|
+
if (replaced)
|
|
167
|
+
({ candidate, output: finalOutput } = replaced);
|
|
168
|
+
}
|
|
169
|
+
if (candidate) {
|
|
99
170
|
invocation.state = {
|
|
100
171
|
...invocation.state,
|
|
101
172
|
transcript: [
|
|
102
173
|
...invocation.state.transcript,
|
|
103
|
-
{ kind: "candidate", turnId, stepId, candidate
|
|
174
|
+
{ kind: "candidate", turnId, stepId, candidate },
|
|
104
175
|
],
|
|
105
176
|
};
|
|
106
177
|
observe({
|
|
@@ -111,7 +182,7 @@ export async function execute(agent, options) {
|
|
|
111
182
|
...(result.requestedModelId === undefined
|
|
112
183
|
? {}
|
|
113
184
|
: { requestedModelId: result.requestedModelId }),
|
|
114
|
-
attributes: result.candidate,
|
|
185
|
+
attributes: result.candidate ?? candidate,
|
|
115
186
|
});
|
|
116
187
|
}
|
|
117
188
|
if (result.output.kind === "tripwire") {
|
|
@@ -125,21 +196,60 @@ export async function execute(agent, options) {
|
|
|
125
196
|
});
|
|
126
197
|
return finish({ status: "failed", error: result.output.tripwire });
|
|
127
198
|
}
|
|
199
|
+
if (turnDecision.block !== undefined) {
|
|
200
|
+
const tripwire = {
|
|
201
|
+
code: "dynamics.blocked",
|
|
202
|
+
message: turnDecision.block,
|
|
203
|
+
scope: "execution",
|
|
204
|
+
};
|
|
205
|
+
observe({
|
|
206
|
+
type: "tripwire",
|
|
207
|
+
turnId,
|
|
208
|
+
stepId,
|
|
209
|
+
code: tripwire.code,
|
|
210
|
+
scope: tripwire.scope,
|
|
211
|
+
attributes: { message: tripwire.message },
|
|
212
|
+
});
|
|
213
|
+
return finish({ status: "failed", error: tripwire });
|
|
214
|
+
}
|
|
215
|
+
const feedback = result.retry ?? turnDecision.retry;
|
|
216
|
+
if (feedback !== undefined) {
|
|
217
|
+
// A hook sent the answer back: the model sees its answer, then the feedback.
|
|
218
|
+
const event = {
|
|
219
|
+
kind: "user-message",
|
|
220
|
+
text: feedback,
|
|
221
|
+
metadata: { source: "hook.retry" },
|
|
222
|
+
};
|
|
223
|
+
if (turnDecision.retry !== undefined)
|
|
224
|
+
setTurn((turn) => ({
|
|
225
|
+
...turn,
|
|
226
|
+
attempts: { ...turn.attempts, afterTurn: turn.attempts.afterTurn + 1 },
|
|
227
|
+
}));
|
|
228
|
+
invocation.state = {
|
|
229
|
+
...invocation.state,
|
|
230
|
+
transcript: [...invocation.state.transcript, { kind: "input", turnId, event }],
|
|
231
|
+
};
|
|
232
|
+
await record();
|
|
233
|
+
arrivals = [event];
|
|
234
|
+
toolResults = [];
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
128
237
|
if (result.output.kind === "final") {
|
|
238
|
+
const output = finalOutput;
|
|
129
239
|
invocation.state = {
|
|
130
240
|
...invocation.state,
|
|
131
241
|
transcript: [
|
|
132
242
|
...invocation.state.transcript,
|
|
133
|
-
{ kind: "final", turnId, stepId, output:
|
|
243
|
+
{ kind: "final", turnId, stepId, output: output },
|
|
134
244
|
],
|
|
135
245
|
};
|
|
136
246
|
observe({
|
|
137
247
|
type: "turn.completed",
|
|
138
248
|
turnId,
|
|
139
249
|
stepId,
|
|
140
|
-
attributes: { output:
|
|
250
|
+
attributes: { output: output },
|
|
141
251
|
});
|
|
142
|
-
return finish({ status: "completed", output:
|
|
252
|
+
return finish({ status: "completed", output: output });
|
|
143
253
|
}
|
|
144
254
|
const plan = result.output.plan;
|
|
145
255
|
const calls = plan.executable.map((entry) => {
|
|
@@ -240,6 +350,10 @@ async function finishInvocation(invocation, result) {
|
|
|
240
350
|
],
|
|
241
351
|
};
|
|
242
352
|
}
|
|
353
|
+
if (result.status !== "paused" && invocation.state.turn) {
|
|
354
|
+
const { turn: _turn, ...rest } = invocation.state;
|
|
355
|
+
invocation.state = rest;
|
|
356
|
+
}
|
|
243
357
|
invocation.state = { ...invocation.state, status: result.status };
|
|
244
358
|
await invocation.record();
|
|
245
359
|
invocation.emit({
|
|
@@ -262,3 +376,29 @@ function lastResults(state) {
|
|
|
262
376
|
const entry = state.transcript[state.transcript.length - 1];
|
|
263
377
|
return entry?.kind === "tool-results" ? entry.results : [];
|
|
264
378
|
}
|
|
379
|
+
/** Apply an after("turn") replacement to the final candidate and output. */
|
|
380
|
+
function replaceAnswer(decision, candidate, contract) {
|
|
381
|
+
if (decision.text === undefined && decision.output === undefined)
|
|
382
|
+
return undefined;
|
|
383
|
+
if (contract) {
|
|
384
|
+
if (decision.text !== undefined)
|
|
385
|
+
throw new HarnessError("configuration.invalid", 'after("turn") must return output, not text, for an agent with an output schema');
|
|
386
|
+
const validation = contract.schema.validate(decision.output);
|
|
387
|
+
if (!validation.ok)
|
|
388
|
+
throw new HarnessError("output.invalid", `after("turn") output failed validation: ${validation.issues
|
|
389
|
+
.map((issue) => issue.message)
|
|
390
|
+
.join("; ")}`);
|
|
391
|
+
const value = copyJson(validation.value);
|
|
392
|
+
return {
|
|
393
|
+
candidate: { ...candidate, output: [{ type: "json", value }] },
|
|
394
|
+
output: value,
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
if (decision.output !== undefined)
|
|
398
|
+
throw new HarnessError("configuration.invalid", 'after("turn") must return text, not output, for an agent without an output schema');
|
|
399
|
+
const text = decision.text;
|
|
400
|
+
return {
|
|
401
|
+
candidate: { ...candidate, output: [{ type: "text", text }] },
|
|
402
|
+
output: text,
|
|
403
|
+
};
|
|
404
|
+
}
|
package/dist/loop/state.js
CHANGED
|
@@ -97,6 +97,27 @@ const schema = z
|
|
|
97
97
|
status: z.enum(["ready", "active", "completed", "paused", "cancelled", "failed"]),
|
|
98
98
|
cancelledCalls: z.array(call).optional(),
|
|
99
99
|
state: z.record(z.string(), json).optional(),
|
|
100
|
+
turn: z
|
|
101
|
+
.object({
|
|
102
|
+
turnId: id,
|
|
103
|
+
input: z.string().optional(),
|
|
104
|
+
patch: z
|
|
105
|
+
.object({
|
|
106
|
+
capabilities: z.record(z.string(), z.boolean()).optional(),
|
|
107
|
+
tools: z.record(z.string(), z.boolean()).optional(),
|
|
108
|
+
instructions: z.array(z.string()).optional(),
|
|
109
|
+
})
|
|
110
|
+
.strict()
|
|
111
|
+
.optional(),
|
|
112
|
+
attempts: z
|
|
113
|
+
.object({
|
|
114
|
+
afterStep: z.number().int().nonnegative(),
|
|
115
|
+
afterTurn: z.number().int().nonnegative(),
|
|
116
|
+
})
|
|
117
|
+
.strict(),
|
|
118
|
+
})
|
|
119
|
+
.strict()
|
|
120
|
+
.optional(),
|
|
100
121
|
plan: z
|
|
101
122
|
.object({
|
|
102
123
|
turnId: id,
|
|
@@ -129,6 +150,8 @@ export function validateExecutionState(value) {
|
|
|
129
150
|
const plan = parsed.plan;
|
|
130
151
|
if (parsed.status === "paused" && !plan)
|
|
131
152
|
throw new HarnessError("execution.invalid-state", "Paused execution requires a pending plan");
|
|
153
|
+
if (plan && parsed.turn && parsed.turn.turnId !== plan.turnId)
|
|
154
|
+
throw new HarnessError("execution.invalid-state", "Turn hook state does not belong to the pending plan's turn");
|
|
132
155
|
if (plan) {
|
|
133
156
|
const ids = new Set();
|
|
134
157
|
const invocations = new Set();
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { AgentDefinition, Implementations } from "../../definition/agent-definition.js";
|
|
2
|
+
import type { Decision, HookAt, HookScope, TurnDecision } from "@nylorun/core/define";
|
|
3
|
+
import type { JsonValue } from "@nylorun/core/define";
|
|
4
|
+
import type { InputEvent } from "@nylorun/core/define";
|
|
5
|
+
import type { ModelConfigurationDraft } from "./model-configuration.js";
|
|
6
|
+
export interface HookPoint {
|
|
7
|
+
readonly at: HookAt;
|
|
8
|
+
readonly scope: HookScope;
|
|
9
|
+
}
|
|
10
|
+
/** Runs one hook point for the listed capabilities; results are keyed by capability id. */
|
|
11
|
+
export type HookRunner = (request: {
|
|
12
|
+
readonly point: HookPoint;
|
|
13
|
+
readonly capabilityIds: readonly string[];
|
|
14
|
+
readonly args: unknown;
|
|
15
|
+
/** Stable name of this call within the turn, used to journal it durably. */
|
|
16
|
+
readonly identity: string;
|
|
17
|
+
}) => Promise<Readonly<Record<string, unknown>>>;
|
|
18
|
+
/** The part of a before-hook Patch that shapes model calls. JSON, so a turn can persist it. */
|
|
19
|
+
export interface CallPatch {
|
|
20
|
+
readonly capabilities?: Readonly<Record<string, boolean>>;
|
|
21
|
+
readonly tools?: Readonly<Record<string, boolean>>;
|
|
22
|
+
readonly instructions?: readonly string[];
|
|
23
|
+
}
|
|
24
|
+
export interface CombinedPatch {
|
|
25
|
+
readonly block?: string;
|
|
26
|
+
readonly state?: Readonly<Record<string, JsonValue>>;
|
|
27
|
+
readonly patch: CallPatch;
|
|
28
|
+
}
|
|
29
|
+
export declare function localHookRunner(implementations: Implementations): HookRunner;
|
|
30
|
+
/** Capability ids registered at a hook point, in manifest (`.use()`) order. */
|
|
31
|
+
export declare function hookRegistrants(agent: AgentDefinition, point: HookPoint): readonly string[];
|
|
32
|
+
export declare function hasAnyHooks(agent: AgentDefinition): boolean;
|
|
33
|
+
/** Run a hook point, returning results in manifest order. Skips the call when nobody registered. */
|
|
34
|
+
export declare function callHooks(agent: AgentDefinition, point: HookPoint, args: unknown, identity: string): Promise<readonly {
|
|
35
|
+
readonly id: string;
|
|
36
|
+
readonly result: unknown;
|
|
37
|
+
}[]>;
|
|
38
|
+
/** Validate and merge before-hook Patches in manifest order. */
|
|
39
|
+
export declare function combinePatches(agent: AgentDefinition, results: readonly {
|
|
40
|
+
readonly id: string;
|
|
41
|
+
readonly result: unknown;
|
|
42
|
+
}[]): CombinedPatch;
|
|
43
|
+
/** Layer a step patch over the turn patch: step toggles win, instructions concatenate. */
|
|
44
|
+
export declare function layerPatches(turn: CallPatch | undefined, step: CallPatch | undefined): CallPatch;
|
|
45
|
+
/** Apply a patch to this model call's configuration. Toggles hide tools; hooks keep running. */
|
|
46
|
+
export declare function applyPatch(configuration: ModelConfigurationDraft, patch: CallPatch, order: number): void;
|
|
47
|
+
/** Merge after("step") Decisions; strictest wins. */
|
|
48
|
+
export declare function mergeDecisions(decisions: readonly Decision[]): Decision;
|
|
49
|
+
/** Merge after("turn") decisions: block, then retry, then a replacement answer. */
|
|
50
|
+
export declare function mergeTurnDecisions(decisions: readonly TurnDecision[]): TurnDecision;
|
|
51
|
+
export declare function asDecisions<T>(results: readonly {
|
|
52
|
+
readonly id: string;
|
|
53
|
+
readonly result: unknown;
|
|
54
|
+
}[]): T[];
|
|
55
|
+
/** The text of the user message that started a turn, when there is one. */
|
|
56
|
+
export declare function projectInput(arrivals: readonly InputEvent[]): string | undefined;
|