@openagents-org/agent-launcher 0.2.210 → 0.2.211
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/icons/mimo-code.svg +1 -0
- package/icons/qoder-cn.svg +1 -0
- package/icons/qoder.svg +1 -0
- package/icons/qwen-code.svg +1 -0
- package/package.json +1 -1
- package/registry.json +374 -2
- package/src/adapters/base.js +25 -4
- package/src/adapters/deepseek.js +21 -3
- package/src/adapters/index.js +13 -1
- package/src/adapters/kimi-stream.js +6 -5
- package/src/adapters/mimo-code-runtime.js +266 -0
- package/src/adapters/mimo-code.js +581 -0
- package/src/adapters/opencode.js +21 -16
- package/src/adapters/pi.js +91 -8
- package/src/adapters/qoder-cn.js +24 -0
- package/src/adapters/qoder-runtime.js +611 -0
- package/src/adapters/qoder.js +946 -0
- package/src/adapters/qwen-code-stream.js +735 -0
- package/src/adapters/qwen-code.js +1125 -0
- package/src/agent-login.js +93 -0
- package/src/cli-models.js +45 -2
- package/src/cli.js +94 -0
- package/src/daemon.js +80 -4
- package/src/env.js +3 -0
- package/src/installer.js +49 -17
- package/src/paths.js +21 -0
- package/src/probe.js +44 -1
- package/src/workspace-client.js +12 -1
|
@@ -0,0 +1,946 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Qoder CLI adapter for OpenAgents workspace.
|
|
3
|
+
*
|
|
4
|
+
* Bridges Qoder's terminal agent (`qodercli`, installed by qoder.com/install)
|
|
5
|
+
* to an OpenAgents workspace:
|
|
6
|
+
* - polling loop + per-channel task dispatch (inherited from BaseAdapter)
|
|
7
|
+
* - one headless `qodercli -p -o stream-json` run per user message, prompt
|
|
8
|
+
* piped over stdin
|
|
9
|
+
* - workspace tools over MCP (`--mcp-config` + `--strict-mcp-config`), the
|
|
10
|
+
* same stdio server the Claude adapter wires up
|
|
11
|
+
* - session continuity per channel: a new session gets an id chosen here
|
|
12
|
+
* (`--session-id`), later turns pass `-r <id>`
|
|
13
|
+
*
|
|
14
|
+
* The China edition (`qoderclicn`, qoder.com.cn) is the same CLI under another
|
|
15
|
+
* brand, so QoderCnAdapter (qoder-cn.js) only swaps the edition table.
|
|
16
|
+
*
|
|
17
|
+
* Decisions worth knowing before editing this file (the verified facts behind
|
|
18
|
+
* them are in qoder-runtime.js):
|
|
19
|
+
*
|
|
20
|
+
* THE USER'S CONFIG ROOT STAYS. `--config-dir` / QODER_CONFIG_DIR would
|
|
21
|
+
* isolate a run completely, but the root holds the browser sign-in
|
|
22
|
+
* (<root>/.auth/user): moving it signs the agent out. Isolation is done
|
|
23
|
+
* layer by layer instead — the token in the env (read before any saved
|
|
24
|
+
* sign-in), `-m` (above every settings file), `--strict-mcp-config` (only
|
|
25
|
+
* the workspace server), and a flag settings layer for the rest.
|
|
26
|
+
*
|
|
27
|
+
* NOTHING LANDS IN THE PROJECT OR THE SHELL. Transcripts, memory and plans
|
|
28
|
+
* live under the config root; the one write the CLI makes outside it on a
|
|
29
|
+
* fresh machine — rewriting the shell's rc files — is turned off with
|
|
30
|
+
* <prefix>NO_RC.
|
|
31
|
+
*
|
|
32
|
+
* STOP KILLS THE TREE. The CLI starts its shell commands in sessions of
|
|
33
|
+
* their own and leaves its MCP servers running when terminated, so neither
|
|
34
|
+
* is reached through its process group. The descendants are read from the
|
|
35
|
+
* process table while the CLI is still alive, then signalled one by one
|
|
36
|
+
* (Windows: `taskkill /T`, which walks the same tree).
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
'use strict';
|
|
40
|
+
|
|
41
|
+
const fs = require('fs');
|
|
42
|
+
const os = require('os');
|
|
43
|
+
const path = require('path');
|
|
44
|
+
const crypto = require('crypto');
|
|
45
|
+
const { execFileSync } = require('child_process');
|
|
46
|
+
// spawn() here is the WSL bridge from ../wsl: same signature as
|
|
47
|
+
// child_process.spawn, and a straight pass-through unless the resolved CLI
|
|
48
|
+
// lives on the other side of the Windows/WSL boundary.
|
|
49
|
+
const { spawn } = require('../wsl');
|
|
50
|
+
|
|
51
|
+
const BaseAdapter = require('./base');
|
|
52
|
+
const { formatAttachmentsForPrompt, SESSION_DEFAULT_RE, generateSessionTitle } = require('./utils');
|
|
53
|
+
const { buildClaudeSystemPrompt } = require('./workspace-prompt');
|
|
54
|
+
const { REASON } = require('./health-status');
|
|
55
|
+
const { defaultAgentWorkdir, whichBinary, whereBinary, getEnhancedEnv } = require('../paths');
|
|
56
|
+
const {
|
|
57
|
+
EDITIONS,
|
|
58
|
+
QODER_MIN_VERSION,
|
|
59
|
+
buildQoderArgs,
|
|
60
|
+
buildQoderChildEnv,
|
|
61
|
+
classifyQoderRun,
|
|
62
|
+
classifyQoderVersion,
|
|
63
|
+
descendantsOf,
|
|
64
|
+
installHint,
|
|
65
|
+
interpretQoderFrame,
|
|
66
|
+
modelFallbackNotice,
|
|
67
|
+
parseFrame,
|
|
68
|
+
parseModelFallback,
|
|
69
|
+
parseProcessTable,
|
|
70
|
+
redactArgs,
|
|
71
|
+
redactSecrets,
|
|
72
|
+
resolveQoderAuth,
|
|
73
|
+
truncate,
|
|
74
|
+
} = require('./qoder-runtime');
|
|
75
|
+
|
|
76
|
+
const IS_WINDOWS = process.platform === 'win32';
|
|
77
|
+
|
|
78
|
+
// Idle watchdog: with no stdout frame for this long we nudge the channel, and
|
|
79
|
+
// after MAX consecutive silences we kill a run that is probably wedged. It
|
|
80
|
+
// pauses while a tool call is out: a build or a slow MCP call is legitimately
|
|
81
|
+
// silent until its result comes back.
|
|
82
|
+
const WATCHDOG_INTERVAL_MS = 15000;
|
|
83
|
+
const WATCHDOG_NUDGE_AT = 2; // ~30s of silence → "still working"
|
|
84
|
+
const WATCHDOG_MAX = 20; // ~5 min of silence → kill
|
|
85
|
+
|
|
86
|
+
// The npm edition's floor (`engines.node`); the native binary needs no Node.
|
|
87
|
+
const MIN_NODE_MAJOR = 20;
|
|
88
|
+
|
|
89
|
+
const VERSION_PROBE_TTL_MS = 60000;
|
|
90
|
+
|
|
91
|
+
// SIGTERM ends the CLI in well under a second; the grace is for a wedged one.
|
|
92
|
+
const STOP_GRACE_MS = 3000;
|
|
93
|
+
|
|
94
|
+
class QoderAdapter extends BaseAdapter {
|
|
95
|
+
/** Which edition this adapter drives. QoderCnAdapter overrides it. */
|
|
96
|
+
static get edition() {
|
|
97
|
+
return EDITIONS.global;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* @param {object} opts - BaseAdapter opts plus:
|
|
102
|
+
* @param {Set} [opts.disabledModules]
|
|
103
|
+
* @param {string} [opts.workingDir]
|
|
104
|
+
*/
|
|
105
|
+
constructor(opts) {
|
|
106
|
+
super(opts);
|
|
107
|
+
this.edition = this.constructor.edition;
|
|
108
|
+
this.disabledModules = opts.disabledModules || new Set();
|
|
109
|
+
this._usesPinnedContext = true;
|
|
110
|
+
// channel → { sessionId, workingDir }
|
|
111
|
+
this._channelSessions = {};
|
|
112
|
+
// channel → child process (the in-flight headless run)
|
|
113
|
+
this._channelProcesses = {};
|
|
114
|
+
this._stoppingChannels = new Set();
|
|
115
|
+
this._sessionsFile = path.join(
|
|
116
|
+
os.homedir(), '.openagents', 'sessions',
|
|
117
|
+
`${this.workspaceId}_${this.agentName}_${this.edition.type}.json`,
|
|
118
|
+
);
|
|
119
|
+
this._isWindows = IS_WINDOWS;
|
|
120
|
+
this._versionProbe = null; // { at, bin, version, supported }
|
|
121
|
+
// { requested, used }: the configured model the CLI last fell back from.
|
|
122
|
+
this._modelFallback = null;
|
|
123
|
+
this._watchdogIntervalMs = WATCHDOG_INTERVAL_MS;
|
|
124
|
+
this._watchdogMax = WATCHDOG_MAX;
|
|
125
|
+
this._loadSessions();
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* The model the CLI runs on, so the workspace never shows another one: the
|
|
130
|
+
* one passed with `-m`, unless the CLI last fell back from it.
|
|
131
|
+
*/
|
|
132
|
+
modelLabel() {
|
|
133
|
+
const requested = resolveQoderAuth(this.agentEnv, this.edition, this.workspaceModel).model || null;
|
|
134
|
+
const fb = this._modelFallback;
|
|
135
|
+
return fb && requested && fb.requested === requested ? fb.used : requested;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// ------------------------------------------------------------------
|
|
139
|
+
// Session persistence (bound to the working directory)
|
|
140
|
+
// ------------------------------------------------------------------
|
|
141
|
+
|
|
142
|
+
_loadSessions() {
|
|
143
|
+
try {
|
|
144
|
+
if (fs.existsSync(this._sessionsFile)) {
|
|
145
|
+
const data = JSON.parse(fs.readFileSync(this._sessionsFile, 'utf-8'));
|
|
146
|
+
if (data && typeof data === 'object') {
|
|
147
|
+
Object.assign(this._channelSessions, data);
|
|
148
|
+
this._log(`Loaded ${Object.keys(data).length} ${this.edition.label} session(s)`);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
} catch {
|
|
152
|
+
this._log(`Could not load ${this.edition.label} sessions file, starting fresh`);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
_saveSessions() {
|
|
157
|
+
try {
|
|
158
|
+
fs.mkdirSync(path.dirname(this._sessionsFile), { recursive: true });
|
|
159
|
+
fs.writeFileSync(this._sessionsFile, JSON.stringify(this._channelSessions));
|
|
160
|
+
} catch {}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* A resumable session id for this channel, or null. The CLI files a
|
|
165
|
+
* transcript under the directory it ran in (<root>/projects/<dir>), and
|
|
166
|
+
* `-r` from anywhere else fails — so resume only from the same directory.
|
|
167
|
+
*/
|
|
168
|
+
_resumableSession(channel, workingDir) {
|
|
169
|
+
const entry = this._channelSessions[channel];
|
|
170
|
+
if (!entry || !entry.sessionId) return null;
|
|
171
|
+
if (entry.workingDir && workingDir && entry.workingDir !== workingDir) return null;
|
|
172
|
+
return entry.sessionId;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
_rememberSession(channel, sessionId, workingDir) {
|
|
176
|
+
if (!sessionId) return;
|
|
177
|
+
const prev = this._channelSessions[channel];
|
|
178
|
+
if (prev && prev.sessionId === sessionId && prev.workingDir === workingDir) return;
|
|
179
|
+
this._channelSessions[channel] = { sessionId, workingDir };
|
|
180
|
+
this._saveSessions();
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
_clearSession(channel) {
|
|
184
|
+
if (this._channelSessions[channel]) {
|
|
185
|
+
delete this._channelSessions[channel];
|
|
186
|
+
this._saveSessions();
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// ------------------------------------------------------------------
|
|
191
|
+
// Shutdown
|
|
192
|
+
// ------------------------------------------------------------------
|
|
193
|
+
|
|
194
|
+
stop() {
|
|
195
|
+
super.stop();
|
|
196
|
+
void this._stopAllProcesses('Agent stopped.');
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async _stopAllProcesses(message = 'Execution stopped.') {
|
|
200
|
+
const entries = Object.entries(this._channelProcesses);
|
|
201
|
+
if (!entries.length) return;
|
|
202
|
+
this._log(`Stopping ${entries.length} running ${this.edition.label} process(es)...`);
|
|
203
|
+
for (const [channel, proc] of entries) {
|
|
204
|
+
this._stoppingChannels.add(channel);
|
|
205
|
+
await this._stopProcess(proc);
|
|
206
|
+
delete this._channelProcesses[channel];
|
|
207
|
+
delete this._channelQueues[channel];
|
|
208
|
+
try { await this.sendResponse(channel, message); } catch {}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* End the CLI and everything it started. Resolves true once the CLI is gone.
|
|
214
|
+
*
|
|
215
|
+
* SIGTERM, not SIGINT: during startup (MCP servers still connecting) the CLI
|
|
216
|
+
* sits on SIGINT for ~30s, while SIGTERM ends it in under a second.
|
|
217
|
+
*/
|
|
218
|
+
async _stopProcess(proc) {
|
|
219
|
+
if (!proc || proc.exitCode !== null || proc.signalCode) return true;
|
|
220
|
+
if (this._isWindows) {
|
|
221
|
+
this._killTree(proc.pid);
|
|
222
|
+
let exited = await this._waitExit(proc, STOP_GRACE_MS);
|
|
223
|
+
if (!exited) {
|
|
224
|
+
try { proc.kill(); } catch {}
|
|
225
|
+
exited = await this._waitExit(proc, 1000);
|
|
226
|
+
}
|
|
227
|
+
return exited;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const groups = new Set([proc.pid]);
|
|
231
|
+
const pids = new Set();
|
|
232
|
+
for (const d of descendantsOf(this._processTable(), proc.pid)) {
|
|
233
|
+
pids.add(d.pid);
|
|
234
|
+
if (d.pgid > 1 && d.pgid !== process.pid) groups.add(d.pgid);
|
|
235
|
+
}
|
|
236
|
+
const signal = (sig) => {
|
|
237
|
+
for (const g of groups) { try { process.kill(-g, sig); } catch {} }
|
|
238
|
+
for (const p of pids) { try { process.kill(p, sig); } catch {} }
|
|
239
|
+
try { proc.kill(sig); } catch {}
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
signal('SIGTERM');
|
|
243
|
+
if (await this._waitExit(proc, STOP_GRACE_MS) && ![...pids].some((p) => this._alive(p))) return true;
|
|
244
|
+
signal('SIGKILL');
|
|
245
|
+
return this._waitExit(proc, 1000);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** Kill a Windows process tree. Isolated for testing. */
|
|
249
|
+
_killTree(pid) {
|
|
250
|
+
try {
|
|
251
|
+
execFileSync('taskkill', ['/F', '/T', '/PID', String(pid)], { timeout: 5000, windowsHide: true });
|
|
252
|
+
} catch {}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** The process table as { pid, ppid, pgid } rows. Isolated for testing. */
|
|
256
|
+
_processTable() {
|
|
257
|
+
try {
|
|
258
|
+
return parseProcessTable(execFileSync('ps', ['-A', '-o', 'pid=,ppid=,pgid='], { encoding: 'utf-8', timeout: 3000 }));
|
|
259
|
+
} catch {
|
|
260
|
+
return [];
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
_alive(pid) {
|
|
265
|
+
try { process.kill(pid, 0); return true; } catch (e) { return !!(e && e.code === 'EPERM'); }
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
_waitExit(proc, ms) {
|
|
269
|
+
return new Promise((resolve) => {
|
|
270
|
+
if (proc.exitCode !== null || proc.signalCode) { resolve(true); return; }
|
|
271
|
+
const t = setTimeout(() => resolve(proc.exitCode !== null || !!proc.signalCode), ms);
|
|
272
|
+
proc.once('exit', () => { clearTimeout(t); resolve(true); });
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// ------------------------------------------------------------------
|
|
277
|
+
// Binary resolution (cross-platform)
|
|
278
|
+
// ------------------------------------------------------------------
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Node interpreter for the npm edition's JS entry point: the launcher's
|
|
282
|
+
* managed runtime, else the one running this daemon when it is new enough.
|
|
283
|
+
*/
|
|
284
|
+
_findNodeBin(minMajor = MIN_NODE_MAJOR) {
|
|
285
|
+
const home = os.homedir();
|
|
286
|
+
const candidates = this._isWindows
|
|
287
|
+
? [path.join(home, '.openagents', 'nodejs', 'node.exe')]
|
|
288
|
+
: [path.join(home, '.openagents', 'nodejs', 'node'),
|
|
289
|
+
path.join(home, '.openagents', 'nodejs', 'bin', 'node')];
|
|
290
|
+
for (const c of candidates) {
|
|
291
|
+
if (fs.existsSync(c) && (!minMajor || this._nodeMajor(c) >= minMajor)) return c;
|
|
292
|
+
}
|
|
293
|
+
const ownMajor = parseInt(String(process.versions.node).split('.')[0], 10) || 0;
|
|
294
|
+
return ownMajor >= minMajor ? process.execPath : null;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
_nodeMajor(nodeBin) {
|
|
298
|
+
try {
|
|
299
|
+
const out = execFileSync(nodeBin, ['--version'], { encoding: 'utf-8', timeout: 5000, windowsHide: true });
|
|
300
|
+
const m = String(out).match(/v(\d+)\./);
|
|
301
|
+
return m ? parseInt(m[1], 10) : 0;
|
|
302
|
+
} catch {
|
|
303
|
+
return 0;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Locate the CLI through the shared lookup. Every place an install can land
|
|
309
|
+
* — the official installer's ~/.local/bin link (Unix) and ~/<root>/bin/<bin>
|
|
310
|
+
* dir (Windows, added in paths._addAgentInstallerPaths), the managed
|
|
311
|
+
* ~/.openagents/runtimes/<type> prefix, and npm's global bins — is in
|
|
312
|
+
* getKnownBinDirs, so there is no private candidate list here (see CLAUDE.md).
|
|
313
|
+
*/
|
|
314
|
+
_findQoderBinary() {
|
|
315
|
+
return whichBinary(this.edition.bin) || null;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** Daemon gate before join: a missing CLI is reported, not joined. */
|
|
319
|
+
preflight() {
|
|
320
|
+
const bin = this._findQoderBinary();
|
|
321
|
+
if (!bin) {
|
|
322
|
+
return {
|
|
323
|
+
ok: false,
|
|
324
|
+
reason: REASON.RUNTIME_MISSING,
|
|
325
|
+
message: `${this.edition.label} not found — install it with: ${installHint(this.edition)}`,
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
this._log(`${this.edition.label} resolved: ${bin}`);
|
|
329
|
+
return { ok: true };
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Resolve an npm shim to [nodeBin, jsEntry]; null for the native binary or
|
|
334
|
+
* when no suitable Node exists. Running the entry directly keeps a Windows
|
|
335
|
+
* .cmd shim — and cmd.exe's 8191-character command line, which the
|
|
336
|
+
* kilobytes of briefing in argv would overflow — out of the path.
|
|
337
|
+
*/
|
|
338
|
+
_resolveToNodeCmd(binPath) {
|
|
339
|
+
if (this._isWindows && binPath.toLowerCase().endsWith('.cmd')) {
|
|
340
|
+
try {
|
|
341
|
+
const cmdDir = path.dirname(path.resolve(binPath));
|
|
342
|
+
const content = fs.readFileSync(binPath, 'utf-8');
|
|
343
|
+
const jsMatch = content.match(/%dp0%\\([^\s"*?]+\.m?js)/i);
|
|
344
|
+
if (jsMatch) {
|
|
345
|
+
const target = path.resolve(cmdDir, jsMatch[1]);
|
|
346
|
+
const nodeBin = fs.existsSync(target) ? this._findNodeBin() : null;
|
|
347
|
+
if (nodeBin) return [nodeBin, target];
|
|
348
|
+
}
|
|
349
|
+
} catch {}
|
|
350
|
+
return null;
|
|
351
|
+
}
|
|
352
|
+
try {
|
|
353
|
+
let target = binPath;
|
|
354
|
+
if (fs.lstatSync(binPath).isSymbolicLink()) {
|
|
355
|
+
target = path.resolve(path.dirname(binPath), fs.readlinkSync(binPath));
|
|
356
|
+
}
|
|
357
|
+
if (/\.(c|m)?js$/.test(target) || this._isNodeShebangScript(target)) {
|
|
358
|
+
const nodeBin = this._findNodeBin();
|
|
359
|
+
return nodeBin ? [nodeBin, target] : null;
|
|
360
|
+
}
|
|
361
|
+
} catch {}
|
|
362
|
+
return null;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
_isNodeShebangScript(filePath) {
|
|
366
|
+
try {
|
|
367
|
+
const fd = fs.openSync(filePath, 'r');
|
|
368
|
+
try {
|
|
369
|
+
const buf = Buffer.alloc(64);
|
|
370
|
+
const n = fs.readSync(fd, buf, 0, 64, 0);
|
|
371
|
+
const head = buf.slice(0, n).toString('utf-8');
|
|
372
|
+
return head.startsWith('#!') && /\bnode\b/.test(head.split('\n')[0]);
|
|
373
|
+
} finally {
|
|
374
|
+
fs.closeSync(fd);
|
|
375
|
+
}
|
|
376
|
+
} catch {
|
|
377
|
+
return false;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* How to spawn the CLI: { command, args }. Throws when a Windows npm shim
|
|
383
|
+
* cannot be run directly: routing it through `cmd.exe /c` would hand the
|
|
384
|
+
* multi-KB briefing (user-pinned text included) to cmd's parser, where `"`,
|
|
385
|
+
* `&` and `|` are live, and overflow its 8191-character line besides.
|
|
386
|
+
*/
|
|
387
|
+
_spawnPlan(binPath, args) {
|
|
388
|
+
const resolved = this._resolveToNodeCmd(binPath);
|
|
389
|
+
if (resolved) return { command: resolved[0], args: [resolved[1], ...args] };
|
|
390
|
+
if (this._isWindows && binPath.toLowerCase().endsWith('.cmd')) {
|
|
391
|
+
const label = this.edition.label;
|
|
392
|
+
throw new Error(this._findNodeBin()
|
|
393
|
+
? `${label}'s npm shim ${binPath} does not name its entry script; reinstall ${label} with the official installer`
|
|
394
|
+
: `${label} (npm install) needs Node.js >= ${MIN_NODE_MAJOR} to run here and none was found; ` +
|
|
395
|
+
`install Node.js ${MIN_NODE_MAJOR}+ or reinstall ${label} with the official installer`);
|
|
396
|
+
}
|
|
397
|
+
return { command: binPath, args };
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// ------------------------------------------------------------------
|
|
401
|
+
// Version preflight (cached; HARD minimum QODER_MIN_VERSION)
|
|
402
|
+
// ------------------------------------------------------------------
|
|
403
|
+
|
|
404
|
+
/** Run `--version` and return raw output. Isolated for testing. */
|
|
405
|
+
_readVersionRaw(bin) {
|
|
406
|
+
try {
|
|
407
|
+
const plan = this._spawnPlan(bin, ['--version']);
|
|
408
|
+
return execFileSync(plan.command, plan.args, {
|
|
409
|
+
encoding: 'utf-8',
|
|
410
|
+
timeout: 15000,
|
|
411
|
+
windowsHide: true,
|
|
412
|
+
env: buildQoderChildEnv(getEnhancedEnv(this.agentEnv), { edition: this.edition }),
|
|
413
|
+
});
|
|
414
|
+
} catch (e) {
|
|
415
|
+
return (e && (e.stdout || e.stderr)) ? String(e.stdout || e.stderr) : '';
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
_checkVersion(bin) {
|
|
420
|
+
const now = Date.now();
|
|
421
|
+
if (this._versionProbe && this._versionProbe.bin === bin && now - this._versionProbe.at < VERSION_PROBE_TTL_MS) {
|
|
422
|
+
return this._versionProbe;
|
|
423
|
+
}
|
|
424
|
+
const verdict = classifyQoderVersion(this._readVersionRaw(bin));
|
|
425
|
+
this._versionProbe = { ...verdict, bin, at: now };
|
|
426
|
+
return this._versionProbe;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// ------------------------------------------------------------------
|
|
430
|
+
// Workspace MCP server
|
|
431
|
+
// ------------------------------------------------------------------
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* Write the MCP config that gives this run the workspace_* tools, and return
|
|
435
|
+
* its path (null when the server cannot be located or the file cannot be
|
|
436
|
+
* written — the run proceeds without workspace tools, and still without the
|
|
437
|
+
* user's MCP servers). It carries the workspace token, so it is 0600
|
|
438
|
+
* in an OpenAgents directory, never the project or the CLI's config root,
|
|
439
|
+
* and the caller deletes it when the run ends.
|
|
440
|
+
*/
|
|
441
|
+
_writeMcpConfig(channel) {
|
|
442
|
+
try {
|
|
443
|
+
const mcpArgs = [
|
|
444
|
+
'mcp-server',
|
|
445
|
+
'--workspace-id', this.workspaceId,
|
|
446
|
+
'--channel-name', channel,
|
|
447
|
+
'--agent-name', this.agentName,
|
|
448
|
+
'--endpoint', this.endpoint,
|
|
449
|
+
];
|
|
450
|
+
if (this.disabledModules.has('files')) mcpArgs.push('--disable-files');
|
|
451
|
+
if (this.disabledModules.has('browser')) mcpArgs.push('--disable-browser');
|
|
452
|
+
if (this.disabledModules.has('knowledge')) mcpArgs.push('--disable-knowledge');
|
|
453
|
+
|
|
454
|
+
const resolved = this._resolveMcpServerCmd(mcpArgs);
|
|
455
|
+
if (!resolved) {
|
|
456
|
+
this._log('Could not find the openagents binary — workspace MCP tools are unavailable this run');
|
|
457
|
+
return null;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
const config = {
|
|
461
|
+
mcpServers: {
|
|
462
|
+
'openagents-workspace': {
|
|
463
|
+
command: resolved.command,
|
|
464
|
+
args: resolved.args,
|
|
465
|
+
env: { OA_WORKSPACE_TOKEN: this.token },
|
|
466
|
+
},
|
|
467
|
+
},
|
|
468
|
+
};
|
|
469
|
+
|
|
470
|
+
const dir = path.join(os.homedir(), '.openagents', 'mcp-configs');
|
|
471
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
472
|
+
const file = path.join(dir, `${this.edition.type}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`);
|
|
473
|
+
fs.writeFileSync(file, JSON.stringify(config), { mode: 0o600 });
|
|
474
|
+
try { fs.chmodSync(file, 0o600); } catch {}
|
|
475
|
+
return file;
|
|
476
|
+
} catch (e) {
|
|
477
|
+
this._log(`Could not write the MCP config: ${this._redact(e && e.message)}`, 'warn');
|
|
478
|
+
return null;
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/** Locate this package's own CLI, which hosts the workspace MCP server. */
|
|
483
|
+
_resolveMcpServerCmd(mcpArgs) {
|
|
484
|
+
const siblingBin = path.resolve(__dirname, '..', '..', 'bin', 'agent-connector.js');
|
|
485
|
+
if (fs.existsSync(siblingBin)) {
|
|
486
|
+
// The MCP server is this package's own code: any Node that runs the
|
|
487
|
+
// daemon runs it.
|
|
488
|
+
return { command: this._findNodeBin(0), args: [siblingBin, ...mcpArgs] };
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
const home = os.homedir();
|
|
492
|
+
const ext = this._isWindows ? '.cmd' : '';
|
|
493
|
+
const candidates = [];
|
|
494
|
+
try {
|
|
495
|
+
const runtimesRoot = path.join(home, '.openagents', 'runtimes');
|
|
496
|
+
for (const d of fs.readdirSync(runtimesRoot, { withFileTypes: true })) {
|
|
497
|
+
if (d.isDirectory()) {
|
|
498
|
+
candidates.push(path.join(runtimesRoot, d.name, 'node_modules', '.bin', `openagents${ext}`));
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
} catch {}
|
|
502
|
+
candidates.push(path.join(home, '.openagents', 'nodejs', 'node_modules', '.bin', `openagents${ext}`));
|
|
503
|
+
|
|
504
|
+
let bin = candidates.find((c) => fs.existsSync(c)) || null;
|
|
505
|
+
if (!bin) bin = whereBinary('openagents');
|
|
506
|
+
if (!bin) return null;
|
|
507
|
+
|
|
508
|
+
const resolved = this._resolveToNodeCmd(bin);
|
|
509
|
+
if (resolved) return { command: resolved[0], args: [...resolved.slice(1), ...mcpArgs] };
|
|
510
|
+
return { command: bin, args: mcpArgs };
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
// ------------------------------------------------------------------
|
|
514
|
+
// Prompt assembly
|
|
515
|
+
// ------------------------------------------------------------------
|
|
516
|
+
|
|
517
|
+
/** Recent channel chat, to seed a fresh session (a resumed one has it). */
|
|
518
|
+
async _buildChannelRecap(channel, currentMessage) {
|
|
519
|
+
try {
|
|
520
|
+
const messages = await this.client.getRecentMessages(this.workspaceId, channel, this.token, 30);
|
|
521
|
+
if (!messages || messages.length === 0) return null;
|
|
522
|
+
const lines = [];
|
|
523
|
+
for (const m of messages) {
|
|
524
|
+
const mt = m.messageType || 'chat';
|
|
525
|
+
if (mt === 'status' || mt === 'thinking' || mt === 'loading' || mt === 'todos') continue;
|
|
526
|
+
const text = (m.content || '').trim();
|
|
527
|
+
if (!text || text === currentMessage) continue;
|
|
528
|
+
const who = m.senderType === 'human' ? (m.senderName || 'user') : (m.senderName || 'agent');
|
|
529
|
+
lines.push(`[${who}] ${truncate(text, 800)}`);
|
|
530
|
+
}
|
|
531
|
+
if (lines.length === 0) return null;
|
|
532
|
+
return 'Recent conversation in this channel for context:\n\n' + lines.slice(-12).join('\n');
|
|
533
|
+
} catch {
|
|
534
|
+
return null;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
_dirExists(p) {
|
|
539
|
+
try { return fs.statSync(p).isDirectory(); } catch { return false; }
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// ------------------------------------------------------------------
|
|
543
|
+
// Run
|
|
544
|
+
// ------------------------------------------------------------------
|
|
545
|
+
|
|
546
|
+
/**
|
|
547
|
+
* Run one headless turn and consume its stream-json output. The reply comes
|
|
548
|
+
* off the `result` frame; assistant frames only drive the live ticker.
|
|
549
|
+
*
|
|
550
|
+
* @returns {Promise<object>} { code, signal, result, sessionId, model,
|
|
551
|
+
* anyOutput, lastAssistantText, apiErrors, userStopped, stderr }
|
|
552
|
+
*/
|
|
553
|
+
_runQoder(channel, bin, args, workingDir, prompt, env = {}, secrets = []) {
|
|
554
|
+
// Stopped while this turn was being prepared: start nothing.
|
|
555
|
+
if (this._stoppedBeforeStart(channel)) return Promise.resolve({ userStopped: true });
|
|
556
|
+
return new Promise((resolve) => {
|
|
557
|
+
let plan;
|
|
558
|
+
try {
|
|
559
|
+
plan = this._spawnPlan(bin, args);
|
|
560
|
+
} catch (e) {
|
|
561
|
+
resolve({ code: null, signal: null, result: null, sessionId: null, anyOutput: false, userStopped: false, spawnError: e && e.message });
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
this._log(`Spawning: ${path.basename(plan.command)} ${redactArgs(plan.args).join(' ')} (cwd=${workingDir})`);
|
|
565
|
+
|
|
566
|
+
let proc;
|
|
567
|
+
try {
|
|
568
|
+
proc = spawn(plan.command, plan.args, {
|
|
569
|
+
cwd: workingDir,
|
|
570
|
+
env,
|
|
571
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
572
|
+
// Own process group: a stop reaches the CLI and the MCP servers it
|
|
573
|
+
// started (its shell commands are walked separately).
|
|
574
|
+
detached: !this._isWindows,
|
|
575
|
+
windowsHide: true,
|
|
576
|
+
});
|
|
577
|
+
} catch (e) {
|
|
578
|
+
resolve({ code: null, signal: null, result: null, sessionId: null, anyOutput: false, userStopped: false, spawnError: e && e.message });
|
|
579
|
+
return;
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
this._channelProcesses[channel] = proc;
|
|
583
|
+
|
|
584
|
+
let settled = false;
|
|
585
|
+
let stdoutBuf = '';
|
|
586
|
+
let stderrBuf = '';
|
|
587
|
+
let anyOutput = false;
|
|
588
|
+
let result = null;
|
|
589
|
+
let sessionId = null;
|
|
590
|
+
let model = null;
|
|
591
|
+
let lastAssistantText = '';
|
|
592
|
+
const apiErrors = [];
|
|
593
|
+
let lastFrameAt = Date.now();
|
|
594
|
+
let silences = 0;
|
|
595
|
+
let lastToolLabel = null;
|
|
596
|
+
const toolsInFlight = new Set(); // tool_use ids still waiting on a result
|
|
597
|
+
let killedByWatchdog = false;
|
|
598
|
+
let exitInfo = null;
|
|
599
|
+
let closeFallback = null;
|
|
600
|
+
|
|
601
|
+
const finish = (payload) => {
|
|
602
|
+
if (settled) return;
|
|
603
|
+
settled = true;
|
|
604
|
+
clearInterval(watchdog);
|
|
605
|
+
if (closeFallback) clearTimeout(closeFallback);
|
|
606
|
+
if (this._channelProcesses[channel] === proc) delete this._channelProcesses[channel];
|
|
607
|
+
resolve(payload);
|
|
608
|
+
};
|
|
609
|
+
|
|
610
|
+
const onFrame = (line) => {
|
|
611
|
+
const frame = parseFrame(line);
|
|
612
|
+
if (!frame) return;
|
|
613
|
+
lastFrameAt = Date.now();
|
|
614
|
+
silences = 0;
|
|
615
|
+
anyOutput = true;
|
|
616
|
+
|
|
617
|
+
const ev = interpretQoderFrame(frame, secrets);
|
|
618
|
+
if (ev.kind === 'result') {
|
|
619
|
+
toolsInFlight.clear();
|
|
620
|
+
result = ev;
|
|
621
|
+
if (ev.sessionId) sessionId = ev.sessionId;
|
|
622
|
+
return;
|
|
623
|
+
}
|
|
624
|
+
if (ev.kind === 'init') {
|
|
625
|
+
if (ev.sessionId) sessionId = ev.sessionId;
|
|
626
|
+
if (ev.model) model = ev.model;
|
|
627
|
+
for (const s of ev.mcpServers) {
|
|
628
|
+
if (s && s.status && s.status !== 'connected') {
|
|
629
|
+
this._log(`MCP server ${s.name} is ${s.status} — its tools are unavailable this run`);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
return;
|
|
633
|
+
}
|
|
634
|
+
if (ev.kind === 'assistant') {
|
|
635
|
+
if (ev.apiError) {
|
|
636
|
+
apiErrors.push(ev.apiError);
|
|
637
|
+
return;
|
|
638
|
+
}
|
|
639
|
+
if (ev.texts.length) lastAssistantText = ev.texts.join('\n');
|
|
640
|
+
for (const text of ev.texts) {
|
|
641
|
+
void this.sendThinking(channel, text).catch(() => {});
|
|
642
|
+
}
|
|
643
|
+
for (const tool of ev.tools) {
|
|
644
|
+
if (tool.id) toolsInFlight.add(tool.id);
|
|
645
|
+
if (tool.todos) {
|
|
646
|
+
const wsTodos = tool.todos.map((t) => ({
|
|
647
|
+
content: t.content, status: t.status || 'pending', assignee: t.assignee,
|
|
648
|
+
}));
|
|
649
|
+
void this.sendTodos(channel, wsTodos).catch(() => {});
|
|
650
|
+
}
|
|
651
|
+
// Only announce a CHANGE of activity.
|
|
652
|
+
const label = tool.preview ? `${tool.name} › ${tool.preview}` : tool.name;
|
|
653
|
+
if (label && label !== lastToolLabel) {
|
|
654
|
+
lastToolLabel = label;
|
|
655
|
+
void this.sendStatus(channel, label).catch(() => {});
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
return;
|
|
659
|
+
}
|
|
660
|
+
if (ev.kind === 'tool_results') {
|
|
661
|
+
// A result that names no call can't be matched: stop pausing.
|
|
662
|
+
if (ev.ids.includes(null)) toolsInFlight.clear();
|
|
663
|
+
for (const id of ev.ids) toolsInFlight.delete(id);
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
if (ev.kind === 'status') {
|
|
667
|
+
void this.sendStatus(channel, ev.text).catch(() => {});
|
|
668
|
+
return;
|
|
669
|
+
}
|
|
670
|
+
if (ev.kind === 'unknown') {
|
|
671
|
+
this._log(`Unrecognized frame (ignored): ${ev.raw}`);
|
|
672
|
+
}
|
|
673
|
+
};
|
|
674
|
+
|
|
675
|
+
const done = () => {
|
|
676
|
+
if (settled) return;
|
|
677
|
+
if (stdoutBuf.trim()) { try { onFrame(stdoutBuf); } catch {} stdoutBuf = ''; }
|
|
678
|
+
const userStopped = this._stoppingChannels.has(channel);
|
|
679
|
+
this._stoppingChannels.delete(channel);
|
|
680
|
+
const { code = null, signal = null } = exitInfo || {};
|
|
681
|
+
finish({
|
|
682
|
+
code,
|
|
683
|
+
signal: killedByWatchdog ? 'SIGKILL' : signal,
|
|
684
|
+
result,
|
|
685
|
+
sessionId,
|
|
686
|
+
model,
|
|
687
|
+
anyOutput,
|
|
688
|
+
lastAssistantText,
|
|
689
|
+
apiErrors,
|
|
690
|
+
userStopped,
|
|
691
|
+
stderr: redactSecrets(stderrBuf, secrets),
|
|
692
|
+
});
|
|
693
|
+
};
|
|
694
|
+
|
|
695
|
+
// A killed child's pipes can emit 'error' (EPIPE/ECONNRESET); unhandled,
|
|
696
|
+
// that would take the daemon down.
|
|
697
|
+
proc.stdout.on('error', () => {});
|
|
698
|
+
proc.stderr.on('error', () => {});
|
|
699
|
+
proc.stdout.setEncoding('utf8');
|
|
700
|
+
proc.stderr.setEncoding('utf8');
|
|
701
|
+
|
|
702
|
+
proc.stdout.on('data', (chunk) => {
|
|
703
|
+
stdoutBuf += chunk;
|
|
704
|
+
let nl;
|
|
705
|
+
while ((nl = stdoutBuf.indexOf('\n')) !== -1) {
|
|
706
|
+
const line = stdoutBuf.slice(0, nl);
|
|
707
|
+
stdoutBuf = stdoutBuf.slice(nl + 1);
|
|
708
|
+
try { onFrame(line); } catch (e) { this._log(`Frame handling failed: ${redactSecrets(e && e.message, secrets)}`); }
|
|
709
|
+
}
|
|
710
|
+
});
|
|
711
|
+
|
|
712
|
+
proc.stderr.on('data', (chunk) => {
|
|
713
|
+
stderrBuf = truncate(stderrBuf + chunk, 8000);
|
|
714
|
+
});
|
|
715
|
+
|
|
716
|
+
proc.on('error', (e) => {
|
|
717
|
+
finish({ code: null, signal: null, result, sessionId, anyOutput, lastAssistantText, apiErrors, userStopped: false, spawnError: e && e.message });
|
|
718
|
+
});
|
|
719
|
+
|
|
720
|
+
proc.on('exit', (code, signal) => {
|
|
721
|
+
exitInfo = { code, signal };
|
|
722
|
+
// 'close' waits for every holder of the pipes; an MCP server the CLI
|
|
723
|
+
// left running would keep them open and the turn would never end.
|
|
724
|
+
closeFallback = setTimeout(done, 2000);
|
|
725
|
+
});
|
|
726
|
+
|
|
727
|
+
proc.on('close', (code, signal) => {
|
|
728
|
+
if (!exitInfo) exitInfo = { code, signal };
|
|
729
|
+
done();
|
|
730
|
+
});
|
|
731
|
+
|
|
732
|
+
const watchdog = setInterval(() => {
|
|
733
|
+
if (toolsInFlight.size) { silences = 0; return; }
|
|
734
|
+
if (Date.now() - lastFrameAt < this._watchdogIntervalMs) return;
|
|
735
|
+
silences += 1;
|
|
736
|
+
if (silences === WATCHDOG_NUDGE_AT) {
|
|
737
|
+
void this.sendStatus(channel, 'still working...').catch(() => {});
|
|
738
|
+
}
|
|
739
|
+
if (silences >= this._watchdogMax) {
|
|
740
|
+
this._log('No output for ~5 minutes — killing a wedged run');
|
|
741
|
+
killedByWatchdog = true;
|
|
742
|
+
void this._stopProcess(proc);
|
|
743
|
+
}
|
|
744
|
+
}, this._watchdogIntervalMs);
|
|
745
|
+
|
|
746
|
+
try {
|
|
747
|
+
proc.stdin.on('error', () => {});
|
|
748
|
+
proc.stdin.write(prompt, 'utf-8');
|
|
749
|
+
proc.stdin.end();
|
|
750
|
+
} catch (e) {
|
|
751
|
+
this._log(`Could not write the prompt to stdin: ${redactSecrets(e && e.message, secrets)}`);
|
|
752
|
+
}
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
// ------------------------------------------------------------------
|
|
757
|
+
// Message handling
|
|
758
|
+
// ------------------------------------------------------------------
|
|
759
|
+
|
|
760
|
+
async _handleMessage(msg) {
|
|
761
|
+
let content = (msg.content || '').trim();
|
|
762
|
+
const attachments = msg.attachments || [];
|
|
763
|
+
const attText = formatAttachmentsForPrompt(attachments, 'mcp');
|
|
764
|
+
if (attText) content = content ? content + attText : attText.trim();
|
|
765
|
+
if (!content) return;
|
|
766
|
+
|
|
767
|
+
const label = this.edition.label;
|
|
768
|
+
const channel = msg.sessionId || this.channelName;
|
|
769
|
+
this._stoppingChannels.delete(channel);
|
|
770
|
+
const sender = msg.senderName || msg.senderType || 'user';
|
|
771
|
+
this._log(`Processing message from ${sender} in ${channel}: ${this._redact(truncate(content, 80))}`);
|
|
772
|
+
|
|
773
|
+
// Never silently fall back to the launcher/repo dir.
|
|
774
|
+
const workingDir = this.workingDir || defaultAgentWorkdir(this.agentName);
|
|
775
|
+
if (this.workingDir && !this._dirExists(this.workingDir)) {
|
|
776
|
+
await this.sendError(channel, `Working directory does not exist: ${this.workingDir}`);
|
|
777
|
+
return;
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
const bin = this._findQoderBinary();
|
|
781
|
+
if (!bin) {
|
|
782
|
+
await this.sendError(channel, `${label} not found. Install it with: ${installHint(this.edition)}`);
|
|
783
|
+
return;
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
const ver = this._checkVersion(bin);
|
|
787
|
+
if (ver.supported === false) {
|
|
788
|
+
this._log(`Refusing to start: ${label} ${ver.version} < minimum ${QODER_MIN_VERSION}`, 'warn');
|
|
789
|
+
await this.sendError(channel,
|
|
790
|
+
`${label} ${ver.version} is below the minimum supported version ${QODER_MIN_VERSION}. ` +
|
|
791
|
+
`Upgrade with: ${installHint(this.edition)}`);
|
|
792
|
+
return;
|
|
793
|
+
}
|
|
794
|
+
if (ver.supported === null) {
|
|
795
|
+
this._log(`Could not determine the ${label} version — proceeding leniently`);
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
// Auto-title + resume-from on first encounter (parity with other adapters).
|
|
799
|
+
if (!this._titledSessions.has(channel)) {
|
|
800
|
+
this._titledSessions.add(channel);
|
|
801
|
+
try {
|
|
802
|
+
const info = await this.client.getSession(this.workspaceId, channel, this.token);
|
|
803
|
+
const resumeFrom = info.resumeFrom;
|
|
804
|
+
if (resumeFrom && !this._channelSessions[channel] && this._channelSessions[resumeFrom]) {
|
|
805
|
+
this._channelSessions[channel] = { ...this._channelSessions[resumeFrom] };
|
|
806
|
+
this._saveSessions();
|
|
807
|
+
}
|
|
808
|
+
const title = generateSessionTitle(content);
|
|
809
|
+
if (title && !info.titleManuallySet && SESSION_DEFAULT_RE.test(info.title || '')) {
|
|
810
|
+
await this.client.updateSession(this.workspaceId, channel, this.token, { title, autoTitle: true });
|
|
811
|
+
}
|
|
812
|
+
} catch {}
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
await this.sendStatus(channel, 'thinking...');
|
|
816
|
+
|
|
817
|
+
const auth = resolveQoderAuth(this.agentEnv, this.edition, this.workspaceModel);
|
|
818
|
+
const browserEnabled = await this.getBrowserEnabled();
|
|
819
|
+
|
|
820
|
+
// The Claude builder is reused verbatim: Qoder takes the same
|
|
821
|
+
// --append-system-prompt hook and names MCP tools the same way, so the
|
|
822
|
+
// briefing is character-for-character the one that adapter writes.
|
|
823
|
+
const systemPrompt = buildClaudeSystemPrompt({
|
|
824
|
+
agentName: this.agentName,
|
|
825
|
+
workspaceId: this.workspaceId,
|
|
826
|
+
channelName: channel,
|
|
827
|
+
mode: this._mode,
|
|
828
|
+
model: this.modelLabel(),
|
|
829
|
+
browserEnabled,
|
|
830
|
+
toolMode: 'mcp',
|
|
831
|
+
...this.pinnedPromptOpts(channel),
|
|
832
|
+
});
|
|
833
|
+
|
|
834
|
+
const env = buildQoderChildEnv(getEnhancedEnv(this.agentEnv), { edition: this.edition, pat: auth.pat });
|
|
835
|
+
// Every value this agent must never quote back — the workspace token and
|
|
836
|
+
// the agentEnv credentials (base._knownSecrets) — plus the resolved PAT.
|
|
837
|
+
const secrets = [...new Set([...this._knownSecrets(), ...(auth.pat ? [auth.pat] : [])])];
|
|
838
|
+
|
|
839
|
+
// One retry: a saved session the CLI no longer has (pruned, or the turn
|
|
840
|
+
// that created it never reached the model) fails the resume, and the turn
|
|
841
|
+
// is worth re-running fresh.
|
|
842
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
843
|
+
const resumeId = attempt === 0 ? this._resumableSession(channel, workingDir) : null;
|
|
844
|
+
const newSessionId = resumeId ? null : crypto.randomUUID();
|
|
845
|
+
|
|
846
|
+
let prompt = content;
|
|
847
|
+
if (!resumeId) {
|
|
848
|
+
const recap = await this._buildChannelRecap(channel, content);
|
|
849
|
+
if (recap) prompt = `${recap}\n\n---\n\n${content}`;
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
const mcpConfigPath = this._writeMcpConfig(channel);
|
|
853
|
+
const args = buildQoderArgs({
|
|
854
|
+
appendSystemPrompt: systemPrompt,
|
|
855
|
+
model: auth.model,
|
|
856
|
+
resumeSessionId: resumeId || undefined,
|
|
857
|
+
newSessionId: newSessionId || undefined,
|
|
858
|
+
mcpConfigPath: mcpConfigPath || undefined,
|
|
859
|
+
planMode: this._mode === 'plan',
|
|
860
|
+
// The native fetch can't render JS and bypasses the workspace browser,
|
|
861
|
+
// as in the Claude adapter.
|
|
862
|
+
extraDisallowedTools: browserEnabled ? ['WebFetch'] : [],
|
|
863
|
+
});
|
|
864
|
+
|
|
865
|
+
let run;
|
|
866
|
+
try {
|
|
867
|
+
run = await this._runQoder(channel, bin, args, workingDir, prompt, env, secrets);
|
|
868
|
+
} finally {
|
|
869
|
+
if (mcpConfigPath) { try { fs.unlinkSync(mcpConfigPath); } catch {} }
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
if (run.userStopped) {
|
|
873
|
+
// A stopped session stays resumable, so the channel keeps its thread.
|
|
874
|
+
this._rememberSession(channel, run.sessionId || resumeId || newSessionId, workingDir);
|
|
875
|
+
return;
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
if (run.spawnError) {
|
|
879
|
+
await this.sendError(channel,
|
|
880
|
+
`${label} could not be started (${redactSecrets(run.spawnError, secrets)}). Reinstall it with: ${installHint(this.edition)}`);
|
|
881
|
+
return;
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
const verdict = classifyQoderRun(run, this.edition, secrets);
|
|
885
|
+
const fallbackNotice = this._noteModelFallback(auth.model, run);
|
|
886
|
+
const withNotice = (text) => (fallbackNotice ? `${text}\n\n_${fallbackNotice}_` : text);
|
|
887
|
+
|
|
888
|
+
if (resumeId && attempt === 0 && (verdict.kind === 'stale_session' || (!verdict.ok && !run.anyOutput && verdict.kind !== 'auth'))) {
|
|
889
|
+
this._log(`Resume of session ${resumeId} failed (${verdict.kind}) — clearing and retrying fresh`, 'warn');
|
|
890
|
+
this._clearSession(channel);
|
|
891
|
+
continue;
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
// A run that never reached the model leaves no transcript to resume,
|
|
895
|
+
// so only a turn that got going is remembered.
|
|
896
|
+
if (verdict.ok || run.lastAssistantText || (run.result && !['auth', 'quota'].includes(verdict.kind))) {
|
|
897
|
+
this._rememberSession(channel, run.sessionId || resumeId || newSessionId, workingDir);
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
const resultText = run.result && run.result.text ? run.result.text.trim() : '';
|
|
901
|
+
const finalText = verdict.ok ? (resultText || (run.lastAssistantText || '').trim()) : '';
|
|
902
|
+
|
|
903
|
+
if (verdict.ok) {
|
|
904
|
+
try {
|
|
905
|
+
await this.sendResponse(channel, withNotice(finalText || 'No response generated. Please try again.'));
|
|
906
|
+
} catch {}
|
|
907
|
+
return;
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
// The model answered, then a later step failed: deliver the answer with
|
|
911
|
+
// the reason appended rather than replacing it.
|
|
912
|
+
const partial = (run.lastAssistantText || '').trim();
|
|
913
|
+
if (partial && verdict.kind !== 'auth') {
|
|
914
|
+
this._log(`Run reported ${verdict.kind} but returned text; text delivered`);
|
|
915
|
+
try { await this.sendResponse(channel, withNotice(`${partial}\n\n_${verdict.userMessage}_`)); } catch {}
|
|
916
|
+
return;
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
this._log(`Run failed (${verdict.kind}, exit ${run.code}): ${redactSecrets(truncate(run.stderr || '', 300), secrets)}`, 'warn');
|
|
920
|
+
try { await this.sendError(channel, withNotice(verdict.userMessage)); } catch {}
|
|
921
|
+
return;
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
/**
|
|
926
|
+
* Track a fallback from the configured model, so modelLabel() and the next
|
|
927
|
+
* briefing name the model that really ran. Returns a notice for the channel
|
|
928
|
+
* the first time a fallback is seen; null otherwise.
|
|
929
|
+
*/
|
|
930
|
+
_noteModelFallback(requested, run) {
|
|
931
|
+
if (!requested || !run.model) return null;
|
|
932
|
+
const fb = parseModelFallback(run.stderr);
|
|
933
|
+
if (!fb) {
|
|
934
|
+
// The model ran as asked (the account gained it, or the pick changed).
|
|
935
|
+
if (this._modelFallback && this._modelFallback.requested === requested) this._modelFallback = null;
|
|
936
|
+
return null;
|
|
937
|
+
}
|
|
938
|
+
const prev = this._modelFallback;
|
|
939
|
+
this._modelFallback = { requested, used: run.model };
|
|
940
|
+
this._log(`${this.edition.label} fell back from model ${requested} to ${run.model} (${fb.used})`);
|
|
941
|
+
if (prev && prev.requested === requested && prev.used === run.model) return null;
|
|
942
|
+
return modelFallbackNotice(this.edition, requested, run.model);
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
module.exports = QoderAdapter;
|