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/mcp.js CHANGED
@@ -3,11 +3,16 @@ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
3
3
  import { z } from 'zod';
4
4
  import { FauxnixSession } from './executor.js';
5
5
  import { parseCommand } from './parser.js';
6
- import { translateCommandList, wrapScript, translatePipelineBody } from './translator.js';
6
+ import { EXECUTE_TRANSLATION, PURE_TRANSLATION, translateCommandList, wrapScript, translatePipelineBody, } from './translator.js';
7
7
  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)
@@ -69,6 +178,18 @@ export function bashToolResult(r, sessionId, infra) {
69
178
  ...(infra ? { isError: true } : {}),
70
179
  };
71
180
  }
181
+ export function translateToolResult(command) {
182
+ try {
183
+ const list = parseCommand(command);
184
+ const plans = translateCommandList(list, PURE_TRANSLATION);
185
+ const script = wrapScript(plans.map((p) => p.script).join('\n# ---- next segment ----\n'));
186
+ return { content: [{ type: 'text', text: script }] };
187
+ }
188
+ catch (e) {
189
+ const msg = e instanceof Error ? e.message : String(e);
190
+ return { content: [{ type: 'text', text: msg }], isError: true };
191
+ }
192
+ }
72
193
  /** Packed FAUXNIX_POS uses char-30 separators (same as array sidecar). */
73
194
  const POS_SEP = '\x1e';
74
195
  export function positionalCountFromEnv(env) {
@@ -112,7 +233,7 @@ export async function startMcpServer() {
112
233
  .describe('Timeout in milliseconds (default 120000)'),
113
234
  }, EXEC_ANNOTATIONS, async ({ command, timeout_ms }, extra) => {
114
235
  try {
115
- const plans = translateCommandList(parseCommand(command));
236
+ const plans = translateCommandList(parseCommand(command), EXECUTE_TRANSLATION);
116
237
  const result = await session.run(plans, {
117
238
  timeoutMs: timeout_ms,
118
239
  signal: extra.signal,
@@ -132,18 +253,81 @@ export async function startMcpServer() {
132
253
  }, session.id, true);
133
254
  }
134
255
  });
135
- 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 }) => {
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) => {
136
292
  try {
137
- const list = parseCommand(command);
138
- const plans = translateCommandList(list);
139
- const script = wrapScript(plans.map((p) => p.script).join('\n# ---- next segment ----\n'));
140
- return { content: [{ type: 'text', text: script }] };
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);
141
302
  }
142
303
  catch (e) {
143
- const msg = e instanceof Error ? e.message : String(e);
144
- return { content: [{ type: 'text', text: msg }], isError: true };
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
+ };
145
328
  }
146
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));
147
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".', {
148
332
  action: z
149
333
  .enum(['status', 'reset'])
package/dist/parser.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { FauxnixParseError, isUnquotedLiteral, wordToString, } from './ast.js';
2
2
  const OPERATORS = [
3
- '&&', '||', '>>', '<<', '2>&1', '1>&2', '2>', '&>>', '&>', '>', '<', '|', ';;', ';', '&',
3
+ '&&', '||', '2>>', '>>', '<<', '2>&1', '1>&2', '2>', '&>>', '&>', '>', '<', '|', ';;', ';', '&',
4
4
  ];
5
5
  const BACKGROUND_MSG = 'fauxnix: background & is not supported yet. Run the command in the foreground instead.';
6
6
  const WHILE_UNTIL_MSG = 'fauxnix: while/until loops are not supported yet. Use `for x in ...; do ...; done` over a known list instead.';
@@ -61,6 +61,12 @@ export function tokenize(input) {
61
61
  // try operators (longest first — list above is ordered)
62
62
  let matched;
63
63
  for (const op of OPERATORS) {
64
+ // A digit-leading fd operator is only a direct token at a word boundary.
65
+ // Otherwise consume the digit normally: `file2>>out` is word `file2`
66
+ // plus stdout `>>out`, while `12>>out` stays one unsupported fd token
67
+ // and fails loud instead of being stolen by `2>>`.
68
+ if (cur.length > 0 && /^\d/.test(op))
69
+ continue;
64
70
  if (input.startsWith(op, i)) {
65
71
  matched = op;
66
72
  break;
@@ -184,8 +190,10 @@ export function tokenize(input) {
184
190
  i += 2;
185
191
  continue;
186
192
  }
187
- // track leading digits (potential fd number for redirects)
188
- if (/[0-9]/.test(ch) && cur.length === 0 && fdDigits.length < 2) {
193
+ // Track an all-digit word as a potential fd number. Keep consuming every
194
+ // leading digit so unsupported multi-digit fds stay intact and fail loud
195
+ // instead of becoming argv plus a different redirect.
196
+ if (/[0-9]/.test(ch) && (cur.length === 0 || fdDigits.length === cur.length)) {
189
197
  beginWordPart();
190
198
  fdDigits += ch;
191
199
  cur.push({ kind: 'Text', text: ch });
@@ -0,0 +1,22 @@
1
+ export declare const POWERSHELL_ARGS: readonly ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass"];
2
+ export type PowerShellEdition = 'Desktop' | 'Core';
3
+ export interface PowerShellSelection {
4
+ /** Absolute executable path resolved once for this check/session. */
5
+ readonly executable: string;
6
+ readonly expectedEdition: PowerShellEdition;
7
+ readonly configured: boolean;
8
+ readonly requested?: string;
9
+ readonly error?: string;
10
+ }
11
+ export interface PowerShellResolveOptions {
12
+ cwd?: string;
13
+ exists?: (candidate: string) => boolean;
14
+ }
15
+ /**
16
+ * Select the process-wide PowerShell host. FAUXNIX_PS is intentionally a
17
+ * small enum, not a command line: spawn() receives one executable and the
18
+ * fixed fauxnix arguments separately.
19
+ */
20
+ export declare function resolvePowerShell(env?: NodeJS.ProcessEnv, options?: PowerShellResolveOptions): PowerShellSelection;
21
+ export declare function powerShellDisplay(selection: PowerShellSelection): string;
22
+ export declare function powerShellMissingMessage(selection: PowerShellSelection): string;
@@ -0,0 +1,129 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { win32 } from 'node:path';
3
+ export const POWERSHELL_ARGS = [
4
+ '-NoProfile',
5
+ '-NonInteractive',
6
+ '-ExecutionPolicy',
7
+ 'Bypass',
8
+ ];
9
+ function envValue(env, name) {
10
+ const key = Object.keys(env).find((candidate) => candidate.toLowerCase() === name.toLowerCase());
11
+ return key === undefined ? undefined : env[key];
12
+ }
13
+ function comparableWindowsPath(value) {
14
+ return win32.normalize(value).replace(/[\\/]+$/, '').toLowerCase();
15
+ }
16
+ function isFullyQualifiedWindowsPath(value) {
17
+ return /^[a-z]:[\\/]/i.test(value) || /^\\\\[^\\/]+[\\/][^\\/]+/.test(value);
18
+ }
19
+ function unquotePathEntry(value) {
20
+ const trimmed = value.trim();
21
+ if (trimmed.length >= 2 && trimmed.startsWith('"') && trimmed.endsWith('"')) {
22
+ return trimmed.slice(1, -1).trim();
23
+ }
24
+ return trimmed;
25
+ }
26
+ function desktopSelection(env, configured, requested, exists) {
27
+ const systemRoot = envValue(env, 'SystemRoot')?.trim();
28
+ if (!systemRoot || !/^[a-z]:[\\/]/i.test(systemRoot)) {
29
+ return {
30
+ executable: '',
31
+ expectedEdition: 'Desktop',
32
+ configured,
33
+ requested,
34
+ error: 'fauxnix: cannot resolve Windows PowerShell safely because SystemRoot is missing or not drive-absolute.',
35
+ };
36
+ }
37
+ const executable = win32.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
38
+ if (!exists(executable)) {
39
+ return {
40
+ executable,
41
+ expectedEdition: 'Desktop',
42
+ configured,
43
+ requested,
44
+ error: `fauxnix: Windows PowerShell not found at trusted system path ${executable}.`,
45
+ };
46
+ }
47
+ return { executable, expectedEdition: 'Desktop', configured, requested };
48
+ }
49
+ function coreSelection(env, requested, cwd, exists) {
50
+ const cwdKey = win32.isAbsolute(cwd) ? comparableWindowsPath(cwd) : '';
51
+ const rawPath = envValue(env, 'PATH') ?? '';
52
+ const seen = new Set();
53
+ for (const rawEntry of rawPath.split(';')) {
54
+ const directory = unquotePathEntry(rawEntry);
55
+ if (!directory || !isFullyQualifiedWindowsPath(directory))
56
+ continue;
57
+ const directoryKey = comparableWindowsPath(directory);
58
+ if (!directoryKey || directoryKey === cwdKey || seen.has(directoryKey))
59
+ continue;
60
+ seen.add(directoryKey);
61
+ const candidate = win32.join(directory, 'pwsh.exe');
62
+ if (exists(candidate)) {
63
+ return {
64
+ executable: candidate,
65
+ expectedEdition: 'Core',
66
+ configured: true,
67
+ requested,
68
+ };
69
+ }
70
+ }
71
+ return {
72
+ executable: '',
73
+ expectedEdition: 'Core',
74
+ configured: true,
75
+ requested,
76
+ error: 'fauxnix: pwsh.exe not found in eligible PATH entries ' +
77
+ '(absolute directories only; the current directory is excluded).',
78
+ };
79
+ }
80
+ /**
81
+ * Select the process-wide PowerShell host. FAUXNIX_PS is intentionally a
82
+ * small enum, not a command line: spawn() receives one executable and the
83
+ * fixed fauxnix arguments separately.
84
+ */
85
+ export function resolvePowerShell(env = process.env, options = {}) {
86
+ const requested = envValue(env, 'FAUXNIX_PS')?.trim();
87
+ const exists = options.exists ?? existsSync;
88
+ const cwd = options.cwd ?? process.cwd();
89
+ if (!requested) {
90
+ return desktopSelection(env, false, undefined, exists);
91
+ }
92
+ switch (requested.toLowerCase()) {
93
+ case 'powershell':
94
+ case 'powershell.exe':
95
+ return desktopSelection(env, true, requested, exists);
96
+ case 'pwsh':
97
+ case 'pwsh.exe':
98
+ return coreSelection(env, requested, cwd, exists);
99
+ default:
100
+ return {
101
+ executable: '',
102
+ expectedEdition: 'Desktop',
103
+ configured: true,
104
+ requested,
105
+ error: `fauxnix: invalid FAUXNIX_PS=${JSON.stringify(requested)}; ` +
106
+ 'expected "powershell" or "pwsh". Unset it to use Windows PowerShell 5.1.',
107
+ };
108
+ }
109
+ }
110
+ export function powerShellDisplay(selection) {
111
+ if (selection.error) {
112
+ if (selection.requested === undefined)
113
+ return 'unresolved default Windows PowerShell';
114
+ return `unresolved selection (FAUXNIX_PS=${JSON.stringify(selection.requested)})`;
115
+ }
116
+ if (!selection.configured)
117
+ return `${selection.executable} (default, trusted system path)`;
118
+ return `${selection.executable} (FAUXNIX_PS=${selection.requested}, resolved once)`;
119
+ }
120
+ export function powerShellMissingMessage(selection) {
121
+ if (selection.expectedEdition === 'Core') {
122
+ return ('fauxnix: pwsh.exe not found in eligible absolute PATH entries — FAUXNIX_PS=pwsh selects PowerShell 7.\n' +
123
+ 'Install PowerShell 7 in an absolute PATH directory outside the current working directory, ' +
124
+ 'or unset FAUXNIX_PS ' +
125
+ 'to use Windows PowerShell 5.1.\n');
126
+ }
127
+ return (`fauxnix: Windows PowerShell not found at ${selection.executable || 'the trusted SystemRoot path'}.\n` +
128
+ 'Run fauxnix on Windows, or set FAUXNIX_PS=pwsh after installing PowerShell 7 in an eligible absolute PATH directory.\n');
129
+ }
package/dist/ps-host.d.ts CHANGED
@@ -1,24 +1,44 @@
1
- export declare const PS_MISSING_MESSAGE: string;
1
+ import { PowerShellSelection } from './powershell.js';
2
+ type NativeSpoolWriter = (fd: number, buffer: Buffer, offset: number, length: number) => number;
2
3
  export declare const DEFAULT_STDOUT_LIMIT = 8388608;
3
4
  export declare const DEFAULT_STDERR_LIMIT = 1048576;
4
5
  export interface HostInvokeResult {
5
6
  stdout: Buffer;
7
+ /** UTF-8 stderr captured inside the JSON-framed host protocol. */
6
8
  stderr: Buffer;
9
+ /** Bytes written directly to the PowerShell process stderr OS pipe. */
10
+ nativeStderr?: Buffer;
7
11
  exitCode: number;
8
12
  timedOut: boolean;
9
13
  cancelled: boolean;
10
14
  truncated: boolean;
15
+ /** The framed stdout source crossed its capture limit. */
16
+ stdoutTruncated?: boolean;
17
+ /** Framed or native stderr crossed the shared stderr capture limit. */
18
+ stderrTruncated?: boolean;
11
19
  spawnError?: 'ENOENT' | 'START';
12
20
  spawnMessage?: string;
21
+ infrastructureError?: boolean;
22
+ stdoutSpool?: string;
23
+ stderrSpool?: string;
24
+ nativeStderrSpool?: string;
25
+ }
26
+ export type HostStreamMode = 'capture' | 'spool' | 'discard';
27
+ export interface HostOutputLimits {
28
+ stdoutLimit?: number;
29
+ stderrLimit?: number;
30
+ stdoutMode?: HostStreamMode;
31
+ stderrMode?: HostStreamMode;
32
+ stdoutSpoolPath?: string;
33
+ stderrSpoolPath?: string;
34
+ nativeStderrSpoolPath?: string;
13
35
  }
14
36
  export interface HostRequestEnv {
15
37
  [key: string]: string;
16
38
  }
17
39
  export declare function encodeHostRequest(id: string, script: string, env: HostRequestEnv, opts?: {
18
40
  v?: number;
19
- stdoutLimit?: number;
20
- stderrLimit?: number;
21
- }): string;
41
+ } & HostOutputLimits): string;
22
42
  export type HostV2Frame = {
23
43
  v: 2;
24
44
  type: 'ready';
@@ -41,6 +61,8 @@ export type HostV2Frame = {
41
61
  timedOut?: boolean;
42
62
  cancelled?: boolean;
43
63
  truncated?: boolean;
64
+ stdoutTruncated?: boolean;
65
+ stderrTruncated?: boolean;
44
66
  };
45
67
  export declare function parseHostLine(line: string): {
46
68
  v1Ready?: boolean;
@@ -55,31 +77,31 @@ export declare function decodeHostResponse(line: string): {
55
77
  ready?: boolean;
56
78
  };
57
79
  /**
58
- * One resident powershell.exe 5.1 process. Frames are UTF-8 JSON lines;
59
- * command stdout/stderr come back as base64 so PS 5.1's UTF-16LE pipe
60
- * encoding cannot scramble the payload.
80
+ * One resident selected PowerShell process. Frames are UTF-8 JSON lines;
81
+ * command stdout/stderr come back as base64 so Windows PowerShell 5.1's
82
+ * UTF-16LE pipe encoding cannot scramble the payload.
61
83
  */
62
84
  export declare class PowerShellHost {
63
85
  private readonly hostFile;
64
86
  private readonly envFn;
87
+ private readonly powerShell;
88
+ private readonly nativeSpoolWrite;
65
89
  private proc;
66
90
  private stdoutBuf;
67
91
  private queuedLines;
68
92
  private waiters;
69
93
  private stderrChunks;
94
+ private nativeCapture;
70
95
  private closeCode;
71
96
  private closeErr;
72
97
  private closed;
73
98
  private startLock;
74
99
  private invokeLock;
75
100
  protocol: 1 | 2;
76
- constructor(hostFile: string, envFn: () => NodeJS.ProcessEnv);
101
+ constructor(hostFile: string, envFn: () => NodeJS.ProcessEnv, powerShell?: PowerShellSelection, nativeSpoolWrite?: NativeSpoolWriter);
77
102
  /** Start the resident process and wait for the ready handshake (B1 prewarm). */
78
103
  ready(): Promise<HostInvokeResult | null>;
79
- invoke(script: string, env: HostRequestEnv, timeoutMs: number, signal?: AbortSignal, limits?: {
80
- stdoutLimit?: number;
81
- stderrLimit?: number;
82
- }): Promise<HostInvokeResult>;
104
+ invoke(script: string, env: HostRequestEnv, timeoutMs: number, signal?: AbortSignal, limits?: HostOutputLimits): Promise<HostInvokeResult>;
83
105
  drainNativeStderr(): Buffer;
84
106
  stop(): Promise<void>;
85
107
  private cancelledResult;
@@ -92,6 +114,13 @@ export declare class PowerShellHost {
92
114
  private nextReadyLine;
93
115
  private nextJsonLine;
94
116
  private collectV2;
95
- private waitNativeMarker;
117
+ private beginNativeCapture;
118
+ private appendNativePayload;
119
+ private onNativeStderr;
120
+ private cancelNativeCapture;
121
+ private closeNativeSpool;
122
+ private readUtf8Prefix;
123
+ private removeRequestSpools;
96
124
  private failWaiters;
97
125
  }
126
+ export {};