@wraith-ai/core 0.1.0 → 0.1.1
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/README.md +1 -1
- package/dist/{attempt-BeB7EltG.d.mts → attempt-HgararU3.d.mts} +2 -1
- package/dist/attempt-HgararU3.d.mts.map +1 -0
- package/dist/{capabilities-BPb5HSH6.d.mts → capabilities-CNsPrkB7.d.mts} +2 -1
- package/dist/capabilities-CNsPrkB7.d.mts.map +1 -0
- package/dist/index.d.mts +6 -5
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +11 -9
- package/dist/index.mjs.map +1 -0
- package/dist/{methods-CZp6XGn8.mjs → methods-7Ryz6zbd.mjs} +4 -2
- package/dist/methods-7Ryz6zbd.mjs.map +1 -0
- package/dist/{model-B6tJ9kX_.mjs → model-C16NUwXW.mjs} +2 -0
- package/dist/model-C16NUwXW.mjs.map +1 -0
- package/dist/{model-D6LQSveS.d.mts → model-_wqePNTL.d.mts} +4 -3
- package/dist/model-_wqePNTL.d.mts.map +1 -0
- package/dist/{models-dev-Y0ZikMBQ.d.mts → models-dev-DNgymZy3.d.mts} +3 -2
- package/dist/models-dev-DNgymZy3.d.mts.map +1 -0
- package/dist/{openai-codex-BhtZvNpm.mjs → openai-codex-Bz1EFPEi.mjs} +3 -1
- package/dist/openai-codex-Bz1EFPEi.mjs.map +1 -0
- package/dist/{openai-codex-Bk-iG7MZ.mjs → openai-codex-uvjhVoVy.mjs} +6 -4
- package/dist/openai-codex-uvjhVoVy.mjs.map +1 -0
- package/dist/{openai-compatible-hkXv-P74.mjs → openai-compatible-DBppnQ_N.mjs} +4 -2
- package/dist/openai-compatible-DBppnQ_N.mjs.map +1 -0
- package/dist/{openrouter-BflQBug2.mjs → openrouter-D8nTOAQo.mjs} +5 -3
- package/dist/openrouter-D8nTOAQo.mjs.map +1 -0
- package/dist/providers/openai-codex.d.mts +4 -3
- package/dist/providers/openai-codex.d.mts.map +1 -0
- package/dist/providers/openai-codex.mjs +1 -1
- package/dist/providers/openai-compatible.d.mts +3 -2
- package/dist/providers/openai-compatible.d.mts.map +1 -0
- package/dist/providers/openai-compatible.mjs +1 -1
- package/dist/providers/openrouter.d.mts +3 -2
- package/dist/providers/openrouter.d.mts.map +1 -0
- package/dist/providers/openrouter.mjs +1 -1
- package/dist/{shared-8d7RsyPH.mjs → shared-BIJaPhMm.mjs} +3 -1
- package/dist/shared-BIJaPhMm.mjs.map +1 -0
- package/dist/snapshot.d.mts +3 -2
- package/dist/snapshot.d.mts.map +1 -0
- package/dist/snapshot.mjs +4999 -4977
- package/dist/snapshot.mjs.map +1 -0
- package/dist/{turn-effort-DquDDwdE.mjs → turn-effort-C61L4JIt.mjs} +2 -0
- package/dist/turn-effort-C61L4JIt.mjs.map +1 -0
- package/package.json +3 -2
- package/src/agent/agent.ts +90 -0
- package/src/agent/attachments.ts +195 -0
- package/src/agent/classifier.ts +525 -0
- package/src/agent/compact.ts +384 -0
- package/src/agent/conversation.ts +300 -0
- package/src/agent/cost.ts +164 -0
- package/src/agent/inbox.ts +80 -0
- package/src/agent/instructions.ts +62 -0
- package/src/agent/loop.ts +675 -0
- package/src/agent/messages.ts +252 -0
- package/src/agent/on-demand.ts +58 -0
- package/src/agent/prompts.ts +35 -0
- package/src/agent/request-images.ts +94 -0
- package/src/agent/stop.ts +37 -0
- package/src/agent/title.ts +122 -0
- package/src/agent/tool-groups.ts +186 -0
- package/src/agent/tools.ts +106 -0
- package/src/app.ts +67 -0
- package/src/config/credential-file-store.ts +66 -0
- package/src/config/environment.ts +105 -0
- package/src/config/instructions.ts +157 -0
- package/src/config/load.ts +667 -0
- package/src/config/locked-file.ts +85 -0
- package/src/config/paths.ts +368 -0
- package/src/config/schema.ts +363 -0
- package/src/config/subagents.ts +156 -0
- package/src/config/trust.ts +53 -0
- package/src/config/write.ts +241 -0
- package/src/errors.ts +85 -0
- package/src/events/types.ts +258 -0
- package/src/glob.ts +161 -0
- package/src/index.ts +681 -0
- package/src/logger.ts +47 -0
- package/src/paths.ts +143 -0
- package/src/permissions/chain.ts +42 -0
- package/src/permissions/command.ts +233 -0
- package/src/permissions/layered.ts +77 -0
- package/src/permissions/match.ts +80 -0
- package/src/permissions/modes.ts +48 -0
- package/src/permissions/policy.ts +160 -0
- package/src/permissions/types.ts +159 -0
- package/src/providers/cache.ts +107 -0
- package/src/providers/capabilities.ts +77 -0
- package/src/providers/catalog-view.ts +91 -0
- package/src/providers/catalog.ts +65 -0
- package/src/providers/errors.ts +108 -0
- package/src/providers/factories/index.ts +15 -0
- package/src/providers/factories/openai-codex.ts +382 -0
- package/src/providers/factories/openai-compatible.ts +81 -0
- package/src/providers/factories/openrouter.ts +165 -0
- package/src/providers/factories/shared.ts +22 -0
- package/src/providers/model.ts +197 -0
- package/src/providers/models-dev.ts +355 -0
- package/src/providers/oauth/methods.ts +10 -0
- package/src/providers/oauth/openai-codex.ts +228 -0
- package/src/providers/oauth.ts +177 -0
- package/src/providers/openai-codex.ts +7 -0
- package/src/providers/openai-compatible.ts +2 -0
- package/src/providers/openrouter.ts +2 -0
- package/src/providers/registry.ts +464 -0
- package/src/providers/turn-effort.ts +156 -0
- package/src/providers/types.ts +83 -0
- package/src/session/backend.ts +44 -0
- package/src/session/file-store.ts +278 -0
- package/src/session/format.ts +1037 -0
- package/src/session/memory-store.ts +73 -0
- package/src/session/session.ts +153 -0
- package/src/session/store.ts +219 -0
- package/src/sign-in/attempt.ts +166 -0
- package/src/sign-in/loopback.ts +74 -0
- package/src/snapshot/data.json +8936 -0
- package/src/snapshot/index.ts +37 -0
- package/src/tools/bin.ts +364 -0
- package/src/tools/builtin.ts +48 -0
- package/src/tools/change.ts +88 -0
- package/src/tools/define.ts +267 -0
- package/src/tools/describe.ts +96 -0
- package/src/tools/fs/edit-file.ts +129 -0
- package/src/tools/fs/glob.ts +75 -0
- package/src/tools/fs/grep.ts +212 -0
- package/src/tools/fs/line-endings.ts +17 -0
- package/src/tools/fs/list-dir.ts +85 -0
- package/src/tools/fs/read-file.ts +230 -0
- package/src/tools/fs/ripgrep.ts +211 -0
- package/src/tools/fs/write-file.ts +97 -0
- package/src/tools/job.ts +252 -0
- package/src/tools/mcp/auth-store.ts +127 -0
- package/src/tools/mcp/command.ts +151 -0
- package/src/tools/mcp/config.ts +168 -0
- package/src/tools/mcp/servers.ts +463 -0
- package/src/tools/mcp/sign-in.ts +226 -0
- package/src/tools/mcp/stdio.ts +204 -0
- package/src/tools/mcp/tools.ts +173 -0
- package/src/tools/on-demand.ts +184 -0
- package/src/tools/registry.ts +935 -0
- package/src/tools/shell/bash.ts +217 -0
- package/src/tools/shell/find-bash.ts +162 -0
- package/src/tools/source.ts +35 -0
- package/src/tools/spill.ts +127 -0
- package/src/tools/subagents.ts +597 -0
- package/src/tools/tasks.ts +603 -0
- package/src/tools/to-model.ts +33 -0
- package/src/tools/web/address.ts +95 -0
- package/src/tools/web/exa.ts +163 -0
- package/src/tools/web/fetch.ts +373 -0
- package/src/tools/web/html.ts +173 -0
- package/src/tools/web/search.ts +111 -0
- package/src/tools/web/source.ts +51 -0
- package/src/units.ts +18 -0
- package/src/version.ts +23 -0
|
@@ -0,0 +1,597 @@
|
|
|
1
|
+
import { Buffer } from "node:buffer";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { createAgent } from "../agent/agent";
|
|
4
|
+
import { createCompactor, type Compactor } from "../agent/compact";
|
|
5
|
+
import { createConversation, type Conversation, type ConversationEvent } from "../agent/conversation";
|
|
6
|
+
import { createInbox, type InboxQueue } from "../agent/inbox";
|
|
7
|
+
import { hostMessage } from "../agent/messages";
|
|
8
|
+
import { TOOL_POLICY_GUIDANCE, composeSystemPrompt } from "../agent/prompts";
|
|
9
|
+
import { INHERIT_MODEL, reasoningEffortSchema, type ReasoningEffort } from "../config/schema";
|
|
10
|
+
import { AgentError, type SerializedError } from "../errors";
|
|
11
|
+
import type { FinishReason } from "../events/types";
|
|
12
|
+
import { noopLogger, type Logger } from "../logger";
|
|
13
|
+
import { toModel, type Model } from "../providers/model";
|
|
14
|
+
import type { ProviderRegistry } from "../providers/registry";
|
|
15
|
+
import type { AgentLanguageModel } from "../providers/types";
|
|
16
|
+
import { createSession, type Session } from "../session/session";
|
|
17
|
+
import type { SessionStore } from "../session/store";
|
|
18
|
+
import { defineTool, type Delegation, type ToolContext, type ToolTask } from "./define";
|
|
19
|
+
import type { ToolSource } from "./source";
|
|
20
|
+
import { formatBytes, headOf, openSpill } from "./spill";
|
|
21
|
+
import { TASK_STOP_NAME, TASK_WAIT_NAME } from "./tasks";
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Agents an agent starts: two tools, and behind them a conversation per agent
|
|
25
|
+
* with a session of its own.
|
|
26
|
+
*
|
|
27
|
+
* Nothing here blocks. The registry defers every call of these tools, so an
|
|
28
|
+
* agent's report reaches its parent the way any background task's end does:
|
|
29
|
+
* through the parent's inbox. Here, not in `agent/`, because a report too long
|
|
30
|
+
* to return is written to a file.
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
export const SUBAGENT_NAME = "subagent";
|
|
34
|
+
export const SEND_MESSAGE_NAME = "send_message";
|
|
35
|
+
export const SUBAGENTS_SOURCE_ID = "subagents";
|
|
36
|
+
|
|
37
|
+
/** What a session's header says its source is, when an agent's tool started it. */
|
|
38
|
+
export const SUBAGENT_SESSION_SOURCE = "subagent";
|
|
39
|
+
|
|
40
|
+
/** As much of a report as comes back directly; the whole goes to a file. */
|
|
41
|
+
export const REPORT_LIMIT_BYTES = 50 * 1024;
|
|
42
|
+
|
|
43
|
+
const DEFAULT_MAX_WORKING = 4;
|
|
44
|
+
|
|
45
|
+
/** A kind of agent: its role, and how it differs from the agent that starts it. */
|
|
46
|
+
export interface SubagentType {
|
|
47
|
+
/** Read by the model that chooses: what this agent is for, and when to start one. */
|
|
48
|
+
description: string;
|
|
49
|
+
/** The role, where the application's own prompt would be. */
|
|
50
|
+
system: string;
|
|
51
|
+
/** Names it may use, as globs. Absent: every tool its parent has, bar these two. */
|
|
52
|
+
tools?: readonly string[];
|
|
53
|
+
/** A profile or `provider:model`. Absent: the default. Needs `models`. */
|
|
54
|
+
model?: string;
|
|
55
|
+
/** Needs `models`, which is what applies it. */
|
|
56
|
+
reasoning?: ReasoningEffort;
|
|
57
|
+
maxSteps?: number;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface SubagentsOptions {
|
|
61
|
+
agents: Readonly<Record<string, SubagentType>>;
|
|
62
|
+
/**
|
|
63
|
+
* What an agent runs on when neither the call nor its type names a model. A
|
|
64
|
+
* function for a host whose own model changes: asked when an agent starts,
|
|
65
|
+
* so agents follow the switch and those already at work are left alone.
|
|
66
|
+
*/
|
|
67
|
+
model: Model | AgentLanguageModel | (() => Model | AgentLanguageModel);
|
|
68
|
+
/**
|
|
69
|
+
* Resolves a model by name. With it the model may choose a model and an
|
|
70
|
+
* effort per agent, and a type may name its own; without it nobody can.
|
|
71
|
+
*/
|
|
72
|
+
models?: ProviderRegistry;
|
|
73
|
+
/** Where the agents' sessions are kept. Absent: in memory, gone with the process. */
|
|
74
|
+
store?: SessionStore;
|
|
75
|
+
/** The step limit of an agent whose type names none. Absent or undefined: `createAgent`'s. */
|
|
76
|
+
maxSteps?: number | undefined;
|
|
77
|
+
/**
|
|
78
|
+
* Absent: an agent's own model summarises its history when it no longer
|
|
79
|
+
* fits. `{ model }` names a cheaper one, and needs `models`. False: never.
|
|
80
|
+
*/
|
|
81
|
+
compaction?: false | { model: string };
|
|
82
|
+
/** The facts of the workspace, for the agent's prompt: `environmentBlock`, with its model. */
|
|
83
|
+
environment?: (model: Model) => string | Promise<string>;
|
|
84
|
+
/** The instruction files, as the parent agent is given them: `createAgent`'s `instructions`. */
|
|
85
|
+
instructions?: () => string | undefined | Promise<string | undefined>;
|
|
86
|
+
/** How many agents may work at once. */
|
|
87
|
+
maxWorking?: number;
|
|
88
|
+
logger?: Logger;
|
|
89
|
+
now?: () => number;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export interface SubagentSnapshot {
|
|
93
|
+
/** Also its task's id, and its session's. */
|
|
94
|
+
id: string;
|
|
95
|
+
/** The name of its type. */
|
|
96
|
+
agent: string;
|
|
97
|
+
description: string;
|
|
98
|
+
model: string;
|
|
99
|
+
working: boolean;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export interface Subagents {
|
|
103
|
+
/** `subagent` and `send_message`, for the registry whose agent may start others. */
|
|
104
|
+
toolSource(): ToolSource;
|
|
105
|
+
list(): SubagentSnapshot[];
|
|
106
|
+
/** Everything an agent's conversation emits, with whose it is. */
|
|
107
|
+
subscribe(listener: (event: { agentId: string; event: ConversationEvent }) => void): () => void;
|
|
108
|
+
/** Cancels what is running and writes what is left. */
|
|
109
|
+
close(): Promise<void>;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Fixed texts: they open every request as part of the cached prefix. */
|
|
113
|
+
const SPAWN_DESCRIPTION = [
|
|
114
|
+
"Start an agent to work on a task in the background. This returns at once with the agent's id; " +
|
|
115
|
+
"its report arrives later as a message, and you are told when it does.",
|
|
116
|
+
"The agent has not seen this conversation and knows only your prompt. Say what to do, what you " +
|
|
117
|
+
"already know, and what to report back.",
|
|
118
|
+
"Start several in one message when the tasks do not depend on each other, and give them work " +
|
|
119
|
+
"that does not overlap: two agents editing the same files undo each other.",
|
|
120
|
+
`Keep working meanwhile, or call ${TASK_WAIT_NAME} when nothing else is left to do. Continue an ` +
|
|
121
|
+
`agent with ${SEND_MESSAGE_NAME}; stop one with ${TASK_STOP_NAME}, giving the same id.`,
|
|
122
|
+
].join("\n");
|
|
123
|
+
|
|
124
|
+
const SEND_DESCRIPTION =
|
|
125
|
+
"Send a message to an agent you started. One that is working reads it before its next step. " +
|
|
126
|
+
"One that has finished starts again with everything it knew, and reports when it is done. " +
|
|
127
|
+
"Use it to answer an agent's question, add to its task, or ask about its report.";
|
|
128
|
+
|
|
129
|
+
const MODEL_PARAM =
|
|
130
|
+
"Leave this out: the agent then runs on its default, which is usually your own model. Set it " +
|
|
131
|
+
"only when the user asks for a particular model, with the name they gave: a profile, or provider:model.";
|
|
132
|
+
|
|
133
|
+
const REASONING_PARAM =
|
|
134
|
+
"Leave this out. Set it only when the user asks for a particular reasoning effort for this agent.";
|
|
135
|
+
|
|
136
|
+
const SHARED_ROLE = [
|
|
137
|
+
"You were started by another agent to do one task. You have not seen its conversation: the " +
|
|
138
|
+
"task you are given is all you know, so read it closely and do not assume the rest.",
|
|
139
|
+
"Your last message is the only thing that agent receives. Make it the report: what you did or " +
|
|
140
|
+
"found, with file paths and line numbers where they matter, and what you could not do. Do not " +
|
|
141
|
+
"address the user; you are not talking to one.",
|
|
142
|
+
"If the task cannot go on without an answer you do not have, end with the question. The answer " +
|
|
143
|
+
"will be sent to you, and you carry on with everything you know.",
|
|
144
|
+
].join("\n\n");
|
|
145
|
+
|
|
146
|
+
export const builtinSubagents = {
|
|
147
|
+
explore: {
|
|
148
|
+
description:
|
|
149
|
+
"Reads and searches the codebase and reports what it found. It cannot edit files or run " +
|
|
150
|
+
"commands, so it never needs approval. Use it for questions that take many searches, to " +
|
|
151
|
+
"keep their output out of your own context.",
|
|
152
|
+
system: [
|
|
153
|
+
SHARED_ROLE,
|
|
154
|
+
"Your task is to find things out. You can read and search; you cannot change anything or " +
|
|
155
|
+
"run commands. Search widely before you settle on an answer, read the code rather than " +
|
|
156
|
+
"guess from names, and quote the lines that carry the answer.",
|
|
157
|
+
].join("\n\n"),
|
|
158
|
+
tools: ["read_file", "list_dir", "glob", "grep"],
|
|
159
|
+
},
|
|
160
|
+
general: {
|
|
161
|
+
description:
|
|
162
|
+
"Does a multi-step task on its own with every tool you have: research, edits, commands. " +
|
|
163
|
+
"Use it for work that can go on while you do something else, and several at once for " +
|
|
164
|
+
"tasks that do not overlap.",
|
|
165
|
+
system: [
|
|
166
|
+
SHARED_ROLE,
|
|
167
|
+
"Do the task with the tools you have. Other agents may be working in this workspace at the " +
|
|
168
|
+
"same time, so change only what the task needs.",
|
|
169
|
+
].join("\n\n"),
|
|
170
|
+
},
|
|
171
|
+
} satisfies Record<string, SubagentType>;
|
|
172
|
+
|
|
173
|
+
interface SpawnInput {
|
|
174
|
+
agent: string;
|
|
175
|
+
description: string;
|
|
176
|
+
prompt: string;
|
|
177
|
+
model?: string;
|
|
178
|
+
reasoning?: ReasoningEffort;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
interface SendInput {
|
|
182
|
+
agent_id: string;
|
|
183
|
+
message: string;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** One agent, for as long as this process knows it. */
|
|
187
|
+
interface Child {
|
|
188
|
+
id: string;
|
|
189
|
+
type: string;
|
|
190
|
+
description: string;
|
|
191
|
+
model: Model;
|
|
192
|
+
maxSteps: number;
|
|
193
|
+
conversation: Conversation;
|
|
194
|
+
inbox: InboxQueue;
|
|
195
|
+
delegation: Delegation;
|
|
196
|
+
/** The run that asked for the round in flight. */
|
|
197
|
+
askedBy: string | undefined;
|
|
198
|
+
/** The task of the round in flight, which is told what the round costs. */
|
|
199
|
+
task: ToolTask | undefined;
|
|
200
|
+
working: boolean;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** How one turn of an agent ended. */
|
|
204
|
+
interface Ended {
|
|
205
|
+
text: string;
|
|
206
|
+
reason: FinishReason;
|
|
207
|
+
error?: SerializedError;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export function createSubagents(options: SubagentsOptions): Subagents {
|
|
211
|
+
const logger = options.logger ?? noopLogger;
|
|
212
|
+
const now = options.now ?? Date.now;
|
|
213
|
+
const fallback = (): Model =>
|
|
214
|
+
toModel(typeof options.model === "function" ? options.model() : options.model);
|
|
215
|
+
const { models, store } = options;
|
|
216
|
+
const maxWorking = options.maxWorking ?? DEFAULT_MAX_WORKING;
|
|
217
|
+
const names = Object.keys(options.agents).sort();
|
|
218
|
+
|
|
219
|
+
if (names.length === 0) {
|
|
220
|
+
throw new AgentError("config/invalid", "Sub-agents need at least one kind of agent to start.");
|
|
221
|
+
}
|
|
222
|
+
// Said when the host assembles, not when the model first asks for that agent.
|
|
223
|
+
if (models === undefined) {
|
|
224
|
+
const needy = names.find((name) => {
|
|
225
|
+
const type = options.agents[name];
|
|
226
|
+
return type?.model !== undefined || type?.reasoning !== undefined;
|
|
227
|
+
});
|
|
228
|
+
if (needy !== undefined) {
|
|
229
|
+
throw new AgentError(
|
|
230
|
+
"config/invalid",
|
|
231
|
+
`The agent "${needy}" names a model or a reasoning effort, which takes a provider registry (\`models\`) to apply.`,
|
|
232
|
+
{ details: { agent: needy } },
|
|
233
|
+
);
|
|
234
|
+
}
|
|
235
|
+
if (typeof options.compaction === "object" && options.compaction.model !== INHERIT_MODEL) {
|
|
236
|
+
throw new AgentError(
|
|
237
|
+
"config/invalid",
|
|
238
|
+
"A model to summarise the agents' histories takes a provider registry (`models`) to resolve.",
|
|
239
|
+
);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const children = new Map<string, Child>();
|
|
244
|
+
const listeners = new Set<(event: { agentId: string; event: ConversationEvent }) => void>();
|
|
245
|
+
|
|
246
|
+
const unknownAgent = (id: string): AgentError =>
|
|
247
|
+
new AgentError("tool/unknown-task", `No agent ${id} was started in this session.`, {
|
|
248
|
+
details: { taskId: id },
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
const ensureRoom = (): void => {
|
|
252
|
+
const working = [...children.values()].filter((child) => child.working).length;
|
|
253
|
+
if (working < maxWorking) return;
|
|
254
|
+
throw new AgentError(
|
|
255
|
+
"tool/failed",
|
|
256
|
+
`${String(working)} agents are already working, which is the limit. Wait for one with ${TASK_WAIT_NAME}, or stop one with ${TASK_STOP_NAME}.`,
|
|
257
|
+
);
|
|
258
|
+
};
|
|
259
|
+
|
|
260
|
+
const modelFor = async (type: SubagentType, asked: Pick<SpawnInput, "model" | "reasoning">): Promise<Model> => {
|
|
261
|
+
const ref = asked.model ?? type.model;
|
|
262
|
+
const reasoning = asked.reasoning ?? type.reasoning;
|
|
263
|
+
if (models === undefined || (ref === undefined && reasoning === undefined)) return fallback();
|
|
264
|
+
|
|
265
|
+
const named = ref ?? fallback().ref;
|
|
266
|
+
if (named === undefined) {
|
|
267
|
+
throw new AgentError(
|
|
268
|
+
"tool/failed",
|
|
269
|
+
"The default model has no name to resolve it by, so its reasoning effort cannot be changed. Name a model as well.",
|
|
270
|
+
);
|
|
271
|
+
}
|
|
272
|
+
return models.resolve(named, reasoning === undefined ? {} : { reasoning });
|
|
273
|
+
};
|
|
274
|
+
|
|
275
|
+
const compactorFor = async (model: Model): Promise<Compactor | undefined> => {
|
|
276
|
+
if (options.compaction === false) return undefined;
|
|
277
|
+
// No window size means no compactor: one that cannot know when to fire does nothing.
|
|
278
|
+
if (model.contextLimit === undefined) {
|
|
279
|
+
logger.warn("sub-agent runs without compaction: its model's window is unknown", {
|
|
280
|
+
model: model.modelId,
|
|
281
|
+
});
|
|
282
|
+
return undefined;
|
|
283
|
+
}
|
|
284
|
+
const named = options.compaction?.model;
|
|
285
|
+
const summariser =
|
|
286
|
+
named === undefined || named === INHERIT_MODEL || models === undefined ? model : await models.resolve(named);
|
|
287
|
+
// The summarising model, and the window of the model that runs.
|
|
288
|
+
return createCompactor({ model: summariser, contextLimit: model.contextLimit });
|
|
289
|
+
};
|
|
290
|
+
|
|
291
|
+
/** Builds an agent around a session: a new one, or one read back from the store. */
|
|
292
|
+
const assemble = async (
|
|
293
|
+
spec: { id: string; type: string; description: string; model: Model; session?: Session },
|
|
294
|
+
context: ToolContext,
|
|
295
|
+
): Promise<Child> => {
|
|
296
|
+
const type = options.agents[spec.type] as SubagentType;
|
|
297
|
+
if (context.delegate === undefined) {
|
|
298
|
+
throw new AgentError(
|
|
299
|
+
"config/invalid",
|
|
300
|
+
"The tools that list sub-agents cannot be handed on, so an agent would have none.",
|
|
301
|
+
);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
const inbox = createInbox();
|
|
305
|
+
const delegation = context.delegate({
|
|
306
|
+
...(type.tools === undefined ? {} : { allow: type.tools }),
|
|
307
|
+
// One level: an agent started by an agent starts none.
|
|
308
|
+
deny: [SUBAGENT_NAME, SEND_MESSAGE_NAME],
|
|
309
|
+
tasks: { id: spec.id, inbox },
|
|
310
|
+
});
|
|
311
|
+
|
|
312
|
+
const compactor = await compactorFor(spec.model);
|
|
313
|
+
const maxSteps = type.maxSteps ?? options.maxSteps;
|
|
314
|
+
const agent = createAgent({
|
|
315
|
+
model: spec.model,
|
|
316
|
+
system: composeSystemPrompt(type.system, await options.environment?.(spec.model), TOOL_POLICY_GUIDANCE),
|
|
317
|
+
instructions: await options.instructions?.(),
|
|
318
|
+
tools: delegation.tools,
|
|
319
|
+
...(maxSteps === undefined ? {} : { maxSteps }),
|
|
320
|
+
...(compactor === undefined ? {} : { compactor }),
|
|
321
|
+
logger,
|
|
322
|
+
now,
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
const meta = {
|
|
326
|
+
source: SUBAGENT_SESSION_SOURCE,
|
|
327
|
+
parent: context.sessionId,
|
|
328
|
+
parentRunId: context.runId,
|
|
329
|
+
agent: spec.type,
|
|
330
|
+
description: spec.description,
|
|
331
|
+
};
|
|
332
|
+
const session =
|
|
333
|
+
spec.session ??
|
|
334
|
+
(store === undefined
|
|
335
|
+
? createSession(spec.id, { meta }, now())
|
|
336
|
+
: await store.create({ id: spec.id, meta }));
|
|
337
|
+
|
|
338
|
+
const child: Child = {
|
|
339
|
+
id: spec.id,
|
|
340
|
+
type: spec.type,
|
|
341
|
+
description: spec.description,
|
|
342
|
+
model: spec.model,
|
|
343
|
+
maxSteps: agent.maxSteps,
|
|
344
|
+
inbox,
|
|
345
|
+
delegation,
|
|
346
|
+
askedBy: context.runId,
|
|
347
|
+
task: undefined,
|
|
348
|
+
working: false,
|
|
349
|
+
conversation: createConversation({
|
|
350
|
+
agent,
|
|
351
|
+
session,
|
|
352
|
+
...(store === undefined ? {} : { store }),
|
|
353
|
+
inbox,
|
|
354
|
+
// Its rounds start when its parent says so, never because one of its own tasks ended.
|
|
355
|
+
wake: false,
|
|
356
|
+
parentRunId: () => child.askedBy,
|
|
357
|
+
}),
|
|
358
|
+
};
|
|
359
|
+
child.conversation.subscribe((event) => {
|
|
360
|
+
// Every token the agent is billed for goes through a `usage` record: its steps,
|
|
361
|
+
// its compactions, its classifier. The round's task carries them to the parent's bill.
|
|
362
|
+
if (event.type === "record" && event.record.type === "usage") child.task?.spend(event.record.usage);
|
|
363
|
+
for (const listener of listeners) listener({ agentId: child.id, event });
|
|
364
|
+
});
|
|
365
|
+
children.set(child.id, child);
|
|
366
|
+
return child;
|
|
367
|
+
};
|
|
368
|
+
|
|
369
|
+
/** An agent this process did not start: its session is on disk, from an earlier one. */
|
|
370
|
+
const revive = async (id: string, context: ToolContext): Promise<Child> => {
|
|
371
|
+
if (store === undefined || !/^[A-Za-z0-9_-]+$/.test(id)) throw unknownAgent(id);
|
|
372
|
+
const session = await store.get(id);
|
|
373
|
+
// Only its own: a session id from elsewhere must not become an agent here.
|
|
374
|
+
if (
|
|
375
|
+
session === null ||
|
|
376
|
+
session.meta.source !== SUBAGENT_SESSION_SOURCE ||
|
|
377
|
+
session.meta.parent !== context.sessionId
|
|
378
|
+
) {
|
|
379
|
+
throw unknownAgent(id);
|
|
380
|
+
}
|
|
381
|
+
const type = typeof session.meta.agent === "string" ? session.meta.agent : "";
|
|
382
|
+
if (options.agents[type] === undefined) {
|
|
383
|
+
throw new AgentError(
|
|
384
|
+
"tool/failed",
|
|
385
|
+
`Agent ${id} was a "${type}", a kind of agent this session no longer has.`,
|
|
386
|
+
{ details: { taskId: id } },
|
|
387
|
+
);
|
|
388
|
+
}
|
|
389
|
+
// The model it last ran on, when that can be named again.
|
|
390
|
+
const profile = session.meta.profile;
|
|
391
|
+
const model =
|
|
392
|
+
models !== undefined && typeof profile === "string" ? await models.resolve(profile) : fallback();
|
|
393
|
+
const description = typeof session.meta.description === "string" ? session.meta.description : type;
|
|
394
|
+
return assemble({ id, type, description, model, session }, context);
|
|
395
|
+
};
|
|
396
|
+
|
|
397
|
+
/** One turn, from the wake to its end. */
|
|
398
|
+
const turn = (child: Child): Promise<Ended> =>
|
|
399
|
+
new Promise((resolve) => {
|
|
400
|
+
let text = "";
|
|
401
|
+
let error: SerializedError | undefined;
|
|
402
|
+
const off = child.conversation.subscribe((event) => {
|
|
403
|
+
if (event.type === "run-finish") text = event.text;
|
|
404
|
+
else if (event.type === "error") error = event.error;
|
|
405
|
+
else if (event.type === "turn-end") {
|
|
406
|
+
off();
|
|
407
|
+
resolve({ text, reason: event.result.reason, ...(error === undefined ? {} : { error }) });
|
|
408
|
+
} else if (event.type === "turn-error") {
|
|
409
|
+
off();
|
|
410
|
+
resolve({ text, reason: "error", error: event.error });
|
|
411
|
+
}
|
|
412
|
+
});
|
|
413
|
+
child.conversation.wake();
|
|
414
|
+
});
|
|
415
|
+
|
|
416
|
+
/** What the parent reads: the answer, then whatever it should know about how it ended. */
|
|
417
|
+
const reportOf = (child: Child, ended: Ended, context: ToolContext): string => {
|
|
418
|
+
if (ended.reason === "aborted") {
|
|
419
|
+
throw new AgentError("run/aborted", `Agent ${child.id} was stopped.`, {
|
|
420
|
+
details: { taskId: child.id },
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
if (ended.reason === "error") {
|
|
424
|
+
throw new AgentError("tool/failed", `Agent ${child.id} failed: ${ended.error?.message ?? "unknown error"}`, {
|
|
425
|
+
details: { taskId: child.id, ...(ended.error === undefined ? {} : { code: ended.error.code }) },
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
const said = ended.text.trim() === "" ? "(The agent ended without a written answer.)" : ended.text;
|
|
430
|
+
const notes: string[] = [];
|
|
431
|
+
let body = said;
|
|
432
|
+
|
|
433
|
+
const bytes = Buffer.byteLength(said, "utf8");
|
|
434
|
+
if (bytes > REPORT_LIMIT_BYTES) {
|
|
435
|
+
// The start comes back, not the end: a report opens with its conclusion.
|
|
436
|
+
const spill = openSpill(context, SUBAGENT_NAME, { extension: "md" });
|
|
437
|
+
spill?.write(said);
|
|
438
|
+
const saved = spill?.close();
|
|
439
|
+
body = headOf(said, REPORT_LIMIT_BYTES).head;
|
|
440
|
+
notes.push(
|
|
441
|
+
saved === undefined
|
|
442
|
+
? `Only the first ${formatBytes(REPORT_LIMIT_BYTES)} of the report (${formatBytes(bytes)}) are above; the rest was not kept. Ask the agent for the part you need with ${SEND_MESSAGE_NAME}.`
|
|
443
|
+
: `Only the first ${formatBytes(REPORT_LIMIT_BYTES)} of the report are above. All of it (${formatBytes(bytes)}) is saved at ${saved.path}; read on with read_file.`,
|
|
444
|
+
);
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
if (ended.reason === "max-steps") {
|
|
448
|
+
notes.push(
|
|
449
|
+
`The agent stopped at its limit of ${String(child.maxSteps)} steps, so the task may be unfinished. Tell it to carry on with ${SEND_MESSAGE_NAME}.`,
|
|
450
|
+
);
|
|
451
|
+
} else if (ended.reason !== "stop") {
|
|
452
|
+
notes.push(`The agent's last answer ended early (${ended.reason}).`);
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
const running = child.delegation.tasks?.list().filter((task) => task.status === "running") ?? [];
|
|
456
|
+
if (running.length > 0) {
|
|
457
|
+
notes.push(
|
|
458
|
+
`It left running in the background: ${running.map((task) => `${task.id} ${task.label}`).join("; ")}. ` +
|
|
459
|
+
`They stay up for its next round; stop one with ${TASK_STOP_NAME}.`,
|
|
460
|
+
);
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
return [body, ...notes].join("\n\n");
|
|
464
|
+
};
|
|
465
|
+
|
|
466
|
+
/** One round of work: what was sent, every turn it takes, and the report. */
|
|
467
|
+
const round = async (child: Child, text: string, context: ToolContext): Promise<string> => {
|
|
468
|
+
if (context.signal.aborted) {
|
|
469
|
+
throw new AgentError("run/aborted", `Agent ${child.id} was stopped before it started.`, {
|
|
470
|
+
details: { taskId: child.id },
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
child.working = true;
|
|
474
|
+
child.askedBy = context.runId;
|
|
475
|
+
child.task = context.task;
|
|
476
|
+
const onAbort = (): void => {
|
|
477
|
+
child.conversation.abort();
|
|
478
|
+
};
|
|
479
|
+
context.signal.addEventListener("abort", onAbort, { once: true });
|
|
480
|
+
try {
|
|
481
|
+
// The other agent's words, stamped so the approval classifier does not read them as the user's.
|
|
482
|
+
child.inbox.push({ type: "message", message: hostMessage(text) }, { wake: true });
|
|
483
|
+
let ended: Ended;
|
|
484
|
+
do {
|
|
485
|
+
ended = await turn(child);
|
|
486
|
+
// A message that arrived after the turn's last request starts another.
|
|
487
|
+
} while (child.inbox.wakes() && !context.signal.aborted && ended.reason !== "error");
|
|
488
|
+
return reportOf(child, ended, context);
|
|
489
|
+
} finally {
|
|
490
|
+
context.signal.removeEventListener("abort", onAbort);
|
|
491
|
+
child.working = false;
|
|
492
|
+
child.task = undefined;
|
|
493
|
+
}
|
|
494
|
+
};
|
|
495
|
+
|
|
496
|
+
const spawnSchema = z.object({
|
|
497
|
+
agent: z.enum(names as [string, ...string[]]).describe("The kind of agent to start."),
|
|
498
|
+
description: z.string().min(1).describe("Three to five words naming the task, shown to the user."),
|
|
499
|
+
prompt: z.string().min(1).describe("The whole task. The agent knows nothing else."),
|
|
500
|
+
});
|
|
501
|
+
|
|
502
|
+
const spawn = defineTool<SpawnInput, string>({
|
|
503
|
+
name: SUBAGENT_NAME,
|
|
504
|
+
description: [
|
|
505
|
+
SPAWN_DESCRIPTION,
|
|
506
|
+
"",
|
|
507
|
+
"Agents:",
|
|
508
|
+
...names.map((name) => `- ${name}: ${(options.agents[name] as SubagentType).description}`),
|
|
509
|
+
].join("\n"),
|
|
510
|
+
danger: "safe",
|
|
511
|
+
// The parameters exist only where something can apply them.
|
|
512
|
+
inputSchema: (models === undefined
|
|
513
|
+
? spawnSchema
|
|
514
|
+
: spawnSchema.extend({
|
|
515
|
+
model: z.string().min(1).optional().describe(MODEL_PARAM),
|
|
516
|
+
reasoning: reasoningEffortSchema.optional().describe(REASONING_PARAM),
|
|
517
|
+
})) as z.ZodType<SpawnInput>,
|
|
518
|
+
describe: (input) => `${input.agent}: ${input.description}`,
|
|
519
|
+
background: { always: true },
|
|
520
|
+
execute: async (input, context) => {
|
|
521
|
+
if (context.task === undefined) {
|
|
522
|
+
throw new AgentError("config/invalid", `${SUBAGENT_NAME} ran outside a task, so it has no id to give its agent.`);
|
|
523
|
+
}
|
|
524
|
+
ensureRoom();
|
|
525
|
+
const type = options.agents[input.agent] as SubagentType;
|
|
526
|
+
const model = await modelFor(type, input);
|
|
527
|
+
const child = await assemble(
|
|
528
|
+
{ id: context.task.id, type: input.agent, description: input.description, model },
|
|
529
|
+
context,
|
|
530
|
+
);
|
|
531
|
+
return round(
|
|
532
|
+
child,
|
|
533
|
+
`[Task from the agent that started you. It is that agent's request, not a message from the user.]\n${input.prompt}`,
|
|
534
|
+
context,
|
|
535
|
+
);
|
|
536
|
+
},
|
|
537
|
+
describeResult: firstLine,
|
|
538
|
+
});
|
|
539
|
+
|
|
540
|
+
const send = defineTool<SendInput, string>({
|
|
541
|
+
name: SEND_MESSAGE_NAME,
|
|
542
|
+
description: SEND_DESCRIPTION,
|
|
543
|
+
danger: "safe",
|
|
544
|
+
inputSchema: z.object({
|
|
545
|
+
agent_id: z.string().min(1).describe(`The id ${SUBAGENT_NAME} returned for the agent.`),
|
|
546
|
+
message: z.string().min(1),
|
|
547
|
+
}),
|
|
548
|
+
describe: (input) => input.agent_id,
|
|
549
|
+
background: {
|
|
550
|
+
always: true,
|
|
551
|
+
// A new round runs under the agent's id; a word to a working agent is no task of its own.
|
|
552
|
+
taskId: (input) => (children.get(input.agent_id)?.working === true ? undefined : input.agent_id),
|
|
553
|
+
},
|
|
554
|
+
execute: async (input, context) => {
|
|
555
|
+
const text = `[Message from the agent that started you, not from the user.]\n${input.message}`;
|
|
556
|
+
const known = children.get(input.agent_id);
|
|
557
|
+
if (known?.working === true) {
|
|
558
|
+
known.inbox.push({ type: "message", message: hostMessage(text) }, { wake: true });
|
|
559
|
+
return `Delivered. Agent ${known.id} is still working and reads it before its next step; its report arrives as before.`;
|
|
560
|
+
}
|
|
561
|
+
ensureRoom();
|
|
562
|
+
const child = known ?? (await revive(input.agent_id, context));
|
|
563
|
+
return round(child, text, context);
|
|
564
|
+
},
|
|
565
|
+
describeResult: firstLine,
|
|
566
|
+
});
|
|
567
|
+
|
|
568
|
+
return {
|
|
569
|
+
toolSource: () => ({ id: SUBAGENTS_SOURCE_ID, list: async () => [spawn, send] }),
|
|
570
|
+
|
|
571
|
+
list: () =>
|
|
572
|
+
[...children.values()].map((child) => ({
|
|
573
|
+
id: child.id,
|
|
574
|
+
agent: child.type,
|
|
575
|
+
description: child.description,
|
|
576
|
+
model: child.model.modelId,
|
|
577
|
+
working: child.working,
|
|
578
|
+
})),
|
|
579
|
+
|
|
580
|
+
subscribe(listener) {
|
|
581
|
+
listeners.add(listener);
|
|
582
|
+
return () => {
|
|
583
|
+
listeners.delete(listener);
|
|
584
|
+
};
|
|
585
|
+
},
|
|
586
|
+
|
|
587
|
+
async close() {
|
|
588
|
+
await Promise.all([...children.values()].map((child) => child.conversation.close()));
|
|
589
|
+
},
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
/** A report in one line, for a screen. */
|
|
594
|
+
function firstLine(output: string): string {
|
|
595
|
+
const line = output.split("\n").find((candidate) => candidate.trim() !== "") ?? "";
|
|
596
|
+
return line.length > 80 ? `${line.slice(0, 79)}…` : line;
|
|
597
|
+
}
|