@pixelbyte-software/pixcode 1.34.0 → 1.35.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (247) hide show
  1. package/LICENSE +718 -718
  2. package/README.de.md +248 -248
  3. package/README.ja.md +240 -240
  4. package/README.ko.md +240 -240
  5. package/README.md +303 -303
  6. package/README.ru.md +248 -248
  7. package/README.tr.md +250 -250
  8. package/README.zh-CN.md +240 -240
  9. package/dist/api-docs.html +548 -395
  10. package/dist/assets/index-B8w57E1r.css +32 -0
  11. package/dist/assets/index-CBdsvGSR.js +854 -0
  12. package/dist/clear-cache.html +85 -85
  13. package/dist/convert-icons.md +52 -52
  14. package/dist/favicon.svg +8 -8
  15. package/dist/generate-icons.js +48 -48
  16. package/dist/icons/codex-white.svg +3 -3
  17. package/dist/icons/codex.svg +3 -3
  18. package/dist/icons/cursor-white.svg +11 -11
  19. package/dist/icons/icon-128x128.svg +9 -9
  20. package/dist/icons/icon-144x144.svg +9 -9
  21. package/dist/icons/icon-152x152.svg +9 -9
  22. package/dist/icons/icon-192x192.svg +9 -9
  23. package/dist/icons/icon-384x384.svg +9 -9
  24. package/dist/icons/icon-512x512.svg +9 -9
  25. package/dist/icons/icon-72x72.svg +9 -9
  26. package/dist/icons/icon-96x96.svg +9 -9
  27. package/dist/icons/icon-template.svg +9 -9
  28. package/dist/icons/qwen-logo.svg +14 -14
  29. package/dist/index.html +59 -59
  30. package/dist/logo.svg +12 -12
  31. package/dist/manifest.json +60 -60
  32. package/dist/openapi.yaml +1693 -1311
  33. package/dist/sw.js +124 -124
  34. package/dist-server/server/claude-sdk.js +38 -7
  35. package/dist-server/server/claude-sdk.js.map +1 -1
  36. package/dist-server/server/cli.js +107 -112
  37. package/dist-server/server/cli.js.map +1 -1
  38. package/dist-server/server/daemon/manager.js +33 -33
  39. package/dist-server/server/daemon-manager.js +159 -112
  40. package/dist-server/server/daemon-manager.js.map +1 -1
  41. package/dist-server/server/database/json-store.js +8 -5
  42. package/dist-server/server/database/json-store.js.map +1 -1
  43. package/dist-server/server/index.js +31 -10
  44. package/dist-server/server/index.js.map +1 -1
  45. package/dist-server/server/modules/orchestration/a2a/adapter-registry.js +45 -19
  46. package/dist-server/server/modules/orchestration/a2a/adapter-registry.js.map +1 -1
  47. package/dist-server/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.js.map +1 -1
  48. package/dist-server/server/modules/orchestration/a2a/adapters/claude-code.adapter.js +1 -0
  49. package/dist-server/server/modules/orchestration/a2a/adapters/claude-code.adapter.js.map +1 -1
  50. package/dist-server/server/modules/orchestration/a2a/adapters/codex.adapter.js +202 -0
  51. package/dist-server/server/modules/orchestration/a2a/adapters/codex.adapter.js.map +1 -0
  52. package/dist-server/server/modules/orchestration/a2a/adapters/cursor.adapter.js +205 -0
  53. package/dist-server/server/modules/orchestration/a2a/adapters/cursor.adapter.js.map +1 -0
  54. package/dist-server/server/modules/orchestration/a2a/adapters/gemini.adapter.js +205 -0
  55. package/dist-server/server/modules/orchestration/a2a/adapters/gemini.adapter.js.map +1 -0
  56. package/dist-server/server/modules/orchestration/a2a/adapters/opencode.adapter.js +205 -0
  57. package/dist-server/server/modules/orchestration/a2a/adapters/opencode.adapter.js.map +1 -0
  58. package/dist-server/server/modules/orchestration/a2a/adapters/qwen.adapter.js +205 -0
  59. package/dist-server/server/modules/orchestration/a2a/adapters/qwen.adapter.js.map +1 -0
  60. package/dist-server/server/modules/orchestration/a2a/routes.js +298 -34
  61. package/dist-server/server/modules/orchestration/a2a/routes.js.map +1 -1
  62. package/dist-server/server/modules/orchestration/a2a/task-store.js +144 -0
  63. package/dist-server/server/modules/orchestration/a2a/task-store.js.map +1 -0
  64. package/dist-server/server/modules/orchestration/a2a/validator.js +16 -0
  65. package/dist-server/server/modules/orchestration/a2a/validator.js.map +1 -1
  66. package/dist-server/server/modules/orchestration/index.js +14 -0
  67. package/dist-server/server/modules/orchestration/index.js.map +1 -1
  68. package/dist-server/server/modules/orchestration/preview/port-watcher.js +90 -0
  69. package/dist-server/server/modules/orchestration/preview/port-watcher.js.map +1 -0
  70. package/dist-server/server/modules/orchestration/preview/preview-proxy.js +58 -0
  71. package/dist-server/server/modules/orchestration/preview/preview-proxy.js.map +1 -0
  72. package/dist-server/server/modules/orchestration/preview/types.js +2 -0
  73. package/dist-server/server/modules/orchestration/preview/types.js.map +1 -0
  74. package/dist-server/server/modules/orchestration/tasks/orchestration-task-store.js +37 -0
  75. package/dist-server/server/modules/orchestration/tasks/orchestration-task-store.js.map +1 -0
  76. package/dist-server/server/modules/orchestration/tasks/orchestration-task.routes.js +68 -0
  77. package/dist-server/server/modules/orchestration/tasks/orchestration-task.routes.js.map +1 -0
  78. package/dist-server/server/modules/orchestration/tasks/orchestration-task.service.js +128 -0
  79. package/dist-server/server/modules/orchestration/tasks/orchestration-task.service.js.map +1 -0
  80. package/dist-server/server/modules/orchestration/tasks/orchestration-task.types.js +2 -0
  81. package/dist-server/server/modules/orchestration/tasks/orchestration-task.types.js.map +1 -0
  82. package/dist-server/server/modules/orchestration/workflows/built-in-workflows.js +126 -0
  83. package/dist-server/server/modules/orchestration/workflows/built-in-workflows.js.map +1 -0
  84. package/dist-server/server/modules/orchestration/workflows/workflow-runner.js +1047 -0
  85. package/dist-server/server/modules/orchestration/workflows/workflow-runner.js.map +1 -0
  86. package/dist-server/server/modules/orchestration/workflows/workflow-store.js +76 -0
  87. package/dist-server/server/modules/orchestration/workflows/workflow-store.js.map +1 -0
  88. package/dist-server/server/modules/orchestration/workflows/workflow.routes.js +151 -0
  89. package/dist-server/server/modules/orchestration/workflows/workflow.routes.js.map +1 -0
  90. package/dist-server/server/modules/orchestration/workflows/workflow.types.js +2 -0
  91. package/dist-server/server/modules/orchestration/workflows/workflow.types.js.map +1 -0
  92. package/dist-server/server/modules/orchestration/workflows/workspace-target.js +98 -0
  93. package/dist-server/server/modules/orchestration/workflows/workspace-target.js.map +1 -0
  94. package/dist-server/server/modules/orchestration/workspace/docker-workspace.js +122 -0
  95. package/dist-server/server/modules/orchestration/workspace/docker-workspace.js.map +1 -0
  96. package/dist-server/server/modules/orchestration/workspace/path-safety.js +48 -0
  97. package/dist-server/server/modules/orchestration/workspace/path-safety.js.map +1 -0
  98. package/dist-server/server/modules/orchestration/workspace/types.js +11 -0
  99. package/dist-server/server/modules/orchestration/workspace/types.js.map +1 -0
  100. package/dist-server/server/modules/orchestration/workspace/workspace-manager.js +80 -0
  101. package/dist-server/server/modules/orchestration/workspace/workspace-manager.js.map +1 -0
  102. package/dist-server/server/modules/orchestration/workspace/worktree-workspace.js +96 -0
  103. package/dist-server/server/modules/orchestration/workspace/worktree-workspace.js.map +1 -0
  104. package/dist-server/server/modules/providers/index.js +3 -0
  105. package/dist-server/server/modules/providers/index.js.map +1 -0
  106. package/dist-server/server/openai-codex.js +35 -4
  107. package/dist-server/server/openai-codex.js.map +1 -1
  108. package/dist-server/server/routes/commands.js +25 -25
  109. package/dist-server/server/routes/git.js +17 -17
  110. package/dist-server/server/routes/taskmaster.js +525 -508
  111. package/dist-server/server/routes/taskmaster.js.map +1 -1
  112. package/package.json +180 -178
  113. package/scripts/fix-node-pty.js +67 -67
  114. package/scripts/smoke/a2a-roundtrip.mjs +86 -17
  115. package/scripts/smoke/orchestration-api.mjs +172 -0
  116. package/scripts/smoke/orchestration-live-run.mjs +176 -0
  117. package/server/claude-sdk.js +898 -857
  118. package/server/cli.js +935 -940
  119. package/server/constants/config.js +4 -4
  120. package/server/cursor-cli.js +342 -342
  121. package/server/daemon/manager.js +564 -564
  122. package/server/daemon-manager.js +959 -920
  123. package/server/database/db.js +794 -794
  124. package/server/database/json-store.js +197 -194
  125. package/server/gemini-cli.js +535 -535
  126. package/server/gemini-response-handler.js +79 -79
  127. package/server/index.js +3135 -3104
  128. package/server/load-env.js +34 -34
  129. package/server/middleware/auth.js +173 -173
  130. package/server/modules/orchestration/a2a/adapter-registry.ts +72 -22
  131. package/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.ts +9 -3
  132. package/server/modules/orchestration/a2a/adapters/claude-code.adapter.ts +1 -0
  133. package/server/modules/orchestration/a2a/adapters/codex.adapter.ts +244 -0
  134. package/server/modules/orchestration/a2a/adapters/cursor.adapter.ts +249 -0
  135. package/server/modules/orchestration/a2a/adapters/gemini.adapter.ts +248 -0
  136. package/server/modules/orchestration/a2a/adapters/opencode.adapter.ts +248 -0
  137. package/server/modules/orchestration/a2a/adapters/qwen.adapter.ts +248 -0
  138. package/server/modules/orchestration/a2a/routes.ts +349 -36
  139. package/server/modules/orchestration/a2a/task-store.ts +178 -0
  140. package/server/modules/orchestration/a2a/types.ts +14 -0
  141. package/server/modules/orchestration/a2a/validator.ts +25 -2
  142. package/server/modules/orchestration/index.ts +40 -0
  143. package/server/modules/orchestration/preview/port-watcher.ts +112 -0
  144. package/server/modules/orchestration/preview/preview-proxy.ts +60 -0
  145. package/server/modules/orchestration/preview/types.ts +19 -0
  146. package/server/modules/orchestration/tasks/orchestration-task-store.ts +45 -0
  147. package/server/modules/orchestration/tasks/orchestration-task.routes.ts +73 -0
  148. package/server/modules/orchestration/tasks/orchestration-task.service.ts +145 -0
  149. package/server/modules/orchestration/tasks/orchestration-task.types.ts +29 -0
  150. package/server/modules/orchestration/workflows/built-in-workflows.ts +127 -0
  151. package/server/modules/orchestration/workflows/workflow-runner.ts +1206 -0
  152. package/server/modules/orchestration/workflows/workflow-store.ts +97 -0
  153. package/server/modules/orchestration/workflows/workflow.routes.ts +169 -0
  154. package/server/modules/orchestration/workflows/workflow.types.ts +70 -0
  155. package/server/modules/orchestration/workflows/workspace-target.ts +120 -0
  156. package/server/modules/orchestration/workspace/docker-workspace.ts +135 -0
  157. package/server/modules/orchestration/workspace/path-safety.ts +55 -0
  158. package/server/modules/orchestration/workspace/types.ts +52 -0
  159. package/server/modules/orchestration/workspace/workspace-manager.ts +97 -0
  160. package/server/modules/orchestration/workspace/worktree-workspace.ts +125 -0
  161. package/server/modules/providers/index.ts +2 -0
  162. package/server/modules/providers/list/claude/claude-auth.provider.ts +145 -145
  163. package/server/modules/providers/list/claude/claude-mcp.provider.ts +135 -135
  164. package/server/modules/providers/list/claude/claude-sessions.provider.ts +306 -306
  165. package/server/modules/providers/list/claude/claude.provider.ts +15 -15
  166. package/server/modules/providers/list/codex/codex-auth.provider.ts +115 -115
  167. package/server/modules/providers/list/codex/codex-mcp.provider.ts +135 -135
  168. package/server/modules/providers/list/codex/codex-sessions.provider.ts +319 -319
  169. package/server/modules/providers/list/codex/codex.provider.ts +15 -15
  170. package/server/modules/providers/list/cursor/cursor-auth.provider.ts +143 -143
  171. package/server/modules/providers/list/cursor/cursor-mcp.provider.ts +108 -108
  172. package/server/modules/providers/list/cursor/cursor-sessions.provider.ts +421 -421
  173. package/server/modules/providers/list/cursor/cursor.provider.ts +15 -15
  174. package/server/modules/providers/list/gemini/gemini-auth.provider.ts +163 -163
  175. package/server/modules/providers/list/gemini/gemini-mcp.provider.ts +110 -110
  176. package/server/modules/providers/list/gemini/gemini-sessions.provider.ts +227 -227
  177. package/server/modules/providers/list/gemini/gemini.provider.ts +15 -15
  178. package/server/modules/providers/list/opencode/opencode-auth.provider.ts +130 -130
  179. package/server/modules/providers/list/opencode/opencode-mcp.provider.ts +126 -126
  180. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +232 -232
  181. package/server/modules/providers/list/opencode/opencode.provider.ts +29 -29
  182. package/server/modules/providers/list/qwen/qwen-auth.provider.ts +145 -145
  183. package/server/modules/providers/list/qwen/qwen-mcp.provider.ts +114 -114
  184. package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +265 -265
  185. package/server/modules/providers/list/qwen/qwen.provider.ts +21 -21
  186. package/server/modules/providers/provider.registry.ts +40 -40
  187. package/server/modules/providers/provider.routes.ts +819 -819
  188. package/server/modules/providers/services/mcp.service.ts +86 -86
  189. package/server/modules/providers/services/provider-auth.service.ts +26 -26
  190. package/server/modules/providers/services/sessions.service.ts +45 -45
  191. package/server/modules/providers/shared/base/abstract.provider.ts +20 -20
  192. package/server/modules/providers/shared/mcp/mcp.provider.ts +151 -151
  193. package/server/modules/providers/shared/provider-configs.ts +142 -142
  194. package/server/modules/providers/tests/mcp.test.ts +293 -293
  195. package/server/openai-codex.js +462 -426
  196. package/server/opencode-cli.js +459 -459
  197. package/server/opencode-response-handler.js +107 -107
  198. package/server/projects.js +3105 -3105
  199. package/server/qwen-code-cli.js +395 -395
  200. package/server/qwen-response-handler.js +73 -73
  201. package/server/routes/agent.js +1365 -1365
  202. package/server/routes/auth.js +138 -138
  203. package/server/routes/codex.js +19 -19
  204. package/server/routes/commands.js +554 -554
  205. package/server/routes/cursor.js +52 -52
  206. package/server/routes/gemini.js +24 -24
  207. package/server/routes/git.js +1488 -1488
  208. package/server/routes/mcp-utils.js +31 -31
  209. package/server/routes/messages.js +61 -61
  210. package/server/routes/network.js +120 -120
  211. package/server/routes/plugins.js +318 -318
  212. package/server/routes/projects.js +915 -915
  213. package/server/routes/qwen.js +27 -27
  214. package/server/routes/settings.js +286 -286
  215. package/server/routes/taskmaster.js +1496 -1471
  216. package/server/routes/telegram.js +125 -125
  217. package/server/routes/user.js +123 -123
  218. package/server/services/external-access.js +171 -171
  219. package/server/services/install-jobs.js +571 -571
  220. package/server/services/notification-orchestrator.js +242 -242
  221. package/server/services/provider-credentials.js +189 -189
  222. package/server/services/provider-models.js +381 -381
  223. package/server/services/telegram/bot.js +279 -279
  224. package/server/services/telegram/telegram-http-client.js +130 -130
  225. package/server/services/telegram/translations.js +170 -170
  226. package/server/services/vapid-keys.js +36 -36
  227. package/server/sessionManager.js +225 -225
  228. package/server/shared/interfaces.ts +54 -54
  229. package/server/shared/types.ts +172 -172
  230. package/server/shared/utils.ts +193 -193
  231. package/server/tsconfig.json +36 -36
  232. package/server/utils/colors.js +21 -21
  233. package/server/utils/commandParser.js +303 -303
  234. package/server/utils/frontmatter.js +18 -18
  235. package/server/utils/gitConfig.js +34 -34
  236. package/server/utils/mcp-detector.js +147 -147
  237. package/server/utils/plugin-loader.js +457 -457
  238. package/server/utils/plugin-process-manager.js +184 -184
  239. package/server/utils/port-access.js +209 -209
  240. package/server/utils/runtime-paths.js +37 -37
  241. package/server/utils/taskmaster-websocket.js +128 -128
  242. package/server/utils/url-detection.js +71 -71
  243. package/server/vite-daemon.js +78 -78
  244. package/shared/modelConstants.js +162 -162
  245. package/shared/networkHosts.js +22 -22
  246. package/dist/assets/index-B1ghfb4w.css +0 -32
  247. package/dist/assets/index-BvClqlMf.js +0 -852
@@ -1,920 +1,959 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import os from 'os';
4
- import { spawnSync } from 'child_process';
5
- import { request } from 'node:http';
6
- import net from 'node:net';
7
-
8
- const DAEMON_SERVICE_NAME = 'pixcode.service';
9
- const FRONTEND_DAEMON_SERVICE_NAME = 'pixcode-frontend.service';
10
- const DAEMON_USER_SERVICE_PATH = path.join(os.homedir(), '.config', 'systemd', 'user', DAEMON_SERVICE_NAME);
11
- const DAEMON_SYSTEM_SERVICE_PATH = path.join('/etc', 'systemd', 'system', DAEMON_SERVICE_NAME);
12
- const FRONTEND_DAEMON_USER_SERVICE_PATH = path.join(os.homedir(), '.config', 'systemd', 'user', FRONTEND_DAEMON_SERVICE_NAME);
13
- const FRONTEND_DAEMON_SYSTEM_SERVICE_PATH = path.join('/etc', 'systemd', 'system', FRONTEND_DAEMON_SERVICE_NAME);
14
- const DEFAULT_FRONTEND_PORT = 5173;
15
- const DAEMON_HEALTH_TIMEOUT_MS = 60000;
16
- const DAEMON_HEALTH_REQUEST_TIMEOUT_MS = 4000;
17
- const DAEMON_HEALTH_RETRY_INTERVAL_MS = 1000;
18
-
19
- const DAEMON_SUBCOMMANDS = new Set([
20
- 'install',
21
- 'start',
22
- 'stop',
23
- 'restart',
24
- 'status',
25
- 'logs',
26
- 'enable',
27
- 'disable',
28
- 'uninstall',
29
- 'doctor',
30
- 'help',
31
- ]);
32
-
33
- const DAEMON_MODES = new Set(['auto', 'user', 'system']);
34
- const SYSTEM_MUTATING_DAEMON_SUBCOMMANDS = new Set([
35
- 'install',
36
- 'start',
37
- 'stop',
38
- 'restart',
39
- 'enable',
40
- 'disable',
41
- 'uninstall',
42
- 'logs',
43
- ]);
44
- let pixcodeBinaryAvailableCache = null;
45
-
46
- function passthroughColor(text) {
47
- return text;
48
- }
49
-
50
- function getColorHelpers(color) {
51
- if (color) {
52
- return color;
53
- }
54
- return {
55
- info: passthroughColor,
56
- ok: passthroughColor,
57
- warn: passthroughColor,
58
- error: passthroughColor,
59
- tip: passthroughColor,
60
- bright: passthroughColor,
61
- dim: passthroughColor,
62
- };
63
- }
64
-
65
- function runCommand(bin, args, opts = {}) {
66
- const stdio = opts.inherit ? 'inherit' : 'pipe';
67
- return spawnSync(bin, args, {
68
- encoding: 'utf8',
69
- stdio,
70
- });
71
- }
72
-
73
- function extractCommandError(result, fallbackMessage) {
74
- if (!result) return fallbackMessage;
75
- const fromError = result.error?.message?.trim();
76
- if (fromError) return fromError;
77
- const fromStd = (result.stderr || result.stdout || '').trim();
78
- if (fromStd) return fromStd;
79
- return fallbackMessage;
80
- }
81
-
82
- function isRootUser() {
83
- return typeof process.getuid === 'function' && process.getuid() === 0;
84
- }
85
-
86
- function quoteShellArg(arg) {
87
- const value = String(arg);
88
- if (/^[A-Za-z0-9_./:=+-]+$/.test(value)) {
89
- return value;
90
- }
91
- return `'${value.replace(/'/g, `'\\''`)}'`;
92
- }
93
-
94
- function quoteSystemdArg(arg) {
95
- return `"${String(arg).replace(/(["\\$`])/g, '\\$1')}"`;
96
- }
97
-
98
- function resolveDaemonCliEntryPath(context = {}) {
99
- const appRoot = context.appRoot || process.cwd();
100
- const explicitCliEntry = context.cliEntry ? path.resolve(context.cliEntry) : null;
101
- const argvCliEntry = process.argv[1] ? path.resolve(process.argv[1]) : null;
102
- const candidatePaths = [
103
- explicitCliEntry,
104
- argvCliEntry,
105
- path.join(appRoot, 'dist-server', 'server', 'cli.js'),
106
- path.join(appRoot, 'server', 'cli.js'),
107
- ].filter(Boolean);
108
-
109
- const existingPath = candidatePaths.find(candidate => fs.existsSync(candidate));
110
- if (existingPath) {
111
- return existingPath;
112
- }
113
-
114
- return explicitCliEntry || argvCliEntry || path.join(appRoot, 'server', 'cli.js');
115
- }
116
-
117
- function hasPixcodeBinary() {
118
- if (pixcodeBinaryAvailableCache !== null) {
119
- return pixcodeBinaryAvailableCache;
120
- }
121
-
122
- const probe = runCommand('pixcode', ['--version']);
123
- pixcodeBinaryAvailableCache = probe.status === 0;
124
- return pixcodeBinaryAvailableCache;
125
- }
126
-
127
- function getDaemonCommandPrefix(context = {}, { forceLocal = false } = {}) {
128
- if (!forceLocal && hasPixcodeBinary()) {
129
- return 'pixcode';
130
- }
131
-
132
- const nodeExec = context.nodeExecPath || process.execPath || 'node';
133
- const cliEntry = resolveDaemonCliEntryPath(context);
134
- return `${quoteShellArg(nodeExec)} ${quoteShellArg(cliEntry)}`;
135
- }
136
-
137
- export function buildDaemonCliCommand({ subcommand, mode = 'system', extraArgs = [] }, context = {}) {
138
- const normalizedSubcommand = String(subcommand || 'status').trim() || 'status';
139
- const normalizedMode = String(mode || 'system').trim() || 'system';
140
- const args = ['daemon', normalizedSubcommand, '--mode', normalizedMode, ...extraArgs.map(value => String(value))];
141
- const needsSudo =
142
- normalizedMode === 'system' &&
143
- SYSTEM_MUTATING_DAEMON_SUBCOMMANDS.has(normalizedSubcommand) &&
144
- !isRootUser();
145
- const prefix = getDaemonCommandPrefix(context, { forceLocal: needsSudo });
146
- const command = `${prefix} ${args.map(quoteShellArg).join(' ')}`;
147
- return needsSudo ? `sudo ${command}` : command;
148
- }
149
-
150
- function getDaemonServicePath(mode) {
151
- return mode === 'system' ? DAEMON_SYSTEM_SERVICE_PATH : DAEMON_USER_SERVICE_PATH;
152
- }
153
-
154
- function getFrontendServicePath(mode) {
155
- return mode === 'system' ? FRONTEND_DAEMON_SYSTEM_SERVICE_PATH : FRONTEND_DAEMON_USER_SERVICE_PATH;
156
- }
157
-
158
- function getSystemctlArgs(mode, commandArgs) {
159
- return mode === 'user' ? ['--user', ...commandArgs] : commandArgs;
160
- }
161
-
162
- function getJournalctlArgs(mode, commandArgs) {
163
- return mode === 'user' ? ['--user', ...commandArgs] : commandArgs;
164
- }
165
-
166
- function parseDaemonArgs(args) {
167
- const parsed = {
168
- subcommand: 'status',
169
- options: {
170
- mode: 'system',
171
- },
172
- };
173
-
174
- let i = 0;
175
- if (args[0] && DAEMON_SUBCOMMANDS.has(args[0])) {
176
- parsed.subcommand = args[0];
177
- i = 1;
178
- }
179
-
180
- for (; i < args.length; i++) {
181
- const arg = args[i];
182
- if (arg === '--port' || arg === '-p') {
183
- parsed.options.serverPort = args[++i];
184
- } else if (arg.startsWith('--port=')) {
185
- parsed.options.serverPort = arg.split('=')[1];
186
- } else if (arg === '--frontend-port') {
187
- parsed.options.frontendPort = args[++i];
188
- } else if (arg.startsWith('--frontend-port=')) {
189
- parsed.options.frontendPort = arg.split('=')[1];
190
- } else if (arg === '--mode' || arg === '-m') {
191
- parsed.options.mode = (args[++i] || '').toLowerCase();
192
- } else if (arg.startsWith('--mode=')) {
193
- parsed.options.mode = (arg.split('=')[1] || '').toLowerCase();
194
- } else if (arg === '--database-path') {
195
- parsed.options.databasePath = args[++i];
196
- } else if (arg.startsWith('--database-path=')) {
197
- parsed.options.databasePath = arg.split('=')[1];
198
- } else if (arg === '--help' || arg === '-h') {
199
- parsed.subcommand = 'help';
200
- } else {
201
- parsed.options.extraArgs = parsed.options.extraArgs || [];
202
- parsed.options.extraArgs.push(arg);
203
- }
204
- }
205
-
206
- return parsed;
207
- }
208
-
209
- function buildDaemonExecStart({ appRoot, serverPort, databasePath, nodeExecPath, cliEntry }) {
210
- const nodeExec = nodeExecPath || process.execPath || 'node';
211
- const cliCandidate = cliEntry
212
- ? path.resolve(cliEntry)
213
- : (process.argv[1] ? path.resolve(process.argv[1]) : path.join(appRoot, 'dist-server', 'server', 'cli.js'));
214
- const resolvedCliEntry = fs.existsSync(cliCandidate)
215
- ? cliCandidate
216
- : path.join(appRoot, 'dist-server', 'server', 'cli.js');
217
-
218
- const args = [nodeExec, resolvedCliEntry, 'start', '--port', String(serverPort)];
219
- if (databasePath) {
220
- args.push('--database-path', databasePath);
221
- }
222
-
223
- return args.map(quoteSystemdArg).join(' ');
224
- }
225
-
226
- function buildDaemonServiceUnit({ appRoot, serverPort, databasePath, nodeExecPath, cliEntry }) {
227
- const execStart = buildDaemonExecStart({
228
- appRoot,
229
- serverPort,
230
- databasePath,
231
- nodeExecPath,
232
- cliEntry,
233
- });
234
- return `[Unit]
235
- Description=Pixcode Server
236
- After=network.target
237
-
238
- [Service]
239
- Type=simple
240
- WorkingDirectory=${appRoot}
241
- ExecStart=${execStart}
242
- Environment=HOST=0.0.0.0
243
- Environment=CI=true
244
- Environment=PIXCODE_DAEMON_MANAGED=1
245
- Restart=always
246
- RestartSec=2
247
-
248
- [Install]
249
- WantedBy=default.target
250
- `;
251
- }
252
-
253
- function resolveFrontendDaemonEntry(appRoot, cliEntry) {
254
- const cliCandidate = cliEntry
255
- ? path.resolve(cliEntry)
256
- : (process.argv[1] ? path.resolve(process.argv[1]) : '');
257
- const candidates = [];
258
- if (cliCandidate) {
259
- candidates.push(path.join(path.dirname(cliCandidate), 'vite-daemon.js'));
260
- }
261
- candidates.push(path.join(appRoot, 'dist-server', 'server', 'vite-daemon.js'));
262
- candidates.push(path.join(appRoot, 'server', 'vite-daemon.js'));
263
-
264
- const resolved = candidates.find(candidate => fs.existsSync(candidate));
265
- if (!resolved) {
266
- throw new Error(
267
- `Frontend daemon entry was not found. Checked: ${candidates.join(', ')}. ` +
268
- `Run "npm run build:server" or ensure server/vite-daemon.js exists.`
269
- );
270
- }
271
- return resolved;
272
- }
273
-
274
- function buildFrontendDaemonExecStart({ appRoot, frontendPort, nodeExecPath, cliEntry }) {
275
- const nodeExec = nodeExecPath || process.execPath || 'node';
276
- const frontendEntry = resolveFrontendDaemonEntry(appRoot, cliEntry);
277
- const args = [
278
- nodeExec,
279
- frontendEntry,
280
- '--host',
281
- '0.0.0.0',
282
- '--port',
283
- String(frontendPort),
284
- '--strictPort',
285
- ];
286
- return args.map(quoteSystemdArg).join(' ');
287
- }
288
-
289
- function buildFrontendDaemonServiceUnit({ appRoot, frontendPort, nodeExecPath, cliEntry }) {
290
- const execStart = buildFrontendDaemonExecStart({
291
- appRoot,
292
- frontendPort,
293
- nodeExecPath,
294
- cliEntry,
295
- });
296
- return `[Unit]
297
- Description=Pixcode Frontend (Vite Dev Server)
298
- After=network.target
299
-
300
- [Service]
301
- Type=simple
302
- WorkingDirectory=${appRoot}
303
- ExecStart=${execStart}
304
- Environment=HOST=0.0.0.0
305
- Environment=CI=true
306
- Environment=PIXCODE_DAEMON_MANAGED=1
307
- Restart=always
308
- RestartSec=2
309
-
310
- [Install]
311
- WantedBy=default.target
312
- `;
313
- }
314
-
315
- function normalizeState(value) {
316
- const text = (value || '').trim();
317
- if (!text) return 'unknown';
318
- if (/No such file or directory/i.test(text)) return 'not-found';
319
- return text;
320
- }
321
-
322
- function getServiceState(mode, serviceName) {
323
- const activeRes = runCommand('systemctl', getSystemctlArgs(mode, ['is-active', serviceName]));
324
- const enabledRes = runCommand('systemctl', getSystemctlArgs(mode, ['is-enabled', serviceName]));
325
-
326
- return {
327
- active: normalizeState(activeRes.stdout || activeRes.stderr),
328
- enabled: normalizeState(enabledRes.stdout || enabledRes.stderr),
329
- };
330
- }
331
-
332
- function readLogs(mode, lines = 100, inherit = false, serviceNames = [DAEMON_SERVICE_NAME]) {
333
- const unitArgs = serviceNames.flatMap((serviceName) => ['-u', serviceName]);
334
- const args = [...getJournalctlArgs(mode, unitArgs), '-n', String(lines), '--no-pager'];
335
- return runCommand('journalctl', args, { inherit });
336
- }
337
-
338
- function getPortFromServiceUnit(servicePath) {
339
- if (!fs.existsSync(servicePath)) return null;
340
- try {
341
- const content = fs.readFileSync(servicePath, 'utf8');
342
- const quoted = content.match(/"--port"\s+"(\d+)"/);
343
- if (quoted) return Number(quoted[1]);
344
- const plain = content.match(/--port(?:\s+|=)(\d+)/);
345
- if (plain) return Number(plain[1]);
346
- } catch {
347
- // Ignore parse errors and use fallback port.
348
- }
349
- return null;
350
- }
351
-
352
- function findLatestErrorLine(logText) {
353
- if (!logText) return '';
354
- const lines = logText.split('\n').map(line => line.trim()).filter(Boolean);
355
- const errorLine = [...lines].reverse().find(line => /(error|failed|exception|denied|cannot|traceback)/i.test(line));
356
- return errorLine || '';
357
- }
358
-
359
- function probeUserBus() {
360
- const result = runCommand('systemctl', ['--user', 'show-environment']);
361
- return {
362
- ok: result.status === 0,
363
- detail: extractCommandError(result, 'systemd user bus is not reachable'),
364
- };
365
- }
366
-
367
- function probeLinger() {
368
- const result = runCommand('loginctl', ['show-user', os.userInfo().username, '-p', 'Linger']);
369
- if (result.status !== 0) {
370
- return {
371
- value: 'unknown',
372
- detail: extractCommandError(result, 'Could not read linger status'),
373
- };
374
- }
375
- const output = (result.stdout || '').trim();
376
- const value = output.includes('=') ? output.split('=')[1].trim().toLowerCase() : output.toLowerCase();
377
- return {
378
- value: value || 'unknown',
379
- detail: '',
380
- };
381
- }
382
-
383
- function resolveDaemonMode({ requestedMode, subcommand, userBusAvailable }) {
384
- if (requestedMode !== 'auto') {
385
- return requestedMode;
386
- }
387
-
388
- // Auto mode is intentionally system-first to guarantee boot-time startup
389
- // even without an interactive user session.
390
- const systemUnitInstalled = fs.existsSync(getDaemonServicePath('system'));
391
- const userUnitInstalled = fs.existsSync(getDaemonServicePath('user'));
392
-
393
- if (systemUnitInstalled) return 'system';
394
- if (subcommand === 'install') return 'system';
395
- if (userUnitInstalled && userBusAvailable) return 'user';
396
- return 'system';
397
- }
398
-
399
- function runSystemctl(mode, commandArgs, opts = {}) {
400
- const result = runCommand('systemctl', getSystemctlArgs(mode, commandArgs), { inherit: opts.inherit });
401
- if (result.status !== 0 && !opts.allowFailure) {
402
- let errorText = extractCommandError(result, `systemctl ${commandArgs.join(' ')} failed`);
403
- if (mode === 'system' && /(access denied|permission denied|must be root|interactive authentication required|not permitted)/i.test(errorText)) {
404
- errorText += '\nTry rerunning this daemon operation with elevated privileges (sudo).';
405
- }
406
- throw new Error(errorText);
407
- }
408
- return result;
409
- }
410
-
411
- async function sleep(ms) {
412
- await new Promise(resolve => setTimeout(resolve, ms));
413
- }
414
-
415
- async function isPortReachable(port, timeoutMs = 1000) {
416
- return await new Promise(resolve => {
417
- const socket = net.createConnection({ host: '127.0.0.1', port: Number(port) });
418
- let settled = false;
419
- const done = (value) => {
420
- if (settled) return;
421
- settled = true;
422
- socket.destroy();
423
- resolve(value);
424
- };
425
- socket.setTimeout(timeoutMs);
426
- socket.once('connect', () => done(true));
427
- socket.once('timeout', () => done(false));
428
- socket.once('error', () => done(false));
429
- });
430
- }
431
-
432
- async function requestHealthOnce(port, timeoutMs = DAEMON_HEALTH_REQUEST_TIMEOUT_MS) {
433
- return await new Promise((resolve, reject) => {
434
- const req = request({
435
- host: '127.0.0.1',
436
- port: Number(port),
437
- method: 'GET',
438
- path: '/health',
439
- timeout: timeoutMs,
440
- }, (res) => {
441
- res.resume();
442
- resolve({ ok: true, statusCode: res.statusCode });
443
- });
444
-
445
- req.on('timeout', () => req.destroy(new Error(`Health check timed out after ${timeoutMs}ms`)));
446
- req.on('error', reject);
447
- req.end();
448
- });
449
- }
450
-
451
- async function waitForHealth(port, timeoutMs = DAEMON_HEALTH_TIMEOUT_MS) {
452
- const deadline = Date.now() + timeoutMs;
453
- let lastError = null;
454
- while (Date.now() < deadline) {
455
- try {
456
- return await requestHealthOnce(port);
457
- } catch (error) {
458
- lastError = error;
459
- if (await isPortReachable(port, 700)) {
460
- return { ok: true, statusCode: null, probe: 'tcp' };
461
- }
462
- await sleep(DAEMON_HEALTH_RETRY_INTERVAL_MS);
463
- }
464
- }
465
- throw new Error(lastError?.message || `Service did not become healthy on port ${port}`);
466
- }
467
-
468
- async function healthCheckOrThrow(mode, serviceName, port, c) {
469
- const state = getServiceState(mode, serviceName);
470
- if (state.active !== 'active' && state.active !== 'activating') {
471
- throw new Error(`Service ${serviceName} is not active (state: ${state.active})`);
472
- }
473
-
474
- try {
475
- const health = await waitForHealth(port);
476
- if (health.probe === 'tcp') {
477
- console.log(`${c.warn('[WARN]')} HTTP /health probe delayed; TCP port ${port} is already accepting connections.`);
478
- }
479
- } catch (healthError) {
480
- const logsResult = readLogs(mode, 50, false, [serviceName]);
481
- const logText = (logsResult.stdout || logsResult.stderr || '').trim();
482
- const lastErrorLine = findLatestErrorLine(logText);
483
-
484
- if (logText) {
485
- console.log(`\n${c.warn('[WARN]')} Last 50 log lines for ${serviceName}:`);
486
- console.log(logText);
487
- }
488
-
489
- if (lastErrorLine) {
490
- throw new Error(`Health check failed for ${serviceName}: ${healthError.message}\nLikely cause: ${lastErrorLine}`);
491
- }
492
- throw new Error(`Health check failed for ${serviceName}: ${healthError.message}`);
493
- }
494
- }
495
-
496
- function ensureLinux() {
497
- if (process.platform !== 'linux') {
498
- throw new Error('The daemon command is supported on Linux only.');
499
- }
500
- }
501
-
502
- function ensureSystemctl() {
503
- const probe = runCommand('systemctl', ['--version']);
504
- if (probe.status !== 0) {
505
- throw new Error(extractCommandError(probe, 'systemctl is not available in this environment'));
506
- }
507
- }
508
-
509
- function showDaemonHelp(c, context = {}) {
510
- const usagePrefix = getDaemonCommandPrefix(context);
511
- const installExample = buildDaemonCliCommand(
512
- {
513
- subcommand: 'install',
514
- mode: 'system',
515
- extraArgs: ['--port', '3001', '--frontend-port', '5173'],
516
- },
517
- context
518
- );
519
- const statusExample = buildDaemonCliCommand({ subcommand: 'status', mode: 'system' }, context);
520
- const doctorExample = buildDaemonCliCommand({ subcommand: 'doctor', mode: 'auto' }, context);
521
- const logsExample = buildDaemonCliCommand({ subcommand: 'logs', mode: 'system' }, context);
522
- console.log(`
523
- ${c.bright('Pixcode Daemon')} - Persistent Linux service manager
524
-
525
- Usage:
526
- ${usagePrefix} daemon [subcommand] [options]
527
-
528
- Subcommands:
529
- ${c.bright('install')} Install/update unit, reload daemon, enable and start now
530
- ${c.bright('start')} Start the service
531
- ${c.bright('stop')} Stop the service (temporary; auto-start remains enabled)
532
- ${c.bright('restart')} Restart the service
533
- ${c.bright('status')} Show active/enabled state
534
- ${c.bright('logs')} Show recent service logs
535
- ${c.bright('enable')} Enable auto-start at boot
536
- ${c.bright('disable')} Disable auto-start at boot
537
- ${c.bright('uninstall')} Stop, disable, and remove the service unit
538
- ${c.bright('doctor')} Run diagnostics (bus, linger, units, state, port, logs)
539
- ${c.bright('help')} Show this help
540
-
541
- Options:
542
- -p, --port <port> Set service server port (default: 3001)
543
- --frontend-port <port> Set frontend Vite port (default: 5173)
544
- -m, --mode <mode> Service mode: user | system | auto (default: system)
545
- --database-path <path> Set service database path
546
-
547
- Examples:
548
- $ ${installExample}
549
- $ ${statusExample}
550
- $ ${doctorExample}
551
- $ ${logsExample}
552
- `);
553
- }
554
-
555
- export function hasInstalledDaemonUnit() {
556
- return (
557
- fs.existsSync(DAEMON_USER_SERVICE_PATH) ||
558
- fs.existsSync(DAEMON_SYSTEM_SERVICE_PATH) ||
559
- fs.existsSync(FRONTEND_DAEMON_USER_SERVICE_PATH) ||
560
- fs.existsSync(FRONTEND_DAEMON_SYSTEM_SERVICE_PATH)
561
- );
562
- }
563
-
564
- export async function handleDaemonCommand(args, context = {}) {
565
- const c = getColorHelpers(context.color);
566
- const parsed = parseDaemonArgs(args);
567
- const appRoot = context.appRoot || process.cwd();
568
- const daemonCommandContext = {
569
- appRoot,
570
- cliEntry: context.cliEntry,
571
- nodeExecPath: context.nodeExecPath,
572
- };
573
-
574
- if (parsed.options.extraArgs?.length) {
575
- showDaemonHelp(c, daemonCommandContext);
576
- throw new Error(`Unknown daemon arguments: ${parsed.options.extraArgs.join(' ')}`);
577
- }
578
-
579
- if (parsed.subcommand === 'help') {
580
- showDaemonHelp(c, daemonCommandContext);
581
- return;
582
- }
583
-
584
- if (!DAEMON_MODES.has(parsed.options.mode)) {
585
- throw new Error(`Invalid daemon mode "${parsed.options.mode}". Use one of: auto, user, system.`);
586
- }
587
-
588
- ensureLinux();
589
- ensureSystemctl();
590
-
591
- const defaultPort = context.defaultPort || process.env.SERVER_PORT || process.env.PORT || '3001';
592
- const defaultFrontendPort = context.defaultFrontendPort || process.env.VITE_PORT || String(DEFAULT_FRONTEND_PORT);
593
- const configuredPort = parsed.options.serverPort || defaultPort;
594
- const configuredFrontendPort = parsed.options.frontendPort || defaultFrontendPort;
595
- const databasePath = parsed.options.databasePath || process.env.DATABASE_PATH || '';
596
-
597
- const portNum = Number(configuredPort);
598
- if (!Number.isInteger(portNum) || portNum < 1 || portNum > 65535) {
599
- throw new Error(`Invalid port "${configuredPort}". Expected an integer between 1 and 65535.`);
600
- }
601
- const frontendPortNum = Number(configuredFrontendPort);
602
- if (!Number.isInteger(frontendPortNum) || frontendPortNum < 1 || frontendPortNum > 65535) {
603
- throw new Error(`Invalid frontend port "${configuredFrontendPort}". Expected an integer between 1 and 65535.`);
604
- }
605
-
606
- const userBus = probeUserBus();
607
- const mode = resolveDaemonMode({
608
- requestedMode: parsed.options.mode,
609
- subcommand: parsed.subcommand,
610
- userBusAvailable: userBus.ok,
611
- });
612
- const servicePath = getDaemonServicePath(mode);
613
- const frontendServicePath = getFrontendServicePath(mode);
614
- const effectivePort = getPortFromServiceUnit(servicePath) || portNum;
615
- const effectiveFrontendPort = getPortFromServiceUnit(frontendServicePath) || frontendPortNum;
616
-
617
- if (mode === 'user' && !userBus.ok) {
618
- const installSystemCommand = buildDaemonCliCommand(
619
- { subcommand: 'install', mode: 'system' },
620
- daemonCommandContext
621
- );
622
- throw new Error(
623
- `Could not connect to your systemd user session.\n${userBus.detail}\n` +
624
- `Try ${c.bright(installSystemCommand)} or enable user linger: ${c.bright(`sudo loginctl enable-linger ${os.userInfo().username}`)}`
625
- );
626
- }
627
-
628
- if (parsed.subcommand === 'doctor') {
629
- const linger = probeLinger();
630
- const userUnitInstalled = fs.existsSync(getDaemonServicePath('user'));
631
- const userFrontendUnitInstalled = fs.existsSync(getFrontendServicePath('user'));
632
- const systemUnitInstalled = fs.existsSync(getDaemonServicePath('system'));
633
- const systemFrontendUnitInstalled = fs.existsSync(getFrontendServicePath('system'));
634
- const selectedModePort = getPortFromServiceUnit(servicePath) || portNum;
635
- const selectedModeFrontendPort = getPortFromServiceUnit(frontendServicePath) || frontendPortNum;
636
- const portReachable = await isPortReachable(selectedModePort);
637
- const frontendPortReachable = await isPortReachable(selectedModeFrontendPort);
638
- const userState = userBus.ok
639
- ? {
640
- backend: getServiceState('user', DAEMON_SERVICE_NAME),
641
- frontend: getServiceState('user', FRONTEND_DAEMON_SERVICE_NAME),
642
- }
643
- : {
644
- backend: { active: 'unavailable', enabled: 'unavailable' },
645
- frontend: { active: 'unavailable', enabled: 'unavailable' },
646
- };
647
- const systemState = {
648
- backend: getServiceState('system', DAEMON_SERVICE_NAME),
649
- frontend: getServiceState('system', FRONTEND_DAEMON_SERVICE_NAME),
650
- };
651
- const logsResult = readLogs(mode, 50, false, [DAEMON_SERVICE_NAME, FRONTEND_DAEMON_SERVICE_NAME]);
652
- const logsText = (logsResult.stdout || logsResult.stderr || '').trim();
653
- const lastErrorLine = findLatestErrorLine(logsText);
654
-
655
- console.log(`\n${c.bright('Pixcode Daemon Doctor')}\n`);
656
- console.log(`${c.info('[INFO]')} Requested mode: ${c.bright(parsed.options.mode)}`);
657
- console.log(`${c.info('[INFO]')} Resolved mode: ${c.bright(mode)}`);
658
- console.log(`${c.info('[INFO]')} user-bus: ${userBus.ok ? c.ok('ok') : c.warn('unavailable')}`);
659
- if (!userBus.ok) {
660
- console.log(` ${c.dim(userBus.detail)}`);
661
- }
662
- console.log(`${c.info('[INFO]')} linger: ${c.bright(linger.value)}${linger.detail ? ` ${c.dim(`(${linger.detail})`)}` : ''}`);
663
- console.log(`${c.info('[INFO]')} user backend: ${userUnitInstalled ? c.ok('installed') : c.warn('missing')} (${c.dim(getDaemonServicePath('user'))})`);
664
- console.log(`${c.info('[INFO]')} user frontend: ${userFrontendUnitInstalled ? c.ok('installed') : c.warn('missing')} (${c.dim(getFrontendServicePath('user'))})`);
665
- console.log(`${c.info('[INFO]')} system backend: ${systemUnitInstalled ? c.ok('installed') : c.warn('missing')} (${c.dim(getDaemonServicePath('system'))})`);
666
- console.log(`${c.info('[INFO]')} system frontend:${systemFrontendUnitInstalled ? c.ok('installed') : c.warn('missing')} (${c.dim(getFrontendServicePath('system'))})`);
667
- console.log(`${c.info('[INFO]')} user state: backend active=${c.bright(userState.backend.active)} enabled=${c.bright(userState.backend.enabled)} | frontend active=${c.bright(userState.frontend.active)} enabled=${c.bright(userState.frontend.enabled)}`);
668
- console.log(`${c.info('[INFO]')} system state: backend active=${c.bright(systemState.backend.active)} enabled=${c.bright(systemState.backend.enabled)} | frontend active=${c.bright(systemState.frontend.active)} enabled=${c.bright(systemState.frontend.enabled)}`);
669
- console.log(`${c.info('[INFO]')} backend port: ${c.bright(String(selectedModePort))} (${portReachable ? c.ok('reachable') : c.warn('not reachable')})`);
670
- console.log(`${c.info('[INFO]')} frontend port: ${c.bright(String(selectedModeFrontendPort))} (${frontendPortReachable ? c.ok('reachable') : c.warn('not reachable')})`);
671
- if (lastErrorLine) {
672
- console.log(`${c.warn('[WARN]')} Latest error: ${lastErrorLine}`);
673
- }
674
-
675
- console.log(`\n${c.bright('Machine Readable')}`);
676
- console.log(`MODE_REQUESTED=${parsed.options.mode}`);
677
- console.log(`MODE_RESOLVED=${mode}`);
678
- console.log(`USER_BUS_OK=${userBus.ok}`);
679
- console.log(`LINGER=${linger.value}`);
680
- console.log(`USER_BACKEND_UNIT_INSTALLED=${userUnitInstalled}`);
681
- console.log(`USER_FRONTEND_UNIT_INSTALLED=${userFrontendUnitInstalled}`);
682
- console.log(`SYSTEM_BACKEND_UNIT_INSTALLED=${systemUnitInstalled}`);
683
- console.log(`SYSTEM_FRONTEND_UNIT_INSTALLED=${systemFrontendUnitInstalled}`);
684
- console.log(`USER_BACKEND_ACTIVE=${userState.backend.active}`);
685
- console.log(`USER_BACKEND_ENABLED=${userState.backend.enabled}`);
686
- console.log(`USER_FRONTEND_ACTIVE=${userState.frontend.active}`);
687
- console.log(`USER_FRONTEND_ENABLED=${userState.frontend.enabled}`);
688
- console.log(`SYSTEM_BACKEND_ACTIVE=${systemState.backend.active}`);
689
- console.log(`SYSTEM_BACKEND_ENABLED=${systemState.backend.enabled}`);
690
- console.log(`SYSTEM_FRONTEND_ACTIVE=${systemState.frontend.active}`);
691
- console.log(`SYSTEM_FRONTEND_ENABLED=${systemState.frontend.enabled}`);
692
- console.log(`BACKEND_PORT=${selectedModePort}`);
693
- console.log(`BACKEND_PORT_REACHABLE=${portReachable}`);
694
- console.log(`FRONTEND_PORT=${selectedModeFrontendPort}`);
695
- console.log(`FRONTEND_PORT_REACHABLE=${frontendPortReachable}`);
696
- console.log(`LAST_ERROR_LINE=${JSON.stringify(lastErrorLine || '')}\n`);
697
- return;
698
- }
699
-
700
- const serviceDefs = [
701
- {
702
- servicePath,
703
- },
704
- {
705
- servicePath: frontendServicePath,
706
- },
707
- ];
708
-
709
- switch (parsed.subcommand) {
710
- case 'install': {
711
- if (parsed.options.mode === 'auto' && mode === 'system' && !userBus.ok) {
712
- console.log(`${c.warn('[WARN]')} User mode is unavailable; auto mode is falling back to system mode.`);
713
- }
714
-
715
- try {
716
- fs.mkdirSync(path.dirname(servicePath), { recursive: true });
717
- fs.mkdirSync(path.dirname(frontendServicePath), { recursive: true });
718
-
719
- const backendUnitContent = buildDaemonServiceUnit({
720
- appRoot,
721
- serverPort: portNum,
722
- databasePath,
723
- nodeExecPath: context.nodeExecPath,
724
- cliEntry: context.cliEntry,
725
- });
726
- fs.writeFileSync(servicePath, backendUnitContent, 'utf8');
727
-
728
- const frontendUnitContent = buildFrontendDaemonServiceUnit({
729
- appRoot,
730
- frontendPort: frontendPortNum,
731
- nodeExecPath: context.nodeExecPath,
732
- cliEntry: context.cliEntry,
733
- });
734
- fs.writeFileSync(frontendServicePath, frontendUnitContent, 'utf8');
735
- } catch (fileError) {
736
- if (mode === 'system' && (fileError.code === 'EACCES' || fileError.code === 'EPERM')) {
737
- const installHint = buildDaemonCliCommand(
738
- {
739
- subcommand: 'install',
740
- mode: 'system',
741
- extraArgs: ['--port', String(portNum), '--frontend-port', String(frontendPortNum)],
742
- },
743
- daemonCommandContext
744
- );
745
- throw new Error(
746
- `Permission denied writing daemon unit files (${servicePath}, ${frontendServicePath}). ` +
747
- `Try: ${installHint}`
748
- );
749
- }
750
- throw fileError;
751
- }
752
-
753
- runSystemctl(mode, ['daemon-reload']);
754
- runSystemctl(mode, ['enable', '--now', DAEMON_SERVICE_NAME]);
755
- runSystemctl(mode, ['enable', '--now', FRONTEND_DAEMON_SERVICE_NAME]);
756
-
757
- if (mode === 'user') {
758
- const lingerResult = runCommand('loginctl', ['enable-linger', os.userInfo().username]);
759
- if (lingerResult.status !== 0) {
760
- console.log(`${c.warn('[WARN]')} Could not enable linger automatically.`);
761
- console.log(` ${c.dim(extractCommandError(lingerResult, 'Unknown linger error'))}`);
762
- console.log(` ${c.tip('[TIP]')} Run with sufficient privileges: ${c.bright(`sudo loginctl enable-linger ${os.userInfo().username}`)}`);
763
- }
764
- }
765
-
766
- const installedPort = getPortFromServiceUnit(servicePath) || portNum;
767
- const installedFrontendPort = getPortFromServiceUnit(frontendServicePath) || frontendPortNum;
768
- await healthCheckOrThrow(mode, DAEMON_SERVICE_NAME, installedPort, c);
769
- await healthCheckOrThrow(mode, FRONTEND_DAEMON_SERVICE_NAME, installedFrontendPort, c);
770
-
771
- const backendState = getServiceState(mode, DAEMON_SERVICE_NAME);
772
- const frontendState = getServiceState(mode, FRONTEND_DAEMON_SERVICE_NAME);
773
- console.log(`\n${c.ok('✔')} Daemon installed and started.`);
774
- console.log(` Mode: ${c.bright(mode)}`);
775
- console.log(` Backend Unit: ${c.dim(servicePath)}`);
776
- console.log(` Frontend Unit: ${c.dim(frontendServicePath)}`);
777
- console.log(` Backend Active: ${c.bright(backendState.active)}`);
778
- console.log(` Backend Enabled:${c.bright(backendState.enabled)}`);
779
- console.log(` Frontend Active:${c.bright(frontendState.active)}`);
780
- console.log(` Frontend Enabled:${c.bright(frontendState.enabled)}`);
781
- console.log(` Backend URL: ${c.bright(`http://localhost:${installedPort}`)}`);
782
- console.log(` Frontend URL: ${c.bright(`http://localhost:${installedFrontendPort}`)}\n`);
783
- if (mode === 'system') {
784
- const statusCommand = buildDaemonCliCommand(
785
- { subcommand: 'status', mode: 'system' },
786
- daemonCommandContext
787
- );
788
- const stopCommand = buildDaemonCliCommand(
789
- { subcommand: 'stop', mode: 'system' },
790
- daemonCommandContext
791
- );
792
- const logsCommand = buildDaemonCliCommand(
793
- { subcommand: 'logs', mode: 'system' },
794
- daemonCommandContext
795
- );
796
- console.log(`${c.ok('[OK]')} System daemon is active for backend and frontend.`);
797
- console.log(`${c.info('[INFO]')} Backend health: ${c.bright(`http://localhost:${installedPort}/health`)}`);
798
- console.log(`${c.info('[INFO]')} Frontend: ${c.bright(`http://localhost:${installedFrontendPort}/`)}`);
799
- console.log(`${c.info('[INFO]')} Status: ${c.bright(statusCommand)}`);
800
- console.log(`${c.info('[INFO]')} Stop: ${c.bright(stopCommand)}`);
801
- console.log(`${c.info('[INFO]')} Logs: ${c.bright(logsCommand)}\n`);
802
- } else {
803
- const linger = probeLinger();
804
- const statusCommand = buildDaemonCliCommand(
805
- { subcommand: 'status', mode: 'user' },
806
- daemonCommandContext
807
- );
808
- const stopCommand = buildDaemonCliCommand(
809
- { subcommand: 'stop', mode: 'user' },
810
- daemonCommandContext
811
- );
812
- const logsCommand = buildDaemonCliCommand(
813
- { subcommand: 'logs', mode: 'user' },
814
- daemonCommandContext
815
- );
816
- console.log(`${c.ok('[OK]')} User daemon is active for backend and frontend.`);
817
- console.log(`${c.info('[INFO]')} Backend health: ${c.bright(`http://localhost:${installedPort}/health`)}`);
818
- console.log(`${c.info('[INFO]')} Frontend: ${c.bright(`http://localhost:${installedFrontendPort}/`)}`);
819
- console.log(`${c.info('[INFO]')} Status: ${c.bright(statusCommand)}`);
820
- console.log(`${c.info('[INFO]')} Stop: ${c.bright(stopCommand)}`);
821
- console.log(`${c.info('[INFO]')} Logs: ${c.bright(logsCommand)}`);
822
- if (linger.value !== 'yes') {
823
- console.log(`${c.tip('[TIP]')} Enable linger for reboot/login persistence: ${c.bright(`sudo loginctl enable-linger ${os.userInfo().username}`)}\n`);
824
- } else {
825
- console.log('');
826
- }
827
- }
828
- break;
829
- }
830
-
831
- case 'start':
832
- runSystemctl(mode, ['start', DAEMON_SERVICE_NAME]);
833
- runSystemctl(mode, ['start', FRONTEND_DAEMON_SERVICE_NAME]);
834
- await healthCheckOrThrow(mode, DAEMON_SERVICE_NAME, effectivePort, c);
835
- await healthCheckOrThrow(mode, FRONTEND_DAEMON_SERVICE_NAME, effectiveFrontendPort, c);
836
- console.log(`${c.ok('[OK]')} Backend and frontend services started.`);
837
- break;
838
-
839
- case 'stop':
840
- runSystemctl(mode, ['stop', FRONTEND_DAEMON_SERVICE_NAME], { allowFailure: true });
841
- runSystemctl(mode, ['stop', DAEMON_SERVICE_NAME]);
842
- console.log(`${c.ok('[OK]')} Backend and frontend services stopped (auto-start remains enabled).`);
843
- break;
844
-
845
- case 'restart':
846
- runSystemctl(mode, ['restart', DAEMON_SERVICE_NAME]);
847
- runSystemctl(mode, ['restart', FRONTEND_DAEMON_SERVICE_NAME]);
848
- await healthCheckOrThrow(mode, DAEMON_SERVICE_NAME, effectivePort, c);
849
- await healthCheckOrThrow(mode, FRONTEND_DAEMON_SERVICE_NAME, effectiveFrontendPort, c);
850
- console.log(`${c.ok('[OK]')} Backend and frontend services restarted.`);
851
- break;
852
-
853
- case 'enable':
854
- runSystemctl(mode, ['enable', DAEMON_SERVICE_NAME]);
855
- runSystemctl(mode, ['enable', FRONTEND_DAEMON_SERVICE_NAME]);
856
- console.log(`${c.ok('[OK]')} Backend and frontend services enabled for auto-start.`);
857
- break;
858
-
859
- case 'disable':
860
- runSystemctl(mode, ['disable', DAEMON_SERVICE_NAME]);
861
- runSystemctl(mode, ['disable', FRONTEND_DAEMON_SERVICE_NAME]);
862
- console.log(`${c.ok('[OK]')} Backend and frontend services disabled for auto-start.`);
863
- break;
864
-
865
- case 'logs': {
866
- const logsResult = readLogs(mode, 100, true, [DAEMON_SERVICE_NAME, FRONTEND_DAEMON_SERVICE_NAME]);
867
- if (logsResult.status !== 0) {
868
- throw new Error(extractCommandError(logsResult, 'Unable to read daemon logs'));
869
- }
870
- break;
871
- }
872
-
873
- case 'uninstall': {
874
- runSystemctl(mode, ['stop', FRONTEND_DAEMON_SERVICE_NAME], { allowFailure: true });
875
- runSystemctl(mode, ['disable', FRONTEND_DAEMON_SERVICE_NAME], { allowFailure: true });
876
- runSystemctl(mode, ['stop', DAEMON_SERVICE_NAME], { allowFailure: true });
877
- runSystemctl(mode, ['disable', DAEMON_SERVICE_NAME], { allowFailure: true });
878
-
879
- for (const def of serviceDefs) {
880
- if (!fs.existsSync(def.servicePath)) continue;
881
- try {
882
- fs.unlinkSync(def.servicePath);
883
- } catch (unlinkError) {
884
- if (mode === 'system' && (unlinkError.code === 'EACCES' || unlinkError.code === 'EPERM')) {
885
- const uninstallHint = buildDaemonCliCommand(
886
- { subcommand: 'uninstall', mode: 'system' },
887
- daemonCommandContext
888
- );
889
- throw new Error(`Permission denied removing ${def.servicePath}. Try: ${uninstallHint}`);
890
- }
891
- throw unlinkError;
892
- }
893
- }
894
- runSystemctl(mode, ['daemon-reload'], { allowFailure: true });
895
- console.log(`${c.ok('[OK]')} Backend and frontend daemons uninstalled.`);
896
- break;
897
- }
898
-
899
- case 'status':
900
- default: {
901
- const backendState = getServiceState(mode, DAEMON_SERVICE_NAME);
902
- const frontendState = getServiceState(mode, FRONTEND_DAEMON_SERVICE_NAME);
903
- const backendUnitExists = fs.existsSync(servicePath);
904
- const frontendUnitExists = fs.existsSync(frontendServicePath);
905
- const selectedPort = getPortFromServiceUnit(servicePath) || portNum;
906
- const selectedFrontendPort = getPortFromServiceUnit(frontendServicePath) || frontendPortNum;
907
- console.log(`\n${c.bright('Pixcode Daemon Status')}\n`);
908
- console.log(`${c.info('[INFO]')} Mode: ${c.bright(mode)} ${parsed.options.mode === 'auto' ? c.dim('(resolved from auto)') : ''}`);
909
- console.log(`${c.info('[INFO]')} Backend Unit: ${c.dim(servicePath)} ${backendUnitExists ? c.ok('[OK]') : c.warn('[MISSING]')}`);
910
- console.log(`${c.info('[INFO]')} Backend Active: ${c.bright(backendState.active)}`);
911
- console.log(`${c.info('[INFO]')} Backend Enabled:${c.bright(backendState.enabled)}`);
912
- console.log(`${c.info('[INFO]')} Backend Port: ${c.bright(String(selectedPort))}`);
913
- console.log(`${c.info('[INFO]')} Frontend Unit: ${c.dim(frontendServicePath)} ${frontendUnitExists ? c.ok('[OK]') : c.warn('[MISSING]')}`);
914
- console.log(`${c.info('[INFO]')} Frontend Active:${c.bright(frontendState.active)}`);
915
- console.log(`${c.info('[INFO]')} Frontend Enabled:${c.bright(frontendState.enabled)}`);
916
- console.log(`${c.info('[INFO]')} Frontend Port: ${c.bright(String(selectedFrontendPort))}`);
917
- console.log('');
918
- }
919
- }
920
- }
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import os from 'os';
4
+ import { spawnSync } from 'child_process';
5
+ import { request } from 'node:http';
6
+ import net from 'node:net';
7
+
8
+ const DAEMON_SERVICE_NAME = 'pixcode.service';
9
+ const FRONTEND_DAEMON_SERVICE_NAME = 'pixcode-frontend.service';
10
+ const DAEMON_USER_SERVICE_PATH = path.join(os.homedir(), '.config', 'systemd', 'user', DAEMON_SERVICE_NAME);
11
+ const DAEMON_SYSTEM_SERVICE_PATH = path.join('/etc', 'systemd', 'system', DAEMON_SERVICE_NAME);
12
+ const FRONTEND_DAEMON_USER_SERVICE_PATH = path.join(os.homedir(), '.config', 'systemd', 'user', FRONTEND_DAEMON_SERVICE_NAME);
13
+ const FRONTEND_DAEMON_SYSTEM_SERVICE_PATH = path.join('/etc', 'systemd', 'system', FRONTEND_DAEMON_SERVICE_NAME);
14
+ const DEFAULT_FRONTEND_PORT = 5173;
15
+ const DAEMON_HEALTH_TIMEOUT_MS = 60000;
16
+ const DAEMON_HEALTH_REQUEST_TIMEOUT_MS = 4000;
17
+ const DAEMON_HEALTH_RETRY_INTERVAL_MS = 1000;
18
+
19
+ const DAEMON_SUBCOMMANDS = new Set([
20
+ 'install',
21
+ 'start',
22
+ 'stop',
23
+ 'restart',
24
+ 'status',
25
+ 'logs',
26
+ 'enable',
27
+ 'disable',
28
+ 'uninstall',
29
+ 'doctor',
30
+ 'help',
31
+ ]);
32
+
33
+ const DAEMON_MODES = new Set(['auto', 'user', 'system']);
34
+ const SYSTEM_MUTATING_DAEMON_SUBCOMMANDS = new Set([
35
+ 'install',
36
+ 'start',
37
+ 'stop',
38
+ 'restart',
39
+ 'enable',
40
+ 'disable',
41
+ 'uninstall',
42
+ 'logs',
43
+ ]);
44
+ let pixcodeBinaryAvailableCache = null;
45
+
46
+ function passthroughColor(text) {
47
+ return text;
48
+ }
49
+
50
+ function getColorHelpers(color) {
51
+ if (color) {
52
+ return color;
53
+ }
54
+ return {
55
+ info: passthroughColor,
56
+ ok: passthroughColor,
57
+ warn: passthroughColor,
58
+ error: passthroughColor,
59
+ tip: passthroughColor,
60
+ bright: passthroughColor,
61
+ dim: passthroughColor,
62
+ };
63
+ }
64
+
65
+ function runCommand(bin, args, opts = {}) {
66
+ const stdio = opts.inherit ? 'inherit' : 'pipe';
67
+ return spawnSync(bin, args, {
68
+ encoding: 'utf8',
69
+ stdio,
70
+ });
71
+ }
72
+
73
+ function extractCommandError(result, fallbackMessage) {
74
+ if (!result) return fallbackMessage;
75
+ const fromError = result.error?.message?.trim();
76
+ if (fromError) return fromError;
77
+ const fromStd = (result.stderr || result.stdout || '').trim();
78
+ if (fromStd) return fromStd;
79
+ return fallbackMessage;
80
+ }
81
+
82
+ function isRootUser() {
83
+ return typeof process.getuid === 'function' && process.getuid() === 0;
84
+ }
85
+
86
+ function quoteShellArg(arg) {
87
+ const value = String(arg);
88
+ if (/^[A-Za-z0-9_./:=+-]+$/.test(value)) {
89
+ return value;
90
+ }
91
+ return `'${value.replace(/'/g, `'\\''`)}'`;
92
+ }
93
+
94
+ function quoteSystemdArg(arg) {
95
+ return `"${String(arg).replace(/(["\\$`])/g, '\\$1')}"`;
96
+ }
97
+
98
+ function resolveDaemonCliEntryPath(context = {}) {
99
+ const appRoot = context.appRoot || process.cwd();
100
+ const explicitCliEntry = context.cliEntry ? path.resolve(context.cliEntry) : null;
101
+ const argvCliEntry = process.argv[1] ? path.resolve(process.argv[1]) : null;
102
+ const candidatePaths = [
103
+ explicitCliEntry,
104
+ argvCliEntry,
105
+ path.join(appRoot, 'dist-server', 'server', 'cli.js'),
106
+ path.join(appRoot, 'server', 'cli.js'),
107
+ ].filter(Boolean);
108
+
109
+ const existingPath = candidatePaths.find(candidate => fs.existsSync(candidate));
110
+ if (existingPath) {
111
+ return existingPath;
112
+ }
113
+
114
+ return explicitCliEntry || argvCliEntry || path.join(appRoot, 'server', 'cli.js');
115
+ }
116
+
117
+ function hasPixcodeBinary() {
118
+ if (pixcodeBinaryAvailableCache !== null) {
119
+ return pixcodeBinaryAvailableCache;
120
+ }
121
+
122
+ const probe = runCommand('pixcode', ['--version']);
123
+ pixcodeBinaryAvailableCache = probe.status === 0;
124
+ return pixcodeBinaryAvailableCache;
125
+ }
126
+
127
+ function getDaemonCommandPrefix(context = {}, { forceLocal = false } = {}) {
128
+ if (!forceLocal && hasPixcodeBinary()) {
129
+ return 'pixcode';
130
+ }
131
+
132
+ const nodeExec = context.nodeExecPath || process.execPath || 'node';
133
+ const cliEntry = resolveDaemonCliEntryPath(context);
134
+ return `${quoteShellArg(nodeExec)} ${quoteShellArg(cliEntry)}`;
135
+ }
136
+
137
+ export function buildDaemonCliCommand({ subcommand, mode = 'system', extraArgs = [] }, context = {}) {
138
+ const normalizedSubcommand = String(subcommand || 'status').trim() || 'status';
139
+ const normalizedMode = String(mode || 'system').trim() || 'system';
140
+ const args = ['daemon', normalizedSubcommand, '--mode', normalizedMode, ...extraArgs.map(value => String(value))];
141
+ const needsSudo =
142
+ normalizedMode === 'system' &&
143
+ SYSTEM_MUTATING_DAEMON_SUBCOMMANDS.has(normalizedSubcommand) &&
144
+ !isRootUser();
145
+ const prefix = getDaemonCommandPrefix(context, { forceLocal: needsSudo });
146
+ const command = `${prefix} ${args.map(quoteShellArg).join(' ')}`;
147
+ return needsSudo ? `sudo ${command}` : command;
148
+ }
149
+
150
+ function getDaemonServicePath(mode) {
151
+ return mode === 'system' ? DAEMON_SYSTEM_SERVICE_PATH : DAEMON_USER_SERVICE_PATH;
152
+ }
153
+
154
+ function getFrontendServicePath(mode) {
155
+ return mode === 'system' ? FRONTEND_DAEMON_SYSTEM_SERVICE_PATH : FRONTEND_DAEMON_USER_SERVICE_PATH;
156
+ }
157
+
158
+ function getSystemctlArgs(mode, commandArgs) {
159
+ return mode === 'user' ? ['--user', ...commandArgs] : commandArgs;
160
+ }
161
+
162
+ function getJournalctlArgs(mode, commandArgs) {
163
+ return mode === 'user' ? ['--user', ...commandArgs] : commandArgs;
164
+ }
165
+
166
+ function parseDaemonArgs(args) {
167
+ const parsed = {
168
+ subcommand: 'status',
169
+ options: {
170
+ mode: 'system',
171
+ },
172
+ };
173
+
174
+ let i = 0;
175
+ if (args[0] && DAEMON_SUBCOMMANDS.has(args[0])) {
176
+ parsed.subcommand = args[0];
177
+ i = 1;
178
+ }
179
+
180
+ for (; i < args.length; i++) {
181
+ const arg = args[i];
182
+ if (arg === '--port' || arg === '-p') {
183
+ parsed.options.serverPort = args[++i];
184
+ } else if (arg.startsWith('--port=')) {
185
+ parsed.options.serverPort = arg.split('=')[1];
186
+ } else if (arg === '--frontend-port') {
187
+ parsed.options.frontendPort = args[++i];
188
+ } else if (arg.startsWith('--frontend-port=')) {
189
+ parsed.options.frontendPort = arg.split('=')[1];
190
+ } else if (arg === '--no-frontend' || arg === '--single-port') {
191
+ parsed.options.noFrontend = true;
192
+ } else if (arg === '--mode' || arg === '-m') {
193
+ parsed.options.mode = (args[++i] || '').toLowerCase();
194
+ } else if (arg.startsWith('--mode=')) {
195
+ parsed.options.mode = (arg.split('=')[1] || '').toLowerCase();
196
+ } else if (arg === '--database-path') {
197
+ parsed.options.databasePath = args[++i];
198
+ } else if (arg.startsWith('--database-path=')) {
199
+ parsed.options.databasePath = arg.split('=')[1];
200
+ } else if (arg === '--help' || arg === '-h') {
201
+ parsed.subcommand = 'help';
202
+ } else {
203
+ parsed.options.extraArgs = parsed.options.extraArgs || [];
204
+ parsed.options.extraArgs.push(arg);
205
+ }
206
+ }
207
+
208
+ return parsed;
209
+ }
210
+
211
+ function buildDaemonExecStart({ appRoot, serverPort, databasePath, nodeExecPath, cliEntry }) {
212
+ const nodeExec = nodeExecPath || process.execPath || 'node';
213
+ const cliCandidate = cliEntry
214
+ ? path.resolve(cliEntry)
215
+ : (process.argv[1] ? path.resolve(process.argv[1]) : path.join(appRoot, 'dist-server', 'server', 'cli.js'));
216
+ const resolvedCliEntry = fs.existsSync(cliCandidate)
217
+ ? cliCandidate
218
+ : path.join(appRoot, 'dist-server', 'server', 'cli.js');
219
+
220
+ const args = [nodeExec, resolvedCliEntry, 'start', '--port', String(serverPort)];
221
+ if (databasePath) {
222
+ args.push('--database-path', databasePath);
223
+ }
224
+
225
+ return args.map(quoteSystemdArg).join(' ');
226
+ }
227
+
228
+ function buildDaemonServiceUnit({ appRoot, serverPort, databasePath, nodeExecPath, cliEntry }) {
229
+ const execStart = buildDaemonExecStart({
230
+ appRoot,
231
+ serverPort,
232
+ databasePath,
233
+ nodeExecPath,
234
+ cliEntry,
235
+ });
236
+ return `[Unit]
237
+ Description=Pixcode Server
238
+ After=network.target
239
+
240
+ [Service]
241
+ Type=simple
242
+ WorkingDirectory=${appRoot}
243
+ ExecStart=${execStart}
244
+ Environment=HOST=0.0.0.0
245
+ Environment=CI=true
246
+ Environment=PIXCODE_DAEMON_MANAGED=1
247
+ Restart=always
248
+ RestartSec=2
249
+
250
+ [Install]
251
+ WantedBy=default.target
252
+ `;
253
+ }
254
+
255
+ function resolveFrontendDaemonEntry(appRoot, cliEntry) {
256
+ const cliCandidate = cliEntry
257
+ ? path.resolve(cliEntry)
258
+ : (process.argv[1] ? path.resolve(process.argv[1]) : '');
259
+ const candidates = [];
260
+ if (cliCandidate) {
261
+ candidates.push(path.join(path.dirname(cliCandidate), 'vite-daemon.js'));
262
+ }
263
+ candidates.push(path.join(appRoot, 'dist-server', 'server', 'vite-daemon.js'));
264
+ candidates.push(path.join(appRoot, 'server', 'vite-daemon.js'));
265
+
266
+ const resolved = candidates.find(candidate => fs.existsSync(candidate));
267
+ if (!resolved) {
268
+ throw new Error(
269
+ `Frontend daemon entry was not found. Checked: ${candidates.join(', ')}. ` +
270
+ `Run "npm run build:server" or ensure server/vite-daemon.js exists.`
271
+ );
272
+ }
273
+ return resolved;
274
+ }
275
+
276
+ function buildFrontendDaemonExecStart({ appRoot, frontendPort, nodeExecPath, cliEntry }) {
277
+ const nodeExec = nodeExecPath || process.execPath || 'node';
278
+ const frontendEntry = resolveFrontendDaemonEntry(appRoot, cliEntry);
279
+ const args = [
280
+ nodeExec,
281
+ frontendEntry,
282
+ '--host',
283
+ '0.0.0.0',
284
+ '--port',
285
+ String(frontendPort),
286
+ '--strictPort',
287
+ ];
288
+ return args.map(quoteSystemdArg).join(' ');
289
+ }
290
+
291
+ function buildFrontendDaemonServiceUnit({ appRoot, frontendPort, nodeExecPath, cliEntry }) {
292
+ const execStart = buildFrontendDaemonExecStart({
293
+ appRoot,
294
+ frontendPort,
295
+ nodeExecPath,
296
+ cliEntry,
297
+ });
298
+ return `[Unit]
299
+ Description=Pixcode Frontend (Vite Dev Server)
300
+ After=network.target
301
+
302
+ [Service]
303
+ Type=simple
304
+ WorkingDirectory=${appRoot}
305
+ ExecStart=${execStart}
306
+ Environment=HOST=0.0.0.0
307
+ Environment=CI=true
308
+ Environment=PIXCODE_DAEMON_MANAGED=1
309
+ Restart=always
310
+ RestartSec=2
311
+
312
+ [Install]
313
+ WantedBy=default.target
314
+ `;
315
+ }
316
+
317
+ function normalizeState(value) {
318
+ const text = (value || '').trim();
319
+ if (!text) return 'unknown';
320
+ if (/No such file or directory/i.test(text)) return 'not-found';
321
+ return text;
322
+ }
323
+
324
+ function getServiceState(mode, serviceName) {
325
+ const activeRes = runCommand('systemctl', getSystemctlArgs(mode, ['is-active', serviceName]));
326
+ const enabledRes = runCommand('systemctl', getSystemctlArgs(mode, ['is-enabled', serviceName]));
327
+
328
+ return {
329
+ active: normalizeState(activeRes.stdout || activeRes.stderr),
330
+ enabled: normalizeState(enabledRes.stdout || enabledRes.stderr),
331
+ };
332
+ }
333
+
334
+ function readLogs(mode, lines = 100, inherit = false, serviceNames = [DAEMON_SERVICE_NAME]) {
335
+ const unitArgs = serviceNames.flatMap((serviceName) => ['-u', serviceName]);
336
+ const args = [...getJournalctlArgs(mode, unitArgs), '-n', String(lines), '--no-pager'];
337
+ return runCommand('journalctl', args, { inherit });
338
+ }
339
+
340
+ function getPortFromServiceUnit(servicePath) {
341
+ if (!fs.existsSync(servicePath)) return null;
342
+ try {
343
+ const content = fs.readFileSync(servicePath, 'utf8');
344
+ const quoted = content.match(/"--port"\s+"(\d+)"/);
345
+ if (quoted) return Number(quoted[1]);
346
+ const plain = content.match(/--port(?:\s+|=)(\d+)/);
347
+ if (plain) return Number(plain[1]);
348
+ } catch {
349
+ // Ignore parse errors and use fallback port.
350
+ }
351
+ return null;
352
+ }
353
+
354
+ function findLatestErrorLine(logText) {
355
+ if (!logText) return '';
356
+ const lines = logText.split('\n').map(line => line.trim()).filter(Boolean);
357
+ const errorLine = [...lines].reverse().find(line => /(error|failed|exception|denied|cannot|traceback)/i.test(line));
358
+ return errorLine || '';
359
+ }
360
+
361
+ function probeUserBus() {
362
+ const result = runCommand('systemctl', ['--user', 'show-environment']);
363
+ return {
364
+ ok: result.status === 0,
365
+ detail: extractCommandError(result, 'systemd user bus is not reachable'),
366
+ };
367
+ }
368
+
369
+ function probeLinger() {
370
+ const result = runCommand('loginctl', ['show-user', os.userInfo().username, '-p', 'Linger']);
371
+ if (result.status !== 0) {
372
+ return {
373
+ value: 'unknown',
374
+ detail: extractCommandError(result, 'Could not read linger status'),
375
+ };
376
+ }
377
+ const output = (result.stdout || '').trim();
378
+ const value = output.includes('=') ? output.split('=')[1].trim().toLowerCase() : output.toLowerCase();
379
+ return {
380
+ value: value || 'unknown',
381
+ detail: '',
382
+ };
383
+ }
384
+
385
+ function resolveDaemonMode({ requestedMode, subcommand, userBusAvailable }) {
386
+ if (requestedMode !== 'auto') {
387
+ return requestedMode;
388
+ }
389
+
390
+ // Auto mode is intentionally system-first to guarantee boot-time startup
391
+ // even without an interactive user session.
392
+ const systemUnitInstalled = fs.existsSync(getDaemonServicePath('system'));
393
+ const userUnitInstalled = fs.existsSync(getDaemonServicePath('user'));
394
+
395
+ if (systemUnitInstalled) return 'system';
396
+ if (subcommand === 'install') return 'system';
397
+ if (userUnitInstalled && userBusAvailable) return 'user';
398
+ return 'system';
399
+ }
400
+
401
+ function runSystemctl(mode, commandArgs, opts = {}) {
402
+ const result = runCommand('systemctl', getSystemctlArgs(mode, commandArgs), { inherit: opts.inherit });
403
+ if (result.status !== 0 && !opts.allowFailure) {
404
+ let errorText = extractCommandError(result, `systemctl ${commandArgs.join(' ')} failed`);
405
+ if (mode === 'system' && /(access denied|permission denied|must be root|interactive authentication required|not permitted)/i.test(errorText)) {
406
+ errorText += '\nTry rerunning this daemon operation with elevated privileges (sudo).';
407
+ }
408
+ throw new Error(errorText);
409
+ }
410
+ return result;
411
+ }
412
+
413
+ async function sleep(ms) {
414
+ await new Promise(resolve => setTimeout(resolve, ms));
415
+ }
416
+
417
+ async function isPortReachable(port, timeoutMs = 1000) {
418
+ return await new Promise(resolve => {
419
+ const socket = net.createConnection({ host: '127.0.0.1', port: Number(port) });
420
+ let settled = false;
421
+ const done = (value) => {
422
+ if (settled) return;
423
+ settled = true;
424
+ socket.destroy();
425
+ resolve(value);
426
+ };
427
+ socket.setTimeout(timeoutMs);
428
+ socket.once('connect', () => done(true));
429
+ socket.once('timeout', () => done(false));
430
+ socket.once('error', () => done(false));
431
+ });
432
+ }
433
+
434
+ async function requestHealthOnce(port, timeoutMs = DAEMON_HEALTH_REQUEST_TIMEOUT_MS) {
435
+ return await new Promise((resolve, reject) => {
436
+ const req = request({
437
+ host: '127.0.0.1',
438
+ port: Number(port),
439
+ method: 'GET',
440
+ path: '/health',
441
+ timeout: timeoutMs,
442
+ }, (res) => {
443
+ res.resume();
444
+ resolve({ ok: true, statusCode: res.statusCode });
445
+ });
446
+
447
+ req.on('timeout', () => req.destroy(new Error(`Health check timed out after ${timeoutMs}ms`)));
448
+ req.on('error', reject);
449
+ req.end();
450
+ });
451
+ }
452
+
453
+ async function waitForHealth(port, timeoutMs = DAEMON_HEALTH_TIMEOUT_MS) {
454
+ const deadline = Date.now() + timeoutMs;
455
+ let lastError = null;
456
+ while (Date.now() < deadline) {
457
+ try {
458
+ return await requestHealthOnce(port);
459
+ } catch (error) {
460
+ lastError = error;
461
+ if (await isPortReachable(port, 700)) {
462
+ return { ok: true, statusCode: null, probe: 'tcp' };
463
+ }
464
+ await sleep(DAEMON_HEALTH_RETRY_INTERVAL_MS);
465
+ }
466
+ }
467
+ throw new Error(lastError?.message || `Service did not become healthy on port ${port}`);
468
+ }
469
+
470
+ async function healthCheckOrThrow(mode, serviceName, port, c) {
471
+ const state = getServiceState(mode, serviceName);
472
+ if (state.active !== 'active' && state.active !== 'activating') {
473
+ throw new Error(`Service ${serviceName} is not active (state: ${state.active})`);
474
+ }
475
+
476
+ try {
477
+ const health = await waitForHealth(port);
478
+ if (health.probe === 'tcp') {
479
+ console.log(`${c.warn('[WARN]')} HTTP /health probe delayed; TCP port ${port} is already accepting connections.`);
480
+ }
481
+ } catch (healthError) {
482
+ const logsResult = readLogs(mode, 50, false, [serviceName]);
483
+ const logText = (logsResult.stdout || logsResult.stderr || '').trim();
484
+ const lastErrorLine = findLatestErrorLine(logText);
485
+
486
+ if (logText) {
487
+ console.log(`\n${c.warn('[WARN]')} Last 50 log lines for ${serviceName}:`);
488
+ console.log(logText);
489
+ }
490
+
491
+ if (lastErrorLine) {
492
+ throw new Error(`Health check failed for ${serviceName}: ${healthError.message}\nLikely cause: ${lastErrorLine}`);
493
+ }
494
+ throw new Error(`Health check failed for ${serviceName}: ${healthError.message}`);
495
+ }
496
+ }
497
+
498
+ function ensureLinux() {
499
+ if (process.platform !== 'linux') {
500
+ throw new Error('The daemon command is supported on Linux only.');
501
+ }
502
+ }
503
+
504
+ function ensureSystemctl() {
505
+ const probe = runCommand('systemctl', ['--version']);
506
+ if (probe.status !== 0) {
507
+ throw new Error(extractCommandError(probe, 'systemctl is not available in this environment'));
508
+ }
509
+ }
510
+
511
+ function showDaemonHelp(c, context = {}) {
512
+ const usagePrefix = getDaemonCommandPrefix(context);
513
+ const installExample = buildDaemonCliCommand(
514
+ {
515
+ subcommand: 'install',
516
+ mode: 'system',
517
+ extraArgs: ['--port', '3001', '--single-port'],
518
+ },
519
+ context
520
+ );
521
+ const statusExample = buildDaemonCliCommand({ subcommand: 'status', mode: 'system' }, context);
522
+ const doctorExample = buildDaemonCliCommand({ subcommand: 'doctor', mode: 'auto' }, context);
523
+ const logsExample = buildDaemonCliCommand({ subcommand: 'logs', mode: 'system' }, context);
524
+ console.log(`
525
+ ${c.bright('Pixcode Daemon')} - Persistent Linux service manager
526
+
527
+ Usage:
528
+ ${usagePrefix} daemon [subcommand] [options]
529
+
530
+ Subcommands:
531
+ ${c.bright('install')} Install/update unit, reload daemon, enable and start now
532
+ ${c.bright('start')} Start the service
533
+ ${c.bright('stop')} Stop the service (temporary; auto-start remains enabled)
534
+ ${c.bright('restart')} Restart the service
535
+ ${c.bright('status')} Show active/enabled state
536
+ ${c.bright('logs')} Show recent service logs
537
+ ${c.bright('enable')} Enable auto-start at boot
538
+ ${c.bright('disable')} Disable auto-start at boot
539
+ ${c.bright('uninstall')} Stop, disable, and remove the service unit
540
+ ${c.bright('doctor')} Run diagnostics (bus, linger, units, state, port, logs)
541
+ ${c.bright('help')} Show this help
542
+
543
+ Options:
544
+ -p, --port <port> Set service server port (default: 3001)
545
+ --frontend-port <port> Start a separate frontend Vite service on this port (legacy/dev)
546
+ --single-port, --no-frontend
547
+ Serve the built UI from the backend port only (default)
548
+ -m, --mode <mode> Service mode: user | system | auto (default: system)
549
+ --database-path <path> Set service database path
550
+
551
+ Examples:
552
+ $ ${installExample}
553
+ $ ${statusExample}
554
+ $ ${doctorExample}
555
+ $ ${logsExample}
556
+ `);
557
+ }
558
+
559
+ export function hasInstalledDaemonUnit() {
560
+ return (
561
+ fs.existsSync(DAEMON_USER_SERVICE_PATH) ||
562
+ fs.existsSync(DAEMON_SYSTEM_SERVICE_PATH) ||
563
+ fs.existsSync(FRONTEND_DAEMON_USER_SERVICE_PATH) ||
564
+ fs.existsSync(FRONTEND_DAEMON_SYSTEM_SERVICE_PATH)
565
+ );
566
+ }
567
+
568
+ export async function handleDaemonCommand(args, context = {}) {
569
+ const c = getColorHelpers(context.color);
570
+ const parsed = parseDaemonArgs(args);
571
+ const appRoot = context.appRoot || process.cwd();
572
+ const daemonCommandContext = {
573
+ appRoot,
574
+ cliEntry: context.cliEntry,
575
+ nodeExecPath: context.nodeExecPath,
576
+ };
577
+
578
+ if (parsed.options.extraArgs?.length) {
579
+ showDaemonHelp(c, daemonCommandContext);
580
+ throw new Error(`Unknown daemon arguments: ${parsed.options.extraArgs.join(' ')}`);
581
+ }
582
+
583
+ if (parsed.subcommand === 'help') {
584
+ showDaemonHelp(c, daemonCommandContext);
585
+ return;
586
+ }
587
+
588
+ if (!DAEMON_MODES.has(parsed.options.mode)) {
589
+ throw new Error(`Invalid daemon mode "${parsed.options.mode}". Use one of: auto, user, system.`);
590
+ }
591
+
592
+ ensureLinux();
593
+ ensureSystemctl();
594
+
595
+ const defaultPort = context.defaultPort || process.env.SERVER_PORT || process.env.PORT || '3001';
596
+ const defaultFrontendPort = context.defaultFrontendPort || process.env.VITE_PORT || String(DEFAULT_FRONTEND_PORT);
597
+ const configuredPort = parsed.options.serverPort || defaultPort;
598
+ const configuredFrontendPort = parsed.options.frontendPort || defaultFrontendPort;
599
+ const frontendEnabled = parsed.options.noFrontend !== true &&
600
+ (Boolean(parsed.options.frontendPort) || process.env.PIXCODE_SEPARATE_FRONTEND === '1');
601
+ const databasePath = parsed.options.databasePath || process.env.DATABASE_PATH || '';
602
+
603
+ const portNum = Number(configuredPort);
604
+ if (!Number.isInteger(portNum) || portNum < 1 || portNum > 65535) {
605
+ throw new Error(`Invalid port "${configuredPort}". Expected an integer between 1 and 65535.`);
606
+ }
607
+ const frontendPortNum = Number(configuredFrontendPort);
608
+ if (frontendEnabled && (!Number.isInteger(frontendPortNum) || frontendPortNum < 1 || frontendPortNum > 65535)) {
609
+ throw new Error(`Invalid frontend port "${configuredFrontendPort}". Expected an integer between 1 and 65535.`);
610
+ }
611
+
612
+ const userBus = probeUserBus();
613
+ const mode = resolveDaemonMode({
614
+ requestedMode: parsed.options.mode,
615
+ subcommand: parsed.subcommand,
616
+ userBusAvailable: userBus.ok,
617
+ });
618
+ const servicePath = getDaemonServicePath(mode);
619
+ const frontendServicePath = getFrontendServicePath(mode);
620
+ const effectivePort = getPortFromServiceUnit(servicePath) || portNum;
621
+ const effectiveFrontendPort = getPortFromServiceUnit(frontendServicePath) || frontendPortNum;
622
+
623
+ if (mode === 'user' && !userBus.ok) {
624
+ const installSystemCommand = buildDaemonCliCommand(
625
+ { subcommand: 'install', mode: 'system' },
626
+ daemonCommandContext
627
+ );
628
+ throw new Error(
629
+ `Could not connect to your systemd user session.\n${userBus.detail}\n` +
630
+ `Try ${c.bright(installSystemCommand)} or enable user linger: ${c.bright(`sudo loginctl enable-linger ${os.userInfo().username}`)}`
631
+ );
632
+ }
633
+
634
+ if (parsed.subcommand === 'doctor') {
635
+ const linger = probeLinger();
636
+ const userUnitInstalled = fs.existsSync(getDaemonServicePath('user'));
637
+ const userFrontendUnitInstalled = fs.existsSync(getFrontendServicePath('user'));
638
+ const systemUnitInstalled = fs.existsSync(getDaemonServicePath('system'));
639
+ const systemFrontendUnitInstalled = fs.existsSync(getFrontendServicePath('system'));
640
+ const selectedModePort = getPortFromServiceUnit(servicePath) || portNum;
641
+ const selectedModeFrontendPort = frontendEnabled
642
+ ? getPortFromServiceUnit(frontendServicePath) || frontendPortNum
643
+ : undefined;
644
+ const portReachable = await isPortReachable(selectedModePort);
645
+ const frontendPortReachable = selectedModeFrontendPort
646
+ ? await isPortReachable(selectedModeFrontendPort)
647
+ : false;
648
+ const userState = userBus.ok
649
+ ? {
650
+ backend: getServiceState('user', DAEMON_SERVICE_NAME),
651
+ frontend: getServiceState('user', FRONTEND_DAEMON_SERVICE_NAME),
652
+ }
653
+ : {
654
+ backend: { active: 'unavailable', enabled: 'unavailable' },
655
+ frontend: { active: 'unavailable', enabled: 'unavailable' },
656
+ };
657
+ const systemState = {
658
+ backend: getServiceState('system', DAEMON_SERVICE_NAME),
659
+ frontend: getServiceState('system', FRONTEND_DAEMON_SERVICE_NAME),
660
+ };
661
+ const logsResult = readLogs(mode, 50, false, [DAEMON_SERVICE_NAME, FRONTEND_DAEMON_SERVICE_NAME]);
662
+ const logsText = (logsResult.stdout || logsResult.stderr || '').trim();
663
+ const lastErrorLine = findLatestErrorLine(logsText);
664
+
665
+ console.log(`\n${c.bright('Pixcode Daemon Doctor')}\n`);
666
+ console.log(`${c.info('[INFO]')} Requested mode: ${c.bright(parsed.options.mode)}`);
667
+ console.log(`${c.info('[INFO]')} Resolved mode: ${c.bright(mode)}`);
668
+ console.log(`${c.info('[INFO]')} user-bus: ${userBus.ok ? c.ok('ok') : c.warn('unavailable')}`);
669
+ if (!userBus.ok) {
670
+ console.log(` ${c.dim(userBus.detail)}`);
671
+ }
672
+ console.log(`${c.info('[INFO]')} linger: ${c.bright(linger.value)}${linger.detail ? ` ${c.dim(`(${linger.detail})`)}` : ''}`);
673
+ console.log(`${c.info('[INFO]')} user backend: ${userUnitInstalled ? c.ok('installed') : c.warn('missing')} (${c.dim(getDaemonServicePath('user'))})`);
674
+ console.log(`${c.info('[INFO]')} user frontend: ${userFrontendUnitInstalled ? c.ok('installed') : c.warn('missing')} (${c.dim(getFrontendServicePath('user'))})`);
675
+ console.log(`${c.info('[INFO]')} system backend: ${systemUnitInstalled ? c.ok('installed') : c.warn('missing')} (${c.dim(getDaemonServicePath('system'))})`);
676
+ console.log(`${c.info('[INFO]')} system frontend:${systemFrontendUnitInstalled ? c.ok('installed') : c.warn('missing')} (${c.dim(getFrontendServicePath('system'))})`);
677
+ console.log(`${c.info('[INFO]')} user state: backend active=${c.bright(userState.backend.active)} enabled=${c.bright(userState.backend.enabled)} | frontend active=${c.bright(userState.frontend.active)} enabled=${c.bright(userState.frontend.enabled)}`);
678
+ console.log(`${c.info('[INFO]')} system state: backend active=${c.bright(systemState.backend.active)} enabled=${c.bright(systemState.backend.enabled)} | frontend active=${c.bright(systemState.frontend.active)} enabled=${c.bright(systemState.frontend.enabled)}`);
679
+ console.log(`${c.info('[INFO]')} backend port: ${c.bright(String(selectedModePort))} (${portReachable ? c.ok('reachable') : c.warn('not reachable')})`);
680
+ console.log(`${c.info('[INFO]')} frontend mode: ${frontendEnabled ? c.bright('separate Vite service') : c.bright('single backend port')}`);
681
+ if (frontendEnabled) {
682
+ console.log(`${c.info('[INFO]')} frontend port: ${c.bright(String(selectedModeFrontendPort))} (${frontendPortReachable ? c.ok('reachable') : c.warn('not reachable')})`);
683
+ }
684
+ if (lastErrorLine) {
685
+ console.log(`${c.warn('[WARN]')} Latest error: ${lastErrorLine}`);
686
+ }
687
+
688
+ console.log(`\n${c.bright('Machine Readable')}`);
689
+ console.log(`MODE_REQUESTED=${parsed.options.mode}`);
690
+ console.log(`MODE_RESOLVED=${mode}`);
691
+ console.log(`USER_BUS_OK=${userBus.ok}`);
692
+ console.log(`LINGER=${linger.value}`);
693
+ console.log(`USER_BACKEND_UNIT_INSTALLED=${userUnitInstalled}`);
694
+ console.log(`USER_FRONTEND_UNIT_INSTALLED=${userFrontendUnitInstalled}`);
695
+ console.log(`SYSTEM_BACKEND_UNIT_INSTALLED=${systemUnitInstalled}`);
696
+ console.log(`SYSTEM_FRONTEND_UNIT_INSTALLED=${systemFrontendUnitInstalled}`);
697
+ console.log(`USER_BACKEND_ACTIVE=${userState.backend.active}`);
698
+ console.log(`USER_BACKEND_ENABLED=${userState.backend.enabled}`);
699
+ console.log(`USER_FRONTEND_ACTIVE=${userState.frontend.active}`);
700
+ console.log(`USER_FRONTEND_ENABLED=${userState.frontend.enabled}`);
701
+ console.log(`SYSTEM_BACKEND_ACTIVE=${systemState.backend.active}`);
702
+ console.log(`SYSTEM_BACKEND_ENABLED=${systemState.backend.enabled}`);
703
+ console.log(`SYSTEM_FRONTEND_ACTIVE=${systemState.frontend.active}`);
704
+ console.log(`SYSTEM_FRONTEND_ENABLED=${systemState.frontend.enabled}`);
705
+ console.log(`BACKEND_PORT=${selectedModePort}`);
706
+ console.log(`BACKEND_PORT_REACHABLE=${portReachable}`);
707
+ console.log(`FRONTEND_ENABLED=${frontendEnabled}`);
708
+ console.log(`FRONTEND_PORT=${selectedModeFrontendPort ?? ''}`);
709
+ console.log(`FRONTEND_PORT_REACHABLE=${frontendPortReachable}`);
710
+ console.log(`LAST_ERROR_LINE=${JSON.stringify(lastErrorLine || '')}\n`);
711
+ return;
712
+ }
713
+
714
+ const serviceDefs = [{ servicePath }];
715
+ if (frontendEnabled) {
716
+ serviceDefs.push({ servicePath: frontendServicePath });
717
+ }
718
+
719
+ switch (parsed.subcommand) {
720
+ case 'install': {
721
+ if (parsed.options.mode === 'auto' && mode === 'system' && !userBus.ok) {
722
+ console.log(`${c.warn('[WARN]')} User mode is unavailable; auto mode is falling back to system mode.`);
723
+ }
724
+
725
+ try {
726
+ fs.mkdirSync(path.dirname(servicePath), { recursive: true });
727
+ if (frontendEnabled) {
728
+ fs.mkdirSync(path.dirname(frontendServicePath), { recursive: true });
729
+ }
730
+
731
+ const backendUnitContent = buildDaemonServiceUnit({
732
+ appRoot,
733
+ serverPort: portNum,
734
+ databasePath,
735
+ nodeExecPath: context.nodeExecPath,
736
+ cliEntry: context.cliEntry,
737
+ });
738
+ fs.writeFileSync(servicePath, backendUnitContent, 'utf8');
739
+
740
+ if (frontendEnabled) {
741
+ const frontendUnitContent = buildFrontendDaemonServiceUnit({
742
+ appRoot,
743
+ frontendPort: frontendPortNum,
744
+ nodeExecPath: context.nodeExecPath,
745
+ cliEntry: context.cliEntry,
746
+ });
747
+ fs.writeFileSync(frontendServicePath, frontendUnitContent, 'utf8');
748
+ }
749
+ } catch (fileError) {
750
+ if (mode === 'system' && (fileError.code === 'EACCES' || fileError.code === 'EPERM')) {
751
+ const installHint = buildDaemonCliCommand(
752
+ {
753
+ subcommand: 'install',
754
+ mode: 'system',
755
+ extraArgs: frontendEnabled
756
+ ? ['--port', String(portNum), '--frontend-port', String(frontendPortNum)]
757
+ : ['--port', String(portNum), '--single-port'],
758
+ },
759
+ daemonCommandContext
760
+ );
761
+ throw new Error(
762
+ `Permission denied writing daemon unit files (${servicePath}, ${frontendServicePath}). ` +
763
+ `Try: ${installHint}`
764
+ );
765
+ }
766
+ throw fileError;
767
+ }
768
+
769
+ runSystemctl(mode, ['daemon-reload']);
770
+ runSystemctl(mode, ['enable', '--now', DAEMON_SERVICE_NAME]);
771
+ if (frontendEnabled) {
772
+ runSystemctl(mode, ['enable', '--now', FRONTEND_DAEMON_SERVICE_NAME]);
773
+ } else {
774
+ runSystemctl(mode, ['stop', FRONTEND_DAEMON_SERVICE_NAME], { allowFailure: true });
775
+ runSystemctl(mode, ['disable', FRONTEND_DAEMON_SERVICE_NAME], { allowFailure: true });
776
+ }
777
+
778
+ if (mode === 'user') {
779
+ const lingerResult = runCommand('loginctl', ['enable-linger', os.userInfo().username]);
780
+ if (lingerResult.status !== 0) {
781
+ console.log(`${c.warn('[WARN]')} Could not enable linger automatically.`);
782
+ console.log(` ${c.dim(extractCommandError(lingerResult, 'Unknown linger error'))}`);
783
+ console.log(` ${c.tip('[TIP]')} Run with sufficient privileges: ${c.bright(`sudo loginctl enable-linger ${os.userInfo().username}`)}`);
784
+ }
785
+ }
786
+
787
+ const installedPort = getPortFromServiceUnit(servicePath) || portNum;
788
+ await healthCheckOrThrow(mode, DAEMON_SERVICE_NAME, installedPort, c);
789
+ const installedFrontendPort = frontendEnabled
790
+ ? getPortFromServiceUnit(frontendServicePath) || frontendPortNum
791
+ : undefined;
792
+ if (frontendEnabled && installedFrontendPort) {
793
+ await healthCheckOrThrow(mode, FRONTEND_DAEMON_SERVICE_NAME, installedFrontendPort, c);
794
+ }
795
+
796
+ const backendState = getServiceState(mode, DAEMON_SERVICE_NAME);
797
+ const frontendState = frontendEnabled
798
+ ? getServiceState(mode, FRONTEND_DAEMON_SERVICE_NAME)
799
+ : { active: 'disabled', enabled: 'disabled' };
800
+ console.log(`\n${c.ok('')} Daemon installed and started.`);
801
+ console.log(` Mode: ${c.bright(mode)}`);
802
+ console.log(` Backend Unit: ${c.dim(servicePath)}`);
803
+ console.log(` Frontend Mode: ${c.bright(frontendEnabled ? 'separate service' : 'single backend port')}`);
804
+ console.log(` Backend Active: ${c.bright(backendState.active)}`);
805
+ console.log(` Backend Enabled:${c.bright(backendState.enabled)}`);
806
+ console.log(` Backend URL: ${c.bright(`http://localhost:${installedPort}`)}`);
807
+ if (frontendEnabled) {
808
+ console.log(` Frontend Unit: ${c.dim(frontendServicePath)}`);
809
+ console.log(` Frontend Active:${c.bright(frontendState.active)}`);
810
+ console.log(` Frontend Enabled:${c.bright(frontendState.enabled)}`);
811
+ console.log(` Frontend URL: ${c.bright(`http://localhost:${installedFrontendPort}`)}`);
812
+ }
813
+ console.log('');
814
+ if (mode === 'system') {
815
+ const statusCommand = buildDaemonCliCommand(
816
+ { subcommand: 'status', mode: 'system' },
817
+ daemonCommandContext
818
+ );
819
+ const stopCommand = buildDaemonCliCommand(
820
+ { subcommand: 'stop', mode: 'system' },
821
+ daemonCommandContext
822
+ );
823
+ const logsCommand = buildDaemonCliCommand(
824
+ { subcommand: 'logs', mode: 'system' },
825
+ daemonCommandContext
826
+ );
827
+ console.log(`${c.ok('[OK]')} System daemon is active.`);
828
+ console.log(`${c.info('[INFO]')} Backend health: ${c.bright(`http://localhost:${installedPort}/health`)}`);
829
+ console.log(`${c.info('[INFO]')} UI: ${c.bright(`http://localhost:${installedPort}/`)}`);
830
+ console.log(`${c.info('[INFO]')} Status: ${c.bright(statusCommand)}`);
831
+ console.log(`${c.info('[INFO]')} Stop: ${c.bright(stopCommand)}`);
832
+ console.log(`${c.info('[INFO]')} Logs: ${c.bright(logsCommand)}\n`);
833
+ } else {
834
+ const linger = probeLinger();
835
+ const statusCommand = buildDaemonCliCommand(
836
+ { subcommand: 'status', mode: 'user' },
837
+ daemonCommandContext
838
+ );
839
+ const stopCommand = buildDaemonCliCommand(
840
+ { subcommand: 'stop', mode: 'user' },
841
+ daemonCommandContext
842
+ );
843
+ const logsCommand = buildDaemonCliCommand(
844
+ { subcommand: 'logs', mode: 'user' },
845
+ daemonCommandContext
846
+ );
847
+ console.log(`${c.ok('[OK]')} User daemon is active.`);
848
+ console.log(`${c.info('[INFO]')} Backend health: ${c.bright(`http://localhost:${installedPort}/health`)}`);
849
+ console.log(`${c.info('[INFO]')} UI: ${c.bright(`http://localhost:${installedPort}/`)}`);
850
+ console.log(`${c.info('[INFO]')} Status: ${c.bright(statusCommand)}`);
851
+ console.log(`${c.info('[INFO]')} Stop: ${c.bright(stopCommand)}`);
852
+ console.log(`${c.info('[INFO]')} Logs: ${c.bright(logsCommand)}`);
853
+ if (linger.value !== 'yes') {
854
+ console.log(`${c.tip('[TIP]')} Enable linger for reboot/login persistence: ${c.bright(`sudo loginctl enable-linger ${os.userInfo().username}`)}\n`);
855
+ } else {
856
+ console.log('');
857
+ }
858
+ }
859
+ break;
860
+ }
861
+
862
+ case 'start':
863
+ runSystemctl(mode, ['start', DAEMON_SERVICE_NAME]);
864
+ if (frontendEnabled) runSystemctl(mode, ['start', FRONTEND_DAEMON_SERVICE_NAME]);
865
+ await healthCheckOrThrow(mode, DAEMON_SERVICE_NAME, effectivePort, c);
866
+ if (frontendEnabled) await healthCheckOrThrow(mode, FRONTEND_DAEMON_SERVICE_NAME, effectiveFrontendPort, c);
867
+ console.log(`${c.ok('[OK]')} Pixcode service started.`);
868
+ break;
869
+
870
+ case 'stop':
871
+ runSystemctl(mode, ['stop', FRONTEND_DAEMON_SERVICE_NAME], { allowFailure: true });
872
+ runSystemctl(mode, ['stop', DAEMON_SERVICE_NAME]);
873
+ console.log(`${c.ok('[OK]')} Pixcode service stopped (auto-start remains enabled).`);
874
+ break;
875
+
876
+ case 'restart':
877
+ runSystemctl(mode, ['restart', DAEMON_SERVICE_NAME]);
878
+ if (frontendEnabled) runSystemctl(mode, ['restart', FRONTEND_DAEMON_SERVICE_NAME]);
879
+ await healthCheckOrThrow(mode, DAEMON_SERVICE_NAME, effectivePort, c);
880
+ if (frontendEnabled) await healthCheckOrThrow(mode, FRONTEND_DAEMON_SERVICE_NAME, effectiveFrontendPort, c);
881
+ console.log(`${c.ok('[OK]')} Pixcode service restarted.`);
882
+ break;
883
+
884
+ case 'enable':
885
+ runSystemctl(mode, ['enable', DAEMON_SERVICE_NAME]);
886
+ if (frontendEnabled) runSystemctl(mode, ['enable', FRONTEND_DAEMON_SERVICE_NAME]);
887
+ console.log(`${c.ok('[OK]')} Pixcode service enabled for auto-start.`);
888
+ break;
889
+
890
+ case 'disable':
891
+ runSystemctl(mode, ['disable', DAEMON_SERVICE_NAME]);
892
+ runSystemctl(mode, ['disable', FRONTEND_DAEMON_SERVICE_NAME]);
893
+ console.log(`${c.ok('[OK]')} Pixcode service disabled for auto-start.`);
894
+ break;
895
+
896
+ case 'logs': {
897
+ const logsResult = readLogs(mode, 100, true, [DAEMON_SERVICE_NAME, FRONTEND_DAEMON_SERVICE_NAME]);
898
+ if (logsResult.status !== 0) {
899
+ throw new Error(extractCommandError(logsResult, 'Unable to read daemon logs'));
900
+ }
901
+ break;
902
+ }
903
+
904
+ case 'uninstall': {
905
+ runSystemctl(mode, ['stop', FRONTEND_DAEMON_SERVICE_NAME], { allowFailure: true });
906
+ runSystemctl(mode, ['disable', FRONTEND_DAEMON_SERVICE_NAME], { allowFailure: true });
907
+ runSystemctl(mode, ['stop', DAEMON_SERVICE_NAME], { allowFailure: true });
908
+ runSystemctl(mode, ['disable', DAEMON_SERVICE_NAME], { allowFailure: true });
909
+
910
+ for (const def of serviceDefs) {
911
+ if (!fs.existsSync(def.servicePath)) continue;
912
+ try {
913
+ fs.unlinkSync(def.servicePath);
914
+ } catch (unlinkError) {
915
+ if (mode === 'system' && (unlinkError.code === 'EACCES' || unlinkError.code === 'EPERM')) {
916
+ const uninstallHint = buildDaemonCliCommand(
917
+ { subcommand: 'uninstall', mode: 'system' },
918
+ daemonCommandContext
919
+ );
920
+ throw new Error(`Permission denied removing ${def.servicePath}. Try: ${uninstallHint}`);
921
+ }
922
+ throw unlinkError;
923
+ }
924
+ }
925
+ runSystemctl(mode, ['daemon-reload'], { allowFailure: true });
926
+ console.log(`${c.ok('[OK]')} Backend and frontend daemons uninstalled.`);
927
+ break;
928
+ }
929
+
930
+ case 'status':
931
+ default: {
932
+ const backendState = getServiceState(mode, DAEMON_SERVICE_NAME);
933
+ const frontendState = getServiceState(mode, FRONTEND_DAEMON_SERVICE_NAME);
934
+ const backendUnitExists = fs.existsSync(servicePath);
935
+ const frontendUnitExists = fs.existsSync(frontendServicePath);
936
+ const selectedPort = getPortFromServiceUnit(servicePath) || portNum;
937
+ const selectedFrontendPort = frontendEnabled
938
+ ? getPortFromServiceUnit(frontendServicePath) || frontendPortNum
939
+ : undefined;
940
+ console.log(`\n${c.bright('Pixcode Daemon Status')}\n`);
941
+ console.log(`${c.info('[INFO]')} Mode: ${c.bright(mode)} ${parsed.options.mode === 'auto' ? c.dim('(resolved from auto)') : ''}`);
942
+ console.log(`${c.info('[INFO]')} Backend Unit: ${c.dim(servicePath)} ${backendUnitExists ? c.ok('[OK]') : c.warn('[MISSING]')}`);
943
+ console.log(`${c.info('[INFO]')} Backend Active: ${c.bright(backendState.active)}`);
944
+ console.log(`${c.info('[INFO]')} Backend Enabled:${c.bright(backendState.enabled)}`);
945
+ console.log(`${c.info('[INFO]')} Backend Port: ${c.bright(String(selectedPort))}`);
946
+ console.log(`${c.info('[INFO]')} UI URL: ${c.bright(`http://localhost:${selectedPort}/`)}`);
947
+ console.log(`${c.info('[INFO]')} Frontend Mode: ${frontendEnabled ? c.bright('separate Vite service') : c.bright('single backend port')}`);
948
+ if (frontendEnabled) {
949
+ console.log(`${c.info('[INFO]')} Frontend Unit: ${c.dim(frontendServicePath)} ${frontendUnitExists ? c.ok('[OK]') : c.warn('[MISSING]')}`);
950
+ console.log(`${c.info('[INFO]')} Frontend Active:${c.bright(frontendState.active)}`);
951
+ console.log(`${c.info('[INFO]')} Frontend Enabled:${c.bright(frontendState.enabled)}`);
952
+ console.log(`${c.info('[INFO]')} Frontend Port: ${c.bright(String(selectedFrontendPort))}`);
953
+ } else if (frontendUnitExists) {
954
+ console.log(`${c.info('[INFO]')} Legacy Frontend:${c.dim(frontendServicePath)} active=${c.bright(frontendState.active)} enabled=${c.bright(frontendState.enabled)}`);
955
+ }
956
+ console.log('');
957
+ }
958
+ }
959
+ }