@pixelbyte-software/pixcode 1.54.10 → 1.54.11

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 (282) hide show
  1. package/CODE_OF_CONDUCT.md +41 -41
  2. package/CONTRIBUTING.md +156 -156
  3. package/LICENSE +21 -718
  4. package/README.de.md +169 -169
  5. package/README.ja.md +167 -167
  6. package/README.ko.md +167 -167
  7. package/README.md +435 -418
  8. package/README.ru.md +169 -169
  9. package/README.tr.md +298 -298
  10. package/README.zh-CN.md +167 -167
  11. package/SECURITY.md +46 -46
  12. package/dist/api-automation.html +110 -110
  13. package/dist/api-docs.html +548 -548
  14. package/dist/assets/{index-DWOW_Jn0.js → index-Bcqs_1vc.js} +114 -114
  15. package/dist/clear-cache.html +85 -85
  16. package/dist/convert-icons.md +52 -52
  17. package/dist/docs.html +308 -308
  18. package/dist/features.html +133 -133
  19. package/dist/generate-icons.js +48 -48
  20. package/dist/humans.txt +15 -15
  21. package/dist/icons/codex-white.svg +3 -3
  22. package/dist/icons/codex.svg +3 -3
  23. package/dist/icons/cursor-white.svg +11 -11
  24. package/dist/icons/qwen-logo.svg +14 -14
  25. package/dist/index.html +58 -58
  26. package/dist/landing.html +268 -268
  27. package/dist/llms-full.txt +119 -119
  28. package/dist/llms.txt +53 -53
  29. package/dist/manifest.json +60 -60
  30. package/dist/openapi.yaml +1696 -1696
  31. package/dist/orchestration.html +125 -125
  32. package/dist/robots.txt +4 -4
  33. package/dist/site.css +692 -692
  34. package/dist/sitemap.xml +51 -51
  35. package/dist/sw.js +132 -132
  36. package/dist-server/server/cli.js +100 -100
  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/routes/commands.js +25 -25
  40. package/dist-server/server/routes/git.js +17 -17
  41. package/dist-server/server/routes/live-view.js +46 -46
  42. package/dist-server/server/services/public-api-manifest.js +51 -51
  43. package/package.json +224 -224
  44. package/scripts/fix-node-pty.js +67 -67
  45. package/scripts/github/create-v1.38-issues.mjs +351 -351
  46. package/scripts/github/create-vscode-workbench-issues.mjs +121 -121
  47. package/scripts/smoke/backend-resource-bounds.mjs +152 -152
  48. package/scripts/smoke/changes-panel-layout.mjs +48 -48
  49. package/scripts/smoke/chat-composer-fixed-layout.mjs +55 -55
  50. package/scripts/smoke/chat-message-timeline-order.mjs +41 -41
  51. package/scripts/smoke/chat-realtime-hydration.mjs +44 -44
  52. package/scripts/smoke/chat-session-provider-pools.mjs +35 -35
  53. package/scripts/smoke/chat-session-state.mjs +19 -19
  54. package/scripts/smoke/code-editor-theme.mjs +55 -55
  55. package/scripts/smoke/code-editor-vscode-engine.mjs +91 -91
  56. package/scripts/smoke/command-center-agent-writes.mjs +79 -79
  57. package/scripts/smoke/command-center-non-git.mjs +46 -46
  58. package/scripts/smoke/context-packet.mjs +43 -43
  59. package/scripts/smoke/control-room-ux-redesign.mjs +91 -91
  60. package/scripts/smoke/daemon-entrypoint.mjs +20 -20
  61. package/scripts/smoke/default-landing-routing.mjs +33 -33
  62. package/scripts/smoke/desktop-native-notifications.mjs +30 -30
  63. package/scripts/smoke/desktop-tray-icon.mjs +33 -33
  64. package/scripts/smoke/discord-release-workflow.mjs +24 -24
  65. package/scripts/smoke/git-install-update.mjs +255 -255
  66. package/scripts/smoke/handoff-artifact-protocol.mjs +50 -50
  67. package/scripts/smoke/live-view-diagnostics.mjs +53 -53
  68. package/scripts/smoke/live-view-environment.mjs +92 -92
  69. package/scripts/smoke/live-view-integration.mjs +450 -450
  70. package/scripts/smoke/mac-desktop-runtime.mjs +37 -37
  71. package/scripts/smoke/mobile-tunnel-guidance.mjs +29 -29
  72. package/scripts/smoke/mobile-ux.mjs +76 -76
  73. package/scripts/smoke/model-registry.mjs +36 -36
  74. package/scripts/smoke/multi-project-ui.mjs +45 -45
  75. package/scripts/smoke/multi-worker-slots.mjs +42 -42
  76. package/scripts/smoke/notification-center.mjs +87 -87
  77. package/scripts/smoke/notification-inapp-preference.mjs +23 -23
  78. package/scripts/smoke/notification-taxonomy.mjs +58 -58
  79. package/scripts/smoke/orchestration-api.mjs +172 -172
  80. package/scripts/smoke/orchestration-execution-dashboard.mjs +33 -33
  81. package/scripts/smoke/orchestration-live-run.mjs +176 -176
  82. package/scripts/smoke/orchestration-mobile-scroll.mjs +29 -29
  83. package/scripts/smoke/orchestration-model-sync.mjs +30 -30
  84. package/scripts/smoke/orchestration-permission-fallback.mjs +34 -34
  85. package/scripts/smoke/orchestration-runtime-guards.mjs +48 -48
  86. package/scripts/smoke/orchestration-user-facing-output.mjs +25 -25
  87. package/scripts/smoke/permission-policy.mjs +50 -50
  88. package/scripts/smoke/pixcode-workbench-1-48.mjs +167 -167
  89. package/scripts/smoke/provider-models-opencode-live.mjs +66 -66
  90. package/scripts/smoke/provider-rest-api.mjs +124 -124
  91. package/scripts/smoke/provider-selection-status.mjs +52 -52
  92. package/scripts/smoke/run-state-refresh.mjs +52 -52
  93. package/scripts/smoke/runtime-manager.mjs +99 -99
  94. package/scripts/smoke/shell-manual-disconnect.mjs +30 -30
  95. package/scripts/smoke/side-panel-editor-layout.mjs +34 -34
  96. package/scripts/smoke/static-root-routing.mjs +21 -21
  97. package/scripts/smoke/strict-handoff-compact.mjs +60 -60
  98. package/scripts/smoke/taskmaster-config.mjs +24 -24
  99. package/scripts/smoke/taskmaster-execution-telegram.mjs +3 -3
  100. package/scripts/smoke/taskmaster-onboarding.mjs +3 -3
  101. package/scripts/smoke/taskmaster-run-graph.mjs +3 -3
  102. package/scripts/smoke/telegram-control.mjs +331 -331
  103. package/scripts/smoke/tunnel-persistence.mjs +56 -56
  104. package/scripts/smoke/update-issue-progress.mjs +69 -69
  105. package/scripts/smoke/update-ux.mjs +55 -55
  106. package/scripts/smoke/v138-completion.mjs +132 -132
  107. package/scripts/smoke/v138-desktop-release-hardening.mjs +69 -69
  108. package/scripts/smoke/v138-diagnostics.mjs +63 -63
  109. package/scripts/smoke/v138-issue-planner.mjs +33 -33
  110. package/scripts/smoke/v143-remote-control.mjs +76 -76
  111. package/scripts/smoke/v144-production-loop.mjs +47 -47
  112. package/scripts/smoke/v145-platformization.mjs +46 -46
  113. package/scripts/smoke/v146-control-room-ui.mjs +150 -150
  114. package/scripts/smoke/version-modal-autoshow.mjs +29 -29
  115. package/scripts/smoke/vscode-workbench-layout.mjs +63 -63
  116. package/scripts/smoke/vscode-workbench-polish.mjs +461 -461
  117. package/scripts/smoke/workflow-fallback-replay.mjs +56 -56
  118. package/scripts/smoke/workflow-templates.mjs +43 -43
  119. package/scripts/smoke/workflow-trace-timeline.mjs +46 -46
  120. package/scripts/update-git-install.mjs +298 -298
  121. package/server/claude-sdk.js +927 -927
  122. package/server/cli.js +1106 -1106
  123. package/server/constants/config.js +4 -4
  124. package/server/cursor-cli.js +344 -344
  125. package/server/daemon/manager.js +563 -563
  126. package/server/daemon-manager.js +964 -964
  127. package/server/database/db.js +988 -988
  128. package/server/database/json-store.js +197 -197
  129. package/server/gemini-cli.js +550 -550
  130. package/server/gemini-response-handler.js +79 -79
  131. package/server/index.js +5671 -5671
  132. package/server/load-env.js +35 -35
  133. package/server/middleware/account-lockout.js +112 -112
  134. package/server/middleware/auth.js +277 -277
  135. package/server/middleware/rate-limiter.js +87 -87
  136. package/server/modules/orchestration/a2a/adapter-registry.ts +108 -108
  137. package/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.ts +63 -63
  138. package/server/modules/orchestration/a2a/adapters/claude-code.adapter.ts +286 -286
  139. package/server/modules/orchestration/a2a/adapters/codex.adapter.ts +244 -244
  140. package/server/modules/orchestration/a2a/adapters/cursor.adapter.ts +249 -249
  141. package/server/modules/orchestration/a2a/adapters/gemini.adapter.ts +248 -248
  142. package/server/modules/orchestration/a2a/adapters/json-event.adapter.test.ts +60 -60
  143. package/server/modules/orchestration/a2a/adapters/json-event.adapter.ts +101 -101
  144. package/server/modules/orchestration/a2a/adapters/opencode.adapter.ts +248 -248
  145. package/server/modules/orchestration/a2a/adapters/qwen.adapter.ts +248 -248
  146. package/server/modules/orchestration/a2a/agent-card.ts +55 -55
  147. package/server/modules/orchestration/a2a/auth.middleware.ts +29 -29
  148. package/server/modules/orchestration/a2a/bus.ts +46 -46
  149. package/server/modules/orchestration/a2a/routes.ts +586 -586
  150. package/server/modules/orchestration/a2a/task-dispatcher.ts +345 -345
  151. package/server/modules/orchestration/a2a/task-store.ts +178 -178
  152. package/server/modules/orchestration/a2a/types.ts +126 -126
  153. package/server/modules/orchestration/a2a/validator.ts +113 -113
  154. package/server/modules/orchestration/index.ts +99 -99
  155. package/server/modules/orchestration/preview/port-watcher.ts +112 -112
  156. package/server/modules/orchestration/preview/preview-proxy.ts +60 -60
  157. package/server/modules/orchestration/preview/types.ts +19 -19
  158. package/server/modules/orchestration/security/permission-policy.ts +401 -401
  159. package/server/modules/orchestration/tasks/orchestration-task-store.ts +41 -41
  160. package/server/modules/orchestration/tasks/orchestration-task.routes.ts +81 -81
  161. package/server/modules/orchestration/tasks/orchestration-task.service.ts +201 -201
  162. package/server/modules/orchestration/tasks/orchestration-task.types.ts +40 -40
  163. package/server/modules/orchestration/tasks/task-run-graph.ts +155 -155
  164. package/server/modules/orchestration/workflows/approval-queue.ts +106 -106
  165. package/server/modules/orchestration/workflows/built-in-workflows.ts +127 -127
  166. package/server/modules/orchestration/workflows/context-packet.ts +186 -186
  167. package/server/modules/orchestration/workflows/handoff-artifact.ts +175 -175
  168. package/server/modules/orchestration/workflows/workflow-fallback-policy.ts +161 -161
  169. package/server/modules/orchestration/workflows/workflow-replay.ts +254 -254
  170. package/server/modules/orchestration/workflows/workflow-runner.ts +2062 -2062
  171. package/server/modules/orchestration/workflows/workflow-store.ts +97 -97
  172. package/server/modules/orchestration/workflows/workflow-templates.ts +272 -272
  173. package/server/modules/orchestration/workflows/workflow-trace.ts +424 -424
  174. package/server/modules/orchestration/workflows/workflow.routes.ts +586 -586
  175. package/server/modules/orchestration/workflows/workflow.types.ts +111 -111
  176. package/server/modules/orchestration/workflows/workspace-target.ts +122 -122
  177. package/server/modules/orchestration/workspace/docker-workspace.ts +136 -136
  178. package/server/modules/orchestration/workspace/path-safety.ts +55 -55
  179. package/server/modules/orchestration/workspace/types.ts +52 -52
  180. package/server/modules/orchestration/workspace/workspace-manager.ts +102 -102
  181. package/server/modules/orchestration/workspace/worktree-workspace.ts +126 -126
  182. package/server/modules/providers/index.ts +2 -2
  183. package/server/modules/providers/list/claude/claude-auth.provider.ts +146 -146
  184. package/server/modules/providers/list/claude/claude-mcp.provider.ts +135 -135
  185. package/server/modules/providers/list/claude/claude-sessions.provider.ts +306 -306
  186. package/server/modules/providers/list/claude/claude.provider.ts +15 -15
  187. package/server/modules/providers/list/codex/codex-auth.provider.ts +117 -117
  188. package/server/modules/providers/list/codex/codex-mcp.provider.ts +135 -135
  189. package/server/modules/providers/list/codex/codex-sessions.provider.ts +319 -319
  190. package/server/modules/providers/list/codex/codex.provider.ts +15 -15
  191. package/server/modules/providers/list/cursor/cursor-auth.provider.ts +147 -147
  192. package/server/modules/providers/list/cursor/cursor-mcp.provider.ts +108 -108
  193. package/server/modules/providers/list/cursor/cursor-sessions.provider.ts +421 -421
  194. package/server/modules/providers/list/cursor/cursor.provider.ts +15 -15
  195. package/server/modules/providers/list/gemini/gemini-auth.provider.ts +173 -173
  196. package/server/modules/providers/list/gemini/gemini-mcp.provider.ts +110 -110
  197. package/server/modules/providers/list/gemini/gemini-sessions.provider.ts +227 -227
  198. package/server/modules/providers/list/gemini/gemini.provider.ts +15 -15
  199. package/server/modules/providers/list/opencode/opencode-auth.provider.ts +131 -131
  200. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +286 -286
  201. package/server/modules/providers/list/qwen/qwen-auth.provider.ts +146 -146
  202. package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +265 -265
  203. package/server/modules/providers/provider.registry.ts +40 -40
  204. package/server/modules/providers/provider.routes.ts +982 -982
  205. package/server/modules/providers/services/mcp.service.ts +86 -86
  206. package/server/modules/providers/services/provider-auth.service.ts +26 -26
  207. package/server/modules/providers/services/sessions.service.ts +45 -45
  208. package/server/modules/providers/shared/base/abstract.provider.ts +20 -20
  209. package/server/modules/providers/shared/mcp/mcp.provider.ts +151 -151
  210. package/server/modules/providers/tests/mcp.test.ts +293 -293
  211. package/server/openai-codex.js +468 -468
  212. package/server/opencode-cli.js +491 -491
  213. package/server/opencode-response-handler.js +111 -111
  214. package/server/projects.js +3135 -3135
  215. package/server/qwen-code-cli.js +410 -410
  216. package/server/routes/agent.js +1462 -1462
  217. package/server/routes/auth.js +298 -298
  218. package/server/routes/codex.js +20 -20
  219. package/server/routes/commands.js +581 -581
  220. package/server/routes/cursor.js +61 -61
  221. package/server/routes/diagnostics.js +44 -44
  222. package/server/routes/gemini.js +25 -25
  223. package/server/routes/git.js +1822 -1822
  224. package/server/routes/live-view.js +434 -434
  225. package/server/routes/mcp-utils.js +13 -13
  226. package/server/routes/messages.js +97 -97
  227. package/server/routes/network.js +143 -143
  228. package/server/routes/platformization.js +231 -231
  229. package/server/routes/plugins.js +690 -690
  230. package/server/routes/production-agent-loop.js +90 -90
  231. package/server/routes/projects.js +918 -918
  232. package/server/routes/public-api.js +34 -34
  233. package/server/routes/qwen.js +27 -27
  234. package/server/routes/remote.js +56 -56
  235. package/server/routes/settings.js +321 -321
  236. package/server/routes/telegram.js +163 -163
  237. package/server/routes/user.js +125 -125
  238. package/server/routes/webhooks.js +63 -63
  239. package/server/services/control-room.js +102 -102
  240. package/server/services/diagnostics.js +165 -165
  241. package/server/services/external-access.js +403 -403
  242. package/server/services/install-jobs.js +715 -715
  243. package/server/services/live-view.js +956 -956
  244. package/server/services/managed-runtimes.js +493 -493
  245. package/server/services/model-registry.js +144 -144
  246. package/server/services/notification-orchestrator.js +365 -365
  247. package/server/services/notification-taxonomy.js +204 -204
  248. package/server/services/platformization.js +1052 -1052
  249. package/server/services/production-agent-loop.js +248 -248
  250. package/server/services/provider-cli-versions.js +149 -149
  251. package/server/services/provider-credentials.js +189 -189
  252. package/server/services/provider-models.js +396 -396
  253. package/server/services/public-api-manifest.js +181 -181
  254. package/server/services/qr-login.js +126 -126
  255. package/server/services/remote-connection.js +127 -127
  256. package/server/services/runtime-manager.js +323 -323
  257. package/server/services/startup-update.js +259 -259
  258. package/server/services/telegram/bot.js +393 -393
  259. package/server/services/telegram/control-center.js +2453 -2453
  260. package/server/services/telegram/telegram-gateway.js +314 -314
  261. package/server/services/telegram/telegram-http-client.js +201 -201
  262. package/server/services/telegram/translations.js +470 -470
  263. package/server/services/webhooks.js +216 -216
  264. package/server/sessionManager.js +225 -225
  265. package/server/setup-wizard.js +283 -283
  266. package/server/shared/interfaces.ts +54 -54
  267. package/server/shared/types.ts +172 -172
  268. package/server/shared/utils.ts +193 -193
  269. package/server/tsconfig.json +36 -36
  270. package/server/utils/colors.js +21 -21
  271. package/server/utils/commandParser.js +305 -305
  272. package/server/utils/frontmatter.js +18 -18
  273. package/server/utils/gitConfig.js +34 -34
  274. package/server/utils/plugin-loader.js +461 -461
  275. package/server/utils/plugin-process-manager.js +185 -185
  276. package/server/utils/port-access.js +227 -227
  277. package/server/utils/runtime-paths.js +37 -37
  278. package/server/utils/security-log.js +84 -84
  279. package/server/utils/url-detection.js +71 -71
  280. package/server/vite-daemon.js +79 -79
  281. package/shared/modelConstants.js +161 -161
  282. package/shared/networkHosts.js +22 -22
package/server/cli.js CHANGED
@@ -1,1106 +1,1106 @@
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
- * setup - Run the interactive setup wizard
11
- * sandbox - Manage Docker sandbox environments
12
- * daemon - Manage persistent Linux service modes
13
- * status - Show configuration and data locations
14
- * help - Show help information
15
- * version - Show version information
16
- */
17
-
18
- import fs from 'fs';
19
- import path from 'path';
20
- import os from 'os';
21
- import net from 'node:net';
22
- import { spawn } from 'node:child_process';
23
-
24
- import { findAppRoot, getModuleDir } from './utils/runtime-paths.js';
25
- import { buildDaemonCliCommand, handleDaemonCommand, hasInstalledDaemonUnit } from './daemon-manager.js';
26
- import { runStartupAutoUpdate, startupUpdateReexecEnv } from './services/startup-update.js';
27
- import { runSetupWizard, postStartupGuidance, isFirstRun, isPortAvailable, findAvailablePort, waitForServerReady } from './setup-wizard.js';
28
-
29
- const __dirname = getModuleDir(import.meta.url);
30
- // The CLI is compiled into dist-server/server, but it still needs to read the top-level
31
- // package.json and .env file. Resolving the app root once keeps those lookups stable.
32
- const APP_ROOT = findAppRoot(__dirname);
33
- const DAEMON_COMMAND_CONTEXT = {
34
- appRoot: APP_ROOT,
35
- cliEntry: process.argv[1],
36
- nodeExecPath: process.execPath,
37
- };
38
-
39
- // ANSI color codes for terminal output
40
- const colors = {
41
- reset: '\x1b[0m',
42
- bright: '\x1b[1m',
43
- dim: '\x1b[2m',
44
-
45
- // Foreground colors
46
- cyan: '\x1b[36m',
47
- green: '\x1b[32m',
48
- yellow: '\x1b[33m',
49
- blue: '\x1b[34m',
50
- magenta: '\x1b[35m',
51
- white: '\x1b[37m',
52
- gray: '\x1b[90m',
53
- };
54
-
55
- // Helper to colorize text
56
- const c = {
57
- info: (text) => `${colors.cyan}${text}${colors.reset}`,
58
- ok: (text) => `${colors.green}${text}${colors.reset}`,
59
- warn: (text) => `${colors.yellow}${text}${colors.reset}`,
60
- error: (text) => `${colors.yellow}${text}${colors.reset}`,
61
- tip: (text) => `${colors.blue}${text}${colors.reset}`,
62
- bright: (text) => `${colors.bright}${text}${colors.reset}`,
63
- dim: (text) => `${colors.dim}${text}${colors.reset}`,
64
- };
65
-
66
- // Load package.json for version info
67
- const packageJsonPath = path.join(APP_ROOT, 'package.json');
68
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
69
- const installMode = fs.existsSync(path.join(APP_ROOT, '.git')) ? 'git' : 'npm';
70
- // Match the runtime fallback in load-env.js so "pixcode status" reports the same default
71
- // database location that the backend will actually use when no DATABASE_PATH is configured.
72
- const DEFAULT_DATABASE_PATH = path.join(os.homedir(), '.pixcode', 'auth.db');
73
-
74
- // Load environment variables from .env file if it exists
75
- function loadEnvFile() {
76
- try {
77
- const envPath = path.join(APP_ROOT, '.env');
78
- const envFile = fs.readFileSync(envPath, 'utf8');
79
- envFile.split('\n').forEach(line => {
80
- const trimmedLine = line.trim();
81
- if (trimmedLine && !trimmedLine.startsWith('#')) {
82
- const [key, ...valueParts] = trimmedLine.split('=');
83
- if (key && valueParts.length > 0 && !process.env[key]) {
84
- process.env[key] = valueParts.join('=').trim();
85
- }
86
- }
87
- });
88
- } catch (e) {
89
- // .env file is optional
90
- }
91
- }
92
-
93
- // Get the database path (same logic as db.js)
94
- function getDatabasePath() {
95
- loadEnvFile();
96
- return process.env.DATABASE_PATH || DEFAULT_DATABASE_PATH;
97
- }
98
-
99
- // Get the installation directory
100
- function getInstallDir() {
101
- return APP_ROOT;
102
- }
103
-
104
- // Show status command
105
- function showStatus() {
106
- console.log(`\n${c.bright('Pixcode - Status')}\n`);
107
- console.log(c.dim('═'.repeat(60)));
108
-
109
- // Version info
110
- console.log(`\n${c.info('[INFO]')} Version: ${c.bright(packageJson.version)}`);
111
-
112
- // Installation location
113
- const installDir = getInstallDir();
114
- console.log(`\n${c.info('[INFO]')} Installation Directory:`);
115
- console.log(` ${c.dim(installDir)}`);
116
-
117
- // Database location
118
- const dbPath = getDatabasePath();
119
- const dbExists = fs.existsSync(dbPath);
120
- console.log(`\n${c.info('[INFO]')} Database Location:`);
121
- console.log(` ${c.dim(dbPath)}`);
122
- console.log(` Status: ${dbExists ? c.ok('[OK] Exists') : c.warn('[WARN] Not created yet (will be created on first run)')}`);
123
-
124
- if (dbExists) {
125
- const stats = fs.statSync(dbPath);
126
- console.log(` Size: ${c.dim((stats.size / 1024).toFixed(2) + ' KB')}`);
127
- console.log(` Modified: ${c.dim(stats.mtime.toLocaleString())}`);
128
- }
129
-
130
- // Environment variables
131
- console.log(`\n${c.info('[INFO]')} Configuration:`);
132
- console.log(` SERVER_PORT: ${c.bright(process.env.SERVER_PORT || process.env.PORT || '3001')} ${c.dim(process.env.SERVER_PORT || process.env.PORT ? '' : '(default)')}`);
133
- console.log(` DATABASE_PATH: ${c.dim(process.env.DATABASE_PATH || '(using default location)')}`);
134
- console.log(` CLAUDE_CLI_PATH: ${c.dim(process.env.CLAUDE_CLI_PATH || 'claude (default)')}`);
135
- console.log(` CONTEXT_WINDOW: ${c.dim(process.env.CONTEXT_WINDOW || '160000 (default)')}`);
136
-
137
- // Claude projects folder
138
- const claudeProjectsPath = path.join(os.homedir(), '.claude', 'projects');
139
- const projectsExists = fs.existsSync(claudeProjectsPath);
140
- console.log(`\n${c.info('[INFO]')} Claude Projects Folder:`);
141
- console.log(` ${c.dim(claudeProjectsPath)}`);
142
- console.log(` Status: ${projectsExists ? c.ok('[OK] Exists') : c.warn('[WARN] Not found')}`);
143
-
144
- // Config file location
145
- const envFilePath = path.join(APP_ROOT, '.env');
146
- const envExists = fs.existsSync(envFilePath);
147
- console.log(`\n${c.info('[INFO]')} Configuration File:`);
148
- console.log(` ${c.dim(envFilePath)}`);
149
- // Missing .env is fine — Pixcode ships sensible defaults. Keep this
150
- // purely informational so users don't misread an "[INFO] optional"
151
- // line as an install-time failure.
152
- console.log(` Status: ${envExists ? c.ok('[OK] Exists') : c.info('[INFO] Optional — running on defaults')}`);
153
-
154
- console.log('\n' + c.dim('═'.repeat(60)));
155
- console.log(`\n${c.tip('[TIP]')} Hints:`);
156
- console.log(` ${c.dim('>')} Use ${c.bright('pixcode --port 8080')} to run on a custom port`);
157
- console.log(` ${c.dim('>')} Use ${c.bright('pixcode --database-path /path/to/db')} for custom database`);
158
- console.log(` ${c.dim('>')} Run ${c.bright('pixcode help')} for all options`);
159
- console.log(` ${c.dim('>')} Access the UI at http://localhost:${process.env.SERVER_PORT || process.env.PORT || '3001'}\n`);
160
- }
161
-
162
- // Show help
163
- function showHelp() {
164
- console.log(`
165
- ╔═══════════════════════════════════════════════════════════════╗
166
- ║ Pixcode - Command Line Tool ║
167
- ╚═══════════════════════════════════════════════════════════════╝
168
-
169
- Usage:
170
- pixcode [command] [options]
171
-
172
- Commands:
173
- start Start the Pixcode server (default)
174
- setup Run the interactive setup wizard (port, mode, browser)
175
- daemon Manage persistent Linux service (system-first)
176
- sandbox Manage Docker sandbox environments
177
- status Show configuration and data locations
178
- update Update to the latest version
179
- help Show this help information
180
- version Show version information
181
-
182
- Options:
183
- -p, --port <port> Set server port (default: 3001)
184
- --database-path <path> Set custom database location
185
- --no-daemon Disable automatic daemon startup on Linux
186
- --no-browser Do not auto-open browser on startup
187
- --restart-daemon Restart daemon automatically after update
188
- -h, --help Show this help information
189
- -v, --version Show version information
190
-
191
- Examples:
192
- $ pixcode # Start with defaults
193
- $ pixcode setup # Run the interactive setup wizard
194
- $ pixcode --port 8080 # Start on port 8080
195
- $ pixcode --no-daemon # Force foreground mode
196
- $ pixcode --no-browser # Start without auto-opening browser
197
- $ sudo pixcode daemon install --mode system --port 3001
198
- $ pixcode daemon install --mode user --port 3001 --single-port
199
- $ pixcode daemon doctor --mode system
200
- $ pixcode update --restart-daemon
201
- $ pixcode sandbox ~/my-project # Run in a Docker sandbox
202
- $ pixcode status # Show configuration
203
-
204
- Environment Variables:
205
- SERVER_PORT Set server port (default: 3001)
206
- PORT Set server port (default: 3001) (LEGACY)
207
- DATABASE_PATH Set custom database location
208
- CLAUDE_CLI_PATH Set custom Claude CLI path
209
- CONTEXT_WINDOW Set context window size (default: 160000)
210
-
211
- Documentation:
212
- ${packageJson.homepage || 'https://github.com/alicomert/pixcode'}
213
-
214
- Report Issues:
215
- ${packageJson.bugs?.url || 'https://github.com/alicomert/pixcode/issues'}
216
- `);
217
- }
218
-
219
- // Show version
220
- function showVersion() {
221
- console.log(`${packageJson.version}`);
222
- }
223
-
224
- // Compare semver versions, returns true if v1 > v2
225
- function isNewerVersion(v1, v2) {
226
- const parts1 = v1.split('.').map(Number);
227
- const parts2 = v2.split('.').map(Number);
228
- for (let i = 0; i < 3; i++) {
229
- if (parts1[i] > parts2[i]) return true;
230
- if (parts1[i] < parts2[i]) return false;
231
- }
232
- return false;
233
- }
234
-
235
- // Check for updates
236
- async function checkForUpdates(silent = false) {
237
- try {
238
- const { execSync } = await import('child_process');
239
- const latestVersion = execSync('npm show @pixelbyte-software/pixcode version', { encoding: 'utf8' }).trim();
240
- const currentVersion = packageJson.version;
241
-
242
- if (isNewerVersion(latestVersion, currentVersion)) {
243
- console.log(`\n${c.warn('[UPDATE]')} New version available: ${c.bright(latestVersion)} (current: ${currentVersion})`);
244
- console.log(` Run ${c.bright('pixcode update')} to update\n`);
245
- return { hasUpdate: true, latestVersion, currentVersion };
246
- } else if (!silent) {
247
- console.log(`${c.ok('[OK]')} You are on the latest version (${currentVersion})`);
248
- }
249
- return { hasUpdate: false, latestVersion, currentVersion };
250
- } catch (e) {
251
- if (!silent) {
252
- console.log(`${c.warn('[WARN]')} Could not check for updates`);
253
- }
254
- return { hasUpdate: false, error: e.message };
255
- }
256
- }
257
-
258
- function runInherited(command, args, options = {}) {
259
- return new Promise((resolve, reject) => {
260
- const child = spawn(command, args, {
261
- cwd: options.cwd || APP_ROOT,
262
- env: options.env || process.env,
263
- stdio: 'inherit',
264
- shell: false,
265
- windowsHide: false,
266
- });
267
-
268
- child.on('error', reject);
269
- child.on('close', (code) => {
270
- if (code === 0) {
271
- resolve();
272
- return;
273
- }
274
-
275
- reject(new Error(`${command} ${args.join(' ')} exited with code ${code}`));
276
- });
277
- });
278
- }
279
-
280
- async function maybeRestartDaemonAfterUpdate(options = {}) {
281
- if (options.restartDaemon) {
282
- if (!hasInstalledDaemonUnit()) {
283
- console.log(`${c.warn('[WARN]')} No daemon unit detected; skipping restart.`);
284
- return;
285
- }
286
- console.log(`${c.info('[INFO]')} Restarting daemon service...`);
287
- await handleDaemonCommand(['restart', '--mode=system'], {
288
- appRoot: APP_ROOT,
289
- defaultPort: process.env.SERVER_PORT || process.env.PORT || '3001',
290
- color: c,
291
- });
292
- console.log(`${c.ok('[OK]')} Daemon restart completed.`);
293
- return;
294
- }
295
-
296
- if (hasInstalledDaemonUnit()) {
297
- const restartCommand = buildDaemonCliCommand(
298
- { subcommand: 'restart', mode: 'system' },
299
- DAEMON_COMMAND_CONTEXT
300
- );
301
- console.log(`${c.tip('[TIP]')} Daemon unit detected. Restart to apply update: ${c.bright(restartCommand)}`);
302
- console.log(`${c.tip('[TIP]')} Or update + restart in one step: ${c.bright('pixcode update --restart-daemon')}`);
303
- } else {
304
- console.log(`${c.tip('[TIP]')} Restart pixcode to use the new version.`);
305
- }
306
- }
307
-
308
- async function updateGitPackage(options = {}) {
309
- const gitUpdateScript = path.join(APP_ROOT, 'scripts', 'update-git-install.mjs');
310
- if (!fs.existsSync(gitUpdateScript)) {
311
- throw new Error(`Git update script was not found: ${gitUpdateScript}`);
312
- }
313
-
314
- console.log(`${c.info('[INFO]')} Updating Pixcode source checkout...`);
315
- await runInherited(process.execPath, [gitUpdateScript], { cwd: APP_ROOT });
316
- console.log(`${c.ok('[OK]')} Source update complete!`);
317
- await maybeRestartDaemonAfterUpdate(options);
318
- }
319
-
320
- // Update the package
321
- async function updatePackage(options = {}) {
322
- try {
323
- const { execSync } = await import('child_process');
324
- if (installMode === 'git') {
325
- await updateGitPackage(options);
326
- return;
327
- }
328
-
329
- console.log(`${c.info('[INFO]')} Checking for updates...`);
330
-
331
- const { hasUpdate, latestVersion, currentVersion } = await checkForUpdates(true);
332
-
333
- if (!hasUpdate) {
334
- console.log(`${c.ok('[OK]')} Already on the latest version (${currentVersion})`);
335
- return;
336
- }
337
-
338
- console.log(`${c.info('[INFO]')} Updating from ${currentVersion} to ${latestVersion}...`);
339
- execSync('npm update -g @pixelbyte-software/pixcode', { stdio: 'inherit' });
340
- console.log(`${c.ok('[OK]')} Update complete!`);
341
- await maybeRestartDaemonAfterUpdate(options);
342
- } catch (e) {
343
- console.error(`${c.error('[ERROR]')} Update failed: ${e.message}`);
344
- const fallbackCommand = installMode === 'git'
345
- ? 'pixcode update --restart-daemon'
346
- : 'npm update -g @pixelbyte-software/pixcode';
347
- console.log(`${c.tip('[TIP]')} Try running manually: ${fallbackCommand}`);
348
- }
349
- }
350
-
351
- // ── Sandbox command ─────────────────────────────────────────
352
-
353
- const SANDBOX_TEMPLATES = {
354
- claude: 'ghcr.io/alicomert/pixcode-sandbox:claude-code',
355
- codex: 'ghcr.io/alicomert/pixcode-sandbox:codex',
356
- gemini: 'ghcr.io/alicomert/pixcode-sandbox:gemini',
357
- };
358
-
359
- const SANDBOX_SECRETS = {
360
- claude: 'anthropic',
361
- codex: 'openai',
362
- gemini: 'google',
363
- };
364
-
365
- function parseSandboxArgs(args) {
366
- const result = {
367
- subcommand: null,
368
- workspace: null,
369
- agent: 'claude',
370
- name: null,
371
- port: 3001,
372
- template: null,
373
- env: [],
374
- };
375
-
376
- const subcommands = ['ls', 'stop', 'start', 'rm', 'logs', 'help'];
377
-
378
- for (let i = 0; i < args.length; i++) {
379
- const arg = args[i];
380
-
381
- if (i === 0 && subcommands.includes(arg)) {
382
- result.subcommand = arg;
383
- } else if (arg === '--agent' || arg === '-a') {
384
- result.agent = args[++i];
385
- } else if (arg === '--name' || arg === '-n') {
386
- result.name = args[++i];
387
- } else if (arg === '--port') {
388
- result.port = parseInt(args[++i], 10);
389
- } else if (arg === '--template' || arg === '-t') {
390
- result.template = args[++i];
391
- } else if (arg === '--env' || arg === '-e') {
392
- result.env.push(args[++i]);
393
- } else if (!arg.startsWith('-')) {
394
- if (!result.subcommand) {
395
- result.workspace = arg;
396
- } else {
397
- result.name = arg; // for stop/start/rm/logs <name>
398
- }
399
- }
400
- }
401
-
402
- // Default subcommand based on what we got
403
- if (!result.subcommand) {
404
- result.subcommand = 'create';
405
- }
406
-
407
- // Derive name from workspace path if not set
408
- if (!result.name && result.workspace) {
409
- result.name = path.basename(path.resolve(result.workspace.replace(/^~/, os.homedir())));
410
- }
411
-
412
- // Default template from agent
413
- if (!result.template) {
414
- result.template = SANDBOX_TEMPLATES[result.agent] || SANDBOX_TEMPLATES.claude;
415
- }
416
-
417
- return result;
418
- }
419
-
420
- function showSandboxHelp() {
421
- console.log(`
422
- ${c.bright('Pixcode Sandbox')} — Run Pixcode inside Docker Sandboxes
423
-
424
- Usage:
425
- pixcode sandbox <workspace> Create and start a sandbox
426
- pixcode sandbox <subcommand> [name] Manage sandboxes
427
-
428
- Subcommands:
429
- ${c.bright('(default)')} Create a sandbox and start the web UI
430
- ${c.bright('ls')} List all sandboxes
431
- ${c.bright('start')} Restart a stopped sandbox and re-launch the web UI
432
- ${c.bright('stop')} Stop a sandbox (preserves state)
433
- ${c.bright('rm')} Remove a sandbox
434
- ${c.bright('logs')} Show Pixcode server logs
435
- ${c.bright('help')} Show this help
436
-
437
- Options:
438
- -a, --agent <agent> Agent to use: claude, codex, gemini (default: claude)
439
- -n, --name <name> Sandbox name (default: derived from workspace folder)
440
- -t, --template <image> Custom template image
441
- -e, --env <KEY=VALUE> Set environment variable (repeatable)
442
- --port <port> Host port for the web UI (default: 3001)
443
-
444
- Examples:
445
- $ pixcode sandbox ~/my-project
446
- $ pixcode sandbox ~/my-project --agent codex --port 8080
447
- $ pixcode sandbox ~/my-project --env SERVER_PORT=8080 --env HOST=0.0.0.0
448
- $ pixcode sandbox ls
449
- $ pixcode sandbox stop my-project
450
- $ pixcode sandbox start my-project
451
- $ pixcode sandbox rm my-project
452
-
453
- Prerequisites:
454
- 1. Install sbx CLI: https://docs.docker.com/ai/sandboxes/get-started/
455
- 2. Authenticate and store your API key:
456
- sbx login
457
- sbx secret set -g anthropic # for Claude
458
- sbx secret set -g openai # for Codex
459
- sbx secret set -g google # for Gemini
460
-
461
- Advanced usage:
462
- For branch mode, multiple workspaces, memory limits, network policies,
463
- or passing prompts to the agent, use sbx directly with the template:
464
-
465
- sbx run --template ghcr.io/alicomert/pixcode-sandbox:claude-code claude ~/my-project --branch my-feature
466
- sbx run --template ghcr.io/alicomert/pixcode-sandbox:claude-code claude ~/project ~/libs:ro --memory 8g
467
-
468
- Full Docker Sandboxes docs: https://docs.docker.com/ai/sandboxes/usage/
469
- `);
470
- }
471
-
472
- async function sandboxCommand(args) {
473
- const { execFileSync, spawn: spawnProcess } = await import('child_process');
474
-
475
- // Safe execution — uses execFileSync (no shell) to prevent injection
476
- const sbx = (subcmd, opts = {}) => {
477
- const result = execFileSync('sbx', subcmd, {
478
- encoding: 'utf8',
479
- stdio: opts.inherit ? 'inherit' : 'pipe',
480
- });
481
- return result || '';
482
- };
483
-
484
- const opts = parseSandboxArgs(args);
485
-
486
- if (opts.subcommand === 'help') {
487
- showSandboxHelp();
488
- return;
489
- }
490
-
491
- // Validate name (alphanumeric, hyphens, underscores only)
492
- if (opts.name && !/^[\w-]+$/.test(opts.name)) {
493
- console.error(`\n${c.error('❌')} Invalid sandbox name: ${opts.name}`);
494
- console.log(` Names may only contain letters, numbers, hyphens, and underscores.\n`);
495
- process.exit(1);
496
- }
497
-
498
- // Check sbx is installed
499
- try {
500
- sbx(['version']);
501
- } catch {
502
- console.error(`\n${c.error('❌')} ${c.bright('sbx')} CLI not found.\n`);
503
- console.log(` Install it from: ${c.info('https://docs.docker.com/ai/sandboxes/get-started/')}`);
504
- console.log(` Then run: ${c.bright('sbx login')}`);
505
- console.log(` And store your API key: ${c.bright('sbx secret set -g anthropic')}\n`);
506
- process.exit(1);
507
- }
508
-
509
- switch (opts.subcommand) {
510
-
511
- case 'ls':
512
- sbx(['ls'], { inherit: true });
513
- break;
514
-
515
- case 'stop':
516
- if (!opts.name) {
517
- console.error(`\n${c.error('❌')} Sandbox name required: pixcode sandbox stop <name>\n`);
518
- process.exit(1);
519
- }
520
- sbx(['stop', opts.name], { inherit: true });
521
- break;
522
-
523
- case 'rm':
524
- if (!opts.name) {
525
- console.error(`\n${c.error('❌')} Sandbox name required: pixcode sandbox rm <name>\n`);
526
- process.exit(1);
527
- }
528
- sbx(['rm', opts.name], { inherit: true });
529
- break;
530
-
531
- case 'logs':
532
- if (!opts.name) {
533
- console.error(`\n${c.error('❌')} Sandbox name required: pixcode sandbox logs <name>\n`);
534
- process.exit(1);
535
- }
536
- try {
537
- sbx(['exec', opts.name, 'bash', '-c', 'cat /tmp/pixcode-ui.log'], { inherit: true });
538
- } catch (e) {
539
- console.error(`\n${c.error('❌')} Could not read logs: ${e.message || 'Is the sandbox running?'}\n`);
540
- }
541
- break;
542
-
543
- case 'start': {
544
- if (!opts.name) {
545
- console.error(`\n${c.error('❌')} Sandbox name required: pixcode sandbox start <name>\n`);
546
- process.exit(1);
547
- }
548
- console.log(`\n${c.info('▶')} Starting sandbox ${c.bright(opts.name)}...`);
549
- const restartRun = spawnProcess('sbx', ['run', opts.name], {
550
- detached: true,
551
- stdio: ['ignore', 'ignore', 'ignore'],
552
- });
553
- restartRun.unref();
554
- await new Promise(resolve => setTimeout(resolve, 5000));
555
-
556
- console.log(`${c.info('▶')} Launching Pixcode web server...`);
557
- sbx(['exec', opts.name, 'bash', '-c', 'pixcode start --port 3001 &']);
558
-
559
- console.log(`${c.info('▶')} Forwarding port ${opts.port} → 3001...`);
560
- try {
561
- sbx(['ports', opts.name, '--publish', `${opts.port}:3001`]);
562
- } catch (e) {
563
- const msg = e.stdout || e.stderr || e.message || '';
564
- if (msg.includes('address already in use')) {
565
- const altPort = opts.port + 1;
566
- console.log(`${c.warn('⚠')} Port ${opts.port} in use, trying ${altPort}...`);
567
- try {
568
- sbx(['ports', opts.name, '--publish', `${altPort}:3001`]);
569
- opts.port = altPort;
570
- } catch {
571
- console.error(`${c.error('❌')} Ports ${opts.port} and ${altPort} both in use. Use --port to specify a free port.`);
572
- process.exit(1);
573
- }
574
- } else {
575
- throw e;
576
- }
577
- }
578
-
579
- console.log(`\n${c.ok('✔')} ${c.bright('Pixcode is ready!')}`);
580
- console.log(` ${c.info('→')} ${c.bright(`http://localhost:${opts.port}`)}\n`);
581
- break;
582
- }
583
-
584
- case 'create': {
585
- if (!opts.workspace) {
586
- console.error(`\n${c.error('❌')} Workspace path required: pixcode sandbox <path>\n`);
587
- console.log(` Example: ${c.bright('pixcode sandbox ~/my-project')}\n`);
588
- process.exit(1);
589
- }
590
-
591
- const workspace = opts.workspace.startsWith('~')
592
- ? opts.workspace.replace(/^~/, os.homedir())
593
- : path.resolve(opts.workspace);
594
-
595
- if (!fs.existsSync(workspace)) {
596
- console.error(`\n${c.error('❌')} Workspace path not found: ${c.dim(workspace)}\n`);
597
- process.exit(1);
598
- }
599
-
600
- const secret = SANDBOX_SECRETS[opts.agent] || 'anthropic';
601
-
602
- // Check if the required secret is stored
603
- try {
604
- const secretList = sbx(['secret', 'ls']);
605
- if (!secretList.includes(secret)) {
606
- console.error(`\n${c.error('❌')} No ${c.bright(secret)} API key found.\n`);
607
- console.log(` Run: ${c.bright(`sbx secret set -g ${secret}`)}\n`);
608
- process.exit(1);
609
- }
610
- } catch { /* sbx secret ls not available, skip check */ }
611
-
612
- console.log(`\n${c.bright('Pixcode Sandbox')}`);
613
- console.log(c.dim('─'.repeat(50)));
614
- console.log(` Agent: ${c.info(opts.agent)} ${c.dim(`(${secret} credentials)`)}`);
615
- console.log(` Workspace: ${c.dim(workspace)}`);
616
- console.log(` Name: ${c.dim(opts.name)}`);
617
- console.log(` Template: ${c.dim(opts.template)}`);
618
- console.log(` Port: ${c.dim(String(opts.port))}`);
619
- if (opts.env.length > 0) {
620
- console.log(` Env: ${c.dim(opts.env.join(', '))}`);
621
- }
622
- console.log(c.dim('─'.repeat(50)));
623
-
624
- // Step 1: Launch sandbox with sbx run in background.
625
- // sbx run creates the sandbox (or reconnects) AND holds an active session,
626
- // which prevents the sandbox from auto-stopping.
627
- console.log(`\n${c.info('▶')} Creating sandbox ${c.bright(opts.name)}...`);
628
- const bgRun = spawnProcess('sbx', [
629
- 'run', '--template', opts.template, '--name', opts.name, opts.agent, workspace,
630
- ], {
631
- detached: true,
632
- stdio: ['ignore', 'ignore', 'ignore'],
633
- });
634
- bgRun.unref();
635
- // Wait for sandbox to be ready
636
- await new Promise(resolve => setTimeout(resolve, 5000));
637
-
638
- // Step 2: Inject environment variables
639
- if (opts.env.length > 0) {
640
- console.log(`${c.info('▶')} Setting environment variables...`);
641
- const exports = opts.env
642
- .filter(e => /^\w+=.+$/.test(e))
643
- .map(e => `export ${e}`)
644
- .join('\n');
645
- if (exports) {
646
- sbx(['exec', opts.name, 'bash', '-c', `echo '${exports}' >> /etc/sandbox-persistent.sh`]);
647
- }
648
- const invalid = opts.env.filter(e => !/^\w+=.+$/.test(e));
649
- if (invalid.length > 0) {
650
- console.log(`${c.warn('⚠')} Skipped invalid env vars: ${invalid.join(', ')} (expected KEY=VALUE)`);
651
- }
652
- }
653
-
654
- // Step 3: Start Pixcode inside the sandbox
655
- console.log(`${c.info('▶')} Launching Pixcode web server...`);
656
- sbx(['exec', opts.name, 'bash', '-c', 'pixcode start --port 3001 &']);
657
-
658
- // Step 4: Forward port
659
- console.log(`${c.info('▶')} Forwarding port ${opts.port} → 3001...`);
660
- try {
661
- sbx(['ports', opts.name, '--publish', `${opts.port}:3001`]);
662
- } catch (e) {
663
- const msg = e.stdout || e.stderr || e.message || '';
664
- if (msg.includes('address already in use')) {
665
- const altPort = opts.port + 1;
666
- console.log(`${c.warn('⚠')} Port ${opts.port} in use, trying ${altPort}...`);
667
- try {
668
- sbx(['ports', opts.name, '--publish', `${altPort}:3001`]);
669
- opts.port = altPort;
670
- } catch {
671
- console.error(`${c.error('❌')} Ports ${opts.port} and ${altPort} both in use. Use --port to specify a free port.`);
672
- process.exit(1);
673
- }
674
- } else {
675
- throw e;
676
- }
677
- }
678
-
679
- // Done
680
- console.log(`\n${c.ok('✔')} ${c.bright('Pixcode is ready!')}`);
681
- console.log(` ${c.info('→')} Open ${c.bright(`http://localhost:${opts.port}`)}`);
682
- console.log(`\n${c.dim(' Manage with:')}`);
683
- console.log(` ${c.dim('$')} sbx ls`);
684
- console.log(` ${c.dim('$')} sbx stop ${opts.name}`);
685
- console.log(` ${c.dim('$')} sbx start ${opts.name}`);
686
- console.log(` ${c.dim('$')} sbx rm ${opts.name}`);
687
- console.log(`\n${c.dim(' Or install globally:')} npm install -g @pixelbyte-software/pixcode\n`);
688
- break;
689
- }
690
-
691
- default:
692
- showSandboxHelp();
693
- }
694
- }
695
-
696
- // ── Server ──────────────────────────────────────────────────
697
-
698
- // Start the server
699
- async function startServer() {
700
- // Import and run the server
701
- await import('./index.js');
702
- }
703
-
704
- async function reexecAfterStartupUpdate() {
705
- await new Promise((resolve, reject) => {
706
- const child = spawn(process.execPath, process.argv.slice(1), {
707
- cwd: process.cwd(),
708
- env: startupUpdateReexecEnv(),
709
- stdio: 'inherit',
710
- windowsHide: false,
711
- });
712
- child.on('error', reject);
713
- child.on('close', (code, signal) => {
714
- if (signal) {
715
- process.kill(process.pid, signal);
716
- return;
717
- }
718
- process.exit(code ?? 0);
719
- });
720
- });
721
- }
722
-
723
- async function runStartupUpdateGate() {
724
- const result = await runStartupAutoUpdate({
725
- appRoot: APP_ROOT,
726
- currentVersion: packageJson.version,
727
- installMode,
728
- color: c,
729
- });
730
-
731
- if (result.failed) {
732
- console.log(`${c.warn('[WARN]')} Startup update check failed: ${result.error}`);
733
- console.log(`${c.tip('[TIP]')} Continuing with the current version (${packageJson.version}).`);
734
- return false;
735
- }
736
-
737
- if (result.skipped && result.reason && process.env.PIXCODE_DEBUG_STARTUP_UPDATE === '1') {
738
- console.log(`${c.dim('[INFO]')} Startup update skipped: ${result.reason}`);
739
- }
740
-
741
- if (!result.updated) {
742
- return false;
743
- }
744
-
745
- console.log(`${c.ok('[OK]')} Startup update applied${result.version ? ` (${result.version})` : ''}.`);
746
- if (result.restartMode === 'exit42') {
747
- console.log(`${c.info('[INFO]')} Restarting through the desktop wrapper before opening the port...`);
748
- process.exit(42);
749
- }
750
-
751
- console.log(`${c.info('[INFO]')} Restarting Pixcode on the updated code before opening the port...`);
752
- await reexecAfterStartupUpdate();
753
- return true;
754
- }
755
-
756
- async function isPortOpen(port, timeoutMs = 800) {
757
- return await new Promise((resolve) => {
758
- const socket = net.createConnection({ host: '127.0.0.1', port: Number(port) });
759
- let settled = false;
760
- const done = (value) => {
761
- if (settled) return;
762
- settled = true;
763
- socket.destroy();
764
- resolve(value);
765
- };
766
-
767
- socket.setTimeout(timeoutMs);
768
- socket.once('connect', () => done(true));
769
- socket.once('timeout', () => done(false));
770
- socket.once('error', () => done(false));
771
- });
772
- }
773
-
774
- async function waitForPortOpen(port, timeoutMs = 25000) {
775
- const deadline = Date.now() + timeoutMs;
776
- while (Date.now() < deadline) {
777
- if (await isPortOpen(port)) {
778
- return true;
779
- }
780
- await new Promise(resolve => setTimeout(resolve, 1000));
781
- }
782
- return false;
783
- }
784
-
785
- function printSystemDaemonActiveNotice(port) {
786
- const effectivePort = Number(port) || 3001;
787
- const statusCommand = buildDaemonCliCommand(
788
- { subcommand: 'status', mode: 'system' },
789
- DAEMON_COMMAND_CONTEXT
790
- );
791
- const stopCommand = buildDaemonCliCommand(
792
- { subcommand: 'stop', mode: 'system' },
793
- DAEMON_COMMAND_CONTEXT
794
- );
795
- const logsCommand = buildDaemonCliCommand(
796
- { subcommand: 'logs', mode: 'system' },
797
- DAEMON_COMMAND_CONTEXT
798
- );
799
- console.log(`${c.ok('[OK]')} System daemon is active and managing Pixcode.`);
800
- console.log(`${c.info('[INFO]')} Health URL: ${c.bright(`http://localhost:${effectivePort}/health`)}`);
801
- console.log(`${c.info('[INFO]')} Status: ${c.bright(statusCommand)}`);
802
- console.log(`${c.info('[INFO]')} Stop: ${c.bright(stopCommand)}`);
803
- console.log(`${c.info('[INFO]')} Logs: ${c.bright(logsCommand)}`);
804
- }
805
-
806
- function printUserDaemonActiveNotice(port) {
807
- const effectivePort = Number(port) || 3001;
808
- const statusCommand = buildDaemonCliCommand(
809
- { subcommand: 'status', mode: 'user' },
810
- DAEMON_COMMAND_CONTEXT
811
- );
812
- const stopCommand = buildDaemonCliCommand(
813
- { subcommand: 'stop', mode: 'user' },
814
- DAEMON_COMMAND_CONTEXT
815
- );
816
- const logsCommand = buildDaemonCliCommand(
817
- { subcommand: 'logs', mode: 'user' },
818
- DAEMON_COMMAND_CONTEXT
819
- );
820
- console.log(`${c.ok('[OK]')} User daemon is active for this account.`);
821
- console.log(`${c.info('[INFO]')} UI: ${c.bright(`http://localhost:${effectivePort}`)}`);
822
- console.log(`${c.info('[INFO]')} Status: ${c.bright(statusCommand)}`);
823
- console.log(`${c.info('[INFO]')} Stop: ${c.bright(stopCommand)}`);
824
- console.log(`${c.info('[INFO]')} Logs: ${c.bright(logsCommand)}`);
825
- console.log(`${c.tip('[TIP]')} For login/reboot persistence, enable linger once: ${c.bright(`sudo loginctl enable-linger ${os.userInfo().username}`)}`);
826
- }
827
-
828
- function isSystemPermissionError(error) {
829
- const message = String(error?.message || error || '');
830
- 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);
831
- }
832
-
833
- function buildAutoInstallArgs(mode, options) {
834
- const args = ['install', `--mode=${mode}`];
835
- if (options.serverPort) {
836
- args.push('--port', String(options.serverPort));
837
- }
838
- if (options.databasePath) {
839
- args.push('--database-path', String(options.databasePath));
840
- }
841
- args.push('--single-port');
842
- return args;
843
- }
844
-
845
- async function maybeAutoDaemonStart(options = {}) {
846
- if (process.platform !== 'linux') return false;
847
- if (process.env.PIXCODE_DAEMON_MANAGED === '1') return false;
848
- if (process.env.PIXCODE_NO_DAEMON === '1') return false;
849
- if (process.env.PIXCODE_DAEMON_ATTEMPTED === '1') return false;
850
- if (options.noDaemon) return false;
851
-
852
- process.env.PIXCODE_DAEMON_ATTEMPTED = '1';
853
- const daemonPort = Number(options.serverPort || process.env.SERVER_PORT || process.env.PORT || '3001');
854
- const systemArgs = buildAutoInstallArgs('system', options);
855
- const userArgs = buildAutoInstallArgs('user', options);
856
-
857
- try {
858
- console.log(`${c.info('[INFO]')} Linux detected. Enforcing system daemon mode for Pixcode...`);
859
- await handleDaemonCommand(systemArgs, {
860
- appRoot: APP_ROOT,
861
- defaultPort: process.env.SERVER_PORT || process.env.PORT || '3001',
862
- color: c,
863
- });
864
- return true;
865
- } catch (systemError) {
866
- const healthySoon = await waitForPortOpen(daemonPort);
867
- if (healthySoon) {
868
- console.log(`${c.warn('[WARN]')} System daemon health check was delayed, but port ${daemonPort} is now reachable.`);
869
- printSystemDaemonActiveNotice(daemonPort);
870
- return true;
871
- }
872
-
873
- if (!isSystemPermissionError(systemError)) {
874
- const installSystemCommand = buildDaemonCliCommand(
875
- {
876
- subcommand: 'install',
877
- mode: 'system',
878
- extraArgs: ['--port', String(daemonPort), '--single-port'],
879
- },
880
- DAEMON_COMMAND_CONTEXT
881
- );
882
- throw new Error(
883
- `System daemon bootstrap failed.\n` +
884
- `${systemError.message}\n` +
885
- `Run with privileges: ${installSystemCommand}`
886
- );
887
- }
888
-
889
- console.log(`${c.warn('[WARN]')} System daemon setup requires elevated privileges for this user.`);
890
- console.log(`${c.info('[INFO]')} Falling back to user daemon mode for account "${os.userInfo().username}"...`);
891
-
892
- try {
893
- await handleDaemonCommand(userArgs, {
894
- appRoot: APP_ROOT,
895
- defaultPort: process.env.SERVER_PORT || process.env.PORT || '3001',
896
- color: c,
897
- });
898
- printUserDaemonActiveNotice(daemonPort);
899
- return true;
900
- } catch (userError) {
901
- const userHealthySoon = await waitForPortOpen(daemonPort);
902
- if (userHealthySoon) {
903
- console.log(`${c.warn('[WARN]')} User daemon health check was delayed, but port ${daemonPort} is now reachable.`);
904
- printUserDaemonActiveNotice(daemonPort);
905
- return true;
906
- }
907
- const installSystemCommand = buildDaemonCliCommand(
908
- {
909
- subcommand: 'install',
910
- mode: 'system',
911
- extraArgs: ['--port', String(daemonPort), '--single-port'],
912
- },
913
- DAEMON_COMMAND_CONTEXT
914
- );
915
- const installUserCommand = buildDaemonCliCommand(
916
- {
917
- subcommand: 'install',
918
- mode: 'user',
919
- extraArgs: ['--port', String(daemonPort), '--single-port'],
920
- },
921
- DAEMON_COMMAND_CONTEXT
922
- );
923
- throw new Error(
924
- `System daemon bootstrap failed.\n` +
925
- `${systemError.message}\n\n` +
926
- `User daemon fallback also failed.\n` +
927
- `${userError.message}\n` +
928
- `Try one of:\n` +
929
- `1) ${installSystemCommand}\n` +
930
- `2) ${installUserCommand}`
931
- );
932
- }
933
- }
934
- }
935
-
936
- // Parse CLI arguments
937
- function parseArgs(args) {
938
- const parsed = { command: 'start', options: {} };
939
- let commandSet = false;
940
-
941
- for (let i = 0; i < args.length; i++) {
942
- const arg = args[i];
943
-
944
- if (arg === '--port' || arg === '-p') {
945
- parsed.options.serverPort = args[++i];
946
- } else if (arg.startsWith('--port=')) {
947
- parsed.options.serverPort = arg.split('=')[1];
948
- } else if (arg === '--database-path') {
949
- parsed.options.databasePath = args[++i];
950
- } else if (arg.startsWith('--database-path=')) {
951
- parsed.options.databasePath = arg.split('=')[1];
952
- } else if (arg === '--no-daemon') {
953
- parsed.options.noDaemon = true;
954
- } else if (arg === '--no-browser') {
955
- parsed.options.noBrowser = true;
956
- } else if (arg === '--restart-daemon') {
957
- parsed.options.restartDaemon = true;
958
- } else if (arg === '--help' || arg === '-h') {
959
- parsed.command = 'help';
960
- commandSet = true;
961
- } else if (arg === '--version' || arg === '-v') {
962
- parsed.command = 'version';
963
- commandSet = true;
964
- } else if (!arg.startsWith('-')) {
965
- if (!commandSet) {
966
- parsed.command = arg;
967
- commandSet = true;
968
- }
969
- if (arg === 'sandbox' || arg === 'daemon') {
970
- parsed.remainingArgs = args.slice(i + 1);
971
- break;
972
- }
973
- }
974
- }
975
-
976
- return parsed;
977
- }
978
-
979
- // Main CLI handler
980
- async function main() {
981
- const args = process.argv.slice(2);
982
- const { command, options, remainingArgs } = parseArgs(args);
983
-
984
- // Apply CLI options to environment variables
985
- if (options.serverPort) {
986
- process.env.SERVER_PORT = options.serverPort;
987
- } else if (!process.env.SERVER_PORT && process.env.PORT) {
988
- process.env.SERVER_PORT = process.env.PORT;
989
- }
990
- if (options.noDaemon) {
991
- process.env.PIXCODE_NO_DAEMON = '1';
992
- }
993
- if (options.noBrowser) {
994
- process.env.PIXCODE_NO_BROWSER = '1';
995
- }
996
- if (options.databasePath) {
997
- process.env.DATABASE_PATH = options.databasePath;
998
- }
999
-
1000
- switch (command) {
1001
- case 'start':
1002
- if (process.env.PIXCODE_ENABLE_STARTUP_UPDATE === '1' && await runStartupUpdateGate()) {
1003
- break;
1004
- }
1005
- {
1006
- const effectivePort = Number(options.serverPort || process.env.SERVER_PORT || process.env.PORT || '3001');
1007
-
1008
- // First-run setup wizard
1009
- if (isFirstRun()) {
1010
- const wizardResult = await runSetupWizard(options);
1011
- if (wizardResult) {
1012
- if (!options.serverPort) {
1013
- process.env.SERVER_PORT = String(wizardResult.port);
1014
- }
1015
- if (wizardResult.useDaemon === false) {
1016
- options.noDaemon = true;
1017
- process.env.PIXCODE_NO_DAEMON = '1';
1018
- }
1019
- }
1020
- }
1021
-
1022
- // Port conflict detection (every run, not just first)
1023
- const currentPort = Number(options.serverPort || process.env.SERVER_PORT || process.env.PORT || '3001');
1024
- if (!await isPortAvailable(currentPort)) {
1025
- const alreadyRunning = await waitForServerReady(currentPort, 2000);
1026
- if (alreadyRunning) {
1027
- console.log(`\n${c.ok('[OK]')} Pixcode is already running on port ${c.bright(String(currentPort))}.`);
1028
- await postStartupGuidance(currentPort);
1029
- break;
1030
- }
1031
- console.log(`\n${c.warn('[WARN]')} Port ${c.bright(String(currentPort))} is in use by another process.`);
1032
- const altPort = await findAvailablePort(currentPort + 1);
1033
- if (altPort) {
1034
- console.log(`${c.info('[INFO]')} Switching to port ${c.bright(String(altPort))}.`);
1035
- process.env.SERVER_PORT = String(altPort);
1036
- options.serverPort = String(altPort);
1037
- } else {
1038
- console.error(`${c.error('[ERROR]')} No free ports found. Specify one with ${c.bright('--port <port>')}.`);
1039
- process.exit(1);
1040
- }
1041
- }
1042
- }
1043
- if (await maybeAutoDaemonStart(options)) {
1044
- const daemonPort = Number(options.serverPort || process.env.SERVER_PORT || process.env.PORT || '3001');
1045
- const ready = await waitForServerReady(daemonPort, 15000);
1046
- if (ready) {
1047
- await postStartupGuidance(daemonPort);
1048
- }
1049
- break;
1050
- }
1051
- await startServer();
1052
- break;
1053
- case 'setup':
1054
- {
1055
- const wizardResult = await runSetupWizard(options);
1056
- if (wizardResult) {
1057
- process.env.SERVER_PORT = String(wizardResult.port);
1058
- if (wizardResult.useDaemon === false) {
1059
- options.noDaemon = true;
1060
- process.env.PIXCODE_NO_DAEMON = '1';
1061
- }
1062
- }
1063
- console.log(`\n${c.ok('[OK]')} Setup complete! Run ${c.bright('pixcode start')} to launch.`);
1064
- }
1065
- break;
1066
- case 'sandbox':
1067
- await sandboxCommand(remainingArgs || []);
1068
- break;
1069
- case 'daemon':
1070
- await handleDaemonCommand(remainingArgs || [], {
1071
- appRoot: APP_ROOT,
1072
- defaultPort: process.env.SERVER_PORT || process.env.PORT || '3001',
1073
- color: c,
1074
- cliEntry: process.argv[1],
1075
- nodeExecPath: process.execPath,
1076
- });
1077
- break;
1078
- case 'status':
1079
- case 'info':
1080
- showStatus();
1081
- break;
1082
- case 'help':
1083
- case '-h':
1084
- case '--help':
1085
- showHelp();
1086
- break;
1087
- case 'version':
1088
- case '-v':
1089
- case '--version':
1090
- showVersion();
1091
- break;
1092
- case 'update':
1093
- await updatePackage(options);
1094
- break;
1095
- default:
1096
- console.error(`\n❌ Unknown command: ${command}`);
1097
- console.log(' Run "pixcode help" for usage information.\n');
1098
- process.exit(1);
1099
- }
1100
- }
1101
-
1102
- // Run the CLI
1103
- main().catch(error => {
1104
- console.error('\n❌ Error:', error.message);
1105
- process.exit(1);
1106
- });
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
+ * setup - Run the interactive setup wizard
11
+ * sandbox - Manage Docker sandbox environments
12
+ * daemon - Manage persistent Linux service modes
13
+ * status - Show configuration and data locations
14
+ * help - Show help information
15
+ * version - Show version information
16
+ */
17
+
18
+ import fs from 'fs';
19
+ import path from 'path';
20
+ import os from 'os';
21
+ import net from 'node:net';
22
+ import { spawn } from 'node:child_process';
23
+
24
+ import { findAppRoot, getModuleDir } from './utils/runtime-paths.js';
25
+ import { buildDaemonCliCommand, handleDaemonCommand, hasInstalledDaemonUnit } from './daemon-manager.js';
26
+ import { runStartupAutoUpdate, startupUpdateReexecEnv } from './services/startup-update.js';
27
+ import { runSetupWizard, postStartupGuidance, isFirstRun, isPortAvailable, findAvailablePort, waitForServerReady } from './setup-wizard.js';
28
+
29
+ const __dirname = getModuleDir(import.meta.url);
30
+ // The CLI is compiled into dist-server/server, but it still needs to read the top-level
31
+ // package.json and .env file. Resolving the app root once keeps those lookups stable.
32
+ const APP_ROOT = findAppRoot(__dirname);
33
+ const DAEMON_COMMAND_CONTEXT = {
34
+ appRoot: APP_ROOT,
35
+ cliEntry: process.argv[1],
36
+ nodeExecPath: process.execPath,
37
+ };
38
+
39
+ // ANSI color codes for terminal output
40
+ const colors = {
41
+ reset: '\x1b[0m',
42
+ bright: '\x1b[1m',
43
+ dim: '\x1b[2m',
44
+
45
+ // Foreground colors
46
+ cyan: '\x1b[36m',
47
+ green: '\x1b[32m',
48
+ yellow: '\x1b[33m',
49
+ blue: '\x1b[34m',
50
+ magenta: '\x1b[35m',
51
+ white: '\x1b[37m',
52
+ gray: '\x1b[90m',
53
+ };
54
+
55
+ // Helper to colorize text
56
+ const c = {
57
+ info: (text) => `${colors.cyan}${text}${colors.reset}`,
58
+ ok: (text) => `${colors.green}${text}${colors.reset}`,
59
+ warn: (text) => `${colors.yellow}${text}${colors.reset}`,
60
+ error: (text) => `${colors.yellow}${text}${colors.reset}`,
61
+ tip: (text) => `${colors.blue}${text}${colors.reset}`,
62
+ bright: (text) => `${colors.bright}${text}${colors.reset}`,
63
+ dim: (text) => `${colors.dim}${text}${colors.reset}`,
64
+ };
65
+
66
+ // Load package.json for version info
67
+ const packageJsonPath = path.join(APP_ROOT, 'package.json');
68
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
69
+ const installMode = fs.existsSync(path.join(APP_ROOT, '.git')) ? 'git' : 'npm';
70
+ // Match the runtime fallback in load-env.js so "pixcode status" reports the same default
71
+ // database location that the backend will actually use when no DATABASE_PATH is configured.
72
+ const DEFAULT_DATABASE_PATH = path.join(os.homedir(), '.pixcode', 'auth.db');
73
+
74
+ // Load environment variables from .env file if it exists
75
+ function loadEnvFile() {
76
+ try {
77
+ const envPath = path.join(APP_ROOT, '.env');
78
+ const envFile = fs.readFileSync(envPath, 'utf8');
79
+ envFile.split('\n').forEach(line => {
80
+ const trimmedLine = line.trim();
81
+ if (trimmedLine && !trimmedLine.startsWith('#')) {
82
+ const [key, ...valueParts] = trimmedLine.split('=');
83
+ if (key && valueParts.length > 0 && !process.env[key]) {
84
+ process.env[key] = valueParts.join('=').trim();
85
+ }
86
+ }
87
+ });
88
+ } catch (e) {
89
+ // .env file is optional
90
+ }
91
+ }
92
+
93
+ // Get the database path (same logic as db.js)
94
+ function getDatabasePath() {
95
+ loadEnvFile();
96
+ return process.env.DATABASE_PATH || DEFAULT_DATABASE_PATH;
97
+ }
98
+
99
+ // Get the installation directory
100
+ function getInstallDir() {
101
+ return APP_ROOT;
102
+ }
103
+
104
+ // Show status command
105
+ function showStatus() {
106
+ console.log(`\n${c.bright('Pixcode - Status')}\n`);
107
+ console.log(c.dim('═'.repeat(60)));
108
+
109
+ // Version info
110
+ console.log(`\n${c.info('[INFO]')} Version: ${c.bright(packageJson.version)}`);
111
+
112
+ // Installation location
113
+ const installDir = getInstallDir();
114
+ console.log(`\n${c.info('[INFO]')} Installation Directory:`);
115
+ console.log(` ${c.dim(installDir)}`);
116
+
117
+ // Database location
118
+ const dbPath = getDatabasePath();
119
+ const dbExists = fs.existsSync(dbPath);
120
+ console.log(`\n${c.info('[INFO]')} Database Location:`);
121
+ console.log(` ${c.dim(dbPath)}`);
122
+ console.log(` Status: ${dbExists ? c.ok('[OK] Exists') : c.warn('[WARN] Not created yet (will be created on first run)')}`);
123
+
124
+ if (dbExists) {
125
+ const stats = fs.statSync(dbPath);
126
+ console.log(` Size: ${c.dim((stats.size / 1024).toFixed(2) + ' KB')}`);
127
+ console.log(` Modified: ${c.dim(stats.mtime.toLocaleString())}`);
128
+ }
129
+
130
+ // Environment variables
131
+ console.log(`\n${c.info('[INFO]')} Configuration:`);
132
+ console.log(` SERVER_PORT: ${c.bright(process.env.SERVER_PORT || process.env.PORT || '3001')} ${c.dim(process.env.SERVER_PORT || process.env.PORT ? '' : '(default)')}`);
133
+ console.log(` DATABASE_PATH: ${c.dim(process.env.DATABASE_PATH || '(using default location)')}`);
134
+ console.log(` CLAUDE_CLI_PATH: ${c.dim(process.env.CLAUDE_CLI_PATH || 'claude (default)')}`);
135
+ console.log(` CONTEXT_WINDOW: ${c.dim(process.env.CONTEXT_WINDOW || '160000 (default)')}`);
136
+
137
+ // Claude projects folder
138
+ const claudeProjectsPath = path.join(os.homedir(), '.claude', 'projects');
139
+ const projectsExists = fs.existsSync(claudeProjectsPath);
140
+ console.log(`\n${c.info('[INFO]')} Claude Projects Folder:`);
141
+ console.log(` ${c.dim(claudeProjectsPath)}`);
142
+ console.log(` Status: ${projectsExists ? c.ok('[OK] Exists') : c.warn('[WARN] Not found')}`);
143
+
144
+ // Config file location
145
+ const envFilePath = path.join(APP_ROOT, '.env');
146
+ const envExists = fs.existsSync(envFilePath);
147
+ console.log(`\n${c.info('[INFO]')} Configuration File:`);
148
+ console.log(` ${c.dim(envFilePath)}`);
149
+ // Missing .env is fine — Pixcode ships sensible defaults. Keep this
150
+ // purely informational so users don't misread an "[INFO] optional"
151
+ // line as an install-time failure.
152
+ console.log(` Status: ${envExists ? c.ok('[OK] Exists') : c.info('[INFO] Optional — running on defaults')}`);
153
+
154
+ console.log('\n' + c.dim('═'.repeat(60)));
155
+ console.log(`\n${c.tip('[TIP]')} Hints:`);
156
+ console.log(` ${c.dim('>')} Use ${c.bright('pixcode --port 8080')} to run on a custom port`);
157
+ console.log(` ${c.dim('>')} Use ${c.bright('pixcode --database-path /path/to/db')} for custom database`);
158
+ console.log(` ${c.dim('>')} Run ${c.bright('pixcode help')} for all options`);
159
+ console.log(` ${c.dim('>')} Access the UI at http://localhost:${process.env.SERVER_PORT || process.env.PORT || '3001'}\n`);
160
+ }
161
+
162
+ // Show help
163
+ function showHelp() {
164
+ console.log(`
165
+ ╔═══════════════════════════════════════════════════════════════╗
166
+ ║ Pixcode - Command Line Tool ║
167
+ ╚═══════════════════════════════════════════════════════════════╝
168
+
169
+ Usage:
170
+ pixcode [command] [options]
171
+
172
+ Commands:
173
+ start Start the Pixcode server (default)
174
+ setup Run the interactive setup wizard (port, mode, browser)
175
+ daemon Manage persistent Linux service (system-first)
176
+ sandbox Manage Docker sandbox environments
177
+ status Show configuration and data locations
178
+ update Update to the latest version
179
+ help Show this help information
180
+ version Show version information
181
+
182
+ Options:
183
+ -p, --port <port> Set server port (default: 3001)
184
+ --database-path <path> Set custom database location
185
+ --no-daemon Disable automatic daemon startup on Linux
186
+ --no-browser Do not auto-open browser on startup
187
+ --restart-daemon Restart daemon automatically after update
188
+ -h, --help Show this help information
189
+ -v, --version Show version information
190
+
191
+ Examples:
192
+ $ pixcode # Start with defaults
193
+ $ pixcode setup # Run the interactive setup wizard
194
+ $ pixcode --port 8080 # Start on port 8080
195
+ $ pixcode --no-daemon # Force foreground mode
196
+ $ pixcode --no-browser # Start without auto-opening browser
197
+ $ sudo pixcode daemon install --mode system --port 3001
198
+ $ pixcode daemon install --mode user --port 3001 --single-port
199
+ $ pixcode daemon doctor --mode system
200
+ $ pixcode update --restart-daemon
201
+ $ pixcode sandbox ~/my-project # Run in a Docker sandbox
202
+ $ pixcode status # Show configuration
203
+
204
+ Environment Variables:
205
+ SERVER_PORT Set server port (default: 3001)
206
+ PORT Set server port (default: 3001) (LEGACY)
207
+ DATABASE_PATH Set custom database location
208
+ CLAUDE_CLI_PATH Set custom Claude CLI path
209
+ CONTEXT_WINDOW Set context window size (default: 160000)
210
+
211
+ Documentation:
212
+ ${packageJson.homepage || 'https://github.com/alicomert/pixcode'}
213
+
214
+ Report Issues:
215
+ ${packageJson.bugs?.url || 'https://github.com/alicomert/pixcode/issues'}
216
+ `);
217
+ }
218
+
219
+ // Show version
220
+ function showVersion() {
221
+ console.log(`${packageJson.version}`);
222
+ }
223
+
224
+ // Compare semver versions, returns true if v1 > v2
225
+ function isNewerVersion(v1, v2) {
226
+ const parts1 = v1.split('.').map(Number);
227
+ const parts2 = v2.split('.').map(Number);
228
+ for (let i = 0; i < 3; i++) {
229
+ if (parts1[i] > parts2[i]) return true;
230
+ if (parts1[i] < parts2[i]) return false;
231
+ }
232
+ return false;
233
+ }
234
+
235
+ // Check for updates
236
+ async function checkForUpdates(silent = false) {
237
+ try {
238
+ const { execSync } = await import('child_process');
239
+ const latestVersion = execSync('npm show @pixelbyte-software/pixcode version', { encoding: 'utf8' }).trim();
240
+ const currentVersion = packageJson.version;
241
+
242
+ if (isNewerVersion(latestVersion, currentVersion)) {
243
+ console.log(`\n${c.warn('[UPDATE]')} New version available: ${c.bright(latestVersion)} (current: ${currentVersion})`);
244
+ console.log(` Run ${c.bright('pixcode update')} to update\n`);
245
+ return { hasUpdate: true, latestVersion, currentVersion };
246
+ } else if (!silent) {
247
+ console.log(`${c.ok('[OK]')} You are on the latest version (${currentVersion})`);
248
+ }
249
+ return { hasUpdate: false, latestVersion, currentVersion };
250
+ } catch (e) {
251
+ if (!silent) {
252
+ console.log(`${c.warn('[WARN]')} Could not check for updates`);
253
+ }
254
+ return { hasUpdate: false, error: e.message };
255
+ }
256
+ }
257
+
258
+ function runInherited(command, args, options = {}) {
259
+ return new Promise((resolve, reject) => {
260
+ const child = spawn(command, args, {
261
+ cwd: options.cwd || APP_ROOT,
262
+ env: options.env || process.env,
263
+ stdio: 'inherit',
264
+ shell: false,
265
+ windowsHide: false,
266
+ });
267
+
268
+ child.on('error', reject);
269
+ child.on('close', (code) => {
270
+ if (code === 0) {
271
+ resolve();
272
+ return;
273
+ }
274
+
275
+ reject(new Error(`${command} ${args.join(' ')} exited with code ${code}`));
276
+ });
277
+ });
278
+ }
279
+
280
+ async function maybeRestartDaemonAfterUpdate(options = {}) {
281
+ if (options.restartDaemon) {
282
+ if (!hasInstalledDaemonUnit()) {
283
+ console.log(`${c.warn('[WARN]')} No daemon unit detected; skipping restart.`);
284
+ return;
285
+ }
286
+ console.log(`${c.info('[INFO]')} Restarting daemon service...`);
287
+ await handleDaemonCommand(['restart', '--mode=system'], {
288
+ appRoot: APP_ROOT,
289
+ defaultPort: process.env.SERVER_PORT || process.env.PORT || '3001',
290
+ color: c,
291
+ });
292
+ console.log(`${c.ok('[OK]')} Daemon restart completed.`);
293
+ return;
294
+ }
295
+
296
+ if (hasInstalledDaemonUnit()) {
297
+ const restartCommand = buildDaemonCliCommand(
298
+ { subcommand: 'restart', mode: 'system' },
299
+ DAEMON_COMMAND_CONTEXT
300
+ );
301
+ console.log(`${c.tip('[TIP]')} Daemon unit detected. Restart to apply update: ${c.bright(restartCommand)}`);
302
+ console.log(`${c.tip('[TIP]')} Or update + restart in one step: ${c.bright('pixcode update --restart-daemon')}`);
303
+ } else {
304
+ console.log(`${c.tip('[TIP]')} Restart pixcode to use the new version.`);
305
+ }
306
+ }
307
+
308
+ async function updateGitPackage(options = {}) {
309
+ const gitUpdateScript = path.join(APP_ROOT, 'scripts', 'update-git-install.mjs');
310
+ if (!fs.existsSync(gitUpdateScript)) {
311
+ throw new Error(`Git update script was not found: ${gitUpdateScript}`);
312
+ }
313
+
314
+ console.log(`${c.info('[INFO]')} Updating Pixcode source checkout...`);
315
+ await runInherited(process.execPath, [gitUpdateScript], { cwd: APP_ROOT });
316
+ console.log(`${c.ok('[OK]')} Source update complete!`);
317
+ await maybeRestartDaemonAfterUpdate(options);
318
+ }
319
+
320
+ // Update the package
321
+ async function updatePackage(options = {}) {
322
+ try {
323
+ const { execSync } = await import('child_process');
324
+ if (installMode === 'git') {
325
+ await updateGitPackage(options);
326
+ return;
327
+ }
328
+
329
+ console.log(`${c.info('[INFO]')} Checking for updates...`);
330
+
331
+ const { hasUpdate, latestVersion, currentVersion } = await checkForUpdates(true);
332
+
333
+ if (!hasUpdate) {
334
+ console.log(`${c.ok('[OK]')} Already on the latest version (${currentVersion})`);
335
+ return;
336
+ }
337
+
338
+ console.log(`${c.info('[INFO]')} Updating from ${currentVersion} to ${latestVersion}...`);
339
+ execSync('npm update -g @pixelbyte-software/pixcode', { stdio: 'inherit' });
340
+ console.log(`${c.ok('[OK]')} Update complete!`);
341
+ await maybeRestartDaemonAfterUpdate(options);
342
+ } catch (e) {
343
+ console.error(`${c.error('[ERROR]')} Update failed: ${e.message}`);
344
+ const fallbackCommand = installMode === 'git'
345
+ ? 'pixcode update --restart-daemon'
346
+ : 'npm update -g @pixelbyte-software/pixcode';
347
+ console.log(`${c.tip('[TIP]')} Try running manually: ${fallbackCommand}`);
348
+ }
349
+ }
350
+
351
+ // ── Sandbox command ─────────────────────────────────────────
352
+
353
+ const SANDBOX_TEMPLATES = {
354
+ claude: 'ghcr.io/alicomert/pixcode-sandbox:claude-code',
355
+ codex: 'ghcr.io/alicomert/pixcode-sandbox:codex',
356
+ gemini: 'ghcr.io/alicomert/pixcode-sandbox:gemini',
357
+ };
358
+
359
+ const SANDBOX_SECRETS = {
360
+ claude: 'anthropic',
361
+ codex: 'openai',
362
+ gemini: 'google',
363
+ };
364
+
365
+ function parseSandboxArgs(args) {
366
+ const result = {
367
+ subcommand: null,
368
+ workspace: null,
369
+ agent: 'claude',
370
+ name: null,
371
+ port: 3001,
372
+ template: null,
373
+ env: [],
374
+ };
375
+
376
+ const subcommands = ['ls', 'stop', 'start', 'rm', 'logs', 'help'];
377
+
378
+ for (let i = 0; i < args.length; i++) {
379
+ const arg = args[i];
380
+
381
+ if (i === 0 && subcommands.includes(arg)) {
382
+ result.subcommand = arg;
383
+ } else if (arg === '--agent' || arg === '-a') {
384
+ result.agent = args[++i];
385
+ } else if (arg === '--name' || arg === '-n') {
386
+ result.name = args[++i];
387
+ } else if (arg === '--port') {
388
+ result.port = parseInt(args[++i], 10);
389
+ } else if (arg === '--template' || arg === '-t') {
390
+ result.template = args[++i];
391
+ } else if (arg === '--env' || arg === '-e') {
392
+ result.env.push(args[++i]);
393
+ } else if (!arg.startsWith('-')) {
394
+ if (!result.subcommand) {
395
+ result.workspace = arg;
396
+ } else {
397
+ result.name = arg; // for stop/start/rm/logs <name>
398
+ }
399
+ }
400
+ }
401
+
402
+ // Default subcommand based on what we got
403
+ if (!result.subcommand) {
404
+ result.subcommand = 'create';
405
+ }
406
+
407
+ // Derive name from workspace path if not set
408
+ if (!result.name && result.workspace) {
409
+ result.name = path.basename(path.resolve(result.workspace.replace(/^~/, os.homedir())));
410
+ }
411
+
412
+ // Default template from agent
413
+ if (!result.template) {
414
+ result.template = SANDBOX_TEMPLATES[result.agent] || SANDBOX_TEMPLATES.claude;
415
+ }
416
+
417
+ return result;
418
+ }
419
+
420
+ function showSandboxHelp() {
421
+ console.log(`
422
+ ${c.bright('Pixcode Sandbox')} — Run Pixcode inside Docker Sandboxes
423
+
424
+ Usage:
425
+ pixcode sandbox <workspace> Create and start a sandbox
426
+ pixcode sandbox <subcommand> [name] Manage sandboxes
427
+
428
+ Subcommands:
429
+ ${c.bright('(default)')} Create a sandbox and start the web UI
430
+ ${c.bright('ls')} List all sandboxes
431
+ ${c.bright('start')} Restart a stopped sandbox and re-launch the web UI
432
+ ${c.bright('stop')} Stop a sandbox (preserves state)
433
+ ${c.bright('rm')} Remove a sandbox
434
+ ${c.bright('logs')} Show Pixcode server logs
435
+ ${c.bright('help')} Show this help
436
+
437
+ Options:
438
+ -a, --agent <agent> Agent to use: claude, codex, gemini (default: claude)
439
+ -n, --name <name> Sandbox name (default: derived from workspace folder)
440
+ -t, --template <image> Custom template image
441
+ -e, --env <KEY=VALUE> Set environment variable (repeatable)
442
+ --port <port> Host port for the web UI (default: 3001)
443
+
444
+ Examples:
445
+ $ pixcode sandbox ~/my-project
446
+ $ pixcode sandbox ~/my-project --agent codex --port 8080
447
+ $ pixcode sandbox ~/my-project --env SERVER_PORT=8080 --env HOST=0.0.0.0
448
+ $ pixcode sandbox ls
449
+ $ pixcode sandbox stop my-project
450
+ $ pixcode sandbox start my-project
451
+ $ pixcode sandbox rm my-project
452
+
453
+ Prerequisites:
454
+ 1. Install sbx CLI: https://docs.docker.com/ai/sandboxes/get-started/
455
+ 2. Authenticate and store your API key:
456
+ sbx login
457
+ sbx secret set -g anthropic # for Claude
458
+ sbx secret set -g openai # for Codex
459
+ sbx secret set -g google # for Gemini
460
+
461
+ Advanced usage:
462
+ For branch mode, multiple workspaces, memory limits, network policies,
463
+ or passing prompts to the agent, use sbx directly with the template:
464
+
465
+ sbx run --template ghcr.io/alicomert/pixcode-sandbox:claude-code claude ~/my-project --branch my-feature
466
+ sbx run --template ghcr.io/alicomert/pixcode-sandbox:claude-code claude ~/project ~/libs:ro --memory 8g
467
+
468
+ Full Docker Sandboxes docs: https://docs.docker.com/ai/sandboxes/usage/
469
+ `);
470
+ }
471
+
472
+ async function sandboxCommand(args) {
473
+ const { execFileSync, spawn: spawnProcess } = await import('child_process');
474
+
475
+ // Safe execution — uses execFileSync (no shell) to prevent injection
476
+ const sbx = (subcmd, opts = {}) => {
477
+ const result = execFileSync('sbx', subcmd, {
478
+ encoding: 'utf8',
479
+ stdio: opts.inherit ? 'inherit' : 'pipe',
480
+ });
481
+ return result || '';
482
+ };
483
+
484
+ const opts = parseSandboxArgs(args);
485
+
486
+ if (opts.subcommand === 'help') {
487
+ showSandboxHelp();
488
+ return;
489
+ }
490
+
491
+ // Validate name (alphanumeric, hyphens, underscores only)
492
+ if (opts.name && !/^[\w-]+$/.test(opts.name)) {
493
+ console.error(`\n${c.error('❌')} Invalid sandbox name: ${opts.name}`);
494
+ console.log(` Names may only contain letters, numbers, hyphens, and underscores.\n`);
495
+ process.exit(1);
496
+ }
497
+
498
+ // Check sbx is installed
499
+ try {
500
+ sbx(['version']);
501
+ } catch {
502
+ console.error(`\n${c.error('❌')} ${c.bright('sbx')} CLI not found.\n`);
503
+ console.log(` Install it from: ${c.info('https://docs.docker.com/ai/sandboxes/get-started/')}`);
504
+ console.log(` Then run: ${c.bright('sbx login')}`);
505
+ console.log(` And store your API key: ${c.bright('sbx secret set -g anthropic')}\n`);
506
+ process.exit(1);
507
+ }
508
+
509
+ switch (opts.subcommand) {
510
+
511
+ case 'ls':
512
+ sbx(['ls'], { inherit: true });
513
+ break;
514
+
515
+ case 'stop':
516
+ if (!opts.name) {
517
+ console.error(`\n${c.error('❌')} Sandbox name required: pixcode sandbox stop <name>\n`);
518
+ process.exit(1);
519
+ }
520
+ sbx(['stop', opts.name], { inherit: true });
521
+ break;
522
+
523
+ case 'rm':
524
+ if (!opts.name) {
525
+ console.error(`\n${c.error('❌')} Sandbox name required: pixcode sandbox rm <name>\n`);
526
+ process.exit(1);
527
+ }
528
+ sbx(['rm', opts.name], { inherit: true });
529
+ break;
530
+
531
+ case 'logs':
532
+ if (!opts.name) {
533
+ console.error(`\n${c.error('❌')} Sandbox name required: pixcode sandbox logs <name>\n`);
534
+ process.exit(1);
535
+ }
536
+ try {
537
+ sbx(['exec', opts.name, 'bash', '-c', 'cat /tmp/pixcode-ui.log'], { inherit: true });
538
+ } catch (e) {
539
+ console.error(`\n${c.error('❌')} Could not read logs: ${e.message || 'Is the sandbox running?'}\n`);
540
+ }
541
+ break;
542
+
543
+ case 'start': {
544
+ if (!opts.name) {
545
+ console.error(`\n${c.error('❌')} Sandbox name required: pixcode sandbox start <name>\n`);
546
+ process.exit(1);
547
+ }
548
+ console.log(`\n${c.info('▶')} Starting sandbox ${c.bright(opts.name)}...`);
549
+ const restartRun = spawnProcess('sbx', ['run', opts.name], {
550
+ detached: true,
551
+ stdio: ['ignore', 'ignore', 'ignore'],
552
+ });
553
+ restartRun.unref();
554
+ await new Promise(resolve => setTimeout(resolve, 5000));
555
+
556
+ console.log(`${c.info('▶')} Launching Pixcode web server...`);
557
+ sbx(['exec', opts.name, 'bash', '-c', 'pixcode start --port 3001 &']);
558
+
559
+ console.log(`${c.info('▶')} Forwarding port ${opts.port} → 3001...`);
560
+ try {
561
+ sbx(['ports', opts.name, '--publish', `${opts.port}:3001`]);
562
+ } catch (e) {
563
+ const msg = e.stdout || e.stderr || e.message || '';
564
+ if (msg.includes('address already in use')) {
565
+ const altPort = opts.port + 1;
566
+ console.log(`${c.warn('⚠')} Port ${opts.port} in use, trying ${altPort}...`);
567
+ try {
568
+ sbx(['ports', opts.name, '--publish', `${altPort}:3001`]);
569
+ opts.port = altPort;
570
+ } catch {
571
+ console.error(`${c.error('❌')} Ports ${opts.port} and ${altPort} both in use. Use --port to specify a free port.`);
572
+ process.exit(1);
573
+ }
574
+ } else {
575
+ throw e;
576
+ }
577
+ }
578
+
579
+ console.log(`\n${c.ok('✔')} ${c.bright('Pixcode is ready!')}`);
580
+ console.log(` ${c.info('→')} ${c.bright(`http://localhost:${opts.port}`)}\n`);
581
+ break;
582
+ }
583
+
584
+ case 'create': {
585
+ if (!opts.workspace) {
586
+ console.error(`\n${c.error('❌')} Workspace path required: pixcode sandbox <path>\n`);
587
+ console.log(` Example: ${c.bright('pixcode sandbox ~/my-project')}\n`);
588
+ process.exit(1);
589
+ }
590
+
591
+ const workspace = opts.workspace.startsWith('~')
592
+ ? opts.workspace.replace(/^~/, os.homedir())
593
+ : path.resolve(opts.workspace);
594
+
595
+ if (!fs.existsSync(workspace)) {
596
+ console.error(`\n${c.error('❌')} Workspace path not found: ${c.dim(workspace)}\n`);
597
+ process.exit(1);
598
+ }
599
+
600
+ const secret = SANDBOX_SECRETS[opts.agent] || 'anthropic';
601
+
602
+ // Check if the required secret is stored
603
+ try {
604
+ const secretList = sbx(['secret', 'ls']);
605
+ if (!secretList.includes(secret)) {
606
+ console.error(`\n${c.error('❌')} No ${c.bright(secret)} API key found.\n`);
607
+ console.log(` Run: ${c.bright(`sbx secret set -g ${secret}`)}\n`);
608
+ process.exit(1);
609
+ }
610
+ } catch { /* sbx secret ls not available, skip check */ }
611
+
612
+ console.log(`\n${c.bright('Pixcode Sandbox')}`);
613
+ console.log(c.dim('─'.repeat(50)));
614
+ console.log(` Agent: ${c.info(opts.agent)} ${c.dim(`(${secret} credentials)`)}`);
615
+ console.log(` Workspace: ${c.dim(workspace)}`);
616
+ console.log(` Name: ${c.dim(opts.name)}`);
617
+ console.log(` Template: ${c.dim(opts.template)}`);
618
+ console.log(` Port: ${c.dim(String(opts.port))}`);
619
+ if (opts.env.length > 0) {
620
+ console.log(` Env: ${c.dim(opts.env.join(', '))}`);
621
+ }
622
+ console.log(c.dim('─'.repeat(50)));
623
+
624
+ // Step 1: Launch sandbox with sbx run in background.
625
+ // sbx run creates the sandbox (or reconnects) AND holds an active session,
626
+ // which prevents the sandbox from auto-stopping.
627
+ console.log(`\n${c.info('▶')} Creating sandbox ${c.bright(opts.name)}...`);
628
+ const bgRun = spawnProcess('sbx', [
629
+ 'run', '--template', opts.template, '--name', opts.name, opts.agent, workspace,
630
+ ], {
631
+ detached: true,
632
+ stdio: ['ignore', 'ignore', 'ignore'],
633
+ });
634
+ bgRun.unref();
635
+ // Wait for sandbox to be ready
636
+ await new Promise(resolve => setTimeout(resolve, 5000));
637
+
638
+ // Step 2: Inject environment variables
639
+ if (opts.env.length > 0) {
640
+ console.log(`${c.info('▶')} Setting environment variables...`);
641
+ const exports = opts.env
642
+ .filter(e => /^\w+=.+$/.test(e))
643
+ .map(e => `export ${e}`)
644
+ .join('\n');
645
+ if (exports) {
646
+ sbx(['exec', opts.name, 'bash', '-c', `echo '${exports}' >> /etc/sandbox-persistent.sh`]);
647
+ }
648
+ const invalid = opts.env.filter(e => !/^\w+=.+$/.test(e));
649
+ if (invalid.length > 0) {
650
+ console.log(`${c.warn('⚠')} Skipped invalid env vars: ${invalid.join(', ')} (expected KEY=VALUE)`);
651
+ }
652
+ }
653
+
654
+ // Step 3: Start Pixcode inside the sandbox
655
+ console.log(`${c.info('▶')} Launching Pixcode web server...`);
656
+ sbx(['exec', opts.name, 'bash', '-c', 'pixcode start --port 3001 &']);
657
+
658
+ // Step 4: Forward port
659
+ console.log(`${c.info('▶')} Forwarding port ${opts.port} → 3001...`);
660
+ try {
661
+ sbx(['ports', opts.name, '--publish', `${opts.port}:3001`]);
662
+ } catch (e) {
663
+ const msg = e.stdout || e.stderr || e.message || '';
664
+ if (msg.includes('address already in use')) {
665
+ const altPort = opts.port + 1;
666
+ console.log(`${c.warn('⚠')} Port ${opts.port} in use, trying ${altPort}...`);
667
+ try {
668
+ sbx(['ports', opts.name, '--publish', `${altPort}:3001`]);
669
+ opts.port = altPort;
670
+ } catch {
671
+ console.error(`${c.error('❌')} Ports ${opts.port} and ${altPort} both in use. Use --port to specify a free port.`);
672
+ process.exit(1);
673
+ }
674
+ } else {
675
+ throw e;
676
+ }
677
+ }
678
+
679
+ // Done
680
+ console.log(`\n${c.ok('✔')} ${c.bright('Pixcode is ready!')}`);
681
+ console.log(` ${c.info('→')} Open ${c.bright(`http://localhost:${opts.port}`)}`);
682
+ console.log(`\n${c.dim(' Manage with:')}`);
683
+ console.log(` ${c.dim('$')} sbx ls`);
684
+ console.log(` ${c.dim('$')} sbx stop ${opts.name}`);
685
+ console.log(` ${c.dim('$')} sbx start ${opts.name}`);
686
+ console.log(` ${c.dim('$')} sbx rm ${opts.name}`);
687
+ console.log(`\n${c.dim(' Or install globally:')} npm install -g @pixelbyte-software/pixcode\n`);
688
+ break;
689
+ }
690
+
691
+ default:
692
+ showSandboxHelp();
693
+ }
694
+ }
695
+
696
+ // ── Server ──────────────────────────────────────────────────
697
+
698
+ // Start the server
699
+ async function startServer() {
700
+ // Import and run the server
701
+ await import('./index.js');
702
+ }
703
+
704
+ async function reexecAfterStartupUpdate() {
705
+ await new Promise((resolve, reject) => {
706
+ const child = spawn(process.execPath, process.argv.slice(1), {
707
+ cwd: process.cwd(),
708
+ env: startupUpdateReexecEnv(),
709
+ stdio: 'inherit',
710
+ windowsHide: false,
711
+ });
712
+ child.on('error', reject);
713
+ child.on('close', (code, signal) => {
714
+ if (signal) {
715
+ process.kill(process.pid, signal);
716
+ return;
717
+ }
718
+ process.exit(code ?? 0);
719
+ });
720
+ });
721
+ }
722
+
723
+ async function runStartupUpdateGate() {
724
+ const result = await runStartupAutoUpdate({
725
+ appRoot: APP_ROOT,
726
+ currentVersion: packageJson.version,
727
+ installMode,
728
+ color: c,
729
+ });
730
+
731
+ if (result.failed) {
732
+ console.log(`${c.warn('[WARN]')} Startup update check failed: ${result.error}`);
733
+ console.log(`${c.tip('[TIP]')} Continuing with the current version (${packageJson.version}).`);
734
+ return false;
735
+ }
736
+
737
+ if (result.skipped && result.reason && process.env.PIXCODE_DEBUG_STARTUP_UPDATE === '1') {
738
+ console.log(`${c.dim('[INFO]')} Startup update skipped: ${result.reason}`);
739
+ }
740
+
741
+ if (!result.updated) {
742
+ return false;
743
+ }
744
+
745
+ console.log(`${c.ok('[OK]')} Startup update applied${result.version ? ` (${result.version})` : ''}.`);
746
+ if (result.restartMode === 'exit42') {
747
+ console.log(`${c.info('[INFO]')} Restarting through the desktop wrapper before opening the port...`);
748
+ process.exit(42);
749
+ }
750
+
751
+ console.log(`${c.info('[INFO]')} Restarting Pixcode on the updated code before opening the port...`);
752
+ await reexecAfterStartupUpdate();
753
+ return true;
754
+ }
755
+
756
+ async function isPortOpen(port, timeoutMs = 800) {
757
+ return await new Promise((resolve) => {
758
+ const socket = net.createConnection({ host: '127.0.0.1', port: Number(port) });
759
+ let settled = false;
760
+ const done = (value) => {
761
+ if (settled) return;
762
+ settled = true;
763
+ socket.destroy();
764
+ resolve(value);
765
+ };
766
+
767
+ socket.setTimeout(timeoutMs);
768
+ socket.once('connect', () => done(true));
769
+ socket.once('timeout', () => done(false));
770
+ socket.once('error', () => done(false));
771
+ });
772
+ }
773
+
774
+ async function waitForPortOpen(port, timeoutMs = 25000) {
775
+ const deadline = Date.now() + timeoutMs;
776
+ while (Date.now() < deadline) {
777
+ if (await isPortOpen(port)) {
778
+ return true;
779
+ }
780
+ await new Promise(resolve => setTimeout(resolve, 1000));
781
+ }
782
+ return false;
783
+ }
784
+
785
+ function printSystemDaemonActiveNotice(port) {
786
+ const effectivePort = Number(port) || 3001;
787
+ const statusCommand = buildDaemonCliCommand(
788
+ { subcommand: 'status', mode: 'system' },
789
+ DAEMON_COMMAND_CONTEXT
790
+ );
791
+ const stopCommand = buildDaemonCliCommand(
792
+ { subcommand: 'stop', mode: 'system' },
793
+ DAEMON_COMMAND_CONTEXT
794
+ );
795
+ const logsCommand = buildDaemonCliCommand(
796
+ { subcommand: 'logs', mode: 'system' },
797
+ DAEMON_COMMAND_CONTEXT
798
+ );
799
+ console.log(`${c.ok('[OK]')} System daemon is active and managing Pixcode.`);
800
+ console.log(`${c.info('[INFO]')} Health URL: ${c.bright(`http://localhost:${effectivePort}/health`)}`);
801
+ console.log(`${c.info('[INFO]')} Status: ${c.bright(statusCommand)}`);
802
+ console.log(`${c.info('[INFO]')} Stop: ${c.bright(stopCommand)}`);
803
+ console.log(`${c.info('[INFO]')} Logs: ${c.bright(logsCommand)}`);
804
+ }
805
+
806
+ function printUserDaemonActiveNotice(port) {
807
+ const effectivePort = Number(port) || 3001;
808
+ const statusCommand = buildDaemonCliCommand(
809
+ { subcommand: 'status', mode: 'user' },
810
+ DAEMON_COMMAND_CONTEXT
811
+ );
812
+ const stopCommand = buildDaemonCliCommand(
813
+ { subcommand: 'stop', mode: 'user' },
814
+ DAEMON_COMMAND_CONTEXT
815
+ );
816
+ const logsCommand = buildDaemonCliCommand(
817
+ { subcommand: 'logs', mode: 'user' },
818
+ DAEMON_COMMAND_CONTEXT
819
+ );
820
+ console.log(`${c.ok('[OK]')} User daemon is active for this account.`);
821
+ console.log(`${c.info('[INFO]')} UI: ${c.bright(`http://localhost:${effectivePort}`)}`);
822
+ console.log(`${c.info('[INFO]')} Status: ${c.bright(statusCommand)}`);
823
+ console.log(`${c.info('[INFO]')} Stop: ${c.bright(stopCommand)}`);
824
+ console.log(`${c.info('[INFO]')} Logs: ${c.bright(logsCommand)}`);
825
+ console.log(`${c.tip('[TIP]')} For login/reboot persistence, enable linger once: ${c.bright(`sudo loginctl enable-linger ${os.userInfo().username}`)}`);
826
+ }
827
+
828
+ function isSystemPermissionError(error) {
829
+ const message = String(error?.message || error || '');
830
+ 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);
831
+ }
832
+
833
+ function buildAutoInstallArgs(mode, options) {
834
+ const args = ['install', `--mode=${mode}`];
835
+ if (options.serverPort) {
836
+ args.push('--port', String(options.serverPort));
837
+ }
838
+ if (options.databasePath) {
839
+ args.push('--database-path', String(options.databasePath));
840
+ }
841
+ args.push('--single-port');
842
+ return args;
843
+ }
844
+
845
+ async function maybeAutoDaemonStart(options = {}) {
846
+ if (process.platform !== 'linux') return false;
847
+ if (process.env.PIXCODE_DAEMON_MANAGED === '1') return false;
848
+ if (process.env.PIXCODE_NO_DAEMON === '1') return false;
849
+ if (process.env.PIXCODE_DAEMON_ATTEMPTED === '1') return false;
850
+ if (options.noDaemon) return false;
851
+
852
+ process.env.PIXCODE_DAEMON_ATTEMPTED = '1';
853
+ const daemonPort = Number(options.serverPort || process.env.SERVER_PORT || process.env.PORT || '3001');
854
+ const systemArgs = buildAutoInstallArgs('system', options);
855
+ const userArgs = buildAutoInstallArgs('user', options);
856
+
857
+ try {
858
+ console.log(`${c.info('[INFO]')} Linux detected. Enforcing system daemon mode for Pixcode...`);
859
+ await handleDaemonCommand(systemArgs, {
860
+ appRoot: APP_ROOT,
861
+ defaultPort: process.env.SERVER_PORT || process.env.PORT || '3001',
862
+ color: c,
863
+ });
864
+ return true;
865
+ } catch (systemError) {
866
+ const healthySoon = await waitForPortOpen(daemonPort);
867
+ if (healthySoon) {
868
+ console.log(`${c.warn('[WARN]')} System daemon health check was delayed, but port ${daemonPort} is now reachable.`);
869
+ printSystemDaemonActiveNotice(daemonPort);
870
+ return true;
871
+ }
872
+
873
+ if (!isSystemPermissionError(systemError)) {
874
+ const installSystemCommand = buildDaemonCliCommand(
875
+ {
876
+ subcommand: 'install',
877
+ mode: 'system',
878
+ extraArgs: ['--port', String(daemonPort), '--single-port'],
879
+ },
880
+ DAEMON_COMMAND_CONTEXT
881
+ );
882
+ throw new Error(
883
+ `System daemon bootstrap failed.\n` +
884
+ `${systemError.message}\n` +
885
+ `Run with privileges: ${installSystemCommand}`
886
+ );
887
+ }
888
+
889
+ console.log(`${c.warn('[WARN]')} System daemon setup requires elevated privileges for this user.`);
890
+ console.log(`${c.info('[INFO]')} Falling back to user daemon mode for account "${os.userInfo().username}"...`);
891
+
892
+ try {
893
+ await handleDaemonCommand(userArgs, {
894
+ appRoot: APP_ROOT,
895
+ defaultPort: process.env.SERVER_PORT || process.env.PORT || '3001',
896
+ color: c,
897
+ });
898
+ printUserDaemonActiveNotice(daemonPort);
899
+ return true;
900
+ } catch (userError) {
901
+ const userHealthySoon = await waitForPortOpen(daemonPort);
902
+ if (userHealthySoon) {
903
+ console.log(`${c.warn('[WARN]')} User daemon health check was delayed, but port ${daemonPort} is now reachable.`);
904
+ printUserDaemonActiveNotice(daemonPort);
905
+ return true;
906
+ }
907
+ const installSystemCommand = buildDaemonCliCommand(
908
+ {
909
+ subcommand: 'install',
910
+ mode: 'system',
911
+ extraArgs: ['--port', String(daemonPort), '--single-port'],
912
+ },
913
+ DAEMON_COMMAND_CONTEXT
914
+ );
915
+ const installUserCommand = buildDaemonCliCommand(
916
+ {
917
+ subcommand: 'install',
918
+ mode: 'user',
919
+ extraArgs: ['--port', String(daemonPort), '--single-port'],
920
+ },
921
+ DAEMON_COMMAND_CONTEXT
922
+ );
923
+ throw new Error(
924
+ `System daemon bootstrap failed.\n` +
925
+ `${systemError.message}\n\n` +
926
+ `User daemon fallback also failed.\n` +
927
+ `${userError.message}\n` +
928
+ `Try one of:\n` +
929
+ `1) ${installSystemCommand}\n` +
930
+ `2) ${installUserCommand}`
931
+ );
932
+ }
933
+ }
934
+ }
935
+
936
+ // Parse CLI arguments
937
+ function parseArgs(args) {
938
+ const parsed = { command: 'start', options: {} };
939
+ let commandSet = false;
940
+
941
+ for (let i = 0; i < args.length; i++) {
942
+ const arg = args[i];
943
+
944
+ if (arg === '--port' || arg === '-p') {
945
+ parsed.options.serverPort = args[++i];
946
+ } else if (arg.startsWith('--port=')) {
947
+ parsed.options.serverPort = arg.split('=')[1];
948
+ } else if (arg === '--database-path') {
949
+ parsed.options.databasePath = args[++i];
950
+ } else if (arg.startsWith('--database-path=')) {
951
+ parsed.options.databasePath = arg.split('=')[1];
952
+ } else if (arg === '--no-daemon') {
953
+ parsed.options.noDaemon = true;
954
+ } else if (arg === '--no-browser') {
955
+ parsed.options.noBrowser = true;
956
+ } else if (arg === '--restart-daemon') {
957
+ parsed.options.restartDaemon = true;
958
+ } else if (arg === '--help' || arg === '-h') {
959
+ parsed.command = 'help';
960
+ commandSet = true;
961
+ } else if (arg === '--version' || arg === '-v') {
962
+ parsed.command = 'version';
963
+ commandSet = true;
964
+ } else if (!arg.startsWith('-')) {
965
+ if (!commandSet) {
966
+ parsed.command = arg;
967
+ commandSet = true;
968
+ }
969
+ if (arg === 'sandbox' || arg === 'daemon') {
970
+ parsed.remainingArgs = args.slice(i + 1);
971
+ break;
972
+ }
973
+ }
974
+ }
975
+
976
+ return parsed;
977
+ }
978
+
979
+ // Main CLI handler
980
+ async function main() {
981
+ const args = process.argv.slice(2);
982
+ const { command, options, remainingArgs } = parseArgs(args);
983
+
984
+ // Apply CLI options to environment variables
985
+ if (options.serverPort) {
986
+ process.env.SERVER_PORT = options.serverPort;
987
+ } else if (!process.env.SERVER_PORT && process.env.PORT) {
988
+ process.env.SERVER_PORT = process.env.PORT;
989
+ }
990
+ if (options.noDaemon) {
991
+ process.env.PIXCODE_NO_DAEMON = '1';
992
+ }
993
+ if (options.noBrowser) {
994
+ process.env.PIXCODE_NO_BROWSER = '1';
995
+ }
996
+ if (options.databasePath) {
997
+ process.env.DATABASE_PATH = options.databasePath;
998
+ }
999
+
1000
+ switch (command) {
1001
+ case 'start':
1002
+ if (process.env.PIXCODE_ENABLE_STARTUP_UPDATE === '1' && await runStartupUpdateGate()) {
1003
+ break;
1004
+ }
1005
+ {
1006
+ const effectivePort = Number(options.serverPort || process.env.SERVER_PORT || process.env.PORT || '3001');
1007
+
1008
+ // First-run setup wizard
1009
+ if (isFirstRun()) {
1010
+ const wizardResult = await runSetupWizard(options);
1011
+ if (wizardResult) {
1012
+ if (!options.serverPort) {
1013
+ process.env.SERVER_PORT = String(wizardResult.port);
1014
+ }
1015
+ if (wizardResult.useDaemon === false) {
1016
+ options.noDaemon = true;
1017
+ process.env.PIXCODE_NO_DAEMON = '1';
1018
+ }
1019
+ }
1020
+ }
1021
+
1022
+ // Port conflict detection (every run, not just first)
1023
+ const currentPort = Number(options.serverPort || process.env.SERVER_PORT || process.env.PORT || '3001');
1024
+ if (!await isPortAvailable(currentPort)) {
1025
+ const alreadyRunning = await waitForServerReady(currentPort, 2000);
1026
+ if (alreadyRunning) {
1027
+ console.log(`\n${c.ok('[OK]')} Pixcode is already running on port ${c.bright(String(currentPort))}.`);
1028
+ await postStartupGuidance(currentPort);
1029
+ break;
1030
+ }
1031
+ console.log(`\n${c.warn('[WARN]')} Port ${c.bright(String(currentPort))} is in use by another process.`);
1032
+ const altPort = await findAvailablePort(currentPort + 1);
1033
+ if (altPort) {
1034
+ console.log(`${c.info('[INFO]')} Switching to port ${c.bright(String(altPort))}.`);
1035
+ process.env.SERVER_PORT = String(altPort);
1036
+ options.serverPort = String(altPort);
1037
+ } else {
1038
+ console.error(`${c.error('[ERROR]')} No free ports found. Specify one with ${c.bright('--port <port>')}.`);
1039
+ process.exit(1);
1040
+ }
1041
+ }
1042
+ }
1043
+ if (await maybeAutoDaemonStart(options)) {
1044
+ const daemonPort = Number(options.serverPort || process.env.SERVER_PORT || process.env.PORT || '3001');
1045
+ const ready = await waitForServerReady(daemonPort, 15000);
1046
+ if (ready) {
1047
+ await postStartupGuidance(daemonPort);
1048
+ }
1049
+ break;
1050
+ }
1051
+ await startServer();
1052
+ break;
1053
+ case 'setup':
1054
+ {
1055
+ const wizardResult = await runSetupWizard(options);
1056
+ if (wizardResult) {
1057
+ process.env.SERVER_PORT = String(wizardResult.port);
1058
+ if (wizardResult.useDaemon === false) {
1059
+ options.noDaemon = true;
1060
+ process.env.PIXCODE_NO_DAEMON = '1';
1061
+ }
1062
+ }
1063
+ console.log(`\n${c.ok('[OK]')} Setup complete! Run ${c.bright('pixcode start')} to launch.`);
1064
+ }
1065
+ break;
1066
+ case 'sandbox':
1067
+ await sandboxCommand(remainingArgs || []);
1068
+ break;
1069
+ case 'daemon':
1070
+ await handleDaemonCommand(remainingArgs || [], {
1071
+ appRoot: APP_ROOT,
1072
+ defaultPort: process.env.SERVER_PORT || process.env.PORT || '3001',
1073
+ color: c,
1074
+ cliEntry: process.argv[1],
1075
+ nodeExecPath: process.execPath,
1076
+ });
1077
+ break;
1078
+ case 'status':
1079
+ case 'info':
1080
+ showStatus();
1081
+ break;
1082
+ case 'help':
1083
+ case '-h':
1084
+ case '--help':
1085
+ showHelp();
1086
+ break;
1087
+ case 'version':
1088
+ case '-v':
1089
+ case '--version':
1090
+ showVersion();
1091
+ break;
1092
+ case 'update':
1093
+ await updatePackage(options);
1094
+ break;
1095
+ default:
1096
+ console.error(`\n❌ Unknown command: ${command}`);
1097
+ console.log(' Run "pixcode help" for usage information.\n');
1098
+ process.exit(1);
1099
+ }
1100
+ }
1101
+
1102
+ // Run the CLI
1103
+ main().catch(error => {
1104
+ console.error('\n❌ Error:', error.message);
1105
+ process.exit(1);
1106
+ });