@sortlist/cli 0.56.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,7 +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";
704
- var FORBIDDEN_COMPANY = "FORBIDDEN_COMPANY";
753
+ var QUERY_LIMIT_CODES = /* @__PURE__ */ new Set(["QUERY_TOO_COMPLEX", "QUERY_TOO_DEEP"]);
705
754
  function subrequestStatus(errors) {
706
755
  for (const { message, extensions } of errors) {
707
756
  const http = extensions?.http;
@@ -777,12 +826,6 @@ function serviceOf(errors) {
777
826
  }
778
827
  return null;
779
828
  }
780
- function refusedForNamingNoCompany(errors, namedNoCompany) {
781
- if (!namedNoCompany) return false;
782
- const status = subrequestStatus(errors);
783
- const maskedCallbackRefusal = status === null && codeOf(errors) === CALLBACK_STATUS_NOT_OK;
784
- return status === 403 || maskedCallbackRefusal || codeOf(errors) === FORBIDDEN_COMPANY;
785
- }
786
829
  function hasResolvedField(data) {
787
830
  if (data === null || data === void 0) return false;
788
831
  return Object.values(data).some((value) => value !== null);
@@ -831,21 +874,21 @@ function reportGraphqlErrors(errors, options, attempt) {
831
874
  const company = options.company ?? getUserContext().company ?? options.companyId;
832
875
  if (options.actingForPersonalCompany) {
833
876
  error(`${where} refused to act for your personal company.`);
834
- hint("It was tried because the request named no company, and your token does not list it as yours.");
877
+ hint("A request that names no company acts for it, and your token does not list it as yours.");
835
878
  hint("On a local stack the token comes from a shared tenant and lists that environment's companies.");
836
- 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.");
837
880
  } else if (company && UUID.test(company)) {
838
881
  error(`${where} refused ${company}: that is a raw uuid, not a company id.`);
839
- hint("Pass its slug, or the id `sl hermes companies` lists.");
882
+ hint("Pass its slug, or the id `sl use company` lists.");
840
883
  } else if (company) {
841
884
  error(`${where} refused to act for company ${company}.`);
842
885
  hint("Your token does not list that company, or Hermes no longer knows you as one of its members.");
843
886
  hint("`sl whoami` shows what the CLI is acting as;");
844
- 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>`.");
845
888
  } else {
846
889
  error(`${where} refused this request: it names no company to act for.`);
847
- hint("Pick one of your companies with --company or `sl config set company <slug|id>`;");
848
- 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.");
849
892
  }
850
893
  if (verbose) for (const gqlError of errors) info(`[debug] ${JSON.stringify(gqlError)}`);
851
894
  process.exit(4);
@@ -854,6 +897,10 @@ function reportGraphqlErrors(errors, options, attempt) {
854
897
  if (code !== null && code !== "DOWNSTREAM_SERVICE_ERROR") {
855
898
  error(humanise(code));
856
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
+ }
857
904
  if (verbose) for (const gqlError of errors) info(`[debug] ${JSON.stringify(gqlError)}`);
858
905
  process.exit(1);
859
906
  }
@@ -892,17 +939,27 @@ function startAttempt(query, variables, options) {
892
939
  }
893
940
  async function requestHeaders(options, attempt) {
894
941
  const headers = baseRequestHeaders();
895
- if (!(options.authenticated ?? true)) return { headers, namedNoCompany: false };
942
+ if (!(options.authenticated ?? true)) return { headers, options };
896
943
  const { token, kind } = await resolveAccessToken(options, attempt);
897
944
  headers["Authorization"] = `Bearer ${token}`;
898
- const companyId = options.withoutCompany ? void 0 : options.companyId ?? await resolveCompanyId({ ctx: getUserContext() });
945
+ const { companyId, personal: personal2 } = await actingCompany2(options, kind, {
946
+ named: async () => options.companyId ?? await resolveCompanyId({ ctx: getUserContext() }),
947
+ personal: personalCompanyId
948
+ });
899
949
  if (companyId) headers["X-Company-Id"] = companyId;
900
950
  if (attempt.verbose) info(`[debug] ${kind} token: ...${token.slice(-8)}`);
901
- return { headers, namedNoCompany: !companyId && kind === "user" && !options.withoutCompany };
951
+ return { headers, options: { ...options, actingForPersonalCompany: personal2 } };
952
+ }
953
+ async function actingCompany2(options, kind, lookup) {
954
+ if (options.withoutCompany) return { companyId: void 0, personal: false };
955
+ const named = await lookup.named();
956
+ if (named || kind !== "user") return { companyId: named, personal: false };
957
+ const personal2 = await lookup.personal();
958
+ return { companyId: personal2, personal: personal2 !== void 0 };
902
959
  }
903
960
  async function executeQuery(query, variables, options = {}) {
904
961
  const attempt = startAttempt(query, variables, options);
905
- const { headers, namedNoCompany } = await requestHeaders(options, attempt);
962
+ const { headers, options: sent } = await requestHeaders(options, attempt);
906
963
  let res;
907
964
  try {
908
965
  res = await fetch(attempt.endpoint, {
@@ -920,14 +977,7 @@ async function executeQuery(query, variables, options = {}) {
920
977
  if (!res.ok) reportHttpFailure(res, await res.text(), attempt);
921
978
  const json = await res.json();
922
979
  if (json.errors?.length) {
923
- const refused = !hasResolvedField(json.data);
924
- if (refused && refusedForNamingNoCompany(json.errors, namedNoCompany)) {
925
- const personal2 = await personalCompanyId();
926
- if (personal2) {
927
- return executeQuery(query, variables, { ...options, companyId: personal2, actingForPersonalCompany: true });
928
- }
929
- }
930
- if (refused) reportGraphqlErrors(json.errors, options, attempt);
980
+ if (!hasResolvedField(json.data)) reportGraphqlErrors(json.errors, sent, attempt);
931
981
  for (const gqlError of json.errors) warn(gqlError.message);
932
982
  if (hasFieldError(json.errors)) {
933
983
  hint("Use --fields to select specific fields, or --exclude to skip broken ones.");
@@ -979,7 +1029,7 @@ function parseEventBlock(block) {
979
1029
  return data.length > 0 || event !== "message" ? { event, data: data.join("\n") } : null;
980
1030
  }
981
1031
  async function openEventStream(query, variables, options, attempt) {
982
- const { headers, namedNoCompany } = await requestHeaders(options, attempt);
1032
+ const { headers, options: sent } = await requestHeaders(options, attempt);
983
1033
  headers["Accept"] = "text/event-stream";
984
1034
  let res;
985
1035
  try {
@@ -999,10 +1049,10 @@ async function openEventStream(query, variables, options, attempt) {
999
1049
  if (!res.ok) {
1000
1050
  const body = await res.text();
1001
1051
  const errors = parseErrors(body);
1002
- if (errors) reportGraphqlErrors(errors, options, attempt);
1052
+ if (errors) reportGraphqlErrors(errors, sent, attempt);
1003
1053
  reportHttpFailure(res, body, attempt);
1004
1054
  }
1005
- return { res, namedNoCompany };
1055
+ return { res, sent };
1006
1056
  }
1007
1057
  function parseErrors(body) {
1008
1058
  try {
@@ -1012,25 +1062,13 @@ function parseErrors(body) {
1012
1062
  return null;
1013
1063
  }
1014
1064
  }
1015
- async function* subscriptionEvents(res, query, variables, options, attempt, namedNoCompany) {
1065
+ async function* subscriptionEvents(res, options, attempt) {
1016
1066
  if (!res.body) return;
1017
1067
  for await (const { event, data } of parseEventStream(res.body)) {
1018
1068
  if (event === "complete") return;
1019
1069
  if (event !== "next" && event !== "message") continue;
1020
1070
  const payload = JSON.parse(data);
1021
1071
  if (payload.errors?.length && !hasResolvedField(payload.data)) {
1022
- if (refusedForNamingNoCompany(payload.errors, namedNoCompany)) {
1023
- const personal2 = await personalCompanyId();
1024
- if (personal2) {
1025
- const retry = await graphqlSubscribe(query, variables, {
1026
- ...options,
1027
- companyId: personal2,
1028
- actingForPersonalCompany: true
1029
- });
1030
- yield* retry.events;
1031
- return;
1032
- }
1033
- }
1034
1072
  reportGraphqlErrors(payload.errors, options, attempt);
1035
1073
  }
1036
1074
  for (const gqlError of payload.errors ?? []) warn(gqlError.message);
@@ -1039,8 +1077,8 @@ async function* subscriptionEvents(res, query, variables, options, attempt, name
1039
1077
  }
1040
1078
  async function graphqlSubscribe(query, variables, options = {}) {
1041
1079
  const attempt = startAttempt(query, variables, options);
1042
- const { res, namedNoCompany } = await openEventStream(query, variables, options, attempt);
1043
- return { events: subscriptionEvents(res, query, variables, options, attempt, namedNoCompany) };
1080
+ const { res, sent } = await openEventStream(query, variables, options, attempt);
1081
+ return { events: subscriptionEvents(res, sent, attempt) };
1044
1082
  }
1045
1083
  async function graphql(document, variables, options = {}) {
1046
1084
  return executeQuery(print(document), variables, options);
@@ -1052,6 +1090,330 @@ async function graphqlUnauthenticated(document, variables, endpoint) {
1052
1090
  return graphql(document, variables, { endpoint, authenticated: false });
1053
1091
  }
1054
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
+
1055
1417
  // src/graphql/query-builder.ts
1056
1418
  import {
1057
1419
  isAbstractType,
@@ -1233,6 +1595,12 @@ function connectionSelections(connection, nodeSelections, totalCount) {
1233
1595
  return lines;
1234
1596
  }
1235
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
+ }
1236
1604
  function connectionExtras(connection) {
1237
1605
  return selectableFields(connection).filter((field) => !CONNECTION_PLUMBING.has(field.name)).flatMap((field) => {
1238
1606
  const named = unwrap(field.type);
@@ -1324,14 +1692,15 @@ function buildFieldsFromList(type, schema, requestedPaths, totalCount) {
1324
1692
  if (!isObjectType(type)) return [];
1325
1693
  const fields = type.getFields();
1326
1694
  const page = deliveredPageField(type);
1327
- 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;
1328
1696
  if (isConnection(type)) {
1329
1697
  const nodesType = unwrap(fields.nodes.type);
1330
- 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");
1331
1700
  const nodeSelections = buildFieldsFromList(
1332
1701
  nodesType,
1333
1702
  schema,
1334
- withId ? ["id", ...fieldPaths] : fieldPaths,
1703
+ withId ? ["id", ...nodePaths] : nodePaths,
1335
1704
  totalCount
1336
1705
  );
1337
1706
  return connectionSelections(type, nodeSelections, totalCount);
@@ -1615,7 +1984,8 @@ function coerceValue(raw, type, flagName) {
1615
1984
  if (enumList && !raw.trim().startsWith("[")) return coerceEnumList(raw, enumList, flagName);
1616
1985
  const enumValue = enumOf(type);
1617
1986
  if (enumValue) return coerceEnum(raw, enumValue, flagName);
1618
- if (isStructuredInput(type)) {
1987
+ const typeName = unwrap2(type).name;
1988
+ if (isStructuredInput(type) || typeName === "JSON" && /^\s*[[{]/.test(raw)) {
1619
1989
  try {
1620
1990
  return JSON.parse(raw);
1621
1991
  } catch (parseError) {
@@ -1624,7 +1994,6 @@ function coerceValue(raw, type, flagName) {
1624
1994
  );
1625
1995
  }
1626
1996
  }
1627
- const typeName = unwrap2(type).name;
1628
1997
  if (typeName === "Int") {
1629
1998
  const parsed = parseInt(raw, 10);
1630
1999
  if (Number.isNaN(parsed)) throw new Error(`--${flagName} expects an integer, got "${raw}".`);
@@ -1739,21 +2108,31 @@ function supersededBy(field, siblings) {
1739
2108
  const sibling = siblings[replacement];
1740
2109
  return sibling && !sibling.deprecationReason ? replacement : null;
1741
2110
  }
1742
- function hasExternalId(field) {
1743
- const args = getInputFields(field) ?? field.args;
1744
- return args.some((a) => a.name === "externalId");
2111
+ function argumentNames(field) {
2112
+ return new Set((getInputFields(field) ?? field.args).map((a) => a.name));
1745
2113
  }
2114
+ var RESULT_OF_MUTATION = /(?:result|outcome) of an? `(\w+)` call|then call `(\w+)`/;
1746
2115
  function resultSubscriptions(schema) {
1747
2116
  const pairs = /* @__PURE__ */ new Map();
1748
2117
  const mutations = schema.getMutationType()?.getFields() ?? {};
1749
2118
  for (const [name, field] of Object.entries(schema.getSubscriptionType()?.getFields() ?? {})) {
1750
- 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];
1751
2121
  if (!mutation || !mutations[mutation]) continue;
1752
- 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;
1753
2125
  pairs.set(mutation, name);
1754
2126
  }
1755
2127
  return pairs;
1756
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
+ }
1757
2136
  function isRecord2(value) {
1758
2137
  return typeof value === "object" && value !== null;
1759
2138
  }
@@ -1863,7 +2242,7 @@ function buildCommand(schema, fieldName, kind, description, service, resultSubsc
1863
2242
  required: isNonNullType2(a.type),
1864
2243
  description: a.description
1865
2244
  }));
1866
- const cmd = new Command2(kebab(fieldName)).description(description);
2245
+ const cmd = new Command3(kebab(fieldName)).description(description);
1867
2246
  const requiresCompanyId = cliArgs.some((a) => a.name === "companyId" && a.required);
1868
2247
  for (const a of cliArgs) {
1869
2248
  const placeholder = enumListOf(a.type) ? "a,b|all|none..." : isStructuredInput(a.type) ? "json" : kebab(a.name);
@@ -1902,7 +2281,7 @@ function buildCommand(schema, fieldName, kind, description, service, resultSubsc
1902
2281
  const argumentCompanyId = typeof opts.companyId === "string" ? await resolveCompanyId({ company: opts.companyId, ctx }) : actingId;
1903
2282
  if (requiresCompanyId && !argumentCompanyId) {
1904
2283
  error("No company selected.");
1905
- 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>`.");
1906
2285
  process.exit(2);
1907
2286
  }
1908
2287
  if (argumentCompanyId) opts.companyId = argumentCompanyId;
@@ -1966,11 +2345,9 @@ function buildCommand(schema, fieldName, kind, description, service, resultSubsc
1966
2345
  }
1967
2346
  if (waiting && resultSubscription) {
1968
2347
  const seconds = secondsOption(opts.wait, DEFAULT_WAIT_SECONDS, "--wait");
1969
- if (!requestOptions.companyId && !actingAsApplication()) {
1970
- requestOptions.companyId = await personalCompanyId();
1971
- }
1972
2348
  const externalId = opts.externalId;
1973
- const subscriptionVariables = { externalId };
2349
+ const mutationArguments = useInputWrapper ? variables.input : variables;
2350
+ const subscriptionVariables = subscriptionVariablesFor(schema, resultSubscription, mutationArguments, externalId);
1974
2351
  if (selection.fields && !selection.fields.includes(PAGE_STATUS_FIELD) && deliversFillingPages(schema, resultSubscription)) {
1975
2352
  selection.fields = [...selection.fields, PAGE_STATUS_FIELD];
1976
2353
  }
@@ -2077,7 +2454,7 @@ function groupOperationCommands(operations) {
2077
2454
  for (const operation of operations) {
2078
2455
  let group = services.get(operation.service);
2079
2456
  if (!group) {
2080
- group = new Command2(operation.service).description(`Operations served by ${operation.service}`);
2457
+ group = new Command3(operation.service).description(`Operations served by ${operation.service}`);
2081
2458
  services.set(operation.service, group);
2082
2459
  }
2083
2460
  group.addCommand(operation.command);
@@ -2164,7 +2541,7 @@ function formatOperationList(operations, search) {
2164
2541
  }
2165
2542
 
2166
2543
  // src/commands/login.ts
2167
- import { Command as Command3, Option as Option2 } from "commander";
2544
+ import { Command as Command4, Option as Option2 } from "commander";
2168
2545
 
2169
2546
  // src/graphql/operations/common.ts
2170
2547
  var Me = gql(`
@@ -2219,7 +2596,7 @@ function scopeForLogin(scope, scopeIsDefault, level) {
2219
2596
  const requested = scopeIsDefault ? `openid profile email ${[...USER_API_SCOPES, ...ELEVATION_API_SCOPES[level]].join(" ")}` : scope;
2220
2597
  return requested.split(" ").filter((name) => name && name !== "offline_access").join(" ");
2221
2598
  }
2222
- function sleep(ms) {
2599
+ function sleep3(ms) {
2223
2600
  return new Promise((resolve) => setTimeout(resolve, ms));
2224
2601
  }
2225
2602
  async function setupUserContext(endpoint) {
@@ -2241,12 +2618,12 @@ function reportScopeGrant(requestedScope, accessToken) {
2241
2618
  hint("permissions and drops the rest silently \u2014 this is a role assignment in the");
2242
2619
  hint("tenant you logged into, not a CLI setting. Ask an administrator, then re-run `sl login`.");
2243
2620
  }
2244
- 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(
2245
2622
  `Log in to your Sortlist account
2246
2623
 
2247
2624
  Opens a browser to complete authentication, then saves your
2248
2625
  credentials locally. To act for one of your companies, pass
2249
- --company or run \`sl config set company <slug>\`.
2626
+ --company or run \`sl use company <slug>\`.
2250
2627
 
2251
2628
  Examples:
2252
2629
  sl login Log in with the user scopes, no staff scope
@@ -2289,7 +2666,7 @@ commands fall back to the plain login.`
2289
2666
  let interval = device.interval * 1e3;
2290
2667
  const deadline = Date.now() + device.expiresIn * 1e3;
2291
2668
  while (Date.now() < deadline) {
2292
- await sleep(interval);
2669
+ await sleep3(interval);
2293
2670
  const tokenData = await graphqlUnauthenticated(
2294
2671
  DeviceToken,
2295
2672
  { input: { deviceCode: device.deviceCode } },
@@ -2352,8 +2729,8 @@ commands fall back to the plain login.`
2352
2729
  });
2353
2730
 
2354
2731
  // src/commands/logout.ts
2355
- import { Command as Command4 } from "commander";
2356
- 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(
2357
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"
2358
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() {
2359
2736
  const opts = this.optsWithGlobals();
@@ -2384,9 +2761,162 @@ var logoutCommand = new Command4("logout").summary("Log out and remove stored cr
2384
2761
  hint("Run `sl login` to authenticate again.");
2385
2762
  });
2386
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
+
2387
2917
  // src/commands/token.ts
2388
- import { Command as Command5 } from "commander";
2389
- 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(
2390
2920
  `Print the current access token to stdout
2391
2921
 
2392
2922
  Prints the application credential's token when SORTLIST_CLIENT_ID and
@@ -2423,7 +2953,7 @@ Examples:
2423
2953
  });
2424
2954
 
2425
2955
  // src/commands/use.ts
2426
- import { Command as Command6 } from "commander";
2956
+ import { Command as Command8 } from "commander";
2427
2957
 
2428
2958
  // src/lib/application.ts
2429
2959
  function isApplicationId(value) {
@@ -2482,8 +3012,8 @@ var REVOKE = `
2482
3012
  revokeApplicationCredential(input: { credentialId: $credentialId }) { revokedAt }
2483
3013
  }
2484
3014
  `;
2485
- var useCommand = new Command6("use").summary("Act as an application, or go back to acting as yourself").description(
2486
- "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"
2487
3017
  );
2488
3018
  useCommand.command("application <application>").description(
2489
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"
@@ -2534,6 +3064,76 @@ useCommand.command("application <application>").description(
2534
3064
  hint("Managing companies, applications and credentials is now out of reach: Hermes refuses");
2535
3065
  hint("its own tokens on its management API. Run `sl use me` to act as yourself again.");
2536
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
+ }
2537
3137
  useCommand.command("me").description("Go back to acting as yourself").action(() => {
2538
3138
  if (clearApplicationSession()) {
2539
3139
  success("Now acting as yourself again.");
@@ -2560,7 +3160,7 @@ async function applicationIdFor(reference, opts) {
2560
3160
  error(
2561
3161
  company ? `You do not belong to a company "${company}".` : "You have no personal company to look the application up in."
2562
3162
  );
2563
- 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.");
2564
3164
  } else {
2565
3165
  error(`No application "${named.slug}" in ${found.company.slug ?? "that company"}.`);
2566
3166
  hint(APPLICATIONS_HINT);
@@ -2569,7 +3169,7 @@ async function applicationIdFor(reference, opts) {
2569
3169
  }
2570
3170
 
2571
3171
  // src/commands/whoami.ts
2572
- import { Command as Command7 } from "commander";
3172
+ import { Command as Command9 } from "commander";
2573
3173
  function apiScopes(accessToken) {
2574
3174
  return accessToken ? grantedScopes(accessToken).filter((scope) => scope.includes("/")) : [];
2575
3175
  }
@@ -2577,7 +3177,7 @@ function currentElevation() {
2577
3177
  const elevated = loadElevatedCredentials();
2578
3178
  return elevated ? { level: elevated.level, until: new Date(elevated.expiresAt * 1e3).toISOString() } : null;
2579
3179
  }
2580
- 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(
2581
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"
2582
3182
  ).action(async function() {
2583
3183
  const opts = this.optsWithGlobals();
@@ -2660,8 +3260,17 @@ var whoamiCommand = new Command7("whoami").summary("Show what the CLI is current
2660
3260
  }
2661
3261
  const elevation = currentElevation();
2662
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);
2663
3266
  if (isJsonMode(opts)) {
2664
- 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
+ });
2665
3274
  return;
2666
3275
  }
2667
3276
  info(elevation ? `Acting as yourself, elevated to ${elevation.level}.
@@ -2671,21 +3280,33 @@ var whoamiCommand = new Command7("whoami").summary("Show what the CLI is current
2671
3280
  name: personName(user),
2672
3281
  email: user.email,
2673
3282
  id: user.id,
3283
+ "acts for company": company ? `${company.slug} (${company.name}${company.personal ? ", personal" : ""})` : chosen ?? "none",
3284
+ ...company && { credits, plan },
2674
3285
  ...elevation && { "elevated until": elevation.until },
2675
3286
  scopes: scopes.length > 0 ? scopes.join(" ") : "none"
2676
3287
  }) ?? ""
2677
3288
  );
2678
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.");
2679
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
+ }
2680
3301
 
2681
3302
  // src/graphql/introspection.ts
2682
3303
  import { createHash } from "crypto";
2683
- import fs6 from "fs";
2684
- import os4 from "os";
2685
- import path6 from "path";
3304
+ import fs8 from "fs";
3305
+ import os6 from "os";
3306
+ import path8 from "path";
2686
3307
  import { buildClientSchema, getIntrospectionQuery } from "graphql";
2687
- var CACHE_DIR = path6.join(os4.homedir(), ".sortlist");
2688
- 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");
2689
3310
  var CACHE_TTL_MS = 60 * 60 * 1e3;
2690
3311
  var cached2 = null;
2691
3312
  function tokenFingerprint(token) {
@@ -2694,7 +3315,7 @@ function tokenFingerprint(token) {
2694
3315
  }
2695
3316
  function readCache(endpoint, token) {
2696
3317
  try {
2697
- const text = fs6.readFileSync(CACHE_PATH, "utf-8");
3318
+ const text = fs8.readFileSync(CACHE_PATH, "utf-8");
2698
3319
  const envelope = JSON.parse(text);
2699
3320
  if (envelope.endpoint !== endpoint) return null;
2700
3321
  if (envelope.tokenFingerprint !== tokenFingerprint(token)) return null;
@@ -2707,8 +3328,8 @@ function readCache(endpoint, token) {
2707
3328
  }
2708
3329
  function writeCache(endpoint, token, introspection, raw) {
2709
3330
  try {
2710
- if (!fs6.existsSync(CACHE_DIR)) {
2711
- fs6.mkdirSync(CACHE_DIR, { recursive: true });
3331
+ if (!fs8.existsSync(CACHE_DIR)) {
3332
+ fs8.mkdirSync(CACHE_DIR, { recursive: true });
2712
3333
  }
2713
3334
  const envelope = {
2714
3335
  endpoint,
@@ -2717,7 +3338,7 @@ function writeCache(endpoint, token, introspection, raw) {
2717
3338
  introspection,
2718
3339
  raw
2719
3340
  };
2720
- fs6.writeFileSync(CACHE_PATH, JSON.stringify(envelope));
3341
+ fs8.writeFileSync(CACHE_PATH, JSON.stringify(envelope));
2721
3342
  } catch {
2722
3343
  }
2723
3344
  }
@@ -2820,7 +3441,7 @@ function build(introspection, raw) {
2820
3441
  }
2821
3442
  function discardCache() {
2822
3443
  try {
2823
- fs6.unlinkSync(CACHE_PATH);
3444
+ fs8.unlinkSync(CACHE_PATH);
2824
3445
  } catch {
2825
3446
  }
2826
3447
  }
@@ -2951,7 +3572,7 @@ grouped under the service that serves it, Hermes's account and company operation
2951
3572
  }
2952
3573
  return parts.join("\n\n");
2953
3574
  }
2954
- var program = new Command8().name("sl").configureOutput({
3575
+ var program = new Command10().name("sl").configureOutput({
2955
3576
  writeOut: (str) => process.stdout.write(colorizeHelp(str)),
2956
3577
  writeErr: (str) => process.stderr.write(colorizeHelp(str))
2957
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");
@@ -2961,7 +3582,8 @@ program.addCommand(whoamiCommand);
2961
3582
  program.addCommand(tokenCommand);
2962
3583
  program.addCommand(useCommand);
2963
3584
  program.addCommand(configCommand);
2964
- 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");
2965
3587
  schemaCommand.command("refresh").description("Force-refresh the cached schema from the federation endpoint").action(async function() {
2966
3588
  const opts = this.optsWithGlobals();
2967
3589
  try {
@@ -2998,19 +3620,20 @@ try {
2998
3620
  const { schema, fieldServices, fieldScopes } = await getIntrospectedSchema(endpointOverride);
2999
3621
  const operations = buildOperationCommands(schema, fieldServices, fieldScopes);
3000
3622
  for (const command of groupOperationCommands(operations)) {
3623
+ if (command.name() === "outreach") command.addCommand(connectLinkedinCommand);
3001
3624
  program.addCommand(command);
3002
3625
  }
3003
3626
  for (const command of legacyTopLevelCommands(schema, fieldServices, fieldScopes)) {
3004
3627
  program.addCommand(command, { hidden: true });
3005
3628
  }
3006
- 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() {
3007
3630
  info(formatOperationList(operations, this.opts().search));
3008
3631
  });
3009
3632
  program.addCommand(operationsCommand);
3010
3633
  program.description(buildRootDescription(operations.length));
3011
3634
  } catch (err) {
3012
3635
  const message = err.message;
3013
- const offline = ["login", "logout", "config", "token", "whoami", "schema"];
3636
+ const offline = ["login", "logout", "config", "token", "whoami", "schema", "skill"];
3014
3637
  if (!process.argv.some((a) => offline.includes(a))) {
3015
3638
  error(`Could not fetch schema: ${message}`);
3016
3639
  hint("Check your network connection and endpoint: sl config show");