@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,1125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Qwen Code adapter for OpenAgents workspace.
|
|
3
|
+
*
|
|
4
|
+
* Bridges Alibaba's Qwen Code CLI (`npm i -g @qwen-code/qwen-code`, binary
|
|
5
|
+
* `qwen`) to an OpenAgents workspace:
|
|
6
|
+
* - polling loop + per-channel task dispatch (inherited from BaseAdapter)
|
|
7
|
+
* - one headless `qwen --output-format stream-json` run per user message,
|
|
8
|
+
* prompt piped over stdin; stopping the run stops the task
|
|
9
|
+
* - workspace tools over MCP, the same stdio server the Claude adapter wires
|
|
10
|
+
* up, pointed at with `--mcp-config`
|
|
11
|
+
* - session continuity per channel: the CLI's `session_id` comes back on the
|
|
12
|
+
* init frame and is replayed with `--resume` on the channel's next turn
|
|
13
|
+
*
|
|
14
|
+
* Four CLI-specific decisions are worth knowing before editing this file
|
|
15
|
+
* (the verified facts behind them are in qwen-code-stream.js):
|
|
16
|
+
*
|
|
17
|
+
* AUTO-MEMORY IS OFF. Left on, a memory-extractor subagent runs after every
|
|
18
|
+
* turn and the result frame waits for it — minutes, on a long session. The
|
|
19
|
+
* adapter loads a "system defaults" settings layer that turns it off; the
|
|
20
|
+
* user's own ~/.qwen/settings.json still outranks it.
|
|
21
|
+
*
|
|
22
|
+
* THE KEY IS THE AGENT'S, AS A SET. Key, base URL and model come together
|
|
23
|
+
* from the agent's form (LLM_*) or together from OPENAI_*, and `--auth-type
|
|
24
|
+
* openai` is passed whenever there is a key. Without one, the CLI's own
|
|
25
|
+
* settings decide, so a provider configured with /auth keeps working.
|
|
26
|
+
*
|
|
27
|
+
* SESSIONS BELONG TO A DIRECTORY. The CLI files a transcript under the
|
|
28
|
+
* working directory it ran in, and `--resume` from anywhere else fails. The
|
|
29
|
+
* channel's session is remembered together with its directory.
|
|
30
|
+
*
|
|
31
|
+
* ON WINDOWS THE CLI IS TWO PROCESSES. Its entry script relaunches itself as
|
|
32
|
+
* a child (`node --expose-gc cli.js`), and killing the parent — which is all
|
|
33
|
+
* `ChildProcess.kill()` does there — leaves that child running the turn. Stop
|
|
34
|
+
* therefore goes straight to `taskkill /T`.
|
|
35
|
+
*
|
|
36
|
+
* Verified end to end against @qwen-code/qwen-code 0.25.1.
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
'use strict';
|
|
40
|
+
|
|
41
|
+
const fs = require('fs');
|
|
42
|
+
const os = require('os');
|
|
43
|
+
const path = require('path');
|
|
44
|
+
const { execFileSync } = require('child_process');
|
|
45
|
+
// spawn() here is the WSL bridge from ../wsl: same signature as
|
|
46
|
+
// child_process.spawn, and a straight pass-through unless the resolved CLI
|
|
47
|
+
// lives on the other side of the Windows/WSL boundary.
|
|
48
|
+
const { spawn } = require('../wsl');
|
|
49
|
+
|
|
50
|
+
const BaseAdapter = require('./base');
|
|
51
|
+
const { formatAttachmentsForPrompt, SESSION_DEFAULT_RE, generateSessionTitle } = require('./utils');
|
|
52
|
+
const { buildClaudeSystemPrompt } = require('./workspace-prompt');
|
|
53
|
+
const { REASON } = require('./health-status');
|
|
54
|
+
const { defaultAgentWorkdir, whichBinary, whereBinary, getEnhancedEnv } = require('../paths');
|
|
55
|
+
const {
|
|
56
|
+
buildQwenArgs,
|
|
57
|
+
buildQwenChildEnv,
|
|
58
|
+
buildQwenSystemDefaults,
|
|
59
|
+
classifyQwenRun,
|
|
60
|
+
classifyQwenVersion,
|
|
61
|
+
interpretQwenFrame,
|
|
62
|
+
parseFrame,
|
|
63
|
+
parseQwenSettings,
|
|
64
|
+
qwenSystemDefaultsSource,
|
|
65
|
+
qwenSystemSettingsSource,
|
|
66
|
+
redactArgs,
|
|
67
|
+
resolveQwenCredentials,
|
|
68
|
+
sameQwenSettings,
|
|
69
|
+
truncate,
|
|
70
|
+
QWEN_MIN_VERSION,
|
|
71
|
+
} = require('./qwen-code-stream');
|
|
72
|
+
|
|
73
|
+
const IS_WINDOWS = process.platform === 'win32';
|
|
74
|
+
|
|
75
|
+
// Idle watchdog: with no stdout frame for this long we nudge the channel, and
|
|
76
|
+
// after MAX consecutive silences we kill a run that is probably wedged.
|
|
77
|
+
const WATCHDOG_INTERVAL_MS = 15000;
|
|
78
|
+
const WATCHDOG_NUDGE_AT = 2; // ~30s of silence → "still working"
|
|
79
|
+
const WATCHDOG_MAX = 20; // ~5 min of silence → kill
|
|
80
|
+
|
|
81
|
+
// The CLI's own floor (`engines.node` in its package.json), so an interpreter
|
|
82
|
+
// under it cannot run the agent at all.
|
|
83
|
+
const MIN_NODE_MAJOR = 22;
|
|
84
|
+
|
|
85
|
+
// Cache window for the version probe, so preflight never spawns `--version`
|
|
86
|
+
// more than once per window across channels.
|
|
87
|
+
const VERSION_PROBE_TTL_MS = 60000;
|
|
88
|
+
|
|
89
|
+
// Grace periods for a stop. The CLI answers SIGINT within ~100ms (it cancels
|
|
90
|
+
// the turn and kills its own shell tools), so escalation is for a wedged run.
|
|
91
|
+
const STOP_GRACE_MS = 3000;
|
|
92
|
+
|
|
93
|
+
const INSTALL_HINT = 'npm install -g @qwen-code/qwen-code';
|
|
94
|
+
const NO_NODE_FOR_SHIM = `Qwen Code needs Node.js >= ${MIN_NODE_MAJOR} to run on Windows, and none was found ` +
|
|
95
|
+
'(its .cmd shim cannot carry the workspace briefing safely). Install Node.js 22 or newer, ' +
|
|
96
|
+
'or reinstall Qwen Code from the Install page.';
|
|
97
|
+
const PACKAGE_DIR = ['@qwen-code', 'qwen-code'];
|
|
98
|
+
|
|
99
|
+
class QwenCodeAdapter extends BaseAdapter {
|
|
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.disabledModules = opts.disabledModules || new Set();
|
|
108
|
+
this._usesPinnedContext = true;
|
|
109
|
+
// channel → { sessionId, workingDir }
|
|
110
|
+
this._channelSessions = {};
|
|
111
|
+
// channel → child process (the in-flight headless run)
|
|
112
|
+
this._channelProcesses = {};
|
|
113
|
+
this._stoppingChannels = new Set();
|
|
114
|
+
this._sessionsFile = path.join(
|
|
115
|
+
os.homedir(), '.openagents', 'sessions',
|
|
116
|
+
`${this.workspaceId}_${this.agentName}_qwen-code.json`,
|
|
117
|
+
);
|
|
118
|
+
this._isWindows = IS_WINDOWS;
|
|
119
|
+
this._versionProbe = null; // { at, bin, version, supported }
|
|
120
|
+
this._loadSessions();
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* The model this agent actually runs — exactly what is passed to the CLI,
|
|
125
|
+
* so the workspace never shows a model the run did not use.
|
|
126
|
+
*/
|
|
127
|
+
modelLabel() {
|
|
128
|
+
return resolveQwenCredentials(this.agentEnv, this.workspaceModel).model || null;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// ------------------------------------------------------------------
|
|
132
|
+
// Session persistence (Qwen Code session ids, bound to working dir)
|
|
133
|
+
// ------------------------------------------------------------------
|
|
134
|
+
|
|
135
|
+
_loadSessions() {
|
|
136
|
+
try {
|
|
137
|
+
if (fs.existsSync(this._sessionsFile)) {
|
|
138
|
+
const data = JSON.parse(fs.readFileSync(this._sessionsFile, 'utf-8'));
|
|
139
|
+
if (data && typeof data === 'object') {
|
|
140
|
+
Object.assign(this._channelSessions, data);
|
|
141
|
+
this._log(`Loaded ${Object.keys(data).length} Qwen Code session(s)`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
} catch {
|
|
145
|
+
this._log('Could not load Qwen Code sessions file, starting fresh', 'warn');
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
_saveSessions() {
|
|
150
|
+
try {
|
|
151
|
+
fs.mkdirSync(path.dirname(this._sessionsFile), { recursive: true });
|
|
152
|
+
fs.writeFileSync(this._sessionsFile, JSON.stringify(this._channelSessions));
|
|
153
|
+
} catch {}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* A resumable session id for this channel, or null.
|
|
158
|
+
*
|
|
159
|
+
* Qwen Code stores a transcript under the directory it ran in
|
|
160
|
+
* (~/.qwen/projects/<dir>/chats), so a saved id from a different directory
|
|
161
|
+
* would not resolve — resume only when the directory still matches.
|
|
162
|
+
*/
|
|
163
|
+
_resumableSession(channel, workingDir) {
|
|
164
|
+
const entry = this._channelSessions[channel];
|
|
165
|
+
if (!entry || !entry.sessionId) return null;
|
|
166
|
+
if (entry.workingDir && workingDir && entry.workingDir !== workingDir) return null;
|
|
167
|
+
return entry.sessionId;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
_rememberSession(channel, sessionId, workingDir) {
|
|
171
|
+
if (!sessionId) return;
|
|
172
|
+
const prev = this._channelSessions[channel];
|
|
173
|
+
if (prev && prev.sessionId === sessionId && prev.workingDir === workingDir) return;
|
|
174
|
+
this._channelSessions[channel] = { sessionId, workingDir };
|
|
175
|
+
this._saveSessions();
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
_clearSession(channel) {
|
|
179
|
+
if (this._channelSessions[channel]) {
|
|
180
|
+
delete this._channelSessions[channel];
|
|
181
|
+
this._saveSessions();
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// ------------------------------------------------------------------
|
|
186
|
+
// Shutdown
|
|
187
|
+
// ------------------------------------------------------------------
|
|
188
|
+
|
|
189
|
+
stop() {
|
|
190
|
+
super.stop();
|
|
191
|
+
void this._stopAllProcesses('Agent stopped.');
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
async _stopAllProcesses(message = 'Execution stopped.') {
|
|
195
|
+
const entries = Object.entries(this._channelProcesses);
|
|
196
|
+
if (!entries.length) return;
|
|
197
|
+
this._log(`Stopping ${entries.length} running Qwen Code process(es)...`);
|
|
198
|
+
for (const [channel, proc] of entries) {
|
|
199
|
+
this._stoppingChannels.add(channel);
|
|
200
|
+
await this._stopProcess(proc);
|
|
201
|
+
delete this._channelProcesses[channel];
|
|
202
|
+
delete this._channelQueues[channel];
|
|
203
|
+
try { await this.sendResponse(channel, message); } catch {}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Stop a run. Resolves true once the process has exited, false when that
|
|
209
|
+
* could not be confirmed.
|
|
210
|
+
*
|
|
211
|
+
* POSIX: SIGINT to the process group, which the CLI handles by cancelling the
|
|
212
|
+
* turn and killing its own shell tools (they run in a PTY session of their
|
|
213
|
+
* own, outside our group), then SIGTERM and SIGKILL for a wedged run.
|
|
214
|
+
*
|
|
215
|
+
* Windows: `taskkill /T /F` straight away. There is no SIGINT to send — Node
|
|
216
|
+
* maps every kill() to TerminateProcess — and terminating only the entry
|
|
217
|
+
* process would orphan the child it relaunched the CLI in (file header).
|
|
218
|
+
*/
|
|
219
|
+
async _stopProcess(proc) {
|
|
220
|
+
if (!proc || proc.exitCode !== null || proc.signalCode) return true;
|
|
221
|
+
try {
|
|
222
|
+
if (this._isWindows) {
|
|
223
|
+
this._killTree(proc.pid);
|
|
224
|
+
let exited = await this._waitExit(proc, STOP_GRACE_MS);
|
|
225
|
+
if (!exited) {
|
|
226
|
+
try { proc.kill(); } catch {}
|
|
227
|
+
exited = await this._waitExit(proc, 1000);
|
|
228
|
+
}
|
|
229
|
+
return exited;
|
|
230
|
+
}
|
|
231
|
+
const signalGroup = (sig) => {
|
|
232
|
+
try { process.kill(-proc.pid, sig); } catch { try { proc.kill(sig); } catch {} }
|
|
233
|
+
};
|
|
234
|
+
signalGroup('SIGINT');
|
|
235
|
+
let exited = await this._waitExit(proc, STOP_GRACE_MS);
|
|
236
|
+
if (!exited) {
|
|
237
|
+
signalGroup('SIGTERM');
|
|
238
|
+
exited = await this._waitExit(proc, 1500);
|
|
239
|
+
}
|
|
240
|
+
if (!exited) {
|
|
241
|
+
signalGroup('SIGKILL');
|
|
242
|
+
exited = await this._waitExit(proc, 1000);
|
|
243
|
+
}
|
|
244
|
+
return exited;
|
|
245
|
+
} catch {
|
|
246
|
+
return false;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Kill a Windows process tree. Isolated for testing. */
|
|
251
|
+
_killTree(pid) {
|
|
252
|
+
try {
|
|
253
|
+
execFileSync('taskkill', ['/F', '/T', '/PID', String(pid)], { timeout: 5000, windowsHide: true });
|
|
254
|
+
} catch {}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
_waitExit(proc, ms) {
|
|
258
|
+
return new Promise((resolve) => {
|
|
259
|
+
if (proc.exitCode !== null || proc.signalCode) { resolve(true); return; }
|
|
260
|
+
const t = setTimeout(() => resolve(false), ms);
|
|
261
|
+
proc.once('exit', () => { clearTimeout(t); resolve(true); });
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// ------------------------------------------------------------------
|
|
266
|
+
// Binary resolution (cross-platform)
|
|
267
|
+
// ------------------------------------------------------------------
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Node interpreter used to execute a JS entry point.
|
|
271
|
+
*
|
|
272
|
+
* Prefer the launcher's managed runtime, and fall back to the interpreter
|
|
273
|
+
* running this daemon when it clears `minMajor` (by default the CLI's own
|
|
274
|
+
* floor). Returning null means "no suitable Node" and the caller spawns the
|
|
275
|
+
* shim directly instead of guessing.
|
|
276
|
+
*/
|
|
277
|
+
_findNodeBin(minMajor = MIN_NODE_MAJOR) {
|
|
278
|
+
const home = os.homedir();
|
|
279
|
+
const candidates = this._isWindows
|
|
280
|
+
? [path.join(home, '.openagents', 'nodejs', 'node.exe')]
|
|
281
|
+
: [path.join(home, '.openagents', 'nodejs', 'node'),
|
|
282
|
+
path.join(home, '.openagents', 'nodejs', 'bin', 'node')];
|
|
283
|
+
for (const c of candidates) {
|
|
284
|
+
if (fs.existsSync(c) && (!minMajor || this._nodeMajor(c) >= minMajor)) return c;
|
|
285
|
+
}
|
|
286
|
+
const ownMajor = parseInt(String(process.versions.node).split('.')[0], 10) || 0;
|
|
287
|
+
return ownMajor >= minMajor ? process.execPath : null;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** Major version of a Node binary, or 0 when it cannot be read. */
|
|
291
|
+
_nodeMajor(nodeBin) {
|
|
292
|
+
try {
|
|
293
|
+
const out = execFileSync(nodeBin, ['--version'], { encoding: 'utf-8', timeout: 5000, windowsHide: true });
|
|
294
|
+
const m = String(out).match(/v(\d+)\./);
|
|
295
|
+
return m ? parseInt(m[1], 10) : 0;
|
|
296
|
+
} catch {
|
|
297
|
+
return 0;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Locate the Qwen Code CLI.
|
|
303
|
+
*
|
|
304
|
+
* The isolated runtime prefix is checked first so the version the launcher
|
|
305
|
+
* installed wins over anything else on PATH. The official standalone
|
|
306
|
+
* installer's wrapper dirs (~/.local/bin, %LOCALAPPDATA%\qwen-code\bin,
|
|
307
|
+
* QWEN_INSTALL_BIN_DIR / QWEN_INSTALL_ROOT) are known bin dirs in paths.js,
|
|
308
|
+
* so the PATH lookup and the deep scan already reach them.
|
|
309
|
+
*/
|
|
310
|
+
_findQwenBinary() {
|
|
311
|
+
const home = os.homedir();
|
|
312
|
+
const ext = this._isWindows ? '.cmd' : '';
|
|
313
|
+
|
|
314
|
+
const prefixes = [
|
|
315
|
+
path.join(home, '.openagents', 'runtimes', 'qwen-code', 'node_modules'),
|
|
316
|
+
path.join(home, '.openagents', 'nodejs', 'node_modules'),
|
|
317
|
+
];
|
|
318
|
+
|
|
319
|
+
// Tier 0: npm shim inside an OpenAgents-managed prefix.
|
|
320
|
+
for (const root of prefixes) {
|
|
321
|
+
const c = path.join(root, '.bin', `qwen${ext}`);
|
|
322
|
+
if (fs.existsSync(c)) return c;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// Tier 0b: the package's own entry point, run under Node directly.
|
|
326
|
+
for (const root of prefixes) {
|
|
327
|
+
const entry = path.join(root, ...PACKAGE_DIR, 'cli-entry.js');
|
|
328
|
+
if (fs.existsSync(entry)) return entry;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// Tier 1: PATH, via the codepage-safe lookup (a non-ASCII username would
|
|
332
|
+
// otherwise be mangled into an ENOENT) using the enriched PATH.
|
|
333
|
+
const viaWhere = whereBinary('qwen');
|
|
334
|
+
if (viaWhere) return viaWhere;
|
|
335
|
+
|
|
336
|
+
// Tier 2: next to the current Node interpreter (npm global installs).
|
|
337
|
+
const nearNode = path.join(path.dirname(process.execPath), `qwen${ext}`);
|
|
338
|
+
if (fs.existsSync(nearNode)) return nearNode;
|
|
339
|
+
|
|
340
|
+
// Tier 3: deep scan of every known bin dir (nvm/fnm/volta/homebrew/…).
|
|
341
|
+
return whichBinary('qwen') || null;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* True when `dir` is a standalone install: the release archive's layout,
|
|
346
|
+
* with its manifest, its bundled Node, and the CLI's entry script.
|
|
347
|
+
*/
|
|
348
|
+
_isStandaloneRoot(dir) {
|
|
349
|
+
try {
|
|
350
|
+
const manifest = JSON.parse(fs.readFileSync(path.join(dir, 'manifest.json'), 'utf-8'));
|
|
351
|
+
if (!manifest || manifest.name !== '@qwen-code/qwen-code') return false;
|
|
352
|
+
} catch {
|
|
353
|
+
return false;
|
|
354
|
+
}
|
|
355
|
+
return fs.existsSync(path.join(dir, 'lib', 'cli-entry.js'))
|
|
356
|
+
&& fs.existsSync(this._standaloneNode(dir));
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
_standaloneNode(dir) {
|
|
360
|
+
return this._isWindows
|
|
361
|
+
? path.join(dir, 'node', 'node.exe')
|
|
362
|
+
: path.join(dir, 'node', 'bin', 'node');
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* The standalone install a binary path belongs to, or null.
|
|
367
|
+
*
|
|
368
|
+
* The path is either the archive's own launcher (<root>/bin/qwen[.cmd]) or
|
|
369
|
+
* the installer's one-line wrapper on PATH, which names that launcher by
|
|
370
|
+
* absolute path (`exec '<root>/bin/qwen' "$@"` / `call "<root>\bin\qwen.cmd" %*`).
|
|
371
|
+
*/
|
|
372
|
+
_findStandaloneRoot(binPath) {
|
|
373
|
+
const direct = path.resolve(path.dirname(binPath), '..');
|
|
374
|
+
if (this._isStandaloneRoot(direct)) return direct;
|
|
375
|
+
try {
|
|
376
|
+
if (fs.statSync(binPath).size > 4096) return null;
|
|
377
|
+
const text = fs.readFileSync(binPath, 'utf-8');
|
|
378
|
+
const m = text.match(/(["'])([^"'\r\n]+?[\\/]bin[\\/]qwen(?:\.cmd)?)\1/i);
|
|
379
|
+
if (m) {
|
|
380
|
+
const root = path.resolve(path.dirname(m[2]), '..');
|
|
381
|
+
if (this._isStandaloneRoot(root)) return root;
|
|
382
|
+
}
|
|
383
|
+
} catch {}
|
|
384
|
+
return null;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* Resolve a shim to [nodeBin, jsEntry] so the JS entry point runs directly.
|
|
389
|
+
* Returns null when no suitable Node exists or the target isn't a JS entry,
|
|
390
|
+
* leaving the caller to spawn the shim as-is.
|
|
391
|
+
*/
|
|
392
|
+
_resolveToNodeCmd(binPath, minMajor = MIN_NODE_MAJOR) {
|
|
393
|
+
if (this._isWindows && binPath.toLowerCase().endsWith('.cmd')) {
|
|
394
|
+
try {
|
|
395
|
+
const cmdDir = path.dirname(path.resolve(binPath));
|
|
396
|
+
const content = fs.readFileSync(binPath, 'utf-8');
|
|
397
|
+
const jsMatch = content.match(/%dp0%\\([^\s"*?]+\.m?js)/i);
|
|
398
|
+
if (jsMatch) {
|
|
399
|
+
const target = path.resolve(cmdDir, jsMatch[1]);
|
|
400
|
+
const nodeBin = fs.existsSync(target) ? this._findNodeBin(minMajor) : null;
|
|
401
|
+
if (nodeBin) return [nodeBin, target];
|
|
402
|
+
}
|
|
403
|
+
} catch {}
|
|
404
|
+
return null;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
if (binPath.endsWith('.mjs') || binPath.endsWith('.js')) {
|
|
408
|
+
const nodeBin = this._findNodeBin(minMajor);
|
|
409
|
+
return nodeBin ? [nodeBin, binPath] : null;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
try {
|
|
413
|
+
let target = binPath;
|
|
414
|
+
if (fs.lstatSync(binPath).isSymbolicLink()) {
|
|
415
|
+
target = path.resolve(path.dirname(binPath), fs.readlinkSync(binPath));
|
|
416
|
+
}
|
|
417
|
+
if (target.endsWith('.mjs') || target.endsWith('.js') || this._isNodeShebangScript(target)) {
|
|
418
|
+
const nodeBin = this._findNodeBin(minMajor);
|
|
419
|
+
return nodeBin ? [nodeBin, target] : null;
|
|
420
|
+
}
|
|
421
|
+
} catch {}
|
|
422
|
+
return null;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/** True when a file begins with a `#!...node` shebang. */
|
|
426
|
+
_isNodeShebangScript(filePath) {
|
|
427
|
+
try {
|
|
428
|
+
const fd = fs.openSync(filePath, 'r');
|
|
429
|
+
try {
|
|
430
|
+
const buf = Buffer.alloc(64);
|
|
431
|
+
const n = fs.readSync(fd, buf, 0, 64, 0);
|
|
432
|
+
const head = buf.slice(0, n).toString('utf-8');
|
|
433
|
+
return head.startsWith('#!') && /\bnode\b/.test(head.split('\n')[0]);
|
|
434
|
+
} finally {
|
|
435
|
+
fs.closeSync(fd);
|
|
436
|
+
}
|
|
437
|
+
} catch {
|
|
438
|
+
return false;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* How to spawn the CLI: { command, args, env } where env is an overlay.
|
|
444
|
+
*
|
|
445
|
+
* Every route ends at the CLI's JS entry under a Node that can run it,
|
|
446
|
+
* because a Windows .cmd shim would put the whole command line — the
|
|
447
|
+
* kilobytes-long system prompt included — through cmd.exe and its
|
|
448
|
+
* 8191-character limit:
|
|
449
|
+
* - a standalone install runs on its own bundled Node, with the launcher
|
|
450
|
+
* path its shim would have exported;
|
|
451
|
+
* - an npm install runs on the launcher's Node (>= 22);
|
|
452
|
+
* - anything else is spawned as found, except a Windows .cmd shim with no
|
|
453
|
+
* Node to bypass it: that returns { error } unless `shellSafe` says the
|
|
454
|
+
* argv is fixed and harmless (the `--version` probe).
|
|
455
|
+
*/
|
|
456
|
+
_spawnPlan(binPath, args, { shellSafe = false } = {}) {
|
|
457
|
+
const root = this._findStandaloneRoot(binPath);
|
|
458
|
+
if (root) {
|
|
459
|
+
return {
|
|
460
|
+
command: this._standaloneNode(root),
|
|
461
|
+
args: [path.join(root, 'lib', 'cli-entry.js'), ...args],
|
|
462
|
+
env: { QWEN_CODE_LAUNCHER_PATH: path.join(root, 'bin', this._isWindows ? 'qwen.cmd' : 'qwen') },
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
const resolved = this._resolveToNodeCmd(binPath);
|
|
466
|
+
if (resolved) return { command: resolved[0], args: [resolved[1], ...args], env: {} };
|
|
467
|
+
if (this._isWindows && binPath.toLowerCase().endsWith('.cmd')) {
|
|
468
|
+
// Only a fixed, harmless argv may go through cmd.exe. A real turn carries
|
|
469
|
+
// the system prompt, whose glossary text can hold `"` or `&` that cmd.exe
|
|
470
|
+
// would reinterpret — and the whole line is capped at 8191 characters.
|
|
471
|
+
if (!shellSafe) return { error: NO_NODE_FOR_SHIM };
|
|
472
|
+
return { command: 'cmd.exe', args: ['/c', binPath, ...args], env: {} };
|
|
473
|
+
}
|
|
474
|
+
return { command: binPath, args, env: {} };
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
// ------------------------------------------------------------------
|
|
478
|
+
// Version preflight (cached; HARD minimum QWEN_MIN_VERSION)
|
|
479
|
+
// ------------------------------------------------------------------
|
|
480
|
+
|
|
481
|
+
/**
|
|
482
|
+
* Health check run before the adapter takes work: a missing CLI or one below
|
|
483
|
+
* QWEN_MIN_VERSION is reported here instead of failing every message. An
|
|
484
|
+
* unreadable version passes, as it does at run time.
|
|
485
|
+
*/
|
|
486
|
+
preflight() {
|
|
487
|
+
const bin = this._findQwenBinary();
|
|
488
|
+
if (!bin) {
|
|
489
|
+
return {
|
|
490
|
+
ok: false,
|
|
491
|
+
reason: REASON.RUNTIME_MISSING,
|
|
492
|
+
message: `Qwen Code CLI not found — install it with: ${INSTALL_HINT}`,
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
const ver = this._checkVersion(bin);
|
|
496
|
+
if (ver.supported === false) {
|
|
497
|
+
return {
|
|
498
|
+
ok: false,
|
|
499
|
+
reason: REASON.VERSION_INCOMPATIBLE,
|
|
500
|
+
message: `Qwen Code ${ver.version} is below the minimum supported version ${QWEN_MIN_VERSION}. ` +
|
|
501
|
+
`Upgrade with: ${INSTALL_HINT}`,
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
this._log(`Qwen Code CLI resolved: ${bin}${ver.version ? ` (v${ver.version})` : ''}`);
|
|
505
|
+
return { ok: true };
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/** Run `--version` and return raw output. Isolated for testing. */
|
|
509
|
+
_readVersionRaw(bin) {
|
|
510
|
+
try {
|
|
511
|
+
const plan = this._spawnPlan(bin, ['--version'], { shellSafe: true });
|
|
512
|
+
return execFileSync(plan.command, plan.args, {
|
|
513
|
+
encoding: 'utf-8',
|
|
514
|
+
timeout: 15000,
|
|
515
|
+
windowsHide: true,
|
|
516
|
+
env: { ...getEnhancedEnv(this.agentEnv), ...plan.env },
|
|
517
|
+
});
|
|
518
|
+
} catch (e) {
|
|
519
|
+
// A CLI that errors on --version still tells us its version sometimes.
|
|
520
|
+
return (e && (e.stdout || e.stderr)) ? String(e.stdout || e.stderr) : '';
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/** Cached version verdict for a resolved binary. */
|
|
525
|
+
_checkVersion(bin) {
|
|
526
|
+
const now = Date.now();
|
|
527
|
+
if (this._versionProbe && this._versionProbe.bin === bin && now - this._versionProbe.at < VERSION_PROBE_TTL_MS) {
|
|
528
|
+
return this._versionProbe;
|
|
529
|
+
}
|
|
530
|
+
const verdict = classifyQwenVersion(this._readVersionRaw(bin));
|
|
531
|
+
this._versionProbe = { ...verdict, bin, at: now };
|
|
532
|
+
return this._versionProbe;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
// ------------------------------------------------------------------
|
|
536
|
+
// Settings layer
|
|
537
|
+
// ------------------------------------------------------------------
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* Write the system-defaults settings file this run loads, and return its
|
|
541
|
+
* path — or null to leave the CLI's own lookup alone.
|
|
542
|
+
*
|
|
543
|
+
* A machine-wide system-defaults file is merged in (and wins) rather than
|
|
544
|
+
* replaced. One that exists but cannot be read is left in charge: the
|
|
545
|
+
* adapter's settings are worth less than an administrator's.
|
|
546
|
+
*/
|
|
547
|
+
_writeSystemDefaults() {
|
|
548
|
+
const target = path.join(os.homedir(), '.openagents', 'qwen-code', 'system-defaults.json');
|
|
549
|
+
try {
|
|
550
|
+
let existing = null;
|
|
551
|
+
const source = qwenSystemDefaultsSource(this.agentEnv, process.platform);
|
|
552
|
+
if (source && path.resolve(source) !== target && fs.existsSync(source)) {
|
|
553
|
+
try {
|
|
554
|
+
existing = JSON.parse(fs.readFileSync(source, 'utf-8'));
|
|
555
|
+
} catch {
|
|
556
|
+
this._log(`Could not parse ${source}; leaving Qwen Code's system defaults as they are`, 'warn');
|
|
557
|
+
return null;
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
const desired = buildQwenSystemDefaults(existing);
|
|
561
|
+
let current = null;
|
|
562
|
+
try { current = JSON.parse(fs.readFileSync(target, 'utf-8')); } catch {}
|
|
563
|
+
// The CLI stamps `$version` into the file after loading it; only a real
|
|
564
|
+
// difference is worth a rewrite (see sameQwenSettings).
|
|
565
|
+
if (!sameQwenSettings(current, desired)) {
|
|
566
|
+
const content = JSON.stringify(desired, null, 2);
|
|
567
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
568
|
+
// Atomic replace: another channel's run may be reading it right now.
|
|
569
|
+
const tmp = `${target}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
570
|
+
fs.writeFileSync(tmp, content);
|
|
571
|
+
fs.renameSync(tmp, target);
|
|
572
|
+
}
|
|
573
|
+
return target;
|
|
574
|
+
} catch (e) {
|
|
575
|
+
this._log(`Could not write the Qwen Code settings layer: ${this._redact(e && e.message)}`, 'warn');
|
|
576
|
+
return null;
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/** Keep saved modelProviders from redirecting this run's explicit credentials. */
|
|
581
|
+
_writeRunSettings() {
|
|
582
|
+
const source = qwenSystemSettingsSource(this.agentEnv);
|
|
583
|
+
let existing = {};
|
|
584
|
+
if (fs.existsSync(source)) {
|
|
585
|
+
try {
|
|
586
|
+
existing = parseQwenSettings(fs.readFileSync(source, 'utf-8'));
|
|
587
|
+
} catch {
|
|
588
|
+
throw new Error(`Cannot read system settings as JSON: ${source}`);
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
// System settings outrank user/project settings. null clears the map;
|
|
592
|
+
// an empty object would merge the saved providers back into this run.
|
|
593
|
+
const settings = { ...existing, modelProviders: null };
|
|
594
|
+
const dir = path.join(os.homedir(), '.openagents', 'qwen-code', 'run-settings');
|
|
595
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
596
|
+
const file = path.join(dir, `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`);
|
|
597
|
+
fs.writeFileSync(file, JSON.stringify(settings), { mode: 0o600 });
|
|
598
|
+
return file;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
// ------------------------------------------------------------------
|
|
602
|
+
// Workspace MCP server
|
|
603
|
+
// ------------------------------------------------------------------
|
|
604
|
+
|
|
605
|
+
/**
|
|
606
|
+
* Write the MCP config that gives this run the workspace_* tools, and return
|
|
607
|
+
* its path (or null when the server entry point cannot be located — the run
|
|
608
|
+
* still proceeds, just without workspace tools).
|
|
609
|
+
*
|
|
610
|
+
* The file carries the workspace token, so it is written 0600 into an
|
|
611
|
+
* OpenAgents-owned directory rather than the user's project or their
|
|
612
|
+
* ~/.qwen config. The caller deletes it when the run ends.
|
|
613
|
+
*/
|
|
614
|
+
_writeMcpConfig(channel) {
|
|
615
|
+
try {
|
|
616
|
+
const mcpArgs = [
|
|
617
|
+
'mcp-server',
|
|
618
|
+
'--workspace-id', this.workspaceId,
|
|
619
|
+
'--channel-name', channel,
|
|
620
|
+
'--agent-name', this.agentName,
|
|
621
|
+
'--endpoint', this.endpoint,
|
|
622
|
+
];
|
|
623
|
+
if (this.disabledModules.has('files')) mcpArgs.push('--disable-files');
|
|
624
|
+
if (this.disabledModules.has('browser')) mcpArgs.push('--disable-browser');
|
|
625
|
+
if (this.disabledModules.has('knowledge')) mcpArgs.push('--disable-knowledge');
|
|
626
|
+
|
|
627
|
+
const resolved = this._resolveMcpServerCmd(mcpArgs);
|
|
628
|
+
if (!resolved) {
|
|
629
|
+
this._log('Could not find the openagents binary — workspace MCP tools are unavailable this run', 'warn');
|
|
630
|
+
return null;
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
const config = {
|
|
634
|
+
mcpServers: {
|
|
635
|
+
'openagents-workspace': {
|
|
636
|
+
command: resolved.command,
|
|
637
|
+
args: resolved.args,
|
|
638
|
+
env: { OA_WORKSPACE_TOKEN: this.token },
|
|
639
|
+
},
|
|
640
|
+
},
|
|
641
|
+
};
|
|
642
|
+
|
|
643
|
+
const dir = path.join(os.homedir(), '.openagents', 'mcp-configs');
|
|
644
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
645
|
+
const file = path.join(dir, `qwen-code-${Date.now()}-${Math.random().toString(36).slice(2)}.json`);
|
|
646
|
+
fs.writeFileSync(file, JSON.stringify(config), { mode: 0o600 });
|
|
647
|
+
try { fs.chmodSync(file, 0o600); } catch {}
|
|
648
|
+
return file;
|
|
649
|
+
} catch (e) {
|
|
650
|
+
this._log(`Could not write the MCP config: ${this._redact(e && e.message)}`, 'warn');
|
|
651
|
+
return null;
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
/**
|
|
656
|
+
* Locate this package's own CLI, which hosts the workspace MCP server.
|
|
657
|
+
* Returns { command, args } or null.
|
|
658
|
+
*/
|
|
659
|
+
_resolveMcpServerCmd(mcpArgs) {
|
|
660
|
+
const siblingBin = path.resolve(__dirname, '..', '..', 'bin', 'agent-connector.js');
|
|
661
|
+
if (fs.existsSync(siblingBin)) {
|
|
662
|
+
// The MCP server is this package's own code: any Node that runs the
|
|
663
|
+
// daemon runs it, so the CLI's newer floor does not apply.
|
|
664
|
+
return { command: this._findNodeBin(0), args: [siblingBin, ...mcpArgs] };
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
const home = os.homedir();
|
|
668
|
+
const ext = this._isWindows ? '.cmd' : '';
|
|
669
|
+
const candidates = [];
|
|
670
|
+
try {
|
|
671
|
+
const runtimesRoot = path.join(home, '.openagents', 'runtimes');
|
|
672
|
+
for (const d of fs.readdirSync(runtimesRoot, { withFileTypes: true })) {
|
|
673
|
+
if (d.isDirectory()) {
|
|
674
|
+
candidates.push(path.join(runtimesRoot, d.name, 'node_modules', '.bin', `openagents${ext}`));
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
} catch {}
|
|
678
|
+
candidates.push(path.join(home, '.openagents', 'nodejs', 'node_modules', '.bin', `openagents${ext}`));
|
|
679
|
+
|
|
680
|
+
let bin = candidates.find((c) => fs.existsSync(c)) || null;
|
|
681
|
+
if (!bin) bin = whereBinary('openagents');
|
|
682
|
+
if (!bin) return null;
|
|
683
|
+
|
|
684
|
+
const resolved = this._resolveToNodeCmd(bin, 0);
|
|
685
|
+
if (resolved) return { command: resolved[0], args: [...resolved.slice(1), ...mcpArgs] };
|
|
686
|
+
return { command: bin, args: mcpArgs };
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
// ------------------------------------------------------------------
|
|
690
|
+
// Prompt assembly
|
|
691
|
+
// ------------------------------------------------------------------
|
|
692
|
+
|
|
693
|
+
/**
|
|
694
|
+
* Short transcript of recent channel chat, used to re-seed a fresh session.
|
|
695
|
+
* Only needed when there is no session to resume — the CLI already holds the
|
|
696
|
+
* history in that case.
|
|
697
|
+
*/
|
|
698
|
+
async _buildChannelRecap(channel, currentMessage) {
|
|
699
|
+
try {
|
|
700
|
+
const messages = await this.client.getRecentMessages(this.workspaceId, channel, this.token, 30);
|
|
701
|
+
if (!messages || messages.length === 0) return null;
|
|
702
|
+
const lines = [];
|
|
703
|
+
for (const m of messages) {
|
|
704
|
+
const mt = m.messageType || 'chat';
|
|
705
|
+
if (mt === 'status' || mt === 'thinking' || mt === 'loading' || mt === 'todos') continue;
|
|
706
|
+
const text = (m.content || '').trim();
|
|
707
|
+
if (!text || text === currentMessage) continue;
|
|
708
|
+
const who = m.senderType === 'human' ? (m.senderName || 'user') : (m.senderName || 'agent');
|
|
709
|
+
lines.push(`[${who}] ${truncate(text, 800)}`);
|
|
710
|
+
}
|
|
711
|
+
if (lines.length === 0) return null;
|
|
712
|
+
return 'Recent conversation in this channel for context:\n\n' + lines.slice(-12).join('\n');
|
|
713
|
+
} catch {
|
|
714
|
+
return null;
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
_dirExists(p) {
|
|
719
|
+
try { return fs.statSync(p).isDirectory(); } catch { return false; }
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
// ------------------------------------------------------------------
|
|
723
|
+
// Run
|
|
724
|
+
// ------------------------------------------------------------------
|
|
725
|
+
|
|
726
|
+
/**
|
|
727
|
+
* Run one headless turn and consume its stream-json output.
|
|
728
|
+
*
|
|
729
|
+
* The prompt goes in over stdin; the reply comes off the single `result`
|
|
730
|
+
* frame. Assistant frames only drive the live ticker, so a change to the
|
|
731
|
+
* streaming shape costs a progress update, never the answer.
|
|
732
|
+
*
|
|
733
|
+
* @returns {Promise<object>} { code, signal, result, sessionId, anyOutput,
|
|
734
|
+
* lastAssistantText, apiErrors, userStopped, stderr }
|
|
735
|
+
*/
|
|
736
|
+
_runQwen(channel, bin, args, workingDir, prompt, env = {}) {
|
|
737
|
+
// Stopped while this turn was being prepared: start nothing (no tokens).
|
|
738
|
+
if (this._stoppedBeforeStart(channel)) return Promise.resolve({ userStopped: true });
|
|
739
|
+
return new Promise((resolve) => {
|
|
740
|
+
const plan = this._spawnPlan(bin, args);
|
|
741
|
+
if (plan.error) {
|
|
742
|
+
resolve({ code: null, signal: null, result: null, sessionId: null, anyOutput: false, userStopped: false, refused: plan.error });
|
|
743
|
+
return;
|
|
744
|
+
}
|
|
745
|
+
this._log(`Spawning: ${path.basename(plan.command)} ${redactArgs(plan.args).join(' ')} (cwd=${workingDir})`);
|
|
746
|
+
|
|
747
|
+
let proc;
|
|
748
|
+
try {
|
|
749
|
+
proc = spawn(plan.command, plan.args, {
|
|
750
|
+
cwd: workingDir,
|
|
751
|
+
env: { ...env, ...plan.env },
|
|
752
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
753
|
+
// Own process group, so a stop reaches the CLI and anything it left
|
|
754
|
+
// in our group.
|
|
755
|
+
detached: !this._isWindows,
|
|
756
|
+
windowsHide: true,
|
|
757
|
+
});
|
|
758
|
+
} catch (e) {
|
|
759
|
+
resolve({ code: null, signal: null, result: null, sessionId: null, anyOutput: false, userStopped: false, spawnError: e && e.message });
|
|
760
|
+
return;
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
this._channelProcesses[channel] = proc;
|
|
764
|
+
|
|
765
|
+
let settled = false;
|
|
766
|
+
let stdoutBuf = '';
|
|
767
|
+
let stderrBuf = '';
|
|
768
|
+
let anyOutput = false;
|
|
769
|
+
let result = null;
|
|
770
|
+
let sessionId = null;
|
|
771
|
+
// The most recent assistant text, kept as a fallback answer for a clean
|
|
772
|
+
// run whose result frame came back empty.
|
|
773
|
+
let lastAssistantText = '';
|
|
774
|
+
const apiErrors = [];
|
|
775
|
+
// Masked by value in every error text kept from the stream.
|
|
776
|
+
const secrets = this._knownSecrets();
|
|
777
|
+
let lastFrameAt = Date.now();
|
|
778
|
+
let silences = 0;
|
|
779
|
+
let lastToolLabel = null;
|
|
780
|
+
let killedByWatchdog = false;
|
|
781
|
+
let exitInfo = null;
|
|
782
|
+
let closeFallback = null;
|
|
783
|
+
|
|
784
|
+
const finish = (payload) => {
|
|
785
|
+
if (settled) return;
|
|
786
|
+
settled = true;
|
|
787
|
+
clearInterval(watchdog);
|
|
788
|
+
if (closeFallback) clearTimeout(closeFallback);
|
|
789
|
+
if (this._channelProcesses[channel] === proc) delete this._channelProcesses[channel];
|
|
790
|
+
resolve(payload);
|
|
791
|
+
};
|
|
792
|
+
|
|
793
|
+
const onFrame = (line) => {
|
|
794
|
+
const frame = parseFrame(line);
|
|
795
|
+
if (!frame) return;
|
|
796
|
+
lastFrameAt = Date.now();
|
|
797
|
+
silences = 0;
|
|
798
|
+
anyOutput = true;
|
|
799
|
+
|
|
800
|
+
const ev = interpretQwenFrame(frame, secrets);
|
|
801
|
+
if (ev.kind === 'result') {
|
|
802
|
+
result = ev;
|
|
803
|
+
if (ev.sessionId) sessionId = ev.sessionId;
|
|
804
|
+
return;
|
|
805
|
+
}
|
|
806
|
+
if (ev.kind === 'init') {
|
|
807
|
+
// The id arrives here, BEFORE any model call — which is what keeps a
|
|
808
|
+
// channel resumable even when the turn itself fails.
|
|
809
|
+
if (ev.sessionId) sessionId = ev.sessionId;
|
|
810
|
+
for (const s of ev.mcpServers) {
|
|
811
|
+
if (s.status && s.status !== 'connected') {
|
|
812
|
+
this._log(`MCP server ${s.name} is ${s.status} — its tools are unavailable this run`, 'warn');
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
return;
|
|
816
|
+
}
|
|
817
|
+
if (ev.kind === 'assistant') {
|
|
818
|
+
apiErrors.push(...ev.apiErrors);
|
|
819
|
+
if (ev.texts.length) lastAssistantText = ev.texts.join('\n');
|
|
820
|
+
for (const text of ev.texts) {
|
|
821
|
+
void this.sendThinking(channel, text).catch(() => {});
|
|
822
|
+
}
|
|
823
|
+
for (const tool of ev.tools) {
|
|
824
|
+
// Only announce a CHANGE of activity: a run touching thirty files
|
|
825
|
+
// would otherwise post thirty near-identical status lines.
|
|
826
|
+
const label = tool.preview ? `${tool.name} › ${tool.preview}` : tool.name;
|
|
827
|
+
if (label && label !== lastToolLabel) {
|
|
828
|
+
lastToolLabel = label;
|
|
829
|
+
void this.sendStatus(channel, label).catch(() => {});
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
return;
|
|
833
|
+
}
|
|
834
|
+
if (ev.kind === 'status') {
|
|
835
|
+
void this.sendStatus(channel, ev.text).catch(() => {});
|
|
836
|
+
return;
|
|
837
|
+
}
|
|
838
|
+
if (ev.kind === 'unknown') {
|
|
839
|
+
this._log(`Unrecognized frame (ignored): ${ev.raw}`);
|
|
840
|
+
}
|
|
841
|
+
};
|
|
842
|
+
|
|
843
|
+
const done = () => {
|
|
844
|
+
// Runs once: 'close' can still arrive after the fallback timer ended
|
|
845
|
+
// the turn, by which time this channel may be on its next turn.
|
|
846
|
+
if (settled) return;
|
|
847
|
+
// Flush a trailing line with no newline (the result frame, if the CLI
|
|
848
|
+
// exits without one).
|
|
849
|
+
if (stdoutBuf.trim()) { try { onFrame(stdoutBuf); } catch {} stdoutBuf = ''; }
|
|
850
|
+
const userStopped = this._stoppingChannels.has(channel);
|
|
851
|
+
this._stoppingChannels.delete(channel);
|
|
852
|
+
const { code = null, signal = null } = exitInfo || {};
|
|
853
|
+
finish({
|
|
854
|
+
code,
|
|
855
|
+
signal: killedByWatchdog ? 'SIGKILL' : signal,
|
|
856
|
+
result,
|
|
857
|
+
sessionId,
|
|
858
|
+
anyOutput,
|
|
859
|
+
lastAssistantText,
|
|
860
|
+
apiErrors,
|
|
861
|
+
userStopped,
|
|
862
|
+
stderr: stderrBuf,
|
|
863
|
+
});
|
|
864
|
+
};
|
|
865
|
+
|
|
866
|
+
// A stopped or killed child's pipes can emit 'error' (EPIPE/ECONNRESET,
|
|
867
|
+
// seen on macOS); unhandled, that would take the daemon down.
|
|
868
|
+
proc.stdout.on('error', () => {});
|
|
869
|
+
proc.stderr.on('error', () => {});
|
|
870
|
+
proc.stdout.setEncoding('utf8');
|
|
871
|
+
proc.stderr.setEncoding('utf8');
|
|
872
|
+
|
|
873
|
+
proc.stdout.on('data', (chunk) => {
|
|
874
|
+
stdoutBuf += chunk;
|
|
875
|
+
let nl;
|
|
876
|
+
while ((nl = stdoutBuf.indexOf('\n')) !== -1) {
|
|
877
|
+
const line = stdoutBuf.slice(0, nl);
|
|
878
|
+
stdoutBuf = stdoutBuf.slice(nl + 1);
|
|
879
|
+
try { onFrame(line); } catch (e) { this._log(`Frame handling failed: ${this._redact(e && e.message)}`, 'warn'); }
|
|
880
|
+
}
|
|
881
|
+
});
|
|
882
|
+
|
|
883
|
+
proc.stderr.on('data', (chunk) => {
|
|
884
|
+
// Bounded: a long run must not grow it without limit.
|
|
885
|
+
stderrBuf = truncate(stderrBuf + chunk, 8000);
|
|
886
|
+
});
|
|
887
|
+
|
|
888
|
+
proc.on('error', (e) => {
|
|
889
|
+
finish({ code: null, signal: null, result, sessionId, anyOutput, lastAssistantText, apiErrors, userStopped: false, spawnError: e && e.message });
|
|
890
|
+
});
|
|
891
|
+
|
|
892
|
+
proc.on('exit', (code, signal) => {
|
|
893
|
+
exitInfo = { code, signal };
|
|
894
|
+
// 'close' waits for every holder of the pipes. Something the CLI left
|
|
895
|
+
// running could keep them open, and the turn would never end.
|
|
896
|
+
closeFallback = setTimeout(done, 2000);
|
|
897
|
+
});
|
|
898
|
+
|
|
899
|
+
proc.on('close', (code, signal) => {
|
|
900
|
+
if (!exitInfo) exitInfo = { code, signal };
|
|
901
|
+
done();
|
|
902
|
+
});
|
|
903
|
+
|
|
904
|
+
const watchdog = setInterval(() => {
|
|
905
|
+
if (Date.now() - lastFrameAt < WATCHDOG_INTERVAL_MS) return;
|
|
906
|
+
silences += 1;
|
|
907
|
+
if (silences === WATCHDOG_NUDGE_AT) {
|
|
908
|
+
void this.sendStatus(channel, 'still working...').catch(() => {});
|
|
909
|
+
}
|
|
910
|
+
if (silences >= WATCHDOG_MAX) {
|
|
911
|
+
this._log('No output for ~5 minutes — killing a wedged run', 'warn');
|
|
912
|
+
killedByWatchdog = true;
|
|
913
|
+
void this._stopProcess(proc);
|
|
914
|
+
}
|
|
915
|
+
}, WATCHDOG_INTERVAL_MS);
|
|
916
|
+
|
|
917
|
+
try {
|
|
918
|
+
proc.stdin.on('error', () => {});
|
|
919
|
+
proc.stdin.write(prompt, 'utf-8');
|
|
920
|
+
proc.stdin.end();
|
|
921
|
+
} catch (e) {
|
|
922
|
+
this._log(`Could not write the prompt to stdin: ${this._redact(e && e.message)}`, 'warn');
|
|
923
|
+
}
|
|
924
|
+
});
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
// ------------------------------------------------------------------
|
|
928
|
+
// Message handling
|
|
929
|
+
// ------------------------------------------------------------------
|
|
930
|
+
|
|
931
|
+
async _handleMessage(msg) {
|
|
932
|
+
let content = (msg.content || '').trim();
|
|
933
|
+
const attachments = msg.attachments || [];
|
|
934
|
+
const attText = formatAttachmentsForPrompt(attachments, 'mcp');
|
|
935
|
+
if (attText) content = content ? content + attText : attText.trim();
|
|
936
|
+
if (!content) return;
|
|
937
|
+
|
|
938
|
+
const channel = msg.sessionId || this.channelName;
|
|
939
|
+
this._stoppingChannels.delete(channel);
|
|
940
|
+
const sender = msg.senderName || msg.senderType || 'user';
|
|
941
|
+
this._log(`Processing message from ${sender} in ${channel}: ${truncate(this._redact(content), 80)}`);
|
|
942
|
+
|
|
943
|
+
// Resolve the working directory up front. Never silently fall back to the
|
|
944
|
+
// launcher/repo dir — a wrong cwd is a destructive surprise, not a default.
|
|
945
|
+
const workingDir = this.workingDir || defaultAgentWorkdir(this.agentName);
|
|
946
|
+
if (this.workingDir && !this._dirExists(this.workingDir)) {
|
|
947
|
+
await this.sendError(channel, `Working directory does not exist: ${this.workingDir}`);
|
|
948
|
+
return;
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
const bin = this._findQwenBinary();
|
|
952
|
+
if (!bin) {
|
|
953
|
+
await this.sendError(channel, `Qwen Code CLI not found. Install it with: ${INSTALL_HINT}`);
|
|
954
|
+
return;
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
// HARD minimum gate. A confirmed-older CLI rejects this adapter's argv; an
|
|
958
|
+
// undetermined version (supported === null) proceeds leniently.
|
|
959
|
+
const ver = this._checkVersion(bin);
|
|
960
|
+
if (ver.supported === false) {
|
|
961
|
+
this._log(`Refusing to start: Qwen Code ${ver.version} < minimum ${QWEN_MIN_VERSION}`, 'warn');
|
|
962
|
+
await this.sendError(channel,
|
|
963
|
+
`Qwen Code ${ver.version} is below the minimum supported version ${QWEN_MIN_VERSION} ` +
|
|
964
|
+
`(the first release that accepts --mcp-config). Upgrade with: ${INSTALL_HINT}`);
|
|
965
|
+
return;
|
|
966
|
+
}
|
|
967
|
+
if (ver.supported === null) {
|
|
968
|
+
this._log('Could not determine the Qwen Code version — proceeding leniently');
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
// Auto-title + resume-from on first encounter (parity with other adapters).
|
|
972
|
+
if (!this._titledSessions.has(channel)) {
|
|
973
|
+
this._titledSessions.add(channel);
|
|
974
|
+
try {
|
|
975
|
+
const info = await this.client.getSession(this.workspaceId, channel, this.token);
|
|
976
|
+
const resumeFrom = info.resumeFrom;
|
|
977
|
+
if (resumeFrom && !this._channelSessions[channel] && this._channelSessions[resumeFrom]) {
|
|
978
|
+
this._channelSessions[channel] = { ...this._channelSessions[resumeFrom] };
|
|
979
|
+
this._saveSessions();
|
|
980
|
+
}
|
|
981
|
+
const title = generateSessionTitle(content);
|
|
982
|
+
if (title && !info.titleManuallySet && SESSION_DEFAULT_RE.test(info.title || '')) {
|
|
983
|
+
await this.client.updateSession(this.workspaceId, channel, this.token, { title, autoTitle: true });
|
|
984
|
+
}
|
|
985
|
+
} catch {}
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
await this.sendStatus(channel, 'thinking...');
|
|
989
|
+
|
|
990
|
+
const creds = resolveQwenCredentials(this.agentEnv, this.workspaceModel);
|
|
991
|
+
|
|
992
|
+
// The Claude builder is reused verbatim: Qwen Code takes the same
|
|
993
|
+
// --append-system-prompt hook, names MCP tools the same way
|
|
994
|
+
// (mcp__<server>__<tool>), and reaches the workspace through the same
|
|
995
|
+
// stdio MCP server, so the briefing is character-for-character the one
|
|
996
|
+
// that adapter already writes.
|
|
997
|
+
const systemPrompt = buildClaudeSystemPrompt({
|
|
998
|
+
agentName: this.agentName,
|
|
999
|
+
workspaceId: this.workspaceId,
|
|
1000
|
+
channelName: channel,
|
|
1001
|
+
mode: this._mode,
|
|
1002
|
+
model: creds.model || null,
|
|
1003
|
+
browserEnabled: await this.getBrowserEnabled(),
|
|
1004
|
+
toolMode: 'mcp',
|
|
1005
|
+
...this.pinnedPromptOpts(channel),
|
|
1006
|
+
});
|
|
1007
|
+
|
|
1008
|
+
const env = buildQwenChildEnv(getEnhancedEnv(this.agentEnv), {
|
|
1009
|
+
creds,
|
|
1010
|
+
defaultsPath: this._writeSystemDefaults() || '',
|
|
1011
|
+
});
|
|
1012
|
+
|
|
1013
|
+
// One retry: a stale session id (its transcript pruned, or the directory
|
|
1014
|
+
// re-keyed) fails the resume, and the turn is worth re-running fresh.
|
|
1015
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
1016
|
+
const resumeId = attempt === 0 ? this._resumableSession(channel, workingDir) : null;
|
|
1017
|
+
|
|
1018
|
+
// Resuming → the CLI already holds the history, so send the bare turn.
|
|
1019
|
+
// Fresh → prepend a recap of the channel.
|
|
1020
|
+
let prompt = content;
|
|
1021
|
+
if (!resumeId) {
|
|
1022
|
+
const recap = await this._buildChannelRecap(channel, content);
|
|
1023
|
+
if (recap) prompt = `${recap}\n\n---\n\n${content}`;
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
let runSettingsPath;
|
|
1027
|
+
try {
|
|
1028
|
+
if (creds.apiKey) runSettingsPath = this._writeRunSettings();
|
|
1029
|
+
} catch (e) {
|
|
1030
|
+
this._log(`Could not prepare Qwen Code settings: ${this._redact(e.message)}`, 'error');
|
|
1031
|
+
await this.sendError(channel, `Could not prepare Qwen Code settings: ${this._redact(e.message)}`);
|
|
1032
|
+
return;
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
const mcpConfigPath = this._writeMcpConfig(channel);
|
|
1036
|
+
const args = buildQwenArgs({
|
|
1037
|
+
appendSystemPrompt: systemPrompt,
|
|
1038
|
+
authType: creds.apiKey ? 'openai' : '',
|
|
1039
|
+
model: creds.model,
|
|
1040
|
+
resumeSessionId: resumeId || undefined,
|
|
1041
|
+
mcpConfigPath: mcpConfigPath || undefined,
|
|
1042
|
+
planMode: this._mode === 'plan',
|
|
1043
|
+
});
|
|
1044
|
+
|
|
1045
|
+
let run;
|
|
1046
|
+
try {
|
|
1047
|
+
const runEnv = runSettingsPath
|
|
1048
|
+
? {
|
|
1049
|
+
...env,
|
|
1050
|
+
QWEN_CODE_SYSTEM_SETTINGS_PATH: runSettingsPath,
|
|
1051
|
+
QWEN_CODE_SYSTEM_DEFAULTS_PATH: env.QWEN_CODE_SYSTEM_DEFAULTS_PATH
|
|
1052
|
+
|| qwenSystemDefaultsSource(this.agentEnv),
|
|
1053
|
+
} : env;
|
|
1054
|
+
run = await this._runQwen(channel, bin, args, workingDir, prompt, runEnv);
|
|
1055
|
+
} finally {
|
|
1056
|
+
if (mcpConfigPath) { try { fs.unlinkSync(mcpConfigPath); } catch {} }
|
|
1057
|
+
if (runSettingsPath) {
|
|
1058
|
+
// Older CLIs back up the settings file before migrating it.
|
|
1059
|
+
for (const file of [runSettingsPath, `${runSettingsPath}.orig`]) {
|
|
1060
|
+
try { fs.unlinkSync(file); } catch {}
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
if (run.userStopped) {
|
|
1066
|
+
// A stopped session is still resumable (verified), so the channel
|
|
1067
|
+
// keeps its conversation.
|
|
1068
|
+
this._rememberSession(channel, run.sessionId || resumeId, workingDir);
|
|
1069
|
+
return;
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
if (run.refused) {
|
|
1073
|
+
this._log(`Refusing to start: ${run.refused}`, 'error');
|
|
1074
|
+
await this.sendError(channel, run.refused);
|
|
1075
|
+
return;
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
if (run.spawnError) {
|
|
1079
|
+
this._log(`Could not start Qwen Code: ${this._redact(run.spawnError)}`, 'error');
|
|
1080
|
+
await this.sendError(channel,
|
|
1081
|
+
`Qwen Code CLI could not be started (${this._redact(run.spawnError)}). Reinstall it with: ${INSTALL_HINT}`);
|
|
1082
|
+
return;
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
const verdict = classifyQwenRun({ ...run, secrets: this._knownSecrets() });
|
|
1086
|
+
|
|
1087
|
+
// A resume the CLI could not find is the stale-session case: drop the
|
|
1088
|
+
// binding and retry once from scratch.
|
|
1089
|
+
if (resumeId && attempt === 0 && (verdict.kind === 'stale_session' || (!verdict.ok && !run.anyOutput))) {
|
|
1090
|
+
this._log(`Resume of session ${resumeId} failed (${verdict.kind}) — clearing and retrying fresh`, 'warn');
|
|
1091
|
+
this._clearSession(channel);
|
|
1092
|
+
continue;
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
// Persist the session id for the next turn. It comes off the init frame,
|
|
1096
|
+
// so this survives a turn that failed at the model call.
|
|
1097
|
+
this._rememberSession(channel, run.sessionId || resumeId, workingDir);
|
|
1098
|
+
|
|
1099
|
+
const resultText = run.result && run.result.text ? run.result.text.trim() : '';
|
|
1100
|
+
const finalText = resultText || (verdict.ok ? (run.lastAssistantText || '').trim() : '');
|
|
1101
|
+
|
|
1102
|
+
if (verdict.ok) {
|
|
1103
|
+
try {
|
|
1104
|
+
await this.sendResponse(channel, finalText || 'No response generated. Please try again.');
|
|
1105
|
+
} catch {}
|
|
1106
|
+
return;
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
// A failed run that still produced text (the model answered, then a later
|
|
1110
|
+
// step failed) delivers the text with the reason appended rather than
|
|
1111
|
+
// replacing an answer the user can use.
|
|
1112
|
+
if (finalText) {
|
|
1113
|
+
this._log(`Run reported ${verdict.kind} but returned text; text delivered`, 'warn');
|
|
1114
|
+
try { await this.sendResponse(channel, `${finalText}\n\n_${verdict.userMessage}_`); } catch {}
|
|
1115
|
+
return;
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
this._log(`Run failed (${verdict.kind}, exit ${run.code}): ${truncate(this._redact(run.stderr || ''), 300)}`, 'error');
|
|
1119
|
+
try { await this.sendError(channel, verdict.userMessage); } catch {}
|
|
1120
|
+
return;
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
module.exports = QwenCodeAdapter;
|