@morphllm/morphsdk 0.2.7 → 0.2.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-ZQEWQ7LJ.js → chunk-4F6DRRCR.js} +10 -10
- package/dist/chunk-4F6DRRCR.js.map +1 -0
- package/dist/{chunk-G4DJ6VSM.js → chunk-7NG7SI6M.js} +6 -2
- package/dist/{chunk-G4DJ6VSM.js.map → chunk-7NG7SI6M.js.map} +1 -1
- package/dist/{chunk-OI5YYE36.js → chunk-AKVAAKRB.js} +7 -60
- package/dist/chunk-AKVAAKRB.js.map +1 -0
- package/dist/{chunk-5COKN3XD.js → chunk-IUCGXKTX.js} +2 -2
- package/dist/{chunk-5COKN3XD.js.map → chunk-IUCGXKTX.js.map} +1 -1
- package/dist/{chunk-4UVEBIDK.js → chunk-OWXIAZUZ.js} +150 -6
- package/dist/chunk-OWXIAZUZ.js.map +1 -0
- package/dist/{chunk-YWS2GRQC.js → chunk-QFUHDWGY.js} +11 -2
- package/dist/{chunk-YWS2GRQC.js.map → chunk-QFUHDWGY.js.map} +1 -1
- package/dist/client.cjs +151 -64
- package/dist/client.cjs.map +1 -1
- package/dist/client.js +4 -4
- package/dist/index.cjs +151 -64
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +10 -10
- package/dist/{tools/modelrouter → modelrouter}/core.cjs +7 -60
- package/dist/modelrouter/core.cjs.map +1 -0
- package/dist/modelrouter/core.js +13 -0
- package/dist/{tools/modelrouter → modelrouter}/index.cjs +7 -60
- package/dist/modelrouter/index.cjs.map +1 -0
- package/dist/modelrouter/index.js +13 -0
- package/dist/{tools/modelrouter → modelrouter}/types.cjs +1 -1
- package/dist/modelrouter/types.cjs.map +1 -0
- package/dist/tools/browser/anthropic.cjs +9 -3
- package/dist/tools/browser/anthropic.cjs.map +1 -1
- package/dist/tools/browser/anthropic.js +1 -1
- package/dist/tools/browser/core.cjs +145 -5
- package/dist/tools/browser/core.cjs.map +1 -1
- package/dist/tools/browser/core.js +1 -1
- package/dist/tools/browser/index.cjs +153 -5
- package/dist/tools/browser/index.cjs.map +1 -1
- package/dist/tools/browser/index.js +9 -1
- package/dist/tools/browser/openai.cjs +9 -3
- package/dist/tools/browser/openai.cjs.map +1 -1
- package/dist/tools/browser/openai.js +1 -1
- package/dist/tools/browser/types.cjs.map +1 -1
- package/dist/tools/browser/vercel.cjs +9 -3
- package/dist/tools/browser/vercel.cjs.map +1 -1
- package/dist/tools/browser/vercel.js +1 -1
- package/dist/tools/codebase_search/index.js +3 -3
- package/dist/tools/fastapply/anthropic.cjs +5 -1
- package/dist/tools/fastapply/anthropic.cjs.map +1 -1
- package/dist/tools/fastapply/anthropic.js +1 -1
- package/dist/tools/fastapply/index.cjs +16 -3
- package/dist/tools/fastapply/index.cjs.map +1 -1
- package/dist/tools/fastapply/index.js +5 -5
- package/dist/tools/fastapply/openai.cjs +10 -1
- package/dist/tools/fastapply/openai.cjs.map +1 -1
- package/dist/tools/fastapply/openai.js +1 -1
- package/dist/tools/fastapply/types.cjs.map +1 -1
- package/dist/tools/fastapply/vercel.cjs +1 -1
- package/dist/tools/fastapply/vercel.cjs.map +1 -1
- package/dist/tools/fastapply/vercel.js +1 -1
- package/dist/tools/index.cjs +16 -3
- package/dist/tools/index.cjs.map +1 -1
- package/dist/tools/index.js +5 -5
- package/package.json +11 -8
- package/dist/chunk-4UVEBIDK.js.map +0 -1
- package/dist/chunk-OI5YYE36.js.map +0 -1
- package/dist/chunk-ZQEWQ7LJ.js.map +0 -1
- package/dist/tools/modelrouter/core.cjs.map +0 -1
- package/dist/tools/modelrouter/core.js +0 -13
- package/dist/tools/modelrouter/index.cjs.map +0 -1
- package/dist/tools/modelrouter/index.js +0 -13
- package/dist/tools/modelrouter/types.cjs.map +0 -1
- /package/dist/{tools/modelrouter → modelrouter}/core.js.map +0 -0
- /package/dist/{tools/modelrouter → modelrouter}/index.js.map +0 -0
- /package/dist/{tools/modelrouter → modelrouter}/types.js +0 -0
- /package/dist/{tools/modelrouter → modelrouter}/types.js.map +0 -0
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
2
|
+
BrowserClient
|
|
3
|
+
} from "./chunk-OWXIAZUZ.js";
|
|
4
|
+
import {
|
|
5
|
+
FastApplyClient
|
|
6
|
+
} from "./chunk-4V46N27D.js";
|
|
6
7
|
import {
|
|
7
8
|
CodebaseSearchClient
|
|
8
9
|
} from "./chunk-VJK4PH5V.js";
|
|
@@ -10,11 +11,10 @@ import {
|
|
|
10
11
|
MorphGit
|
|
11
12
|
} from "./chunk-5VQEQSJQ.js";
|
|
12
13
|
import {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
} from "./chunk-4UVEBIDK.js";
|
|
14
|
+
AnthropicRouter,
|
|
15
|
+
GeminiRouter,
|
|
16
|
+
OpenAIRouter
|
|
17
|
+
} from "./chunk-AKVAAKRB.js";
|
|
18
18
|
|
|
19
19
|
// client.ts
|
|
20
20
|
var MorphClient = class {
|
|
@@ -94,4 +94,4 @@ var MorphClient = class {
|
|
|
94
94
|
export {
|
|
95
95
|
MorphClient
|
|
96
96
|
};
|
|
97
|
-
//# sourceMappingURL=chunk-
|
|
97
|
+
//# sourceMappingURL=chunk-4F6DRRCR.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../client.ts"],"sourcesContent":["/**\n * Unified Morph SDK Client\n * \n * Provides access to all Morph tools through a single interface\n * \n * @example\n * ```typescript\n * import { MorphClient } from '@cuda_oom/morphsdk';\n * \n * const morph = new MorphClient({ \n * apiKey: process.env.MORPH_API_KEY,\n * debug: true,\n * timeout: 60000\n * });\n * \n * // Use FastApply\n * const editResult = await morph.fastApply.execute({\n * target_filepath: 'src/index.ts',\n * instructions: 'Add error handling',\n * code_edit: 'try { ... } catch (e) { ... }'\n * });\n * \n * // Use CodebaseSearch\n * const searchResult = await morph.codebaseSearch.search({\n * query: 'authentication logic',\n * repoId: 'my-project'\n * });\n * \n * // Use Browser automation\n * const browserResult = await morph.browser.execute({\n * task: 'Test the checkout flow',\n * url: 'https://example.com'\n * });\n * \n * // Use Model Router\n * const { model } = await morph.routers.openai.selectModel({\n * input: 'Complex refactoring task',\n * mode: 'balanced'\n * });\n * ```\n */\n\nimport type { RetryConfig } from './tools/utils/resilience.js';\nimport { FastApplyClient } from './tools/fastapply/core.js';\nimport { CodebaseSearchClient } from './tools/codebase_search/core.js';\nimport { BrowserClient } from './tools/browser/core.js';\nimport { MorphGit } from './git/index.js';\nimport { OpenAIRouter, AnthropicRouter, GeminiRouter } from './modelrouter/core.js';\n\n/**\n * Configuration for the MorphClient\n */\nexport interface MorphClientConfig {\n /** Morph API key for authentication (defaults to MORPH_API_KEY env var) */\n apiKey?: string;\n /** Enable debug logging across all tools */\n debug?: boolean;\n /** Default timeout in milliseconds for API requests */\n timeout?: number;\n /** Retry configuration for failed requests */\n retryConfig?: RetryConfig;\n}\n\n/**\n * Unified Morph SDK Client\n * \n * Provides access to all Morph tools through a single interface:\n * - fastApply: AI-powered file editing with intelligent merging\n * - codebaseSearch: Semantic code search\n * - browser: AI-powered browser automation\n * - git: Version control operations\n * - routers: Intelligent model selection (OpenAI, Anthropic, Gemini)\n */\nexport class MorphClient {\n /** Client configuration */\n public config: MorphClientConfig;\n\n /** FastApply tool for editing files with AI-powered merge */\n public fastApply: FastApplyClient;\n\n /** CodebaseSearch tool for semantic code search */\n public codebaseSearch: CodebaseSearchClient;\n\n /** Browser tool for AI-powered browser automation */\n public browser: BrowserClient;\n\n /** Git tool for version control operations */\n public git: MorphGit;\n\n /** Model routers for intelligent model selection */\n public routers: {\n openai: OpenAIRouter;\n anthropic: AnthropicRouter;\n gemini: GeminiRouter;\n };\n\n /**\n * Create a new Morph SDK client\n * \n * @param config - Client configuration (apiKey, debug, timeout, retryConfig)\n * \n * @example\n * ```typescript\n * const morph = new MorphClient({ \n * apiKey: process.env.MORPH_API_KEY,\n * debug: true,\n * timeout: 60000\n * });\n * ```\n */\n constructor(config: MorphClientConfig = {}) {\n this.config = config;\n\n // Initialize all sub-clients with shared config\n this.fastApply = new FastApplyClient({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n });\n\n this.codebaseSearch = new CodebaseSearchClient({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n });\n\n this.browser = new BrowserClient({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n });\n\n this.git = new MorphGit({\n apiKey: config.apiKey,\n retryConfig: config.retryConfig,\n });\n\n this.routers = {\n openai: new OpenAIRouter({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n }),\n anthropic: new AnthropicRouter({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n }),\n gemini: new GeminiRouter({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n }),\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAyEO,IAAM,cAAN,MAAkB;AAAA;AAAA,EAEhB;AAAA;AAAA,EAGA;AAAA;AAAA,EAGA;AAAA;AAAA,EAGA;AAAA;AAAA,EAGA;AAAA;AAAA,EAGA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAoBP,YAAY,SAA4B,CAAC,GAAG;AAC1C,SAAK,SAAS;AAGd,SAAK,YAAY,IAAI,gBAAgB;AAAA,MACnC,QAAQ,OAAO;AAAA,MACf,OAAO,OAAO;AAAA,MACd,SAAS,OAAO;AAAA,MAChB,aAAa,OAAO;AAAA,IACtB,CAAC;AAED,SAAK,iBAAiB,IAAI,qBAAqB;AAAA,MAC7C,QAAQ,OAAO;AAAA,MACf,OAAO,OAAO;AAAA,MACd,SAAS,OAAO;AAAA,MAChB,aAAa,OAAO;AAAA,IACtB,CAAC;AAED,SAAK,UAAU,IAAI,cAAc;AAAA,MAC/B,QAAQ,OAAO;AAAA,MACf,OAAO,OAAO;AAAA,MACd,SAAS,OAAO;AAAA,MAChB,aAAa,OAAO;AAAA,IACtB,CAAC;AAED,SAAK,MAAM,IAAI,SAAS;AAAA,MACtB,QAAQ,OAAO;AAAA,MACf,aAAa,OAAO;AAAA,IACtB,CAAC;AAED,SAAK,UAAU;AAAA,MACb,QAAQ,IAAI,aAAa;AAAA,QACvB,QAAQ,OAAO;AAAA,QACf,OAAO,OAAO;AAAA,QACd,SAAS,OAAO;AAAA,QAChB,aAAa,OAAO;AAAA,MACtB,CAAC;AAAA,MACD,WAAW,IAAI,gBAAgB;AAAA,QAC7B,QAAQ,OAAO;AAAA,QACf,OAAO,OAAO;AAAA,QACd,SAAS,OAAO;AAAA,QAChB,aAAa,OAAO;AAAA,MACtB,CAAC;AAAA,MACD,QAAQ,IAAI,aAAa;AAAA,QACvB,QAAQ,OAAO;AAAA,QACf,OAAO,OAAO;AAAA,QACd,SAAS,OAAO;AAAA,QAChB,aAAa,OAAO;AAAA,MACtB,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":[]}
|
|
@@ -57,7 +57,11 @@ Summary: ${summary}`;
|
|
|
57
57
|
return `Successfully applied changes to ${result.filepath}. ${summary}`;
|
|
58
58
|
}
|
|
59
59
|
function createEditFileTool(config = {}) {
|
|
60
|
-
|
|
60
|
+
const toolDef = {
|
|
61
|
+
...editFileTool,
|
|
62
|
+
...config.description && { description: config.description }
|
|
63
|
+
};
|
|
64
|
+
return Object.assign({}, toolDef, {
|
|
61
65
|
execute: async (input) => {
|
|
62
66
|
return executeEditFile(input, config);
|
|
63
67
|
},
|
|
@@ -75,4 +79,4 @@ export {
|
|
|
75
79
|
createEditFileTool,
|
|
76
80
|
anthropic_exports
|
|
77
81
|
};
|
|
78
|
-
//# sourceMappingURL=chunk-
|
|
82
|
+
//# sourceMappingURL=chunk-7NG7SI6M.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/fastapply/anthropic.ts"],"sourcesContent":["/**\n * Anthropic SDK adapter for edit_file tool\n */\n\nimport type { Tool } from '@anthropic-ai/sdk/resources/messages';\nimport { executeEditFile } from './core.js';\nimport { EDIT_FILE_TOOL_DESCRIPTION, EDIT_FILE_SYSTEM_PROMPT } from './prompts.js';\nimport type { EditFileInput, EditFileResult, EditFileConfig } from './types.js';\n\n/**\n * Anthropic-native tool definition for edit_file\n * \n * @example\n * ```ts\n * import Anthropic from '@anthropic-ai/sdk';\n * import { editFileTool } from 'morphsdk/tools/anthropic';\n * \n * const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });\n * \n * const response = await client.messages.create({\n * model: \"claude-sonnet-4-5-20250929\",\n * tools: [editFileTool],\n * messages: [{ role: \"user\", content: \"Fix the bug in app.ts\" }]\n * });\n * ```\n */\nexport const editFileTool: Tool = {\n name: 'edit_file',\n description: EDIT_FILE_TOOL_DESCRIPTION,\n input_schema: {\n type: 'object',\n properties: {\n target_filepath: {\n type: 'string',\n description: 'The path of the target file to modify',\n },\n instructions: {\n type: 'string',\n description: 'A single sentence describing what you are changing (first person)',\n },\n code_edit: {\n type: 'string',\n description: 'The lazy edit with // ... existing code ... markers',\n },\n },\n required: ['target_filepath', 'instructions', 'code_edit'],\n },\n};\n\n/**\n * Format the result for passing back to Claude\n * \n * @param result - The edit result\n * @returns Formatted string for tool_result\n */\nfunction formatResult(result: EditFileResult): string {\n if (!result.success) {\n return `Error editing file: ${result.error}`;\n }\n \n const { changes } = result;\n const summary = [\n changes.linesAdded && `+${changes.linesAdded} lines`,\n changes.linesRemoved && `-${changes.linesRemoved} lines`,\n changes.linesModified && `~${changes.linesModified} lines modified`,\n ]\n .filter(Boolean)\n .join(', ');\n \n if (result.udiff) {\n return `Successfully applied changes to ${result.filepath}:\\n\\n${result.udiff}\\n\\nSummary: ${summary}`;\n }\n \n return `Successfully applied changes to ${result.filepath}. ${summary}`;\n}\n\n/**\n * Create a custom edit_file tool with configuration\n * \n * @param config - Configuration options\n * @returns Tool definition with execute and formatResult methods\n * \n * @example\n * ```ts\n * const tool = createEditFileTool({\n * baseDir: './src',\n * generateUdiff: true,\n * morphApiKey: 'sk-...'\n * });\n * \n * // Use as Anthropic tool\n * const response = await client.messages.create({\n * tools: [tool], // tool itself is the Tool definition\n * ...\n * });\n * \n * // Execute and format\n * const result = await tool.execute(toolUseBlock.input);\n * const formatted = tool.formatResult(result);\n * ```\n */\nexport function createEditFileTool(config: EditFileConfig = {}) {\n return Object.assign({},
|
|
1
|
+
{"version":3,"sources":["../tools/fastapply/anthropic.ts"],"sourcesContent":["/**\n * Anthropic SDK adapter for edit_file tool\n */\n\nimport type { Tool } from '@anthropic-ai/sdk/resources/messages';\nimport { executeEditFile } from './core.js';\nimport { EDIT_FILE_TOOL_DESCRIPTION, EDIT_FILE_SYSTEM_PROMPT } from './prompts.js';\nimport type { EditFileInput, EditFileResult, EditFileConfig } from './types.js';\n\n/**\n * Anthropic-native tool definition for edit_file\n * \n * @example\n * ```ts\n * import Anthropic from '@anthropic-ai/sdk';\n * import { editFileTool } from 'morphsdk/tools/anthropic';\n * \n * const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });\n * \n * const response = await client.messages.create({\n * model: \"claude-sonnet-4-5-20250929\",\n * tools: [editFileTool],\n * messages: [{ role: \"user\", content: \"Fix the bug in app.ts\" }]\n * });\n * ```\n */\nexport const editFileTool: Tool = {\n name: 'edit_file',\n description: EDIT_FILE_TOOL_DESCRIPTION,\n input_schema: {\n type: 'object',\n properties: {\n target_filepath: {\n type: 'string',\n description: 'The path of the target file to modify',\n },\n instructions: {\n type: 'string',\n description: 'A single sentence describing what you are changing (first person)',\n },\n code_edit: {\n type: 'string',\n description: 'The lazy edit with // ... existing code ... markers',\n },\n },\n required: ['target_filepath', 'instructions', 'code_edit'],\n },\n};\n\n/**\n * Format the result for passing back to Claude\n * \n * @param result - The edit result\n * @returns Formatted string for tool_result\n */\nfunction formatResult(result: EditFileResult): string {\n if (!result.success) {\n return `Error editing file: ${result.error}`;\n }\n \n const { changes } = result;\n const summary = [\n changes.linesAdded && `+${changes.linesAdded} lines`,\n changes.linesRemoved && `-${changes.linesRemoved} lines`,\n changes.linesModified && `~${changes.linesModified} lines modified`,\n ]\n .filter(Boolean)\n .join(', ');\n \n if (result.udiff) {\n return `Successfully applied changes to ${result.filepath}:\\n\\n${result.udiff}\\n\\nSummary: ${summary}`;\n }\n \n return `Successfully applied changes to ${result.filepath}. ${summary}`;\n}\n\n/**\n * Create a custom edit_file tool with configuration\n * \n * @param config - Configuration options\n * @returns Tool definition with execute and formatResult methods\n * \n * @example\n * ```ts\n * const tool = createEditFileTool({\n * baseDir: './src',\n * generateUdiff: true,\n * morphApiKey: 'sk-...',\n * description: 'Custom tool description for your use case'\n * });\n * \n * // Use as Anthropic tool\n * const response = await client.messages.create({\n * tools: [tool], // tool itself is the Tool definition\n * ...\n * });\n * \n * // Execute and format\n * const result = await tool.execute(toolUseBlock.input);\n * const formatted = tool.formatResult(result);\n * ```\n */\nexport function createEditFileTool(config: EditFileConfig = {}) {\n const toolDef: Tool = {\n ...editFileTool,\n ...(config.description && { description: config.description }),\n };\n \n return Object.assign({}, toolDef, {\n execute: async (input: EditFileInput): Promise<EditFileResult> => {\n return executeEditFile(input, config);\n },\n formatResult: (result: EditFileResult): string => {\n return formatResult(result);\n },\n getSystemPrompt: (): string => {\n return EDIT_FILE_SYSTEM_PROMPT;\n },\n });\n}\n\n"],"mappings":";;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA0BO,IAAM,eAAqB;AAAA,EAChC,MAAM;AAAA,EACN,aAAa;AAAA,EACb,cAAc;AAAA,IACZ,MAAM;AAAA,IACN,YAAY;AAAA,MACV,iBAAiB;AAAA,QAC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WJFZVS.js";
|
|
5
5
|
|
|
6
|
-
//
|
|
6
|
+
// modelrouter/core.ts
|
|
7
7
|
var DEFAULT_CONFIG = {
|
|
8
8
|
apiUrl: "https://api.morphllm.com",
|
|
9
|
-
timeout:
|
|
10
|
-
//
|
|
9
|
+
timeout: 5e3,
|
|
10
|
+
// 5 seconds (responses typically <500ms)
|
|
11
11
|
debug: false
|
|
12
12
|
};
|
|
13
|
-
var MODEL_MAPPINGS = {
|
|
14
|
-
openai: {
|
|
15
|
-
balanced: {
|
|
16
|
-
easy: "gpt-5-mini",
|
|
17
|
-
medium: "gpt-5-low",
|
|
18
|
-
hard: "gpt-5-medium",
|
|
19
|
-
"needs-info": "gpt-5-mini"
|
|
20
|
-
},
|
|
21
|
-
aggressive: {
|
|
22
|
-
easy: "gpt-5-low",
|
|
23
|
-
medium: "gpt-5-medium",
|
|
24
|
-
hard: "gpt-5-high",
|
|
25
|
-
"needs-info": "gpt-5-mini"
|
|
26
|
-
}
|
|
27
|
-
},
|
|
28
|
-
anthropic: {
|
|
29
|
-
balanced: {
|
|
30
|
-
easy: "claude-4.5-haiku",
|
|
31
|
-
medium: "claude-4.5-haiku",
|
|
32
|
-
hard: "claude-4.5-sonnet",
|
|
33
|
-
"needs-info": "claude-4.5-haiku"
|
|
34
|
-
},
|
|
35
|
-
aggressive: {
|
|
36
|
-
easy: "claude-4.5-haiku",
|
|
37
|
-
medium: "claude-4.5-sonnet",
|
|
38
|
-
hard: "claude-4.5-sonnet",
|
|
39
|
-
"needs-info": "claude-4.5-haiku"
|
|
40
|
-
}
|
|
41
|
-
},
|
|
42
|
-
gemini: {
|
|
43
|
-
balanced: {
|
|
44
|
-
easy: "gemini-2.5-flash",
|
|
45
|
-
medium: "gemini-2.5-flash",
|
|
46
|
-
hard: "gemini-2.5-pro",
|
|
47
|
-
"needs-info": "gemini-2.5-flash"
|
|
48
|
-
},
|
|
49
|
-
aggressive: {
|
|
50
|
-
easy: "gemini-2.5-flash",
|
|
51
|
-
medium: "gemini-2.5-pro",
|
|
52
|
-
hard: "gemini-2.5-pro",
|
|
53
|
-
"needs-info": "gemini-2.5-flash"
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
};
|
|
57
13
|
var BaseRouter = class {
|
|
58
14
|
config;
|
|
59
15
|
provider;
|
|
@@ -67,13 +23,6 @@ var BaseRouter = class {
|
|
|
67
23
|
retryConfig: config.retryConfig
|
|
68
24
|
};
|
|
69
25
|
}
|
|
70
|
-
/**
|
|
71
|
-
* Map backend complexity classification to actual model name
|
|
72
|
-
*/
|
|
73
|
-
mapComplexityToModel(complexity, mode) {
|
|
74
|
-
const mapping = MODEL_MAPPINGS[this.provider][mode];
|
|
75
|
-
return mapping[complexity];
|
|
76
|
-
}
|
|
77
26
|
/**
|
|
78
27
|
* Select the optimal model for a given input and mode
|
|
79
28
|
*/
|
|
@@ -85,7 +34,7 @@ var BaseRouter = class {
|
|
|
85
34
|
"Morph API key is required. Set MORPH_API_KEY environment variable or pass apiKey in config."
|
|
86
35
|
);
|
|
87
36
|
}
|
|
88
|
-
const url = `${this.config.apiUrl}/router/${this.provider}`;
|
|
37
|
+
const url = `${this.config.apiUrl}/v1/router/${this.provider}`;
|
|
89
38
|
const payload = {
|
|
90
39
|
input: input.input,
|
|
91
40
|
mode
|
|
@@ -121,13 +70,11 @@ var BaseRouter = class {
|
|
|
121
70
|
);
|
|
122
71
|
}
|
|
123
72
|
const apiResult = await response.json();
|
|
124
|
-
const actualModel = this.mapComplexityToModel(apiResult.model, mode);
|
|
125
73
|
const result = {
|
|
126
|
-
model:
|
|
127
|
-
reasoning: apiResult.reasoning
|
|
74
|
+
model: apiResult.model
|
|
128
75
|
};
|
|
129
76
|
if (this.config.debug) {
|
|
130
|
-
console.log(`[ModelRouter]
|
|
77
|
+
console.log(`[ModelRouter] Selected model: ${apiResult.model}, Confidence: ${apiResult.confidence?.toFixed(3)}`);
|
|
131
78
|
}
|
|
132
79
|
return result;
|
|
133
80
|
} catch (error) {
|
|
@@ -186,4 +133,4 @@ export {
|
|
|
186
133
|
AnthropicRouter,
|
|
187
134
|
GeminiRouter
|
|
188
135
|
};
|
|
189
|
-
//# sourceMappingURL=chunk-
|
|
136
|
+
//# sourceMappingURL=chunk-AKVAAKRB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../modelrouter/core.ts"],"sourcesContent":["/**\n * Core implementation for intelligent model routing\n */\n\nimport { fetchWithRetry, withTimeout } from '../tools/utils/resilience.js';\nimport type {\n RouterConfig,\n RouterInput,\n RouterResult,\n ComplexityLevel,\n RouterMode,\n Provider,\n} from './types.js';\n\nconst DEFAULT_CONFIG = {\n apiUrl: 'https://api.morphllm.com',\n timeout: 5000, // 5 seconds (responses typically <500ms)\n debug: false,\n};\n\nabstract class BaseRouter {\n protected config: Required<Omit<RouterConfig, 'apiKey' | 'retryConfig'>> & Pick<RouterConfig, 'apiKey' | 'retryConfig'>;\n protected provider: Provider;\n\n constructor(provider: Provider, config: RouterConfig = {}) {\n this.provider = provider;\n this.config = {\n apiKey: config.apiKey,\n apiUrl: config.apiUrl || DEFAULT_CONFIG.apiUrl,\n timeout: config.timeout || DEFAULT_CONFIG.timeout,\n debug: config.debug || DEFAULT_CONFIG.debug,\n retryConfig: config.retryConfig,\n };\n }\n\n /**\n * Select the optimal model for a given input and mode\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n const mode = input.mode || 'balanced';\n const apiKey = this.config.apiKey || process.env.MORPH_API_KEY;\n\n if (!apiKey) {\n throw new Error(\n 'Morph API key is required. Set MORPH_API_KEY environment variable or pass apiKey in config.'\n );\n }\n\n const url = `${this.config.apiUrl}/v1/router/${this.provider}`;\n const payload = {\n input: input.input,\n mode,\n };\n\n if (this.config.debug) {\n console.log(`[ModelRouter] Requesting ${this.provider} model selection:`, {\n mode,\n inputLength: input.input.length,\n });\n }\n\n try {\n const fetchPromise = fetchWithRetry(\n url,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(payload),\n },\n this.config.retryConfig\n );\n\n const response = await withTimeout(\n fetchPromise,\n this.config.timeout,\n `Router API request timed out after ${this.config.timeout}ms`\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Router API error (${response.status}): ${errorText || response.statusText}`\n );\n }\n\n const apiResult: { model: string; confidence?: number } = await response.json();\n\n const result: RouterResult = {\n model: apiResult.model,\n };\n\n if (this.config.debug) {\n console.log(`[ModelRouter] Selected model: ${apiResult.model}, Confidence: ${apiResult.confidence?.toFixed(3)}`);\n }\n\n return result;\n } catch (error) {\n if (this.config.debug) {\n console.error(`[ModelRouter] Error selecting model:`, error);\n }\n throw error;\n }\n }\n}\n\n/**\n * OpenAI model router for GPT-5 series\n */\nexport class OpenAIRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('openai', config);\n }\n\n /**\n * Select optimal GPT-5 model\n * \n * @param input - User input and mode\n * @returns Selected model name (gpt-5-mini | gpt-5-low | gpt-5-medium | gpt-5-high)\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n return super.selectModel(input);\n }\n}\n\n/**\n * Anthropic model router for Claude 4.5 series\n */\nexport class AnthropicRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('anthropic', config);\n }\n\n /**\n * Select optimal Claude model\n * \n * @param input - User input and mode\n * @returns Selected model name (claude-4.5-haiku | claude-4.5-sonnet)\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n return super.selectModel(input);\n }\n}\n\n/**\n * Google Gemini model router\n */\nexport class GeminiRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('gemini', config);\n }\n\n /**\n * Select optimal Gemini model\n * \n * @param input - User input and mode\n * @returns Selected model name (gemini-2.5-flash | gemini-2.5-pro)\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n return super.selectModel(input);\n }\n}\n"],"mappings":";;;;;;AAcA,IAAM,iBAAiB;AAAA,EACrB,Q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describe("The lazy edit with // ... existing code ... markers")
|
|
56
56
|
});
|
|
57
57
|
return tool({
|
|
58
|
-
description: EDIT_FILE_TOOL_DESCRIPTION,
|
|
58
|
+
description: config.description || EDIT_FILE_TOOL_DESCRIPTION,
|
|
59
59
|
parameters: schema,
|
|
60
60
|
// @ts-ignore
|
|
61
61
|
execute: async (params) => {
|
|
@@ -88,4 +88,4 @@ export {
|
|
|
88
88
|
vercel_default,
|
|
89
89
|
vercel_exports
|
|
90
90
|
};
|
|
91
|
-
//# sourceMappingURL=chunk-
|
|
91
|
+
//# sourceMappingURL=chunk-IUCGXKTX.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/fastapply/vercel.ts"],"sourcesContent":["/**\n * Vercel AI SDK adapter for edit_file tool\n */\n\nimport { tool } from 'ai';\nimport { z } from 'zod';\nimport { executeEditFile } from './core.js';\nimport { EDIT_FILE_TOOL_DESCRIPTION, EDIT_FILE_SYSTEM_PROMPT } from './prompts.js';\nimport type { EditFileConfig } from './types.js';\n\n/**\n * Vercel AI SDK tool for edit_file\n * \n * @example\n * ```ts\n * import { generateText } from 'ai';\n * import { anthropic } from '@ai-sdk/anthropic';\n * import { editFileTool } from 'morphsdk/tools/vercel';\n * \n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { editFile: editFileTool },\n * prompt: \"Fix the bug in app.ts\"\n * });\n * ```\n */\nconst editFileSchema = z.object({\n target_filepath: z.string().describe('The path of the target file to modify'),\n instructions: z\n .string()\n .describe('A single sentence describing what you are changing (first person)'),\n code_edit: z\n .string()\n .describe('The lazy edit with // ... existing code ... markers'),\n});\n\n// @ts-ignore - Vercel AI SDK tool() has execute runtime support but types are incomplete\nexport const editFileTool = tool({\n description: EDIT_FILE_TOOL_DESCRIPTION,\n parameters: editFileSchema,\n // @ts-ignore\n execute: async (params) => {\n const result = await executeEditFile({\n target_filepath: params.target_filepath,\n instructions: params.instructions,\n code_edit: params.code_edit,\n });\n \n if (!result.success) {\n throw new Error(`Failed to edit file: ${result.error}`);\n }\n \n return {\n success: true,\n filepath: result.filepath,\n changes: result.changes,\n udiff: result.udiff,\n };\n },\n});\n\n/**\n * Get the system prompt for edit_file usage\n * \n * Add this to your system message to guide the model on using edit_file properly.\n * \n * @example\n * ```ts\n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * system: getSystemPrompt(),\n * tools: { editFile: editFileTool },\n * prompt: \"Fix bugs\"\n * });\n * ```\n */\nexport function getSystemPrompt(): string {\n return EDIT_FILE_SYSTEM_PROMPT;\n}\n\n/**\n * Create a custom edit_file tool with configuration\n * \n * @param config - Configuration options\n * @returns Vercel AI SDK tool with custom config\n * \n * @example\n * ```ts\n * const customEditTool = createEditFileTool({\n * baseDir: './src',\n * generateUdiff: true\n * });\n * \n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { editFile: customEditTool },\n * prompt: \"Fix bugs\"\n * });\n * ```\n */\nexport function createEditFileTool(config: EditFileConfig = {}) {\n const schema = z.object({\n target_filepath: z.string().describe('The path of the target file to modify'),\n instructions: z\n .string()\n .describe('A single sentence describing what you are changing (first person)'),\n code_edit: z\n .string()\n .describe('The lazy edit with // ... existing code ... markers'),\n });\n\n // @ts-ignore - Vercel AI SDK tool() has execute runtime support but types are incomplete\n return tool({\n description: EDIT_FILE_TOOL_DESCRIPTION,\n parameters: schema,\n // @ts-ignore\n execute: async (params) => {\n const result = await executeEditFile(\n {\n target_filepath: params.target_filepath,\n instructions: params.instructions,\n code_edit: params.code_edit,\n },\n config\n );\n \n if (!result.success) {\n throw new Error(`Failed to edit file: ${result.error}`);\n }\n \n return {\n success: true,\n filepath: result.filepath,\n changes: result.changes,\n udiff: result.udiff,\n };\n },\n });\n}\n\n// Default export for convenience\nexport default editFileTool;\n\n"],"mappings":";;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,SAAS,YAAY;AACrB,SAAS,SAAS;AAqBlB,IAAM,iBAAiB,EAAE,OAAO;AAAA,EAC9B,iBAAiB,EAAE,OAAO,EAAE,SAAS,uCAAuC;AAAA,EAC5E,cAAc,EACX,OAAO,EACP,SAAS,mEAAmE;AAAA,EAC/E,WAAW,EACR,OAAO,EACP,SAAS,qDAAqD;AACnE,CAAC;AAGM,IAAM,eAAe,KAAK;AAAA,EAC/B,aAAa;AAAA,EACb,YAAY;AAAA;AAAA,EAEZ,SAAS,OAAO,WAAW;AACzB,UAAM,SAAS,MAAM,gBAAgB;AAAA,MACnC,iBAAiB,OAAO;AAAA,MACxB,cAAc,OAAO;AAAA,MACrB,WAAW,OAAO;AAAA,IACpB,CAAC;AAED,QAAI,CAAC,OAAO,SAAS;AACnB,YAAM,IAAI,MAAM,wBAAwB,OAAO,KAAK,EAAE;AAAA,IACxD;AAEA,WAAO;AAAA,MACL,SAAS;AAAA,MACT,UAAU,OAAO;AAAA,MACjB,SAAS,OAAO;AAAA,MAChB,OAAO,OAAO;AAAA,IAChB;AAAA,EACF;AACF,CAAC;AAiBM,SAAS,kBAA0B;AACxC,SAAO;AACT;
|
|
1
|
+
{"version":3,"sources":["../tools/fastapply/vercel.ts"],"sourcesContent":["/**\n * Vercel AI SDK adapter for edit_file tool\n */\n\nimport { tool } from 'ai';\nimport { z } from 'zod';\nimport { executeEditFile } from './core.js';\nimport { EDIT_FILE_TOOL_DESCRIPTION, EDIT_FILE_SYSTEM_PROMPT } from './prompts.js';\nimport type { EditFileConfig } from './types.js';\n\n/**\n * Vercel AI SDK tool for edit_file\n * \n * @example\n * ```ts\n * import { generateText } from 'ai';\n * import { anthropic } from '@ai-sdk/anthropic';\n * import { editFileTool } from 'morphsdk/tools/vercel';\n * \n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { editFile: editFileTool },\n * prompt: \"Fix the bug in app.ts\"\n * });\n * ```\n */\nconst editFileSchema = z.object({\n target_filepath: z.string().describe('The path of the target file to modify'),\n instructions: z\n .string()\n .describe('A single sentence describing what you are changing (first person)'),\n code_edit: z\n .string()\n .describe('The lazy edit with // ... existing code ... markers'),\n});\n\n// @ts-ignore - Vercel AI SDK tool() has execute runtime support but types are incomplete\nexport const editFileTool = tool({\n description: EDIT_FILE_TOOL_DESCRIPTION,\n parameters: editFileSchema,\n // @ts-ignore\n execute: async (params) => {\n const result = await executeEditFile({\n target_filepath: params.target_filepath,\n instructions: params.instructions,\n code_edit: params.code_edit,\n });\n \n if (!result.success) {\n throw new Error(`Failed to edit file: ${result.error}`);\n }\n \n return {\n success: true,\n filepath: result.filepath,\n changes: result.changes,\n udiff: result.udiff,\n };\n },\n});\n\n/**\n * Get the system prompt for edit_file usage\n * \n * Add this to your system message to guide the model on using edit_file properly.\n * \n * @example\n * ```ts\n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * system: getSystemPrompt(),\n * tools: { editFile: editFileTool },\n * prompt: \"Fix bugs\"\n * });\n * ```\n */\nexport function getSystemPrompt(): string {\n return EDIT_FILE_SYSTEM_PROMPT;\n}\n\n/**\n * Create a custom edit_file tool with configuration\n * \n * @param config - Configuration options\n * @returns Vercel AI SDK tool with custom config\n * \n * @example\n * ```ts\n * const customEditTool = createEditFileTool({\n * baseDir: './src',\n * generateUdiff: true,\n * description: 'Custom tool description for your use case'\n * });\n * \n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { editFile: customEditTool },\n * prompt: \"Fix bugs\"\n * });\n * ```\n */\nexport function createEditFileTool(config: EditFileConfig = {}) {\n const schema = z.object({\n target_filepath: z.string().describe('The path of the target file to modify'),\n instructions: z\n .string()\n .describe('A single sentence describing what you are changing (first person)'),\n code_edit: z\n .string()\n .describe('The lazy edit with // ... existing code ... markers'),\n });\n\n // @ts-ignore - Vercel AI SDK tool() has execute runtime support but types are incomplete\n return tool({\n description: config.description || EDIT_FILE_TOOL_DESCRIPTION,\n parameters: schema,\n // @ts-ignore\n execute: async (params) => {\n const result = await executeEditFile(\n {\n target_filepath: params.target_filepath,\n instructions: params.instructions,\n code_edit: params.code_edit,\n },\n config\n );\n \n if (!result.success) {\n throw new Error(`Failed to edit file: ${result.error}`);\n }\n \n return {\n success: true,\n filepath: result.filepath,\n changes: result.changes,\n udiff: result.udiff,\n };\n },\n });\n}\n\n// Default export for convenience\nexport default editFileTool;\n\n"],"mappings":";;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,SAAS,YAAY;AACrB,SAAS,SAAS;AAqBlB,IAAM,iBAAiB,EAAE,OAAO;AAAA,EAC9B,iBAAiB,EAAE,OAAO,EAAE,SAAS,uCAAuC;AAAA,EAC5E,cAAc,EACX,OAAO,EACP,SAAS,mEAAmE;AAAA,EAC/E,WAAW,EACR,OAAO,EACP,SAAS,qDAAqD;AACnE,CAAC;AAGM,IAAM,eAAe,KAAK;AAAA,EAC/B,aAAa;AAAA,EACb,YAAY;AAAA;AAAA,EAEZ,SAAS,OAAO,WAAW;AACzB,UAAM,SAAS,MAAM,gBAAgB;AAAA,MACnC,iBAAiB,OAAO;AAAA,MACxB,cAAc,OAAO;AAAA,MACrB,WAAW,OAAO;AAAA,IACpB,CAAC;AAED,QAAI,CAAC,OAAO,SAAS;AACnB,YAAM,IAAI,MAAM,wBAAwB,OAAO,KAAK,EAAE;AAAA,IACxD;AAEA,WAAO;AAAA,MACL,SAAS;AAAA,MACT,UAAU,OAAO;AAAA,MACjB,SAAS,OAAO;AAAA,MAChB,OAAO,OAAO;AAAA,IAChB;AAAA,EACF;AACF,CAAC;AAiBM,SAAS,kBAA0B;AACxC,SAAO;AACT;AAuBO,SAAS,mBAAmB,SAAyB,CAAC,GAAG;AAC9D,QAAM,SAAS,EAAE,OAAO;AAAA,IACtB,iBAAiB,EAAE,OAAO,EAAE,SAAS,uCAAuC;AAAA,IAC5E,cAAc,EACX,OAAO,EACP,SAAS,mEAAmE;AAAA,IAC/E,WAAW,EACR,OAAO,EACP,SAAS,qDAAqD;AAAA,EACnE,CAAC;AAGD,SAAO,KAAK;AAAA,IACV,aAAa,OAAO,eAAe;AAAA,IACnC,YAAY;AAAA;AAAA,IAEZ,SAAS,OAAO,WAAW;AACzB,YAAM,SAAS,MAAM;AAAA,QACnB;AAAA,UACE,iBAAiB,OAAO;AAAA,UACxB,cAAc,OAAO;AAAA,UACrB,WAAW,OAAO;AAAA,QACpB;AAAA,QACA;AAAA,MACF;AAEA,UAAI,CAAC,OAAO,SAAS;AACnB,cAAM,IAAI,MAAM,wBAAwB,OAAO,KAAK,EAAE;AAAA,MACxD;AAEA,aAAO;AAAA,QACL,SAAS;AAAA,QACT,UAAU,OAAO;AAAA,QACjB,SAAS,OAAO;AAAA,QAChB,OAAO,OAAO;AAAA,MAChB;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAGA,IAAO,iBAAQ;","names":[]}
|
|
@@ -3,6 +3,82 @@ import {
|
|
|
3
3
|
withTimeout
|
|
4
4
|
} from "./chunk-4VWJFZVS.js";
|
|
5
5
|
|
|
6
|
+
// tools/browser/live.ts
|
|
7
|
+
var LIVE_PRESETS = {
|
|
8
|
+
/** Read-only monitoring (no interaction) */
|
|
9
|
+
readonly: { interactive: false },
|
|
10
|
+
/** Interactive control (human-in-the-loop) */
|
|
11
|
+
interactive: { interactive: true },
|
|
12
|
+
/** Watch-only without controls */
|
|
13
|
+
monitoring: { interactive: false, showControls: false }
|
|
14
|
+
};
|
|
15
|
+
function buildLiveUrl(debugUrl, options = {}) {
|
|
16
|
+
if (!debugUrl) {
|
|
17
|
+
throw new Error(
|
|
18
|
+
"debugUrl is required. Ensure your backend returns debugUrl in the task response. Contact support@morphllm.com if you need help."
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
const url = new URL(debugUrl);
|
|
22
|
+
if (options.interactive !== void 0) {
|
|
23
|
+
url.searchParams.set("interactive", String(options.interactive));
|
|
24
|
+
}
|
|
25
|
+
if (options.theme) {
|
|
26
|
+
url.searchParams.set("theme", options.theme);
|
|
27
|
+
}
|
|
28
|
+
if (options.showControls !== void 0) {
|
|
29
|
+
url.searchParams.set("showControls", String(options.showControls));
|
|
30
|
+
}
|
|
31
|
+
if (options.pageId) {
|
|
32
|
+
url.searchParams.set("pageId", options.pageId);
|
|
33
|
+
}
|
|
34
|
+
if (options.pageIndex) {
|
|
35
|
+
url.searchParams.set("pageIndex", options.pageIndex);
|
|
36
|
+
}
|
|
37
|
+
return url.toString();
|
|
38
|
+
}
|
|
39
|
+
function buildLiveIframe(debugUrl, options = {}) {
|
|
40
|
+
const {
|
|
41
|
+
width = "100%",
|
|
42
|
+
height = "600px",
|
|
43
|
+
style = "",
|
|
44
|
+
className = "",
|
|
45
|
+
...sessionOptions
|
|
46
|
+
} = options;
|
|
47
|
+
const src = buildLiveUrl(debugUrl, sessionOptions);
|
|
48
|
+
const widthStr = typeof width === "number" ? `${width}px` : width;
|
|
49
|
+
const heightStr = typeof height === "number" ? `${height}px` : height;
|
|
50
|
+
const baseStyle = `width: ${widthStr}; height: ${heightStr}; border: none;`;
|
|
51
|
+
const fullStyle = style ? `${baseStyle} ${style}` : baseStyle;
|
|
52
|
+
const attributes = [
|
|
53
|
+
`src="${src}"`,
|
|
54
|
+
`style="${fullStyle}"`
|
|
55
|
+
];
|
|
56
|
+
if (className) {
|
|
57
|
+
attributes.push(`class="${className}"`);
|
|
58
|
+
}
|
|
59
|
+
return `<iframe ${attributes.join(" ")}></iframe>`;
|
|
60
|
+
}
|
|
61
|
+
function buildEmbedCode(debugUrl, options = {}) {
|
|
62
|
+
const iframe = buildLiveIframe(debugUrl, options);
|
|
63
|
+
return `<!-- Embed Morph Live Session -->
|
|
64
|
+
${iframe}`;
|
|
65
|
+
}
|
|
66
|
+
function resolvePreset(optionsOrPreset) {
|
|
67
|
+
if (!optionsOrPreset) {
|
|
68
|
+
return {};
|
|
69
|
+
}
|
|
70
|
+
if (typeof optionsOrPreset === "string") {
|
|
71
|
+
const preset = LIVE_PRESETS[optionsOrPreset];
|
|
72
|
+
if (!preset) {
|
|
73
|
+
throw new Error(
|
|
74
|
+
`Unknown preset: ${optionsOrPreset}. Available presets: ${Object.keys(LIVE_PRESETS).join(", ")}`
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
return preset;
|
|
78
|
+
}
|
|
79
|
+
return optionsOrPreset;
|
|
80
|
+
}
|
|
81
|
+
|
|
6
82
|
// tools/browser/core.ts
|
|
7
83
|
var DEFAULT_CONFIG = {
|
|
8
84
|
apiUrl: process.env.MORPH_ENVIRONMENT === "DEV" ? "http://localhost:8000" : "https://browser.morphllm.com",
|
|
@@ -73,10 +149,16 @@ async function executeBrowserTask(input, config = {}) {
|
|
|
73
149
|
const timeout = config.timeout || DEFAULT_CONFIG.timeout;
|
|
74
150
|
const debug = config.debug || false;
|
|
75
151
|
if (!input.task || input.task.trim().length === 0) {
|
|
76
|
-
return {
|
|
152
|
+
return {
|
|
153
|
+
success: false,
|
|
154
|
+
error: 'Task description is required. Example: "Go to example.com and click the login button"'
|
|
155
|
+
};
|
|
77
156
|
}
|
|
78
157
|
if (input.max_steps !== void 0 && (input.max_steps < 1 || input.max_steps > 50)) {
|
|
79
|
-
return {
|
|
158
|
+
return {
|
|
159
|
+
success: false,
|
|
160
|
+
error: "max_steps must be between 1 and 50. Use more steps for complex multi-page flows."
|
|
161
|
+
};
|
|
80
162
|
}
|
|
81
163
|
if (debug) {
|
|
82
164
|
console.log(`[Browser] Task: "${input.task.slice(0, 60)}..." url=${input.url || "none"} maxSteps=${input.max_steps ?? 10}`);
|
|
@@ -129,7 +211,7 @@ async function executeBrowserTask(input, config = {}) {
|
|
|
129
211
|
if (error.message.includes("ECONNREFUSED") || error.message.includes("fetch failed")) {
|
|
130
212
|
return {
|
|
131
213
|
success: false,
|
|
132
|
-
error: `Cannot connect to browser worker at ${apiUrl}. Ensure the service is running.`
|
|
214
|
+
error: `Cannot connect to browser worker at ${apiUrl}. Ensure the service is running and accessible. For local dev, set MORPH_ENVIRONMENT=DEV.`
|
|
133
215
|
};
|
|
134
216
|
}
|
|
135
217
|
return {
|
|
@@ -294,7 +376,7 @@ function wrapTaskResponse(result, config) {
|
|
|
294
376
|
if (!result.task_id) {
|
|
295
377
|
throw new Error("task_id is required to wrap response");
|
|
296
378
|
}
|
|
297
|
-
|
|
379
|
+
const wrapped = {
|
|
298
380
|
...result,
|
|
299
381
|
task_id: result.task_id,
|
|
300
382
|
liveUrl: generateLiveUrl(result.task_id, config),
|
|
@@ -302,13 +384,42 @@ function wrapTaskResponse(result, config) {
|
|
|
302
384
|
return pollTaskUntilComplete(result.task_id, config, pollConfig);
|
|
303
385
|
}
|
|
304
386
|
};
|
|
387
|
+
if (result.debugUrl) {
|
|
388
|
+
wrapped.getLiveUrl = (options) => {
|
|
389
|
+
return buildLiveUrl(result.debugUrl, options);
|
|
390
|
+
};
|
|
391
|
+
wrapped.getLiveIframe = (optionsOrPreset) => {
|
|
392
|
+
const options = resolvePreset(optionsOrPreset);
|
|
393
|
+
return buildLiveIframe(result.debugUrl, options);
|
|
394
|
+
};
|
|
395
|
+
wrapped.getEmbedCode = () => {
|
|
396
|
+
return buildEmbedCode(result.debugUrl);
|
|
397
|
+
};
|
|
398
|
+
} else {
|
|
399
|
+
wrapped.getLiveUrl = () => {
|
|
400
|
+
throw new Error(
|
|
401
|
+
"Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help."
|
|
402
|
+
);
|
|
403
|
+
};
|
|
404
|
+
wrapped.getLiveIframe = () => {
|
|
405
|
+
throw new Error(
|
|
406
|
+
"Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help."
|
|
407
|
+
);
|
|
408
|
+
};
|
|
409
|
+
wrapped.getEmbedCode = () => {
|
|
410
|
+
throw new Error(
|
|
411
|
+
"Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help."
|
|
412
|
+
);
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
return wrapped;
|
|
305
416
|
}
|
|
306
417
|
function wrapTaskResponseWithSchema(result, config, schema) {
|
|
307
418
|
if (!result.task_id) {
|
|
308
419
|
throw new Error("task_id is required to wrap response");
|
|
309
420
|
}
|
|
310
421
|
const parsed = result.output ? parseStructuredTaskOutput(result, schema) : { ...result, parsed: null };
|
|
311
|
-
|
|
422
|
+
const wrapped = {
|
|
312
423
|
...parsed,
|
|
313
424
|
task_id: result.task_id,
|
|
314
425
|
liveUrl: generateLiveUrl(result.task_id, config),
|
|
@@ -317,6 +428,35 @@ function wrapTaskResponseWithSchema(result, config, schema) {
|
|
|
317
428
|
return parseStructuredTaskOutput(finalResult, schema);
|
|
318
429
|
}
|
|
319
430
|
};
|
|
431
|
+
if (result.debugUrl) {
|
|
432
|
+
wrapped.getLiveUrl = (options) => {
|
|
433
|
+
return buildLiveUrl(result.debugUrl, options);
|
|
434
|
+
};
|
|
435
|
+
wrapped.getLiveIframe = (optionsOrPreset) => {
|
|
436
|
+
const options = resolvePreset(optionsOrPreset);
|
|
437
|
+
return buildLiveIframe(result.debugUrl, options);
|
|
438
|
+
};
|
|
439
|
+
wrapped.getEmbedCode = () => {
|
|
440
|
+
return buildEmbedCode(result.debugUrl);
|
|
441
|
+
};
|
|
442
|
+
} else {
|
|
443
|
+
wrapped.getLiveUrl = () => {
|
|
444
|
+
throw new Error(
|
|
445
|
+
"Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help enabling live sessions. "
|
|
446
|
+
);
|
|
447
|
+
};
|
|
448
|
+
wrapped.getLiveIframe = () => {
|
|
449
|
+
throw new Error(
|
|
450
|
+
"Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help enabling live sessions."
|
|
451
|
+
);
|
|
452
|
+
};
|
|
453
|
+
wrapped.getEmbedCode = () => {
|
|
454
|
+
throw new Error(
|
|
455
|
+
"Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help enabling live sessions."
|
|
456
|
+
);
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
return wrapped;
|
|
320
460
|
}
|
|
321
461
|
async function checkHealth(config = {}) {
|
|
322
462
|
const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;
|
|
@@ -347,6 +487,10 @@ async function checkHealth(config = {}) {
|
|
|
347
487
|
}
|
|
348
488
|
|
|
349
489
|
export {
|
|
490
|
+
LIVE_PRESETS,
|
|
491
|
+
buildLiveUrl,
|
|
492
|
+
buildLiveIframe,
|
|
493
|
+
buildEmbedCode,
|
|
350
494
|
BrowserClient,
|
|
351
495
|
executeBrowserTask,
|
|
352
496
|
getRecording,
|
|
@@ -355,4 +499,4 @@ export {
|
|
|
355
499
|
getErrors,
|
|
356
500
|
checkHealth
|
|
357
501
|
};
|
|
358
|
-
//# sourceMappingURL=chunk-
|
|
502
|
+
//# sourceMappingURL=chunk-OWXIAZUZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../tools/browser/live.ts","../tools/browser/core.ts"],"sourcesContent":["/**\n * Live session utilities for Morph browser sessions\n * \n * Provides helpers for embedding and sharing live browser sessions with WebRTC streaming.\n */\n\nimport type { LiveSessionOptions, IframeOptions } from './types.js';\n\n/**\n * Preset configurations for common use cases\n */\nexport const LIVE_PRESETS = {\n /** Read-only monitoring (no interaction) */\n readonly: { interactive: false } as LiveSessionOptions,\n /** Interactive control (human-in-the-loop) */\n interactive: { interactive: true } as LiveSessionOptions,\n /** Watch-only without controls */\n monitoring: { interactive: false, showControls: false } as LiveSessionOptions,\n} as const;\n\n/**\n * Build a live session URL with query parameters\n * \n * @param debugUrl - Live session debug URL (e.g., from task.debugUrl)\n * @param options - Live session configuration options\n * @returns URL with query parameters for iframe embedding\n * \n * @example\n * ```typescript\n * const url = buildLiveUrl(task.debugUrl, { interactive: true });\n * // Returns: https://example.com/sessions/abc?interactive=true\n * ```\n */\nexport function buildLiveUrl(\n debugUrl: string,\n options: LiveSessionOptions = {}\n): string {\n if (!debugUrl) {\n throw new Error(\n 'debugUrl is required. Ensure your backend returns debugUrl in the task response. ' +\n 'Contact support@morphllm.com if you need help.'\n );\n } \n\n const url = new URL(debugUrl);\n \n // Add query parameters for supported options\n if (options.interactive !== undefined) {\n url.searchParams.set('interactive', String(options.interactive));\n }\n \n if (options.theme) {\n url.searchParams.set('theme', options.theme);\n }\n \n if (options.showControls !== undefined) {\n url.searchParams.set('showControls', String(options.showControls));\n }\n \n if (options.pageId) {\n url.searchParams.set('pageId', options.pageId);\n }\n \n if (options.pageIndex) {\n url.searchParams.set('pageIndex', options.pageIndex);\n }\n \n return url.toString();\n}\n\n/**\n * Build iframe HTML for embedding a live session\n * \n * @param debugUrl - Live session debug URL\n * @param options - Iframe configuration including dimensions and session options\n * @returns HTML iframe element as string\n * \n * @example\n * ```typescript\n * const iframe = buildLiveIframe(task.debugUrl, {\n * interactive: true,\n * width: '100%',\n * height: '600px'\n * });\n * ```\n */\nexport function buildLiveIframe(\n debugUrl: string,\n options: IframeOptions = {}\n): string {\n const {\n width = '100%',\n height = '600px',\n style = '',\n className = '',\n ...sessionOptions\n } = options;\n\n const src = buildLiveUrl(debugUrl, sessionOptions);\n \n // Convert numeric dimensions to pixels\n const widthStr = typeof width === 'number' ? `${width}px` : width;\n const heightStr = typeof height === 'number' ? `${height}px` : height;\n \n // Build style attribute\n const baseStyle = `width: ${widthStr}; height: ${heightStr}; border: none;`;\n const fullStyle = style ? `${baseStyle} ${style}` : baseStyle;\n \n // Build iframe attributes\n const attributes = [\n `src=\"${src}\"`,\n `style=\"${fullStyle}\"`,\n ];\n \n if (className) {\n attributes.push(`class=\"${className}\"`);\n }\n \n return `<iframe ${attributes.join(' ')}></iframe>`;\n}\n\n/**\n * Build complete embed code with HTML snippet\n * \n * @param debugUrl - Live session debug URL\n * @param options - Iframe configuration\n * @returns Multi-line HTML snippet ready to copy-paste\n * \n * @example\n * ```typescript\n * const code = buildEmbedCode(task.debugUrl, { interactive: false });\n * console.log(code);\n * // <!-- Embed Morph Live Session -->\n * // <iframe src=\"...\" style=\"...\"></iframe>\n * ```\n */\nexport function buildEmbedCode(\n debugUrl: string,\n options: IframeOptions = {}\n): string {\n const iframe = buildLiveIframe(debugUrl, options);\n return `<!-- Embed Morph Live Session -->\\n${iframe}`;\n}\n\n/**\n * Get live session options from preset name or custom config\n * \n * @internal\n */\nexport function resolvePreset(\n optionsOrPreset?: string | IframeOptions\n): IframeOptions {\n if (!optionsOrPreset) {\n return {};\n }\n \n if (typeof optionsOrPreset === 'string') {\n const preset = LIVE_PRESETS[optionsOrPreset as keyof typeof LIVE_PRESETS];\n if (!preset) {\n throw new Error(\n `Unknown preset: ${optionsOrPreset}. Available presets: ${Object.keys(LIVE_PRESETS).join(', ')}`\n );\n }\n return preset;\n }\n \n return optionsOrPreset;\n}\n\n","/**\n * Core implementation for browser automation tasks\n */\n\nimport { fetchWithRetry, withTimeout } from '../utils/resilience.js';\nimport type {\n BrowserConfig,\n BrowserTaskInput,\n BrowserTaskInputWithSchema,\n BrowserTaskResult,\n BrowserTaskWithPromise,\n BrowserTaskWithPromiseAndSchema,\n RecordingStatus,\n ErrorsResponse,\n LiveSessionOptions,\n IframeOptions,\n} from './types.js';\nimport { buildLiveUrl, buildLiveIframe, buildEmbedCode, resolvePreset } from './live.js';\n\nconst DEFAULT_CONFIG = {\n apiUrl: process.env.MORPH_ENVIRONMENT === 'DEV' \n ? 'http://localhost:8000'\n : 'https://browser.morphllm.com',\n timeout: 120000, // 2 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 constructor(config: BrowserConfig = {}) {\n this.config = {\n ...DEFAULT_CONFIG,\n ...config,\n };\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 if ('schema' in input) {\n const taskInput: BrowserTaskInput = {\n ...input,\n structured_output: stringifyStructuredOutput(input.schema),\n };\n const result = await executeBrowserTask(taskInput, this.config);\n return wrapTaskResponseWithSchema(result, this.config, input.schema);\n } else {\n const result = await executeBrowserTask(input, this.config);\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 & { record_video: true }\n ): Promise<BrowserTaskResult & { recording?: RecordingStatus }> {\n return executeWithRecording(input, this.config);\n }\n\n /**\n * Get recording status and URLs\n */\n async getRecording(recordingId: string): Promise<RecordingStatus> {\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<RecordingStatus> {\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 * 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 * @param input - Task parameters\n * @param config - Optional configuration (apiKey, apiUrl to override default)\n * @returns Task result with success status and findings\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 * max_steps: 20,\n * repo_id: \"my-project\",\n * commit_id: \"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('Replay:', result.replay_url);\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.max_steps !== undefined && (input.max_steps < 1 || input.max_steps > 50)) {\n return { \n success: false, \n error: 'max_steps must be between 1 and 50. Use more steps for complex multi-page flows.' \n };\n }\n\n if (debug) {\n console.log(`[Browser] Task: \"${input.task.slice(0, 60)}...\" url=${input.url || 'none'} maxSteps=${input.max_steps ?? 10}`);\n console.log(`[Browser] Recording: ${input.record_video ? 'yes' : 'no'} | Calling ${apiUrl}/browser-task`);\n }\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.max_steps ?? 10,\n model: input.model ?? 'morph-computer-use-v0',\n viewport_width: input.viewport_width ?? 1280,\n viewport_height: input.viewport_height ?? 720,\n repo_id: input.repo_id,\n commit_id: input.commit_id,\n record_video: input.record_video ?? false,\n video_width: input.video_width ?? input.viewport_width ?? 1280,\n video_height: input.video_height ?? input.viewport_height ?? 720,\n structured_output: input.structured_output,\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 max_steps.`\n );\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n if (debug) console.error(`[Browser] Error: ${response.status} - ${errorText}`);\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const result: BrowserTaskResult = await response.json();\n const elapsed = Date.now() - startTime;\n \n if (debug) {\n console.log(`[Browser] ✅ ${result.success ? 'Success' : 'Failed'} in ${elapsed}ms | steps=${result.steps_taken ?? 0} recordingId=${result.recording_id ?? 'none'}`);\n }\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 status with video URL when ready\n * \n * @example\n * ```typescript\n * const status = await getRecording('uuid-here', { apiKey: 'key' });\n * if (status.status === 'COMPLETED' && status.video_url) {\n * console.log('Video ready:', status.video_url);\n * }\n * ```\n */\nexport async function getRecording(\n recordingId: string,\n config: BrowserConfig = {}\n): Promise<RecordingStatus> {\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 recording = await response.json();\n if (debug) console.log(`[Browser] Recording status: ${recording.status}`);\n\n return recording;\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: '...', record_video: true }, config);\n * if (result.recording_id) {\n * const recording = await waitForRecording(result.recording_id, config, {\n * timeout: 60000, // 1 minute\n * pollInterval: 2000 // Check every 2 seconds\n * });\n * console.log('Video URL:', recording.video_url);\n * }\n * ```\n */\nexport async function waitForRecording(\n recordingId: string,\n config: BrowserConfig = {},\n options: { timeout?: number; pollInterval?: number } = {}\n): Promise<RecordingStatus> {\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 record_video=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 * record_video: true,\n * repo_id: \"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?.video_url);\n * ```\n */\nexport async function executeWithRecording(\n input: BrowserTaskInput & { record_video: true },\n config: BrowserConfig = {}\n): Promise<BrowserTaskResult & { recording?: RecordingStatus }> {\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.recording_id) {\n try {\n const recording = await waitForRecording(\n taskResult.recording_id,\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 return {\n ...taskResult,\n recording: {\n id: taskResult.recording_id,\n status: 'ERROR',\n error: error instanceof Error ? error.message : String(error),\n created_at: new Date().toISOString(),\n },\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, total_errors } = await getErrors('uuid-here', { apiKey: 'key' });\n * \n * console.log(`Found ${total_errors} 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.screenshot_url) console.log(` Screenshot: ${err.screenshot_url}`);\n * \n * // Download screenshot\n * if (err.screenshot_url) {\n * const response = await fetch(err.screenshot_url);\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 = await response.json();\n if (debug) console.log(`[Browser] Found ${errors.total_errors} 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\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 = 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 if (!result.task_id) {\n throw new Error('task_id is required to wrap response');\n }\n\n const wrapped: BrowserTaskWithPromise = {\n ...result,\n task_id: result.task_id,\n liveUrl: generateLiveUrl(result.task_id, config),\n complete: async (pollConfig?: { interval?: number; timeout?: number }) => {\n return pollTaskUntilComplete(result.task_id!, config, pollConfig);\n },\n };\n\n // Add Steel live session helpers if debugUrl is available\n if (result.debugUrl) {\n wrapped.getLiveUrl = (options?: LiveSessionOptions) => {\n return buildLiveUrl(result.debugUrl!, options);\n };\n\n wrapped.getLiveIframe = (optionsOrPreset?: string | IframeOptions) => {\n const options = resolvePreset(optionsOrPreset);\n return buildLiveIframe(result.debugUrl!, options);\n };\n\n wrapped.getEmbedCode = () => {\n return buildEmbedCode(result.debugUrl!);\n };\n } else {\n // Provide helpful error messages when methods are called without debugUrl\n wrapped.getLiveUrl = () => {\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 wrapped.getLiveIframe = () => {\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 wrapped.getEmbedCode = () => {\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 if (!result.task_id) {\n throw new Error('task_id is required to wrap response');\n }\n\n const parsed = result.output\n ? parseStructuredTaskOutput<T>(result, schema)\n : { ...result, parsed: null };\n\n const wrapped: BrowserTaskWithPromiseAndSchema<T> = {\n ...parsed,\n task_id: result.task_id,\n liveUrl: generateLiveUrl(result.task_id, config),\n complete: async (pollConfig?: { interval?: number; timeout?: number }) => {\n const finalResult = await pollTaskUntilComplete(result.task_id!, config, pollConfig);\n return parseStructuredTaskOutput<T>(finalResult, schema);\n },\n };\n\n // Add Steel live session helpers if debugUrl is available\n if (result.debugUrl) {\n wrapped.getLiveUrl = (options?: LiveSessionOptions) => {\n return buildLiveUrl(result.debugUrl!, options);\n };\n\n wrapped.getLiveIframe = (optionsOrPreset?: string | IframeOptions) => {\n const options = resolvePreset(optionsOrPreset);\n return buildLiveIframe(result.debugUrl!, options);\n };\n\n wrapped.getEmbedCode = () => {\n return buildEmbedCode(result.debugUrl!);\n };\n } else {\n // Provide helpful error messages when methods are called without debugUrl\n wrapped.getLiveUrl = () => {\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 wrapped.getLiveIframe = () => {\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 wrapped.getEmbedCode = () => {\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 * 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\n"],"mappings":";;;;;;AAWO,IAAM,eAAe;AAAA;AAAA,EAE1B,UAAU,EAAE,aAAa,MAAM;AAAA;AAAA,EAE/B,aAAa,EAAE,aAAa,KAAK;AAAA;AAAA,EAEjC,YAAY,EAAE,aAAa,OAAO,cAAc,MAAM;AACxD;AAeO,SAAS,aACd,UACA,UAA8B,CAAC,GACvB;AACR,MAAI,CAAC,UAAU;AACb,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AAEA,QAAM,MAAM,IAAI,IAAI,QAAQ;AAG5B,MAAI,QAAQ,gBAAgB,QAAW;AACrC,QAAI,aAAa,IAAI,eAAe,OAAO,QAAQ,WAAW,CAAC;AAAA,EACjE;AAEA,MAAI,QAAQ,OAAO;AACjB,QAAI,aAAa,IAAI,SAAS,QAAQ,KAAK;AAAA,EAC7C;AAEA,MAAI,QAAQ,iBAAiB,QAAW;AACtC,QAAI,aAAa,IAAI,gBAAgB,OAAO,QAAQ,YAAY,CAAC;AAAA,EACnE;AAEA,MAAI,QAAQ,QAAQ;AAClB,QAAI,aAAa,IAAI,UAAU,QAAQ,MAAM;AAAA,EAC/C;AAEA,MAAI,QAAQ,WAAW;AACrB,QAAI,aAAa,IAAI,aAAa,QAAQ,SAAS;AAAA,EACrD;AAEA,SAAO,IAAI,SAAS;AACtB;AAkBO,SAAS,gBACd,UACA,UAAyB,CAAC,GAClB;AACR,QAAM;AAAA,IACJ,QAAQ;AAAA,IACR,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,YAAY;AAAA,IACZ,GAAG;AAAA,EACL,IAAI;AAEJ,QAAM,MAAM,aAAa,UAAU,cAAc;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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":[]}
|
|
@@ -70,7 +70,16 @@ Summary: ${summary}`;
|
|
|
70
70
|
return `Successfully applied changes to ${result.filepath}. ${summary}`;
|
|
71
71
|
}
|
|
72
72
|
function createEditFileTool(config = {}) {
|
|
73
|
-
|
|
73
|
+
const toolDef = {
|
|
74
|
+
...editFileTool,
|
|
75
|
+
...config.description && {
|
|
76
|
+
function: {
|
|
77
|
+
...editFileTool.function,
|
|
78
|
+
description: config.description
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
return Object.assign({}, toolDef, {
|
|
74
83
|
execute: async (input) => {
|
|
75
84
|
const parsedInput = typeof input === "string" ? JSON.parse(input) : input;
|
|
76
85
|
return execute(parsedInput, config);
|
|
@@ -94,4 +103,4 @@ export {
|
|
|
94
103
|
openai_default,
|
|
95
104
|
openai_exports
|
|
96
105
|
};
|
|
97
|
-
//# sourceMappingURL=chunk-
|
|
106
|
+
//# sourceMappingURL=chunk-QFUHDWGY.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/fastapply/openai.ts"],"sourcesContent":["/**\n * OpenAI SDK adapter for edit_file tool\n */\n\nimport type { ChatCompletionTool } from 'openai/resources/chat/completions';\nimport { executeEditFile } from './core.js';\nimport { EDIT_FILE_TOOL_DESCRIPTION, EDIT_FILE_SYSTEM_PROMPT } from './prompts.js';\nimport type { EditFileInput, EditFileResult, EditFileConfig } from './types.js';\n\n/**\n * OpenAI-native tool definition for edit_file\n * \n * @example\n * ```ts\n * import OpenAI from 'openai';\n * import { editFileTool } from 'morphsdk/tools/openai';\n * \n * const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });\n * \n * const response = await client.chat.completions.create({\n * model: \"gpt-4o\",\n * tools: [editFileTool],\n * messages: [{ role: \"user\", content: \"Fix the bug in app.ts\" }]\n * });\n * ```\n */\nexport const editFileTool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: 'edit_file',\n description: EDIT_FILE_TOOL_DESCRIPTION,\n parameters: {\n type: 'object',\n properties: {\n target_filepath: {\n type: 'string',\n description: 'The path of the target file to modify',\n },\n instructions: {\n type: 'string',\n description: 'A single sentence describing what you are changing (first person)',\n },\n code_edit: {\n type: 'string',\n description: 'The lazy edit with // ... existing code ... markers',\n },\n },\n required: ['target_filepath', 'instructions', 'code_edit'],\n },\n },\n};\n\n/**\n * Execute an edit_file tool call\n * \n * @param input - The tool input from GPT (parsed from tool_calls)\n * @param config - Optional configuration\n * @returns The result of the edit operation\n * \n * @example\n * ```ts\n * const args = JSON.parse(toolCall.function.arguments);\n * const result = await execute(args);\n * console.log('Changes applied:', result.udiff);\n * ```\n */\nexport async function execute(\n input: EditFileInput,\n config?: EditFileConfig\n): Promise<EditFileResult> {\n return executeEditFile(input, config);\n}\n\n/**\n * Get the system prompt for edit_file usage\n * \n * Add this to your system message to guide GPT on using edit_file properly.\n * \n * @example\n * ```ts\n * const response = await client.chat.completions.create({\n * model: \"gpt-4o\",\n * messages: [\n * { role: \"system\", content: getSystemPrompt() },\n * { role: \"user\", content: \"Fix bugs\" }\n * ],\n * tools: [editFileTool]\n * });\n * ```\n */\nexport function getSystemPrompt(): string {\n return EDIT_FILE_SYSTEM_PROMPT;\n}\n\n/**\n * Format the result for passing back to GPT\n * \n * @param result - The edit result\n * @returns Formatted string for tool message\n */\nexport function formatResult(result: EditFileResult): string {\n if (!result.success) {\n return `Error editing file: ${result.error}`;\n }\n \n const { changes } = result;\n const summary = [\n changes.linesAdded && `+${changes.linesAdded} lines`,\n changes.linesRemoved && `-${changes.linesRemoved} lines`,\n changes.linesModified && `~${changes.linesModified} lines modified`,\n ]\n .filter(Boolean)\n .join(', ');\n \n if (result.udiff) {\n return `Successfully applied changes to ${result.filepath}:\\n\\n${result.udiff}\\n\\nSummary: ${summary}`;\n }\n \n return `Successfully applied changes to ${result.filepath}. ${summary}`;\n}\n\n/**\n * Create a custom edit_file tool with configuration and methods\n * \n * @param config - Configuration options\n * @returns Tool definition with execute and formatResult methods\n * \n * @example\n * ```ts\n * import OpenAI from 'openai';\n * import { createEditFileTool } from 'morphsdk/tools/fastapply/openai';\n * \n * const tool = createEditFileTool({\n * baseDir: './src',\n * generateUdiff: true\n * });\n * \n * const client = new OpenAI();\n * \n * const response = await client.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [tool], // tool itself is the ChatCompletionTool\n * messages: [{ role: 'user', content: 'Fix bug in app.ts' }]\n * });\n * \n * // Execute and format\n * const result = await tool.execute(toolCallArgs);\n * const formatted = tool.formatResult(result);\n * ```\n */\nexport function createEditFileTool(config: EditFileConfig = {}) {\n return Object.assign({},
|
|
1
|
+
{"version":3,"sources":["../tools/fastapply/openai.ts"],"sourcesContent":["/**\n * OpenAI SDK adapter for edit_file tool\n */\n\nimport type { ChatCompletionTool } from 'openai/resources/chat/completions';\nimport { executeEditFile } from './core.js';\nimport { EDIT_FILE_TOOL_DESCRIPTION, EDIT_FILE_SYSTEM_PROMPT } from './prompts.js';\nimport type { EditFileInput, EditFileResult, EditFileConfig } from './types.js';\n\n/**\n * OpenAI-native tool definition for edit_file\n * \n * @example\n * ```ts\n * import OpenAI from 'openai';\n * import { editFileTool } from 'morphsdk/tools/openai';\n * \n * const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });\n * \n * const response = await client.chat.completions.create({\n * model: \"gpt-4o\",\n * tools: [editFileTool],\n * messages: [{ role: \"user\", content: \"Fix the bug in app.ts\" }]\n * });\n * ```\n */\nexport const editFileTool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: 'edit_file',\n description: EDIT_FILE_TOOL_DESCRIPTION,\n parameters: {\n type: 'object',\n properties: {\n target_filepath: {\n type: 'string',\n description: 'The path of the target file to modify',\n },\n instructions: {\n type: 'string',\n description: 'A single sentence describing what you are changing (first person)',\n },\n code_edit: {\n type: 'string',\n description: 'The lazy edit with // ... existing code ... markers',\n },\n },\n required: ['target_filepath', 'instructions', 'code_edit'],\n },\n },\n};\n\n/**\n * Execute an edit_file tool call\n * \n * @param input - The tool input from GPT (parsed from tool_calls)\n * @param config - Optional configuration\n * @returns The result of the edit operation\n * \n * @example\n * ```ts\n * const args = JSON.parse(toolCall.function.arguments);\n * const result = await execute(args);\n * console.log('Changes applied:', result.udiff);\n * ```\n */\nexport async function execute(\n input: EditFileInput,\n config?: EditFileConfig\n): Promise<EditFileResult> {\n return executeEditFile(input, config);\n}\n\n/**\n * Get the system prompt for edit_file usage\n * \n * Add this to your system message to guide GPT on using edit_file properly.\n * \n * @example\n * ```ts\n * const response = await client.chat.completions.create({\n * model: \"gpt-4o\",\n * messages: [\n * { role: \"system\", content: getSystemPrompt() },\n * { role: \"user\", content: \"Fix bugs\" }\n * ],\n * tools: [editFileTool]\n * });\n * ```\n */\nexport function getSystemPrompt(): string {\n return EDIT_FILE_SYSTEM_PROMPT;\n}\n\n/**\n * Format the result for passing back to GPT\n * \n * @param result - The edit result\n * @returns Formatted string for tool message\n */\nexport function formatResult(result: EditFileResult): string {\n if (!result.success) {\n return `Error editing file: ${result.error}`;\n }\n \n const { changes } = result;\n const summary = [\n changes.linesAdded && `+${changes.linesAdded} lines`,\n changes.linesRemoved && `-${changes.linesRemoved} lines`,\n changes.linesModified && `~${changes.linesModified} lines modified`,\n ]\n .filter(Boolean)\n .join(', ');\n \n if (result.udiff) {\n return `Successfully applied changes to ${result.filepath}:\\n\\n${result.udiff}\\n\\nSummary: ${summary}`;\n }\n \n return `Successfully applied changes to ${result.filepath}. ${summary}`;\n}\n\n/**\n * Create a custom edit_file tool with configuration and methods\n * \n * @param config - Configuration options\n * @returns Tool definition with execute and formatResult methods\n * \n * @example\n * ```ts\n * import OpenAI from 'openai';\n * import { createEditFileTool } from 'morphsdk/tools/fastapply/openai';\n * \n * const tool = createEditFileTool({\n * baseDir: './src',\n * generateUdiff: true,\n * description: 'Custom tool description for your use case'\n * });\n * \n * const client = new OpenAI();\n * \n * const response = await client.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [tool], // tool itself is the ChatCompletionTool\n * messages: [{ role: 'user', content: 'Fix bug in app.ts' }]\n * });\n * \n * // Execute and format\n * const result = await tool.execute(toolCallArgs);\n * const formatted = tool.formatResult(result);\n * ```\n */\nexport function createEditFileTool(config: EditFileConfig = {}) {\n const toolDef: ChatCompletionTool = {\n ...editFileTool,\n ...(config.description && {\n function: {\n ...editFileTool.function,\n description: config.description,\n },\n }),\n };\n \n return Object.assign({}, toolDef, {\n execute: async (input: EditFileInput | string): Promise<EditFileResult> => {\n const parsedInput = typeof input === 'string' ? JSON.parse(input) : input;\n return execute(parsedInput, config);\n },\n formatResult: (result: EditFileResult): string => {\n return formatResult(result);\n },\n getSystemPrompt: (): string => {\n return getSystemPrompt();\n },\n });\n}\n\n// Default export for convenience\nexport default editFileTool;\n\n"],"mappings":";;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA0BO,IAAM,eAAmC;AAAA,EAC9C,MAAM;AAAA,EACN,UAAU;AAAA,IACR,MAAM;AAAA,IACN,aAAa;AAAA,IACb,YAAY;AAAA,MACV,MAAM;AAAA,MACN,YAAY;AAAA,QACV,iBAAiB;AAAA,UACf,MAAM;AAAA,UACN,aAAa;AAAA,QACf;AAAA,QACA,cAAc;AAAA,UACZ,MAAM;AAAA,UACN,aAAa;AAAA,QACf;AAAA,QACA,WAAW;AAAA,UACT,MAAM;AAAA,UACN,aAAa;AAAA,QACf;AAAA,MACF;AAAA,MACA,UAA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