@pixelbyte-software/pixcode 1.35.0 → 1.35.1

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.
Files changed (150) hide show
  1. package/LICENSE +718 -718
  2. package/README.de.md +248 -248
  3. package/README.ja.md +240 -240
  4. package/README.ko.md +240 -240
  5. package/README.md +303 -303
  6. package/README.ru.md +248 -248
  7. package/README.tr.md +250 -250
  8. package/README.zh-CN.md +240 -240
  9. package/dist/api-docs.html +548 -548
  10. package/dist/assets/{index-Djuh0wHV.js → index-CBdsvGSR.js} +133 -133
  11. package/dist/clear-cache.html +85 -85
  12. package/dist/convert-icons.md +52 -52
  13. package/dist/generate-icons.js +48 -48
  14. package/dist/icons/codex-white.svg +3 -3
  15. package/dist/icons/codex.svg +3 -3
  16. package/dist/icons/cursor-white.svg +11 -11
  17. package/dist/icons/qwen-logo.svg +14 -14
  18. package/dist/index.html +58 -58
  19. package/dist/manifest.json +60 -60
  20. package/dist/openapi.yaml +1693 -1693
  21. package/dist/sw.js +124 -124
  22. package/dist-server/server/cli.js +96 -96
  23. package/dist-server/server/daemon/manager.js +33 -33
  24. package/dist-server/server/daemon-manager.js +64 -64
  25. package/dist-server/server/modules/orchestration/preview/preview-proxy.js +3 -3
  26. package/dist-server/server/modules/orchestration/preview/preview-proxy.js.map +1 -1
  27. package/dist-server/server/routes/commands.js +25 -25
  28. package/dist-server/server/routes/git.js +17 -17
  29. package/dist-server/server/routes/taskmaster.js +419 -419
  30. package/package.json +180 -180
  31. package/scripts/fix-node-pty.js +67 -67
  32. package/scripts/smoke/a2a-roundtrip.mjs +167 -167
  33. package/scripts/smoke/orchestration-api.mjs +172 -172
  34. package/scripts/smoke/orchestration-live-run.mjs +176 -176
  35. package/server/claude-sdk.js +898 -898
  36. package/server/cli.js +935 -935
  37. package/server/constants/config.js +4 -4
  38. package/server/cursor-cli.js +342 -342
  39. package/server/daemon/manager.js +564 -564
  40. package/server/daemon-manager.js +959 -959
  41. package/server/database/json-store.js +197 -197
  42. package/server/gemini-cli.js +535 -535
  43. package/server/gemini-response-handler.js +79 -79
  44. package/server/index.js +3135 -3135
  45. package/server/load-env.js +34 -34
  46. package/server/middleware/auth.js +173 -173
  47. package/server/modules/orchestration/a2a/adapter-registry.ts +108 -108
  48. package/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.ts +55 -55
  49. package/server/modules/orchestration/a2a/adapters/claude-code.adapter.ts +284 -284
  50. package/server/modules/orchestration/a2a/adapters/codex.adapter.ts +244 -244
  51. package/server/modules/orchestration/a2a/adapters/cursor.adapter.ts +249 -249
  52. package/server/modules/orchestration/a2a/adapters/gemini.adapter.ts +248 -248
  53. package/server/modules/orchestration/a2a/adapters/opencode.adapter.ts +248 -248
  54. package/server/modules/orchestration/a2a/adapters/qwen.adapter.ts +248 -248
  55. package/server/modules/orchestration/a2a/agent-card.ts +55 -55
  56. package/server/modules/orchestration/a2a/auth.middleware.ts +29 -29
  57. package/server/modules/orchestration/a2a/bus.ts +46 -46
  58. package/server/modules/orchestration/a2a/routes.ts +577 -577
  59. package/server/modules/orchestration/a2a/task-store.ts +178 -178
  60. package/server/modules/orchestration/a2a/types.ts +125 -125
  61. package/server/modules/orchestration/a2a/validator.ts +113 -113
  62. package/server/modules/orchestration/index.ts +66 -66
  63. package/server/modules/orchestration/preview/port-watcher.ts +112 -112
  64. package/server/modules/orchestration/preview/preview-proxy.ts +60 -60
  65. package/server/modules/orchestration/preview/types.ts +19 -19
  66. package/server/modules/orchestration/tasks/orchestration-task-store.ts +45 -45
  67. package/server/modules/orchestration/tasks/orchestration-task.routes.ts +73 -73
  68. package/server/modules/orchestration/tasks/orchestration-task.service.ts +145 -145
  69. package/server/modules/orchestration/tasks/orchestration-task.types.ts +29 -29
  70. package/server/modules/orchestration/workflows/built-in-workflows.ts +127 -127
  71. package/server/modules/orchestration/workflows/workflow-runner.ts +1206 -1206
  72. package/server/modules/orchestration/workflows/workflow-store.ts +97 -97
  73. package/server/modules/orchestration/workflows/workflow.routes.ts +169 -169
  74. package/server/modules/orchestration/workflows/workflow.types.ts +70 -70
  75. package/server/modules/orchestration/workflows/workspace-target.ts +120 -120
  76. package/server/modules/orchestration/workspace/docker-workspace.ts +135 -135
  77. package/server/modules/orchestration/workspace/path-safety.ts +55 -55
  78. package/server/modules/orchestration/workspace/types.ts +52 -52
  79. package/server/modules/orchestration/workspace/workspace-manager.ts +97 -97
  80. package/server/modules/orchestration/workspace/worktree-workspace.ts +125 -125
  81. package/server/modules/providers/index.ts +2 -2
  82. package/server/modules/providers/list/claude/claude-auth.provider.ts +145 -145
  83. package/server/modules/providers/list/claude/claude-mcp.provider.ts +135 -135
  84. package/server/modules/providers/list/claude/claude-sessions.provider.ts +306 -306
  85. package/server/modules/providers/list/claude/claude.provider.ts +15 -15
  86. package/server/modules/providers/list/codex/codex-auth.provider.ts +115 -115
  87. package/server/modules/providers/list/codex/codex-mcp.provider.ts +135 -135
  88. package/server/modules/providers/list/codex/codex-sessions.provider.ts +319 -319
  89. package/server/modules/providers/list/codex/codex.provider.ts +15 -15
  90. package/server/modules/providers/list/cursor/cursor-auth.provider.ts +143 -143
  91. package/server/modules/providers/list/cursor/cursor-mcp.provider.ts +108 -108
  92. package/server/modules/providers/list/cursor/cursor-sessions.provider.ts +421 -421
  93. package/server/modules/providers/list/cursor/cursor.provider.ts +15 -15
  94. package/server/modules/providers/list/gemini/gemini-auth.provider.ts +163 -163
  95. package/server/modules/providers/list/gemini/gemini-mcp.provider.ts +110 -110
  96. package/server/modules/providers/list/gemini/gemini-sessions.provider.ts +227 -227
  97. package/server/modules/providers/list/gemini/gemini.provider.ts +15 -15
  98. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +232 -232
  99. package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +265 -265
  100. package/server/modules/providers/provider.registry.ts +40 -40
  101. package/server/modules/providers/provider.routes.ts +819 -819
  102. package/server/modules/providers/services/mcp.service.ts +86 -86
  103. package/server/modules/providers/services/provider-auth.service.ts +26 -26
  104. package/server/modules/providers/services/sessions.service.ts +45 -45
  105. package/server/modules/providers/shared/base/abstract.provider.ts +20 -20
  106. package/server/modules/providers/shared/mcp/mcp.provider.ts +151 -151
  107. package/server/modules/providers/tests/mcp.test.ts +293 -293
  108. package/server/openai-codex.js +462 -462
  109. package/server/opencode-cli.js +459 -459
  110. package/server/opencode-response-handler.js +107 -107
  111. package/server/projects.js +3105 -3105
  112. package/server/routes/agent.js +1365 -1365
  113. package/server/routes/auth.js +138 -138
  114. package/server/routes/codex.js +19 -19
  115. package/server/routes/commands.js +554 -554
  116. package/server/routes/cursor.js +52 -52
  117. package/server/routes/gemini.js +24 -24
  118. package/server/routes/git.js +1488 -1488
  119. package/server/routes/mcp-utils.js +31 -31
  120. package/server/routes/messages.js +61 -61
  121. package/server/routes/network.js +120 -120
  122. package/server/routes/plugins.js +318 -318
  123. package/server/routes/projects.js +915 -915
  124. package/server/routes/settings.js +286 -286
  125. package/server/routes/taskmaster.js +1496 -1496
  126. package/server/routes/telegram.js +125 -125
  127. package/server/routes/user.js +123 -123
  128. package/server/services/install-jobs.js +571 -571
  129. package/server/services/notification-orchestrator.js +242 -242
  130. package/server/services/provider-credentials.js +189 -189
  131. package/server/services/telegram/bot.js +279 -279
  132. package/server/services/telegram/translations.js +170 -170
  133. package/server/sessionManager.js +225 -225
  134. package/server/shared/interfaces.ts +54 -54
  135. package/server/shared/types.ts +172 -172
  136. package/server/shared/utils.ts +193 -193
  137. package/server/tsconfig.json +36 -36
  138. package/server/utils/colors.js +21 -21
  139. package/server/utils/commandParser.js +303 -303
  140. package/server/utils/frontmatter.js +18 -18
  141. package/server/utils/gitConfig.js +34 -34
  142. package/server/utils/mcp-detector.js +147 -147
  143. package/server/utils/plugin-loader.js +457 -457
  144. package/server/utils/plugin-process-manager.js +184 -184
  145. package/server/utils/runtime-paths.js +37 -37
  146. package/server/utils/taskmaster-websocket.js +128 -128
  147. package/server/utils/url-detection.js +71 -71
  148. package/server/vite-daemon.js +78 -78
  149. package/shared/modelConstants.js +162 -162
  150. package/shared/networkHosts.js +22 -22
@@ -1,571 +1,571 @@
1
- /**
2
- * In-memory install-job registry + sandboxed local CLI installer.
3
- *
4
- * Why not `npm install -g`:
5
- * - Requires admin/sudo on Windows and most Linux distros. When Pixcode
6
- * runs as a non-privileged daemon, -g fails with EACCES and the user
7
- * sees a blank log with no actionable error.
8
- * - Even on Windows desktop, npm's global prefix is sometimes broken
9
- * (AppData permissions, antivirus quarantining node_modules/.bin).
10
- * - CI/docker/VPS setups often don't have `npm` on the daemon's PATH at
11
- * all, even when the user's interactive shell does.
12
- *
13
- * What we do instead:
14
- * - Install targets go into `~/.pixcode/cli-bin/` as LOCAL dependencies
15
- * of a pixcode-owned package.json (no -g, no sudo, no UAC).
16
- * - Resolve `npm` from the same Node install that's running the server
17
- * (sibling file to `process.execPath`) so PATH environment doesn't
18
- * matter.
19
- * - On server boot, `~/.pixcode/cli-bin/node_modules/.bin` is prepended
20
- * to `process.env.PATH`. Every existing `cross-spawn(binary)` call
21
- * (in claude-auth, gemini-cli, qwen-code-cli, etc.) then resolves to
22
- * the locally installed binary without any change to the adapter code.
23
- *
24
- * The HTTP/stream side of the API is the same as before:
25
- * - POST /install → spawns the child, returns { jobId }
26
- * - GET /install/:jobId/stream → EventSource that replays the buffered
27
- * transcript and then streams live chunks.
28
- * - DELETE /install/:jobId → cancels an in-flight install.
29
- *
30
- * Jobs linger 10 minutes after completion so late subscribers still see
31
- * the outcome.
32
- */
33
- import { execFileSync } from 'node:child_process';
34
- import { EventEmitter } from 'node:events';
35
- import { randomUUID } from 'node:crypto';
36
- import fs from 'node:fs';
37
- import os from 'node:os';
38
- import path from 'node:path';
39
-
40
- // Use cross-spawn instead of node:child_process.spawn. On Windows, node's
41
- // spawn cannot invoke `.cmd` / `.bat` files without `shell: true`, and with
42
- // `shell: true` it tokenises on spaces — so a valid npm path like
43
- // `C:\Program Files\nodejs\npm.cmd` gets split into "C:\Program" + "Files...".
44
- // cross-spawn shells out through cmd.exe with proper quoting transparently
45
- // and is already a transitive dependency we can safely re-use.
46
- import spawn from 'cross-spawn';
47
-
48
- const jobs = new Map();
49
- const FINISHED_TTL_MS = 10 * 60 * 1000;
50
- const HARD_TIMEOUT_MS = 10 * 60 * 1000;
51
-
52
- export const CLI_HOME = path.join(os.homedir(), '.pixcode', 'cli-bin');
53
- export const CLI_BIN_DIR = path.join(CLI_HOME, 'node_modules', '.bin');
54
-
55
- /**
56
- * npm package → the binary name it installs. Used to verify the install
57
- * actually dropped an executable we can run, since npm can exit(0) even
58
- * when a package has no `bin` entry or our PATH wiring is wrong.
59
- */
60
- const PACKAGE_BINARIES = {
61
- '@anthropic-ai/claude-code': 'claude',
62
- '@openai/codex': 'codex',
63
- '@google/gemini-cli': 'gemini',
64
- '@qwen-code/qwen-code': 'qwen',
65
- 'opencode-ai': 'opencode',
66
- };
67
-
68
- /**
69
- * Make sure `CLI_HOME` exists with a minimal package.json so `npm install`
70
- * doesn't walk up to some unrelated parent and pollute it.
71
- */
72
- function ensureCliHome() {
73
- fs.mkdirSync(CLI_HOME, { recursive: true });
74
- const pkgPath = path.join(CLI_HOME, 'package.json');
75
- if (!fs.existsSync(pkgPath)) {
76
- const pkg = {
77
- name: 'pixcode-cli-bin',
78
- private: true,
79
- version: '0.0.0',
80
- description:
81
- 'Pixcode-managed sandbox for provider CLIs (claude/codex/gemini/qwen). '
82
- + 'Safe to delete; Pixcode will re-create it on next install.',
83
- };
84
- fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2));
85
- }
86
- }
87
-
88
- /**
89
- * Prepend the pixcode-managed bin dir to PATH. Called at server boot so
90
- * every subsequent `spawn('claude'|'gemini'|'codex'|'qwen', …)` in the
91
- * provider adapters (which use cross-spawn with bare names) resolves to
92
- * the locally installed binary without any per-adapter change.
93
- */
94
- export function primeCliBinPath(env = process.env) {
95
- ensureCliHome();
96
- const sep = process.platform === 'win32' ? ';' : ':';
97
- const current = env.PATH || env.Path || '';
98
- if (!current.split(sep).some((entry) => path.resolve(entry || '') === path.resolve(CLI_BIN_DIR))) {
99
- const next = current ? `${CLI_BIN_DIR}${sep}${current}` : CLI_BIN_DIR;
100
- env.PATH = next;
101
- if ('Path' in env) env.Path = next;
102
- }
103
- // Once PATH is ready, resolve any well-known provider binaries to absolute
104
- // paths and export them as *_CLI_PATH env vars. This side-steps a Windows
105
- // gotcha: `child_process.spawn('claude', …)` does NOT auto-resolve .cmd /
106
- // .bat extensions, and the Claude Agent SDK calls spawn directly instead
107
- // of via cross-spawn — so a bare "claude" on PATH works in a shell but
108
- // fails inside the SDK. Pinning the full path side-steps it entirely.
109
- resolveProviderExecutables(env);
110
- }
111
-
112
- /**
113
- * Scan PATH (plus known native-installer locations) for every provider
114
- * binary we ship support for, and export *_CLI_PATH env vars pointing to
115
- * the absolute executable. Existing vars are left alone so users can
116
- * override detection.
117
- */
118
- export function resolveProviderExecutables(env = process.env) {
119
- // Claude is intentionally omitted. The Claude Agent SDK ships a bundled
120
- // native binary per platform (@anthropic-ai/claude-agent-sdk-<os>-<arch>)
121
- // and resolves it automatically. Exporting CLAUDE_CLI_PATH here would
122
- // override that and hand a `.cmd` shim to Node's spawn on Windows,
123
- // which then throws EINVAL (spawn can't exec .cmd files directly).
124
- //
125
- // The other providers use cross-spawn in our own adapters, which
126
- // handles .cmd/.bat resolution on Windows. Forcing an absolute path
127
- // there is still helpful because cross-spawn.sync without quoting
128
- // can hit edge cases when PATH contains spaces.
129
- const providers = [
130
- { name: 'codex', envKey: 'CODEX_CLI_PATH' },
131
- { name: 'gemini', envKey: 'GEMINI_CLI_PATH' },
132
- { name: 'qwen', envKey: 'QWEN_CLI_PATH' },
133
- { name: 'opencode', envKey: 'OPENCODE_CLI_PATH' },
134
- { name: 'cursor-agent', envKey: 'CURSOR_CLI_PATH' },
135
- ];
136
- for (const { name, envKey } of providers) {
137
- if (env[envKey]) continue;
138
- const resolved = findExecutableOnPath(name, env);
139
- if (resolved) env[envKey] = resolved;
140
- }
141
- }
142
-
143
- /**
144
- * Cross-platform lookup for the Claude Code CLI executable. The
145
- * @anthropic-ai/claude-agent-sdk SDK spawns its target with plain
146
- * `child_process.spawn(command, args)` — no shell, no cross-spawn — which
147
- * means:
148
- * - On Unix, `"claude"` resolves via PATH + shebang. Works out of the box.
149
- * - On Windows, `"claude"` does NOT resolve (Node doesn't traverse PATHEXT
150
- * for bare names), and spawning a `.cmd` shim directly throws EINVAL
151
- * after Node 20.12's CVE-2024-27980 fix. We have to hand the SDK the
152
- * real `.exe` target instead.
153
- *
154
- * We use the OS's own `where`/`which` so we stay consistent with whatever
155
- * the user sees in their shell. When `where` yields a `.cmd` shim, we
156
- * peek inside it (npm-generated shims quote the underlying `.exe` path)
157
- * and return that real binary.
158
- *
159
- * Returns the absolute path, or `null` if nothing turned up — callers
160
- * should leave `pathToClaudeCodeExecutable` unset so the SDK falls back
161
- * to its own bundled native binary.
162
- */
163
- export function resolveClaudeExecutable() {
164
- const isWindows = process.platform === 'win32';
165
- try {
166
- if (isWindows) {
167
- // `where.exe` returns one path per line. Prefer `.exe` over any
168
- // `.cmd` or `.ps1` shim because Node's spawn can exec .exe
169
- // directly — .cmd needs shell:true which the SDK doesn't set.
170
- const stdout = execFileSync('where', ['claude'], {
171
- encoding: 'utf8',
172
- stdio: ['ignore', 'pipe', 'ignore'],
173
- }).trim();
174
- const candidates = stdout.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
175
- const exe = candidates.find((p) => p.toLowerCase().endsWith('.exe'));
176
- if (exe && fs.existsSync(exe)) return exe;
177
- // Only a `.cmd` shim found. Parse it for the real .exe target.
178
- for (const candidate of candidates) {
179
- if (candidate.toLowerCase().endsWith('.cmd')) {
180
- const underlying = parseNpmCmdShim(candidate);
181
- if (underlying) return underlying;
182
- }
183
- }
184
- return candidates[0] || null;
185
- }
186
- const stdout = execFileSync('which', ['claude'], {
187
- encoding: 'utf8',
188
- stdio: ['ignore', 'pipe', 'ignore'],
189
- }).trim();
190
- return stdout || null;
191
- } catch {
192
- // `where`/`which` returns non-zero when nothing matches. Fall back
193
- // to null so the SDK uses its own resolver.
194
- return null;
195
- }
196
- }
197
-
198
- /**
199
- * Cross-platform lookup for a POSIX `bash` the Claude CLI can drive. On
200
- * Windows, `claude.exe` hard-requires a `bash.exe` (typically from Git
201
- * for Windows) and exits with code 1 + a guidance message if it can't
202
- * find one. The CLI reads the path from `CLAUDE_CODE_GIT_BASH_PATH`
203
- * when set, otherwise probes a short list of known install locations —
204
- * which are exactly the ones we try below.
205
- *
206
- * Returns the absolute path or null. On non-Windows platforms we skip
207
- * the probe entirely and rely on the system `bash` that Claude expects
208
- * to already be on PATH.
209
- */
210
- export function resolveGitBashPath() {
211
- if (process.platform !== 'win32') return null;
212
-
213
- if (process.env.CLAUDE_CODE_GIT_BASH_PATH
214
- && fs.existsSync(process.env.CLAUDE_CODE_GIT_BASH_PATH)) {
215
- return process.env.CLAUDE_CODE_GIT_BASH_PATH;
216
- }
217
-
218
- // 1. `where.exe bash` first — the user already has it on PATH if any
219
- // shell launcher (VS Code, etc.) set it up. Prefer this over our
220
- // hard-coded list because it reflects their actual install.
221
- try {
222
- const stdout = execFileSync('where', ['bash'], {
223
- encoding: 'utf8',
224
- stdio: ['ignore', 'pipe', 'ignore'],
225
- }).trim();
226
- const first = stdout.split(/\r?\n/)[0]?.trim();
227
- if (first && fs.existsSync(first)) return first;
228
- } catch { /* fall through to hard-coded probes */ }
229
-
230
- // 2. Known Git-for-Windows install locations. Covers system-wide,
231
- // per-user, scoop, and chocolatey defaults.
232
- const home = os.homedir();
233
- const programFiles = process.env['ProgramFiles'] || 'C:\\Program Files';
234
- const programFilesX86 = process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)';
235
- const localAppData = process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
236
-
237
- const candidates = [
238
- path.join(programFiles, 'Git', 'bin', 'bash.exe'),
239
- path.join(programFiles, 'Git', 'usr', 'bin', 'bash.exe'),
240
- path.join(programFilesX86, 'Git', 'bin', 'bash.exe'),
241
- path.join(programFilesX86, 'Git', 'usr', 'bin', 'bash.exe'),
242
- path.join(localAppData, 'Programs', 'Git', 'bin', 'bash.exe'),
243
- path.join(localAppData, 'Programs', 'Git', 'usr', 'bin', 'bash.exe'),
244
- // Scoop's default install path for the git package
245
- path.join(home, 'scoop', 'apps', 'git', 'current', 'bin', 'bash.exe'),
246
- ];
247
-
248
- for (const candidate of candidates) {
249
- try {
250
- if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
251
- return candidate;
252
- }
253
- } catch { /* ignore */ }
254
- }
255
-
256
- return null;
257
- }
258
-
259
- /**
260
- * Extract the real .exe target from an npm-generated Windows .cmd shim.
261
- *
262
- * The shim looks like:
263
- * @"%_prog%" "%dp0%\node_modules\@anthropic-ai\claude-code\bin\claude.exe" %*
264
- * We capture the first quoted `.exe` path, then expand `%~dp0` / `%dp0`
265
- * to the shim's own directory so the returned path is absolute.
266
- */
267
- function parseNpmCmdShim(cmdPath) {
268
- try {
269
- const content = fs.readFileSync(cmdPath, 'utf8');
270
- const match = content.match(/"([^"]+\.exe)"/i);
271
- if (!match) return null;
272
- const rel = match[1];
273
- const dir = path.dirname(cmdPath);
274
- const resolved = rel
275
- .replace(/%~?dp0%?\\?/gi, `${dir}${path.sep}`)
276
- .replace(/%~dp0/gi, dir);
277
- return fs.existsSync(resolved) ? resolved : null;
278
- } catch {
279
- return null;
280
- }
281
- }
282
-
283
- /**
284
- * Search PATH for an executable, including the Windows extension variants.
285
- * Returns the absolute path or null. Plain Node has no cross-platform
286
- * equivalent of `which`, so we roll our own — it's small enough to not be
287
- * worth an extra dependency.
288
- */
289
- export function findExecutableOnPath(name, env = process.env) {
290
- const isWindows = process.platform === 'win32';
291
- const sep = isWindows ? ';' : ':';
292
- const paths = (env.PATH || env.Path || '').split(sep).filter(Boolean);
293
-
294
- // Common native-installer / per-user fallback paths that aren't always on
295
- // the daemon's PATH but are on the user's interactive shell PATH. We
296
- // union them in so "pixcode --no-daemon" and "pixcode daemon" agree.
297
- const home = os.homedir();
298
- if (isWindows) {
299
- paths.push(path.join(env.APPDATA || path.join(home, 'AppData', 'Roaming'), 'npm'));
300
- paths.push(path.join(env.LOCALAPPDATA || path.join(home, 'AppData', 'Local'), 'Programs', `${name}-code`));
301
- paths.push(path.join(env.LOCALAPPDATA || path.join(home, 'AppData', 'Local'), 'AnthropicClaude'));
302
- } else {
303
- paths.push(path.join(home, '.local', 'bin'));
304
- paths.push(path.join(home, '.npm-global', 'bin'));
305
- paths.push('/usr/local/bin');
306
- paths.push('/opt/homebrew/bin');
307
- }
308
-
309
- const exts = isWindows
310
- ? ['.cmd', '.exe', '.bat', '.ps1', '']
311
- : [''];
312
-
313
- for (const dir of paths) {
314
- for (const ext of exts) {
315
- const candidate = path.join(dir, name + ext);
316
- try {
317
- if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
318
- return candidate;
319
- }
320
- } catch {
321
- // Permission denied / broken symlink — ignore and keep looking.
322
- }
323
- }
324
- }
325
- return null;
326
- }
327
-
328
- /**
329
- * Resolve `npm` next to the currently-running `node` binary. This is
330
- * more reliable than trusting PATH — when Pixcode runs as a daemon, PATH
331
- * is often minimal and doesn't include the user's node install.
332
- */
333
- function resolveNpmCommand() {
334
- const nodeDir = path.dirname(process.execPath);
335
- const isWindows = process.platform === 'win32';
336
- const candidates = isWindows
337
- ? ['npm.cmd', 'npm.exe']
338
- : ['npm'];
339
- for (const c of candidates) {
340
- const full = path.join(nodeDir, c);
341
- if (fs.existsSync(full)) return full;
342
- }
343
- // Windows sometimes ships npm in a sibling "npm" directory.
344
- if (isWindows) {
345
- const siblingNpm = path.join(nodeDir, 'node_modules', 'npm', 'bin', 'npm-cli.js');
346
- if (fs.existsSync(siblingNpm)) {
347
- return siblingNpm; // we'll invoke `node <npm-cli.js>`
348
- }
349
- }
350
- // Fall back to bare name and let the shell resolve.
351
- return isWindows ? 'npm.cmd' : 'npm';
352
- }
353
-
354
- function packageFromCommand(installCmd) {
355
- // Legacy callers still pass `npm install -g <pkg>` strings — extract
356
- // the @scope/name so the local installer can reuse the same input.
357
- const match = String(installCmd).match(/@[^\s]+\/[^\s]+|[\w.-]+(?:@[\w.-]+)?$/);
358
- return match ? match[0] : installCmd;
359
- }
360
-
361
- export function createInstallJob({ provider, installCmd, packageName }) {
362
- const pkg = packageName || packageFromCommand(installCmd);
363
- const id = randomUUID();
364
- const emitter = new EventEmitter();
365
- emitter.setMaxListeners(20);
366
-
367
- const job = {
368
- id,
369
- provider,
370
- installCmd,
371
- package: pkg,
372
- status: 'running',
373
- startedAt: new Date().toISOString(),
374
- finishedAt: null,
375
- exitCode: null,
376
- error: null,
377
- logs: [],
378
- emitter,
379
- child: null,
380
- timer: null,
381
- };
382
-
383
- const appendLog = (stream, chunk) => {
384
- const entry = { stream, chunk, at: Date.now() };
385
- job.logs.push(entry);
386
- if (job.logs.length > 2000) {
387
- job.logs.splice(0, job.logs.length - 2000);
388
- }
389
- emitter.emit('log', entry);
390
- };
391
-
392
- try {
393
- ensureCliHome();
394
- } catch (err) {
395
- job.status = 'error';
396
- job.error = `Could not create ${CLI_HOME}: ${err?.message || err}`;
397
- job.finishedAt = new Date().toISOString();
398
- appendLog('stderr', job.error + '\n');
399
- emitter.emit('done', buildDonePayload(job));
400
- scheduleCleanup(job);
401
- jobs.set(id, job);
402
- return job;
403
- }
404
-
405
- appendLog('meta', `Installing ${pkg} into ${CLI_HOME}\n`);
406
- appendLog('meta', `(sandboxed — no sudo / admin required)\n`);
407
-
408
- const npmCmd = resolveNpmCommand();
409
- const useNodeRunner = npmCmd.endsWith('.js');
410
-
411
- const cmd = useNodeRunner ? process.execPath : npmCmd;
412
- const args = useNodeRunner
413
- ? [npmCmd, 'install', pkg, '--no-audit', '--no-fund', '--loglevel=http']
414
- : ['install', pkg, '--no-audit', '--no-fund', '--loglevel=http'];
415
-
416
- appendLog('meta', `$ ${cmd} ${args.join(' ')}\n`);
417
-
418
- let child;
419
- try {
420
- child = spawn(cmd, args, {
421
- cwd: CLI_HOME,
422
- env: { ...process.env, npm_config_yes: 'true' },
423
- stdio: ['ignore', 'pipe', 'pipe'],
424
- windowsHide: true,
425
- // cross-spawn handles .cmd/.bat resolution itself — no shell
426
- // needed. Passing `shell: true` here would re-introduce the
427
- // space-in-path tokenisation bug that caused "'C:\Program' is
428
- // not recognized" on Windows installs of Node.
429
- });
430
- } catch (err) {
431
- const message = err?.message || String(err);
432
- console.error(`[install-job:${provider}:${id}] Spawn failed:`, message);
433
- job.status = 'error';
434
- job.error = `Failed to launch npm: ${message}`;
435
- job.finishedAt = new Date().toISOString();
436
- appendLog('stderr', job.error + '\n');
437
- emitter.emit('done', buildDonePayload(job));
438
- scheduleCleanup(job);
439
- jobs.set(id, job);
440
- return job;
441
- }
442
-
443
- job.child = child;
444
- child.stdout.on('data', (buf) => appendLog('stdout', buf.toString()));
445
- child.stderr.on('data', (buf) => appendLog('stderr', buf.toString()));
446
-
447
- child.on('error', (err) => {
448
- if (job.status !== 'running') return;
449
- job.status = 'error';
450
- job.error = `npm process error: ${err.message}`;
451
- job.finishedAt = new Date().toISOString();
452
- appendLog('stderr', job.error + '\n');
453
- emitter.emit('done', buildDonePayload(job));
454
- scheduleCleanup(job);
455
- });
456
-
457
- child.on('close', (code, signal) => {
458
- if (job.status !== 'running') return;
459
- job.exitCode = code ?? null;
460
- job.finishedAt = new Date().toISOString();
461
-
462
- if (code !== 0) {
463
- job.status = 'error';
464
- job.error = signal
465
- ? `Install killed by signal ${signal}`
466
- : `npm exited with code ${code}`;
467
- emitter.emit('done', buildDonePayload(job));
468
- scheduleCleanup(job);
469
- return;
470
- }
471
-
472
- // Verify the binary actually landed. If we don't check, a package
473
- // without a `bin` entry (or a half-extracted tarball) would still
474
- // read as "success" and the user would be confused when auth
475
- // status stays red.
476
- const binName = PACKAGE_BINARIES[pkg] || provider;
477
- const binaryPath = findInstalledBinary(binName);
478
- if (!binaryPath) {
479
- job.status = 'error';
480
- job.error = `npm exited cleanly but ${binName} was not found in ${CLI_BIN_DIR}`;
481
- appendLog('stderr', job.error + '\n');
482
- emitter.emit('done', buildDonePayload(job));
483
- scheduleCleanup(job);
484
- return;
485
- }
486
-
487
- // Make sure our live server process can resolve the new binary
488
- // from this moment on, without a restart. primeCliBinPath is
489
- // idempotent so re-calling after each install is cheap.
490
- primeCliBinPath();
491
-
492
- appendLog('meta', `✓ Installed ${binName} → ${binaryPath}\n`);
493
- job.status = 'done';
494
- job.binaryPath = binaryPath;
495
- emitter.emit('done', buildDonePayload(job));
496
- scheduleCleanup(job);
497
- });
498
-
499
- job.timer = setTimeout(() => {
500
- if (job.status !== 'running') return;
501
- try { child.kill('SIGKILL'); } catch { /* noop */ }
502
- job.status = 'error';
503
- job.error = 'Install timed out after 10 minutes';
504
- job.finishedAt = new Date().toISOString();
505
- appendLog('stderr', job.error + '\n');
506
- emitter.emit('done', buildDonePayload(job));
507
- scheduleCleanup(job);
508
- }, HARD_TIMEOUT_MS);
509
-
510
- jobs.set(id, job);
511
- return job;
512
- }
513
-
514
- function findInstalledBinary(name) {
515
- const isWindows = process.platform === 'win32';
516
- const candidates = isWindows
517
- ? [`${name}.cmd`, `${name}.exe`, name]
518
- : [name];
519
- for (const c of candidates) {
520
- const full = path.join(CLI_BIN_DIR, c);
521
- if (fs.existsSync(full)) return full;
522
- }
523
- return null;
524
- }
525
-
526
- function buildDonePayload(job) {
527
- if (job.status === 'done') {
528
- return {
529
- success: true,
530
- exitCode: job.exitCode,
531
- binaryPath: job.binaryPath,
532
- message: `${job.provider} installed. Refreshing auth status…`,
533
- };
534
- }
535
- return {
536
- success: false,
537
- exitCode: job.exitCode,
538
- error: job.error || 'Install failed',
539
- };
540
- }
541
-
542
- function scheduleCleanup(job) {
543
- if (job.timer) {
544
- clearTimeout(job.timer);
545
- job.timer = null;
546
- }
547
- setTimeout(() => {
548
- jobs.delete(job.id);
549
- }, FINISHED_TTL_MS);
550
- }
551
-
552
- export function getInstallJob(id) {
553
- return jobs.get(id) || null;
554
- }
555
-
556
- export function cancelInstallJob(id) {
557
- const job = jobs.get(id);
558
- if (!job) return false;
559
- if (job.status !== 'running') return false;
560
- try { job.child?.kill(); } catch { /* noop */ }
561
- job.status = 'error';
562
- job.error = 'Install cancelled';
563
- job.finishedAt = new Date().toISOString();
564
- job.emitter.emit('done', buildDonePayload(job));
565
- scheduleCleanup(job);
566
- return true;
567
- }
568
-
569
- export function snapshotDonePayload(job) {
570
- return buildDonePayload(job);
571
- }
1
+ /**
2
+ * In-memory install-job registry + sandboxed local CLI installer.
3
+ *
4
+ * Why not `npm install -g`:
5
+ * - Requires admin/sudo on Windows and most Linux distros. When Pixcode
6
+ * runs as a non-privileged daemon, -g fails with EACCES and the user
7
+ * sees a blank log with no actionable error.
8
+ * - Even on Windows desktop, npm's global prefix is sometimes broken
9
+ * (AppData permissions, antivirus quarantining node_modules/.bin).
10
+ * - CI/docker/VPS setups often don't have `npm` on the daemon's PATH at
11
+ * all, even when the user's interactive shell does.
12
+ *
13
+ * What we do instead:
14
+ * - Install targets go into `~/.pixcode/cli-bin/` as LOCAL dependencies
15
+ * of a pixcode-owned package.json (no -g, no sudo, no UAC).
16
+ * - Resolve `npm` from the same Node install that's running the server
17
+ * (sibling file to `process.execPath`) so PATH environment doesn't
18
+ * matter.
19
+ * - On server boot, `~/.pixcode/cli-bin/node_modules/.bin` is prepended
20
+ * to `process.env.PATH`. Every existing `cross-spawn(binary)` call
21
+ * (in claude-auth, gemini-cli, qwen-code-cli, etc.) then resolves to
22
+ * the locally installed binary without any change to the adapter code.
23
+ *
24
+ * The HTTP/stream side of the API is the same as before:
25
+ * - POST /install → spawns the child, returns { jobId }
26
+ * - GET /install/:jobId/stream → EventSource that replays the buffered
27
+ * transcript and then streams live chunks.
28
+ * - DELETE /install/:jobId → cancels an in-flight install.
29
+ *
30
+ * Jobs linger 10 minutes after completion so late subscribers still see
31
+ * the outcome.
32
+ */
33
+ import { execFileSync } from 'node:child_process';
34
+ import { EventEmitter } from 'node:events';
35
+ import { randomUUID } from 'node:crypto';
36
+ import fs from 'node:fs';
37
+ import os from 'node:os';
38
+ import path from 'node:path';
39
+
40
+ // Use cross-spawn instead of node:child_process.spawn. On Windows, node's
41
+ // spawn cannot invoke `.cmd` / `.bat` files without `shell: true`, and with
42
+ // `shell: true` it tokenises on spaces — so a valid npm path like
43
+ // `C:\Program Files\nodejs\npm.cmd` gets split into "C:\Program" + "Files...".
44
+ // cross-spawn shells out through cmd.exe with proper quoting transparently
45
+ // and is already a transitive dependency we can safely re-use.
46
+ import spawn from 'cross-spawn';
47
+
48
+ const jobs = new Map();
49
+ const FINISHED_TTL_MS = 10 * 60 * 1000;
50
+ const HARD_TIMEOUT_MS = 10 * 60 * 1000;
51
+
52
+ export const CLI_HOME = path.join(os.homedir(), '.pixcode', 'cli-bin');
53
+ export const CLI_BIN_DIR = path.join(CLI_HOME, 'node_modules', '.bin');
54
+
55
+ /**
56
+ * npm package → the binary name it installs. Used to verify the install
57
+ * actually dropped an executable we can run, since npm can exit(0) even
58
+ * when a package has no `bin` entry or our PATH wiring is wrong.
59
+ */
60
+ const PACKAGE_BINARIES = {
61
+ '@anthropic-ai/claude-code': 'claude',
62
+ '@openai/codex': 'codex',
63
+ '@google/gemini-cli': 'gemini',
64
+ '@qwen-code/qwen-code': 'qwen',
65
+ 'opencode-ai': 'opencode',
66
+ };
67
+
68
+ /**
69
+ * Make sure `CLI_HOME` exists with a minimal package.json so `npm install`
70
+ * doesn't walk up to some unrelated parent and pollute it.
71
+ */
72
+ function ensureCliHome() {
73
+ fs.mkdirSync(CLI_HOME, { recursive: true });
74
+ const pkgPath = path.join(CLI_HOME, 'package.json');
75
+ if (!fs.existsSync(pkgPath)) {
76
+ const pkg = {
77
+ name: 'pixcode-cli-bin',
78
+ private: true,
79
+ version: '0.0.0',
80
+ description:
81
+ 'Pixcode-managed sandbox for provider CLIs (claude/codex/gemini/qwen). '
82
+ + 'Safe to delete; Pixcode will re-create it on next install.',
83
+ };
84
+ fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2));
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Prepend the pixcode-managed bin dir to PATH. Called at server boot so
90
+ * every subsequent `spawn('claude'|'gemini'|'codex'|'qwen', …)` in the
91
+ * provider adapters (which use cross-spawn with bare names) resolves to
92
+ * the locally installed binary without any per-adapter change.
93
+ */
94
+ export function primeCliBinPath(env = process.env) {
95
+ ensureCliHome();
96
+ const sep = process.platform === 'win32' ? ';' : ':';
97
+ const current = env.PATH || env.Path || '';
98
+ if (!current.split(sep).some((entry) => path.resolve(entry || '') === path.resolve(CLI_BIN_DIR))) {
99
+ const next = current ? `${CLI_BIN_DIR}${sep}${current}` : CLI_BIN_DIR;
100
+ env.PATH = next;
101
+ if ('Path' in env) env.Path = next;
102
+ }
103
+ // Once PATH is ready, resolve any well-known provider binaries to absolute
104
+ // paths and export them as *_CLI_PATH env vars. This side-steps a Windows
105
+ // gotcha: `child_process.spawn('claude', …)` does NOT auto-resolve .cmd /
106
+ // .bat extensions, and the Claude Agent SDK calls spawn directly instead
107
+ // of via cross-spawn — so a bare "claude" on PATH works in a shell but
108
+ // fails inside the SDK. Pinning the full path side-steps it entirely.
109
+ resolveProviderExecutables(env);
110
+ }
111
+
112
+ /**
113
+ * Scan PATH (plus known native-installer locations) for every provider
114
+ * binary we ship support for, and export *_CLI_PATH env vars pointing to
115
+ * the absolute executable. Existing vars are left alone so users can
116
+ * override detection.
117
+ */
118
+ export function resolveProviderExecutables(env = process.env) {
119
+ // Claude is intentionally omitted. The Claude Agent SDK ships a bundled
120
+ // native binary per platform (@anthropic-ai/claude-agent-sdk-<os>-<arch>)
121
+ // and resolves it automatically. Exporting CLAUDE_CLI_PATH here would
122
+ // override that and hand a `.cmd` shim to Node's spawn on Windows,
123
+ // which then throws EINVAL (spawn can't exec .cmd files directly).
124
+ //
125
+ // The other providers use cross-spawn in our own adapters, which
126
+ // handles .cmd/.bat resolution on Windows. Forcing an absolute path
127
+ // there is still helpful because cross-spawn.sync without quoting
128
+ // can hit edge cases when PATH contains spaces.
129
+ const providers = [
130
+ { name: 'codex', envKey: 'CODEX_CLI_PATH' },
131
+ { name: 'gemini', envKey: 'GEMINI_CLI_PATH' },
132
+ { name: 'qwen', envKey: 'QWEN_CLI_PATH' },
133
+ { name: 'opencode', envKey: 'OPENCODE_CLI_PATH' },
134
+ { name: 'cursor-agent', envKey: 'CURSOR_CLI_PATH' },
135
+ ];
136
+ for (const { name, envKey } of providers) {
137
+ if (env[envKey]) continue;
138
+ const resolved = findExecutableOnPath(name, env);
139
+ if (resolved) env[envKey] = resolved;
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Cross-platform lookup for the Claude Code CLI executable. The
145
+ * @anthropic-ai/claude-agent-sdk SDK spawns its target with plain
146
+ * `child_process.spawn(command, args)` — no shell, no cross-spawn — which
147
+ * means:
148
+ * - On Unix, `"claude"` resolves via PATH + shebang. Works out of the box.
149
+ * - On Windows, `"claude"` does NOT resolve (Node doesn't traverse PATHEXT
150
+ * for bare names), and spawning a `.cmd` shim directly throws EINVAL
151
+ * after Node 20.12's CVE-2024-27980 fix. We have to hand the SDK the
152
+ * real `.exe` target instead.
153
+ *
154
+ * We use the OS's own `where`/`which` so we stay consistent with whatever
155
+ * the user sees in their shell. When `where` yields a `.cmd` shim, we
156
+ * peek inside it (npm-generated shims quote the underlying `.exe` path)
157
+ * and return that real binary.
158
+ *
159
+ * Returns the absolute path, or `null` if nothing turned up — callers
160
+ * should leave `pathToClaudeCodeExecutable` unset so the SDK falls back
161
+ * to its own bundled native binary.
162
+ */
163
+ export function resolveClaudeExecutable() {
164
+ const isWindows = process.platform === 'win32';
165
+ try {
166
+ if (isWindows) {
167
+ // `where.exe` returns one path per line. Prefer `.exe` over any
168
+ // `.cmd` or `.ps1` shim because Node's spawn can exec .exe
169
+ // directly — .cmd needs shell:true which the SDK doesn't set.
170
+ const stdout = execFileSync('where', ['claude'], {
171
+ encoding: 'utf8',
172
+ stdio: ['ignore', 'pipe', 'ignore'],
173
+ }).trim();
174
+ const candidates = stdout.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
175
+ const exe = candidates.find((p) => p.toLowerCase().endsWith('.exe'));
176
+ if (exe && fs.existsSync(exe)) return exe;
177
+ // Only a `.cmd` shim found. Parse it for the real .exe target.
178
+ for (const candidate of candidates) {
179
+ if (candidate.toLowerCase().endsWith('.cmd')) {
180
+ const underlying = parseNpmCmdShim(candidate);
181
+ if (underlying) return underlying;
182
+ }
183
+ }
184
+ return candidates[0] || null;
185
+ }
186
+ const stdout = execFileSync('which', ['claude'], {
187
+ encoding: 'utf8',
188
+ stdio: ['ignore', 'pipe', 'ignore'],
189
+ }).trim();
190
+ return stdout || null;
191
+ } catch {
192
+ // `where`/`which` returns non-zero when nothing matches. Fall back
193
+ // to null so the SDK uses its own resolver.
194
+ return null;
195
+ }
196
+ }
197
+
198
+ /**
199
+ * Cross-platform lookup for a POSIX `bash` the Claude CLI can drive. On
200
+ * Windows, `claude.exe` hard-requires a `bash.exe` (typically from Git
201
+ * for Windows) and exits with code 1 + a guidance message if it can't
202
+ * find one. The CLI reads the path from `CLAUDE_CODE_GIT_BASH_PATH`
203
+ * when set, otherwise probes a short list of known install locations —
204
+ * which are exactly the ones we try below.
205
+ *
206
+ * Returns the absolute path or null. On non-Windows platforms we skip
207
+ * the probe entirely and rely on the system `bash` that Claude expects
208
+ * to already be on PATH.
209
+ */
210
+ export function resolveGitBashPath() {
211
+ if (process.platform !== 'win32') return null;
212
+
213
+ if (process.env.CLAUDE_CODE_GIT_BASH_PATH
214
+ && fs.existsSync(process.env.CLAUDE_CODE_GIT_BASH_PATH)) {
215
+ return process.env.CLAUDE_CODE_GIT_BASH_PATH;
216
+ }
217
+
218
+ // 1. `where.exe bash` first — the user already has it on PATH if any
219
+ // shell launcher (VS Code, etc.) set it up. Prefer this over our
220
+ // hard-coded list because it reflects their actual install.
221
+ try {
222
+ const stdout = execFileSync('where', ['bash'], {
223
+ encoding: 'utf8',
224
+ stdio: ['ignore', 'pipe', 'ignore'],
225
+ }).trim();
226
+ const first = stdout.split(/\r?\n/)[0]?.trim();
227
+ if (first && fs.existsSync(first)) return first;
228
+ } catch { /* fall through to hard-coded probes */ }
229
+
230
+ // 2. Known Git-for-Windows install locations. Covers system-wide,
231
+ // per-user, scoop, and chocolatey defaults.
232
+ const home = os.homedir();
233
+ const programFiles = process.env['ProgramFiles'] || 'C:\\Program Files';
234
+ const programFilesX86 = process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)';
235
+ const localAppData = process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
236
+
237
+ const candidates = [
238
+ path.join(programFiles, 'Git', 'bin', 'bash.exe'),
239
+ path.join(programFiles, 'Git', 'usr', 'bin', 'bash.exe'),
240
+ path.join(programFilesX86, 'Git', 'bin', 'bash.exe'),
241
+ path.join(programFilesX86, 'Git', 'usr', 'bin', 'bash.exe'),
242
+ path.join(localAppData, 'Programs', 'Git', 'bin', 'bash.exe'),
243
+ path.join(localAppData, 'Programs', 'Git', 'usr', 'bin', 'bash.exe'),
244
+ // Scoop's default install path for the git package
245
+ path.join(home, 'scoop', 'apps', 'git', 'current', 'bin', 'bash.exe'),
246
+ ];
247
+
248
+ for (const candidate of candidates) {
249
+ try {
250
+ if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
251
+ return candidate;
252
+ }
253
+ } catch { /* ignore */ }
254
+ }
255
+
256
+ return null;
257
+ }
258
+
259
+ /**
260
+ * Extract the real .exe target from an npm-generated Windows .cmd shim.
261
+ *
262
+ * The shim looks like:
263
+ * @"%_prog%" "%dp0%\node_modules\@anthropic-ai\claude-code\bin\claude.exe" %*
264
+ * We capture the first quoted `.exe` path, then expand `%~dp0` / `%dp0`
265
+ * to the shim's own directory so the returned path is absolute.
266
+ */
267
+ function parseNpmCmdShim(cmdPath) {
268
+ try {
269
+ const content = fs.readFileSync(cmdPath, 'utf8');
270
+ const match = content.match(/"([^"]+\.exe)"/i);
271
+ if (!match) return null;
272
+ const rel = match[1];
273
+ const dir = path.dirname(cmdPath);
274
+ const resolved = rel
275
+ .replace(/%~?dp0%?\\?/gi, `${dir}${path.sep}`)
276
+ .replace(/%~dp0/gi, dir);
277
+ return fs.existsSync(resolved) ? resolved : null;
278
+ } catch {
279
+ return null;
280
+ }
281
+ }
282
+
283
+ /**
284
+ * Search PATH for an executable, including the Windows extension variants.
285
+ * Returns the absolute path or null. Plain Node has no cross-platform
286
+ * equivalent of `which`, so we roll our own — it's small enough to not be
287
+ * worth an extra dependency.
288
+ */
289
+ export function findExecutableOnPath(name, env = process.env) {
290
+ const isWindows = process.platform === 'win32';
291
+ const sep = isWindows ? ';' : ':';
292
+ const paths = (env.PATH || env.Path || '').split(sep).filter(Boolean);
293
+
294
+ // Common native-installer / per-user fallback paths that aren't always on
295
+ // the daemon's PATH but are on the user's interactive shell PATH. We
296
+ // union them in so "pixcode --no-daemon" and "pixcode daemon" agree.
297
+ const home = os.homedir();
298
+ if (isWindows) {
299
+ paths.push(path.join(env.APPDATA || path.join(home, 'AppData', 'Roaming'), 'npm'));
300
+ paths.push(path.join(env.LOCALAPPDATA || path.join(home, 'AppData', 'Local'), 'Programs', `${name}-code`));
301
+ paths.push(path.join(env.LOCALAPPDATA || path.join(home, 'AppData', 'Local'), 'AnthropicClaude'));
302
+ } else {
303
+ paths.push(path.join(home, '.local', 'bin'));
304
+ paths.push(path.join(home, '.npm-global', 'bin'));
305
+ paths.push('/usr/local/bin');
306
+ paths.push('/opt/homebrew/bin');
307
+ }
308
+
309
+ const exts = isWindows
310
+ ? ['.cmd', '.exe', '.bat', '.ps1', '']
311
+ : [''];
312
+
313
+ for (const dir of paths) {
314
+ for (const ext of exts) {
315
+ const candidate = path.join(dir, name + ext);
316
+ try {
317
+ if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
318
+ return candidate;
319
+ }
320
+ } catch {
321
+ // Permission denied / broken symlink — ignore and keep looking.
322
+ }
323
+ }
324
+ }
325
+ return null;
326
+ }
327
+
328
+ /**
329
+ * Resolve `npm` next to the currently-running `node` binary. This is
330
+ * more reliable than trusting PATH — when Pixcode runs as a daemon, PATH
331
+ * is often minimal and doesn't include the user's node install.
332
+ */
333
+ function resolveNpmCommand() {
334
+ const nodeDir = path.dirname(process.execPath);
335
+ const isWindows = process.platform === 'win32';
336
+ const candidates = isWindows
337
+ ? ['npm.cmd', 'npm.exe']
338
+ : ['npm'];
339
+ for (const c of candidates) {
340
+ const full = path.join(nodeDir, c);
341
+ if (fs.existsSync(full)) return full;
342
+ }
343
+ // Windows sometimes ships npm in a sibling "npm" directory.
344
+ if (isWindows) {
345
+ const siblingNpm = path.join(nodeDir, 'node_modules', 'npm', 'bin', 'npm-cli.js');
346
+ if (fs.existsSync(siblingNpm)) {
347
+ return siblingNpm; // we'll invoke `node <npm-cli.js>`
348
+ }
349
+ }
350
+ // Fall back to bare name and let the shell resolve.
351
+ return isWindows ? 'npm.cmd' : 'npm';
352
+ }
353
+
354
+ function packageFromCommand(installCmd) {
355
+ // Legacy callers still pass `npm install -g <pkg>` strings — extract
356
+ // the @scope/name so the local installer can reuse the same input.
357
+ const match = String(installCmd).match(/@[^\s]+\/[^\s]+|[\w.-]+(?:@[\w.-]+)?$/);
358
+ return match ? match[0] : installCmd;
359
+ }
360
+
361
+ export function createInstallJob({ provider, installCmd, packageName }) {
362
+ const pkg = packageName || packageFromCommand(installCmd);
363
+ const id = randomUUID();
364
+ const emitter = new EventEmitter();
365
+ emitter.setMaxListeners(20);
366
+
367
+ const job = {
368
+ id,
369
+ provider,
370
+ installCmd,
371
+ package: pkg,
372
+ status: 'running',
373
+ startedAt: new Date().toISOString(),
374
+ finishedAt: null,
375
+ exitCode: null,
376
+ error: null,
377
+ logs: [],
378
+ emitter,
379
+ child: null,
380
+ timer: null,
381
+ };
382
+
383
+ const appendLog = (stream, chunk) => {
384
+ const entry = { stream, chunk, at: Date.now() };
385
+ job.logs.push(entry);
386
+ if (job.logs.length > 2000) {
387
+ job.logs.splice(0, job.logs.length - 2000);
388
+ }
389
+ emitter.emit('log', entry);
390
+ };
391
+
392
+ try {
393
+ ensureCliHome();
394
+ } catch (err) {
395
+ job.status = 'error';
396
+ job.error = `Could not create ${CLI_HOME}: ${err?.message || err}`;
397
+ job.finishedAt = new Date().toISOString();
398
+ appendLog('stderr', job.error + '\n');
399
+ emitter.emit('done', buildDonePayload(job));
400
+ scheduleCleanup(job);
401
+ jobs.set(id, job);
402
+ return job;
403
+ }
404
+
405
+ appendLog('meta', `Installing ${pkg} into ${CLI_HOME}\n`);
406
+ appendLog('meta', `(sandboxed — no sudo / admin required)\n`);
407
+
408
+ const npmCmd = resolveNpmCommand();
409
+ const useNodeRunner = npmCmd.endsWith('.js');
410
+
411
+ const cmd = useNodeRunner ? process.execPath : npmCmd;
412
+ const args = useNodeRunner
413
+ ? [npmCmd, 'install', pkg, '--no-audit', '--no-fund', '--loglevel=http']
414
+ : ['install', pkg, '--no-audit', '--no-fund', '--loglevel=http'];
415
+
416
+ appendLog('meta', `$ ${cmd} ${args.join(' ')}\n`);
417
+
418
+ let child;
419
+ try {
420
+ child = spawn(cmd, args, {
421
+ cwd: CLI_HOME,
422
+ env: { ...process.env, npm_config_yes: 'true' },
423
+ stdio: ['ignore', 'pipe', 'pipe'],
424
+ windowsHide: true,
425
+ // cross-spawn handles .cmd/.bat resolution itself — no shell
426
+ // needed. Passing `shell: true` here would re-introduce the
427
+ // space-in-path tokenisation bug that caused "'C:\Program' is
428
+ // not recognized" on Windows installs of Node.
429
+ });
430
+ } catch (err) {
431
+ const message = err?.message || String(err);
432
+ console.error(`[install-job:${provider}:${id}] Spawn failed:`, message);
433
+ job.status = 'error';
434
+ job.error = `Failed to launch npm: ${message}`;
435
+ job.finishedAt = new Date().toISOString();
436
+ appendLog('stderr', job.error + '\n');
437
+ emitter.emit('done', buildDonePayload(job));
438
+ scheduleCleanup(job);
439
+ jobs.set(id, job);
440
+ return job;
441
+ }
442
+
443
+ job.child = child;
444
+ child.stdout.on('data', (buf) => appendLog('stdout', buf.toString()));
445
+ child.stderr.on('data', (buf) => appendLog('stderr', buf.toString()));
446
+
447
+ child.on('error', (err) => {
448
+ if (job.status !== 'running') return;
449
+ job.status = 'error';
450
+ job.error = `npm process error: ${err.message}`;
451
+ job.finishedAt = new Date().toISOString();
452
+ appendLog('stderr', job.error + '\n');
453
+ emitter.emit('done', buildDonePayload(job));
454
+ scheduleCleanup(job);
455
+ });
456
+
457
+ child.on('close', (code, signal) => {
458
+ if (job.status !== 'running') return;
459
+ job.exitCode = code ?? null;
460
+ job.finishedAt = new Date().toISOString();
461
+
462
+ if (code !== 0) {
463
+ job.status = 'error';
464
+ job.error = signal
465
+ ? `Install killed by signal ${signal}`
466
+ : `npm exited with code ${code}`;
467
+ emitter.emit('done', buildDonePayload(job));
468
+ scheduleCleanup(job);
469
+ return;
470
+ }
471
+
472
+ // Verify the binary actually landed. If we don't check, a package
473
+ // without a `bin` entry (or a half-extracted tarball) would still
474
+ // read as "success" and the user would be confused when auth
475
+ // status stays red.
476
+ const binName = PACKAGE_BINARIES[pkg] || provider;
477
+ const binaryPath = findInstalledBinary(binName);
478
+ if (!binaryPath) {
479
+ job.status = 'error';
480
+ job.error = `npm exited cleanly but ${binName} was not found in ${CLI_BIN_DIR}`;
481
+ appendLog('stderr', job.error + '\n');
482
+ emitter.emit('done', buildDonePayload(job));
483
+ scheduleCleanup(job);
484
+ return;
485
+ }
486
+
487
+ // Make sure our live server process can resolve the new binary
488
+ // from this moment on, without a restart. primeCliBinPath is
489
+ // idempotent so re-calling after each install is cheap.
490
+ primeCliBinPath();
491
+
492
+ appendLog('meta', `✓ Installed ${binName} → ${binaryPath}\n`);
493
+ job.status = 'done';
494
+ job.binaryPath = binaryPath;
495
+ emitter.emit('done', buildDonePayload(job));
496
+ scheduleCleanup(job);
497
+ });
498
+
499
+ job.timer = setTimeout(() => {
500
+ if (job.status !== 'running') return;
501
+ try { child.kill('SIGKILL'); } catch { /* noop */ }
502
+ job.status = 'error';
503
+ job.error = 'Install timed out after 10 minutes';
504
+ job.finishedAt = new Date().toISOString();
505
+ appendLog('stderr', job.error + '\n');
506
+ emitter.emit('done', buildDonePayload(job));
507
+ scheduleCleanup(job);
508
+ }, HARD_TIMEOUT_MS);
509
+
510
+ jobs.set(id, job);
511
+ return job;
512
+ }
513
+
514
+ function findInstalledBinary(name) {
515
+ const isWindows = process.platform === 'win32';
516
+ const candidates = isWindows
517
+ ? [`${name}.cmd`, `${name}.exe`, name]
518
+ : [name];
519
+ for (const c of candidates) {
520
+ const full = path.join(CLI_BIN_DIR, c);
521
+ if (fs.existsSync(full)) return full;
522
+ }
523
+ return null;
524
+ }
525
+
526
+ function buildDonePayload(job) {
527
+ if (job.status === 'done') {
528
+ return {
529
+ success: true,
530
+ exitCode: job.exitCode,
531
+ binaryPath: job.binaryPath,
532
+ message: `${job.provider} installed. Refreshing auth status…`,
533
+ };
534
+ }
535
+ return {
536
+ success: false,
537
+ exitCode: job.exitCode,
538
+ error: job.error || 'Install failed',
539
+ };
540
+ }
541
+
542
+ function scheduleCleanup(job) {
543
+ if (job.timer) {
544
+ clearTimeout(job.timer);
545
+ job.timer = null;
546
+ }
547
+ setTimeout(() => {
548
+ jobs.delete(job.id);
549
+ }, FINISHED_TTL_MS);
550
+ }
551
+
552
+ export function getInstallJob(id) {
553
+ return jobs.get(id) || null;
554
+ }
555
+
556
+ export function cancelInstallJob(id) {
557
+ const job = jobs.get(id);
558
+ if (!job) return false;
559
+ if (job.status !== 'running') return false;
560
+ try { job.child?.kill(); } catch { /* noop */ }
561
+ job.status = 'error';
562
+ job.error = 'Install cancelled';
563
+ job.finishedAt = new Date().toISOString();
564
+ job.emitter.emit('done', buildDonePayload(job));
565
+ scheduleCleanup(job);
566
+ return true;
567
+ }
568
+
569
+ export function snapshotDonePayload(job) {
570
+ return buildDonePayload(job);
571
+ }