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