@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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openagents-org/agent-launcher",
3
- "version": "0.2.228",
3
+ "version": "0.2.230",
4
4
  "description": "OpenAgents Launcher — install, configure, and run AI coding agents from your terminal",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -1540,6 +1540,14 @@ class BaseAdapter {
1540
1540
  }
1541
1541
  }
1542
1542
 
1543
+ /**
1544
+ * A workflow step another agent handed on to this one: sent by an agent,
1545
+ * but standing in for the person who started the workflow.
1546
+ */
1547
+ _isWorkflowHandoff(msg) {
1548
+ return Boolean(msg) && msg.senderType === 'agent' && msg.metadata?.orchestration?.action === 'next';
1549
+ }
1550
+
1543
1551
  /**
1544
1552
  * When the triggering message comes from an identified person, look up the
1545
1553
  * shared context and, if it applies, prepend the instruction block to the
@@ -1548,7 +1556,7 @@ class BaseAdapter {
1548
1556
  */
1549
1557
  _sharedContextEmail(msg) {
1550
1558
  if (!msg) return null;
1551
- const continuation = msg.senderType === 'agent' && msg.metadata?.orchestration?.action === 'next';
1559
+ const continuation = this._isWorkflowHandoff(msg);
1552
1560
  if (msg.senderType !== 'human' && !continuation) return null;
1553
1561
  // Continuations retain the authenticated original requester so the next
1554
1562
  // agent applies the same owner-reviewed shared context and tool identity.
@@ -82,6 +82,7 @@ const FAILURE_MESSAGES = {
82
82
  process_crashed: 'CodeArts Agent exited unexpectedly. Open diagnostics or retry.',
83
83
  cwd_unavailable: "CodeArts Agent's working directory is not accessible. Check the agent's configured path (or agent home) permissions.",
84
84
  config_invalid: 'CodeArts Agent would not start because one of its config files is invalid — the file and what is wrong with it are below. Correct or remove that entry, then retry.',
85
+ malformed_tool_call: "The model sent back a tool call CodeArts Agent 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.",
85
86
  unknown_error: 'CodeArts Agent failed for an undetermined reason. Open diagnostics or retry.',
86
87
  };
87
88
 
@@ -19,6 +19,7 @@ const { execSync } = require('child_process');
19
19
  // spawn() here is the WSL bridge from ../wsl: same signature as
20
20
  // child_process.spawn, and a straight pass-through unless the resolved CLI
21
21
  // lives on the other side of the Windows/WSL boundary.
22
+ const { codexPlanRefusedModel, codexPlanFallback } = require('../cli-models');
22
23
  const { spawn, resolveWslBinary } = require('../wsl');
23
24
  const http = require('http');
24
25
  const https = require('https');
@@ -413,7 +414,9 @@ class CodexAdapter extends BaseAdapter {
413
414
  await this.sendStatus(msgChannel, 'thinking...');
414
415
 
415
416
  if (this._useCliMode) {
416
- await this._handleViaSubprocess(content, msgChannel, attachments);
417
+ // Another agent's message, not a workflow step handed on to this one.
418
+ const fromAgent = msg.senderType === 'agent' && !this._isWorkflowHandoff(msg);
419
+ await this._handleViaSubprocess(content, msgChannel, attachments, { fromAgent });
417
420
  } else if (this._directMode) {
418
421
  await this._handleViaDirectApi(content, msgChannel, attachments);
419
422
  } else {
@@ -431,7 +434,7 @@ class CodexAdapter extends BaseAdapter {
431
434
  return workspaceModel || String(this._directModel || '').trim();
432
435
  }
433
436
 
434
- async _handleViaSubprocess(content, msgChannel, attachments = []) {
437
+ async _handleViaSubprocess(content, msgChannel, attachments = [], { fromAgent = false } = {}) {
435
438
  // A missing cwd fails the spawn itself, and Node blames the shell for it
436
439
  // ("spawn C:\Windows\system32\cmd.exe ENOENT"), which names nothing the
437
440
  // user can fix. A configured folder that was never made (or was cleaned
@@ -445,7 +448,10 @@ class CodexAdapter extends BaseAdapter {
445
448
  }
446
449
 
447
450
  const env = { ...(this.agentEnv || process.env) };
448
- const effectiveModel = this._effectiveModel();
451
+ // No model chosen: Codex's own default, unless the account's plan already
452
+ // refused that once and a model it does list was picked instead.
453
+ let effectiveModel = this._effectiveModel() || this._planFallbackModel || '';
454
+ let planRetried = false;
449
455
 
450
456
  // Set model via env if configured
451
457
  if (effectiveModel) env.CODEX_MODEL = effectiveModel;
@@ -516,19 +522,45 @@ class CodexAdapter extends BaseAdapter {
516
522
  // error left in daemon.log. Say it stopped, and why.
517
523
  if (CodexAdapter._endedEarly(result)) {
518
524
  await this._sendRunFailure(msgChannel, result, { partial: true });
525
+ // Failed after some text (an auto-compaction refused mid-turn):
526
+ // the reply is posted, so no rerun, but the next message must not
527
+ // resume the same thread and fail again.
528
+ const unusable = threadId ? CodexAdapter._unusableThread(result) : null;
529
+ if (unusable) await this._dropThread(msgChannel, unusable);
519
530
  }
520
531
  return;
521
- } else if (threadId && attempt === 0 && CodexAdapter._threadTooLarge(result)) {
522
- // The thread holds an item the API will no longer take, and codex
523
- // sends the whole thread with every turn, so every later message in
524
- // this channel failed the same way. Only a new thread runs again.
525
- this._log(`Thread ${threadId} for ${msgChannel} exceeds an API limit; starting a new one`);
526
- delete this._channelThreads[msgChannel];
527
- this._saveSessions();
532
+ } else if (!planRetried && !this._effectiveModel() && !this._customProvider
533
+ && codexPlanRefusedModel(`${result.errorMessage || ''}\n${result.stderr || ''}`)) {
534
+ // No model was chosen, so Codex ran its default, and the ChatGPT
535
+ // plan refused it ("The 'gpt-6.1-sol' model is not supported when
536
+ // using Codex with a ChatGPT account"). Every message failed the
537
+ // same way. Run the first model the account itself lists instead,
538
+ // and keep it for this agent's later messages.
539
+ planRetried = true;
540
+ const refused = codexPlanRefusedModel(`${result.errorMessage || ''}\n${result.stderr || ''}`);
541
+ let fallback = null;
542
+ try { fallback = await codexPlanFallback(this._codexBin, env, refused); } catch {}
543
+ if (!fallback) {
544
+ await this._sendRunFailure(msgChannel, result);
545
+ return;
546
+ }
547
+ this._log(`ChatGPT plan refused ${refused}; running ${fallback}, the first model the account lists`);
548
+ this._planFallbackModel = fallback;
549
+ effectiveModel = fallback;
550
+ env.CODEX_MODEL = fallback;
528
551
  try {
529
- await this.sendStatus(msgChannel, 'This Codex conversation grew past what the model API accepts, '
530
- + 'so it continues in a new one. Earlier context in this thread is not carried over.');
552
+ await this.sendStatus(msgChannel, `Codex's default model (${refused}) isn't included in this ChatGPT plan, `
553
+ + `so this agent now runs ${fallback}. To use another model, pick one in the agent's settings.`);
531
554
  } catch {}
555
+ attempt--;
556
+ continue;
557
+ } else if (threadId && attempt === 0 && CodexAdapter._unusableThread(result)) {
558
+ // The thread holds something the service will no longer take (an
559
+ // item over an API limit, or reasoning sealed for another account),
560
+ // and codex resends the whole thread with every turn, so every later
561
+ // message in this channel failed the same way. Only a new thread
562
+ // runs again.
563
+ await this._dropThread(msgChannel, CodexAdapter._unusableThread(result));
532
564
  continue;
533
565
  } else if (result.exitCode !== 0 && threadId && attempt === 0 && !result.turnStarted && !CodexAdapter._serviceRefused(result)) {
534
566
  // Stale thread — clear and retry fresh. Only when the turn never
@@ -541,6 +573,19 @@ class CodexAdapter extends BaseAdapter {
541
573
  delete this._channelThreads[msgChannel];
542
574
  this._saveSessions();
543
575
  continue;
576
+ } else if (fromAgent && !result.ranTools && CodexAdapter._finishedQuietly(result)) {
577
+ // Another agent wrote ("received", "noted") and codex ended its
578
+ // turn with nothing to add, as the prompt tells it to. Posting
579
+ // "Codex couldn't run" for that read as a failure: the daily errors
580
+ // dashboard of 2026-11-17 had one agent post it 14 times in two
581
+ // minutes while two agents acknowledged each other. A status says
582
+ // so and wakes nobody. A person's message still gets the error, and
583
+ // so does a turn that ran commands or edited files and then said
584
+ // nothing: that was a task, and whoever asked for it has to hear
585
+ // that no answer came.
586
+ this._log(`Turn from another agent in ${msgChannel} ended with no reply; not posting one`);
587
+ try { await this.sendStatus(msgChannel, 'Nothing to add, so no reply was posted.'); } catch {}
588
+ return;
544
589
  } else {
545
590
  // Surface the actual reason (turn.failed message, stderr, exit code)
546
591
  // instead of a generic "no response" — mirrors the OpenCode adapter
@@ -596,6 +641,7 @@ class CodexAdapter extends BaseAdapter {
596
641
  let lastErrorMessage = '';
597
642
  let turnFailed = false;
598
643
  let turnStarted = false;
644
+ let ranTools = false;
599
645
  let reconnectNoted = false;
600
646
  let _pendingLines = Promise.resolve();
601
647
 
@@ -637,6 +683,7 @@ class CodexAdapter extends BaseAdapter {
637
683
  try { await this.sendThinking(msgChannel, item.text); } catch {}
638
684
  } else if (item.type === 'command_execution') {
639
685
  hasToolUseSinceLastText = true;
686
+ ranTools = true;
640
687
  const cmdText = (item.command || '').slice(0, 200);
641
688
  const exitCode = item.exit_code;
642
689
  const output = (item.output || '').slice(0, 500);
@@ -648,6 +695,7 @@ class CodexAdapter extends BaseAdapter {
648
695
  this._log(`Command: ${cmdText} → exit ${exitCode}`);
649
696
  } else if (item.type === 'file_change') {
650
697
  hasToolUseSinceLastText = true;
698
+ ranTools = true;
651
699
  // codex reports the edited files in `changes`; `filename` is the
652
700
  // legacy shape and was always empty on current CLIs.
653
701
  const filename = Array.isArray(item.changes) && item.changes.length
@@ -713,6 +761,7 @@ class CodexAdapter extends BaseAdapter {
713
761
  errorMessage: lastErrorMessage,
714
762
  turnFailed,
715
763
  turnStarted,
764
+ ranTools,
716
765
  });
717
766
  });
718
767
 
@@ -802,7 +851,11 @@ class CodexAdapter extends BaseAdapter {
802
851
  * reply, instead of a generic "No response generated".
803
852
  */
804
853
  async _sendRunFailure(msgChannel, result, { partial = false } = {}) {
805
- const detail = CodexAdapter._failureDetail(result, { customProvider: this._customProvider });
854
+ const detail = CodexAdapter._failureDetail(result, {
855
+ customProvider: this._customProvider,
856
+ // What _effectiveModel() reads, plus a plan fallback already picked.
857
+ modelChosen: Boolean(String(this.workspaceModel || this._directModel || this._planFallbackModel || '').trim()),
858
+ });
806
859
  if (partial) {
807
860
  const body = detail
808
861
  ? `It stopped before finishing this task.\n\n> ${detail}`
@@ -826,6 +879,16 @@ class CodexAdapter extends BaseAdapter {
826
879
  return Boolean(turnFailed) || (exitCode !== 0 && exitCode !== undefined);
827
880
  }
828
881
 
882
+ /**
883
+ * True when codex ended its turn normally and simply wrote no reply: exit
884
+ * 0, no signal, no turn.failed and no error event. Anything else is a run
885
+ * that failed, whoever sent the message.
886
+ */
887
+ static _finishedQuietly({ exitCode, signal, turnFailed, errorMessage, responseText } = {}) {
888
+ return exitCode === 0 && !signal && !turnFailed
889
+ && !String(errorMessage || '').trim() && !String(responseText || '').trim();
890
+ }
891
+
829
892
  /**
830
893
  * True when the API refused the thread itself as too big. Seen as
831
894
  * `[ArrayParam] [input[77].content] [array_above_max_length] Invalid
@@ -839,6 +902,52 @@ class CodexAdapter extends BaseAdapter {
839
902
  return /array_above_max_length|context_length_exceeded/i.test(reason);
840
903
  }
841
904
 
905
+ /**
906
+ * Why the channel's thread can no longer be resumed, as `{ log, status }`
907
+ * (what the daemon log and the channel are told), or null when it can.
908
+ */
909
+ static _unusableThread(result) {
910
+ if (CodexAdapter._threadTooLarge(result)) {
911
+ return {
912
+ log: 'exceeds an API limit',
913
+ status: 'This Codex conversation grew past what the model API accepts, so it continues in a new one. '
914
+ + 'Earlier context in this thread is not carried over.',
915
+ };
916
+ }
917
+ if (CodexAdapter._threadUnverifiable(result)) {
918
+ return {
919
+ log: 'holds content this account cannot verify',
920
+ status: 'Codex could no longer read back this conversation\'s earlier turns (this happens after Codex is '
921
+ + 'signed in to a different account), so it continues in a new one. Earlier context in this thread is not '
922
+ + 'carried over.',
923
+ };
924
+ }
925
+ return null;
926
+ }
927
+
928
+ /** Forget the channel's thread, and say why in the log and the channel. */
929
+ async _dropThread(msgChannel, { log, status }) {
930
+ this._log(`Thread ${this._channelThreads[msgChannel]} for ${msgChannel} ${log}; starting a new one`);
931
+ delete this._channelThreads[msgChannel];
932
+ this._saveSessions();
933
+ try { await this.sendStatus(msgChannel, status); } catch {}
934
+ }
935
+
936
+ /**
937
+ * True when the service could not verify the thread's encrypted reasoning.
938
+ * Seen as `Error running remote compact task: {"error":{"message":"The
939
+ * encrypted content for item rs_… could not be verified. Reason: Encrypted
940
+ * content item_id did not match the target item id.", "code":
941
+ * "invalid_encrypted_content"}}` on every message of two agents, after their
942
+ * user signed Codex in to another ChatGPT account: the items were sealed for
943
+ * the old one, and codex resends them each turn. The run's error, else what
944
+ * its stderr gives as the reason (_stderrReason), as for _threadTooLarge.
945
+ */
946
+ static _threadUnverifiable({ errorMessage, stderr } = {}) {
947
+ const reason = String(errorMessage || '').trim() || CodexAdapter._stderrReason(stderr);
948
+ return /invalid_encrypted_content|encrypted content\b.{0,120}\bcould not be (?:verified|decrypted)/i.test(reason);
949
+ }
950
+
842
951
  /**
843
952
  * True when the model service turned the run away (rate limit, quota,
844
953
  * credentials, network) — nothing to do with the thread being resumed. Such
@@ -863,7 +972,7 @@ class CodexAdapter extends BaseAdapter {
863
972
  * The cap applies to the quoted reason, before the advice is added, so a
864
973
  * long stderr cannot push the advice out of the message.
865
974
  */
866
- static _failureDetail({ errorMessage, stderr, exitCode, signal } = {}, { customProvider = null } = {}) {
975
+ static _failureDetail({ errorMessage, stderr, exitCode, signal } = {}, { customProvider = null, modelChosen = true } = {}) {
867
976
  // A clean exit with no turn.failed and no error event is codex saying the
868
977
  // turn finished; it just wrote no reply. Whatever stderr holds then is not
869
978
  // why (a skill it skipped, its ChatGPT connector), and quoting it read as
@@ -874,8 +983,9 @@ class CodexAdapter extends BaseAdapter {
874
983
  || (finished ? '' : CodexAdapter._stderrReason(stderr))
875
984
  || (signal ? `codex was terminated by ${signal}` : '')
876
985
  || (exitCode ? `codex exited with code ${exitCode}` : '');
877
- const reason = CodexAdapter._redact(CodexAdapter._unwrap(raw)).slice(0, FAILURE_DETAIL_CAP).trim();
878
- return reason ? CodexAdapter._explain(reason, stderr, { customProvider }) : '';
986
+ const full = CodexAdapter._redact(CodexAdapter._unwrap(raw));
987
+ const reason = full.slice(0, FAILURE_DETAIL_CAP).trim();
988
+ return reason ? CodexAdapter._explain(reason, stderr, { customProvider, modelChosen, full }) : '';
879
989
  }
880
990
 
881
991
  /**
@@ -964,7 +1074,22 @@ class CodexAdapter extends BaseAdapter {
964
1074
  * match is on the backend's own wording, so an unrelated failure is passed
965
1075
  * through untouched.
966
1076
  */
967
- static _explain(detail, stderr = '', { customProvider = null } = {}) {
1077
+ static _explain(detail, stderr = '', { customProvider = null, modelChosen = true, full = '' } = {}) {
1078
+ // An endpoint that serves other models than the one Codex sent. Seen as
1079
+ // "The supported API model names are deepseek-flash, deepseek-v4-pro, but
1080
+ // you passed gpt-6.1-sol" on every message of an agent pointed at a
1081
+ // DeepSeek-compatible endpoint with no model set: Codex then sends its
1082
+ // own default, which only OpenAI serves. Read from the whole reason: a
1083
+ // long list of names can push "but you passed" past the quoted cap.
1084
+ const served = /supported (?:API )?model names are (.+?),? but you passed ['"`]?([^'"`\s(,]+)/i.exec(full || detail);
1085
+ if (served) {
1086
+ const names = served[1].length > 300 ? `${served[1].slice(0, 300)}…` : served[1];
1087
+ const passed = served[2].replace(/\.+$/, '');
1088
+ const why = modelChosen ? ''
1089
+ : `No model is set for this agent, so Codex sent its own default (${passed}). `;
1090
+ return `${detail}\n\nThis endpoint serves ${names.trim()}. ${why}` +
1091
+ 'Pick one of those models for this agent (the model menu in the thread, or the agent\'s settings).';
1092
+ }
968
1093
  // A custom Responses endpoint refusing a field Codex always sends. Nothing
969
1094
  // the user retries changes that; which endpoint to use, or the chat-only
970
1095
  // mode, does.
@@ -371,7 +371,7 @@ class CursorAdapter extends BaseAdapter {
371
371
  // this agent is and exactly which skill file is its interface — otherwise
372
372
  // it can read a sibling's skill and upload under that agent's name.
373
373
  const identityHeader =
374
- `[workspace] You are agent '${this.agentName}'. For ANY workspace ` +
374
+ `[workspace] You are agent '${this.agentName}', answering in channel '${channelName}'. For ANY workspace ` +
375
375
  `operation (messages, files, agents, browser) read and follow ONLY the ` +
376
376
  `'${workspaceSkillName(this.agentName)}' skill. Other ` +
377
377
  `openagents-workspace-* skills belong to OTHER agents and carry the ` +
@@ -95,6 +95,7 @@ const FAILURE_MESSAGES = {
95
95
  cwd_unavailable: "MiMo Code's working directory is not accessible. Check the agent's configured path (or agent home) permissions.",
96
96
  session_missing: 'MiMo Code no longer has this conversation\'s session. Send the message again to start a new one.',
97
97
  config_invalid: 'MiMo Code would not start because one of its config files is invalid — the file and what is wrong with it are below. Correct or remove that entry, then retry.',
98
+ malformed_tool_call: "The model sent back a tool call MiMo Code 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.",
98
99
  unknown_error: 'MiMo Code failed for an undetermined reason. Open diagnostics or retry.',
99
100
  };
100
101
 
@@ -0,0 +1,254 @@
1
+ /**
2
+ * A warm `opencode serve` for one adapter, so a message is sent to a running
3
+ * OpenCode over its HTTP API instead of booting `opencode run` for it. Booting
4
+ * is most of a message's latency: about 5 s before the model is even called,
5
+ * against about 1–2 s on a warm server.
6
+ *
7
+ * (`opencode run --attach` would be simpler, but its client exits after the
8
+ * reasoning and drops the reply — the turn completes on the server, the text
9
+ * never reaches the client. So the adapter talks to the API itself.)
10
+ *
11
+ * A server costs memory (about 220 MB idle, 450 MB once it has run), so:
12
+ * - at most one per adapter, started on demand and stopped after `idleMs`
13
+ * without a run;
14
+ * - it serves one setup (environment, working directory and its config file)
15
+ * and one turn at a time: a message with a different setup restarts it when
16
+ * idle, and a message arriving while it's busy runs the ordinary way;
17
+ * - it listens on 127.0.0.1 only, behind a random password;
18
+ * - anything unusual (it doesn't come up, it dies) means "no server" for that
19
+ * message, and after repeated start failures it stays off for a while.
20
+ *
21
+ * Opt-in: the OpenCode adapter uses it only when OPENAGENTS_OPENCODE_SERVER=1.
22
+ */
23
+ const crypto = require('crypto');
24
+ const fs = require('fs');
25
+ const net = require('net');
26
+ const path = require('path');
27
+ const { spawn } = require('child_process');
28
+
29
+ const IDLE_MS = 5 * 60 * 1000;
30
+ const START_TIMEOUT_MS = 15 * 1000;
31
+ const BACKOFF_MS = 10 * 60 * 1000;
32
+ const MAX_START_FAILURES = 2;
33
+
34
+ function freePort() {
35
+ return new Promise((resolve, reject) => {
36
+ const srv = net.createServer();
37
+ srv.unref();
38
+ srv.on('error', reject);
39
+ srv.listen(0, '127.0.0.1', () => {
40
+ const { port } = srv.address();
41
+ srv.close(() => resolve(port));
42
+ });
43
+ });
44
+ }
45
+
46
+ function reachable(port, timeoutMs = 500) {
47
+ return new Promise((resolve) => {
48
+ const sock = net.createConnection({ host: '127.0.0.1', port });
49
+ const done = (ok) => { sock.destroy(); resolve(ok); };
50
+ sock.setTimeout(timeoutMs, () => done(false));
51
+ sock.once('connect', () => done(true));
52
+ sock.once('error', () => done(false));
53
+ });
54
+ }
55
+
56
+ class OpenCodeServer {
57
+ constructor({ binary, log = () => {}, idleMs = IDLE_MS, startTimeoutMs = START_TIMEOUT_MS } = {}) {
58
+ this.binary = binary;
59
+ this.log = log;
60
+ this.idleMs = idleMs;
61
+ this.startTimeoutMs = startTimeoutMs;
62
+ this._proc = null;
63
+ this._key = null;
64
+ this._url = null;
65
+ this._auth = null;
66
+ this._active = 0;
67
+ this._idleTimer = null;
68
+ this._starting = null;
69
+ this._failures = 0;
70
+ this._offUntil = 0;
71
+ this._listeners = new Set();
72
+ this._events = null; // AbortController of the live event subscription
73
+ }
74
+
75
+ /** What a server is good for: same environment, directory and config file. */
76
+ static keyFor(env, cwd) {
77
+ let config = '';
78
+ try { config = fs.readFileSync(path.join(cwd, '.opencode', 'opencode.json'), 'utf-8'); } catch {}
79
+ return crypto.createHash('sha256').update(JSON.stringify([env, cwd, config])).digest('hex');
80
+ }
81
+
82
+ get running() { return Boolean(this._proc && this._proc.exitCode === null && this._url); }
83
+
84
+ /**
85
+ * True when this server is up for the setup and now held for one run, which
86
+ * must be paired with release(). False: run the ordinary way.
87
+ */
88
+ async acquire({ env, cwd }) {
89
+ if (Date.now() < this._offUntil) return false;
90
+ const key = OpenCodeServer.keyFor(env, cwd);
91
+ if (this._starting) { try { await this._starting; } catch {} }
92
+ // One turn at a time: the turn's context (channel, requester) is the server's.
93
+ if (this._active > 0) return false; // busy: run this message the ordinary way
94
+ if (this.running && this._key === key && await reachable(this._port)) {
95
+ this._take();
96
+ return true;
97
+ }
98
+ this.stop();
99
+ this._starting = this._start({ env, cwd, key });
100
+ try {
101
+ if (!(await this._starting)) return false;
102
+ this._take();
103
+ return true;
104
+ } finally {
105
+ this._starting = null;
106
+ }
107
+ }
108
+
109
+ release() {
110
+ this._active = Math.max(0, this._active - 1);
111
+ if (this._active === 0) this._armIdle();
112
+ }
113
+
114
+ /** JSON request to the server; throws with `status` on HTTP errors. */
115
+ async request(method, urlPath, body, { signal } = {}) {
116
+ if (!this.running) throw Object.assign(new Error('OpenCode server is not running'), { status: 0 });
117
+ const res = await fetch(this._url + urlPath, {
118
+ method, signal,
119
+ headers: { Authorization: this._auth, ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}) },
120
+ body: body !== undefined ? JSON.stringify(body) : undefined,
121
+ });
122
+ const text = await res.text();
123
+ if (!res.ok) throw Object.assign(new Error(`OpenCode server ${method} ${urlPath} → ${res.status}: ${text.slice(0, 300)}`), { status: res.status });
124
+ return text ? JSON.parse(text) : null;
125
+ }
126
+
127
+ /** Receive the server's live events (`{type, properties}`); returns an unsubscribe function. */
128
+ subscribe(fn) {
129
+ this._listeners.add(fn);
130
+ return () => this._listeners.delete(fn);
131
+ }
132
+
133
+ /** Stop a session's turn (a stop, a timeout). */
134
+ async abort(sessionId) {
135
+ if (!sessionId || !this.running) return false;
136
+ try { await this.request('POST', `/session/${encodeURIComponent(sessionId)}/abort`, undefined, { signal: AbortSignal.timeout(5000) }); return true; }
137
+ catch { return false; }
138
+ }
139
+
140
+ /** Answer a permission request (newer servers, then the older per-session route). */
141
+ async replyPermission(sessionId, requestId, reply = 'once') {
142
+ try { await this.request('POST', `/permission/${encodeURIComponent(requestId)}/reply`, { reply }); return true; } catch {}
143
+ try { await this.request('POST', `/session/${encodeURIComponent(sessionId)}/permissions/${encodeURIComponent(requestId)}`, { response: reply }); return true; }
144
+ catch { return false; }
145
+ }
146
+
147
+ stop() {
148
+ clearTimeout(this._idleTimer);
149
+ this._idleTimer = null;
150
+ if (this._events) { this._events.abort(); this._events = null; }
151
+ const proc = this._proc;
152
+ this._proc = null;
153
+ this._url = null;
154
+ this._key = null;
155
+ if (!proc || proc.exitCode !== null) return;
156
+ const kill = (sig) => { try { process.kill(-proc.pid, sig); } catch { try { proc.kill(sig); } catch {} } };
157
+ kill('SIGTERM');
158
+ const t = setTimeout(() => kill('SIGKILL'), 3000);
159
+ t.unref();
160
+ proc.once('exit', () => clearTimeout(t));
161
+ }
162
+
163
+ _take() {
164
+ this._active += 1;
165
+ clearTimeout(this._idleTimer);
166
+ this._idleTimer = null;
167
+ }
168
+
169
+ _armIdle() {
170
+ clearTimeout(this._idleTimer);
171
+ this._idleTimer = setTimeout(() => {
172
+ if (this._active === 0 && this._proc) {
173
+ this.log(`OpenCode server idle for ${Math.round(this.idleMs / 1000)}s; stopping it`);
174
+ this.stop();
175
+ }
176
+ }, this.idleMs);
177
+ this._idleTimer.unref();
178
+ }
179
+
180
+ async _start({ env, cwd, key }) {
181
+ const port = await freePort();
182
+ const password = crypto.randomBytes(24).toString('base64url');
183
+ const started = Date.now();
184
+ let proc;
185
+ try {
186
+ proc = spawn(this.binary, ['serve', '--port', String(port), '--hostname', '127.0.0.1'],
187
+ { env: { ...env, OPENCODE_SERVER_PASSWORD: password }, cwd, stdio: 'ignore', detached: true });
188
+ } catch (e) {
189
+ return this._failed(`could not start (${e.message})`);
190
+ }
191
+ proc.on('error', () => {});
192
+ proc.on('exit', () => {
193
+ if (this._proc !== proc) return;
194
+ this._proc = null; this._url = null; this._key = null;
195
+ if (this._events) { this._events.abort(); this._events = null; }
196
+ });
197
+ while (Date.now() - started < this.startTimeoutMs) {
198
+ if (proc.exitCode !== null) return this._failed(`exited with code ${proc.exitCode}`);
199
+ if (await reachable(port)) {
200
+ this._proc = proc;
201
+ this._port = port;
202
+ this._key = key;
203
+ this._url = `http://127.0.0.1:${port}`;
204
+ this._auth = 'Basic ' + Buffer.from(`opencode:${password}`).toString('base64');
205
+ this._failures = 0;
206
+ this._listen();
207
+ this.log(`OpenCode server ready on port ${port} in ${Date.now() - started}ms`);
208
+ return true;
209
+ }
210
+ await new Promise((r) => setTimeout(r, 150));
211
+ }
212
+ try { process.kill(-proc.pid, 'SIGKILL'); } catch { try { proc.kill('SIGKILL'); } catch {} }
213
+ return this._failed(`not reachable after ${this.startTimeoutMs}ms`);
214
+ }
215
+
216
+ /** One live event stream per server, fanned out to the runs' listeners. */
217
+ _listen() {
218
+ const ctrl = new AbortController();
219
+ this._events = ctrl;
220
+ (async () => {
221
+ try {
222
+ const res = await fetch(this._url + '/event', { headers: { Authorization: this._auth }, signal: ctrl.signal });
223
+ let buf = '';
224
+ const decoder = new TextDecoder();
225
+ for await (const chunk of res.body) {
226
+ buf += decoder.decode(chunk, { stream: true });
227
+ let i;
228
+ while ((i = buf.indexOf('\n')) >= 0) {
229
+ const line = buf.slice(0, i).trim();
230
+ buf = buf.slice(i + 1);
231
+ if (!line.startsWith('data:')) continue;
232
+ let event;
233
+ try { event = JSON.parse(line.slice(5)); } catch { continue; }
234
+ for (const fn of this._listeners) { try { fn(event); } catch {} }
235
+ }
236
+ }
237
+ } catch { /* stopped, or the server went away: runs fall back on the final reply */ }
238
+ })();
239
+ }
240
+
241
+ _failed(why) {
242
+ this._failures += 1;
243
+ if (this._failures >= MAX_START_FAILURES) {
244
+ this._offUntil = Date.now() + BACKOFF_MS;
245
+ this._failures = 0;
246
+ this.log(`OpenCode server ${why}; running without it for ${BACKOFF_MS / 60000} minutes`, 'error');
247
+ } else {
248
+ this.log(`OpenCode server ${why}; running this message without it`, 'error');
249
+ }
250
+ return false;
251
+ }
252
+ }
253
+
254
+ module.exports = { OpenCodeServer };