@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
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { HarnessError, hasHook, runHookPoint } from "@nylorun/core/define";
|
|
2
|
+
export function localHookRunner(implementations) {
|
|
3
|
+
return ({ point, capabilityIds, args }) => runHookPoint(implementations, { ...point, capabilityIds }, args);
|
|
4
|
+
}
|
|
5
|
+
/** Capability ids registered at a hook point, in manifest (`.use()`) order. */
|
|
6
|
+
export function hookRegistrants(agent, point) {
|
|
7
|
+
return agent.manifest.capabilities
|
|
8
|
+
.filter((capability) => hasHook(capability.hooks, point.at, point.scope))
|
|
9
|
+
.map((capability) => capability.id);
|
|
10
|
+
}
|
|
11
|
+
export function hasAnyHooks(agent) {
|
|
12
|
+
return agent.manifest.capabilities.some((capability) => capability.hooks?.length);
|
|
13
|
+
}
|
|
14
|
+
/** Run a hook point, returning results in manifest order. Skips the call when nobody registered. */
|
|
15
|
+
export async function callHooks(agent, point, args, identity) {
|
|
16
|
+
const capabilityIds = hookRegistrants(agent, point);
|
|
17
|
+
if (!capabilityIds.length)
|
|
18
|
+
return [];
|
|
19
|
+
const results = await agent.runHooks({ point, capabilityIds, args, identity });
|
|
20
|
+
return capabilityIds.map((id) => ({ id, result: results[id] ?? {} }));
|
|
21
|
+
}
|
|
22
|
+
/** Validate and merge before-hook Patches in manifest order. */
|
|
23
|
+
export function combinePatches(agent, results) {
|
|
24
|
+
let block;
|
|
25
|
+
const state = {};
|
|
26
|
+
const capabilities = {};
|
|
27
|
+
const tools = {};
|
|
28
|
+
const instructions = [];
|
|
29
|
+
for (const { id, result } of results) {
|
|
30
|
+
const agentLevel = id === "agent";
|
|
31
|
+
const patch = normalizeCapabilityPatch(id, asObject(result, id), agentLevel);
|
|
32
|
+
if (patch.block !== undefined)
|
|
33
|
+
block = checkedString(patch.block, id, "block");
|
|
34
|
+
if (patch.state !== undefined)
|
|
35
|
+
Object.assign(state, asObject(patch.state, id));
|
|
36
|
+
if (patch.instructions !== undefined) {
|
|
37
|
+
if (!Array.isArray(patch.instructions) ||
|
|
38
|
+
patch.instructions.some((item) => typeof item !== "string"))
|
|
39
|
+
throw invalid(`Capability '${id}' hook instructions must be strings`);
|
|
40
|
+
instructions.push(...patch.instructions);
|
|
41
|
+
}
|
|
42
|
+
for (const [name, on] of Object.entries(asObject(patch.capabilities ?? {}, id))) {
|
|
43
|
+
if (!agentLevel && name !== id)
|
|
44
|
+
throw invalid(`Capability '${id}' hook may only toggle itself, not '${name}'`);
|
|
45
|
+
if (!agent.manifest.capabilities.some((item) => item.id === name))
|
|
46
|
+
throw invalid(`Hook referenced unknown capability '${name}'`);
|
|
47
|
+
capabilities[name] = checkedBoolean(on, id);
|
|
48
|
+
}
|
|
49
|
+
for (const [name, on] of Object.entries(asObject(patch.tools ?? {}, id))) {
|
|
50
|
+
const owner = toolOwner(agent, name);
|
|
51
|
+
if (owner === undefined)
|
|
52
|
+
throw invalid(`Hook referenced unknown tool '${name}'`);
|
|
53
|
+
if (!agentLevel && owner !== id)
|
|
54
|
+
throw invalid(`Capability '${id}' hook may only toggle its own tools`);
|
|
55
|
+
tools[name] = checkedBoolean(on, id);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
...(block === undefined ? {} : { block }),
|
|
60
|
+
...(Object.keys(state).length ? { state } : {}),
|
|
61
|
+
patch: compact({ capabilities, tools, instructions }),
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/** Layer a step patch over the turn patch: step toggles win, instructions concatenate. */
|
|
65
|
+
export function layerPatches(turn, step) {
|
|
66
|
+
return compact({
|
|
67
|
+
capabilities: { ...turn?.capabilities, ...step?.capabilities },
|
|
68
|
+
tools: { ...turn?.tools, ...step?.tools },
|
|
69
|
+
instructions: [...(turn?.instructions ?? []), ...(step?.instructions ?? [])],
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
/** Apply a patch to this model call's configuration. Toggles hide tools; hooks keep running. */
|
|
73
|
+
export function applyPatch(configuration, patch, order) {
|
|
74
|
+
const offCapabilities = Object.entries(patch.capabilities ?? {})
|
|
75
|
+
.filter(([, on]) => !on)
|
|
76
|
+
.map(([id]) => id);
|
|
77
|
+
const offTools = Object.entries(patch.tools ?? {})
|
|
78
|
+
.filter(([, on]) => !on)
|
|
79
|
+
.map(([name]) => name);
|
|
80
|
+
if (offCapabilities.length || offTools.length)
|
|
81
|
+
configuration.exclude({ capabilities: offCapabilities, tools: offTools });
|
|
82
|
+
if (patch.instructions?.length)
|
|
83
|
+
configuration.setInstructions("dynamics", order, "dynamics", Object.freeze([...patch.instructions]));
|
|
84
|
+
}
|
|
85
|
+
/** Merge after("step") Decisions; strictest wins. */
|
|
86
|
+
export function mergeDecisions(decisions) {
|
|
87
|
+
let block;
|
|
88
|
+
let retry;
|
|
89
|
+
const deny = new Map();
|
|
90
|
+
const approve = new Map();
|
|
91
|
+
let text;
|
|
92
|
+
for (const decision of decisions) {
|
|
93
|
+
if (decision.block)
|
|
94
|
+
block = decision.block;
|
|
95
|
+
if (decision.retry)
|
|
96
|
+
retry = decision.retry;
|
|
97
|
+
for (const item of decision.deny ?? [])
|
|
98
|
+
deny.set(item.id, item.reason);
|
|
99
|
+
for (const item of decision.approve ?? [])
|
|
100
|
+
approve.set(item.id, item.prompt);
|
|
101
|
+
if (decision.text !== undefined)
|
|
102
|
+
text = decision.text;
|
|
103
|
+
}
|
|
104
|
+
if (block)
|
|
105
|
+
return { block };
|
|
106
|
+
if (retry)
|
|
107
|
+
return { retry, ...(text === undefined ? {} : { text }) };
|
|
108
|
+
return {
|
|
109
|
+
...(text === undefined ? {} : { text }),
|
|
110
|
+
...(deny.size ? { deny: [...deny.entries()].map(([id, reason]) => ({ id, reason })) } : {}),
|
|
111
|
+
...(approve.size
|
|
112
|
+
? { approve: [...approve.entries()].map(([id, prompt]) => ({ id, prompt })) }
|
|
113
|
+
: {}),
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
/** Merge after("turn") decisions: block, then retry, then a replacement answer. */
|
|
117
|
+
export function mergeTurnDecisions(decisions) {
|
|
118
|
+
let block;
|
|
119
|
+
let retry;
|
|
120
|
+
let text;
|
|
121
|
+
let output;
|
|
122
|
+
for (const decision of decisions) {
|
|
123
|
+
if (decision.block)
|
|
124
|
+
block = decision.block;
|
|
125
|
+
if (decision.retry)
|
|
126
|
+
retry = decision.retry;
|
|
127
|
+
if (decision.text !== undefined)
|
|
128
|
+
text = decision.text;
|
|
129
|
+
if (decision.output !== undefined)
|
|
130
|
+
output = decision.output;
|
|
131
|
+
}
|
|
132
|
+
if (block)
|
|
133
|
+
return { block };
|
|
134
|
+
if (retry)
|
|
135
|
+
return { retry };
|
|
136
|
+
return {
|
|
137
|
+
...(text === undefined ? {} : { text }),
|
|
138
|
+
...(output === undefined ? {} : { output }),
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
export function asDecisions(results) {
|
|
142
|
+
return results.map(({ id, result }) => asObject(result, id));
|
|
143
|
+
}
|
|
144
|
+
/** The text of the user message that started a turn, when there is one. */
|
|
145
|
+
export function projectInput(arrivals) {
|
|
146
|
+
const message = arrivals.find((item) => item.kind === "user-message");
|
|
147
|
+
if (!message)
|
|
148
|
+
return undefined;
|
|
149
|
+
if ("text" in message && typeof message.text === "string")
|
|
150
|
+
return message.text;
|
|
151
|
+
return undefined;
|
|
152
|
+
}
|
|
153
|
+
function toolOwner(agent, name) {
|
|
154
|
+
return agent.manifest.capabilities.find((capability) => capability.tools?.some((tool) => tool.name === name) ||
|
|
155
|
+
agent.implementations[capability.id]?.tools?.[name] !== undefined)?.id;
|
|
156
|
+
}
|
|
157
|
+
function normalizeCapabilityPatch(id, patch, agentLevel) {
|
|
158
|
+
if (patch.active === undefined)
|
|
159
|
+
return patch;
|
|
160
|
+
if (agentLevel)
|
|
161
|
+
throw invalid("Agent-level before hooks must use capabilities{}, not active");
|
|
162
|
+
return {
|
|
163
|
+
...patch,
|
|
164
|
+
capabilities: { ...(patch.capabilities ?? {}), [id]: checkedBoolean(patch.active, id) },
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
function compact(patch) {
|
|
168
|
+
return {
|
|
169
|
+
...(Object.keys(patch.capabilities).length ? { capabilities: patch.capabilities } : {}),
|
|
170
|
+
...(Object.keys(patch.tools).length ? { tools: patch.tools } : {}),
|
|
171
|
+
...(patch.instructions.length ? { instructions: patch.instructions } : {}),
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
function asObject(value, id) {
|
|
175
|
+
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
176
|
+
throw invalid(`Capability '${id}' hook must return an object`);
|
|
177
|
+
return value;
|
|
178
|
+
}
|
|
179
|
+
function checkedBoolean(value, id) {
|
|
180
|
+
if (typeof value !== "boolean")
|
|
181
|
+
throw invalid(`Capability '${id}' hook toggles must be booleans`);
|
|
182
|
+
return value;
|
|
183
|
+
}
|
|
184
|
+
function checkedString(value, id, field) {
|
|
185
|
+
if (typeof value !== "string")
|
|
186
|
+
throw invalid(`Capability '${id}' hook ${field} must be a string`);
|
|
187
|
+
return value;
|
|
188
|
+
}
|
|
189
|
+
function invalid(message) {
|
|
190
|
+
return new HarnessError("configuration.invalid", message);
|
|
191
|
+
}
|
|
@@ -9,6 +9,11 @@ export declare class ModelConfigurationDraft {
|
|
|
9
9
|
setTools(middlewareId: string, middlewareOrder: number, slot: string, tools: readonly ToolDefinition[], options?: ModelConfigurationMutationOptions): void;
|
|
10
10
|
select(middlewareId: string, middlewareOrder: number, directive: ModelDirective, options?: Omit<ModelConfigurationMutationOptions, "order">): void;
|
|
11
11
|
replace(middlewareId: string, middlewareOrder: number, directive: ModelDirective, options?: Omit<ModelConfigurationMutationOptions, "order">): void;
|
|
12
|
+
/** Hide tools from this model call: every tool a capability contributed, or tools by name. */
|
|
13
|
+
exclude(input: {
|
|
14
|
+
readonly capabilities?: readonly string[];
|
|
15
|
+
readonly tools?: readonly string[];
|
|
16
|
+
}): void;
|
|
12
17
|
clear(options?: Omit<ModelConfigurationMutationOptions, "order">): void;
|
|
13
18
|
snapshot(): InternalModelConfigurationSnapshot;
|
|
14
19
|
}
|
|
@@ -8,6 +8,8 @@ export class ModelConfigurationDraft {
|
|
|
8
8
|
#instructions = new SlotDraft();
|
|
9
9
|
#tools = new SlotDraft();
|
|
10
10
|
#model;
|
|
11
|
+
#excludedOwners = new Set();
|
|
12
|
+
#excludedTools = new Set();
|
|
11
13
|
constructor(directive) {
|
|
12
14
|
if (directive !== undefined)
|
|
13
15
|
this.#model = Object.freeze({ directive: checkedDirective(directive) });
|
|
@@ -69,6 +71,13 @@ export class ModelConfigurationDraft {
|
|
|
69
71
|
}),
|
|
70
72
|
});
|
|
71
73
|
}
|
|
74
|
+
/** Hide tools from this model call: every tool a capability contributed, or tools by name. */
|
|
75
|
+
exclude(input) {
|
|
76
|
+
for (const id of input.capabilities ?? [])
|
|
77
|
+
this.#excludedOwners.add(id);
|
|
78
|
+
for (const name of input.tools ?? [])
|
|
79
|
+
this.#excludedTools.add(name);
|
|
80
|
+
}
|
|
72
81
|
clear(options) {
|
|
73
82
|
if (options?.reason !== undefined)
|
|
74
83
|
checkedReason(options.reason, "configuration.invalid-reason", "Model configuration");
|
|
@@ -81,7 +90,11 @@ export class ModelConfigurationDraft {
|
|
|
81
90
|
text,
|
|
82
91
|
contributor: contributor(slot.owner, slot.reason),
|
|
83
92
|
})));
|
|
84
|
-
const sourcedTools = toolSlots
|
|
93
|
+
const sourcedTools = toolSlots
|
|
94
|
+
.filter((slot) => !this.#excludedOwners.has(slot.owner.middlewareId))
|
|
95
|
+
.flatMap((slot) => slot.value
|
|
96
|
+
.filter((tool) => !this.#excludedTools.has(tool.name))
|
|
97
|
+
.map((tool) => Object.freeze({ tool, contributor: contributor(slot.owner, slot.reason) })));
|
|
85
98
|
const seen = new Set();
|
|
86
99
|
const duplicate = new Set();
|
|
87
100
|
for (const item of sourcedTools) {
|
package/dist/loop/step/run.d.ts
CHANGED
|
@@ -1,17 +1,23 @@
|
|
|
1
|
-
import type { ExecutionSnapshot, StepRuntime } from "./runtime.js";
|
|
1
|
+
import type { ExecutionSnapshot, StepRuntime, StepTurnHooks } from "./runtime.js";
|
|
2
2
|
import type { TurnOutputContract } from "@nylorun/core/define";
|
|
3
3
|
import type { ModelCandidate } from "@nylorun/core/define";
|
|
4
4
|
import type { InputEvent } from "@nylorun/core/define";
|
|
5
5
|
import type { ToolResult } from "@nylorun/core/define";
|
|
6
6
|
import type { ObserveEmit } from "../observe.js";
|
|
7
7
|
import { type SealedStepOutput } from "./seal.js";
|
|
8
|
+
import { type CallPatch } from "./hooks.js";
|
|
8
9
|
export interface StepRunResult {
|
|
9
10
|
readonly stepId: string;
|
|
10
11
|
readonly candidate?: ModelCandidate;
|
|
11
12
|
readonly output: SealedStepOutput;
|
|
12
13
|
readonly requestedModelId?: string;
|
|
13
14
|
readonly modelInvocationId?: string;
|
|
15
|
+
/** Feedback when an after("step") hook asked a text-only answer to be redone. */
|
|
14
16
|
readonly retry?: string;
|
|
17
|
+
/** True when an after("step") hook requested a retry (text or tool calls). */
|
|
18
|
+
readonly retried?: boolean;
|
|
19
|
+
/** Validated before("turn") patch, returned on the first step of a turn. */
|
|
20
|
+
readonly turnPatch?: CallPatch;
|
|
15
21
|
}
|
|
16
22
|
export declare function runStep(input: {
|
|
17
23
|
agent: StepRuntime;
|
|
@@ -27,4 +33,6 @@ export declare function runStep(input: {
|
|
|
27
33
|
signal: AbortSignal;
|
|
28
34
|
info?: unknown;
|
|
29
35
|
output?: TurnOutputContract;
|
|
36
|
+
/** Turn-scoped hook state; omitted when the agent registers no hooks. */
|
|
37
|
+
turn?: StepTurnHooks;
|
|
30
38
|
}): Promise<StepRunResult>;
|
package/dist/loop/step/run.js
CHANGED
|
@@ -10,11 +10,13 @@ import { resolveModelRequest } from "./resolve.js";
|
|
|
10
10
|
import { sealStep } from "./seal.js";
|
|
11
11
|
import { ModelConfigurationDraft } from "./model-configuration.js";
|
|
12
12
|
import { createId } from "../../utils/ids.js";
|
|
13
|
-
import {
|
|
13
|
+
import { applyPatch, asDecisions, callHooks, combinePatches, layerPatches, mergeDecisions, } from "./hooks.js";
|
|
14
14
|
export async function runStep(input) {
|
|
15
15
|
let requestedModelId;
|
|
16
16
|
let modelInvocationId;
|
|
17
17
|
let retryFeedback;
|
|
18
|
+
let retried = false;
|
|
19
|
+
let turnPatch;
|
|
18
20
|
const stepInput = Object.freeze({
|
|
19
21
|
executionId: input.executionId,
|
|
20
22
|
turnId: input.turnId,
|
|
@@ -42,35 +44,38 @@ export async function runStep(input) {
|
|
|
42
44
|
if (context.currentTripwire)
|
|
43
45
|
return context.tripwire(context.currentTripwire);
|
|
44
46
|
const definition = input.agent.definition;
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
step: input.stepNumber - 1,
|
|
50
|
-
arrivals: input.arrivals,
|
|
51
|
-
messages: projectModelCall(resolveModelRequest({
|
|
47
|
+
const turn = input.turn;
|
|
48
|
+
if (definition && turn) {
|
|
49
|
+
try {
|
|
50
|
+
const messages = projectModelCall(resolveModelRequest({
|
|
52
51
|
context,
|
|
53
52
|
arrivals: input.arrivals,
|
|
54
53
|
toolResults: input.toolResults,
|
|
55
54
|
output: input.output,
|
|
56
|
-
})).prompt
|
|
57
|
-
sessionState
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
55
|
+
})).prompt;
|
|
56
|
+
const sessionState = input.agent.sessionState ?? {};
|
|
57
|
+
const base = { input: turn.input, info: input.info, messages };
|
|
58
|
+
let patch = turn.patch;
|
|
59
|
+
if (turn.start) {
|
|
60
|
+
const combined = combinePatches(definition, await callHooks(definition, { at: "before", scope: "turn" }, { ...base, state: { ...sessionState } }, "before-turn"));
|
|
61
|
+
if (combined.state)
|
|
62
|
+
Object.assign(sessionState, combined.state);
|
|
63
|
+
if (combined.block !== undefined)
|
|
64
|
+
return context.tripwire({
|
|
65
|
+
code: "dynamics.blocked",
|
|
66
|
+
message: combined.block,
|
|
67
|
+
scope: "execution",
|
|
68
|
+
});
|
|
69
|
+
patch = turnPatch = combined.patch;
|
|
65
70
|
}
|
|
71
|
+
const step = combinePatches(definition, await callHooks(definition, { at: "before", scope: "step" }, { ...base, state: { ...sessionState }, step: input.stepNumber - 1 }, `before-step:${input.stepId}`));
|
|
72
|
+
if (step.state)
|
|
73
|
+
Object.assign(sessionState, step.state);
|
|
66
74
|
if (input.agent.recordAfterDynamics)
|
|
67
75
|
await input.agent.recordAfterDynamics();
|
|
68
|
-
if (
|
|
69
|
-
return context.tripwire({
|
|
70
|
-
|
|
71
|
-
message: before.blocked,
|
|
72
|
-
});
|
|
73
|
-
}
|
|
76
|
+
if (step.block !== undefined)
|
|
77
|
+
return context.tripwire({ code: "dynamics.blocked", message: step.block });
|
|
78
|
+
applyPatch(configuration, layerPatches(patch, step.patch), 10_000);
|
|
74
79
|
}
|
|
75
80
|
catch (error) {
|
|
76
81
|
if (error instanceof HostSuspension)
|
|
@@ -148,7 +153,7 @@ export async function runStep(input) {
|
|
|
148
153
|
const candidate = context.currentCandidate;
|
|
149
154
|
if (!candidate)
|
|
150
155
|
throw new HarnessError("model.candidate-missing", "Model candidate missing after mint");
|
|
151
|
-
if (
|
|
156
|
+
if (definition && turn) {
|
|
152
157
|
const text = candidate.output
|
|
153
158
|
?.filter((block) => block.type === "text")
|
|
154
159
|
.map((block) => block.text)
|
|
@@ -159,18 +164,28 @@ export async function runStep(input) {
|
|
|
159
164
|
const call = block;
|
|
160
165
|
return { id: call.id, name: call.name, args: call.args };
|
|
161
166
|
});
|
|
162
|
-
const decision = await
|
|
167
|
+
const decision = mergeDecisions(asDecisions(await callHooks(definition, { at: "after", scope: "step" }, {
|
|
163
168
|
...(text ? { text } : {}),
|
|
164
169
|
toolCalls,
|
|
165
|
-
|
|
170
|
+
info: input.info,
|
|
171
|
+
state: { ...(input.agent.sessionState ?? {}) },
|
|
172
|
+
step: input.stepNumber - 1,
|
|
173
|
+
attempt: turn.afterStepAttempts,
|
|
174
|
+
}, `after-step:${input.stepId}`)));
|
|
166
175
|
if (input.agent.recordAfterDynamics)
|
|
167
176
|
await input.agent.recordAfterDynamics();
|
|
168
177
|
if (decision.block) {
|
|
169
178
|
return context.tripwire({ code: "dynamics.blocked", message: decision.block });
|
|
170
179
|
}
|
|
171
180
|
if (decision.retry) {
|
|
172
|
-
|
|
173
|
-
|
|
181
|
+
retried = true;
|
|
182
|
+
// Denied calls reach the model as tool results carrying the feedback.
|
|
183
|
+
if (toolCalls.length)
|
|
184
|
+
for (const call of toolCalls)
|
|
185
|
+
minted.deny(call.id, decision.retry);
|
|
186
|
+
else
|
|
187
|
+
retryFeedback = decision.retry;
|
|
188
|
+
return minted;
|
|
174
189
|
}
|
|
175
190
|
if (decision.text !== undefined) {
|
|
176
191
|
minted.replace({
|
|
@@ -198,7 +213,8 @@ export async function runStep(input) {
|
|
|
198
213
|
});
|
|
199
214
|
}
|
|
200
215
|
}, input.observe);
|
|
201
|
-
|
|
216
|
+
// A text answer sent back for a retry is not the turn's output, so skip output sealing.
|
|
217
|
+
const output = sealStep(context, retryFeedback === undefined ? input.output : undefined);
|
|
202
218
|
const candidate = output.kind === "tools" ? output.plan.candidate : context.currentCandidate;
|
|
203
219
|
return Object.freeze({
|
|
204
220
|
stepId: input.stepId,
|
|
@@ -207,6 +223,8 @@ export async function runStep(input) {
|
|
|
207
223
|
output,
|
|
208
224
|
...(modelInvocationId ? { modelInvocationId } : {}),
|
|
209
225
|
...(retryFeedback ? { retry: retryFeedback } : {}),
|
|
226
|
+
...(retried ? { retried } : {}),
|
|
227
|
+
...(turnPatch === undefined ? {} : { turnPatch }),
|
|
210
228
|
});
|
|
211
229
|
}
|
|
212
230
|
function snapshotStepStart(input) {
|
|
@@ -5,18 +5,30 @@ import type { InputEvent, TranscriptEntry } from "@nylorun/core/define";
|
|
|
5
5
|
import type { ToolResult } from "@nylorun/core/define";
|
|
6
6
|
import type { BoundMiddleware } from "@nylorun/core/define";
|
|
7
7
|
import type { JsonValue } from "@nylorun/core/define";
|
|
8
|
+
import type { CallPatch } from "./hooks.js";
|
|
8
9
|
/** Compiled definition pieces plus the per-run model adapter for one step. */
|
|
9
10
|
export interface StepRuntime {
|
|
10
11
|
readonly middleware: readonly BoundMiddleware[];
|
|
11
12
|
readonly invoke: ModelAdapter;
|
|
12
13
|
readonly registry: ToolRegistry;
|
|
13
|
-
/** Full definition for before/after
|
|
14
|
+
/** Full definition for before/after hooks (optional for middleware-only agents). */
|
|
14
15
|
readonly definition?: AgentDefinition;
|
|
15
16
|
/** Mutable session memory bag shared with tools. */
|
|
16
17
|
sessionState?: Record<string, JsonValue>;
|
|
17
|
-
/** Called after
|
|
18
|
+
/** Called after hook results are applied so the host can record. */
|
|
18
19
|
recordAfterDynamics?: () => Promise<void>;
|
|
19
20
|
}
|
|
21
|
+
/** Turn-scoped hook state carried into each step. */
|
|
22
|
+
export interface StepTurnHooks {
|
|
23
|
+
/** True for the first model call of a new turn: run before("turn"). */
|
|
24
|
+
readonly start: boolean;
|
|
25
|
+
/** Input that started the turn; hooks see it on every step, including retries. */
|
|
26
|
+
readonly input?: string;
|
|
27
|
+
/** Validated before("turn") patch applied to every step. */
|
|
28
|
+
readonly patch?: CallPatch;
|
|
29
|
+
/** Retries already requested by after("step") hooks this turn. */
|
|
30
|
+
readonly afterStepAttempts: number;
|
|
31
|
+
}
|
|
20
32
|
export interface StepInput {
|
|
21
33
|
readonly executionId: string;
|
|
22
34
|
readonly turnId: string;
|
package/dist/run/durable.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type { AgentManifest } from "@nylorun/core/define";
|
|
|
2
2
|
import type { ExecutionInput, ExecutionState, RunResult } from "../types/execution.js";
|
|
3
3
|
import type { JsonObject } from "@nylorun/core/define";
|
|
4
4
|
import type { ActionOutcome } from "@nylorun/core/contracts";
|
|
5
|
+
import type { HookAt, HookScope } from "@nylorun/core/define";
|
|
5
6
|
import { ENGINE_VERSION } from "../compatibility.js";
|
|
6
7
|
/** Private persistence contract for hosts; this is not a session wire type. */
|
|
7
8
|
export interface DurableCheckpoint {
|
|
@@ -22,9 +23,15 @@ export interface HostEffect {
|
|
|
22
23
|
readonly turnId: string;
|
|
23
24
|
readonly agentId: string;
|
|
24
25
|
readonly manifestHash: string;
|
|
25
|
-
readonly kind: "model" | "tool" | "
|
|
26
|
+
readonly kind: "model" | "tool" | "hook";
|
|
26
27
|
readonly capabilityId?: string;
|
|
27
28
|
readonly toolName?: string;
|
|
29
|
+
/** For `hook` effects: the hook point and every capability that registered it, in manifest order. */
|
|
30
|
+
readonly hook?: {
|
|
31
|
+
readonly at: HookAt;
|
|
32
|
+
readonly scope: HookScope;
|
|
33
|
+
readonly capabilityIds: readonly string[];
|
|
34
|
+
};
|
|
28
35
|
readonly input: unknown;
|
|
29
36
|
readonly context: Record<string, unknown>;
|
|
30
37
|
}
|
package/dist/run/durable.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { HarnessError } from "@nylorun/core/define";
|
|
2
|
+
import { HOOK_POINTS, hasHook } from "@nylorun/core/define";
|
|
2
3
|
import { AgentManifestSchema } from "@nylorun/core/contracts";
|
|
3
4
|
import { agentFrom } from "@nylorun/core/define";
|
|
4
5
|
import { definitionFor } from "../definition/agent-definition.js";
|
|
@@ -39,11 +40,11 @@ export async function runDurable(options) {
|
|
|
39
40
|
checkpoint.state.agentId !== manifest.id ||
|
|
40
41
|
checkpoint.state.executionId !== checkpoint.sessionId))
|
|
41
42
|
throw new HarnessError("execution.incompatible", "Checkpoint definition/session mismatch");
|
|
42
|
-
let serial = 0;
|
|
43
43
|
const pending = new Map();
|
|
44
44
|
const inFlight = new Set();
|
|
45
|
-
|
|
46
|
-
|
|
45
|
+
// Effect ids are derived from stable names, never call order, so replays line up.
|
|
46
|
+
const effect = async (kind, input, context, identity, target = {}) => {
|
|
47
|
+
const effectId = `${checkpoint.turnId}:${checkpoint.segment}:${kind}:${identity}`;
|
|
47
48
|
const request = JSON.parse(JSON.stringify({
|
|
48
49
|
effectId,
|
|
49
50
|
sessionId: checkpoint.sessionId,
|
|
@@ -53,8 +54,7 @@ export async function runDurable(options) {
|
|
|
53
54
|
kind,
|
|
54
55
|
input,
|
|
55
56
|
context,
|
|
56
|
-
...
|
|
57
|
-
...(toolName ? { toolName } : {}),
|
|
57
|
+
...target,
|
|
58
58
|
}));
|
|
59
59
|
const operation = host.resolveEffect(request);
|
|
60
60
|
inFlight.add(operation);
|
|
@@ -94,7 +94,7 @@ export async function runDurable(options) {
|
|
|
94
94
|
info: ctx.info,
|
|
95
95
|
state: ctx.state.entries(),
|
|
96
96
|
resume: ctx.resume,
|
|
97
|
-
}, capabilityId, tool.name
|
|
97
|
+
}, ctx.invocationId, { capabilityId, toolName: tool.name });
|
|
98
98
|
// Apply concurrently resolved patches in manifest call order, independent of host I/O timing.
|
|
99
99
|
await previous;
|
|
100
100
|
for (const [key, value] of Object.entries(outcome.statePatch ?? {}))
|
|
@@ -127,17 +127,8 @@ export async function runDurable(options) {
|
|
|
127
127
|
tools[tool.name] = hostedTool(capability.id, tool);
|
|
128
128
|
implementations[capability.id] = {
|
|
129
129
|
tools,
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
beforeModelCall: async (args) => (await effect("beforeModelCall", args, { info: checkpoint.info }, capability.id))
|
|
133
|
-
.value,
|
|
134
|
-
}
|
|
135
|
-
: {}),
|
|
136
|
-
...(capability.afterModelCall
|
|
137
|
-
? {
|
|
138
|
-
afterModelCall: async (args, ctx) => (await effect("afterModelCall", args, ctx, capability.id)).value,
|
|
139
|
-
}
|
|
140
|
-
: {}),
|
|
130
|
+
// Hooks run through runHooks below, one effect per hook point; these only satisfy binding.
|
|
131
|
+
...hookPlaceholders(capability.hooks),
|
|
141
132
|
};
|
|
142
133
|
}
|
|
143
134
|
const definition = definitionFor(agentFrom(manifest, implementations, sessionTools.length === 0
|
|
@@ -151,14 +142,25 @@ export async function runDurable(options) {
|
|
|
151
142
|
// Manifest reconstruction must retain definition identity, including schemas and instructions.
|
|
152
143
|
if (definition.hash !== checkpoint.manifestHash)
|
|
153
144
|
throw new HarnessError("execution.incompatible", "Reconstructed definition hash mismatch");
|
|
145
|
+
// All capabilities registered at a hook point share one effect, so one executor round trip.
|
|
146
|
+
const runHooks = async ({ point, capabilityIds, args, identity }) => {
|
|
147
|
+
const outcome = await effect("hook", args, { info: checkpoint.info }, identity, {
|
|
148
|
+
hook: { at: point.at, scope: point.scope, capabilityIds },
|
|
149
|
+
});
|
|
150
|
+
const results = outcome.value?.results;
|
|
151
|
+
return results !== null && typeof results === "object" && !Array.isArray(results)
|
|
152
|
+
? results
|
|
153
|
+
: {};
|
|
154
|
+
};
|
|
155
|
+
const hosted = Object.freeze({ ...definition, runHooks });
|
|
154
156
|
try {
|
|
155
|
-
const result = await withDeterministicIds(`${checkpoint.turnId}_${checkpoint.segment}`, () => execute(
|
|
157
|
+
const result = await withDeterministicIds(`${checkpoint.turnId}_${checkpoint.segment}`, () => execute(hosted, {
|
|
156
158
|
state: checkpoint.state ??
|
|
157
159
|
initializeExecutionState(definition, { executionId: checkpoint.sessionId }),
|
|
158
160
|
input: checkpoint.input,
|
|
159
161
|
info: checkpoint.info,
|
|
160
162
|
signal: options.signal,
|
|
161
|
-
onModelCall: async (call, ctx) => (await effect("model", call, { request: ctx.request, invocationId: ctx.invocationId },
|
|
163
|
+
onModelCall: async (call, ctx) => (await effect("model", call, { request: ctx.request, invocationId: ctx.invocationId }, ctx.invocationId)).value,
|
|
162
164
|
}));
|
|
163
165
|
return { status: result.status, checkpoint: { ...checkpoint, state: result.state }, result };
|
|
164
166
|
}
|
|
@@ -174,3 +176,13 @@ export async function runDurable(options) {
|
|
|
174
176
|
};
|
|
175
177
|
}
|
|
176
178
|
}
|
|
179
|
+
function hookPlaceholders(hooks) {
|
|
180
|
+
const placeholder = () => {
|
|
181
|
+
throw new HarnessError("execution.incompatible", "Hosted hooks run through the host effect");
|
|
182
|
+
};
|
|
183
|
+
const table = {};
|
|
184
|
+
for (const point of HOOK_POINTS)
|
|
185
|
+
if (hasHook(hooks, point.at, point.scope))
|
|
186
|
+
(table[point.at] ??= {})[point.scope] = placeholder;
|
|
187
|
+
return table;
|
|
188
|
+
}
|
package/dist/types/client.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import type { MessageInput } from "@nylorun/core/define";
|
|
|
3
3
|
import type { SavedToolCall } from "./execution.js";
|
|
4
4
|
/**
|
|
5
5
|
* Definition-parameterized client types (H11). Types only — harness does not implement Session.
|
|
6
|
-
* Runtime imports these for
|
|
6
|
+
* Runtime imports these for session and stream typing.
|
|
7
7
|
*/
|
|
8
8
|
export interface InputAccepted {
|
|
9
9
|
readonly status: "accepted" | "rejected";
|
|
@@ -58,6 +58,23 @@ export interface ExecutionPlan {
|
|
|
58
58
|
readonly immediate: readonly ToolResult[];
|
|
59
59
|
readonly calls: readonly SavedToolCall[];
|
|
60
60
|
}
|
|
61
|
+
/** Hook progress for the turn in flight. Cleared when the turn ends. */
|
|
62
|
+
export interface TurnHookState {
|
|
63
|
+
readonly turnId: string;
|
|
64
|
+
/** Text of the input that started the turn. */
|
|
65
|
+
readonly input?: string;
|
|
66
|
+
/** Validated before("turn") patch, applied to every step of the turn. */
|
|
67
|
+
readonly patch?: {
|
|
68
|
+
readonly capabilities?: Readonly<Record<string, boolean>>;
|
|
69
|
+
readonly tools?: Readonly<Record<string, boolean>>;
|
|
70
|
+
readonly instructions?: readonly string[];
|
|
71
|
+
};
|
|
72
|
+
/** Retries requested so far this turn, per hook point. */
|
|
73
|
+
readonly attempts: {
|
|
74
|
+
readonly afterStep: number;
|
|
75
|
+
readonly afterTurn: number;
|
|
76
|
+
};
|
|
77
|
+
}
|
|
61
78
|
/** Versioned continuation data, not a live execution object. */
|
|
62
79
|
export interface ExecutionState {
|
|
63
80
|
readonly version: 1;
|
|
@@ -73,8 +90,10 @@ export interface ExecutionState {
|
|
|
73
90
|
readonly plan?: ExecutionPlan;
|
|
74
91
|
/** Abandoned actions retained for reconciliation, never automatically dispatched. */
|
|
75
92
|
readonly cancelledCalls?: readonly SavedToolCall[];
|
|
93
|
+
/** Hook progress for the current turn; present only while a turn with hooks is in flight. */
|
|
94
|
+
readonly turn?: TurnHookState;
|
|
76
95
|
/**
|
|
77
|
-
* Durable session memory (tools write via `ctx.state`;
|
|
96
|
+
* Durable session memory (tools write via `ctx.state`; hooks read it).
|
|
78
97
|
* Runtime persists this with the checkpoint.
|
|
79
98
|
*/
|
|
80
99
|
readonly state?: JsonObject;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nylorun/harness",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.17.0-beta",
|
|
4
4
|
"description": "Nylorun's TypeScript agent execution engine. See github.com/nylorun/harness.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -76,7 +76,7 @@
|
|
|
76
76
|
"zod": "^4.6.5"
|
|
77
77
|
},
|
|
78
78
|
"dependencies": {
|
|
79
|
-
"@nylorun/core": "0.
|
|
79
|
+
"@nylorun/core": "0.3.0-beta"
|
|
80
80
|
},
|
|
81
81
|
"peerDependencies": {
|
|
82
82
|
"zod": "^4.6.5"
|
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import type { AgentDefinition } from "../../definition/agent-definition.js";
|
|
2
|
-
import type { Decision } from "@nylorun/core/define";
|
|
3
|
-
import type { JsonValue } from "@nylorun/core/define";
|
|
4
|
-
import type { PromptItem } from "@nylorun/core/define";
|
|
5
|
-
import type { InputEvent } from "@nylorun/core/define";
|
|
6
|
-
import type { ModelConfigurationDraft } from "./model-configuration.js";
|
|
7
|
-
export interface DynamicsContext {
|
|
8
|
-
readonly agent: AgentDefinition;
|
|
9
|
-
readonly info?: unknown;
|
|
10
|
-
readonly step: number;
|
|
11
|
-
readonly arrivals: readonly InputEvent[];
|
|
12
|
-
readonly messages: readonly PromptItem[];
|
|
13
|
-
sessionState: Record<string, JsonValue>;
|
|
14
|
-
}
|
|
15
|
-
/** Run all beforeModelCall handlers in capability `.use()` order. */
|
|
16
|
-
export declare function applyBeforeModelCall(ctx: DynamicsContext, configuration: ModelConfigurationDraft): Promise<{
|
|
17
|
-
readonly blocked?: string;
|
|
18
|
-
}>;
|
|
19
|
-
/** Run all afterModelCall handlers; merge with strictest-wins rules. */
|
|
20
|
-
export declare function applyAfterModelCall(ctx: DynamicsContext, args: {
|
|
21
|
-
readonly text?: string;
|
|
22
|
-
readonly toolCalls: readonly {
|
|
23
|
-
readonly id: string;
|
|
24
|
-
readonly name: string;
|
|
25
|
-
readonly args: JsonValue;
|
|
26
|
-
}[];
|
|
27
|
-
}): Promise<Decision>;
|
|
28
|
-
export declare function mergeDecisions(decisions: readonly Decision[]): Decision;
|
|
29
|
-
export declare function hasDynamics(agent: AgentDefinition): boolean;
|