@pixelbyte-software/pixcode 1.35.1 → 1.35.2

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 (172) hide show
  1. package/LICENSE +718 -718
  2. package/README.de.md +248 -248
  3. package/README.ja.md +240 -240
  4. package/README.ko.md +240 -240
  5. package/README.md +303 -303
  6. package/README.ru.md +248 -248
  7. package/README.tr.md +250 -250
  8. package/README.zh-CN.md +240 -240
  9. package/dist/api-docs.html +548 -548
  10. package/dist/assets/{index-CBdsvGSR.js → index-D1-AIL_5.js} +1 -1
  11. package/dist/clear-cache.html +85 -85
  12. package/dist/convert-icons.md +52 -52
  13. package/dist/favicon.svg +8 -8
  14. package/dist/generate-icons.js +48 -48
  15. package/dist/icons/codex-white.svg +3 -3
  16. package/dist/icons/codex.svg +3 -3
  17. package/dist/icons/cursor-white.svg +11 -11
  18. package/dist/icons/icon-128x128.svg +9 -9
  19. package/dist/icons/icon-144x144.svg +9 -9
  20. package/dist/icons/icon-152x152.svg +9 -9
  21. package/dist/icons/icon-192x192.svg +9 -9
  22. package/dist/icons/icon-384x384.svg +9 -9
  23. package/dist/icons/icon-512x512.svg +9 -9
  24. package/dist/icons/icon-72x72.svg +9 -9
  25. package/dist/icons/icon-96x96.svg +9 -9
  26. package/dist/icons/icon-template.svg +9 -9
  27. package/dist/icons/qwen-logo.svg +14 -14
  28. package/dist/index.html +58 -58
  29. package/dist/logo.svg +12 -12
  30. package/dist/manifest.json +60 -60
  31. package/dist/openapi.yaml +1693 -1693
  32. package/dist/sw.js +124 -124
  33. package/dist-server/server/cli.js +96 -96
  34. package/dist-server/server/daemon/manager.js +33 -33
  35. package/dist-server/server/daemon-manager.js +64 -64
  36. package/dist-server/server/routes/commands.js +25 -25
  37. package/dist-server/server/routes/git.js +17 -17
  38. package/dist-server/server/routes/taskmaster.js +419 -419
  39. package/package.json +180 -180
  40. package/scripts/fix-node-pty.js +67 -67
  41. package/scripts/smoke/a2a-roundtrip.mjs +167 -167
  42. package/scripts/smoke/orchestration-api.mjs +172 -172
  43. package/scripts/smoke/orchestration-live-run.mjs +176 -176
  44. package/server/claude-sdk.js +898 -898
  45. package/server/cli.js +935 -935
  46. package/server/constants/config.js +4 -4
  47. package/server/cursor-cli.js +342 -342
  48. package/server/daemon/manager.js +564 -564
  49. package/server/daemon-manager.js +959 -959
  50. package/server/database/db.js +794 -794
  51. package/server/database/json-store.js +197 -197
  52. package/server/gemini-cli.js +535 -535
  53. package/server/gemini-response-handler.js +79 -79
  54. package/server/index.js +3135 -3135
  55. package/server/load-env.js +34 -34
  56. package/server/middleware/auth.js +173 -173
  57. package/server/modules/orchestration/a2a/adapter-registry.ts +108 -108
  58. package/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.ts +55 -55
  59. package/server/modules/orchestration/a2a/adapters/claude-code.adapter.ts +284 -284
  60. package/server/modules/orchestration/a2a/adapters/codex.adapter.ts +244 -244
  61. package/server/modules/orchestration/a2a/adapters/cursor.adapter.ts +249 -249
  62. package/server/modules/orchestration/a2a/adapters/gemini.adapter.ts +248 -248
  63. package/server/modules/orchestration/a2a/adapters/opencode.adapter.ts +248 -248
  64. package/server/modules/orchestration/a2a/adapters/qwen.adapter.ts +248 -248
  65. package/server/modules/orchestration/a2a/routes.ts +577 -577
  66. package/server/modules/orchestration/a2a/task-store.ts +178 -178
  67. package/server/modules/orchestration/a2a/types.ts +125 -125
  68. package/server/modules/orchestration/a2a/validator.ts +113 -113
  69. package/server/modules/orchestration/index.ts +66 -66
  70. package/server/modules/orchestration/preview/port-watcher.ts +112 -112
  71. package/server/modules/orchestration/preview/preview-proxy.ts +60 -60
  72. package/server/modules/orchestration/preview/types.ts +19 -19
  73. package/server/modules/orchestration/tasks/orchestration-task-store.ts +45 -45
  74. package/server/modules/orchestration/tasks/orchestration-task.routes.ts +73 -73
  75. package/server/modules/orchestration/tasks/orchestration-task.service.ts +145 -145
  76. package/server/modules/orchestration/tasks/orchestration-task.types.ts +29 -29
  77. package/server/modules/orchestration/workflows/built-in-workflows.ts +127 -127
  78. package/server/modules/orchestration/workflows/workflow-runner.ts +1206 -1206
  79. package/server/modules/orchestration/workflows/workflow-store.ts +97 -97
  80. package/server/modules/orchestration/workflows/workflow.routes.ts +169 -169
  81. package/server/modules/orchestration/workflows/workflow.types.ts +70 -70
  82. package/server/modules/orchestration/workflows/workspace-target.ts +120 -120
  83. package/server/modules/orchestration/workspace/docker-workspace.ts +135 -135
  84. package/server/modules/orchestration/workspace/path-safety.ts +55 -55
  85. package/server/modules/orchestration/workspace/types.ts +52 -52
  86. package/server/modules/orchestration/workspace/workspace-manager.ts +97 -97
  87. package/server/modules/orchestration/workspace/worktree-workspace.ts +125 -125
  88. package/server/modules/providers/index.ts +2 -2
  89. package/server/modules/providers/list/claude/claude-auth.provider.ts +145 -145
  90. package/server/modules/providers/list/claude/claude-mcp.provider.ts +135 -135
  91. package/server/modules/providers/list/claude/claude-sessions.provider.ts +306 -306
  92. package/server/modules/providers/list/claude/claude.provider.ts +15 -15
  93. package/server/modules/providers/list/codex/codex-auth.provider.ts +115 -115
  94. package/server/modules/providers/list/codex/codex-mcp.provider.ts +135 -135
  95. package/server/modules/providers/list/codex/codex-sessions.provider.ts +319 -319
  96. package/server/modules/providers/list/codex/codex.provider.ts +15 -15
  97. package/server/modules/providers/list/cursor/cursor-auth.provider.ts +143 -143
  98. package/server/modules/providers/list/cursor/cursor-mcp.provider.ts +108 -108
  99. package/server/modules/providers/list/cursor/cursor-sessions.provider.ts +421 -421
  100. package/server/modules/providers/list/cursor/cursor.provider.ts +15 -15
  101. package/server/modules/providers/list/gemini/gemini-auth.provider.ts +163 -163
  102. package/server/modules/providers/list/gemini/gemini-mcp.provider.ts +110 -110
  103. package/server/modules/providers/list/gemini/gemini-sessions.provider.ts +227 -227
  104. package/server/modules/providers/list/gemini/gemini.provider.ts +15 -15
  105. package/server/modules/providers/list/opencode/opencode-auth.provider.ts +130 -130
  106. package/server/modules/providers/list/opencode/opencode-mcp.provider.ts +126 -126
  107. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +232 -232
  108. package/server/modules/providers/list/opencode/opencode.provider.ts +29 -29
  109. package/server/modules/providers/list/qwen/qwen-auth.provider.ts +145 -145
  110. package/server/modules/providers/list/qwen/qwen-mcp.provider.ts +114 -114
  111. package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +265 -265
  112. package/server/modules/providers/list/qwen/qwen.provider.ts +21 -21
  113. package/server/modules/providers/provider.registry.ts +40 -40
  114. package/server/modules/providers/provider.routes.ts +819 -819
  115. package/server/modules/providers/services/mcp.service.ts +86 -86
  116. package/server/modules/providers/services/provider-auth.service.ts +26 -26
  117. package/server/modules/providers/services/sessions.service.ts +45 -45
  118. package/server/modules/providers/shared/base/abstract.provider.ts +20 -20
  119. package/server/modules/providers/shared/mcp/mcp.provider.ts +151 -151
  120. package/server/modules/providers/shared/provider-configs.ts +142 -142
  121. package/server/modules/providers/tests/mcp.test.ts +293 -293
  122. package/server/openai-codex.js +462 -462
  123. package/server/opencode-cli.js +459 -459
  124. package/server/opencode-response-handler.js +107 -107
  125. package/server/projects.js +3105 -3105
  126. package/server/qwen-code-cli.js +395 -395
  127. package/server/qwen-response-handler.js +73 -73
  128. package/server/routes/agent.js +1365 -1365
  129. package/server/routes/auth.js +138 -138
  130. package/server/routes/codex.js +19 -19
  131. package/server/routes/commands.js +554 -554
  132. package/server/routes/cursor.js +52 -52
  133. package/server/routes/gemini.js +24 -24
  134. package/server/routes/git.js +1488 -1488
  135. package/server/routes/mcp-utils.js +31 -31
  136. package/server/routes/messages.js +61 -61
  137. package/server/routes/network.js +120 -120
  138. package/server/routes/plugins.js +318 -318
  139. package/server/routes/projects.js +915 -915
  140. package/server/routes/qwen.js +27 -27
  141. package/server/routes/settings.js +286 -286
  142. package/server/routes/taskmaster.js +1496 -1496
  143. package/server/routes/telegram.js +125 -125
  144. package/server/routes/user.js +123 -123
  145. package/server/services/external-access.js +171 -171
  146. package/server/services/install-jobs.js +571 -571
  147. package/server/services/notification-orchestrator.js +242 -242
  148. package/server/services/provider-credentials.js +189 -189
  149. package/server/services/provider-models.js +381 -381
  150. package/server/services/telegram/bot.js +279 -279
  151. package/server/services/telegram/telegram-http-client.js +130 -130
  152. package/server/services/telegram/translations.js +170 -170
  153. package/server/services/vapid-keys.js +36 -36
  154. package/server/sessionManager.js +225 -225
  155. package/server/shared/interfaces.ts +54 -54
  156. package/server/shared/types.ts +172 -172
  157. package/server/shared/utils.ts +193 -193
  158. package/server/tsconfig.json +36 -36
  159. package/server/utils/colors.js +21 -21
  160. package/server/utils/commandParser.js +303 -303
  161. package/server/utils/frontmatter.js +18 -18
  162. package/server/utils/gitConfig.js +34 -34
  163. package/server/utils/mcp-detector.js +147 -147
  164. package/server/utils/plugin-loader.js +457 -457
  165. package/server/utils/plugin-process-manager.js +184 -184
  166. package/server/utils/port-access.js +209 -209
  167. package/server/utils/runtime-paths.js +37 -37
  168. package/server/utils/taskmaster-websocket.js +128 -128
  169. package/server/utils/url-detection.js +71 -71
  170. package/server/vite-daemon.js +78 -78
  171. package/shared/modelConstants.js +162 -162
  172. package/shared/networkHosts.js +22 -22
package/server/cli.js CHANGED
@@ -1,935 +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 --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
- });
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
+ });