@kb-labs/agent-tools 2.118.2 → 2.119.0-canary.0c078654e

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/registry.ts","../src/tools/shared/tool-error.ts","../src/config.ts","../src/utils.ts","../src/tools/filesystem/filesystem.ts","../src/tools/filesystem/mass-replace.ts","../src/tools/search/search.ts","../src/tools/memory/memory.ts","../src/tools/memory/archive-recall.ts","../src/tools/planning/todo.ts","../src/tools/planning/plan-validate.ts","../src/tools/planning/plan-write.ts","../src/tools/execution/shell.ts","../src/tools/execution/async-tasks.ts","../src/tools/interaction/interaction.ts","../src/tools/interaction/reporting.ts","../src/tools/index.ts","../src/gateway.ts","../src/remote-workspace-provider.ts"],"names":["path","fs","relative","path2","MAX_FILE_SIZE","fs3","path3","crypto2","trimOutput","MAX_OUTPUT_CHARS","fs4","normalizeOffsetLimit","path5","fs5","path6","fs6","resolve","useLLM","path8","fs7"],"mappings":";;;;;;;;;;;;AAMO,IAAM,eAAN,MAAmB;AAAA,EAChB,KAAA,uBAAY,GAAA,EAAkB;AAAA,EAC9B,OAAA;AAAA,EAER,YAAY,OAAA,EAAsB;AAChC,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA,EAKA,SAAS,IAAA,EAAkB;AACzB,IAAA,IAAA,CAAK,MAAM,GAAA,CAAI,IAAA,CAAK,UAAA,CAAW,QAAA,CAAS,MAAM,IAAI,CAAA;AAAA,EACpD;AAAA;AAAA;AAAA;AAAA,EAKA,IAAI,IAAA,EAAgC;AAClC,IAAA,OAAO,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,IAAI,CAAA;AAAA,EAC5B;AAAA;AAAA;AAAA;AAAA,EAKA,cAAA,GAAiB;AACf,IAAA,OAAO,KAAA,CAAM,IAAA,CAAK,IAAA,CAAK,KAAA,CAAM,M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IAAA,OAAO,MAAM,IAAA,CAAK,IAAA,CAAK,QAAA,CAAS,QAAA,EAAU,QAAQ,CAAC,OAAA,EAAS,SAAA,EAAW,OAAO,CAAC,CAAA;AAAA,EACjF;AAAA,EAEA,MAAM,SAAA,CACJ,OAAA,EACA,OAAA,EACsB;AACtB,IAAA,OAAO,MAAM,KAAK,IAAA,CAAK,QAAA,CAAS,SAAS,MAAA,EAAQ,CAAC,OAAA,EAAS,OAAO,CAAC,CAAA;AAAA,EACrE;AACF","file":"index.js","sourcesContent":["/**\n * Tool registry for managing available tools\n */\n\nimport type { Tool, ToolContext } from './types.js';\n\nexport class ToolRegistry {\n private tools = new Map<string, Tool>();\n private context: ToolContext;\n\n constructor(context: ToolContext) {\n this.context = context;\n }\n\n /**\n * Register a tool\n */\n register(tool: Tool): void {\n this.tools.set(tool.definition.function.name, tool);\n }\n\n /**\n * Get tool by name\n */\n get(name: string): Tool | undefined {\n return this.tools.get(name);\n }\n\n /**\n * Get all tool definitions for LLM\n */\n getDefinitions() {\n return Array.from(this.tools.values()).map(t => t.definition);\n }\n\n /**\n * Execute a tool with automatic required-argument validation.\n * Returns a structured error if required args are missing/null/undefined,\n * so the agent understands what went wrong and can correct its call.\n */\n async execute(name: string, input: Record<string, unknown>) {\n const tool = this.tools.get(name);\n if (!tool) {\n return {\n success: false,\n output: `UNKNOWN_TOOL: \"${name}\" is not a registered tool. Available tools: ${this.getToolNames().join(', ')}`,\n };\n }\n\n // Validate required parameters against JSON schema\n const required: string[] = tool.definition.function.parameters?.required ?? [];\n const missing = required.filter(\n (key) => input[key] === undefined || input[key] === null,\n );\n if (missing.length > 0) {\n const params = tool.definition.function.parameters?.properties ?? {};\n const details = missing\n .map((k) => {\n const desc = (params[k] as { description?: string } | undefined)?.description ?? '';\n return ` - ${k}${desc ? ': ' + desc : ''}`;\n })\n .join('\\n');\n return {\n success: false,\n output:\n `MISSING_REQUIRED_ARGUMENTS for tool \"${name}\":\\n${details}\\n\\n` +\n `Hint: if a string argument is missing, your response may have been cut off by the output token limit (stop_reason=max_tokens). ` +\n `For large content, write in multiple smaller calls instead of one large call.`,\n };\n }\n\n return tool.executor(input);\n }\n\n /**\n * Get sorted list of registered tool names\n */\n getToolNames(): string[] {\n return Array.from(this.tools.keys()).sort();\n }\n\n /**\n * Get context\n */\n getContext(): ToolContext {\n return this.context;\n }\n}\n","import type { ToolResult } from '@kb-labs/agent-contracts';\n\nexport function toolError(input: {\n code: string;\n message: string;\n retryable?: boolean;\n hint?: string;\n details?: Record<string, unknown>;\n}): ToolResult {\n // Build error string that the LLM actually sees in tool results.\n // Include the hint directly — it tells the LLM what to do next,\n // preventing retry loops where the model doesn't know how to recover.\n const parts = [`${input.code}: ${input.message}`];\n if (input.hint) {\n parts.push(`\\nNext step: ${input.hint}`);\n }\n if (input.retryable === false) {\n parts.push('(This error cannot be resolved by retrying the same call.)');\n }\n const error = parts.join('\\n');\n\n return {\n success: false,\n error,\n errorDetails: {\n code: input.code,\n message: input.message,\n retryable: input.retryable,\n hint: input.hint,\n details: input.details,\n },\n metadata: {\n errorCode: input.code,\n retryable: input.retryable ?? false,\n ...(input.details || {}),\n },\n };\n}\n\n","/**\n * Centralized configuration constants for agent tools.\n *\n * All magic numbers and default values live here — tool implementations\n * import from this module instead of defining inline constants.\n */\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Filesystem tool config\n// ═══════════════════════════════════════════════════════════════════════════\n\nexport const FILESYSTEM_CONFIG = {\n /** Hard cap on file size to read (500KB) — prevents context overflow */\n maxFileSize: 500_000,\n /** Hard cap on lines returned per read — prevents context overflow */\n maxLinesPerRead: 2_000,\n /** Default lines to return when not specified — read whole file up to maxLinesPerRead */\n defaultLines: 2_000,\n /** Hard cap on content size for write operations (1MB) */\n maxWriteSize: 1_000_000,\n /** Default limit for directory listing */\n defaultListLimit: 50,\n /** Maximum limit for directory listing */\n maxListLimit: 200,\n /** Max output characters before trimming (prevents context explosion) */\n maxOutputChars: 12_000,\n} as const;\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Search tool config\n// ═══════════════════════════════════════════════════════════════════════════\n\nexport const SEARCH_CONFIG = {\n /** Timeout for search commands (15s) — fail fast, don't burn iterations */\n timeoutMs: 15_000,\n /** Max stdout buffer for search commands (8MB) */\n maxBuffer: 8 * 1024 * 1024,\n /** Default result limit — enough for actionable results */\n defaultResultLimit: 50,\n /** Maximum result limit */\n maxResultLimit: 200,\n /** Max output characters before trimming */\n maxOutputChars: 8_000,\n /**\n * Directories excluded from search by default.\n * These are never useful for code understanding and often huge.\n * Pass exclude=[] to override entirely, or exclude=[...custom] to replace the list.\n */\n defaultExcludes: [\n 'node_modules', '.git', 'dist', 'build', '.next',\n '.kb', '.pnpm', 'coverage', '__pycache__', '.venv', '.cache',\n ] as string[],\n} as const;\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Shell tool config\n// ═══════════════════════════════════════════════════════════════════════════\n\nexport const SHELL_CONFIG = {\n /** Max stdout buffer — aligned with SEARCH_CONFIG (16MB) */\n maxBuffer: 16 * 1024 * 1024,\n} as const;\n\n// ═══════════════════════════════════════════════════════════════════════════\n// TODO tool config\n// ═══════════════════════════════════════════════════════════════════════════\n\nexport const TODO_CONFIG = {\n /** Cache key prefix for todo lists */\n cachePrefix: 'agent:todo:',\n /** TTL for cached todo lists (7 days) */\n cacheTtlMs: 7 * 24 * 60 * 60 * 1000,\n} as const;\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Delegation tool config\n// ═══════════════════════════════════════════════════════════════════════════\n\nexport const DELEGATION_CONFIG = {\n /** Default max iterations for spawned sub-agents (safety net — token budget is primary control) */\n defaultMaxIterations: 100,\n /** Default budget fraction (50% of parent remaining — sub-agents need real budget) */\n defaultBudgetFraction: 0.5,\n} as const;\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Sub-agent presets\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Sub-agent tool allowlists and iteration defaults per preset.\n *\n * Single source of truth: lives in agent-tools because it knows tool names.\n * agent-core receives these as `allowedTools: string[]` data via SpawnAgentRequest\n * (no import from agent-tools needed — correct dependency direction).\n */\nexport const SUB_AGENT_PRESETS = {\n /** Read-only exploration and evidence gathering. */\n research: {\n tools: new Set<string>([\n 'fs_read', 'fs_list',\n 'glob_search', 'grep_search', 'find_definition', 'code_stats',\n 'memory_get', 'memory_finding', 'archive_recall',\n 'todo_get',\n 'report',\n ]),\n maxIterations: 50,\n },\n /** Full read/write capabilities for implementation tasks. */\n execute: {\n tools: new Set<string>([\n 'fs_read', 'fs_write', 'fs_patch', 'fs_replace', 'fs_list', 'mass_replace',\n 'glob_search', 'grep_search', 'find_definition', 'code_stats',\n 'shell_exec',\n 'memory_get', 'memory_finding', 'memory_blocker', 'memory_correction',\n 'todo_create', 'todo_update', 'todo_get',\n 'plan_write',\n 'ask_user', 'report',\n ]),\n maxIterations: 100,\n },\n /** Code review and verification: read + shell (linters, tests). */\n review: {\n tools: new Set<string>([\n 'fs_read', 'fs_list',\n 'glob_search', 'grep_search', 'find_definition', 'code_stats',\n 'shell_exec',\n 'memory_get', 'memory_finding', 'archive_recall',\n 'todo_get',\n 'report',\n ]),\n maxIterations: 50,\n },\n /**\n * Adversarial verification: independent agent that checks another agent's work.\n * Has read + shell access to run tests, check imports, verify builds.\n * Reports PASS/FAIL verdict with evidence.\n */\n verification: {\n tools: new Set<string>([\n 'fs_read', 'fs_list',\n 'glob_search', 'grep_search', 'find_definition', 'code_stats',\n 'shell_exec',\n 'report',\n ]),\n maxIterations: 25,\n },\n} as const;\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Mass replace tool config\n// ═══════════════════════════════════════════════════════════════════════════\n\nexport const MASS_REPLACE_CONFIG = {\n /** Hard cap on file size to process (1MB) — same as maxWriteSize */\n maxFileSize: 1_000_000,\n /** Maximum number of files to process in one operation */\n maxFiles: 100,\n} as const;\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Plan mode tool allowlist\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Tools available in plan mode — read-only exploration + async task delegation.\n * Used as `allowedTools` in ToolContext for both the plan-writer and any\n * research sub-agents it spawns via task_submit. Single source of truth:\n * lives in agent-tools so both agent-core and tests can import it without\n * creating a circular dependency.\n */\nexport const PLAN_READ_ONLY_TOOL_NAMES = new Set<string>([\n 'fs_read',\n 'fs_list',\n 'glob_search',\n 'grep_search',\n 'find_definition',\n 'code_stats',\n 'memory_get',\n 'memory_finding',\n 'memory_blocker',\n 'archive_recall',\n 'todo_create',\n 'todo_update',\n 'todo_get',\n 'ask_user',\n 'report',\n 'task_submit', // plan-writer can delegate research to async sub-agents\n 'task_status', // check progress of delegated tasks\n 'task_collect', // wait for and collect sub-agent results\n 'plan_validate', // LLM-based plan quality gate (agent calls this to self-assess before report)\n 'plan_write', // Write/update plan file on disk (iterative plan building)\n]);\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Source file extensions — single source of truth\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Source file extensions grouped by language.\n * Use ALL_SOURCE_EXTENSIONS or the helper functions for CLI flags.\n */\nexport const SOURCE_FILE_EXTENSIONS = {\n typescript: ['ts', 'tsx'],\n javascript: ['js', 'jsx'],\n python: ['py'],\n csharp: ['cs'],\n java: ['java'],\n go: ['go'],\n rust: ['rs'],\n ruby: ['rb'],\n php: ['php'],\n swift: ['swift'],\n kotlin: ['kt'],\n scala: ['scala'],\n cpp: ['cpp', 'c', 'h', 'cc', 'cxx'],\n} as const;\n\n/** Flat list of all source file extensions */\nexport const ALL_SOURCE_EXTENSIONS: readonly string[] = Object.values(SOURCE_FILE_EXTENSIONS).flat();\n\nexport function shellSingleQuote(value: string): string {\n return `'${value.replace(/'/g, `'\\\"'\\\"'`)}'`;\n}\n\n/**\n * Build `--include='*.ext'` flags for ripgrep / grep.\n * @example toRgIncludes(ALL_SOURCE_EXTENSIONS)\n * // → \"--include='*.ts' --include='*.tsx' ...\"\n */\nexport function toRgIncludes(exts: readonly string[]): string {\n return exts.map(e => `--include=${shellSingleQuote(`*.${e}`)}`).join(' ');\n}\n\n/**\n * Build `--include=*.ext` args for grep when using execa array mode (no shell).\n * @example toRgIncludesArgs(['ts', 'tsx'])\n * // → ['--include=*.ts', '--include=*.tsx']\n */\nexport function toRgIncludesArgs(exts: readonly string[]): string[] {\n return exts.map(e => `--include=*.${e}`);\n}\n\n/**\n * Build `-name '*.ext'` flags for `find` (joined with ` -o `).\n * @example toFindNames(ALL_SOURCE_EXTENSIONS)\n * // → \"-name '*.ts' -o -name '*.tsx' ...\"\n */\nexport function toFindNames(exts: readonly string[]): string {\n return exts.map(e => `-name ${shellSingleQuote(`*.${e}`)}`).join(' -o ');\n}\n\n/**\n * Build `-name *.ext` args for `find` when using execa array mode (no shell).\n * Returns a flat list of alternating pairs: ['-name', '*.ts', '-o', '-name', '*.tsx', ...]\n * with no leading/trailing `-o`.\n * @example toFindNamesArgs(['ts', 'tsx'])\n * // → ['-name', '*.ts', '-o', '-name', '*.tsx']\n */\nexport function toFindNamesArgs(exts: readonly string[]): string[] {\n if (exts.length === 0) {return [];}\n const result: string[] = [];\n for (let i = 0; i < exts.length; i++) {\n if (i > 0) {result.push('-o');}\n result.push('-name', `*.${exts[i]}`);\n }\n return result;\n}\n","/**\n * Shared utilities for agent tool implementations.\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\n\n/**\n * Normalize offset and limit parameters from tool input.\n *\n * Handles NaN, negative values, and enforces configured max/default limits.\n * Previously duplicated in filesystem.ts and search.ts.\n *\n * @example\n * const { offset, limit } = normalizeOffsetLimit(input, {\n * defaultLimit: FILESYSTEM_CONFIG.defaultLines,\n * maxLimit: FILESYSTEM_CONFIG.maxLinesPerRead,\n * });\n */\nexport function normalizeOffsetLimit(\n input: Record<string, unknown>,\n config: { defaultLimit: number; maxLimit: number },\n): { offset: number; limit: number } {\n const rawOffset = Number(input.offset);\n const rawLimit = Number(input.limit);\n\n const offset =\n Number.isFinite(rawOffset) && rawOffset >= 0 ? Math.floor(rawOffset) : 0;\n\n const limit =\n Number.isFinite(rawLimit) && rawLimit > 0\n ? Math.min(config.maxLimit, Math.floor(rawLimit))\n : config.defaultLimit;\n\n return { offset, limit };\n}\n\n/**\n * Validate that a file path stays within the working directory.\n *\n * Resolves symlinks to prevent symlink-based traversal bypasses.\n * Uses path.relative() which is more robust than startsWith().\n *\n * Previously duplicated in filesystem.ts and mass-replace.ts.\n */\nexport function validatePath(\n workingDir: string,\n filePath: string,\n): { valid: boolean; resolved: string; error?: string } {\n let resolved = path.resolve(workingDir, filePath);\n\n // Resolve symlinks to prevent symlink-based bypasses\n try {\n if (fs.existsSync(resolved)) {\n resolved = fs.realpathSync(resolved);\n }\n } catch {\n // If realpath fails, continue with resolved path (might be a non-existent file)\n }\n\n const relative = path.relative(workingDir, resolved);\n\n if (relative.startsWith('..')) {\n return {\n valid: false,\n resolved,\n error: `PATH_TRAVERSAL_ERROR: Cannot access \"${filePath}\" - path is outside working directory.\n\nHOW TO FIX: Use paths relative to the working directory. Do not use \"..\" to navigate above it.\nWORKING_DIR: ${workingDir}\nATTEMPTED_PATH: ${resolved}`,\n };\n }\n\n return { valid: true, resolved };\n}\n\n/**\n * Suggest a similar directory when the requested one doesn't exist.\n *\n * Handles common agent mistakes like nested paths (e.g. \"foo/bar\" when \"foo-bar/\" exists).\n * Returns null if no good suggestion found.\n */\nexport function suggestDirectory(workingDir: string, requestedDir: string): string | null {\n // Normalize: strip leading ./ and trailing /\n const clean = requestedDir.replace(/^\\.\\//, '').replace(/\\/$/, '');\n if (!clean || clean === '.') {return null;}\n\n // Only suggest for paths that look like nested mistakes (contain /)\n const parts = clean.split('/');\n if (parts.length < 2) {return null;}\n\n // Strategy: join first two segments with - instead of /\n // e.g. \"kb-labs/agents\" → \"kb-labs-agents\"\n const candidate = `${parts[0]}-${parts[1]}`;\n const rest = parts.slice(2).join('/');\n const fullCandidate = rest ? path.join(candidate, rest) : candidate;\n const resolved = path.resolve(workingDir, fullCandidate);\n\n if (fs.existsSync(resolved) && fs.statSync(resolved).isDirectory()) {\n return fullCandidate;\n }\n\n return null;\n}\n","/**\n * Filesystem tools for agent operations\n *\n * Features:\n * - Atomic operations with offset/limit for large files\n * - Path traversal protection\n * - Clear error messages for agent understanding\n * - Size limits to prevent context overflow\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport * as crypto from 'node:crypto';\nimport type { Tool, ToolContext } from '../../types.js';\nimport { toolError } from '../shared/tool-error.js';\nimport { FILESYSTEM_CONFIG } from '../../config.js';\nimport { normalizeOffsetLimit, validatePath, suggestDirectory } from '../../utils.js';\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Constants (sourced from centralized config)\n// ═══════════════════════════════════════════════════════════════════════════\n\nconst MAX_FILE_SIZE = FILESYSTEM_CONFIG.maxFileSize;\nconst MAX_LINES_PER_READ = FILESYSTEM_CONFIG.maxLinesPerRead;\nconst DEFAULT_LINES = FILESYSTEM_CONFIG.defaultLines;\nconst MAX_WRITE_SIZE = FILESYSTEM_CONFIG.maxWriteSize;\nconst DEFAULT_LIST_LIMIT = FILESYSTEM_CONFIG.defaultListLimit;\nconst MAX_LIST_LIMIT = FILESYSTEM_CONFIG.maxListLimit;\nconst MAX_OUTPUT_CHARS = FILESYSTEM_CONFIG.maxOutputChars;\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Output trimming\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Trim output to maxChars, appending a clear continuation hint.\n * Always shown when output is large — tells agent exactly what to do next.\n */\nfunction trimOutput(output: string, maxChars: number, continuationHint: string): string {\n if (output.length <= maxChars) {return output;}\n const trimmed = output.slice(0, maxChars);\n return `${trimmed}\\n\\n⚠️ OUTPUT TRIMMED (${output.length.toLocaleString()} chars → ${maxChars.toLocaleString()} shown)\\n${continuationHint}`;\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Helpers\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Validate path is within working directory (prevent path traversal)\n */\n/**\n * Format file size for display\n */\nfunction formatSize(bytes: number): string {\n if (bytes < 1024) {return `${bytes} bytes`;}\n if (bytes < 1024 * 1024) {return `${(bytes / 1024).toFixed(1)} KB`;}\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/**\n * Compute SHA-256 hash of content\n */\nfunction computeHash(content: string): string {\n return crypto.createHash('sha256').update(content, 'utf-8').digest('hex');\n}\n\nfunction normalizeListWindow(input: Record<string, unknown>): { offset: number; limit: number } {\n return normalizeOffsetLimit(input, { defaultLimit: DEFAULT_LIST_LIMIT, maxLimit: MAX_LIST_LIMIT });\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// fs_read - Read file with offset/limit support\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Read file contents with optional line range\n */\nexport function createFsReadTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'fs_read',\n description: `Read file contents. By default reads the entire file (up to ${MAX_LINES_PER_READ} lines). For very large files, use offset+limit to read specific sections. Prefer reading the whole file when possible — partial reads waste iterations.`,\n parameters: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'File path relative to working directory',\n },\n offset: {\n type: 'number',\n description: 'Line number to start from (1-indexed, default: 1)',\n },\n limit: {\n type: 'number',\n description: `Number of lines to read (default: all, max: ${MAX_LINES_PER_READ}). Only use for very large files — prefer reading the whole file.`,\n },\n },\n required: ['path'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const filePath = input.path as string;\n const offset = Math.max(1, (input.offset as number) || 1);\n const requestedLimit = (input.limit as number) || DEFAULT_LINES;\n const limit = Math.min(requestedLimit, MAX_LINES_PER_READ);\n\n // Validate path\n const pathValidation = validatePath(context.workingDir, filePath);\n if (!pathValidation.valid) {\n return toolError({\n code: 'PATH_VALIDATION_FAILED',\n message: pathValidation.error || 'Invalid path',\n retryable: false,\n hint: 'Use a path inside working directory.',\n details: { filePath, workingDir: context.workingDir },\n });\n }\n\n const fullPath = pathValidation.resolved;\n\n // Check file exists\n if (!fs.existsSync(fullPath)) {\n return toolError({\n code: 'FILE_NOT_FOUND',\n message: `\"${filePath}\" does not exist.`,\n retryable: true,\n hint: `Use fs_list(path=\"${path.dirname(filePath) || '.'}\") to inspect available files.`,\n details: { filePath, workingDir: context.workingDir },\n });\n }\n\n // Check if it's a file\n const stats = fs.statSync(fullPath);\n if (stats.isDirectory()) {\n return toolError({\n code: 'NOT_A_FILE',\n message: `\"${filePath}\" is a directory, not a file.`,\n retryable: false,\n hint: 'Use fs_list for directories or provide a file path.',\n details: { filePath },\n });\n }\n\n // Check file size\n if (stats.size > MAX_FILE_SIZE) {\n return toolError({\n code: 'FILE_TOO_LARGE',\n message: `\"${filePath}\" is ${formatSize(stats.size)}, exceeds limit ${formatSize(MAX_FILE_SIZE)}.`,\n retryable: true,\n hint: `Use fs_read(path=\"${filePath}\", offset=<line>, limit=<small number>).`,\n details: { filePath, size: stats.size, maxSize: MAX_FILE_SIZE },\n });\n }\n\n // Read file\n const content = fs.readFileSync(fullPath, 'utf-8');\n const allLines = content.split('\\n');\n const totalLines = allLines.length;\n\n // Validate offset\n if (offset > totalLines) {\n return toolError({\n code: 'OFFSET_OUT_OF_RANGE',\n message: `Requested offset ${offset} but file has ${totalLines} lines.`,\n retryable: true,\n hint: `Use offset between 1 and ${totalLines}.`,\n details: { filePath, offset, totalLines },\n });\n }\n\n // Extract requested lines (convert to 0-indexed)\n const startIndex = offset - 1;\n const endIndex = Math.min(startIndex + limit, totalLines);\n const selectedLines = allLines.slice(startIndex, endIndex);\n\n // Format output with line numbers\n const numberedLines = selectedLines.map((line, i) => {\n const lineNum = (startIndex + i + 1).toString().padStart(5, ' ');\n return `${lineNum}→${line}`;\n });\n\n // Build metadata header\n const hasMore = endIndex < totalLines;\n const linesRemaining = totalLines - endIndex;\n\n const warnings = [];\n if (requestedLimit > MAX_LINES_PER_READ) {\n warnings.push(`⚠️ Limit capped at ${MAX_LINES_PER_READ} (you requested ${requestedLimit})`);\n }\n if (hasMore) {\n warnings.push(`⚠️ PARTIAL READ: ${linesRemaining} lines unread. Next chunk: fs_read(path=\"${filePath}\", offset=${endIndex + 1})`);\n }\n\n const header = [\n `File: ${filePath}`,\n `Lines: ${offset}-${endIndex} of ${totalLines}`,\n hasMore ? `(${Math.round(((endIndex - offset + 1) / totalLines) * 100)}% read so far — ${linesRemaining} lines remain)` : '(end of file ✓)',\n ...warnings,\n '─'.repeat(60),\n ].filter(Boolean).join('\\n');\n\n const rawOutput = `${header}\\n${numberedLines.join('\\n')}`;\n const continuationHint = hasMore\n ? `Next chunk: fs_read(path=\"${filePath}\", offset=${endIndex + 1})`\n : '';\n\n // Register this file as read so fs_patch / fs_edit can edit it.\n // We update context directly here — this is the single authoritative place\n // to mark a file as \"seen\", regardless of whether the read was partial or full.\n const hash = computeHash(content);\n context.filesRead?.add(filePath);\n context.filesReadHash?.set(filePath, hash);\n\n return {\n success: true,\n output: trimOutput(rawOutput, MAX_OUTPUT_CHARS, continuationHint),\n metadata: {\n filePath,\n totalLines,\n readFrom: offset,\n readTo: endIndex,\n hasMore,\n fileSize: stats.size,\n contentHash: hash,\n },\n };\n },\n };\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// fs_write - Write file with size limits\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Write content to a file\n */\nexport function createFsWriteTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'fs_write',\n description: `Write a new file or completely rewrite an existing one. Creates parent directories if needed. IMPORTANT: Prefer fs_replace for modifying existing files — it only sends the diff. Only use fs_write to create NEW files or for complete rewrites where the entire content changes. If you're modifying an existing file, use fs_replace instead.`,\n parameters: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'File path relative to working directory',\n },\n content: {\n type: 'string',\n description: 'Content to write to the file',\n },\n },\n required: ['path', 'content'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const filePath = input.path as string;\n const content = input.content as string;\n\n // Validate path\n const pathValidation = validatePath(context.workingDir, filePath);\n if (!pathValidation.valid) {\n return toolError({\n code: 'PATH_VALIDATION_FAILED',\n message: pathValidation.error || 'Invalid path',\n retryable: false,\n hint: 'Use a path inside working directory.',\n details: { filePath, workingDir: context.workingDir },\n });\n }\n\n const fullPath = pathValidation.resolved;\n\n // Check content size\n const contentSize = Buffer.byteLength(content, 'utf-8');\n if (contentSize > MAX_WRITE_SIZE) {\n return {\n success: false,\n error: `CONTENT_TOO_LARGE: Content is ${formatSize(contentSize)}, exceeds limit of ${formatSize(MAX_WRITE_SIZE)}.\n\nHOW TO FIX: Split the content into smaller files, or write in chunks.`,\n };\n }\n\n // Check if overwriting existing file\n const isOverwrite = fs.existsSync(fullPath);\n const beforeContent = isOverwrite ? fs.readFileSync(fullPath, 'utf-8') : undefined;\n\n // Create parent directories if needed\n const dir = path.dirname(fullPath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n // Write file\n fs.writeFileSync(fullPath, content, 'utf-8');\n\n // Update read state so subsequent edits don't require a separate read\n const writeHash = computeHash(content);\n context.filesRead?.add(filePath);\n context.filesReadHash?.set(filePath, writeHash);\n\n const lineCount = content.split('\\n').length;\n\n return {\n success: true,\n output: `${isOverwrite ? 'Overwrote' : 'Created'} file: ${filePath}\nSize: ${formatSize(contentSize)}\nLines: ${lineCount}`,\n metadata: {\n filePath,\n fileContent: content,\n size: contentSize,\n lines: lineCount,\n isOverwrite,\n uiHint: 'code',\n // Consumed by ChangeTrackingMiddleware\n changeSnapshot: {\n operation: 'write' as const,\n beforeContent,\n afterContent: content,\n isOverwrite,\n },\n },\n };\n },\n };\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// fs_patch - Edit file by line numbers (like Claude Code)\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Edit file by replacing a range of lines\n */\nexport function createFsPatchTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'fs_patch',\n description: `Replace a range of lines by line numbers. Use fs_replace instead when possible — it's more reliable. Only use fs_patch for large block replacements where fs_replace match text would be too long. You must fs_read the file first. Line numbers are 1-indexed and inclusive.`,\n parameters: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'File path relative to working directory',\n },\n startLine: {\n type: 'number',\n description: 'First line to replace (1-indexed, inclusive)',\n },\n endLine: {\n type: 'number',\n description: 'Last line to replace (1-indexed, inclusive)',\n },\n newContent: {\n type: 'string',\n description: 'New content to replace the line range with',\n },\n },\n required: ['path', 'startLine', 'endLine', 'newContent'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const filePath = input.path as string;\n const startLine = input.startLine as number;\n const endLine = input.endLine as number;\n const newContent = input.newContent as string;\n\n // Validate path\n const pathValidation = validatePath(context.workingDir, filePath);\n if (!pathValidation.valid) {\n return { success: false, error: pathValidation.error };\n }\n\n const fullPath = pathValidation.resolved;\n\n // ═══════════════════════════════════════════════════════════════════════\n // PROTECTION 1: File must have been read in this session\n // ═══════════════════════════════════════════════════════════════════════\n if (context.filesRead && !context.filesRead.has(filePath)) {\n return toolError({\n code: 'CANNOT_EDIT_UNREAD_FILE',\n message: `File has not been read yet. You must read a file before editing it.`,\n retryable: true,\n hint: `Call fs_read(path=\"${filePath}\") to read the file first, then retry this edit.`,\n details: { filePath, startLine, endLine },\n });\n }\n\n // Check file exists\n if (!fs.existsSync(fullPath)) {\n return toolError({\n code: 'FILE_NOT_FOUND',\n message: `\"${filePath}\" does not exist.`,\n retryable: true,\n hint: 'Use fs_list to find files or fs_write to create a new file.',\n details: { filePath },\n });\n }\n\n // Read current content\n const currentContent = fs.readFileSync(fullPath, 'utf-8');\n\n // ═══════════════════════════════════════════════════════════════════════\n // PROTECTION 2: File must not have changed since read\n // ═══════════════════════════════════════════════════════════════════════\n if (context.filesReadHash) {\n const savedHash = context.filesReadHash.get(filePath);\n const currentHash = computeHash(currentContent);\n\n if (savedHash && savedHash !== currentHash) {\n return toolError({\n code: 'FILE_CHANGED_SINCE_READ',\n message: `File was modified since you last read it (possibly by a linter, formatter, or another tool).`,\n retryable: true,\n hint: `Call fs_read(path=\"${filePath}\") to get the current content, then retry the edit with updated line numbers.`,\n details: { filePath, startLine, endLine },\n });\n }\n }\n\n const allLines = currentContent.split('\\n');\n const totalLines = allLines.length;\n\n // Validate line numbers\n if (startLine < 1 || startLine > totalLines) {\n return toolError({\n code: 'INVALID_START_LINE',\n message: `startLine ${startLine} is out of range (file has ${totalLines} lines).`,\n retryable: true,\n hint: `Use startLine between 1 and ${totalLines}.`,\n details: { filePath, startLine, totalLines },\n });\n }\n\n if (endLine < startLine || endLine > totalLines) {\n return toolError({\n code: 'INVALID_END_LINE',\n message: `endLine ${endLine} is invalid (startLine=${startLine}, file has ${totalLines} lines).`,\n retryable: true,\n hint: `Use endLine between ${startLine} and ${totalLines}.`,\n details: { filePath, startLine, endLine, totalLines },\n });\n }\n\n // Apply patch (convert to 0-indexed)\n const beforeLines = allLines.slice(0, startLine - 1);\n const afterLines = allLines.slice(endLine);\n const newLines = newContent ? newContent.split('\\n') : [];\n\n const patchedContent = [...beforeLines, ...newLines, ...afterLines].join('\\n');\n\n // Calculate line changes\n const removedCount = endLine - startLine + 1;\n const addedCount = newLines.length;\n const netChange = addedCount - removedCount;\n\n // Write updated content\n fs.writeFileSync(fullPath, patchedContent, 'utf-8');\n\n // Update read state so subsequent edits don't require re-read.\n // Mirrors Claude Code pattern: readFileState.set() after every edit.\n const patchedHash = computeHash(patchedContent);\n context.filesRead?.add(filePath);\n context.filesReadHash?.set(filePath, patchedHash);\n\n let action: string;\n if (addedCount === 0) {\n action = `Deleted ${removedCount} line(s)`;\n } else if (removedCount === addedCount) {\n action = `Replaced ${removedCount} line(s)`;\n } else if (netChange > 0) {\n action = `Replaced ${removedCount} line(s) with ${addedCount} line(s) (+${netChange})`;\n } else {\n action = `Replaced ${removedCount} line(s) with ${addedCount} line(s) (${netChange})`;\n }\n\n return {\n success: true,\n output: `${action} in ${filePath}\nLines ${startLine}-${endLine} → ${addedCount} new line(s)\nFile now has ${beforeLines.length + newLines.length + afterLines.length} lines (was ${totalLines})`,\n metadata: {\n filePath,\n startLine,\n endLine,\n linesRemoved: removedCount,\n linesAdded: addedCount,\n netChange,\n totalLinesBefore: totalLines,\n totalLinesAfter: beforeLines.length + newLines.length + afterLines.length,\n // Consumed by ChangeTrackingMiddleware\n changeSnapshot: {\n operation: 'patch' as const,\n beforeContent: currentContent,\n afterContent: patchedContent,\n startLine,\n endLine,\n linesAdded: addedCount,\n linesRemoved: removedCount,\n },\n },\n };\n },\n };\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// fs_replace - Content-based edit (find text → replace)\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Edit a file by matching text content and replacing it.\n * More reliable than line-number-based fs_patch because LLMs\n * can copy exact text from fs_read output.\n */\nexport function createFsReplaceTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'fs_replace',\n description: `PREFERRED tool for editing existing files. Finds exact text and replaces it — only sends the diff, not the whole file. You must fs_read the file first. Use the smallest match text that uniquely identifies the target — usually 2-4 lines is enough. The match must appear exactly once (unless replace_all=true). If multiple matches, add more surrounding context to make it unique.`,\n parameters: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'File path relative to working directory',\n },\n match: {\n type: 'string',\n description: 'Exact text to find in the file (copy from fs_read output)',\n },\n replacement: {\n type: 'string',\n description: 'Text to replace the match with',\n },\n replace_all: {\n type: 'boolean',\n description: 'Replace all occurrences (default: false — requires unique match)',\n },\n },\n required: ['path', 'match', 'replacement'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const filePath = input.path as string;\n const match = input.match as string;\n const replacement = input.replacement as string;\n const replaceAll = (input.replace_all as boolean) || false;\n\n // ── Validate path ──\n const pathValidation = validatePath(context.workingDir, filePath);\n if (!pathValidation.valid) {\n return toolError({\n code: 'PATH_VALIDATION_FAILED',\n message: pathValidation.error || 'Invalid path',\n retryable: false,\n hint: 'Use a path inside working directory.',\n details: { filePath, workingDir: context.workingDir },\n });\n }\n const fullPath = pathValidation.resolved;\n\n // ── Validate: file must have been read ──\n if (context.filesRead && !context.filesRead.has(filePath)) {\n return toolError({\n code: 'CANNOT_EDIT_UNREAD_FILE',\n message: 'File has not been read yet. You must read a file before editing it.',\n retryable: true,\n hint: `Call fs_read(path=\"${filePath}\") to read the file first, then retry this edit.`,\n details: { filePath },\n });\n }\n\n // ── Validate: file exists ──\n if (!fs.existsSync(fullPath)) {\n return toolError({\n code: 'FILE_NOT_FOUND',\n message: `\"${filePath}\" does not exist.`,\n retryable: true,\n hint: 'Use fs_list to find files or fs_write to create a new file.',\n details: { filePath },\n });\n }\n\n // ── Read current content ──\n const currentContent = fs.readFileSync(fullPath, 'utf-8');\n\n // ── Validate: file not modified since read ──\n if (context.filesReadHash) {\n const savedHash = context.filesReadHash.get(filePath);\n const currentHash = computeHash(currentContent);\n if (savedHash && savedHash !== currentHash) {\n return toolError({\n code: 'FILE_CHANGED_SINCE_READ',\n message: 'File was modified since you last read it (possibly by a linter, formatter, or another tool).',\n retryable: true,\n hint: `Call fs_read(path=\"${filePath}\") to get the current content, then retry the edit.`,\n details: { filePath },\n });\n }\n }\n\n // ── Validate: match !== replacement ──\n if (match === replacement) {\n return toolError({\n code: 'NO_CHANGE',\n message: 'The match and replacement text are identical. No changes needed.',\n retryable: false,\n hint: 'Provide different replacement text, or skip this edit if no change is needed.',\n details: { filePath },\n });\n }\n\n // ── Validate: match exists in file ──\n if (!currentContent.includes(match)) {\n return toolError({\n code: 'MATCH_NOT_FOUND',\n message: 'The match text was not found in the file.',\n retryable: true,\n hint: `Call fs_read(path=\"${filePath}\") to see the current file content, then copy the exact text you want to replace.`,\n details: { filePath, matchLength: match.length },\n });\n }\n\n // ── Validate: uniqueness (unless replace_all) ──\n const occurrences = currentContent.split(match).length - 1;\n if (occurrences > 1 && !replaceAll) {\n return toolError({\n code: 'AMBIGUOUS_MATCH',\n message: `Found ${occurrences} occurrences of the match text, but replace_all is false.`,\n retryable: true,\n hint: `Include more surrounding context in the match text to make it unique (only 1 occurrence), or set replace_all=true to replace all ${occurrences} occurrences.`,\n details: { filePath, occurrences },\n });\n }\n\n // ── Apply replacement ──\n const updatedContent = replaceAll\n ? currentContent.replaceAll(match, replacement)\n : currentContent.replace(match, replacement);\n\n // ── Write file ──\n fs.writeFileSync(fullPath, updatedContent, 'utf-8');\n\n // ── Update read state for chained edits ──\n const newHash = computeHash(updatedContent);\n context.filesRead?.add(filePath);\n context.filesReadHash?.set(filePath, newHash);\n\n // ── Calculate diff stats ──\n const matchLines = match.split('\\n').length;\n const replacementLines = replacement.split('\\n').length;\n const netChange = replacementLines - matchLines;\n\n const action = replaceAll\n ? `Replaced ${occurrences} occurrence(s)`\n : 'Replaced 1 occurrence';\n\n return {\n success: true,\n output: `${action} in ${filePath}\nMatch: ${matchLines} line(s) → Replacement: ${replacementLines} line(s) (${netChange >= 0 ? '+' : ''}${netChange})\nFile now has ${updatedContent.split('\\n').length} lines`,\n metadata: {\n filePath,\n occurrences: replaceAll ? occurrences : 1,\n matchLines,\n replacementLines,\n netChange,\n totalLinesAfter: updatedContent.split('\\n').length,\n changeSnapshot: {\n operation: 'replace' as const,\n beforeContent: currentContent,\n afterContent: updatedContent,\n match,\n replacement,\n replaceAll,\n },\n },\n };\n },\n };\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// fs_list - List directory contents\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * List files in a directory\n */\nexport function createFsListTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'fs_list',\n description: `List files and directories at a path. Non-recursive by default. IMPORTANT: node_modules/, dist/, .git/, build/, .next/ are hidden by default — they contain no useful source code. Use include_ignored=true only if you specifically need to inspect build artifacts.`,\n parameters: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Directory path relative to working directory (default: \".\")',\n },\n recursive: {\n type: 'boolean',\n description: 'Include subdirectories recursively (default: false, max depth: 3)',\n },\n include_ignored: {\n type: 'boolean',\n description: 'Include normally-hidden dirs: node_modules, dist, build, .next, .git (default: false). Only use when you explicitly need to inspect build artifacts or dependencies.',\n },\n offset: {\n type: 'number',\n description: 'Result offset for pagination (default: 0)',\n },\n limit: {\n type: 'number',\n description: `Result limit per page (default: ${DEFAULT_LIST_LIMIT}, max: ${MAX_LIST_LIMIT})`,\n },\n },\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const dirPath = (input.path as string) || '.';\n const recursive = (input.recursive as boolean) || false;\n const includeIgnored = (input.include_ignored as boolean) || false;\n const { offset, limit } = normalizeListWindow(input);\n\n // Directories hidden by default — contain no useful source code\n const IGNORED_DIRS = new Set(['node_modules', 'dist', 'build', '.next', '.git', '.pnpm', '.cache', 'coverage', '__pycache__']);\n\n // Validate path\n const pathValidation = validatePath(context.workingDir, dirPath);\n if (!pathValidation.valid) {\n return toolError({\n code: 'PATH_VALIDATION_FAILED',\n message: pathValidation.error || 'Invalid path',\n retryable: false,\n hint: 'Use a path inside working directory.',\n details: { path: dirPath, workingDir: context.workingDir },\n });\n }\n\n const fullPath = pathValidation.resolved;\n\n // Check exists\n if (!fs.existsSync(fullPath)) {\n const suggestion = suggestDirectory(context.workingDir, dirPath);\n return toolError({\n code: 'DIRECTORY_NOT_FOUND',\n message: `\"${dirPath}\" does not exist.`,\n retryable: true,\n hint: suggestion\n ? `Did you mean \"${suggestion}\"?`\n : 'Use fs_list on parent directory to discover valid paths.',\n details: { path: dirPath, workingDir: context.workingDir },\n });\n }\n\n // Check is directory\n const stats = fs.statSync(fullPath);\n if (!stats.isDirectory()) {\n return toolError({\n code: 'NOT_A_DIRECTORY',\n message: `\"${dirPath}\" is a file, not a directory.`,\n retryable: false,\n hint: 'Use fs_read for files or provide a directory path.',\n details: { path: dirPath },\n });\n }\n\n // List contents\n const entries = fs.readdirSync(fullPath, { withFileTypes: true });\n\n // Separate and sort — filter ignored dirs unless include_ignored=true\n const files = entries\n .filter(e => e.isFile())\n .map(e => e.name)\n .filter(name => !name.startsWith('.')) // Hide dotfiles\n .sort();\n\n const dirs = entries\n .filter(e => e.isDirectory())\n .map(e => e.name)\n .filter(name => {\n if (name.startsWith('.')) {return false;}\n if (!includeIgnored && IGNORED_DIRS.has(name)) {return false;}\n return true;\n })\n .sort();\n\n // Track how many ignored dirs exist so agent knows they're there\n const hiddenDirCount = includeIgnored ? 0 : entries\n .filter(e => e.isDirectory() && IGNORED_DIRS.has(e.name))\n .length;\n\n const combinedEntries = [\n ...dirs.map((name) => ({ type: 'dir' as const, name })),\n ...files.map((name) => ({ type: 'file' as const, name })),\n ];\n const pageEntries = combinedEntries.slice(offset, offset + limit);\n const hasMore = offset + limit < combinedEntries.length;\n const nextOffset = hasMore ? offset + limit : null;\n const pageDirs = pageEntries.filter((entry) => entry.type === 'dir');\n const pageFiles = pageEntries.filter((entry) => entry.type === 'file');\n\n // Format output\n const ignoredNote = hiddenDirCount > 0\n ? `[${hiddenDirCount} ignored dir(s) hidden: node_modules/dist/build/etc — use include_ignored=true to show]`\n : '';\n\n const outputParts = [\n `📁 ${dirPath === '.' ? 'Working Directory' : dirPath} (showing ${pageEntries.length}/${combinedEntries.length}, offset=${offset}, limit=${limit})`,\n ignoredNote,\n '',\n ].filter(Boolean);\n\n if (pageDirs.length > 0) {\n outputParts.push(`Directories (${dirs.length}):`);\n for (const d of pageDirs) {\n outputParts.push(` 📁 ${d.name}/`);\n }\n outputParts.push('');\n }\n\n if (pageFiles.length > 0) {\n outputParts.push(`Files (${files.length}):`);\n for (const f of pageFiles) {\n // Get file size\n const filePath = path.join(fullPath, f.name);\n const fileStats = fs.statSync(filePath);\n outputParts.push(` 📄 ${f.name} (${formatSize(fileStats.size)})`);\n }\n }\n\n if (combinedEntries.length === 0) {\n outputParts.push('(empty directory)');\n }\n\n // Add recursive listing if requested\n if (recursive && dirs.length > 0) {\n outputParts.push('');\n outputParts.push('─'.repeat(40));\n outputParts.push('Recursive structure (depth 2):');\n\n for (const d of dirs.slice(0, 10)) { // Limit to 10 dirs\n outputParts.push(`\\n📁 ${d}/`);\n const subPath = path.join(fullPath, d);\n try {\n const subEntries = fs.readdirSync(subPath, { withFileTypes: true });\n const subDirs = subEntries.filter(e => e.isDirectory() && !e.name.startsWith('.') && e.name !== 'node_modules');\n const subFiles = subEntries.filter(e => e.isFile() && !e.name.startsWith('.'));\n\n for (const sd of subDirs.slice(0, 5)) {\n outputParts.push(` 📁 ${sd.name}/`);\n }\n if (subDirs.length > 5) {\n outputParts.push(` ... and ${subDirs.length - 5} more directories`);\n }\n\n for (const sf of subFiles.slice(0, 5)) {\n outputParts.push(` 📄 ${sf.name}`);\n }\n if (subFiles.length > 5) {\n outputParts.push(` ... and ${subFiles.length - 5} more files`);\n }\n } catch {\n outputParts.push(' (unable to read)');\n }\n }\n\n if (dirs.length > 10) {\n outputParts.push(`\\n... and ${dirs.length - 10} more directories`);\n }\n }\n\n const rawOutput = outputParts.join('\\n');\n const continuationHint = hasMore\n ? `Next page: fs_list(path=\"${dirPath}\", offset=${nextOffset}, limit=${limit})`\n : '';\n\n return {\n success: true,\n output: trimOutput(rawOutput, MAX_OUTPUT_CHARS, continuationHint),\n metadata: {\n path: dirPath,\n directoryCount: dirs.length,\n fileCount: files.length,\n directories: dirs,\n files,\n totalEntries: combinedEntries.length,\n offset,\n limit,\n hasMore,\n nextOffset,\n },\n };\n },\n };\n}\n","/**\n * Mass replace tool for batch text replacement across multiple files\n *\n * Features:\n * - Supports literal string or regex patterns\n * - Glob-based file selection\n * - File history tracking for rollback\n * - Dry-run mode for preview\n * - Safe: validates paths, checks file sizes\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport * as crypto from 'node:crypto';\nimport { glob } from 'glob';\nimport type { Tool, ToolContext } from '../../types.js';\nimport { validatePath } from '../../utils.js';\nimport { MASS_REPLACE_CONFIG } from '../../config.js';\n\nconst MAX_FILE_SIZE = MASS_REPLACE_CONFIG.maxFileSize;\nconst MAX_FILES = MASS_REPLACE_CONFIG.maxFiles;\n\n// ═══════════════════════════════════════════════════════════════════════════\n// mass_replace - Batch text replacement with history tracking\n// ═══════════════════════════════════════════════════════════════════════════\n\nexport function createMassReplaceTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'mass_replace',\n description: `Batch find-and-replace across multiple files. Supports literal and regex modes. Use dryRun=true to preview. Changes are tracked for rollback.`,\n parameters: {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: 'Text or regex pattern to search for. For regex mode, use JavaScript regex syntax (without / delimiters).',\n },\n replacement: {\n type: 'string',\n description: 'Replacement text. In regex mode, can use $1, $2 for capture groups.',\n },\n scope: {\n type: 'string',\n description: 'REQUIRED: Directory to limit search scope (e.g., \"src\", \"packages/agent-core\", \".\"). Prevents accidental project-wide changes. Use \".\" for current directory only.',\n },\n files: {\n type: 'string',\n description: 'Glob pattern for files within scope (e.g., \"**/*.ts\", \"*.js\"). Combined with scope to form full path.',\n },\n mode: {\n type: 'string',\n enum: ['literal', 'regex'],\n description: 'Replacement mode: \"literal\" for exact string match (default), \"regex\" for regex patterns.',\n },\n dryRun: {\n type: 'boolean',\n description: 'Preview changes without applying them. Shows what would be changed.',\n },\n caseInsensitive: {\n type: 'boolean',\n description: 'For regex mode: make pattern case-insensitive (adds \"i\" flag).',\n },\n },\n required: ['pattern', 'replacement', 'scope', 'files'],\n },\n },\n },\n\n executor: async (input: Record<string, unknown>) => {\n const pattern = String(input.pattern || '');\n const replacement = String(input.replacement || '');\n const scope = String(input.scope || '');\n const filesPattern = String(input.files || '');\n const mode = String(input.mode || 'literal');\n const dryRun = Boolean(input.dryRun);\n const caseInsensitive = Boolean(input.caseInsensitive);\n\n // Validation\n if (!pattern) {\n return {\n success: false,\n error: 'VALIDATION_ERROR: \"pattern\" is required.',\n };\n }\n\n if (!scope) {\n return {\n success: false,\n error: 'VALIDATION_ERROR: \"scope\" is required. Specify directory to limit search (e.g., \"src\", \"packages/agent-core\", or \".\" for current dir).',\n };\n }\n\n if (!filesPattern) {\n return {\n success: false,\n error: 'VALIDATION_ERROR: \"files\" glob pattern is required.',\n };\n }\n\n if (mode !== 'literal' && mode !== 'regex') {\n return {\n success: false,\n error: `VALIDATION_ERROR: Invalid mode \"${mode}\". Must be \"literal\" or \"regex\".`,\n };\n }\n\n try {\n // Validate and resolve scope directory\n const scopeValidation = validatePath(context.workingDir, scope);\n if (!scopeValidation.valid) {\n return {\n success: false,\n error: scopeValidation.error,\n };\n }\n\n const scopePath = scopeValidation.resolved;\n if (!fs.existsSync(scopePath)) {\n return {\n success: false,\n error: `SCOPE_ERROR: Directory \"${scope}\" does not exist.`,\n };\n }\n\n if (!fs.statSync(scopePath).isDirectory()) {\n return {\n success: false,\n error: `SCOPE_ERROR: \"${scope}\" is not a directory.`,\n };\n }\n\n // Find matching files within scope\n const matches = await glob(filesPattern, {\n cwd: scopePath,\n nodir: true,\n absolute: false,\n ignore: ['**/node_modules/**', '**/dist/**', '**/.git/**'],\n });\n\n if (matches.length === 0) {\n return {\n success: true,\n output: `No files matched pattern: \"${filesPattern}\" in scope: \"${scope}\"`,\n metadata: {\n filesMatched: 0,\n filesChanged: 0,\n totalReplacements: 0,\n scope,\n },\n };\n }\n\n if (matches.length > MAX_FILES) {\n return {\n success: false,\n error: `TOO_MANY_FILES: Pattern matched ${matches.length} files, but limit is ${MAX_FILES}. Use more specific glob pattern.`,\n };\n }\n\n // Prepare regex or literal pattern\n let searchPattern: RegExp;\n if (mode === 'regex') {\n const flags = caseInsensitive ? 'gi' : 'g';\n try {\n searchPattern = new RegExp(pattern, flags);\n } catch (err) {\n return {\n success: false,\n error: `REGEX_ERROR: Invalid regex pattern \"${pattern}\": ${(err as Error).message}`,\n };\n }\n } else {\n // Literal mode: escape special chars and make global\n const escapedPattern = pattern.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const flags = caseInsensitive ? 'gi' : 'g';\n searchPattern = new RegExp(escapedPattern, flags);\n }\n\n // Process files\n const results: Array<{\n file: string;\n replacements: number;\n preview?: string;\n }> = [];\n\n let totalReplacements = 0;\n let filesChanged = 0;\n\n for (const relPath of matches) {\n // Combine scope and relative path\n const scopedPath = path.join(scope, relPath);\n\n // Validate path\n const validation = validatePath(context.workingDir, scopedPath);\n if (!validation.valid) {\n return {\n success: false,\n error: validation.error,\n };\n }\n\n const fullPath = validation.resolved;\n\n // Check file exists and size\n if (!fs.existsSync(fullPath)) {\n continue; // Skip missing files\n }\n\n const stats = fs.statSync(fullPath);\n if (stats.size > MAX_FILE_SIZE) {\n results.push({\n file: scopedPath,\n replacements: 0,\n preview: `[SKIPPED: File too large (${(stats.size / 1024).toFixed(1)} KB > ${MAX_FILE_SIZE / 1024} KB)]`,\n });\n continue;\n }\n\n // Read file\n const beforeContent = fs.readFileSync(fullPath, 'utf-8');\n\n // Apply replacement\n const afterContent = beforeContent.replace(searchPattern, replacement);\n\n // Check if anything changed\n if (beforeContent === afterContent) {\n continue; // No changes, skip\n }\n\n const matchCount = (beforeContent.match(searchPattern) || []).length;\n totalReplacements += matchCount;\n filesChanged++;\n\n // Dry-run: collect preview\n if (dryRun) {\n // Show first 3 changes as preview\n const lines = beforeContent.split('\\n');\n const changedLines: string[] = [];\n let previewCount = 0;\n\n for (let i = 0; i < lines.length && previewCount < 3; i++) {\n const line = lines[i]!;\n if (searchPattern.test(line)) {\n const newLine = line.replace(searchPattern, replacement);\n changedLines.push(` Line ${i + 1}:`);\n changedLines.push(` - ${line.slice(0, 80)}`);\n changedLines.push(` + ${newLine.slice(0, 80)}`);\n previewCount++;\n }\n }\n\n results.push({\n file: scopedPath,\n replacements: matchCount,\n preview: changedLines.join('\\n'),\n });\n } else {\n // Apply changes\n fs.writeFileSync(fullPath, afterContent, 'utf-8');\n\n // Update read state so subsequent edits don't require re-read\n const hash = crypto.createHash('sha256').update(afterContent, 'utf-8').digest('hex');\n context.filesRead?.add(scopedPath);\n context.filesReadHash?.set(scopedPath, hash);\n\n results.push({\n file: scopedPath,\n replacements: matchCount,\n });\n }\n }\n\n // Format output\n const summary = dryRun\n ? `[DRY RUN] Would replace in ${filesChanged} file(s):`\n : `✅ Replaced in ${filesChanged} file(s):`;\n\n const details = results\n .map((r) => {\n if (r.preview) {\n return `${r.file}: ${r.replacements} replacement(s)\\n${r.preview}`;\n }\n return `${r.file}: ${r.replacements} replacement(s)`;\n })\n .join('\\n\\n');\n\n const output = `${summary}\\n\\n${details}\\n\\n` +\n `Scope: ${scope}\\n` +\n `Total replacements: ${totalReplacements}\\n` +\n `Files matched: ${matches.length}\\n` +\n `Files changed: ${filesChanged}` +\n (dryRun ? '\\n\\n⚠️ DRY RUN: No files were modified. Remove dryRun=true to apply changes.' : '');\n\n return {\n success: true,\n output,\n metadata: {\n scope,\n filesMatched: matches.length,\n filesChanged,\n totalReplacements,\n dryRun,\n pattern,\n replacement,\n mode,\n },\n };\n } catch (error) {\n return {\n success: false,\n error: `EXECUTION_ERROR: ${(error as Error).message}`,\n };\n }\n },\n };\n}\n","/**\n * Search tools for finding files and content\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { execa } from 'execa';\nimport type { Tool, ToolContext } from '../../types.js';\nimport { toolError } from '../shared/tool-error.js';\nimport { SEARCH_CONFIG, ALL_SOURCE_EXTENSIONS, toRgIncludesArgs, toFindNamesArgs } from '../../config.js';\nimport { normalizeOffsetLimit as _normalizeOffsetLimit, suggestDirectory } from '../../utils.js';\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Output trimming\n// ═══════════════════════════════════════════════════════════════════════════\n\nfunction trimOutput(output: string, maxChars: number, continuationHint: string): string {\n if (output.length <= maxChars) {return output;}\n const trimmed = output.slice(0, maxChars);\n return `${trimmed}\\n\\n⚠️ OUTPUT TRIMMED (${output.length.toLocaleString()} chars → ${maxChars.toLocaleString()} shown)\\n${continuationHint}`;\n}\n\n/** Default directories to exclude from search (sourced from centralized config) */\nconst DEFAULT_EXCLUDES = SEARCH_CONFIG.defaultExcludes;\nconst MAX_OUTPUT_CHARS = SEARCH_CONFIG.maxOutputChars;\n\n/**\n * Build find exclude args from exclude list.\n * Returns flat triplets: ['!', '-path', '*\\/node_modules\\/*', '!', '-path', ...]\n */\nfunction buildFindExcludes(excludes: readonly string[]): string[] {\n const args: string[] = [];\n for (const d of excludes) {\n args.push('!', '-path', `*/${d}/*`);\n }\n return args;\n}\n\n/**\n * Build grep exclude-dir args from exclude list.\n * Returns: ['--exclude-dir=node_modules', '--exclude-dir=dist', ...]\n */\nfunction buildGrepExcludes(excludes: readonly string[]): string[] {\n return excludes.map(d => `--exclude-dir=${d}`);\n}\n\nconst SEARCH_TIMEOUT_MS = SEARCH_CONFIG.timeoutMs;\nconst DEFAULT_RESULT_LIMIT = SEARCH_CONFIG.defaultResultLimit;\nconst MAX_RESULT_LIMIT = SEARCH_CONFIG.maxResultLimit;\n\n/**\n * Check if directory exists and return error message if not.\n * Lists available top-level directories as a hint.\n */\nfunction validateDirectory(workingDir: string, directory: string): string | null {\n const fullPath = path.resolve(workingDir, directory);\n if (fs.existsSync(fullPath) && fs.statSync(fullPath).isDirectory()) {\n return null;\n }\n\n // List available directories as hint\n let hint = '';\n try {\n const entries = fs.readdirSync(workingDir, { withFileTypes: true });\n const dirs = entries\n .filter(e => e.isDirectory() && !e.name.startsWith('.') && e.name !== 'node_modules')\n .map(e => e.name)\n .sort();\n if (dirs.length > 0) {\n hint = `\\nAvailable directories: ${dirs.slice(0, 15).join(', ')}${dirs.length > 15 ? ` ... (${dirs.length} total)` : ''}`;\n }\n } catch { /* ignore */ }\n\n const suggestion = suggestDirectory(workingDir, directory);\n const didYouMean = suggestion ? `\\nDid you mean: \"${suggestion}\"?` : '';\n return `Directory \"${directory}\" not found (resolved to ${fullPath}). Use \".\" to search from project root.${hint}${didYouMean}`;\n}\n\nfunction normalizeOffsetLimit(input: Record<string, unknown>): { offset: number; limit: number } {\n return _normalizeOffsetLimit(input, { defaultLimit: DEFAULT_RESULT_LIMIT, maxLimit: MAX_RESULT_LIMIT });\n}\n\nfunction paginate<T>(items: T[], offset: number, limit: number): { page: T[]; hasMore: boolean; nextOffset: number | null } {\n const page = items.slice(offset, offset + limit);\n const hasMore = offset + limit < items.length;\n return {\n page,\n hasMore,\n nextOffset: hasMore ? offset + limit : null,\n };\n}\n\n/**\n * Search for files by pattern (glob)\n */\nexport function createGlobSearchTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'glob_search',\n description: `Find files by name pattern (glob). Pattern matches filename only — use \"*.ts\" or \"user.ts\", not bare words. IMPORTANT: node_modules/, dist/, build/, .git/ are excluded by default — they contain no source code. Omit directory to search the entire working directory. Returns up to ${DEFAULT_RESULT_LIMIT} results.`,\n parameters: {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: 'Glob pattern (e.g., \"*.ts\", \"user.ts\", \"*user*.ts\")',\n },\n directory: {\n type: 'string',\n description: 'Directory to search in (default: working directory root). Narrow to a subfolder when you already know the scope.',\n },\n exclude: {\n type: 'array',\n items: { type: 'string' },\n description: 'Extra directories to exclude on top of defaults (node_modules, dist, .git, build, .next, .kb, .pnpm, coverage are always excluded). Rarely needed.',\n },\n offset: {\n type: 'number',\n description: 'Result offset for pagination (default: 0)',\n },\n limit: {\n type: 'number',\n description: `Max results per page (default: ${DEFAULT_RESULT_LIMIT}, max: ${MAX_RESULT_LIMIT})`,\n },\n },\n required: ['pattern'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const pattern = input.pattern as string;\n const directory = (input.directory as string) || '.';\n const extra = input.exclude as string[] | undefined;\n const excludes = extra && extra.length > 0 ? [...new Set([...DEFAULT_EXCLUDES, ...extra])] : DEFAULT_EXCLUDES;\n const { offset, limit } = normalizeOffsetLimit(input);\n\n try {\n const fullPath = path.resolve(context.workingDir, directory);\n\n const dirError = validateDirectory(context.workingDir, directory);\n if (dirError) {\n return { success: true, output: dirError };\n }\n\n const windowSize = Math.min(2000, Math.max(500, offset + limit));\n\n const args = [\n fullPath,\n '-type', 'f',\n '-iname', pattern,\n ...buildFindExcludes(excludes),\n ];\n\n const result = await execa('find', args, {\n cwd: context.workingDir,\n reject: false,\n timeout: SEARCH_TIMEOUT_MS,\n });\n\n const files = result.stdout\n .split('\\n')\n .filter(Boolean)\n .slice(0, windowSize)\n .map(f => path.relative(context.workingDir, f));\n\n if (files.length === 0) {\n return {\n success: true,\n output: `No files found matching pattern: ${pattern} in ${directory === '.' ? 'project root' : directory}. Note: glob_search matches filenames only. To search file contents, use grep_search. To find class/function definitions, use find_definition.`,\n };\n }\n\n const page = paginate(files, offset, limit);\n const excludeNote = `[Excluded: ${DEFAULT_EXCLUDES.join(', ')}${extra && extra.length > 0 ? ` + ${extra.join(', ')}` : ''}]`;\n const resultText = [\n `Found ${files.length} file(s) matching \"${pattern}\" in \"${directory}\" (showing ${page.page.length}, offset=${offset}, limit=${limit})`,\n excludeNote,\n '',\n ...page.page.map(f => ` ${f}`),\n page.hasMore ? '' : '',\n ].filter(s => s !== undefined).join('\\n');\n\n const continuationHint = page.hasMore\n ? `Next page: glob_search(pattern=\"${pattern}\", directory=\"${directory}\", offset=${page.nextOffset}, limit=${limit})`\n : '';\n\n return {\n success: true,\n output: trimOutput(resultText, MAX_OUTPUT_CHARS, continuationHint),\n metadata: {\n totalMatches: files.length,\n offset,\n limit,\n hasMore: page.hasMore,\n nextOffset: page.nextOffset,\n },\n };\n } catch (error) {\n if (error instanceof Error && 'killed' in error && error.killed) {\n return toolError({\n code: 'SEARCH_TIMEOUT',\n message: `Glob search timed out after ${SEARCH_TIMEOUT_MS / 1000}s.`,\n retryable: true,\n hint: 'Narrow directory/pattern or lower limit.',\n details: { directory, pattern, timeoutMs: SEARCH_TIMEOUT_MS },\n });\n }\n if ((error as { code?: string }).code === 'ENOBUFS') {\n return toolError({\n code: 'SEARCH_BUFFER_OVERFLOW',\n message: 'Search output exceeded buffer.',\n retryable: true,\n hint: 'Narrow directory/pattern or reduce limit.',\n details: { directory, pattern, offset, limit },\n });\n }\n return toolError({\n code: 'SEARCH_FAILED',\n message: `Glob search failed: ${error instanceof Error ? error.message : String(error)}`,\n retryable: true,\n hint: 'Check pattern syntax and directory.',\n details: { directory, pattern },\n });\n }\n },\n };\n}\n\n/**\n * Search for text in files (grep)\n */\nexport function createGrepSearchTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'grep_search',\n description: `Search for text/regex in files. Returns file:line matches. IMPORTANT: node_modules/, dist/, build/ excluded by default. Omit directory to search the entire working directory. Add filePattern (e.g. \"*.ts\") to limit to specific file types. Returns up to ${DEFAULT_RESULT_LIMIT} matches.`,\n parameters: {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: 'Text pattern to search for (can be regex)',\n },\n directory: {\n type: 'string',\n description: 'Directory to search in (default: working directory root). Narrow to a subfolder when you already know the scope.',\n },\n filePattern: {\n type: 'string',\n description: 'Filter by file extension (e.g., \"*.ts\", \"*.md\"). STRONGLY RECOMMENDED: always set this to avoid scanning binary/generated files.',\n },\n exclude: {\n type: 'array',\n items: { type: 'string' },\n description: 'Extra directories to exclude on top of defaults (node_modules, dist, .git, build, .next, .kb, .pnpm, coverage are always excluded). Rarely needed.',\n },\n mode: {\n type: 'string',\n enum: ['auto', 'regex', 'literal'],\n description: 'Search mode: auto (default), regex, or literal',\n },\n offset: {\n type: 'number',\n description: 'Result offset for pagination (default: 0)',\n },\n limit: {\n type: 'number',\n description: `Max matches per page (default: ${DEFAULT_RESULT_LIMIT}, max: ${MAX_RESULT_LIMIT})`,\n },\n },\n required: ['pattern'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const pattern = input.pattern as string;\n const directory = (input.directory as string) || '.';\n const filePattern = input.filePattern as string | undefined;\n const extra = input.exclude as string[] | undefined;\n const excludes = extra && extra.length > 0 ? [...new Set([...DEFAULT_EXCLUDES, ...extra])] : DEFAULT_EXCLUDES;\n const mode = ((input.mode as string) || 'auto').toLowerCase();\n const { offset, limit } = normalizeOffsetLimit(input);\n\n try {\n const fullPath = path.resolve(context.workingDir, directory);\n\n const dirError = validateDirectory(context.workingDir, directory);\n if (dirError) {\n return { success: true, output: dirError };\n }\n\n const windowSize = Math.min(2000, Math.max(500, offset + limit));\n\n const buildArgs = (literal: boolean): string[] => {\n const args: string[] = ['-rIn'];\n if (literal) {args.push('-F');}\n args.push(pattern, fullPath);\n args.push(...buildGrepExcludes(excludes));\n if (filePattern) {\n args.push(`--include=${filePattern}`);\n }\n return args;\n };\n\n let output = '';\n let usedLiteralFallback = false;\n\n const runGrep = async (literal: boolean): Promise<{ stdout: string; exitCode: number; stderr: string }> => {\n const res = await execa('grep', buildArgs(literal), {\n cwd: context.workingDir,\n reject: false,\n timeout: SEARCH_TIMEOUT_MS,\n });\n return { stdout: res.stdout, exitCode: res.exitCode ?? 0, stderr: res.stderr };\n };\n\n const initial = await runGrep(mode === 'literal');\n\n if (initial.exitCode === 2) {\n // exit code 2 = grep error (e.g. invalid regex)\n const looksLikeInvalidRegex = /(unbalanced|parentheses|invalid regular expression|regular expression)/i.test(initial.stderr);\n if (looksLikeInvalidRegex && mode !== 'regex') {\n // auto mode: fall back to literal\n usedLiteralFallback = true;\n const fallback = await runGrep(true);\n output = fallback.stdout;\n if (fallback.exitCode === 2) {\n return toolError({\n code: 'SEARCH_FAILED',\n message: `Grep search failed: ${fallback.stderr}`,\n retryable: true,\n hint: 'Try mode=\"literal\" for special characters, or narrow directory.',\n details: { directory, pattern, filePattern, mode },\n });\n }\n } else {\n return toolError({\n code: 'SEARCH_FAILED',\n message: `Grep search failed: ${initial.stderr}`,\n retryable: true,\n hint: 'Try mode=\"literal\" for special characters, or narrow directory.',\n details: { directory, pattern, filePattern, mode },\n });\n }\n } else {\n // exitCode 0 = matches found, exitCode 1 = no matches (grep convention)\n output = initial.stdout;\n }\n\n const lines = output.split('\\n').filter(Boolean).slice(0, windowSize);\n\n if (lines.length === 0) {\n return {\n success: true,\n output: `No matches found for \"${pattern}\" in ${directory === '.' ? 'project root' : directory}.${filePattern ? '' : ' Try adding filePattern (e.g. \"*.ts\") to narrow the search.'}`,\n };\n }\n\n const page = paginate(lines, offset, limit);\n const excludeNote = `[Excluded: ${DEFAULT_EXCLUDES.join(', ')}${extra && extra.length > 0 ? ` + ${extra.join(', ')}` : ''}]`;\n const resultText = [\n `Found ${lines.length} match(es) for \"${pattern}\" in \"${directory}\"${filePattern ? ` (${filePattern})` : ''}${usedLiteralFallback ? ' (literal fallback)' : ''} (showing ${page.page.length}, offset=${offset}, limit=${limit})`,\n excludeNote,\n '',\n ...page.page.map(line => {\n const match = line.match(/^(.+?):(\\d+):(.+)$/);\n if (match) {\n const [, filePath, lineNum, content] = match;\n const relPath = path.relative(context.workingDir, filePath!);\n return ` ${relPath}:${lineNum}\\n ${content!.trim()}`;\n }\n return ` ${line}`;\n }),\n page.hasMore ? '' : '',\n ].filter(s => s !== undefined).join('\\n');\n\n const continuationHint = page.hasMore\n ? `Next page: grep_search(pattern=\"${pattern}\", directory=\"${directory}\", offset=${page.nextOffset}, limit=${limit})`\n : '';\n\n return {\n success: true,\n output: trimOutput(resultText, MAX_OUTPUT_CHARS, continuationHint),\n metadata: {\n totalMatches: lines.length,\n offset,\n limit,\n hasMore: page.hasMore,\n nextOffset: page.nextOffset,\n modeUsed: usedLiteralFallback ? 'literal' : mode === 'auto' ? 'regex' : mode,\n },\n };\n } catch (error) {\n if (error instanceof Error && 'killed' in error && (error as Error & { killed?: boolean }).killed) {\n return toolError({\n code: 'SEARCH_TIMEOUT',\n message: `Grep search timed out after ${SEARCH_TIMEOUT_MS / 1000}s.`,\n retryable: true,\n hint: 'Narrow directory, add filePattern, or lower limit.',\n details: { directory, pattern, timeoutMs: SEARCH_TIMEOUT_MS },\n });\n }\n if ((error as { code?: string }).code === 'ENOBUFS') {\n return toolError({\n code: 'SEARCH_BUFFER_OVERFLOW',\n message: 'Search output exceeded buffer.',\n retryable: true,\n hint: 'Narrow directory, add filePattern, or reduce limit.',\n details: { directory, pattern, filePattern, offset, limit, mode },\n });\n }\n\n return toolError({\n code: 'SEARCH_FAILED',\n message: `Grep search failed: ${error instanceof Error ? error.message : String(error)}`,\n retryable: true,\n hint: 'Try mode=\"literal\" for special characters, or narrow directory.',\n details: { directory, pattern, filePattern, mode },\n });\n }\n },\n };\n}\n\n/**\n * List files in directory\n */\nexport function createListFilesTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'list_files',\n description: 'List files and directories at a path. Good for exploring what exists.',\n parameters: {\n type: 'object',\n properties: {\n directory: {\n type: 'string',\n description: 'Directory to list (default: \".\" for current directory)',\n },\n recursive: {\n type: 'boolean',\n description: 'Include subdirectories (default: false)',\n },\n offset: {\n type: 'number',\n description: 'Result offset for pagination (default: 0)',\n },\n limit: {\n type: 'number',\n description: `Max results per page (default: ${DEFAULT_RESULT_LIMIT}, max: ${MAX_RESULT_LIMIT})`,\n },\n },\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const directory = (input.directory as string) || '.';\n const recursive = (input.recursive as boolean) || false;\n const { offset, limit } = normalizeOffsetLimit(input);\n\n try {\n const fullPath = path.resolve(context.workingDir, directory);\n\n if (recursive) {\n const args = [\n fullPath,\n '-type', 'f',\n '!', '-path', '*/node_modules/*',\n '!', '-path', '*/.git/*',\n '!', '-path', '*/dist/*',\n '!', '-path', '*/.kb/*',\n ];\n\n const result = await execa('find', args, {\n cwd: context.workingDir,\n reject: false,\n timeout: SEARCH_TIMEOUT_MS,\n });\n\n const files = result.stdout\n .split('\\n')\n .filter(Boolean)\n .slice(0, 100)\n .map(f => path.relative(context.workingDir, f));\n\n const page = paginate(files, offset, limit);\n return {\n success: true,\n output: files.length > 0\n ? `Files in ${directory} (recursive, showing ${page.page.length}/${files.length}, offset=${offset}, limit=${limit}):\\n\\n${page.page.map(f => ` ${f}`).join('\\n')}${page.hasMore ? `\\n\\nNext page: list_files(directory=\"${directory}\", recursive=true, offset=${page.nextOffset}, limit=${limit})` : ''}`\n : `No files found in ${directory}`,\n metadata: {\n totalMatches: files.length,\n offset,\n limit,\n hasMore: page.hasMore,\n nextOffset: page.nextOffset,\n },\n };\n }\n\n // Non-recursive: use fs.readdirSync to avoid shell entirely\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(fullPath, { withFileTypes: true });\n } catch {\n return {\n success: true,\n output: 'Directory not found',\n };\n }\n\n const lines = entries\n .sort((a, b) => a.name.localeCompare(b.name))\n .map(e => {\n const indicator = e.isDirectory() ? '/' : e.isSymbolicLink() ? '@' : '';\n return `${e.name}${indicator}`;\n });\n\n return {\n success: true,\n output: `Contents of ${directory}:\\n\\n${lines.join('\\n')}`,\n };\n } catch (error) {\n return {\n success: false,\n error: `List files failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n },\n };\n}\n\n/**\n * Find files containing specific code pattern (semantic search)\n * Language-agnostic - works with any programming language\n */\nexport function createFindDefinitionTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'find_definition',\n description: 'Find where a symbol (class, function, interface, type, etc.) is defined. Works with any language. Uses project root as default directory, which works well for monorepos with nested packages.',\n parameters: {\n type: 'object',\n properties: {\n name: {\n type: 'string',\n description: 'Name of the symbol to find (class, function, interface, type, struct, etc.)',\n },\n directory: {\n type: 'string',\n description: 'Directory to search in (default: \".\")',\n },\n filePattern: {\n type: 'string',\n description: 'File pattern to search (e.g., \"*.cs\" for C#, \"*.py\" for Python). If not specified, searches all source files.',\n },\n },\n required: ['name'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const name = input.name as string;\n const directory = (input.directory as string) || '.';\n const filePattern = input.filePattern as string | undefined;\n\n try {\n const fullPath = path.resolve(context.workingDir, directory);\n\n const dirError = validateDirectory(context.workingDir, directory);\n if (dirError) {\n return { success: true, output: dirError };\n }\n\n // Language-agnostic definition patterns\n const patterns = [\n // Common across languages\n `class ${name}`,\n `interface ${name}`,\n `struct ${name}`,\n `enum ${name}`,\n // TypeScript/JavaScript\n `function ${name}`,\n `const ${name}`,\n `let ${name}`,\n `var ${name}`,\n `type ${name}`,\n `export.*${name}`,\n // Python\n `def ${name}`,\n // C#/Java\n `public.*${name}`,\n `private.*${name}`,\n `protected.*${name}`,\n `static.*${name}`,\n // Go\n `func ${name}`,\n `func \\\\(.*\\\\) ${name}`,\n // Rust\n `fn ${name}`,\n `impl ${name}`,\n `trait ${name}`,\n `mod ${name}`,\n ];\n\n // Build include flags for grep\n let includeArgs: string[];\n if (filePattern) {\n includeArgs = [`--include=${filePattern}`];\n } else {\n // Default: search common source file extensions\n includeArgs = toRgIncludesArgs(ALL_SOURCE_EXTENSIONS);\n }\n\n const args = [\n '-rn', '-E',\n `(${patterns.join('|')})`,\n fullPath,\n ...includeArgs,\n ...buildGrepExcludes(DEFAULT_EXCLUDES),\n '--exclude-dir=bin',\n '--exclude-dir=obj',\n '--exclude-dir=target',\n ];\n\n const result = await execa('grep', args, {\n cwd: context.workingDir,\n reject: false,\n timeout: SEARCH_TIMEOUT_MS,\n });\n\n const lines = result.stdout.split('\\n').filter(Boolean).slice(0, 30);\n\n if (lines.length === 0) {\n return {\n success: true,\n output: `No definition found for \"${name}\" in ${directory === '.' ? 'project root' : directory}. Try: grep_search for text matching, or glob_search with \"*${name.toLowerCase()}*\" for filename matching.`,\n };\n }\n\n const resultLines = lines.map(line => {\n const match = line.match(/^(.+?):(\\d+):(.+)$/);\n if (match) {\n const [, filePath, lineNum, content] = match;\n const relPath = path.relative(context.workingDir, filePath!);\n return `${relPath}:${lineNum}\\n ${content!.trim()}`;\n }\n return line;\n });\n\n return {\n success: true,\n output: `Found definition(s) for \"${name}\":\\n\\n${resultLines.join('\\n\\n')}`,\n };\n } catch (error) {\n if (error instanceof Error && 'killed' in error && (error as Error & { killed?: boolean }).killed) {\n return {\n success: false,\n error: `Find definition timed out after ${SEARCH_TIMEOUT_MS / 1000}s. Try specifying a narrower directory.`,\n };\n }\n return {\n success: false,\n error: `Find definition failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n },\n };\n}\n\n/**\n * Get project structure overview — level-by-level exploration\n */\nexport function createProjectStructureTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'project_structure',\n description: 'Show directory contents at a given path. Defaults to project root, depth 1. Use to explore the codebase incrementally — first see top-level, then drill into specific directories.',\n parameters: {\n type: 'object',\n properties: {\n targetPath: {\n type: 'string',\n description: 'Directory to explore (default: project root). Use to drill deeper into a specific folder.',\n },\n depth: {\n type: 'number',\n description: 'How many levels deep (default: 1, max: 3)',\n },\n },\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const depth = Math.min((input.depth as number) || 1, 3);\n const targetPath = (input.targetPath as string) || '.';\n\n // Resolve and validate target path\n const resolvedPath = path.resolve(context.workingDir, targetPath);\n if (!resolvedPath.startsWith(context.workingDir)) {\n return {\n success: false,\n error: 'Cannot access paths outside project directory.',\n };\n }\n\n if (!fs.existsSync(resolvedPath) || !fs.statSync(resolvedPath).isDirectory()) {\n return {\n success: false,\n error: `\"${targetPath}\" is not a directory or does not exist.`,\n };\n }\n\n try {\n const skipNames = new Set(['node_modules', '.git', 'dist', '.next', 'build']);\n const lines: string[] = [];\n\n function listLevel(dir: string, prefix: string, currentDepth: number): void {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(dir, { withFileTypes: true });\n } catch {\n return;\n }\n\n // Separate dirs and files, sort each group\n const dirs = entries.filter(e => e.isDirectory() && !skipNames.has(e.name)).sort((a, b) => a.name.localeCompare(b.name));\n const files = entries.filter(e => e.isFile()).sort((a, b) => a.name.localeCompare(b.name));\n\n // Show directories with child counts\n for (const d of dirs) {\n const fullPath = path.join(dir, d.name);\n let childDirs = 0;\n let childFiles = 0;\n try {\n const children = fs.readdirSync(fullPath, { withFileTypes: true });\n childDirs = children.filter(c => c.isDirectory() && !skipNames.has(c.name)).length;\n childFiles = children.filter(c => c.isFile()).length;\n } catch {\n // inaccessible\n }\n const info = `${childDirs} dirs, ${childFiles} files`;\n lines.push(`${prefix}${d.name}/ (${info})`);\n\n if (currentDepth < depth) {\n listLevel(fullPath, prefix + ' ', currentDepth + 1);\n }\n }\n\n // Show files (only at requested depth, not intermediate levels for brevity)\n if (currentDepth === 1 || depth === 1) {\n for (const f of files) {\n lines.push(`${prefix}${f.name}`);\n }\n }\n }\n\n listLevel(resolvedPath, '', 1);\n\n const relPath = path.relative(context.workingDir, resolvedPath) || '.';\n const header = `${relPath}/ (depth ${depth})`;\n\n return {\n success: true,\n output: `${header}\\n\\n${lines.join('\\n')}`,\n };\n } catch (error) {\n return {\n success: false,\n error: `Project structure failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n },\n };\n}\n\n/**\n * Count lines of code - language agnostic\n */\nexport function createCodeStatsTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'code_stats',\n description: 'Get line counts and file counts by extension for a directory scope (not single-file line counts).',\n parameters: {\n type: 'object',\n properties: {\n directory: {\n type: 'string',\n description: 'Directory to analyze (default: \".\"). If a file path is provided by mistake, use its parent directory.',\n },\n extensions: {\n type: 'string',\n description: 'Comma-separated list of extensions to count (e.g., \"ts,tsx,js\" or \"cs,csproj\" or \"py\"). If not specified, counts all source files.',\n },\n offset: {\n type: 'number',\n description: 'Offset for extension summary rows (default: 0)',\n },\n limit: {\n type: 'number',\n description: `Rows per page for extension summary (default: ${DEFAULT_RESULT_LIMIT}, max: ${MAX_RESULT_LIMIT})`,\n },\n },\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const directory = (input.directory as string) || '.';\n const extensionsInput = input.extensions as string | undefined;\n const { offset, limit } = normalizeOffsetLimit(input);\n\n try {\n const fullPath = path.resolve(context.workingDir, directory);\n\n const dirError = validateDirectory(context.workingDir, directory);\n if (dirError) {\n return { success: true, output: dirError };\n }\n\n // Build extension filter args\n let extFilterArgs: string[];\n if (extensionsInput) {\n const exts = extensionsInput.split(',').map(e => e.trim());\n extFilterArgs = toFindNamesArgs(exts);\n } else {\n extFilterArgs = toFindNamesArgs(ALL_SOURCE_EXTENSIONS);\n }\n\n const commonExcludes = [\n '!', '-path', '*/node_modules/*',\n '!', '-path', '*/dist/*',\n '!', '-path', '*/.git/*',\n '!', '-path', '*/bin/*',\n '!', '-path', '*/obj/*',\n '!', '-path', '*/target/*',\n '!', '-path', '*/__pycache__/*',\n ];\n\n // Find matching files (used as base for all three queries)\n const findArgs = [\n fullPath,\n '-type', 'f',\n '(',\n ...extFilterArgs,\n ')',\n ...commonExcludes,\n ];\n\n const findResult = await execa('find', findArgs, {\n cwd: context.workingDir,\n reject: false,\n timeout: SEARCH_TIMEOUT_MS,\n });\n\n const filePaths = findResult.stdout.split('\\n').filter(Boolean);\n\n // Count total files\n const fileCount = filePaths.length;\n\n // Count by extension using JS\n const extCounts = new Map<string, number>();\n for (const fp of filePaths) {\n const ext = fp.includes('.') ? fp.split('.').pop()! : '(no ext)';\n extCounts.set(ext, (extCounts.get(ext) ?? 0) + 1);\n }\n const countByExt = [...extCounts.entries()]\n .sort((a, b) => b[1] - a[1])\n .slice(0, 200)\n .map(([ext, count]) => ` ${count} ${ext}`);\n\n // Count total lines using wc -l on found files (batch call)\n let totalOutput = '0 total';\n if (filePaths.length > 0) {\n const wcResult = await execa('wc', ['-l', ...filePaths], {\n cwd: context.workingDir,\n reject: false,\n });\n // wc -l outputs a total line at the end when given multiple files\n const wcLines = wcResult.stdout.trim().split('\\n').filter(Boolean);\n const lastLine = wcLines[wcLines.length - 1] ?? '';\n totalOutput = lastLine.trim();\n }\n\n const page = paginate(countByExt, offset, limit);\n return {\n success: true,\n output: `Code statistics for directory ${directory}:\\n\\nTotal lines: ${totalOutput}\\nTotal files: ${fileCount}\\n\\nFiles by extension (showing ${page.page.length}/${countByExt.length}, offset=${offset}, limit=${limit}):\\n${page.page.join('\\n')}${page.hasMore ? `\\n\\nNext page: code_stats(directory=\"${directory}\", offset=${page.nextOffset}, limit=${limit})` : ''}\\n\\nNote: This is directory-level aggregate. For a single file line count, use fs_read on that file and rely on metadata.totalLines.`,\n metadata: {\n totalExtensionRows: countByExt.length,\n offset,\n limit,\n hasMore: page.hasMore,\n nextOffset: page.nextOffset,\n },\n };\n } catch (error) {\n return toolError({\n code: 'CODE_STATS_FAILED',\n message: `Code stats failed: ${error instanceof Error ? error.message : String(error)}`,\n retryable: true,\n hint: 'Narrow directory or provide extensions.',\n details: { directory, extensions: extensionsInput },\n });\n }\n },\n };\n}\n","/**\n * Memory tools for persistent context and session management\n *\n * ARCHITECTURE:\n * - Shared memory (.kb/memory/shared/) - persistent across sessions\n * - preferences: user preferences (e.g., \"use TypeScript strict mode\")\n * - constraints: project rules (e.g., \"never modify /legacy/\")\n *\n * - Session memory (.kb/memory/session-xxx/) - handled by FileMemory\n * - corrections: user corrections for current session\n * - findings: agent discoveries\n * - blockers: current blockers\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { Tool, ToolContext } from '../../types.js';\nimport type { MemoryEntry, SessionEntry } from '@kb-labs/agent-contracts';\n\n/**\n * Shared memory structure (persistent)\n */\ninterface SharedMemory {\n preferences: MemoryEntry[];\n constraints: MemoryEntry[];\n sessions: SessionEntry[];\n projectContext: {\n name: string;\n description: string;\n technologies: string[];\n structure: string;\n };\n}\n\n/**\n * Get memory file path\n * Uses .kb/memory/shared/ for cross-session persistent memory\n */\nfunction getMemoryPath(context: ToolContext): string {\n // Use .kb/memory/shared/ for persistent memory across sessions\n const memoryDir = path.join(context.workingDir, '.kb', 'memory', 'shared');\n if (!fs.existsSync(memoryDir)) {\n fs.mkdirSync(memoryDir, { recursive: true });\n }\n return path.join(memoryDir, 'memory.json');\n}\n\n/**\n * Load shared memory from disk\n */\nfunction loadSharedMemory(context: ToolContext): SharedMemory {\n const memoryPath = getMemoryPath(context);\n\n const defaultMemory: SharedMemory = {\n preferences: [],\n constraints: [],\n sessions: [],\n projectContext: {\n name: '',\n description: '',\n technologies: [],\n structure: '',\n },\n };\n\n if (!fs.existsSync(memoryPath)) {\n return defaultMemory;\n }\n\n try {\n const content = fs.readFileSync(memoryPath, 'utf-8');\n const parsed = JSON.parse(content);\n\n // Migration: convert old format (facts array) to new format\n if (parsed.facts && Array.isArray(parsed.facts)) {\n const preferences = parsed.facts.filter((f: MemoryEntry) => f.type === 'user_preference');\n const constraints = parsed.facts.filter((f: MemoryEntry) => f.type === 'constraint');\n return {\n preferences,\n constraints,\n sessions: parsed.sessions || [],\n projectContext: parsed.projectContext || defaultMemory.projectContext,\n };\n }\n\n return {\n ...defaultMemory,\n ...parsed,\n };\n } catch {\n return defaultMemory;\n }\n}\n\n/**\n * Save shared memory to disk\n */\nfunction saveSharedMemory(context: ToolContext, memory: SharedMemory): void {\n const memoryPath = getMemoryPath(context);\n fs.writeFileSync(memoryPath, JSON.stringify(memory, null, 2), 'utf-8');\n}\n\nasync function loadCanonicalSessionMemory(context: ToolContext): Promise<{\n constraints: string[];\n corrections: string[];\n}> {\n if (!context.sessionMemory) {\n return { constraints: [], corrections: [] };\n }\n\n const kernel = await context.sessionMemory.loadKernelState();\n if (!kernel) {\n return { constraints: [], corrections: [] };\n }\n\n return {\n constraints: kernel.constraints,\n corrections: kernel.memory.corrections.map((item) => item.content),\n };\n}\n\n/**\n * Get shared memory (preferences, constraints, project context)\n */\nexport function createMemoryGetTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'memory_get',\n description:\n 'Get stored user preferences, project constraints, and session history.',\n parameters: {\n type: 'object',\n properties: {\n sessionId: {\n type: 'string',\n description: 'Optional session ID to get specific session context',\n },\n },\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const sessionId = input.sessionId as string | undefined;\n const memory = loadSharedMemory(context);\n const canonicalSession = await loadCanonicalSessionMemory(context);\n\n // Format preferences\n const preferencesText =\n memory.preferences.length > 0\n ? memory.preferences.map((p) => `- ${p.content}`).join('\\n')\n : 'No preferences set';\n\n // Format constraints\n const constraintsText =\n memory.constraints.length > 0\n ? memory.constraints.map((c) => `- ${c.content}`).join('\\n')\n : 'No constraints set';\n\n const sessionConstraintsText =\n canonicalSession.constraints.length > 0\n ? canonicalSession.constraints.map((item) => `- ${item}`).join('\\n')\n : 'No session constraints set';\n\n const sessionCorrectionsText =\n canonicalSession.corrections.length > 0\n ? canonicalSession.corrections.map((item) => `- ${item}`).join('\\n')\n : 'No session corrections recorded';\n\n // Format sessions\n const sessions = sessionId\n ? memory.sessions.filter((s) => s.sessionId === sessionId)\n : memory.sessions.slice(-5);\n\n const sessionInfo = sessions\n .map((s) => {\n const tasks = s.tasks.join(', ');\n return `Session ${s.sessionId} (${s.timestamp}):\\n Tasks: ${tasks}\\n Learnings: ${s.learnings}`;\n })\n .join('\\n\\n');\n\n const output = [\n '=== Shared Memory ===',\n '',\n '## 👤 User Preferences (persistent)',\n preferencesText,\n '',\n '## 🚫 Constraints (persistent)',\n constraintsText,\n '',\n '## Session Constraints (canonical)',\n sessionConstraintsText,\n '',\n '## Session Corrections (canonical)',\n sessionCorrectionsText,\n '',\n '## Project Context',\n `Name: ${memory.projectContext.name || 'Unknown'}`,\n `Description: ${memory.projectContext.description || 'N/A'}`,\n `Technologies: ${memory.projectContext.technologies.join(', ') || 'N/A'}`,\n '',\n '## Session History',\n sessionInfo || 'No sessions yet',\n '',\n '---',\n 'Note: Corrections, findings, and blockers are stored in session memory.',\n ].join('\\n');\n\n return {\n success: true,\n output,\n };\n },\n };\n}\n\n/**\n * Add user preference to shared memory (persistent)\n */\nexport function createMemoryPreferenceTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'memory_preference',\n description:\n 'Store a persistent user preference (coding style, tool choices, etc.).',\n parameters: {\n type: 'object',\n properties: {\n content: {\n type: 'string',\n description: 'The preference to store (e.g., \"Always use TypeScript strict mode\")',\n },\n tags: {\n type: 'array',\n items: { type: 'string' },\n description: 'Optional tags for categorization (e.g., [\"typescript\", \"style\"])',\n },\n },\n required: ['content'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const content = input.content as string;\n const tags = input.tags as string[] | undefined;\n\n const memory = loadSharedMemory(context);\n\n const preference: MemoryEntry = {\n content,\n category: 'user_input',\n timestamp: new Date().toISOString(),\n type: 'user_preference',\n metadata: {\n importance: 0.9,\n source: 'user',\n scope: 'project',\n tags,\n },\n };\n\n memory.preferences.push(preference);\n\n // Keep only last 50 preferences\n if (memory.preferences.length > 50) {\n memory.preferences = memory.preferences.slice(-50);\n }\n\n saveSharedMemory(context, memory);\n\n return {\n success: true,\n output: `👤 Preference stored: ${content}`,\n };\n },\n };\n}\n\n/**\n * Add constraint to shared memory (persistent)\n */\nexport function createMemoryConstraintTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'memory_constraint',\n description:\n 'Store a persistent project constraint or rule. Use this for durable project-wide rules, not session-only instructions.',\n parameters: {\n type: 'object',\n properties: {\n content: {\n type: 'string',\n description: 'The constraint (e.g., \"Do not modify files in /legacy/ directory\")',\n },\n },\n required: ['content'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const content = input.content as string;\n\n if (context.sessionMemory) {\n await context.sessionMemory.recordConstraint(content);\n }\n\n const memory = loadSharedMemory(context);\n\n const constraint: MemoryEntry = {\n content,\n category: 'project_rules',\n timestamp: new Date().toISOString(),\n type: 'constraint',\n metadata: {\n importance: 1.0,\n source: 'user',\n scope: 'project',\n },\n };\n\n memory.constraints.push(constraint);\n\n // Keep only last 50 constraints\n if (memory.constraints.length > 50) {\n memory.constraints = memory.constraints.slice(-50);\n }\n\n saveSharedMemory(context, memory);\n\n return {\n success: true,\n output: `🚫 Constraint stored: ${content}`,\n };\n },\n };\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Session Memory Tools - corrections, findings, blockers (session-scoped)\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Get session memory directory path\n * Creates directory if it doesn't exist\n */\nfunction getSessionMemoryPath(context: ToolContext, sessionId?: string): string {\n const id = sessionId || `session-${Date.now()}`;\n const sessionDir = path.join(context.workingDir, '.kb', 'memory', id);\n if (!fs.existsSync(sessionDir)) {\n fs.mkdirSync(sessionDir, { recursive: true });\n }\n return sessionDir;\n}\n\n/**\n * Save entry to session memory\n */\nfunction saveToSession(context: ToolContext, entry: MemoryEntry, sessionId?: string): void {\n const sessionDir = getSessionMemoryPath(context, sessionId);\n const entryId = `mem-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;\n const filePath = path.join(sessionDir, `${entryId}.json`);\n fs.writeFileSync(filePath, JSON.stringify({ ...entry, id: entryId }, null, 2), 'utf-8');\n}\n\n/**\n * Add user correction to session memory\n * Session-scoped - only valid for current session\n */\nexport function createMemoryCorrectionTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'memory_correction',\n description:\n 'Store a user correction for the current session. Use this immediately after the user corrects you or changes active instructions. Set constraint=true if the correction should remain an active session constraint.',\n parameters: {\n type: 'object',\n properties: {\n content: {\n type: 'string',\n description:\n 'The correction (e.g., \"AuthService is in packages/auth/, not src/services/\")',\n },\n supersedes: {\n type: 'string',\n description: 'Optional: what this correction replaces',\n },\n invalidates: {\n type: 'array',\n items: { type: 'string' },\n description: 'Optional: assumption IDs invalidated by this correction',\n },\n constraint: {\n type: 'boolean',\n description: 'Set true if this correction should also become an active session constraint',\n },\n sessionId: {\n type: 'string',\n description: 'Optional: session ID (defaults to current timestamp-based session)',\n },\n },\n required: ['content'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const content = input.content as string;\n const supersedes = input.supersedes as string | undefined;\n const invalidates = Array.isArray(input.invalidates)\n ? input.invalidates.filter((item): item is string => typeof item === 'string' && item.trim().length > 0)\n : [];\n const asConstraint = input.constraint === true;\n const sessionId = input.sessionId as string | undefined;\n\n if (context.sessionMemory) {\n await context.sessionMemory.recordCorrection({\n content,\n invalidates,\n asConstraint,\n });\n }\n\n const correction: MemoryEntry = {\n content,\n category: 'user_input',\n timestamp: new Date().toISOString(),\n type: 'user_correction',\n metadata: {\n importance: 1.0,\n source: 'user',\n supersedes,\n scope: 'session',\n },\n };\n\n saveToSession(context, correction, sessionId);\n\n const supersedesInfo = supersedes ? ` (replaces: ${supersedes})` : '';\n const constraintInfo = asConstraint ? ' [active session constraint]' : '';\n return {\n success: true,\n output: `⚠️ Correction stored in session${supersedesInfo}${constraintInfo}: ${content}`,\n };\n },\n };\n}\n\n/**\n * Add finding to session memory\n */\nexport function createMemoryFindingTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'memory_finding',\n description:\n 'Store a codebase finding with confidence level (session-scoped).',\n parameters: {\n type: 'object',\n properties: {\n content: {\n type: 'string',\n description: 'The finding (e.g., \"All services use Repository pattern\")',\n },\n confidence: {\n type: 'number',\n description: 'Confidence level 0-1 (e.g., 0.9 for high confidence)',\n },\n sources: {\n type: 'array',\n items: { type: 'string' },\n description: 'Source files that support this finding',\n },\n sessionId: {\n type: 'string',\n description: 'Optional: session ID',\n },\n },\n required: ['content', 'confidence'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const content = input.content as string;\n const confidence = input.confidence as number;\n const sources = input.sources as string[] | undefined;\n const sessionId = input.sessionId as string | undefined;\n\n const finding: MemoryEntry = {\n content,\n category: 'learning',\n timestamp: new Date().toISOString(),\n type: 'finding',\n metadata: {\n importance: confidence,\n confidence,\n source: 'agent',\n tags: sources,\n scope: 'session',\n },\n };\n\n saveToSession(context, finding, sessionId);\n\n return {\n success: true,\n output: `🔍 Finding stored (confidence: ${(confidence * 100).toFixed(0)}%): ${content}`,\n };\n },\n };\n}\n\n/**\n * Add blocker to session memory\n */\nexport function createMemoryBlockerTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'memory_blocker',\n description:\n 'Store a blocker that prevents progress (session-scoped).',\n parameters: {\n type: 'object',\n properties: {\n content: {\n type: 'string',\n description: 'The blocker (e.g., \"Cannot find database config. Need DATABASE_URL\")',\n },\n taskId: {\n type: 'string',\n description: 'Optional: related task ID',\n },\n sessionId: {\n type: 'string',\n description: 'Optional: session ID',\n },\n },\n required: ['content'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const content = input.content as string;\n const taskId = input.taskId as string | undefined;\n const sessionId = input.sessionId as string | undefined;\n\n const blocker: MemoryEntry = {\n content,\n category: 'agent_state',\n timestamp: new Date().toISOString(),\n type: 'blocker',\n metadata: {\n importance: 1.0,\n source: 'agent',\n taskId,\n scope: 'session',\n },\n };\n\n saveToSession(context, blocker, sessionId);\n\n return {\n success: true,\n output: `🛑 Blocker stored: ${content}`,\n };\n },\n };\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Session Summary Tool\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Save session summary (shared)\n */\nexport function createSessionSaveTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'session_save',\n description:\n 'Save session summary and learnings to persistent memory.',\n parameters: {\n type: 'object',\n properties: {\n sessionId: {\n type: 'string',\n description: 'Session identifier',\n },\n tasks: {\n type: 'array',\n items: { type: 'string' },\n description: 'List of tasks completed in this session',\n },\n learnings: {\n type: 'string',\n description: 'Summary of what was learned or discovered',\n },\n },\n required: ['sessionId', 'tasks', 'learnings'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const sessionId = input.sessionId as string;\n const tasks = input.tasks as string[];\n const learnings = input.learnings as string;\n\n const memory = loadSharedMemory(context);\n\n const session: SessionEntry = {\n sessionId,\n timestamp: new Date().toISOString(),\n tasks,\n learnings,\n };\n\n memory.sessions.push(session);\n\n // Keep only last 50 sessions\n if (memory.sessions.length > 50) {\n memory.sessions = memory.sessions.slice(-50);\n }\n\n saveSharedMemory(context, memory);\n\n return {\n success: true,\n output: `Session ${sessionId} saved with ${tasks.length} task(s)`,\n };\n },\n };\n}\n","/**\n * archive_recall tool - Retrieve full content from previously-read files\n * or tool outputs WITHOUT re-reading them.\n *\n * This is the agent's interface to Tier 2 (Cold Storage / ArchiveMemory).\n */\n\nimport type { ToolResult } from '@kb-labs/agent-contracts';\nimport type { Tool, ToolContext } from '../../types.js';\n\nexport function createArchiveRecallTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'archive_recall',\n description:\n 'Retrieve full content from previously-read files or tool outputs WITHOUT re-reading them. ' +\n 'Use this to recall file contents, grep results, or any tool output from earlier iterations. ' +\n 'Specify exactly one query mode: file_path, keyword, list_files, tool_name, or iteration.',\n parameters: {\n type: 'object',\n properties: {\n file_path: {\n type: 'string',\n description: 'Recall the last read of this file (full content)',\n },\n keyword: {\n type: 'string',\n description: 'Search across all archived outputs for this keyword',\n },\n list_files: {\n type: 'boolean',\n description: 'List all file paths that have been archived',\n },\n tool_name: {\n type: 'string',\n description: 'Recall recent outputs of a specific tool (e.g., grep_search)',\n },\n iteration: {\n type: 'number',\n description: 'Recall all tool outputs from a specific iteration number',\n },\n limit: {\n type: 'number',\n description: 'Maximum number of results to return (default: 5)',\n },\n },\n },\n },\n },\n executor: async (input: Record<string, unknown>): Promise<ToolResult> => {\n const archive = context.archiveMemory;\n if (!archive) {\n return {\n success: false,\n error: 'Archive memory not available. This tool requires the two-tier memory system.',\n };\n }\n\n const limit = (input.limit as number) || 5;\n\n // Mode 1: Recall file content\n if (input.file_path) {\n const filePath = input.file_path as string;\n const entry = archive.recallByFilePath(filePath);\n if (!entry) {\n return {\n success: false,\n output: `File not found in archive: ${filePath}\\n\\nArchived files:\\n${archive.getArchivedFilePaths().join('\\n') || '(none)'}`,\n };\n }\n return {\n success: true,\n output: `[Archive] File: ${filePath} (read in iteration ${entry.iteration} via ${entry.toolName})\\n\\n${entry.fullOutput}`,\n };\n }\n\n // Mode 2: Keyword search\n if (input.keyword) {\n const keyword = input.keyword as string;\n const results = archive.search(keyword, limit);\n if (results.length === 0) {\n return {\n success: true,\n output: `No archived outputs contain \"${keyword}\"`,\n };\n }\n const formatted = results\n .map((r, i) => {\n const fileInfo = r.filePath ? ` (file: ${r.filePath})` : '';\n const preview = r.fullOutput.length > 500\n ? r.fullOutput.substring(0, 500) + `\\n... (${r.fullOutput.length} chars total)`\n : r.fullOutput;\n return `--- Result ${i + 1}: ${r.toolName} @ iter ${r.iteration}${fileInfo} ---\\n${preview}`;\n })\n .join('\\n\\n');\n return {\n success: true,\n output: `[Archive] Found ${results.length} result(s) for \"${keyword}\":\\n\\n${formatted}`,\n };\n }\n\n // Mode 3: List files\n if (input.list_files) {\n const files = archive.getArchivedFilePaths();\n if (files.length === 0) {\n return { success: true, output: 'No files archived yet.' };\n }\n return {\n success: true,\n output: `[Archive] ${files.length} file(s) archived:\\n${files.join('\\n')}`,\n };\n }\n\n // Mode 4: By tool name\n if (input.tool_name) {\n const toolName = input.tool_name as string;\n const results = archive.recallByToolName(toolName, limit);\n if (results.length === 0) {\n return {\n success: true,\n output: `No archived outputs for tool \"${toolName}\"`,\n };\n }\n const formatted = results\n .map((r, i) => {\n const fileInfo = r.filePath ? ` (file: ${r.filePath})` : '';\n const preview = r.fullOutput.length > 500\n ? r.fullOutput.substring(0, 500) + `\\n... (${r.fullOutput.length} chars total)`\n : r.fullOutput;\n return `--- ${toolName} #${i + 1} @ iter ${r.iteration}${fileInfo} ---\\n${preview}`;\n })\n .join('\\n\\n');\n return {\n success: true,\n output: `[Archive] ${results.length} output(s) from \"${toolName}\":\\n\\n${formatted}`,\n };\n }\n\n // Mode 5: By iteration\n if (input.iteration !== undefined) {\n const iteration = input.iteration as number;\n const results = archive.recallByIteration(iteration);\n if (results.length === 0) {\n return {\n success: true,\n output: `No archived outputs from iteration ${iteration}`,\n };\n }\n const formatted = results\n .map((r, i) => {\n const fileInfo = r.filePath ? ` (file: ${r.filePath})` : '';\n const preview = r.fullOutput.length > 500\n ? r.fullOutput.substring(0, 500) + `\\n... (${r.fullOutput.length} chars total)`\n : r.fullOutput;\n return `--- ${r.toolName} #${i + 1}${fileInfo} ---\\n${preview}`;\n })\n .join('\\n\\n');\n return {\n success: true,\n output: `[Archive] ${results.length} output(s) from iteration ${iteration}:\\n\\n${formatted}`,\n };\n }\n\n return {\n success: false,\n error: 'Specify at least one query parameter: file_path, keyword, list_files, tool_name, or iteration',\n };\n },\n };\n}\n","/**\n * TODO tools for task planning and progress tracking\n */\n\nimport type { Tool, ToolContext } from '../../types.js';\nimport type { TodoList, TodoItem } from '@kb-labs/agent-contracts';\nimport { toolError } from '../shared/tool-error.js';\nimport { TODO_CONFIG } from '../../config.js';\n\n// In-memory TODO storage (session-scoped)\nconst todoLists = new Map<string, TodoList>();\nconst TODO_CACHE_PREFIX = TODO_CONFIG.cachePrefix;\nconst TODO_CACHE_TTL_MS = TODO_CONFIG.cacheTtlMs;\n\n/**\n * Get a summary of the todo list for a session.\n * Used by Status Block (FactSheetMiddleware) to display todo progress.\n */\nexport function getTodoSummary(sessionId: string): { completed: number; total: number; inProgress: number; pending: number; blocked: number } | null {\n const list = todoLists.get(sessionId);\n if (!list || list.items.length === 0) {return null;}\n return {\n completed: list.items.filter(i => i.status === 'completed').length,\n inProgress: list.items.filter(i => i.status === 'in-progress').length,\n pending: list.items.filter(i => i.status === 'pending').length,\n blocked: list.items.filter(i => i.status === 'blocked').length,\n total: list.items.length,\n };\n}\n\nfunction getTodoCacheKey(sessionId: string): string {\n return `${TODO_CACHE_PREFIX}${sessionId}`;\n}\n\nasync function loadTodoList(context: ToolContext, sessionId: string): Promise<TodoList | null> {\n if (context.cache) {\n const cached = await context.cache.get<TodoList>(getTodoCacheKey(sessionId));\n if (cached) {\n todoLists.set(sessionId, cached);\n return cached;\n }\n }\n return todoLists.get(sessionId) ?? null;\n}\n\nasync function persistTodoList(context: ToolContext, todoList: TodoList): Promise<void> {\n todoLists.set(todoList.sessionId, todoList);\n if (context.cache) {\n await context.cache.set(getTodoCacheKey(todoList.sessionId), todoList, TODO_CACHE_TTL_MS);\n }\n}\n\nfunction resolveTodoItem(todoList: TodoList, sessionId: string, itemId: string): TodoItem | null {\n const direct = todoList.items.find((i) => i.id === itemId);\n if (direct) {\n return direct;\n }\n\n const asIndex = Number(itemId);\n if (Number.isFinite(asIndex) && asIndex >= 1) {\n const indexed = todoList.items.find((i) => i.id === `${sessionId}-${Math.floor(asIndex)}`);\n if (indexed) {\n return indexed;\n }\n }\n\n const normalized = itemId.trim().toLowerCase();\n if (!normalized) {\n return null;\n }\n const descriptionMatches = todoList.items.filter(\n (i) => i.description.toLowerCase().includes(normalized)\n );\n if (descriptionMatches.length === 1) {\n return descriptionMatches[0]!;\n }\n\n return null;\n}\n\n/**\n * Create TODO list with tasks\n */\nexport function createTodoCreateTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'todo_create',\n description: 'Create a TODO list to track task progress. Optional - use if helpful for planning complex tasks.',\n parameters: {\n type: 'object',\n properties: {\n sessionId: {\n type: 'string',\n description: 'Session identifier to associate TODO list',\n },\n items: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n description: {\n type: 'string',\n description: 'Task description',\n },\n priority: {\n type: 'string',\n enum: ['low', 'medium', 'high'],\n description: 'Task priority',\n },\n },\n required: ['description'],\n },\n description: 'List of tasks',\n },\n },\n required: ['sessionId', 'items'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const sessionId = input.sessionId as string;\n const items = input.items as Array<{\n description: string;\n priority?: 'low' | 'medium' | 'high';\n }>;\n\n const todoItems: TodoItem[] = items.map((item, index) => ({\n id: `${sessionId}-${index + 1}`,\n description: item.description,\n status: 'pending',\n priority: item.priority || 'medium',\n createdAt: new Date().toISOString(),\n }));\n\n const todoList: TodoList = {\n sessionId,\n items: todoItems,\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n };\n\n await persistTodoList(context, todoList);\n\n const output = [\n `TODO list created for session: ${sessionId}`,\n '',\n ...todoItems.map(\n (item, i) => `${i + 1}. [ ] ${item.description} (${item.priority})`\n ),\n ].join('\\n');\n\n return {\n success: true,\n output,\n metadata: {\n uiHint: 'todo',\n structured: { todoList },\n },\n };\n },\n };\n}\n\n/**\n * Update TODO item status\n */\nexport function createTodoUpdateTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'todo_update',\n description: 'Update status of a TODO item. Use to mark tasks as in-progress or completed.',\n parameters: {\n type: 'object',\n properties: {\n sessionId: {\n type: 'string',\n description: 'Session identifier',\n },\n itemId: {\n type: 'string',\n description: 'TODO item ID to update',\n },\n status: {\n type: 'string',\n enum: ['pending', 'in-progress', 'completed', 'blocked'],\n description: 'New status',\n },\n notes: {\n type: 'string',\n description: 'Optional notes about the update',\n },\n },\n required: ['sessionId', 'itemId', 'status'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const sessionId = input.sessionId as string;\n const itemId = input.itemId as string;\n const status = input.status as TodoItem['status'];\n const notes = input.notes as string | undefined;\n\n const todoList = await loadTodoList(context, sessionId);\n\n if (!todoList) {\n return toolError({\n code: 'TODO_LIST_NOT_FOUND',\n message: `No TODO list found for session: ${sessionId}`,\n retryable: true,\n hint: 'Call todo_create first, then todo_update.',\n details: { sessionId },\n });\n }\n\n const item = resolveTodoItem(todoList, sessionId, itemId);\n\n if (!item) {\n return toolError({\n code: 'TODO_ITEM_NOT_FOUND',\n message: `TODO item not found: ${itemId}`,\n retryable: true,\n hint: 'Use todo_get to list valid item IDs, then retry with exact itemId.',\n details: {\n sessionId,\n itemId,\n knownIds: todoList.items.map((i) => i.id),\n },\n });\n }\n\n item.status = status;\n item.updatedAt = new Date().toISOString();\n\n if (notes) {\n item.notes = notes;\n }\n\n todoList.updatedAt = new Date().toISOString();\n await persistTodoList(context, todoList);\n\n const statusIcon =\n status === 'completed'\n ? '✓'\n : status === 'in-progress'\n ? '⏳'\n : status === 'blocked'\n ? '🚫'\n : ' ';\n\n const updatedList = await loadTodoList(context, sessionId);\n return {\n success: true,\n output: `[${statusIcon}] ${item.description} → ${status}${notes ? `\\n Note: ${notes}` : ''}`,\n metadata: {\n uiHint: 'todo',\n structured: { todoList: updatedList },\n },\n };\n },\n };\n}\n\n/**\n * Get TODO list status\n */\nexport function createTodoGetTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'todo_get',\n description: 'Get current TODO list with task statuses. Use to check progress.',\n parameters: {\n type: 'object',\n properties: {\n sessionId: {\n type: 'string',\n description: 'Session identifier',\n },\n },\n required: ['sessionId'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const sessionId = input.sessionId as string;\n\n const todoList = await loadTodoList(context, sessionId);\n\n if (!todoList) {\n return toolError({\n code: 'TODO_LIST_NOT_FOUND',\n message: `No TODO list found for session: ${sessionId}`,\n retryable: true,\n hint: 'Create a TODO list with todo_create before calling todo_get.',\n details: { sessionId },\n });\n }\n\n const completed = todoList.items.filter(i => i.status === 'completed')\n .length;\n const total = todoList.items.length;\n\n const output = [\n `TODO List for ${sessionId} (${completed}/${total} completed)`,\n '',\n ...todoList.items.map(item => {\n const icon =\n item.status === 'completed'\n ? '✓'\n : item.status === 'in-progress'\n ? '⏳'\n : item.status === 'blocked'\n ? '🚫'\n : ' ';\n return `[${icon}] ${item.description} (${item.priority})${item.notes ? `\\n ${item.notes}` : ''}`;\n }),\n ].join('\\n');\n\n return {\n success: true,\n output,\n metadata: {\n uiHint: 'todo',\n structured: { todoList },\n },\n };\n },\n };\n}\n","/**\n * plan_validate tool — LLM-based plan quality gate.\n *\n * Called by the plan-writer agent after drafting a plan to get structured\n * feedback before reporting it as ready. The LLM evaluator receives:\n * - The original user task (so it can judge relevance)\n * - The full plan markdown\n * - The requested evaluation tier (default: small)\n *\n * Returns a human+agent-readable string with:\n * - passed: yes/no\n * - score: 0.0–1.0\n * - Per-dimension breakdown (specificity, actionability, completeness, verification)\n * - Concrete, actionable feedback for each failing dimension\n *\n * The agent uses this output to decide:\n * 1. passed=yes → call report() with the plan\n * 2. passed=no → revise the plan based on feedback and call plan_validate again\n * 3. After 3 failed attempts → call ask_user() with the plan + issues\n */\n\nimport type { Tool, ToolContext } from '../../types.js';\nimport { useLLM } from '@kb-labs/sdk';\n\nconst EVAL_SYSTEM_PROMPT = `You are a plan quality evaluator. Evaluate implementation plans written by AI agents.\n\nYou will receive the original user task and the plan markdown.\n\nScore the plan on four dimensions (0.0–1.0 each):\n\n**specificity** (weight 0.30)\n- Does the plan reference real file paths from the codebase?\n- Are function names, class names, or line numbers mentioned where relevant?\n- For simple tasks (1-2 files), mentioning those files is sufficient for a high score.\n- For complex tasks (many files), more paths are expected.\n\n**actionability** (weight 0.35)\n- Can each step be executed without guessing what to do?\n- Steps should contain: what file to edit, what to change, or what command to run.\n- \"Edit X to add Y\" is actionable. \"Update the configuration\" is not.\n\n**completeness** (weight 0.15)\n- Does the plan have: task description, steps, verification?\n- Are sections substantive (not just headings)?\n\n**verification** (weight 0.20)\n- Does the plan include concrete commands to verify correctness?\n- At least one build or test command expected.\n\nRespond in EXACTLY this format (no other text before or after):\nSCORE: 0.XX\nSPECIFICITY: 0.XX\nACTIONABILITY: 0.XX\nCOMPLETENESS: 0.XX\nVERIFICATION: 0.XX\nFEEDBACK:\n<One paragraph per dimension scoring below 0.7. Quote the weak part, explain the problem, give a fix example. If all dimensions ≥ 0.7, write \"Plan meets quality threshold.\">\n\nIMPORTANT: Only output the format above. Do NOT output tool calls, code blocks, or any other format.`;\n\n/**\n * Build the evaluation user message.\n */\nfunction buildEvalPrompt(task: string, planMarkdown: string): string {\n return `## Original user task\n\n${task}\n\n## Plan to evaluate\n\n${planMarkdown}`;\n}\n\n/**\n * Parse the LLM response into a structured result string for the agent.\n * If parsing fails, returns the raw response — the agent can still read it.\n */\nconst PASS_THRESHOLD = 0.55;\n\nfunction formatResult(raw: string, tier: string): string {\n const lines = raw.split('\\n');\n const get = (key: string): string => {\n const line = lines.find(l => l.toUpperCase().startsWith(key.toUpperCase() + ':'));\n return line?.slice(line.indexOf(':') + 1).trim() ?? '';\n };\n\n const specificity = parseFloat(get('SPECIFICITY') || '0');\n const actionability = parseFloat(get('ACTIONABILITY') || '0');\n const completeness = parseFloat(get('COMPLETENESS') || '0');\n const verification = parseFloat(get('VERIFICATION') || '0');\n\n // Compute composite score ourselves — don't trust LLM's SCORE or PASSED fields\n const composite = specificity * 0.30 + actionability * 0.35 + completeness * 0.15 + verification * 0.20;\n const passed = composite >= PASS_THRESHOLD;\n\n // If all dimensions parsed as 0, the LLM likely hallucinated (wrong format)\n if (specificity === 0 && actionability === 0 && completeness === 0 && verification === 0) {\n return [\n `⚠️ EVAL_ERROR — LLM returned unparseable response (${tier} tier)`,\n '',\n 'Raw response (first 300 chars):',\n raw.slice(0, 300),\n '',\n 'ACTION: Try again with a different tier, or call report() if you believe the plan is ready.',\n ].join('\\n');\n }\n\n const feedbackIdx = raw.toUpperCase().indexOf('FEEDBACK:');\n const feedback = feedbackIdx >= 0 ? raw.slice(feedbackIdx + 'FEEDBACK:'.length).trim() : '';\n\n const status = passed ? '✅ PASSED' : '❌ FAILED';\n const scoreBar = Math.round(composite * 10);\n const bar = '█'.repeat(scoreBar) + '░'.repeat(10 - scoreBar);\n\n return [\n `${status} — score: ${composite.toFixed(2)} [${bar}] (threshold ${PASS_THRESHOLD}, ${tier} tier)`,\n '',\n ` specificity: ${specificity.toFixed(2)} (weight 0.30)`,\n ` actionability: ${actionability.toFixed(2)} (weight 0.35)`,\n ` completeness: ${completeness.toFixed(2)} (weight 0.15)`,\n ` verification: ${verification.toFixed(2)} (weight 0.20)`,\n '',\n ...(feedback ? ['─── Feedback ───', feedback, ''] : []),\n passed\n ? 'ACTION: Call report() with the plan — it is ready for user approval.'\n : 'ACTION: Revise the plan addressing the feedback above, then call plan_validate again.\\n After 3 failed validations, call ask_user() with the plan and this feedback.',\n ].join('\\n');\n}\n\nexport function createPlanValidateTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function' as const,\n function: {\n name: 'plan_validate',\n description: `Evaluate a plan draft against quality criteria using an LLM judge.\nReturns pass/fail, per-dimension scores, and concrete actionable feedback on what to fix.\nCall this after writing a plan draft, before calling report().\nIf it fails, revise the plan based on the feedback and call plan_validate again.\nAfter 3 consecutive failures, call ask_user() with the plan and the feedback to escalate to the human.`,\n parameters: {\n type: 'object' as const,\n properties: {\n task: {\n type: 'string' as const,\n description: 'The original user task/request that the plan is supposed to address. Copied verbatim — the evaluator needs this to judge relevance.',\n },\n plan_markdown: {\n type: 'string' as const,\n description: 'The full plan markdown to evaluate.',\n },\n tier: {\n type: 'string' as const,\n enum: ['small', 'medium', 'large'],\n description: 'LLM tier for evaluation. Default: small (fast, cheap). Use medium/large for complex plans or if small gives inconsistent results.',\n },\n },\n required: ['task', 'plan_markdown'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const task = input.task as string;\n const planMarkdown = input.plan_markdown as string;\n const tier = (input.tier as string | undefined) ?? 'small';\n\n if (!task?.trim()) {\n return { success: false, output: 'ERROR: task is required — provide the original user request so the evaluator can judge plan relevance.' };\n }\n if (!planMarkdown?.trim()) {\n return { success: false, output: 'ERROR: plan_markdown is required — provide the full plan markdown to evaluate.' };\n }\n\n const llm = useLLM({ tier: tier as 'small' | 'medium' | 'large' });\n if (!llm) {\n return { success: false, output: `ERROR: LLM tier \"${tier}\" is not available. Try a different tier or check platform configuration.` };\n }\n\n try {\n const response = await llm.complete(buildEvalPrompt(task, planMarkdown), {\n systemPrompt: EVAL_SYSTEM_PROMPT,\n maxTokens: 1500,\n });\n\n const formatted = formatResult(response.content, tier);\n\n // If plan passed, signal to report tool that validation is complete\n if (formatted.startsWith('✅ PASSED') || formatted.startsWith('⚠️ EVAL_ERROR')) {\n (context as unknown as Record<string, unknown>).planValidationPassed = true;\n }\n\n return { success: true, output: formatted };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { success: false, output: `ERROR: LLM evaluation failed: ${message}` };\n }\n },\n };\n}\n","/**\n * plan_write tool — write/update the session plan file on disk.\n *\n * Enables iterative plan building: agent writes plan incrementally during\n * exploration, rather than generating everything at the end in one shot.\n * The plan survives context compaction because it lives on disk.\n *\n * Plan file location: .kb/agents/sessions/{sessionId}/plan.md\n * (resolved from context.sessionId and context.workingDir)\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { Tool, ToolContext } from '../../types.js';\nimport { toolError } from '../shared/tool-error.js';\n\nexport function createPlanWriteTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'plan_write',\n description: `Write or update the plan file for this session. The plan is saved to disk and survives context compaction. Use this to iteratively build your plan during exploration — write what you've learned so far, then continue exploring. The user can view the plan file at any time.`,\n parameters: {\n type: 'object',\n properties: {\n content: {\n type: 'string',\n description: 'Full markdown content for the plan file (replaces previous content)',\n },\n append: {\n type: 'string',\n description: 'Text to append to the existing plan (mutually exclusive with content)',\n },\n },\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const content = input.content as string | undefined;\n const append = input.append as string | undefined;\n\n if (!content && !append) {\n return toolError({\n code: 'MISSING_INPUT',\n message: 'Either content or append must be provided.',\n retryable: false,\n hint: 'Provide content= for full replacement, or append= to add to existing plan.',\n });\n }\n\n if (content && append) {\n return toolError({\n code: 'AMBIGUOUS_INPUT',\n message: 'Cannot use both content and append at the same time.',\n retryable: false,\n hint: 'Use content= to replace the entire plan, or append= to add a section.',\n });\n }\n\n // Resolve plan file path\n const sessionId = context.sessionId;\n if (!sessionId) {\n return toolError({\n code: 'NO_SESSION',\n message: 'No session ID available. Plan write requires an active session.',\n retryable: false,\n });\n }\n\n const planDir = path.join(context.workingDir, '.kb', 'agents', 'sessions', sessionId);\n const planPath = path.join(planDir, 'plan.md');\n\n // Ensure directory exists\n if (!fs.existsSync(planDir)) {\n fs.mkdirSync(planDir, { recursive: true });\n }\n\n let finalContent: string;\n\n if (content) {\n // Full replacement\n finalContent = content;\n } else {\n // Append mode\n let existing = '';\n try {\n existing = fs.readFileSync(planPath, 'utf-8');\n } catch {\n // File doesn't exist yet — start fresh\n }\n finalContent = existing\n ? `${existing.trimEnd()}\\n\\n${append}`\n : append!;\n }\n\n fs.writeFileSync(planPath, finalContent, 'utf-8');\n\n const lineCount = finalContent.split('\\n').length;\n const mode = content ? 'replaced' : 'appended to';\n\n return {\n success: true,\n output: `Plan ${mode}: ${planPath}\\nLines: ${lineCount}`,\n metadata: {\n planPath,\n lineCount,\n mode: content ? 'replace' : 'append',\n },\n };\n },\n };\n}\n","/**\n * Shell execution tool\n */\n\nimport { execSync } from 'node:child_process';\nimport path from 'node:path';\nimport type { Tool, ToolContext } from '../../types.js';\nimport { toolError } from '../shared/tool-error.js';\nimport { SHELL_CONFIG } from '../../config.js';\n\nconst MAX_OUTPUT_CHARS = 8_000;\n\nfunction trimOutput(output: string, label: 'stdout' | 'stderr'): string {\n if (output.length <= MAX_OUTPUT_CHARS) {return output;}\n const head = output.slice(0, MAX_OUTPUT_CHARS * 0.3);\n const tail = output.slice(-Math.floor(MAX_OUTPUT_CHARS * 0.7));\n return `${head}\\n\\n⚠️ ${label.toUpperCase()} TRIMMED (${output.length.toLocaleString()} chars, showing head+tail)\\n💡 Pipe through grep/head/tail in your command to get focused output.\\n\\n...${tail}`;\n}\n\n/**\n * Execute shell command\n */\nexport function createShellExecTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'shell_exec',\n description: 'Execute a shell command and return output. Use for running builds, tests, git commands, etc. Commands run in the working directory.',\n parameters: {\n type: 'object',\n properties: {\n command: {\n type: 'string',\n description: 'Shell command to execute',\n },\n cwd: {\n type: 'string',\n description: 'Optional working directory relative to agent workingDir. Use to run command in a specific package/subdirectory.',\n },\n },\n required: ['command'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const command = input.command as string;\n const requestedCwd = typeof input.cwd === 'string' ? input.cwd.trim() : '';\n const resolvedCwd = requestedCwd\n ? path.resolve(context.workingDir, requestedCwd)\n : context.workingDir;\n\n const relative = path.relative(context.workingDir, resolvedCwd);\n if (relative.startsWith('..') || path.isAbsolute(relative)) {\n return toolError({\n code: 'INVALID_CWD',\n message: `Invalid cwd \"${requestedCwd}\" - outside working directory.`,\n retryable: false,\n hint: 'Use cwd relative to the agent working directory.',\n details: { requestedCwd, resolvedCwd, workingDir: context.workingDir },\n });\n }\n\n try {\n const output = execSync(command, {\n cwd: resolvedCwd,\n encoding: 'utf-8',\n maxBuffer: SHELL_CONFIG.maxBuffer,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n\n const trimmed = trimOutput(output || '', 'stdout');\n return {\n success: true,\n output: `[cwd: ${resolvedCwd}]\\n${trimmed || '(command completed with no output)'}`,\n metadata: {\n cwd: resolvedCwd,\n outputLength: output?.length ?? 0,\n trimmed: (output?.length ?? 0) > MAX_OUTPUT_CHARS,\n },\n };\n } catch (error: unknown) {\n // execSync throws when command exits with non-zero code\n const e = error as { stderr?: Buffer | string; stdout?: Buffer | string; status?: number; code?: string; signal?: string };\n const stderr = e.stderr?.toString() || '';\n const stdout = e.stdout?.toString() || '';\n const exitCode = e.status ?? -1;\n const commandText = typeof command === 'string' ? command.trim() : '';\n\n if (e.code === 'ETIMEDOUT' || e.signal === 'SIGTERM') {\n return toolError({\n code: 'SHELL_TIMEOUT',\n message: `Command timed out in ${resolvedCwd}`,\n retryable: true,\n hint: 'Use a narrower command or run package-scoped command via cwd.',\n details: { cwd: resolvedCwd, command: commandText, exitCode },\n });\n }\n\n if (/command not found/i.test(stderr) || exitCode === 127) {\n return toolError({\n code: 'COMMAND_NOT_FOUND',\n message: `Command not found: ${commandText}`,\n retryable: false,\n hint: 'Check binary name or ensure dependency is installed in this workspace.',\n details: { cwd: resolvedCwd, command: commandText, exitCode },\n });\n }\n\n if (/permission denied/i.test(stderr) || exitCode === 126) {\n return toolError({\n code: 'PERMISSION_DENIED',\n message: `Permission denied while executing command in ${resolvedCwd}`,\n retryable: false,\n hint: 'Check file permissions and executable bits.',\n details: { cwd: resolvedCwd, command: commandText, exitCode },\n });\n }\n\n const stdoutDisplay = trimOutput(stdout, 'stdout');\n const stderrDisplay = trimOutput(stderr, 'stderr');\n\n return toolError({\n code: 'NON_ZERO_EXIT',\n message: `Command failed with exit code ${exitCode}`,\n retryable: true,\n hint: 'Inspect stderr/stdout below. Pipe output through grep/head/tail to narrow it down.',\n details: {\n cwd: resolvedCwd,\n exitCode,\n stdout: stdoutDisplay || undefined,\n stderr: stderrDisplay || undefined,\n },\n });\n }\n },\n };\n}\n","/**\n * Async task tools — fire-and-forget sub-agent operations.\n *\n * - task_submit: Start a sub-agent in the background, get a task ID immediately\n * - task_status: Check status of one or all async tasks\n * - task_collect: Wait for a specific task to complete and get its result\n */\n\nimport type { ToolContext, Tool } from '../../types.js';\nimport type { SubAgentPreset } from '@kb-labs/agent-contracts';\nimport { SUB_AGENT_PRESETS } from '../../config.js';\n\n/**\n * Submit an async task (fire-and-forget sub-agent).\n */\nexport function createTaskSubmitTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'task_submit',\n description:\n 'Start a sub-agent task in the background. Returns immediately with a task ID.\\n' +\n 'The sub-agent runs concurrently — you can continue working while it executes.\\n' +\n 'Use task_status to check progress or task_collect to wait for results.',\n parameters: {\n type: 'object',\n properties: {\n description: {\n type: 'string',\n description: 'Short description of the task (for tracking).',\n },\n task: {\n type: 'string',\n description: 'Detailed task description for the sub-agent.',\n },\n preset: {\n type: 'string',\n enum: ['research', 'execute', 'review'],\n description: 'Sub-agent preset (default: \"research\").',\n },\n budgetPercent: {\n type: 'number',\n description: 'Percent of remaining budget to allocate (1-100, default: 20).',\n },\n },\n required: ['description', 'task'],\n },\n },\n },\n executor: async (input) => {\n if (!context.taskManager) {\n return {\n success: false,\n error: 'Async task system not available. Task delegation is not enabled for this agent.',\n };\n }\n\n const description = input.description as string;\n const task = input.task as string;\n const presetId = (input.preset as SubAgentPreset) ?? 'research';\n const preset = SUB_AGENT_PRESETS[presetId];\n if (!preset) {\n return { success: false, error: `Unknown preset: \"${presetId}\".` };\n }\n\n const budgetPercent = (input.budgetPercent as number | undefined) ?? 50;\n const budgetFraction = Math.min(1, Math.max(0, budgetPercent / 100));\n\n try {\n const asyncTask = await context.taskManager.submit(description, {\n task,\n preset: presetId,\n allowedTools: Array.from(preset.tools),\n maxIterations: preset.maxIterations,\n budgetFraction,\n });\n\n return {\n success: true,\n output: `Task submitted: ${asyncTask.id}\\nDescription: ${description}\\nPreset: ${presetId}\\nStatus: ${asyncTask.status}\\n\\nUse task_status(\"${asyncTask.id}\") to check progress or task_collect(\"${asyncTask.id}\") to wait for results.`,\n };\n } catch (error) {\n return {\n success: false,\n error: `Failed to submit task: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n },\n };\n}\n\n/**\n * Check status of async tasks.\n */\nexport function createTaskStatusTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'task_status',\n description:\n 'Check status of one or all async tasks.\\n' +\n 'Without taskId: returns all tasks.\\n' +\n 'With taskId: returns details for that specific task.',\n parameters: {\n type: 'object',\n properties: {\n taskId: {\n type: 'string',\n description: 'Specific task ID to check (omit for all tasks).',\n },\n },\n required: [],\n },\n },\n },\n executor: async (input) => {\n if (!context.taskManager) {\n return { success: false, error: 'Async task system not available.' };\n }\n\n const taskId = input.taskId as string | undefined;\n const result = context.taskManager.getStatus(taskId);\n\n if (result === null) {\n return { success: false, error: `Task not found: \"${taskId}\"` };\n }\n\n const tasks = Array.isArray(result) ? result : [result];\n if (tasks.length === 0) {\n return { success: true, output: 'No async tasks.' };\n }\n\n const lines = tasks.map(t => {\n const status = t.status === 'completed' ? '✅' :\n t.status === 'failed' ? '❌' :\n t.status === 'running' ? '⏳' : '⏸️';\n let line = `${status} ${t.id}: ${t.description} [${t.status}]`;\n if (t.result) { line += `\\n Result: ${t.result.slice(0, 200)}`; }\n if (t.error) { line += `\\n Error: ${t.error}`; }\n return line;\n });\n\n return { success: true, output: lines.join('\\n') };\n },\n };\n}\n\n/**\n * Wait for a specific async task to complete and get its full result.\n */\nexport function createTaskCollectTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'task_collect',\n description:\n 'Wait for a specific async task to complete and return its full result.\\n' +\n 'Blocks until the task is done. Use task_status to check without waiting.',\n parameters: {\n type: 'object',\n properties: {\n taskId: {\n type: 'string',\n description: 'The task ID to wait for.',\n },\n },\n required: ['taskId'],\n },\n },\n },\n executor: async (input) => {\n if (!context.taskManager) {\n return { success: false, error: 'Async task system not available.' };\n }\n\n const taskId = input.taskId as string;\n\n try {\n const result = await context.taskManager.collect(taskId);\n const status = result.success ? 'completed successfully' : 'failed';\n const lines = [\n `Task ${taskId} ${status} [preset=${result.preset}, ${result.iterations} iters, ${result.tokensUsed.toLocaleString()} tokens, ${(result.durationMs / 1000).toFixed(1)}s]`,\n ];\n\n if (result.filesRead.length > 0) { lines.push(`Files read: ${result.filesRead.length}`); }\n if (result.filesModified.length > 0) { lines.push(`Files modified: ${result.filesModified.join(', ')}`); }\n if (result.filesCreated.length > 0) { lines.push(`Files created: ${result.filesCreated.join(', ')}`); }\n\n lines.push('', result.summary);\n if (result.error) { lines.push('', `Error: ${result.error}`); }\n\n return { success: result.success, output: lines.join('\\n') };\n } catch (error) {\n return {\n success: false,\n error: `Failed to collect task: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n },\n };\n}\n","/**\n * User interaction tools\n */\n\nimport * as readline from 'node:readline';\nimport type { Tool, ToolContext } from '../../types.js';\n\n/**\n * Ask user a question (interactive mode only)\n */\nexport function createAskUserTool(_context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'ask_user',\n description: 'Ask the user a question and wait for their response. Use when you need clarification or additional information. In non-interactive mode, returns a default answer.',\n parameters: {\n type: 'object',\n properties: {\n question: {\n type: 'string',\n description: 'Question to ask the user',\n },\n },\n required: ['question'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const question = input.question as string;\n\n // Check if running in interactive mode\n const isInteractive =\n process.stdin.isTTY && process.stdout.isTTY && !process.env.CI;\n\n if (!isInteractive) {\n // Non-interactive mode: return default answer\n return {\n success: true,\n output: `[Auto-answer] Question was: \"${question}\". Proceeding with default behavior.`,\n };\n }\n\n // Interactive mode: ask user\n return new Promise(resolve => {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n rl.question(`\\n❓ ${question}\\n> `, answer => {\n rl.close();\n\n if (!answer || answer.trim() === '') {\n resolve({\n success: false,\n error: 'No answer provided',\n });\n } else {\n resolve({\n success: true,\n output: answer.trim(),\n });\n }\n });\n });\n },\n };\n}\n","/**\n * Reporting tools - for sub-agents to communicate with parent agent\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type {\n ClaimVerificationResult,\n EvidenceRequirements,\n EvidenceRecord,\n KernelState,\n} from '@kb-labs/agent-contracts';\nimport { useLLM } from '@kb-labs/sdk/hooks';\nimport type { Tool, ToolContext, ToolResponseRequirements } from '../../types.js';\n\nasync function hasPendingCorrectionCommit(context: ToolContext): Promise<boolean> {\n const kernel = await context.sessionMemory?.loadKernelState();\n if (!kernel) {\n return false;\n }\n return kernel.memory.pendingActions.some((action) =>\n action.status !== 'done'\n && action.content.startsWith('Persist user correction via memory_correction:')\n );\n}\n\nconst VERIFY_REPORT_CLAIMS_PROMPT = [\n 'Evaluate whether the proposed final agent answer is sufficiently supported by the provided session evidence.',\n 'Prefer blocking only when the answer makes unsupported code, file, architecture, or behavioral claims.',\n 'Allow simple session recall when kernel evidence is enough.',\n 'If evidence is partial, prefer warn instead of block unless the answer states unsupported details as facts.',\n 'Return strict JSON only.',\n].join(' ');\n\nasync function verifyReportClaims(\n context: ToolContext,\n answer: string,\n): Promise<ClaimVerificationResult> {\n const kernel = await context.sessionMemory?.loadKernelState();\n const requirements = await resolveResponseRequirements(context, answer, kernel);\n const evidence = kernel?.memory.evidence ?? [];\n const recallFastPath = verifyEvidenceBackedRecall(answer, kernel, requirements);\n if (recallFastPath) {\n return recallFastPath;\n }\n const fallback = deterministicVerification(answer, kernel, requirements);\n const llm = useLLM({ tier: 'small' });\n\n if (!llm?.complete) {\n return fallback;\n }\n\n try {\n const response = await llm.complete(buildClaimVerificationPrompt(answer, kernel, context), {\n systemPrompt: VERIFY_REPORT_CLAIMS_PROMPT,\n temperature: 0,\n maxTokens: 350,\n });\n return normalizeClaimVerification(response.content, fallback, evidence);\n } catch {\n return fallback;\n }\n}\n\nasync function resolveResponseRequirements(\n context: ToolContext,\n answer: string,\n kernel: KernelState | null | undefined,\n): Promise<ToolResponseRequirements | null> {\n if (!context.responseRequirementsResolver) {\n return null;\n }\n try {\n return await context.responseRequirementsResolver({\n task: context.currentTask,\n answer,\n kernel: kernel ?? null,\n });\n } catch {\n return null;\n }\n}\n\nfunction buildClaimVerificationPrompt(\n answer: string,\n kernel: KernelState | null | undefined,\n context: ToolContext,\n): string {\n const recentEvidence = (kernel?.memory.evidence ?? [])\n .slice(-6)\n .map((item) => ({\n toolName: item.toolName ?? item.source,\n toolInputSummary: item.toolInputSummary,\n summary: item.summary,\n }));\n const archiveEvidence = (kernel?.memory.evidence ?? [])\n .slice(-4)\n .flatMap((item) => {\n if (!item.toolInputSummary || !context.archiveMemory?.hasFile(item.toolInputSummary)) {\n return [];\n }\n const archived = context.archiveMemory.recallByFilePath(item.toolInputSummary);\n if (!archived) {\n return [];\n }\n return [{\n filePath: item.toolInputSummary,\n toolName: archived.toolName,\n excerpt: truncateText(archived.fullOutput, 1200),\n }];\n });\n\n return JSON.stringify({\n answer,\n objective: kernel?.objective ?? kernel?.currentTask ?? '',\n constraints: kernel?.constraints ?? [],\n recentCorrections: kernel?.memory.corrections.slice(-3).map((item) => item.content) ?? [],\n recentEvidence,\n archiveEvidence,\n schema: {\n verdict: 'allow | warn | block',\n rationale: 'short explanation',\n requirements: {\n allowsMemoryOnlyRecall: 'boolean',\n needsDirectToolEvidence: 'boolean',\n needsFileBackedClaims: 'boolean',\n allowsInference: 'boolean',\n maxUnsupportedClaims: 'number',\n },\n supportedClaims: ['string'],\n unsupportedClaims: ['string'],\n },\n }, null, 2);\n}\n\nfunction normalizeClaimVerification(\n content: string,\n fallback: ClaimVerificationResult,\n evidence: EvidenceRecord[],\n): ClaimVerificationResult {\n const parsed = extractJsonObject(content);\n if (!parsed) {\n return fallback;\n }\n\n const requirements = normalizeEvidenceRequirements(parsed.requirements, fallback.requirements);\n const verdict = parsed.verdict === 'allow' || parsed.verdict === 'warn' || parsed.verdict === 'block'\n ? parsed.verdict\n : fallback.verdict;\n const supportedClaims = normalizeStringArray(parsed.supportedClaims);\n const unsupportedClaims = normalizeStringArray(parsed.unsupportedClaims);\n const rationale = typeof parsed.rationale === 'string' && parsed.rationale.trim()\n ? parsed.rationale.trim()\n : fallback.rationale;\n\n if (verdict === 'block' && unsupportedClaims.length === 0 && evidence.length > 0) {\n return fallback;\n }\n\n return {\n verdict,\n rationale,\n requirements,\n supportedClaims,\n unsupportedClaims,\n };\n}\n\nfunction deterministicVerification(\n answer: string,\n kernel: KernelState | null | undefined,\n responseRequirements?: ToolResponseRequirements | null,\n): ClaimVerificationResult {\n const evidence = kernel?.memory.evidence ?? [];\n const shellRecall = /shell command|previous shell command|used in this session|latest shell command/i.test(answer);\n const fileLikeClaims = /RuntimeEngine|projectKernelPrompt|compactKernelState|plugins\\/|packages\\/|\\.ts\\b|line \\d+/i.test(answer);\n const hasFileEvidence = evidence.some((item) => item.toolName === 'fs_read');\n const hasShellEvidence = evidence.some((item) => item.toolName === 'shell_exec');\n const requirements = responseRequirements?.requirements;\n\n if (shellRecall && hasShellEvidence) {\n return {\n verdict: 'allow',\n rationale: 'Shell recall answer is grounded in stored shell_exec evidence.',\n requirements: {\n allowsMemoryOnlyRecall: true,\n needsDirectToolEvidence: false,\n needsFileBackedClaims: false,\n allowsInference: false,\n maxUnsupportedClaims: 0,\n },\n supportedClaims: ['Session shell recall supported by shell_exec evidence.'],\n unsupportedClaims: [],\n };\n }\n\n if (fileLikeClaims && !hasFileEvidence) {\n return {\n verdict: 'block',\n rationale: 'Code/file claims require fs_read-backed evidence before report is allowed.',\n requirements: {\n allowsMemoryOnlyRecall: false,\n needsDirectToolEvidence: true,\n needsFileBackedClaims: true,\n allowsInference: false,\n maxUnsupportedClaims: 0,\n },\n supportedClaims: [],\n unsupportedClaims: ['Answer makes file/code claims without fs_read evidence.'],\n };\n }\n\n return {\n verdict: 'allow',\n rationale: 'No unsupported claims were detected by deterministic fallback.',\n requirements: requirements ?? {\n allowsMemoryOnlyRecall: true,\n needsDirectToolEvidence: false,\n needsFileBackedClaims: false,\n allowsInference: true,\n maxUnsupportedClaims: 1,\n },\n supportedClaims: [],\n unsupportedClaims: [],\n };\n}\n\nfunction verifyEvidenceBackedRecall(\n answer: string,\n kernel: KernelState | null | undefined,\n responseRequirements: ToolResponseRequirements | null,\n): ClaimVerificationResult | null {\n if (!responseRequirements?.requirements.allowsMemoryOnlyRecall) {\n return null;\n }\n\n const evidence = kernel?.memory.evidence ?? [];\n const fileEvidence = evidence\n .filter((item) => item.toolName === 'fs_read' && item.toolInputSummary)\n .map((item) => item.toolInputSummary as string);\n const mentionedFiles = extractMentionedFilePaths(answer);\n\n if (mentionedFiles.length > 0 && mentionedFiles.every((filePath) => fileEvidence.includes(filePath))) {\n return {\n verdict: 'allow',\n rationale: 'Answer is a direct recall of file evidence already recorded in the session.',\n requirements: responseRequirements.requirements,\n supportedClaims: mentionedFiles.map((filePath) => `Read evidence exists for ${filePath}.`),\n unsupportedClaims: [],\n };\n }\n\n return null;\n}\n\nfunction extractMentionedFilePaths(answer: string): string[] {\n const matches = answer.match(/plugins\\/[^\\s`*]+|packages\\/[^\\s`*]+/g) ?? [];\n return [...new Set(matches)];\n}\n\nfunction normalizeEvidenceRequirements(\n value: unknown,\n fallback: EvidenceRequirements,\n): EvidenceRequirements {\n if (!value || typeof value !== 'object') {\n return fallback;\n }\n const input = value as Record<string, unknown>;\n return {\n allowsMemoryOnlyRecall: typeof input.allowsMemoryOnlyRecall === 'boolean'\n ? input.allowsMemoryOnlyRecall\n : fallback.allowsMemoryOnlyRecall,\n needsDirectToolEvidence: typeof input.needsDirectToolEvidence === 'boolean'\n ? input.needsDirectToolEvidence\n : fallback.needsDirectToolEvidence,\n needsFileBackedClaims: typeof input.needsFileBackedClaims === 'boolean'\n ? input.needsFileBackedClaims\n : fallback.needsFileBackedClaims,\n allowsInference: typeof input.allowsInference === 'boolean'\n ? input.allowsInference\n : fallback.allowsInference,\n maxUnsupportedClaims: typeof input.maxUnsupportedClaims === 'number'\n ? input.maxUnsupportedClaims\n : fallback.maxUnsupportedClaims,\n };\n}\n\nfunction normalizeStringArray(value: unknown): string[] {\n if (!Array.isArray(value)) {\n return [];\n }\n return value.filter((item): item is string => typeof item === 'string' && item.trim().length > 0);\n}\n\nfunction extractJsonObject(content: string): Record<string, unknown> | null {\n const start = content.indexOf('{');\n const end = content.lastIndexOf('}');\n if (start === -1 || end === -1 || end <= start) {\n return null;\n }\n try {\n return JSON.parse(content.slice(start, end + 1)) as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\nfunction truncateText(value: string, maxChars: number): string {\n const normalized = value.trim();\n if (normalized.length <= maxChars) {\n return normalized;\n }\n return `${normalized.slice(0, maxChars - 1).trimEnd()}…`;\n}\n\n/**\n * Ask parent agent for help when stuck or uncertain.\n * Sub-agents use this to escalate to the main agent for guidance.\n */\nexport function createAskParentTool(_context: ToolContext): Tool {\n return {\n definition: {\n type: 'function' as const,\n function: {\n name: 'ask_parent',\n description: `Ask the parent agent for help when stuck or need clarification.`,\n parameters: {\n type: 'object' as const,\n properties: {\n question: {\n type: 'string' as const,\n description: 'Your question for the parent agent. Be specific about what you need help with.',\n },\n reason: {\n type: 'string' as const,\n enum: ['stuck', 'uncertain', 'blocker', 'clarification'],\n description: 'Why are you asking? stuck=repeating tools, uncertain=unclear approach, blocker=cannot proceed, clarification=need more info',\n },\n context: {\n type: 'object' as const,\n description: 'Relevant context: tools tried, iteration number, what you attempted',\n },\n },\n required: ['question', 'reason'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const question = input.question as string;\n const reason = input.reason as string;\n const context = input.context as Record<string, unknown> | undefined;\n\n return {\n success: true,\n output: '', // Will be populated by parent agent\n metadata: {\n question,\n reason,\n context,\n needsParentHelp: true,\n },\n };\n },\n };\n}\n\n/**\n * Report findings and exit. Used by agents to provide synthesized answer\n * and signal early exit when task is complete.\n */\nexport function createReportTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function' as const,\n function: {\n name: 'report',\n description: `Report your answer and exit. Include specific findings with file paths and code snippets as evidence.`,\n parameters: {\n type: 'object' as const,\n properties: {\n answer: {\n type: 'string' as const,\n description: 'Synthesized answer with specific details, file references, and code snippets. Be concise but complete.',\n },\n confidence: {\n type: 'number' as const,\n description: 'How confident you are in this answer (0.0-1.0). Use 0.8+ if you found concrete evidence, 0.5-0.7 if partial, <0.5 if uncertain.',\n },\n },\n required: ['answer', 'confidence'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const answer = input.answer as string;\n const confidence = input.confidence as number;\n\n // In plan mode (plan_validate is in the allowed tool set), prefer\n // plan_validate before report — but don't hard-block if budget is exhausted.\n // If the agent wrote a plan file via plan_write, allow report as fallback.\n const inPlanMode = context.allowedTools?.has('plan_validate') ?? false;\n if (inPlanMode && !context.planValidationPassed) {\n // Check if plan file exists on disk (written via plan_write)\n const planPath = context.sessionId\n ? path.join(context.workingDir, '.kb', 'agents', 'sessions', context.sessionId, 'plan.md')\n : null;\n const hasPlanFile = planPath && fs.existsSync(planPath);\n\n if (!hasPlanFile) {\n return {\n success: false,\n output: 'BLOCKED: You must either (1) call plan_validate first, or (2) save your plan via plan_write and then call report. Call plan_write with your plan content now.',\n };\n }\n // Plan file exists — allow report even without validation (budget fallback)\n }\n\n if (await hasPendingCorrectionCommit(context)) {\n return {\n success: false,\n output: 'BLOCKED: You must call memory_correction before report because this session has an unpersisted user correction or active instruction. Persist it first, then report.',\n metadata: {\n code: 'PENDING_MEMORY_COMMIT',\n },\n };\n }\n\n const verification = await verifyReportClaims(context, answer);\n if (verification.verdict === 'block') {\n return {\n success: false,\n output: `BLOCKED: Report claims are not sufficiently supported by session evidence. ${verification.rationale}`,\n metadata: {\n code: 'INSUFFICIENT_EVIDENCE',\n verification,\n },\n };\n }\n\n return {\n success: true,\n output: '', // Intentionally empty - agent should exit after calling this\n metadata: {\n answer,\n confidence,\n earlyExit: true,\n verification,\n },\n };\n },\n };\n}\n\n/**\n * Reflection tool - agent reflects on progress and decides whether to continue.\n * Auto-triggers report when confidence is high and shouldContinue is false.\n */\nexport function createReflectOnProgressTool(_context: ToolContext): Tool {\n return {\n definition: {\n type: 'function' as const,\n function: {\n name: 'reflect_on_progress',\n description: `Reflect on progress and decide whether to continue or report. If confidence >= 0.7 and should_continue = false, auto-reports findings.`,\n parameters: {\n type: 'object' as const,\n properties: {\n findings_summary: {\n type: 'string' as const,\n description: 'Brief summary of what you accomplished so far (2-3 sentences)',\n },\n confidence: {\n type: 'number' as const,\n description: 'Confidence that task is complete (0.0-1.0). For implementation: 0.8+ only if artifacts created. For research: 0.8+ if answers found.',\n minimum: 0,\n maximum: 1,\n },\n questions_remaining: {\n type: 'array' as const,\n items: { type: 'string' as const },\n description: 'List of aspects still incomplete. Empty array if all done.',\n },\n should_continue: {\n type: 'boolean' as const,\n description: 'true = need more work, false = ready to report completion',\n },\n reason: {\n type: 'string' as const,\n description: 'Explanation for your continue/stop decision (1 sentence)',\n },\n evidence_of_completion: {\n type: 'string' as const,\n description: 'Concrete evidence of task completion (e.g., \"Created 15 files\", \"Tests passing\", \"Found answer in 3 sources\"). Required for high confidence.',\n },\n },\n required: ['findings_summary', 'confidence', 'questions_remaining', 'should_continue', 'reason', 'evidence_of_completion'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const reflection = {\n findingsSummary: input.findings_summary as string,\n confidence: input.confidence as number,\n questionsRemaining: input.questions_remaining as string[],\n shouldContinue: input.should_continue as boolean,\n reason: input.reason as string,\n evidenceOfCompletion: input.evidence_of_completion as string,\n };\n\n // Anti-hallucination check: If agent claims completion without evidence, reduce confidence\n const hasNoEvidence = !reflection.evidenceOfCompletion ||\n reflection.evidenceOfCompletion.toLowerCase().includes('need to') ||\n reflection.evidenceOfCompletion.toLowerCase().includes('will create') ||\n reflection.evidenceOfCompletion.toLowerCase().includes('plan to');\n\n let adjustedConfidence = reflection.confidence;\n let adjustedShouldContinue = reflection.shouldContinue;\n let warningMessage = '';\n\n if (reflection.confidence >= 0.7 && !reflection.shouldContinue && hasNoEvidence) {\n adjustedConfidence = 0.3;\n adjustedShouldContinue = true;\n warningMessage = ' [ADJUSTED: No concrete evidence of completion - lowered confidence to 0.30, continue required]';\n }\n\n return {\n success: true,\n output: `Reflection recorded: confidence=${adjustedConfidence.toFixed(2)}, should_continue=${adjustedShouldContinue}${warningMessage}`,\n metadata: {\n reflection: {\n ...reflection,\n confidence: adjustedConfidence,\n shouldContinue: adjustedShouldContinue,\n },\n shouldAutoReport: adjustedConfidence >= 0.7 && !adjustedShouldContinue,\n adjusted: adjustedConfidence !== reflection.confidence,\n },\n };\n },\n };\n}\n","/**\n * Tool registration and exports\n *\n * Tools are organized by category:\n * filesystem/ — fs_read, fs_write, fs_patch, fs_replace, fs_list, mass_replace\n * search/ — glob_search, grep_search, find_definition, code_stats\n * memory/ — memory_*, archive_recall, session_save\n * planning/ — plan_validate, plan_write, todo_*\n * execution/ — shell_exec, task_submit/status/collect\n * interaction/ — ask_user, ask_parent, report\n * shared/ — tool-error (utilities)\n */\n\nimport type { ToolContext } from '../types.js';\nimport { ToolRegistry } from '../registry.js';\n\n// ── Filesystem ──────────────────────────────────────────────────────────────\n\nimport {\n createFsWriteTool,\n createFsReadTool,\n createFsPatchTool,\n createFsReplaceTool,\n createFsListTool,\n} from './filesystem/filesystem.js';\n\nimport { createMassReplaceTool } from './filesystem/mass-replace.js';\n\n// ── Search ──────────────────────────────────────────────────────────────────\n\nimport {\n createGlobSearchTool,\n createGrepSearchTool,\n createListFilesTool,\n createFindDefinitionTool,\n createCodeStatsTool,\n} from './search/search.js';\n\n// ── Memory ──────────────────────────────────────────────────────────────────\n\nimport {\n createMemoryGetTool,\n createMemoryPreferenceTool,\n createMemoryConstraintTool,\n createSessionSaveTool,\n createMemoryCorrectionTool,\n createMemoryFindingTool,\n createMemoryBlockerTool,\n} from './memory/memory.js';\n\nimport { createArchiveRecallTool } from './memory/archive-recall.js';\n\n// ── Planning ────────────────────────────────────────────────────────────────\n\nimport {\n createTodoCreateTool,\n createTodoUpdateTool,\n createTodoGetTool,\n} from './planning/todo.js';\n\nimport { createPlanValidateTool } from './planning/plan-validate.js';\nimport { createPlanWriteTool } from './planning/plan-write.js';\n\n// ── Execution ───────────────────────────────────────────────────────────────\n\nimport { createShellExecTool } from './execution/shell.js';\nimport { createTaskSubmitTool, createTaskStatusTool, createTaskCollectTool } from './execution/async-tasks.js';\n\n// ── Interaction ─────────────────────────────────────────────────────────────\n\nimport { createAskUserTool } from './interaction/interaction.js';\nimport { createAskParentTool, createReportTool } from './interaction/reporting.js';\n\n// ═════════════════════════════════════════════════════════════════════════════\n// Registry\n// ═════════════════════════════════════════════════════════════════════════════\n\n/**\n * Create and register all tools\n */\nexport function createToolRegistry(context: ToolContext): ToolRegistry {\n const allowed = context.allowedTools;\n const allow = (name: string) => !allowed || allowed.has(name);\n const registry = new ToolRegistry(context);\n\n // ── Filesystem ──\n if (allow('fs_write')) {registry.register(createFsWriteTool(context));}\n if (allow('fs_read')) {registry.register(createFsReadTool(context));}\n if (allow('fs_patch')) {registry.register(createFsPatchTool(context));}\n if (allow('fs_replace')) {registry.register(createFsReplaceTool(context));}\n if (allow('fs_list')) {registry.register(createFsListTool(context));}\n if (allow('mass_replace')) {registry.register(createMassReplaceTool(context));}\n\n // ── Search ──\n if (allow('glob_search')) {registry.register(createGlobSearchTool(context));}\n if (allow('grep_search')) {registry.register(createGrepSearchTool(context));}\n if (allow('find_definition')) {registry.register(createFindDefinitionTool(context));}\n if (allow('code_stats')) {registry.register(createCodeStatsTool(context));}\n\n // ── Execution ──\n if (allow('shell_exec')) {registry.register(createShellExecTool(context));}\n if (context.taskManager) {\n if (allow('task_submit')) { registry.register(createTaskSubmitTool(context)); }\n if (allow('task_status')) { registry.register(createTaskStatusTool(context)); }\n if (allow('task_collect')) { registry.register(createTaskCollectTool(context)); }\n }\n\n // ── Memory ──\n if (allow('memory_get')) {registry.register(createMemoryGetTool(context));}\n if (allow('memory_preference')) {registry.register(createMemoryPreferenceTool(context));}\n if (allow('memory_constraint')) {registry.register(createMemoryConstraintTool(context));}\n if (allow('session_save')) {registry.register(createSessionSaveTool(context));}\n if (allow('memory_correction')) {registry.register(createMemoryCorrectionTool(context));}\n if (allow('memory_finding')) {registry.register(createMemoryFindingTool(context));}\n if (allow('memory_blocker')) {registry.register(createMemoryBlockerTool(context));}\n if (context.archiveMemory && allow('archive_recall')) {\n registry.register(createArchiveRecallTool(context));\n }\n\n // ── Planning ──\n if (allow('todo_create')) {registry.register(createTodoCreateTool(context));}\n if (allow('todo_update')) {registry.register(createTodoUpdateTool(context));}\n if (allow('todo_get')) {registry.register(createTodoGetTool(context));}\n if (allow('plan_validate')) { registry.register(createPlanValidateTool(context)); }\n if (allow('plan_write')) { registry.register(createPlanWriteTool(context)); }\n\n // ── Interaction ──\n if (allow('ask_user')) {registry.register(createAskUserTool(context));}\n if (allow('ask_parent')) {registry.register(createAskParentTool(context));}\n if (allow('report')) {registry.register(createReportTool(context));}\n\n return registry;\n}\n\n// ═════════════════════════════════════════════════════════════════════════════\n// Re-exports\n// ═════════════════════════════════════════════════════════════════════════════\n\nexport {\n // Filesystem\n createFsWriteTool,\n createFsReadTool,\n createFsPatchTool,\n createFsReplaceTool,\n createFsListTool,\n createMassReplaceTool,\n // Search\n createListFilesTool,\n createGlobSearchTool,\n createGrepSearchTool,\n createFindDefinitionTool,\n createCodeStatsTool,\n // Memory\n createMemoryGetTool,\n createMemoryPreferenceTool,\n createMemoryConstraintTool,\n createSessionSaveTool,\n createMemoryCorrectionTool,\n createMemoryFindingTool,\n createMemoryBlockerTool,\n createArchiveRecallTool,\n // Planning\n createTodoCreateTool,\n createTodoUpdateTool,\n createTodoGetTool,\n createPlanValidateTool,\n createPlanWriteTool,\n // Execution\n createShellExecTool,\n createTaskSubmitTool,\n createTaskStatusTool,\n createTaskCollectTool,\n // Interaction\n createAskUserTool,\n createAskParentTool,\n createReportTool,\n};\n","import type { ToolCapability, ToolResultArtifact } from '@kb-labs/agent-contracts';\nimport { ToolRegistry } from './registry.js';\nimport type { ToolContext, ToolExecutionEnvelope, ToolPolicy } from './types.js';\nimport { createToolRegistry } from './tools/index.js';\n\nconst DEFAULT_TOOL_CAPABILITIES: Record<string, ToolCapability[]> = {\n fs_write: ['filesystem'],\n fs_read: ['filesystem'],\n fs_patch: ['filesystem'],\n fs_list: ['filesystem'],\n mass_replace: ['filesystem'],\n glob_search: ['search'],\n grep_search: ['search'],\n list_files: ['search'],\n find_definition: ['code-navigation'],\n code_stats: ['search'],\n shell_exec: ['shell'],\n memory_get: ['memory'],\n memory_preference: ['memory'],\n memory_constraint: ['memory'],\n session_save: ['memory'],\n memory_correction: ['memory'],\n memory_finding: ['memory'],\n memory_blocker: ['memory'],\n archive_recall: ['memory'],\n todo_create: ['todo'],\n todo_update: ['todo'],\n todo_get: ['todo'],\n ask_user: ['interaction'],\n ask_parent: ['reporting'],\n report: ['reporting'],\n task_submit: ['delegation'],\n task_status: ['delegation'],\n task_collect: ['delegation'],\n plan_validate: ['planning'],\n};\n\nfunction toArtifact(toolName: string, result: {\n success: boolean;\n output?: string;\n error?: string;\n metadata?: Record<string, unknown>;\n}): ToolResultArtifact {\n const summary = result.output || result.error || `${toolName} completed`;\n return {\n status: result.success ? 'success' : 'error',\n summary,\n artifact: result.metadata,\n evidence: summary\n ? [{\n id: `ev-${Date.now()}-${toolName}`,\n summary,\n source: toolName,\n createdAt: new Date().toISOString(),\n artifact: result.metadata,\n }]\n : [],\n mutations: typeof result.metadata?.filePath === 'string'\n ? { filesRead: [result.metadata.filePath] }\n : undefined,\n followUpHints: typeof result.metadata?.summary === 'string'\n ? [String(result.metadata.summary)]\n : undefined,\n };\n}\n\nexport class ToolGateway {\n private readonly registry: ToolRegistry;\n\n constructor(\n private readonly context: ToolContext,\n private readonly policies: ToolPolicy[] = [],\n ) {\n this.registry = createToolRegistry(context);\n }\n\n getDefinitions() {\n return this.registry.getDefinitions().filter((definition) =>\n this.isAllowed(definition.function.name),\n );\n }\n\n getToolNames(): string[] {\n return this.getDefinitions().map((definition) => definition.function.name);\n }\n\n async execute(name: string, input: Record<string, unknown>): Promise<ToolExecutionEnvelope> {\n const allowed = this.isAllowed(name);\n if (!allowed) {\n const artifact: ToolResultArtifact = {\n status: 'error',\n summary: `Tool \"${name}\" blocked by policy`,\n evidence: [],\n };\n return {\n result: { success: false, error: artifact.summary },\n artifact,\n };\n }\n\n const result = await this.registry.execute(name, input);\n return {\n result,\n artifact: toArtifact(name, result),\n };\n }\n\n private isAllowed(toolName: string): boolean {\n const capabilities = this.getToolCapabilities(toolName);\n return this.policies.every((policy) =>\n policy.allows(toolName, this.context)\n && capabilities.every((capability) => policy.allowsCapability?.(capability, this.context, toolName) ?? true),\n );\n }\n\n private getToolCapabilities(toolName: string): ToolCapability[] {\n const mapped = this.context.toolCapabilitiesByName?.get(toolName);\n return mapped ?? DEFAULT_TOOL_CAPABILITIES[toolName] ?? [];\n }\n}\n","/**\n * RemoteWorkspaceProvider — proxies workspace operations to Workspace Agent via Gateway.\n *\n * Used when Agent Runner runs on Platform but needs to access files\n * on a remote Workspace Agent (Cursor-model: \"brain\" on server, \"hands\" on client).\n *\n * Uses Gateway dispatcher to send capability calls to connected Workspace Agent.\n *\n * @see ADR-0017: Workspace Agent Architecture (Phase 3)\n */\n\nimport type {\n IWorkspaceProvider,\n FileReadResult,\n FileStatResult,\n GrepResult,\n GlobResult,\n ShellResult,\n} from './workspace-provider.js';\n\n/** Gateway dispatcher call function (injected, avoids direct dependency on Gateway) */\nexport type DispatchFn = (\n adapter: string,\n method: string,\n args: unknown[],\n) => Promise<unknown>;\n\nexport interface RemoteWorkspaceProviderOptions {\n /** Function to dispatch capability calls via Gateway */\n dispatch: DispatchFn;\n}\n\nexport class RemoteWorkspaceProvider implements IWorkspaceProvider {\n constructor(private readonly opts: RemoteWorkspaceProviderOptions) {}\n\n async readFile(path: string, offset?: number, limit?: number): Promise<FileReadResult> {\n const result = await this.opts.dispatch('filesystem', 'readFile', [path]);\n const content = result as string;\n const lines = content.split('\\n');\n\n const start = (offset ?? 1) - 1;\n const count = limit ?? lines.length;\n const sliced = lines.slice(start, start + count);\n\n return {\n content: sliced.join('\\n'),\n totalLines: lines.length,\n truncated: sliced.length < lines.length,\n };\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n await this.opts.dispatch('filesystem', 'writeFile', [path, content]);\n }\n\n async listDir(path: string, limit?: number): Promise<string[]> {\n const result = await this.opts.dispatch('filesystem', 'listDir', [path]);\n const entries = result as string[];\n return limit ? entries.slice(0, limit) : entries;\n }\n\n async stat(path: string): Promise<FileStatResult> {\n return await this.opts.dispatch('filesystem', 'stat', [path]) as FileStatResult;\n }\n\n async exists(path: string): Promise<boolean> {\n return await this.opts.dispatch('filesystem', 'exists', [path]) as boolean;\n }\n\n async grep(\n pattern: string,\n directory: string,\n options?: { includes?: string[]; excludes?: string[]; maxResults?: number; contextLines?: number },\n ): Promise<GrepResult> {\n return await this.opts.dispatch('search', 'grep', [pattern, directory, options]) as GrepResult;\n }\n\n async glob(\n pattern: string,\n directory: string,\n options?: { excludes?: string[]; maxResults?: number },\n ): Promise<GlobResult> {\n return await this.opts.dispatch('search', 'glob', [pattern, directory, options]) as GlobResult;\n }\n\n async shellExec(\n command: string,\n options?: { cwd?: string; timeoutMs?: number; env?: Record<string, string> },\n ): Promise<ShellResult> {\n return await this.opts.dispatch('shell', 'exec', [command, options]) as ShellResult;\n }\n}\n"]}
1
+ {"version":3,"sources":["../../home/runner/work/kb-labs/kb-labs/plugins/agents/tools/src/registry.ts","../../home/runner/work/kb-labs/kb-labs/plugins/agents/tools/src/tools/shared/tool-error.ts","../../home/runner/work/kb-labs/kb-labs/plugins/agents/tools/src/config.ts","../../home/runner/work/kb-labs/kb-labs/plugins/agents/tools/src/utils.ts","../../home/runner/work/kb-labs/kb-labs/plugins/agents/tools/src/tools/filesystem/filesystem.ts","../../home/runner/work/kb-labs/kb-labs/plugins/agents/tools/src/tools/filesystem/mass-replace.ts","../../home/runner/work/kb-labs/kb-labs/plugins/agents/tools/src/tools/search/search.ts","../../home/runner/work/kb-labs/kb-labs/plugins/agents/tools/src/tools/memory/memory.ts","../../home/runner/work/kb-labs/kb-labs/plugins/agents/tools/src/tools/memory/archive-recall.ts","../../home/runner/work/kb-labs/kb-labs/plugins/agents/tools/src/tools/planning/todo.ts","../../home/runner/work/kb-labs/kb-labs/plugins/agents/tools/src/tools/planning/plan-validate.ts","../../home/runner/work/kb-labs/kb-labs/plugins/agents/tools/src/tools/planning/plan-write.ts","../../home/runner/work/kb-labs/kb-labs/plugins/agents/tools/src/tools/execution/shell.ts","../../home/runner/work/kb-labs/kb-labs/plugins/agents/tools/src/tools/execution/async-tasks.ts","../../home/runner/work/kb-labs/kb-labs/plugins/agents/tools/src/tools/interaction/interaction.ts","../../home/runner/work/kb-labs/kb-labs/plugins/agents/tools/src/tools/interaction/reporting.ts","../../home/runner/work/kb-labs/kb-labs/plugins/agents/tools/src/tools/index.ts","../../home/runner/work/kb-labs/kb-labs/plugins/agents/tools/src/gateway.ts","../../home/runner/work/kb-labs/kb-labs/plugins/agents/tools/src/remote-workspace-provider.ts"],"names":["path","fs","relative","path2","MAX_FILE_SIZE","fs3","path3","crypto2","trimOutput","MAX_OUTPUT_CHARS","fs4","normalizeOffsetLimit","path5","fs5","path6","fs6","resolve","useLLM","path8","fs7"],"mappings":";;;;;;;;;;;;AAMO,IAAM,eAAN,MAAmB;AAAA,EAChB,KAAA,uBAAY,GAAA,EAAkB;AAAA,EAC9B,OAAA;AAAA,EAER,YAAY,OAAA,EAAsB;AAChC,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA,EAKA,SAAS,IAAA,EAAkB;AACzB,IAAA,IAAA,CAAK,MAAM,GAAA,CAAI,IAAA,CAAK,UAA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AA;AAAA,EAChE;AAAA,EAEA,MAAM,IAAA,CACJ,OAAA,EACA,SAAA,EACA,OAAA,EACqB;AACrB,IAAA,OAAO,MAAM,IAAA,CAAK,IAAA,CAAK,QAAA,CAAS,QAAA,EAAU,QAAQ,CAAC,OAAA,EAAS,SAAA,EAAW,OAAO,CAAC,CAAA;AAAA,EACjF;AAAA,EAEA,MAAM,IAAA,CACJ,OAAA,EACA,SAAA,EACA,OAAA,EACqB;AACrB,IAAA,OAAO,MAAM,IAAA,CAAK,IAAA,CAAK,QAAA,CAAS,QAAA,EAAU,QAAQ,CAAC,OAAA,EAAS,SAAA,EAAW,OAAO,CAAC,CAAA;AAAA,EACjF;AAAA,EAEA,MAAM,SAAA,CACJ,OAAA,EACA,OAAA,EACsB;AACtB,IAAA,OAAO,MAAM,KAAK,IAAA,CAAK,QAAA,CAAS,SAAS,MAAA,EAAQ,CAAC,OAAA,EAAS,OAAO,CAAC,CAAA;AAAA,EACrE;AACF","file":"index.js","sourcesContent":["/**\n * Tool registry for managing available tools\n */\n\nimport type { Tool, ToolContext } from './types.js';\n\nexport class ToolRegistry {\n private tools = new Map<string, Tool>();\n private context: ToolContext;\n\n constructor(context: ToolContext) {\n this.context = context;\n }\n\n /**\n * Register a tool\n */\n register(tool: Tool): void {\n this.tools.set(tool.definition.function.name, tool);\n }\n\n /**\n * Get tool by name\n */\n get(name: string): Tool | undefined {\n return this.tools.get(name);\n }\n\n /**\n * Get all tool definitions for LLM\n */\n getDefinitions() {\n return Array.from(this.tools.values()).map(t => t.definition);\n }\n\n /**\n * Execute a tool with automatic required-argument validation.\n * Returns a structured error if required args are missing/null/undefined,\n * so the agent understands what went wrong and can correct its call.\n */\n async execute(name: string, input: Record<string, unknown>) {\n const tool = this.tools.get(name);\n if (!tool) {\n return {\n success: false,\n output: `UNKNOWN_TOOL: \"${name}\" is not a registered tool. Available tools: ${this.getToolNames().join(', ')}`,\n };\n }\n\n // Validate required parameters against JSON schema\n const required: string[] = tool.definition.function.parameters?.required ?? [];\n const missing = required.filter(\n (key) => input[key] === undefined || input[key] === null,\n );\n if (missing.length > 0) {\n const params = tool.definition.function.parameters?.properties ?? {};\n const details = missing\n .map((k) => {\n const desc = (params[k] as { description?: string } | undefined)?.description ?? '';\n return ` - ${k}${desc ? ': ' + desc : ''}`;\n })\n .join('\\n');\n return {\n success: false,\n output:\n `MISSING_REQUIRED_ARGUMENTS for tool \"${name}\":\\n${details}\\n\\n` +\n `Hint: if a string argument is missing, your response may have been cut off by the output token limit (stop_reason=max_tokens). ` +\n `For large content, write in multiple smaller calls instead of one large call.`,\n };\n }\n\n return tool.executor(input);\n }\n\n /**\n * Get sorted list of registered tool names\n */\n getToolNames(): string[] {\n return Array.from(this.tools.keys()).sort();\n }\n\n /**\n * Get context\n */\n getContext(): ToolContext {\n return this.context;\n }\n}\n","import type { ToolResult } from '@kb-labs/agent-contracts';\n\nexport function toolError(input: {\n code: string;\n message: string;\n retryable?: boolean;\n hint?: string;\n details?: Record<string, unknown>;\n}): ToolResult {\n // Build error string that the LLM actually sees in tool results.\n // Include the hint directly — it tells the LLM what to do next,\n // preventing retry loops where the model doesn't know how to recover.\n const parts = [`${input.code}: ${input.message}`];\n if (input.hint) {\n parts.push(`\\nNext step: ${input.hint}`);\n }\n if (input.retryable === false) {\n parts.push('(This error cannot be resolved by retrying the same call.)');\n }\n const error = parts.join('\\n');\n\n return {\n success: false,\n error,\n errorDetails: {\n code: input.code,\n message: input.message,\n retryable: input.retryable,\n hint: input.hint,\n details: input.details,\n },\n metadata: {\n errorCode: input.code,\n retryable: input.retryable ?? false,\n ...(input.details || {}),\n },\n };\n}\n\n","/**\n * Centralized configuration constants for agent tools.\n *\n * All magic numbers and default values live here — tool implementations\n * import from this module instead of defining inline constants.\n */\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Filesystem tool config\n// ═══════════════════════════════════════════════════════════════════════════\n\nexport const FILESYSTEM_CONFIG = {\n /** Hard cap on file size to read (500KB) — prevents context overflow */\n maxFileSize: 500_000,\n /** Hard cap on lines returned per read — prevents context overflow */\n maxLinesPerRead: 2_000,\n /** Default lines to return when not specified — read whole file up to maxLinesPerRead */\n defaultLines: 2_000,\n /** Hard cap on content size for write operations (1MB) */\n maxWriteSize: 1_000_000,\n /** Default limit for directory listing */\n defaultListLimit: 50,\n /** Maximum limit for directory listing */\n maxListLimit: 200,\n /** Max output characters before trimming (prevents context explosion) */\n maxOutputChars: 12_000,\n} as const;\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Search tool config\n// ═══════════════════════════════════════════════════════════════════════════\n\nexport const SEARCH_CONFIG = {\n /** Timeout for search commands (15s) — fail fast, don't burn iterations */\n timeoutMs: 15_000,\n /** Max stdout buffer for search commands (8MB) */\n maxBuffer: 8 * 1024 * 1024,\n /** Default result limit — enough for actionable results */\n defaultResultLimit: 50,\n /** Maximum result limit */\n maxResultLimit: 200,\n /** Max output characters before trimming */\n maxOutputChars: 8_000,\n /**\n * Directories excluded from search by default.\n * These are never useful for code understanding and often huge.\n * Pass exclude=[] to override entirely, or exclude=[...custom] to replace the list.\n */\n defaultExcludes: [\n 'node_modules', '.git', 'dist', 'build', '.next',\n '.kb', '.pnpm', 'coverage', '__pycache__', '.venv', '.cache',\n ] as string[],\n} as const;\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Shell tool config\n// ═══════════════════════════════════════════════════════════════════════════\n\nexport const SHELL_CONFIG = {\n /** Max stdout buffer — aligned with SEARCH_CONFIG (16MB) */\n maxBuffer: 16 * 1024 * 1024,\n} as const;\n\n// ═══════════════════════════════════════════════════════════════════════════\n// TODO tool config\n// ═══════════════════════════════════════════════════════════════════════════\n\nexport const TODO_CONFIG = {\n /** Cache key prefix for todo lists */\n cachePrefix: 'agent:todo:',\n /** TTL for cached todo lists (7 days) */\n cacheTtlMs: 7 * 24 * 60 * 60 * 1000,\n} as const;\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Delegation tool config\n// ═══════════════════════════════════════════════════════════════════════════\n\nexport const DELEGATION_CONFIG = {\n /** Default max iterations for spawned sub-agents (safety net — token budget is primary control) */\n defaultMaxIterations: 100,\n /** Default budget fraction (50% of parent remaining — sub-agents need real budget) */\n defaultBudgetFraction: 0.5,\n} as const;\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Sub-agent presets\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Sub-agent tool allowlists and iteration defaults per preset.\n *\n * Single source of truth: lives in agent-tools because it knows tool names.\n * agent-core receives these as `allowedTools: string[]` data via SpawnAgentRequest\n * (no import from agent-tools needed — correct dependency direction).\n */\nexport const SUB_AGENT_PRESETS = {\n /** Read-only exploration and evidence gathering. */\n research: {\n tools: new Set<string>([\n 'fs_read', 'fs_list',\n 'glob_search', 'grep_search', 'find_definition', 'code_stats',\n 'memory_get', 'memory_finding', 'archive_recall',\n 'todo_get',\n 'report',\n ]),\n maxIterations: 50,\n },\n /** Full read/write capabilities for implementation tasks. */\n execute: {\n tools: new Set<string>([\n 'fs_read', 'fs_write', 'fs_patch', 'fs_replace', 'fs_list', 'mass_replace',\n 'glob_search', 'grep_search', 'find_definition', 'code_stats',\n 'shell_exec',\n 'memory_get', 'memory_finding', 'memory_blocker', 'memory_correction',\n 'todo_create', 'todo_update', 'todo_get',\n 'plan_write',\n 'ask_user', 'report',\n ]),\n maxIterations: 100,\n },\n /** Code review and verification: read + shell (linters, tests). */\n review: {\n tools: new Set<string>([\n 'fs_read', 'fs_list',\n 'glob_search', 'grep_search', 'find_definition', 'code_stats',\n 'shell_exec',\n 'memory_get', 'memory_finding', 'archive_recall',\n 'todo_get',\n 'report',\n ]),\n maxIterations: 50,\n },\n /**\n * Adversarial verification: independent agent that checks another agent's work.\n * Has read + shell access to run tests, check imports, verify builds.\n * Reports PASS/FAIL verdict with evidence.\n */\n verification: {\n tools: new Set<string>([\n 'fs_read', 'fs_list',\n 'glob_search', 'grep_search', 'find_definition', 'code_stats',\n 'shell_exec',\n 'report',\n ]),\n maxIterations: 25,\n },\n} as const;\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Mass replace tool config\n// ═══════════════════════════════════════════════════════════════════════════\n\nexport const MASS_REPLACE_CONFIG = {\n /** Hard cap on file size to process (1MB) — same as maxWriteSize */\n maxFileSize: 1_000_000,\n /** Maximum number of files to process in one operation */\n maxFiles: 100,\n} as const;\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Plan mode tool allowlist\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Tools available in plan mode — read-only exploration + async task delegation.\n * Used as `allowedTools` in ToolContext for both the plan-writer and any\n * research sub-agents it spawns via task_submit. Single source of truth:\n * lives in agent-tools so both agent-core and tests can import it without\n * creating a circular dependency.\n */\nexport const PLAN_READ_ONLY_TOOL_NAMES = new Set<string>([\n 'fs_read',\n 'fs_list',\n 'glob_search',\n 'grep_search',\n 'find_definition',\n 'code_stats',\n 'memory_get',\n 'memory_finding',\n 'memory_blocker',\n 'archive_recall',\n 'todo_create',\n 'todo_update',\n 'todo_get',\n 'ask_user',\n 'report',\n 'task_submit', // plan-writer can delegate research to async sub-agents\n 'task_status', // check progress of delegated tasks\n 'task_collect', // wait for and collect sub-agent results\n 'plan_validate', // LLM-based plan quality gate (agent calls this to self-assess before report)\n 'plan_write', // Write/update plan file on disk (iterative plan building)\n]);\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Source file extensions — single source of truth\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Source file extensions grouped by language.\n * Use ALL_SOURCE_EXTENSIONS or the helper functions for CLI flags.\n */\nexport const SOURCE_FILE_EXTENSIONS = {\n typescript: ['ts', 'tsx'],\n javascript: ['js', 'jsx'],\n python: ['py'],\n csharp: ['cs'],\n java: ['java'],\n go: ['go'],\n rust: ['rs'],\n ruby: ['rb'],\n php: ['php'],\n swift: ['swift'],\n kotlin: ['kt'],\n scala: ['scala'],\n cpp: ['cpp', 'c', 'h', 'cc', 'cxx'],\n} as const;\n\n/** Flat list of all source file extensions */\nexport const ALL_SOURCE_EXTENSIONS: readonly string[] = Object.values(SOURCE_FILE_EXTENSIONS).flat();\n\nexport function shellSingleQuote(value: string): string {\n return `'${value.replace(/'/g, `'\\\"'\\\"'`)}'`;\n}\n\n/**\n * Build `--include='*.ext'` flags for ripgrep / grep.\n * @example toRgIncludes(ALL_SOURCE_EXTENSIONS)\n * // → \"--include='*.ts' --include='*.tsx' ...\"\n */\nexport function toRgIncludes(exts: readonly string[]): string {\n return exts.map(e => `--include=${shellSingleQuote(`*.${e}`)}`).join(' ');\n}\n\n/**\n * Build `--include=*.ext` args for grep when using execa array mode (no shell).\n * @example toRgIncludesArgs(['ts', 'tsx'])\n * // → ['--include=*.ts', '--include=*.tsx']\n */\nexport function toRgIncludesArgs(exts: readonly string[]): string[] {\n return exts.map(e => `--include=*.${e}`);\n}\n\n/**\n * Build `-name '*.ext'` flags for `find` (joined with ` -o `).\n * @example toFindNames(ALL_SOURCE_EXTENSIONS)\n * // → \"-name '*.ts' -o -name '*.tsx' ...\"\n */\nexport function toFindNames(exts: readonly string[]): string {\n return exts.map(e => `-name ${shellSingleQuote(`*.${e}`)}`).join(' -o ');\n}\n\n/**\n * Build `-name *.ext` args for `find` when using execa array mode (no shell).\n * Returns a flat list of alternating pairs: ['-name', '*.ts', '-o', '-name', '*.tsx', ...]\n * with no leading/trailing `-o`.\n * @example toFindNamesArgs(['ts', 'tsx'])\n * // → ['-name', '*.ts', '-o', '-name', '*.tsx']\n */\nexport function toFindNamesArgs(exts: readonly string[]): string[] {\n if (exts.length === 0) {return [];}\n const result: string[] = [];\n for (let i = 0; i < exts.length; i++) {\n if (i > 0) {result.push('-o');}\n result.push('-name', `*.${exts[i]}`);\n }\n return result;\n}\n","/**\n * Shared utilities for agent tool implementations.\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\n\n/**\n * Normalize offset and limit parameters from tool input.\n *\n * Handles NaN, negative values, and enforces configured max/default limits.\n * Previously duplicated in filesystem.ts and search.ts.\n *\n * @example\n * const { offset, limit } = normalizeOffsetLimit(input, {\n * defaultLimit: FILESYSTEM_CONFIG.defaultLines,\n * maxLimit: FILESYSTEM_CONFIG.maxLinesPerRead,\n * });\n */\nexport function normalizeOffsetLimit(\n input: Record<string, unknown>,\n config: { defaultLimit: number; maxLimit: number },\n): { offset: number; limit: number } {\n const rawOffset = Number(input.offset);\n const rawLimit = Number(input.limit);\n\n const offset =\n Number.isFinite(rawOffset) && rawOffset >= 0 ? Math.floor(rawOffset) : 0;\n\n const limit =\n Number.isFinite(rawLimit) && rawLimit > 0\n ? Math.min(config.maxLimit, Math.floor(rawLimit))\n : config.defaultLimit;\n\n return { offset, limit };\n}\n\n/**\n * Validate that a file path stays within the working directory.\n *\n * Resolves symlinks to prevent symlink-based traversal bypasses.\n * Uses path.relative() which is more robust than startsWith().\n *\n * Previously duplicated in filesystem.ts and mass-replace.ts.\n */\nexport function validatePath(\n workingDir: string,\n filePath: string,\n): { valid: boolean; resolved: string; error?: string } {\n let resolved = path.resolve(workingDir, filePath);\n\n // Resolve symlinks to prevent symlink-based bypasses\n try {\n if (fs.existsSync(resolved)) {\n resolved = fs.realpathSync(resolved);\n }\n } catch {\n // If realpath fails, continue with resolved path (might be a non-existent file)\n }\n\n const relative = path.relative(workingDir, resolved);\n\n if (relative.startsWith('..')) {\n return {\n valid: false,\n resolved,\n error: `PATH_TRAVERSAL_ERROR: Cannot access \"${filePath}\" - path is outside working directory.\n\nHOW TO FIX: Use paths relative to the working directory. Do not use \"..\" to navigate above it.\nWORKING_DIR: ${workingDir}\nATTEMPTED_PATH: ${resolved}`,\n };\n }\n\n return { valid: true, resolved };\n}\n\n/**\n * Suggest a similar directory when the requested one doesn't exist.\n *\n * Handles common agent mistakes like nested paths (e.g. \"foo/bar\" when \"foo-bar/\" exists).\n * Returns null if no good suggestion found.\n */\nexport function suggestDirectory(workingDir: string, requestedDir: string): string | null {\n // Normalize: strip leading ./ and trailing /\n const clean = requestedDir.replace(/^\\.\\//, '').replace(/\\/$/, '');\n if (!clean || clean === '.') {return null;}\n\n // Only suggest for paths that look like nested mistakes (contain /)\n const parts = clean.split('/');\n if (parts.length < 2) {return null;}\n\n // Strategy: join first two segments with - instead of /\n // e.g. \"kb-labs/agents\" → \"kb-labs-agents\"\n const candidate = `${parts[0]}-${parts[1]}`;\n const rest = parts.slice(2).join('/');\n const fullCandidate = rest ? path.join(candidate, rest) : candidate;\n const resolved = path.resolve(workingDir, fullCandidate);\n\n if (fs.existsSync(resolved) && fs.statSync(resolved).isDirectory()) {\n return fullCandidate;\n }\n\n return null;\n}\n","/**\n * Filesystem tools for agent operations\n *\n * Features:\n * - Atomic operations with offset/limit for large files\n * - Path traversal protection\n * - Clear error messages for agent understanding\n * - Size limits to prevent context overflow\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport * as crypto from 'node:crypto';\nimport type { Tool, ToolContext } from '../../types.js';\nimport { toolError } from '../shared/tool-error.js';\nimport { FILESYSTEM_CONFIG } from '../../config.js';\nimport { normalizeOffsetLimit, validatePath, suggestDirectory } from '../../utils.js';\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Constants (sourced from centralized config)\n// ═══════════════════════════════════════════════════════════════════════════\n\nconst MAX_FILE_SIZE = FILESYSTEM_CONFIG.maxFileSize;\nconst MAX_LINES_PER_READ = FILESYSTEM_CONFIG.maxLinesPerRead;\nconst DEFAULT_LINES = FILESYSTEM_CONFIG.defaultLines;\nconst MAX_WRITE_SIZE = FILESYSTEM_CONFIG.maxWriteSize;\nconst DEFAULT_LIST_LIMIT = FILESYSTEM_CONFIG.defaultListLimit;\nconst MAX_LIST_LIMIT = FILESYSTEM_CONFIG.maxListLimit;\nconst MAX_OUTPUT_CHARS = FILESYSTEM_CONFIG.maxOutputChars;\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Output trimming\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Trim output to maxChars, appending a clear continuation hint.\n * Always shown when output is large — tells agent exactly what to do next.\n */\nfunction trimOutput(output: string, maxChars: number, continuationHint: string): string {\n if (output.length <= maxChars) {return output;}\n const trimmed = output.slice(0, maxChars);\n return `${trimmed}\\n\\n⚠️ OUTPUT TRIMMED (${output.length.toLocaleString()} chars → ${maxChars.toLocaleString()} shown)\\n${continuationHint}`;\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Helpers\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Validate path is within working directory (prevent path traversal)\n */\n/**\n * Format file size for display\n */\nfunction formatSize(bytes: number): string {\n if (bytes < 1024) {return `${bytes} bytes`;}\n if (bytes < 1024 * 1024) {return `${(bytes / 1024).toFixed(1)} KB`;}\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/**\n * Compute SHA-256 hash of content\n */\nfunction computeHash(content: string): string {\n return crypto.createHash('sha256').update(content, 'utf-8').digest('hex');\n}\n\nfunction normalizeListWindow(input: Record<string, unknown>): { offset: number; limit: number } {\n return normalizeOffsetLimit(input, { defaultLimit: DEFAULT_LIST_LIMIT, maxLimit: MAX_LIST_LIMIT });\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// fs_read - Read file with offset/limit support\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Read file contents with optional line range\n */\nexport function createFsReadTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'fs_read',\n description: `Read file contents. By default reads the entire file (up to ${MAX_LINES_PER_READ} lines). For very large files, use offset+limit to read specific sections. Prefer reading the whole file when possible — partial reads waste iterations.`,\n parameters: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'File path relative to working directory',\n },\n offset: {\n type: 'number',\n description: 'Line number to start from (1-indexed, default: 1)',\n },\n limit: {\n type: 'number',\n description: `Number of lines to read (default: all, max: ${MAX_LINES_PER_READ}). Only use for very large files — prefer reading the whole file.`,\n },\n },\n required: ['path'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const filePath = input.path as string;\n const offset = Math.max(1, (input.offset as number) || 1);\n const requestedLimit = (input.limit as number) || DEFAULT_LINES;\n const limit = Math.min(requestedLimit, MAX_LINES_PER_READ);\n\n // Validate path\n const pathValidation = validatePath(context.workingDir, filePath);\n if (!pathValidation.valid) {\n return toolError({\n code: 'PATH_VALIDATION_FAILED',\n message: pathValidation.error || 'Invalid path',\n retryable: false,\n hint: 'Use a path inside working directory.',\n details: { filePath, workingDir: context.workingDir },\n });\n }\n\n const fullPath = pathValidation.resolved;\n\n // Check file exists\n if (!fs.existsSync(fullPath)) {\n return toolError({\n code: 'FILE_NOT_FOUND',\n message: `\"${filePath}\" does not exist.`,\n retryable: true,\n hint: `Use fs_list(path=\"${path.dirname(filePath) || '.'}\") to inspect available files.`,\n details: { filePath, workingDir: context.workingDir },\n });\n }\n\n // Check if it's a file\n const stats = fs.statSync(fullPath);\n if (stats.isDirectory()) {\n return toolError({\n code: 'NOT_A_FILE',\n message: `\"${filePath}\" is a directory, not a file.`,\n retryable: false,\n hint: 'Use fs_list for directories or provide a file path.',\n details: { filePath },\n });\n }\n\n // Check file size\n if (stats.size > MAX_FILE_SIZE) {\n return toolError({\n code: 'FILE_TOO_LARGE',\n message: `\"${filePath}\" is ${formatSize(stats.size)}, exceeds limit ${formatSize(MAX_FILE_SIZE)}.`,\n retryable: true,\n hint: `Use fs_read(path=\"${filePath}\", offset=<line>, limit=<small number>).`,\n details: { filePath, size: stats.size, maxSize: MAX_FILE_SIZE },\n });\n }\n\n // Read file\n const content = fs.readFileSync(fullPath, 'utf-8');\n const allLines = content.split('\\n');\n const totalLines = allLines.length;\n\n // Validate offset\n if (offset > totalLines) {\n return toolError({\n code: 'OFFSET_OUT_OF_RANGE',\n message: `Requested offset ${offset} but file has ${totalLines} lines.`,\n retryable: true,\n hint: `Use offset between 1 and ${totalLines}.`,\n details: { filePath, offset, totalLines },\n });\n }\n\n // Extract requested lines (convert to 0-indexed)\n const startIndex = offset - 1;\n const endIndex = Math.min(startIndex + limit, totalLines);\n const selectedLines = allLines.slice(startIndex, endIndex);\n\n // Format output with line numbers\n const numberedLines = selectedLines.map((line, i) => {\n const lineNum = (startIndex + i + 1).toString().padStart(5, ' ');\n return `${lineNum}→${line}`;\n });\n\n // Build metadata header\n const hasMore = endIndex < totalLines;\n const linesRemaining = totalLines - endIndex;\n\n const warnings = [];\n if (requestedLimit > MAX_LINES_PER_READ) {\n warnings.push(`⚠️ Limit capped at ${MAX_LINES_PER_READ} (you requested ${requestedLimit})`);\n }\n if (hasMore) {\n warnings.push(`⚠️ PARTIAL READ: ${linesRemaining} lines unread. Next chunk: fs_read(path=\"${filePath}\", offset=${endIndex + 1})`);\n }\n\n const header = [\n `File: ${filePath}`,\n `Lines: ${offset}-${endIndex} of ${totalLines}`,\n hasMore ? `(${Math.round(((endIndex - offset + 1) / totalLines) * 100)}% read so far — ${linesRemaining} lines remain)` : '(end of file ✓)',\n ...warnings,\n '─'.repeat(60),\n ].filter(Boolean).join('\\n');\n\n const rawOutput = `${header}\\n${numberedLines.join('\\n')}`;\n const continuationHint = hasMore\n ? `Next chunk: fs_read(path=\"${filePath}\", offset=${endIndex + 1})`\n : '';\n\n // Register this file as read so fs_patch / fs_edit can edit it.\n // We update context directly here — this is the single authoritative place\n // to mark a file as \"seen\", regardless of whether the read was partial or full.\n const hash = computeHash(content);\n context.filesRead?.add(filePath);\n context.filesReadHash?.set(filePath, hash);\n\n return {\n success: true,\n output: trimOutput(rawOutput, MAX_OUTPUT_CHARS, continuationHint),\n metadata: {\n filePath,\n totalLines,\n readFrom: offset,\n readTo: endIndex,\n hasMore,\n fileSize: stats.size,\n contentHash: hash,\n },\n };\n },\n };\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// fs_write - Write file with size limits\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Write content to a file\n */\nexport function createFsWriteTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'fs_write',\n description: `Write a new file or completely rewrite an existing one. Creates parent directories if needed. IMPORTANT: Prefer fs_replace for modifying existing files — it only sends the diff. Only use fs_write to create NEW files or for complete rewrites where the entire content changes. If you're modifying an existing file, use fs_replace instead.`,\n parameters: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'File path relative to working directory',\n },\n content: {\n type: 'string',\n description: 'Content to write to the file',\n },\n },\n required: ['path', 'content'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const filePath = input.path as string;\n const content = input.content as string;\n\n // Validate path\n const pathValidation = validatePath(context.workingDir, filePath);\n if (!pathValidation.valid) {\n return toolError({\n code: 'PATH_VALIDATION_FAILED',\n message: pathValidation.error || 'Invalid path',\n retryable: false,\n hint: 'Use a path inside working directory.',\n details: { filePath, workingDir: context.workingDir },\n });\n }\n\n const fullPath = pathValidation.resolved;\n\n // Check content size\n const contentSize = Buffer.byteLength(content, 'utf-8');\n if (contentSize > MAX_WRITE_SIZE) {\n return {\n success: false,\n error: `CONTENT_TOO_LARGE: Content is ${formatSize(contentSize)}, exceeds limit of ${formatSize(MAX_WRITE_SIZE)}.\n\nHOW TO FIX: Split the content into smaller files, or write in chunks.`,\n };\n }\n\n // Check if overwriting existing file\n const isOverwrite = fs.existsSync(fullPath);\n const beforeContent = isOverwrite ? fs.readFileSync(fullPath, 'utf-8') : undefined;\n\n // Create parent directories if needed\n const dir = path.dirname(fullPath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n // Write file\n fs.writeFileSync(fullPath, content, 'utf-8');\n\n // Update read state so subsequent edits don't require a separate read\n const writeHash = computeHash(content);\n context.filesRead?.add(filePath);\n context.filesReadHash?.set(filePath, writeHash);\n\n const lineCount = content.split('\\n').length;\n\n return {\n success: true,\n output: `${isOverwrite ? 'Overwrote' : 'Created'} file: ${filePath}\nSize: ${formatSize(contentSize)}\nLines: ${lineCount}`,\n metadata: {\n filePath,\n fileContent: content,\n size: contentSize,\n lines: lineCount,\n isOverwrite,\n uiHint: 'code',\n // Consumed by ChangeTrackingMiddleware\n changeSnapshot: {\n operation: 'write' as const,\n beforeContent,\n afterContent: content,\n isOverwrite,\n },\n },\n };\n },\n };\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// fs_patch - Edit file by line numbers (like Claude Code)\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Edit file by replacing a range of lines\n */\nexport function createFsPatchTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'fs_patch',\n description: `Replace a range of lines by line numbers. Use fs_replace instead when possible — it's more reliable. Only use fs_patch for large block replacements where fs_replace match text would be too long. You must fs_read the file first. Line numbers are 1-indexed and inclusive.`,\n parameters: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'File path relative to working directory',\n },\n startLine: {\n type: 'number',\n description: 'First line to replace (1-indexed, inclusive)',\n },\n endLine: {\n type: 'number',\n description: 'Last line to replace (1-indexed, inclusive)',\n },\n newContent: {\n type: 'string',\n description: 'New content to replace the line range with',\n },\n },\n required: ['path', 'startLine', 'endLine', 'newContent'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const filePath = input.path as string;\n const startLine = input.startLine as number;\n const endLine = input.endLine as number;\n const newContent = input.newContent as string;\n\n // Validate path\n const pathValidation = validatePath(context.workingDir, filePath);\n if (!pathValidation.valid) {\n return { success: false, error: pathValidation.error };\n }\n\n const fullPath = pathValidation.resolved;\n\n // ═══════════════════════════════════════════════════════════════════════\n // PROTECTION 1: File must have been read in this session\n // ═══════════════════════════════════════════════════════════════════════\n if (context.filesRead && !context.filesRead.has(filePath)) {\n return toolError({\n code: 'CANNOT_EDIT_UNREAD_FILE',\n message: `File has not been read yet. You must read a file before editing it.`,\n retryable: true,\n hint: `Call fs_read(path=\"${filePath}\") to read the file first, then retry this edit.`,\n details: { filePath, startLine, endLine },\n });\n }\n\n // Check file exists\n if (!fs.existsSync(fullPath)) {\n return toolError({\n code: 'FILE_NOT_FOUND',\n message: `\"${filePath}\" does not exist.`,\n retryable: true,\n hint: 'Use fs_list to find files or fs_write to create a new file.',\n details: { filePath },\n });\n }\n\n // Read current content\n const currentContent = fs.readFileSync(fullPath, 'utf-8');\n\n // ═══════════════════════════════════════════════════════════════════════\n // PROTECTION 2: File must not have changed since read\n // ═══════════════════════════════════════════════════════════════════════\n if (context.filesReadHash) {\n const savedHash = context.filesReadHash.get(filePath);\n const currentHash = computeHash(currentContent);\n\n if (savedHash && savedHash !== currentHash) {\n return toolError({\n code: 'FILE_CHANGED_SINCE_READ',\n message: `File was modified since you last read it (possibly by a linter, formatter, or another tool).`,\n retryable: true,\n hint: `Call fs_read(path=\"${filePath}\") to get the current content, then retry the edit with updated line numbers.`,\n details: { filePath, startLine, endLine },\n });\n }\n }\n\n const allLines = currentContent.split('\\n');\n const totalLines = allLines.length;\n\n // Validate line numbers\n if (startLine < 1 || startLine > totalLines) {\n return toolError({\n code: 'INVALID_START_LINE',\n message: `startLine ${startLine} is out of range (file has ${totalLines} lines).`,\n retryable: true,\n hint: `Use startLine between 1 and ${totalLines}.`,\n details: { filePath, startLine, totalLines },\n });\n }\n\n if (endLine < startLine || endLine > totalLines) {\n return toolError({\n code: 'INVALID_END_LINE',\n message: `endLine ${endLine} is invalid (startLine=${startLine}, file has ${totalLines} lines).`,\n retryable: true,\n hint: `Use endLine between ${startLine} and ${totalLines}.`,\n details: { filePath, startLine, endLine, totalLines },\n });\n }\n\n // Apply patch (convert to 0-indexed)\n const beforeLines = allLines.slice(0, startLine - 1);\n const afterLines = allLines.slice(endLine);\n const newLines = newContent ? newContent.split('\\n') : [];\n\n const patchedContent = [...beforeLines, ...newLines, ...afterLines].join('\\n');\n\n // Calculate line changes\n const removedCount = endLine - startLine + 1;\n const addedCount = newLines.length;\n const netChange = addedCount - removedCount;\n\n // Write updated content\n fs.writeFileSync(fullPath, patchedContent, 'utf-8');\n\n // Update read state so subsequent edits don't require re-read.\n // Mirrors Claude Code pattern: readFileState.set() after every edit.\n const patchedHash = computeHash(patchedContent);\n context.filesRead?.add(filePath);\n context.filesReadHash?.set(filePath, patchedHash);\n\n let action: string;\n if (addedCount === 0) {\n action = `Deleted ${removedCount} line(s)`;\n } else if (removedCount === addedCount) {\n action = `Replaced ${removedCount} line(s)`;\n } else if (netChange > 0) {\n action = `Replaced ${removedCount} line(s) with ${addedCount} line(s) (+${netChange})`;\n } else {\n action = `Replaced ${removedCount} line(s) with ${addedCount} line(s) (${netChange})`;\n }\n\n return {\n success: true,\n output: `${action} in ${filePath}\nLines ${startLine}-${endLine} → ${addedCount} new line(s)\nFile now has ${beforeLines.length + newLines.length + afterLines.length} lines (was ${totalLines})`,\n metadata: {\n filePath,\n startLine,\n endLine,\n linesRemoved: removedCount,\n linesAdded: addedCount,\n netChange,\n totalLinesBefore: totalLines,\n totalLinesAfter: beforeLines.length + newLines.length + afterLines.length,\n // Consumed by ChangeTrackingMiddleware\n changeSnapshot: {\n operation: 'patch' as const,\n beforeContent: currentContent,\n afterContent: patchedContent,\n startLine,\n endLine,\n linesAdded: addedCount,\n linesRemoved: removedCount,\n },\n },\n };\n },\n };\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// fs_replace - Content-based edit (find text → replace)\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Edit a file by matching text content and replacing it.\n * More reliable than line-number-based fs_patch because LLMs\n * can copy exact text from fs_read output.\n */\nexport function createFsReplaceTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'fs_replace',\n description: `PREFERRED tool for editing existing files. Finds exact text and replaces it — only sends the diff, not the whole file. You must fs_read the file first. Use the smallest match text that uniquely identifies the target — usually 2-4 lines is enough. The match must appear exactly once (unless replace_all=true). If multiple matches, add more surrounding context to make it unique.`,\n parameters: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'File path relative to working directory',\n },\n match: {\n type: 'string',\n description: 'Exact text to find in the file (copy from fs_read output)',\n },\n replacement: {\n type: 'string',\n description: 'Text to replace the match with',\n },\n replace_all: {\n type: 'boolean',\n description: 'Replace all occurrences (default: false — requires unique match)',\n },\n },\n required: ['path', 'match', 'replacement'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const filePath = input.path as string;\n const match = input.match as string;\n const replacement = input.replacement as string;\n const replaceAll = (input.replace_all as boolean) || false;\n\n // ── Validate path ──\n const pathValidation = validatePath(context.workingDir, filePath);\n if (!pathValidation.valid) {\n return toolError({\n code: 'PATH_VALIDATION_FAILED',\n message: pathValidation.error || 'Invalid path',\n retryable: false,\n hint: 'Use a path inside working directory.',\n details: { filePath, workingDir: context.workingDir },\n });\n }\n const fullPath = pathValidation.resolved;\n\n // ── Validate: file must have been read ──\n if (context.filesRead && !context.filesRead.has(filePath)) {\n return toolError({\n code: 'CANNOT_EDIT_UNREAD_FILE',\n message: 'File has not been read yet. You must read a file before editing it.',\n retryable: true,\n hint: `Call fs_read(path=\"${filePath}\") to read the file first, then retry this edit.`,\n details: { filePath },\n });\n }\n\n // ── Validate: file exists ──\n if (!fs.existsSync(fullPath)) {\n return toolError({\n code: 'FILE_NOT_FOUND',\n message: `\"${filePath}\" does not exist.`,\n retryable: true,\n hint: 'Use fs_list to find files or fs_write to create a new file.',\n details: { filePath },\n });\n }\n\n // ── Read current content ──\n const currentContent = fs.readFileSync(fullPath, 'utf-8');\n\n // ── Validate: file not modified since read ──\n if (context.filesReadHash) {\n const savedHash = context.filesReadHash.get(filePath);\n const currentHash = computeHash(currentContent);\n if (savedHash && savedHash !== currentHash) {\n return toolError({\n code: 'FILE_CHANGED_SINCE_READ',\n message: 'File was modified since you last read it (possibly by a linter, formatter, or another tool).',\n retryable: true,\n hint: `Call fs_read(path=\"${filePath}\") to get the current content, then retry the edit.`,\n details: { filePath },\n });\n }\n }\n\n // ── Validate: match !== replacement ──\n if (match === replacement) {\n return toolError({\n code: 'NO_CHANGE',\n message: 'The match and replacement text are identical. No changes needed.',\n retryable: false,\n hint: 'Provide different replacement text, or skip this edit if no change is needed.',\n details: { filePath },\n });\n }\n\n // ── Validate: match exists in file ──\n if (!currentContent.includes(match)) {\n return toolError({\n code: 'MATCH_NOT_FOUND',\n message: 'The match text was not found in the file.',\n retryable: true,\n hint: `Call fs_read(path=\"${filePath}\") to see the current file content, then copy the exact text you want to replace.`,\n details: { filePath, matchLength: match.length },\n });\n }\n\n // ── Validate: uniqueness (unless replace_all) ──\n const occurrences = currentContent.split(match).length - 1;\n if (occurrences > 1 && !replaceAll) {\n return toolError({\n code: 'AMBIGUOUS_MATCH',\n message: `Found ${occurrences} occurrences of the match text, but replace_all is false.`,\n retryable: true,\n hint: `Include more surrounding context in the match text to make it unique (only 1 occurrence), or set replace_all=true to replace all ${occurrences} occurrences.`,\n details: { filePath, occurrences },\n });\n }\n\n // ── Apply replacement ──\n const updatedContent = replaceAll\n ? currentContent.replaceAll(match, replacement)\n : currentContent.replace(match, replacement);\n\n // ── Write file ──\n fs.writeFileSync(fullPath, updatedContent, 'utf-8');\n\n // ── Update read state for chained edits ──\n const newHash = computeHash(updatedContent);\n context.filesRead?.add(filePath);\n context.filesReadHash?.set(filePath, newHash);\n\n // ── Calculate diff stats ──\n const matchLines = match.split('\\n').length;\n const replacementLines = replacement.split('\\n').length;\n const netChange = replacementLines - matchLines;\n\n const action = replaceAll\n ? `Replaced ${occurrences} occurrence(s)`\n : 'Replaced 1 occurrence';\n\n return {\n success: true,\n output: `${action} in ${filePath}\nMatch: ${matchLines} line(s) → Replacement: ${replacementLines} line(s) (${netChange >= 0 ? '+' : ''}${netChange})\nFile now has ${updatedContent.split('\\n').length} lines`,\n metadata: {\n filePath,\n occurrences: replaceAll ? occurrences : 1,\n matchLines,\n replacementLines,\n netChange,\n totalLinesAfter: updatedContent.split('\\n').length,\n changeSnapshot: {\n operation: 'replace' as const,\n beforeContent: currentContent,\n afterContent: updatedContent,\n match,\n replacement,\n replaceAll,\n },\n },\n };\n },\n };\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// fs_list - List directory contents\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * List files in a directory\n */\nexport function createFsListTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'fs_list',\n description: `List files and directories at a path. Non-recursive by default. IMPORTANT: node_modules/, dist/, .git/, build/, .next/ are hidden by default — they contain no useful source code. Use include_ignored=true only if you specifically need to inspect build artifacts.`,\n parameters: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Directory path relative to working directory (default: \".\")',\n },\n recursive: {\n type: 'boolean',\n description: 'Include subdirectories recursively (default: false, max depth: 3)',\n },\n include_ignored: {\n type: 'boolean',\n description: 'Include normally-hidden dirs: node_modules, dist, build, .next, .git (default: false). Only use when you explicitly need to inspect build artifacts or dependencies.',\n },\n offset: {\n type: 'number',\n description: 'Result offset for pagination (default: 0)',\n },\n limit: {\n type: 'number',\n description: `Result limit per page (default: ${DEFAULT_LIST_LIMIT}, max: ${MAX_LIST_LIMIT})`,\n },\n },\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const dirPath = (input.path as string) || '.';\n const recursive = (input.recursive as boolean) || false;\n const includeIgnored = (input.include_ignored as boolean) || false;\n const { offset, limit } = normalizeListWindow(input);\n\n // Directories hidden by default — contain no useful source code\n const IGNORED_DIRS = new Set(['node_modules', 'dist', 'build', '.next', '.git', '.pnpm', '.cache', 'coverage', '__pycache__']);\n\n // Validate path\n const pathValidation = validatePath(context.workingDir, dirPath);\n if (!pathValidation.valid) {\n return toolError({\n code: 'PATH_VALIDATION_FAILED',\n message: pathValidation.error || 'Invalid path',\n retryable: false,\n hint: 'Use a path inside working directory.',\n details: { path: dirPath, workingDir: context.workingDir },\n });\n }\n\n const fullPath = pathValidation.resolved;\n\n // Check exists\n if (!fs.existsSync(fullPath)) {\n const suggestion = suggestDirectory(context.workingDir, dirPath);\n return toolError({\n code: 'DIRECTORY_NOT_FOUND',\n message: `\"${dirPath}\" does not exist.`,\n retryable: true,\n hint: suggestion\n ? `Did you mean \"${suggestion}\"?`\n : 'Use fs_list on parent directory to discover valid paths.',\n details: { path: dirPath, workingDir: context.workingDir },\n });\n }\n\n // Check is directory\n const stats = fs.statSync(fullPath);\n if (!stats.isDirectory()) {\n return toolError({\n code: 'NOT_A_DIRECTORY',\n message: `\"${dirPath}\" is a file, not a directory.`,\n retryable: false,\n hint: 'Use fs_read for files or provide a directory path.',\n details: { path: dirPath },\n });\n }\n\n // List contents\n const entries = fs.readdirSync(fullPath, { withFileTypes: true });\n\n // Separate and sort — filter ignored dirs unless include_ignored=true\n const files = entries\n .filter(e => e.isFile())\n .map(e => e.name)\n .filter(name => !name.startsWith('.')) // Hide dotfiles\n .sort();\n\n const dirs = entries\n .filter(e => e.isDirectory())\n .map(e => e.name)\n .filter(name => {\n if (name.startsWith('.')) {return false;}\n if (!includeIgnored && IGNORED_DIRS.has(name)) {return false;}\n return true;\n })\n .sort();\n\n // Track how many ignored dirs exist so agent knows they're there\n const hiddenDirCount = includeIgnored ? 0 : entries\n .filter(e => e.isDirectory() && IGNORED_DIRS.has(e.name))\n .length;\n\n const combinedEntries = [\n ...dirs.map((name) => ({ type: 'dir' as const, name })),\n ...files.map((name) => ({ type: 'file' as const, name })),\n ];\n const pageEntries = combinedEntries.slice(offset, offset + limit);\n const hasMore = offset + limit < combinedEntries.length;\n const nextOffset = hasMore ? offset + limit : null;\n const pageDirs = pageEntries.filter((entry) => entry.type === 'dir');\n const pageFiles = pageEntries.filter((entry) => entry.type === 'file');\n\n // Format output\n const ignoredNote = hiddenDirCount > 0\n ? `[${hiddenDirCount} ignored dir(s) hidden: node_modules/dist/build/etc — use include_ignored=true to show]`\n : '';\n\n const outputParts = [\n `📁 ${dirPath === '.' ? 'Working Directory' : dirPath} (showing ${pageEntries.length}/${combinedEntries.length}, offset=${offset}, limit=${limit})`,\n ignoredNote,\n '',\n ].filter(Boolean);\n\n if (pageDirs.length > 0) {\n outputParts.push(`Directories (${dirs.length}):`);\n for (const d of pageDirs) {\n outputParts.push(` 📁 ${d.name}/`);\n }\n outputParts.push('');\n }\n\n if (pageFiles.length > 0) {\n outputParts.push(`Files (${files.length}):`);\n for (const f of pageFiles) {\n // Get file size\n const filePath = path.join(fullPath, f.name);\n const fileStats = fs.statSync(filePath);\n outputParts.push(` 📄 ${f.name} (${formatSize(fileStats.size)})`);\n }\n }\n\n if (combinedEntries.length === 0) {\n outputParts.push('(empty directory)');\n }\n\n // Add recursive listing if requested\n if (recursive && dirs.length > 0) {\n outputParts.push('');\n outputParts.push('─'.repeat(40));\n outputParts.push('Recursive structure (depth 2):');\n\n for (const d of dirs.slice(0, 10)) { // Limit to 10 dirs\n outputParts.push(`\\n📁 ${d}/`);\n const subPath = path.join(fullPath, d);\n try {\n const subEntries = fs.readdirSync(subPath, { withFileTypes: true });\n const subDirs = subEntries.filter(e => e.isDirectory() && !e.name.startsWith('.') && e.name !== 'node_modules');\n const subFiles = subEntries.filter(e => e.isFile() && !e.name.startsWith('.'));\n\n for (const sd of subDirs.slice(0, 5)) {\n outputParts.push(` 📁 ${sd.name}/`);\n }\n if (subDirs.length > 5) {\n outputParts.push(` ... and ${subDirs.length - 5} more directories`);\n }\n\n for (const sf of subFiles.slice(0, 5)) {\n outputParts.push(` 📄 ${sf.name}`);\n }\n if (subFiles.length > 5) {\n outputParts.push(` ... and ${subFiles.length - 5} more files`);\n }\n } catch {\n outputParts.push(' (unable to read)');\n }\n }\n\n if (dirs.length > 10) {\n outputParts.push(`\\n... and ${dirs.length - 10} more directories`);\n }\n }\n\n const rawOutput = outputParts.join('\\n');\n const continuationHint = hasMore\n ? `Next page: fs_list(path=\"${dirPath}\", offset=${nextOffset}, limit=${limit})`\n : '';\n\n return {\n success: true,\n output: trimOutput(rawOutput, MAX_OUTPUT_CHARS, continuationHint),\n metadata: {\n path: dirPath,\n directoryCount: dirs.length,\n fileCount: files.length,\n directories: dirs,\n files,\n totalEntries: combinedEntries.length,\n offset,\n limit,\n hasMore,\n nextOffset,\n },\n };\n },\n };\n}\n","/**\n * Mass replace tool for batch text replacement across multiple files\n *\n * Features:\n * - Supports literal string or regex patterns\n * - Glob-based file selection\n * - File history tracking for rollback\n * - Dry-run mode for preview\n * - Safe: validates paths, checks file sizes\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport * as crypto from 'node:crypto';\nimport { glob } from 'glob';\nimport type { Tool, ToolContext } from '../../types.js';\nimport { validatePath } from '../../utils.js';\nimport { MASS_REPLACE_CONFIG } from '../../config.js';\n\nconst MAX_FILE_SIZE = MASS_REPLACE_CONFIG.maxFileSize;\nconst MAX_FILES = MASS_REPLACE_CONFIG.maxFiles;\n\n// ═══════════════════════════════════════════════════════════════════════════\n// mass_replace - Batch text replacement with history tracking\n// ═══════════════════════════════════════════════════════════════════════════\n\nexport function createMassReplaceTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'mass_replace',\n description: `Batch find-and-replace across multiple files. Supports literal and regex modes. Use dryRun=true to preview. Changes are tracked for rollback.`,\n parameters: {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: 'Text or regex pattern to search for. For regex mode, use JavaScript regex syntax (without / delimiters).',\n },\n replacement: {\n type: 'string',\n description: 'Replacement text. In regex mode, can use $1, $2 for capture groups.',\n },\n scope: {\n type: 'string',\n description: 'REQUIRED: Directory to limit search scope (e.g., \"src\", \"packages/agent-core\", \".\"). Prevents accidental project-wide changes. Use \".\" for current directory only.',\n },\n files: {\n type: 'string',\n description: 'Glob pattern for files within scope (e.g., \"**/*.ts\", \"*.js\"). Combined with scope to form full path.',\n },\n mode: {\n type: 'string',\n enum: ['literal', 'regex'],\n description: 'Replacement mode: \"literal\" for exact string match (default), \"regex\" for regex patterns.',\n },\n dryRun: {\n type: 'boolean',\n description: 'Preview changes without applying them. Shows what would be changed.',\n },\n caseInsensitive: {\n type: 'boolean',\n description: 'For regex mode: make pattern case-insensitive (adds \"i\" flag).',\n },\n },\n required: ['pattern', 'replacement', 'scope', 'files'],\n },\n },\n },\n\n executor: async (input: Record<string, unknown>) => {\n const pattern = String(input.pattern || '');\n const replacement = String(input.replacement || '');\n const scope = String(input.scope || '');\n const filesPattern = String(input.files || '');\n const mode = String(input.mode || 'literal');\n const dryRun = Boolean(input.dryRun);\n const caseInsensitive = Boolean(input.caseInsensitive);\n\n // Validation\n if (!pattern) {\n return {\n success: false,\n error: 'VALIDATION_ERROR: \"pattern\" is required.',\n };\n }\n\n if (!scope) {\n return {\n success: false,\n error: 'VALIDATION_ERROR: \"scope\" is required. Specify directory to limit search (e.g., \"src\", \"packages/agent-core\", or \".\" for current dir).',\n };\n }\n\n if (!filesPattern) {\n return {\n success: false,\n error: 'VALIDATION_ERROR: \"files\" glob pattern is required.',\n };\n }\n\n if (mode !== 'literal' && mode !== 'regex') {\n return {\n success: false,\n error: `VALIDATION_ERROR: Invalid mode \"${mode}\". Must be \"literal\" or \"regex\".`,\n };\n }\n\n try {\n // Validate and resolve scope directory\n const scopeValidation = validatePath(context.workingDir, scope);\n if (!scopeValidation.valid) {\n return {\n success: false,\n error: scopeValidation.error,\n };\n }\n\n const scopePath = scopeValidation.resolved;\n if (!fs.existsSync(scopePath)) {\n return {\n success: false,\n error: `SCOPE_ERROR: Directory \"${scope}\" does not exist.`,\n };\n }\n\n if (!fs.statSync(scopePath).isDirectory()) {\n return {\n success: false,\n error: `SCOPE_ERROR: \"${scope}\" is not a directory.`,\n };\n }\n\n // Find matching files within scope\n const matches = await glob(filesPattern, {\n cwd: scopePath,\n nodir: true,\n absolute: false,\n ignore: ['**/node_modules/**', '**/dist/**', '**/.git/**'],\n });\n\n if (matches.length === 0) {\n return {\n success: true,\n output: `No files matched pattern: \"${filesPattern}\" in scope: \"${scope}\"`,\n metadata: {\n filesMatched: 0,\n filesChanged: 0,\n totalReplacements: 0,\n scope,\n },\n };\n }\n\n if (matches.length > MAX_FILES) {\n return {\n success: false,\n error: `TOO_MANY_FILES: Pattern matched ${matches.length} files, but limit is ${MAX_FILES}. Use more specific glob pattern.`,\n };\n }\n\n // Prepare regex or literal pattern\n let searchPattern: RegExp;\n if (mode === 'regex') {\n const flags = caseInsensitive ? 'gi' : 'g';\n try {\n searchPattern = new RegExp(pattern, flags);\n } catch (err) {\n return {\n success: false,\n error: `REGEX_ERROR: Invalid regex pattern \"${pattern}\": ${(err as Error).message}`,\n };\n }\n } else {\n // Literal mode: escape special chars and make global\n const escapedPattern = pattern.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const flags = caseInsensitive ? 'gi' : 'g';\n searchPattern = new RegExp(escapedPattern, flags);\n }\n\n // Process files\n const results: Array<{\n file: string;\n replacements: number;\n preview?: string;\n }> = [];\n\n let totalReplacements = 0;\n let filesChanged = 0;\n\n for (const relPath of matches) {\n // Combine scope and relative path\n const scopedPath = path.join(scope, relPath);\n\n // Validate path\n const validation = validatePath(context.workingDir, scopedPath);\n if (!validation.valid) {\n return {\n success: false,\n error: validation.error,\n };\n }\n\n const fullPath = validation.resolved;\n\n // Check file exists and size\n if (!fs.existsSync(fullPath)) {\n continue; // Skip missing files\n }\n\n const stats = fs.statSync(fullPath);\n if (stats.size > MAX_FILE_SIZE) {\n results.push({\n file: scopedPath,\n replacements: 0,\n preview: `[SKIPPED: File too large (${(stats.size / 1024).toFixed(1)} KB > ${MAX_FILE_SIZE / 1024} KB)]`,\n });\n continue;\n }\n\n // Read file\n const beforeContent = fs.readFileSync(fullPath, 'utf-8');\n\n // Apply replacement\n const afterContent = beforeContent.replace(searchPattern, replacement);\n\n // Check if anything changed\n if (beforeContent === afterContent) {\n continue; // No changes, skip\n }\n\n const matchCount = (beforeContent.match(searchPattern) || []).length;\n totalReplacements += matchCount;\n filesChanged++;\n\n // Dry-run: collect preview\n if (dryRun) {\n // Show first 3 changes as preview\n const lines = beforeContent.split('\\n');\n const changedLines: string[] = [];\n let previewCount = 0;\n\n for (let i = 0; i < lines.length && previewCount < 3; i++) {\n const line = lines[i]!;\n if (searchPattern.test(line)) {\n const newLine = line.replace(searchPattern, replacement);\n changedLines.push(` Line ${i + 1}:`);\n changedLines.push(` - ${line.slice(0, 80)}`);\n changedLines.push(` + ${newLine.slice(0, 80)}`);\n previewCount++;\n }\n }\n\n results.push({\n file: scopedPath,\n replacements: matchCount,\n preview: changedLines.join('\\n'),\n });\n } else {\n // Apply changes\n fs.writeFileSync(fullPath, afterContent, 'utf-8');\n\n // Update read state so subsequent edits don't require re-read\n const hash = crypto.createHash('sha256').update(afterContent, 'utf-8').digest('hex');\n context.filesRead?.add(scopedPath);\n context.filesReadHash?.set(scopedPath, hash);\n\n results.push({\n file: scopedPath,\n replacements: matchCount,\n });\n }\n }\n\n // Format output\n const summary = dryRun\n ? `[DRY RUN] Would replace in ${filesChanged} file(s):`\n : `✅ Replaced in ${filesChanged} file(s):`;\n\n const details = results\n .map((r) => {\n if (r.preview) {\n return `${r.file}: ${r.replacements} replacement(s)\\n${r.preview}`;\n }\n return `${r.file}: ${r.replacements} replacement(s)`;\n })\n .join('\\n\\n');\n\n const output = `${summary}\\n\\n${details}\\n\\n` +\n `Scope: ${scope}\\n` +\n `Total replacements: ${totalReplacements}\\n` +\n `Files matched: ${matches.length}\\n` +\n `Files changed: ${filesChanged}` +\n (dryRun ? '\\n\\n⚠️ DRY RUN: No files were modified. Remove dryRun=true to apply changes.' : '');\n\n return {\n success: true,\n output,\n metadata: {\n scope,\n filesMatched: matches.length,\n filesChanged,\n totalReplacements,\n dryRun,\n pattern,\n replacement,\n mode,\n },\n };\n } catch (error) {\n return {\n success: false,\n error: `EXECUTION_ERROR: ${(error as Error).message}`,\n };\n }\n },\n };\n}\n","/**\n * Search tools for finding files and content\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { execa } from 'execa';\nimport type { Tool, ToolContext } from '../../types.js';\nimport { toolError } from '../shared/tool-error.js';\nimport { SEARCH_CONFIG, ALL_SOURCE_EXTENSIONS, toRgIncludesArgs, toFindNamesArgs } from '../../config.js';\nimport { normalizeOffsetLimit as _normalizeOffsetLimit, suggestDirectory } from '../../utils.js';\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Output trimming\n// ═══════════════════════════════════════════════════════════════════════════\n\nfunction trimOutput(output: string, maxChars: number, continuationHint: string): string {\n if (output.length <= maxChars) {return output;}\n const trimmed = output.slice(0, maxChars);\n return `${trimmed}\\n\\n⚠️ OUTPUT TRIMMED (${output.length.toLocaleString()} chars → ${maxChars.toLocaleString()} shown)\\n${continuationHint}`;\n}\n\n/** Default directories to exclude from search (sourced from centralized config) */\nconst DEFAULT_EXCLUDES = SEARCH_CONFIG.defaultExcludes;\nconst MAX_OUTPUT_CHARS = SEARCH_CONFIG.maxOutputChars;\n\n/**\n * Build find exclude args from exclude list.\n * Returns flat triplets: ['!', '-path', '*\\/node_modules\\/*', '!', '-path', ...]\n */\nfunction buildFindExcludes(excludes: readonly string[]): string[] {\n const args: string[] = [];\n for (const d of excludes) {\n args.push('!', '-path', `*/${d}/*`);\n }\n return args;\n}\n\n/**\n * Build grep exclude-dir args from exclude list.\n * Returns: ['--exclude-dir=node_modules', '--exclude-dir=dist', ...]\n */\nfunction buildGrepExcludes(excludes: readonly string[]): string[] {\n return excludes.map(d => `--exclude-dir=${d}`);\n}\n\nconst SEARCH_TIMEOUT_MS = SEARCH_CONFIG.timeoutMs;\nconst DEFAULT_RESULT_LIMIT = SEARCH_CONFIG.defaultResultLimit;\nconst MAX_RESULT_LIMIT = SEARCH_CONFIG.maxResultLimit;\n\n/**\n * Check if directory exists and return error message if not.\n * Lists available top-level directories as a hint.\n */\nfunction validateDirectory(workingDir: string, directory: string): string | null {\n const fullPath = path.resolve(workingDir, directory);\n if (fs.existsSync(fullPath) && fs.statSync(fullPath).isDirectory()) {\n return null;\n }\n\n // List available directories as hint\n let hint = '';\n try {\n const entries = fs.readdirSync(workingDir, { withFileTypes: true });\n const dirs = entries\n .filter(e => e.isDirectory() && !e.name.startsWith('.') && e.name !== 'node_modules')\n .map(e => e.name)\n .sort();\n if (dirs.length > 0) {\n hint = `\\nAvailable directories: ${dirs.slice(0, 15).join(', ')}${dirs.length > 15 ? ` ... (${dirs.length} total)` : ''}`;\n }\n } catch { /* ignore */ }\n\n const suggestion = suggestDirectory(workingDir, directory);\n const didYouMean = suggestion ? `\\nDid you mean: \"${suggestion}\"?` : '';\n return `Directory \"${directory}\" not found (resolved to ${fullPath}). Use \".\" to search from project root.${hint}${didYouMean}`;\n}\n\nfunction normalizeOffsetLimit(input: Record<string, unknown>): { offset: number; limit: number } {\n return _normalizeOffsetLimit(input, { defaultLimit: DEFAULT_RESULT_LIMIT, maxLimit: MAX_RESULT_LIMIT });\n}\n\nfunction paginate<T>(items: T[], offset: number, limit: number): { page: T[]; hasMore: boolean; nextOffset: number | null } {\n const page = items.slice(offset, offset + limit);\n const hasMore = offset + limit < items.length;\n return {\n page,\n hasMore,\n nextOffset: hasMore ? offset + limit : null,\n };\n}\n\n/**\n * Search for files by pattern (glob)\n */\nexport function createGlobSearchTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'glob_search',\n description: `Find files by name pattern (glob). Pattern matches filename only — use \"*.ts\" or \"user.ts\", not bare words. IMPORTANT: node_modules/, dist/, build/, .git/ are excluded by default — they contain no source code. Omit directory to search the entire working directory. Returns up to ${DEFAULT_RESULT_LIMIT} results.`,\n parameters: {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: 'Glob pattern (e.g., \"*.ts\", \"user.ts\", \"*user*.ts\")',\n },\n directory: {\n type: 'string',\n description: 'Directory to search in (default: working directory root). Narrow to a subfolder when you already know the scope.',\n },\n exclude: {\n type: 'array',\n items: { type: 'string' },\n description: 'Extra directories to exclude on top of defaults (node_modules, dist, .git, build, .next, .kb, .pnpm, coverage are always excluded). Rarely needed.',\n },\n offset: {\n type: 'number',\n description: 'Result offset for pagination (default: 0)',\n },\n limit: {\n type: 'number',\n description: `Max results per page (default: ${DEFAULT_RESULT_LIMIT}, max: ${MAX_RESULT_LIMIT})`,\n },\n },\n required: ['pattern'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const pattern = input.pattern as string;\n const directory = (input.directory as string) || '.';\n const extra = input.exclude as string[] | undefined;\n const excludes = extra && extra.length > 0 ? [...new Set([...DEFAULT_EXCLUDES, ...extra])] : DEFAULT_EXCLUDES;\n const { offset, limit } = normalizeOffsetLimit(input);\n\n try {\n const fullPath = path.resolve(context.workingDir, directory);\n\n const dirError = validateDirectory(context.workingDir, directory);\n if (dirError) {\n return { success: true, output: dirError };\n }\n\n const windowSize = Math.min(2000, Math.max(500, offset + limit));\n\n const args = [\n fullPath,\n '-type', 'f',\n '-iname', pattern,\n ...buildFindExcludes(excludes),\n ];\n\n const result = await execa('find', args, {\n cwd: context.workingDir,\n reject: false,\n timeout: SEARCH_TIMEOUT_MS,\n });\n\n const files = result.stdout\n .split('\\n')\n .filter(Boolean)\n .slice(0, windowSize)\n .map(f => path.relative(context.workingDir, f));\n\n if (files.length === 0) {\n return {\n success: true,\n output: `No files found matching pattern: ${pattern} in ${directory === '.' ? 'project root' : directory}. Note: glob_search matches filenames only. To search file contents, use grep_search. To find class/function definitions, use find_definition.`,\n };\n }\n\n const page = paginate(files, offset, limit);\n const excludeNote = `[Excluded: ${DEFAULT_EXCLUDES.join(', ')}${extra && extra.length > 0 ? ` + ${extra.join(', ')}` : ''}]`;\n const resultText = [\n `Found ${files.length} file(s) matching \"${pattern}\" in \"${directory}\" (showing ${page.page.length}, offset=${offset}, limit=${limit})`,\n excludeNote,\n '',\n ...page.page.map(f => ` ${f}`),\n page.hasMore ? '' : '',\n ].filter(s => s !== undefined).join('\\n');\n\n const continuationHint = page.hasMore\n ? `Next page: glob_search(pattern=\"${pattern}\", directory=\"${directory}\", offset=${page.nextOffset}, limit=${limit})`\n : '';\n\n return {\n success: true,\n output: trimOutput(resultText, MAX_OUTPUT_CHARS, continuationHint),\n metadata: {\n totalMatches: files.length,\n offset,\n limit,\n hasMore: page.hasMore,\n nextOffset: page.nextOffset,\n },\n };\n } catch (error) {\n if (error instanceof Error && 'killed' in error && error.killed) {\n return toolError({\n code: 'SEARCH_TIMEOUT',\n message: `Glob search timed out after ${SEARCH_TIMEOUT_MS / 1000}s.`,\n retryable: true,\n hint: 'Narrow directory/pattern or lower limit.',\n details: { directory, pattern, timeoutMs: SEARCH_TIMEOUT_MS },\n });\n }\n if ((error as { code?: string }).code === 'ENOBUFS') {\n return toolError({\n code: 'SEARCH_BUFFER_OVERFLOW',\n message: 'Search output exceeded buffer.',\n retryable: true,\n hint: 'Narrow directory/pattern or reduce limit.',\n details: { directory, pattern, offset, limit },\n });\n }\n return toolError({\n code: 'SEARCH_FAILED',\n message: `Glob search failed: ${error instanceof Error ? error.message : String(error)}`,\n retryable: true,\n hint: 'Check pattern syntax and directory.',\n details: { directory, pattern },\n });\n }\n },\n };\n}\n\n/**\n * Search for text in files (grep)\n */\nexport function createGrepSearchTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'grep_search',\n description: `Search for text/regex in files. Returns file:line matches. IMPORTANT: node_modules/, dist/, build/ excluded by default. Omit directory to search the entire working directory. Add filePattern (e.g. \"*.ts\") to limit to specific file types. Returns up to ${DEFAULT_RESULT_LIMIT} matches.`,\n parameters: {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: 'Text pattern to search for (can be regex)',\n },\n directory: {\n type: 'string',\n description: 'Directory to search in (default: working directory root). Narrow to a subfolder when you already know the scope.',\n },\n filePattern: {\n type: 'string',\n description: 'Filter by file extension (e.g., \"*.ts\", \"*.md\"). STRONGLY RECOMMENDED: always set this to avoid scanning binary/generated files.',\n },\n exclude: {\n type: 'array',\n items: { type: 'string' },\n description: 'Extra directories to exclude on top of defaults (node_modules, dist, .git, build, .next, .kb, .pnpm, coverage are always excluded). Rarely needed.',\n },\n mode: {\n type: 'string',\n enum: ['auto', 'regex', 'literal'],\n description: 'Search mode: auto (default), regex, or literal',\n },\n offset: {\n type: 'number',\n description: 'Result offset for pagination (default: 0)',\n },\n limit: {\n type: 'number',\n description: `Max matches per page (default: ${DEFAULT_RESULT_LIMIT}, max: ${MAX_RESULT_LIMIT})`,\n },\n },\n required: ['pattern'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const pattern = input.pattern as string;\n const directory = (input.directory as string) || '.';\n const filePattern = input.filePattern as string | undefined;\n const extra = input.exclude as string[] | undefined;\n const excludes = extra && extra.length > 0 ? [...new Set([...DEFAULT_EXCLUDES, ...extra])] : DEFAULT_EXCLUDES;\n const mode = ((input.mode as string) || 'auto').toLowerCase();\n const { offset, limit } = normalizeOffsetLimit(input);\n\n try {\n const fullPath = path.resolve(context.workingDir, directory);\n\n const dirError = validateDirectory(context.workingDir, directory);\n if (dirError) {\n return { success: true, output: dirError };\n }\n\n const windowSize = Math.min(2000, Math.max(500, offset + limit));\n\n const buildArgs = (literal: boolean): string[] => {\n const args: string[] = ['-rIn'];\n if (literal) {args.push('-F');}\n args.push(pattern, fullPath);\n args.push(...buildGrepExcludes(excludes));\n if (filePattern) {\n args.push(`--include=${filePattern}`);\n }\n return args;\n };\n\n let output = '';\n let usedLiteralFallback = false;\n\n const runGrep = async (literal: boolean): Promise<{ stdout: string; exitCode: number; stderr: string }> => {\n const res = await execa('grep', buildArgs(literal), {\n cwd: context.workingDir,\n reject: false,\n timeout: SEARCH_TIMEOUT_MS,\n });\n return { stdout: res.stdout, exitCode: res.exitCode ?? 0, stderr: res.stderr };\n };\n\n const initial = await runGrep(mode === 'literal');\n\n if (initial.exitCode === 2) {\n // exit code 2 = grep error (e.g. invalid regex)\n const looksLikeInvalidRegex = /(unbalanced|parentheses|invalid regular expression|regular expression)/i.test(initial.stderr);\n if (looksLikeInvalidRegex && mode !== 'regex') {\n // auto mode: fall back to literal\n usedLiteralFallback = true;\n const fallback = await runGrep(true);\n output = fallback.stdout;\n if (fallback.exitCode === 2) {\n return toolError({\n code: 'SEARCH_FAILED',\n message: `Grep search failed: ${fallback.stderr}`,\n retryable: true,\n hint: 'Try mode=\"literal\" for special characters, or narrow directory.',\n details: { directory, pattern, filePattern, mode },\n });\n }\n } else {\n return toolError({\n code: 'SEARCH_FAILED',\n message: `Grep search failed: ${initial.stderr}`,\n retryable: true,\n hint: 'Try mode=\"literal\" for special characters, or narrow directory.',\n details: { directory, pattern, filePattern, mode },\n });\n }\n } else {\n // exitCode 0 = matches found, exitCode 1 = no matches (grep convention)\n output = initial.stdout;\n }\n\n const lines = output.split('\\n').filter(Boolean).slice(0, windowSize);\n\n if (lines.length === 0) {\n return {\n success: true,\n output: `No matches found for \"${pattern}\" in ${directory === '.' ? 'project root' : directory}.${filePattern ? '' : ' Try adding filePattern (e.g. \"*.ts\") to narrow the search.'}`,\n };\n }\n\n const page = paginate(lines, offset, limit);\n const excludeNote = `[Excluded: ${DEFAULT_EXCLUDES.join(', ')}${extra && extra.length > 0 ? ` + ${extra.join(', ')}` : ''}]`;\n const resultText = [\n `Found ${lines.length} match(es) for \"${pattern}\" in \"${directory}\"${filePattern ? ` (${filePattern})` : ''}${usedLiteralFallback ? ' (literal fallback)' : ''} (showing ${page.page.length}, offset=${offset}, limit=${limit})`,\n excludeNote,\n '',\n ...page.page.map(line => {\n const match = line.match(/^(.+?):(\\d+):(.+)$/);\n if (match) {\n const [, filePath, lineNum, content] = match;\n const relPath = path.relative(context.workingDir, filePath!);\n return ` ${relPath}:${lineNum}\\n ${content!.trim()}`;\n }\n return ` ${line}`;\n }),\n page.hasMore ? '' : '',\n ].filter(s => s !== undefined).join('\\n');\n\n const continuationHint = page.hasMore\n ? `Next page: grep_search(pattern=\"${pattern}\", directory=\"${directory}\", offset=${page.nextOffset}, limit=${limit})`\n : '';\n\n return {\n success: true,\n output: trimOutput(resultText, MAX_OUTPUT_CHARS, continuationHint),\n metadata: {\n totalMatches: lines.length,\n offset,\n limit,\n hasMore: page.hasMore,\n nextOffset: page.nextOffset,\n modeUsed: usedLiteralFallback ? 'literal' : mode === 'auto' ? 'regex' : mode,\n },\n };\n } catch (error) {\n if (error instanceof Error && 'killed' in error && (error as Error & { killed?: boolean }).killed) {\n return toolError({\n code: 'SEARCH_TIMEOUT',\n message: `Grep search timed out after ${SEARCH_TIMEOUT_MS / 1000}s.`,\n retryable: true,\n hint: 'Narrow directory, add filePattern, or lower limit.',\n details: { directory, pattern, timeoutMs: SEARCH_TIMEOUT_MS },\n });\n }\n if ((error as { code?: string }).code === 'ENOBUFS') {\n return toolError({\n code: 'SEARCH_BUFFER_OVERFLOW',\n message: 'Search output exceeded buffer.',\n retryable: true,\n hint: 'Narrow directory, add filePattern, or reduce limit.',\n details: { directory, pattern, filePattern, offset, limit, mode },\n });\n }\n\n return toolError({\n code: 'SEARCH_FAILED',\n message: `Grep search failed: ${error instanceof Error ? error.message : String(error)}`,\n retryable: true,\n hint: 'Try mode=\"literal\" for special characters, or narrow directory.',\n details: { directory, pattern, filePattern, mode },\n });\n }\n },\n };\n}\n\n/**\n * List files in directory\n */\nexport function createListFilesTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'list_files',\n description: 'List files and directories at a path. Good for exploring what exists.',\n parameters: {\n type: 'object',\n properties: {\n directory: {\n type: 'string',\n description: 'Directory to list (default: \".\" for current directory)',\n },\n recursive: {\n type: 'boolean',\n description: 'Include subdirectories (default: false)',\n },\n offset: {\n type: 'number',\n description: 'Result offset for pagination (default: 0)',\n },\n limit: {\n type: 'number',\n description: `Max results per page (default: ${DEFAULT_RESULT_LIMIT}, max: ${MAX_RESULT_LIMIT})`,\n },\n },\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const directory = (input.directory as string) || '.';\n const recursive = (input.recursive as boolean) || false;\n const { offset, limit } = normalizeOffsetLimit(input);\n\n try {\n const fullPath = path.resolve(context.workingDir, directory);\n\n if (recursive) {\n const args = [\n fullPath,\n '-type', 'f',\n '!', '-path', '*/node_modules/*',\n '!', '-path', '*/.git/*',\n '!', '-path', '*/dist/*',\n '!', '-path', '*/.kb/*',\n ];\n\n const result = await execa('find', args, {\n cwd: context.workingDir,\n reject: false,\n timeout: SEARCH_TIMEOUT_MS,\n });\n\n const files = result.stdout\n .split('\\n')\n .filter(Boolean)\n .slice(0, 100)\n .map(f => path.relative(context.workingDir, f));\n\n const page = paginate(files, offset, limit);\n return {\n success: true,\n output: files.length > 0\n ? `Files in ${directory} (recursive, showing ${page.page.length}/${files.length}, offset=${offset}, limit=${limit}):\\n\\n${page.page.map(f => ` ${f}`).join('\\n')}${page.hasMore ? `\\n\\nNext page: list_files(directory=\"${directory}\", recursive=true, offset=${page.nextOffset}, limit=${limit})` : ''}`\n : `No files found in ${directory}`,\n metadata: {\n totalMatches: files.length,\n offset,\n limit,\n hasMore: page.hasMore,\n nextOffset: page.nextOffset,\n },\n };\n }\n\n // Non-recursive: use fs.readdirSync to avoid shell entirely\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(fullPath, { withFileTypes: true });\n } catch {\n return {\n success: true,\n output: 'Directory not found',\n };\n }\n\n const lines = entries\n .sort((a, b) => a.name.localeCompare(b.name))\n .map(e => {\n const indicator = e.isDirectory() ? '/' : e.isSymbolicLink() ? '@' : '';\n return `${e.name}${indicator}`;\n });\n\n return {\n success: true,\n output: `Contents of ${directory}:\\n\\n${lines.join('\\n')}`,\n };\n } catch (error) {\n return {\n success: false,\n error: `List files failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n },\n };\n}\n\n/**\n * Find files containing specific code pattern (semantic search)\n * Language-agnostic - works with any programming language\n */\nexport function createFindDefinitionTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'find_definition',\n description: 'Find where a symbol (class, function, interface, type, etc.) is defined. Works with any language. Uses project root as default directory, which works well for monorepos with nested packages.',\n parameters: {\n type: 'object',\n properties: {\n name: {\n type: 'string',\n description: 'Name of the symbol to find (class, function, interface, type, struct, etc.)',\n },\n directory: {\n type: 'string',\n description: 'Directory to search in (default: \".\")',\n },\n filePattern: {\n type: 'string',\n description: 'File pattern to search (e.g., \"*.cs\" for C#, \"*.py\" for Python). If not specified, searches all source files.',\n },\n },\n required: ['name'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const name = input.name as string;\n const directory = (input.directory as string) || '.';\n const filePattern = input.filePattern as string | undefined;\n\n try {\n const fullPath = path.resolve(context.workingDir, directory);\n\n const dirError = validateDirectory(context.workingDir, directory);\n if (dirError) {\n return { success: true, output: dirError };\n }\n\n // Language-agnostic definition patterns\n const patterns = [\n // Common across languages\n `class ${name}`,\n `interface ${name}`,\n `struct ${name}`,\n `enum ${name}`,\n // TypeScript/JavaScript\n `function ${name}`,\n `const ${name}`,\n `let ${name}`,\n `var ${name}`,\n `type ${name}`,\n `export.*${name}`,\n // Python\n `def ${name}`,\n // C#/Java\n `public.*${name}`,\n `private.*${name}`,\n `protected.*${name}`,\n `static.*${name}`,\n // Go\n `func ${name}`,\n `func \\\\(.*\\\\) ${name}`,\n // Rust\n `fn ${name}`,\n `impl ${name}`,\n `trait ${name}`,\n `mod ${name}`,\n ];\n\n // Build include flags for grep\n let includeArgs: string[];\n if (filePattern) {\n includeArgs = [`--include=${filePattern}`];\n } else {\n // Default: search common source file extensions\n includeArgs = toRgIncludesArgs(ALL_SOURCE_EXTENSIONS);\n }\n\n const args = [\n '-rn', '-E',\n `(${patterns.join('|')})`,\n fullPath,\n ...includeArgs,\n ...buildGrepExcludes(DEFAULT_EXCLUDES),\n '--exclude-dir=bin',\n '--exclude-dir=obj',\n '--exclude-dir=target',\n ];\n\n const result = await execa('grep', args, {\n cwd: context.workingDir,\n reject: false,\n timeout: SEARCH_TIMEOUT_MS,\n });\n\n const lines = result.stdout.split('\\n').filter(Boolean).slice(0, 30);\n\n if (lines.length === 0) {\n return {\n success: true,\n output: `No definition found for \"${name}\" in ${directory === '.' ? 'project root' : directory}. Try: grep_search for text matching, or glob_search with \"*${name.toLowerCase()}*\" for filename matching.`,\n };\n }\n\n const resultLines = lines.map(line => {\n const match = line.match(/^(.+?):(\\d+):(.+)$/);\n if (match) {\n const [, filePath, lineNum, content] = match;\n const relPath = path.relative(context.workingDir, filePath!);\n return `${relPath}:${lineNum}\\n ${content!.trim()}`;\n }\n return line;\n });\n\n return {\n success: true,\n output: `Found definition(s) for \"${name}\":\\n\\n${resultLines.join('\\n\\n')}`,\n };\n } catch (error) {\n if (error instanceof Error && 'killed' in error && (error as Error & { killed?: boolean }).killed) {\n return {\n success: false,\n error: `Find definition timed out after ${SEARCH_TIMEOUT_MS / 1000}s. Try specifying a narrower directory.`,\n };\n }\n return {\n success: false,\n error: `Find definition failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n },\n };\n}\n\n/**\n * Get project structure overview — level-by-level exploration\n */\nexport function createProjectStructureTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'project_structure',\n description: 'Show directory contents at a given path. Defaults to project root, depth 1. Use to explore the codebase incrementally — first see top-level, then drill into specific directories.',\n parameters: {\n type: 'object',\n properties: {\n targetPath: {\n type: 'string',\n description: 'Directory to explore (default: project root). Use to drill deeper into a specific folder.',\n },\n depth: {\n type: 'number',\n description: 'How many levels deep (default: 1, max: 3)',\n },\n },\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const depth = Math.min((input.depth as number) || 1, 3);\n const targetPath = (input.targetPath as string) || '.';\n\n // Resolve and validate target path\n const resolvedPath = path.resolve(context.workingDir, targetPath);\n if (!resolvedPath.startsWith(context.workingDir)) {\n return {\n success: false,\n error: 'Cannot access paths outside project directory.',\n };\n }\n\n if (!fs.existsSync(resolvedPath) || !fs.statSync(resolvedPath).isDirectory()) {\n return {\n success: false,\n error: `\"${targetPath}\" is not a directory or does not exist.`,\n };\n }\n\n try {\n const skipNames = new Set(['node_modules', '.git', 'dist', '.next', 'build']);\n const lines: string[] = [];\n\n function listLevel(dir: string, prefix: string, currentDepth: number): void {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(dir, { withFileTypes: true });\n } catch {\n return;\n }\n\n // Separate dirs and files, sort each group\n const dirs = entries.filter(e => e.isDirectory() && !skipNames.has(e.name)).sort((a, b) => a.name.localeCompare(b.name));\n const files = entries.filter(e => e.isFile()).sort((a, b) => a.name.localeCompare(b.name));\n\n // Show directories with child counts\n for (const d of dirs) {\n const fullPath = path.join(dir, d.name);\n let childDirs = 0;\n let childFiles = 0;\n try {\n const children = fs.readdirSync(fullPath, { withFileTypes: true });\n childDirs = children.filter(c => c.isDirectory() && !skipNames.has(c.name)).length;\n childFiles = children.filter(c => c.isFile()).length;\n } catch {\n // inaccessible\n }\n const info = `${childDirs} dirs, ${childFiles} files`;\n lines.push(`${prefix}${d.name}/ (${info})`);\n\n if (currentDepth < depth) {\n listLevel(fullPath, prefix + ' ', currentDepth + 1);\n }\n }\n\n // Show files (only at requested depth, not intermediate levels for brevity)\n if (currentDepth === 1 || depth === 1) {\n for (const f of files) {\n lines.push(`${prefix}${f.name}`);\n }\n }\n }\n\n listLevel(resolvedPath, '', 1);\n\n const relPath = path.relative(context.workingDir, resolvedPath) || '.';\n const header = `${relPath}/ (depth ${depth})`;\n\n return {\n success: true,\n output: `${header}\\n\\n${lines.join('\\n')}`,\n };\n } catch (error) {\n return {\n success: false,\n error: `Project structure failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n },\n };\n}\n\n/**\n * Count lines of code - language agnostic\n */\nexport function createCodeStatsTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'code_stats',\n description: 'Get line counts and file counts by extension for a directory scope (not single-file line counts).',\n parameters: {\n type: 'object',\n properties: {\n directory: {\n type: 'string',\n description: 'Directory to analyze (default: \".\"). If a file path is provided by mistake, use its parent directory.',\n },\n extensions: {\n type: 'string',\n description: 'Comma-separated list of extensions to count (e.g., \"ts,tsx,js\" or \"cs,csproj\" or \"py\"). If not specified, counts all source files.',\n },\n offset: {\n type: 'number',\n description: 'Offset for extension summary rows (default: 0)',\n },\n limit: {\n type: 'number',\n description: `Rows per page for extension summary (default: ${DEFAULT_RESULT_LIMIT}, max: ${MAX_RESULT_LIMIT})`,\n },\n },\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const directory = (input.directory as string) || '.';\n const extensionsInput = input.extensions as string | undefined;\n const { offset, limit } = normalizeOffsetLimit(input);\n\n try {\n const fullPath = path.resolve(context.workingDir, directory);\n\n const dirError = validateDirectory(context.workingDir, directory);\n if (dirError) {\n return { success: true, output: dirError };\n }\n\n // Build extension filter args\n let extFilterArgs: string[];\n if (extensionsInput) {\n const exts = extensionsInput.split(',').map(e => e.trim());\n extFilterArgs = toFindNamesArgs(exts);\n } else {\n extFilterArgs = toFindNamesArgs(ALL_SOURCE_EXTENSIONS);\n }\n\n const commonExcludes = [\n '!', '-path', '*/node_modules/*',\n '!', '-path', '*/dist/*',\n '!', '-path', '*/.git/*',\n '!', '-path', '*/bin/*',\n '!', '-path', '*/obj/*',\n '!', '-path', '*/target/*',\n '!', '-path', '*/__pycache__/*',\n ];\n\n // Find matching files (used as base for all three queries)\n const findArgs = [\n fullPath,\n '-type', 'f',\n '(',\n ...extFilterArgs,\n ')',\n ...commonExcludes,\n ];\n\n const findResult = await execa('find', findArgs, {\n cwd: context.workingDir,\n reject: false,\n timeout: SEARCH_TIMEOUT_MS,\n });\n\n const filePaths = findResult.stdout.split('\\n').filter(Boolean);\n\n // Count total files\n const fileCount = filePaths.length;\n\n // Count by extension using JS\n const extCounts = new Map<string, number>();\n for (const fp of filePaths) {\n const ext = fp.includes('.') ? fp.split('.').pop()! : '(no ext)';\n extCounts.set(ext, (extCounts.get(ext) ?? 0) + 1);\n }\n const countByExt = [...extCounts.entries()]\n .sort((a, b) => b[1] - a[1])\n .slice(0, 200)\n .map(([ext, count]) => ` ${count} ${ext}`);\n\n // Count total lines using wc -l on found files (batch call)\n let totalOutput = '0 total';\n if (filePaths.length > 0) {\n const wcResult = await execa('wc', ['-l', ...filePaths], {\n cwd: context.workingDir,\n reject: false,\n });\n // wc -l outputs a total line at the end when given multiple files\n const wcLines = wcResult.stdout.trim().split('\\n').filter(Boolean);\n const lastLine = wcLines[wcLines.length - 1] ?? '';\n totalOutput = lastLine.trim();\n }\n\n const page = paginate(countByExt, offset, limit);\n return {\n success: true,\n output: `Code statistics for directory ${directory}:\\n\\nTotal lines: ${totalOutput}\\nTotal files: ${fileCount}\\n\\nFiles by extension (showing ${page.page.length}/${countByExt.length}, offset=${offset}, limit=${limit}):\\n${page.page.join('\\n')}${page.hasMore ? `\\n\\nNext page: code_stats(directory=\"${directory}\", offset=${page.nextOffset}, limit=${limit})` : ''}\\n\\nNote: This is directory-level aggregate. For a single file line count, use fs_read on that file and rely on metadata.totalLines.`,\n metadata: {\n totalExtensionRows: countByExt.length,\n offset,\n limit,\n hasMore: page.hasMore,\n nextOffset: page.nextOffset,\n },\n };\n } catch (error) {\n return toolError({\n code: 'CODE_STATS_FAILED',\n message: `Code stats failed: ${error instanceof Error ? error.message : String(error)}`,\n retryable: true,\n hint: 'Narrow directory or provide extensions.',\n details: { directory, extensions: extensionsInput },\n });\n }\n },\n };\n}\n","/**\n * Memory tools for persistent context and session management\n *\n * ARCHITECTURE:\n * - Shared memory (.kb/memory/shared/) - persistent across sessions\n * - preferences: user preferences (e.g., \"use TypeScript strict mode\")\n * - constraints: project rules (e.g., \"never modify /legacy/\")\n *\n * - Session memory (.kb/memory/session-xxx/) - handled by FileMemory\n * - corrections: user corrections for current session\n * - findings: agent discoveries\n * - blockers: current blockers\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { Tool, ToolContext } from '../../types.js';\nimport type { MemoryEntry, SessionEntry } from '@kb-labs/agent-contracts';\n\n/**\n * Shared memory structure (persistent)\n */\ninterface SharedMemory {\n preferences: MemoryEntry[];\n constraints: MemoryEntry[];\n sessions: SessionEntry[];\n projectContext: {\n name: string;\n description: string;\n technologies: string[];\n structure: string;\n };\n}\n\n/**\n * Get memory file path\n * Uses .kb/memory/shared/ for cross-session persistent memory\n */\nfunction getMemoryPath(context: ToolContext): string {\n // Use .kb/memory/shared/ for persistent memory across sessions\n const memoryDir = path.join(context.workingDir, '.kb', 'memory', 'shared');\n if (!fs.existsSync(memoryDir)) {\n fs.mkdirSync(memoryDir, { recursive: true });\n }\n return path.join(memoryDir, 'memory.json');\n}\n\n/**\n * Load shared memory from disk\n */\nfunction loadSharedMemory(context: ToolContext): SharedMemory {\n const memoryPath = getMemoryPath(context);\n\n const defaultMemory: SharedMemory = {\n preferences: [],\n constraints: [],\n sessions: [],\n projectContext: {\n name: '',\n description: '',\n technologies: [],\n structure: '',\n },\n };\n\n if (!fs.existsSync(memoryPath)) {\n return defaultMemory;\n }\n\n try {\n const content = fs.readFileSync(memoryPath, 'utf-8');\n const parsed = JSON.parse(content);\n\n // Migration: convert old format (facts array) to new format\n if (parsed.facts && Array.isArray(parsed.facts)) {\n const preferences = parsed.facts.filter((f: MemoryEntry) => f.type === 'user_preference');\n const constraints = parsed.facts.filter((f: MemoryEntry) => f.type === 'constraint');\n return {\n preferences,\n constraints,\n sessions: parsed.sessions || [],\n projectContext: parsed.projectContext || defaultMemory.projectContext,\n };\n }\n\n return {\n ...defaultMemory,\n ...parsed,\n };\n } catch {\n return defaultMemory;\n }\n}\n\n/**\n * Save shared memory to disk\n */\nfunction saveSharedMemory(context: ToolContext, memory: SharedMemory): void {\n const memoryPath = getMemoryPath(context);\n fs.writeFileSync(memoryPath, JSON.stringify(memory, null, 2), 'utf-8');\n}\n\nasync function loadCanonicalSessionMemory(context: ToolContext): Promise<{\n constraints: string[];\n corrections: string[];\n}> {\n if (!context.sessionMemory) {\n return { constraints: [], corrections: [] };\n }\n\n const kernel = await context.sessionMemory.loadKernelState();\n if (!kernel) {\n return { constraints: [], corrections: [] };\n }\n\n return {\n constraints: kernel.constraints,\n corrections: kernel.memory.corrections.map((item) => item.content),\n };\n}\n\n/**\n * Get shared memory (preferences, constraints, project context)\n */\nexport function createMemoryGetTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'memory_get',\n description:\n 'Get stored user preferences, project constraints, and session history.',\n parameters: {\n type: 'object',\n properties: {\n sessionId: {\n type: 'string',\n description: 'Optional session ID to get specific session context',\n },\n },\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const sessionId = input.sessionId as string | undefined;\n const memory = loadSharedMemory(context);\n const canonicalSession = await loadCanonicalSessionMemory(context);\n\n // Format preferences\n const preferencesText =\n memory.preferences.length > 0\n ? memory.preferences.map((p) => `- ${p.content}`).join('\\n')\n : 'No preferences set';\n\n // Format constraints\n const constraintsText =\n memory.constraints.length > 0\n ? memory.constraints.map((c) => `- ${c.content}`).join('\\n')\n : 'No constraints set';\n\n const sessionConstraintsText =\n canonicalSession.constraints.length > 0\n ? canonicalSession.constraints.map((item) => `- ${item}`).join('\\n')\n : 'No session constraints set';\n\n const sessionCorrectionsText =\n canonicalSession.corrections.length > 0\n ? canonicalSession.corrections.map((item) => `- ${item}`).join('\\n')\n : 'No session corrections recorded';\n\n // Format sessions\n const sessions = sessionId\n ? memory.sessions.filter((s) => s.sessionId === sessionId)\n : memory.sessions.slice(-5);\n\n const sessionInfo = sessions\n .map((s) => {\n const tasks = s.tasks.join(', ');\n return `Session ${s.sessionId} (${s.timestamp}):\\n Tasks: ${tasks}\\n Learnings: ${s.learnings}`;\n })\n .join('\\n\\n');\n\n const output = [\n '=== Shared Memory ===',\n '',\n '## 👤 User Preferences (persistent)',\n preferencesText,\n '',\n '## 🚫 Constraints (persistent)',\n constraintsText,\n '',\n '## Session Constraints (canonical)',\n sessionConstraintsText,\n '',\n '## Session Corrections (canonical)',\n sessionCorrectionsText,\n '',\n '## Project Context',\n `Name: ${memory.projectContext.name || 'Unknown'}`,\n `Description: ${memory.projectContext.description || 'N/A'}`,\n `Technologies: ${memory.projectContext.technologies.join(', ') || 'N/A'}`,\n '',\n '## Session History',\n sessionInfo || 'No sessions yet',\n '',\n '---',\n 'Note: Corrections, findings, and blockers are stored in session memory.',\n ].join('\\n');\n\n return {\n success: true,\n output,\n };\n },\n };\n}\n\n/**\n * Add user preference to shared memory (persistent)\n */\nexport function createMemoryPreferenceTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'memory_preference',\n description:\n 'Store a persistent user preference (coding style, tool choices, etc.).',\n parameters: {\n type: 'object',\n properties: {\n content: {\n type: 'string',\n description: 'The preference to store (e.g., \"Always use TypeScript strict mode\")',\n },\n tags: {\n type: 'array',\n items: { type: 'string' },\n description: 'Optional tags for categorization (e.g., [\"typescript\", \"style\"])',\n },\n },\n required: ['content'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const content = input.content as string;\n const tags = input.tags as string[] | undefined;\n\n const memory = loadSharedMemory(context);\n\n const preference: MemoryEntry = {\n content,\n category: 'user_input',\n timestamp: new Date().toISOString(),\n type: 'user_preference',\n metadata: {\n importance: 0.9,\n source: 'user',\n scope: 'project',\n tags,\n },\n };\n\n memory.preferences.push(preference);\n\n // Keep only last 50 preferences\n if (memory.preferences.length > 50) {\n memory.preferences = memory.preferences.slice(-50);\n }\n\n saveSharedMemory(context, memory);\n\n return {\n success: true,\n output: `👤 Preference stored: ${content}`,\n };\n },\n };\n}\n\n/**\n * Add constraint to shared memory (persistent)\n */\nexport function createMemoryConstraintTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'memory_constraint',\n description:\n 'Store a persistent project constraint or rule. Use this for durable project-wide rules, not session-only instructions.',\n parameters: {\n type: 'object',\n properties: {\n content: {\n type: 'string',\n description: 'The constraint (e.g., \"Do not modify files in /legacy/ directory\")',\n },\n },\n required: ['content'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const content = input.content as string;\n\n if (context.sessionMemory) {\n await context.sessionMemory.recordConstraint(content);\n }\n\n const memory = loadSharedMemory(context);\n\n const constraint: MemoryEntry = {\n content,\n category: 'project_rules',\n timestamp: new Date().toISOString(),\n type: 'constraint',\n metadata: {\n importance: 1.0,\n source: 'user',\n scope: 'project',\n },\n };\n\n memory.constraints.push(constraint);\n\n // Keep only last 50 constraints\n if (memory.constraints.length > 50) {\n memory.constraints = memory.constraints.slice(-50);\n }\n\n saveSharedMemory(context, memory);\n\n return {\n success: true,\n output: `🚫 Constraint stored: ${content}`,\n };\n },\n };\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Session Memory Tools - corrections, findings, blockers (session-scoped)\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Get session memory directory path\n * Creates directory if it doesn't exist\n */\nfunction getSessionMemoryPath(context: ToolContext, sessionId?: string): string {\n const id = sessionId || `session-${Date.now()}`;\n const sessionDir = path.join(context.workingDir, '.kb', 'memory', id);\n if (!fs.existsSync(sessionDir)) {\n fs.mkdirSync(sessionDir, { recursive: true });\n }\n return sessionDir;\n}\n\n/**\n * Save entry to session memory\n */\nfunction saveToSession(context: ToolContext, entry: MemoryEntry, sessionId?: string): void {\n const sessionDir = getSessionMemoryPath(context, sessionId);\n const entryId = `mem-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;\n const filePath = path.join(sessionDir, `${entryId}.json`);\n fs.writeFileSync(filePath, JSON.stringify({ ...entry, id: entryId }, null, 2), 'utf-8');\n}\n\n/**\n * Add user correction to session memory\n * Session-scoped - only valid for current session\n */\nexport function createMemoryCorrectionTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'memory_correction',\n description:\n 'Store a user correction for the current session. Use this immediately after the user corrects you or changes active instructions. Set constraint=true if the correction should remain an active session constraint.',\n parameters: {\n type: 'object',\n properties: {\n content: {\n type: 'string',\n description:\n 'The correction (e.g., \"AuthService is in packages/auth/, not src/services/\")',\n },\n supersedes: {\n type: 'string',\n description: 'Optional: what this correction replaces',\n },\n invalidates: {\n type: 'array',\n items: { type: 'string' },\n description: 'Optional: assumption IDs invalidated by this correction',\n },\n constraint: {\n type: 'boolean',\n description: 'Set true if this correction should also become an active session constraint',\n },\n sessionId: {\n type: 'string',\n description: 'Optional: session ID (defaults to current timestamp-based session)',\n },\n },\n required: ['content'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const content = input.content as string;\n const supersedes = input.supersedes as string | undefined;\n const invalidates = Array.isArray(input.invalidates)\n ? input.invalidates.filter((item): item is string => typeof item === 'string' && item.trim().length > 0)\n : [];\n const asConstraint = input.constraint === true;\n const sessionId = input.sessionId as string | undefined;\n\n if (context.sessionMemory) {\n await context.sessionMemory.recordCorrection({\n content,\n invalidates,\n asConstraint,\n });\n }\n\n const correction: MemoryEntry = {\n content,\n category: 'user_input',\n timestamp: new Date().toISOString(),\n type: 'user_correction',\n metadata: {\n importance: 1.0,\n source: 'user',\n supersedes,\n scope: 'session',\n },\n };\n\n saveToSession(context, correction, sessionId);\n\n const supersedesInfo = supersedes ? ` (replaces: ${supersedes})` : '';\n const constraintInfo = asConstraint ? ' [active session constraint]' : '';\n return {\n success: true,\n output: `⚠️ Correction stored in session${supersedesInfo}${constraintInfo}: ${content}`,\n };\n },\n };\n}\n\n/**\n * Add finding to session memory\n */\nexport function createMemoryFindingTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'memory_finding',\n description:\n 'Store a codebase finding with confidence level (session-scoped).',\n parameters: {\n type: 'object',\n properties: {\n content: {\n type: 'string',\n description: 'The finding (e.g., \"All services use Repository pattern\")',\n },\n confidence: {\n type: 'number',\n description: 'Confidence level 0-1 (e.g., 0.9 for high confidence)',\n },\n sources: {\n type: 'array',\n items: { type: 'string' },\n description: 'Source files that support this finding',\n },\n sessionId: {\n type: 'string',\n description: 'Optional: session ID',\n },\n },\n required: ['content', 'confidence'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const content = input.content as string;\n const confidence = input.confidence as number;\n const sources = input.sources as string[] | undefined;\n const sessionId = input.sessionId as string | undefined;\n\n const finding: MemoryEntry = {\n content,\n category: 'learning',\n timestamp: new Date().toISOString(),\n type: 'finding',\n metadata: {\n importance: confidence,\n confidence,\n source: 'agent',\n tags: sources,\n scope: 'session',\n },\n };\n\n saveToSession(context, finding, sessionId);\n\n return {\n success: true,\n output: `🔍 Finding stored (confidence: ${(confidence * 100).toFixed(0)}%): ${content}`,\n };\n },\n };\n}\n\n/**\n * Add blocker to session memory\n */\nexport function createMemoryBlockerTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'memory_blocker',\n description:\n 'Store a blocker that prevents progress (session-scoped).',\n parameters: {\n type: 'object',\n properties: {\n content: {\n type: 'string',\n description: 'The blocker (e.g., \"Cannot find database config. Need DATABASE_URL\")',\n },\n taskId: {\n type: 'string',\n description: 'Optional: related task ID',\n },\n sessionId: {\n type: 'string',\n description: 'Optional: session ID',\n },\n },\n required: ['content'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const content = input.content as string;\n const taskId = input.taskId as string | undefined;\n const sessionId = input.sessionId as string | undefined;\n\n const blocker: MemoryEntry = {\n content,\n category: 'agent_state',\n timestamp: new Date().toISOString(),\n type: 'blocker',\n metadata: {\n importance: 1.0,\n source: 'agent',\n taskId,\n scope: 'session',\n },\n };\n\n saveToSession(context, blocker, sessionId);\n\n return {\n success: true,\n output: `🛑 Blocker stored: ${content}`,\n };\n },\n };\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Session Summary Tool\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Save session summary (shared)\n */\nexport function createSessionSaveTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'session_save',\n description:\n 'Save session summary and learnings to persistent memory.',\n parameters: {\n type: 'object',\n properties: {\n sessionId: {\n type: 'string',\n description: 'Session identifier',\n },\n tasks: {\n type: 'array',\n items: { type: 'string' },\n description: 'List of tasks completed in this session',\n },\n learnings: {\n type: 'string',\n description: 'Summary of what was learned or discovered',\n },\n },\n required: ['sessionId', 'tasks', 'learnings'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const sessionId = input.sessionId as string;\n const tasks = input.tasks as string[];\n const learnings = input.learnings as string;\n\n const memory = loadSharedMemory(context);\n\n const session: SessionEntry = {\n sessionId,\n timestamp: new Date().toISOString(),\n tasks,\n learnings,\n };\n\n memory.sessions.push(session);\n\n // Keep only last 50 sessions\n if (memory.sessions.length > 50) {\n memory.sessions = memory.sessions.slice(-50);\n }\n\n saveSharedMemory(context, memory);\n\n return {\n success: true,\n output: `Session ${sessionId} saved with ${tasks.length} task(s)`,\n };\n },\n };\n}\n","/**\n * archive_recall tool - Retrieve full content from previously-read files\n * or tool outputs WITHOUT re-reading them.\n *\n * This is the agent's interface to Tier 2 (Cold Storage / ArchiveMemory).\n */\n\nimport type { ToolResult } from '@kb-labs/agent-contracts';\nimport type { Tool, ToolContext } from '../../types.js';\n\nexport function createArchiveRecallTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'archive_recall',\n description:\n 'Retrieve full content from previously-read files or tool outputs WITHOUT re-reading them. ' +\n 'Use this to recall file contents, grep results, or any tool output from earlier iterations. ' +\n 'Specify exactly one query mode: file_path, keyword, list_files, tool_name, or iteration.',\n parameters: {\n type: 'object',\n properties: {\n file_path: {\n type: 'string',\n description: 'Recall the last read of this file (full content)',\n },\n keyword: {\n type: 'string',\n description: 'Search across all archived outputs for this keyword',\n },\n list_files: {\n type: 'boolean',\n description: 'List all file paths that have been archived',\n },\n tool_name: {\n type: 'string',\n description: 'Recall recent outputs of a specific tool (e.g., grep_search)',\n },\n iteration: {\n type: 'number',\n description: 'Recall all tool outputs from a specific iteration number',\n },\n limit: {\n type: 'number',\n description: 'Maximum number of results to return (default: 5)',\n },\n },\n },\n },\n },\n executor: async (input: Record<string, unknown>): Promise<ToolResult> => {\n const archive = context.archiveMemory;\n if (!archive) {\n return {\n success: false,\n error: 'Archive memory not available. This tool requires the two-tier memory system.',\n };\n }\n\n const limit = (input.limit as number) || 5;\n\n // Mode 1: Recall file content\n if (input.file_path) {\n const filePath = input.file_path as string;\n const entry = archive.recallByFilePath(filePath);\n if (!entry) {\n return {\n success: false,\n output: `File not found in archive: ${filePath}\\n\\nArchived files:\\n${archive.getArchivedFilePaths().join('\\n') || '(none)'}`,\n };\n }\n return {\n success: true,\n output: `[Archive] File: ${filePath} (read in iteration ${entry.iteration} via ${entry.toolName})\\n\\n${entry.fullOutput}`,\n };\n }\n\n // Mode 2: Keyword search\n if (input.keyword) {\n const keyword = input.keyword as string;\n const results = archive.search(keyword, limit);\n if (results.length === 0) {\n return {\n success: true,\n output: `No archived outputs contain \"${keyword}\"`,\n };\n }\n const formatted = results\n .map((r, i) => {\n const fileInfo = r.filePath ? ` (file: ${r.filePath})` : '';\n const preview = r.fullOutput.length > 500\n ? r.fullOutput.substring(0, 500) + `\\n... (${r.fullOutput.length} chars total)`\n : r.fullOutput;\n return `--- Result ${i + 1}: ${r.toolName} @ iter ${r.iteration}${fileInfo} ---\\n${preview}`;\n })\n .join('\\n\\n');\n return {\n success: true,\n output: `[Archive] Found ${results.length} result(s) for \"${keyword}\":\\n\\n${formatted}`,\n };\n }\n\n // Mode 3: List files\n if (input.list_files) {\n const files = archive.getArchivedFilePaths();\n if (files.length === 0) {\n return { success: true, output: 'No files archived yet.' };\n }\n return {\n success: true,\n output: `[Archive] ${files.length} file(s) archived:\\n${files.join('\\n')}`,\n };\n }\n\n // Mode 4: By tool name\n if (input.tool_name) {\n const toolName = input.tool_name as string;\n const results = archive.recallByToolName(toolName, limit);\n if (results.length === 0) {\n return {\n success: true,\n output: `No archived outputs for tool \"${toolName}\"`,\n };\n }\n const formatted = results\n .map((r, i) => {\n const fileInfo = r.filePath ? ` (file: ${r.filePath})` : '';\n const preview = r.fullOutput.length > 500\n ? r.fullOutput.substring(0, 500) + `\\n... (${r.fullOutput.length} chars total)`\n : r.fullOutput;\n return `--- ${toolName} #${i + 1} @ iter ${r.iteration}${fileInfo} ---\\n${preview}`;\n })\n .join('\\n\\n');\n return {\n success: true,\n output: `[Archive] ${results.length} output(s) from \"${toolName}\":\\n\\n${formatted}`,\n };\n }\n\n // Mode 5: By iteration\n if (input.iteration !== undefined) {\n const iteration = input.iteration as number;\n const results = archive.recallByIteration(iteration);\n if (results.length === 0) {\n return {\n success: true,\n output: `No archived outputs from iteration ${iteration}`,\n };\n }\n const formatted = results\n .map((r, i) => {\n const fileInfo = r.filePath ? ` (file: ${r.filePath})` : '';\n const preview = r.fullOutput.length > 500\n ? r.fullOutput.substring(0, 500) + `\\n... (${r.fullOutput.length} chars total)`\n : r.fullOutput;\n return `--- ${r.toolName} #${i + 1}${fileInfo} ---\\n${preview}`;\n })\n .join('\\n\\n');\n return {\n success: true,\n output: `[Archive] ${results.length} output(s) from iteration ${iteration}:\\n\\n${formatted}`,\n };\n }\n\n return {\n success: false,\n error: 'Specify at least one query parameter: file_path, keyword, list_files, tool_name, or iteration',\n };\n },\n };\n}\n","/**\n * TODO tools for task planning and progress tracking\n */\n\nimport type { Tool, ToolContext } from '../../types.js';\nimport type { TodoList, TodoItem } from '@kb-labs/agent-contracts';\nimport { toolError } from '../shared/tool-error.js';\nimport { TODO_CONFIG } from '../../config.js';\n\n// In-memory TODO storage (session-scoped)\nconst todoLists = new Map<string, TodoList>();\nconst TODO_CACHE_PREFIX = TODO_CONFIG.cachePrefix;\nconst TODO_CACHE_TTL_MS = TODO_CONFIG.cacheTtlMs;\n\n/**\n * Get a summary of the todo list for a session.\n * Used by Status Block (FactSheetMiddleware) to display todo progress.\n */\nexport function getTodoSummary(sessionId: string): { completed: number; total: number; inProgress: number; pending: number; blocked: number } | null {\n const list = todoLists.get(sessionId);\n if (!list || list.items.length === 0) {return null;}\n return {\n completed: list.items.filter(i => i.status === 'completed').length,\n inProgress: list.items.filter(i => i.status === 'in-progress').length,\n pending: list.items.filter(i => i.status === 'pending').length,\n blocked: list.items.filter(i => i.status === 'blocked').length,\n total: list.items.length,\n };\n}\n\nfunction getTodoCacheKey(sessionId: string): string {\n return `${TODO_CACHE_PREFIX}${sessionId}`;\n}\n\nasync function loadTodoList(context: ToolContext, sessionId: string): Promise<TodoList | null> {\n if (context.cache) {\n const cached = await context.cache.get<TodoList>(getTodoCacheKey(sessionId));\n if (cached) {\n todoLists.set(sessionId, cached);\n return cached;\n }\n }\n return todoLists.get(sessionId) ?? null;\n}\n\nasync function persistTodoList(context: ToolContext, todoList: TodoList): Promise<void> {\n todoLists.set(todoList.sessionId, todoList);\n if (context.cache) {\n await context.cache.set(getTodoCacheKey(todoList.sessionId), todoList, TODO_CACHE_TTL_MS);\n }\n}\n\nfunction resolveTodoItem(todoList: TodoList, sessionId: string, itemId: string): TodoItem | null {\n const direct = todoList.items.find((i) => i.id === itemId);\n if (direct) {\n return direct;\n }\n\n const asIndex = Number(itemId);\n if (Number.isFinite(asIndex) && asIndex >= 1) {\n const indexed = todoList.items.find((i) => i.id === `${sessionId}-${Math.floor(asIndex)}`);\n if (indexed) {\n return indexed;\n }\n }\n\n const normalized = itemId.trim().toLowerCase();\n if (!normalized) {\n return null;\n }\n const descriptionMatches = todoList.items.filter(\n (i) => i.description.toLowerCase().includes(normalized)\n );\n if (descriptionMatches.length === 1) {\n return descriptionMatches[0]!;\n }\n\n return null;\n}\n\n/**\n * Create TODO list with tasks\n */\nexport function createTodoCreateTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'todo_create',\n description: 'Create a TODO list to track task progress. Optional - use if helpful for planning complex tasks.',\n parameters: {\n type: 'object',\n properties: {\n sessionId: {\n type: 'string',\n description: 'Session identifier to associate TODO list',\n },\n items: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n description: {\n type: 'string',\n description: 'Task description',\n },\n priority: {\n type: 'string',\n enum: ['low', 'medium', 'high'],\n description: 'Task priority',\n },\n },\n required: ['description'],\n },\n description: 'List of tasks',\n },\n },\n required: ['sessionId', 'items'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const sessionId = input.sessionId as string;\n const items = input.items as Array<{\n description: string;\n priority?: 'low' | 'medium' | 'high';\n }>;\n\n const todoItems: TodoItem[] = items.map((item, index) => ({\n id: `${sessionId}-${index + 1}`,\n description: item.description,\n status: 'pending',\n priority: item.priority || 'medium',\n createdAt: new Date().toISOString(),\n }));\n\n const todoList: TodoList = {\n sessionId,\n items: todoItems,\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n };\n\n await persistTodoList(context, todoList);\n\n const output = [\n `TODO list created for session: ${sessionId}`,\n '',\n ...todoItems.map(\n (item, i) => `${i + 1}. [ ] ${item.description} (${item.priority})`\n ),\n ].join('\\n');\n\n return {\n success: true,\n output,\n metadata: {\n uiHint: 'todo',\n structured: { todoList },\n },\n };\n },\n };\n}\n\n/**\n * Update TODO item status\n */\nexport function createTodoUpdateTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'todo_update',\n description: 'Update status of a TODO item. Use to mark tasks as in-progress or completed.',\n parameters: {\n type: 'object',\n properties: {\n sessionId: {\n type: 'string',\n description: 'Session identifier',\n },\n itemId: {\n type: 'string',\n description: 'TODO item ID to update',\n },\n status: {\n type: 'string',\n enum: ['pending', 'in-progress', 'completed', 'blocked'],\n description: 'New status',\n },\n notes: {\n type: 'string',\n description: 'Optional notes about the update',\n },\n },\n required: ['sessionId', 'itemId', 'status'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const sessionId = input.sessionId as string;\n const itemId = input.itemId as string;\n const status = input.status as TodoItem['status'];\n const notes = input.notes as string | undefined;\n\n const todoList = await loadTodoList(context, sessionId);\n\n if (!todoList) {\n return toolError({\n code: 'TODO_LIST_NOT_FOUND',\n message: `No TODO list found for session: ${sessionId}`,\n retryable: true,\n hint: 'Call todo_create first, then todo_update.',\n details: { sessionId },\n });\n }\n\n const item = resolveTodoItem(todoList, sessionId, itemId);\n\n if (!item) {\n return toolError({\n code: 'TODO_ITEM_NOT_FOUND',\n message: `TODO item not found: ${itemId}`,\n retryable: true,\n hint: 'Use todo_get to list valid item IDs, then retry with exact itemId.',\n details: {\n sessionId,\n itemId,\n knownIds: todoList.items.map((i) => i.id),\n },\n });\n }\n\n item.status = status;\n item.updatedAt = new Date().toISOString();\n\n if (notes) {\n item.notes = notes;\n }\n\n todoList.updatedAt = new Date().toISOString();\n await persistTodoList(context, todoList);\n\n const statusIcon =\n status === 'completed'\n ? '✓'\n : status === 'in-progress'\n ? '⏳'\n : status === 'blocked'\n ? '🚫'\n : ' ';\n\n const updatedList = await loadTodoList(context, sessionId);\n return {\n success: true,\n output: `[${statusIcon}] ${item.description} → ${status}${notes ? `\\n Note: ${notes}` : ''}`,\n metadata: {\n uiHint: 'todo',\n structured: { todoList: updatedList },\n },\n };\n },\n };\n}\n\n/**\n * Get TODO list status\n */\nexport function createTodoGetTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'todo_get',\n description: 'Get current TODO list with task statuses. Use to check progress.',\n parameters: {\n type: 'object',\n properties: {\n sessionId: {\n type: 'string',\n description: 'Session identifier',\n },\n },\n required: ['sessionId'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const sessionId = input.sessionId as string;\n\n const todoList = await loadTodoList(context, sessionId);\n\n if (!todoList) {\n return toolError({\n code: 'TODO_LIST_NOT_FOUND',\n message: `No TODO list found for session: ${sessionId}`,\n retryable: true,\n hint: 'Create a TODO list with todo_create before calling todo_get.',\n details: { sessionId },\n });\n }\n\n const completed = todoList.items.filter(i => i.status === 'completed')\n .length;\n const total = todoList.items.length;\n\n const output = [\n `TODO List for ${sessionId} (${completed}/${total} completed)`,\n '',\n ...todoList.items.map(item => {\n const icon =\n item.status === 'completed'\n ? '✓'\n : item.status === 'in-progress'\n ? '⏳'\n : item.status === 'blocked'\n ? '🚫'\n : ' ';\n return `[${icon}] ${item.description} (${item.priority})${item.notes ? `\\n ${item.notes}` : ''}`;\n }),\n ].join('\\n');\n\n return {\n success: true,\n output,\n metadata: {\n uiHint: 'todo',\n structured: { todoList },\n },\n };\n },\n };\n}\n","/**\n * plan_validate tool — LLM-based plan quality gate.\n *\n * Called by the plan-writer agent after drafting a plan to get structured\n * feedback before reporting it as ready. The LLM evaluator receives:\n * - The original user task (so it can judge relevance)\n * - The full plan markdown\n * - The requested evaluation tier (default: small)\n *\n * Returns a human+agent-readable string with:\n * - passed: yes/no\n * - score: 0.0–1.0\n * - Per-dimension breakdown (specificity, actionability, completeness, verification)\n * - Concrete, actionable feedback for each failing dimension\n *\n * The agent uses this output to decide:\n * 1. passed=yes → call report() with the plan\n * 2. passed=no → revise the plan based on feedback and call plan_validate again\n * 3. After 3 failed attempts → call ask_user() with the plan + issues\n */\n\nimport type { Tool, ToolContext } from '../../types.js';\nimport { useLLM } from '@kb-labs/sdk';\n\nconst EVAL_SYSTEM_PROMPT = `You are a plan quality evaluator. Evaluate implementation plans written by AI agents.\n\nYou will receive the original user task and the plan markdown.\n\nScore the plan on four dimensions (0.0–1.0 each):\n\n**specificity** (weight 0.30)\n- Does the plan reference real file paths from the codebase?\n- Are function names, class names, or line numbers mentioned where relevant?\n- For simple tasks (1-2 files), mentioning those files is sufficient for a high score.\n- For complex tasks (many files), more paths are expected.\n\n**actionability** (weight 0.35)\n- Can each step be executed without guessing what to do?\n- Steps should contain: what file to edit, what to change, or what command to run.\n- \"Edit X to add Y\" is actionable. \"Update the configuration\" is not.\n\n**completeness** (weight 0.15)\n- Does the plan have: task description, steps, verification?\n- Are sections substantive (not just headings)?\n\n**verification** (weight 0.20)\n- Does the plan include concrete commands to verify correctness?\n- At least one build or test command expected.\n\nRespond in EXACTLY this format (no other text before or after):\nSCORE: 0.XX\nSPECIFICITY: 0.XX\nACTIONABILITY: 0.XX\nCOMPLETENESS: 0.XX\nVERIFICATION: 0.XX\nFEEDBACK:\n<One paragraph per dimension scoring below 0.7. Quote the weak part, explain the problem, give a fix example. If all dimensions ≥ 0.7, write \"Plan meets quality threshold.\">\n\nIMPORTANT: Only output the format above. Do NOT output tool calls, code blocks, or any other format.`;\n\n/**\n * Build the evaluation user message.\n */\nfunction buildEvalPrompt(task: string, planMarkdown: string): string {\n return `## Original user task\n\n${task}\n\n## Plan to evaluate\n\n${planMarkdown}`;\n}\n\n/**\n * Parse the LLM response into a structured result string for the agent.\n * If parsing fails, returns the raw response — the agent can still read it.\n */\nconst PASS_THRESHOLD = 0.55;\n\nfunction formatResult(raw: string, tier: string): string {\n const lines = raw.split('\\n');\n const get = (key: string): string => {\n const line = lines.find(l => l.toUpperCase().startsWith(key.toUpperCase() + ':'));\n return line?.slice(line.indexOf(':') + 1).trim() ?? '';\n };\n\n const specificity = parseFloat(get('SPECIFICITY') || '0');\n const actionability = parseFloat(get('ACTIONABILITY') || '0');\n const completeness = parseFloat(get('COMPLETENESS') || '0');\n const verification = parseFloat(get('VERIFICATION') || '0');\n\n // Compute composite score ourselves — don't trust LLM's SCORE or PASSED fields\n const composite = specificity * 0.30 + actionability * 0.35 + completeness * 0.15 + verification * 0.20;\n const passed = composite >= PASS_THRESHOLD;\n\n // If all dimensions parsed as 0, the LLM likely hallucinated (wrong format)\n if (specificity === 0 && actionability === 0 && completeness === 0 && verification === 0) {\n return [\n `⚠️ EVAL_ERROR — LLM returned unparseable response (${tier} tier)`,\n '',\n 'Raw response (first 300 chars):',\n raw.slice(0, 300),\n '',\n 'ACTION: Try again with a different tier, or call report() if you believe the plan is ready.',\n ].join('\\n');\n }\n\n const feedbackIdx = raw.toUpperCase().indexOf('FEEDBACK:');\n const feedback = feedbackIdx >= 0 ? raw.slice(feedbackIdx + 'FEEDBACK:'.length).trim() : '';\n\n const status = passed ? '✅ PASSED' : '❌ FAILED';\n const scoreBar = Math.round(composite * 10);\n const bar = '█'.repeat(scoreBar) + '░'.repeat(10 - scoreBar);\n\n return [\n `${status} — score: ${composite.toFixed(2)} [${bar}] (threshold ${PASS_THRESHOLD}, ${tier} tier)`,\n '',\n ` specificity: ${specificity.toFixed(2)} (weight 0.30)`,\n ` actionability: ${actionability.toFixed(2)} (weight 0.35)`,\n ` completeness: ${completeness.toFixed(2)} (weight 0.15)`,\n ` verification: ${verification.toFixed(2)} (weight 0.20)`,\n '',\n ...(feedback ? ['─── Feedback ───', feedback, ''] : []),\n passed\n ? 'ACTION: Call report() with the plan — it is ready for user approval.'\n : 'ACTION: Revise the plan addressing the feedback above, then call plan_validate again.\\n After 3 failed validations, call ask_user() with the plan and this feedback.',\n ].join('\\n');\n}\n\nexport function createPlanValidateTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function' as const,\n function: {\n name: 'plan_validate',\n description: `Evaluate a plan draft against quality criteria using an LLM judge.\nReturns pass/fail, per-dimension scores, and concrete actionable feedback on what to fix.\nCall this after writing a plan draft, before calling report().\nIf it fails, revise the plan based on the feedback and call plan_validate again.\nAfter 3 consecutive failures, call ask_user() with the plan and the feedback to escalate to the human.`,\n parameters: {\n type: 'object' as const,\n properties: {\n task: {\n type: 'string' as const,\n description: 'The original user task/request that the plan is supposed to address. Copied verbatim — the evaluator needs this to judge relevance.',\n },\n plan_markdown: {\n type: 'string' as const,\n description: 'The full plan markdown to evaluate.',\n },\n tier: {\n type: 'string' as const,\n enum: ['small', 'medium', 'large'],\n description: 'LLM tier for evaluation. Default: small (fast, cheap). Use medium/large for complex plans or if small gives inconsistent results.',\n },\n },\n required: ['task', 'plan_markdown'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const task = input.task as string;\n const planMarkdown = input.plan_markdown as string;\n const tier = (input.tier as string | undefined) ?? 'small';\n\n if (!task?.trim()) {\n return { success: false, output: 'ERROR: task is required — provide the original user request so the evaluator can judge plan relevance.' };\n }\n if (!planMarkdown?.trim()) {\n return { success: false, output: 'ERROR: plan_markdown is required — provide the full plan markdown to evaluate.' };\n }\n\n const llm = useLLM({ tier: tier as 'small' | 'medium' | 'large' });\n if (!llm) {\n return { success: false, output: `ERROR: LLM tier \"${tier}\" is not available. Try a different tier or check platform configuration.` };\n }\n\n try {\n const response = await llm.complete(buildEvalPrompt(task, planMarkdown), {\n systemPrompt: EVAL_SYSTEM_PROMPT,\n maxTokens: 1500,\n });\n\n const formatted = formatResult(response.content, tier);\n\n // If plan passed, signal to report tool that validation is complete\n if (formatted.startsWith('✅ PASSED') || formatted.startsWith('⚠️ EVAL_ERROR')) {\n (context as unknown as Record<string, unknown>).planValidationPassed = true;\n }\n\n return { success: true, output: formatted };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { success: false, output: `ERROR: LLM evaluation failed: ${message}` };\n }\n },\n };\n}\n","/**\n * plan_write tool — write/update the session plan file on disk.\n *\n * Enables iterative plan building: agent writes plan incrementally during\n * exploration, rather than generating everything at the end in one shot.\n * The plan survives context compaction because it lives on disk.\n *\n * Plan file location: .kb/agents/sessions/{sessionId}/plan.md\n * (resolved from context.sessionId and context.workingDir)\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { Tool, ToolContext } from '../../types.js';\nimport { toolError } from '../shared/tool-error.js';\n\nexport function createPlanWriteTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'plan_write',\n description: `Write or update the plan file for this session. The plan is saved to disk and survives context compaction. Use this to iteratively build your plan during exploration — write what you've learned so far, then continue exploring. The user can view the plan file at any time.`,\n parameters: {\n type: 'object',\n properties: {\n content: {\n type: 'string',\n description: 'Full markdown content for the plan file (replaces previous content)',\n },\n append: {\n type: 'string',\n description: 'Text to append to the existing plan (mutually exclusive with content)',\n },\n },\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const content = input.content as string | undefined;\n const append = input.append as string | undefined;\n\n if (!content && !append) {\n return toolError({\n code: 'MISSING_INPUT',\n message: 'Either content or append must be provided.',\n retryable: false,\n hint: 'Provide content= for full replacement, or append= to add to existing plan.',\n });\n }\n\n if (content && append) {\n return toolError({\n code: 'AMBIGUOUS_INPUT',\n message: 'Cannot use both content and append at the same time.',\n retryable: false,\n hint: 'Use content= to replace the entire plan, or append= to add a section.',\n });\n }\n\n // Resolve plan file path\n const sessionId = context.sessionId;\n if (!sessionId) {\n return toolError({\n code: 'NO_SESSION',\n message: 'No session ID available. Plan write requires an active session.',\n retryable: false,\n });\n }\n\n const planDir = path.join(context.workingDir, '.kb', 'agents', 'sessions', sessionId);\n const planPath = path.join(planDir, 'plan.md');\n\n // Ensure directory exists\n if (!fs.existsSync(planDir)) {\n fs.mkdirSync(planDir, { recursive: true });\n }\n\n let finalContent: string;\n\n if (content) {\n // Full replacement\n finalContent = content;\n } else {\n // Append mode\n let existing = '';\n try {\n existing = fs.readFileSync(planPath, 'utf-8');\n } catch {\n // File doesn't exist yet — start fresh\n }\n finalContent = existing\n ? `${existing.trimEnd()}\\n\\n${append}`\n : append!;\n }\n\n fs.writeFileSync(planPath, finalContent, 'utf-8');\n\n const lineCount = finalContent.split('\\n').length;\n const mode = content ? 'replaced' : 'appended to';\n\n return {\n success: true,\n output: `Plan ${mode}: ${planPath}\\nLines: ${lineCount}`,\n metadata: {\n planPath,\n lineCount,\n mode: content ? 'replace' : 'append',\n },\n };\n },\n };\n}\n","/**\n * Shell execution tool\n */\n\nimport { execSync } from 'node:child_process';\nimport path from 'node:path';\nimport type { Tool, ToolContext } from '../../types.js';\nimport { toolError } from '../shared/tool-error.js';\nimport { SHELL_CONFIG } from '../../config.js';\n\nconst MAX_OUTPUT_CHARS = 8_000;\n\nfunction trimOutput(output: string, label: 'stdout' | 'stderr'): string {\n if (output.length <= MAX_OUTPUT_CHARS) {return output;}\n const head = output.slice(0, MAX_OUTPUT_CHARS * 0.3);\n const tail = output.slice(-Math.floor(MAX_OUTPUT_CHARS * 0.7));\n return `${head}\\n\\n⚠️ ${label.toUpperCase()} TRIMMED (${output.length.toLocaleString()} chars, showing head+tail)\\n💡 Pipe through grep/head/tail in your command to get focused output.\\n\\n...${tail}`;\n}\n\n/**\n * Execute shell command\n */\nexport function createShellExecTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'shell_exec',\n description: 'Execute a shell command and return output. Use for running builds, tests, git commands, etc. Commands run in the working directory.',\n parameters: {\n type: 'object',\n properties: {\n command: {\n type: 'string',\n description: 'Shell command to execute',\n },\n cwd: {\n type: 'string',\n description: 'Optional working directory relative to agent workingDir. Use to run command in a specific package/subdirectory.',\n },\n },\n required: ['command'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const command = input.command as string;\n const requestedCwd = typeof input.cwd === 'string' ? input.cwd.trim() : '';\n const resolvedCwd = requestedCwd\n ? path.resolve(context.workingDir, requestedCwd)\n : context.workingDir;\n\n const relative = path.relative(context.workingDir, resolvedCwd);\n if (relative.startsWith('..') || path.isAbsolute(relative)) {\n return toolError({\n code: 'INVALID_CWD',\n message: `Invalid cwd \"${requestedCwd}\" - outside working directory.`,\n retryable: false,\n hint: 'Use cwd relative to the agent working directory.',\n details: { requestedCwd, resolvedCwd, workingDir: context.workingDir },\n });\n }\n\n try {\n const output = execSync(command, {\n cwd: resolvedCwd,\n encoding: 'utf-8',\n maxBuffer: SHELL_CONFIG.maxBuffer,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n\n const trimmed = trimOutput(output || '', 'stdout');\n return {\n success: true,\n output: `[cwd: ${resolvedCwd}]\\n${trimmed || '(command completed with no output)'}`,\n metadata: {\n cwd: resolvedCwd,\n outputLength: output?.length ?? 0,\n trimmed: (output?.length ?? 0) > MAX_OUTPUT_CHARS,\n },\n };\n } catch (error: unknown) {\n // execSync throws when command exits with non-zero code\n const e = error as { stderr?: Buffer | string; stdout?: Buffer | string; status?: number; code?: string; signal?: string };\n const stderr = e.stderr?.toString() || '';\n const stdout = e.stdout?.toString() || '';\n const exitCode = e.status ?? -1;\n const commandText = typeof command === 'string' ? command.trim() : '';\n\n if (e.code === 'ETIMEDOUT' || e.signal === 'SIGTERM') {\n return toolError({\n code: 'SHELL_TIMEOUT',\n message: `Command timed out in ${resolvedCwd}`,\n retryable: true,\n hint: 'Use a narrower command or run package-scoped command via cwd.',\n details: { cwd: resolvedCwd, command: commandText, exitCode },\n });\n }\n\n if (/command not found/i.test(stderr) || exitCode === 127) {\n return toolError({\n code: 'COMMAND_NOT_FOUND',\n message: `Command not found: ${commandText}`,\n retryable: false,\n hint: 'Check binary name or ensure dependency is installed in this workspace.',\n details: { cwd: resolvedCwd, command: commandText, exitCode },\n });\n }\n\n if (/permission denied/i.test(stderr) || exitCode === 126) {\n return toolError({\n code: 'PERMISSION_DENIED',\n message: `Permission denied while executing command in ${resolvedCwd}`,\n retryable: false,\n hint: 'Check file permissions and executable bits.',\n details: { cwd: resolvedCwd, command: commandText, exitCode },\n });\n }\n\n const stdoutDisplay = trimOutput(stdout, 'stdout');\n const stderrDisplay = trimOutput(stderr, 'stderr');\n\n return toolError({\n code: 'NON_ZERO_EXIT',\n message: `Command failed with exit code ${exitCode}`,\n retryable: true,\n hint: 'Inspect stderr/stdout below. Pipe output through grep/head/tail to narrow it down.',\n details: {\n cwd: resolvedCwd,\n exitCode,\n stdout: stdoutDisplay || undefined,\n stderr: stderrDisplay || undefined,\n },\n });\n }\n },\n };\n}\n","/**\n * Async task tools — fire-and-forget sub-agent operations.\n *\n * - task_submit: Start a sub-agent in the background, get a task ID immediately\n * - task_status: Check status of one or all async tasks\n * - task_collect: Wait for a specific task to complete and get its result\n */\n\nimport type { ToolContext, Tool } from '../../types.js';\nimport type { SubAgentPreset } from '@kb-labs/agent-contracts';\nimport { SUB_AGENT_PRESETS } from '../../config.js';\n\n/**\n * Submit an async task (fire-and-forget sub-agent).\n */\nexport function createTaskSubmitTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'task_submit',\n description:\n 'Start a sub-agent task in the background. Returns immediately with a task ID.\\n' +\n 'The sub-agent runs concurrently — you can continue working while it executes.\\n' +\n 'Use task_status to check progress or task_collect to wait for results.',\n parameters: {\n type: 'object',\n properties: {\n description: {\n type: 'string',\n description: 'Short description of the task (for tracking).',\n },\n task: {\n type: 'string',\n description: 'Detailed task description for the sub-agent.',\n },\n preset: {\n type: 'string',\n enum: ['research', 'execute', 'review'],\n description: 'Sub-agent preset (default: \"research\").',\n },\n budgetPercent: {\n type: 'number',\n description: 'Percent of remaining budget to allocate (1-100, default: 20).',\n },\n },\n required: ['description', 'task'],\n },\n },\n },\n executor: async (input) => {\n if (!context.taskManager) {\n return {\n success: false,\n error: 'Async task system not available. Task delegation is not enabled for this agent.',\n };\n }\n\n const description = input.description as string;\n const task = input.task as string;\n const presetId = (input.preset as SubAgentPreset) ?? 'research';\n const preset = SUB_AGENT_PRESETS[presetId];\n if (!preset) {\n return { success: false, error: `Unknown preset: \"${presetId}\".` };\n }\n\n const budgetPercent = (input.budgetPercent as number | undefined) ?? 50;\n const budgetFraction = Math.min(1, Math.max(0, budgetPercent / 100));\n\n try {\n const asyncTask = await context.taskManager.submit(description, {\n task,\n preset: presetId,\n allowedTools: Array.from(preset.tools),\n maxIterations: preset.maxIterations,\n budgetFraction,\n });\n\n return {\n success: true,\n output: `Task submitted: ${asyncTask.id}\\nDescription: ${description}\\nPreset: ${presetId}\\nStatus: ${asyncTask.status}\\n\\nUse task_status(\"${asyncTask.id}\") to check progress or task_collect(\"${asyncTask.id}\") to wait for results.`,\n };\n } catch (error) {\n return {\n success: false,\n error: `Failed to submit task: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n },\n };\n}\n\n/**\n * Check status of async tasks.\n */\nexport function createTaskStatusTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'task_status',\n description:\n 'Check status of one or all async tasks.\\n' +\n 'Without taskId: returns all tasks.\\n' +\n 'With taskId: returns details for that specific task.',\n parameters: {\n type: 'object',\n properties: {\n taskId: {\n type: 'string',\n description: 'Specific task ID to check (omit for all tasks).',\n },\n },\n required: [],\n },\n },\n },\n executor: async (input) => {\n if (!context.taskManager) {\n return { success: false, error: 'Async task system not available.' };\n }\n\n const taskId = input.taskId as string | undefined;\n const result = context.taskManager.getStatus(taskId);\n\n if (result === null) {\n return { success: false, error: `Task not found: \"${taskId}\"` };\n }\n\n const tasks = Array.isArray(result) ? result : [result];\n if (tasks.length === 0) {\n return { success: true, output: 'No async tasks.' };\n }\n\n const lines = tasks.map(t => {\n const status = t.status === 'completed' ? '✅' :\n t.status === 'failed' ? '❌' :\n t.status === 'running' ? '⏳' : '⏸️';\n let line = `${status} ${t.id}: ${t.description} [${t.status}]`;\n if (t.result) { line += `\\n Result: ${t.result.slice(0, 200)}`; }\n if (t.error) { line += `\\n Error: ${t.error}`; }\n return line;\n });\n\n return { success: true, output: lines.join('\\n') };\n },\n };\n}\n\n/**\n * Wait for a specific async task to complete and get its full result.\n */\nexport function createTaskCollectTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'task_collect',\n description:\n 'Wait for a specific async task to complete and return its full result.\\n' +\n 'Blocks until the task is done. Use task_status to check without waiting.',\n parameters: {\n type: 'object',\n properties: {\n taskId: {\n type: 'string',\n description: 'The task ID to wait for.',\n },\n },\n required: ['taskId'],\n },\n },\n },\n executor: async (input) => {\n if (!context.taskManager) {\n return { success: false, error: 'Async task system not available.' };\n }\n\n const taskId = input.taskId as string;\n\n try {\n const result = await context.taskManager.collect(taskId);\n const status = result.success ? 'completed successfully' : 'failed';\n const lines = [\n `Task ${taskId} ${status} [preset=${result.preset}, ${result.iterations} iters, ${result.tokensUsed.toLocaleString()} tokens, ${(result.durationMs / 1000).toFixed(1)}s]`,\n ];\n\n if (result.filesRead.length > 0) { lines.push(`Files read: ${result.filesRead.length}`); }\n if (result.filesModified.length > 0) { lines.push(`Files modified: ${result.filesModified.join(', ')}`); }\n if (result.filesCreated.length > 0) { lines.push(`Files created: ${result.filesCreated.join(', ')}`); }\n\n lines.push('', result.summary);\n if (result.error) { lines.push('', `Error: ${result.error}`); }\n\n return { success: result.success, output: lines.join('\\n') };\n } catch (error) {\n return {\n success: false,\n error: `Failed to collect task: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n },\n };\n}\n","/**\n * User interaction tools\n */\n\nimport * as readline from 'node:readline';\nimport type { Tool, ToolContext } from '../../types.js';\n\n/**\n * Ask user a question (interactive mode only)\n */\nexport function createAskUserTool(_context: ToolContext): Tool {\n return {\n definition: {\n type: 'function',\n function: {\n name: 'ask_user',\n description: 'Ask the user a question and wait for their response. Use when you need clarification or additional information. In non-interactive mode, returns a default answer.',\n parameters: {\n type: 'object',\n properties: {\n question: {\n type: 'string',\n description: 'Question to ask the user',\n },\n },\n required: ['question'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const question = input.question as string;\n\n // Check if running in interactive mode\n const isInteractive =\n process.stdin.isTTY && process.stdout.isTTY && !process.env.CI;\n\n if (!isInteractive) {\n // Non-interactive mode: return default answer\n return {\n success: true,\n output: `[Auto-answer] Question was: \"${question}\". Proceeding with default behavior.`,\n };\n }\n\n // Interactive mode: ask user\n return new Promise(resolve => {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n rl.question(`\\n❓ ${question}\\n> `, answer => {\n rl.close();\n\n if (!answer || answer.trim() === '') {\n resolve({\n success: false,\n error: 'No answer provided',\n });\n } else {\n resolve({\n success: true,\n output: answer.trim(),\n });\n }\n });\n });\n },\n };\n}\n","/**\n * Reporting tools - for sub-agents to communicate with parent agent\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type {\n ClaimVerificationResult,\n EvidenceRequirements,\n EvidenceRecord,\n KernelState,\n} from '@kb-labs/agent-contracts';\nimport { useLLM } from '@kb-labs/sdk/hooks';\nimport type { Tool, ToolContext, ToolResponseRequirements } from '../../types.js';\n\nasync function hasPendingCorrectionCommit(context: ToolContext): Promise<boolean> {\n const kernel = await context.sessionMemory?.loadKernelState();\n if (!kernel) {\n return false;\n }\n return kernel.memory.pendingActions.some((action) =>\n action.status !== 'done'\n && action.content.startsWith('Persist user correction via memory_correction:')\n );\n}\n\nconst VERIFY_REPORT_CLAIMS_PROMPT = [\n 'Evaluate whether the proposed final agent answer is sufficiently supported by the provided session evidence.',\n 'Prefer blocking only when the answer makes unsupported code, file, architecture, or behavioral claims.',\n 'Allow simple session recall when kernel evidence is enough.',\n 'If evidence is partial, prefer warn instead of block unless the answer states unsupported details as facts.',\n 'Return strict JSON only.',\n].join(' ');\n\nasync function verifyReportClaims(\n context: ToolContext,\n answer: string,\n): Promise<ClaimVerificationResult> {\n const kernel = await context.sessionMemory?.loadKernelState();\n const requirements = await resolveResponseRequirements(context, answer, kernel);\n const evidence = kernel?.memory.evidence ?? [];\n const recallFastPath = verifyEvidenceBackedRecall(answer, kernel, requirements);\n if (recallFastPath) {\n return recallFastPath;\n }\n const fallback = deterministicVerification(answer, kernel, requirements);\n const llm = useLLM({ tier: 'small' });\n\n if (!llm?.complete) {\n return fallback;\n }\n\n try {\n const response = await llm.complete(buildClaimVerificationPrompt(answer, kernel, context), {\n systemPrompt: VERIFY_REPORT_CLAIMS_PROMPT,\n temperature: 0,\n maxTokens: 350,\n });\n return normalizeClaimVerification(response.content, fallback, evidence);\n } catch {\n return fallback;\n }\n}\n\nasync function resolveResponseRequirements(\n context: ToolContext,\n answer: string,\n kernel: KernelState | null | undefined,\n): Promise<ToolResponseRequirements | null> {\n if (!context.responseRequirementsResolver) {\n return null;\n }\n try {\n return await context.responseRequirementsResolver({\n task: context.currentTask,\n answer,\n kernel: kernel ?? null,\n });\n } catch {\n return null;\n }\n}\n\nfunction buildClaimVerificationPrompt(\n answer: string,\n kernel: KernelState | null | undefined,\n context: ToolContext,\n): string {\n const recentEvidence = (kernel?.memory.evidence ?? [])\n .slice(-6)\n .map((item) => ({\n toolName: item.toolName ?? item.source,\n toolInputSummary: item.toolInputSummary,\n summary: item.summary,\n }));\n const archiveEvidence = (kernel?.memory.evidence ?? [])\n .slice(-4)\n .flatMap((item) => {\n if (!item.toolInputSummary || !context.archiveMemory?.hasFile(item.toolInputSummary)) {\n return [];\n }\n const archived = context.archiveMemory.recallByFilePath(item.toolInputSummary);\n if (!archived) {\n return [];\n }\n return [{\n filePath: item.toolInputSummary,\n toolName: archived.toolName,\n excerpt: truncateText(archived.fullOutput, 1200),\n }];\n });\n\n return JSON.stringify({\n answer,\n objective: kernel?.objective ?? kernel?.currentTask ?? '',\n constraints: kernel?.constraints ?? [],\n recentCorrections: kernel?.memory.corrections.slice(-3).map((item) => item.content) ?? [],\n recentEvidence,\n archiveEvidence,\n schema: {\n verdict: 'allow | warn | block',\n rationale: 'short explanation',\n requirements: {\n allowsMemoryOnlyRecall: 'boolean',\n needsDirectToolEvidence: 'boolean',\n needsFileBackedClaims: 'boolean',\n allowsInference: 'boolean',\n maxUnsupportedClaims: 'number',\n },\n supportedClaims: ['string'],\n unsupportedClaims: ['string'],\n },\n }, null, 2);\n}\n\nfunction normalizeClaimVerification(\n content: string,\n fallback: ClaimVerificationResult,\n evidence: EvidenceRecord[],\n): ClaimVerificationResult {\n const parsed = extractJsonObject(content);\n if (!parsed) {\n return fallback;\n }\n\n const requirements = normalizeEvidenceRequirements(parsed.requirements, fallback.requirements);\n const verdict = parsed.verdict === 'allow' || parsed.verdict === 'warn' || parsed.verdict === 'block'\n ? parsed.verdict\n : fallback.verdict;\n const supportedClaims = normalizeStringArray(parsed.supportedClaims);\n const unsupportedClaims = normalizeStringArray(parsed.unsupportedClaims);\n const rationale = typeof parsed.rationale === 'string' && parsed.rationale.trim()\n ? parsed.rationale.trim()\n : fallback.rationale;\n\n if (verdict === 'block' && unsupportedClaims.length === 0 && evidence.length > 0) {\n return fallback;\n }\n\n return {\n verdict,\n rationale,\n requirements,\n supportedClaims,\n unsupportedClaims,\n };\n}\n\nfunction deterministicVerification(\n answer: string,\n kernel: KernelState | null | undefined,\n responseRequirements?: ToolResponseRequirements | null,\n): ClaimVerificationResult {\n const evidence = kernel?.memory.evidence ?? [];\n const shellRecall = /shell command|previous shell command|used in this session|latest shell command/i.test(answer);\n const fileLikeClaims = /RuntimeEngine|projectKernelPrompt|compactKernelState|plugins\\/|packages\\/|\\.ts\\b|line \\d+/i.test(answer);\n const hasFileEvidence = evidence.some((item) => item.toolName === 'fs_read');\n const hasShellEvidence = evidence.some((item) => item.toolName === 'shell_exec');\n const requirements = responseRequirements?.requirements;\n\n if (shellRecall && hasShellEvidence) {\n return {\n verdict: 'allow',\n rationale: 'Shell recall answer is grounded in stored shell_exec evidence.',\n requirements: {\n allowsMemoryOnlyRecall: true,\n needsDirectToolEvidence: false,\n needsFileBackedClaims: false,\n allowsInference: false,\n maxUnsupportedClaims: 0,\n },\n supportedClaims: ['Session shell recall supported by shell_exec evidence.'],\n unsupportedClaims: [],\n };\n }\n\n if (fileLikeClaims && !hasFileEvidence) {\n return {\n verdict: 'block',\n rationale: 'Code/file claims require fs_read-backed evidence before report is allowed.',\n requirements: {\n allowsMemoryOnlyRecall: false,\n needsDirectToolEvidence: true,\n needsFileBackedClaims: true,\n allowsInference: false,\n maxUnsupportedClaims: 0,\n },\n supportedClaims: [],\n unsupportedClaims: ['Answer makes file/code claims without fs_read evidence.'],\n };\n }\n\n return {\n verdict: 'allow',\n rationale: 'No unsupported claims were detected by deterministic fallback.',\n requirements: requirements ?? {\n allowsMemoryOnlyRecall: true,\n needsDirectToolEvidence: false,\n needsFileBackedClaims: false,\n allowsInference: true,\n maxUnsupportedClaims: 1,\n },\n supportedClaims: [],\n unsupportedClaims: [],\n };\n}\n\nfunction verifyEvidenceBackedRecall(\n answer: string,\n kernel: KernelState | null | undefined,\n responseRequirements: ToolResponseRequirements | null,\n): ClaimVerificationResult | null {\n if (!responseRequirements?.requirements.allowsMemoryOnlyRecall) {\n return null;\n }\n\n const evidence = kernel?.memory.evidence ?? [];\n const fileEvidence = evidence\n .filter((item) => item.toolName === 'fs_read' && item.toolInputSummary)\n .map((item) => item.toolInputSummary as string);\n const mentionedFiles = extractMentionedFilePaths(answer);\n\n if (mentionedFiles.length > 0 && mentionedFiles.every((filePath) => fileEvidence.includes(filePath))) {\n return {\n verdict: 'allow',\n rationale: 'Answer is a direct recall of file evidence already recorded in the session.',\n requirements: responseRequirements.requirements,\n supportedClaims: mentionedFiles.map((filePath) => `Read evidence exists for ${filePath}.`),\n unsupportedClaims: [],\n };\n }\n\n return null;\n}\n\nfunction extractMentionedFilePaths(answer: string): string[] {\n const matches = answer.match(/plugins\\/[^\\s`*]+|packages\\/[^\\s`*]+/g) ?? [];\n return [...new Set(matches)];\n}\n\nfunction normalizeEvidenceRequirements(\n value: unknown,\n fallback: EvidenceRequirements,\n): EvidenceRequirements {\n if (!value || typeof value !== 'object') {\n return fallback;\n }\n const input = value as Record<string, unknown>;\n return {\n allowsMemoryOnlyRecall: typeof input.allowsMemoryOnlyRecall === 'boolean'\n ? input.allowsMemoryOnlyRecall\n : fallback.allowsMemoryOnlyRecall,\n needsDirectToolEvidence: typeof input.needsDirectToolEvidence === 'boolean'\n ? input.needsDirectToolEvidence\n : fallback.needsDirectToolEvidence,\n needsFileBackedClaims: typeof input.needsFileBackedClaims === 'boolean'\n ? input.needsFileBackedClaims\n : fallback.needsFileBackedClaims,\n allowsInference: typeof input.allowsInference === 'boolean'\n ? input.allowsInference\n : fallback.allowsInference,\n maxUnsupportedClaims: typeof input.maxUnsupportedClaims === 'number'\n ? input.maxUnsupportedClaims\n : fallback.maxUnsupportedClaims,\n };\n}\n\nfunction normalizeStringArray(value: unknown): string[] {\n if (!Array.isArray(value)) {\n return [];\n }\n return value.filter((item): item is string => typeof item === 'string' && item.trim().length > 0);\n}\n\nfunction extractJsonObject(content: string): Record<string, unknown> | null {\n const start = content.indexOf('{');\n const end = content.lastIndexOf('}');\n if (start === -1 || end === -1 || end <= start) {\n return null;\n }\n try {\n return JSON.parse(content.slice(start, end + 1)) as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\nfunction truncateText(value: string, maxChars: number): string {\n const normalized = value.trim();\n if (normalized.length <= maxChars) {\n return normalized;\n }\n return `${normalized.slice(0, maxChars - 1).trimEnd()}…`;\n}\n\n/**\n * Ask parent agent for help when stuck or uncertain.\n * Sub-agents use this to escalate to the main agent for guidance.\n */\nexport function createAskParentTool(_context: ToolContext): Tool {\n return {\n definition: {\n type: 'function' as const,\n function: {\n name: 'ask_parent',\n description: `Ask the parent agent for help when stuck or need clarification.`,\n parameters: {\n type: 'object' as const,\n properties: {\n question: {\n type: 'string' as const,\n description: 'Your question for the parent agent. Be specific about what you need help with.',\n },\n reason: {\n type: 'string' as const,\n enum: ['stuck', 'uncertain', 'blocker', 'clarification'],\n description: 'Why are you asking? stuck=repeating tools, uncertain=unclear approach, blocker=cannot proceed, clarification=need more info',\n },\n context: {\n type: 'object' as const,\n description: 'Relevant context: tools tried, iteration number, what you attempted',\n },\n },\n required: ['question', 'reason'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const question = input.question as string;\n const reason = input.reason as string;\n const context = input.context as Record<string, unknown> | undefined;\n\n return {\n success: true,\n output: '', // Will be populated by parent agent\n metadata: {\n question,\n reason,\n context,\n needsParentHelp: true,\n },\n };\n },\n };\n}\n\n/**\n * Report findings and exit. Used by agents to provide synthesized answer\n * and signal early exit when task is complete.\n */\nexport function createReportTool(context: ToolContext): Tool {\n return {\n definition: {\n type: 'function' as const,\n function: {\n name: 'report',\n description: `Report your answer and exit. Include specific findings with file paths and code snippets as evidence.`,\n parameters: {\n type: 'object' as const,\n properties: {\n answer: {\n type: 'string' as const,\n description: 'Synthesized answer with specific details, file references, and code snippets. Be concise but complete.',\n },\n confidence: {\n type: 'number' as const,\n description: 'How confident you are in this answer (0.0-1.0). Use 0.8+ if you found concrete evidence, 0.5-0.7 if partial, <0.5 if uncertain.',\n },\n },\n required: ['answer', 'confidence'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const answer = input.answer as string;\n const confidence = input.confidence as number;\n\n // In plan mode (plan_validate is in the allowed tool set), prefer\n // plan_validate before report — but don't hard-block if budget is exhausted.\n // If the agent wrote a plan file via plan_write, allow report as fallback.\n const inPlanMode = context.allowedTools?.has('plan_validate') ?? false;\n if (inPlanMode && !context.planValidationPassed) {\n // Check if plan file exists on disk (written via plan_write)\n const planPath = context.sessionId\n ? path.join(context.workingDir, '.kb', 'agents', 'sessions', context.sessionId, 'plan.md')\n : null;\n const hasPlanFile = planPath && fs.existsSync(planPath);\n\n if (!hasPlanFile) {\n return {\n success: false,\n output: 'BLOCKED: You must either (1) call plan_validate first, or (2) save your plan via plan_write and then call report. Call plan_write with your plan content now.',\n };\n }\n // Plan file exists — allow report even without validation (budget fallback)\n }\n\n if (await hasPendingCorrectionCommit(context)) {\n return {\n success: false,\n output: 'BLOCKED: You must call memory_correction before report because this session has an unpersisted user correction or active instruction. Persist it first, then report.',\n metadata: {\n code: 'PENDING_MEMORY_COMMIT',\n },\n };\n }\n\n const verification = await verifyReportClaims(context, answer);\n if (verification.verdict === 'block') {\n return {\n success: false,\n output: `BLOCKED: Report claims are not sufficiently supported by session evidence. ${verification.rationale}`,\n metadata: {\n code: 'INSUFFICIENT_EVIDENCE',\n verification,\n },\n };\n }\n\n return {\n success: true,\n output: '', // Intentionally empty - agent should exit after calling this\n metadata: {\n answer,\n confidence,\n earlyExit: true,\n verification,\n },\n };\n },\n };\n}\n\n/**\n * Reflection tool - agent reflects on progress and decides whether to continue.\n * Auto-triggers report when confidence is high and shouldContinue is false.\n */\nexport function createReflectOnProgressTool(_context: ToolContext): Tool {\n return {\n definition: {\n type: 'function' as const,\n function: {\n name: 'reflect_on_progress',\n description: `Reflect on progress and decide whether to continue or report. If confidence >= 0.7 and should_continue = false, auto-reports findings.`,\n parameters: {\n type: 'object' as const,\n properties: {\n findings_summary: {\n type: 'string' as const,\n description: 'Brief summary of what you accomplished so far (2-3 sentences)',\n },\n confidence: {\n type: 'number' as const,\n description: 'Confidence that task is complete (0.0-1.0). For implementation: 0.8+ only if artifacts created. For research: 0.8+ if answers found.',\n minimum: 0,\n maximum: 1,\n },\n questions_remaining: {\n type: 'array' as const,\n items: { type: 'string' as const },\n description: 'List of aspects still incomplete. Empty array if all done.',\n },\n should_continue: {\n type: 'boolean' as const,\n description: 'true = need more work, false = ready to report completion',\n },\n reason: {\n type: 'string' as const,\n description: 'Explanation for your continue/stop decision (1 sentence)',\n },\n evidence_of_completion: {\n type: 'string' as const,\n description: 'Concrete evidence of task completion (e.g., \"Created 15 files\", \"Tests passing\", \"Found answer in 3 sources\"). Required for high confidence.',\n },\n },\n required: ['findings_summary', 'confidence', 'questions_remaining', 'should_continue', 'reason', 'evidence_of_completion'],\n },\n },\n },\n executor: async (input: Record<string, unknown>) => {\n const reflection = {\n findingsSummary: input.findings_summary as string,\n confidence: input.confidence as number,\n questionsRemaining: input.questions_remaining as string[],\n shouldContinue: input.should_continue as boolean,\n reason: input.reason as string,\n evidenceOfCompletion: input.evidence_of_completion as string,\n };\n\n // Anti-hallucination check: If agent claims completion without evidence, reduce confidence\n const hasNoEvidence = !reflection.evidenceOfCompletion ||\n reflection.evidenceOfCompletion.toLowerCase().includes('need to') ||\n reflection.evidenceOfCompletion.toLowerCase().includes('will create') ||\n reflection.evidenceOfCompletion.toLowerCase().includes('plan to');\n\n let adjustedConfidence = reflection.confidence;\n let adjustedShouldContinue = reflection.shouldContinue;\n let warningMessage = '';\n\n if (reflection.confidence >= 0.7 && !reflection.shouldContinue && hasNoEvidence) {\n adjustedConfidence = 0.3;\n adjustedShouldContinue = true;\n warningMessage = ' [ADJUSTED: No concrete evidence of completion - lowered confidence to 0.30, continue required]';\n }\n\n return {\n success: true,\n output: `Reflection recorded: confidence=${adjustedConfidence.toFixed(2)}, should_continue=${adjustedShouldContinue}${warningMessage}`,\n metadata: {\n reflection: {\n ...reflection,\n confidence: adjustedConfidence,\n shouldContinue: adjustedShouldContinue,\n },\n shouldAutoReport: adjustedConfidence >= 0.7 && !adjustedShouldContinue,\n adjusted: adjustedConfidence !== reflection.confidence,\n },\n };\n },\n };\n}\n","/**\n * Tool registration and exports\n *\n * Tools are organized by category:\n * filesystem/ — fs_read, fs_write, fs_patch, fs_replace, fs_list, mass_replace\n * search/ — glob_search, grep_search, find_definition, code_stats\n * memory/ — memory_*, archive_recall, session_save\n * planning/ — plan_validate, plan_write, todo_*\n * execution/ — shell_exec, task_submit/status/collect\n * interaction/ — ask_user, ask_parent, report\n * shared/ — tool-error (utilities)\n */\n\nimport type { ToolContext } from '../types.js';\nimport { ToolRegistry } from '../registry.js';\n\n// ── Filesystem ──────────────────────────────────────────────────────────────\n\nimport {\n createFsWriteTool,\n createFsReadTool,\n createFsPatchTool,\n createFsReplaceTool,\n createFsListTool,\n} from './filesystem/filesystem.js';\n\nimport { createMassReplaceTool } from './filesystem/mass-replace.js';\n\n// ── Search ──────────────────────────────────────────────────────────────────\n\nimport {\n createGlobSearchTool,\n createGrepSearchTool,\n createListFilesTool,\n createFindDefinitionTool,\n createCodeStatsTool,\n} from './search/search.js';\n\n// ── Memory ──────────────────────────────────────────────────────────────────\n\nimport {\n createMemoryGetTool,\n createMemoryPreferenceTool,\n createMemoryConstraintTool,\n createSessionSaveTool,\n createMemoryCorrectionTool,\n createMemoryFindingTool,\n createMemoryBlockerTool,\n} from './memory/memory.js';\n\nimport { createArchiveRecallTool } from './memory/archive-recall.js';\n\n// ── Planning ────────────────────────────────────────────────────────────────\n\nimport {\n createTodoCreateTool,\n createTodoUpdateTool,\n createTodoGetTool,\n} from './planning/todo.js';\n\nimport { createPlanValidateTool } from './planning/plan-validate.js';\nimport { createPlanWriteTool } from './planning/plan-write.js';\n\n// ── Execution ───────────────────────────────────────────────────────────────\n\nimport { createShellExecTool } from './execution/shell.js';\nimport { createTaskSubmitTool, createTaskStatusTool, createTaskCollectTool } from './execution/async-tasks.js';\n\n// ── Interaction ─────────────────────────────────────────────────────────────\n\nimport { createAskUserTool } from './interaction/interaction.js';\nimport { createAskParentTool, createReportTool } from './interaction/reporting.js';\n\n// ═════════════════════════════════════════════════════════════════════════════\n// Registry\n// ═════════════════════════════════════════════════════════════════════════════\n\n/**\n * Create and register all tools\n */\nexport function createToolRegistry(context: ToolContext): ToolRegistry {\n const allowed = context.allowedTools;\n const allow = (name: string) => !allowed || allowed.has(name);\n const registry = new ToolRegistry(context);\n\n // ── Filesystem ──\n if (allow('fs_write')) {registry.register(createFsWriteTool(context));}\n if (allow('fs_read')) {registry.register(createFsReadTool(context));}\n if (allow('fs_patch')) {registry.register(createFsPatchTool(context));}\n if (allow('fs_replace')) {registry.register(createFsReplaceTool(context));}\n if (allow('fs_list')) {registry.register(createFsListTool(context));}\n if (allow('mass_replace')) {registry.register(createMassReplaceTool(context));}\n\n // ── Search ──\n if (allow('glob_search')) {registry.register(createGlobSearchTool(context));}\n if (allow('grep_search')) {registry.register(createGrepSearchTool(context));}\n if (allow('find_definition')) {registry.register(createFindDefinitionTool(context));}\n if (allow('code_stats')) {registry.register(createCodeStatsTool(context));}\n\n // ── Execution ──\n if (allow('shell_exec')) {registry.register(createShellExecTool(context));}\n if (context.taskManager) {\n if (allow('task_submit')) { registry.register(createTaskSubmitTool(context)); }\n if (allow('task_status')) { registry.register(createTaskStatusTool(context)); }\n if (allow('task_collect')) { registry.register(createTaskCollectTool(context)); }\n }\n\n // ── Memory ──\n if (allow('memory_get')) {registry.register(createMemoryGetTool(context));}\n if (allow('memory_preference')) {registry.register(createMemoryPreferenceTool(context));}\n if (allow('memory_constraint')) {registry.register(createMemoryConstraintTool(context));}\n if (allow('session_save')) {registry.register(createSessionSaveTool(context));}\n if (allow('memory_correction')) {registry.register(createMemoryCorrectionTool(context));}\n if (allow('memory_finding')) {registry.register(createMemoryFindingTool(context));}\n if (allow('memory_blocker')) {registry.register(createMemoryBlockerTool(context));}\n if (context.archiveMemory && allow('archive_recall')) {\n registry.register(createArchiveRecallTool(context));\n }\n\n // ── Planning ──\n if (allow('todo_create')) {registry.register(createTodoCreateTool(context));}\n if (allow('todo_update')) {registry.register(createTodoUpdateTool(context));}\n if (allow('todo_get')) {registry.register(createTodoGetTool(context));}\n if (allow('plan_validate')) { registry.register(createPlanValidateTool(context)); }\n if (allow('plan_write')) { registry.register(createPlanWriteTool(context)); }\n\n // ── Interaction ──\n if (allow('ask_user')) {registry.register(createAskUserTool(context));}\n if (allow('ask_parent')) {registry.register(createAskParentTool(context));}\n if (allow('report')) {registry.register(createReportTool(context));}\n\n return registry;\n}\n\n// ═════════════════════════════════════════════════════════════════════════════\n// Re-exports\n// ═════════════════════════════════════════════════════════════════════════════\n\nexport {\n // Filesystem\n createFsWriteTool,\n createFsReadTool,\n createFsPatchTool,\n createFsReplaceTool,\n createFsListTool,\n createMassReplaceTool,\n // Search\n createListFilesTool,\n createGlobSearchTool,\n createGrepSearchTool,\n createFindDefinitionTool,\n createCodeStatsTool,\n // Memory\n createMemoryGetTool,\n createMemoryPreferenceTool,\n createMemoryConstraintTool,\n createSessionSaveTool,\n createMemoryCorrectionTool,\n createMemoryFindingTool,\n createMemoryBlockerTool,\n createArchiveRecallTool,\n // Planning\n createTodoCreateTool,\n createTodoUpdateTool,\n createTodoGetTool,\n createPlanValidateTool,\n createPlanWriteTool,\n // Execution\n createShellExecTool,\n createTaskSubmitTool,\n createTaskStatusTool,\n createTaskCollectTool,\n // Interaction\n createAskUserTool,\n createAskParentTool,\n createReportTool,\n};\n","import type { ToolCapability, ToolResultArtifact } from '@kb-labs/agent-contracts';\nimport { ToolRegistry } from './registry.js';\nimport type { ToolContext, ToolExecutionEnvelope, ToolPolicy } from './types.js';\nimport { createToolRegistry } from './tools/index.js';\n\nconst DEFAULT_TOOL_CAPABILITIES: Record<string, ToolCapability[]> = {\n fs_write: ['filesystem'],\n fs_read: ['filesystem'],\n fs_patch: ['filesystem'],\n fs_list: ['filesystem'],\n mass_replace: ['filesystem'],\n glob_search: ['search'],\n grep_search: ['search'],\n list_files: ['search'],\n find_definition: ['code-navigation'],\n code_stats: ['search'],\n shell_exec: ['shell'],\n memory_get: ['memory'],\n memory_preference: ['memory'],\n memory_constraint: ['memory'],\n session_save: ['memory'],\n memory_correction: ['memory'],\n memory_finding: ['memory'],\n memory_blocker: ['memory'],\n archive_recall: ['memory'],\n todo_create: ['todo'],\n todo_update: ['todo'],\n todo_get: ['todo'],\n ask_user: ['interaction'],\n ask_parent: ['reporting'],\n report: ['reporting'],\n task_submit: ['delegation'],\n task_status: ['delegation'],\n task_collect: ['delegation'],\n plan_validate: ['planning'],\n};\n\nfunction toArtifact(toolName: string, result: {\n success: boolean;\n output?: string;\n error?: string;\n metadata?: Record<string, unknown>;\n}): ToolResultArtifact {\n const summary = result.output || result.error || `${toolName} completed`;\n return {\n status: result.success ? 'success' : 'error',\n summary,\n artifact: result.metadata,\n evidence: summary\n ? [{\n id: `ev-${Date.now()}-${toolName}`,\n summary,\n source: toolName,\n createdAt: new Date().toISOString(),\n artifact: result.metadata,\n }]\n : [],\n mutations: typeof result.metadata?.filePath === 'string'\n ? { filesRead: [result.metadata.filePath] }\n : undefined,\n followUpHints: typeof result.metadata?.summary === 'string'\n ? [String(result.metadata.summary)]\n : undefined,\n };\n}\n\nexport class ToolGateway {\n private readonly registry: ToolRegistry;\n\n constructor(\n private readonly context: ToolContext,\n private readonly policies: ToolPolicy[] = [],\n ) {\n this.registry = createToolRegistry(context);\n }\n\n getDefinitions() {\n return this.registry.getDefinitions().filter((definition) =>\n this.isAllowed(definition.function.name),\n );\n }\n\n getToolNames(): string[] {\n return this.getDefinitions().map((definition) => definition.function.name);\n }\n\n async execute(name: string, input: Record<string, unknown>): Promise<ToolExecutionEnvelope> {\n const allowed = this.isAllowed(name);\n if (!allowed) {\n const artifact: ToolResultArtifact = {\n status: 'error',\n summary: `Tool \"${name}\" blocked by policy`,\n evidence: [],\n };\n return {\n result: { success: false, error: artifact.summary },\n artifact,\n };\n }\n\n const result = await this.registry.execute(name, input);\n return {\n result,\n artifact: toArtifact(name, result),\n };\n }\n\n private isAllowed(toolName: string): boolean {\n const capabilities = this.getToolCapabilities(toolName);\n return this.policies.every((policy) =>\n policy.allows(toolName, this.context)\n && capabilities.every((capability) => policy.allowsCapability?.(capability, this.context, toolName) ?? true),\n );\n }\n\n private getToolCapabilities(toolName: string): ToolCapability[] {\n const mapped = this.context.toolCapabilitiesByName?.get(toolName);\n return mapped ?? DEFAULT_TOOL_CAPABILITIES[toolName] ?? [];\n }\n}\n","/**\n * RemoteWorkspaceProvider — proxies workspace operations to Workspace Agent via Gateway.\n *\n * Used when Agent Runner runs on Platform but needs to access files\n * on a remote Workspace Agent (Cursor-model: \"brain\" on server, \"hands\" on client).\n *\n * Uses Gateway dispatcher to send capability calls to connected Workspace Agent.\n *\n * @see ADR-0017: Workspace Agent Architecture (Phase 3)\n */\n\nimport type {\n IWorkspaceProvider,\n FileReadResult,\n FileStatResult,\n GrepResult,\n GlobResult,\n ShellResult,\n} from './workspace-provider.js';\n\n/** Gateway dispatcher call function (injected, avoids direct dependency on Gateway) */\nexport type DispatchFn = (\n adapter: string,\n method: string,\n args: unknown[],\n) => Promise<unknown>;\n\nexport interface RemoteWorkspaceProviderOptions {\n /** Function to dispatch capability calls via Gateway */\n dispatch: DispatchFn;\n}\n\nexport class RemoteWorkspaceProvider implements IWorkspaceProvider {\n constructor(private readonly opts: RemoteWorkspaceProviderOptions) {}\n\n async readFile(path: string, offset?: number, limit?: number): Promise<FileReadResult> {\n const result = await this.opts.dispatch('filesystem', 'readFile', [path]);\n const content = result as string;\n const lines = content.split('\\n');\n\n const start = (offset ?? 1) - 1;\n const count = limit ?? lines.length;\n const sliced = lines.slice(start, start + count);\n\n return {\n content: sliced.join('\\n'),\n totalLines: lines.length,\n truncated: sliced.length < lines.length,\n };\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n await this.opts.dispatch('filesystem', 'writeFile', [path, content]);\n }\n\n async listDir(path: string, limit?: number): Promise<string[]> {\n const result = await this.opts.dispatch('filesystem', 'listDir', [path]);\n const entries = result as string[];\n return limit ? entries.slice(0, limit) : entries;\n }\n\n async stat(path: string): Promise<FileStatResult> {\n return await this.opts.dispatch('filesystem', 'stat', [path]) as FileStatResult;\n }\n\n async exists(path: string): Promise<boolean> {\n return await this.opts.dispatch('filesystem', 'exists', [path]) as boolean;\n }\n\n async grep(\n pattern: string,\n directory: string,\n options?: { includes?: string[]; excludes?: string[]; maxResults?: number; contextLines?: number },\n ): Promise<GrepResult> {\n return await this.opts.dispatch('search', 'grep', [pattern, directory, options]) as GrepResult;\n }\n\n async glob(\n pattern: string,\n directory: string,\n options?: { excludes?: string[]; maxResults?: number },\n ): Promise<GlobResult> {\n return await this.opts.dispatch('search', 'glob', [pattern, directory, options]) as GlobResult;\n }\n\n async shellExec(\n command: string,\n options?: { cwd?: string; timeoutMs?: number; env?: Record<string, string> },\n ): Promise<ShellResult> {\n return await this.opts.dispatch('shell', 'exec', [command, options]) as ShellResult;\n }\n}\n"]}