@nylorun/harness 0.22.1-beta → 0.23.1-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 +93 -0
- package/HOST_CONTRACT.md +26 -23
- package/README.md +5 -30
- package/dist/api/executors.d.ts +5 -4
- package/dist/api/harness.d.ts +0 -10
- package/dist/api/harness.js +1 -52
- package/dist/api/host.d.ts +2 -8
- package/dist/api/host.js +3 -15
- package/dist/api/run.d.ts +0 -11
- package/dist/api/run.js +1 -11
- package/dist/compatibility.d.ts +4 -12
- package/dist/compatibility.js +3 -11
- package/dist/definition/agent-definition.d.ts +0 -3
- package/dist/definition/agent-definition.js +0 -2
- package/dist/flow/checkpoint.d.ts +16 -0
- package/dist/flow/checkpoint.js +6 -2
- package/dist/flow/context.d.ts +19 -10
- package/dist/flow/context.js +36 -20
- package/dist/flow/engine.d.ts +25 -7
- package/dist/flow/engine.js +304 -38
- package/dist/flow/index.d.ts +3 -5
- package/dist/flow/index.js +3 -5
- package/dist/flow/paths.d.ts +1 -8
- package/dist/flow/paths.js +1 -12
- package/dist/flow/tool.d.ts +14 -0
- package/dist/flow/tool.js +67 -0
- package/dist/flow/types.d.ts +30 -3
- package/dist/flow/types.js +14 -1
- package/dist/loop/run.js +5 -134
- package/dist/loop/state.js +2 -22
- package/dist/loop/step/run.d.ts +1 -10
- package/dist/loop/step/run.js +2 -101
- package/dist/loop/step/runtime.d.ts +0 -17
- package/dist/run/durable.d.ts +7 -11
- package/dist/run/durable.js +14 -33
- package/dist/run/index.d.ts +3 -4
- package/dist/run/index.js +1 -2
- package/dist/types/execution.d.ts +5 -18
- package/package.json +2 -2
- package/dist/flow/chain.d.ts +0 -8
- package/dist/flow/chain.js +0 -27
- package/dist/flow/loop.d.ts +0 -35
- package/dist/flow/loop.js +0 -238
- package/dist/flow/map.d.ts +0 -7
- package/dist/flow/map.js +0 -64
- package/dist/flow/node.d.ts +0 -31
- package/dist/flow/node.js +0 -113
- package/dist/flow/parallel.d.ts +0 -7
- package/dist/flow/parallel.js +0 -47
- package/dist/flow/switch.d.ts +0 -8
- package/dist/flow/switch.js +0 -35
- package/dist/flow/v2.d.ts +0 -12
- package/dist/flow/v2.js +0 -370
- package/dist/loop/step/hooks.d.ts +0 -56
- package/dist/loop/step/hooks.js +0 -191
package/dist/loop/run.js
CHANGED
|
@@ -3,12 +3,10 @@ import { HarnessError, isHarnessError } from "@nylorun/core/define";
|
|
|
3
3
|
import { runStep } from "./step/run.js";
|
|
4
4
|
import { compact, contextBudget, estimateTokens } from "./compaction/index.js";
|
|
5
5
|
import { createId } from "../utils/ids.js";
|
|
6
|
-
import { copyJson } from "@nylorun/core/define";
|
|
7
6
|
import { dispatchPlan } from "./dispatch.js";
|
|
8
7
|
import { createInvocation } from "./invocation.js";
|
|
9
8
|
import { openExecution, validateRunOptions } from "./options.js";
|
|
10
9
|
import { applyResume } from "./resume.js";
|
|
11
|
-
import { asDecisions, callHooks, hasAnyHooks, mergeTurnDecisions, projectInput, } from "./step/hooks.js";
|
|
12
10
|
/** All mutable progress belongs to this invocation and is discarded when it settles. */
|
|
13
11
|
export async function execute(agent, options, internals = {}) {
|
|
14
12
|
validateRunOptions(options);
|
|
@@ -61,15 +59,6 @@ export async function execute(agent, options, internals = {}) {
|
|
|
61
59
|
};
|
|
62
60
|
let arrivals = [];
|
|
63
61
|
let toolResults = [];
|
|
64
|
-
const hooked = hasAnyHooks(agent);
|
|
65
|
-
let turnStart = false;
|
|
66
|
-
const setTurn = (update) => {
|
|
67
|
-
const turn = invocation.state.turn ?? {
|
|
68
|
-
turnId,
|
|
69
|
-
attempts: { afterStep: 0, afterTurn: 0 },
|
|
70
|
-
};
|
|
71
|
-
invocation.state = { ...invocation.state, turn: update(turn) };
|
|
72
|
-
};
|
|
73
62
|
if (invocation.state.plan) {
|
|
74
63
|
turnId = invocation.state.plan.turnId;
|
|
75
64
|
stepNumber = invocation.state.plan.stepNumber + 1;
|
|
@@ -80,7 +69,7 @@ export async function execute(agent, options, internals = {}) {
|
|
|
80
69
|
toolResults = lastResults(invocation.state);
|
|
81
70
|
}
|
|
82
71
|
else if (invocation.state.turn) {
|
|
83
|
-
//
|
|
72
|
+
// Continue a turn that yielded, or crash-continue inside it: keep the turn.
|
|
84
73
|
turnId = invocation.state.turn.turnId;
|
|
85
74
|
stepNumber =
|
|
86
75
|
1 +
|
|
@@ -103,18 +92,6 @@ export async function execute(agent, options, internals = {}) {
|
|
|
103
92
|
...arrivals.map((event) => ({ kind: "input", turnId, event })),
|
|
104
93
|
],
|
|
105
94
|
};
|
|
106
|
-
if (hooked) {
|
|
107
|
-
const text = projectInput(arrivals);
|
|
108
|
-
invocation.state = {
|
|
109
|
-
...invocation.state,
|
|
110
|
-
turn: {
|
|
111
|
-
turnId,
|
|
112
|
-
...(text === undefined ? {} : { input: text }),
|
|
113
|
-
attempts: { afterStep: 0, afterTurn: 0 },
|
|
114
|
-
},
|
|
115
|
-
};
|
|
116
|
-
turnStart = true;
|
|
117
|
-
}
|
|
118
95
|
await record();
|
|
119
96
|
}
|
|
120
97
|
for (;; stepNumber++) {
|
|
@@ -127,7 +104,7 @@ export async function execute(agent, options, internals = {}) {
|
|
|
127
104
|
((yieldAfter.steps !== undefined && stepsRun >= yieldAfter.steps) ||
|
|
128
105
|
(yieldAfter.ms !== undefined && Date.now() - started >= yieldAfter.ms))) {
|
|
129
106
|
if (!invocation.state.turn)
|
|
130
|
-
|
|
107
|
+
invocation.state = { ...invocation.state, turn: { turnId } };
|
|
131
108
|
return finish({ status: "yielded" });
|
|
132
109
|
}
|
|
133
110
|
stepsRun++;
|
|
@@ -149,11 +126,7 @@ export async function execute(agent, options, internals = {}) {
|
|
|
149
126
|
middleware: agent.middleware,
|
|
150
127
|
invoke: options.onModelCall,
|
|
151
128
|
registry: agent.registry,
|
|
152
|
-
definition: agent,
|
|
153
129
|
sessionState: invocation.sessionBag,
|
|
154
|
-
recordAfterDynamics: async () => {
|
|
155
|
-
await record();
|
|
156
|
-
},
|
|
157
130
|
},
|
|
158
131
|
state: snapshot,
|
|
159
132
|
executionId: invocation.state.executionId,
|
|
@@ -167,32 +140,8 @@ export async function execute(agent, options, internals = {}) {
|
|
|
167
140
|
info: options.info,
|
|
168
141
|
observe,
|
|
169
142
|
output: agent.output,
|
|
170
|
-
...(hooked
|
|
171
|
-
? {
|
|
172
|
-
turn: {
|
|
173
|
-
start: turnStart,
|
|
174
|
-
...(invocation.state.turn?.input === undefined
|
|
175
|
-
? {}
|
|
176
|
-
: { input: invocation.state.turn.input }),
|
|
177
|
-
...(invocation.state.turn?.patch === undefined
|
|
178
|
-
? {}
|
|
179
|
-
: { patch: invocation.state.turn.patch }),
|
|
180
|
-
afterStepAttempts: invocation.state.turn?.attempts.afterStep ?? 0,
|
|
181
|
-
},
|
|
182
|
-
}
|
|
183
|
-
: {}),
|
|
184
143
|
});
|
|
185
144
|
signal.throwIfAborted();
|
|
186
|
-
turnStart = false;
|
|
187
|
-
if (result.turnPatch) {
|
|
188
|
-
const patch = result.turnPatch;
|
|
189
|
-
setTurn((turn) => ({ ...turn, patch }));
|
|
190
|
-
}
|
|
191
|
-
if (result.retried)
|
|
192
|
-
setTurn((turn) => ({
|
|
193
|
-
...turn,
|
|
194
|
-
attempts: { ...turn.attempts, afterStep: turn.attempts.afterStep + 1 },
|
|
195
|
-
}));
|
|
196
145
|
// The prompt did not fit: compact once and ask again with the same inputs.
|
|
197
146
|
if (result.output.kind === "tripwire" &&
|
|
198
147
|
result.output.tripwire.code === "model.context_overflow" &&
|
|
@@ -203,21 +152,7 @@ export async function execute(agent, options, internals = {}) {
|
|
|
203
152
|
}
|
|
204
153
|
if (result.output.kind !== "tripwire")
|
|
205
154
|
overflowCompacted = false;
|
|
206
|
-
|
|
207
|
-
let finalOutput = result.output.kind === "final" ? result.output.output : undefined;
|
|
208
|
-
let turnDecision = {};
|
|
209
|
-
if (hooked && result.output.kind === "final" && result.retry === undefined) {
|
|
210
|
-
turnDecision = mergeTurnDecisions(asDecisions(await callHooks(agent, { at: "after", scope: "turn" }, {
|
|
211
|
-
...(agent.output || typeof finalOutput !== "string" ? {} : { text: finalOutput }),
|
|
212
|
-
output: finalOutput ?? null,
|
|
213
|
-
info: options.info,
|
|
214
|
-
state: { ...invocation.sessionBag },
|
|
215
|
-
attempt: invocation.state.turn?.attempts.afterTurn ?? 0,
|
|
216
|
-
}, `after-turn:${stepId}`)));
|
|
217
|
-
const replaced = replaceAnswer(turnDecision, candidate, agent.output);
|
|
218
|
-
if (replaced)
|
|
219
|
-
({ candidate, output: finalOutput } = replaced);
|
|
220
|
-
}
|
|
155
|
+
const candidate = result.candidate;
|
|
221
156
|
if (candidate) {
|
|
222
157
|
invocation.state = {
|
|
223
158
|
...invocation.state,
|
|
@@ -234,7 +169,7 @@ export async function execute(agent, options, internals = {}) {
|
|
|
234
169
|
...(result.requestedModelId === undefined
|
|
235
170
|
? {}
|
|
236
171
|
: { requestedModelId: result.requestedModelId }),
|
|
237
|
-
attributes:
|
|
172
|
+
attributes: candidate,
|
|
238
173
|
});
|
|
239
174
|
}
|
|
240
175
|
if (result.output.kind === "tripwire") {
|
|
@@ -248,46 +183,8 @@ export async function execute(agent, options, internals = {}) {
|
|
|
248
183
|
});
|
|
249
184
|
return finish({ status: "failed", error: result.output.tripwire });
|
|
250
185
|
}
|
|
251
|
-
if (turnDecision.block !== undefined) {
|
|
252
|
-
const tripwire = {
|
|
253
|
-
code: "dynamics.blocked",
|
|
254
|
-
message: turnDecision.block,
|
|
255
|
-
scope: "execution",
|
|
256
|
-
};
|
|
257
|
-
observe({
|
|
258
|
-
type: "tripwire",
|
|
259
|
-
turnId,
|
|
260
|
-
stepId,
|
|
261
|
-
code: tripwire.code,
|
|
262
|
-
scope: tripwire.scope,
|
|
263
|
-
attributes: { message: tripwire.message },
|
|
264
|
-
});
|
|
265
|
-
return finish({ status: "failed", error: tripwire });
|
|
266
|
-
}
|
|
267
|
-
const feedback = result.retry ?? turnDecision.retry;
|
|
268
|
-
if (feedback !== undefined) {
|
|
269
|
-
// A hook sent the answer back: the model sees its answer, then the feedback.
|
|
270
|
-
const event = {
|
|
271
|
-
kind: "user-message",
|
|
272
|
-
text: feedback,
|
|
273
|
-
metadata: { source: "hook.retry" },
|
|
274
|
-
};
|
|
275
|
-
if (turnDecision.retry !== undefined)
|
|
276
|
-
setTurn((turn) => ({
|
|
277
|
-
...turn,
|
|
278
|
-
attempts: { ...turn.attempts, afterTurn: turn.attempts.afterTurn + 1 },
|
|
279
|
-
}));
|
|
280
|
-
invocation.state = {
|
|
281
|
-
...invocation.state,
|
|
282
|
-
transcript: [...invocation.state.transcript, { kind: "input", turnId, event }],
|
|
283
|
-
};
|
|
284
|
-
await record();
|
|
285
|
-
arrivals = [event];
|
|
286
|
-
toolResults = [];
|
|
287
|
-
continue;
|
|
288
|
-
}
|
|
289
186
|
if (result.output.kind === "final") {
|
|
290
|
-
const output =
|
|
187
|
+
const output = result.output.output;
|
|
291
188
|
invocation.state = {
|
|
292
189
|
...invocation.state,
|
|
293
190
|
transcript: [
|
|
@@ -434,29 +331,3 @@ function lastResults(state) {
|
|
|
434
331
|
const entry = state.transcript[state.transcript.length - 1];
|
|
435
332
|
return entry?.kind === "tool-results" ? entry.results : [];
|
|
436
333
|
}
|
|
437
|
-
/** Apply an after("turn") replacement to the final candidate and output. */
|
|
438
|
-
function replaceAnswer(decision, candidate, contract) {
|
|
439
|
-
if (decision.text === undefined && decision.output === undefined)
|
|
440
|
-
return undefined;
|
|
441
|
-
if (contract) {
|
|
442
|
-
if (decision.text !== undefined)
|
|
443
|
-
throw new HarnessError("configuration.invalid", 'after("turn") must return output, not text, for an agent with an output schema');
|
|
444
|
-
const validation = contract.schema.validate(decision.output);
|
|
445
|
-
if (!validation.ok)
|
|
446
|
-
throw new HarnessError("output.invalid", `after("turn") output failed validation: ${validation.issues
|
|
447
|
-
.map((issue) => issue.message)
|
|
448
|
-
.join("; ")}`);
|
|
449
|
-
const value = copyJson(validation.value);
|
|
450
|
-
return {
|
|
451
|
-
candidate: { ...candidate, output: [{ type: "json", value }] },
|
|
452
|
-
output: value,
|
|
453
|
-
};
|
|
454
|
-
}
|
|
455
|
-
if (decision.output !== undefined)
|
|
456
|
-
throw new HarnessError("configuration.invalid", 'after("turn") must return text, not output, for an agent without an output schema');
|
|
457
|
-
const text = decision.text;
|
|
458
|
-
return {
|
|
459
|
-
candidate: { ...candidate, output: [{ type: "text", text }] },
|
|
460
|
-
output: text,
|
|
461
|
-
};
|
|
462
|
-
}
|
package/dist/loop/state.js
CHANGED
|
@@ -97,27 +97,7 @@ 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
|
+
turn: z.object({ turnId: id }).strict().optional(),
|
|
121
101
|
plan: z
|
|
122
102
|
.object({
|
|
123
103
|
turnId: id,
|
|
@@ -151,7 +131,7 @@ export function validateExecutionState(value) {
|
|
|
151
131
|
if (parsed.status === "paused" && !plan)
|
|
152
132
|
throw new HarnessError("execution.invalid-state", "Paused execution requires a pending plan");
|
|
153
133
|
if (plan && parsed.turn && parsed.turn.turnId !== plan.turnId)
|
|
154
|
-
throw new HarnessError("execution.invalid-state", "Turn
|
|
134
|
+
throw new HarnessError("execution.invalid-state", "Turn state does not belong to the pending plan's turn");
|
|
155
135
|
if (plan) {
|
|
156
136
|
const ids = new Set();
|
|
157
137
|
const invocations = new Set();
|
package/dist/loop/step/run.d.ts
CHANGED
|
@@ -1,23 +1,16 @@
|
|
|
1
|
-
import type { ExecutionSnapshot, StepRuntime
|
|
1
|
+
import type { ExecutionSnapshot, StepRuntime } 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";
|
|
9
8
|
export interface StepRunResult {
|
|
10
9
|
readonly stepId: string;
|
|
11
10
|
readonly candidate?: ModelCandidate;
|
|
12
11
|
readonly output: SealedStepOutput;
|
|
13
12
|
readonly requestedModelId?: string;
|
|
14
13
|
readonly modelInvocationId?: string;
|
|
15
|
-
/** Feedback when an after("step") hook asked a text-only answer to be redone. */
|
|
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;
|
|
21
14
|
}
|
|
22
15
|
export declare function runStep(input: {
|
|
23
16
|
agent: StepRuntime;
|
|
@@ -33,6 +26,4 @@ export declare function runStep(input: {
|
|
|
33
26
|
signal: AbortSignal;
|
|
34
27
|
info?: unknown;
|
|
35
28
|
output?: TurnOutputContract;
|
|
36
|
-
/** Turn-scoped hook state; omitted when the agent registers no hooks. */
|
|
37
|
-
turn?: StepTurnHooks;
|
|
38
29
|
}): Promise<StepRunResult>;
|
package/dist/loop/step/run.js
CHANGED
|
@@ -10,13 +10,9 @@ 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 { applyPatch, asDecisions, callHooks, combinePatches, layerPatches, mergeDecisions, } from "./hooks.js";
|
|
14
13
|
export async function runStep(input) {
|
|
15
14
|
let requestedModelId;
|
|
16
15
|
let modelInvocationId;
|
|
17
|
-
let retryFeedback;
|
|
18
|
-
let retried = false;
|
|
19
|
-
let turnPatch;
|
|
20
16
|
const stepInput = Object.freeze({
|
|
21
17
|
executionId: input.executionId,
|
|
22
18
|
turnId: input.turnId,
|
|
@@ -43,49 +39,6 @@ export async function runStep(input) {
|
|
|
43
39
|
input.signal.throwIfAborted();
|
|
44
40
|
if (context.currentTripwire)
|
|
45
41
|
return context.tripwire(context.currentTripwire);
|
|
46
|
-
const definition = input.agent.definition;
|
|
47
|
-
const turn = input.turn;
|
|
48
|
-
if (definition && turn) {
|
|
49
|
-
try {
|
|
50
|
-
const messages = projectModelCall(resolveModelRequest({
|
|
51
|
-
context,
|
|
52
|
-
arrivals: input.arrivals,
|
|
53
|
-
toolResults: input.toolResults,
|
|
54
|
-
output: input.output,
|
|
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;
|
|
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);
|
|
74
|
-
if (input.agent.recordAfterDynamics)
|
|
75
|
-
await input.agent.recordAfterDynamics();
|
|
76
|
-
if (step.block !== undefined)
|
|
77
|
-
return context.tripwire({ code: "dynamics.blocked", message: step.block });
|
|
78
|
-
applyPatch(configuration, layerPatches(patch, step.patch), 10_000);
|
|
79
|
-
}
|
|
80
|
-
catch (error) {
|
|
81
|
-
if (error instanceof HostSuspension)
|
|
82
|
-
throw error;
|
|
83
|
-
return context.tripwire({
|
|
84
|
-
code: isHarnessError(error) ? error.code : "configuration.invalid",
|
|
85
|
-
message: error instanceof Error ? error.message : String(error),
|
|
86
|
-
});
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
42
|
try {
|
|
90
43
|
const selected = configuration.snapshot();
|
|
91
44
|
for (const tool of selected.tools)
|
|
@@ -158,56 +111,8 @@ export async function runStep(input) {
|
|
|
158
111
|
},
|
|
159
112
|
});
|
|
160
113
|
const minted = context.mintFromModel(normalizeCandidate(outcome));
|
|
161
|
-
|
|
162
|
-
if (!candidate)
|
|
114
|
+
if (!context.currentCandidate)
|
|
163
115
|
throw new HarnessError("model.candidate-missing", "Model candidate missing after mint");
|
|
164
|
-
if (definition && turn) {
|
|
165
|
-
const text = candidate.output
|
|
166
|
-
?.filter((block) => block.type === "text")
|
|
167
|
-
.map((block) => block.text)
|
|
168
|
-
.join("");
|
|
169
|
-
const toolCalls = (candidate.output ?? [])
|
|
170
|
-
.filter((block) => block.type === "tool-call")
|
|
171
|
-
.map((block) => {
|
|
172
|
-
const call = block;
|
|
173
|
-
return { id: call.id, name: call.name, args: call.args };
|
|
174
|
-
});
|
|
175
|
-
const decision = mergeDecisions(asDecisions(await callHooks(definition, { at: "after", scope: "step" }, {
|
|
176
|
-
...(text ? { text } : {}),
|
|
177
|
-
toolCalls,
|
|
178
|
-
info: input.info,
|
|
179
|
-
state: { ...(input.agent.sessionState ?? {}) },
|
|
180
|
-
step: input.stepNumber - 1,
|
|
181
|
-
attempt: turn.afterStepAttempts,
|
|
182
|
-
}, `after-step:${input.stepId}`)));
|
|
183
|
-
if (input.agent.recordAfterDynamics)
|
|
184
|
-
await input.agent.recordAfterDynamics();
|
|
185
|
-
if (decision.block) {
|
|
186
|
-
return context.tripwire({ code: "dynamics.blocked", message: decision.block });
|
|
187
|
-
}
|
|
188
|
-
if (decision.retry) {
|
|
189
|
-
retried = true;
|
|
190
|
-
// Denied calls reach the model as tool results carrying the feedback.
|
|
191
|
-
if (toolCalls.length)
|
|
192
|
-
for (const call of toolCalls)
|
|
193
|
-
minted.deny(call.id, decision.retry);
|
|
194
|
-
else
|
|
195
|
-
retryFeedback = decision.retry;
|
|
196
|
-
return minted;
|
|
197
|
-
}
|
|
198
|
-
if (decision.text !== undefined) {
|
|
199
|
-
minted.replace({
|
|
200
|
-
output: [{ type: "text", text: decision.text }],
|
|
201
|
-
});
|
|
202
|
-
}
|
|
203
|
-
for (const item of decision.deny ?? [])
|
|
204
|
-
minted.deny(item.id, item.reason);
|
|
205
|
-
for (const item of decision.approve ?? [])
|
|
206
|
-
minted.requireInteraction(item.id, {
|
|
207
|
-
kind: "approval",
|
|
208
|
-
prompt: item.prompt,
|
|
209
|
-
});
|
|
210
|
-
}
|
|
211
116
|
return minted;
|
|
212
117
|
}
|
|
213
118
|
catch (error) {
|
|
@@ -221,8 +126,7 @@ export async function runStep(input) {
|
|
|
221
126
|
});
|
|
222
127
|
}
|
|
223
128
|
}, input.observe);
|
|
224
|
-
|
|
225
|
-
const output = sealStep(context, retryFeedback === undefined ? input.output : undefined);
|
|
129
|
+
const output = sealStep(context, input.output);
|
|
226
130
|
const candidate = output.kind === "tools" ? output.plan.candidate : context.currentCandidate;
|
|
227
131
|
return Object.freeze({
|
|
228
132
|
stepId: input.stepId,
|
|
@@ -230,9 +134,6 @@ export async function runStep(input) {
|
|
|
230
134
|
...(requestedModelId === undefined ? {} : { requestedModelId }),
|
|
231
135
|
output,
|
|
232
136
|
...(modelInvocationId ? { modelInvocationId } : {}),
|
|
233
|
-
...(retryFeedback ? { retry: retryFeedback } : {}),
|
|
234
|
-
...(retried ? { retried } : {}),
|
|
235
|
-
...(turnPatch === undefined ? {} : { turnPatch }),
|
|
236
137
|
});
|
|
237
138
|
}
|
|
238
139
|
function snapshotStepStart(input) {
|
|
@@ -1,33 +1,16 @@
|
|
|
1
1
|
import type { ToolRegistry } from "../../definition/registry.js";
|
|
2
|
-
import type { AgentDefinition } from "../../definition/agent-definition.js";
|
|
3
2
|
import type { ModelAdapter } from "@nylorun/core/define";
|
|
4
3
|
import type { InputEvent, TranscriptEntry } from "@nylorun/core/define";
|
|
5
4
|
import type { ToolResult } from "@nylorun/core/define";
|
|
6
5
|
import type { BoundMiddleware } from "@nylorun/core/define";
|
|
7
6
|
import type { JsonValue } from "@nylorun/core/define";
|
|
8
|
-
import type { CallPatch } from "./hooks.js";
|
|
9
7
|
/** Compiled definition pieces plus the per-run model adapter for one step. */
|
|
10
8
|
export interface StepRuntime {
|
|
11
9
|
readonly middleware: readonly BoundMiddleware[];
|
|
12
10
|
readonly invoke: ModelAdapter;
|
|
13
11
|
readonly registry: ToolRegistry;
|
|
14
|
-
/** Full definition for before/after hooks (optional for middleware-only agents). */
|
|
15
|
-
readonly definition?: AgentDefinition;
|
|
16
12
|
/** Mutable session memory bag shared with tools. */
|
|
17
13
|
sessionState?: Record<string, JsonValue>;
|
|
18
|
-
/** Called after hook results are applied so the host can record. */
|
|
19
|
-
recordAfterDynamics?: () => Promise<void>;
|
|
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
14
|
}
|
|
32
15
|
export interface StepInput {
|
|
33
16
|
readonly executionId: string;
|
package/dist/run/durable.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
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
|
-
import type {
|
|
5
|
-
import type { AgentRef,
|
|
4
|
+
import type { EffectOutcome } from "@nylorun/core/contracts";
|
|
5
|
+
import type { AgentRef, ApprovalMode } from "@nylorun/core/define";
|
|
6
6
|
import { ENGINE_VERSION } from "../compatibility.js";
|
|
7
7
|
/** Private persistence contract for hosts; this is not a session wire type. */
|
|
8
8
|
export interface DurableCheckpoint {
|
|
@@ -25,19 +25,13 @@ export interface HostEffect {
|
|
|
25
25
|
readonly manifestHash: string;
|
|
26
26
|
/**
|
|
27
27
|
* `delegation` journals when an agent used as a tool starts and settles; hosts record it and resolve it at once.
|
|
28
|
-
* Flow effects: `agent
|
|
28
|
+
* Flow effects: `agent` and `tool` (node) — each carries `path`, `key`, and `iterations`.
|
|
29
29
|
*/
|
|
30
|
-
readonly kind: "model" | "tool" | "
|
|
30
|
+
readonly kind: "model" | "tool" | "delegation" | "agent";
|
|
31
31
|
/** Set on work for an agent used as a tool; `agentId` stays the session's root agent. */
|
|
32
32
|
readonly agent?: AgentRef;
|
|
33
33
|
readonly capabilityId?: string;
|
|
34
34
|
readonly toolName?: string;
|
|
35
|
-
/** For `hook` effects: the hook point and every capability that registered it, in manifest order. */
|
|
36
|
-
readonly hook?: {
|
|
37
|
-
readonly at: HookAt;
|
|
38
|
-
readonly scope: HookScope;
|
|
39
|
-
readonly capabilityIds: readonly string[];
|
|
40
|
-
};
|
|
41
35
|
/** Workflow node path (flow effects). */
|
|
42
36
|
readonly path?: string;
|
|
43
37
|
/** Workflow node key without Map indices (flow effects). */
|
|
@@ -49,7 +43,7 @@ export interface HostEffect {
|
|
|
49
43
|
}
|
|
50
44
|
export type EffectResolution = {
|
|
51
45
|
readonly status: "completed";
|
|
52
|
-
readonly outcome:
|
|
46
|
+
readonly outcome: EffectOutcome;
|
|
53
47
|
} | {
|
|
54
48
|
readonly status: "pending" | "uncertain";
|
|
55
49
|
};
|
|
@@ -78,6 +72,8 @@ export interface DurableSessionTool {
|
|
|
78
72
|
readonly description?: string;
|
|
79
73
|
readonly inputSchema: JsonObject;
|
|
80
74
|
readonly outputSchema?: JsonObject;
|
|
75
|
+
/** `always`: each call waits for approval (a remote MCP server's `approval`). */
|
|
76
|
+
readonly approval?: ApprovalMode;
|
|
81
77
|
}
|
|
82
78
|
export declare function createDurableCheckpoint(input: {
|
|
83
79
|
manifest: AgentManifest;
|
package/dist/run/durable.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { HarnessError } from "@nylorun/core/define";
|
|
2
|
-
import { HOOK_POINTS, hasHook } from "@nylorun/core/define";
|
|
3
2
|
import { AgentManifestSchema } from "@nylorun/core/contracts";
|
|
4
|
-
import { agentFrom } from "@nylorun/core/define";
|
|
3
|
+
import { agentFrom, withHttpTarget } from "@nylorun/core/define";
|
|
5
4
|
import { definitionFor } from "../definition/agent-definition.js";
|
|
6
5
|
import { schemaFromJSON } from "@nylorun/core/define";
|
|
7
6
|
import { hashManifest } from "@nylorun/core/define";
|
|
@@ -79,6 +78,8 @@ export async function runDurable(options) {
|
|
|
79
78
|
...(tool.description === undefined ? {} : { description: tool.description }),
|
|
80
79
|
inputSchema: schemaFromJSON(tool.inputSchema),
|
|
81
80
|
...(tool.outputSchema ? { outputSchema: schemaFromJSON(tool.outputSchema) } : {}),
|
|
81
|
+
// Static approval: the engine asks before the call becomes an effect.
|
|
82
|
+
...(tool.approval === "always" ? { approval: () => true } : {}),
|
|
82
83
|
async execute(args, ctx) {
|
|
83
84
|
const previous = patchTail;
|
|
84
85
|
let release;
|
|
@@ -122,27 +123,29 @@ export async function runDurable(options) {
|
|
|
122
123
|
});
|
|
123
124
|
};
|
|
124
125
|
const sessionTools = options.sessionTools ?? [];
|
|
125
|
-
/** Rebuild one agent from its manifest with every tool
|
|
126
|
+
/** Rebuild one agent from its manifest with every tool routed through host effects. */
|
|
126
127
|
const hostedDefinition = (agent, ref) => {
|
|
127
128
|
const hostedTool = hostedTools(ref);
|
|
128
129
|
const owned = sessionTools.filter((tool) => (tool.agentId ?? manifest.id) === agent.id);
|
|
129
130
|
const implementations = {};
|
|
130
131
|
for (const capability of agent.capabilities) {
|
|
131
132
|
const tools = {};
|
|
132
|
-
// Agents used as tools are rebuilt from their manifest body; the engine runs them.
|
|
133
|
+
// Agents used as tools are rebuilt from their manifest body; the engine runs them. An
|
|
134
|
+
// HTTP tool keeps its target (the manifest's hash covers it) and runs as a host effect.
|
|
133
135
|
for (const tool of capability.tools ?? [])
|
|
134
|
-
if (
|
|
136
|
+
if (tool.http)
|
|
137
|
+
tools[tool.name] = withHttpTarget(hostedTool(capability.id, tool), {
|
|
138
|
+
http: tool.http,
|
|
139
|
+
...(tool.approval === undefined ? {} : { approval: tool.approval }),
|
|
140
|
+
});
|
|
141
|
+
else if (!tool.agent)
|
|
135
142
|
tools[tool.name] = hostedTool(capability.id, tool);
|
|
136
143
|
for (const tool of owned)
|
|
137
144
|
if (tool.capabilityId === capability.id)
|
|
138
145
|
tools[tool.name] = hostedTool(capability.id, tool);
|
|
139
|
-
implementations[capability.id] = {
|
|
140
|
-
tools,
|
|
141
|
-
// Hooks run through runHooks below, one effect per hook point; these only satisfy binding.
|
|
142
|
-
...hookPlaceholders(capability.hooks),
|
|
143
|
-
};
|
|
146
|
+
implementations[capability.id] = { tools };
|
|
144
147
|
}
|
|
145
|
-
|
|
148
|
+
return definitionFor(agentFrom(agent, implementations, owned.length === 0
|
|
146
149
|
? undefined
|
|
147
150
|
: {
|
|
148
151
|
sessionTools: owned.map((tool) => ({
|
|
@@ -150,18 +153,6 @@ export async function runDurable(options) {
|
|
|
150
153
|
name: tool.name,
|
|
151
154
|
})),
|
|
152
155
|
}));
|
|
153
|
-
// All capabilities registered at a hook point share one effect, so one Action delivery.
|
|
154
|
-
const runHooks = async ({ point, capabilityIds, args, identity }) => {
|
|
155
|
-
const outcome = await effect("hook", args, { info: checkpoint.info }, scoped(ref, identity), {
|
|
156
|
-
hook: { at: point.at, scope: point.scope, capabilityIds },
|
|
157
|
-
...(ref ? { agent: ref } : {}),
|
|
158
|
-
});
|
|
159
|
-
const results = outcome.value?.results;
|
|
160
|
-
return results !== null && typeof results === "object" && !Array.isArray(results)
|
|
161
|
-
? results
|
|
162
|
-
: {};
|
|
163
|
-
};
|
|
164
|
-
return Object.freeze({ ...definition, runHooks });
|
|
165
156
|
};
|
|
166
157
|
const modelCall = (ref) => async (call, ctx) => (await effect("model", call,
|
|
167
158
|
// The call already holds the whole prompt; journaling the request would store it twice.
|
|
@@ -217,13 +208,3 @@ export async function runDurable(options) {
|
|
|
217
208
|
function scoped(ref, identity) {
|
|
218
209
|
return ref ? `${ref.delegationId}/${identity}` : identity;
|
|
219
210
|
}
|
|
220
|
-
function hookPlaceholders(hooks) {
|
|
221
|
-
const placeholder = () => {
|
|
222
|
-
throw new HarnessError("execution.incompatible", "Hosted hooks run through the host effect");
|
|
223
|
-
};
|
|
224
|
-
const table = {};
|
|
225
|
-
for (const point of HOOK_POINTS)
|
|
226
|
-
if (hasHook(hooks, point.at, point.scope))
|
|
227
|
-
(table[point.at] ??= {})[point.scope] = placeholder;
|
|
228
|
-
return table;
|
|
229
|
-
}
|
package/dist/run/index.d.ts
CHANGED
|
@@ -29,9 +29,8 @@ export declare function bindingFromAgent(agent: BuiltAgent): RunBinding;
|
|
|
29
29
|
export { checkCompatibility, createExecutionState, validateExecutionState, execute };
|
|
30
30
|
export type { Implementations, ExecutionState, RunResult, RunOptions };
|
|
31
31
|
export { createDurableCheckpoint, runDurable } from "./durable.js";
|
|
32
|
-
export { createFlowCheckpoint, runFlowDurable } from "../flow/index.js";
|
|
32
|
+
export { createFlowCheckpoint, resumeFlowCheckpoint, runFlowDurable } from "../flow/index.js";
|
|
33
33
|
export type { DurableCheckpoint, DurableSessionTool, HostEffect, EffectResolution, DurableHost, DurableResult, } from "./durable.js";
|
|
34
|
-
export type { FlowCheckpoint } from "../flow/checkpoint.js";
|
|
35
|
-
export type { FlowDurableResult, FlowRunResult } from "../flow/types.js";
|
|
36
|
-
export { agentTurnValue, AGENT_TURN_MARKER, type AgentTurnValue } from "../flow/loop.js";
|
|
34
|
+
export type { FlowCheckpoint, FlowResume } from "../flow/checkpoint.js";
|
|
35
|
+
export type { FlowDurableResult, FlowInteraction, FlowRunResult } from "../flow/types.js";
|
|
37
36
|
export type { ModelAdapter, ModelCandidate, ModelCall, ModelRequest } from "@nylorun/core/define";
|
package/dist/run/index.js
CHANGED
|
@@ -36,5 +36,4 @@ export function bindingFromAgent(agent) {
|
|
|
36
36
|
}
|
|
37
37
|
export { checkCompatibility, createExecutionState, validateExecutionState, execute };
|
|
38
38
|
export { createDurableCheckpoint, runDurable } from "./durable.js";
|
|
39
|
-
export { createFlowCheckpoint, runFlowDurable } from "../flow/index.js";
|
|
40
|
-
export { agentTurnValue, AGENT_TURN_MARKER } from "../flow/loop.js";
|
|
39
|
+
export { createFlowCheckpoint, resumeFlowCheckpoint, runFlowDurable } from "../flow/index.js";
|
|
@@ -58,22 +58,9 @@ export interface ExecutionPlan {
|
|
|
58
58
|
readonly immediate: readonly ToolResult[];
|
|
59
59
|
readonly calls: readonly SavedToolCall[];
|
|
60
60
|
}
|
|
61
|
-
/**
|
|
62
|
-
export interface
|
|
61
|
+
/** The turn in flight, kept across a segment rollover or a crash. Cleared when the turn ends. */
|
|
62
|
+
export interface TurnState {
|
|
63
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
64
|
}
|
|
78
65
|
/** Versioned continuation data, not a live execution object. */
|
|
79
66
|
export interface ExecutionState {
|
|
@@ -90,10 +77,10 @@ export interface ExecutionState {
|
|
|
90
77
|
readonly plan?: ExecutionPlan;
|
|
91
78
|
/** Abandoned actions retained for reconciliation, never automatically dispatched. */
|
|
92
79
|
readonly cancelledCalls?: readonly SavedToolCall[];
|
|
93
|
-
/**
|
|
94
|
-
readonly turn?:
|
|
80
|
+
/** The current turn; present only while a turn continues in a later segment. */
|
|
81
|
+
readonly turn?: TurnState;
|
|
95
82
|
/**
|
|
96
|
-
* Durable session memory (tools write via `ctx.state
|
|
83
|
+
* Durable session memory (tools write via `ctx.state`).
|
|
97
84
|
* Runtime persists this with the checkpoint.
|
|
98
85
|
*/
|
|
99
86
|
readonly state?: JsonObject;
|