@pixelbyte-software/pixcode 1.34.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 (247) 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 -395
  10. package/dist/assets/index-B8w57E1r.css +32 -0
  11. package/dist/assets/index-CBdsvGSR.js +854 -0
  12. package/dist/clear-cache.html +85 -85
  13. package/dist/convert-icons.md +52 -52
  14. package/dist/favicon.svg +8 -8
  15. package/dist/generate-icons.js +48 -48
  16. package/dist/icons/codex-white.svg +3 -3
  17. package/dist/icons/codex.svg +3 -3
  18. package/dist/icons/cursor-white.svg +11 -11
  19. package/dist/icons/icon-128x128.svg +9 -9
  20. package/dist/icons/icon-144x144.svg +9 -9
  21. package/dist/icons/icon-152x152.svg +9 -9
  22. package/dist/icons/icon-192x192.svg +9 -9
  23. package/dist/icons/icon-384x384.svg +9 -9
  24. package/dist/icons/icon-512x512.svg +9 -9
  25. package/dist/icons/icon-72x72.svg +9 -9
  26. package/dist/icons/icon-96x96.svg +9 -9
  27. package/dist/icons/icon-template.svg +9 -9
  28. package/dist/icons/qwen-logo.svg +14 -14
  29. package/dist/index.html +59 -59
  30. package/dist/logo.svg +12 -12
  31. package/dist/manifest.json +60 -60
  32. package/dist/openapi.yaml +1693 -1311
  33. package/dist/sw.js +124 -124
  34. package/dist-server/server/claude-sdk.js +38 -7
  35. package/dist-server/server/claude-sdk.js.map +1 -1
  36. package/dist-server/server/cli.js +107 -112
  37. package/dist-server/server/cli.js.map +1 -1
  38. package/dist-server/server/daemon/manager.js +33 -33
  39. package/dist-server/server/daemon-manager.js +159 -112
  40. package/dist-server/server/daemon-manager.js.map +1 -1
  41. package/dist-server/server/database/json-store.js +8 -5
  42. package/dist-server/server/database/json-store.js.map +1 -1
  43. package/dist-server/server/index.js +31 -10
  44. package/dist-server/server/index.js.map +1 -1
  45. package/dist-server/server/modules/orchestration/a2a/adapter-registry.js +45 -19
  46. package/dist-server/server/modules/orchestration/a2a/adapter-registry.js.map +1 -1
  47. package/dist-server/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.js.map +1 -1
  48. package/dist-server/server/modules/orchestration/a2a/adapters/claude-code.adapter.js +1 -0
  49. package/dist-server/server/modules/orchestration/a2a/adapters/claude-code.adapter.js.map +1 -1
  50. package/dist-server/server/modules/orchestration/a2a/adapters/codex.adapter.js +202 -0
  51. package/dist-server/server/modules/orchestration/a2a/adapters/codex.adapter.js.map +1 -0
  52. package/dist-server/server/modules/orchestration/a2a/adapters/cursor.adapter.js +205 -0
  53. package/dist-server/server/modules/orchestration/a2a/adapters/cursor.adapter.js.map +1 -0
  54. package/dist-server/server/modules/orchestration/a2a/adapters/gemini.adapter.js +205 -0
  55. package/dist-server/server/modules/orchestration/a2a/adapters/gemini.adapter.js.map +1 -0
  56. package/dist-server/server/modules/orchestration/a2a/adapters/opencode.adapter.js +205 -0
  57. package/dist-server/server/modules/orchestration/a2a/adapters/opencode.adapter.js.map +1 -0
  58. package/dist-server/server/modules/orchestration/a2a/adapters/qwen.adapter.js +205 -0
  59. package/dist-server/server/modules/orchestration/a2a/adapters/qwen.adapter.js.map +1 -0
  60. package/dist-server/server/modules/orchestration/a2a/routes.js +298 -34
  61. package/dist-server/server/modules/orchestration/a2a/routes.js.map +1 -1
  62. package/dist-server/server/modules/orchestration/a2a/task-store.js +144 -0
  63. package/dist-server/server/modules/orchestration/a2a/task-store.js.map +1 -0
  64. package/dist-server/server/modules/orchestration/a2a/validator.js +16 -0
  65. package/dist-server/server/modules/orchestration/a2a/validator.js.map +1 -1
  66. package/dist-server/server/modules/orchestration/index.js +14 -0
  67. package/dist-server/server/modules/orchestration/index.js.map +1 -1
  68. package/dist-server/server/modules/orchestration/preview/port-watcher.js +90 -0
  69. package/dist-server/server/modules/orchestration/preview/port-watcher.js.map +1 -0
  70. package/dist-server/server/modules/orchestration/preview/preview-proxy.js +58 -0
  71. package/dist-server/server/modules/orchestration/preview/preview-proxy.js.map +1 -0
  72. package/dist-server/server/modules/orchestration/preview/types.js +2 -0
  73. package/dist-server/server/modules/orchestration/preview/types.js.map +1 -0
  74. package/dist-server/server/modules/orchestration/tasks/orchestration-task-store.js +37 -0
  75. package/dist-server/server/modules/orchestration/tasks/orchestration-task-store.js.map +1 -0
  76. package/dist-server/server/modules/orchestration/tasks/orchestration-task.routes.js +68 -0
  77. package/dist-server/server/modules/orchestration/tasks/orchestration-task.routes.js.map +1 -0
  78. package/dist-server/server/modules/orchestration/tasks/orchestration-task.service.js +128 -0
  79. package/dist-server/server/modules/orchestration/tasks/orchestration-task.service.js.map +1 -0
  80. package/dist-server/server/modules/orchestration/tasks/orchestration-task.types.js +2 -0
  81. package/dist-server/server/modules/orchestration/tasks/orchestration-task.types.js.map +1 -0
  82. package/dist-server/server/modules/orchestration/workflows/built-in-workflows.js +126 -0
  83. package/dist-server/server/modules/orchestration/workflows/built-in-workflows.js.map +1 -0
  84. package/dist-server/server/modules/orchestration/workflows/workflow-runner.js +1047 -0
  85. package/dist-server/server/modules/orchestration/workflows/workflow-runner.js.map +1 -0
  86. package/dist-server/server/modules/orchestration/workflows/workflow-store.js +76 -0
  87. package/dist-server/server/modules/orchestration/workflows/workflow-store.js.map +1 -0
  88. package/dist-server/server/modules/orchestration/workflows/workflow.routes.js +151 -0
  89. package/dist-server/server/modules/orchestration/workflows/workflow.routes.js.map +1 -0
  90. package/dist-server/server/modules/orchestration/workflows/workflow.types.js +2 -0
  91. package/dist-server/server/modules/orchestration/workflows/workflow.types.js.map +1 -0
  92. package/dist-server/server/modules/orchestration/workflows/workspace-target.js +98 -0
  93. package/dist-server/server/modules/orchestration/workflows/workspace-target.js.map +1 -0
  94. package/dist-server/server/modules/orchestration/workspace/docker-workspace.js +122 -0
  95. package/dist-server/server/modules/orchestration/workspace/docker-workspace.js.map +1 -0
  96. package/dist-server/server/modules/orchestration/workspace/path-safety.js +48 -0
  97. package/dist-server/server/modules/orchestration/workspace/path-safety.js.map +1 -0
  98. package/dist-server/server/modules/orchestration/workspace/types.js +11 -0
  99. package/dist-server/server/modules/orchestration/workspace/types.js.map +1 -0
  100. package/dist-server/server/modules/orchestration/workspace/workspace-manager.js +80 -0
  101. package/dist-server/server/modules/orchestration/workspace/workspace-manager.js.map +1 -0
  102. package/dist-server/server/modules/orchestration/workspace/worktree-workspace.js +96 -0
  103. package/dist-server/server/modules/orchestration/workspace/worktree-workspace.js.map +1 -0
  104. package/dist-server/server/modules/providers/index.js +3 -0
  105. package/dist-server/server/modules/providers/index.js.map +1 -0
  106. package/dist-server/server/openai-codex.js +35 -4
  107. package/dist-server/server/openai-codex.js.map +1 -1
  108. package/dist-server/server/routes/commands.js +25 -25
  109. package/dist-server/server/routes/git.js +17 -17
  110. package/dist-server/server/routes/taskmaster.js +525 -508
  111. package/dist-server/server/routes/taskmaster.js.map +1 -1
  112. package/package.json +180 -178
  113. package/scripts/fix-node-pty.js +67 -67
  114. package/scripts/smoke/a2a-roundtrip.mjs +86 -17
  115. package/scripts/smoke/orchestration-api.mjs +172 -0
  116. package/scripts/smoke/orchestration-live-run.mjs +176 -0
  117. package/server/claude-sdk.js +898 -857
  118. package/server/cli.js +935 -940
  119. package/server/constants/config.js +4 -4
  120. package/server/cursor-cli.js +342 -342
  121. package/server/daemon/manager.js +564 -564
  122. package/server/daemon-manager.js +959 -920
  123. package/server/database/db.js +794 -794
  124. package/server/database/json-store.js +197 -194
  125. package/server/gemini-cli.js +535 -535
  126. package/server/gemini-response-handler.js +79 -79
  127. package/server/index.js +3135 -3104
  128. package/server/load-env.js +34 -34
  129. package/server/middleware/auth.js +173 -173
  130. package/server/modules/orchestration/a2a/adapter-registry.ts +72 -22
  131. package/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.ts +9 -3
  132. package/server/modules/orchestration/a2a/adapters/claude-code.adapter.ts +1 -0
  133. package/server/modules/orchestration/a2a/adapters/codex.adapter.ts +244 -0
  134. package/server/modules/orchestration/a2a/adapters/cursor.adapter.ts +249 -0
  135. package/server/modules/orchestration/a2a/adapters/gemini.adapter.ts +248 -0
  136. package/server/modules/orchestration/a2a/adapters/opencode.adapter.ts +248 -0
  137. package/server/modules/orchestration/a2a/adapters/qwen.adapter.ts +248 -0
  138. package/server/modules/orchestration/a2a/routes.ts +349 -36
  139. package/server/modules/orchestration/a2a/task-store.ts +178 -0
  140. package/server/modules/orchestration/a2a/types.ts +14 -0
  141. package/server/modules/orchestration/a2a/validator.ts +25 -2
  142. package/server/modules/orchestration/index.ts +40 -0
  143. package/server/modules/orchestration/preview/port-watcher.ts +112 -0
  144. package/server/modules/orchestration/preview/preview-proxy.ts +60 -0
  145. package/server/modules/orchestration/preview/types.ts +19 -0
  146. package/server/modules/orchestration/tasks/orchestration-task-store.ts +45 -0
  147. package/server/modules/orchestration/tasks/orchestration-task.routes.ts +73 -0
  148. package/server/modules/orchestration/tasks/orchestration-task.service.ts +145 -0
  149. package/server/modules/orchestration/tasks/orchestration-task.types.ts +29 -0
  150. package/server/modules/orchestration/workflows/built-in-workflows.ts +127 -0
  151. package/server/modules/orchestration/workflows/workflow-runner.ts +1206 -0
  152. package/server/modules/orchestration/workflows/workflow-store.ts +97 -0
  153. package/server/modules/orchestration/workflows/workflow.routes.ts +169 -0
  154. package/server/modules/orchestration/workflows/workflow.types.ts +70 -0
  155. package/server/modules/orchestration/workflows/workspace-target.ts +120 -0
  156. package/server/modules/orchestration/workspace/docker-workspace.ts +135 -0
  157. package/server/modules/orchestration/workspace/path-safety.ts +55 -0
  158. package/server/modules/orchestration/workspace/types.ts +52 -0
  159. package/server/modules/orchestration/workspace/workspace-manager.ts +97 -0
  160. package/server/modules/orchestration/workspace/worktree-workspace.ts +125 -0
  161. package/server/modules/providers/index.ts +2 -0
  162. package/server/modules/providers/list/claude/claude-auth.provider.ts +145 -145
  163. package/server/modules/providers/list/claude/claude-mcp.provider.ts +135 -135
  164. package/server/modules/providers/list/claude/claude-sessions.provider.ts +306 -306
  165. package/server/modules/providers/list/claude/claude.provider.ts +15 -15
  166. package/server/modules/providers/list/codex/codex-auth.provider.ts +115 -115
  167. package/server/modules/providers/list/codex/codex-mcp.provider.ts +135 -135
  168. package/server/modules/providers/list/codex/codex-sessions.provider.ts +319 -319
  169. package/server/modules/providers/list/codex/codex.provider.ts +15 -15
  170. package/server/modules/providers/list/cursor/cursor-auth.provider.ts +143 -143
  171. package/server/modules/providers/list/cursor/cursor-mcp.provider.ts +108 -108
  172. package/server/modules/providers/list/cursor/cursor-sessions.provider.ts +421 -421
  173. package/server/modules/providers/list/cursor/cursor.provider.ts +15 -15
  174. package/server/modules/providers/list/gemini/gemini-auth.provider.ts +163 -163
  175. package/server/modules/providers/list/gemini/gemini-mcp.provider.ts +110 -110
  176. package/server/modules/providers/list/gemini/gemini-sessions.provider.ts +227 -227
  177. package/server/modules/providers/list/gemini/gemini.provider.ts +15 -15
  178. package/server/modules/providers/list/opencode/opencode-auth.provider.ts +130 -130
  179. package/server/modules/providers/list/opencode/opencode-mcp.provider.ts +126 -126
  180. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +232 -232
  181. package/server/modules/providers/list/opencode/opencode.provider.ts +29 -29
  182. package/server/modules/providers/list/qwen/qwen-auth.provider.ts +145 -145
  183. package/server/modules/providers/list/qwen/qwen-mcp.provider.ts +114 -114
  184. package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +265 -265
  185. package/server/modules/providers/list/qwen/qwen.provider.ts +21 -21
  186. package/server/modules/providers/provider.registry.ts +40 -40
  187. package/server/modules/providers/provider.routes.ts +819 -819
  188. package/server/modules/providers/services/mcp.service.ts +86 -86
  189. package/server/modules/providers/services/provider-auth.service.ts +26 -26
  190. package/server/modules/providers/services/sessions.service.ts +45 -45
  191. package/server/modules/providers/shared/base/abstract.provider.ts +20 -20
  192. package/server/modules/providers/shared/mcp/mcp.provider.ts +151 -151
  193. package/server/modules/providers/shared/provider-configs.ts +142 -142
  194. package/server/modules/providers/tests/mcp.test.ts +293 -293
  195. package/server/openai-codex.js +462 -426
  196. package/server/opencode-cli.js +459 -459
  197. package/server/opencode-response-handler.js +107 -107
  198. package/server/projects.js +3105 -3105
  199. package/server/qwen-code-cli.js +395 -395
  200. package/server/qwen-response-handler.js +73 -73
  201. package/server/routes/agent.js +1365 -1365
  202. package/server/routes/auth.js +138 -138
  203. package/server/routes/codex.js +19 -19
  204. package/server/routes/commands.js +554 -554
  205. package/server/routes/cursor.js +52 -52
  206. package/server/routes/gemini.js +24 -24
  207. package/server/routes/git.js +1488 -1488
  208. package/server/routes/mcp-utils.js +31 -31
  209. package/server/routes/messages.js +61 -61
  210. package/server/routes/network.js +120 -120
  211. package/server/routes/plugins.js +318 -318
  212. package/server/routes/projects.js +915 -915
  213. package/server/routes/qwen.js +27 -27
  214. package/server/routes/settings.js +286 -286
  215. package/server/routes/taskmaster.js +1496 -1471
  216. package/server/routes/telegram.js +125 -125
  217. package/server/routes/user.js +123 -123
  218. package/server/services/external-access.js +171 -171
  219. package/server/services/install-jobs.js +571 -571
  220. package/server/services/notification-orchestrator.js +242 -242
  221. package/server/services/provider-credentials.js +189 -189
  222. package/server/services/provider-models.js +381 -381
  223. package/server/services/telegram/bot.js +279 -279
  224. package/server/services/telegram/telegram-http-client.js +130 -130
  225. package/server/services/telegram/translations.js +170 -170
  226. package/server/services/vapid-keys.js +36 -36
  227. package/server/sessionManager.js +225 -225
  228. package/server/shared/interfaces.ts +54 -54
  229. package/server/shared/types.ts +172 -172
  230. package/server/shared/utils.ts +193 -193
  231. package/server/tsconfig.json +36 -36
  232. package/server/utils/colors.js +21 -21
  233. package/server/utils/commandParser.js +303 -303
  234. package/server/utils/frontmatter.js +18 -18
  235. package/server/utils/gitConfig.js +34 -34
  236. package/server/utils/mcp-detector.js +147 -147
  237. package/server/utils/plugin-loader.js +457 -457
  238. package/server/utils/plugin-process-manager.js +184 -184
  239. package/server/utils/port-access.js +209 -209
  240. package/server/utils/runtime-paths.js +37 -37
  241. package/server/utils/taskmaster-websocket.js +128 -128
  242. package/server/utils/url-detection.js +71 -71
  243. package/server/vite-daemon.js +78 -78
  244. package/shared/modelConstants.js +162 -162
  245. package/shared/networkHosts.js +22 -22
  246. package/dist/assets/index-B1ghfb4w.css +0 -32
  247. package/dist/assets/index-BvClqlMf.js +0 -852
@@ -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
+ }