@nylorun/harness 0.22.0-beta → 0.23.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.
Files changed (55) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/HOST_CONTRACT.md +18 -21
  3. package/README.md +5 -30
  4. package/dist/api/executors.d.ts +5 -4
  5. package/dist/api/harness.d.ts +0 -10
  6. package/dist/api/harness.js +1 -52
  7. package/dist/api/host.d.ts +2 -8
  8. package/dist/api/host.js +3 -15
  9. package/dist/api/run.d.ts +0 -11
  10. package/dist/api/run.js +1 -11
  11. package/dist/compatibility.d.ts +4 -12
  12. package/dist/compatibility.js +3 -11
  13. package/dist/definition/agent-definition.d.ts +0 -3
  14. package/dist/definition/agent-definition.js +0 -2
  15. package/dist/flow/checkpoint.d.ts +16 -0
  16. package/dist/flow/checkpoint.js +6 -2
  17. package/dist/flow/context.d.ts +19 -10
  18. package/dist/flow/context.js +36 -20
  19. package/dist/flow/engine.d.ts +25 -7
  20. package/dist/flow/engine.js +304 -38
  21. package/dist/flow/index.d.ts +3 -5
  22. package/dist/flow/index.js +3 -5
  23. package/dist/flow/paths.d.ts +1 -8
  24. package/dist/flow/paths.js +1 -12
  25. package/dist/flow/tool.d.ts +14 -0
  26. package/dist/flow/tool.js +67 -0
  27. package/dist/flow/types.d.ts +30 -3
  28. package/dist/flow/types.js +14 -1
  29. package/dist/loop/run.js +5 -134
  30. package/dist/loop/state.js +2 -22
  31. package/dist/loop/step/run.d.ts +1 -10
  32. package/dist/loop/step/run.js +2 -101
  33. package/dist/loop/step/runtime.d.ts +0 -17
  34. package/dist/run/durable.d.ts +7 -11
  35. package/dist/run/durable.js +14 -33
  36. package/dist/run/index.d.ts +3 -4
  37. package/dist/run/index.js +1 -2
  38. package/dist/types/execution.d.ts +5 -18
  39. package/package.json +2 -2
  40. package/dist/flow/chain.d.ts +0 -8
  41. package/dist/flow/chain.js +0 -27
  42. package/dist/flow/loop.d.ts +0 -35
  43. package/dist/flow/loop.js +0 -238
  44. package/dist/flow/map.d.ts +0 -7
  45. package/dist/flow/map.js +0 -64
  46. package/dist/flow/node.d.ts +0 -31
  47. package/dist/flow/node.js +0 -113
  48. package/dist/flow/parallel.d.ts +0 -7
  49. package/dist/flow/parallel.js +0 -47
  50. package/dist/flow/switch.d.ts +0 -8
  51. package/dist/flow/switch.js +0 -35
  52. package/dist/flow/v2.d.ts +0 -12
  53. package/dist/flow/v2.js +0 -370
  54. package/dist/loop/step/hooks.d.ts +0 -56
  55. package/dist/loop/step/hooks.js +0 -191
package/dist/flow/v2.js DELETED
@@ -1,370 +0,0 @@
1
- /**
2
- * Flow engine for workflow manifest v2 (`flow-2`).
3
- *
4
- * Differences from v1 (`flow-1`), per the Flow Agents design:
5
- * - Agent and tool sessions are named by leaf paths: the leaf's id, `[i]` per Map
6
- * item, under nested flow agents' ids. Control stages add nothing.
7
- * - Functions are bound under stage keys (`route:on`, `@1.default.1:input`) and all
8
- * receive `{ input, results, flowInput }`; `flowInput` is the nearest Agent's input.
9
- * - Any node may carry `input`; there are no slots. A Map runs over its input.
10
- * - A Loop without `decide` passes on a pass verdict and retries with the feedback,
11
- * up to `max` attempts; `decide` returns `{ output }` or `{ retry, agent? }`.
12
- * - Leaf agents come from the manifest's embedded `agents`; nested flow agents run
13
- * inline with their own `flowInput` and `results`.
14
- */
15
- import { HarnessError, isVariantOf } from "@nylorun/core/define";
16
- import { ROOT_POSITION, childPosition, functionKey, indexSuffix, isWorkflowManifestV2, leafPart, leafPath, stageKey, } from "@nylorun/core/define";
17
- import { HostSuspension } from "../loop/host-suspension.js";
18
- import { createFlowContext, failureOf, markFailFastCancels, settleInFlight, } from "./context.js";
19
- import { assertLoopIteration, assertMapItemCount } from "./limits.js";
20
- import { iterationsOf } from "./paths.js";
21
- import { readAgentTurn } from "./loop.js";
22
- import { FlowNodeError } from "./types.js";
23
- export async function runFlowV2(options) {
24
- const { manifest, checkpoint, signal } = options;
25
- const ctx = createFlowContext(options);
26
- const scope = {
27
- manifest,
28
- flow: [],
29
- pathPrefix: "",
30
- keyPrefix: "",
31
- pending: [],
32
- indices: [],
33
- iterations: [],
34
- flowInput: checkpoint.input,
35
- results: {},
36
- };
37
- try {
38
- if (signal?.aborted)
39
- return { status: "cancelled", checkpoint, result: { status: "cancelled" } };
40
- const output = await runNode(ctx, scope, manifest.root, ROOT_POSITION, checkpoint.input);
41
- return { status: "completed", checkpoint, result: { status: "completed", output } };
42
- }
43
- catch (error) {
44
- await settleInFlight(ctx);
45
- if (error instanceof HostSuspension)
46
- return {
47
- status: [...ctx.pending.values()].includes("uncertain") ? "uncertain" : "waiting",
48
- checkpoint,
49
- effectIds: [...ctx.pending.keys()],
50
- };
51
- if (error instanceof FlowNodeError && error.failure.code === "cancelled")
52
- return { status: "cancelled", checkpoint, result: { status: "cancelled" } };
53
- return {
54
- status: "failed",
55
- checkpoint,
56
- result: { status: "failed", error: failureOf(error, manifest.id) },
57
- ...(ctx.cancelEffectIds.size > 0 ? { cancelEffectIds: [...ctx.cancelEffectIds] } : {}),
58
- };
59
- }
60
- }
61
- /** Where a node's effects are recorded: a leaf's path, or its stage key plus Map indices. */
62
- function siteOf(scope, node, key) {
63
- const part = leafPart(node);
64
- return part === undefined
65
- ? `${key}${indexSuffix(scope.indices)}`
66
- : leafPath(scope.pathPrefix, part, scope.pending);
67
- }
68
- async function runNode(ctx, scope, node, position, input, agentOptions = {}) {
69
- const key = stageKey(node, position, scope.keyPrefix);
70
- const site = siteOf(scope, node, key);
71
- let value = input;
72
- if (node.input)
73
- value = await callFn(ctx, scope, key, site, "input", stageArgs(scope, value));
74
- if ("agent" in node)
75
- return (await runAgent(ctx, scope, node, key, site, value, agentOptions)).output;
76
- if ("tool" in node)
77
- return runTool(ctx, scope, node.tool.name, key, site, value);
78
- if ("chain" in node)
79
- return runChain(ctx, scope, node.chain, position, value);
80
- if ("switch" in node)
81
- return runSwitch(ctx, scope, node.switch, key, site, position, value);
82
- if ("parallel" in node)
83
- return runParallel(ctx, scope, node.parallel, site, position, value);
84
- if ("map" in node)
85
- return runMap(ctx, scope, node.map.each, site, position, value);
86
- if ("loop" in node)
87
- return runLoop(ctx, scope, node.loop, key, site, position, value);
88
- throw new HarnessError("execution.invalid-state", "Unknown workflow node kind");
89
- }
90
- function stageArgs(scope, input) {
91
- return { input, results: scope.results, flowInput: scope.flowInput };
92
- }
93
- async function callFn(ctx, scope, key, site, role, args, context = {}) {
94
- return (await ctx.effect(role === "verify" ? "verify" : "fn", args, {
95
- path: `${site}:${role}`,
96
- key: functionKey(key, role),
97
- iterations: iterationsOf(scope.iterations),
98
- }, { role, ...context }));
99
- }
100
- /**
101
- * An agent node: a leaf agent runs as one turn in its own session; a nested flow agent
102
- * runs inline, under its own id, with its own `flowInput` and `results`.
103
- */
104
- async function runAgent(ctx, scope, node, key, site, input, options) {
105
- const target = scope.manifest.agents[node.agent];
106
- if (target === undefined)
107
- throw new FlowNodeError({
108
- code: "flow.unknown-agent",
109
- message: `Agent '${node.agent}' is not embedded in flow agent '${scope.manifest.id}'`,
110
- path: site,
111
- });
112
- if (isWorkflowManifestV2(target)) {
113
- const flow = target;
114
- const nested = {
115
- manifest: flow,
116
- flow: [...scope.flow, node.agent],
117
- pathPrefix: site,
118
- keyPrefix: key,
119
- pending: [],
120
- indices: scope.indices,
121
- iterations: scope.iterations,
122
- flowInput: input,
123
- results: {},
124
- };
125
- return { output: await runNode(ctx, nested, flow.root, ROOT_POSITION, input) };
126
- }
127
- const raw = await ctx.effect("agent", {
128
- agentId: node.agent,
129
- input,
130
- path: site,
131
- ...(scope.flow.length > 0 ? { flow: scope.flow } : {}),
132
- ...(options.manifest ? { manifest: options.manifest } : {}),
133
- }, { path: site, key, iterations: iterationsOf(scope.iterations) }, options.context ?? {});
134
- return readAgentTurn(raw);
135
- }
136
- async function runTool(ctx, scope, name, key, site, input) {
137
- const value = (await ctx.effect("tool", input, { path: site, key, iterations: iterationsOf(scope.iterations) }, { toolName: name }));
138
- if (!value || typeof value !== "object" || Array.isArray(value))
139
- return value;
140
- const outcome = value;
141
- if (outcome.kind === "completed" && "output" in outcome)
142
- return outcome.output ?? null;
143
- if (outcome.kind === "denied")
144
- throw new FlowNodeError({
145
- code: "tool.denied",
146
- message: typeof outcome.reason === "string" ? outcome.reason : "Tool call denied",
147
- path: site,
148
- });
149
- return value;
150
- }
151
- /** Steps in order; each step's output is the next one's input. `results` is lexical. */
152
- async function runChain(ctx, scope, steps, position, input) {
153
- const results = {};
154
- const inner = { ...scope, results };
155
- let current = input;
156
- for (const [index, step] of steps.entries()) {
157
- current = await runNode(ctx, inner, step, childPosition(position, index), current);
158
- const name = step.id ?? leafPart(step);
159
- if (name !== undefined)
160
- results[name] = current;
161
- }
162
- return current;
163
- }
164
- /** `on` picks a case; the key is journaled, so replay always takes the same case. */
165
- async function runSwitch(ctx, scope, node, key, site, position, input) {
166
- const chosen = await callFn(ctx, scope, key, site, "on", stageArgs(scope, input));
167
- if (typeof chosen !== "string")
168
- throw new FlowNodeError({
169
- code: "fn.failed",
170
- message: `Switch on must return a case name, got ${typeof chosen}`,
171
- path: site,
172
- });
173
- const caseNode = node.cases[chosen];
174
- if (caseNode)
175
- return runNode(ctx, scope, caseNode, childPosition(position, chosen), input);
176
- if (node.default)
177
- return runNode(ctx, scope, node.default, childPosition(position, "default"), input);
178
- throw new FlowNodeError({
179
- code: "switch.no-match",
180
- message: `No Switch case is named ${JSON.stringify(chosen)} and there is no default case`,
181
- path: site,
182
- });
183
- }
184
- /** Run `tasks` together; fail fast on the first failure in declaration order. */
185
- async function runTogether(ctx, tasks, pathOf) {
186
- const outputs = new Array(tasks.length);
187
- const suspensions = [];
188
- const failures = [];
189
- await Promise.all(tasks.map(async (task, index) => {
190
- try {
191
- outputs[index] = await task();
192
- }
193
- catch (error) {
194
- if (error instanceof HostSuspension) {
195
- suspensions.push(error);
196
- return;
197
- }
198
- failures.push({
199
- index,
200
- error: error instanceof FlowNodeError
201
- ? error
202
- : new FlowNodeError(failureOf(error, pathOf(index))),
203
- });
204
- }
205
- }));
206
- if (failures.length > 0) {
207
- markFailFastCancels(ctx);
208
- failures.sort((a, b) => a.index - b.index);
209
- throw failures[0].error;
210
- }
211
- if (suspensions.length > 0)
212
- throw suspensions[0];
213
- return outputs;
214
- }
215
- /** Every branch gets the same input; the output is keyed by branch, in declaration order. */
216
- async function runParallel(ctx, scope, branches, site, position, input) {
217
- const names = Object.keys(branches);
218
- const outputs = await runTogether(ctx, names.map((name) => () => runNode(ctx, scope, branches[name], childPosition(position, name), input)), () => site);
219
- const result = {};
220
- names.forEach((name, index) => {
221
- result[name] = outputs[index];
222
- });
223
- return result;
224
- }
225
- /** Runs `each` once per item of its input; the output is in item order. */
226
- async function runMap(ctx, scope, each, site, position, input) {
227
- if (!Array.isArray(input))
228
- throw new FlowNodeError({
229
- code: "map.not-a-list",
230
- message: `A Map runs over its input, which must be an array; got ${input === null ? "null" : typeof input}`,
231
- path: site,
232
- });
233
- assertMapItemCount(input.length, ctx.limits, site);
234
- if (input.length === 0)
235
- return [];
236
- const eachPosition = childPosition(position, "each");
237
- return runTogether(ctx, input.map((item, index) => () => runNode(ctx, { ...scope, pending: [...scope.pending, index], indices: [...scope.indices, index] }, each, eachPosition, item)), (index) => `${site}[${index}]`);
238
- }
239
- /** Run, verify, then stop or retry. The body keeps its session across attempts. */
240
- async function runLoop(ctx, scope, loop, key, site, position, input) {
241
- const history = [];
242
- const runPosition = childPosition(position, "run");
243
- const runIsLeaf = "agent" in loop.run &&
244
- !isWorkflowManifestV2(scope.manifest.agents[loop.run.agent]);
245
- let current = input;
246
- let pinned;
247
- let variant;
248
- for (let iteration = 1;; iteration += 1) {
249
- if (ctx.signal?.aborted)
250
- throw new FlowNodeError({ code: "cancelled", message: "cancelled", path: site });
251
- assertLoopIteration(iteration, ctx.limits, site);
252
- const turn = { ...scope, iterations: [...scope.iterations, iteration] };
253
- const loopContext = { loopPath: site, n: iteration };
254
- let output;
255
- if (runIsLeaf) {
256
- const node = loop.run;
257
- const runKey = stageKey(node, runPosition, scope.keyPrefix);
258
- const runSite = siteOf(turn, node, runKey);
259
- let value = current;
260
- if (node.input)
261
- value = await callFn(ctx, turn, runKey, runSite, "input", stageArgs(turn, value), loopContext);
262
- const result = await runAgent(ctx, turn, node, runKey, runSite, value, {
263
- context: loopContext,
264
- ...(variant ? { manifest: variant } : {}),
265
- });
266
- output = result.output;
267
- if (result.agent) {
268
- pinned ??= result.agent;
269
- variant = result.agent;
270
- }
271
- }
272
- else
273
- output = await runNode(ctx, turn, loop.run, runPosition, current);
274
- const verdict = await runVerify(ctx, turn, loop.verify, key, site, position, {
275
- input,
276
- output,
277
- iteration,
278
- loopContext,
279
- });
280
- let decision;
281
- if (loop.decide) {
282
- try {
283
- decision = (await callFn(ctx, turn, key, site, "decide", {
284
- input,
285
- output,
286
- verdict,
287
- iteration,
288
- history,
289
- ...(variant ? { agent: variant } : {}),
290
- results: turn.results,
291
- flowInput: turn.flowInput,
292
- }, loopContext));
293
- }
294
- catch (error) {
295
- if (error instanceof FlowNodeError && error.failure.code === "fn.failed")
296
- throw new FlowNodeError({
297
- code: "loop.stopped",
298
- message: error.failure.message,
299
- path: site,
300
- });
301
- throw error;
302
- }
303
- }
304
- else
305
- decision = verdict.pass ? { output } : { retry: verdict.feedback };
306
- if (!decision || typeof decision !== "object")
307
- throw new FlowNodeError({
308
- code: "loop.invalid-decision",
309
- message: "Loop decide must return { output } or { retry }",
310
- path: site,
311
- });
312
- if ("output" in decision)
313
- return decision.output;
314
- if (!("retry" in decision))
315
- throw new FlowNodeError({
316
- code: "loop.invalid-decision",
317
- message: "Loop decide must return { output } or { retry }",
318
- path: site,
319
- });
320
- if (loop.max !== undefined && iteration >= loop.max)
321
- throw new FlowNodeError({
322
- code: "loop.exhausted",
323
- message: `Loop stopped after ${loop.max} attempt${loop.max === 1 ? "" : "s"}` +
324
- (verdict.pass ? "" : `: ${verdict.feedback}`),
325
- path: site,
326
- });
327
- if (decision.agent !== undefined) {
328
- if (!runIsLeaf)
329
- throw new FlowNodeError({
330
- code: "loop.invalid-agent",
331
- message: "decide returned agent, but the Loop body is not an agent",
332
- path: site,
333
- });
334
- if (pinned && !isVariantOf(decision.agent, pinned))
335
- throw new FlowNodeError({
336
- code: "loop.invalid-agent",
337
- message: "decide returned a manifest that is not a variant of the body agent",
338
- path: site,
339
- });
340
- variant = decision.agent;
341
- }
342
- history.push({ iteration, output, verdict });
343
- current = decision.retry;
344
- }
345
- }
346
- async function runVerify(ctx, scope, verify, key, site, position, args) {
347
- try {
348
- if ("fn" in verify)
349
- return (await callFn(ctx, scope, key, site, "verify", {
350
- input: args.input,
351
- output: args.output,
352
- iteration: args.iteration,
353
- results: scope.results,
354
- flowInput: scope.flowInput,
355
- }, args.loopContext));
356
- // A verifier agent judges `{ task, response, iteration }` in a fresh session per attempt.
357
- const judged = { task: args.input, response: args.output, iteration: args.iteration };
358
- return (await runNode(ctx, scope, verify, childPosition(position, "verify"), judged, {
359
- context: { ...args.loopContext, role: "verify-agent" },
360
- }));
361
- }
362
- catch (error) {
363
- if (error instanceof HostSuspension)
364
- throw error;
365
- const failure = failureOf(error, site);
366
- if (failure.code === "loop.verify-failed")
367
- throw error;
368
- throw new FlowNodeError({ code: "loop.verify-failed", message: failure.message, path: site });
369
- }
370
- }
@@ -1,56 +0,0 @@
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;
@@ -1,191 +0,0 @@
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
- }