crewswarm-cli 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/worker/autonomous-loop.ts", "../src/tools/gemini/definitions/base-declarations.ts", "../src/lsp/index.ts", "../src/tools/docker-sandbox.ts", "../src/tools/gemini/crew-adapter.ts", "../src/learning/corrections.ts", "../src/collections/index.ts", "../src/executor/agentic-executor.ts", "../src/engine-api.ts", "../src/sandbox/index.ts"],
4
- "sourcesContent": ["/**\n * Autonomous Worker Loop\n * Implements OpenOrca-style THINK \u2192 ACT \u2192 OBSERVE pattern\n * \n * @license\n * Copyright 2026 CrewSwarm\n */\n\nexport interface ToolCall {\n tool: string;\n params: Record<string, any>;\n}\n\nexport interface TurnResult {\n turn: number;\n tool: string;\n params: Record<string, any>;\n result: any;\n error?: string;\n}\n\nexport interface AutonomousResult {\n success: boolean;\n turns: number;\n history: TurnResult[];\n finalResponse?: string;\n reason?: string;\n}\n\nexport interface AutonomousConfig {\n maxTurns?: number;\n repeatThreshold?: number;\n tools: any[];\n onProgress?: (turn: number, action: string) => void;\n}\n\nconst DEFAULT_MAX_TURNS = 25;\nconst DEFAULT_REPEAT_THRESHOLD = 10;\n\n/**\n * Execute task autonomously with up to MAX_TURNS iterations\n */\nexport async function executeAutonomous(\n task: string,\n executeLLM: (prompt: string, tools: any[], history: TurnResult[]) => Promise<{ toolCalls?: ToolCall[]; response: string; status?: string }>,\n executeTool: (tool: string, params: Record<string, any>) => Promise<any>,\n config: AutonomousConfig\n): Promise<AutonomousResult> {\n const maxTurns = config.maxTurns || DEFAULT_MAX_TURNS;\n const repeatThreshold = config.repeatThreshold || DEFAULT_REPEAT_THRESHOLD;\n const history: TurnResult[] = [];\n\n let lastResponseText = '';\n let staleCount = 0;\n\n for (let turn = 0; turn < maxTurns; turn++) {\n config.onProgress?.(turn + 1, 'THINKING');\n\n // THINK: LLM decides next action\n const response = await executeLLM(task, config.tools, history);\n\n // Check if task is complete\n if (response.status === 'COMPLETE' || !response.toolCalls || response.toolCalls.length === 0) {\n return {\n success: true,\n turns: turn + 1,\n history,\n finalResponse: response.response\n };\n }\n\n // Stale response detection: if LLM gives same text 2x in a row, it's done\n if (response.response && response.response.length > 20) {\n if (response.response === lastResponseText) {\n staleCount++;\n if (staleCount >= 2) {\n return {\n success: true,\n turns: turn + 1,\n history,\n finalResponse: response.response,\n reason: 'Detected stale response (same output repeated), treating as complete'\n };\n }\n } else {\n staleCount = 0;\n }\n lastResponseText = response.response;\n }\n\n // ACT: Execute tool calls \u2014 parallel when multiple, sequential when single\n if (response.toolCalls.length === 1) {\n // Single tool call \u2014 run directly\n const call = response.toolCalls[0];\n config.onProgress?.(turn + 1, `EXECUTING: ${call.tool}`);\n try {\n const result = await executeTool(call.tool, call.params);\n history.push({ turn: turn + 1, tool: call.tool, params: call.params, result });\n } catch (error: any) {\n history.push({ turn: turn + 1, tool: call.tool, params: call.params, result: null, error: error.message });\n }\n } else {\n // Multiple tool calls \u2014 run in parallel for speed\n config.onProgress?.(turn + 1, `EXECUTING ${response.toolCalls.length} tools in parallel`);\n const results = await Promise.allSettled(\n response.toolCalls.map(async (call) => {\n config.onProgress?.(turn + 1, `EXECUTING: ${call.tool}`);\n return { call, result: await executeTool(call.tool, call.params) };\n })\n );\n for (let i = 0; i < results.length; i++) {\n const r = results[i];\n const call = response.toolCalls[i];\n if (r.status === 'fulfilled') {\n history.push({ turn: turn + 1, tool: r.value.call.tool, params: r.value.call.params, result: r.value.result });\n } else {\n history.push({ turn: turn + 1, tool: call.tool, params: call.params, result: null, error: r.reason?.message || 'parallel execution failed' });\n }\n }\n }\n\n // Safety check: Detect if stuck in a loop\n if (turn > repeatThreshold && isRepeating(history, 3)) {\n return {\n success: false,\n turns: turn + 1,\n history,\n reason: 'Detected repeated actions, stopping to prevent infinite loop'\n };\n }\n }\n\n return {\n success: false,\n turns: maxTurns,\n history,\n reason: 'Maximum turns exceeded without completing task'\n };\n}\n\n/**\n * Detect if the agent is repeating the same actions\n */\nfunction isRepeating(history: TurnResult[], windowSize: number = 3): boolean {\n if (history.length < windowSize * 2) return false;\n\n const recentActions = history\n .slice(-windowSize)\n .map(h => `${h.tool}:${JSON.stringify(h.params)}`);\n\n const previousActions = history\n .slice(-windowSize * 2, -windowSize)\n .map(h => `${h.tool}:${JSON.stringify(h.params)}`);\n\n return JSON.stringify(recentActions) === JSON.stringify(previousActions);\n}\n\n/**\n * Format autonomous execution result for display\n */\nexport function formatAutonomousResult(result: AutonomousResult): string {\n let output = `\\n\uD83E\uDD16 Autonomous Execution ${result.success ? '\u2713' : '\u2717'}\\n`;\n output += `Turns: ${result.turns}/${result.history.length}\\n\\n`;\n\n for (const turn of result.history) {\n output += `Turn ${turn.turn}: ${turn.tool}\\n`;\n if (turn.error) {\n output += ` \u2717 Error: ${turn.error}\\n`;\n } else {\n const resultStr = typeof turn.result === 'string' \n ? turn.result.slice(0, 100) \n : JSON.stringify(turn.result).slice(0, 100);\n output += ` \u2713 ${resultStr}${resultStr.length >= 100 ? '...' : ''}\\n`;\n }\n }\n\n if (result.finalResponse) {\n output += `\\n\uD83D\uDCDD Final Response:\\n${result.finalResponse}\\n`;\n }\n\n if (result.reason) {\n output += `\\n\u26A0\uFE0F Stopped: ${result.reason}\\n`;\n }\n\n return output;\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Identity registry for all core tools.\n * Sits at the bottom of the dependency tree to prevent circular imports.\n */\n\n// ============================================================================\n// SHARED PARAMETER NAMES (used by multiple tools)\n// ============================================================================\n\nexport const PARAM_FILE_PATH = 'file_path';\nexport const PARAM_DIR_PATH = 'dir_path';\nexport const PARAM_PATTERN = 'pattern';\nexport const PARAM_CASE_SENSITIVE = 'case_sensitive';\nexport const PARAM_RESPECT_GIT_IGNORE = 'respect_git_ignore';\nexport const PARAM_RESPECT_GEMINI_IGNORE = 'respect_gemini_ignore';\nexport const PARAM_FILE_FILTERING_OPTIONS = 'file_filtering_options';\nexport const PARAM_DESCRIPTION = 'description';\n\n// ============================================================================\n// TOOL NAMES & TOOL-SPECIFIC PARAMETER NAMES\n// ============================================================================\n\n// -- glob --\nexport const GLOB_TOOL_NAME = 'glob';\n\n// -- grep_search --\nexport const GREP_TOOL_NAME = 'grep_search';\nexport const GREP_PARAM_INCLUDE_PATTERN = 'include_pattern';\nexport const GREP_PARAM_EXCLUDE_PATTERN = 'exclude_pattern';\nexport const GREP_PARAM_NAMES_ONLY = 'names_only';\nexport const GREP_PARAM_MAX_MATCHES_PER_FILE = 'max_matches_per_file';\nexport const GREP_PARAM_TOTAL_MAX_MATCHES = 'total_max_matches';\n// ripgrep only\nexport const GREP_PARAM_FIXED_STRINGS = 'fixed_strings';\nexport const GREP_PARAM_CONTEXT = 'context';\nexport const GREP_PARAM_AFTER = 'after';\nexport const GREP_PARAM_BEFORE = 'before';\nexport const GREP_PARAM_NO_IGNORE = 'no_ignore';\n\n// -- list_directory --\nexport const LS_TOOL_NAME = 'list_directory';\nexport const LS_PARAM_IGNORE = 'ignore';\n\n// -- read_file --\nexport const READ_FILE_TOOL_NAME = 'read_file';\nexport const READ_FILE_PARAM_START_LINE = 'start_line';\nexport const READ_FILE_PARAM_END_LINE = 'end_line';\n\n// -- run_shell_command --\nexport const SHELL_TOOL_NAME = 'run_shell_command';\nexport const SHELL_PARAM_COMMAND = 'command';\nexport const SHELL_PARAM_IS_BACKGROUND = 'is_background';\n\n// -- write_file --\nexport const WRITE_FILE_TOOL_NAME = 'write_file';\nexport const WRITE_FILE_PARAM_CONTENT = 'content';\n\n// -- replace (edit) --\nexport const EDIT_TOOL_NAME = 'replace';\nexport const EDIT_PARAM_INSTRUCTION = 'instruction';\nexport const EDIT_PARAM_OLD_STRING = 'old_string';\nexport const EDIT_PARAM_NEW_STRING = 'new_string';\nexport const EDIT_PARAM_ALLOW_MULTIPLE = 'allow_multiple';\n\n// -- google_web_search --\nexport const WEB_SEARCH_TOOL_NAME = 'google_web_search';\nexport const WEB_SEARCH_PARAM_QUERY = 'query';\n\n// -- write_todos --\nexport const WRITE_TODOS_TOOL_NAME = 'write_todos';\nexport const TODOS_PARAM_TODOS = 'todos';\nexport const TODOS_ITEM_PARAM_DESCRIPTION = 'description';\nexport const TODOS_ITEM_PARAM_STATUS = 'status';\n\n// -- web_fetch --\nexport const WEB_FETCH_TOOL_NAME = 'web_fetch';\nexport const WEB_FETCH_PARAM_PROMPT = 'prompt';\n\n// -- read_many_files --\nexport const READ_MANY_FILES_TOOL_NAME = 'read_many_files';\nexport const READ_MANY_PARAM_INCLUDE = 'include';\nexport const READ_MANY_PARAM_EXCLUDE = 'exclude';\nexport const READ_MANY_PARAM_RECURSIVE = 'recursive';\nexport const READ_MANY_PARAM_USE_DEFAULT_EXCLUDES = 'useDefaultExcludes';\n\n// -- save_memory --\nexport const MEMORY_TOOL_NAME = 'save_memory';\nexport const MEMORY_PARAM_FACT = 'fact';\n\n// -- get_internal_docs --\nexport const GET_INTERNAL_DOCS_TOOL_NAME = 'get_internal_docs';\nexport const DOCS_PARAM_PATH = 'path';\n\n// -- activate_skill --\nexport const ACTIVATE_SKILL_TOOL_NAME = 'activate_skill';\nexport const SKILL_PARAM_NAME = 'name';\n\n// -- ask_user --\nexport const ASK_USER_TOOL_NAME = 'ask_user';\nexport const ASK_USER_PARAM_QUESTIONS = 'questions';\n// ask_user question item params\nexport const ASK_USER_QUESTION_PARAM_QUESTION = 'question';\nexport const ASK_USER_QUESTION_PARAM_HEADER = 'header';\nexport const ASK_USER_QUESTION_PARAM_TYPE = 'type';\nexport const ASK_USER_QUESTION_PARAM_OPTIONS = 'options';\nexport const ASK_USER_QUESTION_PARAM_MULTI_SELECT = 'multiSelect';\nexport const ASK_USER_QUESTION_PARAM_PLACEHOLDER = 'placeholder';\n// ask_user option item params\nexport const ASK_USER_OPTION_PARAM_LABEL = 'label';\nexport const ASK_USER_OPTION_PARAM_DESCRIPTION = 'description';\n\n// -- exit_plan_mode --\nexport const EXIT_PLAN_MODE_TOOL_NAME = 'exit_plan_mode';\nexport const EXIT_PLAN_PARAM_PLAN_PATH = 'plan_path';\n\n// -- enter_plan_mode --\nexport const ENTER_PLAN_MODE_TOOL_NAME = 'enter_plan_mode';\nexport const PLAN_MODE_PARAM_REASON = 'reason';\n", "import { existsSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\n\n// Lazy-load typescript to avoid blocking ESM module init on Node 24+\n// (Node 24 ESM resolver can't resolve `import ts from 'typescript'` at top level)\nlet _ts: any;\nasync function ensureTs(): Promise<any> {\n if (!_ts) {\n _ts = await import('typescript').then(m => m.default ?? m);\n }\n return _ts;\n}\n\nexport interface LspDiagnostic {\n file: string;\n line: number;\n column: number;\n code: number;\n category: 'error' | 'warning' | 'suggestion' | 'message';\n message: string;\n}\n\nexport interface LspCompletion {\n name: string;\n kind: string;\n sortText?: string;\n}\n\nexport interface LspLocation {\n file: string;\n line: number;\n column: number;\n}\n\nexport interface LspSymbol {\n name: string;\n kind: string;\n line: number;\n column: number;\n}\n\ninterface LoadedProject {\n root: string;\n options: any;\n fileNames: string[];\n}\n\nfunction categoryToText(cat: number): LspDiagnostic['category'] {\n // ts.DiagnosticCategory.Error = 1, Warning = 0, Suggestion = 2, Message = 3\n if (cat === 1) return 'error';\n if (cat === 0) return 'warning';\n if (cat === 2) return 'suggestion';\n return 'message';\n}\n\nfunction loadProject(projectDir: string, ts: any): LoadedProject {\n const root = resolve(projectDir);\n const configPath = ts.findConfigFile(root, ts.sys.fileExists, 'tsconfig.json');\n if (!configPath) {\n throw new Error(`No tsconfig.json found at or above ${root}`);\n }\n\n const configFile = ts.readConfigFile(configPath, ts.sys.readFile);\n if (configFile.error) {\n throw new Error(ts.flattenDiagnosticMessageText(configFile.error.messageText, '\\n'));\n }\n\n const parsed = ts.parseJsonConfigFileContent(\n configFile.config,\n ts.sys,\n dirname(configPath)\n );\n if (parsed.errors.length > 0) {\n const first = parsed.errors[0];\n throw new Error(ts.flattenDiagnosticMessageText(first.messageText, '\\n'));\n }\n\n return {\n root,\n options: parsed.options,\n fileNames: parsed.fileNames\n };\n}\n\nexport async function typeCheckProject(projectDir: string, includeFiles: string[] = []): Promise<LspDiagnostic[]> {\n const ts = await ensureTs();\n const project = loadProject(projectDir, ts);\n const includeAbs = new Set(includeFiles.map(x => resolve(project.root, x)));\n const shouldFilter = includeAbs.size > 0;\n const host = ts.createCompilerHost(project.options, true);\n const program = ts.createProgram(project.fileNames, project.options, host);\n\n const diagnostics = ts.getPreEmitDiagnostics(program);\n const out: LspDiagnostic[] = [];\n for (const diagnostic of diagnostics) {\n const sourceFile = diagnostic.file;\n if (!sourceFile) continue;\n const absFile = resolve(sourceFile.fileName);\n if (shouldFilter && !includeAbs.has(absFile)) continue;\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(diagnostic.start ?? 0);\n out.push({\n file: absFile,\n line: line + 1,\n column: character + 1,\n code: diagnostic.code,\n category: categoryToText(diagnostic.category),\n message: ts.flattenDiagnosticMessageText(diagnostic.messageText, '\\n')\n });\n }\n return out;\n}\n\nfunction kindToText(kind: any): string {\n return String(kind || 'unknown');\n}\n\nfunction createLanguageService(projectDir: string, ts: any) {\n const project = loadProject(projectDir, ts);\n const sourceTexts = new Map<string, { version: number; text: string }>();\n for (const file of project.fileNames) {\n const text = ts.sys.readFile(file) || '';\n sourceTexts.set(resolve(file), { version: 1, text });\n }\n\n const serviceHost = {\n getCompilationSettings: () => project.options,\n getScriptFileNames: () => Array.from(sourceTexts.keys()),\n getScriptVersion: (fileName: string) => String(sourceTexts.get(resolve(fileName))?.version || 1),\n getScriptSnapshot: (fileName: string) => {\n const resolved = resolve(fileName);\n const entry = sourceTexts.get(resolved);\n if (!entry) return undefined;\n return ts.ScriptSnapshot.fromString(entry.text);\n },\n getCurrentDirectory: () => project.root,\n getDefaultLibFileName: (options: any) => ts.getDefaultLibFilePath(options),\n fileExists: ts.sys.fileExists,\n readFile: ts.sys.readFile,\n readDirectory: ts.sys.readDirectory,\n directoryExists: ts.sys.directoryExists,\n getDirectories: ts.sys.getDirectories\n };\n\n const service = ts.createLanguageService(serviceHost);\n return { service, project, sourceTexts };\n}\n\nfunction lineColToPosition(text: string, line: number, column: number): number {\n const lines = text.split('\\n');\n const lineIndex = Math.max(0, line - 1);\n const offset = lines.slice(0, lineIndex).reduce((sum: number, x: string) => sum + x.length + 1, 0) + Math.max(0, column - 1);\n return Math.min(offset, text.length);\n}\n\nexport async function getCompletions(\n projectDir: string,\n filePath: string,\n line: number,\n column: number,\n limit = 50,\n prefix = ''\n): Promise<LspCompletion[]> {\n const ts = await ensureTs();\n const { service, project, sourceTexts } = createLanguageService(projectDir, ts);\n try {\n const absFile = resolve(project.root, filePath);\n if (!existsSync(absFile)) {\n throw new Error(`File not found: ${absFile}`);\n }\n\n if (!sourceTexts.has(absFile)) {\n sourceTexts.set(absFile, { version: 1, text: ts.sys.readFile(absFile) || '' });\n }\n\n const fileText = sourceTexts.get(absFile)?.text || '';\n const lines = fileText.split('\\n');\n const lineIndex = Math.max(0, line - 1);\n const safeLine = lines[lineIndex] || '';\n const offset = lines.slice(0, lineIndex).reduce((sum: number, x: string) => sum + x.length + 1, 0) + Math.max(0, column - 1);\n const position = Math.min(offset, fileText.length);\n\n const completions = service.getCompletionsAtPosition(absFile, position, {\n includeCompletionsWithInsertText: true,\n includeCompletionsForModuleExports: true\n });\n\n const items = (completions?.entries || []).filter((entry: any) => {\n if (!prefix) return true;\n return entry.name.toLowerCase().startsWith(prefix.toLowerCase());\n });\n\n return items.slice(0, Math.max(1, limit)).map((entry: any) => ({\n name: entry.name,\n kind: kindToText(entry.kind),\n sortText: entry.sortText\n }));\n } finally {\n service.dispose();\n }\n}\n\nexport async function getDefinitions(projectDir: string, filePath: string, line: number, column: number): Promise<LspLocation[]> {\n const ts = await ensureTs();\n const { service, project, sourceTexts } = createLanguageService(projectDir, ts);\n try {\n const absFile = resolve(project.root, filePath);\n const fileText = sourceTexts.get(absFile)?.text || ts.sys.readFile(absFile) || '';\n const position = lineColToPosition(fileText, line, column);\n const defs = service.getDefinitionAtPosition(absFile, position) || [];\n return defs.map((def: any) => {\n const sf = service.getProgram()?.getSourceFile(def.fileName);\n const lc = sf?.getLineAndCharacterOfPosition(def.textSpan.start) || { line: 0, character: 0 };\n return {\n file: resolve(def.fileName),\n line: lc.line + 1,\n column: lc.character + 1\n };\n });\n } finally {\n service.dispose();\n }\n}\n\nexport async function getReferences(projectDir: string, filePath: string, line: number, column: number): Promise<LspLocation[]> {\n const ts = await ensureTs();\n const { service, project, sourceTexts } = createLanguageService(projectDir, ts);\n try {\n const absFile = resolve(project.root, filePath);\n const fileText = sourceTexts.get(absFile)?.text || ts.sys.readFile(absFile) || '';\n const position = lineColToPosition(fileText, line, column);\n const refs = service.getReferencesAtPosition(absFile, position) || [];\n return refs.map((ref: any) => {\n const sf = service.getProgram()?.getSourceFile(ref.fileName);\n const lc = sf?.getLineAndCharacterOfPosition(ref.textSpan.start) || { line: 0, character: 0 };\n return {\n file: resolve(ref.fileName),\n line: lc.line + 1,\n column: lc.character + 1\n };\n });\n } finally {\n service.dispose();\n }\n}\n\nexport async function getDocumentSymbols(projectDir: string, filePath: string): Promise<LspSymbol[]> {\n const ts = await ensureTs();\n const { service, project } = createLanguageService(projectDir, ts);\n try {\n const absFile = resolve(project.root, filePath);\n const nav = service.getNavigationTree(absFile);\n const out: LspSymbol[] = [];\n const walk = (node: any) => {\n for (const span of node.spans || []) {\n const sf = service.getProgram()?.getSourceFile(absFile);\n const lc = sf?.getLineAndCharacterOfPosition(span.start) || { line: 0, character: 0 };\n if (node.text && node.text !== '<global>') {\n out.push({\n name: node.text,\n kind: String(node.kind || 'unknown'),\n line: lc.line + 1,\n column: lc.character + 1\n });\n }\n }\n for (const child of node.childItems || []) walk(child);\n };\n walk(nav);\n return out;\n } finally {\n service.dispose();\n }\n}\n", "/**\n * Docker-based sandbox for safe command execution\n * Runs commands in isolated Docker containers with staged files\n */\n\nimport { execSync } from 'child_process';\nimport fs from 'fs';\nimport path from 'path';\nimport { randomUUID } from 'crypto';\n\nexport interface DockerSandboxOptions {\n workDir: string;\n image?: string;\n timeout?: number;\n env?: Record<string, string>;\n}\n\nexport interface DockerSandboxResult {\n success: boolean;\n output: string;\n exitCode: number;\n duration: number;\n}\n\nexport class DockerSandbox {\n private readonly defaultImage = 'node:20-slim';\n private readonly defaultTimeout = 30000; // 30 seconds\n \n /**\n * Check if Docker is available and running\n */\n async isDockerAvailable(): Promise<boolean> {\n try {\n execSync('docker info', { \n stdio: 'ignore',\n timeout: 5000 \n });\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Copy staged files from sandbox to temp directory\n */\n private async prepareTempDir(sandbox: any, tempDir: string): Promise<number> {\n const pendingPaths = sandbox.getPendingPaths();\n const branch = sandbox.state?.branches?.[sandbox.getActiveBranch()];\n \n if (!branch) return 0;\n\n let fileCount = 0;\n for (const filePath of pendingPaths) {\n const fileData = branch[filePath];\n if (!fileData?.modified) continue;\n\n const fullPath = path.join(tempDir, filePath);\n const dir = path.dirname(fullPath);\n \n // Create directory structure\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n // Write staged content\n fs.writeFileSync(fullPath, fileData.modified, 'utf8');\n fileCount++;\n }\n\n return fileCount;\n }\n\n /**\n * Run command in Docker container with staged files\n */\n async runCommand(\n command: string,\n sandbox: any,\n options: Partial<DockerSandboxOptions> = {}\n ): Promise<DockerSandboxResult> {\n const startTime = Date.now();\n const tempDir = path.join('/tmp', `crew-sandbox-${randomUUID()}`);\n const image = options.image || this.defaultImage;\n const timeout = options.timeout || this.defaultTimeout;\n const workDir = options.workDir || process.cwd();\n\n try {\n // Create temp directory\n fs.mkdirSync(tempDir, { recursive: true });\n console.log(`[Docker] Created temp dir: ${tempDir}`);\n\n // Copy staged files to temp dir\n const fileCount = await this.prepareTempDir(sandbox, tempDir);\n console.log(`[Docker] Copied ${fileCount} staged file(s) to sandbox`);\n\n // Copy package.json if it exists (for npm commands)\n const pkgPath = path.join(workDir, 'package.json');\n if (fs.existsSync(pkgPath)) {\n fs.copyFileSync(pkgPath, path.join(tempDir, 'package.json'));\n console.log(`[Docker] Copied package.json`);\n }\n\n // Copy node_modules if npm/node command (for dependencies)\n const needsNodeModules = /\\b(npm|node|npx)\\b/.test(command);\n if (needsNodeModules) {\n const nodeModulesPath = path.join(workDir, 'node_modules');\n if (fs.existsSync(nodeModulesPath)) {\n console.log(`[Docker] Copying node_modules (this may take a few seconds)...`);\n execSync(`cp -r \"${nodeModulesPath}\" \"${tempDir}/\"`, {\n stdio: 'ignore',\n timeout: 10000\n });\n }\n }\n\n // Build environment variables\n const envFlags = options.env \n ? Object.entries(options.env).map(([k, v]) => `-e ${k}=\"${v}\"`).join(' ')\n : '';\n\n // Run command in Docker\n console.log(`[Docker] Running: ${command}`);\n const dockerCmd = `docker run --rm -v \"${tempDir}\":/work -w /work ${envFlags} ${image} sh -c \"${command.replace(/\"/g, '\\\\\"')}\"`;\n \n const output = execSync(dockerCmd, {\n encoding: 'utf8',\n timeout,\n stdio: ['ignore', 'pipe', 'pipe']\n });\n\n const duration = Date.now() - startTime;\n console.log(`[Docker] \u2713 Command completed in ${duration}ms`);\n\n return {\n success: true,\n output,\n exitCode: 0,\n duration\n };\n\n } catch (err: any) {\n const duration = Date.now() - startTime;\n console.log(`[Docker] \u2717 Command failed after ${duration}ms`);\n \n return {\n success: false,\n output: err.stdout || err.stderr || err.message,\n exitCode: err.status || 1,\n duration\n };\n\n } finally {\n // Cleanup temp directory\n try {\n if (fs.existsSync(tempDir)) {\n fs.rmSync(tempDir, { recursive: true, force: true });\n console.log(`[Docker] Cleaned up temp dir`);\n }\n } catch (cleanupErr) {\n console.warn(`[Docker] Failed to cleanup ${tempDir}:`, cleanupErr);\n }\n }\n }\n\n /**\n * Pull Docker image if not present (with progress)\n */\n async ensureImage(image: string = this.defaultImage): Promise<boolean> {\n try {\n // Check if image exists\n execSync(`docker image inspect ${image}`, { \n stdio: 'ignore',\n timeout: 5000 \n });\n return true; // Image already exists\n } catch {\n // Image doesn't exist, pull it\n console.log(`[Docker] Pulling image ${image}...`);\n try {\n execSync(`docker pull ${image}`, {\n stdio: 'inherit', // Show progress\n timeout: 120000 // 2 minutes for image pull\n });\n console.log(`[Docker] \u2713 Image pulled successfully`);\n return true;\n } catch (pullErr) {\n console.error(`[Docker] Failed to pull image:`, pullErr);\n return false;\n }\n }\n }\n}\n", "/**\n * Adapter to use Gemini CLI tools with crew-cli's sandbox\n */\n\nimport { Sandbox } from '../../sandbox/index.js';\nimport { execSync } from 'node:child_process';\nimport { mkdir, readFile, readdir, stat, writeFile } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\nimport {\n GLOB_TOOL_NAME,\n GREP_TOOL_NAME,\n LS_TOOL_NAME,\n READ_FILE_TOOL_NAME,\n SHELL_TOOL_NAME,\n WRITE_FILE_TOOL_NAME,\n EDIT_TOOL_NAME,\n WEB_SEARCH_TOOL_NAME,\n WRITE_TODOS_TOOL_NAME,\n WEB_FETCH_TOOL_NAME,\n READ_MANY_FILES_TOOL_NAME,\n MEMORY_TOOL_NAME,\n GET_INTERNAL_DOCS_TOOL_NAME,\n ACTIVATE_SKILL_TOOL_NAME,\n ASK_USER_TOOL_NAME,\n EXIT_PLAN_MODE_TOOL_NAME,\n ENTER_PLAN_MODE_TOOL_NAME\n} from './definitions/base-declarations.js';\n\n// Minimal adapter types\nexport interface ToolResult {\n success: boolean;\n output?: string;\n error?: string;\n}\n\n// Create config adapter for Gemini tools\nexport class CrewConfig {\n constructor(private workspaceRoot: string) {}\n \n getWorkspaceRoot() {\n return this.workspaceRoot;\n }\n \n getTargetDir() {\n return this.workspaceRoot;\n }\n}\n\n// Create message bus adapter (auto-approve for CLI)\nexport class CrewMessageBus {\n async requestConfirmation(): Promise<{ status: 'approved' }> {\n return { status: 'approved' }; // Auto-approve for CLI\n }\n}\n\n// Shell timeout: configurable via CREW_SHELL_TIMEOUT env (seconds), default 120s, max 600s\nfunction getShellTimeout(): number {\n const envVal = parseInt(process.env.CREW_SHELL_TIMEOUT || '', 10);\n if (envVal > 0) return Math.min(envVal * 1000, 600000); // max 600s\n return 120000; // default 120s\n}\n\n// Dangerous shell commands that should warn (matches Claude Code behavior)\nconst DANGEROUS_SHELL_PATTERNS = [\n /\\brm\\s+-rf?\\s/, // rm -r / rm -rf\n /\\bgit\\s+push\\s+.*--force/, // force push\n /\\bgit\\s+reset\\s+--hard/, // hard reset\n /\\bgit\\s+clean\\s+-f/, // clean untracked\n /\\bdrop\\s+table\\b/i, // SQL drop\n /\\bdrop\\s+database\\b/i, // SQL drop database\n /\\bkill\\s+-9\\b/, // kill -9\n /\\bmkfs\\b/, // format filesystem\n /\\bdd\\s+if=/, // dd (disk destroyer)\n];\n\n// Background shell processes tracked by ID\nconst _backgroundProcesses = new Map<string, { promise: Promise<ToolResult>; startedAt: number }>();\n\n// Main adapter class\nexport class GeminiToolAdapter {\n private config: CrewConfig;\n private messageBus: CrewMessageBus;\n private _filesRead = new Set<string>(); // Track reads for read-before-edit guard\n\n constructor(private sandbox: Sandbox) {\n const workspaceRoot = (sandbox as any).baseDir || process.cwd();\n this.config = new CrewConfig(workspaceRoot);\n this.messageBus = new CrewMessageBus();\n }\n\n private buildDynamicDeclarations(): any[] {\n // Pull canonical names from Gemini base declarations and hydrate schemas from static declarations.\n const staticDecls = this.getStaticToolDeclarations();\n const staticByName = new Map<string, any>(staticDecls.map((d: any) => [d.name, d]));\n const canonicalNames = [\n READ_FILE_TOOL_NAME,\n WRITE_FILE_TOOL_NAME,\n EDIT_TOOL_NAME,\n GLOB_TOOL_NAME,\n GREP_TOOL_NAME,\n LS_TOOL_NAME,\n SHELL_TOOL_NAME,\n WEB_SEARCH_TOOL_NAME,\n WEB_FETCH_TOOL_NAME,\n READ_MANY_FILES_TOOL_NAME,\n MEMORY_TOOL_NAME,\n WRITE_TODOS_TOOL_NAME,\n GET_INTERNAL_DOCS_TOOL_NAME,\n ACTIVATE_SKILL_TOOL_NAME,\n ASK_USER_TOOL_NAME,\n ENTER_PLAN_MODE_TOOL_NAME,\n EXIT_PLAN_MODE_TOOL_NAME,\n 'grep_search_ripgrep',\n 'tracker_create_task',\n 'tracker_update_task',\n 'tracker_get_task',\n 'tracker_list_tasks',\n 'tracker_add_dependency',\n 'tracker_visualize',\n 'spawn_agent',\n 'check_background_task'\n ];\n const canonical = canonicalNames.map((name) => {\n const found = staticByName.get(name);\n if (found) return found;\n return {\n name,\n description: `${name} tool`,\n parameters: { type: 'object', properties: {} }\n };\n });\n\n const aliases = [\n { alias: 'read_file', target: 'read_file' },\n { alias: 'write_file', target: 'write_file' },\n { alias: 'append_file', target: 'write_file' },\n { alias: 'edit', target: 'replace' },\n { alias: 'replace', target: 'replace' },\n { alias: 'glob', target: 'glob' },\n { alias: 'grep', target: 'grep_search' },\n { alias: 'grep_search', target: 'grep_search' },\n { alias: 'grep_search_ripgrep', target: 'grep_search_ripgrep' },\n { alias: 'list', target: 'list_directory' },\n { alias: 'list_directory', target: 'list_directory' },\n { alias: 'shell', target: 'run_shell_command' },\n { alias: 'run_cmd', target: 'run_shell_command' },\n { alias: 'run_shell_command', target: 'run_shell_command' },\n { alias: 'web_search', target: 'google_web_search' },\n { alias: 'google_web_search', target: 'google_web_search' },\n { alias: 'web_fetch', target: 'web_fetch' },\n { alias: 'save_memory', target: 'save_memory' },\n { alias: 'write_todos', target: 'write_todos' },\n { alias: 'get_internal_docs', target: 'get_internal_docs' },\n { alias: 'ask_user', target: 'ask_user' },\n { alias: 'enter_plan_mode', target: 'enter_plan_mode' },\n { alias: 'exit_plan_mode', target: 'exit_plan_mode' },\n { alias: 'activate_skill', target: 'activate_skill' },\n { alias: 'tracker_create_task', target: 'tracker_create_task' },\n { alias: 'tracker_update_task', target: 'tracker_update_task' },\n { alias: 'tracker_get_task', target: 'tracker_get_task' },\n { alias: 'tracker_list_tasks', target: 'tracker_list_tasks' },\n { alias: 'tracker_add_dependency', target: 'tracker_add_dependency' },\n { alias: 'tracker_visualize', target: 'tracker_visualize' },\n { alias: 'mkdir', target: 'write_file' },\n { alias: 'git', target: 'run_shell_command' },\n // LSP is not yet implemented \u2014 don't alias to read_file (misleads the model)\n // { alias: 'lsp', target: 'read_file' }\n ];\n\n const byName = new Map<string, any>();\n for (const decl of canonical) byName.set(decl.name, decl);\n for (const a of aliases) {\n const target = byName.get(a.target);\n if (!target) continue;\n if (!byName.has(a.alias)) {\n byName.set(a.alias, { ...target, name: a.alias });\n }\n }\n // Local compatibility schemas for non-Gemini built-ins we support in adapter.\n byName.set('mkdir', {\n name: 'mkdir',\n description: 'Create a directory path (staged via sandbox).',\n parameters: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Directory path to create' },\n dir_path: { type: 'string', description: 'Alternative directory path field' }\n }\n }\n });\n byName.set('git', {\n name: 'git',\n description: 'Run limited git subcommands (status/diff/log/add/commit/show/branch).',\n parameters: {\n type: 'object',\n properties: {\n command: { type: 'string', description: 'Git subcommand and args' }\n },\n required: ['command']\n }\n });\n byName.set('lsp', {\n name: 'lsp',\n description: 'Run code-intel queries (symbols/refs/goto/diagnostics/complete).',\n parameters: {\n type: 'object',\n properties: {\n query: { type: 'string', description: 'LSP query string' }\n },\n required: ['query']\n }\n });\n return Array.from(byName.values());\n }\n\n private getStaticToolDeclarations() {\n return [\n { name: 'read_file', description: 'Read file', parameters: { type: 'object', properties: { file_path: { type: 'string' } }, required: ['file_path'] } },\n { name: 'write_file', description: 'Write file', parameters: { type: 'object', properties: { file_path: { type: 'string' }, content: { type: 'string' } }, required: ['file_path', 'content'] } },\n { name: 'replace', description: 'Replace text in file. old_string must uniquely match one location (use replace_all:true for all occurrences). You MUST read_file before editing.', parameters: { type: 'object', properties: { file_path: { type: 'string' }, old_string: { type: 'string' }, new_string: { type: 'string' }, replace_all: { type: 'boolean', description: 'Replace ALL occurrences (useful for renames). Default: false (unique match required)' } }, required: ['file_path', 'old_string', 'new_string'] } },\n { name: 'glob', description: 'Glob search', parameters: { type: 'object', properties: { pattern: { type: 'string' } }, required: ['pattern'] } },\n { name: 'grep_search', description: 'Search for regex/text in files. Supports output modes (content/files/count), context lines, case insensitivity, file type filters.', parameters: { type: 'object', properties: { pattern: { type: 'string' }, path: { type: 'string' }, dir_path: { type: 'string' }, output_mode: { type: 'string', description: 'content (matching lines), files (file paths only), count (match counts)' }, context: { type: 'number', description: 'Lines of context around matches' }, before: { type: 'number' }, after: { type: 'number' }, case_insensitive: { type: 'boolean' }, type: { type: 'string', description: 'File type filter (js, py, ts, go, etc.)' }, max_results: { type: 'number' } }, required: ['pattern'] } },\n { name: 'grep_search_ripgrep', description: 'Alias for grep_search with same capabilities', parameters: { type: 'object', properties: { pattern: { type: 'string' }, path: { type: 'string' }, dir_path: { type: 'string' }, output_mode: { type: 'string' }, context: { type: 'number' }, case_insensitive: { type: 'boolean' }, type: { type: 'string' }, max_results: { type: 'number' } }, required: ['pattern'] } },\n { name: 'list_directory', description: 'List directory', parameters: { type: 'object', properties: { dir_path: { type: 'string' }, path: { type: 'string' } } } },\n { name: 'run_shell_command', description: 'Run shell command (configurable timeout, Docker isolation when staged files exist). Use run_in_background:true for long-running commands.', parameters: { type: 'object', properties: { command: { type: 'string' }, run_in_background: { type: 'boolean', description: 'Run in background and return task ID. Use check_background_task to get result.' }, description: { type: 'string', description: 'Brief description of what the command does' } }, required: ['command'] } },\n { name: 'google_web_search', description: 'Web search', parameters: { type: 'object', properties: { query: { type: 'string' } }, required: ['query'] } },\n { name: 'web_fetch', description: 'Fetch URL', parameters: { type: 'object', properties: { url: { type: 'string' }, prompt: { type: 'string' } } } },\n { name: 'read_many_files', description: 'Read many files', parameters: { type: 'object', properties: { include: { type: 'string' }, exclude: { type: 'string' }, recursive: { type: 'boolean' } } } },\n { name: 'save_memory', description: 'Save memory fact', parameters: { type: 'object', properties: { fact: { type: 'string' } }, required: ['fact'] } },\n { name: 'write_todos', description: 'Write todos', parameters: { type: 'object', properties: { todos: { type: 'array', items: { type: 'object', properties: { text: { type: 'string' }, done: { type: 'boolean' } } } } }, required: ['todos'] } },\n { name: 'get_internal_docs', description: 'Read internal docs', parameters: { type: 'object', properties: { path: { type: 'string' } } } },\n { name: 'ask_user', description: 'Ask user placeholder', parameters: { type: 'object', properties: { questions: { type: 'array', items: { type: 'object', properties: { question: { type: 'string' } } } } } } },\n { name: 'enter_plan_mode', description: 'Enter plan mode', parameters: { type: 'object', properties: { reason: { type: 'string' } } } },\n { name: 'exit_plan_mode', description: 'Exit plan mode', parameters: { type: 'object', properties: { plan_path: { type: 'string' } } } },\n { name: 'activate_skill', description: 'Activate skill', parameters: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] } },\n { name: 'tracker_create_task', description: 'Create tracker task', parameters: { type: 'object', properties: { title: { type: 'string' }, description: { type: 'string' }, type: { type: 'string' }, parentId: { type: 'string' }, dependencies: { type: 'array', items: { type: 'string' } } }, required: ['title', 'description', 'type'] } },\n { name: 'tracker_update_task', description: 'Update tracker task', parameters: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] } },\n { name: 'tracker_get_task', description: 'Get tracker task', parameters: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] } },\n { name: 'tracker_list_tasks', description: 'List tracker tasks', parameters: { type: 'object', properties: { status: { type: 'string' }, type: { type: 'string' }, parentId: { type: 'string' } } } },\n { name: 'tracker_add_dependency', description: 'Add tracker dependency', parameters: { type: 'object', properties: { taskId: { type: 'string' }, dependencyId: { type: 'string' } }, required: ['taskId', 'dependencyId'] } },\n { name: 'tracker_visualize', description: 'Visualize tracker graph', parameters: { type: 'object', properties: {} } },\n { name: 'spawn_agent', description: 'Spawn a sub-agent to handle a task autonomously in parallel. Use for independent research, file analysis, or coding subtasks. Returns the sub-agent result when complete.', parameters: { type: 'object', properties: { task: { type: 'string', description: 'Clear task description for the sub-agent' }, model: { type: 'string', description: 'Optional model override (default: use cheap model for workers)' }, max_turns: { type: 'number', description: 'Max turns for sub-agent (default: 15)' } }, required: ['task'] } },\n { name: 'check_background_task', description: 'Check the status/result of a background shell command. Returns result if done, or elapsed time if still running.', parameters: { type: 'object', properties: { task_id: { type: 'string', description: 'Task ID returned by run_shell_command with run_in_background:true' } }, required: ['task_id'] } }\n ];\n }\n\n /**\n * Execute a tool call from LLM\n */\n async executeTool(toolName: string, params: any): Promise<ToolResult> {\n try {\n switch (toolName) {\n // Canonical Gemini names + local aliases\n case 'write_file':\n return await this.writeFile(params);\n case 'replace':\n return await this.editFile({\n file_path: params.file_path,\n old_string: params.old_string,\n new_string: params.new_string,\n replace_all: params.replace_all\n });\n case 'append_file':\n return await this.appendFile(params);\n case 'read_file':\n return await this.readFile(params);\n case 'edit':\n return await this.editFile(params);\n case 'read_many_files':\n return await this.readManyFilesTool(params);\n case 'save_memory':\n return await this.saveMemoryTool(params);\n case 'write_todos':\n return await this.writeTodosTool(params);\n case 'get_internal_docs':\n return await this.getInternalDocsTool(params);\n case 'ask_user':\n return await this.askUserTool(params);\n case 'enter_plan_mode':\n return await this.enterPlanModeTool(params);\n case 'exit_plan_mode':\n return await this.exitPlanModeTool(params);\n case 'activate_skill':\n return await this.activateSkillTool(params);\n case 'mkdir':\n return await this.mkdirTool(params);\n case 'list':\n return await this.listTool(params);\n case 'list_directory':\n return await this.listTool({ dir_path: params.dir_path || params.path });\n case 'glob':\n return await this.globTool(params);\n case 'grep':\n return await this.grepTool(params);\n case 'grep_search':\n case 'grep_search_ripgrep':\n return await this.grepTool({\n pattern: params.pattern,\n path: params.dir_path || params.path,\n output_mode: params.output_mode,\n context: params.context,\n before: params.before,\n after: params.after,\n case_insensitive: params.case_insensitive,\n type: params.type,\n max_results: params.max_results\n });\n case 'git':\n return await this.gitTool(params);\n case 'shell':\n case 'run_cmd':\n case 'run_shell_command':\n return await this.shellTool(params);\n case 'lsp':\n return await this.lspTool(params);\n case 'web_search':\n case 'google_web_search':\n return await this.webSearchTool(params);\n case 'web_fetch':\n return await this.webFetchTool(params);\n case 'tracker_create_task':\n return await this.trackerCreateTaskTool(params);\n case 'tracker_update_task':\n return await this.trackerUpdateTaskTool(params);\n case 'tracker_get_task':\n return await this.trackerGetTaskTool(params);\n case 'tracker_list_tasks':\n return await this.trackerListTasksTool(params);\n case 'tracker_add_dependency':\n return await this.trackerAddDependencyTool(params);\n case 'tracker_visualize':\n return await this.trackerVisualizeTool();\n case 'spawn_agent':\n return await this.spawnAgentTool(params);\n case 'check_background_task':\n return await this.checkBackgroundTask(params);\n default:\n return {\n success: false,\n error: `Unknown tool: ${toolName}`\n };\n }\n } catch (err: any) {\n return {\n success: false,\n error: err.message\n };\n }\n }\n \n private async writeFile(params: { file_path: string; content: string }): Promise<ToolResult> {\n // Path traversal guard\n const fullPath = resolve(this.config.getWorkspaceRoot(), params.file_path);\n const wsRoot = resolve(this.config.getWorkspaceRoot());\n if (!fullPath.startsWith(wsRoot + '/') && fullPath !== wsRoot) {\n return { success: false, error: `Access denied: path \"${params.file_path}\" resolves outside workspace root.` };\n }\n // Stage in sandbox instead of writing directly\n await this.sandbox.addChange(params.file_path, params.content);\n return {\n success: true,\n output: `Staged ${params.file_path} (${params.content.length} bytes)`\n };\n }\n\n private async appendFile(params: { file_path: string; content: string }): Promise<ToolResult> {\n const filePath = resolve(this.config.getWorkspaceRoot(), params.file_path);\n let existing = '';\n try {\n const stagedContent = this.sandbox.getStagedContent?.(params.file_path)\n || this.sandbox.getStagedContent?.(filePath);\n existing = stagedContent ?? await readFile(filePath, 'utf8');\n } catch {\n existing = '';\n }\n const combined = `${existing}${params.content || ''}`;\n await this.sandbox.addChange(params.file_path, combined);\n return {\n success: true,\n output: `Appended ${params.file_path} (${(params.content || '').length} bytes)`\n };\n }\n \n private async readFile(params: { file_path: string; start_line?: number; end_line?: number }): Promise<ToolResult> {\n const filePath = resolve(this.config.getWorkspaceRoot(), params.file_path);\n\n // Path traversal guard: ensure resolved path is within workspace\n const wsRoot = resolve(this.config.getWorkspaceRoot());\n if (!filePath.startsWith(wsRoot + '/') && filePath !== wsRoot) {\n return { success: false, error: `Access denied: path \"${params.file_path}\" resolves outside workspace root.` };\n }\n\n // Track that this file has been read (for read-before-edit guard)\n this._filesRead.add(params.file_path);\n this._filesRead.add(filePath);\n\n // Check sandbox first for staged (not yet applied) changes\n const stagedContent = this.sandbox.getStagedContent?.(params.file_path)\n || this.sandbox.getStagedContent?.(filePath);\n const content = stagedContent ?? await readFile(filePath, 'utf8');\n \n if (params.start_line || params.end_line) {\n const lines = content.split('\\n');\n const start = (params.start_line || 1) - 1;\n const end = params.end_line || lines.length;\n const slice = lines.slice(start, end).join('\\n');\n return { success: true, output: slice };\n }\n \n return { success: true, output: content };\n }\n \n private async editFile(params: { file_path: string; old_string: string; new_string: string; replace_all?: boolean }): Promise<ToolResult> {\n const filePath = resolve(this.config.getWorkspaceRoot(), params.file_path);\n\n // Path traversal guard\n const wsRoot = resolve(this.config.getWorkspaceRoot());\n if (!filePath.startsWith(wsRoot + '/') && filePath !== wsRoot) {\n return { success: false, error: `Access denied: path \"${params.file_path}\" resolves outside workspace root.` };\n }\n\n // Read-before-edit guard: require the file to have been read first (matches Claude Code)\n if (!this._filesRead.has(params.file_path) && !this._filesRead.has(filePath)) {\n return {\n success: false,\n error: `You must read_file \"${params.file_path}\" before editing it. Never guess at file contents.`\n };\n }\n\n // Read current content (could be staged)\n const stagedContent = this.sandbox.getStagedContent?.(params.file_path)\n || this.sandbox.getStagedContent?.(filePath);\n const content = stagedContent ?? await readFile(filePath, 'utf8');\n\n if (!content.includes(params.old_string)) {\n return {\n success: false,\n error: `String not found in ${params.file_path}`\n };\n }\n\n const occurrences = content.split(params.old_string).length - 1;\n\n // replace_all mode: replace every occurrence (useful for renames)\n if (params.replace_all) {\n const updated = content.split(params.old_string).join(params.new_string);\n await this.sandbox.addChange(params.file_path, updated);\n const diagnostics = await this.shadowValidate(params.file_path);\n return {\n success: true,\n output: `Edited ${params.file_path} (${occurrences} replacements)${diagnostics}`\n };\n }\n\n // Default: unique match required\n if (occurrences > 1) {\n return {\n success: false,\n error: `old_string matches ${occurrences} locations in ${params.file_path}. Provide more context to make it unique, or use replace_all:true to replace all occurrences.`\n };\n }\n\n const updated = content.replace(params.old_string, params.new_string);\n await this.sandbox.addChange(params.file_path, updated);\n\n // Shadow validation: run diagnostics on the edited file (Cursor-style)\n const diagnostics = await this.shadowValidate(params.file_path);\n\n return {\n success: true,\n output: `Edited ${params.file_path}${diagnostics}`\n };\n }\n\n /**\n * Shadow validation: after an edit, check for type/lint errors using LSP.\n * Returns empty string if clean, or diagnostic summary if errors found.\n * Non-fatal \u2014 silently returns empty on any failure.\n */\n private async shadowValidate(filePath: string): Promise<string> {\n // Only validate TypeScript/JavaScript files\n if (!/\\.(ts|tsx|js|jsx|mjs|mts)$/.test(filePath)) return '';\n\n try {\n const lsp = await import('../../lsp/index.js');\n const diags = await lsp.typeCheckProject(this.config.getWorkspaceRoot(), [filePath]);\n\n // Filter to only errors in the edited file\n const fileErrors = diags.filter((d: any) =>\n d.category === 'error' && d.file?.endsWith(filePath)\n );\n\n if (fileErrors.length === 0) return '';\n\n const errorLines = fileErrors.slice(0, 5).map((d: any) =>\n ` ${d.file}:${d.line} \u2014 ${d.message}`\n );\n\n return `\\n\\n\u26A0\uFE0F Shadow validation found ${fileErrors.length} error(s) after edit:\\n${errorLines.join('\\n')}${fileErrors.length > 5 ? `\\n ... and ${fileErrors.length - 5} more` : ''}\\nFix these before moving on.`;\n } catch {\n // LSP not available or failed \u2014 non-fatal\n return '';\n }\n }\n\n private async mkdirTool(params: { path?: string; dir_path?: string }): Promise<ToolResult> {\n const dir = (params.path || params.dir_path || '').trim();\n if (!dir) return { success: false, error: 'mkdir requires path' };\n const keep = join(dir, '.gitkeep');\n await this.sandbox.addChange(keep, '');\n return { success: true, output: `Staged directory ${dir}` };\n }\n\n private async listTool(params: { path?: string; dir_path?: string }): Promise<ToolResult> {\n const target = (params.path || params.dir_path || '.').trim();\n const abs = resolve(process.cwd(), target);\n const items = await readdir(abs, { withFileTypes: true });\n const lines = items.map(i => `${i.isDirectory() ? 'd' : 'f'} ${i.name}`);\n return { success: true, output: lines.join('\\n') };\n }\n\n private async globTool(params: { pattern: string }): Promise<ToolResult> {\n const pattern = String(params.pattern || '').trim();\n if (!pattern) return { success: false, error: 'glob requires pattern' };\n try {\n const out = execSync(`rg --files -g ${JSON.stringify(pattern)}`, { cwd: process.cwd(), stdio: 'pipe', encoding: 'utf8' });\n return { success: true, output: out.trim() };\n } catch (err: any) {\n return { success: false, error: err?.stderr?.toString?.() || err?.message || 'glob failed' };\n }\n }\n\n private async grepTool(params: {\n pattern: string;\n path?: string;\n output_mode?: 'content' | 'files' | 'count';\n context?: number;\n before?: number;\n after?: number;\n case_insensitive?: boolean;\n type?: string;\n max_results?: number;\n }): Promise<ToolResult> {\n const pattern = String(params.pattern || '').trim();\n const searchPath = String(params.path || '.').trim();\n if (!pattern) return { success: false, error: 'grep requires pattern' };\n\n const args = ['rg'];\n\n // Output mode (matches Claude Code's Grep tool)\n const mode = params.output_mode || 'content';\n if (mode === 'files') {\n args.push('-l'); // files_with_matches\n } else if (mode === 'count') {\n args.push('-c'); // count\n } else {\n args.push('-n'); // line numbers for content mode\n }\n\n // Context flags\n if (params.context) args.push(`-C${params.context}`);\n else {\n if (params.before) args.push(`-B${params.before}`);\n if (params.after) args.push(`-A${params.after}`);\n }\n\n // Case insensitive\n if (params.case_insensitive) args.push('-i');\n\n // File type filter\n if (params.type) args.push(`--type=${params.type}`);\n\n // Max results\n if (params.max_results) args.push(`-m${params.max_results}`);\n\n args.push(JSON.stringify(pattern), JSON.stringify(searchPath));\n\n try {\n const out = execSync(args.join(' '), {\n cwd: process.cwd(),\n stdio: 'pipe',\n encoding: 'utf8'\n });\n return { success: true, output: out.trim() };\n } catch (err: any) {\n const text = `${err?.stdout?.toString?.() || ''}\\n${err?.stderr?.toString?.() || ''}`.trim();\n // rg returns exit code 1 for no matches \u2014 that's not an error\n if (err?.status === 1 && !text) return { success: true, output: '(no matches)' };\n return { success: false, error: text || err?.message || 'grep failed' };\n }\n }\n\n private async gitTool(params: { command: string }): Promise<ToolResult> {\n const command = String(params.command || '').trim();\n if (!command) return { success: false, error: 'git requires command' };\n\n // Expanded allowed subcommands (matches Claude Code git safety protocol)\n const allowed = ['status', 'diff', 'log', 'add', 'commit', 'show', 'branch', 'stash', 'tag', 'blame', 'checkout', 'switch', 'restore', 'rev-parse', 'remote', 'fetch', 'pull', 'push', 'merge', 'rebase', 'reset', 'cherry-pick', 'worktree'];\n const verb = command.split(/\\s+/)[0];\n if (!allowed.includes(verb)) {\n return { success: false, error: `git subcommand not allowed: ${verb}. Allowed: ${allowed.join(', ')}` };\n }\n\n // Safety guards (Claude Code pattern: never force push, never skip hooks)\n if (/--force|--force-with-lease/.test(command) && verb === 'push') {\n return { success: false, error: 'Force push is not allowed. Use a regular push or create a new branch.' };\n }\n if (/--no-verify/.test(command)) {\n return { success: false, error: 'Skipping hooks (--no-verify) is not allowed. Fix the hook issue instead.' };\n }\n if (verb === 'reset' && /--hard/.test(command)) {\n return { success: false, error: 'git reset --hard is destructive. Use git stash or git checkout <file> instead.' };\n }\n\n // Reject shell metacharacters to prevent command injection\n if (/[;&|`$(){}\\\\!<>]/.test(command)) {\n return { success: false, error: 'git command contains disallowed shell characters. Use only git arguments.' };\n }\n\n try {\n const args = command.split(/\\s+/).filter(Boolean);\n const { execFileSync } = await import('node:child_process');\n const out = execFileSync('git', args, {\n cwd: this.config.getWorkspaceRoot(),\n stdio: 'pipe',\n encoding: 'utf8',\n timeout: 30000\n });\n return { success: true, output: out.trim() };\n } catch (err: any) {\n const text = `${err?.stdout?.toString?.() || ''}\\n${err?.stderr?.toString?.() || ''}`.trim();\n return { success: false, error: text || err?.message || 'git failed' };\n }\n }\n\n private async shellTool(params: { command: string; run_in_background?: boolean; description?: string }): Promise<ToolResult> {\n const command = String(params.command || '').trim();\n if (!command) return { success: false, error: 'shell requires command' };\n\n // Dangerous command detection \u2014 block destructive patterns\n for (const pat of DANGEROUS_SHELL_PATTERNS) {\n if (pat.test(command)) {\n return { success: false, error: `Blocked: destructive command detected (${command.slice(0, 60)}). Use a safer alternative.` };\n }\n }\n\n // Background execution: run command asynchronously, return task ID\n if (params.run_in_background) {\n const taskId = `bg_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;\n const bgPromise = (async (): Promise<ToolResult> => {\n try {\n const { spawn } = await import('node:child_process');\n return new Promise((resolve) => {\n const proc = spawn('sh', ['-c', command], {\n cwd: this.config.getWorkspaceRoot(),\n stdio: 'pipe'\n });\n let stdout = '', stderr = '';\n proc.stdout?.on('data', (d: Buffer) => { stdout += d.toString(); });\n proc.stderr?.on('data', (d: Buffer) => { stderr += d.toString(); });\n const timeout = setTimeout(() => { proc.kill('SIGTERM'); resolve({ success: false, error: 'Background task timed out' }); }, getShellTimeout());\n proc.on('close', (code: number | null) => {\n clearTimeout(timeout);\n resolve(code === 0\n ? { success: true, output: stdout.trim() }\n : { success: false, error: (stderr || stdout).trim() || `exit code ${code}` });\n });\n });\n } catch (err: any) {\n return { success: false, error: err.message };\n }\n })();\n _backgroundProcesses.set(taskId, { promise: bgPromise, startedAt: Date.now() });\n return { success: true, output: `Background task started: ${taskId}\\nUse check_background_task with this ID to get the result.` };\n }\n \n try {\n // Check if we have staged files - if so, use Docker sandbox\n const hasStagedFiles = this.sandbox.getPendingPaths().length > 0;\n \n if (hasStagedFiles) {\n const { DockerSandbox } = await import('../docker-sandbox.js');\n const docker = new DockerSandbox();\n const dockerAvailable = await docker.isDockerAvailable();\n \n if (dockerAvailable) {\n console.log(`[GeminiAdapter] Running command in Docker with ${this.sandbox.getPendingPaths().length} staged file(s)`);\n const result = await docker.runCommand(command, this.sandbox, {\n workDir: this.config.getWorkspaceRoot(),\n timeout: getShellTimeout()\n });\n return {\n success: result.success,\n output: result.output,\n error: result.success ? undefined : result.output\n };\n } else {\n console.warn('[GeminiAdapter] Docker unavailable - running natively (staged files not available to command)');\n }\n }\n \n // Fallback: run natively from workspace root\n const out = execSync(command, {\n cwd: this.config.getWorkspaceRoot(),\n stdio: 'pipe',\n encoding: 'utf8',\n timeout: getShellTimeout()\n });\n return { success: true, output: out.trim() };\n } catch (err: any) {\n const text = `${err?.stdout?.toString?.() || ''}\\n${err?.stderr?.toString?.() || ''}`.trim();\n return { success: false, error: text || err?.message || 'shell failed' };\n }\n }\n\n private async webSearchTool(params: { query: string }): Promise<ToolResult> {\n const query = String(params.query || '').trim();\n if (!query) return { success: false, error: 'web_search requires query' };\n const braveKey = process.env.BRAVE_API_KEY || process.env.BRAVE_SEARCH_API_KEY;\n if (!braveKey) return { success: false, error: 'web_search unavailable (missing BRAVE_API_KEY)' };\n try {\n const res = await fetch(\n `https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(query)}&count=5`,\n {\n headers: {\n 'Accept': 'application/json',\n 'X-Subscription-Token': braveKey\n },\n signal: AbortSignal.timeout(10000)\n }\n );\n if (!res.ok) return { success: false, error: `web_search failed: HTTP ${res.status}` };\n const data: any = await res.json();\n const hits = (data?.web?.results || []).slice(0, 5);\n const formatted = hits.map((r: any, i: number) =>\n `${i + 1}. ${r.title || '(untitled)'}\\n${r.url || ''}\\n${r.description || ''}`\n ).join('\\n\\n');\n return { success: true, output: formatted || 'No results' };\n } catch (err: any) {\n return { success: false, error: err?.message || 'web_search failed' };\n }\n }\n\n private async webFetchTool(params: { url: string }): Promise<ToolResult> {\n const url = String(params.url || '').trim();\n if (!url || !/^https?:\\/\\//i.test(url)) {\n return { success: false, error: 'web_fetch requires valid http(s) url' };\n }\n try {\n const res = await fetch(url, {\n headers: { 'User-Agent': 'CrewSwarm-CLI/1.0' },\n signal: AbortSignal.timeout(12000)\n });\n if (!res.ok) return { success: false, error: `web_fetch failed: HTTP ${res.status}` };\n const ct = String(res.headers.get('content-type') || '');\n let text = await res.text();\n if (ct.includes('html')) {\n text = text\n .replace(/<script[\\s\\S]*?<\\/script>/gi, '')\n .replace(/<style[\\s\\S]*?<\\/style>/gi, '')\n .replace(/<[^>]+>/g, ' ')\n .replace(/\\s{2,}/g, ' ')\n .trim();\n }\n return { success: true, output: text.slice(0, 12000) };\n } catch (err: any) {\n return { success: false, error: err?.message || 'web_fetch failed' };\n }\n }\n\n private async readManyFilesTool(params: {\n include?: string;\n exclude?: string | string[];\n recursive?: boolean;\n }): Promise<ToolResult> {\n const include = String(params.include || '**/*').trim();\n try {\n const out = execSync(`rg --files -g ${JSON.stringify(include)}`, {\n cwd: this.config.getWorkspaceRoot(),\n stdio: 'pipe',\n encoding: 'utf8'\n });\n const files = out.split('\\n').filter(Boolean).slice(0, 20);\n const chunks: string[] = [];\n for (const rel of files) {\n const full = resolve(this.config.getWorkspaceRoot(), rel);\n try {\n const content = await readFile(full, 'utf8');\n chunks.push(`--- ${rel} ---\\n${content.slice(0, 2000)}`);\n } catch {\n // Skip unreadable/non-text\n }\n }\n return { success: true, output: chunks.join('\\n\\n') || 'No readable files matched' };\n } catch (err: any) {\n return { success: false, error: err?.message || 'read_many_files failed' };\n }\n }\n\n private async saveMemoryTool(params: { fact: string }): Promise<ToolResult> {\n const fact = String(params.fact || '').trim();\n if (!fact) return { success: false, error: 'save_memory requires fact' };\n const memDir = resolve(this.config.getWorkspaceRoot(), '.crew');\n await mkdir(memDir, { recursive: true });\n const memFile = resolve(memDir, 'memory-facts.log');\n let prior = '';\n try { prior = await readFile(memFile, 'utf8'); } catch {}\n await writeFile(memFile, `${prior}${new Date().toISOString()} ${fact}\\n`, 'utf8');\n return { success: true, output: 'Memory saved' };\n }\n\n private async writeTodosTool(params: { todos: any[] }): Promise<ToolResult> {\n const todos = Array.isArray(params.todos) ? params.todos : [];\n const memDir = resolve(this.config.getWorkspaceRoot(), '.crew');\n await mkdir(memDir, { recursive: true });\n const todoFile = resolve(memDir, 'todos.json');\n await writeFile(todoFile, JSON.stringify(todos, null, 2), 'utf8');\n return { success: true, output: `Saved ${todos.length} todos` };\n }\n\n private async getInternalDocsTool(params: { path?: string }): Promise<ToolResult> {\n const target = String(params.path || 'AGENTS.md').trim();\n const abs = resolve(this.config.getWorkspaceRoot(), target);\n try {\n const content = await readFile(abs, 'utf8');\n return { success: true, output: content.slice(0, 12000) };\n } catch (err: any) {\n return { success: false, error: `get_internal_docs failed: ${err?.message || target}` };\n }\n }\n\n private async askUserTool(params: { questions?: any[] }): Promise<ToolResult> {\n const qs = Array.isArray(params.questions) ? params.questions : [];\n if (qs.length === 0) {\n return { success: false, error: 'ask_user requires at least one question' };\n }\n const now = new Date().toISOString();\n const request = {\n id: `ask-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`,\n ts: now,\n status: 'pending',\n questions: qs\n };\n const crewDir = this.crewDirPath();\n await mkdir(crewDir, { recursive: true });\n await this.appendJsonLine(this.askUserRequestsPath(), request);\n await writeFile(this.askUserLatestPath(), JSON.stringify(request, null, 2), 'utf8');\n const summary = qs.map((q: any, i: number) => `${i + 1}. ${q?.question || 'question'}`).join('\\n');\n return {\n success: true,\n output: `User input required (non-interactive runtime).\\nSaved request: ${this.relativeCrewPath(this.askUserLatestPath())}\\nQuestions:\\n${summary}`\n };\n }\n\n private async enterPlanModeTool(params: { reason?: string }): Promise<ToolResult> {\n const crewDir = this.crewDirPath();\n await mkdir(crewDir, { recursive: true });\n const state = {\n active: true,\n enteredAt: new Date().toISOString(),\n exitedAt: null,\n reason: String(params?.reason || '').trim() || null,\n planPath: null\n };\n await writeFile(this.planModeStatePath(), JSON.stringify(state, null, 2), 'utf8');\n return {\n success: true,\n output: `Plan mode entered${state.reason ? `: ${state.reason}` : ''} (${this.relativeCrewPath(this.planModeStatePath())})`\n };\n }\n\n private async exitPlanModeTool(params: { plan_path?: string }): Promise<ToolResult> {\n const crewDir = this.crewDirPath();\n await mkdir(crewDir, { recursive: true });\n let prior: any = {};\n try {\n prior = JSON.parse(await readFile(this.planModeStatePath(), 'utf8'));\n } catch {\n prior = {};\n }\n const state = {\n ...prior,\n active: false,\n exitedAt: new Date().toISOString(),\n planPath: String(params?.plan_path || '').trim() || prior?.planPath || null\n };\n await writeFile(this.planModeStatePath(), JSON.stringify(state, null, 2), 'utf8');\n return {\n success: true,\n output: `Plan mode exited${state.planPath ? `: ${state.planPath}` : ''} (${this.relativeCrewPath(this.planModeStatePath())})`\n };\n }\n\n private async activateSkillTool(params: { name?: string }): Promise<ToolResult> {\n const name = String(params?.name || '').trim();\n if (!name) return { success: false, error: 'activate_skill requires name' };\n const crewDir = this.crewDirPath();\n await mkdir(crewDir, { recursive: true });\n let state: any = { active: [] };\n try {\n state = JSON.parse(await readFile(this.activeSkillsPath(), 'utf8'));\n } catch {\n state = { active: [] };\n }\n const active = new Set(Array.isArray(state?.active) ? state.active : []);\n active.add(name);\n const next = {\n active: Array.from(active).sort(),\n updatedAt: new Date().toISOString()\n };\n await writeFile(this.activeSkillsPath(), JSON.stringify(next, null, 2), 'utf8');\n return { success: true, output: `Skill activated: ${name} (${this.relativeCrewPath(this.activeSkillsPath())})` };\n }\n\n private crewDirPath() {\n return resolve(this.config.getWorkspaceRoot(), '.crew');\n }\n\n private askUserRequestsPath() {\n return resolve(this.crewDirPath(), 'ask-user-requests.jsonl');\n }\n\n private askUserLatestPath() {\n return resolve(this.crewDirPath(), 'ask-user-latest.json');\n }\n\n private planModeStatePath() {\n return resolve(this.crewDirPath(), 'plan-mode.json');\n }\n\n private activeSkillsPath() {\n return resolve(this.crewDirPath(), 'active-skills.json');\n }\n\n private relativeCrewPath(absPath: string) {\n return absPath.replace(this.config.getWorkspaceRoot(), '.');\n }\n\n private async appendJsonLine(filePath: string, data: any): Promise<void> {\n let prior = '';\n try {\n prior = await readFile(filePath, 'utf8');\n } catch {\n prior = '';\n }\n const line = `${JSON.stringify(data)}\\n`;\n await writeFile(filePath, `${prior}${line}`, 'utf8');\n }\n\n private trackerFilePath() {\n return resolve(this.config.getWorkspaceRoot(), '.crew', 'tracker.json');\n }\n\n private async readTracker(): Promise<any[]> {\n try {\n const raw = await readFile(this.trackerFilePath(), 'utf8');\n const parsed = JSON.parse(raw);\n return Array.isArray(parsed) ? parsed : [];\n } catch {\n return [];\n }\n }\n\n private async writeTracker(tasks: any[]): Promise<void> {\n const dir = resolve(this.config.getWorkspaceRoot(), '.crew');\n await mkdir(dir, { recursive: true });\n await writeFile(this.trackerFilePath(), JSON.stringify(tasks, null, 2), 'utf8');\n }\n\n private mkTrackerId() {\n return Math.random().toString(16).slice(2, 8);\n }\n\n private async trackerCreateTaskTool(params: any): Promise<ToolResult> {\n const tasks = await this.readTracker();\n const task = {\n id: this.mkTrackerId(),\n title: String(params?.title || 'Untitled'),\n description: String(params?.description || ''),\n type: String(params?.type || 'task'),\n status: 'open',\n parentId: params?.parentId || null,\n dependencies: Array.isArray(params?.dependencies) ? params.dependencies : []\n };\n tasks.push(task);\n await this.writeTracker(tasks);\n return { success: true, output: JSON.stringify(task, null, 2) };\n }\n\n private async trackerUpdateTaskTool(params: any): Promise<ToolResult> {\n const tasks = await this.readTracker();\n const id = String(params?.id || '');\n const idx = tasks.findIndex((t: any) => t.id === id);\n if (idx < 0) return { success: false, error: `Task not found: ${id}` };\n tasks[idx] = { ...tasks[idx], ...params };\n await this.writeTracker(tasks);\n return { success: true, output: JSON.stringify(tasks[idx], null, 2) };\n }\n\n private async trackerGetTaskTool(params: any): Promise<ToolResult> {\n const tasks = await this.readTracker();\n const id = String(params?.id || '');\n const task = tasks.find((t: any) => t.id === id);\n if (!task) return { success: false, error: `Task not found: ${id}` };\n return { success: true, output: JSON.stringify(task, null, 2) };\n }\n\n private async trackerListTasksTool(params: any): Promise<ToolResult> {\n const tasks = await this.readTracker();\n const filtered = tasks.filter((t: any) => {\n if (params?.status && t.status !== params.status) return false;\n if (params?.type && t.type !== params.type) return false;\n if (params?.parentId && t.parentId !== params.parentId) return false;\n return true;\n });\n return { success: true, output: JSON.stringify(filtered, null, 2) };\n }\n\n private async trackerAddDependencyTool(params: any): Promise<ToolResult> {\n const tasks = await this.readTracker();\n const taskId = String(params?.taskId || '');\n const depId = String(params?.dependencyId || '');\n const idx = tasks.findIndex((t: any) => t.id === taskId);\n if (idx < 0) return { success: false, error: `Task not found: ${taskId}` };\n const deps = new Set(Array.isArray(tasks[idx].dependencies) ? tasks[idx].dependencies : []);\n deps.add(depId);\n tasks[idx].dependencies = Array.from(deps);\n await this.writeTracker(tasks);\n return { success: true, output: JSON.stringify(tasks[idx], null, 2) };\n }\n\n private async trackerVisualizeTool(): Promise<ToolResult> {\n const tasks = await this.readTracker();\n const lines = tasks.map((t: any) => {\n const deps = Array.isArray(t.dependencies) && t.dependencies.length\n ? ` -> [${t.dependencies.join(', ')}]`\n : '';\n return `${t.id} [${t.status}] ${t.title}${deps}`;\n });\n return { success: true, output: lines.join('\\n') || '(no tasks)' };\n }\n\n private async lspTool(params: { query: string }): Promise<ToolResult> {\n const query = String(params.query || '').trim();\n if (!query) return { success: false, error: 'lsp requires query' };\n const lower = query.toLowerCase();\n const lsp = await import('../../lsp/index.js');\n if (lower.startsWith('symbols')) {\n const file = query.slice('symbols'.length).trim();\n if (!file) return { success: false, error: 'lsp symbols requires file path' };\n const symbols = await lsp.getDocumentSymbols(process.cwd(), file);\n return { success: true, output: symbols.map(s => `${file}:${s.line}:${s.column} ${s.kind} ${s.name}`).join('\\n') };\n }\n if (lower.startsWith('refs')) {\n const target = query.slice('refs'.length).trim();\n const match = target.match(/^(.+):(\\d+)(?::(\\d+))?$/);\n if (match) {\n const refs = await lsp.getReferences(process.cwd(), match[1], Number(match[2]), Number(match[3] || '1'));\n return { success: true, output: refs.map(r => `${r.file}:${r.line}:${r.column}`).join('\\n') };\n }\n if (target) return this.grepTool({ pattern: `\\\\b${target}\\\\b`, path: '.' });\n return { success: false, error: 'lsp refs requires symbol or file:line[:col]' };\n }\n if (lower.startsWith('goto')) {\n const target = query.slice('goto'.length).trim();\n const match = target.match(/^(.+):(\\d+)(?::(\\d+))?$/);\n if (!match) return { success: false, error: 'lsp goto format: file:line[:col]' };\n const defs = await lsp.getDefinitions(process.cwd(), match[1], Number(match[2]), Number(match[3] || '1'));\n return { success: true, output: defs.map(d => `${d.file}:${d.line}:${d.column}`).join('\\n') };\n }\n if (lower.startsWith('diagnostics') || lower === 'check') {\n const diags = await lsp.typeCheckProject(process.cwd(), []);\n return { success: true, output: diags.map(d => `${d.file}:${d.line}:${d.column} [${d.category}] ${d.message}`).join('\\n') };\n }\n if (lower.startsWith('complete')) {\n const target = query.slice('complete'.length).trim();\n const match = target.match(/^(.+):(\\d+):(\\d+)(?:\\s+(.+))?$/);\n if (!match) return { success: false, error: 'lsp complete format: file:line:col [prefix]' };\n const items = await lsp.getCompletions(process.cwd(), match[1], Number(match[2]), Number(match[3]), 50, match[4] || '');\n return { success: true, output: items.map(i => `${i.name} (${i.kind})`).join('\\n') };\n }\n return { success: false, error: `Unsupported lsp query: ${query}` };\n }\n\n private async checkBackgroundTask(params: { task_id: string }): Promise<ToolResult> {\n const taskId = String(params.task_id || '').trim();\n if (!taskId) return { success: false, error: 'check_background_task requires task_id' };\n const bg = _backgroundProcesses.get(taskId);\n if (!bg) return { success: false, error: `No background task found with ID: ${taskId}` };\n\n // Check if done (non-blocking with race against a resolved promise)\n const done = await Promise.race([\n bg.promise.then(r => ({ done: true as const, result: r })),\n new Promise<{ done: false }>(resolve => setTimeout(() => resolve({ done: false }), 50))\n ]);\n\n if (!done.done) {\n const elapsed = Math.round((Date.now() - bg.startedAt) / 1000);\n return { success: true, output: `Task ${taskId} still running (${elapsed}s elapsed). Check again later.` };\n }\n\n _backgroundProcesses.delete(taskId);\n return done.result;\n }\n\n // Track sub-agent depth to prevent infinite recursion\n private static _spawnDepth = 0;\n private static readonly MAX_SPAWN_DEPTH = 3;\n\n private async spawnAgentTool(params: { task: string; model?: string; max_turns?: number }): Promise<ToolResult> {\n const task = String(params.task || '').trim();\n if (!task) return { success: false, error: 'spawn_agent requires task' };\n\n if (GeminiToolAdapter._spawnDepth >= GeminiToolAdapter.MAX_SPAWN_DEPTH) {\n return { success: false, error: `Sub-agent depth limit reached (max ${GeminiToolAdapter.MAX_SPAWN_DEPTH}). Complete this task directly instead.` };\n }\n\n const maxTurns = Math.min(params.max_turns || 15, 25);\n const model = params.model || process.env.CREW_WORKER_MODEL || process.env.CREW_EXECUTION_MODEL || '';\n const branchName = `sub-agent-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;\n\n try {\n // Create isolated sandbox branch for sub-agent\n await this.sandbox.createBranch(branchName);\n\n GeminiToolAdapter._spawnDepth++;\n\n const { runAgenticWorker } = await import('../../executor/agentic-executor.js');\n const result = await runAgenticWorker(task, this.sandbox, {\n model,\n maxTurns,\n stream: false, // Sub-agents don't stream to stdout\n verbose: Boolean(process.env.CREW_DEBUG),\n tier: 'fast' // Default to cheap model for sub-agents\n });\n\n GeminiToolAdapter._spawnDepth--;\n\n // Merge sub-agent changes back to parent branch\n const parentBranch = this.sandbox.getActiveBranch();\n if (parentBranch !== branchName) {\n // Already switched back by the sub-agent's sandbox ops \u2014 merge explicitly\n await this.sandbox.mergeBranch(branchName, parentBranch);\n } else {\n // Switch back to parent and merge\n const branches = this.sandbox.getBranches();\n const parent = branches.find(b => b !== branchName) || 'main';\n await this.sandbox.switchBranch(parent);\n await this.sandbox.mergeBranch(branchName, parent);\n }\n\n // Clean up the branch\n try { await this.sandbox.deleteBranch(branchName); } catch { /* ignore */ }\n\n const output = [\n `Sub-agent completed in ${result.turns || 0} turns (${result.modelUsed || 'unknown'})`,\n result.cost ? `Cost: $${result.cost.toFixed(4)}` : '',\n `Status: ${result.success ? 'SUCCESS' : 'FAILED'}`,\n '',\n result.output?.slice(0, 3000) || '(no output)'\n ].filter(Boolean).join('\\n');\n\n return { success: result.success, output };\n } catch (err: any) {\n GeminiToolAdapter._spawnDepth = Math.max(0, GeminiToolAdapter._spawnDepth - 1);\n // Try to clean up branch\n try { await this.sandbox.switchBranch('main'); } catch { /* ignore */ }\n try { await this.sandbox.deleteBranch(branchName); } catch { /* ignore */ }\n return { success: false, error: `Sub-agent failed: ${err.message}` };\n }\n }\n\n /**\n * Get tool declarations for LLM function calling\n */\n getToolDeclarations() {\n const dynamicEnabled = process.env.CREW_GEMINI_DYNAMIC_DECLARATIONS !== 'false';\n if (dynamicEnabled) {\n try {\n const decls = this.buildDynamicDeclarations();\n if (decls.length > 0) return decls;\n } catch {\n // Fallback to static declarations below.\n }\n }\n return [\n {\n name: 'read_file',\n description: 'Read the contents of a file. ALWAYS read files before editing them. Use start_line/end_line for large files.',\n parameters: {\n type: 'object',\n properties: {\n file_path: { type: 'string', description: 'Relative path from project root' },\n start_line: { type: 'number', description: 'Start line number (1-based, optional)' },\n end_line: { type: 'number', description: 'End line number (inclusive, optional)' }\n },\n required: ['file_path']\n }\n },\n {\n name: 'glob',\n description: 'Find files matching a glob pattern. Use this to discover file structure. Examples: \"**/*.ts\", \"src/**/*.tsx\", \"*.json\"',\n parameters: {\n type: 'object',\n properties: {\n pattern: { type: 'string', description: 'Glob pattern (e.g. \"src/**/*.ts\")' }\n },\n required: ['pattern']\n }\n },\n {\n name: 'grep',\n description: 'Search for text/regex patterns in files. Returns matching lines with file paths and line numbers.',\n parameters: {\n type: 'object',\n properties: {\n pattern: { type: 'string', description: 'Regex or text pattern to search for' },\n path: { type: 'string', description: 'Directory or file to search in (default: \".\")' }\n },\n required: ['pattern']\n }\n },\n {\n name: 'grep_search',\n description: 'Canonical alias for grep. Search for regex/text in files.',\n parameters: {\n type: 'object',\n properties: {\n pattern: { type: 'string', description: 'Regex/text pattern' },\n dir_path: { type: 'string', description: 'Path to search (default: .)' }\n },\n required: ['pattern']\n }\n },\n {\n name: 'grep_search_ripgrep',\n description: 'Ripgrep-optimized canonical name. Routed to grep tool in this adapter.',\n parameters: {\n type: 'object',\n properties: {\n pattern: { type: 'string', description: 'Regex/text pattern' },\n dir_path: { type: 'string', description: 'Path to search (default: .)' },\n path: { type: 'string', description: 'Alternative path field' }\n },\n required: ['pattern']\n }\n },\n {\n name: 'write_file',\n description: 'Write content to a file (creates or overwrites). Changes are staged in sandbox. Use for new files or full rewrites.',\n parameters: {\n type: 'object',\n properties: {\n file_path: { type: 'string', description: 'Relative path from project root' },\n content: { type: 'string', description: 'Complete file content' }\n },\n required: ['file_path', 'content']\n }\n },\n {\n name: 'append_file',\n description: 'Append content to an existing file. Creates file if it does not exist. Changes are staged in sandbox.',\n parameters: {\n type: 'object',\n properties: {\n file_path: { type: 'string', description: 'Relative path from project root' },\n content: { type: 'string', description: 'Content to append' }\n },\n required: ['file_path', 'content']\n }\n },\n {\n name: 'edit',\n description: 'Edit a file by replacing an exact string match. ALWAYS read the file first to get the exact string. Use for targeted changes.',\n parameters: {\n type: 'object',\n properties: {\n file_path: { type: 'string', description: 'Relative path from project root' },\n old_string: { type: 'string', description: 'Exact string to find (must match precisely)' },\n new_string: { type: 'string', description: 'Replacement string' }\n },\n required: ['file_path', 'old_string', 'new_string']\n }\n },\n {\n name: 'replace',\n description: 'Canonical alias for edit. Replace exact old_string with new_string.',\n parameters: {\n type: 'object',\n properties: {\n file_path: { type: 'string', description: 'Relative path from project root' },\n old_string: { type: 'string', description: 'Exact string to replace' },\n new_string: { type: 'string', description: 'Replacement string' }\n },\n required: ['file_path', 'old_string', 'new_string']\n }\n },\n {\n name: 'shell',\n description: 'Run a shell command (e.g. npm test, node script.js, cat, ls). Use for build verification, running tests, or commands not covered by other tools.',\n parameters: {\n type: 'object',\n properties: {\n command: { type: 'string', description: 'Shell command to execute' }\n },\n required: ['command']\n }\n },\n {\n name: 'run_cmd',\n description: 'Alias for shell. Run a shell command. Prefer this for compatibility with existing prompts.',\n parameters: {\n type: 'object',\n properties: {\n command: { type: 'string', description: 'Shell command to execute' }\n },\n required: ['command']\n }\n },\n {\n name: 'run_shell_command',\n description: 'Canonical alias for shell/run_cmd.',\n parameters: {\n type: 'object',\n properties: {\n command: { type: 'string', description: 'Shell command to execute' }\n },\n required: ['command']\n }\n },\n {\n name: 'mkdir',\n description: 'Create a directory (staged via .gitkeep in sandbox).',\n parameters: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Directory path to create' },\n dir_path: { type: 'string', description: 'Alternate directory path field' }\n },\n required: []\n }\n },\n {\n name: 'list',\n description: 'List files and directories for a path.',\n parameters: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Path to list (default: .)' },\n dir_path: { type: 'string', description: 'Alternate path field' }\n },\n required: []\n }\n },\n {\n name: 'list_directory',\n description: 'Canonical alias for list.',\n parameters: {\n type: 'object',\n properties: {\n dir_path: { type: 'string', description: 'Directory path to list (default: .)' }\n },\n required: []\n }\n },\n {\n name: 'git',\n description: 'Run git subcommands (status, diff, log, show, branch). Use to understand repo state and recent changes.',\n parameters: {\n type: 'object',\n properties: {\n command: { type: 'string', description: 'Git subcommand (e.g. \"diff HEAD~3\", \"log --oneline -10\")' }\n },\n required: ['command']\n }\n },\n {\n name: 'lsp',\n description: 'Code intelligence: \"symbols <file>\" for outline, \"refs <file:line:col>\" for references, \"goto <file:line:col>\" for definition, \"diagnostics\" for type errors.',\n parameters: {\n type: 'object',\n properties: {\n query: { type: 'string', description: 'LSP query (e.g. \"symbols src/app.ts\", \"goto src/app.ts:42:5\")' }\n },\n required: ['query']\n }\n },\n {\n name: 'web_search',\n description: 'Search the web via Brave Search API (requires BRAVE_API_KEY).',\n parameters: {\n type: 'object',\n properties: {\n query: { type: 'string', description: 'Search query' }\n },\n required: ['query']\n }\n },\n {\n name: 'google_web_search',\n description: 'Canonical alias for web_search.',\n parameters: {\n type: 'object',\n properties: {\n query: { type: 'string', description: 'Search query' }\n },\n required: ['query']\n }\n },\n {\n name: 'web_fetch',\n description: 'Fetch content from a URL and return cleaned text for analysis.',\n parameters: {\n type: 'object',\n properties: {\n url: { type: 'string', description: 'http(s) URL to fetch' }\n },\n required: ['url']\n }\n },\n {\n name: 'read_many_files',\n description: 'Read multiple files by include glob and return concatenated excerpts.',\n parameters: {\n type: 'object',\n properties: {\n include: { type: 'string', description: 'Glob include pattern (default: **/*)' },\n exclude: { type: 'string', description: 'Optional exclude glob' },\n recursive: { type: 'boolean', description: 'Recursive search (optional)' }\n },\n required: []\n }\n },\n {\n name: 'save_memory',\n description: 'Save a memory fact to local project memory log.',\n parameters: {\n type: 'object',\n properties: {\n fact: { type: 'string', description: 'Memory fact to persist' }\n },\n required: ['fact']\n }\n },\n {\n name: 'write_todos',\n description: 'Persist todo items for the current project.',\n parameters: {\n type: 'object',\n properties: {\n todos: { type: 'array', description: 'Todo items array' }\n },\n required: ['todos']\n }\n },\n {\n name: 'get_internal_docs',\n description: 'Read internal docs by relative path (default AGENTS.md).',\n parameters: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Relative doc path' }\n },\n required: []\n }\n },\n {\n name: 'ask_user',\n description: 'Non-interactive placeholder for ask-user; returns summarized questions.',\n parameters: {\n type: 'object',\n properties: {\n questions: { type: 'array', description: 'Question descriptors' }\n },\n required: []\n }\n },\n {\n name: 'enter_plan_mode',\n description: 'Enter plan mode (no-op marker in CLI adapter).',\n parameters: {\n type: 'object',\n properties: {\n reason: { type: 'string', description: 'Plan mode reason' }\n },\n required: []\n }\n },\n {\n name: 'exit_plan_mode',\n description: 'Exit plan mode (no-op marker in CLI adapter).',\n parameters: {\n type: 'object',\n properties: {\n plan_path: { type: 'string', description: 'Optional plan file path' }\n },\n required: []\n }\n },\n {\n name: 'activate_skill',\n description: 'Activate a named skill (adapter acknowledgment).',\n parameters: {\n type: 'object',\n properties: {\n name: { type: 'string', description: 'Skill name' }\n },\n required: ['name']\n }\n },\n {\n name: 'tracker_create_task',\n description: 'Create tracker task in local .crew/tracker.json.',\n parameters: {\n type: 'object',\n properties: {\n title: { type: 'string' },\n description: { type: 'string' },\n type: { type: 'string' },\n parentId: { type: 'string' },\n dependencies: { type: 'array' }\n },\n required: ['title', 'description', 'type']\n }\n },\n {\n name: 'tracker_update_task',\n description: 'Update tracker task by id.',\n parameters: {\n type: 'object',\n properties: {\n id: { type: 'string' },\n title: { type: 'string' },\n description: { type: 'string' },\n status: { type: 'string' },\n dependencies: { type: 'array' }\n },\n required: ['id']\n }\n },\n {\n name: 'tracker_get_task',\n description: 'Get tracker task by id.',\n parameters: {\n type: 'object',\n properties: {\n id: { type: 'string' }\n },\n required: ['id']\n }\n },\n {\n name: 'tracker_list_tasks',\n description: 'List tracker tasks with optional filters.',\n parameters: {\n type: 'object',\n properties: {\n status: { type: 'string' },\n type: { type: 'string' },\n parentId: { type: 'string' }\n },\n required: []\n }\n },\n {\n name: 'tracker_add_dependency',\n description: 'Add dependency between tracker tasks.',\n parameters: {\n type: 'object',\n properties: {\n taskId: { type: 'string' },\n dependencyId: { type: 'string' }\n },\n required: ['taskId', 'dependencyId']\n }\n },\n {\n name: 'tracker_visualize',\n description: 'Visualize tracker tasks as ASCII list.',\n parameters: {\n type: 'object',\n properties: {},\n required: []\n }\n }\n ];\n }\n}\n", "import { access, copyFile, mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { constants } from 'node:fs';\nimport { join } from 'node:path';\n\nexport interface CorrectionEntry {\n timestamp: string;\n prompt: string;\n original: string;\n corrected: string;\n agent?: string;\n tags?: string[];\n}\n\nfunction nowIso(): string {\n return new Date().toISOString();\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nexport class CorrectionStore {\n baseDir: string;\n stateDir: string;\n dataPath: string;\n\n constructor(baseDir = process.cwd()) {\n this.baseDir = baseDir;\n this.stateDir = join(baseDir, '.crew');\n this.dataPath = join(this.stateDir, 'training-data.jsonl');\n }\n\n async ensureReady(): Promise<void> {\n if (!(await pathExists(this.stateDir))) {\n await mkdir(this.stateDir, { recursive: true });\n }\n\n if (!(await pathExists(this.dataPath))) {\n await writeFile(this.dataPath, '', 'utf8');\n }\n }\n\n async record(entry: Omit<CorrectionEntry, 'timestamp'>): Promise<CorrectionEntry> {\n await this.ensureReady();\n\n const payload: CorrectionEntry = {\n timestamp: nowIso(),\n ...entry\n };\n\n await writeFile(this.dataPath, `${JSON.stringify(payload)}\\n`, {\n encoding: 'utf8',\n flag: 'a'\n });\n\n return payload;\n }\n\n async loadAll(): Promise<CorrectionEntry[]> {\n await this.ensureReady();\n const raw = await readFile(this.dataPath, 'utf8');\n const lines = raw.split('\\n').map(line => line.trim()).filter(Boolean);\n return lines.map(line => JSON.parse(line) as CorrectionEntry);\n }\n\n async summary(): Promise<{ count: number; latest?: CorrectionEntry }> {\n const all = await this.loadAll();\n return {\n count: all.length,\n latest: all.length > 0 ? all[all.length - 1] : undefined\n };\n }\n\n async exportTo(path: string): Promise<void> {\n await this.ensureReady();\n await copyFile(this.dataPath, path);\n }\n}\n", "/**\n * Collections Search \u2014 lightweight local RAG over docs and markdown files.\n *\n * Indexes markdown / text files under configurable paths, builds a simple\n * TF-IDF\u2013style term index, and returns ranked chunks with source attribution.\n */\n\nimport { readdir, readFile, stat } from 'node:fs/promises';\nimport { extname, join, relative, resolve } from 'node:path';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface CollectionChunk {\n /** Relative path from the collection root */\n source: string;\n /** 1-based line number where the chunk starts */\n startLine: number;\n /** The raw text of the chunk */\n text: string;\n /** Relevance score (higher = more relevant) */\n score: number;\n}\n\nexport interface CollectionIndex {\n root: string;\n fileCount: number;\n chunkCount: number;\n /** term \u2192 Set of chunk indices */\n terms: Map<string, Set<number>>;\n chunks: CollectionChunk[];\n}\n\nexport interface BuildCollectionOptions {\n includeCode?: boolean;\n}\n\nexport interface SearchResult {\n query: string;\n hits: CollectionChunk[];\n totalChunks: number;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst DOC_EXTENSIONS = new Set(['.md', '.mdx', '.txt', '.rst', '.adoc']);\nconst CODE_EXTENSIONS = new Set([\n '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.json',\n '.py', '.go', '.rs', '.java', '.kt', '.swift',\n '.sh', '.bash', '.zsh', '.yaml', '.yml', '.toml'\n]);\n\nconst IGNORED_DIRS = new Set([\n 'node_modules', '.git', 'dist', 'build', '.crew',\n '.next', '.turbo', 'coverage', '__pycache__'\n]);\n\nfunction tokenize(text: string): string[] {\n return text\n .toLowerCase()\n .replace(/[^a-z0-9\\s_-]/g, ' ')\n .split(/\\s+/)\n .filter(t => t.length > 1);\n}\n\nfunction hashToken(token: string, dim: number): number {\n let h = 2166136261;\n for (let i = 0; i < token.length; i++) {\n h ^= token.charCodeAt(i);\n h = Math.imul(h, 16777619);\n }\n return Math.abs(h) % dim;\n}\n\nfunction toHashedVector(text: string, dim = 256): Float64Array {\n const vec = new Float64Array(dim);\n const toks = tokenize(text);\n for (const t of toks) {\n vec[hashToken(t, dim)] += 1;\n }\n // l2 normalize\n let norm = 0;\n for (let i = 0; i < dim; i++) norm += vec[i] * vec[i];\n norm = Math.sqrt(norm);\n if (norm > 0) {\n for (let i = 0; i < dim; i++) vec[i] /= norm;\n }\n return vec;\n}\n\nfunction cosineSimilarity(a: Float64Array, b: Float64Array): number {\n const dim = Math.min(a.length, b.length);\n let dot = 0;\n for (let i = 0; i < dim; i++) {\n dot += a[i] * b[i];\n }\n return dot;\n}\n\n/**\n * Split a file into chunks \u2014 one chunk per heading section, or fixed-size\n * paragraphs for files without headings.\n */\nfunction chunkFile(content: string, source: string): CollectionChunk[] {\n const lines = content.split('\\n');\n const chunks: CollectionChunk[] = [];\n let currentLines: string[] = [];\n let currentStart = 1;\n\n const flush = () => {\n const text = currentLines.join('\\n').trim();\n if (text.length > 0) {\n chunks.push({ source, startLine: currentStart, text, score: 0 });\n }\n currentLines = [];\n };\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n // Split on markdown headings\n if (/^#{1,4}\\s/.test(line) && currentLines.length > 0) {\n flush();\n currentStart = i + 1;\n }\n currentLines.push(line);\n\n // Also split on large paragraphs (every ~40 lines if no heading)\n if (currentLines.length >= 40 && !/^#{1,4}\\s/.test(line)) {\n flush();\n currentStart = i + 2;\n }\n }\n flush();\n return chunks;\n}\n\n// ---------------------------------------------------------------------------\n// Walk & Index\n// ---------------------------------------------------------------------------\n\nasync function walkDocs(rootDir: string, includeCode = false): Promise<string[]> {\n const files: string[] = [];\n\n async function walk(dir: string) {\n let entries: string[];\n try {\n entries = await readdir(dir);\n } catch {\n return;\n }\n for (const entry of entries) {\n if (IGNORED_DIRS.has(entry)) continue;\n const fullPath = join(dir, entry);\n let st;\n try {\n st = await stat(fullPath);\n } catch {\n continue;\n }\n if (st.isDirectory()) {\n await walk(fullPath);\n } else {\n const ext = extname(entry).toLowerCase();\n if (DOC_EXTENSIONS.has(ext) || (includeCode && CODE_EXTENSIONS.has(ext))) {\n files.push(fullPath);\n }\n }\n }\n }\n\n await walk(rootDir);\n return files;\n}\n\nexport async function buildCollectionIndex(\n paths: string[],\n options: BuildCollectionOptions = {}\n): Promise<CollectionIndex> {\n const allChunks: CollectionChunk[] = [];\n const roots = paths.map(p => resolve(p));\n let fileCount = 0;\n\n for (const rootPath of roots) {\n let st;\n try {\n st = await stat(rootPath);\n } catch {\n continue;\n }\n\n const files = st.isDirectory() ? await walkDocs(rootPath, Boolean(options.includeCode)) : [rootPath];\n\n for (const file of files) {\n let content: string;\n try {\n content = await readFile(file, 'utf8');\n } catch {\n continue;\n }\n fileCount++;\n const rel = relative(resolve(rootPath, st.isDirectory() ? '.' : '..'), file);\n const chunks = chunkFile(content, rel);\n allChunks.push(...chunks);\n }\n }\n\n // Build inverted term index\n const terms = new Map<string, Set<number>>();\n for (let i = 0; i < allChunks.length; i++) {\n const tokens = tokenize(allChunks[i].text);\n for (const token of tokens) {\n if (!terms.has(token)) terms.set(token, new Set());\n terms.get(token)!.add(i);\n }\n }\n\n return {\n root: roots[0] || '.',\n fileCount,\n chunkCount: allChunks.length,\n terms,\n chunks: allChunks\n };\n}\n\n// ---------------------------------------------------------------------------\n// Search\n// ---------------------------------------------------------------------------\n\nexport function searchCollection(\n index: CollectionIndex,\n query: string,\n maxResults = 10\n): SearchResult {\n const queryTokens = tokenize(query);\n if (queryTokens.length === 0) {\n return { query, hits: [], totalChunks: index.chunkCount };\n }\n\n // Score each chunk by number of matching query terms + term rarity (IDF-like)\n const scores = new Float64Array(index.chunkCount);\n\n for (const token of queryTokens) {\n const matchingChunks = index.terms.get(token);\n if (!matchingChunks) continue;\n // IDF-like weight: rarer terms score higher\n const idf = Math.log(1 + index.chunkCount / matchingChunks.size);\n for (const idx of matchingChunks) {\n scores[idx] += idf;\n }\n }\n\n // Collect non-zero scores\n const candidates: Array<{ idx: number; score: number }> = [];\n for (let i = 0; i < scores.length; i++) {\n if (scores[i] > 0) {\n candidates.push({ idx: i, score: scores[i] });\n }\n }\n\n // Sort descending by score\n candidates.sort((a, b) => b.score - a.score);\n\n const queryVector = toHashedVector(query);\n const maxTfidf = candidates.length > 0 ? candidates[0].score : 1;\n const tfidfWeight = 0.7;\n const vectorWeight = 0.3;\n\n const hybrid = candidates.map(c => {\n const chunk = index.chunks[c.idx];\n const chunkVector = toHashedVector(chunk.text);\n const cosine = Math.max(0, cosineSimilarity(queryVector, chunkVector));\n const tfidfNorm = maxTfidf > 0 ? (c.score / maxTfidf) : 0;\n const hybridScore = (tfidfNorm * tfidfWeight) + (cosine * vectorWeight);\n return { idx: c.idx, score: hybridScore };\n });\n\n hybrid.sort((a, b) => b.score - a.score);\n\n const hits = hybrid.slice(0, maxResults).map(c => ({\n ...index.chunks[c.idx],\n score: Math.round(c.score * 1000) / 1000\n }));\n\n return { query, hits, totalChunks: index.chunkCount };\n}\n", "/**\n * Agentic L3 Executor v2 \u2014 10/10 competitive CLI engine\n *\n * Features:\n * - 34+ tools via GeminiToolAdapter (LSP, git, web, memory, tracker, etc.)\n * - Streaming output \u2014 real-time token display as LLM generates\n * - JIT context discovery \u2014 files discovered by tools are indexed for next turn\n * - Turn compression \u2014 Topic-Action-Summary keeps prompts lean on long sessions\n * - Multi-model routing \u2014 cheap models for simple tasks, heavy for complex\n * - Auto-retry \u2014 failed tool calls retry up to 3 times with correction\n * - Repo-map context \u2014 TF-IDF semantic search injected before execution\n */\n\nimport type { AutonomousResult, TurnResult } from '../worker/autonomous-loop.js';\nimport type { ToolDeclaration } from '../tools/base.js';\nimport type { Sandbox } from '../sandbox/index.js';\nimport { executeAutonomous } from '../worker/autonomous-loop.js';\nimport { GeminiToolAdapter } from '../tools/gemini/crew-adapter.js';\nimport {\n openAICompatibleTurn,\n anthropicTurn,\n type LLMTurnResult\n} from './multi-turn-drivers.js';\nimport { CorrectionStore } from '../learning/corrections.js';\n\n// ---------------------------------------------------------------------------\n// System prompt\n// ---------------------------------------------------------------------------\n\n// Repair common JSON quirks from provider tool call responses\nfunction repairJson(raw: string): string {\n if (!raw || raw.trim() === '') return '{}';\n let s = raw.trim();\n // Remove trailing commas before } or ]\n s = s.replace(/,\\s*([}\\]])/g, '$1');\n // Fix single quotes to double quotes (but not inside strings)\n if (!s.includes('\"') && s.includes(\"'\")) {\n s = s.replace(/'/g, '\"');\n }\n // Fix unquoted keys: { key: \"value\" } \u2192 { \"key\": \"value\" }\n s = s.replace(/([{,])\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*:/g, '$1\"$2\":');\n // Handle truncated JSON from streaming \u2014 close open braces/brackets\n const openBraces = (s.match(/{/g) || []).length;\n const closeBraces = (s.match(/}/g) || []).length;\n for (let i = 0; i < openBraces - closeBraces; i++) s += '}';\n const openBrackets = (s.match(/\\[/g) || []).length;\n const closeBrackets = (s.match(/]/g) || []).length;\n for (let i = 0; i < openBrackets - closeBrackets; i++) s += ']';\n return s;\n}\n\nconst L3_SYSTEM_PROMPT = `You are a senior AI engineer executing coding tasks autonomously.\n\n## Cognitive Loop: THINK \u2192 ACT \u2192 OBSERVE\n\nEvery turn, follow this exact pattern:\n\n**THINK** (internal reasoning, 1-3 sentences):\n- What is the current state? What do I know from previous tool results?\n- What is the minimal next action to make progress?\n- Am I done? If so, summarize and stop.\n\n**ACT** (one or more tool calls):\n- Choose the most targeted tool for the job.\n- Prefer small, verifiable steps over large changes.\n- When multiple independent lookups are needed, call multiple tools in parallel.\n\n**OBSERVE** (after tools return):\n- Did the tool succeed or fail? What does the output tell me?\n- Do I need to adjust my approach?\n\n## Operating Principles\n\n- Match the request. Do what was asked \u2014 nothing more. A bug fix is just a bug fix. Don't refactor adjacent code, add docstrings to unchanged functions, or suggest rewrites beyond the task scope.\n- Simplest approach first. Don't over-engineer. Three similar lines are better than a premature abstraction. Only add error handling, validation, or fallbacks at system boundaries (user input, external APIs), not for internal guarantees.\n- Own mistakes. If a tool call fails or your approach is wrong, say so briefly and try a different approach. Don't repeat the same failing action. If the same failure pattern repeats twice, switch strategy.\n- Be security-conscious. Don't introduce injection, XSS, or hardcoded secrets. Validate at trust boundaries.\n\n## Available Tools\n\n**Files**: read_file, write_file, replace (edit with replace_all flag), read_many_files, glob, grep_search (output_mode: content/files/count, context, type filter), list_directory, mkdir\n**Shell**: run_shell_command (Docker isolation when staged files exist; run_in_background for long commands; configurable timeout via CREW_SHELL_TIMEOUT, default 120s, max 600s), check_background_task\n**Git**: git (status, diff, log, add, commit, show, branch, stash, tag, blame, checkout, fetch, pull, merge, rebase, cherry-pick, worktree \u2014 force-push and --no-verify blocked)\n**Web**: google_web_search, web_fetch\n**Memory**: save_memory (persist facts across sessions), write_todos\n**Docs**: get_internal_docs (read project documentation)\n**Agents**: spawn_agent (spawn autonomous sub-agent for independent subtasks \u2014 isolated sandbox branch, cheap model by default, merges changes on completion)\n\n## File Reading Strategy\n\n1. ALWAYS read a file before editing it. Never guess at file contents.\n2. For large files (500+ lines): read specific line ranges instead of the whole file.\n3. If a read_file result looks truncated, re-read with a narrower range around the area of interest.\n4. Use grep_search to locate exact strings before attempting replace/edit.\n\n## Edit Strategy\n\n1. ALWAYS read_file before editing. Edits on unread files will be rejected.\n2. Use replace (edit) for surgical changes \u2014 provide exact old_string that uniquely matches.\n3. Use replace_all:true when renaming a variable/function across the file.\n4. For new files, use write_file.\n5. Never rewrite an entire existing file \u2014 always use targeted edits.\n6. If an edit fails with \"not unique\", provide more surrounding context or use replace_all:true.\n7. If an edit fails with \"String not found\", re-read the file and retry with current content.\n\n## Shell Strategy\n\n1. For long-running commands (builds, tests, installs), use run_in_background:true.\n2. Use check_background_task to poll for results.\n3. Prefer dedicated tools over shell: use read_file not cat, grep_search not rg, glob not find.\n4. Never use destructive commands (rm -rf, git reset --hard) without explicit task instruction.\n\n## Verification\n\n1. After code changes: run the build command (usually \"npm run build\" or \"tsc --noEmit\").\n2. After logic changes: run relevant tests (\"npm test\", or specific test file).\n3. Check git diff to confirm only intended changes were made.\n\n## Output\n\n- Lead with what you did, not how you thought about it. Skip preamble.\n- For informational queries (listing files, reading code, checking status): include the actual tool output in your response so the user sees the data.\n- For code changes: concise summary of files modified, what changed, verification result.\n- When you used a tool to answer a question, show the results \u2014 don't just say \"I listed the files\" without showing them.\n\n## Stop Conditions \u2014 When to Finish\n\n- The task is fully complete and verified.\n- You have confirmed the changes work (via build, test, or diagnostic check).\n- Do NOT keep reading files or running tools after the work is done.\n- Do NOT repeat yourself or restate your work \u2014 just give a concise summary.\n\n## Anti-Patterns to Avoid\n\n- Do NOT read every file in the project to \"understand context\" \u2014 read only what's needed.\n- Do NOT make speculative changes to files you haven't read.\n- Do NOT run the same command twice if it already succeeded.\n- Do NOT apologize or explain failures at length \u2014 just fix them and move on.\n- Do NOT add features, refactor, or \"improve\" code beyond what the task asks.\n- Do NOT add comments, docstrings, or type annotations to code you didn't change.`;\n\n// ---------------------------------------------------------------------------\n// Corrections injection \u2014 load recent corrections to prevent repeat mistakes\n// ---------------------------------------------------------------------------\n\nasync function loadCorrectionsContext(projectDir: string): Promise<string> {\n try {\n const store = new CorrectionStore(projectDir);\n const entries = await store.loadAll();\n if (entries.length === 0) return '';\n\n // Take last 10 corrections (most recent = most relevant)\n const recent = entries.slice(-10);\n const lines = recent.map(c => {\n const tags = c.tags?.length ? ` [${c.tags.join(', ')}]` : '';\n return `- ${c.prompt.slice(0, 100)}${tags}: ${c.corrected.slice(0, 200)}`;\n });\n\n return `\\n\\n## Past Corrections (avoid repeating these mistakes)\\n${lines.join('\\n')}`;\n } catch {\n return ''; // No corrections file or parse error \u2014 non-fatal\n }\n}\n\n// ---------------------------------------------------------------------------\n// Turn Compression \u2014 Topic-Action-Summary model\n// ---------------------------------------------------------------------------\n\ninterface CompressedTurn {\n turn: number;\n topic: string; // what was being worked on\n action: string; // tool + brief params\n outcome: string; // success/fail + short result\n}\n\nfunction compressTurnHistory(history: TurnResult[]): CompressedTurn[] {\n return history.map(h => {\n const paramStr = JSON.stringify(h.params);\n // Extract the most important param (usually file_path, pattern, or command)\n const keyParam = h.params.file_path || h.params.pattern || h.params.command\n || h.params.query || h.params.path || h.params.dir_path || '';\n const action = `${h.tool}(${String(keyParam).slice(0, 80)})`;\n\n const isError = Boolean(h.error);\n const resultText = isError\n ? h.error!\n : (typeof h.result === 'object' && h.result && 'output' in h.result)\n ? String((h.result as any).output ?? '')\n : String(h.result ?? '');\n\n // Compress outcome to most useful info\n const outcome = isError\n ? `FAIL: ${resultText.slice(0, 120)}`\n : `OK: ${resultText.slice(0, 120)}`;\n\n // Infer topic from tool + params\n const topic = h.params.file_path\n ? String(h.params.file_path).split('/').pop() || 'file'\n : h.tool;\n\n return { turn: h.turn, topic, action, outcome };\n });\n}\n\n/** Format a tool result as a string, truncated for context */\nfunction formatToolResult(h: TurnResult, maxLen = 1500): string {\n const res = h.error\n ? `ERROR: ${h.error}`\n : (typeof h.result === 'object' && h.result && 'output' in h.result)\n ? String((h.result as { output?: string }).output ?? '')\n : String(h.result ?? '');\n return res.slice(0, maxLen);\n}\n\n/**\n * Convert TurnResult[] into provider-specific structured messages.\n * Each TurnResult becomes an assistant tool_call + user tool_result pair.\n * For long histories, middle turns are compressed to text summary while\n * the first 3 (initial context) and last 5 (recent work) use full structured format.\n */\nfunction historyToGeminiContents(history: TurnResult[]): any[] {\n if (history.length === 0) return [];\n const contents: any[] = [];\n\n // Selective compression: keep first 3 + last 5 detailed, compress only middle\n const firstN = 3;\n const lastN = 5;\n const needsCompression = history.length > firstN + lastN;\n const headDetailed = needsCompression ? history.slice(0, firstN) : [];\n const middleTurns = needsCompression ? history.slice(firstN, -lastN) : [];\n const structuredTurns = needsCompression ? history.slice(-lastN) : history;\n\n // Emit head turns (initial context) as full structured messages\n for (const h of headDetailed) {\n contents.push({\n role: 'model',\n parts: [{ functionCall: { name: h.tool, args: h.params } }]\n });\n const resultObj = h.error\n ? { error: h.error }\n : (typeof h.result === 'object' && h.result) ? h.result : { output: formatToolResult(h) };\n contents.push({\n role: 'user',\n parts: [{ functionResponse: { name: h.tool, response: resultObj } }]\n });\n }\n\n // Emit compressed summary of middle turns\n if (middleTurns.length > 0) {\n const compressed = compressTurnHistory(middleTurns);\n const summary = compressed.map(c => `[${c.turn}] ${c.action} \u2192 ${c.outcome}`).join('\\n');\n contents.push(\n { role: 'model', parts: [{ text: `[Earlier execution summary]\\n${summary}` }] },\n { role: 'user', parts: [{ text: 'Acknowledged. Continue with the task.' }] }\n );\n }\n\n for (const h of structuredTurns) {\n // Model made a tool call\n contents.push({\n role: 'model',\n parts: [{ functionCall: { name: h.tool, args: h.params } }]\n });\n // User provided tool result\n const resultObj = h.error\n ? { error: h.error }\n : (typeof h.result === 'object' && h.result) ? h.result : { output: formatToolResult(h) };\n contents.push({\n role: 'user',\n parts: [{ functionResponse: { name: h.tool, response: resultObj } }]\n });\n }\n return contents;\n}\n\nfunction historyToOpenAIMessages(history: TurnResult[]): any[] {\n if (history.length === 0) return [];\n const messages: any[] = [];\n\n // Selective compression: keep first 3 + last 5 detailed, compress only middle\n const firstN = 3;\n const lastN = 5;\n const needsCompression = history.length > firstN + lastN;\n const headDetailed = needsCompression ? history.slice(0, firstN) : [];\n const middleTurns = needsCompression ? history.slice(firstN, -lastN) : [];\n const structuredTurns = needsCompression ? history.slice(-lastN) : history;\n\n // Emit head turns (initial context) as full structured messages\n for (const h of headDetailed) {\n const callId = `call_${h.turn}_${h.tool}`;\n messages.push({\n role: 'assistant',\n tool_calls: [{\n id: callId,\n type: 'function',\n function: { name: h.tool, arguments: JSON.stringify(h.params) }\n }]\n });\n messages.push({\n role: 'tool',\n tool_call_id: callId,\n content: formatToolResult(h)\n });\n }\n\n // Emit compressed summary of middle turns\n if (middleTurns.length > 0) {\n const compressed = compressTurnHistory(middleTurns);\n const summary = compressed.map(c => `[${c.turn}] ${c.action} \u2192 ${c.outcome}`).join('\\n');\n messages.push(\n { role: 'assistant', content: `[Earlier execution summary]\\n${summary}` },\n { role: 'user', content: 'Acknowledged. Continue with the task.' }\n );\n }\n\n for (const h of structuredTurns) {\n const callId = `call_${h.turn}_${h.tool}`;\n messages.push({\n role: 'assistant',\n tool_calls: [{\n id: callId,\n type: 'function',\n function: { name: h.tool, arguments: JSON.stringify(h.params) }\n }]\n });\n messages.push({\n role: 'tool',\n tool_call_id: callId,\n content: formatToolResult(h)\n });\n }\n return messages;\n}\n\nfunction historyToAnthropicMessages(history: TurnResult[]): any[] {\n if (history.length === 0) return [];\n const messages: any[] = [];\n\n // Selective compression: keep first 3 + last 5 detailed, compress only middle\n const firstN = 3;\n const lastN = 5;\n const needsCompression = history.length > firstN + lastN;\n const headDetailed = needsCompression ? history.slice(0, firstN) : [];\n const middleTurns = needsCompression ? history.slice(firstN, -lastN) : [];\n const structuredTurns = needsCompression ? history.slice(-lastN) : history;\n\n // Emit head turns (initial context) as full structured messages\n for (const h of headDetailed) {\n const useId = `tu_${h.turn}_${h.tool}`;\n messages.push({\n role: 'assistant',\n content: [{\n type: 'tool_use',\n id: useId,\n name: h.tool,\n input: h.params\n }]\n });\n messages.push({\n role: 'user',\n content: [{\n type: 'tool_result',\n tool_use_id: useId,\n content: formatToolResult(h)\n }]\n });\n }\n\n // Emit compressed summary of middle turns\n if (middleTurns.length > 0) {\n const compressed = compressTurnHistory(middleTurns);\n const summary = compressed.map(c => `[${c.turn}] ${c.action} \u2192 ${c.outcome}`).join('\\n');\n messages.push(\n { role: 'assistant', content: `[Earlier execution summary]\\n${summary}` },\n { role: 'user', content: 'Acknowledged. Continue with the task.' }\n );\n }\n\n for (const h of structuredTurns) {\n const useId = `tu_${h.turn}_${h.tool}`;\n messages.push({\n role: 'assistant',\n content: [{\n type: 'tool_use',\n id: useId,\n name: h.tool,\n input: h.params\n }]\n });\n messages.push({\n role: 'user',\n content: [{\n type: 'tool_result',\n tool_use_id: useId,\n content: formatToolResult(h)\n }]\n });\n }\n return messages;\n}\n\n/** Legacy text-based history for fallback (markers-only providers) */\nfunction historyToContext(history: TurnResult[]): string {\n if (history.length === 0) return '';\n\n // For short histories, use detailed format\n if (history.length <= 5) {\n const lines = history.map(h => {\n return `[Turn ${h.turn}] ${h.tool}(${JSON.stringify(h.params).slice(0, 200)}) \u2192 ${formatToolResult(h, 800)}`;\n });\n return '\\n\\nPrevious tool results:\\n' + lines.join('\\n');\n }\n\n // For longer histories, use compressed Topic-Action-Summary\n const compressed = compressTurnHistory(history);\n const recentDetailed = history.slice(-3); // Keep last 3 turns detailed\n const olderCompressed = compressed.slice(0, -3);\n\n let ctx = '\\n\\nExecution summary (compressed):\\n';\n ctx += olderCompressed.map(c =>\n `[${c.turn}] ${c.action} \u2192 ${c.outcome}`\n ).join('\\n');\n\n ctx += '\\n\\nRecent actions (detailed):\\n';\n ctx += recentDetailed.map(h => {\n return `[Turn ${h.turn}] ${h.tool}(${JSON.stringify(h.params).slice(0, 200)}) \u2192 ${formatToolResult(h, 800)}`;\n }).join('\\n');\n\n return ctx;\n}\n\n// ---------------------------------------------------------------------------\n// Multi-model routing \u2014 more providers, task-based selection\n// ---------------------------------------------------------------------------\n\ninterface ProviderEntry {\n id: string;\n envKey: string;\n model: string;\n driver: 'gemini' | 'openai' | 'anthropic' | 'openrouter';\n apiUrl?: string;\n modelPrefix?: string;\n tier: 'fast' | 'standard' | 'heavy'; // for complexity-based routing\n}\n\nconst PROVIDER_ORDER: ProviderEntry[] = [\n // Heavy tier \u2014 L2 brain (complex multi-file tasks, planning)\n { id: 'openai', envKey: 'OPENAI_API_KEY', model: 'gpt-4.1', driver: 'openai', apiUrl: 'https://api.openai.com/v1/chat/completions', modelPrefix: 'gpt', tier: 'heavy' },\n { id: 'anthropic', envKey: 'ANTHROPIC_API_KEY', model: 'claude-sonnet-4-20250514', driver: 'anthropic', modelPrefix: 'claude', tier: 'heavy' },\n { id: 'grok', envKey: 'XAI_API_KEY', model: 'grok-3-mini-beta', driver: 'openai', apiUrl: 'https://api.x.ai/v1/chat/completions', modelPrefix: 'grok', tier: 'heavy' },\n // Standard tier \u2014 L3 workers (execution, parallel tasks)\n { id: 'gemini', envKey: 'GEMINI_API_KEY', model: 'gemini-2.5-flash', driver: 'gemini', modelPrefix: 'gemini', tier: 'standard' },\n { id: 'gemini', envKey: 'GOOGLE_API_KEY', model: 'gemini-2.5-flash', driver: 'gemini', modelPrefix: 'gemini', tier: 'standard' },\n { id: 'deepseek', envKey: 'DEEPSEEK_API_KEY', model: 'deepseek-chat', driver: 'openai', apiUrl: 'https://api.deepseek.com/v1/chat/completions', modelPrefix: 'deepseek', tier: 'standard' },\n { id: 'kimi', envKey: 'MOONSHOT_API_KEY', model: 'moonshot-v1-128k', driver: 'openai', apiUrl: 'https://api.moonshot.cn/v1/chat/completions', modelPrefix: 'kimi', tier: 'standard' },\n // Fast tier \u2014 L1 routing (classification, cheap)\n { id: 'groq', envKey: 'GROQ_API_KEY', model: 'llama-3.3-70b-versatile', driver: 'openai', apiUrl: 'https://api.groq.com/openai/v1/chat/completions', modelPrefix: 'llama', tier: 'fast' },\n // Fallback \u2014 free tier\n { id: 'openrouter', envKey: 'OPENROUTER_API_KEY', model: 'google/gemini-2.0-flash-exp:free', driver: 'openrouter', apiUrl: 'https://openrouter.ai/api/v1/chat/completions', modelPrefix: 'openrouter', tier: 'standard' },\n // Additional providers (OpenAI-compatible, cheap workers)\n { id: 'together', envKey: 'TOGETHER_API_KEY', model: 'Qwen/Qwen3.5-397B-A17B', driver: 'openai', apiUrl: 'https://api.together.xyz/v1/chat/completions', modelPrefix: 'qwen', tier: 'standard' },\n { id: 'fireworks', envKey: 'FIREWORKS_API_KEY', model: 'accounts/fireworks/models/qwen3.5-397b-a17b', driver: 'openai', apiUrl: 'https://api.fireworks.ai/inference/v1/chat/completions', modelPrefix: 'fireworks', tier: 'standard' },\n];\n\nfunction resolveProvider(modelOverride?: string, preferTier?: string): { key: string; model: string; driver: string; apiUrl?: string; id: string } | null {\n const effectiveModel = (modelOverride || process.env.CREW_EXECUTION_MODEL || '').trim().toLowerCase();\n\n // If a specific model is requested, find the matching provider\n if (effectiveModel) {\n for (const p of PROVIDER_ORDER) {\n const key = process.env[p.envKey];\n if (!key || key.length < 5) continue;\n if (p.envKey === 'GOOGLE_API_KEY' && process.env.GEMINI_API_KEY) continue;\n if (p.modelPrefix && effectiveModel.includes(p.modelPrefix)) {\n return { key, model: modelOverride || process.env.CREW_EXECUTION_MODEL || p.model, driver: p.driver, apiUrl: p.apiUrl, id: p.id };\n }\n }\n }\n\n // Tier-based routing\n const targetTier = preferTier || 'standard';\n // Try preferred tier first, then fall back to any\n const tieredOrder = [\n ...PROVIDER_ORDER.filter(p => p.tier === targetTier),\n ...PROVIDER_ORDER.filter(p => p.tier !== targetTier)\n ];\n\n for (const p of tieredOrder) {\n const key = process.env[p.envKey];\n if (!key || key.length < 5) continue;\n if (p.envKey === 'GOOGLE_API_KEY' && process.env.GEMINI_API_KEY) continue;\n return { key, model: p.model, driver: p.driver, apiUrl: p.apiUrl, id: p.id };\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Streaming LLM turn \u2014 real-time token output\n// ---------------------------------------------------------------------------\n\n/** Image attachment for multimodal input */\nexport interface ImageAttachment {\n data: string; // base64-encoded image data\n mimeType: string; // e.g. 'image/png', 'image/jpeg'\n}\n\nasync function executeStreamingGeminiTurn(\n fullTask: string,\n tools: ToolDeclaration[],\n key: string,\n model: string,\n systemPrompt: string,\n stream: boolean,\n images?: ImageAttachment[],\n historyMessages?: any[]\n): Promise<LLMTurnResult> {\n const functionDeclarations = tools.map(t => ({\n name: t.name,\n description: t.description,\n parameters: t.parameters\n }));\n\n // Build user parts: text + optional images\n const userParts: any[] = [{ text: `${systemPrompt}\\n\\nTask:\\n${fullTask}` }];\n if (images?.length) {\n for (const img of images) {\n userParts.push({ inlineData: { mimeType: img.mimeType, data: img.data } });\n }\n }\n const contents: any[] = [\n { role: 'user', parts: userParts },\n // Insert structured history (tool call/result pairs)\n ...(historyMessages || []),\n // Continuation prompt if we have history\n ...(historyMessages?.length ? [{ role: 'user', parts: [{ text: 'Continue executing the task based on the results above.' }] }] : [])\n ];\n\n const endpoint = stream ? 'streamGenerateContent' : 'generateContent';\n const url = `https://generativelanguage.googleapis.com/v1beta/models/${model}:${endpoint}?key=${encodeURIComponent(key)}${stream ? '&alt=sse' : ''}`;\n\n const res = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n signal: AbortSignal.timeout(120000),\n body: JSON.stringify({\n contents,\n tools: [{ functionDeclarations }],\n generationConfig: { temperature: 0.3, maxOutputTokens: 8192 }\n })\n });\n\n if (!res.ok) {\n const err = await res.text();\n throw new Error(`Gemini API ${res.status}: ${err.slice(0, 300)}`);\n }\n\n if (stream && res.body) {\n // Parse SSE stream\n let fullText = '';\n const toolCalls: Array<{ tool: string; params: Record<string, any> }> = [];\n let totalCost = 0;\n\n const reader = res.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() || '';\n\n for (const line of lines) {\n if (!line.startsWith('data: ')) continue;\n const jsonStr = line.slice(6).trim();\n if (!jsonStr || jsonStr === '[DONE]') continue;\n\n try {\n const chunk = JSON.parse(jsonStr);\n const parts = chunk?.candidates?.[0]?.content?.parts ?? [];\n\n for (const part of parts) {\n if (part.text) {\n process.stdout.write(part.text);\n fullText += part.text;\n }\n if (part.functionCall) {\n toolCalls.push({\n tool: part.functionCall.name || '',\n params: part.functionCall.args || {}\n });\n }\n }\n\n // Accumulate usage\n const usage = chunk?.usageMetadata;\n if (usage) {\n totalCost = (usage.promptTokenCount || 0) * 0.075 / 1_000_000\n + (usage.candidatesTokenCount || 0) * 0.30 / 1_000_000;\n }\n } catch {\n // Skip malformed chunks\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n if (fullText) process.stdout.write('\\n');\n\n if (toolCalls.length > 0) {\n return { toolCalls, response: fullText, cost: totalCost };\n }\n return { response: fullText, status: 'COMPLETE', cost: totalCost };\n }\n\n // Non-streaming fallback\n const data = await res.json() as any;\n const parts = data?.candidates?.[0]?.content?.parts ?? [];\n const usage = data?.usageMetadata ?? {};\n const cost = (usage.promptTokenCount || 0) * 0.075 / 1_000_000 + (usage.candidatesTokenCount || 0) * 0.30 / 1_000_000;\n\n const toolCalls: Array<{ tool: string; params: Record<string, any> }> = [];\n for (const part of parts) {\n if (part.functionCall) {\n toolCalls.push({ tool: part.functionCall.name || '', params: part.functionCall.args || {} });\n }\n }\n\n if (toolCalls.length > 0) return { toolCalls, response: '', cost };\n\n const textPart = parts.find((p: any) => p.text);\n return { response: textPart?.text ?? '', status: 'COMPLETE', cost };\n}\n\nasync function executeStreamingOpenAITurn(\n fullTask: string,\n tools: ToolDeclaration[],\n apiUrl: string,\n apiKey: string,\n model: string,\n systemPrompt: string,\n stream: boolean,\n images?: ImageAttachment[],\n historyMessages?: any[]\n): Promise<LLMTurnResult> {\n // Build user content: text + optional images as content array\n let userContent: any = fullTask;\n if (images?.length) {\n const parts: any[] = [{ type: 'text', text: fullTask }];\n for (const img of images) {\n parts.push({\n type: 'image_url',\n image_url: { url: `data:${img.mimeType};base64,${img.data}` }\n });\n }\n userContent = parts;\n }\n const messages = [\n { role: 'system', content: systemPrompt },\n { role: 'user', content: userContent },\n // Insert structured history (assistant tool_calls + tool results)\n ...(historyMessages || [])\n ];\n\n const openaiTools = tools.map(t => ({\n type: 'function' as const,\n function: { name: t.name, description: t.description, parameters: t.parameters }\n }));\n\n // GPT-5/6 only support temperature=1; other values cause 400\n const temp = (model?.startsWith?.('gpt-5') || model?.startsWith?.('gpt-6')) ? 1 : 0.3;\n const body: any = {\n model,\n messages,\n tools: openaiTools,\n temperature: temp,\n max_tokens: 8192,\n stream\n };\n\n const res = await fetch(apiUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${apiKey}`\n },\n signal: AbortSignal.timeout(120000),\n body: JSON.stringify(body)\n });\n\n if (!res.ok) {\n const err = await res.text();\n throw new Error(`OpenAI API ${res.status}: ${err.slice(0, 300)}`);\n }\n\n if (stream && res.body) {\n let fullText = '';\n const toolCallAccumulator = new Map<number, { name: string; args: string }>();\n\n const reader = res.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() || '';\n\n for (const line of lines) {\n if (!line.startsWith('data: ')) continue;\n const jsonStr = line.slice(6).trim();\n if (!jsonStr || jsonStr === '[DONE]') continue;\n\n try {\n const chunk = JSON.parse(jsonStr);\n const delta = chunk?.choices?.[0]?.delta;\n if (!delta) continue;\n\n // Stream text content\n if (delta.content) {\n process.stdout.write(delta.content);\n fullText += delta.content;\n }\n\n // Accumulate tool calls (streamed in pieces)\n if (delta.tool_calls) {\n for (const tc of delta.tool_calls) {\n const idx = tc.index ?? 0;\n if (!toolCallAccumulator.has(idx)) {\n toolCallAccumulator.set(idx, { name: '', args: '' });\n }\n const acc = toolCallAccumulator.get(idx)!;\n if (tc.function?.name) acc.name += tc.function.name;\n if (tc.function?.arguments) acc.args += tc.function.arguments;\n }\n }\n } catch {\n // Skip malformed chunks\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n if (fullText) process.stdout.write('\\n');\n\n // Parse accumulated tool calls\n const toolCalls: Array<{ tool: string; params: Record<string, any> }> = [];\n for (const [, tc] of toolCallAccumulator) {\n if (tc.name) {\n let params = {};\n try { params = JSON.parse(repairJson(tc.args)); } catch {}\n toolCalls.push({ tool: tc.name, params });\n }\n }\n\n if (toolCalls.length > 0) return { toolCalls, response: fullText, cost: 0 };\n return { response: fullText, status: 'COMPLETE', cost: 0 };\n }\n\n // Non-streaming fallback to multi-turn-drivers\n // (this path shouldn't be hit normally since we always stream)\n const data = await res.json() as any;\n const choice = data?.choices?.[0];\n const msg = choice?.message;\n\n if (msg?.tool_calls?.length > 0) {\n const toolCalls = msg.tool_calls.map((tc: any) => {\n let params = {};\n try { params = JSON.parse(repairJson(tc.function?.arguments || '{}')); } catch {}\n return { tool: tc.function?.name || '', params };\n });\n return { toolCalls, response: msg?.content || '', cost: 0 };\n }\n\n return { response: msg?.content || '', status: 'COMPLETE', cost: 0 };\n}\n\nasync function executeStreamingAnthropicTurn(\n fullTask: string,\n tools: ToolDeclaration[],\n apiKey: string,\n model: string,\n systemPrompt: string,\n stream: boolean,\n images?: ImageAttachment[],\n historyMessages?: any[]\n): Promise<LLMTurnResult> {\n // Build user content: text + optional images\n let userContent: any = fullTask;\n if (images?.length) {\n const parts: any[] = [{ type: 'text', text: fullTask }];\n for (const img of images) {\n parts.push({\n type: 'image',\n source: { type: 'base64', media_type: img.mimeType, data: img.data }\n });\n }\n userContent = parts;\n }\n\n const anthropicTools = tools.map(t => ({\n name: t.name,\n description: t.description,\n input_schema: t.parameters\n }));\n\n const body: any = {\n model,\n max_tokens: 8192,\n system: systemPrompt,\n messages: [\n { role: 'user', content: userContent },\n // Insert structured history (assistant tool_use + user tool_result)\n ...(historyMessages || [])\n ],\n temperature: 0.3,\n tools: anthropicTools,\n stream\n };\n\n const res = await fetch('https://api.anthropic.com/v1/messages', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-api-key': apiKey,\n 'anthropic-version': '2023-06-01'\n },\n signal: AbortSignal.timeout(120000),\n body: JSON.stringify(body)\n });\n\n if (!res.ok) {\n const err = await res.text();\n throw new Error(`Anthropic API ${res.status}: ${err.slice(0, 300)}`);\n }\n\n if (stream && res.body) {\n let fullText = '';\n const toolBlocks = new Map<number, { name: string; inputJson: string }>();\n let totalCost = 0;\n\n const reader = res.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() || '';\n\n for (const line of lines) {\n if (!line.startsWith('data: ')) continue;\n const jsonStr = line.slice(6).trim();\n if (!jsonStr) continue;\n\n try {\n const event = JSON.parse(jsonStr);\n\n if (event.type === 'content_block_start') {\n if (event.content_block?.type === 'tool_use') {\n toolBlocks.set(event.index, {\n name: event.content_block.name || '',\n inputJson: ''\n });\n }\n }\n\n if (event.type === 'content_block_delta') {\n if (event.delta?.type === 'text_delta' && event.delta.text) {\n process.stdout.write(event.delta.text);\n fullText += event.delta.text;\n }\n if (event.delta?.type === 'input_json_delta' && event.delta.partial_json) {\n const block = toolBlocks.get(event.index);\n if (block) block.inputJson += event.delta.partial_json;\n }\n }\n\n if (event.type === 'message_delta' && event.usage) {\n totalCost = (event.usage.input_tokens || 0) * 3 / 1_000_000\n + (event.usage.output_tokens || 0) * 15 / 1_000_000;\n }\n } catch {\n // Skip malformed events\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n if (fullText) process.stdout.write('\\n');\n\n // Parse accumulated tool calls\n const toolCalls: Array<{ tool: string; params: Record<string, any> }> = [];\n for (const [, block] of toolBlocks) {\n if (block.name) {\n let params = {};\n try { params = JSON.parse(repairJson(block.inputJson)); } catch {}\n toolCalls.push({ tool: block.name, params });\n }\n }\n\n if (toolCalls.length > 0) return { toolCalls, response: fullText, cost: totalCost };\n return { response: fullText, status: 'COMPLETE', cost: totalCost };\n }\n\n // Non-streaming fallback\n const data = await res.json() as any;\n const usage = data?.usage || {};\n const cost = (usage.input_tokens || 0) * 3 / 1_000_000 + (usage.output_tokens || 0) * 15 / 1_000_000;\n const content = data?.content || [];\n const toolUseBlocks = content.filter((b: any) => b.type === 'tool_use');\n const textBlocks = content.filter((b: any) => b.type === 'text');\n const textResponse = textBlocks.map((b: any) => b.text).join('\\n');\n\n if (toolUseBlocks.length > 0) {\n const toolCalls = toolUseBlocks.map((b: any) => ({ tool: b.name, params: b.input || {} }));\n return { toolCalls, response: textResponse, cost };\n }\n return { response: textResponse, status: 'COMPLETE', cost };\n}\n\nasync function executeLLMTurn(\n task: string,\n tools: ToolDeclaration[],\n history: TurnResult[],\n model: string,\n systemPrompt: string,\n stream: boolean,\n images?: ImageAttachment[]\n): Promise<LLMTurnResult> {\n const resolved = resolveProvider(model);\n if (!resolved) {\n throw new Error(\n 'No LLM providers available. Set at least one API key:\\n' +\n ' \u2192 GEMINI_API_KEY (free tier \u2014 https://aistudio.google.com/apikey)\\n' +\n ' \u2192 GROQ_API_KEY (free \u2014 https://console.groq.com/keys)\\n' +\n ' \u2192 XAI_API_KEY ($5/mo free credits \u2014 https://console.x.ai)\\n' +\n 'Or any of: OPENAI_API_KEY, ANTHROPIC_API_KEY, DEEPSEEK_API_KEY, OPENROUTER_API_KEY\\n' +\n 'Run \"crew doctor\" to check your setup.'\n );\n }\n\n const { key, model: effectiveModel, driver, apiUrl, id } = resolved;\n\n // Gemini: structured multi-turn with functionCall/functionResponse\n if (driver === 'gemini') {\n const historyMsgs = historyToGeminiContents(history);\n return executeStreamingGeminiTurn(task, tools, key, effectiveModel, systemPrompt, stream, images, historyMsgs);\n }\n\n // Anthropic: structured multi-turn with tool_use/tool_result\n if (driver === 'anthropic') {\n const historyMsgs = historyToAnthropicMessages(history);\n return executeStreamingAnthropicTurn(task, tools, key, effectiveModel, systemPrompt, stream, images, historyMsgs);\n }\n\n // OpenAI-compatible: structured multi-turn with tool_calls/tool messages\n if (driver === 'openai' || driver === 'openrouter') {\n const historyMsgs = historyToOpenAIMessages(history);\n return executeStreamingOpenAITurn(task, tools, apiUrl!, key, effectiveModel, systemPrompt, stream, images, historyMsgs);\n }\n\n throw new Error(`Unsupported driver: ${driver}`);\n}\n\n// ---------------------------------------------------------------------------\n// JIT Context Discovery \u2014 index files as tools discover them\n// ---------------------------------------------------------------------------\n\nclass JITContextTracker {\n private discoveredFiles = new Set<string>();\n private contextCache: string = '';\n\n /** Hydrate from a prior session's discovered files */\n static fromPrior(files: string[]): JITContextTracker {\n const tracker = new JITContextTracker();\n for (const f of files) tracker.discoveredFiles.add(f);\n return tracker;\n }\n\n /** Serialize discovered files for session persistence */\n toFileList(): string[] {\n return Array.from(this.discoveredFiles);\n }\n\n /** Track a file that was read/written/grepped during tool execution */\n trackFile(filePath: string) {\n if (filePath && !this.discoveredFiles.has(filePath)) {\n this.discoveredFiles.add(filePath);\n }\n }\n\n /** Extract file paths from tool calls and results */\n trackFromToolResult(toolName: string, params: Record<string, any>, result: any) {\n // Track files referenced in tool params\n for (const key of ['file_path', 'path', 'dir_path']) {\n if (params[key]) this.trackFile(String(params[key]));\n }\n\n // Track files discovered by glob/grep results\n if ((toolName === 'glob' || toolName === 'grep_search' || toolName === 'grep_search_ripgrep') && result?.output) {\n const lines = String(result.output).split('\\n');\n for (const line of lines) {\n const match = line.match(/^([^\\s:]+\\.[a-zA-Z]+)/);\n if (match) this.trackFile(match[1]);\n }\n }\n\n // Track files from list_directory\n if (toolName === 'list_directory' && result?.output) {\n const lines = String(result.output).split('\\n');\n const dir = params.dir_path || params.path || '.';\n for (const line of lines) {\n const match = line.match(/^[fd]\\s+(.+)/);\n if (match && match[1].includes('.')) {\n this.trackFile(`${dir}/${match[1]}`);\n }\n }\n }\n }\n\n /** Build enriched context from discovered files for next turn */\n async buildJITContext(projectDir: string): Promise<string> {\n if (this.discoveredFiles.size === 0) return '';\n\n try {\n const { buildCollectionIndex, searchCollection } = await import('../collections/index.js');\n\n // Index only the discovered files/directories\n const uniqueDirs = new Set<string>();\n for (const f of this.discoveredFiles) {\n const parts = f.split('/');\n if (parts.length > 1) {\n uniqueDirs.add(parts.slice(0, -1).join('/'));\n }\n }\n\n // If we've discovered specific directories, search them\n const dirsToIndex = Array.from(uniqueDirs).slice(0, 5);\n if (dirsToIndex.length === 0) return '';\n\n const { resolve: resolvePath } = await import('node:path');\n const paths = dirsToIndex.map(d => resolvePath(projectDir, d));\n\n const index = await buildCollectionIndex(paths, { includeCode: true });\n if (index.chunkCount === 0) return '';\n\n // Search for related patterns based on discovered file names\n const query = Array.from(this.discoveredFiles).slice(0, 10).join(' ');\n const results = searchCollection(index, query, 3);\n if (results.hits.length === 0) return '';\n\n const newContext = results.hits.map(h =>\n `--- JIT: ${h.source}:${h.startLine} ---\\n${h.text.slice(0, 400)}`\n ).join('\\n\\n');\n\n this.contextCache = newContext;\n return `\\n\\nJIT-discovered context:\\n${newContext}`;\n } catch {\n return '';\n }\n }\n\n get fileCount() { return this.discoveredFiles.size; }\n}\n\n// ---------------------------------------------------------------------------\n// Repo-map context builder\n// ---------------------------------------------------------------------------\n\nasync function buildRepoMapContext(task: string, projectDir: string): Promise<string> {\n try {\n const { buildCollectionIndex, searchCollection } = await import('../collections/index.js');\n const index = await buildCollectionIndex([projectDir], { includeCode: true });\n if (index.chunkCount === 0) return '';\n\n const results = searchCollection(index, task, 5);\n if (results.hits.length === 0) return '';\n\n const chunks = results.hits.map(h =>\n `--- ${h.source}:${h.startLine} (score: ${h.score}) ---\\n${h.text.slice(0, 600)}`\n );\n return `\\n\\nRelevant codebase context (${index.fileCount} files indexed, ${index.chunkCount} chunks):\\n${chunks.join('\\n\\n')}`;\n } catch {\n return '';\n }\n}\n\n// ---------------------------------------------------------------------------\n// Auto-retry wrapper\n// ---------------------------------------------------------------------------\n\nconst MAX_RETRIES = 3;\n\nasync function executeToolWithRetry(\n adapter: GeminiToolAdapter,\n name: string,\n params: Record<string, any>,\n verbose: boolean\n): Promise<{ output: string; success: boolean; error?: string }> {\n for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {\n const result = await adapter.executeTool(name, params);\n if (result.success) {\n return { output: result.output ?? '', success: true };\n }\n\n // If first attempt failed and we have retries left, try with corrections\n if (attempt < MAX_RETRIES) {\n if (verbose) {\n console.log(` \u27F3 Retry ${attempt}/${MAX_RETRIES - 1} for ${name}: ${(result.error || '').slice(0, 80)}`);\n }\n\n // Auto-correct common errors\n if (result.error?.includes('String not found') && params.old_string) {\n // Edge case fix: re-read the file to get fresh content before retrying\n if (params.file_path) {\n try {\n const freshRead = await adapter.executeTool('read_file', { file_path: params.file_path });\n if (freshRead.success && freshRead.output) {\n // Return the fresh content as error context so the LLM can see it on next turn\n return {\n output: `File content has changed. Current content of ${params.file_path}:\\n${freshRead.output.slice(0, 3000)}`,\n success: false,\n error: `String not found in ${params.file_path}. File was re-read \u2014 content returned above for correction.`\n };\n }\n } catch { /* fall through to trim retry */ }\n }\n // Fallback: try trimming whitespace\n params.old_string = params.old_string.trim();\n } else if (result.error?.includes('No such file') && params.file_path) {\n // For file ops: try without leading ./\n params.file_path = params.file_path.replace(/^\\.\\//, '');\n } else {\n // No auto-correction available, don't retry\n return { output: result.output ?? '', success: false, error: result.error };\n }\n } else {\n return { output: result.output ?? '', success: false, error: result.error };\n }\n }\n\n return { output: '', success: false, error: 'Max retries exceeded' };\n}\n\n// ---------------------------------------------------------------------------\n// Main executor\n// ---------------------------------------------------------------------------\n\nexport interface AgenticExecutorResult {\n success: boolean;\n output: string;\n cost: number;\n turns?: number;\n toolsUsed?: string[];\n providerId?: string;\n modelUsed?: string;\n filesDiscovered?: number;\n discoveredFiles?: string[];\n history?: TurnResult[];\n stopReason?: string;\n}\n\nexport async function runAgenticWorker(\n task: string,\n sandbox: Sandbox,\n options: {\n systemPrompt?: string;\n model?: string;\n maxTurns?: number;\n projectDir?: string;\n verbose?: boolean;\n stream?: boolean;\n tier?: 'fast' | 'standard' | 'heavy';\n images?: ImageAttachment[];\n onToolCall?: (name: string, params: Record<string, any>) => void;\n priorDiscoveredFiles?: string[];\n } = {}\n): Promise<AgenticExecutorResult> {\n const adapter = new GeminiToolAdapter(sandbox);\n const allTools = adapter.getToolDeclarations() as ToolDeclaration[];\n const systemPrompt = options.systemPrompt || L3_SYSTEM_PROMPT;\n const model = options.model || process.env.CREW_EXECUTION_MODEL || '';\n const maxTurns = options.maxTurns ?? 25;\n const projectDir = options.projectDir || (sandbox as any).baseDir || process.cwd();\n const verbose = options.verbose ?? Boolean(process.env.CREW_DEBUG);\n const stream = options.stream ?? !process.env.CREW_NO_STREAM; // Stream by default\n const jit = options.priorDiscoveredFiles?.length\n ? JITContextTracker.fromPrior(options.priorDiscoveredFiles)\n : new JITContextTracker();\n\n // Resolve provider early to report which model/provider is being used\n const resolvedProvider = resolveProvider(model, options.tier);\n\n if (verbose) {\n const prov = resolvedProvider ? `${resolvedProvider.id}/${resolvedProvider.model}` : 'none';\n console.log(`[AgenticExecutor] Provider: ${prov} | Stream: ${stream} | Tools: ${allTools.length}`);\n }\n\n // Inject repo-map context\n let enrichedTask = task;\n try {\n const repoContext = await buildRepoMapContext(task, projectDir);\n if (repoContext) {\n enrichedTask = `${task}${repoContext}`;\n if (verbose) {\n console.log(`[AgenticExecutor] Repo-map: ${repoContext.length} chars injected`);\n }\n }\n } catch {\n // Non-fatal\n }\n\n // Inject past corrections to prevent repeat mistakes\n try {\n const correctionsContext = await loadCorrectionsContext(projectDir);\n if (correctionsContext) {\n enrichedTask = `${enrichedTask}${correctionsContext}`;\n if (verbose) {\n console.log(`[AgenticExecutor] Corrections context injected`);\n }\n }\n } catch {\n // Non-fatal\n }\n\n if (verbose) {\n console.log(`[AgenticExecutor] ${allTools.length} tools: ${allTools.map(t => t.name).join(', ')}`);\n }\n\n let totalCost = 0;\n const toolsUsed = new Set<string>();\n\n const executeTool = async (name: string, params: Record<string, any>) => {\n toolsUsed.add(name);\n\n // Always fire onToolCall callback (for REPL tool progress display)\n options.onToolCall?.(name, params);\n\n if (verbose) {\n const paramStr = JSON.stringify(params).slice(0, 120);\n process.stdout.write(` \uD83D\uDD27 ${name}(${paramStr})...`);\n }\n\n const result = await executeToolWithRetry(adapter, name, params, verbose);\n\n // Auto-pagination: if read_file result looks truncated, hint for narrower read\n if (name === 'read_file' && result.success && result.output) {\n const outputLen = result.output.length;\n if (outputLen > 8000 && (result.output.includes('... (truncated)') || result.output.includes('content truncated'))) {\n result.output += '\\n\\n[NOTE: File output was truncated. Use line_start and line_end parameters to read specific sections.]';\n }\n }\n\n // JIT: track discovered files\n jit.trackFromToolResult(name, params, result);\n\n if (verbose) {\n const status = result.success ? '\u2713' : '\u2717';\n const preview = (result.output || result.error || '').slice(0, 80).replace(/\\n/g, ' ');\n console.log(` ${status} ${preview}`);\n }\n return result;\n };\n\n let turnCount = 0;\n\n const result: AutonomousResult = await executeAutonomous(\n enrichedTask,\n async (prompt, tools, history) => {\n turnCount++;\n\n // JIT: inject discovered context every 3 turns\n let taskWithJIT = enrichedTask;\n if (turnCount > 1 && turnCount % 3 === 0 && jit.fileCount > 0) {\n try {\n const jitContext = await jit.buildJITContext(projectDir);\n if (jitContext) {\n taskWithJIT = `${enrichedTask}${jitContext}`;\n if (verbose) {\n console.log(` [JIT] Injected context from ${jit.fileCount} discovered files`);\n }\n }\n } catch {\n // Non-fatal\n }\n }\n\n // Only inject images on the first turn to avoid context bloat\n const turnImages = turnCount === 1 ? options.images : undefined;\n const turnResult = await executeLLMTurn(taskWithJIT, allTools, history, model, systemPrompt, stream, turnImages);\n totalCost += turnResult.cost || 0;\n return {\n toolCalls: turnResult.toolCalls,\n response: turnResult.response,\n status: turnResult.status\n };\n },\n async (name, params) => {\n return await executeTool(name, params);\n },\n {\n maxTurns,\n tools: allTools,\n onProgress: verbose\n ? (turn, action) => {\n console.log(` [Turn ${turn}] ${action}`);\n }\n : undefined\n }\n );\n\n return {\n success: result.success ?? false,\n output: result.finalResponse ?? result.history?.map(h => String(h.result)).join('\\n') ?? '',\n cost: totalCost,\n turns: result.turns,\n toolsUsed: Array.from(toolsUsed),\n providerId: resolvedProvider?.id,\n modelUsed: resolvedProvider?.model,\n filesDiscovered: jit.fileCount,\n discoveredFiles: jit.toFileList(),\n history: result.history,\n stopReason: result.reason\n };\n}\n", "/**\n * Engine API \u2014 public exports for use by gateway-bridge.\n * This is the entry point that lib/engines/crew-cli.mjs imports.\n * Provides direct function access to the agentic executor without spawning subprocesses.\n */\nexport { runAgenticWorker } from './executor/agentic-executor.js';\nexport { Sandbox } from './sandbox/index.js';\n", "import { createTwoFilesPatch } from 'diff';\nimport { readFile, writeFile, mkdir, access } from 'node:fs/promises';\nimport { constants } from 'node:fs';\nimport { join, dirname } from 'node:path';\n\nexport interface SandboxChange {\n path: string;\n original: string;\n modified: string;\n timestamp: string;\n}\n\nexport interface SandboxState {\n updatedAt: string;\n activeBranch: string;\n branches: Record<string, Record<string, SandboxChange>>;\n}\n\nexport class Sandbox {\n private state: SandboxState = {\n updatedAt: new Date().toISOString(),\n activeBranch: 'main',\n branches: { main: {} }\n };\n protected baseDir: string; // Changed from private to protected\n private stateFilePath: string;\n\n constructor(baseDir = process.cwd()) {\n this.baseDir = baseDir;\n this.stateFilePath = join(baseDir, '.crew', 'sandbox.json');\n }\n\n private async exists(path: string): Promise<boolean> {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n }\n\n async load(): Promise<void> {\n if (await this.exists(this.stateFilePath)) {\n try {\n const data = await readFile(this.stateFilePath, 'utf8');\n const parsed = JSON.parse(data) as SandboxState;\n this.state = {\n ...this.state,\n ...parsed,\n branches: parsed.branches || { main: {} },\n activeBranch: parsed.activeBranch || 'main'\n };\n } catch (err) {\n console.error(`Failed to load sandbox state: ${(err as Error).message}`);\n }\n }\n }\n\n async persist(): Promise<void> {\n this.state.updatedAt = new Date().toISOString();\n const dir = dirname(this.stateFilePath);\n if (!(await this.exists(dir))) {\n await mkdir(dir, { recursive: true });\n }\n await writeFile(this.stateFilePath, JSON.stringify(this.state, null, 2), 'utf8');\n }\n\n /** Alias for persist() to match external API expectations */\n async save(): Promise<void> {\n await this.persist();\n }\n\n async addChange(filePath: string, modifiedContent: string): Promise<void> {\n const fullPath = join(this.baseDir, filePath);\n let original = '';\n\n // Ensure branch exists and is an object (not array)\n if (!this.state.branches[this.state.activeBranch] || Array.isArray(this.state.branches[this.state.activeBranch])) {\n // Fix malformed branch data silently\n this.state.branches[this.state.activeBranch] = {};\n }\n\n const activeChanges = this.state.branches[this.state.activeBranch];\n\n if (activeChanges[filePath]) {\n original = activeChanges[filePath].original;\n } else if (await this.exists(fullPath)) {\n original = await readFile(fullPath, 'utf8');\n }\n\n activeChanges[filePath] = {\n path: filePath,\n original,\n modified: modifiedContent,\n timestamp: new Date().toISOString()\n };\n \n\n await this.persist();\n }\n\n preview(branchName = this.state.activeBranch): string {\n const branch = this.state.branches[branchName];\n if (!branch) return `Branch \"${branchName}\" not found.`;\n\n let diff = '';\n for (const [path, change] of Object.entries(branch)) {\n diff += createTwoFilesPatch(\n `a/${path}`,\n `b/${path}`,\n change.original,\n change.modified,\n undefined,\n undefined,\n { context: 3 }\n );\n }\n return diff || 'No pending changes.';\n }\n\n async apply(branchName = this.state.activeBranch): Promise<void> {\n const branch = this.state.branches[branchName];\n if (!branch) throw new Error(`Branch \"${branchName}\" not found.`);\n\n for (const [path, change] of Object.entries(branch)) {\n const fullPath = join(this.baseDir, path);\n const dir = dirname(fullPath);\n if (!(await this.exists(dir))) {\n await mkdir(dir, { recursive: true });\n }\n await writeFile(fullPath, change.modified, 'utf8');\n }\n await this.rollback(branchName);\n }\n\n async rollback(branchName = this.state.activeBranch): Promise<void> {\n if (this.state.branches[branchName]) {\n this.state.branches[branchName] = {};\n await this.persist();\n }\n }\n\n async createBranch(name: string, fromBranch = this.state.activeBranch): Promise<void> {\n if (this.state.branches[name]) {\n throw new Error(`Branch \"${name}\" already exists.`);\n }\n // Deep copy current changes from fromBranch\n const sourceBranch = this.state.branches[fromBranch] || {};\n this.state.branches[name] = JSON.parse(JSON.stringify(sourceBranch));\n this.state.activeBranch = name;\n await this.persist();\n }\n\n async switchBranch(name: string): Promise<void> {\n if (!this.state.branches[name]) {\n throw new Error(`Branch \"${name}\" does not exist.`);\n }\n this.state.activeBranch = name;\n await this.persist();\n }\n\n async deleteBranch(name: string): Promise<void> {\n if (name === 'main') throw new Error('Cannot delete main branch.');\n if (this.state.activeBranch === name) {\n this.state.activeBranch = 'main';\n }\n delete this.state.branches[name];\n await this.persist();\n }\n\n async mergeBranch(source: string, target = this.state.activeBranch): Promise<void> {\n if (!this.state.branches[source]) throw new Error(`Source branch \"${source}\" not found.`);\n if (!this.state.branches[target]) throw new Error(`Target branch \"${target}\" not found.`);\n\n const sourceChanges = this.state.branches[source];\n const targetChanges = this.state.branches[target];\n\n for (const [path, change] of Object.entries(sourceChanges)) {\n targetChanges[path] = JSON.parse(JSON.stringify(change));\n }\n\n await this.persist();\n }\n\n getActiveBranch(): string {\n return this.state.activeBranch;\n }\n\n getBranches(): string[] {\n return Object.keys(this.state.branches);\n }\n\n getPendingPaths(branchName = this.state.activeBranch): string[] {\n return Object.keys(this.state.branches[branchName] || {});\n }\n\n hasChanges(branchName = this.state.activeBranch): boolean {\n return Object.keys(this.state.branches[branchName] || {}).length > 0;\n }\n\n /**\n * Get staged content for a file path (returns undefined if not staged).\n * Used by tool adapter so agentic workers can read their own staged files.\n */\n getStagedContent(filePath: string, branchName = this.state.activeBranch): string | undefined {\n const branch = this.state.branches[branchName];\n if (!branch) return undefined;\n // Try both the raw path and normalized path\n const change = branch[filePath];\n if (change) return change.modified;\n return undefined;\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;AA0CA,eAAsB,kBACpB,MACA,YACA,aACA,QAC2B;AAC3B,QAAM,WAAW,OAAO,YAAY;AACpC,QAAM,kBAAkB,OAAO,mBAAmB;AAClD,QAAM,UAAwB,CAAC;AAE/B,MAAI,mBAAmB;AACvB,MAAI,aAAa;AAEjB,WAAS,OAAO,GAAG,OAAO,UAAU,QAAQ;AAC1C,WAAO,aAAa,OAAO,GAAG,UAAU;AAGxC,UAAM,WAAW,MAAM,WAAW,MAAM,OAAO,OAAO,OAAO;AAG7D,QAAI,SAAS,WAAW,cAAc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B,WAAO,OAAO,KAAK,KAAK,MAAM,QAAQ;AAAA,EACxC;AAAA,EAEA,gBAAgB,aAAa,KAAK,MAAM,cAAwB;AAC9D,WAAO,OAAO,KAAK,KAAK,MAAM,SAAS,UAAU,KAAK,CAAC,CAAC;AAAA,EAC1D;AAAA,EAEA,WAAW,aAAa,KAAK,MAAM,cAAuB;AACxD,WAAO,OAAO,KAAK,KAAK,MAAM,SAAS,UAAU,KAAK,CAAC,CAAC,EAAE,SAAS;AAAA,EACrE;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,iBAAiB,UAAkB,aAAa,KAAK,MAAM,cAAkC;AAC3F,UAAM,SAAS,KAAK,MAAM,SAAS,UAAU;AAC7C,QAAI,CAAC,OAAQ,QAAO;AAEpB,UAAM,SAAS,OAAO,QAAQ;AAC9B,QAAI,OAAQ,QAAO,OAAO;AAC1B,WAAO;AAAA,EACT;AACF;",
6
- "names": ["execSync", "resolve", "updated", "diagnostics", "DockerSandbox", "runAgenticWorker", "mkdir", "readFile", "writeFile", "join", "path", "readdir", "readFile", "stat", "join", "resolve", "toolCalls", "parts", "usage", "buildCollectionIndex", "searchCollection", "result", "readFile", "writeFile", "mkdir", "access", "constants", "join", "dirname", "path"]
4
+ "sourcesContent": ["/**\n * Autonomous Worker Loop\n * Implements OpenOrca-style THINK \u2192 ACT \u2192 OBSERVE pattern\n * \n * @license\n * Copyright 2026 CrewSwarm\n */\n\nexport interface ToolCall {\n tool: string;\n params: Record<string, any>;\n}\n\nexport interface TurnResult {\n turn: number;\n tool: string;\n params: Record<string, any>;\n result: any;\n error?: string;\n}\n\nexport interface AutonomousResult {\n success: boolean;\n turns: number;\n history: TurnResult[];\n finalResponse?: string;\n reason?: string;\n}\n\nexport interface AutonomousConfig {\n maxTurns?: number;\n repeatThreshold?: number;\n tools: any[];\n onProgress?: (turn: number, action: string) => void;\n}\n\nconst DEFAULT_MAX_TURNS = 25;\nconst DEFAULT_REPEAT_THRESHOLD = 10;\n\n/**\n * Execute task autonomously with up to MAX_TURNS iterations\n */\nexport async function executeAutonomous(\n task: string,\n executeLLM: (prompt: string, tools: any[], history: TurnResult[]) => Promise<{ toolCalls?: ToolCall[]; response: string; status?: string }>,\n executeTool: (tool: string, params: Record<string, any>) => Promise<any>,\n config: AutonomousConfig\n): Promise<AutonomousResult> {\n const maxTurns = config.maxTurns || DEFAULT_MAX_TURNS;\n const repeatThreshold = config.repeatThreshold || DEFAULT_REPEAT_THRESHOLD;\n const history: TurnResult[] = [];\n\n let lastResponseText = '';\n let staleCount = 0;\n\n for (let turn = 0; turn < maxTurns; turn++) {\n config.onProgress?.(turn + 1, 'THINKING');\n\n // THINK: LLM decides next action\n const response = await executeLLM(task, config.tools, history);\n\n // Check if task is complete\n if (response.status === 'COMPLETE' || !response.toolCalls || response.toolCalls.length === 0) {\n return {\n success: true,\n turns: turn + 1,\n history,\n finalResponse: response.response\n };\n }\n\n // Stale response detection: if LLM gives same text 2x in a row, it's done\n if (response.response && response.response.length > 20) {\n if (response.response === lastResponseText) {\n staleCount++;\n if (staleCount >= 2) {\n return {\n success: true,\n turns: turn + 1,\n history,\n finalResponse: response.response,\n reason: 'Detected stale response (same output repeated), treating as complete'\n };\n }\n } else {\n staleCount = 0;\n }\n lastResponseText = response.response;\n }\n\n // ACT: Execute tool calls \u2014 parallel when multiple, sequential when single\n if (response.toolCalls.length === 1) {\n // Single tool call \u2014 run directly\n const call = response.toolCalls[0];\n config.onProgress?.(turn + 1, `EXECUTING: ${call.tool}`);\n try {\n const result = await executeTool(call.tool, call.params);\n history.push({ turn: turn + 1, tool: call.tool, params: call.params, result });\n } catch (error: any) {\n history.push({ turn: turn + 1, tool: call.tool, params: call.params, result: null, error: error.message });\n }\n } else {\n // Multiple tool calls \u2014 run in parallel for speed\n config.onProgress?.(turn + 1, `EXECUTING ${response.toolCalls.length} tools in parallel`);\n const results = await Promise.allSettled(\n response.toolCalls.map(async (call) => {\n config.onProgress?.(turn + 1, `EXECUTING: ${call.tool}`);\n return { call, result: await executeTool(call.tool, call.params) };\n })\n );\n for (let i = 0; i < results.length; i++) {\n const r = results[i];\n const call = response.toolCalls[i];\n if (r.status === 'fulfilled') {\n history.push({ turn: turn + 1, tool: r.value.call.tool, params: r.value.call.params, result: r.value.result });\n } else {\n history.push({ turn: turn + 1, tool: call.tool, params: call.params, result: null, error: r.reason?.message || 'parallel execution failed' });\n }\n }\n }\n\n // Safety check: Detect if stuck in a loop\n if (turn > repeatThreshold && isRepeating(history, 3)) {\n return {\n success: false,\n turns: turn + 1,\n history,\n reason: 'Detected repeated actions, stopping to prevent infinite loop'\n };\n }\n }\n\n return {\n success: false,\n turns: maxTurns,\n history,\n reason: 'Maximum turns exceeded without completing task'\n };\n}\n\n/**\n * Detect if the agent is repeating the same actions\n */\nfunction isRepeating(history: TurnResult[], windowSize: number = 3): boolean {\n if (history.length < windowSize * 2) return false;\n\n const recentActions = history\n .slice(-windowSize)\n .map(h => `${h.tool}:${JSON.stringify(h.params)}`);\n\n const previousActions = history\n .slice(-windowSize * 2, -windowSize)\n .map(h => `${h.tool}:${JSON.stringify(h.params)}`);\n\n return JSON.stringify(recentActions) === JSON.stringify(previousActions);\n}\n\n/**\n * Format autonomous execution result for display\n */\nexport function formatAutonomousResult(result: AutonomousResult): string {\n let output = `\\n\uD83E\uDD16 Autonomous Execution ${result.success ? '\u2713' : '\u2717'}\\n`;\n output += `Turns: ${result.turns}/${result.history.length}\\n\\n`;\n\n for (const turn of result.history) {\n output += `Turn ${turn.turn}: ${turn.tool}\\n`;\n if (turn.error) {\n output += ` \u2717 Error: ${turn.error}\\n`;\n } else {\n const resultStr = typeof turn.result === 'string' \n ? turn.result.slice(0, 100) \n : JSON.stringify(turn.result).slice(0, 100);\n output += ` \u2713 ${resultStr}${resultStr.length >= 100 ? '...' : ''}\\n`;\n }\n }\n\n if (result.finalResponse) {\n output += `\\n\uD83D\uDCDD Final Response:\\n${result.finalResponse}\\n`;\n }\n\n if (result.reason) {\n output += `\\n\u26A0\uFE0F Stopped: ${result.reason}\\n`;\n }\n\n return output;\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Identity registry for all core tools.\n * Sits at the bottom of the dependency tree to prevent circular imports.\n */\n\n// ============================================================================\n// SHARED PARAMETER NAMES (used by multiple tools)\n// ============================================================================\n\nexport const PARAM_FILE_PATH = 'file_path';\nexport const PARAM_DIR_PATH = 'dir_path';\nexport const PARAM_PATTERN = 'pattern';\nexport const PARAM_CASE_SENSITIVE = 'case_sensitive';\nexport const PARAM_RESPECT_GIT_IGNORE = 'respect_git_ignore';\nexport const PARAM_RESPECT_GEMINI_IGNORE = 'respect_gemini_ignore';\nexport const PARAM_FILE_FILTERING_OPTIONS = 'file_filtering_options';\nexport const PARAM_DESCRIPTION = 'description';\n\n// ============================================================================\n// TOOL NAMES & TOOL-SPECIFIC PARAMETER NAMES\n// ============================================================================\n\n// -- glob --\nexport const GLOB_TOOL_NAME = 'glob';\n\n// -- grep_search --\nexport const GREP_TOOL_NAME = 'grep_search';\nexport const GREP_PARAM_INCLUDE_PATTERN = 'include_pattern';\nexport const GREP_PARAM_EXCLUDE_PATTERN = 'exclude_pattern';\nexport const GREP_PARAM_NAMES_ONLY = 'names_only';\nexport const GREP_PARAM_MAX_MATCHES_PER_FILE = 'max_matches_per_file';\nexport const GREP_PARAM_TOTAL_MAX_MATCHES = 'total_max_matches';\n// ripgrep only\nexport const GREP_PARAM_FIXED_STRINGS = 'fixed_strings';\nexport const GREP_PARAM_CONTEXT = 'context';\nexport const GREP_PARAM_AFTER = 'after';\nexport const GREP_PARAM_BEFORE = 'before';\nexport const GREP_PARAM_NO_IGNORE = 'no_ignore';\n\n// -- list_directory --\nexport const LS_TOOL_NAME = 'list_directory';\nexport const LS_PARAM_IGNORE = 'ignore';\n\n// -- read_file --\nexport const READ_FILE_TOOL_NAME = 'read_file';\nexport const READ_FILE_PARAM_START_LINE = 'start_line';\nexport const READ_FILE_PARAM_END_LINE = 'end_line';\n\n// -- run_shell_command --\nexport const SHELL_TOOL_NAME = 'run_shell_command';\nexport const SHELL_PARAM_COMMAND = 'command';\nexport const SHELL_PARAM_IS_BACKGROUND = 'is_background';\n\n// -- write_file --\nexport const WRITE_FILE_TOOL_NAME = 'write_file';\nexport const WRITE_FILE_PARAM_CONTENT = 'content';\n\n// -- replace (edit) --\nexport const EDIT_TOOL_NAME = 'replace';\nexport const EDIT_PARAM_INSTRUCTION = 'instruction';\nexport const EDIT_PARAM_OLD_STRING = 'old_string';\nexport const EDIT_PARAM_NEW_STRING = 'new_string';\nexport const EDIT_PARAM_ALLOW_MULTIPLE = 'allow_multiple';\n\n// -- google_web_search --\nexport const WEB_SEARCH_TOOL_NAME = 'google_web_search';\nexport const WEB_SEARCH_PARAM_QUERY = 'query';\n\n// -- write_todos --\nexport const WRITE_TODOS_TOOL_NAME = 'write_todos';\nexport const TODOS_PARAM_TODOS = 'todos';\nexport const TODOS_ITEM_PARAM_DESCRIPTION = 'description';\nexport const TODOS_ITEM_PARAM_STATUS = 'status';\n\n// -- web_fetch --\nexport const WEB_FETCH_TOOL_NAME = 'web_fetch';\nexport const WEB_FETCH_PARAM_PROMPT = 'prompt';\n\n// -- read_many_files --\nexport const READ_MANY_FILES_TOOL_NAME = 'read_many_files';\nexport const READ_MANY_PARAM_INCLUDE = 'include';\nexport const READ_MANY_PARAM_EXCLUDE = 'exclude';\nexport const READ_MANY_PARAM_RECURSIVE = 'recursive';\nexport const READ_MANY_PARAM_USE_DEFAULT_EXCLUDES = 'useDefaultExcludes';\n\n// -- save_memory --\nexport const MEMORY_TOOL_NAME = 'save_memory';\nexport const MEMORY_PARAM_FACT = 'fact';\n\n// -- get_internal_docs --\nexport const GET_INTERNAL_DOCS_TOOL_NAME = 'get_internal_docs';\nexport const DOCS_PARAM_PATH = 'path';\n\n// -- activate_skill --\nexport const ACTIVATE_SKILL_TOOL_NAME = 'activate_skill';\nexport const SKILL_PARAM_NAME = 'name';\n\n// -- ask_user --\nexport const ASK_USER_TOOL_NAME = 'ask_user';\nexport const ASK_USER_PARAM_QUESTIONS = 'questions';\n// ask_user question item params\nexport const ASK_USER_QUESTION_PARAM_QUESTION = 'question';\nexport const ASK_USER_QUESTION_PARAM_HEADER = 'header';\nexport const ASK_USER_QUESTION_PARAM_TYPE = 'type';\nexport const ASK_USER_QUESTION_PARAM_OPTIONS = 'options';\nexport const ASK_USER_QUESTION_PARAM_MULTI_SELECT = 'multiSelect';\nexport const ASK_USER_QUESTION_PARAM_PLACEHOLDER = 'placeholder';\n// ask_user option item params\nexport const ASK_USER_OPTION_PARAM_LABEL = 'label';\nexport const ASK_USER_OPTION_PARAM_DESCRIPTION = 'description';\n\n// -- exit_plan_mode --\nexport const EXIT_PLAN_MODE_TOOL_NAME = 'exit_plan_mode';\nexport const EXIT_PLAN_PARAM_PLAN_PATH = 'plan_path';\n\n// -- enter_plan_mode --\nexport const ENTER_PLAN_MODE_TOOL_NAME = 'enter_plan_mode';\nexport const PLAN_MODE_PARAM_REASON = 'reason';\n", "import { existsSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\n\n// Lazy-load typescript to avoid blocking ESM module init on Node 24+\n// (Node 24 ESM resolver can't resolve `import ts from 'typescript'` at top level)\nlet _ts: any;\nasync function ensureTs(): Promise<any> {\n if (!_ts) {\n _ts = await import('typescript').then(m => m.default ?? m);\n }\n return _ts;\n}\n\nexport interface LspDiagnostic {\n file: string;\n line: number;\n column: number;\n code: number;\n category: 'error' | 'warning' | 'suggestion' | 'message';\n message: string;\n}\n\nexport interface LspCompletion {\n name: string;\n kind: string;\n sortText?: string;\n}\n\nexport interface LspLocation {\n file: string;\n line: number;\n column: number;\n}\n\nexport interface LspSymbol {\n name: string;\n kind: string;\n line: number;\n column: number;\n}\n\ninterface LoadedProject {\n root: string;\n options: any;\n fileNames: string[];\n}\n\nfunction categoryToText(cat: number): LspDiagnostic['category'] {\n // ts.DiagnosticCategory.Error = 1, Warning = 0, Suggestion = 2, Message = 3\n if (cat === 1) return 'error';\n if (cat === 0) return 'warning';\n if (cat === 2) return 'suggestion';\n return 'message';\n}\n\nfunction loadProject(projectDir: string, ts: any): LoadedProject {\n const root = resolve(projectDir);\n const configPath = ts.findConfigFile(root, ts.sys.fileExists, 'tsconfig.json');\n if (!configPath) {\n throw new Error(`No tsconfig.json found at or above ${root}`);\n }\n\n const configFile = ts.readConfigFile(configPath, ts.sys.readFile);\n if (configFile.error) {\n throw new Error(ts.flattenDiagnosticMessageText(configFile.error.messageText, '\\n'));\n }\n\n const parsed = ts.parseJsonConfigFileContent(\n configFile.config,\n ts.sys,\n dirname(configPath)\n );\n if (parsed.errors.length > 0) {\n const first = parsed.errors[0];\n throw new Error(ts.flattenDiagnosticMessageText(first.messageText, '\\n'));\n }\n\n return {\n root,\n options: parsed.options,\n fileNames: parsed.fileNames\n };\n}\n\nexport async function typeCheckProject(projectDir: string, includeFiles: string[] = []): Promise<LspDiagnostic[]> {\n const ts = await ensureTs();\n const project = loadProject(projectDir, ts);\n const includeAbs = new Set(includeFiles.map(x => resolve(project.root, x)));\n const shouldFilter = includeAbs.size > 0;\n const host = ts.createCompilerHost(project.options, true);\n const program = ts.createProgram(project.fileNames, project.options, host);\n\n const diagnostics = ts.getPreEmitDiagnostics(program);\n const out: LspDiagnostic[] = [];\n for (const diagnostic of diagnostics) {\n const sourceFile = diagnostic.file;\n if (!sourceFile) continue;\n const absFile = resolve(sourceFile.fileName);\n if (shouldFilter && !includeAbs.has(absFile)) continue;\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(diagnostic.start ?? 0);\n out.push({\n file: absFile,\n line: line + 1,\n column: character + 1,\n code: diagnostic.code,\n category: categoryToText(diagnostic.category),\n message: ts.flattenDiagnosticMessageText(diagnostic.messageText, '\\n')\n });\n }\n return out;\n}\n\nfunction kindToText(kind: any): string {\n return String(kind || 'unknown');\n}\n\nfunction createLanguageService(projectDir: string, ts: any) {\n const project = loadProject(projectDir, ts);\n const sourceTexts = new Map<string, { version: number; text: string }>();\n for (const file of project.fileNames) {\n const text = ts.sys.readFile(file) || '';\n sourceTexts.set(resolve(file), { version: 1, text });\n }\n\n const serviceHost = {\n getCompilationSettings: () => project.options,\n getScriptFileNames: () => Array.from(sourceTexts.keys()),\n getScriptVersion: (fileName: string) => String(sourceTexts.get(resolve(fileName))?.version || 1),\n getScriptSnapshot: (fileName: string) => {\n const resolved = resolve(fileName);\n const entry = sourceTexts.get(resolved);\n if (!entry) return undefined;\n return ts.ScriptSnapshot.fromString(entry.text);\n },\n getCurrentDirectory: () => project.root,\n getDefaultLibFileName: (options: any) => ts.getDefaultLibFilePath(options),\n fileExists: ts.sys.fileExists,\n readFile: ts.sys.readFile,\n readDirectory: ts.sys.readDirectory,\n directoryExists: ts.sys.directoryExists,\n getDirectories: ts.sys.getDirectories\n };\n\n const service = ts.createLanguageService(serviceHost);\n return { service, project, sourceTexts };\n}\n\nfunction lineColToPosition(text: string, line: number, column: number): number {\n const lines = text.split('\\n');\n const lineIndex = Math.max(0, line - 1);\n const offset = lines.slice(0, lineIndex).reduce((sum: number, x: string) => sum + x.length + 1, 0) + Math.max(0, column - 1);\n return Math.min(offset, text.length);\n}\n\nexport async function getCompletions(\n projectDir: string,\n filePath: string,\n line: number,\n column: number,\n limit = 50,\n prefix = ''\n): Promise<LspCompletion[]> {\n const ts = await ensureTs();\n const { service, project, sourceTexts } = createLanguageService(projectDir, ts);\n try {\n const absFile = resolve(project.root, filePath);\n if (!existsSync(absFile)) {\n throw new Error(`File not found: ${absFile}`);\n }\n\n if (!sourceTexts.has(absFile)) {\n sourceTexts.set(absFile, { version: 1, text: ts.sys.readFile(absFile) || '' });\n }\n\n const fileText = sourceTexts.get(absFile)?.text || '';\n const lines = fileText.split('\\n');\n const lineIndex = Math.max(0, line - 1);\n const safeLine = lines[lineIndex] || '';\n const offset = lines.slice(0, lineIndex).reduce((sum: number, x: string) => sum + x.length + 1, 0) + Math.max(0, column - 1);\n const position = Math.min(offset, fileText.length);\n\n const completions = service.getCompletionsAtPosition(absFile, position, {\n includeCompletionsWithInsertText: true,\n includeCompletionsForModuleExports: true\n });\n\n const items = (completions?.entries || []).filter((entry: any) => {\n if (!prefix) return true;\n return entry.name.toLowerCase().startsWith(prefix.toLowerCase());\n });\n\n return items.slice(0, Math.max(1, limit)).map((entry: any) => ({\n name: entry.name,\n kind: kindToText(entry.kind),\n sortText: entry.sortText\n }));\n } finally {\n service.dispose();\n }\n}\n\nexport async function getDefinitions(projectDir: string, filePath: string, line: number, column: number): Promise<LspLocation[]> {\n const ts = await ensureTs();\n const { service, project, sourceTexts } = createLanguageService(projectDir, ts);\n try {\n const absFile = resolve(project.root, filePath);\n const fileText = sourceTexts.get(absFile)?.text || ts.sys.readFile(absFile) || '';\n const position = lineColToPosition(fileText, line, column);\n const defs = service.getDefinitionAtPosition(absFile, position) || [];\n return defs.map((def: any) => {\n const sf = service.getProgram()?.getSourceFile(def.fileName);\n const lc = sf?.getLineAndCharacterOfPosition(def.textSpan.start) || { line: 0, character: 0 };\n return {\n file: resolve(def.fileName),\n line: lc.line + 1,\n column: lc.character + 1\n };\n });\n } finally {\n service.dispose();\n }\n}\n\nexport async function getReferences(projectDir: string, filePath: string, line: number, column: number): Promise<LspLocation[]> {\n const ts = await ensureTs();\n const { service, project, sourceTexts } = createLanguageService(projectDir, ts);\n try {\n const absFile = resolve(project.root, filePath);\n const fileText = sourceTexts.get(absFile)?.text || ts.sys.readFile(absFile) || '';\n const position = lineColToPosition(fileText, line, column);\n const refs = service.getReferencesAtPosition(absFile, position) || [];\n return refs.map((ref: any) => {\n const sf = service.getProgram()?.getSourceFile(ref.fileName);\n const lc = sf?.getLineAndCharacterOfPosition(ref.textSpan.start) || { line: 0, character: 0 };\n return {\n file: resolve(ref.fileName),\n line: lc.line + 1,\n column: lc.character + 1\n };\n });\n } finally {\n service.dispose();\n }\n}\n\nexport async function getDocumentSymbols(projectDir: string, filePath: string): Promise<LspSymbol[]> {\n const ts = await ensureTs();\n const { service, project } = createLanguageService(projectDir, ts);\n try {\n const absFile = resolve(project.root, filePath);\n const nav = service.getNavigationTree(absFile);\n const out: LspSymbol[] = [];\n const walk = (node: any) => {\n for (const span of node.spans || []) {\n const sf = service.getProgram()?.getSourceFile(absFile);\n const lc = sf?.getLineAndCharacterOfPosition(span.start) || { line: 0, character: 0 };\n if (node.text && node.text !== '<global>') {\n out.push({\n name: node.text,\n kind: String(node.kind || 'unknown'),\n line: lc.line + 1,\n column: lc.character + 1\n });\n }\n }\n for (const child of node.childItems || []) walk(child);\n };\n walk(nav);\n return out;\n } finally {\n service.dispose();\n }\n}\n", "/**\n * Docker-based sandbox for safe command execution\n * Runs commands in isolated Docker containers with staged files\n */\n\nimport { execSync } from 'child_process';\nimport fs from 'fs';\nimport path from 'path';\nimport { randomUUID } from 'crypto';\n\nexport interface DockerSandboxOptions {\n workDir: string;\n image?: string;\n timeout?: number;\n env?: Record<string, string>;\n}\n\nexport interface DockerSandboxResult {\n success: boolean;\n output: string;\n exitCode: number;\n duration: number;\n}\n\nexport class DockerSandbox {\n private readonly defaultImage = 'node:20-slim';\n private readonly defaultTimeout = 30000; // 30 seconds\n \n /**\n * Check if Docker is available and running\n */\n async isDockerAvailable(): Promise<boolean> {\n try {\n execSync('docker info', { \n stdio: 'ignore',\n timeout: 5000 \n });\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Copy staged files from sandbox to temp directory\n */\n private async prepareTempDir(sandbox: any, tempDir: string): Promise<number> {\n const pendingPaths = sandbox.getPendingPaths();\n const branch = sandbox.state?.branches?.[sandbox.getActiveBranch()];\n \n if (!branch) return 0;\n\n let fileCount = 0;\n for (const filePath of pendingPaths) {\n const fileData = branch[filePath];\n if (!fileData?.modified) continue;\n\n const fullPath = path.join(tempDir, filePath);\n const dir = path.dirname(fullPath);\n \n // Create directory structure\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n // Write staged content\n fs.writeFileSync(fullPath, fileData.modified, 'utf8');\n fileCount++;\n }\n\n return fileCount;\n }\n\n /**\n * Run command in Docker container with staged files\n */\n async runCommand(\n command: string,\n sandbox: any,\n options: Partial<DockerSandboxOptions> = {}\n ): Promise<DockerSandboxResult> {\n const startTime = Date.now();\n const tempDir = path.join('/tmp', `crew-sandbox-${randomUUID()}`);\n const image = options.image || this.defaultImage;\n const timeout = options.timeout || this.defaultTimeout;\n const workDir = options.workDir || process.cwd();\n\n try {\n // Create temp directory\n fs.mkdirSync(tempDir, { recursive: true });\n console.log(`[Docker] Created temp dir: ${tempDir}`);\n\n // Copy staged files to temp dir\n const fileCount = await this.prepareTempDir(sandbox, tempDir);\n console.log(`[Docker] Copied ${fileCount} staged file(s) to sandbox`);\n\n // Copy package.json if it exists (for npm commands)\n const pkgPath = path.join(workDir, 'package.json');\n if (fs.existsSync(pkgPath)) {\n fs.copyFileSync(pkgPath, path.join(tempDir, 'package.json'));\n console.log(`[Docker] Copied package.json`);\n }\n\n // Copy node_modules if npm/node command (for dependencies)\n const needsNodeModules = /\\b(npm|node|npx)\\b/.test(command);\n if (needsNodeModules) {\n const nodeModulesPath = path.join(workDir, 'node_modules');\n if (fs.existsSync(nodeModulesPath)) {\n console.log(`[Docker] Copying node_modules (this may take a few seconds)...`);\n execSync(`cp -r \"${nodeModulesPath}\" \"${tempDir}/\"`, {\n stdio: 'ignore',\n timeout: 10000\n });\n }\n }\n\n // Build environment variables\n const envFlags = options.env \n ? Object.entries(options.env).map(([k, v]) => `-e ${k}=\"${v}\"`).join(' ')\n : '';\n\n // Run command in Docker\n console.log(`[Docker] Running: ${command}`);\n const dockerCmd = `docker run --rm -v \"${tempDir}\":/work -w /work ${envFlags} ${image} sh -c \"${command.replace(/\"/g, '\\\\\"')}\"`;\n \n const output = execSync(dockerCmd, {\n encoding: 'utf8',\n timeout,\n stdio: ['ignore', 'pipe', 'pipe']\n });\n\n const duration = Date.now() - startTime;\n console.log(`[Docker] \u2713 Command completed in ${duration}ms`);\n\n return {\n success: true,\n output,\n exitCode: 0,\n duration\n };\n\n } catch (err: any) {\n const duration = Date.now() - startTime;\n console.log(`[Docker] \u2717 Command failed after ${duration}ms`);\n \n return {\n success: false,\n output: err.stdout || err.stderr || err.message,\n exitCode: err.status || 1,\n duration\n };\n\n } finally {\n // Cleanup temp directory\n try {\n if (fs.existsSync(tempDir)) {\n fs.rmSync(tempDir, { recursive: true, force: true });\n console.log(`[Docker] Cleaned up temp dir`);\n }\n } catch (cleanupErr) {\n console.warn(`[Docker] Failed to cleanup ${tempDir}:`, cleanupErr);\n }\n }\n }\n\n /**\n * Pull Docker image if not present (with progress)\n */\n async ensureImage(image: string = this.defaultImage): Promise<boolean> {\n try {\n // Check if image exists\n execSync(`docker image inspect ${image}`, { \n stdio: 'ignore',\n timeout: 5000 \n });\n return true; // Image already exists\n } catch {\n // Image doesn't exist, pull it\n console.log(`[Docker] Pulling image ${image}...`);\n try {\n execSync(`docker pull ${image}`, {\n stdio: 'inherit', // Show progress\n timeout: 120000 // 2 minutes for image pull\n });\n console.log(`[Docker] \u2713 Image pulled successfully`);\n return true;\n } catch (pullErr) {\n console.error(`[Docker] Failed to pull image:`, pullErr);\n return false;\n }\n }\n }\n}\n", "/**\n * Adapter to use Gemini CLI tools with crew-cli's sandbox\n */\n\nimport { Sandbox } from '../../sandbox/index.js';\nimport { execSync } from 'node:child_process';\nimport { mkdir, readFile, readdir, stat, writeFile } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\nimport {\n GLOB_TOOL_NAME,\n GREP_TOOL_NAME,\n LS_TOOL_NAME,\n READ_FILE_TOOL_NAME,\n SHELL_TOOL_NAME,\n WRITE_FILE_TOOL_NAME,\n EDIT_TOOL_NAME,\n WEB_SEARCH_TOOL_NAME,\n WRITE_TODOS_TOOL_NAME,\n WEB_FETCH_TOOL_NAME,\n READ_MANY_FILES_TOOL_NAME,\n MEMORY_TOOL_NAME,\n GET_INTERNAL_DOCS_TOOL_NAME,\n ACTIVATE_SKILL_TOOL_NAME,\n ASK_USER_TOOL_NAME,\n EXIT_PLAN_MODE_TOOL_NAME,\n ENTER_PLAN_MODE_TOOL_NAME\n} from './definitions/base-declarations.js';\n\n// Minimal adapter types\nexport interface ToolResult {\n success: boolean;\n output?: string;\n error?: string;\n}\n\n// Create config adapter for Gemini tools\nexport class CrewConfig {\n constructor(private workspaceRoot: string) {}\n \n getWorkspaceRoot() {\n return this.workspaceRoot;\n }\n \n getTargetDir() {\n return this.workspaceRoot;\n }\n}\n\n// Create message bus adapter (auto-approve for CLI)\nexport class CrewMessageBus {\n async requestConfirmation(): Promise<{ status: 'approved' }> {\n return { status: 'approved' }; // Auto-approve for CLI\n }\n}\n\n// Shell timeout: configurable via CREW_SHELL_TIMEOUT env (seconds), default 120s, max 600s\nfunction getShellTimeout(): number {\n const envVal = parseInt(process.env.CREW_SHELL_TIMEOUT || '', 10);\n if (envVal > 0) return Math.min(envVal * 1000, 600000); // max 600s\n return 120000; // default 120s\n}\n\n// Dangerous shell commands that should warn (matches Claude Code behavior)\nconst DANGEROUS_SHELL_PATTERNS = [\n /\\brm\\s+-rf?\\s/, // rm -r / rm -rf\n /\\bgit\\s+push\\s+.*--force/, // force push\n /\\bgit\\s+reset\\s+--hard/, // hard reset\n /\\bgit\\s+clean\\s+-f/, // clean untracked\n /\\bdrop\\s+table\\b/i, // SQL drop\n /\\bdrop\\s+database\\b/i, // SQL drop database\n /\\bkill\\s+-9\\b/, // kill -9\n /\\bmkfs\\b/, // format filesystem\n /\\bdd\\s+if=/, // dd (disk destroyer)\n];\n\n// Background shell processes tracked by ID\nconst _backgroundProcesses = new Map<string, { promise: Promise<ToolResult>; startedAt: number }>();\n\n// Main adapter class\nexport class GeminiToolAdapter {\n private config: CrewConfig;\n private messageBus: CrewMessageBus;\n private _filesRead = new Set<string>(); // Track reads for read-before-edit guard\n\n constructor(private sandbox: Sandbox) {\n const workspaceRoot = (sandbox as any).baseDir || process.cwd();\n this.config = new CrewConfig(workspaceRoot);\n this.messageBus = new CrewMessageBus();\n }\n\n private buildDynamicDeclarations(): any[] {\n // Pull canonical names from Gemini base declarations and hydrate schemas from static declarations.\n const staticDecls = this.getStaticToolDeclarations();\n const staticByName = new Map<string, any>(staticDecls.map((d: any) => [d.name, d]));\n const canonicalNames = [\n READ_FILE_TOOL_NAME,\n WRITE_FILE_TOOL_NAME,\n EDIT_TOOL_NAME,\n GLOB_TOOL_NAME,\n GREP_TOOL_NAME,\n LS_TOOL_NAME,\n SHELL_TOOL_NAME,\n WEB_SEARCH_TOOL_NAME,\n WEB_FETCH_TOOL_NAME,\n READ_MANY_FILES_TOOL_NAME,\n MEMORY_TOOL_NAME,\n WRITE_TODOS_TOOL_NAME,\n GET_INTERNAL_DOCS_TOOL_NAME,\n ACTIVATE_SKILL_TOOL_NAME,\n ASK_USER_TOOL_NAME,\n ENTER_PLAN_MODE_TOOL_NAME,\n EXIT_PLAN_MODE_TOOL_NAME,\n 'grep_search_ripgrep',\n 'tracker_create_task',\n 'tracker_update_task',\n 'tracker_get_task',\n 'tracker_list_tasks',\n 'tracker_add_dependency',\n 'tracker_visualize',\n 'spawn_agent',\n 'check_background_task'\n ];\n const canonical = canonicalNames.map((name) => {\n const found = staticByName.get(name);\n if (found) return found;\n return {\n name,\n description: `${name} tool`,\n parameters: { type: 'object', properties: {} }\n };\n });\n\n const aliases = [\n { alias: 'read_file', target: 'read_file' },\n { alias: 'write_file', target: 'write_file' },\n { alias: 'append_file', target: 'write_file' },\n { alias: 'edit', target: 'replace' },\n { alias: 'replace', target: 'replace' },\n { alias: 'glob', target: 'glob' },\n { alias: 'grep', target: 'grep_search' },\n { alias: 'grep_search', target: 'grep_search' },\n { alias: 'grep_search_ripgrep', target: 'grep_search_ripgrep' },\n { alias: 'list', target: 'list_directory' },\n { alias: 'list_directory', target: 'list_directory' },\n { alias: 'shell', target: 'run_shell_command' },\n { alias: 'run_cmd', target: 'run_shell_command' },\n { alias: 'run_shell_command', target: 'run_shell_command' },\n { alias: 'web_search', target: 'google_web_search' },\n { alias: 'google_web_search', target: 'google_web_search' },\n { alias: 'web_fetch', target: 'web_fetch' },\n { alias: 'save_memory', target: 'save_memory' },\n { alias: 'write_todos', target: 'write_todos' },\n { alias: 'get_internal_docs', target: 'get_internal_docs' },\n { alias: 'ask_user', target: 'ask_user' },\n { alias: 'enter_plan_mode', target: 'enter_plan_mode' },\n { alias: 'exit_plan_mode', target: 'exit_plan_mode' },\n { alias: 'activate_skill', target: 'activate_skill' },\n { alias: 'tracker_create_task', target: 'tracker_create_task' },\n { alias: 'tracker_update_task', target: 'tracker_update_task' },\n { alias: 'tracker_get_task', target: 'tracker_get_task' },\n { alias: 'tracker_list_tasks', target: 'tracker_list_tasks' },\n { alias: 'tracker_add_dependency', target: 'tracker_add_dependency' },\n { alias: 'tracker_visualize', target: 'tracker_visualize' },\n { alias: 'mkdir', target: 'write_file' },\n { alias: 'git', target: 'run_shell_command' },\n // LSP is not yet implemented \u2014 don't alias to read_file (misleads the model)\n // { alias: 'lsp', target: 'read_file' }\n ];\n\n const byName = new Map<string, any>();\n for (const decl of canonical) byName.set(decl.name, decl);\n for (const a of aliases) {\n const target = byName.get(a.target);\n if (!target) continue;\n if (!byName.has(a.alias)) {\n byName.set(a.alias, { ...target, name: a.alias });\n }\n }\n // Local compatibility schemas for non-Gemini built-ins we support in adapter.\n byName.set('mkdir', {\n name: 'mkdir',\n description: 'Create a directory path (staged via sandbox).',\n parameters: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Directory path to create' },\n dir_path: { type: 'string', description: 'Alternative directory path field' }\n }\n }\n });\n byName.set('git', {\n name: 'git',\n description: 'Run limited git subcommands (status/diff/log/add/commit/show/branch).',\n parameters: {\n type: 'object',\n properties: {\n command: { type: 'string', description: 'Git subcommand and args' }\n },\n required: ['command']\n }\n });\n byName.set('lsp', {\n name: 'lsp',\n description: 'Run code-intel queries (symbols/refs/goto/diagnostics/complete).',\n parameters: {\n type: 'object',\n properties: {\n query: { type: 'string', description: 'LSP query string' }\n },\n required: ['query']\n }\n });\n return Array.from(byName.values());\n }\n\n private getStaticToolDeclarations() {\n return [\n { name: 'read_file', description: 'Read file', parameters: { type: 'object', properties: { file_path: { type: 'string' } }, required: ['file_path'] } },\n { name: 'write_file', description: 'Write file', parameters: { type: 'object', properties: { file_path: { type: 'string' }, content: { type: 'string' } }, required: ['file_path', 'content'] } },\n { name: 'replace', description: 'Replace text in file. old_string must uniquely match one location (use replace_all:true for all occurrences). You MUST read_file before editing.', parameters: { type: 'object', properties: { file_path: { type: 'string' }, old_string: { type: 'string' }, new_string: { type: 'string' }, replace_all: { type: 'boolean', description: 'Replace ALL occurrences (useful for renames). Default: false (unique match required)' } }, required: ['file_path', 'old_string', 'new_string'] } },\n { name: 'glob', description: 'Glob search', parameters: { type: 'object', properties: { pattern: { type: 'string' } }, required: ['pattern'] } },\n { name: 'grep_search', description: 'Search for regex/text in files. Supports output modes (content/files/count), context lines, case insensitivity, file type filters.', parameters: { type: 'object', properties: { pattern: { type: 'string' }, path: { type: 'string' }, dir_path: { type: 'string' }, output_mode: { type: 'string', description: 'content (matching lines), files (file paths only), count (match counts)' }, context: { type: 'number', description: 'Lines of context around matches' }, before: { type: 'number' }, after: { type: 'number' }, case_insensitive: { type: 'boolean' }, type: { type: 'string', description: 'File type filter (js, py, ts, go, etc.)' }, max_results: { type: 'number' } }, required: ['pattern'] } },\n { name: 'grep_search_ripgrep', description: 'Alias for grep_search with same capabilities', parameters: { type: 'object', properties: { pattern: { type: 'string' }, path: { type: 'string' }, dir_path: { type: 'string' }, output_mode: { type: 'string' }, context: { type: 'number' }, case_insensitive: { type: 'boolean' }, type: { type: 'string' }, max_results: { type: 'number' } }, required: ['pattern'] } },\n { name: 'list_directory', description: 'List directory', parameters: { type: 'object', properties: { dir_path: { type: 'string' }, path: { type: 'string' } } } },\n { name: 'run_shell_command', description: 'Run shell command (configurable timeout, Docker isolation when staged files exist). Use run_in_background:true for long-running commands.', parameters: { type: 'object', properties: { command: { type: 'string' }, run_in_background: { type: 'boolean', description: 'Run in background and return task ID. Use check_background_task to get result.' }, description: { type: 'string', description: 'Brief description of what the command does' } }, required: ['command'] } },\n { name: 'google_web_search', description: 'Web search', parameters: { type: 'object', properties: { query: { type: 'string' } }, required: ['query'] } },\n { name: 'web_fetch', description: 'Fetch URL', parameters: { type: 'object', properties: { url: { type: 'string' }, prompt: { type: 'string' } } } },\n { name: 'read_many_files', description: 'Read many files', parameters: { type: 'object', properties: { include: { type: 'string' }, exclude: { type: 'string' }, recursive: { type: 'boolean' } } } },\n { name: 'save_memory', description: 'Save memory fact', parameters: { type: 'object', properties: { fact: { type: 'string' } }, required: ['fact'] } },\n { name: 'write_todos', description: 'Write todos', parameters: { type: 'object', properties: { todos: { type: 'array', items: { type: 'object', properties: { text: { type: 'string' }, done: { type: 'boolean' } } } } }, required: ['todos'] } },\n { name: 'get_internal_docs', description: 'Read internal docs', parameters: { type: 'object', properties: { path: { type: 'string' } } } },\n { name: 'ask_user', description: 'Ask user placeholder', parameters: { type: 'object', properties: { questions: { type: 'array', items: { type: 'object', properties: { question: { type: 'string' } } } } } } },\n { name: 'enter_plan_mode', description: 'Enter plan mode', parameters: { type: 'object', properties: { reason: { type: 'string' } } } },\n { name: 'exit_plan_mode', description: 'Exit plan mode', parameters: { type: 'object', properties: { plan_path: { type: 'string' } } } },\n { name: 'activate_skill', description: 'Activate skill', parameters: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] } },\n { name: 'tracker_create_task', description: 'Create tracker task', parameters: { type: 'object', properties: { title: { type: 'string' }, description: { type: 'string' }, type: { type: 'string' }, parentId: { type: 'string' }, dependencies: { type: 'array', items: { type: 'string' } } }, required: ['title', 'description', 'type'] } },\n { name: 'tracker_update_task', description: 'Update tracker task', parameters: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] } },\n { name: 'tracker_get_task', description: 'Get tracker task', parameters: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] } },\n { name: 'tracker_list_tasks', description: 'List tracker tasks', parameters: { type: 'object', properties: { status: { type: 'string' }, type: { type: 'string' }, parentId: { type: 'string' } } } },\n { name: 'tracker_add_dependency', description: 'Add tracker dependency', parameters: { type: 'object', properties: { taskId: { type: 'string' }, dependencyId: { type: 'string' } }, required: ['taskId', 'dependencyId'] } },\n { name: 'tracker_visualize', description: 'Visualize tracker graph', parameters: { type: 'object', properties: {} } },\n { name: 'spawn_agent', description: 'Spawn a sub-agent to handle a task autonomously in parallel. Use for independent research, file analysis, or coding subtasks. Returns the sub-agent result when complete.', parameters: { type: 'object', properties: { task: { type: 'string', description: 'Clear task description for the sub-agent' }, model: { type: 'string', description: 'Optional model override (default: use cheap model for workers)' }, max_turns: { type: 'number', description: 'Max turns for sub-agent (default: 15)' } }, required: ['task'] } },\n { name: 'check_background_task', description: 'Check the status/result of a background shell command. Returns result if done, or elapsed time if still running.', parameters: { type: 'object', properties: { task_id: { type: 'string', description: 'Task ID returned by run_shell_command with run_in_background:true' } }, required: ['task_id'] } }\n ];\n }\n\n /**\n * Execute a tool call from LLM\n */\n async executeTool(toolName: string, params: any): Promise<ToolResult> {\n try {\n switch (toolName) {\n // Canonical Gemini names + local aliases\n case 'write_file':\n return await this.writeFile(params);\n case 'replace':\n return await this.editFile({\n file_path: params.file_path,\n old_string: params.old_string,\n new_string: params.new_string,\n replace_all: params.replace_all\n });\n case 'append_file':\n return await this.appendFile(params);\n case 'read_file':\n return await this.readFile(params);\n case 'edit':\n return await this.editFile(params);\n case 'read_many_files':\n return await this.readManyFilesTool(params);\n case 'save_memory':\n return await this.saveMemoryTool(params);\n case 'write_todos':\n return await this.writeTodosTool(params);\n case 'get_internal_docs':\n return await this.getInternalDocsTool(params);\n case 'ask_user':\n return await this.askUserTool(params);\n case 'enter_plan_mode':\n return await this.enterPlanModeTool(params);\n case 'exit_plan_mode':\n return await this.exitPlanModeTool(params);\n case 'activate_skill':\n return await this.activateSkillTool(params);\n case 'mkdir':\n return await this.mkdirTool(params);\n case 'list':\n return await this.listTool(params);\n case 'list_directory':\n return await this.listTool({ dir_path: params.dir_path || params.path });\n case 'glob':\n return await this.globTool(params);\n case 'grep':\n return await this.grepTool(params);\n case 'grep_search':\n case 'grep_search_ripgrep':\n return await this.grepTool({\n pattern: params.pattern,\n path: params.dir_path || params.path,\n output_mode: params.output_mode,\n context: params.context,\n before: params.before,\n after: params.after,\n case_insensitive: params.case_insensitive,\n type: params.type,\n max_results: params.max_results\n });\n case 'git':\n return await this.gitTool(params);\n case 'shell':\n case 'run_cmd':\n case 'run_shell_command':\n return await this.shellTool(params);\n case 'lsp':\n return await this.lspTool(params);\n case 'web_search':\n case 'google_web_search':\n return await this.webSearchTool(params);\n case 'web_fetch':\n return await this.webFetchTool(params);\n case 'tracker_create_task':\n return await this.trackerCreateTaskTool(params);\n case 'tracker_update_task':\n return await this.trackerUpdateTaskTool(params);\n case 'tracker_get_task':\n return await this.trackerGetTaskTool(params);\n case 'tracker_list_tasks':\n return await this.trackerListTasksTool(params);\n case 'tracker_add_dependency':\n return await this.trackerAddDependencyTool(params);\n case 'tracker_visualize':\n return await this.trackerVisualizeTool();\n case 'spawn_agent':\n return await this.spawnAgentTool(params);\n case 'check_background_task':\n return await this.checkBackgroundTask(params);\n default:\n return {\n success: false,\n error: `Unknown tool: ${toolName}`\n };\n }\n } catch (err: any) {\n return {\n success: false,\n error: err.message\n };\n }\n }\n \n private async writeFile(params: { file_path: string; content: string }): Promise<ToolResult> {\n const isAbsolute = params.file_path.startsWith('/');\n\n if (isAbsolute) {\n // Absolute paths: write directly to disk (user explicitly specified the path)\n try {\n const { mkdir, writeFile } = await import('node:fs/promises');\n const { dirname } = await import('node:path');\n const dir = dirname(params.file_path);\n await mkdir(dir, { recursive: true });\n await writeFile(params.file_path, params.content, 'utf8');\n return {\n success: true,\n output: `Wrote ${params.file_path} (${params.content.length} bytes)`\n };\n } catch (err: any) {\n return { success: false, error: `Write failed: ${err.message}` };\n }\n }\n\n // Relative paths: stage in sandbox with path traversal guard\n const fullPath = resolve(this.config.getWorkspaceRoot(), params.file_path);\n const wsRoot = resolve(this.config.getWorkspaceRoot());\n if (!fullPath.startsWith(wsRoot + '/') && fullPath !== wsRoot) {\n return { success: false, error: `Access denied: path \"${params.file_path}\" resolves outside workspace root.` };\n }\n await this.sandbox.addChange(params.file_path, params.content);\n return {\n success: true,\n output: `Staged ${params.file_path} (${params.content.length} bytes)`\n };\n }\n\n private async appendFile(params: { file_path: string; content: string }): Promise<ToolResult> {\n const filePath = resolve(this.config.getWorkspaceRoot(), params.file_path);\n let existing = '';\n try {\n const stagedContent = this.sandbox.getStagedContent?.(params.file_path)\n || this.sandbox.getStagedContent?.(filePath);\n existing = stagedContent ?? await readFile(filePath, 'utf8');\n } catch {\n existing = '';\n }\n const combined = `${existing}${params.content || ''}`;\n await this.sandbox.addChange(params.file_path, combined);\n return {\n success: true,\n output: `Appended ${params.file_path} (${(params.content || '').length} bytes)`\n };\n }\n \n private async readFile(params: { file_path: string; start_line?: number; end_line?: number }): Promise<ToolResult> {\n const filePath = resolve(this.config.getWorkspaceRoot(), params.file_path);\n\n // Path traversal guard: ensure resolved path is within workspace\n const wsRoot = resolve(this.config.getWorkspaceRoot());\n if (!filePath.startsWith(wsRoot + '/') && filePath !== wsRoot) {\n return { success: false, error: `Access denied: path \"${params.file_path}\" resolves outside workspace root.` };\n }\n\n // Track that this file has been read (for read-before-edit guard)\n this._filesRead.add(params.file_path);\n this._filesRead.add(filePath);\n\n // Check sandbox first for staged (not yet applied) changes\n const stagedContent = this.sandbox.getStagedContent?.(params.file_path)\n || this.sandbox.getStagedContent?.(filePath);\n const content = stagedContent ?? await readFile(filePath, 'utf8');\n \n if (params.start_line || params.end_line) {\n const lines = content.split('\\n');\n const start = (params.start_line || 1) - 1;\n const end = params.end_line || lines.length;\n const slice = lines.slice(start, end).join('\\n');\n return { success: true, output: slice };\n }\n \n return { success: true, output: content };\n }\n \n private async editFile(params: { file_path: string; old_string: string; new_string: string; replace_all?: boolean }): Promise<ToolResult> {\n const filePath = resolve(this.config.getWorkspaceRoot(), params.file_path);\n\n // Path traversal guard\n const wsRoot = resolve(this.config.getWorkspaceRoot());\n if (!filePath.startsWith(wsRoot + '/') && filePath !== wsRoot) {\n return { success: false, error: `Access denied: path \"${params.file_path}\" resolves outside workspace root.` };\n }\n\n // Read-before-edit guard: require the file to have been read first (matches Claude Code)\n if (!this._filesRead.has(params.file_path) && !this._filesRead.has(filePath)) {\n return {\n success: false,\n error: `You must read_file \"${params.file_path}\" before editing it. Never guess at file contents.`\n };\n }\n\n // Read current content (could be staged)\n const stagedContent = this.sandbox.getStagedContent?.(params.file_path)\n || this.sandbox.getStagedContent?.(filePath);\n const content = stagedContent ?? await readFile(filePath, 'utf8');\n\n if (!content.includes(params.old_string)) {\n return {\n success: false,\n error: `String not found in ${params.file_path}`\n };\n }\n\n const occurrences = content.split(params.old_string).length - 1;\n\n // replace_all mode: replace every occurrence (useful for renames)\n if (params.replace_all) {\n const updated = content.split(params.old_string).join(params.new_string);\n await this.sandbox.addChange(params.file_path, updated);\n const diagnostics = await this.shadowValidate(params.file_path);\n return {\n success: true,\n output: `Edited ${params.file_path} (${occurrences} replacements)${diagnostics}`\n };\n }\n\n // Default: unique match required\n if (occurrences > 1) {\n return {\n success: false,\n error: `old_string matches ${occurrences} locations in ${params.file_path}. Provide more context to make it unique, or use replace_all:true to replace all occurrences.`\n };\n }\n\n const updated = content.replace(params.old_string, params.new_string);\n await this.sandbox.addChange(params.file_path, updated);\n\n // Shadow validation: run diagnostics on the edited file (Cursor-style)\n const diagnostics = await this.shadowValidate(params.file_path);\n\n return {\n success: true,\n output: `Edited ${params.file_path}${diagnostics}`\n };\n }\n\n /**\n * Shadow validation: after an edit, check for type/lint errors using LSP.\n * Returns empty string if clean, or diagnostic summary if errors found.\n * Non-fatal \u2014 silently returns empty on any failure.\n */\n private async shadowValidate(filePath: string): Promise<string> {\n // Only validate TypeScript/JavaScript files\n if (!/\\.(ts|tsx|js|jsx|mjs|mts)$/.test(filePath)) return '';\n\n try {\n const lsp = await import('../../lsp/index.js');\n const diags = await lsp.typeCheckProject(this.config.getWorkspaceRoot(), [filePath]);\n\n // Filter to only errors in the edited file\n const fileErrors = diags.filter((d: any) =>\n d.category === 'error' && d.file?.endsWith(filePath)\n );\n\n if (fileErrors.length === 0) return '';\n\n const errorLines = fileErrors.slice(0, 5).map((d: any) =>\n ` ${d.file}:${d.line} \u2014 ${d.message}`\n );\n\n return `\\n\\n\u26A0\uFE0F Shadow validation found ${fileErrors.length} error(s) after edit:\\n${errorLines.join('\\n')}${fileErrors.length > 5 ? `\\n ... and ${fileErrors.length - 5} more` : ''}\\nFix these before moving on.`;\n } catch {\n // LSP not available or failed \u2014 non-fatal\n return '';\n }\n }\n\n private async mkdirTool(params: { path?: string; dir_path?: string }): Promise<ToolResult> {\n const dir = (params.path || params.dir_path || '').trim();\n if (!dir) return { success: false, error: 'mkdir requires path' };\n const keep = join(dir, '.gitkeep');\n await this.sandbox.addChange(keep, '');\n return { success: true, output: `Staged directory ${dir}` };\n }\n\n private async listTool(params: { path?: string; dir_path?: string }): Promise<ToolResult> {\n const target = (params.path || params.dir_path || '.').trim();\n const abs = resolve(process.cwd(), target);\n const items = await readdir(abs, { withFileTypes: true });\n const lines = items.map(i => `${i.isDirectory() ? 'd' : 'f'} ${i.name}`);\n return { success: true, output: lines.join('\\n') };\n }\n\n private async globTool(params: { pattern: string }): Promise<ToolResult> {\n const pattern = String(params.pattern || '').trim();\n if (!pattern) return { success: false, error: 'glob requires pattern' };\n try {\n const out = execSync(`rg --files -g ${JSON.stringify(pattern)}`, { cwd: process.cwd(), stdio: 'pipe', encoding: 'utf8' });\n return { success: true, output: out.trim() };\n } catch (err: any) {\n return { success: false, error: err?.stderr?.toString?.() || err?.message || 'glob failed' };\n }\n }\n\n private async grepTool(params: {\n pattern: string;\n path?: string;\n output_mode?: 'content' | 'files' | 'count';\n context?: number;\n before?: number;\n after?: number;\n case_insensitive?: boolean;\n type?: string;\n max_results?: number;\n }): Promise<ToolResult> {\n const pattern = String(params.pattern || '').trim();\n const searchPath = String(params.path || '.').trim();\n if (!pattern) return { success: false, error: 'grep requires pattern' };\n\n const args = ['rg'];\n\n // Output mode (matches Claude Code's Grep tool)\n const mode = params.output_mode || 'content';\n if (mode === 'files') {\n args.push('-l'); // files_with_matches\n } else if (mode === 'count') {\n args.push('-c'); // count\n } else {\n args.push('-n'); // line numbers for content mode\n }\n\n // Context flags\n if (params.context) args.push(`-C${params.context}`);\n else {\n if (params.before) args.push(`-B${params.before}`);\n if (params.after) args.push(`-A${params.after}`);\n }\n\n // Case insensitive\n if (params.case_insensitive) args.push('-i');\n\n // File type filter\n if (params.type) args.push(`--type=${params.type}`);\n\n // Max results\n if (params.max_results) args.push(`-m${params.max_results}`);\n\n args.push(JSON.stringify(pattern), JSON.stringify(searchPath));\n\n try {\n const out = execSync(args.join(' '), {\n cwd: process.cwd(),\n stdio: 'pipe',\n encoding: 'utf8'\n });\n return { success: true, output: out.trim() };\n } catch (err: any) {\n const text = `${err?.stdout?.toString?.() || ''}\\n${err?.stderr?.toString?.() || ''}`.trim();\n // rg returns exit code 1 for no matches \u2014 that's not an error\n if (err?.status === 1 && !text) return { success: true, output: '(no matches)' };\n return { success: false, error: text || err?.message || 'grep failed' };\n }\n }\n\n private async gitTool(params: { command: string }): Promise<ToolResult> {\n const command = String(params.command || '').trim();\n if (!command) return { success: false, error: 'git requires command' };\n\n // Expanded allowed subcommands (matches Claude Code git safety protocol)\n const allowed = ['status', 'diff', 'log', 'add', 'commit', 'show', 'branch', 'stash', 'tag', 'blame', 'checkout', 'switch', 'restore', 'rev-parse', 'remote', 'fetch', 'pull', 'push', 'merge', 'rebase', 'reset', 'cherry-pick', 'worktree'];\n const verb = command.split(/\\s+/)[0];\n if (!allowed.includes(verb)) {\n return { success: false, error: `git subcommand not allowed: ${verb}. Allowed: ${allowed.join(', ')}` };\n }\n\n // Safety guards (Claude Code pattern: never force push, never skip hooks)\n if (/--force|--force-with-lease/.test(command) && verb === 'push') {\n return { success: false, error: 'Force push is not allowed. Use a regular push or create a new branch.' };\n }\n if (/--no-verify/.test(command)) {\n return { success: false, error: 'Skipping hooks (--no-verify) is not allowed. Fix the hook issue instead.' };\n }\n if (verb === 'reset' && /--hard/.test(command)) {\n return { success: false, error: 'git reset --hard is destructive. Use git stash or git checkout <file> instead.' };\n }\n\n // Reject shell metacharacters to prevent command injection\n if (/[;&|`$(){}\\\\!<>]/.test(command)) {\n return { success: false, error: 'git command contains disallowed shell characters. Use only git arguments.' };\n }\n\n try {\n const args = command.split(/\\s+/).filter(Boolean);\n const { execFileSync } = await import('node:child_process');\n const out = execFileSync('git', args, {\n cwd: this.config.getWorkspaceRoot(),\n stdio: 'pipe',\n encoding: 'utf8',\n timeout: 30000\n });\n return { success: true, output: out.trim() };\n } catch (err: any) {\n const text = `${err?.stdout?.toString?.() || ''}\\n${err?.stderr?.toString?.() || ''}`.trim();\n return { success: false, error: text || err?.message || 'git failed' };\n }\n }\n\n private async shellTool(params: { command: string; run_in_background?: boolean; description?: string }): Promise<ToolResult> {\n const command = String(params.command || '').trim();\n if (!command) return { success: false, error: 'shell requires command' };\n\n // Dangerous command detection \u2014 block destructive patterns\n for (const pat of DANGEROUS_SHELL_PATTERNS) {\n if (pat.test(command)) {\n return { success: false, error: `Blocked: destructive command detected (${command.slice(0, 60)}). Use a safer alternative.` };\n }\n }\n\n // Background execution: run command asynchronously, return task ID\n if (params.run_in_background) {\n const taskId = `bg_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;\n const bgPromise = (async (): Promise<ToolResult> => {\n try {\n const { spawn } = await import('node:child_process');\n return new Promise((resolve) => {\n const proc = spawn('sh', ['-c', command], {\n cwd: this.config.getWorkspaceRoot(),\n stdio: 'pipe'\n });\n let stdout = '', stderr = '';\n proc.stdout?.on('data', (d: Buffer) => { stdout += d.toString(); });\n proc.stderr?.on('data', (d: Buffer) => { stderr += d.toString(); });\n const timeout = setTimeout(() => { proc.kill('SIGTERM'); resolve({ success: false, error: 'Background task timed out' }); }, getShellTimeout());\n proc.on('close', (code: number | null) => {\n clearTimeout(timeout);\n resolve(code === 0\n ? { success: true, output: stdout.trim() }\n : { success: false, error: (stderr || stdout).trim() || `exit code ${code}` });\n });\n });\n } catch (err: any) {\n return { success: false, error: err.message };\n }\n })();\n _backgroundProcesses.set(taskId, { promise: bgPromise, startedAt: Date.now() });\n return { success: true, output: `Background task started: ${taskId}\\nUse check_background_task with this ID to get the result.` };\n }\n \n try {\n // Check if we have staged files - if so, use Docker sandbox\n const hasStagedFiles = this.sandbox.getPendingPaths().length > 0;\n \n if (hasStagedFiles) {\n const { DockerSandbox } = await import('../docker-sandbox.js');\n const docker = new DockerSandbox();\n const dockerAvailable = await docker.isDockerAvailable();\n \n if (dockerAvailable) {\n console.log(`[GeminiAdapter] Running command in Docker with ${this.sandbox.getPendingPaths().length} staged file(s)`);\n const result = await docker.runCommand(command, this.sandbox, {\n workDir: this.config.getWorkspaceRoot(),\n timeout: getShellTimeout()\n });\n return {\n success: result.success,\n output: result.output,\n error: result.success ? undefined : result.output\n };\n } else {\n console.warn('[GeminiAdapter] Docker unavailable - running natively (staged files not available to command)');\n }\n }\n \n // Fallback: run natively from workspace root\n const out = execSync(command, {\n cwd: this.config.getWorkspaceRoot(),\n stdio: 'pipe',\n encoding: 'utf8',\n timeout: getShellTimeout()\n });\n return { success: true, output: out.trim() };\n } catch (err: any) {\n const text = `${err?.stdout?.toString?.() || ''}\\n${err?.stderr?.toString?.() || ''}`.trim();\n return { success: false, error: text || err?.message || 'shell failed' };\n }\n }\n\n private async webSearchTool(params: { query: string }): Promise<ToolResult> {\n const query = String(params.query || '').trim();\n if (!query) return { success: false, error: 'web_search requires query' };\n const braveKey = process.env.BRAVE_API_KEY || process.env.BRAVE_SEARCH_API_KEY;\n if (!braveKey) return { success: false, error: 'web_search unavailable (missing BRAVE_API_KEY)' };\n try {\n const res = await fetch(\n `https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(query)}&count=5`,\n {\n headers: {\n 'Accept': 'application/json',\n 'X-Subscription-Token': braveKey\n },\n signal: AbortSignal.timeout(10000)\n }\n );\n if (!res.ok) return { success: false, error: `web_search failed: HTTP ${res.status}` };\n const data: any = await res.json();\n const hits = (data?.web?.results || []).slice(0, 5);\n const formatted = hits.map((r: any, i: number) =>\n `${i + 1}. ${r.title || '(untitled)'}\\n${r.url || ''}\\n${r.description || ''}`\n ).join('\\n\\n');\n return { success: true, output: formatted || 'No results' };\n } catch (err: any) {\n return { success: false, error: err?.message || 'web_search failed' };\n }\n }\n\n private async webFetchTool(params: { url: string }): Promise<ToolResult> {\n const url = String(params.url || '').trim();\n if (!url || !/^https?:\\/\\//i.test(url)) {\n return { success: false, error: 'web_fetch requires valid http(s) url' };\n }\n try {\n const res = await fetch(url, {\n headers: { 'User-Agent': 'CrewSwarm-CLI/1.0' },\n signal: AbortSignal.timeout(12000)\n });\n if (!res.ok) return { success: false, error: `web_fetch failed: HTTP ${res.status}` };\n const ct = String(res.headers.get('content-type') || '');\n let text = await res.text();\n if (ct.includes('html')) {\n text = text\n .replace(/<script[\\s\\S]*?<\\/script>/gi, '')\n .replace(/<style[\\s\\S]*?<\\/style>/gi, '')\n .replace(/<[^>]+>/g, ' ')\n .replace(/\\s{2,}/g, ' ')\n .trim();\n }\n return { success: true, output: text.slice(0, 12000) };\n } catch (err: any) {\n return { success: false, error: err?.message || 'web_fetch failed' };\n }\n }\n\n private async readManyFilesTool(params: {\n include?: string;\n exclude?: string | string[];\n recursive?: boolean;\n }): Promise<ToolResult> {\n const include = String(params.include || '**/*').trim();\n try {\n const out = execSync(`rg --files -g ${JSON.stringify(include)}`, {\n cwd: this.config.getWorkspaceRoot(),\n stdio: 'pipe',\n encoding: 'utf8'\n });\n const files = out.split('\\n').filter(Boolean).slice(0, 20);\n const chunks: string[] = [];\n for (const rel of files) {\n const full = resolve(this.config.getWorkspaceRoot(), rel);\n try {\n const content = await readFile(full, 'utf8');\n chunks.push(`--- ${rel} ---\\n${content.slice(0, 2000)}`);\n } catch {\n // Skip unreadable/non-text\n }\n }\n return { success: true, output: chunks.join('\\n\\n') || 'No readable files matched' };\n } catch (err: any) {\n return { success: false, error: err?.message || 'read_many_files failed' };\n }\n }\n\n private async saveMemoryTool(params: { fact: string }): Promise<ToolResult> {\n const fact = String(params.fact || '').trim();\n if (!fact) return { success: false, error: 'save_memory requires fact' };\n const memDir = resolve(this.config.getWorkspaceRoot(), '.crew');\n await mkdir(memDir, { recursive: true });\n const memFile = resolve(memDir, 'memory-facts.log');\n let prior = '';\n try { prior = await readFile(memFile, 'utf8'); } catch {}\n await writeFile(memFile, `${prior}${new Date().toISOString()} ${fact}\\n`, 'utf8');\n return { success: true, output: 'Memory saved' };\n }\n\n private async writeTodosTool(params: { todos: any[] }): Promise<ToolResult> {\n const todos = Array.isArray(params.todos) ? params.todos : [];\n const memDir = resolve(this.config.getWorkspaceRoot(), '.crew');\n await mkdir(memDir, { recursive: true });\n const todoFile = resolve(memDir, 'todos.json');\n await writeFile(todoFile, JSON.stringify(todos, null, 2), 'utf8');\n return { success: true, output: `Saved ${todos.length} todos` };\n }\n\n private async getInternalDocsTool(params: { path?: string }): Promise<ToolResult> {\n const target = String(params.path || 'AGENTS.md').trim();\n const abs = resolve(this.config.getWorkspaceRoot(), target);\n try {\n const content = await readFile(abs, 'utf8');\n return { success: true, output: content.slice(0, 12000) };\n } catch (err: any) {\n return { success: false, error: `get_internal_docs failed: ${err?.message || target}` };\n }\n }\n\n private async askUserTool(params: { questions?: any[] }): Promise<ToolResult> {\n const qs = Array.isArray(params.questions) ? params.questions : [];\n if (qs.length === 0) {\n return { success: false, error: 'ask_user requires at least one question' };\n }\n const now = new Date().toISOString();\n const request = {\n id: `ask-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`,\n ts: now,\n status: 'pending',\n questions: qs\n };\n const crewDir = this.crewDirPath();\n await mkdir(crewDir, { recursive: true });\n await this.appendJsonLine(this.askUserRequestsPath(), request);\n await writeFile(this.askUserLatestPath(), JSON.stringify(request, null, 2), 'utf8');\n const summary = qs.map((q: any, i: number) => `${i + 1}. ${q?.question || 'question'}`).join('\\n');\n return {\n success: true,\n output: `User input required (non-interactive runtime).\\nSaved request: ${this.relativeCrewPath(this.askUserLatestPath())}\\nQuestions:\\n${summary}`\n };\n }\n\n private async enterPlanModeTool(params: { reason?: string }): Promise<ToolResult> {\n const crewDir = this.crewDirPath();\n await mkdir(crewDir, { recursive: true });\n const state = {\n active: true,\n enteredAt: new Date().toISOString(),\n exitedAt: null,\n reason: String(params?.reason || '').trim() || null,\n planPath: null\n };\n await writeFile(this.planModeStatePath(), JSON.stringify(state, null, 2), 'utf8');\n return {\n success: true,\n output: `Plan mode entered${state.reason ? `: ${state.reason}` : ''} (${this.relativeCrewPath(this.planModeStatePath())})`\n };\n }\n\n private async exitPlanModeTool(params: { plan_path?: string }): Promise<ToolResult> {\n const crewDir = this.crewDirPath();\n await mkdir(crewDir, { recursive: true });\n let prior: any = {};\n try {\n prior = JSON.parse(await readFile(this.planModeStatePath(), 'utf8'));\n } catch {\n prior = {};\n }\n const state = {\n ...prior,\n active: false,\n exitedAt: new Date().toISOString(),\n planPath: String(params?.plan_path || '').trim() || prior?.planPath || null\n };\n await writeFile(this.planModeStatePath(), JSON.stringify(state, null, 2), 'utf8');\n return {\n success: true,\n output: `Plan mode exited${state.planPath ? `: ${state.planPath}` : ''} (${this.relativeCrewPath(this.planModeStatePath())})`\n };\n }\n\n private async activateSkillTool(params: { name?: string }): Promise<ToolResult> {\n const name = String(params?.name || '').trim();\n if (!name) return { success: false, error: 'activate_skill requires name' };\n const crewDir = this.crewDirPath();\n await mkdir(crewDir, { recursive: true });\n let state: any = { active: [] };\n try {\n state = JSON.parse(await readFile(this.activeSkillsPath(), 'utf8'));\n } catch {\n state = { active: [] };\n }\n const active = new Set(Array.isArray(state?.active) ? state.active : []);\n active.add(name);\n const next = {\n active: Array.from(active).sort(),\n updatedAt: new Date().toISOString()\n };\n await writeFile(this.activeSkillsPath(), JSON.stringify(next, null, 2), 'utf8');\n return { success: true, output: `Skill activated: ${name} (${this.relativeCrewPath(this.activeSkillsPath())})` };\n }\n\n private crewDirPath() {\n return resolve(this.config.getWorkspaceRoot(), '.crew');\n }\n\n private askUserRequestsPath() {\n return resolve(this.crewDirPath(), 'ask-user-requests.jsonl');\n }\n\n private askUserLatestPath() {\n return resolve(this.crewDirPath(), 'ask-user-latest.json');\n }\n\n private planModeStatePath() {\n return resolve(this.crewDirPath(), 'plan-mode.json');\n }\n\n private activeSkillsPath() {\n return resolve(this.crewDirPath(), 'active-skills.json');\n }\n\n private relativeCrewPath(absPath: string) {\n return absPath.replace(this.config.getWorkspaceRoot(), '.');\n }\n\n private async appendJsonLine(filePath: string, data: any): Promise<void> {\n let prior = '';\n try {\n prior = await readFile(filePath, 'utf8');\n } catch {\n prior = '';\n }\n const line = `${JSON.stringify(data)}\\n`;\n await writeFile(filePath, `${prior}${line}`, 'utf8');\n }\n\n private trackerFilePath() {\n return resolve(this.config.getWorkspaceRoot(), '.crew', 'tracker.json');\n }\n\n private async readTracker(): Promise<any[]> {\n try {\n const raw = await readFile(this.trackerFilePath(), 'utf8');\n const parsed = JSON.parse(raw);\n return Array.isArray(parsed) ? parsed : [];\n } catch {\n return [];\n }\n }\n\n private async writeTracker(tasks: any[]): Promise<void> {\n const dir = resolve(this.config.getWorkspaceRoot(), '.crew');\n await mkdir(dir, { recursive: true });\n await writeFile(this.trackerFilePath(), JSON.stringify(tasks, null, 2), 'utf8');\n }\n\n private mkTrackerId() {\n return Math.random().toString(16).slice(2, 8);\n }\n\n private async trackerCreateTaskTool(params: any): Promise<ToolResult> {\n const tasks = await this.readTracker();\n const task = {\n id: this.mkTrackerId(),\n title: String(params?.title || 'Untitled'),\n description: String(params?.description || ''),\n type: String(params?.type || 'task'),\n status: 'open',\n parentId: params?.parentId || null,\n dependencies: Array.isArray(params?.dependencies) ? params.dependencies : []\n };\n tasks.push(task);\n await this.writeTracker(tasks);\n return { success: true, output: JSON.stringify(task, null, 2) };\n }\n\n private async trackerUpdateTaskTool(params: any): Promise<ToolResult> {\n const tasks = await this.readTracker();\n const id = String(params?.id || '');\n const idx = tasks.findIndex((t: any) => t.id === id);\n if (idx < 0) return { success: false, error: `Task not found: ${id}` };\n tasks[idx] = { ...tasks[idx], ...params };\n await this.writeTracker(tasks);\n return { success: true, output: JSON.stringify(tasks[idx], null, 2) };\n }\n\n private async trackerGetTaskTool(params: any): Promise<ToolResult> {\n const tasks = await this.readTracker();\n const id = String(params?.id || '');\n const task = tasks.find((t: any) => t.id === id);\n if (!task) return { success: false, error: `Task not found: ${id}` };\n return { success: true, output: JSON.stringify(task, null, 2) };\n }\n\n private async trackerListTasksTool(params: any): Promise<ToolResult> {\n const tasks = await this.readTracker();\n const filtered = tasks.filter((t: any) => {\n if (params?.status && t.status !== params.status) return false;\n if (params?.type && t.type !== params.type) return false;\n if (params?.parentId && t.parentId !== params.parentId) return false;\n return true;\n });\n return { success: true, output: JSON.stringify(filtered, null, 2) };\n }\n\n private async trackerAddDependencyTool(params: any): Promise<ToolResult> {\n const tasks = await this.readTracker();\n const taskId = String(params?.taskId || '');\n const depId = String(params?.dependencyId || '');\n const idx = tasks.findIndex((t: any) => t.id === taskId);\n if (idx < 0) return { success: false, error: `Task not found: ${taskId}` };\n const deps = new Set(Array.isArray(tasks[idx].dependencies) ? tasks[idx].dependencies : []);\n deps.add(depId);\n tasks[idx].dependencies = Array.from(deps);\n await this.writeTracker(tasks);\n return { success: true, output: JSON.stringify(tasks[idx], null, 2) };\n }\n\n private async trackerVisualizeTool(): Promise<ToolResult> {\n const tasks = await this.readTracker();\n const lines = tasks.map((t: any) => {\n const deps = Array.isArray(t.dependencies) && t.dependencies.length\n ? ` -> [${t.dependencies.join(', ')}]`\n : '';\n return `${t.id} [${t.status}] ${t.title}${deps}`;\n });\n return { success: true, output: lines.join('\\n') || '(no tasks)' };\n }\n\n private async lspTool(params: { query: string }): Promise<ToolResult> {\n const query = String(params.query || '').trim();\n if (!query) return { success: false, error: 'lsp requires query' };\n const lower = query.toLowerCase();\n const lsp = await import('../../lsp/index.js');\n if (lower.startsWith('symbols')) {\n const file = query.slice('symbols'.length).trim();\n if (!file) return { success: false, error: 'lsp symbols requires file path' };\n const symbols = await lsp.getDocumentSymbols(process.cwd(), file);\n return { success: true, output: symbols.map(s => `${file}:${s.line}:${s.column} ${s.kind} ${s.name}`).join('\\n') };\n }\n if (lower.startsWith('refs')) {\n const target = query.slice('refs'.length).trim();\n const match = target.match(/^(.+):(\\d+)(?::(\\d+))?$/);\n if (match) {\n const refs = await lsp.getReferences(process.cwd(), match[1], Number(match[2]), Number(match[3] || '1'));\n return { success: true, output: refs.map(r => `${r.file}:${r.line}:${r.column}`).join('\\n') };\n }\n if (target) return this.grepTool({ pattern: `\\\\b${target}\\\\b`, path: '.' });\n return { success: false, error: 'lsp refs requires symbol or file:line[:col]' };\n }\n if (lower.startsWith('goto')) {\n const target = query.slice('goto'.length).trim();\n const match = target.match(/^(.+):(\\d+)(?::(\\d+))?$/);\n if (!match) return { success: false, error: 'lsp goto format: file:line[:col]' };\n const defs = await lsp.getDefinitions(process.cwd(), match[1], Number(match[2]), Number(match[3] || '1'));\n return { success: true, output: defs.map(d => `${d.file}:${d.line}:${d.column}`).join('\\n') };\n }\n if (lower.startsWith('diagnostics') || lower === 'check') {\n const diags = await lsp.typeCheckProject(process.cwd(), []);\n return { success: true, output: diags.map(d => `${d.file}:${d.line}:${d.column} [${d.category}] ${d.message}`).join('\\n') };\n }\n if (lower.startsWith('complete')) {\n const target = query.slice('complete'.length).trim();\n const match = target.match(/^(.+):(\\d+):(\\d+)(?:\\s+(.+))?$/);\n if (!match) return { success: false, error: 'lsp complete format: file:line:col [prefix]' };\n const items = await lsp.getCompletions(process.cwd(), match[1], Number(match[2]), Number(match[3]), 50, match[4] || '');\n return { success: true, output: items.map(i => `${i.name} (${i.kind})`).join('\\n') };\n }\n return { success: false, error: `Unsupported lsp query: ${query}` };\n }\n\n private async checkBackgroundTask(params: { task_id: string }): Promise<ToolResult> {\n const taskId = String(params.task_id || '').trim();\n if (!taskId) return { success: false, error: 'check_background_task requires task_id' };\n const bg = _backgroundProcesses.get(taskId);\n if (!bg) return { success: false, error: `No background task found with ID: ${taskId}` };\n\n // Check if done (non-blocking with race against a resolved promise)\n const done = await Promise.race([\n bg.promise.then(r => ({ done: true as const, result: r })),\n new Promise<{ done: false }>(resolve => setTimeout(() => resolve({ done: false }), 50))\n ]);\n\n if (!done.done) {\n const elapsed = Math.round((Date.now() - bg.startedAt) / 1000);\n return { success: true, output: `Task ${taskId} still running (${elapsed}s elapsed). Check again later.` };\n }\n\n _backgroundProcesses.delete(taskId);\n return done.result;\n }\n\n // Track sub-agent depth to prevent infinite recursion\n private static _spawnDepth = 0;\n private static readonly MAX_SPAWN_DEPTH = 3;\n\n private async spawnAgentTool(params: { task: string; model?: string; max_turns?: number }): Promise<ToolResult> {\n const task = String(params.task || '').trim();\n if (!task) return { success: false, error: 'spawn_agent requires task' };\n\n if (GeminiToolAdapter._spawnDepth >= GeminiToolAdapter.MAX_SPAWN_DEPTH) {\n return { success: false, error: `Sub-agent depth limit reached (max ${GeminiToolAdapter.MAX_SPAWN_DEPTH}). Complete this task directly instead.` };\n }\n\n const maxTurns = Math.min(params.max_turns || 15, 25);\n const model = params.model || process.env.CREW_WORKER_MODEL || process.env.CREW_EXECUTION_MODEL || '';\n const branchName = `sub-agent-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;\n\n try {\n // Create isolated sandbox branch for sub-agent\n await this.sandbox.createBranch(branchName);\n\n GeminiToolAdapter._spawnDepth++;\n\n const { runAgenticWorker } = await import('../../executor/agentic-executor.js');\n const result = await runAgenticWorker(task, this.sandbox, {\n model,\n maxTurns,\n stream: false, // Sub-agents don't stream to stdout\n verbose: Boolean(process.env.CREW_DEBUG),\n tier: 'fast' // Default to cheap model for sub-agents\n });\n\n GeminiToolAdapter._spawnDepth--;\n\n // Merge sub-agent changes back to parent branch\n const parentBranch = this.sandbox.getActiveBranch();\n if (parentBranch !== branchName) {\n // Already switched back by the sub-agent's sandbox ops \u2014 merge explicitly\n await this.sandbox.mergeBranch(branchName, parentBranch);\n } else {\n // Switch back to parent and merge\n const branches = this.sandbox.getBranches();\n const parent = branches.find(b => b !== branchName) || 'main';\n await this.sandbox.switchBranch(parent);\n await this.sandbox.mergeBranch(branchName, parent);\n }\n\n // Clean up the branch\n try { await this.sandbox.deleteBranch(branchName); } catch { /* ignore */ }\n\n const output = [\n `Sub-agent completed in ${result.turns || 0} turns (${result.modelUsed || 'unknown'})`,\n result.cost ? `Cost: $${result.cost.toFixed(4)}` : '',\n `Status: ${result.success ? 'SUCCESS' : 'FAILED'}`,\n '',\n result.output?.slice(0, 3000) || '(no output)'\n ].filter(Boolean).join('\\n');\n\n return { success: result.success, output };\n } catch (err: any) {\n GeminiToolAdapter._spawnDepth = Math.max(0, GeminiToolAdapter._spawnDepth - 1);\n // Try to clean up branch\n try { await this.sandbox.switchBranch('main'); } catch { /* ignore */ }\n try { await this.sandbox.deleteBranch(branchName); } catch { /* ignore */ }\n return { success: false, error: `Sub-agent failed: ${err.message}` };\n }\n }\n\n /**\n * Get tool declarations for LLM function calling\n */\n getToolDeclarations() {\n const dynamicEnabled = process.env.CREW_GEMINI_DYNAMIC_DECLARATIONS !== 'false';\n if (dynamicEnabled) {\n try {\n const decls = this.buildDynamicDeclarations();\n if (decls.length > 0) return decls;\n } catch {\n // Fallback to static declarations below.\n }\n }\n return [\n {\n name: 'read_file',\n description: 'Read the contents of a file. ALWAYS read files before editing them. Use start_line/end_line for large files.',\n parameters: {\n type: 'object',\n properties: {\n file_path: { type: 'string', description: 'Relative path from project root' },\n start_line: { type: 'number', description: 'Start line number (1-based, optional)' },\n end_line: { type: 'number', description: 'End line number (inclusive, optional)' }\n },\n required: ['file_path']\n }\n },\n {\n name: 'glob',\n description: 'Find files matching a glob pattern. Use this to discover file structure. Examples: \"**/*.ts\", \"src/**/*.tsx\", \"*.json\"',\n parameters: {\n type: 'object',\n properties: {\n pattern: { type: 'string', description: 'Glob pattern (e.g. \"src/**/*.ts\")' }\n },\n required: ['pattern']\n }\n },\n {\n name: 'grep',\n description: 'Search for text/regex patterns in files. Returns matching lines with file paths and line numbers.',\n parameters: {\n type: 'object',\n properties: {\n pattern: { type: 'string', description: 'Regex or text pattern to search for' },\n path: { type: 'string', description: 'Directory or file to search in (default: \".\")' }\n },\n required: ['pattern']\n }\n },\n {\n name: 'grep_search',\n description: 'Canonical alias for grep. Search for regex/text in files.',\n parameters: {\n type: 'object',\n properties: {\n pattern: { type: 'string', description: 'Regex/text pattern' },\n dir_path: { type: 'string', description: 'Path to search (default: .)' }\n },\n required: ['pattern']\n }\n },\n {\n name: 'grep_search_ripgrep',\n description: 'Ripgrep-optimized canonical name. Routed to grep tool in this adapter.',\n parameters: {\n type: 'object',\n properties: {\n pattern: { type: 'string', description: 'Regex/text pattern' },\n dir_path: { type: 'string', description: 'Path to search (default: .)' },\n path: { type: 'string', description: 'Alternative path field' }\n },\n required: ['pattern']\n }\n },\n {\n name: 'write_file',\n description: 'Write content to a file (creates or overwrites). Changes are staged in sandbox. Use for new files or full rewrites.',\n parameters: {\n type: 'object',\n properties: {\n file_path: { type: 'string', description: 'Relative path from project root' },\n content: { type: 'string', description: 'Complete file content' }\n },\n required: ['file_path', 'content']\n }\n },\n {\n name: 'append_file',\n description: 'Append content to an existing file. Creates file if it does not exist. Changes are staged in sandbox.',\n parameters: {\n type: 'object',\n properties: {\n file_path: { type: 'string', description: 'Relative path from project root' },\n content: { type: 'string', description: 'Content to append' }\n },\n required: ['file_path', 'content']\n }\n },\n {\n name: 'edit',\n description: 'Edit a file by replacing an exact string match. ALWAYS read the file first to get the exact string. Use for targeted changes.',\n parameters: {\n type: 'object',\n properties: {\n file_path: { type: 'string', description: 'Relative path from project root' },\n old_string: { type: 'string', description: 'Exact string to find (must match precisely)' },\n new_string: { type: 'string', description: 'Replacement string' }\n },\n required: ['file_path', 'old_string', 'new_string']\n }\n },\n {\n name: 'replace',\n description: 'Canonical alias for edit. Replace exact old_string with new_string.',\n parameters: {\n type: 'object',\n properties: {\n file_path: { type: 'string', description: 'Relative path from project root' },\n old_string: { type: 'string', description: 'Exact string to replace' },\n new_string: { type: 'string', description: 'Replacement string' }\n },\n required: ['file_path', 'old_string', 'new_string']\n }\n },\n {\n name: 'shell',\n description: 'Run a shell command (e.g. npm test, node script.js, cat, ls). Use for build verification, running tests, or commands not covered by other tools.',\n parameters: {\n type: 'object',\n properties: {\n command: { type: 'string', description: 'Shell command to execute' }\n },\n required: ['command']\n }\n },\n {\n name: 'run_cmd',\n description: 'Alias for shell. Run a shell command. Prefer this for compatibility with existing prompts.',\n parameters: {\n type: 'object',\n properties: {\n command: { type: 'string', description: 'Shell command to execute' }\n },\n required: ['command']\n }\n },\n {\n name: 'run_shell_command',\n description: 'Canonical alias for shell/run_cmd.',\n parameters: {\n type: 'object',\n properties: {\n command: { type: 'string', description: 'Shell command to execute' }\n },\n required: ['command']\n }\n },\n {\n name: 'mkdir',\n description: 'Create a directory (staged via .gitkeep in sandbox).',\n parameters: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Directory path to create' },\n dir_path: { type: 'string', description: 'Alternate directory path field' }\n },\n required: []\n }\n },\n {\n name: 'list',\n description: 'List files and directories for a path.',\n parameters: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Path to list (default: .)' },\n dir_path: { type: 'string', description: 'Alternate path field' }\n },\n required: []\n }\n },\n {\n name: 'list_directory',\n description: 'Canonical alias for list.',\n parameters: {\n type: 'object',\n properties: {\n dir_path: { type: 'string', description: 'Directory path to list (default: .)' }\n },\n required: []\n }\n },\n {\n name: 'git',\n description: 'Run git subcommands (status, diff, log, show, branch). Use to understand repo state and recent changes.',\n parameters: {\n type: 'object',\n properties: {\n command: { type: 'string', description: 'Git subcommand (e.g. \"diff HEAD~3\", \"log --oneline -10\")' }\n },\n required: ['command']\n }\n },\n {\n name: 'lsp',\n description: 'Code intelligence: \"symbols <file>\" for outline, \"refs <file:line:col>\" for references, \"goto <file:line:col>\" for definition, \"diagnostics\" for type errors.',\n parameters: {\n type: 'object',\n properties: {\n query: { type: 'string', description: 'LSP query (e.g. \"symbols src/app.ts\", \"goto src/app.ts:42:5\")' }\n },\n required: ['query']\n }\n },\n {\n name: 'web_search',\n description: 'Search the web via Brave Search API (requires BRAVE_API_KEY).',\n parameters: {\n type: 'object',\n properties: {\n query: { type: 'string', description: 'Search query' }\n },\n required: ['query']\n }\n },\n {\n name: 'google_web_search',\n description: 'Canonical alias for web_search.',\n parameters: {\n type: 'object',\n properties: {\n query: { type: 'string', description: 'Search query' }\n },\n required: ['query']\n }\n },\n {\n name: 'web_fetch',\n description: 'Fetch content from a URL and return cleaned text for analysis.',\n parameters: {\n type: 'object',\n properties: {\n url: { type: 'string', description: 'http(s) URL to fetch' }\n },\n required: ['url']\n }\n },\n {\n name: 'read_many_files',\n description: 'Read multiple files by include glob and return concatenated excerpts.',\n parameters: {\n type: 'object',\n properties: {\n include: { type: 'string', description: 'Glob include pattern (default: **/*)' },\n exclude: { type: 'string', description: 'Optional exclude glob' },\n recursive: { type: 'boolean', description: 'Recursive search (optional)' }\n },\n required: []\n }\n },\n {\n name: 'save_memory',\n description: 'Save a memory fact to local project memory log.',\n parameters: {\n type: 'object',\n properties: {\n fact: { type: 'string', description: 'Memory fact to persist' }\n },\n required: ['fact']\n }\n },\n {\n name: 'write_todos',\n description: 'Persist todo items for the current project.',\n parameters: {\n type: 'object',\n properties: {\n todos: { type: 'array', description: 'Todo items array' }\n },\n required: ['todos']\n }\n },\n {\n name: 'get_internal_docs',\n description: 'Read internal docs by relative path (default AGENTS.md).',\n parameters: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Relative doc path' }\n },\n required: []\n }\n },\n {\n name: 'ask_user',\n description: 'Non-interactive placeholder for ask-user; returns summarized questions.',\n parameters: {\n type: 'object',\n properties: {\n questions: { type: 'array', description: 'Question descriptors' }\n },\n required: []\n }\n },\n {\n name: 'enter_plan_mode',\n description: 'Enter plan mode (no-op marker in CLI adapter).',\n parameters: {\n type: 'object',\n properties: {\n reason: { type: 'string', description: 'Plan mode reason' }\n },\n required: []\n }\n },\n {\n name: 'exit_plan_mode',\n description: 'Exit plan mode (no-op marker in CLI adapter).',\n parameters: {\n type: 'object',\n properties: {\n plan_path: { type: 'string', description: 'Optional plan file path' }\n },\n required: []\n }\n },\n {\n name: 'activate_skill',\n description: 'Activate a named skill (adapter acknowledgment).',\n parameters: {\n type: 'object',\n properties: {\n name: { type: 'string', description: 'Skill name' }\n },\n required: ['name']\n }\n },\n {\n name: 'tracker_create_task',\n description: 'Create tracker task in local .crew/tracker.json.',\n parameters: {\n type: 'object',\n properties: {\n title: { type: 'string' },\n description: { type: 'string' },\n type: { type: 'string' },\n parentId: { type: 'string' },\n dependencies: { type: 'array' }\n },\n required: ['title', 'description', 'type']\n }\n },\n {\n name: 'tracker_update_task',\n description: 'Update tracker task by id.',\n parameters: {\n type: 'object',\n properties: {\n id: { type: 'string' },\n title: { type: 'string' },\n description: { type: 'string' },\n status: { type: 'string' },\n dependencies: { type: 'array' }\n },\n required: ['id']\n }\n },\n {\n name: 'tracker_get_task',\n description: 'Get tracker task by id.',\n parameters: {\n type: 'object',\n properties: {\n id: { type: 'string' }\n },\n required: ['id']\n }\n },\n {\n name: 'tracker_list_tasks',\n description: 'List tracker tasks with optional filters.',\n parameters: {\n type: 'object',\n properties: {\n status: { type: 'string' },\n type: { type: 'string' },\n parentId: { type: 'string' }\n },\n required: []\n }\n },\n {\n name: 'tracker_add_dependency',\n description: 'Add dependency between tracker tasks.',\n parameters: {\n type: 'object',\n properties: {\n taskId: { type: 'string' },\n dependencyId: { type: 'string' }\n },\n required: ['taskId', 'dependencyId']\n }\n },\n {\n name: 'tracker_visualize',\n description: 'Visualize tracker tasks as ASCII list.',\n parameters: {\n type: 'object',\n properties: {},\n required: []\n }\n }\n ];\n }\n}\n", "import { access, copyFile, mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { constants } from 'node:fs';\nimport { join } from 'node:path';\n\nexport interface CorrectionEntry {\n timestamp: string;\n prompt: string;\n original: string;\n corrected: string;\n agent?: string;\n tags?: string[];\n}\n\nfunction nowIso(): string {\n return new Date().toISOString();\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nexport class CorrectionStore {\n baseDir: string;\n stateDir: string;\n dataPath: string;\n\n constructor(baseDir = process.cwd()) {\n this.baseDir = baseDir;\n this.stateDir = join(baseDir, '.crew');\n this.dataPath = join(this.stateDir, 'training-data.jsonl');\n }\n\n async ensureReady(): Promise<void> {\n if (!(await pathExists(this.stateDir))) {\n await mkdir(this.stateDir, { recursive: true });\n }\n\n if (!(await pathExists(this.dataPath))) {\n await writeFile(this.dataPath, '', 'utf8');\n }\n }\n\n async record(entry: Omit<CorrectionEntry, 'timestamp'>): Promise<CorrectionEntry> {\n await this.ensureReady();\n\n const payload: CorrectionEntry = {\n timestamp: nowIso(),\n ...entry\n };\n\n await writeFile(this.dataPath, `${JSON.stringify(payload)}\\n`, {\n encoding: 'utf8',\n flag: 'a'\n });\n\n return payload;\n }\n\n async loadAll(): Promise<CorrectionEntry[]> {\n await this.ensureReady();\n const raw = await readFile(this.dataPath, 'utf8');\n const lines = raw.split('\\n').map(line => line.trim()).filter(Boolean);\n return lines.map(line => JSON.parse(line) as CorrectionEntry);\n }\n\n async summary(): Promise<{ count: number; latest?: CorrectionEntry }> {\n const all = await this.loadAll();\n return {\n count: all.length,\n latest: all.length > 0 ? all[all.length - 1] : undefined\n };\n }\n\n async exportTo(path: string): Promise<void> {\n await this.ensureReady();\n await copyFile(this.dataPath, path);\n }\n}\n", "/**\n * Collections Search \u2014 lightweight local RAG over docs and markdown files.\n *\n * Indexes markdown / text files under configurable paths, builds a simple\n * TF-IDF\u2013style term index, and returns ranked chunks with source attribution.\n */\n\nimport { readdir, readFile, stat } from 'node:fs/promises';\nimport { extname, join, relative, resolve } from 'node:path';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface CollectionChunk {\n /** Relative path from the collection root */\n source: string;\n /** 1-based line number where the chunk starts */\n startLine: number;\n /** The raw text of the chunk */\n text: string;\n /** Relevance score (higher = more relevant) */\n score: number;\n}\n\nexport interface CollectionIndex {\n root: string;\n fileCount: number;\n chunkCount: number;\n /** term \u2192 Set of chunk indices */\n terms: Map<string, Set<number>>;\n chunks: CollectionChunk[];\n}\n\nexport interface BuildCollectionOptions {\n includeCode?: boolean;\n}\n\nexport interface SearchResult {\n query: string;\n hits: CollectionChunk[];\n totalChunks: number;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst DOC_EXTENSIONS = new Set(['.md', '.mdx', '.txt', '.rst', '.adoc']);\nconst CODE_EXTENSIONS = new Set([\n '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.json',\n '.py', '.go', '.rs', '.java', '.kt', '.swift',\n '.sh', '.bash', '.zsh', '.yaml', '.yml', '.toml'\n]);\n\nconst IGNORED_DIRS = new Set([\n 'node_modules', '.git', 'dist', 'build', '.crew',\n '.next', '.turbo', 'coverage', '__pycache__'\n]);\n\nfunction tokenize(text: string): string[] {\n return text\n .toLowerCase()\n .replace(/[^a-z0-9\\s_-]/g, ' ')\n .split(/\\s+/)\n .filter(t => t.length > 1);\n}\n\nfunction hashToken(token: string, dim: number): number {\n let h = 2166136261;\n for (let i = 0; i < token.length; i++) {\n h ^= token.charCodeAt(i);\n h = Math.imul(h, 16777619);\n }\n return Math.abs(h) % dim;\n}\n\nfunction toHashedVector(text: string, dim = 256): Float64Array {\n const vec = new Float64Array(dim);\n const toks = tokenize(text);\n for (const t of toks) {\n vec[hashToken(t, dim)] += 1;\n }\n // l2 normalize\n let norm = 0;\n for (let i = 0; i < dim; i++) norm += vec[i] * vec[i];\n norm = Math.sqrt(norm);\n if (norm > 0) {\n for (let i = 0; i < dim; i++) vec[i] /= norm;\n }\n return vec;\n}\n\nfunction cosineSimilarity(a: Float64Array, b: Float64Array): number {\n const dim = Math.min(a.length, b.length);\n let dot = 0;\n for (let i = 0; i < dim; i++) {\n dot += a[i] * b[i];\n }\n return dot;\n}\n\n/**\n * Split a file into chunks \u2014 one chunk per heading section, or fixed-size\n * paragraphs for files without headings.\n */\nfunction chunkFile(content: string, source: string): CollectionChunk[] {\n const lines = content.split('\\n');\n const chunks: CollectionChunk[] = [];\n let currentLines: string[] = [];\n let currentStart = 1;\n\n const flush = () => {\n const text = currentLines.join('\\n').trim();\n if (text.length > 0) {\n chunks.push({ source, startLine: currentStart, text, score: 0 });\n }\n currentLines = [];\n };\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n // Split on markdown headings\n if (/^#{1,4}\\s/.test(line) && currentLines.length > 0) {\n flush();\n currentStart = i + 1;\n }\n currentLines.push(line);\n\n // Also split on large paragraphs (every ~40 lines if no heading)\n if (currentLines.length >= 40 && !/^#{1,4}\\s/.test(line)) {\n flush();\n currentStart = i + 2;\n }\n }\n flush();\n return chunks;\n}\n\n// ---------------------------------------------------------------------------\n// Walk & Index\n// ---------------------------------------------------------------------------\n\nasync function walkDocs(rootDir: string, includeCode = false): Promise<string[]> {\n const files: string[] = [];\n\n async function walk(dir: string) {\n let entries: string[];\n try {\n entries = await readdir(dir);\n } catch {\n return;\n }\n for (const entry of entries) {\n if (IGNORED_DIRS.has(entry)) continue;\n const fullPath = join(dir, entry);\n let st;\n try {\n st = await stat(fullPath);\n } catch {\n continue;\n }\n if (st.isDirectory()) {\n await walk(fullPath);\n } else {\n const ext = extname(entry).toLowerCase();\n if (DOC_EXTENSIONS.has(ext) || (includeCode && CODE_EXTENSIONS.has(ext))) {\n files.push(fullPath);\n }\n }\n }\n }\n\n await walk(rootDir);\n return files;\n}\n\nexport async function buildCollectionIndex(\n paths: string[],\n options: BuildCollectionOptions = {}\n): Promise<CollectionIndex> {\n const allChunks: CollectionChunk[] = [];\n const roots = paths.map(p => resolve(p));\n let fileCount = 0;\n\n for (const rootPath of roots) {\n let st;\n try {\n st = await stat(rootPath);\n } catch {\n continue;\n }\n\n const files = st.isDirectory() ? await walkDocs(rootPath, Boolean(options.includeCode)) : [rootPath];\n\n for (const file of files) {\n let content: string;\n try {\n content = await readFile(file, 'utf8');\n } catch {\n continue;\n }\n fileCount++;\n const rel = relative(resolve(rootPath, st.isDirectory() ? '.' : '..'), file);\n const chunks = chunkFile(content, rel);\n allChunks.push(...chunks);\n }\n }\n\n // Build inverted term index\n const terms = new Map<string, Set<number>>();\n for (let i = 0; i < allChunks.length; i++) {\n const tokens = tokenize(allChunks[i].text);\n for (const token of tokens) {\n if (!terms.has(token)) terms.set(token, new Set());\n terms.get(token)!.add(i);\n }\n }\n\n return {\n root: roots[0] || '.',\n fileCount,\n chunkCount: allChunks.length,\n terms,\n chunks: allChunks\n };\n}\n\n// ---------------------------------------------------------------------------\n// Search\n// ---------------------------------------------------------------------------\n\nexport function searchCollection(\n index: CollectionIndex,\n query: string,\n maxResults = 10\n): SearchResult {\n const queryTokens = tokenize(query);\n if (queryTokens.length === 0) {\n return { query, hits: [], totalChunks: index.chunkCount };\n }\n\n // Score each chunk by number of matching query terms + term rarity (IDF-like)\n const scores = new Float64Array(index.chunkCount);\n\n for (const token of queryTokens) {\n const matchingChunks = index.terms.get(token);\n if (!matchingChunks) continue;\n // IDF-like weight: rarer terms score higher\n const idf = Math.log(1 + index.chunkCount / matchingChunks.size);\n for (const idx of matchingChunks) {\n scores[idx] += idf;\n }\n }\n\n // Collect non-zero scores\n const candidates: Array<{ idx: number; score: number }> = [];\n for (let i = 0; i < scores.length; i++) {\n if (scores[i] > 0) {\n candidates.push({ idx: i, score: scores[i] });\n }\n }\n\n // Sort descending by score\n candidates.sort((a, b) => b.score - a.score);\n\n const queryVector = toHashedVector(query);\n const maxTfidf = candidates.length > 0 ? candidates[0].score : 1;\n const tfidfWeight = 0.7;\n const vectorWeight = 0.3;\n\n const hybrid = candidates.map(c => {\n const chunk = index.chunks[c.idx];\n const chunkVector = toHashedVector(chunk.text);\n const cosine = Math.max(0, cosineSimilarity(queryVector, chunkVector));\n const tfidfNorm = maxTfidf > 0 ? (c.score / maxTfidf) : 0;\n const hybridScore = (tfidfNorm * tfidfWeight) + (cosine * vectorWeight);\n return { idx: c.idx, score: hybridScore };\n });\n\n hybrid.sort((a, b) => b.score - a.score);\n\n const hits = hybrid.slice(0, maxResults).map(c => ({\n ...index.chunks[c.idx],\n score: Math.round(c.score * 1000) / 1000\n }));\n\n return { query, hits, totalChunks: index.chunkCount };\n}\n", "/**\n * Agentic L3 Executor v2 \u2014 10/10 competitive CLI engine\n *\n * Features:\n * - 34+ tools via GeminiToolAdapter (LSP, git, web, memory, tracker, etc.)\n * - Streaming output \u2014 real-time token display as LLM generates\n * - JIT context discovery \u2014 files discovered by tools are indexed for next turn\n * - Turn compression \u2014 Topic-Action-Summary keeps prompts lean on long sessions\n * - Multi-model routing \u2014 cheap models for simple tasks, heavy for complex\n * - Auto-retry \u2014 failed tool calls retry up to 3 times with correction\n * - Repo-map context \u2014 TF-IDF semantic search injected before execution\n */\n\nimport type { AutonomousResult, TurnResult } from '../worker/autonomous-loop.js';\nimport type { ToolDeclaration } from '../tools/base.js';\nimport type { Sandbox } from '../sandbox/index.js';\nimport { executeAutonomous } from '../worker/autonomous-loop.js';\nimport { GeminiToolAdapter } from '../tools/gemini/crew-adapter.js';\nimport {\n openAICompatibleTurn,\n anthropicTurn,\n type LLMTurnResult\n} from './multi-turn-drivers.js';\nimport { CorrectionStore } from '../learning/corrections.js';\n\n// ---------------------------------------------------------------------------\n// System prompt\n// ---------------------------------------------------------------------------\n\n// Repair common JSON quirks from provider tool call responses\nfunction repairJson(raw: string): string {\n if (!raw || raw.trim() === '') return '{}';\n let s = raw.trim();\n // Remove trailing commas before } or ]\n s = s.replace(/,\\s*([}\\]])/g, '$1');\n // Fix single quotes to double quotes (but not inside strings)\n if (!s.includes('\"') && s.includes(\"'\")) {\n s = s.replace(/'/g, '\"');\n }\n // Fix unquoted keys: { key: \"value\" } \u2192 { \"key\": \"value\" }\n s = s.replace(/([{,])\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*:/g, '$1\"$2\":');\n // Handle truncated JSON from streaming \u2014 close open braces/brackets\n const openBraces = (s.match(/{/g) || []).length;\n const closeBraces = (s.match(/}/g) || []).length;\n for (let i = 0; i < openBraces - closeBraces; i++) s += '}';\n const openBrackets = (s.match(/\\[/g) || []).length;\n const closeBrackets = (s.match(/]/g) || []).length;\n for (let i = 0; i < openBrackets - closeBrackets; i++) s += ']';\n return s;\n}\n\nconst L3_SYSTEM_PROMPT = `You are a senior AI engineer executing coding tasks autonomously.\n\n## Cognitive Loop: THINK \u2192 ACT \u2192 OBSERVE\n\nEvery turn, follow this exact pattern:\n\n**THINK** (internal reasoning, 1-3 sentences):\n- What is the current state? What do I know from previous tool results?\n- What is the minimal next action to make progress?\n- Am I done? If so, summarize and stop.\n\n**ACT** (one or more tool calls):\n- Choose the most targeted tool for the job.\n- Prefer small, verifiable steps over large changes.\n- When multiple independent lookups are needed, call multiple tools in parallel.\n\n**OBSERVE** (after tools return):\n- Did the tool succeed or fail? What does the output tell me?\n- Do I need to adjust my approach?\n\n## Operating Principles\n\n- Match the request. Do what was asked \u2014 nothing more. A bug fix is just a bug fix. Don't refactor adjacent code, add docstrings to unchanged functions, or suggest rewrites beyond the task scope.\n- Simplest approach first. Don't over-engineer. Three similar lines are better than a premature abstraction. Only add error handling, validation, or fallbacks at system boundaries (user input, external APIs), not for internal guarantees.\n- Own mistakes. If a tool call fails or your approach is wrong, say so briefly and try a different approach. Don't repeat the same failing action. If the same failure pattern repeats twice, switch strategy.\n- Be security-conscious. Don't introduce injection, XSS, or hardcoded secrets. Validate at trust boundaries.\n\n## Available Tools\n\n**Files**: read_file, write_file, replace (edit with replace_all flag), read_many_files, glob, grep_search (output_mode: content/files/count, context, type filter), list_directory, mkdir\n**Shell**: run_shell_command (Docker isolation when staged files exist; run_in_background for long commands; configurable timeout via CREW_SHELL_TIMEOUT, default 120s, max 600s), check_background_task\n**Git**: git (status, diff, log, add, commit, show, branch, stash, tag, blame, checkout, fetch, pull, merge, rebase, cherry-pick, worktree \u2014 force-push and --no-verify blocked)\n**Web**: google_web_search, web_fetch\n**Memory**: save_memory (persist facts across sessions), write_todos\n**Docs**: get_internal_docs (read project documentation)\n**Agents**: spawn_agent (spawn autonomous sub-agent for independent subtasks \u2014 isolated sandbox branch, cheap model by default, merges changes on completion)\n\n## File Reading Strategy\n\n1. ALWAYS read a file before editing it. Never guess at file contents.\n2. For large files (500+ lines): read specific line ranges instead of the whole file.\n3. If a read_file result looks truncated, re-read with a narrower range around the area of interest.\n4. Use grep_search to locate exact strings before attempting replace/edit.\n\n## Edit Strategy\n\n1. ALWAYS read_file before editing. Edits on unread files will be rejected.\n2. Use replace (edit) for surgical changes \u2014 provide exact old_string that uniquely matches.\n3. Use replace_all:true when renaming a variable/function across the file.\n4. For new files, use write_file.\n5. Never rewrite an entire existing file \u2014 always use targeted edits.\n6. If an edit fails with \"not unique\", provide more surrounding context or use replace_all:true.\n7. If an edit fails with \"String not found\", re-read the file and retry with current content.\n\n## Shell Strategy\n\n1. For long-running commands (builds, tests, installs), use run_in_background:true.\n2. Use check_background_task to poll for results.\n3. Prefer dedicated tools over shell: use read_file not cat, grep_search not rg, glob not find.\n4. Never use destructive commands (rm -rf, git reset --hard) without explicit task instruction.\n\n## Verification\n\n1. After code changes: run the build command (usually \"npm run build\" or \"tsc --noEmit\").\n2. After logic changes: run relevant tests (\"npm test\", or specific test file).\n3. Check git diff to confirm only intended changes were made.\n\n## Output\n\n- Lead with what you did, not how you thought about it. Skip preamble.\n- For informational queries (listing files, reading code, checking status): include the actual tool output in your response so the user sees the data.\n- For code changes: concise summary of files modified, what changed, verification result.\n- When you used a tool to answer a question, show the results \u2014 don't just say \"I listed the files\" without showing them.\n\n## Stop Conditions \u2014 When to Finish\n\n- The task is fully complete and verified.\n- You have confirmed the changes work (via build, test, or diagnostic check).\n- Do NOT keep reading files or running tools after the work is done.\n- Do NOT repeat yourself or restate your work \u2014 just give a concise summary.\n\n## Anti-Patterns to Avoid\n\n- Do NOT read every file in the project to \"understand context\" \u2014 read only what's needed.\n- Do NOT make speculative changes to files you haven't read.\n- Do NOT run the same command twice if it already succeeded.\n- Do NOT apologize or explain failures at length \u2014 just fix them and move on.\n- Do NOT add features, refactor, or \"improve\" code beyond what the task asks.\n- Do NOT add comments, docstrings, or type annotations to code you didn't change.`;\n\n// ---------------------------------------------------------------------------\n// Corrections injection \u2014 load recent corrections to prevent repeat mistakes\n// ---------------------------------------------------------------------------\n\nasync function loadCorrectionsContext(projectDir: string): Promise<string> {\n try {\n const store = new CorrectionStore(projectDir);\n const entries = await store.loadAll();\n if (entries.length === 0) return '';\n\n // Take last 10 corrections (most recent = most relevant)\n const recent = entries.slice(-10);\n const lines = recent.map(c => {\n const tags = c.tags?.length ? ` [${c.tags.join(', ')}]` : '';\n return `- ${c.prompt.slice(0, 100)}${tags}: ${c.corrected.slice(0, 200)}`;\n });\n\n return `\\n\\n## Past Corrections (avoid repeating these mistakes)\\n${lines.join('\\n')}`;\n } catch {\n return ''; // No corrections file or parse error \u2014 non-fatal\n }\n}\n\n// ---------------------------------------------------------------------------\n// Turn Compression \u2014 Topic-Action-Summary model\n// ---------------------------------------------------------------------------\n\ninterface CompressedTurn {\n turn: number;\n topic: string; // what was being worked on\n action: string; // tool + brief params\n outcome: string; // success/fail + short result\n}\n\nfunction compressTurnHistory(history: TurnResult[]): CompressedTurn[] {\n return history.map(h => {\n const paramStr = JSON.stringify(h.params);\n // Extract the most important param (usually file_path, pattern, or command)\n const keyParam = h.params.file_path || h.params.pattern || h.params.command\n || h.params.query || h.params.path || h.params.dir_path || '';\n const action = `${h.tool}(${String(keyParam).slice(0, 80)})`;\n\n const isError = Boolean(h.error);\n const resultText = isError\n ? h.error!\n : (typeof h.result === 'object' && h.result && 'output' in h.result)\n ? String((h.result as any).output ?? '')\n : String(h.result ?? '');\n\n // Compress outcome to most useful info\n const outcome = isError\n ? `FAIL: ${resultText.slice(0, 120)}`\n : `OK: ${resultText.slice(0, 120)}`;\n\n // Infer topic from tool + params\n const topic = h.params.file_path\n ? String(h.params.file_path).split('/').pop() || 'file'\n : h.tool;\n\n return { turn: h.turn, topic, action, outcome };\n });\n}\n\n/** Format a tool result as a string, truncated for context */\nfunction formatToolResult(h: TurnResult, maxLen = 1500): string {\n const res = h.error\n ? `ERROR: ${h.error}`\n : (typeof h.result === 'object' && h.result && 'output' in h.result)\n ? String((h.result as { output?: string }).output ?? '')\n : String(h.result ?? '');\n return res.slice(0, maxLen);\n}\n\n/**\n * Convert TurnResult[] into provider-specific structured messages.\n * Each TurnResult becomes an assistant tool_call + user tool_result pair.\n * For long histories, middle turns are compressed to text summary while\n * the first 3 (initial context) and last 5 (recent work) use full structured format.\n */\nfunction historyToGeminiContents(history: TurnResult[]): any[] {\n if (history.length === 0) return [];\n const contents: any[] = [];\n\n // Selective compression: keep first 3 + last 5 detailed, compress only middle\n const firstN = 3;\n const lastN = 5;\n const needsCompression = history.length > firstN + lastN;\n const headDetailed = needsCompression ? history.slice(0, firstN) : [];\n const middleTurns = needsCompression ? history.slice(firstN, -lastN) : [];\n const structuredTurns = needsCompression ? history.slice(-lastN) : history;\n\n // Emit head turns (initial context) as full structured messages\n for (const h of headDetailed) {\n contents.push({\n role: 'model',\n parts: [{ functionCall: { name: h.tool, args: h.params } }]\n });\n const resultObj = h.error\n ? { error: h.error }\n : (typeof h.result === 'object' && h.result) ? h.result : { output: formatToolResult(h) };\n contents.push({\n role: 'user',\n parts: [{ functionResponse: { name: h.tool, response: resultObj } }]\n });\n }\n\n // Emit compressed summary of middle turns\n if (middleTurns.length > 0) {\n const compressed = compressTurnHistory(middleTurns);\n const summary = compressed.map(c => `[${c.turn}] ${c.action} \u2192 ${c.outcome}`).join('\\n');\n contents.push(\n { role: 'model', parts: [{ text: `[Earlier execution summary]\\n${summary}` }] },\n { role: 'user', parts: [{ text: 'Acknowledged. Continue with the task.' }] }\n );\n }\n\n for (const h of structuredTurns) {\n // Model made a tool call\n contents.push({\n role: 'model',\n parts: [{ functionCall: { name: h.tool, args: h.params } }]\n });\n // User provided tool result\n const resultObj = h.error\n ? { error: h.error }\n : (typeof h.result === 'object' && h.result) ? h.result : { output: formatToolResult(h) };\n contents.push({\n role: 'user',\n parts: [{ functionResponse: { name: h.tool, response: resultObj } }]\n });\n }\n return contents;\n}\n\nfunction historyToOpenAIMessages(history: TurnResult[]): any[] {\n if (history.length === 0) return [];\n const messages: any[] = [];\n\n // Selective compression: keep first 3 + last 5 detailed, compress only middle\n const firstN = 3;\n const lastN = 5;\n const needsCompression = history.length > firstN + lastN;\n const headDetailed = needsCompression ? history.slice(0, firstN) : [];\n const middleTurns = needsCompression ? history.slice(firstN, -lastN) : [];\n const structuredTurns = needsCompression ? history.slice(-lastN) : history;\n\n // Emit head turns (initial context) as full structured messages\n for (const h of headDetailed) {\n const callId = `call_${h.turn}_${h.tool}`;\n messages.push({\n role: 'assistant',\n tool_calls: [{\n id: callId,\n type: 'function',\n function: { name: h.tool, arguments: JSON.stringify(h.params) }\n }]\n });\n messages.push({\n role: 'tool',\n tool_call_id: callId,\n content: formatToolResult(h)\n });\n }\n\n // Emit compressed summary of middle turns\n if (middleTurns.length > 0) {\n const compressed = compressTurnHistory(middleTurns);\n const summary = compressed.map(c => `[${c.turn}] ${c.action} \u2192 ${c.outcome}`).join('\\n');\n messages.push(\n { role: 'assistant', content: `[Earlier execution summary]\\n${summary}` },\n { role: 'user', content: 'Acknowledged. Continue with the task.' }\n );\n }\n\n for (const h of structuredTurns) {\n const callId = `call_${h.turn}_${h.tool}`;\n messages.push({\n role: 'assistant',\n tool_calls: [{\n id: callId,\n type: 'function',\n function: { name: h.tool, arguments: JSON.stringify(h.params) }\n }]\n });\n messages.push({\n role: 'tool',\n tool_call_id: callId,\n content: formatToolResult(h)\n });\n }\n return messages;\n}\n\nfunction historyToAnthropicMessages(history: TurnResult[]): any[] {\n if (history.length === 0) return [];\n const messages: any[] = [];\n\n // Selective compression: keep first 3 + last 5 detailed, compress only middle\n const firstN = 3;\n const lastN = 5;\n const needsCompression = history.length > firstN + lastN;\n const headDetailed = needsCompression ? history.slice(0, firstN) : [];\n const middleTurns = needsCompression ? history.slice(firstN, -lastN) : [];\n const structuredTurns = needsCompression ? history.slice(-lastN) : history;\n\n // Emit head turns (initial context) as full structured messages\n for (const h of headDetailed) {\n const useId = `tu_${h.turn}_${h.tool}`;\n messages.push({\n role: 'assistant',\n content: [{\n type: 'tool_use',\n id: useId,\n name: h.tool,\n input: h.params\n }]\n });\n messages.push({\n role: 'user',\n content: [{\n type: 'tool_result',\n tool_use_id: useId,\n content: formatToolResult(h)\n }]\n });\n }\n\n // Emit compressed summary of middle turns\n if (middleTurns.length > 0) {\n const compressed = compressTurnHistory(middleTurns);\n const summary = compressed.map(c => `[${c.turn}] ${c.action} \u2192 ${c.outcome}`).join('\\n');\n messages.push(\n { role: 'assistant', content: `[Earlier execution summary]\\n${summary}` },\n { role: 'user', content: 'Acknowledged. Continue with the task.' }\n );\n }\n\n for (const h of structuredTurns) {\n const useId = `tu_${h.turn}_${h.tool}`;\n messages.push({\n role: 'assistant',\n content: [{\n type: 'tool_use',\n id: useId,\n name: h.tool,\n input: h.params\n }]\n });\n messages.push({\n role: 'user',\n content: [{\n type: 'tool_result',\n tool_use_id: useId,\n content: formatToolResult(h)\n }]\n });\n }\n return messages;\n}\n\n/** Legacy text-based history for fallback (markers-only providers) */\nfunction historyToContext(history: TurnResult[]): string {\n if (history.length === 0) return '';\n\n // For short histories, use detailed format\n if (history.length <= 5) {\n const lines = history.map(h => {\n return `[Turn ${h.turn}] ${h.tool}(${JSON.stringify(h.params).slice(0, 200)}) \u2192 ${formatToolResult(h, 800)}`;\n });\n return '\\n\\nPrevious tool results:\\n' + lines.join('\\n');\n }\n\n // For longer histories, use compressed Topic-Action-Summary\n const compressed = compressTurnHistory(history);\n const recentDetailed = history.slice(-3); // Keep last 3 turns detailed\n const olderCompressed = compressed.slice(0, -3);\n\n let ctx = '\\n\\nExecution summary (compressed):\\n';\n ctx += olderCompressed.map(c =>\n `[${c.turn}] ${c.action} \u2192 ${c.outcome}`\n ).join('\\n');\n\n ctx += '\\n\\nRecent actions (detailed):\\n';\n ctx += recentDetailed.map(h => {\n return `[Turn ${h.turn}] ${h.tool}(${JSON.stringify(h.params).slice(0, 200)}) \u2192 ${formatToolResult(h, 800)}`;\n }).join('\\n');\n\n return ctx;\n}\n\n// ---------------------------------------------------------------------------\n// Multi-model routing \u2014 more providers, task-based selection\n// ---------------------------------------------------------------------------\n\ninterface ProviderEntry {\n id: string;\n envKey: string;\n model: string;\n driver: 'gemini' | 'openai' | 'anthropic' | 'openrouter';\n apiUrl?: string;\n modelPrefix?: string;\n tier: 'fast' | 'standard' | 'heavy'; // for complexity-based routing\n}\n\nconst PROVIDER_ORDER: ProviderEntry[] = [\n // Heavy tier \u2014 L2 brain (complex multi-file tasks, planning)\n { id: 'openai', envKey: 'OPENAI_API_KEY', model: 'gpt-4.1', driver: 'openai', apiUrl: 'https://api.openai.com/v1/chat/completions', modelPrefix: 'gpt', tier: 'heavy' },\n { id: 'anthropic', envKey: 'ANTHROPIC_API_KEY', model: 'claude-sonnet-4-20250514', driver: 'anthropic', modelPrefix: 'claude', tier: 'heavy' },\n { id: 'grok', envKey: 'XAI_API_KEY', model: 'grok-3-mini-beta', driver: 'openai', apiUrl: 'https://api.x.ai/v1/chat/completions', modelPrefix: 'grok', tier: 'heavy' },\n // Standard tier \u2014 L3 workers (execution, parallel tasks)\n { id: 'gemini', envKey: 'GEMINI_API_KEY', model: 'gemini-2.5-flash', driver: 'gemini', modelPrefix: 'gemini', tier: 'standard' },\n { id: 'gemini', envKey: 'GOOGLE_API_KEY', model: 'gemini-2.5-flash', driver: 'gemini', modelPrefix: 'gemini', tier: 'standard' },\n { id: 'deepseek', envKey: 'DEEPSEEK_API_KEY', model: 'deepseek-chat', driver: 'openai', apiUrl: 'https://api.deepseek.com/v1/chat/completions', modelPrefix: 'deepseek', tier: 'standard' },\n { id: 'kimi', envKey: 'MOONSHOT_API_KEY', model: 'moonshot-v1-128k', driver: 'openai', apiUrl: 'https://api.moonshot.cn/v1/chat/completions', modelPrefix: 'kimi', tier: 'standard' },\n // Fast tier \u2014 L1 routing (classification, cheap)\n { id: 'groq', envKey: 'GROQ_API_KEY', model: 'llama-3.3-70b-versatile', driver: 'openai', apiUrl: 'https://api.groq.com/openai/v1/chat/completions', modelPrefix: 'llama', tier: 'fast' },\n // Fallback \u2014 free tier\n { id: 'openrouter', envKey: 'OPENROUTER_API_KEY', model: 'google/gemini-2.0-flash-exp:free', driver: 'openrouter', apiUrl: 'https://openrouter.ai/api/v1/chat/completions', modelPrefix: 'openrouter', tier: 'standard' },\n // Additional providers (OpenAI-compatible, cheap workers)\n { id: 'together', envKey: 'TOGETHER_API_KEY', model: 'Qwen/Qwen3.5-397B-A17B', driver: 'openai', apiUrl: 'https://api.together.xyz/v1/chat/completions', modelPrefix: 'qwen', tier: 'standard' },\n { id: 'fireworks', envKey: 'FIREWORKS_API_KEY', model: 'accounts/fireworks/models/qwen3.5-397b-a17b', driver: 'openai', apiUrl: 'https://api.fireworks.ai/inference/v1/chat/completions', modelPrefix: 'fireworks', tier: 'standard' },\n];\n\nfunction resolveProvider(modelOverride?: string, preferTier?: string): { key: string; model: string; driver: string; apiUrl?: string; id: string } | null {\n const effectiveModel = (modelOverride || process.env.CREW_EXECUTION_MODEL || '').trim().toLowerCase();\n\n // If a specific model is requested, find the matching provider\n if (effectiveModel) {\n for (const p of PROVIDER_ORDER) {\n const key = process.env[p.envKey];\n if (!key || key.length < 5) continue;\n if (p.envKey === 'GOOGLE_API_KEY' && process.env.GEMINI_API_KEY) continue;\n if (p.modelPrefix && effectiveModel.includes(p.modelPrefix)) {\n return { key, model: modelOverride || process.env.CREW_EXECUTION_MODEL || p.model, driver: p.driver, apiUrl: p.apiUrl, id: p.id };\n }\n }\n }\n\n // Tier-based routing\n const targetTier = preferTier || 'standard';\n // Try preferred tier first, then fall back to any\n const tieredOrder = [\n ...PROVIDER_ORDER.filter(p => p.tier === targetTier),\n ...PROVIDER_ORDER.filter(p => p.tier !== targetTier)\n ];\n\n for (const p of tieredOrder) {\n const key = process.env[p.envKey];\n if (!key || key.length < 5) continue;\n if (p.envKey === 'GOOGLE_API_KEY' && process.env.GEMINI_API_KEY) continue;\n return { key, model: p.model, driver: p.driver, apiUrl: p.apiUrl, id: p.id };\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Streaming LLM turn \u2014 real-time token output\n// ---------------------------------------------------------------------------\n\n/** Image attachment for multimodal input */\nexport interface ImageAttachment {\n data: string; // base64-encoded image data\n mimeType: string; // e.g. 'image/png', 'image/jpeg'\n}\n\nasync function executeStreamingGeminiTurn(\n fullTask: string,\n tools: ToolDeclaration[],\n key: string,\n model: string,\n systemPrompt: string,\n stream: boolean,\n images?: ImageAttachment[],\n historyMessages?: any[]\n): Promise<LLMTurnResult> {\n const functionDeclarations = tools.map(t => ({\n name: t.name,\n description: t.description,\n parameters: t.parameters\n }));\n\n // Build user parts: text + optional images\n const userParts: any[] = [{ text: `${systemPrompt}\\n\\nTask:\\n${fullTask}` }];\n if (images?.length) {\n for (const img of images) {\n userParts.push({ inlineData: { mimeType: img.mimeType, data: img.data } });\n }\n }\n const contents: any[] = [\n { role: 'user', parts: userParts },\n // Insert structured history (tool call/result pairs)\n ...(historyMessages || []),\n // Continuation prompt if we have history\n ...(historyMessages?.length ? [{ role: 'user', parts: [{ text: 'Continue executing the task based on the results above.' }] }] : [])\n ];\n\n const endpoint = stream ? 'streamGenerateContent' : 'generateContent';\n const url = `https://generativelanguage.googleapis.com/v1beta/models/${model}:${endpoint}?key=${encodeURIComponent(key)}${stream ? '&alt=sse' : ''}`;\n\n const res = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n signal: AbortSignal.timeout(120000),\n body: JSON.stringify({\n contents,\n tools: [{ functionDeclarations }],\n generationConfig: { temperature: 0.3, maxOutputTokens: 8192 }\n })\n });\n\n if (!res.ok) {\n const err = await res.text();\n throw new Error(`Gemini API ${res.status}: ${err.slice(0, 300)}`);\n }\n\n if (stream && res.body) {\n // Parse SSE stream\n let fullText = '';\n const toolCalls: Array<{ tool: string; params: Record<string, any> }> = [];\n let totalCost = 0;\n\n const reader = res.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() || '';\n\n for (const line of lines) {\n if (!line.startsWith('data: ')) continue;\n const jsonStr = line.slice(6).trim();\n if (!jsonStr || jsonStr === '[DONE]') continue;\n\n try {\n const chunk = JSON.parse(jsonStr);\n const parts = chunk?.candidates?.[0]?.content?.parts ?? [];\n\n for (const part of parts) {\n if (part.text) {\n process.stdout.write(part.text);\n fullText += part.text;\n }\n if (part.functionCall) {\n toolCalls.push({\n tool: part.functionCall.name || '',\n params: part.functionCall.args || {}\n });\n }\n }\n\n // Accumulate usage\n const usage = chunk?.usageMetadata;\n if (usage) {\n totalCost = (usage.promptTokenCount || 0) * 0.075 / 1_000_000\n + (usage.candidatesTokenCount || 0) * 0.30 / 1_000_000;\n }\n } catch {\n // Skip malformed chunks\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n if (fullText) process.stdout.write('\\n');\n\n if (toolCalls.length > 0) {\n return { toolCalls, response: fullText, cost: totalCost };\n }\n return { response: fullText, status: 'COMPLETE', cost: totalCost };\n }\n\n // Non-streaming fallback\n const data = await res.json() as any;\n const parts = data?.candidates?.[0]?.content?.parts ?? [];\n const usage = data?.usageMetadata ?? {};\n const cost = (usage.promptTokenCount || 0) * 0.075 / 1_000_000 + (usage.candidatesTokenCount || 0) * 0.30 / 1_000_000;\n\n const toolCalls: Array<{ tool: string; params: Record<string, any> }> = [];\n for (const part of parts) {\n if (part.functionCall) {\n toolCalls.push({ tool: part.functionCall.name || '', params: part.functionCall.args || {} });\n }\n }\n\n if (toolCalls.length > 0) return { toolCalls, response: '', cost };\n\n const textPart = parts.find((p: any) => p.text);\n return { response: textPart?.text ?? '', status: 'COMPLETE', cost };\n}\n\nasync function executeStreamingOpenAITurn(\n fullTask: string,\n tools: ToolDeclaration[],\n apiUrl: string,\n apiKey: string,\n model: string,\n systemPrompt: string,\n stream: boolean,\n images?: ImageAttachment[],\n historyMessages?: any[]\n): Promise<LLMTurnResult> {\n // Build user content: text + optional images as content array\n let userContent: any = fullTask;\n if (images?.length) {\n const parts: any[] = [{ type: 'text', text: fullTask }];\n for (const img of images) {\n parts.push({\n type: 'image_url',\n image_url: { url: `data:${img.mimeType};base64,${img.data}` }\n });\n }\n userContent = parts;\n }\n const messages = [\n { role: 'system', content: systemPrompt },\n { role: 'user', content: userContent },\n // Insert structured history (assistant tool_calls + tool results)\n ...(historyMessages || [])\n ];\n\n const openaiTools = tools.map(t => ({\n type: 'function' as const,\n function: { name: t.name, description: t.description, parameters: t.parameters }\n }));\n\n // GPT-5/6 only support temperature=1; other values cause 400\n const temp = (model?.startsWith?.('gpt-5') || model?.startsWith?.('gpt-6')) ? 1 : 0.3;\n const body: any = {\n model,\n messages,\n tools: openaiTools,\n temperature: temp,\n max_tokens: 8192,\n stream\n };\n\n const res = await fetch(apiUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${apiKey}`\n },\n signal: AbortSignal.timeout(120000),\n body: JSON.stringify(body)\n });\n\n if (!res.ok) {\n const err = await res.text();\n throw new Error(`OpenAI API ${res.status}: ${err.slice(0, 300)}`);\n }\n\n if (stream && res.body) {\n let fullText = '';\n const toolCallAccumulator = new Map<number, { name: string; args: string }>();\n\n const reader = res.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() || '';\n\n for (const line of lines) {\n if (!line.startsWith('data: ')) continue;\n const jsonStr = line.slice(6).trim();\n if (!jsonStr || jsonStr === '[DONE]') continue;\n\n try {\n const chunk = JSON.parse(jsonStr);\n const delta = chunk?.choices?.[0]?.delta;\n if (!delta) continue;\n\n // Stream text content\n if (delta.content) {\n process.stdout.write(delta.content);\n fullText += delta.content;\n }\n\n // Accumulate tool calls (streamed in pieces)\n if (delta.tool_calls) {\n for (const tc of delta.tool_calls) {\n const idx = tc.index ?? 0;\n if (!toolCallAccumulator.has(idx)) {\n toolCallAccumulator.set(idx, { name: '', args: '' });\n }\n const acc = toolCallAccumulator.get(idx)!;\n if (tc.function?.name) acc.name += tc.function.name;\n if (tc.function?.arguments) acc.args += tc.function.arguments;\n }\n }\n } catch {\n // Skip malformed chunks\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n if (fullText) process.stdout.write('\\n');\n\n // Parse accumulated tool calls\n const toolCalls: Array<{ tool: string; params: Record<string, any> }> = [];\n for (const [, tc] of toolCallAccumulator) {\n if (tc.name) {\n let params = {};\n try { params = JSON.parse(repairJson(tc.args)); } catch {}\n toolCalls.push({ tool: tc.name, params });\n }\n }\n\n if (toolCalls.length > 0) return { toolCalls, response: fullText, cost: 0 };\n return { response: fullText, status: 'COMPLETE', cost: 0 };\n }\n\n // Non-streaming fallback to multi-turn-drivers\n // (this path shouldn't be hit normally since we always stream)\n const data = await res.json() as any;\n const choice = data?.choices?.[0];\n const msg = choice?.message;\n\n if (msg?.tool_calls?.length > 0) {\n const toolCalls = msg.tool_calls.map((tc: any) => {\n let params = {};\n try { params = JSON.parse(repairJson(tc.function?.arguments || '{}')); } catch {}\n return { tool: tc.function?.name || '', params };\n });\n return { toolCalls, response: msg?.content || '', cost: 0 };\n }\n\n return { response: msg?.content || '', status: 'COMPLETE', cost: 0 };\n}\n\nasync function executeStreamingAnthropicTurn(\n fullTask: string,\n tools: ToolDeclaration[],\n apiKey: string,\n model: string,\n systemPrompt: string,\n stream: boolean,\n images?: ImageAttachment[],\n historyMessages?: any[]\n): Promise<LLMTurnResult> {\n // Build user content: text + optional images\n let userContent: any = fullTask;\n if (images?.length) {\n const parts: any[] = [{ type: 'text', text: fullTask }];\n for (const img of images) {\n parts.push({\n type: 'image',\n source: { type: 'base64', media_type: img.mimeType, data: img.data }\n });\n }\n userContent = parts;\n }\n\n const anthropicTools = tools.map(t => ({\n name: t.name,\n description: t.description,\n input_schema: t.parameters\n }));\n\n const body: any = {\n model,\n max_tokens: 8192,\n system: systemPrompt,\n messages: [\n { role: 'user', content: userContent },\n // Insert structured history (assistant tool_use + user tool_result)\n ...(historyMessages || [])\n ],\n temperature: 0.3,\n tools: anthropicTools,\n stream\n };\n\n const res = await fetch('https://api.anthropic.com/v1/messages', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-api-key': apiKey,\n 'anthropic-version': '2023-06-01'\n },\n signal: AbortSignal.timeout(120000),\n body: JSON.stringify(body)\n });\n\n if (!res.ok) {\n const err = await res.text();\n throw new Error(`Anthropic API ${res.status}: ${err.slice(0, 300)}`);\n }\n\n if (stream && res.body) {\n let fullText = '';\n const toolBlocks = new Map<number, { name: string; inputJson: string }>();\n let totalCost = 0;\n\n const reader = res.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() || '';\n\n for (const line of lines) {\n if (!line.startsWith('data: ')) continue;\n const jsonStr = line.slice(6).trim();\n if (!jsonStr) continue;\n\n try {\n const event = JSON.parse(jsonStr);\n\n if (event.type === 'content_block_start') {\n if (event.content_block?.type === 'tool_use') {\n toolBlocks.set(event.index, {\n name: event.content_block.name || '',\n inputJson: ''\n });\n }\n }\n\n if (event.type === 'content_block_delta') {\n if (event.delta?.type === 'text_delta' && event.delta.text) {\n process.stdout.write(event.delta.text);\n fullText += event.delta.text;\n }\n if (event.delta?.type === 'input_json_delta' && event.delta.partial_json) {\n const block = toolBlocks.get(event.index);\n if (block) block.inputJson += event.delta.partial_json;\n }\n }\n\n if (event.type === 'message_delta' && event.usage) {\n totalCost = (event.usage.input_tokens || 0) * 3 / 1_000_000\n + (event.usage.output_tokens || 0) * 15 / 1_000_000;\n }\n } catch {\n // Skip malformed events\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n if (fullText) process.stdout.write('\\n');\n\n // Parse accumulated tool calls\n const toolCalls: Array<{ tool: string; params: Record<string, any> }> = [];\n for (const [, block] of toolBlocks) {\n if (block.name) {\n let params = {};\n try { params = JSON.parse(repairJson(block.inputJson)); } catch {}\n toolCalls.push({ tool: block.name, params });\n }\n }\n\n if (toolCalls.length > 0) return { toolCalls, response: fullText, cost: totalCost };\n return { response: fullText, status: 'COMPLETE', cost: totalCost };\n }\n\n // Non-streaming fallback\n const data = await res.json() as any;\n const usage = data?.usage || {};\n const cost = (usage.input_tokens || 0) * 3 / 1_000_000 + (usage.output_tokens || 0) * 15 / 1_000_000;\n const content = data?.content || [];\n const toolUseBlocks = content.filter((b: any) => b.type === 'tool_use');\n const textBlocks = content.filter((b: any) => b.type === 'text');\n const textResponse = textBlocks.map((b: any) => b.text).join('\\n');\n\n if (toolUseBlocks.length > 0) {\n const toolCalls = toolUseBlocks.map((b: any) => ({ tool: b.name, params: b.input || {} }));\n return { toolCalls, response: textResponse, cost };\n }\n return { response: textResponse, status: 'COMPLETE', cost };\n}\n\nasync function executeLLMTurn(\n task: string,\n tools: ToolDeclaration[],\n history: TurnResult[],\n model: string,\n systemPrompt: string,\n stream: boolean,\n images?: ImageAttachment[]\n): Promise<LLMTurnResult> {\n const resolved = resolveProvider(model);\n if (!resolved) {\n throw new Error(\n 'No LLM providers available. Set at least one API key:\\n' +\n ' \u2192 GEMINI_API_KEY (free tier \u2014 https://aistudio.google.com/apikey)\\n' +\n ' \u2192 GROQ_API_KEY (free \u2014 https://console.groq.com/keys)\\n' +\n ' \u2192 XAI_API_KEY ($5/mo free credits \u2014 https://console.x.ai)\\n' +\n 'Or any of: OPENAI_API_KEY, ANTHROPIC_API_KEY, DEEPSEEK_API_KEY, OPENROUTER_API_KEY\\n' +\n 'Run \"crew doctor\" to check your setup.'\n );\n }\n\n const { key, model: effectiveModel, driver, apiUrl, id } = resolved;\n\n // Gemini: structured multi-turn with functionCall/functionResponse\n if (driver === 'gemini') {\n const historyMsgs = historyToGeminiContents(history);\n return executeStreamingGeminiTurn(task, tools, key, effectiveModel, systemPrompt, stream, images, historyMsgs);\n }\n\n // Anthropic: structured multi-turn with tool_use/tool_result\n if (driver === 'anthropic') {\n const historyMsgs = historyToAnthropicMessages(history);\n return executeStreamingAnthropicTurn(task, tools, key, effectiveModel, systemPrompt, stream, images, historyMsgs);\n }\n\n // OpenAI-compatible: structured multi-turn with tool_calls/tool messages\n if (driver === 'openai' || driver === 'openrouter') {\n const historyMsgs = historyToOpenAIMessages(history);\n return executeStreamingOpenAITurn(task, tools, apiUrl!, key, effectiveModel, systemPrompt, stream, images, historyMsgs);\n }\n\n throw new Error(`Unsupported driver: ${driver}`);\n}\n\n// ---------------------------------------------------------------------------\n// JIT Context Discovery \u2014 index files as tools discover them\n// ---------------------------------------------------------------------------\n\nclass JITContextTracker {\n private discoveredFiles = new Set<string>();\n private contextCache: string = '';\n\n /** Hydrate from a prior session's discovered files */\n static fromPrior(files: string[]): JITContextTracker {\n const tracker = new JITContextTracker();\n for (const f of files) tracker.discoveredFiles.add(f);\n return tracker;\n }\n\n /** Serialize discovered files for session persistence */\n toFileList(): string[] {\n return Array.from(this.discoveredFiles);\n }\n\n /** Track a file that was read/written/grepped during tool execution */\n trackFile(filePath: string) {\n if (filePath && !this.discoveredFiles.has(filePath)) {\n this.discoveredFiles.add(filePath);\n }\n }\n\n /** Extract file paths from tool calls and results */\n trackFromToolResult(toolName: string, params: Record<string, any>, result: any) {\n // Track files referenced in tool params\n for (const key of ['file_path', 'path', 'dir_path']) {\n if (params[key]) this.trackFile(String(params[key]));\n }\n\n // Track files discovered by glob/grep results\n if ((toolName === 'glob' || toolName === 'grep_search' || toolName === 'grep_search_ripgrep') && result?.output) {\n const lines = String(result.output).split('\\n');\n for (const line of lines) {\n const match = line.match(/^([^\\s:]+\\.[a-zA-Z]+)/);\n if (match) this.trackFile(match[1]);\n }\n }\n\n // Track files from list_directory\n if (toolName === 'list_directory' && result?.output) {\n const lines = String(result.output).split('\\n');\n const dir = params.dir_path || params.path || '.';\n for (const line of lines) {\n const match = line.match(/^[fd]\\s+(.+)/);\n if (match && match[1].includes('.')) {\n this.trackFile(`${dir}/${match[1]}`);\n }\n }\n }\n }\n\n /** Build enriched context from discovered files for next turn */\n async buildJITContext(projectDir: string): Promise<string> {\n if (this.discoveredFiles.size === 0) return '';\n\n try {\n const { buildCollectionIndex, searchCollection } = await import('../collections/index.js');\n\n // Index only the discovered files/directories\n const uniqueDirs = new Set<string>();\n for (const f of this.discoveredFiles) {\n const parts = f.split('/');\n if (parts.length > 1) {\n uniqueDirs.add(parts.slice(0, -1).join('/'));\n }\n }\n\n // If we've discovered specific directories, search them\n const dirsToIndex = Array.from(uniqueDirs).slice(0, 5);\n if (dirsToIndex.length === 0) return '';\n\n const { resolve: resolvePath } = await import('node:path');\n const paths = dirsToIndex.map(d => resolvePath(projectDir, d));\n\n const index = await buildCollectionIndex(paths, { includeCode: true });\n if (index.chunkCount === 0) return '';\n\n // Search for related patterns based on discovered file names\n const query = Array.from(this.discoveredFiles).slice(0, 10).join(' ');\n const results = searchCollection(index, query, 3);\n if (results.hits.length === 0) return '';\n\n const newContext = results.hits.map(h =>\n `--- JIT: ${h.source}:${h.startLine} ---\\n${h.text.slice(0, 400)}`\n ).join('\\n\\n');\n\n this.contextCache = newContext;\n return `\\n\\nJIT-discovered context:\\n${newContext}`;\n } catch {\n return '';\n }\n }\n\n get fileCount() { return this.discoveredFiles.size; }\n}\n\n// ---------------------------------------------------------------------------\n// Repo-map context builder\n// ---------------------------------------------------------------------------\n\nasync function buildRepoMapContext(task: string, projectDir: string): Promise<string> {\n try {\n const { buildCollectionIndex, searchCollection } = await import('../collections/index.js');\n const index = await buildCollectionIndex([projectDir], { includeCode: true });\n if (index.chunkCount === 0) return '';\n\n const results = searchCollection(index, task, 5);\n if (results.hits.length === 0) return '';\n\n const chunks = results.hits.map(h =>\n `--- ${h.source}:${h.startLine} (score: ${h.score}) ---\\n${h.text.slice(0, 600)}`\n );\n return `\\n\\nRelevant codebase context (${index.fileCount} files indexed, ${index.chunkCount} chunks):\\n${chunks.join('\\n\\n')}`;\n } catch {\n return '';\n }\n}\n\n// ---------------------------------------------------------------------------\n// Auto-retry wrapper\n// ---------------------------------------------------------------------------\n\nconst MAX_RETRIES = 3;\n\nasync function executeToolWithRetry(\n adapter: GeminiToolAdapter,\n name: string,\n params: Record<string, any>,\n verbose: boolean\n): Promise<{ output: string; success: boolean; error?: string }> {\n for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {\n const result = await adapter.executeTool(name, params);\n if (result.success) {\n return { output: result.output ?? '', success: true };\n }\n\n // If first attempt failed and we have retries left, try with corrections\n if (attempt < MAX_RETRIES) {\n if (verbose) {\n console.log(` \u27F3 Retry ${attempt}/${MAX_RETRIES - 1} for ${name}: ${(result.error || '').slice(0, 80)}`);\n }\n\n // Auto-correct common errors\n if (result.error?.includes('String not found') && params.old_string) {\n // Edge case fix: re-read the file to get fresh content before retrying\n if (params.file_path) {\n try {\n const freshRead = await adapter.executeTool('read_file', { file_path: params.file_path });\n if (freshRead.success && freshRead.output) {\n // Return the fresh content as error context so the LLM can see it on next turn\n return {\n output: `File content has changed. Current content of ${params.file_path}:\\n${freshRead.output.slice(0, 3000)}`,\n success: false,\n error: `String not found in ${params.file_path}. File was re-read \u2014 content returned above for correction.`\n };\n }\n } catch { /* fall through to trim retry */ }\n }\n // Fallback: try trimming whitespace\n params.old_string = params.old_string.trim();\n } else if (result.error?.includes('No such file') && params.file_path) {\n // For file ops: try without leading ./\n params.file_path = params.file_path.replace(/^\\.\\//, '');\n } else {\n // No auto-correction available, don't retry\n return { output: result.output ?? '', success: false, error: result.error };\n }\n } else {\n return { output: result.output ?? '', success: false, error: result.error };\n }\n }\n\n return { output: '', success: false, error: 'Max retries exceeded' };\n}\n\n// ---------------------------------------------------------------------------\n// Main executor\n// ---------------------------------------------------------------------------\n\nexport interface AgenticExecutorResult {\n success: boolean;\n output: string;\n cost: number;\n turns?: number;\n toolsUsed?: string[];\n providerId?: string;\n modelUsed?: string;\n filesDiscovered?: number;\n discoveredFiles?: string[];\n history?: TurnResult[];\n stopReason?: string;\n}\n\nexport async function runAgenticWorker(\n task: string,\n sandbox: Sandbox,\n options: {\n systemPrompt?: string;\n model?: string;\n maxTurns?: number;\n projectDir?: string;\n verbose?: boolean;\n stream?: boolean;\n tier?: 'fast' | 'standard' | 'heavy';\n images?: ImageAttachment[];\n onToolCall?: (name: string, params: Record<string, any>) => void;\n priorDiscoveredFiles?: string[];\n } = {}\n): Promise<AgenticExecutorResult> {\n const adapter = new GeminiToolAdapter(sandbox);\n const allTools = adapter.getToolDeclarations() as ToolDeclaration[];\n const systemPrompt = options.systemPrompt || L3_SYSTEM_PROMPT;\n const model = options.model || process.env.CREW_EXECUTION_MODEL || '';\n const maxTurns = options.maxTurns ?? 25;\n const projectDir = options.projectDir || (sandbox as any).baseDir || process.cwd();\n const verbose = options.verbose ?? Boolean(process.env.CREW_DEBUG);\n const stream = options.stream ?? !process.env.CREW_NO_STREAM; // Stream by default\n const jit = options.priorDiscoveredFiles?.length\n ? JITContextTracker.fromPrior(options.priorDiscoveredFiles)\n : new JITContextTracker();\n\n // Resolve provider early to report which model/provider is being used\n const resolvedProvider = resolveProvider(model, options.tier);\n\n if (verbose) {\n const prov = resolvedProvider ? `${resolvedProvider.id}/${resolvedProvider.model}` : 'none';\n console.log(`[AgenticExecutor] Provider: ${prov} | Stream: ${stream} | Tools: ${allTools.length}`);\n }\n\n // Inject repo-map context\n let enrichedTask = task;\n try {\n const repoContext = await buildRepoMapContext(task, projectDir);\n if (repoContext) {\n enrichedTask = `${task}${repoContext}`;\n if (verbose) {\n console.log(`[AgenticExecutor] Repo-map: ${repoContext.length} chars injected`);\n }\n }\n } catch {\n // Non-fatal\n }\n\n // Inject past corrections to prevent repeat mistakes\n try {\n const correctionsContext = await loadCorrectionsContext(projectDir);\n if (correctionsContext) {\n enrichedTask = `${enrichedTask}${correctionsContext}`;\n if (verbose) {\n console.log(`[AgenticExecutor] Corrections context injected`);\n }\n }\n } catch {\n // Non-fatal\n }\n\n if (verbose) {\n console.log(`[AgenticExecutor] ${allTools.length} tools: ${allTools.map(t => t.name).join(', ')}`);\n }\n\n let totalCost = 0;\n const toolsUsed = new Set<string>();\n\n const executeTool = async (name: string, params: Record<string, any>) => {\n toolsUsed.add(name);\n\n // Always fire onToolCall callback (for REPL tool progress display)\n options.onToolCall?.(name, params);\n\n if (verbose) {\n const paramStr = JSON.stringify(params).slice(0, 120);\n process.stdout.write(` \uD83D\uDD27 ${name}(${paramStr})...`);\n }\n\n const result = await executeToolWithRetry(adapter, name, params, verbose);\n\n // Auto-pagination: if read_file result looks truncated, hint for narrower read\n if (name === 'read_file' && result.success && result.output) {\n const outputLen = result.output.length;\n if (outputLen > 8000 && (result.output.includes('... (truncated)') || result.output.includes('content truncated'))) {\n result.output += '\\n\\n[NOTE: File output was truncated. Use line_start and line_end parameters to read specific sections.]';\n }\n }\n\n // JIT: track discovered files\n jit.trackFromToolResult(name, params, result);\n\n if (verbose) {\n const status = result.success ? '\u2713' : '\u2717';\n const preview = (result.output || result.error || '').slice(0, 80).replace(/\\n/g, ' ');\n console.log(` ${status} ${preview}`);\n }\n return result;\n };\n\n let turnCount = 0;\n\n const result: AutonomousResult = await executeAutonomous(\n enrichedTask,\n async (prompt, tools, history) => {\n turnCount++;\n\n // JIT: inject discovered context every 3 turns\n let taskWithJIT = enrichedTask;\n if (turnCount > 1 && turnCount % 3 === 0 && jit.fileCount > 0) {\n try {\n const jitContext = await jit.buildJITContext(projectDir);\n if (jitContext) {\n taskWithJIT = `${enrichedTask}${jitContext}`;\n if (verbose) {\n console.log(` [JIT] Injected context from ${jit.fileCount} discovered files`);\n }\n }\n } catch {\n // Non-fatal\n }\n }\n\n // Only inject images on the first turn to avoid context bloat\n const turnImages = turnCount === 1 ? options.images : undefined;\n const turnResult = await executeLLMTurn(taskWithJIT, allTools, history, model, systemPrompt, stream, turnImages);\n totalCost += turnResult.cost || 0;\n return {\n toolCalls: turnResult.toolCalls,\n response: turnResult.response,\n status: turnResult.status\n };\n },\n async (name, params) => {\n return await executeTool(name, params);\n },\n {\n maxTurns,\n tools: allTools,\n onProgress: verbose\n ? (turn, action) => {\n console.log(` [Turn ${turn}] ${action}`);\n }\n : undefined\n }\n );\n\n return {\n success: result.success ?? false,\n output: result.finalResponse ?? result.history?.map(h => {\n if (!h.result) return '';\n if (typeof h.result === 'string') return h.result;\n return h.result.output || h.result.error || JSON.stringify(h.result);\n }).filter(Boolean).join('\\n') ?? '',\n cost: totalCost,\n turns: result.turns,\n toolsUsed: Array.from(toolsUsed),\n providerId: resolvedProvider?.id,\n modelUsed: resolvedProvider?.model,\n filesDiscovered: jit.fileCount,\n discoveredFiles: jit.toFileList(),\n history: result.history,\n stopReason: result.reason\n };\n}\n", "/**\n * Engine API \u2014 public exports for use by gateway-bridge.\n * This is the entry point that lib/engines/crew-cli.mjs imports.\n * Provides direct function access to the agentic executor without spawning subprocesses.\n */\nexport { runAgenticWorker } from './executor/agentic-executor.js';\nexport { Sandbox } from './sandbox/index.js';\n", "import { createTwoFilesPatch } from 'diff';\nimport { readFile, writeFile, mkdir, access } from 'node:fs/promises';\nimport { constants } from 'node:fs';\nimport { join, dirname } from 'node:path';\n\nexport interface SandboxChange {\n path: string;\n original: string;\n modified: string;\n timestamp: string;\n}\n\nexport interface SandboxState {\n updatedAt: string;\n activeBranch: string;\n branches: Record<string, Record<string, SandboxChange>>;\n}\n\nexport class Sandbox {\n private state: SandboxState = {\n updatedAt: new Date().toISOString(),\n activeBranch: 'main',\n branches: { main: {} }\n };\n protected baseDir: string; // Changed from private to protected\n private stateFilePath: string;\n\n constructor(baseDir = process.cwd()) {\n this.baseDir = baseDir;\n this.stateFilePath = join(baseDir, '.crew', 'sandbox.json');\n }\n\n private async exists(path: string): Promise<boolean> {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n }\n\n async load(): Promise<void> {\n if (await this.exists(this.stateFilePath)) {\n try {\n const data = await readFile(this.stateFilePath, 'utf8');\n const parsed = JSON.parse(data) as SandboxState;\n this.state = {\n ...this.state,\n ...parsed,\n branches: parsed.branches || { main: {} },\n activeBranch: parsed.activeBranch || 'main'\n };\n } catch (err) {\n console.error(`Failed to load sandbox state: ${(err as Error).message}`);\n }\n }\n }\n\n async persist(): Promise<void> {\n this.state.updatedAt = new Date().toISOString();\n const dir = dirname(this.stateFilePath);\n if (!(await this.exists(dir))) {\n await mkdir(dir, { recursive: true });\n }\n await writeFile(this.stateFilePath, JSON.stringify(this.state, null, 2), 'utf8');\n }\n\n /** Alias for persist() to match external API expectations */\n async save(): Promise<void> {\n await this.persist();\n }\n\n async addChange(filePath: string, modifiedContent: string): Promise<void> {\n const fullPath = join(this.baseDir, filePath);\n let original = '';\n\n // Ensure branch exists and is an object (not array)\n if (!this.state.branches[this.state.activeBranch] || Array.isArray(this.state.branches[this.state.activeBranch])) {\n // Fix malformed branch data silently\n this.state.branches[this.state.activeBranch] = {};\n }\n\n const activeChanges = this.state.branches[this.state.activeBranch];\n\n if (activeChanges[filePath]) {\n original = activeChanges[filePath].original;\n } else if (await this.exists(fullPath)) {\n original = await readFile(fullPath, 'utf8');\n }\n\n activeChanges[filePath] = {\n path: filePath,\n original,\n modified: modifiedContent,\n timestamp: new Date().toISOString()\n };\n \n\n await this.persist();\n }\n\n preview(branchName = this.state.activeBranch): string {\n const branch = this.state.branches[branchName];\n if (!branch) return `Branch \"${branchName}\" not found.`;\n\n let diff = '';\n for (const [path, change] of Object.entries(branch)) {\n diff += createTwoFilesPatch(\n `a/${path}`,\n `b/${path}`,\n change.original,\n change.modified,\n undefined,\n undefined,\n { context: 3 }\n );\n }\n return diff || 'No pending changes.';\n }\n\n async apply(branchName = this.state.activeBranch): Promise<void> {\n const branch = this.state.branches[branchName];\n if (!branch) throw new Error(`Branch \"${branchName}\" not found.`);\n\n for (const [path, change] of Object.entries(branch)) {\n const fullPath = join(this.baseDir, path);\n const dir = dirname(fullPath);\n if (!(await this.exists(dir))) {\n await mkdir(dir, { recursive: true });\n }\n await writeFile(fullPath, change.modified, 'utf8');\n }\n await this.rollback(branchName);\n }\n\n async rollback(branchName = this.state.activeBranch): Promise<void> {\n if (this.state.branches[branchName]) {\n this.state.branches[branchName] = {};\n await this.persist();\n }\n }\n\n async createBranch(name: string, fromBranch = this.state.activeBranch): Promise<void> {\n if (this.state.branches[name]) {\n throw new Error(`Branch \"${name}\" already exists.`);\n }\n // Deep copy current changes from fromBranch\n const sourceBranch = this.state.branches[fromBranch] || {};\n this.state.branches[name] = JSON.parse(JSON.stringify(sourceBranch));\n this.state.activeBranch = name;\n await this.persist();\n }\n\n async switchBranch(name: string): Promise<void> {\n if (!this.state.branches[name]) {\n throw new Error(`Branch \"${name}\" does not exist.`);\n }\n this.state.activeBranch = name;\n await this.persist();\n }\n\n async deleteBranch(name: string): Promise<void> {\n if (name === 'main') throw new Error('Cannot delete main branch.');\n if (this.state.activeBranch === name) {\n this.state.activeBranch = 'main';\n }\n delete this.state.branches[name];\n await this.persist();\n }\n\n async mergeBranch(source: string, target = this.state.activeBranch): Promise<void> {\n if (!this.state.branches[source]) throw new Error(`Source branch \"${source}\" not found.`);\n if (!this.state.branches[target]) throw new Error(`Target branch \"${target}\" not found.`);\n\n const sourceChanges = this.state.branches[source];\n const targetChanges = this.state.branches[target];\n\n for (const [path, change] of Object.entries(sourceChanges)) {\n targetChanges[path] = JSON.parse(JSON.stringify(change));\n }\n\n await this.persist();\n }\n\n getActiveBranch(): string {\n return this.state.activeBranch;\n }\n\n getBranches(): string[] {\n return Object.keys(this.state.branches);\n }\n\n getPendingPaths(branchName = this.state.activeBranch): string[] {\n return Object.keys(this.state.branches[branchName] || {});\n }\n\n hasChanges(branchName = this.state.activeBranch): boolean {\n return Object.keys(this.state.branches[branchName] || {}).length > 0;\n }\n\n /**\n * Get staged content for a file path (returns undefined if not staged).\n * Used by tool adapter so agentic workers can read their own staged files.\n */\n getStagedContent(filePath: string, branchName = this.state.activeBranch): string | undefined {\n const branch = this.state.branches[branchName];\n if (!branch) return undefined;\n // Try both the raw path and normalized path\n const change = branch[filePath];\n if (change) return change.modified;\n return undefined;\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;AA0CA,eAAsB,kBACpB,MACA,YACA,aACA,QAC2B;AAC3B,QAAM,WAAW,OAAO,YAAY;AACpC,QAAM,kBAAkB,OAAO,mBAAmB;AAClD,QAAM,UAAwB,CAAC;AAE/B,MAAI,mBAAmB;AACvB,MAAI,aAAa;AAEjB,WAAS,OAAO,GAAG,OAAO,UAAU,QAAQ;AAC1C,WAAO,aAAa,OAAO,GAAG,UAAU;AAGxC,UAAM,WAAW,MAAM,WAAW,MAAM,OAAO,OAAO,OAAO;AAG7D,QAAI,SAAS,WAAW,cAAc,CAAC,SAAS,aAAa,SAAS,UAAU,WAAW,GAAG;AAC5F,aAAO;AAAA,QACL,SAAS;AAAA,QACT,OAAO,OAAO;AAAA,QACd;AAAA,QACA,eAAe,SAAS;AAAA,MAC1B;AAAA,IACF;AAGA,QAAI,SAAS,YAAY,SAAS,SAAS,SAAS,IAAI;AACtD,UAAI,SAAS,aAAa,kBAAkB;AAC1C;AACA,YAAI,cAAc,GAAG;AACnB,iBAAO;AAAA,YACL,SAAS;AAAA,YACT,OAAO,OAAO;AAAA,YACd;AAAA,YACA,eAAe,SAAS;AAAA,YACxB,QAAQ;AAAA,UACV;AAAA,QACF;AAAA,MACF,OAAO;AACL,qBAAa;AAAA,MACf;AACA,yBAAmB,SAAS;AAAA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M,SAAS,MAAM;AAEhD,eAAW,CAACM,OAAM,MAAM,KAAK,OAAO,QAAQ,aAAa,GAAG;AAC1D,oBAAcA,KAAI,IAAI,KAAK,MAAM,KAAK,UAAU,MAAM,CAAC;AAAA,IACzD;AAEA,UAAM,KAAK,QAAQ;AAAA,EACrB;AAAA,EAEA,kBAA0B;AACxB,WAAO,KAAK,MAAM;AAAA,EACpB;AAAA,EAEA,cAAwB;AACtB,WAAO,OAAO,KAAK,KAAK,MAAM,QAAQ;AAAA,EACxC;AAAA,EAEA,gBAAgB,aAAa,KAAK,MAAM,cAAwB;AAC9D,WAAO,OAAO,KAAK,KAAK,MAAM,SAAS,UAAU,KAAK,CAAC,CAAC;AAAA,EAC1D;AAAA,EAEA,WAAW,aAAa,KAAK,MAAM,cAAuB;AACxD,WAAO,OAAO,KAAK,KAAK,MAAM,SAAS,UAAU,KAAK,CAAC,CAAC,EAAE,SAAS;AAAA,EACrE;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,iBAAiB,UAAkB,aAAa,KAAK,MAAM,cAAkC;AAC3F,UAAM,SAAS,KAAK,MAAM,SAAS,UAAU;AAC7C,QAAI,CAAC,OAAQ,QAAO;AAEpB,UAAM,SAAS,OAAO,QAAQ;AAC9B,QAAI,OAAQ,QAAO,OAAO;AAC1B,WAAO;AAAA,EACT;AACF;",
6
+ "names": ["execSync", "resolve", "mkdir", "writeFile", "dirname", "updated", "diagnostics", "DockerSandbox", "runAgenticWorker", "mkdir", "readFile", "writeFile", "join", "path", "readdir", "readFile", "stat", "join", "resolve", "toolCalls", "parts", "usage", "buildCollectionIndex", "searchCollection", "result", "readFile", "writeFile", "mkdir", "access", "constants", "join", "dirname", "path"]
7
7
  }