@greppleai/grip 0.1.3 → 0.1.4

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.
Files changed (38) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/core/extensions/types.d.ts +5 -1
  3. package/dist/core/extensions/types.d.ts.map +1 -1
  4. package/dist/core/extensions/types.js.map +1 -1
  5. package/dist/core/tools/find.d.ts.map +1 -1
  6. package/dist/core/tools/find.js +2 -3
  7. package/dist/core/tools/find.js.map +1 -1
  8. package/dist/core/tools/grep.d.ts.map +1 -1
  9. package/dist/core/tools/grep.js +2 -3
  10. package/dist/core/tools/grep.js.map +1 -1
  11. package/dist/core/tools/ls.d.ts.map +1 -1
  12. package/dist/core/tools/ls.js +2 -3
  13. package/dist/core/tools/ls.js.map +1 -1
  14. package/dist/core/tools/read.d.ts.map +1 -1
  15. package/dist/core/tools/read.js +3 -3
  16. package/dist/core/tools/read.js.map +1 -1
  17. package/dist/core/tools/render-utils.d.ts +1 -0
  18. package/dist/core/tools/render-utils.d.ts.map +1 -1
  19. package/dist/core/tools/render-utils.js +5 -0
  20. package/dist/core/tools/render-utils.js.map +1 -1
  21. package/dist/core/tools/write.d.ts.map +1 -1
  22. package/dist/core/tools/write.js +2 -3
  23. package/dist/core/tools/write.js.map +1 -1
  24. package/dist/modes/interactive/components/hook-execution.d.ts +3 -0
  25. package/dist/modes/interactive/components/hook-execution.d.ts.map +1 -1
  26. package/dist/modes/interactive/components/hook-execution.js +17 -0
  27. package/dist/modes/interactive/components/hook-execution.js.map +1 -1
  28. package/dist/modes/interactive/interactive-mode.d.ts +1 -0
  29. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  30. package/dist/modes/interactive/interactive-mode.js +51 -3
  31. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  32. package/docs/extensions.md +3 -0
  33. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  34. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  35. package/examples/extensions/sandbox/package.json +1 -1
  36. package/examples/extensions/with-deps/package.json +1 -1
  37. package/npm-shrinkwrap.json +12 -12
  38. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"grep.d.ts","sourceRoot":"","sources":["../../../src/core/tools/grep.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAmB,MAAM,4BAA4B,CAAC;AAI7E,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAI5C,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AACtF,OAAO,KAAK,EAAiB,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAIrE,OAAO,EAIN,KAAK,gBAAgB,EAGrB,MAAM,eAAe,CAAC;AAEvB,QAAA,MAAM,UAAU;;;;;;;;EAYd,CAAC;AAEH,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAGtD,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,cAAc,CAAC,EAAE,OAAO,CAAC;CACzB;AAED,MAAM,WAAW,eAAe;CAAG;AAuVnC,MAAM,MAAM,kBAAkB,GAAG,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,CAAC,CAAC;AAEhG,wBAAgB,wBAAwB,CAAC,UAAU,EAAE,cAAc,EAAE,QAAQ,CAAC,EAAE,eAAe,GAAG,kBAAkB,CAuBnH;AAED,wBAAgB,cAAc,CAAC,UAAU,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAElH","sourcesContent":["import { createInterface } from \"node:readline\";\nimport type { AgentTool, AgentToolResult } from \"@greppleai/grip-agent-core\";\nimport { Text } from \"@greppleai/grip-tui\";\nimport { spawn } from \"child_process\";\nimport path from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { ensureTool } from \"../../utils/tools-manager.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport type { ToolGrepMatch, ToolOperations } from \"./operations.ts\";\nimport { resolveToCwd } from \"./path-utils.ts\";\nimport { formatBackendIcon, getTextOutput, invalidArgText, shortenPath, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport {\n\tDEFAULT_MAX_BYTES,\n\tformatSize,\n\tGREP_MAX_LINE_LENGTH,\n\ttype TruncationResult,\n\ttruncateHead,\n\ttruncateLine,\n} from \"./truncate.ts\";\n\nconst grepSchema = Type.Object({\n\tpattern: Type.String({ description: \"Search pattern (regex or literal string)\" }),\n\tpath: Type.Optional(Type.String({ description: \"Directory or file to search (default: current directory)\" })),\n\tglob: Type.Optional(Type.String({ description: \"Filter files by glob pattern, e.g. '*.ts' or '**/*.spec.ts'\" })),\n\tignoreCase: Type.Optional(Type.Boolean({ description: \"Case-insensitive search (default: false)\" })),\n\tliteral: Type.Optional(\n\t\tType.Boolean({ description: \"Treat pattern as literal string instead of regex (default: false)\" }),\n\t),\n\tcontext: Type.Optional(\n\t\tType.Number({ description: \"Number of lines to show before and after each match (default: 0)\" }),\n\t),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of matches to return (default: 100)\" })),\n});\n\nexport type GrepToolInput = Static<typeof grepSchema>;\nconst DEFAULT_LIMIT = 100;\n\nexport interface GrepToolDetails {\n\ttruncation?: TruncationResult;\n\tmatchLimitReached?: number;\n\tlinesTruncated?: boolean;\n}\n\nexport interface GrepToolOptions {}\n\nfunction formatGrepCall(args: Partial<GrepToolInput> | undefined, theme: Theme): string {\n\tconst pattern = str(args?.pattern);\n\tconst rawPath = str(args?.path);\n\tconst path = rawPath !== null ? shortenPath(rawPath || \".\") : null;\n\tconst glob = str(args?.glob);\n\tconst limit = args?.limit;\n\tconst invalidArg = invalidArgText(theme);\n\tlet text =\n\t\ttheme.fg(\"toolTitle\", theme.bold(\"grep\")) +\n\t\t\" \" +\n\t\t(pattern === null ? invalidArg : theme.fg(\"accent\", `/${pattern || \"\"}/`)) +\n\t\ttheme.fg(\"toolOutput\", ` in ${path === null ? invalidArg : path}`);\n\tif (glob) text += theme.fg(\"toolOutput\", ` (${glob})`);\n\tif (limit !== undefined) text += theme.fg(\"toolOutput\", ` limit ${limit}`);\n\treturn text;\n}\n\nfunction formatGrepResult(\n\tresult: AgentToolResult<GrepToolDetails | undefined>,\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n): string {\n\tconst output = getTextOutput(result, showImages).trim();\n\tlet text = \"\";\n\tif (output) {\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst maxLines = options.expanded ? lines.length : 15;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n${displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")})`;\n\t\t}\n\t}\n\n\tconst matchLimit = result.details?.matchLimitReached;\n\tconst truncation = result.details?.truncation;\n\tconst linesTruncated = result.details?.linesTruncated;\n\tif (matchLimit || truncation?.truncated || linesTruncated) {\n\t\tconst warnings: string[] = [];\n\t\tif (matchLimit) warnings.push(`${matchLimit} matches limit`);\n\t\tif (truncation?.truncated) warnings.push(`${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit`);\n\t\tif (linesTruncated) warnings.push(\"some lines truncated\");\n\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${warnings.join(\", \")}]`)}`;\n\t}\n\treturn text;\n}\ninterface GrepFormatState {\n\toperations: ToolOperations;\n\tsearchPath: string;\n\tisDirectory: boolean;\n\tcontext: number;\n\tfileCache: Map<string, string[]>;\n\tlinesTruncated: boolean;\n}\n\ninterface GrepExecutionInput {\n\tpattern: string;\n\tsearchPath: string;\n\tglob?: string;\n\tignoreCase?: boolean;\n\tliteral?: boolean;\n\tcontext: number;\n\tlimit: number;\n}\n\ninterface RipgrepCollectionState {\n\tstderr: string;\n\tmatchCount: number;\n\tmatchLimitReached: boolean;\n\taborted: boolean;\n\tkilledDueToLimit: boolean;\n\tmatches: ToolGrepMatch[];\n}\n\nfunction noGrepMatchesResult(): AgentToolResult<GrepToolDetails | undefined> {\n\treturn { content: [{ type: \"text\", text: \"No matches found\" }], details: undefined };\n}\n\nfunction formatMatchedFilePath(state: GrepFormatState, filePath: string): string {\n\tif (state.isDirectory) {\n\t\tconst relative = path.relative(state.searchPath, filePath);\n\t\tif (relative && !relative.startsWith(\"..\")) return relative.replace(/\\\\/g, \"/\");\n\t}\n\treturn path.basename(filePath);\n}\n\nasync function getGrepFileLines(state: GrepFormatState, filePath: string): Promise<string[]> {\n\tconst cached = state.fileCache.get(filePath);\n\tif (cached) return cached;\n\tlet lines: string[];\n\ttry {\n\t\tconst content = (await state.operations.readFile(filePath)).toString(\"utf-8\");\n\t\tlines = content.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\").split(\"\\n\");\n\t} catch {\n\t\tlines = [];\n\t}\n\tstate.fileCache.set(filePath, lines);\n\treturn lines;\n}\n\nasync function formatGrepContextBlock(state: GrepFormatState, match: ToolGrepMatch): Promise<string[]> {\n\tconst relativePath = formatMatchedFilePath(state, match.filePath);\n\tconst lines = await getGrepFileLines(state, match.filePath);\n\tif (!lines.length) return [`${relativePath}:${match.lineNumber}: (unable to read file)`];\n\tconst block: string[] = [];\n\tconst start = state.context > 0 ? Math.max(1, match.lineNumber - state.context) : match.lineNumber;\n\tconst end = state.context > 0 ? Math.min(lines.length, match.lineNumber + state.context) : match.lineNumber;\n\tfor (let current = start; current <= end; current++) {\n\t\tconst sanitized = (lines[current - 1] ?? \"\").replace(/\\r/g, \"\");\n\t\tconst { text, wasTruncated } = truncateLine(sanitized);\n\t\tif (wasTruncated) state.linesTruncated = true;\n\t\tblock.push(\n\t\t\tcurrent === match.lineNumber ? `${relativePath}:${current}: ${text}` : `${relativePath}-${current}- ${text}`,\n\t\t);\n\t}\n\treturn block;\n}\n\nasync function formatGrepMatch(state: GrepFormatState, match: ToolGrepMatch): Promise<string[]> {\n\tif (state.context !== 0 || match.lineText === undefined) return formatGrepContextBlock(state, match);\n\tconst sanitized = match.lineText.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\").replace(/\\n$/, \"\");\n\tconst { text, wasTruncated } = truncateLine(sanitized);\n\tif (wasTruncated) state.linesTruncated = true;\n\treturn [`${formatMatchedFilePath(state, match.filePath)}:${match.lineNumber}: ${text}`];\n}\n\nasync function formatGrepMatches(state: GrepFormatState, matches: ToolGrepMatch[]): Promise<string[]> {\n\tconst outputLines: string[] = [];\n\tfor (const match of matches) outputLines.push(...(await formatGrepMatch(state, match)));\n\treturn outputLines;\n}\n\nfunction buildGrepResult(\n\tstate: GrepFormatState,\n\toutputLines: string[],\n\tmatchLimitReached: number | undefined,\n): AgentToolResult<GrepToolDetails | undefined> {\n\tconst truncation = truncateHead(outputLines.join(\"\\n\"), { maxLines: Number.MAX_SAFE_INTEGER });\n\tlet output = truncation.content;\n\tconst details: GrepToolDetails = {};\n\tconst notices: string[] = [];\n\tif (matchLimitReached !== undefined) {\n\t\tnotices.push(\n\t\t\t`${matchLimitReached} matches limit reached. Use limit=${matchLimitReached * 2} for more, or refine pattern`,\n\t\t);\n\t\tdetails.matchLimitReached = matchLimitReached;\n\t}\n\tif (truncation.truncated) {\n\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\tdetails.truncation = truncation;\n\t}\n\tif (state.linesTruncated) {\n\t\tnotices.push(`Some lines truncated to ${GREP_MAX_LINE_LENGTH} chars. Use read tool to see full lines`);\n\t\tdetails.linesTruncated = true;\n\t}\n\tif (notices.length > 0) output += `\\n\\n[${notices.join(\". \")}]`;\n\treturn {\n\t\tcontent: [{ type: \"text\", text: output }],\n\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t};\n}\n\nasync function executeOperationsGrep(\n\toperations: ToolOperations,\n\tinput: GrepExecutionInput,\n\tformatState: GrepFormatState,\n): Promise<AgentToolResult<GrepToolDetails | undefined>> {\n\tconst result = await operations.grep!({\n\t\tpattern: input.pattern,\n\t\tpath: input.searchPath,\n\t\tglob: input.glob,\n\t\tignoreCase: input.ignoreCase,\n\t\tliteral: input.literal,\n\t\tlimit: input.limit,\n\t});\n\tformatState.isDirectory = result.isDirectory;\n\tif (result.matches.length === 0) return noGrepMatchesResult();\n\tconst outputLines = await formatGrepMatches(formatState, result.matches);\n\treturn buildGrepResult(formatState, outputLines, result.matches.length >= input.limit ? input.limit : undefined);\n}\n\nfunction buildRipgrepArgs(input: GrepExecutionInput): string[] {\n\tconst args: string[] = [\"--json\", \"--line-number\", \"--color=never\", \"--hidden\"];\n\tif (input.ignoreCase) args.push(\"--ignore-case\");\n\tif (input.literal) args.push(\"--fixed-strings\");\n\tif (input.glob) args.push(\"--glob\", input.glob);\n\targs.push(\"--\", input.pattern, input.searchPath);\n\treturn args;\n}\n\ninterface ParsedRipgrepLine {\n\tmatchedEvent: boolean;\n\tmatch?: ToolGrepMatch;\n}\n\nfunction isUnknownRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction getRecordText(value: unknown): unknown {\n\treturn isUnknownRecord(value) ? value.text : undefined;\n}\n\nfunction parseRipgrepLine(line: string): ParsedRipgrepLine {\n\tif (!line.trim()) return { matchedEvent: false };\n\tlet event: unknown;\n\ttry {\n\t\tevent = JSON.parse(line) as unknown;\n\t} catch {\n\t\treturn { matchedEvent: false };\n\t}\n\tif (!isUnknownRecord(event) || event.type !== \"match\") return { matchedEvent: false };\n\tconst data = isUnknownRecord(event.data) ? event.data : undefined;\n\tconst filePath = getRecordText(data?.path);\n\tconst lineNumber = data?.line_number;\n\tconst lineText = getRecordText(data?.lines);\n\treturn {\n\t\tmatchedEvent: true,\n\t\t...(typeof filePath === \"string\" && typeof lineNumber === \"number\"\n\t\t\t? { match: { filePath, lineNumber, ...(typeof lineText === \"string\" ? { lineText } : {}) } }\n\t\t\t: {}),\n\t};\n}\n\nfunction collectRipgrepLine(\n\tline: string,\n\tstate: RipgrepCollectionState,\n\tlimit: number,\n\tstopChild: (dueToLimit?: boolean) => void,\n): void {\n\tif (state.matchCount >= limit) return;\n\tconst parsed = parseRipgrepLine(line);\n\tif (!parsed.matchedEvent) return;\n\tstate.matchCount++;\n\tif (parsed.match) state.matches.push(parsed.match);\n\tif (state.matchCount >= limit) {\n\t\tstate.matchLimitReached = true;\n\t\tstopChild(true);\n\t}\n}\n\nasync function finishRipgrepExecution(\n\tcode: number | null,\n\tstate: RipgrepCollectionState,\n\tformatState: GrepFormatState,\n\tlimit: number,\n): Promise<AgentToolResult<GrepToolDetails | undefined>> {\n\tif (state.aborted) throw new Error(\"Operation aborted\");\n\tif (!state.killedDueToLimit && code !== 0 && code !== 1) {\n\t\tthrow new Error(state.stderr.trim() || `ripgrep exited with code ${code}`);\n\t}\n\tif (state.matchCount === 0) return noGrepMatchesResult();\n\tconst outputLines = await formatGrepMatches(formatState, state.matches);\n\treturn buildGrepResult(formatState, outputLines, state.matchLimitReached ? limit : undefined);\n}\n\nfunction executeRipgrep(\n\trgPath: string,\n\tinput: GrepExecutionInput,\n\tformatState: GrepFormatState,\n\tsignal?: AbortSignal,\n): Promise<AgentToolResult<GrepToolDetails | undefined>> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst child = spawn(rgPath, buildRipgrepArgs(input), { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n\t\tconst rl = createInterface({ input: child.stdout });\n\t\tconst state: RipgrepCollectionState = {\n\t\t\tstderr: \"\",\n\t\t\tmatchCount: 0,\n\t\t\tmatchLimitReached: false,\n\t\t\taborted: false,\n\t\t\tkilledDueToLimit: false,\n\t\t\tmatches: [],\n\t\t};\n\t\tconst cleanup = (): void => {\n\t\t\trl.close();\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t\tconst stopChild = (dueToLimit = false): void => {\n\t\t\tif (child.killed) return;\n\t\t\tstate.killedDueToLimit = dueToLimit;\n\t\t\tchild.kill();\n\t\t};\n\t\tconst onAbort = (): void => {\n\t\t\tstate.aborted = true;\n\t\t\tstopChild();\n\t\t};\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\tchild.stderr.on(\"data\", (chunk) => {\n\t\t\tstate.stderr += chunk.toString();\n\t\t});\n\t\trl.on(\"line\", (line) => collectRipgrepLine(line, state, input.limit, stopChild));\n\t\tchild.on(\"error\", (error) => {\n\t\t\tcleanup();\n\t\t\treject(new Error(`Failed to run ripgrep: ${error.message}`));\n\t\t});\n\t\tchild.on(\"close\", (code) => {\n\t\t\tcleanup();\n\t\t\tvoid finishRipgrepExecution(code, state, formatState, input.limit).then(resolve, reject);\n\t\t});\n\t});\n}\n\nasync function executeGrep(\n\toperations: ToolOperations,\n\tcwd: string,\n\tinput: GrepToolInput,\n\tsignal?: AbortSignal,\n): Promise<AgentToolResult<GrepToolDetails | undefined>> {\n\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\tconst searchPath = resolveToCwd(input.path || \".\", cwd);\n\tlet isDirectory: boolean;\n\ttry {\n\t\tisDirectory = (await operations.stat(searchPath)).isDirectory();\n\t} catch {\n\t\tthrow new Error(`Path not found: ${searchPath}`);\n\t}\n\tconst executionInput: GrepExecutionInput = {\n\t\tpattern: input.pattern,\n\t\tsearchPath,\n\t\tglob: input.glob,\n\t\tignoreCase: input.ignoreCase,\n\t\tliteral: input.literal,\n\t\tcontext: input.context && input.context > 0 ? input.context : 0,\n\t\tlimit: Math.max(1, input.limit ?? DEFAULT_LIMIT),\n\t};\n\tconst formatState: GrepFormatState = {\n\t\toperations,\n\t\tsearchPath,\n\t\tisDirectory,\n\t\tcontext: executionInput.context,\n\t\tfileCache: new Map(),\n\t\tlinesTruncated: false,\n\t};\n\tif (operations.grep) return executeOperationsGrep(operations, executionInput, formatState);\n\tconst rgPath = await ensureTool(\"rg\", true);\n\tif (!rgPath) throw new Error(\"ripgrep (rg) is not available and could not be downloaded\");\n\treturn executeRipgrep(rgPath, executionInput, formatState, signal);\n}\n\nexport type GrepToolDefinition = ToolDefinition<typeof grepSchema, GrepToolDetails | undefined>;\n\nexport function createGrepToolDefinition(operations: ToolOperations, _options?: GrepToolOptions): GrepToolDefinition {\n\tconst ops = operations;\n\tconst cwd = operations.cwd;\n\treturn {\n\t\tname: \"grep\",\n\t\tlabel: \"grep\",\n\t\tdescription: `Search file contents for a pattern. Returns matching lines with file paths and line numbers. Respects .gitignore. Output is truncated to ${DEFAULT_LIMIT} matches or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Long lines are truncated to ${GREP_MAX_LINE_LENGTH} chars.`,\n\t\tpromptSnippet: \"Search file contents for patterns (respects .gitignore)\",\n\t\tparameters: grepSchema,\n\t\tasync execute(_toolCallId, input: GrepToolInput, signal?: AbortSignal) {\n\t\t\treturn executeGrep(ops, cwd, input, signal);\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatBackendIcon(ops.getBackendInfo?.(), theme) + formatGrepCall(args, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatGrepResult(result, options, theme, context.showImages));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createGrepTool(operations: ToolOperations, options?: GrepToolOptions): AgentTool<typeof grepSchema> {\n\treturn wrapToolDefinition(createGrepToolDefinition(operations, options));\n}\n"]}
1
+ {"version":3,"file":"grep.d.ts","sourceRoot":"","sources":["../../../src/core/tools/grep.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAmB,MAAM,4BAA4B,CAAC;AAI7E,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAG5C,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AACtF,OAAO,KAAK,EAAiB,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAWrE,OAAO,EAIN,KAAK,gBAAgB,EAGrB,MAAM,eAAe,CAAC;AAEvB,QAAA,MAAM,UAAU;;;;;;;;EAYd,CAAC;AAEH,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAGtD,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,cAAc,CAAC,EAAE,OAAO,CAAC;CACzB;AAED,MAAM,WAAW,eAAe;CAAG;AAuVnC,MAAM,MAAM,kBAAkB,GAAG,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,CAAC,CAAC;AAEhG,wBAAgB,wBAAwB,CAAC,UAAU,EAAE,cAAc,EAAE,QAAQ,CAAC,EAAE,eAAe,GAAG,kBAAkB,CAuBnH;AAED,wBAAgB,cAAc,CAAC,UAAU,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAElH","sourcesContent":["import { createInterface } from \"node:readline\";\nimport type { AgentTool, AgentToolResult } from \"@greppleai/grip-agent-core\";\nimport { Text } from \"@greppleai/grip-tui\";\nimport { spawn } from \"child_process\";\nimport path from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { ensureTool } from \"../../utils/tools-manager.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport type { ToolGrepMatch, ToolOperations } from \"./operations.ts\";\nimport { resolveToCwd } from \"./path-utils.ts\";\nimport {\n\tformatBackendIcon,\n\tformatHiddenLinesHint,\n\tgetTextOutput,\n\tinvalidArgText,\n\tshortenPath,\n\tstr,\n} from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport {\n\tDEFAULT_MAX_BYTES,\n\tformatSize,\n\tGREP_MAX_LINE_LENGTH,\n\ttype TruncationResult,\n\ttruncateHead,\n\ttruncateLine,\n} from \"./truncate.ts\";\n\nconst grepSchema = Type.Object({\n\tpattern: Type.String({ description: \"Search pattern (regex or literal string)\" }),\n\tpath: Type.Optional(Type.String({ description: \"Directory or file to search (default: current directory)\" })),\n\tglob: Type.Optional(Type.String({ description: \"Filter files by glob pattern, e.g. '*.ts' or '**/*.spec.ts'\" })),\n\tignoreCase: Type.Optional(Type.Boolean({ description: \"Case-insensitive search (default: false)\" })),\n\tliteral: Type.Optional(\n\t\tType.Boolean({ description: \"Treat pattern as literal string instead of regex (default: false)\" }),\n\t),\n\tcontext: Type.Optional(\n\t\tType.Number({ description: \"Number of lines to show before and after each match (default: 0)\" }),\n\t),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of matches to return (default: 100)\" })),\n});\n\nexport type GrepToolInput = Static<typeof grepSchema>;\nconst DEFAULT_LIMIT = 100;\n\nexport interface GrepToolDetails {\n\ttruncation?: TruncationResult;\n\tmatchLimitReached?: number;\n\tlinesTruncated?: boolean;\n}\n\nexport interface GrepToolOptions {}\n\nfunction formatGrepCall(args: Partial<GrepToolInput> | undefined, theme: Theme): string {\n\tconst pattern = str(args?.pattern);\n\tconst rawPath = str(args?.path);\n\tconst path = rawPath !== null ? shortenPath(rawPath || \".\") : null;\n\tconst glob = str(args?.glob);\n\tconst limit = args?.limit;\n\tconst invalidArg = invalidArgText(theme);\n\tlet text =\n\t\ttheme.fg(\"toolTitle\", theme.bold(\"grep\")) +\n\t\t\" \" +\n\t\t(pattern === null ? invalidArg : theme.fg(\"accent\", `/${pattern || \"\"}/`)) +\n\t\ttheme.fg(\"toolOutput\", ` in ${path === null ? invalidArg : path}`);\n\tif (glob) text += theme.fg(\"toolOutput\", ` (${glob})`);\n\tif (limit !== undefined) text += theme.fg(\"toolOutput\", ` limit ${limit}`);\n\treturn text;\n}\n\nfunction formatGrepResult(\n\tresult: AgentToolResult<GrepToolDetails | undefined>,\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n): string {\n\tconst output = getTextOutput(result, showImages).trim();\n\tlet text = \"\";\n\tif (output) {\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst maxLines = options.expanded ? lines.length : 15;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n${displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `\\n\\n${formatHiddenLinesHint(remaining, theme)}`;\n\t\t}\n\t}\n\n\tconst matchLimit = result.details?.matchLimitReached;\n\tconst truncation = result.details?.truncation;\n\tconst linesTruncated = result.details?.linesTruncated;\n\tif (matchLimit || truncation?.truncated || linesTruncated) {\n\t\tconst warnings: string[] = [];\n\t\tif (matchLimit) warnings.push(`${matchLimit} matches limit`);\n\t\tif (truncation?.truncated) warnings.push(`${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit`);\n\t\tif (linesTruncated) warnings.push(\"some lines truncated\");\n\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${warnings.join(\", \")}]`)}`;\n\t}\n\treturn text;\n}\ninterface GrepFormatState {\n\toperations: ToolOperations;\n\tsearchPath: string;\n\tisDirectory: boolean;\n\tcontext: number;\n\tfileCache: Map<string, string[]>;\n\tlinesTruncated: boolean;\n}\n\ninterface GrepExecutionInput {\n\tpattern: string;\n\tsearchPath: string;\n\tglob?: string;\n\tignoreCase?: boolean;\n\tliteral?: boolean;\n\tcontext: number;\n\tlimit: number;\n}\n\ninterface RipgrepCollectionState {\n\tstderr: string;\n\tmatchCount: number;\n\tmatchLimitReached: boolean;\n\taborted: boolean;\n\tkilledDueToLimit: boolean;\n\tmatches: ToolGrepMatch[];\n}\n\nfunction noGrepMatchesResult(): AgentToolResult<GrepToolDetails | undefined> {\n\treturn { content: [{ type: \"text\", text: \"No matches found\" }], details: undefined };\n}\n\nfunction formatMatchedFilePath(state: GrepFormatState, filePath: string): string {\n\tif (state.isDirectory) {\n\t\tconst relative = path.relative(state.searchPath, filePath);\n\t\tif (relative && !relative.startsWith(\"..\")) return relative.replace(/\\\\/g, \"/\");\n\t}\n\treturn path.basename(filePath);\n}\n\nasync function getGrepFileLines(state: GrepFormatState, filePath: string): Promise<string[]> {\n\tconst cached = state.fileCache.get(filePath);\n\tif (cached) return cached;\n\tlet lines: string[];\n\ttry {\n\t\tconst content = (await state.operations.readFile(filePath)).toString(\"utf-8\");\n\t\tlines = content.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\").split(\"\\n\");\n\t} catch {\n\t\tlines = [];\n\t}\n\tstate.fileCache.set(filePath, lines);\n\treturn lines;\n}\n\nasync function formatGrepContextBlock(state: GrepFormatState, match: ToolGrepMatch): Promise<string[]> {\n\tconst relativePath = formatMatchedFilePath(state, match.filePath);\n\tconst lines = await getGrepFileLines(state, match.filePath);\n\tif (!lines.length) return [`${relativePath}:${match.lineNumber}: (unable to read file)`];\n\tconst block: string[] = [];\n\tconst start = state.context > 0 ? Math.max(1, match.lineNumber - state.context) : match.lineNumber;\n\tconst end = state.context > 0 ? Math.min(lines.length, match.lineNumber + state.context) : match.lineNumber;\n\tfor (let current = start; current <= end; current++) {\n\t\tconst sanitized = (lines[current - 1] ?? \"\").replace(/\\r/g, \"\");\n\t\tconst { text, wasTruncated } = truncateLine(sanitized);\n\t\tif (wasTruncated) state.linesTruncated = true;\n\t\tblock.push(\n\t\t\tcurrent === match.lineNumber ? `${relativePath}:${current}: ${text}` : `${relativePath}-${current}- ${text}`,\n\t\t);\n\t}\n\treturn block;\n}\n\nasync function formatGrepMatch(state: GrepFormatState, match: ToolGrepMatch): Promise<string[]> {\n\tif (state.context !== 0 || match.lineText === undefined) return formatGrepContextBlock(state, match);\n\tconst sanitized = match.lineText.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\").replace(/\\n$/, \"\");\n\tconst { text, wasTruncated } = truncateLine(sanitized);\n\tif (wasTruncated) state.linesTruncated = true;\n\treturn [`${formatMatchedFilePath(state, match.filePath)}:${match.lineNumber}: ${text}`];\n}\n\nasync function formatGrepMatches(state: GrepFormatState, matches: ToolGrepMatch[]): Promise<string[]> {\n\tconst outputLines: string[] = [];\n\tfor (const match of matches) outputLines.push(...(await formatGrepMatch(state, match)));\n\treturn outputLines;\n}\n\nfunction buildGrepResult(\n\tstate: GrepFormatState,\n\toutputLines: string[],\n\tmatchLimitReached: number | undefined,\n): AgentToolResult<GrepToolDetails | undefined> {\n\tconst truncation = truncateHead(outputLines.join(\"\\n\"), { maxLines: Number.MAX_SAFE_INTEGER });\n\tlet output = truncation.content;\n\tconst details: GrepToolDetails = {};\n\tconst notices: string[] = [];\n\tif (matchLimitReached !== undefined) {\n\t\tnotices.push(\n\t\t\t`${matchLimitReached} matches limit reached. Use limit=${matchLimitReached * 2} for more, or refine pattern`,\n\t\t);\n\t\tdetails.matchLimitReached = matchLimitReached;\n\t}\n\tif (truncation.truncated) {\n\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\tdetails.truncation = truncation;\n\t}\n\tif (state.linesTruncated) {\n\t\tnotices.push(`Some lines truncated to ${GREP_MAX_LINE_LENGTH} chars. Use read tool to see full lines`);\n\t\tdetails.linesTruncated = true;\n\t}\n\tif (notices.length > 0) output += `\\n\\n[${notices.join(\". \")}]`;\n\treturn {\n\t\tcontent: [{ type: \"text\", text: output }],\n\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t};\n}\n\nasync function executeOperationsGrep(\n\toperations: ToolOperations,\n\tinput: GrepExecutionInput,\n\tformatState: GrepFormatState,\n): Promise<AgentToolResult<GrepToolDetails | undefined>> {\n\tconst result = await operations.grep!({\n\t\tpattern: input.pattern,\n\t\tpath: input.searchPath,\n\t\tglob: input.glob,\n\t\tignoreCase: input.ignoreCase,\n\t\tliteral: input.literal,\n\t\tlimit: input.limit,\n\t});\n\tformatState.isDirectory = result.isDirectory;\n\tif (result.matches.length === 0) return noGrepMatchesResult();\n\tconst outputLines = await formatGrepMatches(formatState, result.matches);\n\treturn buildGrepResult(formatState, outputLines, result.matches.length >= input.limit ? input.limit : undefined);\n}\n\nfunction buildRipgrepArgs(input: GrepExecutionInput): string[] {\n\tconst args: string[] = [\"--json\", \"--line-number\", \"--color=never\", \"--hidden\"];\n\tif (input.ignoreCase) args.push(\"--ignore-case\");\n\tif (input.literal) args.push(\"--fixed-strings\");\n\tif (input.glob) args.push(\"--glob\", input.glob);\n\targs.push(\"--\", input.pattern, input.searchPath);\n\treturn args;\n}\n\ninterface ParsedRipgrepLine {\n\tmatchedEvent: boolean;\n\tmatch?: ToolGrepMatch;\n}\n\nfunction isUnknownRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction getRecordText(value: unknown): unknown {\n\treturn isUnknownRecord(value) ? value.text : undefined;\n}\n\nfunction parseRipgrepLine(line: string): ParsedRipgrepLine {\n\tif (!line.trim()) return { matchedEvent: false };\n\tlet event: unknown;\n\ttry {\n\t\tevent = JSON.parse(line) as unknown;\n\t} catch {\n\t\treturn { matchedEvent: false };\n\t}\n\tif (!isUnknownRecord(event) || event.type !== \"match\") return { matchedEvent: false };\n\tconst data = isUnknownRecord(event.data) ? event.data : undefined;\n\tconst filePath = getRecordText(data?.path);\n\tconst lineNumber = data?.line_number;\n\tconst lineText = getRecordText(data?.lines);\n\treturn {\n\t\tmatchedEvent: true,\n\t\t...(typeof filePath === \"string\" && typeof lineNumber === \"number\"\n\t\t\t? { match: { filePath, lineNumber, ...(typeof lineText === \"string\" ? { lineText } : {}) } }\n\t\t\t: {}),\n\t};\n}\n\nfunction collectRipgrepLine(\n\tline: string,\n\tstate: RipgrepCollectionState,\n\tlimit: number,\n\tstopChild: (dueToLimit?: boolean) => void,\n): void {\n\tif (state.matchCount >= limit) return;\n\tconst parsed = parseRipgrepLine(line);\n\tif (!parsed.matchedEvent) return;\n\tstate.matchCount++;\n\tif (parsed.match) state.matches.push(parsed.match);\n\tif (state.matchCount >= limit) {\n\t\tstate.matchLimitReached = true;\n\t\tstopChild(true);\n\t}\n}\n\nasync function finishRipgrepExecution(\n\tcode: number | null,\n\tstate: RipgrepCollectionState,\n\tformatState: GrepFormatState,\n\tlimit: number,\n): Promise<AgentToolResult<GrepToolDetails | undefined>> {\n\tif (state.aborted) throw new Error(\"Operation aborted\");\n\tif (!state.killedDueToLimit && code !== 0 && code !== 1) {\n\t\tthrow new Error(state.stderr.trim() || `ripgrep exited with code ${code}`);\n\t}\n\tif (state.matchCount === 0) return noGrepMatchesResult();\n\tconst outputLines = await formatGrepMatches(formatState, state.matches);\n\treturn buildGrepResult(formatState, outputLines, state.matchLimitReached ? limit : undefined);\n}\n\nfunction executeRipgrep(\n\trgPath: string,\n\tinput: GrepExecutionInput,\n\tformatState: GrepFormatState,\n\tsignal?: AbortSignal,\n): Promise<AgentToolResult<GrepToolDetails | undefined>> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst child = spawn(rgPath, buildRipgrepArgs(input), { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n\t\tconst rl = createInterface({ input: child.stdout });\n\t\tconst state: RipgrepCollectionState = {\n\t\t\tstderr: \"\",\n\t\t\tmatchCount: 0,\n\t\t\tmatchLimitReached: false,\n\t\t\taborted: false,\n\t\t\tkilledDueToLimit: false,\n\t\t\tmatches: [],\n\t\t};\n\t\tconst cleanup = (): void => {\n\t\t\trl.close();\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t\tconst stopChild = (dueToLimit = false): void => {\n\t\t\tif (child.killed) return;\n\t\t\tstate.killedDueToLimit = dueToLimit;\n\t\t\tchild.kill();\n\t\t};\n\t\tconst onAbort = (): void => {\n\t\t\tstate.aborted = true;\n\t\t\tstopChild();\n\t\t};\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\tchild.stderr.on(\"data\", (chunk) => {\n\t\t\tstate.stderr += chunk.toString();\n\t\t});\n\t\trl.on(\"line\", (line) => collectRipgrepLine(line, state, input.limit, stopChild));\n\t\tchild.on(\"error\", (error) => {\n\t\t\tcleanup();\n\t\t\treject(new Error(`Failed to run ripgrep: ${error.message}`));\n\t\t});\n\t\tchild.on(\"close\", (code) => {\n\t\t\tcleanup();\n\t\t\tvoid finishRipgrepExecution(code, state, formatState, input.limit).then(resolve, reject);\n\t\t});\n\t});\n}\n\nasync function executeGrep(\n\toperations: ToolOperations,\n\tcwd: string,\n\tinput: GrepToolInput,\n\tsignal?: AbortSignal,\n): Promise<AgentToolResult<GrepToolDetails | undefined>> {\n\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\tconst searchPath = resolveToCwd(input.path || \".\", cwd);\n\tlet isDirectory: boolean;\n\ttry {\n\t\tisDirectory = (await operations.stat(searchPath)).isDirectory();\n\t} catch {\n\t\tthrow new Error(`Path not found: ${searchPath}`);\n\t}\n\tconst executionInput: GrepExecutionInput = {\n\t\tpattern: input.pattern,\n\t\tsearchPath,\n\t\tglob: input.glob,\n\t\tignoreCase: input.ignoreCase,\n\t\tliteral: input.literal,\n\t\tcontext: input.context && input.context > 0 ? input.context : 0,\n\t\tlimit: Math.max(1, input.limit ?? DEFAULT_LIMIT),\n\t};\n\tconst formatState: GrepFormatState = {\n\t\toperations,\n\t\tsearchPath,\n\t\tisDirectory,\n\t\tcontext: executionInput.context,\n\t\tfileCache: new Map(),\n\t\tlinesTruncated: false,\n\t};\n\tif (operations.grep) return executeOperationsGrep(operations, executionInput, formatState);\n\tconst rgPath = await ensureTool(\"rg\", true);\n\tif (!rgPath) throw new Error(\"ripgrep (rg) is not available and could not be downloaded\");\n\treturn executeRipgrep(rgPath, executionInput, formatState, signal);\n}\n\nexport type GrepToolDefinition = ToolDefinition<typeof grepSchema, GrepToolDetails | undefined>;\n\nexport function createGrepToolDefinition(operations: ToolOperations, _options?: GrepToolOptions): GrepToolDefinition {\n\tconst ops = operations;\n\tconst cwd = operations.cwd;\n\treturn {\n\t\tname: \"grep\",\n\t\tlabel: \"grep\",\n\t\tdescription: `Search file contents for a pattern. Returns matching lines with file paths and line numbers. Respects .gitignore. Output is truncated to ${DEFAULT_LIMIT} matches or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Long lines are truncated to ${GREP_MAX_LINE_LENGTH} chars.`,\n\t\tpromptSnippet: \"Search file contents for patterns (respects .gitignore)\",\n\t\tparameters: grepSchema,\n\t\tasync execute(_toolCallId, input: GrepToolInput, signal?: AbortSignal) {\n\t\t\treturn executeGrep(ops, cwd, input, signal);\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatBackendIcon(ops.getBackendInfo?.(), theme) + formatGrepCall(args, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatGrepResult(result, options, theme, context.showImages));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createGrepTool(operations: ToolOperations, options?: GrepToolOptions): AgentTool<typeof grepSchema> {\n\treturn wrapToolDefinition(createGrepToolDefinition(operations, options));\n}\n"]}
@@ -3,10 +3,9 @@ import { Text } from "@greppleai/grip-tui";
3
3
  import { spawn } from "child_process";
4
4
  import path from "path";
5
5
  import { Type } from "typebox";
6
- import { keyHint } from "../../modes/interactive/components/keybinding-hints.js";
7
6
  import { ensureTool } from "../../utils/tools-manager.js";
8
7
  import { resolveToCwd } from "./path-utils.js";
9
- import { formatBackendIcon, getTextOutput, invalidArgText, shortenPath, str } from "./render-utils.js";
8
+ import { formatBackendIcon, formatHiddenLinesHint, getTextOutput, invalidArgText, shortenPath, str, } from "./render-utils.js";
10
9
  import { wrapToolDefinition } from "./tool-definition-wrapper.js";
11
10
  import { DEFAULT_MAX_BYTES, formatSize, GREP_MAX_LINE_LENGTH, truncateHead, truncateLine, } from "./truncate.js";
12
11
  const grepSchema = Type.Object({
@@ -46,7 +45,7 @@ function formatGrepResult(result, options, theme, showImages) {
46
45
  const remaining = lines.length - maxLines;
47
46
  text += `\n${displayLines.map((line) => theme.fg("toolOutput", line)).join("\n")}`;
48
47
  if (remaining > 0) {
49
- text += `${theme.fg("muted", `\n... (${remaining} more lines,`)} ${keyHint("app.tools.expand", "to expand")})`;
48
+ text += `\n\n${formatHiddenLinesHint(remaining, theme)}`;
50
49
  }
51
50
  }
52
51
  const matchLimit = result.details?.matchLimitReached;
@@ -1 +1 @@
1
- {"version":3,"file":"grep.js","sourceRoot":"","sources":["../../../src/core/tools/grep.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAEhD,OAAO,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAC;AAC3C,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AAEjF,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AAG1D,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,cAAc,EAAE,WAAW,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAA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AAC;AAAA,CACzE","sourcesContent":["import { createInterface } from \"node:readline\";\nimport type { AgentTool, AgentToolResult } from \"@greppleai/grip-agent-core\";\nimport { Text } from \"@greppleai/grip-tui\";\nimport { spawn } from \"child_process\";\nimport path from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { ensureTool } from \"../../utils/tools-manager.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport type { ToolGrepMatch, ToolOperations } from \"./operations.ts\";\nimport { resolveToCwd } from \"./path-utils.ts\";\nimport { formatBackendIcon, getTextOutput, invalidArgText, shortenPath, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport {\n\tDEFAULT_MAX_BYTES,\n\tformatSize,\n\tGREP_MAX_LINE_LENGTH,\n\ttype TruncationResult,\n\ttruncateHead,\n\ttruncateLine,\n} from \"./truncate.ts\";\n\nconst grepSchema = Type.Object({\n\tpattern: Type.String({ description: \"Search pattern (regex or literal string)\" }),\n\tpath: Type.Optional(Type.String({ description: \"Directory or file to search (default: current directory)\" })),\n\tglob: Type.Optional(Type.String({ description: \"Filter files by glob pattern, e.g. '*.ts' or '**/*.spec.ts'\" })),\n\tignoreCase: Type.Optional(Type.Boolean({ description: \"Case-insensitive search (default: false)\" })),\n\tliteral: Type.Optional(\n\t\tType.Boolean({ description: \"Treat pattern as literal string instead of regex (default: false)\" }),\n\t),\n\tcontext: Type.Optional(\n\t\tType.Number({ description: \"Number of lines to show before and after each match (default: 0)\" }),\n\t),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of matches to return (default: 100)\" })),\n});\n\nexport type GrepToolInput = Static<typeof grepSchema>;\nconst DEFAULT_LIMIT = 100;\n\nexport interface GrepToolDetails {\n\ttruncation?: TruncationResult;\n\tmatchLimitReached?: number;\n\tlinesTruncated?: boolean;\n}\n\nexport interface GrepToolOptions {}\n\nfunction formatGrepCall(args: Partial<GrepToolInput> | undefined, theme: Theme): string {\n\tconst pattern = str(args?.pattern);\n\tconst rawPath = str(args?.path);\n\tconst path = rawPath !== null ? shortenPath(rawPath || \".\") : null;\n\tconst glob = str(args?.glob);\n\tconst limit = args?.limit;\n\tconst invalidArg = invalidArgText(theme);\n\tlet text =\n\t\ttheme.fg(\"toolTitle\", theme.bold(\"grep\")) +\n\t\t\" \" +\n\t\t(pattern === null ? invalidArg : theme.fg(\"accent\", `/${pattern || \"\"}/`)) +\n\t\ttheme.fg(\"toolOutput\", ` in ${path === null ? invalidArg : path}`);\n\tif (glob) text += theme.fg(\"toolOutput\", ` (${glob})`);\n\tif (limit !== undefined) text += theme.fg(\"toolOutput\", ` limit ${limit}`);\n\treturn text;\n}\n\nfunction formatGrepResult(\n\tresult: AgentToolResult<GrepToolDetails | undefined>,\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n): string {\n\tconst output = getTextOutput(result, showImages).trim();\n\tlet text = \"\";\n\tif (output) {\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst maxLines = options.expanded ? lines.length : 15;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n${displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")})`;\n\t\t}\n\t}\n\n\tconst matchLimit = result.details?.matchLimitReached;\n\tconst truncation = result.details?.truncation;\n\tconst linesTruncated = result.details?.linesTruncated;\n\tif (matchLimit || truncation?.truncated || linesTruncated) {\n\t\tconst warnings: string[] = [];\n\t\tif (matchLimit) warnings.push(`${matchLimit} matches limit`);\n\t\tif (truncation?.truncated) warnings.push(`${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit`);\n\t\tif (linesTruncated) warnings.push(\"some lines truncated\");\n\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${warnings.join(\", \")}]`)}`;\n\t}\n\treturn text;\n}\ninterface GrepFormatState {\n\toperations: ToolOperations;\n\tsearchPath: string;\n\tisDirectory: boolean;\n\tcontext: number;\n\tfileCache: Map<string, string[]>;\n\tlinesTruncated: boolean;\n}\n\ninterface GrepExecutionInput {\n\tpattern: string;\n\tsearchPath: string;\n\tglob?: string;\n\tignoreCase?: boolean;\n\tliteral?: boolean;\n\tcontext: number;\n\tlimit: number;\n}\n\ninterface RipgrepCollectionState {\n\tstderr: string;\n\tmatchCount: number;\n\tmatchLimitReached: boolean;\n\taborted: boolean;\n\tkilledDueToLimit: boolean;\n\tmatches: ToolGrepMatch[];\n}\n\nfunction noGrepMatchesResult(): AgentToolResult<GrepToolDetails | undefined> {\n\treturn { content: [{ type: \"text\", text: \"No matches found\" }], details: undefined };\n}\n\nfunction formatMatchedFilePath(state: GrepFormatState, filePath: string): string {\n\tif (state.isDirectory) {\n\t\tconst relative = path.relative(state.searchPath, filePath);\n\t\tif (relative && !relative.startsWith(\"..\")) return relative.replace(/\\\\/g, \"/\");\n\t}\n\treturn path.basename(filePath);\n}\n\nasync function getGrepFileLines(state: GrepFormatState, filePath: string): Promise<string[]> {\n\tconst cached = state.fileCache.get(filePath);\n\tif (cached) return cached;\n\tlet lines: string[];\n\ttry {\n\t\tconst content = (await state.operations.readFile(filePath)).toString(\"utf-8\");\n\t\tlines = content.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\").split(\"\\n\");\n\t} catch {\n\t\tlines = [];\n\t}\n\tstate.fileCache.set(filePath, lines);\n\treturn lines;\n}\n\nasync function formatGrepContextBlock(state: GrepFormatState, match: ToolGrepMatch): Promise<string[]> {\n\tconst relativePath = formatMatchedFilePath(state, match.filePath);\n\tconst lines = await getGrepFileLines(state, match.filePath);\n\tif (!lines.length) return [`${relativePath}:${match.lineNumber}: (unable to read file)`];\n\tconst block: string[] = [];\n\tconst start = state.context > 0 ? Math.max(1, match.lineNumber - state.context) : match.lineNumber;\n\tconst end = state.context > 0 ? Math.min(lines.length, match.lineNumber + state.context) : match.lineNumber;\n\tfor (let current = start; current <= end; current++) {\n\t\tconst sanitized = (lines[current - 1] ?? \"\").replace(/\\r/g, \"\");\n\t\tconst { text, wasTruncated } = truncateLine(sanitized);\n\t\tif (wasTruncated) state.linesTruncated = true;\n\t\tblock.push(\n\t\t\tcurrent === match.lineNumber ? `${relativePath}:${current}: ${text}` : `${relativePath}-${current}- ${text}`,\n\t\t);\n\t}\n\treturn block;\n}\n\nasync function formatGrepMatch(state: GrepFormatState, match: ToolGrepMatch): Promise<string[]> {\n\tif (state.context !== 0 || match.lineText === undefined) return formatGrepContextBlock(state, match);\n\tconst sanitized = match.lineText.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\").replace(/\\n$/, \"\");\n\tconst { text, wasTruncated } = truncateLine(sanitized);\n\tif (wasTruncated) state.linesTruncated = true;\n\treturn [`${formatMatchedFilePath(state, match.filePath)}:${match.lineNumber}: ${text}`];\n}\n\nasync function formatGrepMatches(state: GrepFormatState, matches: ToolGrepMatch[]): Promise<string[]> {\n\tconst outputLines: string[] = [];\n\tfor (const match of matches) outputLines.push(...(await formatGrepMatch(state, match)));\n\treturn outputLines;\n}\n\nfunction buildGrepResult(\n\tstate: GrepFormatState,\n\toutputLines: string[],\n\tmatchLimitReached: number | undefined,\n): AgentToolResult<GrepToolDetails | undefined> {\n\tconst truncation = truncateHead(outputLines.join(\"\\n\"), { maxLines: Number.MAX_SAFE_INTEGER });\n\tlet output = truncation.content;\n\tconst details: GrepToolDetails = {};\n\tconst notices: string[] = [];\n\tif (matchLimitReached !== undefined) {\n\t\tnotices.push(\n\t\t\t`${matchLimitReached} matches limit reached. Use limit=${matchLimitReached * 2} for more, or refine pattern`,\n\t\t);\n\t\tdetails.matchLimitReached = matchLimitReached;\n\t}\n\tif (truncation.truncated) {\n\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\tdetails.truncation = truncation;\n\t}\n\tif (state.linesTruncated) {\n\t\tnotices.push(`Some lines truncated to ${GREP_MAX_LINE_LENGTH} chars. Use read tool to see full lines`);\n\t\tdetails.linesTruncated = true;\n\t}\n\tif (notices.length > 0) output += `\\n\\n[${notices.join(\". \")}]`;\n\treturn {\n\t\tcontent: [{ type: \"text\", text: output }],\n\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t};\n}\n\nasync function executeOperationsGrep(\n\toperations: ToolOperations,\n\tinput: GrepExecutionInput,\n\tformatState: GrepFormatState,\n): Promise<AgentToolResult<GrepToolDetails | undefined>> {\n\tconst result = await operations.grep!({\n\t\tpattern: input.pattern,\n\t\tpath: input.searchPath,\n\t\tglob: input.glob,\n\t\tignoreCase: input.ignoreCase,\n\t\tliteral: input.literal,\n\t\tlimit: input.limit,\n\t});\n\tformatState.isDirectory = result.isDirectory;\n\tif (result.matches.length === 0) return noGrepMatchesResult();\n\tconst outputLines = await formatGrepMatches(formatState, result.matches);\n\treturn buildGrepResult(formatState, outputLines, result.matches.length >= input.limit ? input.limit : undefined);\n}\n\nfunction buildRipgrepArgs(input: GrepExecutionInput): string[] {\n\tconst args: string[] = [\"--json\", \"--line-number\", \"--color=never\", \"--hidden\"];\n\tif (input.ignoreCase) args.push(\"--ignore-case\");\n\tif (input.literal) args.push(\"--fixed-strings\");\n\tif (input.glob) args.push(\"--glob\", input.glob);\n\targs.push(\"--\", input.pattern, input.searchPath);\n\treturn args;\n}\n\ninterface ParsedRipgrepLine {\n\tmatchedEvent: boolean;\n\tmatch?: ToolGrepMatch;\n}\n\nfunction isUnknownRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction getRecordText(value: unknown): unknown {\n\treturn isUnknownRecord(value) ? value.text : undefined;\n}\n\nfunction parseRipgrepLine(line: string): ParsedRipgrepLine {\n\tif (!line.trim()) return { matchedEvent: false };\n\tlet event: unknown;\n\ttry {\n\t\tevent = JSON.parse(line) as unknown;\n\t} catch {\n\t\treturn { matchedEvent: false };\n\t}\n\tif (!isUnknownRecord(event) || event.type !== \"match\") return { matchedEvent: false };\n\tconst data = isUnknownRecord(event.data) ? event.data : undefined;\n\tconst filePath = getRecordText(data?.path);\n\tconst lineNumber = data?.line_number;\n\tconst lineText = getRecordText(data?.lines);\n\treturn {\n\t\tmatchedEvent: true,\n\t\t...(typeof filePath === \"string\" && typeof lineNumber === \"number\"\n\t\t\t? { match: { filePath, lineNumber, ...(typeof lineText === \"string\" ? { lineText } : {}) } }\n\t\t\t: {}),\n\t};\n}\n\nfunction collectRipgrepLine(\n\tline: string,\n\tstate: RipgrepCollectionState,\n\tlimit: number,\n\tstopChild: (dueToLimit?: boolean) => void,\n): void {\n\tif (state.matchCount >= limit) return;\n\tconst parsed = parseRipgrepLine(line);\n\tif (!parsed.matchedEvent) return;\n\tstate.matchCount++;\n\tif (parsed.match) state.matches.push(parsed.match);\n\tif (state.matchCount >= limit) {\n\t\tstate.matchLimitReached = true;\n\t\tstopChild(true);\n\t}\n}\n\nasync function finishRipgrepExecution(\n\tcode: number | null,\n\tstate: RipgrepCollectionState,\n\tformatState: GrepFormatState,\n\tlimit: number,\n): Promise<AgentToolResult<GrepToolDetails | undefined>> {\n\tif (state.aborted) throw new Error(\"Operation aborted\");\n\tif (!state.killedDueToLimit && code !== 0 && code !== 1) {\n\t\tthrow new Error(state.stderr.trim() || `ripgrep exited with code ${code}`);\n\t}\n\tif (state.matchCount === 0) return noGrepMatchesResult();\n\tconst outputLines = await formatGrepMatches(formatState, state.matches);\n\treturn buildGrepResult(formatState, outputLines, state.matchLimitReached ? limit : undefined);\n}\n\nfunction executeRipgrep(\n\trgPath: string,\n\tinput: GrepExecutionInput,\n\tformatState: GrepFormatState,\n\tsignal?: AbortSignal,\n): Promise<AgentToolResult<GrepToolDetails | undefined>> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst child = spawn(rgPath, buildRipgrepArgs(input), { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n\t\tconst rl = createInterface({ input: child.stdout });\n\t\tconst state: RipgrepCollectionState = {\n\t\t\tstderr: \"\",\n\t\t\tmatchCount: 0,\n\t\t\tmatchLimitReached: false,\n\t\t\taborted: false,\n\t\t\tkilledDueToLimit: false,\n\t\t\tmatches: [],\n\t\t};\n\t\tconst cleanup = (): void => {\n\t\t\trl.close();\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t\tconst stopChild = (dueToLimit = false): void => {\n\t\t\tif (child.killed) return;\n\t\t\tstate.killedDueToLimit = dueToLimit;\n\t\t\tchild.kill();\n\t\t};\n\t\tconst onAbort = (): void => {\n\t\t\tstate.aborted = true;\n\t\t\tstopChild();\n\t\t};\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\tchild.stderr.on(\"data\", (chunk) => {\n\t\t\tstate.stderr += chunk.toString();\n\t\t});\n\t\trl.on(\"line\", (line) => collectRipgrepLine(line, state, input.limit, stopChild));\n\t\tchild.on(\"error\", (error) => {\n\t\t\tcleanup();\n\t\t\treject(new Error(`Failed to run ripgrep: ${error.message}`));\n\t\t});\n\t\tchild.on(\"close\", (code) => {\n\t\t\tcleanup();\n\t\t\tvoid finishRipgrepExecution(code, state, formatState, input.limit).then(resolve, reject);\n\t\t});\n\t});\n}\n\nasync function executeGrep(\n\toperations: ToolOperations,\n\tcwd: string,\n\tinput: GrepToolInput,\n\tsignal?: AbortSignal,\n): Promise<AgentToolResult<GrepToolDetails | undefined>> {\n\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\tconst searchPath = resolveToCwd(input.path || \".\", cwd);\n\tlet isDirectory: boolean;\n\ttry {\n\t\tisDirectory = (await operations.stat(searchPath)).isDirectory();\n\t} catch {\n\t\tthrow new Error(`Path not found: ${searchPath}`);\n\t}\n\tconst executionInput: GrepExecutionInput = {\n\t\tpattern: input.pattern,\n\t\tsearchPath,\n\t\tglob: input.glob,\n\t\tignoreCase: input.ignoreCase,\n\t\tliteral: input.literal,\n\t\tcontext: input.context && input.context > 0 ? input.context : 0,\n\t\tlimit: Math.max(1, input.limit ?? DEFAULT_LIMIT),\n\t};\n\tconst formatState: GrepFormatState = {\n\t\toperations,\n\t\tsearchPath,\n\t\tisDirectory,\n\t\tcontext: executionInput.context,\n\t\tfileCache: new Map(),\n\t\tlinesTruncated: false,\n\t};\n\tif (operations.grep) return executeOperationsGrep(operations, executionInput, formatState);\n\tconst rgPath = await ensureTool(\"rg\", true);\n\tif (!rgPath) throw new Error(\"ripgrep (rg) is not available and could not be downloaded\");\n\treturn executeRipgrep(rgPath, executionInput, formatState, signal);\n}\n\nexport type GrepToolDefinition = ToolDefinition<typeof grepSchema, GrepToolDetails | undefined>;\n\nexport function createGrepToolDefinition(operations: ToolOperations, _options?: GrepToolOptions): GrepToolDefinition {\n\tconst ops = operations;\n\tconst cwd = operations.cwd;\n\treturn {\n\t\tname: \"grep\",\n\t\tlabel: \"grep\",\n\t\tdescription: `Search file contents for a pattern. Returns matching lines with file paths and line numbers. Respects .gitignore. Output is truncated to ${DEFAULT_LIMIT} matches or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Long lines are truncated to ${GREP_MAX_LINE_LENGTH} chars.`,\n\t\tpromptSnippet: \"Search file contents for patterns (respects .gitignore)\",\n\t\tparameters: grepSchema,\n\t\tasync execute(_toolCallId, input: GrepToolInput, signal?: AbortSignal) {\n\t\t\treturn executeGrep(ops, cwd, input, signal);\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatBackendIcon(ops.getBackendInfo?.(), theme) + formatGrepCall(args, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatGrepResult(result, options, theme, context.showImages));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createGrepTool(operations: ToolOperations, options?: GrepToolOptions): AgentTool<typeof grepSchema> {\n\treturn wrapToolDefinition(createGrepToolDefinition(operations, options));\n}\n"]}
1
+ {"version":3,"file":"grep.js","sourceRoot":"","sources":["../../../src/core/tools/grep.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAEhD,OAAO,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAC;AAC3C,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AAG1D,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EACN,iBAAiB,EACjB,qBAAqB,EACrB,aAAa,EACb,cAAc,EACd,WAAW,EACX,GAAG,GACH,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EACN,iBAAiB,EACjB,UAAU,EACV,oBAAoB,EAEpB,YAAY,EACZ,YAAY,GACZ,MAAM,eAAe,CAAC;AAEvB,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC;IAC9B,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,0CAA0C,EAAE,CAAC;IACjF,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,0DAA0D,EAAE,CAAC,CAAC;IAC7G,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,6DAA6D,EAAE,CAAC,CAAC;IAChH,UAAU,EAAE,IAAI,CAAC,QAAQ,CAA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CAAC,cAAc,EAAE,EAAE,EAAE,KAAK,CAAC,GAAG,cAAc,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC;YAC7F,OAAO,IAAI,CAAC;QAAA,CACZ;QACD,YAAY,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE;YAC7C,MAAM,IAAI,GAAI,OAAO,CAAC,aAAkC,IAAI,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YAC/E,IAAI,CAAC,OAAO,CAAC,gBAAgB,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC;YAC3E,OAAO,IAAI,CAAC;QAAA,CACZ;KACD,CAAC;AAAA,CACF;AAED,MAAM,UAAU,cAAc,CAAC,UAA0B,EAAE,OAAyB,EAAgC;IACnH,OAAO,kBAAkB,CAAC,wBAAwB,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC,CAAC;AAAA,CACzE","sourcesContent":["import { createInterface } from \"node:readline\";\nimport type { AgentTool, AgentToolResult } from \"@greppleai/grip-agent-core\";\nimport { Text } from \"@greppleai/grip-tui\";\nimport { spawn } from \"child_process\";\nimport path from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { ensureTool } from \"../../utils/tools-manager.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport type { ToolGrepMatch, ToolOperations } from \"./operations.ts\";\nimport { resolveToCwd } from \"./path-utils.ts\";\nimport {\n\tformatBackendIcon,\n\tformatHiddenLinesHint,\n\tgetTextOutput,\n\tinvalidArgText,\n\tshortenPath,\n\tstr,\n} from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport {\n\tDEFAULT_MAX_BYTES,\n\tformatSize,\n\tGREP_MAX_LINE_LENGTH,\n\ttype TruncationResult,\n\ttruncateHead,\n\ttruncateLine,\n} from \"./truncate.ts\";\n\nconst grepSchema = Type.Object({\n\tpattern: Type.String({ description: \"Search pattern (regex or literal string)\" }),\n\tpath: Type.Optional(Type.String({ description: \"Directory or file to search (default: current directory)\" })),\n\tglob: Type.Optional(Type.String({ description: \"Filter files by glob pattern, e.g. '*.ts' or '**/*.spec.ts'\" })),\n\tignoreCase: Type.Optional(Type.Boolean({ description: \"Case-insensitive search (default: false)\" })),\n\tliteral: Type.Optional(\n\t\tType.Boolean({ description: \"Treat pattern as literal string instead of regex (default: false)\" }),\n\t),\n\tcontext: Type.Optional(\n\t\tType.Number({ description: \"Number of lines to show before and after each match (default: 0)\" }),\n\t),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of matches to return (default: 100)\" })),\n});\n\nexport type GrepToolInput = Static<typeof grepSchema>;\nconst DEFAULT_LIMIT = 100;\n\nexport interface GrepToolDetails {\n\ttruncation?: TruncationResult;\n\tmatchLimitReached?: number;\n\tlinesTruncated?: boolean;\n}\n\nexport interface GrepToolOptions {}\n\nfunction formatGrepCall(args: Partial<GrepToolInput> | undefined, theme: Theme): string {\n\tconst pattern = str(args?.pattern);\n\tconst rawPath = str(args?.path);\n\tconst path = rawPath !== null ? shortenPath(rawPath || \".\") : null;\n\tconst glob = str(args?.glob);\n\tconst limit = args?.limit;\n\tconst invalidArg = invalidArgText(theme);\n\tlet text =\n\t\ttheme.fg(\"toolTitle\", theme.bold(\"grep\")) +\n\t\t\" \" +\n\t\t(pattern === null ? invalidArg : theme.fg(\"accent\", `/${pattern || \"\"}/`)) +\n\t\ttheme.fg(\"toolOutput\", ` in ${path === null ? invalidArg : path}`);\n\tif (glob) text += theme.fg(\"toolOutput\", ` (${glob})`);\n\tif (limit !== undefined) text += theme.fg(\"toolOutput\", ` limit ${limit}`);\n\treturn text;\n}\n\nfunction formatGrepResult(\n\tresult: AgentToolResult<GrepToolDetails | undefined>,\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n): string {\n\tconst output = getTextOutput(result, showImages).trim();\n\tlet text = \"\";\n\tif (output) {\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst maxLines = options.expanded ? lines.length : 15;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n${displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `\\n\\n${formatHiddenLinesHint(remaining, theme)}`;\n\t\t}\n\t}\n\n\tconst matchLimit = result.details?.matchLimitReached;\n\tconst truncation = result.details?.truncation;\n\tconst linesTruncated = result.details?.linesTruncated;\n\tif (matchLimit || truncation?.truncated || linesTruncated) {\n\t\tconst warnings: string[] = [];\n\t\tif (matchLimit) warnings.push(`${matchLimit} matches limit`);\n\t\tif (truncation?.truncated) warnings.push(`${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit`);\n\t\tif (linesTruncated) warnings.push(\"some lines truncated\");\n\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${warnings.join(\", \")}]`)}`;\n\t}\n\treturn text;\n}\ninterface GrepFormatState {\n\toperations: ToolOperations;\n\tsearchPath: string;\n\tisDirectory: boolean;\n\tcontext: number;\n\tfileCache: Map<string, string[]>;\n\tlinesTruncated: boolean;\n}\n\ninterface GrepExecutionInput {\n\tpattern: string;\n\tsearchPath: string;\n\tglob?: string;\n\tignoreCase?: boolean;\n\tliteral?: boolean;\n\tcontext: number;\n\tlimit: number;\n}\n\ninterface RipgrepCollectionState {\n\tstderr: string;\n\tmatchCount: number;\n\tmatchLimitReached: boolean;\n\taborted: boolean;\n\tkilledDueToLimit: boolean;\n\tmatches: ToolGrepMatch[];\n}\n\nfunction noGrepMatchesResult(): AgentToolResult<GrepToolDetails | undefined> {\n\treturn { content: [{ type: \"text\", text: \"No matches found\" }], details: undefined };\n}\n\nfunction formatMatchedFilePath(state: GrepFormatState, filePath: string): string {\n\tif (state.isDirectory) {\n\t\tconst relative = path.relative(state.searchPath, filePath);\n\t\tif (relative && !relative.startsWith(\"..\")) return relative.replace(/\\\\/g, \"/\");\n\t}\n\treturn path.basename(filePath);\n}\n\nasync function getGrepFileLines(state: GrepFormatState, filePath: string): Promise<string[]> {\n\tconst cached = state.fileCache.get(filePath);\n\tif (cached) return cached;\n\tlet lines: string[];\n\ttry {\n\t\tconst content = (await state.operations.readFile(filePath)).toString(\"utf-8\");\n\t\tlines = content.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\").split(\"\\n\");\n\t} catch {\n\t\tlines = [];\n\t}\n\tstate.fileCache.set(filePath, lines);\n\treturn lines;\n}\n\nasync function formatGrepContextBlock(state: GrepFormatState, match: ToolGrepMatch): Promise<string[]> {\n\tconst relativePath = formatMatchedFilePath(state, match.filePath);\n\tconst lines = await getGrepFileLines(state, match.filePath);\n\tif (!lines.length) return [`${relativePath}:${match.lineNumber}: (unable to read file)`];\n\tconst block: string[] = [];\n\tconst start = state.context > 0 ? Math.max(1, match.lineNumber - state.context) : match.lineNumber;\n\tconst end = state.context > 0 ? Math.min(lines.length, match.lineNumber + state.context) : match.lineNumber;\n\tfor (let current = start; current <= end; current++) {\n\t\tconst sanitized = (lines[current - 1] ?? \"\").replace(/\\r/g, \"\");\n\t\tconst { text, wasTruncated } = truncateLine(sanitized);\n\t\tif (wasTruncated) state.linesTruncated = true;\n\t\tblock.push(\n\t\t\tcurrent === match.lineNumber ? `${relativePath}:${current}: ${text}` : `${relativePath}-${current}- ${text}`,\n\t\t);\n\t}\n\treturn block;\n}\n\nasync function formatGrepMatch(state: GrepFormatState, match: ToolGrepMatch): Promise<string[]> {\n\tif (state.context !== 0 || match.lineText === undefined) return formatGrepContextBlock(state, match);\n\tconst sanitized = match.lineText.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\").replace(/\\n$/, \"\");\n\tconst { text, wasTruncated } = truncateLine(sanitized);\n\tif (wasTruncated) state.linesTruncated = true;\n\treturn [`${formatMatchedFilePath(state, match.filePath)}:${match.lineNumber}: ${text}`];\n}\n\nasync function formatGrepMatches(state: GrepFormatState, matches: ToolGrepMatch[]): Promise<string[]> {\n\tconst outputLines: string[] = [];\n\tfor (const match of matches) outputLines.push(...(await formatGrepMatch(state, match)));\n\treturn outputLines;\n}\n\nfunction buildGrepResult(\n\tstate: GrepFormatState,\n\toutputLines: string[],\n\tmatchLimitReached: number | undefined,\n): AgentToolResult<GrepToolDetails | undefined> {\n\tconst truncation = truncateHead(outputLines.join(\"\\n\"), { maxLines: Number.MAX_SAFE_INTEGER });\n\tlet output = truncation.content;\n\tconst details: GrepToolDetails = {};\n\tconst notices: string[] = [];\n\tif (matchLimitReached !== undefined) {\n\t\tnotices.push(\n\t\t\t`${matchLimitReached} matches limit reached. Use limit=${matchLimitReached * 2} for more, or refine pattern`,\n\t\t);\n\t\tdetails.matchLimitReached = matchLimitReached;\n\t}\n\tif (truncation.truncated) {\n\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\tdetails.truncation = truncation;\n\t}\n\tif (state.linesTruncated) {\n\t\tnotices.push(`Some lines truncated to ${GREP_MAX_LINE_LENGTH} chars. Use read tool to see full lines`);\n\t\tdetails.linesTruncated = true;\n\t}\n\tif (notices.length > 0) output += `\\n\\n[${notices.join(\". \")}]`;\n\treturn {\n\t\tcontent: [{ type: \"text\", text: output }],\n\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t};\n}\n\nasync function executeOperationsGrep(\n\toperations: ToolOperations,\n\tinput: GrepExecutionInput,\n\tformatState: GrepFormatState,\n): Promise<AgentToolResult<GrepToolDetails | undefined>> {\n\tconst result = await operations.grep!({\n\t\tpattern: input.pattern,\n\t\tpath: input.searchPath,\n\t\tglob: input.glob,\n\t\tignoreCase: input.ignoreCase,\n\t\tliteral: input.literal,\n\t\tlimit: input.limit,\n\t});\n\tformatState.isDirectory = result.isDirectory;\n\tif (result.matches.length === 0) return noGrepMatchesResult();\n\tconst outputLines = await formatGrepMatches(formatState, result.matches);\n\treturn buildGrepResult(formatState, outputLines, result.matches.length >= input.limit ? input.limit : undefined);\n}\n\nfunction buildRipgrepArgs(input: GrepExecutionInput): string[] {\n\tconst args: string[] = [\"--json\", \"--line-number\", \"--color=never\", \"--hidden\"];\n\tif (input.ignoreCase) args.push(\"--ignore-case\");\n\tif (input.literal) args.push(\"--fixed-strings\");\n\tif (input.glob) args.push(\"--glob\", input.glob);\n\targs.push(\"--\", input.pattern, input.searchPath);\n\treturn args;\n}\n\ninterface ParsedRipgrepLine {\n\tmatchedEvent: boolean;\n\tmatch?: ToolGrepMatch;\n}\n\nfunction isUnknownRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction getRecordText(value: unknown): unknown {\n\treturn isUnknownRecord(value) ? value.text : undefined;\n}\n\nfunction parseRipgrepLine(line: string): ParsedRipgrepLine {\n\tif (!line.trim()) return { matchedEvent: false };\n\tlet event: unknown;\n\ttry {\n\t\tevent = JSON.parse(line) as unknown;\n\t} catch {\n\t\treturn { matchedEvent: false };\n\t}\n\tif (!isUnknownRecord(event) || event.type !== \"match\") return { matchedEvent: false };\n\tconst data = isUnknownRecord(event.data) ? event.data : undefined;\n\tconst filePath = getRecordText(data?.path);\n\tconst lineNumber = data?.line_number;\n\tconst lineText = getRecordText(data?.lines);\n\treturn {\n\t\tmatchedEvent: true,\n\t\t...(typeof filePath === \"string\" && typeof lineNumber === \"number\"\n\t\t\t? { match: { filePath, lineNumber, ...(typeof lineText === \"string\" ? { lineText } : {}) } }\n\t\t\t: {}),\n\t};\n}\n\nfunction collectRipgrepLine(\n\tline: string,\n\tstate: RipgrepCollectionState,\n\tlimit: number,\n\tstopChild: (dueToLimit?: boolean) => void,\n): void {\n\tif (state.matchCount >= limit) return;\n\tconst parsed = parseRipgrepLine(line);\n\tif (!parsed.matchedEvent) return;\n\tstate.matchCount++;\n\tif (parsed.match) state.matches.push(parsed.match);\n\tif (state.matchCount >= limit) {\n\t\tstate.matchLimitReached = true;\n\t\tstopChild(true);\n\t}\n}\n\nasync function finishRipgrepExecution(\n\tcode: number | null,\n\tstate: RipgrepCollectionState,\n\tformatState: GrepFormatState,\n\tlimit: number,\n): Promise<AgentToolResult<GrepToolDetails | undefined>> {\n\tif (state.aborted) throw new Error(\"Operation aborted\");\n\tif (!state.killedDueToLimit && code !== 0 && code !== 1) {\n\t\tthrow new Error(state.stderr.trim() || `ripgrep exited with code ${code}`);\n\t}\n\tif (state.matchCount === 0) return noGrepMatchesResult();\n\tconst outputLines = await formatGrepMatches(formatState, state.matches);\n\treturn buildGrepResult(formatState, outputLines, state.matchLimitReached ? limit : undefined);\n}\n\nfunction executeRipgrep(\n\trgPath: string,\n\tinput: GrepExecutionInput,\n\tformatState: GrepFormatState,\n\tsignal?: AbortSignal,\n): Promise<AgentToolResult<GrepToolDetails | undefined>> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst child = spawn(rgPath, buildRipgrepArgs(input), { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n\t\tconst rl = createInterface({ input: child.stdout });\n\t\tconst state: RipgrepCollectionState = {\n\t\t\tstderr: \"\",\n\t\t\tmatchCount: 0,\n\t\t\tmatchLimitReached: false,\n\t\t\taborted: false,\n\t\t\tkilledDueToLimit: false,\n\t\t\tmatches: [],\n\t\t};\n\t\tconst cleanup = (): void => {\n\t\t\trl.close();\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t\tconst stopChild = (dueToLimit = false): void => {\n\t\t\tif (child.killed) return;\n\t\t\tstate.killedDueToLimit = dueToLimit;\n\t\t\tchild.kill();\n\t\t};\n\t\tconst onAbort = (): void => {\n\t\t\tstate.aborted = true;\n\t\t\tstopChild();\n\t\t};\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\tchild.stderr.on(\"data\", (chunk) => {\n\t\t\tstate.stderr += chunk.toString();\n\t\t});\n\t\trl.on(\"line\", (line) => collectRipgrepLine(line, state, input.limit, stopChild));\n\t\tchild.on(\"error\", (error) => {\n\t\t\tcleanup();\n\t\t\treject(new Error(`Failed to run ripgrep: ${error.message}`));\n\t\t});\n\t\tchild.on(\"close\", (code) => {\n\t\t\tcleanup();\n\t\t\tvoid finishRipgrepExecution(code, state, formatState, input.limit).then(resolve, reject);\n\t\t});\n\t});\n}\n\nasync function executeGrep(\n\toperations: ToolOperations,\n\tcwd: string,\n\tinput: GrepToolInput,\n\tsignal?: AbortSignal,\n): Promise<AgentToolResult<GrepToolDetails | undefined>> {\n\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\tconst searchPath = resolveToCwd(input.path || \".\", cwd);\n\tlet isDirectory: boolean;\n\ttry {\n\t\tisDirectory = (await operations.stat(searchPath)).isDirectory();\n\t} catch {\n\t\tthrow new Error(`Path not found: ${searchPath}`);\n\t}\n\tconst executionInput: GrepExecutionInput = {\n\t\tpattern: input.pattern,\n\t\tsearchPath,\n\t\tglob: input.glob,\n\t\tignoreCase: input.ignoreCase,\n\t\tliteral: input.literal,\n\t\tcontext: input.context && input.context > 0 ? input.context : 0,\n\t\tlimit: Math.max(1, input.limit ?? DEFAULT_LIMIT),\n\t};\n\tconst formatState: GrepFormatState = {\n\t\toperations,\n\t\tsearchPath,\n\t\tisDirectory,\n\t\tcontext: executionInput.context,\n\t\tfileCache: new Map(),\n\t\tlinesTruncated: false,\n\t};\n\tif (operations.grep) return executeOperationsGrep(operations, executionInput, formatState);\n\tconst rgPath = await ensureTool(\"rg\", true);\n\tif (!rgPath) throw new Error(\"ripgrep (rg) is not available and could not be downloaded\");\n\treturn executeRipgrep(rgPath, executionInput, formatState, signal);\n}\n\nexport type GrepToolDefinition = ToolDefinition<typeof grepSchema, GrepToolDetails | undefined>;\n\nexport function createGrepToolDefinition(operations: ToolOperations, _options?: GrepToolOptions): GrepToolDefinition {\n\tconst ops = operations;\n\tconst cwd = operations.cwd;\n\treturn {\n\t\tname: \"grep\",\n\t\tlabel: \"grep\",\n\t\tdescription: `Search file contents for a pattern. Returns matching lines with file paths and line numbers. Respects .gitignore. Output is truncated to ${DEFAULT_LIMIT} matches or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Long lines are truncated to ${GREP_MAX_LINE_LENGTH} chars.`,\n\t\tpromptSnippet: \"Search file contents for patterns (respects .gitignore)\",\n\t\tparameters: grepSchema,\n\t\tasync execute(_toolCallId, input: GrepToolInput, signal?: AbortSignal) {\n\t\t\treturn executeGrep(ops, cwd, input, signal);\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatBackendIcon(ops.getBackendInfo?.(), theme) + formatGrepCall(args, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatGrepResult(result, options, theme, context.showImages));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createGrepTool(operations: ToolOperations, options?: GrepToolOptions): AgentTool<typeof grepSchema> {\n\treturn wrapToolDefinition(createGrepToolDefinition(operations, options));\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"ls.d.ts","sourceRoot":"","sources":["../../../src/core/tools/ls.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAmB,MAAM,4BAA4B,CAAC;AAG7E,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAG5C,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AACtF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAItD,OAAO,EAAiC,KAAK,gBAAgB,EAAgB,MAAM,eAAe,CAAC;AAEnG,QAAA,MAAM,QAAQ;;;EAGZ,CAAC;AAEH,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,OAAO,QAAQ,CAAC,CAAC;AAIlD,MAAM,WAAW,aAAa;IAC7B,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED,MAAM,WAAW,aAAa;CAAG;AAmJjC,MAAM,MAAM,gBAAgB,GAAG,cAAc,CAAC,OAAO,QAAQ,EAAE,aAAa,GAAG,SAAS,CAAC,CAAC;AAE1F,wBAAgB,sBAAsB,CAAC,UAAU,EAAE,cAAc,EAAE,QAAQ,CAAC,EAAE,aAAa,GAAG,gBAAgB,CAuB7G;AAED,wBAAgB,YAAY,CAAC,UAAU,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE,aAAa,GAAG,SAAS,CAAC,OAAO,QAAQ,CAAC,CAE5G","sourcesContent":["import type { AgentTool, AgentToolResult } from \"@greppleai/grip-agent-core\";\nimport { Text } from \"@greppleai/grip-tui\";\nimport nodePath from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport type { ToolOperations } from \"./operations.ts\";\nimport { resolveToCwd } from \"./path-utils.ts\";\nimport { formatBackendIcon, getTextOutput, invalidArgText, shortenPath, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, formatSize, type TruncationResult, truncateHead } from \"./truncate.ts\";\n\nconst lsSchema = Type.Object({\n\tpath: Type.Optional(Type.String({ description: \"Directory to list (default: current directory)\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of entries to return (default: 500)\" })),\n});\n\nexport type LsToolInput = Static<typeof lsSchema>;\n\nconst DEFAULT_LIMIT = 500;\n\nexport interface LsToolDetails {\n\ttruncation?: TruncationResult;\n\tentryLimitReached?: number;\n}\n\nexport interface LsToolOptions {}\n\nfunction formatLsCall(args: Partial<LsToolInput> | undefined, theme: Theme): string {\n\tconst rawPath = str(args?.path);\n\tconst path = rawPath !== null ? shortenPath(rawPath || \".\") : null;\n\tconst limit = args?.limit;\n\tconst invalidArg = invalidArgText(theme);\n\tlet text = `${theme.fg(\"toolTitle\", theme.bold(\"ls\"))} ${path === null ? invalidArg : theme.fg(\"accent\", path)}`;\n\tif (limit !== undefined) {\n\t\ttext += theme.fg(\"toolOutput\", ` (limit ${limit})`);\n\t}\n\treturn text;\n}\n\nfunction formatLsResult(\n\tresult: AgentToolResult<LsToolDetails | undefined>,\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n): string {\n\tconst output = getTextOutput(result, showImages).trim();\n\tlet text = \"\";\n\tif (output) {\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst maxLines = options.expanded ? lines.length : 20;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n${displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")})`;\n\t\t}\n\t}\n\n\tconst entryLimit = result.details?.entryLimitReached;\n\tconst truncation = result.details?.truncation;\n\tif (entryLimit || truncation?.truncated) {\n\t\tconst warnings: string[] = [];\n\t\tif (entryLimit) warnings.push(`${entryLimit} entries limit`);\n\t\tif (truncation?.truncated) warnings.push(`${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit`);\n\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${warnings.join(\", \")}]`)}`;\n\t}\n\treturn text;\n}\ninterface DirectoryListingEntries {\n\tentries: string[];\n\tentryLimitReached: boolean;\n}\n\nasync function readDirectoryNames(dirPath: string, operations: ToolOperations): Promise<string[]> {\n\ttry {\n\t\treturn await operations.readdir(dirPath);\n\t} catch (error) {\n\t\tconst message =\n\t\t\ttypeof error === \"object\" && error !== null && \"message\" in error ? String(error.message) : \"undefined\";\n\t\tthrow new Error(`Cannot read directory: ${message}`);\n\t}\n}\n\nasync function collectDirectoryListingEntries(\n\tdirPath: string,\n\tnames: string[],\n\tlimit: number,\n\toperations: ToolOperations,\n): Promise<DirectoryListingEntries> {\n\tnames.sort((left, right) => left.toLowerCase().localeCompare(right.toLowerCase()));\n\tconst entries: string[] = [];\n\tfor (const name of names) {\n\t\tif (entries.length >= limit) return { entries, entryLimitReached: true };\n\t\ttry {\n\t\t\tconst entryStat = await operations.stat(nodePath.join(dirPath, name));\n\t\t\tentries.push(entryStat.isDirectory() ? `${name}/` : name);\n\t\t} catch {\n\t\t\t// Skip entries we cannot stat.\n\t\t}\n\t}\n\treturn { entries, entryLimitReached: false };\n}\n\nfunction formatDirectoryListingResult(\n\tlisting: DirectoryListingEntries,\n\tlimit: number,\n): AgentToolResult<LsToolDetails | undefined> {\n\tif (listing.entries.length === 0) {\n\t\treturn { content: [{ type: \"text\", text: \"(empty directory)\" }], details: undefined };\n\t}\n\tconst truncation = truncateHead(listing.entries.join(\"\\n\"), { maxLines: Number.MAX_SAFE_INTEGER });\n\tlet output = truncation.content;\n\tconst details: LsToolDetails = {};\n\tconst notices: string[] = [];\n\tif (listing.entryLimitReached) {\n\t\tnotices.push(`${limit} entries limit reached. Use limit=${limit * 2} for more`);\n\t\tdetails.entryLimitReached = limit;\n\t}\n\tif (truncation.truncated) {\n\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\tdetails.truncation = truncation;\n\t}\n\tif (notices.length > 0) output += `\\n\\n[${notices.join(\". \")}]`;\n\treturn {\n\t\tcontent: [{ type: \"text\", text: output }],\n\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t};\n}\n\nasync function buildDirectoryListing(\n\tinput: LsToolInput,\n\toperations: ToolOperations,\n\tcwd: string,\n): Promise<AgentToolResult<LsToolDetails | undefined>> {\n\tconst dirPath = resolveToCwd(input.path || \".\", cwd);\n\tconst limit = input.limit ?? DEFAULT_LIMIT;\n\ttry {\n\t\tawait operations.access(dirPath, \"exists\");\n\t} catch {\n\t\tthrow new Error(`Path not found: ${dirPath}`);\n\t}\n\tif (!(await operations.stat(dirPath)).isDirectory()) throw new Error(`Not a directory: ${dirPath}`);\n\tconst names = await readDirectoryNames(dirPath, operations);\n\treturn formatDirectoryListingResult(await collectDirectoryListingEntries(dirPath, names, limit, operations), limit);\n}\n\nfunction executeAbortableDirectoryListing(\n\tinput: LsToolInput,\n\toperations: ToolOperations,\n\tcwd: string,\n\tsignal: AbortSignal | undefined,\n): Promise<AgentToolResult<LsToolDetails | undefined>> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\treturn;\n\t\t}\n\t\tconst onAbort = () => reject(new Error(\"Operation aborted\"));\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\tvoid buildDirectoryListing(input, operations, cwd).then(\n\t\t\t(result) => {\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\tresolve(result);\n\t\t\t},\n\t\t\t(error) => {\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\treject(error);\n\t\t\t},\n\t\t);\n\t});\n}\n\nexport type LsToolDefinition = ToolDefinition<typeof lsSchema, LsToolDetails | undefined>;\n\nexport function createLsToolDefinition(operations: ToolOperations, _options?: LsToolOptions): LsToolDefinition {\n\tconst ops = operations;\n\tconst cwd = operations.cwd;\n\treturn {\n\t\tname: \"ls\",\n\t\tlabel: \"ls\",\n\t\tdescription: `List directory contents. Returns entries sorted alphabetically, with '/' suffix for directories. Includes dotfiles. Output is truncated to ${DEFAULT_LIMIT} entries or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first).`,\n\t\tpromptSnippet: \"List directory contents\",\n\t\tparameters: lsSchema,\n\t\tasync execute(_toolCallId, input: LsToolInput, signal?: AbortSignal, _onUpdate?, _ctx?) {\n\t\t\treturn executeAbortableDirectoryListing(input, ops, cwd, signal);\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatBackendIcon(ops.getBackendInfo?.(), theme) + formatLsCall(args, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatLsResult(result, options, theme, context.showImages));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createLsTool(operations: ToolOperations, options?: LsToolOptions): AgentTool<typeof lsSchema> {\n\treturn wrapToolDefinition(createLsToolDefinition(operations, options));\n}\n"]}
1
+ {"version":3,"file":"ls.d.ts","sourceRoot":"","sources":["../../../src/core/tools/ls.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAmB,MAAM,4BAA4B,CAAC;AAG7E,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AACtF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAWtD,OAAO,EAAiC,KAAK,gBAAgB,EAAgB,MAAM,eAAe,CAAC;AAEnG,QAAA,MAAM,QAAQ;;;EAGZ,CAAC;AAEH,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,OAAO,QAAQ,CAAC,CAAC;AAIlD,MAAM,WAAW,aAAa;IAC7B,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED,MAAM,WAAW,aAAa;CAAG;AAmJjC,MAAM,MAAM,gBAAgB,GAAG,cAAc,CAAC,OAAO,QAAQ,EAAE,aAAa,GAAG,SAAS,CAAC,CAAC;AAE1F,wBAAgB,sBAAsB,CAAC,UAAU,EAAE,cAAc,EAAE,QAAQ,CAAC,EAAE,aAAa,GAAG,gBAAgB,CAuB7G;AAED,wBAAgB,YAAY,CAAC,UAAU,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE,aAAa,GAAG,SAAS,CAAC,OAAO,QAAQ,CAAC,CAE5G","sourcesContent":["import type { AgentTool, AgentToolResult } from \"@greppleai/grip-agent-core\";\nimport { Text } from \"@greppleai/grip-tui\";\nimport nodePath from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport type { ToolOperations } from \"./operations.ts\";\nimport { resolveToCwd } from \"./path-utils.ts\";\nimport {\n\tformatBackendIcon,\n\tformatHiddenLinesHint,\n\tgetTextOutput,\n\tinvalidArgText,\n\tshortenPath,\n\tstr,\n} from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, formatSize, type TruncationResult, truncateHead } from \"./truncate.ts\";\n\nconst lsSchema = Type.Object({\n\tpath: Type.Optional(Type.String({ description: \"Directory to list (default: current directory)\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of entries to return (default: 500)\" })),\n});\n\nexport type LsToolInput = Static<typeof lsSchema>;\n\nconst DEFAULT_LIMIT = 500;\n\nexport interface LsToolDetails {\n\ttruncation?: TruncationResult;\n\tentryLimitReached?: number;\n}\n\nexport interface LsToolOptions {}\n\nfunction formatLsCall(args: Partial<LsToolInput> | undefined, theme: Theme): string {\n\tconst rawPath = str(args?.path);\n\tconst path = rawPath !== null ? shortenPath(rawPath || \".\") : null;\n\tconst limit = args?.limit;\n\tconst invalidArg = invalidArgText(theme);\n\tlet text = `${theme.fg(\"toolTitle\", theme.bold(\"ls\"))} ${path === null ? invalidArg : theme.fg(\"accent\", path)}`;\n\tif (limit !== undefined) {\n\t\ttext += theme.fg(\"toolOutput\", ` (limit ${limit})`);\n\t}\n\treturn text;\n}\n\nfunction formatLsResult(\n\tresult: AgentToolResult<LsToolDetails | undefined>,\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n): string {\n\tconst output = getTextOutput(result, showImages).trim();\n\tlet text = \"\";\n\tif (output) {\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst maxLines = options.expanded ? lines.length : 20;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n${displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `\\n\\n${formatHiddenLinesHint(remaining, theme)}`;\n\t\t}\n\t}\n\n\tconst entryLimit = result.details?.entryLimitReached;\n\tconst truncation = result.details?.truncation;\n\tif (entryLimit || truncation?.truncated) {\n\t\tconst warnings: string[] = [];\n\t\tif (entryLimit) warnings.push(`${entryLimit} entries limit`);\n\t\tif (truncation?.truncated) warnings.push(`${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit`);\n\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${warnings.join(\", \")}]`)}`;\n\t}\n\treturn text;\n}\ninterface DirectoryListingEntries {\n\tentries: string[];\n\tentryLimitReached: boolean;\n}\n\nasync function readDirectoryNames(dirPath: string, operations: ToolOperations): Promise<string[]> {\n\ttry {\n\t\treturn await operations.readdir(dirPath);\n\t} catch (error) {\n\t\tconst message =\n\t\t\ttypeof error === \"object\" && error !== null && \"message\" in error ? String(error.message) : \"undefined\";\n\t\tthrow new Error(`Cannot read directory: ${message}`);\n\t}\n}\n\nasync function collectDirectoryListingEntries(\n\tdirPath: string,\n\tnames: string[],\n\tlimit: number,\n\toperations: ToolOperations,\n): Promise<DirectoryListingEntries> {\n\tnames.sort((left, right) => left.toLowerCase().localeCompare(right.toLowerCase()));\n\tconst entries: string[] = [];\n\tfor (const name of names) {\n\t\tif (entries.length >= limit) return { entries, entryLimitReached: true };\n\t\ttry {\n\t\t\tconst entryStat = await operations.stat(nodePath.join(dirPath, name));\n\t\t\tentries.push(entryStat.isDirectory() ? `${name}/` : name);\n\t\t} catch {\n\t\t\t// Skip entries we cannot stat.\n\t\t}\n\t}\n\treturn { entries, entryLimitReached: false };\n}\n\nfunction formatDirectoryListingResult(\n\tlisting: DirectoryListingEntries,\n\tlimit: number,\n): AgentToolResult<LsToolDetails | undefined> {\n\tif (listing.entries.length === 0) {\n\t\treturn { content: [{ type: \"text\", text: \"(empty directory)\" }], details: undefined };\n\t}\n\tconst truncation = truncateHead(listing.entries.join(\"\\n\"), { maxLines: Number.MAX_SAFE_INTEGER });\n\tlet output = truncation.content;\n\tconst details: LsToolDetails = {};\n\tconst notices: string[] = [];\n\tif (listing.entryLimitReached) {\n\t\tnotices.push(`${limit} entries limit reached. Use limit=${limit * 2} for more`);\n\t\tdetails.entryLimitReached = limit;\n\t}\n\tif (truncation.truncated) {\n\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\tdetails.truncation = truncation;\n\t}\n\tif (notices.length > 0) output += `\\n\\n[${notices.join(\". \")}]`;\n\treturn {\n\t\tcontent: [{ type: \"text\", text: output }],\n\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t};\n}\n\nasync function buildDirectoryListing(\n\tinput: LsToolInput,\n\toperations: ToolOperations,\n\tcwd: string,\n): Promise<AgentToolResult<LsToolDetails | undefined>> {\n\tconst dirPath = resolveToCwd(input.path || \".\", cwd);\n\tconst limit = input.limit ?? DEFAULT_LIMIT;\n\ttry {\n\t\tawait operations.access(dirPath, \"exists\");\n\t} catch {\n\t\tthrow new Error(`Path not found: ${dirPath}`);\n\t}\n\tif (!(await operations.stat(dirPath)).isDirectory()) throw new Error(`Not a directory: ${dirPath}`);\n\tconst names = await readDirectoryNames(dirPath, operations);\n\treturn formatDirectoryListingResult(await collectDirectoryListingEntries(dirPath, names, limit, operations), limit);\n}\n\nfunction executeAbortableDirectoryListing(\n\tinput: LsToolInput,\n\toperations: ToolOperations,\n\tcwd: string,\n\tsignal: AbortSignal | undefined,\n): Promise<AgentToolResult<LsToolDetails | undefined>> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\treturn;\n\t\t}\n\t\tconst onAbort = () => reject(new Error(\"Operation aborted\"));\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\tvoid buildDirectoryListing(input, operations, cwd).then(\n\t\t\t(result) => {\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\tresolve(result);\n\t\t\t},\n\t\t\t(error) => {\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\treject(error);\n\t\t\t},\n\t\t);\n\t});\n}\n\nexport type LsToolDefinition = ToolDefinition<typeof lsSchema, LsToolDetails | undefined>;\n\nexport function createLsToolDefinition(operations: ToolOperations, _options?: LsToolOptions): LsToolDefinition {\n\tconst ops = operations;\n\tconst cwd = operations.cwd;\n\treturn {\n\t\tname: \"ls\",\n\t\tlabel: \"ls\",\n\t\tdescription: `List directory contents. Returns entries sorted alphabetically, with '/' suffix for directories. Includes dotfiles. Output is truncated to ${DEFAULT_LIMIT} entries or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first).`,\n\t\tpromptSnippet: \"List directory contents\",\n\t\tparameters: lsSchema,\n\t\tasync execute(_toolCallId, input: LsToolInput, signal?: AbortSignal, _onUpdate?, _ctx?) {\n\t\t\treturn executeAbortableDirectoryListing(input, ops, cwd, signal);\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatBackendIcon(ops.getBackendInfo?.(), theme) + formatLsCall(args, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatLsResult(result, options, theme, context.showImages));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createLsTool(operations: ToolOperations, options?: LsToolOptions): AgentTool<typeof lsSchema> {\n\treturn wrapToolDefinition(createLsToolDefinition(operations, options));\n}\n"]}
@@ -1,9 +1,8 @@
1
1
  import { Text } from "@greppleai/grip-tui";
2
2
  import nodePath from "path";
3
3
  import { Type } from "typebox";
4
- import { keyHint } from "../../modes/interactive/components/keybinding-hints.js";
5
4
  import { resolveToCwd } from "./path-utils.js";
6
- import { formatBackendIcon, getTextOutput, invalidArgText, shortenPath, str } from "./render-utils.js";
5
+ import { formatBackendIcon, formatHiddenLinesHint, getTextOutput, invalidArgText, shortenPath, str, } from "./render-utils.js";
7
6
  import { wrapToolDefinition } from "./tool-definition-wrapper.js";
8
7
  import { DEFAULT_MAX_BYTES, formatSize, truncateHead } from "./truncate.js";
9
8
  const lsSchema = Type.Object({
@@ -32,7 +31,7 @@ function formatLsResult(result, options, theme, showImages) {
32
31
  const remaining = lines.length - maxLines;
33
32
  text += `\n${displayLines.map((line) => theme.fg("toolOutput", line)).join("\n")}`;
34
33
  if (remaining > 0) {
35
- text += `${theme.fg("muted", `\n... (${remaining} more lines,`)} ${keyHint("app.tools.expand", "to expand")})`;
34
+ text += `\n\n${formatHiddenLinesHint(remaining, theme)}`;
36
35
  }
37
36
  }
38
37
  const entryLimit = result.details?.entryLimitReached;
@@ -1 +1 @@
1
- {"version":3,"file":"ls.js","sourceRoot":"","sources":["../../../src/core/tools/ls.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAC;AAC3C,OAAO,QAAQ,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AAIjF,OAAO,EAAE,YAAY,E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Q;QACpB,KAAK,CAAC,OAAO,CAAC,WAAW,EAAE,KAAkB,EAAE,MAAoB,EAAE,SAAU,EAAE,IAAK,EAAE;YACvF,OAAO,gCAAgC,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,MAAM,CAAC,CAAC;QAAA,CACjE;QACD,UAAU,CAAC,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE;YAChC,MAAM,IAAI,GAAI,OAAO,CAAC,aAAkC,IAAI,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YAC/E,IAAI,CAAC,OAAO,CAAC,iBAAiB,CAAC,GAAG,CAAC,cAAc,EAAE,EAAE,EAAE,KAAK,CAAC,GAAG,YAAY,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC;YAC3F,OAAO,IAAI,CAAC;QAAA,CACZ;QACD,YAAY,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE;YAC7C,MAAM,IAAI,GAAI,OAAO,CAAC,aAAkC,IAAI,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YAC/E,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC;YACzE,OAAO,IAAI,CAAC;QAAA,CACZ;KACD,CAAC;AAAA,CACF;AAED,MAAM,UAAU,YAAY,CAAC,UAA0B,EAAE,OAAuB,EAA8B;IAC7G,OAAO,kBAAkB,CAAC,sBAAsB,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC,CAAC;AAAA,CACvE","sourcesContent":["import type { AgentTool, AgentToolResult } from \"@greppleai/grip-agent-core\";\nimport { Text } from \"@greppleai/grip-tui\";\nimport nodePath from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport type { ToolOperations } from \"./operations.ts\";\nimport { resolveToCwd } from \"./path-utils.ts\";\nimport { formatBackendIcon, getTextOutput, invalidArgText, shortenPath, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, formatSize, type TruncationResult, truncateHead } from \"./truncate.ts\";\n\nconst lsSchema = Type.Object({\n\tpath: Type.Optional(Type.String({ description: \"Directory to list (default: current directory)\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of entries to return (default: 500)\" })),\n});\n\nexport type LsToolInput = Static<typeof lsSchema>;\n\nconst DEFAULT_LIMIT = 500;\n\nexport interface LsToolDetails {\n\ttruncation?: TruncationResult;\n\tentryLimitReached?: number;\n}\n\nexport interface LsToolOptions {}\n\nfunction formatLsCall(args: Partial<LsToolInput> | undefined, theme: Theme): string {\n\tconst rawPath = str(args?.path);\n\tconst path = rawPath !== null ? shortenPath(rawPath || \".\") : null;\n\tconst limit = args?.limit;\n\tconst invalidArg = invalidArgText(theme);\n\tlet text = `${theme.fg(\"toolTitle\", theme.bold(\"ls\"))} ${path === null ? invalidArg : theme.fg(\"accent\", path)}`;\n\tif (limit !== undefined) {\n\t\ttext += theme.fg(\"toolOutput\", ` (limit ${limit})`);\n\t}\n\treturn text;\n}\n\nfunction formatLsResult(\n\tresult: AgentToolResult<LsToolDetails | undefined>,\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n): string {\n\tconst output = getTextOutput(result, showImages).trim();\n\tlet text = \"\";\n\tif (output) {\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst maxLines = options.expanded ? lines.length : 20;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n${displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")})`;\n\t\t}\n\t}\n\n\tconst entryLimit = result.details?.entryLimitReached;\n\tconst truncation = result.details?.truncation;\n\tif (entryLimit || truncation?.truncated) {\n\t\tconst warnings: string[] = [];\n\t\tif (entryLimit) warnings.push(`${entryLimit} entries limit`);\n\t\tif (truncation?.truncated) warnings.push(`${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit`);\n\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${warnings.join(\", \")}]`)}`;\n\t}\n\treturn text;\n}\ninterface DirectoryListingEntries {\n\tentries: string[];\n\tentryLimitReached: boolean;\n}\n\nasync function readDirectoryNames(dirPath: string, operations: ToolOperations): Promise<string[]> {\n\ttry {\n\t\treturn await operations.readdir(dirPath);\n\t} catch (error) {\n\t\tconst message =\n\t\t\ttypeof error === \"object\" && error !== null && \"message\" in error ? String(error.message) : \"undefined\";\n\t\tthrow new Error(`Cannot read directory: ${message}`);\n\t}\n}\n\nasync function collectDirectoryListingEntries(\n\tdirPath: string,\n\tnames: string[],\n\tlimit: number,\n\toperations: ToolOperations,\n): Promise<DirectoryListingEntries> {\n\tnames.sort((left, right) => left.toLowerCase().localeCompare(right.toLowerCase()));\n\tconst entries: string[] = [];\n\tfor (const name of names) {\n\t\tif (entries.length >= limit) return { entries, entryLimitReached: true };\n\t\ttry {\n\t\t\tconst entryStat = await operations.stat(nodePath.join(dirPath, name));\n\t\t\tentries.push(entryStat.isDirectory() ? `${name}/` : name);\n\t\t} catch {\n\t\t\t// Skip entries we cannot stat.\n\t\t}\n\t}\n\treturn { entries, entryLimitReached: false };\n}\n\nfunction formatDirectoryListingResult(\n\tlisting: DirectoryListingEntries,\n\tlimit: number,\n): AgentToolResult<LsToolDetails | undefined> {\n\tif (listing.entries.length === 0) {\n\t\treturn { content: [{ type: \"text\", text: \"(empty directory)\" }], details: undefined };\n\t}\n\tconst truncation = truncateHead(listing.entries.join(\"\\n\"), { maxLines: Number.MAX_SAFE_INTEGER });\n\tlet output = truncation.content;\n\tconst details: LsToolDetails = {};\n\tconst notices: string[] = [];\n\tif (listing.entryLimitReached) {\n\t\tnotices.push(`${limit} entries limit reached. Use limit=${limit * 2} for more`);\n\t\tdetails.entryLimitReached = limit;\n\t}\n\tif (truncation.truncated) {\n\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\tdetails.truncation = truncation;\n\t}\n\tif (notices.length > 0) output += `\\n\\n[${notices.join(\". \")}]`;\n\treturn {\n\t\tcontent: [{ type: \"text\", text: output }],\n\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t};\n}\n\nasync function buildDirectoryListing(\n\tinput: LsToolInput,\n\toperations: ToolOperations,\n\tcwd: string,\n): Promise<AgentToolResult<LsToolDetails | undefined>> {\n\tconst dirPath = resolveToCwd(input.path || \".\", cwd);\n\tconst limit = input.limit ?? DEFAULT_LIMIT;\n\ttry {\n\t\tawait operations.access(dirPath, \"exists\");\n\t} catch {\n\t\tthrow new Error(`Path not found: ${dirPath}`);\n\t}\n\tif (!(await operations.stat(dirPath)).isDirectory()) throw new Error(`Not a directory: ${dirPath}`);\n\tconst names = await readDirectoryNames(dirPath, operations);\n\treturn formatDirectoryListingResult(await collectDirectoryListingEntries(dirPath, names, limit, operations), limit);\n}\n\nfunction executeAbortableDirectoryListing(\n\tinput: LsToolInput,\n\toperations: ToolOperations,\n\tcwd: string,\n\tsignal: AbortSignal | undefined,\n): Promise<AgentToolResult<LsToolDetails | undefined>> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\treturn;\n\t\t}\n\t\tconst onAbort = () => reject(new Error(\"Operation aborted\"));\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\tvoid buildDirectoryListing(input, operations, cwd).then(\n\t\t\t(result) => {\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\tresolve(result);\n\t\t\t},\n\t\t\t(error) => {\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\treject(error);\n\t\t\t},\n\t\t);\n\t});\n}\n\nexport type LsToolDefinition = ToolDefinition<typeof lsSchema, LsToolDetails | undefined>;\n\nexport function createLsToolDefinition(operations: ToolOperations, _options?: LsToolOptions): LsToolDefinition {\n\tconst ops = operations;\n\tconst cwd = operations.cwd;\n\treturn {\n\t\tname: \"ls\",\n\t\tlabel: \"ls\",\n\t\tdescription: `List directory contents. Returns entries sorted alphabetically, with '/' suffix for directories. Includes dotfiles. Output is truncated to ${DEFAULT_LIMIT} entries or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first).`,\n\t\tpromptSnippet: \"List directory contents\",\n\t\tparameters: lsSchema,\n\t\tasync execute(_toolCallId, input: LsToolInput, signal?: AbortSignal, _onUpdate?, _ctx?) {\n\t\t\treturn executeAbortableDirectoryListing(input, ops, cwd, signal);\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatBackendIcon(ops.getBackendInfo?.(), theme) + formatLsCall(args, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatLsResult(result, options, theme, context.showImages));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createLsTool(operations: ToolOperations, options?: LsToolOptions): AgentTool<typeof lsSchema> {\n\treturn wrapToolDefinition(createLsToolDefinition(operations, options));\n}\n"]}
1
+ {"version":3,"file":"ls.js","sourceRoot":"","sources":["../../../src/core/tools/ls.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAC;AAC3C,OAAO,QAAQ,MAAM,MAAM,CAAC;AAC5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UAAU,EAAE,QAAQ;QACpB,KAAK,CAAC,OAAO,CAAC,WAAW,EAAE,KAAkB,EAAE,MAAoB,EAAE,SAAU,EAAE,IAAK,EAAE;YACvF,OAAO,gCAAgC,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,MAAM,CAAC,CAAC;QAAA,CACjE;QACD,UAAU,CAAC,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE;YAChC,MAAM,IAAI,GAAI,OAAO,CAAC,aAAkC,IAAI,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YAC/E,IAAI,CAAC,OAAO,CAAC,iBAAiB,CAAC,GAAG,CAAC,cAAc,EAAE,EAAE,EAAE,KAAK,CAAC,GAAG,YAAY,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC;YAC3F,OAAO,IAAI,CAAC;QAAA,CACZ;QACD,YAAY,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE;YAC7C,MAAM,IAAI,GAAI,OAAO,CAAC,aAAkC,IAAI,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YAC/E,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC;YACzE,OAAO,IAAI,CAAC;QAAA,CACZ;KACD,CAAC;AAAA,CACF;AAED,MAAM,UAAU,YAAY,CAAC,UAA0B,EAAE,OAAuB,EAA8B;IAC7G,OAAO,kBAAkB,CAAC,sBAAsB,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC,CAAC;AAAA,CACvE","sourcesContent":["import type { AgentTool, AgentToolResult } from \"@greppleai/grip-agent-core\";\nimport { Text } from \"@greppleai/grip-tui\";\nimport nodePath from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport type { ToolOperations } from \"./operations.ts\";\nimport { resolveToCwd } from \"./path-utils.ts\";\nimport {\n\tformatBackendIcon,\n\tformatHiddenLinesHint,\n\tgetTextOutput,\n\tinvalidArgText,\n\tshortenPath,\n\tstr,\n} from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, formatSize, type TruncationResult, truncateHead } from \"./truncate.ts\";\n\nconst lsSchema = Type.Object({\n\tpath: Type.Optional(Type.String({ description: \"Directory to list (default: current directory)\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of entries to return (default: 500)\" })),\n});\n\nexport type LsToolInput = Static<typeof lsSchema>;\n\nconst DEFAULT_LIMIT = 500;\n\nexport interface LsToolDetails {\n\ttruncation?: TruncationResult;\n\tentryLimitReached?: number;\n}\n\nexport interface LsToolOptions {}\n\nfunction formatLsCall(args: Partial<LsToolInput> | undefined, theme: Theme): string {\n\tconst rawPath = str(args?.path);\n\tconst path = rawPath !== null ? shortenPath(rawPath || \".\") : null;\n\tconst limit = args?.limit;\n\tconst invalidArg = invalidArgText(theme);\n\tlet text = `${theme.fg(\"toolTitle\", theme.bold(\"ls\"))} ${path === null ? invalidArg : theme.fg(\"accent\", path)}`;\n\tif (limit !== undefined) {\n\t\ttext += theme.fg(\"toolOutput\", ` (limit ${limit})`);\n\t}\n\treturn text;\n}\n\nfunction formatLsResult(\n\tresult: AgentToolResult<LsToolDetails | undefined>,\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n): string {\n\tconst output = getTextOutput(result, showImages).trim();\n\tlet text = \"\";\n\tif (output) {\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst maxLines = options.expanded ? lines.length : 20;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n${displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `\\n\\n${formatHiddenLinesHint(remaining, theme)}`;\n\t\t}\n\t}\n\n\tconst entryLimit = result.details?.entryLimitReached;\n\tconst truncation = result.details?.truncation;\n\tif (entryLimit || truncation?.truncated) {\n\t\tconst warnings: string[] = [];\n\t\tif (entryLimit) warnings.push(`${entryLimit} entries limit`);\n\t\tif (truncation?.truncated) warnings.push(`${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit`);\n\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${warnings.join(\", \")}]`)}`;\n\t}\n\treturn text;\n}\ninterface DirectoryListingEntries {\n\tentries: string[];\n\tentryLimitReached: boolean;\n}\n\nasync function readDirectoryNames(dirPath: string, operations: ToolOperations): Promise<string[]> {\n\ttry {\n\t\treturn await operations.readdir(dirPath);\n\t} catch (error) {\n\t\tconst message =\n\t\t\ttypeof error === \"object\" && error !== null && \"message\" in error ? String(error.message) : \"undefined\";\n\t\tthrow new Error(`Cannot read directory: ${message}`);\n\t}\n}\n\nasync function collectDirectoryListingEntries(\n\tdirPath: string,\n\tnames: string[],\n\tlimit: number,\n\toperations: ToolOperations,\n): Promise<DirectoryListingEntries> {\n\tnames.sort((left, right) => left.toLowerCase().localeCompare(right.toLowerCase()));\n\tconst entries: string[] = [];\n\tfor (const name of names) {\n\t\tif (entries.length >= limit) return { entries, entryLimitReached: true };\n\t\ttry {\n\t\t\tconst entryStat = await operations.stat(nodePath.join(dirPath, name));\n\t\t\tentries.push(entryStat.isDirectory() ? `${name}/` : name);\n\t\t} catch {\n\t\t\t// Skip entries we cannot stat.\n\t\t}\n\t}\n\treturn { entries, entryLimitReached: false };\n}\n\nfunction formatDirectoryListingResult(\n\tlisting: DirectoryListingEntries,\n\tlimit: number,\n): AgentToolResult<LsToolDetails | undefined> {\n\tif (listing.entries.length === 0) {\n\t\treturn { content: [{ type: \"text\", text: \"(empty directory)\" }], details: undefined };\n\t}\n\tconst truncation = truncateHead(listing.entries.join(\"\\n\"), { maxLines: Number.MAX_SAFE_INTEGER });\n\tlet output = truncation.content;\n\tconst details: LsToolDetails = {};\n\tconst notices: string[] = [];\n\tif (listing.entryLimitReached) {\n\t\tnotices.push(`${limit} entries limit reached. Use limit=${limit * 2} for more`);\n\t\tdetails.entryLimitReached = limit;\n\t}\n\tif (truncation.truncated) {\n\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\tdetails.truncation = truncation;\n\t}\n\tif (notices.length > 0) output += `\\n\\n[${notices.join(\". \")}]`;\n\treturn {\n\t\tcontent: [{ type: \"text\", text: output }],\n\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t};\n}\n\nasync function buildDirectoryListing(\n\tinput: LsToolInput,\n\toperations: ToolOperations,\n\tcwd: string,\n): Promise<AgentToolResult<LsToolDetails | undefined>> {\n\tconst dirPath = resolveToCwd(input.path || \".\", cwd);\n\tconst limit = input.limit ?? DEFAULT_LIMIT;\n\ttry {\n\t\tawait operations.access(dirPath, \"exists\");\n\t} catch {\n\t\tthrow new Error(`Path not found: ${dirPath}`);\n\t}\n\tif (!(await operations.stat(dirPath)).isDirectory()) throw new Error(`Not a directory: ${dirPath}`);\n\tconst names = await readDirectoryNames(dirPath, operations);\n\treturn formatDirectoryListingResult(await collectDirectoryListingEntries(dirPath, names, limit, operations), limit);\n}\n\nfunction executeAbortableDirectoryListing(\n\tinput: LsToolInput,\n\toperations: ToolOperations,\n\tcwd: string,\n\tsignal: AbortSignal | undefined,\n): Promise<AgentToolResult<LsToolDetails | undefined>> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\treturn;\n\t\t}\n\t\tconst onAbort = () => reject(new Error(\"Operation aborted\"));\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\tvoid buildDirectoryListing(input, operations, cwd).then(\n\t\t\t(result) => {\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\tresolve(result);\n\t\t\t},\n\t\t\t(error) => {\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\treject(error);\n\t\t\t},\n\t\t);\n\t});\n}\n\nexport type LsToolDefinition = ToolDefinition<typeof lsSchema, LsToolDetails | undefined>;\n\nexport function createLsToolDefinition(operations: ToolOperations, _options?: LsToolOptions): LsToolDefinition {\n\tconst ops = operations;\n\tconst cwd = operations.cwd;\n\treturn {\n\t\tname: \"ls\",\n\t\tlabel: \"ls\",\n\t\tdescription: `List directory contents. Returns entries sorted alphabetically, with '/' suffix for directories. Includes dotfiles. Output is truncated to ${DEFAULT_LIMIT} entries or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first).`,\n\t\tpromptSnippet: \"List directory contents\",\n\t\tparameters: lsSchema,\n\t\tasync execute(_toolCallId, input: LsToolInput, signal?: AbortSignal, _onUpdate?, _ctx?) {\n\t\t\treturn executeAbortableDirectoryListing(input, ops, cwd, signal);\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatBackendIcon(ops.getBackendInfo?.(), theme) + formatLsCall(args, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatLsResult(result, options, theme, context.showImages));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createLsTool(operations: ToolOperations, options?: LsToolOptions): AgentTool<typeof lsSchema> {\n\treturn wrapToolDefinition(createLsToolDefinition(operations, options));\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../../../src/core/tools/read.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAmB,MAAM,4BAA4B,CAAC;AAI7E,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAM5C,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AAItF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAItD,OAAO,EAAoD,KAAK,gBAAgB,EAAgB,MAAM,eAAe,CAAC;AAEtH,QAAA,MAAM,UAAU;;;;EAId,CAAC;AAEH,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAEtD,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,gBAAgB,CAAC;CAC9B;AAWD,MAAM,WAAW,2BAA2B;IAC3C,IAAI,EAAE,WAAW,CAAC;IAClB,UAAU,EAAE,cAAc,CAAC;IAC3B,IAAI,EAAE,MAAM,CAAC;CACb;AAED,MAAM,MAAM,kBAAkB,GAAG,cAAc,GAAG,2BAA2B,CAAC;AAE9E,KAAK,0BAA0B,GAAG,CAAC,YAAY,EAAE,MAAM,KAAK,kBAAkB,GAAG,SAAS,CAAC;AAE3F,MAAM,WAAW,eAAe;IAC/B,oEAAoE;IACpE,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,qHAAqH;IACrH,iBAAiB,CAAC,EAAE,0BAA0B,CAAC;CAC/C;AAoUD,MAAM,MAAM,kBAAkB,GAAG,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,CAAC,CAAC;AAEhG,wBAAgB,wBAAwB,CAAC,UAAU,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,kBAAkB,CAgDlH;AAED,wBAAgB,cAAc,CAAC,UAAU,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAElH","sourcesContent":["import { basename, dirname, isAbsolute, relative, resolve as resolvePath, sep } from \"node:path\";\nimport type { AgentTool, AgentToolResult } from \"@greppleai/grip-agent-core\";\nimport type { Api, Model } from \"@greppleai/grip-ai\";\nimport { Text } from \"@greppleai/grip-tui\";\n\nimport { type Static, Type } from \"typebox\";\nimport { getReadmePath } from \"../../config.ts\";\nimport { keyHint, keyText } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { getLanguageFromPath, highlightCode, type Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { processImage } from \"../../utils/image-process.ts\";\nimport { formatPathRelativeToCwdOrAbsolute } from \"../../utils/paths.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { fmtRegion } from \"./hashline/apply.ts\";\nimport { HASH_SEP, initHasher, lineHashes } from \"./hashline/hash.ts\";\nimport { visLines as hashlineVisLines } from \"./hashline-utils.ts\";\nimport type { ToolOperations } from \"./operations.ts\";\nimport { resolveReadPathAsync, resolveToCwd } from \"./path-utils.ts\";\nimport { formatBackendIcon, getTextOutput, invalidArgText, replaceTabs, shortenPath, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult, truncateHead } from \"./truncate.ts\";\n\nconst readSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to read (relative or absolute)\" }),\n\toffset: Type.Optional(Type.Number({ description: \"Line number to start reading from (1-indexed)\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of lines to read\" })),\n});\n\nexport type ReadToolInput = Static<typeof readSchema>;\n\nexport interface ReadToolDetails {\n\ttruncation?: TruncationResult;\n}\n\ntype CompactReadClassificationKind = \"docs\" | \"resource\" | \"skill\" | \"rule\";\n\ninterface CompactReadClassification {\n\tkind: CompactReadClassificationKind;\n\tlabel: string;\n}\n\nconst COMPACT_RESOURCE_FILE_NAMES = new Set([\"AGENTS.override.md\", \"AGENTS.md\", \"AGENTS.MD\", \"CLAUDE.md\", \"CLAUDE.MD\"]);\n\nexport interface ReadToolOperationsSelection {\n\tkind: \"selection\";\n\toperations: ToolOperations;\n\tpath: string;\n}\n\nexport type ReadToolOperations = ToolOperations | ReadToolOperationsSelection;\n\ntype ReadToolOperationsSelector = (absolutePath: string) => ReadToolOperations | undefined;\n\nexport interface ReadToolOptions {\n\t/** Whether to auto-resize images to 2000x2000 max. Default: true */\n\tautoResizeImages?: boolean;\n\t/** Select a backend, and optionally a canonical path, for a resolved absolute path. Defaults to the tool backend. */\n\toperationsForPath?: ReadToolOperationsSelector;\n}\n\nfunction isReadToolOperationsSelection(value: ReadToolOperations): value is ReadToolOperationsSelection {\n\treturn \"kind\" in value && value.kind === \"selection\";\n}\n\nfunction getReadToolOperations(value: ReadToolOperations | undefined): ToolOperations | undefined {\n\treturn value && isReadToolOperationsSelection(value) ? value.operations : value;\n}\n\ntype ReadRenderArgs = { path?: string; file_path?: string; offset?: number; limit?: number };\n\nfunction formatReadLineRange(args: ReadRenderArgs | undefined, theme: Theme): string {\n\tif (args?.offset === undefined && args?.limit === undefined) return \"\";\n\tconst startLine = args.offset ?? 1;\n\tconst endLine = args.limit !== undefined ? startLine + args.limit - 1 : \"\";\n\treturn theme.fg(\"warning\", `:${startLine}${endLine ? `-${endLine}` : \"\"}`);\n}\n\nfunction formatReadCall(args: ReadRenderArgs | undefined, theme: Theme): string {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst path = rawPath !== null ? shortenPath(rawPath) : null;\n\tconst invalidArg = invalidArgText(theme);\n\tconst pathDisplay = path === null ? invalidArg : path ? theme.fg(\"accent\", path) : theme.fg(\"toolOutput\", \"...\");\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"read\"))} ${pathDisplay}${formatReadLineRange(args, theme)}`;\n}\n\nfunction trimTrailingEmptyLines(lines: string[]): string[] {\n\tlet end = lines.length;\n\twhile (end > 0 && lines[end - 1] === \"\") {\n\t\tend--;\n\t}\n\treturn lines.slice(0, end);\n}\n\nfunction getNonVisionImageNote(model: Model<Api> | undefined): string | undefined {\n\tif (!model || model.input.includes(\"image\")) {\n\t\treturn undefined;\n\t}\n\treturn \"[Current model does not support images. The image will be omitted from this request.]\";\n}\n\nfunction toPosixPath(filePath: string): string {\n\treturn filePath.split(sep).join(\"/\");\n}\n\nfunction getGripDocsClassification(absolutePath: string): CompactReadClassification | undefined {\n\tconst packageRoot = dirname(getReadmePath());\n\tconst relativePath = relative(resolvePath(packageRoot), resolvePath(absolutePath));\n\tif (\n\t\trelativePath === \"\" ||\n\t\trelativePath === \"..\" ||\n\t\trelativePath.startsWith(`..${sep}`) ||\n\t\tisAbsolute(relativePath)\n\t) {\n\t\treturn undefined;\n\t}\n\n\tconst label = toPosixPath(relativePath);\n\tif (label === \"README.md\" || label.startsWith(\"docs/\") || label.startsWith(\"examples/\")) {\n\t\treturn { kind: \"docs\", label };\n\t}\n\treturn undefined;\n}\n\nfunction getCompactReadClassification(\n\targs: ReadRenderArgs | undefined,\n\tcwd: string,\n): CompactReadClassification | undefined {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tif (!rawPath) return undefined;\n\n\tconst absolutePath = resolveToCwd(rawPath, cwd);\n\tconst fileName = basename(absolutePath);\n\tif (fileName === \"SKILL.md\") {\n\t\treturn { kind: \"skill\", label: basename(dirname(absolutePath)) || fileName };\n\t}\n\tif (fileName === \"RULES.md\") {\n\t\treturn { kind: \"rule\", label: basename(dirname(absolutePath)) || fileName };\n\t}\n\n\tconst docsClassification = getGripDocsClassification(absolutePath);\n\tif (docsClassification) return docsClassification;\n\n\tif (COMPACT_RESOURCE_FILE_NAMES.has(fileName)) {\n\t\treturn { kind: \"resource\", label: formatPathRelativeToCwdOrAbsolute(absolutePath, cwd) };\n\t}\n\n\treturn undefined;\n}\n\nfunction formatCompactReadCall(\n\tclassification: CompactReadClassification,\n\targs: ReadRenderArgs | undefined,\n\ttheme: Theme,\n): string {\n\tconst expandHint = theme.fg(\"dim\", ` (${keyText(\"app.tools.expand\")} to expand)`);\n\tif (classification.kind === \"skill\" || classification.kind === \"rule\") {\n\t\tconst label = classification.kind === \"skill\" ? \"skill\" : \"rule\";\n\t\treturn (\n\t\t\ttheme.fg(\"customMessageLabel\", `\\x1b[1m[${label}]\\x1b[22m `) +\n\t\t\ttheme.fg(\"customMessageText\", classification.label) +\n\t\t\tformatReadLineRange(args, theme) +\n\t\t\texpandHint\n\t\t);\n\t}\n\n\treturn (\n\t\ttheme.fg(\"toolTitle\", theme.bold(`read ${classification.kind}`)) +\n\t\t\" \" +\n\t\ttheme.fg(\"accent\", classification.label) +\n\t\tformatReadLineRange(args, theme) +\n\t\texpandHint\n\t);\n}\n\nfunction formatReadTruncationWarning(truncation: TruncationResult | undefined, theme: Theme): string {\n\tif (!truncation?.truncated) return \"\";\n\tif (truncation.firstLineExceedsLimit) {\n\t\treturn `\\n${theme.fg(\"warning\", `[First line exceeds ${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit]`)}`;\n\t}\n\tif (truncation.truncatedBy === \"lines\") {\n\t\treturn `\\n${theme.fg(\"warning\", `[Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines (${truncation.maxLines ?? DEFAULT_MAX_LINES} line limit)]`)}`;\n\t}\n\treturn `\\n${theme.fg(\"warning\", `[Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)]`)}`;\n}\n\nfunction formatReadResult(\n\targs: ReadRenderArgs | undefined,\n\tresult: AgentToolResult<ReadToolDetails | undefined>,\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n\tcwd: string,\n\tisError: boolean,\n): string {\n\tif (!options.expanded && !isError && getCompactReadClassification(args, cwd)) {\n\t\treturn \"\";\n\t}\n\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst output = getTextOutput(result, showImages);\n\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tconst renderedLines = lang ? highlightCode(replaceTabs(output), lang) : output.split(\"\\n\");\n\tconst lines = trimTrailingEmptyLines(renderedLines);\n\tconst maxLines = options.expanded ? lines.length : 10;\n\tconst displayLines = lines.slice(0, maxLines);\n\tconst remaining = lines.length - maxLines;\n\tlet text = `\\n${displayLines.map((line) => (lang ? replaceTabs(line) : theme.fg(\"toolOutput\", replaceTabs(line)))).join(\"\\n\")}`;\n\tif (remaining > 0) {\n\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")})`;\n\t}\n\n\ttext += formatReadTruncationWarning(result.details?.truncation, theme);\n\treturn text;\n}\n\ninterface ResolvedReadTarget {\n\toperations: ToolOperations;\n\tpath: string;\n}\n\ninterface ReadExecutionOptions {\n\tinput: ReadToolInput;\n\tdefaultOperations: ToolOperations;\n\tcwd: string;\n\toperationsForPath: ReadToolOperationsSelector | undefined;\n\tautoResizeImages: boolean;\n\tmodel: Model<Api> | undefined;\n\tsignal: AbortSignal | undefined;\n}\n\ninterface TextReadOutputOptions {\n\ttruncation: TruncationResult;\n\tallLines: string[];\n\tstartLine: number;\n\tstartLineDisplay: number;\n\tendLine: number;\n\ttotalFileLines: number;\n}\n\nasync function resolveReadTarget(options: ReadExecutionOptions): Promise<ResolvedReadTarget> {\n\tconst absolutePath = await resolveReadPathAsync(options.input.path, options.cwd);\n\tconst selection = options.operationsForPath?.(absolutePath);\n\treturn {\n\t\toperations: getReadToolOperations(selection) ?? options.defaultOperations,\n\t\tpath: selection && isReadToolOperationsSelection(selection) ? selection.path : absolutePath,\n\t};\n}\n\nasync function readImageFile(\n\toperations: ToolOperations,\n\tpath: string,\n\tmimeType: string,\n\tautoResizeImages: boolean,\n\tnonVisionImageNote: string | undefined,\n): Promise<AgentToolResult<ReadToolDetails | undefined>> {\n\tconst buffer = await operations.readFile(path);\n\tconst processed = await processImage(buffer, mimeType, { autoResizeImages });\n\tif (!processed.ok) {\n\t\tlet text = `Read image file [${mimeType}]\\n${processed.message}`;\n\t\tif (nonVisionImageNote) text += `\\n${nonVisionImageNote}`;\n\t\treturn { content: [{ type: \"text\", text }], details: undefined };\n\t}\n\tlet text = `Read image file [${processed.mimeType}]`;\n\tif (processed.hints.length > 0) text += `\\n${processed.hints.join(\"\\n\")}`;\n\tif (nonVisionImageNote) text += `\\n${nonVisionImageNote}`;\n\treturn {\n\t\tcontent: [\n\t\t\t{ type: \"text\", text },\n\t\t\t{ type: \"image\", data: processed.data, mimeType: processed.mimeType },\n\t\t],\n\t\tdetails: undefined,\n\t};\n}\n\nfunction formatTextReadOutput(options: TextReadOutputOptions): AgentToolResult<ReadToolDetails | undefined> {\n\tconst { truncation } = options;\n\tlet text: string;\n\tlet details: ReadToolDetails | undefined;\n\tif (truncation.firstLineExceedsLimit) {\n\t\tconst firstLineSize = formatSize(Buffer.byteLength(options.allLines[options.startLine] ?? \"\", \"utf-8\"));\n\t\ttext = `[Line ${options.startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Hashline output requires full lines; use bash for this line.]`;\n\t\tdetails = { truncation };\n\t} else if (truncation.truncated) {\n\t\tconst endLineDisplay = options.startLineDisplay + truncation.outputLines - 1;\n\t\tconst nextOffset = endLineDisplay + 1;\n\t\ttext = truncation.content;\n\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\ttext += `\\n\\n[Showing lines ${options.startLineDisplay}-${endLineDisplay} of ${options.totalFileLines}. Use offset=${nextOffset} to continue.]`;\n\t\t} else {\n\t\t\ttext += `\\n\\n[Showing lines ${options.startLineDisplay}-${endLineDisplay} of ${options.totalFileLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Use offset=${nextOffset} to continue.]`;\n\t\t}\n\t\tdetails = { truncation };\n\t} else if (options.endLine < options.totalFileLines) {\n\t\tconst remaining = options.totalFileLines - options.endLine;\n\t\ttext = `${truncation.content}\\n\\n[${remaining} more lines in file. Use offset=${options.endLine + 1} to continue.]`;\n\t} else {\n\t\ttext = truncation.content;\n\t}\n\treturn { content: [{ type: \"text\", text }], details };\n}\n\nasync function readTextFile(\n\toperations: ToolOperations,\n\tpath: string,\n\toffset: number | undefined,\n\tlimit: number | undefined,\n): Promise<AgentToolResult<ReadToolDetails | undefined>> {\n\tawait initHasher();\n\tconst buffer = await operations.readFile(path);\n\tconst textContent = buffer.toString(\"utf-8\").replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\");\n\tconst allLines = hashlineVisLines(textContent);\n\tconst totalFileLines = allLines.length;\n\tconst startLine = offset ? Math.max(0, offset - 1) : 0;\n\tconst startLineDisplay = startLine + 1;\n\tif (totalFileLines === 0) {\n\t\tif (startLineDisplay !== 1) throw new Error(`Offset ${offset} is beyond end of file (0 lines total)`);\n\t\tconst emptyHash = (await lineHashes(textContent, path))[0] ?? \"\";\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `${emptyHash}${HASH_SEP}\\n[File is empty. Use edit to insert content.]` }],\n\t\t\tdetails: undefined,\n\t\t};\n\t}\n\tif (startLine >= totalFileLines) {\n\t\tthrow new Error(`Offset ${offset} is beyond end of file (${totalFileLines} lines total)`);\n\t}\n\tconst endLine = limit !== undefined ? Math.min(startLine + limit, totalFileLines) : totalFileLines;\n\tconst allHashes = await lineHashes(textContent, path);\n\tconst selectedContent = fmtRegion(allHashes.slice(startLine, endLine), allLines.slice(startLine, endLine));\n\treturn formatTextReadOutput({\n\t\ttruncation: truncateHead(selectedContent),\n\t\tallLines,\n\t\tstartLine,\n\t\tstartLineDisplay,\n\t\tendLine,\n\t\ttotalFileLines,\n\t});\n}\n\nasync function executeReadRequest(\n\toptions: ReadExecutionOptions,\n\tisAborted: () => boolean,\n): Promise<AgentToolResult<ReadToolDetails | undefined> | undefined> {\n\tconst target = await resolveReadTarget(options);\n\tif (isAborted()) return undefined;\n\tawait target.operations.access(target.path, \"read\");\n\tif (isAborted()) return undefined;\n\tconst mimeType = target.operations.detectImageMimeType\n\t\t? await target.operations.detectImageMimeType(target.path)\n\t\t: undefined;\n\tconst nonVisionImageNote = getNonVisionImageNote(options.model);\n\tconst result = mimeType\n\t\t? await readImageFile(target.operations, target.path, mimeType, options.autoResizeImages, nonVisionImageNote)\n\t\t: await readTextFile(target.operations, target.path, options.input.offset, options.input.limit);\n\treturn isAborted() ? undefined : result;\n}\n\nfunction executeAbortableRead(options: ReadExecutionOptions): Promise<AgentToolResult<ReadToolDetails | undefined>> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (options.signal?.aborted) {\n\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\treturn;\n\t\t}\n\t\tlet aborted = false;\n\t\tconst onAbort = () => {\n\t\t\taborted = true;\n\t\t\treject(new Error(\"Operation aborted\"));\n\t\t};\n\t\toptions.signal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\tvoid executeReadRequest(options, () => aborted).then(\n\t\t\t(result) => {\n\t\t\t\tif (result === undefined) return;\n\t\t\t\toptions.signal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\tresolve(result);\n\t\t\t},\n\t\t\t(error) => {\n\t\t\t\toptions.signal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\tif (!aborted) reject(error);\n\t\t\t},\n\t\t);\n\t});\n}\n\nexport type ReadToolDefinition = ToolDefinition<typeof readSchema, ReadToolDetails | undefined>;\n\nexport function createReadToolDefinition(operations: ToolOperations, options?: ReadToolOptions): ReadToolDefinition {\n\tconst autoResizeImages = options?.autoResizeImages ?? true;\n\tconst ops = operations;\n\tconst cwd = operations.cwd;\n\tconst operationsForPath = options?.operationsForPath;\n\treturn {\n\t\tname: \"read\",\n\t\tlabel: \"read\",\n\t\tdescription: `Read the contents of a file. Supports text files and images (jpg, png, gif, webp). Images are sent as attachments. Text files are returned as HASH│content rows for hash-anchored editing. Output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`,\n\t\tpromptSnippet: \"Read file contents with hashline anchors\",\n\t\tpromptGuidelines: [\n\t\t\t\"Use read to examine files instead of cat or sed.\",\n\t\t\t\"For edits, copy only the 3-character HASH values into edit hash_range_inclusive; do not include HASH│ prefixes in content_lines.\",\n\t\t],\n\t\tparameters: readSchema,\n\t\tasync execute(_toolCallId, input: ReadToolInput, signal?: AbortSignal, _onUpdate?, ctx?) {\n\t\t\treturn executeAbortableRead({\n\t\t\t\tinput,\n\t\t\t\tdefaultOperations: ops,\n\t\t\t\tcwd,\n\t\t\t\toperationsForPath,\n\t\t\t\tautoResizeImages,\n\t\t\t\tmodel: ctx?.model,\n\t\t\t\tsignal,\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tconst classification = !context.expanded ? getCompactReadClassification(args, context.cwd) : undefined;\n\t\t\tconst renderArgs = args as ReadRenderArgs | undefined;\n\t\t\tconst rawPath = str(renderArgs?.file_path ?? renderArgs?.path);\n\t\t\tconst displayOps = rawPath\n\t\t\t\t? (getReadToolOperations(operationsForPath?.(resolveToCwd(rawPath, cwd))) ?? ops)\n\t\t\t\t: ops;\n\t\t\ttext.setText(\n\t\t\t\tformatBackendIcon(displayOps.getBackendInfo?.(), theme) +\n\t\t\t\t\t(classification ? formatCompactReadCall(classification, args, theme) : formatReadCall(args, theme)),\n\t\t\t);\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(\n\t\t\t\tformatReadResult(context.args, result, options, theme, context.showImages, context.cwd, context.isError),\n\t\t\t);\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createReadTool(operations: ToolOperations, options?: ReadToolOptions): AgentTool<typeof readSchema> {\n\treturn wrapToolDefinition(createReadToolDefinition(operations, options));\n}\n"]}
1
+ {"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../../../src/core/tools/read.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAmB,MAAM,4BAA4B,CAAC;AAI7E,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAM5C,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AAItF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAYtD,OAAO,EAAoD,KAAK,gBAAgB,EAAgB,MAAM,eAAe,CAAC;AAEtH,QAAA,MAAM,UAAU;;;;EAId,CAAC;AAEH,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAEtD,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,gBAAgB,CAAC;CAC9B;AAWD,MAAM,WAAW,2BAA2B;IAC3C,IAAI,EAAE,WAAW,CAAC;IAClB,UAAU,EAAE,cAAc,CAAC;IAC3B,IAAI,EAAE,MAAM,CAAC;CACb;AAED,MAAM,MAAM,kBAAkB,GAAG,cAAc,GAAG,2BAA2B,CAAC;AAE9E,KAAK,0BAA0B,GAAG,CAAC,YAAY,EAAE,MAAM,KAAK,kBAAkB,GAAG,SAAS,CAAC;AAE3F,MAAM,WAAW,eAAe;IAC/B,oEAAoE;IACpE,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,qHAAqH;IACrH,iBAAiB,CAAC,EAAE,0BAA0B,CAAC;CAC/C;AAoUD,MAAM,MAAM,kBAAkB,GAAG,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,CAAC,CAAC;AAEhG,wBAAgB,wBAAwB,CAAC,UAAU,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,kBAAkB,CAgDlH;AAED,wBAAgB,cAAc,CAAC,UAAU,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAElH","sourcesContent":["import { basename, dirname, isAbsolute, relative, resolve as resolvePath, sep } from \"node:path\";\nimport type { AgentTool, AgentToolResult } from \"@greppleai/grip-agent-core\";\nimport type { Api, Model } from \"@greppleai/grip-ai\";\nimport { Text } from \"@greppleai/grip-tui\";\n\nimport { type Static, Type } from \"typebox\";\nimport { getReadmePath } from \"../../config.ts\";\nimport { keyText } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { getLanguageFromPath, highlightCode, type Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { processImage } from \"../../utils/image-process.ts\";\nimport { formatPathRelativeToCwdOrAbsolute } from \"../../utils/paths.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { fmtRegion } from \"./hashline/apply.ts\";\nimport { HASH_SEP, initHasher, lineHashes } from \"./hashline/hash.ts\";\nimport { visLines as hashlineVisLines } from \"./hashline-utils.ts\";\nimport type { ToolOperations } from \"./operations.ts\";\nimport { resolveReadPathAsync, resolveToCwd } from \"./path-utils.ts\";\nimport {\n\tformatBackendIcon,\n\tformatHiddenLinesHint,\n\tgetTextOutput,\n\tinvalidArgText,\n\treplaceTabs,\n\tshortenPath,\n\tstr,\n} from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult, truncateHead } from \"./truncate.ts\";\n\nconst readSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to read (relative or absolute)\" }),\n\toffset: Type.Optional(Type.Number({ description: \"Line number to start reading from (1-indexed)\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of lines to read\" })),\n});\n\nexport type ReadToolInput = Static<typeof readSchema>;\n\nexport interface ReadToolDetails {\n\ttruncation?: TruncationResult;\n}\n\ntype CompactReadClassificationKind = \"docs\" | \"resource\" | \"skill\" | \"rule\";\n\ninterface CompactReadClassification {\n\tkind: CompactReadClassificationKind;\n\tlabel: string;\n}\n\nconst COMPACT_RESOURCE_FILE_NAMES = new Set([\"AGENTS.override.md\", \"AGENTS.md\", \"AGENTS.MD\", \"CLAUDE.md\", \"CLAUDE.MD\"]);\n\nexport interface ReadToolOperationsSelection {\n\tkind: \"selection\";\n\toperations: ToolOperations;\n\tpath: string;\n}\n\nexport type ReadToolOperations = ToolOperations | ReadToolOperationsSelection;\n\ntype ReadToolOperationsSelector = (absolutePath: string) => ReadToolOperations | undefined;\n\nexport interface ReadToolOptions {\n\t/** Whether to auto-resize images to 2000x2000 max. Default: true */\n\tautoResizeImages?: boolean;\n\t/** Select a backend, and optionally a canonical path, for a resolved absolute path. Defaults to the tool backend. */\n\toperationsForPath?: ReadToolOperationsSelector;\n}\n\nfunction isReadToolOperationsSelection(value: ReadToolOperations): value is ReadToolOperationsSelection {\n\treturn \"kind\" in value && value.kind === \"selection\";\n}\n\nfunction getReadToolOperations(value: ReadToolOperations | undefined): ToolOperations | undefined {\n\treturn value && isReadToolOperationsSelection(value) ? value.operations : value;\n}\n\ntype ReadRenderArgs = { path?: string; file_path?: string; offset?: number; limit?: number };\n\nfunction formatReadLineRange(args: ReadRenderArgs | undefined, theme: Theme): string {\n\tif (args?.offset === undefined && args?.limit === undefined) return \"\";\n\tconst startLine = args.offset ?? 1;\n\tconst endLine = args.limit !== undefined ? startLine + args.limit - 1 : \"\";\n\treturn theme.fg(\"warning\", `:${startLine}${endLine ? `-${endLine}` : \"\"}`);\n}\n\nfunction formatReadCall(args: ReadRenderArgs | undefined, theme: Theme): string {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst path = rawPath !== null ? shortenPath(rawPath) : null;\n\tconst invalidArg = invalidArgText(theme);\n\tconst pathDisplay = path === null ? invalidArg : path ? theme.fg(\"accent\", path) : theme.fg(\"toolOutput\", \"...\");\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"read\"))} ${pathDisplay}${formatReadLineRange(args, theme)}`;\n}\n\nfunction trimTrailingEmptyLines(lines: string[]): string[] {\n\tlet end = lines.length;\n\twhile (end > 0 && lines[end - 1] === \"\") {\n\t\tend--;\n\t}\n\treturn lines.slice(0, end);\n}\n\nfunction getNonVisionImageNote(model: Model<Api> | undefined): string | undefined {\n\tif (!model || model.input.includes(\"image\")) {\n\t\treturn undefined;\n\t}\n\treturn \"[Current model does not support images. The image will be omitted from this request.]\";\n}\n\nfunction toPosixPath(filePath: string): string {\n\treturn filePath.split(sep).join(\"/\");\n}\n\nfunction getGripDocsClassification(absolutePath: string): CompactReadClassification | undefined {\n\tconst packageRoot = dirname(getReadmePath());\n\tconst relativePath = relative(resolvePath(packageRoot), resolvePath(absolutePath));\n\tif (\n\t\trelativePath === \"\" ||\n\t\trelativePath === \"..\" ||\n\t\trelativePath.startsWith(`..${sep}`) ||\n\t\tisAbsolute(relativePath)\n\t) {\n\t\treturn undefined;\n\t}\n\n\tconst label = toPosixPath(relativePath);\n\tif (label === \"README.md\" || label.startsWith(\"docs/\") || label.startsWith(\"examples/\")) {\n\t\treturn { kind: \"docs\", label };\n\t}\n\treturn undefined;\n}\n\nfunction getCompactReadClassification(\n\targs: ReadRenderArgs | undefined,\n\tcwd: string,\n): CompactReadClassification | undefined {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tif (!rawPath) return undefined;\n\n\tconst absolutePath = resolveToCwd(rawPath, cwd);\n\tconst fileName = basename(absolutePath);\n\tif (fileName === \"SKILL.md\") {\n\t\treturn { kind: \"skill\", label: basename(dirname(absolutePath)) || fileName };\n\t}\n\tif (fileName === \"RULES.md\") {\n\t\treturn { kind: \"rule\", label: basename(dirname(absolutePath)) || fileName };\n\t}\n\n\tconst docsClassification = getGripDocsClassification(absolutePath);\n\tif (docsClassification) return docsClassification;\n\n\tif (COMPACT_RESOURCE_FILE_NAMES.has(fileName)) {\n\t\treturn { kind: \"resource\", label: formatPathRelativeToCwdOrAbsolute(absolutePath, cwd) };\n\t}\n\n\treturn undefined;\n}\n\nfunction formatCompactReadCall(\n\tclassification: CompactReadClassification,\n\targs: ReadRenderArgs | undefined,\n\ttheme: Theme,\n): string {\n\tconst expandHint = theme.fg(\"dim\", ` (${keyText(\"app.tools.expand\")} to expand)`);\n\tif (classification.kind === \"skill\" || classification.kind === \"rule\") {\n\t\tconst label = classification.kind === \"skill\" ? \"skill\" : \"rule\";\n\t\treturn (\n\t\t\ttheme.fg(\"customMessageLabel\", `\\x1b[1m[${label}]\\x1b[22m `) +\n\t\t\ttheme.fg(\"customMessageText\", classification.label) +\n\t\t\tformatReadLineRange(args, theme) +\n\t\t\texpandHint\n\t\t);\n\t}\n\n\treturn (\n\t\ttheme.fg(\"toolTitle\", theme.bold(`read ${classification.kind}`)) +\n\t\t\" \" +\n\t\ttheme.fg(\"accent\", classification.label) +\n\t\tformatReadLineRange(args, theme) +\n\t\texpandHint\n\t);\n}\n\nfunction formatReadTruncationWarning(truncation: TruncationResult | undefined, theme: Theme): string {\n\tif (!truncation?.truncated) return \"\";\n\tif (truncation.firstLineExceedsLimit) {\n\t\treturn `\\n${theme.fg(\"warning\", `[First line exceeds ${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit]`)}`;\n\t}\n\tif (truncation.truncatedBy === \"lines\") {\n\t\treturn `\\n${theme.fg(\"warning\", `[Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines (${truncation.maxLines ?? DEFAULT_MAX_LINES} line limit)]`)}`;\n\t}\n\treturn `\\n${theme.fg(\"warning\", `[Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)]`)}`;\n}\n\nfunction formatReadResult(\n\targs: ReadRenderArgs | undefined,\n\tresult: AgentToolResult<ReadToolDetails | undefined>,\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n\tcwd: string,\n\tisError: boolean,\n): string {\n\tif (!options.expanded && !isError && getCompactReadClassification(args, cwd)) {\n\t\treturn \"\";\n\t}\n\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst output = getTextOutput(result, showImages);\n\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tconst renderedLines = lang ? highlightCode(replaceTabs(output), lang) : output.split(\"\\n\");\n\tconst lines = trimTrailingEmptyLines(renderedLines);\n\tconst maxLines = options.expanded ? lines.length : 10;\n\tconst displayLines = lines.slice(0, maxLines);\n\tconst remaining = lines.length - maxLines;\n\tlet text = `\\n${displayLines.map((line) => (lang ? replaceTabs(line) : theme.fg(\"toolOutput\", replaceTabs(line)))).join(\"\\n\")}`;\n\tif (remaining > 0) {\n\t\ttext += `\\n\\n${formatHiddenLinesHint(remaining, theme)}`;\n\t}\n\n\ttext += formatReadTruncationWarning(result.details?.truncation, theme);\n\treturn text;\n}\n\ninterface ResolvedReadTarget {\n\toperations: ToolOperations;\n\tpath: string;\n}\n\ninterface ReadExecutionOptions {\n\tinput: ReadToolInput;\n\tdefaultOperations: ToolOperations;\n\tcwd: string;\n\toperationsForPath: ReadToolOperationsSelector | undefined;\n\tautoResizeImages: boolean;\n\tmodel: Model<Api> | undefined;\n\tsignal: AbortSignal | undefined;\n}\n\ninterface TextReadOutputOptions {\n\ttruncation: TruncationResult;\n\tallLines: string[];\n\tstartLine: number;\n\tstartLineDisplay: number;\n\tendLine: number;\n\ttotalFileLines: number;\n}\n\nasync function resolveReadTarget(options: ReadExecutionOptions): Promise<ResolvedReadTarget> {\n\tconst absolutePath = await resolveReadPathAsync(options.input.path, options.cwd);\n\tconst selection = options.operationsForPath?.(absolutePath);\n\treturn {\n\t\toperations: getReadToolOperations(selection) ?? options.defaultOperations,\n\t\tpath: selection && isReadToolOperationsSelection(selection) ? selection.path : absolutePath,\n\t};\n}\n\nasync function readImageFile(\n\toperations: ToolOperations,\n\tpath: string,\n\tmimeType: string,\n\tautoResizeImages: boolean,\n\tnonVisionImageNote: string | undefined,\n): Promise<AgentToolResult<ReadToolDetails | undefined>> {\n\tconst buffer = await operations.readFile(path);\n\tconst processed = await processImage(buffer, mimeType, { autoResizeImages });\n\tif (!processed.ok) {\n\t\tlet text = `Read image file [${mimeType}]\\n${processed.message}`;\n\t\tif (nonVisionImageNote) text += `\\n${nonVisionImageNote}`;\n\t\treturn { content: [{ type: \"text\", text }], details: undefined };\n\t}\n\tlet text = `Read image file [${processed.mimeType}]`;\n\tif (processed.hints.length > 0) text += `\\n${processed.hints.join(\"\\n\")}`;\n\tif (nonVisionImageNote) text += `\\n${nonVisionImageNote}`;\n\treturn {\n\t\tcontent: [\n\t\t\t{ type: \"text\", text },\n\t\t\t{ type: \"image\", data: processed.data, mimeType: processed.mimeType },\n\t\t],\n\t\tdetails: undefined,\n\t};\n}\n\nfunction formatTextReadOutput(options: TextReadOutputOptions): AgentToolResult<ReadToolDetails | undefined> {\n\tconst { truncation } = options;\n\tlet text: string;\n\tlet details: ReadToolDetails | undefined;\n\tif (truncation.firstLineExceedsLimit) {\n\t\tconst firstLineSize = formatSize(Buffer.byteLength(options.allLines[options.startLine] ?? \"\", \"utf-8\"));\n\t\ttext = `[Line ${options.startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Hashline output requires full lines; use bash for this line.]`;\n\t\tdetails = { truncation };\n\t} else if (truncation.truncated) {\n\t\tconst endLineDisplay = options.startLineDisplay + truncation.outputLines - 1;\n\t\tconst nextOffset = endLineDisplay + 1;\n\t\ttext = truncation.content;\n\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\ttext += `\\n\\n[Showing lines ${options.startLineDisplay}-${endLineDisplay} of ${options.totalFileLines}. Use offset=${nextOffset} to continue.]`;\n\t\t} else {\n\t\t\ttext += `\\n\\n[Showing lines ${options.startLineDisplay}-${endLineDisplay} of ${options.totalFileLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Use offset=${nextOffset} to continue.]`;\n\t\t}\n\t\tdetails = { truncation };\n\t} else if (options.endLine < options.totalFileLines) {\n\t\tconst remaining = options.totalFileLines - options.endLine;\n\t\ttext = `${truncation.content}\\n\\n[${remaining} more lines in file. Use offset=${options.endLine + 1} to continue.]`;\n\t} else {\n\t\ttext = truncation.content;\n\t}\n\treturn { content: [{ type: \"text\", text }], details };\n}\n\nasync function readTextFile(\n\toperations: ToolOperations,\n\tpath: string,\n\toffset: number | undefined,\n\tlimit: number | undefined,\n): Promise<AgentToolResult<ReadToolDetails | undefined>> {\n\tawait initHasher();\n\tconst buffer = await operations.readFile(path);\n\tconst textContent = buffer.toString(\"utf-8\").replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\");\n\tconst allLines = hashlineVisLines(textContent);\n\tconst totalFileLines = allLines.length;\n\tconst startLine = offset ? Math.max(0, offset - 1) : 0;\n\tconst startLineDisplay = startLine + 1;\n\tif (totalFileLines === 0) {\n\t\tif (startLineDisplay !== 1) throw new Error(`Offset ${offset} is beyond end of file (0 lines total)`);\n\t\tconst emptyHash = (await lineHashes(textContent, path))[0] ?? \"\";\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `${emptyHash}${HASH_SEP}\\n[File is empty. Use edit to insert content.]` }],\n\t\t\tdetails: undefined,\n\t\t};\n\t}\n\tif (startLine >= totalFileLines) {\n\t\tthrow new Error(`Offset ${offset} is beyond end of file (${totalFileLines} lines total)`);\n\t}\n\tconst endLine = limit !== undefined ? Math.min(startLine + limit, totalFileLines) : totalFileLines;\n\tconst allHashes = await lineHashes(textContent, path);\n\tconst selectedContent = fmtRegion(allHashes.slice(startLine, endLine), allLines.slice(startLine, endLine));\n\treturn formatTextReadOutput({\n\t\ttruncation: truncateHead(selectedContent),\n\t\tallLines,\n\t\tstartLine,\n\t\tstartLineDisplay,\n\t\tendLine,\n\t\ttotalFileLines,\n\t});\n}\n\nasync function executeReadRequest(\n\toptions: ReadExecutionOptions,\n\tisAborted: () => boolean,\n): Promise<AgentToolResult<ReadToolDetails | undefined> | undefined> {\n\tconst target = await resolveReadTarget(options);\n\tif (isAborted()) return undefined;\n\tawait target.operations.access(target.path, \"read\");\n\tif (isAborted()) return undefined;\n\tconst mimeType = target.operations.detectImageMimeType\n\t\t? await target.operations.detectImageMimeType(target.path)\n\t\t: undefined;\n\tconst nonVisionImageNote = getNonVisionImageNote(options.model);\n\tconst result = mimeType\n\t\t? await readImageFile(target.operations, target.path, mimeType, options.autoResizeImages, nonVisionImageNote)\n\t\t: await readTextFile(target.operations, target.path, options.input.offset, options.input.limit);\n\treturn isAborted() ? undefined : result;\n}\n\nfunction executeAbortableRead(options: ReadExecutionOptions): Promise<AgentToolResult<ReadToolDetails | undefined>> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (options.signal?.aborted) {\n\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\treturn;\n\t\t}\n\t\tlet aborted = false;\n\t\tconst onAbort = () => {\n\t\t\taborted = true;\n\t\t\treject(new Error(\"Operation aborted\"));\n\t\t};\n\t\toptions.signal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\tvoid executeReadRequest(options, () => aborted).then(\n\t\t\t(result) => {\n\t\t\t\tif (result === undefined) return;\n\t\t\t\toptions.signal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\tresolve(result);\n\t\t\t},\n\t\t\t(error) => {\n\t\t\t\toptions.signal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\tif (!aborted) reject(error);\n\t\t\t},\n\t\t);\n\t});\n}\n\nexport type ReadToolDefinition = ToolDefinition<typeof readSchema, ReadToolDetails | undefined>;\n\nexport function createReadToolDefinition(operations: ToolOperations, options?: ReadToolOptions): ReadToolDefinition {\n\tconst autoResizeImages = options?.autoResizeImages ?? true;\n\tconst ops = operations;\n\tconst cwd = operations.cwd;\n\tconst operationsForPath = options?.operationsForPath;\n\treturn {\n\t\tname: \"read\",\n\t\tlabel: \"read\",\n\t\tdescription: `Read the contents of a file. Supports text files and images (jpg, png, gif, webp). Images are sent as attachments. Text files are returned as HASH│content rows for hash-anchored editing. Output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`,\n\t\tpromptSnippet: \"Read file contents with hashline anchors\",\n\t\tpromptGuidelines: [\n\t\t\t\"Use read to examine files instead of cat or sed.\",\n\t\t\t\"For edits, copy only the 3-character HASH values into edit hash_range_inclusive; do not include HASH│ prefixes in content_lines.\",\n\t\t],\n\t\tparameters: readSchema,\n\t\tasync execute(_toolCallId, input: ReadToolInput, signal?: AbortSignal, _onUpdate?, ctx?) {\n\t\t\treturn executeAbortableRead({\n\t\t\t\tinput,\n\t\t\t\tdefaultOperations: ops,\n\t\t\t\tcwd,\n\t\t\t\toperationsForPath,\n\t\t\t\tautoResizeImages,\n\t\t\t\tmodel: ctx?.model,\n\t\t\t\tsignal,\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tconst classification = !context.expanded ? getCompactReadClassification(args, context.cwd) : undefined;\n\t\t\tconst renderArgs = args as ReadRenderArgs | undefined;\n\t\t\tconst rawPath = str(renderArgs?.file_path ?? renderArgs?.path);\n\t\t\tconst displayOps = rawPath\n\t\t\t\t? (getReadToolOperations(operationsForPath?.(resolveToCwd(rawPath, cwd))) ?? ops)\n\t\t\t\t: ops;\n\t\t\ttext.setText(\n\t\t\t\tformatBackendIcon(displayOps.getBackendInfo?.(), theme) +\n\t\t\t\t\t(classification ? formatCompactReadCall(classification, args, theme) : formatReadCall(args, theme)),\n\t\t\t);\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(\n\t\t\t\tformatReadResult(context.args, result, options, theme, context.showImages, context.cwd, context.isError),\n\t\t\t);\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createReadTool(operations: ToolOperations, options?: ReadToolOptions): AgentTool<typeof readSchema> {\n\treturn wrapToolDefinition(createReadToolDefinition(operations, options));\n}\n"]}
@@ -2,7 +2,7 @@ import { basename, dirname, isAbsolute, relative, resolve as resolvePath, sep }
2
2
  import { Text } from "@greppleai/grip-tui";
3
3
  import { Type } from "typebox";
4
4
  import { getReadmePath } from "../../config.js";
5
- import { keyHint, keyText } from "../../modes/interactive/components/keybinding-hints.js";
5
+ import { keyText } from "../../modes/interactive/components/keybinding-hints.js";
6
6
  import { getLanguageFromPath, highlightCode } from "../../modes/interactive/theme/theme.js";
7
7
  import { processImage } from "../../utils/image-process.js";
8
8
  import { formatPathRelativeToCwdOrAbsolute } from "../../utils/paths.js";
@@ -10,7 +10,7 @@ import { fmtRegion } from "./hashline/apply.js";
10
10
  import { HASH_SEP, initHasher, lineHashes } from "./hashline/hash.js";
11
11
  import { visLines as hashlineVisLines } from "./hashline-utils.js";
12
12
  import { resolveReadPathAsync, resolveToCwd } from "./path-utils.js";
13
- import { formatBackendIcon, getTextOutput, invalidArgText, replaceTabs, shortenPath, str } from "./render-utils.js";
13
+ import { formatBackendIcon, formatHiddenLinesHint, getTextOutput, invalidArgText, replaceTabs, shortenPath, str, } from "./render-utils.js";
14
14
  import { wrapToolDefinition } from "./tool-definition-wrapper.js";
15
15
  import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateHead } from "./truncate.js";
16
16
  const readSchema = Type.Object({
@@ -130,7 +130,7 @@ function formatReadResult(args, result, options, theme, showImages, cwd, isError
130
130
  const remaining = lines.length - maxLines;
131
131
  let text = `\n${displayLines.map((line) => (lang ? replaceTabs(line) : theme.fg("toolOutput", replaceTabs(line)))).join("\n")}`;
132
132
  if (remaining > 0) {
133
- text += `${theme.fg("muted", `\n... (${remaining} more lines,`)} ${keyHint("app.tools.expand", "to expand")})`;
133
+ text += `\n\n${formatHiddenLinesHint(remaining, theme)}`;
134
134
  }
135
135
  text += formatReadTruncationWarning(result.details?.truncation, theme);
136
136
  return text;