fauxnix-cli 0.13.0 → 2.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/facade.js ADDED
@@ -0,0 +1,115 @@
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 -c '' is a successful no-op, distinct from a missing operand.
33
+ if (script === '')
34
+ return 0;
35
+ // bash: trailing operands set $0, then $1.. via `set --`.
36
+ session.env['FAUXNIX_ARG0'] = positionals[0] ?? 'bash';
37
+ if (positionals.length > 1) {
38
+ const r = await runScript(session, 'set -- ' + positionals.slice(1).map(bashQuote).join(' '));
39
+ if (r.exitCode !== 0) {
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
+ }
47
+ const r = await runScript(session, script);
48
+ if (r.stdout)
49
+ process.stdout.write(r.stdout);
50
+ if (r.stderr)
51
+ process.stderr.write(r.stderr);
52
+ return r.exitCode;
53
+ }
54
+ async function runMarkerSession(session) {
55
+ await session.prewarm();
56
+ return new Promise((resolve) => {
57
+ let buf = '';
58
+ let queue = Promise.resolve();
59
+ process.stdin.setEncoding('utf8');
60
+ process.stdin.on('data', (chunk) => {
61
+ buf += chunk;
62
+ let m;
63
+ while ((m = MARKER_RE.exec(buf))) {
64
+ buf = buf.slice(m.index + m[0].length);
65
+ const cmd = m[1];
66
+ // serialize markers: a session executes one command at a time
67
+ queue = queue.then(async () => {
68
+ try {
69
+ const r = await runScript(session, cmd);
70
+ if (r.stdout)
71
+ process.stdout.write(r.stdout);
72
+ if (r.stderr)
73
+ process.stderr.write(r.stderr);
74
+ process.stdout.write(`<bash-exit>${r.exitCode}</bash-exit>\n`);
75
+ }
76
+ catch (err) {
77
+ const msg = err instanceof Error ? err.message : String(err);
78
+ process.stderr.write(`fauxnix: facade: ${msg}\n`);
79
+ process.stdout.write('<bash-exit>127</bash-exit>\n');
80
+ }
81
+ });
82
+ }
83
+ });
84
+ process.stdin.on('end', () => {
85
+ queue.then(() => resolve(0));
86
+ });
87
+ });
88
+ }
89
+ export async function runFacade(argv) {
90
+ const session = new FauxnixSession();
91
+ try {
92
+ if (argv[0] === '--version') {
93
+ process.stdout.write(VERSION_LINE);
94
+ return 0;
95
+ }
96
+ if (argv[0] === '-c' || argv[0] === '-e') {
97
+ const [script, ...positionals] = argv.slice(1);
98
+ if (script === undefined) {
99
+ process.stderr.write('bash: -c: option requires an argument\n');
100
+ return 2;
101
+ }
102
+ return await runOneShot(session, script, positionals);
103
+ }
104
+ return await runMarkerSession(session);
105
+ }
106
+ catch (err) {
107
+ // bash -c exits 2 on syntax errors; 127 covers the not-found family
108
+ const msg = err instanceof Error ? err.message : String(err);
109
+ process.stderr.write('bash: -c: ' + msg + '\n');
110
+ return msg.includes('not found') ? 127 : 2;
111
+ }
112
+ finally {
113
+ await session.dispose();
114
+ }
115
+ }
package/dist/index.js CHANGED
@@ -1,6 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { runCli } from './cli.js';
3
- runCli(process.argv.slice(2)).catch((e) => {
4
- console.error(e instanceof Error ? e.message : String(e));
5
- process.exit(1);
6
- });
2
+ import { nodeEngineRange, supportsNode } from './runtime-support.js';
3
+ if (!supportsNode(process.version)) {
4
+ console.error(`fauxnix: Node.js ${nodeEngineRange} is required; found ${process.version}`);
5
+ process.exitCode = 1;
6
+ }
7
+ else {
8
+ await import('./cli.js').then(({ runCli }) => runCli(process.argv.slice(2))).catch((e) => {
9
+ console.error(e instanceof Error ? e.message : String(e));
10
+ process.exitCode = 1;
11
+ });
12
+ }
package/dist/mcp.d.ts CHANGED
@@ -32,7 +32,7 @@ export declare function batchToolResult(inputs: BatchStepInput[], batch: BatchEx
32
32
  id?: string | undefined;
33
33
  index: number;
34
34
  } | {
35
- status: "cancelled" | "completed" | "timed_out" | "failed" | "infrastructure_error";
35
+ status: "cancelled" | "timed_out" | "completed" | "failed" | "infrastructure_error";
36
36
  stdout: string;
37
37
  stderr: string;
38
38
  exitCode: number;
package/dist/mcp.js CHANGED
@@ -11,8 +11,8 @@ const TOOL_NAME = process.env.FAUXNIX_TOOL_NAME || 'bash';
11
11
  const BATCH_TOOL_NAME = TOOL_NAME + '_batch';
12
12
  // Text and structured output both appear in the JSON response. Leave room for
13
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;
14
+ const MCP_STDOUT_LIMIT = 262_144;
15
+ const MCP_STDERR_LIMIT = 65_536;
16
16
  const EXEC_ANNOTATIONS = {
17
17
  readOnlyHint: false,
18
18
  destructiveHint: true,
@@ -41,6 +41,7 @@ Unknown commands (git, node, npm, python, cargo...) are passed through and execu
41
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.
42
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
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.
44
+ MCP capture is bounded to 256 KiB stdout and 64 KiB stderr across the complete command list; larger output is marked truncated. Redirect larger artifacts to files. These transport-safe budgets include room for JSON escaping and duplicate text/structured fields.
44
45
  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.
45
46
 
46
47
  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.`;
@@ -221,155 +222,175 @@ export async function startMcpServer() {
221
222
  process.env.FAUXNIX_ARG0 = TOOL_NAME;
222
223
  const server = new McpServer({ name: 'fauxnix', version: packageVersion }, { capabilities: { tools: {} } });
223
224
  const session = new FauxnixSession();
224
- await session.prewarm();
225
- server.tool(TOOL_NAME, TOOL_DESCRIPTION, {
226
- command: z.string().describe('The bash-style command line to run'),
227
- timeout_ms: z
228
- .number()
229
- .int()
230
- .min(1000)
231
- .max(600_000)
232
- .optional()
233
- .describe('Timeout in milliseconds (default 120000)'),
234
- }, EXEC_ANNOTATIONS, async ({ command, timeout_ms }, extra) => {
235
- try {
236
- const plans = translateCommandList(parseCommand(command), EXECUTE_TRANSLATION);
237
- const result = await session.run(plans, {
238
- timeoutMs: timeout_ms,
239
- signal: extra.signal,
240
- });
241
- const infra = result.spawnError === 'ENOENT' || result.spawnError === 'START';
242
- return bashToolResult(result, session.id, infra);
243
- }
244
- catch (e) {
245
- const msg = e instanceof Error ? e.message : String(e);
246
- return bashToolResult({
247
- stdout: '',
248
- stderr: msg,
249
- exitCode: 2,
250
- timedOut: false,
251
- cancelled: false,
252
- truncated: false,
253
- }, session.id, true);
254
- }
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,
225
+ const input = process.stdin;
226
+ let shutdownPromise;
227
+ const shutdown = () => {
228
+ if (!shutdownPromise) {
229
+ input.removeListener('end', onShutdown);
230
+ input.removeListener('close', onShutdown);
231
+ process.removeListener('SIGINT', onShutdown);
232
+ process.removeListener('SIGTERM', onShutdown);
233
+ // Schedule cleanup after storing the promise so transport.close callbacks
234
+ // can request shutdown again without disposing the session twice.
235
+ shutdownPromise = Promise.resolve().then(async () => {
236
+ try {
237
+ await session.dispose();
238
+ }
239
+ finally {
240
+ try {
241
+ await server.close();
242
+ }
243
+ catch {
244
+ /* best effort, including partially connected transports */
245
+ }
246
+ }
300
247
  });
301
- return batchToolResult(steps, result, session.id);
302
248
  }
303
- catch (e) {
304
- if (e instanceof BatchCompileError) {
305
- return batchCompileErrorResult(steps, e, session.id);
249
+ return shutdownPromise;
250
+ };
251
+ const onShutdown = () => {
252
+ void shutdown().catch(() => undefined);
253
+ };
254
+ try {
255
+ await session.prewarm();
256
+ server.tool(TOOL_NAME, TOOL_DESCRIPTION, {
257
+ command: z.string().describe('The bash-style command line to run'),
258
+ timeout_ms: z
259
+ .number()
260
+ .int()
261
+ .min(1000)
262
+ .max(600_000)
263
+ .optional()
264
+ .describe('Timeout in milliseconds (default 120000)'),
265
+ }, EXEC_ANNOTATIONS, async ({ command, timeout_ms }, extra) => {
266
+ try {
267
+ const plans = translateCommandList(parseCommand(command), EXECUTE_TRANSLATION);
268
+ const result = await session.run(plans, {
269
+ timeoutMs: timeout_ms,
270
+ signal: extra.signal,
271
+ stdoutLimit: MCP_STDOUT_LIMIT,
272
+ stderrLimit: MCP_STDERR_LIMIT,
273
+ });
274
+ const infra = result.infrastructureError === true ||
275
+ result.spawnError === 'ENOENT' || result.spawnError === 'START';
276
+ return bashToolResult(result, session.id, infra);
306
277
  }
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,
278
+ catch (e) {
279
+ const msg = e instanceof Error ? e.message : String(e);
280
+ return bashToolResult({
281
+ stdout: '',
282
+ stderr: msg,
283
+ exitCode: 2,
317
284
  timedOut: false,
318
285
  cancelled: false,
319
286
  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
- });
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));
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".', {
332
- action: z
333
- .enum(['status', 'reset'])
334
- .default('status')
335
- .describe('"status" shows the session state (cwd, tracked env keys, positional count); "reset" clears it back to a fresh shell'),
336
- }, SESSION_ANNOTATIONS, async ({ action }) => {
337
- if (action === 'reset') {
338
- await session.reset();
339
- return { content: [{ type: 'text', text: 'fauxnix: session reset' }] };
340
- }
341
- return { content: [{ type: 'text', text: formatSessionStatus(session) }] };
342
- });
343
- const transport = new StdioServerTransport();
344
- let shuttingDown = false;
345
- const shutdown = async () => {
346
- if (shuttingDown)
347
- return;
348
- shuttingDown = true;
349
- await session.dispose();
287
+ }, session.id, true);
288
+ }
289
+ });
290
+ server.tool(BATCH_TOOL_NAME, BATCH_TOOL_DESCRIPTION, {
291
+ steps: z
292
+ .array(z.object({
293
+ id: z.string().min(1).max(64).optional().describe('Optional short step label'),
294
+ command: z.string().min(1).max(16384).describe('Bash-style command for this step'),
295
+ }))
296
+ .min(1)
297
+ .max(32)
298
+ .describe('Ordered workflow steps; all are compiled before execution begins'),
299
+ stop_on_error: z
300
+ .boolean()
301
+ .optional()
302
+ .default(true)
303
+ .describe('Stop after the first nonzero exit (default true)'),
304
+ timeout_ms: z
305
+ .number()
306
+ .int()
307
+ .min(1000)
308
+ .max(600_000)
309
+ .optional()
310
+ .describe('Total timeout for the complete batch (default 120000)'),
311
+ stdout_limit_bytes: z
312
+ .number()
313
+ .int()
314
+ .min(0)
315
+ .max(MCP_STDOUT_LIMIT)
316
+ .optional()
317
+ .describe('Total stdout budget shared by every step (default 262144)'),
318
+ stderr_limit_bytes: z
319
+ .number()
320
+ .int()
321
+ .min(0)
322
+ .max(MCP_STDERR_LIMIT)
323
+ .optional()
324
+ .describe('Total stderr budget shared by every step (default 65536)'),
325
+ }, EXEC_ANNOTATIONS, async ({ steps, stop_on_error, timeout_ms, stdout_limit_bytes, stderr_limit_bytes }, extra) => {
326
+ try {
327
+ const compiled = compileBatchSteps(steps);
328
+ const result = await session.runBatch(compiled, {
329
+ stopOnError: stop_on_error,
330
+ timeoutMs: timeout_ms,
331
+ stdoutLimit: stdout_limit_bytes ?? MCP_STDOUT_LIMIT,
332
+ stderrLimit: stderr_limit_bytes ?? MCP_STDERR_LIMIT,
333
+ signal: extra.signal,
334
+ });
335
+ return batchToolResult(steps, result, session.id);
336
+ }
337
+ catch (e) {
338
+ if (e instanceof BatchCompileError) {
339
+ return batchCompileErrorResult(steps, e, session.id);
340
+ }
341
+ const message = e instanceof Error ? e.message : String(e);
342
+ return {
343
+ content: [{ type: 'text', text: message }],
344
+ structuredContent: {
345
+ schemaVersion: 1,
346
+ sessionId: session.id,
347
+ preflightOk: true,
348
+ stopReason: 'infrastructure',
349
+ stepsRequested: steps.length,
350
+ stepsCompleted: 0,
351
+ timedOut: false,
352
+ cancelled: false,
353
+ truncated: false,
354
+ steps: steps.map((step, index) => ({
355
+ index,
356
+ ...(step.id ? { id: step.id } : {}),
357
+ status: 'skipped',
358
+ })),
359
+ },
360
+ isError: true,
361
+ };
362
+ }
363
+ });
364
+ 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));
365
+ server.tool('fauxnix_session', 'Inspect or reset the persistent fauxnix shell session (current directory, environment, positional count, session id). Actions: "status" (default) or "reset".', {
366
+ action: z
367
+ .enum(['status', 'reset'])
368
+ .default('status')
369
+ .describe('"status" shows the session state (cwd, tracked env keys, positional count); "reset" clears it back to a fresh shell'),
370
+ }, SESSION_ANNOTATIONS, async ({ action }) => {
371
+ if (action === 'reset') {
372
+ await session.reset();
373
+ return { content: [{ type: 'text', text: 'fauxnix: session reset' }] };
374
+ }
375
+ return { content: [{ type: 'text', text: formatSessionStatus(session) }] };
376
+ });
377
+ const transport = new StdioServerTransport();
378
+ input.on('end', onShutdown);
379
+ input.on('close', onShutdown);
380
+ process.on('SIGINT', onShutdown);
381
+ process.on('SIGTERM', onShutdown);
382
+ transport.onclose = onShutdown;
383
+ await server.connect(transport);
384
+ }
385
+ catch (error) {
350
386
  try {
351
- await server.close();
387
+ await shutdown();
352
388
  }
353
389
  catch {
354
- /* ignore */
390
+ /* preserve the startup error if session teardown also fails */
355
391
  }
356
- };
357
- process.stdin.on('end', () => {
358
- void shutdown();
359
- });
360
- process.stdin.on('close', () => {
361
- void shutdown();
362
- });
363
- process.on('SIGINT', () => {
364
- void shutdown();
365
- });
366
- process.on('SIGTERM', () => {
367
- void shutdown();
368
- });
369
- transport.onclose = () => {
370
- void shutdown();
371
- };
372
- await server.connect(transport);
392
+ throw error;
393
+ }
373
394
  }
374
395
  // keep referenced for tree-shaking clarity
375
396
  export { translatePipelineBody };
package/dist/parser.js CHANGED
@@ -123,6 +123,12 @@ export function tokenize(input) {
123
123
  let buf = '';
124
124
  while (i < n && input[i] !== '"') {
125
125
  const c = input[i];
126
+ // A quoted continuation joins the physical lines just as it does
127
+ // outside quotes; unlike an ordinary quoted newline it adds no text.
128
+ if (c === '\\' && input[i + 1] === '\n') {
129
+ i += 2;
130
+ continue;
131
+ }
126
132
  if (c === '\\' && i + 1 < n && '"$`\\'.includes(input[i + 1])) {
127
133
  buf += input[i + 1];
128
134
  i += 2;
@@ -441,6 +447,12 @@ function readDollar(input, i) {
441
447
  let depth = 1;
442
448
  let k = j + 1;
443
449
  while (k < n && depth > 0) {
450
+ // Escaped delimiters belong to the command text, not the enclosing
451
+ // substitution. Preserve both characters for its recursive tokenizer.
452
+ if (input[k] === '\\' && k + 1 < n) {
453
+ k += 2;
454
+ continue;
455
+ }
444
456
  if (input[k] === '(')
445
457
  depth++;
446
458
  else if (input[k] === ')')
@@ -449,7 +461,8 @@ function readDollar(input, i) {
449
461
  const q = input[k];
450
462
  k++;
451
463
  while (k < n && input[k] !== q) {
452
- if (input[k] === '\\')
464
+ // Single quotes are fully literal, including a final backslash.
465
+ if (q === '"' && input[k] === '\\')
453
466
  k++;
454
467
  k++;
455
468
  }
@@ -913,6 +926,10 @@ export function parseCommand(input) {
913
926
  const t = peek();
914
927
  if (t.type === 'OP' && t.op === '|') {
915
928
  next();
929
+ // Bash permits physical newlines (and comments on those lines)
930
+ // while waiting for the next pipeline stage, as after && and ||.
931
+ while (peek().type === 'OP' && peek().op === '\n')
932
+ next();
916
933
  continue;
917
934
  }
918
935
  break;
package/dist/ps-host.js CHANGED
@@ -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) {
@@ -145,7 +152,38 @@ export class PowerShellHost {
145
152
  await this.stop();
146
153
  return this.cancelledResult();
147
154
  }
148
- const started = await this.ensureStarted();
155
+ // Startup is part of the caller's deadline. A cold host must not send a
156
+ // command after its caller has already cancelled or exhausted its budget.
157
+ const deadline = Date.now() + timeoutMs;
158
+ let startupTimer;
159
+ let onStartupAbort;
160
+ const interrupted = new Promise((resolve) => {
161
+ startupTimer = setTimeout(() => resolve('timed_out'), Math.max(0, timeoutMs));
162
+ onStartupAbort = () => resolve('cancelled');
163
+ signal?.addEventListener('abort', onStartupAbort, { once: true });
164
+ if (signal?.aborted)
165
+ resolve('cancelled');
166
+ });
167
+ let started;
168
+ try {
169
+ started = await Promise.race([this.ensureStarted(), interrupted]);
170
+ }
171
+ finally {
172
+ clearTimeout(startupTimer);
173
+ if (onStartupAbort)
174
+ signal?.removeEventListener('abort', onStartupAbort);
175
+ }
176
+ if (started === 'cancelled' || signal?.aborted) {
177
+ await this.stop();
178
+ return this.cancelledResult();
179
+ }
180
+ if (started === 'timed_out' || Date.now() >= deadline) {
181
+ await this.stop();
182
+ return {
183
+ stdout: Buffer.alloc(0), stderr: Buffer.alloc(0), exitCode: 124,
184
+ timedOut: true, cancelled: false, truncated: false,
185
+ };
186
+ }
149
187
  if (started)
150
188
  return { ...started, cancelled: false, truncated: false };
151
189
  const id = 'f' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
@@ -192,9 +230,9 @@ export class PowerShellHost {
192
230
  signal?.addEventListener('abort', onAbort, { once: true });
193
231
  try {
194
232
  if (this.protocol === 2) {
195
- return await this.collectV2(id, timeoutMs, resolvedLimits);
233
+ return await this.collectV2(id, Math.max(0, deadline - Date.now()), resolvedLimits);
196
234
  }
197
- const raw = await this.nextJsonLine(timeoutMs, id);
235
+ const raw = await this.nextJsonLine(Math.max(0, deadline - Date.now()), id);
198
236
  const msg = decodeHostResponse(raw);
199
237
  const native = this.drainNativeStderr();
200
238
  return {
@@ -68,6 +68,11 @@ export interface WordArgs {
68
68
  flags: Set<string>;
69
69
  longs: Set<string>;
70
70
  values: Map<string, string>;
71
+ /** Every option value in argv order, including repeated options/aliases. */
72
+ valueEntries: Array<{
73
+ name: string;
74
+ value: string;
75
+ }>;
71
76
  /** Options that take a value but were not followed by one. */
72
77
  missingValue: string[];
73
78
  operandWords: Word[];
package/dist/registry.js CHANGED
@@ -96,6 +96,11 @@ export function parseWords(args, shortValues = [], longValues = []) {
96
96
  const flags = new Set();
97
97
  const longs = new Set();
98
98
  const values = new Map();
99
+ const valueEntries = [];
100
+ const addValue = (name, value) => {
101
+ values.set(name, value);
102
+ valueEntries.push({ name, value });
103
+ };
99
104
  const missingValue = [];
100
105
  const operandWords = [];
101
106
  let i = 0;
@@ -109,12 +114,12 @@ export function parseWords(args, shortValues = [], longValues = []) {
109
114
  const eq = t.indexOf('=');
110
115
  if (eq >= 0) {
111
116
  longs.add(t.slice(0, eq));
112
- values.set(t.slice(0, eq), t.slice(eq + 1));
117
+ addValue(t.slice(0, eq), t.slice(eq + 1));
113
118
  }
114
119
  else if (longValues.includes(t)) {
115
120
  longs.add(t);
116
121
  if (i + 1 < args.length) {
117
- values.set(t, wordToString(args[i + 1]));
122
+ addValue(t, wordToString(args[i + 1]));
118
123
  i++;
119
124
  }
120
125
  else
@@ -133,10 +138,10 @@ export function parseWords(args, shortValues = [], longValues = []) {
133
138
  // value-taking options report via `values`, not `flags`
134
139
  const rest = body.slice(c + 1);
135
140
  if (rest) {
136
- values.set('-' + ch, rest);
141
+ addValue('-' + ch, rest);
137
142
  }
138
143
  else if (i + 1 < args.length) {
139
- values.set('-' + ch, wordToString(args[i + 1]));
144
+ addValue('-' + ch, wordToString(args[i + 1]));
140
145
  i++;
141
146
  }
142
147
  else
@@ -151,7 +156,7 @@ export function parseWords(args, shortValues = [], longValues = []) {
151
156
  }
152
157
  i++;
153
158
  }
154
- return { flags, longs, values, missingValue, operandWords };
159
+ return { flags, longs, values, valueEntries, missingValue, operandWords };
155
160
  }
156
161
  const specs = new Map();
157
162
  /**
@@ -0,0 +1,3 @@
1
+ export declare const nodeEngineRange: string;
2
+ /** This package uses one inclusive stable-version floor, not general semver ranges. */
3
+ export declare function supportsNode(version: string): boolean;