@mikode13/harness 7.0.0 → 9.0.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/README.md +14 -8
- package/dist/engines/claude/infrastructure/model/claudeAgent.js +10 -3
- package/dist/engines/claude/infrastructure/model/claudeAgent.js.map +1 -1
- package/dist/factory/infrastructure/agentFactory.js +1 -1
- package/dist/factory/infrastructure/agentFactory.js.map +1 -1
- package/dist/factory/infrastructure/agentLLMFactory.d.ts +5 -5
- package/dist/factory/infrastructure/agentLLMFactory.js +16 -13
- package/dist/factory/infrastructure/agentLLMFactory.js.map +1 -1
- package/dist/llm/infrastructure/claudeLLMClient.js +17 -33
- package/dist/llm/infrastructure/claudeLLMClient.js.map +1 -1
- package/dist/llm/infrastructure/claudeModelIds.d.ts +11 -0
- package/dist/llm/infrastructure/claudeModelIds.js +12 -0
- package/dist/llm/infrastructure/claudeModelIds.js.map +1 -0
- package/dist/tools/infrastructure/fileTools.d.ts +3 -2
- package/dist/tools/infrastructure/fileTools.js +7 -6
- package/dist/tools/infrastructure/fileTools.js.map +1 -1
- package/dist/tools/infrastructure/trackedReadFile.d.ts +5 -0
- package/dist/tools/infrastructure/trackedReadFile.js +21 -1
- package/dist/tools/infrastructure/trackedReadFile.js.map +1 -1
- package/dist/tools/infrastructure/workspaceTools.d.ts +23 -1
- package/dist/tools/infrastructure/workspaceTools.js +53 -1
- package/dist/tools/infrastructure/workspaceTools.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fileTools.js","sourceRoot":"","sources":["../../../src/tools/infrastructure/fileTools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAG1C,OAAO,EACN,qBAAqB,EACrB,iBAAiB,GACjB,MAAM,gDAAgD,CAAC;A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ASG;AACH,MAAM,UAAU,YAAY,CAC3B,QAAgC,EAChC,SAA0B;IAE1B,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,SAAS,CAAC;IACrD,MAAM,CAAC,SAAS,EAAE,UAAU,CAAC,GAAG,oBAAoB,CAAC,IAAI,CAAC,CAAC,MAAM,CAChE,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,WAAW,IAAI,IAAI,CAAC,IAAI,KAAK,YAAY,CAC/D,CAAC;IACF,MAAM,OAAO,GAAgB,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC;IACxF,MAAM,QAAQ,GAAG,qBAAqB,CAAC,MAAM,CAAC,CAAC;IAC/C,IAAI,CAAC,QAAQ;QAAE,OAAO,CAAC,GAAG,OAAO,EAAE,QAAQ,CAAC,CAAC;IAC7C,IAAI,QAAQ,KAAK,QAAQ;QAAE,OAAO,CAAC,GAAG,OAAO,EAAE,QAAQ,EAAE,oBAAoB,CAAC,MAAM,CAAC,CAAC,CAAC;IACvF,OAAO;QACN,GAAG,OAAO;QACV,oBAAoB,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;QACzD,oBAAoB,CAAC,MAAM,CAAC;KAC5B,CAAC;AACH,CAAC","sourcesContent":["import { mkdir, realpath } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport type { ToolDefinition } from '#src/llm/domain/tool';\nimport type { RecoveryStore } from '#src/recovery/domain/recoveryStore';\nimport {\n\tdefaultStateDirectory,\n\tFileRecoveryStore,\n} from '#src/recovery/infrastructure/fileRecoveryStore';\nimport { InvalidAgentConfigError, UnrecoverableError } from '#src/shared/domain/errors';\nimport type { ILogger } from '#src/shared/domain/logger';\nimport { describeFailure } from '#src/shared/domain/providerFailure';\nimport type { AccessPolicy, WorkspaceRoot } from '../domain/accessPolicy.ts';\nimport type { Commands, Formatter } from '../domain/commands.ts';\nimport type { AgentTool } from '../domain/preparedCall.ts';\nimport type { Workspace } from '../domain/workspace.ts';\nimport type { CoveredFiles } from './commandCheckpoint.ts';\nimport { createCommandTool } from './commandTool.ts';\nimport { chooseWorkspace } from './createWorkspace.ts';\nimport { createApplyPatchTool, createDeleteFileTool, createTextEditorTool } from './editFormats.ts';\nimport { FileFormatter } from './fileFormatter.ts';\nimport { GitIgnoreRules } from './gitIgnoreRules.ts';\nimport { PolicyWorkspace } from './policyWorkspace.ts';\nimport { RootsAccessPolicy, type SecretRules } from './rootsAccessPolicy.ts';\nimport { createTrackedReadFile } from './trackedReadFile.ts';\nimport { createWorkspaceTools } from './workspaceTools.ts';\nimport { WorkspaceWrites } from './workspaceWrites.ts';\n\n/** The folders an agent works on, and what it may do in each. */\nexport interface WorkspaceOptions {\n\t/**\n\t * Each folder `read` or `write`. The first is where a relative path starts, and the one whose\n\t * history of runs is kept; a write to another root is recorded in it too.\n\t */\n\troots: WorkspaceRoot[];\n\t/** More files to keep closed as secrets, and exact files to open. */\n\tsecrets?: SecretRules;\n\t/**\n\t * Where the history of runs is kept, relative to the working directory if not absolute.\n\t * Defaults to the platform's state directory. No tool may reach it, even inside a root.\n\t */\n\tstateDirectory?: string;\n}\n\ndeclare const fileToolBrand: unique symbol;\n\n/**\n * A tool the harness builds for files, from `createFileTools`. It goes to an agent from\n * `createLLMAgent` beside the consumer's own tools; what it does inside is the harness's.\n */\nexport type FileTool = ToolDefinition & { readonly [fileToolBrand]: true };\n\n/** What the file tools of one workspace share: one policy, one history, one record of writes. */\nexport interface OpenedWorkspace {\n\treadonly roots: WorkspaceRoot[];\n\treadonly policy: AccessPolicy;\n\treadonly store: RecoveryStore;\n\t/** The read side, with the policy's word on every path. */\n\treadonly read: Workspace;\n\treadonly writes: WorkspaceWrites;\n\treadonly writable: boolean;\n\t/** The real path of the first root. */\n\treadonly base: string;\n\t/** What a command's checkpoint captures and compares: see `CoveredFiles`. */\n\treadonly covered: CoveredFiles;\n}\n\n/**\n * Where a workspace's history is kept, as one real path: made if missing, then resolved, links\n * included. The store and the access policy must name the same folder, or a tool could reach the\n * history the policy means to protect. A relative path is from the working directory.\n *\n * @throws {UnrecoverableError} when the folder cannot be made or reached.\n */\nexport async function stateDirectoryOf({ stateDirectory }: WorkspaceOptions): Promise<string> {\n\tconst directory = resolve(stateDirectory ?? defaultStateDirectory());\n\ttry {\n\t\tawait mkdir(directory, { recursive: true, mode: 0o700 });\n\t\treturn await realpath(directory);\n\t} catch (error) {\n\t\tthrow new UnrecoverableError('The folder for the workspace history could not be made', {\n\t\t\tcause: describeFailure(error),\n\t\t});\n\t}\n}\n\n/**\n * The recovery store of a workspace, at its first root.\n *\n * @throws {InvalidAgentConfigError} when the workspace has no root.\n * @throws {UnrecoverableError} when the store cannot be opened.\n */\nexport async function openStore(\n\tworkspace: WorkspaceOptions,\n\tdirectory: string,\n): Promise<RecoveryStore> {\n\tconst [first] = workspace.roots;\n\tif (!first) throw new InvalidAgentConfigError('A workspace needs at least one root');\n\ttry {\n\t\treturn await FileRecoveryStore.open({ root: resolve(first.path), directory });\n\t} catch (error) {\n\t\tthrow new UnrecoverableError('The workspace history could not be opened', {\n\t\t\tcause: describeFailure(error),\n\t\t});\n\t}\n}\n\n/**\n * Opens what the file tools of one workspace share. With `formatter`, its edits format each file\n * they write.\n *\n * @throws {InvalidAgentConfigError} for a workspace with no root, or an invalid formatter.\n */\nexport async function openWorkspace(\n\tworkspace: WorkspaceOptions,\n\tlogger: ILogger,\n\t{ formatter }: { formatter?: Formatter } = {},\n): Promise<OpenedWorkspace> {\n\tconst { roots, secrets } = workspace;\n\tconst stateDirectory = await stateDirectoryOf(workspace);\n\tconst policy = await RootsAccessPolicy.create({\n\t\troots,\n\t\t...(secrets ? { secrets } : {}),\n\t\tignoreRules: new GitIgnoreRules(),\n\t\t// The history holds the source a run replaced: no tool may read or write it.\n\t\tprotectedPaths: [stateDirectory],\n\t});\n\tconst store = await openStore(workspace, stateDirectory);\n\t// Real, as the policy's paths are, so a file's path can be judged by name.\n\tconst root = await realpath(resolve(roots[0]?.path ?? '.'));\n\tconst inner = await chooseWorkspace({\n\t\troot,\n\t\tlogger,\n\t\t// Left out before a search counts or stores a match, so no total, limit or error can tell\n\t\t// that a secret matched. The policy still decides each path after it.\n\t\thidden: path => policy.hidesFromReading(join(root, path)),\n\t});\n\tconst read = new PolicyWorkspace({ inner, policy });\n\tconst fileFormatter =\n\t\tformatter && (await FileFormatter.create({ formatter, policy, base: root }));\n\treturn {\n\t\troots,\n\t\tpolicy,\n\t\tstore,\n\t\tread,\n\t\twrites: new WorkspaceWrites({\n\t\t\tpolicy,\n\t\t\tstore,\n\t\t\t...(fileFormatter ? { formatter: fileFormatter } : {}),\n\t\t}),\n\t\twritable: roots.some(({ access }) => access === 'write'),\n\t\tbase: root,\n\t\tcovered: coveredFiles(roots, policy, logger),\n\t};\n}\n\n/**\n * Lists every file of the `write` roots that `.gitignore` does not exclude, less what the policy\n * closes to writing by name, before anything is read. Each root is listed by its own program,\n * opened on the first listing.\n */\nfunction coveredFiles(\n\troots: WorkspaceRoot[],\n\tpolicy: RootsAccessPolicy,\n\tlogger: ILogger,\n): CoveredFiles {\n\tlet listers: Promise<{ root: string; workspace: Workspace }[]> | undefined;\n\tconst open = () =>\n\t\tPromise.all(\n\t\t\troots\n\t\t\t\t.filter(({ access }) => access === 'write')\n\t\t\t\t.map(async ({ path }) => {\n\t\t\t\t\tconst root = await realpath(resolve(path));\n\t\t\t\t\tconst workspace = await chooseWorkspace({\n\t\t\t\t\t\troot,\n\t\t\t\t\t\tlogger,\n\t\t\t\t\t\thidden: relativePath => policy.closedToWriting(join(root, relativePath)),\n\t\t\t\t\t});\n\t\t\t\t\treturn { root, workspace };\n\t\t\t\t}),\n\t\t);\n\n\treturn async signal => {\n\t\tlisters ??= open().catch((error: unknown) => {\n\t\t\t// Not kept: the next command tries again.\n\t\t\tlisters = undefined;\n\t\t\tthrow error;\n\t\t});\n\t\tconst files = new Set<string>();\n\t\tfor (const { root, workspace } of await listers) {\n\t\t\tconst listed = await workspace.listFiles({ limit: Number.MAX_SAFE_INTEGER }, signal);\n\t\t\tfor (const path of listed.files) files.add(join(root, path));\n\t\t}\n\t\treturn [...files];\n\t};\n}\n\n/**\n * `runCommand` over an opened workspace: see `createCommandTool`.\n *\n * @throws {InvalidAgentConfigError} for an invalid configuration, or on Windows.\n */\nexport function commandToolFor(workspace: OpenedWorkspace, commands: Commands): Promise<AgentTool> {\n\tconst { policy, writes, covered, base } = workspace;\n\treturn createCommandTool({ commands, policy, writes, covered, base });\n}\n\n/**\n * The file tools of a provider's executor, over one workspace. Every one reads through the access\n * policy, and an edit starts only from a version the conversation read.\n *\n * - OpenAI: `listFiles`, `searchText`, `readFile`, and its native `apply_patch`.\n * - Anthropic: `listFiles`, `searchText`, its native text editor, whose `view` reads, and\n * `delete_file`.\n *\n * Without a `write` root they only read: `readFile` in place of the editor and the patch.\n */\nexport function fileToolsFor(\n\tprovider: 'anthropic' | 'openai',\n\tworkspace: OpenedWorkspace,\n): AgentTool[] {\n\tconst { policy, read, writes, writable } = workspace;\n\tconst [listFiles, searchText] = createWorkspaceTools(read).filter(\n\t\ttool => tool.name === 'listFiles' || tool.name === 'searchText',\n\t);\n\tconst finding: AgentTool[] = [listFiles, searchText].filter(tool => tool !== undefined);\n\tconst readFile = createTrackedReadFile(policy);\n\tif (!writable) return [...finding, readFile];\n\tif (provider === 'openai') return [...finding, readFile, createApplyPatchTool(writes)];\n\treturn [\n\t\t...finding,\n\t\tcreateTextEditorTool({ writes, policy, workspace: read }),\n\t\tcreateDeleteFileTool(writes),\n\t];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"fileTools.js","sourceRoot":"","sources":["../../../src/tools/infrastructure/fileTools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAA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AAO,iBAAiB,CAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;AACvE,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,YAAY,CAC3B,QAAgC,EAChC,SAA0B;IAE1B,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,SAAS,CAAC;IACrD,MAAM,CAAC,SAAS,EAAE,UAAU,CAAC,GAAG,oBAAoB,CAAC,IAAI,CAAC,CAAC,MAAM,CAChE,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,WAAW,IAAI,IAAI,CAAC,IAAI,KAAK,YAAY,CAC/D,CAAC;IACF,MAAM,OAAO,GAAgB,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC;IACxF,MAAM,OAAO,GAAG,CAAC,qBAAqB,CAAC,MAAM,CAAC,EAAE,sBAAsB,CAAC,MAAM,CAAC,CAAC,CAAC;IAChF,IAAI,CAAC,QAAQ;QAAE,OAAO,CAAC,GAAG,OAAO,EAAE,GAAG,OAAO,CAAC,CAAC;IAC/C,IAAI,QAAQ,KAAK,QAAQ;QAAE,OAAO,CAAC,GAAG,OAAO,EAAE,GAAG,OAAO,EAAE,oBAAoB,CAAC,MAAM,CAAC,CAAC,CAAC;IACzF,OAAO;QACN,GAAG,OAAO;QACV,oBAAoB,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;QACzD,oBAAoB,CAAC,MAAM,CAAC;KAC5B,CAAC;AACH,CAAC","sourcesContent":["import { mkdir, realpath } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport type { ToolDefinition } from '#src/llm/domain/tool';\nimport type { RecoveryStore } from '#src/recovery/domain/recoveryStore';\nimport {\n\tdefaultStateDirectory,\n\tFileRecoveryStore,\n} from '#src/recovery/infrastructure/fileRecoveryStore';\nimport { InvalidAgentConfigError, UnrecoverableError } from '#src/shared/domain/errors';\nimport type { ILogger } from '#src/shared/domain/logger';\nimport { describeFailure } from '#src/shared/domain/providerFailure';\nimport type { AccessPolicy, WorkspaceRoot } from '../domain/accessPolicy.ts';\nimport type { Commands, Formatter } from '../domain/commands.ts';\nimport type { AgentTool } from '../domain/preparedCall.ts';\nimport type { Workspace } from '../domain/workspace.ts';\nimport type { CoveredFiles } from './commandCheckpoint.ts';\nimport { createCommandTool } from './commandTool.ts';\nimport { chooseWorkspace } from './createWorkspace.ts';\nimport { createApplyPatchTool, createDeleteFileTool, createTextEditorTool } from './editFormats.ts';\nimport { FileFormatter } from './fileFormatter.ts';\nimport { GitIgnoreRules } from './gitIgnoreRules.ts';\nimport { PolicyWorkspace } from './policyWorkspace.ts';\nimport { RootsAccessPolicy, type SecretRules } from './rootsAccessPolicy.ts';\nimport { createTrackedReadFile, createTrackedReadFiles } from './trackedReadFile.ts';\nimport { createWorkspaceTools } from './workspaceTools.ts';\nimport { WorkspaceWrites } from './workspaceWrites.ts';\n\n/** The folders an agent works on, and what it may do in each. */\nexport interface WorkspaceOptions {\n\t/**\n\t * Each folder `read` or `write`. The first is where a relative path starts, and the one whose\n\t * history of runs is kept; a write to another root is recorded in it too.\n\t */\n\troots: WorkspaceRoot[];\n\t/** More files to keep closed as secrets, and exact files to open. */\n\tsecrets?: SecretRules;\n\t/**\n\t * Where the history of runs is kept, relative to the working directory if not absolute.\n\t * Defaults to the platform's state directory. No tool may reach it, even inside a root.\n\t */\n\tstateDirectory?: string;\n}\n\ndeclare const fileToolBrand: unique symbol;\n\n/**\n * A tool the harness builds for files, from `createFileTools`. It goes to an agent from\n * `createLLMAgent` beside the consumer's own tools; what it does inside is the harness's.\n */\nexport type FileTool = ToolDefinition & { readonly [fileToolBrand]: true };\n\n/** What the file tools of one workspace share: one policy, one history, one record of writes. */\nexport interface OpenedWorkspace {\n\treadonly roots: WorkspaceRoot[];\n\treadonly policy: AccessPolicy;\n\treadonly store: RecoveryStore;\n\t/** The read side, with the policy's word on every path. */\n\treadonly read: Workspace;\n\treadonly writes: WorkspaceWrites;\n\treadonly writable: boolean;\n\t/** The real path of the first root. */\n\treadonly base: string;\n\t/** What a command's checkpoint captures and compares: see `CoveredFiles`. */\n\treadonly covered: CoveredFiles;\n}\n\n/**\n * Where a workspace's history is kept, as one real path: made if missing, then resolved, links\n * included. The store and the access policy must name the same folder, or a tool could reach the\n * history the policy means to protect. A relative path is from the working directory.\n *\n * @throws {UnrecoverableError} when the folder cannot be made or reached.\n */\nexport async function stateDirectoryOf({ stateDirectory }: WorkspaceOptions): Promise<string> {\n\tconst directory = resolve(stateDirectory ?? defaultStateDirectory());\n\ttry {\n\t\tawait mkdir(directory, { recursive: true, mode: 0o700 });\n\t\treturn await realpath(directory);\n\t} catch (error) {\n\t\tthrow new UnrecoverableError('The folder for the workspace history could not be made', {\n\t\t\tcause: describeFailure(error),\n\t\t});\n\t}\n}\n\n/**\n * The recovery store of a workspace, at its first root.\n *\n * @throws {InvalidAgentConfigError} when the workspace has no root.\n * @throws {UnrecoverableError} when the store cannot be opened.\n */\nexport async function openStore(\n\tworkspace: WorkspaceOptions,\n\tdirectory: string,\n): Promise<RecoveryStore> {\n\tconst [first] = workspace.roots;\n\tif (!first) throw new InvalidAgentConfigError('A workspace needs at least one root');\n\ttry {\n\t\treturn await FileRecoveryStore.open({ root: resolve(first.path), directory });\n\t} catch (error) {\n\t\tthrow new UnrecoverableError('The workspace history could not be opened', {\n\t\t\tcause: describeFailure(error),\n\t\t});\n\t}\n}\n\n/**\n * Opens what the file tools of one workspace share. With `formatter`, its edits format each file\n * they write.\n *\n * @throws {InvalidAgentConfigError} for a workspace with no root, or an invalid formatter.\n */\nexport async function openWorkspace(\n\tworkspace: WorkspaceOptions,\n\tlogger: ILogger,\n\t{ formatter }: { formatter?: Formatter } = {},\n): Promise<OpenedWorkspace> {\n\tconst { roots, secrets } = workspace;\n\tconst stateDirectory = await stateDirectoryOf(workspace);\n\tconst policy = await RootsAccessPolicy.create({\n\t\troots,\n\t\t...(secrets ? { secrets } : {}),\n\t\tignoreRules: new GitIgnoreRules(),\n\t\t// The history holds the source a run replaced: no tool may read or write it.\n\t\tprotectedPaths: [stateDirectory],\n\t});\n\tconst store = await openStore(workspace, stateDirectory);\n\t// Real, as the policy's paths are, so a file's path can be judged by name.\n\tconst root = await realpath(resolve(roots[0]?.path ?? '.'));\n\tconst inner = await chooseWorkspace({\n\t\troot,\n\t\tlogger,\n\t\t// Left out before a search counts or stores a match, so no total, limit or error can tell\n\t\t// that a secret matched. The policy still decides each path after it.\n\t\thidden: path => policy.hidesFromReading(join(root, path)),\n\t});\n\tconst read = new PolicyWorkspace({ inner, policy });\n\tconst fileFormatter =\n\t\tformatter && (await FileFormatter.create({ formatter, policy, base: root }));\n\treturn {\n\t\troots,\n\t\tpolicy,\n\t\tstore,\n\t\tread,\n\t\twrites: new WorkspaceWrites({\n\t\t\tpolicy,\n\t\t\tstore,\n\t\t\t...(fileFormatter ? { formatter: fileFormatter } : {}),\n\t\t}),\n\t\twritable: roots.some(({ access }) => access === 'write'),\n\t\tbase: root,\n\t\tcovered: coveredFiles(roots, policy, logger),\n\t};\n}\n\n/**\n * Lists every file of the `write` roots that `.gitignore` does not exclude, less what the policy\n * closes to writing by name, before anything is read. Each root is listed by its own program,\n * opened on the first listing.\n */\nfunction coveredFiles(\n\troots: WorkspaceRoot[],\n\tpolicy: RootsAccessPolicy,\n\tlogger: ILogger,\n): CoveredFiles {\n\tlet listers: Promise<{ root: string; workspace: Workspace }[]> | undefined;\n\tconst open = () =>\n\t\tPromise.all(\n\t\t\troots\n\t\t\t\t.filter(({ access }) => access === 'write')\n\t\t\t\t.map(async ({ path }) => {\n\t\t\t\t\tconst root = await realpath(resolve(path));\n\t\t\t\t\tconst workspace = await chooseWorkspace({\n\t\t\t\t\t\troot,\n\t\t\t\t\t\tlogger,\n\t\t\t\t\t\thidden: relativePath => policy.closedToWriting(join(root, relativePath)),\n\t\t\t\t\t});\n\t\t\t\t\treturn { root, workspace };\n\t\t\t\t}),\n\t\t);\n\n\treturn async signal => {\n\t\tlisters ??= open().catch((error: unknown) => {\n\t\t\t// Not kept: the next command tries again.\n\t\t\tlisters = undefined;\n\t\t\tthrow error;\n\t\t});\n\t\tconst files = new Set<string>();\n\t\tfor (const { root, workspace } of await listers) {\n\t\t\tconst listed = await workspace.listFiles({ limit: Number.MAX_SAFE_INTEGER }, signal);\n\t\t\tfor (const path of listed.files) files.add(join(root, path));\n\t\t}\n\t\treturn [...files];\n\t};\n}\n\n/**\n * `runCommand` over an opened workspace: see `createCommandTool`.\n *\n * @throws {InvalidAgentConfigError} for an invalid configuration, or on Windows.\n */\nexport function commandToolFor(workspace: OpenedWorkspace, commands: Commands): Promise<AgentTool> {\n\tconst { policy, writes, covered, base } = workspace;\n\treturn createCommandTool({ commands, policy, writes, covered, base });\n}\n\n/**\n * The file tools of a provider's executor, over one workspace. Every one reads through the access\n * policy, and an edit starts only from a version the conversation read.\n *\n * - OpenAI: `listFiles`, `searchText`, `readFile`, `readFiles`, and its native `apply_patch`.\n * - Anthropic: `listFiles`, `searchText`, its native text editor, whose `view` reads, and\n * `delete_file`.\n *\n * Without a `write` root they only read: `readFile` and `readFiles` in place of the editor and\n * the patch.\n */\nexport function fileToolsFor(\n\tprovider: 'anthropic' | 'openai',\n\tworkspace: OpenedWorkspace,\n): AgentTool[] {\n\tconst { policy, read, writes, writable } = workspace;\n\tconst [listFiles, searchText] = createWorkspaceTools(read).filter(\n\t\ttool => tool.name === 'listFiles' || tool.name === 'searchText',\n\t);\n\tconst finding: AgentTool[] = [listFiles, searchText].filter(tool => tool !== undefined);\n\tconst reading = [createTrackedReadFile(policy), createTrackedReadFiles(policy)];\n\tif (!writable) return [...finding, ...reading];\n\tif (provider === 'openai') return [...finding, ...reading, createApplyPatchTool(writes)];\n\treturn [\n\t\t...finding,\n\t\tcreateTextEditorTool({ writes, policy, workspace: read }),\n\t\tcreateDeleteFileTool(writes),\n\t];\n}\n"]}
|
|
@@ -19,3 +19,8 @@ export declare function readTracked({ target, path, from, count, reads, signal,
|
|
|
19
19
|
* and it records the version of the file the model saw, so an edit starts only from it.
|
|
20
20
|
*/
|
|
21
21
|
export declare function createTrackedReadFile(policy: AccessPolicy): PreparingTool;
|
|
22
|
+
/**
|
|
23
|
+
* `readFiles` for an agent that edits: several reads in one call, each as `createTrackedReadFile`
|
|
24
|
+
* makes it, and each recorded. A file the policy refuses is reported in its place.
|
|
25
|
+
*/
|
|
26
|
+
export declare function createTrackedReadFiles(policy: AccessPolicy): PreparingTool;
|
|
@@ -2,7 +2,7 @@ import { createHash } from 'node:crypto';
|
|
|
2
2
|
import { lstat, readFile } from 'node:fs/promises';
|
|
3
3
|
import { isText } from '#src/recovery/domain/runChanges';
|
|
4
4
|
import { definePreparingTool } from "./defineTool.js";
|
|
5
|
-
import { readFileDescription, readFileInput, readFileSummary, readRange, renderLines, } from "./workspaceTools.js";
|
|
5
|
+
import { readEach, readFileDescription, readFileInput, readFilesDescription, readFilesInput, readFileSummary, readFilesSummary, readRange, renderLines, } from "./workspaceTools.js";
|
|
6
6
|
// The same bound as an edit: a file too large to change need not be read whole to track it.
|
|
7
7
|
const maxFileBytes = 5 * 1024 * 1024;
|
|
8
8
|
/**
|
|
@@ -76,4 +76,24 @@ export function createTrackedReadFile(policy) {
|
|
|
76
76
|
},
|
|
77
77
|
});
|
|
78
78
|
}
|
|
79
|
+
/**
|
|
80
|
+
* `readFiles` for an agent that edits: several reads in one call, each as `createTrackedReadFile`
|
|
81
|
+
* makes it, and each recorded. A file the policy refuses is reported in its place.
|
|
82
|
+
*/
|
|
83
|
+
export function createTrackedReadFiles(policy) {
|
|
84
|
+
return definePreparingTool({
|
|
85
|
+
name: 'readFiles',
|
|
86
|
+
description: readFilesDescription,
|
|
87
|
+
input: readFilesInput,
|
|
88
|
+
summarize: readFilesSummary,
|
|
89
|
+
prepare: ({ files }, _signal, { reads }) => Promise.resolve({
|
|
90
|
+
risk: 'safe',
|
|
91
|
+
run: runSignal => readEach(files, async ({ path, fromLine, lineCount }) => {
|
|
92
|
+
const { from, count } = readRange({ fromLine, lineCount });
|
|
93
|
+
const target = await policy.check(path, 'read', runSignal);
|
|
94
|
+
return readTracked({ target, path, from, count, reads, signal: runSignal });
|
|
95
|
+
}, runSignal),
|
|
96
|
+
}),
|
|
97
|
+
});
|
|
98
|
+
}
|
|
79
99
|
//# sourceMappingURL=trackedReadFile.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trackedReadFile.js","sourceRoot":"","sources":["../../../src/tools/infrastructure/trackedReadFile.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,MAAM,EAAE,MAAM,iCAAiC,CAAC;AAIzD,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EACN,mBAAmB,EACnB,aAAa,EACb,eAAe,EACf,SAAS,EACT,WAAW,GACX,MAAM,qBAAqB,CAAC;AAE7B,4FAA4F;AAC5F,MAAM,YAAY,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AAErC;;;GAGG;AACH,SAAS,KAAK,CAAC,IAAY;IAC1B,IAAI,IAAI,KAAK,EAAE;QAAE,OAAO,EAAE,CAAC;IAC3B,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;IAC3F,IAAI,GAAG,CAAC,E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YACxD,OAAO;gBACN,IAAI,EAAE,MAAM;gBACZ,GAAG,EAAE,SAAS,CAAC,EAAE,CAAC,WAAW,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;aACtF,CAAC;QACH,CAAC;KACD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { createHash } from 'node:crypto';\nimport { lstat, readFile } from 'node:fs/promises';\nimport { isText } from '#src/recovery/domain/runChanges';\nimport type { AccessPolicy, AllowedPath } from '../domain/accessPolicy.ts';\nimport type { PreparingTool } from '../domain/preparedCall.ts';\nimport type { RunReads } from '../domain/readRegistry.ts';\nimport { definePreparingTool } from './defineTool.ts';\nimport {\n\treadFileDescription,\n\treadFileInput,\n\treadFileSummary,\n\treadRange,\n\trenderLines,\n} from './workspaceTools.ts';\n\n// The same bound as an edit: a file too large to change need not be read whole to track it.\nconst maxFileBytes = 5 * 1024 * 1024;\n\n/**\n * The lines of a text, split as the diff an edit returns splits them, so their numbers agree: on\n * `\\n`, with a `\\r` before it dropped. A final newline ends the last line; it starts no other.\n */\nfunction lines(text: string): string[] {\n\tif (text === '') return [];\n\tconst all = text.split('\\n').map(line => (line.endsWith('\\r') ? line.slice(0, -1) : line));\n\tif (all.at(-1) === '') all.pop();\n\treturn all;\n}\n\nfunction code(error: unknown): string {\n\treturn (error as NodeJS.ErrnoException).code ?? 'an unknown error';\n}\n\n/**\n * Reads lines `from` to `from + count - 1` of a file the policy allowed, and records the version\n * of the whole file the model saw. The file is read once, so the version recorded is the content\n * shown. A partial read counts: the model saw this version, and can read the rest.\n */\nexport async function readTracked({\n\ttarget,\n\tpath,\n\tfrom,\n\tcount,\n\treads,\n\tsignal,\n}: {\n\ttarget: AllowedPath;\n\tpath: string;\n\tfrom: number;\n\tcount: number;\n\treads: RunReads;\n\tsignal: AbortSignal;\n}): Promise<string> {\n\tsignal.throwIfAborted();\n\tconst stats = await lstat(target.absolute).catch((error: unknown) => {\n\t\tif (code(error) === 'ENOENT') return undefined;\n\t\t// Its own message would name the host path.\n\t\tthrow new Error(`Could not read ${path} (${code(error)})`);\n\t});\n\t// One answer for every file it cannot show, as the read tools give.\n\tif (!stats?.isFile()) throw new Error(`No such file: ${path}`);\n\tif (stats.size > maxFileBytes) {\n\t\tthrow new Error(\n\t\t\t`${path} is larger than ${String(maxFileBytes / 1024 / 1024)} MB, too large to read`,\n\t\t);\n\t}\n\tconst content = await readFile(target.absolute, { signal }).catch((error: unknown) => {\n\t\tsignal.throwIfAborted();\n\t\tthrow new Error(`Could not read ${path} (${code(error)})`);\n\t});\n\tif (!isText(content)) throw new Error(`Not a text file: ${path}`);\n\n\tconst all = lines(content.toString('utf8'));\n\tconst shown = all.slice(from - 1, from - 1 + count);\n\treads.record(target.absolute, createHash('sha256').update(content).digest('hex'));\n\treturn renderLines({\n\t\tpath,\n\t\tlines: shown,\n\t\tfrom,\n\t\ttotalLines: all.length,\n\t\ttruncated: from - 1 + shown.length < all.length,\n\t});\n}\n\n/**\n * `readFile` for an agent that edits: the same tool for the model, through the access policy,\n * and it records the version of the file the model saw, so an edit starts only from it.\n */\nexport function createTrackedReadFile(policy: AccessPolicy): PreparingTool {\n\treturn definePreparingTool({\n\t\tname: 'readFile',\n\t\tdescription: readFileDescription,\n\t\tinput: readFileInput,\n\t\tsummarize: readFileSummary,\n\t\tprepare: async ({ path, fromLine, lineCount }, signal, { reads }) => {\n\t\t\tconst { from, count } = readRange({ fromLine, lineCount });\n\t\t\tconst target = await policy.check(path, 'read', signal);\n\t\t\treturn {\n\t\t\t\trisk: 'safe',\n\t\t\t\trun: runSignal => readTracked({ target, path, from, count, reads, signal: runSignal }),\n\t\t\t};\n\t\t},\n\t});\n}\n"]}
|
|
1
|
+
{"version":3,"file":"trackedReadFile.js","sourceRoot":"","sources":["../../../src/tools/infrastructure/trackedReadFile.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,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AAE,KAAK,EAAE,EAAE,OAAO,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,CAC1C,OAAO,CAAC,OAAO,CAAC;YACf,IAAI,EAAE,MAAM;YACZ,GAAG,EAAE,SAAS,CAAC,EAAE,CAChB,QAAQ,CACP,KAAK,EACL,KAAK,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,SAAS,EAAE,EAAE,EAAE;gBACvC,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,SAAS,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAC,CAAC;gBAC3D,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,CAAC,CAAC;gBAC3D,OAAO,WAAW,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC;YAC7E,CAAC,EACD,SAAS,CACT;SACF,CAAC;KACH,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { createHash } from 'node:crypto';\nimport { lstat, readFile } from 'node:fs/promises';\nimport { isText } from '#src/recovery/domain/runChanges';\nimport type { AccessPolicy, AllowedPath } from '../domain/accessPolicy.ts';\nimport type { PreparingTool } from '../domain/preparedCall.ts';\nimport type { RunReads } from '../domain/readRegistry.ts';\nimport { definePreparingTool } from './defineTool.ts';\nimport {\n\treadEach,\n\treadFileDescription,\n\treadFileInput,\n\treadFilesDescription,\n\treadFilesInput,\n\treadFileSummary,\n\treadFilesSummary,\n\treadRange,\n\trenderLines,\n} from './workspaceTools.ts';\n\n// The same bound as an edit: a file too large to change need not be read whole to track it.\nconst maxFileBytes = 5 * 1024 * 1024;\n\n/**\n * The lines of a text, split as the diff an edit returns splits them, so their numbers agree: on\n * `\\n`, with a `\\r` before it dropped. A final newline ends the last line; it starts no other.\n */\nfunction lines(text: string): string[] {\n\tif (text === '') return [];\n\tconst all = text.split('\\n').map(line => (line.endsWith('\\r') ? line.slice(0, -1) : line));\n\tif (all.at(-1) === '') all.pop();\n\treturn all;\n}\n\nfunction code(error: unknown): string {\n\treturn (error as NodeJS.ErrnoException).code ?? 'an unknown error';\n}\n\n/**\n * Reads lines `from` to `from + count - 1` of a file the policy allowed, and records the version\n * of the whole file the model saw. The file is read once, so the version recorded is the content\n * shown. A partial read counts: the model saw this version, and can read the rest.\n */\nexport async function readTracked({\n\ttarget,\n\tpath,\n\tfrom,\n\tcount,\n\treads,\n\tsignal,\n}: {\n\ttarget: AllowedPath;\n\tpath: string;\n\tfrom: number;\n\tcount: number;\n\treads: RunReads;\n\tsignal: AbortSignal;\n}): Promise<string> {\n\tsignal.throwIfAborted();\n\tconst stats = await lstat(target.absolute).catch((error: unknown) => {\n\t\tif (code(error) === 'ENOENT') return undefined;\n\t\t// Its own message would name the host path.\n\t\tthrow new Error(`Could not read ${path} (${code(error)})`);\n\t});\n\t// One answer for every file it cannot show, as the read tools give.\n\tif (!stats?.isFile()) throw new Error(`No such file: ${path}`);\n\tif (stats.size > maxFileBytes) {\n\t\tthrow new Error(\n\t\t\t`${path} is larger than ${String(maxFileBytes / 1024 / 1024)} MB, too large to read`,\n\t\t);\n\t}\n\tconst content = await readFile(target.absolute, { signal }).catch((error: unknown) => {\n\t\tsignal.throwIfAborted();\n\t\tthrow new Error(`Could not read ${path} (${code(error)})`);\n\t});\n\tif (!isText(content)) throw new Error(`Not a text file: ${path}`);\n\n\tconst all = lines(content.toString('utf8'));\n\tconst shown = all.slice(from - 1, from - 1 + count);\n\treads.record(target.absolute, createHash('sha256').update(content).digest('hex'));\n\treturn renderLines({\n\t\tpath,\n\t\tlines: shown,\n\t\tfrom,\n\t\ttotalLines: all.length,\n\t\ttruncated: from - 1 + shown.length < all.length,\n\t});\n}\n\n/**\n * `readFile` for an agent that edits: the same tool for the model, through the access policy,\n * and it records the version of the file the model saw, so an edit starts only from it.\n */\nexport function createTrackedReadFile(policy: AccessPolicy): PreparingTool {\n\treturn definePreparingTool({\n\t\tname: 'readFile',\n\t\tdescription: readFileDescription,\n\t\tinput: readFileInput,\n\t\tsummarize: readFileSummary,\n\t\tprepare: async ({ path, fromLine, lineCount }, signal, { reads }) => {\n\t\t\tconst { from, count } = readRange({ fromLine, lineCount });\n\t\t\tconst target = await policy.check(path, 'read', signal);\n\t\t\treturn {\n\t\t\t\trisk: 'safe',\n\t\t\t\trun: runSignal => readTracked({ target, path, from, count, reads, signal: runSignal }),\n\t\t\t};\n\t\t},\n\t});\n}\n\n/**\n * `readFiles` for an agent that edits: several reads in one call, each as `createTrackedReadFile`\n * makes it, and each recorded. A file the policy refuses is reported in its place.\n */\nexport function createTrackedReadFiles(policy: AccessPolicy): PreparingTool {\n\treturn definePreparingTool({\n\t\tname: 'readFiles',\n\t\tdescription: readFilesDescription,\n\t\tinput: readFilesInput,\n\t\tsummarize: readFilesSummary,\n\t\tprepare: ({ files }, _signal, { reads }) =>\n\t\t\tPromise.resolve({\n\t\t\t\trisk: 'safe',\n\t\t\t\trun: runSignal =>\n\t\t\t\t\treadEach(\n\t\t\t\t\t\tfiles,\n\t\t\t\t\t\tasync ({ path, fromLine, lineCount }) => {\n\t\t\t\t\t\t\tconst { from, count } = readRange({ fromLine, lineCount });\n\t\t\t\t\t\t\tconst target = await policy.check(path, 'read', runSignal);\n\t\t\t\t\t\t\treturn readTracked({ target, path, from, count, reads, signal: runSignal });\n\t\t\t\t\t\t},\n\t\t\t\t\t\trunSignal,\n\t\t\t\t\t),\n\t\t\t}),\n\t});\n}\n"]}
|
|
@@ -21,6 +21,24 @@ export declare const readFileInput: z.ZodObject<{
|
|
|
21
21
|
fromLine: z.ZodNullable<z.ZodNumber>;
|
|
22
22
|
lineCount: z.ZodNullable<z.ZodNumber>;
|
|
23
23
|
}, z.core.$strip>;
|
|
24
|
+
/** What `readFiles` takes, shared with the harness's own version of it. */
|
|
25
|
+
export declare const readFilesDescription: string;
|
|
26
|
+
export declare const readFilesInput: z.ZodObject<{
|
|
27
|
+
files: z.ZodArray<z.ZodObject<{
|
|
28
|
+
path: z.ZodString;
|
|
29
|
+
fromLine: z.ZodNullable<z.ZodNumber>;
|
|
30
|
+
lineCount: z.ZodNullable<z.ZodNumber>;
|
|
31
|
+
}, z.core.$strip>>;
|
|
32
|
+
}, z.core.$strip>;
|
|
33
|
+
type ReadRequest = z.infer<typeof readFileInput>;
|
|
34
|
+
export declare function readFilesSummary({ files }: {
|
|
35
|
+
files: ReadRequest[];
|
|
36
|
+
}): string;
|
|
37
|
+
/**
|
|
38
|
+
* Reads each request with `read`, in order, each under its own heading, and reports a file it
|
|
39
|
+
* could not read in its place. Fails only when it read none of them, or was cancelled.
|
|
40
|
+
*/
|
|
41
|
+
export declare function readEach(files: ReadRequest[], read: (file: ReadRequest) => Promise<string>, signal: AbortSignal): Promise<string>;
|
|
24
42
|
/** The range a `readFile` call asks for, checked: strict mode allows the schema no minimum. */
|
|
25
43
|
export declare function readRange({ fromLine, lineCount, }: {
|
|
26
44
|
fromLine: number | null;
|
|
@@ -35,5 +53,9 @@ export declare function readFileSummary({ path, fromLine, lineCount, }: {
|
|
|
35
53
|
fromLine: number | null;
|
|
36
54
|
lineCount: number | null;
|
|
37
55
|
}): string;
|
|
38
|
-
/**
|
|
56
|
+
/**
|
|
57
|
+
* The read-only tools an agent explores a repository with: `listFiles`, `searchText`,
|
|
58
|
+
* `readFile` and `readFiles`.
|
|
59
|
+
*/
|
|
39
60
|
export declare function createWorkspaceTools(workspace: Workspace): Tool[];
|
|
61
|
+
export {};
|
|
@@ -5,6 +5,8 @@ import { cutLine, maxLineLength } from "../domain/lineLength.js";
|
|
|
5
5
|
const maxFiles = 200;
|
|
6
6
|
const maxMatches = 100;
|
|
7
7
|
const maxLines = 200;
|
|
8
|
+
// How many files, or ranges, one `readFiles` call may read.
|
|
9
|
+
const maxReads = 10;
|
|
8
10
|
// What one read or one search may bring into the context, whatever its lines: 200 lines of
|
|
9
11
|
// prose can be 50 KB, and the context carries them on every step after.
|
|
10
12
|
export const maxResultBytes = 16 * 1024;
|
|
@@ -68,6 +70,41 @@ export const readFileInput = z.object({
|
|
|
68
70
|
.nullable()
|
|
69
71
|
.describe(`How many lines to read, at most ${String(maxLines)}. Defaults to ${String(maxLines)}.`),
|
|
70
72
|
});
|
|
73
|
+
/** What `readFiles` takes, shared with the harness's own version of it. */
|
|
74
|
+
export const readFilesDescription = `Reads several files, or several ranges of files, in one call: each as readFile reads it, at most ${String(maxReads)}. A file that cannot be read is reported in its place.`;
|
|
75
|
+
export const readFilesInput = z.object({
|
|
76
|
+
files: z.array(readFileInput).describe('What to read, in order: each a file and its range.'),
|
|
77
|
+
});
|
|
78
|
+
export function readFilesSummary({ files }) {
|
|
79
|
+
return files.map(readFileSummary).join(', ');
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Reads each request with `read`, in order, each under its own heading, and reports a file it
|
|
83
|
+
* could not read in its place. Fails only when it read none of them, or was cancelled.
|
|
84
|
+
*/
|
|
85
|
+
export async function readEach(files, read, signal) {
|
|
86
|
+
if (files.length === 0)
|
|
87
|
+
throw new Error('files must name at least one file to read');
|
|
88
|
+
if (files.length > maxReads) {
|
|
89
|
+
throw new Error(`files may name at most ${String(maxReads)} reads at once; got ${String(files.length)}`);
|
|
90
|
+
}
|
|
91
|
+
let failed = 0;
|
|
92
|
+
const results = [];
|
|
93
|
+
for (const file of files) {
|
|
94
|
+
try {
|
|
95
|
+
results.push(`== ${readFileSummary(file)}\n${await read(file)}`);
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
signal.throwIfAborted();
|
|
99
|
+
failed++;
|
|
100
|
+
results.push(`== ${file.path}\nCould not read it: ${error instanceof Error ? error.message : String(error)}`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const output = results.join('\n\n');
|
|
104
|
+
if (failed === files.length)
|
|
105
|
+
throw new Error(output);
|
|
106
|
+
return output;
|
|
107
|
+
}
|
|
71
108
|
/** The range a `readFile` call asks for, checked: strict mode allows the schema no minimum. */
|
|
72
109
|
export function readRange({ fromLine, lineCount, }) {
|
|
73
110
|
const from = fromLine ?? 1;
|
|
@@ -94,7 +131,10 @@ function assertPositiveInteger(name, value) {
|
|
|
94
131
|
throw new Error(`${name} must be a whole number of at least 1; got ${String(value)}`);
|
|
95
132
|
}
|
|
96
133
|
}
|
|
97
|
-
/**
|
|
134
|
+
/**
|
|
135
|
+
* The read-only tools an agent explores a repository with: `listFiles`, `searchText`,
|
|
136
|
+
* `readFile` and `readFiles`.
|
|
137
|
+
*/
|
|
98
138
|
export function createWorkspaceTools(workspace) {
|
|
99
139
|
return [
|
|
100
140
|
defineTool({
|
|
@@ -159,6 +199,18 @@ export function createWorkspaceTools(workspace) {
|
|
|
159
199
|
return renderLines({ path, lines, from, totalLines, truncated });
|
|
160
200
|
},
|
|
161
201
|
}),
|
|
202
|
+
defineTool({
|
|
203
|
+
name: 'readFiles',
|
|
204
|
+
description: readFilesDescription,
|
|
205
|
+
risk: 'safe',
|
|
206
|
+
input: readFilesInput,
|
|
207
|
+
summarize: readFilesSummary,
|
|
208
|
+
execute: ({ files }, signal) => readEach(files, async ({ path, fromLine, lineCount }) => {
|
|
209
|
+
const { from, count } = readRange({ fromLine, lineCount });
|
|
210
|
+
const { lines, totalLines, truncated } = await workspace.readFile({ path, fromLine: from, lineCount: count }, signal);
|
|
211
|
+
return renderLines({ path, lines, from, totalLines, truncated });
|
|
212
|
+
}, signal),
|
|
213
|
+
}),
|
|
162
214
|
];
|
|
163
215
|
}
|
|
164
216
|
//# sourceMappingURL=workspaceTools.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workspaceTools.js","sourceRoot":"","sources":["../../../src/tools/infrastructure/workspaceTools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,OAAO,EAAE,aAAa,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,EAAE,EAAE,MAAM,EAAE,EAAE;gBACxD,0BAA0B;gBAC1B,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,SAAS,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAC,CAAC;gBAC3D,MAAM,EAAE,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,GAAG,MAAM,SAAS,CAAC,QAAQ,CAChE,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,EAC1C,MAAM,CACN,CAAC;gBACF,OAAO,WAAW,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,SAAS,EAAE,CAAC,CAAC;YAClE,CAAC;SACD,CAAC;KACF,CAAC;AACH,CAAC","sourcesContent":["import { z } from 'zod';\nimport type { Tool } from '../domain/tool.ts';\nimport type { Workspace } from '../domain/workspace.ts';\nimport { defineTool } from './defineTool.ts';\nimport { cutLine, maxLineLength } from '../domain/lineLength.ts';\n\n// What one call may return. The model can ask for fewer lines, never for more.\nconst maxFiles = 200;\nconst maxMatches = 100;\nconst maxLines = 200;\n// What one read or one search may bring into the context, whatever its lines: 200 lines of\n// prose can be 50 KB, and the context carries them on every step after.\nexport const maxResultBytes = 16 * 1024;\n\n// Strict mode has no optional fields: an argument the model may leave out is nullable.\nconst scope = {\n\tpath: z.string().nullable().describe('A folder or file to stay inside, relative to the root.'),\n\tglob: z\n\t\t.string()\n\t\t.nullable()\n\t\t.describe(\n\t\t\t'Only paths matching this glob, relative to the root. \"*\" stays inside one folder and \"**\" crosses folders: \"**/*.ts\" is every TypeScript file, \"*.ts\" only those at the top.',\n\t\t),\n};\n\n/**\n * Lines of a file as the model reads them: each numbered, a line too long cut, and a notice for\n * what was cut or lies beyond.\n */\nexport function renderLines({\n\tpath,\n\tlines,\n\tfrom,\n\ttotalLines,\n\ttruncated,\n}: {\n\t/** The file, which decides how long a line may be. */\n\tpath: string;\n\tlines: string[];\n\tfrom: number;\n\ttotalLines: number;\n\ttruncated: boolean;\n}): string {\n\t// The file's length tells the model where its range went wrong.\n\tif (lines.length === 0) {\n\t\treturn `No lines from ${String(from)}: the file has ${String(totalLines)} lines.`;\n\t}\n\n\tconst numbered = withinBytes(\n\t\tlines.map((text, index) => `${String(from + index)}: ${cutLine(path, text)}`),\n\t);\n\tconst shown = lines.slice(0, numbered.length);\n\tconst max = maxLineLength(path);\n\tconst cut = shown.filter(text => text.length > max).length;\n\tconst next = from + shown.length;\n\tconst notices = [\n\t\t...(cut > 0\n\t\t\t? [`[${String(cut)} lines were longer than ${String(max)} characters and were cut.]`]\n\t\t\t: []),\n\t\t...(shown.length < lines.length\n\t\t\t? [\n\t\t\t\t\t`[Lines ${String(from)} to ${String(next - 1)} fill the ${String(maxResultBytes / 1024)} KB one read may return. The file has ${String(totalLines)} lines. Read from line ${String(next)} to continue.]`,\n\t\t\t\t]\n\t\t\t: truncated\n\t\t\t\t? [\n\t\t\t\t\t\t`[The file has ${String(totalLines)} lines. Read from line ${String(next)} to continue.]`,\n\t\t\t\t\t]\n\t\t\t\t: []),\n\t];\n\treturn [...numbered, ...notices].join('\\n');\n}\n\n/** The first of `lines` that fit in `maxResultBytes` together, and always the first one. */\nfunction withinBytes(lines: string[]): string[] {\n\tlet bytes = 0;\n\tconst kept: string[] = [];\n\tfor (const line of lines) {\n\t\tbytes += Buffer.byteLength(line, 'utf8') + 1;\n\t\tif (bytes > maxResultBytes && kept.length > 0) break;\n\t\tkept.push(line);\n\t}\n\treturn kept;\n}\n\n/** What `readFile` takes, shared with the harness's own version of it. */\nexport const readFileDescription = 'Reads lines of a file, each prefixed with its number.';\nexport const readFileInput = z.object({\n\tpath: z.string().describe('The file, relative to the root.'),\n\tfromLine: z.number().nullable().describe('The first line to read, from 1. Defaults to 1.'),\n\tlineCount: z\n\t\t.number()\n\t\t.nullable()\n\t\t.describe(\n\t\t\t`How many lines to read, at most ${String(maxLines)}. Defaults to ${String(maxLines)}.`,\n\t\t),\n});\n\n/** The range a `readFile` call asks for, checked: strict mode allows the schema no minimum. */\nexport function readRange({\n\tfromLine,\n\tlineCount,\n}: {\n\tfromLine: number | null;\n\tlineCount: number | null;\n}): { from: number; count: number } {\n\tconst from = fromLine ?? 1;\n\tconst requested = lineCount ?? maxLines;\n\tassertPositiveInteger('fromLine', from);\n\tassertPositiveInteger('lineCount', requested);\n\treturn { from, count: Math.min(requested, maxLines) };\n}\n\n/** A stable description of a read request, using only the range the model supplied. */\nexport function readFileSummary({\n\tpath,\n\tfromLine,\n\tlineCount,\n}: {\n\tpath: string;\n\tfromLine: number | null;\n\tlineCount: number | null;\n}): string {\n\tconst suppliedFrom = fromLine ?? 1;\n\tconst from = Number.isInteger(suppliedFrom) && suppliedFrom > 0 ? suppliedFrom : 1;\n\tconst suppliedCount = lineCount ?? maxLines;\n\tconst requested = Number.isInteger(suppliedCount) && suppliedCount > 0 ? suppliedCount : maxLines;\n\tconst count = Math.min(requested, maxLines);\n\treturn `${path}:${String(from)}-${String(from + count - 1)}`;\n}\n\nfunction scopeSummary(path: string | null, glob: string | null): string {\n\tconst scopePath = path ?? '.';\n\treturn glob ? `${scopePath === '.' ? '' : `${scopePath}/`}${glob}` : scopePath;\n}\n\nfunction assertPositiveInteger(name: string, value: number): void {\n\tif (!Number.isInteger(value) || value < 1) {\n\t\tthrow new Error(`${name} must be a whole number of at least 1; got ${String(value)}`);\n\t}\n}\n\n/** The three read-only tools an agent explores a repository with. */\nexport function createWorkspaceTools(workspace: Workspace): Tool[] {\n\treturn [\n\t\tdefineTool({\n\t\t\tname: 'listFiles',\n\t\t\tdescription:\n\t\t\t\t'Lists the files of the repository, sorted. Ignored files such as dependencies are left out.',\n\t\t\trisk: 'safe',\n\t\t\tinput: z.object(scope),\n\t\t\tsummarize: ({ path, glob }) => scopeSummary(path, glob),\n\t\t\texecute: async ({ path, glob }, signal) => {\n\t\t\t\t// The port takes \"no scope\" as a missing field.\n\t\t\t\tconst { files, total, truncated } = await workspace.listFiles(\n\t\t\t\t\t{ path: path ?? undefined, glob: glob ?? undefined, limit: maxFiles },\n\t\t\t\t\tsignal,\n\t\t\t\t);\n\n\t\t\t\t// Nothing found is an answer too, not an empty string.\n\t\t\t\tif (files.length === 0) {\n\t\t\t\t\treturn 'No files.';\n\t\t\t\t}\n\n\t\t\t\tconst notice = truncated\n\t\t\t\t\t? `\\n[Showing ${String(files.length)} of ${String(total)} files. Narrow the path or glob to see the rest.]`\n\t\t\t\t\t: '';\n\t\t\t\treturn files.join('\\n') + notice;\n\t\t\t},\n\t\t}),\n\n\t\tdefineTool({\n\t\t\tname: 'searchText',\n\t\t\tdescription:\n\t\t\t\t'Searches the repository for a regular expression and returns each matching line as path:line: text.',\n\t\t\trisk: 'safe',\n\t\t\tinput: z.object({\n\t\t\t\tpattern: z.string().describe('A regular expression.'),\n\t\t\t\tignoreCase: z.boolean().nullable().describe('Match regardless of case. Defaults to false.'),\n\t\t\t\t...scope,\n\t\t\t}),\n\t\t\tsummarize: ({ path, glob, pattern }) => `\"${pattern}\" in ${scopeSummary(path, glob)}`,\n\t\t\texecute: async ({ path, glob, ignoreCase, pattern }, signal) => {\n\t\t\t\tconst { matches, total, truncated } = await workspace.searchText(\n\t\t\t\t\t{\n\t\t\t\t\t\tpath: path ?? undefined,\n\t\t\t\t\t\tglob: glob ?? undefined,\n\t\t\t\t\t\tignoreCase: ignoreCase ?? false,\n\t\t\t\t\t\tpattern,\n\t\t\t\t\t\tlimit: maxMatches,\n\t\t\t\t\t},\n\t\t\t\t\tsignal,\n\t\t\t\t);\n\n\t\t\t\tif (matches.length === 0) {\n\t\t\t\t\treturn 'No matches.';\n\t\t\t\t}\n\n\t\t\t\tconst results = withinBytes(\n\t\t\t\t\tmatches.map(\n\t\t\t\t\t\tmatch => `${match.path}:${String(match.line)}: ${cutLine(match.path, match.text)}`,\n\t\t\t\t\t),\n\t\t\t\t);\n\n\t\t\t\tconst notice =\n\t\t\t\t\tresults.length < matches.length\n\t\t\t\t\t\t? `\\n[Showing ${String(results.length)} of ${String(total)} matches, the ${String(maxResultBytes / 1024)} KB one search may return. Narrow the pattern, the path or the glob to see the rest.]`\n\t\t\t\t\t\t: truncated\n\t\t\t\t\t\t\t? `\\n[Showing ${String(results.length)} of ${String(total)} matches. Narrow the path or glob to see the rest.]`\n\t\t\t\t\t\t\t: '';\n\t\t\t\treturn results.join('\\n') + notice;\n\t\t\t},\n\t\t}),\n\n\t\tdefineTool({\n\t\t\tname: 'readFile',\n\t\t\tdescription: readFileDescription,\n\t\t\trisk: 'safe',\n\t\t\tinput: readFileInput,\n\t\t\tsummarize: readFileSummary,\n\t\t\texecute: async ({ fromLine, lineCount, path }, signal) => {\n\t\t\t\t// Checked before reading.\n\t\t\t\tconst { from, count } = readRange({ fromLine, lineCount });\n\t\t\t\tconst { lines, totalLines, truncated } = await workspace.readFile(\n\t\t\t\t\t{ path, fromLine: from, lineCount: count },\n\t\t\t\t\tsignal,\n\t\t\t\t);\n\t\t\t\treturn renderLines({ path, lines, from, totalLines, truncated });\n\t\t\t},\n\t\t}),\n\t];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"workspaceTools.js","sourceRoot":"","sources":["../../../src/tools/infrastructure/workspaceTools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAEjE,+EAA+E;AAC/E,MAAM,QAAQ,GAAG,GAAG,CAAC;AACrB,MAAM,UAAU,GAAG,GAAG,CAAC;AACvB,MAAM,QAAQ,GAAG,GAAG,CAAC;AACrB,4DAA4D;AAC5D,MAAM,QAAQ,GAAG,EAAE,CAAC;AACpB,2FAA2F;AAC3F,wEAAwE;AACxE,MAAM,CAAC,MAAM,cAAc,GAAG,EAAE,GAAG,IAAI,CAAC;AAExC,uFAAuF;AACvF,MAAM,KAAK,GAA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AC;AACH,CAAC","sourcesContent":["import { z } from 'zod';\nimport type { Tool } from '../domain/tool.ts';\nimport type { Workspace } from '../domain/workspace.ts';\nimport { defineTool } from './defineTool.ts';\nimport { cutLine, maxLineLength } from '../domain/lineLength.ts';\n\n// What one call may return. The model can ask for fewer lines, never for more.\nconst maxFiles = 200;\nconst maxMatches = 100;\nconst maxLines = 200;\n// How many files, or ranges, one `readFiles` call may read.\nconst maxReads = 10;\n// What one read or one search may bring into the context, whatever its lines: 200 lines of\n// prose can be 50 KB, and the context carries them on every step after.\nexport const maxResultBytes = 16 * 1024;\n\n// Strict mode has no optional fields: an argument the model may leave out is nullable.\nconst scope = {\n\tpath: z.string().nullable().describe('A folder or file to stay inside, relative to the root.'),\n\tglob: z\n\t\t.string()\n\t\t.nullable()\n\t\t.describe(\n\t\t\t'Only paths matching this glob, relative to the root. \"*\" stays inside one folder and \"**\" crosses folders: \"**/*.ts\" is every TypeScript file, \"*.ts\" only those at the top.',\n\t\t),\n};\n\n/**\n * Lines of a file as the model reads them: each numbered, a line too long cut, and a notice for\n * what was cut or lies beyond.\n */\nexport function renderLines({\n\tpath,\n\tlines,\n\tfrom,\n\ttotalLines,\n\ttruncated,\n}: {\n\t/** The file, which decides how long a line may be. */\n\tpath: string;\n\tlines: string[];\n\tfrom: number;\n\ttotalLines: number;\n\ttruncated: boolean;\n}): string {\n\t// The file's length tells the model where its range went wrong.\n\tif (lines.length === 0) {\n\t\treturn `No lines from ${String(from)}: the file has ${String(totalLines)} lines.`;\n\t}\n\n\tconst numbered = withinBytes(\n\t\tlines.map((text, index) => `${String(from + index)}: ${cutLine(path, text)}`),\n\t);\n\tconst shown = lines.slice(0, numbered.length);\n\tconst max = maxLineLength(path);\n\tconst cut = shown.filter(text => text.length > max).length;\n\tconst next = from + shown.length;\n\tconst notices = [\n\t\t...(cut > 0\n\t\t\t? [`[${String(cut)} lines were longer than ${String(max)} characters and were cut.]`]\n\t\t\t: []),\n\t\t...(shown.length < lines.length\n\t\t\t? [\n\t\t\t\t\t`[Lines ${String(from)} to ${String(next - 1)} fill the ${String(maxResultBytes / 1024)} KB one read may return. The file has ${String(totalLines)} lines. Read from line ${String(next)} to continue.]`,\n\t\t\t\t]\n\t\t\t: truncated\n\t\t\t\t? [\n\t\t\t\t\t\t`[The file has ${String(totalLines)} lines. Read from line ${String(next)} to continue.]`,\n\t\t\t\t\t]\n\t\t\t\t: []),\n\t];\n\treturn [...numbered, ...notices].join('\\n');\n}\n\n/** The first of `lines` that fit in `maxResultBytes` together, and always the first one. */\nfunction withinBytes(lines: string[]): string[] {\n\tlet bytes = 0;\n\tconst kept: string[] = [];\n\tfor (const line of lines) {\n\t\tbytes += Buffer.byteLength(line, 'utf8') + 1;\n\t\tif (bytes > maxResultBytes && kept.length > 0) break;\n\t\tkept.push(line);\n\t}\n\treturn kept;\n}\n\n/** What `readFile` takes, shared with the harness's own version of it. */\nexport const readFileDescription = 'Reads lines of a file, each prefixed with its number.';\nexport const readFileInput = z.object({\n\tpath: z.string().describe('The file, relative to the root.'),\n\tfromLine: z.number().nullable().describe('The first line to read, from 1. Defaults to 1.'),\n\tlineCount: z\n\t\t.number()\n\t\t.nullable()\n\t\t.describe(\n\t\t\t`How many lines to read, at most ${String(maxLines)}. Defaults to ${String(maxLines)}.`,\n\t\t),\n});\n\n/** What `readFiles` takes, shared with the harness's own version of it. */\nexport const readFilesDescription = `Reads several files, or several ranges of files, in one call: each as readFile reads it, at most ${String(maxReads)}. A file that cannot be read is reported in its place.`;\nexport const readFilesInput = z.object({\n\tfiles: z.array(readFileInput).describe('What to read, in order: each a file and its range.'),\n});\n\ntype ReadRequest = z.infer<typeof readFileInput>;\n\nexport function readFilesSummary({ files }: { files: ReadRequest[] }): string {\n\treturn files.map(readFileSummary).join(', ');\n}\n\n/**\n * Reads each request with `read`, in order, each under its own heading, and reports a file it\n * could not read in its place. Fails only when it read none of them, or was cancelled.\n */\nexport async function readEach(\n\tfiles: ReadRequest[],\n\tread: (file: ReadRequest) => Promise<string>,\n\tsignal: AbortSignal,\n): Promise<string> {\n\tif (files.length === 0) throw new Error('files must name at least one file to read');\n\tif (files.length > maxReads) {\n\t\tthrow new Error(\n\t\t\t`files may name at most ${String(maxReads)} reads at once; got ${String(files.length)}`,\n\t\t);\n\t}\n\tlet failed = 0;\n\tconst results: string[] = [];\n\tfor (const file of files) {\n\t\ttry {\n\t\t\tresults.push(`== ${readFileSummary(file)}\\n${await read(file)}`);\n\t\t} catch (error) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tfailed++;\n\t\t\tresults.push(\n\t\t\t\t`== ${file.path}\\nCould not read it: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t}\n\tconst output = results.join('\\n\\n');\n\tif (failed === files.length) throw new Error(output);\n\treturn output;\n}\n\n/** The range a `readFile` call asks for, checked: strict mode allows the schema no minimum. */\nexport function readRange({\n\tfromLine,\n\tlineCount,\n}: {\n\tfromLine: number | null;\n\tlineCount: number | null;\n}): { from: number; count: number } {\n\tconst from = fromLine ?? 1;\n\tconst requested = lineCount ?? maxLines;\n\tassertPositiveInteger('fromLine', from);\n\tassertPositiveInteger('lineCount', requested);\n\treturn { from, count: Math.min(requested, maxLines) };\n}\n\n/** A stable description of a read request, using only the range the model supplied. */\nexport function readFileSummary({\n\tpath,\n\tfromLine,\n\tlineCount,\n}: {\n\tpath: string;\n\tfromLine: number | null;\n\tlineCount: number | null;\n}): string {\n\tconst suppliedFrom = fromLine ?? 1;\n\tconst from = Number.isInteger(suppliedFrom) && suppliedFrom > 0 ? suppliedFrom : 1;\n\tconst suppliedCount = lineCount ?? maxLines;\n\tconst requested = Number.isInteger(suppliedCount) && suppliedCount > 0 ? suppliedCount : maxLines;\n\tconst count = Math.min(requested, maxLines);\n\treturn `${path}:${String(from)}-${String(from + count - 1)}`;\n}\n\nfunction scopeSummary(path: string | null, glob: string | null): string {\n\tconst scopePath = path ?? '.';\n\treturn glob ? `${scopePath === '.' ? '' : `${scopePath}/`}${glob}` : scopePath;\n}\n\nfunction assertPositiveInteger(name: string, value: number): void {\n\tif (!Number.isInteger(value) || value < 1) {\n\t\tthrow new Error(`${name} must be a whole number of at least 1; got ${String(value)}`);\n\t}\n}\n\n/**\n * The read-only tools an agent explores a repository with: `listFiles`, `searchText`,\n * `readFile` and `readFiles`.\n */\nexport function createWorkspaceTools(workspace: Workspace): Tool[] {\n\treturn [\n\t\tdefineTool({\n\t\t\tname: 'listFiles',\n\t\t\tdescription:\n\t\t\t\t'Lists the files of the repository, sorted. Ignored files such as dependencies are left out.',\n\t\t\trisk: 'safe',\n\t\t\tinput: z.object(scope),\n\t\t\tsummarize: ({ path, glob }) => scopeSummary(path, glob),\n\t\t\texecute: async ({ path, glob }, signal) => {\n\t\t\t\t// The port takes \"no scope\" as a missing field.\n\t\t\t\tconst { files, total, truncated } = await workspace.listFiles(\n\t\t\t\t\t{ path: path ?? undefined, glob: glob ?? undefined, limit: maxFiles },\n\t\t\t\t\tsignal,\n\t\t\t\t);\n\n\t\t\t\t// Nothing found is an answer too, not an empty string.\n\t\t\t\tif (files.length === 0) {\n\t\t\t\t\treturn 'No files.';\n\t\t\t\t}\n\n\t\t\t\tconst notice = truncated\n\t\t\t\t\t? `\\n[Showing ${String(files.length)} of ${String(total)} files. Narrow the path or glob to see the rest.]`\n\t\t\t\t\t: '';\n\t\t\t\treturn files.join('\\n') + notice;\n\t\t\t},\n\t\t}),\n\n\t\tdefineTool({\n\t\t\tname: 'searchText',\n\t\t\tdescription:\n\t\t\t\t'Searches the repository for a regular expression and returns each matching line as path:line: text.',\n\t\t\trisk: 'safe',\n\t\t\tinput: z.object({\n\t\t\t\tpattern: z.string().describe('A regular expression.'),\n\t\t\t\tignoreCase: z.boolean().nullable().describe('Match regardless of case. Defaults to false.'),\n\t\t\t\t...scope,\n\t\t\t}),\n\t\t\tsummarize: ({ path, glob, pattern }) => `\"${pattern}\" in ${scopeSummary(path, glob)}`,\n\t\t\texecute: async ({ path, glob, ignoreCase, pattern }, signal) => {\n\t\t\t\tconst { matches, total, truncated } = await workspace.searchText(\n\t\t\t\t\t{\n\t\t\t\t\t\tpath: path ?? undefined,\n\t\t\t\t\t\tglob: glob ?? undefined,\n\t\t\t\t\t\tignoreCase: ignoreCase ?? false,\n\t\t\t\t\t\tpattern,\n\t\t\t\t\t\tlimit: maxMatches,\n\t\t\t\t\t},\n\t\t\t\t\tsignal,\n\t\t\t\t);\n\n\t\t\t\tif (matches.length === 0) {\n\t\t\t\t\treturn 'No matches.';\n\t\t\t\t}\n\n\t\t\t\tconst results = withinBytes(\n\t\t\t\t\tmatches.map(\n\t\t\t\t\t\tmatch => `${match.path}:${String(match.line)}: ${cutLine(match.path, match.text)}`,\n\t\t\t\t\t),\n\t\t\t\t);\n\n\t\t\t\tconst notice =\n\t\t\t\t\tresults.length < matches.length\n\t\t\t\t\t\t? `\\n[Showing ${String(results.length)} of ${String(total)} matches, the ${String(maxResultBytes / 1024)} KB one search may return. Narrow the pattern, the path or the glob to see the rest.]`\n\t\t\t\t\t\t: truncated\n\t\t\t\t\t\t\t? `\\n[Showing ${String(results.length)} of ${String(total)} matches. Narrow the path or glob to see the rest.]`\n\t\t\t\t\t\t\t: '';\n\t\t\t\treturn results.join('\\n') + notice;\n\t\t\t},\n\t\t}),\n\n\t\tdefineTool({\n\t\t\tname: 'readFile',\n\t\t\tdescription: readFileDescription,\n\t\t\trisk: 'safe',\n\t\t\tinput: readFileInput,\n\t\t\tsummarize: readFileSummary,\n\t\t\texecute: async ({ fromLine, lineCount, path }, signal) => {\n\t\t\t\t// Checked before reading.\n\t\t\t\tconst { from, count } = readRange({ fromLine, lineCount });\n\t\t\t\tconst { lines, totalLines, truncated } = await workspace.readFile(\n\t\t\t\t\t{ path, fromLine: from, lineCount: count },\n\t\t\t\t\tsignal,\n\t\t\t\t);\n\t\t\t\treturn renderLines({ path, lines, from, totalLines, truncated });\n\t\t\t},\n\t\t}),\n\n\t\tdefineTool({\n\t\t\tname: 'readFiles',\n\t\t\tdescription: readFilesDescription,\n\t\t\trisk: 'safe',\n\t\t\tinput: readFilesInput,\n\t\t\tsummarize: readFilesSummary,\n\t\t\texecute: ({ files }, signal) =>\n\t\t\t\treadEach(\n\t\t\t\t\tfiles,\n\t\t\t\t\tasync ({ path, fromLine, lineCount }) => {\n\t\t\t\t\t\tconst { from, count } = readRange({ fromLine, lineCount });\n\t\t\t\t\t\tconst { lines, totalLines, truncated } = await workspace.readFile(\n\t\t\t\t\t\t\t{ path, fromLine: from, lineCount: count },\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn renderLines({ path, lines, from, totalLines, truncated });\n\t\t\t\t\t},\n\t\t\t\t\tsignal,\n\t\t\t\t),\n\t\t}),\n\t];\n}\n"]}
|