@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.
- package/package.json +1 -1
- package/src/adapters/base.js +9 -1
- package/src/adapters/codex.js +104 -8
- package/src/adapters/cursor.js +1 -1
- package/src/adapters/opencode-server.js +254 -0
- package/src/adapters/opencode.js +355 -37
- package/src/adapters/workspace-prompt.js +65 -18
- package/src/cli-models.js +37 -1
- package/src/cli.js +1 -1
- package/src/installer.js +26 -2
- package/src/mcp-server.js +53 -3
- package/src/probe.js +162 -15
- package/src/workspace-client.js +21 -0
package/package.json
CHANGED
package/src/adapters/base.js
CHANGED
|
@@ -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 =
|
|
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.
|
package/src/adapters/codex.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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;
|
|
@@ -518,6 +524,43 @@ class CodexAdapter extends BaseAdapter {
|
|
|
518
524
|
await this._sendRunFailure(msgChannel, result, { partial: true });
|
|
519
525
|
}
|
|
520
526
|
return;
|
|
527
|
+
} else if (!planRetried && !this._effectiveModel() && !this._customProvider
|
|
528
|
+
&& codexPlanRefusedModel(`${result.errorMessage || ''}\n${result.stderr || ''}`)) {
|
|
529
|
+
// No model was chosen, so Codex ran its default, and the ChatGPT
|
|
530
|
+
// plan refused it ("The 'gpt-6.1-sol' model is not supported when
|
|
531
|
+
// using Codex with a ChatGPT account"). Every message failed the
|
|
532
|
+
// same way. Run the first model the account itself lists instead,
|
|
533
|
+
// and keep it for this agent's later messages.
|
|
534
|
+
planRetried = true;
|
|
535
|
+
const refused = codexPlanRefusedModel(`${result.errorMessage || ''}\n${result.stderr || ''}`);
|
|
536
|
+
let fallback = null;
|
|
537
|
+
try { fallback = await codexPlanFallback(this._codexBin, env, refused); } catch {}
|
|
538
|
+
if (!fallback) {
|
|
539
|
+
await this._sendRunFailure(msgChannel, result);
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
this._log(`ChatGPT plan refused ${refused}; running ${fallback}, the first model the account lists`);
|
|
543
|
+
this._planFallbackModel = fallback;
|
|
544
|
+
effectiveModel = fallback;
|
|
545
|
+
env.CODEX_MODEL = fallback;
|
|
546
|
+
try {
|
|
547
|
+
await this.sendStatus(msgChannel, `Codex's default model (${refused}) isn't included in this ChatGPT plan, `
|
|
548
|
+
+ `so this agent now runs ${fallback}. To use another model, pick one in the agent's settings.`);
|
|
549
|
+
} catch {}
|
|
550
|
+
attempt--;
|
|
551
|
+
continue;
|
|
552
|
+
} else if (threadId && attempt === 0 && CodexAdapter._threadTooLarge(result)) {
|
|
553
|
+
// The thread holds an item the API will no longer take, and codex
|
|
554
|
+
// sends the whole thread with every turn, so every later message in
|
|
555
|
+
// this channel failed the same way. Only a new thread runs again.
|
|
556
|
+
this._log(`Thread ${threadId} for ${msgChannel} exceeds an API limit; starting a new one`);
|
|
557
|
+
delete this._channelThreads[msgChannel];
|
|
558
|
+
this._saveSessions();
|
|
559
|
+
try {
|
|
560
|
+
await this.sendStatus(msgChannel, 'This Codex conversation grew past what the model API accepts, '
|
|
561
|
+
+ 'so it continues in a new one. Earlier context in this thread is not carried over.');
|
|
562
|
+
} catch {}
|
|
563
|
+
continue;
|
|
521
564
|
} else if (result.exitCode !== 0 && threadId && attempt === 0 && !result.turnStarted && !CodexAdapter._serviceRefused(result)) {
|
|
522
565
|
// Stale thread — clear and retry fresh. Only when the turn never
|
|
523
566
|
// started: a thread codex cannot resume fails at once with nothing
|
|
@@ -529,6 +572,16 @@ class CodexAdapter extends BaseAdapter {
|
|
|
529
572
|
delete this._channelThreads[msgChannel];
|
|
530
573
|
this._saveSessions();
|
|
531
574
|
continue;
|
|
575
|
+
} else if (fromAgent && CodexAdapter._finishedQuietly(result)) {
|
|
576
|
+
// Another agent wrote ("received", "noted") and codex ended its
|
|
577
|
+
// turn with nothing to add, as the prompt tells it to. Posting
|
|
578
|
+
// "Codex couldn't run" for that read as a failure: the daily errors
|
|
579
|
+
// dashboard of 2026-11-17 had one agent post it 14 times in two
|
|
580
|
+
// minutes while two agents acknowledged each other. A status says
|
|
581
|
+
// so and wakes nobody. A person's message still gets the error.
|
|
582
|
+
this._log(`Turn from another agent in ${msgChannel} ended with no reply; not posting one`);
|
|
583
|
+
try { await this.sendStatus(msgChannel, 'Nothing to add, so no reply was posted.'); } catch {}
|
|
584
|
+
return;
|
|
532
585
|
} else {
|
|
533
586
|
// Surface the actual reason (turn.failed message, stderr, exit code)
|
|
534
587
|
// instead of a generic "no response" — mirrors the OpenCode adapter
|
|
@@ -790,7 +843,11 @@ class CodexAdapter extends BaseAdapter {
|
|
|
790
843
|
* reply, instead of a generic "No response generated".
|
|
791
844
|
*/
|
|
792
845
|
async _sendRunFailure(msgChannel, result, { partial = false } = {}) {
|
|
793
|
-
const detail = CodexAdapter._failureDetail(result, {
|
|
846
|
+
const detail = CodexAdapter._failureDetail(result, {
|
|
847
|
+
customProvider: this._customProvider,
|
|
848
|
+
// What _effectiveModel() reads, plus a plan fallback already picked.
|
|
849
|
+
modelChosen: Boolean(String(this.workspaceModel || this._directModel || this._planFallbackModel || '').trim()),
|
|
850
|
+
});
|
|
794
851
|
if (partial) {
|
|
795
852
|
const body = detail
|
|
796
853
|
? `It stopped before finishing this task.\n\n> ${detail}`
|
|
@@ -814,6 +871,29 @@ class CodexAdapter extends BaseAdapter {
|
|
|
814
871
|
return Boolean(turnFailed) || (exitCode !== 0 && exitCode !== undefined);
|
|
815
872
|
}
|
|
816
873
|
|
|
874
|
+
/**
|
|
875
|
+
* True when codex ended its turn normally and simply wrote no reply: exit
|
|
876
|
+
* 0, no signal, no turn.failed and no error event. Anything else is a run
|
|
877
|
+
* that failed, whoever sent the message.
|
|
878
|
+
*/
|
|
879
|
+
static _finishedQuietly({ exitCode, signal, turnFailed, errorMessage, responseText } = {}) {
|
|
880
|
+
return exitCode === 0 && !signal && !turnFailed
|
|
881
|
+
&& !String(errorMessage || '').trim() && !String(responseText || '').trim();
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
/**
|
|
885
|
+
* True when the API refused the thread itself as too big. Seen as
|
|
886
|
+
* `[ArrayParam] [input[77].content] [array_above_max_length] Invalid
|
|
887
|
+
* 'input[77].content': array too long` on every message of one channel: an
|
|
888
|
+
* item in the history has more content parts than the API allows, and codex
|
|
889
|
+
* resends it each turn. The run's error, else what its stderr gives as the
|
|
890
|
+
* reason (_stderrReason), never a line of its log further up.
|
|
891
|
+
*/
|
|
892
|
+
static _threadTooLarge({ errorMessage, stderr } = {}) {
|
|
893
|
+
const reason = String(errorMessage || '').trim() || CodexAdapter._stderrReason(stderr);
|
|
894
|
+
return /array_above_max_length|context_length_exceeded/i.test(reason);
|
|
895
|
+
}
|
|
896
|
+
|
|
817
897
|
/**
|
|
818
898
|
* True when the model service turned the run away (rate limit, quota,
|
|
819
899
|
* credentials, network) — nothing to do with the thread being resumed. Such
|
|
@@ -838,7 +918,7 @@ class CodexAdapter extends BaseAdapter {
|
|
|
838
918
|
* The cap applies to the quoted reason, before the advice is added, so a
|
|
839
919
|
* long stderr cannot push the advice out of the message.
|
|
840
920
|
*/
|
|
841
|
-
static _failureDetail({ errorMessage, stderr, exitCode, signal } = {}, { customProvider = null } = {}) {
|
|
921
|
+
static _failureDetail({ errorMessage, stderr, exitCode, signal } = {}, { customProvider = null, modelChosen = true } = {}) {
|
|
842
922
|
// A clean exit with no turn.failed and no error event is codex saying the
|
|
843
923
|
// turn finished; it just wrote no reply. Whatever stderr holds then is not
|
|
844
924
|
// why (a skill it skipped, its ChatGPT connector), and quoting it read as
|
|
@@ -849,8 +929,9 @@ class CodexAdapter extends BaseAdapter {
|
|
|
849
929
|
|| (finished ? '' : CodexAdapter._stderrReason(stderr))
|
|
850
930
|
|| (signal ? `codex was terminated by ${signal}` : '')
|
|
851
931
|
|| (exitCode ? `codex exited with code ${exitCode}` : '');
|
|
852
|
-
const
|
|
853
|
-
|
|
932
|
+
const full = CodexAdapter._redact(CodexAdapter._unwrap(raw));
|
|
933
|
+
const reason = full.slice(0, FAILURE_DETAIL_CAP).trim();
|
|
934
|
+
return reason ? CodexAdapter._explain(reason, stderr, { customProvider, modelChosen, full }) : '';
|
|
854
935
|
}
|
|
855
936
|
|
|
856
937
|
/**
|
|
@@ -939,7 +1020,22 @@ class CodexAdapter extends BaseAdapter {
|
|
|
939
1020
|
* match is on the backend's own wording, so an unrelated failure is passed
|
|
940
1021
|
* through untouched.
|
|
941
1022
|
*/
|
|
942
|
-
static _explain(detail, stderr = '', { customProvider = null } = {}) {
|
|
1023
|
+
static _explain(detail, stderr = '', { customProvider = null, modelChosen = true, full = '' } = {}) {
|
|
1024
|
+
// An endpoint that serves other models than the one Codex sent. Seen as
|
|
1025
|
+
// "The supported API model names are deepseek-flash, deepseek-v4-pro, but
|
|
1026
|
+
// you passed gpt-6.1-sol" on every message of an agent pointed at a
|
|
1027
|
+
// DeepSeek-compatible endpoint with no model set: Codex then sends its
|
|
1028
|
+
// own default, which only OpenAI serves. Read from the whole reason: a
|
|
1029
|
+
// long list of names can push "but you passed" past the quoted cap.
|
|
1030
|
+
const served = /supported (?:API )?model names are (.+?),? but you passed ['"`]?([^'"`\s(,]+)/i.exec(full || detail);
|
|
1031
|
+
if (served) {
|
|
1032
|
+
const names = served[1].length > 300 ? `${served[1].slice(0, 300)}…` : served[1];
|
|
1033
|
+
const passed = served[2].replace(/\.+$/, '');
|
|
1034
|
+
const why = modelChosen ? ''
|
|
1035
|
+
: `No model is set for this agent, so Codex sent its own default (${passed}). `;
|
|
1036
|
+
return `${detail}\n\nThis endpoint serves ${names.trim()}. ${why}` +
|
|
1037
|
+
'Pick one of those models for this agent (the model menu in the thread, or the agent\'s settings).';
|
|
1038
|
+
}
|
|
943
1039
|
// A custom Responses endpoint refusing a field Codex always sends. Nothing
|
|
944
1040
|
// the user retries changes that; which endpoint to use, or the chat-only
|
|
945
1041
|
// mode, does.
|
package/src/adapters/cursor.js
CHANGED
|
@@ -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 ` +
|
|
@@ -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 };
|