@providerkit/agents 0.1.0 → 0.2.0
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/LICENSE-APACHE-2.0 +202 -0
- package/README.md +2108 -52
- package/THIRD_PARTY_NOTICES.md +521 -0
- package/dist/a2a/auth.d.ts +10 -0
- package/dist/a2a/auth.d.ts.map +1 -0
- package/dist/a2a/auth.js +52 -0
- package/dist/a2a/auth.js.map +1 -0
- package/dist/a2a/client.d.ts +74 -0
- package/dist/a2a/client.d.ts.map +1 -0
- package/dist/a2a/client.js +601 -0
- package/dist/a2a/client.js.map +1 -0
- package/dist/a2a/index.d.ts +22 -0
- package/dist/a2a/index.d.ts.map +1 -0
- package/dist/a2a/index.js +11 -0
- package/dist/a2a/index.js.map +1 -0
- package/dist/a2a/memory-runs.d.ts +62 -0
- package/dist/a2a/memory-runs.d.ts.map +1 -0
- package/dist/a2a/memory-runs.js +349 -0
- package/dist/a2a/memory-runs.js.map +1 -0
- package/dist/a2a/policy.d.ts +15 -0
- package/dist/a2a/policy.d.ts.map +1 -0
- package/dist/a2a/policy.js +114 -0
- package/dist/a2a/policy.js.map +1 -0
- package/dist/a2a/push.d.ts +34 -0
- package/dist/a2a/push.d.ts.map +1 -0
- package/dist/a2a/push.js +180 -0
- package/dist/a2a/push.js.map +1 -0
- package/dist/a2a/remote.d.ts +155 -0
- package/dist/a2a/remote.d.ts.map +1 -0
- package/dist/a2a/remote.js +1196 -0
- package/dist/a2a/remote.js.map +1 -0
- package/dist/a2a/server.d.ts +110 -0
- package/dist/a2a/server.d.ts.map +1 -0
- package/dist/a2a/server.js +1139 -0
- package/dist/a2a/server.js.map +1 -0
- package/dist/a2a/signing.d.ts +21 -0
- package/dist/a2a/signing.d.ts.map +1 -0
- package/dist/a2a/signing.js +305 -0
- package/dist/a2a/signing.js.map +1 -0
- package/dist/a2a/tasks.d.ts +88 -0
- package/dist/a2a/tasks.d.ts.map +1 -0
- package/dist/a2a/tasks.js +170 -0
- package/dist/a2a/tasks.js.map +1 -0
- package/dist/a2a/wire.d.ts +267 -0
- package/dist/a2a/wire.d.ts.map +1 -0
- package/dist/a2a/wire.js +1202 -0
- package/dist/a2a/wire.js.map +1 -0
- package/dist/background-types.d.ts +76 -0
- package/dist/background-types.d.ts.map +1 -0
- package/dist/background-types.js +2 -0
- package/dist/background-types.js.map +1 -0
- package/dist/child.d.ts +25 -0
- package/dist/child.d.ts.map +1 -0
- package/dist/child.js +129 -0
- package/dist/child.js.map +1 -0
- package/dist/code-driver.d.ts +40 -0
- package/dist/code-driver.d.ts.map +1 -0
- package/dist/code-driver.js +2 -0
- package/dist/code-driver.js.map +1 -0
- package/dist/code-mode.d.ts +3 -0
- package/dist/code-mode.d.ts.map +1 -0
- package/dist/code-mode.js +2 -0
- package/dist/code-mode.js.map +1 -0
- package/dist/code-script.d.ts +3 -0
- package/dist/code-script.d.ts.map +1 -0
- package/dist/code-script.js +149 -0
- package/dist/code-script.js.map +1 -0
- package/dist/code.d.ts +75 -0
- package/dist/code.d.ts.map +1 -0
- package/dist/code.js +326 -0
- package/dist/code.js.map +1 -0
- package/dist/compaction.d.ts +15 -0
- package/dist/compaction.d.ts.map +1 -0
- package/dist/compaction.js +168 -0
- package/dist/compaction.js.map +1 -0
- package/dist/delegation.d.ts +85 -16
- package/dist/delegation.d.ts.map +1 -1
- package/dist/delegation.js +240 -106
- package/dist/delegation.js.map +1 -1
- package/dist/evals/driver.d.ts +10 -0
- package/dist/evals/driver.d.ts.map +1 -0
- package/dist/evals/driver.js +192 -0
- package/dist/evals/driver.js.map +1 -0
- package/dist/evals/journal.d.ts +26 -0
- package/dist/evals/journal.d.ts.map +1 -0
- package/dist/evals/journal.js +483 -0
- package/dist/evals/journal.js.map +1 -0
- package/dist/evals/judge.d.ts +31 -0
- package/dist/evals/judge.d.ts.map +1 -0
- package/dist/evals/judge.js +142 -0
- package/dist/evals/judge.js.map +1 -0
- package/dist/evals/report.d.ts +38 -0
- package/dist/evals/report.d.ts.map +1 -0
- package/dist/evals/report.js +241 -0
- package/dist/evals/report.js.map +1 -0
- package/dist/evals/runner.d.ts +24 -0
- package/dist/evals/runner.d.ts.map +1 -0
- package/dist/evals/runner.js +655 -0
- package/dist/evals/runner.js.map +1 -0
- package/dist/evals/scorers.d.ts +36 -0
- package/dist/evals/scorers.d.ts.map +1 -0
- package/dist/evals/scorers.js +259 -0
- package/dist/evals/scorers.js.map +1 -0
- package/dist/evals/simulation.d.ts +7 -0
- package/dist/evals/simulation.d.ts.map +1 -0
- package/dist/evals/simulation.js +38 -0
- package/dist/evals/simulation.js.map +1 -0
- package/dist/evals/testing.d.ts +36 -0
- package/dist/evals/testing.d.ts.map +1 -0
- package/dist/evals/testing.js +87 -0
- package/dist/evals/testing.js.map +1 -0
- package/dist/evals/trajectory.d.ts +11 -0
- package/dist/evals/trajectory.d.ts.map +1 -0
- package/dist/evals/trajectory.js +180 -0
- package/dist/evals/trajectory.js.map +1 -0
- package/dist/evals/types.d.ts +431 -0
- package/dist/evals/types.d.ts.map +1 -0
- package/dist/evals/types.js +4 -0
- package/dist/evals/types.js.map +1 -0
- package/dist/evals.d.ts +14 -0
- package/dist/evals.d.ts.map +1 -0
- package/dist/evals.js +9 -0
- package/dist/evals.js.map +1 -0
- package/dist/extensions.d.ts +33 -0
- package/dist/extensions.d.ts.map +1 -0
- package/dist/extensions.js +188 -0
- package/dist/extensions.js.map +1 -0
- package/dist/handoff.d.ts +58 -0
- package/dist/handoff.d.ts.map +1 -0
- package/dist/handoff.js +160 -0
- package/dist/handoff.js.map +1 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -1
- package/dist/input.d.ts +42 -0
- package/dist/input.d.ts.map +1 -0
- package/dist/input.js +266 -0
- package/dist/input.js.map +1 -0
- package/dist/mcp.d.ts +77 -0
- package/dist/mcp.d.ts.map +1 -0
- package/dist/mcp.js +505 -0
- package/dist/mcp.js.map +1 -0
- package/dist/memory-store.d.ts +11 -0
- package/dist/memory-store.d.ts.map +1 -0
- package/dist/memory-store.js +272 -0
- package/dist/memory-store.js.map +1 -0
- package/dist/memory.d.ts +212 -0
- package/dist/memory.d.ts.map +1 -0
- package/dist/memory.js +613 -0
- package/dist/memory.js.map +1 -0
- package/dist/otel.d.ts +74 -0
- package/dist/otel.d.ts.map +1 -0
- package/dist/otel.js +427 -0
- package/dist/otel.js.map +1 -0
- package/dist/progress.d.ts +17 -0
- package/dist/progress.d.ts.map +1 -0
- package/dist/progress.js +193 -0
- package/dist/progress.js.map +1 -0
- package/dist/quickjs.d.ts +19 -0
- package/dist/quickjs.d.ts.map +1 -0
- package/dist/quickjs.js +519 -0
- package/dist/quickjs.js.map +1 -0
- package/dist/recovery.d.ts +10 -0
- package/dist/recovery.d.ts.map +1 -0
- package/dist/recovery.js +62 -0
- package/dist/recovery.js.map +1 -0
- package/dist/request.d.ts +88 -0
- package/dist/request.d.ts.map +1 -0
- package/dist/request.js +422 -0
- package/dist/request.js.map +1 -0
- package/dist/run.d.ts +16 -4
- package/dist/run.d.ts.map +1 -1
- package/dist/run.js +2016 -245
- package/dist/run.js.map +1 -1
- package/dist/runs.d.ts +77 -34
- package/dist/runs.d.ts.map +1 -1
- package/dist/runs.js +267 -85
- package/dist/runs.js.map +1 -1
- package/dist/schema-to-ts.d.ts +4 -0
- package/dist/schema-to-ts.d.ts.map +1 -0
- package/dist/schema-to-ts.js +191 -0
- package/dist/schema-to-ts.js.map +1 -0
- package/dist/session.d.ts +23 -0
- package/dist/session.d.ts.map +1 -0
- package/dist/session.js +137 -0
- package/dist/session.js.map +1 -0
- package/dist/snapshot.d.ts +57 -8
- package/dist/snapshot.d.ts.map +1 -1
- package/dist/snapshot.js +1206 -109
- package/dist/snapshot.js.map +1 -1
- package/dist/steering.d.ts +75 -0
- package/dist/steering.d.ts.map +1 -0
- package/dist/steering.js +214 -0
- package/dist/steering.js.map +1 -0
- package/dist/subagents.d.ts +141 -0
- package/dist/subagents.d.ts.map +1 -0
- package/dist/subagents.js +746 -0
- package/dist/subagents.js.map +1 -0
- package/dist/tool-retry.d.ts +12 -0
- package/dist/tool-retry.d.ts.map +1 -0
- package/dist/tool-retry.js +53 -0
- package/dist/tool-retry.js.map +1 -0
- package/dist/tree.d.ts +62 -6
- package/dist/tree.d.ts.map +1 -1
- package/dist/tree.js +192 -23
- package/dist/tree.js.map +1 -1
- package/dist/types.d.ts +767 -52
- package/dist/types.d.ts.map +1 -1
- package/dist/workflow-snapshot.d.ts +8 -0
- package/dist/workflow-snapshot.d.ts.map +1 -0
- package/dist/workflow-snapshot.js +276 -0
- package/dist/workflow-snapshot.js.map +1 -0
- package/dist/workflow-types.d.ts +171 -0
- package/dist/workflow-types.d.ts.map +1 -0
- package/dist/workflow-types.js +2 -0
- package/dist/workflow-types.js.map +1 -0
- package/dist/workflow.d.ts +19 -0
- package/dist/workflow.d.ts.map +1 -0
- package/dist/workflow.js +1053 -0
- package/dist/workflow.js.map +1 -0
- package/examples/a2a-remote.ts +85 -0
- package/examples/a2a-server.ts +100 -0
- package/examples/background.ts +18 -4
- package/examples/code-mode.ts +76 -0
- package/examples/conversation.ts +57 -0
- package/examples/evals.ts +79 -0
- package/examples/guardrails.ts +56 -0
- package/examples/handoff.ts +79 -0
- package/examples/memory.ts +44 -0
- package/examples/otel.ts +99 -0
- package/examples/steering.ts +69 -0
- package/examples/structured-handoff.ts +92 -0
- package/examples/subagents.ts +127 -0
- package/examples/workflow.ts +74 -0
- package/package.json +58 -6
- package/src/a2a/auth.ts +62 -0
- package/src/a2a/client.ts +733 -0
- package/src/a2a/index.ts +74 -0
- package/src/a2a/memory-runs.ts +448 -0
- package/src/a2a/policy.ts +148 -0
- package/src/a2a/push.ts +251 -0
- package/src/a2a/remote.ts +1652 -0
- package/src/a2a/server.ts +1390 -0
- package/src/a2a/signing.ts +348 -0
- package/src/a2a/tasks.ts +260 -0
- package/src/a2a/wire.ts +1443 -0
- package/src/background-types.ts +86 -0
- package/src/child.ts +181 -0
- package/src/code-driver.ts +48 -0
- package/src/code-mode.ts +12 -0
- package/src/code-script.ts +149 -0
- package/src/code.ts +424 -0
- package/src/compaction.ts +212 -0
- package/src/delegation.ts +444 -155
- package/src/evals/driver.ts +222 -0
- package/src/evals/journal.ts +605 -0
- package/src/evals/judge.ts +188 -0
- package/src/evals/report.ts +295 -0
- package/src/evals/runner.ts +826 -0
- package/src/evals/scorers.ts +339 -0
- package/src/evals/simulation.ts +46 -0
- package/src/evals/testing.ts +126 -0
- package/src/evals/trajectory.ts +223 -0
- package/src/evals/types.ts +463 -0
- package/src/evals.ts +72 -0
- package/src/extensions.ts +247 -0
- package/src/handoff.ts +214 -0
- package/src/index.ts +51 -0
- package/src/input.ts +319 -0
- package/src/mcp.ts +690 -0
- package/src/memory-store.ts +366 -0
- package/src/memory.ts +893 -0
- package/src/otel.ts +568 -0
- package/src/progress.ts +214 -0
- package/src/quickjs.ts +524 -0
- package/src/recovery.ts +90 -0
- package/src/request.ts +513 -0
- package/src/run.ts +2678 -313
- package/src/runs.ts +464 -133
- package/src/schema-to-ts.ts +194 -0
- package/src/session.ts +178 -0
- package/src/snapshot.ts +1595 -124
- package/src/steering.ts +329 -0
- package/src/subagents.ts +1084 -0
- package/src/tool-retry.ts +86 -0
- package/src/tree.ts +223 -27
- package/src/types.ts +711 -52
- package/src/workflow-snapshot.ts +366 -0
- package/src/workflow-types.ts +213 -0
- package/src/workflow.ts +1316 -0
package/src/subagents.ts
ADDED
|
@@ -0,0 +1,1084 @@
|
|
|
1
|
+
// Adapted from PydanticAI Harness / Vstorm (MIT), sub_agents/_toolset.py and
|
|
2
|
+
// _control.py, and TanStack AI (MIT), first-party/agents.ts. Fork behavior follows Mastra's
|
|
3
|
+
// agent-controller/tools.ts (Apache-2.0). See THIRD_PARTY_NOTICES.md.
|
|
4
|
+
// Changed: versioned host templates, journaled grants, bounded host-selected history and
|
|
5
|
+
// opaque child keys. No detached work, dynamic credentials or second execution loop.
|
|
6
|
+
import { parseToolArgs, type ToolDefinition } from "@providerkit/core";
|
|
7
|
+
import {
|
|
8
|
+
AGENT_RUNTIME,
|
|
9
|
+
SUBAGENT_CONTEXT,
|
|
10
|
+
isDelegation,
|
|
11
|
+
type Delegation,
|
|
12
|
+
type DelegationContext,
|
|
13
|
+
} from "./delegation.ts";
|
|
14
|
+
import { jsonBytes } from "./extensions.ts";
|
|
15
|
+
import { conversationOnly, isHandoff } from "./handoff.ts";
|
|
16
|
+
import { conversationOf, readInput } from "./input.ts";
|
|
17
|
+
import {
|
|
18
|
+
copyData,
|
|
19
|
+
childRunId,
|
|
20
|
+
equalData,
|
|
21
|
+
immutableCopy,
|
|
22
|
+
isId,
|
|
23
|
+
isNames,
|
|
24
|
+
isRecord,
|
|
25
|
+
readLimits,
|
|
26
|
+
readModelSettings,
|
|
27
|
+
} from "./snapshot.ts";
|
|
28
|
+
import { childJournals, fail, Halt, isLocalStop, untilAbort } from "./tree.ts";
|
|
29
|
+
import type {
|
|
30
|
+
Agent,
|
|
31
|
+
AgentConfig,
|
|
32
|
+
AgentMessage,
|
|
33
|
+
DelegationExecution,
|
|
34
|
+
RecordedModelSettings,
|
|
35
|
+
RunDefinition,
|
|
36
|
+
RunLimits,
|
|
37
|
+
RunSnapshot,
|
|
38
|
+
TreeNode,
|
|
39
|
+
ToolRequest,
|
|
40
|
+
ToolResult,
|
|
41
|
+
} from "./types.ts";
|
|
42
|
+
|
|
43
|
+
/** Only the host writes these settings. The model selects the alias, never settings or a
|
|
44
|
+
* provider. Hosted capabilities and tool choice cannot be changed by a model choice. */
|
|
45
|
+
export interface ModelChoice {
|
|
46
|
+
description: string;
|
|
47
|
+
settings: Omit<RecordedModelSettings, "toolChoice" | "hostedTools">;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Private model input, not a public label or authorization. limits is host-only. */
|
|
51
|
+
export interface SubagentDraft {
|
|
52
|
+
name: string;
|
|
53
|
+
task: string;
|
|
54
|
+
instructions?: string;
|
|
55
|
+
tools: string[];
|
|
56
|
+
model?: string;
|
|
57
|
+
fork?: true;
|
|
58
|
+
/** Opaque helperId from a previous result, not a name or run id. */
|
|
59
|
+
continues?: string;
|
|
60
|
+
limits?: Partial<RunLimits>;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Only selected, already-sanitized messages can cross the fork boundary. */
|
|
64
|
+
export interface SubagentForkPolicy {
|
|
65
|
+
identity: string;
|
|
66
|
+
maxMessages: number;
|
|
67
|
+
maxBytes: number;
|
|
68
|
+
/** Pure host policy. Return increasing message indices, never model-selected indices. */
|
|
69
|
+
select: (
|
|
70
|
+
messages: readonly AgentMessage[],
|
|
71
|
+
context: SubagentContext,
|
|
72
|
+
) => readonly number[] | Promise<readonly number[]>;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface SubagentContext {
|
|
76
|
+
readonly call: ToolRequest;
|
|
77
|
+
readonly depth: number;
|
|
78
|
+
readonly level: number;
|
|
79
|
+
readonly grantable: readonly string[];
|
|
80
|
+
readonly signal: AbortSignal;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export type SubagentResult<T = unknown> = { name: string } & (
|
|
84
|
+
| { status: "completed"; runId: string; helperId: string; output: T }
|
|
85
|
+
| { status: "failed"; runId: string; helperId: string; error: string }
|
|
86
|
+
| { status: "refused"; error: string }
|
|
87
|
+
);
|
|
88
|
+
|
|
89
|
+
export interface SubagentToolSpec {
|
|
90
|
+
name: string;
|
|
91
|
+
description: string;
|
|
92
|
+
/** Host-owned provider, instructions, tools, limits, guards and output contract. */
|
|
93
|
+
agent: Agent<unknown> | "self";
|
|
94
|
+
models?: Readonly<Record<string, ModelChoice>>;
|
|
95
|
+
defaultTools?: "none" | "all";
|
|
96
|
+
/** Omitted means task-only. Forks require host.beforeTool as a live authority check. */
|
|
97
|
+
fork?: SubagentForkPolicy;
|
|
98
|
+
/** Continue completed helpers owned by this creator/tool. Requires host.beforeTool. */
|
|
99
|
+
followUp?: boolean;
|
|
100
|
+
/** Explicit recursive spawning permission. Default 1; tree depth still applies. */
|
|
101
|
+
maxLevels?: number;
|
|
102
|
+
maxPerCall?: number;
|
|
103
|
+
maxPerRun?: number;
|
|
104
|
+
needsApproval?: boolean;
|
|
105
|
+
/** Pure admission policy. May narrow tools and limits, rewrite instructions/task or refuse.
|
|
106
|
+
* It runs before admission and is not called again for a saved child. */
|
|
107
|
+
prepare?: (
|
|
108
|
+
draft: SubagentDraft,
|
|
109
|
+
context: SubagentContext,
|
|
110
|
+
) => SubagentDraft | { refuse: string } | Promise<SubagentDraft | { refuse: string }>;
|
|
111
|
+
/** Pure. The default is JSON in declaration order. */
|
|
112
|
+
summarize?: (results: readonly SubagentResult[]) => string;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
interface SubagentPolicy {
|
|
116
|
+
models: Record<string, ModelChoice>;
|
|
117
|
+
defaultTools: "none" | "all";
|
|
118
|
+
maxLevels: number;
|
|
119
|
+
maxPerCall: number;
|
|
120
|
+
maxPerRun: number;
|
|
121
|
+
needsApproval: boolean;
|
|
122
|
+
prepare: boolean;
|
|
123
|
+
self: boolean;
|
|
124
|
+
fork: Omit<SubagentForkPolicy, "select"> | null;
|
|
125
|
+
followUp: boolean;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Private admission record in the ordinary child snapshot. No functions or credentials. */
|
|
129
|
+
export interface SubagentRecord {
|
|
130
|
+
/** SDK-issued identity. It grants nothing outside its recorded creator and root. */
|
|
131
|
+
identity: { id: string; rootRunId: string; creatorRunId: string; originRunId: string };
|
|
132
|
+
previousRunId?: string;
|
|
133
|
+
/** Indices into conversationOnly of the creator's settled prefix at admission. */
|
|
134
|
+
fork?: { indices: number[] };
|
|
135
|
+
tool: string;
|
|
136
|
+
requested: SubagentDraft;
|
|
137
|
+
spec: SubagentDraft;
|
|
138
|
+
policy: SubagentPolicy;
|
|
139
|
+
template: Record<string, unknown>;
|
|
140
|
+
/** Resolved host definition, before the model-written instruction suffix. */
|
|
141
|
+
base: RunDefinition;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** @internal Carried only through the journaled child creation path. */
|
|
145
|
+
export interface SubagentCreation {
|
|
146
|
+
record: Omit<SubagentRecord, "base">;
|
|
147
|
+
/** Self children reuse the creator's frozen frame, not its definition callbacks. */
|
|
148
|
+
source?: RunDefinition;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const MARK = Symbol("subagent-tool");
|
|
152
|
+
const NAME = /^[A-Za-z0-9_-]{1,64}$/;
|
|
153
|
+
/** UTF-8 JSON bytes for one model-supplied batch or one prepared helper. */
|
|
154
|
+
export const SUBAGENT_SPEC_BYTES = 65_536;
|
|
155
|
+
|
|
156
|
+
type RegisteredTool = NonNullable<AgentConfig["tools"]>[number];
|
|
157
|
+
interface SubagentTool extends Delegation {
|
|
158
|
+
readonly [MARK]: true;
|
|
159
|
+
bind(holder: () => Agent<unknown>): BoundSubagentTool;
|
|
160
|
+
}
|
|
161
|
+
interface BoundSubagentTool extends Delegation {
|
|
162
|
+
readonly [MARK]: true;
|
|
163
|
+
check(parent: RunSnapshot, journal: DelegationExecution): void;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export function isSubagentTool(tool: RegisteredTool): tool is SubagentTool {
|
|
167
|
+
return MARK in tool;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function count(value: number, zero = false): boolean {
|
|
171
|
+
return Number.isSafeInteger(value) && value >= (zero ? 0 : 1) && value <= 1_024;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function subagentLimits(base: RunLimits, lower?: Partial<RunLimits>): RunLimits {
|
|
175
|
+
if (
|
|
176
|
+
lower !== undefined &&
|
|
177
|
+
(!isRecord(lower) ||
|
|
178
|
+
Object.keys(lower).some((key) => !Object.hasOwn(base, key)) ||
|
|
179
|
+
Object.entries(lower).some(([key, value]) => {
|
|
180
|
+
const ceiling = Object.entries(base).find(([name]) => name === key)?.[1];
|
|
181
|
+
return typeof value !== "number" || ceiling === undefined || value > ceiling;
|
|
182
|
+
}))
|
|
183
|
+
)
|
|
184
|
+
throw new TypeError("A helper's limits may only lower its host template's limits.");
|
|
185
|
+
return readLimits({ ...base, ...lower });
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export function subagentInstructions(base: string, instructions?: string): string {
|
|
189
|
+
return instructions === undefined
|
|
190
|
+
? base
|
|
191
|
+
: `${base}\n\nInstructions from the agent that created you:\n${instructions}`;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function readDraft(raw: unknown, host = false): SubagentDraft {
|
|
195
|
+
if (
|
|
196
|
+
!isRecord(raw) ||
|
|
197
|
+
!isId(raw.name) ||
|
|
198
|
+
!NAME.test(raw.name) ||
|
|
199
|
+
!isId(raw.task) ||
|
|
200
|
+
(raw.instructions !== undefined && !isId(raw.instructions)) ||
|
|
201
|
+
(raw.tools !== undefined && !isNames(raw.tools)) ||
|
|
202
|
+
(raw.model !== undefined && (!isId(raw.model) || !NAME.test(raw.model))) ||
|
|
203
|
+
(raw.fork !== undefined && typeof raw.fork !== "boolean") ||
|
|
204
|
+
(raw.continues !== undefined && !isId(raw.continues)) ||
|
|
205
|
+
(raw.continues !== undefined &&
|
|
206
|
+
(raw.fork !== undefined ||
|
|
207
|
+
(!host &&
|
|
208
|
+
[raw.instructions, raw.tools, raw.model].some((value) => value !== undefined)))) ||
|
|
209
|
+
Object.keys(raw).some(
|
|
210
|
+
(key) =>
|
|
211
|
+
![
|
|
212
|
+
"name",
|
|
213
|
+
"task",
|
|
214
|
+
"instructions",
|
|
215
|
+
"tools",
|
|
216
|
+
"model",
|
|
217
|
+
"fork",
|
|
218
|
+
"continues",
|
|
219
|
+
...(host ? ["limits"] : []),
|
|
220
|
+
].includes(key),
|
|
221
|
+
) ||
|
|
222
|
+
(raw.limits !== undefined && !isRecord(raw.limits))
|
|
223
|
+
)
|
|
224
|
+
throw new TypeError(
|
|
225
|
+
"Give each helper a unique name (1 to 64 letters, digits, _ or -), a task and only the offered tools and model alias.",
|
|
226
|
+
);
|
|
227
|
+
// Limits are checked by subagentLimits against the actual template before admission.
|
|
228
|
+
const limits: Partial<RunLimits> = {};
|
|
229
|
+
if (raw.limits !== undefined) {
|
|
230
|
+
for (const key of [
|
|
231
|
+
"turns",
|
|
232
|
+
"toolCalls",
|
|
233
|
+
"elapsedMs",
|
|
234
|
+
"parallelTools",
|
|
235
|
+
"inlineBytes",
|
|
236
|
+
] as const) {
|
|
237
|
+
const value = raw.limits[key];
|
|
238
|
+
if (value !== undefined) {
|
|
239
|
+
if (typeof value !== "number") throw new TypeError("Helper limits must be numbers.");
|
|
240
|
+
limits[key] = value;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
if (Object.keys(raw.limits).some((key) => !Object.hasOwn(limits, key)))
|
|
244
|
+
throw new TypeError("Use only the template's run limits.");
|
|
245
|
+
}
|
|
246
|
+
return {
|
|
247
|
+
name: raw.name,
|
|
248
|
+
task: raw.task,
|
|
249
|
+
tools: raw.tools === undefined ? [] : [...raw.tools],
|
|
250
|
+
...(raw.instructions !== undefined ? { instructions: raw.instructions } : {}),
|
|
251
|
+
...(raw.model !== undefined ? { model: raw.model } : {}),
|
|
252
|
+
...(raw.fork === true ? { fork: true } : {}),
|
|
253
|
+
...(raw.continues !== undefined ? { continues: raw.continues } : {}),
|
|
254
|
+
...(raw.limits !== undefined ? { limits } : {}),
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Shape check only; the bound descriptor checks authority and identity during restore. */
|
|
259
|
+
export function isSubagentRecord(value: unknown): value is SubagentRecord {
|
|
260
|
+
if (
|
|
261
|
+
!isRecord(value) ||
|
|
262
|
+
!isRecord(value.identity) ||
|
|
263
|
+
!isId(value.identity.id) ||
|
|
264
|
+
!isId(value.identity.rootRunId) ||
|
|
265
|
+
!isId(value.identity.creatorRunId) ||
|
|
266
|
+
!isId(value.identity.originRunId) ||
|
|
267
|
+
(value.previousRunId !== undefined && !isId(value.previousRunId)) ||
|
|
268
|
+
(value.fork !== undefined &&
|
|
269
|
+
(!isRecord(value.fork) ||
|
|
270
|
+
!Array.isArray(value.fork.indices) ||
|
|
271
|
+
!value.fork.indices.every((index) => Number.isSafeInteger(index) && index >= 0))) ||
|
|
272
|
+
!isId(value.tool) ||
|
|
273
|
+
!isRecord(value.policy) ||
|
|
274
|
+
!isRecord(value.template) ||
|
|
275
|
+
typeof value.policy.maxLevels !== "number" ||
|
|
276
|
+
!count(value.policy.maxLevels) ||
|
|
277
|
+
typeof value.policy.maxPerCall !== "number" ||
|
|
278
|
+
!count(value.policy.maxPerCall) ||
|
|
279
|
+
typeof value.policy.maxPerRun !== "number" ||
|
|
280
|
+
!count(value.policy.maxPerRun, true) ||
|
|
281
|
+
!["none", "all"].includes(String(value.policy.defaultTools)) ||
|
|
282
|
+
!isRecord(value.policy.models) ||
|
|
283
|
+
typeof value.policy.prepare !== "boolean" ||
|
|
284
|
+
typeof value.policy.self !== "boolean" ||
|
|
285
|
+
typeof value.policy.needsApproval !== "boolean" ||
|
|
286
|
+
typeof value.policy.followUp !== "boolean" ||
|
|
287
|
+
(value.policy.fork !== null && !isForkPolicy(value.policy.fork))
|
|
288
|
+
)
|
|
289
|
+
return false;
|
|
290
|
+
try {
|
|
291
|
+
return (
|
|
292
|
+
equalData(value.requested, readDraft(value.requested, true)) &&
|
|
293
|
+
equalData(value.spec, readDraft(value.spec, true)) &&
|
|
294
|
+
jsonBytes([value.requested, value.spec]) <= SUBAGENT_SPEC_BYTES * 2 &&
|
|
295
|
+
isRecord(value.base)
|
|
296
|
+
);
|
|
297
|
+
} catch {
|
|
298
|
+
return false;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function isForkPolicy(value: unknown): value is Omit<SubagentForkPolicy, "select"> {
|
|
303
|
+
return (
|
|
304
|
+
isRecord(value) &&
|
|
305
|
+
isId(value.identity) &&
|
|
306
|
+
typeof value.maxMessages === "number" &&
|
|
307
|
+
count(value.maxMessages) &&
|
|
308
|
+
typeof value.maxBytes === "number" &&
|
|
309
|
+
Number.isSafeInteger(value.maxBytes) &&
|
|
310
|
+
value.maxBytes > 0 &&
|
|
311
|
+
value.maxBytes <= 1_000_000
|
|
312
|
+
);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function failure(content: string): ToolResult {
|
|
316
|
+
return { ok: false, kind: "invalid_input", content };
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
export function subagentTool(spec: SubagentToolSpec): Delegation {
|
|
320
|
+
if (
|
|
321
|
+
spec.fork !== undefined &&
|
|
322
|
+
(!isForkPolicy(spec.fork) || typeof spec.fork.select !== "function")
|
|
323
|
+
)
|
|
324
|
+
throw new TypeError(
|
|
325
|
+
"A fork needs a policy identity, a select function, maxMessages from 1 to 1024 and maxBytes from 1 to 1000000.",
|
|
326
|
+
);
|
|
327
|
+
if (
|
|
328
|
+
!isId(spec.name) ||
|
|
329
|
+
!isId(spec.description) ||
|
|
330
|
+
(spec.agent !== "self" && !spec.agent?.[AGENT_RUNTIME]) ||
|
|
331
|
+
(spec.defaultTools !== undefined && !["none", "all"].includes(spec.defaultTools)) ||
|
|
332
|
+
(spec.prepare !== undefined && typeof spec.prepare !== "function") ||
|
|
333
|
+
(spec.summarize !== undefined && typeof spec.summarize !== "function") ||
|
|
334
|
+
(spec.needsApproval !== undefined && typeof spec.needsApproval !== "boolean") ||
|
|
335
|
+
(spec.followUp !== undefined && typeof spec.followUp !== "boolean") ||
|
|
336
|
+
(spec.models !== undefined && !isRecord(spec.models))
|
|
337
|
+
)
|
|
338
|
+
throw new TypeError("A subagent tool needs a name, description and a host agent or self.");
|
|
339
|
+
const models: Record<string, ModelChoice> = Object.fromEntries(
|
|
340
|
+
Object.entries(spec.models ?? {}).map(([alias, choice]) => {
|
|
341
|
+
if (!NAME.test(alias) || !isRecord(choice) || !isId(choice.description))
|
|
342
|
+
throw new TypeError("Each model alias needs a short name and a description.");
|
|
343
|
+
const settings = readModelSettings(choice.settings);
|
|
344
|
+
if (
|
|
345
|
+
[settings.hostedTools, settings.toolChoice, settings.onActivity, settings.onRateLimit].some(
|
|
346
|
+
(value) => value !== undefined,
|
|
347
|
+
)
|
|
348
|
+
)
|
|
349
|
+
throw new TypeError("Model choices cannot change hosted tools, tool choice or callbacks.");
|
|
350
|
+
return [alias, { description: choice.description, settings }];
|
|
351
|
+
}),
|
|
352
|
+
);
|
|
353
|
+
const policy: SubagentPolicy = immutableCopy({
|
|
354
|
+
models,
|
|
355
|
+
defaultTools: spec.defaultTools ?? "none",
|
|
356
|
+
maxLevels: spec.maxLevels ?? 1,
|
|
357
|
+
maxPerCall: spec.maxPerCall ?? 4,
|
|
358
|
+
maxPerRun: spec.maxPerRun ?? 8,
|
|
359
|
+
needsApproval: spec.needsApproval ?? false,
|
|
360
|
+
prepare: !!spec.prepare,
|
|
361
|
+
self: spec.agent === "self",
|
|
362
|
+
fork: spec.fork
|
|
363
|
+
? {
|
|
364
|
+
identity: spec.fork.identity,
|
|
365
|
+
maxMessages: spec.fork.maxMessages,
|
|
366
|
+
maxBytes: spec.fork.maxBytes,
|
|
367
|
+
}
|
|
368
|
+
: null,
|
|
369
|
+
followUp: spec.followUp ?? false,
|
|
370
|
+
});
|
|
371
|
+
if (!count(policy.maxLevels) || !count(policy.maxPerCall) || !count(policy.maxPerRun, true))
|
|
372
|
+
throw new TypeError("Helper counts must be whole numbers up to 1024; only maxPerRun may be 0.");
|
|
373
|
+
const { name, description, prepare, summarize } = spec;
|
|
374
|
+
const selectFork = spec.fork?.select;
|
|
375
|
+
const target = spec.agent;
|
|
376
|
+
const descriptor: SubagentTool = Object.freeze({
|
|
377
|
+
[MARK]: true as const,
|
|
378
|
+
kind: "delegation",
|
|
379
|
+
name,
|
|
380
|
+
needsApproval: policy.needsApproval,
|
|
381
|
+
specialists: target === "self" ? [] : [target],
|
|
382
|
+
definition() {
|
|
383
|
+
throw new TypeError("Register subagentTool on an agent before reading its definition.");
|
|
384
|
+
},
|
|
385
|
+
async execute() {
|
|
386
|
+
throw new TypeError("Start model-created helpers through their registered agent.");
|
|
387
|
+
},
|
|
388
|
+
bind(holder: () => Agent<unknown>) {
|
|
389
|
+
const template = () => (target === "self" ? holder() : target);
|
|
390
|
+
function grantable(): RegisteredTool[] {
|
|
391
|
+
const owner = holder()[AGENT_RUNTIME];
|
|
392
|
+
const worker = template()[AGENT_RUNTIME];
|
|
393
|
+
// TanStack filters the starting turn's tools. Match objects too: an identically named
|
|
394
|
+
// tool with a different implementation is not the same capability.
|
|
395
|
+
return worker.tools.filter(
|
|
396
|
+
(tool) =>
|
|
397
|
+
owner.tools.includes(tool) &&
|
|
398
|
+
(owner.enabledTools === undefined || owner.enabledTools.includes(tool.name)) &&
|
|
399
|
+
(worker.enabledTools === undefined || worker.enabledTools.includes(tool.name)) &&
|
|
400
|
+
!isHandoff(tool) &&
|
|
401
|
+
(!isDelegation(tool) || (tool === descriptor && policy.maxLevels > 1)),
|
|
402
|
+
);
|
|
403
|
+
}
|
|
404
|
+
function allowed(parent: RunSnapshot): string[] {
|
|
405
|
+
return grantable()
|
|
406
|
+
.map((tool) => tool.name)
|
|
407
|
+
.filter((name) => parent.definition.enabledTools.includes(name));
|
|
408
|
+
}
|
|
409
|
+
function drafts(raw: unknown, parent: RunSnapshot): SubagentDraft[] {
|
|
410
|
+
if (jsonBytes(raw) > SUBAGENT_SPEC_BYTES)
|
|
411
|
+
throw new TypeError(
|
|
412
|
+
`The helper definitions exceed ${SUBAGENT_SPEC_BYTES} UTF-8 JSON bytes. Send less text.`,
|
|
413
|
+
);
|
|
414
|
+
if (
|
|
415
|
+
!isRecord(raw) ||
|
|
416
|
+
Object.keys(raw).length !== 1 ||
|
|
417
|
+
!Array.isArray(raw.agents) ||
|
|
418
|
+
raw.agents.length < 1 ||
|
|
419
|
+
raw.agents.length > policy.maxPerCall
|
|
420
|
+
)
|
|
421
|
+
throw new TypeError(`Pass agents with 1 to ${policy.maxPerCall} helper definitions.`);
|
|
422
|
+
const available = allowed(parent);
|
|
423
|
+
const result = raw.agents.map((raw) => {
|
|
424
|
+
const draft = readDraft(raw);
|
|
425
|
+
if (draft.fork && !policy.fork)
|
|
426
|
+
throw new TypeError("The host has not allowed history forks. Send only a task.");
|
|
427
|
+
if (draft.continues && !policy.followUp)
|
|
428
|
+
throw new TypeError("The host has not allowed follow-ups. Start a new helper.");
|
|
429
|
+
if (
|
|
430
|
+
!draft.continues &&
|
|
431
|
+
isRecord(raw) &&
|
|
432
|
+
raw.tools === undefined &&
|
|
433
|
+
policy.defaultTools === "all"
|
|
434
|
+
)
|
|
435
|
+
draft.tools = [...available];
|
|
436
|
+
if (draft.tools.some((tool) => !available.includes(tool)))
|
|
437
|
+
throw new TypeError(
|
|
438
|
+
"A helper may use only tools enabled on its creator and offered by its host template.",
|
|
439
|
+
);
|
|
440
|
+
if (draft.model !== undefined && !Object.hasOwn(models, draft.model))
|
|
441
|
+
throw new TypeError("Choose a model alias from the host's menu, or omit model.");
|
|
442
|
+
draft.tools = available.filter((name) => draft.tools.includes(name));
|
|
443
|
+
return draft;
|
|
444
|
+
});
|
|
445
|
+
if (new Set(result.map((draft) => draft.name)).size !== result.length)
|
|
446
|
+
throw new TypeError("Use a different name for each helper in this call.");
|
|
447
|
+
const targets = result.flatMap((draft) => (draft.continues ? [draft.continues] : []));
|
|
448
|
+
if (new Set(targets).size !== targets.length)
|
|
449
|
+
throw new TypeError(
|
|
450
|
+
"Send only one follow-up per helper in a call. Wait for it to finish before sending another.",
|
|
451
|
+
);
|
|
452
|
+
return result;
|
|
453
|
+
}
|
|
454
|
+
function nodes(parent: RunSnapshot, before?: DelegationExecution): RunSnapshot[] {
|
|
455
|
+
const ordered = parent.models.flatMap((model) =>
|
|
456
|
+
model.status === "completed"
|
|
457
|
+
? model.tools.flatMap((tool) => {
|
|
458
|
+
const entry = parent.delegations.find((entry) => entry.operationId === tool.id);
|
|
459
|
+
return entry ? [entry] : [];
|
|
460
|
+
})
|
|
461
|
+
: [],
|
|
462
|
+
);
|
|
463
|
+
const entries = before ? ordered.slice(0, ordered.indexOf(before)) : ordered;
|
|
464
|
+
return entries.flatMap((entry) =>
|
|
465
|
+
entry.children.flatMap((child) =>
|
|
466
|
+
child.snapshot.kind === "agent" && child.snapshot.subagent?.tool === name
|
|
467
|
+
? [child.snapshot]
|
|
468
|
+
: [],
|
|
469
|
+
),
|
|
470
|
+
);
|
|
471
|
+
}
|
|
472
|
+
function records(parent: RunSnapshot) {
|
|
473
|
+
return nodes(parent).flatMap((node) => (node.subagent ? [node.subagent] : []));
|
|
474
|
+
}
|
|
475
|
+
function previous(
|
|
476
|
+
parent: RunSnapshot,
|
|
477
|
+
journal: DelegationExecution,
|
|
478
|
+
requested: SubagentDraft,
|
|
479
|
+
): RunSnapshot {
|
|
480
|
+
const node = nodes(parent, journal)
|
|
481
|
+
.reverse()
|
|
482
|
+
.find((node) => node.subagent?.identity.id === requested.continues);
|
|
483
|
+
if (
|
|
484
|
+
!node?.subagent ||
|
|
485
|
+
node.subagent.spec.name !== requested.name ||
|
|
486
|
+
node.subagent.identity.creatorRunId !== parent.runId ||
|
|
487
|
+
node.subagent.identity.rootRunId !== parent.tree.runId
|
|
488
|
+
)
|
|
489
|
+
throw new TypeError(
|
|
490
|
+
"Use the helperId and name returned by this tool in this run. Other helpers cannot be continued here.",
|
|
491
|
+
);
|
|
492
|
+
if (
|
|
493
|
+
!equalData(node.subagent.policy, policy) ||
|
|
494
|
+
!equalData(node.subagent.template, template()[AGENT_RUNTIME].configuration())
|
|
495
|
+
)
|
|
496
|
+
throw new TypeError(
|
|
497
|
+
"The helper's host template changed. Restore its admitted configuration before continuing.",
|
|
498
|
+
);
|
|
499
|
+
if (
|
|
500
|
+
node.state.status !== "completed" ||
|
|
501
|
+
node.models.some(
|
|
502
|
+
(model) =>
|
|
503
|
+
model.status !== "completed" ||
|
|
504
|
+
model.tools.some((tool) => tool.status !== "completed"),
|
|
505
|
+
)
|
|
506
|
+
)
|
|
507
|
+
throw new TypeError(
|
|
508
|
+
"This helper has unfinished or uncertain work. Resolve its requests or reconcile it on the host before continuing.",
|
|
509
|
+
);
|
|
510
|
+
return node;
|
|
511
|
+
}
|
|
512
|
+
function followupSpec(prior: SubagentRecord, task: string, helperId: string): SubagentDraft {
|
|
513
|
+
const { fork: _fork, ...original } = prior.spec;
|
|
514
|
+
return { ...original, task, continues: helperId };
|
|
515
|
+
}
|
|
516
|
+
function forkHistory(
|
|
517
|
+
parent: RunSnapshot,
|
|
518
|
+
journal: DelegationExecution,
|
|
519
|
+
indices: readonly number[],
|
|
520
|
+
): AgentMessage[] {
|
|
521
|
+
const bound = policy.fork;
|
|
522
|
+
const position = parent.models.findIndex(
|
|
523
|
+
(model) =>
|
|
524
|
+
model.status === "completed" &&
|
|
525
|
+
model.tools.some((tool) => tool.id === journal.operationId),
|
|
526
|
+
);
|
|
527
|
+
const source = conversationOnly(conversationOf(parent, position));
|
|
528
|
+
if (
|
|
529
|
+
!bound ||
|
|
530
|
+
position < 0 ||
|
|
531
|
+
!Array.isArray(indices) ||
|
|
532
|
+
indices.length > bound.maxMessages ||
|
|
533
|
+
indices.some(
|
|
534
|
+
(index, i) =>
|
|
535
|
+
!Number.isSafeInteger(index) ||
|
|
536
|
+
index < 0 ||
|
|
537
|
+
index >= source.length ||
|
|
538
|
+
index <= (indices[i - 1] ?? -1),
|
|
539
|
+
)
|
|
540
|
+
)
|
|
541
|
+
throw new TypeError(
|
|
542
|
+
"The fork must select an ordered subset within the host's message limit.",
|
|
543
|
+
);
|
|
544
|
+
const history = indices.flatMap((index) => (source[index] ? [source[index]] : []));
|
|
545
|
+
if (jsonBytes(history) > bound.maxBytes)
|
|
546
|
+
throw new TypeError(
|
|
547
|
+
"The selected fork history exceeds the host's byte limit. Select fewer messages.",
|
|
548
|
+
);
|
|
549
|
+
return history;
|
|
550
|
+
}
|
|
551
|
+
function check(parent: RunSnapshot, journal: DelegationExecution): void {
|
|
552
|
+
const runtime = template()[AGENT_RUNTIME];
|
|
553
|
+
const model = parent.models.find(
|
|
554
|
+
(model) =>
|
|
555
|
+
model.status === "completed" &&
|
|
556
|
+
model.tools.some((tool) => tool.id === journal.operationId),
|
|
557
|
+
);
|
|
558
|
+
const position =
|
|
559
|
+
model?.status === "completed"
|
|
560
|
+
? model.tools.findIndex((tool) => tool.id === journal.operationId)
|
|
561
|
+
: -1;
|
|
562
|
+
const execution = model?.status === "completed" ? model.tools[position] : undefined;
|
|
563
|
+
const call =
|
|
564
|
+
model?.status === "completed" ? model.turn.message.toolCalls?.[position] : undefined;
|
|
565
|
+
if (!call || !execution || journal.kind !== "delegation")
|
|
566
|
+
throw new TypeError("Missing helper creation call.");
|
|
567
|
+
// An expired approval may have edited the original call. Its admission remains pinned;
|
|
568
|
+
// a later edit is checked again by execute, never used to redefine an admitted child.
|
|
569
|
+
const sources: unknown[] = [
|
|
570
|
+
parseToolArgs(call.arguments),
|
|
571
|
+
...(execution.asks ?? []).flatMap((ask) =>
|
|
572
|
+
ask.decision?.type === "approve" && ask.decision.arguments !== undefined
|
|
573
|
+
? [ask.decision.arguments]
|
|
574
|
+
: [],
|
|
575
|
+
),
|
|
576
|
+
];
|
|
577
|
+
const candidates = sources.flatMap((raw) => {
|
|
578
|
+
try {
|
|
579
|
+
return [drafts(raw, parent)];
|
|
580
|
+
} catch {
|
|
581
|
+
return [];
|
|
582
|
+
}
|
|
583
|
+
});
|
|
584
|
+
for (const child of journal.children) {
|
|
585
|
+
if (child.snapshot.kind !== "agent")
|
|
586
|
+
throw new TypeError("A generated helper must be an agent.");
|
|
587
|
+
const index = Number(child.key.slice("helper-".length)) - 1;
|
|
588
|
+
const record = child.snapshot.subagent;
|
|
589
|
+
if (
|
|
590
|
+
!record ||
|
|
591
|
+
!Number.isSafeInteger(index) ||
|
|
592
|
+
index < 0 ||
|
|
593
|
+
index >= policy.maxPerCall ||
|
|
594
|
+
child.key !== `helper-${index + 1}` ||
|
|
595
|
+
record.tool !== name ||
|
|
596
|
+
!equalData(record.policy, policy) ||
|
|
597
|
+
!equalData(record.template, runtime.configuration()) ||
|
|
598
|
+
!candidates.some((items) => equalData(items[index], record.requested))
|
|
599
|
+
)
|
|
600
|
+
throw new TypeError(
|
|
601
|
+
"The saved helper definition or capabilities changed. Restore its host configuration before resuming.",
|
|
602
|
+
);
|
|
603
|
+
const prior = record.requested.continues
|
|
604
|
+
? previous(parent, journal, record.requested)
|
|
605
|
+
: undefined;
|
|
606
|
+
if (
|
|
607
|
+
record.identity.rootRunId !== parent.tree.runId ||
|
|
608
|
+
record.identity.creatorRunId !== parent.runId ||
|
|
609
|
+
(prior
|
|
610
|
+
? !equalData(record.identity, prior.subagent?.identity) ||
|
|
611
|
+
record.previousRunId !== prior.runId
|
|
612
|
+
: record.previousRunId !== undefined ||
|
|
613
|
+
record.identity.originRunId !== child.snapshot.runId)
|
|
614
|
+
)
|
|
615
|
+
throw new TypeError(
|
|
616
|
+
"The helper identity does not belong to this creator or conversation.",
|
|
617
|
+
);
|
|
618
|
+
let history: AgentMessage[] = [];
|
|
619
|
+
if (prior?.subagent) {
|
|
620
|
+
if (
|
|
621
|
+
!policy.followUp ||
|
|
622
|
+
jsonBytes(record.spec) > SUBAGENT_SPEC_BYTES ||
|
|
623
|
+
record.fork ||
|
|
624
|
+
!equalData(
|
|
625
|
+
record.spec,
|
|
626
|
+
followupSpec(prior.subagent, record.spec.task, prior.subagent.identity.id),
|
|
627
|
+
) ||
|
|
628
|
+
!equalData(record.base, prior.subagent.base)
|
|
629
|
+
)
|
|
630
|
+
throw new TypeError("A follow-up must keep its helper's admitted definition.");
|
|
631
|
+
// Only the new task may be rewritten by host admission policy.
|
|
632
|
+
checkPrepared(
|
|
633
|
+
record.requested,
|
|
634
|
+
{ ...record.requested, task: record.spec.task },
|
|
635
|
+
parent,
|
|
636
|
+
);
|
|
637
|
+
history = conversationOf(prior);
|
|
638
|
+
} else {
|
|
639
|
+
checkPrepared(record.requested, record.spec, parent);
|
|
640
|
+
if (record.spec.fork) {
|
|
641
|
+
if (!record.fork) throw new TypeError("Missing admitted fork history.");
|
|
642
|
+
history = forkHistory(parent, journal, record.fork.indices);
|
|
643
|
+
} else if (record.fork)
|
|
644
|
+
throw new TypeError("A task-only helper cannot carry fork history.");
|
|
645
|
+
}
|
|
646
|
+
// Child creation repairs reused tool-call ids. Compare the same canonical input,
|
|
647
|
+
// not the predecessor's unchanged journal.
|
|
648
|
+
const start = runtime.freeze(
|
|
649
|
+
readInput(
|
|
650
|
+
{ messages: [...history, { role: "user", content: record.spec.task }] },
|
|
651
|
+
"trusted",
|
|
652
|
+
),
|
|
653
|
+
);
|
|
654
|
+
if (record.spec.tools.some((name) => !allowed(parent).includes(name)))
|
|
655
|
+
throw new TypeError("The helper's tools are no longer granted by its creator.");
|
|
656
|
+
const expectedNames = runtime.tools
|
|
657
|
+
.map((tool) => tool.name)
|
|
658
|
+
.filter((name) => record.spec.tools.includes(name));
|
|
659
|
+
if (runtime.configuration().output !== null) expectedNames.push("submit_result");
|
|
660
|
+
const baseSettings = policy.self
|
|
661
|
+
? parent.definition.modelSettings
|
|
662
|
+
: runtime.configuration().modelSettings;
|
|
663
|
+
const expectedSettings = {
|
|
664
|
+
...readModelSettings(baseSettings),
|
|
665
|
+
...models[record.spec.model ?? ""]?.settings,
|
|
666
|
+
};
|
|
667
|
+
const baseInstructions = policy.self
|
|
668
|
+
? parent.definition.instructions
|
|
669
|
+
: runtime.configuration().instructions;
|
|
670
|
+
if (
|
|
671
|
+
child.snapshot.agentId !== template().id ||
|
|
672
|
+
child.snapshot.version !== template().version ||
|
|
673
|
+
child.snapshot.session !== undefined ||
|
|
674
|
+
!equalData(child.snapshot.history, start.history) ||
|
|
675
|
+
child.snapshot.input !== start.input ||
|
|
676
|
+
!equalData(child.snapshot.limits, subagentLimits(runtime.limits, record.spec.limits)) ||
|
|
677
|
+
!equalData(record.base.enabledTools, expectedNames) ||
|
|
678
|
+
!equalData(record.base.modelSettings, expectedSettings) ||
|
|
679
|
+
(typeof baseInstructions === "string" &&
|
|
680
|
+
record.base.instructions !== baseInstructions) ||
|
|
681
|
+
!equalData(child.snapshot.definition, {
|
|
682
|
+
...record.base,
|
|
683
|
+
instructions: subagentInstructions(
|
|
684
|
+
record.base.instructions,
|
|
685
|
+
record.spec.instructions,
|
|
686
|
+
),
|
|
687
|
+
})
|
|
688
|
+
)
|
|
689
|
+
throw new TypeError(
|
|
690
|
+
"The saved helper no longer matches its admitted task, tools or definition.",
|
|
691
|
+
);
|
|
692
|
+
}
|
|
693
|
+
const admitted = records(parent);
|
|
694
|
+
const origins = admitted.filter((record) => !record.previousRunId);
|
|
695
|
+
if (
|
|
696
|
+
admitted.length > policy.maxPerRun ||
|
|
697
|
+
new Set(origins.map((record) => record.spec.name)).size !== origins.length ||
|
|
698
|
+
new Set(origins.map((record) => record.identity.id)).size !== origins.length
|
|
699
|
+
)
|
|
700
|
+
throw new TypeError(
|
|
701
|
+
"The saved helpers exceed this tool's per-run limit or reuse a name.",
|
|
702
|
+
);
|
|
703
|
+
}
|
|
704
|
+
function checkPrepared(
|
|
705
|
+
requested: SubagentDraft,
|
|
706
|
+
prepared: SubagentDraft,
|
|
707
|
+
parent: RunSnapshot,
|
|
708
|
+
): void {
|
|
709
|
+
if (
|
|
710
|
+
(!prepare && !equalData(requested, prepared)) ||
|
|
711
|
+
jsonBytes(prepared) > SUBAGENT_SPEC_BYTES ||
|
|
712
|
+
prepared.name !== requested.name ||
|
|
713
|
+
prepared.model !== requested.model ||
|
|
714
|
+
prepared.fork !== requested.fork ||
|
|
715
|
+
prepared.continues !== requested.continues ||
|
|
716
|
+
(requested.continues !== undefined &&
|
|
717
|
+
!equalData({ ...prepared, task: requested.task }, requested)) ||
|
|
718
|
+
prepared.tools.some(
|
|
719
|
+
(name) => !requested.tools.includes(name) || !allowed(parent).includes(name),
|
|
720
|
+
)
|
|
721
|
+
)
|
|
722
|
+
throw new TypeError(
|
|
723
|
+
"Admission policy may narrow tools and limits, not change identity or grant capabilities.",
|
|
724
|
+
);
|
|
725
|
+
subagentLimits(template()[AGENT_RUNTIME].limits, prepared.limits);
|
|
726
|
+
}
|
|
727
|
+
async function prepareDraft(
|
|
728
|
+
requested: SubagentDraft,
|
|
729
|
+
parent: RunSnapshot,
|
|
730
|
+
context: SubagentContext,
|
|
731
|
+
): Promise<SubagentDraft | { refuse: string }> {
|
|
732
|
+
try {
|
|
733
|
+
const prepared = prepare
|
|
734
|
+
? await untilAbort(
|
|
735
|
+
Promise.resolve(prepare(immutableCopy(requested), Object.freeze(context))),
|
|
736
|
+
context.signal,
|
|
737
|
+
)
|
|
738
|
+
: requested;
|
|
739
|
+
context.signal.throwIfAborted();
|
|
740
|
+
if (isRecord(prepared) && isId(prepared.refuse)) {
|
|
741
|
+
if (jsonBytes(prepared.refuse) > SUBAGENT_SPEC_BYTES)
|
|
742
|
+
throw new TypeError("The admission refusal is too large.");
|
|
743
|
+
return { refuse: prepared.refuse };
|
|
744
|
+
}
|
|
745
|
+
const admitted = readDraft(prepared, true);
|
|
746
|
+
checkPrepared(requested, admitted, parent);
|
|
747
|
+
admitted.tools = allowed(parent).filter((name) => admitted.tools.includes(name));
|
|
748
|
+
return admitted;
|
|
749
|
+
} catch {
|
|
750
|
+
context.signal.throwIfAborted();
|
|
751
|
+
fail(
|
|
752
|
+
"subagent_policy_failed",
|
|
753
|
+
"The helper admission policy failed or tried to grant capabilities. Check the host policy before starting new work.",
|
|
754
|
+
);
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
return Object.freeze({
|
|
758
|
+
[MARK]: true as const,
|
|
759
|
+
kind: "delegation" as const,
|
|
760
|
+
name,
|
|
761
|
+
needsApproval: policy.needsApproval,
|
|
762
|
+
get specialists() {
|
|
763
|
+
return [template()];
|
|
764
|
+
},
|
|
765
|
+
definition(): ToolDefinition {
|
|
766
|
+
const aliases = Object.keys(models);
|
|
767
|
+
const grants = grantable().map((tool) => tool.name);
|
|
768
|
+
return {
|
|
769
|
+
name,
|
|
770
|
+
description,
|
|
771
|
+
inputSchema: {
|
|
772
|
+
type: "object",
|
|
773
|
+
properties: {
|
|
774
|
+
agents: {
|
|
775
|
+
type: "array",
|
|
776
|
+
minItems: 1,
|
|
777
|
+
maxItems: policy.maxPerCall,
|
|
778
|
+
items: {
|
|
779
|
+
type: "object",
|
|
780
|
+
properties: {
|
|
781
|
+
name: {
|
|
782
|
+
type: "string",
|
|
783
|
+
description: "Private name: 1 to 64 letters, digits, _ or -.",
|
|
784
|
+
},
|
|
785
|
+
task: { type: "string" },
|
|
786
|
+
instructions: { type: "string" },
|
|
787
|
+
...(policy.fork
|
|
788
|
+
? {
|
|
789
|
+
fork: {
|
|
790
|
+
type: "boolean",
|
|
791
|
+
description: "Ask the host to share approved earlier messages.",
|
|
792
|
+
},
|
|
793
|
+
}
|
|
794
|
+
: {}),
|
|
795
|
+
...(policy.followUp
|
|
796
|
+
? {
|
|
797
|
+
continues: {
|
|
798
|
+
type: "string",
|
|
799
|
+
description:
|
|
800
|
+
"The helperId returned by this tool. Pass only name, task and continues for a follow-up.",
|
|
801
|
+
},
|
|
802
|
+
}
|
|
803
|
+
: {}),
|
|
804
|
+
tools: {
|
|
805
|
+
type: "array",
|
|
806
|
+
items: { type: "string", ...(grants.length ? { enum: grants } : {}) },
|
|
807
|
+
...(grants.length ? {} : { maxItems: 0 }),
|
|
808
|
+
uniqueItems: true,
|
|
809
|
+
},
|
|
810
|
+
...(aliases.length
|
|
811
|
+
? {
|
|
812
|
+
model: {
|
|
813
|
+
type: "string",
|
|
814
|
+
enum: aliases,
|
|
815
|
+
description: aliases
|
|
816
|
+
.map((alias) => `${alias}: ${models[alias]?.description}`)
|
|
817
|
+
.join("\n"),
|
|
818
|
+
},
|
|
819
|
+
}
|
|
820
|
+
: {}),
|
|
821
|
+
},
|
|
822
|
+
required: ["name", "task"],
|
|
823
|
+
additionalProperties: false,
|
|
824
|
+
},
|
|
825
|
+
},
|
|
826
|
+
},
|
|
827
|
+
required: ["agents"],
|
|
828
|
+
additionalProperties: false,
|
|
829
|
+
},
|
|
830
|
+
};
|
|
831
|
+
},
|
|
832
|
+
check,
|
|
833
|
+
async execute(raw: unknown, context: DelegationContext): Promise<ToolResult> {
|
|
834
|
+
const internal = context[SUBAGENT_CONTEXT];
|
|
835
|
+
if (!internal)
|
|
836
|
+
throw new TypeError("Helper creation needs a journaled delegation context.");
|
|
837
|
+
const { parent, journal, scope, request, signal } = internal;
|
|
838
|
+
let items: SubagentDraft[];
|
|
839
|
+
try {
|
|
840
|
+
items = drafts(raw, parent);
|
|
841
|
+
} catch (error) {
|
|
842
|
+
if (journal.children.length)
|
|
843
|
+
fail(
|
|
844
|
+
"subagent_input_changed",
|
|
845
|
+
"An admitted helper's definition cannot change. Reconcile the saved run before starting different work.",
|
|
846
|
+
);
|
|
847
|
+
return failure(error instanceof Error ? error.message : "Invalid helper definitions.");
|
|
848
|
+
}
|
|
849
|
+
check(parent, journal);
|
|
850
|
+
for (const child of journal.children)
|
|
851
|
+
if (
|
|
852
|
+
!equalData(
|
|
853
|
+
child.snapshot.kind === "agent" ? child.snapshot.subagent?.requested : undefined,
|
|
854
|
+
items[Number(child.key.slice("helper-".length)) - 1],
|
|
855
|
+
)
|
|
856
|
+
)
|
|
857
|
+
fail(
|
|
858
|
+
"subagent_input_changed",
|
|
859
|
+
"An admitted helper's definition cannot change. Reconcile the saved run before starting different work.",
|
|
860
|
+
);
|
|
861
|
+
const ancestors = scope.path.reduce<TreeNode[]>(
|
|
862
|
+
(nodes, step) => {
|
|
863
|
+
const parent = nodes.at(-1);
|
|
864
|
+
const node =
|
|
865
|
+
parent &&
|
|
866
|
+
childJournals(parent)
|
|
867
|
+
.find((entry) => entry.operationId === step.operationId)
|
|
868
|
+
?.children.find((child) => child.key === step.key)?.snapshot;
|
|
869
|
+
if (!node) throw new TypeError("Missing helper ancestor in the execution tree.");
|
|
870
|
+
nodes.push(node);
|
|
871
|
+
return nodes;
|
|
872
|
+
},
|
|
873
|
+
[scope.tree.root],
|
|
874
|
+
);
|
|
875
|
+
const created = ancestors.flatMap((node) =>
|
|
876
|
+
node.kind === "agent" && node.subagent ? [node.subagent] : [],
|
|
877
|
+
);
|
|
878
|
+
const level = created.length + 1;
|
|
879
|
+
if (
|
|
880
|
+
level > Math.min(policy.maxLevels, ...created.map((record) => record.policy.maxLevels))
|
|
881
|
+
)
|
|
882
|
+
return failure(
|
|
883
|
+
"Recursive helper creation is not allowed here. Complete the task with the tools you have.",
|
|
884
|
+
);
|
|
885
|
+
const existing = records(parent);
|
|
886
|
+
const remaining = Math.min(
|
|
887
|
+
policy.maxPerRun - existing.length,
|
|
888
|
+
scope.tree.childRoom(scope.depth + 1),
|
|
889
|
+
);
|
|
890
|
+
if (items.length - journal.children.length > remaining)
|
|
891
|
+
return failure(
|
|
892
|
+
`There is room for ${Math.max(0, remaining)} more helpers. Request fewer helpers or do the work here.`,
|
|
893
|
+
);
|
|
894
|
+
const continuations = new Map<string, RunSnapshot>();
|
|
895
|
+
try {
|
|
896
|
+
for (const item of items)
|
|
897
|
+
if (item.continues)
|
|
898
|
+
continuations.set(item.continues, previous(parent, journal, item));
|
|
899
|
+
} catch (error) {
|
|
900
|
+
if (journal.children.length) throw error;
|
|
901
|
+
return failure(error instanceof Error ? error.message : "Invalid helper follow-up.");
|
|
902
|
+
}
|
|
903
|
+
if (
|
|
904
|
+
items.some(
|
|
905
|
+
(item, index) =>
|
|
906
|
+
!item.continues &&
|
|
907
|
+
!journal.children.some((child) => child.key === `helper-${index + 1}`) &&
|
|
908
|
+
existing.some((record) => record.spec.name === item.name),
|
|
909
|
+
)
|
|
910
|
+
)
|
|
911
|
+
return failure("A helper with that name already exists in this run. Use a new name.");
|
|
912
|
+
const handles = [];
|
|
913
|
+
const results: SubagentResult[] = [];
|
|
914
|
+
for (const [index, requested] of items.entries()) {
|
|
915
|
+
const key = `helper-${index + 1}`;
|
|
916
|
+
const saved = journal.children.find((child) => child.key === key);
|
|
917
|
+
const prior = requested.continues ? continuations.get(requested.continues) : undefined;
|
|
918
|
+
const admissionContext: SubagentContext = {
|
|
919
|
+
call: immutableCopy(request),
|
|
920
|
+
depth: scope.depth + 1,
|
|
921
|
+
level,
|
|
922
|
+
grantable: Object.freeze(allowed(parent)),
|
|
923
|
+
signal,
|
|
924
|
+
};
|
|
925
|
+
if (saved && saved.snapshot.kind !== "agent")
|
|
926
|
+
throw new TypeError("A generated helper must be an agent.");
|
|
927
|
+
const savedHelper =
|
|
928
|
+
saved?.snapshot.kind === "agent" ? saved.snapshot.subagent : undefined;
|
|
929
|
+
let admitted = savedHelper?.spec;
|
|
930
|
+
if (!admitted) {
|
|
931
|
+
const prepared = await prepareDraft(requested, parent, admissionContext);
|
|
932
|
+
if ("refuse" in prepared) {
|
|
933
|
+
results.push({ name: requested.name, status: "refused", error: prepared.refuse });
|
|
934
|
+
continue;
|
|
935
|
+
}
|
|
936
|
+
admitted = prior?.subagent
|
|
937
|
+
? followupSpec(prior.subagent, prepared.task, prior.subagent.identity.id)
|
|
938
|
+
: prepared;
|
|
939
|
+
}
|
|
940
|
+
if (jsonBytes(admitted) > SUBAGENT_SPEC_BYTES)
|
|
941
|
+
fail(
|
|
942
|
+
"subagent_spec_limit",
|
|
943
|
+
`The helper's saved definition and new task exceed ${SUBAGENT_SPEC_BYTES} UTF-8 JSON bytes. Send a shorter task.`,
|
|
944
|
+
);
|
|
945
|
+
let fork = savedHelper?.fork;
|
|
946
|
+
let history = prior ? conversationOf(prior) : [];
|
|
947
|
+
if (admitted.fork) {
|
|
948
|
+
if (!fork) {
|
|
949
|
+
if (!selectFork) throw new TypeError("Missing host fork policy.");
|
|
950
|
+
try {
|
|
951
|
+
const selected = await untilAbort(
|
|
952
|
+
Promise.resolve(
|
|
953
|
+
selectFork(
|
|
954
|
+
immutableCopy(conversationOnly(context.conversation)),
|
|
955
|
+
Object.freeze(admissionContext),
|
|
956
|
+
),
|
|
957
|
+
),
|
|
958
|
+
signal,
|
|
959
|
+
);
|
|
960
|
+
history = forkHistory(parent, journal, selected);
|
|
961
|
+
fork = { indices: [...selected] };
|
|
962
|
+
} catch {
|
|
963
|
+
signal.throwIfAborted();
|
|
964
|
+
fail(
|
|
965
|
+
"subagent_policy_failed",
|
|
966
|
+
"The fork policy failed or exceeded its limits. Check the host's history filter before trying again.",
|
|
967
|
+
);
|
|
968
|
+
}
|
|
969
|
+
} else history = forkHistory(parent, journal, fork.indices);
|
|
970
|
+
}
|
|
971
|
+
// New history use is an authority boundary, not permission inferred from prose.
|
|
972
|
+
// Also recheck on replay before an unfinished child can continue.
|
|
973
|
+
if (admitted.fork || prior) {
|
|
974
|
+
await internal.recheck(holder(), parent);
|
|
975
|
+
if (prior) await internal.recheck(template(), prior);
|
|
976
|
+
}
|
|
977
|
+
const identity = savedHelper?.identity ??
|
|
978
|
+
prior?.subagent?.identity ?? {
|
|
979
|
+
id: crypto.randomUUID(),
|
|
980
|
+
rootRunId: parent.tree.runId,
|
|
981
|
+
creatorRunId: parent.runId,
|
|
982
|
+
originRunId: childRunId(journal.operationId, key),
|
|
983
|
+
};
|
|
984
|
+
const creation: SubagentCreation = {
|
|
985
|
+
record: {
|
|
986
|
+
identity,
|
|
987
|
+
...(prior ? { previousRunId: prior.runId } : {}),
|
|
988
|
+
...(fork ? { fork } : {}),
|
|
989
|
+
tool: name,
|
|
990
|
+
requested,
|
|
991
|
+
spec: admitted,
|
|
992
|
+
policy,
|
|
993
|
+
template: template()[AGENT_RUNTIME].configuration(),
|
|
994
|
+
},
|
|
995
|
+
...(prior?.subagent
|
|
996
|
+
? { source: prior.subagent.base }
|
|
997
|
+
: policy.self
|
|
998
|
+
? { source: parent.definition }
|
|
999
|
+
: {}),
|
|
1000
|
+
};
|
|
1001
|
+
const child = internal.child(
|
|
1002
|
+
key,
|
|
1003
|
+
template(),
|
|
1004
|
+
{ messages: [...history, { role: "user", content: admitted.task }] },
|
|
1005
|
+
creation,
|
|
1006
|
+
);
|
|
1007
|
+
handles.push({ index: results.length, child });
|
|
1008
|
+
results.push({
|
|
1009
|
+
name: requested.name,
|
|
1010
|
+
helperId: identity.id,
|
|
1011
|
+
runId: child.runId,
|
|
1012
|
+
status: "failed",
|
|
1013
|
+
error: "The helper has not finished.",
|
|
1014
|
+
});
|
|
1015
|
+
}
|
|
1016
|
+
const settled = await context.join(handles.map(({ child }) => child));
|
|
1017
|
+
for (const [index, outcome] of settled.entries()) {
|
|
1018
|
+
const slot = handles[index]?.index;
|
|
1019
|
+
if (slot === undefined) throw new Error("Missing helper result position.");
|
|
1020
|
+
const previous = results[slot];
|
|
1021
|
+
if (!previous || previous.status === "refused")
|
|
1022
|
+
throw new Error("Missing helper result.");
|
|
1023
|
+
if (outcome.status === "completed") {
|
|
1024
|
+
// Each template's runtime has already checked its own output contract.
|
|
1025
|
+
if (outcome.snapshot.state.status !== "completed")
|
|
1026
|
+
throw new Error("Invalid helper outcome.");
|
|
1027
|
+
results[slot] = {
|
|
1028
|
+
name: previous.name,
|
|
1029
|
+
helperId: previous.helperId,
|
|
1030
|
+
runId: outcome.runId,
|
|
1031
|
+
status: "completed",
|
|
1032
|
+
output: outcome.snapshot.state.candidate,
|
|
1033
|
+
};
|
|
1034
|
+
} else {
|
|
1035
|
+
const state = outcome.snapshot.state;
|
|
1036
|
+
if (!isLocalStop(state)) {
|
|
1037
|
+
if (state.status === "running" || state.status === "completed")
|
|
1038
|
+
throw new Error("Invalid helper outcome.");
|
|
1039
|
+
throw new Halt(state);
|
|
1040
|
+
}
|
|
1041
|
+
results[slot] = {
|
|
1042
|
+
name: previous.name,
|
|
1043
|
+
helperId: previous.helperId,
|
|
1044
|
+
runId: outcome.runId,
|
|
1045
|
+
status: "failed",
|
|
1046
|
+
error:
|
|
1047
|
+
"The helper could not finish within its limits or returned a model or result failure. Continue with the other results.",
|
|
1048
|
+
};
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
const content = summarize ? summarize(immutableCopy(results)) : JSON.stringify(results);
|
|
1052
|
+
if (typeof content !== "string") throw new TypeError("A helper summary must be text.");
|
|
1053
|
+
return results.some((result) => result.status === "completed")
|
|
1054
|
+
? { ok: true, content, output: copyData(results) }
|
|
1055
|
+
: {
|
|
1056
|
+
ok: false,
|
|
1057
|
+
kind: results.every((result) => result.status === "refused") ? "denied" : "failed",
|
|
1058
|
+
content,
|
|
1059
|
+
};
|
|
1060
|
+
},
|
|
1061
|
+
});
|
|
1062
|
+
},
|
|
1063
|
+
});
|
|
1064
|
+
return descriptor;
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
/** @internal Bind per holder; a reusable self descriptor must not capture another agent. */
|
|
1068
|
+
export function bindSubagentTool(tool: Delegation, holder: () => Agent<unknown>): Delegation {
|
|
1069
|
+
return isSubagentTool(tool) ? tool.bind(holder) : tool;
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
/** @internal Called before any host resume callback, including for completed children. */
|
|
1073
|
+
export function checkSubagentChildren(
|
|
1074
|
+
descriptor: Delegation,
|
|
1075
|
+
parent: RunSnapshot,
|
|
1076
|
+
journal: DelegationExecution,
|
|
1077
|
+
): void {
|
|
1078
|
+
if (MARK in descriptor && "check" in descriptor && typeof descriptor.check === "function")
|
|
1079
|
+
descriptor.check(parent, journal);
|
|
1080
|
+
else if (
|
|
1081
|
+
journal.children.some((child) => child.snapshot.kind === "agent" && child.snapshot.subagent)
|
|
1082
|
+
)
|
|
1083
|
+
throw new TypeError("A model-created helper must belong to its registered creation tool.");
|
|
1084
|
+
}
|