@nylorun/harness 0.17.0-beta → 0.18.0-beta
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/HOST_CONTRACT.md +2 -0
- package/dist/loop/delegation.d.ts +32 -0
- package/dist/loop/delegation.js +136 -0
- package/dist/loop/dispatch.js +56 -0
- package/dist/loop/invocation.d.ts +7 -1
- package/dist/loop/invocation.js +2 -0
- package/dist/loop/run.d.ts +2 -1
- package/dist/loop/run.js +2 -2
- package/dist/run/durable.d.ts +7 -2
- package/dist/run/durable.js +109 -81
- package/dist/types/execution.d.ts +3 -1
- package/dist/utils/ids.d.ts +2 -0
- package/dist/utils/ids.js +5 -0
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.18.0-beta
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 1cd7dc7: Add subagents: put an agent in another agent's `tools` (`Agent({ tools: [lookupOrder, researcher] })` or `.use({ tools: [researcher] })`) and the model can delegate to it. The tool is named after the agent's id, takes `{ task: string }`, and its description is the agent's `description`, which is now required for an agent used as a tool. The engine runs the child inside the parent's turn as a durable branch: fresh context, its own tools and hooks served by the root agent's executor, its own MCP servers, the session's sandbox, and only its final output (or `outputSchema` result) returned. Empty output, failures (with partial output marked as evidence), and requests for input or approval inside a child reach the parent as failed tool results. Parallel delegation calls run concurrently, completed child work is never re-run on replay, and cancelling the session cancels every child.
|
|
8
|
+
|
|
9
|
+
v1 is one level deep and non-interactive. Nested delegation, child tools that declare `approval`, and differing sandboxes across the tree fail the build with a named diagnostic. The manifest adds an optional `agent` body on a tool (schema version unchanged), actions and effects carry `agent: { id, path, delegationId }`, tool context gains `ctx.agent`, the durable host resolves a new `delegation` effect kind, and the Runtime emits `delegation.started` / `delegation.completed` events and filters history with `?agent=` (`session.history({ agent })`). Studio shows delegations, labels child actions with their agent, and filters events by agent.
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- Pin core to the tested release.
|
|
14
|
+
- Updated dependencies [1cd7dc7]
|
|
15
|
+
- @nylorun/core@0.4.0-beta
|
|
16
|
+
|
|
3
17
|
## 0.17.0-beta
|
|
4
18
|
|
|
5
19
|
### Minor Changes
|
package/HOST_CONTRACT.md
CHANGED
|
@@ -22,6 +22,8 @@ A terminal/paused result includes `result.state`. Save it. A new message uses a
|
|
|
22
22
|
|
|
23
23
|
Host resolveEffect must bind the effect ID to the original request and reject drift. Intent/outcome, action transitions, checkpoint settlement and canonical event/outbox writes must use runtime transactions. Restate journals individual effect boundaries, not the loop. Scheduling, storage, publication, lease policy and reconciliation remain runtime-owned.
|
|
24
24
|
|
|
25
|
+
Agents used as tools: a manifest tool with an `agent` body (the child manifest inlined; name equals the child id, description equals the child description, input is the standard `{task}` schema, no outputSchema, no nested agent tools, identical sandbox specs across the tree) is run by the engine inside the parent's `runDurable`, never by an executor. Its model, tool and hook effects carry `agent: {id, path, delegationId}` (`delegationId` is the parent tool call's invocationId), keep the root `agentId` and `manifestHash`, and use identity `<delegationId>/<inner identity>`; tool context `idempotencyKey` is prefixed the same way. Hosts resolve child effects against the child manifest (`delegateManifest`) for pinned tool schemas, sandbox and MCP routing, copy `agent` onto the Action, and include it in action event payloads. A `delegation` effect (identity `<delegationId>:started` or `<delegationId>:settled`, input `{task}` or `{status, outcome}`) must be recorded completed immediately with value null and publish `delegation.started` / `delegation.completed` exactly once; the journal makes replays silent. `DurableSessionTool.agentId` attaches discovered MCP tools to a child; MCP snapshot records and diagnostics carry `agentId`, and child plugin roots are keyed `<childId>/<capabilityId>`. Children share the session sandbox. `GET /v1/sessions/:id/items?agent=` filters history by `payload.agent.delegationId` or `payload.agent.path`. Existing checkpoints are unaffected; engine version stays `hosted-2`.
|
|
26
|
+
|
|
25
27
|
## Definitions, validation, compatibility
|
|
26
28
|
|
|
27
29
|
`/define` is execution-free and browser-bundleable; Agent has no `.run()`. Explicit local execution uses `/run` run + bindingFromAgent(agent.build()). `/contracts` never imports checkpoint internals. Tools and before/after hooks are supported remotely. Arbitrary legacy middleware closures are rejected for durable definitions because they cannot be reconstructed from manifests. JSON schemas are reconstructed through Zod's JSON Schema importer; unsupported schemas fail closed. The original manifest document must survive reconstruction. Runtime is the only hasher: it hashes the accepted manifest and pins that digest on the session and on each action. Agents do not hash. Model configuration is host-owned. The executor claims by agent id. Runtime checks a successful tool result against the output schema copied onto the action and stores a schema mismatch as a failed outcome on a completed action.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { AgentRef, Delegate, JsonObject, JsonValue, ModelAdapter, ToolOutcome } from "@nylorun/core/define";
|
|
2
|
+
import type { AgentDefinition } from "../definition/agent-definition.js";
|
|
3
|
+
import type { RunOptions, RunResult } from "../types/execution.js";
|
|
4
|
+
import type { Invocation } from "./invocation.js";
|
|
5
|
+
/** How one agent used as a tool is built and journaled. Durable hosts supply their own. */
|
|
6
|
+
export interface DelegationHost {
|
|
7
|
+
child(delegate: Delegate, ref: AgentRef): {
|
|
8
|
+
readonly definition: AgentDefinition;
|
|
9
|
+
readonly onModelCall: ModelAdapter;
|
|
10
|
+
};
|
|
11
|
+
/** Journal a lifecycle point exactly once. Local runs have nothing to journal. */
|
|
12
|
+
announce?(phase: "started" | "settled", ref: AgentRef, payload: JsonObject): Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
/** Engine-internal options for execute(); not part of the public RunOptions. */
|
|
15
|
+
export interface ExecuteInternals {
|
|
16
|
+
readonly delegation?: DelegationHost;
|
|
17
|
+
/** Set when this invocation is an agent used as a tool. */
|
|
18
|
+
readonly delegated?: AgentRef;
|
|
19
|
+
}
|
|
20
|
+
/** Codes are curated: a child's provider error bodies never reach the parent's context. */
|
|
21
|
+
export declare const INTERACTION_UNSUPPORTED = "Agents used as tools can't ask for input, approval or a wait yet; do this work on the parent agent.";
|
|
22
|
+
/** In-process children, built from the authored agent and sharing the parent's model callable. */
|
|
23
|
+
export declare function localDelegation(onModelCall: ModelAdapter): DelegationHost;
|
|
24
|
+
/** Run one agent used as a tool to settlement. Only its final output returns to the parent. */
|
|
25
|
+
export declare function runDelegation(invocation: Invocation, execute: (agent: AgentDefinition, options: RunOptions<any>, internals: ExecuteInternals) => Promise<RunResult<JsonValue>>, call: {
|
|
26
|
+
readonly turnId: string;
|
|
27
|
+
readonly stepId: string;
|
|
28
|
+
readonly callId: string;
|
|
29
|
+
readonly invocationId: string;
|
|
30
|
+
readonly toolName: string;
|
|
31
|
+
readonly args: JsonValue;
|
|
32
|
+
}, delegate: Delegate): Promise<ToolOutcome>;
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { HarnessError, isHarnessError } from "@nylorun/core/define";
|
|
2
|
+
import { definitionFromBinding } from "../definition/agent-definition.js";
|
|
3
|
+
import { withNestedIds } from "../utils/ids.js";
|
|
4
|
+
import { initializeExecutionState } from "./initial-state.js";
|
|
5
|
+
import { textFromOutput } from "./model/normalize.js";
|
|
6
|
+
import { HostSuspension } from "./host-suspension.js";
|
|
7
|
+
/** Codes are curated: a child's provider error bodies never reach the parent's context. */
|
|
8
|
+
export const INTERACTION_UNSUPPORTED = "Agents used as tools can't ask for input, approval or a wait yet; do this work on the parent agent.";
|
|
9
|
+
const PARTIAL_LIMIT = 4_000;
|
|
10
|
+
/** In-process children, built from the authored agent and sharing the parent's model callable. */
|
|
11
|
+
export function localDelegation(onModelCall) {
|
|
12
|
+
return {
|
|
13
|
+
child(delegate, ref) {
|
|
14
|
+
if (!delegate.agent)
|
|
15
|
+
throw new HarnessError("execution.invalid-input", `Agent '${ref.id}' is used as a tool but has no local implementation; build the parent from authored agents`);
|
|
16
|
+
return { definition: definitionFromBinding(delegate.agent.getBinding()), onModelCall };
|
|
17
|
+
},
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
/** Run one agent used as a tool to settlement. Only its final output returns to the parent. */
|
|
21
|
+
export async function runDelegation(invocation, execute, call, delegate) {
|
|
22
|
+
const { signal, options } = invocation;
|
|
23
|
+
const ref = {
|
|
24
|
+
id: delegate.manifest.id,
|
|
25
|
+
path: `${invocation.agent.id}/${delegate.manifest.id}`,
|
|
26
|
+
delegationId: call.invocationId,
|
|
27
|
+
};
|
|
28
|
+
const ids = {
|
|
29
|
+
turnId: call.turnId,
|
|
30
|
+
stepId: call.stepId,
|
|
31
|
+
callId: call.callId,
|
|
32
|
+
invocationId: call.invocationId,
|
|
33
|
+
toolName: call.toolName,
|
|
34
|
+
agent: ref,
|
|
35
|
+
};
|
|
36
|
+
const task = call.args.task;
|
|
37
|
+
const host = invocation.delegation ?? localDelegation(options.onModelCall);
|
|
38
|
+
await host.announce?.("started", ref, { task });
|
|
39
|
+
invocation.observe({ type: "delegation.started", ...ids, attributes: { task } });
|
|
40
|
+
let outcome;
|
|
41
|
+
let status = "failed";
|
|
42
|
+
try {
|
|
43
|
+
const child = host.child(delegate, ref);
|
|
44
|
+
const listener = options.onEvent;
|
|
45
|
+
const result = await withNestedIds(call.invocationId, () => execute(child.definition, {
|
|
46
|
+
input: task,
|
|
47
|
+
onModelCall: child.onModelCall,
|
|
48
|
+
signal,
|
|
49
|
+
...(options.info === undefined ? {} : { info: options.info }),
|
|
50
|
+
state: initializeExecutionState(child.definition, {
|
|
51
|
+
executionId: `${invocation.state.executionId}/${call.invocationId}`,
|
|
52
|
+
}),
|
|
53
|
+
...(listener ? { onEvent: (event) => listener({ ...event, agent: ref }) } : {}),
|
|
54
|
+
}, { delegated: ref }));
|
|
55
|
+
status = result.status;
|
|
56
|
+
outcome = settle(result);
|
|
57
|
+
}
|
|
58
|
+
catch (cause) {
|
|
59
|
+
// Durable hosts suspend children mid-flight; that must escape to the parent journal.
|
|
60
|
+
if (cause instanceof HostSuspension)
|
|
61
|
+
throw cause;
|
|
62
|
+
// Construction or setup failures still settle the journaled delegation; the parent
|
|
63
|
+
// sees the same failed tool result as an empty or crashed child.
|
|
64
|
+
if (isHarnessError(cause))
|
|
65
|
+
outcome = { kind: "failed", code: cause.code, message: cause.message };
|
|
66
|
+
else if (cause instanceof Error)
|
|
67
|
+
outcome = { kind: "failed", code: "delegation.failed", message: cause.message };
|
|
68
|
+
else
|
|
69
|
+
outcome = { kind: "failed", code: "delegation.failed", message: String(cause) };
|
|
70
|
+
}
|
|
71
|
+
await host.announce?.("settled", ref, {
|
|
72
|
+
status,
|
|
73
|
+
outcome: outcome,
|
|
74
|
+
});
|
|
75
|
+
invocation.observe({
|
|
76
|
+
type: "delegation.completed",
|
|
77
|
+
...ids,
|
|
78
|
+
status,
|
|
79
|
+
attributes: outcome.kind === "completed"
|
|
80
|
+
? {
|
|
81
|
+
callId: call.callId,
|
|
82
|
+
toolName: call.toolName,
|
|
83
|
+
kind: "completed",
|
|
84
|
+
output: outcome.output,
|
|
85
|
+
}
|
|
86
|
+
: {
|
|
87
|
+
callId: call.callId,
|
|
88
|
+
toolName: call.toolName,
|
|
89
|
+
kind: "failed",
|
|
90
|
+
code: outcome.code,
|
|
91
|
+
message: outcome.message,
|
|
92
|
+
},
|
|
93
|
+
});
|
|
94
|
+
return outcome;
|
|
95
|
+
}
|
|
96
|
+
/** "Done" means settled with real output; empty or unfinished work is a failure with evidence. */
|
|
97
|
+
function settle(result) {
|
|
98
|
+
if (result.status === "completed") {
|
|
99
|
+
const output = result.output;
|
|
100
|
+
if (output === null || (typeof output === "string" && output.trim() === ""))
|
|
101
|
+
return {
|
|
102
|
+
kind: "failed",
|
|
103
|
+
code: "delegation.empty-output",
|
|
104
|
+
message: "The agent finished without an answer.",
|
|
105
|
+
};
|
|
106
|
+
return { kind: "completed", output };
|
|
107
|
+
}
|
|
108
|
+
if (result.status === "cancelled")
|
|
109
|
+
return { kind: "failed", code: "tool.cancelled", message: "The agent was cancelled." };
|
|
110
|
+
if (result.status === "paused")
|
|
111
|
+
return {
|
|
112
|
+
kind: "failed",
|
|
113
|
+
code: "delegation.interaction-unsupported",
|
|
114
|
+
message: INTERACTION_UNSUPPORTED,
|
|
115
|
+
};
|
|
116
|
+
const reason = result.error.code;
|
|
117
|
+
const curated = reason.startsWith("execution.") ? reason : `${reason}: ${result.error.message}`;
|
|
118
|
+
const partial = lastText(result);
|
|
119
|
+
return {
|
|
120
|
+
kind: "failed",
|
|
121
|
+
code: "delegation.failed",
|
|
122
|
+
message: `The agent failed (${curated}).` +
|
|
123
|
+
(partial ? `\nPartial output (evidence, not an answer):\n${partial}` : ""),
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
function lastText(result) {
|
|
127
|
+
for (let index = result.state.transcript.length - 1; index >= 0; index--) {
|
|
128
|
+
const entry = result.state.transcript[index];
|
|
129
|
+
if (entry.kind !== "candidate")
|
|
130
|
+
continue;
|
|
131
|
+
const text = textFromOutput(entry.candidate.output).trim();
|
|
132
|
+
if (text)
|
|
133
|
+
return text.length > PARTIAL_LIMIT ? `${text.slice(0, PARTIAL_LIMIT)}…` : text;
|
|
134
|
+
}
|
|
135
|
+
return undefined;
|
|
136
|
+
}
|
package/dist/loop/dispatch.js
CHANGED
|
@@ -6,9 +6,25 @@ import { copyJson } from "@nylorun/core/define";
|
|
|
6
6
|
import { createSessionStateBag } from "./initial-state.js";
|
|
7
7
|
import { toolResult } from "./tool-result.js";
|
|
8
8
|
import { isWaitSignal, WaitSignal } from "./waits.js";
|
|
9
|
+
import { INTERACTION_UNSUPPORTED, runDelegation } from "./delegation.js";
|
|
10
|
+
import { execute } from "./run.js";
|
|
9
11
|
export async function dispatchPlan(invocation) {
|
|
10
12
|
const { signal, definitions, options, observe, record } = invocation;
|
|
11
13
|
let plan = invocation.state.plan;
|
|
14
|
+
if (invocation.delegated && plan.calls.some((call) => call.status === "interaction")) {
|
|
15
|
+
// Agents used as tools can't pause; the model sees why and can continue without the call.
|
|
16
|
+
plan = {
|
|
17
|
+
...plan,
|
|
18
|
+
calls: plan.calls.map((call) => call.status === "interaction"
|
|
19
|
+
? copyJson({
|
|
20
|
+
...call,
|
|
21
|
+
status: "settled",
|
|
22
|
+
result: unsupported(call.callId, call.toolName),
|
|
23
|
+
})
|
|
24
|
+
: call),
|
|
25
|
+
};
|
|
26
|
+
invocation.state = { ...invocation.state, plan };
|
|
27
|
+
}
|
|
12
28
|
if (plan.calls.some((call) => call.status === "interaction" && call.interactionPhase === "before")) {
|
|
13
29
|
for (const call of plan.calls)
|
|
14
30
|
if (call.status === "interaction")
|
|
@@ -61,6 +77,16 @@ export async function dispatchPlan(invocation) {
|
|
|
61
77
|
let outcome;
|
|
62
78
|
try {
|
|
63
79
|
signal.throwIfAborted();
|
|
80
|
+
if (definition.delegate) {
|
|
81
|
+
const result = toolResult(call, definition, await runDelegation(invocation, execute, { ...eventIds, args: call.args }, definition.delegate));
|
|
82
|
+
observe({
|
|
83
|
+
type: "tool.completed",
|
|
84
|
+
...eventIds,
|
|
85
|
+
outcome: result.kind,
|
|
86
|
+
attributes: result,
|
|
87
|
+
});
|
|
88
|
+
return copyJson({ ...call, status: "settled", result });
|
|
89
|
+
}
|
|
64
90
|
if (definition.approval && !call.resume) {
|
|
65
91
|
const decision = await definition.approval(call.args);
|
|
66
92
|
const prompt = typeof decision === "string"
|
|
@@ -101,6 +127,10 @@ export async function dispatchPlan(invocation) {
|
|
|
101
127
|
...(redelivering || call.status === "active" ? { redelivery: true } : {}),
|
|
102
128
|
state: stateApi,
|
|
103
129
|
session: { id: invocation.state.executionId },
|
|
130
|
+
agent: invocation.delegated ?? {
|
|
131
|
+
id: invocation.agent.id,
|
|
132
|
+
path: invocation.agent.id,
|
|
133
|
+
},
|
|
104
134
|
progress(message, data) {
|
|
105
135
|
observe({
|
|
106
136
|
type: "tool.progress",
|
|
@@ -161,6 +191,13 @@ export async function dispatchPlan(invocation) {
|
|
|
161
191
|
outcome = normalizeOutcome(raw);
|
|
162
192
|
if (!outcome || typeof outcome !== "object")
|
|
163
193
|
throw new HarnessError("tool.invalid-tool-result", "Tool returned an invalid outcome");
|
|
194
|
+
if (invocation.delegated &&
|
|
195
|
+
(outcome.kind === "interaction-required" || outcome.kind === "deferred"))
|
|
196
|
+
outcome = {
|
|
197
|
+
kind: "failed",
|
|
198
|
+
code: "delegation.interaction-unsupported",
|
|
199
|
+
message: INTERACTION_UNSUPPORTED,
|
|
200
|
+
};
|
|
164
201
|
if (outcome.kind === "interaction-required") {
|
|
165
202
|
if (!["approval", "response"].includes(outcome.interaction.kind) ||
|
|
166
203
|
typeof outcome.interaction.prompt !== "string")
|
|
@@ -200,6 +237,16 @@ export async function dispatchPlan(invocation) {
|
|
|
200
237
|
catch (cause) {
|
|
201
238
|
if (cause instanceof HostSuspension)
|
|
202
239
|
throw cause;
|
|
240
|
+
if (isWaitSignal(cause) && invocation.delegated) {
|
|
241
|
+
const result = unsupported(call.callId, call.toolName);
|
|
242
|
+
observe({
|
|
243
|
+
type: "tool.completed",
|
|
244
|
+
...eventIds,
|
|
245
|
+
outcome: result.kind,
|
|
246
|
+
attributes: result,
|
|
247
|
+
});
|
|
248
|
+
return copyJson({ ...call, status: "settled", result });
|
|
249
|
+
}
|
|
203
250
|
if (isWaitSignal(cause)) {
|
|
204
251
|
if (cause.outcome.kind === "interaction-required") {
|
|
205
252
|
return copyJson({
|
|
@@ -305,6 +352,15 @@ export async function dispatchPlan(invocation) {
|
|
|
305
352
|
};
|
|
306
353
|
await record();
|
|
307
354
|
}
|
|
355
|
+
function unsupported(callId, toolName) {
|
|
356
|
+
return {
|
|
357
|
+
callId,
|
|
358
|
+
toolName,
|
|
359
|
+
kind: "failed",
|
|
360
|
+
code: "delegation.interaction-unsupported",
|
|
361
|
+
message: INTERACTION_UNSUPPORTED,
|
|
362
|
+
};
|
|
363
|
+
}
|
|
308
364
|
function normalizeOutcome(raw) {
|
|
309
365
|
if (raw && typeof raw === "object" && "kind" in raw) {
|
|
310
366
|
const kind = raw.kind;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { AgentDefinition } from "../definition/agent-definition.js";
|
|
2
|
-
import type { BoundToolDefinition } from "@nylorun/core/define";
|
|
2
|
+
import type { AgentRef, BoundToolDefinition } from "@nylorun/core/define";
|
|
3
|
+
import type { DelegationHost, ExecuteInternals } from "./delegation.js";
|
|
3
4
|
import type { ExecutionState, RunOptions } from "../types/execution.js";
|
|
4
5
|
import type { ObserveEvent } from "@nylorun/core/define";
|
|
5
6
|
import type { JsonValue } from "@nylorun/core/define";
|
|
@@ -9,6 +10,10 @@ export interface Invocation {
|
|
|
9
10
|
readonly options: RunOptions<any>;
|
|
10
11
|
readonly signal: AbortSignal;
|
|
11
12
|
readonly definitions: Map<string, BoundToolDefinition>;
|
|
13
|
+
/** Builds agents used as tools; absent means in-process children. */
|
|
14
|
+
readonly delegation?: DelegationHost;
|
|
15
|
+
/** Set when this invocation is itself an agent used as a tool. */
|
|
16
|
+
readonly delegated?: AgentRef;
|
|
12
17
|
state: ExecutionState;
|
|
13
18
|
/** Mutable durable session memory for this invocation. */
|
|
14
19
|
sessionBag: Record<string, JsonValue>;
|
|
@@ -21,4 +26,5 @@ export declare function createInvocation(input: {
|
|
|
21
26
|
readonly options: RunOptions<any>;
|
|
22
27
|
readonly state: ExecutionState;
|
|
23
28
|
readonly definitions: Map<string, BoundToolDefinition>;
|
|
29
|
+
readonly internals?: ExecuteInternals;
|
|
24
30
|
}): Invocation;
|
package/dist/loop/invocation.js
CHANGED
|
@@ -8,6 +8,8 @@ export function createInvocation(input) {
|
|
|
8
8
|
options: input.options,
|
|
9
9
|
signal: input.options.signal ?? new AbortController().signal,
|
|
10
10
|
definitions: input.definitions,
|
|
11
|
+
...(input.internals?.delegation ? { delegation: input.internals.delegation } : {}),
|
|
12
|
+
...(input.internals?.delegated ? { delegated: input.internals.delegated } : {}),
|
|
11
13
|
state: input.state,
|
|
12
14
|
sessionBag: { ...(input.state.state ?? {}) },
|
|
13
15
|
};
|
package/dist/loop/run.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { AgentDefinition } from "../definition/agent-definition.js";
|
|
2
2
|
import type { RunOptions, RunResult } from "../types/execution.js";
|
|
3
3
|
import type { JsonValue } from "@nylorun/core/define";
|
|
4
|
+
import type { ExecuteInternals } from "./delegation.js";
|
|
4
5
|
/** All mutable progress belongs to this invocation and is discarded when it settles. */
|
|
5
|
-
export declare function execute(agent: AgentDefinition, options: RunOptions<any
|
|
6
|
+
export declare function execute(agent: AgentDefinition, options: RunOptions<any>, internals?: ExecuteInternals): Promise<RunResult<JsonValue>>;
|
package/dist/loop/run.js
CHANGED
|
@@ -9,7 +9,7 @@ import { openExecution, validateRunOptions } from "./options.js";
|
|
|
9
9
|
import { applyResume } from "./resume.js";
|
|
10
10
|
import { asDecisions, callHooks, hasAnyHooks, mergeTurnDecisions, projectInput, } from "./step/hooks.js";
|
|
11
11
|
/** All mutable progress belongs to this invocation and is discarded when it settles. */
|
|
12
|
-
export async function execute(agent, options) {
|
|
12
|
+
export async function execute(agent, options, internals = {}) {
|
|
13
13
|
validateRunOptions(options);
|
|
14
14
|
const opened = openExecution(agent, options);
|
|
15
15
|
let { state } = opened;
|
|
@@ -28,7 +28,7 @@ export async function execute(agent, options) {
|
|
|
28
28
|
else if (input.kind === "approve" || input.kind === "respond" || input.kind === "settle") {
|
|
29
29
|
throw new HarnessError("execution.invalid-input", "There is no matching paused operation for this input");
|
|
30
30
|
}
|
|
31
|
-
const invocation = createInvocation({ agent, options, state, definitions });
|
|
31
|
+
const invocation = createInvocation({ agent, options, state, definitions, internals });
|
|
32
32
|
const { signal, observe, record } = invocation;
|
|
33
33
|
const finish = (result) => finishInvocation(invocation, result);
|
|
34
34
|
try {
|
package/dist/run/durable.d.ts
CHANGED
|
@@ -2,7 +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
|
+
import type { AgentRef, HookAt, HookScope } 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 {
|
|
@@ -23,7 +23,10 @@ export interface HostEffect {
|
|
|
23
23
|
readonly turnId: string;
|
|
24
24
|
readonly agentId: string;
|
|
25
25
|
readonly manifestHash: string;
|
|
26
|
-
|
|
26
|
+
/** `delegation` journals when an agent used as a tool starts and settles; hosts record it and resolve it at once. */
|
|
27
|
+
readonly kind: "model" | "tool" | "hook" | "delegation";
|
|
28
|
+
/** Set on work for an agent used as a tool; `agentId` stays the session's root agent. */
|
|
29
|
+
readonly agent?: AgentRef;
|
|
27
30
|
readonly capabilityId?: string;
|
|
28
31
|
readonly toolName?: string;
|
|
29
32
|
/** For `hook` effects: the hook point and every capability that registered it, in manifest order. */
|
|
@@ -59,6 +62,8 @@ export type DurableResult = {
|
|
|
59
62
|
};
|
|
60
63
|
/** Discovered tool advertised for this execution. It is not part of the hashed manifest. */
|
|
61
64
|
export interface DurableSessionTool {
|
|
65
|
+
/** The agent used as a tool that owns this tool; absent for the root agent. */
|
|
66
|
+
readonly agentId?: string;
|
|
62
67
|
readonly capabilityId: string;
|
|
63
68
|
readonly name: string;
|
|
64
69
|
readonly description?: string;
|
package/dist/run/durable.js
CHANGED
|
@@ -71,97 +71,121 @@ export async function runDurable(options) {
|
|
|
71
71
|
}
|
|
72
72
|
return result.outcome;
|
|
73
73
|
};
|
|
74
|
-
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
release
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
ctx.
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
74
|
+
/** Tools of one agent. Each agent keeps its own patch order; children namespace their effects. */
|
|
75
|
+
const hostedTools = (ref) => {
|
|
76
|
+
let patchTail = Promise.resolve();
|
|
77
|
+
return (capabilityId, tool) => ({
|
|
78
|
+
name: tool.name,
|
|
79
|
+
...(tool.description === undefined ? {} : { description: tool.description }),
|
|
80
|
+
inputSchema: schemaFromJSON(tool.inputSchema),
|
|
81
|
+
...(tool.outputSchema ? { outputSchema: schemaFromJSON(tool.outputSchema) } : {}),
|
|
82
|
+
async execute(args, ctx) {
|
|
83
|
+
const previous = patchTail;
|
|
84
|
+
let release;
|
|
85
|
+
patchTail = new Promise((resolve) => {
|
|
86
|
+
release = resolve;
|
|
87
|
+
});
|
|
88
|
+
try {
|
|
89
|
+
const outcome = await effect("tool", args, {
|
|
90
|
+
executionId: ctx.executionId,
|
|
91
|
+
turnId: ctx.turnId,
|
|
92
|
+
stepId: ctx.stepId,
|
|
93
|
+
callId: ctx.callId,
|
|
94
|
+
invocationId: ctx.invocationId,
|
|
95
|
+
idempotencyKey: ref
|
|
96
|
+
? `${ref.delegationId}/${ctx.idempotencyKey}`
|
|
97
|
+
: ctx.idempotencyKey,
|
|
98
|
+
info: ctx.info,
|
|
99
|
+
state: ctx.state.entries(),
|
|
100
|
+
resume: ctx.resume,
|
|
101
|
+
}, scoped(ref, ctx.invocationId), { capabilityId, toolName: tool.name, ...(ref ? { agent: ref } : {}) });
|
|
102
|
+
// Apply concurrently resolved patches in manifest call order, independent of host I/O timing.
|
|
103
|
+
await previous;
|
|
104
|
+
for (const [key, value] of Object.entries(outcome.statePatch ?? {}))
|
|
105
|
+
ctx.state.set(key, value);
|
|
106
|
+
const value = outcome.value;
|
|
107
|
+
return value?.kind === "interaction-required"
|
|
108
|
+
? {
|
|
109
|
+
...value,
|
|
110
|
+
interaction: {
|
|
111
|
+
...value.interaction,
|
|
112
|
+
id: `${checkpoint.turnId}:${checkpoint.segment}:interaction:${ctx.invocationId}`,
|
|
113
|
+
},
|
|
114
|
+
}
|
|
115
|
+
: value;
|
|
116
|
+
}
|
|
117
|
+
finally {
|
|
118
|
+
await previous;
|
|
119
|
+
release();
|
|
120
|
+
}
|
|
121
|
+
},
|
|
122
|
+
});
|
|
123
|
+
};
|
|
120
124
|
const sessionTools = options.sessionTools ?? [];
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
tools
|
|
130
|
-
|
|
131
|
-
|
|
125
|
+
/** Rebuild one agent from its manifest with every tool and hook routed through host effects. */
|
|
126
|
+
const hostedDefinition = (agent, ref) => {
|
|
127
|
+
const hostedTool = hostedTools(ref);
|
|
128
|
+
const owned = sessionTools.filter((tool) => (tool.agentId ?? manifest.id) === agent.id);
|
|
129
|
+
const implementations = {};
|
|
130
|
+
for (const capability of agent.capabilities) {
|
|
131
|
+
const tools = {};
|
|
132
|
+
// Agents used as tools are rebuilt from their manifest body; the engine runs them.
|
|
133
|
+
for (const tool of capability.tools ?? [])
|
|
134
|
+
if (!tool.agent)
|
|
135
|
+
tools[tool.name] = hostedTool(capability.id, tool);
|
|
136
|
+
for (const tool of owned)
|
|
137
|
+
if (tool.capabilityId === capability.id)
|
|
138
|
+
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
|
+
};
|
|
144
|
+
}
|
|
145
|
+
const definition = definitionFor(agentFrom(agent, implementations, owned.length === 0
|
|
146
|
+
? undefined
|
|
147
|
+
: {
|
|
148
|
+
sessionTools: owned.map((tool) => ({
|
|
149
|
+
capabilityId: tool.capabilityId,
|
|
150
|
+
name: tool.name,
|
|
151
|
+
})),
|
|
152
|
+
}));
|
|
153
|
+
// All capabilities registered at a hook point share one effect, so one executor round trip.
|
|
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
|
+
: {};
|
|
132
163
|
};
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
164
|
+
return Object.freeze({ ...definition, runHooks });
|
|
165
|
+
};
|
|
166
|
+
const modelCall = (ref) => async (call, ctx) => (await effect("model", call, { request: ctx.request, invocationId: ctx.invocationId }, scoped(ref, ctx.invocationId), ref ? { agent: ref } : {})).value;
|
|
167
|
+
const delegation = {
|
|
168
|
+
child: (delegate, ref) => ({
|
|
169
|
+
definition: hostedDefinition(delegate.manifest, ref),
|
|
170
|
+
onModelCall: modelCall(ref),
|
|
171
|
+
}),
|
|
172
|
+
async announce(phase, ref, payload) {
|
|
173
|
+
await effect("delegation", payload, {}, `${ref.delegationId}:${phase}`, { agent: ref });
|
|
174
|
+
},
|
|
175
|
+
};
|
|
176
|
+
const hosted = hostedDefinition(manifest);
|
|
142
177
|
// Manifest reconstruction must retain definition identity, including schemas and instructions.
|
|
143
|
-
if (
|
|
178
|
+
if (hosted.hash !== checkpoint.manifestHash)
|
|
144
179
|
throw new HarnessError("execution.incompatible", "Reconstructed definition hash mismatch");
|
|
145
|
-
// All capabilities registered at a hook point share one effect, so one executor round trip.
|
|
146
|
-
const runHooks = async ({ point, capabilityIds, args, identity }) => {
|
|
147
|
-
const outcome = await effect("hook", args, { info: checkpoint.info }, identity, {
|
|
148
|
-
hook: { at: point.at, scope: point.scope, capabilityIds },
|
|
149
|
-
});
|
|
150
|
-
const results = outcome.value?.results;
|
|
151
|
-
return results !== null && typeof results === "object" && !Array.isArray(results)
|
|
152
|
-
? results
|
|
153
|
-
: {};
|
|
154
|
-
};
|
|
155
|
-
const hosted = Object.freeze({ ...definition, runHooks });
|
|
156
180
|
try {
|
|
157
181
|
const result = await withDeterministicIds(`${checkpoint.turnId}_${checkpoint.segment}`, () => execute(hosted, {
|
|
158
182
|
state: checkpoint.state ??
|
|
159
|
-
initializeExecutionState(
|
|
183
|
+
initializeExecutionState(hosted, { executionId: checkpoint.sessionId }),
|
|
160
184
|
input: checkpoint.input,
|
|
161
185
|
info: checkpoint.info,
|
|
162
186
|
signal: options.signal,
|
|
163
|
-
onModelCall:
|
|
164
|
-
}));
|
|
187
|
+
onModelCall: modelCall(),
|
|
188
|
+
}, { delegation }));
|
|
165
189
|
return { status: result.status, checkpoint: { ...checkpoint, state: result.state }, result };
|
|
166
190
|
}
|
|
167
191
|
catch (error) {
|
|
@@ -176,6 +200,10 @@ export async function runDurable(options) {
|
|
|
176
200
|
};
|
|
177
201
|
}
|
|
178
202
|
}
|
|
203
|
+
/** Effect identities of an agent used as a tool live under its delegation. */
|
|
204
|
+
function scoped(ref, identity) {
|
|
205
|
+
return ref ? `${ref.delegationId}/${identity}` : identity;
|
|
206
|
+
}
|
|
179
207
|
function hookPlaceholders(hooks) {
|
|
180
208
|
const placeholder = () => {
|
|
181
209
|
throw new HarnessError("execution.incompatible", "Hosted hooks run through the host effect");
|
|
@@ -2,7 +2,7 @@ import type { ModelAdapter } from "@nylorun/core/define";
|
|
|
2
2
|
import type { InputEvent, MessageInput, TranscriptEntry } from "@nylorun/core/define";
|
|
3
3
|
import type { ObserveEvent } from "@nylorun/core/define";
|
|
4
4
|
import type { JsonObject, JsonValue, Tripwire } from "@nylorun/core/define";
|
|
5
|
-
import type { RequiredInteraction, ToolExecutionResume, ToolOutcome, ToolResult } from "@nylorun/core/define";
|
|
5
|
+
import type { AgentRef, RequiredInteraction, ToolExecutionResume, ToolOutcome, ToolResult } from "@nylorun/core/define";
|
|
6
6
|
export type ExecutionInput = MessageInput | InputEvent | {
|
|
7
7
|
readonly kind: "continue";
|
|
8
8
|
} | {
|
|
@@ -105,6 +105,8 @@ export type ExecutionEvent = (ObserveEvent | {
|
|
|
105
105
|
readonly executionId: string;
|
|
106
106
|
readonly sequence: number;
|
|
107
107
|
readonly runId: string;
|
|
108
|
+
/** Set on events forwarded from an agent used as a tool. */
|
|
109
|
+
readonly agent?: AgentRef;
|
|
108
110
|
};
|
|
109
111
|
export interface RunOptions<Info = unknown> {
|
|
110
112
|
readonly state?: ExecutionState;
|
package/dist/utils/ids.d.ts
CHANGED
|
@@ -1,2 +1,4 @@
|
|
|
1
1
|
export declare function withDeterministicIds<T>(seed: string, fn: () => T): T;
|
|
2
2
|
export declare function createId(prefix: string): string;
|
|
3
|
+
/** Run `fn` with its own id counters, seeded under the current scope, so concurrent work stays deterministic. */
|
|
4
|
+
export declare function withNestedIds<T>(suffix: string, fn: () => T): T;
|
package/dist/utils/ids.js
CHANGED
|
@@ -11,3 +11,8 @@ export function createId(prefix) {
|
|
|
11
11
|
value.counts.set(prefix, count);
|
|
12
12
|
return `${prefix}_${value.seed}_${count}`;
|
|
13
13
|
}
|
|
14
|
+
/** Run `fn` with its own id counters, seeded under the current scope, so concurrent work stays deterministic. */
|
|
15
|
+
export function withNestedIds(suffix, fn) {
|
|
16
|
+
const value = scope.getStore();
|
|
17
|
+
return value ? scope.run({ seed: `${value.seed}_${suffix}`, counts: new Map() }, fn) : fn();
|
|
18
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nylorun/harness",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.18.0-beta",
|
|
4
4
|
"description": "Nylorun's TypeScript agent execution engine. See github.com/nylorun/harness.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -76,7 +76,7 @@
|
|
|
76
76
|
"zod": "^4.6.5"
|
|
77
77
|
},
|
|
78
78
|
"dependencies": {
|
|
79
|
-
"@nylorun/core": "0.
|
|
79
|
+
"@nylorun/core": "0.4.0-beta"
|
|
80
80
|
},
|
|
81
81
|
"peerDependencies": {
|
|
82
82
|
"zod": "^4.6.5"
|