@nylorun/harness 0.15.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.
@@ -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.flatMap((slot) => slot.value.map((tool) => Object.freeze({ tool, contributor: contributor(slot.owner, slot.reason) })));
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) {
@@ -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>;
@@ -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 { applyAfterModelCall, applyBeforeModelCall, hasDynamics, } from "./dynamics.js";
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 dynamicsCtx = definition && hasDynamics(definition)
46
- ? {
47
- agent: definition,
48
- info: input.info,
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: input.agent.sessionState ?? {},
58
- }
59
- : undefined;
60
- if (dynamicsCtx) {
61
- try {
62
- const before = await applyBeforeModelCall(dynamicsCtx, configuration);
63
- if (input.agent.sessionState) {
64
- Object.assign(input.agent.sessionState, dynamicsCtx.sessionState);
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 (before.blocked) {
69
- return context.tripwire({
70
- code: "dynamics.blocked",
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 (dynamicsCtx) {
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 applyAfterModelCall(dynamicsCtx, {
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
- retryFeedback = decision.retry;
173
- return context.tripwire({ code: "dynamics.retry", message: decision.retry });
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
- const output = sealStep(context, input.output);
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 dynamics (optional for middleware-only agents). */
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 Patch/Decision applied so the host can record. */
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;
@@ -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" | "beforeModelCall" | "afterModelCall";
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
  }
@@ -50,6 +57,14 @@ export type DurableResult = {
50
57
  readonly checkpoint: DurableCheckpoint;
51
58
  readonly result: RunResult<unknown>;
52
59
  };
60
+ /** Discovered tool advertised for this execution. It is not part of the hashed manifest. */
61
+ export interface DurableSessionTool {
62
+ readonly capabilityId: string;
63
+ readonly name: string;
64
+ readonly description?: string;
65
+ readonly inputSchema: JsonObject;
66
+ readonly outputSchema?: JsonObject;
67
+ }
53
68
  export declare function createDurableCheckpoint(input: {
54
69
  manifest: AgentManifest;
55
70
  sessionId: string;
@@ -68,4 +83,5 @@ export declare function runDurable(options: {
68
83
  checkpoint: DurableCheckpoint;
69
84
  host: DurableHost;
70
85
  signal?: AbortSignal;
86
+ sessionTools?: readonly DurableSessionTool[];
71
87
  }): Promise<DurableResult>;