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