@openagents-org/agent-launcher 0.2.228 → 0.2.230

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.
@@ -26,6 +26,8 @@ const { formatAttachmentsForPrompt, redactSecrets, stripAnsi } = require('./util
26
26
  const { buildOpenCodeSkillMd, buildOpenCodeSystemPrompt, workspaceSkillName } = require('./workspace-prompt');
27
27
  const { whichBinary, whereBinary, getEnhancedEnv } = require('../paths');
28
28
  const { isPostinstallStub, isPostinstallStubOutput } = require('../postinstall-stub');
29
+ const EventEmitter = require('events');
30
+ const { OpenCodeServer } = require('./opencode-server');
29
31
 
30
32
  // The launcher's own CLI, whose `mcp-server` command serves the workspace tools.
31
33
  const WORKSPACE_MCP_BIN = path.resolve(__dirname, '..', '..', 'bin', 'agent-connector.js');
@@ -38,6 +40,9 @@ const IS_WINDOWS = process.platform === 'win32';
38
40
  // timeout killed those healthy runs midway through their answer.
39
41
  const TIMEOUT_MS = 300000; // 5 minutes
40
42
 
43
+ // _runViaServer's answer for "the server can't take this message": run it the ordinary way.
44
+ const NO_SERVER = Symbol('no-server');
45
+
41
46
  // Pinned OpenCode CLI version. Do NOT use @latest anywhere (registry.json /
42
47
  // opencode.yaml install commands, install hints below). This adapter parses
43
48
  // opencode's `--format json` stream, so an unbounded version floats the event
@@ -84,6 +89,22 @@ const CUSTOM_PROVIDER_ID = 'openagents-gateway';
84
89
  const ownDbPath = () => path.join(os.homedir(), '.openagents', 'opencode', 'opencode.db');
85
90
  const SHARED_DB_MIGRATED_RE = /database is not empty and has no session table/i;
86
91
 
92
+ // Lets OpenCode's subagents read and write outside the working directory, as
93
+ // the main session already may. `opencode run --dangerously-skip-permissions`
94
+ // answers only the main session's permission prompts (opencode-ai 1.17.11,
95
+ // packages/opencode/src/cli/cmd/run.ts: `permission.sessionID !== sessionID`
96
+ // is skipped). A subagent started by the task tool runs in a child session,
97
+ // and `external_directory` defaults to "ask", so its prompt went unanswered
98
+ // until the idle watchdog stopped the turn: "OpenCode timed out before
99
+ // producing a reply" (daily errors dashboard, 2026-11-17, ~10 runs from 4
100
+ // users). Fixed upstream in 1.19.0, which also answers child sessions; the
101
+ // pinned 1.17.11 is not. OPENCODE_PERMISSION is merged over the user's config
102
+ // last (packages/opencode/src/config/config.ts), so it is left out when the
103
+ // user set it, wrote an external_directory rule of their own, or set every
104
+ // permission at once.
105
+ const SUBAGENT_PERMISSION = JSON.stringify({ external_directory: 'allow' });
106
+ const CONFIG_FILES = ['opencode.json', 'opencode.jsonc', path.join('.opencode', 'opencode.json'), path.join('.opencode', 'opencode.jsonc')];
107
+
87
108
  // Short, de-identified, actionable user messages per failure category. These
88
109
  // must NEVER default to "run auth login": only credential_missing / auth_failed
89
110
  // mention authentication. Diagnostics (exit code, signal, redacted stdout/
@@ -111,6 +132,7 @@ const FAILURE_MESSAGES = {
111
132
  process_crashed: 'OpenCode exited unexpectedly. Open diagnostics or retry.',
112
133
  cwd_unavailable: "OpenCode's working directory is not accessible. Check the agent's configured path (or agent home) permissions.",
113
134
  shared_db_migrated: "OpenCode could not open its session database: a newer OpenCode (2.x, or the OpenCode desktop app) on this device has converted it to a format the OpenCode CLI that OpenAgents runs cannot read, and running it on a database of its own did not help either. Reinstall OpenCode from the launcher, or set OPENCODE_DB in this agent's configuration to the full path of a new file, then retry.",
135
+ malformed_tool_call: "The model sent back a tool call OpenCode could not read (it named no tool), so the run stopped. This comes from the model or the endpoint serving it, not from this agent's settings: retry, and if it keeps happening, switch this agent to another model or provider.",
114
136
  config_invalid: 'OpenCode would not start because one of its config files is invalid — the file and what is wrong with it are below. OpenCode reads it on every run, so every message fails until it is fixed: correct or remove that entry, then retry.',
115
137
  unknown_error: 'OpenCode failed for an undetermined reason. Open diagnostics or retry.',
116
138
  };
@@ -146,6 +168,7 @@ class OpenCodeAdapter extends BaseAdapter {
146
168
  // Process tracking for stop control
147
169
  this._channelProcesses = {}; // channel → child process
148
170
  this._stoppingChannels = new Set();
171
+ this._server = null; // warm `opencode serve` (opencode-server.js), when enabled
149
172
 
150
173
  this._opencodeBinary = this._findOpencodeBinary();
151
174
  if (this._opencodeBinary) {
@@ -269,9 +292,73 @@ class OpenCodeAdapter extends BaseAdapter {
269
292
  touch();
270
293
  return { touch, cancel, timeoutMs };
271
294
  }
272
- _spawnEnv(channel) {
295
+
296
+ /**
297
+ * Whether the user's own OpenCode config has an external_directory rule,
298
+ * or sets every permission at once (`"permission": "deny"` or
299
+ * `{"*": "deny"}`): the global config and ~/.opencode, OPENCODE_CONFIG and
300
+ * OPENCODE_CONFIG_DIR, the inline config, and the project files from the
301
+ * run's folder up. A text match is enough, and errs toward leaving
302
+ * their rules alone.
303
+ */
304
+ static _userRulesExternalDirs(env, runCwd) {
305
+ const mentions = (text) => /external_directory/.test(String(text || ''))
306
+ || OpenCodeAdapter._setsEveryPermission(String(text || ''));
307
+ if (mentions(env.OPENCODE_CONFIG_CONTENT)) return true;
308
+ const home = env.HOME || env.USERPROFILE || os.homedir();
309
+ const globalDir = path.join(env.XDG_CONFIG_HOME || path.join(home, '.config'), 'opencode');
310
+ const files = ['config.json', 'opencode.json', 'opencode.jsonc'].map((f) => path.join(globalDir, f));
311
+ files.push(...['opencode.json', 'opencode.jsonc'].map((f) => path.join(home, '.opencode', f)));
312
+ if (env.OPENCODE_CONFIG) files.push(env.OPENCODE_CONFIG);
313
+ if (env.OPENCODE_CONFIG_DIR) files.push(...['opencode.json', 'opencode.jsonc'].map((f) => path.join(env.OPENCODE_CONFIG_DIR, f)));
314
+ for (let dir = runCwd ? path.resolve(runCwd) : ''; dir; ) {
315
+ files.push(...CONFIG_FILES.map((f) => path.join(dir, f)));
316
+ const up = path.dirname(dir);
317
+ dir = up === dir ? '' : up;
318
+ }
319
+ return files.some((file) => {
320
+ try { return mentions(fs.readFileSync(file, 'utf-8')); } catch { return false; }
321
+ });
322
+ }
323
+
324
+ /**
325
+ * Whether a config's text sets every permission at once: `"permission":
326
+ * "deny"`, or a `"*"` key anywhere in the permission object — not only as
327
+ * its first key: `{"bash": {"git *": "allow"}, "*": "deny"}` was read as
328
+ * no rule, and the external_directory allow then went over a lockdown.
329
+ * Only the object's own keys count, not a `"*"` inside a nested rule.
330
+ */
331
+ static _setsEveryPermission(text) {
332
+ const re = /"permission"\s*:\s*/g;
333
+ for (let m = re.exec(text); m; m = re.exec(text)) {
334
+ let i = m.index + m[0].length;
335
+ if (text[i] === '"') return true;
336
+ if (text[i] !== '{') continue;
337
+ let depth = 0;
338
+ let inString = false;
339
+ for (let start = i; i < text.length; i++) {
340
+ const c = text[i];
341
+ if (inString) {
342
+ if (c === '\\') i++;
343
+ else if (c === '"') {
344
+ inString = false;
345
+ // A key of the permission object itself.
346
+ if (depth === 1 && text.slice(start, i + 1) === '"*"' && /^\s*:/.test(text.slice(i + 1))) return true;
347
+ }
348
+ } else if (c === '"') { inString = true; start = i; }
349
+ else if (c === '{') depth++;
350
+ else if (c === '}' && --depth === 0) break;
351
+ }
352
+ }
353
+ return false;
354
+ }
355
+
356
+ _spawnEnv(channel, { contextFile = null } = {}) {
273
357
  const env = { ...(this.agentEnv || process.env) };
274
358
  if (!env.OPENCODE_DB && fs.existsSync(ownDbPath())) env.OPENCODE_DB = ownDbPath();
359
+ if (!env.OPENCODE_PERMISSION && !OpenCodeAdapter._userRulesExternalDirs(env, this._resolveCwd())) {
360
+ env.OPENCODE_PERMISSION = SUBAGENT_PERMISSION;
361
+ }
275
362
  if (!this._wiresWorkspaceMcp()) return env;
276
363
  // Give OpenCode the workspace tools (publish, todos, browser, ...) through
277
364
  // our MCP server, as the Claude adapter does. Merged into any inline config
@@ -282,11 +369,14 @@ class OpenCodeAdapter extends BaseAdapter {
282
369
  const args = [WORKSPACE_MCP_BIN, 'mcp-server',
283
370
  '--workspace-id', this.workspaceId, '--channel-name', channel || this.channelName || 'general',
284
371
  '--agent-name', this.agentName, '--endpoint', this.endpoint];
372
+ // On the warm server one tools server serves every channel: it reads the
373
+ // turn's channel and requester from this file (written per turn).
374
+ if (contextFile) args.push('--context-file', contextFile);
285
375
  const disabled = this.disabledModules || new Set();
286
376
  if (disabled.has('files')) args.push('--disable-files');
287
377
  if (disabled.has('browser')) args.push('--disable-browser');
288
378
  if (disabled.has('knowledge')) args.push('--disable-knowledge');
289
- const requester = channel && this.requesterEmailFor ? this.requesterEmailFor(channel) : null;
379
+ const requester = !contextFile && channel && this.requesterEmailFor ? this.requesterEmailFor(channel) : null;
290
380
  cfg.mcp = { ...(cfg.mcp || {}), openagents: { type: 'local', enabled: true,
291
381
  command: [process.execPath, ...args],
292
382
  environment: { OA_WORKSPACE_TOKEN: this.token, ...(requester ? { OPENAGENTS_REQUESTER_EMAIL: requester } : {}) } } };
@@ -826,10 +916,34 @@ class OpenCodeAdapter extends BaseAdapter {
826
916
  this._stopAllProcesses(
827
917
  'Task interrupted — daemon restarting. Send another message to continue.'
828
918
  ).catch(() => {});
919
+ if (this._server) this._server.stop();
829
920
  super.stop();
830
921
  }
831
922
 
923
+ /**
924
+ * Whether messages may go to a warm `opencode serve` instead of a new
925
+ * `opencode run`. Opt-in (OPENAGENTS_OPENCODE_SERVER=1), plain OpenCode
926
+ * only, and not on Windows or across the WSL boundary for now.
927
+ */
928
+ _serverEnabled() {
929
+ if ((this.agentEnv || process.env).OPENAGENTS_OPENCODE_SERVER !== '1') return false;
930
+ const bin = String(this._opencodeBinary || '');
931
+ return !IS_WINDOWS && !bin.startsWith('wsl:') && this._cliLabel() === 'OpenCode';
932
+ }
933
+
934
+ /** Where the warm server's tools read the current turn's channel and requester. */
935
+ _turnContextFile() {
936
+ return path.join(this.agentHome || os.tmpdir(), 'opencode-turn-context.json');
937
+ }
938
+
939
+ _getServer() {
940
+ if (!this._server) this._server = new OpenCodeServer({ binary: this._opencodeBinary, log: (m, l) => this._log(m, l) });
941
+ return this._server;
942
+ }
943
+
832
944
  async _stopProcess(proc) {
945
+ // A turn on the warm server keeps going until the server is told to stop it.
946
+ if (proc && proc.__abortAttached) { try { await proc.__abortAttached(); } catch {} }
833
947
  if (!proc || proc.exitCode !== null) return;
834
948
  try {
835
949
  if (IS_WINDOWS) {
@@ -985,7 +1099,7 @@ class OpenCodeAdapter extends BaseAdapter {
985
1099
  }
986
1100
  }
987
1101
 
988
- _runOpencode(content, msgChannel) {
1102
+ _runOpencode(content, msgChannel, { noServer = false } = {}) {
989
1103
  // Preflight BEFORE spawning: bail out with a structured, actionable error
990
1104
  // instead of launching a child that will hang for 5 minutes or exit 1 with
991
1105
  // an opaque message. Stubbing _runOpencode in tests bypasses this, exactly
@@ -1023,6 +1137,14 @@ class OpenCodeAdapter extends BaseAdapter {
1023
1137
  // Stopped while this turn was being prepared: start nothing (no tokens).
1024
1138
  if (this._stoppedBeforeStart(msgChannel)) return Promise.resolve('');
1025
1139
 
1140
+ if (!noServer && this._serverEnabled()) {
1141
+ // The server's setup must not depend on the channel, so it can serve them all.
1142
+ const contextFile = this._turnContextFile();
1143
+ const serverEnv = this._spawnEnv(this.channelName || 'general', { contextFile });
1144
+ return this._runViaServer({ msgChannel, runCwd, model, sessionId, fullPrompt, spawnEnv: serverEnv, contextFile })
1145
+ .then((r) => (r === NO_SERVER ? this._runOpencode(content, msgChannel, { noServer: true }) : r));
1146
+ }
1147
+
1026
1148
  return new Promise((resolve, reject) => {
1027
1149
  const proc = spawn(spawnBinary, spawnArgs, {
1028
1150
  stdio: ['pipe', 'pipe', 'pipe'],
@@ -1102,44 +1224,227 @@ class OpenCodeAdapter extends BaseAdapter {
1102
1224
  return finish(resolve, '');
1103
1225
  }
1104
1226
 
1105
- stdout = stdout.trim();
1106
- stderr = stderr.trim();
1107
-
1108
- // A structured error event may ride on stdout regardless of exit code
1109
- // (opencode emits {"type":"error", ...} as a JSONL event). Look there
1110
- // first so the real auth/provider/model failure is never discarded just
1111
- // because stderr happened to be empty.
1112
- const stdoutErr = OpenCodeAdapter._extractErrorFromStdout(stdout);
1113
-
1114
- if (timedOut) {
1115
- this._log(`opencode timed out after ${watchdog.timeoutMs / 1000}s idle (output: ${!!stdout})`);
1116
- const cls = this.constructor._classifyFailure({ code, signal, stdout, stderr, stdoutErr });
1117
- const category = (cls.category === 'unknown_error' || cls.category === 'process_crashed')
1118
- ? 'timeout' : cls.category;
1119
- return finish(reject, this._failure(category, cls.diagnostic || `idle=${watchdog.timeoutMs}ms`, cls.detail));
1120
- }
1227
+ const outcome = this._settleOutcome({ code, signal, stdout, stderr, timedOut, timeoutMs: watchdog.timeoutMs, responseState, msgChannel });
1228
+ return outcome.error ? finish(reject, outcome.error) : finish(resolve, outcome.text);
1229
+ });
1230
+ });
1231
+ }
1121
1232
 
1122
- if (signal) {
1123
- this._log(`opencode killed by signal ${signal} (output: ${!!stdout})`);
1124
- const cls = this.constructor._classifyFailure({ code, signal, stdout, stderr, stdoutErr });
1125
- return finish(reject, this._failure(cls.category, cls.diagnostic || `signal=${signal}`, cls.detail));
1126
- }
1233
+ /**
1234
+ * What a finished run means, from its exit and its JSON output: `{ text }`
1235
+ * for a reply or `{ error }` (a classified failure). Shared by `opencode run`
1236
+ * and runs on the warm server, so both fail the same way.
1237
+ */
1238
+ _settleOutcome({ code, signal, stdout, stderr, timedOut, timeoutMs, responseState, msgChannel }) {
1239
+ stdout = String(stdout || '').trim();
1240
+ stderr = String(stderr || '').trim();
1241
+
1242
+ // A structured error event may ride on stdout regardless of exit code
1243
+ // (opencode emits {"type":"error", ...} as a JSONL event). Look there
1244
+ // first so the real auth/provider/model failure is never discarded just
1245
+ // because stderr happened to be empty.
1246
+ const stdoutErr = OpenCodeAdapter._extractErrorFromStdout(stdout);
1247
+
1248
+ if (timedOut) {
1249
+ this._log(`opencode timed out after ${timeoutMs / 1000}s idle (output: ${!!stdout})`);
1250
+ const cls = this.constructor._classifyFailure({ code, signal, stdout, stderr, stdoutErr });
1251
+ const category = (cls.category === 'unknown_error' || cls.category === 'process_crashed')
1252
+ ? 'timeout' : cls.category;
1253
+ return { error: this._failure(category, cls.diagnostic || `idle=${timeoutMs}ms`, cls.detail) };
1254
+ }
1255
+
1256
+ if (signal) {
1257
+ this._log(`opencode killed by signal ${signal} (output: ${!!stdout})`);
1258
+ const cls = this.constructor._classifyFailure({ code, signal, stdout, stderr, stdoutErr });
1259
+ return { error: this._failure(cls.category, cls.diagnostic || `signal=${signal}`, cls.detail) };
1260
+ }
1127
1261
 
1128
- if (code !== 0) {
1129
- const cls = this.constructor._classifyFailure({ code, signal, stdout, stderr, stdoutErr });
1130
- this._log(`opencode exited code ${code} → [${cls.category}]: ${this._redact(cls.diagnostic).slice(0, 300)}`);
1131
- return finish(reject, this._failure(cls.category, cls.diagnostic, cls.detail));
1262
+ if (code !== 0) {
1263
+ const cls = this.constructor._classifyFailure({ code, signal, stdout, stderr, stdoutErr });
1264
+ this._log(`opencode exited code ${code} → [${cls.category}]: ${this._redact(cls.diagnostic).slice(0, 300)}`);
1265
+ return { error: this._failure(cls.category, cls.diagnostic, cls.detail) };
1266
+ }
1267
+
1268
+ // Exit 0.
1269
+ if (stdout) this._persistSessionId(msgChannel, stdout);
1270
+ const outcome = this.constructor._outcomeForCleanExit({ stdout, stderr, stdoutErr, responseState });
1271
+ if (outcome.text) return { text: outcome.text };
1272
+ const f = outcome.failure;
1273
+ this._log(`opencode exit 0 → [${f.category}]: ${this._redact(f.diagnostic).slice(0, 300)}`);
1274
+ return { error: this._failure(f.category, f.diagnostic, f.detail) };
1275
+ }
1276
+
1277
+ /**
1278
+ * One turn on the warm server (opencode-server.js): the message goes to the
1279
+ * session over HTTP and the server's live events become the same JSON
1280
+ * events `opencode run --format json` prints, so thinking, tool steps and
1281
+ * the reply show exactly as they do today. The finished message the request
1282
+ * returns is the source of truth: parts the live stream missed are replayed
1283
+ * from it. Permission requests are answered `once`, like
1284
+ * --dangerously-skip-permissions (rules that deny still deny). Returns
1285
+ * NO_SERVER when the message should run the ordinary way instead.
1286
+ */
1287
+ async _runViaServer({ msgChannel, runCwd, model, sessionId, fullPrompt, spawnEnv, contextFile = null }) {
1288
+ const slash = String(model || '').indexOf('/');
1289
+ if (slash <= 0) return NO_SERVER;
1290
+ const server = this._getServer();
1291
+ if (!(await server.acquire({ env: spawnEnv, cwd: runCwd }))) return NO_SERVER;
1292
+ if (contextFile) {
1293
+ // The server runs one turn at a time, so this is the only turn reading it.
1294
+ try {
1295
+ fs.mkdirSync(path.dirname(contextFile), { recursive: true });
1296
+ const requesterEmail = this.requesterEmailFor ? this.requesterEmailFor(msgChannel) : null;
1297
+ fs.writeFileSync(contextFile, JSON.stringify({ channel: msgChannel, requesterEmail }), { mode: 0o600 });
1298
+ } catch (e) {
1299
+ this._log(`Could not write the turn context (${e.message}); running this message without the server`, 'error');
1300
+ server.release();
1301
+ return NO_SERVER;
1302
+ }
1303
+ }
1304
+
1305
+ let sid = sessionId || null;
1306
+ // Stand-in for a child process, so stop and interrupt reach this turn.
1307
+ const proc = new EventEmitter();
1308
+ proc.pid = null;
1309
+ proc.exitCode = null;
1310
+ proc.kill = () => { if (proc.exitCode === null) { proc.exitCode = 0; proc.emit('exit', 0); } };
1311
+ proc.__abortAttached = () => server.abort(sid);
1312
+ this._channelProcesses[msgChannel] = proc;
1313
+
1314
+ const responseState = { finalText: '', allText: '', seenText: false };
1315
+ const lines = [];
1316
+ const emitted = new Set();
1317
+ const roles = {};
1318
+ const early = []; // parts seen before their message's role
1319
+ const children = new Set(); // subagent sessions started from this turn's session
1320
+ let pending = Promise.resolve();
1321
+ let timedOut = false;
1322
+ const watchdog = this._createIdleWatchdog(() => {
1323
+ timedOut = true;
1324
+ this._log(`opencode idle for ${this._runTimeoutMs() / 1000}s; stopping the turn on the server`);
1325
+ server.abort(sid).catch(() => {});
1326
+ });
1327
+ const emit = (part, final = false) => {
1328
+ const event = OpenCodeAdapter._eventForPart(part, final);
1329
+ if (!event) return;
1330
+ const key = `${part.id}:${event.type}`;
1331
+ if (emitted.has(key)) return;
1332
+ emitted.add(key);
1333
+ lines.push(JSON.stringify(event));
1334
+ pending = pending
1335
+ .then(() => this._handleStreamEvent(event, msgChannel, responseState))
1336
+ .catch((e) => this._log(`opencode stream event handling failed: ${e.message}`));
1337
+ };
1338
+ const unsubscribe = server.subscribe((ev) => {
1339
+ const props = (ev && ev.properties) || {};
1340
+ if (!sid) return;
1341
+ if (ev.type === 'message.updated' && props.info && props.info.sessionID === sid) {
1342
+ roles[props.info.id] = props.info.role;
1343
+ for (let k = early.length - 1; k >= 0; k--) {
1344
+ if (roles[early[k].messageID]) { const [part] = early.splice(k, 1); if (roles[part.messageID] === 'assistant') emit(part); }
1132
1345
  }
1346
+ } else if (ev.type === 'session.created' && props.info && props.info.parentID
1347
+ && (props.info.parentID === sid || children.has(props.info.parentID))) {
1348
+ children.add(props.info.id);
1349
+ } else if (ev.type === 'permission.asked' && (props.sessionID === sid || children.has(props.sessionID))) {
1350
+ // A subagent's prompt arrives from its own child session; left
1351
+ // unanswered it held the turn until the idle watchdog stopped it.
1352
+ watchdog.touch();
1353
+ server.replyPermission(props.sessionID, props.id, 'once').catch(() => {});
1354
+ } else if (ev.type === 'message.part.updated' && props.part && props.part.sessionID === sid) {
1355
+ watchdog.touch();
1356
+ const part = props.part;
1357
+ if (!roles[part.messageID]) early.push(part);
1358
+ else if (roles[part.messageID] === 'assistant') emit(part);
1359
+ } else if (ev.type === 'message.part.delta' && props.sessionID === sid) {
1360
+ watchdog.touch();
1361
+ } else if ((ev.type === 'message.part.updated' && props.part && children.has(props.part.sessionID))
1362
+ || (ev.type === 'message.part.delta' && children.has(props.sessionID))) {
1363
+ // A subagent at work is the turn at work: its parts are not this
1364
+ // channel's reply, but a long task run in a child session left the
1365
+ // turn's own session quiet until the watchdog stopped it.
1366
+ watchdog.touch();
1367
+ }
1368
+ });
1369
+ const stopping = () => this._stoppingChannels.has(msgChannel);
1370
+ const done = () => {
1371
+ watchdog.cancel();
1372
+ unsubscribe();
1373
+ server.release();
1374
+ if (this._channelProcesses[msgChannel] === proc) delete this._channelProcesses[msgChannel];
1375
+ proc.kill();
1376
+ };
1133
1377
 
1134
- // Exit 0.
1135
- if (stdout) this._persistSessionId(msgChannel, stdout);
1136
- const outcome = this.constructor._outcomeForCleanExit({ stdout, stderr, stdoutErr, responseState });
1137
- if (outcome.text) return finish(resolve, outcome.text);
1138
- const f = outcome.failure;
1139
- this._log(`opencode exit 0 → [${f.category}]: ${this._redact(f.diagnostic).slice(0, 300)}`);
1140
- return finish(reject, this._failure(f.category, f.diagnostic, f.detail));
1378
+ try {
1379
+ try {
1380
+ if (!sid) {
1381
+ sid = (await server.request('POST', '/session', {})).id;
1382
+ this._channelSessions[msgChannel] = sid;
1383
+ this._saveSessions();
1384
+ }
1385
+ } catch (e) {
1386
+ this._log(`OpenCode server could not open a session (${e.message}); running this message without it`, 'error');
1387
+ done();
1388
+ return NO_SERVER;
1389
+ }
1390
+ this._log(`CLI (warm server): message to session ${sid}`);
1391
+ let res;
1392
+ try {
1393
+ res = await server.request('POST', `/session/${encodeURIComponent(sid)}/message`, {
1394
+ model: { providerID: model.slice(0, slash), modelID: model.slice(slash + 1) },
1395
+ parts: [{ type: 'text', text: fullPrompt }],
1396
+ });
1397
+ } catch (e) {
1398
+ if (!emitted.size && !stopping() && !timedOut) {
1399
+ // Nothing happened yet: an unknown session, or a server in trouble.
1400
+ this._log(`OpenCode server turn failed before any output (${e.message}); running this message without it`, 'error');
1401
+ if (e.status !== 404) server.stop();
1402
+ done();
1403
+ return NO_SERVER;
1404
+ }
1405
+ res = null;
1406
+ }
1407
+ for (const part of (res && res.parts) || []) emit(part, true);
1408
+ const info = (res && res.info) || {};
1409
+ if (info.error) lines.push(JSON.stringify({ type: 'error', sessionID: sid, error: info.error }));
1410
+ try { await pending; } catch {}
1411
+ if (stopping()) {
1412
+ this._stoppingChannels.delete(msgChannel);
1413
+ done();
1414
+ return '';
1415
+ }
1416
+ done();
1417
+ const outcome = this._settleOutcome({
1418
+ code: info.error || !res ? 1 : 0, signal: null, stdout: lines.join('\n'), stderr: '',
1419
+ timedOut, timeoutMs: watchdog.timeoutMs, responseState, msgChannel,
1141
1420
  });
1142
- });
1421
+ if (outcome.error) throw outcome.error;
1422
+ return outcome.text;
1423
+ } catch (e) {
1424
+ if (this._channelProcesses[msgChannel] === proc) done();
1425
+ throw e;
1426
+ }
1427
+ }
1428
+
1429
+ /**
1430
+ * The `opencode run --format json` event for a finished message part, or
1431
+ * null while it's still being written (live parts) / for other part types.
1432
+ */
1433
+ static _eventForPart(part, final = false) {
1434
+ if (!part || typeof part !== 'object') return null;
1435
+ const ended = final || Boolean(part.time && part.time.end);
1436
+ const base = { sessionID: part.sessionID, part };
1437
+ switch (part.type) {
1438
+ case 'step-start': return { type: 'step_start', ...base };
1439
+ case 'step-finish': return { type: 'step_finish', ...base };
1440
+ case 'reasoning': return ended ? { type: 'reasoning', ...base } : null;
1441
+ case 'text': return ended && !part.synthetic && !part.ignored ? { type: 'text', ...base } : null;
1442
+ case 'tool': {
1443
+ const status = part.state && part.state.status;
1444
+ return (status === 'completed' || status === 'error') ? { type: 'tool_use', ...base } : null;
1445
+ }
1446
+ default: return null;
1447
+ }
1143
1448
  }
1144
1449
 
1145
1450
  /**
@@ -1552,6 +1857,14 @@ class OpenCodeAdapter extends BaseAdapter {
1552
1857
  category = 'network_error';
1553
1858
  } else if (has(/\b5\d\d\b|server error|internal server|bad gateway|service unavailable|gateway timeout|server is busy|system is busy|系统繁忙|服务繁忙|đang bận/)) {
1554
1859
  category = 'provider_server_error';
1860
+ } else if (has(/expected '?function\.name'? to be a string/)) {
1861
+ // The provider streamed a tool call with no tool name, and the AI SDK
1862
+ // under OpenCode refused it: "Expected 'function.name' to be a string."
1863
+ // Six times in a row from one user's agents on GLM / DeepSeek models
1864
+ // (daily errors dashboard, 2026-11-18), each read as "OpenCode failed
1865
+ // for an undetermined reason". After the provider categories: a key,
1866
+ // credit or network failure in the same output is the cause to report.
1867
+ category = 'malformed_tool_call';
1555
1868
  } else if (has(/timeout|timed out/)) {
1556
1869
  category = 'timeout';
1557
1870
  } else if (err) {