@sortlist/cli 0.57.0 → 0.58.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/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/index.ts
2
- import { Command as Command8 } from "commander";
2
+ import { Command as Command10 } from "commander";
3
3
 
4
4
  // src/commands/config.ts
5
5
  import { Command } from "commander";
@@ -264,7 +264,7 @@ var ENVIRONMENTS = [
264
264
  }
265
265
  ];
266
266
  var configCommand = new Command("config").summary("View or update CLI configuration").description(
267
- "View or update CLI configuration\n\nManage your company context and credentials.\n\nExamples:\n sl config show See current endpoint and company\n sl config set company <slug|id> Act for that company on every command\n" + (isLocalDev ? " sl config set endpoint <url> Point to a custom endpoint\n" : "") + " sl config reset Clear all config and credentials"
267
+ "View or update CLI configuration\n\nManage your company context and credentials.\n\nExamples:\n sl config show See current endpoint and company\n sl use company <slug> Act for that company on every command\n" + (isLocalDev ? " sl config set endpoint <url> Point to a custom endpoint\n" : "") + " sl config reset Clear all config and credentials"
268
268
  );
269
269
  configCommand.command("show").description("Show current configuration").action(function() {
270
270
  const opts = this.optsWithGlobals();
@@ -291,11 +291,12 @@ configCommand.command("set <key> <value>").description(`Set a config value (${SE
291
291
  }
292
292
  saveConfig({ [key]: value });
293
293
  success(`Set ${key} = ${value}`);
294
+ if (key === "company") hint("`sl use company <slug>` does the same and checks you belong to it.");
294
295
  });
295
296
  if (isLocalDev) {
296
297
  for (const environment of ENVIRONMENTS) {
297
298
  configCommand.command(`use-${environment.name}`).description(`Point CLI to ${environment.name} (${environment.label})`).action(() => {
298
- saveConfig({ endpoint: environment.endpoint, tokenEndpoint: environment.tokenEndpoint });
299
+ saveConfig({ endpoint: environment.endpoint, tokenEndpoint: environment.tokenEndpoint, company: void 0 });
299
300
  success(`Endpoint set to ${environment.endpoint}`);
300
301
  info(`Token endpoint set to ${environment.tokenEndpoint}`);
301
302
  hint(`Run \`sl login\` to authenticate against ${environment.name}.`);
@@ -311,19 +312,8 @@ configCommand.command("reset").description("Reset all config and credentials").a
311
312
  hint("Run `sl login` to re-authenticate.");
312
313
  });
313
314
 
314
- // src/commands/dynamic.ts
315
- import { randomUUID } from "crypto";
316
- import { Command as Command2, Option } from "commander";
317
- import {
318
- isEnumType as isEnumType2,
319
- isInputObjectType,
320
- isInterfaceType,
321
- isListType as isListType2,
322
- isNonNullType as isNonNullType2,
323
- isObjectType as isObjectType2,
324
- isScalarType as isScalarType2,
325
- isUnionType
326
- } from "graphql";
315
+ // src/commands/connect-linkedin.ts
316
+ import { Command as Command2 } from "commander";
327
317
 
328
318
  // src/graphql/client.ts
329
319
  import { print } from "graphql";
@@ -431,7 +421,7 @@ function isCompanyId(value) {
431
421
  }
432
422
  }
433
423
  var COMPANY_BY_SLUG = `query CompanyBySlug($slug: String!) { company(slug: $slug) { id } }`;
434
- var PERSONAL_COMPANY = `query PersonalCompany { me { companies(first: 50) { nodes { id personal } } } }`;
424
+ var MY_COMPANIES = `query MyCompanies { me { companies(first: 50) { nodes { id slug name personal } } } }`;
435
425
  var resolved = /* @__PURE__ */ new Map();
436
426
  var personal;
437
427
  function pickPersonalCompanyId(data) {
@@ -439,15 +429,74 @@ function pickPersonalCompanyId(data) {
439
429
  return me?.companies?.nodes?.find((company) => company.personal === true)?.id;
440
430
  }
441
431
  function personalCompanyId() {
442
- personal ??= graphqlRaw(PERSONAL_COMPANY, void 0, { withoutCompany: true, throwOnError: true }).then(pickPersonalCompanyId).catch(() => void 0);
432
+ personal ??= graphqlRaw(MY_COMPANIES, void 0, { withoutCompany: true, throwOnError: true }).then(pickPersonalCompanyId).catch(() => void 0);
443
433
  return personal;
444
434
  }
435
+ function pickCompanies(data) {
436
+ const me = data.me;
437
+ return (me?.companies?.nodes ?? []).flatMap(
438
+ (node) => typeof node.id === "string" && typeof node.slug === "string" ? [{ id: node.id, slug: node.slug, name: node.name ?? node.slug, personal: node.personal === true }] : []
439
+ );
440
+ }
441
+ async function listCompanies(options = {}) {
442
+ const data = await graphqlRaw(MY_COMPANIES, void 0, {
443
+ endpoint: options.endpoint,
444
+ withoutCompany: true,
445
+ throwOnError: true
446
+ });
447
+ return pickCompanies(data);
448
+ }
449
+ var MY_COMPANIES_BILLING = `query MyCompaniesBilling { me { companies(first: 50) { nodes { id billingCustomer { creditBalance activeSubscription { plan periodicity } } } } } }`;
450
+ function pickCompanyBilling(data) {
451
+ const me = data.me;
452
+ const billing = /* @__PURE__ */ new Map();
453
+ for (const node of me?.companies?.nodes ?? []) {
454
+ if (typeof node.id !== "string") continue;
455
+ const customer = node.billingCustomer;
456
+ billing.set(
457
+ node.id,
458
+ customer ? {
459
+ kind: "customer",
460
+ creditBalance: customer.creditBalance ?? null,
461
+ plan: customer.activeSubscription?.plan ?? null,
462
+ periodicity: customer.activeSubscription?.periodicity ?? null
463
+ } : { kind: "none" }
464
+ );
465
+ }
466
+ return billing;
467
+ }
468
+ async function companiesBilling(options = {}) {
469
+ try {
470
+ const data = await graphqlRaw(MY_COMPANIES_BILLING, void 0, {
471
+ endpoint: options.endpoint,
472
+ withoutCompany: true,
473
+ throwOnError: true
474
+ });
475
+ return pickCompanyBilling(data);
476
+ } catch {
477
+ return /* @__PURE__ */ new Map();
478
+ }
479
+ }
480
+ function describeBilling(billing) {
481
+ if (!billing) return { credits: "unknown", plan: "unknown" };
482
+ if (billing.kind === "none") return { credits: "no billing account", plan: "none" };
483
+ const credits = billing.creditBalance === null ? "unknown" : `${billing.creditBalance} credits`;
484
+ if (!billing.plan) return { credits, plan: "none" };
485
+ const plan = billing.periodicity ? `${billing.plan} (${billing.periodicity.toLowerCase()})` : billing.plan;
486
+ return { credits, plan };
487
+ }
488
+ function matchCompany(companies, value) {
489
+ return companies.find((company) => company.slug === value || company.id === value);
490
+ }
491
+ function actingCompany(companies, chosen) {
492
+ return chosen ? matchCompany(companies, chosen) : companies.find((company) => company.personal);
493
+ }
445
494
  async function lookupCompanyId(slug) {
446
495
  const data = await graphqlRaw(COMPANY_BY_SLUG, { slug }, { withoutCompany: true });
447
496
  const id = data.company?.id;
448
497
  if (typeof id === "string") return id;
449
498
  error(`No company with slug "${slug}" among yours.`);
450
- hint("`sl hermes companies` lists the companies you belong to, with their slugs and ids.");
499
+ hint("`sl use company` lists the companies you belong to, with their slugs.");
451
500
  process.exit(2);
452
501
  }
453
502
  async function resolveCompanyId(opts) {
@@ -701,6 +750,7 @@ function codeOf(errors) {
701
750
  }
702
751
  var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
703
752
  var CALLBACK_STATUS_NOT_OK = "SUBGRAPH_HTTP_CALLBACK_STATUS_CODE_NOT_OK";
753
+ var QUERY_LIMIT_CODES = /* @__PURE__ */ new Set(["QUERY_TOO_COMPLEX", "QUERY_TOO_DEEP"]);
704
754
  function subrequestStatus(errors) {
705
755
  for (const { message, extensions } of errors) {
706
756
  const http = extensions?.http;
@@ -826,19 +876,19 @@ function reportGraphqlErrors(errors, options, attempt) {
826
876
  error(`${where} refused to act for your personal company.`);
827
877
  hint("A request that names no company acts for it, and your token does not list it as yours.");
828
878
  hint("On a local stack the token comes from a shared tenant and lists that environment's companies.");
829
- hint("Pass --company <slug|id>, or `sl config set company <slug|id>`; `sl hermes companies` lists them.");
879
+ hint("Pass --company <slug|id>, or `sl use company <slug>`; `sl use company` lists them.");
830
880
  } else if (company && UUID.test(company)) {
831
881
  error(`${where} refused ${company}: that is a raw uuid, not a company id.`);
832
- hint("Pass its slug, or the id `sl hermes companies` lists.");
882
+ hint("Pass its slug, or the id `sl use company` lists.");
833
883
  } else if (company) {
834
884
  error(`${where} refused to act for company ${company}.`);
835
885
  hint("Your token does not list that company, or Hermes no longer knows you as one of its members.");
836
886
  hint("`sl whoami` shows what the CLI is acting as;");
837
- hint("pick one of your companies with --company or `sl config set company <slug|id>`.");
887
+ hint("pick one of your companies with --company or `sl use company <slug>`.");
838
888
  } else {
839
889
  error(`${where} refused this request: it names no company to act for.`);
840
- hint("Pick one of your companies with --company or `sl config set company <slug|id>`;");
841
- hint("`sl hermes companies` lists them. Join one first if the list is empty.");
890
+ hint("Pick one of your companies with --company or `sl use company <slug>`;");
891
+ hint("`sl use company` lists them. Join one first if the list is empty.");
842
892
  }
843
893
  if (verbose) for (const gqlError of errors) info(`[debug] ${JSON.stringify(gqlError)}`);
844
894
  process.exit(4);
@@ -847,6 +897,10 @@ function reportGraphqlErrors(errors, options, attempt) {
847
897
  if (code !== null && code !== "DOWNSTREAM_SERVICE_ERROR") {
848
898
  error(humanise(code));
849
899
  for (const line of explainLines(errors)) info(` ${line}`);
900
+ if (QUERY_LIMIT_CODES.has(code)) {
901
+ hint("Ask for less in one call: fewer --fields (each nested list multiplies the cost),");
902
+ hint("or a smaller page with --first.");
903
+ }
850
904
  if (verbose) for (const gqlError of errors) info(`[debug] ${JSON.stringify(gqlError)}`);
851
905
  process.exit(1);
852
906
  }
@@ -888,7 +942,7 @@ async function requestHeaders(options, attempt) {
888
942
  if (!(options.authenticated ?? true)) return { headers, options };
889
943
  const { token, kind } = await resolveAccessToken(options, attempt);
890
944
  headers["Authorization"] = `Bearer ${token}`;
891
- const { companyId, personal: personal2 } = await actingCompany(options, kind, {
945
+ const { companyId, personal: personal2 } = await actingCompany2(options, kind, {
892
946
  named: async () => options.companyId ?? await resolveCompanyId({ ctx: getUserContext() }),
893
947
  personal: personalCompanyId
894
948
  });
@@ -896,7 +950,7 @@ async function requestHeaders(options, attempt) {
896
950
  if (attempt.verbose) info(`[debug] ${kind} token: ...${token.slice(-8)}`);
897
951
  return { headers, options: { ...options, actingForPersonalCompany: personal2 } };
898
952
  }
899
- async function actingCompany(options, kind, lookup) {
953
+ async function actingCompany2(options, kind, lookup) {
900
954
  if (options.withoutCompany) return { companyId: void 0, personal: false };
901
955
  const named = await lookup.named();
902
956
  if (named || kind !== "user") return { companyId: named, personal: false };
@@ -1036,6 +1090,330 @@ async function graphqlUnauthenticated(document, variables, endpoint) {
1036
1090
  return graphql(document, variables, { endpoint, authenticated: false });
1037
1091
  }
1038
1092
 
1093
+ // src/lib/linkedin-session.ts
1094
+ import { spawn } from "child_process";
1095
+ import fs6 from "fs";
1096
+ import os4 from "os";
1097
+ import path6 from "path";
1098
+ var SIGNED_IN_PAGE = /linkedin\.com\/(feed|in\/|mynetwork|messaging)/;
1099
+ var REQUIRED_COOKIES = ["li_at", "JSESSIONID"];
1100
+ var LINUX_COMMANDS = [
1101
+ "google-chrome",
1102
+ "google-chrome-stable",
1103
+ "chromium",
1104
+ "chromium-browser",
1105
+ "microsoft-edge",
1106
+ "microsoft-edge-stable",
1107
+ "brave-browser"
1108
+ ];
1109
+ var MAC_APPS = [
1110
+ "Google Chrome.app/Contents/MacOS/Google Chrome",
1111
+ "Chromium.app/Contents/MacOS/Chromium",
1112
+ "Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
1113
+ "Brave Browser.app/Contents/MacOS/Brave Browser"
1114
+ ];
1115
+ var WINDOWS_EXECUTABLES = [
1116
+ "Google\\Chrome\\Application\\chrome.exe",
1117
+ "Microsoft\\Edge\\Application\\msedge.exe",
1118
+ "BraveSoftware\\Brave-Browser\\Application\\brave.exe"
1119
+ ];
1120
+ function playwrightChromes(cacheRoot, exists) {
1121
+ if (!exists(cacheRoot)) return [];
1122
+ return fs6.readdirSync(cacheRoot).filter((name) => /^chromium-\d+$/.test(name)).sort().reverse().flatMap((name) => [
1123
+ path6.join(cacheRoot, name, "chrome-linux64", "chrome"),
1124
+ path6.join(cacheRoot, name, "chrome-linux", "chrome"),
1125
+ path6.join(cacheRoot, name, "chrome-mac", "Chromium.app", "Contents", "MacOS", "Chromium"),
1126
+ path6.join(cacheRoot, name, "chrome-win", "chrome.exe")
1127
+ ]);
1128
+ }
1129
+ function browserCandidates({ platform, env, home }) {
1130
+ if (platform === "darwin") {
1131
+ return [
1132
+ ...MAC_APPS.map((app) => path6.posix.join("/Applications", app)),
1133
+ ...MAC_APPS.map((app) => path6.posix.join(home, "Applications", app))
1134
+ ];
1135
+ }
1136
+ if (platform === "win32") {
1137
+ const roots = [env.PROGRAMFILES, env["PROGRAMFILES(X86)"], env.LOCALAPPDATA].filter(
1138
+ (root) => root != null && root !== ""
1139
+ );
1140
+ return roots.flatMap((root) => WINDOWS_EXECUTABLES.map((executable) => path6.win32.join(root, executable)));
1141
+ }
1142
+ const pathDirectories = (env.PATH ?? "").split(path6.delimiter).filter((directory) => directory !== "");
1143
+ return [
1144
+ ...LINUX_COMMANDS.flatMap((command) => pathDirectories.map((directory) => path6.posix.join(directory, command))),
1145
+ "/opt/google/chrome/chrome"
1146
+ ];
1147
+ }
1148
+ function isSandboxedPackage(browserPath) {
1149
+ return /^\/(snap|var\/lib\/flatpak|var\/lib\/snapd)\//.test(browserPath);
1150
+ }
1151
+ function installedBrowsers(current = { platform: process.platform, env: process.env, home: os4.homedir() }) {
1152
+ const exists = (file) => fs6.existsSync(file);
1153
+ const playwrightCaches = [
1154
+ path6.join(current.home, ".cache", "ms-playwright"),
1155
+ path6.join(current.home, "Library", "Caches", "ms-playwright"),
1156
+ path6.join(current.env.LOCALAPPDATA ?? path6.join(current.home, "AppData", "Local"), "ms-playwright")
1157
+ ];
1158
+ const candidates = [
1159
+ current.env.CHROME_PATH,
1160
+ ...browserCandidates(current),
1161
+ ...playwrightCaches.flatMap((cache) => playwrightChromes(cache, exists))
1162
+ ].filter((candidate) => candidate != null && candidate !== "" && exists(candidate));
1163
+ const resolved2 = [...new Set(candidates)].map((candidate) => ({ candidate, real: realPath(candidate) }));
1164
+ return {
1165
+ usable: resolved2.filter(({ real }) => !isSandboxedPackage(real)).map(({ candidate }) => candidate),
1166
+ sandboxed: resolved2.filter(({ real }) => isSandboxedPackage(real)).map(({ candidate }) => candidate)
1167
+ };
1168
+ }
1169
+ function realPath(file) {
1170
+ try {
1171
+ return fs6.realpathSync(file);
1172
+ } catch {
1173
+ return file;
1174
+ }
1175
+ }
1176
+ function hasDisplay(current = { platform: process.platform, env: process.env, home: os4.homedir() }) {
1177
+ if (current.platform !== "linux") return true;
1178
+ return Boolean(current.env.DISPLAY) || Boolean(current.env.WAYLAND_DISPLAY);
1179
+ }
1180
+ function sessionFrom(cookies, pageUrls, userAgent2) {
1181
+ const linkedinCookies = cookies.filter((cookie) => cookie.domain.endsWith("linkedin.com"));
1182
+ const names = new Set(linkedinCookies.map((cookie) => cookie.name));
1183
+ const signedIn = pageUrls.some((url) => SIGNED_IN_PAGE.test(url));
1184
+ if (!signedIn || !REQUIRED_COOKIES.every((name) => names.has(name))) return null;
1185
+ return { cookie: linkedinCookies.map((cookie) => `${cookie.name}=${cookie.value}`).join("; "), userAgent: userAgent2 };
1186
+ }
1187
+ var sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
1188
+ async function debuggingPort(profile) {
1189
+ const file = path6.join(profile, "DevToolsActivePort");
1190
+ for (let attempt = 0; attempt < 75; attempt += 1) {
1191
+ if (fs6.existsSync(file)) {
1192
+ const port = fs6.readFileSync(file, "utf8").split("\n")[0].trim();
1193
+ if (port !== "") return port;
1194
+ }
1195
+ await sleep(200);
1196
+ }
1197
+ return null;
1198
+ }
1199
+ async function connectDevtools(webSocketUrl) {
1200
+ const socket = new WebSocket(webSocketUrl);
1201
+ const pending = /* @__PURE__ */ new Map();
1202
+ let nextId = 0;
1203
+ socket.addEventListener("message", (message) => {
1204
+ const reply = JSON.parse(String(message.data));
1205
+ const resolve = reply.id == null ? void 0 : pending.get(reply.id);
1206
+ if (resolve != null && reply.id != null) {
1207
+ pending.delete(reply.id);
1208
+ resolve(reply);
1209
+ }
1210
+ });
1211
+ await new Promise((resolve, reject) => {
1212
+ socket.addEventListener("open", resolve, { once: true });
1213
+ socket.addEventListener("error", reject, { once: true });
1214
+ });
1215
+ return {
1216
+ send: (method) => new Promise((resolve) => {
1217
+ nextId += 1;
1218
+ pending.set(nextId, resolve);
1219
+ socket.send(JSON.stringify({ id: nextId, method, params: {} }));
1220
+ }),
1221
+ close: () => socket.close()
1222
+ };
1223
+ }
1224
+ async function stopBrowser(browser, profile) {
1225
+ if (browser.exitCode === null && browser.signalCode === null) {
1226
+ const exited = new Promise((resolve) => browser.once("exit", resolve));
1227
+ browser.kill();
1228
+ await Promise.race([exited, sleep(5e3)]);
1229
+ }
1230
+ await sleep(500);
1231
+ fs6.rmSync(profile, { recursive: true, force: true });
1232
+ }
1233
+ async function launch(browsers) {
1234
+ for (const browserPath of browsers) {
1235
+ const profile = fs6.mkdtempSync(path6.join(os4.tmpdir(), "sl-linkedin-"));
1236
+ const browser = spawn(
1237
+ browserPath,
1238
+ [
1239
+ `--user-data-dir=${profile}`,
1240
+ "--remote-debugging-port=0",
1241
+ "--no-first-run",
1242
+ "--no-default-browser-check",
1243
+ "https://www.linkedin.com/login"
1244
+ ],
1245
+ { stdio: "ignore" }
1246
+ );
1247
+ browser.on("error", () => {
1248
+ });
1249
+ const port = await debuggingPort(profile);
1250
+ if (port != null) return { browser, profile, port };
1251
+ await stopBrowser(browser, profile);
1252
+ }
1253
+ return null;
1254
+ }
1255
+ async function captureLinkedinSession(options) {
1256
+ const launched = await launch(options.browsers);
1257
+ if (launched == null) return { kind: "no-browser" };
1258
+ const { browser, profile, port } = launched;
1259
+ let connection = null;
1260
+ let linkedinCookies = 0;
1261
+ try {
1262
+ const version = await (await fetch(`http://127.0.0.1:${port}/json/version`)).json();
1263
+ connection = await connectDevtools(version.webSocketDebuggerUrl);
1264
+ options.onOpened();
1265
+ const deadline = Date.now() + options.timeoutSeconds * 1e3;
1266
+ while (Date.now() < deadline) {
1267
+ await sleep(2e3);
1268
+ const pages = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
1269
+ const cookies = (await connection.send("Storage.getCookies")).result?.cookies ?? [];
1270
+ linkedinCookies = cookies.filter((cookie) => cookie.domain.endsWith("linkedin.com")).length;
1271
+ const session = sessionFrom(
1272
+ cookies,
1273
+ pages.map((page) => page.url),
1274
+ version["User-Agent"]
1275
+ );
1276
+ if (session != null) return { kind: "signed-in", session };
1277
+ }
1278
+ return { kind: "timed-out", linkedinCookies };
1279
+ } finally {
1280
+ if (connection != null) {
1281
+ await Promise.race([connection.send("Browser.close"), sleep(2e3)]);
1282
+ connection.close();
1283
+ }
1284
+ await stopBrowser(browser, profile);
1285
+ }
1286
+ }
1287
+
1288
+ // src/commands/connect-linkedin.ts
1289
+ var AUTHENTICATE = `mutation SlCli_ConnectLinkedin($input: AuthenticateOutboundChannelAccountInput!) {
1290
+ authenticateOutboundChannelAccount(input: $input) { channelAccount { id status provider } }
1291
+ }`;
1292
+ var ACCOUNT_STATUS = `query SlCli_LinkedinAccountStatus($id: ID!) {
1293
+ outboundChannelAccount(id: $id) { id status provider identity { ... on LinkedinIdentity { displayName profileUrl } } }
1294
+ }`;
1295
+ var SETTLED = /* @__PURE__ */ new Set(["RUNNING", "DISCONNECTED", "REMOVED", "ERROR"]);
1296
+ var sleep2 = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
1297
+ async function sendSession(accountId, session, countryCode) {
1298
+ const debug = process.env.SL_DEBUG;
1299
+ delete process.env.SL_DEBUG;
1300
+ try {
1301
+ const linkedinCookie = {
1302
+ cookie: session.cookie,
1303
+ userAgent: session.userAgent,
1304
+ ...countryCode ? { countryCode } : {}
1305
+ };
1306
+ await graphqlRaw(
1307
+ AUTHENTICATE,
1308
+ { input: { id: accountId, credentials: { linkedinCookie } } },
1309
+ {
1310
+ throwOnError: true,
1311
+ subgraph: "outreach"
1312
+ }
1313
+ );
1314
+ } finally {
1315
+ if (debug !== void 0) process.env.SL_DEBUG = debug;
1316
+ }
1317
+ }
1318
+ async function settledAccount(accountId, seconds) {
1319
+ let account = null;
1320
+ for (let attempt = 0; attempt < seconds / 2; attempt += 1) {
1321
+ const data = await graphqlRaw(ACCOUNT_STATUS, { id: accountId }, { throwOnError: true, subgraph: "outreach" });
1322
+ account = data.outboundChannelAccount ?? null;
1323
+ if (account?.status != null && SETTLED.has(account.status)) return account;
1324
+ await sleep2(2e3);
1325
+ }
1326
+ return account;
1327
+ }
1328
+ function redacted(message, session) {
1329
+ const secrets = [
1330
+ session.cookie,
1331
+ ...session.cookie.split("; ").map((pair) => pair.slice(pair.indexOf("=") + 1))
1332
+ ].filter((secret) => secret.length >= 8);
1333
+ return secrets.reduce((text, secret) => text.split(secret).join("<cookie>"), message);
1334
+ }
1335
+ var connectLinkedinCommand = new Command2("connect-linkedin").summary("Sign a LinkedIn account in through the owner's own browser").description(
1336
+ "Sign a LinkedIn account in through the owner's own browser\n\nFor an account whose provider is LINKEDIN_DIRECT. Opens Chrome, Edge, Brave or Chromium on linkedin.com/login in a fresh, empty profile, waits for the owner to sign in there, verification code included, then sends that browser's LinkedIn session to Outreach and deletes the profile. The session is never printed or written anywhere else.\n\nNeeds a desktop session: run it on the computer the owner is sitting at. Set CHROME_PATH to pick the browser.\n\nExamples:\n sl outreach connect-linkedin <account id> BE\n sl outreach connect-linkedin <account id> --timeout 15"
1337
+ ).argument("<account-id>", "Global id of the outbound channel account to connect.").argument("[country-code]", "The owner's country, e.g. BE: Outreach uses a proxy from there.").option("--timeout <minutes>", "How long to wait for the sign-in.", "10").action(async function(accountId, countryCode) {
1338
+ const opts = this.optsWithGlobals();
1339
+ const json = isJsonMode(opts);
1340
+ const timeoutMinutes = Number(opts.timeout);
1341
+ if (!hasDisplay()) {
1342
+ error("No desktop session to open a browser in.");
1343
+ hint("Run this on the computer the account owner is sitting at, not over SSH or in a headless container.");
1344
+ process.exit(2);
1345
+ }
1346
+ const { usable, sandboxed } = installedBrowsers();
1347
+ if (usable.length === 0) {
1348
+ error("No Chrome, Edge, Brave or Chromium this command can drive was found.");
1349
+ if (sandboxed.length > 0) {
1350
+ hint(
1351
+ `${sandboxed.join(", ")} is a snap or Flatpak package, which cannot open a debugging port on a temporary profile.`
1352
+ );
1353
+ }
1354
+ hint("Install Google Chrome, or point CHROME_PATH at a Chromium-based browser.");
1355
+ process.exit(2);
1356
+ }
1357
+ const outcome = await captureLinkedinSession({
1358
+ browsers: usable,
1359
+ timeoutSeconds: (Number.isFinite(timeoutMinutes) && timeoutMinutes > 0 ? timeoutMinutes : 10) * 60,
1360
+ onOpened: () => {
1361
+ info(
1362
+ `A browser window is open on linkedin.com/login. Sign in there (waiting up to ${timeoutMinutes} minutes).`
1363
+ );
1364
+ }
1365
+ });
1366
+ if (outcome.kind === "no-browser") {
1367
+ error(`None of these browsers opened a debugging port: ${usable.join(", ")}.`);
1368
+ hint("Close every window of that browser and try again, or set CHROME_PATH to another one.");
1369
+ process.exit(2);
1370
+ }
1371
+ if (outcome.kind === "timed-out") {
1372
+ error(
1373
+ `No LinkedIn session before the timeout (${outcome.linkedinCookies} linkedin.com cookies seen). Nothing was sent.`
1374
+ );
1375
+ hint("Run the command again and finish the sign-in, verification code included, until the feed shows.");
1376
+ process.exit(5);
1377
+ }
1378
+ info("Signed in. Sending the session to Outreach; its value is never printed.");
1379
+ try {
1380
+ await sendSession(accountId, outcome.session, countryCode?.toUpperCase());
1381
+ } catch (caught) {
1382
+ const message = caught instanceof Error ? caught.message : String(caught);
1383
+ error(`Outreach did not accept the session: ${redacted(message, outcome.session)}`);
1384
+ if (caught instanceof GraphQLRequestError && caught.graphqlErrors != null) {
1385
+ for (const line of detailLines(caught.graphqlErrors)) info(` ${redacted(line, outcome.session)}`);
1386
+ }
1387
+ hint("`credentials.rejected` means LinkedIn ended that session: run the command again and sign in.");
1388
+ process.exit(1);
1389
+ }
1390
+ const account = await settledAccount(accountId, 30);
1391
+ if (json) {
1392
+ printJson(account);
1393
+ return;
1394
+ }
1395
+ if (account?.status === "RUNNING") {
1396
+ success(`Connected: ${account.identity?.displayName ?? accountId} is RUNNING.`);
1397
+ return;
1398
+ }
1399
+ info(`The account is ${account?.status ?? "unknown"} for now; Outreach checks the session in the background.`);
1400
+ hint(`Check again with: sl outreach outbound-channel-account --id ${accountId} --fields status,identity`);
1401
+ });
1402
+
1403
+ // src/commands/dynamic.ts
1404
+ import { randomUUID } from "crypto";
1405
+ import { Command as Command3, Option } from "commander";
1406
+ import {
1407
+ isEnumType as isEnumType2,
1408
+ isInputObjectType,
1409
+ isInterfaceType,
1410
+ isListType as isListType2,
1411
+ isNonNullType as isNonNullType2,
1412
+ isObjectType as isObjectType2,
1413
+ isScalarType as isScalarType2,
1414
+ isUnionType
1415
+ } from "graphql";
1416
+
1039
1417
  // src/graphql/query-builder.ts
1040
1418
  import {
1041
1419
  isAbstractType,
@@ -1217,6 +1595,12 @@ function connectionSelections(connection, nodeSelections, totalCount) {
1217
1595
  return lines;
1218
1596
  }
1219
1597
  var CONNECTION_PLUMBING = /* @__PURE__ */ new Set(["edges", "nodes", "pageInfo", "totalCount", "approximateTotalCount"]);
1598
+ function isConnectionExtraPath(connection, nodesType, path9) {
1599
+ const [top] = path9.split(".");
1600
+ if (CONNECTION_PLUMBING.has(top)) return false;
1601
+ if (isObjectType(nodesType) && nodesType.getFields()[top]) return false;
1602
+ return Boolean(connection.getFields()[top]);
1603
+ }
1220
1604
  function connectionExtras(connection) {
1221
1605
  return selectableFields(connection).filter((field) => !CONNECTION_PLUMBING.has(field.name)).flatMap((field) => {
1222
1606
  const named = unwrap(field.type);
@@ -1308,14 +1692,15 @@ function buildFieldsFromList(type, schema, requestedPaths, totalCount) {
1308
1692
  if (!isObjectType(type)) return [];
1309
1693
  const fields = type.getFields();
1310
1694
  const page = deliveredPageField(type);
1311
- const fieldPaths = page ? requestedPaths.map((path7) => fields[path7.split(".")[0]] ? path7 : `${page.name}.${path7}`) : requestedPaths;
1695
+ const fieldPaths = page ? requestedPaths.map((path9) => fields[path9.split(".")[0]] ? path9 : `${page.name}.${path9}`) : requestedPaths;
1312
1696
  if (isConnection(type)) {
1313
1697
  const nodesType = unwrap(fields.nodes.type);
1314
- const withId = isObjectType(nodesType) && nodesType.getFields().id && !fieldPaths.includes("id");
1698
+ const nodePaths = fieldPaths.filter((path9) => !isConnectionExtraPath(type, nodesType, path9));
1699
+ const withId = isObjectType(nodesType) && nodesType.getFields().id && !nodePaths.includes("id");
1315
1700
  const nodeSelections = buildFieldsFromList(
1316
1701
  nodesType,
1317
1702
  schema,
1318
- withId ? ["id", ...fieldPaths] : fieldPaths,
1703
+ withId ? ["id", ...nodePaths] : nodePaths,
1319
1704
  totalCount
1320
1705
  );
1321
1706
  return connectionSelections(type, nodeSelections, totalCount);
@@ -1599,7 +1984,8 @@ function coerceValue(raw, type, flagName) {
1599
1984
  if (enumList && !raw.trim().startsWith("[")) return coerceEnumList(raw, enumList, flagName);
1600
1985
  const enumValue = enumOf(type);
1601
1986
  if (enumValue) return coerceEnum(raw, enumValue, flagName);
1602
- if (isStructuredInput(type)) {
1987
+ const typeName = unwrap2(type).name;
1988
+ if (isStructuredInput(type) || typeName === "JSON" && /^\s*[[{]/.test(raw)) {
1603
1989
  try {
1604
1990
  return JSON.parse(raw);
1605
1991
  } catch (parseError) {
@@ -1608,7 +1994,6 @@ function coerceValue(raw, type, flagName) {
1608
1994
  );
1609
1995
  }
1610
1996
  }
1611
- const typeName = unwrap2(type).name;
1612
1997
  if (typeName === "Int") {
1613
1998
  const parsed = parseInt(raw, 10);
1614
1999
  if (Number.isNaN(parsed)) throw new Error(`--${flagName} expects an integer, got "${raw}".`);
@@ -1723,21 +2108,31 @@ function supersededBy(field, siblings) {
1723
2108
  const sibling = siblings[replacement];
1724
2109
  return sibling && !sibling.deprecationReason ? replacement : null;
1725
2110
  }
1726
- function hasExternalId(field) {
1727
- const args = getInputFields(field) ?? field.args;
1728
- return args.some((a) => a.name === "externalId");
2111
+ function argumentNames(field) {
2112
+ return new Set((getInputFields(field) ?? field.args).map((a) => a.name));
1729
2113
  }
2114
+ var RESULT_OF_MUTATION = /(?:result|outcome) of an? `(\w+)` call|then call `(\w+)`/;
1730
2115
  function resultSubscriptions(schema) {
1731
2116
  const pairs = /* @__PURE__ */ new Map();
1732
2117
  const mutations = schema.getMutationType()?.getFields() ?? {};
1733
2118
  for (const [name, field] of Object.entries(schema.getSubscriptionType()?.getFields() ?? {})) {
1734
- const mutation = field.description?.match(/(?:result|outcome) of an? `(\w+)` call/)?.[1];
2119
+ const match = field.description?.match(RESULT_OF_MUTATION);
2120
+ const mutation = match?.[1] ?? match?.[2];
1735
2121
  if (!mutation || !mutations[mutation]) continue;
1736
- if (!field.args.some((a) => a.name === "externalId") || !hasExternalId(mutations[mutation])) continue;
2122
+ const mutationArguments = argumentNames(mutations[mutation]);
2123
+ if (!field.args.some((a) => a.name === "externalId") || !mutationArguments.has("externalId")) continue;
2124
+ if (field.args.some((a) => isNonNullType2(a.type) && !mutationArguments.has(a.name))) continue;
1737
2125
  pairs.set(mutation, name);
1738
2126
  }
1739
2127
  return pairs;
1740
2128
  }
2129
+ function subscriptionVariablesFor(schema, subscription, mutationArguments, externalId) {
2130
+ const variables = {};
2131
+ for (const arg of schema.getSubscriptionType()?.getFields()[subscription]?.args ?? []) {
2132
+ if (mutationArguments[arg.name] !== void 0) variables[arg.name] = mutationArguments[arg.name];
2133
+ }
2134
+ return { ...variables, externalId };
2135
+ }
1741
2136
  function isRecord2(value) {
1742
2137
  return typeof value === "object" && value !== null;
1743
2138
  }
@@ -1847,7 +2242,7 @@ function buildCommand(schema, fieldName, kind, description, service, resultSubsc
1847
2242
  required: isNonNullType2(a.type),
1848
2243
  description: a.description
1849
2244
  }));
1850
- const cmd = new Command2(kebab(fieldName)).description(description);
2245
+ const cmd = new Command3(kebab(fieldName)).description(description);
1851
2246
  const requiresCompanyId = cliArgs.some((a) => a.name === "companyId" && a.required);
1852
2247
  for (const a of cliArgs) {
1853
2248
  const placeholder = enumListOf(a.type) ? "a,b|all|none..." : isStructuredInput(a.type) ? "json" : kebab(a.name);
@@ -1886,7 +2281,7 @@ function buildCommand(schema, fieldName, kind, description, service, resultSubsc
1886
2281
  const argumentCompanyId = typeof opts.companyId === "string" ? await resolveCompanyId({ company: opts.companyId, ctx }) : actingId;
1887
2282
  if (requiresCompanyId && !argumentCompanyId) {
1888
2283
  error("No company selected.");
1889
- hint("Pass --company-id <slug|id>, or act for one with --company or `sl config set company <slug|id>`.");
2284
+ hint("Pass --company-id <slug|id>, or act for one with --company or `sl use company <slug>`.");
1890
2285
  process.exit(2);
1891
2286
  }
1892
2287
  if (argumentCompanyId) opts.companyId = argumentCompanyId;
@@ -1951,7 +2346,8 @@ function buildCommand(schema, fieldName, kind, description, service, resultSubsc
1951
2346
  if (waiting && resultSubscription) {
1952
2347
  const seconds = secondsOption(opts.wait, DEFAULT_WAIT_SECONDS, "--wait");
1953
2348
  const externalId = opts.externalId;
1954
- const subscriptionVariables = { externalId };
2349
+ const mutationArguments = useInputWrapper ? variables.input : variables;
2350
+ const subscriptionVariables = subscriptionVariablesFor(schema, resultSubscription, mutationArguments, externalId);
1955
2351
  if (selection.fields && !selection.fields.includes(PAGE_STATUS_FIELD) && deliversFillingPages(schema, resultSubscription)) {
1956
2352
  selection.fields = [...selection.fields, PAGE_STATUS_FIELD];
1957
2353
  }
@@ -2058,7 +2454,7 @@ function groupOperationCommands(operations) {
2058
2454
  for (const operation of operations) {
2059
2455
  let group = services.get(operation.service);
2060
2456
  if (!group) {
2061
- group = new Command2(operation.service).description(`Operations served by ${operation.service}`);
2457
+ group = new Command3(operation.service).description(`Operations served by ${operation.service}`);
2062
2458
  services.set(operation.service, group);
2063
2459
  }
2064
2460
  group.addCommand(operation.command);
@@ -2145,7 +2541,7 @@ function formatOperationList(operations, search) {
2145
2541
  }
2146
2542
 
2147
2543
  // src/commands/login.ts
2148
- import { Command as Command3, Option as Option2 } from "commander";
2544
+ import { Command as Command4, Option as Option2 } from "commander";
2149
2545
 
2150
2546
  // src/graphql/operations/common.ts
2151
2547
  var Me = gql(`
@@ -2200,7 +2596,7 @@ function scopeForLogin(scope, scopeIsDefault, level) {
2200
2596
  const requested = scopeIsDefault ? `openid profile email ${[...USER_API_SCOPES, ...ELEVATION_API_SCOPES[level]].join(" ")}` : scope;
2201
2597
  return requested.split(" ").filter((name) => name && name !== "offline_access").join(" ");
2202
2598
  }
2203
- function sleep(ms) {
2599
+ function sleep3(ms) {
2204
2600
  return new Promise((resolve) => setTimeout(resolve, ms));
2205
2601
  }
2206
2602
  async function setupUserContext(endpoint) {
@@ -2222,12 +2618,12 @@ function reportScopeGrant(requestedScope, accessToken) {
2222
2618
  hint("permissions and drops the rest silently \u2014 this is a role assignment in the");
2223
2619
  hint("tenant you logged into, not a CLI setting. Ask an administrator, then re-run `sl login`.");
2224
2620
  }
2225
- var loginCommand = new Command3("login").summary("Log in to your Sortlist account").description(
2621
+ var loginCommand = new Command4("login").summary("Log in to your Sortlist account").description(
2226
2622
  `Log in to your Sortlist account
2227
2623
 
2228
2624
  Opens a browser to complete authentication, then saves your
2229
2625
  credentials locally. To act for one of your companies, pass
2230
- --company or run \`sl config set company <slug>\`.
2626
+ --company or run \`sl use company <slug>\`.
2231
2627
 
2232
2628
  Examples:
2233
2629
  sl login Log in with the user scopes, no staff scope
@@ -2270,7 +2666,7 @@ commands fall back to the plain login.`
2270
2666
  let interval = device.interval * 1e3;
2271
2667
  const deadline = Date.now() + device.expiresIn * 1e3;
2272
2668
  while (Date.now() < deadline) {
2273
- await sleep(interval);
2669
+ await sleep3(interval);
2274
2670
  const tokenData = await graphqlUnauthenticated(
2275
2671
  DeviceToken,
2276
2672
  { input: { deviceCode: device.deviceCode } },
@@ -2333,8 +2729,8 @@ commands fall back to the plain login.`
2333
2729
  });
2334
2730
 
2335
2731
  // src/commands/logout.ts
2336
- import { Command as Command4 } from "commander";
2337
- var logoutCommand = new Command4("logout").summary("Log out and remove stored credentials").description(
2732
+ import { Command as Command5 } from "commander";
2733
+ var logoutCommand = new Command5("logout").summary("Log out and remove stored credentials").description(
2338
2734
  "Log out and remove stored credentials\n\nDeletes the saved tokens from ~/.sortlist/credentials.json and\nopens the Auth0 logout URL in your browser so the next `sl login`\ndoesn't silently reuse the previous account.\n\nExamples:\n sl logout Clear credentials and log out of Auth0\n sl logout --no-browser Only clear local credentials\n sl logout --elevated Drop the elevated token, keep your session"
2339
2735
  ).option("--no-browser", "Skip opening the Auth0 logout URL in a browser").option("--elevated", "Only drop the token from `sl login --elevate`").action(async function() {
2340
2736
  const opts = this.optsWithGlobals();
@@ -2365,9 +2761,162 @@ var logoutCommand = new Command4("logout").summary("Log out and remove stored cr
2365
2761
  hint("Run `sl login` to authenticate again.");
2366
2762
  });
2367
2763
 
2764
+ // src/commands/skill.ts
2765
+ import { Command as Command6 } from "commander";
2766
+
2767
+ // src/lib/skills.ts
2768
+ import { randomUUID as randomUUID2 } from "crypto";
2769
+ import fs7 from "fs";
2770
+ import os5 from "os";
2771
+ import path7 from "path";
2772
+ var bundledSkillsRoot = path7.join(packageRoot, "skills");
2773
+ var SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
2774
+ function listFiles(directory, prefix = "") {
2775
+ if (!fs7.existsSync(directory)) return [];
2776
+ return fs7.readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
2777
+ if (entry.isSymbolicLink())
2778
+ throw new Error(`Refusing a symbolic link inside a skill: ${path7.join(prefix, entry.name)}`);
2779
+ const relative = path7.posix.join(prefix, entry.name);
2780
+ return entry.isDirectory() ? listFiles(path7.join(directory, entry.name), relative) : [relative];
2781
+ }).sort();
2782
+ }
2783
+ function frontmatterDescription(skillMarkdown) {
2784
+ const frontmatter = /^---\n([\s\S]*?)\n---/.exec(skillMarkdown)?.[1] ?? "";
2785
+ return /^description:\s*(.+)$/m.exec(frontmatter)?.[1]?.trim() ?? "";
2786
+ }
2787
+ function readBundledSkills(root = bundledSkillsRoot) {
2788
+ if (!fs7.existsSync(root)) throw new Error(`No bundled skills found at ${root}`);
2789
+ return fs7.readdirSync(root, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => entry.name).sort().map((name) => {
2790
+ if (!SKILL_NAME.test(name)) throw new Error(`Invalid skill name: ${name}`);
2791
+ const folder = path7.join(root, name);
2792
+ const files = new Map(
2793
+ listFiles(folder).map((relative) => [relative, fs7.readFileSync(path7.join(folder, relative))])
2794
+ );
2795
+ const entrypoint = files.get("SKILL.md");
2796
+ if (!entrypoint) throw new Error(`Skill ${name} has no SKILL.md`);
2797
+ return { name, description: frontmatterDescription(entrypoint.toString("utf-8")), files };
2798
+ });
2799
+ }
2800
+ function defaultSkillsDestination(project, home = os5.homedir(), configDir = process.env.CLAUDE_CONFIG_DIR) {
2801
+ if (project) return path7.join(path7.resolve(project), ".claude", "skills");
2802
+ return path7.join(configDir ? path7.resolve(configDir) : path7.join(home, ".claude"), "skills");
2803
+ }
2804
+ function isIdentical(folder, skill) {
2805
+ const installed = listFiles(folder);
2806
+ const bundled = [...skill.files.keys()].sort();
2807
+ if (JSON.stringify(installed) !== JSON.stringify(bundled)) return false;
2808
+ return bundled.every((relative) => fs7.readFileSync(path7.join(folder, relative)).equals(skill.files.get(relative)));
2809
+ }
2810
+ function planInstall(skills, destination, replace) {
2811
+ return skills.map((skill) => {
2812
+ const folder = path7.join(destination, skill.name);
2813
+ if (!fs7.existsSync(folder)) return { name: skill.name, action: "install", folder };
2814
+ const stat = fs7.lstatSync(folder);
2815
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
2816
+ throw new Error(`${folder} exists and is not a skill folder. Move it away, then install again.`);
2817
+ }
2818
+ if (isIdentical(folder, skill)) return { name: skill.name, action: "unchanged", folder };
2819
+ if (!replace) {
2820
+ throw new Error(`${folder} differs from the bundled skill. Pass --replace to back it up and replace it.`);
2821
+ }
2822
+ return { name: skill.name, action: "replace", folder };
2823
+ });
2824
+ }
2825
+ function installSkills(options) {
2826
+ const skills = readBundledSkills(options.root);
2827
+ const destination = path7.resolve(options.destination);
2828
+ const plan = planInstall(skills, destination, options.replace ?? false);
2829
+ const result = { destination, dryRun: options.dryRun ?? false, skills: plan, backups: [] };
2830
+ if (result.dryRun || plan.every((item) => item.action === "unchanged")) return result;
2831
+ fs7.mkdirSync(destination, { recursive: true });
2832
+ const stage = fs7.mkdtempSync(path7.join(destination, ".sl-skill-stage-"));
2833
+ try {
2834
+ for (const item of plan) {
2835
+ if (item.action === "unchanged") continue;
2836
+ const skill = skills.find((candidate) => candidate.name === item.name);
2837
+ for (const [relative, bytes] of skill.files) {
2838
+ const target = path7.join(stage, item.name, relative);
2839
+ fs7.mkdirSync(path7.dirname(target), { recursive: true });
2840
+ fs7.writeFileSync(target, bytes);
2841
+ }
2842
+ }
2843
+ for (const item of plan) {
2844
+ if (item.action === "unchanged") continue;
2845
+ let backup;
2846
+ if (item.action === "replace") {
2847
+ const archive = path7.join(path7.dirname(destination), ".sl-skill-backups", randomUUID2());
2848
+ fs7.mkdirSync(archive, { recursive: true, mode: 448 });
2849
+ backup = path7.join(archive, item.name);
2850
+ fs7.renameSync(item.folder, backup);
2851
+ result.backups.push(backup);
2852
+ }
2853
+ try {
2854
+ fs7.renameSync(path7.join(stage, item.name), item.folder);
2855
+ } catch (err) {
2856
+ if (backup) fs7.renameSync(backup, item.folder);
2857
+ throw err;
2858
+ }
2859
+ }
2860
+ } finally {
2861
+ fs7.rmSync(stage, { recursive: true, force: true });
2862
+ }
2863
+ return result;
2864
+ }
2865
+
2866
+ // src/commands/skill.ts
2867
+ var skillCommand = new Command6("skill").description(
2868
+ "Install the agent skills that teach Claude Code how to drive sl\n\nExamples:\n sl skill list The skills bundled with this version\n sl skill install Into ~/.claude/skills ($CLAUDE_CONFIG_DIR/skills when set)\n sl skill install --project . Into ./.claude/skills, for this project only"
2869
+ );
2870
+ skillCommand.command("list").description("List the skills bundled with this version of sl").action(function() {
2871
+ try {
2872
+ const skills = readBundledSkills().map(({ name, description }) => ({ name, description }));
2873
+ if (isJsonMode(this.optsWithGlobals())) {
2874
+ printJson(skills);
2875
+ return;
2876
+ }
2877
+ for (const { name, description } of skills) info(`${name}
2878
+ ${description}
2879
+ `);
2880
+ } catch (err) {
2881
+ error(err.message);
2882
+ process.exit(1);
2883
+ }
2884
+ });
2885
+ skillCommand.command("install").description(
2886
+ "Copy the bundled skills where Claude Code reads them\n\nInstalls into ~/.claude/skills, or $CLAUDE_CONFIG_DIR/skills when it is set, unless\n--project or --destination says otherwise.\nA skill already there and identical is left alone. One that differs is refused\nunless --replace, which backs it up first. Start a new Claude Code session afterwards:\nskills are read when a session starts."
2887
+ ).option("--project <dir>", "Install into <dir>/.claude/skills instead of your home directory").option("--destination <dir>", "Install into this skills directory").option("--replace", "Back up and replace skills that differ from the bundled ones").option("--dry-run", "Show what would change without writing anything").action(function() {
2888
+ const opts = this.optsWithGlobals();
2889
+ if (opts.project && opts.destination) {
2890
+ error("Pass either --project or --destination, not both.");
2891
+ process.exit(2);
2892
+ }
2893
+ try {
2894
+ const result = installSkills({
2895
+ destination: opts.destination ?? defaultSkillsDestination(opts.project),
2896
+ replace: opts.replace,
2897
+ dryRun: opts.dryRun
2898
+ });
2899
+ if (isJsonMode(opts)) {
2900
+ printJson(result);
2901
+ return;
2902
+ }
2903
+ for (const item of result.skills) {
2904
+ const verb = result.dryRun ? `would ${item.action}` : item.action === "unchanged" ? "already installed" : `${item.action}ed`;
2905
+ info(`${item.name}: ${verb} (${item.folder})`);
2906
+ }
2907
+ for (const backup of result.backups) hint(`Previous version kept at ${backup}`);
2908
+ if (!result.dryRun && result.skills.some((item) => item.action !== "unchanged")) {
2909
+ success("Skills installed. Start a new Claude Code session to load them.");
2910
+ }
2911
+ } catch (err) {
2912
+ error(err.message);
2913
+ process.exit(1);
2914
+ }
2915
+ });
2916
+
2368
2917
  // src/commands/token.ts
2369
- import { Command as Command5 } from "commander";
2370
- var tokenCommand = new Command5("token").summary("Print the current access token to stdout").description(
2918
+ import { Command as Command7 } from "commander";
2919
+ var tokenCommand = new Command7("token").summary("Print the current access token to stdout").description(
2371
2920
  `Print the current access token to stdout
2372
2921
 
2373
2922
  Prints the application credential's token when SORTLIST_CLIENT_ID and
@@ -2404,7 +2953,7 @@ Examples:
2404
2953
  });
2405
2954
 
2406
2955
  // src/commands/use.ts
2407
- import { Command as Command6 } from "commander";
2956
+ import { Command as Command8 } from "commander";
2408
2957
 
2409
2958
  // src/lib/application.ts
2410
2959
  function isApplicationId(value) {
@@ -2463,8 +3012,8 @@ var REVOKE = `
2463
3012
  revokeApplicationCredential(input: { credentialId: $credentialId }) { revokedAt }
2464
3013
  }
2465
3014
  `;
2466
- var useCommand = new Command6("use").summary("Act as an application, or go back to acting as yourself").description(
2467
- "Act as an application, or go back to acting as yourself\n\nExamples:\n sl use application testapp Act as your application testapp for one token lifetime\n sl use application acme/testapp The same, naming the company it belongs to\n sl use application <id> The same, by the application's id\n sl use me Go back to acting as yourself"
3015
+ var useCommand = new Command8("use").summary("Choose the company you act for, act as an application, or go back to yourself").description(
3016
+ "Choose the company you act for, act as an application, or go back to acting as yourself\n\nExamples:\n sl use company List your companies and the one you act for\n sl use company acme Act for acme, and bill it, on every command\n sl use company --personal Act for your personal company again\n sl use application testapp Act as your application testapp for one token lifetime\n sl use application acme/testapp The same, naming the company it belongs to\n sl use application <id> The same, by the application's id\n sl use me Go back to acting as yourself"
2468
3017
  );
2469
3018
  useCommand.command("application <application>").description(
2470
3019
  "Act as an application for one token lifetime. Name it by slug, which is looked up in the company you act for, by <company>/<slug>, or by its id"
@@ -2515,6 +3064,76 @@ useCommand.command("application <application>").description(
2515
3064
  hint("Managing companies, applications and credentials is now out of reach: Hermes refuses");
2516
3065
  hint("its own tokens on its management API. Run `sl use me` to act as yourself again.");
2517
3066
  });
3067
+ useCommand.command("company [company]").description(
3068
+ "Choose the company every command acts for and bills, by slug or id. Without one, list your companies. --company on a single command still overrides it"
3069
+ ).option("--personal", "Act for your personal company again").action(async function(value) {
3070
+ const opts = this.optsWithGlobals();
3071
+ if (value && opts.personal) {
3072
+ error("Pass either a company or --personal, not both.");
3073
+ process.exit(2);
3074
+ }
3075
+ let companies;
3076
+ let billing;
3077
+ try {
3078
+ [companies, billing] = await Promise.all([
3079
+ listCompanies({ endpoint: opts.endpoint }),
3080
+ companiesBilling({ endpoint: opts.endpoint })
3081
+ ]);
3082
+ } catch (err) {
3083
+ error(`Could not list your companies: ${err.message}`);
3084
+ hint("Run `sl login` if your session expired.");
3085
+ process.exit(1);
3086
+ }
3087
+ if (opts.personal) {
3088
+ saveConfig({ company: void 0 });
3089
+ const personal2 = actingCompany(companies, void 0);
3090
+ success(
3091
+ personal2 ? `Now acting for your personal company, ${companyLabel(personal2)}.` : "Now acting for your personal company."
3092
+ );
3093
+ return;
3094
+ }
3095
+ if (!value) {
3096
+ listChosenCompany(companies, billing, getUserContext().company, isJsonMode(opts));
3097
+ return;
3098
+ }
3099
+ const company = matchCompany(companies, value);
3100
+ if (!company) {
3101
+ error(`You are not a member of a company "${value}".`);
3102
+ hint("`sl use company` lists the companies you belong to, with their slugs.");
3103
+ process.exit(2);
3104
+ }
3105
+ saveConfig({ company: company.slug });
3106
+ success(`Now acting for ${companyLabel(company)} on every command.`);
3107
+ const { credits, plan } = describeBilling(billing.get(company.id));
3108
+ info(` ${credits}, plan: ${plan}`);
3109
+ hint("What a command reveals or sends is billed to this company. `sl use company --personal` goes back.");
3110
+ });
3111
+ function companyLabel(company) {
3112
+ return `${company.name} (${company.slug})`;
3113
+ }
3114
+ function listChosenCompany(companies, billing, chosen, json) {
3115
+ const current = actingCompany(companies, chosen);
3116
+ if (json) {
3117
+ printJson(
3118
+ companies.map((company) => ({
3119
+ ...company,
3120
+ current: company.id === current?.id,
3121
+ billing: billing.get(company.id) ?? null
3122
+ }))
3123
+ );
3124
+ return;
3125
+ }
3126
+ const width = Math.max(...companies.map((company) => company.slug.length));
3127
+ for (const company of companies) {
3128
+ const acting = company.id === current?.id;
3129
+ const marks = [acting && "acting for", company.personal && "personal"].filter(Boolean).join(", ");
3130
+ const suffix = marks ? ` (${marks})` : "";
3131
+ const { credits, plan } = describeBilling(billing.get(company.id));
3132
+ info(`${acting ? "*" : " "} ${company.slug.padEnd(width)} ${credits}, plan: ${plan} ${company.name}${suffix}`);
3133
+ }
3134
+ if (chosen && !current) hint(`The saved company "${chosen}" is not one of yours any more.`);
3135
+ hint("`sl use company <slug>` acts for another one.");
3136
+ }
2518
3137
  useCommand.command("me").description("Go back to acting as yourself").action(() => {
2519
3138
  if (clearApplicationSession()) {
2520
3139
  success("Now acting as yourself again.");
@@ -2541,7 +3160,7 @@ async function applicationIdFor(reference, opts) {
2541
3160
  error(
2542
3161
  company ? `You do not belong to a company "${company}".` : "You have no personal company to look the application up in."
2543
3162
  );
2544
- hint("`sl hermes companies` lists the companies you belong to, with their slugs.");
3163
+ hint("`sl use company` lists the companies you belong to, with their slugs.");
2545
3164
  } else {
2546
3165
  error(`No application "${named.slug}" in ${found.company.slug ?? "that company"}.`);
2547
3166
  hint(APPLICATIONS_HINT);
@@ -2550,7 +3169,7 @@ async function applicationIdFor(reference, opts) {
2550
3169
  }
2551
3170
 
2552
3171
  // src/commands/whoami.ts
2553
- import { Command as Command7 } from "commander";
3172
+ import { Command as Command9 } from "commander";
2554
3173
  function apiScopes(accessToken) {
2555
3174
  return accessToken ? grantedScopes(accessToken).filter((scope) => scope.includes("/")) : [];
2556
3175
  }
@@ -2558,7 +3177,7 @@ function currentElevation() {
2558
3177
  const elevated = loadElevatedCredentials();
2559
3178
  return elevated ? { level: elevated.level, until: new Date(elevated.expiresAt * 1e3).toISOString() } : null;
2560
3179
  }
2561
- var whoamiCommand = new Command7("whoami").summary("Show what the CLI is currently acting as").description(
3180
+ var whoamiCommand = new Command9("whoami").summary("Show what the CLI is currently acting as").description(
2562
3181
  "Show what the CLI is currently acting as\n\nReports a person or an application, matching what every command\nauthenticates as. Use --json for machine-readable output.\n\nExamples:\n sl whoami Show the current identity\n sl whoami --json Output the full object as JSON"
2563
3182
  ).action(async function() {
2564
3183
  const opts = this.optsWithGlobals();
@@ -2641,8 +3260,17 @@ var whoamiCommand = new Command7("whoami").summary("Show what the CLI is current
2641
3260
  }
2642
3261
  const elevation = currentElevation();
2643
3262
  const scopes = apiScopes(storedUserAccessToken());
3263
+ const chosen = opts.company ?? getUserContext().company;
3264
+ const { company, billing } = await companyActedFor(chosen, opts.endpoint);
3265
+ const { credits, plan } = describeBilling(billing);
2644
3266
  if (isJsonMode(opts)) {
2645
- printJson({ kind: "person", ...user, elevation, scopes });
3267
+ printJson({
3268
+ kind: "person",
3269
+ ...user,
3270
+ company: company && { ...company, billing: billing ?? null },
3271
+ elevation,
3272
+ scopes
3273
+ });
2646
3274
  return;
2647
3275
  }
2648
3276
  info(elevation ? `Acting as yourself, elevated to ${elevation.level}.
@@ -2652,21 +3280,33 @@ var whoamiCommand = new Command7("whoami").summary("Show what the CLI is current
2652
3280
  name: personName(user),
2653
3281
  email: user.email,
2654
3282
  id: user.id,
3283
+ "acts for company": company ? `${company.slug} (${company.name}${company.personal ? ", personal" : ""})` : chosen ?? "none",
3284
+ ...company && { credits, plan },
2655
3285
  ...elevation && { "elevated until": elevation.until },
2656
3286
  scopes: scopes.length > 0 ? scopes.join(" ") : "none"
2657
3287
  }) ?? ""
2658
3288
  );
2659
3289
  if (elevation) hint("Run `sl logout --elevated` to drop the elevation now.");
3290
+ hint("`sl use company` lists your companies and chooses the one you act for.");
2660
3291
  });
3292
+ async function companyActedFor(chosen, endpoint) {
3293
+ try {
3294
+ const [companies, billing] = await Promise.all([listCompanies({ endpoint }), companiesBilling({ endpoint })]);
3295
+ const company = actingCompany(companies, chosen) ?? null;
3296
+ return { company, billing: company ? billing.get(company.id) : void 0 };
3297
+ } catch {
3298
+ return { company: null, billing: void 0 };
3299
+ }
3300
+ }
2661
3301
 
2662
3302
  // src/graphql/introspection.ts
2663
3303
  import { createHash } from "crypto";
2664
- import fs6 from "fs";
2665
- import os4 from "os";
2666
- import path6 from "path";
3304
+ import fs8 from "fs";
3305
+ import os6 from "os";
3306
+ import path8 from "path";
2667
3307
  import { buildClientSchema, getIntrospectionQuery } from "graphql";
2668
- var CACHE_DIR = path6.join(os4.homedir(), ".sortlist");
2669
- var CACHE_PATH = path6.join(CACHE_DIR, "schema.json");
3308
+ var CACHE_DIR = path8.join(os6.homedir(), ".sortlist");
3309
+ var CACHE_PATH = path8.join(CACHE_DIR, "schema.json");
2670
3310
  var CACHE_TTL_MS = 60 * 60 * 1e3;
2671
3311
  var cached2 = null;
2672
3312
  function tokenFingerprint(token) {
@@ -2675,7 +3315,7 @@ function tokenFingerprint(token) {
2675
3315
  }
2676
3316
  function readCache(endpoint, token) {
2677
3317
  try {
2678
- const text = fs6.readFileSync(CACHE_PATH, "utf-8");
3318
+ const text = fs8.readFileSync(CACHE_PATH, "utf-8");
2679
3319
  const envelope = JSON.parse(text);
2680
3320
  if (envelope.endpoint !== endpoint) return null;
2681
3321
  if (envelope.tokenFingerprint !== tokenFingerprint(token)) return null;
@@ -2688,8 +3328,8 @@ function readCache(endpoint, token) {
2688
3328
  }
2689
3329
  function writeCache(endpoint, token, introspection, raw) {
2690
3330
  try {
2691
- if (!fs6.existsSync(CACHE_DIR)) {
2692
- fs6.mkdirSync(CACHE_DIR, { recursive: true });
3331
+ if (!fs8.existsSync(CACHE_DIR)) {
3332
+ fs8.mkdirSync(CACHE_DIR, { recursive: true });
2693
3333
  }
2694
3334
  const envelope = {
2695
3335
  endpoint,
@@ -2698,7 +3338,7 @@ function writeCache(endpoint, token, introspection, raw) {
2698
3338
  introspection,
2699
3339
  raw
2700
3340
  };
2701
- fs6.writeFileSync(CACHE_PATH, JSON.stringify(envelope));
3341
+ fs8.writeFileSync(CACHE_PATH, JSON.stringify(envelope));
2702
3342
  } catch {
2703
3343
  }
2704
3344
  }
@@ -2801,7 +3441,7 @@ function build(introspection, raw) {
2801
3441
  }
2802
3442
  function discardCache() {
2803
3443
  try {
2804
- fs6.unlinkSync(CACHE_PATH);
3444
+ fs8.unlinkSync(CACHE_PATH);
2805
3445
  } catch {
2806
3446
  }
2807
3447
  }
@@ -2932,7 +3572,7 @@ grouped under the service that serves it, Hermes's account and company operation
2932
3572
  }
2933
3573
  return parts.join("\n\n");
2934
3574
  }
2935
- var program = new Command8().name("sl").configureOutput({
3575
+ var program = new Command10().name("sl").configureOutput({
2936
3576
  writeOut: (str) => process.stdout.write(colorizeHelp(str)),
2937
3577
  writeErr: (str) => process.stderr.write(colorizeHelp(str))
2938
3578
  }).description(BASE_DESCRIPTION).version(pkg.version).option("--endpoint <url>", "Override the federation endpoint URL").option("--company <slug|id>", "Act for this company, by slug or id; must be one you belong to").option("--json", "Output as JSON (auto-enabled when stdout is not a TTY)").option("--no-color", "Disable colored output");
@@ -2942,7 +3582,8 @@ program.addCommand(whoamiCommand);
2942
3582
  program.addCommand(tokenCommand);
2943
3583
  program.addCommand(useCommand);
2944
3584
  program.addCommand(configCommand);
2945
- var schemaCommand = new Command8("schema").description("Manage the cached GraphQL schema");
3585
+ program.addCommand(skillCommand);
3586
+ var schemaCommand = new Command10("schema").description("Manage the cached GraphQL schema");
2946
3587
  schemaCommand.command("refresh").description("Force-refresh the cached schema from the federation endpoint").action(async function() {
2947
3588
  const opts = this.optsWithGlobals();
2948
3589
  try {
@@ -2979,19 +3620,20 @@ try {
2979
3620
  const { schema, fieldServices, fieldScopes } = await getIntrospectedSchema(endpointOverride);
2980
3621
  const operations = buildOperationCommands(schema, fieldServices, fieldScopes);
2981
3622
  for (const command of groupOperationCommands(operations)) {
3623
+ if (command.name() === "outreach") command.addCommand(connectLinkedinCommand);
2982
3624
  program.addCommand(command);
2983
3625
  }
2984
3626
  for (const command of legacyTopLevelCommands(schema, fieldServices, fieldScopes)) {
2985
3627
  program.addCommand(command, { hidden: true });
2986
3628
  }
2987
- const operationsCommand = new Command8("operations").summary("List every federation operation available as a command").option("--search <text>", "Filter by operation or subgraph name").action(function() {
3629
+ const operationsCommand = new Command10("operations").summary("List every federation operation available as a command").option("--search <text>", "Filter by operation or subgraph name").action(function() {
2988
3630
  info(formatOperationList(operations, this.opts().search));
2989
3631
  });
2990
3632
  program.addCommand(operationsCommand);
2991
3633
  program.description(buildRootDescription(operations.length));
2992
3634
  } catch (err) {
2993
3635
  const message = err.message;
2994
- const offline = ["login", "logout", "config", "token", "whoami", "schema"];
3636
+ const offline = ["login", "logout", "config", "token", "whoami", "schema", "skill"];
2995
3637
  if (!process.argv.some((a) => offline.includes(a))) {
2996
3638
  error(`Could not fetch schema: ${message}`);
2997
3639
  hint("Check your network connection and endpoint: sl config show");