@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/dist/loop/run.js
CHANGED
|
@@ -2,12 +2,14 @@ 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
|
-
export async function execute(agent, options) {
|
|
12
|
+
export async function execute(agent, options, internals = {}) {
|
|
11
13
|
validateRunOptions(options);
|
|
12
14
|
const opened = openExecution(agent, options);
|
|
13
15
|
let { state } = opened;
|
|
@@ -26,7 +28,7 @@ export async function execute(agent, options) {
|
|
|
26
28
|
else if (input.kind === "approve" || input.kind === "respond" || input.kind === "settle") {
|
|
27
29
|
throw new HarnessError("execution.invalid-input", "There is no matching paused operation for this input");
|
|
28
30
|
}
|
|
29
|
-
const invocation = createInvocation({ agent, options, state, definitions });
|
|
31
|
+
const invocation = createInvocation({ agent, options, state, definitions, internals });
|
|
30
32
|
const { signal, observe, record } = invocation;
|
|
31
33
|
const finish = (result) => finishInvocation(invocation, result);
|
|
32
34
|
try {
|
|
@@ -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;
|
|
@@ -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>;
|