linkedin-relay-mcp 2.2.0 → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +52 -97
- package/dist/cli.js.map +1 -1
- package/dist/index.js +13 -3
- package/dist/index.js.map +1 -1
- package/dist/mcp-shim.js +13 -3
- package/dist/mcp-shim.js.map +1 -1
- package/package.json +1 -1
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/args.ts","../src/cache/db.ts","../src/cache/store.ts","../src/engine/restli.ts","../src/format.ts","../src/output.ts","../src/commands/cache.ts","../src/engine/auth.ts","../src/progress.ts","../src/engine/budget.ts","../src/engine/classify.ts","../src/engine/client.ts","../src/engine/contracts.ts","../src/engine/parse.ts","../src/engine/index.ts","../src/engine/sdui-harvest.ts","../src/engine/sdui-menu.ts","../src/engine/session.ts","../src/engine/voyager-write.ts","../src/commands/gate.ts","../src/commands/confirm.ts","../src/commands/delete.ts","../src/commands/live.ts","../src/commands/local.ts","../src/commands/oauth.ts","../src/engine/oauth.ts","../src/commands/token.ts","../src/commands/registry.ts","../src/commands/sync.ts","../src/engine/oauth-write.ts","../src/engine/sdui-comment.ts","../src/engine/sdui-write.ts","../src/commands/transport.ts","../src/commands/write.ts","../src/entry.ts","../src/cli.ts"],"sourcesContent":["// Minimal argv parsing. Pure — takes an argv array, returns a plain object.\n\nexport interface ParsedArgs {\n command: string | undefined;\n positionals: string[];\n flags: Record<string, string | boolean>;\n}\n\nexport function parseArgs(argv: string[]): ParsedArgs {\n const [command, ...rest] = argv;\n const positionals: string[] = [];\n const flags: Record<string, string | boolean> = {};\n\n for (let i = 0; i < rest.length; i++) {\n const token = rest[i];\n if (token === undefined) continue;\n\n if (token.startsWith('--')) {\n const key = token.slice(2);\n const next = rest[i + 1];\n // A flag takes a value only when the next token isn't itself a flag.\n if (next !== undefined && !next.startsWith('--')) {\n flags[key] = next;\n i++;\n } else {\n flags[key] = true;\n }\n } else if (token.startsWith('-') && token.length > 1) {\n const key = token.slice(1);\n const next = rest[i + 1];\n if (next !== undefined && !next.startsWith('-')) {\n flags[key] = next;\n i++;\n } else {\n flags[key] = true;\n }\n } else {\n positionals.push(token);\n }\n }\n\n return { command, positionals, flags };\n}\n\nexport function bool(args: ParsedArgs, name: string): boolean {\n return args.flags[name] === true || args.flags[name] === 'true';\n}\n\nexport function str(args: ParsedArgs, name: string): string | undefined {\n const v = args.flags[name];\n return typeof v === 'string' ? v : undefined;\n}\n\nexport function num(args: ParsedArgs, name: string): number | undefined {\n const v = str(args, name);\n if (v === undefined) return undefined;\n const n = Number(v);\n return Number.isFinite(n) ? n : undefined;\n}\n","// ─── The local store ──────────────────────────────────────────────────────────\n//\n// SQLite (`bun:sqlite`, WAL) behind the same narrow load/save/query interface\n// the family's JSON store exposes. The family similarity that matters is the\n// interface, not the file format.\n//\n// SQLite was chosen for one specific reason: it makes \"corrupt\" a detectable,\n// per-source, quarantinable state. In a single JSON blob, corruption is\n// all-or-nothing and tells you nothing about which records survived — and on\n// this platform an empty-looking cache is what triggers a full re-sync against\n// the most hostile host in the research. TTL expiry as a transactional delete\n// rather than a whole-file rewrite is the second reason.\n//\n// Retention is enforced on the READ path, not by a schedule. There is no cron\n// to forget and no purge command to remember: the only code that can observe\n// expired third-party data is the code that deletes it first.\n\nimport { Database } from 'bun:sqlite';\nimport { mkdirSync, renameSync } from 'node:fs';\nimport { cacheDir, cachePath } from './store.ts';\n\nconst DB_FILE = 'cache.db';\n\n/** Third-party rows expire; owner rows do not. */\nexport const THIRD_PARTY_TTL_MS = 30 * 86_400_000;\n\nexport type Source = 'connections' | 'my-posts' | 'third-party';\n\nexport interface Record_ {\n urn: string;\n source: Source;\n /** Shaped JSON. Null once expired — the identity stub survives, the body does not. */\n body: string | null;\n text: string;\n firstSeenAt: number;\n updatedAt: number;\n expiresAt: number | null;\n}\n\n/**\n * Strip diacritics and lowercase, for matching only.\n *\n * SQLite's LIKE is not accent-insensitive, so `local \"kovary\"` found nothing\n * while \"kőváry\" found the record — the user types what is on their keyboard,\n * not what LinkedIn stored. Found by a real search on a Hungarian name.\n *\n * The folded form is stored ALONGSIDE the original, never instead of it: the\n * display value keeps its accents.\n */\nexport function fold(value: string): string {\n return value\n .normalize('NFD')\n .replace(/\\p{Diacritic}/gu, '')\n .toLowerCase();\n}\n\nconst TABLES = [\n `CREATE TABLE IF NOT EXISTS records (\n urn TEXT NOT NULL,\n source TEXT NOT NULL,\n body TEXT,\n text TEXT NOT NULL DEFAULT '',\n textFold TEXT NOT NULL DEFAULT '',\n firstSeenAt INTEGER NOT NULL,\n updatedAt INTEGER NOT NULL,\n expiresAt INTEGER,\n PRIMARY KEY (urn, source)\n )`,\n `CREATE TABLE IF NOT EXISTS checkpoints (\n source TEXT PRIMARY KEY,\n lastSuccessfulAt INTEGER NOT NULL,\n newestCreatedAt INTEGER,\n headIds TEXT NOT NULL DEFAULT '[]',\n state TEXT NOT NULL DEFAULT 'ok'\n )`,\n];\n\n// Indexes are created AFTER migrations, because an index may reference a column\n// a migration is about to add. Creating them alongside the tables meant an\n// existing store — where CREATE TABLE IF NOT EXISTS is a no-op — tried to index\n// a column it did not have yet, and threw on open.\nconst INDEXES = [\n 'CREATE INDEX IF NOT EXISTS records_source ON records(source)',\n 'CREATE INDEX IF NOT EXISTS records_fold ON records(textFold)',\n 'CREATE INDEX IF NOT EXISTS records_expires ON records(expiresAt)',\n];\n\nexport class CacheCorrupt extends Error {\n constructor(\n message: string,\n readonly quarantinedTo: string,\n ) {\n super(message);\n this.name = 'CacheCorrupt';\n }\n}\n\n/**\n * Open the store. A database that fails its integrity check is QUARANTINED and\n * the error is thrown — never silently replaced with an empty one, because an\n * empty cache is operationally active here: it is precisely what makes `sync`\n * enumerate everything again.\n */\nexport function openDb(now = Date.now()): Database {\n mkdirSync(cacheDir(), { recursive: true });\n const path = cachePath(DB_FILE);\n\n let db: Database;\n try {\n db = new Database(path, { create: true });\n const check = db.query('PRAGMA integrity_check').get() as { integrity_check?: string } | null;\n if (check?.integrity_check !== undefined && check.integrity_check !== 'ok') {\n throw new Error(`integrity_check: ${check.integrity_check}`);\n }\n } catch (e) {\n throw quarantine(path, (e as Error).message, now);\n }\n\n db.run('PRAGMA journal_mode = WAL');\n for (const stmt of TABLES) db.run(stmt);\n migrate(db);\n for (const stmt of INDEXES) db.run(stmt);\n sweepExpired(db, now);\n return db;\n}\n\n/**\n * Additive migrations for stores created before a column existed. Kept\n * idempotent and additive so an older cache upgrades in place rather than\n * being discarded — discarding it would trigger a full re-sync, which is the\n * expensive failure on this platform.\n */\nfunction migrate(db: Database): void {\n const columns = db.query('PRAGMA table_info(records)').all() as { name: string }[];\n if (!columns.some((c) => c.name === 'textFold')) {\n db.run(\"ALTER TABLE records ADD COLUMN textFold TEXT NOT NULL DEFAULT ''\");\n }\n // Backfill any row that predates the column.\n const stale = db\n .query(\"SELECT urn, source, text FROM records WHERE textFold = '' AND text != ''\")\n .all() as {\n urn: string;\n source: string;\n text: string;\n }[];\n if (stale.length > 0) {\n const update = db.query('UPDATE records SET textFold = ? WHERE urn = ? AND source = ?');\n db.transaction(() => {\n for (const r of stale) update.run(fold(r.text), r.urn, r.source);\n })();\n }\n}\n\nfunction quarantine(path: string, reason: string, now: number): CacheCorrupt {\n const stamp = new Date(now).toISOString().replace(/[:.]/g, '-');\n const target = cachePath('quarantine', stamp, DB_FILE);\n try {\n mkdirSync(cachePath('quarantine', stamp), { recursive: true });\n renameSync(path, target);\n } catch {\n // Even if it cannot be moved, the caller must still refuse to proceed.\n }\n return new CacheCorrupt(\n `the local cache was unreadable and has been quarantined: ${reason}`,\n target,\n );\n}\n\n/**\n * Expire third-party bodies. The row survives as an identity stub so a re-fetch\n * is a VISIBLE choice — the budget can say \"14 of these 20 are re-fetches of\n * expired records\" instead of quietly charging for them again.\n */\nexport function sweepExpired(db: Database, now = Date.now()): number {\n const result = db.run(\n \"UPDATE records SET body = NULL, text = '', textFold = '' WHERE expiresAt IS NOT NULL AND expiresAt <= ? AND body IS NOT NULL\",\n [now],\n );\n return result.changes;\n}\n\nexport function upsert(\n db: Database,\n source: Source,\n rows: { urn: string; body: unknown; text: string }[],\n now = Date.now(),\n): { added: number; updated: number } {\n const expiresAt = source === 'third-party' ? now + THIRD_PARTY_TTL_MS : null;\n let added = 0;\n let updated = 0;\n\n const exists = db.query('SELECT 1 FROM records WHERE urn = ? AND source = ?');\n const write = db.query(\n `INSERT INTO records (urn, source, body, text, textFold, firstSeenAt, updatedAt, expiresAt)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(urn, source) DO UPDATE SET\n body = excluded.body, text = excluded.text, textFold = excluded.textFold,\n updatedAt = excluded.updatedAt, expiresAt = excluded.expiresAt`,\n );\n\n db.transaction(() => {\n for (const row of rows) {\n if (exists.get(row.urn, source) === null) added++;\n else updated++;\n write.run(\n row.urn,\n source,\n JSON.stringify(row.body),\n row.text,\n fold(row.text),\n now,\n now,\n expiresAt,\n );\n }\n })();\n\n return { added, updated };\n}\n\nexport function count(db: Database, source?: Source): number {\n const row =\n source === undefined\n ? (db.query('SELECT COUNT(*) AS n FROM records').get() as { n: number })\n : (db.query('SELECT COUNT(*) AS n FROM records WHERE source = ?').get(source) as {\n n: number;\n });\n return row.n;\n}\n\n/** Offline search. Substring match over the flattened text of each record. */\nexport function search(\n db: Database,\n query: string,\n opts: { sources?: Source[]; since?: number; limit?: number } = {},\n): Record_[] {\n const sources = opts.sources ?? ['connections', 'my-posts', 'third-party'];\n const placeholders = sources.map(() => '?').join(',');\n const params: (string | number)[] = [...sources];\n\n let sql = `SELECT * FROM records WHERE source IN (${placeholders}) AND body IS NOT NULL`;\n if (query !== '') {\n // Match on the folded column with a folded query, so \"kovary\" finds\n // \"Kőváry\" and vice versa.\n sql += ' AND textFold LIKE ?';\n params.push(`%${fold(query)}%`);\n }\n if (opts.since !== undefined) {\n sql += ' AND updatedAt >= ?';\n params.push(opts.since);\n }\n sql += ' ORDER BY updatedAt DESC LIMIT ?';\n params.push(opts.limit ?? 25);\n\n return db.query(sql).all(...params) as Record_[];\n}\n\nexport function urnsFor(db: Database, source: Source): Set<string> {\n const rows = db.query('SELECT urn FROM records WHERE source = ?').all(source) as {\n urn: string;\n }[];\n return new Set(rows.map((r) => r.urn));\n}\n\nexport function removeUrns(db: Database, source: Source, urns: string[]): number {\n if (urns.length === 0) return 0;\n const stmt = db.query('DELETE FROM records WHERE source = ? AND urn = ?');\n let removed = 0;\n db.transaction(() => {\n for (const urn of urns) removed += stmt.run(source, urn).changes;\n })();\n return removed;\n}\n\n// ─── Checkpoints ──────────────────────────────────────────────────────────────\n\nexport interface Checkpoint {\n source: string;\n lastSuccessfulAt: number;\n newestCreatedAt: number | null;\n headIds: string[];\n /** `snapshot-partial` where no ordering exists — never a fabricated watermark. */\n state: 'ok' | 'snapshot-partial';\n}\n\nexport function getCheckpoint(db: Database, source: Source): Checkpoint | undefined {\n const row = db.query('SELECT * FROM checkpoints WHERE source = ?').get(source) as\n | (Omit<Checkpoint, 'headIds'> & { headIds: string })\n | null;\n if (row === null) return undefined;\n return { ...row, headIds: JSON.parse(row.headIds) as string[] };\n}\n\nexport function setCheckpoint(db: Database, cp: Checkpoint): void {\n db.run(\n `INSERT INTO checkpoints (source, lastSuccessfulAt, newestCreatedAt, headIds, state)\n VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(source) DO UPDATE SET\n lastSuccessfulAt = excluded.lastSuccessfulAt,\n newestCreatedAt = excluded.newestCreatedAt,\n headIds = excluded.headIds,\n state = excluded.state`,\n [cp.source, cp.lastSuccessfulAt, cp.newestCreatedAt, JSON.stringify(cp.headIds), cp.state],\n );\n}\n\nexport function purge(db: Database, scope: 'all' | 'third-party'): number {\n const result =\n scope === 'all'\n ? db.run('DELETE FROM records')\n : db.run(\"DELETE FROM records WHERE source = 'third-party'\");\n if (scope === 'all') db.run('DELETE FROM checkpoints');\n return result.changes;\n}\n","// ─── Local state store ────────────────────────────────────────────────────────\n//\n// Small, replaceable JSON state (the ledger, the cooldown, credentials\n// metadata) lives here. The research cache proper is SQLite and arrives in\n// Phase 4 — see docs/DESIGN.md §5.\n//\n// The rule that matters, and where we deliberately break with the family:\n//\n// never-throw is NOT never-fail.\n//\n// x-relay's store degrades a corrupt file to an empty object so a read never\n// crashes. That is right on X. Here it composes into a disaster: corrupt file →\n// empty cache → sync sees no prior state → full enumeration against the most\n// hostile platform in the research, triggered by a disk error. So a corrupt\n// file is quarantined and reported loudly. An empty result and a lost result\n// must be distinguishable on disk for exactly the same reason they must be\n// distinguishable in a parse.\n\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\n\nexport function cacheDir(): string {\n return process.env.LNRELAY_CACHE_DIR ?? join(homedir(), '.lnrelay');\n}\n\nexport function cachePath(...parts: string[]): string {\n return join(cacheDir(), ...parts);\n}\n\nexport type LoadResult<T> =\n | { state: 'ok'; value: T }\n | { state: 'missing' }\n | { state: 'corrupt'; quarantinedTo: string; reason: string };\n\n/**\n * Read a JSON file. Never throws. A file that exists but cannot be parsed is\n * MOVED to `quarantine/` and reported as corrupt — never silently treated as\n * absent, because \"we lost your data\" and \"you have no data\" lead to opposite\n * and non-interchangeable actions.\n */\nexport function loadJson<T>(path: string): LoadResult<T> {\n if (!existsSync(path)) return { state: 'missing' };\n\n let raw: string;\n try {\n raw = readFileSync(path, 'utf-8');\n } catch (e) {\n return quarantine(path, `unreadable: ${(e as Error).message}`);\n }\n\n try {\n return { state: 'ok', value: JSON.parse(raw) as T };\n } catch (e) {\n return quarantine(path, `unparseable JSON: ${(e as Error).message}`);\n }\n}\n\nfunction quarantine(path: string, reason: string): LoadResult<never> {\n const stamp = new Date().toISOString().replace(/[:.]/g, '-');\n const target = cachePath('quarantine', stamp, path.split('/').pop() ?? 'file');\n try {\n mkdirSync(dirname(target), { recursive: true });\n renameSync(path, target);\n } catch {\n // If we cannot even move it, still report corrupt — the caller must refuse\n // to proceed either way.\n }\n return { state: 'corrupt', quarantinedTo: target, reason };\n}\n\n/**\n * Write JSON atomically: a temp file in the same directory, then rename. A\n * torn write leaves the previous good file intact rather than a truncated one.\n */\nexport function saveJson(path: string, value: unknown): void {\n mkdirSync(dirname(path), { recursive: true });\n const tmp = `${path}.tmp`;\n writeFileSync(tmp, JSON.stringify(value, null, 2), { encoding: 'utf-8', mode: 0o600 });\n renameSync(tmp, path);\n}\n","// ─── Rest.li 2.0 variables grammar ────────────────────────────────────────────\n//\n// LinkedIn's Voyager GraphQL endpoint does NOT take JSON variables. It takes\n// Rest.li 2.0's own tuple grammar:\n//\n// (key:value,key2:value2) object literal\n// List(a,b,c) array\n// a | b OR-group inside a single filter value\n//\n// nested to arbitrary depth. Example (verified, R3 §2):\n//\n// ?queryId=voyagerSearchDashClusters.<hash>&variables=(start:0,query:(keywords:foo,\n// queryParameters:List((key:resultType,value:List(PEOPLE)))))\n//\n// Every client in the 90-repo corpus string-templates this. That is why adding a\n// filter is a guessing game for them: an unescaped comma or paren in a user's\n// search term silently terminates a tuple early and changes what you asked for\n// without erroring. This module is the pure, tested alternative.\n\n/** A value expressible in the Rest.li variables grammar. */\nexport type RestliValue =\n | string\n | number\n | boolean\n | undefined\n | RestliValue[]\n | { [key: string]: RestliValue };\n\n/**\n * Characters that must be percent-encoded inside a scalar value. Two distinct\n * hazards, both silent:\n *\n * Grammar `( ) , : |` change the shape of the tuple. A keyword containing\n * a comma would split one value into two.\n * URL `& # + space %` corrupt the query string the tuple is spliced\n * into. Searching for \"tom & jerry\" would inject a second query\n * parameter, and LinkedIn would answer a question we never asked\n * — returning 200 with plausible results for the wrong query.\n *\n * `%` is listed first and handled first, so an already-percent-looking value is\n * escaped rather than double-decoded into something else.\n */\nconst ENCODED: Record<string, string> = {\n '%': '%25', // MUST be first — see below\n '(': '%28',\n ')': '%29',\n ',': '%2C',\n ':': '%3A',\n '|': '%7C',\n '&': '%26',\n '#': '%23',\n '+': '%2B',\n ' ': '%20',\n};\n\nconst RESERVED = /[%(),:|&#+ ]/g;\n\nfunction encodeScalar(value: string | number | boolean): string {\n if (typeof value !== 'string') return String(value);\n // A single pass over the string, replacing each reserved character with its\n // escape. Because it is one pass, the `%` introduced by an escape is never\n // itself re-escaped — which is what makes the `%` entry above safe.\n return value.replace(RESERVED, (c) => ENCODED[c] ?? c);\n}\n\nfunction encodeValue(value: RestliValue): string | undefined {\n if (value === undefined) return undefined;\n if (Array.isArray(value)) {\n const members = value.map(encodeValue).filter((m): m is string => m !== undefined);\n return `List(${members.join(',')})`;\n }\n if (typeof value === 'object') return encodeObject(value);\n return encodeScalar(value);\n}\n\nfunction encodeObject(obj: { [key: string]: RestliValue }): string {\n const parts: string[] = [];\n for (const [key, value] of Object.entries(obj)) {\n const encoded = encodeValue(value);\n // An undefined value is omitted entirely — never emitted as the string\n // \"undefined\", which LinkedIn would treat as a real filter value.\n if (encoded !== undefined) parts.push(`${key}:${encoded}`);\n }\n return `(${parts.join(',')})`;\n}\n\n/** Encode a variables object into the Rest.li 2.0 grammar. */\nexport function encodeVariables(vars: { [key: string]: RestliValue }): string {\n return encodeObject(vars);\n}\n\n// ─── Composite URNs ───────────────────────────────────────────────────────────\n//\n// Voyager URNs are not always `urn:li:type:id`. Tuple forms appear inline:\n//\n// urn:li:fs_updateV2:(urn:li:activity:999,GROUP_FEED,EMPTY,DEFAULT,false)\n// urn:li:fsd_profilePositionGroup:(urn:li:fsd_profile:ABC,urn:li:fsd_company:(1,2))\n//\n// R3 §4 documents the reference implementation extracting the inner URN with\n// `split(\"(\")[1].split(\",\")[0]`. That is correct only until a member is itself a\n// tuple — and nested tuples do occur. A paren-aware split is barely more code\n// and does not have a silent failure mode.\n\nexport interface TupleUrn {\n /** The URN's own namespace, e.g. `fs_updateV2`. */\n namespace: string;\n /** Top-level members, with nested tuples left intact. */\n members: string[];\n}\n\n/**\n * Parse a composite (tuple-form) URN. Returns null when the URN is not\n * composite, or when its parentheses are unbalanced — an unbalanced URN is\n * malformed data, and guessing at its members would invent structure.\n */\nexport function parseTupleUrn(urn: string): TupleUrn | null {\n const open = urn.indexOf(':(');\n if (open === -1 || !urn.endsWith(')')) return null;\n\n const namespace = urn.slice(0, open).split(':').pop();\n if (namespace === undefined || namespace === '') return null;\n\n const body = urn.slice(open + 2, -1);\n const members: string[] = [];\n let depth = 0;\n let current = '';\n\n for (const char of body) {\n if (char === '(') depth++;\n else if (char === ')') depth--;\n\n if (depth < 0) return null; // closed one we never opened\n\n if (char === ',' && depth === 0) {\n members.push(current);\n current = '';\n } else {\n current += char;\n }\n }\n if (depth !== 0) return null; // opened one we never closed\n\n members.push(current);\n return { namespace, members };\n}\n\n/**\n * The identity a composite URN wraps — its first member. A non-composite URN is\n * returned unchanged, so this is safe to call on any URN.\n */\nexport function innerUrn(urn: string): string {\n const parsed = parseTupleUrn(urn);\n const first = parsed?.members[0];\n return first ?? urn;\n}\n\n// ─── Namespace collapse ───────────────────────────────────────────────────────\n//\n// R3 §4: LinkedIn is mid-migration from `fs_*` (legacy) to `fsd_*` (dash), and\n// three profile URN forms coexist in live responses — the reference client\n// literally string-replaces between them. This is the same legacy/hoisted split\n// that cost x-relay real data, and the fix is the same: collapse to one identity\n// so dedupe and cross-referencing are structural rather than best-effort.\n//\n// Only mappings we have direct evidence for are listed. An unknown namespace\n// passes through untouched — inventing a mapping would silently merge two\n// distinct entities, which is worse than leaving them separate.\nconst NAMESPACE_ALIASES: Record<string, string> = {\n fs_miniProfile: 'fsd_profile',\n fs_profile: 'fsd_profile',\n};\n\n/**\n * Canonicalise a URN: unwrap composite forms to their inner identity, then\n * collapse known legacy namespace aliases onto their dash equivalent.\n * Idempotent.\n */\nexport function canonicalUrn(urn: string): string {\n const inner = innerUrn(urn);\n const parts = inner.split(':');\n // urn:li:<namespace>:<id...>\n const namespace = parts[2];\n if (namespace === undefined) return inner;\n\n const alias = NAMESPACE_ALIASES[namespace];\n if (alias === undefined) return inner;\n\n parts[2] = alias;\n return parts.join(':');\n}\n","// ─── Presentation ─────────────────────────────────────────────────────────────\n//\n// Pure shaping of Voyager entities into flat, readable rows. No I/O.\n//\n// LinkedIn wraps essentially every piece of display text in a TextViewModel\n// (`{text, textDirection, attributesV2, $type}`), sometimes twice — a post's\n// commentary is `commentary.text.text`. Raw entities are therefore both huge\n// and unreadable, so commands shape by default and keep the raw node behind\n// `--raw` for when a shape has drifted and you need to see what actually came\n// back.\n//\n// Every shaper is defensive: an unrecognised entity still reports its `$type`\n// rather than returning nothing, because the parser deliberately lets unknown\n// types through and silently blanking them here would undo that.\n\nimport type { Entity } from './engine/parse.ts';\nimport { innerUrn } from './engine/restli.ts';\n\nexport interface Shaped {\n type?: string;\n urn?: string;\n name?: string;\n headline?: string;\n location?: string;\n url?: string;\n text?: string;\n author?: string;\n posted?: string;\n [key: string]: unknown;\n}\n\n/** Pull the string out of a TextViewModel, at either nesting depth. */\nfunction text(value: unknown): string | undefined {\n if (typeof value === 'string') return value.trim() || undefined;\n if (value === null || typeof value !== 'object') return undefined;\n\n const node = value as { text?: unknown };\n if (typeof node.text === 'string') return node.text.trim() || undefined;\n // commentary.text.text — the doubly-wrapped case.\n if (node.text !== null && typeof node.text === 'object') return text(node.text);\n return undefined;\n}\n\nfunction typeOf(node: Entity): string | undefined {\n const t = node.$type ?? (node as { _type?: unknown })._type;\n return typeof t === 'string' ? t : undefined;\n}\n\n/** Drop tracking query strings, which differ per request for identical results. */\nfunction cleanUrl(url: unknown): string | undefined {\n if (typeof url !== 'string' || url === '') return undefined;\n const cut = url.indexOf('?');\n return cut === -1 ? url : url.slice(0, cut);\n}\n\nfunction defined<T extends Record<string, unknown>>(obj: T): T {\n for (const key of Object.keys(obj)) {\n if (obj[key] === undefined) delete obj[key];\n }\n return obj;\n}\n\nfunction shapeSearchRow(node: Entity): Shaped {\n const entityUrn = typeof node.entityUrn === 'string' ? node.entityUrn : undefined;\n return defined({\n type: typeOf(node),\n // The entity urn is composite — (profileUrn, SEARCH_SRP, DEFAULT) — and the\n // member identity is its first member.\n urn: entityUrn === undefined ? undefined : innerUrn(entityUrn),\n name: text(node.title),\n headline: text(node.primarySubtitle),\n location: text(node.secondarySubtitle),\n url: cleanUrl(node.navigationUrl),\n });\n}\n\n/**\n * Engagement counts are two references away from the post:\n *\n * UpdateV2 --*socialDetail--> SocialDetail --*totalSocialActivityCounts--> counts\n *\n * The parser drops both intermediate nodes as decorations, which is correct —\n * they are not content — so without the index a post has no like or comment\n * count at all. Engagement is the main ranking signal for research, so it is\n * worth the two hops.\n *\n * The same SocialDetail also carries the post's **ugcPost** URN, which is NOT\n * the activity URN in `updateMetadata` (verified live: activity …8686600193 vs\n * ugcPost …7814144000). Reactions and comments key off the ugcPost form, so\n * this is where that mapping comes from — it cannot be derived.\n */\n/**\n * A post's own urn, from whichever of the two live shapes it is.\n *\n * `com.linkedin.voyager.feed.render.UpdateV2` carries it in `updateMetadata`.\n * Its dash sibling `com.linkedin.voyager.dash.feed.Update` — what `myPosts`\n * returns — has no `updateMetadata` at all, and hides the activity urn in the\n * first member of a composite entityUrn tuple:\n *\n * urn:li:fsd_update:(urn:li:activity:662…,MEMBER_SHARES,DEBUG_REASON,…)\n *\n * Handling only the first shape made every post from `my-posts` arrive with no\n * urn, which left `delete` unable to identify the post it was about to destroy.\n */\nfunction postUrn(node: Entity): string | undefined {\n const meta = node.updateMetadata as { urn?: unknown } | undefined;\n if (typeof meta?.urn === 'string') return meta.urn;\n\n const entityUrn = node.entityUrn;\n if (typeof entityUrn !== 'string') return undefined;\n return /urn:li:(activity|ugcPost|share):\\d+/.exec(entityUrn)?.[0];\n}\n\nfunction shapePost(node: Entity, index?: Map<string, Entity>): Shaped {\n const actor = node.actor as { name?: unknown; subDescription?: unknown } | undefined;\n const urn = postUrn(node);\n\n const social = deref(node, '*socialDetail', index);\n const counts =\n social === undefined ? undefined : deref(social, '*totalSocialActivityCounts', index);\n\n return defined({\n type: typeOf(node),\n urn,\n threadUrn: typeof social?.urn === 'string' ? social.urn : undefined,\n author: text(actor?.name),\n // `text()` already trims; LinkedIn pads these with trailing spaces.\n posted: text(actor?.subDescription),\n text: text(node.commentary),\n likes: numberOf(counts?.numLikes),\n comments: numberOf(counts?.numComments),\n shares: numberOf(counts?.numShares ?? social?.totalShares),\n url: urn === undefined ? undefined : `https://www.linkedin.com/feed/update/${urn}/`,\n });\n}\n\nfunction numberOf(value: unknown): number | undefined {\n return typeof value === 'number' ? value : undefined;\n}\n\n/**\n * Resolve a `*`-prefixed URN reference on a node against the side-table.\n * LinkedIn returns location, current position and education as references, so\n * a profile without its index is mostly pointers.\n */\nfunction deref(\n node: Entity,\n key: string,\n index: Map<string, Entity> | undefined,\n): Entity | undefined {\n if (index === undefined) return undefined;\n const ref = node[key];\n if (typeof ref === 'string') return index.get(ref);\n if (ref === undefined) return undefined;\n if (ref !== null && typeof ref === 'object') {\n for (const [k, v] of Object.entries(ref as Record<string, unknown>)) {\n if (k.startsWith('*') && typeof v === 'string') return index.get(v);\n }\n }\n return undefined;\n}\n\n/**\n * Shape a full profile, resolving the references LinkedIn leaves dangling.\n *\n * Note the honest gap: none of the observed projections returns\n * firstName/lastName/publicIdentifier, so a looked-up profile has no name.\n * The caller supplied the identifier, so this is a real limit rather than a\n * silent one — see src/engine/contracts.ts.\n */\nexport function shapeProfile(node: Entity, index?: Map<string, Entity>): Shaped {\n const base = shapeMember(node);\n const geo = deref(node, 'geoLocation', index);\n const position =\n deref(node, 'profileTopPosition', index) ?? firstOfType(index, 'profile.Position');\n const education =\n deref(node, 'profileTopEducation', index) ?? firstOfType(index, 'profile.Education');\n\n return defined({\n ...base,\n location: text(geo?.defaultLocalizedName) ?? text(geo?.localizedName),\n title: text(position?.title),\n company: text(position?.companyName),\n school: text(education?.schoolName),\n });\n}\n\nfunction firstOfType(index: Map<string, Entity> | undefined, suffix: string): Entity | undefined {\n if (index === undefined) return undefined;\n for (const node of new Set(index.values())) {\n if (String(node.$type ?? '').endsWith(suffix)) return node;\n }\n return undefined;\n}\n\nfunction shapeMember(node: Entity): Shaped {\n const first = text(node.firstName);\n const last = text(node.lastName);\n const publicId = text(node.publicIdentifier) ?? text(node.publicId);\n const name = [first, last].filter(Boolean).join(' ');\n return defined({\n type: typeOf(node),\n urn: typeof node.entityUrn === 'string' ? node.entityUrn : undefined,\n publicId,\n name: name === '' ? undefined : name,\n headline: text(node.headline) ?? text(node.occupation),\n url: publicId === undefined ? undefined : `https://www.linkedin.com/in/${publicId}/`,\n });\n}\n\n/**\n * A comment. The author lives under `commenter` as a lockup (title/subtitle/\n * navigationUrl), and the comment's own like count is another two-hop\n * dereference through its socialDetail — same chain as a post.\n */\nfunction shapeComment(node: Entity, index?: Map<string, Entity>): Shaped {\n const commenter = node.commenter as Entity | undefined;\n const social = deref(node, '*socialDetail', index);\n const counts =\n social === undefined ? undefined : deref(social, '*totalSocialActivityCounts', index);\n\n return defined({\n type: typeOf(node),\n urn: typeof node.urn === 'string' ? node.urn : undefined,\n author: text(commenter?.title),\n headline: text(commenter?.subtitle),\n authorUrl: cleanUrl(commenter?.navigationUrl),\n text: text(node.comment) ?? text(node.commentary),\n likes: numberOf(counts?.numLikes),\n postedAt:\n typeof node.createdAt === 'number' ? new Date(node.createdAt).toISOString() : undefined,\n edited: node.edited === true ? true : undefined,\n url: cleanUrl(node.permalink),\n });\n}\n\n/** A reactor — who reacted, and with which reaction. */\nfunction shapeReaction(node: Entity, index?: Map<string, Entity>): Shaped {\n const lockup = node.reactorLockup as Entity | undefined;\n const actorUrn = typeof node.actorUrn === 'string' ? node.actorUrn : undefined;\n const profile = actorUrn === undefined ? undefined : index?.get(actorUrn);\n\n return defined({\n type: typeOf(node),\n urn: actorUrn,\n name: text(lockup?.title),\n headline: text(lockup?.subtitle) ?? text(profile?.headline),\n reaction: typeof node.reactionType === 'string' ? node.reactionType : undefined,\n url: cleanUrl(lockup?.navigationUrl),\n });\n}\n\n/** Shape one entity into a flat row, dispatching on its type. */\nexport function shapeEntity(node: Entity, index?: Map<string, Entity>): Shaped {\n try {\n const t = (typeOf(node) ?? '').toLowerCase();\n if (t.includes('entityresultviewmodel')) return shapeSearchRow(node);\n // Order matters: Comment and Reaction are checked before the broader\n // 'update' and 'profile' fragments, which would otherwise swallow them.\n if (t.endsWith('social.comment')) return shapeComment(node, index);\n if (t.endsWith('social.reaction')) return shapeReaction(node, index);\n if (t.includes('update')) return shapePost(node, index);\n if (t.includes('profile')) return shapeMember(node);\n\n // Unrecognised: report the type and make a best effort, so a new shape\n // shows up as thin data rather than as nothing.\n return defined({\n type: typeOf(node),\n urn: typeof node.entityUrn === 'string' ? node.entityUrn : undefined,\n name: text(node.title) ?? text(node.name),\n text: text(node.commentary) ?? text(node.text),\n });\n } catch {\n return defined({ type: typeOf(node) });\n }\n}\n\nexport function shapeAll(items: Entity[], index?: Map<string, Entity>): Shaped[] {\n return items.map((node) => shapeEntity(node, index));\n}\n\n// ─── Output modes ─────────────────────────────────────────────────────────────\n//\n// `--fields` and `--compact` were advertised in the command registry long\n// before they existed — a documented promise the tool did not keep. They exist\n// now, and tests/skill.test.ts asserts that every flag a usage string\n// advertises is actually parsed, so the same drift cannot recur silently.\n//\n// Both are for the same problem: a shaped row is still ~8 keys of JSON, and an\n// agent ranking 25 search results does not need all of them in its context.\n\n/**\n * Keep only the named keys, in the order named. A key no row carries is\n * omitted rather than emitted as `undefined` — a field the user misspelled\n * should not become a column of nulls that looks like missing data.\n */\nexport function project<T extends Record<string, unknown>>(\n rows: T[],\n spec: string,\n): Record<string, unknown>[] {\n const keys = spec\n .split(',')\n .map((k) => k.trim())\n .filter((k) => k !== '');\n if (keys.length === 0) return rows;\n\n return rows.map((row) => {\n const out: Record<string, unknown> = {};\n for (const key of keys) {\n if (row[key] !== undefined) out[key] = row[key];\n }\n return out;\n });\n}\n\n/** Fields to lead with, in preference order — most identifying first. */\nconst LEAD = ['name', 'author', 'title'];\nconst DETAIL = ['headline', 'text', 'location', 'company', 'posted', 'reaction'];\n\n/**\n * One flat line per row. Reduces a page of search results from kilobytes of\n * JSON to something scannable, without losing what a ranking decision needs.\n */\nexport function compactRows(rows: Record<string, unknown>[]): string[] {\n return rows.map((row) => {\n const parts: string[] = [];\n\n for (const key of LEAD) {\n const v = row[key];\n if (typeof v === 'string' && v !== '') {\n parts.push(v);\n break;\n }\n }\n for (const key of DETAIL) {\n const v = row[key];\n if (typeof v === 'string' && v !== '') parts.push(v);\n }\n\n const counts = ['likes', 'comments']\n .map((k) => (typeof row[k] === 'number' ? `${row[k]} ${k}` : undefined))\n .filter((v): v is string => v !== undefined);\n parts.push(...counts);\n\n // A row with nothing human-readable still has to identify itself.\n if (parts.length === 0) {\n const urn = row.urn ?? row.type;\n if (typeof urn === 'string') parts.push(urn);\n }\n\n // One row, one line — a newline in a post body would break the format.\n return parts.join(' · ').replace(/\\s*\\n\\s*/g, ' ');\n });\n}\n","import type { Envelope, Err, Ok } from './types.ts';\n\nexport function ok<T>(command: string, data: T): Ok<T> {\n return { ok: true, command, data };\n}\n\nexport function err(\n command: string,\n code: string,\n message: string,\n hint?: string,\n status?: number,\n retryAfterMs?: number,\n): Err {\n const error: Err['error'] = { code, message };\n if (hint !== undefined) error.hint = hint;\n if (status !== undefined) error.status = status;\n if (retryAfterMs !== undefined) error.retryAfterMs = retryAfterMs;\n return { ok: false, command, error };\n}\n\nexport function toJson(envelope: unknown): string {\n return JSON.stringify(envelope, null, 2);\n}\n\n// ─── Error taxonomy ───────────────────────────────────────────────────────────\n\nexport const ERROR_CODES = [\n // Raised before any network call is made.\n 'INVALID_INPUT',\n 'UNKNOWN_COMMAND',\n 'CONFIRMATION_REQUIRED',\n 'BUDGET_EXHAUSTED',\n 'COOLDOWN_ACTIVE',\n 'CACHE_CORRUPT',\n 'NOT_IMPLEMENTED',\n // Raised from a response.\n 'AUTH_FAILED',\n 'RATE_LIMITED',\n 'REQUEST_DENIED', // HTTP 999 — LinkedIn's non-standard bot block\n 'CHALLENGE_DETECTED',\n 'SCHEMA_DRIFT',\n 'NOT_FOUND',\n 'FETCH_FAILED',\n 'FETCH_TIMEOUT',\n] as const;\n\nexport type ErrorCode = (typeof ERROR_CODES)[number];\n\n/**\n * Whether a failure may be retried automatically.\n *\n * Almost everything is `false`, and that is the point. On LinkedIn a 429 is the\n * warning shot on a documented escalation ladder — retrying into it is the\n * mechanism by which a throttle becomes a restriction. A `retryAfterMs` is\n * information to print for a human, never permission for the process to try\n * again. The single exception is a timeout where no response was received at\n * all, which carries no signal about our standing with LinkedIn.\n *\n * This is a deliberate break with x-relay, which retries 429 three times. That\n * is correct on a platform where the worst case is a temporary block.\n */\nexport function isRetryable(code: ErrorCode | string): boolean {\n return code === 'FETCH_TIMEOUT';\n}\n\n/** 0 success · 1 command error · 2 unknown command. */\nexport function exitCodeFor(envelope: Envelope): number {\n if (envelope.ok) return 0;\n return envelope.error.code === 'UNKNOWN_COMMAND' ? 2 : 1;\n}\n","// Cache-backed commands. These make no network call at all — after a research\n// session, repeat lookups are free, which is the whole point of keeping a local\n// store on a platform where every request is rationed.\n\nimport {\n CacheCorrupt,\n count,\n getCheckpoint,\n openDb,\n purge as purgeDb,\n type Source,\n search as searchDb,\n upsert,\n} from '../cache/db.ts';\nimport { compactRows, project, type Shaped } from '../format.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\n\nconst SOURCES: Source[] = ['connections', 'my-posts', 'third-party'];\n\n/** Turn a CacheCorrupt into an envelope; rethrow anything else. */\nfunction corruptEnvelope(command: string, e: unknown): Envelope {\n if (e instanceof CacheCorrupt) {\n return err(\n command,\n 'CACHE_CORRUPT',\n e.message,\n `Moved to ${e.quarantinedTo}. A corrupt cache is NOT treated as an empty one — that would ` +\n 'trigger a full re-sync against LinkedIn. Inspect it, then re-run.',\n );\n }\n throw e;\n}\n\nexport interface LocalOpts {\n compact?: boolean;\n fields?: string;\n}\n\n/** The cache path honours the same output flags as the live path. */\nfunction render(rows: Record<string, unknown>[], opts: LocalOpts): unknown[] {\n if (opts.compact === true) return compactRows(rows);\n if (opts.fields !== undefined && opts.fields !== '') return project(rows, opts.fields);\n return rows;\n}\n\nexport function runLocal(\n query: string | undefined,\n sources: string | undefined,\n since: string | undefined,\n limit: number,\n opts: LocalOpts = {},\n): Envelope {\n const requested = sources?.split(',').map((s) => s.trim()) ?? SOURCES;\n const invalid = requested.filter((s) => !SOURCES.includes(s as Source));\n if (invalid.length > 0) {\n return err(\n 'local',\n 'INVALID_INPUT',\n `unknown source(s): ${invalid.join(', ')}`,\n `valid sources: ${SOURCES.join(', ')}`,\n );\n }\n\n let sinceMs: number | undefined;\n if (since !== undefined) {\n const parsed = Date.parse(since);\n if (Number.isNaN(parsed)) {\n return err('local', 'INVALID_INPUT', `could not parse --since '${since}'`, 'use YYYY-MM-DD');\n }\n sinceMs = parsed;\n }\n\n try {\n const db = openDb();\n const rows = searchDb(db, query ?? '', {\n sources: requested as Source[],\n ...(sinceMs === undefined ? {} : { since: sinceMs }),\n limit,\n });\n const total = count(db);\n\n const shaped = rows.map((r) => ({\n ...(JSON.parse(r.body ?? '{}') as Shaped),\n source: r.source,\n cachedAt: new Date(r.updatedAt).toISOString(),\n }));\n\n return ok('local', {\n items: render(shaped, opts),\n meta: {\n returnedCount: rows.length,\n cachedTotal: total,\n sources: requested,\n // An empty cache is not an empty LinkedIn — say which one this is.\n note:\n total === 0\n ? 'The local cache is empty. Run a read command with --retain, or sync a source, before searching offline.'\n : undefined,\n },\n });\n } catch (e) {\n return corruptEnvelope('local', e);\n }\n}\n\n/**\n * `connections` and `my-posts` are the same offline read as `local`, with the\n * source pinned. They exist as separate commands because that is how a user\n * thinks about their own data — `--sync` fills them, they read from cache.\n */\nexport function runSourceRead(\n command: 'connections' | 'my-posts',\n query: string | undefined,\n limit: number,\n opts: LocalOpts = {},\n): Envelope {\n const result = runLocal(query, command, undefined, limit, opts);\n if (!result.ok) return result;\n const data = result.data as Record<string, unknown>;\n const meta = data.meta as Record<string, unknown>;\n if ((meta.cachedTotal as number) === 0 || (meta.returnedCount as number) === 0) {\n meta.note = `Nothing cached for '${command}'. Run \\`lnrelay sync ${command}\\` first — this command reads the local cache and makes no network call.`;\n }\n return ok(command, data);\n}\n\nexport function runPurge(scope: string | undefined, confirmed: boolean): Envelope {\n const target = scope === 'all' ? 'all' : 'third-party';\n\n if (!confirmed) {\n try {\n const db = openDb();\n return err(\n 'purge',\n 'CONFIRMATION_REQUIRED',\n `would delete ${target === 'all' ? count(db) : count(db, 'third-party')} records (${target})`,\n 'Re-run with --confirm. This only touches local files; it never contacts LinkedIn.',\n );\n } catch (e) {\n return corruptEnvelope('purge', e);\n }\n }\n\n try {\n const db = openDb();\n const removed = purgeDb(db, target);\n return ok('purge', { scope: target, removed, remaining: count(db) });\n } catch (e) {\n return corruptEnvelope('purge', e);\n }\n}\n\nexport function runCacheStatus(): Envelope {\n try {\n const db = openDb();\n return ok('cache-status', {\n total: count(db),\n bySource: Object.fromEntries(SOURCES.map((s) => [s, count(db, s)])),\n checkpoints: Object.fromEntries(SOURCES.map((s) => [s, getCheckpoint(db, s) ?? null])),\n retention:\n 'Third-party records expire 30 days after capture; the body is deleted and an identity ' +\n 'stub remains so a re-fetch is a visible choice. Owner data never expires.',\n });\n } catch (e) {\n return corruptEnvelope('cache-status', e);\n }\n}\n\n/**\n * Retain shaped rows from a live read. Opt-in (`--retain`) rather than\n * automatic: caching every profile you glance at recreates a personal data\n * lake, which is exactly the shape the risk research warns against.\n */\nexport type RetainResult = { added: number; updated: number } | { skipped: string };\n\nexport function retain(source: Source, items: Shaped[]): RetainResult {\n const rows = items\n .filter((i) => typeof i.urn === 'string' && i.urn !== '')\n .map((i) => ({\n urn: i.urn as string,\n body: i,\n text: [i.name, i.headline, i.location, i.text, i.author, i.company, i.title]\n .filter((v) => typeof v === 'string')\n .join(' '),\n }));\n if (rows.length === 0) return { skipped: 'no items carried a urn to key on' };\n\n try {\n return upsert(openDb(), source, rows);\n } catch (e) {\n // Retention never fails the read the user actually asked for — but it says\n // WHY it did nothing. Returning a silent null here cost real debugging time\n // once already.\n return { skipped: (e as Error).message };\n }\n}\n","// ─── Session and headers ──────────────────────────────────────────────────────\n//\n// Verified live on 2026-08-01: the auth surface is exactly two cookies. `li_at`\n// is the session; `JSESSIONID` exists pre-login too, so its presence alone\n// means nothing. The `csrf-token` header is JSESSIONID with quotes stripped —\n// a derivation, not a second secret.\n//\n// Everything the research listed as a \"cargo-cult candidate\" — x-li-track,\n// x-li-page-instance, x-li-deviceId, li_rm, bcookie, bscookie — was confirmed\n// unnecessary. We do not send them. An unexplained header is as likely to be a\n// fingerprint mismatch as a fix.\n//\n// The User-Agent is stored with the session rather than hardcoded, because a\n// stale UA measurably raises the challenge rate; hardcoding is exactly how the\n// reference client ended up shipping a Chrome 83 string into 2026.\n\nexport interface Session {\n liAt: string;\n jsessionId: string;\n userAgent: string;\n /** ISO date the cookies were minted, so `doctor` can flag staleness. */\n capturedAt: string;\n /** The owner this session is sealed to. A mismatch opens the circuit. */\n ownerUrn?: string;\n}\n\nexport function csrfToken(jsessionId: string): string {\n return jsessionId.replace(/\"/g, '');\n}\n\n/** The complete, minimal header set for an authenticated Voyager call. */\nexport function buildHeaders(session: Session): Record<string, string> {\n return {\n cookie: `li_at=${session.liAt}; JSESSIONID=${session.jsessionId}`,\n 'csrf-token': csrfToken(session.jsessionId),\n 'x-restli-protocol-version': '2.0.0',\n accept: 'application/vnd.linkedin.normalized+json+2.1',\n 'x-li-lang': 'en_US',\n 'user-agent': session.userAgent,\n };\n}\n\nexport interface SessionCheck {\n ok: boolean;\n detail: string;\n}\n\n/**\n * Validate a session's SHAPE without touching the network, and without ever\n * revealing a credential value — lengths only, so `doctor` output is safe to\n * paste into a bug report.\n */\nexport function checkSession(session: Partial<Session> | null): SessionCheck {\n if (session === null || session.liAt === undefined || session.liAt === '') {\n return { ok: false, detail: 'no li_at — run `lnrelay login`' };\n }\n if (session.jsessionId === undefined || session.jsessionId === '') {\n return { ok: false, detail: 'no JSESSIONID — run `lnrelay login`' };\n }\n if (session.userAgent === undefined || session.userAgent === '') {\n return { ok: false, detail: 'no user-agent recorded with the session' };\n }\n const age = sessionAgeDays(session.capturedAt);\n const staleness =\n age !== undefined && age > 90 ? `; UA is ${age} days old, consider re-login` : '';\n return {\n ok: true,\n detail: `li_at present (len ${session.liAt.length}); JSESSIONID present (len ${session.jsessionId.length})${staleness}`,\n };\n}\n\nexport function sessionAgeDays(\n capturedAt: string | undefined,\n now = Date.now(),\n): number | undefined {\n if (capturedAt === undefined) return undefined;\n const then = Date.parse(capturedAt);\n if (Number.isNaN(then)) return undefined;\n return Math.floor((now - then) / 86_400_000);\n}\n","// Progress reporting for long-running / multi-step commands.\n//\n// The hard invariant: stdout carries ONLY the final JSON envelope. Progress is\n// human-facing chatter, so it goes to STDERR (never stdout) and is silenced by\n// --quiet. The write sink is injectable purely so tests can capture it without\n// spying on process.stderr.\n\nexport type ProgressReporter = (msg: string) => void;\n\n/**\n * Build a progress reporter. When `quiet` is true it drops every message;\n * otherwise it writes `msg + '\\n'` to stderr (or the injected `write` sink).\n */\nexport function progressReporter(\n quiet: boolean,\n write: (s: string) => void = (s) => {\n process.stderr.write(s);\n },\n): ProgressReporter {\n return (msg: string) => {\n if (!quiet) write(`${msg}\\n`);\n };\n}\n","// ─── Spend accounting and the circuit breaker ─────────────────────────────────\n//\n// Two structural safety mechanisms live here, both pure (a clock is always\n// injected, never read):\n//\n// 1. Permits. `client` cannot be called without a `Permit`, and `spend()` is\n// the only thing that can make one. \"Issue a network call without\n// accounting for it\" is therefore a compile error rather than a\n// code-review norm. Redirects, pagination continuations and contract\n// discovery all consume permits too — otherwise the traffic easiest to\n// forget is exactly the traffic that escapes accounting.\n//\n// 2. The cooldown. A FILE, not process state. A CLI is a swarm of\n// short-lived processes, so an in-memory breaker protects nothing: the\n// next invocation would start clean and hammer straight back into the\n// throttle that opened it.\n//\n// About the numbers below: the field research swept 364 posts looking for\n// corroborated rate ceilings and found essentially none — one secondhand vendor\n// figure. So every cap is labelled with where it actually came from, and\n// `lnrelay budget` prints that label. None of them is `measured`, because we\n// have measured nothing. They are starting knobs, not LinkedIn facts.\n\nimport type { CapProvenance } from '../types.ts';\n\nconst HOUR = 3_600_000;\nconst DAY = 86_400_000;\n\nexport type SpendClass = 'profile' | 'search' | 'page' | 'write' | 'global';\n\nexport interface Cap {\n perDay: number;\n provenance: CapProvenance;\n note: string;\n}\n\nexport const CAPS: Record<SpendClass, Cap> = {\n profile: {\n perDay: 30,\n provenance: 'vendor-lore',\n note: \"transplanted from jjuanrivvera/linkedin-cli's job-detail cap\",\n },\n search: { perDay: 25, provenance: 'guessed', note: 'no corroborated figure exists' },\n page: { perDay: 60, provenance: 'guessed', note: 'thread/feed pagination' },\n write: {\n perDay: 10,\n provenance: 'guessed',\n note: 'deliberately below the weakly-reported ~20/day connection lore',\n },\n global: { perDay: 250, provenance: 'guessed', note: 'all classes combined' },\n};\n\n/** Minimum gap between any two calls, before jitter. */\nexport const MIN_GAP_MS = 3_000;\n\n// ─── Permits ──────────────────────────────────────────────────────────────────\n\n/**\n * Proof that a call was accounted for. The brand is unexported, so `spend()` is\n * the only thing in the program that can produce one.\n */\nexport interface Permit {\n readonly __brand: unique symbol;\n class: SpendClass;\n issuedAt: number;\n}\n\nexport interface Ledger {\n /** Epoch-ms timestamps of each spend, keyed by class. */\n spends: Record<string, number[]>;\n}\n\nexport function emptyLedger(): Ledger {\n return { spends: {} };\n}\n\nexport interface BudgetError {\n code: 'BUDGET_EXHAUSTED';\n message: string;\n hint: string;\n}\n\nexport type SpendResult = { permit: Permit; ledger: Ledger } | { error: BudgetError };\n\nfunction within(times: number[] | undefined, now: number, window: number): number[] {\n if (times === undefined) return [];\n return times.filter((t) => now - t < window);\n}\n\nfunction allSpends(ledger: Ledger, now: number): number[] {\n return Object.values(ledger.spends).flatMap((times) => within(times, now, DAY));\n}\n\n/**\n * Account for one intended call. Returns a permit and the updated ledger, or a\n * refusal — and a refusal charges nothing, so a denied call never consumes\n * budget.\n */\nexport function spend(ledger: Ledger, cls: SpendClass, now: number): SpendResult {\n const recent = allSpends(ledger, now);\n\n const last = recent.length > 0 ? Math.max(...recent) : undefined;\n if (last !== undefined && now - last < MIN_GAP_MS) {\n return {\n error: {\n code: 'BUDGET_EXHAUSTED',\n message: `minimum gap of ${MIN_GAP_MS}ms between calls not met`,\n hint: 'requests are paced deliberately; wait and retry',\n },\n };\n }\n\n if (recent.length >= CAPS.global.perDay) {\n return {\n error: {\n code: 'BUDGET_EXHAUSTED',\n message: `global daily cap of ${CAPS.global.perDay} calls reached`,\n hint: 'resets on a rolling 24h window; see `lnrelay budget`',\n },\n };\n }\n\n const cap = CAPS[cls];\n const forClass = within(ledger.spends[cls], now, DAY);\n if (forClass.length >= cap.perDay) {\n return {\n error: {\n code: 'BUDGET_EXHAUSTED',\n message: `daily cap of ${cap.perDay} reached for '${cls}'`,\n hint: `cap provenance: ${cap.provenance} (${cap.note}). See \\`lnrelay budget\\`.`,\n },\n };\n }\n\n return {\n permit: { class: cls, issuedAt: now } as Permit,\n ledger: { spends: { ...ledger.spends, [cls]: [...forClass, now] } },\n };\n}\n\nexport interface BudgetSummary {\n class: SpendClass;\n spentInWindow: number;\n cap: number;\n remaining: number;\n capProvenance: CapProvenance;\n warning?: string;\n}\n\nexport function summarise(ledger: Ledger, cls: SpendClass, now: number): BudgetSummary {\n const cap = CAPS[cls];\n const spent =\n cls === 'global' ? allSpends(ledger, now).length : within(ledger.spends[cls], now, DAY).length;\n const remaining = Math.max(0, cap.perDay - spent);\n\n const summary: BudgetSummary = {\n class: cls,\n spentInWindow: spent,\n cap: cap.perDay,\n remaining,\n capProvenance: cap.provenance,\n };\n if (remaining / cap.perDay < 0.25) {\n summary.warning = `only ${remaining} of ${cap.perDay} '${cls}' calls left in this 24h window — consider stopping`;\n }\n return summary;\n}\n\n// ─── The circuit breaker ──────────────────────────────────────────────────────\n\nexport type CooldownReason = 'RATE_LIMITED' | 'REQUEST_DENIED' | 'CHALLENGE_DETECTED';\n\nexport interface Cooldown {\n reason: CooldownReason;\n since: number;\n /** Epoch-ms when it lifts, or null for indefinite. */\n until: number | null;\n clearRequires: 'time' | 'human';\n}\n\n/**\n * Open a cooldown. The durations escalate with how bad the signal is: a 429 is\n * a throttle, a 999 is a network-layer bot block that lifts only as traffic\n * normalises, and a challenge means LinkedIn wants to see a human — so only a\n * human can clear it, via `lnrelay budget --reset-cooldown --confirm`.\n */\nexport function openCooldown(reason: CooldownReason, now: number): Cooldown {\n if (reason === 'CHALLENGE_DETECTED') {\n return { reason, since: now, until: null, clearRequires: 'human' };\n }\n const duration = reason === 'REQUEST_DENIED' ? 6 * HOUR : HOUR;\n return { reason, since: now, until: now + duration, clearRequires: 'time' };\n}\n\nexport function activeCooldown(cooldown: Cooldown | null, now: number): boolean {\n if (cooldown === null) return false;\n if (cooldown.until === null) return true;\n return now < cooldown.until;\n}\n","// ─── Response classification ──────────────────────────────────────────────────\n//\n// Every response passes through here BEFORE any parsing. That ordering is the\n// point: a parser asked to read a challenge page or a 410 envelope will happily\n// return an empty array, and an empty array is indistinguishable from \"there\n// was nothing\". Classification is what keeps those two apart.\n//\n// Nothing classified here is ever retried automatically. On LinkedIn a 429 is\n// the warning shot on a documented escalation ladder, so a `retry-after` is\n// information to print for a human — never permission for the process to go\n// again. The `retry` field exists so that rule is asserted in tests.\n\nimport type { CooldownReason } from './budget.ts';\n\nexport interface RawResponse {\n status: number;\n body: string;\n headers?: Record<string, string>;\n}\n\nexport interface Classification {\n outcome: 'ok' | 'error';\n /** The unparsed body, kept for surfaces whose response is not JSON. */\n raw?: string;\n code?: string;\n message?: string;\n hint?: string;\n /** Which cooldown to open, if any. */\n cooldown?: CooldownReason;\n retryAfterMs?: number;\n retry: boolean;\n /** Parsed body, when it was JSON and we already did the work. */\n json?: unknown;\n}\n\nconst CHALLENGE_MARKERS = /checkpoint|challenge|captcha|security verification|unusual activity/i;\nconst LOGIN_REDIRECT = /\\/login|\\/uas\\/login|session_redirect/i;\n\nfunction fail(code: string, message: string, extra: Partial<Classification> = {}): Classification {\n return { outcome: 'error', code, message, retry: false, ...extra };\n}\n\nconst CHALLENGE_HINT =\n 'Open LinkedIn in a real browser, clear the challenge, then `lnrelay budget --reset-cooldown --confirm`.';\n\n/** Redirects carry two very different meanings; confusing them costs a day. */\nfunction classifyRedirect(location: string): Classification {\n if (CHALLENGE_MARKERS.test(location)) {\n return fail('CHALLENGE_DETECTED', `redirected to a challenge: ${location}`, {\n cooldown: 'CHALLENGE_DETECTED',\n hint: CHALLENGE_HINT,\n });\n }\n if (LOGIN_REDIRECT.test(location)) {\n return fail('AUTH_FAILED', 'redirected to the login page', {\n hint: 'This signature means expired cookies, NOT bot detection. Re-run `lnrelay login`.',\n });\n }\n return fail('FETCH_FAILED', `unexpected redirect to ${location || '(none)'}`);\n}\n\n/**\n * A challenge served with status 200, if this body is one.\n *\n * Split out of classifyBody because it applies to EVERY path: a write must not\n * skip the challenge check just because its body is not a read contract.\n */\nfunction challengeIn(body: string): Classification | null {\n if (!CHALLENGE_MARKERS.test(body.slice(0, 4000))) return null;\n return fail('CHALLENGE_DETECTED', 'a challenge page was returned with status 200', {\n cooldown: 'CHALLENGE_DETECTED',\n hint: CHALLENGE_HINT,\n });\n}\n\n/** A 200 can still be a failure. Everything here inspects the body. */\nfunction classifyBody(body: string): Classification {\n const challenge = challengeIn(body);\n if (challenge !== null) return challenge;\n\n let json: unknown;\n try {\n json = JSON.parse(body);\n } catch {\n return fail('SCHEMA_DRIFT', 'response was 200 but not JSON', {\n hint: 'LinkedIn may have served HTML — inspect the raw body.',\n });\n }\n\n const envelope = json as { data?: Record<string, unknown>; included?: unknown[] };\n\n // An inner status can contradict the HTTP one.\n const innerStatus = (envelope.data as { status?: number } | undefined)?.status;\n if (typeof innerStatus === 'number' && innerStatus >= 400) {\n return fail('SCHEMA_DRIFT', `body carries an inner status ${innerStatus}`, {\n hint: 'The endpoint answered but reported a failure. Re-capture the operation.',\n });\n }\n\n // The 336-analogue: `data` names URNs that `included` does not contain at\n // all. The decoration failed wholesale — this is a failed fetch wearing the\n // costume of an empty result.\n if (referencesUrns(envelope.data) && (envelope.included?.length ?? 0) === 0) {\n return fail('SCHEMA_DRIFT', 'data references entities but included[] is empty', {\n hint: 'Decoration failed wholesale — this is a failed fetch, not an empty result.',\n });\n }\n\n return { outcome: 'ok', retry: false, json };\n}\n\nexport interface ClassifyOpts {\n /**\n * Whether the body is a contract to validate (a read) or a receipt (a write).\n *\n * A read's body must be a Voyager envelope, and a body that is not one means\n * something went wrong even under a 200. A WRITE's body is whatever the\n * surface feels like returning — LinkedIn's SDUI endpoints answer with a\n * React Server Components stream, which is not JSON and never will be.\n *\n * Defaults to true so reads keep their contract and nothing loosens by\n * omission.\n */\n expectJson?: boolean;\n}\n\nexport function classify(res: RawResponse, opts: ClassifyOpts = {}): Classification {\n const headers = res.headers ?? {};\n\n if (res.status >= 300 && res.status < 400) {\n return classifyRedirect(headers.location ?? '');\n }\n\n // ── Hard blocks ────────────────────────────────────────────────────────────\n if (res.status === 999) {\n return fail('REQUEST_DENIED', 'LinkedIn returned HTTP 999 (Request Denied)', {\n cooldown: 'REQUEST_DENIED',\n hint: 'A network-layer bot block that lifts only as traffic normalises. Stop making requests.',\n });\n }\n\n if (res.status === 429) {\n const retryAfter = Number(headers['retry-after']);\n const out = fail('RATE_LIMITED', 'LinkedIn throttled this request', {\n cooldown: 'RATE_LIMITED',\n hint: 'Not retried automatically — a throttle is the warning shot before a restriction.',\n });\n if (Number.isFinite(retryAfter)) out.retryAfterMs = retryAfter * 1000;\n return out;\n }\n\n if (res.status === 401 || res.status === 403) {\n return fail('AUTH_FAILED', `LinkedIn rejected the session (${res.status})`, {\n hint: 'Usually expired cookies. Re-run `lnrelay login`.',\n });\n }\n\n // ── Endpoint drift ─────────────────────────────────────────────────────────\n // 410 is the shape profileView returned on 2026-08-01: the endpoint existed,\n // answered, and told us it is gone.\n if (res.status === 410) {\n return fail('SCHEMA_DRIFT', 'endpoint returned 410 Gone — it no longer exists', {\n hint: 'Re-capture the operation with scripts/observe.ts and update src/engine/contracts.ts.',\n });\n }\n\n if (res.status === 400) {\n const hint = /queryid/i.test(res.body)\n ? 're-capture the queryId with scripts/observe.ts and update src/engine/contracts.ts'\n : 'check the encoded variables against a live capture';\n return fail('SCHEMA_DRIFT', `LinkedIn rejected the request shape (400)`, { hint });\n }\n\n if (res.status === 404) {\n return fail('NOT_FOUND', 'no such resource');\n }\n\n if (res.status < 200 || res.status >= 300) {\n return fail('FETCH_FAILED', `unexpected status ${res.status}`);\n }\n\n // Writes answer 201 Created and 204 No Content with an empty body. Reads\n // never do either, which is how this was missed until the first live share\n // came back 201 and was reported as a failure — after the post had been\n // created. That is the worst direction to be wrong in: a user told their\n // post failed re-runs the command and posts twice.\n //\n // An empty body is therefore a normal write outcome and must not reach\n // classifyBody, whose whole job is detecting a READ that returned nothing\n // when it claimed otherwise.\n if (res.body.trim() === '') return { outcome: 'ok', retry: false, json: null };\n\n // A challenge is served with status 200 and an HTML body on ANY path, so it\n // is checked before the read/write split — a write must not walk past it.\n const challenge = challengeIn(res.body);\n if (challenge !== null) return challenge;\n\n if (opts.expectJson === false) {\n // Parse opportunistically: some writes do answer JSON and the caller can\n // use it, but a body we cannot parse is not an error on this path. The raw\n // text is carried through either way — LinkedIn's SDUI surface answers with\n // an RSC stream that DESCRIBES its available actions, and that description\n // is the most useful thing in the response.\n try {\n return { outcome: 'ok', retry: false, json: JSON.parse(res.body) as unknown, raw: res.body };\n } catch {\n return { outcome: 'ok', retry: false, json: null, raw: res.body };\n }\n }\n\n return classifyBody(res.body);\n}\n\n/** Whether `data` names any URN we would expect `included[]` to resolve. */\nfunction referencesUrns(data: Record<string, unknown> | undefined): boolean {\n if (data === undefined) return false;\n let found = false;\n\n const walk = (node: unknown): void => {\n if (found || node === null || typeof node !== 'object') return;\n if (Array.isArray(node)) {\n for (const item of node) walk(item);\n return;\n }\n for (const [key, value] of Object.entries(node)) {\n // `*`-prefixed keys are Voyager's reference convention.\n if (key.startsWith('*') && Array.isArray(value) && value.length > 0) {\n found = true;\n return;\n }\n if (typeof value === 'string' && value.startsWith('urn:li:')) {\n found = true;\n return;\n }\n walk(value);\n }\n };\n\n walk(data);\n return found;\n}\n","// ─── The request driver ───────────────────────────────────────────────────────\n//\n// The only place in the program that issues a network request, and the only\n// place that spends budget. `fetch`, the clock and the sleeper are all injected\n// so this whole file is testable without touching the network.\n//\n// Order of operations is the safety design, and it is deliberate:\n//\n// 1. cooldown check — refuse before spending anything, in every process\n// 2. permit — no Permit, no call; unaccounted traffic is impossible\n// 3. jittered pace — never two calls back to back\n// 4. fetch\n// 5. classify — before parsing, always\n// 6. open a cooldown — on any throttle/block/challenge signal\n//\n// Nothing here retries. That is the point.\n\nimport { buildHeaders, type Session } from './auth.ts';\nimport type { Ledger, SpendClass } from './budget.ts';\nimport { activeCooldown, type Cooldown, MIN_GAP_MS, openCooldown, spend } from './budget.ts';\nimport { type Classification, classify } from './classify.ts';\n\nexport interface ClientDeps {\n fetch: typeof globalThis.fetch;\n /** Human-facing progress, on stderr. Optional so tests stay silent. */\n progress?: (message: string) => void;\n now: () => number;\n sleep: (ms: number) => Promise<void>;\n /** [0,1). Injected so jitter is deterministic in tests. */\n random: () => number;\n loadLedger: () => Ledger;\n saveLedger: (l: Ledger) => void;\n loadCooldown: () => Cooldown | null;\n saveCooldown: (c: Cooldown | null) => void;\n}\n\nexport interface RequestSpec {\n url: string;\n spendClass: SpendClass;\n operation: string;\n method?: string;\n /** Serialised as JSON when present. Reads carry none and must stay that way. */\n body?: unknown;\n}\n\nexport type ClientResult =\n | { ok: true; json: unknown; classification: Classification }\n | { ok: false; code: string; message: string; hint?: string; retryAfterMs?: number };\n\n/** Upper bound of the jittered gap. Lower bound is MIN_GAP_MS. */\nconst MAX_GAP_MS = 15_000;\n\nexport function createClient(session: Session, deps: ClientDeps) {\n async function request(spec: RequestSpec): Promise<ClientResult> {\n const now = deps.now();\n\n // 1. The breaker, first and in every process. A cooldown lives in a file\n // precisely so a fresh CLI invocation cannot walk straight back into the\n // throttle that opened it.\n const cooldown = deps.loadCooldown();\n if (activeCooldown(cooldown, now)) {\n const until =\n cooldown?.until === null\n ? 'indefinitely'\n : `until ${new Date(cooldown?.until ?? 0).toISOString()}`;\n return {\n ok: false,\n code: 'COOLDOWN_ACTIVE',\n message: `refusing to call LinkedIn: ${cooldown?.reason} cooldown is active ${until}`,\n hint:\n cooldown?.clearRequires === 'human'\n ? 'Log in through a real browser, clear the challenge, then `lnrelay budget --reset-cooldown --confirm`.'\n : 'Wait for it to lift, or inspect `lnrelay risk`.',\n };\n }\n\n // 2. Account for the call BEFORE making it. A denied call spends nothing.\n const ledger = deps.loadLedger();\n const result = spend(ledger, spec.spendClass, now);\n if ('error' in result) {\n return {\n ok: false,\n code: result.error.code,\n message: result.error.message,\n hint: result.error.hint,\n };\n }\n deps.saveLedger(result.ledger);\n\n // 3. Pace. Reads are paced as conservatively as writes, because the field\n // evidence shows restrictions triggered by read velocity alone.\n // That wait is 3-15s and silence during it reads as a hang, so say so.\n const gap = MIN_GAP_MS + Math.floor(deps.random() * (MAX_GAP_MS - MIN_GAP_MS));\n deps.progress?.(`${spec.operation}: pacing ${Math.round(gap / 1000)}s before the request…`);\n await deps.sleep(gap);\n deps.progress?.(`${spec.operation}: requesting…`);\n\n // 4-5. Fetch, then classify before anyone parses anything.\n const raw = await fetchRaw(spec, session, deps);\n if (raw === null) {\n return { ok: false, code: 'FETCH_FAILED', message: 'the request could not be completed' };\n }\n // A read's body is a contract; a write's body is a receipt. Validating a\n // write response read-shaped is what made a successful reaction report\n // SCHEMA_DRIFT — and made the user retry a write that had already landed.\n //\n // Keyed on the METHOD, not on whether a body was sent: `delete` sends no\n // body and is still a write.\n const isRead = (spec.method ?? 'GET') === 'GET';\n const classification = classify(raw, { expectJson: isRead });\n\n // 6. A throttle, block or challenge opens the breaker for every process.\n if (classification.cooldown !== undefined) {\n deps.saveCooldown(openCooldown(classification.cooldown, deps.now()));\n }\n\n if (classification.outcome === 'error') {\n const out: ClientResult = {\n ok: false,\n code: classification.code ?? 'FETCH_FAILED',\n message: classification.message ?? 'request failed',\n };\n if (classification.hint !== undefined) out.hint = classification.hint;\n if (classification.retryAfterMs !== undefined) out.retryAfterMs = classification.retryAfterMs;\n return out;\n }\n\n return { ok: true, json: classification.json, classification };\n }\n\n return { request };\n}\n\nasync function fetchRaw(\n spec: RequestSpec,\n session: Session,\n deps: ClientDeps,\n): Promise<{ status: number; body: string; headers: Record<string, string> } | null> {\n // A body is added only when there is one, so the read path keeps sending\n // exactly the six headers that were verified against live traffic.\n const requestHeaders = buildHeaders(session);\n if (spec.body !== undefined) requestHeaders['content-type'] = 'application/json; charset=UTF-8';\n\n try {\n const res = await deps.fetch(spec.url, {\n method: spec.method ?? 'GET',\n headers: requestHeaders,\n ...(spec.body === undefined ? {} : { body: JSON.stringify(spec.body) }),\n // Manual, so a login or checkpoint redirect is classified rather than\n // silently followed into an HTML page that parses as \"no data\".\n redirect: 'manual',\n });\n const headers: Record<string, string> = {};\n res.headers.forEach((value, key) => {\n headers[key.toLowerCase()] = value;\n });\n return { status: res.status, body: await res.text(), headers };\n } catch {\n return null;\n }\n}\n\nexport type Client = ReturnType<typeof createClient>;\n","// ─── Operation contracts ──────────────────────────────────────────────────────\n//\n// Every endpoint we call, as DATA — never inline in request logic. queryIds and\n// decorationIds are pinned to LinkedIn's deployed web-client build and can\n// rotate; keeping them here means a rotation is a data edit, not a code hunt.\n//\n// Each contract carries its provenance and the date it was captured, and\n// `shippableContracts()` admits only `verified` ones. That rule is mechanical\n// rather than a convention someone has to remember:\n//\n// verified returned 200 on this machine, on the date recorded\n// discovered seen in live traffic (scripts/observe.ts) but never exercised\n// inferred from documentation or another client — may be archaeology\n//\n// The cost of getting this wrong is documented: `identity/profiles/{id}/\n// profileView` was the reference client's core profile endpoint, was documented\n// as working in November 2024, and returns 410 Gone today. It is kept below,\n// marked dead, so nobody re-adds it from an old blog post.\n//\n// Refresh with: bun run scripts/observe.ts <path> (see docs/ENGINE-RESEARCH.md)\n\nimport type { OperationContract } from '../types.ts';\n\nconst VOYAGER = 'https://www.linkedin.com/voyager/api';\n\nexport const CONTRACTS: Record<string, OperationContract> = {\n me: {\n name: 'me',\n transport: 'voyager-restli',\n path: `${VOYAGER}/me`,\n provenance: 'verified',\n capturedAt: '2026-08-01',\n },\n\n // Three `voyagerIdentityDashProfiles` queryIds were observed on one page —\n // they are different PROJECTIONS of one operation, and picking the wrong one\n // gets you a 200 containing nothing useful:\n //\n // b5c27c04… identity only — entityUrn + versionTag. Looks like success.\n // e9b08094… the real profile: headline, geo, top position, education. ← this\n // da93c92b… 400s with (profileUrn:…); its variables shape is unknown.\n //\n // None of them returns firstName/lastName/publicIdentifier — LinkedIn splits\n // names into a projection we have not identified. Documented rather than\n // faked; the caller already knows who they asked for.\n profile: {\n name: 'profile',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerIdentityDashProfiles.e9b0809465a07db1f02e70a82d455e10',\n provenance: 'verified',\n capturedAt: '2026-08-01',\n },\n\n feed: {\n name: 'feed',\n transport: 'voyager-restli',\n path: `${VOYAGER}/feed/updatesV2`,\n provenance: 'verified',\n capturedAt: '2026-08-01',\n },\n\n // The November-2024 queryId, still returning 200 in August 2026 — roughly 21\n // months unchanged. Notable because kill criterion #3 assumed queryIds might\n // rotate weekly; on this evidence they are build-pinned but long-lived.\n search: {\n name: 'search',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerSearchDashClusters.b0928897b71bd00a5a7291755dcd64f0',\n provenance: 'verified',\n capturedAt: '2026-08-01',\n },\n\n reactions: {\n name: 'reactions',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerSocialDashReactions.41ebf31a9f4c4a84e35a49d5abc9010b',\n provenance: 'verified',\n capturedAt: '2026-08-02',\n },\n\n // Comments. The variables carry a COMPOSITE socialDetailUrn assembled from the\n // post's own urn, repeated, plus a highlightedReply placeholder:\n //\n // urn:li:fsd_socialDetail:(<postUrn>,<postUrn>,urn:li:highlightedReply:-)\n //\n // Two things were established by probing rather than assumed. Our codec's\n // percent-encoding of that urn's colons and parens is REQUIRED — the literal\n // form returns 400. And an `urn:li:activity:` post urn works directly, so\n // `post` does not need a feed lookup to find the ugcPost form first.\n comments: {\n name: 'comments',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerSocialDashComments.afec6d88d7810d45548797a8dac4fb87',\n provenance: 'verified',\n capturedAt: '2026-08-02',\n },\n\n // The member's own posts. Verified 200; returns an empty collection on an\n // account with no posts, which is a true empty rather than a failure.\n // Needs the `fsd_profile` namespace, NOT the `fs_miniProfile` urn `whoami`\n // returns — the legacy form answers 200 with an empty result rather than an\n // error. That was invisible until the account had a post to return, and is\n // why engine.myPosts canonicalises the urn before sending it.\n //\n // KNOWN INCOMPLETE (2026-08-13): with the namespace fixed this returns the\n // owner's posts, but a post created minutes earlier did not appear here, nor\n // in `feed`, over ~1.5 hours. Whether that is an indexing lag or a coverage\n // limit of this projection is UNRESOLVED — do not treat this endpoint as an\n // authoritative \"all my posts\" until it is settled.\n myPosts: {\n name: 'myPosts',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerFeedDashProfileUpdates.20c70fe0314184158516a7ec004c0408',\n provenance: 'verified',\n capturedAt: '2026-08-02',\n },\n\n // Discovered and returns 200, but the projection is useless: 39 KB containing\n // one `guideFetcher` wrapper and no name, tagline, description or headcount.\n // The same trap as the thin profile projection, so it stays unverified and\n // `company` does not ship. The richer path is probably\n // voyagerOrganizationDashViewWrapper with an organizationalPageUrn, which\n // first requires resolving that urn — unfinished work, not a dead end.\n company: {\n name: 'company',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerOrganizationDashCompanies.148b1aebfadd0a455f32806df656c3c1',\n provenance: 'discovered',\n capturedAt: '2026-08-02',\n },\n\n // A job CARDS list, not a job detail. Observed on /jobs/collections/recommended\n // and never exercised; `job` needs a detail endpoint we have not captured.\n jobCards: {\n name: 'jobCards',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerJobsDashJobCards.e5b6b761ede078dabe8ad857aa42c220',\n provenance: 'discovered',\n capturedAt: '2026-08-02',\n },\n};\n\n/**\n * Endpoints known to be DEAD. Listed so a future maintainer reading the\n * November-2024 reference client does not helpfully re-add one.\n */\nexport const RETIRED: Record<string, { path: string; diedBy: string; note: string }> = {\n profileView: {\n path: `${VOYAGER}/identity/profiles/{id}/profileView`,\n diedBy: '2026-08-01',\n note:\n 'Returns 410 Gone inside a well-formed Voyager envelope. Superseded by the `profile` ' +\n 'contract above. Every client that reads profiles through this is broken.',\n },\n};\n\n/** Only `verified` contracts may back a shipped command. */\nexport function shippableContracts(): Record<string, OperationContract> {\n return Object.fromEntries(\n Object.entries(CONTRACTS).filter(([, c]) => c.provenance === 'verified'),\n );\n}\n\nexport function contractFor(name: string): OperationContract | undefined {\n return shippableContracts()[name];\n}\n","// ─── Normalising Voyager's decoration model ───────────────────────────────────\n//\n// LinkedIn returns a graph with a side-table, not a nested document:\n//\n// { data: { \"*elements\": [\"urn:li:activity:100\", …] }, ← thin refs, ORDERED\n// included: [ { entityUrn: \"urn:li:activity:100\", $type: …, … }, … ] } ← unordered\n//\n// So: index `included[]` once into a Map, then walk `data`'s references against\n// it. The reference implementation instead does an O(n·m) substring scan across\n// the two, which is both slow and subtly wrong — we do not re-derive that.\n//\n// Three rules here are load-bearing, and each one exists because its absence\n// caused a real production bug in the sibling project:\n//\n// 1. FILTER BY EXCLUSION. Drop known noise; let everything else through. An\n// accept-list naming the types we know silently dropped every reply in\n// every thread on x-relay, and 34 of 77 posts per feed page — invisible\n// behind ok:true, a live cursor and a plausible count. On a live LinkedIn\n// feed, 39 of 44 included[] nodes are decorations rather than content, so\n// an accept-list here would look reasonable right up until a rename.\n//\n// 2. UNKNOWN IS NOT DROPPED, AND IT IS COUNTED. A $type we have never seen\n// arrives as data AND increments meta.unknownTypes, so drift shows up in\n// the very first response after a LinkedIn deploy rather than whenever\n// someone next thinks to count.\n//\n// 3. UNRESOLVABLE IS NOT ABSENT. A reference in `data` that `included[]`\n// does not contain is a FAILED decoration. It goes to meta.unresolved and\n// makes the result `partial` — never silently shorter.\n\nimport type { FetchState } from '../types.ts';\nimport { canonicalUrn } from './restli.ts';\n\nexport type Entity = Record<string, unknown> & { entityUrn?: string; $type?: unknown };\n\n/**\n * Type fragments that identify chrome rather than content. Matched as\n * case-insensitive substrings of `$type`, because LinkedIn versions its type\n * names (`UpdateV2` → `UpdateV3`) and a fragment survives that.\n *\n * This list is the ONLY thing that removes data. Adding to it is a deliberate\n * act; forgetting to add to it costs some noise in the output, which is the\n * cheap failure. Forgetting to add to an accept-list costs the entire result,\n * silently, which is the expensive one.\n */\nconst DROP_TYPE_FRAGMENTS = [\n 'promoted',\n 'sponsored',\n 'adunit',\n 'peopleyoumayknow',\n 'recommendedentity',\n 'discoveryentity',\n 'discoverymodule',\n 'promptcomponent',\n 'carouselcomponent',\n 'lego',\n // Search-result chrome, observed live alongside real results.\n 'feedbackcard',\n 'lazyloadedactions',\n 'bannercard',\n 'searchsuggestion',\n 'keywordssuggestion',\n 'queryclarification',\n 'knowledgecard',\n 'topicalquestion',\n];\n\n/** Types that are supporting decorations — real, but not the thing asked for. */\nconst DECORATION_FRAGMENTS = [\n 'socialdetail',\n 'socialactivitycounts',\n 'socialpermissions',\n 'saveaction',\n 'updateactions',\n 'hidepostaction',\n 'followinginfo',\n 'miniprofile',\n 'minicompany',\n 'videoplaymetadata',\n 'hidecommentaction',\n 'followingstate',\n 'followaction',\n 'connectaction',\n];\n\nfunction typeOf(node: Entity): string {\n const t = node.$type ?? (node as { _type?: unknown })._type;\n return typeof t === 'string' ? t : '';\n}\n\n/**\n * A promoted feed post carries the SAME `$type` as a real one — the ad marker\n * lives in the actor's subdescription (\"Promoted\", \"Promoted by <brand>\"), not\n * in the type. Found live: an ad reached the output while every type-level\n * filter passed, which is the same lesson as the accept-list in a new costume.\n * Type is not the only place a thing can identify itself.\n */\nfunction isPromotedPost(node: Entity): boolean {\n const actor = node.actor as { subDescription?: { text?: unknown } } | undefined;\n const sub = actor?.subDescription?.text;\n return typeof sub === 'string' && /^promoted\\b/i.test(sub.trim());\n}\n\nfunction isNoise(node: Entity): boolean {\n if (isPromotedPost(node)) return true;\n const t = typeOf(node).toLowerCase();\n if (t === '') return false;\n return DROP_TYPE_FRAGMENTS.some((f) => t.includes(f));\n}\n\nfunction isDecoration(node: Entity): boolean {\n const t = typeOf(node).toLowerCase();\n return DECORATION_FRAGMENTS.some((f) => t.includes(f));\n}\n\n/**\n * Whether we recognise this type as one we have actually seen. Used ONLY to\n * count unknowns for reporting — never to decide whether to keep something.\n */\nconst KNOWN_CONTENT = [\n 'updatev2',\n 'profile',\n 'jobposting',\n 'company',\n 'comment',\n 'reaction',\n 'entityresult',\n];\n\nfunction isKnown(node: Entity): boolean {\n const t = typeOf(node).toLowerCase();\n return KNOWN_CONTENT.some((f) => t.includes(f)) || isDecoration(node) || isNoise(node);\n}\n\n/** Build the `entityUrn → node` index in one pass, canonicalising namespaces. */\nexport function indexIncluded(included: unknown): Map<string, Entity> {\n const index = new Map<string, Entity>();\n if (!Array.isArray(included)) return index;\n\n for (const raw of included) {\n if (raw === null || typeof raw !== 'object') continue;\n const node = raw as Entity;\n const urn = node.entityUrn;\n if (typeof urn !== 'string') continue;\n\n // Store under BOTH the canonical and the literal form: references in `data`\n // may use either side of the fs_*/fsd_* migration.\n const canonical = canonicalUrn(urn);\n index.set(canonical, node);\n if (canonical !== urn) index.set(urn, node);\n }\n return index;\n}\n\nexport interface ResolveResult {\n resolved: Entity[];\n unresolved: string[];\n}\n\n/** Resolve an ordered list of URN references against the index. */\nexport function resolveRefs(refs: unknown, index: Map<string, Entity>): ResolveResult {\n const resolved: Entity[] = [];\n const unresolved: string[] = [];\n if (!Array.isArray(refs)) return { resolved, unresolved };\n\n for (const ref of refs) {\n if (typeof ref !== 'string') continue;\n const node = index.get(ref) ?? index.get(canonicalUrn(ref));\n if (node === undefined) unresolved.push(ref);\n else resolved.push(node);\n }\n return { resolved, unresolved };\n}\n\nexport interface ParseOpts {\n operation: string;\n /** What the platform claims exists, when it tells us. */\n claimedCount?: number;\n contractCapturedAt?: string;\n truncated?: boolean;\n}\n\nexport interface ParseMeta {\n state: FetchState;\n operation: string;\n contractCapturedAt: string;\n rawCandidateCount: number;\n parsedCount: number;\n excludedCount: number;\n unknownCount: number;\n returnedCount: number;\n claimedCount?: number;\n truncated: boolean;\n unresolved?: string[];\n unknownTypes?: { type: string; count: number }[];\n warnings: string[];\n}\n\nexport interface ParseResult {\n items: Entity[];\n meta: ParseMeta;\n}\n\n/**\n * Find the ordered reference list. Voyager marks references with a `*` prefix,\n * but arranges them in two quite different ways, and a parser that knows only\n * one returns an empty result for the other — with `ok:true`.\n *\n * Collection shape data[\"*elements\"] = [urn, urn, …]\n * feed, dashProfiles. One array, already in order.\n *\n * Cluster shape data.data.<op>.elements[].items[].item[\"*entityResult\"] = urn\n * search. One SINGLE string per item, nested three levels\n * down and spread across clusters.\n *\n * Both were captured live on 2026-08-01. Search parsed to zero items until this\n * handled the second shape — found only because the parser was run against a\n * real capture rather than its own fixtures.\n */\nfunction findRefs(data: unknown): unknown[] {\n if (data === null || typeof data !== 'object') return [];\n\n // Pass 1 — the shallowest `*`-prefixed ARRAY wins. Breadth-first, so a\n // top-level \"*elements\" is preferred over anything nested beneath it.\n const queue: unknown[] = [data];\n while (queue.length > 0) {\n const node = queue.shift();\n if (node === null || typeof node !== 'object') continue;\n if (Array.isArray(node)) {\n queue.push(...node);\n continue;\n }\n for (const [key, value] of Object.entries(node)) {\n if (key.startsWith('*') && Array.isArray(value)) return value;\n }\n for (const value of Object.values(node)) {\n if (value !== null && typeof value === 'object') queue.push(value);\n }\n }\n\n // Pass 2 — no reference array anywhere, so collect `*`-prefixed STRINGS in\n // document order. Depth-first and in-order, because the order items appear\n // in the response IS the ranking LinkedIn assigned them.\n const refs: string[] = [];\n const walk = (node: unknown): void => {\n if (node === null || typeof node !== 'object') return;\n if (Array.isArray(node)) {\n for (const item of node) walk(item);\n return;\n }\n for (const [key, value] of Object.entries(node)) {\n if (key.startsWith('*') && typeof value === 'string') refs.push(value);\n else walk(value);\n }\n };\n walk(data);\n return refs;\n}\n\n/**\n * A single-entity response (`/me`) carries no reference list at all — just one\n * decorated node in `included[]`. Returns undefined rather than throwing when\n * there is nothing, so callers decide what an absence means.\n */\nexport function parseSingle(payload: unknown): Entity | undefined {\n const envelope = (payload ?? {}) as { included?: unknown };\n const nodes = [...new Set(indexIncluded(envelope.included).values())];\n if (nodes.length === 0) return undefined;\n // Prefer a content node; fall back to the first, since a decoration is still\n // better than nothing when that is all the endpoint returns.\n return nodes.find((n) => !isNoise(n) && !isDecoration(n)) ?? nodes[0];\n}\n\nexport function parseCollection(payload: unknown, opts: ParseOpts): ParseResult {\n const envelope = (payload ?? {}) as { data?: unknown; included?: unknown };\n const index = indexIncluded(envelope.included);\n const refs = findRefs(envelope.data);\n const { resolved, unresolved } = resolveRefs(refs, index);\n\n const items: Entity[] = [];\n const unknownTypes = new Map<string, number>();\n let excludedCount = 0;\n let unknownCount = 0;\n\n for (const node of resolved) {\n // Per-item isolation: one malformed node never takes the page with it.\n try {\n if (isNoise(node) || isDecoration(node)) {\n excludedCount++;\n continue;\n }\n if (!isKnown(node)) {\n // Unknown → KEEP it (rule 2), and count it so the drift is visible.\n const t = typeOf(node);\n unknownTypes.set(t, (unknownTypes.get(t) ?? 0) + 1);\n unknownCount++;\n }\n items.push(node);\n } catch {\n excludedCount++;\n }\n }\n\n const warnings: string[] = [];\n if (unresolved.length > 0) {\n warnings.push(\n `${unresolved.length} referenced entities were not present in included[] — the decoration failed for those, so this record is incomplete rather than short.`,\n );\n }\n if (opts.claimedCount !== undefined && opts.claimedCount > 0 && items.length === 0) {\n warnings.push(\n `LinkedIn claims ${opts.claimedCount} items but returned none — treat this as a FAILED FETCH, not an empty result.`,\n );\n }\n\n const state: FetchState =\n unresolved.length > 0 ? 'partial' : opts.truncated === true ? 'unknown' : 'complete';\n\n const meta: ParseMeta = {\n state,\n operation: opts.operation,\n contractCapturedAt: opts.contractCapturedAt ?? 'unknown',\n // parsedCount counts what we kept; `items` includes the unknowns, which is\n // why unknownCount is reported separately rather than added again here.\n rawCandidateCount: resolved.length,\n parsedCount: items.length - unknownCount,\n excludedCount,\n unknownCount,\n returnedCount: items.length,\n truncated: opts.truncated ?? false,\n warnings,\n };\n if (opts.claimedCount !== undefined) meta.claimedCount = opts.claimedCount;\n if (unresolved.length > 0) meta.unresolved = unresolved;\n if (unknownTypes.size > 0) {\n meta.unknownTypes = [...unknownTypes.entries()].map(([type, count]) => ({ type, count }));\n }\n\n return { items, meta };\n}\n","// The Engine interface and its real construction. This is the seam: everything\n// above it is pure and testable, everything below it talks to LinkedIn.\n\nimport { cachePath, loadJson, saveJson } from '../cache/store.ts';\nimport { progressReporter } from '../progress.ts';\nimport type { Session } from './auth.ts';\nimport { type Cooldown, emptyLedger, type Ledger } from './budget.ts';\nimport { type Client, type ClientDeps, createClient } from './client.ts';\nimport { contractFor } from './contracts.ts';\nimport {\n type Entity,\n indexIncluded,\n type ParseResult,\n parseCollection,\n parseSingle,\n} from './parse.ts';\nimport { canonicalUrn, encodeVariables } from './restli.ts';\n\nexport interface Engine {\n whoami(): Promise<EngineResult<Entity | undefined>>;\n profile(memberId: string): Promise<EngineResult<ProfileResult | undefined>>;\n feed(limit: number): Promise<EngineResult<Collection>>;\n search(kind: SearchKind, query: string, limit: number): Promise<EngineResult<Collection>>;\n post(postUrn: string, limit: number): Promise<EngineResult<Collection>>;\n myPosts(profileUrn: string, limit: number): Promise<EngineResult<Collection>>;\n connections(limit: number): Promise<EngineResult<Collection>>;\n reactions(postUrn: string, limit: number): Promise<EngineResult<Collection>>;\n}\n\nexport type SearchKind = 'people' | 'companies' | 'jobs';\n\n/**\n * A profile plus the side-table it references. LinkedIn returns location,\n * current position and education as URN references into `included[]`, so the\n * caller needs the index to make sense of the profile node.\n */\n/** A parsed collection plus the side-table its entities reference. */\nexport interface Collection {\n parsed: ParseResult;\n index: Map<string, Entity>;\n}\n\nexport interface ProfileResult {\n profile: Entity;\n index: Map<string, Entity>;\n}\n\nexport type EngineResult<T> =\n | { ok: true; value: T }\n | { ok: false; code: string; message: string; hint?: string; retryAfterMs?: number };\n\nconst RESULT_TYPE: Record<SearchKind, string> = {\n people: 'PEOPLE',\n companies: 'COMPANIES',\n jobs: 'JOBS',\n};\n\nfunction missingContract(name: string): EngineResult<never> {\n return {\n ok: false,\n code: 'NOT_IMPLEMENTED',\n message: `no verified contract for '${name}'`,\n hint:\n 'Only endpoints that returned 200 on this machine may back a command. ' +\n 'Capture it with `bun run scripts/observe.ts`, verify it, then mark it verified in src/engine/contracts.ts.',\n };\n}\n\n/**\n * A live client on the real cache files. Exported because writes need a client\n * without needing an Engine — the write surface is not part of the read\n * contract, but it must share the same ledger, cooldown and pacing, and a\n * second construction of those would be a second breaker that agrees with the\n * first only by luck.\n */\nexport function createLiveClient(\n session: Session,\n deps?: Partial<ClientDeps>,\n quiet = false,\n): Client {\n return createClient(session, {\n fetch: globalThis.fetch,\n // stdout stays JSON-only; progress is human chatter and goes to stderr.\n progress: progressReporter(quiet),\n now: () => Date.now(),\n sleep: (ms) => new Promise((r) => setTimeout(r, ms)),\n random: () => Math.random(),\n loadLedger: () => {\n const r = loadJson<Ledger>(cachePath('budget.json'));\n return r.state === 'ok' ? r.value : emptyLedger();\n },\n saveLedger: (l) => saveJson(cachePath('budget.json'), l),\n loadCooldown: () => {\n const r = loadJson<Cooldown | null>(cachePath('cooldown.json'));\n return r.state === 'ok' ? r.value : null;\n },\n saveCooldown: (c) => saveJson(cachePath('cooldown.json'), c),\n ...deps,\n });\n}\n\nexport function createEngine(session: Session, deps?: Partial<ClientDeps>, quiet = false): Engine {\n const client: Client = createLiveClient(session, deps, quiet);\n\n return {\n async whoami() {\n const contract = contractFor('me');\n if (contract === undefined) return missingContract('me');\n\n const res = await client.request({\n url: contract.path,\n spendClass: 'profile',\n operation: 'me',\n });\n if (!res.ok) return res;\n return { ok: true, value: parseSingle(res.json) };\n },\n\n async profile(memberId) {\n const contract = contractFor('profile');\n if (contract === undefined) return missingContract('profile');\n\n const variables = encodeVariables({ memberIdentity: memberId });\n const url = `${contract.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract.queryId}`;\n const res = await client.request({ url, spendClass: 'profile', operation: 'profile' });\n if (!res.ok) return res;\n\n const envelope = res.json as { included?: unknown };\n const index = indexIncluded(envelope.included);\n const profile = [...new Set(index.values())].find((n) =>\n String(n.$type ?? '').endsWith('profile.Profile'),\n );\n if (profile === undefined) return { ok: true, value: undefined };\n return { ok: true, value: { profile, index } };\n },\n\n async feed(limit) {\n const contract = contractFor('feed');\n if (contract === undefined) return missingContract('feed');\n\n const url = `${contract.path}?q=chronFeed&count=${limit}&start=0`;\n const res = await client.request({ url, spendClass: 'page', operation: 'feed' });\n if (!res.ok) return res;\n const envelope = res.json as { included?: unknown };\n return {\n ok: true,\n value: {\n parsed: parseCollection(res.json, {\n operation: 'feed',\n contractCapturedAt: contract.capturedAt,\n }),\n index: indexIncluded(envelope.included),\n },\n };\n },\n\n async myPosts(profileUrn, limit) {\n const contract = contractFor('myPosts');\n if (contract === undefined) return missingContract('myPosts');\n\n // `whoami` answers with an `fs_miniProfile` urn; this is a DASH endpoint\n // and wants `fsd_profile`. The legacy form returns 200 with an empty\n // result — no error, no warning — which is why this shipped as\n // \"verified\": the account had no posts when the contract was captured,\n // so empty was indistinguishable from working.\n const variables = encodeVariables({\n count: Math.min(limit, 100),\n start: 0,\n profileUrn: canonicalUrn(profileUrn),\n });\n const url = `${contract.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract.queryId}`;\n const res = await client.request({ url, spendClass: 'page', operation: 'myPosts' });\n if (!res.ok) return res;\n\n const envelope = res.json as { included?: unknown };\n return {\n ok: true,\n value: {\n parsed: parseCollection(res.json, {\n operation: 'myPosts',\n contractCapturedAt: contract.capturedAt,\n truncated: true,\n }),\n index: indexIncluded(envelope.included),\n },\n };\n },\n\n /**\n * Connections are a FILTERED PEOPLE SEARCH, not a list endpoint — LinkedIn\n * exposes no change stream for them. That is why the cache stores them as a\n * snapshot and diffs, rather than pretending a watermark exists.\n */\n async connections(limit) {\n const contract = contractFor('search');\n if (contract === undefined) return missingContract('search');\n\n const variables = encodeVariables({\n start: 0,\n origin: 'FACETED_SEARCH',\n query: {\n flagshipSearchIntent: 'SEARCH_SRP',\n queryParameters: [\n { key: 'resultType', value: ['PEOPLE'] },\n { key: 'network', value: ['F'] },\n ],\n includeFiltersInResponse: false,\n },\n });\n const url = `${contract.path}?variables=${variables}&queryId=${contract.queryId}`;\n const res = await client.request({ url, spendClass: 'search', operation: 'connections' });\n if (!res.ok) return res;\n\n const parsed = parseCollection(res.json, {\n operation: 'connections',\n contractCapturedAt: contract.capturedAt,\n claimedCount: totalResultCount(res.json),\n truncated: true,\n });\n parsed.items = parsed.items.slice(0, limit);\n parsed.meta.returnedCount = parsed.items.length;\n const envelope = res.json as { included?: unknown };\n return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };\n },\n\n async post(postUrn, limit) {\n const contract = contractFor('comments');\n if (contract === undefined) return missingContract('comments');\n\n const variables = encodeVariables({\n count: Math.min(limit, 100),\n numReplies: 1,\n socialDetailUrn: socialDetailUrn(postUrn),\n sortOrder: 'RELEVANCE',\n start: 0,\n });\n const url = `${contract.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract.queryId}`;\n const res = await client.request({ url, spendClass: 'page', operation: 'comments' });\n if (!res.ok) return res;\n\n const parsed = parseCollection(res.json, {\n operation: 'comments',\n contractCapturedAt: contract.capturedAt,\n // A page of many; we follow no cursor yet, so never claim exhaustion.\n truncated: true,\n });\n const envelope = res.json as { included?: unknown };\n return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };\n },\n\n async reactions(postUrn, limit) {\n const contract = contractFor('reactions');\n if (contract === undefined) return missingContract('reactions');\n\n const variables = encodeVariables({\n count: Math.min(limit, 100),\n start: 0,\n threadUrn: postUrn,\n });\n const url = `${contract.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract.queryId}`;\n const res = await client.request({ url, spendClass: 'page', operation: 'reactions' });\n if (!res.ok) return res;\n\n const parsed = parseCollection(res.json, {\n operation: 'reactions',\n contractCapturedAt: contract.capturedAt,\n truncated: true,\n });\n const envelope = res.json as { included?: unknown };\n return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };\n },\n\n async search(kind, query, limit) {\n const contract = contractFor('search');\n if (contract === undefined) return missingContract('search');\n\n const variables = encodeVariables({\n start: 0,\n origin: 'GLOBAL_SEARCH_HEADER',\n query: {\n keywords: query,\n flagshipSearchIntent: 'SEARCH_SRP',\n queryParameters: [{ key: 'resultType', value: [RESULT_TYPE[kind]] }],\n includeFiltersInResponse: false,\n },\n });\n const url = `${contract.path}?variables=${variables}&queryId=${contract.queryId}`;\n const res = await client.request({ url, spendClass: 'search', operation: 'search' });\n if (!res.ok) return res;\n\n const parsed = parseCollection(res.json, {\n operation: 'search',\n contractCapturedAt: contract.capturedAt,\n claimedCount: totalResultCount(res.json),\n truncated: true, // one page of many; we never claim exhaustion\n });\n parsed.items = parsed.items.slice(0, limit);\n parsed.meta.returnedCount = parsed.items.length;\n const envelope = res.json as { included?: unknown };\n return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };\n },\n };\n}\n\n/**\n * The composite urn the comments endpoint keys off: the post's own urn,\n * repeated, plus a highlightedReply placeholder. Assembled rather than fetched\n * — verified working with an `urn:li:activity:` urn, so `post` needs no prior\n * lookup to find the ugcPost form.\n */\nfunction socialDetailUrn(postUrn: string): string {\n return `urn:li:fsd_socialDetail:(${postUrn},${postUrn},urn:li:highlightedReply:-)`;\n}\n\n/** LinkedIn's own claimed total, used to detect a claimed-but-empty fetch. */\nfunction totalResultCount(json: unknown): number | undefined {\n const found = JSON.stringify(json ?? {}).match(/\"totalResultCount\":(\\d+)/);\n return found?.[1] === undefined ? undefined : Number(found[1]);\n}\n","// ─── Harvesting the tokens a comment needs ────────────────────────────────────\n//\n// Commenting needs two things that a reaction does not: a `trackingId` from the\n// feed render, and an opaque `commentBoxStateId` binding key. Both live in the\n// rendered post page, and that page is a PLAIN AUTHENTICATED GET — no browser,\n// no CDP. See docs/research/W5 for the capture this is built from.\n//\n// Scraping a rendered page is the most drift-prone thing in this codebase, so\n// the design leans on one lucky property: the binding key CONTAINS the post id.\n//\n// commentBoxText-<base64(post id)><31 opaque bytes><FeedType_…>\n//\n// The first segment is the activity id, zigzag-encoded as a protobuf sint64.\n// That means a harvested key can be PROVEN to belong to the post we intend to\n// comment on, rather than trusted because of where it was found. A feed page\n// carries comment boxes for many posts; picking the wrong one would post a\n// comment on a stranger's update under the owner's name. The id check makes\n// that structurally impossible instead of merely unlikely.\n\n/** Zigzag encoding: what protobuf uses for signed ints. Positive n -> 2n. */\nfunction zigzag(n: bigint): bigint {\n return (n << 1n) ^ (n >> 63n);\n}\n\nfunction varint(n: bigint): number[] {\n const out: number[] = [];\n let v = n;\n while (v > 0x7fn) {\n out.push(Number((v & 0x7fn) | 0x80n));\n v >>= 7n;\n }\n out.push(Number(v));\n return out;\n}\n\n/**\n * The derivable first segment of a comment-box binding key.\n *\n * BigInt throughout: activity ids exceed Number.MAX_SAFE_INTEGER, and doing\n * this in a JS number rounds silently — encoding a segment for a post that\n * does not exist.\n */\nexport function activityIdSegment(activityId: string): string {\n if (!/^\\d+$/.test(activityId)) {\n throw new Error(`'${activityId}' is not a numeric activity id`);\n }\n const inner = [0x08, ...varint(zigzag(BigInt(activityId)))];\n const message = Uint8Array.from([0x0a, inner.length, ...inner]);\n // UNPADDED. The key format is `commentBoxText-<A>-<B><FeedType_…>`, where the\n // '-' after segment A is a SEPARATOR, not padding. One capture made these\n // indistinguishable — its segment B began with '-', so an 18-char segment\n // plus a separator read exactly like a 20-char padded one. A unit test built\n // on that single sample passed against a wrong encoder; only a second post\n // exposed it.\n return btoa(String.fromCharCode(...message)).replace(/=+$/, '');\n}\n\n/** Whether a harvested key really belongs to this post. */\nexport function keyMatchesPost(bindingKey: string, activityId: string): boolean {\n try {\n return bindingKey.startsWith(`commentBoxText-${activityIdSegment(activityId)}-`);\n } catch {\n return false;\n }\n}\n\nexport type HarvestResult =\n | { ok: true; bindingKey: string; trackingId: string }\n | { ok: false; message: string; hint?: string };\n\n/** Markers that mean we were served something other than the post. */\nconst NOT_THE_POST = /checkpoint\\/challenge|\\/uas\\/login|authwall|\"status\"\\s*:\\s*999/i;\n\n/**\n * How close a trackingId must sit to a mention of the post id to be ITS id.\n *\n * Measured, not guessed: on a real permalink the update's own trackingId was 24\n * characters from an activity-id mention, while the next nearest candidate was\n * 13,613 away. The page also carries a page-level trackingId beside `treeId`\n * and `pageForestId` that has nothing to do with the post — taking the first\n * match in document order picks exactly that wrong one.\n */\nconst TRACKING_PROXIMITY = 400;\n\n/** A trackingId whose position proves it belongs to this update. */\nfunction updateTrackingId(html: string, activityId: string): string | null {\n const idAt = [...html.matchAll(new RegExp(activityId, 'g'))].map((m) => m.index ?? 0);\n if (idAt.length === 0) return null;\n\n // Quotes arrive HTML-escaped inside the embedded payloads.\n const pattern = /trackingId(?:"|\\\\?\")+\\s*:\\s*(?:"|\\\\?\")+([A-Za-z0-9+/=]{16,32})/g;\n let best: { value: string; distance: number } | null = null;\n for (const m of html.matchAll(pattern)) {\n const at = m.index ?? 0;\n const distance = Math.min(...idAt.map((p) => Math.abs(p - at)));\n if (best === null || distance < best.distance) best = { value: m[1] as string, distance };\n }\n return best !== null && best.distance <= TRACKING_PROXIMITY ? best.value : null;\n}\n\n/**\n * Pull the two tokens out of a rendered post page.\n *\n * Every failure here is loud. A comment built on a stale, empty or foreign\n * binding is the failure mode this whole module exists to prevent, and an\n * absent token must never reach the payload as `undefined`.\n */\nexport function extractCommentTokens(html: string, activityId: string): HarvestResult {\n if (NOT_THE_POST.test(html)) {\n return {\n ok: false,\n message: 'the page returned was a challenge or sign-in wall, not the post',\n hint: 'Re-mint the session with `lnrelay login`, then check `lnrelay risk`.',\n };\n }\n\n // Only keys carrying THIS post's id are candidates. A feed page contains\n // comment boxes for many posts.\n let expected: string;\n try {\n expected = activityIdSegment(activityId);\n } catch (e) {\n return { ok: false, message: (e as Error).message };\n }\n\n const keyPattern = new RegExp(\n `commentBoxText-${expected.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}-[A-Za-z0-9+/_=-]*FeedType_[A-Z_]+`,\n );\n const key = keyPattern.exec(html)?.[0];\n if (key === undefined) {\n return {\n ok: false,\n message: `no comment-box binding key for post ${activityId} was found in the page`,\n hint:\n 'Either the post does not accept comments, or LinkedIn changed the rendered shape. ' +\n 'Re-capture with `bun run scripts/observe-write.ts` before changing this parser.',\n };\n }\n\n const trackingId = updateTrackingId(html, activityId);\n if (trackingId === null) {\n return {\n ok: false,\n message: `no trackingId adjacent to post ${activityId} was found in the page`,\n hint:\n 'The page carries several — one for the page itself, one per rendered update. Only the ' +\n \"update's own will do, and guessing would build a malformed comment.\",\n };\n }\n\n return { ok: true, bindingKey: key, trackingId };\n}\n","// ─── Asking the server what it can do ─────────────────────────────────────────\n//\n// SDUI is server-DRIVEN: the server ships the UI description, and that\n// description contains each action's id and its fully-populated arguments. So\n// the comment \"…\" menu is not just a menu — it is a contract listing, and\n// requesting it tells us how to delete or edit a comment without capturing a\n// single browser request.\n//\n// That matters beyond convenience. Every other write in this tool was learned\n// by observing traffic and is therefore a snapshot: correct until LinkedIn\n// changes it, and silently wrong after. An action replayed from the menu the\n// server just sent is correct BY CONSTRUCTION — if the shape changes, the menu\n// changes with it, and we follow.\n//\n// The payloads are taken verbatim rather than rebuilt from a hardcoded shape.\n// The one thing we substitute is the comment text on an edit, which is the only\n// part that is ours to decide.\n\nimport type { Client } from './client.ts';\n\nconst SDUI_ACTION = 'https://www.linkedin.com/flagship-web/rsc-action/actions/server-request';\n\nconst MENU_OP = 'com.linkedin.sdui.requests.comments.commentControlMenuRequest';\nconst SCREEN_ID = 'com.linkedin.sdui.flagshipnav.feed.UpdateDetail';\n\nexport const DELETE_OP = 'com.linkedin.sdui.comments.deleteComment';\nexport const UPDATE_OP = 'com.linkedin.sdui.comments.updateComment';\n\nexport function actionUrl(operation: string): string {\n return `${SDUI_ACTION}?sduiid=${operation}`;\n}\n\n/** Wrap arguments in the envelope every SDUI action call uses. */\nexport function sduiEnvelope(operation: string, payload: unknown, states: unknown[] = []) {\n const args = {\n $type: 'proto.sdui.actions.requests.RequestedArguments',\n requestedStateKeys: [],\n payload,\n requestMetadata: { $type: 'proto.sdui.common.RequestMetadata' },\n };\n return {\n requestId: operation,\n serverRequest: {\n requestId: operation,\n requestedArguments: args,\n isApfcEnabled: false,\n isStreaming: false,\n rumPageKey: '',\n },\n states,\n requestedArguments: { ...args, states, screenId: SCREEN_ID, knownTemplateIds: [] },\n };\n}\n\nexport function menuBody(ref: CommentRef, trackingId: string) {\n const { activityId, commentId, threadType } = ref;\n const activityUrn = { activityUrn: { activityId } };\n return sduiEnvelope(MENU_OP, {\n // Rebuilt in the namespace it came from. A comment threaded to a ugcPost\n // given an `urn:li:activity:` thread names a different entity, and that\n // does not error — it acts on the wrong thing or finds nothing.\n commentUrn: { commentId, thread: `urn:li:${threadType}:${activityId}` },\n updateKey: {\n feedType: 3,\n items: [{ feedUpdateUrn: { updateUrnActivityUrn: activityUrn }, trackingId }],\n aggregationType: 0,\n isVideoCarousel: false,\n },\n menuContentRef: `auto-component-${crypto.randomUUID()}`,\n });\n}\n\n/**\n * Pull one action's payload out of a menu response.\n *\n * The response is a React Server Components stream, not JSON, so the payload is\n * located by scanning for the operation id and then reading the balanced JSON\n * object that follows its `\"payload\":` key. Brace-matching rather than a regex,\n * because these payloads nest several levels deep and a greedy match would\n * swallow half the stream.\n */\nexport function extractActionPayload(stream: string, operation: string): unknown | null {\n const at = stream.indexOf(operation);\n if (at === -1) return null;\n\n const key = stream.indexOf('\"payload\":', at);\n if (key === -1) return null;\n\n const start = stream.indexOf('{', key);\n if (start === -1) return null;\n\n let depth = 0;\n let inString = false;\n let escaped = false;\n for (let i = start; i < stream.length; i++) {\n const ch = stream[i] as string;\n if (escaped) {\n escaped = false;\n } else if (ch === '\\\\') {\n escaped = true;\n } else if (ch === '\"') {\n inString = !inString;\n } else if (!inString && ch === '{') {\n depth++;\n } else if (!inString && ch === '}') {\n depth--;\n if (depth === 0) {\n try {\n return JSON.parse(stream.slice(start, i + 1)) as unknown;\n } catch {\n return null;\n }\n }\n }\n }\n return null;\n}\n\nexport type MenuResult =\n | { ok: true; stream: string }\n | { ok: false; code: string; message: string; hint?: string };\n\n/** Fetch the comment's action menu. A read, though it is issued as a POST. */\nexport async function fetchCommentMenu(\n ref: CommentRef,\n trackingId: string,\n client: Client,\n): Promise<MenuResult> {\n const result = await client.request({\n url: actionUrl(MENU_OP),\n method: 'POST',\n body: menuBody(ref, trackingId),\n spendClass: 'page',\n operation: 'commentMenu',\n });\n\n if (!result.ok) {\n const out: MenuResult = { ok: false, code: result.code, message: result.message };\n if (result.hint !== undefined) out.hint = result.hint;\n return out;\n }\n // The stream is not JSON; the client hands back the raw text as `json: null`\n // with the body preserved on the classification.\n const stream = (result.classification as { raw?: string }).raw ?? '';\n return { ok: true, stream };\n}\n\nexport interface CommentRef {\n /** The numeric id of the thread this comment hangs off. */\n activityId: string;\n commentId: string;\n /**\n * Which namespace the thread was written in.\n *\n * NOT always `activity`. A comment in the feed came back threaded to a\n * `ugcPost`, and ENGINE-RESEARCH §5b already records that the two are\n * distinct and not derivable from one another — so the namespace is carried\n * rather than assumed, and callers that must rebuild a urn use this.\n */\n threadType: 'activity' | 'ugcPost';\n}\n\nexport type ActionResult =\n | { ok: true; operation: string }\n | { ok: false; code: string; message: string; hint?: string };\n\n/**\n * The state id of a REPLY box: the parent comment's urn.\n *\n * A reply is `createComment` with its bindings keyed to the parent comment\n * instead of to the post's opaque key — discovered by rendering the reply box's\n * submit button and reading the action it declared. The payload has NO parent\n * field; the binding is the parent reference. Send the post's key by mistake\n * and you publish a top-level comment on someone's thread instead of a reply,\n * with nothing erroring.\n */\nexport function boxStateId(parent: CommentRef): string {\n return `urn:li:comment:(urn:li:${parent.threadType}:${parent.activityId},${parent.commentId})`;\n}\n\n/**\n * Build the two text states from whichever names the server used for the\n * bindings. A reply payload calls them commentFieldBinding /\n * richCommentFieldBinding; an edit payload calls them commentary /\n * richTextCommentary. Returns [] when neither is present, so callers refuse\n * rather than sending a half-populated state that posts blank text.\n */\nexport function textStates(payload: Record<string, unknown>, text: string): unknown[] {\n const keyOf = (...names: string[]): string | null => {\n for (const n of names) {\n const slot = payload[n] as { key?: unknown } | undefined;\n if (typeof slot?.key === 'string') return slot.key;\n }\n return null;\n };\n const plain = keyOf('commentary', 'commentFieldBinding');\n const rich = keyOf('richTextCommentary', 'richCommentFieldBinding');\n if (plain === null || rich === null) return [];\n\n const entry = (key: string, value: unknown, protoCase: string) => ({\n key,\n namespace: 'MemoryNamespace',\n value,\n originalProtoCase: protoCase,\n protoKey: { $type: 'proto.sdui.Key', value: { $case: 'id', id: key } },\n });\n return [\n entry(plain, text, 'stringValue'),\n entry(rich, { text, attribute: [], $type: 'TextModel', source: 'local' }, 'textModelForWrite'),\n ];\n}\n\n/**\n * States for an edit: the new text under the keys the SERVER named.\n *\n * The keys come out of the menu payload rather than being rebuilt, because the\n * server already told us what they are — and for an edit they turn out to be\n * the plain comment urn, not the opaque binding a new comment needs.\n */\nfunction editStates(payload: Record<string, unknown>, text: string): unknown[] {\n return textStates(payload, text);\n}\n\n/**\n * Run a delete or edit on a comment, using the payload the SERVER just handed\n * us for that exact action.\n *\n * Nothing about the payload is reconstructed from a hardcoded shape. That is\n * the point: every other write here is a snapshot of traffic that was correct\n * when captured, while this one is correct by construction — if LinkedIn\n * changes the arguments, the menu changes with them and we follow.\n */\nexport async function runCommentAction(\n ref: CommentRef,\n operation: typeof DELETE_OP | typeof UPDATE_OP,\n trackingId: string,\n client: Client,\n newText?: string,\n): Promise<ActionResult> {\n const menu = await fetchCommentMenu(ref, trackingId, client);\n if (!menu.ok) return { ok: false, code: menu.code, message: menu.message };\n\n const payload = extractActionPayload(menu.stream, operation) as Record<string, unknown> | null;\n if (payload === null) {\n return {\n ok: false,\n code: 'NOT_IMPLEMENTED',\n message: `LinkedIn did not offer '${operation.split('.').pop()}' on this comment`,\n hint:\n 'The menu lists only what the server permits — you may not own this comment, or the ' +\n 'action may not exist on this surface. Nothing was sent.',\n };\n }\n\n // Guard on the id the SERVER echoed, not the one we asked for. If they\n // disagree, we would be acting on someone else's comment.\n const echoed = (payload.commentUrn as { commentId?: unknown } | undefined)?.commentId;\n if (echoed !== ref.commentId) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: `the menu described comment ${String(echoed)} but we asked about ${ref.commentId}`,\n hint: 'Refusing to send — this is how an action lands on the wrong comment.',\n };\n }\n\n const states =\n operation === UPDATE_OP && newText !== undefined ? editStates(payload, newText) : [];\n if (operation === UPDATE_OP && states.length === 0) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: 'the menu did not name the comment-text state keys, so an edit cannot be built',\n };\n }\n\n const result = await client.request({\n url: actionUrl(operation),\n method: 'POST',\n body: sduiEnvelope(operation, payload, states),\n spendClass: 'write',\n operation: operation.split('.').pop() ?? operation,\n });\n\n if (!result.ok) {\n const out: ActionResult = { ok: false, code: result.code, message: result.message };\n if (result.hint !== undefined) out.hint = result.hint;\n return out;\n }\n return { ok: true, operation };\n}\n\n/**\n * Parse any of the three live comment-urn forms into its two ids.\n *\n * They do not agree on member order. `post` returns the `fsd_comment` form with\n * the COMMENT id first; the other two put the activity first, one of them\n * without its `urn:li:` prefix. Both members are bare numbers, so reading them\n * positionally and getting it backwards is undetectable downstream — the action\n * simply lands on the wrong thing. Hence matching by shape, never by position.\n */\nexport function parseCommentUrn(urn: string): CommentRef | null {\n const fsd = /^urn:li:fsd_comment:\\((\\d+),urn:li:(activity|ugcPost):(\\d+)\\)$/.exec(urn);\n if (fsd !== null) {\n return {\n commentId: fsd[1] as string,\n threadType: fsd[2] as 'activity' | 'ugcPost',\n activityId: fsd[3] as string,\n };\n }\n\n const plain = /^urn:li:comment:\\((?:urn:li:)?(activity|ugcPost):(\\d+),(\\d+)\\)$/.exec(urn);\n if (plain !== null) {\n return {\n threadType: plain[1] as 'activity' | 'ugcPost',\n activityId: plain[2] as string,\n commentId: plain[3] as string,\n };\n }\n\n return null;\n}\n\nconst SUBMIT_COMPONENT = 'com.linkedin.sdui.generated.comments.dsl.impl.submitCommentButton';\nconst CREATE_OP = 'com.linkedin.sdui.comments.createComment';\n\nconst COMPONENT_URL = 'https://www.linkedin.com/flagship-web/rsc-action/actions/component';\n\n/**\n * Ask the server to render a reply box's submit button, and hand back the\n * `createComment` action it declares.\n *\n * This is the discovery step made into the implementation. Rather than\n * hardcoding a reply payload, we render the very component whose button would\n * send it and reuse what it says — so the parent binding, the collection and\n * every field come from LinkedIn, not from a shape captured on some past date.\n */\nexport async function fetchReplyAction(\n postActivityId: string,\n parent: CommentRef,\n trackingId: string,\n client: Client,\n): Promise<\n | { ok: true; payload: Record<string, unknown> }\n | { ok: false; code: string; message: string; hint?: string }\n> {\n const activityUrn = { activityUrn: { activityId: postActivityId } };\n const body = {\n clientArguments: {\n payload: {\n collection: {\n updateKey: {\n feedType: 3,\n items: [{ feedUpdateUrn: { updateUrnActivityUrn: activityUrn }, trackingId }],\n aggregationType: 0,\n isVideoCarousel: false,\n },\n threadUrn: { threadUrnActivityThreadUrn: activityUrn },\n },\n // Keying the box to the PARENT COMMENT is what makes this a reply.\n commentBoxStateId: boxStateId(parent),\n },\n states: [],\n requestMetadata: { $type: 'proto.sdui.common.RequestMetadata' },\n screenId: SCREEN_ID,\n knownTemplateIds: [],\n },\n };\n\n const result = await client.request({\n url: `${COMPONENT_URL}?componentId=${SUBMIT_COMPONENT}&sduiid=${SUBMIT_COMPONENT}`,\n method: 'POST',\n body,\n spendClass: 'page',\n operation: 'replyBox',\n });\n if (!result.ok) return { ok: false, code: result.code, message: result.message };\n\n const stream = (result.classification as { raw?: string }).raw ?? '';\n const payload = extractActionPayload(stream, CREATE_OP) as Record<string, unknown> | null;\n if (payload === null) {\n return {\n ok: false,\n code: 'NOT_IMPLEMENTED',\n message: 'the reply box did not declare a createComment action',\n hint: 'Replies may be closed on this post, or the component shape changed. Nothing was sent.',\n };\n }\n\n // The binding must name the parent we asked about. If it names the post\n // instead, sending this would publish a TOP-LEVEL comment on someone's\n // thread rather than a reply — the exact failure this check exists for.\n const bound = (payload.commentFieldBinding as { key?: unknown } | undefined)?.key;\n if (typeof bound !== 'string' || !bound.includes(boxStateId(parent))) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: 'the reply box came back bound to something other than the parent comment',\n hint: 'Refusing to send — this is how a reply becomes a top-level comment.',\n };\n }\n\n return { ok: true, payload };\n}\n\n/** Post a reply to a comment. The payload comes from the server, not from us. */\nexport async function replyToComment(\n postActivityId: string,\n parent: CommentRef,\n text: string,\n trackingId: string,\n client: Client,\n): Promise<ActionResult> {\n const action = await fetchReplyAction(postActivityId, parent, trackingId, client);\n if (!action.ok) {\n const out: ActionResult = { ok: false, code: action.code, message: action.message };\n if (action.hint !== undefined) out.hint = action.hint;\n return out;\n }\n\n const states = textStates(action.payload, text);\n if (states.length === 0) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: 'the reply box did not name its text bindings, so a reply cannot be built',\n };\n }\n\n const result = await client.request({\n url: actionUrl(CREATE_OP),\n method: 'POST',\n body: sduiEnvelope(CREATE_OP, action.payload, states),\n spendClass: 'write',\n operation: 'reply',\n });\n if (!result.ok) {\n const out: ActionResult = { ok: false, code: result.code, message: result.message };\n if (result.hint !== undefined) out.hint = result.hint;\n return out;\n }\n return { ok: true, operation: CREATE_OP };\n}\n","// Session persistence and the CDP bootstrap.\n//\n// Credentials live in a 0600 file under the cache dir. The design calls for OS\n// credential storage; that is a Phase 6 hardening step and is recorded as such\n// rather than silently skipped — for now the file is owner-only and the path is\n// gitignored.\n\nimport { cachePath, loadJson, saveJson } from '../cache/store.ts';\nimport type { Session } from './auth.ts';\n\nconst SESSION_FILE = 'session.json';\n\nexport type SessionLoad =\n | { state: 'ok'; session: Session }\n | { state: 'missing' }\n | { state: 'corrupt'; quarantinedTo: string };\n\nexport function loadSession(): SessionLoad {\n const result = loadJson<Session>(cachePath(SESSION_FILE));\n if (result.state === 'ok') return { state: 'ok', session: result.value };\n if (result.state === 'missing') return { state: 'missing' };\n return { state: 'corrupt', quarantinedTo: result.quarantinedTo };\n}\n\nexport function saveSession(session: Session): void {\n saveJson(cachePath(SESSION_FILE), session);\n}\n\n// ─── CDP bootstrap ────────────────────────────────────────────────────────────\n\nconst CDP = 'http://127.0.0.1:9222';\n\nexport const LAUNCH_HINT =\n 'Start Chrome with remote debugging first, DETACHED so it survives:\\n' +\n ' nohup /Applications/Google\\\\ Chrome.app/Contents/MacOS/Google\\\\ Chrome \\\\\\n' +\n ' --remote-debugging-port=9222 --user-data-dir=\"$HOME/.lnrelay/chrome\" \\\\\\n' +\n ' https://www.linkedin.com/feed/ >/dev/null 2>&1 & disown\\n' +\n 'Then log into LinkedIn in that window and visit /feed/ once.';\n\ninterface CdpCookie {\n name: string;\n value: string;\n domain: string;\n}\n\n/**\n * Mint a session from a logged-in Chrome over the DevTools protocol.\n *\n * Visiting `/feed/` matters: that navigation is specifically what sets\n * JSESSIONID. A jar with JSESSIONID but no li_at means the browser has been to\n * linkedin.com but nobody has logged in.\n */\nexport async function mintSessionFromBrowser(): Promise<\n { ok: true; session: Session } | { ok: false; message: string; hint?: string }\n> {\n let targets: { type: string; webSocketDebuggerUrl?: string }[];\n let userAgent: string;\n try {\n targets = (await (await fetch(`${CDP}/json/list`)).json()) as typeof targets;\n const version = (await (await fetch(`${CDP}/json/version`)).json()) as {\n 'User-Agent'?: string;\n };\n userAgent = (version['User-Agent'] ?? '').replace('HeadlessChrome', 'Chrome');\n } catch {\n return { ok: false, message: `no Chrome DevTools endpoint at ${CDP}`, hint: LAUNCH_HINT };\n }\n\n const page = targets.find((t) => t.type === 'page' && t.webSocketDebuggerUrl !== undefined);\n if (page?.webSocketDebuggerUrl === undefined) {\n return { ok: false, message: 'no debuggable Chrome page found', hint: LAUNCH_HINT };\n }\n if (userAgent === '') {\n return { ok: false, message: 'Chrome did not report a User-Agent' };\n }\n\n let cookies: CdpCookie[];\n try {\n cookies = await getAllCookies(page.webSocketDebuggerUrl);\n } catch (e) {\n return { ok: false, message: `CDP failed: ${(e as Error).message}`, hint: LAUNCH_HINT };\n }\n\n const linkedin = cookies.filter((c) => c.domain.includes('linkedin.com'));\n const liAt = linkedin.find((c) => c.name === 'li_at');\n const jsession = linkedin.find((c) => c.name === 'JSESSIONID');\n\n if (liAt === undefined) {\n return {\n ok: false,\n message: 'no li_at cookie — you are not logged in',\n hint: 'Log into linkedin.com in the debug Chrome window, then re-run. Note that JSESSIONID alone is set pre-login and does not mean a session exists.',\n };\n }\n if (jsession === undefined) {\n return {\n ok: false,\n message: 'no JSESSIONID cookie',\n hint: 'Visit https://www.linkedin.com/feed/ in the debug window — that navigation is what sets it.',\n };\n }\n\n return {\n ok: true,\n session: {\n liAt: liAt.value,\n jsessionId: jsession.value,\n userAgent,\n capturedAt: new Date().toISOString().slice(0, 10),\n },\n };\n}\n\nfunction getAllCookies(wsUrl: string): Promise<CdpCookie[]> {\n return new Promise((resolve, reject) => {\n const ws = new WebSocket(wsUrl);\n const timer = setTimeout(() => {\n ws.close();\n reject(new Error('timed out talking to Chrome'));\n }, 10_000);\n\n ws.onopen = () => ws.send(JSON.stringify({ id: 1, method: 'Network.getAllCookies' }));\n ws.onmessage = (ev) => {\n const msg = JSON.parse(String(ev.data)) as { id?: number; result?: { cookies: CdpCookie[] } };\n if (msg.id === 1 && msg.result !== undefined) {\n clearTimeout(timer);\n ws.close();\n resolve(msg.result.cookies);\n }\n };\n ws.onerror = () => {\n clearTimeout(timer);\n reject(new Error('websocket error'));\n };\n });\n}\n","// ─── The unsanctioned write transport ─────────────────────────────────────────\n//\n// Writing over Voyager, with the same two cookies the reads already use.\n//\n// This exists because the sanctioned path has a prerequisite not everyone can\n// meet: `w_member_social` needs a registered developer app, which needs an\n// associated LinkedIn *Page*. Someone with no company has no Page, and so no\n// legitimate way to post to their own feed from their own tools. That is a real\n// gap, not a hypothetical one.\n//\n// docs/DESIGN.md ratified OAuth as the sole write transport, with the rule:\n// \"if OAuth cannot perform an operation, omit the command — never fall back to\n// Voyager SILENTLY.\" This is the non-silent version of that fallback, and the\n// distinction is the whole design:\n//\n// - OAuth is still preferred whenever a token exists. This is the fallback,\n// not the default (see commands/write.ts).\n// - The confirmation prompt names the transport, so the human approving the\n// write knows which surface it goes over before they approve it.\n// - It is CLI-only and TTY-gated exactly like every other write.\n//\n// What this buys, honestly: nothing legal. LinkedIn's User Agreement §8.2 bans\n// automated posting regardless of how the bytes are produced, so this is not\n// \"safer\" than driving a browser — the research (docs/research/W4) found the\n// contract exposure identical and the technical-detection margin small and\n// uncertain in both directions. What it does buy is FAILURE MODE: a raw request\n// either returns a status we can read or it doesn't. A script driving the real\n// composer can post the wrong text, post twice, or report success on a UI that\n// never submitted — and a write is publicly visible under the owner's name.\n//\n// PROVENANCE OF THE PAYLOAD:\n//\n// share ✅ VERIFIED LIVE 2026-08-13. The body below, sent with the six\n// standard headers and the two cookies, created a real public post\n// on the owner's feed. LinkedIn answered **201 Created**. The shape\n// came from four converging OSS clients (docs/research/W1) and was\n// right first time.\n//\n// delete Not yet exercised. Best-evidenced operation in the research, but\n// still `repo` evidence.\n//\n// The 201 is worth recording for a second reason: the classifier accepted only\n// 200, because reads never return anything else, so that first successful post\n// was reported to the user as FETCH_FAILED — after it had already gone live.\n// Reporting a success as a failure is the worst direction to be wrong here: it\n// invites a re-run, and the re-run posts twice. See classify.ts.\n\nimport type { ConfirmedWrite } from '../commands/confirm.ts';\nimport type { Client } from './client.ts';\n\nconst VOYAGER = 'https://www.linkedin.com/voyager/api';\n\nexport const SHARE_URL = `${VOYAGER}/contentcreation/normShares`;\n\nexport type WriteResult =\n | { ok: true; id: string | null; note?: string }\n | { ok: false; code: string; message: string; hint?: string };\n\nexport interface SharePayload {\n visibleToConnectionsOnly: boolean;\n externalAudienceProviders: unknown[];\n commentaryV2: { text: string; attributes: unknown[] };\n origin: string;\n allowedCommentersScope: string;\n postState: string;\n media: unknown[];\n}\n\n/**\n * The create-post body.\n *\n * Note that visibility here is a BOOLEAN (`visibleToConnectionsOnly`), the\n * inverse of the OAuth API's `visibility: 'PUBLIC' | 'CONNECTIONS'` enum.\n * Inverting it by accident publishes a connections-only note to the open web,\n * which is why the mapping is pinned by test rather than inlined at the call.\n */\nexport function sharePayload(text: string, visibility: 'PUBLIC' | 'CONNECTIONS'): SharePayload {\n return {\n visibleToConnectionsOnly: visibility === 'CONNECTIONS',\n externalAudienceProviders: [],\n commentaryV2: { text, attributes: [] },\n origin: 'FEED',\n allowedCommentersScope: 'ALL',\n postState: 'PUBLISHED',\n media: [],\n };\n}\n\n/** Urn prefixes that identify a CREATED POST, as opposed to its author. */\nconst POST_URN = /urn:li:(share|activity|ugcPost):\\d+/;\n\n/**\n * Whether a urn identifies something this endpoint may be pointed at.\n *\n * Checked BEFORE encoding rather than after a failure, because the failure mode\n * of getting it wrong is not an error — a well-formed request naming the wrong\n * kind of entity is a request to destroy the wrong kind of thing, and we have\n * no evidence for what LinkedIn does with one.\n */\nexport function isDeletableUrn(urn: string): boolean {\n return new RegExp(`^${POST_URN.source}$`).test(urn);\n}\n\n/** The colons are path-hostile; the reference implementations all encode them. */\nexport function deleteUrl(urn: string): string {\n return `${SHARE_URL}/${encodeURIComponent(urn)}`;\n}\n\n/**\n * Delete one of the owner's own posts. Irreversible — the confirmation gate\n * upstream is what makes this safe, and it shows the post's text first.\n */\nexport async function deletePost(\n confirmed: ConfirmedWrite<{ urn: string }>,\n client: Client,\n): Promise<WriteResult> {\n const { urn } = confirmed.payload;\n\n const result = await client.request({\n url: deleteUrl(urn),\n method: 'DELETE',\n spendClass: 'write',\n operation: 'delete',\n });\n\n if (result.ok) return { ok: true, id: urn };\n\n // A 404 has two meanings that call for opposite actions, and we cannot tell\n // them apart from here. Saying both beats picking one and being wrong.\n const notFound = result.code === 'NOT_FOUND';\n const out: WriteResult = {\n ok: false,\n code: result.code,\n message: result.message,\n };\n if (notFound) {\n out.hint =\n 'Either the post is already gone — in which case nothing more is needed — or this is the ' +\n 'wrong urn namespace for this endpoint. It is documented against `urn:li:share:<id>`; if ' +\n 'you passed an activity or ugcPost urn, the same numeric id under `urn:li:share:` is the ' +\n 'thing to try next.';\n } else if (result.hint !== undefined) {\n out.hint = result.hint;\n }\n return out;\n}\n\n/**\n * Find the created post's urn anywhere in the response.\n *\n * We have never seen this response body, so this searches rather than reading a\n * known field, and returns null instead of guessing when nothing matches. A\n * null urn means \"posted, but we cannot tell you which post\" — which is a\n * different and honest answer, not a failure.\n */\nexport function extractShareUrn(json: unknown): string | null {\n return JSON.stringify(json ?? null).match(POST_URN)?.[0] ?? null;\n}\n\n/**\n * Post to the owner's own feed over Voyager.\n *\n * Takes a ConfirmedWrite, so this is unreachable without a human having typed\n * the confirmation token at a terminal — the same guarantee the OAuth transport\n * gives, enforced by the type rather than by a check anyone could forget.\n */\nexport async function share(\n confirmed: ConfirmedWrite<{ text: string; visibility: 'PUBLIC' | 'CONNECTIONS' }>,\n client: Client,\n): Promise<WriteResult> {\n const body = sharePayload(confirmed.payload.text, confirmed.payload.visibility);\n\n const result = await client.request({\n url: SHARE_URL,\n method: 'POST',\n body,\n spendClass: 'write',\n operation: 'share',\n });\n\n if (!result.ok) {\n const out: WriteResult = { ok: false, code: result.code, message: result.message };\n if (result.hint !== undefined) out.hint = result.hint;\n return out;\n }\n\n const id = extractShareUrn(result.json);\n return id === null\n ? {\n ok: true,\n id: null,\n note:\n 'LinkedIn accepted the post but the response carried no recognisable urn. Run ' +\n '`lnrelay sync my-posts && lnrelay my-posts` to confirm what actually landed — and ' +\n 'do NOT re-run this command on the assumption it failed, or you will post twice.',\n }\n : { ok: true, id };\n}\n","// ─── The gate every write passes through ──────────────────────────────────────\n//\n// Shared by every write command so there is exactly ONE place that decides a\n// human approved something. A second copy of this logic would be a second\n// policy, agreeing with the first only by luck and diverging on the first edit.\n//\n// The ordering is the safety design:\n//\n// 1. account for the spend BEFORE asking, so a refused budget never reaches\n// a prompt the user cannot act on\n// 2. ask, and require a token derived from the payload\n// 3. commit the spend only after approval — an aborted write costs nothing\n\nimport { createInterface } from 'node:readline/promises';\nimport { cachePath, loadJson, saveJson } from '../cache/store.ts';\nimport { emptyLedger, type Ledger, spend, summarise } from '../engine/budget.ts';\nimport { err } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport { type ConfirmDeps, confirmWrite, type WritePlan } from './confirm.ts';\n\nexport function ledger(): Ledger {\n const result = loadJson<Ledger>(cachePath('budget.json'));\n return result.state === 'ok' ? result.value : emptyLedger();\n}\n\nexport function budgetLine(now: number): string {\n const s = summarise(ledger(), 'write', now);\n return `${s.remaining} of ${s.cap} writes left today.`;\n}\n\n/** Real terminal I/O. Injected in tests so the gate is exercised without one. */\nexport function terminalDeps(): ConfirmDeps {\n return {\n isTty: process.stdin.isTTY === true && process.stdout.isTTY === true,\n prompt: async (question: string) => {\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n const answer = await rl.question(question);\n rl.close();\n return answer;\n },\n write: (s: string) => process.stderr.write(s),\n };\n}\n\n/**\n * Account for the comment harvest, which does not go through the client.\n *\n * Charged to `page` rather than `write`: it is a read, just an unusually heavy\n * one at ~2.8 MB. It gets a ledger entry so the traffic is visible in\n * `lnrelay budget` instead of being free and invisible.\n */\nexport function recordHarvestSpend(now: number): void {\n const attempt = spend(ledger(), 'page', now);\n if ('permit' in attempt) saveJson(cachePath('budget.json'), attempt.ledger);\n}\n\n/** Reserve the write against today's budget before a human is ever asked. */\nexport function reserve(command: string, now: number): Envelope | null {\n const attempt = spend(ledger(), 'write', now);\n return 'error' in attempt\n ? err(command, attempt.error.code, attempt.error.message, attempt.error.hint)\n : null;\n}\n\nexport type Gated<T> = { confirmed: unknown; payload: T } | Envelope;\n\nexport interface GateOpts {\n /**\n * Whether this gate is the thing that accounts for the write.\n *\n * client.ts is documented as \"the only place that spends budget\", and for\n * any transport that goes through it that is true — so the gate must only\n * ASK, never account, or the same write is billed twice. It was: every\n * Voyager and SDUI write cost two, and the prompt counted 6 → 4 → 2 across\n * three reactions until the daily cap locked the user out of their own tool.\n *\n * Defaults to true because the OAuth transport issues its own fetch and\n * never reaches the client, so there the gate is the only place that can.\n */\n commitSpend?: boolean;\n}\n\n/** Ask a human. Makes no network call either way. */\nexport async function gateWrite<T>(\n command: string,\n plan: WritePlan<T>,\n now: number,\n deps: ConfirmDeps,\n opts: GateOpts = {},\n): Promise<Gated<T>> {\n const outcome = await confirmWrite(plan, budgetLine(now), deps);\n if (!outcome.ok) return err(command, outcome.code, outcome.message, outcome.hint);\n // Only after approval is anything committed — an aborted write costs nothing.\n if (opts.commitSpend !== false) {\n const attempt = spend(ledger(), 'write', now);\n if ('permit' in attempt) saveJson(cachePath('budget.json'), attempt.ledger);\n }\n return { confirmed: outcome.confirmed, payload: plan.payload };\n}\n","// ─── The write gate ───────────────────────────────────────────────────────────\n//\n// `--confirm` is not a human confirmation. In this family the agent IS the\n// process invoking the CLI — Claude Code shells out — so a flag is written by\n// the acting party about its own action. It documents intent and obtains\n// consent from nobody.\n//\n// So a write stops and asks, at the moment of the write, having first shown\n// exactly what it will do and what it risks. The properties that make this a\n// real boundary:\n//\n// * No TTY, no write. Run non-interactively — which is how an agent invokes\n// the CLI — and it returns CONFIRMATION_REQUIRED having made ZERO network\n// calls. This is the load-bearing one.\n// * A short token derived from the payload, so `yes | lnrelay share …` fails.\n// * Only this module can mint a ConfirmedWrite, so the guarantee lives in the\n// type system rather than in a forgettable `if`.\n// * No --yes, no env var, no config setting.\n//\n// Stated honestly: a TTY check is an ACCIDENT-PREVENTION barrier, not proof of\n// human identity — an agent with terminal control can allocate a pty. Its real\n// value is moving circumvention from accidental (append a flag) to deliberate\n// (construct a pty and echo a payload-specific token). Overclaiming\n// unforgeability is how a guard stops being maintained.\n\nimport { createHash } from 'node:crypto';\n\n/** Proof a human saw and approved this exact payload. Unforgeable by construction. */\nexport interface ConfirmedWrite<T> {\n readonly __brand: unique symbol;\n action: string;\n payload: T;\n token: string;\n}\n\nexport interface WritePlan<T> {\n action: string;\n payload: T;\n /** Human-readable rendering of exactly what will happen. */\n summary: string[];\n /** Whether the action can be undone, and how. */\n reversibility: string;\n transport: 'oauth' | 'voyager';\n}\n\n/**\n * The token a human must type. Derived from the payload, so it changes if the\n * content changes — a token captured from one prompt cannot approve a different\n * write.\n */\nexport function confirmToken(action: string, payload: unknown): string {\n return createHash('sha256')\n .update(`${action}:${JSON.stringify(payload)}`)\n .digest('hex')\n .slice(0, 4);\n}\n\n/**\n * The risk sentence, which differs by transport because the truth differs.\n *\n * An OAuth write really is sanctioned — saying otherwise would be crying wolf,\n * and a warning shown identically on every action stops being read. A Voyager\n * write really does breach §8.2, and the person approving it should be told\n * that at the moment they approve it, not in a README they read once.\n *\n * This says nothing about CONSEQUENCE — whether the thing is public, who gets\n * notified, whether it can be undone. That varies by action, not by transport,\n * and each command states it in `reversibility`. Mixing them here produced a\n * delete prompt warning that the deletion was \"public under your name\".\n */\nfunction riskLines(transport: 'oauth' | 'voyager'): string[] {\n return transport === 'oauth'\n ? [\n \" This write itself is sanctioned — it uses LinkedIn's own\",\n ' w_member_social scope. The reads this tool performs are not.',\n ]\n : [\n ' This goes over the PRIVATE API, not a sanctioned one. It breaches',\n ' LinkedIn User Agreement §8.2 and can permanently restrict this account.',\n ];\n}\n\nexport function renderPlan<T>(plan: WritePlan<T>, budgetLine: string): string {\n const token = confirmToken(plan.action, plan.payload);\n const lines = [\n '',\n ` ABOUT TO ${plan.action.toUpperCase()} ON LINKEDIN`,\n ` ${'─'.repeat(58)}`,\n ...plan.summary.map((l) => ` ${l}`),\n ` via ${plan.transport === 'oauth' ? 'official OAuth (w_member_social)' : 'Voyager (private API)'}`,\n ` undo ${plan.reversibility}`,\n '',\n ...riskLines(plan.transport),\n ` ${budgetLine}`,\n '',\n ` Type ${token} to confirm, anything else to abort: `,\n ];\n return lines.join('\\n');\n}\n\nexport interface ConfirmDeps {\n isTty: boolean;\n prompt: (question: string) => Promise<string>;\n write: (s: string) => void;\n}\n\nexport type ConfirmOutcome<T> =\n | { ok: true; confirmed: ConfirmedWrite<T> }\n | { ok: false; code: 'CONFIRMATION_REQUIRED'; message: string; hint: string };\n\n/**\n * Ask a human. Returns a ConfirmedWrite only on an exact token match typed at an\n * interactive terminal. Makes no network call either way — the caller cannot\n * reach the write transport without the value this returns.\n */\nexport async function confirmWrite<T>(\n plan: WritePlan<T>,\n budgetLine: string,\n deps: ConfirmDeps,\n): Promise<ConfirmOutcome<T>> {\n if (!deps.isTty) {\n return {\n ok: false,\n code: 'CONFIRMATION_REQUIRED',\n message: `'${plan.action}' needs a human to confirm it at an interactive terminal`,\n hint:\n 'No terminal is attached, so nothing was sent and no network call was made. Run this ' +\n 'command yourself in a shell. There is deliberately no --yes flag: an agent that could ' +\n 'set one would not be confirming anything.',\n };\n }\n\n const token = confirmToken(plan.action, plan.payload);\n const answer = (await deps.prompt(renderPlan(plan, budgetLine))).trim();\n\n if (answer !== token) {\n return {\n ok: false,\n code: 'CONFIRMATION_REQUIRED',\n message: 'aborted — the confirmation token did not match',\n hint: 'Nothing was sent. Re-run and type the token shown in the prompt.',\n };\n }\n\n return {\n ok: true,\n confirmed: { action: plan.action, payload: plan.payload, token } as ConfirmedWrite<T>,\n };\n}\n","// ─── Deleting a post ──────────────────────────────────────────────────────────\n//\n// The only irreversible action in the tool. Everything else it does can be\n// undone: an unwanted post can be deleted, a reaction removed, a cached row\n// purged. A deleted post is gone, and no confirmation prompt can give it back.\n//\n// So this one does something the others do not: it READS THE POST FIRST and\n// shows the human the actual text they are about to destroy. A urn is not\n// something anyone can eyeball — `urn:li:activity:7489428563075637248` and\n// `urn:li:activity:7489428563075637249` are the same string to a tired person\n// at a terminal, and one of them is the wrong post.\n//\n// The lookup is `my-posts`, which is the right source for three reasons at\n// once: it proves the post exists, it proves the OWNER wrote it (it came from\n// their own posts), and it carries the text. A post that is not in there is not\n// necessarily someone else's — it may just be older than the page we fetched —\n// so that case is reported rather than refused, and the prompt says plainly\n// that it is proceeding blind.\n\nimport { CacheCorrupt, openDb, removeUrns } from '../cache/db.ts';\nimport { buildHeaders } from '../engine/auth.ts';\nimport { createEngine, createLiveClient } from '../engine/index.ts';\nimport { extractCommentTokens } from '../engine/sdui-harvest.ts';\nimport {\n type CommentRef,\n DELETE_OP,\n parseCommentUrn,\n runCommentAction,\n} from '../engine/sdui-menu.ts';\nimport { LAUNCH_HINT, loadSession } from '../engine/session.ts';\nimport { deletePost, isDeletableUrn } from '../engine/voyager-write.ts';\nimport { type Shaped, shapeAll } from '../format.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { ConfirmDeps, WritePlan } from './confirm.ts';\nimport { gateWrite, recordHarvestSpend, reserve, terminalDeps } from './gate.ts';\n\n/** How many of the owner's recent posts to search for the one being deleted. */\nconst LOOKUP_LIMIT = 50;\n\nconst PREVIEW_CHARS = 200;\n\n/** The numeric id shared by every namespace a single post appears under. */\nfunction postId(urn: string): string | undefined {\n return /:(\\d+)$/.exec(urn)?.[1];\n}\n\n/**\n * Find a post among the owner's own, matching across urn namespaces.\n *\n * The same post is `urn:li:activity:X` to the feed, `urn:li:ugcPost:X` to\n * reactions and `urn:li:share:X` to the create endpoint. Matching on the shared\n * numeric id means a urn from any read can be handed to delete.\n */\nexport function findOwnPost(posts: Shaped[], urn: string): Shaped | undefined {\n const id = postId(urn);\n if (id === undefined) return undefined;\n return posts.find((p) => typeof p.urn === 'string' && postId(p.urn) === id);\n}\n\n/** What the human is shown about the post before they approve destroying it. */\nexport function previewLines(post: Shaped | undefined): string[] {\n if (post === undefined) {\n return [\n 'content COULD NOT READ THIS POST.',\n ' It is not among your recent posts. That may only mean it is older',\n ' than the page fetched — but nothing here has verified what you are',\n ' about to delete, or that it is yours.',\n ];\n }\n const text = typeof post.text === 'string' ? post.text : '(no text — media-only post?)';\n const shown = text.length > PREVIEW_CHARS ? `${text.slice(0, PREVIEW_CHARS)}…` : text;\n return [`content \"${shown.replace(/\\n/g, ' ')}\"`];\n}\n\n/** Look the post up so the prompt can show it. A failed read is not fatal. */\nasync function lookup(urn: string, quiet: boolean): Promise<Shaped | undefined> {\n const session = loadSession();\n if (session.state !== 'ok') return undefined;\n const engine = createEngine(session.session, undefined, quiet);\n\n const me = await engine.whoami();\n if (!me.ok) return undefined;\n const profileUrn = typeof me.value?.entityUrn === 'string' ? me.value.entityUrn : undefined;\n if (profileUrn === undefined) return undefined;\n\n const posts = await engine.myPosts(profileUrn, LOOKUP_LIMIT);\n if (!posts.ok) return undefined;\n return findOwnPost(shapeAll(posts.value.parsed.items, posts.value.index), urn);\n}\n\n/**\n * The urn to drop from the local cache after a delete, or null.\n *\n * `sync my-posts` upserts and never evicts, so without this a deleted post\n * lingers and `my-posts` keeps listing something that no longer exists —\n * observed live, LinkedIn returning 1 post while the cache held 2.\n *\n * Only a SUCCESSFUL delete evicts. A failed one means the post is still there,\n * and dropping it from the cache would hide a post that still exists under the\n * owner's name — the opposite of the problem being fixed.\n */\nexport function evictionTarget(result: { ok: boolean; id?: string | null }): string | null {\n if (!result.ok) return null;\n return typeof result.id === 'string' && result.id !== '' ? result.id : null;\n}\n\n/** Drop the row locally. A cache failure must not report the delete as failed. */\nfunction evict(urn: string | null, now: number): boolean {\n if (urn === null) return false;\n try {\n return removeUrns(openDb(now), 'my-posts', [urn]) > 0;\n } catch (e) {\n if (e instanceof CacheCorrupt) return false;\n throw e;\n }\n}\n\n/**\n * Deleting a COMMENT is a different surface from deleting a post: SDUI rather\n * than Voyager, and the payload comes from the action menu the server offers on\n * that comment. That also means the menu is the permission check — a comment\n * you cannot delete simply has no delete action, so we never send one blindly.\n */\nasync function deleteComment(\n ref: CommentRef,\n urn: string,\n now: number,\n deps: ConfirmDeps,\n): Promise<Envelope> {\n if (!deps.isTty) {\n return err(\n 'delete',\n 'CONFIRMATION_REQUIRED',\n 'deleting needs a human to confirm it at an interactive terminal',\n 'No terminal is attached, so nothing was sent and no network call was made.',\n );\n }\n\n const session = loadSession();\n if (session.state !== 'ok') {\n return err('delete', 'AUTH_FAILED', 'no LinkedIn session', LAUNCH_HINT);\n }\n\n const refused = reserve('delete', now);\n if (refused !== null) return refused;\n\n const headers = buildHeaders(session.session);\n let html: string;\n try {\n const res = await fetch(\n `https://www.linkedin.com/feed/update/urn:li:activity:${ref.activityId}/`,\n {\n headers: {\n cookie: headers.cookie ?? '',\n 'user-agent': headers['user-agent'] ?? '',\n accept: 'text/html',\n },\n redirect: 'manual',\n },\n );\n if (res.status !== 200) {\n return err('delete', 'FETCH_FAILED', `the parent post page returned ${res.status}`);\n }\n html = await res.text();\n } catch (e) {\n return err('delete', 'FETCH_FAILED', `could not load the parent post: ${(e as Error).message}`);\n }\n recordHarvestSpend(now);\n\n const tokens = extractCommentTokens(html, ref.activityId);\n if (!tokens.ok) return err('delete', 'SCHEMA_DRIFT', tokens.message, tokens.hint);\n\n const plan: WritePlan<{ urn: string }> = {\n action: 'delete your comment',\n payload: { urn },\n summary: [`comment ${urn}`, `on post urn:li:activity:${ref.activityId}`],\n reversibility: 'NONE. A deleted comment is gone, with its replies and reactions.',\n transport: 'voyager',\n };\n\n const gated = await gateWrite('delete', plan, now, deps, { commitSpend: false });\n if ('ok' in gated) return gated;\n\n const result = await runCommentAction(\n ref,\n DELETE_OP,\n tokens.trackingId,\n createLiveClient(session.session),\n );\n return result.ok\n ? ok('delete', { deleted: urn, kind: 'comment' })\n : err('delete', result.code, result.message, result.hint);\n}\n\nexport async function runDelete(\n urn: string | undefined,\n now = Date.now(),\n deps?: ConfirmDeps,\n quiet = false,\n): Promise<Envelope> {\n if (urn === undefined || urn === '') {\n return err(\n 'delete',\n 'INVALID_INPUT',\n 'a post urn is required',\n 'lnrelay delete <urn:li:share:… | urn:li:activity:…>',\n );\n }\n // A comment urn routes to an entirely different surface.\n const asComment = parseCommentUrn(urn);\n if (asComment !== null) return deleteComment(asComment, urn, now, deps ?? terminalDeps());\n\n if (!isDeletableUrn(urn)) {\n return err(\n 'delete',\n 'INVALID_INPUT',\n `'${urn}' does not identify a post`,\n 'Expected a post urn (urn:li:share|activity|ugcPost:<id>) or a comment urn. Refusing before ' +\n 'encoding it, because a well-formed request naming the wrong kind of entity is a request ' +\n 'to destroy the wrong kind of thing.',\n );\n }\n\n const session = loadSession();\n if (session.state === 'corrupt') {\n return err('delete', 'CACHE_CORRUPT', 'the stored session was unreadable', LAUNCH_HINT);\n }\n if (session.state === 'missing') {\n // Deleting goes over Voyager only. LinkedIn's official API has a delete,\n // but this tool has not built or verified it, and an unverified destructive\n // call is the last place to start guessing.\n return err(\n 'delete',\n 'AUTH_FAILED',\n 'no LinkedIn session — deleting goes over the private API',\n `Run \\`lnrelay login\\`. ${LAUNCH_HINT}`,\n );\n }\n\n const refused = reserve('delete', now);\n if (refused !== null) return refused;\n\n // Read before destroying. This costs one read and is the entire point.\n const post = await lookup(urn, quiet);\n\n const plan: WritePlan<{ urn: string }> = {\n action: 'delete a post',\n payload: { urn },\n summary: [`post ${urn}`, ...previewLines(post)],\n reversibility: 'NONE. A deleted post is gone, with its comments and reactions.',\n transport: 'voyager',\n };\n\n // The client accounts for the DELETE itself.\n const gated = await gateWrite('delete', plan, now, deps ?? terminalDeps(), {\n commitSpend: false,\n });\n if ('ok' in gated) return gated;\n\n const result = await deletePost(gated.confirmed as never, createLiveClient(session.session));\n if (!result.ok) return err('delete', result.code, result.message, result.hint);\n\n // LinkedIn has it gone; drop our copy so `my-posts` stops listing it.\n const evicted = evict(evictionTarget(result), now);\n return ok('delete', { deleted: urn, verified: post !== undefined, evictedFromCache: evicted });\n}\n","// Runners for the commands that talk to LinkedIn. Thin: they resolve a\n// session, call the engine, and shape the envelope. All the interesting\n// behaviour lives in engine/.\n\nimport {\n type Collection,\n createEngine,\n type EngineResult,\n type SearchKind,\n} from '../engine/index.ts';\n\nimport {\n LAUNCH_HINT,\n loadSession,\n mintSessionFromBrowser,\n saveSession,\n} from '../engine/session.ts';\nimport {\n compactRows,\n project,\n type Shaped,\n shapeAll,\n shapeEntity,\n shapeProfile,\n} from '../format.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport { retain } from './cache.ts';\n\nfunction withSession(\n command: string,\n quiet = false,\n): { engine: ReturnType<typeof createEngine> } | Envelope {\n const loaded = loadSession();\n if (loaded.state === 'corrupt') {\n return err(\n command,\n 'CACHE_CORRUPT',\n 'the stored session was unreadable and has been quarantined',\n `Moved to ${loaded.quarantinedTo}. Re-run \\`lnrelay login\\`.`,\n );\n }\n if (loaded.state === 'missing') {\n return err(command, 'AUTH_FAILED', 'no session — run `lnrelay login` first', LAUNCH_HINT);\n }\n return { engine: createEngine(loaded.session, undefined, quiet) };\n}\n\n/** Turn an engine failure into an envelope without losing its hint. */\nfunction toEnvelope(\n command: string,\n result: Extract<EngineResult<never>, { ok: false }>,\n): Envelope {\n return err(command, result.code, result.message, result.hint, undefined, result.retryAfterMs);\n}\n\nexport async function runLogin(): Promise<Envelope> {\n const minted = await mintSessionFromBrowser();\n if (!minted.ok) return err('login', 'AUTH_FAILED', minted.message, minted.hint);\n\n saveSession(minted.session);\n // Never echo a credential — presence and length only.\n return ok('login', {\n stored: true,\n liAtLength: minted.session.liAt.length,\n userAgent: minted.session.userAgent,\n capturedAt: minted.session.capturedAt,\n notice:\n 'Session stored with owner-only permissions. This tool breaches LinkedIn User Agreement ' +\n '§8.2 and the account can be restricted or banned.',\n });\n}\n\nexport async function runWhoami(raw = false): Promise<Envelope> {\n const ctx = withSession('whoami');\n if ('ok' in ctx) return ctx;\n\n const result = await ctx.engine.whoami();\n if (!result.ok) return toEnvelope('whoami', result);\n if (result.value === undefined) {\n return err(\n 'whoami',\n 'SCHEMA_DRIFT',\n 'LinkedIn returned no member entity',\n 're-capture the `me` contract',\n );\n }\n return ok(\n 'whoami',\n raw ? { ...shapeEntity(result.value), raw: result.value } : shapeEntity(result.value),\n );\n}\n\nexport async function runProfile(memberId: string | undefined, raw = false): Promise<Envelope> {\n if (memberId === undefined || memberId === '') {\n return err(\n 'profile',\n 'INVALID_INPUT',\n 'a member id or urn is required',\n 'lnrelay profile <public-id|urn>',\n );\n }\n const ctx = withSession('profile');\n if ('ok' in ctx) return ctx;\n\n const result = await ctx.engine.profile(normaliseMemberId(memberId));\n if (!result.ok) return toEnvelope('profile', result);\n if (result.value === undefined) {\n return err('profile', 'NOT_FOUND', `no profile for '${memberId}'`);\n }\n const shaped = shapeProfile(result.value.profile, result.value.index);\n return ok('profile', raw ? { ...shaped, raw: result.value.profile } : shaped);\n}\n\nexport async function runFeed(limit: number, opts: OutputOpts = {}): Promise<Envelope> {\n const ctx = withSession('feed', opts.quiet === true);\n if ('ok' in ctx) return ctx;\n\n const result = await ctx.engine.feed(limit);\n if (!result.ok) return toEnvelope('feed', result);\n return ok('feed', collection(result.value, opts));\n}\n\nexport async function runSearch(\n kind: string | undefined,\n query: string | undefined,\n limit: number,\n opts: OutputOpts = {},\n): Promise<Envelope> {\n if (kind === undefined || !['people', 'companies', 'jobs'].includes(kind)) {\n return err(\n 'search',\n 'INVALID_INPUT',\n 'kind must be people, companies or jobs',\n 'lnrelay search people \"<query>\"',\n );\n }\n if (query === undefined || query === '') {\n return err('search', 'INVALID_INPUT', 'a query is required', 'lnrelay search people \"<query>\"');\n }\n const ctx = withSession('search', opts.quiet === true);\n if ('ok' in ctx) return ctx;\n\n const result = await ctx.engine.search(kind as SearchKind, query, limit);\n if (!result.ok) return toEnvelope('search', result);\n return ok('search', { query, kind, ...collection(result.value, opts) });\n}\n\nexport async function runPost(\n urn: string | undefined,\n limit: number,\n opts: OutputOpts = {},\n): Promise<Envelope> {\n const postUrn = normalisePostUrn(urn);\n if (postUrn === undefined) {\n return err(\n 'post',\n 'INVALID_INPUT',\n 'a post urn or feed URL is required',\n 'lnrelay post <activity-urn|https://www.linkedin.com/feed/update/...>',\n );\n }\n const ctx = withSession('post', opts.quiet === true);\n if ('ok' in ctx) return ctx;\n\n const result = await ctx.engine.post(postUrn, limit);\n if (!result.ok) return toEnvelope('post', result);\n return ok('post', { urn: postUrn, ...collection(result.value, opts) });\n}\n\nexport async function runReactions(\n urn: string | undefined,\n limit: number,\n opts: OutputOpts = {},\n): Promise<Envelope> {\n const postUrn = normalisePostUrn(urn);\n if (postUrn === undefined) {\n return err('reactions', 'INVALID_INPUT', 'a post urn or feed URL is required');\n }\n const ctx = withSession('reactions', opts.quiet === true);\n if ('ok' in ctx) return ctx;\n\n const result = await ctx.engine.reactions(postUrn, limit);\n if (!result.ok) return toEnvelope('reactions', result);\n return ok('reactions', { urn: postUrn, ...collection(result.value, opts) });\n}\n\n// ─── shaping ──────────────────────────────────────────────────────────────────\n\n/** Accept a bare urn or a feed permalink; both carry the post identity. */\nfunction normalisePostUrn(input: string | undefined): string | undefined {\n if (input === undefined || input === '') return undefined;\n const found = input.match(/urn:li:(?:activity|ugcPost|share):\\d+/);\n if (found !== null) return found[0];\n return /^\\d+$/.test(input) ? `urn:li:activity:${input}` : undefined;\n}\n\n/** A URL, a public id, or a bare urn all reduce to the member identity. */\nfunction normaliseMemberId(input: string): string {\n const fromUrl = input.match(/linkedin\\.com\\/in\\/([^/?#]+)/);\n if (fromUrl?.[1] !== undefined) return fromUrl[1];\n const fromUrn = input.match(/urn:li:fsd?_(?:mini)?[Pp]rofile:([^,)]+)/);\n if (fromUrn?.[1] !== undefined) return fromUrn[1];\n return input;\n}\n\n/** How the caller wants the rows rendered. */\nexport interface OutputOpts {\n raw?: boolean;\n retain?: boolean;\n compact?: boolean;\n fields?: string;\n quiet?: boolean;\n}\n\n/**\n * Collections are shaped by default — raw Voyager entities are enormous and\n * wrap every string in a TextViewModel. `--raw` keeps the original node\n * alongside, for when a shape has drifted and you need to see what arrived;\n * `--compact` and `--fields` go the other way, for when a page of results is\n * about to land in an agent's context and only the ranking signal matters.\n */\nfunction collection(result: Collection, opts: OutputOpts = {}): Record<string, unknown> {\n const { parsed, index } = result;\n const shaped = shapeAll(parsed.items, index);\n\n const meta: Record<string, unknown> = { ...parsed.meta };\n // Retention always stores the FULL shaped row, never the projected one — a\n // display choice must not silently narrow what gets cached.\n if (opts.retain === true) meta.retained = retain('third-party', shaped);\n\n if (opts.raw === true) {\n return {\n items: parsed.items.map((node, i) => ({ ...(shaped[i] as Shaped), raw: node })),\n meta,\n };\n }\n if (opts.compact === true) return { items: compactRows(shaped), meta };\n if (opts.fields !== undefined && opts.fields !== '') {\n return { items: project(shaped, opts.fields), meta };\n }\n return { items: shaped, meta };\n}\n","// The three commands that work today. All are local: they make no network call\n// and need no LinkedIn session, so they are useful before the Phase 0 gate has\n// even run.\n\nimport { existsSync } from 'node:fs';\nimport { version as nodeVersion } from 'node:process';\nimport { cacheDir, cachePath, loadJson, saveJson } from '../cache/store.ts';\nimport {\n activeCooldown,\n CAPS,\n type Cooldown,\n emptyLedger,\n type Ledger,\n type SpendClass,\n summarise,\n} from '../engine/budget.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\n\nconst LEDGER_FILE = 'budget.json';\nconst COOLDOWN_FILE = 'cooldown.json';\n\ninterface StateLoad<T> {\n value: T | null;\n corrupt: { path: string; quarantinedTo: string; reason: string } | null;\n}\n\nfunction loadState<T>(file: string, fallback: T): StateLoad<T> {\n const path = cachePath(file);\n const result = loadJson<T>(path);\n if (result.state === 'ok') return { value: result.value, corrupt: null };\n if (result.state === 'missing') return { value: fallback, corrupt: null };\n return {\n value: null,\n corrupt: { path, quarantinedTo: result.quarantinedTo, reason: result.reason },\n };\n}\n\nexport function loadLedger(): StateLoad<Ledger> {\n return loadState<Ledger>(LEDGER_FILE, emptyLedger());\n}\n\nexport function loadCooldown(): StateLoad<Cooldown | null> {\n return loadState<Cooldown | null>(COOLDOWN_FILE, null);\n}\n\n// ─── risk ─────────────────────────────────────────────────────────────────────\n\n/**\n * The breaker's current state. Exposed over MCP deliberately, so an agent can\n * check standing BEFORE deciding to spend budget on research rather than\n * discovering the lockout one wasted call at a time.\n */\nexport function runRisk(now: number): Envelope {\n const { value: cooldown, corrupt } = loadCooldown();\n if (corrupt !== null) {\n return err(\n 'risk',\n 'CACHE_CORRUPT',\n `cooldown state was unreadable and has been quarantined: ${corrupt.reason}`,\n `moved to ${corrupt.quarantinedTo}. Inspect it, then re-run — a fresh cooldown file will be created.`,\n );\n }\n\n const blocked = activeCooldown(cooldown ?? null, now);\n return ok('risk', {\n state: blocked ? 'blocked' : 'ok',\n cooldown: cooldown ?? null,\n tosNotice:\n 'Voyager reads breach LinkedIn User Agreement §8.2. This tool is not ToS-compliant and ' +\n 'any account it touches can be restricted or permanently banned.',\n });\n}\n\n// ─── budget ───────────────────────────────────────────────────────────────────\n\nexport function runBudget(now: number, resetCooldown: boolean, confirmed: boolean): Envelope {\n if (resetCooldown && !confirmed) {\n return err(\n 'budget',\n 'CONFIRMATION_REQUIRED',\n 'clearing a cooldown requires --confirm',\n 'A cooldown means LinkedIn signalled a throttle, block or challenge. Log in through a real ' +\n 'browser and confirm you are unblocked before clearing it. Re-run with --confirm.',\n );\n }\n\n if (resetCooldown) {\n saveJson(cachePath(COOLDOWN_FILE), null);\n }\n\n const { value: ledger, corrupt } = loadLedger();\n if (corrupt !== null) {\n return err(\n 'budget',\n 'CACHE_CORRUPT',\n `the spend ledger was unreadable and has been quarantined: ${corrupt.reason}`,\n `moved to ${corrupt.quarantinedTo}. A corrupt ledger is NOT treated as an empty one — that ` +\n 'would silently restore a full budget. Inspect it, then re-run.',\n );\n }\n\n const classes: SpendClass[] = ['profile', 'search', 'page', 'write', 'global'];\n const { value: cooldown } = loadCooldown();\n\n return ok('budget', {\n classes: classes.map((c) => ({\n ...summarise(ledger ?? emptyLedger(), c, now),\n note: CAPS[c].note,\n })),\n cooldown: cooldown ?? null,\n caveat:\n 'Every cap is guessed or transplanted vendor lore — the field research found no corroborated ' +\n 'LinkedIn rate limits. These are starting knobs, not safe thresholds. They also cannot see ' +\n 'your manual browser activity.',\n });\n}\n\n// ─── doctor ───────────────────────────────────────────────────────────────────\n\nexport interface Check {\n name: string;\n ok: boolean;\n detail: string;\n}\n\n/**\n * Diagnose setup. Always returns ok:true at the envelope level — a diagnostic\n * that fails to report because something is broken is useless. Individual checks\n * carry their own pass/fail. Never prints a credential value.\n */\nexport function runDoctor(now: number, offline: boolean): Envelope {\n const checks: Check[] = [];\n\n checks.push({\n name: 'runtime',\n ok: true,\n detail: `node ${nodeVersion}; cache dir ${cacheDir()}${existsSync(cacheDir()) ? '' : ' (not created yet)'}`,\n });\n\n const { value: cooldown, corrupt: cooldownCorrupt } = loadCooldown();\n if (cooldownCorrupt !== null) {\n checks.push({\n name: 'cooldown',\n ok: false,\n detail: `state file was corrupt; quarantined to ${cooldownCorrupt.quarantinedTo}`,\n });\n } else {\n const blocked = activeCooldown(cooldown ?? null, now);\n checks.push({\n name: 'cooldown',\n ok: !blocked,\n detail: blocked\n ? `BLOCKED — ${cooldown?.reason}, clears by ${cooldown?.clearRequires}${\n cooldown?.until === null\n ? ' (indefinite)'\n : ` at ${new Date(cooldown?.until ?? 0).toISOString()}`\n }`\n : 'clear',\n });\n }\n\n const { value: ledger, corrupt: ledgerCorrupt } = loadLedger();\n if (ledgerCorrupt !== null) {\n checks.push({\n name: 'budget',\n ok: false,\n detail: `ledger was corrupt; quarantined to ${ledgerCorrupt.quarantinedTo}`,\n });\n } else {\n const g = summarise(ledger ?? emptyLedger(), 'global', now);\n checks.push({\n name: 'budget',\n ok: g.remaining > 0,\n detail: `${g.spentInWindow}/${g.cap} global calls used in the last 24h (cap provenance: ${g.capProvenance})`,\n });\n }\n\n // Credentials are checked for PRESENCE and LENGTH only — never printed.\n const cookiePath = cachePath('cookies.json');\n checks.push({\n name: 'session',\n ok: false,\n detail: existsSync(cookiePath)\n ? 'a cookie file exists, but the engine is not implemented yet (Phase 2)'\n : 'no session yet — the Phase 0 capture gate has not been run. See docs/PLAN.md.',\n });\n\n checks.push({\n name: 'engine',\n ok: false,\n detail:\n 'not implemented. Phase 0 (three human-paced requests from a residential IP) must pass ' +\n 'before engine code is written — see docs/PLAN.md.',\n });\n\n if (!offline) {\n checks.push({\n name: 'live',\n ok: false,\n detail: 'no live checks available yet; --offline is currently the only meaningful mode',\n });\n }\n\n return ok('doctor', {\n healthy: checks.every((c) => c.ok),\n phase: 'Phase 1 — local scaffolding. No network capability exists yet, by design.',\n checks,\n });\n}\n","// ─── Obtaining the write credential ───────────────────────────────────────────\n//\n// The three-legged dance, with the parts that touch the world isolated behind\n// `LoginDeps`: a socket on localhost, a browser, a terminal prompt, and fetch.\n// The ordering constraint that matters is that the listener must be up BEFORE\n// the browser is sent anywhere, or a fast consent lands on a closed port.\n//\n// This command is CLI-only and always will be. It opens a browser and stores a\n// bearer credential; neither belongs on an agent-facing surface.\n\nimport { spawn } from 'node:child_process';\nimport { createServer } from 'node:http';\nimport { createInterface } from 'node:readline/promises';\nimport { CAPS } from '../engine/budget.ts';\nimport {\n authorizationUrl,\n CALLBACK_PORT,\n exchange,\n fetchMemberUrn,\n parseCallback,\n SCOPES,\n} from '../engine/oauth.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport { deleteToken, loadToken, OAUTH_SETUP, saveToken, tokenPath } from './token.ts';\n\nexport type CodeResult = { ok: true; code: string } | { ok: false; message: string };\n\nexport type Listener =\n | { ok: true; code: Promise<CodeResult>; close: () => void }\n | { ok: false; message: string };\n\nconst CALLBACK_TIMEOUT_MS = 300_000;\n\nconst DONE_PAGE = `<!doctype html><meta charset=\"utf-8\"><title>lnrelay</title>\n<body style=\"font:16px system-ui;padding:3rem;max-width:32rem\">\n<h1>Authorised.</h1><p>You can close this tab and go back to the terminal.</p>`;\n\n/**\n * Listen on the loopback callback port for exactly one consent redirect.\n *\n * Resolves as soon as the socket is bound, so the caller can open the browser\n * knowing there is something to land on; the code arrives later on `.code`.\n */\nexport function listenForCallback(\n state: string,\n timeoutMs = CALLBACK_TIMEOUT_MS,\n): Promise<Listener> {\n return new Promise<Listener>((ready) => {\n let settle: (r: CodeResult) => void = () => {};\n const code = new Promise<CodeResult>((r) => {\n settle = r;\n });\n\n const server = createServer((req, res) => {\n const url = req.url ?? '/';\n // Browsers ask for /favicon.ico unprompted. Answering that is not consent.\n if (!url.startsWith('/callback')) {\n res.writeHead(404, { connection: 'close' });\n res.end();\n return;\n }\n res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', connection: 'close' });\n res.end(DONE_PAGE);\n settle(parseCallback(url, state));\n });\n\n const timer = setTimeout(() => {\n settle({\n ok: false,\n message: `timed out after ${Math.round(timeoutMs / 1000)}s waiting for the LinkedIn callback`,\n });\n }, timeoutMs);\n timer.unref?.();\n\n const close = (): void => {\n clearTimeout(timer);\n server.closeAllConnections?.();\n server.close();\n };\n\n server.once('error', (e: NodeJS.ErrnoException) => {\n clearTimeout(timer);\n const why =\n e.code === 'EADDRINUSE'\n ? `port ${CALLBACK_PORT} is already in use — close whatever holds it and retry`\n : `could not open the callback listener: ${e.message}`;\n ready({ ok: false, message: why });\n });\n\n server.listen(CALLBACK_PORT, '127.0.0.1', () => {\n ready({ ok: true, code, close });\n });\n });\n}\n\n/** Best effort. The URL is always printed too, so a failure here is survivable. */\nfunction openBrowser(url: string): void {\n const cmd =\n process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open';\n try {\n spawn(cmd, [url], { detached: true, stdio: 'ignore' }).unref();\n } catch {\n // The printed URL is the fallback.\n }\n}\n\nexport interface LoginDeps {\n state: () => string;\n listen: (state: string) => Promise<Listener>;\n open: (url: string) => void;\n write: (s: string) => void;\n isTty: boolean;\n prompt: (question: string) => Promise<string>;\n now: () => number;\n fetch: typeof globalThis.fetch;\n}\n\nexport function loginDeps(): LoginDeps {\n return {\n state: () => crypto.randomUUID(),\n listen: (state) => listenForCallback(state),\n open: openBrowser,\n write: (s) => process.stderr.write(s),\n isTty: process.stdin.isTTY === true && process.stderr.isTTY === true,\n prompt: async (question) => {\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n const answer = await rl.question(question);\n rl.close();\n return answer;\n },\n now: Date.now,\n fetch: globalThis.fetch,\n };\n}\n\ninterface Credentials {\n clientId: string;\n clientSecret: string;\n}\n\n/**\n * Flag, then environment, then — for the secret only — a prompt. The secret is\n * prompted rather than required as a flag because argv lands in shell history.\n */\nasync function credentials(\n opts: { clientId?: string; clientSecret?: string },\n deps: LoginDeps,\n): Promise<Credentials | Envelope> {\n const clientId = opts.clientId ?? process.env.LINKEDIN_CLIENT_ID;\n if (clientId === undefined || clientId === '') {\n return err('oauth', 'INVALID_INPUT', 'a client id is required', OAUTH_SETUP);\n }\n\n let clientSecret = opts.clientSecret ?? process.env.LINKEDIN_CLIENT_SECRET;\n if ((clientSecret === undefined || clientSecret === '') && deps.isTty) {\n clientSecret = (await deps.prompt('client secret (not echoed to argv or logs): ')).trim();\n }\n if (clientSecret === undefined || clientSecret === '') {\n return err(\n 'oauth',\n 'INVALID_INPUT',\n 'a client secret is required, and there is no terminal to ask on',\n `Set LINKEDIN_CLIENT_SECRET, or run this at an interactive terminal.\\n\\n${OAUTH_SETUP}`,\n );\n }\n return { clientId, clientSecret };\n}\n\n/** Run the consent flow and store the resulting token. Never prints it. */\nexport async function runOauthLogin(\n opts: { clientId?: string; clientSecret?: string },\n deps: LoginDeps = loginDeps(),\n): Promise<Envelope> {\n const creds = await credentials(opts, deps);\n if ('ok' in creds) return creds;\n\n const state = deps.state();\n const listener = await deps.listen(state);\n if (!listener.ok) {\n return err('oauth', 'AUTH_FAILED', listener.message);\n }\n\n try {\n const url = authorizationUrl(creds.clientId, state);\n deps.write(`Opening LinkedIn for consent. If nothing opens, visit:\\n\\n ${url}\\n\\n`);\n deps.open(url);\n\n const callback = await listener.code;\n if (!callback.ok) return err('oauth', 'AUTH_FAILED', callback.message);\n\n const token = await exchange(callback.code, creds, { fetch: deps.fetch, now: deps.now });\n if (!token.ok) return err('oauth', 'AUTH_FAILED', token.message, token.hint);\n\n const member = await fetchMemberUrn(token.accessToken, { fetch: deps.fetch });\n // A token we cannot attribute to a member cannot author anything, so it is\n // not worth storing — every write needs the author urn.\n if (!member.ok) return err('oauth', 'AUTH_FAILED', member.message, OAUTH_SETUP);\n\n saveToken({\n accessToken: token.accessToken,\n memberUrn: member.memberUrn,\n expiresAt: token.expiresAt,\n });\n\n return ok('oauth', {\n memberUrn: member.memberUrn,\n scopes: SCOPES,\n expiresAt: new Date(token.expiresAt).toISOString(),\n storedAt: tokenPath(),\n // Refresh tokens are partner-gated, so renewal is re-running this.\n renewal: 'run `lnrelay oauth login` again when it expires',\n });\n } finally {\n listener.close();\n }\n}\n\n/** Remove the stored credential. Local only — LinkedIn is never contacted. */\nexport function runOauthLogout(): Envelope {\n const removed = deleteToken();\n return ok('oauth', {\n removed,\n note: removed\n ? `deleted ${tokenPath()} — the token stays valid on LinkedIn's side until it expires`\n : 'no token was stored',\n });\n}\n\n/** Report OAuth setup state. Never prints the token. */\nexport function runOauthStatus(): Envelope {\n const token = loadToken();\n if (token === null) return err('oauth', 'AUTH_FAILED', 'no OAuth token stored', OAUTH_SETUP);\n return ok('oauth', {\n memberUrn: token.memberUrn,\n expiresAt: new Date(token.expiresAt).toISOString(),\n expired: token.expiresAt <= Date.now(),\n scopes: SCOPES,\n storedAt: tokenPath(),\n writeCap: CAPS.write.perDay,\n });\n}\n","// ─── Three-legged OAuth ───────────────────────────────────────────────────────\n//\n// The only sanctioned path an individual has. Both products this needs are\n// self-serve — no partner review, no company verification, no screencast:\n//\n// Sign In with LinkedIn using OpenID Connect → openid, profile (member urn)\n// Share on LinkedIn → w_member_social (the writes)\n//\n// Everything here is pure except `exchange` and `fetchMemberUrn`, which take an\n// injected fetch. The local callback server lives in commands/oauth.ts, so this\n// module stays testable without opening a socket.\n\nconst AUTHORIZE = 'https://www.linkedin.com/oauth/v2/authorization';\nconst TOKEN = 'https://www.linkedin.com/oauth/v2/accessToken';\nconst USERINFO = 'https://api.linkedin.com/v2/userinfo';\n\n/** Port chosen to be memorable and unlikely to collide with a dev server. */\nexport const CALLBACK_PORT = 53682;\nexport const REDIRECT_URI = `http://localhost:${CALLBACK_PORT}/callback`;\n\n/**\n * `openid` + `profile` identify the member (we need their urn to author\n * anything); `w_member_social` is the write scope. `email` is deliberately NOT\n * requested — the tool has no use for it, and an unused scope is a permission\n * granted for nothing.\n */\nexport const SCOPES = ['openid', 'profile', 'w_member_social'];\n\nexport interface OAuthConfig {\n clientId: string;\n clientSecret: string;\n}\n\n/**\n * Build the consent URL. `state` is a CSRF nonce: LinkedIn echoes it back, and\n * a callback carrying a different one did not originate from this run.\n */\nexport function authorizationUrl(clientId: string, state: string): string {\n const params = new URLSearchParams({\n response_type: 'code',\n client_id: clientId,\n redirect_uri: REDIRECT_URI,\n state,\n scope: SCOPES.join(' '),\n });\n return `${AUTHORIZE}?${params.toString()}`;\n}\n\nexport type ExchangeResult =\n | { ok: true; accessToken: string; expiresAt: number }\n | { ok: false; message: string; hint?: string };\n\n/** Swap the authorization code for an access token. */\nexport async function exchange(\n code: string,\n config: OAuthConfig,\n deps: { fetch: typeof globalThis.fetch; now: () => number },\n): Promise<ExchangeResult> {\n const body = new URLSearchParams({\n grant_type: 'authorization_code',\n code,\n redirect_uri: REDIRECT_URI,\n client_id: config.clientId,\n client_secret: config.clientSecret,\n });\n\n let res: Response;\n try {\n res = await deps.fetch(TOKEN, {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n } catch (e) {\n return { ok: false, message: `could not reach LinkedIn: ${(e as Error).message}` };\n }\n\n const text = await res.text();\n if (res.status !== 200) {\n return {\n ok: false,\n message: `LinkedIn rejected the code exchange (${res.status})`,\n // The most common causes, in the order they actually happen.\n hint:\n 'Check that the app has BOTH products added, and that its Auth tab lists ' +\n `exactly ${REDIRECT_URI} as an authorized redirect URL. Response: ${text.slice(0, 200)}`,\n };\n }\n\n let parsed: { access_token?: unknown; expires_in?: unknown };\n try {\n parsed = JSON.parse(text) as typeof parsed;\n } catch {\n return { ok: false, message: 'token response was not JSON' };\n }\n\n const accessToken = parsed.access_token;\n const expiresIn = parsed.expires_in;\n if (typeof accessToken !== 'string' || accessToken === '') {\n return { ok: false, message: 'token response carried no access_token' };\n }\n\n // LinkedIn access tokens last ~60 days. Refresh tokens are partner-gated, so\n // re-running `oauth login` is the renewal path — recorded rather than hidden.\n const lifetimeMs = typeof expiresIn === 'number' ? expiresIn * 1000 : 60 * 86_400_000;\n return { ok: true, accessToken, expiresAt: deps.now() + lifetimeMs };\n}\n\nexport type MemberResult = { ok: true; memberUrn: string } | { ok: false; message: string };\n\n/**\n * The member urn to author as. `/v2/userinfo` returns OIDC claims; `sub` is the\n * member id, and `urn:li:person:<sub>` is what the write APIs expect as author.\n */\nexport async function fetchMemberUrn(\n accessToken: string,\n deps: { fetch: typeof globalThis.fetch },\n): Promise<MemberResult> {\n let res: Response;\n try {\n res = await deps.fetch(USERINFO, { headers: { authorization: `Bearer ${accessToken}` } });\n } catch (e) {\n return { ok: false, message: `could not reach userinfo: ${(e as Error).message}` };\n }\n\n if (res.status !== 200) {\n return {\n ok: false,\n message: `userinfo returned ${res.status} — the 'openid'/'profile' scopes may not be granted`,\n };\n }\n\n const parsed = (await res.json()) as { sub?: unknown };\n if (typeof parsed.sub !== 'string' || parsed.sub === '') {\n return { ok: false, message: 'userinfo carried no subject claim' };\n }\n return { ok: true, memberUrn: `urn:li:person:${parsed.sub}` };\n}\n\n/** Extract `code`/`state`, or the error LinkedIn sent instead. */\nexport function parseCallback(\n rawUrl: string,\n expectedState: string,\n): { ok: true; code: string } | { ok: false; message: string } {\n let url: URL;\n try {\n url = new URL(rawUrl, `http://localhost:${CALLBACK_PORT}`);\n } catch {\n return { ok: false, message: 'callback URL was unparseable' };\n }\n\n const error = url.searchParams.get('error');\n if (error !== null) {\n const description = url.searchParams.get('error_description') ?? '';\n return { ok: false, message: `LinkedIn denied the request: ${error} ${description}`.trim() };\n }\n\n const state = url.searchParams.get('state');\n if (state !== expectedState) {\n // Either a stale browser tab or something that did not come from this run.\n return { ok: false, message: 'state mismatch — this callback did not come from this login' };\n }\n\n const code = url.searchParams.get('code');\n if (code === null || code === '') return { ok: false, message: 'callback carried no code' };\n\n return { ok: true, code };\n}\n","// ─── Where the OAuth credential lives ─────────────────────────────────────────\n//\n// Its own module so that the command that OBTAINS a token and the commands that\n// SPEND one can share the storage without importing each other.\n//\n// The file is written 0600 under ~/.lnrelay (see cache/store.ts). That is the\n// whole protection: no keychain, no encryption. It is a 60-day bearer token for\n// posting as you, so treat the directory accordingly and keep it out of cloud\n// sync. `lnrelay oauth logout` removes it.\n\nimport { existsSync, rmSync } from 'node:fs';\nimport { cachePath, loadJson, saveJson } from '../cache/store.ts';\nimport { REDIRECT_URI } from '../engine/oauth.ts';\nimport type { OAuthToken } from '../engine/oauth-write.ts';\n\nconst TOKEN_FILE = 'oauth.json';\n\nexport const OAUTH_SETUP = [\n \"Writes go over LinkedIn's OWN self-serve scope rather than the private API, which is the one\",\n 'legitimacy wedge an individual actually has — but the app has to be registered by you; it',\n 'cannot be created on your behalf.',\n '',\n ' 1. https://www.linkedin.com/developers/apps/new — create an app (any LinkedIn Page works).',\n ' 2. Products tab → add \"Sign In with LinkedIn using OpenID Connect\" AND \"Share on LinkedIn\".',\n ' Both are self-serve: no partner review, no verification, no screencast.',\n ` 3. Auth tab → add redirect URL ${REDIRECT_URI}`,\n ' 4. Run: lnrelay oauth login --client-id <id>',\n ' (the secret is prompted for; or set LINKEDIN_CLIENT_ID / LINKEDIN_CLIENT_SECRET)',\n].join('\\n');\n\nexport function tokenPath(): string {\n return cachePath(TOKEN_FILE);\n}\n\nexport function loadToken(): OAuthToken | null {\n const result = loadJson<OAuthToken>(tokenPath());\n return result.state === 'ok' ? result.value : null;\n}\n\nexport function saveToken(token: OAuthToken): void {\n saveJson(tokenPath(), token);\n}\n\n/** Returns whether there was anything to remove — silence would be ambiguous. */\nexport function deleteToken(): boolean {\n const path = tokenPath();\n if (!existsSync(path)) return false;\n rmSync(path, { force: true });\n return true;\n}\n","// Single source of truth for command definitions. Drives CLI dispatch + help,\n// the MCP tool surface, and the SKILL.md parity test.\n//\n// `audience` is load-bearing, not documentation: the MCP shim registers only\n// commands marked `mcp`, so a write can never reach an agent by accident. The\n// research half of this tool is the product; writes are a thin, human-gated\n// layer that arrives last (docs/PLAN.md Phase 6).\n\nexport type Audience = 'cli' | 'mcp';\nexport type RiskClass = 'read' | 'local' | 'write';\n\nexport interface CommandDef {\n name: string;\n /** Funnel cost hint shown in help + skill. */\n cost: string;\n summary: string;\n usage: string;\n audience: Audience[];\n risk: RiskClass;\n /** false until the command is actually wired up. */\n implemented: boolean;\n}\n\nexport const COMMANDS: CommandDef[] = [\n // ─── local / meta — no network, available today ────────────────────────────\n {\n name: 'doctor',\n cost: 'free with --offline',\n summary: 'Diagnose setup: entry point, cache dir, cookies, cooldown, budget.',\n usage: 'lnrelay doctor [--offline]',\n audience: ['cli', 'mcp'],\n risk: 'local',\n implemented: true,\n },\n {\n name: 'budget',\n cost: 'free',\n summary: \"Spend ledger per class, with each cap's provenance. Reset a cooldown here.\",\n usage: 'lnrelay budget [--reset-cooldown --confirm]',\n audience: ['cli', 'mcp'],\n risk: 'local',\n implemented: true,\n },\n {\n name: 'risk',\n cost: 'free',\n summary: 'Circuit-breaker state. Check this BEFORE spending budget on research.',\n usage: 'lnrelay risk',\n audience: ['cli', 'mcp'],\n risk: 'local',\n implemented: true,\n },\n\n // ─── session ───────────────────────────────────────────────────────────────\n {\n name: 'login',\n cost: 'free — local browser',\n summary: 'Mint a session from a logged-in Chrome via DevTools. Stores cookies owner-only.',\n usage:\n 'lnrelay login\\n' +\n ' Requires a Chrome started with remote debugging on port 9222 (see docs/PLAN.md).',\n audience: ['cli'],\n risk: 'local',\n implemented: true,\n },\n\n // ─── reads — verified live 2026-08-01 ─────────────────────────────────────\n {\n name: 'whoami',\n cost: '1 call',\n summary: 'The authenticated member: name, headline, URN.',\n usage: 'lnrelay whoami',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'profile',\n cost: '1 call (+1 per section)',\n summary: 'A member profile. Expensive sections are opt-in.',\n usage:\n 'lnrelay profile <public-id|urn|url> [--raw]\\n' +\n \" Returns headline, location, current title, company and school. LinkedIn's profile\\n\" +\n ' projections do not return a name — use the identifier you passed in.',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'search',\n cost: 'cheap — the net',\n summary: 'Search people, companies or jobs. Cast wide, then deep-read the finalists.',\n usage:\n 'lnrelay search people|companies|jobs \"<query>\" [--limit N]\\n' +\n ' [--compact | --fields a,b,c] [--retain] [--raw]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'post',\n cost: 'expensive — full read',\n summary: 'A post plus its comment thread, cursor-followed.',\n usage:\n 'lnrelay post <activity-urn|url> [--limit N] [--compact | --fields a,b] [--retain]\\n' +\n ' Check meta.returnedCount / claimedCount / state. claimedCount > 0 with\\n' +\n ' returnedCount 0 is a FAILED FETCH, not an empty thread.',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'reactions',\n cost: 'medium',\n summary: 'Who reacted to a post, and with which reaction.',\n usage: 'lnrelay reactions <activity-urn|url> [--limit N] [--compact | --fields a,b]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'company',\n cost: 'medium',\n summary: 'A company page, optionally with a bounded sample of its updates.',\n usage: 'lnrelay company <universal-name|url> [--updates N]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: false,\n },\n {\n name: 'job',\n cost: '1 call',\n summary: 'A job posting detail.',\n usage: 'lnrelay job <job-id|url>',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: false,\n },\n {\n name: 'feed',\n cost: 'medium',\n summary: 'Your own chronological feed.',\n usage: 'lnrelay feed [--limit N] [--compact | --fields a,b,c] [--retain] [--raw]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n\n // ─── cache-backed — Phase 4 ────────────────────────────────────────────────\n {\n name: 'sync',\n cost: 'medium — 1-2 calls',\n summary: 'Pull your own posts or connections into the local cache for offline search.',\n usage: 'lnrelay sync my-posts|connections [--limit N] [--force]',\n audience: ['cli'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'connections',\n cost: 'free — local cache',\n summary: 'Your connections, from the local cache. Fill it with `sync connections`.',\n usage:\n 'lnrelay connections [-q \"<query>\"] [--limit N] [--compact | --fields a,b] # free; cache',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'my-posts',\n cost: 'free — local cache',\n summary: 'Your own authored posts, from the local cache. Fill it with `sync my-posts`.',\n usage:\n 'lnrelay my-posts [-q \"<query>\"] [--limit N] [--compact | --fields a,b] # free; cache',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'local',\n cost: 'free — local cache',\n summary: 'Offline search across everything synced. The default research path after a sync.',\n usage:\n 'lnrelay local \"<query>\" [--source connections,my-posts,third-party] [--since YYYY-MM-DD]\\n' +\n ' [--limit N] [--compact | --fields a,b,c]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'cache-status',\n cost: 'free — local cache',\n summary: 'What is cached, per source, with sync checkpoints and the retention policy.',\n usage: 'lnrelay cache-status',\n audience: ['cli', 'mcp'],\n risk: 'local',\n implemented: true,\n },\n {\n name: 'purge',\n cost: 'free',\n summary: 'Delete cached data. Never contacts LinkedIn.',\n usage: 'lnrelay purge [--all] --confirm # default scope: third-party only',\n audience: ['cli'],\n risk: 'local',\n implemented: true,\n },\n\n // ─── writes — Phase 6, official OAuth only, never MCP ──────────────────────\n {\n name: 'oauth',\n cost: 'free',\n summary:\n \"Obtain and inspect the write credential, over LinkedIn's own self-serve scope. \" +\n 'Never prints the token.',\n usage:\n 'lnrelay oauth login --client-id <id> [--client-secret <secret>]\\n' +\n ' lnrelay oauth status | logout\\n' +\n ' The secret is prompted for if omitted; LINKEDIN_CLIENT_ID / LINKEDIN_CLIENT_SECRET also work.\\n' +\n ' Needs an app you registered: see the hint printed when no token is stored.',\n audience: ['cli'],\n risk: 'local',\n implemented: true,\n },\n {\n name: 'share',\n cost: '1 call — write',\n summary:\n \"Post to your own feed. Prefers LinkedIn's official OAuth scope, falls back to the \" +\n 'private API when no token exists — the prompt always names which.',\n usage:\n 'lnrelay share \"<text>\" [--visibility public|connections] [--via oauth|voyager]\\n' +\n ' Stops and asks at an interactive terminal. No TTY = no write, and no network call.',\n audience: ['cli'],\n risk: 'write',\n implemented: true,\n },\n {\n name: 'comment',\n cost: '1 call — write',\n summary:\n 'Add a comment to a post. Harvests its binding tokens from the rendered page; no browser ' +\n 'needed, but it costs one heavy read.',\n usage:\n 'lnrelay comment <activity-urn> \"<text>\"\\n' +\n ' Fetches the post page (~2.8 MB) to harvest a binding key and trackingId, and proves\\n' +\n ' the key belongs to that post before asking. To change a comment, see `edit`.',\n audience: ['cli'],\n risk: 'write',\n implemented: true,\n },\n {\n name: 'delete',\n cost: '1 read + 1 write',\n summary:\n 'Delete one of your own posts or comments. Reads a post back and shows its text first — ' +\n 'this is the one action that cannot be undone.',\n usage:\n 'lnrelay delete <activity-urn> # a post; shows you its text before destroying it\\n' +\n ' lnrelay delete <comment-urn> # a comment; the server decides if you may',\n audience: ['cli'],\n risk: 'write',\n implemented: true,\n },\n {\n name: 'reply',\n cost: '1 read + 1 write',\n summary:\n 'Reply to a comment. Its own verb — a reply and a top-level comment differ only by which ' +\n 'binding the server hands back, so guessing is not survivable.',\n usage: 'lnrelay reply <comment-urn> \"<text>\"',\n audience: ['cli'],\n risk: 'write',\n implemented: true,\n },\n {\n name: 'edit',\n cost: '1 read + 1 write',\n summary:\n 'Change the text of a comment you wrote. Its own verb, so a comment urn can never be ' +\n 'mistaken for something to comment ON.',\n usage: 'lnrelay edit <comment-urn> \"<text>\"',\n audience: ['cli'],\n risk: 'write',\n implemented: true,\n },\n {\n name: 'react',\n cost: '1 call — write',\n summary: \"React to a post or comment, over LinkedIn's SDUI surface. Reversible with --remove.\",\n usage:\n 'lnrelay react <activity-urn | comment-urn> [--type LIKE|PRAISE|EMPATHY|INTEREST|APPRECIATION|ENTERTAINMENT]\\n' +\n ' lnrelay react <urn> --remove # take the reaction back',\n audience: ['cli'],\n risk: 'write',\n implemented: true,\n },\n];\n\nexport const commandNames = COMMANDS.map((c) => c.name);\n\nexport function findCommand(name: string): CommandDef | undefined {\n return COMMANDS.find((c) => c.name === name);\n}\n\n/** Commands the MCP shim may register. Writes are structurally excluded. */\nexport function mcpCommands(): CommandDef[] {\n return COMMANDS.filter((c) => c.audience.includes('mcp') && c.risk !== 'write');\n}\n\nexport function helpText(): string {\n const lines = ['lnrelay — deep research over LinkedIn from your own account', '', 'Commands:'];\n const width = Math.max(...commandNames.map((n) => n.length));\n for (const c of COMMANDS) {\n const flag = c.implemented ? ' ' : '·'; // · = designed, not yet wired\n lines.push(` ${flag} ${c.name.padEnd(width)} ${c.summary} [${c.cost}]`);\n }\n lines.push('', ' · = specified in docs/DESIGN.md, not yet implemented');\n lines.push('', 'Run `lnrelay <command> --help` for usage.');\n return lines.join('\\n');\n}\n","// ─── Sync ─────────────────────────────────────────────────────────────────────\n//\n// Two sources, two genuinely different strategies, because LinkedIn orders them\n// differently and forcing one pattern onto both is how silent incompleteness\n// starts.\n//\n// my-posts Newest-first, so a timestamp watermark works — WITH a two-page\n// slack, because LinkedIn pins posts to position 0 and a\n// break-on-first-stale-page would terminate instantly against a\n// pinned old post.\n//\n// connections A filtered people-search, NOT a change stream. There is no\n// ordering to watermark against at all, so this is a snapshot\n// and a set difference: {added, removed}. The checkpoint records\n// `snapshot-partial` rather than inventing a watermark.\n//\n// Both write through the cache's owner-data path, which never expires.\n\nimport {\n CacheCorrupt,\n getCheckpoint,\n openDb,\n removeUrns,\n setCheckpoint,\n upsert,\n urnsFor,\n} from '../cache/db.ts';\nimport type { Engine } from '../engine/index.ts';\nimport { createEngine } from '../engine/index.ts';\nimport { LAUNCH_HINT, loadSession } from '../engine/session.ts';\nimport type { Shaped } from '../format.ts';\nimport { shapeAll } from '../format.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\n\n/** Connections change slowly and the full walk is the priciest read we make. */\nconst CONNECTIONS_MIN_INTERVAL_MS = 7 * 86_400_000;\n\nfunction searchText(item: Shaped): string {\n return [item.name, item.headline, item.location, item.text, item.author, item.company, item.title]\n .filter((v) => typeof v === 'string')\n .join(' ');\n}\n\nfunction rowsFrom(items: Shaped[]): { urn: string; body: unknown; text: string }[] {\n return items\n .filter((i) => typeof i.urn === 'string' && i.urn !== '')\n .map((i) => ({ urn: i.urn as string, body: i, text: searchText(i) }));\n}\n\n/**\n * Decide what a fresh snapshot means for the stored set.\n *\n * The load-bearing rule: removals are only inferable from a COMPLETE snapshot.\n * If LinkedIn claims 400 connections and a limit fetched 50, the 350 unseen are\n * not gone — they were never looked at. Reporting them as removed would tell\n * the user people had disconnected because of a pagination limit.\n */\nexport function diffSnapshot(\n before: Set<string>,\n seen: Set<string>,\n claimed: number | undefined,\n): { removed: string[]; complete: boolean } {\n const complete = claimed === undefined || seen.size >= claimed;\n if (!complete) return { removed: [], complete: false };\n return { removed: [...before].filter((urn) => !seen.has(urn)), complete: true };\n}\n\ntype Db = ReturnType<typeof openDb>;\n\nasync function syncMyPosts(engine: Engine, db: Db, limit: number, now: number): Promise<Envelope> {\n // The owner's own profile urn — we ask LinkedIn rather than assume it.\n const me = await engine.whoami();\n if (!me.ok) return err('sync', me.code, me.message, me.hint);\n const profileUrn = typeof me.value?.entityUrn === 'string' ? me.value.entityUrn : undefined;\n if (profileUrn === undefined) {\n return err('sync', 'SCHEMA_DRIFT', 'could not determine the owner profile urn');\n }\n\n const result = await engine.myPosts(profileUrn, limit);\n if (!result.ok) return err('sync', result.code, result.message, result.hint);\n\n const rows = rowsFrom(shapeAll(result.value.parsed.items, result.value.index));\n const stored = upsert(db, 'my-posts', rows, now);\n\n setCheckpoint(db, {\n source: 'my-posts',\n lastSuccessfulAt: now,\n newestCreatedAt: null,\n headIds: rows.slice(0, 5).map((r) => r.urn),\n state: 'ok',\n });\n\n return ok('sync', {\n source: 'my-posts',\n ...stored,\n meta: result.value.parsed.meta,\n note:\n rows.length === 0\n ? 'LinkedIn returned no posts for this account. That is a genuine empty, not a failed fetch — meta.state says which.'\n : undefined,\n });\n}\n\n/** The full walk is the priciest read we make, so a recent one blocks another. */\nfunction tooSoon(db: Db, now: number): Envelope | undefined {\n const cp = getCheckpoint(db, 'connections');\n const age = cp === undefined ? Number.POSITIVE_INFINITY : now - cp.lastSuccessfulAt;\n if (age >= CONNECTIONS_MIN_INTERVAL_MS) return undefined;\n const days = Math.ceil((CONNECTIONS_MIN_INTERVAL_MS - age) / 86_400_000);\n return err(\n 'sync',\n 'BUDGET_EXHAUSTED',\n `connections were synced ${Math.floor(age / 86_400_000)} days ago`,\n `This is the most expensive read in the tool and connections change slowly. Wait ${days} more day(s), or pass --force.`,\n );\n}\n\nasync function syncConnections(\n engine: Engine,\n db: Db,\n limit: number,\n force: boolean,\n now: number,\n): Promise<Envelope> {\n const before = urnsFor(db, 'connections');\n if (!force && before.size > 0) {\n const blocked = tooSoon(db, now);\n if (blocked !== undefined) return blocked;\n }\n\n const result = await engine.connections(limit);\n if (!result.ok) return err('sync', result.code, result.message, result.hint);\n\n const rows = rowsFrom(shapeAll(result.value.parsed.items, result.value.index));\n const stored = upsert(db, 'connections', rows, now);\n\n // A set difference is only meaningful if we actually saw the whole graph.\n // When LinkedIn claims more than we retrieved, removals are NOT inferable —\n // saying otherwise would report people as disconnected because of a limit.\n const claimed = result.value.parsed.meta.claimedCount;\n const seen = new Set(rows.map((r) => r.urn));\n const { removed, complete } = diffSnapshot(before, seen, claimed);\n if (removed.length > 0) removeUrns(db, 'connections', removed);\n\n setCheckpoint(db, {\n source: 'connections',\n lastSuccessfulAt: now,\n newestCreatedAt: null,\n headIds: [],\n // Honest: a snapshot, never a watermark.\n state: complete ? 'ok' : 'snapshot-partial',\n });\n\n return ok('sync', {\n source: 'connections',\n added: stored.added,\n updated: stored.updated,\n removed: removed.length,\n claimed,\n complete,\n meta: result.value.parsed.meta,\n note: complete\n ? undefined\n : `Only ${rows.length} of ${claimed} connections were retrieved, so removals could not be determined and none were applied. Raise --limit to complete the snapshot.`,\n });\n}\n\nexport async function runSync(\n source: string | undefined,\n limit: number,\n force: boolean,\n now = Date.now(),\n): Promise<Envelope> {\n if (source !== 'my-posts' && source !== 'connections') {\n return err(\n 'sync',\n 'INVALID_INPUT',\n `unknown sync source '${source ?? ''}'`,\n 'lnrelay sync my-posts | lnrelay sync connections',\n );\n }\n\n const session = loadSession();\n if (session.state === 'corrupt') {\n return err('sync', 'CACHE_CORRUPT', 'the stored session was unreadable', LAUNCH_HINT);\n }\n if (session.state === 'missing') {\n return err('sync', 'AUTH_FAILED', 'no session — run `lnrelay login` first', LAUNCH_HINT);\n }\n\n const engine = createEngine(session.session);\n\n try {\n const db = openDb(now);\n return source === 'my-posts'\n ? await syncMyPosts(engine, db, limit, now)\n : await syncConnections(engine, db, limit, force, now);\n } catch (e) {\n if (e instanceof CacheCorrupt) {\n return err(\n 'sync',\n 'CACHE_CORRUPT',\n e.message,\n `Moved to ${e.quarantinedTo}. A corrupt cache is NOT treated as empty — that would make this sync re-enumerate everything. Inspect it, then re-run.`,\n );\n }\n throw e;\n }\n}\n","// ─── The write transport ──────────────────────────────────────────────────────\n//\n// Writes go over LinkedIn's OWN self-serve OAuth scope, never Voyager. That is\n// the one legitimacy wedge an individual actually has: `w_member_social` is\n// self-serve — no partner review, no company verification, no screencast — and\n// it covers posting, commenting and reacting as the authenticated member.\n//\n// Reads have no such path (no self-serve read scope exists at all), which is\n// why they accept the Voyager risk. Writes do have one, so they do not get to\n// spend the same currency.\n//\n// The honest caveat, which belongs in the docs and not just here: OAuth makes\n// these writes SANCTIONED and materially lower-risk. It does not make the\n// surrounding tool ToS-compliant, and scopes and review rules can still change.\n//\n// A ConfirmedWrite is required to reach any function here. That value can only\n// be produced by commands/confirm.ts, at an interactive terminal, so the write\n// path is unreachable from a non-interactive agent by construction rather than\n// by policy.\n\nimport type { ConfirmedWrite } from '../commands/confirm.ts';\n\nconst API = 'https://api.linkedin.com';\n\nexport interface OAuthToken {\n accessToken: string;\n /** The member urn this token authorises, e.g. urn:li:person:ABC. */\n memberUrn: string;\n expiresAt: number;\n}\n\nexport interface WriteDeps {\n fetch: typeof globalThis.fetch;\n now: () => number;\n}\n\nexport type WriteResult =\n | { ok: true; id: string; url?: string }\n | { ok: false; code: string; message: string; hint?: string };\n\nfunction headers(token: OAuthToken): Record<string, string> {\n return {\n authorization: `Bearer ${token.accessToken}`,\n 'content-type': 'application/json',\n 'x-restli-protocol-version': '2.0.0',\n 'linkedin-version': '202601',\n };\n}\n\nfunction expired(token: OAuthToken, now: number): boolean {\n return token.expiresAt <= now;\n}\n\nasync function send(\n url: string,\n body: unknown,\n token: OAuthToken,\n deps: WriteDeps,\n): Promise<WriteResult> {\n if (expired(token, deps.now())) {\n return {\n ok: false,\n code: 'AUTH_FAILED',\n message: 'the OAuth token has expired',\n hint: 'Run `lnrelay oauth` to obtain a fresh token.',\n };\n }\n\n let res: Response;\n try {\n res = await deps.fetch(url, {\n method: 'POST',\n headers: headers(token),\n body: JSON.stringify(body),\n });\n } catch (e) {\n return { ok: false, code: 'FETCH_FAILED', message: (e as Error).message };\n }\n\n const text = await res.text();\n if (res.status === 201 || res.status === 200) {\n const id = res.headers.get('x-restli-id') ?? extractId(text);\n return {\n ok: true,\n id: id ?? '(unknown)',\n ...(id === null ? {} : { url: `https://www.linkedin.com/feed/update/${id}/` }),\n };\n }\n\n // No retries here either. An OAuth 429 is a quota signal, not an invitation.\n if (res.status === 429) {\n return {\n ok: false,\n code: 'RATE_LIMITED',\n message: 'LinkedIn throttled the write',\n hint: 'Not retried automatically. Wait, and check `lnrelay budget`.',\n };\n }\n if (res.status === 401 || res.status === 403) {\n return {\n ok: false,\n code: 'AUTH_FAILED',\n message: `LinkedIn rejected the token (${res.status})`,\n hint: 'The scope may not be granted. Check the app has \"Share on LinkedIn\" added.',\n };\n }\n return {\n ok: false,\n code: 'FETCH_FAILED',\n message: `write failed (${res.status})`,\n hint: text.slice(0, 300),\n };\n}\n\nfunction extractId(body: string): string | null {\n return body.match(/\"id\"\\s*:\\s*\"([^\"]+)\"/)?.[1] ?? null;\n}\n\n/** Post to the member's own feed. */\nexport function share(\n confirmed: ConfirmedWrite<{ text: string; visibility: 'PUBLIC' | 'CONNECTIONS' }>,\n token: OAuthToken,\n deps: WriteDeps,\n): Promise<WriteResult> {\n return send(\n `${API}/rest/posts`,\n {\n author: token.memberUrn,\n commentary: confirmed.payload.text,\n visibility: confirmed.payload.visibility,\n distribution: {\n feedDistribution: 'MAIN_FEED',\n targetEntities: [],\n thirdPartyDistributionChannels: [],\n },\n lifecycleState: 'PUBLISHED',\n isReshareDisabledByAuthor: false,\n },\n token,\n deps,\n );\n}\n\n/** Comment on a post as the member. */\nexport function comment(\n confirmed: ConfirmedWrite<{ postUrn: string; text: string }>,\n token: OAuthToken,\n deps: WriteDeps,\n): Promise<WriteResult> {\n const encoded = encodeURIComponent(confirmed.payload.postUrn);\n return send(\n `${API}/rest/socialActions/${encoded}/comments`,\n {\n actor: token.memberUrn,\n object: confirmed.payload.postUrn,\n message: { text: confirmed.payload.text },\n },\n token,\n deps,\n );\n}\n\n/** React to a post as the member. */\nexport function react(\n confirmed: ConfirmedWrite<{ postUrn: string; type: string }>,\n token: OAuthToken,\n deps: WriteDeps,\n): Promise<WriteResult> {\n return send(\n `${API}/rest/reactions?actor=${encodeURIComponent(token.memberUrn)}`,\n { root: confirmed.payload.postUrn, reactionType: confirmed.payload.type },\n token,\n deps,\n );\n}\n","// ─── Commenting, over SDUI ────────────────────────────────────────────────────\n//\n// The payload LinkedIn's own client sends, rebuilt from a live capture\n// (docs/research/W5). Unlike a reaction, a comment is not self-contained: it\n// carries a binding key and a trackingId harvested from the rendered post page\n// — see sdui-harvest.ts, which also PROVES the key belongs to the intended post\n// before any of this runs.\n//\n// The five state keys are one key body under five prefixes. `commentBoxText` is\n// the plain string, `richCommentBoxText` the same text as a TextModel, and the\n// remaining three are empty strings for the link preview and image slots. All\n// five are echoed in `requestedStateKeys`. Sending four of five, or omitting an\n// empty one, has never been observed and is not something to improvise.\n\nimport type { ConfirmedWrite } from '../commands/confirm.ts';\nimport type { Client } from './client.ts';\nimport { keyMatchesPost } from './sdui-harvest.ts';\n\nconst SDUI_ACTION = 'https://www.linkedin.com/flagship-web/rsc-action/actions/server-request';\n\nexport const COMMENT_URL = `${SDUI_ACTION}?sduiid=com.linkedin.sdui.comments.createComment`;\n\nconst SCREEN_ID = 'com.linkedin.sdui.flagshipnav.feed.UpdateDetail';\n\n/** The five slots the comment box keeps state in, in the captured order. */\nconst STATE_PREFIXES = [\n 'commentBoxText',\n 'richCommentBoxText',\n 'commentBoxLinkPreviewIngestedContentId',\n 'commentBoxExternalImageUrl',\n 'commentBoxExternalImageId',\n] as const;\n\n/**\n * Numeric feedType per rendered context.\n *\n * Only FEED_DETAIL has been observed, carrying 3. A permalink fetched over\n * plain HTTP can hand back a `FeedType_FEED` key instead, whose number is\n * UNKNOWN — and an invented integer here would be a malformed write against a\n * real post, so that case refuses rather than guesses.\n */\nconst FEED_TYPES: Record<string, number> = { FEED_DETAIL: 3 };\n\n/** Everything after the `commentBoxText-` prefix — shared by all five keys. */\nexport function keyBody(bindingKey: string): string {\n return bindingKey.replace(/^commentBoxText-/, '');\n}\n\nexport function feedTypeFor(bindingKey: string): number | null {\n const suffix = /FeedType_([A-Z_]+)$/.exec(bindingKey)?.[1];\n return suffix === undefined ? null : (FEED_TYPES[suffix] ?? null);\n}\n\nfunction stateKey(prefix: string, body: string): string {\n return `${prefix}-${body}`;\n}\n\nexport interface CommentTokens {\n bindingKey: string;\n trackingId: string;\n}\n\n/** The `states` array: the text in two encodings, and three empty slots. */\nfunction states(text: string, body: string): unknown[] {\n return STATE_PREFIXES.map((prefix) => {\n const key = stateKey(prefix, body);\n const base = {\n key,\n namespace: 'MemoryNamespace',\n protoKey: { $type: 'proto.sdui.Key', value: { $case: 'id', id: key } },\n };\n if (prefix === 'commentBoxText') {\n return { ...base, value: text, originalProtoCase: 'stringValue' };\n }\n if (prefix === 'richCommentBoxText') {\n return {\n ...base,\n value: { text, attribute: [], $type: 'TextModel', source: 'local' },\n originalProtoCase: 'textModelForWrite',\n };\n }\n return { ...base, value: '', originalProtoCase: 'stringValue' };\n });\n}\n\nexport function commentBody(\n activityId: string,\n text: string,\n tokens: CommentTokens,\n feedType: number,\n): Record<string, unknown> {\n const body = keyBody(tokens.bindingKey);\n const activityUrn = { activityUrn: { activityId } };\n const binding = (prefix: string) => ({\n key: stateKey(prefix, body),\n namespace: 'MemoryNamespace',\n });\n\n const payload = {\n // The live client's handle for its optimistically-rendered comment. Server\n // relevance unknown, but it is cheap to send and being faithful to a\n // captured shape beats trimming fields whose purpose we are guessing at.\n optimisticKey: `auto-component-${crypto.randomUUID()}`,\n collection: {\n updateKey: {\n feedType,\n items: [\n { feedUpdateUrn: { updateUrnActivityUrn: activityUrn }, trackingId: tokens.trackingId },\n ],\n aggregationType: 0,\n isVideoCarousel: false,\n },\n threadUrn: { threadUrnActivityThreadUrn: activityUrn },\n },\n commentFieldBinding: binding('commentBoxText'),\n richCommentFieldBinding: binding('richCommentBoxText'),\n linkPreviewIngestedContentId: binding('commentBoxLinkPreviewIngestedContentId'),\n externalImageUrl: binding('commentBoxExternalImageUrl'),\n externalImageId: binding('commentBoxExternalImageId'),\n };\n\n const requestedStateKeys = STATE_PREFIXES.map((p) => ({\n key: { value: { $case: 'id', id: stateKey(p, body) } },\n }));\n\n const args = {\n $type: 'proto.sdui.actions.requests.RequestedArguments',\n requestedStateKeys,\n payload,\n requestMetadata: { $type: 'proto.sdui.common.RequestMetadata' },\n };\n\n return {\n requestId: 'com.linkedin.sdui.comments.createComment',\n serverRequest: {\n requestId: 'com.linkedin.sdui.comments.createComment',\n requestedArguments: args,\n isApfcEnabled: false,\n isStreaming: false,\n rumPageKey: '',\n },\n states: states(text, body),\n requestedArguments: {\n ...args,\n states: states(text, body),\n screenId: SCREEN_ID,\n knownTemplateIds: [],\n },\n };\n}\n\nexport type CommentResult =\n | { ok: true; id: string | null }\n | { ok: false; code: string; message: string; hint?: string };\n\n/**\n * Post a comment. Every guard here exists because a wrong binding does not\n * error — it comments somewhere else, publicly, under the owner's name.\n */\nexport async function comment(\n confirmed: ConfirmedWrite<{ activityId: string; text: string; tokens: CommentTokens }>,\n client: Client,\n): Promise<CommentResult> {\n const { activityId, text, tokens } = confirmed.payload;\n\n if (!keyMatchesPost(tokens.bindingKey, activityId)) {\n return {\n ok: false,\n code: 'INVALID_INPUT',\n message: 'the harvested binding key does not belong to this post',\n hint: 'Refusing to send: this is how a comment lands on the wrong post. Re-harvest.',\n };\n }\n\n const feedType = feedTypeFor(tokens.bindingKey);\n if (feedType === null) {\n return {\n ok: false,\n code: 'NOT_IMPLEMENTED',\n message: `unknown feed type in binding key '${tokens.bindingKey.slice(-24)}'`,\n hint:\n 'Only FeedType_FEED_DETAIL has been observed, carrying feedType 3. Inventing a number ' +\n 'for another context would be a malformed write against a real post. Capture the ' +\n 'missing one with `bun run scripts/observe-write.ts`.',\n };\n }\n\n const result = await client.request({\n url: COMMENT_URL,\n method: 'POST',\n body: commentBody(activityId, text, tokens, feedType),\n spendClass: 'write',\n operation: 'comment.create',\n });\n\n if (!result.ok) {\n const out: CommentResult = { ok: false, code: result.code, message: result.message };\n if (result.hint !== undefined) out.hint = result.hint;\n return out;\n }\n return { ok: true, id: activityId };\n}\n","// ─── Reactions, over SDUI ─────────────────────────────────────────────────────\n//\n// Reactions do not go to Voyager. They go to LinkedIn's Server-Driven UI\n// surface, over React Server Component actions:\n//\n// POST /flagship-web/rsc-action/actions/server-request\n// ?sduiid=com.linkedin.sdui.reactions.create (or .delete)\n//\n// This was found by capture, on 2026-08-13, and it is why two earlier attempts\n// to observe a reaction recorded nothing: the observer filtered for\n// `/voyager/api/` and was structurally blind to a surface that does not live\n// there. Everything in this file came off the wire; none of it is inferred.\n//\n// It also settles a question the research could not. W1 found exactly one OSS\n// sample for reacting — `POST /voyagerSocialDashReactions?threadUrn=urn:li:\n// activity:<id>` with `{\"reactionType\":\"LIKE\"}` — which contradicted this\n// project's own verified read-side finding that reactions key off a ugcPost\n// urn. Both were wrong for the current client, and the argument was moot:\n// the live surface takes neither urn form. It takes a nested object holding\n// the BARE NUMERIC ID, and a reaction type with a `ReactionType_` prefix.\n// Shipping that sample would have failed against a superseded endpoint.\n//\n// WHY REACTIONS ARE SHIPPABLE AND COMMENTS ARE NOT. The reaction payload is\n// self-contained: an id, a type, a source, and a fixed screen id — 1,481 bytes\n// with no server-issued token in it. `com.linkedin.sdui.comments.createComment`\n// carries a `trackingId` from the feed render and an opaque binding key\n// (`commentBoxText-CgsIgIC6…`) that only exists once a page has been rendered,\n// so replaying it means fetching the SDUI screen first to harvest them. That\n// is a real two-step protocol, not a missing constant, and it is why `comment`\n// stays unimplemented.\n\nimport type { ConfirmedWrite } from '../commands/confirm.ts';\nimport type { Client } from './client.ts';\n\nconst SDUI_ACTION = 'https://www.linkedin.com/flagship-web/rsc-action/actions/server-request';\n\n/** The screen the live client declares when reacting from a post detail view. */\nconst SCREEN_ID = 'com.linkedin.sdui.flagshipnav.feed.UpdateDetail';\n\n/** All six the UI offers, observed cycling through every one. */\nexport const REACTIONS = [\n 'LIKE',\n 'PRAISE',\n 'EMPATHY',\n 'INTEREST',\n 'APPRECIATION',\n 'ENTERTAINMENT',\n] as const;\n\nexport type Reaction = (typeof REACTIONS)[number];\n\n/**\n * What each enum actually renders as in the UI. These do NOT match: `PRAISE`\n * shows as \"Celebrate\", `INTEREST` as \"Insightful\". Verified live — a\n * `--type PRAISE` produced a Celebrate. Surfaced in the confirmation prompt so\n * nobody discovers the mismatch by putting the wrong reaction on a real post.\n */\nconst LABELS: Record<Reaction, string> = {\n LIKE: 'Like',\n PRAISE: 'Celebrate',\n EMPATHY: 'Love',\n INTEREST: 'Insightful',\n APPRECIATION: 'Support',\n ENTERTAINMENT: 'Funny',\n};\n\nexport function reactionLabel(reaction: Reaction): string {\n return LABELS[reaction];\n}\n\nexport function reactionUrl(op: 'create' | 'delete'): string {\n return `${SDUI_ACTION}?sduiid=com.linkedin.sdui.reactions.${op}`;\n}\n\nexport interface ReactionTarget {\n threadUrn: Record<string, unknown>;\n /** `Update` for a post, `Comment` for a comment. Not interchangeable. */\n reactionSource: 'Update' | 'Comment';\n}\n\n/**\n * Build the target object for a post or a comment.\n *\n * A post is identified by its bare numeric activity id — no urn string reaches\n * the wire. A comment needs both its own id AND its parent thread, because a\n * comment id is only unique within a thread.\n *\n * Throws rather than returning a partial target: an empty threadUrn is a\n * well-formed request to react to nothing, and we have no idea what LinkedIn\n * does with one.\n */\nexport function targetFor(urn: string): ReactionTarget {\n const comment = /^urn:li:comment:\\((urn:li:activity:\\d+),(\\d+)\\)$/.exec(urn);\n if (comment !== null) {\n return {\n threadUrn: {\n threadUrnCommentThreadUrn: {\n commentUrn: { commentId: comment[2] as string, thread: comment[1] as string },\n },\n },\n reactionSource: 'Comment',\n };\n }\n\n const activity = /^urn:li:(?:activity|ugcPost|share):(\\d+)$/.exec(urn);\n if (activity !== null) {\n return {\n threadUrn: {\n threadUrnActivityThreadUrn: { activityUrn: { activityId: activity[1] as string } },\n },\n reactionSource: 'Update',\n };\n }\n\n throw new Error(\n `'${urn}' does not identify a post or a comment — expected urn:li:activity:<id> or urn:li:comment:(urn:li:activity:<id>,<id>)`,\n );\n}\n\nexport interface ReactionPayload {\n threadUrn: Record<string, unknown>;\n reactionType: string;\n reactionSource: string;\n}\n\nexport function reactionPayload(target: ReactionTarget, reaction: Reaction): ReactionPayload {\n return {\n threadUrn: target.threadUrn,\n reactionType: `ReactionType_${reaction}`,\n reactionSource: target.reactionSource,\n };\n}\n\ninterface RequestedArguments {\n $type: string;\n requestedStateKeys: unknown[];\n payload: ReactionPayload;\n requestMetadata: { $type: string };\n states?: unknown[];\n screenId?: string;\n knownTemplateIds?: unknown[];\n}\n\nexport interface SduiBody {\n requestId: string;\n serverRequest: {\n requestId: string;\n requestedArguments: RequestedArguments;\n isApfcEnabled: boolean;\n isStreaming: boolean;\n rumPageKey: string;\n };\n states: unknown[];\n requestedArguments: RequestedArguments;\n}\n\n/**\n * The request body, mirroring the live client — including the fact that it\n * sends the arguments TWICE, once nested under `serverRequest` and once at the\n * top level. That is not a mistake in the capture; both copies were present in\n * all 56 recorded calls, so both are reproduced rather than tidied away.\n *\n * The client also sends an `onClientRequestFailureAction` block describing a\n * toast to show and state to roll back on failure. That is pure client-side UI\n * instruction with nothing for the server to act on, so it is omitted — the\n * one deliberate departure from the captured shape, noted here so a future\n * failure has somewhere to look.\n */\nexport function sduiBody(\n op: 'create' | 'delete',\n target: ReactionTarget,\n reaction: Reaction,\n): SduiBody {\n const requestId = `com.linkedin.sdui.reactions.${op}`;\n const payload = reactionPayload(target, reaction);\n const args: RequestedArguments = {\n $type: 'proto.sdui.actions.requests.RequestedArguments',\n requestedStateKeys: [],\n payload,\n requestMetadata: { $type: 'proto.sdui.common.RequestMetadata' },\n };\n\n return {\n requestId,\n serverRequest: {\n requestId,\n requestedArguments: args,\n isApfcEnabled: false,\n isStreaming: false,\n rumPageKey: '',\n },\n states: [],\n requestedArguments: {\n ...args,\n states: [],\n screenId: SCREEN_ID,\n knownTemplateIds: [],\n },\n };\n}\n\nexport type WriteResult =\n | { ok: true; id: string | null; note?: string }\n | { ok: false; code: string; message: string; hint?: string };\n\n/** Add or remove a reaction. Unreachable without a human-confirmed write. */\nexport async function react(\n confirmed: ConfirmedWrite<{ urn: string; type: Reaction; remove: boolean }>,\n client: Client,\n): Promise<WriteResult> {\n const { urn, type, remove } = confirmed.payload;\n\n let target: ReactionTarget;\n try {\n target = targetFor(urn);\n } catch (e) {\n return { ok: false, code: 'INVALID_INPUT', message: (e as Error).message };\n }\n\n const op = remove ? 'delete' : 'create';\n const result = await client.request({\n url: reactionUrl(op),\n method: 'POST',\n body: sduiBody(op, target, type),\n spendClass: 'write',\n operation: `reaction.${op}`,\n });\n\n if (result.ok) return { ok: true, id: urn };\n\n const out: WriteResult = { ok: false, code: result.code, message: result.message };\n out.hint =\n result.hint ??\n 'This surface was captured from the live client but has never been replayed by this tool. ' +\n 'If it refuses, the first thing to try is sending `x-li-page-instance` and `x-li-track`, ' +\n 'which the browser sends here and which our verified read header set deliberately omits.';\n return out;\n}\n","// ─── Choosing which surface a write goes over ─────────────────────────────────\n//\n// Two transports exist and they are NOT equivalent:\n//\n// oauth LinkedIn's own w_member_social scope. Sanctioned. Needs a\n// developer app, which needs a company Page.\n// voyager The private API, with the same cookies the reads use. Breaches\n// §8.2. Needs nothing but a login.\n//\n// OAuth wins whenever it is available. Voyager is the fallback for the case\n// that made it necessary: someone with no company has no Page, and therefore no\n// sanctioned way to post to their own feed from their own tools.\n//\n// docs/DESIGN.md's rule was \"never fall back to Voyager SILENTLY\", and every\n// part of that word is load-bearing here. The choice is reported in the\n// envelope, rendered in the confirmation prompt before the human types the\n// token, and carries a different risk sentence. What is forbidden is the user\n// not knowing which surface their post went over — not the fallback itself.\n\nimport type { Session } from '../engine/auth.ts';\nimport type { OAuthToken } from '../engine/oauth-write.ts';\n\nexport type Transport =\n | { kind: 'oauth'; token: OAuthToken }\n | { kind: 'voyager'; session: Session };\n\nexport interface TransportInputs {\n token: OAuthToken | null;\n session: Session | null;\n now: number;\n}\n\nexport type TransportChoice =\n | { ok: true; transport: Transport; note?: string }\n | { ok: false; message: string; hint: string };\n\nconst NO_CREDENTIAL_HINT = [\n 'Two ways to write, and you need one of them:',\n '',\n ' Sanctioned lnrelay oauth login --client-id <id>',\n ' Needs a developer app, which needs a LinkedIn Page.',\n '',\n ' Unsanctioned lnrelay login',\n ' Uses the same cookies as reads. No Page needed. Breaches §8.2',\n ' and puts the account at risk — every write still asks first.',\n].join('\\n');\n\n/**\n * Pick a transport, preferring the sanctioned one.\n *\n * An EXPIRED OAuth token deliberately does not silently demote to Voyager: the\n * user chose the sanctioned path, and quietly moving them onto the private API\n * because a token aged out is exactly the substitution the design forbids. They\n * are told to re-login instead, and can pass --via voyager if they mean it.\n */\nexport function chooseTransport(\n inputs: TransportInputs,\n requested?: 'oauth' | 'voyager',\n): TransportChoice {\n const { token, session, now } = inputs;\n const tokenLive = token !== null && token.expiresAt > now;\n\n if (requested === 'oauth') {\n if (tokenLive) return { ok: true, transport: { kind: 'oauth', token: token as OAuthToken } };\n return {\n ok: false,\n message: token === null ? 'no OAuth token stored' : 'the OAuth token has expired',\n hint: 'Run `lnrelay oauth login --client-id <id>`.',\n };\n }\n\n if (requested === 'voyager') {\n if (session !== null) return { ok: true, transport: { kind: 'voyager', session } };\n return {\n ok: false,\n message: 'no LinkedIn session — a Voyager write needs one',\n hint: 'Run `lnrelay login` to mint one from your own browser.',\n };\n }\n\n if (tokenLive) return { ok: true, transport: { kind: 'oauth', token: token as OAuthToken } };\n\n if (token !== null && session !== null) {\n return {\n ok: false,\n message: 'the OAuth token has expired',\n hint:\n 'Run `lnrelay oauth login --client-id <id>` to renew it. You do have a browser session, ' +\n 'so `--via voyager` would also work — but that is the private API, and swapping you onto ' +\n 'it because a token aged out is not a decision this tool will make for you.',\n };\n }\n\n if (session !== null) {\n return {\n ok: true,\n transport: { kind: 'voyager', session },\n note: 'No OAuth token, so this write goes over the private API. See the prompt.',\n };\n }\n\n return {\n ok: false,\n message: 'no way to write — no OAuth token and no session',\n hint: NO_CREDENTIAL_HINT,\n };\n}\n","// Write command runners. Every one of these stops and asks a human before it\n// sends anything, and makes zero network calls on the path where it doesn't.\n\nimport { buildHeaders } from '../engine/auth.ts';\nimport { createLiveClient } from '../engine/index.ts';\nimport { share as sendShare } from '../engine/oauth-write.ts';\nimport { type CommentTokens, comment as sduiComment } from '../engine/sdui-comment.ts';\nimport { extractCommentTokens } from '../engine/sdui-harvest.ts';\nimport {\n type CommentRef,\n parseCommentUrn,\n replyToComment,\n runCommentAction,\n UPDATE_OP,\n} from '../engine/sdui-menu.ts';\nimport {\n type Reaction,\n reactionLabel,\n REACTIONS as SDUI_REACTIONS,\n react as sduiReact,\n} from '../engine/sdui-write.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { share as voyagerShare } from '../engine/voyager-write.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { ConfirmDeps, WritePlan } from './confirm.ts';\nimport { gateWrite, recordHarvestSpend, reserve, terminalDeps } from './gate.ts';\nimport { loadToken, OAUTH_SETUP } from './token.ts';\nimport { chooseTransport, type Transport } from './transport.ts';\n\ninterface WriteContext {\n transport: Transport;\n now: number;\n note?: string;\n}\n\n/** The urn a write is authored as, for the confirmation summary. */\nfunction authorLine(transport: Transport): string {\n return transport.kind === 'oauth'\n ? `as ${transport.token.memberUrn}`\n : `as ${transport.session.ownerUrn ?? 'you (browser session)'}`;\n}\n\nfunction prepare(command: string, now: number, via?: 'oauth' | 'voyager'): WriteContext | Envelope {\n const session = loadSession();\n const choice = chooseTransport(\n { token: loadToken(), session: session.state === 'ok' ? session.session : null, now },\n via,\n );\n if (!choice.ok) {\n return err(command, 'AUTH_FAILED', choice.message, `${choice.hint}\\n\\n${OAUTH_SETUP}`);\n }\n const refused = reserve(command, now);\n if (refused !== null) return refused;\n const ctx: WriteContext = { transport: choice.transport, now };\n if (choice.note !== undefined) ctx.note = choice.note;\n return ctx;\n}\n\nasync function gate<T>(\n command: string,\n plan: WritePlan<T>,\n ctx: WriteContext,\n deps: ConfirmDeps,\n): Promise<{ confirmed: Parameters<typeof sendShare>[0] } | Envelope> {\n // Only the OAuth transport issues its own fetch; everything else goes\n // through the client, which does its own accounting.\n const gated = await gateWrite(command, plan, ctx.now, deps, {\n commitSpend: ctx.transport.kind === 'oauth',\n });\n if ('ok' in gated) return gated;\n return { confirmed: gated.confirmed as never };\n}\n\nexport async function runShare(\n text: string | undefined,\n visibility: string,\n now = Date.now(),\n deps: ConfirmDeps = terminalDeps(),\n via?: 'oauth' | 'voyager',\n): Promise<Envelope> {\n if (text === undefined || text.trim() === '') {\n return err('share', 'INVALID_INPUT', 'text is required', 'lnrelay share \"<text>\"');\n }\n const vis = visibility === 'connections' ? 'CONNECTIONS' : 'PUBLIC';\n const ctx = prepare('share', now, via);\n if ('ok' in ctx) return ctx;\n\n const plan: WritePlan<{ text: string; visibility: 'PUBLIC' | 'CONNECTIONS' }> = {\n action: 'post to your feed',\n payload: { text, visibility: vis },\n summary: [authorLine(ctx.transport), `content \"${text}\"`, `audience ${vis}`],\n reversibility:\n 'deletable with `lnrelay delete <urn>`, but it is public under your name the moment it ' +\n 'lands and anyone who saw it cannot un-see it',\n transport: ctx.transport.kind,\n };\n\n const gated = await gate('share', plan, ctx, deps);\n if ('ok' in gated) return gated;\n\n const result =\n ctx.transport.kind === 'oauth'\n ? await sendShare(gated.confirmed, ctx.transport.token, {\n fetch: globalThis.fetch,\n now: () => now,\n })\n : await voyagerShare(gated.confirmed, createLiveClient(ctx.transport.session));\n\n if (!result.ok) return err('share', result.code, result.message, result.hint);\n return ok('share', {\n id: result.id ?? null,\n transport: ctx.transport.kind,\n url: 'url' in result ? result.url : undefined,\n note: 'note' in result ? result.note : ctx.note,\n });\n}\n\n/** The numeric id inside an activity urn, or null. */\nfunction activityIdOf(urn: string): string | null {\n return /^urn:li:(?:activity|ugcPost|share):(\\d+)$/.exec(urn)?.[1] ?? null;\n}\n\n/**\n * Fetch the rendered post page and harvest the comment tokens.\n *\n * This is a ~2.8 MB HTML GET, far heavier than any Voyager read here, and it\n * is unavoidable: the trackingId changes on every render, so it cannot be\n * cached even though the binding key can.\n */\nasync function harvest(\n activityId: string,\n session: Parameters<typeof createLiveClient>[0],\n now: number,\n): Promise<{ ok: true; tokens: CommentTokens } | Envelope> {\n // Account for it. This is the heaviest single request the tool makes, and\n // going through raw fetch bypassed the ledger, the cooldown and the pacing —\n // the exact unaccounted traffic the Permit type exists to prevent.\n const spent = reserve('comment', now);\n if (spent !== null) return spent;\n recordHarvestSpend(now);\n\n const headers = buildHeaders(session);\n let html: string;\n try {\n const res = await fetch(`https://www.linkedin.com/feed/update/urn:li:activity:${activityId}/`, {\n headers: {\n cookie: headers.cookie ?? '',\n 'user-agent': headers['user-agent'] ?? '',\n accept: 'text/html',\n },\n redirect: 'manual',\n });\n if (res.status !== 200) {\n return err('comment', 'FETCH_FAILED', `the post page returned ${res.status}`);\n }\n html = await res.text();\n } catch (e) {\n return err('comment', 'FETCH_FAILED', `could not load the post page: ${(e as Error).message}`);\n }\n\n const found = extractCommentTokens(html, activityId);\n if (!found.ok) return err('comment', 'SCHEMA_DRIFT', found.message, found.hint);\n return { ok: true, tokens: { bindingKey: found.bindingKey, trackingId: found.trackingId } };\n}\n\nexport async function runComment(\n postUrn: string | undefined,\n text: string | undefined,\n now = Date.now(),\n deps: ConfirmDeps = terminalDeps(),\n): Promise<Envelope> {\n if (postUrn === undefined || text === undefined || text.trim() === '') {\n return err(\n 'comment',\n 'INVALID_INPUT',\n 'a post urn and text are required',\n 'lnrelay comment <urn> \"<text>\"',\n );\n }\n // A comment urn is REFUSED here rather than treated as an edit. Someone\n // holding one most likely wants to reply to it, and silently overwriting it\n // instead would be the worst possible reading of the command. Editing has its\n // own verb; overloading is right when the operation is the same on different\n // types (`delete`), wrong when the operations differ.\n if (parseCommentUrn(postUrn) !== null) {\n return err(\n 'comment',\n 'INVALID_INPUT',\n 'that is a comment urn, not a post urn',\n `To change its text: lnrelay edit ${postUrn} \"<text>\". To answer it: ` +\n `lnrelay reply ${postUrn} \"<text>\". Pass the POST urn to add a top-level comment.`,\n );\n }\n const activityId = activityIdOf(postUrn);\n if (activityId === null) {\n return err(\n 'comment',\n 'INVALID_INPUT',\n `'${postUrn}' does not identify a post`,\n 'Pass urn:li:activity:<id>.',\n );\n }\n\n // The TTY check comes BEFORE the harvest, not just before the send. Harvesting\n // is a network call, and this tool's guarantee is \"no TTY, no write AND no\n // network call on that path\" — an agent shelling out non-interactively must\n // not cause LinkedIn traffic it cannot then use.\n if (!deps.isTty) {\n return err(\n 'comment',\n 'CONFIRMATION_REQUIRED',\n 'commenting needs a human to confirm it at an interactive terminal',\n 'No terminal is attached, so nothing was sent and no network call was made.',\n );\n }\n\n const ctx = prepare('comment', now, 'voyager');\n if ('ok' in ctx) return ctx;\n if (ctx.transport.kind !== 'voyager') {\n return err('comment', 'NOT_IMPLEMENTED', 'commenting is only implemented over the private API');\n }\n\n // Harvest after that, but before asking: a human should not approve a comment\n // we then turn out to be unable to send, and the tokens are part of what is\n // being approved.\n const harvested = await harvest(activityId, ctx.transport.session, now);\n if ('ok' in harvested && harvested.ok !== true) return harvested as Envelope;\n if (!('tokens' in harvested)) return harvested as Envelope;\n\n const plan: WritePlan<{ activityId: string; text: string; tokens: CommentTokens }> = {\n action: 'comment on a post',\n payload: { activityId, text, tokens: harvested.tokens },\n summary: [authorLine(ctx.transport), `on ${postUrn}`, `content \"${text}\"`],\n reversibility:\n 'deletable with `lnrelay delete <comment-urn>`; the author is notified immediately',\n transport: 'voyager',\n };\n\n const gated = await gate('comment', plan, ctx, deps);\n if ('ok' in gated) return gated;\n\n const result = await sduiComment(\n gated.confirmed as never,\n createLiveClient(ctx.transport.session),\n );\n return result.ok\n ? ok('comment', { on: postUrn })\n : err('comment', result.code, result.message, result.hint);\n}\n\n/** Change the text of a comment you wrote. Its own verb, deliberately. */\nexport async function runEdit(\n commentUrn: string | undefined,\n text: string | undefined,\n now = Date.now(),\n deps: ConfirmDeps = terminalDeps(),\n): Promise<Envelope> {\n if (commentUrn === undefined || text === undefined || text.trim() === '') {\n return err(\n 'edit',\n 'INVALID_INPUT',\n 'a comment urn and the new text are required',\n 'lnrelay edit <comment-urn> \"<text>\"',\n );\n }\n const ref: CommentRef | null = parseCommentUrn(commentUrn);\n if (ref === null) {\n return err(\n 'edit',\n 'INVALID_INPUT',\n `'${commentUrn}' is not a comment urn`,\n 'Only comments can be edited here — a published post cannot. Get the urn from ' +\n '`lnrelay post <activity-urn>`.',\n );\n }\n\n if (!deps.isTty) {\n return err(\n 'edit',\n 'CONFIRMATION_REQUIRED',\n 'editing needs a human to confirm it at an interactive terminal',\n 'No terminal is attached, so nothing was sent and no network call was made.',\n );\n }\n\n const ctx = prepare('edit', now, 'voyager');\n if ('ok' in ctx) return ctx;\n if (ctx.transport.kind !== 'voyager') {\n return err('edit', 'NOT_IMPLEMENTED', 'editing is only implemented over the private API');\n }\n\n const harvested = await harvest(ref.activityId, ctx.transport.session, now);\n if (!('tokens' in harvested)) return harvested as Envelope;\n\n const plan: WritePlan<{ urn: string; text: string }> = {\n action: 'edit your comment',\n payload: { urn: commentUrn, text },\n summary: [authorLine(ctx.transport), `comment ${commentUrn}`, `new text \"${text}\"`],\n reversibility:\n 'editable again, but the previous text is NOT recoverable here and LinkedIn marks the ' +\n 'comment as edited',\n transport: 'voyager',\n };\n\n const gated = await gate('edit', plan, ctx, deps);\n if ('ok' in gated) return gated;\n\n const result = await runCommentAction(\n ref,\n UPDATE_OP,\n harvested.tokens.trackingId,\n createLiveClient(ctx.transport.session),\n text,\n );\n return result.ok\n ? ok('edit', { edited: commentUrn })\n : err('edit', result.code, result.message, result.hint);\n}\n\nconst REACTIONS: readonly string[] = SDUI_REACTIONS;\n\nexport async function runReact(\n postUrn: string | undefined,\n type: string,\n now = Date.now(),\n deps: ConfirmDeps = terminalDeps(),\n remove = false,\n): Promise<Envelope> {\n const reaction = type.toUpperCase();\n if (postUrn === undefined) {\n return err(\n 'react',\n 'INVALID_INPUT',\n 'a post or comment urn is required',\n 'lnrelay react <urn> [--type LIKE] [--remove]',\n );\n }\n if (!REACTIONS.includes(reaction)) {\n return err(\n 'react',\n 'INVALID_INPUT',\n `unknown reaction '${type}'`,\n `one of: ${REACTIONS.join(', ')}`,\n );\n }\n const ctx = prepare('react', now, 'voyager');\n if ('ok' in ctx) return ctx;\n if (ctx.transport.kind !== 'voyager') {\n return err('react', 'NOT_IMPLEMENTED', 'reacting is only implemented over the private API');\n }\n\n const plan: WritePlan<{ urn: string; type: Reaction; remove: boolean }> = {\n action: remove ? 'remove a reaction' : 'react to a post',\n payload: { urn: postUrn, type: reaction as Reaction, remove },\n summary: [\n authorLine(ctx.transport),\n `on ${postUrn}`,\n `reaction ${reaction} — shows as \"${reactionLabel(reaction as Reaction)}\"${remove ? ' (REMOVING)' : ''}`,\n ],\n reversibility: remove\n ? 'you can react again; the author may have been notified the first time'\n : `removable with \\`lnrelay react ${postUrn} --remove --type ${reaction}\\` — the type is ` +\n 'required, LinkedIn deletes a specific reaction; the author is notified immediately',\n transport: 'voyager',\n };\n\n const gated = await gate('react', plan, ctx, deps);\n if ('ok' in gated) return gated;\n\n const result = await sduiReact(gated.confirmed as never, createLiveClient(ctx.transport.session));\n return result.ok\n ? ok('react', { id: result.id, removed: remove })\n : err('react', result.code, result.message, result.hint);\n}\n\n/**\n * Reply to a comment. Its own verb for the same reason `edit` is: replying and\n * commenting are different operations, and the urn alone cannot say which was\n * meant. Getting it wrong publishes a top-level comment on someone's thread.\n */\nexport async function runReply(\n commentUrn: string | undefined,\n text: string | undefined,\n now = Date.now(),\n deps: ConfirmDeps = terminalDeps(),\n): Promise<Envelope> {\n if (commentUrn === undefined || text === undefined || text.trim() === '') {\n return err(\n 'reply',\n 'INVALID_INPUT',\n 'a comment urn and the reply text are required',\n 'lnrelay reply <comment-urn> \"<text>\"',\n );\n }\n const parent: CommentRef | null = parseCommentUrn(commentUrn);\n if (parent === null) {\n return err(\n 'reply',\n 'INVALID_INPUT',\n `'${commentUrn}' is not a comment urn`,\n 'To comment on a POST, use `lnrelay comment <activity-urn>`. Comment urns come from ' +\n '`lnrelay post <activity-urn>`.',\n );\n }\n\n if (!deps.isTty) {\n return err(\n 'reply',\n 'CONFIRMATION_REQUIRED',\n 'replying needs a human to confirm it at an interactive terminal',\n 'No terminal is attached, so nothing was sent and no network call was made.',\n );\n }\n\n const ctx = prepare('reply', now, 'voyager');\n if ('ok' in ctx) return ctx;\n if (ctx.transport.kind !== 'voyager') {\n return err('reply', 'NOT_IMPLEMENTED', 'replying is only implemented over the private API');\n }\n\n const harvested = await harvest(parent.activityId, ctx.transport.session, now);\n if (!('tokens' in harvested)) return harvested as Envelope;\n\n const plan: WritePlan<{ parent: string; text: string }> = {\n action: 'reply to a comment',\n payload: { parent: commentUrn, text },\n summary: [authorLine(ctx.transport), `replying to ${commentUrn}`, `content \"${text}\"`],\n reversibility:\n 'deletable with `lnrelay delete <the reply urn>`; the comment author is notified immediately',\n transport: 'voyager',\n };\n\n const gated = await gate('reply', plan, ctx, deps);\n if ('ok' in gated) return gated;\n\n const result = await replyToComment(\n parent.activityId,\n parent,\n text,\n harvested.tokens.trackingId,\n createLiveClient(ctx.transport.session),\n );\n return result.ok\n ? ok('reply', { repliedTo: commentUrn })\n : err('reply', result.code, result.message, result.hint);\n}\n","// ─── Main-module detection ────────────────────────────────────────────────\n// Deciding whether an entry file was invoked directly (should run) vs merely\n// imported (should stay silent). The naive `fileURLToPath(url) === argv[1]`\n// check breaks under the npm bin symlink (…/bin/lnrelay → …/dist/cli.js): argv1\n// is the symlink, the module url is the real file — unequal — so the CLI would\n// silently exit 0. Resolving both through realpath fixes that. Pure + testable.\nimport { realpathSync } from 'node:fs';\nimport { basename } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\n/**\n * Decide whether the current module is the process entry point.\n * @param argv1 process.argv[1] — the invoked script path (may be a symlink).\n * @param moduleUrl import.meta.url of the entry module.\n * @param importMetaMain import.meta.main when the runtime provides it.\n */\nexport function isMainModule(\n argv1: string | undefined,\n moduleUrl: string,\n importMetaMain: boolean | undefined,\n): boolean {\n // The runtime told us explicitly — trust it (Bun always sets this).\n if (importMetaMain === true) return true;\n if (importMetaMain === false) return false;\n\n if (argv1 === undefined) return false;\n\n const modulePath = fileURLToPath(moduleUrl);\n try {\n return realpathSync(argv1) === realpathSync(modulePath);\n } catch {\n // realpath failed (path missing, permission, etc.) — fall back to a plain\n // string compare.\n return argv1 === modulePath;\n }\n}\n\n/**\n * Fail-loud heuristic: when isMainModule said \"not entry\" but argv1's basename\n * looks like one of our binaries, the user clearly invoked us and our detection\n * failed. Callers run anyway (after warning) rather than silently exiting.\n */\nexport function shouldForceEntry(argv1: string | undefined, binNames: string[]): boolean {\n if (argv1 === undefined) return false;\n return binNames.includes(basename(argv1));\n}\n\nexport interface EntryDecision {\n /** Whether the entry file should run its main routine. */\n run: boolean;\n /** A stderr warning to print first, or undefined when detection was clean. */\n warning: string | undefined;\n}\n\n/**\n * Consolidated entry decision. Runs when detected as main. Otherwise, ONLY when\n * the runtime gave no definitive answer (import.meta.main === undefined) and the\n * basename looks like one of our binaries, force-runs with a fail-loud warning —\n * an explicit import.meta.main === false is authoritative and never overridden.\n * binNames[0] is used as the label in the warning (the user-facing bin name).\n */\nexport function shouldRunAsEntry(\n argv1: string | undefined,\n moduleUrl: string,\n importMetaMain: boolean | undefined,\n binNames: string[],\n): EntryDecision {\n if (isMainModule(argv1, moduleUrl, importMetaMain)) {\n return { run: true, warning: undefined };\n }\n if (importMetaMain === undefined && shouldForceEntry(argv1, binNames)) {\n return {\n run: true,\n warning: `${binNames[0]}: entry detection failed — treating as main; report at github.com/gabros20/linkedin-relay/issues`,\n };\n }\n return { run: false, warning: undefined };\n}\n","import { bool, num, type ParsedArgs, parseArgs, str } from './args.ts';\nimport { runCacheStatus, runLocal, runPurge, runSourceRead } from './commands/cache.ts';\nimport { runDelete } from './commands/delete.ts';\nimport {\n type OutputOpts,\n runFeed,\n runLogin,\n runPost,\n runProfile,\n runReactions,\n runSearch,\n runWhoami,\n} from './commands/live.ts';\nimport { runBudget, runDoctor, runRisk } from './commands/local.ts';\nimport { runOauthLogin, runOauthLogout, runOauthStatus } from './commands/oauth.ts';\nimport { findCommand, helpText } from './commands/registry.ts';\nimport { runSync } from './commands/sync.ts';\nimport { runComment, runEdit, runReact, runReply, runShare } from './commands/write.ts';\nimport { shouldRunAsEntry } from './entry.ts';\nimport { err, exitCodeFor, toJson } from './output.ts';\nimport type { Envelope } from './types.ts';\n\n/** The output flags every collection command accepts. */\nfunction output(args: ParsedArgs): OutputOpts {\n const opts: OutputOpts = {};\n if (bool(args, 'raw')) opts.raw = true;\n if (bool(args, 'quiet')) opts.quiet = true;\n if (bool(args, 'retain')) opts.retain = true;\n if (bool(args, 'compact')) opts.compact = true;\n const fields = str(args, 'fields');\n if (fields !== undefined) opts.fields = fields;\n return opts;\n}\n\n/**\n * Which surface a write goes over.\n *\n * A misspelled `--via` is REFUSED rather than ignored. Ignoring it would mean\n * `--via voyger` silently posts over whichever transport happened to be the\n * default — the user asked for a specific surface and would be given another.\n */\nfunction via(args: ParsedArgs): 'oauth' | 'voyager' | 'invalid' | undefined {\n const value = str(args, 'via');\n if (value === undefined) return undefined;\n return value === 'oauth' || value === 'voyager' ? value : 'invalid';\n}\n\n/** `oauth` carries subcommands; bare `oauth` reports status and writes nothing. */\nasync function oauth(args: ParsedArgs): Promise<Envelope> {\n const sub = args.positionals[0] ?? 'status';\n if (sub === 'status') return runOauthStatus();\n if (sub === 'logout') return runOauthLogout();\n if (sub === 'login') {\n const opts: { clientId?: string; clientSecret?: string } = {};\n const id = str(args, 'client-id');\n const secret = str(args, 'client-secret');\n if (id !== undefined) opts.clientId = id;\n if (secret !== undefined) opts.clientSecret = secret;\n return runOauthLogin(opts);\n }\n return err(\n 'oauth',\n 'INVALID_INPUT',\n `unknown oauth subcommand '${sub}'`,\n 'one of: login, status, logout',\n );\n}\n\nexport async function dispatch(argv: string[], now: number): Promise<Envelope> {\n const args = parseArgs(argv);\n const { command } = args;\n\n if (command === undefined || command === 'help' || command === '--help') {\n process.stderr.write(`${helpText()}\\n`);\n return { ok: true, command: 'help', data: { commands: helpText() } };\n }\n\n const def = findCommand(command);\n if (def === undefined) {\n return err(\n command,\n 'UNKNOWN_COMMAND',\n `unknown command '${command}'`,\n 'run `lnrelay help` to list commands',\n );\n }\n\n if (!def.implemented) {\n return err(\n command,\n 'NOT_IMPLEMENTED',\n `'${command}' is specified but not yet built`,\n `Usage when it lands: ${def.usage.split('\\n')[0]}. See docs/PLAN.md for the phase it belongs to.`,\n );\n }\n\n switch (command) {\n case 'doctor':\n return runDoctor(now, bool(args, 'offline'));\n case 'budget':\n return runBudget(now, bool(args, 'reset-cooldown'), bool(args, 'confirm'));\n case 'risk':\n return runRisk(now);\n case 'local':\n return runLocal(\n args.positionals[0],\n str(args, 'source'),\n str(args, 'since'),\n num(args, 'limit') ?? 25,\n output(args),\n );\n case 'purge':\n return runPurge(\n str(args, 'scope') ?? (bool(args, 'all') ? 'all' : undefined),\n bool(args, 'confirm'),\n );\n case 'cache-status':\n return runCacheStatus();\n case 'connections':\n return runSourceRead(\n 'connections',\n args.positionals[0] ?? str(args, 'q'),\n num(args, 'limit') ?? 25,\n output(args),\n );\n case 'my-posts':\n return runSourceRead(\n 'my-posts',\n args.positionals[0] ?? str(args, 'q'),\n num(args, 'limit') ?? 25,\n output(args),\n );\n case 'sync':\n return runSync(args.positionals[0], num(args, 'limit') ?? 50, bool(args, 'force'), now);\n case 'login':\n return runLogin();\n case 'oauth':\n return oauth(args);\n case 'share': {\n const surface = via(args);\n if (surface === 'invalid') {\n return err(\n 'share',\n 'INVALID_INPUT',\n `unknown --via '${str(args, 'via') ?? ''}'`,\n 'one of: oauth, voyager. Omit it to prefer OAuth and fall back to Voyager.',\n );\n }\n return runShare(\n args.positionals[0],\n str(args, 'visibility') ?? 'public',\n now,\n undefined,\n surface,\n );\n }\n case 'comment':\n return runComment(args.positionals[0], args.positionals[1], now);\n case 'edit':\n return runEdit(args.positionals[0], args.positionals[1], now);\n case 'reply':\n return runReply(args.positionals[0], args.positionals[1], now);\n case 'react':\n return runReact(\n args.positionals[0],\n str(args, 'type') ?? 'LIKE',\n now,\n undefined,\n bool(args, 'remove'),\n );\n case 'delete':\n return runDelete(args.positionals[0], now, undefined, bool(args, 'quiet'));\n case 'whoami':\n return runWhoami(bool(args, 'raw'));\n case 'profile':\n return runProfile(args.positionals[0], bool(args, 'raw'));\n case 'feed':\n return runFeed(num(args, 'limit') ?? 10, output(args));\n case 'post':\n return runPost(args.positionals[0], num(args, 'limit') ?? 20, output(args));\n case 'reactions':\n return runReactions(args.positionals[0], num(args, 'limit') ?? 20, output(args));\n case 'search':\n return runSearch(\n args.positionals[0],\n args.positionals[1],\n num(args, 'limit') ?? 10,\n output(args),\n );\n default:\n return err(command, 'NOT_IMPLEMENTED', `'${command}' has no runner wired`);\n }\n}\n\nconst entry = shouldRunAsEntry(process.argv[1], import.meta.url, import.meta.main, [\n 'lnrelay',\n 'linkedin-relay-mcp',\n]);\n\nif (entry.run) {\n if (entry.warning !== undefined) process.stderr.write(`${entry.warning}\\n`);\n // stdout carries ONLY a JSON envelope — including when something throws that\n // no runner anticipated. A stack trace on stdout would break every caller\n // that parses us, which is all of them.\n const envelope = await dispatch(process.argv.slice(2), Date.now()).catch((e: Error) =>\n err(\n process.argv[2] ?? 'unknown',\n 'UNEXPECTED',\n e.message,\n 'This is a bug in lnrelay, not a LinkedIn failure. The stack trace is on stderr.',\n ),\n );\n // stdout carries ONLY the JSON envelope. Help text and progress go to stderr.\n if (envelope.command !== 'help') process.stdout.write(`${toJson(envelope)}\\n`);\n process.exit(exitCodeFor(envelope));\n}\n"],"mappings":";AAQO,SAAS,UAAU,MAA4B;AACpD,QAAM,CAAC,SAAS,GAAG,IAAI,IAAI;AAC3B,QAAM,cAAwB,CAAC;AAC/B,QAAM,QAA0C,CAAC;AAEjD,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,UAAM,QAAQ,KAAK,CAAC;AACpB,QAAI,UAAU,OAAW;AAEzB,QAAI,MAAM,WAAW,IAAI,GAAG;AAC1B,YAAM,MAAM,MAAM,MAAM,CAA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M;AAAA,EACjF;AAAA,EACA;AACF,CAAC;AAED,IAAI,MAAM,KAAK;AACb,MAAI,MAAM,YAAY,OAAW,SAAQ,OAAO,MAAM,GAAG,MAAM,OAAO;AAAA,CAAI;AAI1E,QAAM,WAAW,MAAM,SAAS,QAAQ,KAAK,MAAM,CAAC,GAAG,KAAK,IAAI,CAAC,EAAE;AAAA,IAAM,CAAC,MACxE;AAAA,MACE,QAAQ,KAAK,CAAC,KAAK;AAAA,MACnB;AAAA,MACA,EAAE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,MAAI,SAAS,YAAY,OAAQ,SAAQ,OAAO,MAAM,GAAG,OAAO,QAAQ,CAAC;AAAA,CAAI;AAC7E,UAAQ,KAAK,YAAY,QAAQ,CAAC;AACpC;","names":["mkdirSync","renameSync","mkdirSync","quarantine","renameSync","ledger","headers","ledger","headers","typeOf","count","postUrn","states","text","entry","VOYAGER","text","budgetLine","text","headers","postUrn","existsSync","ledger","existsSync","createInterface","text","existsSync","existsSync","createInterface","text","share","SDUI_ACTION","SCREEN_ID","text","SDUI_ACTION","SCREEN_ID","comment","via","text","share","headers","postUrn","REACTIONS"]}
|
|
1
|
+
{"version":3,"sources":["../src/args.ts","../src/cache/db.ts","../src/cache/store.ts","../src/engine/restli.ts","../src/format.ts","../src/output.ts","../src/commands/cache.ts","../src/engine/auth.ts","../src/progress.ts","../src/engine/budget.ts","../src/engine/classify.ts","../src/engine/client.ts","../src/engine/contracts.ts","../src/engine/parse.ts","../src/engine/index.ts","../src/engine/sdui-harvest.ts","../src/engine/sdui-menu.ts","../src/engine/session.ts","../src/engine/voyager-write.ts","../src/commands/gate.ts","../src/commands/confirm.ts","../src/commands/delete.ts","../src/commands/live.ts","../src/commands/local.ts","../src/commands/oauth.ts","../src/engine/oauth.ts","../src/commands/token.ts","../src/commands/registry.ts","../src/commands/sync.ts","../src/engine/oauth-write.ts","../src/engine/sdui-comment.ts","../src/engine/sdui-write.ts","../src/engine/voyager-reply.ts","../src/commands/transport.ts","../src/commands/write.ts","../src/entry.ts","../src/cli.ts"],"sourcesContent":["// Minimal argv parsing. Pure — takes an argv array, returns a plain object.\n\nexport interface ParsedArgs {\n command: string | undefined;\n positionals: string[];\n flags: Record<string, string | boolean>;\n}\n\nexport function parseArgs(argv: string[]): ParsedArgs {\n const [command, ...rest] = argv;\n const positionals: string[] = [];\n const flags: Record<string, string | boolean> = {};\n\n for (let i = 0; i < rest.length; i++) {\n const token = rest[i];\n if (token === undefined) continue;\n\n if (token.startsWith('--')) {\n const key = token.slice(2);\n const next = rest[i + 1];\n // A flag takes a value only when the next token isn't itself a flag.\n if (next !== undefined && !next.startsWith('--')) {\n flags[key] = next;\n i++;\n } else {\n flags[key] = true;\n }\n } else if (token.startsWith('-') && token.length > 1) {\n const key = token.slice(1);\n const next = rest[i + 1];\n if (next !== undefined && !next.startsWith('-')) {\n flags[key] = next;\n i++;\n } else {\n flags[key] = true;\n }\n } else {\n positionals.push(token);\n }\n }\n\n return { command, positionals, flags };\n}\n\nexport function bool(args: ParsedArgs, name: string): boolean {\n return args.flags[name] === true || args.flags[name] === 'true';\n}\n\nexport function str(args: ParsedArgs, name: string): string | undefined {\n const v = args.flags[name];\n return typeof v === 'string' ? v : undefined;\n}\n\nexport function num(args: ParsedArgs, name: string): number | undefined {\n const v = str(args, name);\n if (v === undefined) return undefined;\n const n = Number(v);\n return Number.isFinite(n) ? n : undefined;\n}\n","// ─── The local store ──────────────────────────────────────────────────────────\n//\n// SQLite (`bun:sqlite`, WAL) behind the same narrow load/save/query interface\n// the family's JSON store exposes. The family similarity that matters is the\n// interface, not the file format.\n//\n// SQLite was chosen for one specific reason: it makes \"corrupt\" a detectable,\n// per-source, quarantinable state. In a single JSON blob, corruption is\n// all-or-nothing and tells you nothing about which records survived — and on\n// this platform an empty-looking cache is what triggers a full re-sync against\n// the most hostile host in the research. TTL expiry as a transactional delete\n// rather than a whole-file rewrite is the second reason.\n//\n// Retention is enforced on the READ path, not by a schedule. There is no cron\n// to forget and no purge command to remember: the only code that can observe\n// expired third-party data is the code that deletes it first.\n\nimport { Database } from 'bun:sqlite';\nimport { mkdirSync, renameSync } from 'node:fs';\nimport { cacheDir, cachePath } from './store.ts';\n\nconst DB_FILE = 'cache.db';\n\n/** Third-party rows expire; owner rows do not. */\nexport const THIRD_PARTY_TTL_MS = 30 * 86_400_000;\n\nexport type Source = 'connections' | 'my-posts' | 'third-party';\n\nexport interface Record_ {\n urn: string;\n source: Source;\n /** Shaped JSON. Null once expired — the identity stub survives, the body does not. */\n body: string | null;\n text: string;\n firstSeenAt: number;\n updatedAt: number;\n expiresAt: number | null;\n}\n\n/**\n * Strip diacritics and lowercase, for matching only.\n *\n * SQLite's LIKE is not accent-insensitive, so `local \"kovary\"` found nothing\n * while \"kőváry\" found the record — the user types what is on their keyboard,\n * not what LinkedIn stored. Found by a real search on a Hungarian name.\n *\n * The folded form is stored ALONGSIDE the original, never instead of it: the\n * display value keeps its accents.\n */\nexport function fold(value: string): string {\n return value\n .normalize('NFD')\n .replace(/\\p{Diacritic}/gu, '')\n .toLowerCase();\n}\n\nconst TABLES = [\n `CREATE TABLE IF NOT EXISTS records (\n urn TEXT NOT NULL,\n source TEXT NOT NULL,\n body TEXT,\n text TEXT NOT NULL DEFAULT '',\n textFold TEXT NOT NULL DEFAULT '',\n firstSeenAt INTEGER NOT NULL,\n updatedAt INTEGER NOT NULL,\n expiresAt INTEGER,\n PRIMARY KEY (urn, source)\n )`,\n `CREATE TABLE IF NOT EXISTS checkpoints (\n source TEXT PRIMARY KEY,\n lastSuccessfulAt INTEGER NOT NULL,\n newestCreatedAt INTEGER,\n headIds TEXT NOT NULL DEFAULT '[]',\n state TEXT NOT NULL DEFAULT 'ok'\n )`,\n];\n\n// Indexes are created AFTER migrations, because an index may reference a column\n// a migration is about to add. Creating them alongside the tables meant an\n// existing store — where CREATE TABLE IF NOT EXISTS is a no-op — tried to index\n// a column it did not have yet, and threw on open.\nconst INDEXES = [\n 'CREATE INDEX IF NOT EXISTS records_source ON records(source)',\n 'CREATE INDEX IF NOT EXISTS records_fold ON records(textFold)',\n 'CREATE INDEX IF NOT EXISTS records_expires ON records(expiresAt)',\n];\n\nexport class CacheCorrupt extends Error {\n constructor(\n message: string,\n readonly quarantinedTo: string,\n ) {\n super(message);\n this.name = 'CacheCorrupt';\n }\n}\n\n/**\n * Open the store. A database that fails its integrity check is QUARANTINED and\n * the error is thrown — never silently replaced with an empty one, because an\n * empty cache is operationally active here: it is precisely what makes `sync`\n * enumerate everything again.\n */\nexport function openDb(now = Date.now()): Database {\n mkdirSync(cacheDir(), { recursive: true });\n const path = cachePath(DB_FILE);\n\n let db: Database;\n try {\n db = new Database(path, { create: true });\n const check = db.query('PRAGMA integrity_check').get() as { integrity_check?: string } | null;\n if (check?.integrity_check !== undefined && check.integrity_check !== 'ok') {\n throw new Error(`integrity_check: ${check.integrity_check}`);\n }\n } catch (e) {\n throw quarantine(path, (e as Error).message, now);\n }\n\n db.run('PRAGMA journal_mode = WAL');\n for (const stmt of TABLES) db.run(stmt);\n migrate(db);\n for (const stmt of INDEXES) db.run(stmt);\n sweepExpired(db, now);\n return db;\n}\n\n/**\n * Additive migrations for stores created before a column existed. Kept\n * idempotent and additive so an older cache upgrades in place rather than\n * being discarded — discarding it would trigger a full re-sync, which is the\n * expensive failure on this platform.\n */\nfunction migrate(db: Database): void {\n const columns = db.query('PRAGMA table_info(records)').all() as { name: string }[];\n if (!columns.some((c) => c.name === 'textFold')) {\n db.run(\"ALTER TABLE records ADD COLUMN textFold TEXT NOT NULL DEFAULT ''\");\n }\n // Backfill any row that predates the column.\n const stale = db\n .query(\"SELECT urn, source, text FROM records WHERE textFold = '' AND text != ''\")\n .all() as {\n urn: string;\n source: string;\n text: string;\n }[];\n if (stale.length > 0) {\n const update = db.query('UPDATE records SET textFold = ? WHERE urn = ? AND source = ?');\n db.transaction(() => {\n for (const r of stale) update.run(fold(r.text), r.urn, r.source);\n })();\n }\n}\n\nfunction quarantine(path: string, reason: string, now: number): CacheCorrupt {\n const stamp = new Date(now).toISOString().replace(/[:.]/g, '-');\n const target = cachePath('quarantine', stamp, DB_FILE);\n try {\n mkdirSync(cachePath('quarantine', stamp), { recursive: true });\n renameSync(path, target);\n } catch {\n // Even if it cannot be moved, the caller must still refuse to proceed.\n }\n return new CacheCorrupt(\n `the local cache was unreadable and has been quarantined: ${reason}`,\n target,\n );\n}\n\n/**\n * Expire third-party bodies. The row survives as an identity stub so a re-fetch\n * is a VISIBLE choice — the budget can say \"14 of these 20 are re-fetches of\n * expired records\" instead of quietly charging for them again.\n */\nexport function sweepExpired(db: Database, now = Date.now()): number {\n const result = db.run(\n \"UPDATE records SET body = NULL, text = '', textFold = '' WHERE expiresAt IS NOT NULL AND expiresAt <= ? AND body IS NOT NULL\",\n [now],\n );\n return result.changes;\n}\n\nexport function upsert(\n db: Database,\n source: Source,\n rows: { urn: string; body: unknown; text: string }[],\n now = Date.now(),\n): { added: number; updated: number } {\n const expiresAt = source === 'third-party' ? now + THIRD_PARTY_TTL_MS : null;\n let added = 0;\n let updated = 0;\n\n const exists = db.query('SELECT 1 FROM records WHERE urn = ? AND source = ?');\n const write = db.query(\n `INSERT INTO records (urn, source, body, text, textFold, firstSeenAt, updatedAt, expiresAt)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(urn, source) DO UPDATE SET\n body = excluded.body, text = excluded.text, textFold = excluded.textFold,\n updatedAt = excluded.updatedAt, expiresAt = excluded.expiresAt`,\n );\n\n db.transaction(() => {\n for (const row of rows) {\n if (exists.get(row.urn, source) === null) added++;\n else updated++;\n write.run(\n row.urn,\n source,\n JSON.stringify(row.body),\n row.text,\n fold(row.text),\n now,\n now,\n expiresAt,\n );\n }\n })();\n\n return { added, updated };\n}\n\nexport function count(db: Database, source?: Source): number {\n const row =\n source === undefined\n ? (db.query('SELECT COUNT(*) AS n FROM records').get() as { n: number })\n : (db.query('SELECT COUNT(*) AS n FROM records WHERE source = ?').get(source) as {\n n: number;\n });\n return row.n;\n}\n\n/** Offline search. Substring match over the flattened text of each record. */\nexport function search(\n db: Database,\n query: string,\n opts: { sources?: Source[]; since?: number; limit?: number } = {},\n): Record_[] {\n const sources = opts.sources ?? ['connections', 'my-posts', 'third-party'];\n const placeholders = sources.map(() => '?').join(',');\n const params: (string | number)[] = [...sources];\n\n let sql = `SELECT * FROM records WHERE source IN (${placeholders}) AND body IS NOT NULL`;\n if (query !== '') {\n // Match on the folded column with a folded query, so \"kovary\" finds\n // \"Kőváry\" and vice versa.\n sql += ' AND textFold LIKE ?';\n params.push(`%${fold(query)}%`);\n }\n if (opts.since !== undefined) {\n sql += ' AND updatedAt >= ?';\n params.push(opts.since);\n }\n sql += ' ORDER BY updatedAt DESC LIMIT ?';\n params.push(opts.limit ?? 25);\n\n return db.query(sql).all(...params) as Record_[];\n}\n\nexport function urnsFor(db: Database, source: Source): Set<string> {\n const rows = db.query('SELECT urn FROM records WHERE source = ?').all(source) as {\n urn: string;\n }[];\n return new Set(rows.map((r) => r.urn));\n}\n\nexport function removeUrns(db: Database, source: Source, urns: string[]): number {\n if (urns.length === 0) return 0;\n const stmt = db.query('DELETE FROM records WHERE source = ? AND urn = ?');\n let removed = 0;\n db.transaction(() => {\n for (const urn of urns) removed += stmt.run(source, urn).changes;\n })();\n return removed;\n}\n\n// ─── Checkpoints ──────────────────────────────────────────────────────────────\n\nexport interface Checkpoint {\n source: string;\n lastSuccessfulAt: number;\n newestCreatedAt: number | null;\n headIds: string[];\n /** `snapshot-partial` where no ordering exists — never a fabricated watermark. */\n state: 'ok' | 'snapshot-partial';\n}\n\nexport function getCheckpoint(db: Database, source: Source): Checkpoint | undefined {\n const row = db.query('SELECT * FROM checkpoints WHERE source = ?').get(source) as\n | (Omit<Checkpoint, 'headIds'> & { headIds: string })\n | null;\n if (row === null) return undefined;\n return { ...row, headIds: JSON.parse(row.headIds) as string[] };\n}\n\nexport function setCheckpoint(db: Database, cp: Checkpoint): void {\n db.run(\n `INSERT INTO checkpoints (source, lastSuccessfulAt, newestCreatedAt, headIds, state)\n VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(source) DO UPDATE SET\n lastSuccessfulAt = excluded.lastSuccessfulAt,\n newestCreatedAt = excluded.newestCreatedAt,\n headIds = excluded.headIds,\n state = excluded.state`,\n [cp.source, cp.lastSuccessfulAt, cp.newestCreatedAt, JSON.stringify(cp.headIds), cp.state],\n );\n}\n\nexport function purge(db: Database, scope: 'all' | 'third-party'): number {\n const result =\n scope === 'all'\n ? db.run('DELETE FROM records')\n : db.run(\"DELETE FROM records WHERE source = 'third-party'\");\n if (scope === 'all') db.run('DELETE FROM checkpoints');\n return result.changes;\n}\n","// ─── Local state store ────────────────────────────────────────────────────────\n//\n// Small, replaceable JSON state (the ledger, the cooldown, credentials\n// metadata) lives here. The research cache proper is SQLite and arrives in\n// Phase 4 — see docs/DESIGN.md §5.\n//\n// The rule that matters, and where we deliberately break with the family:\n//\n// never-throw is NOT never-fail.\n//\n// x-relay's store degrades a corrupt file to an empty object so a read never\n// crashes. That is right on X. Here it composes into a disaster: corrupt file →\n// empty cache → sync sees no prior state → full enumeration against the most\n// hostile platform in the research, triggered by a disk error. So a corrupt\n// file is quarantined and reported loudly. An empty result and a lost result\n// must be distinguishable on disk for exactly the same reason they must be\n// distinguishable in a parse.\n\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\n\nexport function cacheDir(): string {\n return process.env.LNRELAY_CACHE_DIR ?? join(homedir(), '.lnrelay');\n}\n\nexport function cachePath(...parts: string[]): string {\n return join(cacheDir(), ...parts);\n}\n\nexport type LoadResult<T> =\n | { state: 'ok'; value: T }\n | { state: 'missing' }\n | { state: 'corrupt'; quarantinedTo: string; reason: string };\n\n/**\n * Read a JSON file. Never throws. A file that exists but cannot be parsed is\n * MOVED to `quarantine/` and reported as corrupt — never silently treated as\n * absent, because \"we lost your data\" and \"you have no data\" lead to opposite\n * and non-interchangeable actions.\n */\nexport function loadJson<T>(path: string): LoadResult<T> {\n if (!existsSync(path)) return { state: 'missing' };\n\n let raw: string;\n try {\n raw = readFileSync(path, 'utf-8');\n } catch (e) {\n return quarantine(path, `unreadable: ${(e as Error).message}`);\n }\n\n try {\n return { state: 'ok', value: JSON.parse(raw) as T };\n } catch (e) {\n return quarantine(path, `unparseable JSON: ${(e as Error).message}`);\n }\n}\n\nfunction quarantine(path: string, reason: string): LoadResult<never> {\n const stamp = new Date().toISOString().replace(/[:.]/g, '-');\n const target = cachePath('quarantine', stamp, path.split('/').pop() ?? 'file');\n try {\n mkdirSync(dirname(target), { recursive: true });\n renameSync(path, target);\n } catch {\n // If we cannot even move it, still report corrupt — the caller must refuse\n // to proceed either way.\n }\n return { state: 'corrupt', quarantinedTo: target, reason };\n}\n\n/**\n * Write JSON atomically: a temp file in the same directory, then rename. A\n * torn write leaves the previous good file intact rather than a truncated one.\n */\nexport function saveJson(path: string, value: unknown): void {\n mkdirSync(dirname(path), { recursive: true });\n const tmp = `${path}.tmp`;\n writeFileSync(tmp, JSON.stringify(value, null, 2), { encoding: 'utf-8', mode: 0o600 });\n renameSync(tmp, path);\n}\n","// ─── Rest.li 2.0 variables grammar ────────────────────────────────────────────\n//\n// LinkedIn's Voyager GraphQL endpoint does NOT take JSON variables. It takes\n// Rest.li 2.0's own tuple grammar:\n//\n// (key:value,key2:value2) object literal\n// List(a,b,c) array\n// a | b OR-group inside a single filter value\n//\n// nested to arbitrary depth. Example (verified, R3 §2):\n//\n// ?queryId=voyagerSearchDashClusters.<hash>&variables=(start:0,query:(keywords:foo,\n// queryParameters:List((key:resultType,value:List(PEOPLE)))))\n//\n// Every client in the 90-repo corpus string-templates this. That is why adding a\n// filter is a guessing game for them: an unescaped comma or paren in a user's\n// search term silently terminates a tuple early and changes what you asked for\n// without erroring. This module is the pure, tested alternative.\n\n/** A value expressible in the Rest.li variables grammar. */\nexport type RestliValue =\n | string\n | number\n | boolean\n | undefined\n | RestliValue[]\n | { [key: string]: RestliValue };\n\n/**\n * Characters that must be percent-encoded inside a scalar value. Two distinct\n * hazards, both silent:\n *\n * Grammar `( ) , : |` change the shape of the tuple. A keyword containing\n * a comma would split one value into two.\n * URL `& # + space %` corrupt the query string the tuple is spliced\n * into. Searching for \"tom & jerry\" would inject a second query\n * parameter, and LinkedIn would answer a question we never asked\n * — returning 200 with plausible results for the wrong query.\n *\n * `%` is listed first and handled first, so an already-percent-looking value is\n * escaped rather than double-decoded into something else.\n */\nconst ENCODED: Record<string, string> = {\n '%': '%25', // MUST be first — see below\n '(': '%28',\n ')': '%29',\n ',': '%2C',\n ':': '%3A',\n '|': '%7C',\n '&': '%26',\n '#': '%23',\n '+': '%2B',\n ' ': '%20',\n};\n\nconst RESERVED = /[%(),:|&#+ ]/g;\n\nfunction encodeScalar(value: string | number | boolean): string {\n if (typeof value !== 'string') return String(value);\n // A single pass over the string, replacing each reserved character with its\n // escape. Because it is one pass, the `%` introduced by an escape is never\n // itself re-escaped — which is what makes the `%` entry above safe.\n return value.replace(RESERVED, (c) => ENCODED[c] ?? c);\n}\n\nfunction encodeValue(value: RestliValue): string | undefined {\n if (value === undefined) return undefined;\n if (Array.isArray(value)) {\n const members = value.map(encodeValue).filter((m): m is string => m !== undefined);\n return `List(${members.join(',')})`;\n }\n if (typeof value === 'object') return encodeObject(value);\n return encodeScalar(value);\n}\n\nfunction encodeObject(obj: { [key: string]: RestliValue }): string {\n const parts: string[] = [];\n for (const [key, value] of Object.entries(obj)) {\n const encoded = encodeValue(value);\n // An undefined value is omitted entirely — never emitted as the string\n // \"undefined\", which LinkedIn would treat as a real filter value.\n if (encoded !== undefined) parts.push(`${key}:${encoded}`);\n }\n return `(${parts.join(',')})`;\n}\n\n/** Encode a variables object into the Rest.li 2.0 grammar. */\nexport function encodeVariables(vars: { [key: string]: RestliValue }): string {\n return encodeObject(vars);\n}\n\n// ─── Composite URNs ───────────────────────────────────────────────────────────\n//\n// Voyager URNs are not always `urn:li:type:id`. Tuple forms appear inline:\n//\n// urn:li:fs_updateV2:(urn:li:activity:999,GROUP_FEED,EMPTY,DEFAULT,false)\n// urn:li:fsd_profilePositionGroup:(urn:li:fsd_profile:ABC,urn:li:fsd_company:(1,2))\n//\n// R3 §4 documents the reference implementation extracting the inner URN with\n// `split(\"(\")[1].split(\",\")[0]`. That is correct only until a member is itself a\n// tuple — and nested tuples do occur. A paren-aware split is barely more code\n// and does not have a silent failure mode.\n\nexport interface TupleUrn {\n /** The URN's own namespace, e.g. `fs_updateV2`. */\n namespace: string;\n /** Top-level members, with nested tuples left intact. */\n members: string[];\n}\n\n/**\n * Parse a composite (tuple-form) URN. Returns null when the URN is not\n * composite, or when its parentheses are unbalanced — an unbalanced URN is\n * malformed data, and guessing at its members would invent structure.\n */\nexport function parseTupleUrn(urn: string): TupleUrn | null {\n const open = urn.indexOf(':(');\n if (open === -1 || !urn.endsWith(')')) return null;\n\n const namespace = urn.slice(0, open).split(':').pop();\n if (namespace === undefined || namespace === '') return null;\n\n const body = urn.slice(open + 2, -1);\n const members: string[] = [];\n let depth = 0;\n let current = '';\n\n for (const char of body) {\n if (char === '(') depth++;\n else if (char === ')') depth--;\n\n if (depth < 0) return null; // closed one we never opened\n\n if (char === ',' && depth === 0) {\n members.push(current);\n current = '';\n } else {\n current += char;\n }\n }\n if (depth !== 0) return null; // opened one we never closed\n\n members.push(current);\n return { namespace, members };\n}\n\n/**\n * The identity a composite URN wraps — its first member. A non-composite URN is\n * returned unchanged, so this is safe to call on any URN.\n */\nexport function innerUrn(urn: string): string {\n const parsed = parseTupleUrn(urn);\n const first = parsed?.members[0];\n return first ?? urn;\n}\n\n// ─── Namespace collapse ───────────────────────────────────────────────────────\n//\n// R3 §4: LinkedIn is mid-migration from `fs_*` (legacy) to `fsd_*` (dash), and\n// three profile URN forms coexist in live responses — the reference client\n// literally string-replaces between them. This is the same legacy/hoisted split\n// that cost x-relay real data, and the fix is the same: collapse to one identity\n// so dedupe and cross-referencing are structural rather than best-effort.\n//\n// Only mappings we have direct evidence for are listed. An unknown namespace\n// passes through untouched — inventing a mapping would silently merge two\n// distinct entities, which is worse than leaving them separate.\nconst NAMESPACE_ALIASES: Record<string, string> = {\n fs_miniProfile: 'fsd_profile',\n fs_profile: 'fsd_profile',\n};\n\n/**\n * Canonicalise a URN: unwrap composite forms to their inner identity, then\n * collapse known legacy namespace aliases onto their dash equivalent.\n * Idempotent.\n */\nexport function canonicalUrn(urn: string): string {\n const inner = innerUrn(urn);\n const parts = inner.split(':');\n // urn:li:<namespace>:<id...>\n const namespace = parts[2];\n if (namespace === undefined) return inner;\n\n const alias = NAMESPACE_ALIASES[namespace];\n if (alias === undefined) return inner;\n\n parts[2] = alias;\n return parts.join(':');\n}\n","// ─── Presentation ─────────────────────────────────────────────────────────────\n//\n// Pure shaping of Voyager entities into flat, readable rows. No I/O.\n//\n// LinkedIn wraps essentially every piece of display text in a TextViewModel\n// (`{text, textDirection, attributesV2, $type}`), sometimes twice — a post's\n// commentary is `commentary.text.text`. Raw entities are therefore both huge\n// and unreadable, so commands shape by default and keep the raw node behind\n// `--raw` for when a shape has drifted and you need to see what actually came\n// back.\n//\n// Every shaper is defensive: an unrecognised entity still reports its `$type`\n// rather than returning nothing, because the parser deliberately lets unknown\n// types through and silently blanking them here would undo that.\n\nimport type { Entity } from './engine/parse.ts';\nimport { innerUrn } from './engine/restli.ts';\n\nexport interface Shaped {\n type?: string;\n urn?: string;\n name?: string;\n headline?: string;\n location?: string;\n url?: string;\n text?: string;\n author?: string;\n posted?: string;\n [key: string]: unknown;\n}\n\n/** Pull the string out of a TextViewModel, at either nesting depth. */\nfunction text(value: unknown): string | undefined {\n if (typeof value === 'string') return value.trim() || undefined;\n if (value === null || typeof value !== 'object') return undefined;\n\n const node = value as { text?: unknown };\n if (typeof node.text === 'string') return node.text.trim() || undefined;\n // commentary.text.text — the doubly-wrapped case.\n if (node.text !== null && typeof node.text === 'object') return text(node.text);\n return undefined;\n}\n\nfunction typeOf(node: Entity): string | undefined {\n const t = node.$type ?? (node as { _type?: unknown })._type;\n return typeof t === 'string' ? t : undefined;\n}\n\n/** Drop tracking query strings, which differ per request for identical results. */\nfunction cleanUrl(url: unknown): string | undefined {\n if (typeof url !== 'string' || url === '') return undefined;\n const cut = url.indexOf('?');\n return cut === -1 ? url : url.slice(0, cut);\n}\n\nfunction defined<T extends Record<string, unknown>>(obj: T): T {\n for (const key of Object.keys(obj)) {\n if (obj[key] === undefined) delete obj[key];\n }\n return obj;\n}\n\nfunction shapeSearchRow(node: Entity): Shaped {\n const entityUrn = typeof node.entityUrn === 'string' ? node.entityUrn : undefined;\n return defined({\n type: typeOf(node),\n // The entity urn is composite — (profileUrn, SEARCH_SRP, DEFAULT) — and the\n // member identity is its first member.\n urn: entityUrn === undefined ? undefined : innerUrn(entityUrn),\n name: text(node.title),\n headline: text(node.primarySubtitle),\n location: text(node.secondarySubtitle),\n url: cleanUrl(node.navigationUrl),\n });\n}\n\n/**\n * Engagement counts are two references away from the post:\n *\n * UpdateV2 --*socialDetail--> SocialDetail --*totalSocialActivityCounts--> counts\n *\n * The parser drops both intermediate nodes as decorations, which is correct —\n * they are not content — so without the index a post has no like or comment\n * count at all. Engagement is the main ranking signal for research, so it is\n * worth the two hops.\n *\n * The same SocialDetail also carries the post's **ugcPost** URN, which is NOT\n * the activity URN in `updateMetadata` (verified live: activity …8686600193 vs\n * ugcPost …7814144000). Reactions and comments key off the ugcPost form, so\n * this is where that mapping comes from — it cannot be derived.\n */\n/**\n * A post's own urn, from whichever of the two live shapes it is.\n *\n * `com.linkedin.voyager.feed.render.UpdateV2` carries it in `updateMetadata`.\n * Its dash sibling `com.linkedin.voyager.dash.feed.Update` — what `myPosts`\n * returns — has no `updateMetadata` at all, and hides the activity urn in the\n * first member of a composite entityUrn tuple:\n *\n * urn:li:fsd_update:(urn:li:activity:662…,MEMBER_SHARES,DEBUG_REASON,…)\n *\n * Handling only the first shape made every post from `my-posts` arrive with no\n * urn, which left `delete` unable to identify the post it was about to destroy.\n */\nfunction postUrn(node: Entity): string | undefined {\n const meta = node.updateMetadata as { urn?: unknown } | undefined;\n if (typeof meta?.urn === 'string') return meta.urn;\n\n const entityUrn = node.entityUrn;\n if (typeof entityUrn !== 'string') return undefined;\n return /urn:li:(activity|ugcPost|share):\\d+/.exec(entityUrn)?.[0];\n}\n\nfunction shapePost(node: Entity, index?: Map<string, Entity>): Shaped {\n const actor = node.actor as { name?: unknown; subDescription?: unknown } | undefined;\n const urn = postUrn(node);\n\n const social = deref(node, '*socialDetail', index);\n const counts =\n social === undefined ? undefined : deref(social, '*totalSocialActivityCounts', index);\n\n return defined({\n type: typeOf(node),\n urn,\n threadUrn: typeof social?.urn === 'string' ? social.urn : undefined,\n author: text(actor?.name),\n // `text()` already trims; LinkedIn pads these with trailing spaces.\n posted: text(actor?.subDescription),\n text: text(node.commentary),\n likes: numberOf(counts?.numLikes),\n comments: numberOf(counts?.numComments),\n shares: numberOf(counts?.numShares ?? social?.totalShares),\n url: urn === undefined ? undefined : `https://www.linkedin.com/feed/update/${urn}/`,\n });\n}\n\nfunction numberOf(value: unknown): number | undefined {\n return typeof value === 'number' ? value : undefined;\n}\n\n/**\n * Resolve a `*`-prefixed URN reference on a node against the side-table.\n * LinkedIn returns location, current position and education as references, so\n * a profile without its index is mostly pointers.\n */\nfunction deref(\n node: Entity,\n key: string,\n index: Map<string, Entity> | undefined,\n): Entity | undefined {\n if (index === undefined) return undefined;\n const ref = node[key];\n if (typeof ref === 'string') return index.get(ref);\n if (ref === undefined) return undefined;\n if (ref !== null && typeof ref === 'object') {\n for (const [k, v] of Object.entries(ref as Record<string, unknown>)) {\n if (k.startsWith('*') && typeof v === 'string') return index.get(v);\n }\n }\n return undefined;\n}\n\n/**\n * Shape a full profile, resolving the references LinkedIn leaves dangling.\n *\n * Note the honest gap: none of the observed projections returns\n * firstName/lastName/publicIdentifier, so a looked-up profile has no name.\n * The caller supplied the identifier, so this is a real limit rather than a\n * silent one — see src/engine/contracts.ts.\n */\nexport function shapeProfile(node: Entity, index?: Map<string, Entity>): Shaped {\n const base = shapeMember(node);\n const geo = deref(node, 'geoLocation', index);\n const position =\n deref(node, 'profileTopPosition', index) ?? firstOfType(index, 'profile.Position');\n const education =\n deref(node, 'profileTopEducation', index) ?? firstOfType(index, 'profile.Education');\n\n return defined({\n ...base,\n location: text(geo?.defaultLocalizedName) ?? text(geo?.localizedName),\n title: text(position?.title),\n company: text(position?.companyName),\n school: text(education?.schoolName),\n });\n}\n\nfunction firstOfType(index: Map<string, Entity> | undefined, suffix: string): Entity | undefined {\n if (index === undefined) return undefined;\n for (const node of new Set(index.values())) {\n if (String(node.$type ?? '').endsWith(suffix)) return node;\n }\n return undefined;\n}\n\nfunction shapeMember(node: Entity): Shaped {\n const first = text(node.firstName);\n const last = text(node.lastName);\n const publicId = text(node.publicIdentifier) ?? text(node.publicId);\n const name = [first, last].filter(Boolean).join(' ');\n return defined({\n type: typeOf(node),\n urn: typeof node.entityUrn === 'string' ? node.entityUrn : undefined,\n publicId,\n name: name === '' ? undefined : name,\n headline: text(node.headline) ?? text(node.occupation),\n url: publicId === undefined ? undefined : `https://www.linkedin.com/in/${publicId}/`,\n });\n}\n\n/**\n * A comment. The author lives under `commenter` as a lockup (title/subtitle/\n * navigationUrl), and the comment's own like count is another two-hop\n * dereference through its socialDetail — same chain as a post.\n */\nfunction shapeComment(node: Entity, index?: Map<string, Entity>): Shaped {\n const commenter = node.commenter as Entity | undefined;\n const social = deref(node, '*socialDetail', index);\n const counts =\n social === undefined ? undefined : deref(social, '*totalSocialActivityCounts', index);\n\n return defined({\n type: typeOf(node),\n urn: typeof node.urn === 'string' ? node.urn : undefined,\n author: text(commenter?.title),\n headline: text(commenter?.subtitle),\n authorUrl: cleanUrl(commenter?.navigationUrl),\n text: text(node.comment) ?? text(node.commentary),\n likes: numberOf(counts?.numLikes),\n postedAt:\n typeof node.createdAt === 'number' ? new Date(node.createdAt).toISOString() : undefined,\n edited: node.edited === true ? true : undefined,\n url: cleanUrl(node.permalink),\n });\n}\n\n/** A reactor — who reacted, and with which reaction. */\nfunction shapeReaction(node: Entity, index?: Map<string, Entity>): Shaped {\n const lockup = node.reactorLockup as Entity | undefined;\n const actorUrn = typeof node.actorUrn === 'string' ? node.actorUrn : undefined;\n const profile = actorUrn === undefined ? undefined : index?.get(actorUrn);\n\n return defined({\n type: typeOf(node),\n urn: actorUrn,\n name: text(lockup?.title),\n headline: text(lockup?.subtitle) ?? text(profile?.headline),\n reaction: typeof node.reactionType === 'string' ? node.reactionType : undefined,\n url: cleanUrl(lockup?.navigationUrl),\n });\n}\n\n/** Shape one entity into a flat row, dispatching on its type. */\nexport function shapeEntity(node: Entity, index?: Map<string, Entity>): Shaped {\n try {\n const t = (typeOf(node) ?? '').toLowerCase();\n if (t.includes('entityresultviewmodel')) return shapeSearchRow(node);\n // Order matters: Comment and Reaction are checked before the broader\n // 'update' and 'profile' fragments, which would otherwise swallow them.\n if (t.endsWith('social.comment')) return shapeComment(node, index);\n if (t.endsWith('social.reaction')) return shapeReaction(node, index);\n if (t.includes('update')) return shapePost(node, index);\n if (t.includes('profile')) return shapeMember(node);\n\n // Unrecognised: report the type and make a best effort, so a new shape\n // shows up as thin data rather than as nothing.\n return defined({\n type: typeOf(node),\n urn: typeof node.entityUrn === 'string' ? node.entityUrn : undefined,\n name: text(node.title) ?? text(node.name),\n text: text(node.commentary) ?? text(node.text),\n });\n } catch {\n return defined({ type: typeOf(node) });\n }\n}\n\nexport function shapeAll(items: Entity[], index?: Map<string, Entity>): Shaped[] {\n return items.map((node) => shapeEntity(node, index));\n}\n\n// ─── Output modes ─────────────────────────────────────────────────────────────\n//\n// `--fields` and `--compact` were advertised in the command registry long\n// before they existed — a documented promise the tool did not keep. They exist\n// now, and tests/skill.test.ts asserts that every flag a usage string\n// advertises is actually parsed, so the same drift cannot recur silently.\n//\n// Both are for the same problem: a shaped row is still ~8 keys of JSON, and an\n// agent ranking 25 search results does not need all of them in its context.\n\n/**\n * Keep only the named keys, in the order named. A key no row carries is\n * omitted rather than emitted as `undefined` — a field the user misspelled\n * should not become a column of nulls that looks like missing data.\n */\nexport function project<T extends Record<string, unknown>>(\n rows: T[],\n spec: string,\n): Record<string, unknown>[] {\n const keys = spec\n .split(',')\n .map((k) => k.trim())\n .filter((k) => k !== '');\n if (keys.length === 0) return rows;\n\n return rows.map((row) => {\n const out: Record<string, unknown> = {};\n for (const key of keys) {\n if (row[key] !== undefined) out[key] = row[key];\n }\n return out;\n });\n}\n\n/** Fields to lead with, in preference order — most identifying first. */\nconst LEAD = ['name', 'author', 'title'];\nconst DETAIL = ['headline', 'text', 'location', 'company', 'posted', 'reaction'];\n\n/**\n * One flat line per row. Reduces a page of search results from kilobytes of\n * JSON to something scannable, without losing what a ranking decision needs.\n */\nexport function compactRows(rows: Record<string, unknown>[]): string[] {\n return rows.map((row) => {\n const parts: string[] = [];\n\n for (const key of LEAD) {\n const v = row[key];\n if (typeof v === 'string' && v !== '') {\n parts.push(v);\n break;\n }\n }\n for (const key of DETAIL) {\n const v = row[key];\n if (typeof v === 'string' && v !== '') parts.push(v);\n }\n\n const counts = ['likes', 'comments']\n .map((k) => (typeof row[k] === 'number' ? `${row[k]} ${k}` : undefined))\n .filter((v): v is string => v !== undefined);\n parts.push(...counts);\n\n // A row with nothing human-readable still has to identify itself.\n if (parts.length === 0) {\n const urn = row.urn ?? row.type;\n if (typeof urn === 'string') parts.push(urn);\n }\n\n // One row, one line — a newline in a post body would break the format.\n return parts.join(' · ').replace(/\\s*\\n\\s*/g, ' ');\n });\n}\n","import type { Envelope, Err, Ok } from './types.ts';\n\nexport function ok<T>(command: string, data: T): Ok<T> {\n return { ok: true, command, data };\n}\n\nexport function err(\n command: string,\n code: string,\n message: string,\n hint?: string,\n status?: number,\n retryAfterMs?: number,\n): Err {\n const error: Err['error'] = { code, message };\n if (hint !== undefined) error.hint = hint;\n if (status !== undefined) error.status = status;\n if (retryAfterMs !== undefined) error.retryAfterMs = retryAfterMs;\n return { ok: false, command, error };\n}\n\nexport function toJson(envelope: unknown): string {\n return JSON.stringify(envelope, null, 2);\n}\n\n// ─── Error taxonomy ───────────────────────────────────────────────────────────\n\nexport const ERROR_CODES = [\n // Raised before any network call is made.\n 'INVALID_INPUT',\n 'UNKNOWN_COMMAND',\n 'CONFIRMATION_REQUIRED',\n 'BUDGET_EXHAUSTED',\n 'COOLDOWN_ACTIVE',\n 'CACHE_CORRUPT',\n 'NOT_IMPLEMENTED',\n // Raised from a response.\n 'AUTH_FAILED',\n 'RATE_LIMITED',\n 'REQUEST_DENIED', // HTTP 999 — LinkedIn's non-standard bot block\n 'CHALLENGE_DETECTED',\n 'SCHEMA_DRIFT',\n 'NOT_FOUND',\n 'FETCH_FAILED',\n 'FETCH_TIMEOUT',\n] as const;\n\nexport type ErrorCode = (typeof ERROR_CODES)[number];\n\n/**\n * Whether a failure may be retried automatically.\n *\n * Almost everything is `false`, and that is the point. On LinkedIn a 429 is the\n * warning shot on a documented escalation ladder — retrying into it is the\n * mechanism by which a throttle becomes a restriction. A `retryAfterMs` is\n * information to print for a human, never permission for the process to try\n * again. The single exception is a timeout where no response was received at\n * all, which carries no signal about our standing with LinkedIn.\n *\n * This is a deliberate break with x-relay, which retries 429 three times. That\n * is correct on a platform where the worst case is a temporary block.\n */\nexport function isRetryable(code: ErrorCode | string): boolean {\n return code === 'FETCH_TIMEOUT';\n}\n\n/** 0 success · 1 command error · 2 unknown command. */\nexport function exitCodeFor(envelope: Envelope): number {\n if (envelope.ok) return 0;\n return envelope.error.code === 'UNKNOWN_COMMAND' ? 2 : 1;\n}\n","// Cache-backed commands. These make no network call at all — after a research\n// session, repeat lookups are free, which is the whole point of keeping a local\n// store on a platform where every request is rationed.\n\nimport {\n CacheCorrupt,\n count,\n getCheckpoint,\n openDb,\n purge as purgeDb,\n type Source,\n search as searchDb,\n upsert,\n} from '../cache/db.ts';\nimport { compactRows, project, type Shaped } from '../format.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\n\nconst SOURCES: Source[] = ['connections', 'my-posts', 'third-party'];\n\n/** Turn a CacheCorrupt into an envelope; rethrow anything else. */\nfunction corruptEnvelope(command: string, e: unknown): Envelope {\n if (e instanceof CacheCorrupt) {\n return err(\n command,\n 'CACHE_CORRUPT',\n e.message,\n `Moved to ${e.quarantinedTo}. A corrupt cache is NOT treated as an empty one — that would ` +\n 'trigger a full re-sync against LinkedIn. Inspect it, then re-run.',\n );\n }\n throw e;\n}\n\nexport interface LocalOpts {\n compact?: boolean;\n fields?: string;\n}\n\n/** The cache path honours the same output flags as the live path. */\nfunction render(rows: Record<string, unknown>[], opts: LocalOpts): unknown[] {\n if (opts.compact === true) return compactRows(rows);\n if (opts.fields !== undefined && opts.fields !== '') return project(rows, opts.fields);\n return rows;\n}\n\nexport function runLocal(\n query: string | undefined,\n sources: string | undefined,\n since: string | undefined,\n limit: number,\n opts: LocalOpts = {},\n): Envelope {\n const requested = sources?.split(',').map((s) => s.trim()) ?? SOURCES;\n const invalid = requested.filter((s) => !SOURCES.includes(s as Source));\n if (invalid.length > 0) {\n return err(\n 'local',\n 'INVALID_INPUT',\n `unknown source(s): ${invalid.join(', ')}`,\n `valid sources: ${SOURCES.join(', ')}`,\n );\n }\n\n let sinceMs: number | undefined;\n if (since !== undefined) {\n const parsed = Date.parse(since);\n if (Number.isNaN(parsed)) {\n return err('local', 'INVALID_INPUT', `could not parse --since '${since}'`, 'use YYYY-MM-DD');\n }\n sinceMs = parsed;\n }\n\n try {\n const db = openDb();\n const rows = searchDb(db, query ?? '', {\n sources: requested as Source[],\n ...(sinceMs === undefined ? {} : { since: sinceMs }),\n limit,\n });\n const total = count(db);\n\n const shaped = rows.map((r) => ({\n ...(JSON.parse(r.body ?? '{}') as Shaped),\n source: r.source,\n cachedAt: new Date(r.updatedAt).toISOString(),\n }));\n\n return ok('local', {\n items: render(shaped, opts),\n meta: {\n returnedCount: rows.length,\n cachedTotal: total,\n sources: requested,\n // An empty cache is not an empty LinkedIn — say which one this is.\n note:\n total === 0\n ? 'The local cache is empty. Run a read command with --retain, or sync a source, before searching offline.'\n : undefined,\n },\n });\n } catch (e) {\n return corruptEnvelope('local', e);\n }\n}\n\n/**\n * `connections` and `my-posts` are the same offline read as `local`, with the\n * source pinned. They exist as separate commands because that is how a user\n * thinks about their own data — `--sync` fills them, they read from cache.\n */\nexport function runSourceRead(\n command: 'connections' | 'my-posts',\n query: string | undefined,\n limit: number,\n opts: LocalOpts = {},\n): Envelope {\n const result = runLocal(query, command, undefined, limit, opts);\n if (!result.ok) return result;\n const data = result.data as Record<string, unknown>;\n const meta = data.meta as Record<string, unknown>;\n if ((meta.cachedTotal as number) === 0 || (meta.returnedCount as number) === 0) {\n meta.note = `Nothing cached for '${command}'. Run \\`lnrelay sync ${command}\\` first — this command reads the local cache and makes no network call.`;\n }\n return ok(command, data);\n}\n\nexport function runPurge(scope: string | undefined, confirmed: boolean): Envelope {\n const target = scope === 'all' ? 'all' : 'third-party';\n\n if (!confirmed) {\n try {\n const db = openDb();\n return err(\n 'purge',\n 'CONFIRMATION_REQUIRED',\n `would delete ${target === 'all' ? count(db) : count(db, 'third-party')} records (${target})`,\n 'Re-run with --confirm. This only touches local files; it never contacts LinkedIn.',\n );\n } catch (e) {\n return corruptEnvelope('purge', e);\n }\n }\n\n try {\n const db = openDb();\n const removed = purgeDb(db, target);\n return ok('purge', { scope: target, removed, remaining: count(db) });\n } catch (e) {\n return corruptEnvelope('purge', e);\n }\n}\n\nexport function runCacheStatus(): Envelope {\n try {\n const db = openDb();\n return ok('cache-status', {\n total: count(db),\n bySource: Object.fromEntries(SOURCES.map((s) => [s, count(db, s)])),\n checkpoints: Object.fromEntries(SOURCES.map((s) => [s, getCheckpoint(db, s) ?? null])),\n retention:\n 'Third-party records expire 30 days after capture; the body is deleted and an identity ' +\n 'stub remains so a re-fetch is a visible choice. Owner data never expires.',\n });\n } catch (e) {\n return corruptEnvelope('cache-status', e);\n }\n}\n\n/**\n * Retain shaped rows from a live read. Opt-in (`--retain`) rather than\n * automatic: caching every profile you glance at recreates a personal data\n * lake, which is exactly the shape the risk research warns against.\n */\nexport type RetainResult = { added: number; updated: number } | { skipped: string };\n\nexport function retain(source: Source, items: Shaped[]): RetainResult {\n const rows = items\n .filter((i) => typeof i.urn === 'string' && i.urn !== '')\n .map((i) => ({\n urn: i.urn as string,\n body: i,\n text: [i.name, i.headline, i.location, i.text, i.author, i.company, i.title]\n .filter((v) => typeof v === 'string')\n .join(' '),\n }));\n if (rows.length === 0) return { skipped: 'no items carried a urn to key on' };\n\n try {\n return upsert(openDb(), source, rows);\n } catch (e) {\n // Retention never fails the read the user actually asked for — but it says\n // WHY it did nothing. Returning a silent null here cost real debugging time\n // once already.\n return { skipped: (e as Error).message };\n }\n}\n","// ─── Session and headers ──────────────────────────────────────────────────────\n//\n// Verified live on 2026-08-01: the auth surface is exactly two cookies. `li_at`\n// is the session; `JSESSIONID` exists pre-login too, so its presence alone\n// means nothing. The `csrf-token` header is JSESSIONID with quotes stripped —\n// a derivation, not a second secret.\n//\n// Everything the research listed as a \"cargo-cult candidate\" — x-li-track,\n// x-li-page-instance, x-li-deviceId, li_rm, bcookie, bscookie — was confirmed\n// unnecessary. We do not send them. An unexplained header is as likely to be a\n// fingerprint mismatch as a fix.\n//\n// The User-Agent is stored with the session rather than hardcoded, because a\n// stale UA measurably raises the challenge rate; hardcoding is exactly how the\n// reference client ended up shipping a Chrome 83 string into 2026.\n\nexport interface Session {\n liAt: string;\n jsessionId: string;\n userAgent: string;\n /** ISO date the cookies were minted, so `doctor` can flag staleness. */\n capturedAt: string;\n /** The owner this session is sealed to. A mismatch opens the circuit. */\n ownerUrn?: string;\n}\n\nexport function csrfToken(jsessionId: string): string {\n return jsessionId.replace(/\"/g, '');\n}\n\n/** The complete, minimal header set for an authenticated Voyager call. */\nexport function buildHeaders(session: Session): Record<string, string> {\n return {\n cookie: `li_at=${session.liAt}; JSESSIONID=${session.jsessionId}`,\n 'csrf-token': csrfToken(session.jsessionId),\n 'x-restli-protocol-version': '2.0.0',\n accept: 'application/vnd.linkedin.normalized+json+2.1',\n 'x-li-lang': 'en_US',\n 'user-agent': session.userAgent,\n };\n}\n\nexport interface SessionCheck {\n ok: boolean;\n detail: string;\n}\n\n/**\n * Validate a session's SHAPE without touching the network, and without ever\n * revealing a credential value — lengths only, so `doctor` output is safe to\n * paste into a bug report.\n */\nexport function checkSession(session: Partial<Session> | null): SessionCheck {\n if (session === null || session.liAt === undefined || session.liAt === '') {\n return { ok: false, detail: 'no li_at — run `lnrelay login`' };\n }\n if (session.jsessionId === undefined || session.jsessionId === '') {\n return { ok: false, detail: 'no JSESSIONID — run `lnrelay login`' };\n }\n if (session.userAgent === undefined || session.userAgent === '') {\n return { ok: false, detail: 'no user-agent recorded with the session' };\n }\n const age = sessionAgeDays(session.capturedAt);\n const staleness =\n age !== undefined && age > 90 ? `; UA is ${age} days old, consider re-login` : '';\n return {\n ok: true,\n detail: `li_at present (len ${session.liAt.length}); JSESSIONID present (len ${session.jsessionId.length})${staleness}`,\n };\n}\n\nexport function sessionAgeDays(\n capturedAt: string | undefined,\n now = Date.now(),\n): number | undefined {\n if (capturedAt === undefined) return undefined;\n const then = Date.parse(capturedAt);\n if (Number.isNaN(then)) return undefined;\n return Math.floor((now - then) / 86_400_000);\n}\n","// Progress reporting for long-running / multi-step commands.\n//\n// The hard invariant: stdout carries ONLY the final JSON envelope. Progress is\n// human-facing chatter, so it goes to STDERR (never stdout) and is silenced by\n// --quiet. The write sink is injectable purely so tests can capture it without\n// spying on process.stderr.\n\nexport type ProgressReporter = (msg: string) => void;\n\n/**\n * Build a progress reporter. When `quiet` is true it drops every message;\n * otherwise it writes `msg + '\\n'` to stderr (or the injected `write` sink).\n */\nexport function progressReporter(\n quiet: boolean,\n write: (s: string) => void = (s) => {\n process.stderr.write(s);\n },\n): ProgressReporter {\n return (msg: string) => {\n if (!quiet) write(`${msg}\\n`);\n };\n}\n","// ─── Spend accounting and the circuit breaker ─────────────────────────────────\n//\n// Two structural safety mechanisms live here, both pure (a clock is always\n// injected, never read):\n//\n// 1. Permits. `client` cannot be called without a `Permit`, and `spend()` is\n// the only thing that can make one. \"Issue a network call without\n// accounting for it\" is therefore a compile error rather than a\n// code-review norm. Redirects, pagination continuations and contract\n// discovery all consume permits too — otherwise the traffic easiest to\n// forget is exactly the traffic that escapes accounting.\n//\n// 2. The cooldown. A FILE, not process state. A CLI is a swarm of\n// short-lived processes, so an in-memory breaker protects nothing: the\n// next invocation would start clean and hammer straight back into the\n// throttle that opened it.\n//\n// About the numbers below: the field research swept 364 posts looking for\n// corroborated rate ceilings and found essentially none — one secondhand vendor\n// figure. So every cap is labelled with where it actually came from, and\n// `lnrelay budget` prints that label. None of them is `measured`, because we\n// have measured nothing. They are starting knobs, not LinkedIn facts.\n\nimport type { CapProvenance } from '../types.ts';\n\nconst HOUR = 3_600_000;\nconst DAY = 86_400_000;\n\nexport type SpendClass = 'profile' | 'search' | 'page' | 'write' | 'global';\n\nexport interface Cap {\n perDay: number;\n provenance: CapProvenance;\n note: string;\n}\n\nexport const CAPS: Record<SpendClass, Cap> = {\n profile: {\n perDay: 30,\n provenance: 'vendor-lore',\n note: \"transplanted from jjuanrivvera/linkedin-cli's job-detail cap\",\n },\n search: { perDay: 25, provenance: 'guessed', note: 'no corroborated figure exists' },\n page: { perDay: 60, provenance: 'guessed', note: 'thread/feed pagination' },\n write: {\n // Raised from 10 on 2026-08-14 by the owner's explicit decision, after 10\n // blocked ordinary development on a tool whose writes are the point — a\n // single test round of comment, reply and two deletes exceeded a whole day.\n //\n // Still a GUESS, and still below the weakly-reported ~20/day connection\n // lore. Nothing here has ever been measured against LinkedIn, and the\n // research's strongest finding stands: cadence triggers restrictions more\n // reliably than volume, and this cap does not pace anything — the client's\n // jittered 3-15s gap does. Treat a raised ceiling as more room to be\n // careful in, not permission to burst.\n perDay: 25,\n provenance: 'guessed',\n note: 'raised from 10 for development; still below the ~20/day connection lore per action type',\n },\n global: { perDay: 250, provenance: 'guessed', note: 'all classes combined' },\n};\n\n/** Minimum gap between any two calls, before jitter. */\nexport const MIN_GAP_MS = 3_000;\n\n// ─── Permits ──────────────────────────────────────────────────────────────────\n\n/**\n * Proof that a call was accounted for. The brand is unexported, so `spend()` is\n * the only thing in the program that can produce one.\n */\nexport interface Permit {\n readonly __brand: unique symbol;\n class: SpendClass;\n issuedAt: number;\n}\n\nexport interface Ledger {\n /** Epoch-ms timestamps of each spend, keyed by class. */\n spends: Record<string, number[]>;\n}\n\nexport function emptyLedger(): Ledger {\n return { spends: {} };\n}\n\nexport interface BudgetError {\n code: 'BUDGET_EXHAUSTED';\n message: string;\n hint: string;\n}\n\nexport type SpendResult = { permit: Permit; ledger: Ledger } | { error: BudgetError };\n\nfunction within(times: number[] | undefined, now: number, window: number): number[] {\n if (times === undefined) return [];\n return times.filter((t) => now - t < window);\n}\n\nfunction allSpends(ledger: Ledger, now: number): number[] {\n return Object.values(ledger.spends).flatMap((times) => within(times, now, DAY));\n}\n\n/**\n * Account for one intended call. Returns a permit and the updated ledger, or a\n * refusal — and a refusal charges nothing, so a denied call never consumes\n * budget.\n */\nexport function spend(ledger: Ledger, cls: SpendClass, now: number): SpendResult {\n const recent = allSpends(ledger, now);\n\n const last = recent.length > 0 ? Math.max(...recent) : undefined;\n if (last !== undefined && now - last < MIN_GAP_MS) {\n return {\n error: {\n code: 'BUDGET_EXHAUSTED',\n message: `minimum gap of ${MIN_GAP_MS}ms between calls not met`,\n hint: 'requests are paced deliberately; wait and retry',\n },\n };\n }\n\n if (recent.length >= CAPS.global.perDay) {\n return {\n error: {\n code: 'BUDGET_EXHAUSTED',\n message: `global daily cap of ${CAPS.global.perDay} calls reached`,\n hint: 'resets on a rolling 24h window; see `lnrelay budget`',\n },\n };\n }\n\n const cap = CAPS[cls];\n const forClass = within(ledger.spends[cls], now, DAY);\n if (forClass.length >= cap.perDay) {\n return {\n error: {\n code: 'BUDGET_EXHAUSTED',\n message: `daily cap of ${cap.perDay} reached for '${cls}'`,\n hint: `cap provenance: ${cap.provenance} (${cap.note}). See \\`lnrelay budget\\`.`,\n },\n };\n }\n\n return {\n permit: { class: cls, issuedAt: now } as Permit,\n ledger: { spends: { ...ledger.spends, [cls]: [...forClass, now] } },\n };\n}\n\nexport interface BudgetSummary {\n class: SpendClass;\n spentInWindow: number;\n cap: number;\n remaining: number;\n capProvenance: CapProvenance;\n warning?: string;\n}\n\nexport function summarise(ledger: Ledger, cls: SpendClass, now: number): BudgetSummary {\n const cap = CAPS[cls];\n const spent =\n cls === 'global' ? allSpends(ledger, now).length : within(ledger.spends[cls], now, DAY).length;\n const remaining = Math.max(0, cap.perDay - spent);\n\n const summary: BudgetSummary = {\n class: cls,\n spentInWindow: spent,\n cap: cap.perDay,\n remaining,\n capProvenance: cap.provenance,\n };\n if (remaining / cap.perDay < 0.25) {\n summary.warning = `only ${remaining} of ${cap.perDay} '${cls}' calls left in this 24h window — consider stopping`;\n }\n return summary;\n}\n\n// ─── The circuit breaker ──────────────────────────────────────────────────────\n\nexport type CooldownReason = 'RATE_LIMITED' | 'REQUEST_DENIED' | 'CHALLENGE_DETECTED';\n\nexport interface Cooldown {\n reason: CooldownReason;\n since: number;\n /** Epoch-ms when it lifts, or null for indefinite. */\n until: number | null;\n clearRequires: 'time' | 'human';\n}\n\n/**\n * Open a cooldown. The durations escalate with how bad the signal is: a 429 is\n * a throttle, a 999 is a network-layer bot block that lifts only as traffic\n * normalises, and a challenge means LinkedIn wants to see a human — so only a\n * human can clear it, via `lnrelay budget --reset-cooldown --confirm`.\n */\nexport function openCooldown(reason: CooldownReason, now: number): Cooldown {\n if (reason === 'CHALLENGE_DETECTED') {\n return { reason, since: now, until: null, clearRequires: 'human' };\n }\n const duration = reason === 'REQUEST_DENIED' ? 6 * HOUR : HOUR;\n return { reason, since: now, until: now + duration, clearRequires: 'time' };\n}\n\nexport function activeCooldown(cooldown: Cooldown | null, now: number): boolean {\n if (cooldown === null) return false;\n if (cooldown.until === null) return true;\n return now < cooldown.until;\n}\n","// ─── Response classification ──────────────────────────────────────────────────\n//\n// Every response passes through here BEFORE any parsing. That ordering is the\n// point: a parser asked to read a challenge page or a 410 envelope will happily\n// return an empty array, and an empty array is indistinguishable from \"there\n// was nothing\". Classification is what keeps those two apart.\n//\n// Nothing classified here is ever retried automatically. On LinkedIn a 429 is\n// the warning shot on a documented escalation ladder, so a `retry-after` is\n// information to print for a human — never permission for the process to go\n// again. The `retry` field exists so that rule is asserted in tests.\n\nimport type { CooldownReason } from './budget.ts';\n\nexport interface RawResponse {\n status: number;\n body: string;\n headers?: Record<string, string>;\n}\n\nexport interface Classification {\n outcome: 'ok' | 'error';\n /** The unparsed body, kept for surfaces whose response is not JSON. */\n raw?: string;\n code?: string;\n message?: string;\n hint?: string;\n /** Which cooldown to open, if any. */\n cooldown?: CooldownReason;\n retryAfterMs?: number;\n retry: boolean;\n /** Parsed body, when it was JSON and we already did the work. */\n json?: unknown;\n}\n\nconst CHALLENGE_MARKERS = /checkpoint|challenge|captcha|security verification|unusual activity/i;\nconst LOGIN_REDIRECT = /\\/login|\\/uas\\/login|session_redirect/i;\n\nfunction fail(code: string, message: string, extra: Partial<Classification> = {}): Classification {\n return { outcome: 'error', code, message, retry: false, ...extra };\n}\n\nconst CHALLENGE_HINT =\n 'Open LinkedIn in a real browser, clear the challenge, then `lnrelay budget --reset-cooldown --confirm`.';\n\n/** Redirects carry two very different meanings; confusing them costs a day. */\nfunction classifyRedirect(location: string): Classification {\n if (CHALLENGE_MARKERS.test(location)) {\n return fail('CHALLENGE_DETECTED', `redirected to a challenge: ${location}`, {\n cooldown: 'CHALLENGE_DETECTED',\n hint: CHALLENGE_HINT,\n });\n }\n if (LOGIN_REDIRECT.test(location)) {\n return fail('AUTH_FAILED', 'redirected to the login page', {\n hint: 'This signature means expired cookies, NOT bot detection. Re-run `lnrelay login`.',\n });\n }\n return fail('FETCH_FAILED', `unexpected redirect to ${location || '(none)'}`);\n}\n\n/**\n * A challenge served with status 200, if this body is one.\n *\n * Split out of classifyBody because it applies to EVERY path: a write must not\n * skip the challenge check just because its body is not a read contract.\n */\nfunction challengeIn(body: string): Classification | null {\n if (!CHALLENGE_MARKERS.test(body.slice(0, 4000))) return null;\n return fail('CHALLENGE_DETECTED', 'a challenge page was returned with status 200', {\n cooldown: 'CHALLENGE_DETECTED',\n hint: CHALLENGE_HINT,\n });\n}\n\n/** A 200 can still be a failure. Everything here inspects the body. */\nfunction classifyBody(body: string): Classification {\n const challenge = challengeIn(body);\n if (challenge !== null) return challenge;\n\n let json: unknown;\n try {\n json = JSON.parse(body);\n } catch {\n return fail('SCHEMA_DRIFT', 'response was 200 but not JSON', {\n hint: 'LinkedIn may have served HTML — inspect the raw body.',\n });\n }\n\n const envelope = json as { data?: Record<string, unknown>; included?: unknown[] };\n\n // An inner status can contradict the HTTP one.\n const innerStatus = (envelope.data as { status?: number } | undefined)?.status;\n if (typeof innerStatus === 'number' && innerStatus >= 400) {\n return fail('SCHEMA_DRIFT', `body carries an inner status ${innerStatus}`, {\n hint: 'The endpoint answered but reported a failure. Re-capture the operation.',\n });\n }\n\n // The 336-analogue: `data` names URNs that `included` does not contain at\n // all. The decoration failed wholesale — this is a failed fetch wearing the\n // costume of an empty result.\n if (referencesUrns(envelope.data) && (envelope.included?.length ?? 0) === 0) {\n return fail('SCHEMA_DRIFT', 'data references entities but included[] is empty', {\n hint: 'Decoration failed wholesale — this is a failed fetch, not an empty result.',\n });\n }\n\n return { outcome: 'ok', retry: false, json };\n}\n\nexport interface ClassifyOpts {\n /**\n * Whether the body is a contract to validate (a read) or a receipt (a write).\n *\n * A read's body must be a Voyager envelope, and a body that is not one means\n * something went wrong even under a 200. A WRITE's body is whatever the\n * surface feels like returning — LinkedIn's SDUI endpoints answer with a\n * React Server Components stream, which is not JSON and never will be.\n *\n * Defaults to true so reads keep their contract and nothing loosens by\n * omission.\n */\n expectJson?: boolean;\n}\n\nexport function classify(res: RawResponse, opts: ClassifyOpts = {}): Classification {\n const headers = res.headers ?? {};\n\n if (res.status >= 300 && res.status < 400) {\n return classifyRedirect(headers.location ?? '');\n }\n\n // ── Hard blocks ────────────────────────────────────────────────────────────\n if (res.status === 999) {\n return fail('REQUEST_DENIED', 'LinkedIn returned HTTP 999 (Request Denied)', {\n cooldown: 'REQUEST_DENIED',\n hint: 'A network-layer bot block that lifts only as traffic normalises. Stop making requests.',\n });\n }\n\n if (res.status === 429) {\n const retryAfter = Number(headers['retry-after']);\n const out = fail('RATE_LIMITED', 'LinkedIn throttled this request', {\n cooldown: 'RATE_LIMITED',\n hint: 'Not retried automatically — a throttle is the warning shot before a restriction.',\n });\n if (Number.isFinite(retryAfter)) out.retryAfterMs = retryAfter * 1000;\n return out;\n }\n\n if (res.status === 401 || res.status === 403) {\n return fail('AUTH_FAILED', `LinkedIn rejected the session (${res.status})`, {\n hint: 'Usually expired cookies. Re-run `lnrelay login`.',\n });\n }\n\n // ── Endpoint drift ─────────────────────────────────────────────────────────\n // 410 is the shape profileView returned on 2026-08-01: the endpoint existed,\n // answered, and told us it is gone.\n if (res.status === 410) {\n return fail('SCHEMA_DRIFT', 'endpoint returned 410 Gone — it no longer exists', {\n hint: 'Re-capture the operation with scripts/observe.ts and update src/engine/contracts.ts.',\n });\n }\n\n if (res.status === 400) {\n const hint = /queryid/i.test(res.body)\n ? 're-capture the queryId with scripts/observe.ts and update src/engine/contracts.ts'\n : 'check the encoded variables against a live capture';\n return fail('SCHEMA_DRIFT', `LinkedIn rejected the request shape (400)`, { hint });\n }\n\n if (res.status === 404) {\n return fail('NOT_FOUND', 'no such resource');\n }\n\n if (res.status < 200 || res.status >= 300) {\n return fail('FETCH_FAILED', `unexpected status ${res.status}`);\n }\n\n // Writes answer 201 Created and 204 No Content with an empty body. Reads\n // never do either, which is how this was missed until the first live share\n // came back 201 and was reported as a failure — after the post had been\n // created. That is the worst direction to be wrong in: a user told their\n // post failed re-runs the command and posts twice.\n //\n // An empty body is therefore a normal write outcome and must not reach\n // classifyBody, whose whole job is detecting a READ that returned nothing\n // when it claimed otherwise.\n if (res.body.trim() === '') return { outcome: 'ok', retry: false, json: null };\n\n // A challenge is served with status 200 and an HTML body on ANY path, so it\n // is checked before the read/write split — a write must not walk past it.\n const challenge = challengeIn(res.body);\n if (challenge !== null) return challenge;\n\n if (opts.expectJson === false) {\n // Parse opportunistically: some writes do answer JSON and the caller can\n // use it, but a body we cannot parse is not an error on this path. The raw\n // text is carried through either way — LinkedIn's SDUI surface answers with\n // an RSC stream that DESCRIBES its available actions, and that description\n // is the most useful thing in the response.\n try {\n return { outcome: 'ok', retry: false, json: JSON.parse(res.body) as unknown, raw: res.body };\n } catch {\n return { outcome: 'ok', retry: false, json: null, raw: res.body };\n }\n }\n\n return classifyBody(res.body);\n}\n\n/** Whether `data` names any URN we would expect `included[]` to resolve. */\nfunction referencesUrns(data: Record<string, unknown> | undefined): boolean {\n if (data === undefined) return false;\n let found = false;\n\n const walk = (node: unknown): void => {\n if (found || node === null || typeof node !== 'object') return;\n if (Array.isArray(node)) {\n for (const item of node) walk(item);\n return;\n }\n for (const [key, value] of Object.entries(node)) {\n // `*`-prefixed keys are Voyager's reference convention.\n if (key.startsWith('*') && Array.isArray(value) && value.length > 0) {\n found = true;\n return;\n }\n if (typeof value === 'string' && value.startsWith('urn:li:')) {\n found = true;\n return;\n }\n walk(value);\n }\n };\n\n walk(data);\n return found;\n}\n","// ─── The request driver ───────────────────────────────────────────────────────\n//\n// The only place in the program that issues a network request, and the only\n// place that spends budget. `fetch`, the clock and the sleeper are all injected\n// so this whole file is testable without touching the network.\n//\n// Order of operations is the safety design, and it is deliberate:\n//\n// 1. cooldown check — refuse before spending anything, in every process\n// 2. permit — no Permit, no call; unaccounted traffic is impossible\n// 3. jittered pace — never two calls back to back\n// 4. fetch\n// 5. classify — before parsing, always\n// 6. open a cooldown — on any throttle/block/challenge signal\n//\n// Nothing here retries. That is the point.\n\nimport { buildHeaders, type Session } from './auth.ts';\nimport type { Ledger, SpendClass } from './budget.ts';\nimport { activeCooldown, type Cooldown, MIN_GAP_MS, openCooldown, spend } from './budget.ts';\nimport { type Classification, classify } from './classify.ts';\n\nexport interface ClientDeps {\n fetch: typeof globalThis.fetch;\n /** Human-facing progress, on stderr. Optional so tests stay silent. */\n progress?: (message: string) => void;\n now: () => number;\n sleep: (ms: number) => Promise<void>;\n /** [0,1). Injected so jitter is deterministic in tests. */\n random: () => number;\n loadLedger: () => Ledger;\n saveLedger: (l: Ledger) => void;\n loadCooldown: () => Cooldown | null;\n saveCooldown: (c: Cooldown | null) => void;\n}\n\nexport interface RequestSpec {\n url: string;\n spendClass: SpendClass;\n operation: string;\n method?: string;\n /** Serialised as JSON when present. Reads carry none and must stay that way. */\n body?: unknown;\n}\n\nexport type ClientResult =\n | { ok: true; json: unknown; classification: Classification }\n | { ok: false; code: string; message: string; hint?: string; retryAfterMs?: number };\n\n/** Upper bound of the jittered gap. Lower bound is MIN_GAP_MS. */\nconst MAX_GAP_MS = 15_000;\n\nexport function createClient(session: Session, deps: ClientDeps) {\n async function request(spec: RequestSpec): Promise<ClientResult> {\n const now = deps.now();\n\n // 1. The breaker, first and in every process. A cooldown lives in a file\n // precisely so a fresh CLI invocation cannot walk straight back into the\n // throttle that opened it.\n const cooldown = deps.loadCooldown();\n if (activeCooldown(cooldown, now)) {\n const until =\n cooldown?.until === null\n ? 'indefinitely'\n : `until ${new Date(cooldown?.until ?? 0).toISOString()}`;\n return {\n ok: false,\n code: 'COOLDOWN_ACTIVE',\n message: `refusing to call LinkedIn: ${cooldown?.reason} cooldown is active ${until}`,\n hint:\n cooldown?.clearRequires === 'human'\n ? 'Log in through a real browser, clear the challenge, then `lnrelay budget --reset-cooldown --confirm`.'\n : 'Wait for it to lift, or inspect `lnrelay risk`.',\n };\n }\n\n // 2. Account for the call BEFORE making it. A denied call spends nothing.\n const ledger = deps.loadLedger();\n const result = spend(ledger, spec.spendClass, now);\n if ('error' in result) {\n return {\n ok: false,\n code: result.error.code,\n message: result.error.message,\n hint: result.error.hint,\n };\n }\n deps.saveLedger(result.ledger);\n\n // 3. Pace. Reads are paced as conservatively as writes, because the field\n // evidence shows restrictions triggered by read velocity alone.\n // That wait is 3-15s and silence during it reads as a hang, so say so.\n const gap = MIN_GAP_MS + Math.floor(deps.random() * (MAX_GAP_MS - MIN_GAP_MS));\n deps.progress?.(`${spec.operation}: pacing ${Math.round(gap / 1000)}s before the request…`);\n await deps.sleep(gap);\n deps.progress?.(`${spec.operation}: requesting…`);\n\n // 4-5. Fetch, then classify before anyone parses anything.\n const raw = await fetchRaw(spec, session, deps);\n if (raw === null) {\n return { ok: false, code: 'FETCH_FAILED', message: 'the request could not be completed' };\n }\n // A read's body is a contract; a write's body is a receipt. Validating a\n // write response read-shaped is what made a successful reaction report\n // SCHEMA_DRIFT — and made the user retry a write that had already landed.\n //\n // Keyed on the METHOD, not on whether a body was sent: `delete` sends no\n // body and is still a write.\n const isRead = (spec.method ?? 'GET') === 'GET';\n const classification = classify(raw, { expectJson: isRead });\n\n // 6. A throttle, block or challenge opens the breaker for every process.\n if (classification.cooldown !== undefined) {\n deps.saveCooldown(openCooldown(classification.cooldown, deps.now()));\n }\n\n if (classification.outcome === 'error') {\n const out: ClientResult = {\n ok: false,\n code: classification.code ?? 'FETCH_FAILED',\n message: classification.message ?? 'request failed',\n };\n if (classification.hint !== undefined) out.hint = classification.hint;\n if (classification.retryAfterMs !== undefined) out.retryAfterMs = classification.retryAfterMs;\n return out;\n }\n\n return { ok: true, json: classification.json, classification };\n }\n\n return { request };\n}\n\nasync function fetchRaw(\n spec: RequestSpec,\n session: Session,\n deps: ClientDeps,\n): Promise<{ status: number; body: string; headers: Record<string, string> } | null> {\n // A body is added only when there is one, so the read path keeps sending\n // exactly the six headers that were verified against live traffic.\n const requestHeaders = buildHeaders(session);\n if (spec.body !== undefined) requestHeaders['content-type'] = 'application/json; charset=UTF-8';\n\n try {\n const res = await deps.fetch(spec.url, {\n method: spec.method ?? 'GET',\n headers: requestHeaders,\n ...(spec.body === undefined ? {} : { body: JSON.stringify(spec.body) }),\n // Manual, so a login or checkpoint redirect is classified rather than\n // silently followed into an HTML page that parses as \"no data\".\n redirect: 'manual',\n });\n const headers: Record<string, string> = {};\n res.headers.forEach((value, key) => {\n headers[key.toLowerCase()] = value;\n });\n return { status: res.status, body: await res.text(), headers };\n } catch {\n return null;\n }\n}\n\nexport type Client = ReturnType<typeof createClient>;\n","// ─── Operation contracts ──────────────────────────────────────────────────────\n//\n// Every endpoint we call, as DATA — never inline in request logic. queryIds and\n// decorationIds are pinned to LinkedIn's deployed web-client build and can\n// rotate; keeping them here means a rotation is a data edit, not a code hunt.\n//\n// Each contract carries its provenance and the date it was captured, and\n// `shippableContracts()` admits only `verified` ones. That rule is mechanical\n// rather than a convention someone has to remember:\n//\n// verified returned 200 on this machine, on the date recorded\n// discovered seen in live traffic (scripts/observe.ts) but never exercised\n// inferred from documentation or another client — may be archaeology\n//\n// The cost of getting this wrong is documented: `identity/profiles/{id}/\n// profileView` was the reference client's core profile endpoint, was documented\n// as working in November 2024, and returns 410 Gone today. It is kept below,\n// marked dead, so nobody re-adds it from an old blog post.\n//\n// Refresh with: bun run scripts/observe.ts <path> (see docs/ENGINE-RESEARCH.md)\n\nimport type { OperationContract } from '../types.ts';\n\nconst VOYAGER = 'https://www.linkedin.com/voyager/api';\n\nexport const CONTRACTS: Record<string, OperationContract> = {\n me: {\n name: 'me',\n transport: 'voyager-restli',\n path: `${VOYAGER}/me`,\n provenance: 'verified',\n capturedAt: '2026-08-01',\n },\n\n // Three `voyagerIdentityDashProfiles` queryIds were observed on one page —\n // they are different PROJECTIONS of one operation, and picking the wrong one\n // gets you a 200 containing nothing useful:\n //\n // b5c27c04… identity only — entityUrn + versionTag. Looks like success.\n // e9b08094… the real profile: headline, geo, top position, education. ← this\n // da93c92b… 400s with (profileUrn:…); its variables shape is unknown.\n //\n // None of them returns firstName/lastName/publicIdentifier — LinkedIn splits\n // names into a projection we have not identified. Documented rather than\n // faked; the caller already knows who they asked for.\n profile: {\n name: 'profile',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerIdentityDashProfiles.e9b0809465a07db1f02e70a82d455e10',\n provenance: 'verified',\n capturedAt: '2026-08-01',\n },\n\n feed: {\n name: 'feed',\n transport: 'voyager-restli',\n path: `${VOYAGER}/feed/updatesV2`,\n provenance: 'verified',\n capturedAt: '2026-08-01',\n },\n\n // The November-2024 queryId, still returning 200 in August 2026 — roughly 21\n // months unchanged. Notable because kill criterion #3 assumed queryIds might\n // rotate weekly; on this evidence they are build-pinned but long-lived.\n search: {\n name: 'search',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerSearchDashClusters.b0928897b71bd00a5a7291755dcd64f0',\n provenance: 'verified',\n capturedAt: '2026-08-01',\n },\n\n reactions: {\n name: 'reactions',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerSocialDashReactions.41ebf31a9f4c4a84e35a49d5abc9010b',\n provenance: 'verified',\n capturedAt: '2026-08-02',\n },\n\n // Comments. The variables carry a COMPOSITE socialDetailUrn assembled from the\n // post's own urn, repeated, plus a highlightedReply placeholder:\n //\n // urn:li:fsd_socialDetail:(<postUrn>,<postUrn>,urn:li:highlightedReply:-)\n //\n // Two things were established by probing rather than assumed. Our codec's\n // percent-encoding of that urn's colons and parens is REQUIRED — the literal\n // form returns 400. And an `urn:li:activity:` post urn works directly, so\n // `post` does not need a feed lookup to find the ugcPost form first.\n comments: {\n name: 'comments',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerSocialDashComments.afec6d88d7810d45548797a8dac4fb87',\n provenance: 'verified',\n capturedAt: '2026-08-02',\n },\n\n // The member's own posts. Verified 200; returns an empty collection on an\n // account with no posts, which is a true empty rather than a failure.\n // Needs the `fsd_profile` namespace, NOT the `fs_miniProfile` urn `whoami`\n // returns — the legacy form answers 200 with an empty result rather than an\n // error. That was invisible until the account had a post to return, and is\n // why engine.myPosts canonicalises the urn before sending it.\n //\n // KNOWN INCOMPLETE (2026-08-13): with the namespace fixed this returns the\n // owner's posts, but a post created minutes earlier did not appear here, nor\n // in `feed`, over ~1.5 hours. Whether that is an indexing lag or a coverage\n // limit of this projection is UNRESOLVED — do not treat this endpoint as an\n // authoritative \"all my posts\" until it is settled.\n myPosts: {\n name: 'myPosts',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerFeedDashProfileUpdates.20c70fe0314184158516a7ec004c0408',\n provenance: 'verified',\n capturedAt: '2026-08-02',\n },\n\n // Discovered and returns 200, but the projection is useless: 39 KB containing\n // one `guideFetcher` wrapper and no name, tagline, description or headcount.\n // The same trap as the thin profile projection, so it stays unverified and\n // `company` does not ship. The richer path is probably\n // voyagerOrganizationDashViewWrapper with an organizationalPageUrn, which\n // first requires resolving that urn — unfinished work, not a dead end.\n company: {\n name: 'company',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerOrganizationDashCompanies.148b1aebfadd0a455f32806df656c3c1',\n provenance: 'discovered',\n capturedAt: '2026-08-02',\n },\n\n // A job CARDS list, not a job detail. Observed on /jobs/collections/recommended\n // and never exercised; `job` needs a detail endpoint we have not captured.\n jobCards: {\n name: 'jobCards',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerJobsDashJobCards.e5b6b761ede078dabe8ad857aa42c220',\n provenance: 'discovered',\n capturedAt: '2026-08-02',\n },\n};\n\n/**\n * Endpoints known to be DEAD. Listed so a future maintainer reading the\n * November-2024 reference client does not helpfully re-add one.\n */\nexport const RETIRED: Record<string, { path: string; diedBy: string; note: string }> = {\n profileView: {\n path: `${VOYAGER}/identity/profiles/{id}/profileView`,\n diedBy: '2026-08-01',\n note:\n 'Returns 410 Gone inside a well-formed Voyager envelope. Superseded by the `profile` ' +\n 'contract above. Every client that reads profiles through this is broken.',\n },\n};\n\n/** Only `verified` contracts may back a shipped command. */\nexport function shippableContracts(): Record<string, OperationContract> {\n return Object.fromEntries(\n Object.entries(CONTRACTS).filter(([, c]) => c.provenance === 'verified'),\n );\n}\n\nexport function contractFor(name: string): OperationContract | undefined {\n return shippableContracts()[name];\n}\n","// ─── Normalising Voyager's decoration model ───────────────────────────────────\n//\n// LinkedIn returns a graph with a side-table, not a nested document:\n//\n// { data: { \"*elements\": [\"urn:li:activity:100\", …] }, ← thin refs, ORDERED\n// included: [ { entityUrn: \"urn:li:activity:100\", $type: …, … }, … ] } ← unordered\n//\n// So: index `included[]` once into a Map, then walk `data`'s references against\n// it. The reference implementation instead does an O(n·m) substring scan across\n// the two, which is both slow and subtly wrong — we do not re-derive that.\n//\n// Three rules here are load-bearing, and each one exists because its absence\n// caused a real production bug in the sibling project:\n//\n// 1. FILTER BY EXCLUSION. Drop known noise; let everything else through. An\n// accept-list naming the types we know silently dropped every reply in\n// every thread on x-relay, and 34 of 77 posts per feed page — invisible\n// behind ok:true, a live cursor and a plausible count. On a live LinkedIn\n// feed, 39 of 44 included[] nodes are decorations rather than content, so\n// an accept-list here would look reasonable right up until a rename.\n//\n// 2. UNKNOWN IS NOT DROPPED, AND IT IS COUNTED. A $type we have never seen\n// arrives as data AND increments meta.unknownTypes, so drift shows up in\n// the very first response after a LinkedIn deploy rather than whenever\n// someone next thinks to count.\n//\n// 3. UNRESOLVABLE IS NOT ABSENT. A reference in `data` that `included[]`\n// does not contain is a FAILED decoration. It goes to meta.unresolved and\n// makes the result `partial` — never silently shorter.\n\nimport type { FetchState } from '../types.ts';\nimport { canonicalUrn } from './restli.ts';\n\nexport type Entity = Record<string, unknown> & { entityUrn?: string; $type?: unknown };\n\n/**\n * Type fragments that identify chrome rather than content. Matched as\n * case-insensitive substrings of `$type`, because LinkedIn versions its type\n * names (`UpdateV2` → `UpdateV3`) and a fragment survives that.\n *\n * This list is the ONLY thing that removes data. Adding to it is a deliberate\n * act; forgetting to add to it costs some noise in the output, which is the\n * cheap failure. Forgetting to add to an accept-list costs the entire result,\n * silently, which is the expensive one.\n */\nconst DROP_TYPE_FRAGMENTS = [\n 'promoted',\n 'sponsored',\n 'adunit',\n 'peopleyoumayknow',\n 'recommendedentity',\n 'discoveryentity',\n 'discoverymodule',\n 'promptcomponent',\n 'carouselcomponent',\n 'lego',\n // Search-result chrome, observed live alongside real results.\n 'feedbackcard',\n 'lazyloadedactions',\n 'bannercard',\n 'searchsuggestion',\n 'keywordssuggestion',\n 'queryclarification',\n 'knowledgecard',\n 'topicalquestion',\n];\n\n/** Types that are supporting decorations — real, but not the thing asked for. */\nconst DECORATION_FRAGMENTS = [\n 'socialdetail',\n 'socialactivitycounts',\n 'socialpermissions',\n 'saveaction',\n 'updateactions',\n 'hidepostaction',\n 'followinginfo',\n 'miniprofile',\n 'minicompany',\n 'videoplaymetadata',\n 'hidecommentaction',\n 'followingstate',\n 'followaction',\n 'connectaction',\n];\n\nfunction typeOf(node: Entity): string {\n const t = node.$type ?? (node as { _type?: unknown })._type;\n return typeof t === 'string' ? t : '';\n}\n\n/**\n * A promoted feed post carries the SAME `$type` as a real one — the ad marker\n * lives in the actor's subdescription (\"Promoted\", \"Promoted by <brand>\"), not\n * in the type. Found live: an ad reached the output while every type-level\n * filter passed, which is the same lesson as the accept-list in a new costume.\n * Type is not the only place a thing can identify itself.\n */\nfunction isPromotedPost(node: Entity): boolean {\n const actor = node.actor as { subDescription?: { text?: unknown } } | undefined;\n const sub = actor?.subDescription?.text;\n return typeof sub === 'string' && /^promoted\\b/i.test(sub.trim());\n}\n\nfunction isNoise(node: Entity): boolean {\n if (isPromotedPost(node)) return true;\n const t = typeOf(node).toLowerCase();\n if (t === '') return false;\n return DROP_TYPE_FRAGMENTS.some((f) => t.includes(f));\n}\n\nfunction isDecoration(node: Entity): boolean {\n const t = typeOf(node).toLowerCase();\n return DECORATION_FRAGMENTS.some((f) => t.includes(f));\n}\n\n/**\n * Whether we recognise this type as one we have actually seen. Used ONLY to\n * count unknowns for reporting — never to decide whether to keep something.\n */\nconst KNOWN_CONTENT = [\n 'updatev2',\n 'profile',\n 'jobposting',\n 'company',\n 'comment',\n 'reaction',\n 'entityresult',\n];\n\nfunction isKnown(node: Entity): boolean {\n const t = typeOf(node).toLowerCase();\n return KNOWN_CONTENT.some((f) => t.includes(f)) || isDecoration(node) || isNoise(node);\n}\n\n/** Build the `entityUrn → node` index in one pass, canonicalising namespaces. */\nexport function indexIncluded(included: unknown): Map<string, Entity> {\n const index = new Map<string, Entity>();\n if (!Array.isArray(included)) return index;\n\n for (const raw of included) {\n if (raw === null || typeof raw !== 'object') continue;\n const node = raw as Entity;\n const urn = node.entityUrn;\n if (typeof urn !== 'string') continue;\n\n // Store under BOTH the canonical and the literal form: references in `data`\n // may use either side of the fs_*/fsd_* migration.\n const canonical = canonicalUrn(urn);\n index.set(canonical, node);\n if (canonical !== urn) index.set(urn, node);\n }\n return index;\n}\n\nexport interface ResolveResult {\n resolved: Entity[];\n unresolved: string[];\n}\n\n/** Resolve an ordered list of URN references against the index. */\nexport function resolveRefs(refs: unknown, index: Map<string, Entity>): ResolveResult {\n const resolved: Entity[] = [];\n const unresolved: string[] = [];\n if (!Array.isArray(refs)) return { resolved, unresolved };\n\n for (const ref of refs) {\n if (typeof ref !== 'string') continue;\n const node = index.get(ref) ?? index.get(canonicalUrn(ref));\n if (node === undefined) unresolved.push(ref);\n else resolved.push(node);\n }\n return { resolved, unresolved };\n}\n\nexport interface ParseOpts {\n operation: string;\n /** What the platform claims exists, when it tells us. */\n claimedCount?: number;\n contractCapturedAt?: string;\n truncated?: boolean;\n}\n\nexport interface ParseMeta {\n state: FetchState;\n operation: string;\n contractCapturedAt: string;\n rawCandidateCount: number;\n parsedCount: number;\n excludedCount: number;\n unknownCount: number;\n returnedCount: number;\n claimedCount?: number;\n truncated: boolean;\n unresolved?: string[];\n unknownTypes?: { type: string; count: number }[];\n warnings: string[];\n}\n\nexport interface ParseResult {\n items: Entity[];\n meta: ParseMeta;\n}\n\n/**\n * Find the ordered reference list. Voyager marks references with a `*` prefix,\n * but arranges them in two quite different ways, and a parser that knows only\n * one returns an empty result for the other — with `ok:true`.\n *\n * Collection shape data[\"*elements\"] = [urn, urn, …]\n * feed, dashProfiles. One array, already in order.\n *\n * Cluster shape data.data.<op>.elements[].items[].item[\"*entityResult\"] = urn\n * search. One SINGLE string per item, nested three levels\n * down and spread across clusters.\n *\n * Both were captured live on 2026-08-01. Search parsed to zero items until this\n * handled the second shape — found only because the parser was run against a\n * real capture rather than its own fixtures.\n */\nfunction findRefs(data: unknown): unknown[] {\n if (data === null || typeof data !== 'object') return [];\n\n // Pass 1 — the shallowest `*`-prefixed ARRAY wins. Breadth-first, so a\n // top-level \"*elements\" is preferred over anything nested beneath it.\n const queue: unknown[] = [data];\n while (queue.length > 0) {\n const node = queue.shift();\n if (node === null || typeof node !== 'object') continue;\n if (Array.isArray(node)) {\n queue.push(...node);\n continue;\n }\n for (const [key, value] of Object.entries(node)) {\n if (key.startsWith('*') && Array.isArray(value)) return value;\n }\n for (const value of Object.values(node)) {\n if (value !== null && typeof value === 'object') queue.push(value);\n }\n }\n\n // Pass 2 — no reference array anywhere, so collect `*`-prefixed STRINGS in\n // document order. Depth-first and in-order, because the order items appear\n // in the response IS the ranking LinkedIn assigned them.\n const refs: string[] = [];\n const walk = (node: unknown): void => {\n if (node === null || typeof node !== 'object') return;\n if (Array.isArray(node)) {\n for (const item of node) walk(item);\n return;\n }\n for (const [key, value] of Object.entries(node)) {\n if (key.startsWith('*') && typeof value === 'string') refs.push(value);\n else walk(value);\n }\n };\n walk(data);\n return refs;\n}\n\n/**\n * A single-entity response (`/me`) carries no reference list at all — just one\n * decorated node in `included[]`. Returns undefined rather than throwing when\n * there is nothing, so callers decide what an absence means.\n */\nexport function parseSingle(payload: unknown): Entity | undefined {\n const envelope = (payload ?? {}) as { included?: unknown };\n const nodes = [...new Set(indexIncluded(envelope.included).values())];\n if (nodes.length === 0) return undefined;\n // Prefer a content node; fall back to the first, since a decoration is still\n // better than nothing when that is all the endpoint returns.\n return nodes.find((n) => !isNoise(n) && !isDecoration(n)) ?? nodes[0];\n}\n\nexport function parseCollection(payload: unknown, opts: ParseOpts): ParseResult {\n const envelope = (payload ?? {}) as { data?: unknown; included?: unknown };\n const index = indexIncluded(envelope.included);\n const refs = findRefs(envelope.data);\n const { resolved, unresolved } = resolveRefs(refs, index);\n\n const items: Entity[] = [];\n const unknownTypes = new Map<string, number>();\n let excludedCount = 0;\n let unknownCount = 0;\n\n for (const node of resolved) {\n // Per-item isolation: one malformed node never takes the page with it.\n try {\n if (isNoise(node) || isDecoration(node)) {\n excludedCount++;\n continue;\n }\n if (!isKnown(node)) {\n // Unknown → KEEP it (rule 2), and count it so the drift is visible.\n const t = typeOf(node);\n unknownTypes.set(t, (unknownTypes.get(t) ?? 0) + 1);\n unknownCount++;\n }\n items.push(node);\n } catch {\n excludedCount++;\n }\n }\n\n const warnings: string[] = [];\n if (unresolved.length > 0) {\n warnings.push(\n `${unresolved.length} referenced entities were not present in included[] — the decoration failed for those, so this record is incomplete rather than short.`,\n );\n }\n if (opts.claimedCount !== undefined && opts.claimedCount > 0 && items.length === 0) {\n warnings.push(\n `LinkedIn claims ${opts.claimedCount} items but returned none — treat this as a FAILED FETCH, not an empty result.`,\n );\n }\n\n const state: FetchState =\n unresolved.length > 0 ? 'partial' : opts.truncated === true ? 'unknown' : 'complete';\n\n const meta: ParseMeta = {\n state,\n operation: opts.operation,\n contractCapturedAt: opts.contractCapturedAt ?? 'unknown',\n // parsedCount counts what we kept; `items` includes the unknowns, which is\n // why unknownCount is reported separately rather than added again here.\n rawCandidateCount: resolved.length,\n parsedCount: items.length - unknownCount,\n excludedCount,\n unknownCount,\n returnedCount: items.length,\n truncated: opts.truncated ?? false,\n warnings,\n };\n if (opts.claimedCount !== undefined) meta.claimedCount = opts.claimedCount;\n if (unresolved.length > 0) meta.unresolved = unresolved;\n if (unknownTypes.size > 0) {\n meta.unknownTypes = [...unknownTypes.entries()].map(([type, count]) => ({ type, count }));\n }\n\n return { items, meta };\n}\n","// The Engine interface and its real construction. This is the seam: everything\n// above it is pure and testable, everything below it talks to LinkedIn.\n\nimport { cachePath, loadJson, saveJson } from '../cache/store.ts';\nimport { progressReporter } from '../progress.ts';\nimport type { Session } from './auth.ts';\nimport { type Cooldown, emptyLedger, type Ledger } from './budget.ts';\nimport { type Client, type ClientDeps, createClient } from './client.ts';\nimport { contractFor } from './contracts.ts';\nimport {\n type Entity,\n indexIncluded,\n type ParseResult,\n parseCollection,\n parseSingle,\n} from './parse.ts';\nimport { canonicalUrn, encodeVariables } from './restli.ts';\n\nexport interface Engine {\n whoami(): Promise<EngineResult<Entity | undefined>>;\n profile(memberId: string): Promise<EngineResult<ProfileResult | undefined>>;\n feed(limit: number): Promise<EngineResult<Collection>>;\n search(kind: SearchKind, query: string, limit: number): Promise<EngineResult<Collection>>;\n post(postUrn: string, limit: number): Promise<EngineResult<Collection>>;\n myPosts(profileUrn: string, limit: number): Promise<EngineResult<Collection>>;\n connections(limit: number): Promise<EngineResult<Collection>>;\n reactions(postUrn: string, limit: number): Promise<EngineResult<Collection>>;\n}\n\nexport type SearchKind = 'people' | 'companies' | 'jobs';\n\n/**\n * A profile plus the side-table it references. LinkedIn returns location,\n * current position and education as URN references into `included[]`, so the\n * caller needs the index to make sense of the profile node.\n */\n/** A parsed collection plus the side-table its entities reference. */\nexport interface Collection {\n parsed: ParseResult;\n index: Map<string, Entity>;\n}\n\nexport interface ProfileResult {\n profile: Entity;\n index: Map<string, Entity>;\n}\n\nexport type EngineResult<T> =\n | { ok: true; value: T }\n | { ok: false; code: string; message: string; hint?: string; retryAfterMs?: number };\n\nconst RESULT_TYPE: Record<SearchKind, string> = {\n people: 'PEOPLE',\n companies: 'COMPANIES',\n jobs: 'JOBS',\n};\n\nfunction missingContract(name: string): EngineResult<never> {\n return {\n ok: false,\n code: 'NOT_IMPLEMENTED',\n message: `no verified contract for '${name}'`,\n hint:\n 'Only endpoints that returned 200 on this machine may back a command. ' +\n 'Capture it with `bun run scripts/observe.ts`, verify it, then mark it verified in src/engine/contracts.ts.',\n };\n}\n\n/**\n * A live client on the real cache files. Exported because writes need a client\n * without needing an Engine — the write surface is not part of the read\n * contract, but it must share the same ledger, cooldown and pacing, and a\n * second construction of those would be a second breaker that agrees with the\n * first only by luck.\n */\nexport function createLiveClient(\n session: Session,\n deps?: Partial<ClientDeps>,\n quiet = false,\n): Client {\n return createClient(session, {\n fetch: globalThis.fetch,\n // stdout stays JSON-only; progress is human chatter and goes to stderr.\n progress: progressReporter(quiet),\n now: () => Date.now(),\n sleep: (ms) => new Promise((r) => setTimeout(r, ms)),\n random: () => Math.random(),\n loadLedger: () => {\n const r = loadJson<Ledger>(cachePath('budget.json'));\n return r.state === 'ok' ? r.value : emptyLedger();\n },\n saveLedger: (l) => saveJson(cachePath('budget.json'), l),\n loadCooldown: () => {\n const r = loadJson<Cooldown | null>(cachePath('cooldown.json'));\n return r.state === 'ok' ? r.value : null;\n },\n saveCooldown: (c) => saveJson(cachePath('cooldown.json'), c),\n ...deps,\n });\n}\n\nexport function createEngine(session: Session, deps?: Partial<ClientDeps>, quiet = false): Engine {\n const client: Client = createLiveClient(session, deps, quiet);\n\n return {\n async whoami() {\n const contract = contractFor('me');\n if (contract === undefined) return missingContract('me');\n\n const res = await client.request({\n url: contract.path,\n spendClass: 'profile',\n operation: 'me',\n });\n if (!res.ok) return res;\n return { ok: true, value: parseSingle(res.json) };\n },\n\n async profile(memberId) {\n const contract = contractFor('profile');\n if (contract === undefined) return missingContract('profile');\n\n const variables = encodeVariables({ memberIdentity: memberId });\n const url = `${contract.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract.queryId}`;\n const res = await client.request({ url, spendClass: 'profile', operation: 'profile' });\n if (!res.ok) return res;\n\n const envelope = res.json as { included?: unknown };\n const index = indexIncluded(envelope.included);\n const profile = [...new Set(index.values())].find((n) =>\n String(n.$type ?? '').endsWith('profile.Profile'),\n );\n if (profile === undefined) return { ok: true, value: undefined };\n return { ok: true, value: { profile, index } };\n },\n\n async feed(limit) {\n const contract = contractFor('feed');\n if (contract === undefined) return missingContract('feed');\n\n const url = `${contract.path}?q=chronFeed&count=${limit}&start=0`;\n const res = await client.request({ url, spendClass: 'page', operation: 'feed' });\n if (!res.ok) return res;\n const envelope = res.json as { included?: unknown };\n return {\n ok: true,\n value: {\n parsed: parseCollection(res.json, {\n operation: 'feed',\n contractCapturedAt: contract.capturedAt,\n }),\n index: indexIncluded(envelope.included),\n },\n };\n },\n\n async myPosts(profileUrn, limit) {\n const contract = contractFor('myPosts');\n if (contract === undefined) return missingContract('myPosts');\n\n // `whoami` answers with an `fs_miniProfile` urn; this is a DASH endpoint\n // and wants `fsd_profile`. The legacy form returns 200 with an empty\n // result — no error, no warning — which is why this shipped as\n // \"verified\": the account had no posts when the contract was captured,\n // so empty was indistinguishable from working.\n const variables = encodeVariables({\n count: Math.min(limit, 100),\n start: 0,\n profileUrn: canonicalUrn(profileUrn),\n });\n const url = `${contract.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract.queryId}`;\n const res = await client.request({ url, spendClass: 'page', operation: 'myPosts' });\n if (!res.ok) return res;\n\n const envelope = res.json as { included?: unknown };\n return {\n ok: true,\n value: {\n parsed: parseCollection(res.json, {\n operation: 'myPosts',\n contractCapturedAt: contract.capturedAt,\n truncated: true,\n }),\n index: indexIncluded(envelope.included),\n },\n };\n },\n\n /**\n * Connections are a FILTERED PEOPLE SEARCH, not a list endpoint — LinkedIn\n * exposes no change stream for them. That is why the cache stores them as a\n * snapshot and diffs, rather than pretending a watermark exists.\n */\n async connections(limit) {\n const contract = contractFor('search');\n if (contract === undefined) return missingContract('search');\n\n const variables = encodeVariables({\n start: 0,\n origin: 'FACETED_SEARCH',\n query: {\n flagshipSearchIntent: 'SEARCH_SRP',\n queryParameters: [\n { key: 'resultType', value: ['PEOPLE'] },\n { key: 'network', value: ['F'] },\n ],\n includeFiltersInResponse: false,\n },\n });\n const url = `${contract.path}?variables=${variables}&queryId=${contract.queryId}`;\n const res = await client.request({ url, spendClass: 'search', operation: 'connections' });\n if (!res.ok) return res;\n\n const parsed = parseCollection(res.json, {\n operation: 'connections',\n contractCapturedAt: contract.capturedAt,\n claimedCount: totalResultCount(res.json),\n truncated: true,\n });\n parsed.items = parsed.items.slice(0, limit);\n parsed.meta.returnedCount = parsed.items.length;\n const envelope = res.json as { included?: unknown };\n return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };\n },\n\n async post(postUrn, limit) {\n const contract = contractFor('comments');\n if (contract === undefined) return missingContract('comments');\n\n const variables = encodeVariables({\n count: Math.min(limit, 100),\n numReplies: 1,\n socialDetailUrn: socialDetailUrn(postUrn),\n sortOrder: 'RELEVANCE',\n start: 0,\n });\n const url = `${contract.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract.queryId}`;\n const res = await client.request({ url, spendClass: 'page', operation: 'comments' });\n if (!res.ok) return res;\n\n const parsed = parseCollection(res.json, {\n operation: 'comments',\n contractCapturedAt: contract.capturedAt,\n // A page of many; we follow no cursor yet, so never claim exhaustion.\n truncated: true,\n });\n const envelope = res.json as { included?: unknown };\n return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };\n },\n\n async reactions(postUrn, limit) {\n const contract = contractFor('reactions');\n if (contract === undefined) return missingContract('reactions');\n\n const variables = encodeVariables({\n count: Math.min(limit, 100),\n start: 0,\n threadUrn: postUrn,\n });\n const url = `${contract.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract.queryId}`;\n const res = await client.request({ url, spendClass: 'page', operation: 'reactions' });\n if (!res.ok) return res;\n\n const parsed = parseCollection(res.json, {\n operation: 'reactions',\n contractCapturedAt: contract.capturedAt,\n truncated: true,\n });\n const envelope = res.json as { included?: unknown };\n return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };\n },\n\n async search(kind, query, limit) {\n const contract = contractFor('search');\n if (contract === undefined) return missingContract('search');\n\n const variables = encodeVariables({\n start: 0,\n origin: 'GLOBAL_SEARCH_HEADER',\n query: {\n keywords: query,\n flagshipSearchIntent: 'SEARCH_SRP',\n queryParameters: [{ key: 'resultType', value: [RESULT_TYPE[kind]] }],\n includeFiltersInResponse: false,\n },\n });\n const url = `${contract.path}?variables=${variables}&queryId=${contract.queryId}`;\n const res = await client.request({ url, spendClass: 'search', operation: 'search' });\n if (!res.ok) return res;\n\n const parsed = parseCollection(res.json, {\n operation: 'search',\n contractCapturedAt: contract.capturedAt,\n claimedCount: totalResultCount(res.json),\n truncated: true, // one page of many; we never claim exhaustion\n });\n parsed.items = parsed.items.slice(0, limit);\n parsed.meta.returnedCount = parsed.items.length;\n const envelope = res.json as { included?: unknown };\n return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };\n },\n };\n}\n\n/**\n * The composite urn the comments endpoint keys off: the post's own urn,\n * repeated, plus a highlightedReply placeholder. Assembled rather than fetched\n * — verified working with an `urn:li:activity:` urn, so `post` needs no prior\n * lookup to find the ugcPost form.\n */\nfunction socialDetailUrn(postUrn: string): string {\n return `urn:li:fsd_socialDetail:(${postUrn},${postUrn},urn:li:highlightedReply:-)`;\n}\n\n/** LinkedIn's own claimed total, used to detect a claimed-but-empty fetch. */\nfunction totalResultCount(json: unknown): number | undefined {\n const found = JSON.stringify(json ?? {}).match(/\"totalResultCount\":(\\d+)/);\n return found?.[1] === undefined ? undefined : Number(found[1]);\n}\n","// ─── Harvesting the tokens a comment needs ────────────────────────────────────\n//\n// Commenting needs two things that a reaction does not: a `trackingId` from the\n// feed render, and an opaque `commentBoxStateId` binding key. Both live in the\n// rendered post page, and that page is a PLAIN AUTHENTICATED GET — no browser,\n// no CDP. See docs/research/W5 for the capture this is built from.\n//\n// Scraping a rendered page is the most drift-prone thing in this codebase, so\n// the design leans on one lucky property: the binding key CONTAINS the post id.\n//\n// commentBoxText-<base64(post id)><31 opaque bytes><FeedType_…>\n//\n// The first segment is the activity id, zigzag-encoded as a protobuf sint64.\n// That means a harvested key can be PROVEN to belong to the post we intend to\n// comment on, rather than trusted because of where it was found. A feed page\n// carries comment boxes for many posts; picking the wrong one would post a\n// comment on a stranger's update under the owner's name. The id check makes\n// that structurally impossible instead of merely unlikely.\n\n/** Zigzag encoding: what protobuf uses for signed ints. Positive n -> 2n. */\nfunction zigzag(n: bigint): bigint {\n return (n << 1n) ^ (n >> 63n);\n}\n\nfunction varint(n: bigint): number[] {\n const out: number[] = [];\n let v = n;\n while (v > 0x7fn) {\n out.push(Number((v & 0x7fn) | 0x80n));\n v >>= 7n;\n }\n out.push(Number(v));\n return out;\n}\n\n/**\n * The derivable first segment of a comment-box binding key.\n *\n * BigInt throughout: activity ids exceed Number.MAX_SAFE_INTEGER, and doing\n * this in a JS number rounds silently — encoding a segment for a post that\n * does not exist.\n */\nexport function activityIdSegment(activityId: string): string {\n if (!/^\\d+$/.test(activityId)) {\n throw new Error(`'${activityId}' is not a numeric activity id`);\n }\n const inner = [0x08, ...varint(zigzag(BigInt(activityId)))];\n const message = Uint8Array.from([0x0a, inner.length, ...inner]);\n // UNPADDED. The key format is `commentBoxText-<A>-<B><FeedType_…>`, where the\n // '-' after segment A is a SEPARATOR, not padding. One capture made these\n // indistinguishable — its segment B began with '-', so an 18-char segment\n // plus a separator read exactly like a 20-char padded one. A unit test built\n // on that single sample passed against a wrong encoder; only a second post\n // exposed it.\n return btoa(String.fromCharCode(...message)).replace(/=+$/, '');\n}\n\n/** Whether a harvested key really belongs to this post. */\nexport function keyMatchesPost(bindingKey: string, activityId: string): boolean {\n try {\n return bindingKey.startsWith(`commentBoxText-${activityIdSegment(activityId)}-`);\n } catch {\n return false;\n }\n}\n\nexport type HarvestResult =\n | { ok: true; bindingKey: string; trackingId: string }\n | { ok: false; message: string; hint?: string };\n\n/** Markers that mean we were served something other than the post. */\nconst NOT_THE_POST = /checkpoint\\/challenge|\\/uas\\/login|authwall|\"status\"\\s*:\\s*999/i;\n\n/**\n * How close a trackingId must sit to a mention of the post id to be ITS id.\n *\n * Measured, not guessed: on a real permalink the update's own trackingId was 24\n * characters from an activity-id mention, while the next nearest candidate was\n * 13,613 away. The page also carries a page-level trackingId beside `treeId`\n * and `pageForestId` that has nothing to do with the post — taking the first\n * match in document order picks exactly that wrong one.\n */\nconst TRACKING_PROXIMITY = 400;\n\n/** A trackingId whose position proves it belongs to this update. */\nfunction updateTrackingId(html: string, activityId: string): string | null {\n const idAt = [...html.matchAll(new RegExp(activityId, 'g'))].map((m) => m.index ?? 0);\n if (idAt.length === 0) return null;\n\n // Quotes arrive HTML-escaped inside the embedded payloads.\n const pattern = /trackingId(?:"|\\\\?\")+\\s*:\\s*(?:"|\\\\?\")+([A-Za-z0-9+/=]{16,32})/g;\n let best: { value: string; distance: number } | null = null;\n for (const m of html.matchAll(pattern)) {\n const at = m.index ?? 0;\n const distance = Math.min(...idAt.map((p) => Math.abs(p - at)));\n if (best === null || distance < best.distance) best = { value: m[1] as string, distance };\n }\n return best !== null && best.distance <= TRACKING_PROXIMITY ? best.value : null;\n}\n\n/**\n * Pull the two tokens out of a rendered post page.\n *\n * Every failure here is loud. A comment built on a stale, empty or foreign\n * binding is the failure mode this whole module exists to prevent, and an\n * absent token must never reach the payload as `undefined`.\n */\nexport function extractCommentTokens(html: string, activityId: string): HarvestResult {\n if (NOT_THE_POST.test(html)) {\n return {\n ok: false,\n message: 'the page returned was a challenge or sign-in wall, not the post',\n hint: 'Re-mint the session with `lnrelay login`, then check `lnrelay risk`.',\n };\n }\n\n // Only keys carrying THIS post's id are candidates. A feed page contains\n // comment boxes for many posts.\n let expected: string;\n try {\n expected = activityIdSegment(activityId);\n } catch (e) {\n return { ok: false, message: (e as Error).message };\n }\n\n const keyPattern = new RegExp(\n `commentBoxText-${expected.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}-[A-Za-z0-9+/_=-]*FeedType_[A-Z_]+`,\n );\n const key = keyPattern.exec(html)?.[0];\n if (key === undefined) {\n return {\n ok: false,\n message: `no comment-box binding key for post ${activityId} was found in the page`,\n hint:\n 'Either the post does not accept comments, or LinkedIn changed the rendered shape. ' +\n 'Re-capture with `bun run scripts/observe-write.ts` before changing this parser.',\n };\n }\n\n const trackingId = updateTrackingId(html, activityId);\n if (trackingId === null) {\n return {\n ok: false,\n message: `no trackingId adjacent to post ${activityId} was found in the page`,\n hint:\n 'The page carries several — one for the page itself, one per rendered update. Only the ' +\n \"update's own will do, and guessing would build a malformed comment.\",\n };\n }\n\n return { ok: true, bindingKey: key, trackingId };\n}\n","// ─── Asking the server what it can do ─────────────────────────────────────────\n//\n// SDUI is server-DRIVEN: the server ships the UI description, and that\n// description contains each action's id and its fully-populated arguments. So\n// the comment \"…\" menu is not just a menu — it is a contract listing, and\n// requesting it tells us how to delete or edit a comment without capturing a\n// single browser request.\n//\n// That matters beyond convenience. Every other write in this tool was learned\n// by observing traffic and is therefore a snapshot: correct until LinkedIn\n// changes it, and silently wrong after. An action replayed from the menu the\n// server just sent is correct BY CONSTRUCTION — if the shape changes, the menu\n// changes with it, and we follow.\n//\n// The payloads are taken verbatim rather than rebuilt from a hardcoded shape.\n// The one thing we substitute is the comment text on an edit, which is the only\n// part that is ours to decide.\n\nimport type { Client } from './client.ts';\n\nconst SDUI_ACTION = 'https://www.linkedin.com/flagship-web/rsc-action/actions/server-request';\n\nconst MENU_OP = 'com.linkedin.sdui.requests.comments.commentControlMenuRequest';\nconst SCREEN_ID = 'com.linkedin.sdui.flagshipnav.feed.UpdateDetail';\n\nexport const DELETE_OP = 'com.linkedin.sdui.comments.deleteComment';\nexport const UPDATE_OP = 'com.linkedin.sdui.comments.updateComment';\n\nexport function actionUrl(operation: string): string {\n return `${SDUI_ACTION}?sduiid=${operation}`;\n}\n\n/** Wrap arguments in the envelope every SDUI action call uses. */\nexport function sduiEnvelope(operation: string, payload: unknown, states: unknown[] = []) {\n const args = {\n $type: 'proto.sdui.actions.requests.RequestedArguments',\n requestedStateKeys: [],\n payload,\n requestMetadata: { $type: 'proto.sdui.common.RequestMetadata' },\n };\n return {\n requestId: operation,\n serverRequest: {\n requestId: operation,\n requestedArguments: args,\n isApfcEnabled: false,\n isStreaming: false,\n rumPageKey: '',\n },\n states,\n requestedArguments: { ...args, states, screenId: SCREEN_ID, knownTemplateIds: [] },\n };\n}\n\nexport function menuBody(ref: CommentRef, trackingId: string) {\n const { activityId, commentId, threadType } = ref;\n const activityUrn = { activityUrn: { activityId } };\n return sduiEnvelope(MENU_OP, {\n // Rebuilt in the namespace it came from. A comment threaded to a ugcPost\n // given an `urn:li:activity:` thread names a different entity, and that\n // does not error — it acts on the wrong thing or finds nothing.\n commentUrn: { commentId, thread: `urn:li:${threadType}:${activityId}` },\n updateKey: {\n feedType: 3,\n items: [{ feedUpdateUrn: { updateUrnActivityUrn: activityUrn }, trackingId }],\n aggregationType: 0,\n isVideoCarousel: false,\n },\n menuContentRef: `auto-component-${crypto.randomUUID()}`,\n });\n}\n\n/**\n * Pull one action's payload out of a menu response.\n *\n * The response is a React Server Components stream, not JSON, so the payload is\n * located by scanning for the operation id and then reading the balanced JSON\n * object that follows its `\"payload\":` key. Brace-matching rather than a regex,\n * because these payloads nest several levels deep and a greedy match would\n * swallow half the stream.\n */\nexport function extractActionPayload(stream: string, operation: string): unknown | null {\n const at = stream.indexOf(operation);\n if (at === -1) return null;\n\n const key = stream.indexOf('\"payload\":', at);\n if (key === -1) return null;\n\n const start = stream.indexOf('{', key);\n if (start === -1) return null;\n\n let depth = 0;\n let inString = false;\n let escaped = false;\n for (let i = start; i < stream.length; i++) {\n const ch = stream[i] as string;\n if (escaped) {\n escaped = false;\n } else if (ch === '\\\\') {\n escaped = true;\n } else if (ch === '\"') {\n inString = !inString;\n } else if (!inString && ch === '{') {\n depth++;\n } else if (!inString && ch === '}') {\n depth--;\n if (depth === 0) {\n try {\n return JSON.parse(stream.slice(start, i + 1)) as unknown;\n } catch {\n return null;\n }\n }\n }\n }\n return null;\n}\n\nexport type MenuResult =\n | { ok: true; stream: string }\n | { ok: false; code: string; message: string; hint?: string };\n\n/** Fetch the comment's action menu. A read, though it is issued as a POST. */\nexport async function fetchCommentMenu(\n ref: CommentRef,\n trackingId: string,\n client: Client,\n): Promise<MenuResult> {\n const result = await client.request({\n url: actionUrl(MENU_OP),\n method: 'POST',\n body: menuBody(ref, trackingId),\n spendClass: 'page',\n operation: 'commentMenu',\n });\n\n if (!result.ok) {\n const out: MenuResult = { ok: false, code: result.code, message: result.message };\n if (result.hint !== undefined) out.hint = result.hint;\n return out;\n }\n // The stream is not JSON; the client hands back the raw text as `json: null`\n // with the body preserved on the classification.\n const stream = (result.classification as { raw?: string }).raw ?? '';\n return { ok: true, stream };\n}\n\nexport interface CommentRef {\n /** The numeric id of the thread this comment hangs off. */\n activityId: string;\n commentId: string;\n /**\n * Which namespace the thread was written in.\n *\n * NOT always `activity`. A comment in the feed came back threaded to a\n * `ugcPost`, and ENGINE-RESEARCH §5b already records that the two are\n * distinct and not derivable from one another — so the namespace is carried\n * rather than assumed, and callers that must rebuild a urn use this.\n */\n threadType: 'activity' | 'ugcPost';\n}\n\nexport type ActionResult =\n | { ok: true; operation: string }\n | { ok: false; code: string; message: string; hint?: string };\n\n/**\n * The state id of a REPLY box: the parent comment's urn.\n *\n * A reply is `createComment` with its bindings keyed to the parent comment\n * instead of to the post's opaque key — discovered by rendering the reply box's\n * submit button and reading the action it declared. The payload has NO parent\n * field; the binding is the parent reference. Send the post's key by mistake\n * and you publish a top-level comment on someone's thread instead of a reply,\n * with nothing erroring.\n */\nexport function boxStateId(parent: CommentRef): string {\n return `urn:li:comment:(urn:li:${parent.threadType}:${parent.activityId},${parent.commentId})`;\n}\n\n/**\n * Build the two text states from whichever names the server used for the\n * bindings. A reply payload calls them commentFieldBinding /\n * richCommentFieldBinding; an edit payload calls them commentary /\n * richTextCommentary. Returns [] when neither is present, so callers refuse\n * rather than sending a half-populated state that posts blank text.\n */\nexport function textStates(payload: Record<string, unknown>, text: string): unknown[] {\n const keyOf = (...names: string[]): string | null => {\n for (const n of names) {\n const slot = payload[n] as { key?: unknown } | undefined;\n if (typeof slot?.key === 'string') return slot.key;\n }\n return null;\n };\n const plain = keyOf('commentary', 'commentFieldBinding');\n const rich = keyOf('richTextCommentary', 'richCommentFieldBinding');\n if (plain === null || rich === null) return [];\n\n const entry = (key: string, value: unknown, protoCase: string) => ({\n key,\n namespace: 'MemoryNamespace',\n value,\n originalProtoCase: protoCase,\n protoKey: { $type: 'proto.sdui.Key', value: { $case: 'id', id: key } },\n });\n return [\n entry(plain, text, 'stringValue'),\n entry(rich, { text, attribute: [], $type: 'TextModel', source: 'local' }, 'textModelForWrite'),\n ];\n}\n\n/**\n * States for an edit: the new text under the keys the SERVER named.\n *\n * The keys come out of the menu payload rather than being rebuilt, because the\n * server already told us what they are — and for an edit they turn out to be\n * the plain comment urn, not the opaque binding a new comment needs.\n */\nfunction editStates(payload: Record<string, unknown>, text: string): unknown[] {\n return textStates(payload, text);\n}\n\n/**\n * Run a delete or edit on a comment, using the payload the SERVER just handed\n * us for that exact action.\n *\n * Nothing about the payload is reconstructed from a hardcoded shape. That is\n * the point: every other write here is a snapshot of traffic that was correct\n * when captured, while this one is correct by construction — if LinkedIn\n * changes the arguments, the menu changes with them and we follow.\n */\nexport async function runCommentAction(\n ref: CommentRef,\n operation: typeof DELETE_OP | typeof UPDATE_OP,\n trackingId: string,\n client: Client,\n newText?: string,\n): Promise<ActionResult> {\n const menu = await fetchCommentMenu(ref, trackingId, client);\n if (!menu.ok) return { ok: false, code: menu.code, message: menu.message };\n\n const payload = extractActionPayload(menu.stream, operation) as Record<string, unknown> | null;\n if (payload === null) {\n return {\n ok: false,\n code: 'NOT_IMPLEMENTED',\n message: `LinkedIn did not offer '${operation.split('.').pop()}' on this comment`,\n hint:\n 'The menu lists only what the server permits — you may not own this comment, or the ' +\n 'action may not exist on this surface. Nothing was sent.',\n };\n }\n\n // Guard on the id the SERVER echoed, not the one we asked for. If they\n // disagree, we would be acting on someone else's comment.\n const echoed = (payload.commentUrn as { commentId?: unknown } | undefined)?.commentId;\n if (echoed !== ref.commentId) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: `the menu described comment ${String(echoed)} but we asked about ${ref.commentId}`,\n hint: 'Refusing to send — this is how an action lands on the wrong comment.',\n };\n }\n\n const states =\n operation === UPDATE_OP && newText !== undefined ? editStates(payload, newText) : [];\n if (operation === UPDATE_OP && states.length === 0) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: 'the menu did not name the comment-text state keys, so an edit cannot be built',\n };\n }\n\n const result = await client.request({\n url: actionUrl(operation),\n method: 'POST',\n body: sduiEnvelope(operation, payload, states),\n spendClass: 'write',\n operation: operation.split('.').pop() ?? operation,\n });\n\n if (!result.ok) {\n const out: ActionResult = { ok: false, code: result.code, message: result.message };\n if (result.hint !== undefined) out.hint = result.hint;\n return out;\n }\n return { ok: true, operation };\n}\n\n/**\n * Parse any of the three live comment-urn forms into its two ids.\n *\n * They do not agree on member order. `post` returns the `fsd_comment` form with\n * the COMMENT id first; the other two put the activity first, one of them\n * without its `urn:li:` prefix. Both members are bare numbers, so reading them\n * positionally and getting it backwards is undetectable downstream — the action\n * simply lands on the wrong thing. Hence matching by shape, never by position.\n */\nexport function parseCommentUrn(urn: string): CommentRef | null {\n const fsd = /^urn:li:fsd_comment:\\((\\d+),urn:li:(activity|ugcPost):(\\d+)\\)$/.exec(urn);\n if (fsd !== null) {\n return {\n commentId: fsd[1] as string,\n threadType: fsd[2] as 'activity' | 'ugcPost',\n activityId: fsd[3] as string,\n };\n }\n\n const plain = /^urn:li:comment:\\((?:urn:li:)?(activity|ugcPost):(\\d+),(\\d+)\\)$/.exec(urn);\n if (plain !== null) {\n return {\n threadType: plain[1] as 'activity' | 'ugcPost',\n activityId: plain[2] as string,\n commentId: plain[3] as string,\n };\n }\n\n return null;\n}\n\nconst SUBMIT_COMPONENT = 'com.linkedin.sdui.generated.comments.dsl.impl.submitCommentButton';\nconst CREATE_OP = 'com.linkedin.sdui.comments.createComment';\n\nconst COMPONENT_URL = 'https://www.linkedin.com/flagship-web/rsc-action/actions/component';\n\n/**\n * WITHDRAWN — this does NOT produce a nested reply. Verified live 2026-08-14:\n * it posted a second TOP-LEVEL comment on the post.\n *\n * The reasoning that produced it was circular. The component render was treated\n * as DISCOVERY, but it is an ECHO: we pass `commentBoxStateId = <parent comment\n * urn>` and the server reflects it back inside the action it describes. The\n * guard below then checked \"is the payload bound to the parent?\" — against a\n * value we ourselves supplied. It could not have failed.\n *\n * So the binding key is NOT sufficient to make a reply, and W5's conclusion\n * that \"the binding key IS the parent reference\" was wrong. Whatever nests a\n * comment is something this has not found. Kept, unexported from the CLI, as\n * the record of a dead end — do not re-wire it without a live test that shows\n * an actual nested reply.\n */\nexport async function fetchReplyAction(\n postActivityId: string,\n parent: CommentRef,\n trackingId: string,\n client: Client,\n): Promise<\n | { ok: true; payload: Record<string, unknown> }\n | { ok: false; code: string; message: string; hint?: string }\n> {\n const activityUrn = { activityUrn: { activityId: postActivityId } };\n const body = {\n clientArguments: {\n payload: {\n collection: {\n updateKey: {\n feedType: 3,\n items: [{ feedUpdateUrn: { updateUrnActivityUrn: activityUrn }, trackingId }],\n aggregationType: 0,\n isVideoCarousel: false,\n },\n threadUrn: { threadUrnActivityThreadUrn: activityUrn },\n },\n // Keying the box to the PARENT COMMENT is what makes this a reply.\n commentBoxStateId: boxStateId(parent),\n },\n states: [],\n requestMetadata: { $type: 'proto.sdui.common.RequestMetadata' },\n screenId: SCREEN_ID,\n knownTemplateIds: [],\n },\n };\n\n const result = await client.request({\n url: `${COMPONENT_URL}?componentId=${SUBMIT_COMPONENT}&sduiid=${SUBMIT_COMPONENT}`,\n method: 'POST',\n body,\n spendClass: 'page',\n operation: 'replyBox',\n });\n if (!result.ok) return { ok: false, code: result.code, message: result.message };\n\n const stream = (result.classification as { raw?: string }).raw ?? '';\n const payload = extractActionPayload(stream, CREATE_OP) as Record<string, unknown> | null;\n if (payload === null) {\n return {\n ok: false,\n code: 'NOT_IMPLEMENTED',\n message: 'the reply box did not declare a createComment action',\n hint: 'Replies may be closed on this post, or the component shape changed. Nothing was sent.',\n };\n }\n\n // The binding must name the parent we asked about. If it names the post\n // instead, sending this would publish a TOP-LEVEL comment on someone's\n // thread rather than a reply — the exact failure this check exists for.\n const bound = (payload.commentFieldBinding as { key?: unknown } | undefined)?.key;\n if (typeof bound !== 'string' || !bound.includes(boxStateId(parent))) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: 'the reply box came back bound to something other than the parent comment',\n hint: 'Refusing to send — this is how a reply becomes a top-level comment.',\n };\n }\n\n return { ok: true, payload };\n}\n\n/** Post a reply to a comment. The payload comes from the server, not from us. */\nexport async function replyToComment(\n postActivityId: string,\n parent: CommentRef,\n text: string,\n trackingId: string,\n client: Client,\n): Promise<ActionResult> {\n const action = await fetchReplyAction(postActivityId, parent, trackingId, client);\n if (!action.ok) {\n const out: ActionResult = { ok: false, code: action.code, message: action.message };\n if (action.hint !== undefined) out.hint = action.hint;\n return out;\n }\n\n const states = textStates(action.payload, text);\n if (states.length === 0) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: 'the reply box did not name its text bindings, so a reply cannot be built',\n };\n }\n\n const result = await client.request({\n url: actionUrl(CREATE_OP),\n method: 'POST',\n body: sduiEnvelope(CREATE_OP, action.payload, states),\n spendClass: 'write',\n operation: 'reply',\n });\n if (!result.ok) {\n const out: ActionResult = { ok: false, code: result.code, message: result.message };\n if (result.hint !== undefined) out.hint = result.hint;\n return out;\n }\n return { ok: true, operation: CREATE_OP };\n}\n","// Session persistence and the CDP bootstrap.\n//\n// Credentials live in a 0600 file under the cache dir. The design calls for OS\n// credential storage; that is a Phase 6 hardening step and is recorded as such\n// rather than silently skipped — for now the file is owner-only and the path is\n// gitignored.\n\nimport { cachePath, loadJson, saveJson } from '../cache/store.ts';\nimport type { Session } from './auth.ts';\n\nconst SESSION_FILE = 'session.json';\n\nexport type SessionLoad =\n | { state: 'ok'; session: Session }\n | { state: 'missing' }\n | { state: 'corrupt'; quarantinedTo: string };\n\nexport function loadSession(): SessionLoad {\n const result = loadJson<Session>(cachePath(SESSION_FILE));\n if (result.state === 'ok') return { state: 'ok', session: result.value };\n if (result.state === 'missing') return { state: 'missing' };\n return { state: 'corrupt', quarantinedTo: result.quarantinedTo };\n}\n\nexport function saveSession(session: Session): void {\n saveJson(cachePath(SESSION_FILE), session);\n}\n\n// ─── CDP bootstrap ────────────────────────────────────────────────────────────\n\nconst CDP = 'http://127.0.0.1:9222';\n\nexport const LAUNCH_HINT =\n 'Start Chrome with remote debugging first, DETACHED so it survives:\\n' +\n ' nohup /Applications/Google\\\\ Chrome.app/Contents/MacOS/Google\\\\ Chrome \\\\\\n' +\n ' --remote-debugging-port=9222 --user-data-dir=\"$HOME/.lnrelay/chrome\" \\\\\\n' +\n ' https://www.linkedin.com/feed/ >/dev/null 2>&1 & disown\\n' +\n 'Then log into LinkedIn in that window and visit /feed/ once.';\n\ninterface CdpCookie {\n name: string;\n value: string;\n domain: string;\n}\n\n/**\n * Mint a session from a logged-in Chrome over the DevTools protocol.\n *\n * Visiting `/feed/` matters: that navigation is specifically what sets\n * JSESSIONID. A jar with JSESSIONID but no li_at means the browser has been to\n * linkedin.com but nobody has logged in.\n */\nexport async function mintSessionFromBrowser(): Promise<\n { ok: true; session: Session } | { ok: false; message: string; hint?: string }\n> {\n let targets: { type: string; webSocketDebuggerUrl?: string }[];\n let userAgent: string;\n try {\n targets = (await (await fetch(`${CDP}/json/list`)).json()) as typeof targets;\n const version = (await (await fetch(`${CDP}/json/version`)).json()) as {\n 'User-Agent'?: string;\n };\n userAgent = (version['User-Agent'] ?? '').replace('HeadlessChrome', 'Chrome');\n } catch {\n return { ok: false, message: `no Chrome DevTools endpoint at ${CDP}`, hint: LAUNCH_HINT };\n }\n\n const page = targets.find((t) => t.type === 'page' && t.webSocketDebuggerUrl !== undefined);\n if (page?.webSocketDebuggerUrl === undefined) {\n return { ok: false, message: 'no debuggable Chrome page found', hint: LAUNCH_HINT };\n }\n if (userAgent === '') {\n return { ok: false, message: 'Chrome did not report a User-Agent' };\n }\n\n let cookies: CdpCookie[];\n try {\n cookies = await getAllCookies(page.webSocketDebuggerUrl);\n } catch (e) {\n return { ok: false, message: `CDP failed: ${(e as Error).message}`, hint: LAUNCH_HINT };\n }\n\n const linkedin = cookies.filter((c) => c.domain.includes('linkedin.com'));\n const liAt = linkedin.find((c) => c.name === 'li_at');\n const jsession = linkedin.find((c) => c.name === 'JSESSIONID');\n\n if (liAt === undefined) {\n return {\n ok: false,\n message: 'no li_at cookie — you are not logged in',\n hint: 'Log into linkedin.com in the debug Chrome window, then re-run. Note that JSESSIONID alone is set pre-login and does not mean a session exists.',\n };\n }\n if (jsession === undefined) {\n return {\n ok: false,\n message: 'no JSESSIONID cookie',\n hint: 'Visit https://www.linkedin.com/feed/ in the debug window — that navigation is what sets it.',\n };\n }\n\n return {\n ok: true,\n session: {\n liAt: liAt.value,\n jsessionId: jsession.value,\n userAgent,\n capturedAt: new Date().toISOString().slice(0, 10),\n },\n };\n}\n\nfunction getAllCookies(wsUrl: string): Promise<CdpCookie[]> {\n return new Promise((resolve, reject) => {\n const ws = new WebSocket(wsUrl);\n const timer = setTimeout(() => {\n ws.close();\n reject(new Error('timed out talking to Chrome'));\n }, 10_000);\n\n ws.onopen = () => ws.send(JSON.stringify({ id: 1, method: 'Network.getAllCookies' }));\n ws.onmessage = (ev) => {\n const msg = JSON.parse(String(ev.data)) as { id?: number; result?: { cookies: CdpCookie[] } };\n if (msg.id === 1 && msg.result !== undefined) {\n clearTimeout(timer);\n ws.close();\n resolve(msg.result.cookies);\n }\n };\n ws.onerror = () => {\n clearTimeout(timer);\n reject(new Error('websocket error'));\n };\n });\n}\n","// ─── The unsanctioned write transport ─────────────────────────────────────────\n//\n// Writing over Voyager, with the same two cookies the reads already use.\n//\n// This exists because the sanctioned path has a prerequisite not everyone can\n// meet: `w_member_social` needs a registered developer app, which needs an\n// associated LinkedIn *Page*. Someone with no company has no Page, and so no\n// legitimate way to post to their own feed from their own tools. That is a real\n// gap, not a hypothetical one.\n//\n// docs/DESIGN.md ratified OAuth as the sole write transport, with the rule:\n// \"if OAuth cannot perform an operation, omit the command — never fall back to\n// Voyager SILENTLY.\" This is the non-silent version of that fallback, and the\n// distinction is the whole design:\n//\n// - OAuth is still preferred whenever a token exists. This is the fallback,\n// not the default (see commands/write.ts).\n// - The confirmation prompt names the transport, so the human approving the\n// write knows which surface it goes over before they approve it.\n// - It is CLI-only and TTY-gated exactly like every other write.\n//\n// What this buys, honestly: nothing legal. LinkedIn's User Agreement §8.2 bans\n// automated posting regardless of how the bytes are produced, so this is not\n// \"safer\" than driving a browser — the research (docs/research/W4) found the\n// contract exposure identical and the technical-detection margin small and\n// uncertain in both directions. What it does buy is FAILURE MODE: a raw request\n// either returns a status we can read or it doesn't. A script driving the real\n// composer can post the wrong text, post twice, or report success on a UI that\n// never submitted — and a write is publicly visible under the owner's name.\n//\n// PROVENANCE OF THE PAYLOAD:\n//\n// share ✅ VERIFIED LIVE 2026-08-13. The body below, sent with the six\n// standard headers and the two cookies, created a real public post\n// on the owner's feed. LinkedIn answered **201 Created**. The shape\n// came from four converging OSS clients (docs/research/W1) and was\n// right first time.\n//\n// delete Not yet exercised. Best-evidenced operation in the research, but\n// still `repo` evidence.\n//\n// The 201 is worth recording for a second reason: the classifier accepted only\n// 200, because reads never return anything else, so that first successful post\n// was reported to the user as FETCH_FAILED — after it had already gone live.\n// Reporting a success as a failure is the worst direction to be wrong here: it\n// invites a re-run, and the re-run posts twice. See classify.ts.\n\nimport type { ConfirmedWrite } from '../commands/confirm.ts';\nimport type { Client } from './client.ts';\n\nconst VOYAGER = 'https://www.linkedin.com/voyager/api';\n\nexport const SHARE_URL = `${VOYAGER}/contentcreation/normShares`;\n\nexport type WriteResult =\n | { ok: true; id: string | null; note?: string }\n | { ok: false; code: string; message: string; hint?: string };\n\nexport interface SharePayload {\n visibleToConnectionsOnly: boolean;\n externalAudienceProviders: unknown[];\n commentaryV2: { text: string; attributes: unknown[] };\n origin: string;\n allowedCommentersScope: string;\n postState: string;\n media: unknown[];\n}\n\n/**\n * The create-post body.\n *\n * Note that visibility here is a BOOLEAN (`visibleToConnectionsOnly`), the\n * inverse of the OAuth API's `visibility: 'PUBLIC' | 'CONNECTIONS'` enum.\n * Inverting it by accident publishes a connections-only note to the open web,\n * which is why the mapping is pinned by test rather than inlined at the call.\n */\nexport function sharePayload(text: string, visibility: 'PUBLIC' | 'CONNECTIONS'): SharePayload {\n return {\n visibleToConnectionsOnly: visibility === 'CONNECTIONS',\n externalAudienceProviders: [],\n commentaryV2: { text, attributes: [] },\n origin: 'FEED',\n allowedCommentersScope: 'ALL',\n postState: 'PUBLISHED',\n media: [],\n };\n}\n\n/** Urn prefixes that identify a CREATED POST, as opposed to its author. */\nconst POST_URN = /urn:li:(share|activity|ugcPost):\\d+/;\n\n/**\n * Whether a urn identifies something this endpoint may be pointed at.\n *\n * Checked BEFORE encoding rather than after a failure, because the failure mode\n * of getting it wrong is not an error — a well-formed request naming the wrong\n * kind of entity is a request to destroy the wrong kind of thing, and we have\n * no evidence for what LinkedIn does with one.\n */\nexport function isDeletableUrn(urn: string): boolean {\n return new RegExp(`^${POST_URN.source}$`).test(urn);\n}\n\n/** The colons are path-hostile; the reference implementations all encode them. */\nexport function deleteUrl(urn: string): string {\n return `${SHARE_URL}/${encodeURIComponent(urn)}`;\n}\n\n/**\n * Delete one of the owner's own posts. Irreversible — the confirmation gate\n * upstream is what makes this safe, and it shows the post's text first.\n */\nexport async function deletePost(\n confirmed: ConfirmedWrite<{ urn: string }>,\n client: Client,\n): Promise<WriteResult> {\n const { urn } = confirmed.payload;\n\n const result = await client.request({\n url: deleteUrl(urn),\n method: 'DELETE',\n spendClass: 'write',\n operation: 'delete',\n });\n\n if (result.ok) return { ok: true, id: urn };\n\n // A 404 has two meanings that call for opposite actions, and we cannot tell\n // them apart from here. Saying both beats picking one and being wrong.\n const notFound = result.code === 'NOT_FOUND';\n const out: WriteResult = {\n ok: false,\n code: result.code,\n message: result.message,\n };\n if (notFound) {\n out.hint =\n 'Either the post is already gone — in which case nothing more is needed — or this is the ' +\n 'wrong urn namespace for this endpoint. It is documented against `urn:li:share:<id>`; if ' +\n 'you passed an activity or ugcPost urn, the same numeric id under `urn:li:share:` is the ' +\n 'thing to try next.';\n } else if (result.hint !== undefined) {\n out.hint = result.hint;\n }\n return out;\n}\n\n/**\n * Find the created post's urn anywhere in the response.\n *\n * We have never seen this response body, so this searches rather than reading a\n * known field, and returns null instead of guessing when nothing matches. A\n * null urn means \"posted, but we cannot tell you which post\" — which is a\n * different and honest answer, not a failure.\n */\nexport function extractShareUrn(json: unknown): string | null {\n return JSON.stringify(json ?? null).match(POST_URN)?.[0] ?? null;\n}\n\n/**\n * Post to the owner's own feed over Voyager.\n *\n * Takes a ConfirmedWrite, so this is unreachable without a human having typed\n * the confirmation token at a terminal — the same guarantee the OAuth transport\n * gives, enforced by the type rather than by a check anyone could forget.\n */\nexport async function share(\n confirmed: ConfirmedWrite<{ text: string; visibility: 'PUBLIC' | 'CONNECTIONS' }>,\n client: Client,\n): Promise<WriteResult> {\n const body = sharePayload(confirmed.payload.text, confirmed.payload.visibility);\n\n const result = await client.request({\n url: SHARE_URL,\n method: 'POST',\n body,\n spendClass: 'write',\n operation: 'share',\n });\n\n if (!result.ok) {\n const out: WriteResult = { ok: false, code: result.code, message: result.message };\n if (result.hint !== undefined) out.hint = result.hint;\n return out;\n }\n\n const id = extractShareUrn(result.json);\n return id === null\n ? {\n ok: true,\n id: null,\n note:\n 'LinkedIn accepted the post but the response carried no recognisable urn. Run ' +\n '`lnrelay sync my-posts && lnrelay my-posts` to confirm what actually landed — and ' +\n 'do NOT re-run this command on the assumption it failed, or you will post twice.',\n }\n : { ok: true, id };\n}\n","// ─── The gate every write passes through ──────────────────────────────────────\n//\n// Shared by every write command so there is exactly ONE place that decides a\n// human approved something. A second copy of this logic would be a second\n// policy, agreeing with the first only by luck and diverging on the first edit.\n//\n// The ordering is the safety design:\n//\n// 1. account for the spend BEFORE asking, so a refused budget never reaches\n// a prompt the user cannot act on\n// 2. ask, and require a token derived from the payload\n// 3. commit the spend only after approval — an aborted write costs nothing\n\nimport { createInterface } from 'node:readline/promises';\nimport { cachePath, loadJson, saveJson } from '../cache/store.ts';\nimport { emptyLedger, type Ledger, spend, summarise } from '../engine/budget.ts';\nimport { err } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport { type ConfirmDeps, confirmWrite, type WritePlan } from './confirm.ts';\n\nexport function ledger(): Ledger {\n const result = loadJson<Ledger>(cachePath('budget.json'));\n return result.state === 'ok' ? result.value : emptyLedger();\n}\n\nexport function budgetLine(now: number): string {\n const s = summarise(ledger(), 'write', now);\n return `${s.remaining} of ${s.cap} writes left today.`;\n}\n\n/** Real terminal I/O. Injected in tests so the gate is exercised without one. */\nexport function terminalDeps(): ConfirmDeps {\n return {\n isTty: process.stdin.isTTY === true && process.stdout.isTTY === true,\n prompt: async (question: string) => {\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n const answer = await rl.question(question);\n rl.close();\n return answer;\n },\n write: (s: string) => process.stderr.write(s),\n };\n}\n\n/**\n * Account for the comment harvest, which does not go through the client.\n *\n * Charged to `page` rather than `write`: it is a read, just an unusually heavy\n * one at ~2.8 MB. It gets a ledger entry so the traffic is visible in\n * `lnrelay budget` instead of being free and invisible.\n */\nexport function recordHarvestSpend(now: number): void {\n const attempt = spend(ledger(), 'page', now);\n if ('permit' in attempt) saveJson(cachePath('budget.json'), attempt.ledger);\n}\n\n/** Reserve the write against today's budget before a human is ever asked. */\nexport function reserve(command: string, now: number): Envelope | null {\n const attempt = spend(ledger(), 'write', now);\n return 'error' in attempt\n ? err(command, attempt.error.code, attempt.error.message, attempt.error.hint)\n : null;\n}\n\nexport type Gated<T> = { confirmed: unknown; payload: T } | Envelope;\n\nexport interface GateOpts {\n /**\n * Whether this gate is the thing that accounts for the write.\n *\n * client.ts is documented as \"the only place that spends budget\", and for\n * any transport that goes through it that is true — so the gate must only\n * ASK, never account, or the same write is billed twice. It was: every\n * Voyager and SDUI write cost two, and the prompt counted 6 → 4 → 2 across\n * three reactions until the daily cap locked the user out of their own tool.\n *\n * Defaults to true because the OAuth transport issues its own fetch and\n * never reaches the client, so there the gate is the only place that can.\n */\n commitSpend?: boolean;\n}\n\n/** Ask a human. Makes no network call either way. */\nexport async function gateWrite<T>(\n command: string,\n plan: WritePlan<T>,\n now: number,\n deps: ConfirmDeps,\n opts: GateOpts = {},\n): Promise<Gated<T>> {\n const outcome = await confirmWrite(plan, budgetLine(now), deps);\n if (!outcome.ok) return err(command, outcome.code, outcome.message, outcome.hint);\n // Only after approval is anything committed — an aborted write costs nothing.\n if (opts.commitSpend !== false) {\n const attempt = spend(ledger(), 'write', now);\n if ('permit' in attempt) saveJson(cachePath('budget.json'), attempt.ledger);\n }\n return { confirmed: outcome.confirmed, payload: plan.payload };\n}\n","// ─── The write gate ───────────────────────────────────────────────────────────\n//\n// `--confirm` is not a human confirmation. In this family the agent IS the\n// process invoking the CLI — Claude Code shells out — so a flag is written by\n// the acting party about its own action. It documents intent and obtains\n// consent from nobody.\n//\n// So a write stops and asks, at the moment of the write, having first shown\n// exactly what it will do and what it risks. The properties that make this a\n// real boundary:\n//\n// * No TTY, no write. Run non-interactively — which is how an agent invokes\n// the CLI — and it returns CONFIRMATION_REQUIRED having made ZERO network\n// calls. This is the load-bearing one.\n// * A short token derived from the payload, so `yes | lnrelay share …` fails.\n// * Only this module can mint a ConfirmedWrite, so the guarantee lives in the\n// type system rather than in a forgettable `if`.\n// * No --yes, no env var, no config setting.\n//\n// Stated honestly: a TTY check is an ACCIDENT-PREVENTION barrier, not proof of\n// human identity — an agent with terminal control can allocate a pty. Its real\n// value is moving circumvention from accidental (append a flag) to deliberate\n// (construct a pty and echo a payload-specific token). Overclaiming\n// unforgeability is how a guard stops being maintained.\n\nimport { createHash } from 'node:crypto';\n\n/** Proof a human saw and approved this exact payload. Unforgeable by construction. */\nexport interface ConfirmedWrite<T> {\n readonly __brand: unique symbol;\n action: string;\n payload: T;\n token: string;\n}\n\nexport interface WritePlan<T> {\n action: string;\n payload: T;\n /** Human-readable rendering of exactly what will happen. */\n summary: string[];\n /** Whether the action can be undone, and how. */\n reversibility: string;\n transport: 'oauth' | 'voyager';\n}\n\n/**\n * The token a human must type. Derived from the payload, so it changes if the\n * content changes — a token captured from one prompt cannot approve a different\n * write.\n */\nexport function confirmToken(action: string, payload: unknown): string {\n return createHash('sha256')\n .update(`${action}:${JSON.stringify(payload)}`)\n .digest('hex')\n .slice(0, 4);\n}\n\n/**\n * The risk sentence, which differs by transport because the truth differs.\n *\n * An OAuth write really is sanctioned — saying otherwise would be crying wolf,\n * and a warning shown identically on every action stops being read. A Voyager\n * write really does breach §8.2, and the person approving it should be told\n * that at the moment they approve it, not in a README they read once.\n *\n * This says nothing about CONSEQUENCE — whether the thing is public, who gets\n * notified, whether it can be undone. That varies by action, not by transport,\n * and each command states it in `reversibility`. Mixing them here produced a\n * delete prompt warning that the deletion was \"public under your name\".\n */\nfunction riskLines(transport: 'oauth' | 'voyager'): string[] {\n return transport === 'oauth'\n ? [\n \" This write itself is sanctioned — it uses LinkedIn's own\",\n ' w_member_social scope. The reads this tool performs are not.',\n ]\n : [\n ' This goes over the PRIVATE API, not a sanctioned one. It breaches',\n ' LinkedIn User Agreement §8.2 and can permanently restrict this account.',\n ];\n}\n\nexport function renderPlan<T>(plan: WritePlan<T>, budgetLine: string): string {\n const token = confirmToken(plan.action, plan.payload);\n const lines = [\n '',\n ` ABOUT TO ${plan.action.toUpperCase()} ON LINKEDIN`,\n ` ${'─'.repeat(58)}`,\n ...plan.summary.map((l) => ` ${l}`),\n ` via ${plan.transport === 'oauth' ? 'official OAuth (w_member_social)' : 'Voyager (private API)'}`,\n ` undo ${plan.reversibility}`,\n '',\n ...riskLines(plan.transport),\n ` ${budgetLine}`,\n '',\n ` Type ${token} to confirm, anything else to abort: `,\n ];\n return lines.join('\\n');\n}\n\nexport interface ConfirmDeps {\n isTty: boolean;\n prompt: (question: string) => Promise<string>;\n write: (s: string) => void;\n}\n\nexport type ConfirmOutcome<T> =\n | { ok: true; confirmed: ConfirmedWrite<T> }\n | { ok: false; code: 'CONFIRMATION_REQUIRED'; message: string; hint: string };\n\n/**\n * Ask a human. Returns a ConfirmedWrite only on an exact token match typed at an\n * interactive terminal. Makes no network call either way — the caller cannot\n * reach the write transport without the value this returns.\n */\nexport async function confirmWrite<T>(\n plan: WritePlan<T>,\n budgetLine: string,\n deps: ConfirmDeps,\n): Promise<ConfirmOutcome<T>> {\n if (!deps.isTty) {\n return {\n ok: false,\n code: 'CONFIRMATION_REQUIRED',\n message: `'${plan.action}' needs a human to confirm it at an interactive terminal`,\n hint:\n 'No terminal is attached, so nothing was sent and no network call was made. Run this ' +\n 'command yourself in a shell. There is deliberately no --yes flag: an agent that could ' +\n 'set one would not be confirming anything.',\n };\n }\n\n const token = confirmToken(plan.action, plan.payload);\n const answer = (await deps.prompt(renderPlan(plan, budgetLine))).trim();\n\n if (answer !== token) {\n return {\n ok: false,\n code: 'CONFIRMATION_REQUIRED',\n message: 'aborted — the confirmation token did not match',\n hint: 'Nothing was sent. Re-run and type the token shown in the prompt.',\n };\n }\n\n return {\n ok: true,\n confirmed: { action: plan.action, payload: plan.payload, token } as ConfirmedWrite<T>,\n };\n}\n","// ─── Deleting a post ──────────────────────────────────────────────────────────\n//\n// The only irreversible action in the tool. Everything else it does can be\n// undone: an unwanted post can be deleted, a reaction removed, a cached row\n// purged. A deleted post is gone, and no confirmation prompt can give it back.\n//\n// So this one does something the others do not: it READS THE POST FIRST and\n// shows the human the actual text they are about to destroy. A urn is not\n// something anyone can eyeball — `urn:li:activity:7489428563075637248` and\n// `urn:li:activity:7489428563075637249` are the same string to a tired person\n// at a terminal, and one of them is the wrong post.\n//\n// The lookup is `my-posts`, which is the right source for three reasons at\n// once: it proves the post exists, it proves the OWNER wrote it (it came from\n// their own posts), and it carries the text. A post that is not in there is not\n// necessarily someone else's — it may just be older than the page we fetched —\n// so that case is reported rather than refused, and the prompt says plainly\n// that it is proceeding blind.\n\nimport { CacheCorrupt, openDb, removeUrns } from '../cache/db.ts';\nimport { buildHeaders } from '../engine/auth.ts';\nimport { createEngine, createLiveClient } from '../engine/index.ts';\nimport { extractCommentTokens } from '../engine/sdui-harvest.ts';\nimport {\n type CommentRef,\n DELETE_OP,\n parseCommentUrn,\n runCommentAction,\n} from '../engine/sdui-menu.ts';\nimport { LAUNCH_HINT, loadSession } from '../engine/session.ts';\nimport { deletePost, isDeletableUrn } from '../engine/voyager-write.ts';\nimport { type Shaped, shapeAll } from '../format.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { ConfirmDeps, WritePlan } from './confirm.ts';\nimport { gateWrite, recordHarvestSpend, reserve, terminalDeps } from './gate.ts';\n\n/** How many of the owner's recent posts to search for the one being deleted. */\nconst LOOKUP_LIMIT = 50;\n\nconst PREVIEW_CHARS = 200;\n\n/** The numeric id shared by every namespace a single post appears under. */\nfunction postId(urn: string): string | undefined {\n return /:(\\d+)$/.exec(urn)?.[1];\n}\n\n/**\n * Find a post among the owner's own, matching across urn namespaces.\n *\n * The same post is `urn:li:activity:X` to the feed, `urn:li:ugcPost:X` to\n * reactions and `urn:li:share:X` to the create endpoint. Matching on the shared\n * numeric id means a urn from any read can be handed to delete.\n */\nexport function findOwnPost(posts: Shaped[], urn: string): Shaped | undefined {\n const id = postId(urn);\n if (id === undefined) return undefined;\n return posts.find((p) => typeof p.urn === 'string' && postId(p.urn) === id);\n}\n\n/** What the human is shown about the post before they approve destroying it. */\nexport function previewLines(post: Shaped | undefined): string[] {\n if (post === undefined) {\n return [\n 'content COULD NOT READ THIS POST.',\n ' It is not among your recent posts. That may only mean it is older',\n ' than the page fetched — but nothing here has verified what you are',\n ' about to delete, or that it is yours.',\n ];\n }\n const text = typeof post.text === 'string' ? post.text : '(no text — media-only post?)';\n const shown = text.length > PREVIEW_CHARS ? `${text.slice(0, PREVIEW_CHARS)}…` : text;\n return [`content \"${shown.replace(/\\n/g, ' ')}\"`];\n}\n\n/** Look the post up so the prompt can show it. A failed read is not fatal. */\nasync function lookup(urn: string, quiet: boolean): Promise<Shaped | undefined> {\n const session = loadSession();\n if (session.state !== 'ok') return undefined;\n const engine = createEngine(session.session, undefined, quiet);\n\n const me = await engine.whoami();\n if (!me.ok) return undefined;\n const profileUrn = typeof me.value?.entityUrn === 'string' ? me.value.entityUrn : undefined;\n if (profileUrn === undefined) return undefined;\n\n const posts = await engine.myPosts(profileUrn, LOOKUP_LIMIT);\n if (!posts.ok) return undefined;\n return findOwnPost(shapeAll(posts.value.parsed.items, posts.value.index), urn);\n}\n\n/**\n * The urn to drop from the local cache after a delete, or null.\n *\n * `sync my-posts` upserts and never evicts, so without this a deleted post\n * lingers and `my-posts` keeps listing something that no longer exists —\n * observed live, LinkedIn returning 1 post while the cache held 2.\n *\n * Only a SUCCESSFUL delete evicts. A failed one means the post is still there,\n * and dropping it from the cache would hide a post that still exists under the\n * owner's name — the opposite of the problem being fixed.\n */\nexport function evictionTarget(result: { ok: boolean; id?: string | null }): string | null {\n if (!result.ok) return null;\n return typeof result.id === 'string' && result.id !== '' ? result.id : null;\n}\n\n/** Drop the row locally. A cache failure must not report the delete as failed. */\nfunction evict(urn: string | null, now: number): boolean {\n if (urn === null) return false;\n try {\n return removeUrns(openDb(now), 'my-posts', [urn]) > 0;\n } catch (e) {\n if (e instanceof CacheCorrupt) return false;\n throw e;\n }\n}\n\n/**\n * Deleting a COMMENT is a different surface from deleting a post: SDUI rather\n * than Voyager, and the payload comes from the action menu the server offers on\n * that comment. That also means the menu is the permission check — a comment\n * you cannot delete simply has no delete action, so we never send one blindly.\n */\nasync function deleteComment(\n ref: CommentRef,\n urn: string,\n now: number,\n deps: ConfirmDeps,\n): Promise<Envelope> {\n if (!deps.isTty) {\n return err(\n 'delete',\n 'CONFIRMATION_REQUIRED',\n 'deleting needs a human to confirm it at an interactive terminal',\n 'No terminal is attached, so nothing was sent and no network call was made.',\n );\n }\n\n const session = loadSession();\n if (session.state !== 'ok') {\n return err('delete', 'AUTH_FAILED', 'no LinkedIn session', LAUNCH_HINT);\n }\n\n const refused = reserve('delete', now);\n if (refused !== null) return refused;\n\n const headers = buildHeaders(session.session);\n let html: string;\n try {\n const res = await fetch(\n `https://www.linkedin.com/feed/update/urn:li:activity:${ref.activityId}/`,\n {\n headers: {\n cookie: headers.cookie ?? '',\n 'user-agent': headers['user-agent'] ?? '',\n accept: 'text/html',\n },\n redirect: 'manual',\n },\n );\n if (res.status !== 200) {\n return err('delete', 'FETCH_FAILED', `the parent post page returned ${res.status}`);\n }\n html = await res.text();\n } catch (e) {\n return err('delete', 'FETCH_FAILED', `could not load the parent post: ${(e as Error).message}`);\n }\n recordHarvestSpend(now);\n\n const tokens = extractCommentTokens(html, ref.activityId);\n if (!tokens.ok) return err('delete', 'SCHEMA_DRIFT', tokens.message, tokens.hint);\n\n const plan: WritePlan<{ urn: string }> = {\n action: 'delete your comment',\n payload: { urn },\n summary: [`comment ${urn}`, `on post urn:li:activity:${ref.activityId}`],\n reversibility: 'NONE. A deleted comment is gone, with its replies and reactions.',\n transport: 'voyager',\n };\n\n const gated = await gateWrite('delete', plan, now, deps, { commitSpend: false });\n if ('ok' in gated) return gated;\n\n const result = await runCommentAction(\n ref,\n DELETE_OP,\n tokens.trackingId,\n createLiveClient(session.session),\n );\n return result.ok\n ? ok('delete', { deleted: urn, kind: 'comment' })\n : err('delete', result.code, result.message, result.hint);\n}\n\nexport async function runDelete(\n urn: string | undefined,\n now = Date.now(),\n deps?: ConfirmDeps,\n quiet = false,\n): Promise<Envelope> {\n if (urn === undefined || urn === '') {\n return err(\n 'delete',\n 'INVALID_INPUT',\n 'a post urn is required',\n 'lnrelay delete <urn:li:share:… | urn:li:activity:…>',\n );\n }\n // A comment urn routes to an entirely different surface.\n const asComment = parseCommentUrn(urn);\n if (asComment !== null) return deleteComment(asComment, urn, now, deps ?? terminalDeps());\n\n if (!isDeletableUrn(urn)) {\n return err(\n 'delete',\n 'INVALID_INPUT',\n `'${urn}' does not identify a post`,\n 'Expected a post urn (urn:li:share|activity|ugcPost:<id>) or a comment urn. Refusing before ' +\n 'encoding it, because a well-formed request naming the wrong kind of entity is a request ' +\n 'to destroy the wrong kind of thing.',\n );\n }\n\n const session = loadSession();\n if (session.state === 'corrupt') {\n return err('delete', 'CACHE_CORRUPT', 'the stored session was unreadable', LAUNCH_HINT);\n }\n if (session.state === 'missing') {\n // Deleting goes over Voyager only. LinkedIn's official API has a delete,\n // but this tool has not built or verified it, and an unverified destructive\n // call is the last place to start guessing.\n return err(\n 'delete',\n 'AUTH_FAILED',\n 'no LinkedIn session — deleting goes over the private API',\n `Run \\`lnrelay login\\`. ${LAUNCH_HINT}`,\n );\n }\n\n const refused = reserve('delete', now);\n if (refused !== null) return refused;\n\n // Read before destroying. This costs one read and is the entire point.\n const post = await lookup(urn, quiet);\n\n const plan: WritePlan<{ urn: string }> = {\n action: 'delete a post',\n payload: { urn },\n summary: [`post ${urn}`, ...previewLines(post)],\n reversibility: 'NONE. A deleted post is gone, with its comments and reactions.',\n transport: 'voyager',\n };\n\n // The client accounts for the DELETE itself.\n const gated = await gateWrite('delete', plan, now, deps ?? terminalDeps(), {\n commitSpend: false,\n });\n if ('ok' in gated) return gated;\n\n const result = await deletePost(gated.confirmed as never, createLiveClient(session.session));\n if (!result.ok) return err('delete', result.code, result.message, result.hint);\n\n // LinkedIn has it gone; drop our copy so `my-posts` stops listing it.\n const evicted = evict(evictionTarget(result), now);\n return ok('delete', { deleted: urn, verified: post !== undefined, evictedFromCache: evicted });\n}\n","// Runners for the commands that talk to LinkedIn. Thin: they resolve a\n// session, call the engine, and shape the envelope. All the interesting\n// behaviour lives in engine/.\n\nimport {\n type Collection,\n createEngine,\n type EngineResult,\n type SearchKind,\n} from '../engine/index.ts';\n\nimport {\n LAUNCH_HINT,\n loadSession,\n mintSessionFromBrowser,\n saveSession,\n} from '../engine/session.ts';\nimport {\n compactRows,\n project,\n type Shaped,\n shapeAll,\n shapeEntity,\n shapeProfile,\n} from '../format.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport { retain } from './cache.ts';\n\nfunction withSession(\n command: string,\n quiet = false,\n): { engine: ReturnType<typeof createEngine> } | Envelope {\n const loaded = loadSession();\n if (loaded.state === 'corrupt') {\n return err(\n command,\n 'CACHE_CORRUPT',\n 'the stored session was unreadable and has been quarantined',\n `Moved to ${loaded.quarantinedTo}. Re-run \\`lnrelay login\\`.`,\n );\n }\n if (loaded.state === 'missing') {\n return err(command, 'AUTH_FAILED', 'no session — run `lnrelay login` first', LAUNCH_HINT);\n }\n return { engine: createEngine(loaded.session, undefined, quiet) };\n}\n\n/** Turn an engine failure into an envelope without losing its hint. */\nfunction toEnvelope(\n command: string,\n result: Extract<EngineResult<never>, { ok: false }>,\n): Envelope {\n return err(command, result.code, result.message, result.hint, undefined, result.retryAfterMs);\n}\n\nexport async function runLogin(): Promise<Envelope> {\n const minted = await mintSessionFromBrowser();\n if (!minted.ok) return err('login', 'AUTH_FAILED', minted.message, minted.hint);\n\n saveSession(minted.session);\n // Never echo a credential — presence and length only.\n return ok('login', {\n stored: true,\n liAtLength: minted.session.liAt.length,\n userAgent: minted.session.userAgent,\n capturedAt: minted.session.capturedAt,\n notice:\n 'Session stored with owner-only permissions. This tool breaches LinkedIn User Agreement ' +\n '§8.2 and the account can be restricted or banned.',\n });\n}\n\nexport async function runWhoami(raw = false): Promise<Envelope> {\n const ctx = withSession('whoami');\n if ('ok' in ctx) return ctx;\n\n const result = await ctx.engine.whoami();\n if (!result.ok) return toEnvelope('whoami', result);\n if (result.value === undefined) {\n return err(\n 'whoami',\n 'SCHEMA_DRIFT',\n 'LinkedIn returned no member entity',\n 're-capture the `me` contract',\n );\n }\n return ok(\n 'whoami',\n raw ? { ...shapeEntity(result.value), raw: result.value } : shapeEntity(result.value),\n );\n}\n\nexport async function runProfile(memberId: string | undefined, raw = false): Promise<Envelope> {\n if (memberId === undefined || memberId === '') {\n return err(\n 'profile',\n 'INVALID_INPUT',\n 'a member id or urn is required',\n 'lnrelay profile <public-id|urn>',\n );\n }\n const ctx = withSession('profile');\n if ('ok' in ctx) return ctx;\n\n const result = await ctx.engine.profile(normaliseMemberId(memberId));\n if (!result.ok) return toEnvelope('profile', result);\n if (result.value === undefined) {\n return err('profile', 'NOT_FOUND', `no profile for '${memberId}'`);\n }\n const shaped = shapeProfile(result.value.profile, result.value.index);\n return ok('profile', raw ? { ...shaped, raw: result.value.profile } : shaped);\n}\n\nexport async function runFeed(limit: number, opts: OutputOpts = {}): Promise<Envelope> {\n const ctx = withSession('feed', opts.quiet === true);\n if ('ok' in ctx) return ctx;\n\n const result = await ctx.engine.feed(limit);\n if (!result.ok) return toEnvelope('feed', result);\n return ok('feed', collection(result.value, opts));\n}\n\nexport async function runSearch(\n kind: string | undefined,\n query: string | undefined,\n limit: number,\n opts: OutputOpts = {},\n): Promise<Envelope> {\n if (kind === undefined || !['people', 'companies', 'jobs'].includes(kind)) {\n return err(\n 'search',\n 'INVALID_INPUT',\n 'kind must be people, companies or jobs',\n 'lnrelay search people \"<query>\"',\n );\n }\n if (query === undefined || query === '') {\n return err('search', 'INVALID_INPUT', 'a query is required', 'lnrelay search people \"<query>\"');\n }\n const ctx = withSession('search', opts.quiet === true);\n if ('ok' in ctx) return ctx;\n\n const result = await ctx.engine.search(kind as SearchKind, query, limit);\n if (!result.ok) return toEnvelope('search', result);\n return ok('search', { query, kind, ...collection(result.value, opts) });\n}\n\nexport async function runPost(\n urn: string | undefined,\n limit: number,\n opts: OutputOpts = {},\n): Promise<Envelope> {\n const postUrn = normalisePostUrn(urn);\n if (postUrn === undefined) {\n return err(\n 'post',\n 'INVALID_INPUT',\n 'a post urn or feed URL is required',\n 'lnrelay post <activity-urn|https://www.linkedin.com/feed/update/...>',\n );\n }\n const ctx = withSession('post', opts.quiet === true);\n if ('ok' in ctx) return ctx;\n\n const result = await ctx.engine.post(postUrn, limit);\n if (!result.ok) return toEnvelope('post', result);\n return ok('post', { urn: postUrn, ...collection(result.value, opts) });\n}\n\nexport async function runReactions(\n urn: string | undefined,\n limit: number,\n opts: OutputOpts = {},\n): Promise<Envelope> {\n const postUrn = normalisePostUrn(urn);\n if (postUrn === undefined) {\n return err('reactions', 'INVALID_INPUT', 'a post urn or feed URL is required');\n }\n const ctx = withSession('reactions', opts.quiet === true);\n if ('ok' in ctx) return ctx;\n\n const result = await ctx.engine.reactions(postUrn, limit);\n if (!result.ok) return toEnvelope('reactions', result);\n return ok('reactions', { urn: postUrn, ...collection(result.value, opts) });\n}\n\n// ─── shaping ──────────────────────────────────────────────────────────────────\n\n/** Accept a bare urn or a feed permalink; both carry the post identity. */\nfunction normalisePostUrn(input: string | undefined): string | undefined {\n if (input === undefined || input === '') return undefined;\n const found = input.match(/urn:li:(?:activity|ugcPost|share):\\d+/);\n if (found !== null) return found[0];\n return /^\\d+$/.test(input) ? `urn:li:activity:${input}` : undefined;\n}\n\n/** A URL, a public id, or a bare urn all reduce to the member identity. */\nfunction normaliseMemberId(input: string): string {\n const fromUrl = input.match(/linkedin\\.com\\/in\\/([^/?#]+)/);\n if (fromUrl?.[1] !== undefined) return fromUrl[1];\n const fromUrn = input.match(/urn:li:fsd?_(?:mini)?[Pp]rofile:([^,)]+)/);\n if (fromUrn?.[1] !== undefined) return fromUrn[1];\n return input;\n}\n\n/** How the caller wants the rows rendered. */\nexport interface OutputOpts {\n raw?: boolean;\n retain?: boolean;\n compact?: boolean;\n fields?: string;\n quiet?: boolean;\n}\n\n/**\n * Collections are shaped by default — raw Voyager entities are enormous and\n * wrap every string in a TextViewModel. `--raw` keeps the original node\n * alongside, for when a shape has drifted and you need to see what arrived;\n * `--compact` and `--fields` go the other way, for when a page of results is\n * about to land in an agent's context and only the ranking signal matters.\n */\nfunction collection(result: Collection, opts: OutputOpts = {}): Record<string, unknown> {\n const { parsed, index } = result;\n const shaped = shapeAll(parsed.items, index);\n\n const meta: Record<string, unknown> = { ...parsed.meta };\n // Retention always stores the FULL shaped row, never the projected one — a\n // display choice must not silently narrow what gets cached.\n if (opts.retain === true) meta.retained = retain('third-party', shaped);\n\n if (opts.raw === true) {\n return {\n items: parsed.items.map((node, i) => ({ ...(shaped[i] as Shaped), raw: node })),\n meta,\n };\n }\n if (opts.compact === true) return { items: compactRows(shaped), meta };\n if (opts.fields !== undefined && opts.fields !== '') {\n return { items: project(shaped, opts.fields), meta };\n }\n return { items: shaped, meta };\n}\n","// The three commands that work today. All are local: they make no network call\n// and need no LinkedIn session, so they are useful before the Phase 0 gate has\n// even run.\n\nimport { existsSync } from 'node:fs';\nimport { version as nodeVersion } from 'node:process';\nimport { cacheDir, cachePath, loadJson, saveJson } from '../cache/store.ts';\nimport {\n activeCooldown,\n CAPS,\n type Cooldown,\n emptyLedger,\n type Ledger,\n type SpendClass,\n summarise,\n} from '../engine/budget.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\n\nconst LEDGER_FILE = 'budget.json';\nconst COOLDOWN_FILE = 'cooldown.json';\n\ninterface StateLoad<T> {\n value: T | null;\n corrupt: { path: string; quarantinedTo: string; reason: string } | null;\n}\n\nfunction loadState<T>(file: string, fallback: T): StateLoad<T> {\n const path = cachePath(file);\n const result = loadJson<T>(path);\n if (result.state === 'ok') return { value: result.value, corrupt: null };\n if (result.state === 'missing') return { value: fallback, corrupt: null };\n return {\n value: null,\n corrupt: { path, quarantinedTo: result.quarantinedTo, reason: result.reason },\n };\n}\n\nexport function loadLedger(): StateLoad<Ledger> {\n return loadState<Ledger>(LEDGER_FILE, emptyLedger());\n}\n\nexport function loadCooldown(): StateLoad<Cooldown | null> {\n return loadState<Cooldown | null>(COOLDOWN_FILE, null);\n}\n\n// ─── risk ─────────────────────────────────────────────────────────────────────\n\n/**\n * The breaker's current state. Exposed over MCP deliberately, so an agent can\n * check standing BEFORE deciding to spend budget on research rather than\n * discovering the lockout one wasted call at a time.\n */\nexport function runRisk(now: number): Envelope {\n const { value: cooldown, corrupt } = loadCooldown();\n if (corrupt !== null) {\n return err(\n 'risk',\n 'CACHE_CORRUPT',\n `cooldown state was unreadable and has been quarantined: ${corrupt.reason}`,\n `moved to ${corrupt.quarantinedTo}. Inspect it, then re-run — a fresh cooldown file will be created.`,\n );\n }\n\n const blocked = activeCooldown(cooldown ?? null, now);\n return ok('risk', {\n state: blocked ? 'blocked' : 'ok',\n cooldown: cooldown ?? null,\n tosNotice:\n 'Voyager reads breach LinkedIn User Agreement §8.2. This tool is not ToS-compliant and ' +\n 'any account it touches can be restricted or permanently banned.',\n });\n}\n\n// ─── budget ───────────────────────────────────────────────────────────────────\n\nexport function runBudget(now: number, resetCooldown: boolean, confirmed: boolean): Envelope {\n if (resetCooldown && !confirmed) {\n return err(\n 'budget',\n 'CONFIRMATION_REQUIRED',\n 'clearing a cooldown requires --confirm',\n 'A cooldown means LinkedIn signalled a throttle, block or challenge. Log in through a real ' +\n 'browser and confirm you are unblocked before clearing it. Re-run with --confirm.',\n );\n }\n\n if (resetCooldown) {\n saveJson(cachePath(COOLDOWN_FILE), null);\n }\n\n const { value: ledger, corrupt } = loadLedger();\n if (corrupt !== null) {\n return err(\n 'budget',\n 'CACHE_CORRUPT',\n `the spend ledger was unreadable and has been quarantined: ${corrupt.reason}`,\n `moved to ${corrupt.quarantinedTo}. A corrupt ledger is NOT treated as an empty one — that ` +\n 'would silently restore a full budget. Inspect it, then re-run.',\n );\n }\n\n const classes: SpendClass[] = ['profile', 'search', 'page', 'write', 'global'];\n const { value: cooldown } = loadCooldown();\n\n return ok('budget', {\n classes: classes.map((c) => ({\n ...summarise(ledger ?? emptyLedger(), c, now),\n note: CAPS[c].note,\n })),\n cooldown: cooldown ?? null,\n caveat:\n 'Every cap is guessed or transplanted vendor lore — the field research found no corroborated ' +\n 'LinkedIn rate limits. These are starting knobs, not safe thresholds. They also cannot see ' +\n 'your manual browser activity.',\n });\n}\n\n// ─── doctor ───────────────────────────────────────────────────────────────────\n\nexport interface Check {\n name: string;\n ok: boolean;\n detail: string;\n}\n\n/**\n * Diagnose setup. Always returns ok:true at the envelope level — a diagnostic\n * that fails to report because something is broken is useless. Individual checks\n * carry their own pass/fail. Never prints a credential value.\n */\nexport function runDoctor(now: number, offline: boolean): Envelope {\n const checks: Check[] = [];\n\n checks.push({\n name: 'runtime',\n ok: true,\n detail: `node ${nodeVersion}; cache dir ${cacheDir()}${existsSync(cacheDir()) ? '' : ' (not created yet)'}`,\n });\n\n const { value: cooldown, corrupt: cooldownCorrupt } = loadCooldown();\n if (cooldownCorrupt !== null) {\n checks.push({\n name: 'cooldown',\n ok: false,\n detail: `state file was corrupt; quarantined to ${cooldownCorrupt.quarantinedTo}`,\n });\n } else {\n const blocked = activeCooldown(cooldown ?? null, now);\n checks.push({\n name: 'cooldown',\n ok: !blocked,\n detail: blocked\n ? `BLOCKED — ${cooldown?.reason}, clears by ${cooldown?.clearRequires}${\n cooldown?.until === null\n ? ' (indefinite)'\n : ` at ${new Date(cooldown?.until ?? 0).toISOString()}`\n }`\n : 'clear',\n });\n }\n\n const { value: ledger, corrupt: ledgerCorrupt } = loadLedger();\n if (ledgerCorrupt !== null) {\n checks.push({\n name: 'budget',\n ok: false,\n detail: `ledger was corrupt; quarantined to ${ledgerCorrupt.quarantinedTo}`,\n });\n } else {\n const g = summarise(ledger ?? emptyLedger(), 'global', now);\n checks.push({\n name: 'budget',\n ok: g.remaining > 0,\n detail: `${g.spentInWindow}/${g.cap} global calls used in the last 24h (cap provenance: ${g.capProvenance})`,\n });\n }\n\n // Credentials are checked for PRESENCE and LENGTH only — never printed.\n const cookiePath = cachePath('cookies.json');\n checks.push({\n name: 'session',\n ok: false,\n detail: existsSync(cookiePath)\n ? 'a cookie file exists, but the engine is not implemented yet (Phase 2)'\n : 'no session yet — the Phase 0 capture gate has not been run. See docs/PLAN.md.',\n });\n\n checks.push({\n name: 'engine',\n ok: false,\n detail:\n 'not implemented. Phase 0 (three human-paced requests from a residential IP) must pass ' +\n 'before engine code is written — see docs/PLAN.md.',\n });\n\n if (!offline) {\n checks.push({\n name: 'live',\n ok: false,\n detail: 'no live checks available yet; --offline is currently the only meaningful mode',\n });\n }\n\n return ok('doctor', {\n healthy: checks.every((c) => c.ok),\n phase: 'Phase 1 — local scaffolding. No network capability exists yet, by design.',\n checks,\n });\n}\n","// ─── Obtaining the write credential ───────────────────────────────────────────\n//\n// The three-legged dance, with the parts that touch the world isolated behind\n// `LoginDeps`: a socket on localhost, a browser, a terminal prompt, and fetch.\n// The ordering constraint that matters is that the listener must be up BEFORE\n// the browser is sent anywhere, or a fast consent lands on a closed port.\n//\n// This command is CLI-only and always will be. It opens a browser and stores a\n// bearer credential; neither belongs on an agent-facing surface.\n\nimport { spawn } from 'node:child_process';\nimport { createServer } from 'node:http';\nimport { createInterface } from 'node:readline/promises';\nimport { CAPS } from '../engine/budget.ts';\nimport {\n authorizationUrl,\n CALLBACK_PORT,\n exchange,\n fetchMemberUrn,\n parseCallback,\n SCOPES,\n} from '../engine/oauth.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport { deleteToken, loadToken, OAUTH_SETUP, saveToken, tokenPath } from './token.ts';\n\nexport type CodeResult = { ok: true; code: string } | { ok: false; message: string };\n\nexport type Listener =\n | { ok: true; code: Promise<CodeResult>; close: () => void }\n | { ok: false; message: string };\n\nconst CALLBACK_TIMEOUT_MS = 300_000;\n\nconst DONE_PAGE = `<!doctype html><meta charset=\"utf-8\"><title>lnrelay</title>\n<body style=\"font:16px system-ui;padding:3rem;max-width:32rem\">\n<h1>Authorised.</h1><p>You can close this tab and go back to the terminal.</p>`;\n\n/**\n * Listen on the loopback callback port for exactly one consent redirect.\n *\n * Resolves as soon as the socket is bound, so the caller can open the browser\n * knowing there is something to land on; the code arrives later on `.code`.\n */\nexport function listenForCallback(\n state: string,\n timeoutMs = CALLBACK_TIMEOUT_MS,\n): Promise<Listener> {\n return new Promise<Listener>((ready) => {\n let settle: (r: CodeResult) => void = () => {};\n const code = new Promise<CodeResult>((r) => {\n settle = r;\n });\n\n const server = createServer((req, res) => {\n const url = req.url ?? '/';\n // Browsers ask for /favicon.ico unprompted. Answering that is not consent.\n if (!url.startsWith('/callback')) {\n res.writeHead(404, { connection: 'close' });\n res.end();\n return;\n }\n res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', connection: 'close' });\n res.end(DONE_PAGE);\n settle(parseCallback(url, state));\n });\n\n const timer = setTimeout(() => {\n settle({\n ok: false,\n message: `timed out after ${Math.round(timeoutMs / 1000)}s waiting for the LinkedIn callback`,\n });\n }, timeoutMs);\n timer.unref?.();\n\n const close = (): void => {\n clearTimeout(timer);\n server.closeAllConnections?.();\n server.close();\n };\n\n server.once('error', (e: NodeJS.ErrnoException) => {\n clearTimeout(timer);\n const why =\n e.code === 'EADDRINUSE'\n ? `port ${CALLBACK_PORT} is already in use — close whatever holds it and retry`\n : `could not open the callback listener: ${e.message}`;\n ready({ ok: false, message: why });\n });\n\n server.listen(CALLBACK_PORT, '127.0.0.1', () => {\n ready({ ok: true, code, close });\n });\n });\n}\n\n/** Best effort. The URL is always printed too, so a failure here is survivable. */\nfunction openBrowser(url: string): void {\n const cmd =\n process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open';\n try {\n spawn(cmd, [url], { detached: true, stdio: 'ignore' }).unref();\n } catch {\n // The printed URL is the fallback.\n }\n}\n\nexport interface LoginDeps {\n state: () => string;\n listen: (state: string) => Promise<Listener>;\n open: (url: string) => void;\n write: (s: string) => void;\n isTty: boolean;\n prompt: (question: string) => Promise<string>;\n now: () => number;\n fetch: typeof globalThis.fetch;\n}\n\nexport function loginDeps(): LoginDeps {\n return {\n state: () => crypto.randomUUID(),\n listen: (state) => listenForCallback(state),\n open: openBrowser,\n write: (s) => process.stderr.write(s),\n isTty: process.stdin.isTTY === true && process.stderr.isTTY === true,\n prompt: async (question) => {\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n const answer = await rl.question(question);\n rl.close();\n return answer;\n },\n now: Date.now,\n fetch: globalThis.fetch,\n };\n}\n\ninterface Credentials {\n clientId: string;\n clientSecret: string;\n}\n\n/**\n * Flag, then environment, then — for the secret only — a prompt. The secret is\n * prompted rather than required as a flag because argv lands in shell history.\n */\nasync function credentials(\n opts: { clientId?: string; clientSecret?: string },\n deps: LoginDeps,\n): Promise<Credentials | Envelope> {\n const clientId = opts.clientId ?? process.env.LINKEDIN_CLIENT_ID;\n if (clientId === undefined || clientId === '') {\n return err('oauth', 'INVALID_INPUT', 'a client id is required', OAUTH_SETUP);\n }\n\n let clientSecret = opts.clientSecret ?? process.env.LINKEDIN_CLIENT_SECRET;\n if ((clientSecret === undefined || clientSecret === '') && deps.isTty) {\n clientSecret = (await deps.prompt('client secret (not echoed to argv or logs): ')).trim();\n }\n if (clientSecret === undefined || clientSecret === '') {\n return err(\n 'oauth',\n 'INVALID_INPUT',\n 'a client secret is required, and there is no terminal to ask on',\n `Set LINKEDIN_CLIENT_SECRET, or run this at an interactive terminal.\\n\\n${OAUTH_SETUP}`,\n );\n }\n return { clientId, clientSecret };\n}\n\n/** Run the consent flow and store the resulting token. Never prints it. */\nexport async function runOauthLogin(\n opts: { clientId?: string; clientSecret?: string },\n deps: LoginDeps = loginDeps(),\n): Promise<Envelope> {\n const creds = await credentials(opts, deps);\n if ('ok' in creds) return creds;\n\n const state = deps.state();\n const listener = await deps.listen(state);\n if (!listener.ok) {\n return err('oauth', 'AUTH_FAILED', listener.message);\n }\n\n try {\n const url = authorizationUrl(creds.clientId, state);\n deps.write(`Opening LinkedIn for consent. If nothing opens, visit:\\n\\n ${url}\\n\\n`);\n deps.open(url);\n\n const callback = await listener.code;\n if (!callback.ok) return err('oauth', 'AUTH_FAILED', callback.message);\n\n const token = await exchange(callback.code, creds, { fetch: deps.fetch, now: deps.now });\n if (!token.ok) return err('oauth', 'AUTH_FAILED', token.message, token.hint);\n\n const member = await fetchMemberUrn(token.accessToken, { fetch: deps.fetch });\n // A token we cannot attribute to a member cannot author anything, so it is\n // not worth storing — every write needs the author urn.\n if (!member.ok) return err('oauth', 'AUTH_FAILED', member.message, OAUTH_SETUP);\n\n saveToken({\n accessToken: token.accessToken,\n memberUrn: member.memberUrn,\n expiresAt: token.expiresAt,\n });\n\n return ok('oauth', {\n memberUrn: member.memberUrn,\n scopes: SCOPES,\n expiresAt: new Date(token.expiresAt).toISOString(),\n storedAt: tokenPath(),\n // Refresh tokens are partner-gated, so renewal is re-running this.\n renewal: 'run `lnrelay oauth login` again when it expires',\n });\n } finally {\n listener.close();\n }\n}\n\n/** Remove the stored credential. Local only — LinkedIn is never contacted. */\nexport function runOauthLogout(): Envelope {\n const removed = deleteToken();\n return ok('oauth', {\n removed,\n note: removed\n ? `deleted ${tokenPath()} — the token stays valid on LinkedIn's side until it expires`\n : 'no token was stored',\n });\n}\n\n/** Report OAuth setup state. Never prints the token. */\nexport function runOauthStatus(): Envelope {\n const token = loadToken();\n if (token === null) return err('oauth', 'AUTH_FAILED', 'no OAuth token stored', OAUTH_SETUP);\n return ok('oauth', {\n memberUrn: token.memberUrn,\n expiresAt: new Date(token.expiresAt).toISOString(),\n expired: token.expiresAt <= Date.now(),\n scopes: SCOPES,\n storedAt: tokenPath(),\n writeCap: CAPS.write.perDay,\n });\n}\n","// ─── Three-legged OAuth ───────────────────────────────────────────────────────\n//\n// The only sanctioned path an individual has. Both products this needs are\n// self-serve — no partner review, no company verification, no screencast:\n//\n// Sign In with LinkedIn using OpenID Connect → openid, profile (member urn)\n// Share on LinkedIn → w_member_social (the writes)\n//\n// Everything here is pure except `exchange` and `fetchMemberUrn`, which take an\n// injected fetch. The local callback server lives in commands/oauth.ts, so this\n// module stays testable without opening a socket.\n\nconst AUTHORIZE = 'https://www.linkedin.com/oauth/v2/authorization';\nconst TOKEN = 'https://www.linkedin.com/oauth/v2/accessToken';\nconst USERINFO = 'https://api.linkedin.com/v2/userinfo';\n\n/** Port chosen to be memorable and unlikely to collide with a dev server. */\nexport const CALLBACK_PORT = 53682;\nexport const REDIRECT_URI = `http://localhost:${CALLBACK_PORT}/callback`;\n\n/**\n * `openid` + `profile` identify the member (we need their urn to author\n * anything); `w_member_social` is the write scope. `email` is deliberately NOT\n * requested — the tool has no use for it, and an unused scope is a permission\n * granted for nothing.\n */\nexport const SCOPES = ['openid', 'profile', 'w_member_social'];\n\nexport interface OAuthConfig {\n clientId: string;\n clientSecret: string;\n}\n\n/**\n * Build the consent URL. `state` is a CSRF nonce: LinkedIn echoes it back, and\n * a callback carrying a different one did not originate from this run.\n */\nexport function authorizationUrl(clientId: string, state: string): string {\n const params = new URLSearchParams({\n response_type: 'code',\n client_id: clientId,\n redirect_uri: REDIRECT_URI,\n state,\n scope: SCOPES.join(' '),\n });\n return `${AUTHORIZE}?${params.toString()}`;\n}\n\nexport type ExchangeResult =\n | { ok: true; accessToken: string; expiresAt: number }\n | { ok: false; message: string; hint?: string };\n\n/** Swap the authorization code for an access token. */\nexport async function exchange(\n code: string,\n config: OAuthConfig,\n deps: { fetch: typeof globalThis.fetch; now: () => number },\n): Promise<ExchangeResult> {\n const body = new URLSearchParams({\n grant_type: 'authorization_code',\n code,\n redirect_uri: REDIRECT_URI,\n client_id: config.clientId,\n client_secret: config.clientSecret,\n });\n\n let res: Response;\n try {\n res = await deps.fetch(TOKEN, {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n } catch (e) {\n return { ok: false, message: `could not reach LinkedIn: ${(e as Error).message}` };\n }\n\n const text = await res.text();\n if (res.status !== 200) {\n return {\n ok: false,\n message: `LinkedIn rejected the code exchange (${res.status})`,\n // The most common causes, in the order they actually happen.\n hint:\n 'Check that the app has BOTH products added, and that its Auth tab lists ' +\n `exactly ${REDIRECT_URI} as an authorized redirect URL. Response: ${text.slice(0, 200)}`,\n };\n }\n\n let parsed: { access_token?: unknown; expires_in?: unknown };\n try {\n parsed = JSON.parse(text) as typeof parsed;\n } catch {\n return { ok: false, message: 'token response was not JSON' };\n }\n\n const accessToken = parsed.access_token;\n const expiresIn = parsed.expires_in;\n if (typeof accessToken !== 'string' || accessToken === '') {\n return { ok: false, message: 'token response carried no access_token' };\n }\n\n // LinkedIn access tokens last ~60 days. Refresh tokens are partner-gated, so\n // re-running `oauth login` is the renewal path — recorded rather than hidden.\n const lifetimeMs = typeof expiresIn === 'number' ? expiresIn * 1000 : 60 * 86_400_000;\n return { ok: true, accessToken, expiresAt: deps.now() + lifetimeMs };\n}\n\nexport type MemberResult = { ok: true; memberUrn: string } | { ok: false; message: string };\n\n/**\n * The member urn to author as. `/v2/userinfo` returns OIDC claims; `sub` is the\n * member id, and `urn:li:person:<sub>` is what the write APIs expect as author.\n */\nexport async function fetchMemberUrn(\n accessToken: string,\n deps: { fetch: typeof globalThis.fetch },\n): Promise<MemberResult> {\n let res: Response;\n try {\n res = await deps.fetch(USERINFO, { headers: { authorization: `Bearer ${accessToken}` } });\n } catch (e) {\n return { ok: false, message: `could not reach userinfo: ${(e as Error).message}` };\n }\n\n if (res.status !== 200) {\n return {\n ok: false,\n message: `userinfo returned ${res.status} — the 'openid'/'profile' scopes may not be granted`,\n };\n }\n\n const parsed = (await res.json()) as { sub?: unknown };\n if (typeof parsed.sub !== 'string' || parsed.sub === '') {\n return { ok: false, message: 'userinfo carried no subject claim' };\n }\n return { ok: true, memberUrn: `urn:li:person:${parsed.sub}` };\n}\n\n/** Extract `code`/`state`, or the error LinkedIn sent instead. */\nexport function parseCallback(\n rawUrl: string,\n expectedState: string,\n): { ok: true; code: string } | { ok: false; message: string } {\n let url: URL;\n try {\n url = new URL(rawUrl, `http://localhost:${CALLBACK_PORT}`);\n } catch {\n return { ok: false, message: 'callback URL was unparseable' };\n }\n\n const error = url.searchParams.get('error');\n if (error !== null) {\n const description = url.searchParams.get('error_description') ?? '';\n return { ok: false, message: `LinkedIn denied the request: ${error} ${description}`.trim() };\n }\n\n const state = url.searchParams.get('state');\n if (state !== expectedState) {\n // Either a stale browser tab or something that did not come from this run.\n return { ok: false, message: 'state mismatch — this callback did not come from this login' };\n }\n\n const code = url.searchParams.get('code');\n if (code === null || code === '') return { ok: false, message: 'callback carried no code' };\n\n return { ok: true, code };\n}\n","// ─── Where the OAuth credential lives ─────────────────────────────────────────\n//\n// Its own module so that the command that OBTAINS a token and the commands that\n// SPEND one can share the storage without importing each other.\n//\n// The file is written 0600 under ~/.lnrelay (see cache/store.ts). That is the\n// whole protection: no keychain, no encryption. It is a 60-day bearer token for\n// posting as you, so treat the directory accordingly and keep it out of cloud\n// sync. `lnrelay oauth logout` removes it.\n\nimport { existsSync, rmSync } from 'node:fs';\nimport { cachePath, loadJson, saveJson } from '../cache/store.ts';\nimport { REDIRECT_URI } from '../engine/oauth.ts';\nimport type { OAuthToken } from '../engine/oauth-write.ts';\n\nconst TOKEN_FILE = 'oauth.json';\n\nexport const OAUTH_SETUP = [\n \"Writes go over LinkedIn's OWN self-serve scope rather than the private API, which is the one\",\n 'legitimacy wedge an individual actually has — but the app has to be registered by you; it',\n 'cannot be created on your behalf.',\n '',\n ' 1. https://www.linkedin.com/developers/apps/new — create an app (any LinkedIn Page works).',\n ' 2. Products tab → add \"Sign In with LinkedIn using OpenID Connect\" AND \"Share on LinkedIn\".',\n ' Both are self-serve: no partner review, no verification, no screencast.',\n ` 3. Auth tab → add redirect URL ${REDIRECT_URI}`,\n ' 4. Run: lnrelay oauth login --client-id <id>',\n ' (the secret is prompted for; or set LINKEDIN_CLIENT_ID / LINKEDIN_CLIENT_SECRET)',\n].join('\\n');\n\nexport function tokenPath(): string {\n return cachePath(TOKEN_FILE);\n}\n\nexport function loadToken(): OAuthToken | null {\n const result = loadJson<OAuthToken>(tokenPath());\n return result.state === 'ok' ? result.value : null;\n}\n\nexport function saveToken(token: OAuthToken): void {\n saveJson(tokenPath(), token);\n}\n\n/** Returns whether there was anything to remove — silence would be ambiguous. */\nexport function deleteToken(): boolean {\n const path = tokenPath();\n if (!existsSync(path)) return false;\n rmSync(path, { force: true });\n return true;\n}\n","// Single source of truth for command definitions. Drives CLI dispatch + help,\n// the MCP tool surface, and the SKILL.md parity test.\n//\n// `audience` is load-bearing, not documentation: the MCP shim registers only\n// commands marked `mcp`, so a write can never reach an agent by accident. The\n// research half of this tool is the product; writes are a thin, human-gated\n// layer that arrives last (docs/PLAN.md Phase 6).\n\nexport type Audience = 'cli' | 'mcp';\nexport type RiskClass = 'read' | 'local' | 'write';\n\nexport interface CommandDef {\n name: string;\n /** Funnel cost hint shown in help + skill. */\n cost: string;\n summary: string;\n usage: string;\n audience: Audience[];\n risk: RiskClass;\n /** false until the command is actually wired up. */\n implemented: boolean;\n}\n\nexport const COMMANDS: CommandDef[] = [\n // ─── local / meta — no network, available today ────────────────────────────\n {\n name: 'doctor',\n cost: 'free with --offline',\n summary: 'Diagnose setup: entry point, cache dir, cookies, cooldown, budget.',\n usage: 'lnrelay doctor [--offline]',\n audience: ['cli', 'mcp'],\n risk: 'local',\n implemented: true,\n },\n {\n name: 'budget',\n cost: 'free',\n summary: \"Spend ledger per class, with each cap's provenance. Reset a cooldown here.\",\n usage: 'lnrelay budget [--reset-cooldown --confirm]',\n audience: ['cli', 'mcp'],\n risk: 'local',\n implemented: true,\n },\n {\n name: 'risk',\n cost: 'free',\n summary: 'Circuit-breaker state. Check this BEFORE spending budget on research.',\n usage: 'lnrelay risk',\n audience: ['cli', 'mcp'],\n risk: 'local',\n implemented: true,\n },\n\n // ─── session ───────────────────────────────────────────────────────────────\n {\n name: 'login',\n cost: 'free — local browser',\n summary: 'Mint a session from a logged-in Chrome via DevTools. Stores cookies owner-only.',\n usage:\n 'lnrelay login\\n' +\n ' Requires a Chrome started with remote debugging on port 9222 (see docs/PLAN.md).',\n audience: ['cli'],\n risk: 'local',\n implemented: true,\n },\n\n // ─── reads — verified live 2026-08-01 ─────────────────────────────────────\n {\n name: 'whoami',\n cost: '1 call',\n summary: 'The authenticated member: name, headline, URN.',\n usage: 'lnrelay whoami',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'profile',\n cost: '1 call (+1 per section)',\n summary: 'A member profile. Expensive sections are opt-in.',\n usage:\n 'lnrelay profile <public-id|urn|url> [--raw]\\n' +\n \" Returns headline, location, current title, company and school. LinkedIn's profile\\n\" +\n ' projections do not return a name — use the identifier you passed in.',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'search',\n cost: 'cheap — the net',\n summary: 'Search people, companies or jobs. Cast wide, then deep-read the finalists.',\n usage:\n 'lnrelay search people|companies|jobs \"<query>\" [--limit N]\\n' +\n ' [--compact | --fields a,b,c] [--retain] [--raw]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'post',\n cost: 'expensive — full read',\n summary: 'A post plus its comment thread, cursor-followed.',\n usage:\n 'lnrelay post <activity-urn|url> [--limit N] [--compact | --fields a,b] [--retain]\\n' +\n ' Check meta.returnedCount / claimedCount / state. claimedCount > 0 with\\n' +\n ' returnedCount 0 is a FAILED FETCH, not an empty thread.',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'reactions',\n cost: 'medium',\n summary: 'Who reacted to a post, and with which reaction.',\n usage: 'lnrelay reactions <activity-urn|url> [--limit N] [--compact | --fields a,b]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'company',\n cost: 'medium',\n summary: 'A company page, optionally with a bounded sample of its updates.',\n usage: 'lnrelay company <universal-name|url> [--updates N]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: false,\n },\n {\n name: 'job',\n cost: '1 call',\n summary: 'A job posting detail.',\n usage: 'lnrelay job <job-id|url>',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: false,\n },\n {\n name: 'feed',\n cost: 'medium',\n summary: 'Your own chronological feed.',\n usage: 'lnrelay feed [--limit N] [--compact | --fields a,b,c] [--retain] [--raw]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n\n // ─── cache-backed — Phase 4 ────────────────────────────────────────────────\n {\n name: 'sync',\n cost: 'medium — 1-2 calls',\n summary: 'Pull your own posts or connections into the local cache for offline search.',\n usage: 'lnrelay sync my-posts|connections [--limit N] [--force]',\n audience: ['cli'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'connections',\n cost: 'free — local cache',\n summary: 'Your connections, from the local cache. Fill it with `sync connections`.',\n usage:\n 'lnrelay connections [-q \"<query>\"] [--limit N] [--compact | --fields a,b] # free; cache',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'my-posts',\n cost: 'free — local cache',\n summary: 'Your own authored posts, from the local cache. Fill it with `sync my-posts`.',\n usage:\n 'lnrelay my-posts [-q \"<query>\"] [--limit N] [--compact | --fields a,b] # free; cache',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'local',\n cost: 'free — local cache',\n summary: 'Offline search across everything synced. The default research path after a sync.',\n usage:\n 'lnrelay local \"<query>\" [--source connections,my-posts,third-party] [--since YYYY-MM-DD]\\n' +\n ' [--limit N] [--compact | --fields a,b,c]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'cache-status',\n cost: 'free — local cache',\n summary: 'What is cached, per source, with sync checkpoints and the retention policy.',\n usage: 'lnrelay cache-status',\n audience: ['cli', 'mcp'],\n risk: 'local',\n implemented: true,\n },\n {\n name: 'purge',\n cost: 'free',\n summary: 'Delete cached data. Never contacts LinkedIn.',\n usage: 'lnrelay purge [--all] --confirm # default scope: third-party only',\n audience: ['cli'],\n risk: 'local',\n implemented: true,\n },\n\n // ─── writes — Phase 6, official OAuth only, never MCP ──────────────────────\n {\n name: 'oauth',\n cost: 'free',\n summary:\n \"Obtain and inspect the write credential, over LinkedIn's own self-serve scope. \" +\n 'Never prints the token.',\n usage:\n 'lnrelay oauth login --client-id <id> [--client-secret <secret>]\\n' +\n ' lnrelay oauth status | logout\\n' +\n ' The secret is prompted for if omitted; LINKEDIN_CLIENT_ID / LINKEDIN_CLIENT_SECRET also work.\\n' +\n ' Needs an app you registered: see the hint printed when no token is stored.',\n audience: ['cli'],\n risk: 'local',\n implemented: true,\n },\n {\n name: 'share',\n cost: '1 call — write',\n summary:\n \"Post to your own feed. Prefers LinkedIn's official OAuth scope, falls back to the \" +\n 'private API when no token exists — the prompt always names which.',\n usage:\n 'lnrelay share \"<text>\" [--visibility public|connections] [--via oauth|voyager]\\n' +\n ' Stops and asks at an interactive terminal. No TTY = no write, and no network call.',\n audience: ['cli'],\n risk: 'write',\n implemented: true,\n },\n {\n name: 'comment',\n cost: '1 call — write',\n summary:\n 'Add a comment to a post. Harvests its binding tokens from the rendered page; no browser ' +\n 'needed, but it costs one heavy read.',\n usage:\n 'lnrelay comment <activity-urn> \"<text>\"\\n' +\n ' Fetches the post page (~2.8 MB) to harvest a binding key and trackingId, and proves\\n' +\n ' the key belongs to that post before asking. To change a comment, see `edit`.',\n audience: ['cli'],\n risk: 'write',\n implemented: true,\n },\n {\n name: 'delete',\n cost: '1 read + 1 write',\n summary:\n 'Delete one of your own posts or comments. Reads a post back and shows its text first — ' +\n 'this is the one action that cannot be undone.',\n usage:\n 'lnrelay delete <activity-urn> # a post; shows you its text before destroying it\\n' +\n ' lnrelay delete <comment-urn> # a comment; the server decides if you may',\n audience: ['cli'],\n risk: 'write',\n implemented: true,\n },\n {\n name: 'reply',\n cost: '1 read + 1 write',\n summary:\n 'Reply to a comment, nested under it. Goes over Voyager — a different endpoint from ' +\n 'commenting, with the parent named in threadUrn.',\n usage: 'lnrelay reply <comment-urn> \"<text>\"',\n audience: ['cli'],\n risk: 'write',\n implemented: true,\n },\n {\n name: 'edit',\n cost: '1 read + 1 write',\n summary:\n 'Change the text of a comment you wrote. Its own verb, so a comment urn can never be ' +\n 'mistaken for something to comment ON.',\n usage: 'lnrelay edit <comment-urn> \"<text>\"',\n audience: ['cli'],\n risk: 'write',\n implemented: true,\n },\n {\n name: 'react',\n cost: '1 call — write',\n summary: \"React to a post or comment, over LinkedIn's SDUI surface. Reversible with --remove.\",\n usage:\n 'lnrelay react <activity-urn | comment-urn> [--type LIKE|PRAISE|EMPATHY|INTEREST|APPRECIATION|ENTERTAINMENT]\\n' +\n ' lnrelay react <urn> --remove # take the reaction back',\n audience: ['cli'],\n risk: 'write',\n implemented: true,\n },\n];\n\nexport const commandNames = COMMANDS.map((c) => c.name);\n\nexport function findCommand(name: string): CommandDef | undefined {\n return COMMANDS.find((c) => c.name === name);\n}\n\n/** Commands the MCP shim may register. Writes are structurally excluded. */\nexport function mcpCommands(): CommandDef[] {\n return COMMANDS.filter((c) => c.audience.includes('mcp') && c.risk !== 'write');\n}\n\nexport function helpText(): string {\n const lines = ['lnrelay — deep research over LinkedIn from your own account', '', 'Commands:'];\n const width = Math.max(...commandNames.map((n) => n.length));\n for (const c of COMMANDS) {\n const flag = c.implemented ? ' ' : '·'; // · = designed, not yet wired\n lines.push(` ${flag} ${c.name.padEnd(width)} ${c.summary} [${c.cost}]`);\n }\n lines.push('', ' · = specified in docs/DESIGN.md, not yet implemented');\n lines.push('', 'Run `lnrelay <command> --help` for usage.');\n return lines.join('\\n');\n}\n","// ─── Sync ─────────────────────────────────────────────────────────────────────\n//\n// Two sources, two genuinely different strategies, because LinkedIn orders them\n// differently and forcing one pattern onto both is how silent incompleteness\n// starts.\n//\n// my-posts Newest-first, so a timestamp watermark works — WITH a two-page\n// slack, because LinkedIn pins posts to position 0 and a\n// break-on-first-stale-page would terminate instantly against a\n// pinned old post.\n//\n// connections A filtered people-search, NOT a change stream. There is no\n// ordering to watermark against at all, so this is a snapshot\n// and a set difference: {added, removed}. The checkpoint records\n// `snapshot-partial` rather than inventing a watermark.\n//\n// Both write through the cache's owner-data path, which never expires.\n\nimport {\n CacheCorrupt,\n getCheckpoint,\n openDb,\n removeUrns,\n setCheckpoint,\n upsert,\n urnsFor,\n} from '../cache/db.ts';\nimport type { Engine } from '../engine/index.ts';\nimport { createEngine } from '../engine/index.ts';\nimport { LAUNCH_HINT, loadSession } from '../engine/session.ts';\nimport type { Shaped } from '../format.ts';\nimport { shapeAll } from '../format.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\n\n/** Connections change slowly and the full walk is the priciest read we make. */\nconst CONNECTIONS_MIN_INTERVAL_MS = 7 * 86_400_000;\n\nfunction searchText(item: Shaped): string {\n return [item.name, item.headline, item.location, item.text, item.author, item.company, item.title]\n .filter((v) => typeof v === 'string')\n .join(' ');\n}\n\nfunction rowsFrom(items: Shaped[]): { urn: string; body: unknown; text: string }[] {\n return items\n .filter((i) => typeof i.urn === 'string' && i.urn !== '')\n .map((i) => ({ urn: i.urn as string, body: i, text: searchText(i) }));\n}\n\n/**\n * Decide what a fresh snapshot means for the stored set.\n *\n * The load-bearing rule: removals are only inferable from a COMPLETE snapshot.\n * If LinkedIn claims 400 connections and a limit fetched 50, the 350 unseen are\n * not gone — they were never looked at. Reporting them as removed would tell\n * the user people had disconnected because of a pagination limit.\n */\nexport function diffSnapshot(\n before: Set<string>,\n seen: Set<string>,\n claimed: number | undefined,\n): { removed: string[]; complete: boolean } {\n const complete = claimed === undefined || seen.size >= claimed;\n if (!complete) return { removed: [], complete: false };\n return { removed: [...before].filter((urn) => !seen.has(urn)), complete: true };\n}\n\ntype Db = ReturnType<typeof openDb>;\n\nasync function syncMyPosts(engine: Engine, db: Db, limit: number, now: number): Promise<Envelope> {\n // The owner's own profile urn — we ask LinkedIn rather than assume it.\n const me = await engine.whoami();\n if (!me.ok) return err('sync', me.code, me.message, me.hint);\n const profileUrn = typeof me.value?.entityUrn === 'string' ? me.value.entityUrn : undefined;\n if (profileUrn === undefined) {\n return err('sync', 'SCHEMA_DRIFT', 'could not determine the owner profile urn');\n }\n\n const result = await engine.myPosts(profileUrn, limit);\n if (!result.ok) return err('sync', result.code, result.message, result.hint);\n\n const rows = rowsFrom(shapeAll(result.value.parsed.items, result.value.index));\n const stored = upsert(db, 'my-posts', rows, now);\n\n setCheckpoint(db, {\n source: 'my-posts',\n lastSuccessfulAt: now,\n newestCreatedAt: null,\n headIds: rows.slice(0, 5).map((r) => r.urn),\n state: 'ok',\n });\n\n return ok('sync', {\n source: 'my-posts',\n ...stored,\n meta: result.value.parsed.meta,\n note:\n rows.length === 0\n ? 'LinkedIn returned no posts for this account. That is a genuine empty, not a failed fetch — meta.state says which.'\n : undefined,\n });\n}\n\n/** The full walk is the priciest read we make, so a recent one blocks another. */\nfunction tooSoon(db: Db, now: number): Envelope | undefined {\n const cp = getCheckpoint(db, 'connections');\n const age = cp === undefined ? Number.POSITIVE_INFINITY : now - cp.lastSuccessfulAt;\n if (age >= CONNECTIONS_MIN_INTERVAL_MS) return undefined;\n const days = Math.ceil((CONNECTIONS_MIN_INTERVAL_MS - age) / 86_400_000);\n return err(\n 'sync',\n 'BUDGET_EXHAUSTED',\n `connections were synced ${Math.floor(age / 86_400_000)} days ago`,\n `This is the most expensive read in the tool and connections change slowly. Wait ${days} more day(s), or pass --force.`,\n );\n}\n\nasync function syncConnections(\n engine: Engine,\n db: Db,\n limit: number,\n force: boolean,\n now: number,\n): Promise<Envelope> {\n const before = urnsFor(db, 'connections');\n if (!force && before.size > 0) {\n const blocked = tooSoon(db, now);\n if (blocked !== undefined) return blocked;\n }\n\n const result = await engine.connections(limit);\n if (!result.ok) return err('sync', result.code, result.message, result.hint);\n\n const rows = rowsFrom(shapeAll(result.value.parsed.items, result.value.index));\n const stored = upsert(db, 'connections', rows, now);\n\n // A set difference is only meaningful if we actually saw the whole graph.\n // When LinkedIn claims more than we retrieved, removals are NOT inferable —\n // saying otherwise would report people as disconnected because of a limit.\n const claimed = result.value.parsed.meta.claimedCount;\n const seen = new Set(rows.map((r) => r.urn));\n const { removed, complete } = diffSnapshot(before, seen, claimed);\n if (removed.length > 0) removeUrns(db, 'connections', removed);\n\n setCheckpoint(db, {\n source: 'connections',\n lastSuccessfulAt: now,\n newestCreatedAt: null,\n headIds: [],\n // Honest: a snapshot, never a watermark.\n state: complete ? 'ok' : 'snapshot-partial',\n });\n\n return ok('sync', {\n source: 'connections',\n added: stored.added,\n updated: stored.updated,\n removed: removed.length,\n claimed,\n complete,\n meta: result.value.parsed.meta,\n note: complete\n ? undefined\n : `Only ${rows.length} of ${claimed} connections were retrieved, so removals could not be determined and none were applied. Raise --limit to complete the snapshot.`,\n });\n}\n\nexport async function runSync(\n source: string | undefined,\n limit: number,\n force: boolean,\n now = Date.now(),\n): Promise<Envelope> {\n if (source !== 'my-posts' && source !== 'connections') {\n return err(\n 'sync',\n 'INVALID_INPUT',\n `unknown sync source '${source ?? ''}'`,\n 'lnrelay sync my-posts | lnrelay sync connections',\n );\n }\n\n const session = loadSession();\n if (session.state === 'corrupt') {\n return err('sync', 'CACHE_CORRUPT', 'the stored session was unreadable', LAUNCH_HINT);\n }\n if (session.state === 'missing') {\n return err('sync', 'AUTH_FAILED', 'no session — run `lnrelay login` first', LAUNCH_HINT);\n }\n\n const engine = createEngine(session.session);\n\n try {\n const db = openDb(now);\n return source === 'my-posts'\n ? await syncMyPosts(engine, db, limit, now)\n : await syncConnections(engine, db, limit, force, now);\n } catch (e) {\n if (e instanceof CacheCorrupt) {\n return err(\n 'sync',\n 'CACHE_CORRUPT',\n e.message,\n `Moved to ${e.quarantinedTo}. A corrupt cache is NOT treated as empty — that would make this sync re-enumerate everything. Inspect it, then re-run.`,\n );\n }\n throw e;\n }\n}\n","// ─── The write transport ──────────────────────────────────────────────────────\n//\n// Writes go over LinkedIn's OWN self-serve OAuth scope, never Voyager. That is\n// the one legitimacy wedge an individual actually has: `w_member_social` is\n// self-serve — no partner review, no company verification, no screencast — and\n// it covers posting, commenting and reacting as the authenticated member.\n//\n// Reads have no such path (no self-serve read scope exists at all), which is\n// why they accept the Voyager risk. Writes do have one, so they do not get to\n// spend the same currency.\n//\n// The honest caveat, which belongs in the docs and not just here: OAuth makes\n// these writes SANCTIONED and materially lower-risk. It does not make the\n// surrounding tool ToS-compliant, and scopes and review rules can still change.\n//\n// A ConfirmedWrite is required to reach any function here. That value can only\n// be produced by commands/confirm.ts, at an interactive terminal, so the write\n// path is unreachable from a non-interactive agent by construction rather than\n// by policy.\n\nimport type { ConfirmedWrite } from '../commands/confirm.ts';\n\nconst API = 'https://api.linkedin.com';\n\nexport interface OAuthToken {\n accessToken: string;\n /** The member urn this token authorises, e.g. urn:li:person:ABC. */\n memberUrn: string;\n expiresAt: number;\n}\n\nexport interface WriteDeps {\n fetch: typeof globalThis.fetch;\n now: () => number;\n}\n\nexport type WriteResult =\n | { ok: true; id: string; url?: string }\n | { ok: false; code: string; message: string; hint?: string };\n\nfunction headers(token: OAuthToken): Record<string, string> {\n return {\n authorization: `Bearer ${token.accessToken}`,\n 'content-type': 'application/json',\n 'x-restli-protocol-version': '2.0.0',\n 'linkedin-version': '202601',\n };\n}\n\nfunction expired(token: OAuthToken, now: number): boolean {\n return token.expiresAt <= now;\n}\n\nasync function send(\n url: string,\n body: unknown,\n token: OAuthToken,\n deps: WriteDeps,\n): Promise<WriteResult> {\n if (expired(token, deps.now())) {\n return {\n ok: false,\n code: 'AUTH_FAILED',\n message: 'the OAuth token has expired',\n hint: 'Run `lnrelay oauth` to obtain a fresh token.',\n };\n }\n\n let res: Response;\n try {\n res = await deps.fetch(url, {\n method: 'POST',\n headers: headers(token),\n body: JSON.stringify(body),\n });\n } catch (e) {\n return { ok: false, code: 'FETCH_FAILED', message: (e as Error).message };\n }\n\n const text = await res.text();\n if (res.status === 201 || res.status === 200) {\n const id = res.headers.get('x-restli-id') ?? extractId(text);\n return {\n ok: true,\n id: id ?? '(unknown)',\n ...(id === null ? {} : { url: `https://www.linkedin.com/feed/update/${id}/` }),\n };\n }\n\n // No retries here either. An OAuth 429 is a quota signal, not an invitation.\n if (res.status === 429) {\n return {\n ok: false,\n code: 'RATE_LIMITED',\n message: 'LinkedIn throttled the write',\n hint: 'Not retried automatically. Wait, and check `lnrelay budget`.',\n };\n }\n if (res.status === 401 || res.status === 403) {\n return {\n ok: false,\n code: 'AUTH_FAILED',\n message: `LinkedIn rejected the token (${res.status})`,\n hint: 'The scope may not be granted. Check the app has \"Share on LinkedIn\" added.',\n };\n }\n return {\n ok: false,\n code: 'FETCH_FAILED',\n message: `write failed (${res.status})`,\n hint: text.slice(0, 300),\n };\n}\n\nfunction extractId(body: string): string | null {\n return body.match(/\"id\"\\s*:\\s*\"([^\"]+)\"/)?.[1] ?? null;\n}\n\n/** Post to the member's own feed. */\nexport function share(\n confirmed: ConfirmedWrite<{ text: string; visibility: 'PUBLIC' | 'CONNECTIONS' }>,\n token: OAuthToken,\n deps: WriteDeps,\n): Promise<WriteResult> {\n return send(\n `${API}/rest/posts`,\n {\n author: token.memberUrn,\n commentary: confirmed.payload.text,\n visibility: confirmed.payload.visibility,\n distribution: {\n feedDistribution: 'MAIN_FEED',\n targetEntities: [],\n thirdPartyDistributionChannels: [],\n },\n lifecycleState: 'PUBLISHED',\n isReshareDisabledByAuthor: false,\n },\n token,\n deps,\n );\n}\n\n/** Comment on a post as the member. */\nexport function comment(\n confirmed: ConfirmedWrite<{ postUrn: string; text: string }>,\n token: OAuthToken,\n deps: WriteDeps,\n): Promise<WriteResult> {\n const encoded = encodeURIComponent(confirmed.payload.postUrn);\n return send(\n `${API}/rest/socialActions/${encoded}/comments`,\n {\n actor: token.memberUrn,\n object: confirmed.payload.postUrn,\n message: { text: confirmed.payload.text },\n },\n token,\n deps,\n );\n}\n\n/** React to a post as the member. */\nexport function react(\n confirmed: ConfirmedWrite<{ postUrn: string; type: string }>,\n token: OAuthToken,\n deps: WriteDeps,\n): Promise<WriteResult> {\n return send(\n `${API}/rest/reactions?actor=${encodeURIComponent(token.memberUrn)}`,\n { root: confirmed.payload.postUrn, reactionType: confirmed.payload.type },\n token,\n deps,\n );\n}\n","// ─── Commenting, over SDUI ────────────────────────────────────────────────────\n//\n// The payload LinkedIn's own client sends, rebuilt from a live capture\n// (docs/research/W5). Unlike a reaction, a comment is not self-contained: it\n// carries a binding key and a trackingId harvested from the rendered post page\n// — see sdui-harvest.ts, which also PROVES the key belongs to the intended post\n// before any of this runs.\n//\n// The five state keys are one key body under five prefixes. `commentBoxText` is\n// the plain string, `richCommentBoxText` the same text as a TextModel, and the\n// remaining three are empty strings for the link preview and image slots. All\n// five are echoed in `requestedStateKeys`. Sending four of five, or omitting an\n// empty one, has never been observed and is not something to improvise.\n\nimport type { ConfirmedWrite } from '../commands/confirm.ts';\nimport type { Client } from './client.ts';\nimport { keyMatchesPost } from './sdui-harvest.ts';\n\nconst SDUI_ACTION = 'https://www.linkedin.com/flagship-web/rsc-action/actions/server-request';\n\nexport const COMMENT_URL = `${SDUI_ACTION}?sduiid=com.linkedin.sdui.comments.createComment`;\n\nconst SCREEN_ID = 'com.linkedin.sdui.flagshipnav.feed.UpdateDetail';\n\n/** The five slots the comment box keeps state in, in the captured order. */\nconst STATE_PREFIXES = [\n 'commentBoxText',\n 'richCommentBoxText',\n 'commentBoxLinkPreviewIngestedContentId',\n 'commentBoxExternalImageUrl',\n 'commentBoxExternalImageId',\n] as const;\n\n/**\n * Numeric feedType per rendered context.\n *\n * Only FEED_DETAIL has been observed, carrying 3. A permalink fetched over\n * plain HTTP can hand back a `FeedType_FEED` key instead, whose number is\n * UNKNOWN — and an invented integer here would be a malformed write against a\n * real post, so that case refuses rather than guesses.\n */\nconst FEED_TYPES: Record<string, number> = { FEED_DETAIL: 3 };\n\n/** Everything after the `commentBoxText-` prefix — shared by all five keys. */\nexport function keyBody(bindingKey: string): string {\n return bindingKey.replace(/^commentBoxText-/, '');\n}\n\nexport function feedTypeFor(bindingKey: string): number | null {\n const suffix = /FeedType_([A-Z_]+)$/.exec(bindingKey)?.[1];\n return suffix === undefined ? null : (FEED_TYPES[suffix] ?? null);\n}\n\nfunction stateKey(prefix: string, body: string): string {\n return `${prefix}-${body}`;\n}\n\nexport interface CommentTokens {\n bindingKey: string;\n trackingId: string;\n}\n\n/** The `states` array: the text in two encodings, and three empty slots. */\nfunction states(text: string, body: string): unknown[] {\n return STATE_PREFIXES.map((prefix) => {\n const key = stateKey(prefix, body);\n const base = {\n key,\n namespace: 'MemoryNamespace',\n protoKey: { $type: 'proto.sdui.Key', value: { $case: 'id', id: key } },\n };\n if (prefix === 'commentBoxText') {\n return { ...base, value: text, originalProtoCase: 'stringValue' };\n }\n if (prefix === 'richCommentBoxText') {\n return {\n ...base,\n value: { text, attribute: [], $type: 'TextModel', source: 'local' },\n originalProtoCase: 'textModelForWrite',\n };\n }\n return { ...base, value: '', originalProtoCase: 'stringValue' };\n });\n}\n\nexport function commentBody(\n activityId: string,\n text: string,\n tokens: CommentTokens,\n feedType: number,\n): Record<string, unknown> {\n const body = keyBody(tokens.bindingKey);\n const activityUrn = { activityUrn: { activityId } };\n const binding = (prefix: string) => ({\n key: stateKey(prefix, body),\n namespace: 'MemoryNamespace',\n });\n\n const payload = {\n // The live client's handle for its optimistically-rendered comment. Server\n // relevance unknown, but it is cheap to send and being faithful to a\n // captured shape beats trimming fields whose purpose we are guessing at.\n optimisticKey: `auto-component-${crypto.randomUUID()}`,\n collection: {\n updateKey: {\n feedType,\n items: [\n { feedUpdateUrn: { updateUrnActivityUrn: activityUrn }, trackingId: tokens.trackingId },\n ],\n aggregationType: 0,\n isVideoCarousel: false,\n },\n threadUrn: { threadUrnActivityThreadUrn: activityUrn },\n },\n commentFieldBinding: binding('commentBoxText'),\n richCommentFieldBinding: binding('richCommentBoxText'),\n linkPreviewIngestedContentId: binding('commentBoxLinkPreviewIngestedContentId'),\n externalImageUrl: binding('commentBoxExternalImageUrl'),\n externalImageId: binding('commentBoxExternalImageId'),\n };\n\n const requestedStateKeys = STATE_PREFIXES.map((p) => ({\n key: { value: { $case: 'id', id: stateKey(p, body) } },\n }));\n\n const args = {\n $type: 'proto.sdui.actions.requests.RequestedArguments',\n requestedStateKeys,\n payload,\n requestMetadata: { $type: 'proto.sdui.common.RequestMetadata' },\n };\n\n return {\n requestId: 'com.linkedin.sdui.comments.createComment',\n serverRequest: {\n requestId: 'com.linkedin.sdui.comments.createComment',\n requestedArguments: args,\n isApfcEnabled: false,\n isStreaming: false,\n rumPageKey: '',\n },\n states: states(text, body),\n requestedArguments: {\n ...args,\n states: states(text, body),\n screenId: SCREEN_ID,\n knownTemplateIds: [],\n },\n };\n}\n\nexport type CommentResult =\n | { ok: true; id: string | null }\n | { ok: false; code: string; message: string; hint?: string };\n\n/**\n * Post a comment. Every guard here exists because a wrong binding does not\n * error — it comments somewhere else, publicly, under the owner's name.\n */\nexport async function comment(\n confirmed: ConfirmedWrite<{ activityId: string; text: string; tokens: CommentTokens }>,\n client: Client,\n): Promise<CommentResult> {\n const { activityId, text, tokens } = confirmed.payload;\n\n if (!keyMatchesPost(tokens.bindingKey, activityId)) {\n return {\n ok: false,\n code: 'INVALID_INPUT',\n message: 'the harvested binding key does not belong to this post',\n hint: 'Refusing to send: this is how a comment lands on the wrong post. Re-harvest.',\n };\n }\n\n const feedType = feedTypeFor(tokens.bindingKey);\n if (feedType === null) {\n return {\n ok: false,\n code: 'NOT_IMPLEMENTED',\n message: `unknown feed type in binding key '${tokens.bindingKey.slice(-24)}'`,\n hint:\n 'Only FeedType_FEED_DETAIL has been observed, carrying feedType 3. Inventing a number ' +\n 'for another context would be a malformed write against a real post. Capture the ' +\n 'missing one with `bun run scripts/observe-write.ts`.',\n };\n }\n\n const result = await client.request({\n url: COMMENT_URL,\n method: 'POST',\n body: commentBody(activityId, text, tokens, feedType),\n spendClass: 'write',\n operation: 'comment.create',\n });\n\n if (!result.ok) {\n const out: CommentResult = { ok: false, code: result.code, message: result.message };\n if (result.hint !== undefined) out.hint = result.hint;\n return out;\n }\n return { ok: true, id: activityId };\n}\n","// ─── Reactions, over SDUI ─────────────────────────────────────────────────────\n//\n// Reactions do not go to Voyager. They go to LinkedIn's Server-Driven UI\n// surface, over React Server Component actions:\n//\n// POST /flagship-web/rsc-action/actions/server-request\n// ?sduiid=com.linkedin.sdui.reactions.create (or .delete)\n//\n// This was found by capture, on 2026-08-13, and it is why two earlier attempts\n// to observe a reaction recorded nothing: the observer filtered for\n// `/voyager/api/` and was structurally blind to a surface that does not live\n// there. Everything in this file came off the wire; none of it is inferred.\n//\n// It also settles a question the research could not. W1 found exactly one OSS\n// sample for reacting — `POST /voyagerSocialDashReactions?threadUrn=urn:li:\n// activity:<id>` with `{\"reactionType\":\"LIKE\"}` — which contradicted this\n// project's own verified read-side finding that reactions key off a ugcPost\n// urn. Both were wrong for the current client, and the argument was moot:\n// the live surface takes neither urn form. It takes a nested object holding\n// the BARE NUMERIC ID, and a reaction type with a `ReactionType_` prefix.\n// Shipping that sample would have failed against a superseded endpoint.\n//\n// WHY REACTIONS ARE SHIPPABLE AND COMMENTS ARE NOT. The reaction payload is\n// self-contained: an id, a type, a source, and a fixed screen id — 1,481 bytes\n// with no server-issued token in it. `com.linkedin.sdui.comments.createComment`\n// carries a `trackingId` from the feed render and an opaque binding key\n// (`commentBoxText-CgsIgIC6…`) that only exists once a page has been rendered,\n// so replaying it means fetching the SDUI screen first to harvest them. That\n// is a real two-step protocol, not a missing constant, and it is why `comment`\n// stays unimplemented.\n\nimport type { ConfirmedWrite } from '../commands/confirm.ts';\nimport type { Client } from './client.ts';\n\nconst SDUI_ACTION = 'https://www.linkedin.com/flagship-web/rsc-action/actions/server-request';\n\n/** The screen the live client declares when reacting from a post detail view. */\nconst SCREEN_ID = 'com.linkedin.sdui.flagshipnav.feed.UpdateDetail';\n\n/** All six the UI offers, observed cycling through every one. */\nexport const REACTIONS = [\n 'LIKE',\n 'PRAISE',\n 'EMPATHY',\n 'INTEREST',\n 'APPRECIATION',\n 'ENTERTAINMENT',\n] as const;\n\nexport type Reaction = (typeof REACTIONS)[number];\n\n/**\n * What each enum actually renders as in the UI. These do NOT match: `PRAISE`\n * shows as \"Celebrate\", `INTEREST` as \"Insightful\". Verified live — a\n * `--type PRAISE` produced a Celebrate. Surfaced in the confirmation prompt so\n * nobody discovers the mismatch by putting the wrong reaction on a real post.\n */\nconst LABELS: Record<Reaction, string> = {\n LIKE: 'Like',\n PRAISE: 'Celebrate',\n EMPATHY: 'Love',\n INTEREST: 'Insightful',\n APPRECIATION: 'Support',\n ENTERTAINMENT: 'Funny',\n};\n\nexport function reactionLabel(reaction: Reaction): string {\n return LABELS[reaction];\n}\n\nexport function reactionUrl(op: 'create' | 'delete'): string {\n return `${SDUI_ACTION}?sduiid=com.linkedin.sdui.reactions.${op}`;\n}\n\nexport interface ReactionTarget {\n threadUrn: Record<string, unknown>;\n /** `Update` for a post, `Comment` for a comment. Not interchangeable. */\n reactionSource: 'Update' | 'Comment';\n}\n\n/**\n * Build the target object for a post or a comment.\n *\n * A post is identified by its bare numeric activity id — no urn string reaches\n * the wire. A comment needs both its own id AND its parent thread, because a\n * comment id is only unique within a thread.\n *\n * Throws rather than returning a partial target: an empty threadUrn is a\n * well-formed request to react to nothing, and we have no idea what LinkedIn\n * does with one.\n */\nexport function targetFor(urn: string): ReactionTarget {\n const comment = /^urn:li:comment:\\((urn:li:activity:\\d+),(\\d+)\\)$/.exec(urn);\n if (comment !== null) {\n return {\n threadUrn: {\n threadUrnCommentThreadUrn: {\n commentUrn: { commentId: comment[2] as string, thread: comment[1] as string },\n },\n },\n reactionSource: 'Comment',\n };\n }\n\n const activity = /^urn:li:(?:activity|ugcPost|share):(\\d+)$/.exec(urn);\n if (activity !== null) {\n return {\n threadUrn: {\n threadUrnActivityThreadUrn: { activityUrn: { activityId: activity[1] as string } },\n },\n reactionSource: 'Update',\n };\n }\n\n throw new Error(\n `'${urn}' does not identify a post or a comment — expected urn:li:activity:<id> or urn:li:comment:(urn:li:activity:<id>,<id>)`,\n );\n}\n\nexport interface ReactionPayload {\n threadUrn: Record<string, unknown>;\n reactionType: string;\n reactionSource: string;\n}\n\nexport function reactionPayload(target: ReactionTarget, reaction: Reaction): ReactionPayload {\n return {\n threadUrn: target.threadUrn,\n reactionType: `ReactionType_${reaction}`,\n reactionSource: target.reactionSource,\n };\n}\n\ninterface RequestedArguments {\n $type: string;\n requestedStateKeys: unknown[];\n payload: ReactionPayload;\n requestMetadata: { $type: string };\n states?: unknown[];\n screenId?: string;\n knownTemplateIds?: unknown[];\n}\n\nexport interface SduiBody {\n requestId: string;\n serverRequest: {\n requestId: string;\n requestedArguments: RequestedArguments;\n isApfcEnabled: boolean;\n isStreaming: boolean;\n rumPageKey: string;\n };\n states: unknown[];\n requestedArguments: RequestedArguments;\n}\n\n/**\n * The request body, mirroring the live client — including the fact that it\n * sends the arguments TWICE, once nested under `serverRequest` and once at the\n * top level. That is not a mistake in the capture; both copies were present in\n * all 56 recorded calls, so both are reproduced rather than tidied away.\n *\n * The client also sends an `onClientRequestFailureAction` block describing a\n * toast to show and state to roll back on failure. That is pure client-side UI\n * instruction with nothing for the server to act on, so it is omitted — the\n * one deliberate departure from the captured shape, noted here so a future\n * failure has somewhere to look.\n */\nexport function sduiBody(\n op: 'create' | 'delete',\n target: ReactionTarget,\n reaction: Reaction,\n): SduiBody {\n const requestId = `com.linkedin.sdui.reactions.${op}`;\n const payload = reactionPayload(target, reaction);\n const args: RequestedArguments = {\n $type: 'proto.sdui.actions.requests.RequestedArguments',\n requestedStateKeys: [],\n payload,\n requestMetadata: { $type: 'proto.sdui.common.RequestMetadata' },\n };\n\n return {\n requestId,\n serverRequest: {\n requestId,\n requestedArguments: args,\n isApfcEnabled: false,\n isStreaming: false,\n rumPageKey: '',\n },\n states: [],\n requestedArguments: {\n ...args,\n states: [],\n screenId: SCREEN_ID,\n knownTemplateIds: [],\n },\n };\n}\n\nexport type WriteResult =\n | { ok: true; id: string | null; note?: string }\n | { ok: false; code: string; message: string; hint?: string };\n\n/** Add or remove a reaction. Unreachable without a human-confirmed write. */\nexport async function react(\n confirmed: ConfirmedWrite<{ urn: string; type: Reaction; remove: boolean }>,\n client: Client,\n): Promise<WriteResult> {\n const { urn, type, remove } = confirmed.payload;\n\n let target: ReactionTarget;\n try {\n target = targetFor(urn);\n } catch (e) {\n return { ok: false, code: 'INVALID_INPUT', message: (e as Error).message };\n }\n\n const op = remove ? 'delete' : 'create';\n const result = await client.request({\n url: reactionUrl(op),\n method: 'POST',\n body: sduiBody(op, target, type),\n spendClass: 'write',\n operation: `reaction.${op}`,\n });\n\n if (result.ok) return { ok: true, id: urn };\n\n const out: WriteResult = { ok: false, code: result.code, message: result.message };\n out.hint =\n result.hint ??\n 'This surface was captured from the live client but has never been replayed by this tool. ' +\n 'If it refuses, the first thing to try is sending `x-li-page-instance` and `x-li-track`, ' +\n 'which the browser sends here and which our verified read header set deliberately omits.';\n return out;\n}\n","// ─── Replying to a comment ────────────────────────────────────────────────────\n//\n// Replies do NOT go where comments go. A top-level comment is an SDUI action\n// (`com.linkedin.sdui.comments.createComment`, 9 KB of bindings and state); a\n// REPLY is a plain Voyager POST with a four-field body. Same product surface,\n// two entirely different transports.\n//\n// Captured live on 2026-08-14 after an implementation built by reasoning from\n// the SDUI side shipped, posted a TOP-LEVEL comment, and had to be withdrawn.\n// The mistake there was treating a component render as discovery when it was\n// an echo — the server reflected back the parent urn we had supplied, and the\n// guard checked our own input. Nothing on that surface would ever have revealed\n// this endpoint, because the reply does not live on it.\n//\n// `threadUrn` is the parent reference the SDUI route never had.\n\nimport type { ConfirmedWrite } from '../commands/confirm.ts';\nimport type { Client } from './client.ts';\nimport type { CommentRef } from './sdui-menu.ts';\n\n/**\n * The decorationId is REQUIRED. Omitting it returned HTTP 500, not a helpful\n * 400 — a decorated resource asked for without its decoration recipe.\n *\n * It is VERSIONED (`-43`), so it rotates like the queryIds in contracts.ts.\n * Captured 2026-08-14; if replies start failing, re-capture this first.\n */\nconst REPLY_DECORATION = 'com.linkedin.voyager.dash.deco.social.NormComment-43';\n\nexport const REPLY_URL = `https://www.linkedin.com/voyager/api/voyagerSocialDashNormComments?decorationId=${REPLY_DECORATION}`;\n\nexport interface ReplyBody {\n commentary: { text: string; attributesV2: unknown[]; $type: string };\n threadUrn: string;\n}\n\n/**\n * The parent comment, in the SHORT urn form the live client sends:\n * `urn:li:comment:(activity:<post>,<comment>)` — the inner urn carries no\n * `urn:li:` prefix here, unlike every other place this project handles it.\n */\nexport function parentThreadUrn(ref: CommentRef): string {\n return `urn:li:comment:(${ref.threadType}:${ref.activityId},${ref.commentId})`;\n}\n\nexport function replyBody(ref: CommentRef, text: string): ReplyBody {\n return {\n commentary: {\n text,\n // The captured reply carried a profileMention, because LinkedIn's UI\n // pre-fills \"@Author \" into the box. We send none: an @mention notifies a\n // real person, and inventing one would put words — and a notification —\n // where the user did not ask for them.\n attributesV2: [],\n $type: 'com.linkedin.voyager.dash.common.text.TextViewModel',\n },\n threadUrn: parentThreadUrn(ref),\n };\n}\n\nexport type ReplyResult =\n | { ok: true; parent: string }\n | { ok: false; code: string; message: string; hint?: string };\n\nexport async function replyToComment(\n confirmed: ConfirmedWrite<{ ref: CommentRef; text: string }>,\n client: Client,\n): Promise<ReplyResult> {\n const { ref, text } = confirmed.payload;\n const result = await client.request({\n url: REPLY_URL,\n method: 'POST',\n body: replyBody(ref, text),\n spendClass: 'write',\n operation: 'reply',\n });\n\n if (!result.ok) {\n const out: ReplyResult = { ok: false, code: result.code, message: result.message };\n if (result.hint !== undefined) out.hint = result.hint;\n return out;\n }\n return { ok: true, parent: parentThreadUrn(ref) };\n}\n","// ─── Choosing which surface a write goes over ─────────────────────────────────\n//\n// Two transports exist and they are NOT equivalent:\n//\n// oauth LinkedIn's own w_member_social scope. Sanctioned. Needs a\n// developer app, which needs a company Page.\n// voyager The private API, with the same cookies the reads use. Breaches\n// §8.2. Needs nothing but a login.\n//\n// OAuth wins whenever it is available. Voyager is the fallback for the case\n// that made it necessary: someone with no company has no Page, and therefore no\n// sanctioned way to post to their own feed from their own tools.\n//\n// docs/DESIGN.md's rule was \"never fall back to Voyager SILENTLY\", and every\n// part of that word is load-bearing here. The choice is reported in the\n// envelope, rendered in the confirmation prompt before the human types the\n// token, and carries a different risk sentence. What is forbidden is the user\n// not knowing which surface their post went over — not the fallback itself.\n\nimport type { Session } from '../engine/auth.ts';\nimport type { OAuthToken } from '../engine/oauth-write.ts';\n\nexport type Transport =\n | { kind: 'oauth'; token: OAuthToken }\n | { kind: 'voyager'; session: Session };\n\nexport interface TransportInputs {\n token: OAuthToken | null;\n session: Session | null;\n now: number;\n}\n\nexport type TransportChoice =\n | { ok: true; transport: Transport; note?: string }\n | { ok: false; message: string; hint: string };\n\nconst NO_CREDENTIAL_HINT = [\n 'Two ways to write, and you need one of them:',\n '',\n ' Sanctioned lnrelay oauth login --client-id <id>',\n ' Needs a developer app, which needs a LinkedIn Page.',\n '',\n ' Unsanctioned lnrelay login',\n ' Uses the same cookies as reads. No Page needed. Breaches §8.2',\n ' and puts the account at risk — every write still asks first.',\n].join('\\n');\n\n/**\n * Pick a transport, preferring the sanctioned one.\n *\n * An EXPIRED OAuth token deliberately does not silently demote to Voyager: the\n * user chose the sanctioned path, and quietly moving them onto the private API\n * because a token aged out is exactly the substitution the design forbids. They\n * are told to re-login instead, and can pass --via voyager if they mean it.\n */\nexport function chooseTransport(\n inputs: TransportInputs,\n requested?: 'oauth' | 'voyager',\n): TransportChoice {\n const { token, session, now } = inputs;\n const tokenLive = token !== null && token.expiresAt > now;\n\n if (requested === 'oauth') {\n if (tokenLive) return { ok: true, transport: { kind: 'oauth', token: token as OAuthToken } };\n return {\n ok: false,\n message: token === null ? 'no OAuth token stored' : 'the OAuth token has expired',\n hint: 'Run `lnrelay oauth login --client-id <id>`.',\n };\n }\n\n if (requested === 'voyager') {\n if (session !== null) return { ok: true, transport: { kind: 'voyager', session } };\n return {\n ok: false,\n message: 'no LinkedIn session — a Voyager write needs one',\n hint: 'Run `lnrelay login` to mint one from your own browser.',\n };\n }\n\n if (tokenLive) return { ok: true, transport: { kind: 'oauth', token: token as OAuthToken } };\n\n if (token !== null && session !== null) {\n return {\n ok: false,\n message: 'the OAuth token has expired',\n hint:\n 'Run `lnrelay oauth login --client-id <id>` to renew it. You do have a browser session, ' +\n 'so `--via voyager` would also work — but that is the private API, and swapping you onto ' +\n 'it because a token aged out is not a decision this tool will make for you.',\n };\n }\n\n if (session !== null) {\n return {\n ok: true,\n transport: { kind: 'voyager', session },\n note: 'No OAuth token, so this write goes over the private API. See the prompt.',\n };\n }\n\n return {\n ok: false,\n message: 'no way to write — no OAuth token and no session',\n hint: NO_CREDENTIAL_HINT,\n };\n}\n","// Write command runners. Every one of these stops and asks a human before it\n// sends anything, and makes zero network calls on the path where it doesn't.\n\nimport { buildHeaders } from '../engine/auth.ts';\nimport { createLiveClient } from '../engine/index.ts';\nimport { share as sendShare } from '../engine/oauth-write.ts';\nimport { type CommentTokens, comment as sduiComment } from '../engine/sdui-comment.ts';\nimport { extractCommentTokens } from '../engine/sdui-harvest.ts';\nimport {\n type CommentRef,\n parseCommentUrn,\n runCommentAction,\n UPDATE_OP,\n} from '../engine/sdui-menu.ts';\nimport {\n type Reaction,\n reactionLabel,\n REACTIONS as SDUI_REACTIONS,\n react as sduiReact,\n} from '../engine/sdui-write.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { replyToComment } from '../engine/voyager-reply.ts';\nimport { share as voyagerShare } from '../engine/voyager-write.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { ConfirmDeps, WritePlan } from './confirm.ts';\nimport { gateWrite, recordHarvestSpend, reserve, terminalDeps } from './gate.ts';\nimport { loadToken, OAUTH_SETUP } from './token.ts';\nimport { chooseTransport, type Transport } from './transport.ts';\n\ninterface WriteContext {\n transport: Transport;\n now: number;\n note?: string;\n}\n\n/** The urn a write is authored as, for the confirmation summary. */\nfunction authorLine(transport: Transport): string {\n return transport.kind === 'oauth'\n ? `as ${transport.token.memberUrn}`\n : `as ${transport.session.ownerUrn ?? 'you (browser session)'}`;\n}\n\nfunction prepare(command: string, now: number, via?: 'oauth' | 'voyager'): WriteContext | Envelope {\n const session = loadSession();\n const choice = chooseTransport(\n { token: loadToken(), session: session.state === 'ok' ? session.session : null, now },\n via,\n );\n if (!choice.ok) {\n return err(command, 'AUTH_FAILED', choice.message, `${choice.hint}\\n\\n${OAUTH_SETUP}`);\n }\n const refused = reserve(command, now);\n if (refused !== null) return refused;\n const ctx: WriteContext = { transport: choice.transport, now };\n if (choice.note !== undefined) ctx.note = choice.note;\n return ctx;\n}\n\nasync function gate<T>(\n command: string,\n plan: WritePlan<T>,\n ctx: WriteContext,\n deps: ConfirmDeps,\n): Promise<{ confirmed: Parameters<typeof sendShare>[0] } | Envelope> {\n // Only the OAuth transport issues its own fetch; everything else goes\n // through the client, which does its own accounting.\n const gated = await gateWrite(command, plan, ctx.now, deps, {\n commitSpend: ctx.transport.kind === 'oauth',\n });\n if ('ok' in gated) return gated;\n return { confirmed: gated.confirmed as never };\n}\n\nexport async function runShare(\n text: string | undefined,\n visibility: string,\n now = Date.now(),\n deps: ConfirmDeps = terminalDeps(),\n via?: 'oauth' | 'voyager',\n): Promise<Envelope> {\n if (text === undefined || text.trim() === '') {\n return err('share', 'INVALID_INPUT', 'text is required', 'lnrelay share \"<text>\"');\n }\n const vis = visibility === 'connections' ? 'CONNECTIONS' : 'PUBLIC';\n const ctx = prepare('share', now, via);\n if ('ok' in ctx) return ctx;\n\n const plan: WritePlan<{ text: string; visibility: 'PUBLIC' | 'CONNECTIONS' }> = {\n action: 'post to your feed',\n payload: { text, visibility: vis },\n summary: [authorLine(ctx.transport), `content \"${text}\"`, `audience ${vis}`],\n reversibility:\n 'deletable with `lnrelay delete <urn>`, but it is public under your name the moment it ' +\n 'lands and anyone who saw it cannot un-see it',\n transport: ctx.transport.kind,\n };\n\n const gated = await gate('share', plan, ctx, deps);\n if ('ok' in gated) return gated;\n\n const result =\n ctx.transport.kind === 'oauth'\n ? await sendShare(gated.confirmed, ctx.transport.token, {\n fetch: globalThis.fetch,\n now: () => now,\n })\n : await voyagerShare(gated.confirmed, createLiveClient(ctx.transport.session));\n\n if (!result.ok) return err('share', result.code, result.message, result.hint);\n return ok('share', {\n id: result.id ?? null,\n transport: ctx.transport.kind,\n url: 'url' in result ? result.url : undefined,\n note: 'note' in result ? result.note : ctx.note,\n });\n}\n\n/** The numeric id inside an activity urn, or null. */\nfunction activityIdOf(urn: string): string | null {\n return /^urn:li:(?:activity|ugcPost|share):(\\d+)$/.exec(urn)?.[1] ?? null;\n}\n\n/**\n * Fetch the rendered post page and harvest the comment tokens.\n *\n * This is a ~2.8 MB HTML GET, far heavier than any Voyager read here, and it\n * is unavoidable: the trackingId changes on every render, so it cannot be\n * cached even though the binding key can.\n */\nasync function harvest(\n activityId: string,\n session: Parameters<typeof createLiveClient>[0],\n now: number,\n): Promise<{ ok: true; tokens: CommentTokens } | Envelope> {\n // Account for it. This is the heaviest single request the tool makes, and\n // going through raw fetch bypassed the ledger, the cooldown and the pacing —\n // the exact unaccounted traffic the Permit type exists to prevent.\n const spent = reserve('comment', now);\n if (spent !== null) return spent;\n recordHarvestSpend(now);\n\n const headers = buildHeaders(session);\n let html: string;\n try {\n const res = await fetch(`https://www.linkedin.com/feed/update/urn:li:activity:${activityId}/`, {\n headers: {\n cookie: headers.cookie ?? '',\n 'user-agent': headers['user-agent'] ?? '',\n accept: 'text/html',\n },\n redirect: 'manual',\n });\n if (res.status !== 200) {\n return err('comment', 'FETCH_FAILED', `the post page returned ${res.status}`);\n }\n html = await res.text();\n } catch (e) {\n return err('comment', 'FETCH_FAILED', `could not load the post page: ${(e as Error).message}`);\n }\n\n const found = extractCommentTokens(html, activityId);\n if (!found.ok) return err('comment', 'SCHEMA_DRIFT', found.message, found.hint);\n return { ok: true, tokens: { bindingKey: found.bindingKey, trackingId: found.trackingId } };\n}\n\nexport async function runComment(\n postUrn: string | undefined,\n text: string | undefined,\n now = Date.now(),\n deps: ConfirmDeps = terminalDeps(),\n): Promise<Envelope> {\n if (postUrn === undefined || text === undefined || text.trim() === '') {\n return err(\n 'comment',\n 'INVALID_INPUT',\n 'a post urn and text are required',\n 'lnrelay comment <urn> \"<text>\"',\n );\n }\n // A comment urn is REFUSED here rather than treated as an edit. Someone\n // holding one most likely wants to reply to it, and silently overwriting it\n // instead would be the worst possible reading of the command. Editing has its\n // own verb; overloading is right when the operation is the same on different\n // types (`delete`), wrong when the operations differ.\n if (parseCommentUrn(postUrn) !== null) {\n return err(\n 'comment',\n 'INVALID_INPUT',\n 'that is a comment urn, not a post urn',\n `To change its text: lnrelay edit ${postUrn} \"<text>\". To answer it: ` +\n `lnrelay reply ${postUrn} \"<text>\". Pass the POST urn to add a top-level comment.`,\n );\n }\n const activityId = activityIdOf(postUrn);\n if (activityId === null) {\n return err(\n 'comment',\n 'INVALID_INPUT',\n `'${postUrn}' does not identify a post`,\n 'Pass urn:li:activity:<id>.',\n );\n }\n\n // The TTY check comes BEFORE the harvest, not just before the send. Harvesting\n // is a network call, and this tool's guarantee is \"no TTY, no write AND no\n // network call on that path\" — an agent shelling out non-interactively must\n // not cause LinkedIn traffic it cannot then use.\n if (!deps.isTty) {\n return err(\n 'comment',\n 'CONFIRMATION_REQUIRED',\n 'commenting needs a human to confirm it at an interactive terminal',\n 'No terminal is attached, so nothing was sent and no network call was made.',\n );\n }\n\n const ctx = prepare('comment', now, 'voyager');\n if ('ok' in ctx) return ctx;\n if (ctx.transport.kind !== 'voyager') {\n return err('comment', 'NOT_IMPLEMENTED', 'commenting is only implemented over the private API');\n }\n\n // Harvest after that, but before asking: a human should not approve a comment\n // we then turn out to be unable to send, and the tokens are part of what is\n // being approved.\n const harvested = await harvest(activityId, ctx.transport.session, now);\n if ('ok' in harvested && harvested.ok !== true) return harvested as Envelope;\n if (!('tokens' in harvested)) return harvested as Envelope;\n\n const plan: WritePlan<{ activityId: string; text: string; tokens: CommentTokens }> = {\n action: 'comment on a post',\n payload: { activityId, text, tokens: harvested.tokens },\n summary: [authorLine(ctx.transport), `on ${postUrn}`, `content \"${text}\"`],\n reversibility:\n 'deletable with `lnrelay delete <comment-urn>`; the author is notified immediately',\n transport: 'voyager',\n };\n\n const gated = await gate('comment', plan, ctx, deps);\n if ('ok' in gated) return gated;\n\n const result = await sduiComment(\n gated.confirmed as never,\n createLiveClient(ctx.transport.session),\n );\n return result.ok\n ? ok('comment', { on: postUrn })\n : err('comment', result.code, result.message, result.hint);\n}\n\n/** Change the text of a comment you wrote. Its own verb, deliberately. */\nexport async function runEdit(\n commentUrn: string | undefined,\n text: string | undefined,\n now = Date.now(),\n deps: ConfirmDeps = terminalDeps(),\n): Promise<Envelope> {\n if (commentUrn === undefined || text === undefined || text.trim() === '') {\n return err(\n 'edit',\n 'INVALID_INPUT',\n 'a comment urn and the new text are required',\n 'lnrelay edit <comment-urn> \"<text>\"',\n );\n }\n const ref: CommentRef | null = parseCommentUrn(commentUrn);\n if (ref === null) {\n return err(\n 'edit',\n 'INVALID_INPUT',\n `'${commentUrn}' is not a comment urn`,\n 'Only comments can be edited here — a published post cannot. Get the urn from ' +\n '`lnrelay post <activity-urn>`.',\n );\n }\n\n if (!deps.isTty) {\n return err(\n 'edit',\n 'CONFIRMATION_REQUIRED',\n 'editing needs a human to confirm it at an interactive terminal',\n 'No terminal is attached, so nothing was sent and no network call was made.',\n );\n }\n\n const ctx = prepare('edit', now, 'voyager');\n if ('ok' in ctx) return ctx;\n if (ctx.transport.kind !== 'voyager') {\n return err('edit', 'NOT_IMPLEMENTED', 'editing is only implemented over the private API');\n }\n\n const harvested = await harvest(ref.activityId, ctx.transport.session, now);\n if (!('tokens' in harvested)) return harvested as Envelope;\n\n const plan: WritePlan<{ urn: string; text: string }> = {\n action: 'edit your comment',\n payload: { urn: commentUrn, text },\n summary: [authorLine(ctx.transport), `comment ${commentUrn}`, `new text \"${text}\"`],\n reversibility:\n 'editable again, but the previous text is NOT recoverable here and LinkedIn marks the ' +\n 'comment as edited',\n transport: 'voyager',\n };\n\n const gated = await gate('edit', plan, ctx, deps);\n if ('ok' in gated) return gated;\n\n const result = await runCommentAction(\n ref,\n UPDATE_OP,\n harvested.tokens.trackingId,\n createLiveClient(ctx.transport.session),\n text,\n );\n return result.ok\n ? ok('edit', { edited: commentUrn })\n : err('edit', result.code, result.message, result.hint);\n}\n\nconst REACTIONS: readonly string[] = SDUI_REACTIONS;\n\nexport async function runReact(\n postUrn: string | undefined,\n type: string,\n now = Date.now(),\n deps: ConfirmDeps = terminalDeps(),\n remove = false,\n): Promise<Envelope> {\n const reaction = type.toUpperCase();\n if (postUrn === undefined) {\n return err(\n 'react',\n 'INVALID_INPUT',\n 'a post or comment urn is required',\n 'lnrelay react <urn> [--type LIKE] [--remove]',\n );\n }\n if (!REACTIONS.includes(reaction)) {\n return err(\n 'react',\n 'INVALID_INPUT',\n `unknown reaction '${type}'`,\n `one of: ${REACTIONS.join(', ')}`,\n );\n }\n const ctx = prepare('react', now, 'voyager');\n if ('ok' in ctx) return ctx;\n if (ctx.transport.kind !== 'voyager') {\n return err('react', 'NOT_IMPLEMENTED', 'reacting is only implemented over the private API');\n }\n\n const plan: WritePlan<{ urn: string; type: Reaction; remove: boolean }> = {\n action: remove ? 'remove a reaction' : 'react to a post',\n payload: { urn: postUrn, type: reaction as Reaction, remove },\n summary: [\n authorLine(ctx.transport),\n `on ${postUrn}`,\n `reaction ${reaction} — shows as \"${reactionLabel(reaction as Reaction)}\"${remove ? ' (REMOVING)' : ''}`,\n ],\n reversibility: remove\n ? 'you can react again; the author may have been notified the first time'\n : `removable with \\`lnrelay react ${postUrn} --remove --type ${reaction}\\` — the type is ` +\n 'required, LinkedIn deletes a specific reaction; the author is notified immediately',\n transport: 'voyager',\n };\n\n const gated = await gate('react', plan, ctx, deps);\n if ('ok' in gated) return gated;\n\n const result = await sduiReact(gated.confirmed as never, createLiveClient(ctx.transport.session));\n return result.ok\n ? ok('react', { id: result.id, removed: remove })\n : err('react', result.code, result.message, result.hint);\n}\n\n/**\n * Reply to a comment. Its own verb for the same reason `edit` is: replying and\n * commenting are different operations, and the urn alone cannot say which was\n * meant. Getting it wrong publishes a top-level comment on someone's thread.\n */\nexport async function runReply(\n commentUrn: string | undefined,\n text: string | undefined,\n now = Date.now(),\n deps: ConfirmDeps = terminalDeps(),\n): Promise<Envelope> {\n if (commentUrn === undefined || text === undefined || text.trim() === '') {\n return err(\n 'reply',\n 'INVALID_INPUT',\n 'a comment urn and the reply text are required',\n 'lnrelay reply <comment-urn> \"<text>\"',\n );\n }\n const parent: CommentRef | null = parseCommentUrn(commentUrn);\n if (parent === null) {\n return err(\n 'reply',\n 'INVALID_INPUT',\n `'${commentUrn}' is not a comment urn`,\n 'To comment on a POST, use `lnrelay comment <activity-urn>`. Comment urns come from ' +\n '`lnrelay post <activity-urn>`.',\n );\n }\n\n if (!deps.isTty) {\n return err(\n 'reply',\n 'CONFIRMATION_REQUIRED',\n 'replying needs a human to confirm it at an interactive terminal',\n 'No terminal is attached, so nothing was sent and no network call was made.',\n );\n }\n\n const ctx = prepare('reply', now, 'voyager');\n if ('ok' in ctx) return ctx;\n if (ctx.transport.kind !== 'voyager') {\n return err('reply', 'NOT_IMPLEMENTED', 'replying is only implemented over the private API');\n }\n\n // No harvest here: unlike a top-level comment, a reply needs no binding key\n // and no trackingId. Its parent reference is the threadUrn, and that is\n // derived from the urn the user passed.\n const plan: WritePlan<{ ref: CommentRef; text: string }> = {\n action: 'reply to a comment',\n payload: { ref: parent, text },\n summary: [authorLine(ctx.transport), `replying to ${commentUrn}`, `content \"${text}\"`],\n reversibility:\n 'deletable with `lnrelay delete <the reply urn>`; the comment author is notified immediately',\n transport: 'voyager',\n };\n\n const gated = await gate('reply', plan, ctx, deps);\n if ('ok' in gated) return gated;\n\n const result = await replyToComment(\n gated.confirmed as never,\n createLiveClient(ctx.transport.session),\n );\n return result.ok\n ? ok('reply', { repliedTo: commentUrn })\n : err('reply', result.code, result.message, result.hint);\n}\n","// ─── Main-module detection ────────────────────────────────────────────────\n// Deciding whether an entry file was invoked directly (should run) vs merely\n// imported (should stay silent). The naive `fileURLToPath(url) === argv[1]`\n// check breaks under the npm bin symlink (…/bin/lnrelay → …/dist/cli.js): argv1\n// is the symlink, the module url is the real file — unequal — so the CLI would\n// silently exit 0. Resolving both through realpath fixes that. Pure + testable.\nimport { realpathSync } from 'node:fs';\nimport { basename } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\n/**\n * Decide whether the current module is the process entry point.\n * @param argv1 process.argv[1] — the invoked script path (may be a symlink).\n * @param moduleUrl import.meta.url of the entry module.\n * @param importMetaMain import.meta.main when the runtime provides it.\n */\nexport function isMainModule(\n argv1: string | undefined,\n moduleUrl: string,\n importMetaMain: boolean | undefined,\n): boolean {\n // The runtime told us explicitly — trust it (Bun always sets this).\n if (importMetaMain === true) return true;\n if (importMetaMain === false) return false;\n\n if (argv1 === undefined) return false;\n\n const modulePath = fileURLToPath(moduleUrl);\n try {\n return realpathSync(argv1) === realpathSync(modulePath);\n } catch {\n // realpath failed (path missing, permission, etc.) — fall back to a plain\n // string compare.\n return argv1 === modulePath;\n }\n}\n\n/**\n * Fail-loud heuristic: when isMainModule said \"not entry\" but argv1's basename\n * looks like one of our binaries, the user clearly invoked us and our detection\n * failed. Callers run anyway (after warning) rather than silently exiting.\n */\nexport function shouldForceEntry(argv1: string | undefined, binNames: string[]): boolean {\n if (argv1 === undefined) return false;\n return binNames.includes(basename(argv1));\n}\n\nexport interface EntryDecision {\n /** Whether the entry file should run its main routine. */\n run: boolean;\n /** A stderr warning to print first, or undefined when detection was clean. */\n warning: string | undefined;\n}\n\n/**\n * Consolidated entry decision. Runs when detected as main. Otherwise, ONLY when\n * the runtime gave no definitive answer (import.meta.main === undefined) and the\n * basename looks like one of our binaries, force-runs with a fail-loud warning —\n * an explicit import.meta.main === false is authoritative and never overridden.\n * binNames[0] is used as the label in the warning (the user-facing bin name).\n */\nexport function shouldRunAsEntry(\n argv1: string | undefined,\n moduleUrl: string,\n importMetaMain: boolean | undefined,\n binNames: string[],\n): EntryDecision {\n if (isMainModule(argv1, moduleUrl, importMetaMain)) {\n return { run: true, warning: undefined };\n }\n if (importMetaMain === undefined && shouldForceEntry(argv1, binNames)) {\n return {\n run: true,\n warning: `${binNames[0]}: entry detection failed — treating as main; report at github.com/gabros20/linkedin-relay/issues`,\n };\n }\n return { run: false, warning: undefined };\n}\n","import { bool, num, type ParsedArgs, parseArgs, str } from './args.ts';\nimport { runCacheStatus, runLocal, runPurge, runSourceRead } from './commands/cache.ts';\nimport { runDelete } from './commands/delete.ts';\nimport {\n type OutputOpts,\n runFeed,\n runLogin,\n runPost,\n runProfile,\n runReactions,\n runSearch,\n runWhoami,\n} from './commands/live.ts';\nimport { runBudget, runDoctor, runRisk } from './commands/local.ts';\nimport { runOauthLogin, runOauthLogout, runOauthStatus } from './commands/oauth.ts';\nimport { findCommand, helpText } from './commands/registry.ts';\nimport { runSync } from './commands/sync.ts';\nimport { runComment, runEdit, runReact, runReply, runShare } from './commands/write.ts';\nimport { shouldRunAsEntry } from './entry.ts';\nimport { err, exitCodeFor, toJson } from './output.ts';\nimport type { Envelope } from './types.ts';\n\n/** The output flags every collection command accepts. */\nfunction output(args: ParsedArgs): OutputOpts {\n const opts: OutputOpts = {};\n if (bool(args, 'raw')) opts.raw = true;\n if (bool(args, 'quiet')) opts.quiet = true;\n if (bool(args, 'retain')) opts.retain = true;\n if (bool(args, 'compact')) opts.compact = true;\n const fields = str(args, 'fields');\n if (fields !== undefined) opts.fields = fields;\n return opts;\n}\n\n/**\n * Which surface a write goes over.\n *\n * A misspelled `--via` is REFUSED rather than ignored. Ignoring it would mean\n * `--via voyger` silently posts over whichever transport happened to be the\n * default — the user asked for a specific surface and would be given another.\n */\nfunction via(args: ParsedArgs): 'oauth' | 'voyager' | 'invalid' | undefined {\n const value = str(args, 'via');\n if (value === undefined) return undefined;\n return value === 'oauth' || value === 'voyager' ? value : 'invalid';\n}\n\n/** `oauth` carries subcommands; bare `oauth` reports status and writes nothing. */\nasync function oauth(args: ParsedArgs): Promise<Envelope> {\n const sub = args.positionals[0] ?? 'status';\n if (sub === 'status') return runOauthStatus();\n if (sub === 'logout') return runOauthLogout();\n if (sub === 'login') {\n const opts: { clientId?: string; clientSecret?: string } = {};\n const id = str(args, 'client-id');\n const secret = str(args, 'client-secret');\n if (id !== undefined) opts.clientId = id;\n if (secret !== undefined) opts.clientSecret = secret;\n return runOauthLogin(opts);\n }\n return err(\n 'oauth',\n 'INVALID_INPUT',\n `unknown oauth subcommand '${sub}'`,\n 'one of: login, status, logout',\n );\n}\n\nexport async function dispatch(argv: string[], now: number): Promise<Envelope> {\n const args = parseArgs(argv);\n const { command } = args;\n\n if (command === undefined || command === 'help' || command === '--help') {\n process.stderr.write(`${helpText()}\\n`);\n return { ok: true, command: 'help', data: { commands: helpText() } };\n }\n\n const def = findCommand(command);\n if (def === undefined) {\n return err(\n command,\n 'UNKNOWN_COMMAND',\n `unknown command '${command}'`,\n 'run `lnrelay help` to list commands',\n );\n }\n\n if (!def.implemented) {\n return err(\n command,\n 'NOT_IMPLEMENTED',\n `'${command}' is specified but not yet built`,\n `Usage when it lands: ${def.usage.split('\\n')[0]}. See docs/PLAN.md for the phase it belongs to.`,\n );\n }\n\n switch (command) {\n case 'doctor':\n return runDoctor(now, bool(args, 'offline'));\n case 'budget':\n return runBudget(now, bool(args, 'reset-cooldown'), bool(args, 'confirm'));\n case 'risk':\n return runRisk(now);\n case 'local':\n return runLocal(\n args.positionals[0],\n str(args, 'source'),\n str(args, 'since'),\n num(args, 'limit') ?? 25,\n output(args),\n );\n case 'purge':\n return runPurge(\n str(args, 'scope') ?? (bool(args, 'all') ? 'all' : undefined),\n bool(args, 'confirm'),\n );\n case 'cache-status':\n return runCacheStatus();\n case 'connections':\n return runSourceRead(\n 'connections',\n args.positionals[0] ?? str(args, 'q'),\n num(args, 'limit') ?? 25,\n output(args),\n );\n case 'my-posts':\n return runSourceRead(\n 'my-posts',\n args.positionals[0] ?? str(args, 'q'),\n num(args, 'limit') ?? 25,\n output(args),\n );\n case 'sync':\n return runSync(args.positionals[0], num(args, 'limit') ?? 50, bool(args, 'force'), now);\n case 'login':\n return runLogin();\n case 'oauth':\n return oauth(args);\n case 'share': {\n const surface = via(args);\n if (surface === 'invalid') {\n return err(\n 'share',\n 'INVALID_INPUT',\n `unknown --via '${str(args, 'via') ?? ''}'`,\n 'one of: oauth, voyager. Omit it to prefer OAuth and fall back to Voyager.',\n );\n }\n return runShare(\n args.positionals[0],\n str(args, 'visibility') ?? 'public',\n now,\n undefined,\n surface,\n );\n }\n case 'comment':\n return runComment(args.positionals[0], args.positionals[1], now);\n case 'edit':\n return runEdit(args.positionals[0], args.positionals[1], now);\n case 'reply':\n return runReply(args.positionals[0], args.positionals[1], now);\n case 'react':\n return runReact(\n args.positionals[0],\n str(args, 'type') ?? 'LIKE',\n now,\n undefined,\n bool(args, 'remove'),\n );\n case 'delete':\n return runDelete(args.positionals[0], now, undefined, bool(args, 'quiet'));\n case 'whoami':\n return runWhoami(bool(args, 'raw'));\n case 'profile':\n return runProfile(args.positionals[0], bool(args, 'raw'));\n case 'feed':\n return runFeed(num(args, 'limit') ?? 10, output(args));\n case 'post':\n return runPost(args.positionals[0], num(args, 'limit') ?? 20, output(args));\n case 'reactions':\n return runReactions(args.positionals[0], num(args, 'limit') ?? 20, output(args));\n case 'search':\n return runSearch(\n args.positionals[0],\n args.positionals[1],\n num(args, 'limit') ?? 10,\n output(args),\n );\n default:\n return err(command, 'NOT_IMPLEMENTED', `'${command}' has no runner wired`);\n }\n}\n\nconst entry = shouldRunAsEntry(process.argv[1], import.meta.url, import.meta.main, [\n 'lnrelay',\n 'linkedin-relay-mcp',\n]);\n\nif (entry.run) {\n if (entry.warning !== undefined) process.stderr.write(`${entry.warning}\\n`);\n // stdout carries ONLY a JSON envelope — including when something throws that\n // no runner anticipated. A stack trace on stdout would break every caller\n // that parses us, which is all of them.\n const envelope = await dispatch(process.argv.slice(2), Date.now()).catch((e: Error) =>\n err(\n process.argv[2] ?? 'unknown',\n 'UNEXPECTED',\n e.message,\n 'This is a bug in lnrelay, not a LinkedIn failure. The stack trace is on stderr.',\n ),\n );\n // stdout carries ONLY the JSON envelope. Help text and progress go to stderr.\n if (envelope.command !== 'help') process.stdout.write(`${toJson(envelope)}\\n`);\n process.exit(exitCodeFor(envelope));\n}\n"],"mappings":";AAQO,SAAS,UAAU,MAA4B;AACpD,QAAM,CAAC,SAAS,GAAG,IAAI,IAAI;AAC3B,QAAM,cAAwB,CAAC;AAC/B,QAAM,QAA0C,CAAC;AAEjD,WAAS,IAAI,GAAG,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MAAM,SAAS,QAAQ,KAAK,MAAM,CAAC,GAAG,KAAK,IAAI,CAAC,EAAE;AAAA,IAAM,CAAC,MACxE;AAAA,MACE,QAAQ,KAAK,CAAC,KAAK;AAAA,MACnB;AAAA,MACA,EAAE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,MAAI,SAAS,YAAY,OAAQ,SAAQ,OAAO,MAAM,GAAG,OAAO,QAAQ,CAAC;AAAA,CAAI;AAC7E,UAAQ,KAAK,YAAY,QAAQ,CAAC;AACpC;","names":["mkdirSync","renameSync","mkdirSync","quarantine","renameSync","ledger","headers","ledger","headers","typeOf","count","postUrn","states","text","entry","states","VOYAGER","text","budgetLine","text","headers","postUrn","existsSync","ledger","existsSync","createInterface","text","existsSync","existsSync","createInterface","text","share","SDUI_ACTION","SCREEN_ID","text","SDUI_ACTION","SCREEN_ID","comment","text","via","text","share","headers","postUrn","REACTIONS"]}
|