opencode-morphllm 0.0.4 → 0.0.6

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.
@@ -0,0 +1,204 @@
1
+ import {
2
+ describe,
3
+ it,
4
+ expect,
5
+ beforeEach,
6
+ vi,
7
+ beforeAll,
8
+ afterAll,
9
+ } from 'bun:test';
10
+ import { existsSync, writeFileSync, rmSync, mkdirSync } from 'node:fs';
11
+ import { join } from 'node:path';
12
+ import { tmpdir } from 'node:os';
13
+ // Mock the opencode-config-dir module before importing config
14
+ const mockConfigDir = join(tmpdir(), 'mock-opencode-config-test');
15
+ const mockMorphJson = join(mockConfigDir, 'morph.json');
16
+ const mockMorphJsonc = join(mockConfigDir, 'morph.jsonc');
17
+ vi.mock('./opencode-config-dir', () => ({
18
+ getOpenCodeConfigDir: vi.fn(() => mockConfigDir),
19
+ }));
20
+ import {
21
+ getMorphPluginConfigPath,
22
+ loadMorphPluginConfig,
23
+ loadMorphPluginConfigWithProjectOverride,
24
+ } from './config';
25
+ describe('config.ts', () => {
26
+ beforeAll(() => {
27
+ // Create mock config directory
28
+ if (!existsSync(mockConfigDir)) {
29
+ mkdirSync(mockConfigDir, { recursive: true });
30
+ }
31
+ });
32
+ afterAll(() => {
33
+ // Cleanup
34
+ try {
35
+ if (existsSync(mockMorphJson)) rmSync(mockMorphJson);
36
+ if (existsSync(mockMorphJsonc)) rmSync(mockMorphJsonc);
37
+ if (existsSync(mockConfigDir)) rmSync(mockConfigDir, { recursive: true });
38
+ } catch {
39
+ // Ignore cleanup errors
40
+ }
41
+ });
42
+ beforeEach(() => {
43
+ // Clean up any existing config files before each test
44
+ try {
45
+ if (existsSync(mockMorphJson)) rmSync(mockMorphJson);
46
+ if (existsSync(mockMorphJsonc)) rmSync(mockMorphJsonc);
47
+ } catch {
48
+ // Ignore cleanup errors
49
+ }
50
+ });
51
+ describe('getMorphPluginConfigPath', () => {
52
+ it('should return path to morph.json in config directory', () => {
53
+ const path = getMorphPluginConfigPath();
54
+ expect(path).toContain('morph.json');
55
+ expect(path).toContain(mockConfigDir);
56
+ });
57
+ });
58
+ describe('loadMorphPluginConfig', () => {
59
+ it('should return null when no config files exist', () => {
60
+ const result = loadMorphPluginConfig();
61
+ expect(result).toBeNull();
62
+ });
63
+ it('should load config from .jsonc file', () => {
64
+ const content = `{
65
+ "MORPH_API_KEY": "test-key-123",
66
+ "MORPH_ROUTER_ENABLED": false
67
+ }`;
68
+ writeFileSync(mockMorphJsonc, content);
69
+ const result = loadMorphPluginConfig();
70
+ expect(result).not.toBeNull();
71
+ expect(result?.MORPH_API_KEY).toBe('test-key-123');
72
+ expect(result?.MORPH_ROUTER_ENABLED).toBe(false);
73
+ });
74
+ it('should load config from .json file', () => {
75
+ const content = JSON.stringify({
76
+ MORPH_API_KEY: 'json-key-456',
77
+ MORPH_MODEL_EASY: 'provider/model-easy',
78
+ });
79
+ writeFileSync(mockMorphJson, content);
80
+ const result = loadMorphPluginConfig();
81
+ expect(result).not.toBeNull();
82
+ expect(result?.MORPH_API_KEY).toBe('json-key-456');
83
+ expect(result?.MORPH_MODEL_EASY).toBe('provider/model-easy');
84
+ });
85
+ it('should prefer .jsonc over .json when both exist', () => {
86
+ const jsoncContent = '{"MORPH_API_KEY": "from-jsonc"}';
87
+ const jsonContent = '{"MORPH_API_KEY": "from-json"}';
88
+ writeFileSync(mockMorphJsonc, jsoncContent);
89
+ writeFileSync(mockMorphJson, jsonContent);
90
+ const result = loadMorphPluginConfig();
91
+ expect(result?.MORPH_API_KEY).toBe('from-jsonc');
92
+ });
93
+ it('should return null for invalid .jsonc content', () => {
94
+ writeFileSync(mockMorphJsonc, 'invalid json content');
95
+ const result = loadMorphPluginConfig();
96
+ expect(result).toBeNull();
97
+ });
98
+ it('should return null for invalid .json content', () => {
99
+ writeFileSync(mockMorphJson, 'invalid json content');
100
+ const result = loadMorphPluginConfig();
101
+ expect(result).toBeNull();
102
+ });
103
+ it('should handle all MORPH config fields', () => {
104
+ const content = JSON.stringify({
105
+ MORPH_API_KEY: 'api-key',
106
+ MORPH_ROUTER_ENABLED: true,
107
+ MORPH_MODEL_EASY: 'easy/provider/model',
108
+ MORPH_MODEL_MEDIUM: 'medium/provider/model',
109
+ MORPH_MODEL_HARD: 'hard/provider/model',
110
+ MORPH_MODEL_DEFAULT: 'default/provider/model',
111
+ });
112
+ writeFileSync(mockMorphJson, content);
113
+ const result = loadMorphPluginConfig();
114
+ expect(result).toEqual({
115
+ MORPH_API_KEY: 'api-key',
116
+ MORPH_ROUTER_ENABLED: true,
117
+ MORPH_MODEL_EASY: 'easy/provider/model',
118
+ MORPH_MODEL_MEDIUM: 'medium/provider/model',
119
+ MORPH_MODEL_HARD: 'hard/provider/model',
120
+ MORPH_MODEL_DEFAULT: 'default/provider/model',
121
+ });
122
+ });
123
+ it('should handle nested MORPH_ROUTER_CONFIGS', () => {
124
+ const content = JSON.stringify({
125
+ MORPH_API_KEY: 'api-key',
126
+ MORPH_ROUTER_CONFIGS: {
127
+ MORPH_ROUTER_ENABLED: true,
128
+ MORPH_MODEL_EASY: 'easy/provider/model',
129
+ MORPH_MODEL_MEDIUM: 'medium/provider/model',
130
+ MORPH_MODEL_HARD: 'hard/provider/model',
131
+ MORPH_MODEL_DEFAULT: 'default/provider/model',
132
+ },
133
+ });
134
+ writeFileSync(mockMorphJson, content);
135
+ const result = loadMorphPluginConfig();
136
+ expect(result?.MORPH_API_KEY).toBe('api-key');
137
+ expect(result?.MORPH_ROUTER_CONFIGS).toEqual({
138
+ MORPH_ROUTER_ENABLED: true,
139
+ MORPH_MODEL_EASY: 'easy/provider/model',
140
+ MORPH_MODEL_MEDIUM: 'medium/provider/model',
141
+ MORPH_MODEL_HARD: 'hard/provider/model',
142
+ MORPH_MODEL_DEFAULT: 'default/provider/model',
143
+ });
144
+ });
145
+ });
146
+ describe('loadMorphPluginConfigWithProjectOverride', () => {
147
+ it('should return empty object when no config exists', () => {
148
+ const result =
149
+ loadMorphPluginConfigWithProjectOverride('/non-existent-path');
150
+ expect(result).toEqual({});
151
+ });
152
+ it('should merge user config with project config', () => {
153
+ // Create user config
154
+ writeFileSync(
155
+ mockMorphJson,
156
+ JSON.stringify({
157
+ MORPH_API_KEY: 'user-api-key',
158
+ MORPH_MODEL_EASY: 'user-easy-model',
159
+ })
160
+ );
161
+ // Create project config directory
162
+ const projectDir = join(tmpdir(), 'test-project');
163
+ const projectConfigDir = join(projectDir, '.opencode');
164
+ const projectConfigPath = join(projectConfigDir, 'morph.json');
165
+ mkdirSync(projectConfigDir, { recursive: true });
166
+ writeFileSync(
167
+ projectConfigPath,
168
+ JSON.stringify({
169
+ MORPH_API_KEY: 'project-api-key',
170
+ MORPH_MODEL_HARD: 'project-hard-model',
171
+ })
172
+ );
173
+ const result = loadMorphPluginConfigWithProjectOverride(projectDir);
174
+ // Project config should override user config
175
+ expect(result.MORPH_API_KEY).toBe('project-api-key');
176
+ expect(result.MORPH_MODEL_EASY).toBe('user-easy-model');
177
+ expect(result.MORPH_MODEL_HARD).toBe('project-hard-model');
178
+ });
179
+ it('should handle project .jsonc config', () => {
180
+ // Create user config
181
+ writeFileSync(
182
+ mockMorphJson,
183
+ JSON.stringify({
184
+ MORPH_API_KEY: 'user-key',
185
+ })
186
+ );
187
+ // Create project config with .jsonc
188
+ const projectDir = join(tmpdir(), 'test-project2');
189
+ const projectConfigDir = join(projectDir, '.opencode');
190
+ const projectConfigPath = join(projectConfigDir, 'morph.jsonc');
191
+ mkdirSync(projectConfigDir, { recursive: true });
192
+ const jsoncContent = `
193
+ // Project config with comments
194
+ {
195
+ "MORPH_MODEL_MEDIUM": "project-medium-model"
196
+ }
197
+ `;
198
+ writeFileSync(projectConfigPath, jsoncContent);
199
+ const result = loadMorphPluginConfigWithProjectOverride(projectDir);
200
+ expect(result.MORPH_API_KEY).toBe('user-key');
201
+ expect(result.MORPH_MODEL_MEDIUM).toBe('project-medium-model');
202
+ });
203
+ });
204
+ });
@@ -0,0 +1,9 @@
1
+ interface OpenCodeConfigDirOptions {
2
+ binary: 'opencode' | 'opencode-desktop';
3
+ version?: string | null;
4
+ checkExisting?: boolean;
5
+ }
6
+ export declare function getOpenCodeConfigDir(
7
+ options: OpenCodeConfigDirOptions
8
+ ): string;
9
+ export {};
@@ -0,0 +1,56 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { join, resolve } from 'node:path';
4
+ function getTauriConfigDir(identifier) {
5
+ const platform = process.platform;
6
+ switch (platform) {
7
+ case 'darwin':
8
+ return join(homedir(), 'Library', 'Application Support', identifier);
9
+ case 'win32': {
10
+ const appData =
11
+ process.env.APPDATA || join(homedir(), 'AppData', 'Roaming');
12
+ return join(appData, identifier);
13
+ }
14
+ case 'linux':
15
+ default: {
16
+ const xdgConfig =
17
+ process.env.XDG_CONFIG_HOME || join(homedir(), '.config');
18
+ return join(xdgConfig, identifier);
19
+ }
20
+ }
21
+ }
22
+ function getCliConfigDir() {
23
+ const envConfigDir = process.env.OPENCODE_CONFIG_DIR?.trim();
24
+ if (envConfigDir) {
25
+ return resolve(envConfigDir);
26
+ }
27
+ if (process.platform === 'win32') {
28
+ const crossPlatformDir = join(homedir(), '.config', 'opencode');
29
+ const crossPlatformConfig = join(crossPlatformDir, 'opencode.json');
30
+ if (existsSync(crossPlatformConfig)) {
31
+ return crossPlatformDir;
32
+ }
33
+ const appData =
34
+ process.env.APPDATA || join(homedir(), 'AppData', 'Roaming');
35
+ const appdataDir = join(appData, 'opencode');
36
+ const appdataConfig = join(appdataDir, 'opencode.json');
37
+ if (existsSync(appdataConfig)) {
38
+ return appdataDir;
39
+ }
40
+ return crossPlatformDir;
41
+ }
42
+ const xdgConfig = process.env.XDG_CONFIG_HOME || join(homedir(), '.config');
43
+ return join(xdgConfig, 'opencode');
44
+ }
45
+ export function getOpenCodeConfigDir(options) {
46
+ if (options.binary === 'opencode-desktop') {
47
+ const version = options.version;
48
+ const isDev =
49
+ !!version && (version.includes('-dev') || version.includes('.dev'));
50
+ const identifier = isDev
51
+ ? 'ai.opencode.desktop.dev'
52
+ : 'ai.opencode.desktop';
53
+ return getTauriConfigDir(identifier);
54
+ }
55
+ return getCliConfigDir();
56
+ }
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "opencode-morphllm",
3
- "version": "0.0.4",
3
+ "version": "0.0.6",
4
4
  "author": "Vito Lin",
5
5
  "main": "dist/index.js",
6
6
  "description": "OpenCode plugin for MorphLLM",
7
7
  "scripts": {
8
- "build": "tsc -p tsconfig.json",
8
+ "build": "rm -rf dist && tsc -p tsconfig.json",
9
9
  "test": "bun test",
10
10
  "format": "prettier --write .",
11
11
  "format:check": "prettier --check .",
package/src/index.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { Plugin } from '@opencode-ai/plugin';
2
2
  import type { McpLocalConfig } from '@opencode-ai/sdk';
3
3
 
4
- import { createBuiltinMcps } from './mcps';
5
- import { createModelRouterHook } from './router';
6
- import { MORPH_ROUTER_ENABLED } from './const';
4
+ import { createBuiltinMcps } from './morph/mcps';
5
+ import { createModelRouterHook } from './morph/router';
6
+ import { MORPH_ROUTER_ENABLED } from './shared/config';
7
7
 
8
8
  const MorphOpenCodePlugin: Plugin = async () => {
9
9
  const builtinMcps: Record<string, McpLocalConfig> = createBuiltinMcps();
@@ -0,0 +1,51 @@
1
+ import { describe, it, expect, vi } from 'bun:test';
2
+
3
+ vi.mock('../shared/config', () => ({
4
+ API_KEY: 'test-api-key-123',
5
+ }));
6
+
7
+ import { createBuiltinMcps } from './mcps';
8
+
9
+ describe('mcps.ts', () => {
10
+ describe('createBuiltinMcps', () => {
11
+ it('should create morph_mcp configuration', () => {
12
+ const mcps = createBuiltinMcps();
13
+
14
+ expect(mcps).toHaveProperty('morph_mcp');
15
+ expect(mcps.morph_mcp.type).toBe('local');
16
+ expect(mcps.morph_mcp.enabled).toBe(true);
17
+ });
18
+
19
+ it('should set correct command for morph_mcp', () => {
20
+ const mcps = createBuiltinMcps();
21
+
22
+ expect(mcps.morph_mcp.command).toEqual([
23
+ 'npx',
24
+ '-y',
25
+ '@morphllm/morphmcp',
26
+ ]);
27
+ });
28
+
29
+ it('should set MORPH_API_KEY in environment', () => {
30
+ const mcps = createBuiltinMcps();
31
+ const env = mcps.morph_mcp.environment;
32
+
33
+ expect(env).toBeDefined();
34
+ expect(env?.MORPH_API_KEY).toBe('test-api-key-123');
35
+ });
36
+
37
+ it('should set ENABLED_TOOLS environment variable', () => {
38
+ const mcps = createBuiltinMcps();
39
+ const env = mcps.morph_mcp.environment;
40
+
41
+ expect(env).toBeDefined();
42
+ expect(env?.ENABLED_TOOLS).toBe('edit_file,warpgrep_codebase_search');
43
+ });
44
+
45
+ it('should only create morph_mcp key', () => {
46
+ const mcps = createBuiltinMcps();
47
+
48
+ expect(Object.keys(mcps)).toEqual(['morph_mcp']);
49
+ });
50
+ });
51
+ });
@@ -1,5 +1,5 @@
1
1
  import type { McpLocalConfig } from '@opencode-ai/sdk';
2
- import { API_KEY } from './const';
2
+ import { API_KEY } from '../shared/config';
3
3
 
4
4
  export function createBuiltinMcps(): Record<string, McpLocalConfig> {
5
5
  return {
@@ -0,0 +1,266 @@
1
+ import { describe, it, expect, vi } from 'bun:test';
2
+ import type { Part } from '@opencode-ai/sdk';
3
+
4
+ vi.mock('@morphllm/morphsdk', () => ({
5
+ MorphClient: vi.fn().mockImplementation(() => ({
6
+ routers: {
7
+ raw: {
8
+ classify: vi.fn(),
9
+ },
10
+ },
11
+ })),
12
+ }));
13
+
14
+ vi.mock('../shared/config', () => ({
15
+ API_KEY: 'sk-test-api-key-123',
16
+ MORPH_MODEL_EASY: 'easy/easy',
17
+ MORPH_MODEL_MEDIUM: 'medium/medium',
18
+ MORPH_MODEL_HARD: 'hard/hard',
19
+ MORPH_MODEL_DEFAULT: 'default/default',
20
+ MORPH_ROUTER_ONLY_FIRST_MESSAGE: false,
21
+ }));
22
+
23
+ import { createModelRouterHook, extractPromptText } from './router';
24
+
25
+ describe('router.ts', () => {
26
+ describe('extractPromptText', () => {
27
+ it('should extract text from parts', () => {
28
+ const parts: Part[] = [
29
+ { type: 'text', text: 'Hello' },
30
+ { type: 'text', text: 'World' },
31
+ ] as any;
32
+ expect(extractPromptText(parts)).toBe('Hello World');
33
+ });
34
+
35
+ it('should handle empty parts', () => {
36
+ const parts: Part[] = [];
37
+ expect(extractPromptText(parts)).toBe('');
38
+ });
39
+
40
+ it('should filter out non-text parts', () => {
41
+ const parts: Part[] = [
42
+ { type: 'text', text: 'Hello' },
43
+ { type: 'other', text: 'Ignore' },
44
+ { type: 'text', text: 'World' },
45
+ ] as any;
46
+ expect(extractPromptText(parts)).toBe('Hello World');
47
+ });
48
+
49
+ it('should handle parts with no text', () => {
50
+ const parts: Part[] = [
51
+ { type: 'text', text: 'Hello' },
52
+ { type: 'text' },
53
+ { type: 'text', text: 'World' },
54
+ ] as any;
55
+ expect(extractPromptText(parts)).toBe('Hello World');
56
+ });
57
+
58
+ it('should handle all non-text parts', () => {
59
+ const parts: Part[] = [
60
+ { type: 'image', data: 'base64...' },
61
+ { type: 'tool_use', name: 'bash' },
62
+ ] as any;
63
+ expect(extractPromptText(parts)).toBe('');
64
+ });
65
+ });
66
+
67
+ describe('createModelRouterHook', () => {
68
+ it('should return a chat.message hook', () => {
69
+ const hook = createModelRouterHook();
70
+ expect('chat.message' in hook).toBe(true);
71
+ expect(typeof hook['chat.message']).toBe('function');
72
+ });
73
+
74
+ it('should call the classifier with the correct input', async () => {
75
+ const hook = createModelRouterHook();
76
+ const classify = vi.fn().mockResolvedValue({ difficulty: 'easy' });
77
+ const input = {
78
+ sessionID: '123',
79
+ classify,
80
+ };
81
+ const output = {
82
+ message: {} as any,
83
+ parts: [{ type: 'text', text: 'test prompt' }],
84
+ } as any;
85
+ await hook['chat.message'](input as any, output);
86
+ expect(classify).toHaveBeenCalledWith({ input: 'test prompt' });
87
+ });
88
+
89
+ it('should assign the correct model based on difficulty', async () => {
90
+ const hook = createModelRouterHook();
91
+ const classify = vi.fn().mockResolvedValue({ difficulty: 'hard' });
92
+ const input = {
93
+ sessionID: '123',
94
+ classify,
95
+ };
96
+ const output = {
97
+ message: {} as any,
98
+ parts: [{ type: 'text', text: 'test prompt' }],
99
+ } as any;
100
+ await hook['chat.message'](input as any, output);
101
+ expect(input).toHaveProperty('model');
102
+ expect((input as any).model.providerID).toBe('hard');
103
+ expect((input as any).model.modelID).toBe('hard');
104
+ });
105
+
106
+ it('should use the default model if no difficulty is returned', async () => {
107
+ const hook = createModelRouterHook();
108
+ const classify = vi.fn().mockResolvedValue({});
109
+ const input = {
110
+ sessionID: '123',
111
+ classify,
112
+ };
113
+ const output = {
114
+ message: {} as any,
115
+ parts: [{ type: 'text', text: 'test prompt' }],
116
+ } as any;
117
+ await hook['chat.message'](input as any, output);
118
+ expect(input).toHaveProperty('model');
119
+ expect((input as any).model.providerID).toBe('default');
120
+ expect((input as any).model.modelID).toBe('default');
121
+ });
122
+
123
+ it('should use default model when router returns nothing', async () => {
124
+ const hook = createModelRouterHook();
125
+ const classify = vi.fn().mockResolvedValue({});
126
+ const input = {
127
+ sessionID: '123',
128
+ classify,
129
+ };
130
+ const output = {
131
+ message: {} as any,
132
+ parts: [{ type: 'text', text: 'test prompt' }],
133
+ } as any;
134
+ await hook['chat.message'](input as any, output);
135
+ expect(input).toHaveProperty('model');
136
+ expect((input as any).model.providerID).toBe('default');
137
+ expect((input as any).model.modelID).toBe('default');
138
+ });
139
+
140
+ it('should handle classifier throwing an error gracefully', async () => {
141
+ const hook = createModelRouterHook();
142
+ const classify = vi.fn().mockRejectedValue(new Error('API Error'));
143
+ const input = {
144
+ sessionID: '123',
145
+ classify,
146
+ };
147
+ const output = {
148
+ message: {} as any,
149
+ parts: [{ type: 'text', text: 'test prompt' }],
150
+ } as any;
151
+
152
+ await expect(hook['chat.message'](input as any, output)).rejects.toThrow(
153
+ 'API Error'
154
+ );
155
+ });
156
+
157
+ it('should handle classifier returning null', async () => {
158
+ const hook = createModelRouterHook();
159
+ const classify = vi.fn().mockResolvedValue(null);
160
+ const input = {
161
+ sessionID: '123',
162
+ classify,
163
+ };
164
+ const output = {
165
+ message: {} as any,
166
+ parts: [{ type: 'text', text: 'test prompt' }],
167
+ } as any;
168
+ await hook['chat.message'](input as any, output);
169
+ expect((input as any).model.providerID).toBe('default');
170
+ expect((input as any).model.modelID).toBe('default');
171
+ });
172
+
173
+ it('should handle classifier returning undefined difficulty', async () => {
174
+ const hook = createModelRouterHook();
175
+ const classify = vi.fn().mockResolvedValue({ difficulty: undefined });
176
+ const input = {
177
+ sessionID: '123',
178
+ classify,
179
+ };
180
+ const output = {
181
+ message: {} as any,
182
+ parts: [{ type: 'text', text: 'test prompt' }],
183
+ } as any;
184
+ await hook['chat.message'](input as any, output);
185
+ expect((input as any).model.providerID).toBe('default');
186
+ expect((input as any).model.modelID).toBe('default');
187
+ });
188
+
189
+ it('should default to default model for invalid difficulty values', async () => {
190
+ const hook = createModelRouterHook();
191
+ const classify = vi.fn().mockResolvedValue({ difficulty: 'ultra-hard' });
192
+ const input = {
193
+ sessionID: '123',
194
+ classify,
195
+ };
196
+ const output = {
197
+ message: {} as any,
198
+ parts: [{ type: 'text', text: 'test prompt' }],
199
+ } as any;
200
+ await hook['chat.message'](input as any, output);
201
+ expect((input as any).model.providerID).toBe('default');
202
+ expect((input as any).model.modelID).toBe('default');
203
+ });
204
+
205
+ it('should default to default model for empty string difficulty', async () => {
206
+ const hook = createModelRouterHook();
207
+ const classify = vi.fn().mockResolvedValue({ difficulty: '' });
208
+ const input = {
209
+ sessionID: '123',
210
+ classify,
211
+ };
212
+ const output = {
213
+ message: {} as any,
214
+ parts: [{ type: 'text', text: 'test prompt' }],
215
+ } as any;
216
+ await hook['chat.message'](input as any, output);
217
+ expect((input as any).model.providerID).toBe('default');
218
+ expect((input as any).model.modelID).toBe('default');
219
+ });
220
+
221
+ it('should handle case-insensitive difficulty matching', async () => {
222
+ const hook = createModelRouterHook();
223
+ const classify = vi.fn().mockResolvedValue({ difficulty: 'HARD' });
224
+ const input = {
225
+ sessionID: '123',
226
+ classify,
227
+ };
228
+ const output = {
229
+ message: {} as any,
230
+ parts: [{ type: 'text', text: 'test prompt' }],
231
+ } as any;
232
+ await hook['chat.message'](input as any, output);
233
+ expect((input as any).model.providerID).toBe('hard');
234
+ expect((input as any).model.modelID).toBe('hard');
235
+ });
236
+
237
+ it('should route all messages when MORPH_ROUTER_ONLY_FIRST_MESSAGE is disabled', async () => {
238
+ const hook = createModelRouterHook();
239
+ const classify = vi
240
+ .fn()
241
+ .mockResolvedValueOnce({ difficulty: 'hard' })
242
+ .mockResolvedValueOnce({ difficulty: 'easy' });
243
+
244
+ const sessionID = 'session-456';
245
+ const input1 = { sessionID, classify };
246
+ const output1 = {
247
+ message: {} as any,
248
+ parts: [{ type: 'text', text: 'first message' }],
249
+ } as any;
250
+
251
+ await hook['chat.message'](input1 as any, output1);
252
+ expect(classify).toHaveBeenCalledTimes(1);
253
+ expect((input1 as any).model.providerID).toBe('hard');
254
+
255
+ const input2 = { sessionID, classify };
256
+ const output2 = {
257
+ message: {} as any,
258
+ parts: [{ type: 'text', text: 'second message' }],
259
+ } as any;
260
+
261
+ await hook['chat.message'](input2 as any, output2);
262
+ expect(classify).toHaveBeenCalledTimes(2);
263
+ expect((input2 as any).model.providerID).toBe('easy');
264
+ });
265
+ });
266
+ });
@@ -6,7 +6,8 @@ import {
6
6
  MORPH_MODEL_MEDIUM,
7
7
  MORPH_MODEL_HARD,
8
8
  MORPH_MODEL_DEFAULT,
9
- } from './const';
9
+ MORPH_ROUTER_ONLY_FIRST_MESSAGE,
10
+ } from '../shared/config';
10
11
  import type { Part, UserMessage } from '@opencode-ai/sdk';
11
12
  import type {
12
13
  RouterInput,
@@ -14,7 +15,17 @@ import type {
14
15
  ComplexityLevel,
15
16
  } from '@morphllm/morphsdk';
16
17
 
17
- const morph = new MorphClient({ apiKey: API_KEY });
18
+ // Lazy initialization to allow mocking in tests
19
+ let morph: MorphClient | null = null;
20
+
21
+ const sessionsWithModelSelected = new Set<string>();
22
+
23
+ function getMorphClient(): MorphClient {
24
+ if (!morph) {
25
+ morph = new MorphClient({ apiKey: API_KEY });
26
+ }
27
+ return morph;
28
+ }
18
29
 
19
30
  function parseModel(s?: string): { providerID: string; modelID: string } {
20
31
  if (!s) return { providerID: '', modelID: '' };
@@ -54,11 +65,17 @@ export function createModelRouterHook() {
54
65
  ): Promise<void> => {
55
66
  input.model = input.model ?? { providerID: '', modelID: '' };
56
67
 
68
+ if (MORPH_ROUTER_ONLY_FIRST_MESSAGE) {
69
+ if (sessionsWithModelSelected.has(input.sessionID)) {
70
+ return;
71
+ }
72
+ }
73
+
57
74
  const promptText = extractPromptText(output.parts);
58
75
 
59
76
  const classifier =
60
77
  input.classify ??
61
- ((args: RouterInput) => morph.routers.raw.classify(args));
78
+ ((args: RouterInput) => getMorphClient().routers.raw.classify(args));
62
79
 
63
80
  const classification: RawRouterResult = await classifier({
64
81
  input: promptText,
@@ -69,12 +86,12 @@ export function createModelRouterHook() {
69
86
  const finalProviderID = chosen.providerID || input.model.providerID;
70
87
  const finalModelID = chosen.modelID || input.model.modelID;
71
88
 
72
- console.debug(
73
- `[Morph Router] Prompt classified as difficulty: ${classification?.difficulty}. Routing to model: ${finalProviderID}/${finalModelID}`
74
- );
75
-
76
89
  input.model.providerID = finalProviderID;
77
90
  input.model.modelID = finalModelID;
91
+
92
+ if (MORPH_ROUTER_ONLY_FIRST_MESSAGE) {
93
+ sessionsWithModelSelected.add(input.sessionID);
94
+ }
78
95
  },
79
96
  };
80
97
  }