fauxnix-cli 1.0.0 → 2.1.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 CHANGED
@@ -1,3 +1,4 @@
1
+ import { appendFileSync, writeFileSync } from 'node:fs';
1
2
  import { parseCommand } from './parser.js';
2
3
  import { translateCommandList, EXECUTE_TRANSLATION } from './translator.js';
3
4
  import { FauxnixSession } from './executor.js';
@@ -28,13 +29,86 @@ async function runScript(session, script) {
28
29
  function bashQuote(word) {
29
30
  return "'" + word.replaceAll("'", `'\\''`) + "'";
30
31
  }
32
+ /**
33
+ * Claude Code's Bash tool wraps every command in private scaffolding,
34
+ * captured from a live session (2026-10-05; see docs/rfc-bash-facade.md):
35
+ *
36
+ * export TEMP='..' TMP='..' && shopt -u extglob 2>/dev/null || true &&
37
+ * { \builtin unalias -- 'unsetenv'; \builtin unset -f -- 'unsetenv'; }
38
+ * >/dev/null 2>&1 || true && eval 'PAYLOAD' < /dev/null &&
39
+ * pwd -P >| /c/.../claude-XXXX-cwd
40
+ *
41
+ * plus a shell-snapshot bootstrap built with heredocs and function
42
+ * definitions. The scaffolding is harness plumbing, not user bash: the
43
+ * facade applies the export prefix, executes the payload, and writes the
44
+ * cwd marker itself (only on success, matching bash's `&&` chain). Pattern
45
+ * drift falls through to plain translation and fails loud — visible in the
46
+ * FAUXNIX_FACADE_TRACE capture, never silently wrong.
47
+ */
48
+ const CC_SNAPSHOT_RE = /^SNAPSHOT_FILE='([^']+)'[\s\S]*RIPGREP_FUNC_END/;
49
+ const CC_COMMAND_RE = /^(?:source \S+ 2>\/dev\/null \|\| true &&\s*)?(export\s+[^\n]*?)\s*&&\s*shopt -u extglob[\s\S]*?&& eval '([\s\S]*?)' < \/dev\/null && pwd -P >\| (\S+)\s*$/;
50
+ function toPosixPath(p) {
51
+ const s = p.replaceAll('\\', '/');
52
+ const m = /^([A-Za-z]):(\/.*)?$/.exec(s);
53
+ return m ? '/' + m[1].toLowerCase() + (m[2] ?? '') : s;
54
+ }
55
+ function fromPosixPath(p) {
56
+ const m = /^\/([A-Za-z])(\/.*)?$/.exec(p);
57
+ return m ? m[1].toUpperCase() + ':' + (m[2] ?? '').replaceAll('/', '\\') : p;
58
+ }
59
+ /** Returns the exit code, or null when the script is not Claude Code scaffolding. */
60
+ async function tryClaudeCodeAdapter(session, script) {
61
+ const snap = CC_SNAPSHOT_RE.exec(script);
62
+ if (snap) {
63
+ try {
64
+ writeFileSync(fromPosixPath(snap[1]), '# Snapshot file\n# fauxnix facade: shell state lives in the facade session, not a snapshot script\n');
65
+ return 0;
66
+ }
67
+ catch (err) {
68
+ process.stderr.write(`fauxnix: facade: snapshot write failed: ${err.message}\n`);
69
+ return 1;
70
+ }
71
+ }
72
+ const cmd = CC_COMMAND_RE.exec(script);
73
+ if (!cmd)
74
+ return null;
75
+ const [, exportPart, payload, markerPosix] = cmd;
76
+ const env = await runScript(session, exportPart);
77
+ if (env.exitCode !== 0) {
78
+ if (env.stderr)
79
+ process.stderr.write(env.stderr);
80
+ return env.exitCode;
81
+ }
82
+ const r = await runScript(session, payload);
83
+ if (r.stdout)
84
+ process.stdout.write(r.stdout);
85
+ if (r.stderr)
86
+ process.stderr.write(r.stderr);
87
+ if (r.exitCode !== 0)
88
+ return r.exitCode; // bash: && chain stops, no marker
89
+ try {
90
+ writeFileSync(fromPosixPath(markerPosix), toPosixPath(session.cwd ?? process.cwd()) + '\n');
91
+ }
92
+ catch {
93
+ /* the marker is best-effort bookkeeping for the harness */
94
+ }
95
+ return 0;
96
+ }
31
97
  async function runOneShot(session, script, positionals) {
98
+ // bash -c '' is a successful no-op, distinct from a missing operand.
99
+ if (script === '')
100
+ return 0;
32
101
  // bash: trailing operands set $0, then $1.. via `set --`.
33
- process.env['FAUXNIX_ARG0'] = positionals[0] ?? 'bash';
102
+ session.env['FAUXNIX_ARG0'] = positionals[0] ?? 'bash';
34
103
  if (positionals.length > 1) {
35
104
  const r = await runScript(session, 'set -- ' + positionals.slice(1).map(bashQuote).join(' '));
36
- if (r.exitCode !== 0)
105
+ if (r.exitCode !== 0) {
106
+ if (r.stdout)
107
+ process.stdout.write(r.stdout);
108
+ if (r.stderr)
109
+ process.stderr.write(r.stderr);
37
110
  return r.exitCode;
111
+ }
38
112
  }
39
113
  const r = await runScript(session, script);
40
114
  if (r.stdout)
@@ -43,6 +117,18 @@ async function runOneShot(session, script, positionals) {
43
117
  process.stderr.write(r.stderr);
44
118
  return r.exitCode;
45
119
  }
120
+ /** Diagnostic trace: set FAUXNIX_FACADE_TRACE to append raw argv/stdin traffic. */
121
+ function trace(kind, data) {
122
+ const file = process.env['FAUXNIX_FACADE_TRACE'];
123
+ if (!file)
124
+ return;
125
+ try {
126
+ appendFileSync(file, `[${kind}] ${JSON.stringify(data)}\n`, 'utf8');
127
+ }
128
+ catch {
129
+ /* diagnostics must never break the facade */
130
+ }
131
+ }
46
132
  async function runMarkerSession(session) {
47
133
  await session.prewarm();
48
134
  return new Promise((resolve) => {
@@ -50,6 +136,7 @@ async function runMarkerSession(session) {
50
136
  let queue = Promise.resolve();
51
137
  process.stdin.setEncoding('utf8');
52
138
  process.stdin.on('data', (chunk) => {
139
+ trace('stdin', chunk);
53
140
  buf += chunk;
54
141
  let m;
55
142
  while ((m = MARKER_RE.exec(buf))) {
@@ -66,7 +153,8 @@ async function runMarkerSession(session) {
66
153
  process.stdout.write(`<bash-exit>${r.exitCode}</bash-exit>\n`);
67
154
  }
68
155
  catch (err) {
69
- process.stderr.write(`fauxnix: facade: ${err.message}\n`);
156
+ const msg = err instanceof Error ? err.message : String(err);
157
+ process.stderr.write(`fauxnix: facade: ${msg}\n`);
70
158
  process.stdout.write('<bash-exit>127</bash-exit>\n');
71
159
  }
72
160
  });
@@ -77,26 +165,67 @@ async function runMarkerSession(session) {
77
165
  });
78
166
  });
79
167
  }
168
+ /**
169
+ * bash argv contract: options may combine and may appear between -c and the
170
+ * command string. Observed from Claude Code: `bash -c env`, `bash -lc '...'`,
171
+ * `bash -c -l '<script>'`. Returns null when argv is not a -c invocation.
172
+ */
173
+ function parseDashC(argv) {
174
+ let wantScript = false;
175
+ let script;
176
+ const positionals = [];
177
+ for (let i = 0; i < argv.length; i++) {
178
+ const token = argv[i];
179
+ if (token === '--') {
180
+ for (let j = i + 1; j < argv.length; j++)
181
+ positionals.push(argv[j]);
182
+ break;
183
+ }
184
+ if (token.startsWith('-') && token.length > 1 && script === undefined) {
185
+ for (const ch of token.slice(1)) {
186
+ if (ch === 'c' || ch === 'e')
187
+ wantScript = true;
188
+ else if (ch !== 'l' && ch !== 'i' && ch !== 's' && ch !== 'r')
189
+ return null;
190
+ }
191
+ continue;
192
+ }
193
+ if (wantScript && script === undefined) {
194
+ script = token;
195
+ continue;
196
+ }
197
+ positionals.push(token);
198
+ }
199
+ if (!wantScript)
200
+ return null;
201
+ return { script, positionals };
202
+ }
80
203
  export async function runFacade(argv) {
204
+ trace('argv', argv.join(' '));
81
205
  const session = new FauxnixSession();
82
206
  try {
83
207
  if (argv[0] === '--version') {
84
208
  process.stdout.write(VERSION_LINE);
85
209
  return 0;
86
210
  }
87
- if (argv[0] === '-c' || argv[0] === '-e') {
88
- const [script, ...positionals] = argv.slice(1);
89
- if (!script) {
211
+ const dashC = parseDashC(argv);
212
+ if (dashC) {
213
+ if (dashC.script === undefined) {
90
214
  process.stderr.write('bash: -c: option requires an argument\n');
91
215
  return 2;
92
216
  }
93
- return await runOneShot(session, script, positionals);
217
+ if (dashC.positionals.length === 0) {
218
+ const adapted = await tryClaudeCodeAdapter(session, dashC.script);
219
+ if (adapted !== null)
220
+ return adapted;
221
+ }
222
+ return await runOneShot(session, dashC.script, dashC.positionals);
94
223
  }
95
224
  return await runMarkerSession(session);
96
225
  }
97
226
  catch (err) {
98
227
  // bash -c exits 2 on syntax errors; 127 covers the not-found family
99
- const msg = err.message ?? String(err);
228
+ const msg = err instanceof Error ? err.message : String(err);
100
229
  process.stderr.write('bash: -c: ' + msg + '\n');
101
230
  return msg.includes('not found') ? 127 : 2;
102
231
  }
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 };