@quadient/skillshare 1.11.0 → 1.12.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.
@@ -221,9 +221,40 @@ export async function installService(environment, settings, options = {}) {
221
221
  }
222
222
  return config;
223
223
  }
224
+ /** Match the launcher argument, not a substring belonging to another installation. */
225
+ export function windowsStopServiceScript(appDir) {
226
+ const launcher = servicePaths(appDir).launcher.replace(/'/g, "''");
227
+ return `
228
+ $ErrorActionPreference = 'Stop'
229
+ $launcher = '${launcher}'
230
+ $pattern = '^\\s*(?:"[^"\\r\\n]+"|[^\\s"]+)\\s+(?:"' + [regex]::Escape($launcher) + '"|' + [regex]::Escape($launcher) + ')(?:\\s|$)'
231
+ $all = @(Get-CimInstance Win32_Process)
232
+ $tree = [System.Collections.Generic.List[object]]::new()
233
+ foreach ($p in $all) {
234
+ if ($p.Name -ieq 'node.exe' -and $p.CommandLine -match $pattern) { $tree.Add($p) }
235
+ }
236
+ # Snapshot descendants before stopping their parents, which otherwise loses the tree.
237
+ for ($i = 0; $i -lt $tree.Count; $i++) {
238
+ foreach ($p in $all) {
239
+ if ($p.ParentProcessId -eq $tree[$i].ProcessId -and $p.ProcessId -notin $tree.ProcessId) { $tree.Add($p) }
240
+ }
241
+ }
242
+ # Parent first prevents the supervisor from restarting a listener during teardown.
243
+ foreach ($p in $tree) {
244
+ $live = Get-CimInstance Win32_Process -Filter ("ProcessId = " + $p.ProcessId)
245
+ if ($null -ne $live -and $live.CreationDate -eq $p.CreationDate) {
246
+ Stop-Process -Id $p.ProcessId -Force -ErrorAction Stop
247
+ if (Get-Process -Id $p.ProcessId -ErrorAction SilentlyContinue) {
248
+ Wait-Process -Id $p.ProcessId -Timeout 10 -ErrorAction Stop
249
+ }
250
+ }
251
+ }
252
+ `;
253
+ }
224
254
  /** Stops the service and removes it; downloaded CLI versions and logs stay. */
225
255
  export async function uninstallService(environment) {
226
256
  const definition = definitionPath(environment);
257
+ const wasRunning = (await readListenerLock(environment.appDir))?.service === true;
227
258
  switch (environment.platform) {
228
259
  case 'darwin':
229
260
  await environment.run('launchctl', ['bootout', `gui/${environment.uid}/${LAUNCHD_LABEL}`]);
@@ -231,10 +262,21 @@ export async function uninstallService(environment) {
231
262
  case 'linux':
232
263
  await environment.run('systemctl', ['--user', 'disable', '--now', SYSTEMD_UNIT]);
233
264
  break;
234
- case 'win32':
235
- await environment.run('schtasks', ['/End', '/TN', WINDOWS_TASK]);
236
- await environment.run('schtasks', ['/Delete', '/TN', WINDOWS_TASK, '/F']);
265
+ case 'win32': {
266
+ const task = await environment.run('schtasks', ['/Query', '/TN', WINDOWS_TASK]);
267
+ if (task.code === 0) {
268
+ await must(environment, 'schtasks', ['/Change', '/TN', WINDOWS_TASK, '/DISABLE'], 'Disable agents task');
269
+ }
270
+ // /End only stops conhost on some Windows versions, leaving Node and its worker alive.
271
+ // Discover by launcher path even after a previous uninstall removed the config and task.
272
+ await must(environment, 'powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand',
273
+ Buffer.from(windowsStopServiceScript(environment.appDir), 'utf16le').toString('base64')], 'Stop agents service processes');
274
+ if (task.code === 0) {
275
+ await environment.run('schtasks', ['/End', '/TN', WINDOWS_TASK]);
276
+ await must(environment, 'schtasks', ['/Delete', '/TN', WINDOWS_TASK, '/F'], 'Delete agents task');
277
+ }
237
278
  break;
279
+ }
238
280
  }
239
281
  const existed = existsSync(definition) || existsSync(servicePaths(environment.appDir).config);
240
282
  const paths = servicePaths(environment.appDir);
@@ -242,7 +284,7 @@ export async function uninstallService(environment) {
242
284
  await rm(path, { force: true });
243
285
  if (environment.platform === 'linux')
244
286
  await environment.run('systemctl', ['--user', 'daemon-reload']);
245
- return existed;
287
+ return existed || wasRunning;
246
288
  }
247
289
  export async function serviceStatus(environment) {
248
290
  let config;
@@ -259,7 +301,9 @@ export async function serviceStatus(environment) {
259
301
  }
260
302
  export function renderServiceStatus(status, appDir) {
261
303
  if (!status.installed)
262
- return 'The agents service is not installed. Install it with skillshare agents service install.';
304
+ return status.running
305
+ ? `The agents service is not installed, but process ${status.pid} is still running. Stop it with skillshare agents service uninstall.`
306
+ : 'The agents service is not installed. Install it with skillshare agents service install.';
263
307
  const lines = [
264
308
  status.running
265
309
  ? `The agents service is running (process ${status.pid}, Skillshare CLI ${status.version}, since ${status.since}).`
@@ -85,7 +85,10 @@ export class EventQueue {
85
85
  continue;
86
86
  }
87
87
  failures = 0;
88
- this.queue.splice(0, batch.length);
88
+ // push() replaces an item object when newer content arrives during upload.
89
+ // Acknowledge only the exact snapshots sent, leaving replacements queued.
90
+ const acknowledged = new Set(batch);
91
+ this.queue = this.queue.filter(event => !acknowledged.has(event));
89
92
  }
90
93
  })().finally(() => { this.flushing = null; });
91
94
  return this.flushing;
package/dist/help.js CHANGED
@@ -111,6 +111,18 @@ export const COMMANDS = [
111
111
  ],
112
112
  flags: ['browser', 'headless', 'browser-profile', 'output', 'json'],
113
113
  },
114
+ {
115
+ name: 'salesforce',
116
+ summary: 'Connect Salesforce to the read-only Skillshare Salesforce MCP',
117
+ usage: [
118
+ 'salesforce login [local] [--instance <url>]',
119
+ 'salesforce status | test [--json]',
120
+ 'salesforce logout',
121
+ ],
122
+ description: 'login opens Salesforce sign-in in the browser through the Salesforce CLI connected app (callback on localhost:1717), so no administrator has to create an app; your org must allow that app for you. --instance is the Lightning or My Domain URL of the org (or test.salesforce.com for a sandbox); later logins reuse the connected org. Skillshare keeps the Salesforce sign-in, renews it and offers agents only read tools: search, SOQL queries, records and object metadata, with your own Salesforce permissions. logout also revokes the sign-in in Salesforce.',
123
+ examples: ['skillshare salesforce login --instance https://acme--uat.sandbox.lightning.force.com', 'skillshare salesforce test'],
124
+ flags: ['instance', 'json'],
125
+ },
114
126
  {
115
127
  name: 'agents',
116
128
  summary: 'Run Claude Code or Codex sessions from Skillshare on this computer',
@@ -151,7 +163,7 @@ export function renderUsage(defaultUrl) {
151
163
  'Options:',
152
164
  ' --token <token> Bearer token for API requests (overrides SKILLSHARE_TOKEN)',
153
165
  ' --server <url> Skillshare origin for login and Teams commands',
154
- ' --json Print machine-readable JSON (whoami, list, show, upload, pages, teams, agents)',
166
+ ' --json Print machine-readable JSON (whoami, list, show, upload, pages, teams, salesforce, agents)',
155
167
  ' -h, --help Show help for a command',
156
168
  ' -v, --version Show the CLI version',
157
169
  '',
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { runSalesforceCommand } from './salesforce.js';
1
2
  import { assertCredentialDestination, resolveTeamsObjectId, runTeamsCommand, watchTeamsInBackground } from './teams.js';
2
3
  import { runAgentsCommand, runServiceCommand } from './agents.js';
3
4
  import { SERVICE_ENV } from './agents-update.js';
@@ -146,6 +147,13 @@ async function main() {
146
147
  await runTeamsCommand(teamsClient, options.positionals, options.flags, APP_DIR);
147
148
  return;
148
149
  }
150
+ case 'salesforce': {
151
+ const baseUrl = options.flags.server ?? (options.positionals[1] === 'local' ? LOCAL_URL : await resolveActiveBaseUrl());
152
+ if (!options.token && !await loadSession(baseUrl))
153
+ await login(baseUrl);
154
+ await runSalesforceCommand(await createClient(baseUrl, options.token), options.positionals, options.flags, openBrowser);
155
+ return;
156
+ }
149
157
  case 'agents': {
150
158
  // Managing the background service needs no server, except to install it.
151
159
  if (options.positionals[0] === 'service' && options.positionals[1] !== 'install') {
@@ -0,0 +1,181 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { createServer } from 'node:http';
3
+ import { assertCredentialDestination } from './teams.js';
4
+ const root = '/api/mcps/providers/salesforce';
5
+ // The Salesforce CLI connected app exists in every org and accepts only this loopback redirect,
6
+ // so users can connect without an administrator creating an app for Skillshare.
7
+ export const SALESFORCE_CLIENT_ID = 'PlatformCLI';
8
+ export const SALESFORCE_CALLBACK_PORT = 1717;
9
+ const callbackPath = '/OauthRedirect';
10
+ const domainLabel = '[a-z0-9](?:[a-z0-9-]{0,78}[a-z0-9])?(?:\\.(?:sandbox|develop|scratch|demo|patch|trailblaze))?';
11
+ const myDomainHost = new RegExp(`^${domainLabel}\\.my\\.salesforce\\.com$`);
12
+ const lightningHost = new RegExp(`^${domainLabel}\\.lightning\\.force\\.com$`);
13
+ /**
14
+ * Accepts login.salesforce.com, test.salesforce.com, a My Domain URL or the Lightning URL from the browser
15
+ * (mapped to its My Domain), with or without https://. Returns the https origin, or null.
16
+ */
17
+ export function normalizeSalesforceLoginUrl(value) {
18
+ let input = value?.trim() ?? '';
19
+ if (!input)
20
+ return null;
21
+ if (!input.includes('://'))
22
+ input = `https://${input}`;
23
+ let url;
24
+ try {
25
+ url = new URL(input);
26
+ }
27
+ catch {
28
+ return null;
29
+ }
30
+ if (url.protocol !== 'https:' || url.port || url.username || url.password)
31
+ return null;
32
+ let host = url.hostname.toLowerCase();
33
+ if (lightningHost.test(host))
34
+ host = host.slice(0, -'.lightning.force.com'.length) + '.my.salesforce.com';
35
+ return host === 'login.salesforce.com' || host === 'test.salesforce.com' || myDomainHost.test(host) ? `https://${host}` : null;
36
+ }
37
+ /**
38
+ * Runs the OAuth authorization code flow with PKCE in the browser and returns the code. The code is handed to
39
+ * Skillshare, which redeems it; no Salesforce token is ever stored on this computer.
40
+ */
41
+ export async function captureSalesforceAuthorization(options) {
42
+ const port = options.port ?? SALESFORCE_CALLBACK_PORT;
43
+ const redirectUri = `http://localhost:${port}${callbackPath}`;
44
+ const codeVerifier = randomBytes(32).toString('base64url');
45
+ const state = randomBytes(16).toString('hex');
46
+ const authorize = new URL('/services/oauth2/authorize', options.loginUrl);
47
+ authorize.search = new URLSearchParams({
48
+ response_type: 'code',
49
+ client_id: SALESFORCE_CLIENT_ID,
50
+ redirect_uri: redirectUri,
51
+ scope: 'refresh_token api web',
52
+ code_challenge: createHash('sha256').update(codeVerifier).digest('base64url'),
53
+ code_challenge_method: 'S256',
54
+ state,
55
+ }).toString();
56
+ return new Promise((resolve, reject) => {
57
+ let timer;
58
+ const finish = (error, code) => {
59
+ clearTimeout(timer);
60
+ server.close();
61
+ server.closeAllConnections?.();
62
+ if (error)
63
+ reject(error);
64
+ else
65
+ resolve({ code: code, codeVerifier });
66
+ };
67
+ const server = createServer((request, response) => {
68
+ const url = new URL(request.url ?? '/', redirectUri);
69
+ if (url.pathname !== callbackPath) {
70
+ response.writeHead(404).end();
71
+ return;
72
+ }
73
+ const reply = (message) => response.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8', Connection: 'close' }).end(message);
74
+ if (url.searchParams.get('state') !== state) {
75
+ reply('This sign-in does not belong to the running skillshare salesforce login.');
76
+ return;
77
+ }
78
+ const error = url.searchParams.get('error');
79
+ if (error) {
80
+ const description = url.searchParams.get('error_description') ?? error;
81
+ reply(`Salesforce sign-in failed: ${description}`);
82
+ finish(new Error(error === 'OAUTH_APPROVAL_ERROR_GENERIC' || /installed/i.test(description)
83
+ ? `Salesforce refused the Salesforce CLI app for your user (${description}). Your org must allow it: an administrator installs the Salesforce CLI connected app or grants you "Approve Uninstalled Connected Apps".`
84
+ : `Salesforce sign-in failed: ${description}`));
85
+ return;
86
+ }
87
+ const code = url.searchParams.get('code');
88
+ if (!code) {
89
+ reply('Salesforce did not return an authorization code.');
90
+ finish(new Error('Salesforce did not return an authorization code.'));
91
+ return;
92
+ }
93
+ reply('Salesforce sign-in received. You can close this tab and return to the terminal.');
94
+ finish(null, code);
95
+ });
96
+ server.once('error', (error) => finish(error.code === 'EADDRINUSE'
97
+ ? new Error(`Port ${port} is in use (Salesforce CLI may be signing in). Close it and retry.`)
98
+ : error));
99
+ server.listen(port, '127.0.0.1', () => {
100
+ timer = setTimeout(() => finish(new Error('Salesforce sign-in timed out.')), options.timeoutMs ?? 5 * 60_000);
101
+ options.log?.(`Sign in to Salesforce in the browser. If it does not open, visit:\n${authorize}`);
102
+ options.openBrowser(authorize.toString()).catch(() => { });
103
+ });
104
+ });
105
+ }
106
+ async function expectOk(response) {
107
+ if (response.ok)
108
+ return;
109
+ let error = {};
110
+ try {
111
+ error = await response.json();
112
+ }
113
+ catch { }
114
+ throw new Error(error.error ?? `Skillshare Salesforce API returned HTTP ${response.status}.`);
115
+ }
116
+ export function renderSalesforceStatus(status) {
117
+ const state = status.requiresReconnect
118
+ ? 'reconnect required — run skillshare salesforce login'
119
+ : status.configured
120
+ ? `connected${status.identity ? ` as ${status.identity}` : ''}`
121
+ : 'not connected — run skillshare salesforce login --instance <url>';
122
+ return [
123
+ `Salesforce: ${state}`,
124
+ ...(status.organization ? [` Instance: ${status.organization}`] : []),
125
+ ...(status.updatedAt ? [` Updated: ${new Date(status.updatedAt).toLocaleString()}`] : []),
126
+ ` MCP endpoint: ${status.endpoint}`,
127
+ ].join('\n');
128
+ }
129
+ export async function runSalesforceCommand(client, args, flags, openBrowser) {
130
+ const action = args[0];
131
+ const json = flags.json === 'true';
132
+ if (action === 'login') {
133
+ // The authorization code is a credential: send it only over HTTPS, or HTTP on loopback.
134
+ assertCredentialDestination(client.baseUrl);
135
+ let instance = flags.instance;
136
+ if (!instance) {
137
+ const status = await client.get(`${root}/settings`);
138
+ instance = status.organization ?? undefined;
139
+ }
140
+ if (!instance) {
141
+ throw new Error('Pass the org to sign in to: skillshare salesforce login --instance <url>, for example the Lightning URL from your browser (https://acme.lightning.force.com), its My Domain, or test.salesforce.com for a sandbox.');
142
+ }
143
+ const loginUrl = normalizeSalesforceLoginUrl(instance);
144
+ if (!loginUrl)
145
+ throw new Error(`${instance} is not a Salesforce login URL. Use your My Domain or Lightning URL, login.salesforce.com or test.salesforce.com.`);
146
+ const authorization = await captureSalesforceAuthorization({ loginUrl, openBrowser, log: console.log });
147
+ const response = await client.request(`${root}/connection`, {
148
+ method: 'PUT', headers: { 'Content-Type': 'application/json' },
149
+ body: JSON.stringify({ loginUrl, code: authorization.code, codeVerifier: authorization.codeVerifier }),
150
+ });
151
+ await expectOk(response);
152
+ const result = await response.json();
153
+ console.log(`Salesforce connected as ${result.identity} (${result.instanceUrl}).`);
154
+ console.log(`MCP endpoint: ${client.baseUrl}/salesforce/mcp`);
155
+ return;
156
+ }
157
+ if (action === 'status') {
158
+ const status = await client.get(`${root}/settings`);
159
+ console.log(json ? JSON.stringify(status, null, 2) : renderSalesforceStatus(status));
160
+ return;
161
+ }
162
+ if (action === 'test') {
163
+ const response = await client.request(`${root}/test`, { method: 'POST' });
164
+ const result = await response.json().catch(() => ({}));
165
+ if (json)
166
+ console.log(JSON.stringify(result, null, 2));
167
+ if (!response.ok || !result.success)
168
+ throw new Error(result.error ?? `Skillshare Salesforce API returned HTTP ${response.status}.`);
169
+ if (!json)
170
+ console.log(`Salesforce connection works${result.identity ? ` for ${result.identity}` : ''}.`);
171
+ return;
172
+ }
173
+ if (action === 'logout') {
174
+ const response = await client.request(`${root}/connection`, { method: 'DELETE' });
175
+ if (response.status !== 404)
176
+ await expectOk(response);
177
+ console.log('Salesforce disconnected from Skillshare and the sign-in revoked in Salesforce.');
178
+ return;
179
+ }
180
+ throw new Error('salesforce requires login, status, test or logout.');
181
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quadient/skillshare",
3
- "version": "1.11.0",
3
+ "version": "1.12.0",
4
4
  "description": "Skillshare CLI for installing and publishing Quadient skills",
5
5
  "type": "module",
6
6
  "bin": {
@@ -16,7 +16,7 @@
16
16
  "build": "rm -rf dist && tsc -p tsconfig.build.json",
17
17
  "start": "node ./dist/index.js",
18
18
  "prepublishOnly": "npm run build",
19
- "test": "tsx --test cli-args.test.ts install-files.test.ts output.test.ts pages.test.ts pages-secrets.test.ts pages-dev.test.ts teams-auth.test.ts teams-watch.test.ts teams-browser.test.ts agents.test.ts agents-update.test.ts"
19
+ "test": "tsx --test cli-args.test.ts install-files.test.ts output.test.ts pages.test.ts pages-secrets.test.ts pages-dev.test.ts teams-auth.test.ts teams-watch.test.ts teams-browser.test.ts salesforce.test.ts agents.test.ts agents-update.test.ts"
20
20
  },
21
21
  "publishConfig": {
22
22
  "access": "public"