fascicle 0.14.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -0
- package/dist/acp.d.ts +8 -1
- package/dist/acp.js +62 -29
- package/dist/acp.js.map +1 -1
- package/dist/agents.d.ts +1 -1
- package/dist/{engine-BDWB2jdn.js → engine-ha9xmgwE.js} +520 -454
- package/dist/engine-ha9xmgwE.js.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/{invoke-tjTjZLHj.js → invoke-px31fffH.js} +96 -25
- package/dist/invoke-px31fffH.js.map +1 -0
- package/dist/{json_schema_to_standard-r21kW2LI.js → json_schema_to_standard-BTWD0J6p.js} +3 -21
- package/dist/json_schema_to_standard-BTWD0J6p.js.map +1 -0
- package/dist/{leading_system-BQe_405V.js → leading_system-DfJLqpGi.js} +256 -2
- package/dist/leading_system-DfJLqpGi.js.map +1 -0
- package/dist/mcp.d.ts +4 -4
- package/dist/mcp.js +4 -3
- package/dist/mcp.js.map +1 -1
- package/dist/records-1HU7mWXf.js +22 -0
- package/dist/records-1HU7mWXf.js.map +1 -0
- package/dist/{search-CqH5hmuF.js → search-CA_OqFeW.js} +22 -6
- package/dist/{search-CqH5hmuF.js.map → search-CA_OqFeW.js.map} +1 -1
- package/dist/search_worker.js +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +2 -2
- package/dist/{types-C_Rmcgck.d.ts → types-De-TVQxS.d.ts} +43 -4
- package/package.json +1 -1
- package/dist/engine-BDWB2jdn.js.map +0 -1
- package/dist/invoke-tjTjZLHj.js.map +0 -1
- package/dist/json_schema_to_standard-r21kW2LI.js.map +0 -1
- package/dist/leading_system-BQe_405V.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"search-CqH5hmuF.js","names":["LINE_WIDTH","ALL_FILES"],"sources":["../src/acp/tools/containment.ts","../src/acp/tools/read_file.ts","../src/acp/tools/list_files.ts","../src/acp/tools/search.ts"],"sourcesContent":["/**\n * Containment: the boundary the workspace file tools keep. A path, absolute\n * or relative to the session's `cwd`, is allowed only when its real path\n * lands under one of the session's roots, which are real paths themselves,\n * resolved once at `session/new`.\n *\n * Real paths on both sides are the point. A symlink inside the workspace\n * that points out of it is the classic escape, and checking the path as\n * written would let it through. A `cwd` behind a symlink (macOS's `/tmp` and\n * `/var` both are) would refuse every file in the project if the roots\n * stayed as the client sent them. A path that doesn't exist yet resolves\n * through its nearest existing ancestor, and a dangling symlink through its\n * target, so a path outside the roots is refused the same way whether or\n * not it exists.\n */\n\nimport { readlink, realpath, stat } from 'node:fs/promises'\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport type { AcpSession } from '../types.js'\n\n/** A path a tool may touch, both as the client names it and as the file system resolves it. */\nexport type ContainedPath = {\n /** Absolute, under the `cwd` the client sent: what the client and the model are shown. */\n readonly path: string\n /** Symlinks resolved: what the tool opens. */\n readonly real: string\n}\n\n/** The error codes that mean a path, or a directory on the way to it, doesn't exist. */\nconst MISSING: ReadonlySet<unknown> = new Set(['ENOENT', 'ENOTDIR'])\n\n/**\n * How many symlinks a missing path may pass through before resolving it\n * gives up. `path.resolve` folds `missing/..` away where the kernel would\n * fail on it, so a link such as `a -> missing/../a` would otherwise loop.\n */\nconst MAX_LINK_HOPS = 40\n\n/**\n * The code a Node file system error carries, such as `ENOENT`. Every\n * caller hands in an error from `node:fs`, which always has one.\n */\nexport function error_code(err: unknown): unknown {\n return Reflect.get(Object(err), 'code')\n}\n\n/**\n * Resolve one root the client sent to its real path, refusing a relative\n * path (which would resolve against wherever the agent was launched), a path\n * that doesn't exist, and a file.\n */\nasync function resolve_root(root: string): Promise<string> {\n if (!isAbsolute(root)) {\n throw new Error(`the workspace root ${root} is a relative path; send session/new with absolute paths`)\n }\n const real = await realpath(root).catch((err: unknown) => {\n throw new Error(\n `the workspace root ${root} can't be opened (${String(error_code(err))}); send session/new with a directory that exists`,\n )\n })\n if (!(await stat(real)).isDirectory()) {\n throw new Error(`the workspace root ${root} is a file; send session/new with a directory`)\n }\n return real\n}\n\n/**\n * Resolve a session's roots (its `cwd`, then each additional directory) to\n * their real paths, once, when the session starts. The error names the\n * first root that isn't an absolute path to an existing directory.\n */\nexport async function resolve_roots(roots: ReadonlyArray<string>): Promise<string[]> {\n return Promise.all(roots.map(resolve_root))\n}\n\n/**\n * Whether `target` is `root` or lies beneath it. Both are compared as they\n * are, so the caller hands in real paths for a containment check.\n */\nfunction is_within(root: string, target: string): boolean {\n return target === root || target.startsWith(root.endsWith(sep) ? root : `${root}${sep}`)\n}\n\n/**\n * A symlink's target as written, or `undefined` when the path isn't a\n * symlink or isn't there.\n */\nasync function link_target(path: string): Promise<string | undefined> {\n return readlink(path).catch(() => undefined)\n}\n\n/**\n * The real path of `path`, existing or not. A path that exists is the file\n * system's own answer. A missing one is its parent's real path plus its\n * name, unless it's a dangling symlink, whose real path is its target's:\n * writing through it would land there.\n */\nasync function real_path(path: string, hops_left: number): Promise<string> {\n try {\n return await realpath(path)\n } catch (err: unknown) {\n if (!MISSING.has(error_code(err))) throw err\n }\n const parent = await real_path(dirname(path), hops_left)\n const target = await link_target(path)\n if (target === undefined) return join(parent, basename(path))\n if (hops_left === 0) throw new Error(`${path} passes through too many symbolic links to resolve`)\n return real_path(resolve(parent, target), hops_left - 1)\n}\n\n/**\n * Check that a path a tool was handed lands inside the session's workspace,\n * and return it both ways. The refusal is an ordinary error naming the roots\n * in the client's terms, since the model reads it as a tool result and can\n * try a path that fits.\n */\nexport async function contain(session: AcpSession, requested: string): Promise<ContainedPath> {\n const path = resolve(session.cwd, requested)\n const real = await real_path(path, MAX_LINK_HOPS)\n if (session.roots.some((root) => is_within(root, real))) return { path, real }\n const allowed = [session.cwd, ...session.additional_directories].join(', ')\n throw new Error(`${requested} is outside the workspace; the file tools only reach paths under ${allowed}`)\n}\n\n/**\n * A path as a tool shows it to the model: relative to `cwd` when it's under\n * it, and absolute otherwise, as for a file in an additional directory.\n * Either form reads back through `contain`.\n */\nexport function shown_path(session: AcpSession, path: string): string {\n return is_within(session.cwd, path) ? relative(session.cwd, path) || '.' : path\n}\n","/**\n * read_file: read a text file in the workspace with its lines numbered, a\n * window at a time.\n *\n * A window stops at `read_limit_lines` and says where the next one starts,\n * and a line past LINE_WIDTH characters is cut with a marker, because a\n * minified bundle or a source map can be one line of megabytes and nothing\n * else keeps it out of the model's context. A file with a NUL byte in its\n * first 8 KB is refused as binary, the test `examples/pr-improve` uses. The\n * file streams line by line, so a window near the top of a huge file reads\n * only as far as it shows.\n */\n\nimport { open, stat } from 'node:fs/promises'\nimport type { FileHandle } from 'node:fs/promises'\nimport type { Tool } from '#engine'\nimport { as_record, json_schema_to_standard } from '#schema'\nimport type { AcpSession } from '../types.js'\nimport { contain, error_code } from './containment.js'\n\n/** The longest line `read_file` returns whole, the width Claude Code's Read cuts at. */\nconst LINE_WIDTH = 2000\n\n/** How much of a file's head is checked for a NUL byte, the sign of a binary file. */\nconst BINARY_SNIFF_BYTES = 8192\n\n/** One read: the path as the model gave it, and the lines it covers. */\ntype ReadRequest = {\n readonly path: string\n readonly offset: number\n readonly limit: number\n}\n\n/**\n * Whether a value counts lines: a whole number of at least 1.\n */\nfunction is_count(value: unknown): value is number {\n return Number.isInteger(value) && Number(value) >= 1\n}\n\n/**\n * Read the call's window out of its input, with `limit` held to the cap.\n * The tool loop has already checked the types against the schema, but a\n * flow that wraps the tool can call `execute` directly, and the schema's\n * `minimum` is advice to the model rather than something the loop enforces.\n */\nfunction read_request(input: unknown, read_limit_lines: number): ReadRequest {\n const fields: Record<string, unknown> = as_record(input) ?? {}\n const { path, offset = 1, limit = read_limit_lines } = fields\n if (typeof path !== 'string') throw new Error('read_file needs a path, as a string')\n if (!is_count(offset) || !is_count(limit)) {\n throw new Error('read_file counts offset and limit in lines from 1, so each has to be a whole number of at least 1')\n }\n return { path, offset, limit: Math.min(limit, read_limit_lines) }\n}\n\n/**\n * Whether the file's first BINARY_SNIFF_BYTES hold a NUL byte. `search`\n * skips a file this calls binary, so the two tools agree on what is text.\n */\nexport async function is_binary(handle: FileHandle): Promise<boolean> {\n const head = Buffer.alloc(BINARY_SNIFF_BYTES)\n const { bytesRead } = await handle.read(head, 0, BINARY_SNIFF_BYTES, 0)\n return head.subarray(0, bytesRead).includes(0)\n}\n\n/**\n * One line as the model sees it: its number, a tab, and its text, cut at\n * LINE_WIDTH with a marker that says how long it was.\n */\nfunction numbered(line_number: number, line: string): string {\n const text =\n line.length > LINE_WIDTH ? `${line.slice(0, LINE_WIDTH)} [line cut at ${LINE_WIDTH} of ${line.length} characters]` : line\n return `${String(line_number).padStart(6)}\\t${text}`\n}\n\n/**\n * Number the window's lines, reading one line past it to learn whether the\n * file goes on, and say where to start the next read when it does.\n */\nasync function read_lines(handle: FileHandle, request: ReadRequest): Promise<string> {\n const last = request.offset + request.limit - 1\n const shown: string[] = []\n let count = 0\n let more = false\n // The binary check reads at an explicit position, which leaves the\n // handle's own position at the top, where these lines start.\n for await (const line of handle.readLines()) {\n count += 1\n if (count > last) {\n more = true\n break\n }\n if (count >= request.offset) shown.push(numbered(count, line))\n }\n if (count === 0) return `${request.path} is empty`\n if (shown.length === 0) {\n throw new Error(`offset ${request.offset} is past the end of ${request.path}, which has ${count} lines`)\n }\n const body = shown.join('\\n')\n if (!more) return body\n return `${body}\\n\\n[lines ${request.offset} to ${last} shown; the file goes on, so read on with offset ${last + 1}]`\n}\n\n/**\n * Read a contained file's window, refusing what isn't a regular text file.\n * The type is checked before the file opens, since opening a FIFO would\n * wait for a writer that never comes.\n */\nasync function read_contained(real: string, request: ReadRequest): Promise<string> {\n const info = await stat(real).catch((err: unknown) => {\n throw error_code(err) === 'ENOENT' ? new Error(`${request.path} doesn't exist`) : err\n })\n if (info.isDirectory()) throw new Error(`${request.path} is a directory; list_files shows what's in it`)\n if (!info.isFile()) throw new Error(`${request.path} isn't a regular file, so read_file can't read it`)\n const handle = await open(real)\n try {\n if (await is_binary(handle)) {\n throw new Error(`${request.path} is a binary file (it has a NUL byte in its first 8 KB), so read_file won't read it`)\n }\n return await read_lines(handle, request)\n } finally {\n await handle.close()\n }\n}\n\n/**\n * The `read_file` tool for one session: numbered lines from a file inside\n * its workspace, at most `read_limit_lines` per call.\n */\nexport function read_file_tool(session: AcpSession, read_limit_lines: number): Tool {\n return {\n name: 'read_file',\n description:\n `Read a text file in the workspace. Returns its lines numbered from 1, at most ${read_limit_lines} per call; ` +\n `pass offset (the first line to read) and limit to read part of a longer file. ` +\n `Lines over ${LINE_WIDTH} characters are cut. The path is absolute or relative to the workspace root.`,\n input_schema: json_schema_to_standard({\n type: 'object',\n properties: {\n path: { type: 'string', description: 'The file to read, absolute or relative to the workspace root' },\n offset: { type: 'integer', minimum: 1, description: 'The first line to read, counting from 1; default: 1' },\n limit: {\n type: 'integer',\n minimum: 1,\n description: `How many lines to read; default and most: ${read_limit_lines}`,\n },\n },\n required: ['path'],\n additionalProperties: false,\n }),\n execute: async (input) => {\n const request = read_request(input, read_limit_lines)\n const { real } = await contain(session, request.path)\n return read_contained(real, request)\n },\n }\n}\n","/**\n * list_files: list the workspace's files that match a glob.\n *\n * It walks the directory itself and matches each file with `path`'s\n * `matchesGlob`, rather than handing the walk to `fs/promises`' `glob`.\n * That `glob` steps through a symlinked directory whenever a pattern names\n * it, passes over its `exclude` callback for a pattern that names its\n * segments, swallows a directory it can't read, and, with an `exclude`\n * callback under Stryker's runner, dropped a whole directory it had already\n * listed. The walk here never follows a symlink and never enters an ignored\n * name, so every file it lists lies under the searched directory, which\n * `contain` has already placed inside a root, and its matches follow the\n * same glob rules as `glob`'s.\n */\n\nimport type { Dirent } from 'node:fs'\nimport { readdir, stat } from 'node:fs/promises'\nimport { isAbsolute, join, matchesGlob } from 'node:path'\nimport type { Tool } from '#engine'\nimport { as_record, json_schema_to_standard } from '#schema'\nimport type { AcpSession } from '../types.js'\nimport { contain, shown_path } from './containment.js'\n\n/** What `list_files` matches when the call names no pattern. */\nconst ALL_FILES = '**/*'\n\n/** One listing: the glob, and the directory it runs in, as the model gave them. */\ntype ListRequest = {\n readonly pattern: string\n readonly path: string\n}\n\n/** What one walk needs besides the directory it's in. */\nexport type Walk = {\n readonly pattern: string\n readonly ignored: ReadonlySet<string>\n readonly abort: AbortSignal\n readonly found: string[]\n}\n\n/**\n * Read the call's pattern and directory out of its input, refusing a\n * pattern that reaches past the directory: it could never match, and the\n * model is better told to pass the directory as `path`.\n */\nfunction list_request(input: unknown): ListRequest {\n const fields: Record<string, unknown> = as_record(input) ?? {}\n const { pattern = ALL_FILES, path = '.' } = fields\n if (typeof pattern !== 'string' || typeof path !== 'string') {\n throw new Error('list_files takes its pattern and path as strings')\n }\n if (isAbsolute(pattern) || pattern.split(/[\\\\/]/).includes('..')) {\n throw new Error(\n `list_files matches its pattern under path, so ${pattern} can't be absolute or climb with ..; pass the directory as path instead`,\n )\n }\n return { pattern, path }\n}\n\n/**\n * Walk one directory, depth first: descend into each subdirectory and keep\n * each regular file that matches, skipping ignored names. A symlink is\n * neither a directory nor a file to a `readdir` entry, so the walk never\n * follows one. `search` walks with it too, so both tools see the same files.\n */\nexport async function walk(directory: string, below: string, work: Walk): Promise<void> {\n work.abort.throwIfAborted()\n const entries: Dirent[] = await readdir(directory, { withFileTypes: true })\n for (const entry of entries) {\n if (work.ignored.has(entry.name)) continue\n const relative = join(below, entry.name)\n if (entry.isDirectory()) await walk(join(directory, entry.name), relative, work)\n else if (entry.isFile() && matchesGlob(relative, work.pattern)) work.found.push(relative)\n }\n}\n\n/**\n * The files under the request's directory that match its pattern, in the\n * model's terms and sorted.\n */\nasync function matching_files(\n session: AcpSession,\n request: ListRequest,\n ignored: ReadonlySet<string>,\n abort: AbortSignal,\n): Promise<string[]> {\n const base = await contain(session, request.path)\n if (!(await stat(base.real)).isDirectory()) {\n throw new Error(`${request.path} is a file; list_files lists a directory, and read_file reads a file`)\n }\n const found: string[] = []\n await walk(base.real, '', { pattern: request.pattern, ignored, abort, found })\n return found.map((relative) => shown_path(session, join(base.path, relative))).toSorted()\n}\n\n/**\n * The `list_files` tool for one session: the files under a directory in\n * its workspace that match a glob, skipping the `ignore` names.\n */\nexport function list_files_tool(session: AcpSession, ignore: ReadonlyArray<string>): Tool {\n const ignored = new Set(ignore)\n return {\n name: 'list_files',\n description: [\n 'List the files in the workspace that match a glob pattern, one per line; a path under the workspace root is shown relative to it.',\n `The pattern matches under path (default: the workspace root) and defaults to ${ALL_FILES}.`,\n 'As in a shell, * and ** skip names that start with a dot, so name the dot to list hidden files (.github/**/*).',\n ...(ignore.length === 0 ? [] : [`Skips ${ignore.join(', ')}.`]),\n ].join(' '),\n input_schema: json_schema_to_standard({\n type: 'object',\n properties: {\n pattern: { type: 'string', description: `A glob such as src/**/*.ts; default: ${ALL_FILES}` },\n path: {\n type: 'string',\n description: 'The directory to search, absolute or relative to the workspace root; default: the root',\n },\n },\n additionalProperties: false,\n }),\n execute: async (input, ctx) => {\n const request = list_request(input)\n const files = await matching_files(session, request, ignored, ctx.abort)\n return files.length === 0 ? `no files match ${request.pattern} under ${request.path}` : files.join('\\n')\n },\n }\n}\n","/**\n * search: find the lines in the workspace's files that match a regular\n * expression.\n *\n * The pattern is the model's, and JavaScript's `RegExp` backtracks, so a\n * pattern such as `(a+)+$` against one long line can run for minutes. No\n * abort interrupts synchronous code, and one agent process serves every\n * session, so a search on the main thread could leave even `session/cancel`\n * unanswered. Each search runs in a worker thread instead, which the turn's\n * abort and a time budget can terminate mid-match. The worker is a thin\n * shell, `search_worker.ts`: what it runs is `search_files`, here, where\n * the tests call it on the main thread.\n *\n * The search walks the files itself, with `list_files`' walk, rather than\n * handing the work to `rg`, because the module keeps child processes to\n * `run_command`.\n */\n\nimport { open, stat } from 'node:fs/promises'\nimport { extname, join } from 'node:path'\nimport { Worker } from 'node:worker_threads'\nimport type { Tool } from '#engine'\nimport { as_record, json_schema_to_standard } from '#schema'\nimport type { AcpSession } from '../types.js'\nimport { contain, shown_path } from './containment.js'\nimport { walk } from './list_files.js'\nimport { is_binary } from './read_file.js'\n\n/** What `search` matches when the call names no glob. */\nconst ALL_FILES = '**/*'\n\n/** The most matches one call returns. */\nconst MATCH_LIMIT = 100\n\n/**\n * The longest matching line shown whole. A longer one is shown as a window\n * this wide around its match, since a minified bundle is one line of\n * megabytes and every match in it would otherwise carry the whole line.\n */\nconst LINE_WIDTH = 500\n\n/** How much of a long line its window shows before the match. */\nconst LINE_LEAD = 100\n\n/**\n * The search worker, beside this module with its extension: `.ts` in the\n * source tree, where vitest and Stryker run it, and `.js` once built.\n */\nconst SEARCH_WORKER = new URL(`./search_worker${extname(import.meta.url)}`, import.meta.url)\n\n/** One search as the model asked for it. */\ntype SearchRequest = {\n readonly pattern: string\n readonly path: string\n readonly glob: string\n}\n\n/** One search as the worker runs it: plain data, since it crosses to another thread. */\ntype SearchJob = {\n /** The real path of the directory to walk, or of the one file to search. */\n readonly base: string\n readonly directory: boolean\n readonly pattern: string\n /** The glob as the walk matches it, relative to `base`. */\n readonly glob: string\n readonly ignore: ReadonlyArray<string>\n readonly limit: number\n}\n\n/**\n * One matching line: its file relative to the job's base (empty when the\n * base is that file), its number counting from 1, and its text.\n */\ntype SearchMatch = {\n readonly file: string\n readonly line: number\n readonly text: string\n}\n\n/** The matches, and whether the search stopped at its limit with more to find. */\ntype SearchResult = {\n readonly matches: ReadonlyArray<SearchMatch>\n readonly more: boolean\n}\n\n/**\n * Read the call's pattern, path, and glob out of its input. The pattern\n * compiles in the worker, which reports one that isn't a regular expression\n * with the engine's own message.\n */\nfunction search_request(input: unknown): SearchRequest {\n const fields: Record<string, unknown> = as_record(input) ?? {}\n const { pattern, path = '.', glob = ALL_FILES } = fields\n if (typeof pattern !== 'string' || typeof path !== 'string' || typeof glob !== 'string') {\n throw new Error('search needs a pattern, and takes its pattern, path, and glob as strings')\n }\n return { pattern, path, glob }\n}\n\n/**\n * The glob as the walk matches it. Like `rg --glob`, a glob without a slash\n * names files at any depth, so `*.ts` reaches `src/a.ts`, while one with a\n * slash matches the path under the searched directory.\n */\nfunction walk_glob(glob: string): string {\n return glob.includes('/') ? glob : `**/${glob}`\n}\n\n/**\n * The files a job searches, relative to its base: the one file, or every\n * file the walk keeps, sorted so the same search stops at the same match\n * every time.\n */\nasync function files_of(job: SearchJob): Promise<string[]> {\n if (!job.directory) return ['']\n const found: string[] = []\n // Nothing inside the worker cancels the walk: the turn's abort and the\n // budget terminate the whole thread instead.\n const abort = new AbortController().signal\n await walk(job.base, '', { pattern: job.glob, ignored: new Set(job.ignore), abort, found })\n return found.toSorted()\n}\n\n/**\n * A file's text, or nothing for a binary file, which then has no lines to\n * search.\n */\nasync function file_text(path: string): Promise<string> {\n const handle = await open(path)\n try {\n // The binary check reads at an explicit position, which leaves the\n // handle's own position at the top, where readFile starts.\n return (await is_binary(handle)) ? '' : await handle.readFile('utf8')\n } finally {\n await handle.close()\n }\n}\n\n/**\n * A text's lines without their endings, and without the empty one after a\n * final newline, which isn't a line of the file.\n */\nfunction lines_of(text: string): string[] {\n const lines = text.split(/\\r?\\n/)\n if (lines.at(-1) === '') lines.pop()\n return lines\n}\n\n/**\n * A matching line as `search` shows it: whole up to LINE_WIDTH characters,\n * and past that, a window that wide starting LINE_LEAD characters before\n * the match, kept inside the line, with the columns it covers.\n */\nfunction excerpt(line: string, at: number): string {\n if (line.length <= LINE_WIDTH) return line\n const start = Math.max(0, Math.min(at - LINE_LEAD, line.length - LINE_WIDTH))\n return `${line.slice(start, start + LINE_WIDTH)} [columns ${start + 1} to ${start + LINE_WIDTH} of ${line.length}]`\n}\n\n/**\n * Search a job's files, in order, for the lines its pattern matches,\n * stopping at the first match past the limit, which says there are more.\n * The search worker runs this, and the tests call it on the main thread,\n * where Stryker can switch its mutants on.\n */\nexport async function search_files(job: SearchJob): Promise<SearchResult> {\n const regex = new RegExp(job.pattern)\n const matches: SearchMatch[] = []\n for (const file of await files_of(job)) {\n for (const [index, line] of lines_of(await file_text(join(job.base, file))).entries()) {\n const found = regex.exec(line)\n if (found === null) continue\n if (matches.length === job.limit) return { matches, more: true }\n matches.push({ file, line: index + 1, text: excerpt(line, found.index) })\n }\n }\n return { matches, more: false }\n}\n\n/**\n * Run one job in a search worker. The turn's abort and the budget each\n * terminate the thread, mid-match if need be, which nothing could do to a\n * pattern running on the main thread. However the search ends, the abort\n * listener and the budget's timer go with it.\n */\nasync function in_worker(job: SearchJob, budget_ms: number, abort: AbortSignal): Promise<SearchResult> {\n abort.throwIfAborted()\n const worker = new Worker(SEARCH_WORKER, { workerData: job })\n const { promise, resolve, reject } = Promise.withResolvers<SearchResult>()\n const stop = (reason: unknown): void => {\n void worker.terminate()\n reject(reason)\n }\n const on_abort = (): void => {\n stop(abort.reason)\n }\n const over_budget = new Error(\n `search stopped after ${budget_ms / 1000} s without finishing: the pattern may backtrack without end, ` +\n 'as nested quantifiers such as (a+)+ can, or there may be too much to search; ' +\n 'simplify the pattern, or narrow path or glob',\n )\n const budget = setTimeout(stop, budget_ms, over_budget)\n abort.addEventListener('abort', on_abort)\n worker.once('message', resolve)\n worker.once('error', reject)\n try {\n return await promise\n } finally {\n clearTimeout(budget)\n abort.removeEventListener('abort', on_abort)\n }\n}\n\n/**\n * The matches as the model reads them, one `path:line: text` to a line, and\n * a note when the search stopped at its limit.\n */\nfunction report(session: AcpSession, base: string, request: SearchRequest, result: SearchResult): string {\n if (result.matches.length === 0) {\n return `no lines match ${request.pattern} under ${request.path} in files matching ${request.glob}`\n }\n const lines = result.matches.map(\n (match) => `${shown_path(session, join(base, match.file))}:${match.line}: ${match.text}`,\n )\n if (result.more) {\n lines.push('', `[the first ${result.matches.length} matches; narrow the pattern, path, or glob to see the rest]`)\n }\n return lines.join('\\n')\n}\n\n/**\n * The `search` tool for one session: the lines under a path in its\n * workspace that match a regular expression, skipping binary files and the\n * `ignore` names, at most MATCH_LIMIT per call, each search in a worker\n * that the turn's abort and `budget_ms` can terminate.\n */\nexport function search_tool(session: AcpSession, ignore: ReadonlyArray<string>, budget_ms: number): Tool {\n return {\n name: 'search',\n description: [\n `Search the workspace's files for lines that match a regular expression, at most ${MATCH_LIMIT} per call,`,\n 'each shown as path:line: text; a path under the workspace root is shown relative to it.',\n 'The pattern is a JavaScript regular expression matched against one line at a time; write (?i:...) for a part that ignores case.',\n 'path (default: the workspace root) is the directory to search, or a single file.',\n 'glob picks the files: without a slash it matches a file name at any depth (*.ts, *.{ts,tsx}),',\n 'and with one it matches the path under path (src/**/*.ts).',\n 'As in a shell, * and ** skip names that start with a dot, so name the dot to search hidden files (.github/**/*).',\n ignore.length === 0 ? 'Skips binary files.' : `Skips binary files and ${ignore.join(', ')}.`,\n ].join(' '),\n input_schema: json_schema_to_standard({\n type: 'object',\n properties: {\n pattern: { type: 'string', description: 'A JavaScript regular expression, such as function\\\\s+\\\\w+' },\n path: {\n type: 'string',\n description: 'The directory or file to search, absolute or relative to the workspace root; default: the root',\n },\n glob: { type: 'string', description: `Which files to search, such as *.ts or src/**/*.ts; default: ${ALL_FILES}` },\n },\n required: ['pattern'],\n additionalProperties: false,\n }),\n execute: async (input, ctx) => {\n const request = search_request(input)\n const base = await contain(session, request.path)\n const info = await stat(base.real)\n if (!info.isDirectory() && !info.isFile()) {\n throw new Error(`${request.path} isn't a directory or a regular file, so search can't read it`)\n }\n const job: SearchJob = {\n base: base.real,\n directory: info.isDirectory(),\n pattern: request.pattern,\n glob: walk_glob(request.glob),\n ignore,\n limit: MATCH_LIMIT,\n }\n return report(session, base.path, request, await in_worker(job, budget_ms, ctx.abort))\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA6BA,MAAM,0BAAgC,IAAI,IAAI,CAAC,UAAU,SAAS,CAAC;;;;;;AAOnE,MAAM,gBAAgB;;;;;AAMtB,SAAgB,WAAW,KAAuB;CAChD,OAAO,QAAQ,IAAI,OAAO,GAAG,GAAG,MAAM;AACxC;;;;;;AAOA,eAAe,aAAa,MAA+B;CACzD,IAAI,CAAC,WAAW,IAAI,GAClB,MAAM,IAAI,M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;IAC5B;IACA,OAAO;GACT;GACA,OAAO,OAAO,SAAS,KAAK,MAAM,SAAS,MAAM,UAAU,KAAK,WAAW,IAAI,KAAK,CAAC;EACvF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"search-CA_OqFeW.js","names":["LINE_WIDTH","ALL_FILES"],"sources":["../src/acp/tools/containment.ts","../src/acp/tools/read_file.ts","../src/acp/tools/list_files.ts","../src/acp/tools/search.ts"],"sourcesContent":["/**\n * Containment: the boundary the workspace file tools keep. A path, absolute\n * or relative to the session's `cwd`, is allowed only when its real path\n * lands under one of the session's roots, which are real paths themselves,\n * resolved once at `session/new`.\n *\n * Real paths on both sides are the point. A symlink inside the workspace\n * that points out of it is the classic escape, and checking the path as\n * written would let it through. A `cwd` behind a symlink (macOS's `/tmp` and\n * `/var` both are) would refuse every file in the project if the roots\n * stayed as the client sent them. A path that doesn't exist yet resolves\n * through its nearest existing ancestor, and a dangling symlink through its\n * target, so a path outside the roots is refused the same way whether or\n * not it exists.\n */\n\nimport { readlink, realpath, stat } from 'node:fs/promises'\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport type { AcpSession } from '../types.js'\n\n/** A path a tool may touch, both as the client names it and as the file system resolves it. */\nexport type ContainedPath = {\n /** Absolute, under the `cwd` the client sent: what the client and the model are shown. */\n readonly path: string\n /** Symlinks resolved: what the tool opens. */\n readonly real: string\n}\n\n/** The error codes that mean a path, or a directory on the way to it, doesn't exist. */\nconst MISSING: ReadonlySet<unknown> = new Set(['ENOENT', 'ENOTDIR'])\n\n/**\n * How many symlinks a missing path may pass through before resolving it\n * gives up. `path.resolve` folds `missing/..` away where the kernel would\n * fail on it, so a link such as `a -> missing/../a` would otherwise loop.\n */\nconst MAX_LINK_HOPS = 40\n\n/**\n * The code a Node file system error carries, such as `ENOENT`. Every\n * caller hands in an error from `node:fs`, which always has one.\n */\nexport function error_code(err: unknown): unknown {\n return Reflect.get(Object(err), 'code')\n}\n\n/**\n * Resolve one root the client sent to its real path, refusing a relative\n * path (which would resolve against wherever the agent was launched), a path\n * that doesn't exist, and a file.\n */\nasync function resolve_root(root: string): Promise<string> {\n if (!isAbsolute(root)) {\n throw new Error(`the workspace root ${root} is a relative path; send session/new with absolute paths`)\n }\n const real = await realpath(root).catch((err: unknown) => {\n throw new Error(\n `the workspace root ${root} can't be opened (${String(error_code(err))}); send session/new with a directory that exists`,\n )\n })\n if (!(await stat(real)).isDirectory()) {\n throw new Error(`the workspace root ${root} is a file; send session/new with a directory`)\n }\n return real\n}\n\n/**\n * Resolve a session's roots (its `cwd`, then each additional directory) to\n * their real paths, once, when the session starts. The error names the\n * first root that isn't an absolute path to an existing directory.\n */\nexport async function resolve_roots(roots: ReadonlyArray<string>): Promise<string[]> {\n return Promise.all(roots.map(resolve_root))\n}\n\n/**\n * Whether `target` is `root` or lies beneath it. Both are compared as they\n * are, so the caller hands in real paths for a containment check.\n */\nfunction is_within(root: string, target: string): boolean {\n return target === root || target.startsWith(root.endsWith(sep) ? root : `${root}${sep}`)\n}\n\n/**\n * A symlink's target as written, or `undefined` when the path isn't a\n * symlink or isn't there.\n */\nasync function link_target(path: string): Promise<string | undefined> {\n return readlink(path).catch(() => undefined)\n}\n\n/**\n * The real path of `path`, existing or not. A path that exists is the file\n * system's own answer. A missing one is its parent's real path plus its\n * name, unless it's a dangling symlink, whose real path is its target's:\n * writing through it would land there.\n */\nasync function real_path(path: string, hops_left: number): Promise<string> {\n try {\n return await realpath(path)\n } catch (err: unknown) {\n if (!MISSING.has(error_code(err))) throw err\n }\n const parent = await real_path(dirname(path), hops_left)\n const target = await link_target(path)\n if (target === undefined) return join(parent, basename(path))\n if (hops_left === 0) throw new Error(`${path} passes through too many symbolic links to resolve`)\n return real_path(resolve(parent, target), hops_left - 1)\n}\n\n/**\n * Check that a path a tool was handed lands inside the session's workspace,\n * and return it both ways. The refusal is an ordinary error naming the roots\n * in the client's terms, since the model reads it as a tool result and can\n * try a path that fits.\n */\nexport async function contain(session: AcpSession, requested: string): Promise<ContainedPath> {\n const path = resolve(session.cwd, requested)\n const real = await real_path(path, MAX_LINK_HOPS)\n if (session.roots.some((root) => is_within(root, real))) return { path, real }\n const allowed = [session.cwd, ...session.additional_directories].join(', ')\n throw new Error(`${requested} is outside the workspace; the file tools only reach paths under ${allowed}`)\n}\n\n/**\n * A path as a tool shows it to the model: relative to `cwd` when it's under\n * it, and absolute otherwise, as for a file in an additional directory.\n * Either form reads back through `contain`.\n */\nexport function shown_path(session: AcpSession, path: string): string {\n return is_within(session.cwd, path) ? relative(session.cwd, path) || '.' : path\n}\n","/**\n * read_file: read a text file in the workspace with its lines numbered, a\n * window at a time.\n *\n * A window stops at `read_limit_lines` and says where the next one starts,\n * and a line past LINE_WIDTH characters is cut with a marker, because a\n * minified bundle or a source map can be one line of megabytes and nothing\n * else keeps it out of the model's context. A file with a NUL byte in its\n * first 8 KB is refused as binary, the test `examples/pr-improve` uses. The\n * file streams line by line, so a window near the top of a huge file reads\n * only as far as it shows.\n */\n\nimport { open, stat } from 'node:fs/promises'\nimport type { FileHandle } from 'node:fs/promises'\nimport type { Tool } from '#engine'\nimport { as_record, json_schema_to_standard } from '#schema'\nimport type { AcpSession } from '../types.js'\nimport { contain, error_code } from './containment.js'\n\n/** The longest line `read_file` returns whole, the width Claude Code's Read cuts at. */\nconst LINE_WIDTH = 2000\n\n/** How much of a file's head is checked for a NUL byte, the sign of a binary file. */\nconst BINARY_SNIFF_BYTES = 8192\n\n/** One read: the path as the model gave it, and the lines it covers. */\ntype ReadRequest = {\n readonly path: string\n readonly offset: number\n readonly limit: number\n}\n\n/**\n * Whether a value counts lines: a whole number of at least 1.\n */\nfunction is_count(value: unknown): value is number {\n return Number.isInteger(value) && Number(value) >= 1\n}\n\n/**\n * Read the call's window out of its input, with `limit` held to the cap.\n * The tool loop has already checked the types against the schema, but a\n * flow that wraps the tool can call `execute` directly, and the schema's\n * `minimum` is advice to the model rather than something the loop enforces.\n */\nfunction read_request(input: unknown, read_limit_lines: number): ReadRequest {\n const fields: Record<string, unknown> = as_record(input) ?? {}\n const { path, offset = 1, limit = read_limit_lines } = fields\n if (typeof path !== 'string') throw new Error('read_file needs a path, as a string')\n if (!is_count(offset) || !is_count(limit)) {\n throw new Error('read_file counts offset and limit in lines from 1, so each has to be a whole number of at least 1')\n }\n return { path, offset, limit: Math.min(limit, read_limit_lines) }\n}\n\n/**\n * Whether the file's first BINARY_SNIFF_BYTES hold a NUL byte. `search`\n * skips a file this calls binary, so the two tools agree on what is text.\n */\nexport async function is_binary(handle: FileHandle): Promise<boolean> {\n const head = Buffer.alloc(BINARY_SNIFF_BYTES)\n const { bytesRead } = await handle.read(head, 0, BINARY_SNIFF_BYTES, 0)\n return head.subarray(0, bytesRead).includes(0)\n}\n\n/**\n * One line as the model sees it: its number, a tab, and its text, cut at\n * LINE_WIDTH with a marker that says how long it was.\n */\nfunction numbered(line_number: number, line: string): string {\n const text =\n line.length > LINE_WIDTH ? `${line.slice(0, LINE_WIDTH)} [line cut at ${LINE_WIDTH} of ${line.length} characters]` : line\n return `${String(line_number).padStart(6)}\\t${text}`\n}\n\n/**\n * Number the window's lines, reading one line past it to learn whether the\n * file goes on, and say where to start the next read when it does.\n */\nasync function read_lines(handle: FileHandle, request: ReadRequest): Promise<string> {\n const last = request.offset + request.limit - 1\n const shown: string[] = []\n let count = 0\n let more = false\n // The binary check reads at an explicit position, which leaves the\n // handle's own position at the top, where these lines start.\n for await (const line of handle.readLines()) {\n count += 1\n if (count > last) {\n more = true\n break\n }\n if (count >= request.offset) shown.push(numbered(count, line))\n }\n if (count === 0) return `${request.path} is empty`\n if (shown.length === 0) {\n throw new Error(`offset ${request.offset} is past the end of ${request.path}, which has ${count} lines`)\n }\n const body = shown.join('\\n')\n if (!more) return body\n return `${body}\\n\\n[lines ${request.offset} to ${last} shown; the file goes on, so read on with offset ${last + 1}]`\n}\n\n/**\n * Read a contained file's window, refusing what isn't a regular text file.\n * The type is checked before the file opens, since opening a FIFO would\n * wait for a writer that never comes.\n */\nasync function read_contained(real: string, request: ReadRequest): Promise<string> {\n const info = await stat(real).catch((err: unknown) => {\n throw error_code(err) === 'ENOENT' ? new Error(`${request.path} doesn't exist`) : err\n })\n if (info.isDirectory()) throw new Error(`${request.path} is a directory; list_files shows what's in it`)\n if (!info.isFile()) throw new Error(`${request.path} isn't a regular file, so read_file can't read it`)\n const handle = await open(real)\n try {\n if (await is_binary(handle)) {\n throw new Error(`${request.path} is a binary file (it has a NUL byte in its first 8 KB), so read_file won't read it`)\n }\n return await read_lines(handle, request)\n } finally {\n await handle.close()\n }\n}\n\n/**\n * The `read_file` tool for one session: numbered lines from a file inside\n * its workspace, at most `read_limit_lines` per call.\n */\nexport function read_file_tool(session: AcpSession, read_limit_lines: number): Tool {\n return {\n name: 'read_file',\n description:\n `Read a text file in the workspace. Returns its lines numbered from 1, at most ${read_limit_lines} per call; ` +\n `pass offset (the first line to read) and limit to read part of a longer file. ` +\n `Lines over ${LINE_WIDTH} characters are cut. The path is absolute or relative to the workspace root.`,\n input_schema: json_schema_to_standard({\n type: 'object',\n properties: {\n path: { type: 'string', description: 'The file to read, absolute or relative to the workspace root' },\n offset: { type: 'integer', minimum: 1, description: 'The first line to read, counting from 1; default: 1' },\n limit: {\n type: 'integer',\n minimum: 1,\n description: `How many lines to read; default and most: ${read_limit_lines}`,\n },\n },\n required: ['path'],\n additionalProperties: false,\n }),\n execute: async (input) => {\n const request = read_request(input, read_limit_lines)\n const { real } = await contain(session, request.path)\n return read_contained(real, request)\n },\n }\n}\n","/**\n * list_files: list the workspace's files that match a glob.\n *\n * It walks the directory itself and matches each file with `path`'s\n * `matchesGlob`, rather than handing the walk to `fs/promises`' `glob`.\n * That `glob` steps through a symlinked directory whenever a pattern names\n * it, passes over its `exclude` callback for a pattern that names its\n * segments, swallows a directory it can't read, and, with an `exclude`\n * callback under Stryker's runner, dropped a whole directory it had already\n * listed. The walk here never follows a symlink and never enters an ignored\n * name, so every file it lists lies under the searched directory, which\n * `contain` has already placed inside a root, and its matches follow the\n * same glob rules as `glob`'s.\n */\n\nimport type { Dirent } from 'node:fs'\nimport { readdir, stat } from 'node:fs/promises'\nimport { isAbsolute, join, matchesGlob } from 'node:path'\nimport type { Tool } from '#engine'\nimport { as_record, json_schema_to_standard } from '#schema'\nimport type { AcpSession } from '../types.js'\nimport { contain, shown_path } from './containment.js'\n\n/** What `list_files` matches when the call names no pattern. */\nconst ALL_FILES = '**/*'\n\n/** One listing: the glob, and the directory it runs in, as the model gave them. */\ntype ListRequest = {\n readonly pattern: string\n readonly path: string\n}\n\n/** What one walk needs besides the directory it's in. */\nexport type Walk = {\n readonly pattern: string\n readonly ignored: ReadonlySet<string>\n readonly abort: AbortSignal\n readonly found: string[]\n}\n\n/**\n * Read the call's pattern and directory out of its input, refusing a\n * pattern that reaches past the directory: it could never match, and the\n * model is better told to pass the directory as `path`.\n */\nfunction list_request(input: unknown): ListRequest {\n const fields: Record<string, unknown> = as_record(input) ?? {}\n const { pattern = ALL_FILES, path = '.' } = fields\n if (typeof pattern !== 'string' || typeof path !== 'string') {\n throw new Error('list_files takes its pattern and path as strings')\n }\n if (isAbsolute(pattern) || pattern.split(/[\\\\/]/).includes('..')) {\n throw new Error(\n `list_files matches its pattern under path, so ${pattern} can't be absolute or climb with ..; pass the directory as path instead`,\n )\n }\n return { pattern, path }\n}\n\n/**\n * Walk one directory, depth first: descend into each subdirectory and keep\n * each regular file that matches, skipping ignored names. A symlink is\n * neither a directory nor a file to a `readdir` entry, so the walk never\n * follows one. `search` walks with it too, so both tools see the same files.\n */\nexport async function walk(directory: string, below: string, work: Walk): Promise<void> {\n work.abort.throwIfAborted()\n const entries: Dirent[] = await readdir(directory, { withFileTypes: true })\n for (const entry of entries) {\n if (work.ignored.has(entry.name)) continue\n const relative = join(below, entry.name)\n if (entry.isDirectory()) await walk(join(directory, entry.name), relative, work)\n else if (entry.isFile() && matchesGlob(relative, work.pattern)) work.found.push(relative)\n }\n}\n\n/**\n * The files under the request's directory that match its pattern, in the\n * model's terms and sorted.\n */\nasync function matching_files(\n session: AcpSession,\n request: ListRequest,\n ignored: ReadonlySet<string>,\n abort: AbortSignal,\n): Promise<string[]> {\n const base = await contain(session, request.path)\n if (!(await stat(base.real)).isDirectory()) {\n throw new Error(`${request.path} is a file; list_files lists a directory, and read_file reads a file`)\n }\n const found: string[] = []\n await walk(base.real, '', { pattern: request.pattern, ignored, abort, found })\n return found.map((relative) => shown_path(session, join(base.path, relative))).toSorted()\n}\n\n/**\n * The files as the model reads them, one to a line, and past `limit` the\n * first `limit` of them with a note giving the total. The walk has already\n * found every match to sort them, so the total costs nothing to count.\n */\nfunction listing(files: ReadonlyArray<string>, limit: number): string {\n if (files.length <= limit) return files.join('\\n')\n const note = `[the first ${limit} of ${files.length} files; narrow pattern or path to see the rest]`\n return [...files.slice(0, limit), '', note].join('\\n')\n}\n\n/**\n * The `list_files` tool for one session: the files under a directory in\n * its workspace that match a glob, skipping the `ignore` names, at most\n * `limit` per call.\n */\nexport function list_files_tool(session: AcpSession, ignore: ReadonlyArray<string>, limit: number): Tool {\n const ignored = new Set(ignore)\n return {\n name: 'list_files',\n description: [\n `List the files in the workspace that match a glob pattern, one per line and at most ${limit} per call; a path under the workspace root is shown relative to it.`,\n `The pattern matches under path (default: the workspace root) and defaults to ${ALL_FILES}.`,\n 'As in a shell, * and ** skip names that start with a dot, so name the dot to list hidden files (.github/**/*).',\n ...(ignore.length === 0 ? [] : [`Skips ${ignore.join(', ')}.`]),\n ].join(' '),\n input_schema: json_schema_to_standard({\n type: 'object',\n properties: {\n pattern: { type: 'string', description: `A glob such as src/**/*.ts; default: ${ALL_FILES}` },\n path: {\n type: 'string',\n description: 'The directory to search, absolute or relative to the workspace root; default: the root',\n },\n },\n additionalProperties: false,\n }),\n execute: async (input, ctx) => {\n const request = list_request(input)\n const files = await matching_files(session, request, ignored, ctx.abort)\n return files.length === 0 ? `no files match ${request.pattern} under ${request.path}` : listing(files, limit)\n },\n }\n}\n","/**\n * search: find the lines in the workspace's files that match a regular\n * expression.\n *\n * The pattern is the model's, and JavaScript's `RegExp` backtracks, so a\n * pattern such as `(a+)+$` against one long line can run for minutes. No\n * abort interrupts synchronous code, and one agent process serves every\n * session, so a search on the main thread could leave even `session/cancel`\n * unanswered. Each search runs in a worker thread instead, which the turn's\n * abort and a time budget can terminate mid-match. The worker is a thin\n * shell, `search_worker.ts`: what it runs is `search_files`, here, where\n * the tests call it on the main thread.\n *\n * The search walks the files itself, with `list_files`' walk, rather than\n * handing the work to `rg`, because the module keeps child processes to\n * `run_command`.\n */\n\nimport { open, stat } from 'node:fs/promises'\nimport { extname, join } from 'node:path'\nimport { Worker } from 'node:worker_threads'\nimport type { Tool } from '#engine'\nimport { as_record, json_schema_to_standard } from '#schema'\nimport type { AcpSession } from '../types.js'\nimport { contain, shown_path } from './containment.js'\nimport { walk } from './list_files.js'\nimport { is_binary } from './read_file.js'\n\n/** What `search` matches when the call names no glob. */\nconst ALL_FILES = '**/*'\n\n/** The most matches one call returns. */\nconst MATCH_LIMIT = 100\n\n/**\n * The longest matching line shown whole. A longer one is shown as a window\n * this wide around its match, since a minified bundle is one line of\n * megabytes and every match in it would otherwise carry the whole line.\n */\nconst LINE_WIDTH = 500\n\n/** How much of a long line its window shows before the match. */\nconst LINE_LEAD = 100\n\n/**\n * The search worker, beside this module with its extension: `.ts` in the\n * source tree, where vitest and Stryker run it, and `.js` once built.\n */\nconst SEARCH_WORKER = new URL(`./search_worker${extname(import.meta.url)}`, import.meta.url)\n\n/** One search as the model asked for it. */\ntype SearchRequest = {\n readonly pattern: string\n readonly path: string\n readonly glob: string\n}\n\n/** One search as the worker runs it: plain data, since it crosses to another thread. */\ntype SearchJob = {\n /** The real path of the directory to walk, or of the one file to search. */\n readonly base: string\n readonly directory: boolean\n readonly pattern: string\n /** The glob as the walk matches it, relative to `base`. */\n readonly glob: string\n readonly ignore: ReadonlyArray<string>\n readonly limit: number\n}\n\n/**\n * One matching line: its file relative to the job's base (empty when the\n * base is that file), its number counting from 1, and its text.\n */\ntype SearchMatch = {\n readonly file: string\n readonly line: number\n readonly text: string\n}\n\n/** The matches, and whether the search stopped at its limit with more to find. */\ntype SearchResult = {\n readonly matches: ReadonlyArray<SearchMatch>\n readonly more: boolean\n}\n\n/**\n * Read the call's pattern, path, and glob out of its input. The pattern\n * compiles in the worker, which reports one that isn't a regular expression\n * with the engine's own message.\n */\nfunction search_request(input: unknown): SearchRequest {\n const fields: Record<string, unknown> = as_record(input) ?? {}\n const { pattern, path = '.', glob = ALL_FILES } = fields\n if (typeof pattern !== 'string' || typeof path !== 'string' || typeof glob !== 'string') {\n throw new Error('search needs a pattern, and takes its pattern, path, and glob as strings')\n }\n return { pattern, path, glob }\n}\n\n/**\n * The glob as the walk matches it. Like `rg --glob`, a glob without a slash\n * names files at any depth, so `*.ts` reaches `src/a.ts`, while one with a\n * slash matches the path under the searched directory.\n */\nfunction walk_glob(glob: string): string {\n return glob.includes('/') ? glob : `**/${glob}`\n}\n\n/**\n * The files a job searches, relative to its base: the one file, or every\n * file the walk keeps, sorted so the same search stops at the same match\n * every time.\n */\nasync function files_of(job: SearchJob): Promise<string[]> {\n if (!job.directory) return ['']\n const found: string[] = []\n // Nothing inside the worker cancels the walk: the turn's abort and the\n // budget terminate the whole thread instead.\n const abort = new AbortController().signal\n await walk(job.base, '', { pattern: job.glob, ignored: new Set(job.ignore), abort, found })\n return found.toSorted()\n}\n\n/**\n * A file's text, or nothing for a binary file, which then has no lines to\n * search.\n */\nasync function file_text(path: string): Promise<string> {\n const handle = await open(path)\n try {\n // The binary check reads at an explicit position, which leaves the\n // handle's own position at the top, where readFile starts.\n return (await is_binary(handle)) ? '' : await handle.readFile('utf8')\n } finally {\n await handle.close()\n }\n}\n\n/**\n * A text's lines without their endings, and without the empty one after a\n * final newline, which isn't a line of the file.\n */\nfunction lines_of(text: string): string[] {\n const lines = text.split(/\\r?\\n/)\n if (lines.at(-1) === '') lines.pop()\n return lines\n}\n\n/**\n * A matching line as `search` shows it: whole up to LINE_WIDTH characters,\n * and past that, a window that wide starting LINE_LEAD characters before\n * the match, kept inside the line, with the columns it covers.\n */\nfunction excerpt(line: string, at: number): string {\n if (line.length <= LINE_WIDTH) return line\n const start = Math.max(0, Math.min(at - LINE_LEAD, line.length - LINE_WIDTH))\n return `${line.slice(start, start + LINE_WIDTH)} [columns ${start + 1} to ${start + LINE_WIDTH} of ${line.length}]`\n}\n\n/**\n * Search a job's files, in order, for the lines its pattern matches,\n * stopping at the first match past the limit, which says there are more.\n * The search worker runs this, and the tests call it on the main thread,\n * where Stryker can switch its mutants on.\n */\nexport async function search_files(job: SearchJob): Promise<SearchResult> {\n const regex = new RegExp(job.pattern)\n const matches: SearchMatch[] = []\n for (const file of await files_of(job)) {\n for (const [index, line] of lines_of(await file_text(join(job.base, file))).entries()) {\n const found = regex.exec(line)\n if (found === null) continue\n if (matches.length === job.limit) return { matches, more: true }\n matches.push({ file, line: index + 1, text: excerpt(line, found.index) })\n }\n }\n return { matches, more: false }\n}\n\n/**\n * Run one job in a search worker. The turn's abort and the budget each\n * terminate the thread, mid-match if need be, which nothing could do to a\n * pattern running on the main thread. However the search ends, the abort\n * listener and the budget's timer go with it.\n */\nasync function in_worker(job: SearchJob, budget_ms: number, abort: AbortSignal): Promise<SearchResult> {\n abort.throwIfAborted()\n const worker = new Worker(SEARCH_WORKER, { workerData: job })\n const { promise, resolve, reject } = Promise.withResolvers<SearchResult>()\n const stop = (reason: unknown): void => {\n void worker.terminate()\n reject(reason)\n }\n const on_abort = (): void => {\n stop(abort.reason)\n }\n const over_budget = new Error(\n `search stopped after ${budget_ms / 1000} s without finishing: the pattern may backtrack without end, ` +\n 'as nested quantifiers such as (a+)+ can, or there may be too much to search; ' +\n 'simplify the pattern, or narrow path or glob',\n )\n const budget = setTimeout(stop, budget_ms, over_budget)\n abort.addEventListener('abort', on_abort)\n worker.once('message', resolve)\n worker.once('error', reject)\n try {\n return await promise\n } finally {\n clearTimeout(budget)\n abort.removeEventListener('abort', on_abort)\n }\n}\n\n/**\n * The matches as the model reads them, one `path:line: text` to a line, and\n * a note when the search stopped at its limit.\n */\nfunction report(session: AcpSession, base: string, request: SearchRequest, result: SearchResult): string {\n if (result.matches.length === 0) {\n return `no lines match ${request.pattern} under ${request.path} in files matching ${request.glob}`\n }\n const lines = result.matches.map(\n (match) => `${shown_path(session, join(base, match.file))}:${match.line}: ${match.text}`,\n )\n if (result.more) {\n lines.push('', `[the first ${result.matches.length} matches; narrow the pattern, path, or glob to see the rest]`)\n }\n return lines.join('\\n')\n}\n\n/**\n * The `search` tool for one session: the lines under a path in its\n * workspace that match a regular expression, skipping binary files and the\n * `ignore` names, at most MATCH_LIMIT per call, each search in a worker\n * that the turn's abort and `budget_ms` can terminate.\n */\nexport function search_tool(session: AcpSession, ignore: ReadonlyArray<string>, budget_ms: number): Tool {\n return {\n name: 'search',\n description: [\n `Search the workspace's files for lines that match a regular expression, at most ${MATCH_LIMIT} per call,`,\n 'each shown as path:line: text; a path under the workspace root is shown relative to it.',\n 'The pattern is a JavaScript regular expression matched against one line at a time; write (?i:...) for a part that ignores case.',\n 'path (default: the workspace root) is the directory to search, or a single file.',\n 'glob picks the files: without a slash it matches a file name at any depth (*.ts, *.{ts,tsx}),',\n 'and with one it matches the path under path (src/**/*.ts).',\n 'As in a shell, * and ** skip names that start with a dot, so name the dot to search hidden files (.github/**/*).',\n ignore.length === 0 ? 'Skips binary files.' : `Skips binary files and ${ignore.join(', ')}.`,\n ].join(' '),\n input_schema: json_schema_to_standard({\n type: 'object',\n properties: {\n pattern: { type: 'string', description: 'A JavaScript regular expression, such as function\\\\s+\\\\w+' },\n path: {\n type: 'string',\n description: 'The directory or file to search, absolute or relative to the workspace root; default: the root',\n },\n glob: { type: 'string', description: `Which files to search, such as *.ts or src/**/*.ts; default: ${ALL_FILES}` },\n },\n required: ['pattern'],\n additionalProperties: false,\n }),\n execute: async (input, ctx) => {\n const request = search_request(input)\n const base = await contain(session, request.path)\n const info = await stat(base.real)\n if (!info.isDirectory() && !info.isFile()) {\n throw new Error(`${request.path} isn't a directory or a regular file, so search can't read it`)\n }\n const job: SearchJob = {\n base: base.real,\n directory: info.isDirectory(),\n pattern: request.pattern,\n glob: walk_glob(request.glob),\n ignore,\n limit: MATCH_LIMIT,\n }\n return report(session, base.path, request, await in_worker(job, budget_ms, ctx.abort))\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAM,0BAAgC,IAAI,IAAI,CAAC,UAAU,SAAS,CAAC;;;;;;AAOnE,MAAM,gBAAgB;;;;;AAMtB,SAAgB,WAAW,KAAuB;CAChD,OAAO,QAAQ,IAAI,OAAO,GAAG,GAAG,MAAM;AACxC;;;;;;AAOA,eAAe,aAAa,MAA+B;CACzD,IAAI,CAAC,WAAW,IAAI,GAClB,MAAM,IAAI,MAAM,sBAAsB,KAAK,0DAA0D;CAEvG,MAAM,OAAO,MAAM,SAAS,IAAI,CAAC,CAAC,OAAO,QAAiB;EACxD,MAAM,IAAI,MACR,sBAAsB,KAAK,oBAAoB,OAAO,WAAW,GAAG,CAAC,EAAE,iDACzE;CACF,CAAC;CACD,IAAI,EAAE,MAAM,KAAK,IAAI,EAAA,CAAG,YAAY,GAClC,MAAM,IAAI,MAAM,sBAAsB,KAAK,8CAA8C;CAE3F,OAAO;AACT;;;;;;AAOA,eAAsB,cAAc,OAAiD;CACnF,OAAO,QAAQ,IAAI,MAAM,IAAI,YAAY,CAAC;AAC5C;;;;;AAMA,SAAS,UAAU,MAAc,QAAyB;CACxD,OAAO,WAAW,QAAQ,OAAO,WAAW,KAAK,SAAS,GAAG,IAAI,OAAO,GAAG,OAAO,KAAK;AACzF;;;;;AAMA,eAAe,YAAY,MAA2C;CACpE,OAAO,SAAS,IAAI,CAAC,CAAC,YAAY,KAAA,CAAS;AAC7C;;;;;;;AAQA,eAAe,UAAU,MAAc,WAAoC;CACzE,IAAI;EACF,OAAO,MAAM,SAAS,IAAI;CAC5B,SAAS,KAAc;EACrB,IAAI,CAAC,QA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;EACL,MAAM;EACN,aAAa;GACX,mFAAmF,YAAY;GAC/F;GACA;GACA;GACA;GACA;GACA;GACA,OAAO,WAAW,IAAI,wBAAwB,0BAA0B,OAAO,KAAK,IAAI,EAAE;EAC5F,CAAC,CAAC,KAAK,GAAG;EACV,cAAc,wBAAwB;GACpC,MAAM;GACN,YAAY;IACV,SAAS;KAAE,MAAM;KAAU,aAAa;IAA4D;IACpG,MAAM;KACJ,MAAM;KACN,aAAa;IACf;IACA,MAAM;KAAE,MAAM;KAAU,aAAa,gEAAgE;IAAY;GACnH;GACA,UAAU,CAAC,SAAS;GACpB,sBAAsB;EACxB,CAAC;EACD,SAAS,OAAO,OAAO,QAAQ;GAC7B,MAAM,UAAU,eAAe,KAAK;GACpC,MAAM,OAAO,MAAM,QAAQ,SAAS,QAAQ,IAAI;GAChD,MAAM,OAAO,MAAM,KAAK,KAAK,IAAI;GACjC,IAAI,CAAC,KAAK,YAAY,KAAK,CAAC,KAAK,OAAO,GACtC,MAAM,IAAI,MAAM,GAAG,QAAQ,KAAK,8DAA8D;GAEhG,MAAM,MAAiB;IACrB,MAAM,KAAK;IACX,WAAW,KAAK,YAAY;IAC5B,SAAS,QAAQ;IACjB,MAAM,UAAU,QAAQ,IAAI;IAC5B;IACA,OAAO;GACT;GACA,OAAO,OAAO,SAAS,KAAK,MAAM,SAAS,MAAM,UAAU,KAAK,WAAW,IAAI,KAAK,CAAC;EACvF;CACF;AACF"}
|
package/dist/search_worker.js
CHANGED
package/dist/testing.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { n as CheckpointStore } from "./types-CPqLZOEr.js";
|
|
2
|
-
import {
|
|
2
|
+
import { A as ToolCallRecord, P as UsageTotals, a as Engine, c as FinishReason, l as GenerateOptions, u as GenerateResult } from "./types-De-TVQxS.js";
|
|
3
3
|
//#region src/testing/engine_from_generate.d.ts
|
|
4
4
|
/**
|
|
5
5
|
* Build an `Engine` whose only live member is the supplied `generate`.
|
package/dist/testing.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { k as aborted_error } from "./core-CDrz0NM1.js";
|
|
2
|
-
import "./engine-
|
|
3
|
-
import {
|
|
2
|
+
import "./engine-ha9xmgwE.js";
|
|
3
|
+
import { O as schema_validation_error } from "./leading_system-DfJLqpGi.js";
|
|
4
4
|
//#region src/testing/engine_from_generate.ts
|
|
5
5
|
/**
|
|
6
6
|
* Build an `Engine` whose only live member is the supplied `generate`.
|
|
@@ -76,6 +76,7 @@ type ProviderTransport = 'ai_sdk' | 'native';
|
|
|
76
76
|
type EffortTranslation = {
|
|
77
77
|
provider_options: Record<string, Record<string, unknown>>;
|
|
78
78
|
effort_ignored: boolean;
|
|
79
|
+
reasoning?: Exclude<EffortLevel, 'none'>;
|
|
79
80
|
};
|
|
80
81
|
type ProviderCapability = 'text' | 'tools' | 'schema' | 'streaming' | 'image_input' | 'reasoning' | 'structured_output';
|
|
81
82
|
type RawProviderUsage = {
|
|
@@ -96,6 +97,7 @@ type RawProviderUsage = {
|
|
|
96
97
|
type AiSdkProviderAdapter = {
|
|
97
98
|
readonly kind: 'ai_sdk';
|
|
98
99
|
readonly name: string;
|
|
100
|
+
readonly metadata_key?: string;
|
|
99
101
|
readonly build_model: (model_id: string) => Promise<unknown>;
|
|
100
102
|
readonly translate_effort: (effort: EffortLevel) => EffortTranslation;
|
|
101
103
|
readonly normalize_usage: (raw: RawProviderUsage | undefined) => UsageTotals;
|
|
@@ -249,6 +251,12 @@ type StepRecord = {
|
|
|
249
251
|
*/
|
|
250
252
|
provider_reported?: Record<string, unknown>;
|
|
251
253
|
};
|
|
254
|
+
/**
|
|
255
|
+
* Provider-specific data on a content part, keyed by provider name: the AI
|
|
256
|
+
* SDK's own `providerOptions` shape, and the shape the call-level
|
|
257
|
+
* `provider_options` takes too.
|
|
258
|
+
*/
|
|
259
|
+
type ProviderOptions = Readonly<Record<string, Readonly<Record<string, unknown>>>>;
|
|
252
260
|
/**
|
|
253
261
|
* A part's `provider_options` reaches the AI SDK as that part's
|
|
254
262
|
* `providerOptions`, keyed by provider name like the call-level field. It is
|
|
@@ -260,21 +268,36 @@ type StepRecord = {
|
|
|
260
268
|
type UserContentPart = {
|
|
261
269
|
type: 'text';
|
|
262
270
|
text: string;
|
|
263
|
-
provider_options?:
|
|
271
|
+
provider_options?: ProviderOptions;
|
|
264
272
|
} | {
|
|
265
273
|
type: 'image';
|
|
266
274
|
image: Uint8Array | string;
|
|
267
275
|
media_type?: string;
|
|
268
|
-
provider_options?:
|
|
276
|
+
provider_options?: ProviderOptions;
|
|
269
277
|
};
|
|
278
|
+
/**
|
|
279
|
+
* An assistant turn's parts, in the order the provider sent them. A part's
|
|
280
|
+
* `provider_options` holds the data its provider wants back on the next
|
|
281
|
+
* request (a thinking block's signature, Gemini's thought signature on a tool
|
|
282
|
+
* call), keyed by provider name. Each adapter sends back only the reasoning
|
|
283
|
+
* parts carrying its own key, so a `fallback` never hands one vendor's
|
|
284
|
+
* signature to another.
|
|
285
|
+
*/
|
|
270
286
|
type AssistantContentPart = {
|
|
271
287
|
type: 'text';
|
|
272
288
|
text: string;
|
|
289
|
+
provider_options?: ProviderOptions;
|
|
273
290
|
} | {
|
|
274
291
|
type: 'tool_call';
|
|
275
292
|
id: string;
|
|
276
293
|
name: string;
|
|
277
294
|
input: unknown;
|
|
295
|
+
provider_options?: ProviderOptions;
|
|
296
|
+
} | {
|
|
297
|
+
type: 'reasoning';
|
|
298
|
+
/** The thinking the model showed, or '' when it showed none (encrypted, redacted, or omitted). */
|
|
299
|
+
text: string;
|
|
300
|
+
provider_options?: ProviderOptions;
|
|
278
301
|
};
|
|
279
302
|
type Message = {
|
|
280
303
|
role: 'system';
|
|
@@ -382,6 +405,22 @@ type TurnResult = {
|
|
|
382
405
|
}>;
|
|
383
406
|
readonly finish_reason: FinishReason;
|
|
384
407
|
readonly usage: UsageTotals;
|
|
408
|
+
/**
|
|
409
|
+
* The turn's parts in the order the provider sent them, with the data it
|
|
410
|
+
* wants back. An adapter sets it only when the turn has a reasoning part or
|
|
411
|
+
* a part carrying provider data, and leaves it out otherwise, so every
|
|
412
|
+
* other turn stays as it was. The tool loop builds the assistant message
|
|
413
|
+
* from it when present; `text` and `tool_calls` stay the fields everything
|
|
414
|
+
* else reads.
|
|
415
|
+
*/
|
|
416
|
+
readonly content?: ReadonlyArray<AssistantContentPart>;
|
|
417
|
+
/**
|
|
418
|
+
* What the provider says this turn cost, in US dollars, for a provider that
|
|
419
|
+
* reports its charge on the response (OpenRouter does). The loop records it
|
|
420
|
+
* in place of a pricing-table estimate, since it is what was charged. Absent
|
|
421
|
+
* when the provider reported no cost.
|
|
422
|
+
*/
|
|
423
|
+
readonly reported_cost_usd?: number;
|
|
385
424
|
/**
|
|
386
425
|
* Stamped by the engine's retry wrapper around the successful attempt, not
|
|
387
426
|
* by adapters: an adapter-returned TurnResult never carries one, and the
|
|
@@ -682,5 +721,5 @@ type Engine = {
|
|
|
682
721
|
dispose: () => Promise<void>;
|
|
683
722
|
};
|
|
684
723
|
//#endregion
|
|
685
|
-
export {
|
|
686
|
-
//# sourceMappingURL=types-
|
|
724
|
+
export { ToolCallRecord as A, ProviderAdapter as B, RetryPolicy as C, Tool as D, StreamChunk as E, UserContentPart as F, default_normalize_usage as G, ProviderFactory as H, AiSdkProviderAdapter as I, ClaudeCliProviderReported as K, EffortTranslation as L, TurnRequest as M, TurnResult as N, ToolApprovalHandler as O, UsageTotals as P, ExternalAgentAdapter as R, RetryFailureKind as S, StepTiming as T, ProviderTransport as U, ProviderCapability as V, RawProviderUsage as W, PricingTable as _, Engine as a, ProviderOptions as b, FinishReason as c, GenerateTiming as d, Message as f, Pricing as g, PrepareStepResult as h, EffortLevel as i, ToolExecContext as j, ToolApprovalRequest as k, GenerateOptions as l, PrepareStepHook as m, AssistantContentPart as n, EngineConfig as o, PrepareStepContext as p, CostBreakdown as r, EngineDefaults as s, AiSdkTelemetrySettings as t, GenerateResult as u, ProviderConfigMap as v, StepRecord as w, ResolvedModel as x, ProviderInit as y, NativeProviderAdapter as z };
|
|
725
|
+
//# sourceMappingURL=types-De-TVQxS.d.ts.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "fascicle",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.0",
|
|
4
4
|
"description": "Compose agents like plain values. A TypeScript toolkit that wires LLM calls, tools, and functions into typed steps over eight providers. No framework, no ambient state.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agents",
|