@openagents-org/agent-launcher 0.2.227 → 0.2.229

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
@@ -71,6 +76,35 @@ const VERSION_PROBE_TTL_MS = 60000;
71
76
  // provider keeps requests on `/chat/completions` and skips catalog validation.
72
77
  const CUSTOM_PROVIDER_ID = 'openagents-gateway';
73
78
 
79
+ // The database OpenCode is pointed at (OPENCODE_DB) once the shared one cannot
80
+ // be opened. OpenCode 1.x and 2.x both default to <data>/opencode/opencode.db;
81
+ // 2.x renames the `session` table to `session_v2` when it migrates it, and from
82
+ // then on the 1.x CLI this adapter runs dies at startup with "Database is not
83
+ // empty and has no session table" on every message (opencode-ai 1.17.11,
84
+ // packages/core/src/database/migration.ts). OPENCODE_DB takes an absolute path
85
+ // in that version (packages/core/src/database/database.ts). Once this file
86
+ // exists it is used from then on; auth.json stays shared, so sign-ins keep
87
+ // working, and the user's own database is never written.
88
+ // Resolved per call, so it follows HOME.
89
+ const ownDbPath = () => path.join(os.homedir(), '.openagents', 'opencode', 'opencode.db');
90
+ const SHARED_DB_MIGRATED_RE = /database is not empty and has no session table/i;
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
+
74
108
  // Short, de-identified, actionable user messages per failure category. These
75
109
  // must NEVER default to "run auth login": only credential_missing / auth_failed
76
110
  // mention authentication. Diagnostics (exit code, signal, redacted stdout/
@@ -97,6 +131,7 @@ const FAILURE_MESSAGES = {
97
131
  permission_denied: 'OpenCode could not get permission for a tool call. Check the agent’s explicit deny rules or file access settings; sending continue alone will not change them.',
98
132
  process_crashed: 'OpenCode exited unexpectedly. Open diagnostics or retry.',
99
133
  cwd_unavailable: "OpenCode's working directory is not accessible. Check the agent's configured path (or agent home) permissions.",
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.",
100
135
  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.',
101
136
  unknown_error: 'OpenCode failed for an undetermined reason. Open diagnostics or retry.',
102
137
  };
@@ -132,6 +167,7 @@ class OpenCodeAdapter extends BaseAdapter {
132
167
  // Process tracking for stop control
133
168
  this._channelProcesses = {}; // channel → child process
134
169
  this._stoppingChannels = new Set();
170
+ this._server = null; // warm `opencode serve` (opencode-server.js), when enabled
135
171
 
136
172
  this._opencodeBinary = this._findOpencodeBinary();
137
173
  if (this._opencodeBinary) {
@@ -255,8 +291,40 @@ class OpenCodeAdapter extends BaseAdapter {
255
291
  touch();
256
292
  return { touch, cancel, timeoutMs };
257
293
  }
258
- _spawnEnv(channel) {
294
+
295
+ /**
296
+ * Whether the user's own OpenCode config has an external_directory rule,
297
+ * or sets every permission at once (`"permission": "deny"` or
298
+ * `{"*": "deny"}`): the global config and ~/.opencode, OPENCODE_CONFIG and
299
+ * OPENCODE_CONFIG_DIR, the inline config, and the project files from the
300
+ * run's folder up. A text match is enough, and errs toward leaving
301
+ * their rules alone.
302
+ */
303
+ static _userRulesExternalDirs(env, runCwd) {
304
+ const mentions = (text) => /external_directory|"permission"\s*:\s*("|\{\s*"\*")/.test(String(text || ''));
305
+ if (mentions(env.OPENCODE_CONFIG_CONTENT)) return true;
306
+ const home = env.HOME || env.USERPROFILE || os.homedir();
307
+ const globalDir = path.join(env.XDG_CONFIG_HOME || path.join(home, '.config'), 'opencode');
308
+ const files = ['config.json', 'opencode.json', 'opencode.jsonc'].map((f) => path.join(globalDir, f));
309
+ files.push(...['opencode.json', 'opencode.jsonc'].map((f) => path.join(home, '.opencode', f)));
310
+ if (env.OPENCODE_CONFIG) files.push(env.OPENCODE_CONFIG);
311
+ if (env.OPENCODE_CONFIG_DIR) files.push(...['opencode.json', 'opencode.jsonc'].map((f) => path.join(env.OPENCODE_CONFIG_DIR, f)));
312
+ for (let dir = runCwd ? path.resolve(runCwd) : ''; dir; ) {
313
+ files.push(...CONFIG_FILES.map((f) => path.join(dir, f)));
314
+ const up = path.dirname(dir);
315
+ dir = up === dir ? '' : up;
316
+ }
317
+ return files.some((file) => {
318
+ try { return mentions(fs.readFileSync(file, 'utf-8')); } catch { return false; }
319
+ });
320
+ }
321
+
322
+ _spawnEnv(channel, { contextFile = null } = {}) {
259
323
  const env = { ...(this.agentEnv || process.env) };
324
+ if (!env.OPENCODE_DB && fs.existsSync(ownDbPath())) env.OPENCODE_DB = ownDbPath();
325
+ if (!env.OPENCODE_PERMISSION && !OpenCodeAdapter._userRulesExternalDirs(env, this._resolveCwd())) {
326
+ env.OPENCODE_PERMISSION = SUBAGENT_PERMISSION;
327
+ }
260
328
  if (!this._wiresWorkspaceMcp()) return env;
261
329
  // Give OpenCode the workspace tools (publish, todos, browser, ...) through
262
330
  // our MCP server, as the Claude adapter does. Merged into any inline config
@@ -267,11 +335,14 @@ class OpenCodeAdapter extends BaseAdapter {
267
335
  const args = [WORKSPACE_MCP_BIN, 'mcp-server',
268
336
  '--workspace-id', this.workspaceId, '--channel-name', channel || this.channelName || 'general',
269
337
  '--agent-name', this.agentName, '--endpoint', this.endpoint];
338
+ // On the warm server one tools server serves every channel: it reads the
339
+ // turn's channel and requester from this file (written per turn).
340
+ if (contextFile) args.push('--context-file', contextFile);
270
341
  const disabled = this.disabledModules || new Set();
271
342
  if (disabled.has('files')) args.push('--disable-files');
272
343
  if (disabled.has('browser')) args.push('--disable-browser');
273
344
  if (disabled.has('knowledge')) args.push('--disable-knowledge');
274
- const requester = channel && this.requesterEmailFor ? this.requesterEmailFor(channel) : null;
345
+ const requester = !contextFile && channel && this.requesterEmailFor ? this.requesterEmailFor(channel) : null;
275
346
  cfg.mcp = { ...(cfg.mcp || {}), openagents: { type: 'local', enabled: true,
276
347
  command: [process.execPath, ...args],
277
348
  environment: { OA_WORKSPACE_TOKEN: this.token, ...(requester ? { OPENAGENTS_REQUESTER_EMAIL: requester } : {}) } } };
@@ -279,6 +350,33 @@ class OpenCodeAdapter extends BaseAdapter {
279
350
  return env;
280
351
  }
281
352
 
353
+ /**
354
+ * Whether a run that failed on the shared database can be retried on
355
+ * ownDbPath(), creating that file if need be. False when the failed run was
356
+ * not on the shared database to begin with: OPENCODE_DB set by the user, the
357
+ * file already there before the run (`ownBefore`), or a fork that builds its
358
+ * own environment. The sessions saved so far are ids in the old database
359
+ * and are dropped when the file is created here.
360
+ */
361
+ _moveToOwnDatabase(ownBefore) {
362
+ if (ownBefore || this._spawnEnv !== OpenCodeAdapter.prototype._spawnEnv) return false;
363
+ if ((this.agentEnv || process.env).OPENCODE_DB) return false;
364
+ const file = ownDbPath();
365
+ try {
366
+ fs.mkdirSync(path.dirname(file), { recursive: true });
367
+ fs.writeFileSync(file, '', { flag: 'wx' });
368
+ } catch (e) {
369
+ // Another channel's run got here first: the file is the one to use.
370
+ if (e && e.code === 'EEXIST') return true;
371
+ this._log(`Could not create ${file}: ${e && e.message}`, 'error');
372
+ return false;
373
+ }
374
+ this._log(`Shared OpenCode database was migrated by a newer OpenCode; using ${file}`);
375
+ this._channelSessions = {};
376
+ this._saveSessions();
377
+ return true;
378
+ }
379
+
282
380
  /**
283
381
  * Only plain OpenCode reads OPENCODE_CONFIG_CONTENT; the forks built on this
284
382
  * adapter (CodeArts, MiMo Code) replace _spawnEnv and keep the curl skill.
@@ -497,7 +595,16 @@ class OpenCodeAdapter extends BaseAdapter {
497
595
  await this.sendStatus(msgChannel, 'thinking...');
498
596
 
499
597
  try {
500
- const responseText = await this._runOpencode(content, msgChannel);
598
+ let responseText;
599
+ const ownBefore = fs.existsSync(ownDbPath());
600
+ try {
601
+ responseText = await this._runOpencode(content, msgChannel);
602
+ } catch (e) {
603
+ if (!(e && e.category === 'shared_db_migrated') || !this._moveToOwnDatabase(ownBefore)) throw e;
604
+ await this.sendStatus(msgChannel, "OpenCode's shared database was converted by a newer OpenCode on this "
605
+ + 'device, so this agent now uses one of its own. Earlier context in this thread is not carried over.');
606
+ responseText = await this._runOpencode(content, msgChannel);
607
+ }
501
608
 
502
609
  if (this._stoppingChannels.has(msgChannel)) {
503
610
  this._stoppingChannels.delete(msgChannel);
@@ -775,10 +882,34 @@ class OpenCodeAdapter extends BaseAdapter {
775
882
  this._stopAllProcesses(
776
883
  'Task interrupted — daemon restarting. Send another message to continue.'
777
884
  ).catch(() => {});
885
+ if (this._server) this._server.stop();
778
886
  super.stop();
779
887
  }
780
888
 
889
+ /**
890
+ * Whether messages may go to a warm `opencode serve` instead of a new
891
+ * `opencode run`. Opt-in (OPENAGENTS_OPENCODE_SERVER=1), plain OpenCode
892
+ * only, and not on Windows or across the WSL boundary for now.
893
+ */
894
+ _serverEnabled() {
895
+ if ((this.agentEnv || process.env).OPENAGENTS_OPENCODE_SERVER !== '1') return false;
896
+ const bin = String(this._opencodeBinary || '');
897
+ return !IS_WINDOWS && !bin.startsWith('wsl:') && this._cliLabel() === 'OpenCode';
898
+ }
899
+
900
+ /** Where the warm server's tools read the current turn's channel and requester. */
901
+ _turnContextFile() {
902
+ return path.join(this.agentHome || os.tmpdir(), 'opencode-turn-context.json');
903
+ }
904
+
905
+ _getServer() {
906
+ if (!this._server) this._server = new OpenCodeServer({ binary: this._opencodeBinary, log: (m, l) => this._log(m, l) });
907
+ return this._server;
908
+ }
909
+
781
910
  async _stopProcess(proc) {
911
+ // A turn on the warm server keeps going until the server is told to stop it.
912
+ if (proc && proc.__abortAttached) { try { await proc.__abortAttached(); } catch {} }
782
913
  if (!proc || proc.exitCode !== null) return;
783
914
  try {
784
915
  if (IS_WINDOWS) {
@@ -934,7 +1065,7 @@ class OpenCodeAdapter extends BaseAdapter {
934
1065
  }
935
1066
  }
936
1067
 
937
- _runOpencode(content, msgChannel) {
1068
+ _runOpencode(content, msgChannel, { noServer = false } = {}) {
938
1069
  // Preflight BEFORE spawning: bail out with a structured, actionable error
939
1070
  // instead of launching a child that will hang for 5 minutes or exit 1 with
940
1071
  // an opaque message. Stubbing _runOpencode in tests bypasses this, exactly
@@ -972,6 +1103,14 @@ class OpenCodeAdapter extends BaseAdapter {
972
1103
  // Stopped while this turn was being prepared: start nothing (no tokens).
973
1104
  if (this._stoppedBeforeStart(msgChannel)) return Promise.resolve('');
974
1105
 
1106
+ if (!noServer && this._serverEnabled()) {
1107
+ // The server's setup must not depend on the channel, so it can serve them all.
1108
+ const contextFile = this._turnContextFile();
1109
+ const serverEnv = this._spawnEnv(this.channelName || 'general', { contextFile });
1110
+ return this._runViaServer({ msgChannel, runCwd, model, sessionId, fullPrompt, spawnEnv: serverEnv, contextFile })
1111
+ .then((r) => (r === NO_SERVER ? this._runOpencode(content, msgChannel, { noServer: true }) : r));
1112
+ }
1113
+
975
1114
  return new Promise((resolve, reject) => {
976
1115
  const proc = spawn(spawnBinary, spawnArgs, {
977
1116
  stdio: ['pipe', 'pipe', 'pipe'],
@@ -1051,44 +1190,221 @@ class OpenCodeAdapter extends BaseAdapter {
1051
1190
  return finish(resolve, '');
1052
1191
  }
1053
1192
 
1054
- stdout = stdout.trim();
1055
- stderr = stderr.trim();
1056
-
1057
- // A structured error event may ride on stdout regardless of exit code
1058
- // (opencode emits {"type":"error", ...} as a JSONL event). Look there
1059
- // first so the real auth/provider/model failure is never discarded just
1060
- // because stderr happened to be empty.
1061
- const stdoutErr = OpenCodeAdapter._extractErrorFromStdout(stdout);
1062
-
1063
- if (timedOut) {
1064
- this._log(`opencode timed out after ${watchdog.timeoutMs / 1000}s idle (output: ${!!stdout})`);
1065
- const cls = this.constructor._classifyFailure({ code, signal, stdout, stderr, stdoutErr });
1066
- const category = (cls.category === 'unknown_error' || cls.category === 'process_crashed')
1067
- ? 'timeout' : cls.category;
1068
- return finish(reject, this._failure(category, cls.diagnostic || `idle=${watchdog.timeoutMs}ms`, cls.detail));
1069
- }
1193
+ const outcome = this._settleOutcome({ code, signal, stdout, stderr, timedOut, timeoutMs: watchdog.timeoutMs, responseState, msgChannel });
1194
+ return outcome.error ? finish(reject, outcome.error) : finish(resolve, outcome.text);
1195
+ });
1196
+ });
1197
+ }
1070
1198
 
1071
- if (signal) {
1072
- this._log(`opencode killed by signal ${signal} (output: ${!!stdout})`);
1073
- const cls = this.constructor._classifyFailure({ code, signal, stdout, stderr, stdoutErr });
1074
- return finish(reject, this._failure(cls.category, cls.diagnostic || `signal=${signal}`, cls.detail));
1075
- }
1199
+ /**
1200
+ * What a finished run means, from its exit and its JSON output: `{ text }`
1201
+ * for a reply or `{ error }` (a classified failure). Shared by `opencode run`
1202
+ * and runs on the warm server, so both fail the same way.
1203
+ */
1204
+ _settleOutcome({ code, signal, stdout, stderr, timedOut, timeoutMs, responseState, msgChannel }) {
1205
+ stdout = String(stdout || '').trim();
1206
+ stderr = String(stderr || '').trim();
1207
+
1208
+ // A structured error event may ride on stdout regardless of exit code
1209
+ // (opencode emits {"type":"error", ...} as a JSONL event). Look there
1210
+ // first so the real auth/provider/model failure is never discarded just
1211
+ // because stderr happened to be empty.
1212
+ const stdoutErr = OpenCodeAdapter._extractErrorFromStdout(stdout);
1213
+
1214
+ if (timedOut) {
1215
+ this._log(`opencode timed out after ${timeoutMs / 1000}s idle (output: ${!!stdout})`);
1216
+ const cls = this.constructor._classifyFailure({ code, signal, stdout, stderr, stdoutErr });
1217
+ const category = (cls.category === 'unknown_error' || cls.category === 'process_crashed')
1218
+ ? 'timeout' : cls.category;
1219
+ return { error: this._failure(category, cls.diagnostic || `idle=${timeoutMs}ms`, cls.detail) };
1220
+ }
1221
+
1222
+ if (signal) {
1223
+ this._log(`opencode killed by signal ${signal} (output: ${!!stdout})`);
1224
+ const cls = this.constructor._classifyFailure({ code, signal, stdout, stderr, stdoutErr });
1225
+ return { error: this._failure(cls.category, cls.diagnostic || `signal=${signal}`, cls.detail) };
1226
+ }
1227
+
1228
+ if (code !== 0) {
1229
+ const cls = this.constructor._classifyFailure({ code, signal, stdout, stderr, stdoutErr });
1230
+ this._log(`opencode exited code ${code} → [${cls.category}]: ${this._redact(cls.diagnostic).slice(0, 300)}`);
1231
+ return { error: this._failure(cls.category, cls.diagnostic, cls.detail) };
1232
+ }
1233
+
1234
+ // Exit 0.
1235
+ if (stdout) this._persistSessionId(msgChannel, stdout);
1236
+ const outcome = this.constructor._outcomeForCleanExit({ stdout, stderr, stdoutErr, responseState });
1237
+ if (outcome.text) return { text: outcome.text };
1238
+ const f = outcome.failure;
1239
+ this._log(`opencode exit 0 → [${f.category}]: ${this._redact(f.diagnostic).slice(0, 300)}`);
1240
+ return { error: this._failure(f.category, f.diagnostic, f.detail) };
1241
+ }
1242
+
1243
+ /**
1244
+ * One turn on the warm server (opencode-server.js): the message goes to the
1245
+ * session over HTTP and the server's live events become the same JSON
1246
+ * events `opencode run --format json` prints, so thinking, tool steps and
1247
+ * the reply show exactly as they do today. The finished message the request
1248
+ * returns is the source of truth: parts the live stream missed are replayed
1249
+ * from it. Permission requests are answered `once`, like
1250
+ * --dangerously-skip-permissions (rules that deny still deny). Returns
1251
+ * NO_SERVER when the message should run the ordinary way instead.
1252
+ */
1253
+ async _runViaServer({ msgChannel, runCwd, model, sessionId, fullPrompt, spawnEnv, contextFile = null }) {
1254
+ const slash = String(model || '').indexOf('/');
1255
+ if (slash <= 0) return NO_SERVER;
1256
+ const server = this._getServer();
1257
+ if (!(await server.acquire({ env: spawnEnv, cwd: runCwd }))) return NO_SERVER;
1258
+ if (contextFile) {
1259
+ // The server runs one turn at a time, so this is the only turn reading it.
1260
+ try {
1261
+ fs.mkdirSync(path.dirname(contextFile), { recursive: true });
1262
+ const requesterEmail = this.requesterEmailFor ? this.requesterEmailFor(msgChannel) : null;
1263
+ fs.writeFileSync(contextFile, JSON.stringify({ channel: msgChannel, requesterEmail }), { mode: 0o600 });
1264
+ } catch (e) {
1265
+ this._log(`Could not write the turn context (${e.message}); running this message without the server`, 'error');
1266
+ server.release();
1267
+ return NO_SERVER;
1268
+ }
1269
+ }
1076
1270
 
1077
- if (code !== 0) {
1078
- const cls = this.constructor._classifyFailure({ code, signal, stdout, stderr, stdoutErr });
1079
- this._log(`opencode exited code ${code} → [${cls.category}]: ${this._redact(cls.diagnostic).slice(0, 300)}`);
1080
- return finish(reject, this._failure(cls.category, cls.diagnostic, cls.detail));
1271
+ let sid = sessionId || null;
1272
+ // Stand-in for a child process, so stop and interrupt reach this turn.
1273
+ const proc = new EventEmitter();
1274
+ proc.pid = null;
1275
+ proc.exitCode = null;
1276
+ proc.kill = () => { if (proc.exitCode === null) { proc.exitCode = 0; proc.emit('exit', 0); } };
1277
+ proc.__abortAttached = () => server.abort(sid);
1278
+ this._channelProcesses[msgChannel] = proc;
1279
+
1280
+ const responseState = { finalText: '', allText: '', seenText: false };
1281
+ const lines = [];
1282
+ const emitted = new Set();
1283
+ const roles = {};
1284
+ const early = []; // parts seen before their message's role
1285
+ const children = new Set(); // subagent sessions started from this turn's session
1286
+ let pending = Promise.resolve();
1287
+ let timedOut = false;
1288
+ const watchdog = this._createIdleWatchdog(() => {
1289
+ timedOut = true;
1290
+ this._log(`opencode idle for ${this._runTimeoutMs() / 1000}s; stopping the turn on the server`);
1291
+ server.abort(sid).catch(() => {});
1292
+ });
1293
+ const emit = (part, final = false) => {
1294
+ const event = OpenCodeAdapter._eventForPart(part, final);
1295
+ if (!event) return;
1296
+ const key = `${part.id}:${event.type}`;
1297
+ if (emitted.has(key)) return;
1298
+ emitted.add(key);
1299
+ lines.push(JSON.stringify(event));
1300
+ pending = pending
1301
+ .then(() => this._handleStreamEvent(event, msgChannel, responseState))
1302
+ .catch((e) => this._log(`opencode stream event handling failed: ${e.message}`));
1303
+ };
1304
+ const unsubscribe = server.subscribe((ev) => {
1305
+ const props = (ev && ev.properties) || {};
1306
+ if (!sid) return;
1307
+ if (ev.type === 'message.updated' && props.info && props.info.sessionID === sid) {
1308
+ roles[props.info.id] = props.info.role;
1309
+ for (let k = early.length - 1; k >= 0; k--) {
1310
+ if (roles[early[k].messageID]) { const [part] = early.splice(k, 1); if (roles[part.messageID] === 'assistant') emit(part); }
1081
1311
  }
1312
+ } else if (ev.type === 'session.created' && props.info && props.info.parentID
1313
+ && (props.info.parentID === sid || children.has(props.info.parentID))) {
1314
+ children.add(props.info.id);
1315
+ } else if (ev.type === 'permission.asked' && (props.sessionID === sid || children.has(props.sessionID))) {
1316
+ // A subagent's prompt arrives from its own child session; left
1317
+ // unanswered it held the turn until the idle watchdog stopped it.
1318
+ watchdog.touch();
1319
+ server.replyPermission(props.sessionID, props.id, 'once').catch(() => {});
1320
+ } else if (ev.type === 'message.part.updated' && props.part && props.part.sessionID === sid) {
1321
+ watchdog.touch();
1322
+ const part = props.part;
1323
+ if (!roles[part.messageID]) early.push(part);
1324
+ else if (roles[part.messageID] === 'assistant') emit(part);
1325
+ } else if (ev.type === 'message.part.delta' && props.sessionID === sid) {
1326
+ watchdog.touch();
1327
+ }
1328
+ });
1329
+ const stopping = () => this._stoppingChannels.has(msgChannel);
1330
+ const done = () => {
1331
+ watchdog.cancel();
1332
+ unsubscribe();
1333
+ server.release();
1334
+ if (this._channelProcesses[msgChannel] === proc) delete this._channelProcesses[msgChannel];
1335
+ proc.kill();
1336
+ };
1082
1337
 
1083
- // Exit 0.
1084
- if (stdout) this._persistSessionId(msgChannel, stdout);
1085
- const outcome = this.constructor._outcomeForCleanExit({ stdout, stderr, stdoutErr, responseState });
1086
- if (outcome.text) return finish(resolve, outcome.text);
1087
- const f = outcome.failure;
1088
- this._log(`opencode exit 0 → [${f.category}]: ${this._redact(f.diagnostic).slice(0, 300)}`);
1089
- return finish(reject, this._failure(f.category, f.diagnostic, f.detail));
1338
+ try {
1339
+ try {
1340
+ if (!sid) {
1341
+ sid = (await server.request('POST', '/session', {})).id;
1342
+ this._channelSessions[msgChannel] = sid;
1343
+ this._saveSessions();
1344
+ }
1345
+ } catch (e) {
1346
+ this._log(`OpenCode server could not open a session (${e.message}); running this message without it`, 'error');
1347
+ done();
1348
+ return NO_SERVER;
1349
+ }
1350
+ this._log(`CLI (warm server): message to session ${sid}`);
1351
+ let res;
1352
+ try {
1353
+ res = await server.request('POST', `/session/${encodeURIComponent(sid)}/message`, {
1354
+ model: { providerID: model.slice(0, slash), modelID: model.slice(slash + 1) },
1355
+ parts: [{ type: 'text', text: fullPrompt }],
1356
+ });
1357
+ } catch (e) {
1358
+ if (!emitted.size && !stopping() && !timedOut) {
1359
+ // Nothing happened yet: an unknown session, or a server in trouble.
1360
+ this._log(`OpenCode server turn failed before any output (${e.message}); running this message without it`, 'error');
1361
+ if (e.status !== 404) server.stop();
1362
+ done();
1363
+ return NO_SERVER;
1364
+ }
1365
+ res = null;
1366
+ }
1367
+ for (const part of (res && res.parts) || []) emit(part, true);
1368
+ const info = (res && res.info) || {};
1369
+ if (info.error) lines.push(JSON.stringify({ type: 'error', sessionID: sid, error: info.error }));
1370
+ try { await pending; } catch {}
1371
+ if (stopping()) {
1372
+ this._stoppingChannels.delete(msgChannel);
1373
+ done();
1374
+ return '';
1375
+ }
1376
+ done();
1377
+ const outcome = this._settleOutcome({
1378
+ code: info.error || !res ? 1 : 0, signal: null, stdout: lines.join('\n'), stderr: '',
1379
+ timedOut, timeoutMs: watchdog.timeoutMs, responseState, msgChannel,
1090
1380
  });
1091
- });
1381
+ if (outcome.error) throw outcome.error;
1382
+ return outcome.text;
1383
+ } catch (e) {
1384
+ if (this._channelProcesses[msgChannel] === proc) done();
1385
+ throw e;
1386
+ }
1387
+ }
1388
+
1389
+ /**
1390
+ * The `opencode run --format json` event for a finished message part, or
1391
+ * null while it's still being written (live parts) / for other part types.
1392
+ */
1393
+ static _eventForPart(part, final = false) {
1394
+ if (!part || typeof part !== 'object') return null;
1395
+ const ended = final || Boolean(part.time && part.time.end);
1396
+ const base = { sessionID: part.sessionID, part };
1397
+ switch (part.type) {
1398
+ case 'step-start': return { type: 'step_start', ...base };
1399
+ case 'step-finish': return { type: 'step_finish', ...base };
1400
+ case 'reasoning': return ended ? { type: 'reasoning', ...base } : null;
1401
+ case 'text': return ended && !part.synthetic && !part.ignored ? { type: 'text', ...base } : null;
1402
+ case 'tool': {
1403
+ const status = part.state && part.state.status;
1404
+ return (status === 'completed' || status === 'error') ? { type: 'tool_use', ...base } : null;
1405
+ }
1406
+ default: return null;
1407
+ }
1092
1408
  }
1093
1409
 
1094
1410
  /**
@@ -1466,6 +1782,8 @@ class OpenCodeAdapter extends BaseAdapter {
1466
1782
  let category;
1467
1783
  if (isPostinstallStubOutput(hay)) {
1468
1784
  category = 'install_incomplete';
1785
+ } else if (SHARED_DB_MIGRATED_RE.test(hay)) {
1786
+ category = 'shared_db_migrated';
1469
1787
  } else if (configError) {
1470
1788
  // Checked before the provider patterns: what is wrong with the file is
1471
1789
  // free text ("Unrecognized key: model", "got {…401…}") that would read