@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,611 @@
1
+ /**
2
+ * Pure helpers for the Qoder adapters — the two editions, argv, the child
3
+ * environment, stream-json frames, run classification, and the process-tree
4
+ * walk Stop needs.
5
+ *
6
+ * Split out from qoder.js so everything with decision logic is unit-testable
7
+ * without a CLI, an account or a workspace. Facts below were verified against
8
+ * the real CLI (1.1.72, flags also on 1.0.45 and 1.1.62), not read off the docs
9
+ * — where the two disagree it is noted.
10
+ *
11
+ * TWO EDITIONS, TWO BINARIES. The China edition is not a region switch: its
12
+ * brand is compiled into a separate binary (`qoderclicn`) with its own
13
+ * install script, config root (~/.qoder-cn) and env prefix (QODERCN_). Every
14
+ * name that differs lives in EDITIONS, and nothing else in the adapter knows
15
+ * which edition it is.
16
+ *
17
+ * THE STREAM IS CLAUDE CODE'S. `-p -o stream-json` emits the Claude Agent SDK
18
+ * frames (system/init, assistant, user, result; protocol_version 1.5.0). The
19
+ * difference that matters: a run that never reached a model — signed out —
20
+ * still ends on `result` with subtype "success", flagged only by
21
+ * `is_error: true`. The subtype is not a verdict; `is_error` is.
22
+ *
23
+ * A REJECTED TOKEN HAS NO FRAMES. A personal access token the service turns
24
+ * down kills the CLI before the init frame: stdout is empty, stderr carries
25
+ * "QoderAuthError: The QODER_PERSONAL_ACCESS_TOKEN environment variable
26
+ * contains a token that was rejected…", exit 1. That is the only place the
27
+ * failure is visible, so stderr is read for it.
28
+ */
29
+
30
+ 'use strict';
31
+
32
+ // Oldest release still published (it is in the install manifest's rollback
33
+ // list) — and it accepts every flag buildQoderArgs passes.
34
+ const QODER_MIN_VERSION = '1.0.45';
35
+ // Highest version verified end to end. Newer is allowed, just not claimed.
36
+ const QODER_TESTED_MAX_VERSION = '1.1.72';
37
+
38
+ // ---------------------------------------------------------------------------
39
+ // Editions
40
+ // ---------------------------------------------------------------------------
41
+
42
+ /**
43
+ * Everything that differs between the international and China editions.
44
+ * `bin` is the CLI itself — never the `qoder` / `qodercn` dispatcher the
45
+ * installer also puts on PATH, which hands any argument naming an existing
46
+ * path to the Qoder IDE instead of the CLI.
47
+ */
48
+ const EDITIONS = {
49
+ global: {
50
+ type: 'qoder',
51
+ label: 'Qoder CLI',
52
+ bin: 'qodercli',
53
+ envPrefix: 'QODER_',
54
+ configDirName: '.qoder',
55
+ npmPackage: ['@qoder-ai', 'qodercli'],
56
+ patUrl: 'https://qoder.com/account/integrations',
57
+ installUnix: 'curl -fsSL https://qoder.com/install | bash',
58
+ installWindows: 'irm https://qoder.com/install.ps1 | iex',
59
+ },
60
+ cn: {
61
+ type: 'qoder-cn',
62
+ label: 'Qoder CLI CN',
63
+ bin: 'qoderclicn',
64
+ envPrefix: 'QODERCN_',
65
+ configDirName: '.qoder-cn',
66
+ npmPackage: ['@qodercn-ai', 'qoderclicn'],
67
+ patUrl: 'https://qoder.cn/account/integrations',
68
+ installUnix: 'curl -fsSL https://qoder.com.cn/install | bash',
69
+ installWindows: 'irm https://qoder.com.cn/install.ps1 | iex',
70
+ },
71
+ };
72
+
73
+ /** The CLI reads every one of its variables under the edition's prefix. */
74
+ function editionVar(edition, name) {
75
+ return `${edition.envPrefix}${name}`;
76
+ }
77
+
78
+ function installHint(edition, platform = process.platform) {
79
+ return platform === 'win32' ? edition.installWindows : edition.installUnix;
80
+ }
81
+
82
+ // ---------------------------------------------------------------------------
83
+ // Version gate
84
+ // ---------------------------------------------------------------------------
85
+
86
+ /** Extract a dotted version from `--version` output. Returns null if absent. */
87
+ function parseQoderVersion(raw) {
88
+ if (!raw || typeof raw !== 'string') return null;
89
+ const m = raw.match(/(\d+)\.(\d+)\.(\d+)/);
90
+ return m ? `${m[1]}.${m[2]}.${m[3]}` : null;
91
+ }
92
+
93
+ /** Numeric compare of two dotted versions. Returns -1 / 0 / 1. */
94
+ function compareVersions(a, b) {
95
+ const pa = String(a).split('.').map((n) => parseInt(n, 10) || 0);
96
+ const pb = String(b).split('.').map((n) => parseInt(n, 10) || 0);
97
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
98
+ const x = pa[i] || 0;
99
+ const y = pb[i] || 0;
100
+ if (x !== y) return x < y ? -1 : 1;
101
+ }
102
+ return 0;
103
+ }
104
+
105
+ /**
106
+ * `supported: null` means "could not tell" — an unreadable version proceeds
107
+ * rather than blocking a CLI that is probably fine.
108
+ */
109
+ function classifyQoderVersion(rawVersion) {
110
+ const version = parseQoderVersion(rawVersion);
111
+ if (!version) return { version: null, supported: null, tested: null };
112
+ return {
113
+ version,
114
+ supported: compareVersions(version, QODER_MIN_VERSION) >= 0,
115
+ tested: compareVersions(version, QODER_TESTED_MAX_VERSION) <= 0,
116
+ };
117
+ }
118
+
119
+ // ---------------------------------------------------------------------------
120
+ // Redaction
121
+ // ---------------------------------------------------------------------------
122
+
123
+ const SECRET_PATTERNS = [
124
+ /\bsk-[A-Za-z0-9._-]{8,}\b/g,
125
+ /\bBearer\s+[A-Za-z0-9._-]{8,}\b/gi,
126
+ /\beyJ[A-Za-z0-9._-]{16,}\b/g,
127
+ /\b(api[_-]?key|token|secret|password|authorization)\b\s*[:=]\s*["']?[A-Za-z0-9._-]{8,}["']?/gi,
128
+ ];
129
+
130
+ /**
131
+ * Redact secret material from free text before it is logged or posted.
132
+ * `values` are the exact secrets this run holds (the token): the format of a
133
+ * Qoder token is not documented, so pattern matching alone cannot be trusted
134
+ * to catch one.
135
+ */
136
+ function redactSecrets(text, values = []) {
137
+ if (text == null) return text;
138
+ let out = redactValues(String(text), values);
139
+ for (const re of SECRET_PATTERNS) {
140
+ out = out.replace(re, (m) => {
141
+ const eq = m.match(/\s*[:=]\s*/);
142
+ if (eq) return m.slice(0, m.indexOf(eq[0])) + eq[0] + '[redacted]';
143
+ return /^bearer/i.test(m) ? 'Bearer [redacted]' : '[redacted]';
144
+ });
145
+ }
146
+ return out;
147
+ }
148
+
149
+ /** Only the exact-value half of redactSecrets: safe on model output. */
150
+ function redactValues(text, values = []) {
151
+ let out = text;
152
+ for (const v of values) {
153
+ const s = String(v || '');
154
+ if (s.length >= 8) out = out.split(s).join('[redacted]');
155
+ }
156
+ return out;
157
+ }
158
+
159
+ /** redactValues over every string in a parsed frame. */
160
+ function redactFrame(value, values) {
161
+ if (typeof value === 'string') return redactValues(value, values);
162
+ if (Array.isArray(value)) return value.map((v) => redactFrame(v, values));
163
+ if (value && typeof value === 'object') {
164
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, redactFrame(v, values)]));
165
+ }
166
+ return value;
167
+ }
168
+
169
+ function truncate(s, n) {
170
+ s = String(s == null ? '' : s);
171
+ return s.length > n ? s.slice(0, n - 1) + '…' : s;
172
+ }
173
+
174
+ /** An argv safe to log: the session id and the kilobytes of briefing hidden. */
175
+ function redactArgs(args) {
176
+ const out = [];
177
+ for (let i = 0; i < args.length; i++) {
178
+ const a = args[i];
179
+ out.push(a);
180
+ if (['-r', '--resume', '--session-id', '--append-system-prompt'].includes(a) && args[i + 1] != null) {
181
+ out.push(a === '--append-system-prompt' ? '<system-prompt>' : '<session-id>');
182
+ i++;
183
+ }
184
+ }
185
+ return out;
186
+ }
187
+
188
+ // ---------------------------------------------------------------------------
189
+ // Credentials and the child environment
190
+ // ---------------------------------------------------------------------------
191
+
192
+ /**
193
+ * The token and model this agent runs on.
194
+ *
195
+ * The token is the edition's own variable or the workspace's generic
196
+ * LLM_API_KEY (the registry maps one onto the other; both are read so an env
197
+ * that skipped the mapping still works). No token means the CLI's own browser
198
+ * sign-in. The model is the workspace pick, then the agent's form.
199
+ */
200
+ function resolveQoderAuth(agentEnv = {}, edition = EDITIONS.global, workspaceModel = null) {
201
+ const env = agentEnv || {};
202
+ const pat = String(env[editionVar(edition, 'PERSONAL_ACCESS_TOKEN')] || env.LLM_API_KEY || '').trim();
203
+ const model = String(workspaceModel || env[editionVar(edition, 'MODEL')] || env.LLM_MODEL || '').trim();
204
+ return { pat, model };
205
+ }
206
+
207
+ /**
208
+ * Environment for one run, built from the daemon's enhanced env.
209
+ *
210
+ * - The token goes in the edition's variable, which the CLI reads BEFORE any
211
+ * saved sign-in and does not fall back from: a token set here always wins
212
+ * over whatever `/login` left in the config root.
213
+ * - `<prefix>NO_RC=1`: on a machine where the CLI has never run, its first
214
+ * start rewrites the shell's rc files (.zshrc, .bashrc, …) to put its
215
+ * dispatcher on PATH. A daemon run must not edit the user's shell.
216
+ * - The generic LLM_* names are dropped: the CLI does not read them, and
217
+ * leaving the key under a second name only widens what the commands the
218
+ * agent runs can see.
219
+ */
220
+ function buildQoderChildEnv(baseEnv = {}, { edition = EDITIONS.global, pat = '' } = {}) {
221
+ const env = { ...baseEnv };
222
+ delete env.LLM_API_KEY;
223
+ delete env.LLM_BASE_URL;
224
+ delete env.LLM_MODEL;
225
+ env[editionVar(edition, 'NO_RC')] = '1';
226
+ if (pat) env[editionVar(edition, 'PERSONAL_ACCESS_TOKEN')] = pat;
227
+ return env;
228
+ }
229
+
230
+ /**
231
+ * The flag settings layer: the highest-precedence settings the CLI loads,
232
+ * above ~/.qoder/settings.json. Headless runs already skip the auto-updater
233
+ * (the CLI checks for non-interactive mode first); this keeps it off should
234
+ * that ever change, so a background upgrade never swaps the binary mid-run.
235
+ */
236
+ function buildQoderFlagSettings() {
237
+ return { general: { enableAutoUpdate: false } };
238
+ }
239
+
240
+ // ---------------------------------------------------------------------------
241
+ // argv
242
+ // ---------------------------------------------------------------------------
243
+
244
+ /**
245
+ * Tools an agent answering a workspace channel must not have. Scheduling goes
246
+ * through the workspace's own timers (MCP), as in the Claude adapter; the
247
+ * worktree tools would create directories and branches in the user's
248
+ * repository that nothing ever cleans up.
249
+ */
250
+ const QODER_DISALLOWED_TOOLS = [
251
+ 'CronCreate',
252
+ 'CronDelete',
253
+ 'CronList',
254
+ 'ScheduleWakeup',
255
+ 'EnterWorktree',
256
+ 'ExitWorktree',
257
+ ];
258
+
259
+ /**
260
+ * argv for one headless run. The prompt is NOT here: it goes in over stdin
261
+ * (read to EOF when stdin is not a TTY), which keeps a long turn off the OS
262
+ * argv limit and a quote in a message from ever being a command-line issue.
263
+ *
264
+ * - `--disallowed-tools` takes ONE comma-separated value: the space-separated
265
+ * variadic form drops everything after the first name (verified).
266
+ * - `--strict-mcp-config`: only the workspace server, none of the user's
267
+ * ~/.qoder/settings.json or project .mcp.json servers. Passed even with no
268
+ * config to inject, where it means no MCP servers at all (verified on
269
+ * 1.0.45 and 1.1.73).
270
+ * - plan mode is `--agent Plan` (no Edit/Write) without `--yolo`, so
271
+ * anything else that needs approval is denied. `--permission-mode plan`
272
+ * is documented but 1.1.72 does not accept it (falls back to default).
273
+ * - a new session gets an id chosen here (`--session-id`, a UUID), so the
274
+ * channel knows it even if the run dies before the init frame.
275
+ */
276
+ function buildQoderArgs(o = {}) {
277
+ const args = ['-p', '-o', 'stream-json'];
278
+
279
+ const systemPrompt = (o.appendSystemPrompt || '').trim();
280
+ if (systemPrompt) args.push('--append-system-prompt', systemPrompt);
281
+
282
+ if (o.planMode) args.push('--agent', 'Plan');
283
+ else args.push('--yolo');
284
+
285
+ const disallowed = [...QODER_DISALLOWED_TOOLS, ...(o.extraDisallowedTools || [])];
286
+ args.push('--disallowed-tools', disallowed.join(','));
287
+
288
+ const model = (o.model || '').trim();
289
+ if (model) args.push('-m', model);
290
+
291
+ args.push('--settings', JSON.stringify(o.flagSettings || buildQoderFlagSettings()));
292
+
293
+ if (o.mcpConfigPath) args.push('--mcp-config', o.mcpConfigPath);
294
+ args.push('--strict-mcp-config');
295
+
296
+ const resume = (o.resumeSessionId || '').trim();
297
+ const fresh = (o.newSessionId || '').trim();
298
+ if (resume) args.push('-r', resume);
299
+ else if (fresh) args.push('--session-id', fresh);
300
+
301
+ return args;
302
+ }
303
+
304
+ // ---------------------------------------------------------------------------
305
+ // stream-json frames
306
+ // ---------------------------------------------------------------------------
307
+
308
+ /** Parse one NDJSON line. Returns null for blank lines and malformed JSON. */
309
+ function parseFrame(line) {
310
+ const s = String(line == null ? '' : line).trim();
311
+ if (!s || s[0] !== '{') return null;
312
+ try {
313
+ const v = JSON.parse(s);
314
+ return v && typeof v === 'object' ? v : null;
315
+ } catch {
316
+ return null;
317
+ }
318
+ }
319
+
320
+ /** A short preview of a tool call's input, for the channel's activity line. */
321
+ function toolInputPreview(input) {
322
+ if (input == null) return '';
323
+ if (typeof input !== 'object') return truncate(redactSecrets(String(input)), 150);
324
+ const first = input.command || input.file_path || input.path || input.pattern
325
+ || input.query || input.url || input.prompt || input.description;
326
+ if (typeof first === 'string' && first) return truncate(redactSecrets(first), 150);
327
+ try {
328
+ return truncate(redactSecrets(JSON.stringify(input)), 150);
329
+ } catch {
330
+ return '';
331
+ }
332
+ }
333
+
334
+ // Frames with nothing for the channel. Listed so a genuinely new frame type
335
+ // still reaches the log as "unrecognized".
336
+ const IGNORED_FRAMES = new Set(['user', 'stream_event', 'rate_limit_event', 'control_request', 'control_response']);
337
+
338
+ /**
339
+ * Normalize one parsed frame. `apiError` on an assistant frame is the SDK's
340
+ * error category (authentication_failed, billing_error, rate_limit,
341
+ * invalid_request, server_error, max_output_tokens, unknown) — the CLI's text
342
+ * for it is often a synthetic assistant message, not a model answer.
343
+ *
344
+ * `secrets` are the exact values this run holds (the token). The CLI hands its
345
+ * environment to the shell commands it runs, so the token can come back in any
346
+ * string of any frame — a command, a reply, an error — and every one of them
347
+ * may end up in the channel.
348
+ */
349
+ function interpretQoderFrame(frame, secrets = []) {
350
+ if (!frame || typeof frame !== 'object') return { kind: 'ignored' };
351
+ if (secrets.length) frame = redactFrame(frame, secrets);
352
+
353
+ if (frame.type === 'result') {
354
+ const errors = Array.isArray(frame.errors)
355
+ ? frame.errors.map((e) => redactSecrets(String(e))).filter(Boolean)
356
+ : [];
357
+ return {
358
+ kind: 'result',
359
+ subtype: typeof frame.subtype === 'string' ? frame.subtype : '',
360
+ isError: frame.is_error === true,
361
+ text: typeof frame.result === 'string' ? frame.result : '',
362
+ sessionId: typeof frame.session_id === 'string' ? frame.session_id : null,
363
+ errors,
364
+ errorCode: frame.error_code != null ? frame.error_code : null,
365
+ terminalReason: typeof frame.terminal_reason === 'string' ? frame.terminal_reason : '',
366
+ numTurns: Number.isFinite(frame.num_turns) ? frame.num_turns : null,
367
+ };
368
+ }
369
+
370
+ if (frame.type === 'system') {
371
+ if (frame.subtype === 'init') {
372
+ return {
373
+ kind: 'init',
374
+ sessionId: typeof frame.session_id === 'string' ? frame.session_id : null,
375
+ model: typeof frame.model === 'string' ? frame.model : '',
376
+ version: typeof frame.qodercli_version === 'string' ? frame.qodercli_version : '',
377
+ permissionMode: typeof frame.permissionMode === 'string' ? frame.permissionMode : '',
378
+ mcpServers: Array.isArray(frame.mcp_servers) ? frame.mcp_servers : [],
379
+ };
380
+ }
381
+ const subtype = typeof frame.subtype === 'string' ? frame.subtype : '';
382
+ const message = typeof frame.message === 'string' ? frame.message : '';
383
+ if (/compact/i.test(subtype) || /compact/i.test(message)) {
384
+ return { kind: 'status', text: message || 'Compacting the conversation...' };
385
+ }
386
+ return { kind: 'ignored' };
387
+ }
388
+
389
+ if (frame.type === 'assistant') {
390
+ const blocks = (frame.message && Array.isArray(frame.message.content)) ? frame.message.content : [];
391
+ const apiError = typeof frame.error === 'string' && frame.error ? frame.error : null;
392
+ const texts = [];
393
+ const tools = [];
394
+ for (const block of blocks) {
395
+ if (!block || typeof block !== 'object') continue;
396
+ if (block.type === 'text' && typeof block.text === 'string' && block.text.trim()) {
397
+ texts.push(block.text.trim());
398
+ } else if (block.type === 'tool_use') {
399
+ tools.push({
400
+ id: typeof block.id === 'string' ? block.id : null,
401
+ name: typeof block.name === 'string' ? block.name : '',
402
+ preview: toolInputPreview(block.input),
403
+ todos: block.input && Array.isArray(block.input.todos) ? block.input.todos : null,
404
+ });
405
+ }
406
+ }
407
+ // A synthetic error message is not progress and not an answer.
408
+ if (apiError) return { kind: 'assistant', texts: [], tools, apiError, errorText: texts.join('\n') };
409
+ if (!texts.length && !tools.length) return { kind: 'ignored' };
410
+ return { kind: 'assistant', texts, tools, apiError: null, errorText: '' };
411
+ }
412
+
413
+ // A user frame carries the results of the tool calls the run is waiting on.
414
+ // `ids` holds null for a result that names no call.
415
+ if (frame.type === 'user') {
416
+ const blocks = (frame.message && Array.isArray(frame.message.content)) ? frame.message.content : [];
417
+ const ids = blocks.filter((b) => b && b.type === 'tool_result')
418
+ .map((b) => (typeof b.tool_use_id === 'string' ? b.tool_use_id : null));
419
+ if (ids.length) return { kind: 'tool_results', ids };
420
+ }
421
+
422
+ if (IGNORED_FRAMES.has(frame.type)) return { kind: 'ignored' };
423
+ return { kind: 'unknown', raw: truncate(redactSecrets(String(frame.type || '')), 80) };
424
+ }
425
+
426
+ // ---------------------------------------------------------------------------
427
+ // Run classification
428
+ // ---------------------------------------------------------------------------
429
+
430
+ // Result `error_code`s the CLI documents in its own table.
431
+ const QUOTA_CODES = new Set([110, 113, 114, 115, 116, 117, 118, 119, 122]);
432
+ const LOGIN_EXPIRED_CODE = 105;
433
+
434
+ /** The line of the CLI's stderr worth showing; stack frames are dropped. */
435
+ function qoderErrorLine(stderr) {
436
+ const lines = String(stderr || '').split(/\r?\n/).map((l) => l.trim()).filter(Boolean)
437
+ .filter((l) => !/^at\s/.test(l));
438
+ if (!lines.length) return '';
439
+ const critical = lines.find((l) => /unexpected critical error/i.test(l));
440
+ const line = critical || lines[0];
441
+ return line.replace(/^.*?unexpected critical error occurred:\s*/i, '').replace(/^Qoder\w*Error:\s*/, '').trim();
442
+ }
443
+
444
+ function messages(edition) {
445
+ const pat = editionVar(edition, 'PERSONAL_ACCESS_TOKEN');
446
+ return {
447
+ signedOut: `${edition.label} is not signed in. Run \`${edition.bin} login\` on this machine, or set a personal access token for this agent (${edition.patUrl}).`,
448
+ patRejected: `${edition.label} rejected the personal access token (${pat}). Create a new one at ${edition.patUrl}, or clear it to use the CLI's own sign-in.`,
449
+ loginExpired: `The ${edition.label} sign-in has expired. Run \`${edition.bin} login\` again, or set a personal access token for this agent.`,
450
+ quota: `The ${edition.label} account is out of credits or rate limited. Wait for the quota to reset or upgrade the plan, then retry.`,
451
+ model: `${edition.label} cannot run the selected model. Pick one from \`${edition.bin} --list-models\`, or clear the model to use the account default.`,
452
+ server: `The ${edition.label} model service returned an error. This is usually temporary — retry shortly.`,
453
+ staleSession: `The ${edition.label} session for this channel could not be resumed.`,
454
+ };
455
+ }
456
+
457
+ /**
458
+ * How a run ended. The result frame outranks the exit code (exit 1 is both
459
+ * "signed out" and a real failure); stderr is read only when no frame came.
460
+ * `secrets` are the exact values to mask in any CLI text quoted back.
461
+ *
462
+ * @returns {{kind: string, ok: boolean, userMessage: string|null}}
463
+ */
464
+ function classifyQoderRun({ result = null, apiErrors = [], code = null, signal = null, stderr = '' } = {}, edition = EDITIONS.global, secrets = []) {
465
+ const msg = messages(edition);
466
+
467
+ if (result && !result.isError) return { kind: 'success', ok: true, userMessage: null };
468
+
469
+ if (result && result.isError) {
470
+ const text = [result.text, ...result.errors].join('\n');
471
+ const codeNum = Number(result.errorCode);
472
+ if (codeNum === LOGIN_EXPIRED_CODE) return { kind: 'auth', ok: false, userMessage: msg.loginExpired };
473
+ if (/not logged in|please run \/login/i.test(text) || apiErrors.includes('authentication_failed')) {
474
+ return { kind: 'auth', ok: false, userMessage: msg.signedOut };
475
+ }
476
+ if (QUOTA_CODES.has(codeNum) || apiErrors.includes('billing_error') || apiErrors.includes('rate_limit')) {
477
+ return { kind: 'quota', ok: false, userMessage: msg.quota };
478
+ }
479
+ if (/model.{0,40}(not available|not found|unsupported|invalid)/i.test(text)) {
480
+ return { kind: 'model', ok: false, userMessage: msg.model };
481
+ }
482
+ if (apiErrors.includes('server_error')) return { kind: 'server', ok: false, userMessage: msg.server };
483
+ if (result.terminalReason === 'aborted_streaming') {
484
+ return { kind: 'interrupted', ok: false, userMessage: 'The run was interrupted.' };
485
+ }
486
+ const detail = result.errors[0] || result.text || '';
487
+ return {
488
+ kind: 'run_error',
489
+ ok: false,
490
+ userMessage: detail
491
+ ? `${edition.label} could not finish the run: ${truncate(redactSecrets(detail, secrets), 400)}`
492
+ : `${edition.label} could not finish the run. Check the daemon log for details, then retry.`,
493
+ };
494
+ }
495
+
496
+ // No result frame from here down. A token the service turns down is a
497
+ // QoderAuthError on stderr: 1.1.x names the variable, 1.0.x only says
498
+ // "auth.exchangeJobToken failed: Bad request".
499
+ const line = qoderErrorLine(stderr);
500
+ if (/QoderAuthError|token that was rejected|exchangeJobToken/i.test(String(stderr))) {
501
+ const tokenRefused = /PERSONAL_ACCESS_TOKEN|exchangeJobToken|token that was rejected/i.test(String(stderr));
502
+ return { kind: 'auth', ok: false, userMessage: tokenRefused ? msg.patRejected : msg.signedOut };
503
+ }
504
+ if (/error resuming session|invalid session identifier/i.test(String(stderr))) {
505
+ return { kind: 'stale_session', ok: false, userMessage: msg.staleSession };
506
+ }
507
+ if (signal) return { kind: 'interrupted', ok: false, userMessage: 'The run was interrupted.' };
508
+ if (line) {
509
+ return {
510
+ kind: 'startup_error',
511
+ ok: false,
512
+ userMessage: `${edition.label} stopped before answering: ${truncate(redactSecrets(line, secrets), 400)}`,
513
+ };
514
+ }
515
+ return {
516
+ kind: 'no_result',
517
+ ok: false,
518
+ userMessage: `${edition.label} exited without answering (code ${code}). Check the daemon log, then retry.`,
519
+ };
520
+ }
521
+
522
+ // ---------------------------------------------------------------------------
523
+ // Model fallback
524
+ // ---------------------------------------------------------------------------
525
+
526
+ /**
527
+ * A `-m` the account cannot run is not an error: the CLI warns on stderr —
528
+ * `Model "performance" is not available right now; using "qfmodel" instead.` —
529
+ * and runs on the account default (verified, 1.1.73). Returns the model asked
530
+ * for and the key it fell back to, or null when there was no fallback.
531
+ */
532
+ function parseModelFallback(stderr) {
533
+ const m = String(stderr || '').match(/Model "([^"]+)" is not available right now; using "([^"]+)" instead/);
534
+ return m ? { requested: m[1], used: m[2] } : null;
535
+ }
536
+
537
+ function modelFallbackNotice(edition, requested, used) {
538
+ return `${edition.label} cannot run the model "${requested}" on this account and used "${used}" instead. ` +
539
+ `Pick one from \`${edition.bin} --list-models\`, or clear the model to use the account default.`;
540
+ }
541
+
542
+ // ---------------------------------------------------------------------------
543
+ // Process tree
544
+ // ---------------------------------------------------------------------------
545
+
546
+ /**
547
+ * Every descendant of `rootPid` in a { pid, ppid, pgid } table, nearest first.
548
+ * The CLI starts its shell commands detached (a session of their own), so
549
+ * signalling its process group misses them, and once it exits they are
550
+ * reparented — the table has to be read while it is still alive. Its MCP
551
+ * servers it leaves running on SIGTERM as well (verified), so they are here too.
552
+ */
553
+ function descendantsOf(rows, rootPid) {
554
+ const children = new Map();
555
+ for (const r of rows || []) {
556
+ if (!r || !Number.isInteger(r.pid) || r.pid === r.ppid) continue;
557
+ if (!children.has(r.ppid)) children.set(r.ppid, []);
558
+ children.get(r.ppid).push(r);
559
+ }
560
+ const out = [];
561
+ const seen = new Set([rootPid]);
562
+ const queue = [rootPid];
563
+ while (queue.length) {
564
+ const pid = queue.shift();
565
+ for (const c of children.get(pid) || []) {
566
+ if (seen.has(c.pid)) continue;
567
+ seen.add(c.pid);
568
+ out.push(c);
569
+ queue.push(c.pid);
570
+ }
571
+ }
572
+ return out;
573
+ }
574
+
575
+ /** Parse `ps -A -o pid=,ppid=,pgid=` output. */
576
+ function parseProcessTable(text) {
577
+ const rows = [];
578
+ for (const line of String(text || '').split('\n')) {
579
+ const m = line.trim().match(/^(\d+)\s+(\d+)\s+(\d+)$/);
580
+ if (m) rows.push({ pid: Number(m[1]), ppid: Number(m[2]), pgid: Number(m[3]) });
581
+ }
582
+ return rows;
583
+ }
584
+
585
+ module.exports = {
586
+ QODER_MIN_VERSION,
587
+ QODER_TESTED_MAX_VERSION,
588
+ QODER_DISALLOWED_TOOLS,
589
+ EDITIONS,
590
+ editionVar,
591
+ installHint,
592
+ parseQoderVersion,
593
+ compareVersions,
594
+ classifyQoderVersion,
595
+ redactSecrets,
596
+ redactArgs,
597
+ truncate,
598
+ resolveQoderAuth,
599
+ buildQoderChildEnv,
600
+ buildQoderFlagSettings,
601
+ buildQoderArgs,
602
+ parseFrame,
603
+ toolInputPreview,
604
+ interpretQoderFrame,
605
+ qoderErrorLine,
606
+ classifyQoderRun,
607
+ parseModelFallback,
608
+ modelFallbackNotice,
609
+ descendantsOf,
610
+ parseProcessTable,
611
+ };