@puku-ai/sdk 2.0.2 → 2.0.3
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 +45 -0
- package/dist/helpers/beta/json-schema.d.mts +13 -3
- package/dist/helpers/beta/json-schema.d.ts.map +1 -1
- package/dist/helpers/beta/json-schema.js +10 -6
- package/dist/helpers/beta/json-schema.js.map +1 -1
- package/dist/helpers/beta/json-schema.mjs +10 -6
- package/dist/helpers/beta/json-schema.mjs.map +1 -1
- package/dist/internal/utils/promise.d.mts +11 -0
- package/dist/internal/utils/promise.d.ts.map +1 -0
- package/dist/internal/utils/promise.js +18 -0
- package/dist/internal/utils/promise.js.map +1 -0
- package/dist/internal/utils/promise.mjs +15 -0
- package/dist/internal/utils/promise.mjs.map +1 -0
- package/dist/lib/tools/BetaRunnableTool.d.mts +46 -1
- package/dist/lib/tools/BetaRunnableTool.d.ts.map +1 -1
- package/dist/lib/tools/BetaRunnableTool.js +26 -0
- package/dist/lib/tools/BetaRunnableTool.js.map +1 -1
- package/dist/lib/tools/BetaRunnableTool.mjs +24 -1
- package/dist/lib/tools/BetaRunnableTool.mjs.map +1 -1
- package/dist/tools/agent-toolset/fs-util.d.mts +50 -0
- package/dist/tools/agent-toolset/fs-util.d.ts.map +1 -0
- package/dist/tools/agent-toolset/fs-util.js +191 -0
- package/dist/tools/agent-toolset/fs-util.js.map +1 -0
- package/dist/tools/agent-toolset/fs-util.mjs +151 -0
- package/dist/tools/agent-toolset/fs-util.mjs.map +1 -0
- package/dist/tools/agent-toolset/node.browser.d.mts +51 -0
- package/dist/tools/agent-toolset/node.browser.d.ts.map +1 -0
- package/dist/tools/agent-toolset/node.browser.js +94 -0
- package/dist/tools/agent-toolset/node.browser.js.map +1 -0
- package/dist/tools/agent-toolset/node.browser.mjs +78 -0
- package/dist/tools/agent-toolset/node.browser.mjs.map +1 -0
- package/dist/tools/agent-toolset/node.d.mts +158 -0
- package/dist/tools/agent-toolset/node.d.ts.map +1 -0
- package/dist/tools/agent-toolset/node.js +814 -0
- package/dist/tools/agent-toolset/node.js.map +1 -0
- package/dist/tools/agent-toolset/node.mjs +765 -0
- package/dist/tools/agent-toolset/node.mjs.map +1 -0
- package/dist/tools/agent-toolset/skills.d.mts +75 -0
- package/dist/tools/agent-toolset/skills.d.ts.map +1 -0
- package/dist/tools/agent-toolset/skills.js +196 -0
- package/dist/tools/agent-toolset/skills.js.map +1 -0
- package/dist/tools/agent-toolset/skills.mjs +153 -0
- package/dist/tools/agent-toolset/skills.mjs.map +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,814 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Node implementation of the `agent_toolset_20260401` tools — `bash`, `read`,
|
|
4
|
+
* `write`, `edit`, `glob`, `grep` — plus the workdir/skills
|
|
5
|
+
* {@link AgentToolContext}.
|
|
6
|
+
*
|
|
7
|
+
* This mirrors `@anthropic-ai/sdk/tools/memory/node`: it is the explicit,
|
|
8
|
+
* Node-only entry point for these implementations. Importing it pulls in
|
|
9
|
+
* `node:child_process`, `node:fs`, etc., so it is kept separate from the rest of
|
|
10
|
+
* the SDK — depending on it is an opt-in.
|
|
11
|
+
*
|
|
12
|
+
* **Node 22+ is required** for this module: the `glob` tool uses the native
|
|
13
|
+
* `fs.glob`, added in Node 22. The rest of the SDK still supports Node 18+; only
|
|
14
|
+
* the agent toolset has this requirement.
|
|
15
|
+
*
|
|
16
|
+
* The result of {@link betaAgentToolset20260401} is a plain `BetaRunnableTool[]`;
|
|
17
|
+
* hand it to any tool runner — `client.beta.messages.toolRunner({ …, tools })`
|
|
18
|
+
* for the Messages API, or `client.beta.sessions.events.toolRunner({ …, tools })`
|
|
19
|
+
* for a managed-agents session:
|
|
20
|
+
*
|
|
21
|
+
* ```ts
|
|
22
|
+
* import { betaAgentToolset20260401 } from '@anthropic-ai/sdk/tools/agent-toolset/node';
|
|
23
|
+
*
|
|
24
|
+
* const tools = betaAgentToolset20260401({ workdir: '/work' });
|
|
25
|
+
* const tools2 = betaAgentToolset20260401({ workdir: '/work' }).filter((t) => t.name !== 'bash');
|
|
26
|
+
* ```
|
|
27
|
+
*
|
|
28
|
+
* Trust model: the file tools confine to `workdir` (symlink-aware) and are safe
|
|
29
|
+
* without a sandbox; `bash` is unrestricted and should run inside one. See
|
|
30
|
+
* {@link AgentToolContext}.
|
|
31
|
+
*/
|
|
32
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
33
|
+
if (k2 === undefined) k2 = k;
|
|
34
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
35
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
36
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
37
|
+
}
|
|
38
|
+
Object.defineProperty(o, k2, desc);
|
|
39
|
+
}) : (function(o, m, k, k2) {
|
|
40
|
+
if (k2 === undefined) k2 = k;
|
|
41
|
+
o[k2] = m[k];
|
|
42
|
+
}));
|
|
43
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
44
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
45
|
+
}) : function(o, v) {
|
|
46
|
+
o["default"] = v;
|
|
47
|
+
});
|
|
48
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
49
|
+
var ownKeys = function(o) {
|
|
50
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
51
|
+
var ar = [];
|
|
52
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
53
|
+
return ar;
|
|
54
|
+
};
|
|
55
|
+
return ownKeys(o);
|
|
56
|
+
};
|
|
57
|
+
return function (mod) {
|
|
58
|
+
if (mod && mod.__esModule) return mod;
|
|
59
|
+
var result = {};
|
|
60
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
61
|
+
__setModuleDefault(result, mod);
|
|
62
|
+
return result;
|
|
63
|
+
};
|
|
64
|
+
})();
|
|
65
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
66
|
+
exports.BashSession = exports.BashTimeoutError = exports.extractSkillArchive = exports.resolveSkillVersion = exports.setupSkills = void 0;
|
|
67
|
+
exports.betaAgentToolset20260401 = betaAgentToolset20260401;
|
|
68
|
+
exports.resolvePath = resolvePath;
|
|
69
|
+
exports.betaBashTool = betaBashTool;
|
|
70
|
+
exports.betaReadTool = betaReadTool;
|
|
71
|
+
exports.betaWriteTool = betaWriteTool;
|
|
72
|
+
exports.betaEditTool = betaEditTool;
|
|
73
|
+
exports.betaGlobTool = betaGlobTool;
|
|
74
|
+
exports.betaGrepTool = betaGrepTool;
|
|
75
|
+
const fs = __importStar(require("node:fs/promises"));
|
|
76
|
+
const fssync = __importStar(require("node:fs"));
|
|
77
|
+
const path = __importStar(require("node:path"));
|
|
78
|
+
const cp = __importStar(require("node:child_process"));
|
|
79
|
+
const crypto = __importStar(require("node:crypto"));
|
|
80
|
+
const readline = __importStar(require("node:readline"));
|
|
81
|
+
const error_js_1 = require("../../core/error.js");
|
|
82
|
+
const ToolError_js_1 = require("../../lib/tools/ToolError.js");
|
|
83
|
+
const json_schema_js_1 = require("../../helpers/beta/json-schema.js");
|
|
84
|
+
const promise_js_1 = require("../../internal/utils/promise.js");
|
|
85
|
+
const fs_util_js_1 = require("./fs-util.js");
|
|
86
|
+
var skills_js_1 = require("./skills.js");
|
|
87
|
+
Object.defineProperty(exports, "setupSkills", { enumerable: true, get: function () { return skills_js_1.setupSkills; } });
|
|
88
|
+
Object.defineProperty(exports, "resolveSkillVersion", { enumerable: true, get: function () { return skills_js_1.resolveSkillVersion; } });
|
|
89
|
+
Object.defineProperty(exports, "extractSkillArchive", { enumerable: true, get: function () { return skills_js_1.extractSkillArchive; } });
|
|
90
|
+
const BASH_OUTPUT_LIMIT = 100 * 1024;
|
|
91
|
+
const BASH_DEFAULT_TIMEOUT_MS = 120_000;
|
|
92
|
+
// Default size cap for the read/edit tools (both load the whole file into
|
|
93
|
+
// memory) when AgentToolContext.maxFileBytes is unset. The reject-vs-truncate
|
|
94
|
+
// behaviour remains a separate question pending CMA validation.
|
|
95
|
+
const DEFAULT_MAX_FILE_BYTES = 256 * 1024;
|
|
96
|
+
const GREP_OUTPUT_LIMIT = 100 * 1024;
|
|
97
|
+
const GREP_MAX_LINE_LENGTH = 2000;
|
|
98
|
+
const GLOB_RESULT_LIMIT = 200;
|
|
99
|
+
/**
|
|
100
|
+
* A bash command exceeded its `timeoutMs`. Carries the timeout so a caller can
|
|
101
|
+
* tell it apart from an abort without matching on the message text.
|
|
102
|
+
*/
|
|
103
|
+
class BashTimeoutError extends error_js_1.AnthropicError {
|
|
104
|
+
timeoutMs;
|
|
105
|
+
constructor(timeoutMs) {
|
|
106
|
+
super(`bash command timed out after ${timeoutMs}ms`);
|
|
107
|
+
this.name = 'BashTimeoutError';
|
|
108
|
+
this.timeoutMs = timeoutMs;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
exports.BashTimeoutError = BashTimeoutError;
|
|
112
|
+
const ANSI_RE = /\x1b\[[0-9;?]*[ -/]*[@-~]/g;
|
|
113
|
+
const fsGlob = fs.glob;
|
|
114
|
+
function resolveMaxBytes(configured) {
|
|
115
|
+
return configured === undefined ? DEFAULT_MAX_FILE_BYTES : configured;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Returns the `agent_toolset_20260401` implementations bound to `ctx`. The
|
|
119
|
+
* result is a plain array of `BetaRunnableTool`; filter or extend it before
|
|
120
|
+
* handing it to a tool runner:
|
|
121
|
+
*
|
|
122
|
+
* ```ts
|
|
123
|
+
* const tools = [...betaAgentToolset20260401(ctx), myCustomTool];
|
|
124
|
+
* const tools = betaAgentToolset20260401(ctx).filter((t) => t.name !== 'grep');
|
|
125
|
+
* ```
|
|
126
|
+
*
|
|
127
|
+
* Concurrency note: `client.beta.sessions.events.toolRunner` dispatches a
|
|
128
|
+
* session's tool calls serially (the sessions API delivers one `agent.tool_use`
|
|
129
|
+
* at a time). `client.beta.messages.toolRunner` runs a turn's `tool.run` calls
|
|
130
|
+
* via `Promise.all`. The toolset below is safe under either model —
|
|
131
|
+
* {@link betaBashTool} serializes its persistent shell internally and the FS
|
|
132
|
+
* tools are independent per call — but {@link betaEditTool}/{@link betaWriteTool}
|
|
133
|
+
* cannot synchronize concurrent writes to the *same* file across processes, so a
|
|
134
|
+
* multi-edit turn touching one path is still subject to inherent FS lost-update
|
|
135
|
+
* races. Custom tools that close over mutable state should do their own queueing.
|
|
136
|
+
*/
|
|
137
|
+
function betaAgentToolset20260401(ctx) {
|
|
138
|
+
return [
|
|
139
|
+
betaBashTool(ctx),
|
|
140
|
+
betaReadTool(ctx),
|
|
141
|
+
betaWriteTool(ctx),
|
|
142
|
+
betaEditTool(ctx),
|
|
143
|
+
betaGlobTool(ctx),
|
|
144
|
+
betaGrepTool(ctx),
|
|
145
|
+
];
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Resolve `p` against `ctx.workdir`. Absolute and relative inputs go through
|
|
149
|
+
* the same canonicalise-then-contain check — an absolute path that lands inside
|
|
150
|
+
* the workdir is permitted, only paths that resolve *outside* are rejected.
|
|
151
|
+
* Every symlink in `p` (including the leaf, even a dangling one) is resolved
|
|
152
|
+
* before the workdir check, and the resolved path is what the tool then operates
|
|
153
|
+
* on, so a symlink inside the workdir that points outside it can neither pass
|
|
154
|
+
* the check nor be followed afterwards. See the trust model on
|
|
155
|
+
* {@link AgentToolContext}.
|
|
156
|
+
*
|
|
157
|
+
* Residual TOCTOU: a component could still be swapped for a symlink between this
|
|
158
|
+
* call and the eventual `fs` operation. Closing that fully needs per-component
|
|
159
|
+
* `O_NOFOLLOW`/`openat`, which Node does not expose ergonomically; the same
|
|
160
|
+
* residual exposure exists in `tools/memory/node` and is why a sandbox is still
|
|
161
|
+
* recommended for the toolset as a whole.
|
|
162
|
+
*/
|
|
163
|
+
function resolvePath(ctx, p) {
|
|
164
|
+
return (0, fs_util_js_1.confineToRoot)(ctx.workdir, p, { allowOutside: ctx.unrestrictedPaths ?? false });
|
|
165
|
+
}
|
|
166
|
+
// ---- bash ----------------------------------------------------------------
|
|
167
|
+
/**
|
|
168
|
+
* Build the environment for the spawned bash shell. The runner process holds
|
|
169
|
+
* Anthropic credentials in `ANTHROPIC_*` env vars — the API key, the auth token,
|
|
170
|
+
* and the per-work session token among them. `bash` runs an unrestricted shell,
|
|
171
|
+
* so any command the agent runs could read those straight out of `process.env`;
|
|
172
|
+
* strip the whole `ANTHROPIC_*` namespace from the child's environment.
|
|
173
|
+
* Everything else (PATH, HOME, locale, …) is passed through unchanged.
|
|
174
|
+
*
|
|
175
|
+
* Passing an explicit `env` to {@link AgentToolContext} does NOT add to this
|
|
176
|
+
* default — it FULLY REPLACES it. The provided mapping becomes the entire bash
|
|
177
|
+
* environment verbatim; nothing here is merged in, so callers who want the
|
|
178
|
+
* scrubbed process environment plus extras must build that mapping themselves.
|
|
179
|
+
*/
|
|
180
|
+
function scrubbedShellEnv() {
|
|
181
|
+
const env = {};
|
|
182
|
+
for (const [key, value] of Object.entries(process.env)) {
|
|
183
|
+
if (key.startsWith('ANTHROPIC_'))
|
|
184
|
+
continue;
|
|
185
|
+
env[key] = value;
|
|
186
|
+
}
|
|
187
|
+
return env;
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* A persistent /bin/bash process. State (cwd, env, background jobs) survives
|
|
191
|
+
* across exec() calls. Uses pipes rather than a PTY so input is never echoed.
|
|
192
|
+
*/
|
|
193
|
+
class BashSession {
|
|
194
|
+
#proc;
|
|
195
|
+
#buf = '';
|
|
196
|
+
#truncated = false;
|
|
197
|
+
#closed = false;
|
|
198
|
+
// While a command is in flight, the resolver to fire once its sentinel lands
|
|
199
|
+
// in `#buf` (or once the shell dies). Event-driven: no polling loop.
|
|
200
|
+
#waiting = null;
|
|
201
|
+
constructor(dir, env = scrubbedShellEnv()) {
|
|
202
|
+
this.#proc = cp.spawn('/bin/bash', ['--noprofile', '--norc'], {
|
|
203
|
+
cwd: dir,
|
|
204
|
+
// `env` is the full base environment (the scrubbed process env by
|
|
205
|
+
// default, or the verbatim replacement from `AgentToolContext.env`).
|
|
206
|
+
// PS1/PS2/TERM are shell-control settings BashSession always applies so
|
|
207
|
+
// the pipe-based sentinel exec parsing works — not part of the
|
|
208
|
+
// user-facing environment.
|
|
209
|
+
env: { ...env, PS1: '', PS2: '', TERM: 'dumb' },
|
|
210
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
211
|
+
detached: true,
|
|
212
|
+
});
|
|
213
|
+
this.#proc.stdout.setEncoding('utf8');
|
|
214
|
+
this.#proc.stderr.setEncoding('utf8');
|
|
215
|
+
this.#proc.stdout.on('data', (d) => this.#append(d));
|
|
216
|
+
this.#proc.stderr.on('data', (d) => this.#append(d));
|
|
217
|
+
this.#proc.once('close', () => {
|
|
218
|
+
this.#closed = true;
|
|
219
|
+
// Wake any in-flight exec so it fails fast instead of waiting for its deadline.
|
|
220
|
+
const w = this.#waiting;
|
|
221
|
+
this.#waiting = null;
|
|
222
|
+
w?.resolve();
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
/** Whether the underlying shell process has exited. */
|
|
226
|
+
get closed() {
|
|
227
|
+
return this.#closed;
|
|
228
|
+
}
|
|
229
|
+
// Cap the buffer during accumulation so a command that streams unboundedly
|
|
230
|
+
// can't OOM the runner. Keeps the tail so the sentinel stays detectable.
|
|
231
|
+
// Also resolves the in-flight exec the instant its sentinel is buffered.
|
|
232
|
+
#append(d) {
|
|
233
|
+
this.#buf += d;
|
|
234
|
+
if (this.#buf.length > BASH_OUTPUT_LIMIT) {
|
|
235
|
+
this.#buf = this.#buf.slice(this.#buf.length - BASH_OUTPUT_LIMIT);
|
|
236
|
+
this.#truncated = true;
|
|
237
|
+
}
|
|
238
|
+
if (this.#waiting && this.#buf.indexOf(this.#waiting.sentinel) >= 0) {
|
|
239
|
+
const w = this.#waiting;
|
|
240
|
+
this.#waiting = null;
|
|
241
|
+
w.resolve();
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
async exec(command, opts = {}) {
|
|
245
|
+
if (this.#closed) {
|
|
246
|
+
throw new error_js_1.AnthropicError('bash session terminated');
|
|
247
|
+
}
|
|
248
|
+
const timeoutMs = opts.timeoutMs ?? BASH_DEFAULT_TIMEOUT_MS;
|
|
249
|
+
const signal = opts.signal;
|
|
250
|
+
// Reject with the signal's own reason, so a caller telling a user cancel
|
|
251
|
+
// apart from an `AbortSignal.timeout()` sees the platform's name intact.
|
|
252
|
+
signal?.throwIfAborted();
|
|
253
|
+
this.#buf = '';
|
|
254
|
+
this.#truncated = false;
|
|
255
|
+
// Per-call nonce so a command that prints a fixed marker can't spoof the
|
|
256
|
+
// exit-code framing. The `''` split keeps the literal out of what we write
|
|
257
|
+
// to stdin — only the shell's printf reassembles it.
|
|
258
|
+
const sentinel = `__ANT_CMD_${crypto.randomUUID()}_DONE__`;
|
|
259
|
+
const sentinelSplit = `${sentinel.slice(0, 8)}''${sentinel.slice(8)}`;
|
|
260
|
+
// </dev/null: a stdin-reading command (`cat`, `read`) gets EOF instead of
|
|
261
|
+
// blocking on the shared pipe until the timeout.
|
|
262
|
+
const wrapped = `{ ${command}\n} </dev/null 2>&1; printf '\\n${sentinelSplit}%d\\n' $?\n`;
|
|
263
|
+
this.#proc.stdin.write(wrapped);
|
|
264
|
+
if (this.#buf.indexOf(sentinel) < 0) {
|
|
265
|
+
// Park until the sentinel lands, the deadline passes, the caller aborts,
|
|
266
|
+
// or the shell dies — whichever comes first. `#append` (and the `close`
|
|
267
|
+
// handler) resolve `sentinelSeen`; the deadline / abort reject.
|
|
268
|
+
const { promise: sentinelSeen, resolve } = (0, promise_js_1.promiseWithResolvers)();
|
|
269
|
+
this.#waiting = { sentinel, resolve };
|
|
270
|
+
let timer;
|
|
271
|
+
let onAbort;
|
|
272
|
+
try {
|
|
273
|
+
await Promise.race([
|
|
274
|
+
sentinelSeen,
|
|
275
|
+
new Promise((_, reject) => {
|
|
276
|
+
timer = setTimeout(() => reject(new BashTimeoutError(timeoutMs)), timeoutMs);
|
|
277
|
+
}),
|
|
278
|
+
new Promise((_, reject) => {
|
|
279
|
+
if (!signal)
|
|
280
|
+
return;
|
|
281
|
+
onAbort = () => reject(signal.reason);
|
|
282
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
283
|
+
}),
|
|
284
|
+
]);
|
|
285
|
+
}
|
|
286
|
+
finally {
|
|
287
|
+
if (timer)
|
|
288
|
+
clearTimeout(timer);
|
|
289
|
+
if (onAbort && signal)
|
|
290
|
+
signal.removeEventListener('abort', onAbort);
|
|
291
|
+
this.#waiting = null;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
const idx = this.#buf.indexOf(sentinel);
|
|
295
|
+
if (idx < 0) {
|
|
296
|
+
// The shell closed (or was killed) before emitting the sentinel.
|
|
297
|
+
throw new error_js_1.AnthropicError('bash session terminated');
|
|
298
|
+
}
|
|
299
|
+
const tail = this.#buf.slice(idx + sentinel.length);
|
|
300
|
+
const m = tail.match(/^(-?\d+)/);
|
|
301
|
+
const exitCode = m ? parseInt(m[1], 10) : -1;
|
|
302
|
+
let out = this.#buf.slice(0, idx).replace(ANSI_RE, '').replace(/\n+$/, '');
|
|
303
|
+
if (this.#truncated) {
|
|
304
|
+
out = `[output truncated]\n${out}`;
|
|
305
|
+
}
|
|
306
|
+
return { output: out, exitCode };
|
|
307
|
+
}
|
|
308
|
+
close() {
|
|
309
|
+
if (this.#closed)
|
|
310
|
+
return;
|
|
311
|
+
this.#closed = true;
|
|
312
|
+
const w = this.#waiting;
|
|
313
|
+
this.#waiting = null;
|
|
314
|
+
w?.resolve();
|
|
315
|
+
this.#proc.stdout.destroy();
|
|
316
|
+
this.#proc.stderr.destroy();
|
|
317
|
+
this.#proc.stdin.destroy();
|
|
318
|
+
try {
|
|
319
|
+
// Negative PID targets the process group so foreground jobs (e.g. a
|
|
320
|
+
// hung sleep) die with the shell.
|
|
321
|
+
process.kill(-this.#proc.pid, 'SIGKILL');
|
|
322
|
+
}
|
|
323
|
+
catch {
|
|
324
|
+
this.#proc.kill('SIGKILL');
|
|
325
|
+
}
|
|
326
|
+
this.#proc.unref();
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
exports.BashSession = BashSession;
|
|
330
|
+
function betaBashTool(ctx) {
|
|
331
|
+
let session;
|
|
332
|
+
// Concurrent run() callers chain onto this promise so writes to the shared
|
|
333
|
+
// shell's stdin can't interleave (which would corrupt the sentinel-match
|
|
334
|
+
// exit-code parsing in BashSession.exec). Each call replaces `tail` with a
|
|
335
|
+
// promise that resolves only after its own exec settles.
|
|
336
|
+
let tail = Promise.resolve();
|
|
337
|
+
return (0, json_schema_js_1.betaTool)({
|
|
338
|
+
name: 'bash',
|
|
339
|
+
description: 'Run a bash command in a persistent shell. State (cwd, env vars) persists across calls.',
|
|
340
|
+
inputSchema: {
|
|
341
|
+
type: 'object',
|
|
342
|
+
properties: {
|
|
343
|
+
command: { type: 'string', description: 'The command to run' },
|
|
344
|
+
restart: { type: 'boolean', description: 'Restart the persistent shell before running' },
|
|
345
|
+
timeout_ms: { type: 'integer', description: 'Per-call timeout in milliseconds' },
|
|
346
|
+
},
|
|
347
|
+
},
|
|
348
|
+
run: async ({ command, restart, timeout_ms }, context) => {
|
|
349
|
+
const prev = tail;
|
|
350
|
+
const gate = (0, promise_js_1.promiseWithResolvers)();
|
|
351
|
+
tail = gate.promise;
|
|
352
|
+
// Swallow prior rejections — earlier callers got their own error path;
|
|
353
|
+
// we just need to wait for the shell to be free.
|
|
354
|
+
try {
|
|
355
|
+
await prev;
|
|
356
|
+
}
|
|
357
|
+
catch {
|
|
358
|
+
// ignore
|
|
359
|
+
}
|
|
360
|
+
try {
|
|
361
|
+
if (restart) {
|
|
362
|
+
session?.close();
|
|
363
|
+
session = undefined;
|
|
364
|
+
}
|
|
365
|
+
if (!command) {
|
|
366
|
+
if (restart)
|
|
367
|
+
return 'bash session restarted';
|
|
368
|
+
throw new ToolError_js_1.ToolError('bash: command is required');
|
|
369
|
+
}
|
|
370
|
+
session ??= new BashSession(ctx.workdir, ctx.env);
|
|
371
|
+
try {
|
|
372
|
+
const { output, exitCode } = await session.exec(command, {
|
|
373
|
+
timeoutMs: timeout_ms ?? BASH_DEFAULT_TIMEOUT_MS,
|
|
374
|
+
signal: context?.signal,
|
|
375
|
+
});
|
|
376
|
+
if (exitCode !== 0)
|
|
377
|
+
throw new ToolError_js_1.ToolError(output || `exit ${exitCode}`);
|
|
378
|
+
return output;
|
|
379
|
+
}
|
|
380
|
+
catch (e) {
|
|
381
|
+
if (e instanceof ToolError_js_1.ToolError)
|
|
382
|
+
throw e;
|
|
383
|
+
// Timeout, abort, or terminated: the still-running command will emit
|
|
384
|
+
// a stale sentinel, so discard this session and let the next call
|
|
385
|
+
// start fresh.
|
|
386
|
+
session.close();
|
|
387
|
+
session = undefined;
|
|
388
|
+
throw new ToolError_js_1.ToolError(`bash: ${e instanceof Error ? e.message : String(e)}`);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
finally {
|
|
392
|
+
gate.resolve();
|
|
393
|
+
}
|
|
394
|
+
},
|
|
395
|
+
close: () => {
|
|
396
|
+
session?.close();
|
|
397
|
+
session = undefined;
|
|
398
|
+
},
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
// ---- fs ------------------------------------------------------------------
|
|
402
|
+
function betaReadTool(ctx) {
|
|
403
|
+
return (0, json_schema_js_1.betaTool)({
|
|
404
|
+
name: 'read',
|
|
405
|
+
description: 'Read a UTF-8 text file relative to the workdir.',
|
|
406
|
+
inputSchema: {
|
|
407
|
+
type: 'object',
|
|
408
|
+
properties: {
|
|
409
|
+
file_path: { type: 'string' },
|
|
410
|
+
view_range: {
|
|
411
|
+
type: 'array',
|
|
412
|
+
items: { type: 'integer' },
|
|
413
|
+
description: '[start_line, end_line] 1-indexed inclusive',
|
|
414
|
+
},
|
|
415
|
+
},
|
|
416
|
+
required: ['file_path'],
|
|
417
|
+
},
|
|
418
|
+
run: async ({ file_path, view_range }) => {
|
|
419
|
+
if (!file_path)
|
|
420
|
+
throw new ToolError_js_1.ToolError('read: file_path is required');
|
|
421
|
+
const abs = await resolvePath(ctx, file_path);
|
|
422
|
+
let data;
|
|
423
|
+
try {
|
|
424
|
+
// stat() before any open(): the size cap stops a multi-GB file from
|
|
425
|
+
// OOM'ing the runner, and isFile() rejects FIFOs/devices/dirs without
|
|
426
|
+
// opening them (open() on an unconnected FIFO blocks indefinitely).
|
|
427
|
+
const st = await fs.stat(abs);
|
|
428
|
+
if (!st.isFile()) {
|
|
429
|
+
throw new ToolError_js_1.ToolError(`read: ${file_path} is not a regular file`);
|
|
430
|
+
}
|
|
431
|
+
const limit = resolveMaxBytes(ctx.maxFileBytes);
|
|
432
|
+
if (limit !== null && st.size > limit) {
|
|
433
|
+
throw new ToolError_js_1.ToolError(`read: ${file_path} is ${st.size} bytes, exceeds ${limit}-byte limit. ` +
|
|
434
|
+
'Use bash (head/tail/sed) to read a slice.');
|
|
435
|
+
}
|
|
436
|
+
data = await fs.readFile(abs, 'utf8');
|
|
437
|
+
}
|
|
438
|
+
catch (e) {
|
|
439
|
+
if (e instanceof ToolError_js_1.ToolError)
|
|
440
|
+
throw e;
|
|
441
|
+
throw new ToolError_js_1.ToolError(`read: ${(0, fs_util_js_1.fsErrorMessage)(e, file_path)}`);
|
|
442
|
+
}
|
|
443
|
+
if (!view_range)
|
|
444
|
+
return data;
|
|
445
|
+
if (view_range.length !== 2)
|
|
446
|
+
throw new ToolError_js_1.ToolError('read: view_range must be [start_line, end_line]');
|
|
447
|
+
const [startLine, endLine] = view_range;
|
|
448
|
+
const lines = data.split('\n');
|
|
449
|
+
const start = Math.max(0, startLine - 1);
|
|
450
|
+
const end = endLine > 0 ? endLine : lines.length;
|
|
451
|
+
return lines.slice(start, end).join('\n');
|
|
452
|
+
},
|
|
453
|
+
});
|
|
454
|
+
}
|
|
455
|
+
function betaWriteTool(ctx) {
|
|
456
|
+
return (0, json_schema_js_1.betaTool)({
|
|
457
|
+
name: 'write',
|
|
458
|
+
description: 'Write a UTF-8 text file relative to the workdir, creating parent directories as needed.',
|
|
459
|
+
inputSchema: {
|
|
460
|
+
type: 'object',
|
|
461
|
+
properties: { file_path: { type: 'string' }, content: { type: 'string' } },
|
|
462
|
+
required: ['file_path', 'content'],
|
|
463
|
+
},
|
|
464
|
+
run: async ({ file_path, content }) => {
|
|
465
|
+
if (!file_path)
|
|
466
|
+
throw new ToolError_js_1.ToolError('write: file_path is required');
|
|
467
|
+
const abs = await resolvePath(ctx, file_path);
|
|
468
|
+
try {
|
|
469
|
+
await fs.mkdir(path.dirname(abs), { recursive: true, mode: fs_util_js_1.DIR_CREATE_MODE });
|
|
470
|
+
await (0, fs_util_js_1.atomicWriteFile)(abs, content ?? '');
|
|
471
|
+
}
|
|
472
|
+
catch (e) {
|
|
473
|
+
throw new ToolError_js_1.ToolError(`write: ${(0, fs_util_js_1.fsErrorMessage)(e, file_path)}`);
|
|
474
|
+
}
|
|
475
|
+
return `wrote ${Buffer.byteLength(content ?? '')} bytes to ${file_path}`;
|
|
476
|
+
},
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
function betaEditTool(ctx) {
|
|
480
|
+
return (0, json_schema_js_1.betaTool)({
|
|
481
|
+
name: 'edit',
|
|
482
|
+
description: 'Replace old_string with new_string in a file. old_string must be unique unless replace_all.',
|
|
483
|
+
inputSchema: {
|
|
484
|
+
type: 'object',
|
|
485
|
+
properties: {
|
|
486
|
+
file_path: { type: 'string' },
|
|
487
|
+
old_string: { type: 'string' },
|
|
488
|
+
new_string: { type: 'string' },
|
|
489
|
+
replace_all: { type: 'boolean' },
|
|
490
|
+
},
|
|
491
|
+
required: ['file_path', 'old_string', 'new_string'],
|
|
492
|
+
},
|
|
493
|
+
run: async ({ file_path, old_string, new_string, replace_all }) => {
|
|
494
|
+
if (!file_path)
|
|
495
|
+
throw new ToolError_js_1.ToolError('edit: file_path is required');
|
|
496
|
+
if (!old_string)
|
|
497
|
+
throw new ToolError_js_1.ToolError('edit: old_string is required');
|
|
498
|
+
const abs = await resolvePath(ctx, file_path);
|
|
499
|
+
let data;
|
|
500
|
+
try {
|
|
501
|
+
// stat() before any open() — same guard as `read`: the size cap stops a
|
|
502
|
+
// multi-GB file from OOM'ing the runner, and isFile() rejects
|
|
503
|
+
// FIFOs/devices/dirs without opening them (open() on an unconnected FIFO
|
|
504
|
+
// blocks indefinitely). The edit path is model-controlled, so it needs
|
|
505
|
+
// the same bound `read` already has.
|
|
506
|
+
const st = await fs.stat(abs);
|
|
507
|
+
if (!st.isFile()) {
|
|
508
|
+
throw new ToolError_js_1.ToolError(`edit: ${file_path} is not a regular file`);
|
|
509
|
+
}
|
|
510
|
+
const limit = resolveMaxBytes(ctx.maxFileBytes);
|
|
511
|
+
if (limit !== null && st.size > limit) {
|
|
512
|
+
throw new ToolError_js_1.ToolError(`edit: ${file_path} is ${st.size} bytes, exceeds ${limit}-byte limit. ` +
|
|
513
|
+
'Use bash (sed/awk) to edit a large file.');
|
|
514
|
+
}
|
|
515
|
+
data = await fs.readFile(abs, 'utf8');
|
|
516
|
+
}
|
|
517
|
+
catch (e) {
|
|
518
|
+
if (e instanceof ToolError_js_1.ToolError)
|
|
519
|
+
throw e;
|
|
520
|
+
throw new ToolError_js_1.ToolError(`edit: ${(0, fs_util_js_1.fsErrorMessage)(e, file_path)}`);
|
|
521
|
+
}
|
|
522
|
+
const count = data.split(old_string).length - 1;
|
|
523
|
+
if (count === 0)
|
|
524
|
+
throw new ToolError_js_1.ToolError(`edit: old_string not found in ${file_path}`);
|
|
525
|
+
let updated;
|
|
526
|
+
if (replace_all) {
|
|
527
|
+
updated = data.split(old_string).join(new_string);
|
|
528
|
+
}
|
|
529
|
+
else {
|
|
530
|
+
if (count > 1)
|
|
531
|
+
throw new ToolError_js_1.ToolError(`edit: old_string appears ${count} times in ${file_path} (must be unique)`);
|
|
532
|
+
// Callback form so `$&`/`$1`/`` $` `` in new_string are inserted
|
|
533
|
+
// literally instead of expanded as replacement patterns.
|
|
534
|
+
updated = data.replace(old_string, () => new_string);
|
|
535
|
+
}
|
|
536
|
+
try {
|
|
537
|
+
await (0, fs_util_js_1.atomicWriteFile)(abs, updated);
|
|
538
|
+
}
|
|
539
|
+
catch (e) {
|
|
540
|
+
throw new ToolError_js_1.ToolError(`edit: write: ${(0, fs_util_js_1.fsErrorMessage)(e, file_path)}`);
|
|
541
|
+
}
|
|
542
|
+
return `edited ${file_path} (${replace_all ? count : 1} replacement(s))`;
|
|
543
|
+
},
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
// ---- search --------------------------------------------------------------
|
|
547
|
+
function betaGlobTool(ctx) {
|
|
548
|
+
return (0, json_schema_js_1.betaTool)({
|
|
549
|
+
name: 'glob',
|
|
550
|
+
description: 'Match files under the workdir against a glob pattern. Results are mtime-sorted, newest first.',
|
|
551
|
+
inputSchema: {
|
|
552
|
+
type: 'object',
|
|
553
|
+
properties: {
|
|
554
|
+
pattern: { type: 'string' },
|
|
555
|
+
path: { type: 'string', description: 'Directory to search in. Defaults to the workdir.' },
|
|
556
|
+
},
|
|
557
|
+
required: ['pattern'],
|
|
558
|
+
},
|
|
559
|
+
run: async ({ pattern, path: searchPath }) => {
|
|
560
|
+
if (!pattern)
|
|
561
|
+
throw new ToolError_js_1.ToolError('glob: pattern is required');
|
|
562
|
+
let root = path.resolve(ctx.workdir);
|
|
563
|
+
let pat = pattern;
|
|
564
|
+
if (path.isAbsolute(pattern)) {
|
|
565
|
+
if (!ctx.unrestrictedPaths)
|
|
566
|
+
throw new ToolError_js_1.ToolError('glob: absolute pattern not permitted');
|
|
567
|
+
root = path.parse(pattern).root;
|
|
568
|
+
pat = path.relative(root, pattern);
|
|
569
|
+
}
|
|
570
|
+
else if (searchPath) {
|
|
571
|
+
root = await resolvePath(ctx, searchPath);
|
|
572
|
+
}
|
|
573
|
+
// A `..` in the *pattern itself* (e.g. `../../*`) walks `fs.glob` out of
|
|
574
|
+
// the search root — this is separate from the `searchPath` confinement
|
|
575
|
+
// above, which only covers the path argument. Reject it outright when the
|
|
576
|
+
// toolset is confined.
|
|
577
|
+
if (!ctx.unrestrictedPaths && pat.split(/[\\/]/).includes('..')) {
|
|
578
|
+
throw new ToolError_js_1.ToolError('glob: ".." is not permitted in the pattern');
|
|
579
|
+
}
|
|
580
|
+
// Compare canonical against canonical: a workdir that is itself a
|
|
581
|
+
// symlink would otherwise falsely reject every realpath'd match below.
|
|
582
|
+
const realRoot = ctx.unrestrictedPaths ? root : await fs.realpath(root).catch(() => root);
|
|
583
|
+
const matches = [];
|
|
584
|
+
try {
|
|
585
|
+
// Native `fs.glob` (Node 22+). `exclude` prunes the noisy dirs the
|
|
586
|
+
// legacy walker skipped; only regular files are collected.
|
|
587
|
+
for await (const entry of fsGlob(pat, {
|
|
588
|
+
cwd: root,
|
|
589
|
+
withFileTypes: true,
|
|
590
|
+
exclude: (d) => d.name === '.git' || d.name === 'node_modules',
|
|
591
|
+
})) {
|
|
592
|
+
if (!entry.isFile())
|
|
593
|
+
continue;
|
|
594
|
+
const full = path.join(entry.parentPath, entry.name);
|
|
595
|
+
// Drop any match that resolves outside the search root. A pattern
|
|
596
|
+
// that *names* a symlinked directory (the model controls the
|
|
597
|
+
// pattern, and the bash tool in the same session can plant the
|
|
598
|
+
// link) makes `fs.glob` descend through it and report entries with
|
|
599
|
+
// the raw parent path, so a lexical check on `full` alone would
|
|
600
|
+
// pass `root/link_out/secret` even though it lives outside the
|
|
601
|
+
// jail. Resolve-failure (ELOOP, EACCES, a racing unlink) is a deny.
|
|
602
|
+
if (!ctx.unrestrictedPaths) {
|
|
603
|
+
let real;
|
|
604
|
+
try {
|
|
605
|
+
real = await fs.realpath(full);
|
|
606
|
+
}
|
|
607
|
+
catch {
|
|
608
|
+
continue;
|
|
609
|
+
}
|
|
610
|
+
if (!isWithin(realRoot, real))
|
|
611
|
+
continue;
|
|
612
|
+
}
|
|
613
|
+
let mtime = 0;
|
|
614
|
+
try {
|
|
615
|
+
mtime = (await fs.stat(full)).mtimeMs;
|
|
616
|
+
}
|
|
617
|
+
catch {
|
|
618
|
+
// unreadable — keep it in the list with mtime 0
|
|
619
|
+
}
|
|
620
|
+
matches.push({ path: full, mtime });
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
catch (e) {
|
|
624
|
+
throw new ToolError_js_1.ToolError(`glob: ${e instanceof Error ? e.message : String(e)}`);
|
|
625
|
+
}
|
|
626
|
+
if (matches.length === 0)
|
|
627
|
+
return 'no matches';
|
|
628
|
+
matches.sort((a, b) => b.mtime - a.mtime);
|
|
629
|
+
return matches
|
|
630
|
+
.slice(0, GLOB_RESULT_LIMIT)
|
|
631
|
+
.map((m) => m.path)
|
|
632
|
+
.join('\n');
|
|
633
|
+
},
|
|
634
|
+
});
|
|
635
|
+
}
|
|
636
|
+
function betaGrepTool(ctx) {
|
|
637
|
+
return (0, json_schema_js_1.betaTool)({
|
|
638
|
+
name: 'grep',
|
|
639
|
+
description: 'Search file contents for a regex. Uses ripgrep if available, otherwise a built-in walker.',
|
|
640
|
+
inputSchema: {
|
|
641
|
+
type: 'object',
|
|
642
|
+
properties: { pattern: { type: 'string' }, path: { type: 'string' } },
|
|
643
|
+
required: ['pattern'],
|
|
644
|
+
},
|
|
645
|
+
run: async ({ pattern, path: p }, context) => {
|
|
646
|
+
if (!pattern)
|
|
647
|
+
throw new ToolError_js_1.ToolError('grep: pattern is required');
|
|
648
|
+
let searchPath = path.resolve(ctx.workdir);
|
|
649
|
+
if (p)
|
|
650
|
+
searchPath = await resolvePath(ctx, p);
|
|
651
|
+
const rg = await findRg();
|
|
652
|
+
return rg ?
|
|
653
|
+
runRipgrep(rg, pattern, searchPath, context?.signal)
|
|
654
|
+
: runWalkGrep(pattern, searchPath, context?.signal);
|
|
655
|
+
},
|
|
656
|
+
});
|
|
657
|
+
}
|
|
658
|
+
function runRipgrep(rg, pattern, searchPath, signal) {
|
|
659
|
+
return new Promise((resolve, reject) => {
|
|
660
|
+
const proc = cp.spawn(rg, ['-n', '--no-heading', '-e', pattern, '--', searchPath], {
|
|
661
|
+
...(signal ? { signal } : {}),
|
|
662
|
+
});
|
|
663
|
+
let out = '';
|
|
664
|
+
let errOut = '';
|
|
665
|
+
let truncated = false;
|
|
666
|
+
proc.stdout.on('data', (d) => {
|
|
667
|
+
if (truncated)
|
|
668
|
+
return;
|
|
669
|
+
out += d;
|
|
670
|
+
if (out.length > GREP_OUTPUT_LIMIT) {
|
|
671
|
+
truncated = true;
|
|
672
|
+
out = out.slice(0, GREP_OUTPUT_LIMIT);
|
|
673
|
+
proc.kill('SIGKILL');
|
|
674
|
+
}
|
|
675
|
+
});
|
|
676
|
+
proc.stderr.on('data', (d) => (errOut += d));
|
|
677
|
+
proc.on('close', (code) => {
|
|
678
|
+
if (signal?.aborted)
|
|
679
|
+
return reject(new ToolError_js_1.ToolError('grep: aborted'));
|
|
680
|
+
if (truncated)
|
|
681
|
+
return resolve(out + `\n[output truncated at ${GREP_OUTPUT_LIMIT} bytes]`);
|
|
682
|
+
if (code === 0)
|
|
683
|
+
return resolve(out);
|
|
684
|
+
if (code === 1)
|
|
685
|
+
return resolve('no matches');
|
|
686
|
+
reject(new ToolError_js_1.ToolError(`grep: rg failed: ${errOut || `exit ${code}`}`));
|
|
687
|
+
});
|
|
688
|
+
proc.on('error', (e) => {
|
|
689
|
+
if (signal?.aborted)
|
|
690
|
+
return reject(new ToolError_js_1.ToolError('grep: aborted'));
|
|
691
|
+
reject(new ToolError_js_1.ToolError(`grep: rg failed: ${e.message}`));
|
|
692
|
+
});
|
|
693
|
+
});
|
|
694
|
+
}
|
|
695
|
+
async function runWalkGrep(pattern, root, signal) {
|
|
696
|
+
let re;
|
|
697
|
+
try {
|
|
698
|
+
re = new RegExp(pattern);
|
|
699
|
+
}
|
|
700
|
+
catch (e) {
|
|
701
|
+
throw new ToolError_js_1.ToolError(`grep: invalid regex: ${e instanceof Error ? e.message : String(e)}`);
|
|
702
|
+
}
|
|
703
|
+
const hits = [];
|
|
704
|
+
let budget = GREP_OUTPUT_LIMIT;
|
|
705
|
+
const push = (line) => {
|
|
706
|
+
budget -= line.length + 1;
|
|
707
|
+
if (budget < 0) {
|
|
708
|
+
hits.push(`[output truncated at ${GREP_OUTPUT_LIMIT} bytes]`);
|
|
709
|
+
return false;
|
|
710
|
+
}
|
|
711
|
+
hits.push(line);
|
|
712
|
+
return true;
|
|
713
|
+
};
|
|
714
|
+
const stat = await fs.stat(root).catch(() => null);
|
|
715
|
+
if (stat?.isFile()) {
|
|
716
|
+
await grepFile(root, re, push);
|
|
717
|
+
}
|
|
718
|
+
else {
|
|
719
|
+
await walk(root, '', (rel) => grepFile(path.join(root, rel), re, push), signal);
|
|
720
|
+
}
|
|
721
|
+
if (signal?.aborted)
|
|
722
|
+
throw new ToolError_js_1.ToolError('grep: aborted');
|
|
723
|
+
if (hits.length === 0)
|
|
724
|
+
return 'no matches';
|
|
725
|
+
return hits.join('\n');
|
|
726
|
+
}
|
|
727
|
+
async function grepFile(file, re, push) {
|
|
728
|
+
const stream = fssync.createReadStream(file, { encoding: 'utf8' });
|
|
729
|
+
const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
|
|
730
|
+
let i = 0;
|
|
731
|
+
try {
|
|
732
|
+
for await (const line of rl) {
|
|
733
|
+
i++;
|
|
734
|
+
// Cap line length: `pattern` is model-supplied and JS regexes backtrack,
|
|
735
|
+
// so a pathological pattern against a very long line is a ReDoS.
|
|
736
|
+
if (line.length > GREP_MAX_LINE_LENGTH)
|
|
737
|
+
continue;
|
|
738
|
+
if (re.test(line) && !push(`${file}:${i}:${line}`))
|
|
739
|
+
return false;
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
catch {
|
|
743
|
+
// unreadable / binary
|
|
744
|
+
}
|
|
745
|
+
finally {
|
|
746
|
+
stream.destroy();
|
|
747
|
+
}
|
|
748
|
+
return true;
|
|
749
|
+
}
|
|
750
|
+
// ---- utils ---------------------------------------------------------------
|
|
751
|
+
/** True when `p` is `root` itself or lexically contained within it. */
|
|
752
|
+
function isWithin(root, p) {
|
|
753
|
+
const rel = path.relative(root, p);
|
|
754
|
+
return rel === '' || (!rel.startsWith('..' + path.sep) && rel !== '..' && !path.isAbsolute(rel));
|
|
755
|
+
}
|
|
756
|
+
const WALK_MAX_DEPTH = 40;
|
|
757
|
+
const WALK_MAX_ENTRIES = 50_000;
|
|
758
|
+
/**
|
|
759
|
+
* Bounded recursive walk. `fn` may return `false` to abort. Only real
|
|
760
|
+
* directories are descended into and only real files are handed to `fn` —
|
|
761
|
+
* symlinks (and devices/fifos/sockets) are skipped entirely so a symlink inside
|
|
762
|
+
* the root cannot be followed out of it.
|
|
763
|
+
*/
|
|
764
|
+
async function walk(root, rel, fn, signal) {
|
|
765
|
+
let remaining = WALK_MAX_ENTRIES;
|
|
766
|
+
async function inner(rel, depth) {
|
|
767
|
+
if (depth > WALK_MAX_DEPTH)
|
|
768
|
+
return true;
|
|
769
|
+
if (signal?.aborted)
|
|
770
|
+
return false;
|
|
771
|
+
let entries;
|
|
772
|
+
try {
|
|
773
|
+
entries = await fs.readdir(path.join(root, rel), { withFileTypes: true });
|
|
774
|
+
}
|
|
775
|
+
catch {
|
|
776
|
+
return true;
|
|
777
|
+
}
|
|
778
|
+
for (const e of entries) {
|
|
779
|
+
if (e.name === '.git' || e.name === 'node_modules')
|
|
780
|
+
continue;
|
|
781
|
+
if (remaining-- <= 0)
|
|
782
|
+
return false;
|
|
783
|
+
if (signal?.aborted)
|
|
784
|
+
return false;
|
|
785
|
+
const childRel = rel ? path.join(rel, e.name) : e.name;
|
|
786
|
+
if (e.isDirectory()) {
|
|
787
|
+
if (!(await inner(childRel, depth + 1)))
|
|
788
|
+
return false;
|
|
789
|
+
}
|
|
790
|
+
else if (e.isFile()) {
|
|
791
|
+
if ((await fn(childRel)) === false)
|
|
792
|
+
return false;
|
|
793
|
+
}
|
|
794
|
+
// Symlinks, devices, fifos and sockets are intentionally skipped.
|
|
795
|
+
}
|
|
796
|
+
return true;
|
|
797
|
+
}
|
|
798
|
+
await inner(rel, 0);
|
|
799
|
+
}
|
|
800
|
+
async function findRg() {
|
|
801
|
+
const dirs = (process.env['PATH'] ?? '').split(path.delimiter);
|
|
802
|
+
for (const d of dirs) {
|
|
803
|
+
const candidate = path.join(d, 'rg');
|
|
804
|
+
try {
|
|
805
|
+
await fs.access(candidate, fssync.constants.X_OK);
|
|
806
|
+
return candidate;
|
|
807
|
+
}
|
|
808
|
+
catch {
|
|
809
|
+
// not here
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
return null;
|
|
813
|
+
}
|
|
814
|
+
//# sourceMappingURL=node.js.map
|