@morphllm/morphsdk 0.2.162 → 0.2.163

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/dist/{chunk-YBKT2UOK.js → chunk-2KDJKRZG.js} +2 -2
  2. package/dist/chunk-5AM23TC7.js +42 -0
  3. package/dist/chunk-5AM23TC7.js.map +1 -0
  4. package/dist/{chunk-UETFIUIG.js → chunk-5BMWOPYW.js} +2 -2
  5. package/dist/{chunk-UKT3CKC7.js → chunk-5FYJMU6H.js} +2 -2
  6. package/dist/{chunk-DRTPCCEI.js → chunk-6PFGM4CM.js} +2 -2
  7. package/dist/{chunk-YRHM3RCQ.js → chunk-6YOSNPHS.js} +2 -2
  8. package/dist/{chunk-XUV5B27P.js → chunk-6YTCBLRI.js} +2 -2
  9. package/dist/{chunk-VQSLLYKE.js → chunk-COUYHTIO.js} +2 -2
  10. package/dist/{chunk-Y4NYT5L6.js → chunk-CUMC7Z5R.js} +11 -26
  11. package/dist/chunk-CUMC7Z5R.js.map +1 -0
  12. package/dist/{chunk-4Q6VFODP.js → chunk-EJBWDGTH.js} +2 -2
  13. package/dist/{chunk-UZX7SY33.js → chunk-FNCPPCPV.js} +2 -2
  14. package/dist/{chunk-4GQNYJBB.js → chunk-FQXUOZBX.js} +9 -12
  15. package/dist/chunk-FQXUOZBX.js.map +1 -0
  16. package/dist/{chunk-DXMNKPB6.js → chunk-HBH56DLN.js} +2 -2
  17. package/dist/{chunk-JVKGSMEF.js → chunk-HFN3YCF4.js} +2 -2
  18. package/dist/{chunk-NKUGRAYU.js → chunk-HMGC7FLZ.js} +2 -2
  19. package/dist/{chunk-4U5JFT6X.js → chunk-KHR4CZMX.js} +24 -17
  20. package/dist/{chunk-4U5JFT6X.js.map → chunk-KHR4CZMX.js.map} +1 -1
  21. package/dist/{chunk-OGMHU4PJ.js → chunk-LSHQISAX.js} +9 -2
  22. package/dist/chunk-LSHQISAX.js.map +1 -0
  23. package/dist/{chunk-ZG3YLRR5.js → chunk-LST7MZOZ.js} +7 -2
  24. package/dist/chunk-LST7MZOZ.js.map +1 -0
  25. package/dist/{chunk-5XTA7GCY.js → chunk-LW5EAPZ6.js} +2 -2
  26. package/dist/{chunk-UVRC4LKZ.js → chunk-NNATBEOF.js} +2 -2
  27. package/dist/{chunk-CNFHKQ42.js → chunk-OKFW4KGU.js} +2 -2
  28. package/dist/{chunk-PWGBAVQ5.js → chunk-QXGOEDZD.js} +2 -2
  29. package/dist/{chunk-OOE2TKKY.js → chunk-SELI567A.js} +12 -21
  30. package/dist/chunk-SELI567A.js.map +1 -0
  31. package/dist/{chunk-LECHLXI4.js → chunk-VMNEYCFP.js} +17 -6
  32. package/dist/chunk-VMNEYCFP.js.map +1 -0
  33. package/dist/{chunk-LZQBVEY2.js → chunk-WM6SBI4B.js} +35 -27
  34. package/dist/chunk-WM6SBI4B.js.map +1 -0
  35. package/dist/{chunk-7QMX45QD.js → chunk-ZMCDGAGF.js} +33 -6
  36. package/dist/chunk-ZMCDGAGF.js.map +1 -0
  37. package/dist/client.cjs +184 -115
  38. package/dist/client.cjs.map +1 -1
  39. package/dist/client.d.ts +1 -1
  40. package/dist/client.js +23 -22
  41. package/dist/edge.cjs +82 -50
  42. package/dist/edge.cjs.map +1 -1
  43. package/dist/edge.js +5 -4
  44. package/dist/index.cjs +186 -115
  45. package/dist/index.cjs.map +1 -1
  46. package/dist/index.d.ts +1 -1
  47. package/dist/index.js +23 -22
  48. package/dist/modelrouter/core.cjs +50 -25
  49. package/dist/modelrouter/core.cjs.map +1 -1
  50. package/dist/modelrouter/core.js +4 -3
  51. package/dist/modelrouter/index.cjs +50 -25
  52. package/dist/modelrouter/index.cjs.map +1 -1
  53. package/dist/modelrouter/index.js +4 -3
  54. package/dist/subagents/anthropic.cjs +85 -12
  55. package/dist/subagents/anthropic.cjs.map +1 -1
  56. package/dist/subagents/anthropic.js +5 -4
  57. package/dist/subagents/vercel.cjs +85 -12
  58. package/dist/subagents/vercel.cjs.map +1 -1
  59. package/dist/subagents/vercel.js +5 -4
  60. package/dist/tools/browser/anthropic.cjs +47 -9
  61. package/dist/tools/browser/anthropic.cjs.map +1 -1
  62. package/dist/tools/browser/anthropic.js +6 -5
  63. package/dist/tools/browser/core.cjs +50 -19
  64. package/dist/tools/browser/core.cjs.map +1 -1
  65. package/dist/tools/browser/core.js +5 -4
  66. package/dist/tools/browser/index.cjs +50 -19
  67. package/dist/tools/browser/index.cjs.map +1 -1
  68. package/dist/tools/browser/index.js +8 -7
  69. package/dist/tools/browser/index.js.map +1 -1
  70. package/dist/tools/browser/openai.cjs +47 -9
  71. package/dist/tools/browser/openai.cjs.map +1 -1
  72. package/dist/tools/browser/openai.js +6 -5
  73. package/dist/tools/browser/profiles/core.cjs +6 -1
  74. package/dist/tools/browser/profiles/core.cjs.map +1 -1
  75. package/dist/tools/browser/profiles/core.js +3 -3
  76. package/dist/tools/browser/profiles/index.cjs +6 -1
  77. package/dist/tools/browser/profiles/index.cjs.map +1 -1
  78. package/dist/tools/browser/profiles/index.js +3 -3
  79. package/dist/tools/browser/vercel.cjs +47 -9
  80. package/dist/tools/browser/vercel.cjs.map +1 -1
  81. package/dist/tools/browser/vercel.js +6 -5
  82. package/dist/tools/codebase_search/anthropic.cjs +48 -11
  83. package/dist/tools/codebase_search/anthropic.cjs.map +1 -1
  84. package/dist/tools/codebase_search/anthropic.js +5 -4
  85. package/dist/tools/codebase_search/core.cjs +48 -11
  86. package/dist/tools/codebase_search/core.cjs.map +1 -1
  87. package/dist/tools/codebase_search/core.js +4 -3
  88. package/dist/tools/codebase_search/index.cjs +48 -11
  89. package/dist/tools/codebase_search/index.cjs.map +1 -1
  90. package/dist/tools/codebase_search/index.js +7 -6
  91. package/dist/tools/codebase_search/openai.cjs +48 -11
  92. package/dist/tools/codebase_search/openai.cjs.map +1 -1
  93. package/dist/tools/codebase_search/openai.js +5 -4
  94. package/dist/tools/codebase_search/vercel.cjs +48 -11
  95. package/dist/tools/codebase_search/vercel.cjs.map +1 -1
  96. package/dist/tools/codebase_search/vercel.js +5 -4
  97. package/dist/tools/fastapply/anthropic.cjs +94 -31
  98. package/dist/tools/fastapply/anthropic.cjs.map +1 -1
  99. package/dist/tools/fastapply/anthropic.js +5 -4
  100. package/dist/tools/fastapply/apply.cjs +74 -26
  101. package/dist/tools/fastapply/apply.cjs.map +1 -1
  102. package/dist/tools/fastapply/apply.js +3 -2
  103. package/dist/tools/fastapply/core.cjs +94 -31
  104. package/dist/tools/fastapply/core.cjs.map +1 -1
  105. package/dist/tools/fastapply/core.js +4 -3
  106. package/dist/tools/fastapply/index.cjs +94 -31
  107. package/dist/tools/fastapply/index.cjs.map +1 -1
  108. package/dist/tools/fastapply/index.js +7 -6
  109. package/dist/tools/fastapply/openai.cjs +94 -31
  110. package/dist/tools/fastapply/openai.cjs.map +1 -1
  111. package/dist/tools/fastapply/openai.js +5 -4
  112. package/dist/tools/fastapply/vercel.cjs +94 -31
  113. package/dist/tools/fastapply/vercel.cjs.map +1 -1
  114. package/dist/tools/fastapply/vercel.js +5 -4
  115. package/dist/tools/index.cjs +94 -31
  116. package/dist/tools/index.cjs.map +1 -1
  117. package/dist/tools/index.js +7 -6
  118. package/dist/tools/utils/resilience.cjs +6 -1
  119. package/dist/tools/utils/resilience.cjs.map +1 -1
  120. package/dist/tools/utils/resilience.js +2 -2
  121. package/dist/tools/warp_grep/agent/runner.cjs +74 -5
  122. package/dist/tools/warp_grep/agent/runner.cjs.map +1 -1
  123. package/dist/tools/warp_grep/agent/runner.js +3 -2
  124. package/dist/tools/warp_grep/anthropic.cjs +85 -12
  125. package/dist/tools/warp_grep/anthropic.cjs.map +1 -1
  126. package/dist/tools/warp_grep/anthropic.js +5 -4
  127. package/dist/tools/warp_grep/client.cjs +85 -12
  128. package/dist/tools/warp_grep/client.cjs.map +1 -1
  129. package/dist/tools/warp_grep/client.js +4 -3
  130. package/dist/tools/warp_grep/gemini.cjs +85 -12
  131. package/dist/tools/warp_grep/gemini.cjs.map +1 -1
  132. package/dist/tools/warp_grep/gemini.js +4 -3
  133. package/dist/tools/warp_grep/gemini.js.map +1 -1
  134. package/dist/tools/warp_grep/index.cjs +85 -12
  135. package/dist/tools/warp_grep/index.cjs.map +1 -1
  136. package/dist/tools/warp_grep/index.js +4 -3
  137. package/dist/tools/warp_grep/openai.cjs +85 -12
  138. package/dist/tools/warp_grep/openai.cjs.map +1 -1
  139. package/dist/tools/warp_grep/openai.js +5 -4
  140. package/dist/tools/warp_grep/vercel.cjs +85 -12
  141. package/dist/tools/warp_grep/vercel.cjs.map +1 -1
  142. package/dist/tools/warp_grep/vercel.d.ts +1 -1
  143. package/dist/tools/warp_grep/vercel.js +5 -4
  144. package/dist/version.cjs +6 -1
  145. package/dist/version.cjs.map +1 -1
  146. package/dist/version.js +1 -1
  147. package/package.json +6 -1
  148. package/dist/chunk-4GQNYJBB.js.map +0 -1
  149. package/dist/chunk-7QMX45QD.js.map +0 -1
  150. package/dist/chunk-LECHLXI4.js.map +0 -1
  151. package/dist/chunk-LZQBVEY2.js.map +0 -1
  152. package/dist/chunk-OGMHU4PJ.js.map +0 -1
  153. package/dist/chunk-OOE2TKKY.js.map +0 -1
  154. package/dist/chunk-Y4NYT5L6.js.map +0 -1
  155. package/dist/chunk-ZG3YLRR5.js.map +0 -1
  156. package/dist/{chunk-YBKT2UOK.js.map → chunk-2KDJKRZG.js.map} +0 -0
  157. package/dist/{chunk-UETFIUIG.js.map → chunk-5BMWOPYW.js.map} +0 -0
  158. package/dist/{chunk-UKT3CKC7.js.map → chunk-5FYJMU6H.js.map} +0 -0
  159. package/dist/{chunk-DRTPCCEI.js.map → chunk-6PFGM4CM.js.map} +0 -0
  160. package/dist/{chunk-YRHM3RCQ.js.map → chunk-6YOSNPHS.js.map} +0 -0
  161. package/dist/{chunk-XUV5B27P.js.map → chunk-6YTCBLRI.js.map} +0 -0
  162. package/dist/{chunk-VQSLLYKE.js.map → chunk-COUYHTIO.js.map} +0 -0
  163. package/dist/{chunk-4Q6VFODP.js.map → chunk-EJBWDGTH.js.map} +0 -0
  164. package/dist/{chunk-UZX7SY33.js.map → chunk-FNCPPCPV.js.map} +0 -0
  165. package/dist/{chunk-DXMNKPB6.js.map → chunk-HBH56DLN.js.map} +0 -0
  166. package/dist/{chunk-JVKGSMEF.js.map → chunk-HFN3YCF4.js.map} +0 -0
  167. package/dist/{chunk-NKUGRAYU.js.map → chunk-HMGC7FLZ.js.map} +0 -0
  168. package/dist/{chunk-5XTA7GCY.js.map → chunk-LW5EAPZ6.js.map} +0 -0
  169. package/dist/{chunk-UVRC4LKZ.js.map → chunk-NNATBEOF.js.map} +0 -0
  170. package/dist/{chunk-CNFHKQ42.js.map → chunk-OKFW4KGU.js.map} +0 -0
  171. package/dist/{chunk-PWGBAVQ5.js.map → chunk-QXGOEDZD.js.map} +0 -0
  172. package/dist/{client-PkB7g9SA.d.ts → client-DsAAqupx.d.ts} +1 -1
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  ProfilesClient
3
- } from "./chunk-PWGBAVQ5.js";
3
+ } from "./chunk-QXGOEDZD.js";
4
4
  import {
5
5
  buildEmbedCode,
6
6
  buildLiveIframe,
@@ -10,7 +10,10 @@ import {
10
10
  import {
11
11
  fetchWithRetry,
12
12
  withTimeout
13
- } from "./chunk-UZX7SY33.js";
13
+ } from "./chunk-FNCPPCPV.js";
14
+ import {
15
+ logger
16
+ } from "./chunk-5AM23TC7.js";
14
17
 
15
18
  // tools/browser/core.ts
16
19
  var DEFAULT_CONFIG = {
@@ -46,11 +49,7 @@ var BrowserClient = class {
46
49
  if (!hasTask && !hasDiff) {
47
50
  throw new Error('Browser task requires either "task" (natural language) or "diff" (PR-review planning)');
48
51
  }
49
- if (debug) {
50
- const preview = (input.task ?? "").slice(0, 60);
51
- console.log(`[Browser] createTask: "${preview}..." url=${input.url || "none"}`);
52
- console.log(`[Browser] Calling async endpoint: ${apiUrl}/browser-task/async`);
53
- }
52
+ logger.debug("Browser", "create_task", { task: (input.task ?? "").slice(0, 100), url: input.url, endpoint: `${apiUrl}/browser-task/async` });
54
53
  const headers = { "Content-Type": "application/json" };
55
54
  if (this.config.apiKey) headers["Authorization"] = `Bearer ${this.config.apiKey}`;
56
55
  const response = await fetch(`${apiUrl}/browser-task/async`, {
@@ -80,14 +79,11 @@ var BrowserClient = class {
80
79
  });
81
80
  if (!response.ok) {
82
81
  const errorText = await response.text().catch(() => response.statusText);
83
- if (debug) console.error(`[Browser] Error: ${response.status} - ${errorText}`);
82
+ logger.error("Browser", "create_task_error", { status: response.status, error: errorText });
84
83
  throw new Error(`HTTP ${response.status}: ${errorText}`);
85
84
  }
86
85
  const result = mapTaskResult(await response.json());
87
- if (debug) {
88
- const debugUrl = result.debugUrl;
89
- console.log(`[Browser] \u2705 Task created: recordingId=${result.recordingId ?? "none"} debugUrl=${debugUrl ? "available" : "none"}`);
90
- }
86
+ logger.debug("Browser", "task_created", { recording_id: result.recordingId, task_id: result.taskId, debug_url: !!result.debugUrl });
91
87
  if ("schema" in input) {
92
88
  return wrapTaskResponseWithSchema(result, this.config, input.schema);
93
89
  } else {
@@ -147,10 +143,7 @@ async function executeBrowserTask(input, config = {}) {
147
143
  error: "maxSteps must be between 1 and 50. Use more steps for complex multi-page flows."
148
144
  };
149
145
  }
150
- if (debug) {
151
- console.log(`[Browser] Task: "${input.task.slice(0, 60)}..." url=${input.url || "none"} maxSteps=${input.maxSteps ?? 10}`);
152
- console.log(`[Browser] Recording: ${input.recordVideo ? "yes" : "no"} | Calling ${apiUrl}/browser-task`);
153
- }
146
+ logger.debug("Browser", "execute_start", { task: input.task.slice(0, 100), url: input.url, max_steps: input.maxSteps ?? 10, record_video: input.recordVideo ?? false });
154
147
  const startTime = Date.now();
155
148
  try {
156
149
  const headers = { "Content-Type": "application/json" };
@@ -189,14 +182,12 @@ async function executeBrowserTask(input, config = {}) {
189
182
  );
190
183
  if (!response.ok) {
191
184
  const errorText = await response.text().catch(() => response.statusText);
192
- if (debug) console.error(`[Browser] Error: ${response.status} - ${errorText}`);
185
+ logger.error("Browser", "execute_error", { status: response.status, error: errorText });
193
186
  throw new Error(`HTTP ${response.status}: ${errorText}`);
194
187
  }
195
188
  const result = mapTaskResult(await response.json());
196
189
  const elapsed = Date.now() - startTime;
197
- if (debug) {
198
- console.log(`[Browser] \u2705 ${result.success ? "Success" : "Failed"} in ${elapsed}ms | steps=${result.stepsTaken ?? 0} recordingId=${result.recordingId ?? "none"}`);
199
- }
190
+ logger.debug("Browser", "execute_complete", { success: result.success, latency_ms: elapsed, steps: result.stepsTaken ?? 0, recording_id: result.recordingId });
200
191
  return result;
201
192
  } catch (error) {
202
193
  if (error instanceof Error) {
@@ -609,4 +600,4 @@ export {
609
600
  getWebp,
610
601
  checkHealth
611
602
  };
612
- //# sourceMappingURL=chunk-OOE2TKKY.js.map
603
+ //# sourceMappingURL=chunk-SELI567A.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../tools/browser/core.ts"],"sourcesContent":["/**\n * Core implementation for browser automation tasks\n */\n\nimport { fetchWithRetry, withTimeout } from '../utils/resilience.js';\nimport { logger } from '../../logger.js';\nimport type {\n BrowserConfig,\n BrowserTaskInput,\n BrowserTaskInputWithSchema,\n BrowserTaskResult,\n BrowserTaskWithPromise,\n BrowserTaskWithPromiseAndSchema,\n RecordingStatus,\n RecordingWithMethods,\n ErrorsResponse,\n LiveSessionOptions,\n IframeOptions,\n WebpOptions,\n WebpResponse,\n} from './types.js';\nimport { buildLiveUrl, buildLiveIframe, buildEmbedCode, resolvePreset } from './live.js';\nimport { ProfilesClient } from './profiles/core.js';\n\nconst DEFAULT_CONFIG = {\n apiUrl: process.env.MORPH_ENVIRONMENT === 'DEV' \n ? 'http://localhost:8000'\n : 'https://browser.morphllm.com',\n timeout: 1000000, // 10 minutes for complex tasks\n debug: false,\n};\n\n/**\n * BrowserClient class for easier usage with instance configuration\n */\nexport class BrowserClient {\n private config: BrowserConfig;\n\n /**\n * Profile management - create and manage browser profiles for storing login state.\n */\n public profiles: ProfilesClient;\n\n constructor(config: BrowserConfig = {}) {\n this.config = {\n ...DEFAULT_CONFIG,\n ...config,\n };\n this.profiles = new ProfilesClient(this.config);\n }\n\n /**\n * Execute a browser automation task\n */\n async execute(input: BrowserTaskInput): Promise<BrowserTaskResult> {\n return executeBrowserTask(input, this.config);\n }\n\n async createTask(input: BrowserTaskInput): Promise<BrowserTaskWithPromise>;\n async createTask<T>(input: BrowserTaskInputWithSchema<T>): Promise<BrowserTaskWithPromiseAndSchema<T>>;\n async createTask<T>(\n input: BrowserTaskInput | BrowserTaskInputWithSchema<T>\n ): Promise<BrowserTaskWithPromise | BrowserTaskWithPromiseAndSchema<T>> {\n const apiUrl = this.config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const debug = this.config.debug || false;\n \n const hasTask = typeof input.task === 'string' && input.task.trim().length > 0;\n const hasDiff = typeof (input as any).diff === 'string' && (input as any).diff.trim().length > 0;\n\n if (!hasTask && !hasDiff) {\n throw new Error('Browser task requires either \"task\" (natural language) or \"diff\" (PR-review planning)');\n }\n\n logger.debug('Browser', 'create_task', { task: (input.task ?? '').slice(0, 100), url: input.url, endpoint: `${apiUrl}/browser-task/async` });\n \n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (this.config.apiKey) headers['Authorization'] = `Bearer ${this.config.apiKey}`;\n \n // Call ASYNC endpoint for immediate return with live URL\n const response = await fetch(`${apiUrl}/browser-task/async`, {\n method: 'POST',\n headers,\n body: JSON.stringify({\n task: input.task,\n diff: input.diff,\n url: input.url,\n max_steps: input.maxSteps ?? 10,\n model: input.model ?? 'morph-computer-use-v0',\n viewport_width: input.viewportWidth ?? 1280,\n viewport_height: input.viewportHeight ?? 720,\n external_id: input.externalId,\n repo_id: input.repoId,\n repo_full_name: input.repoFullName,\n commit_id: input.commitId,\n record_video: input.recordVideo ?? false,\n video_width: input.videoWidth ?? input.viewportWidth ?? 1280,\n video_height: input.videoHeight ?? input.viewportHeight ?? 720,\n allow_resizing: input.allowResizing ?? false,\n structured_output: 'schema' in input ? stringifyStructuredOutput(input.schema) : undefined,\n auth: input.auth,\n profile_id: input.profileId,\n force_query_params: input.forceQueryParams,\n }),\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n logger.error('Browser', 'create_task_error', { status: response.status, error: errorText });\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const result = mapTaskResult(await response.json());\n logger.debug('Browser', 'task_created', { recording_id: result.recordingId, task_id: result.taskId, debug_url: !!result.debugUrl });\n \n if ('schema' in input) {\n return wrapTaskResponseWithSchema(result, this.config, input.schema);\n } else {\n return wrapTaskResponse(result, this.config);\n }\n }\n\n /**\n * Execute task with recording and wait for video to be ready\n */\n async executeWithRecording(\n input: BrowserTaskInput & { recordVideo: true }\n ): Promise<BrowserTaskResult & { recording?: RecordingWithMethods }> {\n return executeWithRecording(input, this.config);\n }\n\n /**\n * Get recording status and URLs\n */\n async getRecording(recordingId: string): Promise<RecordingWithMethods> {\n return getRecording(recordingId, this.config);\n }\n\n /**\n * Wait for recording to complete with automatic polling\n */\n async waitForRecording(\n recordingId: string,\n options?: { timeout?: number; pollInterval?: number }\n ): Promise<RecordingWithMethods> {\n return waitForRecording(recordingId, this.config, options);\n }\n\n /**\n * Get errors from recording with screenshots\n */\n async getErrors(recordingId: string): Promise<ErrorsResponse> {\n return getErrors(recordingId, this.config);\n }\n\n /**\n * Get animated WebP preview of recording\n */\n async getWebp(\n recordingId: string,\n options?: WebpOptions\n ): Promise<WebpResponse> {\n return getWebp(recordingId, this.config, options);\n }\n\n /**\n * Check if browser worker service is healthy\n */\n async checkHealth(): Promise<{\n ok: boolean;\n google_configured: boolean;\n database_configured: boolean;\n s3_configured: boolean;\n error?: string;\n }> {\n return checkHealth(this.config);\n }\n}\n\n/**\n * Execute a natural language browser automation task\n * \n * Returns the full task result including rich agent history data (urls, errors, \n * action_history, judgement, etc.). When using this as an agent tool, use the\n * formatResult() functions from the SDK adapters to return a concise summary.\n * \n * @param input - Task parameters\n * @param config - Optional configuration (apiKey, apiUrl to override default)\n * @returns Task result with success status, findings, and comprehensive execution history\n * \n * @example\n * ```typescript\n * const result = await executeBrowserTask(\n * {\n * task: \"Test checkout flow for buying a pineapple\",\n * url: \"https://3000-abc.e2b.dev\",\n * maxSteps: 20,\n * repoId: \"my-project\",\n * commitId: \"uuid-here\"\n * },\n * {\n * apiKey: process.env.MORPH_API_KEY,\n * // apiUrl: 'http://localhost:8001' // Override for local testing\n * }\n * );\n * \n * if (result.success) {\n * console.log('Task completed:', result.result);\n * console.log('URLs visited:', result.urls);\n * console.log('Actions taken:', result.actionNames);\n * console.log('Has errors:', result.hasErrors);\n * console.log('Replay:', result.replayUrl);\n * }\n * ```\n */\nexport async function executeBrowserTask(\n input: BrowserTaskInput,\n config: BrowserConfig = {}\n): Promise<BrowserTaskResult> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const timeout = config.timeout || DEFAULT_CONFIG.timeout;\n const debug = config.debug || false;\n\n if (!input.task || input.task.trim().length === 0) {\n return { \n success: false, \n error: 'Task description is required. Example: \"Go to example.com and click the login button\"' \n };\n }\n\n if (input.maxSteps !== undefined && (input.maxSteps < 1 || input.maxSteps > 50)) {\n return { \n success: false, \n error: 'maxSteps must be between 1 and 50. Use more steps for complex multi-page flows.'\n };\n }\n\n logger.debug('Browser', 'execute_start', { task: input.task.slice(0, 100), url: input.url, max_steps: input.maxSteps ?? 10, record_video: input.recordVideo ?? false });\n\n const startTime = Date.now();\n\n try {\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (config.apiKey) headers['Authorization'] = `Bearer ${config.apiKey}`;\n\n const fetchPromise = fetchWithRetry(\n `${apiUrl}/browser-task`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({\n task: input.task,\n url: input.url,\n max_steps: input.maxSteps ?? 10,\n model: input.model ?? 'morph-computer-use-v0',\n viewport_width: input.viewportWidth ?? 1280,\n viewport_height: input.viewportHeight ?? 720,\n external_id: input.externalId,\n repo_id: input.repoId,\n commit_id: input.commitId,\n record_video: input.recordVideo ?? false,\n video_width: input.videoWidth ?? input.viewportWidth ?? 1280,\n video_height: input.videoHeight ?? input.viewportHeight ?? 720,\n allow_resizing: input.allowResizing ?? false,\n structured_output: input.structuredOutput,\n auth: input.auth,\n profile_id: input.profileId,\n force_query_params: input.forceQueryParams,\n }),\n },\n config.retryConfig\n );\n\n const response = await withTimeout(\n fetchPromise,\n timeout,\n `Browser task timed out after ${timeout}ms. Consider increasing timeout or reducing maxSteps.`\n );\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n logger.error('Browser', 'execute_error', { status: response.status, error: errorText });\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const result: BrowserTaskResult = mapTaskResult(await response.json());\n const elapsed = Date.now() - startTime;\n logger.debug('Browser', 'execute_complete', { success: result.success, latency_ms: elapsed, steps: result.stepsTaken ?? 0, recording_id: result.recordingId });\n\n return result;\n\n } catch (error) {\n if (error instanceof Error) {\n // Handle network errors\n if (error.message.includes('ECONNREFUSED') || error.message.includes('fetch failed')) {\n return {\n success: false,\n error: `Cannot connect to browser worker at ${apiUrl}. Ensure the service is running and accessible. For local dev, set MORPH_ENVIRONMENT=DEV.`,\n };\n }\n\n return {\n success: false,\n error: error.message,\n };\n }\n\n return {\n success: false,\n error: String(error),\n };\n }\n}\n\n/**\n * Get recording status and video URL\n * \n * @param recordingId - Recording UUID from BrowserTaskResult\n * @param config - Configuration with apiKey\n * @returns Recording with convenience methods (.getWebp(), .getErrors())\n * \n * @example\n * ```typescript\n * const recording = await getRecording('uuid-here', { apiKey: 'key' });\n * \n * // Get animated WebP\n * const { webpUrl } = await recording.getWebp({ width: 780 });\n * \n * // Get errors with screenshots\n * const { errors } = await recording.getErrors();\n * ```\n */\nexport async function getRecording(\n recordingId: string,\n config: BrowserConfig = {}\n): Promise<RecordingWithMethods> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const debug = config.debug || false;\n\n if (!config.apiKey) {\n throw new Error('API key required for getRecording');\n }\n\n if (debug) console.log(`[Browser] getRecording: ${recordingId}`);\n\n const response = await fetch(`${apiUrl}/recordings/${recordingId}`, {\n method: 'GET',\n headers: { 'Authorization': `Bearer ${config.apiKey}` },\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n if (debug) console.error(`[Browser] getRecording error: ${response.status} - ${errorText}`);\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const data: RecordingStatus = mapRecordingStatus(await response.json());\n if (debug) console.log(`[Browser] Recording status: ${data.status}`);\n\n // Return recording with convenience methods\n return {\n ...data,\n getWebp: (options?: WebpOptions) => getWebp(recordingId, config, options),\n getErrors: () => getErrors(recordingId, config),\n };\n}\n\n/**\n * Wait for recording to complete with automatic polling\n * \n * @param recordingId - Recording UUID\n * @param config - Configuration with apiKey\n * @param options - Polling options\n * @returns Recording status when completed or errored\n * \n * @example\n * ```typescript\n * const result = await executeBrowserTask({ task: '...', recordVideo: true }, config);\n * if (result.recordingId) {\n * const recording = await waitForRecording(result.recordingId, config, {\n * timeout: 60000, // 1 minute\n * pollInterval: 2000 // Check every 2 seconds\n * });\n * console.log('Video URL:', recording.videoUrl);\n * }\n * ```\n */\nexport async function waitForRecording(\n recordingId: string,\n config: BrowserConfig = {},\n options: { timeout?: number; pollInterval?: number } = {}\n): Promise<RecordingWithMethods> {\n const timeout = options.timeout ?? 60000; // Default 1 minute\n const pollInterval = options.pollInterval ?? 2000; // Default 2 seconds\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeout) {\n const status = await getRecording(recordingId, config);\n \n if (status.status === 'COMPLETED' || status.status === 'ERROR') {\n return status;\n }\n\n // Wait before next poll\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n }\n\n throw new Error(`Recording timeout after ${timeout}ms - status still pending`);\n}\n\n/**\n * Execute task with recording and wait for video to be ready\n * \n * @param input - Task parameters with recordVideo=true\n * @param config - Configuration with apiKey\n * @returns Task result with ready video URL\n * \n * @example\n * ```typescript\n * const result = await executeWithRecording(\n * {\n * task: \"Test checkout flow\",\n * url: \"https://example.com\",\n * recordVideo: true,\n * repoId: \"my-project\"\n * },\n * { apiKey: process.env.MORPH_API_KEY }\n * );\n * \n * console.log('Task result:', result.result);\n * console.log('Video URL:', result.recording?.videoUrl);\n * ```\n */\nexport async function executeWithRecording(\n input: BrowserTaskInput & { recordVideo: true },\n config: BrowserConfig = {}\n): Promise<BrowserTaskResult & { recording?: RecordingWithMethods }> {\n // Execute task with recording\n const taskResult = await executeBrowserTask(input, config);\n\n // If recording was created, wait for it to complete\n if (taskResult.recordingId) {\n try {\n const recording = await waitForRecording(\n taskResult.recordingId,\n config,\n { timeout: 60000, pollInterval: 2000 }\n );\n return {\n ...taskResult,\n recording,\n };\n } catch (error) {\n // Return task result even if recording fails\n // Still attach convenience methods for consistent API\n const errorRecording: RecordingWithMethods = {\n id: taskResult.recordingId,\n status: 'ERROR',\n error: error instanceof Error ? error.message : String(error),\n createdAt: new Date().toISOString(),\n getWebp: (options?: WebpOptions) => getWebp(taskResult.recordingId!, config, options),\n getErrors: () => getErrors(taskResult.recordingId!, config),\n };\n return {\n ...taskResult,\n recording: errorRecording,\n };\n }\n }\n\n return taskResult;\n}\n\n/**\n * Get errors from recording with screenshots\n * \n * Screenshots are captured in real-time (500ms after error occurs) during the browser session.\n * \n * @param recordingId - Recording UUID from BrowserTaskResult\n * @param config - Configuration with apiKey\n * @returns Errors with real-time screenshots\n * \n * @example\n * ```typescript\n * const { errors, totalErrors } = await getErrors('uuid-here', { apiKey: 'key' });\n * \n * console.log(`Found ${totalErrors} errors`);\n * \n * errors.forEach(err => {\n * console.log(`[${err.type}] ${err.message}`);\n * if (err.url) console.log(` URL: ${err.url}`);\n * if (err.screenshotUrl) console.log(` Screenshot: ${err.screenshotUrl}`);\n * \n * // Download screenshot\n * if (err.screenshotUrl) {\n * const response = await fetch(err.screenshotUrl);\n * const screenshot = await response.arrayBuffer();\n * // Save or process screenshot\n * }\n * });\n * ```\n */\nexport async function getErrors(\n recordingId: string,\n config: BrowserConfig = {}\n): Promise<ErrorsResponse> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const debug = config.debug || false;\n\n if (!config.apiKey) {\n throw new Error('API key required for getErrors');\n }\n\n if (debug) console.log(`[Browser] getErrors: ${recordingId}`);\n\n const response = await fetch(`${apiUrl}/recordings/${recordingId}/errors`, {\n method: 'GET',\n headers: { 'Authorization': `Bearer ${config.apiKey}` },\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n if (debug) console.error(`[Browser] getErrors error: ${response.status} - ${errorText}`);\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const errors = mapErrorsResponse(await response.json());\n if (debug) console.log(`[Browser] Found ${errors.totalErrors} errors`);\n\n return errors;\n}\n\n/**\n * Helper to serialize Zod schema for API\n */\nfunction stringifyStructuredOutput(schema: any): string {\n try {\n return JSON.stringify({\n type: 'object',\n description: 'Zod schema definition (Zod v3)',\n zodDef: schema._def,\n });\n } catch (error) {\n console.warn('[Browser] Failed to serialize Zod schema:', error);\n return JSON.stringify({\n type: 'object',\n description: 'Schema serialization failed',\n });\n }\n}\n\n/**\n * Parse and validate structured task output\n */\nfunction parseStructuredTaskOutput<T>(\n result: BrowserTaskResult,\n schema: any\n): BrowserTaskResult & { parsed: T | null } {\n if (!result.output) {\n return { ...result, parsed: null };\n }\n\n try {\n const parsed = JSON.parse(result.output);\n const validated = schema.parse(parsed) as T;\n return { ...result, parsed: validated };\n } catch (error) {\n if (error instanceof SyntaxError) {\n return { ...result, parsed: null };\n }\n throw error;\n }\n}\n\nfunction mapTaskResult(api: any): BrowserTaskResult {\n if (!api || typeof api !== 'object') {\n return api as BrowserTaskResult;\n }\n\n return {\n success: api.success,\n result: api.result,\n error: api.error,\n stepsTaken: api.steps_taken,\n executionTimeMs: api.execution_time_ms,\n urls: api.urls,\n actionNames: api.action_names,\n errors: api.errors,\n modelActions: api.model_actions,\n isDone: api.is_done,\n actionHistory: api.action_history,\n actionResults: api.action_results,\n hasErrors: api.has_errors,\n numberOfSteps: api.number_of_steps,\n judgement: api.judgement,\n isValidated: api.is_validated,\n replayId: api.replay_id,\n replayUrl: api.replay_url,\n recordingId: api.recording_id,\n recordingStatus: api.recording_status,\n taskId: api.task_id,\n status: api.status,\n output: api.output,\n debugUrl: api.debug_url,\n };\n}\n\nfunction mapRecordingStatus(api: any): RecordingStatus {\n return {\n id: api.id,\n status: api.status,\n replayUrl: api.replay_url,\n networkUrl: api.network_url,\n consoleUrl: api.console_url,\n videoUrl: api.video_url,\n result: api.result,\n totalEvents: api.total_events,\n fileSize: api.file_size,\n duration: api.duration,\n error: api.error,\n createdAt: api.created_at,\n };\n}\n\nfunction mapBrowserError(api: any): ErrorsResponse['errors'][number] {\n return {\n type: api.type,\n message: api.message,\n url: api.url,\n timestamp: api.timestamp,\n screenshotUrl: api.screenshot_url,\n capturedAt: api.captured_at,\n status: api.status,\n };\n}\n\nfunction mapErrorsResponse(api: any): ErrorsResponse {\n return {\n recordingId: api.recording_id,\n totalErrors: api.total_errors,\n errors: Array.isArray(api.errors) ? api.errors.map(mapBrowserError) : [],\n };\n}\n\nfunction mapWebpResponse(api: any): WebpResponse {\n return {\n webpUrl: api.webp_url,\n cached: api.cached,\n width: api.width,\n fps: api.fps,\n maxDuration: api.max_duration,\n fileSize: api.file_size,\n maxSizeMb: api.max_size_mb,\n budgetMet: api.budget_met,\n qualityUsed: api.quality_used,\n attempts: api.attempts,\n };\n}\n\n/**\n * Get current task status\n */\nasync function getTaskStatus(\n taskId: string,\n config: BrowserConfig\n): Promise<BrowserTaskResult> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const debug = config.debug || false;\n\n if (debug) console.log(`[Browser] getTaskStatus: ${taskId}`);\n\n const headers: Record<string, string> = {};\n if (config.apiKey) headers['Authorization'] = `Bearer ${config.apiKey}`;\n\n const response = await fetch(`${apiUrl}/tasks/${taskId}`, {\n method: 'GET',\n headers,\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n if (debug) console.error(`[Browser] getTaskStatus error: ${response.status} - ${errorText}`);\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const result: BrowserTaskResult = mapTaskResult(await response.json());\n if (debug) console.log(`[Browser] Task status: ${result.status}`);\n\n return result;\n}\n\n/**\n * Generate live URL for watching task execution in real-time\n */\nfunction generateLiveUrl(taskId: string, config: BrowserConfig): string {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const baseUrl = apiUrl.replace('/api', '');\n return `${baseUrl}/tasks/${taskId}/live`;\n}\n\n/**\n * Poll task until completion\n */\nasync function pollTaskUntilComplete(\n taskId: string,\n config: BrowserConfig,\n pollConfig: { interval?: number; timeout?: number } = {}\n): Promise<BrowserTaskResult> {\n const interval = pollConfig.interval ?? 2000; // 2 seconds\n const timeout = pollConfig.timeout ?? 300000; // 5 minutes\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeout) {\n const status = await getTaskStatus(taskId, config);\n \n if (status.status === 'completed' || status.status === 'failed') {\n return status;\n }\n\n await new Promise(resolve => setTimeout(resolve, interval));\n }\n\n throw new Error(`Task polling timeout after ${timeout}ms`);\n}\n\n/**\n * Wrap task response with convenience methods\n */\nfunction wrapTaskResponse(\n result: BrowserTaskResult,\n config: BrowserConfig\n): BrowserTaskWithPromise {\n const debugUrl = result.debugUrl ?? '';\n\n const wrapped: BrowserTaskWithPromise = {\n ...result,\n debugUrl,\n taskId: result.taskId || '',\n liveUrl: result.taskId\n ? generateLiveUrl(result.taskId, config)\n : debugUrl,\n complete: async (pollConfig?: { interval?: number; timeout?: number }) => {\n // If we have a taskId, poll task status endpoint\n if (result.taskId) {\n return pollTaskUntilComplete(result.taskId!, config, pollConfig);\n }\n // If we have a recordingId, poll recording status instead\n if (result.recordingId) {\n const recording = await waitForRecording(\n result.recordingId,\n config,\n pollConfig\n );\n // Return a result-like object (recording doesn't have full task result)\n return {\n ...result,\n recordingStatus: recording.status,\n } as BrowserTaskResult;\n }\n // No way to poll completion\n throw new Error('Cannot poll completion: no taskId or recordingId available');\n },\n // Add Steel live session helpers - either functional or error-throwing\n getLiveUrl: debugUrl\n ? (options?: LiveSessionOptions) => buildLiveUrl(debugUrl, options)\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help.'\n );\n },\n getLiveIframe: debugUrl\n ? (optionsOrPreset?: string | IframeOptions) => {\n const options = resolvePreset(optionsOrPreset);\n return buildLiveIframe(debugUrl, options);\n }\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help.'\n );\n },\n getEmbedCode: debugUrl\n ? () => buildEmbedCode(debugUrl)\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help.'\n );\n },\n };\n\n return wrapped;\n}\n\n/**\n * Wrap task response with schema validation\n */\nfunction wrapTaskResponseWithSchema<T>(\n result: BrowserTaskResult,\n config: BrowserConfig,\n schema: any\n): BrowserTaskWithPromiseAndSchema<T> {\n const debugUrl = result.debugUrl ?? '';\n const parsed = result.output\n ? parseStructuredTaskOutput<T>(result, schema)\n : { ...result, parsed: null };\n\n const wrapped: BrowserTaskWithPromiseAndSchema<T> = {\n ...parsed,\n debugUrl,\n taskId: result.taskId || '',\n liveUrl: result.taskId\n ? generateLiveUrl(result.taskId, config)\n : debugUrl,\n complete: async (pollConfig?: { interval?: number; timeout?: number }) => {\n // If we have a taskId, poll task status endpoint\n if (result.taskId) {\n const finalResult = await pollTaskUntilComplete(result.taskId!, config, pollConfig);\n return parseStructuredTaskOutput<T>(finalResult, schema);\n }\n // If we have a recordingId, poll recording status instead\n if (result.recordingId) {\n const recording = await waitForRecording(\n result.recordingId,\n config,\n pollConfig\n );\n // Return parsed result (recording doesn't have task output)\n return {\n ...parsed,\n recordingStatus: recording.status,\n };\n }\n // No way to poll completion\n throw new Error('Cannot poll completion: no taskId or recordingId available');\n },\n // Add Steel live session helpers - either functional or error-throwing\n getLiveUrl: debugUrl\n ? (options?: LiveSessionOptions) => buildLiveUrl(debugUrl, options)\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. ' +\n 'Contact support@morphllm.com if you need help enabling live sessions. '\n );\n },\n getLiveIframe: debugUrl\n ? (optionsOrPreset?: string | IframeOptions) => {\n const options = resolvePreset(optionsOrPreset);\n return buildLiveIframe(debugUrl, options);\n }\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. ' +\n 'Contact support@morphllm.com if you need help enabling live sessions.'\n );\n },\n getEmbedCode: debugUrl\n ? () => buildEmbedCode(debugUrl)\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. ' +\n 'Contact support@morphllm.com if you need help enabling live sessions.'\n );\n },\n };\n\n return wrapped;\n}\n\n/**\n * Get animated WebP preview of recording\n * \n * Converts the native video recording to an animated WebP. Results are cached in S3.\n * \n * @param recordingId - Recording UUID from BrowserTaskResult\n * @param config - Configuration with apiKey\n * @param options - WebP generation options\n * @returns WebP URL and metadata\n * \n * @example\n * ```typescript\n * const webp = await getWebp('uuid-here', { apiKey: 'key' }, {\n * width: 780,\n * fps: 10,\n * quality: 65,\n * maxDuration: 15\n * });\n * console.log('WebP URL:', webp.webpUrl);\n * console.log('From cache:', webp.cached);\n * ```\n */\nexport async function getWebp(\n recordingId: string,\n config: BrowserConfig = {},\n options: WebpOptions = {}\n): Promise<WebpResponse> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const debug = config.debug || false;\n\n if (!config.apiKey) {\n throw new Error('API key required for getWebp');\n }\n\n // Build query params\n const params = new URLSearchParams();\n if (options.maxDuration !== undefined) params.set('max_duration', String(options.maxDuration));\n if (options.fps !== undefined) params.set('fps', String(options.fps));\n if (options.width !== undefined) params.set('width', String(options.width));\n if (options.quality !== undefined) params.set('quality', String(options.quality));\n if (options.maxSizeMb !== undefined) params.set('max_size_mb', String(options.maxSizeMb));\n\n const url = `${apiUrl}/recordings/${recordingId}/webp${params.toString() ? '?' + params.toString() : ''}`;\n \n if (debug) console.log(`[Browser] getWebp: ${url}`);\n\n const response = await fetch(url, {\n method: 'GET',\n headers: { 'Authorization': `Bearer ${config.apiKey}` },\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n if (debug) console.error(`[Browser] getWebp error: ${response.status} - ${errorText}`);\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const result = mapWebpResponse(await response.json());\n if (debug) console.log(`[Browser] WebP ready: ${result.webpUrl} (cached: ${result.cached})`);\n\n return result;\n}\n\n/**\n * Check if browser worker service is healthy\n * \n * @param config - Optional configuration\n * @returns Health status\n */\nexport async function checkHealth(config: BrowserConfig = {}): Promise<{\n ok: boolean;\n google_configured: boolean;\n database_configured: boolean;\n s3_configured: boolean;\n error?: string;\n}> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n\n try {\n const response = await fetch(`${apiUrl}/health`, {\n method: 'GET',\n headers: config.apiKey\n ? { 'Authorization': `Bearer ${config.apiKey}` }\n : {},\n });\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}`);\n }\n\n const data = await response.json();\n return {\n ok: true,\n google_configured: data.google_configured ?? false,\n database_configured: data.database_configured ?? false,\n s3_configured: data.s3_configured ?? false,\n };\n } catch (error) {\n return {\n ok: false,\n google_configured: false,\n database_configured: false,\n s3_configured: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAwBA,IAAM,iBAAiB;AAAA,EACrB,QAAQ,QAAQ,IAAI,sBAAsB,QACtC,0BACA;AAAA,EACJ,SAAS;AAAA;AAAA,EACT,OAAO;AACT;AAKO,IAAM,gBAAN,MAAoB;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA,EAKD;AAAA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AEA,QAAM,SAAS,gBAAgB,MAAM,SAAS,KAAK,CAAC;AACpD,MAAI,MAAO,SAAQ,IAAI,yBAAyB,OAAO,OAAO,aAAa,OAAO,MAAM,GAAG;AAE3F,SAAO;AACT;AAQA,eAAsB,YAAY,SAAwB,CAAC,GAMxD;AACD,QAAM,SAAS,OAAO,UAAU,eAAe;AAE/C,MAAI;AACF,UAAM,WAAW,MAAM,MAAM,GAAG,MAAM,WAAW;AAAA,MAC/C,QAAQ;AAAA,MACR,SAAS,OAAO,SACZ,EAAE,iBAAiB,UAAU,OAAO,MAAM,GAAG,IAC7C,CAAC;AAAA,IACP,CAAC;AAED,QAAI,CAAC,SAAS,IAAI;AAChB,YAAM,IAAI,MAAM,QAAQ,SAAS,MAAM,EAAE;AAAA,IAC3C;AAEA,UAAM,OAAO,MAAM,SAAS,KAAK;AACjC,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,mBAAmB,KAAK,qBAAqB;AAAA,MAC7C,qBAAqB,KAAK,uBAAuB;AAAA,MACjD,eAAe,KAAK,iBAAiB;AAAA,IACvC;AAAA,EACF,SAAS,OAAO;AACd,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,mBAAmB;AAAA,MACnB,qBAAqB;AAAA,MACrB,eAAe;AAAA,MACf,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,IAC9D;AAAA,EACF;AACF;","names":[]}
@@ -1,3 +1,7 @@
1
+ import {
2
+ logger
3
+ } from "./chunk-5AM23TC7.js";
4
+
1
5
  // tools/fastapply/core.ts
2
6
  import { join, resolve, relative } from "path";
3
7
  var DEFAULT_CONFIG = {
@@ -59,9 +63,10 @@ var FastApplyClient = class {
59
63
  async function executeEditFile(input, config = {}) {
60
64
  const baseDir = config.baseDir || DEFAULT_CONFIG.baseDir;
61
65
  const fullPath = resolve(join(baseDir, input.target_filepath));
62
- const debug = config.debug || false;
66
+ logger.debug("FastApply", "execute_start", { target_filepath: input.target_filepath, baseDir, autoWrite: config.autoWrite !== false });
63
67
  const relativePath = relative(baseDir, fullPath);
64
68
  if (relativePath.startsWith("..") || fullPath === baseDir) {
69
+ logger.warn("FastApply", "security_check_failed", { target_filepath: input.target_filepath, relative: relativePath });
65
70
  return {
66
71
  success: false,
67
72
  filepath: input.target_filepath,
@@ -69,27 +74,33 @@ async function executeEditFile(input, config = {}) {
69
74
  error: `Invalid filepath: '${input.target_filepath}' is outside baseDir`
70
75
  };
71
76
  }
77
+ logger.debug("FastApply", "security_check", { resolved: fullPath, relative: relativePath });
72
78
  try {
73
- if (debug) console.log(`[FastApply] Reading file: ${input.target_filepath}`);
74
79
  const { readFile, writeFile } = await import("fs/promises");
75
80
  const { callMorphAPI: callMorphAPI2, generateUdiff: generateUdiff2, countChanges: countChanges2 } = await import("./tools/fastapply/apply.js");
76
81
  let originalCode = "";
82
+ let fileExists = true;
77
83
  try {
78
84
  originalCode = await readFile(fullPath, "utf-8");
85
+ logger.debug("FastApply", "file_read", { path: fullPath, exists: true, size_bytes: originalCode.length });
79
86
  } catch (error) {
80
87
  if (error.code !== "ENOENT") {
81
88
  throw error;
82
89
  }
83
- if (debug) console.log(`[FastApply] File doesn't exist, will create new file`);
90
+ fileExists = false;
91
+ logger.debug("FastApply", "file_read", { path: fullPath, exists: false });
84
92
  }
85
93
  const instruction = input.instruction ?? input.instructions ?? "";
94
+ logger.debug("FastApply", "api_call", { instruction_len: instruction.length, code_edit_len: input.code_edit.length, original_len: originalCode.length });
86
95
  const { content: mergedCode, completionId } = await callMorphAPI2(originalCode, input.code_edit, instruction, input.target_filepath, config);
96
+ logger.debug("FastApply", "api_response", { completion_id: completionId, merged_len: mergedCode.length });
87
97
  const udiff = config.generateUdiff !== false ? generateUdiff2(originalCode, mergedCode, input.target_filepath) : void 0;
88
98
  if (config.autoWrite !== false) {
89
99
  await writeFile(fullPath, mergedCode, "utf-8");
90
- if (debug) console.log(`[FastApply] Wrote ${mergedCode.length} chars to ${input.target_filepath}`);
100
+ logger.debug("FastApply", "file_write", { path: fullPath, size_bytes: mergedCode.length });
91
101
  }
92
102
  const changes = countChanges2(originalCode, mergedCode);
103
+ logger.debug("FastApply", "changes", { added: changes.linesAdded, removed: changes.linesRemoved, modified: changes.linesModified });
93
104
  return {
94
105
  success: true,
95
106
  filepath: input.target_filepath,
@@ -99,7 +110,7 @@ async function executeEditFile(input, config = {}) {
99
110
  };
100
111
  } catch (error) {
101
112
  const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
102
- if (debug) console.error(`[FastApply] Error: ${errorMessage}`);
113
+ logger.error("FastApply", "execute_error", { error: errorMessage, target_filepath: input.target_filepath, stack: error instanceof Error ? error.stack : void 0 });
103
114
  return {
104
115
  success: false,
105
116
  filepath: input.target_filepath,
@@ -113,4 +124,4 @@ export {
113
124
  FastApplyClient,
114
125
  executeEditFile
115
126
  };
116
- //# sourceMappingURL=chunk-LECHLXI4.js.map
127
+ //# sourceMappingURL=chunk-VMNEYCFP.js.map
@@ -0,0 +1 @@
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';\n\n// Re-export edge-compatible functions\nexport { applyEdit, generateUdiff, countChanges, callMorphAPI } from './apply.js';\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: 30000,\n debug: false,\n};\n\n/**\n * FastApply client for programmatic file editing\n * Note: This client requires Node.js for file operations\n */\nexport class FastApplyClient {\n private config: EditFileConfig;\n\n constructor(config: { apiKey?: string; debug?: boolean; timeout?: number; retryConfig?: any } = {}) {\n this.config = {\n morphApiKey: config.apiKey,\n morphApiUrl: DEFAULT_CONFIG.morphApiUrl,\n debug: config.debug,\n timeout: config.timeout || DEFAULT_CONFIG.timeout,\n retryConfig: config.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 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 filep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EAAE,eAAe,cAAc,YAAY,WAAW,OAAO,CAAC;AAExG,UAAM,QAAQ,OAAO,kBAAkB,QAAQC,eAAc,cAAc,YAAY,MAAM,eAAe,IAAI;AAEhH,QAAI,OAAO,cAAc,OAAO;AAC9B,YAAM,UAAU,UAAU,YAAY,OAAO;AAC7C,aAAO,MAAM,aAAa,cAAc,EAAE,MAAM,UAAU,YAAY,WAAW,OAAO,CAAC;AAAA,IAC3F;AAEA,UAAM,UAAUC,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,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,IACT;AAAA,EACF;AACF;","names":["applyEdit","callMorphAPI","generateUdiff","countChanges"]}
@@ -1,6 +1,9 @@
1
+ import {
2
+ logger
3
+ } from "./chunk-5AM23TC7.js";
1
4
  import {
2
5
  SDK_VERSION
3
- } from "./chunk-ZG3YLRR5.js";
6
+ } from "./chunk-LST7MZOZ.js";
4
7
 
5
8
  // tools/fastapply/apply.ts
6
9
  import { createTwoFilesPatch } from "diff";
@@ -51,11 +54,14 @@ async function callMorphAPI(originalCode, codeEdit, instructions, filepath, conf
51
54
  const message = `<instruction>${instructions}</instruction>
52
55
  <code>${originalCode}</code>
53
56
  <update>${codeEdit}</update>`;
54
- if (debug) {
55
- console.log(`[FastApply] Calling ${apiUrl}/v1/chat/completions`);
56
- console.log(`[FastApply] File: ${filepath}, Instructions: ${instructions.slice(0, 60)}...`);
57
- console.log(`[FastApply] Original: ${originalCode.length} chars, Edit: ${codeEdit.length} chars`);
58
- }
57
+ logger.debug("FastApply", "http_request", {
58
+ url: `${apiUrl}/v1/chat/completions`,
59
+ model,
60
+ filepath,
61
+ instruction_len: instructions.length,
62
+ original_len: originalCode.length,
63
+ code_edit_len: codeEdit.length
64
+ });
59
65
  const startTime = Date.now();
60
66
  const client = new OpenAI({
61
67
  apiKey,
@@ -64,30 +70,32 @@ async function callMorphAPI(originalCode, codeEdit, instructions, filepath, conf
64
70
  maxRetries: config.retryConfig?.maxRetries ?? 3,
65
71
  defaultHeaders: { "X-Morph-SDK-Version": SDK_VERSION }
66
72
  });
67
- if (debug) {
68
- console.log(`[FastApply] Using model: ${model}`);
69
- }
70
- const completion = await client.chat.completions.create({
71
- model,
72
- messages: [{ role: "user", content: message }]
73
- });
74
- const content = completion.choices[0]?.message?.content;
75
- if (!content) {
76
- throw new Error("Morph API returned empty response");
77
- }
78
- const elapsed = Date.now() - startTime;
79
- if (debug) {
80
- console.log(`[FastApply] Success in ${elapsed}ms, merged: ${content.length} chars`);
73
+ try {
74
+ const completion = await client.chat.completions.create({
75
+ model,
76
+ messages: [{ role: "user", content: message }]
77
+ });
78
+ const content = completion.choices[0]?.message?.content;
79
+ if (!content) {
80
+ throw new Error("Morph API returned empty response");
81
+ }
82
+ const elapsed = Date.now() - startTime;
83
+ logger.debug("FastApply", "http_response", { status: 200, completion_id: completion.id, content_len: content.length, latency_ms: elapsed });
84
+ return { content, completionId: completion.id };
85
+ } catch (error) {
86
+ const elapsed = Date.now() - startTime;
87
+ logger.error("FastApply", "http_error", {
88
+ status: error?.status || error?.response?.status,
89
+ error: error?.message,
90
+ latency_ms: elapsed
91
+ });
92
+ throw error;
81
93
  }
82
- return { content, completionId: completion.id };
83
94
  }
84
95
  async function applyEdit(input, config = {}) {
85
- const debug = config.debug || false;
86
96
  const filepath = input.filepath || "file";
87
97
  try {
88
- if (debug) {
89
- console.log(`[FastApply] Applying edit to code (${input.originalCode.length} chars)`);
90
- }
98
+ logger.debug("FastApply", "apply_edit_start", { original_len: input.originalCode.length, code_edit_len: input.codeEdit.length });
91
99
  const instruction = input.instruction ?? input.instructions ?? "";
92
100
  const { content: mergedCode, completionId } = await callMorphAPI(
93
101
  input.originalCode,
@@ -107,7 +115,7 @@ async function applyEdit(input, config = {}) {
107
115
  };
108
116
  } catch (error) {
109
117
  const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
110
- if (debug) console.error(`[FastApply] Error: ${errorMessage}`);
118
+ logger.error("FastApply", "apply_edit_error", { error: errorMessage });
111
119
  return {
112
120
  success: false,
113
121
  changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
@@ -122,4 +130,4 @@ export {
122
130
  callMorphAPI,
123
131
  applyEdit
124
132
  };
125
- //# sourceMappingURL=chunk-LZQBVEY2.js.map
133
+ //# sourceMappingURL=chunk-WM6SBI4B.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../tools/fastapply/apply.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 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 = 30000;\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 // Format message with XML tags as per Morph Fast Apply spec\n const message = `<instruction>${instructions}</instruction>\\n<code>${originalCode}</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 code_edit_len: codeEdit.length,\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: { 'X-Morph-SDK-Version': SDK_VERSION },\n });\n\n try {\n const completion = await client.chat.completions.create({\n model,\n messages: [{ role: 'user', content: message }],\n });\n\n const content = completion.choices[0]?.message?.content;\n if (!content) {\n throw new Error('Morph API returned empty response');\n }\n\n const elapsed = Date.now() - startTime;\n logger.debug('FastApply', 'http_response', { status: 200, completion_id: completion.id, content_len: content.length, latency_ms: elapsed });\n\n return { content, completionId: completion.id };\n } catch (error: any) {\n const elapsed = Date.now() - startTime;\n logger.error('FastApply', 'http_error', {\n status: error?.status || error?.response?.status,\n error: error?.message,\n latency_ms: elapsed,\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\n return {\n success: false,\n changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },\n error: errorMessage,\n };\n }\n}\n"],"mappings":";;;;;;;;AAaA,SAAS,2BAA2B;AACpC,OAAO,YAAY;AAUnB,IAAM,kBAAkB;AACxB,IAAM,kBAAkB;AAKjB,SAAS,cACd,UACA,UACA,UACQ;AACR,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAKO,SAAS,aAAa,UAAkB,UAA+B;AAC5E,QAAM,OAAO,cAAc,UAAU,UAAU,MAAM;AACrD,QAAM,QAAQ,KAAK,MAAM,IAAI;AAE7B,MAAI,aAAa;AACjB,MAAI,eAAe;AAEnB,aAAW,QAAQ,OAAO;AACxB,QAAI,KAAK,WAAW,GAAG,KAAK,CAAC,KAAK,WAAW,KAAK,GAAG;AACnD;AAAA,IACF,WAAW,KAAK,WAAW,GAAG,KAAK,CAAC,KAAK,WAAW,KAAK,GAAG;AAC1D;AAAA,IACF;AAAA,EACF;AAEA,QAAM,gBAAgB,KAAK,IAAI,YAAY,YAAY;AAEvD,SAAO;AAAA,IACL,YAAY,aAAa;AAAA,IACzB,cAAc,eAAe;AAAA,IAC7B;AAAA,EACF;AACF;AAMA,eAAsB,aACpB,cACA,UACA,cACA,UACA,QACqD;AACrD,QAAM,SAAS,OAAO,gBAAgB,OAAO,YAAY,cAAc,QAAQ,KAAK,gBAAgB;AACpG,QAAM,SAAS,OAAO,eAAe;AACrC,QAAM,WAAW,OAAO,UAAU,OAAO,YAAY,cAAc,QAAQ,KAAK,sBAAsB,UAAU;AAChH,QAAM,QAAQ,WAAW,mBAAmB;AAC5C,QAAM,UAAU,OAAO,WAAW;AAClC,QAAM,QAAQ,OAAO,SAAS;AAE9B,MAAI,CAAC,QAAQ;AACX,UAA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AM,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;AAErE,WAAO;AAAA,MACL,SAAS;AAAA,MACT,SAAS,EAAE,YAAY,GAAG,cAAc,GAAG,eAAe,EAAE;AAAA,MAC5D,OAAO;AAAA,IACT;AAAA,EACF;AACF;","names":[]}
@@ -18,9 +18,12 @@ import {
18
18
  AGENT_CONFIG,
19
19
  DEFAULT_MODEL
20
20
  } from "./chunk-I3J46TSB.js";
21
+ import {
22
+ logger
23
+ } from "./chunk-5AM23TC7.js";
21
24
  import {
22
25
  SDK_VERSION
23
- } from "./chunk-ZG3YLRR5.js";
26
+ } from "./chunk-LST7MZOZ.js";
24
27
 
25
28
  // tools/warp_grep/agent/runner.ts
26
29
  import OpenAI from "openai";
@@ -147,6 +150,8 @@ async function callModel(messages, model, options = {}) {
147
150
  defaultHeaders: { "X-Morph-SDK-Version": SDK_VERSION }
148
151
  });
149
152
  const MAX_EMPTY_RETRIES = 1;
153
+ logger.debug("WarpGrep", "model_call", { url: baseURL, model, message_count: messages.length });
154
+ const callStartTime = Date.now();
150
155
  for (let attempt = 0; attempt <= MAX_EMPTY_RETRIES; attempt++) {
151
156
  let data;
152
157
  try {
@@ -159,10 +164,16 @@ async function callModel(messages, model, options = {}) {
159
164
  ...options.search_type ? { search_type: options.search_type } : {}
160
165
  });
161
166
  } catch (error) {
162
- if (error instanceof OpenAI.APIError && error.status === 404) {
163
- const defaultMsg = "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";
164
- const errorText = error.message?.trim();
165
- throw new Error(errorText || defaultMsg);
167
+ const callLatencyMs = Date.now() - callStartTime;
168
+ if (error instanceof OpenAI.APIError) {
169
+ logger.error("WarpGrep", "model_call_error", { status: error.status, error: error.message, latency_ms: callLatencyMs });
170
+ if (error.status === 404) {
171
+ const defaultMsg = "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";
172
+ const errorText = error.message?.trim();
173
+ throw new Error(errorText || defaultMsg);
174
+ }
175
+ } else {
176
+ logger.error("WarpGrep", "model_call_error", { status: void 0, error: error instanceof Error ? error.message : String(error), latency_ms: callLatencyMs });
166
177
  }
167
178
  throw error;
168
179
  }
@@ -181,6 +192,7 @@ async function callModel(messages, model, options = {}) {
181
192
  function: { name: tc.function.name, arguments: tc.function.arguments }
182
193
  }));
183
194
  if (message.content || toolCalls.length > 0) {
195
+ logger.debug("WarpGrep", "model_call_complete", { latency_ms: Date.now() - callStartTime, tool_calls_count: toolCalls.length, finish_reason: choice?.finish_reason ?? "unknown" });
184
196
  return { content: message.content ?? null, tool_calls: toolCalls };
185
197
  }
186
198
  if (attempt === MAX_EMPTY_RETRIES) {
@@ -251,9 +263,11 @@ async function* runWarpGrepStreaming(config) {
251
263
  const model = config.model || DEFAULT_MODEL;
252
264
  const messages = [];
253
265
  const maxTurns = AGENT_CONFIG.MAX_TURNS;
266
+ logger.debug("WarpGrep", "session_start", { search_term: config.searchTerm, model, max_turns: maxTurns });
254
267
  const initialStateStart = Date.now();
255
268
  const initialState = await buildInitialState(repoRoot, config.searchTerm, config.provider, { search_type: config.search_type });
256
269
  timings.initial_state_ms = Date.now() - initialStateStart;
270
+ logger.debug("WarpGrep", "initial_state", { system_prompt_len: initialState.length, user_message_len: initialState.length });
257
271
  messages.push({ role: "user", content: initialState });
258
272
  const provider = config.provider;
259
273
  const errors = [];
@@ -261,7 +275,13 @@ async function* runWarpGrepStreaming(config) {
261
275
  let terminationReason = "terminated";
262
276
  for (let turn = 1; turn <= maxTurns; turn += 1) {
263
277
  const turnMetrics = { turn, morph_api_ms: 0, local_tools_ms: 0 };
278
+ logger.debug("WarpGrep", "turn_start", { turn, message_count: messages.length });
279
+ const beforeChars = messages.reduce((sum, m) => sum + (typeof m.content === "string" ? m.content.length : 0), 0);
264
280
  enforceContextLimit(messages);
281
+ const afterChars = messages.reduce((sum, m) => sum + (typeof m.content === "string" ? m.content.length : 0), 0);
282
+ if (afterChars < beforeChars) {
283
+ logger.debug("WarpGrep", "context_truncated", { before_chars: beforeChars, after_chars: afterChars });
284
+ }
265
285
  const modelCallStart = Date.now();
266
286
  const response = await callModel(messages, model, {
267
287
  morphApiKey: config.morphApiKey,
@@ -272,6 +292,7 @@ async function* runWarpGrepStreaming(config) {
272
292
  }).catch((e) => {
273
293
  const errMsg = e instanceof Error ? e.message : String(e);
274
294
  console.error(`[warp_grep] Morph API call failed on turn ${turn}:`, errMsg);
295
+ logger.error("WarpGrep", "error", { turn, error: errMsg, phase: "model_call" });
275
296
  errors.push({ message: errMsg });
276
297
  return null;
277
298
  });
@@ -281,6 +302,7 @@ async function* runWarpGrepStreaming(config) {
281
302
  break;
282
303
  }
283
304
  const toolCalls = response.tool_calls;
305
+ logger.debug("WarpGrep", "model_response", { turn, tool_calls: toolCalls.map((tc) => tc.function.name), latency_ms: turnMetrics.morph_api_ms });
284
306
  messages.push({
285
307
  role: "assistant",
286
308
  content: response.content,
@@ -307,6 +329,7 @@ async function* runWarpGrepStreaming(config) {
307
329
  const files = parseFinishFiles(filesStr);
308
330
  finishMeta = { files };
309
331
  terminationReason = "completed";
332
+ logger.debug("WarpGrep", "finish", { turns: turn, files: files.map((f) => f.path) });
310
333
  if (files.length === 0) {
311
334
  const payload2 = filesStr || "No relevant code found.";
312
335
  timings.turns.push(turnMetrics);
@@ -325,7 +348,11 @@ async function* runWarpGrepStreaming(config) {
325
348
  const results = await Promise.all(
326
349
  toolCalls.map(async (tc) => {
327
350
  const args = safeParseJSON(tc.function.arguments);
351
+ const argsSummary = Object.fromEntries(Object.entries(args).map(([k, v]) => [k, typeof v === "string" && v.length > 100 ? v.slice(0, 100) + "..." : v]));
352
+ logger.debug("WarpGrep", "tool_exec", { turn, tool: tc.function.name, args_summary: argsSummary });
353
+ const toolStart = Date.now();
328
354
  const output = await executeTool(provider, tc.function.name, args, repoRoot).catch((err) => String(err));
355
+ logger.debug("WarpGrep", "tool_result", { turn, tool: tc.function.name, result_len: output.length, latency_ms: Date.now() - toolStart });
329
356
  return { tool_call_id: tc.id, content: output };
330
357
  })
331
358
  );
@@ -398,4 +425,4 @@ export {
398
425
  runWarpGrepStreaming,
399
426
  runWarpGrep
400
427
  };
401
- //# sourceMappingURL=chunk-7QMX45QD.js.map
428
+ //# sourceMappingURL=chunk-ZMCDGAGF.js.map
@@ -0,0 +1 @@
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: options.retryConfig?.maxRetries,\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;AAAA,YACN,aAAa;AAAA,UACf;AAAA,UACA,OAAO;AAAA,YACL,MAAM;AAAA,YACN,aAAa;AAAA,UACf;AAAA,QACF;AAAA,QACA,UAAU,CAAC,SAAS;AAAA,MACtB;AAAA,IACF;AAAA,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