fauxnix-cli 0.11.0 → 0.13.0

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/dist/executor.js CHANGED
@@ -1,13 +1,35 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { promises as fs, readFileSync, existsSync, openSync, closeSync, writeSync } from 'node:fs';
2
+ import { promises as fs, readFileSync, existsSync, openSync, closeSync, readSync, rmSync, writeSync, } from 'node:fs';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { normalizeLiteralPath, wrapScript } from './translator.js';
6
- import { decodeOutput, normalizeHostNewlines, resolveNativePref } from './encoding.js';
6
+ import { decodeOutput, resolveNativePref } from './encoding.js';
7
7
  import { normalizeStderr } from './errors.js';
8
- import { DEFAULT_STDERR_LIMIT, DEFAULT_STDOUT_LIMIT, PowerShellHost, PS_MISSING_MESSAGE, } from './ps-host.js';
8
+ import { DEFAULT_STDERR_LIMIT, DEFAULT_STDOUT_LIMIT, PowerShellHost, } from './ps-host.js';
9
+ import { resolvePowerShell } from './powershell.js';
9
10
  const DEFAULT_TIMEOUT_MS = 120_000;
10
11
  const DEFAULT_WINDOWS_PATHEXT = '.COM;.EXE;.BAT;.CMD';
12
+ const MAX_HOST_CAPTURE_LIMIT = 0x7fffffff;
13
+ const UTF8_BOUNDARY_SUFFIX = 4;
14
+ const MAX_CALLER_OUTPUT_LIMIT = MAX_HOST_CAPTURE_LIMIT - UTF8_BOUNDARY_SUFFIX;
15
+ function validateOutputLimit(name, value) {
16
+ if (!Number.isSafeInteger(value) || value < 0 || value > MAX_CALLER_OUTPUT_LIMIT) {
17
+ throw new RangeError('fauxnix: ' + name + ' must be an integer from 0 to ' + MAX_CALLER_OUTPUT_LIMIT);
18
+ }
19
+ return value;
20
+ }
21
+ /**
22
+ * Retain one complete codepoint beyond the logical caller budget so Node can
23
+ * detect truncation and clip at a UTF-8 boundary. The host itself stays
24
+ * bounded even when the caller has no remaining budget.
25
+ */
26
+ function rawHostCaptureLimit(logicalBytes) {
27
+ if (!Number.isFinite(logicalBytes)) {
28
+ return logicalBytes === Number.POSITIVE_INFINITY ? MAX_HOST_CAPTURE_LIMIT : 0;
29
+ }
30
+ const bytes = Math.max(0, Math.floor(logicalBytes));
31
+ return Math.min(MAX_HOST_CAPTURE_LIMIT, bytes + UTF8_BOUNDARY_SUFFIX);
32
+ }
11
33
  function hasEnvKey(env, name) {
12
34
  const normalized = name.toUpperCase();
13
35
  return Object.keys(env).some((key) => key.toUpperCase() === normalized);
@@ -201,8 +223,12 @@ export class FauxnixSession {
201
223
  hostFile;
202
224
  host = null;
203
225
  lifecycleLock = Promise.resolve();
226
+ /** True once `env` was loaded from the host's complete environment snapshot. */
227
+ hasEnvSnapshot = false;
228
+ powerShell;
204
229
  constructor() {
205
230
  this.id = randomUUID().slice(0, 8);
231
+ this.powerShell = resolvePowerShell();
206
232
  this.bindFiles(this.id);
207
233
  }
208
234
  bindFiles(id) {
@@ -231,8 +257,10 @@ export class FauxnixSession {
231
257
  try {
232
258
  if (existsSync(this.envFile)) {
233
259
  const raw = readFileSync(this.envFile, 'utf8');
234
- if (raw.trim())
260
+ if (raw.trim()) {
235
261
  this.env = JSON.parse(raw);
262
+ this.hasEnvSnapshot = true;
263
+ }
236
264
  }
237
265
  }
238
266
  catch {
@@ -241,11 +269,11 @@ export class FauxnixSession {
241
269
  }
242
270
  ensureHost() {
243
271
  if (!this.host) {
244
- this.host = new PowerShellHost(this.hostFile, () => this.childEnv());
272
+ this.host = new PowerShellHost(this.hostFile, () => this.childEnv(), this.powerShell);
245
273
  }
246
274
  return this.host;
247
275
  }
248
- /** Boot powershell.exe now so the first run() is not the 1.1s cold start. */
276
+ /** Boot the selected PowerShell now so the first run() is not a cold start. */
249
277
  prewarm() {
250
278
  return this.withLock(async () => {
251
279
  await this.ensureHost().ready();
@@ -268,6 +296,7 @@ export class FauxnixSession {
268
296
  }
269
297
  this.cwd = null;
270
298
  this.env = {};
299
+ this.hasEnvSnapshot = false;
271
300
  this.prevExit = null;
272
301
  await Promise.allSettled([
273
302
  fs.rm(this.cwdFile, { force: true }),
@@ -279,12 +308,19 @@ export class FauxnixSession {
279
308
  }
280
309
  /** env for the child powershell process. */
281
310
  childEnv(cwdOverride, stdinFile) {
282
- const env = { ...process.env };
283
- for (const [k, v] of Object.entries(this.env)) {
284
- if (v === undefined)
285
- delete env[k];
286
- else
287
- env[k] = v;
311
+ // Before the first completed request, `env` contains optional caller
312
+ // overrides and is layered over the process baseline. Afterwards it is a
313
+ // complete snapshot written by the resident host. Restore that snapshot
314
+ // verbatim on transparent host restarts: merging it with process.env would
315
+ // resurrect inherited variables that the shell successfully unset.
316
+ const env = this.hasEnvSnapshot ? { ...this.env } : { ...process.env };
317
+ if (!this.hasEnvSnapshot) {
318
+ for (const [k, v] of Object.entries(this.env)) {
319
+ if (v === undefined)
320
+ delete env[k];
321
+ else
322
+ env[k] = v;
323
+ }
288
324
  }
289
325
  // The MCP SDK's safe Windows stdio environment omits PATHEXT. Without it,
290
326
  // PowerShell cannot resolve extensionless native commands such as `node`.
@@ -314,20 +350,134 @@ export class FauxnixSession {
314
350
  run(plans, opts = {}) {
315
351
  return this.withLock(() => runPlans(plans, this, opts, () => this.syncFromDisk(), () => this.ensureHost()));
316
352
  }
353
+ /**
354
+ * Execute precompiled steps atomically in one session turn. Each step keeps
355
+ * its own result, while timeout and caller-output budgets cover the complete
356
+ * batch. No run/reset/dispose request can interleave between steps.
357
+ */
358
+ runBatch(planGroups, opts = {}) {
359
+ return this.withLock(async () => {
360
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
361
+ const deadline = Date.now() + timeoutMs;
362
+ let stdoutRemaining = validateOutputLimit('stdoutLimit', opts.stdoutLimit ?? DEFAULT_STDOUT_LIMIT);
363
+ let stderrRemaining = validateOutputLimit('stderrLimit', opts.stderrLimit ?? DEFAULT_STDERR_LIMIT);
364
+ const results = [];
365
+ let stopReason = 'completed';
366
+ for (const plans of planGroups) {
367
+ let result;
368
+ try {
369
+ result = await runPlans(plans, this, {
370
+ ...opts,
371
+ timeoutMs: Math.max(0, deadline - Date.now()),
372
+ stdoutLimit: stdoutRemaining,
373
+ stderrLimit: stderrRemaining,
374
+ }, () => this.syncFromDisk(), () => this.ensureHost());
375
+ }
376
+ catch (error) {
377
+ const message = error instanceof Error ? error.message : String(error);
378
+ const clipped = clipUtf8(message, stderrRemaining);
379
+ result = {
380
+ stdout: '', stderr: clipped.text, exitCode: 1,
381
+ timedOut: false, cancelled: false, truncated: clipped.truncated,
382
+ infrastructureError: true,
383
+ };
384
+ }
385
+ results.push(result);
386
+ stdoutRemaining = Math.max(0, stdoutRemaining - Buffer.byteLength(result.stdout, 'utf8'));
387
+ stderrRemaining = Math.max(0, stderrRemaining - Buffer.byteLength(result.stderr, 'utf8'));
388
+ if (result.stdoutTruncated)
389
+ stdoutRemaining = 0;
390
+ if (result.stderrTruncated)
391
+ stderrRemaining = 0;
392
+ if (result.cancelled) {
393
+ stopReason = 'cancelled';
394
+ break;
395
+ }
396
+ if (result.timedOut) {
397
+ stopReason = 'timed_out';
398
+ break;
399
+ }
400
+ if (result.spawnError || result.infrastructureError) {
401
+ stopReason = 'infrastructure';
402
+ break;
403
+ }
404
+ if ((opts.stopOnError ?? true) && result.exitCode !== 0) {
405
+ stopReason = 'command_failed';
406
+ break;
407
+ }
408
+ }
409
+ return { results, stopReason };
410
+ });
411
+ }
317
412
  }
318
413
  async function runPlans(plans, session, opts, afterSegment, ensureHost) {
319
414
  const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
320
415
  const deadline = Date.now() + timeoutMs;
321
- const stdoutLimit = opts.stdoutLimit ?? DEFAULT_STDOUT_LIMIT;
322
- const stderrLimit = opts.stderrLimit ?? DEFAULT_STDERR_LIMIT;
416
+ const stdoutLimit = validateOutputLimit('stdoutLimit', opts.stdoutLimit ?? DEFAULT_STDOUT_LIMIT);
417
+ const stderrLimit = validateOutputLimit('stderrLimit', opts.stderrLimit ?? DEFAULT_STDERR_LIMIT);
323
418
  const timeoutMessage = '\nbash: command timed out after ' + Math.round(timeoutMs / 1000) + 's';
324
419
  let stdout = '';
325
420
  let stderr = '';
421
+ let stdoutBytes = 0;
422
+ let stderrBytes = 0;
423
+ let stdoutClosed = false;
424
+ let stderrClosed = false;
326
425
  let exitCode = 0;
327
426
  let timedOut = false;
328
427
  let cancelled = false;
329
428
  let truncated = false;
330
429
  let spawnError;
430
+ let infrastructureError = false;
431
+ const appendCaller = (fd, data) => {
432
+ if (!data)
433
+ return;
434
+ if (fd === 1 ? stdoutClosed : stderrClosed)
435
+ return;
436
+ const used = fd === 1 ? stdoutBytes : stderrBytes;
437
+ const limit = fd === 1 ? stdoutLimit : stderrLimit;
438
+ const clipped = clipUtf8(data, Math.max(0, limit - used));
439
+ if (fd === 1) {
440
+ stdout += clipped.text;
441
+ stdoutBytes += Buffer.byteLength(clipped.text, 'utf8');
442
+ }
443
+ else {
444
+ stderr += clipped.text;
445
+ stderrBytes += Buffer.byteLength(clipped.text, 'utf8');
446
+ }
447
+ if (clipped.truncated) {
448
+ if (fd === 1)
449
+ stdoutClosed = true;
450
+ else
451
+ stderrClosed = true;
452
+ truncated = true;
453
+ }
454
+ };
455
+ const remainingFor = (dest) => {
456
+ if (dest.kind !== 'caller')
457
+ return 0;
458
+ if (dest.fd === 1 ? stdoutClosed : stderrClosed)
459
+ return 0;
460
+ const limit = dest.fd === 1 ? stdoutLimit : stderrLimit;
461
+ const used = dest.fd === 1 ? stdoutBytes : stderrBytes;
462
+ return Math.max(0, limit - used);
463
+ };
464
+ const closeCallerDest = (dest) => {
465
+ if (dest.kind !== 'caller')
466
+ return;
467
+ if (dest.fd === 1)
468
+ stdoutClosed = true;
469
+ else
470
+ stderrClosed = true;
471
+ };
472
+ const hostStream = (dest) => {
473
+ if (dest.kind === 'file')
474
+ return { mode: 'spool', limit: 0 };
475
+ if (dest.kind === 'nul')
476
+ return { mode: 'discard', limit: 0 };
477
+ if (dest.fd === 1 ? stdoutClosed : stderrClosed)
478
+ return { mode: 'discard', limit: 0 };
479
+ return { mode: 'capture', limit: rawHostCaptureLimit(remainingFor(dest)) };
480
+ };
331
481
  // bash list semantics: `a && b ; c` runs c regardless of a; `a && b && c`
332
482
  // skips b AND c when a fails. chainOk models the value of the current
333
483
  // &&/|| chain; `;` segments always run and restart the chain.
@@ -350,7 +500,7 @@ async function runPlans(plans, session, opts, afterSegment, ensureHost) {
350
500
  break;
351
501
  }
352
502
  if (Date.now() >= deadline) {
353
- stderr += timeoutMessage;
503
+ appendCaller(2, timeoutMessage);
354
504
  exitCode = 124;
355
505
  timedOut = true;
356
506
  session.prevExit = exitCode;
@@ -377,10 +527,10 @@ async function runPlans(plans, session, opts, afterSegment, ensureHost) {
377
527
  let prepStderr = { kind: 'caller', fd: 2 };
378
528
  const emitPrepError = (msg) => emitToPrepDest(prepStderr, msg, prepFds, {
379
529
  stdout: (s) => {
380
- stdout += s;
530
+ appendCaller(1, s);
381
531
  },
382
532
  stderr: (s) => {
383
- stderr += s;
533
+ appendCaller(2, s);
384
534
  },
385
535
  });
386
536
  for (const r of plan.redirects) {
@@ -424,7 +574,7 @@ async function runPlans(plans, session, opts, afterSegment, ensureHost) {
424
574
  break;
425
575
  }
426
576
  if (remainingMs <= 0) {
427
- stderr += timeoutMessage;
577
+ appendCaller(2, timeoutMessage);
428
578
  exitCode = 124;
429
579
  timedOut = true;
430
580
  session.prevExit = exitCode;
@@ -435,20 +585,30 @@ async function runPlans(plans, session, opts, afterSegment, ensureHost) {
435
585
  // stderr onto the caller's stdout before stdout is pointed at NUL, so
436
586
  // captured stderr is still returned; `>/dev/null 2>&1` points both at NUL.
437
587
  const applyDests = lastStageOutputDests(plan.outputRedirects, resolveTarget);
438
- // Response budgets cap what the CALLER receives — streams redirected to
439
- // files must never be truncated by them (Codex-review P1: `printf … > f`
440
- // with a small stdoutLimit was writing a clipped file). The final
441
- // clipUtf8 below still enforces the returned-data budget.
442
- const fileRedirected = applyDests.stdout.kind === 'file' || applyDests.stderr.kind === 'file';
588
+ // Each source stream is bounded according to its final destination.
589
+ // A file keeps the complete stream, /dev/null retains nothing, and a
590
+ // caller stream receives only the budget left by earlier list segments.
591
+ const hostStdout = hostStream(applyDests.stdout);
592
+ const hostStderr = hostStream(applyDests.stderr);
443
593
  const inv = await ensureHost().invoke(encoded, {
444
594
  FAUXNIX_CWD: currentDir,
445
595
  FAUXNIX_PREV_EXIT: session.prevExit === null ? '' : String(session.prevExit),
446
596
  FAUXNIX_STDIN_FILE: red.stdinFile || '',
447
- }, remainingMs, opts.signal, fileRedirected
448
- ? { stdoutLimit: 0, stderrLimit: 0 }
449
- : { stdoutLimit, stderrLimit });
597
+ }, remainingMs, opts.signal, {
598
+ stdoutLimit: hostStdout.limit,
599
+ stderrLimit: hostStderr.limit,
600
+ stdoutMode: hostStdout.mode,
601
+ stderrMode: hostStderr.mode,
602
+ });
603
+ if (inv.infrastructureError) {
604
+ appendCaller(2, inv.stderr.toString('utf8'));
605
+ exitCode = inv.exitCode;
606
+ session.prevExit = exitCode;
607
+ infrastructureError = true;
608
+ break;
609
+ }
450
610
  if (inv.spawnError === 'ENOENT' || inv.spawnError === 'START') {
451
- stderr += inv.stderr.toString('utf8') || PS_MISSING_MESSAGE;
611
+ appendCaller(2, inv.stderr.toString('utf8') || 'fauxnix: failed to start the selected PowerShell host\n');
452
612
  exitCode = 127;
453
613
  spawnError = inv.spawnError;
454
614
  session.prevExit = exitCode;
@@ -464,11 +624,14 @@ async function runPlans(plans, session, opts, afterSegment, ensureHost) {
464
624
  }
465
625
  afterSegment();
466
626
  const decodePref = resolveNativePref();
467
- // GNU line discipline: the PS host terminates Write-Output lines with
468
- // CRLF. Exact writers (fx-write / printf / echo -n) must keep embedded
469
- // CR so `printf 'a\r\nb' > out` stays 4 bytes.
470
- const segOut = normalizeHostNewlines(decodeOutput(inv.stdout, decodePref));
471
- let segErr = normalizeHostNewlines(normalizeStderr(decodeOutput(inv.stderr, decodePref)));
627
+ // Captured protocol frames are always UTF-8. FAUXNIX_NATIVE_ENCODING is
628
+ // consumed at the native-process boundary inside fx-native; applying it
629
+ // again here double-decodes every translated/non-ASCII frame. Only bytes
630
+ // written directly to the host's OS stderr pipe retain a native encoding.
631
+ const segOut = decodeOutput(inv.stdout, 'utf8');
632
+ const framedErr = decodeOutput(inv.stderr, 'utf8');
633
+ const nativeErr = decodeOutput(inv.nativeStderr ?? Buffer.alloc(0), decodePref);
634
+ let segErr = normalizeStderr(framedErr + nativeErr);
472
635
  if (inv.timedOut) {
473
636
  segErr += timeoutMessage;
474
637
  }
@@ -488,27 +651,53 @@ async function runPlans(plans, session, opts, afterSegment, ensureHost) {
488
651
  }
489
652
  catch (e) {
490
653
  if (fromStdout) {
491
- stderr += 'bash: ' + dest.path + ': cannot create: ' + e.message + '\n';
654
+ appendCaller(2, 'bash: ' + dest.path + ': cannot create: ' + e.message + '\n');
492
655
  exitCode = 1;
493
656
  redirectOk = false;
494
- stdout += data;
657
+ appendCaller(1, data);
495
658
  }
496
659
  else {
497
- stderr += data;
660
+ appendCaller(2, data);
498
661
  }
499
662
  }
500
663
  return;
501
664
  }
502
- if (dest.fd === 1)
503
- stdout += data;
504
- else
505
- stderr += data;
665
+ appendCaller(dest.fd, data);
506
666
  };
507
- deliverCaptured(applyDests.stdout, segOut, true);
508
- deliverCaptured(applyDests.stderr, segErr, false);
667
+ const deliverSpool = (dest, spool, fromStdout) => {
668
+ if (!spool)
669
+ return;
670
+ if (dest.kind !== 'file') {
671
+ throw new Error('fauxnix: host returned a spool for a non-file destination');
672
+ }
673
+ try {
674
+ writeSpoolToPrepFd(prepFds, spool, dest.path);
675
+ }
676
+ catch (e) {
677
+ appendCaller(2, 'bash: ' + dest.path + ': cannot write: ' + e.message + '\n');
678
+ exitCode = 1;
679
+ redirectOk = false;
680
+ }
681
+ };
682
+ const spools = [inv.stdoutSpool, inv.stderrSpool, inv.nativeStderrSpool].filter((file) => !!file);
683
+ try {
684
+ deliverCaptured(applyDests.stdout, segOut, true);
685
+ if (inv.stdoutTruncated)
686
+ closeCallerDest(applyDests.stdout);
687
+ deliverCaptured(applyDests.stderr, segErr, false);
688
+ if (inv.stderrTruncated)
689
+ closeCallerDest(applyDests.stderr);
690
+ deliverSpool(applyDests.stdout, inv.stdoutSpool, true);
691
+ deliverSpool(applyDests.stderr, inv.stderrSpool, false);
692
+ deliverSpool(applyDests.stderr, inv.nativeStderrSpool, false);
693
+ }
694
+ finally {
695
+ for (const spool of spools)
696
+ rmSync(spool, { force: true });
697
+ }
509
698
  if (inv.truncated)
510
699
  truncated = true;
511
- exitCode = inv.timedOut ? 124 : inv.cancelled ? 130 : inv.exitCode;
700
+ exitCode = !redirectOk ? 1 : inv.timedOut ? 124 : inv.cancelled ? 130 : inv.exitCode;
512
701
  if (inv.timedOut)
513
702
  timedOut = true;
514
703
  session.prevExit = exitCode;
@@ -525,25 +714,49 @@ async function runPlans(plans, session, opts, afterSegment, ensureHost) {
525
714
  closePrepFds(prepFds);
526
715
  }
527
716
  }
528
- const clippedOut = clipUtf8(stdout, stdoutLimit);
529
- const clippedErr = clipUtf8(stderr, stderrLimit);
530
- if (clippedOut.truncated || clippedErr.truncated)
531
- truncated = true;
532
717
  return {
533
- stdout: clippedOut.text,
534
- stderr: clippedErr.text,
718
+ stdout,
719
+ stderr,
535
720
  exitCode,
536
721
  timedOut,
537
722
  cancelled,
538
723
  truncated,
724
+ stdoutTruncated: stdoutClosed,
725
+ stderrTruncated: stderrClosed,
726
+ infrastructureError,
539
727
  spawnError,
540
728
  };
541
729
  }
542
730
  function clipUtf8(text, limit) {
543
731
  if (Buffer.byteLength(text, 'utf8') <= limit)
544
732
  return { text, truncated: false };
545
- let end = text.length;
546
- while (end > 0 && Buffer.byteLength(text.slice(0, end), 'utf8') > limit)
547
- end--;
733
+ let used = 0;
734
+ let end = 0;
735
+ for (const codepoint of text) {
736
+ const size = Buffer.byteLength(codepoint, 'utf8');
737
+ if (used + size > limit)
738
+ break;
739
+ used += size;
740
+ end += codepoint.length;
741
+ }
548
742
  return { text: text.slice(0, end), truncated: true };
549
743
  }
744
+ /** Copy a host spool into an already-open redirect fd with bounded memory. */
745
+ function writeSpoolToPrepFd(fds, file, target) {
746
+ const outFd = fds.get(target);
747
+ if (outFd === undefined)
748
+ throw new Error('fauxnix: redirect fd missing for ' + target);
749
+ const inFd = openSync(file, 'r');
750
+ const input = Buffer.allocUnsafe(65_536);
751
+ try {
752
+ while (true) {
753
+ const n = readSync(inFd, input, 0, input.length, null);
754
+ if (n <= 0)
755
+ break;
756
+ writeAllSync(outFd, input.subarray(0, n));
757
+ }
758
+ }
759
+ finally {
760
+ closeSync(inFd);
761
+ }
762
+ }
package/dist/install.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
2
  import { homedir } from 'node:os';
3
3
  import { dirname, join } from 'node:path';
4
- import { claudeUserConfigPath, codexConfigPath, hasCodexFauxnix, hasOpenCodeFauxnix, isServerMap, openCodeConfigPath, serverMapHasFauxnix, } from './doctor.js';
4
+ import { claudeUserConfigPath, codexConfigPath, fauxnixServerNames, hasCodexFauxnix, hasOpenCodeFauxnix, isServerMap, openCodeConfigPath, serverMapHasFauxnix, } from './doctor.js';
5
+ import { resolveQwenLaunchTuple, sameQwenLaunchTuple } from './qwen-launch.js';
5
6
  export const INSTALL_FLAGS = ['claude', 'codex', 'opencode', 'kimi', 'qwen'];
6
7
  const STDIO = { command: 'fauxnix', args: ['mcp'] };
7
8
  const OPENCODE_STDIO = { type: 'local', command: ['fauxnix', 'mcp'] };
@@ -71,9 +72,49 @@ function installHarness(name, ctx) {
71
72
  case 'kimi':
72
73
  return patchMcpServers(kimiConfigPath(ctx.home, ctx.env), 'kimi');
73
74
  case 'qwen':
74
- return patchMcpServers(qwenConfigPath(ctx.home, ctx.env), 'qwen');
75
+ return patchQwen(qwenConfigPath(ctx.home, ctx.env));
75
76
  }
76
77
  }
78
+ function patchQwen(path) {
79
+ const launch = resolveQwenLaunchTuple();
80
+ if (!launch.ok)
81
+ return { ok: false, line: `qwen: ${launch.reason} — not modified` };
82
+ const read = readJsonObject(path);
83
+ if (read.state === 'invalid') {
84
+ return { ok: false, line: `qwen: ${path} is ${read.reason} — not modified` };
85
+ }
86
+ const existed = read.state !== 'missing';
87
+ const data = read.state === 'ok' ? read.data : {};
88
+ if (data.mcpServers != null && !isServerMap(data.mcpServers)) {
89
+ return { ok: false, line: `qwen: ${path} mcpServers is not an object — not modified` };
90
+ }
91
+ if (!isServerMap(data.mcpServers))
92
+ data.mcpServers = {};
93
+ const servers = data.mcpServers;
94
+ const extraNames = fauxnixServerNames(servers).filter((name) => name !== 'fauxnix');
95
+ if (extraNames.length) {
96
+ return {
97
+ ok: false,
98
+ line: `qwen: ${path} has another fauxnix MCP entry (${extraNames.join(', ')}) — remove the extra entry, then retry; not modified`,
99
+ };
100
+ }
101
+ const current = servers.fauxnix;
102
+ if (current != null && !isServerMap(current)) {
103
+ return {
104
+ ok: false,
105
+ line: `qwen: ${path} mcpServers.fauxnix is not an object — not modified`,
106
+ };
107
+ }
108
+ if (sameQwenLaunchTuple(current, launch.value)) {
109
+ return { ok: true, line: `qwen: already configured with an absolute launcher (${path})` };
110
+ }
111
+ servers.fauxnix = {
112
+ ...(isServerMap(current) ? current : {}),
113
+ command: launch.value.command,
114
+ args: [...launch.value.args],
115
+ };
116
+ return writeJson(path, data, 'qwen', existed, current == null ? 'added mcpServers.fauxnix' : 'updated mcpServers.fauxnix launcher');
117
+ }
77
118
  function patchMcpServers(path, harness) {
78
119
  const read = readJsonObject(path);
79
120
  if (read.state === 'invalid') {
package/dist/mcp.d.ts CHANGED
@@ -1,6 +1,70 @@
1
- import { ExecResult } from './executor.js';
1
+ import { BatchExecResult, ExecResult } from './executor.js';
2
2
  import { translatePipelineBody } from './translator.js';
3
3
  import './commands/install-all.js';
4
+ export interface BatchStepInput {
5
+ id?: string;
6
+ command: string;
7
+ }
8
+ export declare class BatchCompileError extends Error {
9
+ readonly stepIndex: number;
10
+ readonly stepId: string | undefined;
11
+ constructor(stepIndex: number, stepId: string | undefined, cause: unknown);
12
+ }
13
+ export declare function compileBatchSteps(steps: BatchStepInput[]): import("./translator.js").SegmentPlan[][];
14
+ export declare function batchToolResult(inputs: BatchStepInput[], batch: BatchExecResult, sessionId: string): {
15
+ isError?: true | undefined;
16
+ content: {
17
+ type: "text";
18
+ text: string;
19
+ }[];
20
+ structuredContent: {
21
+ schemaVersion: 1;
22
+ sessionId: string;
23
+ preflightOk: boolean;
24
+ stopReason: import("./executor.js").BatchStopReason;
25
+ stepsRequested: number;
26
+ stepsCompleted: number;
27
+ timedOut: boolean;
28
+ cancelled: boolean;
29
+ truncated: boolean;
30
+ steps: ({
31
+ status: "skipped";
32
+ id?: string | undefined;
33
+ index: number;
34
+ } | {
35
+ status: "cancelled" | "completed" | "timed_out" | "failed" | "infrastructure_error";
36
+ stdout: string;
37
+ stderr: string;
38
+ exitCode: number;
39
+ timedOut: boolean;
40
+ cancelled: boolean;
41
+ truncated: boolean;
42
+ id?: string | undefined;
43
+ index: number;
44
+ })[];
45
+ };
46
+ };
47
+ export declare function batchCompileErrorResult(inputs: BatchStepInput[], error: BatchCompileError, sessionId: string): {
48
+ content: {
49
+ type: "text";
50
+ text: string;
51
+ }[];
52
+ structuredContent: {
53
+ schemaVersion: 1;
54
+ sessionId: string;
55
+ preflightOk: boolean;
56
+ stopReason: "compile_error";
57
+ stepsRequested: number;
58
+ stepsCompleted: number;
59
+ failedStep: number;
60
+ steps: {
61
+ status: "skipped" | "compile_error";
62
+ id?: string | undefined;
63
+ index: number;
64
+ }[];
65
+ };
66
+ isError: true;
67
+ };
4
68
  export declare function formatBashText(r: Pick<ExecResult, 'stdout' | 'stderr' | 'exitCode' | 'timedOut' | 'cancelled'>): string;
5
69
  export declare function bashToolResult(r: ExecResult, sessionId: string, infra: boolean): {
6
70
  isError?: true | undefined;
@@ -19,6 +83,19 @@ export declare function bashToolResult(r: ExecResult, sessionId: string, infra:
19
83
  sessionId: string;
20
84
  };
21
85
  };
86
+ export declare function translateToolResult(command: string): {
87
+ content: {
88
+ type: "text";
89
+ text: string;
90
+ }[];
91
+ isError?: undefined;
92
+ } | {
93
+ content: {
94
+ type: "text";
95
+ text: string;
96
+ }[];
97
+ isError: true;
98
+ };
22
99
  export declare function positionalCountFromEnv(env: Record<string, string>): number;
23
100
  export declare function formatSessionStatus(session: {
24
101
  cwd: string | null;