salesprompter-cli 0.1.80 → 0.1.82

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # salesprompter-cli
2
2
 
3
+ Requires Node.js 22.12 or newer (Node.js 24 LTS recommended). Chrome research also requires an installed Google Chrome.
4
+
3
5
  Salesprompter CLI is a terminal workflow for lead generation, enrichment, scoring, and sync.
4
6
 
5
7
  It helps operators and agents go from company, market, or product input to qualified outbound-ready leads with a product-facing command surface and machine-readable output.
@@ -48,7 +50,21 @@ Use `--report-only` to refresh saved reports without contacting LinkedIn. The wo
48
50
 
49
51
  For a manually verified legal-name alias, add `verifiedEmployerAliases: [{ "name": "Exact source employer name", "evidenceUrl": "https://official.example/legal" }]` to that company. The CLI records the evidence link but does not independently verify its contents. Aliases never bypass the numeric current-company ID check and are never inferred from similar names. Changing the brief requires a new output directory; no existing review rows are silently promoted.
50
52
 
51
- LinkedIn credentials are loaded only when a pending request needs them; a completed checkpoint can be reopened without LinkedIn credentials (Salesprompter workspace authentication still applies). If LinkedIn rejects the saved session, the command tries refreshed local extension credentials for the same LinkedIn identity once and keeps completed searches. Add `--wait-for-session 300` to wait up to five minutes for that refresh, with progress notices. The CLI does not log in to LinkedIn for you. If none arrives, reconnect the extension and rerun, or use `--browser-relay-port` with a signed-in browser worker. Rate limits stop the run without switching sessions. Session waiting and browser relay are mutually exclusive.
53
+ For standalone browser research, sign in once to the CLI-owned Chrome profile, then select Chrome:
54
+
55
+ ```bash
56
+ salesprompter browser:connect
57
+ salesprompter leads:at-companies --brief companies.json --out-dir ./research \
58
+ --resolve-companies --all --browser chrome
59
+ ```
60
+
61
+ `browser:connect` opens a separate Chrome window and waits up to ten minutes for your manual Sales Navigator sign-in (change with `--wait <seconds>`). It confirms a successful native authenticated request, then closes its own browser. Google Chrome must be installed. The private profile lives at `~/.config/salesprompter/chrome-research` (or under `SALESPROMPTER_CONFIG_DIR`). Your everyday Chrome profile stays untouched. The control connection uses a private OS pipe, not a debugging port. No cookies or browser storage are read/exported. The CLI keeps only allowlisted native request headers in memory.
62
+
63
+ Research runs reuse that profile in background Chrome, execute the GET requests themselves, and close their own browser when finished. No Codex task, relay worker, extension, or manual request polling is needed. A first sign-in, expired login, or security challenge still requires you: rerun `browser:connect`, then repeat the research command with the same output directory. Rate limits stop immediately without switching accounts. `--browser chrome`, `--browser-relay-port`, and `--wait-for-session` are mutually exclusive. Chrome connects lazily, so completed checkpoints and report-only runs never launch it.
64
+
65
+ The default `--browser session` keeps the extension-credential route. Credentials load only for pending requests; on an auth failure it tries changed credentials for the same identity once. Add `--wait-for-session 300` for a bounded refresh wait. The optional Codex `--browser-relay-port` route still needs its external worker. Salesprompter workspace authentication applies in every mode.
66
+
67
+ Ctrl+C, SIGTERM and terminal hangup stop Chrome research gracefully: completed searches stay saved, the owned browser closes, and the research lock is released before exit. Repeat the same command to resume only pending work. A forced kill or power loss cannot run cleanup; if a stale lock remains, confirm that its process stopped before removing only `.research-lock` as the CLI error explains.
52
68
 
53
69
  Create a JSON brief with verified numeric LinkedIn company IDs. Use each subsidiary's own ID; names alone are not an employer match. Missing IDs stay in the coverage report as unresolved.
54
70
 
@@ -58,7 +74,7 @@ For a name-only list, the executable end-to-end research mode is:
58
74
  salesprompter leads:at-companies --brief companies.json --out-dir ./research --resolve-companies --all
59
75
  ```
60
76
 
61
- The CLI first collects prepared IDs, then resolves missing IDs through paginated Account Search and immediately collects their contacts. It accepts only one exact-name identity from a fully read result set of at most 1,000 companies; fuzzy, shared-ID, oversized and ambiguous matches remain unresolved. Resolutions and misses are saved in the workspace-bound checkpoint and `company-resolutions.json`, without editing the input brief. Repeat the command to resume. Add `--retry-unresolved --resolve-companies` to intentionally retry saved identity misses in the same directory without repeating successful resolutions or completed searches. `--all` removes the invocation's job-count limit, not LinkedIn pacing or per-function candidate limits. A working LinkedIn session is required for new requests; the Codex browser relay still requires a connected browser worker when used.
77
+ The CLI first collects prepared IDs, then resolves missing IDs through paginated Account Search and immediately collects their contacts. It accepts only one exact-name identity from a fully read result set of at most 1,000 companies; fuzzy, shared-ID, oversized and ambiguous matches remain unresolved. Resolutions and misses are saved in the workspace-bound checkpoint and `company-resolutions.json`, without editing the input brief. Repeat the command to resume. Add `--retry-unresolved --resolve-companies` to intentionally retry saved identity misses in the same directory without repeating successful resolutions or completed searches. `--all` removes the invocation's job-count limit, not LinkedIn pacing or per-function candidate limits. A working LinkedIn session is required for new requests; use `--browser chrome` to eliminate the external browser-worker dependency.
62
78
 
63
79
  ```bash
64
80
  salesprompter leads:at-companies --brief companies.json --out-dir ./research \
@@ -0,0 +1,231 @@
1
+ import { chmod, lstat, mkdir } from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { setTimeout as sleep } from "node:timers/promises";
5
+ const ORIGIN = "https://www.linkedin.com";
6
+ const LOGIN_HELP = "Run salesprompter browser:connect, sign in to LinkedIn Sales Navigator in the dedicated Chrome window, then rerun with the same --out-dir. Saved work is preserved.";
7
+ export class ChromeResearchError extends Error {
8
+ status;
9
+ constructor(message, status) {
10
+ super(message);
11
+ this.status = status;
12
+ this.name = "ChromeResearchError";
13
+ }
14
+ }
15
+ export class ChromeResearchInterruptedError extends Error {
16
+ signal;
17
+ constructor(signal) {
18
+ super("Research interrupted. Completed searches remain saved; rerun with the same --out-dir to resume.");
19
+ this.signal = signal;
20
+ this.name = "ChromeResearchInterruptedError";
21
+ }
22
+ }
23
+ export function validateChromeResearchUrl(value) {
24
+ const url = new URL(value);
25
+ if (url.origin !== ORIGIN || url.username || url.password || url.hash ||
26
+ !/^\/sales-api\/(?:salesApiAccountSearch|salesApiLeadSearch|salesApiCompanies)(?:\/\d+)?$/.test(url.pathname)) {
27
+ throw new Error("Chrome research only permits LinkedIn Sales Navigator company and people GET requests.");
28
+ }
29
+ // Preserve native Rest.li encoding; URLSearchParams can corrupt its syntax.
30
+ return value;
31
+ }
32
+ /** Only these native request headers enter memory; cookies/storage are never read or exported. */
33
+ export function researchHeaders(headers) {
34
+ const lower = Object.fromEntries(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v]));
35
+ if (!lower["csrf-token"] || !lower["x-li-identity"])
36
+ return null;
37
+ return { "csrf-token": lower["csrf-token"], "x-li-identity": lower["x-li-identity"], accept: "*/*", "x-restli-protocol-version": "2.0.0" };
38
+ }
39
+ export function chromeProfileDirectory() {
40
+ return path.resolve(process.env.SALESPROMPTER_CONFIG_DIR?.trim() || path.join(os.homedir(), ".config", "salesprompter"), "chrome-research");
41
+ }
42
+ /** Launch only a CLI-owned profile and private OS pipe; no debugging port or default-profile attachment. */
43
+ export async function launchResearchChrome(visible = false) {
44
+ const profile = chromeProfileDirectory();
45
+ try {
46
+ if ((await lstat(profile)).isSymbolicLink())
47
+ throw new Error("The research Chrome profile must not be a symlink.");
48
+ }
49
+ catch (error) {
50
+ if (error.code !== "ENOENT")
51
+ throw error;
52
+ }
53
+ await mkdir(profile, { recursive: true, mode: 0o700 });
54
+ await chmod(profile, 0o700);
55
+ const { default: puppeteer } = await import("puppeteer-core");
56
+ try {
57
+ return await puppeteer.launch({ channel: "chrome", userDataDir: profile, pipe: true, headless: !visible,
58
+ timeout: 30000, protocolTimeout: 45000, defaultViewport: null,
59
+ // Let the command unwind its checkpoint/lock finally blocks before exiting.
60
+ handleSIGINT: false, handleSIGTERM: false, handleSIGHUP: false,
61
+ });
62
+ }
63
+ catch {
64
+ // Launch errors can contain paths/flags. Never forward raw browser stderr or credential-bearing URLs.
65
+ throw new ChromeResearchError("Could not start the dedicated research Chrome. Install/update Google Chrome and close any other salesprompter browser:connect or Chrome research run. Your everyday Chrome can stay open.");
66
+ }
67
+ }
68
+ export function parseChromeResearchResult(result) {
69
+ if (result.status === 429 || result.status === 999)
70
+ throw new ChromeResearchError(`LinkedIn returned HTTP ${result.status}. Research stopped; wait for cooldown before resuming the same checkpoint. No session switching or retry was attempted.`, result.status);
71
+ if (result.redirected || result.status === 401 || result.status === 403)
72
+ throw new ChromeResearchError(LOGIN_HELP, result.status);
73
+ if (result.status !== 200)
74
+ throw new ChromeResearchError(`LinkedIn research failed with HTTP ${result.status}. Saved work is preserved.`, result.status);
75
+ try {
76
+ return JSON.parse(result.text);
77
+ }
78
+ catch {
79
+ throw new ChromeResearchError(`LinkedIn did not return research JSON. ${LOGIN_HELP}`);
80
+ }
81
+ }
82
+ /** Lazy and serial: reopening a completed checkpoint never starts Chrome. */
83
+ export function createChromeResearchBrowser(options = {}, launch = launchResearchChrome) {
84
+ let browser;
85
+ let page;
86
+ let headers = null;
87
+ let identity;
88
+ let fatal;
89
+ let initialization;
90
+ let closed = false;
91
+ let busy = false;
92
+ let browserClosing;
93
+ const signals = ["SIGINT", "SIGTERM", "SIGHUP"];
94
+ const signalHandlers = signals.map(signal => () => {
95
+ if (fatal instanceof ChromeResearchInterruptedError)
96
+ return;
97
+ fatal = new ChromeResearchInterruptedError(signal);
98
+ closed = true;
99
+ void closeOwnedBrowser().catch(() => { });
100
+ });
101
+ function closeOwnedBrowser() {
102
+ if (browser)
103
+ browserClosing ??= browser.close();
104
+ return browserClosing ?? Promise.resolve();
105
+ }
106
+ const waitMs = options.loginWaitMs ?? 30000;
107
+ if (!Number.isFinite(waitMs) || waitMs < 0 || waitMs > 3600000)
108
+ throw new Error("Chrome login wait must be between 0 and 3600 seconds.");
109
+ async function initialize() {
110
+ signals.forEach((signal, index) => process.on(signal, signalHandlers[index]));
111
+ browser = await launch(options.visible);
112
+ if (closed) {
113
+ await closeOwnedBrowser();
114
+ throw fatal ?? new ChromeResearchError("Research Chrome connection was cancelled.");
115
+ }
116
+ page = await browser.newPage();
117
+ page.on("response", (response) => {
118
+ if (fatal)
119
+ return;
120
+ const url = new URL(response.url());
121
+ if (url.origin !== ORIGIN)
122
+ return;
123
+ if (response.status() === 429 || response.status() === 999) {
124
+ fatal = new ChromeResearchError(`LinkedIn returned HTTP ${response.status()}. Stop and wait for cooldown before resuming.`, response.status());
125
+ return;
126
+ }
127
+ if (!url.pathname.startsWith("/sales-api/"))
128
+ return;
129
+ if (response.status() !== 200)
130
+ return;
131
+ const next = researchHeaders(response.request().headers());
132
+ if (!next)
133
+ return;
134
+ if (identity && identity !== next["x-li-identity"]) {
135
+ fatal = new ChromeResearchError("LinkedIn identity changed during research. Stopped without switching accounts.");
136
+ return;
137
+ }
138
+ identity = next["x-li-identity"];
139
+ headers = next;
140
+ });
141
+ options.onProgress?.(options.visible
142
+ ? "Sign in to Sales Navigator in the dedicated research Chrome window. The CLI will detect the connection automatically; no extension or browser worker is required."
143
+ : "Connecting to the saved research Chrome profile (no external browser worker).");
144
+ try {
145
+ await page.goto(`${ORIGIN}/sales/search/people`, { waitUntil: "domcontentloaded", timeout: 30000 });
146
+ }
147
+ catch {
148
+ if (closed)
149
+ throw fatal ?? new ChromeResearchError("Research Chrome connection was cancelled.");
150
+ if (!browser.connected)
151
+ throw new ChromeResearchError("Research Chrome closed before connecting.");
152
+ }
153
+ const deadline = Date.now() + waitMs;
154
+ let noticeAt = Date.now() + 30000;
155
+ while (!headers) {
156
+ if (closed)
157
+ throw fatal ?? new ChromeResearchError("Research Chrome connection was cancelled.");
158
+ if (fatal)
159
+ throw fatal;
160
+ if (!browser.connected || page.isClosed())
161
+ throw new ChromeResearchError("Research Chrome was closed before sign-in completed.");
162
+ const location = new URL(page.url());
163
+ const needsLogin = location.origin !== ORIGIN || /\/(?:login|checkpoint|authwall|uas)\b/.test(location.pathname);
164
+ if ((!options.visible && needsLogin) || Date.now() >= deadline)
165
+ throw new ChromeResearchError(LOGIN_HELP);
166
+ if (Date.now() >= noticeAt) {
167
+ options.onProgress?.("Waiting for Sales Navigator sign-in. Complete any sign-in or security check yourself in the research Chrome window.");
168
+ noticeAt += 30000;
169
+ }
170
+ await sleep(250);
171
+ }
172
+ if (fatal)
173
+ throw fatal;
174
+ options.onProgress?.("Research Chrome connected. Requests now run directly in the CLI.");
175
+ }
176
+ async function ready() {
177
+ if (closed)
178
+ throw fatal ?? new Error("Research Chrome is closed.");
179
+ initialization ??= initialize();
180
+ await initialization;
181
+ if (fatal)
182
+ throw fatal;
183
+ }
184
+ return {
185
+ // Compatibility with the existing request adapter, without opening any listener.
186
+ port: 0,
187
+ async connect() { await ready(); return { browser: "chrome", connected: true, workerRequired: false, profile: chromeProfileDirectory() }; },
188
+ async request(request) {
189
+ validateChromeResearchUrl(request.url);
190
+ if (busy)
191
+ throw new Error("Chrome research is single-worker; concurrent requests are not allowed.");
192
+ busy = true;
193
+ try {
194
+ await ready();
195
+ if (new URL(page.url()).origin !== ORIGIN)
196
+ throw new ChromeResearchError(LOGIN_HELP);
197
+ // Serialize URL and allowlisted native headers as data, never concatenate raw input into executable code.
198
+ // Credentials remain browser-managed. Reject redirects to login/challenge pages instead of parsing HTML.
199
+ const result = await page.evaluate(`(async () => {
200
+ const response = await fetch(${JSON.stringify(request.url)}, {
201
+ method: 'GET', credentials: 'include', redirect: 'error',
202
+ headers: ${JSON.stringify(headers)}, signal: AbortSignal.timeout(30000)
203
+ });
204
+ const text = await response.text();
205
+ if (text.length > 50 * 1024 * 1024) throw new Error('Research response exceeded 50 MB');
206
+ return {status: response.status, text, redirected: response.redirected, retryAfter: response.headers.get('retry-after')};
207
+ })()`).catch(() => { throw fatal ?? new ChromeResearchError(`Chrome research request could not complete. ${LOGIN_HELP}`); });
208
+ const body = parseChromeResearchResult(result);
209
+ if (fatal)
210
+ throw fatal;
211
+ return { body, retryCount: 0, retryDelayMs: 0 };
212
+ }
213
+ finally {
214
+ busy = false;
215
+ }
216
+ },
217
+ async close() {
218
+ closed = true;
219
+ try {
220
+ await closeOwnedBrowser();
221
+ await initialization?.catch(() => { });
222
+ await closeOwnedBrowser();
223
+ }
224
+ finally {
225
+ signals.forEach((signal, index) => process.off(signal, signalHandlers[index]));
226
+ headers = null;
227
+ identity = undefined;
228
+ }
229
+ },
230
+ };
231
+ }
package/dist/cli.js CHANGED
@@ -17,6 +17,7 @@ import { z } from "zod";
17
17
  import { AffiliateCopyReviewSchema, renderAffiliateCopyReview } from "./affiliate-copy.js";
18
18
  import { CompanyBriefSchema, planCompanySearches, runCompanyResearch } from "./company-leads.js";
19
19
  import { createLazySessionRecovery, waitForFreshSession, isFreshSessionForIdentity } from "./session-recovery.js";
20
+ import { createChromeResearchBrowser, ChromeResearchInterruptedError } from "./chrome-browser.js";
20
21
  import { clearAuthSession, loginWithBrowserConnect, loginWithDeviceFlow, loginWithToken, readAuthSession, requireAuthSession, shouldBypassAuth, verifySession, writeAuthSession } from "./auth.js";
21
22
  import { buildBigQueryLeadLookupSql, executeBigQuerySql, normalizeBigQueryLeadRows, runBigQueryQuery, runBigQueryRows } from "./bigquery.js";
22
23
  import { AccountProfileSchema, EnrichedLeadSchema, IcpSchema, LeadSchema, ScoredLeadSchema, SyncTargetSchema } from "./domain.js";
@@ -777,6 +778,7 @@ const helpVisibleCommandNames = new Set([
777
778
  "auth:workspace",
778
779
  "wizard",
779
780
  "auth:whoami",
781
+ "browser:connect",
780
782
  "llm:ready",
781
783
  "leads:download",
782
784
  "leads:at-companies",
@@ -15135,6 +15137,19 @@ program
15135
15137
  .action(async (options) => {
15136
15138
  printOutput(await runSalesNavigatorPeopleCollectCommand(options));
15137
15139
  });
15140
+ program
15141
+ .command("browser:connect")
15142
+ .description("Sign in once to the CLI-owned research Chrome; no external browser worker required.")
15143
+ .option("--wait <seconds>", "Time allowed for manual LinkedIn sign-in", "600")
15144
+ .action(async (options) => {
15145
+ const browser = createChromeResearchBrowser({ visible: true, loginWaitMs: z.coerce.number().int().min(1).max(3600).parse(options.wait) * 1000, onProgress: message => process.stderr.write(`${message}\n`) });
15146
+ try {
15147
+ printOutput({ status: "ok", ...await browser.connect() });
15148
+ }
15149
+ finally {
15150
+ await browser.close();
15151
+ }
15152
+ });
15138
15153
  program
15139
15154
  .command("leads:at-companies")
15140
15155
  .description("Find senior contacts at named companies, balanced across functions; export a review shortlist.")
@@ -15147,11 +15162,15 @@ program
15147
15162
  .option("--retry-unresolved", "Retry cached identity misses without discarding completed searches (requires --resolve-companies)", false)
15148
15163
  .option("--wait-for-session <seconds>", "Wait for a refreshed extension session after an auth failure; never retry rate limits", "0")
15149
15164
  .option("--browser-relay-port <number>", "Use the signed-in Codex browser through a loopback relay")
15165
+ .option("--browser <mode>", "Use chrome for CLI-owned browser research, or session for extension credentials", "session")
15150
15166
  .option("--dry-run", "Preview targeting and unresolved companies without network calls", false)
15151
15167
  .action(async (options) => {
15168
+ const browserMode = z.enum(["chrome", "session"]).parse(options.browser);
15152
15169
  if (options.retryUnresolved && !options.resolveCompanies)
15153
15170
  throw new Error("--retry-unresolved requires --resolve-companies.");
15154
15171
  const waitMs = z.coerce.number().int().min(0).max(3600).parse(options.waitForSession) * 1000;
15172
+ if (browserMode === "chrome" && (options.browserRelayPort || waitMs))
15173
+ throw new Error("Use one connection mode: --browser chrome, --browser-relay-port, or --wait-for-session.");
15155
15174
  if (waitMs && options.browserRelayPort)
15156
15175
  throw new Error("--wait-for-session refreshes extension credentials, not a browser relay. Use one connection mode.");
15157
15176
  const brief = await readJsonFile(path.resolve(options.brief), CompanyBriefSchema);
@@ -15171,7 +15190,7 @@ program
15171
15190
  return;
15172
15191
  }
15173
15192
  const port = options.browserRelayPort == null ? null : z.coerce.number().int().min(1).max(65535).parse(options.browserRelayPort);
15174
- const relay = port == null ? null : await createLocalAccountSearchBrowserRelay(port);
15193
+ const relay = browserMode === "chrome" ? createChromeResearchBrowser({ onProgress: message => process.stderr.write(`${message}\n`) }) : port == null ? null : await createLocalAccountSearchBrowserRelay(port);
15175
15194
  let currentConfig = null;
15176
15195
  const refresh = async () => {
15177
15196
  if (relay || shouldDisableLinkedInDirectLookupAutodiscovery())
@@ -15190,6 +15209,8 @@ program
15190
15209
  currentConfig = await readLinkedInDirectLookupConfig();
15191
15210
  }
15192
15211
  catch (error) {
15212
+ if (!waitMs && error instanceof Error && error.message.startsWith("Missing LinkedIn direct lookup session"))
15213
+ throw new Error("No LinkedIn session is available. Run salesprompter browser:connect, then rerun this command with --browser chrome and the same --out-dir. No external browser worker is needed.");
15193
15214
  if (!waitMs || !(error instanceof Error) || !error.message.startsWith("Missing LinkedIn direct lookup session"))
15194
15215
  throw error;
15195
15216
  currentConfig = await refresh();
@@ -19542,6 +19563,11 @@ async function closeGlobalHttpDispatcher() {
19542
19563
  }
19543
19564
  main()
19544
19565
  .catch((error) => {
19566
+ if (error instanceof ChromeResearchInterruptedError) {
19567
+ process.stderr.write(runtimeOutputOptions.json ? `${JSON.stringify({ status: "interrupted", message: error.message, signal: error.signal, resumable: true })}\n` : `${error.message}\n`);
19568
+ process.exitCode = error.signal === "SIGINT" ? 130 : error.signal === "SIGTERM" ? 143 : 129;
19569
+ return;
19570
+ }
19545
19571
  if (error instanceof Error &&
19546
19572
  (error.message === "prompt cancelled" || error.message === "readline was closed")) {
19547
19573
  process.exitCode = 130;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "salesprompter-cli",
3
- "version": "0.1.80",
3
+ "version": "0.1.82",
4
4
  "description": "Sales workflow CLI for guided lead generation, enrichment, scoring, and sync.",
5
5
  "author": "Daniel Sinewe <hello@danielsinewe.com>",
6
6
  "type": "module",
@@ -31,7 +31,7 @@
31
31
  "vercel-build": "npm run build:docs:site"
32
32
  },
33
33
  "engines": {
34
- "node": ">=20.0.0"
34
+ "node": ">=22.12.0"
35
35
  },
36
36
  "publishConfig": {
37
37
  "access": "public"
@@ -70,6 +70,7 @@
70
70
  "cheerio": "^1.2.0",
71
71
  "commander": "^14.0.1",
72
72
  "pg": "^8.21.0",
73
+ "puppeteer-core": "^25.10.0",
73
74
  "zod": "^4.1.5"
74
75
  },
75
76
  "overrides": {