@morphllm/morphsdk 0.2.200 → 0.2.202
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai-sdk/index.cjs +0 -1
- package/dist/ai-sdk/index.js +0 -1
- package/dist/{chunk-TIMDDHYB.js → chunk-26K5EJD3.js} +3 -4
- package/dist/{chunk-HYRHI2UL.js → chunk-2PPYWRMZ.js} +0 -1
- package/dist/{chunk-QTBFL4DG.js → chunk-2XU3XXUE.js} +2 -3
- package/dist/{chunk-MLROWLS6.js → chunk-3CPI6ZIC.js} +8 -9
- package/dist/{chunk-IA5K2HTC.js → chunk-44OIEPIO.js} +1 -2
- package/dist/{chunk-FBRNUWEB.js → chunk-4OUGA3KS.js} +0 -1
- package/dist/{chunk-Z57GJLCG.js → chunk-65TUD7JV.js} +4 -5
- package/dist/{chunk-L6YOMTFU.js → chunk-6OYJC4TZ.js} +4 -5
- package/dist/{chunk-G2RSY56Q.js → chunk-6TZCVTW5.js} +0 -1
- package/dist/{chunk-F3NCFNUX.js → chunk-6WP7EA4F.js} +0 -1
- package/dist/{chunk-SNYHVDE4.js → chunk-CAWQEHKP.js} +3 -4
- package/dist/{chunk-AKSXZBPT.js → chunk-D6YJ5X3C.js} +3 -4
- package/dist/{chunk-UZ42MHTR.js → chunk-E6TL6MIH.js} +2 -4
- package/dist/{chunk-ZZ25FZG2.js → chunk-ETBRAKVV.js} +0 -1
- package/dist/chunk-FBOZIVVQ.js +0 -0
- package/dist/{chunk-MRMBFJR2.js → chunk-HDP4QAZL.js} +0 -1
- package/dist/{chunk-3CCWSLQW.js → chunk-IBRBSDLT.js} +1 -2
- package/dist/{chunk-UKAAT6KT.js → chunk-ICCGLO6V.js} +4 -5
- package/dist/{chunk-XTLPA7ZP.js → chunk-JEVLCA5C.js} +2 -3
- package/dist/chunk-LDM7RNNN.js +0 -0
- package/dist/{chunk-B4X5RWLR.js → chunk-LVKKICOB.js} +14 -15
- package/dist/{chunk-CCJK3HTG.js → chunk-M34E2AMK.js} +0 -1
- package/dist/{chunk-QRXG5CAZ.js → chunk-MF56KEI4.js} +0 -1
- package/dist/{chunk-PZ5AY32C.js → chunk-MLKGABMK.js} +0 -1
- package/dist/{chunk-TPP2UGQP.js → chunk-MLPZKUCO.js} +8 -2
- package/dist/{chunk-Q65LL6UM.js → chunk-NFPRKZQ5.js} +2 -3
- package/dist/{chunk-5TOJD2C5.js → chunk-NRG6QX3L.js} +0 -1
- package/dist/{chunk-63VHBANJ.js → chunk-OPDWMD4Q.js} +0 -1
- package/dist/{chunk-LN7GNFET.js → chunk-OSL4CNSO.js} +4 -5
- package/dist/{chunk-63WE2C5R.js → chunk-PA3UTI4A.js} +0 -1
- package/dist/{chunk-UHIANNKC.js → chunk-PDSIWL7I.js} +3 -4
- package/dist/{chunk-A4D2CIIT.js → chunk-RYVW7RUM.js} +1 -2
- package/dist/{chunk-WTENYKJP.js → chunk-SIFDK4AA.js} +2 -3
- package/dist/{chunk-Q6QCHAMD.js → chunk-UAPK3AIJ.js} +0 -1
- package/dist/{chunk-ZE64EWUV.js → chunk-UAZKHSEU.js} +2 -3
- package/dist/{chunk-PD3EDFQD.js → chunk-UKXCGQPS.js} +5 -6
- package/dist/{chunk-7I2A7GGJ.js → chunk-VQDDL3UH.js} +1 -2
- package/dist/{chunk-PJNL35DC.js → chunk-XPHNS7NW.js} +2 -3
- package/dist/{chunk-MPL6BDR6.js → chunk-YAM6P5OQ.js} +1 -2
- package/dist/{chunk-YPKNMYD4.js → chunk-ZSHVXDA2.js} +0 -1
- package/dist/client.cjs +13 -8
- package/dist/client.js +32 -33
- package/dist/core/client.cjs +2 -4
- package/dist/core/client.js +6 -7
- package/dist/core/error.cjs +2 -4
- package/dist/core/error.js +4 -5
- package/dist/core/index.cjs +2 -4
- package/dist/core/index.js +8 -9
- package/dist/core/resource.cjs +0 -1
- package/dist/core/resource.js +2 -3
- package/dist/edge.cjs +2 -4
- package/dist/edge.js +10 -11
- package/dist/index.cjs +13 -8
- package/dist/index.js +39 -40
- package/dist/modelrouter/core.cjs +2 -4
- package/dist/modelrouter/core.js +8 -9
- package/dist/modelrouter/index.cjs +2 -4
- package/dist/modelrouter/index.js +8 -9
- package/dist/modelrouter/types.cjs +0 -1
- package/dist/modelrouter/types.js +0 -1
- package/dist/subagents/anthropic.cjs +13 -8
- package/dist/subagents/anthropic.js +19 -20
- package/dist/subagents/index.cjs +0 -1
- package/dist/subagents/index.js +2 -3
- package/dist/subagents/prompts.cjs +0 -1
- package/dist/subagents/prompts.js +2 -3
- package/dist/subagents/types.cjs +0 -1
- package/dist/subagents/types.js +0 -1
- package/dist/subagents/vercel.cjs +13 -8
- package/dist/subagents/vercel.js +19 -20
- package/dist/tools/compact/core.cjs +2 -4
- package/dist/tools/compact/core.js +8 -9
- package/dist/tools/compact/index.cjs +2 -4
- package/dist/tools/compact/index.js +9 -10
- package/dist/tools/compact/types.cjs +0 -1
- package/dist/tools/compact/types.js +0 -1
- package/dist/tools/fastapply/anthropic.cjs +2 -4
- package/dist/tools/fastapply/anthropic.js +11 -12
- package/dist/tools/fastapply/apply.cjs +2 -4
- package/dist/tools/fastapply/apply.js +4 -5
- package/dist/tools/fastapply/core.cjs +2 -4
- package/dist/tools/fastapply/core.js +9 -10
- package/dist/tools/fastapply/index.cjs +2 -4
- package/dist/tools/fastapply/index.js +14 -15
- package/dist/tools/fastapply/openai.cjs +2 -4
- package/dist/tools/fastapply/openai.js +11 -12
- package/dist/tools/fastapply/prompts.cjs +0 -1
- package/dist/tools/fastapply/prompts.js +2 -3
- package/dist/tools/fastapply/types.cjs +0 -1
- package/dist/tools/fastapply/types.js +0 -1
- package/dist/tools/fastapply/vercel.cjs +2 -4
- package/dist/tools/fastapply/vercel.js +11 -12
- package/dist/tools/index.cjs +2 -4
- package/dist/tools/index.js +14 -15
- package/dist/tools/utils/resilience.cjs +2 -4
- package/dist/tools/utils/resilience.js +3 -4
- package/dist/tools/warp_grep/agent/config.cjs +0 -1
- package/dist/tools/warp_grep/agent/config.js +2 -3
- package/dist/tools/warp_grep/agent/formatter.cjs +0 -1
- package/dist/tools/warp_grep/agent/formatter.js +2 -3
- package/dist/tools/warp_grep/agent/parser.cjs +0 -1
- package/dist/tools/warp_grep/agent/parser.js +2 -3
- package/dist/tools/warp_grep/agent/runner.cjs +2 -4
- package/dist/tools/warp_grep/agent/runner.js +7 -8
- package/dist/tools/warp_grep/agent/types.cjs +0 -1
- package/dist/tools/warp_grep/agent/types.js +0 -1
- package/dist/tools/warp_grep/anthropic.cjs +13 -8
- package/dist/tools/warp_grep/anthropic.js +19 -20
- package/dist/tools/warp_grep/client.cjs +13 -8
- package/dist/tools/warp_grep/client.js +17 -18
- package/dist/tools/warp_grep/gemini.cjs +13 -8
- package/dist/tools/warp_grep/gemini.js +18 -19
- package/dist/tools/warp_grep/harness.cjs +10 -4
- package/dist/tools/warp_grep/harness.js +9 -10
- package/dist/tools/warp_grep/index.cjs +13 -8
- package/dist/tools/warp_grep/index.js +24 -25
- package/dist/tools/warp_grep/openai.cjs +13 -8
- package/dist/tools/warp_grep/openai.js +19 -20
- package/dist/tools/warp_grep/providers/code_storage_http.cjs +0 -1
- package/dist/tools/warp_grep/providers/code_storage_http.js +2 -3
- package/dist/tools/warp_grep/providers/local.cjs +10 -4
- package/dist/tools/warp_grep/providers/local.js +6 -7
- package/dist/tools/warp_grep/providers/remote.cjs +0 -1
- package/dist/tools/warp_grep/providers/remote.js +3 -4
- package/dist/tools/warp_grep/providers/types.cjs +0 -1
- package/dist/tools/warp_grep/providers/types.js +0 -1
- package/dist/tools/warp_grep/utils/files.cjs +0 -1
- package/dist/tools/warp_grep/utils/files.js +2 -3
- package/dist/tools/warp_grep/utils/github.cjs +0 -1
- package/dist/tools/warp_grep/utils/github.js +2 -3
- package/dist/tools/warp_grep/utils/paths.cjs +0 -1
- package/dist/tools/warp_grep/utils/paths.js +2 -3
- package/dist/tools/warp_grep/utils/ripgrep.cjs +20 -4
- package/dist/tools/warp_grep/utils/ripgrep.js +2 -3
- package/dist/tools/warp_grep/vercel.cjs +13 -8
- package/dist/tools/warp_grep/vercel.js +19 -20
- package/dist/version.cjs +2 -4
- package/dist/version.js +2 -3
- package/package.json +2 -3
- package/dist/ai-sdk/index.cjs.map +0 -1
- package/dist/ai-sdk/index.js.map +0 -1
- package/dist/chunk-3CCWSLQW.js.map +0 -1
- package/dist/chunk-5TOJD2C5.js.map +0 -1
- package/dist/chunk-63VHBANJ.js.map +0 -1
- package/dist/chunk-63WE2C5R.js.map +0 -1
- package/dist/chunk-7I2A7GGJ.js.map +0 -1
- package/dist/chunk-A4D2CIIT.js.map +0 -1
- package/dist/chunk-AKSXZBPT.js.map +0 -1
- package/dist/chunk-B4X5RWLR.js.map +0 -1
- package/dist/chunk-CCJK3HTG.js.map +0 -1
- package/dist/chunk-F3NCFNUX.js.map +0 -1
- package/dist/chunk-FBRNUWEB.js.map +0 -1
- package/dist/chunk-G2RSY56Q.js.map +0 -1
- package/dist/chunk-HYRHI2UL.js.map +0 -1
- package/dist/chunk-IA5K2HTC.js.map +0 -1
- package/dist/chunk-L6YOMTFU.js.map +0 -1
- package/dist/chunk-LN7GNFET.js.map +0 -1
- package/dist/chunk-MLROWLS6.js.map +0 -1
- package/dist/chunk-MPL6BDR6.js.map +0 -1
- package/dist/chunk-MRMBFJR2.js.map +0 -1
- package/dist/chunk-PD3EDFQD.js.map +0 -1
- package/dist/chunk-PJNL35DC.js.map +0 -1
- package/dist/chunk-PZ5AY32C.js.map +0 -1
- package/dist/chunk-Q65LL6UM.js.map +0 -1
- package/dist/chunk-Q6QCHAMD.js.map +0 -1
- package/dist/chunk-QRXG5CAZ.js.map +0 -1
- package/dist/chunk-QTBFL4DG.js.map +0 -1
- package/dist/chunk-SNYHVDE4.js.map +0 -1
- package/dist/chunk-TIMDDHYB.js.map +0 -1
- package/dist/chunk-TPP2UGQP.js.map +0 -1
- package/dist/chunk-UHIANNKC.js.map +0 -1
- package/dist/chunk-UKAAT6KT.js.map +0 -1
- package/dist/chunk-UZ42MHTR.js.map +0 -1
- package/dist/chunk-VZ7BOH2K.js +0 -1
- package/dist/chunk-VZ7BOH2K.js.map +0 -1
- package/dist/chunk-WTENYKJP.js.map +0 -1
- package/dist/chunk-X2K57BH6.js +0 -1
- package/dist/chunk-X2K57BH6.js.map +0 -1
- package/dist/chunk-XTLPA7ZP.js.map +0 -1
- package/dist/chunk-YPKNMYD4.js.map +0 -1
- package/dist/chunk-Z57GJLCG.js.map +0 -1
- package/dist/chunk-ZE64EWUV.js.map +0 -1
- package/dist/chunk-ZZ25FZG2.js.map +0 -1
- package/dist/client.cjs.map +0 -1
- package/dist/client.js.map +0 -1
- package/dist/core/client.cjs.map +0 -1
- package/dist/core/client.js.map +0 -1
- package/dist/core/error.cjs.map +0 -1
- package/dist/core/error.js.map +0 -1
- package/dist/core/index.cjs.map +0 -1
- package/dist/core/index.js.map +0 -1
- package/dist/core/resource.cjs.map +0 -1
- package/dist/core/resource.js.map +0 -1
- package/dist/edge.cjs.map +0 -1
- package/dist/edge.js.map +0 -1
- package/dist/index.cjs.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/modelrouter/core.cjs.map +0 -1
- package/dist/modelrouter/core.js.map +0 -1
- package/dist/modelrouter/index.cjs.map +0 -1
- package/dist/modelrouter/index.js.map +0 -1
- package/dist/modelrouter/types.cjs.map +0 -1
- package/dist/modelrouter/types.js.map +0 -1
- package/dist/subagents/anthropic.cjs.map +0 -1
- package/dist/subagents/anthropic.js.map +0 -1
- package/dist/subagents/index.cjs.map +0 -1
- package/dist/subagents/index.js.map +0 -1
- package/dist/subagents/prompts.cjs.map +0 -1
- package/dist/subagents/prompts.js.map +0 -1
- package/dist/subagents/types.cjs.map +0 -1
- package/dist/subagents/types.js.map +0 -1
- package/dist/subagents/vercel.cjs.map +0 -1
- package/dist/subagents/vercel.js.map +0 -1
- package/dist/tools/compact/core.cjs.map +0 -1
- package/dist/tools/compact/core.js.map +0 -1
- package/dist/tools/compact/index.cjs.map +0 -1
- package/dist/tools/compact/index.js.map +0 -1
- package/dist/tools/compact/types.cjs.map +0 -1
- package/dist/tools/compact/types.js.map +0 -1
- package/dist/tools/fastapply/anthropic.cjs.map +0 -1
- package/dist/tools/fastapply/anthropic.js.map +0 -1
- package/dist/tools/fastapply/apply.cjs.map +0 -1
- package/dist/tools/fastapply/apply.js.map +0 -1
- package/dist/tools/fastapply/core.cjs.map +0 -1
- package/dist/tools/fastapply/core.js.map +0 -1
- package/dist/tools/fastapply/index.cjs.map +0 -1
- package/dist/tools/fastapply/index.js.map +0 -1
- package/dist/tools/fastapply/openai.cjs.map +0 -1
- package/dist/tools/fastapply/openai.js.map +0 -1
- package/dist/tools/fastapply/prompts.cjs.map +0 -1
- package/dist/tools/fastapply/prompts.js.map +0 -1
- package/dist/tools/fastapply/types.cjs.map +0 -1
- package/dist/tools/fastapply/types.js.map +0 -1
- package/dist/tools/fastapply/vercel.cjs.map +0 -1
- package/dist/tools/fastapply/vercel.js.map +0 -1
- package/dist/tools/index.cjs.map +0 -1
- package/dist/tools/index.js.map +0 -1
- package/dist/tools/utils/resilience.cjs.map +0 -1
- package/dist/tools/utils/resilience.js.map +0 -1
- package/dist/tools/warp_grep/agent/config.cjs.map +0 -1
- package/dist/tools/warp_grep/agent/config.js.map +0 -1
- package/dist/tools/warp_grep/agent/formatter.cjs.map +0 -1
- package/dist/tools/warp_grep/agent/formatter.js.map +0 -1
- package/dist/tools/warp_grep/agent/parser.cjs.map +0 -1
- package/dist/tools/warp_grep/agent/parser.js.map +0 -1
- package/dist/tools/warp_grep/agent/runner.cjs.map +0 -1
- package/dist/tools/warp_grep/agent/runner.js.map +0 -1
- package/dist/tools/warp_grep/agent/types.cjs.map +0 -1
- package/dist/tools/warp_grep/agent/types.js.map +0 -1
- package/dist/tools/warp_grep/anthropic.cjs.map +0 -1
- package/dist/tools/warp_grep/anthropic.js.map +0 -1
- package/dist/tools/warp_grep/client.cjs.map +0 -1
- package/dist/tools/warp_grep/client.js.map +0 -1
- package/dist/tools/warp_grep/gemini.cjs.map +0 -1
- package/dist/tools/warp_grep/gemini.js.map +0 -1
- package/dist/tools/warp_grep/harness.cjs.map +0 -1
- package/dist/tools/warp_grep/harness.js.map +0 -1
- package/dist/tools/warp_grep/index.cjs.map +0 -1
- package/dist/tools/warp_grep/index.js.map +0 -1
- package/dist/tools/warp_grep/openai.cjs.map +0 -1
- package/dist/tools/warp_grep/openai.js.map +0 -1
- package/dist/tools/warp_grep/providers/code_storage_http.cjs.map +0 -1
- package/dist/tools/warp_grep/providers/code_storage_http.js.map +0 -1
- package/dist/tools/warp_grep/providers/local.cjs.map +0 -1
- package/dist/tools/warp_grep/providers/local.js.map +0 -1
- package/dist/tools/warp_grep/providers/remote.cjs.map +0 -1
- package/dist/tools/warp_grep/providers/remote.js.map +0 -1
- package/dist/tools/warp_grep/providers/types.cjs.map +0 -1
- package/dist/tools/warp_grep/providers/types.js.map +0 -1
- package/dist/tools/warp_grep/utils/files.cjs.map +0 -1
- package/dist/tools/warp_grep/utils/files.js.map +0 -1
- package/dist/tools/warp_grep/utils/github.cjs.map +0 -1
- package/dist/tools/warp_grep/utils/github.js.map +0 -1
- package/dist/tools/warp_grep/utils/paths.cjs.map +0 -1
- package/dist/tools/warp_grep/utils/paths.js.map +0 -1
- package/dist/tools/warp_grep/utils/ripgrep.cjs.map +0 -1
- package/dist/tools/warp_grep/utils/ripgrep.js.map +0 -1
- package/dist/tools/warp_grep/vercel.cjs.map +0 -1
- package/dist/tools/warp_grep/vercel.js.map +0 -1
- package/dist/version.cjs.map +0 -1
- package/dist/version.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/warp_grep/agent/runner.ts"],"sourcesContent":["import { AGENT_CONFIG, DEFAULT_MODEL } from './config.js';\nimport type { AgentRunResult, ChatMessage, SessionConfig, AgentFinish, ToolCallRef, WarpGrepExecutionMetrics, WarpGrepTurnMetrics, WarpGrepStep } from './types.js';\nimport { parseFinishFiles, parseReadLines, extractPathFromCommand } from './parser.js';\nimport type { WarpGrepProvider } from '../providers/types.js';\nimport { toolGrep } from './tools/grep.js';\nimport { toolRead } from './tools/read.js';\nimport { toolListDirectory } from './tools/list_directory.js';\nimport { toolGlob } from './tools/glob.js';\nimport { readFinishFiles } from './tools/finish.js';\nimport type { RetryConfig } from '../../utils/resilience.js';\nimport { formatTurnMessage, calculateContextBudget, buildInitialState, enforceContextLimit } from './helpers.js';\nimport OpenAI from 'openai';\nimport { SDK_VERSION } from '../../../version.js';\nimport path from 'path';\nimport { logger } from '../../../logger.js';\n\ntype EventName =\n | 'initial_state'\n | 'round_start'\n | 'round_end'\n | 'finish'\n | 'error';\n\nexport type EventCallback = (name: EventName, payload: Record<string, unknown>) => void;\n\nconst DEFAULT_API_URL = 'https://api.morphllm.com';\n\n// Tool definitions sent to the model (OpenAI function calling format)\nconst TOOL_SPECS: OpenAI.Chat.ChatCompletionTool[] = [\n {\n type: 'function',\n function: {\n name: 'list_directory',\n description: 'Execute ls or find commands to explore directory structure. Max 500 results. Common junk directories are excluded automatically.',\n parameters: {\n type: 'object',\n properties: {\n command: {\n type: 'string',\n description: \"Full ls or find command (e.g. ls -la src/, find . -maxdepth 2 -type f -name '*.py', find . -type d, ls -d */).\",\n },\n },\n required: ['command'],\n },\n },\n },\n {\n type: 'function',\n function: {\n name: 'grep_search',\n description: 'Search for a regex pattern in file contents. Returns matching lines with file paths and line numbers. Case-insensitive. Respects .gitignore.',\n parameters: {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: \"Regex pattern to search for in file contents (e.g. 'class\\\\s+\\\\w+Error', 'import|require|from', 'def (get|set|update)_user').\",\n },\n path: {\n type: 'string',\n description: 'File or directory to search in. Defaults to current working directory.',\n },\n glob: {\n type: 'string',\n description: \"Glob pattern to filter files (e.g. '*.py', '*.{ts,tsx,js,jsx,py,go}', 'src/**/*.go', '!*.test.*').\",\n },\n limit: {\n type: 'integer',\n description: 'Limit output to first N matching lines. Shows all matches if not specified.',\n },\n },\n required: ['pattern'],\n },\n },\n },\n {\n type: 'function',\n function: {\n name: 'glob',\n description: 'Find files by name/extension using glob patterns. Returns absolute paths sorted by modification time (newest first). Respects .gitignore. Max 100 results.',\n parameters: {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: \"Glob pattern to match files (e.g. '*.py', 'src/**/*.js', '*.{ts,tsx}', 'test_*.py').\",\n },\n path: {\n type: 'string',\n description: 'Directory to search in. Defaults to repository root.',\n },\n },\n required: ['pattern'],\n },\n },\n },\n {\n type: 'function',\n function: {\n name: 'read',\n description: 'Read entire files or specific line ranges using absolute paths.',\n parameters: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: \"File path to read, using absolute path (e.g. '/home/ubuntu/repo/src/main.py' or windows path).\",\n },\n lines: {\n type: 'string',\n description: \"Optional line range (e.g. '1-50' or '1-20,45-80'). Omit to read entire file.\",\n },\n },\n required: ['path'],\n },\n },\n },\n {\n type: 'function',\n function: {\n name: 'finish',\n description: 'Submit final answer with all relevant code locations. Include imports and over-include rather than miss context.',\n parameters: {\n type: 'object',\n properties: {\n files: {\n type: 'string',\n description: \"One file per line as path:lines (e.g. 'src/auth.py:1-15,25-50\\\\nsrc/user.py'). Omit line range to include entire file.\",\n },\n },\n required: ['files'],\n },\n },\n },\n];\n\ninterface CallModelOptions {\n morphApiKey?: string;\n morphApiUrl?: string;\n retryConfig?: RetryConfig;\n timeout?: number;\n search_type?: string;\n}\n\ntype ModelResponse = {\n content: string | null;\n tool_calls: ToolCallRef[];\n};\n\nasync function callModel(\n messages: ChatMessage[],\n model: string,\n options: CallModelOptions = {}\n): Promise<ModelResponse> {\n const baseUrl = options.morphApiUrl || DEFAULT_API_URL;\n const apiKey = options.morphApiKey || process.env.MORPH_API_KEY || '';\n const timeoutMs = options.timeout ?? AGENT_CONFIG.TIMEOUT_MS;\n\n const parsedUrl = new URL(baseUrl);\n const baseURL = parsedUrl.pathname === '/' ? `${baseUrl}/v1` : baseUrl;\n\n const client = new OpenAI({\n apiKey,\n baseURL,\n maxRetries: 0,\n timeout: timeoutMs,\n defaultHeaders: { 'X-Morph-SDK-Version': SDK_VERSION },\n });\n\n const MAX_EMPTY_RETRIES = 1;\n\n logger.debug('WarpGrep', 'model_call', { url: baseURL, model, message_count: messages.length });\n const callStartTime = Date.now();\n\n for (let attempt = 0; attempt <= MAX_EMPTY_RETRIES; attempt++) {\n let data;\n try {\n data = await client.chat.completions.create({\n model,\n temperature: 0.0,\n max_tokens: 2048,\n messages: messages as OpenAI.Chat.ChatCompletionMessageParam[],\n tools: TOOL_SPECS,\n ...(options.search_type ? { search_type: options.search_type } as Record<string, unknown> : {}),\n });\n } catch (error) {\n const callLatencyMs = Date.now() - callStartTime;\n if (error instanceof OpenAI.APIError) {\n logger.error('WarpGrep', 'model_call_error', { status: error.status, error: error.message, latency_ms: callLatencyMs });\n if (error.status === 404) {\n const defaultMsg =\n 'The endpoint you are trying to call is likely deprecated. Please update with: npm cache clean --force && npx -y @morphllm/morphmcp@latest or visit: https://morphllm.com/mcp';\n const errorText = error.message?.trim();\n throw new Error(errorText || defaultMsg);\n }\n } else {\n logger.error('WarpGrep', 'model_call_error', { status: undefined, error: error instanceof Error ? error.message : String(error), latency_ms: callLatencyMs });\n }\n throw error;\n }\n\n const choice = data?.choices?.[0];\n const message = choice?.message;\n\n if (!message) {\n if (attempt === MAX_EMPTY_RETRIES) {\n throw new Error('Invalid response from model: no message in response');\n }\n await new Promise(resolve => setTimeout(resolve, 200));\n continue;\n }\n\n const toolCalls: ToolCallRef[] = (message.tool_calls || []).map(tc => ({\n id: tc.id,\n type: 'function' as const,\n function: { name: tc.function.name, arguments: tc.function.arguments },\n }));\n\n if (message.content || toolCalls.length > 0) {\n logger.debug('WarpGrep', 'model_call_complete', { latency_ms: Date.now() - callStartTime, tool_calls_count: toolCalls.length, finish_reason: choice?.finish_reason ?? 'unknown' });\n return { content: message.content ?? null, tool_calls: toolCalls };\n }\n\n if (attempt === MAX_EMPTY_RETRIES) {\n const finishReason = choice?.finish_reason ?? 'unknown';\n throw new Error(\n `Invalid response from model: no content and no tool_calls, finish_reason=${finishReason}`\n );\n }\n await new Promise(resolve => setTimeout(resolve, 200));\n }\n\n throw new Error('Invalid response from model');\n}\n\n/** Safely parse JSON, returning empty object on failure */\nfunction safeParseJSON(s: string): Record<string, unknown> {\n try {\n return JSON.parse(s);\n } catch {\n return {};\n }\n}\n\n/**\n * Execute a single tool call against the provider, returning the output string.\n */\nasync function executeTool(\n provider: WarpGrepProvider,\n name: string,\n args: Record<string, unknown>,\n repoRoot?: string,\n): Promise<string> {\n switch (name) {\n case 'grep_search': {\n const grepArgs: { pattern: string; path: string; glob?: string; case_sensitive?: boolean } = {\n pattern: args.pattern as string,\n path: (args.path as string) || '.',\n };\n if (args.glob) grepArgs.glob = args.glob as string;\n if (args.case_sensitive !== undefined) grepArgs.case_sensitive = args.case_sensitive as boolean;\n const result = await toolGrep(provider, grepArgs);\n let output = result.output;\n if (args.limit && typeof args.limit === 'number') {\n const lines = output.split('\\n');\n if (lines.length > args.limit) {\n output = lines.slice(0, args.limit).join('\\n') + `\\n... (truncated at ${args.limit} lines)`;\n }\n }\n return output;\n }\n case 'glob': {\n return toolGlob(provider, {\n pattern: args.pattern as string,\n path: args.path as string | undefined,\n });\n }\n case 'list_directory': {\n const dirPath = extractPathFromCommand((args.command as string) || '.');\n return toolListDirectory(provider, { path: dirPath }, repoRoot);\n }\n case 'read': {\n const readArgs: { path: string; start?: number; end?: number; lines?: Array<[number, number]> } = {\n path: args.path as string,\n };\n if (args.lines && typeof args.lines === 'string') {\n Object.assign(readArgs, parseReadLines(args.lines));\n }\n return toolRead(provider, readArgs);\n }\n default:\n return `Unknown tool: ${name}`;\n }\n}\n\n/**\n * Streaming version of runWarpGrep that yields step information after each turn.\n * Yields WarpGrepStep with tool calls for each turn, then returns the final AgentRunResult.\n */\nexport async function* runWarpGrepStreaming(\n config: SessionConfig & { provider: WarpGrepProvider }\n): AsyncGenerator<WarpGrepStep, AgentRunResult, undefined> {\n const totalStart = Date.now();\n const timeoutMs = config.timeout ?? AGENT_CONFIG.TIMEOUT_MS;\n const timings: Partial<WarpGrepExecutionMetrics> = { turns: [], timeout_ms: timeoutMs };\n\n const repoRoot = config.repoRoot || process.cwd();\n const model = config.model || DEFAULT_MODEL;\n const messages: ChatMessage[] = [];\n\n const maxTurns = AGENT_CONFIG.MAX_TURNS;\n\n logger.debug('WarpGrep', 'session_start', { search_term: config.searchTerm, model, max_turns: maxTurns });\n\n const initialStateStart = Date.now();\n const initialState = await buildInitialState(repoRoot, config.searchTerm, config.provider, { search_type: config.search_type });\n timings.initial_state_ms = Date.now() - initialStateStart;\n\n logger.debug('WarpGrep', 'initial_state', { system_prompt_len: initialState.length, user_message_len: initialState.length });\n\n messages.push({ role: 'user', content: initialState });\n\n const provider = config.provider;\n const errors: Array<{ message: string }> = [];\n\n let finishMeta: AgentFinish | undefined;\n let terminationReason: AgentRunResult['terminationReason'] = 'terminated';\n\n for (let turn = 1; turn <= maxTurns; turn += 1) {\n const turnMetrics: WarpGrepTurnMetrics = { turn, morph_api_ms: 0, local_tools_ms: 0 };\n\n logger.debug('WarpGrep', 'turn_start', { turn, message_count: messages.length });\n\n const beforeChars = messages.reduce((sum, m) => sum + (typeof m.content === 'string' ? m.content.length : 0), 0);\n enforceContextLimit(messages);\n const afterChars = messages.reduce((sum, m) => sum + (typeof m.content === 'string' ? m.content.length : 0), 0);\n if (afterChars < beforeChars) {\n logger.debug('WarpGrep', 'context_truncated', { before_chars: beforeChars, after_chars: afterChars });\n }\n\n // Call model\n const modelCallStart = Date.now();\n const response = await callModel(messages, model, {\n morphApiKey: config.morphApiKey,\n morphApiUrl: config.morphApiUrl,\n retryConfig: config.retryConfig,\n timeout: timeoutMs,\n search_type: config.search_type,\n }).catch((e: unknown) => {\n const errMsg = e instanceof Error ? e.message : String(e);\n console.error(`[warp_grep] Morph API call failed on turn ${turn}:`, errMsg);\n logger.error('WarpGrep', 'error', { turn, error: errMsg, phase: 'model_call' });\n errors.push({ message: errMsg });\n return null;\n });\n turnMetrics.morph_api_ms = Date.now() - modelCallStart;\n\n if (!response) {\n timings.turns!.push(turnMetrics);\n break;\n }\n\n const toolCalls = response.tool_calls;\n logger.debug('WarpGrep', 'model_response', { turn, tool_calls: toolCalls.map(tc => tc.function.name), latency_ms: turnMetrics.morph_api_ms });\n\n // Add assistant message to history\n messages.push({\n role: 'assistant',\n content: response.content,\n ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),\n });\n\n if (toolCalls.length === 0) {\n console.error(`[warp_grep] No tool calls on turn ${turn}. Content: ${(response.content || '').slice(0, 500)}`);\n errors.push({ message: 'No tool calls produced by the model.' });\n terminationReason = 'terminated';\n timings.turns!.push(turnMetrics);\n break;\n }\n\n // Yield step for streaming consumers\n yield {\n turn,\n toolCalls: toolCalls.map(tc => ({\n name: tc.function.name,\n arguments: safeParseJSON(tc.function.arguments),\n })),\n };\n\n // Check for finish call\n const finishCall = toolCalls.find(tc => tc.function.name === 'finish');\n if (finishCall) {\n const args = safeParseJSON(finishCall.function.arguments) as { files?: string };\n const filesStr = args.files || '';\n const files = parseFinishFiles(filesStr);\n finishMeta = { files };\n terminationReason = 'completed';\n logger.debug('WarpGrep', 'finish', { turns: turn, files: files.map(f => f.path) });\n\n if (files.length === 0) {\n const payload = filesStr || 'No relevant code found.';\n timings.turns!.push(turnMetrics);\n timings.total_ms = Date.now() - totalStart;\n return {\n terminationReason: 'completed',\n messages,\n finish: { payload, metadata: finishMeta },\n timings: timings as WarpGrepExecutionMetrics,\n };\n }\n\n timings.turns!.push(turnMetrics);\n break;\n }\n\n // Execute non-finish tool calls in parallel\n const toolExecStart = Date.now();\n const results = await Promise.all(\n toolCalls.map(async (tc) => {\n const args = safeParseJSON(tc.function.arguments);\n const argsSummary = Object.fromEntries(Object.entries(args).map(([k, v]) => [k, typeof v === 'string' && v.length > 100 ? v.slice(0, 100) + '...' : v]));\n logger.debug('WarpGrep', 'tool_exec', { turn, tool: tc.function.name, args_summary: argsSummary });\n const toolStart = Date.now();\n const output = await executeTool(provider, tc.function.name, args, repoRoot).catch(err => String(err));\n logger.debug('WarpGrep', 'tool_result', { turn, tool: tc.function.name, result_len: output.length, latency_ms: Date.now() - toolStart });\n return { tool_call_id: tc.id, content: output };\n })\n );\n turnMetrics.local_tools_ms = Date.now() - toolExecStart;\n\n // Add tool result messages\n for (const result of results) {\n messages.push({ role: 'tool', tool_call_id: result.tool_call_id, content: result.content });\n }\n\n // Add turn counter hint\n const turnMsg = formatTurnMessage(turn, maxTurns);\n const budget = calculateContextBudget(messages);\n messages.push({ role: 'user', content: turnMsg + '\\n' + budget });\n\n timings.turns!.push(turnMetrics);\n }\n\n if (terminationReason !== 'completed' || !finishMeta) {\n timings.total_ms = Date.now() - totalStart;\n return { terminationReason, messages, errors, timings: timings as WarpGrepExecutionMetrics };\n }\n\n // Build finish payload\n const parts: string[] = ['Relevant context found:'];\n for (const f of finishMeta.files) {\n const ranges = f.lines === '*' ? '*'\n : Array.isArray(f.lines) ? f.lines.map(([s, e]) => `${s}-${e}`).join(', ')\n : '*';\n parts.push(`- ${f.path}: ${ranges}`);\n }\n const payload = parts.join('\\n');\n\n // Resolve file contents for returned ranges\n const finishResolutionStart = Date.now();\n const fileReadErrors: Array<{ path: string; error: string }> = [];\n const resolved = await readFinishFiles(\n repoRoot,\n finishMeta.files,\n async (p: string, s?: number, e?: number) => {\n // If the model returned a path that doesn't start with repoRoot,\n // try resolving it against repoRoot (handles truncated absolute paths)\n let resolvedPath = p;\n if (!p.startsWith(repoRoot)) {\n // Strip leading slash for path.join, then try the resolved path\n const relative = p.startsWith('/') ? p.slice(1) : p;\n resolvedPath = path.join(repoRoot, relative);\n }\n try {\n const rr = await provider.read({ path: resolvedPath, start: s, end: e });\n return rr.lines.map(l => {\n const idx = l.indexOf('|');\n return idx >= 0 ? l.slice(idx + 1) : l;\n });\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n fileReadErrors.push({ path: resolvedPath, error: errorMsg });\n console.error(`[warp_grep] Failed to read file: ${resolvedPath} - ${errorMsg}`);\n return [`[couldn't find: ${resolvedPath}]`];\n }\n }\n );\n\n timings.finish_resolution_ms = Date.now() - finishResolutionStart;\n\n if (fileReadErrors.length > 0) {\n errors.push(...fileReadErrors.map(e => ({ message: `File read error: ${e.path} - ${e.error}` })));\n }\n\n timings.total_ms = Date.now() - totalStart;\n return {\n terminationReason: 'completed',\n messages,\n finish: { payload, metadata: finishMeta, resolved },\n timings: timings as WarpGrepExecutionMetrics,\n };\n}\n\n/**\n * Non-streaming version. Runs the agent loop and returns the final result.\n */\nexport async function runWarpGrep(config: SessionConfig & { provider: WarpGrepProvider }): Promise<AgentRunResult> {\n const gen = runWarpGrepStreaming(config);\n // Drain all yielded steps, return the final result\n let result = await gen.next();\n while (!result.done) {\n result = await gen.next();\n }\n return result.value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,OAAO,YAAY;AAEnB,OAAO,UAAU;AAYjB,IAAM,kBAAkB;AAGxB,IAAM,aAA+C;AAAA,EACnD;AAAA,IACE,MAAM;AAAA,IACN,UAAU;AAAA,MACR,MAAM;AAAA,MACN,aAAa;AAAA,MACb,YAAY;AAAA,QACV,MAAM;AAAA,QACN,YAAY;AAAA,UACV,SAAS;AAAA,YACP,MAAM;AAAA,YACN,aAAa;AAAA,UACf;AAAA,QACF;AAAA,QACA,UAAU,CAAC,SAAS;AAAA,MACtB;AAAA,IACF;AAAA,EACF;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,UAAU;AAAA,MACR,MAAM;AAAA,MACN,aAAa;AAAA,MACb,YAAY;AAAA,QACV,MAAM;AAAA,QACN,YAAY;AAAA,UACV,SAAS;AAAA,YACP,MAAM;AAAA,YACN,aAAa;AAAA,UACf;AAAA,UACA,MAAM;AAAA,YACJ,MAAM;AAAA,YACN,aAAa;AAAA,UACf;AAAA,UACA,MAAM;AAAA,YACJ,MAAM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AAA,MACH,SAAS,KAAK;AACZ,cAAM,WAAW,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAChE,uBAAe,KAAK,EAAE,MAAM,cAAc,OAAO,SAAS,CAAC;AAC3D,gBAAQ,MAAM,oCAAoC,YAAY,MAAM,QAAQ,EAAE;AAC9E,eAAO,CAAC,mBAAmB,YAAY,GAAG;AAAA,MAC5C;AAAA,IACF;AAAA,EACF;AAEA,UAAQ,uBAAuB,KAAK,IAAI,IAAI;AAE5C,MAAI,eAAe,SAAS,GAAG;AAC7B,WAAO,KAAK,GAAG,eAAe,IAAI,QAAM,EAAE,SAAS,oBAAoB,EAAE,IAAI,MAAM,EAAE,KAAK,GAAG,EAAE,CAAC;AAAA,EAClG;AAEA,UAAQ,WAAW,KAAK,IAAI,IAAI;AAChC,SAAO;AAAA,IACL,mBAAmB;AAAA,IACnB;AAAA,IACA,QAAQ,EAAE,SAAS,UAAU,YAAY,SAAS;AAAA,IAClD;AAAA,EACF;AACF;AAKA,eAAsB,YAAY,QAAiF;AACjH,QAAM,MAAM,qBAAqB,MAAM;AAEvC,MAAI,SAAS,MAAM,IAAI,KAAK;AAC5B,SAAO,CAAC,OAAO,MAAM;AACnB,aAAS,MAAM,IAAI,KAAK;AAAA,EAC1B;AACA,SAAO,OAAO;AAChB;","names":["payload"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../subagents/anthropic.ts"],"sourcesContent":["/**\n * Anthropic SDK adapter for Explore subagent\n */\n\nimport type { Tool } from '@anthropic-ai/sdk/resources/messages';\nimport { WarpGrepClient } from '../tools/warp_grep/client.js';\nimport { formatResult } from '../tools/warp_grep/client.js';\nimport type { WarpGrepContext } from '../tools/warp_grep/types.js';\nimport { getSystemPrompt, CODEBASE_SEARCH_TOOL, SEND_MESSAGE_TOOL } from './prompts.js';\nimport type {\n ExploreSubagentConfig,\n ExploreResult,\n ExploreStep,\n ExploreSession,\n ExploreEvent,\n SubagentMessage,\n MessageHandler,\n StepHandler,\n} from './types.js';\n\n/** Config for Anthropic SDK Explore subagent */\nexport interface AnthropicExploreConfig extends ExploreSubagentConfig {\n /** Anthropic SDK client instance */\n client: AnthropicClient;\n /** Model name (e.g., 'claude-haiku-4-5-20251001') */\n model: string;\n}\n\n/** Minimal Anthropic client interface — avoids hard dependency on @anthropic-ai/sdk */\ninterface AnthropicClient {\n messages: {\n create(params: any): Promise<any>;\n };\n}\n\nconst DEFAULT_MAX_TURNS: Record<string, number> = {\n quick: 3,\n medium: 6,\n thorough: 12,\n};\n\nfunction getMaxTurns(config: ExploreSubagentConfig): number {\n return config.maxTurns ?? DEFAULT_MAX_TURNS[config.thoroughness ?? 'medium'] ?? 6;\n}\n\n/** Anthropic tool definitions */\nconst TOOLS: Tool[] = [\n {\n name: CODEBASE_SEARCH_TOOL.name,\n description: CODEBASE_SEARCH_TOOL.description,\n input_schema: CODEBASE_SEARCH_TOOL.input_schema,\n },\n {\n name: SEND_MESSAGE_TOOL.name,\n description: SEND_MESSAGE_TOOL.description,\n input_schema: SEND_MESSAGE_TOOL.input_schema,\n },\n];\n\n/**\n * Create an Explore subagent using the Anthropic SDK\n */\nexport function createExploreSubagent(config: AnthropicExploreConfig) {\n if (!config.repoRoot) {\n throw new Error('repoRoot is required for Explore subagent');\n }\n\n const warpGrep = new WarpGrepClient({\n morphApiKey: config.morphApiKey,\n });\n\n const thoroughness = config.thoroughness ?? 'medium';\n const maxTurns = getMaxTurns(config);\n const replyTimeout = config.replyTimeout ?? 30_000;\n\n /** Run the agent loop and collect results */\n async function runExplore(\n prompt: string,\n callbacks: {\n onStep?: StepHandler;\n onMessage?: MessageHandler;\n } = {},\n ): Promise<ExploreResult> {\n const startTime = Date.now();\n const allContexts: WarpGrepContext[] = [];\n let searchCount = 0;\n\n const timeoutMs = config.timeout;\n\n try {\n const messages: any[] = [{ role: 'user', content: prompt }];\n let turns = 0;\n\n while (turns < maxTurns) {\n // Check timeout\n if (timeoutMs && Date.now() - startTime > timeoutMs) {\n return {\n success: false,\n summary: '',\n contexts: deduplicateContexts(allContexts),\n searchCount,\n durationMs: Date.now() - startTime,\n error: `Exploration timed out after ${timeoutMs}ms`,\n };\n }\n\n const response = await config.client.messages.create({\n model: config.model,\n max_tokens: 4096,\n system: getSystemPrompt(thoroughness),\n tools: TOOLS,\n messages,\n });\n\n turns++;\n\n // Check if the model is done (no tool use)\n if (response.stop_reason === 'end_turn' || !response.content.some((b: any) => b.type === 'tool_use')) {\n const textBlock = response.content.find((b: any) => b.type === 'text');\n const summary = textBlock?.text || 'Exploration completed but no summary was generated.';\n\n callbacks.onStep?.({\n step: searchCount,\n searchRequest: '',\n contextsFound: allContexts.length,\n isFinal: true,\n });\n\n return {\n success: true,\n summary,\n contexts: deduplicateContexts(allContexts),\n searchCount,\n durationMs: Date.now() - startTime,\n };\n }\n\n // Process tool calls\n messages.push({ role: 'assistant', content: response.content });\n\n const toolResults: any[] = [];\n\n for (const block of response.content) {\n if (block.type !== 'tool_use') continue;\n\n if (block.name === 'codebase_search') {\n searchCount++;\n const input = block.input as { searchRequest: string };\n\n const warpResult = await warpGrep.execute({\n searchTerm: input.searchRequest,\n repoRoot: config.repoRoot,\n excludes: config.excludes,\n includes: config.includes,\n });\n\n if (warpResult.contexts) {\n allContexts.push(...warpResult.contexts);\n }\n\n callbacks.onStep?.({\n step: searchCount,\n searchRequest: input.searchRequest,\n contextsFound: warpResult.contexts?.length ?? 0,\n isFinal: false,\n });\n\n toolResults.push({\n type: 'tool_result',\n tool_use_id: block.id,\n content: formatResult(warpResult),\n });\n } else if (block.name === 'send_message') {\n const input = block.input as { message: string };\n\n const subagentMsg: SubagentMessage = {\n from: 'explore',\n content: input.message,\n timestamp: Date.now(),\n };\n\n let replyText = '';\n\n if (callbacks.onMessage) {\n // Wait for reply with timeout\n replyText = await Promise.race([\n new Promise<string>((resolve) => {\n callbacks.onMessage!(subagentMsg, (text: string) => {\n resolve(text);\n });\n }),\n new Promise<string>((resolve) =>\n setTimeout(() => resolve(''), replyTimeout),\n ),\n ]);\n }\n\n const toolResponse = replyText\n ? `Response from orchestrator: ${replyText}`\n : 'No response. Continue with your best judgment.';\n\n toolResults.push({\n type: 'tool_result',\n tool_use_id: block.id,\n content: toolResponse,\n });\n }\n }\n\n messages.push({ role: 'user', content: toolResults });\n }\n\n // Ran out of turns — extract what we have\n return {\n success: true,\n summary: 'Exploration completed (max turns reached).',\n contexts: deduplicateContexts(allContexts),\n searchCount,\n durationMs: Date.now() - startTime,\n };\n } catch (error) {\n return {\n success: false,\n summary: '',\n contexts: deduplicateContexts(allContexts),\n searchCount,\n durationMs: Date.now() - startTime,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /** Anthropic Tool definition for use in parent agents */\n const exploreTool: Tool & {\n execute: (input: { searchRequest: string }) => Promise<ExploreResult>;\n formatResult: (result: ExploreResult) => string;\n } = Object.assign(\n {\n name: 'explore',\n description:\n 'Explore a codebase to answer questions about code structure, find implementations, trace call chains, and understand architecture. Returns a summary of findings.',\n input_schema: {\n type: 'object' as const,\n properties: {\n searchRequest: {\n type: 'string' as const,\n description: 'What to explore in the codebase. Be specific about what you want to understand.',\n },\n },\n required: ['searchRequest'] as const,\n },\n },\n {\n execute: async (input: { searchRequest: string }): Promise<ExploreResult> => {\n return runExplore(input.searchRequest);\n },\n formatResult: (result: ExploreResult): string => {\n if (!result.success) {\n return `Exploration failed: ${result.error}`;\n }\n return result.summary;\n },\n },\n );\n\n return {\n /** Anthropic Tool definition for use in parent agents */\n tool: exploreTool,\n\n /** Run exploration with messaging support */\n run(prompt: string): ExploreSession {\n const messageHandlers: MessageHandler[] = [];\n const stepHandlers: StepHandler[] = [];\n\n let resultPromise: Promise<ExploreResult> | null = null;\n\n const session: ExploreSession = {\n on(event: string, handler: any) {\n if (event === 'message') messageHandlers.push(handler);\n if (event === 'step') stepHandlers.push(handler);\n return session;\n },\n send(_text: string) {\n // Convenience method — pause-and-ask flow uses the reply callback\n },\n get result() {\n if (!resultPromise) {\n resultPromise = runExplore(prompt, {\n onStep: (step) => {\n for (const handler of stepHandlers) handler(step);\n },\n onMessage: (msg, reply) => {\n if (messageHandlers.length > 0) {\n for (const handler of messageHandlers) handler(msg, reply);\n } else {\n reply('');\n }\n },\n });\n }\n return resultPromise;\n },\n };\n\n return session;\n },\n\n /** Stream exploration events as an async generator */\n async *stream(prompt: string): AsyncGenerator<ExploreEvent, ExploreResult, undefined> {\n const events: ExploreEvent[] = [];\n let resolveNext: (() => void) | null = null;\n let done = false;\n\n const resultPromise = runExplore(prompt, {\n onStep: (step) => {\n events.push({\n type: 'step',\n step: step.step,\n searchRequest: step.searchRequest,\n contextsFound: step.contextsFound,\n isFinal: step.isFinal,\n });\n resolveNext?.();\n },\n onMessage: (msg, reply) => {\n events.push({\n type: 'message',\n from: msg.from,\n content: msg.content,\n timestamp: msg.timestamp,\n });\n resolveNext?.();\n reply('Continue with your best judgment.');\n },\n });\n\n while (!done) {\n if (events.length > 0) {\n yield events.shift()!;\n } else {\n const raceResult = await Promise.race([\n resultPromise.then((r) => ({ type: 'done' as const, result: r })),\n new Promise<{ type: 'event' }>((resolve) => {\n resolveNext = () => resolve({ type: 'event' });\n }),\n ]);\n\n if (raceResult.type === 'done') {\n while (events.length > 0) {\n yield events.shift()!;\n }\n done = true;\n return raceResult.result;\n }\n }\n }\n\n return await resultPromise;\n },\n };\n}\n\n/** Deduplicate contexts, keeping the latest version of each file */\nfunction deduplicateContexts(contexts: WarpGrepContext[]): WarpGrepContext[] {\n const map = new Map<string, WarpGrepContext>();\n for (const ctx of contexts) {\n const existing = map.get(ctx.file);\n if (!existing || ctx.content.length > existing.content.length) {\n map.set(ctx.file, ctx);\n }\n }\n return Array.from(map.values());\n}\n"],"mappings":";;;;;;;;;;;AAmCA,IAAM,oBAA4C;AAAA,EAChD,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,UAAU;AACZ;AAEA,SAAS,YAAY,QAAuC;AAC1D,SAAO,OAAO,YAAY,kBAAkB,OAAO,gBAAgB,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names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/warp_grep/vercel.ts"],"sourcesContent":["/**\n * Vercel AI SDK adapter for morph-warp-grep tool\n *\n * @example Using with your own Zod instance (recommended for avoiding version conflicts)\n * ```typescript\n * import { z } from 'zod'; // Your project's Zod\n * import { createWarpGrepTool } from '@morphllm/morphsdk/tools/warp-grep/vercel';\n *\n * const schema = z.object({\n * search_term: z.string().describe('Search problem statement'),\n * });\n *\n * const grepTool = createWarpGrepTool({\n * repoRoot: '.',\n * inputSchema: schema,\n * });\n * ```\n */\n\nimport { tool } from 'ai';\nimport { z } from 'zod';\nimport { jsonSchema } from 'ai';\nimport { executeToolCall, executeToolCallStreaming, formatResult, WarpGrepClient, executeGitHubReadFile, formatGitHubReadFileResult } from './client.js';\nimport { WARP_GREP_DESCRIPTION, GITHUB_SEARCH_DESCRIPTION, GITHUB_READ_FILE_DESCRIPTION } from './prompts.js';\nimport type { WarpGrepToolConfig, WarpGrepResult, GitHubSearchToolConfig, GitHubReadFileInput, GitHubReadFileResult, GitHubReadFileToolConfig } from './types.js';\nimport type { WarpGrepStep } from './agent/types.js';\n\n/**\n * Raw JSON Schema for warp grep input (no Zod dependency).\n * Use this with jsonSchema() from 'ai' if you have Zod version conflicts.\n *\n * @example\n * ```typescript\n * import { jsonSchema } from 'ai';\n * import { warpGrepJsonSchema, createWarpGrepToolWithSchema } from '@morphllm/morphsdk/tools/warp-grep/vercel';\n *\n * const grepTool = createWarpGrepToolWithSchema({\n * repoRoot: '.',\n * inputSchema: jsonSchema(warpGrepJsonSchema),\n * });\n * ```\n */\nexport const warpGrepJsonSchema = {\n type: 'object' as const,\n properties: {\n search_term: {\n type: 'string' as const,\n description: 'Search problem statement that this subagent is supposed to research for',\n },\n },\n required: ['search_term'] as const,\n additionalProperties: false as const,\n};\n\n/** Type for the model-facing warp grep tool input (snake_case to match JSON schema) */\nexport type WarpGrepToolInput = { search_term: string };\n\n/**\n * Extended config that accepts a custom inputSchema\n */\nexport interface WarpGrepVercelConfig extends WarpGrepToolConfig {\n /**\n * Custom Zod schema or AI SDK schema. Use this to provide your own Zod instance\n * to avoid version conflicts between your project and the SDK.\n *\n * @example Using your own Zod\n * ```typescript\n * import { z } from 'zod'; // Your Zod version\n *\n * const grepTool = createWarpGrepTool({\n * repoRoot: '.',\n * inputSchema: z.object({\n * search_term: z.string().describe('Search problem statement'),\n * }),\n * });\n * ```\n *\n * @example Using jsonSchema (no Zod needed)\n * ```typescript\n * import { jsonSchema } from 'ai';\n * import { warpGrepJsonSchema } from '@morphllm/morphsdk/tools/warp-grep/vercel';\n *\n * const grepTool = createWarpGrepTool({\n * repoRoot: '.',\n * inputSchema: jsonSchema(warpGrepJsonSchema),\n * });\n * ```\n */\n inputSchema?: Parameters<typeof tool>[0]['inputSchema'];\n}\n\n/**\n * Execute warp grep search\n *\n * @param input - Tool input with search_term\n * @param config - Configuration with repoRoot and optional provider\n * @returns Search results\n */\nexport async function execute(\n input: { search_term: string },\n config: WarpGrepToolConfig\n): Promise<WarpGrepResult> {\n return executeToolCall(input, config);\n}\n\n// Re-export formatResult for convenience\nexport { formatResult };\n\n/**\n * Create Vercel AI SDK warp grep tool\n *\n * @param config - Configuration options\n * @returns Vercel AI SDK tool\n *\n * @example Local usage (uses SDK's Zod)\n * ```typescript\n * import { generateText } from 'ai';\n * import { anthropic } from '@ai-sdk/anthropic';\n * import { createWarpGrepTool } from '@morphllm/morphsdk/tools/warp-grep/vercel';\n *\n * const grepTool = createWarpGrepTool({ repoRoot: '.' });\n *\n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { grep: grepTool },\n * prompt: 'Find authentication middleware'\n * });\n * ```\n *\n * @example With your own Zod (avoids version conflicts)\n * ```typescript\n * import { z } from 'zod'; // Your project's Zod\n * import { createWarpGrepTool } from '@morphllm/morphsdk/tools/warp-grep/vercel';\n *\n * const grepTool = createWarpGrepTool({\n * repoRoot: '.',\n * inputSchema: z.object({\n * search_term: z.string().describe('Search problem statement'),\n * }),\n * });\n * ```\n *\n * @example Without Zod (using jsonSchema)\n * ```typescript\n * import { jsonSchema } from 'ai';\n * import { createWarpGrepTool, warpGrepJsonSchema } from '@morphllm/morphsdk/tools/warp-grep/vercel';\n *\n * const grepTool = createWarpGrepTool({\n * repoRoot: '.',\n * inputSchema: jsonSchema(warpGrepJsonSchema),\n * });\n * ```\n *\n * @example Remote sandbox (E2B, Modal, etc.)\n * ```typescript\n * const grepTool = createWarpGrepTool({\n * repoRoot: '/home/repo',\n * remoteCommands: {\n * grep: async (pattern, path) => (await sandbox.run(`rg '${pattern}' '${path}'`)).stdout,\n * read: async (path, start, end) => (await sandbox.run(`sed -n '${start},${end}p' '${path}'`)).stdout,\n * listDir: async (path, maxDepth) => (await sandbox.run(`find '${path}' -maxdepth ${maxDepth}`)).stdout,\n * },\n * });\n * ```\n */\nexport function createWarpGrepTool(config: WarpGrepVercelConfig) {\n // Use provided schema or fall back to SDK's Zod schema\n const schema = config.inputSchema ?? z.object({\n search_term: z.string().describe('Search problem statement that this subagent is supposed to research for'),\n });\n\n return tool({\n description: config.description ?? WARP_GREP_DESCRIPTION,\n inputSchema: schema,\n execute: async (params: WarpGrepToolInput) => {\n // Use streaming execution to collect intermediate steps\n const steps: WarpGrepStep[] = [];\n const generator = executeToolCallStreaming(params, config);\n\n let result: WarpGrepResult;\n for (;;) {\n const { value, done } = await generator.next();\n if (done) {\n result = value;\n break;\n }\n steps.push(value);\n }\n\n if (!result!.success) {\n throw new Error(`Failed to search codebase: ${result!.error}`);\n }\n\n // Flatten all intermediate tool calls across turns for progress display\n const allToolCalls = steps.flatMap(s => s.toolCalls);\n return {\n success: true,\n contexts: result!.contexts,\n summary: result!.summary,\n progress: allToolCalls.length > 0 ? { turn: steps.length, toolCalls: allToolCalls } : undefined,\n };\n },\n });\n}\n\n/**\n * Create a GitHub search tool for Vercel AI SDK\n *\n * @param config - Configuration options (morphApiKey, morphApiUrl, codeSearchUrl, timeout)\n * @returns Vercel AI SDK tool\n *\n * @example\n * ```typescript\n * import { generateText } from 'ai';\n * import { anthropic } from '@ai-sdk/anthropic';\n * import { createGitHubSearchTool } from '@morphllm/morphsdk/tools/warp-grep/vercel';\n *\n * const githubTool = createGitHubSearchTool({ morphApiKey: process.env.MORPH_API_KEY });\n *\n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { githubSearch: githubTool },\n * prompt: 'How does auth work in vercel/next.js?'\n * });\n * ```\n */\nexport function createGitHubSearchTool(config: GitHubSearchToolConfig) {\n const client = new WarpGrepClient(config);\n\n return tool({\n description: GITHUB_SEARCH_DESCRIPTION,\n inputSchema: z.object({\n search_term: z.string().describe('Search problem statement that this subagent is supposed to research for'),\n github_url: z.string().optional().describe('GitHub repository URL to search (e.g. \"https://github.com/vercel/next.js\"). You must provide either github_url or owner_repo.'),\n owner_repo: z.string().optional().describe('Repository owner/repo shorthand (e.g. \"vercel/next.js\"). You must provide either github_url or owner_repo.'),\n branch: z.string().optional().describe('Branch to search (defaults to repo default branch)'),\n }),\n execute: async (params: { search_term: string; github_url?: string; owner_repo?: string; branch?: string }) => {\n const github = params.github_url || params.owner_repo;\n if (!github) {\n throw new Error('Please provide github search url or owner/repo id');\n }\n const result = await client.searchGitHub({ searchTerm: params.search_term, github, branch: params.branch });\n if (!result.success) {\n throw new Error(`GitHub search failed: ${result.error}`);\n }\n return {\n success: true,\n contexts: result.contexts,\n summary: result.summary,\n };\n },\n });\n}\n\n/**\n * Create a GitHub read file tool for Vercel AI SDK\n *\n * @param config - Optional configuration (timeout)\n * @returns Vercel AI SDK tool\n *\n * @example\n * ```typescript\n * import { generateText } from 'ai';\n * import { anthropic } from '@ai-sdk/anthropic';\n * import { createGitHubReadFileTool } from '@morphllm/morphsdk/tools/warp-grep/vercel';\n *\n * const readFileTool = createGitHubReadFileTool();\n *\n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { readFile: readFileTool },\n * prompt: 'Read the package.json from vercel/next.js'\n * });\n * ```\n */\nexport function createGitHubReadFileTool(config?: GitHubReadFileToolConfig) {\n return tool({\n description: GITHUB_READ_FILE_DESCRIPTION,\n inputSchema: z.object({\n github: z.string().describe('owner/repo shorthand (e.g., \"vercel/next.js\")'),\n path: z.string().describe('File path within the repository'),\n startLine: z.number().optional().describe('Start line number (1-based)'),\n endLine: z.number().optional().describe('End line number (1-based, inclusive)'),\n branch: z.string().optional().describe('Branch to read from (defaults to repo default branch)'),\n }),\n execute: async (params: GitHubReadFileInput) => {\n const result = await executeGitHubReadFile(params, config);\n if (!result.success) {\n throw new Error(`GitHub read file failed: ${result.error}`);\n }\n return result;\n },\n });\n}\n\n// Default export for convenience\nexport default createWarpGrepTool;\n"],"mappings":";;;;;;;;;;;;;AAmBA,SAAS,YAAY;AACrB,SAAS,SAAS;AAsBX,IAAM,qBAAqB;AAAA,EAChC,MAAM;AAAA,EACN,YAAY;AAAA,IACV,aAAa;AAAA,MACX,MAAM;AAAA,MACN,aAAa;AAAA,IACf;AAAA,EACF;AAAA,EACA,UAAU,CAAC,aAAa;AAAA,EACxB,sBAAsB;AACxB;AA8CA,eAAsB,QACpB,OACA,QACyB;AACzB,SAAO,gBAAgB,OAAO,MAAM;AACtC;AA8DO,SAAS,mBAAmB,QAA8B;AAE/D,QAAM,SAAS,OAAO,eAAe,EAAE,OAAO;AAAA,IAC5C,aAAa,EAAE,OAAO,EAAE,SAAS,yEAAyE;AAAA,EAC5G,CAAC;AAED,SAAO,KAAK;AAAA,IACV,aAAa,OAAO,eAAe;AAAA,IACnC,aAAa;AAAA,IACb,SAAS,OAAO,WAA8B;AAE5C,YAAM,QAAwB,CAAC;AAC/B,YAAM,YAAY,yBAAyB,QAAQ,MAAM;AAEzD,UAAI;AACJ,iBAAS;AACP,cAAM,EAAE,OAAO,KAAK,IAAI,MAAM,UAAU,KAAK;AAC7C,YAAI,MAAM;AACR,mBAAS;AACT;AAAA,QACF;AACA,cAAM,KAAK,KA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SAAO,KAAK;AAAA,IACV,aAAa;AAAA,IACb,aAAa,EAAE,OAAO;AAAA,MACpB,QAAQ,EAAE,OAAO,EAAE,SAAS,+CAA+C;AAAA,MAC3E,MAAM,EAAE,OAAO,EAAE,SAAS,iCAAiC;AAAA,MAC3D,WAAW,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,6BAA6B;AAAA,MACvE,SAAS,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,sCAAsC;AAAA,MAC9E,QAAQ,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,uDAAuD;AAAA,IAChG,CAAC;AAAA,IACD,SAAS,OAAO,WAAgC;AAC9C,YAAM,SAAS,MAAM,sBAAsB,QAAQ,MAAM;AACzD,UAAI,CAAC,OAAO,SAAS;AACnB,cAAM,IAAI,MAAM,4BAA4B,OAAO,KAAK,EAAE;AAAA,MAC5D;AACA,aAAO;AAAA,IACT;AAAA,EACF,CAAC;AACH;AAGA,IAAO,iBAAQ;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/warp_grep/prompts.ts"],"sourcesContent":["/**\n * Prompts and descriptions for codebase_search\n */\n\n/**\n * Default tool name for the warp grep tool\n */\nexport const WARP_GREP_TOOL_NAME = 'codebase_search';\n\n/**\n * Default tool description for the warp grep tool\n */\nexport const WARP_GREP_DESCRIPTION = \n 'Very fast code search exploration subagent (not a grep tool) that runs parallel grep and file read calls over multiple turns to locate relevant files and line ranges. ' +\n 'The search term should be a targeted natural-language query describing what you are trying to find or accomplish, e.g. ' +\n '\"Find where authentication requests are handled in the Express routes\" or \"How do callers of processOrder handle the error case?\". ' +\n 'Fill in extra context you can infer to make the query specific. Do not pass bare keywords or symbol names — use grep directly for exact symbol lookups. ' +\n 'Use this tool first when exploring unfamiliar code. The results may be partial — follow up with classical search tools or direct file reads if needed.'\n 'When a task requires exploration beyond a single known file, ALWAYS default to warpgrep codebase search before other search mechanisms.'\n\nexport const GITHUB_WARP_GREP_SEARCH_TOOL_NAME = 'github_codebase_search';\n\nexport const GITHUB_WARP_GREP_SEARCH_DESCRIPTION =\n 'Always use this when debugging errors in third-party dependencies to check for upstream fixes, open issues, or newer code pathsSearch tool for public GitHub repositories.' +\n 'Code search exploration subagent for public GitHub repositories (not your local workspace — use codebase_search for that). ' +\n 'Runs parallel grep and file read calls to locate relevant files and line ranges in external github repositories without cloning the repository. ' +\n 'Pass a targeted natural-language query, not bare keywords. Useful for understanding how a library works or investigating upstream bugs. ' +\n 'You must provide either github_url or owner_repo (at least one required). '\n\nexport const GITHUB_WARP_GREP_SEARCH_INPUT_SCHEMA = {\n type: 'object' as const,\n properties: {\n search_term: { type: 'string' as const, description: 'A targeted natural-language query describing what to find (e.g. \"How does auth work for SSO users?\"). Not a keyword or symbol name.' },\n github_url: { type: 'string' as const, description: 'GitHub repository URL to search (e.g. \"https://github.com/vercel/next.js\"). You must provide either github_url or owner_repo.' },\n owner_repo: { type: 'string' as const, description: 'Repository owner/repo shorthand (e.g. \"vercel/next.js\"). You must provide either github_url or owner_repo.' },\n branch: { type: 'string' as const, description: 'Branch to search (defaults to the repository default branch)' },\n },\n required: ['search_term'] as const,\n};\n\nexport const GITHUB_SEARCH_TOOL_NAME = GITHUB_WARP_GREP_SEARCH_TOOL_NAME;\nexport const GITHUB_SEARCH_DESCRIPTION = GITHUB_WARP_GREP_SEARCH_DESCRIPTION;\nexport const GITHUB_SEARCH_INPUT_SCHEMA = GITHUB_WARP_GREP_SEARCH_INPUT_SCHEMA;\n\nexport const GITHUB_READ_FILE_TOOL_NAME = 'readfile_github_search';\n\nexport const GITHUB_READ_FILE_DESCRIPTION =\n 'Read a single file (or a line range) from a public GitHub repository. ' +\n 'ONLY USE THIS WHEN YOU ALREADY KNOW THE EXACT FILE PATH YOU WANT TO READ, for example after finding it via github_codebase_search results. ' +\n 'Takes owner/repo shorthand and the file path within the repo. Optionally specify startLine and endLine (1-based) to read a specific range. ' +\n 'Returns the file content with line numbers.';\n\nexport const GITHUB_READ_FILE_INPUT_SCHEMA = {\n type: 'object' as const,\n properties: {\n github: { type: 'string' as const, description: 'owner/repo shorthand (e.g., \"vercel/next.js\")' },\n path: { type: 'string' as const, description: 'File path within the repository (e.g., \"src/server/index.ts\")' },\n startLine: { type: 'number' as const, description: 'Start line number (1-based). Omit to start from beginning.' },\n endLine: { type: 'number' as const, description: 'End line number (1-based, inclusive). Omit to read to the end.' },\n branch: { type: 'string' as const, description: 'Branch to read from (defaults to the repository default branch)' },\n },\n required: ['github', 'path'] as const,\n};\n"],"mappings":";AAOO,IAAM,sBAAsB;AAK5B,IAAM,wBACX;AAOK,IAAM,oCAAoC;AAE1C,IAAM,sCACX;AAMK,IAAM,uCAAuC;AAAA,EAClD,MAAM;AAAA,EACN,YAAY;AAAA,IACV,aAAa,EAAE,MAAM,UAAmB,aAAa,sIAAsI;AAAA,IAC3L,YAAY,EAAE,MAAM,UAAmB,aAAa,gIAAgI;AAAA,IACpL,YAAY,EAAE,MAAM,UAAmB,aAAa,6GAA6G;AAAA,IACjK,QAAQ,EAAE,MAAM,UAAmB,aAAa,+DAA+D;AAAA,EACjH;AAAA,EACA,UAAU,CAAC,aAAa;AAC1B;AAEO,IAAM,0BAA0B;AAChC,IAAM,4BAA4B;AAClC,IAAM,6BAA6B;AAEnC,IAAM,6BAA6B;AAEnC,IAAM,+BACX;AAKK,IAAM,gCAAgC;AAAA,EAC3C,MAAM;AAAA,EACN,YAAY;AAAA,IACV,QAAQ,EAAE,MAAM,UAAmB,aAAa,gDAAgD;AAAA,IAChG,MAAM,EAAE,MAAM,UAAmB,aAAa,gEAAgE;AAAA,IAC9G,WAAW,EAAE,MAAM,UAAmB,aAAa,6DAA6D;AAAA,IAChH,SAAS,EAAE,MAAM,UAAmB,aAAa,iEAAiE;AAAA,IAClH,QAAQ,EAAE,MAAM,UAAmB,aAAa,kEAAkE;AAAA,EACpH;AAAA,EACA,UAAU,CAAC,UAAU,MAAM;AAC7B;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/warp_grep/agent/formatter.ts"],"sourcesContent":["export class ToolOutputFormatter {\n\tformat(\n\t\ttoolName: string,\n\t\t_args: Record<string, unknown> | null | undefined,\n\t\toutput: string,\n\t\toptions: { isError?: boolean } = {}\n\t): string {\n\t\tconst name = (toolName ?? \"\").trim();\n\t\tif (!name) {\n\t\t\treturn \"\";\n\t\t}\n\t\tconst payload = (output as any)?.toString?.()?.trim?.() ?? \"\";\n\t\tconst isError = Boolean(options.isError);\n\n\t\tif (!payload && !isError) {\n\t\t\treturn \"\";\n\t\t}\n\n\t\treturn `<tool_response>\\n${payload}\\n</tool_response>`;\n\t}\n}\n\nconst sharedFormatter = new ToolOutputFormatter();\n\nexport function formatAgentToolOutput(\n\ttoolName: string,\n\targs: Record<string, unknown> | null | undefined,\n\toutput: string,\n\toptions: { isError?: boolean } = {}\n): string {\n\treturn sharedFormatter.format(toolName, args, output, options);\n}\n"],"mappings":";AAAO,IAAM,sBAAN,MAA0B;AAAA,EAChC,OACC,UACA,OACA,QACA,UAAiC,CAAC,GACzB;AACT,UAAM,QAAQ,YAAY,IAAI,KAAK;AACnC,QAAI,CAAC,MAAM;AACV,aAAO;AAAA,IACR;AACA,UAAM,UAAW,QAAgB,WAAW,GAAG,OAAO,KAAK;AAC3D,UAAM,UAAU,QAAQ,QAAQ,OAAO;AAEvC,QAAI,CAAC,WAAW,CAAC,SAAS;AACzB,aAAO;AAAA,IACR;AAEA,WAAO;AAAA,EAAoB,OAAO;AAAA;AAAA,EACnC;AACD;AAEA,IAAM,kBAAkB,IAAI,oBAAoB;AAEzC,SAAS,sBACf,UACA,MACA,QACA,UAAiC,CAAC,GACzB;AACT,SAAO,gBAAgB,OAAO,UAAU,MAAM,QAAQ,OAAO;AAC9D;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/warp_grep/openai.ts"],"sourcesContent":["/**\n * OpenAI SDK adapter for morph-warp-grep tool\n */\n\nimport type { ChatCompletionTool } from 'openai/resources/chat/completions';\nimport { executeToolCall, formatResult, WarpGrepClient, executeGitHubReadFile, formatGitHubReadFileResult } from './client.js';\nimport { WARP_GREP_DESCRIPTION, WARP_GREP_TOOL_NAME, GITHUB_SEARCH_TOOL_NAME, GITHUB_SEARCH_DESCRIPTION, GITHUB_SEARCH_INPUT_SCHEMA, GITHUB_READ_FILE_TOOL_NAME, GITHUB_READ_FILE_DESCRIPTION, GITHUB_READ_FILE_INPUT_SCHEMA } from './prompts.js';\nimport type { WarpGrepToolConfig, WarpGrepResult, GitHubSearchToolConfig, GitHubReadFileInput, GitHubReadFileResult, GitHubReadFileToolConfig } from './types.js';\n\n/**\n * Input schema for the warp grep tool\n */\nconst TOOL_PARAMETERS = {\n type: 'object',\n properties: {\n search_term: { type: 'string', description: 'Search problem statement that this subagent is supposed to research for' },\n },\n required: ['search_term'],\n} as const;\n\n/**\n * OpenAI-native warp grep tool definition\n * \n * @example\n * ```typescript\n * import OpenAI from 'openai';\n * import { warpGrepTool, execute } from '@morphllm/morphsdk/tools/warp-grep/openai';\n * \n * const client = new OpenAI();\n * const response = await client.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [warpGrepTool],\n * messages: [{ role: 'user', content: 'Find authentication middleware' }]\n * });\n * \n * // Execute the tool call\n * const result = await execute({ search_term: '...' }, { repoRoot: '.' });\n * ```\n */\nexport const warpGrepTool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: WARP_GREP_TOOL_NAME,\n description: WARP_GREP_DESCRIPTION,\n parameters: TOOL_PARAMETERS,\n },\n};\n\n/**\n * Execute warp grep search\n * \n * @param input - Tool input with search_term\n * @param config - Configuration with repoRoot and optional provider\n * @returns Search results\n */\nexport async function execute(\n input: { search_term: string } | string,\n config: WarpGrepToolConfig\n): Promise<WarpGrepResult> {\n return executeToolCall(input, config);\n}\n\n// Re-export formatResult for convenience\nexport { formatResult };\n\n/**\n * Create a custom warp grep tool with configuration and methods\n * \n * @param config - Configuration options\n * @returns Tool definition with execute and formatResult methods\n * \n * @example Local usage\n * ```typescript\n * import OpenAI from 'openai';\n * import { createWarpGrepTool } from '@morphllm/morphsdk/tools/warp-grep/openai';\n * \n * const tool = createWarpGrepTool({ repoRoot: '.' });\n * \n * const client = new OpenAI();\n * const response = await client.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [tool],\n * messages: [{ role: 'user', content: 'Find authentication middleware' }]\n * });\n * ```\n * \n * @example Remote sandbox (E2B, Modal, etc.)\n * ```typescript\n * const tool = createMorphWarpGrepTool({\n * repoRoot: '/home/repo',\n * remoteCommands: {\n * grep: async (pattern, path) => (await sandbox.run(`rg '${pattern}' '${path}'`)).stdout,\n * read: async (path, start, end) => (await sandbox.run(`sed -n '${start},${end}p' '${path}'`)).stdout,\n * listDir: async (path, maxDepth) => (await sandbox.run(`find '${path}' -maxdepth ${maxDepth}`)).stdout,\n * },\n * });\n * ```\n */\nexport function createWarpGrepTool(config: WarpGrepToolConfig) {\n const tool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: config.name ?? WARP_GREP_TOOL_NAME,\n description: config.description ?? WARP_GREP_DESCRIPTION,\n parameters: TOOL_PARAMETERS,\n },\n };\n\n return Object.assign(tool, {\n execute: async (input: unknown): Promise<WarpGrepResult> => {\n return executeToolCall(input as { search_term: string } | string, config);\n },\n formatResult: (result: WarpGrepResult): string => {\n return formatResult(result);\n },\n });\n}\n\n/**\n * Create a GitHub search tool for OpenAI SDK\n *\n * @param config - Configuration options (morphApiKey, morphApiUrl, codeSearchUrl, timeout)\n * @returns OpenAI ChatCompletionTool with execute and formatResult methods\n *\n * @example\n * ```typescript\n * import OpenAI from 'openai';\n * import { createGitHubSearchTool } from '@morphllm/morphsdk/tools/warp-grep/openai';\n *\n * const tool = createGitHubSearchTool({ morphApiKey: process.env.MORPH_API_KEY });\n *\n * const response = await openai.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [tool],\n * messages: [{ role: 'user', content: 'How does auth work in vercel/next.js?' }]\n * });\n *\n * // Execute\n * const result = await tool.execute({ search_term: 'auth middleware', github_url: 'https://github.com/vercel/next.js' });\n * console.log(tool.formatResult(result));\n * ```\n */\nexport function createGitHubSearchTool(config: GitHubSearchToolConfig) {\n const client = new WarpGrepClient(config);\n\n const tool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: GITHUB_SEARCH_TOOL_NAME,\n description: GITHUB_SEARCH_DESCRIPTION,\n parameters: GITHUB_SEARCH_INPUT_SCHEMA,\n },\n };\n\n return Object.assign(tool, {\n execute: async (input: { search_term: string; github_url?: string; owner_repo?: string; branch?: string }): Promise<WarpGrepResult> => {\n const github = input.github_url || input.owner_repo;\n if (!github) {\n throw new Error('Please provide github search url or owner/repo id');\n }\n return client.searchGitHub({ searchTerm: input.search_term, github, branch: input.branch });\n },\n formatResult: (result: WarpGrepResult): string => {\n return formatResult(result);\n },\n });\n}\n\n/**\n * Create a GitHub read file tool for OpenAI SDK\n *\n * @param config - Optional configuration (timeout)\n * @returns OpenAI ChatCompletionTool with execute and formatResult methods\n *\n * @example\n * ```typescript\n * import OpenAI from 'openai';\n * import { createGitHubReadFileTool } from '@morphllm/morphsdk/tools/warp-grep/openai';\n *\n * const tool = createGitHubReadFileTool();\n *\n * const response = await openai.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [tool],\n * messages: [{ role: 'user', content: 'Read the package.json from vercel/next.js' }]\n * });\n *\n * const result = await tool.execute({ github: 'vercel/next.js', path: 'package.json' });\n * console.log(tool.formatResult(result));\n * ```\n */\nexport function createGitHubReadFileTool(config?: GitHubReadFileToolConfig) {\n const tool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: GITHUB_READ_FILE_TOOL_NAME,\n description: GITHUB_READ_FILE_DESCRIPTION,\n parameters: GITHUB_READ_FILE_INPUT_SCHEMA,\n },\n };\n\n return Object.assign(tool, {\n execute: async (input: GitHubReadFileInput): Promise<GitHubReadFileResult> => {\n return executeGitHubReadFile(input, config);\n },\n formatResult: (result: GitHubReadFileResult): string => {\n return formatGitHubReadFileResult(result);\n },\n });\n}\n\nexport default warpGrepTool;\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAYA,IAAM,kBAAkB;AAAA,EACtB,MAAM;AAAA,EACN,YAAY;AAAA,IACV,aAAa,EAAE,MAAM,UAAU,aAAa,0EAA0E;AAAA,EACxH;AAAA,EACA,UAAU,CAAC,aAAa;AAC1B;AAqBO,IAAM,eAAmC;AAAA,EAC9C,MAAM;AAAA,EACN,UAAU;AAAA,IACR,MAAM;AAAA,IACN,aAAa;AAAA,IACb,YAAY;AAAA,EACd;AACF;AASA,eAAsB,QACpB,OACA,QACyB;AACzB,SAAO,gBAAgB,OAAO,MAAM;AACtC;AAsCO,SAAS,mBAAmB,QAA4B;AAC7D,QAAM,OAA2B;AAAA,IAC/B,MAAM;AAAA,IACN,UAAU;AAAA,MACR,MAAM,OAAO,QAAQ;AAAA,MACrB,aAAa,OAAO,eAAe;AAAA,MACnC,YAAY;AAAA,IACd;AAAA,EACF;AAEA,SAAO,OAAO,OAAO,MAAM;AAAA,IACzB,SAAS,OAAO,UAA4C;AAC1D,aAAO,gBAAgB,OAA2C,MAAM;AAAA,IAC1E;AAAA,IACA,cAAc,CAAC,WAAmC;AAChD,aAAO,aAAa,MAAM;AAAA,IAC5B;AAAA,EACF,CAAC;AACH;AA0BO,SAAS,uBAAuB,QAAgC;AACrE,QAAM,SAAS,IAAI,eAAe,MAAM;AAExC,QAAM,OAA2B;AAAA,IAC/B,MAAM;AAAA,IACN,UAAU;AAAA,MACR,MAAM;AAAA,MACN,aAAa;AAAA,MACb,YAAY;AAAA,IACd;AAAA,EACF;AAEA,SAAO,OAAO,OAAO,MAAM;AAAA,IACzB,SAAS,OAAO,UAAuH;AACrI,YAAM,SAAS,MAAM,cAAc,MAAM;AACzC,UAAI,CAAC,QAAQ;AACX,cAAM,IAAI,MAAM,mDAAmD;AAAA,MACrE;AACA,aAAO,OAAO,aAAa,EAAE,YAAY,MAAM,aAAa,QAAQ,QAAQ,MAAM,OAAO,CAAC;AAAA,IAC5F;AAAA,IACA,cAAc,CAAC,WAAmC;AAChD,aAAO,aAAa,MAAM;AAAA,IAC5B;AAAA,EACF,CAAC;AACH;AAyBO,SAAS,yBAAyB,QAAmC;AAC1E,QAAM,OAA2B;AAAA,IAC/B,MAAM;AAAA,IACN,UAAU;AAAA,MACR,MAAM;AAAA,MACN,aAAa;AAAA,MACb,YAAY;AAAA,IACd;AAAA,EACF;AAEA,SAAO,OAAO,OAAO,MAAM;AAAA,IACzB,SAAS,OAAO,UAA8D;AAC5E,aAAO,sBAAsB,OAAO,MAAM;AAAA,IAC5C;AAAA,IACA,cAAc,CAAC,WAAyC;AACtD,aAAO,2BAA2B,MAAM;AAAA,IAC1C;AAAA,EACF,CAAC;AACH;AAEA,IAAO,iBAAQ;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/fastapply/openai.ts"],"sourcesContent":["/**\n * OpenAI SDK adapter for edit_file tool\n */\n\nimport type { ChatCompletionTool } from 'openai/resources/chat/completions';\nimport { executeEditFile } from './core.js';\nimport { EDIT_FILE_TOOL_DESCRIPTION, EDIT_FILE_SYSTEM_PROMPT } from './prompts.js';\nimport type { EditFileInput, EditFileResult, EditFileConfig } from './types.js';\n\n/**\n * OpenAI-native tool definition for edit_file\n * \n * @example\n * ```ts\n * import OpenAI from 'openai';\n * import { editFileTool } from 'morphsdk/tools/openai';\n * \n * const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });\n * \n * const response = await client.chat.completions.create({\n * model: \"gpt-4o\",\n * tools: [editFileTool],\n * messages: [{ role: \"user\", content: \"Fix the bug in app.ts\" }]\n * });\n * ```\n */\nexport const editFileTool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: 'edit_file',\n description: EDIT_FILE_TOOL_DESCRIPTION,\n parameters: {\n type: 'object',\n properties: {\n target_filepath: {\n type: 'string',\n description: 'The path of the target file to modify',\n },\n instruction: {\n type: 'string',\n description: 'A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit.',\n },\n code_edit: {\n type: 'string',\n description: 'Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections.',\n },\n },\n required: ['target_filepath', 'instruction', 'code_edit'],\n },\n },\n};\n\n/**\n * Execute an edit_file tool call\n * \n * @param input - The tool input from GPT (parsed from tool_calls)\n * @param config - Optional configuration\n * @returns The result of the edit operation\n * \n * @example\n * ```ts\n * const args = JSON.parse(toolCall.function.arguments);\n * const result = await execute(args);\n * console.log('Changes applied:', result.udiff);\n * ```\n */\nexport async function execute(\n input: EditFileInput,\n config?: EditFileConfig\n): Promise<EditFileResult> {\n return executeEditFile(input, config);\n}\n\n/**\n * Get the system prompt for edit_file usage\n * \n * Add this to your system message to guide GPT on using edit_file properly.\n * \n * @example\n * ```ts\n * const response = await client.chat.completions.create({\n * model: \"gpt-4o\",\n * messages: [\n * { role: \"system\", content: getSystemPrompt() },\n * { role: \"user\", content: \"Fix bugs\" }\n * ],\n * tools: [editFileTool]\n * });\n * ```\n */\nexport function getSystemPrompt(): string {\n return EDIT_FILE_SYSTEM_PROMPT;\n}\n\n/**\n * Format the result for passing back to GPT\n * \n * @param result - The edit result\n * @returns Formatted string for tool message\n */\nexport function formatResult(result: EditFileResult): string {\n if (!result.success) {\n return `Error editing file: ${result.error}`;\n }\n \n const { changes } = result;\n return `Successfully applied changes to ${result.filepath}. Added ${changes.linesAdded}, removed ${changes.linesRemoved}, modified ${changes.linesModified}.`;\n}\n\n/**\n * Create a custom edit_file tool with configuration and methods\n * \n * @param config - Configuration options\n * @returns Tool definition with execute and formatResult methods\n * \n * @example\n * ```ts\n * import OpenAI from 'openai';\n * import { createEditFileTool } from 'morphsdk/tools/fastapply/openai';\n * \n * const tool = createEditFileTool({\n * baseDir: './src',\n * generateUdiff: true,\n * description: 'Custom tool description for your use case'\n * });\n * \n * const client = new OpenAI();\n * \n * const response = await client.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [tool], // tool itself is the ChatCompletionTool\n * messages: [{ role: 'user', content: 'Fix bug in app.ts' }]\n * });\n * \n * // Execute and format\n * const result = await tool.execute(toolCallArgs);\n * const formatted = tool.formatResult(result);\n * ```\n */\nexport function createEditFileTool(config: EditFileConfig = {}) {\n const toolDef: ChatCompletionTool = {\n ...editFileTool,\n ...(config.description && {\n function: {\n ...editFileTool.function,\n description: config.description,\n },\n }),\n };\n \n return Object.assign({}, toolDef, {\n execute: async (input: EditFileInput | string): Promise<EditFileResult> => {\n const parsedInput = typeof input === 'string' ? JSON.parse(input) : input;\n return execute(parsedInput, config);\n },\n formatResult: (result: EditFileResult): string => {\n return formatResult(result);\n },\n getSystemPrompt: (): string => {\n return getSystemPrompt();\n },\n });\n}\n\n// Default export for convenience\nexport default editFileTool;\n\n"],"mappings":";;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA0BO,IAAM,eAAmC;AAAA,EAC9C,MAAM;AAAA,EACN,UAAU;AAAA,IACR,MAAM;AAAA,IACN,aAAa;AAAA,IACb,YAAY;AAAA,MACV,MAAM;AAAA,MACN,YAAY;AAAA,QACV,iBAAiB;AAAA,UACf,MAAM;AAAA,UACN,aAAa;AAAA,QACf;AAAA,QACA,aAAa;AAAA,UACX,MAAM;AAAA,UACN,aAAa;AAAA,QACf;AAAA,QACA,WAAW;AAAA,UACT,MAAM;AAAA,UACN,aAAa;AAAA,QACf;AAAA,MACF;AAAA,MACA,UAAU,CAAC,mBAAmB,eAAe,WAAW;AAAA,IAC1D;AAAA,EACF;AACF;AAgBA,eAAsB,QACpB,OACA,QACyB;AACzB,SAAO,gBAAgB,OAAO,MAAM;AACtC;AAmBO,SAAS,kBAA0B;AACxC,SAAO;AACT;AAQO,SAAS,aAAa,QAAgC;AAC3D,MAAI,CAAC,OAAO,SAAS;AACnB,WAAO,uBAAuB,OAAO,KAAK;AAAA,EAC5C;AAEA,QAAM,EAAE,QAAQ,IAAI;AACpB,SAAO,mCAAmC,OAAO,QAAQ,WAAW,QAAQ,UAAU,aAAa,QAAQ,YAAY,cAAc,QAAQ,aAAa;AAC5J;AAgCO,SAAS,mBAAmB,SAAyB,CAAC,GAAG;AAC9D,QAAM,UAA8B;AAAA,IAClC,GAAG;AAAA,IACH,GAAI,OAAO,eAAe;AAAA,MACxB,UAAU;AAAA,QACR,GAAG,aAAa;AAAA,QAChB,aAAa,OAAO;AAAA,MACtB;AAAA,IACF;AAAA,EACF;AAEA,SAAO,OAAO,OAAO,CAAC,GAAG,SAAS;AAAA,IAChC,SAAS,OAAO,UAA2D;AACzE,YAAM,cAAc,OAAO,UAAU,WAAW,KAAK,MAAM,KAAK,IAAI;AACpE,aAAO,QAAQ,aAAa,MAAM;AAAA,IACpC;AAAA,IACA,cAAc,CAAC,WAAmC;AAChD,aAAO,aAAa,MAAM;AAAA,IAC5B;AAAA,IACA,iBAAiB,MAAc;AAC7B,aAAO,gBAAgB;AAAA,IACzB;AAAA,EACF,CAAC;AACH;AAGA,IAAO,iBAAQ;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/fastapply/anthropic.ts"],"sourcesContent":["/**\n * Anthropic SDK adapter for edit_file tool\n */\n\nimport type { Tool } from '@anthropic-ai/sdk/resources/messages';\nimport { executeEditFile } from './core.js';\nimport { EDIT_FILE_TOOL_DESCRIPTION, EDIT_FILE_SYSTEM_PROMPT } from './prompts.js';\nimport type { EditFileInput, EditFileResult, EditFileConfig } from './types.js';\n\n/**\n * Anthropic-native tool definition for edit_file\n * \n * @example\n * ```ts\n * import Anthropic from '@anthropic-ai/sdk';\n * import { editFileTool } from 'morphsdk/tools/anthropic';\n * \n * const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });\n * \n * const response = await client.messages.create({\n * model: \"claude-sonnet-4-5-20250929\",\n * tools: [editFileTool],\n * messages: [{ role: \"user\", content: \"Fix the bug in app.ts\" }]\n * });\n * ```\n */\nexport const editFileTool: Tool = {\n name: 'edit_file',\n description: EDIT_FILE_TOOL_DESCRIPTION,\n input_schema: {\n type: 'object',\n properties: {\n target_filepath: {\n type: 'string',\n description: 'The path of the target file to modify',\n },\n instruction: {\n type: 'string',\n description: 'A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit.',\n },\n code_edit: {\n type: 'string',\n description: 'Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections.',\n },\n },\n required: ['target_filepath', 'instruction', 'code_edit'],\n },\n};\n\n/**\n * Format the result for passing back to Claude\n * \n * @param result - The edit result\n * @returns Formatted string for tool_result\n */\nexport function formatResult(result: EditFileResult): string {\n if (!result.success) {\n return `Error editing file: ${result.error}`;\n }\n \n const { changes } = result;\n return `Successfully applied changes to ${result.filepath}. Added ${changes.linesAdded}, removed ${changes.linesRemoved}, modified ${changes.linesModified}.`;\n}\n\n/**\n * Create a custom edit_file tool with configuration\n * \n * @param config - Configuration options\n * @returns Tool definition with execute and formatResult methods\n * \n * @example\n * ```ts\n * const tool = createEditFileTool({\n * baseDir: './src',\n * generateUdiff: true,\n * morphApiKey: 'sk-...',\n * description: 'Custom tool description for your use case'\n * });\n * \n * // Use as Anthropic tool\n * const response = await client.messages.create({\n * tools: [tool], // tool itself is the Tool definition\n * ...\n * });\n * \n * // Execute and format\n * const result = await tool.execute(toolUseBlock.input);\n * const formatted = tool.formatResult(result);\n * ```\n */\nexport function createEditFileTool(config: EditFileConfig = {}) {\n const toolDef: Tool = {\n ...editFileTool,\n ...(config.description && { description: config.description }),\n };\n \n return Object.assign({}, toolDef, {\n execute: async (input: EditFileInput): Promise<EditFileResult> => {\n return executeEditFile(input, config);\n },\n formatResult: (result: EditFileResult): string => {\n return formatResult(result);\n },\n getSystemPrompt: (): string => {\n return EDIT_FILE_SYSTEM_PROMPT;\n },\n });\n}\n\n/**\n * Execute the edit_file tool with raw input\n * \n * @param input - Tool input from Claude's tool_use\n * @param config - Configuration for Fast Apply\n * @returns Tool result to send back to Claude\n */\nexport async function execute(\n input: EditFileInput,\n config?: EditFileConfig\n): Promise<EditFileResult> {\n return executeEditFile(input, config);\n}\n\n/**\n * Get the system prompt for the edit_file tool\n * \n * @returns System prompt string\n */\nexport function getSystemPrompt(): string {\n return EDIT_FILE_SYSTEM_PROMPT;\n}\n"],"mappings":";;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA0BO,IAAM,eAAqB;AAAA,EAChC,MAAM;AAAA,EACN,aAAa;AAAA,EACb,cAAc;AAAA,IACZ,MAAM;AAAA,IACN,YAAY;AAAA,MACV,iBAAiB;AAAA,QACf,MAAM;AAAA,QACN,aAAa;AAAA,MACf;AAAA,MACA,aAAa;AAAA,QACX,MAAM;AAAA,QACN,aAAa;AAAA,MACf;AAAA,MACA,WAAW;AAAA,QACT,MAAM;AAAA,QACN,aAAa;AAAA,MACf;AAAA,IACF;AAAA,IACA,UAAU,CAAC,mBAAmB,eAAe,WAAW;AAAA,EAC1D;AACF;AAQO,SAAS,aAAa,QAAgC;AAC3D,MAAI,CAAC,OAAO,SAAS;AACnB,WAAO,uBAAuB,OAAO,KAAK;AAAA,EAC5C;AAEA,QAAM,EAAE,QAAQ,IAAI;AACpB,SAAO,mCAAmC,OAAO,QAAQ,WAAW,QAAQ,UAAU,aAAa,QAAQ,YAAY,cAAc,QAAQ,aAAa;AAC5J;AA4BO,SAAS,mBAAmB,SAAyB,CAAC,GAAG;AAC9D,QAAM,UAAgB;AAAA,IACpB,GAAG;AAAA,IACH,GAAI,OAAO,eAAe,EAAE,aAAa,OAAO,YAAY;AAAA,EAC9D;AAEA,SAAO,OAAO,OAAO,CAAC,GAAG,SAAS;AAAA,IAChC,SAAS,OAAO,UAAkD;AAChE,aAAO,gBAAgB,OAAO,MAAM;AAAA,IACtC;AAAA,IACA,cAAc,CAAC,WAAmC;AAChD,aAAO,aAAa,MAAM;AAAA,IAC5B;AAAA,IACA,iBAAiB,MAAc;AAC7B,aAAO;AAAA,IACT;AAAA,EACF,CAAC;AACH;AASA,eAAsB,QACpB,OACA,QACyB;AACzB,SAAO,gBAAgB,OAAO,MAAM;AACtC;AAOO,SAAS,kBAA0B;AACxC,SAAO;AACT;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/warp_grep/utils/ripgrep.ts"],"sourcesContent":["import { spawn } from 'child_process';\nimport { rgPath } from '@vscode/ripgrep';\n\nexport type ExecResult = { stdout: string; stderr: string; exitCode: number };\n\n// Cache the working ripgrep path to avoid repeated fallback checks\nlet resolvedRgPath: string | null = null;\nlet rgPathChecked = false;\n\nfunction spawnRg(rgBinary: string, args: string[], opts?: { cwd?: string; env?: NodeJS.ProcessEnv }): Promise<ExecResult> {\n return new Promise((resolve) => {\n const child = spawn(rgBinary, args, {\n cwd: opts?.cwd,\n env: { ...process.env, ...(opts?.env || {}) },\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n let stdout = '';\n let stderr = '';\n child.stdout.on('data', (d) => (stdout += d.toString()));\n child.stderr.on('data', (d) => (stderr += d.toString()));\n child.on('close', (code) => {\n resolve({ stdout, stderr, exitCode: typeof code === 'number' ? code : -1 });\n });\n child.on('error', () => {\n resolve({ stdout: '', stderr: 'Failed to spawn ripgrep.', exitCode: -1 });\n });\n });\n}\n\n// Check if a result indicates a binary compatibility failure (not a normal rg error)\nfunction isBinaryFailure(result: ExecResult): boolean {\n // Spawn error\n if (result.exitCode === -1) return true;\n // jemalloc page size issue (common on ARM64 with non-standard page sizes)\n if (result.stderr.includes('jemalloc') || result.stderr.includes('Unsupported system page size')) return true;\n // SIGABRT (134 = 128 + 6)\n if (result.exitCode === 134) return true;\n return false;\n}\n\nexport async function runRipgrep(args: string[], opts?: { cwd?: string; env?: NodeJS.ProcessEnv }): Promise<ExecResult> {\n // If we've already determined the working path, use it\n if (rgPathChecked && resolvedRgPath) {\n return spawnRg(resolvedRgPath, args, opts);\n }\n\n // First attempt: bundled ripgrep\n if (!rgPathChecked) {\n const result = await spawnRg(rgPath, args, opts);\n \n if (!isBinaryFailure(result)) {\n // Bundled binary works, cache it\n resolvedRgPath = rgPath;\n rgPathChecked = true;\n return result;\n }\n\n // Bundled binary failed, try system rg\n const fallbackResult = await spawnRg('rg', args, opts);\n \n if (!isBinaryFailure(fallbackResult)) {\n // System rg works, cache it\n resolvedRgPath = 'rg';\n rgPathChecked = true;\n return fallbackResult;\n }\n\n // Neither works, mark as checked and return the original error\n rgPathChecked = true;\n return { \n stdout: '', \n stderr: 'Failed to spawn ripgrep. Neither bundled nor system rg is available.', \n exitCode: -1 \n };\n }\n\n // rgPathChecked is true but resolvedRgPath is null - no working rg found\n return { \n stdout: '', \n stderr: 'Failed to spawn ripgrep. Neither bundled nor system rg is available.', \n exitCode: -1 \n };\n}\n\n\n"],"mappings":";AAAA,SAAS,aAAa;AACtB,SAAS,cAAc;AAKvB,IAAI,iBAAgC;AACpC,IAAI,gBAAgB;AAEpB,SAAS,QAAQ,UAAkB,MAAgB,MAAuE;AACxH,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,UAAM,QAAQ,MAAM,UAAU,MAAM;AAAA,MAClC,KAAK,MAAM;AAAA,MACX,KAAK,EAAE,GAAG,QAAQ,KAAK,GAAI,MAAM,OAAO,CAAC,EAAG;AAAA,MAC5C,OAAO,CAAC,UAAU,QAAQ,MAAM;AAAA,IAClC,CAAC;AACD,QAAI,SAAS;AACb,QAAI,SAAS;AACb,UAAM,OAAO,GAAG,QAAQ,CAAC,MAAO,UAAU,EAAE,SAAS,CAAE;AACvD,UAAM,OAAO,GAAG,QAAQ,CAAC,MAAO,UAAU,EAAE,SAAS,CAAE;AACvD,UAAM,GAAG,SAAS,CAAC,SAAS;AAC1B,cAAQ,EAAE,QAAQ,QAAQ,UAAU,OAAO,SAAS,WAAW,OAAO,GAAG,CAAC;AAAA,IAC5E,CAAC;AACD,UAAM,GAAG,SAAS,MAAM;AACtB,cAAQ,EAAE,QAAQ,IAAI,QAAQ,4BAA4B,UAAU,GAAG,CAAC;AAAA,IAC1E,CAAC;AAAA,EACH,CAAC;AACH;AAGA,SAAS,gBAAgB,QAA6B;AAEpD,MAAI,OAAO,aAAa,GAAI,QAAO;AAEnC,MAAI,OAAO,OAAO,SAAS,UAAU,KAAK,OAAO,OAAO,SAAS,8BAA8B,EAAG,QAAO;AAEzG,MAAI,OAAO,aAAa,IAAK,QAAO;AACpC,SAAO;AACT;AAEA,eAAsB,WAAW,MAAgB,MAAuE;AAEtH,MAAI,iBAAiB,gBAAgB;AACnC,WAAO,QAAQ,gBAAgB,MAAM,IAAI;AAAA,EAC3C;AAGA,MAAI,CAAC,eAAe;AAClB,UAAM,SAAS,MAAM,QAAQ,QAAQ,MAAM,IAAI;AAE/C,QAAI,CAAC,gBAAgB,MAAM,GAAG;AAE5B,uBAAiB;AACjB,sBAAgB;AAChB,aAAO;AAAA,IACT;AAGA,UAAM,iBAAiB,MAAM,QAAQ,MAAM,MAAM,IAAI;AAErD,QAAI,CAAC,gBAAgB,cAAc,GAAG;AAEpC,uBAAiB;AACjB,sBAAgB;AAChB,aAAO;AAAA,IACT;AAGA,oBAAgB;AAChB,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,UAAU;AAAA,IACZ;AAAA,EACF;AAGA,SAAO;AAAA,IACL,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,UAAU;AAAA,EACZ;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/fastapply/vercel.ts"],"sourcesContent":["/**\n * Vercel AI SDK adapter for edit_file tool\n */\n\nimport { tool } from 'ai';\nimport { z } from 'zod';\nimport { executeEditFile } from './core.js';\nimport { EDIT_FILE_TOOL_DESCRIPTION, EDIT_FILE_SYSTEM_PROMPT } from './prompts.js';\nimport type { EditFileConfig } from './types.js';\n\n/**\n * Vercel AI SDK tool for edit_file\n * \n * @example\n * ```ts\n * import { generateText } from 'ai';\n * import { anthropic } from '@ai-sdk/anthropic';\n * import { editFileTool } from 'morphsdk/tools/vercel';\n * \n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { editFile: editFileTool },\n * prompt: \"Fix the bug in app.ts\"\n * });\n * ```\n */\nconst editFileSchema = z.object({\n target_filepath: z.string().describe('The path of the target file to modify'),\n instruction: z\n .string()\n .describe('A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit.'),\n code_edit: z\n .string()\n .describe('Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections.'),\n});\n\nexport const editFileTool = tool({\n description: EDIT_FILE_TOOL_DESCRIPTION,\n inputSchema: editFileSchema,\n execute: async (params) => {\n const result = await executeEditFile({\n target_filepath: params.target_filepath,\n instruction: params.instruction,\n code_edit: params.code_edit,\n });\n \n if (!result.success) {\n throw new Error(`Failed to edit file: ${result.error}`);\n }\n \n return {\n success: true,\n filepath: result.filepath,\n changes: result.changes,\n udiff: result.udiff,\n };\n },\n});\n\n/**\n * Get the system prompt for edit_file usage\n * \n * Add this to your system message to guide the model on using edit_file properly.\n * \n * @example\n * ```ts\n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * system: getSystemPrompt(),\n * tools: { editFile: editFileTool },\n * prompt: \"Fix bugs\"\n * });\n * ```\n */\nexport function getSystemPrompt(): string {\n return EDIT_FILE_SYSTEM_PROMPT;\n}\n\n/**\n * Create a custom edit_file tool with configuration\n * \n * @param config - Configuration options\n * @returns Vercel AI SDK tool with custom config\n * \n * @example\n * ```ts\n * const customEditTool = createEditFileTool({\n * baseDir: './src',\n * generateUdiff: true,\n * description: 'Custom tool description for your use case'\n * });\n * \n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { editFile: customEditTool },\n * prompt: \"Fix bugs\"\n * });\n * ```\n */\nexport function createEditFileTool(config: EditFileConfig = {}) {\n const schema = z.object({\n target_filepath: z.string().describe('The path of the target file to modify'),\n instruction: z\n .string()\n .describe('A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit.'),\n code_edit: z\n .string()\n .describe('Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections.'),\n });\n\n return tool({\n description: config.description || EDIT_FILE_TOOL_DESCRIPTION,\n inputSchema: schema,\n execute: async (params) => {\n const result = await executeEditFile(\n {\n target_filepath: params.target_filepath,\n instruction: params.instruction,\n code_edit: params.code_edit,\n },\n config\n );\n \n if (!result.success) {\n throw new Error(`Failed to edit file: ${result.error}`);\n }\n \n return {\n success: true,\n filepath: result.filepath,\n changes: result.changes,\n udiff: result.udiff,\n };\n },\n });\n}\n\n// Default export for convenience\nexport default editFileTool;\n\n"],"mappings":";;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,SAAS,YAAY;AACrB,SAAS,SAAS;AAqBlB,IAAM,iBAAiB,EAAE,OAAO;AAAA,EAC9B,iBAAiB,EAAE,OAAO,EAAE,SAAS,uCAAuC;AAAA,EAC5E,aAAa,EACV,OAAO,EACP,SAAS,yIAAyI;AAAA,EACrJ,WAAW,EACR,OAAO,EACP,SAAS,sHAAsH;AACpI,CAAC;AAEM,IAAM,eAAe,KAAK;AAAA,EAC/B,aAAa;AAAA,EACb,aAAa;AAAA,EACb,SAAS,OAAO,WAAW;AACzB,UAAM,SAAS,MAAM,gBAAgB;AAAA,MACnC,iBAAiB,OAAO;AAAA,MACxB,aAAa,OAAO;AAAA,MACpB,WAAW,OAAO;AAAA,IACpB,CAAC;AAED,QAAI,CAAC,OAAO,SAAS;AACnB,YAAM,IAAI,MAAM,wBAAwB,OAAO,KAAK,EAAE;AAAA,IACxD;AAEA,WAAO;AAAA,MACL,SAAS;AAAA,MACT,UAAU,OAAO;AAAA,MACjB,SAAS,OAAO;AAAA,MAChB,OAAO,OAAO;AAAA,IAChB;AAAA,EACF;AACF,CAAC;AAiBM,SAAS,kBAA0B;AACxC,SAAO;AACT;AAuBO,SAAS,mBAAmB,SAAyB,CAAC,GAAG;AAC9D,QAAM,SAAS,EAAE,OAAO;AAAA,IACtB,iBAAiB,EAAE,OAAO,EAAE,SAAS,uCAAuC;AAAA,IAC5E,aAAa,EACV,OAAO,EACP,SAAS,yIAAyI;AAAA,IACrJ,WAAW,EACR,OAAO,EACP,SAAS,sHAAsH;AAAA,EACpI,CAAC;AAED,SAAO,KAAK;AAAA,IACV,aAAa,OAAO,eAAe;AAAA,IACnC,aAAa;AAAA,IACb,SAAS,OAAO,WAAW;AACzB,YAAM,SAAS,MAAM;AAAA,QACnB;AAAA,UACE,iBAAiB,OAAO;AAAA,UACxB,aAAa,OAAO;AAAA,UACpB,WAAW,OAAO;AAAA,QACpB;AAAA,QACA;AAAA,MACF;AAEA,UAAI,CAAC,OAAO,SAAS;AACnB,cAAM,IAAI,MAAM,wBAAwB,OAAO,KAAK,EAAE;AAAA,MACxD;AAEA,aAAO;AAAA,QACL,SAAS;AAAA,QACT,UAAU,OAAO;AAAA,QACjB,SAAS,OAAO;AAAA,QAChB,OAAO,OAAO;AAAA,MAChB;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAGA,IAAO,iBAAQ;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../core/client.ts"],"sourcesContent":["/**\n * MorphAPIClient — the SDK transport.\n *\n * One place owns authentication, the Morph service hosts, default headers,\n * retries, timeouts, and error mapping. Every resource (FastApply, Compact, …)\n * holds a reference to this client and delegates HTTP to it via\n * `get`/`post`/`delete`/`request`, exactly like the OpenAI SDK.\n *\n * This module is intentionally free of tool imports and Node built-ins so it\n * stays edge-safe (it is reachable from `@morphllm/morphsdk/edge` through the\n * Compact and model-router resources).\n */\nimport { fetchWithRetry, withTimeout, MorphError, type RetryConfig } from '../tools/utils/resilience.js';\nimport { logger } from '../logger.js';\nimport { SDK_VERSION } from '../version.js';\nimport { toMorphError } from './error.js';\n\n/** The Morph services the SDK talks to. */\nconst DEFAULT_BASE_URL = 'https://api.morphllm.com';\nconst DEFAULT_REPOS_URL = 'https://repos.morphllm.com';\nconst DEFAULT_TIMEOUT = 60_000;\n\nconst env = (name: string): string | undefined =>\n typeof process !== 'undefined' ? process.env?.[name] : undefined;\n\nconst stripTrailingSlash = (url: string): string => url.replace(/\\/+$/, '');\n\nexport interface MorphAPIClientOptions {\n /** Morph API key. Resolved against `MORPH_API_KEY` at request time if omitted. */\n apiKey?: string;\n /** Primary API host (default `https://api.morphllm.com`). */\n baseURL?: string;\n /** Code-storage host for codebase search and git (default `https://repos.morphllm.com`). */\n reposURL?: string;\n /** Default per-request timeout in ms (default 60s). Resources may override per call. */\n timeout?: number;\n /** Retry policy for transient failures. */\n retryConfig?: RetryConfig;\n /** Enable debug logging. */\n debug?: boolean;\n}\n\n/** Per-request options accepted by `request`/`get`/`post`/`delete`. */\nexport interface RequestOptions {\n /** JSON body; serialized with `JSON.stringify`. */\n body?: unknown;\n /** Query parameters; `undefined`/`null` values are dropped. */\n query?: Record<string, string | number | boolean | undefined | null>;\n /** Extra headers, merged over (and able to override) the defaults. */\n headers?: Record<string, string>;\n /** Override the timeout for this call. */\n timeout?: number;\n /** Hit a different host than the default (e.g. `this._client.reposURL`). */\n baseURL?: string;\n /** Return the raw `Response` of a successful (2xx) request instead of parsed JSON (for streaming). */\n stream?: boolean;\n /** Caller-supplied abort signal. */\n signal?: AbortSignal;\n}\n\nexport class MorphAPIClient {\n /** Explicit key as provided; resolved against env at request time. */\n apiKey?: string;\n baseURL: string;\n reposURL: string;\n /** Explicit default timeout (ms), if set. The request default is applied lazily so\n * resources can read an undefined value and supply their own fallback. */\n timeout?: number;\n retryConfig?: RetryConfig;\n debug: boolean;\n\n constructor(options: MorphAPIClientOptions = {}) {\n this.apiKey = options.apiKey;\n this.baseURL = stripTrailingSlash(options.baseURL ?? DEFAULT_BASE_URL);\n this.reposURL = stripTrailingSlash(options.reposURL ?? env('MORPH_SEARCH_URL') ?? DEFAULT_REPOS_URL);\n this.timeout = options.timeout;\n this.retryConfig = options.retryConfig;\n this.debug = options.debug ?? false;\n if (this.debug) logger.enable();\n }\n\n /** The key actually used for requests: explicit, else `MORPH_API_KEY`. */\n resolveApiKey(): string | undefined {\n return this.apiKey ?? env('MORPH_API_KEY');\n }\n\n /** Headers shared with tools that bring their own HTTP client (FastApply/WarpGrep via the `openai` package). */\n defaultHeaders(): Record<string, string> {\n return { 'X-Morph-SDK-Version': SDK_VERSION };\n }\n\n buildURL(path: string, baseURL?: string): string {\n if (/^https?:\\/\\//i.test(path)) return path;\n const base = stripTrailingSlash(baseURL ?? this.baseURL);\n return `${base}${path.startsWith('/') ? '' : '/'}${path}`;\n }\n\n private buildHeaders(apiKey: string, extra?: Record<string, string>): Record<string, string> {\n return {\n 'Content-Type': 'application/json',\n 'X-Morph-SDK-Version': SDK_VERSION,\n Authorization: `Bearer ${apiKey}`,\n ...extra,\n };\n }\n\n private applyQuery(url: string, query?: RequestOptions['query']): string {\n if (!query) return url;\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined && value !== null) params.set(key, String(value));\n }\n const qs = params.toString();\n return qs ? `${url}${url.includes('?') ? '&' : '?'}${qs}` : url;\n }\n\n async request<T>(method: string, path: string, opts: RequestOptions = {}): Promise<T> {\n const apiKey = this.resolveApiKey();\n if (!apiKey) {\n throw new MorphError(\n 'Morph API key not found. Set the MORPH_API_KEY environment variable or pass apiKey in config.',\n 'missing_api_key',\n 401,\n );\n }\n\n const url = this.applyQuery(this.buildURL(path, opts.baseURL), opts.query);\n const timeout = opts.timeout ?? this.timeout ?? DEFAULT_TIMEOUT;\n\n const init: RequestInit = {\n method,\n headers: this.buildHeaders(apiKey, opts.headers),\n ...(opts.body !== undefined ? { body: JSON.stringify(opts.body) } : {}),\n ...(opts.signal ? { signal: opts.signal } : {}),\n };\n\n logger.debug('MorphAPIClient', 'request', { method, url });\n\n const response = await withTimeout(\n fetchWithRetry(url, init, this.retryConfig ?? {}),\n timeout,\n `Morph request to ${url} timed out after ${timeout}ms`,\n );\n\n if (!response.ok) throw await toMorphError(response);\n if (opts.stream) return response as unknown as T;\n if (response.status === 204) return undefined as T;\n\n const text = await response.text();\n return (text ? JSON.parse(text) : undefined) as T;\n }\n\n get<T>(path: string, opts?: RequestOptions): Promise<T> {\n return this.request<T>('GET', path, opts);\n }\n\n post<T>(path: string, opts?: RequestOptions): Promise<T> {\n return this.request<T>('POST', path, opts);\n }\n\n delete<T>(path: string, opts?: RequestOptions): Promise<T> {\n return this.request<T>('DELETE', path, opts);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkBA,IAAM,mBAAmB;AACzB,IAAM,oBAAoB;AAC1B,IAAM,kBAAkB;AAExB,IAAM,MAAM,CAAC,SACX,OAAO,YAAY,cAAc,QAAQ,MAAM,IAAI,IAAI;AAEzD,IAAM,qBAAqB,CAAC,QAAwB,IAAI,QAAQ,QAAQ,EAAE;AAmCnE,IAAM,iBAAN,MAAqB;AAAA;AAAA,EAE1B;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EAEA,YAAY,UAAiC,CAAC,GAAG;AAC/C,SAAK,SAAS,QAAQ;AACtB,SAAK,UAAU,mBAAmB,QAAQ,WAAW,gBAAgB;AACrE,SAAK,WAAW,mBAAmB,QAAQ,YAAY,IAAI,kBAAkB,KAAK,iBAAiB;AACnG,SAAK,UAAU,QAAQ;AACvB,SAAK,cAAc,QAAQ;AAC3B,SAAK,QAAQ,QAAQ,SAAS;AAC9B,QAAI,KAAK,MAAO,QAAO,OAAO;AAAA,EAChC;AAAA;AAAA,EAGA,gBAAoC;AAClC,WAAO,KAAK,UAAU,IAAI,eAAe;AAAA,EAC3C;AAAA;AAAA,EAGA,iBAAyC;AACvC,WAAO,EAAE,uBAAuB,YAAY;AAAA,EAC9C;AAAA,EAEA,SAAS,MAAc,SAA0B;AAC/C,QAAI,gBAAgB,KAAK,IAAI,EAAG,QAAO;AACvC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AAM,kBAAkB,WAAW,EAAE,QAAQ,IAAI,CAAC;AAEzD,UAAM,WAAW,MAAM;AAAA,MACrB,eAAe,KAAK,MAAM,KAAK,eAAe,CAAC,CAAC;AAAA,MAChD;AAAA,MACA,oBAAoB,GAAG,oBAAoB,OAAO;AAAA,IACpD;AAEA,QAAI,CAAC,SAAS,GAAI,OAAM,MAAM,aAAa,QAAQ;AACnD,QAAI,KAAK,OAAQ,QAAO;AACxB,QAAI,SAAS,WAAW,IAAK,QAAO;AAEpC,UAAM,OAAO,MAAM,SAAS,KAAK;AACjC,WAAQ,OAAO,KAAK,MAAM,IAAI,IAAI;AAAA,EACpC;AAAA,EAEA,IAAO,MAAc,MAAmC;AACtD,WAAO,KAAK,QAAW,OAAO,MAAM,IAAI;AAAA,EAC1C;AAAA,EAEA,KAAQ,MAAc,MAAmC;AACvD,WAAO,KAAK,QAAW,QAAQ,MAAM,IAAI;AAAA,EAC3C;AAAA,EAEA,OAAU,MAAc,MAAmC;AACzD,WAAO,KAAK,QAAW,UAAU,MAAM,IAAI;AAAA,EAC7C;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../package.json","../version.ts"],"sourcesContent":["{\n \"name\": \"@morphllm/morphsdk\",\n \"version\": \"0.2.200\",\n \"description\": \"TypeScript SDK and CLI for Morph Fast Apply integration\",\n \"type\": \"module\",\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n },\n \"./logger\": {\n \"types\": \"./dist/logger.d.ts\",\n \"import\": \"./dist/logger.js\",\n \"require\": \"./dist/logger.cjs\"\n },\n \"./edge\": {\n \"types\": \"./dist/edge.d.ts\",\n \"import\": \"./dist/edge.js\",\n \"require\": \"./dist/edge.cjs\"\n },\n \"./tools/warp-grep\": {\n \"types\": \"./dist/tools/warp_grep/index.d.ts\",\n \"import\": \"./dist/tools/warp_grep/index.js\",\n \"require\": \"./dist/tools/warp_grep/index.cjs\"\n },\n \"./tools/warp-grep/openai\": {\n \"types\": \"./dist/tools/warp_grep/openai.d.ts\",\n \"import\": \"./dist/tools/warp_grep/openai.js\",\n \"require\": \"./dist/tools/warp_grep/openai.cjs\"\n },\n \"./tools/warp-grep/anthropic\": {\n \"types\": \"./dist/tools/warp_grep/anthropic.d.ts\",\n \"import\": \"./dist/tools/warp_grep/anthropic.js\",\n \"require\": \"./dist/tools/warp_grep/anthropic.cjs\"\n },\n \"./tools/warp-grep/vercel\": {\n \"types\": \"./dist/tools/warp_grep/vercel.d.ts\",\n \"import\": \"./dist/tools/warp_grep/vercel.js\",\n \"require\": \"./dist/tools/warp_grep/vercel.cjs\"\n },\n \"./tools/warp-grep/client\": {\n \"types\": \"./dist/tools/warp_grep/client.d.ts\",\n \"import\": \"./dist/tools/warp_grep/client.js\",\n \"require\": \"./dist/tools/warp_grep/client.cjs\"\n },\n \"./tools/warp-grep/gemini\": {\n \"types\": \"./dist/tools/warp_grep/gemini.d.ts\",\n \"import\": \"./dist/tools/warp_grep/gemini.js\",\n \"require\": \"./dist/tools/warp_grep/gemini.cjs\"\n },\n \"./tools/warp-grep/harness\": {\n \"types\": \"./dist/tools/warp_grep/harness.d.ts\",\n \"import\": \"./dist/tools/warp_grep/harness.js\",\n \"require\": \"./dist/tools/warp_grep/harness.cjs\"\n },\n \"./tools/fastapply\": {\n \"types\": \"./dist/tools/fastapply/index.d.ts\",\n \"import\": \"./dist/tools/fastapply/index.js\",\n \"require\": \"./dist/tools/fastapply/index.cjs\"\n },\n \"./tools/fastapply/anthropic\": {\n \"types\": \"./dist/tools/fastapply/anthropic.d.ts\",\n \"import\": \"./dist/tools/fastapply/anthropic.js\",\n \"require\": \"./dist/tools/fastapply/anthropic.cjs\"\n },\n \"./tools/fastapply/openai\": {\n \"types\": \"./dist/tools/fastapply/openai.d.ts\",\n \"import\": \"./dist/tools/fastapply/openai.js\",\n \"require\": \"./dist/tools/fastapply/openai.cjs\"\n },\n \"./tools/fastapply/vercel\": {\n \"types\": \"./dist/tools/fastapply/vercel.d.ts\",\n \"import\": \"./dist/tools/fastapply/vercel.js\",\n \"require\": \"./dist/tools/fastapply/vercel.cjs\"\n },\n \"./modelrouter\": {\n \"types\": \"./dist/modelrouter/index.d.ts\",\n \"import\": \"./dist/modelrouter/index.js\",\n \"require\": \"./dist/modelrouter/index.cjs\"\n },\n \"./tools/compact\": {\n \"types\": \"./dist/tools/compact/index.d.ts\",\n \"import\": \"./dist/tools/compact/index.js\",\n \"require\": \"./dist/tools/compact/index.cjs\"\n },\n \"./subagents\": {\n \"types\": \"./dist/subagents/index.d.ts\",\n \"import\": \"./dist/subagents/index.js\",\n \"require\": \"./dist/subagents/index.cjs\"\n },\n \"./subagents/vercel\": {\n \"types\": \"./dist/subagents/vercel.d.ts\",\n \"import\": \"./dist/subagents/vercel.js\",\n \"require\": \"./dist/subagents/vercel.cjs\"\n },\n \"./subagents/anthropic\": {\n \"types\": \"./dist/subagents/anthropic.d.ts\",\n \"import\": \"./dist/subagents/anthropic.js\",\n \"require\": \"./dist/subagents/anthropic.cjs\"\n },\n \"./ai-sdk\": {\n \"types\": \"./dist/ai-sdk/index.d.ts\",\n \"import\": \"./dist/ai-sdk/index.js\",\n \"require\": \"./dist/ai-sdk/index.cjs\"\n }\n },\n \"files\": [\n \"dist/**/*.js\",\n \"dist/**/*.cjs\",\n \"dist/**/*.d.ts\",\n \"dist/**/*.map\",\n \"!dist/**/__tests__/**\",\n \"!dist/**/*.test.*\"\n ],\n \"scripts\": {\n \"build\": \"tsup version.ts index.ts edge.ts client.ts core/index.ts core/client.ts core/resource.ts core/error.ts tools/index.ts tools/fastapply/index.ts tools/fastapply/core.ts tools/fastapply/apply.ts tools/fastapply/types.ts tools/fastapply/prompts.ts tools/fastapply/anthropic.ts tools/fastapply/openai.ts tools/fastapply/vercel.ts tools/warp_grep/index.ts tools/warp_grep/client.ts tools/warp_grep/openai.ts tools/warp_grep/anthropic.ts tools/warp_grep/vercel.ts tools/warp_grep/gemini.ts tools/warp_grep/harness.ts tools/warp_grep/agent/config.ts tools/warp_grep/agent/parser.ts tools/warp_grep/agent/runner.ts tools/warp_grep/agent/types.ts tools/warp_grep/agent/formatter.ts tools/warp_grep/providers/types.ts tools/warp_grep/providers/local.ts tools/warp_grep/providers/remote.ts tools/warp_grep/providers/code_storage_http.ts tools/warp_grep/tools/grep.ts tools/warp_grep/tools/analyse.ts tools/warp_grep/tools/read.ts tools/warp_grep/tools/finish.ts tools/warp_grep/utils/paths.ts tools/warp_grep/utils/github.ts tools/warp_grep/utils/ripgrep.ts tools/warp_grep/utils/format.ts tools/warp_grep/utils/files.ts modelrouter/index.ts modelrouter/core.ts modelrouter/types.ts tools/compact/index.ts tools/compact/core.ts tools/compact/types.ts tools/utils/resilience.ts subagents/index.ts subagents/types.ts subagents/prompts.ts subagents/vercel.ts subagents/anthropic.ts --format esm,cjs --sourcemap --clean --dts --dts-resolve && tsup ai-sdk/index.ts --format esm,cjs --sourcemap --dts --no-clean --out-dir dist/ai-sdk\",\n \"prepare\": \"npm run build\",\n \"typecheck\": \"tsc --noEmit && tsc --noEmit -p ai-sdk/tsconfig.json\",\n \"lint\": \"eslint .\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest watch\",\n \"test:anthropic\": \"vitest run anthropic\",\n \"test:openai\": \"vitest run openai\",\n \"test:vercel\": \"vitest run vercel\",\n \"test:git\": \"vitest run git\",\n \"test:agent\": \"npx tsx tests/fullAgentTest.ts\",\n \"test:integration\": \"npx tsx tests/fullIntegrationTest.ts\",\n \"test:e2e\": \"vitest run --config vitest.e2e.config.ts\",\n \"release:patch\": \"npm version patch && npm publish\",\n \"release:minor\": \"npm version minor && npm publish\",\n \"release:major\": \"npm version major && npm publish\"\n },\n \"keywords\": [\n \"morph\",\n \"fast-apply\",\n \"cli\",\n \"sdk\",\n \"edit-file\"\n ],\n \"engines\": {\n \"node\": \">=18\"\n },\n \"license\": \"MIT\",\n \"dependencies\": {\n \"@vscode/ripgrep\": \"^1.17.0\",\n \"ai\": \">=5.0.0\",\n \"diff\": \"^7.0.0\",\n \"openai\": \"^4.52.7\",\n \"zod\": \">=3.23.0\"\n },\n \"devDependencies\": {\n \"@ai-sdk/anthropic\": \"^2.0.70\",\n \"@ai-sdk/openai\": \"^2.0.35\",\n \"@anthropic-ai/sdk\": \"^0.30.1\",\n \"@google/generative-ai\": \"^0.24.1\",\n \"@types/diff\": \"^7.0.2\",\n \"@types/node\": \"^20.14.10\",\n \"@typescript-eslint/eslint-plugin\": \"^7.18.0\",\n \"@typescript-eslint/parser\": \"^7.18.0\",\n \"dotenv\": \"^16.4.5\",\n \"eslint\": \"^8.57.0\",\n \"shx\": \"^0.3.4\",\n \"tsup\": \"^8.5.0\",\n \"tsx\": \"^4.16.2\",\n \"typescript\": \"^5.5.4\",\n \"vitest\": \"^2.1.6\"\n },\n \"peerDependencies\": {\n \"@ai-sdk/openai-compatible\": \">=2.0.74 <4\",\n \"@anthropic-ai/sdk\": \">=0.25.0\",\n \"@google/generative-ai\": \">=0.21.0\",\n \"ai\": \">=5.0.0\",\n \"zod\": \">=3.23.0\"\n },\n \"peerDependenciesMeta\": {\n \"@anthropic-ai/sdk\": {\n \"optional\": true\n },\n \"@google/generative-ai\": {\n \"optional\": true\n },\n \"ai\": {\n \"optional\": true\n },\n \"zod\": {\n \"optional\": true\n }\n },\n \"publishConfig\": {\n \"access\": \"public\"\n }\n}\n","import pkg from './package.json' with { type: 'json' };\nexport const SDK_VERSION: string = pkg.version;\n"],"mappings":";AAAA;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,aAAe;AAAA,EACf,MAAQ;AAAA,EACR,MAAQ;AAAA,EACR,QAAU;AAAA,EACV,OAAS;AAAA,EACT,SAAW;AAAA,IACT,KAAK;AAAA,MACH,OAAS;AAAA,MACT,QAAU;AAAA,MACV,SA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AA,IACV,KAAO;AAAA,IACP,MAAQ;AAAA,IACR,KAAO;AAAA,IACP,YAAc;AAAA,IACd,QAAU;AAAA,EACZ;AAAA,EACA,kBAAoB;AAAA,IAClB,6BAA6B;AAAA,IAC7B,qBAAqB;AAAA,IACrB,yBAAyB;AAAA,IACzB,IAAM;AAAA,IACN,KAAO;AAAA,EACT;AAAA,EACA,sBAAwB;AAAA,IACtB,qBAAqB;AAAA,MACnB,UAAY;AAAA,IACd;AAAA,IACA,yBAAyB;AAAA,MACvB,UAAY;AAAA,IACd;AAAA,IACA,IAAM;AAAA,MACJ,UAAY;AAAA,IACd;AAAA,IACA,KAAO;AAAA,MACL,UAAY;AAAA,IACd;AAAA,EACF;AAAA,EACA,eAAiB;AAAA,IACf,QAAU;AAAA,EACZ;AACF;;;AClMO,IAAM,cAAsB,gBAAI;","names":[]}
|
package/dist/chunk-VZ7BOH2K.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
//# sourceMappingURL=chunk-VZ7BOH2K.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/warp_grep/anthropic.ts"],"sourcesContent":["/**\n * Anthropic SDK adapter for morph-warp-grep tool\n */\n\nimport type { Tool } from '@anthropic-ai/sdk/resources/messages';\nimport { executeToolCall, formatResult, WarpGrepClient, executeGitHubReadFile, formatGitHubReadFileResult } from './client.js';\nimport { WARP_GREP_DESCRIPTION, WARP_GREP_TOOL_NAME, GITHUB_SEARCH_TOOL_NAME, GITHUB_SEARCH_DESCRIPTION, GITHUB_SEARCH_INPUT_SCHEMA, GITHUB_READ_FILE_TOOL_NAME, GITHUB_READ_FILE_DESCRIPTION, GITHUB_READ_FILE_INPUT_SCHEMA } from './prompts.js';\nimport type { WarpGrepToolConfig, WarpGrepResult, GitHubSearchToolConfig, GitHubReadFileInput, GitHubReadFileResult, GitHubReadFileToolConfig } from './types.js';\n\n/**\n * Input schema for the warp grep tool\n */\nconst INPUT_SCHEMA = {\n type: 'object',\n properties: {\n search_term: { type: 'string', description: 'Search problem statement that this subagent is supposed to research for' },\n },\n required: ['search_term'],\n} as const;\n\n/**\n * Anthropic-native warp grep tool definition\n * \n * @example\n * ```typescript\n * import Anthropic from '@anthropic-ai/sdk';\n * import { warpGrepTool, execute } from '@morphllm/morphsdk/tools/warp-grep/anthropic';\n * \n * const client = new Anthropic();\n * const response = await client.messages.create({\n * model: 'claude-sonnet-4-5-20250929',\n * tools: [warpGrepTool],\n * messages: [{ role: 'user', content: 'Find authentication middleware' }]\n * });\n * \n * // Execute the tool call\n * const result = await execute({ search_term: '...' }, { repoRoot: '.' });\n * ```\n */\nexport const warpGrepTool: Tool = {\n name: WARP_GREP_TOOL_NAME,\n description: WARP_GREP_DESCRIPTION,\n input_schema: INPUT_SCHEMA,\n};\n\n/**\n * Execute warp grep search\n * \n * @param input - Tool input with search_term\n * @param config - Configuration with repoRoot and optional provider\n * @returns Search results\n */\nexport async function execute(\n input: { search_term: string } | string,\n config: WarpGrepToolConfig\n): Promise<WarpGrepResult> {\n return executeToolCall(input, config);\n}\n\n// Re-export formatResult for convenience\nexport { formatResult };\n\n/**\n * Create a custom warp grep tool with configuration and methods\n * \n * @param config - Configuration options\n * @returns Tool definition with execute and formatResult methods\n * \n * @example Local usage\n * ```typescript\n * import Anthropic from '@anthropic-ai/sdk';\n * import { createWarpGrepTool } from '@morphllm/morphsdk/tools/warp-grep/anthropic';\n * \n * const tool = createWarpGrepTool({ repoRoot: '.' });\n * \n * const client = new Anthropic();\n * const response = await client.messages.create({\n * model: 'claude-sonnet-4-5-20250929',\n * tools: [tool],\n * messages: [{ role: 'user', content: 'Find authentication middleware' }]\n * });\n * ```\n * \n * @example Remote sandbox (E2B, Modal, etc.)\n * ```typescript\n * const tool = createMorphWarpGrepTool({\n * repoRoot: '/home/repo',\n * remoteCommands: {\n * grep: async (pattern, path) => (await sandbox.run(`rg '${pattern}' '${path}'`)).stdout,\n * read: async (path, start, end) => (await sandbox.run(`sed -n '${start},${end}p' '${path}'`)).stdout,\n * listDir: async (path, maxDepth) => (await sandbox.run(`find '${path}' -maxdepth ${maxDepth}`)).stdout,\n * },\n * });\n * ```\n */\nexport function createWarpGrepTool(config: WarpGrepToolConfig) {\n const tool: Tool = {\n name: config.name ?? WARP_GREP_TOOL_NAME,\n description: config.description ?? WARP_GREP_DESCRIPTION,\n input_schema: INPUT_SCHEMA,\n };\n\n return Object.assign(tool, {\n execute: async (input: unknown): Promise<WarpGrepResult> => {\n return executeToolCall(input as { search_term: string } | string, config);\n },\n formatResult: (result: WarpGrepResult): string => {\n return formatResult(result);\n },\n });\n}\n\n/**\n * Create a GitHub search tool for Anthropic SDK\n *\n * @param config - Configuration options (morphApiKey, morphApiUrl, codeSearchUrl, timeout)\n * @returns Anthropic Tool with execute and formatResult methods\n *\n * @example\n * ```typescript\n * import Anthropic from '@anthropic-ai/sdk';\n * import { createGitHubSearchTool } from '@morphllm/morphsdk/tools/warp-grep/anthropic';\n *\n * const tool = createGitHubSearchTool({ morphApiKey: process.env.MORPH_API_KEY });\n *\n * const response = await client.messages.create({\n * model: 'claude-sonnet-4-5-20250929',\n * tools: [tool],\n * messages: [{ role: 'user', content: 'How does auth work in vercel/next.js?' }]\n * });\n *\n * // Execute\n * const result = await tool.execute({ search_term: 'auth middleware', github_url: 'https://github.com/vercel/next.js' });\n * console.log(tool.formatResult(result));\n * ```\n */\nexport function createGitHubSearchTool(config: GitHubSearchToolConfig) {\n const client = new WarpGrepClient(config);\n\n const tool: Tool = {\n name: GITHUB_SEARCH_TOOL_NAME,\n description: GITHUB_SEARCH_DESCRIPTION,\n input_schema: GITHUB_SEARCH_INPUT_SCHEMA,\n };\n\n return Object.assign(tool, {\n execute: async (input: { search_term: string; github_url?: string; owner_repo?: string; branch?: string }): Promise<WarpGrepResult> => {\n const github = input.github_url || input.owner_repo;\n if (!github) {\n throw new Error('Please provide github search url or owner/repo id');\n }\n return client.searchGitHub({ searchTerm: input.search_term, github, branch: input.branch });\n },\n formatResult: (result: WarpGrepResult): string => {\n return formatResult(result);\n },\n });\n}\n\n/**\n * Create a GitHub read file tool for Anthropic SDK\n *\n * @param config - Optional configuration (timeout)\n * @returns Anthropic Tool with execute and formatResult methods\n *\n * @example\n * ```typescript\n * import Anthropic from '@anthropic-ai/sdk';\n * import { createGitHubReadFileTool } from '@morphllm/morphsdk/tools/warp-grep/anthropic';\n *\n * const tool = createGitHubReadFileTool();\n *\n * const response = await client.messages.create({\n * model: 'claude-sonnet-4-5-20250929',\n * tools: [tool],\n * messages: [{ role: 'user', content: 'Read the package.json from vercel/next.js' }]\n * });\n *\n * const result = await tool.execute({ github: 'vercel/next.js', path: 'package.json' });\n * console.log(tool.formatResult(result));\n * ```\n */\nexport function createGitHubReadFileTool(config?: GitHubReadFileToolConfig) {\n const tool: Tool = {\n name: GITHUB_READ_FILE_TOOL_NAME,\n description: GITHUB_READ_FILE_DESCRIPTION,\n input_schema: GITHUB_READ_FILE_INPUT_SCHEMA,\n };\n\n return Object.assign(tool, {\n execute: async (input: GitHubReadFileInput): Promise<GitHubReadFileResult> => {\n return executeGitHubReadFile(input, config);\n },\n formatResult: (result: GitHubReadFileResult): string => {\n return formatGitHubReadFileResult(result);\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAYA,IAAM,eAAe;AAAA,EACnB,MAAM;AAAA,EACN,YAAY;AAAA,IACV,aAAa,EAAE,MAAM,UAAU,aAAa,0EAA0E;AAAA,EACxH;AAAA,EACA,UAAU,CAAC,aAAa;AAC1B;AAqBO,IAAM,eAAqB;AAAA,EAChC,MAAM;AAAA,EACN,aAAa;AAAA,EACb,cAAc;AAChB;AASA,eAAsB,QACpB,OACA,QACyB;AACzB,SAAO,gBAAgB,OAAO,MAAM;AACtC;AAsCO,SAAS,mBAAmB,QAA4B;AAC7D,QAAM,OAAa;AAAA,IACjB,MAAM,OAAO,Q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esContent":[],"mappings":"","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/fastapply/apply.ts","../tools/fastapply/anchors.ts"],"sourcesContent":["/**\n * Edge-compatible code application API\n *\n * This module works on:\n * - Node.js\n * - Cloudflare Workers\n * - Vercel Edge Functions\n * - Deno Deploy\n * - Browser environments\n *\n * For file-based operations, use executeEditFile from core.ts\n */\n\nimport { createTwoFilesPatch } from 'diff';\nimport OpenAI from 'openai';\nimport { SDK_VERSION } from '../../version.js';\nimport { logger } from '../../logger.js';\nimport {\n createAnchorCompactionPlan,\n DEFAULT_ANCHOR_COMPACTION_THRESHOLD,\n FastApplyAnchorIntegrityError,\n} from './anchors.js';\nimport type {\n EditChanges,\n ApplyEditInput,\n ApplyEditResult,\n ApplyEditConfig,\n} from './types.js';\n\nconst DEFAULT_API_URL = 'https://api.morphllm.com';\nconst DEFAULT_TIMEOUT = 600000;\n\ntype CompletionChunk = {\n id?: string;\n choices?: Array<{\n delta?: { content?: string | null };\n finish_reason?: string | null;\n }>;\n};\n\ntype CompletionResponse = {\n id?: string;\n choices?: Array<{\n message?: { content?: string | null };\n finish_reason?: string | null;\n }>;\n};\n\nexport class FastApplyContextLengthError extends Error {\n readonly code = 'context_length_exceeded';\n readonly completionId?: string;\n\n constructor(completionId?: string) {\n super(\n 'Fast Apply exhausted its context window before producing the complete file. ' +\n 'Retry with a smaller input/update or use sparse anchors for unchanged code.'\n );\n this.name = 'FastApplyContextLengthError';\n this.completionId = completionId;\n }\n}\n\nexport { FastApplyAnchorIntegrityError } from './anchors.js';\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterable<CompletionChunk> {\n return typeof value === 'object' && value !== null && Symbol.asyncIterator in value;\n}\n\nasync function collectCompletion(\n response: unknown\n): Promise<{ content: string; completionId?: string; finishReason?: string | null }> {\n if (!isAsyncIterable(response)) {\n const completion = response as CompletionResponse;\n return {\n content: completion.choices?.[0]?.message?.content ?? '',\n completionId: completion.id,\n finishReason: completion.choices?.[0]?.finish_reason,\n };\n }\n\n const content: string[] = [];\n let completionId: string | undefined;\n let finishReason: string | null | undefined;\n\n for await (const chunk of response) {\n completionId = chunk.id ?? completionId;\n for (const choice of chunk.choices ?? []) {\n if (choice.delta?.content) {\n content.push(choice.delta.content);\n }\n if (choice.finish_reason !== undefined && choice.finish_reason !== null) {\n finishReason = choice.finish_reason;\n }\n }\n }\n\n return { content: content.join(''), completionId, finishReason };\n}\n\n/**\n * Generate a unified diff between two strings\n */\nexport function generateUdiff(\n original: string,\n modified: string,\n filepath: string\n): string {\n return createTwoFilesPatch(\n filepath,\n filepath,\n original,\n modified,\n 'Original',\n 'Modified'\n );\n}\n\n/**\n * Count changes from a unified diff\n */\nexport function countChanges(original: string, modified: string): EditChanges {\n const diff = generateUdiff(original, modified, 'file');\n const lines = diff.split('\\n');\n\n let linesAdded = 0;\n let linesRemoved = 0;\n\n for (const line of lines) {\n if (line.startsWith('+') && !line.startsWith('+++')) {\n linesAdded++;\n } else if (line.startsWith('-') && !line.startsWith('---')) {\n linesRemoved++;\n }\n }\n\n const linesModified = Math.min(linesAdded, linesRemoved);\n\n return {\n linesAdded: linesAdded - linesModified,\n linesRemoved: linesRemoved - linesModified,\n linesModified,\n };\n}\n\n/**\n * Call Morph Apply API to merge code edits\n * Uses OpenAI SDK for reliable connection handling, retries, and timeouts\n */\nexport async function callMorphAPI(\n originalCode: string,\n codeEdit: string,\n instructions: string,\n filepath: string,\n config: ApplyEditConfig\n): Promise<{ content: string; completionId?: string }> {\n const apiKey = config.morphApiKey || (typeof process !== 'undefined' ? process.env?.MORPH_API_KEY : undefined);\n const apiUrl = config.morphApiUrl || DEFAULT_API_URL;\n const useLarge = config.large ?? (typeof process !== 'undefined' ? process.env?.MORPH_LARGE_APPLY !== 'false' : true);\n const model = useLarge ? 'morph-v3-large' : 'morph-v3-fast';\n const timeout = config.timeout ?? DEFAULT_TIMEOUT;\n const debug = config.debug || false;\n\n if (!apiKey) {\n throw new Error(\n 'Morph API key not found. Set MORPH_API_KEY environment variable or pass morphApiKey in config.'\n );\n }\n\n const anchorThreshold = config.anchorCompactionThreshold\n ?? DEFAULT_ANCHOR_COMPACTION_THRESHOLD;\n const anchorPlan = config.anchorCompaction !== false\n && originalCode.length >= anchorThreshold\n ? createAnchorCompactionPlan(originalCode, [codeEdit, instructions])\n : undefined;\n const requestCode = anchorPlan?.code ?? originalCode;\n const requestInstructions = anchorPlan\n ? instructions + anchorPlan.instructionSuffix\n : instructions;\n\n // Format message with XML tags as per Morph Fast Apply spec\n const message = `<instruction>${requestInstructions}</instruction>\\n<code>${requestCode}</code>\\n<update>${codeEdit}</update>`;\n\n logger.debug('FastApply', 'http_request', {\n url: `${apiUrl}/v1/chat/completions`,\n model,\n filepath,\n instruction_len: instructions.length,\n original_len: originalCode.length,\n request_code_len: requestCode.length,\n code_edit_len: codeEdit.length,\n anchor_count: anchorPlan?.anchorCount ?? 0,\n unique_anchor_count: anchorPlan?.uniqueAnchorCount ?? 0,\n });\n\n const startTime = Date.now();\n\n const client = new OpenAI({\n apiKey,\n baseURL: `${apiUrl}/v1`,\n timeout,\n maxRetries: config.retryConfig?.maxRetries ?? 3,\n defaultHeaders: {\n 'X-Morph-SDK-Version': SDK_VERSION,\n ...(anchorPlan ? { 'X-Morph-Apply-Context': 'extralong' } : {}),\n },\n });\n\n try {\n const maxAttempts = anchorPlan?.hasStructuralValidation ? 2 : 1;\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n const response = await client.chat.completions.create({\n model,\n messages: [{ role: 'user', content: message }],\n stream: true,\n });\n const completion = await collectCompletion(response);\n\n if (completion.finishReason === 'length') {\n throw new FastApplyContextLengthError(completion.completionId);\n }\n\n let content = completion.content;\n if (!content) {\n throw new Error('Morph API returned empty response');\n }\n\n if (anchorPlan) {\n try {\n content = anchorPlan.expand(content);\n } catch (error) {\n if (error instanceof FastApplyAnchorIntegrityError) {\n if (attempt < maxAttempts) {\n logger.warn('FastApply', 'anchor_validation_retry', {\n attempt,\n completion_id: completion.completionId,\n });\n continue;\n }\n throw new FastApplyAnchorIntegrityError(completion.completionId);\n }\n throw error;\n }\n }\n\n const elapsed = Date.now() - startTime;\n logger.debug('FastApply', 'http_response', { status: 200, completion_id: completion.completionId, content_len: content.length, latency_ms: elapsed });\n\n return { content, completionId: completion.completionId };\n }\n\n throw new FastApplyAnchorIntegrityError();\n } catch (error: any) {\n const elapsed = Date.now() - startTime;\n const status = error?.status || error?.response?.status;\n logger.error('FastApply', 'http_error', {\n status,\n error: error?.message,\n latency_ms: elapsed,\n });\n\n if (status === 401) {\n const err = new Error(\n 'Authentication failed: Your Morph API key is invalid or has been revoked. ' +\n 'Please visit https://morphllm.com to get a valid API key, then update your MCP configuration.'\n );\n (err as any).status = 401;\n throw err;\n }\n\n if (status === 429) {\n const err = new Error(\n 'Rate limited: You\\'ve exceeded your Morph API usage limits. ' +\n 'Please visit https://morphllm.com to check your plan and purchase additional credits.'\n );\n (err as any).status = 429;\n throw err;\n }\n\n throw error;\n }\n}\n\n/**\n * Apply an edit to code directly without file I/O\n *\n * This is the edge-compatible code-in/code-out API that accepts code content directly\n * and returns the merged result without reading or writing any files.\n *\n * Works on Cloudflare Workers, Vercel Edge Functions, Deno, and browsers.\n *\n * @param input - Code and edit parameters\n * @param config - Optional configuration\n * @returns Result with merged code\n *\n * @example\n * ```typescript\n * import { applyEdit } from '@morphllm/morphsdk';\n *\n * const result = await applyEdit({\n * originalCode: fs.readFileSync('file.ts', 'utf-8'),\n * codeEdit: '// ... existing code ...\\nconst newVar = 42;\\n// ... existing code ...',\n * instructions: 'Add a new variable',\n * // filepath is accepted but does nothing\n * });\n *\n * if (result.success) {\n * fs.writeFileSync('file.ts', result.mergedCode);\n * }\n * ```\n */\nexport async function applyEdit(\n input: ApplyEditInput,\n config: ApplyEditConfig = {}\n): Promise<ApplyEditResult> {\n const filepath = input.filepath || 'file';\n\n try {\n logger.debug('FastApply', 'apply_edit_start', { original_len: input.originalCode.length, code_edit_len: input.codeEdit.length });\n\n const instruction = input.instruction ?? input.instructions ?? '';\n const { content: mergedCode, completionId } = await callMorphAPI(\n input.originalCode,\n input.codeEdit,\n instruction,\n filepath,\n config\n );\n\n const udiff = config.generateUdiff !== false\n ? generateUdiff(input.originalCode, mergedCode, filepath)\n : undefined;\n\n const changes = countChanges(input.originalCode, mergedCode);\n\n return {\n success: true,\n mergedCode,\n udiff,\n changes,\n completionId,\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';\n logger.error('FastApply', 'apply_edit_error', { error: errorMessage });\n const structuredError = error instanceof FastApplyContextLengthError\n || error instanceof FastApplyAnchorIntegrityError\n ? error\n : undefined;\n\n return {\n success: false,\n changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },\n error: errorMessage,\n errorCode: structuredError?.code,\n completionId: structuredError?.completionId,\n };\n }\n}\n","const DEFAULT_MIN_ANCHOR_LINE_LENGTH = 24;\n\nexport const DEFAULT_ANCHOR_COMPACTION_THRESHOLD = 128 * 1024;\n\nexport interface AnchorCompactionPlan {\n code: string;\n instructionSuffix: string;\n anchorCount: number;\n uniqueAnchorCount: number;\n hasStructuralValidation: boolean;\n expand: (content: string) => string;\n}\n\nexport class FastApplyAnchorIntegrityError extends Error {\n readonly code = 'anchor_integrity_failed';\n readonly completionId?: string;\n\n constructor(completionId?: string) {\n super(\n 'Fast Apply failed large-file anchor integrity checks. The partial result was discarded safely.'\n );\n this.name = 'FastApplyAnchorIntegrityError';\n this.completionId = completionId;\n }\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction findNamespace(values: string[]): number {\n for (let namespace = 0; namespace < Number.MAX_SAFE_INTEGER; namespace++) {\n const prefix = `⟪M${namespace}:`;\n if (values.every((value) => !value.includes(prefix))) {\n return namespace;\n }\n }\n\n throw new Error('Unable to allocate a Fast Apply anchor namespace');\n}\n\ninterface SourceUnit {\n value: string;\n label?: string;\n anchorable: boolean;\n}\n\nfunction htmlLabel(token: string): string {\n if (!token.startsWith('<')) return 'text';\n const match = token.match(/^<\\s*(!doctype|\\/?[a-zA-Z][\\w:-]*)/);\n return (match?.[1] ?? 'tag').toLowerCase();\n}\n\nfunction htmlTokenUnits(value: string, visibleTags = new Set<string>()): SourceUnit[] {\n return (value.match(/<[^>]*>|[^<]+/g) ?? [value]).map((token) => ({\n value: token,\n label: htmlLabel(token),\n anchorable: token.length >= DEFAULT_MIN_ANCHOR_LINE_LENGTH\n && !visibleTags.has(htmlLabel(token).replace(/^\\//, '')),\n }));\n}\n\nfunction sourceUnits(originalCode: string, editContext: string[]): SourceUnit[] {\n const trimmed = originalCode.trimStart().toLowerCase();\n const looksLikeHtml = (trimmed.startsWith('<!doctype') || trimmed.startsWith('<html'))\n && /<\\/html\\s*>/i.test(originalCode);\n\n if (looksLikeHtml) {\n const contextWords = new Set(\n editContext.join(' ').toLowerCase().match(/[a-z][\\w:-]*/g) ?? []\n );\n return htmlTokenUnits(originalCode, contextWords);\n }\n\n const parts = originalCode.split(/(\\r\\n|\\n|\\r)/);\n const units: SourceUnit[] = [];\n for (let index = 0; index < parts.length; index += 2) {\n const line = parts[index] ?? '';\n const lineEnding = parts[index + 1] ?? '';\n units.push({\n value: line,\n label: 'line',\n anchorable: line.length >= DEFAULT_MIN_ANCHOR_LINE_LENGTH,\n });\n if (lineEnding) {\n units.push({ value: lineEnding, anchorable: false });\n }\n }\n return units;\n}\n\nfunction copyCount(value: string): number | undefined {\n const words: Record<string, number> = {\n one: 1,\n two: 2,\n three: 3,\n four: 4,\n five: 5,\n six: 6,\n seven: 7,\n eight: 8,\n nine: 9,\n ten: 10,\n };\n return /^\\d+$/.test(value) ? Number(value) : words[value.toLowerCase()];\n}\n\nfunction structuralExpectation(originalCode: string, editContext: string[]) {\n const context = editContext.join(' ');\n const match = context.match(\n /(?:for every|for each|each)\\s+([a-z][\\w:-]*)[\\s\\S]{0,120}?add\\s+(one|two|three|four|five|six|seven|eight|nine|ten|\\d+)\\s+identical cop(?:y|ies)/i\n );\n if (!match) return undefined;\n\n const tag = match[1]!.toLowerCase();\n const addedCopies = copyCount(match[2]!);\n if (addedCopies === undefined) return undefined;\n\n const tagPattern = new RegExp(`<${escapeRegExp(tag)}(?:\\\\s|>)`, 'gi');\n const originalCount = originalCode.match(tagPattern)?.length ?? 0;\n if (originalCount === 0) return undefined;\n\n return { tag, expectedCount: originalCount * (addedCopies + 1) };\n}\n\n/**\n * Replace long source fragments with lossless placeholders. Definitions are sent once,\n * while the model can emit a small skeleton containing repeated/moved placeholders.\n */\nexport function createAnchorCompactionPlan(\n originalCode: string,\n collisionValues: string[] = []\n): AnchorCompactionPlan | undefined {\n const namespace = findNamespace([originalCode, ...collisionValues]);\n const expectation = structuralExpectation(originalCode, collisionValues);\n const markerPrefix = `⟪M${namespace}:`;\n const definitions = new Map<string, number>();\n const values: string[] = [];\n const markers: string[] = [];\n let anchorCount = 0;\n let skeleton = '';\n\n for (const unit of sourceUnits(originalCode, collisionValues)) {\n if (!unit.anchorable) {\n skeleton += unit.value;\n continue;\n }\n\n let id = definitions.get(unit.value);\n if (id === undefined) {\n id = values.length;\n definitions.set(unit.value, id);\n values.push(unit.value);\n markers.push(`${markerPrefix}${id}:${unit.label ?? 'unit'}⟫`);\n }\n\n skeleton += markers[id];\n anchorCount++;\n }\n\n if (anchorCount === 0 || skeleton.length >= originalCode.length) {\n return undefined;\n }\n\n const definitionsBegin = `⟪MORPH_DEFINITIONS_BEGIN_${namespace}⟫`;\n const definitionsEnd = `⟪MORPH_DEFINITIONS_END_${namespace}⟫`;\n const codeBegin = `⟪MORPH_CODE_BEGIN_${namespace}⟫`;\n const serializedDefinitions = values\n .map((value, id) => `${markers[id]}=${JSON.stringify(value)}`)\n .join('\\n');\n\n const code = [\n definitionsBegin,\n serializedDefinitions,\n definitionsEnd,\n codeBegin,\n skeleton,\n ].join('\\n');\n\n const instructionSuffix = `\n\nLARGE-FILE ANCHOR PROTOCOL:\nThe <code> block starts with an exact anchor definition table, then ${codeBegin}, then the source skeleton.\nEach ${markerPrefix}N:kind⟫ placeholder represents the exact source fragment in its matching JSON-string definition. The kind suffix describes its HTML tag, text, or source line.\nReturn only the updated source skeleton after ${codeBegin}; never return the definition table or protocol delimiters.\nCopy a placeholder exactly when its source fragment is unchanged. You may repeat, reorder, or remove placeholders when the requested edit requires it.\nTo modify an anchored fragment, output the modified source instead of its placeholder.\nDo not invent or alter placeholder IDs.`;\n\n const markerPattern = new RegExp(`${escapeRegExp(markerPrefix)}(\\\\d+):[^⟫]+⟫`, 'g');\n\n return {\n code,\n instructionSuffix,\n anchorCount,\n uniqueAnchorCount: values.length,\n hasStructuralValidation: expectation !== undefined,\n expand(content: string): string {\n const codeBeginIndex = content.lastIndexOf(codeBegin);\n const skeletonContent = codeBeginIndex >= 0\n ? content.slice(codeBeginIndex + codeBegin.length).replace(/^\\r?\\n/, '')\n : content;\n\n const expanded = skeletonContent.replace(markerPattern, (marker, idText: string) => {\n const id = Number(idText);\n const value = values[id];\n return value === undefined || markers[id] !== marker ? marker : value;\n });\n\n if (expanded.includes(markerPrefix)) {\n throw new FastApplyAnchorIntegrityError();\n }\n\n if (expectation) {\n const tagPattern = new RegExp(`<${escapeRegExp(expectation.tag)}(?:\\\\s|>)`, 'gi');\n const actualCount = expanded.match(tagPattern)?.length ?? 0;\n if (actualCount !== expectation.expectedCount) {\n throw new FastApplyAnchorIntegrityError();\n }\n }\n\n return expanded;\n },\n };\n}\n"],"mappings":";;;;;;;;AAaA,SAAS,2BAA2B;AACpC,OAAO,YAAY;;;ACdnB,IAAM,iCAAiC;AAEhC,IAAM,sCAAsC,MAAM;AAWlD,IAAM,gCAAN,cAA4C,MAAM;AAAA,EAC9C,OAAO;AAAA,EACP;AAAA,EAET,YAAY,cAAuB;AACjC;AAAA,MACE;AAAA,IACF;AACA,SAAK,OAAO;AACZ,SAAK,eAAe;AAAA,EACtB;AACF;AAEA,SAAS,aAAa,OAAuB;AAC3C,S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;AACF;AA8BA,eAAsB,UACpB,OACA,SAA0B,CAAC,GACD;AAC1B,QAAM,WAAW,MAAM,YAAY;AAEnC,MAAI;AACF,WAAO,MAAM,aAAa,oBAAoB,EAAE,cAAc,MAAM,aAAa,QAAQ,eAAe,MAAM,SAAS,OAAO,CAAC;AAE/H,UAAM,cAAc,MAAM,eAAe,MAAM,gBAAgB;AAC/D,UAAM,EAAE,SAAS,YAAY,aAAa,IAAI,MAAM;AAAA,MAClD,MAAM;AAAA,MACN,MAAM;AAAA,MACN;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAEA,UAAM,QAAQ,OAAO,kBAAkB,QACnC,cAAc,MAAM,cAAc,YAAY,QAAQ,IACtD;AAEJ,UAAM,UAAU,aAAa,MAAM,cAAc,UAAU;AAE3D,WAAO;AAAA,MACL,SAAS;AAAA,MACT;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF,SAAS,OAAO;AACd,UAAM,eAAe,iBAAiB,QAAQ,MAAM,UAAU;AAC9D,WAAO,MAAM,aAAa,oBAAoB,EAAE,OAAO,aAAa,CAAC;AACrE,UAAM,kBAAkB,iBAAiB,+BACpC,iBAAiB,gCAClB,QACA;AAEJ,WAAO;AAAA,MACL,SAAS;AAAA,MACT,SAAS,EAAE,YAAY,GAAG,cAAc,GAAG,eAAe,EAAE;AAAA,MAC5D,OAAO;AAAA,MACP,WAAW,iBAAiB;AAAA,MAC5B,cAAc,iBAAiB;AAAA,IACjC;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/warp_grep/utils/paths.ts"],"sourcesContent":["import fs from 'fs';\nimport path from 'path';\n\nexport function resolveUnderRepo(repoRoot: string, targetPath: string): string {\n const absRoot = path.resolve(repoRoot);\n const resolved = path.resolve(absRoot, targetPath);\n ensureWithinRepo(absRoot, resolved);\n return resolved;\n}\n\nexport function ensureWithinRepo(repoRoot: string, absTarget: string): void {\n const rel = path.relative(path.resolve(repoRoot), path.resolve(absTarget));\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(`Path outside repository root: ${absTarget}`);\n }\n}\n\nexport function toRepoRelative(repoRoot: string, absPath: string): string {\n return path.relative(path.resolve(repoRoot), path.resolve(absPath));\n}\n\nexport function isSymlink(p: string): boolean {\n try {\n const st = fs.lstatSync(p);\n return st.isSymbolicLink();\n } catch {\n return false;\n }\n}\n\n/**\n * Detects and removes consecutive duplicate path segments.\n *\n * When the model predicts a path that includes the repo directory name,\n * joining with repoRoot creates duplication:\n * repoRoot=\"/Users/dhruv/repo\" + predicted=\"repo/src/file.ts\"\n * → \"/Users/dhruv/repo/repo/src/file.ts\"\n *\n * This function detects such patterns and returns the corrected path,\n * or null if no duplication is found.\n */\nexport function fixPathRepetition(fullPath: string): string | null {\n const segments = fullPath.split(path.sep).filter(Boolean);\n if (segments.length < 2) return null;\n\n for (let len = Math.floor(segments.length / 2); len >= 1; len--) {\n for (let i = 0; i <= segments.length - 2 * len; i++) {\n const first = segments.slice(i, i + len);\n const second = segments.slice(i + len, i + 2 * len);\n\n if (first.every((seg, idx) => seg === second[idx])) {\n const fixed = [...segments.slice(0, i), ...segments.slice(i + len)];\n return path.sep + fixed.join(path.sep);\n }\n }\n }\n\n return null;\n}\n\nexport function isTextualFile(filePath: string, maxBytes = 2_000_000): boolean {\n try {\n const st = fs.statSync(filePath);\n if (!st.isFile()) return false;\n if (st.size > maxBytes) return false;\n const fd = fs.openSync(filePath, 'r');\n const buf = Buffer.alloc(512);\n const read = fs.readSync(fd, buf, 0, buf.length, 0);\n fs.closeSync(fd);\n for (let i = 0; i < read; i++) {\n const c = buf[i];\n if (c === 0) return false; // binary heuristic\n }\n return true;\n } catch {\n return false;\n }\n}\n\n\n"],"mappings":";AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AAEV,SAAS,iBAAiB,UAAkB,YAA4B;AAC7E,QAAM,UAAU,KAAK,QAAQ,QAAQ;AACrC,QAAM,WAA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kB,WAAW,KAAoB;AAC7E,MAAI;AACF,UAAM,KAAK,GAAG,SAAS,QAAQ;AAC/B,QAAI,CAAC,GAAG,OAAO,EAAG,QAAO;AACzB,QAAI,GAAG,OAAO,SAAU,QAAO;AAC/B,UAAM,KAAK,GAAG,SAAS,UAAU,GAAG;AACpC,UAAM,MAAM,OAAO,MAAM,GAAG;AAC5B,UAAM,OAAO,GAAG,SAAS,IAAI,KAAK,GAAG,IAAI,QAAQ,CAAC;AAClD,OAAG,UAAU,EAAE;AACf,aAAS,IAAI,GAAG,IAAI,MAAM,KAAK;AAC7B,YAAM,IAAI,IAAI,CAAC;AACf,UAAI,MAAM,EAAG,QAAO;AAAA,IACtB;AACA,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/fastapply/core.ts"],"sourcesContent":["/**\n * Core implementation of Morph Fast Apply\n *\n * This module provides file-based operations that require Node.js.\n * For edge-compatible code-in/code-out operations, use applyEdit from ./apply.ts\n */\n\nimport { join, resolve, relative } from 'path';\nimport type {\n EditFileInput,\n EditFileResult,\n EditFileConfig,\n} from './types.js';\nimport { logger } from '../../logger.js';\nimport { MorphAPIClient } from '../../core/client.js';\nimport { APIResource } from '../../core/resource.js';\nimport {\n FastApplyAnchorIntegrityError,\n FastApplyContextLengthError,\n} from './apply.js';\n\n// Re-export edge-compatible functions\nexport { applyEdit, generateUdiff, countChanges, callMorphAPI } from './apply.js';\nexport { FastApplyAnchorIntegrityError, FastApplyContextLengthError };\n\nconst DEFAULT_CONFIG: Required<Omit<EditFileConfig, 'morphApiKey' | 'systemPrompt' | 'retryConfig' | 'description' | 'large'>> = {\n morphApiUrl: 'https://api.morphllm.com',\n baseDir: process.cwd(),\n generateUdiff: true,\n autoWrite: true,\n timeout: 600000,\n anchorCompaction: true,\n anchorCompactionThreshold: 128 * 1024,\n debug: false,\n};\n\n/**\n * FastApply client for programmatic file editing\n * Note: This client requires Node.js for file operations\n *\n * @deprecated Prefer the unified `MorphClient` (`new MorphClient({ apiKey }).fastApply`).\n * Standalone clients remain only for backwards compatibility and may be removed in a future\n * major version — do not use them in new code.\n */\nexport class FastApplyClient extends APIResource {\n private config: EditFileConfig;\n\n constructor(clientOrConfig: MorphAPIClient | { apiKey?: string; debug?: boolean; timeout?: number; retryConfig?: any } = {}) {\n const isClient = clientOrConfig instanceof MorphAPIClient;\n super(\n isClient\n ? clientOrConfig\n : new MorphAPIClient({\n apiKey: clientOrConfig.apiKey,\n timeout: clientOrConfig.timeout ?? DEFAULT_CONFIG.timeout,\n retryConfig: clientOrConfig.retryConfig,\n debug: clientOrConfig.debug,\n }),\n );\n // FastApply talks to /v1/chat/completions through the `openai` package, but\n // sources its credentials and host from the shared transport.\n this.config = {\n morphApiKey: this._client.resolveApiKey(),\n morphApiUrl: this._client.baseURL,\n debug: this._client.debug,\n timeout: (isClient ? undefined : clientOrConfig.timeout) ?? DEFAULT_CONFIG.timeout,\n retryConfig: this._client.retryConfig,\n generateUdiff: DEFAULT_CONFIG.generateUdiff,\n autoWrite: DEFAULT_CONFIG.autoWrite,\n };\n }\n\n /**\n * Execute a file edit operation\n *\n * @param input - Edit parameters including filepath, instructions, and code_edit\n * @param overrides - Optional config overrides for this operation\n * @returns Edit result with success status and changes\n */\n async execute(input: EditFileInput, overrides?: Partial<EditFileConfig>): Promise<EditFileResult> {\n return executeEditFile(input, { ...this.config, ...overrides });\n }\n\n /**\n * Apply an edit to code directly without file I/O\n *\n * Useful for sandbox environments or when you manage your own file system.\n * Compatible with the earlier OpenAI client API contract.\n *\n * @param input - Code and edit parameters\n * @param overrides - Optional config overrides for this operation\n * @returns Result with merged code\n *\n * @example\n * ```typescript\n * const result = await client.applyEdit({\n * originalCode: 'function hello() { return \"world\"; }',\n * codeEdit: 'function hello() { return \"universe\"; }',\n * instructions: 'Change return value'\n * });\n * console.log(result.mergedCode);\n * ```\n */\n async applyEdit(input: import('./types.js').ApplyEditInput, overrides?: Partial<import('./types.js').ApplyEditConfig>): Promise<import('./types.js').ApplyEditResult> {\n const { applyEdit } = await import('./apply.js');\n return applyEdit(input, { ...this.config, ...overrides });\n }\n}\n\n/**\n * Execute a file edit using Morph Fast Apply\n * Note: This function requires Node.js for file I/O\n */\nexport async function executeEditFile(\n input: EditFileInput,\n config: EditFileConfig = {}\n): Promise<EditFileResult> {\n const baseDir = config.baseDir || DEFAULT_CONFIG.baseDir;\n const fullPath = resolve(join(baseDir, input.target_filepath));\n\n logger.debug('FastApply', 'execute_start', { target_filepath: input.target_filepath, baseDir, autoWrite: config.autoWrite !== false });\n\n // Security: ensure file is within baseDir\n const relativePath = relative(baseDir, fullPath);\n if (relativePath.startsWith('..') || fullPath === baseDir) {\n logger.warn('FastApply', 'security_check_failed', { target_filepath: input.target_filepath, relative: relativePath });\n return {\n success: false,\n filepath: input.target_filepath,\n changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },\n error: `Invalid filepath: '${input.target_filepath}' is outside baseDir`,\n };\n }\n\n logger.debug('FastApply', 'security_check', { resolved: fullPath, relative: relativePath });\n\n try {\n // Dynamic import to avoid loading Node.js fs module at module evaluation time\n const { readFile, writeFile } = await import('fs/promises');\n const { callMorphAPI, generateUdiff, countChanges } = await import('./apply.js');\n\n // Handle both existing and non-existent files\n let originalCode = '';\n let fileExists = true;\n try {\n originalCode = await readFile(fullPath, 'utf-8');\n logger.debug('FastApply', 'file_read', { path: fullPath, exists: true, size_bytes: originalCode.length });\n } catch (error: any) {\n if (error.code !== 'ENOENT') {\n throw error; // Re-throw if it's not a \"file not found\" error\n }\n fileExists = false;\n logger.debug('FastApply', 'file_read', { path: fullPath, exists: false });\n }\n\n const instruction = input.instruction ?? input.instructions ?? '';\n logger.debug('FastApply', 'api_call', { instruction_len: instruction.length, code_edit_len: input.code_edit.length, original_len: originalCode.length });\n\n const { content: mergedCode, completionId } = await callMorphAPI(originalCode, input.code_edit, instruction, input.target_filepath, config);\n\n logger.debug('FastApply', 'api_response', { completion_id: completionId, merged_len: mergedCode.length });\n\n const udiff = config.generateUdiff !== false ? generateUdiff(originalCode, mergedCode, input.target_filepath) : undefined;\n\n if (config.autoWrite !== false) {\n await writeFile(fullPath, mergedCode, 'utf-8');\n logger.debug('FastApply', 'file_write', { path: fullPath, size_bytes: mergedCode.length });\n }\n\n const changes = countChanges(originalCode, mergedCode);\n logger.debug('FastApply', 'changes', { added: changes.linesAdded, removed: changes.linesRemoved, modified: changes.linesModified });\n\n return {\n success: true,\n filepath: input.target_filepath,\n udiff,\n changes,\n completionId,\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';\n const structuredError = error instanceof FastApplyContextLengthError\n || error instanceof FastApplyAnchorIntegrityError\n ? error\n : undefined;\n logger.error('FastApply', 'execute_error', { error: errorMessage, target_filepath: input.target_filepath, stack: error instanceof Error ? error.stack : undefined });\n\n return {\n success: false,\n filepath: input.target_filepath,\n changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },\n error: errorMessage,\n errorCode: structuredError?.code,\n completionId: structuredError?.completionId,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAOA,SAAS,MAAM,SAAS,gBAAgB;AAkBxC,IAAM,iBAA2H;AAAA,EAC/H,aAAa;AAAA,EACb,SAAS,QAAQ,IAAI;AAAA,EACrB,eAAe;AAAA,EACf,WAAW;AAAA,EACX,SAAS;AAAA,EACT,kBAAkB;AAAA,EAClB,2BAA2B,MAAM;AAAA,EACjC,OAAO;AACT;AAUO,IAAM,kBAAN,cAA8B,YAAY;AAAA,EACvC;AAAA,EAER,YAAY,iBAA6G,CAAC,GAAG;AAC3H,UAAM,WAAW,0BAA0B;AAC3C;AAAA,MACE,WACI,iBACA,IAAI,eAAe;AAAA,QACjB,QAAQ,eAAe;AAAA,QACvB,SAAS,eAAe,WAAW,eAAe;AAAA,QAClD,aAAa,eAAe;AAAA,QAC5B,OAAO,eAAe;AAAA,MACxB,CAAC;AAA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AAUC,cAAa,cAAc,UAAU;AACrD,WAAO,MAAM,aAAa,WAAW,EAAE,OAAO,QAAQ,YAAY,SAAS,QAAQ,cAAc,UAAU,QAAQ,cAAc,CAAC;AAElI,WAAO;AAAA,MACL,SAAS;AAAA,MACT,UAAU,MAAM;AAAA,MAChB;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF,SAAS,OAAO;AACd,UAAM,eAAe,iBAAiB,QAAQ,MAAM,UAAU;AAC9D,UAAM,kBAAkB,iBAAiB,+BACpC,iBAAiB,gCAClB,QACA;AACJ,WAAO,MAAM,aAAa,iBAAiB,EAAE,OAAO,cAAc,iBAAiB,MAAM,iBAAiB,OAAO,iBAAiB,QAAQ,MAAM,QAAQ,OAAU,CAAC;AAEnK,WAAO;AAAA,MACL,SAAS;AAAA,MACT,UAAU,MAAM;AAAA,MAChB,SAAS,EAAE,YAAY,GAAG,cAAc,GAAG,eAAe,EAAE;AAAA,MAC5D,OAAO;AAAA,MACP,WAAW,iBAAiB;AAAA,MAC5B,cAAc,iBAAiB;AAAA,IACjC;AAAA,EACF;AACF;","names":["applyEdit","callMorphAPI","generateUdiff","countChanges"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../subagents/vercel.ts"],"sourcesContent":["/**\n * Vercel AI SDK adapter for Explore subagent\n */\n\nimport { tool, generateText, stepCountIs } from 'ai';\nimport type { LanguageModel } from 'ai';\nimport { z } from 'zod';\nimport { WarpGrepClient } from '../tools/warp_grep/client.js';\nimport { formatResult } from '../tools/warp_grep/client.js';\nimport type { WarpGrepContext } from '../tools/warp_grep/types.js';\nimport { getSystemPrompt, CODEBASE_SEARCH_TOOL, SEND_MESSAGE_TOOL } from './prompts.js';\nimport type {\n ExploreSubagentConfig,\n ExploreResult,\n ExploreStep,\n ExploreSession,\n ExploreEvent,\n SubagentMessage,\n MessageHandler,\n StepHandler,\n} from './types.js';\n\n/** Config for Vercel AI SDK Explore subagent */\nexport interface VercelExploreConfig extends ExploreSubagentConfig {\n /** Vercel AI SDK model instance */\n model: LanguageModel;\n}\n\nconst DEFAULT_MAX_TURNS: Record<string, number> = {\n quick: 3,\n medium: 6,\n thorough: 12,\n};\n\nfunction getMaxTurns(config: ExploreSubagentConfig): number {\n return config.maxTurns ?? DEFAULT_MAX_TURNS[config.thoroughness ?? 'medium'] ?? 6;\n}\n\n/**\n * Create an Explore subagent using Vercel AI SDK\n */\nexport function createExploreSubagent(config: VercelExploreConfig) {\n if (!config.repoRoot) {\n throw new Error('repoRoot is required for Explore subagent');\n }\n\n const warpGrep = new WarpGrepClient({\n morphApiKey: config.morphApiKey,\n });\n\n const thoroughness = config.thoroughness ?? 'medium';\n const replyTimeout = config.replyTimeout ?? 30_000;\n\n /** Run the agent loop and collect results */\n async function runExplore(\n prompt: string,\n callbacks: {\n onStep?: StepHandler;\n onMessage?: MessageHandler;\n } = {},\n ): Promise<ExploreResult> {\n const startTime = Date.now();\n const allContexts: WarpGrepContext[] = [];\n let searchCount = 0;\n\n const timeoutMs = config.timeout;\n const timeoutPromise = timeoutMs\n ? new Promise<never>((_, reject) =>\n setTimeout(() => reject(new Error(`Exploration timed out after ${timeoutMs}ms`)), timeoutMs),\n )\n : null;\n\n const runPromise = (async (): Promise<ExploreResult> => {\n try {\n const codebaseSearchSchema = z.object({\n searchRequest: z.string().describe('Natural language description of what to search for'),\n });\n\n const sendMessageSchema = z.object({\n message: z.string().describe('The message to send to the orchestrator'),\n });\n\n const result = await generateText({\n model: config.model,\n system: getSystemPrompt(thoroughness),\n prompt,\n tools: {\n codebase_search: tool({\n description: CODEBASE_SEARCH_TOOL.description,\n inputSchema: codebaseSearchSchema,\n execute: async (params: z.infer<typeof codebaseSearchSchema>) => {\n searchCount++;\n const warpResult = await warpGrep.execute({\n searchTerm: params.searchRequest,\n repoRoot: config.repoRoot,\n excludes: config.excludes,\n includes: config.includes,\n });\n\n if (warpResult.contexts) {\n allContexts.push(...warpResult.contexts);\n }\n\n callbacks.onStep?.({\n step: searchCount,\n searchRequest: params.searchRequest,\n contextsFound: warpResult.contexts?.length ?? 0,\n isFinal: false,\n });\n\n return formatResult(warpResult);\n },\n }),\n send_message: tool({\n description: SEND_MESSAGE_TOOL.description,\n inputSchema: sendMessageSchema,\n execute: async (params: z.infer<typeof sendMessageSchema>) => {\n const subagentMsg: SubagentMessage = {\n from: 'explore',\n content: params.message,\n timestamp: Date.now(),\n };\n\n // Create a promise that waits for the host's reply\n const replyPromise = new Promise<string>((resolve) => {\n // Emit the message to the host via callback\n if (callbacks.onMessage) {\n callbacks.onMessage(subagentMsg, (replyText: string) => {\n resolve(replyText);\n });\n } else {\n // No handler registered, auto-resolve after timeout\n setTimeout(() => resolve(''), replyTimeout);\n }\n });\n\n // Wait for reply with timeout\n const reply = await Promise.race([\n replyPromise,\n new Promise<string>((resolve) =>\n setTimeout(() => resolve(''), replyTimeout),\n ),\n ]);\n\n if (reply) {\n return `Response from orchestrator: ${reply}`;\n }\n return 'No response. Continue with your best judgment.';\n },\n }),\n },\n stopWhen: stepCountIs(getMaxTurns(config)),\n });\n\n // Emit final step\n callbacks.onStep?.({\n step: searchCount,\n searchRequest: '',\n contextsFound: allContexts.length,\n isFinal: true,\n });\n\n // Deduplicate contexts by file path\n const uniqueContexts = deduplicateContexts(allContexts);\n\n return {\n success: true,\n summary: result.text || 'Exploration completed but no summary was generated.',\n contexts: uniqueContexts,\n searchCount,\n durationMs: Date.now() - startTime,\n };\n } catch (error) {\n return {\n success: false,\n summary: '',\n contexts: deduplicateContexts(allContexts),\n searchCount,\n durationMs: Date.now() - startTime,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n })();\n\n if (timeoutPromise) {\n try {\n return await Promise.race([runPromise, timeoutPromise]);\n } catch (error) {\n return {\n success: false,\n summary: '',\n contexts: deduplicateContexts(allContexts),\n searchCount,\n durationMs: Date.now() - startTime,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n return runPromise;\n }\n\n const exploreToolSchema = z.object({\n searchRequest: z\n .string()\n .describe('What to explore in the codebase. Be specific about what you want to understand.'),\n });\n\n /** The Vercel AI tool for use in parent agents */\n const exploreTool = tool({\n description:\n 'Explore a codebase to answer questions about code structure, find implementations, trace call chains, and understand architecture. Returns a summary of findings. Use this for broad exploration rather than pinpoint keyword searches.',\n inputSchema: exploreToolSchema,\n execute: async (params: z.infer<typeof exploreToolSchema>) => {\n const result = await runExplore(params.searchRequest);\n return {\n success: result.success,\n summary: result.summary,\n searchCount: result.searchCount,\n error: result.error,\n };\n },\n });\n\n return {\n /** Vercel AI SDK tool for use as a tool in parent agents */\n tool: exploreTool,\n\n /** Run exploration with messaging support */\n run(prompt: string): ExploreSession {\n const messageHandlers: MessageHandler[] = [];\n const stepHandlers: StepHandler[] = [];\n\n // Start the run lazily (after handlers are attached)\n let resultPromise: Promise<ExploreResult> | null = null;\n\n const session: ExploreSession = {\n on(event: string, handler: any) {\n if (event === 'message') messageHandlers.push(handler);\n if (event === 'step') stepHandlers.push(handler);\n return session;\n },\n send(_text: string) {\n // Convenience method — pause-and-ask flow uses the reply callback\n },\n get result() {\n if (!resultPromise) {\n resultPromise = runExplore(prompt, {\n onStep: (step) => {\n for (const handler of stepHandlers) handler(step);\n },\n onMessage: (msg, reply) => {\n if (messageHandlers.length > 0) {\n for (const handler of messageHandlers) handler(msg, reply);\n } else {\n // No handlers, auto-reply\n reply('');\n }\n },\n });\n }\n return resultPromise;\n },\n };\n\n return session;\n },\n\n /** Stream exploration events as an async generator */\n async *stream(prompt: string): AsyncGenerator<ExploreEvent, ExploreResult, undefined> {\n const events: ExploreEvent[] = [];\n let resolveNext: (() => void) | null = null;\n let done = false;\n\n const resultPromise = runExplore(prompt, {\n onStep: (step) => {\n events.push({\n type: 'step',\n step: step.step,\n searchRequest: step.searchRequest,\n contextsFound: step.contextsFound,\n isFinal: step.isFinal,\n });\n resolveNext?.();\n },\n onMessage: (msg, reply) => {\n events.push({\n type: 'message',\n from: msg.from,\n content: msg.content,\n timestamp: msg.timestamp,\n });\n resolveNext?.();\n // Auto-reply in streaming mode\n reply('Continue with your best judgment.');\n },\n });\n\n // Yield events as they come in\n while (!done) {\n if (events.length > 0) {\n yield events.shift()!;\n } else {\n // Check if the result is already done\n const raceResult = await Promise.race([\n resultPromise.then((r) => ({ type: 'done' as const, result: r })),\n new Promise<{ type: 'event' }>((resolve) => {\n resolveNext = () => resolve({ type: 'event' });\n }),\n ]);\n\n if (raceResult.type === 'done') {\n // Drain remaining events\n while (events.length > 0) {\n yield events.shift()!;\n }\n done = true;\n return raceResult.result;\n }\n }\n }\n\n return await resultPromise;\n },\n };\n}\n\n/** Deduplicate contexts, keeping the latest version of each file */\nfunction deduplicateContexts(contexts: WarpGrepContext[]): WarpGrepContext[] {\n const map = new Map<string, WarpGrepContext>();\n for (const ctx of contexts) {\n const existing = map.get(ctx.file);\n if (!existing || ctx.content.length > existing.content.length) {\n map.set(ctx.file, ctx);\n }\n }\n return Array.from(map.values());\n}\n"],"mappings":";;;;;;;;;;;AAIA,SAAS,MAAM,cAAc,mBAAmB;AAEhD,SAAS,SAAS;AAsBlB,IAAM,oBAA4C;AAAA,EAChD,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,UAAU;AACZ;AAEA,SAAS,YAAY,QAAuC;AAC1D,SAAO,OAAO,YAAY,kBAAkB,OAAO,gBAAgB,QAAQ,KAAK;AAClF;AAKO,SAAS,sBAAsB,QAA6B;AACjE,MAAI,CAAC,OAAO,UAAU;AACpB,UAAM,IAAI,MAAM,2CAA2C;AAAA,EAC7D;AAEA,QAAM,WAAW,IAAI,eAAe;AAAA,IAClC,aAAa,OAAO;AAAA,EACtB,CAAC;AAED,QAAM,eAAe,OAAO,gBAAgB;AAC5C,QAAM,eAAe,OAAO,gBAAgB;AAG5C,iBAAe,WACb,QACA,YAGI,CAAC,GACmB;AACxB,UAAM,YAAY,KAAK,IAAI;AAC3B,UAAM,cAAiC,CAAC;AACxC,QAAI,cAAc;AAElB,UAAM,YAAY,OAAO;AACzB,UAAM,i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AACF;AAGA,SAAS,oBAAoB,UAAgD;AAC3E,QAAM,MAAM,oBAAI,IAA6B;AAC7C,aAAW,OAAO,UAAU;AAC1B,UAAM,WAAW,IAAI,IAAI,IAAI,IAAI;AACjC,QAAI,CAAC,YAAY,IAAI,QAAQ,SAAS,SAAS,QAAQ,QAAQ;AAC7D,UAAI,IAAI,IAAI,MAAM,GAAG;AAAA,IACvB;AAAA,EACF;AACA,SAAO,MAAM,KAAK,IAAI,OAAO,CAAC;AAChC;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../subagents/prompts.ts"],"sourcesContent":["/**\n * System prompts and tool descriptions for Explore subagent\n */\n\nimport type { ExploreThoroughness } from './types.js';\n\nconst THOROUGHNESS_INSTRUCTIONS: Record<ExploreThoroughness, string> = {\n quick: `Do 1-2 targeted searches. Find the most relevant file/function quickly and summarize. Don't go deep.`,\n medium: `Do 2-4 searches. Start broad, then follow up on the most promising leads. Cover the main aspects.`,\n thorough: `Do 4-8 searches. Explore systematically: start broad, then drill into each relevant area. Cover edge cases, related files, and the full call chain. Leave no stone unturned.`,\n};\n\nexport function getSystemPrompt(thoroughness: ExploreThoroughness = 'medium'): string {\n return `You are a codebase exploration specialist. Your job is to search a codebase and return a concise, accurate summary of what you find.\n\n## Mode\nREAD-ONLY. You cannot modify files. You can only search and read code.\n\n## Strategy\n${THOROUGHNESS_INSTRUCTIONS[thoroughness]}\n\n- Use multiple focused searches rather than one vague search\n- Follow imports, function calls, and type references to build complete understanding\n- If a search returns no results, try alternative terms (e.g., \"auth\" vs \"authentication\" vs \"login\")\n- Look at both implementation and tests when relevant\n\n## Communication\nYou have a \\`send_message\\` tool. Use it when:\n- You hit a fork in the road and need guidance (\"Found auth in both src/middleware/ and legacy/auth/. Which should I focus on?\")\n- You need clarification on ambiguous requests (\"There are 3 auth strategies: JWT, session, OAuth. Which one?\")\n- You want to share a key finding before continuing (\"The main auth handler is in src/auth/index.ts. It delegates to strategy-specific modules. Continuing to trace JWT flow.\")\n\nDo NOT use send_message for routine status updates. Only use it when you genuinely need input or have a significant finding worth sharing before you're done.\n\n## Output\nWhen you have enough information, output your final summary. Structure it as:\n1. Direct answer to the question\n2. Key files and their roles\n3. How the pieces connect\n\nBe concise. The summary should be useful to another AI model that will use your findings to complete a task.`;\n}\n\nexport const CODEBASE_SEARCH_TOOL = {\n name: 'codebase_search',\n description: 'Search the codebase for relevant code. Takes a natural language search request describing what you want to find. Returns matching file contents with line numbers.',\n input_schema: {\n type: 'object' as const,\n properties: {\n searchRequest: {\n type: 'string' as const,\n description: 'Natural language description of what to search for in the codebase',\n },\n },\n required: ['searchRequest'] as const,\n additionalProperties: false as const,\n },\n};\n\nexport const SEND_MESSAGE_TOOL = {\n name: 'send_message',\n description: 'Send a message to the orchestrating agent. Use this to ask questions, request clarification, or share important findings. The orchestrator may reply with additional context. Use sparingly — only when you genuinely need input or have a significant finding.',\n input_schema: {\n type: 'object' as const,\n properties: {\n message: {\n type: 'string' as const,\n description: 'The message to send to the orchestrator',\n },\n },\n required: ['message'] as const,\n additionalProperties: false as const,\n },\n};\n"],"mappings":";AAMA,IAAM,4BAAiE;AAAA,EACrE,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,UAAU;AACZ;AAEO,SAAS,gBAAgB,eAAoC,UAAkB;AACpF,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMP,0BAA0B,YAAY,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAsBzC;AAEO,IAAM,uBAAuB;AAAA,EAClC,MAAM;AAAA,EACN,aAAa;AAAA,EACb,cAAc;AAAA,IACZ,MAAM;AAAA,IACN,YAAY;AAAA,MACV,eAAe;AAAA,QACb,MAAM;AAAA,QACN,aAAa;AAAA,MACf;AAAA,IACF;AAAA,IACA,UAAU,CAAC,eAAe;AAAA,IAC1B,sBAAsB;AAAA,EACxB;AACF;AAEO,IAAM,oBAAoB;AAAA,EAC/B,MAAM;AAAA,EACN,aAAa;AAAA,EACb,cAAc;AAAA,IACZ,MAAM;AAAA,IACN,YAAY;AAAA,MACV,SAAS;AAAA,QACP,MAAM;AAAA,QACN,aAAa;AAAA,MACf;AAAA,IACF;AAAA,IACA,UAAU,CAAC,SAAS;AAAA,IACpB,sBAAsB;AAAA,EACxB;AACF;","names":[]}
|