@pixelbyte-software/pixcode 1.35.2 → 1.35.4

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