fauxnix-cli 0.12.0 → 1.0.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
@@ -350,6 +350,65 @@ export class FauxnixSession {
350
350
  run(plans, opts = {}) {
351
351
  return this.withLock(() => runPlans(plans, this, opts, () => this.syncFromDisk(), () => this.ensureHost()));
352
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
+ }
353
412
  }
354
413
  async function runPlans(plans, session, opts, afterSegment, ensureHost) {
355
414
  const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
@@ -368,6 +427,7 @@ async function runPlans(plans, session, opts, afterSegment, ensureHost) {
368
427
  let cancelled = false;
369
428
  let truncated = false;
370
429
  let spawnError;
430
+ let infrastructureError = false;
371
431
  const appendCaller = (fd, data) => {
372
432
  if (!data)
373
433
  return;
@@ -540,6 +600,13 @@ async function runPlans(plans, session, opts, afterSegment, ensureHost) {
540
600
  stdoutMode: hostStdout.mode,
541
601
  stderrMode: hostStderr.mode,
542
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
+ }
543
610
  if (inv.spawnError === 'ENOENT' || inv.spawnError === 'START') {
544
611
  appendCaller(2, inv.stderr.toString('utf8') || 'fauxnix: failed to start the selected PowerShell host\n');
545
612
  exitCode = 127;
@@ -654,6 +721,9 @@ async function runPlans(plans, session, opts, afterSegment, ensureHost) {
654
721
  timedOut,
655
722
  cancelled,
656
723
  truncated,
724
+ stdoutTruncated: stdoutClosed,
725
+ stderrTruncated: stderrClosed,
726
+ infrastructureError,
657
727
  spawnError,
658
728
  };
659
729
  }
@@ -0,0 +1 @@
1
+ export declare function runFacade(argv: string[]): Promise<number>;
package/dist/facade.js ADDED
@@ -0,0 +1,106 @@
1
+ import { parseCommand } from './parser.js';
2
+ import { translateCommandList, EXECUTE_TRANSLATION } from './translator.js';
3
+ import { FauxnixSession } from './executor.js';
4
+ import { packageVersion } from './version.js';
5
+ /**
6
+ * Experimental native-shell facade (RFC: docs/rfc-bash-facade.md).
7
+ *
8
+ * Implements the bash process contract so a harness can point its built-in
9
+ * Bash tool at fauxnix instead of a real bash.exe:
10
+ * - one-shot: facade -c "<script>" [name arg1 ...] ($0/$1 from operands)
11
+ * - persistent: stdin blocks wrapped in <bash-input>...</bash-input>;
12
+ * each block runs in one resident session (cwd/env persist)
13
+ * and is answered with its output plus a <bash-exit>N line.
14
+ *
15
+ * Disclosure rule from the RFC: --version always identifies fauxnix.
16
+ */
17
+ const MARKER_RE = /<bash-input>([\s\S]*?)<\/bash-input>/;
18
+ const VERSION_LINE = 'GNU bash, version 5.2.0(1)-release (fauxnix facade ' + packageVersion + ')\n';
19
+ async function runScript(session, script) {
20
+ const plans = translateCommandList(parseCommand(script), EXECUTE_TRANSLATION);
21
+ const result = await session.run(plans);
22
+ return {
23
+ stdout: result.stdout,
24
+ stderr: result.stderr,
25
+ exitCode: result.exitCode,
26
+ };
27
+ }
28
+ function bashQuote(word) {
29
+ return "'" + word.replaceAll("'", `'\\''`) + "'";
30
+ }
31
+ async function runOneShot(session, script, positionals) {
32
+ // bash: trailing operands set $0, then $1.. via `set --`.
33
+ process.env['FAUXNIX_ARG0'] = positionals[0] ?? 'bash';
34
+ if (positionals.length > 1) {
35
+ const r = await runScript(session, 'set -- ' + positionals.slice(1).map(bashQuote).join(' '));
36
+ if (r.exitCode !== 0)
37
+ return r.exitCode;
38
+ }
39
+ const r = await runScript(session, script);
40
+ if (r.stdout)
41
+ process.stdout.write(r.stdout);
42
+ if (r.stderr)
43
+ process.stderr.write(r.stderr);
44
+ return r.exitCode;
45
+ }
46
+ async function runMarkerSession(session) {
47
+ await session.prewarm();
48
+ return new Promise((resolve) => {
49
+ let buf = '';
50
+ let queue = Promise.resolve();
51
+ process.stdin.setEncoding('utf8');
52
+ process.stdin.on('data', (chunk) => {
53
+ buf += chunk;
54
+ let m;
55
+ while ((m = MARKER_RE.exec(buf))) {
56
+ buf = buf.slice(m.index + m[0].length);
57
+ const cmd = m[1];
58
+ // serialize markers: a session executes one command at a time
59
+ queue = queue.then(async () => {
60
+ try {
61
+ const r = await runScript(session, cmd);
62
+ if (r.stdout)
63
+ process.stdout.write(r.stdout);
64
+ if (r.stderr)
65
+ process.stderr.write(r.stderr);
66
+ process.stdout.write(`<bash-exit>${r.exitCode}</bash-exit>\n`);
67
+ }
68
+ catch (err) {
69
+ process.stderr.write(`fauxnix: facade: ${err.message}\n`);
70
+ process.stdout.write('<bash-exit>127</bash-exit>\n');
71
+ }
72
+ });
73
+ }
74
+ });
75
+ process.stdin.on('end', () => {
76
+ queue.then(() => resolve(0));
77
+ });
78
+ });
79
+ }
80
+ export async function runFacade(argv) {
81
+ const session = new FauxnixSession();
82
+ try {
83
+ if (argv[0] === '--version') {
84
+ process.stdout.write(VERSION_LINE);
85
+ return 0;
86
+ }
87
+ if (argv[0] === '-c' || argv[0] === '-e') {
88
+ const [script, ...positionals] = argv.slice(1);
89
+ if (!script) {
90
+ process.stderr.write('bash: -c: option requires an argument\n');
91
+ return 2;
92
+ }
93
+ return await runOneShot(session, script, positionals);
94
+ }
95
+ return await runMarkerSession(session);
96
+ }
97
+ catch (err) {
98
+ // bash -c exits 2 on syntax errors; 127 covers the not-found family
99
+ const msg = err.message ?? String(err);
100
+ process.stderr.write('bash: -c: ' + msg + '\n');
101
+ return msg.includes('not found') ? 127 : 2;
102
+ }
103
+ finally {
104
+ await session.dispose();
105
+ }
106
+ }
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;
package/dist/mcp.js CHANGED
@@ -8,6 +8,11 @@ import { registeredNames } from './registry.js';
8
8
  import { packageVersion } from './version.js';
9
9
  import './commands/install-all.js';
10
10
  const TOOL_NAME = process.env.FAUXNIX_TOOL_NAME || 'bash';
11
+ const BATCH_TOOL_NAME = TOOL_NAME + '_batch';
12
+ // Text and structured output both appear in the JSON response. Leave room for
13
+ // worst-case JSON escaping below the official stdio client's 10 MiB limit.
14
+ const BATCH_STDOUT_LIMIT = 262_144;
15
+ const BATCH_STDERR_LIMIT = 65_536;
11
16
  const EXEC_ANNOTATIONS = {
12
17
  readOnlyHint: false,
13
18
  destructiveHint: true,
@@ -35,9 +40,113 @@ Supported: pipes (|), && / || / ;, redirections (> >> 2> 2>&1 < /dev/null), vari
35
40
  Unknown commands (git, node, npm, python, cargo...) are passed through and executed natively with argv-style quoting.
36
41
  Not supported: heredocs, env -i/--ignore-environment, background jobs. if/then/elif/else/fi, for-in loops, while/until, case ... esac, and word-level \$((...)) arithmetic expansion are supported.
37
42
  CWD, environment variables, export/unset, cd, and positional parameters (set -- / $1 / "$@") persist across calls within this session — a resident PowerShell 5.1 host is started when the MCP session begins (and after reset), so the first bash tool call is already warm.
43
+ Efficiency: when two or more commands or verification steps are already known, prefer ${BATCH_TOOL_NAME} once instead of making several ${TOOL_NAME} calls. Keep separate calls only when the next command requires model interpretation of the previous output. For byte-exact work, measure with wc -c or stat -c %s instead of inferring CRLF byte counts from displayed text.
38
44
  Exit codes follow bash conventions (0 ok, 1 fail, 2 usage/serious, 127 command not found, 124 timeout, 130 cancelled). The tool also returns structuredContent (schemaVersion 1) with stdout/stderr/exitCode/timedOut/cancelled/truncated/sessionId.
39
45
 
40
46
  Platform requirement: the execution backend is native Windows PowerShell 5.1+. On hosts without PowerShell on PATH (e.g. Linux containers/sandboxes), the bash tool returns exit code 127 with an actionable error instead of running the command.`;
47
+ const BATCH_TOOL_DESCRIPTION = `Compile and execute a preplanned multi-step bash workflow in one MCP round trip.
48
+
49
+ Use this instead of repeated ${TOOL_NAME} calls when the complete sequence is already known. Steps run serially and atomically in the same persistent session: later steps see cwd, environment, and files from earlier steps, while run/reset requests cannot interleave. Every command is parsed and translated before step 1 runs, and the result reports each step separately.
50
+
51
+ By default the batch stops after the first nonzero exit. Set stop_on_error=false only when later steps should still run. timeout_ms and both output limits apply to the whole batch, not once per step. Output defaults to 256 KiB stdout and 64 KiB stderr; redirect larger artifacts to files. Preflight performs no operand-file reads: use sed -e with inline script text instead of sed -f. If a later command depends on model interpretation of an earlier result, use separate ${TOOL_NAME} calls instead. For byte counts, include wc -c or stat -c %s as a verification step rather than calculating CRLF bytes mentally.`;
52
+ export class BatchCompileError extends Error {
53
+ stepIndex;
54
+ stepId;
55
+ constructor(stepIndex, stepId, cause) {
56
+ const detail = cause instanceof Error ? cause.message : String(cause);
57
+ super('fauxnix: batch compile failed at step ' +
58
+ String(stepIndex + 1) +
59
+ (stepId ? ' (' + stepId + ')' : '') +
60
+ ': ' +
61
+ detail);
62
+ this.stepIndex = stepIndex;
63
+ this.stepId = stepId;
64
+ this.name = 'BatchCompileError';
65
+ }
66
+ }
67
+ export function compileBatchSteps(steps) {
68
+ return steps.map((step, index) => {
69
+ try {
70
+ return translateCommandList(parseCommand(step.command), PURE_TRANSLATION);
71
+ }
72
+ catch (e) {
73
+ throw new BatchCompileError(index, step.id, e);
74
+ }
75
+ });
76
+ }
77
+ function batchStepStatus(r) {
78
+ if (r.spawnError || r.infrastructureError)
79
+ return 'infrastructure_error';
80
+ if (r.cancelled)
81
+ return 'cancelled';
82
+ if (r.timedOut)
83
+ return 'timed_out';
84
+ return r.exitCode === 0 ? 'completed' : 'failed';
85
+ }
86
+ export function batchToolResult(inputs, batch, sessionId) {
87
+ const steps = inputs.map((input, index) => {
88
+ const result = batch.results[index];
89
+ if (!result)
90
+ return { index, ...(input.id ? { id: input.id } : {}), status: 'skipped' };
91
+ return {
92
+ index,
93
+ ...(input.id ? { id: input.id } : {}),
94
+ status: batchStepStatus(result),
95
+ stdout: result.stdout,
96
+ stderr: result.stderr,
97
+ exitCode: result.exitCode,
98
+ timedOut: result.timedOut,
99
+ cancelled: result.cancelled,
100
+ truncated: result.truncated,
101
+ };
102
+ });
103
+ const text = steps
104
+ .map((step, index) => {
105
+ const label = '[' + String(index + 1) + '/' + String(steps.length) + (step.id ? ' ' + step.id : '') + ']';
106
+ if (step.status === 'skipped')
107
+ return label + ' skipped';
108
+ const result = batch.results[index];
109
+ return label + ' ' + step.status + ' (exit ' + String(result.exitCode) + ')\n' + formatBashText(result);
110
+ })
111
+ .join('\n');
112
+ const structuredContent = {
113
+ schemaVersion: 1,
114
+ sessionId,
115
+ preflightOk: true,
116
+ stopReason: batch.stopReason,
117
+ stepsRequested: inputs.length,
118
+ stepsCompleted: batch.results.length,
119
+ timedOut: batch.stopReason === 'timed_out',
120
+ cancelled: batch.stopReason === 'cancelled',
121
+ truncated: batch.results.some((result) => result.truncated),
122
+ steps,
123
+ };
124
+ return {
125
+ content: [{ type: 'text', text }],
126
+ structuredContent,
127
+ ...(batch.stopReason === 'infrastructure' ? { isError: true } : {}),
128
+ };
129
+ }
130
+ export function batchCompileErrorResult(inputs, error, sessionId) {
131
+ return {
132
+ content: [{ type: 'text', text: error.message }],
133
+ structuredContent: {
134
+ schemaVersion: 1,
135
+ sessionId,
136
+ preflightOk: false,
137
+ stopReason: 'compile_error',
138
+ stepsRequested: inputs.length,
139
+ stepsCompleted: 0,
140
+ failedStep: error.stepIndex,
141
+ steps: inputs.map((input, index) => ({
142
+ index,
143
+ ...(input.id ? { id: input.id } : {}),
144
+ status: index === error.stepIndex ? 'compile_error' : 'skipped',
145
+ })),
146
+ },
147
+ isError: true,
148
+ };
149
+ }
41
150
  export function formatBashText(r) {
42
151
  const parts = [];
43
152
  if (r.stdout.length)
@@ -144,6 +253,80 @@ export async function startMcpServer() {
144
253
  }, session.id, true);
145
254
  }
146
255
  });
256
+ server.tool(BATCH_TOOL_NAME, BATCH_TOOL_DESCRIPTION, {
257
+ steps: z
258
+ .array(z.object({
259
+ id: z.string().min(1).max(64).optional().describe('Optional short step label'),
260
+ command: z.string().min(1).max(16384).describe('Bash-style command for this step'),
261
+ }))
262
+ .min(1)
263
+ .max(32)
264
+ .describe('Ordered workflow steps; all are compiled before execution begins'),
265
+ stop_on_error: z
266
+ .boolean()
267
+ .optional()
268
+ .default(true)
269
+ .describe('Stop after the first nonzero exit (default true)'),
270
+ timeout_ms: z
271
+ .number()
272
+ .int()
273
+ .min(1000)
274
+ .max(600_000)
275
+ .optional()
276
+ .describe('Total timeout for the complete batch (default 120000)'),
277
+ stdout_limit_bytes: z
278
+ .number()
279
+ .int()
280
+ .min(0)
281
+ .max(BATCH_STDOUT_LIMIT)
282
+ .optional()
283
+ .describe('Total stdout budget shared by every step (default 262144)'),
284
+ stderr_limit_bytes: z
285
+ .number()
286
+ .int()
287
+ .min(0)
288
+ .max(BATCH_STDERR_LIMIT)
289
+ .optional()
290
+ .describe('Total stderr budget shared by every step (default 65536)'),
291
+ }, EXEC_ANNOTATIONS, async ({ steps, stop_on_error, timeout_ms, stdout_limit_bytes, stderr_limit_bytes }, extra) => {
292
+ try {
293
+ const compiled = compileBatchSteps(steps);
294
+ const result = await session.runBatch(compiled, {
295
+ stopOnError: stop_on_error,
296
+ timeoutMs: timeout_ms,
297
+ stdoutLimit: stdout_limit_bytes ?? BATCH_STDOUT_LIMIT,
298
+ stderrLimit: stderr_limit_bytes ?? BATCH_STDERR_LIMIT,
299
+ signal: extra.signal,
300
+ });
301
+ return batchToolResult(steps, result, session.id);
302
+ }
303
+ catch (e) {
304
+ if (e instanceof BatchCompileError) {
305
+ return batchCompileErrorResult(steps, e, session.id);
306
+ }
307
+ const message = e instanceof Error ? e.message : String(e);
308
+ return {
309
+ content: [{ type: 'text', text: message }],
310
+ structuredContent: {
311
+ schemaVersion: 1,
312
+ sessionId: session.id,
313
+ preflightOk: true,
314
+ stopReason: 'infrastructure',
315
+ stepsRequested: steps.length,
316
+ stepsCompleted: 0,
317
+ timedOut: false,
318
+ cancelled: false,
319
+ truncated: false,
320
+ steps: steps.map((step, index) => ({
321
+ index,
322
+ ...(step.id ? { id: step.id } : {}),
323
+ status: 'skipped',
324
+ })),
325
+ },
326
+ isError: true,
327
+ };
328
+ }
329
+ });
147
330
  server.tool('fauxnix_translate', 'Translate a bash-style command into the equivalent PowerShell script WITHOUT executing it. Useful for learning/debugging what fauxnix does under the hood.', { command: z.string().describe('The bash-style command line to translate (never executed)') }, TRANSLATE_ANNOTATIONS, async ({ command }) => translateToolResult(command));
148
331
  server.tool('fauxnix_session', 'Inspect or reset the persistent fauxnix shell session (current directory, environment, positional count, session id). Actions: "status" (default) or "reset".', {
149
332
  action: z
package/dist/ps-host.d.ts CHANGED
@@ -18,6 +18,7 @@ export interface HostInvokeResult {
18
18
  stderrTruncated?: boolean;
19
19
  spawnError?: 'ENOENT' | 'START';
20
20
  spawnMessage?: string;
21
+ infrastructureError?: boolean;
21
22
  stdoutSpool?: string;
22
23
  stderrSpool?: string;
23
24
  nativeStderrSpool?: string;
package/dist/ps-host.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { spawn } from 'node:child_process';
2
- import { closeSync, mkdirSync, openSync, readSync, rmSync, statSync, writeFileSync, writeSync, } from 'node:fs';
2
+ import { closeSync, openSync, readSync, rmSync, statSync, writeFileSync, writeSync, } from 'node:fs';
3
3
  import { hostBootstrapScript } from './translator.js';
4
4
  import { POWERSHELL_ARGS, powerShellMissingMessage, resolvePowerShell, } from './powershell.js';
5
5
  class NativeStderrSpoolError extends Error {
@@ -16,7 +16,14 @@ class NativeStderrSpoolError extends Error {
16
16
  this.name = 'NativeStderrSpoolError';
17
17
  }
18
18
  }
19
- const READY_TIMEOUT_MS = 30_000;
19
+ // First-ready-line budget. 30s covers every dev machine measured; contended CI
20
+ // runners cold-booting powershell.exe under full test parallelism have exceeded it,
21
+ // so FAUXNIX_HOST_READY_TIMEOUT_MS (milliseconds, minimum 1000) widens the budget
22
+ // without changing the default.
23
+ const READY_TIMEOUT_MS = (() => {
24
+ const raw = Number(process.env.FAUXNIX_HOST_READY_TIMEOUT_MS);
25
+ return Number.isFinite(raw) && raw >= 1000 ? raw : 30_000;
26
+ })();
20
27
  export const DEFAULT_STDOUT_LIMIT = 8_388_608;
21
28
  export const DEFAULT_STDERR_LIMIT = 1_048_576;
22
29
  export function encodeHostRequest(id, script, env, opts) {
@@ -160,7 +167,6 @@ export class PowerShellHost {
160
167
  resolvedLimits.nativeStderrSpoolPath = this.hostFile + '.' + id + '.native-stderr';
161
168
  }
162
169
  const nativeSpoolDir = this.hostFile + '.' + id + '.native';
163
- mkdirSync(nativeSpoolDir);
164
170
  const requestEnv = { ...env, FAUXNIX_NATIVE_SPOOL_DIR: nativeSpoolDir };
165
171
  const line = encodeHostRequest(id, script, requestEnv, this.protocol === 2
166
172
  ? {
@@ -182,6 +188,7 @@ export class PowerShellHost {
182
188
  cancelled: false,
183
189
  truncated: false,
184
190
  spawnMessage: e.message,
191
+ infrastructureError: true,
185
192
  };
186
193
  }
187
194
  let cancelled = false;
@@ -230,6 +237,7 @@ export class PowerShellHost {
230
237
  return {
231
238
  stdout: Buffer.alloc(0),
232
239
  stderr: Buffer.from(nativeSpoolError.message + '\n', 'utf8'),
240
+ infrastructureError: true,
233
241
  exitCode: 1,
234
242
  timedOut: false,
235
243
  cancelled: false,
@@ -254,6 +262,7 @@ export class PowerShellHost {
254
262
  (code !== 1 ? ' (exit ' + String(code) + ')' : '') +
255
263
  '\n', 'utf8'),
256
264
  exitCode: code === 0 ? 1 : code,
265
+ infrastructureError: true,
257
266
  timedOut: false,
258
267
  cancelled: false,
259
268
  truncated: false,
@@ -531,16 +540,13 @@ export class PowerShellHost {
531
540
  let native = Buffer.alloc(0);
532
541
  let nativeTruncated = false;
533
542
  const nativeSpool = limits?.nativeStderrSpoolPath;
534
- if ((limits?.stderrMode ?? 'capture') === 'capture' && nativeSpool) {
543
+ if ((limits?.stderrMode ?? 'capture') === 'capture' && nativeSpool && nativeBytes > 0) {
535
544
  const remaining = Math.max(0, (limits?.stderrLimit ?? DEFAULT_STDERR_LIMIT) - capturedErr.length);
536
545
  const clipped = this.readUtf8Prefix(nativeSpool, remaining, nativeBytes);
537
546
  native = Buffer.from(clipped.data);
538
547
  nativeTruncated = clipped.truncated;
539
548
  rmSync(nativeSpool, { force: true });
540
549
  }
541
- if (limits?.stderrMode === 'spool' && nativeSpool && nativeBytes === 0) {
542
- rmSync(nativeSpool, { force: true });
543
- }
544
550
  const n = Number(end.exitCode);
545
551
  return {
546
552
  stdout: Buffer.from(Buffer.concat(out)),
@@ -569,16 +575,6 @@ export class PowerShellHost {
569
575
  this.nativeCapture = null;
570
576
  reject(failure);
571
577
  }, timeoutMs);
572
- let spoolFd;
573
- let ioError;
574
- if (mode !== 'discard' && spoolPath) {
575
- try {
576
- spoolFd = openSync(spoolPath, 'w');
577
- }
578
- catch (e) {
579
- ioError = new NativeStderrSpoolError('open', spoolPath, e);
580
- }
581
- }
582
578
  this.nativeCapture = {
583
579
  id,
584
580
  needle: Buffer.from('FAUXNIX_ERR_END:' + id + '\n', 'utf8'),
@@ -586,10 +582,8 @@ export class PowerShellHost {
586
582
  limit: Math.max(0, limit),
587
583
  tail: Buffer.alloc(0),
588
584
  spoolPath,
589
- spoolFd,
590
585
  bytesWritten: 0,
591
586
  bytesSeen: 0,
592
- ioError,
593
587
  resolve,
594
588
  reject,
595
589
  timer,
@@ -605,13 +599,26 @@ export class PowerShellHost {
605
599
  if (!data.length)
606
600
  return;
607
601
  state.bytesSeen += data.length;
608
- if (state.ioError || state.mode === 'discard' || state.spoolFd === undefined)
602
+ if (state.ioError || state.mode === 'discard')
609
603
  return;
610
604
  let retained = data;
611
605
  if (state.mode === 'capture') {
612
606
  const remaining = Math.max(0, state.limit + 3 - state.bytesWritten);
613
607
  retained = data.subarray(0, remaining);
614
608
  }
609
+ if (!retained.length)
610
+ return;
611
+ if (state.spoolFd === undefined) {
612
+ if (!state.spoolPath)
613
+ return;
614
+ try {
615
+ state.spoolFd = openSync(state.spoolPath, 'w');
616
+ }
617
+ catch (e) {
618
+ state.ioError = new NativeStderrSpoolError('open', state.spoolPath, e);
619
+ return;
620
+ }
621
+ }
615
622
  try {
616
623
  let offset = 0;
617
624
  while (offset < retained.length) {