@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
package/server/cli.js CHANGED
@@ -1,940 +1,935 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Pixcode CLI
4
- *
5
- * Provides command-line utilities for managing Pixcode
6
- *
7
- * Commands:
8
- * (no args) - Start the server (default)
9
- * start - Start the server
10
- * sandbox - Manage Docker sandbox environments
11
- * daemon - Manage persistent Linux service modes
12
- * status - Show configuration and data locations
13
- * help - Show help information
14
- * version - Show version information
15
- */
16
-
17
- import fs from 'fs';
18
- import path from 'path';
19
- import os from 'os';
20
- import net from 'node:net';
21
- import { findAppRoot, getModuleDir } from './utils/runtime-paths.js';
22
- import { buildDaemonCliCommand, handleDaemonCommand, hasInstalledDaemonUnit } from './daemon-manager.js';
23
-
24
- const __dirname = getModuleDir(import.meta.url);
25
- // The CLI is compiled into dist-server/server, but it still needs to read the top-level
26
- // package.json and .env file. Resolving the app root once keeps those lookups stable.
27
- const APP_ROOT = findAppRoot(__dirname);
28
- const DAEMON_COMMAND_CONTEXT = {
29
- appRoot: APP_ROOT,
30
- cliEntry: process.argv[1],
31
- nodeExecPath: process.execPath,
32
- };
33
-
34
- // ANSI color codes for terminal output
35
- const colors = {
36
- reset: '\x1b[0m',
37
- bright: '\x1b[1m',
38
- dim: '\x1b[2m',
39
-
40
- // Foreground colors
41
- cyan: '\x1b[36m',
42
- green: '\x1b[32m',
43
- yellow: '\x1b[33m',
44
- blue: '\x1b[34m',
45
- magenta: '\x1b[35m',
46
- white: '\x1b[37m',
47
- gray: '\x1b[90m',
48
- };
49
-
50
- // Helper to colorize text
51
- const c = {
52
- info: (text) => `${colors.cyan}${text}${colors.reset}`,
53
- ok: (text) => `${colors.green}${text}${colors.reset}`,
54
- warn: (text) => `${colors.yellow}${text}${colors.reset}`,
55
- error: (text) => `${colors.yellow}${text}${colors.reset}`,
56
- tip: (text) => `${colors.blue}${text}${colors.reset}`,
57
- bright: (text) => `${colors.bright}${text}${colors.reset}`,
58
- dim: (text) => `${colors.dim}${text}${colors.reset}`,
59
- };
60
-
61
- // Load package.json for version info
62
- const packageJsonPath = path.join(APP_ROOT, 'package.json');
63
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
64
- // Match the runtime fallback in load-env.js so "pixcode status" reports the same default
65
- // database location that the backend will actually use when no DATABASE_PATH is configured.
66
- const DEFAULT_DATABASE_PATH = path.join(os.homedir(), '.pixcode', 'auth.db');
67
-
68
- // Load environment variables from .env file if it exists
69
- function loadEnvFile() {
70
- try {
71
- const envPath = path.join(APP_ROOT, '.env');
72
- const envFile = fs.readFileSync(envPath, 'utf8');
73
- envFile.split('\n').forEach(line => {
74
- const trimmedLine = line.trim();
75
- if (trimmedLine && !trimmedLine.startsWith('#')) {
76
- const [key, ...valueParts] = trimmedLine.split('=');
77
- if (key && valueParts.length > 0 && !process.env[key]) {
78
- process.env[key] = valueParts.join('=').trim();
79
- }
80
- }
81
- });
82
- } catch (e) {
83
- // .env file is optional
84
- }
85
- }
86
-
87
- // Get the database path (same logic as db.js)
88
- function getDatabasePath() {
89
- loadEnvFile();
90
- return process.env.DATABASE_PATH || DEFAULT_DATABASE_PATH;
91
- }
92
-
93
- // Get the installation directory
94
- function getInstallDir() {
95
- return APP_ROOT;
96
- }
97
-
98
- // Show status command
99
- function showStatus() {
100
- console.log(`\n${c.bright('Pixcode - Status')}\n`);
101
- console.log(c.dim('═'.repeat(60)));
102
-
103
- // Version info
104
- console.log(`\n${c.info('[INFO]')} Version: ${c.bright(packageJson.version)}`);
105
-
106
- // Installation location
107
- const installDir = getInstallDir();
108
- console.log(`\n${c.info('[INFO]')} Installation Directory:`);
109
- console.log(` ${c.dim(installDir)}`);
110
-
111
- // Database location
112
- const dbPath = getDatabasePath();
113
- const dbExists = fs.existsSync(dbPath);
114
- console.log(`\n${c.info('[INFO]')} Database Location:`);
115
- console.log(` ${c.dim(dbPath)}`);
116
- console.log(` Status: ${dbExists ? c.ok('[OK] Exists') : c.warn('[WARN] Not created yet (will be created on first run)')}`);
117
-
118
- if (dbExists) {
119
- const stats = fs.statSync(dbPath);
120
- console.log(` Size: ${c.dim((stats.size / 1024).toFixed(2) + ' KB')}`);
121
- console.log(` Modified: ${c.dim(stats.mtime.toLocaleString())}`);
122
- }
123
-
124
- // Environment variables
125
- console.log(`\n${c.info('[INFO]')} Configuration:`);
126
- console.log(` SERVER_PORT: ${c.bright(process.env.SERVER_PORT || process.env.PORT || '3001')} ${c.dim(process.env.SERVER_PORT || process.env.PORT ? '' : '(default)')}`);
127
- console.log(` DATABASE_PATH: ${c.dim(process.env.DATABASE_PATH || '(using default location)')}`);
128
- console.log(` CLAUDE_CLI_PATH: ${c.dim(process.env.CLAUDE_CLI_PATH || 'claude (default)')}`);
129
- console.log(` CONTEXT_WINDOW: ${c.dim(process.env.CONTEXT_WINDOW || '160000 (default)')}`);
130
-
131
- // Claude projects folder
132
- const claudeProjectsPath = path.join(os.homedir(), '.claude', 'projects');
133
- const projectsExists = fs.existsSync(claudeProjectsPath);
134
- console.log(`\n${c.info('[INFO]')} Claude Projects Folder:`);
135
- console.log(` ${c.dim(claudeProjectsPath)}`);
136
- console.log(` Status: ${projectsExists ? c.ok('[OK] Exists') : c.warn('[WARN] Not found')}`);
137
-
138
- // Config file location
139
- const envFilePath = path.join(APP_ROOT, '.env');
140
- const envExists = fs.existsSync(envFilePath);
141
- console.log(`\n${c.info('[INFO]')} Configuration File:`);
142
- console.log(` ${c.dim(envFilePath)}`);
143
- // Missing .env is fine — Pixcode ships sensible defaults. Keep this
144
- // purely informational so users don't misread an "[INFO] optional"
145
- // line as an install-time failure.
146
- console.log(` Status: ${envExists ? c.ok('[OK] Exists') : c.info('[INFO] Optional — running on defaults')}`);
147
-
148
- console.log('\n' + c.dim('═'.repeat(60)));
149
- console.log(`\n${c.tip('[TIP]')} Hints:`);
150
- console.log(` ${c.dim('>')} Use ${c.bright('pixcode --port 8080')} to run on a custom port`);
151
- console.log(` ${c.dim('>')} Use ${c.bright('pixcode --database-path /path/to/db')} for custom database`);
152
- console.log(` ${c.dim('>')} Run ${c.bright('pixcode help')} for all options`);
153
- console.log(` ${c.dim('>')} Access the UI at http://localhost:${process.env.SERVER_PORT || process.env.PORT || '3001'}\n`);
154
- }
155
-
156
- // Show help
157
- function showHelp() {
158
- console.log(`
159
- ╔═══════════════════════════════════════════════════════════════╗
160
- ║ Pixcode - Command Line Tool ║
161
- ╚═══════════════════════════════════════════════════════════════╝
162
-
163
- Usage:
164
- pixcode [command] [options]
165
-
166
- Commands:
167
- start Start the Pixcode server (default)
168
- daemon Manage persistent Linux service (system-first)
169
- sandbox Manage Docker sandbox environments
170
- status Show configuration and data locations
171
- update Update to the latest version
172
- help Show this help information
173
- version Show version information
174
-
175
- Options:
176
- -p, --port <port> Set server port (default: 3001)
177
- --database-path <path> Set custom database location
178
- --no-daemon Disable automatic daemon startup on Linux
179
- --restart-daemon Restart daemon automatically after update
180
- -h, --help Show this help information
181
- -v, --version Show version information
182
-
183
- Examples:
184
- $ pixcode # Start with defaults
185
- $ pixcode --port 8080 # Start on port 8080
186
- $ pixcode --no-daemon # Force foreground mode
187
- $ sudo pixcode daemon install --mode system --port 3001
188
- $ pixcode daemon install --mode user --port 3001 --frontend-port 5173
189
- $ pixcode daemon doctor --mode system
190
- $ pixcode update --restart-daemon
191
- $ pixcode sandbox ~/my-project # Run in a Docker sandbox
192
- $ pixcode status # Show configuration
193
-
194
- Environment Variables:
195
- SERVER_PORT Set server port (default: 3001)
196
- PORT Set server port (default: 3001) (LEGACY)
197
- DATABASE_PATH Set custom database location
198
- CLAUDE_CLI_PATH Set custom Claude CLI path
199
- CONTEXT_WINDOW Set context window size (default: 160000)
200
-
201
- Documentation:
202
- ${packageJson.homepage || 'https://github.com/alicomert/pixcode'}
203
-
204
- Report Issues:
205
- ${packageJson.bugs?.url || 'https://github.com/alicomert/pixcode/issues'}
206
- `);
207
- }
208
-
209
- // Show version
210
- function showVersion() {
211
- console.log(`${packageJson.version}`);
212
- }
213
-
214
- // Compare semver versions, returns true if v1 > v2
215
- function isNewerVersion(v1, v2) {
216
- const parts1 = v1.split('.').map(Number);
217
- const parts2 = v2.split('.').map(Number);
218
- for (let i = 0; i < 3; i++) {
219
- if (parts1[i] > parts2[i]) return true;
220
- if (parts1[i] < parts2[i]) return false;
221
- }
222
- return false;
223
- }
224
-
225
- // Check for updates
226
- async function checkForUpdates(silent = false) {
227
- try {
228
- const { execSync } = await import('child_process');
229
- const latestVersion = execSync('npm show @pixelbyte-software/pixcode version', { encoding: 'utf8' }).trim();
230
- const currentVersion = packageJson.version;
231
-
232
- if (isNewerVersion(latestVersion, currentVersion)) {
233
- console.log(`\n${c.warn('[UPDATE]')} New version available: ${c.bright(latestVersion)} (current: ${currentVersion})`);
234
- console.log(` Run ${c.bright('pixcode update')} to update\n`);
235
- return { hasUpdate: true, latestVersion, currentVersion };
236
- } else if (!silent) {
237
- console.log(`${c.ok('[OK]')} You are on the latest version (${currentVersion})`);
238
- }
239
- return { hasUpdate: false, latestVersion, currentVersion };
240
- } catch (e) {
241
- if (!silent) {
242
- console.log(`${c.warn('[WARN]')} Could not check for updates`);
243
- }
244
- return { hasUpdate: false, error: e.message };
245
- }
246
- }
247
-
248
- // Update the package
249
- async function updatePackage(options = {}) {
250
- try {
251
- const { execSync } = await import('child_process');
252
- console.log(`${c.info('[INFO]')} Checking for updates...`);
253
-
254
- const { hasUpdate, latestVersion, currentVersion } = await checkForUpdates(true);
255
-
256
- if (!hasUpdate) {
257
- console.log(`${c.ok('[OK]')} Already on the latest version (${currentVersion})`);
258
- return;
259
- }
260
-
261
- console.log(`${c.info('[INFO]')} Updating from ${currentVersion} to ${latestVersion}...`);
262
- execSync('npm update -g @pixelbyte-software/pixcode', { stdio: 'inherit' });
263
- console.log(`${c.ok('[OK]')} Update complete!`);
264
-
265
- if (options.restartDaemon) {
266
- if (!hasInstalledDaemonUnit()) {
267
- console.log(`${c.warn('[WARN]')} No daemon unit detected; skipping restart.`);
268
- return;
269
- }
270
- console.log(`${c.info('[INFO]')} Restarting daemon service...`);
271
- await handleDaemonCommand(['restart', '--mode=system'], {
272
- appRoot: APP_ROOT,
273
- defaultPort: process.env.SERVER_PORT || process.env.PORT || '3001',
274
- color: c,
275
- });
276
- console.log(`${c.ok('[OK]')} Daemon restart completed.`);
277
- } else if (hasInstalledDaemonUnit()) {
278
- const restartCommand = buildDaemonCliCommand(
279
- { subcommand: 'restart', mode: 'system' },
280
- DAEMON_COMMAND_CONTEXT
281
- );
282
- console.log(`${c.tip('[TIP]')} Daemon unit detected. Restart to apply update: ${c.bright(restartCommand)}`);
283
- console.log(`${c.tip('[TIP]')} Or update + restart in one step: ${c.bright('pixcode update --restart-daemon')}`);
284
- } else {
285
- console.log(`${c.tip('[TIP]')} Restart pixcode to use the new version.`);
286
- }
287
- } catch (e) {
288
- console.error(`${c.error('[ERROR]')} Update failed: ${e.message}`);
289
- console.log(`${c.tip('[TIP]')} Try running manually: npm update -g @pixelbyte-software/pixcode`);
290
- }
291
- }
292
-
293
- // ── Sandbox command ─────────────────────────────────────────
294
-
295
- const SANDBOX_TEMPLATES = {
296
- claude: 'ghcr.io/alicomert/pixcode-sandbox:claude-code',
297
- codex: 'ghcr.io/alicomert/pixcode-sandbox:codex',
298
- gemini: 'ghcr.io/alicomert/pixcode-sandbox:gemini',
299
- };
300
-
301
- const SANDBOX_SECRETS = {
302
- claude: 'anthropic',
303
- codex: 'openai',
304
- gemini: 'google',
305
- };
306
-
307
- function parseSandboxArgs(args) {
308
- const result = {
309
- subcommand: null,
310
- workspace: null,
311
- agent: 'claude',
312
- name: null,
313
- port: 3001,
314
- template: null,
315
- env: [],
316
- };
317
-
318
- const subcommands = ['ls', 'stop', 'start', 'rm', 'logs', 'help'];
319
-
320
- for (let i = 0; i < args.length; i++) {
321
- const arg = args[i];
322
-
323
- if (i === 0 && subcommands.includes(arg)) {
324
- result.subcommand = arg;
325
- } else if (arg === '--agent' || arg === '-a') {
326
- result.agent = args[++i];
327
- } else if (arg === '--name' || arg === '-n') {
328
- result.name = args[++i];
329
- } else if (arg === '--port') {
330
- result.port = parseInt(args[++i], 10);
331
- } else if (arg === '--template' || arg === '-t') {
332
- result.template = args[++i];
333
- } else if (arg === '--env' || arg === '-e') {
334
- result.env.push(args[++i]);
335
- } else if (!arg.startsWith('-')) {
336
- if (!result.subcommand) {
337
- result.workspace = arg;
338
- } else {
339
- result.name = arg; // for stop/start/rm/logs <name>
340
- }
341
- }
342
- }
343
-
344
- // Default subcommand based on what we got
345
- if (!result.subcommand) {
346
- result.subcommand = 'create';
347
- }
348
-
349
- // Derive name from workspace path if not set
350
- if (!result.name && result.workspace) {
351
- result.name = path.basename(path.resolve(result.workspace.replace(/^~/, os.homedir())));
352
- }
353
-
354
- // Default template from agent
355
- if (!result.template) {
356
- result.template = SANDBOX_TEMPLATES[result.agent] || SANDBOX_TEMPLATES.claude;
357
- }
358
-
359
- return result;
360
- }
361
-
362
- function showSandboxHelp() {
363
- console.log(`
364
- ${c.bright('Pixcode Sandbox')} — Run Pixcode inside Docker Sandboxes
365
-
366
- Usage:
367
- pixcode sandbox <workspace> Create and start a sandbox
368
- pixcode sandbox <subcommand> [name] Manage sandboxes
369
-
370
- Subcommands:
371
- ${c.bright('(default)')} Create a sandbox and start the web UI
372
- ${c.bright('ls')} List all sandboxes
373
- ${c.bright('start')} Restart a stopped sandbox and re-launch the web UI
374
- ${c.bright('stop')} Stop a sandbox (preserves state)
375
- ${c.bright('rm')} Remove a sandbox
376
- ${c.bright('logs')} Show Pixcode server logs
377
- ${c.bright('help')} Show this help
378
-
379
- Options:
380
- -a, --agent <agent> Agent to use: claude, codex, gemini (default: claude)
381
- -n, --name <name> Sandbox name (default: derived from workspace folder)
382
- -t, --template <image> Custom template image
383
- -e, --env <KEY=VALUE> Set environment variable (repeatable)
384
- --port <port> Host port for the web UI (default: 3001)
385
-
386
- Examples:
387
- $ pixcode sandbox ~/my-project
388
- $ pixcode sandbox ~/my-project --agent codex --port 8080
389
- $ pixcode sandbox ~/my-project --env SERVER_PORT=8080 --env HOST=0.0.0.0
390
- $ pixcode sandbox ls
391
- $ pixcode sandbox stop my-project
392
- $ pixcode sandbox start my-project
393
- $ pixcode sandbox rm my-project
394
-
395
- Prerequisites:
396
- 1. Install sbx CLI: https://docs.docker.com/ai/sandboxes/get-started/
397
- 2. Authenticate and store your API key:
398
- sbx login
399
- sbx secret set -g anthropic # for Claude
400
- sbx secret set -g openai # for Codex
401
- sbx secret set -g google # for Gemini
402
-
403
- Advanced usage:
404
- For branch mode, multiple workspaces, memory limits, network policies,
405
- or passing prompts to the agent, use sbx directly with the template:
406
-
407
- sbx run --template ghcr.io/alicomert/pixcode-sandbox:claude-code claude ~/my-project --branch my-feature
408
- sbx run --template ghcr.io/alicomert/pixcode-sandbox:claude-code claude ~/project ~/libs:ro --memory 8g
409
-
410
- Full Docker Sandboxes docs: https://docs.docker.com/ai/sandboxes/usage/
411
- `);
412
- }
413
-
414
- async function sandboxCommand(args) {
415
- const { execFileSync, spawn: spawnProcess } = await import('child_process');
416
-
417
- // Safe execution — uses execFileSync (no shell) to prevent injection
418
- const sbx = (subcmd, opts = {}) => {
419
- const result = execFileSync('sbx', subcmd, {
420
- encoding: 'utf8',
421
- stdio: opts.inherit ? 'inherit' : 'pipe',
422
- });
423
- return result || '';
424
- };
425
-
426
- const opts = parseSandboxArgs(args);
427
-
428
- if (opts.subcommand === 'help') {
429
- showSandboxHelp();
430
- return;
431
- }
432
-
433
- // Validate name (alphanumeric, hyphens, underscores only)
434
- if (opts.name && !/^[\w-]+$/.test(opts.name)) {
435
- console.error(`\n${c.error('❌')} Invalid sandbox name: ${opts.name}`);
436
- console.log(` Names may only contain letters, numbers, hyphens, and underscores.\n`);
437
- process.exit(1);
438
- }
439
-
440
- // Check sbx is installed
441
- try {
442
- sbx(['version']);
443
- } catch {
444
- console.error(`\n${c.error('❌')} ${c.bright('sbx')} CLI not found.\n`);
445
- console.log(` Install it from: ${c.info('https://docs.docker.com/ai/sandboxes/get-started/')}`);
446
- console.log(` Then run: ${c.bright('sbx login')}`);
447
- console.log(` And store your API key: ${c.bright('sbx secret set -g anthropic')}\n`);
448
- process.exit(1);
449
- }
450
-
451
- switch (opts.subcommand) {
452
-
453
- case 'ls':
454
- sbx(['ls'], { inherit: true });
455
- break;
456
-
457
- case 'stop':
458
- if (!opts.name) {
459
- console.error(`\n${c.error('❌')} Sandbox name required: pixcode sandbox stop <name>\n`);
460
- process.exit(1);
461
- }
462
- sbx(['stop', opts.name], { inherit: true });
463
- break;
464
-
465
- case 'rm':
466
- if (!opts.name) {
467
- console.error(`\n${c.error('❌')} Sandbox name required: pixcode sandbox rm <name>\n`);
468
- process.exit(1);
469
- }
470
- sbx(['rm', opts.name], { inherit: true });
471
- break;
472
-
473
- case 'logs':
474
- if (!opts.name) {
475
- console.error(`\n${c.error('❌')} Sandbox name required: pixcode sandbox logs <name>\n`);
476
- process.exit(1);
477
- }
478
- try {
479
- sbx(['exec', opts.name, 'bash', '-c', 'cat /tmp/pixcode-ui.log'], { inherit: true });
480
- } catch (e) {
481
- console.error(`\n${c.error('❌')} Could not read logs: ${e.message || 'Is the sandbox running?'}\n`);
482
- }
483
- break;
484
-
485
- case 'start': {
486
- if (!opts.name) {
487
- console.error(`\n${c.error('❌')} Sandbox name required: pixcode sandbox start <name>\n`);
488
- process.exit(1);
489
- }
490
- console.log(`\n${c.info('▶')} Starting sandbox ${c.bright(opts.name)}...`);
491
- const restartRun = spawnProcess('sbx', ['run', opts.name], {
492
- detached: true,
493
- stdio: ['ignore', 'ignore', 'ignore'],
494
- });
495
- restartRun.unref();
496
- await new Promise(resolve => setTimeout(resolve, 5000));
497
-
498
- console.log(`${c.info('▶')} Launching Pixcode web server...`);
499
- sbx(['exec', opts.name, 'bash', '-c', 'pixcode start --port 3001 &']);
500
-
501
- console.log(`${c.info('▶')} Forwarding port ${opts.port} → 3001...`);
502
- try {
503
- sbx(['ports', opts.name, '--publish', `${opts.port}:3001`]);
504
- } catch (e) {
505
- const msg = e.stdout || e.stderr || e.message || '';
506
- if (msg.includes('address already in use')) {
507
- const altPort = opts.port + 1;
508
- console.log(`${c.warn('⚠')} Port ${opts.port} in use, trying ${altPort}...`);
509
- try {
510
- sbx(['ports', opts.name, '--publish', `${altPort}:3001`]);
511
- opts.port = altPort;
512
- } catch {
513
- console.error(`${c.error('❌')} Ports ${opts.port} and ${altPort} both in use. Use --port to specify a free port.`);
514
- process.exit(1);
515
- }
516
- } else {
517
- throw e;
518
- }
519
- }
520
-
521
- console.log(`\n${c.ok('✔')} ${c.bright('Pixcode is ready!')}`);
522
- console.log(` ${c.info('→')} ${c.bright(`http://localhost:${opts.port}`)}\n`);
523
- break;
524
- }
525
-
526
- case 'create': {
527
- if (!opts.workspace) {
528
- console.error(`\n${c.error('❌')} Workspace path required: pixcode sandbox <path>\n`);
529
- console.log(` Example: ${c.bright('pixcode sandbox ~/my-project')}\n`);
530
- process.exit(1);
531
- }
532
-
533
- const workspace = opts.workspace.startsWith('~')
534
- ? opts.workspace.replace(/^~/, os.homedir())
535
- : path.resolve(opts.workspace);
536
-
537
- if (!fs.existsSync(workspace)) {
538
- console.error(`\n${c.error('❌')} Workspace path not found: ${c.dim(workspace)}\n`);
539
- process.exit(1);
540
- }
541
-
542
- const secret = SANDBOX_SECRETS[opts.agent] || 'anthropic';
543
-
544
- // Check if the required secret is stored
545
- try {
546
- const secretList = sbx(['secret', 'ls']);
547
- if (!secretList.includes(secret)) {
548
- console.error(`\n${c.error('❌')} No ${c.bright(secret)} API key found.\n`);
549
- console.log(` Run: ${c.bright(`sbx secret set -g ${secret}`)}\n`);
550
- process.exit(1);
551
- }
552
- } catch { /* sbx secret ls not available, skip check */ }
553
-
554
- console.log(`\n${c.bright('Pixcode Sandbox')}`);
555
- console.log(c.dim('─'.repeat(50)));
556
- console.log(` Agent: ${c.info(opts.agent)} ${c.dim(`(${secret} credentials)`)}`);
557
- console.log(` Workspace: ${c.dim(workspace)}`);
558
- console.log(` Name: ${c.dim(opts.name)}`);
559
- console.log(` Template: ${c.dim(opts.template)}`);
560
- console.log(` Port: ${c.dim(String(opts.port))}`);
561
- if (opts.env.length > 0) {
562
- console.log(` Env: ${c.dim(opts.env.join(', '))}`);
563
- }
564
- console.log(c.dim('─'.repeat(50)));
565
-
566
- // Step 1: Launch sandbox with sbx run in background.
567
- // sbx run creates the sandbox (or reconnects) AND holds an active session,
568
- // which prevents the sandbox from auto-stopping.
569
- console.log(`\n${c.info('▶')} Creating sandbox ${c.bright(opts.name)}...`);
570
- const bgRun = spawnProcess('sbx', [
571
- 'run', '--template', opts.template, '--name', opts.name, opts.agent, workspace,
572
- ], {
573
- detached: true,
574
- stdio: ['ignore', 'ignore', 'ignore'],
575
- });
576
- bgRun.unref();
577
- // Wait for sandbox to be ready
578
- await new Promise(resolve => setTimeout(resolve, 5000));
579
-
580
- // Step 2: Inject environment variables
581
- if (opts.env.length > 0) {
582
- console.log(`${c.info('▶')} Setting environment variables...`);
583
- const exports = opts.env
584
- .filter(e => /^\w+=.+$/.test(e))
585
- .map(e => `export ${e}`)
586
- .join('\n');
587
- if (exports) {
588
- sbx(['exec', opts.name, 'bash', '-c', `echo '${exports}' >> /etc/sandbox-persistent.sh`]);
589
- }
590
- const invalid = opts.env.filter(e => !/^\w+=.+$/.test(e));
591
- if (invalid.length > 0) {
592
- console.log(`${c.warn('⚠')} Skipped invalid env vars: ${invalid.join(', ')} (expected KEY=VALUE)`);
593
- }
594
- }
595
-
596
- // Step 3: Start Pixcode inside the sandbox
597
- console.log(`${c.info('▶')} Launching Pixcode web server...`);
598
- sbx(['exec', opts.name, 'bash', '-c', 'pixcode start --port 3001 &']);
599
-
600
- // Step 4: Forward port
601
- console.log(`${c.info('▶')} Forwarding port ${opts.port} → 3001...`);
602
- try {
603
- sbx(['ports', opts.name, '--publish', `${opts.port}:3001`]);
604
- } catch (e) {
605
- const msg = e.stdout || e.stderr || e.message || '';
606
- if (msg.includes('address already in use')) {
607
- const altPort = opts.port + 1;
608
- console.log(`${c.warn('⚠')} Port ${opts.port} in use, trying ${altPort}...`);
609
- try {
610
- sbx(['ports', opts.name, '--publish', `${altPort}:3001`]);
611
- opts.port = altPort;
612
- } catch {
613
- console.error(`${c.error('❌')} Ports ${opts.port} and ${altPort} both in use. Use --port to specify a free port.`);
614
- process.exit(1);
615
- }
616
- } else {
617
- throw e;
618
- }
619
- }
620
-
621
- // Done
622
- console.log(`\n${c.ok('✔')} ${c.bright('Pixcode is ready!')}`);
623
- console.log(` ${c.info('→')} Open ${c.bright(`http://localhost:${opts.port}`)}`);
624
- console.log(`\n${c.dim(' Manage with:')}`);
625
- console.log(` ${c.dim('$')} sbx ls`);
626
- console.log(` ${c.dim('$')} sbx stop ${opts.name}`);
627
- console.log(` ${c.dim('$')} sbx start ${opts.name}`);
628
- console.log(` ${c.dim('$')} sbx rm ${opts.name}`);
629
- console.log(`\n${c.dim(' Or install globally:')} npm install -g @pixelbyte-software/pixcode\n`);
630
- break;
631
- }
632
-
633
- default:
634
- showSandboxHelp();
635
- }
636
- }
637
-
638
- // ── Server ──────────────────────────────────────────────────
639
-
640
- // Start the server
641
- async function startServer() {
642
- // Check for updates silently on startup
643
- checkForUpdates(true);
644
-
645
- // Import and run the server
646
- await import('./index.js');
647
- }
648
-
649
- async function isPortOpen(port, timeoutMs = 800) {
650
- return await new Promise((resolve) => {
651
- const socket = net.createConnection({ host: '127.0.0.1', port: Number(port) });
652
- let settled = false;
653
- const done = (value) => {
654
- if (settled) return;
655
- settled = true;
656
- socket.destroy();
657
- resolve(value);
658
- };
659
-
660
- socket.setTimeout(timeoutMs);
661
- socket.once('connect', () => done(true));
662
- socket.once('timeout', () => done(false));
663
- socket.once('error', () => done(false));
664
- });
665
- }
666
-
667
- async function waitForPortOpen(port, timeoutMs = 25000) {
668
- const deadline = Date.now() + timeoutMs;
669
- while (Date.now() < deadline) {
670
- if (await isPortOpen(port)) {
671
- return true;
672
- }
673
- await new Promise(resolve => setTimeout(resolve, 1000));
674
- }
675
- return false;
676
- }
677
-
678
- function printSystemDaemonActiveNotice(port) {
679
- const effectivePort = Number(port) || 3001;
680
- const statusCommand = buildDaemonCliCommand(
681
- { subcommand: 'status', mode: 'system' },
682
- DAEMON_COMMAND_CONTEXT
683
- );
684
- const stopCommand = buildDaemonCliCommand(
685
- { subcommand: 'stop', mode: 'system' },
686
- DAEMON_COMMAND_CONTEXT
687
- );
688
- const logsCommand = buildDaemonCliCommand(
689
- { subcommand: 'logs', mode: 'system' },
690
- DAEMON_COMMAND_CONTEXT
691
- );
692
- console.log(`${c.ok('[OK]')} System daemon is active and managing Pixcode.`);
693
- console.log(`${c.info('[INFO]')} Health URL: ${c.bright(`http://localhost:${effectivePort}/health`)}`);
694
- console.log(`${c.info('[INFO]')} Status: ${c.bright(statusCommand)}`);
695
- console.log(`${c.info('[INFO]')} Stop: ${c.bright(stopCommand)}`);
696
- console.log(`${c.info('[INFO]')} Logs: ${c.bright(logsCommand)}`);
697
- }
698
-
699
- function printUserDaemonActiveNotice(port, frontendPort) {
700
- const effectivePort = Number(port) || 3001;
701
- const effectiveFrontendPort = Number(frontendPort) || 5173;
702
- const statusCommand = buildDaemonCliCommand(
703
- { subcommand: 'status', mode: 'user' },
704
- DAEMON_COMMAND_CONTEXT
705
- );
706
- const stopCommand = buildDaemonCliCommand(
707
- { subcommand: 'stop', mode: 'user' },
708
- DAEMON_COMMAND_CONTEXT
709
- );
710
- const logsCommand = buildDaemonCliCommand(
711
- { subcommand: 'logs', mode: 'user' },
712
- DAEMON_COMMAND_CONTEXT
713
- );
714
- console.log(`${c.ok('[OK]')} User daemon is active for this account.`);
715
- console.log(`${c.info('[INFO]')} Backend: ${c.bright(`http://localhost:${effectivePort}`)}`);
716
- console.log(`${c.info('[INFO]')} Frontend: ${c.bright(`http://localhost:${effectiveFrontendPort}`)}`);
717
- console.log(`${c.info('[INFO]')} Status: ${c.bright(statusCommand)}`);
718
- console.log(`${c.info('[INFO]')} Stop: ${c.bright(stopCommand)}`);
719
- console.log(`${c.info('[INFO]')} Logs: ${c.bright(logsCommand)}`);
720
- console.log(`${c.tip('[TIP]')} For login/reboot persistence, enable linger once: ${c.bright(`sudo loginctl enable-linger ${os.userInfo().username}`)}`);
721
- }
722
-
723
- function isSystemPermissionError(error) {
724
- const message = String(error?.message || error || '');
725
- return /(access denied|permission denied|must be root|interactive authentication required|not permitted|failed to connect to bus|operation not permitted|authentication is required|polkit)/i.test(message);
726
- }
727
-
728
- function buildAutoInstallArgs(mode, options, frontendPort) {
729
- const args = ['install', `--mode=${mode}`];
730
- if (options.serverPort) {
731
- args.push('--port', String(options.serverPort));
732
- }
733
- if (options.databasePath) {
734
- args.push('--database-path', String(options.databasePath));
735
- }
736
- if (frontendPort) {
737
- args.push('--frontend-port', String(frontendPort));
738
- }
739
- return args;
740
- }
741
-
742
- async function maybeAutoDaemonStart(options = {}) {
743
- if (process.platform !== 'linux') return false;
744
- if (process.env.PIXCODE_DAEMON_MANAGED === '1') return false;
745
- if (process.env.PIXCODE_NO_DAEMON === '1') return false;
746
- if (process.env.PIXCODE_DAEMON_ATTEMPTED === '1') return false;
747
- if (options.noDaemon) return false;
748
-
749
- process.env.PIXCODE_DAEMON_ATTEMPTED = '1';
750
- const daemonPort = Number(options.serverPort || process.env.SERVER_PORT || process.env.PORT || '3001');
751
- const frontendPort = Number(process.env.VITE_PORT || '5173');
752
- const systemArgs = buildAutoInstallArgs('system', options, frontendPort);
753
- const userArgs = buildAutoInstallArgs('user', options, frontendPort);
754
-
755
- try {
756
- console.log(`${c.info('[INFO]')} Linux detected. Enforcing system daemon mode for Pixcode...`);
757
- await handleDaemonCommand(systemArgs, {
758
- appRoot: APP_ROOT,
759
- defaultPort: process.env.SERVER_PORT || process.env.PORT || '3001',
760
- color: c,
761
- });
762
- return true;
763
- } catch (systemError) {
764
- const healthySoon = await waitForPortOpen(daemonPort);
765
- if (healthySoon) {
766
- console.log(`${c.warn('[WARN]')} System daemon health check was delayed, but port ${daemonPort} is now reachable.`);
767
- printSystemDaemonActiveNotice(daemonPort);
768
- return true;
769
- }
770
-
771
- if (!isSystemPermissionError(systemError)) {
772
- const installSystemCommand = buildDaemonCliCommand(
773
- {
774
- subcommand: 'install',
775
- mode: 'system',
776
- extraArgs: ['--port', String(daemonPort), '--frontend-port', String(frontendPort)],
777
- },
778
- DAEMON_COMMAND_CONTEXT
779
- );
780
- throw new Error(
781
- `System daemon bootstrap failed.\n` +
782
- `${systemError.message}\n` +
783
- `Run with privileges: ${installSystemCommand}`
784
- );
785
- }
786
-
787
- console.log(`${c.warn('[WARN]')} System daemon setup requires elevated privileges for this user.`);
788
- console.log(`${c.info('[INFO]')} Falling back to user daemon mode for account "${os.userInfo().username}"...`);
789
-
790
- try {
791
- await handleDaemonCommand(userArgs, {
792
- appRoot: APP_ROOT,
793
- defaultPort: process.env.SERVER_PORT || process.env.PORT || '3001',
794
- color: c,
795
- });
796
- printUserDaemonActiveNotice(daemonPort, frontendPort);
797
- return true;
798
- } catch (userError) {
799
- const userHealthySoon = await waitForPortOpen(daemonPort);
800
- if (userHealthySoon) {
801
- console.log(`${c.warn('[WARN]')} User daemon health check was delayed, but port ${daemonPort} is now reachable.`);
802
- printUserDaemonActiveNotice(daemonPort, frontendPort);
803
- return true;
804
- }
805
- const installSystemCommand = buildDaemonCliCommand(
806
- {
807
- subcommand: 'install',
808
- mode: 'system',
809
- extraArgs: ['--port', String(daemonPort), '--frontend-port', String(frontendPort)],
810
- },
811
- DAEMON_COMMAND_CONTEXT
812
- );
813
- const installUserCommand = buildDaemonCliCommand(
814
- {
815
- subcommand: 'install',
816
- mode: 'user',
817
- extraArgs: ['--port', String(daemonPort), '--frontend-port', String(frontendPort)],
818
- },
819
- DAEMON_COMMAND_CONTEXT
820
- );
821
- throw new Error(
822
- `System daemon bootstrap failed.\n` +
823
- `${systemError.message}\n\n` +
824
- `User daemon fallback also failed.\n` +
825
- `${userError.message}\n` +
826
- `Try one of:\n` +
827
- `1) ${installSystemCommand}\n` +
828
- `2) ${installUserCommand}`
829
- );
830
- }
831
- }
832
- }
833
-
834
- // Parse CLI arguments
835
- function parseArgs(args) {
836
- const parsed = { command: 'start', options: {} };
837
- let commandSet = false;
838
-
839
- for (let i = 0; i < args.length; i++) {
840
- const arg = args[i];
841
-
842
- if (arg === '--port' || arg === '-p') {
843
- parsed.options.serverPort = args[++i];
844
- } else if (arg.startsWith('--port=')) {
845
- parsed.options.serverPort = arg.split('=')[1];
846
- } else if (arg === '--database-path') {
847
- parsed.options.databasePath = args[++i];
848
- } else if (arg.startsWith('--database-path=')) {
849
- parsed.options.databasePath = arg.split('=')[1];
850
- } else if (arg === '--no-daemon') {
851
- parsed.options.noDaemon = true;
852
- } else if (arg === '--restart-daemon') {
853
- parsed.options.restartDaemon = true;
854
- } else if (arg === '--help' || arg === '-h') {
855
- parsed.command = 'help';
856
- commandSet = true;
857
- } else if (arg === '--version' || arg === '-v') {
858
- parsed.command = 'version';
859
- commandSet = true;
860
- } else if (!arg.startsWith('-')) {
861
- if (!commandSet) {
862
- parsed.command = arg;
863
- commandSet = true;
864
- }
865
- if (arg === 'sandbox' || arg === 'daemon') {
866
- parsed.remainingArgs = args.slice(i + 1);
867
- break;
868
- }
869
- }
870
- }
871
-
872
- return parsed;
873
- }
874
-
875
- // Main CLI handler
876
- async function main() {
877
- const args = process.argv.slice(2);
878
- const { command, options, remainingArgs } = parseArgs(args);
879
-
880
- // Apply CLI options to environment variables
881
- if (options.serverPort) {
882
- process.env.SERVER_PORT = options.serverPort;
883
- } else if (!process.env.SERVER_PORT && process.env.PORT) {
884
- process.env.SERVER_PORT = process.env.PORT;
885
- }
886
- if (options.noDaemon) {
887
- process.env.PIXCODE_NO_DAEMON = '1';
888
- }
889
- if (options.databasePath) {
890
- process.env.DATABASE_PATH = options.databasePath;
891
- }
892
-
893
- switch (command) {
894
- case 'start':
895
- if (await maybeAutoDaemonStart(options)) {
896
- break;
897
- }
898
- await startServer();
899
- break;
900
- case 'sandbox':
901
- await sandboxCommand(remainingArgs || []);
902
- break;
903
- case 'daemon':
904
- await handleDaemonCommand(remainingArgs || [], {
905
- appRoot: APP_ROOT,
906
- defaultPort: process.env.SERVER_PORT || process.env.PORT || '3001',
907
- color: c,
908
- cliEntry: process.argv[1],
909
- nodeExecPath: process.execPath,
910
- });
911
- break;
912
- case 'status':
913
- case 'info':
914
- showStatus();
915
- break;
916
- case 'help':
917
- case '-h':
918
- case '--help':
919
- showHelp();
920
- break;
921
- case 'version':
922
- case '-v':
923
- case '--version':
924
- showVersion();
925
- break;
926
- case 'update':
927
- await updatePackage(options);
928
- break;
929
- default:
930
- console.error(`\n❌ Unknown command: ${command}`);
931
- console.log(' Run "pixcode help" for usage information.\n');
932
- process.exit(1);
933
- }
934
- }
935
-
936
- // Run the CLI
937
- main().catch(error => {
938
- console.error('\n❌ Error:', error.message);
939
- process.exit(1);
940
- });
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Pixcode CLI
4
+ *
5
+ * Provides command-line utilities for managing Pixcode
6
+ *
7
+ * Commands:
8
+ * (no args) - Start the server (default)
9
+ * start - Start the server
10
+ * sandbox - Manage Docker sandbox environments
11
+ * daemon - Manage persistent Linux service modes
12
+ * status - Show configuration and data locations
13
+ * help - Show help information
14
+ * version - Show version information
15
+ */
16
+
17
+ import fs from 'fs';
18
+ import path from 'path';
19
+ import os from 'os';
20
+ import net from 'node:net';
21
+ import { findAppRoot, getModuleDir } from './utils/runtime-paths.js';
22
+ import { buildDaemonCliCommand, handleDaemonCommand, hasInstalledDaemonUnit } from './daemon-manager.js';
23
+
24
+ const __dirname = getModuleDir(import.meta.url);
25
+ // The CLI is compiled into dist-server/server, but it still needs to read the top-level
26
+ // package.json and .env file. Resolving the app root once keeps those lookups stable.
27
+ const APP_ROOT = findAppRoot(__dirname);
28
+ const DAEMON_COMMAND_CONTEXT = {
29
+ appRoot: APP_ROOT,
30
+ cliEntry: process.argv[1],
31
+ nodeExecPath: process.execPath,
32
+ };
33
+
34
+ // ANSI color codes for terminal output
35
+ const colors = {
36
+ reset: '\x1b[0m',
37
+ bright: '\x1b[1m',
38
+ dim: '\x1b[2m',
39
+
40
+ // Foreground colors
41
+ cyan: '\x1b[36m',
42
+ green: '\x1b[32m',
43
+ yellow: '\x1b[33m',
44
+ blue: '\x1b[34m',
45
+ magenta: '\x1b[35m',
46
+ white: '\x1b[37m',
47
+ gray: '\x1b[90m',
48
+ };
49
+
50
+ // Helper to colorize text
51
+ const c = {
52
+ info: (text) => `${colors.cyan}${text}${colors.reset}`,
53
+ ok: (text) => `${colors.green}${text}${colors.reset}`,
54
+ warn: (text) => `${colors.yellow}${text}${colors.reset}`,
55
+ error: (text) => `${colors.yellow}${text}${colors.reset}`,
56
+ tip: (text) => `${colors.blue}${text}${colors.reset}`,
57
+ bright: (text) => `${colors.bright}${text}${colors.reset}`,
58
+ dim: (text) => `${colors.dim}${text}${colors.reset}`,
59
+ };
60
+
61
+ // Load package.json for version info
62
+ const packageJsonPath = path.join(APP_ROOT, 'package.json');
63
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
64
+ // Match the runtime fallback in load-env.js so "pixcode status" reports the same default
65
+ // database location that the backend will actually use when no DATABASE_PATH is configured.
66
+ const DEFAULT_DATABASE_PATH = path.join(os.homedir(), '.pixcode', 'auth.db');
67
+
68
+ // Load environment variables from .env file if it exists
69
+ function loadEnvFile() {
70
+ try {
71
+ const envPath = path.join(APP_ROOT, '.env');
72
+ const envFile = fs.readFileSync(envPath, 'utf8');
73
+ envFile.split('\n').forEach(line => {
74
+ const trimmedLine = line.trim();
75
+ if (trimmedLine && !trimmedLine.startsWith('#')) {
76
+ const [key, ...valueParts] = trimmedLine.split('=');
77
+ if (key && valueParts.length > 0 && !process.env[key]) {
78
+ process.env[key] = valueParts.join('=').trim();
79
+ }
80
+ }
81
+ });
82
+ } catch (e) {
83
+ // .env file is optional
84
+ }
85
+ }
86
+
87
+ // Get the database path (same logic as db.js)
88
+ function getDatabasePath() {
89
+ loadEnvFile();
90
+ return process.env.DATABASE_PATH || DEFAULT_DATABASE_PATH;
91
+ }
92
+
93
+ // Get the installation directory
94
+ function getInstallDir() {
95
+ return APP_ROOT;
96
+ }
97
+
98
+ // Show status command
99
+ function showStatus() {
100
+ console.log(`\n${c.bright('Pixcode - Status')}\n`);
101
+ console.log(c.dim('═'.repeat(60)));
102
+
103
+ // Version info
104
+ console.log(`\n${c.info('[INFO]')} Version: ${c.bright(packageJson.version)}`);
105
+
106
+ // Installation location
107
+ const installDir = getInstallDir();
108
+ console.log(`\n${c.info('[INFO]')} Installation Directory:`);
109
+ console.log(` ${c.dim(installDir)}`);
110
+
111
+ // Database location
112
+ const dbPath = getDatabasePath();
113
+ const dbExists = fs.existsSync(dbPath);
114
+ console.log(`\n${c.info('[INFO]')} Database Location:`);
115
+ console.log(` ${c.dim(dbPath)}`);
116
+ console.log(` Status: ${dbExists ? c.ok('[OK] Exists') : c.warn('[WARN] Not created yet (will be created on first run)')}`);
117
+
118
+ if (dbExists) {
119
+ const stats = fs.statSync(dbPath);
120
+ console.log(` Size: ${c.dim((stats.size / 1024).toFixed(2) + ' KB')}`);
121
+ console.log(` Modified: ${c.dim(stats.mtime.toLocaleString())}`);
122
+ }
123
+
124
+ // Environment variables
125
+ console.log(`\n${c.info('[INFO]')} Configuration:`);
126
+ console.log(` SERVER_PORT: ${c.bright(process.env.SERVER_PORT || process.env.PORT || '3001')} ${c.dim(process.env.SERVER_PORT || process.env.PORT ? '' : '(default)')}`);
127
+ console.log(` DATABASE_PATH: ${c.dim(process.env.DATABASE_PATH || '(using default location)')}`);
128
+ console.log(` CLAUDE_CLI_PATH: ${c.dim(process.env.CLAUDE_CLI_PATH || 'claude (default)')}`);
129
+ console.log(` CONTEXT_WINDOW: ${c.dim(process.env.CONTEXT_WINDOW || '160000 (default)')}`);
130
+
131
+ // Claude projects folder
132
+ const claudeProjectsPath = path.join(os.homedir(), '.claude', 'projects');
133
+ const projectsExists = fs.existsSync(claudeProjectsPath);
134
+ console.log(`\n${c.info('[INFO]')} Claude Projects Folder:`);
135
+ console.log(` ${c.dim(claudeProjectsPath)}`);
136
+ console.log(` Status: ${projectsExists ? c.ok('[OK] Exists') : c.warn('[WARN] Not found')}`);
137
+
138
+ // Config file location
139
+ const envFilePath = path.join(APP_ROOT, '.env');
140
+ const envExists = fs.existsSync(envFilePath);
141
+ console.log(`\n${c.info('[INFO]')} Configuration File:`);
142
+ console.log(` ${c.dim(envFilePath)}`);
143
+ // Missing .env is fine — Pixcode ships sensible defaults. Keep this
144
+ // purely informational so users don't misread an "[INFO] optional"
145
+ // line as an install-time failure.
146
+ console.log(` Status: ${envExists ? c.ok('[OK] Exists') : c.info('[INFO] Optional — running on defaults')}`);
147
+
148
+ console.log('\n' + c.dim('═'.repeat(60)));
149
+ console.log(`\n${c.tip('[TIP]')} Hints:`);
150
+ console.log(` ${c.dim('>')} Use ${c.bright('pixcode --port 8080')} to run on a custom port`);
151
+ console.log(` ${c.dim('>')} Use ${c.bright('pixcode --database-path /path/to/db')} for custom database`);
152
+ console.log(` ${c.dim('>')} Run ${c.bright('pixcode help')} for all options`);
153
+ console.log(` ${c.dim('>')} Access the UI at http://localhost:${process.env.SERVER_PORT || process.env.PORT || '3001'}\n`);
154
+ }
155
+
156
+ // Show help
157
+ function showHelp() {
158
+ console.log(`
159
+ ╔═══════════════════════════════════════════════════════════════╗
160
+ ║ Pixcode - Command Line Tool ║
161
+ ╚═══════════════════════════════════════════════════════════════╝
162
+
163
+ Usage:
164
+ pixcode [command] [options]
165
+
166
+ Commands:
167
+ start Start the Pixcode server (default)
168
+ daemon Manage persistent Linux service (system-first)
169
+ sandbox Manage Docker sandbox environments
170
+ status Show configuration and data locations
171
+ update Update to the latest version
172
+ help Show this help information
173
+ version Show version information
174
+
175
+ Options:
176
+ -p, --port <port> Set server port (default: 3001)
177
+ --database-path <path> Set custom database location
178
+ --no-daemon Disable automatic daemon startup on Linux
179
+ --restart-daemon Restart daemon automatically after update
180
+ -h, --help Show this help information
181
+ -v, --version Show version information
182
+
183
+ Examples:
184
+ $ pixcode # Start with defaults
185
+ $ pixcode --port 8080 # Start on port 8080
186
+ $ pixcode --no-daemon # Force foreground mode
187
+ $ sudo pixcode daemon install --mode system --port 3001
188
+ $ pixcode daemon install --mode user --port 3001 --single-port
189
+ $ pixcode daemon doctor --mode system
190
+ $ pixcode update --restart-daemon
191
+ $ pixcode sandbox ~/my-project # Run in a Docker sandbox
192
+ $ pixcode status # Show configuration
193
+
194
+ Environment Variables:
195
+ SERVER_PORT Set server port (default: 3001)
196
+ PORT Set server port (default: 3001) (LEGACY)
197
+ DATABASE_PATH Set custom database location
198
+ CLAUDE_CLI_PATH Set custom Claude CLI path
199
+ CONTEXT_WINDOW Set context window size (default: 160000)
200
+
201
+ Documentation:
202
+ ${packageJson.homepage || 'https://github.com/alicomert/pixcode'}
203
+
204
+ Report Issues:
205
+ ${packageJson.bugs?.url || 'https://github.com/alicomert/pixcode/issues'}
206
+ `);
207
+ }
208
+
209
+ // Show version
210
+ function showVersion() {
211
+ console.log(`${packageJson.version}`);
212
+ }
213
+
214
+ // Compare semver versions, returns true if v1 > v2
215
+ function isNewerVersion(v1, v2) {
216
+ const parts1 = v1.split('.').map(Number);
217
+ const parts2 = v2.split('.').map(Number);
218
+ for (let i = 0; i < 3; i++) {
219
+ if (parts1[i] > parts2[i]) return true;
220
+ if (parts1[i] < parts2[i]) return false;
221
+ }
222
+ return false;
223
+ }
224
+
225
+ // Check for updates
226
+ async function checkForUpdates(silent = false) {
227
+ try {
228
+ const { execSync } = await import('child_process');
229
+ const latestVersion = execSync('npm show @pixelbyte-software/pixcode version', { encoding: 'utf8' }).trim();
230
+ const currentVersion = packageJson.version;
231
+
232
+ if (isNewerVersion(latestVersion, currentVersion)) {
233
+ console.log(`\n${c.warn('[UPDATE]')} New version available: ${c.bright(latestVersion)} (current: ${currentVersion})`);
234
+ console.log(` Run ${c.bright('pixcode update')} to update\n`);
235
+ return { hasUpdate: true, latestVersion, currentVersion };
236
+ } else if (!silent) {
237
+ console.log(`${c.ok('[OK]')} You are on the latest version (${currentVersion})`);
238
+ }
239
+ return { hasUpdate: false, latestVersion, currentVersion };
240
+ } catch (e) {
241
+ if (!silent) {
242
+ console.log(`${c.warn('[WARN]')} Could not check for updates`);
243
+ }
244
+ return { hasUpdate: false, error: e.message };
245
+ }
246
+ }
247
+
248
+ // Update the package
249
+ async function updatePackage(options = {}) {
250
+ try {
251
+ const { execSync } = await import('child_process');
252
+ console.log(`${c.info('[INFO]')} Checking for updates...`);
253
+
254
+ const { hasUpdate, latestVersion, currentVersion } = await checkForUpdates(true);
255
+
256
+ if (!hasUpdate) {
257
+ console.log(`${c.ok('[OK]')} Already on the latest version (${currentVersion})`);
258
+ return;
259
+ }
260
+
261
+ console.log(`${c.info('[INFO]')} Updating from ${currentVersion} to ${latestVersion}...`);
262
+ execSync('npm update -g @pixelbyte-software/pixcode', { stdio: 'inherit' });
263
+ console.log(`${c.ok('[OK]')} Update complete!`);
264
+
265
+ if (options.restartDaemon) {
266
+ if (!hasInstalledDaemonUnit()) {
267
+ console.log(`${c.warn('[WARN]')} No daemon unit detected; skipping restart.`);
268
+ return;
269
+ }
270
+ console.log(`${c.info('[INFO]')} Restarting daemon service...`);
271
+ await handleDaemonCommand(['restart', '--mode=system'], {
272
+ appRoot: APP_ROOT,
273
+ defaultPort: process.env.SERVER_PORT || process.env.PORT || '3001',
274
+ color: c,
275
+ });
276
+ console.log(`${c.ok('[OK]')} Daemon restart completed.`);
277
+ } else if (hasInstalledDaemonUnit()) {
278
+ const restartCommand = buildDaemonCliCommand(
279
+ { subcommand: 'restart', mode: 'system' },
280
+ DAEMON_COMMAND_CONTEXT
281
+ );
282
+ console.log(`${c.tip('[TIP]')} Daemon unit detected. Restart to apply update: ${c.bright(restartCommand)}`);
283
+ console.log(`${c.tip('[TIP]')} Or update + restart in one step: ${c.bright('pixcode update --restart-daemon')}`);
284
+ } else {
285
+ console.log(`${c.tip('[TIP]')} Restart pixcode to use the new version.`);
286
+ }
287
+ } catch (e) {
288
+ console.error(`${c.error('[ERROR]')} Update failed: ${e.message}`);
289
+ console.log(`${c.tip('[TIP]')} Try running manually: npm update -g @pixelbyte-software/pixcode`);
290
+ }
291
+ }
292
+
293
+ // ── Sandbox command ─────────────────────────────────────────
294
+
295
+ const SANDBOX_TEMPLATES = {
296
+ claude: 'ghcr.io/alicomert/pixcode-sandbox:claude-code',
297
+ codex: 'ghcr.io/alicomert/pixcode-sandbox:codex',
298
+ gemini: 'ghcr.io/alicomert/pixcode-sandbox:gemini',
299
+ };
300
+
301
+ const SANDBOX_SECRETS = {
302
+ claude: 'anthropic',
303
+ codex: 'openai',
304
+ gemini: 'google',
305
+ };
306
+
307
+ function parseSandboxArgs(args) {
308
+ const result = {
309
+ subcommand: null,
310
+ workspace: null,
311
+ agent: 'claude',
312
+ name: null,
313
+ port: 3001,
314
+ template: null,
315
+ env: [],
316
+ };
317
+
318
+ const subcommands = ['ls', 'stop', 'start', 'rm', 'logs', 'help'];
319
+
320
+ for (let i = 0; i < args.length; i++) {
321
+ const arg = args[i];
322
+
323
+ if (i === 0 && subcommands.includes(arg)) {
324
+ result.subcommand = arg;
325
+ } else if (arg === '--agent' || arg === '-a') {
326
+ result.agent = args[++i];
327
+ } else if (arg === '--name' || arg === '-n') {
328
+ result.name = args[++i];
329
+ } else if (arg === '--port') {
330
+ result.port = parseInt(args[++i], 10);
331
+ } else if (arg === '--template' || arg === '-t') {
332
+ result.template = args[++i];
333
+ } else if (arg === '--env' || arg === '-e') {
334
+ result.env.push(args[++i]);
335
+ } else if (!arg.startsWith('-')) {
336
+ if (!result.subcommand) {
337
+ result.workspace = arg;
338
+ } else {
339
+ result.name = arg; // for stop/start/rm/logs <name>
340
+ }
341
+ }
342
+ }
343
+
344
+ // Default subcommand based on what we got
345
+ if (!result.subcommand) {
346
+ result.subcommand = 'create';
347
+ }
348
+
349
+ // Derive name from workspace path if not set
350
+ if (!result.name && result.workspace) {
351
+ result.name = path.basename(path.resolve(result.workspace.replace(/^~/, os.homedir())));
352
+ }
353
+
354
+ // Default template from agent
355
+ if (!result.template) {
356
+ result.template = SANDBOX_TEMPLATES[result.agent] || SANDBOX_TEMPLATES.claude;
357
+ }
358
+
359
+ return result;
360
+ }
361
+
362
+ function showSandboxHelp() {
363
+ console.log(`
364
+ ${c.bright('Pixcode Sandbox')} — Run Pixcode inside Docker Sandboxes
365
+
366
+ Usage:
367
+ pixcode sandbox <workspace> Create and start a sandbox
368
+ pixcode sandbox <subcommand> [name] Manage sandboxes
369
+
370
+ Subcommands:
371
+ ${c.bright('(default)')} Create a sandbox and start the web UI
372
+ ${c.bright('ls')} List all sandboxes
373
+ ${c.bright('start')} Restart a stopped sandbox and re-launch the web UI
374
+ ${c.bright('stop')} Stop a sandbox (preserves state)
375
+ ${c.bright('rm')} Remove a sandbox
376
+ ${c.bright('logs')} Show Pixcode server logs
377
+ ${c.bright('help')} Show this help
378
+
379
+ Options:
380
+ -a, --agent <agent> Agent to use: claude, codex, gemini (default: claude)
381
+ -n, --name <name> Sandbox name (default: derived from workspace folder)
382
+ -t, --template <image> Custom template image
383
+ -e, --env <KEY=VALUE> Set environment variable (repeatable)
384
+ --port <port> Host port for the web UI (default: 3001)
385
+
386
+ Examples:
387
+ $ pixcode sandbox ~/my-project
388
+ $ pixcode sandbox ~/my-project --agent codex --port 8080
389
+ $ pixcode sandbox ~/my-project --env SERVER_PORT=8080 --env HOST=0.0.0.0
390
+ $ pixcode sandbox ls
391
+ $ pixcode sandbox stop my-project
392
+ $ pixcode sandbox start my-project
393
+ $ pixcode sandbox rm my-project
394
+
395
+ Prerequisites:
396
+ 1. Install sbx CLI: https://docs.docker.com/ai/sandboxes/get-started/
397
+ 2. Authenticate and store your API key:
398
+ sbx login
399
+ sbx secret set -g anthropic # for Claude
400
+ sbx secret set -g openai # for Codex
401
+ sbx secret set -g google # for Gemini
402
+
403
+ Advanced usage:
404
+ For branch mode, multiple workspaces, memory limits, network policies,
405
+ or passing prompts to the agent, use sbx directly with the template:
406
+
407
+ sbx run --template ghcr.io/alicomert/pixcode-sandbox:claude-code claude ~/my-project --branch my-feature
408
+ sbx run --template ghcr.io/alicomert/pixcode-sandbox:claude-code claude ~/project ~/libs:ro --memory 8g
409
+
410
+ Full Docker Sandboxes docs: https://docs.docker.com/ai/sandboxes/usage/
411
+ `);
412
+ }
413
+
414
+ async function sandboxCommand(args) {
415
+ const { execFileSync, spawn: spawnProcess } = await import('child_process');
416
+
417
+ // Safe execution — uses execFileSync (no shell) to prevent injection
418
+ const sbx = (subcmd, opts = {}) => {
419
+ const result = execFileSync('sbx', subcmd, {
420
+ encoding: 'utf8',
421
+ stdio: opts.inherit ? 'inherit' : 'pipe',
422
+ });
423
+ return result || '';
424
+ };
425
+
426
+ const opts = parseSandboxArgs(args);
427
+
428
+ if (opts.subcommand === 'help') {
429
+ showSandboxHelp();
430
+ return;
431
+ }
432
+
433
+ // Validate name (alphanumeric, hyphens, underscores only)
434
+ if (opts.name && !/^[\w-]+$/.test(opts.name)) {
435
+ console.error(`\n${c.error('❌')} Invalid sandbox name: ${opts.name}`);
436
+ console.log(` Names may only contain letters, numbers, hyphens, and underscores.\n`);
437
+ process.exit(1);
438
+ }
439
+
440
+ // Check sbx is installed
441
+ try {
442
+ sbx(['version']);
443
+ } catch {
444
+ console.error(`\n${c.error('❌')} ${c.bright('sbx')} CLI not found.\n`);
445
+ console.log(` Install it from: ${c.info('https://docs.docker.com/ai/sandboxes/get-started/')}`);
446
+ console.log(` Then run: ${c.bright('sbx login')}`);
447
+ console.log(` And store your API key: ${c.bright('sbx secret set -g anthropic')}\n`);
448
+ process.exit(1);
449
+ }
450
+
451
+ switch (opts.subcommand) {
452
+
453
+ case 'ls':
454
+ sbx(['ls'], { inherit: true });
455
+ break;
456
+
457
+ case 'stop':
458
+ if (!opts.name) {
459
+ console.error(`\n${c.error('❌')} Sandbox name required: pixcode sandbox stop <name>\n`);
460
+ process.exit(1);
461
+ }
462
+ sbx(['stop', opts.name], { inherit: true });
463
+ break;
464
+
465
+ case 'rm':
466
+ if (!opts.name) {
467
+ console.error(`\n${c.error('❌')} Sandbox name required: pixcode sandbox rm <name>\n`);
468
+ process.exit(1);
469
+ }
470
+ sbx(['rm', opts.name], { inherit: true });
471
+ break;
472
+
473
+ case 'logs':
474
+ if (!opts.name) {
475
+ console.error(`\n${c.error('❌')} Sandbox name required: pixcode sandbox logs <name>\n`);
476
+ process.exit(1);
477
+ }
478
+ try {
479
+ sbx(['exec', opts.name, 'bash', '-c', 'cat /tmp/pixcode-ui.log'], { inherit: true });
480
+ } catch (e) {
481
+ console.error(`\n${c.error('❌')} Could not read logs: ${e.message || 'Is the sandbox running?'}\n`);
482
+ }
483
+ break;
484
+
485
+ case 'start': {
486
+ if (!opts.name) {
487
+ console.error(`\n${c.error('❌')} Sandbox name required: pixcode sandbox start <name>\n`);
488
+ process.exit(1);
489
+ }
490
+ console.log(`\n${c.info('▶')} Starting sandbox ${c.bright(opts.name)}...`);
491
+ const restartRun = spawnProcess('sbx', ['run', opts.name], {
492
+ detached: true,
493
+ stdio: ['ignore', 'ignore', 'ignore'],
494
+ });
495
+ restartRun.unref();
496
+ await new Promise(resolve => setTimeout(resolve, 5000));
497
+
498
+ console.log(`${c.info('▶')} Launching Pixcode web server...`);
499
+ sbx(['exec', opts.name, 'bash', '-c', 'pixcode start --port 3001 &']);
500
+
501
+ console.log(`${c.info('▶')} Forwarding port ${opts.port} → 3001...`);
502
+ try {
503
+ sbx(['ports', opts.name, '--publish', `${opts.port}:3001`]);
504
+ } catch (e) {
505
+ const msg = e.stdout || e.stderr || e.message || '';
506
+ if (msg.includes('address already in use')) {
507
+ const altPort = opts.port + 1;
508
+ console.log(`${c.warn('⚠')} Port ${opts.port} in use, trying ${altPort}...`);
509
+ try {
510
+ sbx(['ports', opts.name, '--publish', `${altPort}:3001`]);
511
+ opts.port = altPort;
512
+ } catch {
513
+ console.error(`${c.error('❌')} Ports ${opts.port} and ${altPort} both in use. Use --port to specify a free port.`);
514
+ process.exit(1);
515
+ }
516
+ } else {
517
+ throw e;
518
+ }
519
+ }
520
+
521
+ console.log(`\n${c.ok('✔')} ${c.bright('Pixcode is ready!')}`);
522
+ console.log(` ${c.info('→')} ${c.bright(`http://localhost:${opts.port}`)}\n`);
523
+ break;
524
+ }
525
+
526
+ case 'create': {
527
+ if (!opts.workspace) {
528
+ console.error(`\n${c.error('❌')} Workspace path required: pixcode sandbox <path>\n`);
529
+ console.log(` Example: ${c.bright('pixcode sandbox ~/my-project')}\n`);
530
+ process.exit(1);
531
+ }
532
+
533
+ const workspace = opts.workspace.startsWith('~')
534
+ ? opts.workspace.replace(/^~/, os.homedir())
535
+ : path.resolve(opts.workspace);
536
+
537
+ if (!fs.existsSync(workspace)) {
538
+ console.error(`\n${c.error('❌')} Workspace path not found: ${c.dim(workspace)}\n`);
539
+ process.exit(1);
540
+ }
541
+
542
+ const secret = SANDBOX_SECRETS[opts.agent] || 'anthropic';
543
+
544
+ // Check if the required secret is stored
545
+ try {
546
+ const secretList = sbx(['secret', 'ls']);
547
+ if (!secretList.includes(secret)) {
548
+ console.error(`\n${c.error('❌')} No ${c.bright(secret)} API key found.\n`);
549
+ console.log(` Run: ${c.bright(`sbx secret set -g ${secret}`)}\n`);
550
+ process.exit(1);
551
+ }
552
+ } catch { /* sbx secret ls not available, skip check */ }
553
+
554
+ console.log(`\n${c.bright('Pixcode Sandbox')}`);
555
+ console.log(c.dim('─'.repeat(50)));
556
+ console.log(` Agent: ${c.info(opts.agent)} ${c.dim(`(${secret} credentials)`)}`);
557
+ console.log(` Workspace: ${c.dim(workspace)}`);
558
+ console.log(` Name: ${c.dim(opts.name)}`);
559
+ console.log(` Template: ${c.dim(opts.template)}`);
560
+ console.log(` Port: ${c.dim(String(opts.port))}`);
561
+ if (opts.env.length > 0) {
562
+ console.log(` Env: ${c.dim(opts.env.join(', '))}`);
563
+ }
564
+ console.log(c.dim('─'.repeat(50)));
565
+
566
+ // Step 1: Launch sandbox with sbx run in background.
567
+ // sbx run creates the sandbox (or reconnects) AND holds an active session,
568
+ // which prevents the sandbox from auto-stopping.
569
+ console.log(`\n${c.info('▶')} Creating sandbox ${c.bright(opts.name)}...`);
570
+ const bgRun = spawnProcess('sbx', [
571
+ 'run', '--template', opts.template, '--name', opts.name, opts.agent, workspace,
572
+ ], {
573
+ detached: true,
574
+ stdio: ['ignore', 'ignore', 'ignore'],
575
+ });
576
+ bgRun.unref();
577
+ // Wait for sandbox to be ready
578
+ await new Promise(resolve => setTimeout(resolve, 5000));
579
+
580
+ // Step 2: Inject environment variables
581
+ if (opts.env.length > 0) {
582
+ console.log(`${c.info('▶')} Setting environment variables...`);
583
+ const exports = opts.env
584
+ .filter(e => /^\w+=.+$/.test(e))
585
+ .map(e => `export ${e}`)
586
+ .join('\n');
587
+ if (exports) {
588
+ sbx(['exec', opts.name, 'bash', '-c', `echo '${exports}' >> /etc/sandbox-persistent.sh`]);
589
+ }
590
+ const invalid = opts.env.filter(e => !/^\w+=.+$/.test(e));
591
+ if (invalid.length > 0) {
592
+ console.log(`${c.warn('⚠')} Skipped invalid env vars: ${invalid.join(', ')} (expected KEY=VALUE)`);
593
+ }
594
+ }
595
+
596
+ // Step 3: Start Pixcode inside the sandbox
597
+ console.log(`${c.info('▶')} Launching Pixcode web server...`);
598
+ sbx(['exec', opts.name, 'bash', '-c', 'pixcode start --port 3001 &']);
599
+
600
+ // Step 4: Forward port
601
+ console.log(`${c.info('▶')} Forwarding port ${opts.port} → 3001...`);
602
+ try {
603
+ sbx(['ports', opts.name, '--publish', `${opts.port}:3001`]);
604
+ } catch (e) {
605
+ const msg = e.stdout || e.stderr || e.message || '';
606
+ if (msg.includes('address already in use')) {
607
+ const altPort = opts.port + 1;
608
+ console.log(`${c.warn('⚠')} Port ${opts.port} in use, trying ${altPort}...`);
609
+ try {
610
+ sbx(['ports', opts.name, '--publish', `${altPort}:3001`]);
611
+ opts.port = altPort;
612
+ } catch {
613
+ console.error(`${c.error('❌')} Ports ${opts.port} and ${altPort} both in use. Use --port to specify a free port.`);
614
+ process.exit(1);
615
+ }
616
+ } else {
617
+ throw e;
618
+ }
619
+ }
620
+
621
+ // Done
622
+ console.log(`\n${c.ok('✔')} ${c.bright('Pixcode is ready!')}`);
623
+ console.log(` ${c.info('→')} Open ${c.bright(`http://localhost:${opts.port}`)}`);
624
+ console.log(`\n${c.dim(' Manage with:')}`);
625
+ console.log(` ${c.dim('$')} sbx ls`);
626
+ console.log(` ${c.dim('$')} sbx stop ${opts.name}`);
627
+ console.log(` ${c.dim('$')} sbx start ${opts.name}`);
628
+ console.log(` ${c.dim('$')} sbx rm ${opts.name}`);
629
+ console.log(`\n${c.dim(' Or install globally:')} npm install -g @pixelbyte-software/pixcode\n`);
630
+ break;
631
+ }
632
+
633
+ default:
634
+ showSandboxHelp();
635
+ }
636
+ }
637
+
638
+ // ── Server ──────────────────────────────────────────────────
639
+
640
+ // Start the server
641
+ async function startServer() {
642
+ // Check for updates silently on startup
643
+ checkForUpdates(true);
644
+
645
+ // Import and run the server
646
+ await import('./index.js');
647
+ }
648
+
649
+ async function isPortOpen(port, timeoutMs = 800) {
650
+ return await new Promise((resolve) => {
651
+ const socket = net.createConnection({ host: '127.0.0.1', port: Number(port) });
652
+ let settled = false;
653
+ const done = (value) => {
654
+ if (settled) return;
655
+ settled = true;
656
+ socket.destroy();
657
+ resolve(value);
658
+ };
659
+
660
+ socket.setTimeout(timeoutMs);
661
+ socket.once('connect', () => done(true));
662
+ socket.once('timeout', () => done(false));
663
+ socket.once('error', () => done(false));
664
+ });
665
+ }
666
+
667
+ async function waitForPortOpen(port, timeoutMs = 25000) {
668
+ const deadline = Date.now() + timeoutMs;
669
+ while (Date.now() < deadline) {
670
+ if (await isPortOpen(port)) {
671
+ return true;
672
+ }
673
+ await new Promise(resolve => setTimeout(resolve, 1000));
674
+ }
675
+ return false;
676
+ }
677
+
678
+ function printSystemDaemonActiveNotice(port) {
679
+ const effectivePort = Number(port) || 3001;
680
+ const statusCommand = buildDaemonCliCommand(
681
+ { subcommand: 'status', mode: 'system' },
682
+ DAEMON_COMMAND_CONTEXT
683
+ );
684
+ const stopCommand = buildDaemonCliCommand(
685
+ { subcommand: 'stop', mode: 'system' },
686
+ DAEMON_COMMAND_CONTEXT
687
+ );
688
+ const logsCommand = buildDaemonCliCommand(
689
+ { subcommand: 'logs', mode: 'system' },
690
+ DAEMON_COMMAND_CONTEXT
691
+ );
692
+ console.log(`${c.ok('[OK]')} System daemon is active and managing Pixcode.`);
693
+ console.log(`${c.info('[INFO]')} Health URL: ${c.bright(`http://localhost:${effectivePort}/health`)}`);
694
+ console.log(`${c.info('[INFO]')} Status: ${c.bright(statusCommand)}`);
695
+ console.log(`${c.info('[INFO]')} Stop: ${c.bright(stopCommand)}`);
696
+ console.log(`${c.info('[INFO]')} Logs: ${c.bright(logsCommand)}`);
697
+ }
698
+
699
+ function printUserDaemonActiveNotice(port) {
700
+ const effectivePort = Number(port) || 3001;
701
+ const statusCommand = buildDaemonCliCommand(
702
+ { subcommand: 'status', mode: 'user' },
703
+ DAEMON_COMMAND_CONTEXT
704
+ );
705
+ const stopCommand = buildDaemonCliCommand(
706
+ { subcommand: 'stop', mode: 'user' },
707
+ DAEMON_COMMAND_CONTEXT
708
+ );
709
+ const logsCommand = buildDaemonCliCommand(
710
+ { subcommand: 'logs', mode: 'user' },
711
+ DAEMON_COMMAND_CONTEXT
712
+ );
713
+ console.log(`${c.ok('[OK]')} User daemon is active for this account.`);
714
+ console.log(`${c.info('[INFO]')} UI: ${c.bright(`http://localhost:${effectivePort}`)}`);
715
+ console.log(`${c.info('[INFO]')} Status: ${c.bright(statusCommand)}`);
716
+ console.log(`${c.info('[INFO]')} Stop: ${c.bright(stopCommand)}`);
717
+ console.log(`${c.info('[INFO]')} Logs: ${c.bright(logsCommand)}`);
718
+ console.log(`${c.tip('[TIP]')} For login/reboot persistence, enable linger once: ${c.bright(`sudo loginctl enable-linger ${os.userInfo().username}`)}`);
719
+ }
720
+
721
+ function isSystemPermissionError(error) {
722
+ const message = String(error?.message || error || '');
723
+ return /(access denied|permission denied|must be root|interactive authentication required|not permitted|failed to connect to bus|operation not permitted|authentication is required|polkit)/i.test(message);
724
+ }
725
+
726
+ function buildAutoInstallArgs(mode, options) {
727
+ const args = ['install', `--mode=${mode}`];
728
+ if (options.serverPort) {
729
+ args.push('--port', String(options.serverPort));
730
+ }
731
+ if (options.databasePath) {
732
+ args.push('--database-path', String(options.databasePath));
733
+ }
734
+ args.push('--single-port');
735
+ return args;
736
+ }
737
+
738
+ async function maybeAutoDaemonStart(options = {}) {
739
+ if (process.platform !== 'linux') return false;
740
+ if (process.env.PIXCODE_DAEMON_MANAGED === '1') return false;
741
+ if (process.env.PIXCODE_NO_DAEMON === '1') return false;
742
+ if (process.env.PIXCODE_DAEMON_ATTEMPTED === '1') return false;
743
+ if (options.noDaemon) return false;
744
+
745
+ process.env.PIXCODE_DAEMON_ATTEMPTED = '1';
746
+ const daemonPort = Number(options.serverPort || process.env.SERVER_PORT || process.env.PORT || '3001');
747
+ const systemArgs = buildAutoInstallArgs('system', options);
748
+ const userArgs = buildAutoInstallArgs('user', options);
749
+
750
+ try {
751
+ console.log(`${c.info('[INFO]')} Linux detected. Enforcing system daemon mode for Pixcode...`);
752
+ await handleDaemonCommand(systemArgs, {
753
+ appRoot: APP_ROOT,
754
+ defaultPort: process.env.SERVER_PORT || process.env.PORT || '3001',
755
+ color: c,
756
+ });
757
+ return true;
758
+ } catch (systemError) {
759
+ const healthySoon = await waitForPortOpen(daemonPort);
760
+ if (healthySoon) {
761
+ console.log(`${c.warn('[WARN]')} System daemon health check was delayed, but port ${daemonPort} is now reachable.`);
762
+ printSystemDaemonActiveNotice(daemonPort);
763
+ return true;
764
+ }
765
+
766
+ if (!isSystemPermissionError(systemError)) {
767
+ const installSystemCommand = buildDaemonCliCommand(
768
+ {
769
+ subcommand: 'install',
770
+ mode: 'system',
771
+ extraArgs: ['--port', String(daemonPort), '--single-port'],
772
+ },
773
+ DAEMON_COMMAND_CONTEXT
774
+ );
775
+ throw new Error(
776
+ `System daemon bootstrap failed.\n` +
777
+ `${systemError.message}\n` +
778
+ `Run with privileges: ${installSystemCommand}`
779
+ );
780
+ }
781
+
782
+ console.log(`${c.warn('[WARN]')} System daemon setup requires elevated privileges for this user.`);
783
+ console.log(`${c.info('[INFO]')} Falling back to user daemon mode for account "${os.userInfo().username}"...`);
784
+
785
+ try {
786
+ await handleDaemonCommand(userArgs, {
787
+ appRoot: APP_ROOT,
788
+ defaultPort: process.env.SERVER_PORT || process.env.PORT || '3001',
789
+ color: c,
790
+ });
791
+ printUserDaemonActiveNotice(daemonPort);
792
+ return true;
793
+ } catch (userError) {
794
+ const userHealthySoon = await waitForPortOpen(daemonPort);
795
+ if (userHealthySoon) {
796
+ console.log(`${c.warn('[WARN]')} User daemon health check was delayed, but port ${daemonPort} is now reachable.`);
797
+ printUserDaemonActiveNotice(daemonPort);
798
+ return true;
799
+ }
800
+ const installSystemCommand = buildDaemonCliCommand(
801
+ {
802
+ subcommand: 'install',
803
+ mode: 'system',
804
+ extraArgs: ['--port', String(daemonPort), '--single-port'],
805
+ },
806
+ DAEMON_COMMAND_CONTEXT
807
+ );
808
+ const installUserCommand = buildDaemonCliCommand(
809
+ {
810
+ subcommand: 'install',
811
+ mode: 'user',
812
+ extraArgs: ['--port', String(daemonPort), '--single-port'],
813
+ },
814
+ DAEMON_COMMAND_CONTEXT
815
+ );
816
+ throw new Error(
817
+ `System daemon bootstrap failed.\n` +
818
+ `${systemError.message}\n\n` +
819
+ `User daemon fallback also failed.\n` +
820
+ `${userError.message}\n` +
821
+ `Try one of:\n` +
822
+ `1) ${installSystemCommand}\n` +
823
+ `2) ${installUserCommand}`
824
+ );
825
+ }
826
+ }
827
+ }
828
+
829
+ // Parse CLI arguments
830
+ function parseArgs(args) {
831
+ const parsed = { command: 'start', options: {} };
832
+ let commandSet = false;
833
+
834
+ for (let i = 0; i < args.length; i++) {
835
+ const arg = args[i];
836
+
837
+ if (arg === '--port' || arg === '-p') {
838
+ parsed.options.serverPort = args[++i];
839
+ } else if (arg.startsWith('--port=')) {
840
+ parsed.options.serverPort = arg.split('=')[1];
841
+ } else if (arg === '--database-path') {
842
+ parsed.options.databasePath = args[++i];
843
+ } else if (arg.startsWith('--database-path=')) {
844
+ parsed.options.databasePath = arg.split('=')[1];
845
+ } else if (arg === '--no-daemon') {
846
+ parsed.options.noDaemon = true;
847
+ } else if (arg === '--restart-daemon') {
848
+ parsed.options.restartDaemon = true;
849
+ } else if (arg === '--help' || arg === '-h') {
850
+ parsed.command = 'help';
851
+ commandSet = true;
852
+ } else if (arg === '--version' || arg === '-v') {
853
+ parsed.command = 'version';
854
+ commandSet = true;
855
+ } else if (!arg.startsWith('-')) {
856
+ if (!commandSet) {
857
+ parsed.command = arg;
858
+ commandSet = true;
859
+ }
860
+ if (arg === 'sandbox' || arg === 'daemon') {
861
+ parsed.remainingArgs = args.slice(i + 1);
862
+ break;
863
+ }
864
+ }
865
+ }
866
+
867
+ return parsed;
868
+ }
869
+
870
+ // Main CLI handler
871
+ async function main() {
872
+ const args = process.argv.slice(2);
873
+ const { command, options, remainingArgs } = parseArgs(args);
874
+
875
+ // Apply CLI options to environment variables
876
+ if (options.serverPort) {
877
+ process.env.SERVER_PORT = options.serverPort;
878
+ } else if (!process.env.SERVER_PORT && process.env.PORT) {
879
+ process.env.SERVER_PORT = process.env.PORT;
880
+ }
881
+ if (options.noDaemon) {
882
+ process.env.PIXCODE_NO_DAEMON = '1';
883
+ }
884
+ if (options.databasePath) {
885
+ process.env.DATABASE_PATH = options.databasePath;
886
+ }
887
+
888
+ switch (command) {
889
+ case 'start':
890
+ if (await maybeAutoDaemonStart(options)) {
891
+ break;
892
+ }
893
+ await startServer();
894
+ break;
895
+ case 'sandbox':
896
+ await sandboxCommand(remainingArgs || []);
897
+ break;
898
+ case 'daemon':
899
+ await handleDaemonCommand(remainingArgs || [], {
900
+ appRoot: APP_ROOT,
901
+ defaultPort: process.env.SERVER_PORT || process.env.PORT || '3001',
902
+ color: c,
903
+ cliEntry: process.argv[1],
904
+ nodeExecPath: process.execPath,
905
+ });
906
+ break;
907
+ case 'status':
908
+ case 'info':
909
+ showStatus();
910
+ break;
911
+ case 'help':
912
+ case '-h':
913
+ case '--help':
914
+ showHelp();
915
+ break;
916
+ case 'version':
917
+ case '-v':
918
+ case '--version':
919
+ showVersion();
920
+ break;
921
+ case 'update':
922
+ await updatePackage(options);
923
+ break;
924
+ default:
925
+ console.error(`\n❌ Unknown command: ${command}`);
926
+ console.log(' Run "pixcode help" for usage information.\n');
927
+ process.exit(1);
928
+ }
929
+ }
930
+
931
+ // Run the CLI
932
+ main().catch(error => {
933
+ console.error('\n❌ Error:', error.message);
934
+ process.exit(1);
935
+ });