@pixelbyte-software/pixcode 1.33.3 → 1.33.4
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/assets/{index-BrB-LHeY.js → index-D0qriZVb.js} +3 -3
- package/dist/index.html +1 -1
- package/dist-server/server/modules/providers/list/opencode/opencode-sessions.provider.js +14 -1
- package/dist-server/server/modules/providers/list/opencode/opencode-sessions.provider.js.map +1 -1
- package/dist-server/server/modules/providers/provider.routes.js +2 -1
- package/dist-server/server/modules/providers/provider.routes.js.map +1 -1
- package/package.json +178 -178
- package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +10 -1
- package/server/modules/providers/provider.routes.ts +2 -1
- package/server/opencode-cli.js +403 -403
- package/server/opencode-response-handler.js +92 -92
package/server/opencode-cli.js
CHANGED
|
@@ -1,403 +1,403 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* OpenCode CLI adapter.
|
|
3
|
-
*
|
|
4
|
-
* OpenCode (https://opencode.ai, npm package: `opencode-ai`, binary: `opencode`)
|
|
5
|
-
* is a multi-provider terminal coding agent. Unlike Claude/Codex/Gemini/Qwen it
|
|
6
|
-
* uses XDG paths (`~/.config/opencode/` for config, `~/.local/share/opencode/`
|
|
7
|
-
* for data) on Linux/macOS/Windows alike — the literal `~/.config` and
|
|
8
|
-
* `~/.local/share` folders under the user profile, NOT %APPDATA% on Windows.
|
|
9
|
-
*
|
|
10
|
-
* Headless invocation:
|
|
11
|
-
* opencode run \
|
|
12
|
-
* --agent <build|plan> # build (default) or plan (read-only) mode
|
|
13
|
-
* --model <provider/model> # e.g. anthropic/claude-sonnet-4-5
|
|
14
|
-
* --format json # NDJSON event stream
|
|
15
|
-
* [-s <id>] # resume a session by id
|
|
16
|
-
* [--dangerously-skip-permissions]
|
|
17
|
-
* -- "<prompt>"
|
|
18
|
-
*
|
|
19
|
-
* Mirrors the structure of qwen-code-cli.js so the dispatch path in
|
|
20
|
-
* server/index.js is uniform across all five spawn-based providers.
|
|
21
|
-
*/
|
|
22
|
-
import { spawn } from 'child_process';
|
|
23
|
-
import crossSpawn from 'cross-spawn';
|
|
24
|
-
import { promises as fs } from 'fs';
|
|
25
|
-
import path from 'path';
|
|
26
|
-
import os from 'os';
|
|
27
|
-
|
|
28
|
-
import sessionManager from './sessionManager.js';
|
|
29
|
-
import OpencodeResponseHandler from './opencode-response-handler.js';
|
|
30
|
-
import { notifyRunFailed, notifyRunStopped } from './services/notification-orchestrator.js';
|
|
31
|
-
import { buildSpawnEnv } from './services/provider-credentials.js';
|
|
32
|
-
import { providerAuthService } from './modules/providers/services/provider-auth.service.js';
|
|
33
|
-
import { createNormalizedMessage } from './shared/utils.js';
|
|
34
|
-
|
|
35
|
-
// `opencode.cmd` shim on Windows — cross-spawn handles the .cmd resolution.
|
|
36
|
-
const spawnFunction = process.platform === 'win32' ? crossSpawn : spawn;
|
|
37
|
-
|
|
38
|
-
const activeOpencodeProcesses = new Map();
|
|
39
|
-
|
|
40
|
-
function mapPermissionModeToArgs(permissionMode, skipPermissions) {
|
|
41
|
-
// OpenCode's permission model is per-tool/per-pattern (see opencode.json
|
|
42
|
-
// "permission" key). For chat-message routing we only need the high-level
|
|
43
|
-
// toggle: build (normal) vs plan (read-only) vs skip-everything.
|
|
44
|
-
if (skipPermissions || permissionMode === 'bypassPermissions' || permissionMode === 'acceptEdits') {
|
|
45
|
-
return { agent: 'build', dangerously: true };
|
|
46
|
-
}
|
|
47
|
-
if (permissionMode === 'plan') {
|
|
48
|
-
return { agent: 'plan', dangerously: false };
|
|
49
|
-
}
|
|
50
|
-
return { agent: 'build', dangerously: false };
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
async function spawnOpencode(command, options = {}, ws) {
|
|
54
|
-
const { sessionId, projectPath, cwd, toolsSettings, permissionMode, images, sessionSummary, agent: agentOverride } = options;
|
|
55
|
-
let capturedSessionId = sessionId;
|
|
56
|
-
let sessionCreatedSent = false;
|
|
57
|
-
let assistantBlocks = [];
|
|
58
|
-
|
|
59
|
-
const settings = toolsSettings || { allowedTools: [], disallowedTools: [], skipPermissions: false };
|
|
60
|
-
|
|
61
|
-
const safeSessionIdPattern = /^[a-zA-Z0-9_.\-:]+$/;
|
|
62
|
-
const args = ['run', '--format', 'json'];
|
|
63
|
-
|
|
64
|
-
const { agent, dangerously } = mapPermissionModeToArgs(permissionMode, settings.skipPermissions || options.skipPermissions);
|
|
65
|
-
const effectiveAgent = agentOverride || agent;
|
|
66
|
-
if (effectiveAgent) {
|
|
67
|
-
args.push('--agent', effectiveAgent);
|
|
68
|
-
}
|
|
69
|
-
if (dangerously) {
|
|
70
|
-
args.push('--dangerously-skip-permissions');
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
if (sessionId) {
|
|
74
|
-
const session = sessionManager.getSession(sessionId);
|
|
75
|
-
const cliId = session?.cliSessionId || sessionId;
|
|
76
|
-
if (cliId && safeSessionIdPattern.test(cliId)) {
|
|
77
|
-
args.push('-s', cliId);
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
const modelToUse = options.model;
|
|
82
|
-
if (modelToUse) {
|
|
83
|
-
args.push('--model', modelToUse);
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
const cleanPath = (cwd || projectPath || process.cwd()).replace(/[^\x20-\x7E]/g, '').trim();
|
|
87
|
-
const workingDir = cleanPath;
|
|
88
|
-
|
|
89
|
-
// Image attachments: OpenCode accepts repeated `-f <path>` flags. We dump
|
|
90
|
-
// base64 attachments to a tmp dir under the project root and pass each path.
|
|
91
|
-
const tempImagePaths = [];
|
|
92
|
-
let tempDir = null;
|
|
93
|
-
if (images && images.length > 0) {
|
|
94
|
-
try {
|
|
95
|
-
tempDir = path.join(workingDir, '.tmp', 'opencode-images', Date.now().toString());
|
|
96
|
-
await fs.mkdir(tempDir, { recursive: true });
|
|
97
|
-
|
|
98
|
-
for (const [index, image] of images.entries()) {
|
|
99
|
-
const matches = image.data.match(/^data:([^;]+);base64,(.+)$/);
|
|
100
|
-
if (!matches) continue;
|
|
101
|
-
const [, mimeType, base64Data] = matches;
|
|
102
|
-
const extension = mimeType.split('/')[1] || 'png';
|
|
103
|
-
const filename = `image_${index}.${extension}`;
|
|
104
|
-
const filepath = path.join(tempDir, filename);
|
|
105
|
-
await fs.writeFile(filepath, Buffer.from(base64Data, 'base64'));
|
|
106
|
-
tempImagePaths.push(filepath);
|
|
107
|
-
args.push('-f', filepath);
|
|
108
|
-
}
|
|
109
|
-
} catch (error) {
|
|
110
|
-
console.error('Error processing images for OpenCode:', error);
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
// Prompt is the trailing positional. Use `--` to be safe against prompts
|
|
115
|
-
// that start with a `-`.
|
|
116
|
-
if (command && command.trim()) {
|
|
117
|
-
args.push('--', command);
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
// OPENCODE_CLI_PATH is exported by primeCliBinPath() during boot. Falls
|
|
121
|
-
// back to the bare binary name (resolved via PATH) when unset.
|
|
122
|
-
const opencodePath = process.env.OPENCODE_CLI_PATH || 'opencode';
|
|
123
|
-
console.log('Spawning OpenCode CLI:', opencodePath, args.join(' '));
|
|
124
|
-
console.log('Working directory:', workingDir);
|
|
125
|
-
|
|
126
|
-
let spawnCmd = opencodePath;
|
|
127
|
-
let spawnArgs = args;
|
|
128
|
-
|
|
129
|
-
if (os.platform() !== 'win32') {
|
|
130
|
-
// Force `exec` so the child replaces the wrapper shell — keeps SIGTERM
|
|
131
|
-
// delivery clean when we abort the session. Same trick as qwen-cli.
|
|
132
|
-
spawnCmd = 'sh';
|
|
133
|
-
spawnArgs = ['-c', 'exec "$0" "$@"', opencodePath, ...args];
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
const spawnEnv = await buildSpawnEnv('opencode');
|
|
137
|
-
|
|
138
|
-
return new Promise((resolve, reject) => {
|
|
139
|
-
const opencodeProcess = spawnFunction(spawnCmd, spawnArgs, {
|
|
140
|
-
cwd: workingDir,
|
|
141
|
-
stdio: ['pipe', 'pipe', 'pipe'],
|
|
142
|
-
env: spawnEnv,
|
|
143
|
-
});
|
|
144
|
-
|
|
145
|
-
let terminalNotificationSent = false;
|
|
146
|
-
let terminalFailureReason = null;
|
|
147
|
-
|
|
148
|
-
const notifyTerminalState = ({ code = null, error = null } = {}) => {
|
|
149
|
-
if (terminalNotificationSent) return;
|
|
150
|
-
terminalNotificationSent = true;
|
|
151
|
-
|
|
152
|
-
const finalSessionId = capturedSessionId || sessionId || processKey;
|
|
153
|
-
if (code === 0 && !error) {
|
|
154
|
-
notifyRunStopped({
|
|
155
|
-
userId: ws?.userId || null,
|
|
156
|
-
provider: 'opencode',
|
|
157
|
-
sessionId: finalSessionId,
|
|
158
|
-
sessionName: sessionSummary,
|
|
159
|
-
stopReason: 'completed',
|
|
160
|
-
});
|
|
161
|
-
return;
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
notifyRunFailed({
|
|
165
|
-
userId: ws?.userId || null,
|
|
166
|
-
provider: 'opencode',
|
|
167
|
-
sessionId: finalSessionId,
|
|
168
|
-
sessionName: sessionSummary,
|
|
169
|
-
error: error || terminalFailureReason || `OpenCode CLI exited with code ${code}`,
|
|
170
|
-
});
|
|
171
|
-
};
|
|
172
|
-
|
|
173
|
-
opencodeProcess.tempImagePaths = tempImagePaths;
|
|
174
|
-
opencodeProcess.tempDir = tempDir;
|
|
175
|
-
|
|
176
|
-
const processKey = capturedSessionId || sessionId || `opencode_${Date.now()}`;
|
|
177
|
-
activeOpencodeProcesses.set(processKey, opencodeProcess);
|
|
178
|
-
opencodeProcess.sessionId = processKey;
|
|
179
|
-
|
|
180
|
-
opencodeProcess.stdin.end();
|
|
181
|
-
|
|
182
|
-
const timeoutMs = 120000;
|
|
183
|
-
let timeout;
|
|
184
|
-
const startTimeout = () => {
|
|
185
|
-
if (timeout) clearTimeout(timeout);
|
|
186
|
-
timeout = setTimeout(() => {
|
|
187
|
-
const socketSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : (capturedSessionId || sessionId || processKey);
|
|
188
|
-
terminalFailureReason = `OpenCode CLI timeout - no response received for ${timeoutMs / 1000} seconds`;
|
|
189
|
-
ws.send(createNormalizedMessage({ kind: 'error', content: terminalFailureReason, sessionId: socketSessionId, provider: 'opencode' }));
|
|
190
|
-
try { opencodeProcess.kill('SIGTERM'); } catch { /* noop */ }
|
|
191
|
-
}, timeoutMs);
|
|
192
|
-
};
|
|
193
|
-
startTimeout();
|
|
194
|
-
|
|
195
|
-
if (command && capturedSessionId) {
|
|
196
|
-
sessionManager.addMessage(capturedSessionId, 'user', command);
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
let responseHandler;
|
|
200
|
-
if (ws) {
|
|
201
|
-
responseHandler = new OpencodeResponseHandler(ws, {
|
|
202
|
-
onContentFragment: (content) => {
|
|
203
|
-
if (assistantBlocks.length > 0 && assistantBlocks[assistantBlocks.length - 1].type === 'text') {
|
|
204
|
-
assistantBlocks[assistantBlocks.length - 1].text += content;
|
|
205
|
-
} else {
|
|
206
|
-
assistantBlocks.push({ type: 'text', text: content });
|
|
207
|
-
}
|
|
208
|
-
},
|
|
209
|
-
onToolUse: (event) => {
|
|
210
|
-
assistantBlocks.push({
|
|
211
|
-
type: 'tool_use',
|
|
212
|
-
id: event.tool_id,
|
|
213
|
-
name: event.tool_name,
|
|
214
|
-
input: event.parameters,
|
|
215
|
-
});
|
|
216
|
-
},
|
|
217
|
-
onToolResult: (event) => {
|
|
218
|
-
if (capturedSessionId) {
|
|
219
|
-
if (assistantBlocks.length > 0) {
|
|
220
|
-
sessionManager.addMessage(capturedSessionId, 'assistant', [...assistantBlocks]);
|
|
221
|
-
assistantBlocks = [];
|
|
222
|
-
}
|
|
223
|
-
sessionManager.addMessage(capturedSessionId, 'user', [{
|
|
224
|
-
type: 'tool_result',
|
|
225
|
-
tool_use_id: event.tool_id,
|
|
226
|
-
content: event.output === undefined ? null : event.output,
|
|
227
|
-
is_error: event.status === 'error',
|
|
228
|
-
}]);
|
|
229
|
-
}
|
|
230
|
-
},
|
|
231
|
-
onInit: (event) => {
|
|
232
|
-
if (capturedSessionId) {
|
|
233
|
-
const sess = sessionManager.getSession(capturedSessionId);
|
|
234
|
-
if (sess && !sess.cliSessionId) {
|
|
235
|
-
sess.cliSessionId = event.session_id;
|
|
236
|
-
sessionManager.saveSession(capturedSessionId);
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
},
|
|
240
|
-
});
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
opencodeProcess.stdout.on('data', (data) => {
|
|
244
|
-
const rawOutput = data.toString();
|
|
245
|
-
startTimeout();
|
|
246
|
-
|
|
247
|
-
if (!sessionId && !sessionCreatedSent && !capturedSessionId) {
|
|
248
|
-
capturedSessionId = `opencode_${Date.now()}`;
|
|
249
|
-
sessionCreatedSent = true;
|
|
250
|
-
|
|
251
|
-
sessionManager.createSession(capturedSessionId, cwd || process.cwd());
|
|
252
|
-
if (command) {
|
|
253
|
-
sessionManager.addMessage(capturedSessionId, 'user', command);
|
|
254
|
-
}
|
|
255
|
-
if (processKey !== capturedSessionId) {
|
|
256
|
-
activeOpencodeProcesses.delete(processKey);
|
|
257
|
-
activeOpencodeProcesses.set(capturedSessionId, opencodeProcess);
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
ws.setSessionId && typeof ws.setSessionId === 'function' && ws.setSessionId(capturedSessionId);
|
|
261
|
-
ws.send(createNormalizedMessage({ kind: 'session_created', newSessionId: capturedSessionId, sessionId: capturedSessionId, provider: 'opencode' }));
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
if (responseHandler) {
|
|
265
|
-
responseHandler.processData(rawOutput);
|
|
266
|
-
} else if (rawOutput) {
|
|
267
|
-
if (assistantBlocks.length > 0 && assistantBlocks[assistantBlocks.length - 1].type === 'text') {
|
|
268
|
-
assistantBlocks[assistantBlocks.length - 1].text += rawOutput;
|
|
269
|
-
} else {
|
|
270
|
-
assistantBlocks.push({ type: 'text', text: rawOutput });
|
|
271
|
-
}
|
|
272
|
-
const socketSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : (capturedSessionId || sessionId);
|
|
273
|
-
ws.send(createNormalizedMessage({ kind: 'stream_delta', content: rawOutput, sessionId: socketSessionId, provider: 'opencode' }));
|
|
274
|
-
}
|
|
275
|
-
});
|
|
276
|
-
|
|
277
|
-
opencodeProcess.stderr.on('data', (data) => {
|
|
278
|
-
const errorMsg = data.toString();
|
|
279
|
-
// Suppress known cosmetic noise.
|
|
280
|
-
if (errorMsg.includes('[DEP0040]') ||
|
|
281
|
-
errorMsg.includes('DeprecationWarning') ||
|
|
282
|
-
errorMsg.includes('--trace-deprecation') ||
|
|
283
|
-
errorMsg.includes('punycode')) {
|
|
284
|
-
return;
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
const socketSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : (capturedSessionId || sessionId);
|
|
288
|
-
ws.send(createNormalizedMessage({ kind: 'error', content: errorMsg, sessionId: socketSessionId, provider: 'opencode' }));
|
|
289
|
-
});
|
|
290
|
-
|
|
291
|
-
opencodeProcess.on('close', async (code) => {
|
|
292
|
-
clearTimeout(timeout);
|
|
293
|
-
|
|
294
|
-
if (responseHandler) {
|
|
295
|
-
responseHandler.forceFlush();
|
|
296
|
-
responseHandler.destroy();
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
const finalSessionId = capturedSessionId || sessionId || processKey;
|
|
300
|
-
activeOpencodeProcesses.delete(finalSessionId);
|
|
301
|
-
|
|
302
|
-
if (finalSessionId && assistantBlocks.length > 0) {
|
|
303
|
-
sessionManager.addMessage(finalSessionId, 'assistant', assistantBlocks);
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
ws.send(createNormalizedMessage({ kind: 'complete', exitCode: code, isNewSession: !sessionId && !!command, sessionId: finalSessionId, provider: 'opencode' }));
|
|
307
|
-
|
|
308
|
-
if (opencodeProcess.tempImagePaths && opencodeProcess.tempImagePaths.length > 0) {
|
|
309
|
-
for (const imagePath of opencodeProcess.tempImagePaths) {
|
|
310
|
-
await fs.unlink(imagePath).catch(() => { /* noop */ });
|
|
311
|
-
}
|
|
312
|
-
if (opencodeProcess.tempDir) {
|
|
313
|
-
await fs.rm(opencodeProcess.tempDir, { recursive: true, force: true }).catch(() => { /* noop */ });
|
|
314
|
-
}
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
if (code === 0) {
|
|
318
|
-
notifyTerminalState({ code });
|
|
319
|
-
resolve();
|
|
320
|
-
} else {
|
|
321
|
-
if (code === 127) {
|
|
322
|
-
const installed = await providerAuthService.isProviderInstalled('opencode');
|
|
323
|
-
if (!installed) {
|
|
324
|
-
const socketSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : finalSessionId;
|
|
325
|
-
ws.send(createNormalizedMessage({
|
|
326
|
-
kind: 'error',
|
|
327
|
-
content: 'OpenCode CLI is not installed. Install it from the Settings → Agents → OpenCode tab, or run: npm install -g opencode-ai',
|
|
328
|
-
sessionId: socketSessionId,
|
|
329
|
-
provider: 'opencode',
|
|
330
|
-
}));
|
|
331
|
-
}
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
notifyTerminalState({
|
|
335
|
-
code,
|
|
336
|
-
error: code === null ? 'OpenCode CLI process was terminated or timed out' : null,
|
|
337
|
-
});
|
|
338
|
-
reject(new Error(code === null ? 'OpenCode CLI process was terminated or timed out' : `OpenCode CLI exited with code ${code}`));
|
|
339
|
-
}
|
|
340
|
-
});
|
|
341
|
-
|
|
342
|
-
opencodeProcess.on('error', async (error) => {
|
|
343
|
-
const finalSessionId = capturedSessionId || sessionId || processKey;
|
|
344
|
-
activeOpencodeProcesses.delete(finalSessionId);
|
|
345
|
-
|
|
346
|
-
const installed = await providerAuthService.isProviderInstalled('opencode');
|
|
347
|
-
const errorContent = !installed
|
|
348
|
-
? 'OpenCode CLI is not installed. Install it from the Settings → Agents → OpenCode tab, or run: npm install -g opencode-ai'
|
|
349
|
-
: error.message;
|
|
350
|
-
|
|
351
|
-
const errorSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : finalSessionId;
|
|
352
|
-
ws.send(createNormalizedMessage({ kind: 'error', content: errorContent, sessionId: errorSessionId, provider: 'opencode' }));
|
|
353
|
-
notifyTerminalState({ error });
|
|
354
|
-
|
|
355
|
-
reject(error);
|
|
356
|
-
});
|
|
357
|
-
});
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
function abortOpencodeSession(sessionId) {
|
|
361
|
-
let opencodeProc = activeOpencodeProcesses.get(sessionId);
|
|
362
|
-
let processKey = sessionId;
|
|
363
|
-
|
|
364
|
-
if (!opencodeProc) {
|
|
365
|
-
for (const [key, proc] of activeOpencodeProcesses.entries()) {
|
|
366
|
-
if (proc.sessionId === sessionId) {
|
|
367
|
-
opencodeProc = proc;
|
|
368
|
-
processKey = key;
|
|
369
|
-
break;
|
|
370
|
-
}
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
if (opencodeProc) {
|
|
375
|
-
try {
|
|
376
|
-
opencodeProc.kill('SIGTERM');
|
|
377
|
-
setTimeout(() => {
|
|
378
|
-
if (activeOpencodeProcesses.has(processKey)) {
|
|
379
|
-
try { opencodeProc.kill('SIGKILL'); } catch { /* noop */ }
|
|
380
|
-
}
|
|
381
|
-
}, 2000);
|
|
382
|
-
return true;
|
|
383
|
-
} catch {
|
|
384
|
-
return false;
|
|
385
|
-
}
|
|
386
|
-
}
|
|
387
|
-
return false;
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
function isOpencodeSessionActive(sessionId) {
|
|
391
|
-
return activeOpencodeProcesses.has(sessionId);
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
function getActiveOpencodeSessions() {
|
|
395
|
-
return Array.from(activeOpencodeProcesses.keys());
|
|
396
|
-
}
|
|
397
|
-
|
|
398
|
-
export {
|
|
399
|
-
spawnOpencode,
|
|
400
|
-
abortOpencodeSession,
|
|
401
|
-
isOpencodeSessionActive,
|
|
402
|
-
getActiveOpencodeSessions,
|
|
403
|
-
};
|
|
1
|
+
/**
|
|
2
|
+
* OpenCode CLI adapter.
|
|
3
|
+
*
|
|
4
|
+
* OpenCode (https://opencode.ai, npm package: `opencode-ai`, binary: `opencode`)
|
|
5
|
+
* is a multi-provider terminal coding agent. Unlike Claude/Codex/Gemini/Qwen it
|
|
6
|
+
* uses XDG paths (`~/.config/opencode/` for config, `~/.local/share/opencode/`
|
|
7
|
+
* for data) on Linux/macOS/Windows alike — the literal `~/.config` and
|
|
8
|
+
* `~/.local/share` folders under the user profile, NOT %APPDATA% on Windows.
|
|
9
|
+
*
|
|
10
|
+
* Headless invocation:
|
|
11
|
+
* opencode run \
|
|
12
|
+
* --agent <build|plan> # build (default) or plan (read-only) mode
|
|
13
|
+
* --model <provider/model> # e.g. anthropic/claude-sonnet-4-5
|
|
14
|
+
* --format json # NDJSON event stream
|
|
15
|
+
* [-s <id>] # resume a session by id
|
|
16
|
+
* [--dangerously-skip-permissions]
|
|
17
|
+
* -- "<prompt>"
|
|
18
|
+
*
|
|
19
|
+
* Mirrors the structure of qwen-code-cli.js so the dispatch path in
|
|
20
|
+
* server/index.js is uniform across all five spawn-based providers.
|
|
21
|
+
*/
|
|
22
|
+
import { spawn } from 'child_process';
|
|
23
|
+
import crossSpawn from 'cross-spawn';
|
|
24
|
+
import { promises as fs } from 'fs';
|
|
25
|
+
import path from 'path';
|
|
26
|
+
import os from 'os';
|
|
27
|
+
|
|
28
|
+
import sessionManager from './sessionManager.js';
|
|
29
|
+
import OpencodeResponseHandler from './opencode-response-handler.js';
|
|
30
|
+
import { notifyRunFailed, notifyRunStopped } from './services/notification-orchestrator.js';
|
|
31
|
+
import { buildSpawnEnv } from './services/provider-credentials.js';
|
|
32
|
+
import { providerAuthService } from './modules/providers/services/provider-auth.service.js';
|
|
33
|
+
import { createNormalizedMessage } from './shared/utils.js';
|
|
34
|
+
|
|
35
|
+
// `opencode.cmd` shim on Windows — cross-spawn handles the .cmd resolution.
|
|
36
|
+
const spawnFunction = process.platform === 'win32' ? crossSpawn : spawn;
|
|
37
|
+
|
|
38
|
+
const activeOpencodeProcesses = new Map();
|
|
39
|
+
|
|
40
|
+
function mapPermissionModeToArgs(permissionMode, skipPermissions) {
|
|
41
|
+
// OpenCode's permission model is per-tool/per-pattern (see opencode.json
|
|
42
|
+
// "permission" key). For chat-message routing we only need the high-level
|
|
43
|
+
// toggle: build (normal) vs plan (read-only) vs skip-everything.
|
|
44
|
+
if (skipPermissions || permissionMode === 'bypassPermissions' || permissionMode === 'acceptEdits') {
|
|
45
|
+
return { agent: 'build', dangerously: true };
|
|
46
|
+
}
|
|
47
|
+
if (permissionMode === 'plan') {
|
|
48
|
+
return { agent: 'plan', dangerously: false };
|
|
49
|
+
}
|
|
50
|
+
return { agent: 'build', dangerously: false };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function spawnOpencode(command, options = {}, ws) {
|
|
54
|
+
const { sessionId, projectPath, cwd, toolsSettings, permissionMode, images, sessionSummary, agent: agentOverride } = options;
|
|
55
|
+
let capturedSessionId = sessionId;
|
|
56
|
+
let sessionCreatedSent = false;
|
|
57
|
+
let assistantBlocks = [];
|
|
58
|
+
|
|
59
|
+
const settings = toolsSettings || { allowedTools: [], disallowedTools: [], skipPermissions: false };
|
|
60
|
+
|
|
61
|
+
const safeSessionIdPattern = /^[a-zA-Z0-9_.\-:]+$/;
|
|
62
|
+
const args = ['run', '--format', 'json'];
|
|
63
|
+
|
|
64
|
+
const { agent, dangerously } = mapPermissionModeToArgs(permissionMode, settings.skipPermissions || options.skipPermissions);
|
|
65
|
+
const effectiveAgent = agentOverride || agent;
|
|
66
|
+
if (effectiveAgent) {
|
|
67
|
+
args.push('--agent', effectiveAgent);
|
|
68
|
+
}
|
|
69
|
+
if (dangerously) {
|
|
70
|
+
args.push('--dangerously-skip-permissions');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
if (sessionId) {
|
|
74
|
+
const session = sessionManager.getSession(sessionId);
|
|
75
|
+
const cliId = session?.cliSessionId || sessionId;
|
|
76
|
+
if (cliId && safeSessionIdPattern.test(cliId)) {
|
|
77
|
+
args.push('-s', cliId);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const modelToUse = options.model;
|
|
82
|
+
if (modelToUse) {
|
|
83
|
+
args.push('--model', modelToUse);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const cleanPath = (cwd || projectPath || process.cwd()).replace(/[^\x20-\x7E]/g, '').trim();
|
|
87
|
+
const workingDir = cleanPath;
|
|
88
|
+
|
|
89
|
+
// Image attachments: OpenCode accepts repeated `-f <path>` flags. We dump
|
|
90
|
+
// base64 attachments to a tmp dir under the project root and pass each path.
|
|
91
|
+
const tempImagePaths = [];
|
|
92
|
+
let tempDir = null;
|
|
93
|
+
if (images && images.length > 0) {
|
|
94
|
+
try {
|
|
95
|
+
tempDir = path.join(workingDir, '.tmp', 'opencode-images', Date.now().toString());
|
|
96
|
+
await fs.mkdir(tempDir, { recursive: true });
|
|
97
|
+
|
|
98
|
+
for (const [index, image] of images.entries()) {
|
|
99
|
+
const matches = image.data.match(/^data:([^;]+);base64,(.+)$/);
|
|
100
|
+
if (!matches) continue;
|
|
101
|
+
const [, mimeType, base64Data] = matches;
|
|
102
|
+
const extension = mimeType.split('/')[1] || 'png';
|
|
103
|
+
const filename = `image_${index}.${extension}`;
|
|
104
|
+
const filepath = path.join(tempDir, filename);
|
|
105
|
+
await fs.writeFile(filepath, Buffer.from(base64Data, 'base64'));
|
|
106
|
+
tempImagePaths.push(filepath);
|
|
107
|
+
args.push('-f', filepath);
|
|
108
|
+
}
|
|
109
|
+
} catch (error) {
|
|
110
|
+
console.error('Error processing images for OpenCode:', error);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Prompt is the trailing positional. Use `--` to be safe against prompts
|
|
115
|
+
// that start with a `-`.
|
|
116
|
+
if (command && command.trim()) {
|
|
117
|
+
args.push('--', command);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// OPENCODE_CLI_PATH is exported by primeCliBinPath() during boot. Falls
|
|
121
|
+
// back to the bare binary name (resolved via PATH) when unset.
|
|
122
|
+
const opencodePath = process.env.OPENCODE_CLI_PATH || 'opencode';
|
|
123
|
+
console.log('Spawning OpenCode CLI:', opencodePath, args.join(' '));
|
|
124
|
+
console.log('Working directory:', workingDir);
|
|
125
|
+
|
|
126
|
+
let spawnCmd = opencodePath;
|
|
127
|
+
let spawnArgs = args;
|
|
128
|
+
|
|
129
|
+
if (os.platform() !== 'win32') {
|
|
130
|
+
// Force `exec` so the child replaces the wrapper shell — keeps SIGTERM
|
|
131
|
+
// delivery clean when we abort the session. Same trick as qwen-cli.
|
|
132
|
+
spawnCmd = 'sh';
|
|
133
|
+
spawnArgs = ['-c', 'exec "$0" "$@"', opencodePath, ...args];
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const spawnEnv = await buildSpawnEnv('opencode');
|
|
137
|
+
|
|
138
|
+
return new Promise((resolve, reject) => {
|
|
139
|
+
const opencodeProcess = spawnFunction(spawnCmd, spawnArgs, {
|
|
140
|
+
cwd: workingDir,
|
|
141
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
142
|
+
env: spawnEnv,
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
let terminalNotificationSent = false;
|
|
146
|
+
let terminalFailureReason = null;
|
|
147
|
+
|
|
148
|
+
const notifyTerminalState = ({ code = null, error = null } = {}) => {
|
|
149
|
+
if (terminalNotificationSent) return;
|
|
150
|
+
terminalNotificationSent = true;
|
|
151
|
+
|
|
152
|
+
const finalSessionId = capturedSessionId || sessionId || processKey;
|
|
153
|
+
if (code === 0 && !error) {
|
|
154
|
+
notifyRunStopped({
|
|
155
|
+
userId: ws?.userId || null,
|
|
156
|
+
provider: 'opencode',
|
|
157
|
+
sessionId: finalSessionId,
|
|
158
|
+
sessionName: sessionSummary,
|
|
159
|
+
stopReason: 'completed',
|
|
160
|
+
});
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
notifyRunFailed({
|
|
165
|
+
userId: ws?.userId || null,
|
|
166
|
+
provider: 'opencode',
|
|
167
|
+
sessionId: finalSessionId,
|
|
168
|
+
sessionName: sessionSummary,
|
|
169
|
+
error: error || terminalFailureReason || `OpenCode CLI exited with code ${code}`,
|
|
170
|
+
});
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
opencodeProcess.tempImagePaths = tempImagePaths;
|
|
174
|
+
opencodeProcess.tempDir = tempDir;
|
|
175
|
+
|
|
176
|
+
const processKey = capturedSessionId || sessionId || `opencode_${Date.now()}`;
|
|
177
|
+
activeOpencodeProcesses.set(processKey, opencodeProcess);
|
|
178
|
+
opencodeProcess.sessionId = processKey;
|
|
179
|
+
|
|
180
|
+
opencodeProcess.stdin.end();
|
|
181
|
+
|
|
182
|
+
const timeoutMs = 120000;
|
|
183
|
+
let timeout;
|
|
184
|
+
const startTimeout = () => {
|
|
185
|
+
if (timeout) clearTimeout(timeout);
|
|
186
|
+
timeout = setTimeout(() => {
|
|
187
|
+
const socketSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : (capturedSessionId || sessionId || processKey);
|
|
188
|
+
terminalFailureReason = `OpenCode CLI timeout - no response received for ${timeoutMs / 1000} seconds`;
|
|
189
|
+
ws.send(createNormalizedMessage({ kind: 'error', content: terminalFailureReason, sessionId: socketSessionId, provider: 'opencode' }));
|
|
190
|
+
try { opencodeProcess.kill('SIGTERM'); } catch { /* noop */ }
|
|
191
|
+
}, timeoutMs);
|
|
192
|
+
};
|
|
193
|
+
startTimeout();
|
|
194
|
+
|
|
195
|
+
if (command && capturedSessionId) {
|
|
196
|
+
sessionManager.addMessage(capturedSessionId, 'user', command);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
let responseHandler;
|
|
200
|
+
if (ws) {
|
|
201
|
+
responseHandler = new OpencodeResponseHandler(ws, {
|
|
202
|
+
onContentFragment: (content) => {
|
|
203
|
+
if (assistantBlocks.length > 0 && assistantBlocks[assistantBlocks.length - 1].type === 'text') {
|
|
204
|
+
assistantBlocks[assistantBlocks.length - 1].text += content;
|
|
205
|
+
} else {
|
|
206
|
+
assistantBlocks.push({ type: 'text', text: content });
|
|
207
|
+
}
|
|
208
|
+
},
|
|
209
|
+
onToolUse: (event) => {
|
|
210
|
+
assistantBlocks.push({
|
|
211
|
+
type: 'tool_use',
|
|
212
|
+
id: event.tool_id,
|
|
213
|
+
name: event.tool_name,
|
|
214
|
+
input: event.parameters,
|
|
215
|
+
});
|
|
216
|
+
},
|
|
217
|
+
onToolResult: (event) => {
|
|
218
|
+
if (capturedSessionId) {
|
|
219
|
+
if (assistantBlocks.length > 0) {
|
|
220
|
+
sessionManager.addMessage(capturedSessionId, 'assistant', [...assistantBlocks]);
|
|
221
|
+
assistantBlocks = [];
|
|
222
|
+
}
|
|
223
|
+
sessionManager.addMessage(capturedSessionId, 'user', [{
|
|
224
|
+
type: 'tool_result',
|
|
225
|
+
tool_use_id: event.tool_id,
|
|
226
|
+
content: event.output === undefined ? null : event.output,
|
|
227
|
+
is_error: event.status === 'error',
|
|
228
|
+
}]);
|
|
229
|
+
}
|
|
230
|
+
},
|
|
231
|
+
onInit: (event) => {
|
|
232
|
+
if (capturedSessionId) {
|
|
233
|
+
const sess = sessionManager.getSession(capturedSessionId);
|
|
234
|
+
if (sess && !sess.cliSessionId) {
|
|
235
|
+
sess.cliSessionId = event.session_id;
|
|
236
|
+
sessionManager.saveSession(capturedSessionId);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
},
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
opencodeProcess.stdout.on('data', (data) => {
|
|
244
|
+
const rawOutput = data.toString();
|
|
245
|
+
startTimeout();
|
|
246
|
+
|
|
247
|
+
if (!sessionId && !sessionCreatedSent && !capturedSessionId) {
|
|
248
|
+
capturedSessionId = `opencode_${Date.now()}`;
|
|
249
|
+
sessionCreatedSent = true;
|
|
250
|
+
|
|
251
|
+
sessionManager.createSession(capturedSessionId, cwd || process.cwd());
|
|
252
|
+
if (command) {
|
|
253
|
+
sessionManager.addMessage(capturedSessionId, 'user', command);
|
|
254
|
+
}
|
|
255
|
+
if (processKey !== capturedSessionId) {
|
|
256
|
+
activeOpencodeProcesses.delete(processKey);
|
|
257
|
+
activeOpencodeProcesses.set(capturedSessionId, opencodeProcess);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
ws.setSessionId && typeof ws.setSessionId === 'function' && ws.setSessionId(capturedSessionId);
|
|
261
|
+
ws.send(createNormalizedMessage({ kind: 'session_created', newSessionId: capturedSessionId, sessionId: capturedSessionId, provider: 'opencode' }));
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
if (responseHandler) {
|
|
265
|
+
responseHandler.processData(rawOutput);
|
|
266
|
+
} else if (rawOutput) {
|
|
267
|
+
if (assistantBlocks.length > 0 && assistantBlocks[assistantBlocks.length - 1].type === 'text') {
|
|
268
|
+
assistantBlocks[assistantBlocks.length - 1].text += rawOutput;
|
|
269
|
+
} else {
|
|
270
|
+
assistantBlocks.push({ type: 'text', text: rawOutput });
|
|
271
|
+
}
|
|
272
|
+
const socketSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : (capturedSessionId || sessionId);
|
|
273
|
+
ws.send(createNormalizedMessage({ kind: 'stream_delta', content: rawOutput, sessionId: socketSessionId, provider: 'opencode' }));
|
|
274
|
+
}
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
opencodeProcess.stderr.on('data', (data) => {
|
|
278
|
+
const errorMsg = data.toString();
|
|
279
|
+
// Suppress known cosmetic noise.
|
|
280
|
+
if (errorMsg.includes('[DEP0040]') ||
|
|
281
|
+
errorMsg.includes('DeprecationWarning') ||
|
|
282
|
+
errorMsg.includes('--trace-deprecation') ||
|
|
283
|
+
errorMsg.includes('punycode')) {
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const socketSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : (capturedSessionId || sessionId);
|
|
288
|
+
ws.send(createNormalizedMessage({ kind: 'error', content: errorMsg, sessionId: socketSessionId, provider: 'opencode' }));
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
opencodeProcess.on('close', async (code) => {
|
|
292
|
+
clearTimeout(timeout);
|
|
293
|
+
|
|
294
|
+
if (responseHandler) {
|
|
295
|
+
responseHandler.forceFlush();
|
|
296
|
+
responseHandler.destroy();
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const finalSessionId = capturedSessionId || sessionId || processKey;
|
|
300
|
+
activeOpencodeProcesses.delete(finalSessionId);
|
|
301
|
+
|
|
302
|
+
if (finalSessionId && assistantBlocks.length > 0) {
|
|
303
|
+
sessionManager.addMessage(finalSessionId, 'assistant', assistantBlocks);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
ws.send(createNormalizedMessage({ kind: 'complete', exitCode: code, isNewSession: !sessionId && !!command, sessionId: finalSessionId, provider: 'opencode' }));
|
|
307
|
+
|
|
308
|
+
if (opencodeProcess.tempImagePaths && opencodeProcess.tempImagePaths.length > 0) {
|
|
309
|
+
for (const imagePath of opencodeProcess.tempImagePaths) {
|
|
310
|
+
await fs.unlink(imagePath).catch(() => { /* noop */ });
|
|
311
|
+
}
|
|
312
|
+
if (opencodeProcess.tempDir) {
|
|
313
|
+
await fs.rm(opencodeProcess.tempDir, { recursive: true, force: true }).catch(() => { /* noop */ });
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
if (code === 0) {
|
|
318
|
+
notifyTerminalState({ code });
|
|
319
|
+
resolve();
|
|
320
|
+
} else {
|
|
321
|
+
if (code === 127) {
|
|
322
|
+
const installed = await providerAuthService.isProviderInstalled('opencode');
|
|
323
|
+
if (!installed) {
|
|
324
|
+
const socketSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : finalSessionId;
|
|
325
|
+
ws.send(createNormalizedMessage({
|
|
326
|
+
kind: 'error',
|
|
327
|
+
content: 'OpenCode CLI is not installed. Install it from the Settings → Agents → OpenCode tab, or run: npm install -g opencode-ai',
|
|
328
|
+
sessionId: socketSessionId,
|
|
329
|
+
provider: 'opencode',
|
|
330
|
+
}));
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
notifyTerminalState({
|
|
335
|
+
code,
|
|
336
|
+
error: code === null ? 'OpenCode CLI process was terminated or timed out' : null,
|
|
337
|
+
});
|
|
338
|
+
reject(new Error(code === null ? 'OpenCode CLI process was terminated or timed out' : `OpenCode CLI exited with code ${code}`));
|
|
339
|
+
}
|
|
340
|
+
});
|
|
341
|
+
|
|
342
|
+
opencodeProcess.on('error', async (error) => {
|
|
343
|
+
const finalSessionId = capturedSessionId || sessionId || processKey;
|
|
344
|
+
activeOpencodeProcesses.delete(finalSessionId);
|
|
345
|
+
|
|
346
|
+
const installed = await providerAuthService.isProviderInstalled('opencode');
|
|
347
|
+
const errorContent = !installed
|
|
348
|
+
? 'OpenCode CLI is not installed. Install it from the Settings → Agents → OpenCode tab, or run: npm install -g opencode-ai'
|
|
349
|
+
: error.message;
|
|
350
|
+
|
|
351
|
+
const errorSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : finalSessionId;
|
|
352
|
+
ws.send(createNormalizedMessage({ kind: 'error', content: errorContent, sessionId: errorSessionId, provider: 'opencode' }));
|
|
353
|
+
notifyTerminalState({ error });
|
|
354
|
+
|
|
355
|
+
reject(error);
|
|
356
|
+
});
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function abortOpencodeSession(sessionId) {
|
|
361
|
+
let opencodeProc = activeOpencodeProcesses.get(sessionId);
|
|
362
|
+
let processKey = sessionId;
|
|
363
|
+
|
|
364
|
+
if (!opencodeProc) {
|
|
365
|
+
for (const [key, proc] of activeOpencodeProcesses.entries()) {
|
|
366
|
+
if (proc.sessionId === sessionId) {
|
|
367
|
+
opencodeProc = proc;
|
|
368
|
+
processKey = key;
|
|
369
|
+
break;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
if (opencodeProc) {
|
|
375
|
+
try {
|
|
376
|
+
opencodeProc.kill('SIGTERM');
|
|
377
|
+
setTimeout(() => {
|
|
378
|
+
if (activeOpencodeProcesses.has(processKey)) {
|
|
379
|
+
try { opencodeProc.kill('SIGKILL'); } catch { /* noop */ }
|
|
380
|
+
}
|
|
381
|
+
}, 2000);
|
|
382
|
+
return true;
|
|
383
|
+
} catch {
|
|
384
|
+
return false;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
return false;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
function isOpencodeSessionActive(sessionId) {
|
|
391
|
+
return activeOpencodeProcesses.has(sessionId);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function getActiveOpencodeSessions() {
|
|
395
|
+
return Array.from(activeOpencodeProcesses.keys());
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
export {
|
|
399
|
+
spawnOpencode,
|
|
400
|
+
abortOpencodeSession,
|
|
401
|
+
isOpencodeSessionActive,
|
|
402
|
+
getActiveOpencodeSessions,
|
|
403
|
+
};
|