@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,935 @@
|
|
|
1
|
+
import type { Attachment } from "../agent/attachments";
|
|
2
|
+
import type {
|
|
3
|
+
Preflight,
|
|
4
|
+
ToolCall,
|
|
5
|
+
ToolOutcome,
|
|
6
|
+
ToolRunContext,
|
|
7
|
+
ToolRunner,
|
|
8
|
+
} from "../agent/tools";
|
|
9
|
+
import { AgentError, serializeError } from "../errors";
|
|
10
|
+
import type { AgentEventPayload, Usage } from "../events/types";
|
|
11
|
+
import { noopLogger, type Logger } from "../logger";
|
|
12
|
+
import { extraRootOf, isInsideWorkspace, type ExtraRoot } from "../paths";
|
|
13
|
+
import { matchPattern } from "../permissions/match";
|
|
14
|
+
import {
|
|
15
|
+
resolveApproval,
|
|
16
|
+
type ApprovalHandler,
|
|
17
|
+
type ApprovalOutcome,
|
|
18
|
+
type PermissionPolicy,
|
|
19
|
+
type PermissionVerdict,
|
|
20
|
+
} from "../permissions/types";
|
|
21
|
+
import { z } from "zod";
|
|
22
|
+
import { compactChange, type FileChange, type FileEdit } from "./change";
|
|
23
|
+
import type {
|
|
24
|
+
AgentTool,
|
|
25
|
+
DelegateOptions,
|
|
26
|
+
Delegation,
|
|
27
|
+
ResourceClaim,
|
|
28
|
+
ToolContext,
|
|
29
|
+
ToolTask,
|
|
30
|
+
} from "./define";
|
|
31
|
+
import { BACKGROUND_FLAG, callLine, describeCall } from "./describe";
|
|
32
|
+
import {
|
|
33
|
+
CALL_TOOL_NAME,
|
|
34
|
+
SEARCH_TOOLS_NAME,
|
|
35
|
+
callToolTool,
|
|
36
|
+
searchToolsTool,
|
|
37
|
+
type CallToolInput,
|
|
38
|
+
type OnDemandCatalog,
|
|
39
|
+
} from "./on-demand";
|
|
40
|
+
import { exposedName, type ToolSource } from "./source";
|
|
41
|
+
import {
|
|
42
|
+
TASKS_SOURCE_ID,
|
|
43
|
+
TASK_STOP_NAME,
|
|
44
|
+
TASK_WAIT_NAME,
|
|
45
|
+
taskStopTool,
|
|
46
|
+
taskWaitTool,
|
|
47
|
+
type OpenTask,
|
|
48
|
+
type TaskRegistry,
|
|
49
|
+
} from "./tasks";
|
|
50
|
+
import { toModelTools } from "./to-model";
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The registry fills in the loop's `ToolRunner` port: it merges sources,
|
|
54
|
+
* applies allow/deny, asks the policy, asks the human when the policy says to,
|
|
55
|
+
* and runs the tool under a timeout.
|
|
56
|
+
*
|
|
57
|
+
* A refusal is a tool result, not an exception: the model is told what happened
|
|
58
|
+
* and the run survives. An exception escapes only for something the model
|
|
59
|
+
* cannot answer.
|
|
60
|
+
*/
|
|
61
|
+
|
|
62
|
+
export interface ToolRegistryEntry {
|
|
63
|
+
/** Name as the model sees it — prefixed for non-builtin sources. */
|
|
64
|
+
name: string;
|
|
65
|
+
sourceId: string;
|
|
66
|
+
tool: AgentTool;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface ToolRegistryOptions {
|
|
70
|
+
sources: readonly ToolSource[];
|
|
71
|
+
/** Workspace root. Tools cannot touch anything outside it, except `roots`. */
|
|
72
|
+
cwd: string;
|
|
73
|
+
/**
|
|
74
|
+
* Directories outside the workspace the file tools may use. The policy must
|
|
75
|
+
* get the same list: a policy that lacks it refuses those paths.
|
|
76
|
+
*/
|
|
77
|
+
roots?: readonly ExtraRoot[];
|
|
78
|
+
/**
|
|
79
|
+
* Where a tool keeps a result too big to return. Must sit inside the
|
|
80
|
+
* workspace or a root, or a saved result could not be read back.
|
|
81
|
+
*/
|
|
82
|
+
resultsDir?: string;
|
|
83
|
+
policy: PermissionPolicy;
|
|
84
|
+
/** Missing handler means an "ask" verdict resolves to a refusal. */
|
|
85
|
+
approval?: ApprovalHandler;
|
|
86
|
+
/**
|
|
87
|
+
* Lets calls outlive their turn. With it, a tool that allows deferring gets a
|
|
88
|
+
* `run_in_background` parameter and `task_stop` joins the tools. Without it
|
|
89
|
+
* nothing changes.
|
|
90
|
+
*/
|
|
91
|
+
tasks?: TaskRegistry;
|
|
92
|
+
logger?: Logger;
|
|
93
|
+
/** Name globs; deny wins, and an allow list makes everything else invisible. */
|
|
94
|
+
allow?: readonly string[];
|
|
95
|
+
deny?: readonly string[];
|
|
96
|
+
newId?: (prefix: string) => string;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export interface ToolRegistry extends ToolRunner {
|
|
100
|
+
/** The tools on the model's list. */
|
|
101
|
+
readonly entries: readonly ToolRegistryEntry[];
|
|
102
|
+
/** The tools reached through `call_tool`, as last listed. Empty without an on-demand source. */
|
|
103
|
+
onDemandEntries(): readonly ToolRegistryEntry[];
|
|
104
|
+
/** Always present here, unlike on the port it fills in. */
|
|
105
|
+
preflight(call: ToolCall): Preflight;
|
|
106
|
+
close(): Promise<void>;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The source id the registry gives `search_tools` and `call_tool`. */
|
|
110
|
+
export const ON_DEMAND_SOURCE_ID = "on-demand";
|
|
111
|
+
|
|
112
|
+
/** What a call is, before anybody is asked or anything runs. */
|
|
113
|
+
type Assessment =
|
|
114
|
+
| { kind: "not-found"; name: string; viaCallTool: boolean }
|
|
115
|
+
| { kind: "invalid"; entry: ToolRegistryEntry; error: unknown }
|
|
116
|
+
| {
|
|
117
|
+
kind: "ready";
|
|
118
|
+
/** The tool that runs: for `call_tool`, the one it names. */
|
|
119
|
+
entry: ToolRegistryEntry;
|
|
120
|
+
/** The tool's own input: what the model sent, without the background flag. */
|
|
121
|
+
input: unknown;
|
|
122
|
+
/** What whoever answers sees: the model's arguments, or `call_tool`'s inner ones. */
|
|
123
|
+
shown: unknown;
|
|
124
|
+
/** The model asked for this call to be deferred. */
|
|
125
|
+
wantsBackground: boolean;
|
|
126
|
+
claim: ResourceClaim;
|
|
127
|
+
verdict: PermissionVerdict;
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
/** Which tool a call reaches, and with what. */
|
|
131
|
+
type Target =
|
|
132
|
+
| { kind: "not-found"; name: string; viaCallTool: boolean }
|
|
133
|
+
| { kind: "invalid"; entry: ToolRegistryEntry; error: unknown }
|
|
134
|
+
| { kind: "found"; entry: ToolRegistryEntry; input: unknown; viaCallTool: boolean };
|
|
135
|
+
|
|
136
|
+
/** Both texts open every request as part of the cached prefix, so they are fixed. */
|
|
137
|
+
const RUN_IN_BACKGROUND =
|
|
138
|
+
"Return at once and be told when it ends. Use it for servers, watchers and anything " +
|
|
139
|
+
"that runs for minutes. Do not use it for quick commands, and never end a command with '&' instead.";
|
|
140
|
+
|
|
141
|
+
const BACKGROUND_NOTE =
|
|
142
|
+
" It can run in the background: set run_in_background and you are told when it ends.";
|
|
143
|
+
|
|
144
|
+
/** What the model is shown for a tool that may be deferred. The tool itself is left as it is. */
|
|
145
|
+
function withBackgroundFlag(tool: AgentTool): AgentTool {
|
|
146
|
+
if (!(tool.inputSchema instanceof z.ZodObject)) {
|
|
147
|
+
throw new AgentError(
|
|
148
|
+
"config/invalid",
|
|
149
|
+
`${tool.name} is marked background, so its input schema has to be an object.`,
|
|
150
|
+
{ details: { toolName: tool.name } },
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
return {
|
|
154
|
+
...tool,
|
|
155
|
+
description: tool.description + BACKGROUND_NOTE,
|
|
156
|
+
inputSchema: tool.inputSchema.extend({
|
|
157
|
+
[BACKGROUND_FLAG]: z.boolean().optional().describe(RUN_IN_BACKGROUND),
|
|
158
|
+
}),
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Splits what the model sent into the tool's own input and the flag. */
|
|
163
|
+
function splitBackground(input: unknown): { input: unknown; background: boolean } {
|
|
164
|
+
if (typeof input !== "object" || input === null || !(BACKGROUND_FLAG in input)) {
|
|
165
|
+
return { input, background: false };
|
|
166
|
+
}
|
|
167
|
+
const { [BACKGROUND_FLAG]: flag, ...rest } = input as Record<string, unknown>;
|
|
168
|
+
return { input: rest, background: flag === true };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Unless the tool says otherwise, only what reads: a write never joins a group, even when allowed. */
|
|
172
|
+
function concurrencySafe(tool: AgentTool): boolean {
|
|
173
|
+
return tool.parallel ?? (tool.danger === "safe" || tool.danger === "read");
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export async function createToolRegistry(options: ToolRegistryOptions): Promise<ToolRegistry> {
|
|
177
|
+
const logger = options.logger ?? noopLogger;
|
|
178
|
+
const newId = options.newId ?? defaultIdGenerator();
|
|
179
|
+
|
|
180
|
+
// Outside both, a saved result could be written and never read back.
|
|
181
|
+
if (
|
|
182
|
+
options.resultsDir !== undefined &&
|
|
183
|
+
!isInsideWorkspace(options.cwd, options.resultsDir) &&
|
|
184
|
+
extraRootOf(options, options.resultsDir) === undefined
|
|
185
|
+
) {
|
|
186
|
+
throw new AgentError(
|
|
187
|
+
"config/invalid",
|
|
188
|
+
`The results directory "${options.resultsDir}" is inside neither the workspace nor a root, so a saved result could not be read back.`,
|
|
189
|
+
{ details: { resultsDir: options.resultsDir } },
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// What the sources list. The tools the registry adds itself are made for each scope.
|
|
194
|
+
const fromSources = new Map<string, ToolRegistryEntry>();
|
|
195
|
+
const onDemandSources = options.sources.filter((source) => source.onDemand === true);
|
|
196
|
+
for (const source of options.sources) {
|
|
197
|
+
if (source.onDemand === true) continue;
|
|
198
|
+
for (const tool of await source.list()) {
|
|
199
|
+
const name = exposedName(source.namespace, tool.name);
|
|
200
|
+
addTool(fromSources, { name, sourceId: source.id, tool }, options, logger);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* The on-demand catalog, listed again before every model call. A source that
|
|
206
|
+
* fails keeps what it last listed: a hiccup must not take tools away mid-turn.
|
|
207
|
+
*/
|
|
208
|
+
let catalog = new Map<string, ToolRegistryEntry>();
|
|
209
|
+
const lastListed = new Map<string, AgentTool[]>();
|
|
210
|
+
const refreshCatalog = async (): Promise<void> => {
|
|
211
|
+
const next = new Map<string, ToolRegistryEntry>();
|
|
212
|
+
for (const source of onDemandSources) {
|
|
213
|
+
let listed: AgentTool[];
|
|
214
|
+
try {
|
|
215
|
+
listed = await source.list();
|
|
216
|
+
lastListed.set(source.id, listed);
|
|
217
|
+
} catch (error) {
|
|
218
|
+
logger.warn("tool source failed to list", { source: source.id, error: String(error) });
|
|
219
|
+
listed = lastListed.get(source.id) ?? [];
|
|
220
|
+
}
|
|
221
|
+
for (const tool of listed) {
|
|
222
|
+
const name = exposedName(source.namespace, tool.name);
|
|
223
|
+
if (!isVisible(name, options)) continue;
|
|
224
|
+
// These come and go, so a clash is skipped rather than thrown.
|
|
225
|
+
if (fromSources.has(name) || OWN_TOOL_NAMES.has(name) || next.has(name)) {
|
|
226
|
+
logger.warn("on-demand tool shadowed by another of the same name", { tool: name });
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
next.set(name, { name, sourceId: source.id, tool });
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
catalog = next;
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
if (onDemandSources.length > 0) await refreshCatalog();
|
|
236
|
+
|
|
237
|
+
// One question at a time: the policy can change between preflight and
|
|
238
|
+
// execute, and the TUI's single card would lose the first of two questions.
|
|
239
|
+
// One queue for every scope, so an agent a tool started waits its turn too.
|
|
240
|
+
let approvals: Promise<void> = Promise.resolve();
|
|
241
|
+
const oneAtATime = <T>(question: () => Promise<T>): Promise<T> => {
|
|
242
|
+
const turn = approvals.then(question);
|
|
243
|
+
approvals = turn.then(
|
|
244
|
+
() => undefined,
|
|
245
|
+
() => undefined,
|
|
246
|
+
);
|
|
247
|
+
return turn;
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
const root = scopedRunner(
|
|
251
|
+
{
|
|
252
|
+
options,
|
|
253
|
+
logger,
|
|
254
|
+
newId,
|
|
255
|
+
listed: fromSources,
|
|
256
|
+
onDemand: onDemandSources.length > 0,
|
|
257
|
+
catalog: () => catalog,
|
|
258
|
+
refreshCatalog,
|
|
259
|
+
oneAtATime,
|
|
260
|
+
},
|
|
261
|
+
{ tasks: options.tasks, sees: () => true, seesTaskTool: () => true },
|
|
262
|
+
);
|
|
263
|
+
|
|
264
|
+
return {
|
|
265
|
+
...root,
|
|
266
|
+
async close(): Promise<void> {
|
|
267
|
+
for (const source of options.sources) await source.close?.();
|
|
268
|
+
},
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** What every scope of one registry shares: its sources, its policy, its one queue of questions. */
|
|
273
|
+
interface Shared {
|
|
274
|
+
options: ToolRegistryOptions;
|
|
275
|
+
logger: Logger;
|
|
276
|
+
newId: (prefix: string) => string;
|
|
277
|
+
listed: ReadonlyMap<string, ToolRegistryEntry>;
|
|
278
|
+
/** Whether any source is on demand, so `search_tools` and `call_tool` exist at all. */
|
|
279
|
+
onDemand: boolean;
|
|
280
|
+
catalog(): ReadonlyMap<string, ToolRegistryEntry>;
|
|
281
|
+
refreshCatalog(): Promise<void>;
|
|
282
|
+
oneAtATime<T>(question: () => Promise<T>): Promise<T>;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** Which of the registry's tools one agent has, and where its deferred calls are kept. */
|
|
286
|
+
interface Scope {
|
|
287
|
+
tasks: TaskRegistry | undefined;
|
|
288
|
+
/** Tools from sources, on demand ones included. */
|
|
289
|
+
sees(name: string): boolean;
|
|
290
|
+
/** `task_stop` and `task_wait`, which follow the tasks rather than an allow list. */
|
|
291
|
+
seesTaskTool(name: string): boolean;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* The registry for one scope: the host's agent, or an agent one of its tools
|
|
296
|
+
* started. Only the names and the tasks differ; the policy and the questions
|
|
297
|
+
* are the registry's.
|
|
298
|
+
*/
|
|
299
|
+
function scopedRunner(shared: Shared, scope: Scope): Omit<ToolRegistry, "close"> {
|
|
300
|
+
const { options, logger, newId, oneAtATime } = shared;
|
|
301
|
+
const { tasks } = scope;
|
|
302
|
+
const catalogEntry = (name: string): ToolRegistryEntry | undefined =>
|
|
303
|
+
scope.sees(name) ? shared.catalog().get(name) : undefined;
|
|
304
|
+
const catalogEntries = (): ToolRegistryEntry[] =>
|
|
305
|
+
[...shared.catalog().values()].filter((entry) => scope.sees(entry.name));
|
|
306
|
+
|
|
307
|
+
const tools = new Map<string, ToolRegistryEntry>();
|
|
308
|
+
for (const [name, entry] of shared.listed) {
|
|
309
|
+
if (scope.sees(name)) tools.set(name, entry);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// A task nobody can stop is worse than no tasks, so the tools come with the registry.
|
|
313
|
+
if (tasks !== undefined) {
|
|
314
|
+
for (const tool of [taskStopTool(tasks), taskWaitTool(tasks)]) {
|
|
315
|
+
addTool(tools, { name: tool.name, sourceId: TASKS_SOURCE_ID, tool }, options, logger, scope.seesTaskTool);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
if (shared.onDemand) {
|
|
320
|
+
const view: OnDemandCatalog = {
|
|
321
|
+
entries: catalogEntries,
|
|
322
|
+
get: (name) => catalogEntry(name)?.tool,
|
|
323
|
+
refresh: shared.refreshCatalog,
|
|
324
|
+
};
|
|
325
|
+
for (const tool of [searchToolsTool(view), callToolTool(view)]) {
|
|
326
|
+
addTool(tools, { name: tool.name, sourceId: ON_DEMAND_SOURCE_ID, tool }, options, logger, scope.sees);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** Whether calls to this tool may be deferred here: the tool allows it and the host can hold tasks. */
|
|
331
|
+
const deferrable = (tool: AgentTool): boolean => tasks !== undefined && tool.background !== undefined;
|
|
332
|
+
const always = (tool: AgentTool): boolean => tool.background?.always === true;
|
|
333
|
+
/** Deferring is the model's choice only where the tool left it one. */
|
|
334
|
+
const offersFlag = (tool: AgentTool): boolean => deferrable(tool) && !always(tool);
|
|
335
|
+
|
|
336
|
+
// Said when the registry is built: run in the foreground, such a call would block for minutes.
|
|
337
|
+
for (const entry of tools.values()) {
|
|
338
|
+
if (always(entry.tool) && tasks === undefined) {
|
|
339
|
+
throw new AgentError(
|
|
340
|
+
"config/invalid",
|
|
341
|
+
`${entry.name} always runs in the background, so its registry needs a task registry (\`tasks\`).`,
|
|
342
|
+
{ details: { toolName: entry.name } },
|
|
343
|
+
);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// The model sees the flag; the map keeps the tool as written, so its own
|
|
348
|
+
// schema, claims and description never meet it.
|
|
349
|
+
const modelTools = toModelTools(
|
|
350
|
+
new Map(
|
|
351
|
+
[...tools].map(
|
|
352
|
+
([name, entry]) =>
|
|
353
|
+
[name, offersFlag(entry.tool) ? withBackgroundFlag(entry.tool) : entry.tool] as const,
|
|
354
|
+
),
|
|
355
|
+
),
|
|
356
|
+
);
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* `call_tool` is unwrapped here, so everything after this sees the tool it
|
|
360
|
+
* names. A listed name may also be called through it; it never names itself.
|
|
361
|
+
* A host may call an on-demand tool by its own name.
|
|
362
|
+
*/
|
|
363
|
+
const targetOf = (call: ToolCall): Target => {
|
|
364
|
+
const wrapper = call.toolName === CALL_TOOL_NAME ? tools.get(CALL_TOOL_NAME) : undefined;
|
|
365
|
+
if (wrapper === undefined || wrapper.sourceId !== ON_DEMAND_SOURCE_ID) {
|
|
366
|
+
const entry = tools.get(call.toolName) ?? catalogEntry(call.toolName);
|
|
367
|
+
return entry === undefined
|
|
368
|
+
? { kind: "not-found", name: call.toolName, viaCallTool: false }
|
|
369
|
+
: { kind: "found", entry, input: call.input, viaCallTool: false };
|
|
370
|
+
}
|
|
371
|
+
let parsed: CallToolInput;
|
|
372
|
+
try {
|
|
373
|
+
parsed = wrapper.tool.parseInput(call.input) as CallToolInput;
|
|
374
|
+
} catch (error) {
|
|
375
|
+
return { kind: "invalid", entry: wrapper, error };
|
|
376
|
+
}
|
|
377
|
+
const { name } = parsed;
|
|
378
|
+
const entry = name === CALL_TOOL_NAME ? undefined : (catalogEntry(name) ?? tools.get(name));
|
|
379
|
+
return entry === undefined
|
|
380
|
+
? { kind: "not-found", name, viaCallTool: true }
|
|
381
|
+
: { kind: "found", entry, input: parsed.arguments ?? {}, viaCallTool: true };
|
|
382
|
+
};
|
|
383
|
+
|
|
384
|
+
// Shared by `preflight` and `execute`: two copies of this sequence would
|
|
385
|
+
// drift apart.
|
|
386
|
+
const assess = (call: ToolCall): Assessment => {
|
|
387
|
+
const target = targetOf(call);
|
|
388
|
+
if (target.kind !== "found") return target;
|
|
389
|
+
const { entry } = target;
|
|
390
|
+
try {
|
|
391
|
+
// Only where we added the flag: another tool may have a field of that name.
|
|
392
|
+
const { input, background } =
|
|
393
|
+
!target.viaCallTool && offersFlag(entry.tool)
|
|
394
|
+
? splitBackground(target.input)
|
|
395
|
+
: { input: target.input, background: deferrable(entry.tool) && always(entry.tool) };
|
|
396
|
+
entry.tool.parseInput(input);
|
|
397
|
+
const claim = entry.tool.resources(input);
|
|
398
|
+
const verdict = options.policy.decide({
|
|
399
|
+
toolName: entry.name,
|
|
400
|
+
danger: entry.tool.danger,
|
|
401
|
+
claim,
|
|
402
|
+
});
|
|
403
|
+
const shown = target.viaCallTool ? input : call.input;
|
|
404
|
+
return { kind: "ready", entry, input, shown, wantsBackground: background, claim, verdict };
|
|
405
|
+
} catch (error) {
|
|
406
|
+
return { kind: "invalid", entry, error };
|
|
407
|
+
}
|
|
408
|
+
};
|
|
409
|
+
|
|
410
|
+
const askFor = async (
|
|
411
|
+
entry: ToolRegistryEntry,
|
|
412
|
+
call: ToolCall,
|
|
413
|
+
input: unknown,
|
|
414
|
+
shown: unknown,
|
|
415
|
+
claim: ResourceClaim,
|
|
416
|
+
verdict: PermissionVerdict,
|
|
417
|
+
context: ToolRunContext,
|
|
418
|
+
publish: (payload: AgentEventPayload) => void,
|
|
419
|
+
): Promise<ApprovalOutcome> => {
|
|
420
|
+
// A turn that comes after Esc asks nobody.
|
|
421
|
+
if (context.signal.aborted) {
|
|
422
|
+
throw new AgentError("run/aborted", `${entry.name} was cancelled.`, {
|
|
423
|
+
details: { toolName: entry.name },
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
const approvalId = newId("approval");
|
|
428
|
+
// Built the same way as the transcript's line, so the two match. From the
|
|
429
|
+
// model's arguments, flag included: whoever answers should see that the
|
|
430
|
+
// call is meant to keep running.
|
|
431
|
+
const summary = callLine(entry.name, describeCall(entry.tool, shown) ?? "");
|
|
432
|
+
const change = await previewOf(entry.tool, input, context);
|
|
433
|
+
|
|
434
|
+
publish({
|
|
435
|
+
type: "tool-approval-request",
|
|
436
|
+
approvalId,
|
|
437
|
+
toolCallId: call.toolCallId,
|
|
438
|
+
toolName: entry.name,
|
|
439
|
+
input: shown,
|
|
440
|
+
danger: entry.tool.danger,
|
|
441
|
+
summary,
|
|
442
|
+
...(change === undefined ? {} : { change }),
|
|
443
|
+
});
|
|
444
|
+
|
|
445
|
+
// No handler, or one that answers with nothing, means nobody was asked, and
|
|
446
|
+
// both refuse. Neither message may say a user refused: the registry sees
|
|
447
|
+
// one handler and cannot see a chain a host built from it.
|
|
448
|
+
const answer =
|
|
449
|
+
options.approval === undefined
|
|
450
|
+
? undefined
|
|
451
|
+
: await options.approval(
|
|
452
|
+
{
|
|
453
|
+
approvalId,
|
|
454
|
+
toolCallId: call.toolCallId,
|
|
455
|
+
toolName: entry.name,
|
|
456
|
+
input: shown,
|
|
457
|
+
danger: entry.tool.danger,
|
|
458
|
+
claim,
|
|
459
|
+
summary,
|
|
460
|
+
...(change === undefined ? {} : { change }),
|
|
461
|
+
...(verdict.rule === undefined ? {} : { rule: verdict.rule }),
|
|
462
|
+
},
|
|
463
|
+
{
|
|
464
|
+
sessionId: context.sessionId,
|
|
465
|
+
runId: context.runId,
|
|
466
|
+
messages: context.messages ?? [],
|
|
467
|
+
},
|
|
468
|
+
);
|
|
469
|
+
|
|
470
|
+
const outcome: ApprovalOutcome =
|
|
471
|
+
answer === undefined
|
|
472
|
+
? {
|
|
473
|
+
decision: "denied",
|
|
474
|
+
decidedBy: "unattended",
|
|
475
|
+
reason:
|
|
476
|
+
options.approval === undefined
|
|
477
|
+
? "no approval handler was installed"
|
|
478
|
+
: "the approval handler did not answer",
|
|
479
|
+
}
|
|
480
|
+
: resolveApproval(answer);
|
|
481
|
+
|
|
482
|
+
publish({
|
|
483
|
+
type: "tool-approval-resolved",
|
|
484
|
+
approvalId,
|
|
485
|
+
decision: outcome.decision,
|
|
486
|
+
decidedBy: outcome.decidedBy,
|
|
487
|
+
...(outcome.reason === undefined ? {} : { reason: outcome.reason }),
|
|
488
|
+
...(outcome.usage === undefined ? {} : { usage: outcome.usage }),
|
|
489
|
+
});
|
|
490
|
+
|
|
491
|
+
return outcome;
|
|
492
|
+
};
|
|
493
|
+
|
|
494
|
+
/** A diff for the card, or nothing — a preview that fails costs the card a diff, never the call. */
|
|
495
|
+
const previewOf = async (
|
|
496
|
+
tool: AgentTool,
|
|
497
|
+
input: unknown,
|
|
498
|
+
context: ToolRunContext,
|
|
499
|
+
): Promise<FileChange | undefined> => {
|
|
500
|
+
try {
|
|
501
|
+
const edit = await tool.preview(input, toolContextFor(context, context.signal, () => {}, () => {}));
|
|
502
|
+
return edit === undefined ? undefined : compactChange(edit);
|
|
503
|
+
} catch (error) {
|
|
504
|
+
logger.debug("tool preview failed", { tool: tool.name, error: String(error) });
|
|
505
|
+
return undefined;
|
|
506
|
+
}
|
|
507
|
+
};
|
|
508
|
+
|
|
509
|
+
const toolContextFor = (
|
|
510
|
+
context: ToolRunContext,
|
|
511
|
+
signal: AbortSignal,
|
|
512
|
+
showChange: (edit: FileEdit) => void,
|
|
513
|
+
attach: (image: Attachment) => void,
|
|
514
|
+
task?: ToolTask,
|
|
515
|
+
): ToolContext => ({
|
|
516
|
+
cwd: options.cwd,
|
|
517
|
+
signal,
|
|
518
|
+
logger,
|
|
519
|
+
sessionId: context.sessionId,
|
|
520
|
+
runId: context.runId,
|
|
521
|
+
showChange,
|
|
522
|
+
attach,
|
|
523
|
+
...(options.roots === undefined ? {} : { roots: options.roots }),
|
|
524
|
+
...(options.resultsDir === undefined ? {} : { resultsDir: options.resultsDir }),
|
|
525
|
+
...(task === undefined ? {} : { task }),
|
|
526
|
+
delegate,
|
|
527
|
+
});
|
|
528
|
+
|
|
529
|
+
/** A narrower scope of this one, for an agent a tool starts. */
|
|
530
|
+
const delegate = (asked: DelegateOptions): Delegation => {
|
|
531
|
+
const denied = (name: string): boolean =>
|
|
532
|
+
asked.deny?.some((pattern) => matchPattern(pattern, name)) === true;
|
|
533
|
+
const sees = (name: string): boolean =>
|
|
534
|
+
scope.sees(name) &&
|
|
535
|
+
!denied(name) &&
|
|
536
|
+
(asked.allow === undefined || asked.allow.some((pattern) => matchPattern(pattern, name)));
|
|
537
|
+
|
|
538
|
+
// Only where a call can be deferred: tasks nobody can start are a folder nobody empties.
|
|
539
|
+
const canDefer = [...shared.listed].some(
|
|
540
|
+
([name, entry]) => sees(name) && entry.tool.background !== undefined,
|
|
541
|
+
);
|
|
542
|
+
const own =
|
|
543
|
+
asked.tasks === undefined || tasks === undefined || !canDefer
|
|
544
|
+
? undefined
|
|
545
|
+
: tasks.child(asked.tasks.id, asked.tasks.inbox);
|
|
546
|
+
|
|
547
|
+
const runner = scopedRunner(shared, {
|
|
548
|
+
tasks: own,
|
|
549
|
+
sees,
|
|
550
|
+
seesTaskTool: (name) => scope.seesTaskTool(name) && !denied(name),
|
|
551
|
+
});
|
|
552
|
+
return { tools: runner, ...(own === undefined ? {} : { tasks: own }) };
|
|
553
|
+
};
|
|
554
|
+
|
|
555
|
+
// Only what `call_tool` reaches from here is worth announcing to the model.
|
|
556
|
+
const reachesOnDemand = tools.get(CALL_TOOL_NAME)?.sourceId === ON_DEMAND_SOURCE_ID;
|
|
557
|
+
|
|
558
|
+
return {
|
|
559
|
+
entries: [...tools.values()],
|
|
560
|
+
modelTools,
|
|
561
|
+
onDemandEntries: catalogEntries,
|
|
562
|
+
|
|
563
|
+
...(reachesOnDemand
|
|
564
|
+
? {
|
|
565
|
+
onDemandTools: async () => {
|
|
566
|
+
await shared.refreshCatalog();
|
|
567
|
+
return catalogEntries()
|
|
568
|
+
.map((entry) => entry.name)
|
|
569
|
+
.sort();
|
|
570
|
+
},
|
|
571
|
+
}
|
|
572
|
+
: {}),
|
|
573
|
+
|
|
574
|
+
preflight(call: ToolCall): Preflight {
|
|
575
|
+
const assessment = assess(call);
|
|
576
|
+
if (assessment.kind !== "ready") return "serial";
|
|
577
|
+
return concurrencySafe(assessment.entry.tool) && assessment.verdict.decision === "allow"
|
|
578
|
+
? "parallel"
|
|
579
|
+
: "serial";
|
|
580
|
+
},
|
|
581
|
+
|
|
582
|
+
async execute(call: ToolCall, context: ToolRunContext): Promise<ToolOutcome> {
|
|
583
|
+
// Published at once if `context.emit` is set, else put in the outcome:
|
|
584
|
+
// never both, or one approval is recorded twice.
|
|
585
|
+
const events: AgentEventPayload[] = [];
|
|
586
|
+
const publish = (payload: AgentEventPayload): void => {
|
|
587
|
+
if (context.emit === undefined) events.push(payload);
|
|
588
|
+
else context.emit(payload);
|
|
589
|
+
};
|
|
590
|
+
|
|
591
|
+
// Asked again, not taken from `preflight`: that answer only scheduled the call.
|
|
592
|
+
const assessment = assess(call);
|
|
593
|
+
|
|
594
|
+
if (assessment.kind === "not-found") {
|
|
595
|
+
const message = assessment.viaCallTool
|
|
596
|
+
? `No tool named "${assessment.name}" can be called with ${CALL_TOOL_NAME}. Find tools with ${SEARCH_TOOLS_NAME}, and use the exact name it gives.`
|
|
597
|
+
: `No tool named "${assessment.name}" is available. Available tools: ${[...tools.keys()].join(", ")}.`;
|
|
598
|
+
return failure(
|
|
599
|
+
call,
|
|
600
|
+
new AgentError("tool/not-found", message, { details: { toolName: assessment.name } }),
|
|
601
|
+
events,
|
|
602
|
+
);
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
if (assessment.kind === "invalid") {
|
|
606
|
+
logger.debug("tool call failed", {
|
|
607
|
+
tool: assessment.entry.name,
|
|
608
|
+
error: String(assessment.error),
|
|
609
|
+
});
|
|
610
|
+
return failure(call, assessment.error, events);
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
const { entry, input, shown, wantsBackground, claim, verdict } = assessment;
|
|
614
|
+
const bill: Bill = {};
|
|
615
|
+
|
|
616
|
+
try {
|
|
617
|
+
if (verdict.decision === "deny") {
|
|
618
|
+
logger.info("tool call denied by policy", { tool: entry.name, reason: verdict.reason });
|
|
619
|
+
return failure(
|
|
620
|
+
call,
|
|
621
|
+
new AgentError(
|
|
622
|
+
"tool/denied",
|
|
623
|
+
`Permission denied: ${verdict.reason}. Do not retry this call — take a different approach or ask the user.`,
|
|
624
|
+
{ details: { toolName: entry.name, reason: verdict.reason } },
|
|
625
|
+
),
|
|
626
|
+
events,
|
|
627
|
+
);
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
if (verdict.decision === "ask") {
|
|
631
|
+
const outcome = await oneAtATime(() =>
|
|
632
|
+
askFor(entry, call, input, shown, claim, verdict, context, publish),
|
|
633
|
+
);
|
|
634
|
+
|
|
635
|
+
if (outcome.decision === "denied") {
|
|
636
|
+
return failure(
|
|
637
|
+
call,
|
|
638
|
+
new AgentError("tool/denied", refusalMessage(entry.name, outcome), {
|
|
639
|
+
details: {
|
|
640
|
+
toolName: entry.name,
|
|
641
|
+
decidedBy: outcome.decidedBy,
|
|
642
|
+
...(outcome.reason === undefined ? {} : { reason: outcome.reason }),
|
|
643
|
+
},
|
|
644
|
+
}),
|
|
645
|
+
events,
|
|
646
|
+
);
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// The last report wins: a tool that writes twice means the file as it was left.
|
|
651
|
+
let change: FileChange | undefined;
|
|
652
|
+
const showChange = (edit: FileEdit): void => {
|
|
653
|
+
change = compactChange(edit);
|
|
654
|
+
};
|
|
655
|
+
const attachments: Attachment[] = [];
|
|
656
|
+
const attach = (image: Attachment): void => {
|
|
657
|
+
attachments.push(image);
|
|
658
|
+
};
|
|
659
|
+
const output =
|
|
660
|
+
tasks !== undefined && entry.tool.background !== undefined
|
|
661
|
+
? await runDeferrable(entry, input, wantsBackground, call, context, tasks, bill, (signal, task) =>
|
|
662
|
+
toolContextFor(context, signal, showChange, attach, task),
|
|
663
|
+
)
|
|
664
|
+
: await runTool(entry, input, context, toolContextFor(context, context.signal, showChange, attach));
|
|
665
|
+
|
|
666
|
+
const outcome: ToolOutcome = {
|
|
667
|
+
toolCallId: call.toolCallId,
|
|
668
|
+
toolName: call.toolName,
|
|
669
|
+
output,
|
|
670
|
+
};
|
|
671
|
+
if (change !== undefined) outcome.change = change;
|
|
672
|
+
if (attachments.length > 0) outcome.attachments = attachments;
|
|
673
|
+
if (events.length > 0) outcome.events = events;
|
|
674
|
+
if (bill.usage !== undefined) outcome.usage = bill.usage;
|
|
675
|
+
return outcome;
|
|
676
|
+
} catch (error) {
|
|
677
|
+
logger.debug("tool call failed", { tool: entry.name, error: String(error) });
|
|
678
|
+
return failure(call, error, events, bill.usage);
|
|
679
|
+
}
|
|
680
|
+
},
|
|
681
|
+
};
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
/**
|
|
685
|
+
* Cancelling rejects the call at once, so a tool that ignores its signal still
|
|
686
|
+
* cannot hold the run open. Killing the process behind that signal is
|
|
687
|
+
* `bin.ts`'s job.
|
|
688
|
+
*
|
|
689
|
+
* No timeout here: a single one would cut `bash` short of the limit it offers
|
|
690
|
+
* the model, so tools that can run long carry their own.
|
|
691
|
+
*/
|
|
692
|
+
async function runTool(
|
|
693
|
+
entry: ToolRegistryEntry,
|
|
694
|
+
input: unknown,
|
|
695
|
+
context: ToolRunContext,
|
|
696
|
+
toolContext: ToolContext,
|
|
697
|
+
): Promise<unknown> {
|
|
698
|
+
const cancelled = (): AgentError =>
|
|
699
|
+
new AgentError("run/aborted", `${entry.name} was cancelled.`, {
|
|
700
|
+
details: { toolName: entry.name },
|
|
701
|
+
});
|
|
702
|
+
|
|
703
|
+
// A cancelled run starts nothing new. Racing would not do: a tool that
|
|
704
|
+
// resolves immediately would win the race and run anyway.
|
|
705
|
+
if (context.signal.aborted) throw cancelled();
|
|
706
|
+
|
|
707
|
+
let onAbort = (): void => {};
|
|
708
|
+
const aborted = new Promise<never>((_, reject) => {
|
|
709
|
+
onAbort = () => reject(cancelled());
|
|
710
|
+
context.signal.addEventListener("abort", onAbort, { once: true });
|
|
711
|
+
});
|
|
712
|
+
|
|
713
|
+
try {
|
|
714
|
+
return await Promise.race([entry.tool.execute(input, toolContext), aborted]);
|
|
715
|
+
} finally {
|
|
716
|
+
// The run's signal outlives this call; a listener left on it per call adds up.
|
|
717
|
+
context.signal.removeEventListener("abort", onAbort);
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
type Waited<T> = { kind: "done"; output: T } | { kind: "waited" } | { kind: "aborted" };
|
|
722
|
+
|
|
723
|
+
/** Whichever comes first: the call ending, the wait running out, or the turn being cancelled. */
|
|
724
|
+
function raceOf<T>(
|
|
725
|
+
done: Promise<T>,
|
|
726
|
+
waitMs: number | undefined,
|
|
727
|
+
signal: AbortSignal,
|
|
728
|
+
): Promise<Waited<T>> {
|
|
729
|
+
return new Promise((resolve, reject) => {
|
|
730
|
+
const tidy = (): void => {
|
|
731
|
+
clearTimeout(timer);
|
|
732
|
+
signal.removeEventListener("abort", onAbort);
|
|
733
|
+
};
|
|
734
|
+
const onAbort = (): void => {
|
|
735
|
+
tidy();
|
|
736
|
+
resolve({ kind: "aborted" });
|
|
737
|
+
};
|
|
738
|
+
const timer =
|
|
739
|
+
waitMs === undefined
|
|
740
|
+
? undefined
|
|
741
|
+
: setTimeout(() => {
|
|
742
|
+
tidy();
|
|
743
|
+
resolve({ kind: "waited" });
|
|
744
|
+
}, waitMs);
|
|
745
|
+
|
|
746
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
747
|
+
done.then(
|
|
748
|
+
(output) => {
|
|
749
|
+
tidy();
|
|
750
|
+
resolve({ kind: "done", output });
|
|
751
|
+
},
|
|
752
|
+
(error: unknown) => {
|
|
753
|
+
tidy();
|
|
754
|
+
reject(error);
|
|
755
|
+
},
|
|
756
|
+
);
|
|
757
|
+
});
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/** What a deferrable call spent, when it ended before it became a task. */
|
|
761
|
+
interface Bill {
|
|
762
|
+
usage?: Usage | undefined;
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
const TOLD_WHEN_DONE =
|
|
766
|
+
`You will be told when it ends, so do not sleep or poll for that. If nothing else is left to do until then, call ${TASK_WAIT_NAME}. Stop it with ${TASK_STOP_NAME}.`;
|
|
767
|
+
|
|
768
|
+
/** What the model reads in place of a result, for a call that is still running. */
|
|
769
|
+
function runningNotice(task: OpenTask, movedAfterMs?: number): string {
|
|
770
|
+
const waited =
|
|
771
|
+
movedAfterMs === undefined || movedAfterMs >= 1_000
|
|
772
|
+
? `${String(Math.round((movedAfterMs ?? 0) / 1_000))} s`
|
|
773
|
+
: `${String(movedAfterMs)} ms`;
|
|
774
|
+
const head =
|
|
775
|
+
movedAfterMs === undefined
|
|
776
|
+
? `Running in the background as ${task.id}.`
|
|
777
|
+
: `It did not finish in ${waited} and was moved to the background as ${task.id}.`;
|
|
778
|
+
const log =
|
|
779
|
+
task.outputPath === undefined
|
|
780
|
+
? ""
|
|
781
|
+
: " Its output is written to outputPath: read it with read_file or grep when you need it.";
|
|
782
|
+
return `${head}${log} ${TOLD_WHEN_DONE}`;
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
/**
|
|
786
|
+
* Runs a call that may outlive its turn. The tool gets the task's signal, not
|
|
787
|
+
* the turn's: once the call is in the background, cancelling the turn must not
|
|
788
|
+
* touch it.
|
|
789
|
+
*/
|
|
790
|
+
async function runDeferrable(
|
|
791
|
+
entry: ToolRegistryEntry,
|
|
792
|
+
input: unknown,
|
|
793
|
+
wantsBackground: boolean,
|
|
794
|
+
call: ToolCall,
|
|
795
|
+
context: ToolRunContext,
|
|
796
|
+
tasks: TaskRegistry,
|
|
797
|
+
bill: Bill,
|
|
798
|
+
contextFor: (signal: AbortSignal, task: ToolTask) => ToolContext,
|
|
799
|
+
): Promise<unknown> {
|
|
800
|
+
const cancelled = (): AgentError =>
|
|
801
|
+
new AgentError("run/aborted", `${entry.name} was cancelled.`, {
|
|
802
|
+
details: { toolName: entry.name },
|
|
803
|
+
});
|
|
804
|
+
if (context.signal.aborted) throw cancelled();
|
|
805
|
+
|
|
806
|
+
const spec = entry.tool.background ?? { log: false, always: false };
|
|
807
|
+
const id = spec.taskId?.(input);
|
|
808
|
+
const task = tasks.open({
|
|
809
|
+
toolName: entry.name,
|
|
810
|
+
toolCallId: call.toolCallId,
|
|
811
|
+
label: callLine(entry.name, describeCall(entry.tool, input) ?? ""),
|
|
812
|
+
log: spec.log,
|
|
813
|
+
...(id === undefined ? {} : { id }),
|
|
814
|
+
});
|
|
815
|
+
let done: Promise<unknown>;
|
|
816
|
+
try {
|
|
817
|
+
done = entry.tool.execute(input, contextFor(task.signal, task.context));
|
|
818
|
+
} catch (error) {
|
|
819
|
+
// A tool that throws before it returns a promise never became a task.
|
|
820
|
+
task.discard();
|
|
821
|
+
throw error;
|
|
822
|
+
}
|
|
823
|
+
// Nobody may be waiting for it yet, and an unheard rejection ends the process.
|
|
824
|
+
done.catch(() => {});
|
|
825
|
+
|
|
826
|
+
// Asked into the background, a call gets a moment to fail fast; any other
|
|
827
|
+
// waits as long as the tool says, or for ever.
|
|
828
|
+
const wait = wantsBackground ? tasks.graceMs : spec.moveAfterMs?.(input);
|
|
829
|
+
|
|
830
|
+
let outcome: Waited<unknown>;
|
|
831
|
+
try {
|
|
832
|
+
outcome = await raceOf(done, wait, context.signal);
|
|
833
|
+
} catch (error) {
|
|
834
|
+
// It failed while we were still waiting: an ordinary error of an ordinary call.
|
|
835
|
+
bill.usage = task.spent();
|
|
836
|
+
task.discard();
|
|
837
|
+
throw error;
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
// Ended in the foreground, there is no task record to say what it spent: the outcome does.
|
|
841
|
+
if (outcome.kind === "done") {
|
|
842
|
+
bill.usage = task.spent();
|
|
843
|
+
task.discard();
|
|
844
|
+
return outcome.output;
|
|
845
|
+
}
|
|
846
|
+
if (outcome.kind === "aborted") {
|
|
847
|
+
task.stop("host");
|
|
848
|
+
bill.usage = task.spent();
|
|
849
|
+
task.discard();
|
|
850
|
+
throw cancelled();
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
task.background(done);
|
|
854
|
+
const output = task.output();
|
|
855
|
+
return {
|
|
856
|
+
status: "running",
|
|
857
|
+
taskId: task.id,
|
|
858
|
+
...(task.outputPath === undefined ? {} : { outputPath: task.outputPath }),
|
|
859
|
+
...(output === "" ? {} : { output }),
|
|
860
|
+
notice: runningNotice(task, wantsBackground ? undefined : wait),
|
|
861
|
+
};
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
/** The names the registry gives its own tools, which no on-demand tool may take. */
|
|
865
|
+
const OWN_TOOL_NAMES: ReadonlySet<string> = new Set([
|
|
866
|
+
TASK_STOP_NAME,
|
|
867
|
+
TASK_WAIT_NAME,
|
|
868
|
+
SEARCH_TOOLS_NAME,
|
|
869
|
+
CALL_TOOL_NAME,
|
|
870
|
+
]);
|
|
871
|
+
|
|
872
|
+
/** Onto a list of tools; a second tool under one name is an error, never a silent override. */
|
|
873
|
+
function addTool(
|
|
874
|
+
into: Map<string, ToolRegistryEntry>,
|
|
875
|
+
entry: ToolRegistryEntry,
|
|
876
|
+
options: ToolRegistryOptions,
|
|
877
|
+
logger: Logger,
|
|
878
|
+
seen: (name: string) => boolean = () => true,
|
|
879
|
+
): void {
|
|
880
|
+
if (!isVisible(entry.name, options) || !seen(entry.name)) {
|
|
881
|
+
logger.debug("tool hidden by configuration", { tool: entry.name });
|
|
882
|
+
return;
|
|
883
|
+
}
|
|
884
|
+
const clash = into.get(entry.name);
|
|
885
|
+
if (clash !== undefined) {
|
|
886
|
+
throw new AgentError(
|
|
887
|
+
"tool/duplicate-name",
|
|
888
|
+
`Two tool sources both provide "${entry.name}" ("${clash.sourceId}" and "${entry.sourceId}").`,
|
|
889
|
+
{ details: { tool: entry.name } },
|
|
890
|
+
);
|
|
891
|
+
}
|
|
892
|
+
into.set(entry.name, entry);
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
function isVisible(name: string, options: ToolRegistryOptions): boolean {
|
|
896
|
+
if (options.deny?.some((pattern) => matchPattern(pattern, name)) === true) return false;
|
|
897
|
+
if (options.allow === undefined) return true;
|
|
898
|
+
return options.allow.some((pattern) => matchPattern(pattern, name));
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
/**
|
|
902
|
+
* The model must be able to tell "a person said no" from "nobody was there":
|
|
903
|
+
* the second is worth mentioning to the user, the first is not. Both end with
|
|
904
|
+
* "do not retry", since a retried refusal costs a whole step.
|
|
905
|
+
*/
|
|
906
|
+
function refusalMessage(toolName: string, outcome: ApprovalOutcome): string {
|
|
907
|
+
const why = outcome.reason === undefined ? "" : ` (${outcome.reason})`;
|
|
908
|
+
if (outcome.decidedBy === "unattended") {
|
|
909
|
+
return `${toolName} needs approval and there is nobody to ask${why}, so it was refused. Do not retry it — take a different approach, or tell the user what you would need.`;
|
|
910
|
+
}
|
|
911
|
+
const who = outcome.decidedBy === "classifier" ? "The approval policy" : "The user";
|
|
912
|
+
return `${who} denied this call${why}. Do not retry it — take a different approach or ask what to do instead.`;
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
function failure(
|
|
916
|
+
call: ToolCall,
|
|
917
|
+
error: unknown,
|
|
918
|
+
events: AgentEventPayload[],
|
|
919
|
+
usage?: Usage,
|
|
920
|
+
): ToolOutcome {
|
|
921
|
+
const outcome: ToolOutcome = {
|
|
922
|
+
toolCallId: call.toolCallId,
|
|
923
|
+
toolName: call.toolName,
|
|
924
|
+
error: serializeError(error),
|
|
925
|
+
};
|
|
926
|
+
if (events.length > 0) outcome.events = events;
|
|
927
|
+
// A call that failed still cost what it had spent by then.
|
|
928
|
+
if (usage !== undefined) outcome.usage = usage;
|
|
929
|
+
return outcome;
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
function defaultIdGenerator(): (prefix: string) => string {
|
|
933
|
+
let counter = 0;
|
|
934
|
+
return (prefix) => `${prefix}-${++counter}-${Math.random().toString(36).slice(2, 8)}`;
|
|
935
|
+
}
|