linkedin-relay-mcp 1.0.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/.claude/skills/linkedin-relay/SKILL.md +205 -0
- package/LICENSE +21 -0
- package/README.md +98 -0
- package/dist/cli.js +2748 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.js +700 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp-shim.js +2073 -0
- package/dist/mcp-shim.js.map +1 -0
- package/package.json +74 -0
package/dist/mcp-shim.js
ADDED
|
@@ -0,0 +1,2073 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
|
|
3
|
+
// src/mcp-shim.ts
|
|
4
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
5
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
|
|
8
|
+
// src/cache/db.ts
|
|
9
|
+
import { Database } from "bun:sqlite";
|
|
10
|
+
import { mkdirSync as mkdirSync2, renameSync as renameSync2 } from "fs";
|
|
11
|
+
|
|
12
|
+
// src/cache/store.ts
|
|
13
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
|
|
14
|
+
import { homedir } from "os";
|
|
15
|
+
import { dirname, join } from "path";
|
|
16
|
+
function cacheDir() {
|
|
17
|
+
return process.env.LNRELAY_CACHE_DIR ?? join(homedir(), ".lnrelay");
|
|
18
|
+
}
|
|
19
|
+
function cachePath(...parts) {
|
|
20
|
+
return join(cacheDir(), ...parts);
|
|
21
|
+
}
|
|
22
|
+
function loadJson(path) {
|
|
23
|
+
if (!existsSync(path)) return { state: "missing" };
|
|
24
|
+
let raw;
|
|
25
|
+
try {
|
|
26
|
+
raw = readFileSync(path, "utf-8");
|
|
27
|
+
} catch (e) {
|
|
28
|
+
return quarantine(path, `unreadable: ${e.message}`);
|
|
29
|
+
}
|
|
30
|
+
try {
|
|
31
|
+
return { state: "ok", value: JSON.parse(raw) };
|
|
32
|
+
} catch (e) {
|
|
33
|
+
return quarantine(path, `unparseable JSON: ${e.message}`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function quarantine(path, reason) {
|
|
37
|
+
const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
38
|
+
const target = cachePath("quarantine", stamp, path.split("/").pop() ?? "file");
|
|
39
|
+
try {
|
|
40
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
41
|
+
renameSync(path, target);
|
|
42
|
+
} catch {
|
|
43
|
+
}
|
|
44
|
+
return { state: "corrupt", quarantinedTo: target, reason };
|
|
45
|
+
}
|
|
46
|
+
function saveJson(path, value) {
|
|
47
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
48
|
+
const tmp = `${path}.tmp`;
|
|
49
|
+
writeFileSync(tmp, JSON.stringify(value, null, 2), { encoding: "utf-8", mode: 384 });
|
|
50
|
+
renameSync(tmp, path);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// src/cache/db.ts
|
|
54
|
+
var DB_FILE = "cache.db";
|
|
55
|
+
var THIRD_PARTY_TTL_MS = 30 * 864e5;
|
|
56
|
+
function fold(value) {
|
|
57
|
+
return value.normalize("NFD").replace(new RegExp("\\p{Diacritic}", "gu"), "").toLowerCase();
|
|
58
|
+
}
|
|
59
|
+
var TABLES = [
|
|
60
|
+
`CREATE TABLE IF NOT EXISTS records (
|
|
61
|
+
urn TEXT NOT NULL,
|
|
62
|
+
source TEXT NOT NULL,
|
|
63
|
+
body TEXT,
|
|
64
|
+
text TEXT NOT NULL DEFAULT '',
|
|
65
|
+
textFold TEXT NOT NULL DEFAULT '',
|
|
66
|
+
firstSeenAt INTEGER NOT NULL,
|
|
67
|
+
updatedAt INTEGER NOT NULL,
|
|
68
|
+
expiresAt INTEGER,
|
|
69
|
+
PRIMARY KEY (urn, source)
|
|
70
|
+
)`,
|
|
71
|
+
`CREATE TABLE IF NOT EXISTS checkpoints (
|
|
72
|
+
source TEXT PRIMARY KEY,
|
|
73
|
+
lastSuccessfulAt INTEGER NOT NULL,
|
|
74
|
+
newestCreatedAt INTEGER,
|
|
75
|
+
headIds TEXT NOT NULL DEFAULT '[]',
|
|
76
|
+
state TEXT NOT NULL DEFAULT 'ok'
|
|
77
|
+
)`
|
|
78
|
+
];
|
|
79
|
+
var INDEXES = [
|
|
80
|
+
"CREATE INDEX IF NOT EXISTS records_source ON records(source)",
|
|
81
|
+
"CREATE INDEX IF NOT EXISTS records_fold ON records(textFold)",
|
|
82
|
+
"CREATE INDEX IF NOT EXISTS records_expires ON records(expiresAt)"
|
|
83
|
+
];
|
|
84
|
+
var CacheCorrupt = class extends Error {
|
|
85
|
+
constructor(message, quarantinedTo) {
|
|
86
|
+
super(message);
|
|
87
|
+
this.quarantinedTo = quarantinedTo;
|
|
88
|
+
this.name = "CacheCorrupt";
|
|
89
|
+
}
|
|
90
|
+
quarantinedTo;
|
|
91
|
+
};
|
|
92
|
+
function openDb(now = Date.now()) {
|
|
93
|
+
mkdirSync2(cacheDir(), { recursive: true });
|
|
94
|
+
const path = cachePath(DB_FILE);
|
|
95
|
+
let db;
|
|
96
|
+
try {
|
|
97
|
+
db = new Database(path, { create: true });
|
|
98
|
+
const check = db.query("PRAGMA integrity_check").get();
|
|
99
|
+
if (check?.integrity_check !== void 0 && check.integrity_check !== "ok") {
|
|
100
|
+
throw new Error(`integrity_check: ${check.integrity_check}`);
|
|
101
|
+
}
|
|
102
|
+
} catch (e) {
|
|
103
|
+
throw quarantine2(path, e.message, now);
|
|
104
|
+
}
|
|
105
|
+
db.run("PRAGMA journal_mode = WAL");
|
|
106
|
+
for (const stmt of TABLES) db.run(stmt);
|
|
107
|
+
migrate(db);
|
|
108
|
+
for (const stmt of INDEXES) db.run(stmt);
|
|
109
|
+
sweepExpired(db, now);
|
|
110
|
+
return db;
|
|
111
|
+
}
|
|
112
|
+
function migrate(db) {
|
|
113
|
+
const columns = db.query("PRAGMA table_info(records)").all();
|
|
114
|
+
if (!columns.some((c) => c.name === "textFold")) {
|
|
115
|
+
db.run("ALTER TABLE records ADD COLUMN textFold TEXT NOT NULL DEFAULT ''");
|
|
116
|
+
}
|
|
117
|
+
const stale = db.query("SELECT urn, source, text FROM records WHERE textFold = '' AND text != ''").all();
|
|
118
|
+
if (stale.length > 0) {
|
|
119
|
+
const update = db.query("UPDATE records SET textFold = ? WHERE urn = ? AND source = ?");
|
|
120
|
+
db.transaction(() => {
|
|
121
|
+
for (const r of stale) update.run(fold(r.text), r.urn, r.source);
|
|
122
|
+
})();
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
function quarantine2(path, reason, now) {
|
|
126
|
+
const stamp = new Date(now).toISOString().replace(/[:.]/g, "-");
|
|
127
|
+
const target = cachePath("quarantine", stamp, DB_FILE);
|
|
128
|
+
try {
|
|
129
|
+
mkdirSync2(cachePath("quarantine", stamp), { recursive: true });
|
|
130
|
+
renameSync2(path, target);
|
|
131
|
+
} catch {
|
|
132
|
+
}
|
|
133
|
+
return new CacheCorrupt(
|
|
134
|
+
`the local cache was unreadable and has been quarantined: ${reason}`,
|
|
135
|
+
target
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
function sweepExpired(db, now = Date.now()) {
|
|
139
|
+
const result = db.run(
|
|
140
|
+
"UPDATE records SET body = NULL, text = '', textFold = '' WHERE expiresAt IS NOT NULL AND expiresAt <= ? AND body IS NOT NULL",
|
|
141
|
+
[now]
|
|
142
|
+
);
|
|
143
|
+
return result.changes;
|
|
144
|
+
}
|
|
145
|
+
function upsert(db, source, rows, now = Date.now()) {
|
|
146
|
+
const expiresAt = source === "third-party" ? now + THIRD_PARTY_TTL_MS : null;
|
|
147
|
+
let added = 0;
|
|
148
|
+
let updated = 0;
|
|
149
|
+
const exists = db.query("SELECT 1 FROM records WHERE urn = ? AND source = ?");
|
|
150
|
+
const write = db.query(
|
|
151
|
+
`INSERT INTO records (urn, source, body, text, textFold, firstSeenAt, updatedAt, expiresAt)
|
|
152
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
153
|
+
ON CONFLICT(urn, source) DO UPDATE SET
|
|
154
|
+
body = excluded.body, text = excluded.text, textFold = excluded.textFold,
|
|
155
|
+
updatedAt = excluded.updatedAt, expiresAt = excluded.expiresAt`
|
|
156
|
+
);
|
|
157
|
+
db.transaction(() => {
|
|
158
|
+
for (const row of rows) {
|
|
159
|
+
if (exists.get(row.urn, source) === null) added++;
|
|
160
|
+
else updated++;
|
|
161
|
+
write.run(
|
|
162
|
+
row.urn,
|
|
163
|
+
source,
|
|
164
|
+
JSON.stringify(row.body),
|
|
165
|
+
row.text,
|
|
166
|
+
fold(row.text),
|
|
167
|
+
now,
|
|
168
|
+
now,
|
|
169
|
+
expiresAt
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
})();
|
|
173
|
+
return { added, updated };
|
|
174
|
+
}
|
|
175
|
+
function count(db, source) {
|
|
176
|
+
const row = source === void 0 ? db.query("SELECT COUNT(*) AS n FROM records").get() : db.query("SELECT COUNT(*) AS n FROM records WHERE source = ?").get(source);
|
|
177
|
+
return row.n;
|
|
178
|
+
}
|
|
179
|
+
function search(db, query, opts = {}) {
|
|
180
|
+
const sources = opts.sources ?? ["connections", "my-posts", "third-party"];
|
|
181
|
+
const placeholders = sources.map(() => "?").join(",");
|
|
182
|
+
const params = [...sources];
|
|
183
|
+
let sql = `SELECT * FROM records WHERE source IN (${placeholders}) AND body IS NOT NULL`;
|
|
184
|
+
if (query !== "") {
|
|
185
|
+
sql += " AND textFold LIKE ?";
|
|
186
|
+
params.push(`%${fold(query)}%`);
|
|
187
|
+
}
|
|
188
|
+
if (opts.since !== void 0) {
|
|
189
|
+
sql += " AND updatedAt >= ?";
|
|
190
|
+
params.push(opts.since);
|
|
191
|
+
}
|
|
192
|
+
sql += " ORDER BY updatedAt DESC LIMIT ?";
|
|
193
|
+
params.push(opts.limit ?? 25);
|
|
194
|
+
return db.query(sql).all(...params);
|
|
195
|
+
}
|
|
196
|
+
function getCheckpoint(db, source) {
|
|
197
|
+
const row = db.query("SELECT * FROM checkpoints WHERE source = ?").get(source);
|
|
198
|
+
if (row === null) return void 0;
|
|
199
|
+
return { ...row, headIds: JSON.parse(row.headIds) };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// src/engine/restli.ts
|
|
203
|
+
var ENCODED = {
|
|
204
|
+
"%": "%25",
|
|
205
|
+
// MUST be first — see below
|
|
206
|
+
"(": "%28",
|
|
207
|
+
")": "%29",
|
|
208
|
+
",": "%2C",
|
|
209
|
+
":": "%3A",
|
|
210
|
+
"|": "%7C",
|
|
211
|
+
"&": "%26",
|
|
212
|
+
"#": "%23",
|
|
213
|
+
"+": "%2B",
|
|
214
|
+
" ": "%20"
|
|
215
|
+
};
|
|
216
|
+
var RESERVED = /[%(),:|&#+ ]/g;
|
|
217
|
+
function encodeScalar(value) {
|
|
218
|
+
if (typeof value !== "string") return String(value);
|
|
219
|
+
return value.replace(RESERVED, (c) => ENCODED[c] ?? c);
|
|
220
|
+
}
|
|
221
|
+
function encodeValue(value) {
|
|
222
|
+
if (value === void 0) return void 0;
|
|
223
|
+
if (Array.isArray(value)) {
|
|
224
|
+
const members = value.map(encodeValue).filter((m) => m !== void 0);
|
|
225
|
+
return `List(${members.join(",")})`;
|
|
226
|
+
}
|
|
227
|
+
if (typeof value === "object") return encodeObject(value);
|
|
228
|
+
return encodeScalar(value);
|
|
229
|
+
}
|
|
230
|
+
function encodeObject(obj) {
|
|
231
|
+
const parts = [];
|
|
232
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
233
|
+
const encoded = encodeValue(value);
|
|
234
|
+
if (encoded !== void 0) parts.push(`${key}:${encoded}`);
|
|
235
|
+
}
|
|
236
|
+
return `(${parts.join(",")})`;
|
|
237
|
+
}
|
|
238
|
+
function encodeVariables(vars) {
|
|
239
|
+
return encodeObject(vars);
|
|
240
|
+
}
|
|
241
|
+
function parseTupleUrn(urn) {
|
|
242
|
+
const open = urn.indexOf(":(");
|
|
243
|
+
if (open === -1 || !urn.endsWith(")")) return null;
|
|
244
|
+
const namespace = urn.slice(0, open).split(":").pop();
|
|
245
|
+
if (namespace === void 0 || namespace === "") return null;
|
|
246
|
+
const body = urn.slice(open + 2, -1);
|
|
247
|
+
const members = [];
|
|
248
|
+
let depth = 0;
|
|
249
|
+
let current = "";
|
|
250
|
+
for (const char of body) {
|
|
251
|
+
if (char === "(") depth++;
|
|
252
|
+
else if (char === ")") depth--;
|
|
253
|
+
if (depth < 0) return null;
|
|
254
|
+
if (char === "," && depth === 0) {
|
|
255
|
+
members.push(current);
|
|
256
|
+
current = "";
|
|
257
|
+
} else {
|
|
258
|
+
current += char;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
if (depth !== 0) return null;
|
|
262
|
+
members.push(current);
|
|
263
|
+
return { namespace, members };
|
|
264
|
+
}
|
|
265
|
+
function innerUrn(urn) {
|
|
266
|
+
const parsed = parseTupleUrn(urn);
|
|
267
|
+
const first = parsed?.members[0];
|
|
268
|
+
return first ?? urn;
|
|
269
|
+
}
|
|
270
|
+
var NAMESPACE_ALIASES = {
|
|
271
|
+
fs_miniProfile: "fsd_profile",
|
|
272
|
+
fs_profile: "fsd_profile"
|
|
273
|
+
};
|
|
274
|
+
function canonicalUrn(urn) {
|
|
275
|
+
const inner = innerUrn(urn);
|
|
276
|
+
const parts = inner.split(":");
|
|
277
|
+
const namespace = parts[2];
|
|
278
|
+
if (namespace === void 0) return inner;
|
|
279
|
+
const alias = NAMESPACE_ALIASES[namespace];
|
|
280
|
+
if (alias === void 0) return inner;
|
|
281
|
+
parts[2] = alias;
|
|
282
|
+
return parts.join(":");
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// src/format.ts
|
|
286
|
+
function text(value) {
|
|
287
|
+
if (typeof value === "string") return value.trim() || void 0;
|
|
288
|
+
if (value === null || typeof value !== "object") return void 0;
|
|
289
|
+
const node = value;
|
|
290
|
+
if (typeof node.text === "string") return node.text.trim() || void 0;
|
|
291
|
+
if (node.text !== null && typeof node.text === "object") return text(node.text);
|
|
292
|
+
return void 0;
|
|
293
|
+
}
|
|
294
|
+
function typeOf(node) {
|
|
295
|
+
const t = node.$type ?? node._type;
|
|
296
|
+
return typeof t === "string" ? t : void 0;
|
|
297
|
+
}
|
|
298
|
+
function cleanUrl(url) {
|
|
299
|
+
if (typeof url !== "string" || url === "") return void 0;
|
|
300
|
+
const cut = url.indexOf("?");
|
|
301
|
+
return cut === -1 ? url : url.slice(0, cut);
|
|
302
|
+
}
|
|
303
|
+
function defined(obj) {
|
|
304
|
+
for (const key of Object.keys(obj)) {
|
|
305
|
+
if (obj[key] === void 0) delete obj[key];
|
|
306
|
+
}
|
|
307
|
+
return obj;
|
|
308
|
+
}
|
|
309
|
+
function shapeSearchRow(node) {
|
|
310
|
+
const entityUrn = typeof node.entityUrn === "string" ? node.entityUrn : void 0;
|
|
311
|
+
return defined({
|
|
312
|
+
type: typeOf(node),
|
|
313
|
+
// The entity urn is composite — (profileUrn, SEARCH_SRP, DEFAULT) — and the
|
|
314
|
+
// member identity is its first member.
|
|
315
|
+
urn: entityUrn === void 0 ? void 0 : innerUrn(entityUrn),
|
|
316
|
+
name: text(node.title),
|
|
317
|
+
headline: text(node.primarySubtitle),
|
|
318
|
+
location: text(node.secondarySubtitle),
|
|
319
|
+
url: cleanUrl(node.navigationUrl)
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
function shapePost(node, index) {
|
|
323
|
+
const meta = node.updateMetadata;
|
|
324
|
+
const actor = node.actor;
|
|
325
|
+
const urn = typeof meta?.urn === "string" ? meta.urn : void 0;
|
|
326
|
+
const social = deref(node, "*socialDetail", index);
|
|
327
|
+
const counts = social === void 0 ? void 0 : deref(social, "*totalSocialActivityCounts", index);
|
|
328
|
+
return defined({
|
|
329
|
+
type: typeOf(node),
|
|
330
|
+
urn,
|
|
331
|
+
threadUrn: typeof social?.urn === "string" ? social.urn : void 0,
|
|
332
|
+
author: text(actor?.name),
|
|
333
|
+
// `text()` already trims; LinkedIn pads these with trailing spaces.
|
|
334
|
+
posted: text(actor?.subDescription),
|
|
335
|
+
text: text(node.commentary),
|
|
336
|
+
likes: numberOf(counts?.numLikes),
|
|
337
|
+
comments: numberOf(counts?.numComments),
|
|
338
|
+
shares: numberOf(counts?.numShares ?? social?.totalShares),
|
|
339
|
+
url: urn === void 0 ? void 0 : `https://www.linkedin.com/feed/update/${urn}/`
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
function numberOf(value) {
|
|
343
|
+
return typeof value === "number" ? value : void 0;
|
|
344
|
+
}
|
|
345
|
+
function deref(node, key, index) {
|
|
346
|
+
if (index === void 0) return void 0;
|
|
347
|
+
const ref = node[key];
|
|
348
|
+
if (typeof ref === "string") return index.get(ref);
|
|
349
|
+
if (ref === void 0) return void 0;
|
|
350
|
+
if (ref !== null && typeof ref === "object") {
|
|
351
|
+
for (const [k, v] of Object.entries(ref)) {
|
|
352
|
+
if (k.startsWith("*") && typeof v === "string") return index.get(v);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
return void 0;
|
|
356
|
+
}
|
|
357
|
+
function shapeProfile(node, index) {
|
|
358
|
+
const base = shapeMember(node);
|
|
359
|
+
const geo = deref(node, "geoLocation", index);
|
|
360
|
+
const position = deref(node, "profileTopPosition", index) ?? firstOfType(index, "profile.Position");
|
|
361
|
+
const education = deref(node, "profileTopEducation", index) ?? firstOfType(index, "profile.Education");
|
|
362
|
+
return defined({
|
|
363
|
+
...base,
|
|
364
|
+
location: text(geo?.defaultLocalizedName) ?? text(geo?.localizedName),
|
|
365
|
+
title: text(position?.title),
|
|
366
|
+
company: text(position?.companyName),
|
|
367
|
+
school: text(education?.schoolName)
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
function firstOfType(index, suffix) {
|
|
371
|
+
if (index === void 0) return void 0;
|
|
372
|
+
for (const node of new Set(index.values())) {
|
|
373
|
+
if (String(node.$type ?? "").endsWith(suffix)) return node;
|
|
374
|
+
}
|
|
375
|
+
return void 0;
|
|
376
|
+
}
|
|
377
|
+
function shapeMember(node) {
|
|
378
|
+
const first = text(node.firstName);
|
|
379
|
+
const last = text(node.lastName);
|
|
380
|
+
const publicId = text(node.publicIdentifier) ?? text(node.publicId);
|
|
381
|
+
const name = [first, last].filter(Boolean).join(" ");
|
|
382
|
+
return defined({
|
|
383
|
+
type: typeOf(node),
|
|
384
|
+
urn: typeof node.entityUrn === "string" ? node.entityUrn : void 0,
|
|
385
|
+
publicId,
|
|
386
|
+
name: name === "" ? void 0 : name,
|
|
387
|
+
headline: text(node.headline) ?? text(node.occupation),
|
|
388
|
+
url: publicId === void 0 ? void 0 : `https://www.linkedin.com/in/${publicId}/`
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
function shapeComment(node, index) {
|
|
392
|
+
const commenter = node.commenter;
|
|
393
|
+
const social = deref(node, "*socialDetail", index);
|
|
394
|
+
const counts = social === void 0 ? void 0 : deref(social, "*totalSocialActivityCounts", index);
|
|
395
|
+
return defined({
|
|
396
|
+
type: typeOf(node),
|
|
397
|
+
urn: typeof node.urn === "string" ? node.urn : void 0,
|
|
398
|
+
author: text(commenter?.title),
|
|
399
|
+
headline: text(commenter?.subtitle),
|
|
400
|
+
authorUrl: cleanUrl(commenter?.navigationUrl),
|
|
401
|
+
text: text(node.comment) ?? text(node.commentary),
|
|
402
|
+
likes: numberOf(counts?.numLikes),
|
|
403
|
+
postedAt: typeof node.createdAt === "number" ? new Date(node.createdAt).toISOString() : void 0,
|
|
404
|
+
edited: node.edited === true ? true : void 0,
|
|
405
|
+
url: cleanUrl(node.permalink)
|
|
406
|
+
});
|
|
407
|
+
}
|
|
408
|
+
function shapeReaction(node, index) {
|
|
409
|
+
const lockup = node.reactorLockup;
|
|
410
|
+
const actorUrn = typeof node.actorUrn === "string" ? node.actorUrn : void 0;
|
|
411
|
+
const profile = actorUrn === void 0 ? void 0 : index?.get(actorUrn);
|
|
412
|
+
return defined({
|
|
413
|
+
type: typeOf(node),
|
|
414
|
+
urn: actorUrn,
|
|
415
|
+
name: text(lockup?.title),
|
|
416
|
+
headline: text(lockup?.subtitle) ?? text(profile?.headline),
|
|
417
|
+
reaction: typeof node.reactionType === "string" ? node.reactionType : void 0,
|
|
418
|
+
url: cleanUrl(lockup?.navigationUrl)
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
function shapeEntity(node, index) {
|
|
422
|
+
try {
|
|
423
|
+
const t = (typeOf(node) ?? "").toLowerCase();
|
|
424
|
+
if (t.includes("entityresultviewmodel")) return shapeSearchRow(node);
|
|
425
|
+
if (t.endsWith("social.comment")) return shapeComment(node, index);
|
|
426
|
+
if (t.endsWith("social.reaction")) return shapeReaction(node, index);
|
|
427
|
+
if (t.includes("update")) return shapePost(node, index);
|
|
428
|
+
if (t.includes("profile")) return shapeMember(node);
|
|
429
|
+
return defined({
|
|
430
|
+
type: typeOf(node),
|
|
431
|
+
urn: typeof node.entityUrn === "string" ? node.entityUrn : void 0,
|
|
432
|
+
name: text(node.title) ?? text(node.name),
|
|
433
|
+
text: text(node.commentary) ?? text(node.text)
|
|
434
|
+
});
|
|
435
|
+
} catch {
|
|
436
|
+
return defined({ type: typeOf(node) });
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
function shapeAll(items, index) {
|
|
440
|
+
return items.map((node) => shapeEntity(node, index));
|
|
441
|
+
}
|
|
442
|
+
function project(rows, spec) {
|
|
443
|
+
const keys = spec.split(",").map((k) => k.trim()).filter((k) => k !== "");
|
|
444
|
+
if (keys.length === 0) return rows;
|
|
445
|
+
return rows.map((row) => {
|
|
446
|
+
const out = {};
|
|
447
|
+
for (const key of keys) {
|
|
448
|
+
if (row[key] !== void 0) out[key] = row[key];
|
|
449
|
+
}
|
|
450
|
+
return out;
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
var LEAD = ["name", "author", "title"];
|
|
454
|
+
var DETAIL = ["headline", "text", "location", "company", "posted", "reaction"];
|
|
455
|
+
function compactRows(rows) {
|
|
456
|
+
return rows.map((row) => {
|
|
457
|
+
const parts = [];
|
|
458
|
+
for (const key of LEAD) {
|
|
459
|
+
const v = row[key];
|
|
460
|
+
if (typeof v === "string" && v !== "") {
|
|
461
|
+
parts.push(v);
|
|
462
|
+
break;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
for (const key of DETAIL) {
|
|
466
|
+
const v = row[key];
|
|
467
|
+
if (typeof v === "string" && v !== "") parts.push(v);
|
|
468
|
+
}
|
|
469
|
+
const counts = ["likes", "comments"].map((k) => typeof row[k] === "number" ? `${row[k]} ${k}` : void 0).filter((v) => v !== void 0);
|
|
470
|
+
parts.push(...counts);
|
|
471
|
+
if (parts.length === 0) {
|
|
472
|
+
const urn = row.urn ?? row.type;
|
|
473
|
+
if (typeof urn === "string") parts.push(urn);
|
|
474
|
+
}
|
|
475
|
+
return parts.join(" \xB7 ").replace(/\s*\n\s*/g, " ");
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
// src/output.ts
|
|
480
|
+
function ok(command, data) {
|
|
481
|
+
return { ok: true, command, data };
|
|
482
|
+
}
|
|
483
|
+
function err(command, code, message, hint, status, retryAfterMs) {
|
|
484
|
+
const error = { code, message };
|
|
485
|
+
if (hint !== void 0) error.hint = hint;
|
|
486
|
+
if (status !== void 0) error.status = status;
|
|
487
|
+
if (retryAfterMs !== void 0) error.retryAfterMs = retryAfterMs;
|
|
488
|
+
return { ok: false, command, error };
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
// src/commands/cache.ts
|
|
492
|
+
var SOURCES = ["connections", "my-posts", "third-party"];
|
|
493
|
+
function corruptEnvelope(command, e) {
|
|
494
|
+
if (e instanceof CacheCorrupt) {
|
|
495
|
+
return err(
|
|
496
|
+
command,
|
|
497
|
+
"CACHE_CORRUPT",
|
|
498
|
+
e.message,
|
|
499
|
+
`Moved to ${e.quarantinedTo}. A corrupt cache is NOT treated as an empty one \u2014 that would trigger a full re-sync against LinkedIn. Inspect it, then re-run.`
|
|
500
|
+
);
|
|
501
|
+
}
|
|
502
|
+
throw e;
|
|
503
|
+
}
|
|
504
|
+
function render(rows, opts) {
|
|
505
|
+
if (opts.compact === true) return compactRows(rows);
|
|
506
|
+
if (opts.fields !== void 0 && opts.fields !== "") return project(rows, opts.fields);
|
|
507
|
+
return rows;
|
|
508
|
+
}
|
|
509
|
+
function runLocal(query, sources, since, limit, opts = {}) {
|
|
510
|
+
const requested = sources?.split(",").map((s) => s.trim()) ?? SOURCES;
|
|
511
|
+
const invalid = requested.filter((s) => !SOURCES.includes(s));
|
|
512
|
+
if (invalid.length > 0) {
|
|
513
|
+
return err(
|
|
514
|
+
"local",
|
|
515
|
+
"INVALID_INPUT",
|
|
516
|
+
`unknown source(s): ${invalid.join(", ")}`,
|
|
517
|
+
`valid sources: ${SOURCES.join(", ")}`
|
|
518
|
+
);
|
|
519
|
+
}
|
|
520
|
+
let sinceMs;
|
|
521
|
+
if (since !== void 0) {
|
|
522
|
+
const parsed = Date.parse(since);
|
|
523
|
+
if (Number.isNaN(parsed)) {
|
|
524
|
+
return err("local", "INVALID_INPUT", `could not parse --since '${since}'`, "use YYYY-MM-DD");
|
|
525
|
+
}
|
|
526
|
+
sinceMs = parsed;
|
|
527
|
+
}
|
|
528
|
+
try {
|
|
529
|
+
const db = openDb();
|
|
530
|
+
const rows = search(db, query ?? "", {
|
|
531
|
+
sources: requested,
|
|
532
|
+
...sinceMs === void 0 ? {} : { since: sinceMs },
|
|
533
|
+
limit
|
|
534
|
+
});
|
|
535
|
+
const total = count(db);
|
|
536
|
+
const shaped = rows.map((r) => ({
|
|
537
|
+
...JSON.parse(r.body ?? "{}"),
|
|
538
|
+
source: r.source,
|
|
539
|
+
cachedAt: new Date(r.updatedAt).toISOString()
|
|
540
|
+
}));
|
|
541
|
+
return ok("local", {
|
|
542
|
+
items: render(shaped, opts),
|
|
543
|
+
meta: {
|
|
544
|
+
returnedCount: rows.length,
|
|
545
|
+
cachedTotal: total,
|
|
546
|
+
sources: requested,
|
|
547
|
+
// An empty cache is not an empty LinkedIn — say which one this is.
|
|
548
|
+
note: total === 0 ? "The local cache is empty. Run a read command with --retain, or sync a source, before searching offline." : void 0
|
|
549
|
+
}
|
|
550
|
+
});
|
|
551
|
+
} catch (e) {
|
|
552
|
+
return corruptEnvelope("local", e);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
function runSourceRead(command, query, limit, opts = {}) {
|
|
556
|
+
const result = runLocal(query, command, void 0, limit, opts);
|
|
557
|
+
if (!result.ok) return result;
|
|
558
|
+
const data = result.data;
|
|
559
|
+
const meta = data.meta;
|
|
560
|
+
if (meta.cachedTotal === 0 || meta.returnedCount === 0) {
|
|
561
|
+
meta.note = `Nothing cached for '${command}'. Run \`lnrelay sync ${command}\` first \u2014 this command reads the local cache and makes no network call.`;
|
|
562
|
+
}
|
|
563
|
+
return ok(command, data);
|
|
564
|
+
}
|
|
565
|
+
function runCacheStatus() {
|
|
566
|
+
try {
|
|
567
|
+
const db = openDb();
|
|
568
|
+
return ok("cache-status", {
|
|
569
|
+
total: count(db),
|
|
570
|
+
bySource: Object.fromEntries(SOURCES.map((s) => [s, count(db, s)])),
|
|
571
|
+
checkpoints: Object.fromEntries(SOURCES.map((s) => [s, getCheckpoint(db, s) ?? null])),
|
|
572
|
+
retention: "Third-party records expire 30 days after capture; the body is deleted and an identity stub remains so a re-fetch is a visible choice. Owner data never expires."
|
|
573
|
+
});
|
|
574
|
+
} catch (e) {
|
|
575
|
+
return corruptEnvelope("cache-status", e);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
function retain(source, items) {
|
|
579
|
+
const rows = items.filter((i) => typeof i.urn === "string" && i.urn !== "").map((i) => ({
|
|
580
|
+
urn: i.urn,
|
|
581
|
+
body: i,
|
|
582
|
+
text: [i.name, i.headline, i.location, i.text, i.author, i.company, i.title].filter((v) => typeof v === "string").join(" ")
|
|
583
|
+
}));
|
|
584
|
+
if (rows.length === 0) return { skipped: "no items carried a urn to key on" };
|
|
585
|
+
try {
|
|
586
|
+
return upsert(openDb(), source, rows);
|
|
587
|
+
} catch (e) {
|
|
588
|
+
return { skipped: e.message };
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
// src/progress.ts
|
|
593
|
+
function progressReporter(quiet, write = (s) => {
|
|
594
|
+
process.stderr.write(s);
|
|
595
|
+
}) {
|
|
596
|
+
return (msg) => {
|
|
597
|
+
if (!quiet) write(`${msg}
|
|
598
|
+
`);
|
|
599
|
+
};
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
// src/engine/budget.ts
|
|
603
|
+
var HOUR = 36e5;
|
|
604
|
+
var DAY = 864e5;
|
|
605
|
+
var CAPS = {
|
|
606
|
+
profile: {
|
|
607
|
+
perDay: 30,
|
|
608
|
+
provenance: "vendor-lore",
|
|
609
|
+
note: "transplanted from jjuanrivvera/linkedin-cli's job-detail cap"
|
|
610
|
+
},
|
|
611
|
+
search: { perDay: 25, provenance: "guessed", note: "no corroborated figure exists" },
|
|
612
|
+
page: { perDay: 60, provenance: "guessed", note: "thread/feed pagination" },
|
|
613
|
+
write: {
|
|
614
|
+
perDay: 10,
|
|
615
|
+
provenance: "guessed",
|
|
616
|
+
note: "deliberately below the weakly-reported ~20/day connection lore"
|
|
617
|
+
},
|
|
618
|
+
global: { perDay: 250, provenance: "guessed", note: "all classes combined" }
|
|
619
|
+
};
|
|
620
|
+
var MIN_GAP_MS = 3e3;
|
|
621
|
+
function emptyLedger() {
|
|
622
|
+
return { spends: {} };
|
|
623
|
+
}
|
|
624
|
+
function within(times, now, window) {
|
|
625
|
+
if (times === void 0) return [];
|
|
626
|
+
return times.filter((t) => now - t < window);
|
|
627
|
+
}
|
|
628
|
+
function allSpends(ledger, now) {
|
|
629
|
+
return Object.values(ledger.spends).flatMap((times) => within(times, now, DAY));
|
|
630
|
+
}
|
|
631
|
+
function spend(ledger, cls, now) {
|
|
632
|
+
const recent = allSpends(ledger, now);
|
|
633
|
+
const last = recent.length > 0 ? Math.max(...recent) : void 0;
|
|
634
|
+
if (last !== void 0 && now - last < MIN_GAP_MS) {
|
|
635
|
+
return {
|
|
636
|
+
error: {
|
|
637
|
+
code: "BUDGET_EXHAUSTED",
|
|
638
|
+
message: `minimum gap of ${MIN_GAP_MS}ms between calls not met`,
|
|
639
|
+
hint: "requests are paced deliberately; wait and retry"
|
|
640
|
+
}
|
|
641
|
+
};
|
|
642
|
+
}
|
|
643
|
+
if (recent.length >= CAPS.global.perDay) {
|
|
644
|
+
return {
|
|
645
|
+
error: {
|
|
646
|
+
code: "BUDGET_EXHAUSTED",
|
|
647
|
+
message: `global daily cap of ${CAPS.global.perDay} calls reached`,
|
|
648
|
+
hint: "resets on a rolling 24h window; see `lnrelay budget`"
|
|
649
|
+
}
|
|
650
|
+
};
|
|
651
|
+
}
|
|
652
|
+
const cap = CAPS[cls];
|
|
653
|
+
const forClass = within(ledger.spends[cls], now, DAY);
|
|
654
|
+
if (forClass.length >= cap.perDay) {
|
|
655
|
+
return {
|
|
656
|
+
error: {
|
|
657
|
+
code: "BUDGET_EXHAUSTED",
|
|
658
|
+
message: `daily cap of ${cap.perDay} reached for '${cls}'`,
|
|
659
|
+
hint: `cap provenance: ${cap.provenance} (${cap.note}). See \`lnrelay budget\`.`
|
|
660
|
+
}
|
|
661
|
+
};
|
|
662
|
+
}
|
|
663
|
+
return {
|
|
664
|
+
permit: { class: cls, issuedAt: now },
|
|
665
|
+
ledger: { spends: { ...ledger.spends, [cls]: [...forClass, now] } }
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
function summarise(ledger, cls, now) {
|
|
669
|
+
const cap = CAPS[cls];
|
|
670
|
+
const spent = cls === "global" ? allSpends(ledger, now).length : within(ledger.spends[cls], now, DAY).length;
|
|
671
|
+
const remaining = Math.max(0, cap.perDay - spent);
|
|
672
|
+
const summary = {
|
|
673
|
+
class: cls,
|
|
674
|
+
spentInWindow: spent,
|
|
675
|
+
cap: cap.perDay,
|
|
676
|
+
remaining,
|
|
677
|
+
capProvenance: cap.provenance
|
|
678
|
+
};
|
|
679
|
+
if (remaining / cap.perDay < 0.25) {
|
|
680
|
+
summary.warning = `only ${remaining} of ${cap.perDay} '${cls}' calls left in this 24h window \u2014 consider stopping`;
|
|
681
|
+
}
|
|
682
|
+
return summary;
|
|
683
|
+
}
|
|
684
|
+
function openCooldown(reason, now) {
|
|
685
|
+
if (reason === "CHALLENGE_DETECTED") {
|
|
686
|
+
return { reason, since: now, until: null, clearRequires: "human" };
|
|
687
|
+
}
|
|
688
|
+
const duration = reason === "REQUEST_DENIED" ? 6 * HOUR : HOUR;
|
|
689
|
+
return { reason, since: now, until: now + duration, clearRequires: "time" };
|
|
690
|
+
}
|
|
691
|
+
function activeCooldown(cooldown, now) {
|
|
692
|
+
if (cooldown === null) return false;
|
|
693
|
+
if (cooldown.until === null) return true;
|
|
694
|
+
return now < cooldown.until;
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
// src/engine/auth.ts
|
|
698
|
+
function csrfToken(jsessionId) {
|
|
699
|
+
return jsessionId.replace(/"/g, "");
|
|
700
|
+
}
|
|
701
|
+
function buildHeaders(session) {
|
|
702
|
+
return {
|
|
703
|
+
cookie: `li_at=${session.liAt}; JSESSIONID=${session.jsessionId}`,
|
|
704
|
+
"csrf-token": csrfToken(session.jsessionId),
|
|
705
|
+
"x-restli-protocol-version": "2.0.0",
|
|
706
|
+
accept: "application/vnd.linkedin.normalized+json+2.1",
|
|
707
|
+
"x-li-lang": "en_US",
|
|
708
|
+
"user-agent": session.userAgent
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
// src/engine/classify.ts
|
|
713
|
+
var CHALLENGE_MARKERS = /checkpoint|challenge|captcha|security verification|unusual activity/i;
|
|
714
|
+
var LOGIN_REDIRECT = /\/login|\/uas\/login|session_redirect/i;
|
|
715
|
+
function fail(code, message, extra = {}) {
|
|
716
|
+
return { outcome: "error", code, message, retry: false, ...extra };
|
|
717
|
+
}
|
|
718
|
+
var CHALLENGE_HINT = "Open LinkedIn in a real browser, clear the challenge, then `lnrelay budget --reset-cooldown --confirm`.";
|
|
719
|
+
function classifyRedirect(location) {
|
|
720
|
+
if (CHALLENGE_MARKERS.test(location)) {
|
|
721
|
+
return fail("CHALLENGE_DETECTED", `redirected to a challenge: ${location}`, {
|
|
722
|
+
cooldown: "CHALLENGE_DETECTED",
|
|
723
|
+
hint: CHALLENGE_HINT
|
|
724
|
+
});
|
|
725
|
+
}
|
|
726
|
+
if (LOGIN_REDIRECT.test(location)) {
|
|
727
|
+
return fail("AUTH_FAILED", "redirected to the login page", {
|
|
728
|
+
hint: "This signature means expired cookies, NOT bot detection. Re-run `lnrelay login`."
|
|
729
|
+
});
|
|
730
|
+
}
|
|
731
|
+
return fail("FETCH_FAILED", `unexpected redirect to ${location || "(none)"}`);
|
|
732
|
+
}
|
|
733
|
+
function classifyBody(body) {
|
|
734
|
+
if (CHALLENGE_MARKERS.test(body.slice(0, 4e3))) {
|
|
735
|
+
return fail("CHALLENGE_DETECTED", "a challenge page was returned with status 200", {
|
|
736
|
+
cooldown: "CHALLENGE_DETECTED",
|
|
737
|
+
hint: CHALLENGE_HINT
|
|
738
|
+
});
|
|
739
|
+
}
|
|
740
|
+
let json;
|
|
741
|
+
try {
|
|
742
|
+
json = JSON.parse(body);
|
|
743
|
+
} catch {
|
|
744
|
+
return fail("SCHEMA_DRIFT", "response was 200 but not JSON", {
|
|
745
|
+
hint: "LinkedIn may have served HTML \u2014 inspect the raw body."
|
|
746
|
+
});
|
|
747
|
+
}
|
|
748
|
+
const envelope = json;
|
|
749
|
+
const innerStatus = envelope.data?.status;
|
|
750
|
+
if (typeof innerStatus === "number" && innerStatus >= 400) {
|
|
751
|
+
return fail("SCHEMA_DRIFT", `body carries an inner status ${innerStatus}`, {
|
|
752
|
+
hint: "The endpoint answered but reported a failure. Re-capture the operation."
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
if (referencesUrns(envelope.data) && (envelope.included?.length ?? 0) === 0) {
|
|
756
|
+
return fail("SCHEMA_DRIFT", "data references entities but included[] is empty", {
|
|
757
|
+
hint: "Decoration failed wholesale \u2014 this is a failed fetch, not an empty result."
|
|
758
|
+
});
|
|
759
|
+
}
|
|
760
|
+
return { outcome: "ok", retry: false, json };
|
|
761
|
+
}
|
|
762
|
+
function classify(res) {
|
|
763
|
+
const headers = res.headers ?? {};
|
|
764
|
+
if (res.status >= 300 && res.status < 400) {
|
|
765
|
+
return classifyRedirect(headers.location ?? "");
|
|
766
|
+
}
|
|
767
|
+
if (res.status === 999) {
|
|
768
|
+
return fail("REQUEST_DENIED", "LinkedIn returned HTTP 999 (Request Denied)", {
|
|
769
|
+
cooldown: "REQUEST_DENIED",
|
|
770
|
+
hint: "A network-layer bot block that lifts only as traffic normalises. Stop making requests."
|
|
771
|
+
});
|
|
772
|
+
}
|
|
773
|
+
if (res.status === 429) {
|
|
774
|
+
const retryAfter = Number(headers["retry-after"]);
|
|
775
|
+
const out = fail("RATE_LIMITED", "LinkedIn throttled this request", {
|
|
776
|
+
cooldown: "RATE_LIMITED",
|
|
777
|
+
hint: "Not retried automatically \u2014 a throttle is the warning shot before a restriction."
|
|
778
|
+
});
|
|
779
|
+
if (Number.isFinite(retryAfter)) out.retryAfterMs = retryAfter * 1e3;
|
|
780
|
+
return out;
|
|
781
|
+
}
|
|
782
|
+
if (res.status === 401 || res.status === 403) {
|
|
783
|
+
return fail("AUTH_FAILED", `LinkedIn rejected the session (${res.status})`, {
|
|
784
|
+
hint: "Usually expired cookies. Re-run `lnrelay login`."
|
|
785
|
+
});
|
|
786
|
+
}
|
|
787
|
+
if (res.status === 410) {
|
|
788
|
+
return fail("SCHEMA_DRIFT", "endpoint returned 410 Gone \u2014 it no longer exists", {
|
|
789
|
+
hint: "Re-capture the operation with scripts/observe.ts and update src/engine/contracts.ts."
|
|
790
|
+
});
|
|
791
|
+
}
|
|
792
|
+
if (res.status === 400) {
|
|
793
|
+
const hint = /queryid/i.test(res.body) ? "re-capture the queryId with scripts/observe.ts and update src/engine/contracts.ts" : "check the encoded variables against a live capture";
|
|
794
|
+
return fail("SCHEMA_DRIFT", `LinkedIn rejected the request shape (400)`, { hint });
|
|
795
|
+
}
|
|
796
|
+
if (res.status === 404) {
|
|
797
|
+
return fail("NOT_FOUND", "no such resource");
|
|
798
|
+
}
|
|
799
|
+
if (res.status !== 200) {
|
|
800
|
+
return fail("FETCH_FAILED", `unexpected status ${res.status}`);
|
|
801
|
+
}
|
|
802
|
+
return classifyBody(res.body);
|
|
803
|
+
}
|
|
804
|
+
function referencesUrns(data) {
|
|
805
|
+
if (data === void 0) return false;
|
|
806
|
+
let found = false;
|
|
807
|
+
const walk = (node) => {
|
|
808
|
+
if (found || node === null || typeof node !== "object") return;
|
|
809
|
+
if (Array.isArray(node)) {
|
|
810
|
+
for (const item of node) walk(item);
|
|
811
|
+
return;
|
|
812
|
+
}
|
|
813
|
+
for (const [key, value] of Object.entries(node)) {
|
|
814
|
+
if (key.startsWith("*") && Array.isArray(value) && value.length > 0) {
|
|
815
|
+
found = true;
|
|
816
|
+
return;
|
|
817
|
+
}
|
|
818
|
+
if (typeof value === "string" && value.startsWith("urn:li:")) {
|
|
819
|
+
found = true;
|
|
820
|
+
return;
|
|
821
|
+
}
|
|
822
|
+
walk(value);
|
|
823
|
+
}
|
|
824
|
+
};
|
|
825
|
+
walk(data);
|
|
826
|
+
return found;
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
// src/engine/client.ts
|
|
830
|
+
var MAX_GAP_MS = 15e3;
|
|
831
|
+
function createClient(session, deps) {
|
|
832
|
+
async function request(spec) {
|
|
833
|
+
const now = deps.now();
|
|
834
|
+
const cooldown = deps.loadCooldown();
|
|
835
|
+
if (activeCooldown(cooldown, now)) {
|
|
836
|
+
const until = cooldown?.until === null ? "indefinitely" : `until ${new Date(cooldown?.until ?? 0).toISOString()}`;
|
|
837
|
+
return {
|
|
838
|
+
ok: false,
|
|
839
|
+
code: "COOLDOWN_ACTIVE",
|
|
840
|
+
message: `refusing to call LinkedIn: ${cooldown?.reason} cooldown is active ${until}`,
|
|
841
|
+
hint: cooldown?.clearRequires === "human" ? "Log in through a real browser, clear the challenge, then `lnrelay budget --reset-cooldown --confirm`." : "Wait for it to lift, or inspect `lnrelay risk`."
|
|
842
|
+
};
|
|
843
|
+
}
|
|
844
|
+
const ledger = deps.loadLedger();
|
|
845
|
+
const result = spend(ledger, spec.spendClass, now);
|
|
846
|
+
if ("error" in result) {
|
|
847
|
+
return {
|
|
848
|
+
ok: false,
|
|
849
|
+
code: result.error.code,
|
|
850
|
+
message: result.error.message,
|
|
851
|
+
hint: result.error.hint
|
|
852
|
+
};
|
|
853
|
+
}
|
|
854
|
+
deps.saveLedger(result.ledger);
|
|
855
|
+
const gap = MIN_GAP_MS + Math.floor(deps.random() * (MAX_GAP_MS - MIN_GAP_MS));
|
|
856
|
+
deps.progress?.(`${spec.operation}: pacing ${Math.round(gap / 1e3)}s before the request\u2026`);
|
|
857
|
+
await deps.sleep(gap);
|
|
858
|
+
deps.progress?.(`${spec.operation}: requesting\u2026`);
|
|
859
|
+
const raw = await fetchRaw(spec, session, deps);
|
|
860
|
+
if (raw === null) {
|
|
861
|
+
return { ok: false, code: "FETCH_FAILED", message: "the request could not be completed" };
|
|
862
|
+
}
|
|
863
|
+
const classification = classify(raw);
|
|
864
|
+
if (classification.cooldown !== void 0) {
|
|
865
|
+
deps.saveCooldown(openCooldown(classification.cooldown, deps.now()));
|
|
866
|
+
}
|
|
867
|
+
if (classification.outcome === "error") {
|
|
868
|
+
const out = {
|
|
869
|
+
ok: false,
|
|
870
|
+
code: classification.code ?? "FETCH_FAILED",
|
|
871
|
+
message: classification.message ?? "request failed"
|
|
872
|
+
};
|
|
873
|
+
if (classification.hint !== void 0) out.hint = classification.hint;
|
|
874
|
+
if (classification.retryAfterMs !== void 0) out.retryAfterMs = classification.retryAfterMs;
|
|
875
|
+
return out;
|
|
876
|
+
}
|
|
877
|
+
return { ok: true, json: classification.json, classification };
|
|
878
|
+
}
|
|
879
|
+
return { request };
|
|
880
|
+
}
|
|
881
|
+
async function fetchRaw(spec, session, deps) {
|
|
882
|
+
try {
|
|
883
|
+
const res = await deps.fetch(spec.url, {
|
|
884
|
+
method: spec.method ?? "GET",
|
|
885
|
+
headers: buildHeaders(session),
|
|
886
|
+
// Manual, so a login or checkpoint redirect is classified rather than
|
|
887
|
+
// silently followed into an HTML page that parses as "no data".
|
|
888
|
+
redirect: "manual"
|
|
889
|
+
});
|
|
890
|
+
const headers = {};
|
|
891
|
+
res.headers.forEach((value, key) => {
|
|
892
|
+
headers[key.toLowerCase()] = value;
|
|
893
|
+
});
|
|
894
|
+
return { status: res.status, body: await res.text(), headers };
|
|
895
|
+
} catch {
|
|
896
|
+
return null;
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
// src/engine/contracts.ts
|
|
901
|
+
var VOYAGER = "https://www.linkedin.com/voyager/api";
|
|
902
|
+
var CONTRACTS = {
|
|
903
|
+
me: {
|
|
904
|
+
name: "me",
|
|
905
|
+
transport: "voyager-restli",
|
|
906
|
+
path: `${VOYAGER}/me`,
|
|
907
|
+
provenance: "verified",
|
|
908
|
+
capturedAt: "2026-08-01"
|
|
909
|
+
},
|
|
910
|
+
// Three `voyagerIdentityDashProfiles` queryIds were observed on one page —
|
|
911
|
+
// they are different PROJECTIONS of one operation, and picking the wrong one
|
|
912
|
+
// gets you a 200 containing nothing useful:
|
|
913
|
+
//
|
|
914
|
+
// b5c27c04… identity only — entityUrn + versionTag. Looks like success.
|
|
915
|
+
// e9b08094… the real profile: headline, geo, top position, education. ← this
|
|
916
|
+
// da93c92b… 400s with (profileUrn:…); its variables shape is unknown.
|
|
917
|
+
//
|
|
918
|
+
// None of them returns firstName/lastName/publicIdentifier — LinkedIn splits
|
|
919
|
+
// names into a projection we have not identified. Documented rather than
|
|
920
|
+
// faked; the caller already knows who they asked for.
|
|
921
|
+
profile: {
|
|
922
|
+
name: "profile",
|
|
923
|
+
transport: "voyager-graphql",
|
|
924
|
+
path: `${VOYAGER}/graphql`,
|
|
925
|
+
queryId: "voyagerIdentityDashProfiles.e9b0809465a07db1f02e70a82d455e10",
|
|
926
|
+
provenance: "verified",
|
|
927
|
+
capturedAt: "2026-08-01"
|
|
928
|
+
},
|
|
929
|
+
feed: {
|
|
930
|
+
name: "feed",
|
|
931
|
+
transport: "voyager-restli",
|
|
932
|
+
path: `${VOYAGER}/feed/updatesV2`,
|
|
933
|
+
provenance: "verified",
|
|
934
|
+
capturedAt: "2026-08-01"
|
|
935
|
+
},
|
|
936
|
+
// The November-2024 queryId, still returning 200 in August 2026 — roughly 21
|
|
937
|
+
// months unchanged. Notable because kill criterion #3 assumed queryIds might
|
|
938
|
+
// rotate weekly; on this evidence they are build-pinned but long-lived.
|
|
939
|
+
search: {
|
|
940
|
+
name: "search",
|
|
941
|
+
transport: "voyager-graphql",
|
|
942
|
+
path: `${VOYAGER}/graphql`,
|
|
943
|
+
queryId: "voyagerSearchDashClusters.b0928897b71bd00a5a7291755dcd64f0",
|
|
944
|
+
provenance: "verified",
|
|
945
|
+
capturedAt: "2026-08-01"
|
|
946
|
+
},
|
|
947
|
+
reactions: {
|
|
948
|
+
name: "reactions",
|
|
949
|
+
transport: "voyager-graphql",
|
|
950
|
+
path: `${VOYAGER}/graphql`,
|
|
951
|
+
queryId: "voyagerSocialDashReactions.41ebf31a9f4c4a84e35a49d5abc9010b",
|
|
952
|
+
provenance: "verified",
|
|
953
|
+
capturedAt: "2026-08-02"
|
|
954
|
+
},
|
|
955
|
+
// Comments. The variables carry a COMPOSITE socialDetailUrn assembled from the
|
|
956
|
+
// post's own urn, repeated, plus a highlightedReply placeholder:
|
|
957
|
+
//
|
|
958
|
+
// urn:li:fsd_socialDetail:(<postUrn>,<postUrn>,urn:li:highlightedReply:-)
|
|
959
|
+
//
|
|
960
|
+
// Two things were established by probing rather than assumed. Our codec's
|
|
961
|
+
// percent-encoding of that urn's colons and parens is REQUIRED — the literal
|
|
962
|
+
// form returns 400. And an `urn:li:activity:` post urn works directly, so
|
|
963
|
+
// `post` does not need a feed lookup to find the ugcPost form first.
|
|
964
|
+
comments: {
|
|
965
|
+
name: "comments",
|
|
966
|
+
transport: "voyager-graphql",
|
|
967
|
+
path: `${VOYAGER}/graphql`,
|
|
968
|
+
queryId: "voyagerSocialDashComments.afec6d88d7810d45548797a8dac4fb87",
|
|
969
|
+
provenance: "verified",
|
|
970
|
+
capturedAt: "2026-08-02"
|
|
971
|
+
},
|
|
972
|
+
// The member's own posts. Verified 200; returns an empty collection on an
|
|
973
|
+
// account with no posts, which is a true empty rather than a failure.
|
|
974
|
+
myPosts: {
|
|
975
|
+
name: "myPosts",
|
|
976
|
+
transport: "voyager-graphql",
|
|
977
|
+
path: `${VOYAGER}/graphql`,
|
|
978
|
+
queryId: "voyagerFeedDashProfileUpdates.20c70fe0314184158516a7ec004c0408",
|
|
979
|
+
provenance: "verified",
|
|
980
|
+
capturedAt: "2026-08-02"
|
|
981
|
+
},
|
|
982
|
+
// Discovered and returns 200, but the projection is useless: 39 KB containing
|
|
983
|
+
// one `guideFetcher` wrapper and no name, tagline, description or headcount.
|
|
984
|
+
// The same trap as the thin profile projection, so it stays unverified and
|
|
985
|
+
// `company` does not ship. The richer path is probably
|
|
986
|
+
// voyagerOrganizationDashViewWrapper with an organizationalPageUrn, which
|
|
987
|
+
// first requires resolving that urn — unfinished work, not a dead end.
|
|
988
|
+
company: {
|
|
989
|
+
name: "company",
|
|
990
|
+
transport: "voyager-graphql",
|
|
991
|
+
path: `${VOYAGER}/graphql`,
|
|
992
|
+
queryId: "voyagerOrganizationDashCompanies.148b1aebfadd0a455f32806df656c3c1",
|
|
993
|
+
provenance: "discovered",
|
|
994
|
+
capturedAt: "2026-08-02"
|
|
995
|
+
},
|
|
996
|
+
// A job CARDS list, not a job detail. Observed on /jobs/collections/recommended
|
|
997
|
+
// and never exercised; `job` needs a detail endpoint we have not captured.
|
|
998
|
+
jobCards: {
|
|
999
|
+
name: "jobCards",
|
|
1000
|
+
transport: "voyager-graphql",
|
|
1001
|
+
path: `${VOYAGER}/graphql`,
|
|
1002
|
+
queryId: "voyagerJobsDashJobCards.e5b6b761ede078dabe8ad857aa42c220",
|
|
1003
|
+
provenance: "discovered",
|
|
1004
|
+
capturedAt: "2026-08-02"
|
|
1005
|
+
}
|
|
1006
|
+
};
|
|
1007
|
+
var RETIRED = {
|
|
1008
|
+
profileView: {
|
|
1009
|
+
path: `${VOYAGER}/identity/profiles/{id}/profileView`,
|
|
1010
|
+
diedBy: "2026-08-01",
|
|
1011
|
+
note: "Returns 410 Gone inside a well-formed Voyager envelope. Superseded by the `profile` contract above. Every client that reads profiles through this is broken."
|
|
1012
|
+
}
|
|
1013
|
+
};
|
|
1014
|
+
function shippableContracts() {
|
|
1015
|
+
return Object.fromEntries(
|
|
1016
|
+
Object.entries(CONTRACTS).filter(([, c]) => c.provenance === "verified")
|
|
1017
|
+
);
|
|
1018
|
+
}
|
|
1019
|
+
function contractFor(name) {
|
|
1020
|
+
return shippableContracts()[name];
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
// src/engine/parse.ts
|
|
1024
|
+
var DROP_TYPE_FRAGMENTS = [
|
|
1025
|
+
"promoted",
|
|
1026
|
+
"sponsored",
|
|
1027
|
+
"adunit",
|
|
1028
|
+
"peopleyoumayknow",
|
|
1029
|
+
"recommendedentity",
|
|
1030
|
+
"discoveryentity",
|
|
1031
|
+
"discoverymodule",
|
|
1032
|
+
"promptcomponent",
|
|
1033
|
+
"carouselcomponent",
|
|
1034
|
+
"lego",
|
|
1035
|
+
// Search-result chrome, observed live alongside real results.
|
|
1036
|
+
"feedbackcard",
|
|
1037
|
+
"lazyloadedactions",
|
|
1038
|
+
"bannercard",
|
|
1039
|
+
"searchsuggestion",
|
|
1040
|
+
"keywordssuggestion",
|
|
1041
|
+
"queryclarification",
|
|
1042
|
+
"knowledgecard",
|
|
1043
|
+
"topicalquestion"
|
|
1044
|
+
];
|
|
1045
|
+
var DECORATION_FRAGMENTS = [
|
|
1046
|
+
"socialdetail",
|
|
1047
|
+
"socialactivitycounts",
|
|
1048
|
+
"socialpermissions",
|
|
1049
|
+
"saveaction",
|
|
1050
|
+
"updateactions",
|
|
1051
|
+
"hidepostaction",
|
|
1052
|
+
"followinginfo",
|
|
1053
|
+
"miniprofile",
|
|
1054
|
+
"minicompany",
|
|
1055
|
+
"videoplaymetadata",
|
|
1056
|
+
"hidecommentaction",
|
|
1057
|
+
"followingstate",
|
|
1058
|
+
"followaction",
|
|
1059
|
+
"connectaction"
|
|
1060
|
+
];
|
|
1061
|
+
function typeOf2(node) {
|
|
1062
|
+
const t = node.$type ?? node._type;
|
|
1063
|
+
return typeof t === "string" ? t : "";
|
|
1064
|
+
}
|
|
1065
|
+
function isPromotedPost(node) {
|
|
1066
|
+
const actor = node.actor;
|
|
1067
|
+
const sub = actor?.subDescription?.text;
|
|
1068
|
+
return typeof sub === "string" && /^promoted\b/i.test(sub.trim());
|
|
1069
|
+
}
|
|
1070
|
+
function isNoise(node) {
|
|
1071
|
+
if (isPromotedPost(node)) return true;
|
|
1072
|
+
const t = typeOf2(node).toLowerCase();
|
|
1073
|
+
if (t === "") return false;
|
|
1074
|
+
return DROP_TYPE_FRAGMENTS.some((f) => t.includes(f));
|
|
1075
|
+
}
|
|
1076
|
+
function isDecoration(node) {
|
|
1077
|
+
const t = typeOf2(node).toLowerCase();
|
|
1078
|
+
return DECORATION_FRAGMENTS.some((f) => t.includes(f));
|
|
1079
|
+
}
|
|
1080
|
+
var KNOWN_CONTENT = [
|
|
1081
|
+
"updatev2",
|
|
1082
|
+
"profile",
|
|
1083
|
+
"jobposting",
|
|
1084
|
+
"company",
|
|
1085
|
+
"comment",
|
|
1086
|
+
"reaction",
|
|
1087
|
+
"entityresult"
|
|
1088
|
+
];
|
|
1089
|
+
function isKnown(node) {
|
|
1090
|
+
const t = typeOf2(node).toLowerCase();
|
|
1091
|
+
return KNOWN_CONTENT.some((f) => t.includes(f)) || isDecoration(node) || isNoise(node);
|
|
1092
|
+
}
|
|
1093
|
+
function indexIncluded(included) {
|
|
1094
|
+
const index = /* @__PURE__ */ new Map();
|
|
1095
|
+
if (!Array.isArray(included)) return index;
|
|
1096
|
+
for (const raw of included) {
|
|
1097
|
+
if (raw === null || typeof raw !== "object") continue;
|
|
1098
|
+
const node = raw;
|
|
1099
|
+
const urn = node.entityUrn;
|
|
1100
|
+
if (typeof urn !== "string") continue;
|
|
1101
|
+
const canonical = canonicalUrn(urn);
|
|
1102
|
+
index.set(canonical, node);
|
|
1103
|
+
if (canonical !== urn) index.set(urn, node);
|
|
1104
|
+
}
|
|
1105
|
+
return index;
|
|
1106
|
+
}
|
|
1107
|
+
function resolveRefs(refs, index) {
|
|
1108
|
+
const resolved = [];
|
|
1109
|
+
const unresolved = [];
|
|
1110
|
+
if (!Array.isArray(refs)) return { resolved, unresolved };
|
|
1111
|
+
for (const ref of refs) {
|
|
1112
|
+
if (typeof ref !== "string") continue;
|
|
1113
|
+
const node = index.get(ref) ?? index.get(canonicalUrn(ref));
|
|
1114
|
+
if (node === void 0) unresolved.push(ref);
|
|
1115
|
+
else resolved.push(node);
|
|
1116
|
+
}
|
|
1117
|
+
return { resolved, unresolved };
|
|
1118
|
+
}
|
|
1119
|
+
function findRefs(data) {
|
|
1120
|
+
if (data === null || typeof data !== "object") return [];
|
|
1121
|
+
const queue = [data];
|
|
1122
|
+
while (queue.length > 0) {
|
|
1123
|
+
const node = queue.shift();
|
|
1124
|
+
if (node === null || typeof node !== "object") continue;
|
|
1125
|
+
if (Array.isArray(node)) {
|
|
1126
|
+
queue.push(...node);
|
|
1127
|
+
continue;
|
|
1128
|
+
}
|
|
1129
|
+
for (const [key, value] of Object.entries(node)) {
|
|
1130
|
+
if (key.startsWith("*") && Array.isArray(value)) return value;
|
|
1131
|
+
}
|
|
1132
|
+
for (const value of Object.values(node)) {
|
|
1133
|
+
if (value !== null && typeof value === "object") queue.push(value);
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
const refs = [];
|
|
1137
|
+
const walk = (node) => {
|
|
1138
|
+
if (node === null || typeof node !== "object") return;
|
|
1139
|
+
if (Array.isArray(node)) {
|
|
1140
|
+
for (const item of node) walk(item);
|
|
1141
|
+
return;
|
|
1142
|
+
}
|
|
1143
|
+
for (const [key, value] of Object.entries(node)) {
|
|
1144
|
+
if (key.startsWith("*") && typeof value === "string") refs.push(value);
|
|
1145
|
+
else walk(value);
|
|
1146
|
+
}
|
|
1147
|
+
};
|
|
1148
|
+
walk(data);
|
|
1149
|
+
return refs;
|
|
1150
|
+
}
|
|
1151
|
+
function parseSingle(payload) {
|
|
1152
|
+
const envelope = payload ?? {};
|
|
1153
|
+
const nodes = [...new Set(indexIncluded(envelope.included).values())];
|
|
1154
|
+
if (nodes.length === 0) return void 0;
|
|
1155
|
+
return nodes.find((n) => !isNoise(n) && !isDecoration(n)) ?? nodes[0];
|
|
1156
|
+
}
|
|
1157
|
+
function parseCollection(payload, opts) {
|
|
1158
|
+
const envelope = payload ?? {};
|
|
1159
|
+
const index = indexIncluded(envelope.included);
|
|
1160
|
+
const refs = findRefs(envelope.data);
|
|
1161
|
+
const { resolved, unresolved } = resolveRefs(refs, index);
|
|
1162
|
+
const items = [];
|
|
1163
|
+
const unknownTypes = /* @__PURE__ */ new Map();
|
|
1164
|
+
let excludedCount = 0;
|
|
1165
|
+
let unknownCount = 0;
|
|
1166
|
+
for (const node of resolved) {
|
|
1167
|
+
try {
|
|
1168
|
+
if (isNoise(node) || isDecoration(node)) {
|
|
1169
|
+
excludedCount++;
|
|
1170
|
+
continue;
|
|
1171
|
+
}
|
|
1172
|
+
if (!isKnown(node)) {
|
|
1173
|
+
const t = typeOf2(node);
|
|
1174
|
+
unknownTypes.set(t, (unknownTypes.get(t) ?? 0) + 1);
|
|
1175
|
+
unknownCount++;
|
|
1176
|
+
}
|
|
1177
|
+
items.push(node);
|
|
1178
|
+
} catch {
|
|
1179
|
+
excludedCount++;
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
const warnings = [];
|
|
1183
|
+
if (unresolved.length > 0) {
|
|
1184
|
+
warnings.push(
|
|
1185
|
+
`${unresolved.length} referenced entities were not present in included[] \u2014 the decoration failed for those, so this record is incomplete rather than short.`
|
|
1186
|
+
);
|
|
1187
|
+
}
|
|
1188
|
+
if (opts.claimedCount !== void 0 && opts.claimedCount > 0 && items.length === 0) {
|
|
1189
|
+
warnings.push(
|
|
1190
|
+
`LinkedIn claims ${opts.claimedCount} items but returned none \u2014 treat this as a FAILED FETCH, not an empty result.`
|
|
1191
|
+
);
|
|
1192
|
+
}
|
|
1193
|
+
const state = unresolved.length > 0 ? "partial" : opts.truncated === true ? "unknown" : "complete";
|
|
1194
|
+
const meta = {
|
|
1195
|
+
state,
|
|
1196
|
+
operation: opts.operation,
|
|
1197
|
+
contractCapturedAt: opts.contractCapturedAt ?? "unknown",
|
|
1198
|
+
// parsedCount counts what we kept; `items` includes the unknowns, which is
|
|
1199
|
+
// why unknownCount is reported separately rather than added again here.
|
|
1200
|
+
rawCandidateCount: resolved.length,
|
|
1201
|
+
parsedCount: items.length - unknownCount,
|
|
1202
|
+
excludedCount,
|
|
1203
|
+
unknownCount,
|
|
1204
|
+
returnedCount: items.length,
|
|
1205
|
+
truncated: opts.truncated ?? false,
|
|
1206
|
+
warnings
|
|
1207
|
+
};
|
|
1208
|
+
if (opts.claimedCount !== void 0) meta.claimedCount = opts.claimedCount;
|
|
1209
|
+
if (unresolved.length > 0) meta.unresolved = unresolved;
|
|
1210
|
+
if (unknownTypes.size > 0) {
|
|
1211
|
+
meta.unknownTypes = [...unknownTypes.entries()].map(([type, count2]) => ({ type, count: count2 }));
|
|
1212
|
+
}
|
|
1213
|
+
return { items, meta };
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
// src/engine/index.ts
|
|
1217
|
+
var RESULT_TYPE = {
|
|
1218
|
+
people: "PEOPLE",
|
|
1219
|
+
companies: "COMPANIES",
|
|
1220
|
+
jobs: "JOBS"
|
|
1221
|
+
};
|
|
1222
|
+
function missingContract(name) {
|
|
1223
|
+
return {
|
|
1224
|
+
ok: false,
|
|
1225
|
+
code: "NOT_IMPLEMENTED",
|
|
1226
|
+
message: `no verified contract for '${name}'`,
|
|
1227
|
+
hint: "Only endpoints that returned 200 on this machine may back a command. Capture it with `bun run scripts/observe.ts`, verify it, then mark it verified in src/engine/contracts.ts."
|
|
1228
|
+
};
|
|
1229
|
+
}
|
|
1230
|
+
function createEngine(session, deps, quiet = false) {
|
|
1231
|
+
const client = createClient(session, {
|
|
1232
|
+
fetch: globalThis.fetch,
|
|
1233
|
+
// stdout stays JSON-only; progress is human chatter and goes to stderr.
|
|
1234
|
+
progress: progressReporter(quiet),
|
|
1235
|
+
now: () => Date.now(),
|
|
1236
|
+
sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
|
|
1237
|
+
random: () => Math.random(),
|
|
1238
|
+
loadLedger: () => {
|
|
1239
|
+
const r = loadJson(cachePath("budget.json"));
|
|
1240
|
+
return r.state === "ok" ? r.value : emptyLedger();
|
|
1241
|
+
},
|
|
1242
|
+
saveLedger: (l) => saveJson(cachePath("budget.json"), l),
|
|
1243
|
+
loadCooldown: () => {
|
|
1244
|
+
const r = loadJson(cachePath("cooldown.json"));
|
|
1245
|
+
return r.state === "ok" ? r.value : null;
|
|
1246
|
+
},
|
|
1247
|
+
saveCooldown: (c) => saveJson(cachePath("cooldown.json"), c),
|
|
1248
|
+
...deps
|
|
1249
|
+
});
|
|
1250
|
+
return {
|
|
1251
|
+
async whoami() {
|
|
1252
|
+
const contract = contractFor("me");
|
|
1253
|
+
if (contract === void 0) return missingContract("me");
|
|
1254
|
+
const res = await client.request({
|
|
1255
|
+
url: contract.path,
|
|
1256
|
+
spendClass: "profile",
|
|
1257
|
+
operation: "me"
|
|
1258
|
+
});
|
|
1259
|
+
if (!res.ok) return res;
|
|
1260
|
+
return { ok: true, value: parseSingle(res.json) };
|
|
1261
|
+
},
|
|
1262
|
+
async profile(memberId) {
|
|
1263
|
+
const contract = contractFor("profile");
|
|
1264
|
+
if (contract === void 0) return missingContract("profile");
|
|
1265
|
+
const variables = encodeVariables({ memberIdentity: memberId });
|
|
1266
|
+
const url = `${contract.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract.queryId}`;
|
|
1267
|
+
const res = await client.request({ url, spendClass: "profile", operation: "profile" });
|
|
1268
|
+
if (!res.ok) return res;
|
|
1269
|
+
const envelope = res.json;
|
|
1270
|
+
const index = indexIncluded(envelope.included);
|
|
1271
|
+
const profile = [...new Set(index.values())].find(
|
|
1272
|
+
(n) => String(n.$type ?? "").endsWith("profile.Profile")
|
|
1273
|
+
);
|
|
1274
|
+
if (profile === void 0) return { ok: true, value: void 0 };
|
|
1275
|
+
return { ok: true, value: { profile, index } };
|
|
1276
|
+
},
|
|
1277
|
+
async feed(limit) {
|
|
1278
|
+
const contract = contractFor("feed");
|
|
1279
|
+
if (contract === void 0) return missingContract("feed");
|
|
1280
|
+
const url = `${contract.path}?q=chronFeed&count=${limit}&start=0`;
|
|
1281
|
+
const res = await client.request({ url, spendClass: "page", operation: "feed" });
|
|
1282
|
+
if (!res.ok) return res;
|
|
1283
|
+
const envelope = res.json;
|
|
1284
|
+
return {
|
|
1285
|
+
ok: true,
|
|
1286
|
+
value: {
|
|
1287
|
+
parsed: parseCollection(res.json, {
|
|
1288
|
+
operation: "feed",
|
|
1289
|
+
contractCapturedAt: contract.capturedAt
|
|
1290
|
+
}),
|
|
1291
|
+
index: indexIncluded(envelope.included)
|
|
1292
|
+
}
|
|
1293
|
+
};
|
|
1294
|
+
},
|
|
1295
|
+
async myPosts(profileUrn, limit) {
|
|
1296
|
+
const contract = contractFor("myPosts");
|
|
1297
|
+
if (contract === void 0) return missingContract("myPosts");
|
|
1298
|
+
const variables = encodeVariables({ count: Math.min(limit, 100), start: 0, profileUrn });
|
|
1299
|
+
const url = `${contract.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract.queryId}`;
|
|
1300
|
+
const res = await client.request({ url, spendClass: "page", operation: "myPosts" });
|
|
1301
|
+
if (!res.ok) return res;
|
|
1302
|
+
const envelope = res.json;
|
|
1303
|
+
return {
|
|
1304
|
+
ok: true,
|
|
1305
|
+
value: {
|
|
1306
|
+
parsed: parseCollection(res.json, {
|
|
1307
|
+
operation: "myPosts",
|
|
1308
|
+
contractCapturedAt: contract.capturedAt,
|
|
1309
|
+
truncated: true
|
|
1310
|
+
}),
|
|
1311
|
+
index: indexIncluded(envelope.included)
|
|
1312
|
+
}
|
|
1313
|
+
};
|
|
1314
|
+
},
|
|
1315
|
+
/**
|
|
1316
|
+
* Connections are a FILTERED PEOPLE SEARCH, not a list endpoint — LinkedIn
|
|
1317
|
+
* exposes no change stream for them. That is why the cache stores them as a
|
|
1318
|
+
* snapshot and diffs, rather than pretending a watermark exists.
|
|
1319
|
+
*/
|
|
1320
|
+
async connections(limit) {
|
|
1321
|
+
const contract = contractFor("search");
|
|
1322
|
+
if (contract === void 0) return missingContract("search");
|
|
1323
|
+
const variables = encodeVariables({
|
|
1324
|
+
start: 0,
|
|
1325
|
+
origin: "FACETED_SEARCH",
|
|
1326
|
+
query: {
|
|
1327
|
+
flagshipSearchIntent: "SEARCH_SRP",
|
|
1328
|
+
queryParameters: [
|
|
1329
|
+
{ key: "resultType", value: ["PEOPLE"] },
|
|
1330
|
+
{ key: "network", value: ["F"] }
|
|
1331
|
+
],
|
|
1332
|
+
includeFiltersInResponse: false
|
|
1333
|
+
}
|
|
1334
|
+
});
|
|
1335
|
+
const url = `${contract.path}?variables=${variables}&queryId=${contract.queryId}`;
|
|
1336
|
+
const res = await client.request({ url, spendClass: "search", operation: "connections" });
|
|
1337
|
+
if (!res.ok) return res;
|
|
1338
|
+
const parsed = parseCollection(res.json, {
|
|
1339
|
+
operation: "connections",
|
|
1340
|
+
contractCapturedAt: contract.capturedAt,
|
|
1341
|
+
claimedCount: totalResultCount(res.json),
|
|
1342
|
+
truncated: true
|
|
1343
|
+
});
|
|
1344
|
+
parsed.items = parsed.items.slice(0, limit);
|
|
1345
|
+
parsed.meta.returnedCount = parsed.items.length;
|
|
1346
|
+
const envelope = res.json;
|
|
1347
|
+
return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };
|
|
1348
|
+
},
|
|
1349
|
+
async post(postUrn, limit) {
|
|
1350
|
+
const contract = contractFor("comments");
|
|
1351
|
+
if (contract === void 0) return missingContract("comments");
|
|
1352
|
+
const variables = encodeVariables({
|
|
1353
|
+
count: Math.min(limit, 100),
|
|
1354
|
+
numReplies: 1,
|
|
1355
|
+
socialDetailUrn: socialDetailUrn(postUrn),
|
|
1356
|
+
sortOrder: "RELEVANCE",
|
|
1357
|
+
start: 0
|
|
1358
|
+
});
|
|
1359
|
+
const url = `${contract.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract.queryId}`;
|
|
1360
|
+
const res = await client.request({ url, spendClass: "page", operation: "comments" });
|
|
1361
|
+
if (!res.ok) return res;
|
|
1362
|
+
const parsed = parseCollection(res.json, {
|
|
1363
|
+
operation: "comments",
|
|
1364
|
+
contractCapturedAt: contract.capturedAt,
|
|
1365
|
+
// A page of many; we follow no cursor yet, so never claim exhaustion.
|
|
1366
|
+
truncated: true
|
|
1367
|
+
});
|
|
1368
|
+
const envelope = res.json;
|
|
1369
|
+
return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };
|
|
1370
|
+
},
|
|
1371
|
+
async reactions(postUrn, limit) {
|
|
1372
|
+
const contract = contractFor("reactions");
|
|
1373
|
+
if (contract === void 0) return missingContract("reactions");
|
|
1374
|
+
const variables = encodeVariables({
|
|
1375
|
+
count: Math.min(limit, 100),
|
|
1376
|
+
start: 0,
|
|
1377
|
+
threadUrn: postUrn
|
|
1378
|
+
});
|
|
1379
|
+
const url = `${contract.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract.queryId}`;
|
|
1380
|
+
const res = await client.request({ url, spendClass: "page", operation: "reactions" });
|
|
1381
|
+
if (!res.ok) return res;
|
|
1382
|
+
const parsed = parseCollection(res.json, {
|
|
1383
|
+
operation: "reactions",
|
|
1384
|
+
contractCapturedAt: contract.capturedAt,
|
|
1385
|
+
truncated: true
|
|
1386
|
+
});
|
|
1387
|
+
const envelope = res.json;
|
|
1388
|
+
return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };
|
|
1389
|
+
},
|
|
1390
|
+
async search(kind, query, limit) {
|
|
1391
|
+
const contract = contractFor("search");
|
|
1392
|
+
if (contract === void 0) return missingContract("search");
|
|
1393
|
+
const variables = encodeVariables({
|
|
1394
|
+
start: 0,
|
|
1395
|
+
origin: "GLOBAL_SEARCH_HEADER",
|
|
1396
|
+
query: {
|
|
1397
|
+
keywords: query,
|
|
1398
|
+
flagshipSearchIntent: "SEARCH_SRP",
|
|
1399
|
+
queryParameters: [{ key: "resultType", value: [RESULT_TYPE[kind]] }],
|
|
1400
|
+
includeFiltersInResponse: false
|
|
1401
|
+
}
|
|
1402
|
+
});
|
|
1403
|
+
const url = `${contract.path}?variables=${variables}&queryId=${contract.queryId}`;
|
|
1404
|
+
const res = await client.request({ url, spendClass: "search", operation: "search" });
|
|
1405
|
+
if (!res.ok) return res;
|
|
1406
|
+
const parsed = parseCollection(res.json, {
|
|
1407
|
+
operation: "search",
|
|
1408
|
+
contractCapturedAt: contract.capturedAt,
|
|
1409
|
+
claimedCount: totalResultCount(res.json),
|
|
1410
|
+
truncated: true
|
|
1411
|
+
// one page of many; we never claim exhaustion
|
|
1412
|
+
});
|
|
1413
|
+
parsed.items = parsed.items.slice(0, limit);
|
|
1414
|
+
parsed.meta.returnedCount = parsed.items.length;
|
|
1415
|
+
const envelope = res.json;
|
|
1416
|
+
return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };
|
|
1417
|
+
}
|
|
1418
|
+
};
|
|
1419
|
+
}
|
|
1420
|
+
function socialDetailUrn(postUrn) {
|
|
1421
|
+
return `urn:li:fsd_socialDetail:(${postUrn},${postUrn},urn:li:highlightedReply:-)`;
|
|
1422
|
+
}
|
|
1423
|
+
function totalResultCount(json) {
|
|
1424
|
+
const found = JSON.stringify(json ?? {}).match(/"totalResultCount":(\d+)/);
|
|
1425
|
+
return found?.[1] === void 0 ? void 0 : Number(found[1]);
|
|
1426
|
+
}
|
|
1427
|
+
|
|
1428
|
+
// src/engine/session.ts
|
|
1429
|
+
var SESSION_FILE = "session.json";
|
|
1430
|
+
function loadSession() {
|
|
1431
|
+
const result = loadJson(cachePath(SESSION_FILE));
|
|
1432
|
+
if (result.state === "ok") return { state: "ok", session: result.value };
|
|
1433
|
+
if (result.state === "missing") return { state: "missing" };
|
|
1434
|
+
return { state: "corrupt", quarantinedTo: result.quarantinedTo };
|
|
1435
|
+
}
|
|
1436
|
+
var LAUNCH_HINT = 'Start Chrome with remote debugging first, DETACHED so it survives:\n nohup /Applications/Google\\ Chrome.app/Contents/MacOS/Google\\ Chrome \\\n --remote-debugging-port=9222 --user-data-dir="$HOME/.lnrelay/chrome" \\\n https://www.linkedin.com/feed/ >/dev/null 2>&1 & disown\nThen log into LinkedIn in that window and visit /feed/ once.';
|
|
1437
|
+
|
|
1438
|
+
// src/commands/live.ts
|
|
1439
|
+
function withSession(command, quiet = false) {
|
|
1440
|
+
const loaded = loadSession();
|
|
1441
|
+
if (loaded.state === "corrupt") {
|
|
1442
|
+
return err(
|
|
1443
|
+
command,
|
|
1444
|
+
"CACHE_CORRUPT",
|
|
1445
|
+
"the stored session was unreadable and has been quarantined",
|
|
1446
|
+
`Moved to ${loaded.quarantinedTo}. Re-run \`lnrelay login\`.`
|
|
1447
|
+
);
|
|
1448
|
+
}
|
|
1449
|
+
if (loaded.state === "missing") {
|
|
1450
|
+
return err(command, "AUTH_FAILED", "no session \u2014 run `lnrelay login` first", LAUNCH_HINT);
|
|
1451
|
+
}
|
|
1452
|
+
return { engine: createEngine(loaded.session, void 0, quiet) };
|
|
1453
|
+
}
|
|
1454
|
+
function toEnvelope(command, result) {
|
|
1455
|
+
return err(command, result.code, result.message, result.hint, void 0, result.retryAfterMs);
|
|
1456
|
+
}
|
|
1457
|
+
async function runWhoami(raw = false) {
|
|
1458
|
+
const ctx = withSession("whoami");
|
|
1459
|
+
if ("ok" in ctx) return ctx;
|
|
1460
|
+
const result = await ctx.engine.whoami();
|
|
1461
|
+
if (!result.ok) return toEnvelope("whoami", result);
|
|
1462
|
+
if (result.value === void 0) {
|
|
1463
|
+
return err(
|
|
1464
|
+
"whoami",
|
|
1465
|
+
"SCHEMA_DRIFT",
|
|
1466
|
+
"LinkedIn returned no member entity",
|
|
1467
|
+
"re-capture the `me` contract"
|
|
1468
|
+
);
|
|
1469
|
+
}
|
|
1470
|
+
return ok(
|
|
1471
|
+
"whoami",
|
|
1472
|
+
raw ? { ...shapeEntity(result.value), raw: result.value } : shapeEntity(result.value)
|
|
1473
|
+
);
|
|
1474
|
+
}
|
|
1475
|
+
async function runProfile(memberId, raw = false) {
|
|
1476
|
+
if (memberId === void 0 || memberId === "") {
|
|
1477
|
+
return err(
|
|
1478
|
+
"profile",
|
|
1479
|
+
"INVALID_INPUT",
|
|
1480
|
+
"a member id or urn is required",
|
|
1481
|
+
"lnrelay profile <public-id|urn>"
|
|
1482
|
+
);
|
|
1483
|
+
}
|
|
1484
|
+
const ctx = withSession("profile");
|
|
1485
|
+
if ("ok" in ctx) return ctx;
|
|
1486
|
+
const result = await ctx.engine.profile(normaliseMemberId(memberId));
|
|
1487
|
+
if (!result.ok) return toEnvelope("profile", result);
|
|
1488
|
+
if (result.value === void 0) {
|
|
1489
|
+
return err("profile", "NOT_FOUND", `no profile for '${memberId}'`);
|
|
1490
|
+
}
|
|
1491
|
+
const shaped = shapeProfile(result.value.profile, result.value.index);
|
|
1492
|
+
return ok("profile", raw ? { ...shaped, raw: result.value.profile } : shaped);
|
|
1493
|
+
}
|
|
1494
|
+
async function runFeed(limit, opts = {}) {
|
|
1495
|
+
const ctx = withSession("feed", opts.quiet === true);
|
|
1496
|
+
if ("ok" in ctx) return ctx;
|
|
1497
|
+
const result = await ctx.engine.feed(limit);
|
|
1498
|
+
if (!result.ok) return toEnvelope("feed", result);
|
|
1499
|
+
return ok("feed", collection(result.value, opts));
|
|
1500
|
+
}
|
|
1501
|
+
async function runSearch(kind, query, limit, opts = {}) {
|
|
1502
|
+
if (kind === void 0 || !["people", "companies", "jobs"].includes(kind)) {
|
|
1503
|
+
return err(
|
|
1504
|
+
"search",
|
|
1505
|
+
"INVALID_INPUT",
|
|
1506
|
+
"kind must be people, companies or jobs",
|
|
1507
|
+
'lnrelay search people "<query>"'
|
|
1508
|
+
);
|
|
1509
|
+
}
|
|
1510
|
+
if (query === void 0 || query === "") {
|
|
1511
|
+
return err("search", "INVALID_INPUT", "a query is required", 'lnrelay search people "<query>"');
|
|
1512
|
+
}
|
|
1513
|
+
const ctx = withSession("search", opts.quiet === true);
|
|
1514
|
+
if ("ok" in ctx) return ctx;
|
|
1515
|
+
const result = await ctx.engine.search(kind, query, limit);
|
|
1516
|
+
if (!result.ok) return toEnvelope("search", result);
|
|
1517
|
+
return ok("search", { query, kind, ...collection(result.value, opts) });
|
|
1518
|
+
}
|
|
1519
|
+
async function runPost(urn, limit, opts = {}) {
|
|
1520
|
+
const postUrn = normalisePostUrn(urn);
|
|
1521
|
+
if (postUrn === void 0) {
|
|
1522
|
+
return err(
|
|
1523
|
+
"post",
|
|
1524
|
+
"INVALID_INPUT",
|
|
1525
|
+
"a post urn or feed URL is required",
|
|
1526
|
+
"lnrelay post <activity-urn|https://www.linkedin.com/feed/update/...>"
|
|
1527
|
+
);
|
|
1528
|
+
}
|
|
1529
|
+
const ctx = withSession("post", opts.quiet === true);
|
|
1530
|
+
if ("ok" in ctx) return ctx;
|
|
1531
|
+
const result = await ctx.engine.post(postUrn, limit);
|
|
1532
|
+
if (!result.ok) return toEnvelope("post", result);
|
|
1533
|
+
return ok("post", { urn: postUrn, ...collection(result.value, opts) });
|
|
1534
|
+
}
|
|
1535
|
+
async function runReactions(urn, limit, opts = {}) {
|
|
1536
|
+
const postUrn = normalisePostUrn(urn);
|
|
1537
|
+
if (postUrn === void 0) {
|
|
1538
|
+
return err("reactions", "INVALID_INPUT", "a post urn or feed URL is required");
|
|
1539
|
+
}
|
|
1540
|
+
const ctx = withSession("reactions", opts.quiet === true);
|
|
1541
|
+
if ("ok" in ctx) return ctx;
|
|
1542
|
+
const result = await ctx.engine.reactions(postUrn, limit);
|
|
1543
|
+
if (!result.ok) return toEnvelope("reactions", result);
|
|
1544
|
+
return ok("reactions", { urn: postUrn, ...collection(result.value, opts) });
|
|
1545
|
+
}
|
|
1546
|
+
function normalisePostUrn(input) {
|
|
1547
|
+
if (input === void 0 || input === "") return void 0;
|
|
1548
|
+
const found = input.match(/urn:li:(?:activity|ugcPost|share):\d+/);
|
|
1549
|
+
if (found !== null) return found[0];
|
|
1550
|
+
return /^\d+$/.test(input) ? `urn:li:activity:${input}` : void 0;
|
|
1551
|
+
}
|
|
1552
|
+
function normaliseMemberId(input) {
|
|
1553
|
+
const fromUrl = input.match(/linkedin\.com\/in\/([^/?#]+)/);
|
|
1554
|
+
if (fromUrl?.[1] !== void 0) return fromUrl[1];
|
|
1555
|
+
const fromUrn = input.match(/urn:li:fsd?_(?:mini)?[Pp]rofile:([^,)]+)/);
|
|
1556
|
+
if (fromUrn?.[1] !== void 0) return fromUrn[1];
|
|
1557
|
+
return input;
|
|
1558
|
+
}
|
|
1559
|
+
function collection(result, opts = {}) {
|
|
1560
|
+
const { parsed, index } = result;
|
|
1561
|
+
const shaped = shapeAll(parsed.items, index);
|
|
1562
|
+
const meta = { ...parsed.meta };
|
|
1563
|
+
if (opts.retain === true) meta.retained = retain("third-party", shaped);
|
|
1564
|
+
if (opts.raw === true) {
|
|
1565
|
+
return {
|
|
1566
|
+
items: parsed.items.map((node, i) => ({ ...shaped[i], raw: node })),
|
|
1567
|
+
meta
|
|
1568
|
+
};
|
|
1569
|
+
}
|
|
1570
|
+
if (opts.compact === true) return { items: compactRows(shaped), meta };
|
|
1571
|
+
if (opts.fields !== void 0 && opts.fields !== "") {
|
|
1572
|
+
return { items: project(shaped, opts.fields), meta };
|
|
1573
|
+
}
|
|
1574
|
+
return { items: shaped, meta };
|
|
1575
|
+
}
|
|
1576
|
+
|
|
1577
|
+
// src/commands/local.ts
|
|
1578
|
+
import { existsSync as existsSync2 } from "fs";
|
|
1579
|
+
import { version as nodeVersion } from "process";
|
|
1580
|
+
var LEDGER_FILE = "budget.json";
|
|
1581
|
+
var COOLDOWN_FILE = "cooldown.json";
|
|
1582
|
+
function loadState(file, fallback) {
|
|
1583
|
+
const path = cachePath(file);
|
|
1584
|
+
const result = loadJson(path);
|
|
1585
|
+
if (result.state === "ok") return { value: result.value, corrupt: null };
|
|
1586
|
+
if (result.state === "missing") return { value: fallback, corrupt: null };
|
|
1587
|
+
return {
|
|
1588
|
+
value: null,
|
|
1589
|
+
corrupt: { path, quarantinedTo: result.quarantinedTo, reason: result.reason }
|
|
1590
|
+
};
|
|
1591
|
+
}
|
|
1592
|
+
function loadLedger() {
|
|
1593
|
+
return loadState(LEDGER_FILE, emptyLedger());
|
|
1594
|
+
}
|
|
1595
|
+
function loadCooldown() {
|
|
1596
|
+
return loadState(COOLDOWN_FILE, null);
|
|
1597
|
+
}
|
|
1598
|
+
function runRisk(now) {
|
|
1599
|
+
const { value: cooldown, corrupt } = loadCooldown();
|
|
1600
|
+
if (corrupt !== null) {
|
|
1601
|
+
return err(
|
|
1602
|
+
"risk",
|
|
1603
|
+
"CACHE_CORRUPT",
|
|
1604
|
+
`cooldown state was unreadable and has been quarantined: ${corrupt.reason}`,
|
|
1605
|
+
`moved to ${corrupt.quarantinedTo}. Inspect it, then re-run \u2014 a fresh cooldown file will be created.`
|
|
1606
|
+
);
|
|
1607
|
+
}
|
|
1608
|
+
const blocked = activeCooldown(cooldown ?? null, now);
|
|
1609
|
+
return ok("risk", {
|
|
1610
|
+
state: blocked ? "blocked" : "ok",
|
|
1611
|
+
cooldown: cooldown ?? null,
|
|
1612
|
+
tosNotice: "Voyager reads breach LinkedIn User Agreement \xA78.2. This tool is not ToS-compliant and any account it touches can be restricted or permanently banned."
|
|
1613
|
+
});
|
|
1614
|
+
}
|
|
1615
|
+
function runBudget(now, resetCooldown, confirmed) {
|
|
1616
|
+
if (resetCooldown && !confirmed) {
|
|
1617
|
+
return err(
|
|
1618
|
+
"budget",
|
|
1619
|
+
"CONFIRMATION_REQUIRED",
|
|
1620
|
+
"clearing a cooldown requires --confirm",
|
|
1621
|
+
"A cooldown means LinkedIn signalled a throttle, block or challenge. Log in through a real browser and confirm you are unblocked before clearing it. Re-run with --confirm."
|
|
1622
|
+
);
|
|
1623
|
+
}
|
|
1624
|
+
if (resetCooldown) {
|
|
1625
|
+
saveJson(cachePath(COOLDOWN_FILE), null);
|
|
1626
|
+
}
|
|
1627
|
+
const { value: ledger, corrupt } = loadLedger();
|
|
1628
|
+
if (corrupt !== null) {
|
|
1629
|
+
return err(
|
|
1630
|
+
"budget",
|
|
1631
|
+
"CACHE_CORRUPT",
|
|
1632
|
+
`the spend ledger was unreadable and has been quarantined: ${corrupt.reason}`,
|
|
1633
|
+
`moved to ${corrupt.quarantinedTo}. A corrupt ledger is NOT treated as an empty one \u2014 that would silently restore a full budget. Inspect it, then re-run.`
|
|
1634
|
+
);
|
|
1635
|
+
}
|
|
1636
|
+
const classes = ["profile", "search", "page", "write", "global"];
|
|
1637
|
+
const { value: cooldown } = loadCooldown();
|
|
1638
|
+
return ok("budget", {
|
|
1639
|
+
classes: classes.map((c) => ({
|
|
1640
|
+
...summarise(ledger ?? emptyLedger(), c, now),
|
|
1641
|
+
note: CAPS[c].note
|
|
1642
|
+
})),
|
|
1643
|
+
cooldown: cooldown ?? null,
|
|
1644
|
+
caveat: "Every cap is guessed or transplanted vendor lore \u2014 the field research found no corroborated LinkedIn rate limits. These are starting knobs, not safe thresholds. They also cannot see your manual browser activity."
|
|
1645
|
+
});
|
|
1646
|
+
}
|
|
1647
|
+
function runDoctor(now, offline) {
|
|
1648
|
+
const checks = [];
|
|
1649
|
+
checks.push({
|
|
1650
|
+
name: "runtime",
|
|
1651
|
+
ok: true,
|
|
1652
|
+
detail: `node ${nodeVersion}; cache dir ${cacheDir()}${existsSync2(cacheDir()) ? "" : " (not created yet)"}`
|
|
1653
|
+
});
|
|
1654
|
+
const { value: cooldown, corrupt: cooldownCorrupt } = loadCooldown();
|
|
1655
|
+
if (cooldownCorrupt !== null) {
|
|
1656
|
+
checks.push({
|
|
1657
|
+
name: "cooldown",
|
|
1658
|
+
ok: false,
|
|
1659
|
+
detail: `state file was corrupt; quarantined to ${cooldownCorrupt.quarantinedTo}`
|
|
1660
|
+
});
|
|
1661
|
+
} else {
|
|
1662
|
+
const blocked = activeCooldown(cooldown ?? null, now);
|
|
1663
|
+
checks.push({
|
|
1664
|
+
name: "cooldown",
|
|
1665
|
+
ok: !blocked,
|
|
1666
|
+
detail: blocked ? `BLOCKED \u2014 ${cooldown?.reason}, clears by ${cooldown?.clearRequires}${cooldown?.until === null ? " (indefinite)" : ` at ${new Date(cooldown?.until ?? 0).toISOString()}`}` : "clear"
|
|
1667
|
+
});
|
|
1668
|
+
}
|
|
1669
|
+
const { value: ledger, corrupt: ledgerCorrupt } = loadLedger();
|
|
1670
|
+
if (ledgerCorrupt !== null) {
|
|
1671
|
+
checks.push({
|
|
1672
|
+
name: "budget",
|
|
1673
|
+
ok: false,
|
|
1674
|
+
detail: `ledger was corrupt; quarantined to ${ledgerCorrupt.quarantinedTo}`
|
|
1675
|
+
});
|
|
1676
|
+
} else {
|
|
1677
|
+
const g = summarise(ledger ?? emptyLedger(), "global", now);
|
|
1678
|
+
checks.push({
|
|
1679
|
+
name: "budget",
|
|
1680
|
+
ok: g.remaining > 0,
|
|
1681
|
+
detail: `${g.spentInWindow}/${g.cap} global calls used in the last 24h (cap provenance: ${g.capProvenance})`
|
|
1682
|
+
});
|
|
1683
|
+
}
|
|
1684
|
+
const cookiePath = cachePath("cookies.json");
|
|
1685
|
+
checks.push({
|
|
1686
|
+
name: "session",
|
|
1687
|
+
ok: false,
|
|
1688
|
+
detail: existsSync2(cookiePath) ? "a cookie file exists, but the engine is not implemented yet (Phase 2)" : "no session yet \u2014 the Phase 0 capture gate has not been run. See docs/PLAN.md."
|
|
1689
|
+
});
|
|
1690
|
+
checks.push({
|
|
1691
|
+
name: "engine",
|
|
1692
|
+
ok: false,
|
|
1693
|
+
detail: "not implemented. Phase 0 (three human-paced requests from a residential IP) must pass before engine code is written \u2014 see docs/PLAN.md."
|
|
1694
|
+
});
|
|
1695
|
+
if (!offline) {
|
|
1696
|
+
checks.push({
|
|
1697
|
+
name: "live",
|
|
1698
|
+
ok: false,
|
|
1699
|
+
detail: "no live checks available yet; --offline is currently the only meaningful mode"
|
|
1700
|
+
});
|
|
1701
|
+
}
|
|
1702
|
+
return ok("doctor", {
|
|
1703
|
+
healthy: checks.every((c) => c.ok),
|
|
1704
|
+
phase: "Phase 1 \u2014 local scaffolding. No network capability exists yet, by design.",
|
|
1705
|
+
checks
|
|
1706
|
+
});
|
|
1707
|
+
}
|
|
1708
|
+
|
|
1709
|
+
// src/commands/registry.ts
|
|
1710
|
+
var COMMANDS = [
|
|
1711
|
+
// ─── local / meta — no network, available today ────────────────────────────
|
|
1712
|
+
{
|
|
1713
|
+
name: "doctor",
|
|
1714
|
+
cost: "free with --offline",
|
|
1715
|
+
summary: "Diagnose setup: entry point, cache dir, cookies, cooldown, budget.",
|
|
1716
|
+
usage: "lnrelay doctor [--offline]",
|
|
1717
|
+
audience: ["cli", "mcp"],
|
|
1718
|
+
risk: "local",
|
|
1719
|
+
implemented: true
|
|
1720
|
+
},
|
|
1721
|
+
{
|
|
1722
|
+
name: "budget",
|
|
1723
|
+
cost: "free",
|
|
1724
|
+
summary: "Spend ledger per class, with each cap's provenance. Reset a cooldown here.",
|
|
1725
|
+
usage: "lnrelay budget [--reset-cooldown --confirm]",
|
|
1726
|
+
audience: ["cli", "mcp"],
|
|
1727
|
+
risk: "local",
|
|
1728
|
+
implemented: true
|
|
1729
|
+
},
|
|
1730
|
+
{
|
|
1731
|
+
name: "risk",
|
|
1732
|
+
cost: "free",
|
|
1733
|
+
summary: "Circuit-breaker state. Check this BEFORE spending budget on research.",
|
|
1734
|
+
usage: "lnrelay risk",
|
|
1735
|
+
audience: ["cli", "mcp"],
|
|
1736
|
+
risk: "local",
|
|
1737
|
+
implemented: true
|
|
1738
|
+
},
|
|
1739
|
+
// ─── session ───────────────────────────────────────────────────────────────
|
|
1740
|
+
{
|
|
1741
|
+
name: "login",
|
|
1742
|
+
cost: "free \u2014 local browser",
|
|
1743
|
+
summary: "Mint a session from a logged-in Chrome via DevTools. Stores cookies owner-only.",
|
|
1744
|
+
usage: "lnrelay login\n Requires a Chrome started with remote debugging on port 9222 (see docs/PLAN.md).",
|
|
1745
|
+
audience: ["cli"],
|
|
1746
|
+
risk: "local",
|
|
1747
|
+
implemented: true
|
|
1748
|
+
},
|
|
1749
|
+
// ─── reads — verified live 2026-08-01 ─────────────────────────────────────
|
|
1750
|
+
{
|
|
1751
|
+
name: "whoami",
|
|
1752
|
+
cost: "1 call",
|
|
1753
|
+
summary: "The authenticated member: name, headline, URN.",
|
|
1754
|
+
usage: "lnrelay whoami",
|
|
1755
|
+
audience: ["cli", "mcp"],
|
|
1756
|
+
risk: "read",
|
|
1757
|
+
implemented: true
|
|
1758
|
+
},
|
|
1759
|
+
{
|
|
1760
|
+
name: "profile",
|
|
1761
|
+
cost: "1 call (+1 per section)",
|
|
1762
|
+
summary: "A member profile. Expensive sections are opt-in.",
|
|
1763
|
+
usage: "lnrelay profile <public-id|urn|url> [--raw]\n Returns headline, location, current title, company and school. LinkedIn's profile\n projections do not return a name \u2014 use the identifier you passed in.",
|
|
1764
|
+
audience: ["cli", "mcp"],
|
|
1765
|
+
risk: "read",
|
|
1766
|
+
implemented: true
|
|
1767
|
+
},
|
|
1768
|
+
{
|
|
1769
|
+
name: "search",
|
|
1770
|
+
cost: "cheap \u2014 the net",
|
|
1771
|
+
summary: "Search people, companies or jobs. Cast wide, then deep-read the finalists.",
|
|
1772
|
+
usage: 'lnrelay search people|companies|jobs "<query>" [--limit N]\n [--compact | --fields a,b,c] [--retain] [--raw]',
|
|
1773
|
+
audience: ["cli", "mcp"],
|
|
1774
|
+
risk: "read",
|
|
1775
|
+
implemented: true
|
|
1776
|
+
},
|
|
1777
|
+
{
|
|
1778
|
+
name: "post",
|
|
1779
|
+
cost: "expensive \u2014 full read",
|
|
1780
|
+
summary: "A post plus its comment thread, cursor-followed.",
|
|
1781
|
+
usage: "lnrelay post <activity-urn|url> [--limit N] [--compact | --fields a,b] [--retain]\n Check meta.returnedCount / claimedCount / state. claimedCount > 0 with\n returnedCount 0 is a FAILED FETCH, not an empty thread.",
|
|
1782
|
+
audience: ["cli", "mcp"],
|
|
1783
|
+
risk: "read",
|
|
1784
|
+
implemented: true
|
|
1785
|
+
},
|
|
1786
|
+
{
|
|
1787
|
+
name: "reactions",
|
|
1788
|
+
cost: "medium",
|
|
1789
|
+
summary: "Who reacted to a post, and with which reaction.",
|
|
1790
|
+
usage: "lnrelay reactions <activity-urn|url> [--limit N] [--compact | --fields a,b]",
|
|
1791
|
+
audience: ["cli", "mcp"],
|
|
1792
|
+
risk: "read",
|
|
1793
|
+
implemented: true
|
|
1794
|
+
},
|
|
1795
|
+
{
|
|
1796
|
+
name: "company",
|
|
1797
|
+
cost: "medium",
|
|
1798
|
+
summary: "A company page, optionally with a bounded sample of its updates.",
|
|
1799
|
+
usage: "lnrelay company <universal-name|url> [--updates N]",
|
|
1800
|
+
audience: ["cli", "mcp"],
|
|
1801
|
+
risk: "read",
|
|
1802
|
+
implemented: false
|
|
1803
|
+
},
|
|
1804
|
+
{
|
|
1805
|
+
name: "job",
|
|
1806
|
+
cost: "1 call",
|
|
1807
|
+
summary: "A job posting detail.",
|
|
1808
|
+
usage: "lnrelay job <job-id|url>",
|
|
1809
|
+
audience: ["cli", "mcp"],
|
|
1810
|
+
risk: "read",
|
|
1811
|
+
implemented: false
|
|
1812
|
+
},
|
|
1813
|
+
{
|
|
1814
|
+
name: "feed",
|
|
1815
|
+
cost: "medium",
|
|
1816
|
+
summary: "Your own chronological feed.",
|
|
1817
|
+
usage: "lnrelay feed [--limit N] [--compact | --fields a,b,c] [--retain] [--raw]",
|
|
1818
|
+
audience: ["cli", "mcp"],
|
|
1819
|
+
risk: "read",
|
|
1820
|
+
implemented: true
|
|
1821
|
+
},
|
|
1822
|
+
// ─── cache-backed — Phase 4 ────────────────────────────────────────────────
|
|
1823
|
+
{
|
|
1824
|
+
name: "sync",
|
|
1825
|
+
cost: "medium \u2014 1-2 calls",
|
|
1826
|
+
summary: "Pull your own posts or connections into the local cache for offline search.",
|
|
1827
|
+
usage: "lnrelay sync my-posts|connections [--limit N] [--force]",
|
|
1828
|
+
audience: ["cli"],
|
|
1829
|
+
risk: "read",
|
|
1830
|
+
implemented: true
|
|
1831
|
+
},
|
|
1832
|
+
{
|
|
1833
|
+
name: "connections",
|
|
1834
|
+
cost: "free \u2014 local cache",
|
|
1835
|
+
summary: "Your connections, from the local cache. Fill it with `sync connections`.",
|
|
1836
|
+
usage: 'lnrelay connections [-q "<query>"] [--limit N] [--compact | --fields a,b] # free; cache',
|
|
1837
|
+
audience: ["cli", "mcp"],
|
|
1838
|
+
risk: "read",
|
|
1839
|
+
implemented: true
|
|
1840
|
+
},
|
|
1841
|
+
{
|
|
1842
|
+
name: "my-posts",
|
|
1843
|
+
cost: "free \u2014 local cache",
|
|
1844
|
+
summary: "Your own authored posts, from the local cache. Fill it with `sync my-posts`.",
|
|
1845
|
+
usage: 'lnrelay my-posts [-q "<query>"] [--limit N] [--compact | --fields a,b] # free; cache',
|
|
1846
|
+
audience: ["cli", "mcp"],
|
|
1847
|
+
risk: "read",
|
|
1848
|
+
implemented: true
|
|
1849
|
+
},
|
|
1850
|
+
{
|
|
1851
|
+
name: "local",
|
|
1852
|
+
cost: "free \u2014 local cache",
|
|
1853
|
+
summary: "Offline search across everything synced. The default research path after a sync.",
|
|
1854
|
+
usage: 'lnrelay local "<query>" [--source connections,my-posts,third-party] [--since YYYY-MM-DD]\n [--limit N] [--compact | --fields a,b,c]',
|
|
1855
|
+
audience: ["cli", "mcp"],
|
|
1856
|
+
risk: "read",
|
|
1857
|
+
implemented: true
|
|
1858
|
+
},
|
|
1859
|
+
{
|
|
1860
|
+
name: "cache-status",
|
|
1861
|
+
cost: "free \u2014 local cache",
|
|
1862
|
+
summary: "What is cached, per source, with sync checkpoints and the retention policy.",
|
|
1863
|
+
usage: "lnrelay cache-status",
|
|
1864
|
+
audience: ["cli", "mcp"],
|
|
1865
|
+
risk: "local",
|
|
1866
|
+
implemented: true
|
|
1867
|
+
},
|
|
1868
|
+
{
|
|
1869
|
+
name: "purge",
|
|
1870
|
+
cost: "free",
|
|
1871
|
+
summary: "Delete cached data. Never contacts LinkedIn.",
|
|
1872
|
+
usage: "lnrelay purge [--all] --confirm # default scope: third-party only",
|
|
1873
|
+
audience: ["cli"],
|
|
1874
|
+
risk: "local",
|
|
1875
|
+
implemented: true
|
|
1876
|
+
},
|
|
1877
|
+
// ─── writes — Phase 6, official OAuth only, never MCP ──────────────────────
|
|
1878
|
+
{
|
|
1879
|
+
name: "oauth",
|
|
1880
|
+
cost: "free",
|
|
1881
|
+
summary: "OAuth token status for writes. Never prints the token.",
|
|
1882
|
+
usage: "lnrelay oauth",
|
|
1883
|
+
audience: ["cli"],
|
|
1884
|
+
risk: "local",
|
|
1885
|
+
implemented: true
|
|
1886
|
+
},
|
|
1887
|
+
{
|
|
1888
|
+
name: "share",
|
|
1889
|
+
cost: "1 call \u2014 write",
|
|
1890
|
+
summary: "Post to your own feed via LinkedIn's official OAuth scope.",
|
|
1891
|
+
usage: 'lnrelay share "<text>" [--visibility public|connections]\n Stops and asks at an interactive terminal. No TTY = no write, and no network call.',
|
|
1892
|
+
audience: ["cli"],
|
|
1893
|
+
risk: "write",
|
|
1894
|
+
implemented: true
|
|
1895
|
+
},
|
|
1896
|
+
{
|
|
1897
|
+
name: "comment",
|
|
1898
|
+
cost: "1 call \u2014 write",
|
|
1899
|
+
summary: "Comment on a post via the official OAuth scope.",
|
|
1900
|
+
usage: 'lnrelay comment <activity-urn> "<text>"',
|
|
1901
|
+
audience: ["cli"],
|
|
1902
|
+
risk: "write",
|
|
1903
|
+
implemented: true
|
|
1904
|
+
},
|
|
1905
|
+
{
|
|
1906
|
+
name: "react",
|
|
1907
|
+
cost: "1 call \u2014 write",
|
|
1908
|
+
summary: "React to a post via the official OAuth scope. Reversible.",
|
|
1909
|
+
usage: "lnrelay react <activity-urn> [--type LIKE|PRAISE|EMPATHY|INTEREST|APPRECIATION]",
|
|
1910
|
+
audience: ["cli"],
|
|
1911
|
+
risk: "write",
|
|
1912
|
+
implemented: true
|
|
1913
|
+
}
|
|
1914
|
+
];
|
|
1915
|
+
var commandNames = COMMANDS.map((c) => c.name);
|
|
1916
|
+
function mcpCommands() {
|
|
1917
|
+
return COMMANDS.filter((c) => c.audience.includes("mcp") && c.risk !== "write");
|
|
1918
|
+
}
|
|
1919
|
+
|
|
1920
|
+
// src/entry.ts
|
|
1921
|
+
import { realpathSync } from "fs";
|
|
1922
|
+
import { basename } from "path";
|
|
1923
|
+
import { fileURLToPath } from "url";
|
|
1924
|
+
function isMainModule(argv1, moduleUrl, importMetaMain) {
|
|
1925
|
+
if (importMetaMain === true) return true;
|
|
1926
|
+
if (importMetaMain === false) return false;
|
|
1927
|
+
if (argv1 === void 0) return false;
|
|
1928
|
+
const modulePath = fileURLToPath(moduleUrl);
|
|
1929
|
+
try {
|
|
1930
|
+
return realpathSync(argv1) === realpathSync(modulePath);
|
|
1931
|
+
} catch {
|
|
1932
|
+
return argv1 === modulePath;
|
|
1933
|
+
}
|
|
1934
|
+
}
|
|
1935
|
+
function shouldForceEntry(argv1, binNames) {
|
|
1936
|
+
if (argv1 === void 0) return false;
|
|
1937
|
+
return binNames.includes(basename(argv1));
|
|
1938
|
+
}
|
|
1939
|
+
function shouldRunAsEntry(argv1, moduleUrl, importMetaMain, binNames) {
|
|
1940
|
+
if (isMainModule(argv1, moduleUrl, importMetaMain)) {
|
|
1941
|
+
return { run: true, warning: void 0 };
|
|
1942
|
+
}
|
|
1943
|
+
if (importMetaMain === void 0 && shouldForceEntry(argv1, binNames)) {
|
|
1944
|
+
return {
|
|
1945
|
+
run: true,
|
|
1946
|
+
warning: `${binNames[0]}: entry detection failed \u2014 treating as main; report at github.com/gabros20/linkedin-relay/issues`
|
|
1947
|
+
};
|
|
1948
|
+
}
|
|
1949
|
+
return { run: false, warning: void 0 };
|
|
1950
|
+
}
|
|
1951
|
+
|
|
1952
|
+
// src/mcp-shim.ts
|
|
1953
|
+
var READING_CONTRACT = 'ALWAYS read `meta` before reporting. `state:"complete"` with an empty `items` genuinely means none. `state:"partial"` means references failed to resolve \u2014 the record is INCOMPLETE, not small. `claimedCount > 0` with `returnedCount === 0` is a FAILED FETCH, never "no results". A non-empty `unknownTypes` means LinkedIn changed shape and the parser is behind \u2014 say so. If `meta.budget.remaining` is low, tell the user and stop.';
|
|
1954
|
+
var NO_RETRY = "Never retry on failure. RATE_LIMITED, REQUEST_DENIED, CHALLENGE_DETECTED and COOLDOWN_ACTIVE all mean a cross-process cooldown has opened; every further call will refuse until it lifts. Report it and stop.";
|
|
1955
|
+
function reply(envelope) {
|
|
1956
|
+
return {
|
|
1957
|
+
content: [{ type: "text", text: JSON.stringify(envelope) }],
|
|
1958
|
+
isError: !envelope.ok
|
|
1959
|
+
};
|
|
1960
|
+
}
|
|
1961
|
+
function buildServer() {
|
|
1962
|
+
const server = new McpServer({ name: "linkedin-relay", version: "0.1.0" });
|
|
1963
|
+
const exposed = mcpCommands();
|
|
1964
|
+
const write = exposed.find((c) => c.risk === "write");
|
|
1965
|
+
if (write !== void 0) {
|
|
1966
|
+
throw new Error(`refusing to start: write command '${write.name}' reached the MCP surface`);
|
|
1967
|
+
}
|
|
1968
|
+
server.tool(
|
|
1969
|
+
"risk",
|
|
1970
|
+
"Circuit-breaker state and the ToS notice. Free, no network. CALL THIS FIRST in a research session \u2014 it reports whether LinkedIn has thrown a throttle, block or challenge, so you find out before spending calls rather than one wasted call at a time.",
|
|
1971
|
+
{},
|
|
1972
|
+
async () => reply(runRisk(Date.now()))
|
|
1973
|
+
);
|
|
1974
|
+
server.tool(
|
|
1975
|
+
"budget",
|
|
1976
|
+
"Remaining request budget per class, with each cap's provenance. Free, no network. The caps are deliberately low because LinkedIn restricts accounts for READ velocity alone \u2014 they are guesses, not measured safe limits, and they cannot see the user's own browser activity.",
|
|
1977
|
+
{},
|
|
1978
|
+
async () => reply(runBudget(Date.now(), false, false))
|
|
1979
|
+
);
|
|
1980
|
+
server.tool(
|
|
1981
|
+
"doctor",
|
|
1982
|
+
"Diagnose setup end to end: session, cooldown, budget, engine readiness. Free with offline. Run this first when anything behaves oddly. Never reveals credential values.",
|
|
1983
|
+
{ offline: z.boolean().optional().describe("skip live checks (default true)") },
|
|
1984
|
+
async ({ offline }) => reply(runDoctor(Date.now(), offline ?? true))
|
|
1985
|
+
);
|
|
1986
|
+
server.tool(
|
|
1987
|
+
"whoami",
|
|
1988
|
+
`The authenticated LinkedIn member: name, headline, public id, urn. Cheap (1 call). Good first call to confirm the session works and which account it is. ${NO_RETRY}`,
|
|
1989
|
+
{},
|
|
1990
|
+
async () => reply(await runWhoami())
|
|
1991
|
+
);
|
|
1992
|
+
server.tool(
|
|
1993
|
+
"search",
|
|
1994
|
+
`Search LinkedIn people, companies or jobs. CHEAP \u2014 this is the net. Rows already carry name, headline, location and url, so RANK ON THOSE and deep-read only 2-3 finalists with \`profile\`. Calling profile on every result burns a day of budget in one request. \`meta.claimedCount\` is LinkedIn's total for the query (often millions), NOT how many you got, and \`meta.state\` is always "unknown" because this is one page of many. Out-of-network people return as name "LinkedIn Member" with a /headless url \u2014 that is real LinkedIn behaviour for this account, not a failure. ${READING_CONTRACT} ${NO_RETRY}`,
|
|
1995
|
+
{
|
|
1996
|
+
kind: z.enum(["people", "companies", "jobs"]),
|
|
1997
|
+
query: z.string().min(1).describe("search terms"),
|
|
1998
|
+
limit: z.number().int().min(1).max(25).optional().describe("default 10")
|
|
1999
|
+
},
|
|
2000
|
+
async ({ kind, query, limit }) => reply(await runSearch(kind, query, limit ?? 10))
|
|
2001
|
+
);
|
|
2002
|
+
server.tool(
|
|
2003
|
+
"profile",
|
|
2004
|
+
`Read one LinkedIn profile: headline, location, current title, company, school. MEDIUM cost \u2014 use only on finalists surfaced by \`search\`. Accepts a public id, a urn, or a linkedin.com/in/\u2026 URL. KNOWN LIMIT: LinkedIn's profile projections do not return a name, so the result has a headline but no first/last name \u2014 use the identifier you passed in. Do NOT report the profile as empty on that basis. ${NO_RETRY}`,
|
|
2005
|
+
{ id: z.string().min(1).describe("public id, urn, or profile URL") },
|
|
2006
|
+
async ({ id }) => reply(await runProfile(id))
|
|
2007
|
+
);
|
|
2008
|
+
server.tool(
|
|
2009
|
+
"feed",
|
|
2010
|
+
`The user's own chronological LinkedIn feed: author, when, text, url. MEDIUM cost. Promoted posts are dropped and counted in \`meta.excludedCount\`, so fewer items than \`limit\` usually means ads were filtered, not that the fetch failed. ${READING_CONTRACT} ${NO_RETRY}`,
|
|
2011
|
+
{ limit: z.number().int().min(1).max(20).optional().describe("default 10") },
|
|
2012
|
+
async ({ limit }) => reply(await runFeed(limit ?? 10))
|
|
2013
|
+
);
|
|
2014
|
+
server.tool(
|
|
2015
|
+
"post",
|
|
2016
|
+
`A LinkedIn post's comment thread. EXPENSIVE \u2014 read only finalists. Accepts a bare urn:li:activity:\u2026, a urn:li:ugcPost:\u2026, or a linkedin.com/feed/update/\u2026 URL; no prior lookup is needed. Feed and search rows already report how many comments a post has, so use that to decide whether the thread is worth a call. \`meta.state\` is always "unknown" \u2014 this is the first page and pagination is not followed, so NEVER report a comment count as complete. Nested replies are not supported and a comment with replies does not carry them. ${READING_CONTRACT} ${NO_RETRY}`,
|
|
2017
|
+
{
|
|
2018
|
+
urn: z.string().min(1).describe("activity/ugcPost urn, or a feed-update URL"),
|
|
2019
|
+
limit: z.number().int().min(1).max(100).optional().describe("default 20")
|
|
2020
|
+
},
|
|
2021
|
+
async ({ urn, limit }) => reply(await runPost(urn, limit ?? 20))
|
|
2022
|
+
);
|
|
2023
|
+
server.tool(
|
|
2024
|
+
"reactions",
|
|
2025
|
+
`Who reacted to a LinkedIn post, and with which reaction. MEDIUM cost. Often more informative than the comments for mapping who is paying attention to a topic. Same input forms as \`post\`. \`meta.state\` is always "unknown" \u2014 first page only, so do not report a total. ${READING_CONTRACT} ${NO_RETRY}`,
|
|
2026
|
+
{
|
|
2027
|
+
urn: z.string().min(1).describe("activity/ugcPost urn, or a feed-update URL"),
|
|
2028
|
+
limit: z.number().int().min(1).max(100).optional().describe("default 20")
|
|
2029
|
+
},
|
|
2030
|
+
async ({ urn, limit }) => reply(await runReactions(urn, limit ?? 20))
|
|
2031
|
+
);
|
|
2032
|
+
server.tool(
|
|
2033
|
+
"local",
|
|
2034
|
+
"Search the LOCAL cache. Free \u2014 no network call, no budget spent. PREFER THIS before any live command: if the answer is already cached, there is no reason to spend a request on it. The cache only fills when the user runs a live read with --retain, so an empty result here means nothing has been retained yet \u2014 NOT that LinkedIn has nothing. Check `meta.cachedTotal`.",
|
|
2035
|
+
{
|
|
2036
|
+
query: z.string().optional().describe("substring match; omit to list everything"),
|
|
2037
|
+
source: z.string().optional().describe("comma-separated: connections,my-posts,third-party"),
|
|
2038
|
+
since: z.string().optional().describe("YYYY-MM-DD"),
|
|
2039
|
+
limit: z.number().int().min(1).max(100).optional().describe("default 25")
|
|
2040
|
+
},
|
|
2041
|
+
async ({ query, source, since, limit }) => reply(runLocal(query, source, since, limit ?? 25))
|
|
2042
|
+
);
|
|
2043
|
+
for (const source of ["connections", "my-posts"]) {
|
|
2044
|
+
server.tool(
|
|
2045
|
+
source.replace("-", "_"),
|
|
2046
|
+
`The user's own ${source === "connections" ? "connections" : "authored posts"}, read from the LOCAL cache. Free \u2014 no network call, no budget spent. An empty result means the cache has not been filled, NOT that the user has none: tell them to run \`lnrelay sync ${source}\` themselves (it is CLI-only). Check \`meta.cachedTotal\` to tell the two apart.`,
|
|
2047
|
+
{
|
|
2048
|
+
query: z.string().optional().describe("substring match; omit to list everything"),
|
|
2049
|
+
limit: z.number().int().min(1).max(100).optional().describe("default 25")
|
|
2050
|
+
},
|
|
2051
|
+
async ({ query, limit }) => reply(runSourceRead(source, query, limit ?? 25))
|
|
2052
|
+
);
|
|
2053
|
+
}
|
|
2054
|
+
server.tool(
|
|
2055
|
+
"cache_status",
|
|
2056
|
+
"What is cached per source, with sync checkpoints and the retention policy. Free, no network. Third-party records expire 30 days after capture \u2014 the body goes, an identity stub stays, so a re-fetch is a visible choice rather than a silent budget charge.",
|
|
2057
|
+
{},
|
|
2058
|
+
async () => reply(runCacheStatus())
|
|
2059
|
+
);
|
|
2060
|
+
return server;
|
|
2061
|
+
}
|
|
2062
|
+
var entry = shouldRunAsEntry(process.argv[1], import.meta.url, import.meta.main, [
|
|
2063
|
+
"linkedin-relay-mcp",
|
|
2064
|
+
"lnrelay"
|
|
2065
|
+
]);
|
|
2066
|
+
if (entry.run) {
|
|
2067
|
+
const server = buildServer();
|
|
2068
|
+
await server.connect(new StdioServerTransport());
|
|
2069
|
+
}
|
|
2070
|
+
export {
|
|
2071
|
+
buildServer
|
|
2072
|
+
};
|
|
2073
|
+
//# sourceMappingURL=mcp-shim.js.map
|