fauxnix-cli 2.1.1 → 2.2.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,7 +1,7 @@
1
1
  import { appendFileSync, writeFileSync } from 'node:fs';
2
2
  import { parseCommand } from './parser.js';
3
3
  import { translateCommandList, EXECUTE_TRANSLATION } from './translator.js';
4
- import { FauxnixSession } from './executor.js';
4
+ import { FauxnixSession, installSessionExitCleanup } from './executor.js';
5
5
  import { packageVersion } from './version.js';
6
6
  /**
7
7
  * Experimental native-shell facade (RFC: docs/rfc-bash-facade.md).
@@ -202,9 +202,13 @@ function parseDashC(argv) {
202
202
  }
203
203
  export async function runFacade(argv) {
204
204
  trace('argv', argv.join(' '));
205
+ installSessionExitCleanup();
205
206
  const session = new FauxnixSession();
206
207
  try {
207
- if (argv[0] === '--version') {
208
+ // GNU bash answers --version wherever it appears among the options
209
+ // (`bash -l --version`), not only as argv[0] (#259). Exact element match:
210
+ // a script operand containing the text is data, not an option.
211
+ if (argv.some((a) => a === '--version')) {
208
212
  process.stdout.write(VERSION_LINE);
209
213
  return 0;
210
214
  }
package/dist/install.js CHANGED
@@ -1,11 +1,9 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
2
  import { homedir } from 'node:os';
3
3
  import { dirname, join } from 'node:path';
4
- import { claudeUserConfigPath, codexConfigPath, fauxnixServerNames, hasCodexFauxnix, hasOpenCodeFauxnix, isServerMap, openCodeConfigPath, serverMapHasFauxnix, } from './doctor.js';
5
- import { resolveQwenLaunchTuple, sameQwenLaunchTuple } from './qwen-launch.js';
4
+ import { claudeUserConfigPath, codexConfigPath, fauxnixServerNames, hasCodexFauxnix, isServerMap, openCodeConfigPath, } from './doctor.js';
5
+ import { isLegacyFauxnixCommand, resolveMcpLaunchTuple, sameMcpLaunchTuple, } from './mcp-launch.js';
6
6
  export const INSTALL_FLAGS = ['claude', 'codex', 'opencode', 'kimi', 'qwen'];
7
- const STDIO = { command: 'fauxnix', args: ['mcp'] };
8
- const OPENCODE_STDIO = { type: 'local', command: ['fauxnix', 'mcp'] };
9
7
  export function kimiConfigPath(home, env) {
10
8
  const root = env.KIMI_CODE_HOME?.trim() || join(home, '.kimi-code');
11
9
  return join(root, 'mcp.json');
@@ -19,6 +17,12 @@ export function runInstall(argv, opts = {}) {
19
17
  return { lines: installUsageLines(), ok: true };
20
18
  if (parsed.error)
21
19
  return { lines: [parsed.error, ...installUsageLines()], ok: false };
20
+ // Every harness config carries the spawn-safe absolute launcher (#252):
21
+ // resolve it once; a failure to locate Node or the built entry fails the
22
+ // whole run rather than writing a config that cannot start.
23
+ const launch = resolveMcpLaunchTuple();
24
+ if (!launch.ok)
25
+ return { lines: [launch.reason], ok: false };
22
26
  const ctx = {
23
27
  home: opts.home ?? homedir(),
24
28
  env: opts.env ?? process.env,
@@ -26,7 +30,7 @@ export function runInstall(argv, opts = {}) {
26
30
  const lines = [];
27
31
  let ok = true;
28
32
  for (const name of parsed.harnesses) {
29
- const one = installHarness(name, ctx);
33
+ const one = installHarness(name, ctx, launch.value);
30
34
  lines.push(one.line);
31
35
  if (!one.ok)
32
36
  ok = false;
@@ -61,24 +65,21 @@ function isHarness(s) {
61
65
  function installUsageLines() {
62
66
  return ['Usage:', ' fauxnix install --claude|--codex|--opencode|--kimi|--qwen'];
63
67
  }
64
- function installHarness(name, ctx) {
68
+ function installHarness(name, ctx, launch) {
65
69
  switch (name) {
66
70
  case 'claude':
67
- return patchMcpServers(claudeUserConfigPath(ctx.home, ctx.env), 'claude');
71
+ return patchMcpServers(claudeUserConfigPath(ctx.home, ctx.env), 'claude', launch);
68
72
  case 'codex':
69
- return patchCodex(codexConfigPath(ctx.home, ctx.env));
73
+ return patchCodex(codexConfigPath(ctx.home, ctx.env), launch);
70
74
  case 'opencode':
71
- return patchOpenCode(openCodeConfigPath(ctx.home, ctx.env));
75
+ return patchOpenCode(openCodeConfigPath(ctx.home, ctx.env), launch);
72
76
  case 'kimi':
73
- return patchMcpServers(kimiConfigPath(ctx.home, ctx.env), 'kimi');
77
+ return patchMcpServers(kimiConfigPath(ctx.home, ctx.env), 'kimi', launch);
74
78
  case 'qwen':
75
- return patchQwen(qwenConfigPath(ctx.home, ctx.env));
79
+ return patchQwen(qwenConfigPath(ctx.home, ctx.env), launch);
76
80
  }
77
81
  }
78
- function patchQwen(path) {
79
- const launch = resolveQwenLaunchTuple();
80
- if (!launch.ok)
81
- return { ok: false, line: `qwen: ${launch.reason} — not modified` };
82
+ function patchQwen(path, launch) {
82
83
  const read = readJsonObject(path);
83
84
  if (read.state === 'invalid') {
84
85
  return { ok: false, line: `qwen: ${path} is ${read.reason} — not modified` };
@@ -105,65 +106,80 @@ function patchQwen(path) {
105
106
  line: `qwen: ${path} mcpServers.fauxnix is not an object — not modified`,
106
107
  };
107
108
  }
108
- if (sameQwenLaunchTuple(current, launch.value)) {
109
+ if (sameMcpLaunchTuple(current, launch)) {
109
110
  return { ok: true, line: `qwen: already configured with an absolute launcher (${path})` };
110
111
  }
112
+ if (current != null && !isLegacyFauxnixCommand(current)) {
113
+ // A hand-written launcher the user chose deliberately; leave it alone.
114
+ return { ok: true, line: `qwen: already configured (${path})` };
115
+ }
111
116
  servers.fauxnix = {
112
117
  ...(isServerMap(current) ? current : {}),
113
- command: launch.value.command,
114
- args: [...launch.value.args],
118
+ command: launch.command,
119
+ args: [...launch.args],
115
120
  };
116
- return writeJson(path, data, 'qwen', existed, current == null ? 'added mcpServers.fauxnix' : 'updated mcpServers.fauxnix launcher');
121
+ return writeJson(path, data, 'qwen', existed, current == null ? 'added mcpServers.fauxnix' : 'upgraded mcpServers.fauxnix to the absolute launcher');
117
122
  }
118
- function patchMcpServers(path, harness) {
123
+ function patchMcpServers(path, harness, launch) {
119
124
  const read = readJsonObject(path);
120
125
  if (read.state === 'invalid') {
121
126
  return { ok: false, line: `${harness}: ${path} is ${read.reason} — not modified` };
122
127
  }
123
128
  const existed = read.state !== 'missing';
124
129
  const data = read.state === 'ok' ? read.data : {};
125
- if (serverMapHasFauxnix(data.mcpServers)) {
126
- return { ok: true, line: `${harness}: already configured (${path})` };
127
- }
128
130
  if (data.mcpServers != null && !isServerMap(data.mcpServers)) {
129
131
  return { ok: false, line: `${harness}: ${path} mcpServers is not an object — not modified` };
130
132
  }
131
133
  if (!isServerMap(data.mcpServers))
132
134
  data.mcpServers = {};
133
- data.mcpServers.fauxnix = {
134
- command: STDIO.command,
135
- args: [...STDIO.args],
135
+ const servers = data.mcpServers;
136
+ const current = servers.fauxnix;
137
+ if (current != null && !isServerMap(current)) {
138
+ return { ok: false, line: `${harness}: ${path} mcpServers.fauxnix is not an object — not modified` };
139
+ }
140
+ if (sameMcpLaunchTuple(current, launch)) {
141
+ return { ok: true, line: `${harness}: already configured with an absolute launcher (${path})` };
142
+ }
143
+ if (current != null && !isLegacyFauxnixCommand(current)) {
144
+ return { ok: true, line: `${harness}: already configured (${path})` };
145
+ }
146
+ // New entry, or the pre-#252 `command: "fauxnix"` form that direct-spawn
147
+ // MCP clients cannot execute on Windows — both get the absolute launcher.
148
+ servers.fauxnix = {
149
+ ...(isServerMap(current) ? current : {}),
150
+ command: launch.command,
151
+ args: [...launch.args],
136
152
  };
137
- return writeJson(path, data, harness, existed, 'added mcpServers.fauxnix');
153
+ return writeJson(path, data, harness, existed, current == null ? 'added mcpServers.fauxnix' : 'upgraded mcpServers.fauxnix to the spawn-safe absolute launcher (#252)');
138
154
  }
139
- function patchOpenCode(path) {
155
+ function patchOpenCode(path, launch) {
140
156
  const read = readJsonObject(path);
141
157
  if (read.state === 'invalid') {
142
158
  return { ok: false, line: `opencode: ${path} is ${read.reason} — not modified` };
143
159
  }
144
160
  const existed = read.state !== 'missing';
145
161
  const data = read.state === 'ok' ? read.data : {};
146
- if (hasOpenCodeFauxnix(data)) {
147
- return { ok: true, line: `opencode: already configured (${path})` };
148
- }
149
162
  if (data.mcp != null && !isServerMap(data.mcp)) {
150
163
  return { ok: false, line: `opencode: ${path} mcp is not an object — not modified` };
151
164
  }
152
165
  if (!isServerMap(data.mcp))
153
166
  data.mcp = {};
154
167
  const mcp = data.mcp;
155
- const payload = { type: OPENCODE_STDIO.type, command: [...OPENCODE_STDIO.command] };
156
- if (isServerMap(mcp.servers)) {
157
- mcp.servers.fauxnix = payload;
158
- return writeJson(path, data, 'opencode', existed, 'added mcp.servers.fauxnix');
168
+ const payload = { type: 'local', command: [launch.command, ...launch.args] };
169
+ const slot = isServerMap(mcp.servers) ? mcp.servers : mcp;
170
+ const where = isServerMap(mcp.servers) ? 'mcp.servers.fauxnix' : 'mcp.fauxnix';
171
+ const current = slot.fauxnix;
172
+ if (current != null && !isLegacyFauxnixCommand(current)) {
173
+ return { ok: true, line: `opencode: already configured (${path})` };
159
174
  }
160
- mcp.fauxnix = payload;
161
- return writeJson(path, data, 'opencode', existed, 'added mcp.fauxnix');
175
+ const change = current == null ? `added ${where}` : `upgraded ${where} to the spawn-safe absolute launcher (#252)`;
176
+ slot.fauxnix = payload;
177
+ return writeJson(path, data, 'opencode', existed, change);
162
178
  }
163
- function patchCodex(path) {
179
+ function patchCodex(path, launch) {
164
180
  const existed = existsSync(path);
165
181
  if (!existed) {
166
- const written = writeText(path, tomlTable('\n'));
182
+ const written = writeText(path, tomlTable('\n', launch));
167
183
  if (!written.ok)
168
184
  return { ok: false, line: `codex: failed to write ${path}: ${written.error}` };
169
185
  return { ok: true, line: `codex: created ${path}` };
@@ -173,11 +189,18 @@ function patchCodex(path) {
173
189
  return { ok: false, line: `codex: ${path} is unreadable — not modified` };
174
190
  }
175
191
  if (hasCodexFauxnix(stripBom(text))) {
176
- return { ok: true, line: `codex: already configured (${path})` };
192
+ const upgraded = upgradeCodexLegacyTable(text, launch);
193
+ if (upgraded === undefined) {
194
+ return { ok: true, line: `codex: already configured (${path})` };
195
+ }
196
+ const written = writeText(path, upgraded);
197
+ if (!written.ok)
198
+ return { ok: false, line: `codex: failed to write ${path}: ${written.error}` };
199
+ return { ok: true, line: `codex: patched ${path} (upgraded mcp_servers.fauxnix to the spawn-safe absolute launcher (#252))` };
177
200
  }
178
201
  const nl = text.includes('\r\n') ? '\r\n' : '\n';
179
202
  if (stripBom(text).trim() === '') {
180
- const written = writeText(path, tomlTable(nl));
203
+ const written = writeText(path, tomlTable(nl, launch));
181
204
  if (!written.ok)
182
205
  return { ok: false, line: `codex: failed to write ${path}: ${written.error}` };
183
206
  return { ok: true, line: `codex: patched ${path} (appended [mcp_servers.fauxnix])` };
@@ -187,13 +210,33 @@ function patchCodex(path) {
187
210
  body += nl;
188
211
  if (!body.endsWith(nl + nl))
189
212
  body += nl;
190
- const written = writeText(path, body + tomlTable(nl));
213
+ const written = writeText(path, body + tomlTable(nl, launch));
191
214
  if (!written.ok)
192
215
  return { ok: false, line: `codex: failed to write ${path}: ${written.error}` };
193
216
  return { ok: true, line: `codex: patched ${path} (appended [mcp_servers.fauxnix])` };
194
217
  }
195
- function tomlTable(nl) {
196
- return `[mcp_servers.fauxnix]${nl}command = "fauxnix"${nl}args = ["mcp"]${nl}`;
218
+ /**
219
+ * TOML literal strings (single quotes) keep Windows backslash paths intact
220
+ * without escape processing.
221
+ */
222
+ function tomlTable(nl, launch) {
223
+ return (`[mcp_servers.fauxnix]${nl}` +
224
+ `command = '${launch.command.replace(/'/g, "''")}'${nl}` +
225
+ `args = ['${launch.args[0].replace(/'/g, "''")}', 'mcp']${nl}`);
226
+ }
227
+ /**
228
+ * Rewrite only the table our own installer wrote pre-#252 — the exact
229
+ * `command = "fauxnix"` + `args = ["mcp"]` spelling inside the fauxnix
230
+ * table. Anything else (user-edited, differently spelled) is left alone.
231
+ */
232
+ function upgradeCodexLegacyTable(text, launch) {
233
+ const re = /(\[mcp_servers\.fauxnix\][^\[]*?)^[ \t]*command[ \t]*=[ \t]*"fauxnix"[ \t]*$[\s\S]*?^[ \t]*args[ \t]*=[ \t]*\["mcp"\][ \t]*$/m;
234
+ if (!re.test(text))
235
+ return undefined;
236
+ const nl = text.includes('\r\n') ? '\r\n' : '\n';
237
+ return text.replace(re, (_m, head) => head +
238
+ `command = '${launch.command.replace(/'/g, "''")}'${nl}` +
239
+ `args = ['${launch.args[0].replace(/'/g, "''")}', 'mcp']`);
197
240
  }
198
241
  function writeJson(path, data, harness, existed, change) {
199
242
  const written = writeText(path, JSON.stringify(data, null, 2) + '\n');
@@ -0,0 +1,22 @@
1
+ export type McpLaunchTuple = {
2
+ command: string;
3
+ args: string[];
4
+ };
5
+ /**
6
+ * Spawn-safe launch form for every harness config (#252): the absolute Node
7
+ * executable plus this installation's absolute built entry. A bare
8
+ * `fauxnix` command is an extension-less npm shim on Windows — MCP clients
9
+ * that spawn the server directly via CreateProcess cannot execute it. The
10
+ * absolute tuple is immune to PATH and shim-resolution differences on every
11
+ * platform.
12
+ */
13
+ export declare function resolveMcpLaunchTuple(): {
14
+ ok: true;
15
+ value: McpLaunchTuple;
16
+ } | {
17
+ ok: false;
18
+ reason: string;
19
+ };
20
+ export declare function sameMcpLaunchTuple(value: unknown, expected: McpLaunchTuple): boolean;
21
+ /** The pre-#252 config form: `{ command: "fauxnix", args: ["mcp"] }`. */
22
+ export declare function isLegacyFauxnixCommand(value: unknown): boolean;
@@ -0,0 +1,44 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { isAbsolute } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ /**
5
+ * Spawn-safe launch form for every harness config (#252): the absolute Node
6
+ * executable plus this installation's absolute built entry. A bare
7
+ * `fauxnix` command is an extension-less npm shim on Windows — MCP clients
8
+ * that spawn the server directly via CreateProcess cannot execute it. The
9
+ * absolute tuple is immune to PATH and shim-resolution differences on every
10
+ * platform.
11
+ */
12
+ export function resolveMcpLaunchTuple() {
13
+ const command = process.execPath;
14
+ const entry = fileURLToPath(new URL('../dist/index.js', import.meta.url));
15
+ if (!isAbsolute(command) || !existsSync(command)) {
16
+ return {
17
+ ok: false,
18
+ reason: 'cannot locate the Node.js executable; reinstall Node.js, then retry `fauxnix install`',
19
+ };
20
+ }
21
+ if (!isAbsolute(entry) || !existsSync(entry)) {
22
+ return {
23
+ ok: false,
24
+ reason: `cannot locate the built fauxnix entry at ${entry}; run \`npm run build\` or reinstall fauxnix-cli, then retry \`fauxnix install\``,
25
+ };
26
+ }
27
+ return { ok: true, value: { command, args: [entry, 'mcp'] } };
28
+ }
29
+ export function sameMcpLaunchTuple(value, expected) {
30
+ if (!value || typeof value !== 'object' || Array.isArray(value))
31
+ return false;
32
+ const rec = value;
33
+ return (rec.command === expected.command &&
34
+ Array.isArray(rec.args) &&
35
+ rec.args.length === expected.args.length &&
36
+ rec.args.every((part, index) => part === expected.args[index]));
37
+ }
38
+ /** The pre-#252 config form: `{ command: "fauxnix", args: ["mcp"] }`. */
39
+ export function isLegacyFauxnixCommand(value) {
40
+ if (!value || typeof value !== 'object' || Array.isArray(value))
41
+ return false;
42
+ const rec = value;
43
+ return rec.command === 'fauxnix' || (Array.isArray(rec.command) && rec.command[0] === 'fauxnix');
44
+ }
package/dist/mcp.js CHANGED
@@ -251,8 +251,16 @@ export async function startMcpServer() {
251
251
  const onShutdown = () => {
252
252
  void shutdown().catch(() => undefined);
253
253
  };
254
+ // Register before the cold-start prewarm: a signal during prewarm must
255
+ // still dispose the host and its private state directory (#256).
256
+ process.on('SIGINT', onShutdown);
257
+ process.on('SIGTERM', onShutdown);
254
258
  try {
255
259
  await session.prewarm();
260
+ if (shutdownPromise) {
261
+ await shutdownPromise;
262
+ return;
263
+ }
256
264
  server.tool(TOOL_NAME, TOOL_DESCRIPTION, {
257
265
  command: z.string().describe('The bash-style command line to run'),
258
266
  timeout_ms: z
@@ -377,8 +385,6 @@ export async function startMcpServer() {
377
385
  const transport = new StdioServerTransport();
378
386
  input.on('end', onShutdown);
379
387
  input.on('close', onShutdown);
380
- process.on('SIGINT', onShutdown);
381
- process.on('SIGTERM', onShutdown);
382
388
  transport.onclose = onShutdown;
383
389
  await server.connect(transport);
384
390
  }
package/dist/ps-host.d.ts CHANGED
@@ -103,6 +103,11 @@ export declare class PowerShellHost {
103
103
  ready(): Promise<HostInvokeResult | null>;
104
104
  invoke(script: string, env: HostRequestEnv, timeoutMs: number, signal?: AbortSignal, limits?: HostOutputLimits): Promise<HostInvokeResult>;
105
105
  drainNativeStderr(): Buffer;
106
+ /**
107
+ * Synchronous best-effort termination for process-exit paths, where the
108
+ * async stop() cannot be awaited. Fails pending waiters like stop().
109
+ */
110
+ killSync(): void;
106
111
  stop(): Promise<void>;
107
112
  private cancelledResult;
108
113
  private invokeSerial;
package/dist/ps-host.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { randomBytes } from 'node:crypto';
1
2
  import { spawn } from 'node:child_process';
2
3
  import { closeSync, openSync, readSync, rmSync, statSync, writeFileSync, writeSync, } from 'node:fs';
3
4
  import { hostBootstrapScript } from './translator.js';
@@ -109,6 +110,31 @@ export class PowerShellHost {
109
110
  this.stderrChunks = [];
110
111
  return b;
111
112
  }
113
+ /**
114
+ * Synchronous best-effort termination for process-exit paths, where the
115
+ * async stop() cannot be awaited. Fails pending waiters like stop().
116
+ */
117
+ killSync() {
118
+ this.cancelNativeCapture();
119
+ const proc = this.proc;
120
+ this.proc = null;
121
+ this.closed = true;
122
+ this.failWaiters(new Error('fauxnix: PowerShell host stopped'));
123
+ if (!proc)
124
+ return;
125
+ try {
126
+ proc.stdin?.destroy();
127
+ }
128
+ catch {
129
+ /* ignore */
130
+ }
131
+ try {
132
+ proc.kill();
133
+ }
134
+ catch {
135
+ /* ignore */
136
+ }
137
+ }
112
138
  async stop() {
113
139
  this.cancelNativeCapture();
114
140
  const proc = this.proc;
@@ -186,7 +212,7 @@ export class PowerShellHost {
186
212
  }
187
213
  if (started)
188
214
  return { ...started, cancelled: false, truncated: false };
189
- const id = 'f' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
215
+ const id = 'f' + Date.now().toString(36) + randomBytes(6).toString('hex');
190
216
  const resolvedLimits = { ...limits };
191
217
  if (resolvedLimits.stdoutMode === 'spool') {
192
218
  resolvedLimits.stdoutSpoolPath = this.hostFile + '.' + id + '.stdout';
@@ -1,12 +1,5 @@
1
- export type QwenLaunchTuple = {
2
- command: string;
3
- args: string[];
4
- };
5
- export declare function resolveQwenLaunchTuple(): {
6
- ok: true;
7
- value: QwenLaunchTuple;
8
- } | {
9
- ok: false;
10
- reason: string;
11
- };
12
- export declare function sameQwenLaunchTuple(value: unknown, expected: QwenLaunchTuple): boolean;
1
+ import type { McpLaunchTuple } from './mcp-launch.js';
2
+ import { resolveMcpLaunchTuple, sameMcpLaunchTuple } from './mcp-launch.js';
3
+ export type QwenLaunchTuple = McpLaunchTuple;
4
+ export declare const resolveQwenLaunchTuple: typeof resolveMcpLaunchTuple;
5
+ export declare const sameQwenLaunchTuple: typeof sameMcpLaunchTuple;
@@ -1,29 +1,5 @@
1
- import { existsSync } from 'node:fs';
2
- import { isAbsolute } from 'node:path';
3
- import { fileURLToPath } from 'node:url';
4
- export function resolveQwenLaunchTuple() {
5
- const command = process.execPath;
6
- const entry = fileURLToPath(new URL('../dist/index.js', import.meta.url));
7
- if (!isAbsolute(command) || !existsSync(command)) {
8
- return {
9
- ok: false,
10
- reason: 'cannot locate the Node.js executable; reinstall Node.js, then retry `fauxnix install --qwen`',
11
- };
12
- }
13
- if (!isAbsolute(entry) || !existsSync(entry)) {
14
- return {
15
- ok: false,
16
- reason: `cannot locate the built fauxnix entry at ${entry}; run \`npm run build\` or reinstall fauxnix-cli, then retry \`fauxnix install --qwen\``,
17
- };
18
- }
19
- return { ok: true, value: { command, args: [entry, 'mcp'] } };
20
- }
21
- export function sameQwenLaunchTuple(value, expected) {
22
- if (!value || typeof value !== 'object' || Array.isArray(value))
23
- return false;
24
- const rec = value;
25
- return (rec.command === expected.command &&
26
- Array.isArray(rec.args) &&
27
- rec.args.length === expected.args.length &&
28
- rec.args.every((part, index) => part === expected.args[index]));
29
- }
1
+ import { resolveMcpLaunchTuple, sameMcpLaunchTuple } from './mcp-launch.js';
2
+ // The Qwen launcher pioneered the absolute spawn-safe tuple; every harness
3
+ // now uses it (#252). These aliases keep the historical import surface.
4
+ export const resolveQwenLaunchTuple = resolveMcpLaunchTuple;
5
+ export const sameQwenLaunchTuple = sameMcpLaunchTuple;
@@ -67,6 +67,15 @@ export declare function literalOfWord(w: Word): string | null;
67
67
  * Literal paths get POSIX-ish normalization (/dev/null, /tmp, /d/...).
68
68
  */
69
69
  export declare function operandExpr(w: Word): string;
70
+ /**
71
+ * Operand expression for handlers whose runtime glob step is `fx-glob`
72
+ * (#255 quote-aware globbing): bash globs a word only where glob characters
73
+ * sat UNQUOTED — quoted parts and backslash-escaped characters are literal
74
+ * even when a variable expands to something containing metas, while unquoted
75
+ * expansions stay glob-active. `fx-glob` unescapes the pattern when no file
76
+ * matches, so unmatched literals keep their shell spelling.
77
+ */
78
+ export declare function globOperandExpr(w: Word): string;
70
79
  /**
71
80
  * `${name[@]}` / `"pre${name[@]}post"` — one argv per element.
72
81
  * Unquoted `${name[*]}` also splats (bash); quoted `"${name[*]}"` stays one join.
@@ -277,7 +277,11 @@ export function varExpr(name, index, param, length = false, extra) {
277
277
  }
278
278
  switch (name) {
279
279
  case 'HOME':
280
- return '$HOME';
280
+ // Session-scoped like every other variable (#255): assignments write
281
+ // $env:HOME + SETVALS, `env -u`/unset track UNSETVARS — fx-scalar0 is
282
+ // the one resolver that honors all three. `$HOME` (the PowerShell
283
+ // automatic) would always answer with the real profile.
284
+ return "(fx-scalar0 'HOME')";
281
285
  case 'PWD':
282
286
  return 'fx-posix([string]$PWD.Path)';
283
287
  case 'USER':
@@ -504,6 +508,60 @@ export function operandExpr(w) {
504
508
  return pathExpr(normalizeLiteralPath(lit));
505
509
  return exprOfWord(w);
506
510
  }
511
+ /**
512
+ * Wildcard-escape characters that must reach `Get-Item -Path` literally
513
+ * (PowerShell's escape is a backtick before `*`, `?` or `[`).
514
+ */
515
+ function wcEscapeLiteral(s) {
516
+ return s.replace(/[*?[]/g, '`$&');
517
+ }
518
+ /**
519
+ * Operand expression for handlers whose runtime glob step is `fx-glob`
520
+ * (#255 quote-aware globbing): bash globs a word only where glob characters
521
+ * sat UNQUOTED — quoted parts and backslash-escaped characters are literal
522
+ * even when a variable expands to something containing metas, while unquoted
523
+ * expansions stay glob-active. `fx-glob` unescapes the pattern when no file
524
+ * matches, so unmatched literals keep their shell spelling.
525
+ */
526
+ export function globOperandExpr(w) {
527
+ const lit = literalOfWord(w);
528
+ // Meta-free literal words keep the ordinary operand path (incl. /tmp, /d/
529
+ // normalization). Anything containing glob characters goes through the
530
+ // quoting-aware walk: only UNQUOTED metas stay glob-active.
531
+ if (lit !== null && !/[*?[]/.test(lit))
532
+ return pathExpr(normalizeLiteralPath(lit));
533
+ const chunks = [];
534
+ const mergeable = (s) => typeof s === 'string' && s.startsWith("'") && s.endsWith("'") && s.length >= 2;
535
+ const pushChunk = (s) => {
536
+ const prev = chunks.length ? chunks[chunks.length - 1] : undefined;
537
+ if (mergeable(prev) && mergeable(s)) {
538
+ // fold adjacent string literals: ('a' + '*' + 'b') → ('a*b'); psStr has
539
+ // already doubled any embedded quotes, so plain concatenation is safe.
540
+ chunks[chunks.length - 1] = "'" + prev.slice(1, -1) + s.slice(1, -1) + "'";
541
+ return;
542
+ }
543
+ chunks.push(s);
544
+ };
545
+ const walk = (parts, quoted) => {
546
+ for (const p of parts) {
547
+ if (p.kind === 'DoubleQuoted') {
548
+ walk(p.parts, true);
549
+ continue;
550
+ }
551
+ if (p.kind === 'Text' || p.kind === 'SingleQuoted') {
552
+ const literal = quoted || p.kind === 'SingleQuoted' || (p.kind === 'Text' && p.escaped === true);
553
+ pushChunk(psStr(literal ? wcEscapeLiteral(p.text) : p.text));
554
+ continue;
555
+ }
556
+ const expr = exprOfWord([p]);
557
+ chunks.push(quoted ? '[WildcardPattern]::Escape([string](' + expr + '))' : '([string](' + expr + '))');
558
+ }
559
+ };
560
+ walk(w, false);
561
+ if (chunks.length === 1)
562
+ return chunks[0];
563
+ return '(' + chunks.join(' + ') + ')';
564
+ }
507
565
  /** Flatten quotes but remember whether a part sat inside `"..."`. */
508
566
  function wordPartsForSplat(w) {
509
567
  const out = [];
@@ -1638,7 +1696,9 @@ export function wrapScript(body, opts = {}) {
1638
1696
  ' if ($fx_eq -lt 1) { continue }',
1639
1697
  ' if ($fx_pair.Substring(0, $fx_eq) -ceq $n) { return (fx-svdec $fx_pair.Substring($fx_eq + 1)) }',
1640
1698
  ' }',
1641
- " if ($n -ceq 'HOME') { return [string]$HOME }",
1699
+ // Inherited HOME (Git Bash hosts) first; bare-Windows fallback is the
1700
+ // profile, like a bash login shell seeding HOME from passwd (#255).
1701
+ " if ($n -ceq 'HOME') { return $(if ($env:HOME) { [string]$env:HOME } else { [string]$HOME }) }",
1642
1702
  " if ($n -ceq 'PWD') { return fx-posix([string]$PWD.Path) }",
1643
1703
  " if ($n -ceq 'USER' -or $n -ceq 'LOGNAME') { return [string]$env:USERNAME }",
1644
1704
  " if ($n -ceq 'PATH') { return [string]$env:PATH }",
@@ -2174,6 +2234,14 @@ function fx-capture-bytes($stream) {
2174
2234
  if ($stream -is [System.IO.MemoryStream]) { return $stream.ToArray() }
2175
2235
  return (New-Object byte[] 0)
2176
2236
  }
2237
+ # Captured at startup, from the script's own location (never from the
2238
+ # user-mutable environment).
2239
+ $fx_sd = $null
2240
+ if ($PSCommandPath) {
2241
+ $fx_sd = [IO.Path]::GetDirectoryName($PSCommandPath)
2242
+ if ([IO.Path]::GetFileName($fx_sd) -cnotmatch '^fauxnix-[0-9]+-[0-9a-f]{24}$') { $fx_sd = $null }
2243
+ }
2244
+ Set-Variable -Name fx_hostStateDir -Value $fx_sd -Option Constant
2177
2245
  while ($true) {
2178
2246
  $fx_line = $fx_reader.ReadLine()
2179
2247
  if ($null -eq $fx_line) { break }
@@ -2286,4 +2354,7 @@ while ($true) {
2286
2354
  $fx_proto.WriteLine($fx_json)
2287
2355
  }
2288
2356
  }
2357
+ # stdin EOF: the owner is gone or disposed us. Remove our private state
2358
+ # directory (#256) - only if it is a genuine per-session directory.
2359
+ if ($fx_hostStateDir) { Remove-Item -LiteralPath $fx_hostStateDir -Recurse -Force -ErrorAction SilentlyContinue }
2289
2360
  `.trim();