@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,267 @@
|
|
|
1
|
+
import type { ZodType } from "zod";
|
|
2
|
+
import type { Attachment } from "../agent/attachments";
|
|
3
|
+
import type { ToolRunner } from "../agent/tools";
|
|
4
|
+
import { AgentError } from "../errors";
|
|
5
|
+
import type { Usage } from "../events/types";
|
|
6
|
+
import type { Logger } from "../logger";
|
|
7
|
+
import type { ExtraRoot } from "../paths";
|
|
8
|
+
import type { FileEdit } from "./change";
|
|
9
|
+
import type { TaskInbox, TaskRegistry } from "./tasks";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* What a tool is, and what it has to tell the permission policy about itself.
|
|
13
|
+
*
|
|
14
|
+
* `execute` is called by us, never by the SDK. Only `{ description,
|
|
15
|
+
* inputSchema }` goes to the model (`to-model.ts`).
|
|
16
|
+
*
|
|
17
|
+
* The tool declares what it does (`danger`) and what it touches (`resources`);
|
|
18
|
+
* the policy decides, and the UI asks.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The config schema builds its enum from this list, so a level added here
|
|
23
|
+
* cannot go missing from `permissions.classifier.decides`.
|
|
24
|
+
*/
|
|
25
|
+
export const DANGER_LEVELS = ["safe", "read", "write", "exec", "network"] as const;
|
|
26
|
+
|
|
27
|
+
export type DangerLevel = (typeof DANGER_LEVELS)[number];
|
|
28
|
+
|
|
29
|
+
/** What one invocation would actually touch. Paths may be relative to cwd. */
|
|
30
|
+
export interface ResourceClaim {
|
|
31
|
+
paths?: readonly string[];
|
|
32
|
+
/** Full command line, for shell tools. */
|
|
33
|
+
command?: string;
|
|
34
|
+
url?: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface ToolContext {
|
|
38
|
+
cwd: string;
|
|
39
|
+
signal: AbortSignal;
|
|
40
|
+
logger: Logger;
|
|
41
|
+
sessionId: string;
|
|
42
|
+
runId: string;
|
|
43
|
+
/**
|
|
44
|
+
* What a write did, for the screen alone. The model never sees it: a diff in
|
|
45
|
+
* `output` would put the file into the context on every edit.
|
|
46
|
+
*/
|
|
47
|
+
showChange(edit: FileEdit): void;
|
|
48
|
+
/**
|
|
49
|
+
* An image for the model, beside `output`. The core decides how each vendor
|
|
50
|
+
* gets it, and tells a model that takes no images that one was left out.
|
|
51
|
+
*/
|
|
52
|
+
attach(image: Attachment): void;
|
|
53
|
+
/** Directories outside the workspace the file tools may use; absent means none. */
|
|
54
|
+
roots?: readonly ExtraRoot[];
|
|
55
|
+
/** Where a result too big to return is kept; absent means it is cut in place. */
|
|
56
|
+
resultsDir?: string;
|
|
57
|
+
/** Present when this call may outlive its turn; `signal` is then the task's. */
|
|
58
|
+
task?: ToolTask;
|
|
59
|
+
/**
|
|
60
|
+
* The runner's own tools for an agent this call starts: the same policy, the
|
|
61
|
+
* same questions asked one at a time, fewer names. Absent from a runner that
|
|
62
|
+
* cannot hand its tools on.
|
|
63
|
+
*/
|
|
64
|
+
delegate?(options: DelegateOptions): Delegation;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** What a tool sees of the task its call may become. */
|
|
68
|
+
export interface ToolTask {
|
|
69
|
+
readonly id: string;
|
|
70
|
+
/** True once the call has left the foreground. */
|
|
71
|
+
readonly background: boolean;
|
|
72
|
+
/** Appends to the task's log. A no-op for a task without one. */
|
|
73
|
+
write(chunk: string | Uint8Array): void;
|
|
74
|
+
/**
|
|
75
|
+
* Adds to what this call cost in model calls of its own, as a tool that runs
|
|
76
|
+
* an agent does. It reaches the session's bill whichever way the call ends.
|
|
77
|
+
*/
|
|
78
|
+
spend(usage: Usage): void;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** How a tool that may be deferred wants that done. */
|
|
82
|
+
export interface BackgroundSpec<TInput> {
|
|
83
|
+
/** The tool streams output through `context.task.write`, so the task gets a log file. */
|
|
84
|
+
log?: boolean;
|
|
85
|
+
/** How long a foreground call may run before it is moved to the background. Absent: never moved. */
|
|
86
|
+
moveAfterMs?: (input: TInput) => number;
|
|
87
|
+
/**
|
|
88
|
+
* Every call is deferred and the model is offered no flag: work that takes
|
|
89
|
+
* minutes by nature, such as a sub-agent. Such a tool needs a host with a
|
|
90
|
+
* task registry, and a registry without one refuses to be built.
|
|
91
|
+
*/
|
|
92
|
+
always?: true;
|
|
93
|
+
/**
|
|
94
|
+
* The id this call's task takes, for a call that continues work an earlier
|
|
95
|
+
* task began. Absent, or answering `undefined`: a fresh one.
|
|
96
|
+
*/
|
|
97
|
+
taskId?: (input: TInput) => string | undefined;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Which of a runner's tools somebody else may use. Names are globs; deny wins. */
|
|
101
|
+
export interface DelegateOptions {
|
|
102
|
+
/** Absent: every tool the runner lists. */
|
|
103
|
+
allow?: readonly string[];
|
|
104
|
+
deny?: readonly string[];
|
|
105
|
+
/**
|
|
106
|
+
* Gives the other side background tasks of its own, kept under this id and
|
|
107
|
+
* announced to this inbox. Absent: its calls cannot be deferred.
|
|
108
|
+
*/
|
|
109
|
+
tasks?: { id: string; inbox: TaskInbox };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export interface Delegation {
|
|
113
|
+
tools: ToolRunner;
|
|
114
|
+
/** Absent when no tasks were asked for, or none of the tools can be deferred. */
|
|
115
|
+
tasks?: TaskRegistry;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export interface AgentToolDefinition<TInput, TOutput> {
|
|
119
|
+
name: string;
|
|
120
|
+
/** Read by the model, so: English, imperative, specific about limits. */
|
|
121
|
+
description: string;
|
|
122
|
+
inputSchema: ZodType<TInput>;
|
|
123
|
+
danger: DangerLevel;
|
|
124
|
+
/**
|
|
125
|
+
* Calls may overlap with other calls, this tool's own included, once nobody
|
|
126
|
+
* has to be asked about them. Absent: true for `safe` and `read` only.
|
|
127
|
+
*/
|
|
128
|
+
parallel?: boolean;
|
|
129
|
+
resources?: (input: TInput) => ResourceClaim;
|
|
130
|
+
/**
|
|
131
|
+
* The call's arguments in one line, without the tool's own name: the caller
|
|
132
|
+
* adds the name and the parentheses, so a name here comes out twice.
|
|
133
|
+
* `src/app.ts`, never `read_file src/app.ts`.
|
|
134
|
+
*
|
|
135
|
+
* Only the tool can write this: `write_file` shows its path and never its
|
|
136
|
+
* `content`, which keeps secrets and file text out of events.
|
|
137
|
+
*
|
|
138
|
+
* Absent: the line is built from `resources()`, which most tools declare
|
|
139
|
+
* anyway.
|
|
140
|
+
*/
|
|
141
|
+
describe?: (input: TInput) => string;
|
|
142
|
+
/**
|
|
143
|
+
* What came back, in one line. Absent leaves the front end to summarise it.
|
|
144
|
+
*
|
|
145
|
+
* Write it after `execute`, not before. The output type is inferred from
|
|
146
|
+
* `execute`, and TypeScript resolves these two function properties in the
|
|
147
|
+
* order they appear: put this one first and `output` is `unknown`. `NoInfer`
|
|
148
|
+
* keeps this parameter out of that inference, so a wrong order is an error
|
|
149
|
+
* here rather than `unknown` everywhere.
|
|
150
|
+
*/
|
|
151
|
+
describeResult?: (output: NoInfer<TOutput>) => string;
|
|
152
|
+
/**
|
|
153
|
+
* What the call would change, computed without writing, so an approval
|
|
154
|
+
* prompt can show a diff before anybody says yes. Returning `undefined`
|
|
155
|
+
* leaves the prompt without one and never stops the call.
|
|
156
|
+
*/
|
|
157
|
+
preview?: (input: TInput, context: ToolContext) => Promise<FileEdit | undefined>;
|
|
158
|
+
/**
|
|
159
|
+
* The call may be deferred: its result then arrives later, as a notice. A
|
|
160
|
+
* permission, not an order — only a host with a task registry offers it, and
|
|
161
|
+
* `execute` stays an ordinary function either way.
|
|
162
|
+
*/
|
|
163
|
+
background?: true | BackgroundSpec<TInput>;
|
|
164
|
+
execute: (input: TInput, context: ToolContext) => Promise<TOutput>;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* A tool with its input type erased, which is what the registry stores. The
|
|
169
|
+
* generic types apply only at the call site, where `defineTool` checks
|
|
170
|
+
* `execute` against the schema.
|
|
171
|
+
*/
|
|
172
|
+
export interface AgentTool {
|
|
173
|
+
readonly name: string;
|
|
174
|
+
readonly description: string;
|
|
175
|
+
readonly danger: DangerLevel;
|
|
176
|
+
/** Absent: decided by `danger`. */
|
|
177
|
+
readonly parallel?: boolean;
|
|
178
|
+
/** Zod schema; the SDK turns it into JSON Schema for the model. */
|
|
179
|
+
readonly inputSchema: ZodType;
|
|
180
|
+
/**
|
|
181
|
+
* The input schema as JSON Schema, for a tool that came with one, such as an
|
|
182
|
+
* MCP tool. `search_tools` shows it; absent, it is derived from `inputSchema`.
|
|
183
|
+
*/
|
|
184
|
+
readonly parameters?: Record<string, unknown>;
|
|
185
|
+
/** Re-validates model input, because an MCP or hand-built host may not have. */
|
|
186
|
+
parseInput(input: unknown): unknown;
|
|
187
|
+
resources(input: unknown): ResourceClaim;
|
|
188
|
+
describe(input: unknown): string;
|
|
189
|
+
describeResult(output: unknown): string | undefined;
|
|
190
|
+
preview(input: unknown, context: ToolContext): Promise<FileEdit | undefined>;
|
|
191
|
+
/** Present when the tool allowed deferring its calls. */
|
|
192
|
+
readonly background?: {
|
|
193
|
+
log: boolean;
|
|
194
|
+
always: boolean;
|
|
195
|
+
moveAfterMs?(input: unknown): number;
|
|
196
|
+
taskId?(input: unknown): string | undefined;
|
|
197
|
+
};
|
|
198
|
+
execute(input: unknown, context: ToolContext): Promise<unknown>;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export function defineTool<TInput, TOutput>(
|
|
202
|
+
definition: AgentToolDefinition<TInput, TOutput>,
|
|
203
|
+
): AgentTool {
|
|
204
|
+
const parseInput = (input: unknown): TInput => {
|
|
205
|
+
const parsed = definition.inputSchema.safeParse(input);
|
|
206
|
+
if (!parsed.success) {
|
|
207
|
+
throw new AgentError(
|
|
208
|
+
"tool/invalid-input",
|
|
209
|
+
`Invalid input for ${definition.name}: ${describeIssues(parsed.error)}`,
|
|
210
|
+
{ details: { toolName: definition.name } },
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
return parsed.data;
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
const resources = (input: unknown): ResourceClaim =>
|
|
217
|
+
definition.resources?.(parseInput(input)) ?? {};
|
|
218
|
+
|
|
219
|
+
const spec = definition.background === true ? {} : definition.background;
|
|
220
|
+
const moveAfterMs = spec?.moveAfterMs;
|
|
221
|
+
const taskId = spec?.taskId;
|
|
222
|
+
const background =
|
|
223
|
+
spec === undefined
|
|
224
|
+
? undefined
|
|
225
|
+
: {
|
|
226
|
+
log: spec.log === true,
|
|
227
|
+
always: spec.always === true,
|
|
228
|
+
...(moveAfterMs === undefined
|
|
229
|
+
? {}
|
|
230
|
+
: { moveAfterMs: (input: unknown) => moveAfterMs(parseInput(input)) }),
|
|
231
|
+
...(taskId === undefined ? {} : { taskId: (input: unknown) => taskId(parseInput(input)) }),
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
return {
|
|
235
|
+
name: definition.name,
|
|
236
|
+
description: definition.description,
|
|
237
|
+
danger: definition.danger,
|
|
238
|
+
...(definition.parallel === undefined ? {} : { parallel: definition.parallel }),
|
|
239
|
+
inputSchema: definition.inputSchema as ZodType,
|
|
240
|
+
parseInput,
|
|
241
|
+
resources,
|
|
242
|
+
describe: (input) => definition.describe?.(parseInput(input)) ?? claimed(resources(input)),
|
|
243
|
+
describeResult: (output) => definition.describeResult?.(output as TOutput),
|
|
244
|
+
preview: async (input, context) => definition.preview?.(parseInput(input), context),
|
|
245
|
+
...(background === undefined ? {} : { background }),
|
|
246
|
+
execute: (input, context) => definition.execute(parseInput(input), context),
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* What a tool told the permission policy, reused as words.
|
|
252
|
+
*
|
|
253
|
+
* A tool that declares nothing gets an empty line rather than its own name:
|
|
254
|
+
* the name is added by the caller.
|
|
255
|
+
*/
|
|
256
|
+
function claimed(claim: ResourceClaim): string {
|
|
257
|
+
return claim.command ?? claim.url ?? claim.paths?.join(", ") ?? "";
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function describeIssues(error: { issues: readonly { path: PropertyKey[]; message: string }[] }): string {
|
|
261
|
+
return error.issues
|
|
262
|
+
.map((issue) => {
|
|
263
|
+
const where = issue.path.map(String).join(".");
|
|
264
|
+
return where === "" ? issue.message : `${where}: ${issue.message}`;
|
|
265
|
+
})
|
|
266
|
+
.join("; ");
|
|
267
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import type { AgentTool } from "./define";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Tools, as words on a screen.
|
|
5
|
+
*
|
|
6
|
+
* The tool writes the content, the front end paints it, and the host
|
|
7
|
+
* introduces them. This file is the introduction: it knows no terminals,
|
|
8
|
+
* colours or widths, and nothing in `ui-kit` knows about tools.
|
|
9
|
+
*
|
|
10
|
+
* Failures answer `undefined`: a tool whose `describe` throws, or one not in
|
|
11
|
+
* this set, gives nothing, and the caller falls back to the raw arguments.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** A tool under the name the model sees. `ToolRegistryEntry` satisfies this. */
|
|
15
|
+
export interface ToolDescription {
|
|
16
|
+
name: string;
|
|
17
|
+
tool: AgentTool;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The shape of a call as one line: `name(args)`.
|
|
22
|
+
*
|
|
23
|
+
* Decided here, so the approval prompt and the transcript cannot disagree.
|
|
24
|
+
*/
|
|
25
|
+
export function callLine(name: string, args: string): string {
|
|
26
|
+
return `${name}(${args})`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** What a host hands a front end. `ui-kit` declares this shape for itself. */
|
|
30
|
+
export interface ToolDescriber {
|
|
31
|
+
call(toolName: string, input: unknown): string | undefined;
|
|
32
|
+
result(toolName: string, output: unknown): string | undefined;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function describeTools(entries: readonly ToolDescription[]): ToolDescriber {
|
|
36
|
+
const byName = new Map(entries.map((entry) => [entry.name, entry.tool]));
|
|
37
|
+
|
|
38
|
+
return {
|
|
39
|
+
call(toolName, input) {
|
|
40
|
+
const tool = byName.get(toolName);
|
|
41
|
+
return tool === undefined ? undefined : describeCall(tool, input);
|
|
42
|
+
},
|
|
43
|
+
result(toolName, output) {
|
|
44
|
+
// Before the tool's own words: it describes what it returns, not this.
|
|
45
|
+
if (isRunningResult(output)) return `running in the background as ${output.taskId}`;
|
|
46
|
+
const tool = byName.get(toolName);
|
|
47
|
+
if (tool === undefined) return undefined;
|
|
48
|
+
try {
|
|
49
|
+
return tool.describeResult(output);
|
|
50
|
+
} catch {
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** What the registry answers with for a call that went to the background. */
|
|
58
|
+
export function isRunningResult(output: unknown): output is { status: "running"; taskId: string } {
|
|
59
|
+
return (
|
|
60
|
+
typeof output === "object" &&
|
|
61
|
+
output !== null &&
|
|
62
|
+
(output as { status?: unknown }).status === "running" &&
|
|
63
|
+
typeof (output as { taskId?: unknown }).taskId === "string"
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The parameter the registry adds to a tool that may run in the background. */
|
|
68
|
+
export const BACKGROUND_FLAG = "run_in_background";
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* One call in words, or nothing.
|
|
72
|
+
*
|
|
73
|
+
* `describe` re-validates its input, so malformed arguments from the model
|
|
74
|
+
* throw here. The result is `undefined`, not a message: the caller still has
|
|
75
|
+
* the raw arguments and shows those.
|
|
76
|
+
*
|
|
77
|
+
* The background flag is the registry's and the tool never sees it, so it is
|
|
78
|
+
* said here: whoever approves the call should know it will outlive the turn.
|
|
79
|
+
*/
|
|
80
|
+
export function describeCall(tool: AgentTool, input: unknown): string | undefined {
|
|
81
|
+
try {
|
|
82
|
+
// Only for a tool that may be deferred: another may have a field of that name.
|
|
83
|
+
const flagged =
|
|
84
|
+
tool.background !== undefined && typeof input === "object" && input !== null && BACKGROUND_FLAG in input;
|
|
85
|
+
// Off before the tool sees it, whatever its value: a strict schema would refuse the field.
|
|
86
|
+
const own = flagged
|
|
87
|
+
? Object.fromEntries(Object.entries(input).filter(([key]) => key !== BACKGROUND_FLAG))
|
|
88
|
+
: input;
|
|
89
|
+
const described = tool.describe(own);
|
|
90
|
+
if (described === "") return undefined;
|
|
91
|
+
const background = flagged && (input as Record<string, unknown>)[BACKGROUND_FLAG] === true;
|
|
92
|
+
return background ? `${described}, in the background` : described;
|
|
93
|
+
} catch {
|
|
94
|
+
return undefined;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { AgentError } from "../../errors";
|
|
4
|
+
import { defineTool } from "../define";
|
|
5
|
+
import { displayPath, resolveInWorkspace } from "../../paths";
|
|
6
|
+
import { lineEndingOf, withLineEnding } from "./line-endings";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Exact string replacement, and it refuses an ambiguous match rather than
|
|
10
|
+
* guess: a guess corrupts the file silently. The failure carries the count,
|
|
11
|
+
* which the model can act on.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export const editFileTool = defineTool({
|
|
15
|
+
name: "edit_file",
|
|
16
|
+
description:
|
|
17
|
+
"Replace an exact string in a file. `old_string` must appear exactly once " +
|
|
18
|
+
"unless `replace_all` is true — include surrounding lines to make it " +
|
|
19
|
+
"unique. Read the file first; the match is literal, whitespace included. " +
|
|
20
|
+
"read_file prefixes each line with its number and a tab; never copy that " +
|
|
21
|
+
"prefix into `old_string` or `new_string`.",
|
|
22
|
+
danger: "write",
|
|
23
|
+
inputSchema: z.object({
|
|
24
|
+
path: z.string().min(1).describe("Path to the file, relative to the workspace root."),
|
|
25
|
+
old_string: z.string().min(1).describe("Text to find. Must match exactly."),
|
|
26
|
+
new_string: z.string().describe("Text to put in its place. May be empty to delete."),
|
|
27
|
+
replace_all: z.boolean().optional().describe("Replace every occurrence instead of failing."),
|
|
28
|
+
}),
|
|
29
|
+
resources: (input) => ({ paths: [input.path] }),
|
|
30
|
+
describe: (input) => input.path,
|
|
31
|
+
preview: async (input, context) => {
|
|
32
|
+
if (input.old_string === input.new_string) return undefined;
|
|
33
|
+
const absolute = resolveInWorkspace(context, input.path, "write");
|
|
34
|
+
const before = await readFile(absolute, "utf8");
|
|
35
|
+
return {
|
|
36
|
+
path: displayPath(context.cwd, absolute),
|
|
37
|
+
before,
|
|
38
|
+
after: applyEdit(before, input).after,
|
|
39
|
+
};
|
|
40
|
+
},
|
|
41
|
+
execute: async (input, context) => {
|
|
42
|
+
const absolute = resolveInWorkspace(context, input.path, "write");
|
|
43
|
+
|
|
44
|
+
if (input.old_string === input.new_string) {
|
|
45
|
+
throw new AgentError("tool/invalid-input", "old_string and new_string are identical.", {
|
|
46
|
+
details: { path: input.path },
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const before = await readFile(absolute, "utf8").catch((cause: unknown) => {
|
|
51
|
+
throw new AgentError("tool/failed", `Cannot read "${input.path}": ${reason(cause)}`, {
|
|
52
|
+
cause,
|
|
53
|
+
details: { path: input.path },
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
const { after, replacements } = applyEdit(before, input);
|
|
58
|
+
await writeFile(absolute, after, "utf8");
|
|
59
|
+
|
|
60
|
+
const path = displayPath(context.cwd, absolute);
|
|
61
|
+
context.showChange({ path, before, after });
|
|
62
|
+
return { path, replacements };
|
|
63
|
+
},
|
|
64
|
+
describeResult: (output) =>
|
|
65
|
+
`${String(output.replacements)} ${output.replacements === 1 ? "replacement" : "replacements"}`,
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
interface EditInput {
|
|
69
|
+
path: string;
|
|
70
|
+
old_string: string;
|
|
71
|
+
new_string: string;
|
|
72
|
+
replace_all?: boolean | undefined;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Shared by `preview` and `execute`, so the card shows the edit that would run. */
|
|
76
|
+
function applyEdit(before: string, input: EditInput): { after: string; replacements: number } {
|
|
77
|
+
// Both strings take the file's line ending: converting the strings rather
|
|
78
|
+
// than the file leaves every line outside the edit alone.
|
|
79
|
+
const ending = lineEndingOf(before);
|
|
80
|
+
let oldString = withLineEnding(input.old_string, ending);
|
|
81
|
+
let newString = withLineEnding(input.new_string, ending);
|
|
82
|
+
let occurrences = countOccurrences(before, oldString);
|
|
83
|
+
|
|
84
|
+
// A mixed file is called CRLF, and the lines being edited may be LF ones.
|
|
85
|
+
if (occurrences === 0 && ending === "\r\n") {
|
|
86
|
+
oldString = withLineEnding(input.old_string, "\n");
|
|
87
|
+
newString = withLineEnding(input.new_string, "\n");
|
|
88
|
+
occurrences = countOccurrences(before, oldString);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
if (occurrences === 0) {
|
|
92
|
+
throw new AgentError("tool/failed", `old_string was not found in "${input.path}".`, {
|
|
93
|
+
details: { path: input.path },
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
if (occurrences > 1 && input.replace_all !== true) {
|
|
97
|
+
throw new AgentError(
|
|
98
|
+
"tool/failed",
|
|
99
|
+
`old_string appears ${occurrences} times in "${input.path}". ` +
|
|
100
|
+
"Include more surrounding text, or pass replace_all.",
|
|
101
|
+
{ details: { path: input.path, occurrences } },
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Never String.replace here: it would read `$&` and friends in new_string
|
|
106
|
+
// as replacement patterns, which is silent corruption in a code file.
|
|
107
|
+
return input.replace_all === true
|
|
108
|
+
? { after: before.split(oldString).join(newString), replacements: occurrences }
|
|
109
|
+
: { after: replaceFirst(before, oldString, newString), replacements: 1 };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function replaceFirst(haystack: string, needle: string, replacement: string): string {
|
|
113
|
+
const index = haystack.indexOf(needle);
|
|
114
|
+
return haystack.slice(0, index) + replacement + haystack.slice(index + needle.length);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function countOccurrences(haystack: string, needle: string): number {
|
|
118
|
+
let count = 0;
|
|
119
|
+
let index = haystack.indexOf(needle);
|
|
120
|
+
while (index !== -1) {
|
|
121
|
+
count += 1;
|
|
122
|
+
index = haystack.indexOf(needle, index + needle.length);
|
|
123
|
+
}
|
|
124
|
+
return count;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function reason(cause: unknown): string {
|
|
128
|
+
return cause instanceof Error ? cause.message : String(cause);
|
|
129
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { readdir } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { couldMatchInside, matchGlob } from "../../glob";
|
|
5
|
+
import { defineTool } from "../define";
|
|
6
|
+
import { displayPath, pathOrRoot, resolveInWorkspace } from "../../paths";
|
|
7
|
+
import { NOISY_DIRECTORIES } from "./list-dir";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Finding files by name, with our own matcher: not `Bun.Glob`, because the core
|
|
11
|
+
* must stay runnable on Node, and not a dependency. Permission rules use the
|
|
12
|
+
* same matcher, so `src/**` means one thing in a rule and in a search.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const DEFAULT_LIMIT = 200;
|
|
16
|
+
const MAX_LIMIT = 1_000;
|
|
17
|
+
|
|
18
|
+
export const globTool = defineTool({
|
|
19
|
+
name: "glob",
|
|
20
|
+
description:
|
|
21
|
+
"Find files whose path matches a glob pattern, e.g. `src/**/*.ts` or " +
|
|
22
|
+
"`**/*.{json,md}`. Supports *, **, ?, [abc] and {a,b}. Results are paths " +
|
|
23
|
+
"relative to the workspace root, sorted; .git and node_modules are skipped.",
|
|
24
|
+
danger: "read",
|
|
25
|
+
inputSchema: z.object({
|
|
26
|
+
pattern: z.string().min(1).describe("Glob pattern, relative to `path`."),
|
|
27
|
+
path: z.string().optional().describe("Directory to search in. Defaults to the workspace root."),
|
|
28
|
+
limit: z.number().int().min(1).max(MAX_LIMIT).optional().describe("Maximum number of results."),
|
|
29
|
+
}),
|
|
30
|
+
resources: (input) => ({ paths: [pathOrRoot(input.path)] }),
|
|
31
|
+
describe: (input) => input.pattern,
|
|
32
|
+
execute: async (input, context) => {
|
|
33
|
+
const base = resolveInWorkspace(context, pathOrRoot(input.path));
|
|
34
|
+
const limit = input.limit ?? DEFAULT_LIMIT;
|
|
35
|
+
// Walked paths never start with `./`, so a pattern that does matches nothing.
|
|
36
|
+
const pattern = input.pattern.replace(/^(?:\.\/)+/, "");
|
|
37
|
+
const found: string[] = [];
|
|
38
|
+
let truncated = false;
|
|
39
|
+
|
|
40
|
+
const visit = async (directory: string, relative: string): Promise<void> => {
|
|
41
|
+
if (truncated) return;
|
|
42
|
+
|
|
43
|
+
const entries = await readdir(directory, { withFileTypes: true }).catch(() => []);
|
|
44
|
+
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
45
|
+
if (truncated) return;
|
|
46
|
+
const childRelative = relative === "" ? entry.name : `${relative}/${entry.name}`;
|
|
47
|
+
|
|
48
|
+
if (entry.isDirectory()) {
|
|
49
|
+
if (NOISY_DIRECTORIES.has(entry.name) && !pattern.includes(entry.name)) continue;
|
|
50
|
+
if (!couldMatchInside(pattern, childRelative)) continue;
|
|
51
|
+
await visit(join(directory, entry.name), childRelative);
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (!matchGlob(pattern, childRelative)) continue;
|
|
56
|
+
if (found.length >= limit) {
|
|
57
|
+
truncated = true;
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
found.push(displayPath(context.cwd, join(directory, entry.name)));
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
await visit(base, "");
|
|
65
|
+
|
|
66
|
+
return {
|
|
67
|
+
pattern: input.pattern,
|
|
68
|
+
base: displayPath(context.cwd, base),
|
|
69
|
+
files: found,
|
|
70
|
+
truncated,
|
|
71
|
+
};
|
|
72
|
+
},
|
|
73
|
+
describeResult: (output) =>
|
|
74
|
+
`${String(output.files.length)} files${output.truncated ? ", truncated" : ""}`,
|
|
75
|
+
});
|