@nylorun/harness 0.22.1-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.
- package/CHANGELOG.md +84 -0
- package/HOST_CONTRACT.md +17 -19
- 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/flow/index.d.ts
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
export { createFlowCheckpoint, type FlowCheckpoint } from "./checkpoint.js";
|
|
1
|
+
export { createFlowCheckpoint, resumeFlowCheckpoint, type FlowCheckpoint, type FlowResume, } from "./checkpoint.js";
|
|
2
2
|
export { runFlowDurable } from "./engine.js";
|
|
3
|
-
export { runLoop, runLoopNode, agentTurnValue, AGENT_TURN_MARKER, type FlowDurableResult, type FlowRunResult, type AgentTurnValue, } from "./loop.js";
|
|
4
3
|
export { assertLoopIteration, assertMapItemCount, FLOW_OPERATOR_DEFAULTS, resolveOperatorLimits, type FlowOperatorLimits, } from "./limits.js";
|
|
5
|
-
export { flowEffectId, iterationsOf,
|
|
6
|
-
export {
|
|
7
|
-
export { FlowNodeError, failedValueOf } from "./types.js";
|
|
4
|
+
export { flowEffectId, iterationsOf, nodeKeyOf } from "./paths.js";
|
|
5
|
+
export { FlowNodeError, failedValueOf, type FlowDurableResult, type FlowInteraction, type FlowRunResult, } from "./types.js";
|
package/dist/flow/index.js
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
export { createFlowCheckpoint } from "./checkpoint.js";
|
|
1
|
+
export { createFlowCheckpoint, resumeFlowCheckpoint, } from "./checkpoint.js";
|
|
2
2
|
export { runFlowDurable } from "./engine.js";
|
|
3
|
-
export { runLoop, runLoopNode, agentTurnValue, AGENT_TURN_MARKER, } from "./loop.js";
|
|
4
3
|
export { assertLoopIteration, assertMapItemCount, FLOW_OPERATOR_DEFAULTS, resolveOperatorLimits, } from "./limits.js";
|
|
5
|
-
export { flowEffectId, iterationsOf,
|
|
6
|
-
export {
|
|
7
|
-
export { FlowNodeError, failedValueOf } from "./types.js";
|
|
4
|
+
export { flowEffectId, iterationsOf, nodeKeyOf } from "./paths.js";
|
|
5
|
+
export { FlowNodeError, failedValueOf, } from "./types.js";
|
package/dist/flow/paths.d.ts
CHANGED
|
@@ -1,18 +1,11 @@
|
|
|
1
1
|
/** Path, node key and iteration-vector helpers (workflows.md §6). */
|
|
2
|
-
export declare function joinPath(parent: string, part: string): string;
|
|
3
|
-
/**
|
|
4
|
-
* Map item path: `<map path>[index]/<each id>` (workflows.md §6).
|
|
5
|
-
* Example: `implement[2]/code`.
|
|
6
|
-
*/
|
|
7
|
-
export declare function mapItemPath(mapPath: string, index: number, eachId: string): string;
|
|
8
2
|
/** Drop Map indices from a path to get the node key. */
|
|
9
3
|
export declare function nodeKeyOf(path: string): string;
|
|
10
4
|
/** Iteration vector string: enclosing Loop numbers outermost first, or "-" outside Loops. */
|
|
11
5
|
export declare function iterationsOf(vector: readonly number[]): string;
|
|
12
6
|
/**
|
|
13
7
|
* Effect id for a flow effect (workflows.md §10).
|
|
14
|
-
* `role` separates two effects of one kind on one path, e.g. a
|
|
15
|
-
* and the Map `over` or Switch `on` it wraps.
|
|
8
|
+
* `role` separates two effects of one kind on one path, e.g. a tool node's runs after it asked.
|
|
16
9
|
*/
|
|
17
10
|
export declare function flowEffectId(input: {
|
|
18
11
|
readonly turnId: string;
|
package/dist/flow/paths.js
CHANGED
|
@@ -1,14 +1,4 @@
|
|
|
1
1
|
/** Path, node key and iteration-vector helpers (workflows.md §6). */
|
|
2
|
-
export function joinPath(parent, part) {
|
|
3
|
-
return parent ? `${parent}/${part}` : part;
|
|
4
|
-
}
|
|
5
|
-
/**
|
|
6
|
-
* Map item path: `<map path>[index]/<each id>` (workflows.md §6).
|
|
7
|
-
* Example: `implement[2]/code`.
|
|
8
|
-
*/
|
|
9
|
-
export function mapItemPath(mapPath, index, eachId) {
|
|
10
|
-
return `${mapPath}[${index}]/${eachId}`;
|
|
11
|
-
}
|
|
12
2
|
/** Drop Map indices from a path to get the node key. */
|
|
13
3
|
export function nodeKeyOf(path) {
|
|
14
4
|
return path.replace(/\[\d+]/g, "");
|
|
@@ -19,8 +9,7 @@ export function iterationsOf(vector) {
|
|
|
19
9
|
}
|
|
20
10
|
/**
|
|
21
11
|
* Effect id for a flow effect (workflows.md §10).
|
|
22
|
-
* `role` separates two effects of one kind on one path, e.g. a
|
|
23
|
-
* and the Map `over` or Switch `on` it wraps.
|
|
12
|
+
* `role` separates two effects of one kind on one path, e.g. a tool node's runs after it asked.
|
|
24
13
|
*/
|
|
25
14
|
export function flowEffectId(input) {
|
|
26
15
|
const kind = input.role === undefined ? input.kind : `${input.kind}.${input.role}`;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { JsonValue } from "@nylorun/core/define";
|
|
2
|
+
import type { FlowContext } from "./context.js";
|
|
3
|
+
/**
|
|
4
|
+
* A tool node's settled value, through its waits. A tool that asks (`ctx.approve`, `ctx.ask`)
|
|
5
|
+
* settles `interaction-required` with a resume token: the flow pauses on it. Once the
|
|
6
|
+
* checkpoint holds the answer (`FlowCheckpoint.resumes`), the tool runs again as a new effect
|
|
7
|
+
* of the node (role `resume.<n>`) with the answer and the token. A rejected approval settles
|
|
8
|
+
* the node `denied` without running the tool again, as in the turn loop.
|
|
9
|
+
*/
|
|
10
|
+
export declare function runToolEffect(ctx: FlowContext, toolName: string, input: JsonValue, identity: {
|
|
11
|
+
readonly path: string;
|
|
12
|
+
readonly key: string;
|
|
13
|
+
readonly iterations: string;
|
|
14
|
+
}): Promise<JsonValue>;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { FlowNodeError } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* A tool node's settled value, through its waits. A tool that asks (`ctx.approve`, `ctx.ask`)
|
|
4
|
+
* settles `interaction-required` with a resume token: the flow pauses on it. Once the
|
|
5
|
+
* checkpoint holds the answer (`FlowCheckpoint.resumes`), the tool runs again as a new effect
|
|
6
|
+
* of the node (role `resume.<n>`) with the answer and the token. A rejected approval settles
|
|
7
|
+
* the node `denied` without running the tool again, as in the turn loop.
|
|
8
|
+
*/
|
|
9
|
+
export async function runToolEffect(ctx, toolName, input, identity) {
|
|
10
|
+
let context = { toolName };
|
|
11
|
+
for (let attempt = 0;; attempt += 1) {
|
|
12
|
+
const at = attempt === 0 ? identity : { ...identity, role: `resume.${attempt}` };
|
|
13
|
+
const value = (await ctx.effect("tool", input, at, context));
|
|
14
|
+
const asked = askedOf(value, identity.path);
|
|
15
|
+
if (!asked)
|
|
16
|
+
return value;
|
|
17
|
+
const invocationId = ctx.effectIdOf("tool", at);
|
|
18
|
+
const id = `${invocationId}:interaction`;
|
|
19
|
+
const answer = ctx.checkpoint.resumes?.[id];
|
|
20
|
+
if (!answer)
|
|
21
|
+
throw ctx.pause({
|
|
22
|
+
invocationId,
|
|
23
|
+
path: identity.path,
|
|
24
|
+
toolName,
|
|
25
|
+
interaction: { ...asked.interaction, id },
|
|
26
|
+
status: "interaction",
|
|
27
|
+
});
|
|
28
|
+
if (answer.kind === "approval" && !answer.approved)
|
|
29
|
+
return { kind: "denied", reason: "Approval rejected" };
|
|
30
|
+
context = {
|
|
31
|
+
toolName,
|
|
32
|
+
resume: {
|
|
33
|
+
interactionId: id,
|
|
34
|
+
...answer,
|
|
35
|
+
...(asked.token === undefined ? {} : { token: asked.token }),
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** The interaction an `interaction-required` outcome asks for, or undefined for any other value. */
|
|
41
|
+
function askedOf(raw, path) {
|
|
42
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
43
|
+
return undefined;
|
|
44
|
+
const value = raw;
|
|
45
|
+
if (value.kind !== "interaction-required")
|
|
46
|
+
return undefined;
|
|
47
|
+
const interaction = value.interaction;
|
|
48
|
+
if (!interaction ||
|
|
49
|
+
(interaction.kind !== "approval" && interaction.kind !== "response") ||
|
|
50
|
+
typeof interaction.prompt !== "string")
|
|
51
|
+
throw new FlowNodeError({
|
|
52
|
+
code: "tool.invalid-tool-result",
|
|
53
|
+
message: "Tool returned an invalid interaction",
|
|
54
|
+
path,
|
|
55
|
+
});
|
|
56
|
+
const metadata = interaction.metadata;
|
|
57
|
+
return {
|
|
58
|
+
interaction: {
|
|
59
|
+
kind: interaction.kind,
|
|
60
|
+
prompt: interaction.prompt,
|
|
61
|
+
...(metadata && typeof metadata === "object" && !Array.isArray(metadata)
|
|
62
|
+
? { metadata: metadata }
|
|
63
|
+
: {}),
|
|
64
|
+
},
|
|
65
|
+
...(value.token === undefined ? {} : { token: value.token }),
|
|
66
|
+
};
|
|
67
|
+
}
|
package/dist/flow/types.d.ts
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
|
-
import type { JsonValue } from "@nylorun/core/define";
|
|
1
|
+
import type { JsonObject, JsonValue } from "@nylorun/core/define";
|
|
2
|
+
import { HostSuspension } from "../loop/host-suspension.js";
|
|
2
3
|
import type { FlowCheckpoint } from "./checkpoint.js";
|
|
4
|
+
/**
|
|
5
|
+
* An interaction the flow itself waits on: a tool node that asked (`ctx.approve`, `ctx.ask`).
|
|
6
|
+
* The tool's resume token stays in its journaled outcome, never here.
|
|
7
|
+
*/
|
|
8
|
+
export type FlowInteraction = {
|
|
9
|
+
/** The effect of the tool run that asked. */
|
|
10
|
+
readonly invocationId: string;
|
|
11
|
+
/** The tool node's path. */
|
|
12
|
+
readonly path: string;
|
|
13
|
+
readonly toolName: string;
|
|
14
|
+
readonly interaction: {
|
|
15
|
+
readonly id: string;
|
|
16
|
+
readonly kind: "approval" | "response";
|
|
17
|
+
readonly prompt: string;
|
|
18
|
+
readonly metadata?: JsonObject;
|
|
19
|
+
};
|
|
20
|
+
readonly status: "interaction";
|
|
21
|
+
};
|
|
3
22
|
export type FlowRunResult = {
|
|
4
23
|
readonly status: "completed";
|
|
5
24
|
readonly output: JsonValue;
|
|
@@ -14,7 +33,7 @@ export type FlowRunResult = {
|
|
|
14
33
|
readonly status: "cancelled";
|
|
15
34
|
} | {
|
|
16
35
|
readonly status: "paused";
|
|
17
|
-
readonly pending:
|
|
36
|
+
readonly pending: readonly FlowInteraction[];
|
|
18
37
|
};
|
|
19
38
|
export type FlowDurableResult = {
|
|
20
39
|
readonly status: "waiting" | "uncertain";
|
|
@@ -41,5 +60,13 @@ export declare class FlowNodeError extends Error {
|
|
|
41
60
|
readonly failure: FlowFailure;
|
|
42
61
|
constructor(failure: FlowFailure);
|
|
43
62
|
}
|
|
44
|
-
/**
|
|
63
|
+
/**
|
|
64
|
+
* A tool node waits on an interaction. Unwinds like a suspension (siblings keep running), and
|
|
65
|
+
* the flow pauses once nothing else is pending.
|
|
66
|
+
*/
|
|
67
|
+
export declare class FlowPause extends HostSuspension {
|
|
68
|
+
readonly interaction: FlowInteraction;
|
|
69
|
+
constructor(interaction: FlowInteraction);
|
|
70
|
+
}
|
|
71
|
+
/** Completed effect value that encodes a curated failure (a tool's failure / agent settle). */
|
|
45
72
|
export declare function failedValueOf(value: unknown): FlowFailure | undefined;
|
package/dist/flow/types.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { HostSuspension } from "../loop/host-suspension.js";
|
|
1
2
|
/** Thrown when a node fails; unwinds to the engine root. */
|
|
2
3
|
export class FlowNodeError extends Error {
|
|
3
4
|
failure;
|
|
@@ -7,7 +8,19 @@ export class FlowNodeError extends Error {
|
|
|
7
8
|
this.name = "FlowNodeError";
|
|
8
9
|
}
|
|
9
10
|
}
|
|
10
|
-
/**
|
|
11
|
+
/**
|
|
12
|
+
* A tool node waits on an interaction. Unwinds like a suspension (siblings keep running), and
|
|
13
|
+
* the flow pauses once nothing else is pending.
|
|
14
|
+
*/
|
|
15
|
+
export class FlowPause extends HostSuspension {
|
|
16
|
+
interaction;
|
|
17
|
+
constructor(interaction) {
|
|
18
|
+
super(interaction.invocationId, "pending");
|
|
19
|
+
this.interaction = interaction;
|
|
20
|
+
this.name = "FlowPause";
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/** Completed effect value that encodes a curated failure (a tool's failure / agent settle). */
|
|
11
24
|
export function failedValueOf(value) {
|
|
12
25
|
if (!value || typeof value !== "object")
|
|
13
26
|
return undefined;
|
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) {
|