@quadient/skillshare 1.20.2 → 1.21.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.
package/README.md CHANGED
@@ -97,10 +97,29 @@ segment are sent to Skillshare.
97
97
  Starting with 1.7.0, `skillshare teams login` opens a dedicated local browser profile,
98
98
  connects your own Teams account to Skillshare and verifies the connection. Sign in with
99
99
  the same Microsoft account as Skillshare. The server refreshes captured tokens in the
100
- background. `teams watch` renews an expired Microsoft grant through local browser SSO; `agents listen` does the same
101
- while it runs, so a computer that runs agents needs no separate `teams watch` (`--no-teams-watch` turns it off).
102
- Keep that process running for automatic recovery beyond the SPA refresh token lifetime;
103
- another interactive CLI login is needed only when SSO cannot complete, for example MFA.
100
+ background. After `teams login`, CLI 1.21.0 can renew expired Teams grants through local
101
+ browser SSO even after you close the terminal. Install the user service once:
102
+
103
+ ```sh
104
+ npx @quadient/skillshare@latest teams service install
105
+ ```
106
+
107
+ The service starts immediately and at each login (including after a restart) through launchd
108
+ on macOS, systemd on Linux, or Task Scheduler on Windows. It runs only `teams watch` and
109
+ does not register your computer for Claude Code or Codex sessions. If you used a custom
110
+ server, browser or profile for `teams login`, pass the same options to `teams service install`.
111
+ Run the install command again to change options or update the service's CLI version.
112
+
113
+ ```sh
114
+ skillshare teams service status
115
+ skillshare teams service logs --lines 20
116
+ skillshare teams service uninstall
117
+ ```
118
+
119
+ For foreground use, run `teams watch`. An existing `agents listen` already renews Teams
120
+ unless started with `--no-teams-watch`. If you installed the agents service solely for Teams,
121
+ `skillshare agents service uninstall` removes that listener before you install the Teams service.
122
+ When Microsoft requires MFA, run `teams login` again.
104
123
 
105
124
  ```sh
106
125
  skillshare login
@@ -1,4 +1,4 @@
1
- import { startAgentProcess } from './agents-process.js';
1
+ import { sanitizeAgentDiagnostics, startAgentProcess } from './agents-process.js';
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { nativeForm, nativeFormResponse } from './agents-forms.js';
4
4
  import { DEFAULT, LOCKDOWN_NOTE, SANDBOX_NOTE, clip, isLockedDown, isSandboxed, mcpServerName, mcpTokenEnvironment, oneLine, shadowedMcpServers, boundedSessionRequest, sessionWorkdir, validateSessionWorkdir, } from './agents-session.js';
@@ -131,6 +131,7 @@ class CodexDriver {
131
131
  process = null;
132
132
  nextId = 0;
133
133
  pending = new Map();
134
+ exitRequests = [];
134
135
  threadId = null;
135
136
  current = null;
136
137
  texts = new Map();
@@ -141,6 +142,8 @@ class CodexDriver {
141
142
  predictions = true;
142
143
  closing = false;
143
144
  startup = new AbortController();
145
+ phase = 'validating working directory';
146
+ lastNotification;
144
147
  requests = new Map();
145
148
  constructor(context, options) {
146
149
  this.context = context;
@@ -150,6 +153,7 @@ class CodexDriver {
150
153
  await validateSessionWorkdir(this.context);
151
154
  const { start } = this.context;
152
155
  const servers = start.mcpServers ?? [];
156
+ this.phase = 'starting app-server process';
153
157
  this.process = await startAgentProcess({
154
158
  command: this.options.command ?? 'codex',
155
159
  args: ['app-server', ...(isLockedDown(start) ? [] : codexConfigArgs(this.context.profile?.args ?? []))],
@@ -165,22 +169,37 @@ class CodexDriver {
165
169
  this.startup.signal.throwIfAborted();
166
170
  }
167
171
  void this.process.exited.then(code => this.onExit(code));
172
+ this.phase = 'initialize';
168
173
  await this.request('initialize', {
169
174
  clientInfo: { name: 'skillshare', title: 'Skillshare', version: this.options.clientVersion ?? '0.0.0' },
170
175
  // Unified diffs are not shown in the transcript, so Codex need not send them.
171
176
  capabilities: { experimentalApi: true, optOutNotificationMethods: ['turn/diff/updated', 'mcpServer/startupStatus/updated'] },
172
177
  });
173
178
  this.notify('initialized');
179
+ this.phase = 'reading MCP configuration';
174
180
  const params = codexThreadParams(this.context, isLockedDown(start) ? undefined : await this.shadowedServers(servers));
181
+ this.startup.signal.throwIfAborted();
182
+ this.phase = start.resumeThreadId ? 'thread/resume' : 'thread/start';
175
183
  const result = start.resumeThreadId
176
184
  ? await this.request('thread/resume', { threadId: start.resumeThreadId, ...params })
177
185
  : await this.request('thread/start', params);
186
+ this.startup.signal.throwIfAborted();
178
187
  const threadId = result?.thread?.id;
179
188
  if (typeof threadId !== 'string')
180
189
  throw new Error('Codex did not return a thread.');
181
190
  this.threadId = threadId;
191
+ this.phase = 'ready';
182
192
  this.context.thread(threadId);
183
193
  }
194
+ diagnostics() {
195
+ const waiting = [...new Set([...this.pending.values()].map(request => request.method).concat(this.exitRequests))].slice(0, 8);
196
+ return sanitizeAgentDiagnostics([
197
+ `Codex phase: ${this.phase}.`,
198
+ waiting.length > 0 ? `Waiting for: ${waiting.join(', ')}.` : '',
199
+ this.lastNotification ? `Last notification: ${this.lastNotification}.` : '',
200
+ this.process?.stderrTail(),
201
+ ].filter(Boolean).join('\n'), (this.context.start.mcpServers ?? []).map(server => server.bearerToken));
202
+ }
184
203
  /** Undefined when Codex cannot report its configuration; the session's servers then replace the user's. */
185
204
  async shadowedServers(servers) {
186
205
  if (servers.length === 0)
@@ -194,6 +213,7 @@ class CodexDriver {
194
213
  }
195
214
  }
196
215
  turn(message) {
216
+ this.phase = 'running turn';
197
217
  const { configuration } = this.context.start;
198
218
  const policy = configuration.approvalMode ? codexThreadParams(this.context) : undefined;
199
219
  return new Promise((resolve, reject) => {
@@ -253,7 +273,7 @@ class CodexDriver {
253
273
  return Promise.reject(new Error('Codex is not running.'));
254
274
  const id = ++this.nextId;
255
275
  return new Promise((resolve, reject) => {
256
- this.pending.set(id, { resolve, reject });
276
+ this.pending.set(id, { method, resolve, reject });
257
277
  if (!this.process.write(JSON.stringify({ id, method, params }))) {
258
278
  this.pending.delete(id);
259
279
  reject(new Error('Codex is not accepting input.'));
@@ -279,7 +299,7 @@ class CodexDriver {
279
299
  return;
280
300
  this.pending.delete(message.id);
281
301
  if (message.error)
282
- pending.reject(new Error(codexErrorText(message.error.message) ?? 'Codex rejected the request.'));
302
+ pending.reject(new Error(sanitizeAgentDiagnostics(`Codex ${pending.method} failed: ${codexErrorText(message.error.message) ?? 'Codex rejected the request.'}`, (this.context.start.mcpServers ?? []).map(server => server.bearerToken))));
283
303
  else
284
304
  pending.resolve(message.result);
285
305
  return;
@@ -421,6 +441,7 @@ class CodexDriver {
421
441
  this.requests.clear();
422
442
  }
423
443
  notification(method, params) {
444
+ this.lastNotification = oneLine(method).slice(0, 150);
424
445
  // Approvals and questions from child threads also belong to this connection's session.
425
446
  if (method === 'serverRequest/resolved') {
426
447
  for (const [id, request] of this.requests) {
@@ -499,6 +520,7 @@ class CodexDriver {
499
520
  this.clearRequests();
500
521
  this.approvalItems.clear();
501
522
  this.current = null;
523
+ this.phase = 'ready';
502
524
  const status = turn.status === 'completed' ? 'completed' : turn.status === 'interrupted' ? 'interrupted' : 'failed';
503
525
  const { usage } = current;
504
526
  const stats = { inputTokens: usage.input, cachedInputTokens: usage.cached, cacheWriteTokens: usage.cacheWrite, outputTokens: usage.output };
@@ -521,7 +543,8 @@ class CodexDriver {
521
543
  }
522
544
  onExit(code) {
523
545
  this.clearRequests();
524
- const reason = `Codex exited${code === null ? '' : ` with code ${code}`}${this.process?.stderrTail() ? `: ${this.process.stderrTail()}` : '.'}`;
546
+ this.exitRequests = [...new Set([...this.pending.values()].map(request => request.method))].slice(0, 8);
547
+ const reason = `Codex exited${code === null ? '' : ` with code ${code}`}.\n${this.diagnostics()}`;
525
548
  for (const pending of this.pending.values())
526
549
  pending.reject(new Error(reason));
527
550
  this.pending.clear();
@@ -3,7 +3,24 @@ import { open } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
4
  import { createInterface } from 'node:readline';
5
5
  import { setTimeout as delay } from 'node:timers/promises';
6
+ import { stripVTControlCharacters } from 'node:util';
6
7
  import { resolveAgentCommand } from './agents-executable.js';
8
+ export function agentEnvironmentSecrets(env) {
9
+ return Object.entries(env).filter(([name, value]) => /token|secret|password|api_?key/i.test(name) && value && value.length >= 8)
10
+ .map(([, value]) => value);
11
+ }
12
+ /** Diagnostic output is persisted in shared transcripts; never include known credentials or terminal escapes. */
13
+ export function sanitizeAgentDiagnostics(text, secrets = []) {
14
+ // Terminals can ignore embedded C0 bytes within escape sequences; normalize them before parsing ANSI.
15
+ text = stripVTControlCharacters(text.replace(/[\u0000-\u0006\u0008\u000b\u000c\u000e-\u001a\u001c-\u001f\u007f]/g, ''))
16
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g, '');
17
+ for (const secret of secrets.filter(Boolean).sort((a, b) => b.length - a.length))
18
+ text = text.replaceAll(secret, '[redacted]');
19
+ return text
20
+ .replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]+/gi, '$1 [redacted]')
21
+ .replace(/((?:access[_-]?token|refresh[_-]?token|api[_-]?key|password|authorization)["']?\s*[:=]\s*["']?)[^\s"'&,;}]+/gi, '$1[redacted]')
22
+ .replace(/([?&](?:token|key|sig|signature)=)[^&\s"']+/gi, '$1[redacted]');
23
+ }
7
24
  /**
8
25
  * Starts an agent that speaks newline-delimited JSON on stdio. Tokens go through the environment only. A separate
9
26
  * process group lets stopping the agent also stop the shell commands it runs.
@@ -55,15 +72,43 @@ export async function startAgentProcess(options) {
55
72
  detached: posix, windowsHide: true,
56
73
  ...(batch ? { windowsVerbatimArguments: true } : {}),
57
74
  });
75
+ const secrets = agentEnvironmentSecrets(env);
58
76
  let stderr = '';
59
- child.stderr?.on('data', chunk => { stderr = (stderr + chunk).slice(-4000); });
77
+ let telemetry = '';
78
+ let partialStderr = '';
79
+ let oversizedStderrLine = false;
80
+ const recordStderr = (line) => {
81
+ const clean = sanitizeAgentDiagnostics(line, secrets).trim();
82
+ if (/\bopentelemetry_sdk\b/i.test(clean))
83
+ telemetry = clean.slice(0, 300);
84
+ else if (clean)
85
+ stderr = (stderr + '\n' + clean).slice(-1200);
86
+ };
87
+ const captureStderr = (chunk) => {
88
+ const lines = (partialStderr + chunk).split(/\r?\n/);
89
+ const partial = lines.pop();
90
+ if (oversizedStderrLine && lines.length > 0) {
91
+ lines.shift();
92
+ oversizedStderrLine = false;
93
+ }
94
+ lines.forEach(recordStderr);
95
+ if (oversizedStderrLine || partial.length > 8000) {
96
+ if (!oversizedStderrLine)
97
+ recordStderr('[Overlong stderr line omitted.]');
98
+ oversizedStderrLine = true;
99
+ partialStderr = '';
100
+ }
101
+ else
102
+ partialStderr = partial;
103
+ };
104
+ child.stderr?.on('data', chunk => captureStderr(String(chunk)));
60
105
  child.stdin?.on('error', () => { });
61
106
  const lines = child.stdout ? createInterface({ input: child.stdout, crlfDelay: Infinity }) : undefined;
62
107
  lines?.on('line', line => { if (line.trim())
63
108
  options.onLine(line); });
64
109
  let running = true;
65
110
  const exited = new Promise(resolve => {
66
- child.once('error', error => { running = false; stderr = (stderr + '\n' + error.message).slice(-4000); resolve(null); });
111
+ child.once('error', error => { running = false; recordStderr(error.message); resolve(null); });
67
112
  child.once('exit', code => { running = false; resolve(code); });
68
113
  });
69
114
  const closed = new Promise(resolve => child.once('close', () => resolve()));
@@ -72,7 +117,15 @@ export async function startAgentProcess(options) {
72
117
  child,
73
118
  exited,
74
119
  closed,
75
- stderrTail: () => stderr.trim().split(/\r?\n/).filter(line => line.trim()).slice(-3).join(' ').slice(-300),
120
+ stderrTail: () => {
121
+ // Do not split a credential across snapshots while its line is still arriving.
122
+ if (!running && partialStderr) {
123
+ recordStderr(partialStderr);
124
+ partialStderr = '';
125
+ }
126
+ return [stderr.trim(), telemetry ? `${stderr.trim() ? 'Telemetry output' : 'Only telemetry output was captured'} (may be unrelated to the failure):\n${telemetry}` : '']
127
+ .filter(Boolean).join('\n');
128
+ },
76
129
  // write(false) signals backpressure, not rejection: the frame is already buffered and must not be resent.
77
130
  write: line => {
78
131
  if (!child.stdin?.writable)
@@ -1,34 +1,11 @@
1
+ import { definitionPath, registerService, servicePaths, unregisterService } from './service-manager.js';
1
2
  import { detectAgents, profilesPath } from './agents-detect.js';
2
3
  import { loadAgentSettings, updateAgentJson, withoutLegacySandboxArgs } from './agents-settings.js';
3
4
  import { refreshServicePath } from './agents-service-path.js';
4
5
  import { existsSync } from 'node:fs';
5
- import { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
6
- import { homedir } from 'node:os';
7
- import { dirname, join } from 'node:path';
8
- import { describeOtherListener, installVersion, readListenerLock, runCommand, } from './agents-update.js';
9
- export const LAUNCHD_LABEL = 'com.quadient.skillshare.agents';
10
- export const SYSTEMD_UNIT = 'skillshare-agents.service';
11
- export const WINDOWS_TASK = 'Skillshare Agents';
12
- export function defaultServiceEnvironment(appDir) {
13
- const platform = process.platform;
14
- if (platform !== 'darwin' && platform !== 'linux' && platform !== 'win32')
15
- throw new Error(`The agents service is not supported on ${platform}.`);
16
- return {
17
- appDir, platform, home: homedir(), run: runCommand, uid: process.getuid?.(),
18
- windowsUser: process.env.USERDOMAIN ? `${process.env.USERDOMAIN}\\${process.env.USERNAME}` : process.env.USERNAME,
19
- };
20
- }
21
- export function servicePaths(appDir) {
22
- return {
23
- config: join(appDir, 'agents-service.json'),
24
- detection: join(appDir, 'agents-service-detection.json'),
25
- launcher: join(appDir, 'agents-service.mjs'),
26
- log: join(appDir, 'logs', 'agents.log'),
27
- // What the service manager catches before the listener's own log opens, such as a launcher that cannot start.
28
- output: join(appDir, 'logs', 'agents-service.out'),
29
- windowsTask: join(appDir, 'agents-service-task.xml'),
30
- };
31
- }
6
+ import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises';
7
+ import { dirname } from 'node:path';
8
+ import { describeOtherListener, installVersion, readListenerLock, } from './agents-update.js';
32
9
  /** Runs on the next service start, including with launchers written by older CLIs. Seed before removing the old argument. */
33
10
  export async function migrateServiceApprovalOptions(appDir, settingsPath = profilesPath()) {
34
11
  const path = servicePaths(appDir).config;
@@ -44,14 +21,6 @@ export async function migrateServiceApprovalOptions(appDir, settingsPath = profi
44
21
  value.args = withoutLegacySandboxArgs(value.args);
45
22
  });
46
23
  }
47
- /** Where the service manager keeps the service definition. */
48
- export function definitionPath(environment) {
49
- switch (environment.platform) {
50
- case 'darwin': return join(environment.home, 'Library', 'LaunchAgents', `${LAUNCHD_LABEL}.plist`);
51
- case 'linux': return join(process.env.XDG_CONFIG_HOME ?? join(environment.home, '.config'), 'systemd', 'user', SYSTEMD_UNIT);
52
- case 'win32': return servicePaths(environment.appDir).windowsTask;
53
- }
54
- }
55
24
  /**
56
25
  * The launcher the service manager starts. It does not depend on any CLI version: it picks the newest installed one, so an
57
26
  * update downloaded by the listener also applies after a restart of the computer.
@@ -84,124 +53,6 @@ process.argv = [process.argv[0], entry, 'agents', 'listen', '--server', config.s
84
53
  await import(pathToFileURL(entry).href)
85
54
  `;
86
55
  }
87
- function xml(value) {
88
- return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
89
- }
90
- /** A launchd agent in the user's login session, so agents reach the keychain and the browser; started again if it fails. */
91
- export function launchdPlist(config, appDir) {
92
- const paths = servicePaths(appDir);
93
- return `<?xml version="1.0" encoding="UTF-8"?>
94
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
95
- <plist version="1.0">
96
- <dict>
97
- <key>Label</key>
98
- <string>${LAUNCHD_LABEL}</string>
99
- <key>ProgramArguments</key>
100
- <array>
101
- <string>${xml(config.node)}</string>
102
- <string>${xml(paths.launcher)}</string>
103
- </array>
104
- <key>WorkingDirectory</key>
105
- <string>${xml(appDir)}</string>
106
- <key>RunAtLoad</key>
107
- <true/>
108
- <key>KeepAlive</key>
109
- <dict>
110
- <key>SuccessfulExit</key>
111
- <false/>
112
- </dict>
113
- <key>ThrottleInterval</key>
114
- <integer>30</integer>
115
- <key>ProcessType</key>
116
- <string>Interactive</string>
117
- <key>StandardOutPath</key>
118
- <string>${xml(paths.output)}</string>
119
- <key>StandardErrorPath</key>
120
- <string>${xml(paths.output)}</string>
121
- </dict>
122
- </plist>
123
- `;
124
- }
125
- function systemdQuote(value) {
126
- return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/%/g, '%%')}"`;
127
- }
128
- /** A systemd user service, started with the user's session and again whenever it fails. */
129
- export function systemdUnit(config, appDir) {
130
- const paths = servicePaths(appDir);
131
- // WorkingDirectory takes a literal path (including spaces), not a quoted command argument.
132
- const workingDirectory = appDir.replace(/%/g, '%%');
133
- return `[Unit]
134
- Description=Skillshare agents listener
135
- After=network-online.target
136
-
137
- [Service]
138
- Type=simple
139
- ExecStart=${systemdQuote(config.node)} ${systemdQuote(paths.launcher)}
140
- WorkingDirectory=${workingDirectory}
141
- Restart=on-failure
142
- RestartSec=30
143
- StandardOutput=append:${paths.output}
144
- StandardError=append:${paths.output}
145
-
146
- [Install]
147
- WantedBy=default.target
148
- `;
149
- }
150
- /**
151
- * A scheduled task that starts at logon in the user's session, without a time limit and also on battery. conhost
152
- * --headless runs Node without a console window.
153
- */
154
- export function windowsTaskXml(config, appDir, user) {
155
- const paths = servicePaths(appDir);
156
- return `<?xml version="1.0" encoding="UTF-16"?>
157
- <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
158
- <RegistrationInfo>
159
- <Description>Skillshare agents listener</Description>
160
- </RegistrationInfo>
161
- <Triggers>
162
- <LogonTrigger>
163
- <Enabled>true</Enabled>
164
- <UserId>${xml(user)}</UserId>
165
- </LogonTrigger>
166
- </Triggers>
167
- <Principals>
168
- <Principal id="Author">
169
- <UserId>${xml(user)}</UserId>
170
- <LogonType>InteractiveToken</LogonType>
171
- <RunLevel>LeastPrivilege</RunLevel>
172
- </Principal>
173
- </Principals>
174
- <Settings>
175
- <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
176
- <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
177
- <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
178
- <AllowHardTerminate>true</AllowHardTerminate>
179
- <StartWhenAvailable>true</StartWhenAvailable>
180
- <AllowStartOnDemand>true</AllowStartOnDemand>
181
- <Enabled>true</Enabled>
182
- <Hidden>false</Hidden>
183
- <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
184
- <RestartOnFailure>
185
- <Interval>PT1M</Interval>
186
- <Count>999</Count>
187
- </RestartOnFailure>
188
- </Settings>
189
- <Actions Context="Author">
190
- <Exec>
191
- <Command>conhost.exe</Command>
192
- <Arguments>--headless "${xml(config.node)}" "${xml(paths.launcher)}"</Arguments>
193
- <WorkingDirectory>${xml(appDir)}</WorkingDirectory>
194
- </Exec>
195
- </Actions>
196
- </Task>
197
- `;
198
- }
199
- async function must(environment, command, args, what) {
200
- const result = await environment.run(command, args);
201
- if (result.code !== 0)
202
- throw new Error(`${what} failed: ${(result.stderr || result.stdout).trim() || `exit code ${result.code}`}`);
203
- return result;
204
- }
205
56
  /**
206
57
  * Installs the CLI version for the service, writes the launcher and registers it with the service manager, which starts it
207
58
  * now and at every login. Installing again replaces the service, for example with other options.
@@ -226,96 +77,12 @@ export async function installService(environment, settings, options = {}) {
226
77
  if (process.platform !== 'win32')
227
78
  await chmod(path, 0o600);
228
79
  }
229
- const definition = definitionPath(environment);
230
- await mkdir(dirname(definition), { recursive: true });
231
- switch (environment.platform) {
232
- case 'darwin': {
233
- const domain = `gui/${environment.uid}`;
234
- await environment.run('launchctl', ['bootout', `${domain}/${LAUNCHD_LABEL}`]);
235
- await writeFile(definition, launchdPlist(config, environment.appDir));
236
- await must(environment, 'launchctl', ['bootstrap', domain, definition], 'launchctl bootstrap');
237
- break;
238
- }
239
- case 'linux':
240
- await writeFile(definition, systemdUnit(config, environment.appDir));
241
- await must(environment, 'systemctl', ['--user', 'daemon-reload'], 'systemctl daemon-reload');
242
- await must(environment, 'systemctl', ['--user', 'enable', SYSTEMD_UNIT], 'systemctl enable');
243
- await must(environment, 'systemctl', ['--user', 'restart', SYSTEMD_UNIT], 'systemctl restart');
244
- break;
245
- case 'win32':
246
- // schtasks reads task definitions as UTF-16.
247
- await writeFile(definition, Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(windowsTaskXml(config, environment.appDir, environment.windowsUser ?? ''), 'utf16le')]));
248
- await environment.run('schtasks', ['/End', '/TN', WINDOWS_TASK]);
249
- await must(environment, 'schtasks', ['/Create', '/TN', WINDOWS_TASK, '/XML', definition, '/F'], 'schtasks /Create');
250
- await must(environment, 'schtasks', ['/Run', '/TN', WINDOWS_TASK], 'schtasks /Run');
251
- break;
252
- }
80
+ await registerService(environment, 'agents', config.node);
253
81
  return config;
254
82
  }
255
- /** Match the launcher argument, not a substring belonging to another installation. */
256
- export function windowsStopServiceScript(appDir) {
257
- const launcher = servicePaths(appDir).launcher.replace(/'/g, "''");
258
- return `
259
- $ErrorActionPreference = 'Stop'
260
- $launcher = '${launcher}'
261
- $pattern = '^\\s*(?:"[^"\\r\\n]+"|[^\\s"]+)\\s+(?:"' + [regex]::Escape($launcher) + '"|' + [regex]::Escape($launcher) + ')(?:\\s|$)'
262
- $all = @(Get-CimInstance Win32_Process)
263
- $tree = [System.Collections.Generic.List[object]]::new()
264
- foreach ($p in $all) {
265
- if ($p.Name -ieq 'node.exe' -and $p.CommandLine -match $pattern) { $tree.Add($p) }
266
- }
267
- # Snapshot descendants before stopping their parents, which otherwise loses the tree.
268
- for ($i = 0; $i -lt $tree.Count; $i++) {
269
- foreach ($p in $all) {
270
- if ($p.ParentProcessId -eq $tree[$i].ProcessId -and $p.ProcessId -notin $tree.ProcessId) { $tree.Add($p) }
271
- }
272
- }
273
- # Parent first prevents the supervisor from restarting a listener during teardown.
274
- foreach ($p in $tree) {
275
- $live = Get-CimInstance Win32_Process -Filter ("ProcessId = " + $p.ProcessId)
276
- if ($null -ne $live -and $live.CreationDate -eq $p.CreationDate) {
277
- Stop-Process -Id $p.ProcessId -Force -ErrorAction Stop
278
- if (Get-Process -Id $p.ProcessId -ErrorAction SilentlyContinue) {
279
- Wait-Process -Id $p.ProcessId -Timeout 10 -ErrorAction Stop
280
- }
281
- }
282
- }
283
- `;
284
- }
285
- /** Stops the service and removes it; downloaded CLI versions and logs stay. */
286
83
  export async function uninstallService(environment) {
287
- const definition = definitionPath(environment);
288
84
  const wasRunning = (await readListenerLock(environment.appDir))?.service === true;
289
- switch (environment.platform) {
290
- case 'darwin':
291
- await environment.run('launchctl', ['bootout', `gui/${environment.uid}/${LAUNCHD_LABEL}`]);
292
- break;
293
- case 'linux':
294
- await environment.run('systemctl', ['--user', 'disable', '--now', SYSTEMD_UNIT]);
295
- break;
296
- case 'win32': {
297
- const task = await environment.run('schtasks', ['/Query', '/TN', WINDOWS_TASK]);
298
- if (task.code === 0) {
299
- await must(environment, 'schtasks', ['/Change', '/TN', WINDOWS_TASK, '/DISABLE'], 'Disable agents task');
300
- }
301
- // /End only stops conhost on some Windows versions, leaving Node and its worker alive.
302
- // Discover by launcher path even after a previous uninstall removed the config and task.
303
- await must(environment, 'powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand',
304
- Buffer.from(windowsStopServiceScript(environment.appDir), 'utf16le').toString('base64')], 'Stop agents service processes');
305
- if (task.code === 0) {
306
- await environment.run('schtasks', ['/End', '/TN', WINDOWS_TASK]);
307
- await must(environment, 'schtasks', ['/Delete', '/TN', WINDOWS_TASK, '/F'], 'Delete agents task');
308
- }
309
- break;
310
- }
311
- }
312
- const existed = existsSync(definition) || existsSync(servicePaths(environment.appDir).config);
313
- const paths = servicePaths(environment.appDir);
314
- for (const path of [definition, paths.config, paths.launcher])
315
- await rm(path, { force: true });
316
- if (environment.platform === 'linux')
317
- await environment.run('systemctl', ['--user', 'daemon-reload']);
318
- return existed || wasRunning;
85
+ return await unregisterService(environment, 'agents') || wasRunning;
319
86
  }
320
87
  export async function detectServiceAgents(appDir, signal) {
321
88
  signal?.throwIfAborted();
@@ -377,17 +144,3 @@ export function renderServiceStatus(status, appDir) {
377
144
  lines.push(`Log: ${servicePaths(appDir).log}`);
378
145
  return lines.join('\n');
379
146
  }
380
- /** The end of the listener's log, and of the service manager's output when the listener could not start. */
381
- export async function serviceLogs(appDir, lines) {
382
- const paths = servicePaths(appDir);
383
- const tail = async (path) => {
384
- try {
385
- return (await readFile(path, 'utf8')).trimEnd().split('\n').slice(-lines).join('\n');
386
- }
387
- catch {
388
- return '';
389
- }
390
- };
391
- const [log, output] = [await tail(paths.log), await tail(paths.output)];
392
- return [log, output ? `--- ${paths.output}\n${output}` : ''].filter(Boolean).join('\n') || 'The agents service has not written a log yet.';
393
- }