@openagents-org/agent-launcher 0.2.210 → 0.2.212

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.
@@ -0,0 +1,735 @@
1
+ /**
2
+ * Pure helpers for the Qwen Code adapter — argv construction, stream-json frame
3
+ * interpretation, run classification, credential and child-env resolution, the
4
+ * settings layer that turns auto-memory off, and the version gate.
5
+ *
6
+ * Split out from qwen-code.js so the parts with real decision logic are unit
7
+ * testable without spawning a CLI, an account, or a workspace.
8
+ *
9
+ * Four facts about Qwen Code's headless contract shape everything here, all
10
+ * verified against the real CLI (@qwen-code/qwen-code 0.25.1) rather than read
11
+ * off a docs page:
12
+ *
13
+ * 1. THE FRAMES ARE CLAUDE CODE'S. `-o stream-json` emits system/init, then
14
+ * one `assistant` frame per content block (thinking, text or tool_use),
15
+ * `user` frames carrying tool results, and one closing `result` frame.
16
+ * The answer is `result.result`; assistant frames only drive the ticker.
17
+ * 2. A FAILED RUN STILL WRITES A RESULT FRAME. Model and auth errors arrive
18
+ * as `result` with `is_error: true` and `error.message`, exit code 1, and
19
+ * nothing on stderr in 0.25.1. 0.16.0 instead wraps an API error in a
20
+ * successful result and exits 0; that result is normalized below.
21
+ * The same error is ALSO streamed first as assistant
22
+ * text ("[API Error: 401 …]"), which must not be mistaken for an answer.
23
+ * Exit 130 is a SIGINT/SIGTERM stop (no result frame), 53 a turn cap and
24
+ * 55 a budget abort.
25
+ * 3. CREDENTIALS NEED AN EXPLICIT AUTH TYPE. The CLI only infers its OpenAI
26
+ * provider when OPENAI_API_KEY AND a model are both in the environment; a
27
+ * key and base URL without a model fails with "No auth type is selected".
28
+ * Passing `--auth-type openai` removes the guess.
29
+ * 4. AUTO-MEMORY HOLDS THE RESULT FRAME HOSTAGE. With the default
30
+ * `memory.enableManagedAutoMemory`, every turn ends with a memory-
31
+ * extractor subagent the run waits for: the answer was on stdout after 7s
32
+ * and the result frame after 194s, with 100k+ extra tokens spent. A
33
+ * system-defaults settings layer (QWEN_CODE_SYSTEM_DEFAULTS_PATH) turns it
34
+ * off without touching the user's own ~/.qwen/settings.json.
35
+ */
36
+
37
+ 'use strict';
38
+
39
+ const { maskSecretValues } = require('./utils');
40
+
41
+ // Supported floor: the first release that accepts every flag buildQwenArgs()
42
+ // passes. 0.15.0 rejects `--mcp-config` as an unknown argument; 0.16.0 takes
43
+ // the whole argv (verified by running each release with it).
44
+ const QWEN_MIN_VERSION = '0.16.0';
45
+ // Highest version whose behavior was verified end to end. Newer is allowed —
46
+ // it just isn't claimed as tested.
47
+ const QWEN_TESTED_MAX_VERSION = '0.25.1';
48
+
49
+ // Where a blank base URL points. Every Qwen Code user this agent is for holds
50
+ // a Model Studio (DashScope) key, and the launcher's model picker lists from
51
+ // the same endpoint — a blank URL reaching api.openai.com instead would fail
52
+ // as an "incorrect API key" that names neither.
53
+ const QWEN_DEFAULT_BASE_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
54
+
55
+ // ---------------------------------------------------------------------------
56
+ // Version gate
57
+ // ---------------------------------------------------------------------------
58
+
59
+ /** Extract a dotted version from `--version` output. Returns null if absent. */
60
+ function parseQwenVersion(raw) {
61
+ if (!raw || typeof raw !== 'string') return null;
62
+ const m = raw.match(/(\d+)\.(\d+)\.(\d+)(?:[-.][0-9A-Za-z.]+)?/);
63
+ return m ? `${m[1]}.${m[2]}.${m[3]}` : null;
64
+ }
65
+
66
+ /** Numeric compare of two dotted versions. Returns -1 / 0 / 1. */
67
+ function compareVersions(a, b) {
68
+ const pa = String(a).split('.').map((n) => parseInt(n, 10) || 0);
69
+ const pb = String(b).split('.').map((n) => parseInt(n, 10) || 0);
70
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
71
+ const x = pa[i] || 0;
72
+ const y = pb[i] || 0;
73
+ if (x !== y) return x < y ? -1 : 1;
74
+ }
75
+ return 0;
76
+ }
77
+
78
+ /**
79
+ * Classify a raw `--version` string.
80
+ *
81
+ * `supported: null` means "could not tell" — an unreadable version proceeds
82
+ * leniently rather than blocking a CLI that is probably fine. Only a version we
83
+ * positively read AND that is below the floor returns `false`.
84
+ */
85
+ function classifyQwenVersion(rawVersion) {
86
+ const version = parseQwenVersion(rawVersion);
87
+ if (!version) return { version: null, supported: null, tested: null };
88
+ return {
89
+ version,
90
+ supported: compareVersions(version, QWEN_MIN_VERSION) >= 0,
91
+ tested: compareVersions(version, QWEN_TESTED_MAX_VERSION) <= 0,
92
+ };
93
+ }
94
+
95
+ // ---------------------------------------------------------------------------
96
+ // Redaction
97
+ // ---------------------------------------------------------------------------
98
+
99
+ const SECRET_PATTERNS = [
100
+ // Provider API keys: sk-..., which covers Model Studio and Coding Plan keys.
101
+ /\bsk-[A-Za-z0-9._-]{8,}\b/g,
102
+ // Bearer tokens in copied headers.
103
+ /\bBearer\s+[A-Za-z0-9._-]{8,}\b/gi,
104
+ // JWTs, which is what the workspace token is.
105
+ /\beyJ[A-Za-z0-9._-]{16,}\b/g,
106
+ // Long opaque blobs assigned to a secret-looking key.
107
+ /\b(api[_-]?key|token|secret|password|authorization)\b\s*[:=]\s*["']?[A-Za-z0-9._-]{8,}["']?/gi,
108
+ ];
109
+
110
+ /**
111
+ * Redact free text before it is logged or posted: the agent's own secrets by
112
+ * value first (`secrets`, from BaseAdapter._knownSecrets()), so a key in a
113
+ * format no pattern knows is still caught, then anything shaped like a
114
+ * credential. Named apart from utils.redactSecrets, whose broader shape rules
115
+ * would rewrite the CLI's own error wording.
116
+ */
117
+ function redactQwenText(text, secrets) {
118
+ if (text == null) return text;
119
+ let out = maskSecretValues(text, secrets);
120
+ for (const re of SECRET_PATTERNS) {
121
+ out = out.replace(re, (m) => {
122
+ const eq = m.match(/\s*[:=]\s*/);
123
+ if (eq) return m.slice(0, m.indexOf(eq[0])) + eq[0] + '[redacted]';
124
+ return /^bearer/i.test(m) ? 'Bearer [redacted]' : '[redacted]';
125
+ });
126
+ }
127
+ return out;
128
+ }
129
+
130
+ /** Truncate with an ellipsis, for previews and diagnostics. */
131
+ function truncate(s, n) {
132
+ s = String(s == null ? '' : s);
133
+ return s.length > n ? s.slice(0, n - 1) + '…' : s;
134
+ }
135
+
136
+ /**
137
+ * Redact an argv for logging.
138
+ *
139
+ * The prompt is piped over stdin and the key travels in the environment, so
140
+ * neither appears here. The values worth hiding are the resumed session id and
141
+ * the system prompt, which carries the agent's workspace identity and runs to
142
+ * kilobytes.
143
+ */
144
+ function redactArgs(args) {
145
+ const out = [];
146
+ for (let i = 0; i < args.length; i++) {
147
+ const a = args[i];
148
+ out.push(a);
149
+ if ((a === '--resume' || a === '-r') && args[i + 1]) {
150
+ out.push('<session-id>');
151
+ i++;
152
+ } else if (a === '--append-system-prompt' && args[i + 1]) {
153
+ out.push('<system-prompt>');
154
+ i++;
155
+ } else if (a === '--openai-api-key' && args[i + 1]) {
156
+ out.push('[redacted]');
157
+ i++;
158
+ }
159
+ }
160
+ return out;
161
+ }
162
+
163
+ // ---------------------------------------------------------------------------
164
+ // Credentials and the child environment
165
+ // ---------------------------------------------------------------------------
166
+
167
+ function firstSet(env, names) {
168
+ for (const name of names) {
169
+ const v = String((env && env[name]) || '').trim();
170
+ if (v) return v;
171
+ }
172
+ return '';
173
+ }
174
+
175
+ /**
176
+ * The key, base URL and model this agent runs with.
177
+ *
178
+ * The three values come as a SET from one source, never mixed: the agent's own
179
+ * form fields (LLM_*) when it has a key there, otherwise OPENAI_* from the
180
+ * environment. Mixing them is how a run ends up sending this agent's DashScope
181
+ * key to the OpenAI base URL the user exported for another tool.
182
+ *
183
+ * The workspace's model picker outranks either source's model.
184
+ *
185
+ * @returns {{apiKey: string, baseUrl: string, model: string, source: 'agent'|'env'|'none'}}
186
+ */
187
+ function resolveQwenCredentials(agentEnv = {}, workspaceModel = '') {
188
+ const picked = String(workspaceModel || '').trim();
189
+ if (firstSet(agentEnv, ['LLM_API_KEY'])) {
190
+ return {
191
+ apiKey: firstSet(agentEnv, ['LLM_API_KEY']),
192
+ baseUrl: firstSet(agentEnv, ['LLM_BASE_URL']),
193
+ model: picked || firstSet(agentEnv, ['LLM_MODEL']),
194
+ source: 'agent',
195
+ };
196
+ }
197
+ if (firstSet(agentEnv, ['OPENAI_API_KEY'])) {
198
+ return {
199
+ apiKey: firstSet(agentEnv, ['OPENAI_API_KEY']),
200
+ baseUrl: firstSet(agentEnv, ['OPENAI_BASE_URL']),
201
+ model: picked || firstSet(agentEnv, ['OPENAI_MODEL', 'QWEN_MODEL']),
202
+ source: 'env',
203
+ };
204
+ }
205
+ // No key of ours: the CLI falls back to whatever its own settings.json
206
+ // configures (a provider set up with /auth in an interactive session).
207
+ return { apiKey: '', baseUrl: '', model: picked, source: 'none' };
208
+ }
209
+
210
+ /**
211
+ * The environment for one headless run — pure, so the whole auth story is
212
+ * testable without spawning anything.
213
+ *
214
+ * With a key, the OPENAI_* trio is written explicitly, so nothing exported for
215
+ * another tool can leak in. A blank base URL becomes Model Studio only for the
216
+ * agent's own key: a key that came from OPENAI_* in the environment was
217
+ * exported for some other tool, most likely for api.openai.com, and must never
218
+ * be sent to a different provider by default — it explicitly uses OpenAI's
219
+ * default so saved settings cannot redirect that key either.
220
+ * Without a key, the environment is left alone for the CLI's own settings.
221
+ *
222
+ * @param {object} baseEnv the agent's full environment (process env included)
223
+ * @param {object} o
224
+ * @param {object} o.creds resolveQwenCredentials() output
225
+ * @param {string} [o.defaultsPath] system-defaults settings file to load
226
+ * @returns {object} a new environment object
227
+ */
228
+ function buildQwenChildEnv(baseEnv = {}, { creds = {}, defaultsPath = '' } = {}) {
229
+ const env = { ...baseEnv };
230
+ if (creds.apiKey) {
231
+ env.OPENAI_API_KEY = creds.apiKey;
232
+ env.OPENAI_BASE_URL = creds.baseUrl || (creds.source === 'agent'
233
+ ? QWEN_DEFAULT_BASE_URL : 'https://api.openai.com/v1');
234
+ if (creds.model) env.OPENAI_MODEL = creds.model;
235
+ else delete env.OPENAI_MODEL;
236
+ }
237
+ if (defaultsPath) env.QWEN_CODE_SYSTEM_DEFAULTS_PATH = defaultsPath;
238
+ // Approval mode is yolo by design (nobody is at a terminal to approve), and
239
+ // the CLI otherwise repeats a warning about it on stderr every run, where it
240
+ // would bury a real startup error.
241
+ env.QWEN_CODE_SUPPRESS_YOLO_WARNING = '1';
242
+ return env;
243
+ }
244
+
245
+ // ---------------------------------------------------------------------------
246
+ // The system-defaults settings layer
247
+ // ---------------------------------------------------------------------------
248
+
249
+ /**
250
+ * Settings this adapter needs that have no command-line flag.
251
+ *
252
+ * Only what a headless run depends on is here — anything else is the user's
253
+ * call, not the adapter's. Loaded as Qwen Code's lowest-precedence "system
254
+ * defaults" scope, so the user's own settings.json (and a project's
255
+ * .qwen/settings.json) still win: someone who wants auto-memory back turns it
256
+ * on there.
257
+ */
258
+ const QWEN_SETTINGS_DEFAULTS = {
259
+ memory: {
260
+ // The post-turn memory extractor delays every result frame by seconds to
261
+ // minutes (see the file header); "dream" is its background consolidation.
262
+ enableManagedAutoMemory: false,
263
+ enableManagedAutoDream: false,
264
+ },
265
+ general: {
266
+ // A self-update would swap the CLI — and the stream contract parsed here —
267
+ // under a daemon that is mid-run. Upgrades go through the launcher.
268
+ enableAutoUpdate: false,
269
+ disableAutoUpdate: true,
270
+ },
271
+ };
272
+
273
+ function isPlainObject(v) {
274
+ return !!v && typeof v === 'object' && !Array.isArray(v);
275
+ }
276
+
277
+ function deepMerge(base, over) {
278
+ const out = { ...base };
279
+ for (const [k, v] of Object.entries(over || {})) {
280
+ out[k] = isPlainObject(v) && isPlainObject(out[k]) ? deepMerge(out[k], v) : v;
281
+ }
282
+ return out;
283
+ }
284
+
285
+ /**
286
+ * The defaults layer to hand the CLI: this adapter's settings under whatever a
287
+ * machine-wide system-defaults file already sets, which wins key by key.
288
+ */
289
+ function buildQwenSystemDefaults(existing = null) {
290
+ return deepMerge(QWEN_SETTINGS_DEFAULTS, isPlainObject(existing) ? existing : {});
291
+ }
292
+
293
+ function canonicalJson(v) {
294
+ if (Array.isArray(v)) return `[${v.map(canonicalJson).join(',')}]`;
295
+ if (isPlainObject(v)) {
296
+ return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${canonicalJson(v[k])}`).join(',')}}`;
297
+ }
298
+ return JSON.stringify(v);
299
+ }
300
+
301
+ /**
302
+ * True when a settings file already holds `desired`.
303
+ *
304
+ * The CLI migrates any settings file it loads and writes the result back,
305
+ * stamping a top-level `$version` (verified: our file came back with
306
+ * `"$version": 4`). That stamp is not a difference — rewriting over it would
307
+ * only make the CLI migrate and write again on the next run, while another
308
+ * channel's run may be reading the file.
309
+ */
310
+ function sameQwenSettings(onDisk, desired) {
311
+ if (!isPlainObject(onDisk) || !isPlainObject(desired)) return false;
312
+ const strip = (o) => { const { $version, ...rest } = o; return rest; };
313
+ return canonicalJson(strip(onDisk)) === canonicalJson(strip(desired));
314
+ }
315
+
316
+ /**
317
+ * Where the CLI would read its system-defaults file from, so a machine-wide
318
+ * one is merged rather than replaced. Mirrors the CLI's own lookup: an
319
+ * explicit QWEN_CODE_SYSTEM_DEFAULTS_PATH, otherwise `system-defaults.json`
320
+ * next to the system settings file.
321
+ */
322
+ function qwenSystemDefaultsSource(env = {}, platform = process.platform) {
323
+ const explicit = String(env.QWEN_CODE_SYSTEM_DEFAULTS_PATH || '').trim();
324
+ if (explicit) return explicit;
325
+ const settings = qwenSystemSettingsSource(env, platform);
326
+ const sep = platform === 'win32' ? '\\' : '/';
327
+ const cut = Math.max(settings.lastIndexOf('/'), settings.lastIndexOf('\\'));
328
+ return (cut >= 0 ? settings.slice(0, cut) : '.') + sep + 'system-defaults.json';
329
+ }
330
+
331
+ function qwenSystemSettingsSource(env = {}, platform = process.platform) {
332
+ return String(env.QWEN_CODE_SYSTEM_SETTINGS_PATH || '').trim()
333
+ || (platform === 'darwin' ? '/Library/Application Support/QwenCode/settings.json'
334
+ : platform === 'win32' ? 'C:\\ProgramData\\qwen-code\\settings.json'
335
+ : '/etc/qwen-code/settings.json');
336
+ }
337
+
338
+ /** Match Qwen's settings reader: JSON with comments and an optional UTF-8 BOM. */
339
+ function parseQwenSettings(source) {
340
+ const json = String(source).replace(/^\uFEFF/, '').replace(
341
+ /"(?:\\.|[^"\\])*"|\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g,
342
+ (token) => token.startsWith('"') ? token : token.replace(/[^\r\n]/g, ' '),
343
+ );
344
+ const settings = JSON.parse(json);
345
+ if (!isPlainObject(settings)) throw new SyntaxError('Expected a settings object.');
346
+ return settings;
347
+ }
348
+
349
+ // ---------------------------------------------------------------------------
350
+ // argv
351
+ // ---------------------------------------------------------------------------
352
+
353
+ /**
354
+ * Built-in tools a workspace agent must not use.
355
+ *
356
+ * They schedule work inside the CLI's own process — which, in a one-shot
357
+ * headless run, exits as soon as the turn ends, so a reminder set this way
358
+ * never fires (or keeps the run alive waiting for it). Workspace timers and
359
+ * routines, reached over MCP, are the scheduling that outlives the turn.
360
+ */
361
+ const EXCLUDED_TOOLS = [
362
+ 'cron_create',
363
+ 'cron_list',
364
+ 'cron_delete',
365
+ 'loop_wakeup',
366
+ ];
367
+
368
+ /**
369
+ * Build the argv for one headless run.
370
+ *
371
+ * THE PROMPT IS NOT HERE. With no positional query the CLI reads the turn from
372
+ * stdin and runs it once (verified), so an arbitrarily long turn — channel
373
+ * recap plus the user's message — stays away from the OS argv limit, and a
374
+ * quote in a user message cannot become a command-line injection. The key is
375
+ * not here either: it travels in the environment, out of the process list.
376
+ *
377
+ * @param {object} o
378
+ * @param {string} [o.appendSystemPrompt] workspace briefing appended to the CLI's own prompt
379
+ * @param {string} [o.authType] 'openai' when this agent supplies the key
380
+ * @param {string} [o.model] model id (empty = provider default)
381
+ * @param {string} [o.resumeSessionId] continue this channel's CLI session
382
+ * @param {string} [o.mcpConfigPath] path to the workspace MCP server config
383
+ * @param {boolean} [o.planMode] read-only investigation instead of full access
384
+ * @returns {string[]}
385
+ */
386
+ function buildQwenArgs(o = {}) {
387
+ const args = ['--output-format', 'stream-json'];
388
+
389
+ // Headless has no one to answer a permission prompt; without yolo the CLI
390
+ // silently drops every write and shell tool from the run. Plan mode keeps
391
+ // read-only tools only (verified against the init frame's tool list).
392
+ args.push('--approval-mode', o.planMode ? 'plan' : 'yolo');
393
+
394
+ // An array option: yargs reads values until the next flag, so another flag
395
+ // must always follow it.
396
+ args.push('--exclude-tools', ...EXCLUDED_TOOLS);
397
+
398
+ const authType = (o.authType || '').trim();
399
+ if (authType) args.push('--auth-type', authType);
400
+
401
+ const model = (o.model || '').trim();
402
+ if (model) args.push('--model', model);
403
+
404
+ if (o.mcpConfigPath) args.push('--mcp-config', o.mcpConfigPath);
405
+
406
+ const resume = (o.resumeSessionId || '').trim();
407
+ if (resume) args.push('--resume', resume);
408
+
409
+ const systemPrompt = (o.appendSystemPrompt || '').trim();
410
+ if (systemPrompt) args.push('--append-system-prompt', systemPrompt);
411
+
412
+ return args;
413
+ }
414
+
415
+ // ---------------------------------------------------------------------------
416
+ // stream-json frames
417
+ // ---------------------------------------------------------------------------
418
+
419
+ /** Parse one NDJSON line. Returns null for blank lines and malformed JSON. */
420
+ function parseFrame(line) {
421
+ const s = String(line == null ? '' : line).trim();
422
+ if (!s || s[0] !== '{') return null;
423
+ try {
424
+ const v = JSON.parse(s);
425
+ return v && typeof v === 'object' ? v : null;
426
+ } catch {
427
+ return null;
428
+ }
429
+ }
430
+
431
+ /**
432
+ * A short, human-readable preview of a tool call's input, for the channel's
433
+ * activity ticker.
434
+ */
435
+ function toolInputPreview(input, secrets) {
436
+ if (input == null) return '';
437
+ if (typeof input !== 'object') return truncate(redactQwenText(String(input), secrets), 150);
438
+ const first = input.command || input.file_path || input.absolute_path || input.path
439
+ || input.pattern || input.query || input.url || input.prompt || input.description;
440
+ if (typeof first === 'string' && first) return truncate(redactQwenText(first, secrets), 150);
441
+ if (typeof input.content === 'string') return truncate(redactQwenText(input.content, secrets), 100);
442
+ try {
443
+ const json = JSON.stringify(input);
444
+ return json === '{}' ? '' : truncate(redactQwenText(json, secrets), 150);
445
+ } catch {
446
+ return '';
447
+ }
448
+ }
449
+
450
+ /** `mcp__openagents-workspace__workspace_get_history` → `workspace_get_history`. */
451
+ function shortToolName(name) {
452
+ const m = String(name || '').match(/^mcp__.+?__(.+)$/);
453
+ return m ? m[1] : String(name || '');
454
+ }
455
+
456
+ /**
457
+ * Describe one tool_use block for the ticker, or null for plumbing.
458
+ *
459
+ * MCP tools are deferred: the model looks one up with `tool_search` and then
460
+ * calls it through the generic `tool_call` wrapper (verified). The lookup is
461
+ * not activity worth announcing, and the wrapper is announced as the tool it
462
+ * actually ran.
463
+ */
464
+ function describeToolUse(block, secrets) {
465
+ const name = typeof block.name === 'string' ? block.name : '';
466
+ const input = block.input && typeof block.input === 'object' ? block.input : {};
467
+ if (name === 'tool_search') return null;
468
+ if (name === 'tool_call' && typeof input.name === 'string' && input.name) {
469
+ return { name: shortToolName(input.name), preview: toolInputPreview(input.arguments, secrets) };
470
+ }
471
+ return { name: shortToolName(name), preview: toolInputPreview(input, secrets) };
472
+ }
473
+
474
+ // An API failure is streamed as assistant text before the result frame
475
+ // reports it. It is the error, not an answer.
476
+ const API_ERROR_TEXT_RE = /^\[API Error:/;
477
+
478
+ // Frames that carry no user-visible progress. Listing them keeps them out of
479
+ // the `unknown` diagnostic channel, so a genuinely new frame type still shows
480
+ // up in the log instead of being lost in the noise. `stream_event` carries the
481
+ // per-run goal_state ping (and partial deltas, which are not requested).
482
+ const IGNORED_FRAMES = new Set(['user', 'stream_event']);
483
+
484
+ /**
485
+ * Normalize one parsed frame into something the adapter can act on.
486
+ *
487
+ * @param {object} frame
488
+ * @param {string[]} [secrets] exact values to mask in any text kept from it
489
+ * @returns {{kind: string, [k: string]: any}}
490
+ */
491
+ function interpretQwenFrame(frame, secrets) {
492
+ if (!frame || typeof frame !== 'object') return { kind: 'ignored' };
493
+
494
+ if (frame.type === 'result') {
495
+ const err = frame.error && typeof frame.error === 'object' ? frame.error : null;
496
+ const text = typeof frame.result === 'string' ? frame.result : '';
497
+ // 0.16.0 wraps provider failures in a success result and exits 0.
498
+ const legacyError = frame.is_error !== true && API_ERROR_TEXT_RE.test(text.trim())
499
+ ? redactQwenText(text, secrets) : '';
500
+ return {
501
+ kind: 'result',
502
+ subtype: typeof frame.subtype === 'string' ? frame.subtype : '',
503
+ isError: frame.is_error === true || !!legacyError,
504
+ // `result` is present on success and absent on failure; always a string
505
+ // here so callers never have to guard it.
506
+ text: legacyError ? '' : text,
507
+ errorMessage: err && typeof err.message === 'string' ? redactQwenText(err.message, secrets) : legacyError,
508
+ sessionId: typeof frame.session_id === 'string' ? frame.session_id : null,
509
+ numTurns: Number.isFinite(frame.num_turns) ? frame.num_turns : null,
510
+ durationMs: Number.isFinite(frame.duration_ms) ? frame.duration_ms : null,
511
+ };
512
+ }
513
+
514
+ if (frame.type === 'system') {
515
+ if (frame.subtype === 'init') {
516
+ return {
517
+ kind: 'init',
518
+ sessionId: typeof frame.session_id === 'string' ? frame.session_id : null,
519
+ model: typeof frame.model === 'string' ? frame.model : '',
520
+ permissionMode: typeof frame.permission_mode === 'string' ? frame.permission_mode : '',
521
+ mcpServers: Array.isArray(frame.mcp_servers)
522
+ ? frame.mcp_servers.filter((s) => s && typeof s === 'object')
523
+ : [],
524
+ version: typeof frame.qwen_code_version === 'string' ? frame.qwen_code_version : '',
525
+ };
526
+ }
527
+ // Compaction is the one system message worth showing: it is slow, and a
528
+ // silent channel during it reads as a hang.
529
+ const message = typeof frame.message === 'string' ? frame.message : '';
530
+ const subtype = typeof frame.subtype === 'string' ? frame.subtype : '';
531
+ if (subtype.includes('compact') || /compact/i.test(message)) {
532
+ return { kind: 'status', text: message || 'Compacting the conversation...' };
533
+ }
534
+ return { kind: 'ignored' };
535
+ }
536
+
537
+ if (frame.type === 'assistant') {
538
+ const blocks = (frame.message && Array.isArray(frame.message.content))
539
+ ? frame.message.content : [];
540
+ const texts = [];
541
+ const tools = [];
542
+ const apiErrors = [];
543
+ for (const block of blocks) {
544
+ if (!block || typeof block !== 'object') continue;
545
+ if (block.type === 'text' && typeof block.text === 'string' && block.text.trim()) {
546
+ const text = block.text.trim();
547
+ if (API_ERROR_TEXT_RE.test(text)) apiErrors.push(redactQwenText(text, secrets));
548
+ else texts.push(text);
549
+ } else if (block.type === 'tool_use') {
550
+ const tool = describeToolUse(block, secrets);
551
+ if (tool) tools.push(tool);
552
+ }
553
+ // `thinking` blocks are the model's private reasoning; the Claude
554
+ // adapter does not post them either.
555
+ }
556
+ if (!texts.length && !tools.length && !apiErrors.length) return { kind: 'ignored' };
557
+ return { kind: 'assistant', texts, tools, apiErrors };
558
+ }
559
+
560
+ if (IGNORED_FRAMES.has(frame.type)) return { kind: 'ignored' };
561
+
562
+ return { kind: 'unknown', raw: truncate(redactQwenText(String(frame.type || ''), secrets), 80) };
563
+ }
564
+
565
+ // ---------------------------------------------------------------------------
566
+ // Run classification
567
+ // ---------------------------------------------------------------------------
568
+
569
+ const CODING_PLAN_HINT = 'Model Studio (DashScope) keys and Coding Plan keys are not interchangeable: ' +
570
+ 'a Coding Plan key needs https://coding.dashscope.aliyuncs.com/v1 (international: ' +
571
+ 'https://coding-intl.dashscope.aliyuncs.com/v1).';
572
+
573
+ /**
574
+ * What a run's error message means for the user, first match wins. Matched on
575
+ * the CLI's own `error.message`, which carries the provider's status code and
576
+ * text verbatim ("[API Error: 401 Incorrect API key provided…]").
577
+ */
578
+ const ERROR_RULES = [
579
+ {
580
+ kind: 'not_configured',
581
+ re: /No auth type is selected/i,
582
+ message: 'Qwen Code has no model credentials. Set an API key for this agent (and a base URL and ' +
583
+ 'model if you are not using Model Studio) — the default base URL is ' +
584
+ `${QWEN_DEFAULT_BASE_URL}. ${CODING_PLAN_HINT}`,
585
+ detail: false,
586
+ },
587
+ {
588
+ kind: 'auth',
589
+ re: /\b(401|403)\b|incorrect api key|invalid (access )?token|invalid api[ _-]?key|unauthori[sz]ed|token expired/i,
590
+ message: `The model endpoint rejected the API key. Check the key, and that it belongs to the base URL's service. ${CODING_PLAN_HINT}`,
591
+ detail: true,
592
+ },
593
+ {
594
+ kind: 'model',
595
+ re: /\b404\b|model\b[^.]*\b(does not exist|not found|not exist|unsupported)|model_not_found/i,
596
+ message: 'The endpoint does not serve the configured model. Pick a model the base URL offers.',
597
+ detail: true,
598
+ },
599
+ {
600
+ kind: 'quota',
601
+ re: /\b429\b|rate.?limit|quota|insufficient|arrearage|exceeded your/i,
602
+ message: 'The model endpoint is rate limiting this key or the account is out of quota. Wait, or top the account up, then retry.',
603
+ detail: true,
604
+ },
605
+ {
606
+ kind: 'network',
607
+ re: /connection error|fetch failed|ENOTFOUND|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|socket hang up|certificate|timed? ?out/i,
608
+ message: 'Qwen Code could not reach the model endpoint. Check the base URL, the network, and any proxy settings.',
609
+ detail: true,
610
+ },
611
+ {
612
+ kind: 'model_service',
613
+ re: /\b5\d\d\b/,
614
+ message: 'The model service returned a server error. This is usually temporary — retry shortly.',
615
+ detail: true,
616
+ },
617
+ ];
618
+
619
+ function messageFor(text, secrets) {
620
+ const raw = String(text || '').trim();
621
+ const detail = truncate(redactQwenText(raw.replace(/^\[API Error:\s*/i, '').replace(/\]$/, ''), secrets), 300);
622
+ for (const rule of ERROR_RULES) {
623
+ if (rule.re.test(raw)) {
624
+ return {
625
+ kind: rule.kind,
626
+ userMessage: rule.detail && detail ? `${rule.message} (${detail})` : rule.message,
627
+ };
628
+ }
629
+ }
630
+ return null;
631
+ }
632
+
633
+ // What the CLI prints, on stderr only, when `--resume` names a session it does
634
+ // not have — pruned, or recorded under a different working directory.
635
+ const STALE_SESSION_RE = /No saved session found/i;
636
+
637
+ /**
638
+ * Classify how a run ended.
639
+ *
640
+ * The result frame outranks the exit code: it is present on every model and
641
+ * auth failure and says what went wrong. The exit code and stderr are read only
642
+ * when no result frame arrived, which is the stopped / crashed / refused-to-
643
+ * start case.
644
+ *
645
+ * @param {object} o
646
+ * @param {object|null} [o.result] the interpreted result frame, when one arrived
647
+ * @param {number|null} [o.code] process exit code
648
+ * @param {string|null} [o.signal] terminating signal, if any
649
+ * @param {string} [o.stderr] captured stderr
650
+ * @param {string[]} [o.apiErrors] API error texts streamed before the result
651
+ * @param {string[]} [o.secrets] exact values to mask in any quoted CLI text
652
+ * @returns {{kind: string, ok: boolean, userMessage: string|null}}
653
+ */
654
+ function classifyQwenRun({ result = null, code = null, signal = null, stderr = '', apiErrors = [], secrets = [] } = {}) {
655
+ if (result && !result.isError) {
656
+ return { kind: 'success', ok: true, userMessage: null };
657
+ }
658
+
659
+ if (result && result.isError) {
660
+ const text = result.errorMessage || (apiErrors && apiErrors[0]) || '';
661
+ const known = messageFor(text, secrets);
662
+ if (known) return { ...known, ok: false };
663
+ return {
664
+ kind: 'run_error',
665
+ ok: false,
666
+ userMessage: text
667
+ ? `Qwen Code could not finish the run: ${truncate(redactQwenText(text, secrets), 400)}`
668
+ : 'Qwen Code could not finish the run. Check the daemon log for details, then retry.',
669
+ };
670
+ }
671
+
672
+ // No result frame from here down.
673
+ if (code === 53) {
674
+ return { kind: 'turn_limit', ok: false, userMessage: 'Qwen Code stopped at its turn limit before finishing.' };
675
+ }
676
+ if (code === 55) {
677
+ return { kind: 'budget', ok: false, userMessage: 'Qwen Code stopped at its time or tool-call budget before finishing.' };
678
+ }
679
+ if (signal || code === 130) {
680
+ return { kind: 'interrupted', ok: false, userMessage: 'The run was interrupted.' };
681
+ }
682
+
683
+ const err = String(stderr || '').trim();
684
+ if (STALE_SESSION_RE.test(err)) {
685
+ return { kind: 'stale_session', ok: false, userMessage: 'The saved Qwen Code session could not be resumed.' };
686
+ }
687
+ const streamed = apiErrors && apiErrors[0];
688
+ if (streamed) {
689
+ const known = messageFor(streamed, secrets);
690
+ if (known) return { ...known, ok: false };
691
+ }
692
+ if (err) {
693
+ const firstLine = err.split('\n').map((l) => l.trim()).find(Boolean) || err;
694
+ return {
695
+ kind: 'startup_error',
696
+ ok: false,
697
+ userMessage: `Qwen Code stopped before answering: ${truncate(redactQwenText(firstLine, secrets), 400)}`,
698
+ };
699
+ }
700
+
701
+ return {
702
+ kind: 'no_result',
703
+ ok: false,
704
+ userMessage: `Qwen Code exited without answering (code ${code}). Check the daemon log, then retry.`,
705
+ };
706
+ }
707
+
708
+ module.exports = {
709
+ QWEN_MIN_VERSION,
710
+ QWEN_TESTED_MAX_VERSION,
711
+ QWEN_DEFAULT_BASE_URL,
712
+ QWEN_SETTINGS_DEFAULTS,
713
+ EXCLUDED_TOOLS,
714
+ ERROR_RULES,
715
+ parseQwenVersion,
716
+ compareVersions,
717
+ classifyQwenVersion,
718
+ redactQwenText,
719
+ redactArgs,
720
+ truncate,
721
+ resolveQwenCredentials,
722
+ buildQwenChildEnv,
723
+ buildQwenSystemDefaults,
724
+ sameQwenSettings,
725
+ qwenSystemDefaultsSource,
726
+ qwenSystemSettingsSource,
727
+ parseQwenSettings,
728
+ buildQwenArgs,
729
+ parseFrame,
730
+ toolInputPreview,
731
+ shortToolName,
732
+ describeToolUse,
733
+ interpretQwenFrame,
734
+ classifyQwenRun,
735
+ };