@pixelbyte-software/pixcode 1.51.8 → 1.51.9

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