aiservermanager 0.6.7 → 0.7.0

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 (33) hide show
  1. package/backend/dist/files/grantLogonServiceRight.ps1 +171 -0
  2. package/backend/dist/files/winsw/LICENSE-WinSW.txt +21 -0
  3. package/backend/dist/files/winsw/WinSW-x64.exe +0 -0
  4. package/backend/dist/helpers/ExecTools.js +22 -5
  5. package/backend/dist/helpers/ExecTools.js.map +1 -1
  6. package/backend/dist/helpers/ServerIdentity.js +64 -0
  7. package/backend/dist/helpers/ServerIdentity.js.map +1 -0
  8. package/backend/dist/index.js +18 -4
  9. package/backend/dist/index.js.map +1 -1
  10. package/backend/dist/models/ServiceConfig.js +54 -6
  11. package/backend/dist/models/ServiceConfig.js.map +1 -1
  12. package/backend/dist/routes/serviceRoutes.js +11 -3
  13. package/backend/dist/routes/serviceRoutes.js.map +1 -1
  14. package/backend/dist/routes/systemRoutes.js +3 -1
  15. package/backend/dist/routes/systemRoutes.js.map +1 -1
  16. package/backend/dist/services/controllers/systemctlController.js +29 -3
  17. package/backend/dist/services/controllers/systemctlController.js.map +1 -1
  18. package/backend/dist/services/controllers/windowsServiceController.js +419 -93
  19. package/backend/dist/services/controllers/windowsServiceController.js.map +1 -1
  20. package/backend/dist/services/helpers/winswConfig.js +248 -0
  21. package/backend/dist/services/helpers/winswConfig.js.map +1 -0
  22. package/backend/dist/services/helpers/winswLog.js +28 -0
  23. package/backend/dist/services/helpers/winswLog.js.map +1 -0
  24. package/backend/dist/services/serviceConfigController.js +25 -6
  25. package/backend/dist/services/serviceConfigController.js.map +1 -1
  26. package/backend/dist/services/serviceManager.js +11 -4
  27. package/backend/dist/services/serviceManager.js.map +1 -1
  28. package/backend/public/browser/{chunk-34LU6STA.js → chunk-P5KEWYS5.js} +1 -1
  29. package/backend/public/browser/chunk-QZRO6WVW.js +4 -0
  30. package/backend/public/browser/index.html +1 -1
  31. package/backend/public/browser/{main-BKNECZIV.js → main-2RRTWG2U.js} +48 -48
  32. package/package.json +1 -1
  33. package/backend/public/browser/chunk-JGNPKRLU.js +0 -4
@@ -1,53 +1,151 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  Object.defineProperty(exports, "__esModule", { value: true });
3
36
  exports.WindowsServiceController = void 0;
37
+ const fs = __importStar(require("fs"));
38
+ const os = __importStar(require("os"));
39
+ const path = __importStar(require("path"));
4
40
  const ExecTools_1 = require("../../helpers/ExecTools");
5
- /** Manage Windows services via sc.exe. */
41
+ const ServerIdentity_1 = require("../../helpers/ServerIdentity");
42
+ const winswConfig_1 = require("../helpers/winswConfig");
43
+ const winswLog_1 = require("../helpers/winswLog");
44
+ const SC = "sc.exe";
45
+ /** Per-service WinSW host directories: ~/.config/aiservermanager/winsw/<name>/. */
46
+ const WINSW_ROOT = path.join(process.env.HOME ?? "", ".config", "aiservermanager", "winsw");
47
+ /**
48
+ * Packaged WinSW binary. From src/services/controllers (ts-node-dev) and from
49
+ * dist/services/controllers (build copies src/files to dist/files) this
50
+ * resolves to files/winsw/ inside the same tree the code runs from.
51
+ * Override with AISERVERMANAGER_WINSW when the binary lives elsewhere.
52
+ */
53
+ const WINSW_BINARY = process.env.AISERVERMANAGER_WINSW ?? path.resolve(__dirname, "../../files/winsw/WinSW-x64.exe");
54
+ /** Grants "Log on as a service" to a service account (see grantLogonServiceRight.ps1). */
55
+ const GRANT_RIGHT_SCRIPT = path.resolve(__dirname, "../../files/grantLogonServiceRight.ps1");
56
+ /** How many trailing bytes of a log file to read when tailing the journal. */
57
+ const JOURNAL_TAIL_BYTES = 256 * 1024;
58
+ /**
59
+ * Explain a rejected service account at registration. Install has already given
60
+ * the account its logon right by this point, so 1069/1385 here means the SCM was
61
+ * handed a password it does not accept for that account.
62
+ */
63
+ function serviceAccountHint(account, output) {
64
+ if (!account)
65
+ return "";
66
+ if (!/1069|1385|logon|password|account name|privileged account/i.test(output))
67
+ return "";
68
+ const fullName = account.domain ? `${account.domain}\\${account.user}` : account.user;
69
+ return (` — the Service Control Manager did not accept the password typed for "${fullName}". ` +
70
+ `Install it again with the current password. If the account name is wrong, ` +
71
+ `correct it in the service settings first.`);
72
+ }
73
+ /**
74
+ * Explain a refused start: the account registered under the service could not be
75
+ * logged on, which happens when its password changed after the registration or
76
+ * when it lost the right that install granted it (a Group Policy refresh does that).
77
+ */
78
+ function logonFailureHint(action, output) {
79
+ if (action !== "start")
80
+ return "";
81
+ if (!/1069|1385/i.test(output))
82
+ return "";
83
+ return (` — the Service Control Manager cannot log on as the account this service is registered with. ` +
84
+ `Its password changed since the registration, or it lost the "Log on as a service" right. ` +
85
+ `Use Reinstall and type the current password, or grant the right in secpol.msc ` +
86
+ `(Local Policies → User Rights Assignment); the System log event says which.`);
87
+ }
88
+ /**
89
+ * Manage Windows services.
90
+ *
91
+ * Real OS services are queried and controlled through sc.exe. Custom services
92
+ * from configs are installed through WinSW (Windows Service Wrapper) because
93
+ * the Service Control Manager only accepts an executable that reports its
94
+ * status — a plain program or a .cmd launcher (ComfyUI, llama-server, …) is
95
+ * not one, and `sc create` for it yields a service that never starts.
96
+ */
6
97
  class WindowsServiceController {
7
- static SC = "sc.exe";
8
- _isAdmin = null;
9
98
  async isAvailable() {
10
99
  return process.platform === "win32";
11
100
  }
12
- /** Check if the current process is running as Administrator. */
13
- async checkIsAdmin() {
14
- if (this._isAdmin !== null)
15
- return this._isAdmin;
16
- const { stdout } = await ExecTools_1.ExecTools.safeExec("[bool]([Security.Principal.WindowsPrincipal]" +
17
- "[Security.Principal.WindowsIdentity]::GetCurrent())" +
18
- ".IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)");
19
- this._isAdmin = stdout.trim().toUpperCase() === "TRUE";
20
- return this._isAdmin;
101
+ serviceDir(name) {
102
+ return path.join(WINSW_ROOT, name);
103
+ }
104
+ /** WinSW derives the config path from its own executable name, hence per-service copies. */
105
+ wrapperBinary(name) {
106
+ return path.join(this.serviceDir(name), `${name}.exe`);
107
+ }
108
+ wrapperConfig(name) {
109
+ return path.join(this.serviceDir(name), `${name}.xml`);
110
+ }
111
+ /** Refuse to run sc.exe actions that an unelevated token is denied anyway. */
112
+ async privilegeFailure(name, action) {
113
+ const identity = await ServerIdentity_1.ServerIdentity.describe();
114
+ return {
115
+ name,
116
+ running: false,
117
+ enabled: false,
118
+ installed: true,
119
+ error: `Backend is not running as Administrator (PID ${identity.pid}, ${identity.host}:${identity.port}). ` +
120
+ `Stop every backend instance and start one elevated — port ${identity.port} may still be held by ` +
121
+ `an older instance. Cannot ${action} "${name}".`,
122
+ };
21
123
  }
22
124
  async getStatus(name) {
23
- // sc.exe queryex gives STATE (RUNNING/STOPPED), START_TYPE (AUTO/DEMAND/DISABLED)
24
- const { stdout, stderr } = await ExecTools_1.ExecTools.safeExec(`${WindowsServiceController.SC} queryex "${name}"`);
125
+ // sc.exe queryex gives STATE and PID; the start type comes from Get-Service below.
126
+ const { stdout, stderr } = await ExecTools_1.ExecTools.safeExec(`${SC} queryex "${name}"`);
25
127
  const lines = stdout.split("\n");
26
128
  let running = false;
27
- let enabled = false;
28
129
  let pid;
29
130
  let foundState = false;
30
131
  for (const line of lines) {
31
132
  const trimmed = line.trim();
32
- // STATE line: " STATE: 4 RUNNING" or " STATE: 1 STOPPED"
33
- if (trimmed.startsWith("STATE:")) {
133
+ // sc.exe pads the field name, so the value sits after the colon of
134
+ // " STATE : 1 STOPPED" / " PID : 0".
135
+ const colon = trimmed.indexOf(":");
136
+ if (colon < 0)
137
+ continue;
138
+ const field = trimmed.slice(0, colon).trim().toUpperCase();
139
+ const value = trimmed.slice(colon + 1).trim().toUpperCase();
140
+ if (field === "STATE") {
34
141
  foundState = true;
35
- const parts = trimmed.split(/\s+/);
36
- const state = parts[parts.length - 1]?.toUpperCase();
37
- running = state === "RUNNING";
38
- }
39
- // START_TYPE line: " START_TYPE: 2 AUTO_START"
40
- if (trimmed.startsWith("START_TYPE:")) {
41
- const parts = trimmed.split(/\s+/);
42
- const startType = parts[parts.length - 1]?.toUpperCase();
43
- enabled = startType !== "DISABLED";
142
+ running = value.includes("RUNNING");
44
143
  }
45
- // PID line: " PID: 1234"
46
- if (trimmed.startsWith("PID:")) {
47
- const pidStr = trimmed.split(/\s+/)[1];
48
- if (pidStr) {
49
- pid = parseInt(pidStr, 10);
50
- }
144
+ // A service without a process reports PID 0, which is no process to show.
145
+ if (field === "PID") {
146
+ const parsed = parseInt(value, 10);
147
+ if (Number.isFinite(parsed) && parsed > 0)
148
+ pid = parsed;
51
149
  }
52
150
  }
53
151
  // Fallback: if sc.exe query failed (service not found), check with Get-Service
@@ -58,22 +156,22 @@ class WindowsServiceController {
58
156
  running = status === "RUNNING";
59
157
  foundState = true;
60
158
  }
61
- if (foundState) {
62
- const startModeResult = await ExecTools_1.ExecTools.safeExec(`Get-Service "${name}" -ErrorAction SilentlyContinue | Select-Object -ExpandProperty StartType`);
63
- const startMode = startModeResult.stdout.trim().toUpperCase();
64
- if (startMode) {
65
- enabled = startMode !== "DISABLED";
66
- }
67
- }
68
159
  }
69
160
  if (!foundState) {
70
161
  const errorMsg = stderr.trim() ? `Service "${name}" not found: ${stderr.trim()}` : `Service "${name}" not found`;
71
162
  return { name, running: false, enabled: false, installed: false, error: errorMsg };
72
163
  }
164
+ // "enabled" here means "starts on boot", the systemd meaning: only Automatic does.
165
+ // Manual is what install() registers and what "disable" leaves behind, and a service
166
+ // in that state is startable by hand but boots on its own never.
167
+ const startModeResult = await ExecTools_1.ExecTools.safeExec(`Get-Service "${name}" -ErrorAction SilentlyContinue | Select-Object -ExpandProperty StartType`);
168
+ const enabled = startModeResult.stdout.trim().toUpperCase() === "AUTOMATIC";
73
169
  return { name, running, enabled, installed: true, pid };
74
170
  }
75
171
  async perform(name, action) {
76
- const SC = WindowsServiceController.SC;
172
+ if (!(await ServerIdentity_1.ServerIdentity.isPrivileged())) {
173
+ return this.privilegeFailure(name, action);
174
+ }
77
175
  let cmd;
78
176
  switch (action) {
79
177
  case "start":
@@ -86,19 +184,23 @@ class WindowsServiceController {
86
184
  cmd = `${SC} config "${name}" start= auto`;
87
185
  break;
88
186
  case "disable":
89
- cmd = `${SC} config "${name}" start= disabled`;
187
+ // Manual, not "disabled": like `systemctl disable`, this only takes the autostart
188
+ // away. A service set to Disabled cannot be started at all (error 1058), so the
189
+ // Start button in the dashboard would be dead until the service is enabled again.
190
+ cmd = `${SC} config "${name}" start= demand`;
90
191
  break;
91
192
  default:
92
193
  throw new Error(`Unknown action: ${action}`);
93
194
  }
94
195
  const result = await ExecTools_1.ExecTools.safeExecWithCode(cmd);
95
196
  if (result.exitCode !== 0) {
197
+ const output = result.stderr.trim() || result.stdout.trim();
96
198
  return {
97
199
  name,
98
200
  running: false,
99
201
  enabled: false,
100
202
  installed: true,
101
- error: `${SC} ${action} failed (code ${result.exitCode}): ${result.stderr.trim() || result.stdout.trim()}`,
203
+ error: `${SC} ${action} failed (code ${result.exitCode}): ${output}${logonFailureHint(action, output)}`,
102
204
  };
103
205
  }
104
206
  // After start/stop, give the service a moment to transition
@@ -108,70 +210,192 @@ class WindowsServiceController {
108
210
  const status = await this.getStatus(name);
109
211
  // After "start", verify the service is actually running
110
212
  if (action === "start" && !status.running && !status.error) {
111
- status.error = `sc.exe start returned success, but "${name}" is not running`;
213
+ status.error = `${SC} start returned success, but "${name}" is not running`;
112
214
  }
113
215
  return status;
114
216
  }
115
217
  /**
116
- * Persist environment variables for a Windows service in
117
- * HKLM\SYSTEM\CurrentControlSet\Services\<name>\Environment (REG_MULTI_SZ).
118
- * The Service Control Manager merges these into the service process
119
- * environment when the service starts. Returns an error message, or null.
218
+ * Drop the legacy HKLM\..\Services\<name>\Environment value written by older
219
+ * versions of this controller. Variables now reach the process through the
220
+ * WinSW <env> elements, and a leftover key would keep being merged in by the
221
+ * Service Control Manager after a reinstall.
120
222
  */
121
- async setServiceEnvironment(name, environment) {
122
- const entries = Object.entries(environment ?? {})
123
- .filter(([key]) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
124
- .map(([key, value]) => `${key}=${value.replace(/[\r\n]+/g, " ")}`);
125
- const regKey = `HKLM\\SYSTEM\\CurrentControlSet\\Services\\${name}`;
126
- if (entries.length === 0) {
127
- // No variables — drop a stale value so the service does not inherit old env (best-effort)
128
- await ExecTools_1.ExecTools.safeExecWithCode(`reg delete "${regKey}" /v Environment /f`);
223
+ async clearLegacyEnvironmentKey(name) {
224
+ await ExecTools_1.ExecTools.safeExecWithCode(`reg delete "HKLM\\SYSTEM\\CurrentControlSet\\Services\\${name}" /v Environment /f`);
225
+ }
226
+ /** Copy the packaged WinSW binary next to the service config under the service's own name. */
227
+ placeWrapperBinary(name) {
228
+ const target = this.wrapperBinary(name);
229
+ fs.mkdirSync(path.dirname(target), { recursive: true });
230
+ if (fs.existsSync(target)) {
231
+ fs.rmSync(target, { force: true });
232
+ }
233
+ // A hard link keeps the 18 MB binary from being duplicated per service.
234
+ try {
235
+ fs.linkSync(WINSW_BINARY, target);
129
236
  return null;
130
237
  }
131
- const result = await ExecTools_1.ExecTools.safeExecWithCode(`reg add "${regKey}" /v Environment /t REG_MULTI_SZ /d "${entries.join("\\0")}" /f`);
132
- return result.exitCode === 0 ? null : `Failed to set environment variables: ${result.stderr.trim()}`;
238
+ catch (err) {
239
+ try {
240
+ fs.copyFileSync(WINSW_BINARY, target);
241
+ return null;
242
+ }
243
+ catch (copyErr) {
244
+ return `Failed to place WinSW host at ${target}: ${copyErr instanceof Error ? copyErr.message : String(copyErr)} (hard link failed: ${err instanceof Error ? err.message : String(err)})`;
245
+ }
246
+ }
133
247
  }
248
+ /**
249
+ * Install a custom service as a WinSW-hosted Windows service. Replaces an
250
+ * existing registration (including one made by an older version of this
251
+ * controller), so calling it again re-applies the config.
252
+ */
134
253
  async install(name, execStart, options) {
135
- const SC = WindowsServiceController.SC;
136
- const isAdmin = await this.checkIsAdmin();
137
- if (!isAdmin) {
254
+ if (!(await ServerIdentity_1.ServerIdentity.isPrivileged())) {
255
+ return {
256
+ ...(await this.privilegeFailure(name, "install")),
257
+ installed: false,
258
+ };
259
+ }
260
+ if (!fs.existsSync(WINSW_BINARY)) {
138
261
  return {
139
262
  name,
140
263
  running: false,
141
264
  enabled: false,
142
265
  installed: false,
143
- error: "Server is not running as Administrator. Restart with elevated privileges to install system services.",
266
+ error: `WinSW host is missing at ${WINSW_BINARY}. ` +
267
+ `Fetch it with "pwsh scripts/get-winsw.ps1" or point AISERVERMANAGER_WINSW at a WinSW executable.`,
144
268
  };
145
269
  }
146
- // Persist environment variables before (re)creating the service
147
- const envError = await this.setServiceEnvironment(name, options?.environment);
148
- if (envError) {
149
- return { name, running: false, enabled: false, installed: false, error: envError };
150
- }
151
- // sc.exe create with demand start (disabled) — install only, no auto-start
152
- const createResult = await ExecTools_1.ExecTools.safeExecWithCode(`${SC} create "${name}" binPath= "${execStart}" start= demand`);
153
- if (createResult.exitCode !== 0) {
154
- // Service may already exist — try sc.exe config to update
155
- const configResult = await ExecTools_1.ExecTools.safeExecWithCode(`${SC} config "${name}" binPath= "${execStart}" start= demand`);
156
- if (configResult.exitCode !== 0) {
157
- return {
158
- name,
159
- running: false,
160
- enabled: false,
161
- installed: false,
162
- error: `Failed to install service: ${configResult.stderr.trim()}`,
163
- };
270
+ const executable = (options?.executable ?? execStart).trim();
271
+ const args = options?.args ?? [];
272
+ const workingDirectory = (0, winswConfig_1.resolveWorkingDirectory)(options?.workingDirectory, executable);
273
+ if (!fs.existsSync(workingDirectory)) {
274
+ return {
275
+ name,
276
+ running: false,
277
+ enabled: false,
278
+ installed: false,
279
+ error: `Working directory "${workingDirectory}" does not exist — set unit.cwd= in the service config.`,
280
+ };
281
+ }
282
+ const { account, error: accountError } = (0, winswConfig_1.parseServiceAccount)(options?.user, options?.runAsPassword);
283
+ if (accountError) {
284
+ return { name, running: false, enabled: false, installed: false, error: accountError };
285
+ }
286
+ // Registering the service does not make the account allowed to log on as one,
287
+ // and without that right every start fails with 1069 — so get it out of the
288
+ // way before touching the registration.
289
+ if (account) {
290
+ const rightError = await this.grantLogonRight(account);
291
+ if (rightError) {
292
+ return { name, running: false, enabled: false, installed: false, error: rightError };
164
293
  }
165
- return this.getStatus(name);
166
294
  }
167
- return this.getStatus(name);
295
+ const priorStatus = await this.getStatus(name);
296
+ if (priorStatus.installed) {
297
+ const removed = await this.removeRegistration(name);
298
+ if (!removed.ok) {
299
+ return { ...priorStatus, error: removed.error };
300
+ }
301
+ }
302
+ const dir = this.serviceDir(name);
303
+ fs.mkdirSync(dir, { recursive: true });
304
+ const spec = {
305
+ id: name,
306
+ displayName: name,
307
+ description: `ai server manager service (${name})`,
308
+ executable,
309
+ args,
310
+ workingDirectory,
311
+ environment: options?.environment,
312
+ serviceAccount: account,
313
+ stopCommand: options?.stopCommand,
314
+ restart: options?.restart,
315
+ logDirectory: dir,
316
+ };
317
+ const xml = (0, winswConfig_1.buildWinSwXml)(spec);
318
+ try {
319
+ fs.writeFileSync(this.wrapperConfig(name), xml, "utf-8");
320
+ }
321
+ catch (err) {
322
+ return {
323
+ name,
324
+ running: false,
325
+ enabled: false,
326
+ installed: false,
327
+ error: `Failed to write WinSW config: ${err instanceof Error ? err.message : String(err)}`,
328
+ };
329
+ }
330
+ const placementError = this.placeWrapperBinary(name);
331
+ if (placementError) {
332
+ return { name, running: false, enabled: false, installed: false, error: placementError };
333
+ }
334
+ await this.clearLegacyEnvironmentKey(name);
335
+ const installResult = await ExecTools_1.ExecTools.safeExecFileWithCode(this.wrapperBinary(name), ["install"], { timeout: 60_000, cwd: dir });
336
+ if (installResult.exitCode !== 0) {
337
+ const output = installResult.stderr.trim() || installResult.stdout.trim();
338
+ return {
339
+ name,
340
+ running: false,
341
+ enabled: false,
342
+ installed: false,
343
+ error: `WinSW install failed (code ${installResult.exitCode}): ${output}${serviceAccountHint(account, output)}`,
344
+ };
345
+ }
346
+ const status = await this.getStatus(name);
347
+ if (!status.installed) {
348
+ return { ...status, installed: false, error: `WinSW installed "${name}", but the service is not registered` };
349
+ }
350
+ this.dropAccountPassword(spec);
351
+ return status;
352
+ }
353
+ /**
354
+ * Give a run-as account the "Log on as a service" right. The Service Control
355
+ * Manager refuses to log the account on (start fails with 1069, System log
356
+ * event 7041) until it has the right, and registering the service does not
357
+ * grant it. The account is passed to the script through the environment, so
358
+ * neither the name nor a password ever appears in a command line.
359
+ */
360
+ async grantLogonRight(account) {
361
+ // COMPUTERNAME is the NetBIOS name the account API wants; os.hostname() can
362
+ // return a DNS alias that resolves to nothing.
363
+ const identity = (0, winswConfig_1.logonRightIdentity)(account, process.env.COMPUTERNAME ?? os.hostname());
364
+ const { stdout, stderr } = await ExecTools_1.ExecTools.safeExecPs1(GRANT_RIGHT_SCRIPT, {
365
+ timeout: 60_000,
366
+ env: { SM_ACCOUNT_DOMAIN: identity.domain ?? "", SM_ACCOUNT_NAME: identity.user },
367
+ });
368
+ const output = (stdout.trim() || stderr.trim()).trim();
369
+ if (output.startsWith("OK"))
370
+ return undefined;
371
+ const fullName = identity.domain ? `${identity.domain}\\${identity.user}` : identity.user;
372
+ return (output +
373
+ ` — "${fullName}" cannot be given the "Log on as a service" right, so the service ` +
374
+ `could never start. Grant the right in secpol.msc (Local Policies → User Rights ` +
375
+ `Assignment) or run the backend elevated and install again.`);
376
+ }
377
+ /**
378
+ * Rewrite the wrapper config without the account password once the service is
379
+ * registered: the Service Control Manager keeps its own protected copy from
380
+ * that point on, so nothing readable is left on disk. A later re-registration
381
+ * is given the password again by the caller that has it.
382
+ */
383
+ dropAccountPassword(spec) {
384
+ if (!spec.serviceAccount?.password)
385
+ return;
386
+ const configPath = this.wrapperConfig(spec.id);
387
+ try {
388
+ fs.writeFileSync(configPath, (0, winswConfig_1.buildWinSwXml)({ ...spec, serviceAccount: { ...spec.serviceAccount, password: "" } }), "utf-8");
389
+ }
390
+ catch (err) {
391
+ console.warn(`[WinSW] installed "${spec.id}", but could not remove the account password from ${configPath}:`, err);
392
+ }
168
393
  }
169
394
  async installAndEnable(name, execStart, options) {
170
395
  const status = await this.install(name, execStart, options);
171
396
  if (status.error)
172
397
  return status;
173
- // Enable (set to auto start)
174
- const enableResult = await ExecTools_1.ExecTools.safeExecWithCode(`${WindowsServiceController.SC} config "${name}" start= auto`);
398
+ const enableResult = await ExecTools_1.ExecTools.safeExecWithCode(`${SC} config "${name}" start= auto`);
175
399
  if (enableResult.exitCode !== 0) {
176
400
  return {
177
401
  name,
@@ -183,8 +407,45 @@ class WindowsServiceController {
183
407
  }
184
408
  return this.getStatus(name);
185
409
  }
410
+ /** Remove the OS registration, preferring WinSW so its wrapper files are cleaned up too. */
411
+ async removeRegistration(name) {
412
+ const wrapper = this.wrapperBinary(name);
413
+ if (fs.existsSync(wrapper) && fs.existsSync(this.wrapperConfig(name))) {
414
+ const result = await ExecTools_1.ExecTools.safeExecFileWithCode(wrapper, ["uninstall"], {
415
+ timeout: 60_000,
416
+ cwd: path.dirname(wrapper),
417
+ });
418
+ if (result.exitCode === 0) {
419
+ return { ok: true };
420
+ }
421
+ // Fall through to sc.exe — the wrapper may be stale (service deleted by hand).
422
+ const fallback = await ExecTools_1.ExecTools.safeExecWithCode(`${SC} delete "${name}"`);
423
+ if (fallback.exitCode === 0) {
424
+ return { ok: true };
425
+ }
426
+ return {
427
+ ok: false,
428
+ error: `WinSW uninstall failed (code ${result.exitCode}): ${result.stderr.trim() || result.stdout.trim()}`,
429
+ };
430
+ }
431
+ const result = await ExecTools_1.ExecTools.safeExecWithCode(`${SC} delete "${name}"`);
432
+ if (result.exitCode !== 0) {
433
+ return {
434
+ ok: false,
435
+ error: `${SC} delete failed (code ${result.exitCode}): ${result.stderr.trim() || result.stdout.trim()}`,
436
+ };
437
+ }
438
+ return { ok: true };
439
+ }
186
440
  async uninstall(name) {
187
- const SC = WindowsServiceController.SC;
441
+ if (!(await ServerIdentity_1.ServerIdentity.isPrivileged())) {
442
+ const identity = await ServerIdentity_1.ServerIdentity.describe();
443
+ return {
444
+ ok: false,
445
+ error: `Backend is not running as Administrator (PID ${identity.pid}). ` +
446
+ `Stop every backend instance and start one elevated to uninstall "${name}".`,
447
+ };
448
+ }
188
449
  // Stop the service (best-effort)
189
450
  const stopResult = await ExecTools_1.ExecTools.safeExecWithCode(`${SC} stop "${name}"`);
190
451
  if (stopResult.exitCode === 0) {
@@ -196,16 +457,25 @@ class WindowsServiceController {
196
457
  break;
197
458
  }
198
459
  }
199
- // Delete the service
200
- const deleteResult = await ExecTools_1.ExecTools.safeExecWithCode(`${SC} delete "${name}"`);
201
- if (deleteResult.exitCode !== 0) {
202
- return {
203
- ok: false,
204
- error: `sc.exe delete failed (code ${deleteResult.exitCode}): ${deleteResult.stderr.trim() || deleteResult.stdout.trim()}`,
205
- };
460
+ const removed = await this.removeRegistration(name);
461
+ if (!removed.ok) {
462
+ return removed;
206
463
  }
464
+ await this.clearLegacyEnvironmentKey(name);
465
+ this.removeWrapperFiles(name);
207
466
  return { ok: true };
208
467
  }
468
+ /** Delete the WinSW wrapper and config; logs are kept so the journal stays readable. */
469
+ removeWrapperFiles(name) {
470
+ for (const file of [this.wrapperBinary(name), this.wrapperConfig(name)]) {
471
+ try {
472
+ fs.rmSync(file, { force: true });
473
+ }
474
+ catch {
475
+ // Leftover wrapper files are harmless — the next install overwrites them.
476
+ }
477
+ }
478
+ }
209
479
  async listAvailable() {
210
480
  const { stdout } = await ExecTools_1.ExecTools.safeExec("Get-Service | Select-Object -ExpandProperty Name");
211
481
  const names = [];
@@ -217,8 +487,64 @@ class WindowsServiceController {
217
487
  }
218
488
  return names.sort();
219
489
  }
220
- async getJournal(_name, _count = 100) {
221
- return { error: "Journal retrieval is not supported on Windows. Use Linux with systemd." };
490
+ /** Read the last bytes of a log file without loading a rolled 10 MB file whole. */
491
+ readTail(filePath) {
492
+ const size = fs.statSync(filePath).size;
493
+ const length = Math.min(size, JOURNAL_TAIL_BYTES);
494
+ const buffer = Buffer.alloc(length);
495
+ const handle = fs.openSync(filePath, "r");
496
+ try {
497
+ fs.readSync(handle, buffer, 0, length, Math.max(0, size - length));
498
+ }
499
+ finally {
500
+ fs.closeSync(handle);
501
+ }
502
+ const text = buffer.toString("utf-8");
503
+ // Drop a leading partial line when the tail starts mid-file.
504
+ return size > length ? text.slice(text.indexOf("\n") + 1) : text;
505
+ }
506
+ /** Newest WinSW log of a service; stdout beats stderr, otherwise the freshest file wins. */
507
+ pickLogFile(dir, name) {
508
+ const candidates = fs
509
+ .readdirSync(dir)
510
+ .filter((file) => file.startsWith(`${name}.`) && file.includes(".log"))
511
+ .map((file) => ({ file, full: path.join(dir, file), mtime: fs.statSync(path.join(dir, file)).mtimeMs }));
512
+ if (candidates.length === 0)
513
+ return null;
514
+ const out = candidates.find((c) => c.file === `${name}.out.log`);
515
+ if (out)
516
+ return out.full;
517
+ candidates.sort((a, b) => b.mtime - a.mtime);
518
+ return candidates[0].full;
519
+ }
520
+ async getJournal(name, count = 100) {
521
+ const dir = this.serviceDir(name);
522
+ if (!fs.existsSync(dir)) {
523
+ return {
524
+ error: `No WinSW logs for "${name}" — install it through ai server manager to get a journal.`,
525
+ };
526
+ }
527
+ const logFile = this.pickLogFile(dir, name);
528
+ if (!logFile) {
529
+ return { error: `No WinSW logs written for "${name}" yet` };
530
+ }
531
+ let text;
532
+ try {
533
+ text = this.readTail(logFile);
534
+ }
535
+ catch (err) {
536
+ return { error: `Failed to read ${logFile}: ${err instanceof Error ? err.message : String(err)}` };
537
+ }
538
+ // WinSW writes raw program output without timestamps; the file's own
539
+ // modification time is the only stamp available for those lines, while the
540
+ // lines WinSW writes itself carry the time of the event.
541
+ const fileTimestamp = new Date(fs.statSync(logFile).mtimeMs).toISOString();
542
+ const lines = text
543
+ .split(/\r?\n/)
544
+ .filter((line) => line.trim().length > 0)
545
+ .slice(-count)
546
+ .map((line) => (0, winswLog_1.parseWinSwLogLine)(line, fileTimestamp));
547
+ return lines;
222
548
  }
223
549
  }
224
550
  exports.WindowsServiceController = WindowsServiceController;